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