]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/users.cpp
There is absolutely no need to cache connect timeout.
[user/henk/code/inspircd.git] / src / users.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2008 InspIRCd Development Team
6  * See: http://www.inspircd.org/wiki/index.php/Credits
7  *
8  * This program is free but copyrighted software; see
9  *            the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 /* $Core */
15
16 #include "inspircd.h"
17 #include <stdarg.h>
18 #include "socketengine.h"
19 #include "xline.h"
20 #include "bancache.h"
21 #include "commands/cmd_whowas.h"
22
23 /* XXX: Used for speeding up WriteCommon operations */
24 unsigned long uniq_id = 1;
25
26 static unsigned long* already_sent = NULL;
27
28
29 void InitializeAlreadySent(SocketEngine* SE)
30 {
31         already_sent = new unsigned long[SE->GetMaxFds()];
32         memset(already_sent, 0, SE->GetMaxFds() * sizeof(unsigned long));
33 }
34
35
36 std::string User::ProcessNoticeMasks(const char *sm)
37 {
38         bool adding = true, oldadding = false;
39         const char *c = sm;
40         std::string output;
41
42         while (c && *c)
43         {
44                 switch (*c)
45                 {
46                         case '+':
47                                 adding = true;
48                         break;
49                         case '-':
50                                 adding = false;
51                         break;
52                         case '*':
53                                 for (unsigned char d = 'A'; d <= 'z'; d++)
54                                 {
55                                         if (ServerInstance->SNO->IsEnabled(d))
56                                         {
57                                                 if ((!IsNoticeMaskSet(d) && adding) || (IsNoticeMaskSet(d) && !adding))
58                                                 {
59                                                         if ((oldadding != adding) || (!output.length()))
60                                                                 output += (adding ? '+' : '-');
61
62                                                         this->SetNoticeMask(d, adding);
63
64                                                         output += d;
65                                                 }
66                                         }
67                                         oldadding = adding;
68                                 }
69                         break;
70                         default:
71                                 if ((*c >= 'A') && (*c <= 'z') && (ServerInstance->SNO->IsEnabled(*c)))
72                                 {
73                                         if ((!IsNoticeMaskSet(*c) && adding) || (IsNoticeMaskSet(*c) && !adding))
74                                         {
75                                                 if ((oldadding != adding) || (!output.length()))
76                                                         output += (adding ? '+' : '-');
77
78                                                 this->SetNoticeMask(*c, adding);
79
80                                                 output += *c;
81                                         }
82                                 }
83                                 else
84                                         this->WriteNumeric(ERR_UNKNOWNSNOMASK, "%s %c :is unknown snomask char to me", this->nick.c_str(), *c);
85
86                                 oldadding = adding;
87                         break;
88                 }
89
90                 *c++;
91         }
92
93         return output;
94 }
95
96 void User::StartDNSLookup()
97 {
98         try
99         {
100                 bool cached = false;
101                 const char* sip = this->GetIPString(false);
102                 UserResolver *res_reverse;
103
104                 /* Special case for 4in6 (Have i mentioned i HATE 4in6?) */
105                 if (!strncmp(sip, "0::ffff:", 8))
106                         res_reverse = new UserResolver(this->ServerInstance, this, sip + 8, DNS_QUERY_PTR4, cached);
107                 else
108                         res_reverse = new UserResolver(this->ServerInstance, this, sip, this->GetProtocolFamily() == AF_INET ? DNS_QUERY_PTR4 : DNS_QUERY_PTR6, cached);
109
110                 this->ServerInstance->AddResolver(res_reverse, cached);
111         }
112         catch (CoreException& e)
113         {
114                 ServerInstance->Logs->Log("USERS", DEBUG,"Error in resolver: %s",e.GetReason());
115         }
116 }
117
118 bool User::IsNoticeMaskSet(unsigned char sm)
119 {
120         if (!isalpha(sm))
121                 return false;
122         return (snomasks[sm-65]);
123 }
124
125 void User::SetNoticeMask(unsigned char sm, bool value)
126 {
127         if (!isalpha(sm))
128                 return;
129         snomasks[sm-65] = value;
130 }
131
132 const char* User::FormatNoticeMasks()
133 {
134         static char data[MAXBUF];
135         int offset = 0;
136
137         for (int n = 0; n < 64; n++)
138         {
139                 if (snomasks[n])
140                         data[offset++] = n+65;
141         }
142
143         data[offset] = 0;
144         return data;
145 }
146
147 bool User::IsModeSet(unsigned char m)
148 {
149         if (!isalpha(m))
150                 return false;
151         return (modes[m-65]);
152 }
153
154 void User::SetMode(unsigned char m, bool value)
155 {
156         if (!isalpha(m))
157                 return;
158         modes[m-65] = value;
159 }
160
161 const char* User::FormatModes(bool showparameters)
162 {
163         static char data[MAXBUF];
164         std::string params;
165         int offset = 0;
166
167         for (unsigned char n = 0; n < 64; n++)
168         {
169                 if (modes[n])
170                 {
171                         data[offset++] = n + 65;
172                         ModeHandler* mh = ServerInstance->Modes->FindMode(n + 65, MODETYPE_USER);
173                         if (showparameters && mh && mh->GetNumParams(true))
174                         {
175                                 std::string p = mh->GetUserParameter(this);
176                                 if (p.length())
177                                         params.append(" ").append(p);
178                         }
179                 }
180         }
181         data[offset] = 0;
182         strlcat(data, params.c_str(), MAXBUF);
183         return data;
184 }
185
186 void User::DecrementModes()
187 {
188         ServerInstance->Logs->Log("USERS", DEBUG, "DecrementModes()");
189         for (unsigned char n = 'A'; n <= 'z'; n++)
190         {
191                 if (modes[n-65])
192                 {
193                         ServerInstance->Logs->Log("USERS", DEBUG,"DecrementModes() found mode %c", n);
194                         ModeHandler* mh = ServerInstance->Modes->FindMode(n, MODETYPE_USER);
195                         if (mh)
196                         {
197                                 ServerInstance->Logs->Log("USERS", DEBUG,"Found handler %c and call ChangeCount", n);
198                                 mh->ChangeCount(-1);
199                         }
200                 }
201         }
202 }
203
204 User::User(InspIRCd* Instance, const std::string &uid) : ServerInstance(Instance)
205 {
206         server = (char*)Instance->FindServerNamePtr(Instance->Config->ServerName);
207         reset_due = ServerInstance->Time();
208         age = ServerInstance->Time();
209         Penalty = 0;
210         lines_in = lastping = signon = idle_lastmsg = nping = registered = 0;
211         bytes_in = bytes_out = cmds_in = cmds_out = 0;
212         quietquit = OverPenalty = ExemptFromPenalty = quitting = exempt = haspassed = dns_done = false;
213         fd = -1;
214         recvq.clear();
215         sendq.clear();
216         Visibility = NULL;
217         ip = NULL;
218         MyClass = NULL;
219         AllowedUserModes = NULL;
220         AllowedChanModes = NULL;
221         AllowedOperCommands = NULL;
222         chans.clear();
223         invites.clear();
224
225         if (uid.empty())
226                 uuid.assign(Instance->GetUID(), 0, UUID_LENGTH - 1);
227         else
228                 uuid.assign(uid, 0, UUID_LENGTH - 1);
229
230         ServerInstance->Logs->Log("USERS", DEBUG,"New UUID for user: %s (%s)", uuid.c_str(), uid.empty() ? "allocated new" : "used remote");
231
232         user_hash::iterator finduuid = Instance->Users->uuidlist->find(uuid);
233         if (finduuid == Instance->Users->uuidlist->end())
234                 (*Instance->Users->uuidlist)[uuid] = this;
235         else
236                 throw CoreException("Duplicate UUID "+std::string(uuid)+" in User constructor");
237 }
238
239 User::~User()
240 {
241         /* NULL for remote users :) */
242         if (this->MyClass)
243         {
244                 this->MyClass->RefCount--;
245                 ServerInstance->Logs->Log("USERS", DEBUG, "User destructor -- connect refcount now: %lu", this->MyClass->RefCount);
246         }
247         if (this->AllowedOperCommands)
248         {
249                 delete AllowedOperCommands;
250                 AllowedOperCommands = NULL;
251         }
252
253         if (this->AllowedUserModes)
254         {
255                 delete[] AllowedUserModes;
256                 AllowedUserModes = NULL;
257         }
258
259         if (this->AllowedChanModes)
260         {
261                 delete[] AllowedChanModes;
262                 AllowedChanModes = NULL;
263         }
264
265         this->InvalidateCache();
266         this->DecrementModes();
267
268         if (ip)
269         {
270                 ServerInstance->Users->RemoveCloneCounts(this);
271
272                 if (this->GetProtocolFamily() == AF_INET)
273                 {
274                         delete (sockaddr_in*)ip;
275                 }
276 #ifdef SUPPORT_IP6LINKS
277                 else
278                 {
279                         delete (sockaddr_in6*)ip;
280                 }
281 #endif
282         }
283
284         ServerInstance->Users->uuidlist->erase(uuid);
285 }
286
287 const std::string& User::MakeHost()
288 {
289         if (!this->cached_makehost.empty())
290                 return this->cached_makehost;
291
292         char nhost[MAXBUF];
293         /* This is much faster than snprintf */
294         char* t = nhost;
295         for(const char* n = ident.c_str(); *n; n++)
296                 *t++ = *n;
297         *t++ = '@';
298         for(const char* n = host.c_str(); *n; n++)
299                 *t++ = *n;
300         *t = 0;
301
302         this->cached_makehost.assign(nhost);
303
304         return this->cached_makehost;
305 }
306
307 const std::string& User::MakeHostIP()
308 {
309         if (!this->cached_hostip.empty())
310                 return this->cached_hostip;
311
312         char ihost[MAXBUF];
313         /* This is much faster than snprintf */
314         char* t = ihost;
315         for(const char* n = ident.c_str(); *n; n++)
316                 *t++ = *n;
317         *t++ = '@';
318         for(const char* n = this->GetIPString(); *n; n++)
319                 *t++ = *n;
320         *t = 0;
321
322         this->cached_hostip = ihost;
323
324         return this->cached_hostip;
325 }
326
327 void User::CloseSocket()
328 {
329         if (this->fd > -1)
330         {
331                 ServerInstance->SE->Shutdown(this, 2);
332                 ServerInstance->SE->Close(this);
333         }
334 }
335
336 const std::string& User::GetFullHost()
337 {
338         if (!this->cached_fullhost.empty())
339                 return this->cached_fullhost;
340
341         char result[MAXBUF];
342         char* t = result;
343         for(const char* n = nick.c_str(); *n; n++)
344                 *t++ = *n;
345         *t++ = '!';
346         for(const char* n = ident.c_str(); *n; n++)
347                 *t++ = *n;
348         *t++ = '@';
349         for(const char* n = dhost.c_str(); *n; n++)
350                 *t++ = *n;
351         *t = 0;
352
353         this->cached_fullhost = result;
354
355         return this->cached_fullhost;
356 }
357
358 char* User::MakeWildHost()
359 {
360         static char nresult[MAXBUF];
361         char* t = nresult;
362         *t++ = '*';     *t++ = '!';
363         *t++ = '*';     *t++ = '@';
364         for(const char* n = dhost.c_str(); *n; n++)
365                 *t++ = *n;
366         *t = 0;
367         return nresult;
368 }
369
370 int User::ReadData(void* buffer, size_t size)
371 {
372         if (IS_LOCAL(this))
373         {
374 #ifndef WIN32
375                 return read(this->fd, buffer, size);
376 #else
377                 return recv(this->fd, (char*)buffer, size, 0);
378 #endif
379         }
380         else
381                 return 0;
382 }
383
384
385 const std::string& User::GetFullRealHost()
386 {
387         if (!this->cached_fullrealhost.empty())
388                 return this->cached_fullrealhost;
389
390         char fresult[MAXBUF];
391         char* t = fresult;
392         for(const char* n = nick.c_str(); *n; n++)
393                 *t++ = *n;
394         *t++ = '!';
395         for(const char* n = ident.c_str(); *n; n++)
396                 *t++ = *n;
397         *t++ = '@';
398         for(const char* n = host.c_str(); *n; n++)
399                 *t++ = *n;
400         *t = 0;
401
402         this->cached_fullrealhost = fresult;
403
404         return this->cached_fullrealhost;
405 }
406
407 bool User::IsInvited(const irc::string &channel)
408 {
409         time_t now = time(NULL);
410         InvitedList::iterator safei;
411         for (InvitedList::iterator i = invites.begin(); i != invites.end(); ++i)
412         {
413                 if (channel == i->first)
414                 {
415                         if (i->second != 0 && now > i->second)
416                         {
417                                 /* Expired invite, remove it. */
418                                 safei = i;
419                                 --i;
420                                 invites.erase(safei);
421                                 continue;
422                         }
423                         return true;
424                 }
425         }
426         return false;
427 }
428
429 InvitedList* User::GetInviteList()
430 {
431         time_t now = time(NULL);
432         /* Weed out expired invites here. */
433         InvitedList::iterator safei;
434         for (InvitedList::iterator i = invites.begin(); i != invites.end(); ++i)
435         {
436                 if (i->second != 0 && now > i->second)
437                 {
438                         /* Expired invite, remove it. */
439                         safei = i;
440                         --i;
441                         invites.erase(safei);
442                 }
443         }
444         return &invites;
445 }
446
447 void User::InviteTo(const irc::string &channel, time_t invtimeout)
448 {
449         time_t now = time(NULL);
450         if (invtimeout != 0 && now > invtimeout) return; /* Don't add invites that are expired from the get-go. */
451         for (InvitedList::iterator i = invites.begin(); i != invites.end(); ++i)
452         {
453                 if (channel == i->first)
454                 {
455                         if (i->second != 0 && invtimeout > i->second)
456                         {
457                                 i->second = invtimeout;
458                         }
459
460                         return;
461                 }
462         }
463         invites.push_back(std::make_pair(channel, invtimeout));
464 }
465
466 void User::RemoveInvite(const irc::string &channel)
467 {
468         for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
469         {
470                 if (channel == i->first)
471                 {
472                         invites.erase(i);
473                         return;
474                 }
475         }
476 }
477
478 bool User::HasModePermission(unsigned char mode, ModeType type)
479 {
480         if (!IS_LOCAL(this))
481                 return true;
482
483         if (!IS_OPER(this))
484                 return false;
485
486         if (!AllowedUserModes || !AllowedChanModes)
487                 return false;
488
489         return ((type == MODETYPE_USER ? AllowedUserModes : AllowedChanModes))[(mode - 'A')];
490         
491 }
492
493 bool User::HasPermission(const std::string &command)
494 {
495         /*
496          * users on remote servers can completely bypass all permissions based checks.
497          * This prevents desyncs when one server has different type/class tags to another.
498          * That having been said, this does open things up to the possibility of source changes
499          * allowing remote kills, etc - but if they have access to the src, they most likely have
500          * access to the conf - so it's an end to a means either way.
501          */
502         if (!IS_LOCAL(this))
503                 return true;
504
505         // are they even an oper at all?
506         if (!IS_OPER(this))
507         {
508                 return false;
509         }
510
511         if (!AllowedOperCommands)
512                 return false;
513
514         if (AllowedOperCommands->find(command) != AllowedOperCommands->end())
515                 return true;
516         else if (AllowedOperCommands->find("*") != AllowedOperCommands->end())
517                 return true;
518
519         return false;
520 }
521
522 bool User::AddBuffer(const std::string &a)
523 {
524         std::string::size_type start = 0;
525         std::string::size_type i = a.find('\r');
526
527         /*
528          * The old implementation here took a copy, and rfind() on \r, removing as it found them, before
529          * copying a second time onto the recvq. That's ok, but involves three copies minimum (recv() to buffer,
530          * buffer to here, here to recvq) - The new method now copies twice (recv() to buffer, buffer to recvq).
531          *
532          * We use find() instead of rfind() for clarity, however unlike the old code, our scanning of the string is
533          * contiguous: as we specify a startpoint, we never see characters we have scanned previously, making this
534          * marginally faster in cases with a number of \r hidden early on in the buffer.
535          *
536          * How it works:
537          * Start at first pos of string, find first \r, append everything in the chunk (excluding \r) to recvq. Set
538          * i ahead of the \r, search for next \r, add next chunk to buffer... repeat.
539          *              -- w00t (7 may, 2008)
540          */
541         if (i == std::string::npos)
542         {
543                 // no \r that we need to dance around, just add to buffer
544                 recvq.append(a);
545         }
546         else
547         {
548                 // While we can find the end of a chunk to add
549                 while (i != std::string::npos)
550                 {
551                         // Append the chunk that we have
552                         recvq.append(a, start, (i - start));
553
554                         // Start looking for the next one
555                         start = i + 1;
556                         i = a.find('\r', start);
557                 }
558
559                 if (start != a.length())
560                 {
561                         /*
562                          * This is here to catch a corner case when we get something like:
563                          * NICK w0
564                          * 0t\r\nU
565                          * SER ...
566                          * in successive calls to us.
567                          *
568                          * Without this conditional, the 'U' on the second case will be dropped,
569                          * which is most *certainly* not the behaviour we want!
570                          *              -- w00t
571                          */
572                         recvq.append(a, start, (a.length() - start));
573                 }
574         }
575
576         if (this->MyClass && (recvq.length() > this->MyClass->GetRecvqMax()))
577         {
578                 ServerInstance->Users->QuitUser(this, "RecvQ exceeded");
579                 ServerInstance->SNO->WriteToSnoMask('A', "User %s RecvQ of %lu exceeds connect class maximum of %lu",this->nick.c_str(),(unsigned long int)recvq.length(),this->MyClass->GetRecvqMax());
580                 return false;
581         }
582
583         return true;
584 }
585
586 bool User::BufferIsReady()
587 {
588         return (recvq.find('\n') != std::string::npos);
589 }
590
591 void User::ClearBuffer()
592 {
593         recvq.clear();
594 }
595
596 std::string User::GetBuffer()
597 {
598         try
599         {
600                 if (recvq.empty())
601                         return "";
602
603                 /* Strip any leading \r or \n off the string.
604                  * Usually there are only one or two of these,
605                  * so its is computationally cheap to do.
606                  */
607                 std::string::iterator t = recvq.begin();
608                 while (t != recvq.end() && (*t == '\r' || *t == '\n'))
609                 {
610                         recvq.erase(t);
611                         t = recvq.begin();
612                 }
613
614                 for (std::string::iterator x = recvq.begin(); x != recvq.end(); x++)
615                 {
616                         /* Find the first complete line, return it as the
617                          * result, and leave the recvq as whats left
618                          */
619                         if (*x == '\n')
620                         {
621                                 std::string ret = std::string(recvq.begin(), x);
622                                 recvq.erase(recvq.begin(), x + 1);
623                                 return ret;
624                         }
625                 }
626                 return "";
627         }
628
629         catch (...)
630         {
631                 ServerInstance->Logs->Log("USERS", DEBUG,"Exception in User::GetBuffer()");
632                 return "";
633         }
634 }
635
636 void User::AddWriteBuf(const std::string &data)
637 {
638         if (this->quitting)
639                 return;
640
641         if (this->MyClass && (sendq.length() + data.length() > this->MyClass->GetSendqMax()))
642         {
643                 /*
644                  * Fix by brain - Set the error text BEFORE calling, because
645                  * if we dont it'll recursively  call here over and over again trying
646                  * to repeatedly add the text to the sendq!
647                  */
648                 ServerInstance->Users->QuitUser(this, "SendQ exceeded");
649                 ServerInstance->SNO->WriteToSnoMask('A', "User %s SendQ of %lu exceeds connect class maximum of %lu",this->nick.c_str(),(unsigned long int)sendq.length() + data.length(),this->MyClass->GetSendqMax());
650                 return;
651         }
652
653         if (data.length() > MAXBUF - 2) /* MAXBUF has a value of 514, to account for line terminators */
654                 sendq.append(data.substr(0,MAXBUF - 4)).append("\r\n"); /* MAXBUF-4 = 510 */
655         else
656                 sendq.append(data);
657 }
658
659 // send AS MUCH OF THE USERS SENDQ as we are able to (might not be all of it)
660 void User::FlushWriteBuf()
661 {
662         if (this->fd == FD_MAGIC_NUMBER)
663         {
664                 sendq.clear();
665                 return;
666         }
667
668         if ((sendq.length()) && (this->fd != FD_MAGIC_NUMBER))
669         {
670                 int old_sendq_length = sendq.length();
671                 int n_sent = ServerInstance->SE->Send(this, this->sendq.data(), this->sendq.length(), 0);
672
673                 if (n_sent == -1)
674                 {
675                         if (errno == EAGAIN)
676                         {
677                                 /* The socket buffer is full. This isnt fatal,
678                                  * try again later.
679                                  */
680                                 ServerInstance->SE->WantWrite(this);
681                         }
682                         else
683                         {
684                                 /* Fatal error, set write error and bail */
685                                 ServerInstance->Users->QuitUser(this, errno ? strerror(errno) : "Write error");
686                                 return;
687                         }
688                 }
689                 else
690                 {
691                         /* advance the queue */
692                         if (n_sent)
693                                 this->sendq = this->sendq.substr(n_sent);
694                         /* update the user's stats counters */
695                         this->bytes_out += n_sent;
696                         this->cmds_out++;
697                         if (n_sent != old_sendq_length)
698                                 this->ServerInstance->SE->WantWrite(this);
699                 }
700         }
701
702         /* note: NOT else if! */
703         if (this->sendq.empty())
704         {
705                 FOREACH_MOD(I_OnBufferFlushed,OnBufferFlushed(this));
706         }
707 }
708
709 void User::Oper(const std::string &opertype, const std::string &opername)
710 {
711         char* mycmd;
712         char* savept;
713         char* savept2;
714
715         if (this->IsModeSet('o'))
716                 this->UnOper();
717
718         this->modes[UM_OPERATOR] = 1;
719         this->WriteServ("MODE %s :+o", this->nick.c_str());
720         FOREACH_MOD(I_OnOper, OnOper(this, opertype));
721
722         ServerInstance->SNO->WriteToSnoMask('o',"%s (%s@%s) is now an IRC operator of type %s (using oper '%s')", this->nick.c_str(), this->ident.c_str(), this->host.c_str(), irc::Spacify(opertype.c_str()), opername.c_str());
723         this->WriteNumeric(381, "%s :You are now %s %s", this->nick.c_str(), strchr("aeiouAEIOU", *opertype.c_str()) ? "an" : "a", irc::Spacify(opertype.c_str()));
724
725         ServerInstance->Logs->Log("OPER", DEFAULT, "%s!%s@%s opered as type: %s", this->nick.c_str(), this->ident.c_str(), this->host.c_str(), opertype.c_str());
726         this->oper.assign(opertype, 0, 512);
727         ServerInstance->Users->all_opers.push_back(this);
728
729         opertype_t::iterator iter_opertype = ServerInstance->Config->opertypes.find(this->oper.c_str());
730         if (iter_opertype != ServerInstance->Config->opertypes.end())
731         {
732
733                 if (AllowedOperCommands)
734                         AllowedOperCommands->clear();
735                 else
736                         AllowedOperCommands = new std::map<std::string, bool>;
737
738                 if (!AllowedChanModes)
739                         AllowedChanModes = new bool[64];
740
741                 if (!AllowedUserModes)
742                         AllowedUserModes = new bool[64];
743
744                 memset(AllowedUserModes, 0, 64);
745                 memset(AllowedChanModes, 0, 64);
746
747                 char* Classes = strdup(iter_opertype->second);
748                 char* myclass = strtok_r(Classes," ",&savept);
749                 while (myclass)
750                 {
751                         operclass_t::iterator iter_operclass = ServerInstance->Config->operclass.find(myclass);
752                         if (iter_operclass != ServerInstance->Config->operclass.end())
753                         {
754                                 char* CommandList = strdup(iter_operclass->second.commandlist);
755                                 mycmd = strtok_r(CommandList," ",&savept2);
756                                 while (mycmd)
757                                 {
758                                         this->AllowedOperCommands->insert(std::make_pair(mycmd, true));
759                                         mycmd = strtok_r(NULL," ",&savept2);
760                                 }
761                                 free(CommandList);
762                                 this->AllowedUserModes['o' - 'A'] = true; // Call me paranoid if you want.
763                                 for (unsigned char* c = (unsigned char*)iter_operclass->second.umodelist; *c; ++c)
764                                 {
765                                         if (*c == '*')
766                                         {
767                                                 memset(this->AllowedUserModes, (int)(true), 64);
768                                         }
769                                         else
770                                         {
771                                                 this->AllowedUserModes[*c - 'A'] = true;
772                                         }
773                                 }
774                                 for (unsigned char* c = (unsigned char*)iter_operclass->second.cmodelist; *c; ++c)
775                                 {
776                                         if (*c == '*')
777                                         {
778                                                 memset(this->AllowedChanModes, (int)(true), 64);
779                                         }
780                                         else
781                                         {
782                                                 this->AllowedChanModes[*c - 'A'] = true;
783                                         }
784                                 }
785                         }
786                         myclass = strtok_r(NULL," ",&savept);
787                 }
788                 free(Classes);
789         }
790
791         FOREACH_MOD(I_OnPostOper,OnPostOper(this, opertype, opername));
792 }
793
794 void User::UnOper()
795 {
796         if (IS_OPER(this))
797         {
798                 /*
799                  * unset their oper type (what IS_OPER checks).
800                  * note, order is important - this must come before modes as -o attempts
801                  * to call UnOper. -- w00t
802                  */
803                 this->oper.clear();
804
805                 /* Remove all oper only modes from the user when the deoper - Bug #466*/
806                 std::string moderemove("-");
807
808                 for (unsigned char letter = 'A'; letter <= 'z'; letter++)
809                 {
810                         ModeHandler* mh = ServerInstance->Modes->FindMode(letter, MODETYPE_USER);
811                         if (mh && mh->NeedsOper())
812                                 moderemove += letter;
813                 }
814
815                 std::vector<std::string> parameters;
816                 parameters.push_back(this->nick);
817                 parameters.push_back(moderemove);
818
819                 ServerInstance->Parser->CallHandler("MODE", parameters, this);
820                         
821                 /* remove the user from the oper list. Will remove multiple entries as a safeguard against bug #404 */
822                 ServerInstance->Users->all_opers.remove(this);
823
824                 if (AllowedOperCommands)
825                 {
826                         delete AllowedOperCommands;
827                         AllowedOperCommands = NULL;
828                 }
829                 if (AllowedUserModes)
830                 {
831                         delete[] AllowedUserModes;
832                         AllowedUserModes = NULL;
833                 }
834                 if (AllowedChanModes)
835                 {
836                         delete[] AllowedChanModes;
837                         AllowedChanModes = NULL;
838                 }
839
840         }
841 }
842
843 /* adds or updates an entry in the whowas list */
844 void User::AddToWhoWas()
845 {
846         Command* whowas_command = ServerInstance->Parser->GetHandler("WHOWAS");
847         if (whowas_command)
848         {
849                 std::deque<classbase*> params;
850                 params.push_back(this);
851                 whowas_command->HandleInternal(WHOWAS_ADD, params);
852         }
853 }
854
855 /*
856  * Check class restrictions
857  */
858 void User::CheckClass()
859 {
860         ConnectClass* a = this->MyClass;
861
862         if ((!a) || (a->GetType() == CC_DENY))
863         {
864                 ServerInstance->Users->QuitUser(this, "Unauthorised connection");
865                 return;
866         }
867         else if ((a->GetMaxLocal()) && (ServerInstance->Users->LocalCloneCount(this) > a->GetMaxLocal()))
868         {
869                 ServerInstance->Users->QuitUser(this, "No more connections allowed from your host via this connect class (local)");
870                 ServerInstance->SNO->WriteToSnoMask('A', "WARNING: maximum LOCAL connections (%ld) exceeded for IP %s", a->GetMaxLocal(), this->GetIPString());
871                 return;
872         }
873         else if ((a->GetMaxGlobal()) && (ServerInstance->Users->GlobalCloneCount(this) > a->GetMaxGlobal()))
874         {
875                 ServerInstance->Users->QuitUser(this, "No more connections allowed from your host via this connect class (global)");
876                 ServerInstance->SNO->WriteToSnoMask('A', "WARNING: maximum GLOBAL connections (%ld) exceeded for IP %s", a->GetMaxGlobal(), this->GetIPString());
877                 return;
878         }
879
880         this->nping = ServerInstance->Time() + a->GetPingTime() + ServerInstance->Config->dns_timeout;
881 }
882
883 bool User::CheckLines()
884 {
885         const char* check[] = { "G" , "K", NULL };
886
887         if (!this->exempt)
888         {
889                 for (int n = 0; check[n]; ++n)
890                 {
891                         XLine *r = ServerInstance->XLines->MatchesLine(check[n], this);
892
893                         if (r)
894                         {
895                                 r->Apply(this);
896                                 return true;
897                         }
898                 }
899         }
900
901         return false;
902 }
903
904 void User::FullConnect()
905 {
906         ServerInstance->stats->statsConnects++;
907         this->idle_lastmsg = ServerInstance->Time();
908
909         /*
910          * You may be thinking "wtf, we checked this in User::AddClient!" - and yes, we did, BUT.
911          * At the time AddClient is called, we don't have a resolved host, by here we probably do - which
912          * may put the user into a totally seperate class with different restrictions! so we *must* check again.
913          * Don't remove this! -- w00t
914          */
915         this->SetClass();
916         
917         /* Check the password, if one is required by the user's connect class.
918          * This CANNOT be in CheckClass(), because that is called prior to PASS as well!
919          */
920         if (this->MyClass && !this->MyClass->GetPass().empty() && !this->haspassed)
921         {
922                 ServerInstance->Users->QuitUser(this, "Invalid password");
923                 return;
924         }
925
926         if (this->CheckLines())
927                 return;
928
929         this->WriteServ("NOTICE Auth :Welcome to \002%s\002!",ServerInstance->Config->Network);
930         this->WriteNumeric(RPL_WELCOME, "%s :Welcome to the %s IRC Network %s!%s@%s",this->nick.c_str(), ServerInstance->Config->Network, this->nick.c_str(), this->ident.c_str(), this->host.c_str());
931         this->WriteNumeric(RPL_YOURHOSTIS, "%s :Your host is %s, running version InspIRCd-1.2",this->nick.c_str(),ServerInstance->Config->ServerName);
932         this->WriteNumeric(RPL_SERVERCREATED, "%s :This server was created %s %s", this->nick.c_str(), __TIME__, __DATE__);
933         this->WriteNumeric(RPL_SERVERVERSION, "%s %s InspIRCd-1.2 %s %s %s", this->nick.c_str(), ServerInstance->Config->ServerName, ServerInstance->Modes->UserModeList().c_str(), ServerInstance->Modes->ChannelModeList().c_str(), ServerInstance->Modes->ParaModeList().c_str());
934
935         ServerInstance->Config->Send005(this);
936         this->WriteNumeric(RPL_YOURUUID, "%s %s :your unique ID", this->nick.c_str(), this->uuid.c_str());
937
938
939         this->ShowMOTD();
940
941         /* Now registered */
942         if (ServerInstance->Users->unregistered_count)
943                 ServerInstance->Users->unregistered_count--;
944
945         /* Trigger LUSERS output, give modules a chance too */
946         int MOD_RESULT = 0;
947         std::string command("LUSERS");
948         std::vector<std::string> parameters;
949         FOREACH_RESULT(I_OnPreCommand, OnPreCommand(command, parameters, this, true, "LUSERS"));
950         if (!MOD_RESULT)
951                 ServerInstance->CallCommandHandler(command, parameters, this);
952
953         /*
954          * We don't set REG_ALL until triggering OnUserConnect, so some module events don't spew out stuff
955          * for a user that doesn't exist yet.
956          */
957         FOREACH_MOD(I_OnUserConnect,OnUserConnect(this));
958
959         this->registered = REG_ALL;
960
961         ServerInstance->PI->Introduce(this);
962
963         FOREACH_MOD(I_OnPostConnect,OnPostConnect(this));
964
965         ServerInstance->SNO->WriteToSnoMask('c',"Client connecting on port %d: %s!%s@%s [%s] [%s]", this->GetPort(), this->nick.c_str(), this->ident.c_str(), this->host.c_str(), this->GetIPString(), this->fullname.c_str());
966         ServerInstance->Logs->Log("BANCACHE", DEBUG, "BanCache: Adding NEGATIVE hit for %s", this->GetIPString());
967         ServerInstance->BanCache->AddHit(this->GetIPString(), "", "");
968 }
969
970 /** User::UpdateNick()
971  * re-allocates a nick in the user_hash after they change nicknames,
972  * returns a pointer to the new user as it may have moved
973  */
974 User* User::UpdateNickHash(const char* New)
975 {
976         //user_hash::iterator newnick;
977         user_hash::iterator oldnick = ServerInstance->Users->clientlist->find(this->nick);
978
979         if (!irc::string(this->nick.c_str()).compare(New))
980                 return oldnick->second;
981
982         if (oldnick == ServerInstance->Users->clientlist->end())
983                 return NULL; /* doesnt exist */
984
985         User* olduser = oldnick->second;
986         (*(ServerInstance->Users->clientlist))[New] = olduser;
987         ServerInstance->Users->clientlist->erase(oldnick);
988         return olduser;
989 }
990
991 void User::InvalidateCache()
992 {
993         /* Invalidate cache */
994         cached_fullhost.clear();
995         cached_hostip.clear();
996         cached_makehost.clear();
997         cached_fullrealhost.clear();
998 }
999
1000 bool User::ForceNickChange(const char* newnick)
1001 {
1002         int MOD_RESULT = 0;
1003
1004         this->InvalidateCache();
1005
1006         FOREACH_RESULT(I_OnUserPreNick,OnUserPreNick(this, newnick));
1007
1008         if (MOD_RESULT)
1009         {
1010                 ServerInstance->stats->statsCollisions++;
1011                 return false;
1012         }
1013
1014         std::deque<classbase*> dummy;
1015         Command* nickhandler = ServerInstance->Parser->GetHandler("NICK");
1016         if (nickhandler) // wtfbbq, when would this not be here
1017         {
1018                 std::vector<std::string> parameters;
1019                 nickhandler->HandleInternal(1, dummy);
1020                 parameters.push_back(newnick);
1021                 bool result = (ServerInstance->Parser->CallHandler("NICK", parameters, this) == CMD_SUCCESS);
1022                 nickhandler->HandleInternal(0, dummy);
1023                 return result;
1024         }
1025
1026         // Unreachable, we hope
1027         return false;
1028 }
1029
1030 void User::SetSockAddr(int protocol_family, const char* sip, int port)
1031 {
1032         this->cachedip = "";
1033
1034         switch (protocol_family)
1035         {
1036 #ifdef SUPPORT_IP6LINKS
1037                 case AF_INET6:
1038                 {
1039                         sockaddr_in6* sin = new sockaddr_in6;
1040                         sin->sin6_family = AF_INET6;
1041                         sin->sin6_port = port;
1042                         inet_pton(AF_INET6, sip, &sin->sin6_addr);
1043                         this->ip = (sockaddr*)sin;
1044                 }
1045                 break;
1046 #endif
1047                 case AF_INET:
1048                 {
1049                         sockaddr_in* sin = new sockaddr_in;
1050                         sin->sin_family = AF_INET;
1051                         sin->sin_port = port;
1052                         inet_pton(AF_INET, sip, &sin->sin_addr);
1053                         this->ip = (sockaddr*)sin;
1054                 }
1055                 break;
1056                 default:
1057                         ServerInstance->Logs->Log("USERS",DEBUG,"Uh oh, I dont know protocol %d to be set on '%s'!", protocol_family, this->nick.c_str());
1058                 break;
1059         }
1060 }
1061
1062 int User::GetPort()
1063 {
1064         if (this->ip == NULL)
1065                 return 0;
1066
1067         switch (this->GetProtocolFamily())
1068         {
1069 #ifdef SUPPORT_IP6LINKS
1070                 case AF_INET6:
1071                 {
1072                         sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1073                         return sin->sin6_port;
1074                 }
1075                 break;
1076 #endif
1077                 case AF_INET:
1078                 {
1079                         sockaddr_in* sin = (sockaddr_in*)this->ip;
1080                         return sin->sin_port;
1081                 }
1082                 break;
1083                 default:
1084                 break;
1085         }
1086         return 0;
1087 }
1088
1089 int User::GetProtocolFamily()
1090 {
1091         if (this->ip == NULL)
1092                 return 0;
1093
1094         sockaddr_in* sin = (sockaddr_in*)this->ip;
1095         return sin->sin_family;
1096 }
1097
1098 const char* User::GetCIDRMask(int range)
1099 {
1100         static char buf[44];
1101
1102         if (this->ip == NULL)
1103                 return "";
1104
1105         if (range < 0)
1106                 throw "Negative range, sorry, no.";
1107
1108         /*
1109          * Original code written by Oliver Lupton (Om).
1110          * Integrated by me. Thanks. :) -- w00t
1111          */
1112         switch (this->GetProtocolFamily())
1113         {
1114 #ifdef SUPPORT_IP6LINKS
1115                 case AF_INET6:
1116                 {
1117                         /* unsigned char s6_addr[16]; */
1118                         struct in6_addr v6;
1119                         sockaddr_in6* sin;
1120                         int i, bytestozero, extrabits;
1121                         char buffer[40];
1122                         
1123                         if(range > 128)
1124                                 throw "CIDR mask width greater than address width (IPv6, 128 bit)";
1125
1126                         /* Access the user's IP structure directly */
1127                         sin = (sockaddr_in6*)this->ip;
1128
1129                         /* To create the CIDR mask we want to set all the bits after 'range' bits of the address
1130                          * to zero. This means the last (128 - range) bits of the address must be set to zero.
1131                          * Hence this number divided by 8 is the number of whole bytes from the end of the address
1132                          * which must be set to zero.
1133                          */
1134                         bytestozero = (128 - range) / 8;
1135                         
1136                         /* Some of the least significant bits of the next most significant byte may also have to
1137                          * be zeroed. The number of bits is the remainder of the above division.
1138                          */
1139                         extrabits = (128 - range) % 8;
1140                         
1141                         /* Populate our working struct with the parts of the user's IP which are required in the
1142                          * final CIDR mask. Set all the subsequent bytes to zero.
1143                          * (16 - bytestozero) is the number of bytes which must be populated with actual IP data.
1144                          */
1145                         for(i = 0; i < (16 - bytestozero); i++)
1146                         {
1147                                 v6.s6_addr[i] = sin->sin6_addr.s6_addr[i];
1148                         }
1149                         
1150                         /* And zero all the remaining bytes in the IP. */
1151                         for(; i < 16; i++)
1152                         {
1153                                 v6.s6_addr[i] = 0;
1154                         }
1155                                         
1156                         /* And finally, zero the extra bits required. */
1157                         v6.s6_addr[15 - bytestozero] = (v6.s6_addr[15 - bytestozero] >> extrabits) << extrabits;
1158
1159                         snprintf(buf, 44, "%s/%d", inet_ntop(AF_INET6, &v6, buffer, 40), range);
1160                         return buf;
1161                 }
1162                 break;
1163 #endif
1164                 case AF_INET:
1165                 {
1166                         struct in_addr v4;
1167                         sockaddr_in* sin;
1168                         char buffer[16];
1169
1170                         if (range > 32)
1171                                 throw "CIDR mask width greater than address width (IPv4, 32 bit)";
1172
1173                         /* Users already have a sockaddr* pointer (User::ip) which contains either a v4 or v6 structure */
1174                         sin = (sockaddr_in*)this->ip;
1175                         v4.s_addr = sin->sin_addr.s_addr;
1176
1177                         /* To create the CIDR mask we want to set all the bits after 'range' bits of the address
1178                          * to zero. This means the last (32 - range) bits of the address must be set to zero.
1179                          * This is done by shifting the value right and then back left by (32 - range) bits.
1180                          */
1181                         if(range > 0)
1182                         {
1183                                 v4.s_addr = ntohl(v4.s_addr);
1184                                 v4.s_addr = (v4.s_addr >> (32 - range)) << (32 - range);
1185                                 v4.s_addr = htonl(v4.s_addr);
1186                         }
1187                         else
1188                         {
1189                                 /* a range of zero would cause a 32 bit value to be shifted by 32 bits.
1190                                  * this has undefined behaviour, but for CIDR purposes the resulting mask
1191                                  * from a.b.c.d/0 is 0.0.0.0/0
1192                                  */
1193                                 v4.s_addr = 0;
1194                         }
1195
1196                         snprintf(buf, 44, "%s/%d", inet_ntop(AF_INET, &v4, buffer, 16), range);
1197                         return buf;
1198                 }
1199                 break;
1200         }
1201
1202         return ""; // unused, but oh well
1203 }
1204
1205 const char* User::GetIPString(bool translate4in6)
1206 {
1207         static char buf[40];
1208
1209         if (this->ip == NULL)
1210                 return "";
1211
1212         if (!this->cachedip.empty())
1213                 return this->cachedip.c_str();
1214
1215         switch (this->GetProtocolFamily())
1216         {
1217 #ifdef SUPPORT_IP6LINKS
1218                 case AF_INET6:
1219                 {
1220                         static char temp[1024];
1221
1222                         sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1223                         inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(buf));
1224                         /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1225                         if (*buf == ':')
1226                         {
1227                                 strlcpy(&temp[1], buf, sizeof(temp) - 1);
1228                                 *temp = '0';
1229                                 if (translate4in6 && !strncmp(temp, "0::ffff:", 8))
1230                                 {
1231                                         this->cachedip = temp + 8;
1232                                         return temp + 8;
1233                                 }
1234
1235                                 this->cachedip = temp;
1236                                 return temp;
1237                         }
1238                         
1239                         this->cachedip = buf;
1240                         return buf;
1241                 }
1242                 break;
1243 #endif
1244                 case AF_INET:
1245                 {
1246                         sockaddr_in* sin = (sockaddr_in*)this->ip;
1247                         inet_ntop(sin->sin_family, &sin->sin_addr, buf, sizeof(buf));
1248                         this->cachedip = buf;
1249                         return buf;
1250                 }
1251                 break;
1252                 default:
1253                 break;
1254         }
1255         
1256         // Unreachable, probably
1257         return "";
1258 }
1259
1260 /** NOTE: We cannot pass a const reference to this method.
1261  * The string is changed by the workings of the method,
1262  * so that if we pass const ref, we end up copying it to
1263  * something we can change anyway. Makes sense to just let
1264  * the compiler do that copy for us.
1265  */
1266 void User::Write(std::string text)
1267 {
1268         if (!ServerInstance->SE->BoundsCheckFd(this))
1269                 return;
1270
1271         try
1272         {
1273                 ServerInstance->Logs->Log("USEROUTPUT", DEBUG,"C[%d] O %s", this->GetFd(), text.c_str());
1274                 text.append("\r\n");
1275         }
1276         catch (...)
1277         {
1278                 ServerInstance->Logs->Log("USEROUTPUT", DEBUG,"Exception in User::Write() std::string::append");
1279                 return;
1280         }
1281
1282         if (this->GetIOHook())
1283         {
1284                 /* XXX: The lack of buffering here is NOT a bug, modules implementing this interface have to
1285                  * implement their own buffering mechanisms
1286                  */
1287                 try
1288                 {
1289                         this->GetIOHook()->OnRawSocketWrite(this->fd, text.data(), text.length());
1290                 }
1291                 catch (CoreException& modexcept)
1292                 {
1293                         ServerInstance->Logs->Log("USEROUTPUT", DEBUG, "%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
1294                 }
1295         }
1296         else
1297         {
1298                 this->AddWriteBuf(text);
1299         }
1300         ServerInstance->stats->statsSent += text.length();
1301         this->ServerInstance->SE->WantWrite(this);
1302 }
1303
1304 /** Write()
1305  */
1306 void User::Write(const char *text, ...)
1307 {
1308         va_list argsPtr;
1309         char textbuffer[MAXBUF];
1310
1311         va_start(argsPtr, text);
1312         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1313         va_end(argsPtr);
1314
1315         this->Write(std::string(textbuffer));
1316 }
1317
1318 void User::WriteServ(const std::string& text)
1319 {
1320         char textbuffer[MAXBUF];
1321
1322         snprintf(textbuffer,MAXBUF,":%s %s",ServerInstance->Config->ServerName,text.c_str());
1323         this->Write(std::string(textbuffer));
1324 }
1325
1326 /** WriteServ()
1327  *  Same as Write(), except `text' is prefixed with `:server.name '.
1328  */
1329 void User::WriteServ(const char* text, ...)
1330 {
1331         va_list argsPtr;
1332         char textbuffer[MAXBUF];
1333
1334         va_start(argsPtr, text);
1335         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1336         va_end(argsPtr);
1337
1338         this->WriteServ(std::string(textbuffer));
1339 }
1340
1341
1342 void User::WriteNumeric(unsigned int numeric, const char* text, ...)
1343 {
1344         va_list argsPtr;
1345         char textbuffer[MAXBUF];
1346
1347         va_start(argsPtr, text);
1348         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1349         va_end(argsPtr);
1350
1351         this->WriteNumeric(numeric, std::string(textbuffer));
1352 }
1353
1354 void User::WriteNumeric(unsigned int numeric, const std::string &text)
1355 {
1356         char textbuffer[MAXBUF];
1357         int MOD_RESULT = 0;
1358
1359         FOREACH_RESULT(I_OnNumeric, OnNumeric(this, numeric, text));
1360
1361         if (MOD_RESULT)
1362                 return;
1363
1364         snprintf(textbuffer,MAXBUF,":%s %03u %s",ServerInstance->Config->ServerName, numeric, text.c_str());
1365         this->Write(std::string(textbuffer));
1366 }
1367
1368 void User::WriteFrom(User *user, const std::string &text)
1369 {
1370         char tb[MAXBUF];
1371
1372         snprintf(tb,MAXBUF,":%s %s",user->GetFullHost().c_str(),text.c_str());
1373
1374         this->Write(std::string(tb));
1375 }
1376
1377
1378 /* write text from an originating user to originating user */
1379
1380 void User::WriteFrom(User *user, const char* text, ...)
1381 {
1382         va_list argsPtr;
1383         char textbuffer[MAXBUF];
1384
1385         va_start(argsPtr, text);
1386         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1387         va_end(argsPtr);
1388
1389         this->WriteFrom(user, std::string(textbuffer));
1390 }
1391
1392
1393 /* write text to an destination user from a source user (e.g. user privmsg) */
1394
1395 void User::WriteTo(User *dest, const char *data, ...)
1396 {
1397         char textbuffer[MAXBUF];
1398         va_list argsPtr;
1399
1400         va_start(argsPtr, data);
1401         vsnprintf(textbuffer, MAXBUF, data, argsPtr);
1402         va_end(argsPtr);
1403
1404         this->WriteTo(dest, std::string(textbuffer));
1405 }
1406
1407 void User::WriteTo(User *dest, const std::string &data)
1408 {
1409         dest->WriteFrom(this, data);
1410 }
1411
1412
1413 void User::WriteCommon(const char* text, ...)
1414 {
1415         char textbuffer[MAXBUF];
1416         va_list argsPtr;
1417
1418         if (this->registered != REG_ALL)
1419                 return;
1420
1421         va_start(argsPtr, text);
1422         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1423         va_end(argsPtr);
1424
1425         this->WriteCommon(std::string(textbuffer));
1426 }
1427
1428 void User::WriteCommon(const std::string &text)
1429 {
1430         bool sent_to_at_least_one = false;
1431         char tb[MAXBUF];
1432
1433         if (this->registered != REG_ALL)
1434                 return;
1435
1436         uniq_id++;
1437
1438         if (!already_sent)
1439                 InitializeAlreadySent(ServerInstance->SE);
1440
1441         /* We dont want to be doing this n times, just once */
1442         snprintf(tb,MAXBUF,":%s %s",this->GetFullHost().c_str(),text.c_str());
1443         std::string out = tb;
1444
1445         for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1446         {
1447                 CUList* ulist = v->first->GetUsers();
1448                 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1449                 {
1450                         if ((IS_LOCAL(i->first)) && (already_sent[i->first->fd] != uniq_id))
1451                         {
1452                                 already_sent[i->first->fd] = uniq_id;
1453                                 i->first->Write(out);
1454                                 sent_to_at_least_one = true;
1455                         }
1456                 }
1457         }
1458
1459         /*
1460          * if the user was not in any channels, no users will receive the text. Make sure the user
1461          * receives their OWN message for WriteCommon
1462          */
1463         if (!sent_to_at_least_one)
1464         {
1465                 this->Write(std::string(tb));
1466         }
1467 }
1468
1469
1470 /* write a formatted string to all users who share at least one common
1471  * channel, NOT including the source user e.g. for use in QUIT
1472  */
1473
1474 void User::WriteCommonExcept(const char* text, ...)
1475 {
1476         char textbuffer[MAXBUF];
1477         va_list argsPtr;
1478
1479         va_start(argsPtr, text);
1480         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1481         va_end(argsPtr);
1482
1483         this->WriteCommonExcept(std::string(textbuffer));
1484 }
1485
1486 void User::WriteCommonQuit(const std::string &normal_text, const std::string &oper_text)
1487 {
1488         char tb1[MAXBUF];
1489         char tb2[MAXBUF];
1490
1491         if (this->registered != REG_ALL)
1492                 return;
1493
1494         uniq_id++;
1495
1496         if (!already_sent)
1497                 InitializeAlreadySent(ServerInstance->SE);
1498
1499         snprintf(tb1,MAXBUF,":%s QUIT :%s",this->GetFullHost().c_str(),normal_text.c_str());
1500         snprintf(tb2,MAXBUF,":%s QUIT :%s",this->GetFullHost().c_str(),oper_text.c_str());
1501         std::string out1 = tb1;
1502         std::string out2 = tb2;
1503
1504         for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1505         {
1506                 CUList *ulist = v->first->GetUsers();
1507                 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1508                 {
1509                         if (this != i->first)
1510                         {
1511                                 if ((IS_LOCAL(i->first)) && (already_sent[i->first->fd] != uniq_id))
1512                                 {
1513                                         already_sent[i->first->fd] = uniq_id;
1514                                         i->first->Write(IS_OPER(i->first) ? out2 : out1);
1515                                 }
1516                         }
1517                 }
1518         }
1519 }
1520
1521 void User::WriteCommonExcept(const std::string &text)
1522 {
1523         char tb1[MAXBUF];
1524         std::string out1;
1525
1526         if (this->registered != REG_ALL)
1527                 return;
1528
1529         uniq_id++;
1530
1531         if (!already_sent)
1532                 InitializeAlreadySent(ServerInstance->SE);
1533
1534         snprintf(tb1,MAXBUF,":%s %s",this->GetFullHost().c_str(),text.c_str());
1535         out1 = tb1;
1536
1537         for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1538         {
1539                 CUList *ulist = v->first->GetUsers();
1540                 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1541                 {
1542                         if (this != i->first)
1543                         {
1544                                 if ((IS_LOCAL(i->first)) && (already_sent[i->first->fd] != uniq_id))
1545                                 {
1546                                         already_sent[i->first->fd] = uniq_id;
1547                                         i->first->Write(out1);
1548                                 }
1549                         }
1550                 }
1551         }
1552
1553 }
1554
1555 void User::WriteWallOps(const std::string &text)
1556 {
1557         if (!IS_LOCAL(this))
1558                 return;
1559
1560         std::string wallop("WALLOPS :");
1561         wallop.append(text);
1562
1563         for (std::vector<User*>::const_iterator i = ServerInstance->Users->local_users.begin(); i != ServerInstance->Users->local_users.end(); i++)
1564         {
1565                 User* t = *i;
1566                 if (t->IsModeSet('w'))
1567                         this->WriteTo(t,wallop);
1568         }
1569 }
1570
1571 void User::WriteWallOps(const char* text, ...)
1572 {
1573         if (!IS_LOCAL(this))
1574                 return;
1575
1576         char textbuffer[MAXBUF];
1577         va_list argsPtr;
1578
1579         va_start(argsPtr, text);
1580         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1581         va_end(argsPtr);
1582
1583         this->WriteWallOps(std::string(textbuffer));
1584 }
1585
1586 /* return 0 or 1 depending if users u and u2 share one or more common channels
1587  * (used by QUIT, NICK etc which arent channel specific notices)
1588  *
1589  * The old algorithm in 1.0 for this was relatively inefficient, iterating over
1590  * the first users channels then the second users channels within the outer loop,
1591  * therefore it was a maximum of x*y iterations (upon returning 0 and checking
1592  * all possible iterations). However this new function instead checks against the
1593  * channel's userlist in the inner loop which is a std::map<User*,User*>
1594  * and saves us time as we already know what pointer value we are after.
1595  * Don't quote me on the maths as i am not a mathematician or computer scientist,
1596  * but i believe this algorithm is now x+(log y) maximum iterations instead.
1597  */
1598 bool User::SharesChannelWith(User *other)
1599 {
1600         if ((!other) || (this->registered != REG_ALL) || (other->registered != REG_ALL))
1601                 return false;
1602
1603         /* Outer loop */
1604         for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1605         {
1606                 /* Eliminate the inner loop (which used to be ~equal in size to the outer loop)
1607                  * by replacing it with a map::find which *should* be more efficient
1608                  */
1609                 if (i->first->HasUser(other))
1610                         return true;
1611         }
1612         return false;
1613 }
1614
1615 bool User::ChangeName(const char* gecos)
1616 {
1617         if (!this->fullname.compare(gecos))
1618                 return true;
1619
1620         if (IS_LOCAL(this))
1621         {
1622                 int MOD_RESULT = 0;
1623                 FOREACH_RESULT(I_OnChangeLocalUserGECOS,OnChangeLocalUserGECOS(this,gecos));
1624                 if (MOD_RESULT)
1625                         return false;
1626                 FOREACH_MOD(I_OnChangeName,OnChangeName(this,gecos));
1627         }
1628         this->fullname.assign(gecos, 0, ServerInstance->Config->Limits.MaxGecos);
1629
1630         return true;
1631 }
1632
1633 bool User::ChangeDisplayedHost(const char* shost)
1634 {
1635         if (dhost == shost)
1636                 return true;
1637
1638         if (IS_LOCAL(this))
1639         {
1640                 int MOD_RESULT = 0;
1641                 FOREACH_RESULT(I_OnChangeLocalUserHost,OnChangeLocalUserHost(this,shost));
1642                 if (MOD_RESULT)
1643                         return false;
1644                 FOREACH_MOD(I_OnChangeHost,OnChangeHost(this,shost));
1645         }
1646
1647         if (this->ServerInstance->Config->CycleHosts)
1648                 this->WriteCommonExcept("QUIT :Changing hosts");
1649
1650         /* Fix by Om: User::dhost is 65 long, this was truncating some long hosts */
1651         this->dhost.assign(shost, 0, 64);
1652
1653         this->InvalidateCache();
1654
1655         if (this->ServerInstance->Config->CycleHosts)
1656         {
1657                 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1658                 {
1659                         i->first->WriteAllExceptSender(this, false, 0, "JOIN %s", i->first->name.c_str());
1660                         std::string n = this->ServerInstance->Modes->ModeString(this, i->first);
1661                         if (n.length() > 0)
1662                                 i->first->WriteAllExceptSender(this, true, 0, "MODE %s +%s", i->first->name.c_str(), n.c_str());
1663                 }
1664         }
1665
1666         if (IS_LOCAL(this))
1667                 this->WriteNumeric(RPL_YOURDISPLAYEDHOST, "%s %s :is now your displayed host",this->nick.c_str(),this->dhost.c_str());
1668
1669         return true;
1670 }
1671
1672 bool User::ChangeIdent(const char* newident)
1673 {
1674         if (!this->ident.compare(newident))
1675                 return true;
1676
1677         if (this->ServerInstance->Config->CycleHosts)
1678                 this->WriteCommonExcept("%s","QUIT :Changing ident");
1679
1680         this->ident.assign(newident, 0, ServerInstance->Config->Limits.IdentMax + 1);
1681
1682         this->InvalidateCache();
1683
1684         if (this->ServerInstance->Config->CycleHosts)
1685         {
1686                 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1687                 {
1688                         i->first->WriteAllExceptSender(this, false, 0, "JOIN %s", i->first->name.c_str());
1689                         std::string n = this->ServerInstance->Modes->ModeString(this, i->first);
1690                         if (n.length() > 0)
1691                                 i->first->WriteAllExceptSender(this, true, 0, "MODE %s +%s", i->first->name.c_str(), n.c_str());
1692                 }
1693         }
1694
1695         return true;
1696 }
1697
1698 void User::SendAll(const char* command, const char* text, ...)
1699 {
1700         char textbuffer[MAXBUF];
1701         char formatbuffer[MAXBUF];
1702         va_list argsPtr;
1703
1704         va_start(argsPtr, text);
1705         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1706         va_end(argsPtr);
1707
1708         snprintf(formatbuffer,MAXBUF,":%s %s $* :%s", this->GetFullHost().c_str(), command, textbuffer);
1709         std::string fmt = formatbuffer;
1710
1711         for (std::vector<User*>::const_iterator i = ServerInstance->Users->local_users.begin(); i != ServerInstance->Users->local_users.end(); i++)
1712         {
1713                 (*i)->Write(fmt);
1714         }
1715 }
1716
1717
1718 std::string User::ChannelList(User* source)
1719 {
1720         std::string list;
1721
1722         for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1723         {
1724                 /* If the target is the same as the sender, let them see all their channels.
1725                  * If the channel is NOT private/secret OR the user shares a common channel
1726                  * If the user is an oper, and the <options:operspywhois> option is set.
1727                  */
1728                 if ((source == this) || (IS_OPER(source) && ServerInstance->Config->OperSpyWhois) || (((!i->first->IsModeSet('p')) && (!i->first->IsModeSet('s'))) || (i->first->HasUser(source))))
1729                 {
1730                         list.append(i->first->GetPrefixChar(this)).append(i->first->name).append(" ");
1731                 }
1732         }
1733
1734         return list;
1735 }
1736
1737 void User::SplitChanList(User* dest, const std::string &cl)
1738 {
1739         std::string line;
1740         std::ostringstream prefix;
1741         std::string::size_type start, pos, length;
1742
1743         prefix << this->nick << " " << dest->nick << " :";
1744         line = prefix.str();
1745         int namelen = strlen(ServerInstance->Config->ServerName) + 6;
1746
1747         for (start = 0; (pos = cl.find(' ', start)) != std::string::npos; start = pos+1)
1748         {
1749                 length = (pos == std::string::npos) ? cl.length() : pos;
1750
1751                 if (line.length() + namelen + length - start > 510)
1752                 {
1753                         ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1754                         line = prefix.str();
1755                 }
1756
1757                 if(pos == std::string::npos)
1758                 {
1759                         line.append(cl.substr(start, length - start));
1760                         break;
1761                 }
1762                 else
1763                 {
1764                         line.append(cl.substr(start, length - start + 1));
1765                 }
1766         }
1767
1768         if (line.length())
1769         {
1770                 ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1771         }
1772 }
1773
1774 /*
1775  * Sets a user's connection class.
1776  * If the class name is provided, it will be used. Otherwise, the class will be guessed using host/ip/ident/etc.
1777  * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1778  * then their ip will be taken as 'priority' anyway, so for example,
1779  * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1780  */
1781 ConnectClass* User::SetClass(const std::string &explicit_name)
1782 {
1783         ConnectClass *found = NULL;
1784
1785         if (!IS_LOCAL(this))
1786                 return NULL;
1787
1788         ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "Setting connect class for UID %s", this->uuid.c_str());
1789
1790         if (!explicit_name.empty())
1791         {
1792                 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1793                 {
1794                         ConnectClass* c = *i;
1795
1796                         if (c->GetDisabled())
1797                                 continue; // can't possibly match, removed from conf
1798
1799                         if (explicit_name == c->GetName())
1800                         {
1801                                 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "Explicitly set to %s", explicit_name.c_str());
1802                                 found = c;
1803                         }
1804                 }
1805         }
1806         else
1807         {
1808                 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1809                 {
1810                         ConnectClass* c = *i;
1811
1812                         if (c->GetType() == CC_ALLOW)
1813                         {
1814                                 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "ALLOW %s %d %s", c->GetHost().c_str(), c->GetPort(), c->GetName().c_str());
1815                         }
1816                         else
1817                         {
1818                                 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "DENY %s %d %s", c->GetHost().c_str(), c->GetPort(), c->GetName().c_str());
1819                         }
1820
1821                         /* if it's disabled, we can't match this one. */
1822                         if (c->GetDisabled())
1823                         {
1824                                 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "Class disabled");
1825                                 continue;
1826                         }
1827
1828                         /* check if host matches.. */
1829                         if (!InspIRCd::MatchCIDR(this->GetIPString(), c->GetHost(), NULL) && 
1830                             !InspIRCd::MatchCIDR(this->host, c->GetHost(), NULL))
1831                         {
1832                                 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "No host match (for %s)", c->GetHost().c_str());
1833                                 continue;
1834                         }
1835
1836                         /*
1837                          * deny change if change will take class over the limit check it HERE, not after we found a matching class,
1838                          * because we should attempt to find another class if this one doesn't match us. -- w00t
1839                          */
1840                         if (c->limit && (c->RefCount + 1 >= c->limit))
1841                         {
1842                                 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "OOPS: Connect class limit (%lu) hit, denying", c->limit);
1843                                 continue;
1844                         }
1845
1846                         /* if it requires a port ... */
1847                         if (c->GetPort())
1848                         {
1849                                 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "Requires port (%d)", c->GetPort());
1850
1851                                 /* and our port doesn't match, fail. */
1852                                 if (this->GetPort() != c->GetPort())
1853                                 {
1854                                         ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "Port match failed (%d)", this->GetPort());
1855                                         continue;
1856                                 }
1857                         }
1858
1859                         /* we stop at the first class that meets ALL critera. */
1860                         found = c;
1861                         break;
1862                 }
1863         }
1864
1865         /*
1866          * Okay, assuming we found a class that matches.. switch us into that class, keeping refcounts up to date.
1867          */
1868         if (found)
1869         {
1870                 /* only fiddle with refcounts if they are already in a class .. */
1871                 if (this->MyClass)
1872                 {
1873                         if (found == this->MyClass) // no point changing this shit :P
1874                                 return this->MyClass;
1875                         this->MyClass->RefCount--;
1876                         ServerInstance->Logs->Log("USERS", DEBUG, "Untying user from connect class -- refcount: %lu", this->MyClass->RefCount);
1877                 }
1878
1879                 this->MyClass = found;
1880                 this->MyClass->RefCount++;
1881                 ServerInstance->Logs->Log("USERS", DEBUG, "User tied to new class -- connect refcount now: %lu", this->MyClass->RefCount);
1882         }
1883
1884         return this->MyClass;
1885 }
1886
1887 /* looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1888  * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1889  * then their ip will be taken as 'priority' anyway, so for example,
1890  * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1891  */
1892 ConnectClass* User::GetClass()
1893 {
1894         return this->MyClass;
1895 }
1896
1897 void User::PurgeEmptyChannels()
1898 {
1899         std::vector<Channel*> to_delete;
1900
1901         // firstly decrement the count on each channel
1902         for (UCListIter f = this->chans.begin(); f != this->chans.end(); f++)
1903         {
1904                 f->first->RemoveAllPrefixes(this);
1905                 if (f->first->DelUser(this) == 0)
1906                 {
1907                         /* No users left in here, mark it for deletion */
1908                         try
1909                         {
1910                                 to_delete.push_back(f->first);
1911                         }
1912                         catch (...)
1913                         {
1914                                 ServerInstance->Logs->Log("USERS", DEBUG,"Exception in User::PurgeEmptyChannels to_delete.push_back()");
1915                         }
1916                 }
1917         }
1918
1919         for (std::vector<Channel*>::iterator n = to_delete.begin(); n != to_delete.end(); n++)
1920         {
1921                 Channel* thischan = *n;
1922                 chan_hash::iterator i2 = ServerInstance->chanlist->find(thischan->name);
1923                 if (i2 != ServerInstance->chanlist->end())
1924                 {
1925                         FOREACH_MOD(I_OnChannelDelete,OnChannelDelete(i2->second));
1926                         delete i2->second;
1927                         ServerInstance->chanlist->erase(i2);
1928                         this->chans.erase(*n);
1929                 }
1930         }
1931
1932         this->UnOper();
1933 }
1934
1935 void User::ShowMOTD()
1936 {
1937         if (!ServerInstance->Config->MOTD.size())
1938         {
1939                 this->WriteNumeric(ERR_NOMOTD, "%s :Message of the day file is missing.",this->nick.c_str());
1940                 return;
1941         }
1942         this->WriteNumeric(RPL_MOTDSTART, "%s :%s message of the day", this->nick.c_str(), ServerInstance->Config->ServerName);
1943
1944         for (file_cache::iterator i = ServerInstance->Config->MOTD.begin(); i != ServerInstance->Config->MOTD.end(); i++)
1945                 this->WriteNumeric(RPL_MOTD, "%s :- %s",this->nick.c_str(),i->c_str());
1946
1947         this->WriteNumeric(RPL_ENDOFMOTD, "%s :End of message of the day.", this->nick.c_str());
1948 }
1949
1950 void User::ShowRULES()
1951 {
1952         if (!ServerInstance->Config->RULES.size())
1953         {
1954                 this->WriteNumeric(ERR_NORULES, "%s :RULES File is missing",this->nick.c_str());
1955                 return;
1956         }
1957
1958         this->WriteNumeric(RPL_RULESTART, "%s :- %s Server Rules -",this->nick.c_str(),ServerInstance->Config->ServerName);
1959
1960         for (file_cache::iterator i = ServerInstance->Config->RULES.begin(); i != ServerInstance->Config->RULES.end(); i++)
1961                 this->WriteNumeric(RPL_RULES, "%s :- %s",this->nick.c_str(),i->c_str());
1962
1963         this->WriteNumeric(RPL_RULESEND, "%s :End of RULES command.",this->nick.c_str());
1964 }
1965
1966 void User::HandleEvent(EventType et, int errornum)
1967 {
1968         if (this->quitting) // drop everything, user is due to be quit
1969                 return;
1970
1971         switch (et)
1972         {
1973                 case EVENT_READ:
1974                         ServerInstance->ProcessUser(this);
1975                 break;
1976                 case EVENT_WRITE:
1977                         this->FlushWriteBuf();
1978                 break;
1979                 case EVENT_ERROR:
1980                         ServerInstance->Users->QuitUser(this, errornum ? strerror(errornum) : "Client closed the connection");
1981                 break;
1982         }
1983 }
1984
1985 void User::SetOperQuit(const std::string &oquit)
1986 {
1987         operquitmsg = oquit;
1988 }
1989
1990 const std::string& User::GetOperQuit()
1991 {
1992         return operquitmsg;
1993 }
1994
1995 void User::IncreasePenalty(int increase)
1996 {
1997         this->Penalty += increase;
1998 }
1999
2000 void User::DecreasePenalty(int decrease)
2001 {
2002         this->Penalty -= decrease;
2003 }
2004
2005 VisData::VisData()
2006 {
2007 }
2008
2009 VisData::~VisData()
2010 {
2011 }
2012
2013 bool VisData::VisibleTo(User* user)
2014 {
2015         return true;
2016 }
2017