]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/users.cpp
a98adb0440f63869e11ad96b7080c295fcc5f255
[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         try
705         {
706                 this->modes[UM_OPERATOR] = 1;
707                 this->WriteServ("MODE %s :+o", this->nick.c_str());
708                 FOREACH_MOD(I_OnOper, OnOper(this, opertype));
709                 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());
710                 this->oper.assign(opertype, 0, 512);
711                 ServerInstance->Users->all_opers.push_back(this);
712
713                 opertype_t::iterator iter_opertype = ServerInstance->Config->opertypes.find(this->oper.c_str());
714                 if (iter_opertype != ServerInstance->Config->opertypes.end())
715                 {
716
717                         if (AllowedOperCommands)
718                                 AllowedOperCommands->clear();
719                         else
720                                 AllowedOperCommands = new std::map<std::string, bool>;
721
722                         if (!AllowedChanModes)
723                                 AllowedChanModes = new bool[64];
724
725                         if (!AllowedUserModes)
726                                 AllowedUserModes = new bool[64];
727
728                         memset(AllowedUserModes, 0, 64);
729                         memset(AllowedChanModes, 0, 64);
730
731                         char* Classes = strdup(iter_opertype->second);
732                         char* myclass = strtok_r(Classes," ",&savept);
733                         while (myclass)
734                         {
735                                 operclass_t::iterator iter_operclass = ServerInstance->Config->operclass.find(myclass);
736                                 if (iter_operclass != ServerInstance->Config->operclass.end())
737                                 {
738                                         char* CommandList = strdup(iter_operclass->second.commandlist);
739                                         mycmd = strtok_r(CommandList," ",&savept2);
740                                         while (mycmd)
741                                         {
742                                                 this->AllowedOperCommands->insert(std::make_pair(mycmd, true));
743                                                 mycmd = strtok_r(NULL," ",&savept2);
744                                         }
745                                         free(CommandList);
746                                         this->AllowedUserModes['o' - 'A'] = true; // Call me paranoid if you want.
747                                         for (unsigned char* c = (unsigned char*)iter_operclass->second.umodelist; *c; ++c)
748                                         {
749                                                 if (*c == '*')
750                                                 {
751                                                         memset(this->AllowedUserModes, (int)(true), 64);
752                                                 }
753                                                 else
754                                                 {
755                                                         this->AllowedUserModes[*c - 'A'] = true;
756                                                 }
757                                         }
758                                         for (unsigned char* c = (unsigned char*)iter_operclass->second.cmodelist; *c; ++c)
759                                         {
760                                                 if (*c == '*')
761                                                 {
762                                                         memset(this->AllowedChanModes, (int)(true), 64);
763                                                 }
764                                                 else
765                                                 {
766                                                         this->AllowedChanModes[*c - 'A'] = true;
767                                                 }
768                                         }
769                                 }
770                                 myclass = strtok_r(NULL," ",&savept);
771                         }
772                         free(Classes);
773                 }
774
775                 FOREACH_MOD(I_OnPostOper,OnPostOper(this, opertype, opername));
776         }
777
778         catch (...)
779         {
780                 ServerInstance->Logs->Log("OPER", DEBUG,"Exception in User::Oper()");
781         }
782 }
783
784 void User::UnOper()
785 {
786         if (IS_OPER(this))
787         {
788                 /* Remove all oper only modes from the user when the deoper - Bug #466*/
789                 std::string moderemove("-");
790
791                 for (unsigned char letter = 'A'; letter <= 'z'; letter++)
792                 {
793                         if (letter != 'o')
794                         {
795                                 ModeHandler* mh = ServerInstance->Modes->FindMode(letter, MODETYPE_USER);
796                                 if (mh && mh->NeedsOper())
797                                         moderemove += letter;
798                         }
799                 }
800
801                 std::vector<std::string> parameters;
802                 parameters.push_back(this->nick);
803                 parameters.push_back(moderemove);
804
805                 ServerInstance->Parser->CallHandler("MODE", parameters, this);
806
807                 /* unset their oper type (what IS_OPER checks), and remove +o */
808                 this->oper.clear();
809                 this->modes[UM_OPERATOR] = 0;
810                         
811                 /* remove the user from the oper list. Will remove multiple entries as a safeguard against bug #404 */
812                 ServerInstance->Users->all_opers.remove(this);
813
814                 if (AllowedOperCommands)
815                 {
816                         delete AllowedOperCommands;
817                         AllowedOperCommands = NULL;
818                 }
819                 if (AllowedUserModes)
820                 {
821                         delete[] AllowedUserModes;
822                         AllowedUserModes = NULL;
823                 }
824                 if (AllowedChanModes)
825                 {
826                         delete[] AllowedChanModes;
827                         AllowedChanModes = NULL;
828                 }
829
830         }
831 }
832
833 /* adds or updates an entry in the whowas list */
834 void User::AddToWhoWas()
835 {
836         Command* whowas_command = ServerInstance->Parser->GetHandler("WHOWAS");
837         if (whowas_command)
838         {
839                 std::deque<classbase*> params;
840                 params.push_back(this);
841                 whowas_command->HandleInternal(WHOWAS_ADD, params);
842         }
843 }
844
845 /*
846  * Check class restrictions
847  */
848 void User::CheckClass()
849 {
850         ConnectClass* a = this->MyClass;
851
852         if ((!a) || (a->GetType() == CC_DENY))
853         {
854                 ServerInstance->Users->QuitUser(this, "Unauthorised connection");
855                 return;
856         }
857         else if ((a->GetMaxLocal()) && (ServerInstance->Users->LocalCloneCount(this) > a->GetMaxLocal()))
858         {
859                 ServerInstance->Users->QuitUser(this, "No more connections allowed from your host via this connect class (local)");
860                 ServerInstance->SNO->WriteToSnoMask('A', "WARNING: maximum LOCAL connections (%ld) exceeded for IP %s", a->GetMaxLocal(), this->GetIPString());
861                 return;
862         }
863         else if ((a->GetMaxGlobal()) && (ServerInstance->Users->GlobalCloneCount(this) > a->GetMaxGlobal()))
864         {
865                 ServerInstance->Users->QuitUser(this, "No more connections allowed from your host via this connect class (global)");
866                 ServerInstance->SNO->WriteToSnoMask('A', "WARNING: maximum GLOBAL connections (%ld) exceeded for IP %s", a->GetMaxGlobal(), this->GetIPString());
867                 return;
868         }
869
870         this->nping = ServerInstance->Time() + a->GetPingTime() + ServerInstance->Config->dns_timeout;
871 }
872
873 bool User::CheckLines()
874 {
875         const char* check[] = { "G" , "K", NULL };
876
877         if (!this->exempt)
878         {
879                 for (int n = 0; check[n]; ++n)
880                 {
881                         XLine *r = ServerInstance->XLines->MatchesLine(check[n], this);
882
883                         if (r)
884                         {
885                                 r->Apply(this);
886                                 return true;
887                         }
888                 }
889         }
890
891         return false;
892 }
893
894 void User::FullConnect()
895 {
896         ServerInstance->stats->statsConnects++;
897         this->idle_lastmsg = ServerInstance->Time();
898
899         /*
900          * You may be thinking "wtf, we checked this in User::AddClient!" - and yes, we did, BUT.
901          * At the time AddClient is called, we don't have a resolved host, by here we probably do - which
902          * may put the user into a totally seperate class with different restrictions! so we *must* check again.
903          * Don't remove this! -- w00t
904          */
905         this->SetClass();
906         
907         /* Check the password, if one is required by the user's connect class.
908          * This CANNOT be in CheckClass(), because that is called prior to PASS as well!
909          */
910         if (this->MyClass && !this->MyClass->GetPass().empty() && !this->haspassed)
911         {
912                 ServerInstance->Users->QuitUser(this, "Invalid password");
913                 return;
914         }
915
916         if (this->CheckLines())
917                 return;
918
919         this->WriteServ("NOTICE Auth :Welcome to \002%s\002!",ServerInstance->Config->Network);
920         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());
921         this->WriteNumeric(RPL_YOURHOSTIS, "%s :Your host is %s, running version InspIRCd-1.2",this->nick.c_str(),ServerInstance->Config->ServerName);
922         this->WriteNumeric(RPL_SERVERCREATED, "%s :This server was created %s %s", this->nick.c_str(), __TIME__, __DATE__);
923         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());
924
925         ServerInstance->Config->Send005(this);
926         this->WriteNumeric(RPL_YOURUUID, "%s %s :your unique ID", this->nick.c_str(), this->uuid.c_str());
927
928
929         this->ShowMOTD();
930
931         /* Now registered */
932         if (ServerInstance->Users->unregistered_count)
933                 ServerInstance->Users->unregistered_count--;
934
935         /* Trigger LUSERS output, give modules a chance too */
936         int MOD_RESULT = 0;
937         std::string command("LUSERS");
938         std::vector<std::string> parameters;
939         FOREACH_RESULT(I_OnPreCommand, OnPreCommand(command, parameters, this, true, "LUSERS"));
940         if (!MOD_RESULT)
941                 ServerInstance->CallCommandHandler(command, parameters, this);
942
943         /*
944          * We don't set REG_ALL until triggering OnUserConnect, so some module events don't spew out stuff
945          * for a user that doesn't exist yet.
946          */
947         FOREACH_MOD(I_OnUserConnect,OnUserConnect(this));
948
949         this->registered = REG_ALL;
950
951         ServerInstance->PI->Introduce(this);
952
953         FOREACH_MOD(I_OnPostConnect,OnPostConnect(this));
954
955         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());
956         ServerInstance->Logs->Log("BANCACHE", DEBUG, "BanCache: Adding NEGATIVE hit for %s", this->GetIPString());
957         ServerInstance->BanCache->AddHit(this->GetIPString(), "", "");
958 }
959
960 /** User::UpdateNick()
961  * re-allocates a nick in the user_hash after they change nicknames,
962  * returns a pointer to the new user as it may have moved
963  */
964 User* User::UpdateNickHash(const char* New)
965 {
966         //user_hash::iterator newnick;
967         user_hash::iterator oldnick = ServerInstance->Users->clientlist->find(this->nick);
968
969         if (!irc::string(this->nick.c_str()).compare(New))
970                 return oldnick->second;
971
972         if (oldnick == ServerInstance->Users->clientlist->end())
973                 return NULL; /* doesnt exist */
974
975         User* olduser = oldnick->second;
976         (*(ServerInstance->Users->clientlist))[New] = olduser;
977         ServerInstance->Users->clientlist->erase(oldnick);
978         return olduser;
979 }
980
981 void User::InvalidateCache()
982 {
983         /* Invalidate cache */
984         cached_fullhost.clear();
985         cached_hostip.clear();
986         cached_makehost.clear();
987         cached_fullrealhost.clear();
988 }
989
990 bool User::ForceNickChange(const char* newnick)
991 {
992         int MOD_RESULT = 0;
993
994         this->InvalidateCache();
995
996         FOREACH_RESULT(I_OnUserPreNick,OnUserPreNick(this, newnick));
997
998         if (MOD_RESULT)
999         {
1000                 ServerInstance->stats->statsCollisions++;
1001                 return false;
1002         }
1003
1004         std::deque<classbase*> dummy;
1005         Command* nickhandler = ServerInstance->Parser->GetHandler("NICK");
1006         if (nickhandler) // wtfbbq, when would this not be here
1007         {
1008                 std::vector<std::string> parameters;
1009                 nickhandler->HandleInternal(1, dummy);
1010                 parameters.push_back(newnick);
1011                 bool result = (ServerInstance->Parser->CallHandler("NICK", parameters, this) == CMD_SUCCESS);
1012                 nickhandler->HandleInternal(0, dummy);
1013                 return result;
1014         }
1015
1016         // Unreachable, we hope
1017         return false;
1018 }
1019
1020 void User::SetSockAddr(int protocol_family, const char* sip, int port)
1021 {
1022         this->cachedip = "";
1023
1024         switch (protocol_family)
1025         {
1026 #ifdef SUPPORT_IP6LINKS
1027                 case AF_INET6:
1028                 {
1029                         sockaddr_in6* sin = new sockaddr_in6;
1030                         sin->sin6_family = AF_INET6;
1031                         sin->sin6_port = port;
1032                         inet_pton(AF_INET6, sip, &sin->sin6_addr);
1033                         this->ip = (sockaddr*)sin;
1034                 }
1035                 break;
1036 #endif
1037                 case AF_INET:
1038                 {
1039                         sockaddr_in* sin = new sockaddr_in;
1040                         sin->sin_family = AF_INET;
1041                         sin->sin_port = port;
1042                         inet_pton(AF_INET, sip, &sin->sin_addr);
1043                         this->ip = (sockaddr*)sin;
1044                 }
1045                 break;
1046                 default:
1047                         ServerInstance->Logs->Log("USERS",DEBUG,"Uh oh, I dont know protocol %d to be set on '%s'!", protocol_family, this->nick.c_str());
1048                 break;
1049         }
1050 }
1051
1052 int User::GetPort()
1053 {
1054         if (this->ip == NULL)
1055                 return 0;
1056
1057         switch (this->GetProtocolFamily())
1058         {
1059 #ifdef SUPPORT_IP6LINKS
1060                 case AF_INET6:
1061                 {
1062                         sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1063                         return sin->sin6_port;
1064                 }
1065                 break;
1066 #endif
1067                 case AF_INET:
1068                 {
1069                         sockaddr_in* sin = (sockaddr_in*)this->ip;
1070                         return sin->sin_port;
1071                 }
1072                 break;
1073                 default:
1074                 break;
1075         }
1076         return 0;
1077 }
1078
1079 int User::GetProtocolFamily()
1080 {
1081         if (this->ip == NULL)
1082                 return 0;
1083
1084         sockaddr_in* sin = (sockaddr_in*)this->ip;
1085         return sin->sin_family;
1086 }
1087
1088 const char* User::GetCIDRMask(int range)
1089 {
1090         static char buf[44];
1091
1092         if (this->ip == NULL)
1093                 return "";
1094
1095         if (range < 0)
1096                 throw "Negative range, sorry, no.";
1097
1098         /*
1099          * Original code written by Oliver Lupton (Om).
1100          * Integrated by me. Thanks. :) -- w00t
1101          */
1102         switch (this->GetProtocolFamily())
1103         {
1104 #ifdef SUPPORT_IP6LINKS
1105                 case AF_INET6:
1106                 {
1107                         /* unsigned char s6_addr[16]; */
1108                         struct in6_addr v6;
1109                         sockaddr_in6* sin;
1110                         int i, bytestozero, extrabits;
1111                         char buffer[40];
1112                         
1113                         if(range > 128)
1114                                 throw "CIDR mask width greater than address width (IPv6, 128 bit)";
1115
1116                         /* Access the user's IP structure directly */
1117                         sin = (sockaddr_in6*)this->ip;
1118
1119                         /* To create the CIDR mask we want to set all the bits after 'range' bits of the address
1120                          * to zero. This means the last (128 - range) bits of the address must be set to zero.
1121                          * Hence this number divided by 8 is the number of whole bytes from the end of the address
1122                          * which must be set to zero.
1123                          */
1124                         bytestozero = (128 - range) / 8;
1125                         
1126                         /* Some of the least significant bits of the next most significant byte may also have to
1127                          * be zeroed. The number of bits is the remainder of the above division.
1128                          */
1129                         extrabits = (128 - range) % 8;
1130                         
1131                         /* Populate our working struct with the parts of the user's IP which are required in the
1132                          * final CIDR mask. Set all the subsequent bytes to zero.
1133                          * (16 - bytestozero) is the number of bytes which must be populated with actual IP data.
1134                          */
1135                         for(i = 0; i < (16 - bytestozero); i++)
1136                         {
1137                                 v6.s6_addr[i] = sin->sin6_addr.s6_addr[i];
1138                         }
1139                         
1140                         /* And zero all the remaining bytes in the IP. */
1141                         for(; i < 16; i++)
1142                         {
1143                                 v6.s6_addr[i] = 0;
1144                         }
1145                                         
1146                         /* And finally, zero the extra bits required. */
1147                         v6.s6_addr[15 - bytestozero] = (v6.s6_addr[15 - bytestozero] >> extrabits) << extrabits;
1148
1149                         snprintf(buf, 44, "%s/%d", inet_ntop(AF_INET6, &v6, buffer, 40), range);
1150                         return buf;
1151                 }
1152                 break;
1153 #endif
1154                 case AF_INET:
1155                 {
1156                         struct in_addr v4;
1157                         sockaddr_in* sin;
1158                         char buffer[16];
1159
1160                         if (range > 32)
1161                                 throw "CIDR mask width greater than address width (IPv4, 32 bit)";
1162
1163                         /* Users already have a sockaddr* pointer (User::ip) which contains either a v4 or v6 structure */
1164                         sin = (sockaddr_in*)this->ip;
1165                         v4.s_addr = sin->sin_addr.s_addr;
1166
1167                         /* To create the CIDR mask we want to set all the bits after 'range' bits of the address
1168                          * to zero. This means the last (32 - range) bits of the address must be set to zero.
1169                          * This is done by shifting the value right and then back left by (32 - range) bits.
1170                          */
1171                         if(range > 0)
1172                         {
1173                                 v4.s_addr = ntohl(v4.s_addr);
1174                                 v4.s_addr = (v4.s_addr >> (32 - range)) << (32 - range);
1175                                 v4.s_addr = htonl(v4.s_addr);
1176                         }
1177                         else
1178                         {
1179                                 /* a range of zero would cause a 32 bit value to be shifted by 32 bits.
1180                                  * this has undefined behaviour, but for CIDR purposes the resulting mask
1181                                  * from a.b.c.d/0 is 0.0.0.0/0
1182                                  */
1183                                 v4.s_addr = 0;
1184                         }
1185
1186                         snprintf(buf, 44, "%s/%d", inet_ntop(AF_INET, &v4, buffer, 16), range);
1187                         return buf;
1188                 }
1189                 break;
1190         }
1191
1192         return ""; // unused, but oh well
1193 }
1194
1195 const char* User::GetIPString(bool translate4in6)
1196 {
1197         static char buf[40];
1198
1199         if (this->ip == NULL)
1200                 return "";
1201
1202         if (!this->cachedip.empty())
1203                 return this->cachedip.c_str();
1204
1205         switch (this->GetProtocolFamily())
1206         {
1207 #ifdef SUPPORT_IP6LINKS
1208                 case AF_INET6:
1209                 {
1210                         static char temp[1024];
1211
1212                         sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1213                         inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(buf));
1214                         /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1215                         if (*buf == ':')
1216                         {
1217                                 strlcpy(&temp[1], buf, sizeof(temp) - 1);
1218                                 *temp = '0';
1219                                 if (translate4in6 && !strncmp(temp, "0::ffff:", 8))
1220                                 {
1221                                         this->cachedip = temp + 8;
1222                                         return temp + 8;
1223                                 }
1224
1225                                 this->cachedip = temp;
1226                                 return temp;
1227                         }
1228                         
1229                         this->cachedip = buf;
1230                         return buf;
1231                 }
1232                 break;
1233 #endif
1234                 case AF_INET:
1235                 {
1236                         sockaddr_in* sin = (sockaddr_in*)this->ip;
1237                         inet_ntop(sin->sin_family, &sin->sin_addr, buf, sizeof(buf));
1238                         this->cachedip = buf;
1239                         return buf;
1240                 }
1241                 break;
1242                 default:
1243                 break;
1244         }
1245         
1246         // Unreachable, probably
1247         return "";
1248 }
1249
1250 /** NOTE: We cannot pass a const reference to this method.
1251  * The string is changed by the workings of the method,
1252  * so that if we pass const ref, we end up copying it to
1253  * something we can change anyway. Makes sense to just let
1254  * the compiler do that copy for us.
1255  */
1256 void User::Write(std::string text)
1257 {
1258         if (!ServerInstance->SE->BoundsCheckFd(this))
1259                 return;
1260
1261         try
1262         {
1263                 ServerInstance->Logs->Log("USEROUTPUT", DEBUG,"C[%d] O %s", this->GetFd(), text.c_str());
1264                 text.append("\r\n");
1265         }
1266         catch (...)
1267         {
1268                 ServerInstance->Logs->Log("USEROUTPUT", DEBUG,"Exception in User::Write() std::string::append");
1269                 return;
1270         }
1271
1272         if (this->io)
1273         {
1274                 /* XXX: The lack of buffering here is NOT a bug, modules implementing this interface have to
1275                  * implement their own buffering mechanisms
1276                  */
1277                 try
1278                 {
1279                         this->io->OnRawSocketWrite(this->fd, text.data(), text.length());
1280                 }
1281                 catch (CoreException& modexcept)
1282                 {
1283                         ServerInstance->Logs->Log("USEROUTPUT", DEBUG, "%s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
1284                 }
1285         }
1286         else
1287         {
1288                 this->AddWriteBuf(text);
1289         }
1290         ServerInstance->stats->statsSent += text.length();
1291         this->ServerInstance->SE->WantWrite(this);
1292 }
1293
1294 /** Write()
1295  */
1296 void User::Write(const char *text, ...)
1297 {
1298         va_list argsPtr;
1299         char textbuffer[MAXBUF];
1300
1301         va_start(argsPtr, text);
1302         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1303         va_end(argsPtr);
1304
1305         this->Write(std::string(textbuffer));
1306 }
1307
1308 void User::WriteServ(const std::string& text)
1309 {
1310         char textbuffer[MAXBUF];
1311
1312         snprintf(textbuffer,MAXBUF,":%s %s",ServerInstance->Config->ServerName,text.c_str());
1313         this->Write(std::string(textbuffer));
1314 }
1315
1316 /** WriteServ()
1317  *  Same as Write(), except `text' is prefixed with `:server.name '.
1318  */
1319 void User::WriteServ(const char* text, ...)
1320 {
1321         va_list argsPtr;
1322         char textbuffer[MAXBUF];
1323
1324         va_start(argsPtr, text);
1325         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1326         va_end(argsPtr);
1327
1328         this->WriteServ(std::string(textbuffer));
1329 }
1330
1331
1332 void User::WriteNumeric(unsigned int numeric, const char* text, ...)
1333 {
1334         va_list argsPtr;
1335         char textbuffer[MAXBUF];
1336
1337         va_start(argsPtr, text);
1338         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1339         va_end(argsPtr);
1340
1341         this->WriteNumeric(numeric, std::string(textbuffer));
1342 }
1343
1344 void User::WriteNumeric(unsigned int numeric, const std::string &text)
1345 {
1346         char textbuffer[MAXBUF];
1347         int MOD_RESULT = 0;
1348
1349         FOREACH_RESULT(I_OnNumeric, OnNumeric(this, numeric, text));
1350
1351         if (MOD_RESULT)
1352                 return;
1353
1354         snprintf(textbuffer,MAXBUF,":%s %03u %s",ServerInstance->Config->ServerName, numeric, text.c_str());
1355         this->Write(std::string(textbuffer));
1356 }
1357
1358 void User::WriteFrom(User *user, const std::string &text)
1359 {
1360         char tb[MAXBUF];
1361
1362         snprintf(tb,MAXBUF,":%s %s",user->GetFullHost().c_str(),text.c_str());
1363
1364         this->Write(std::string(tb));
1365 }
1366
1367
1368 /* write text from an originating user to originating user */
1369
1370 void User::WriteFrom(User *user, const char* text, ...)
1371 {
1372         va_list argsPtr;
1373         char textbuffer[MAXBUF];
1374
1375         va_start(argsPtr, text);
1376         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1377         va_end(argsPtr);
1378
1379         this->WriteFrom(user, std::string(textbuffer));
1380 }
1381
1382
1383 /* write text to an destination user from a source user (e.g. user privmsg) */
1384
1385 void User::WriteTo(User *dest, const char *data, ...)
1386 {
1387         char textbuffer[MAXBUF];
1388         va_list argsPtr;
1389
1390         va_start(argsPtr, data);
1391         vsnprintf(textbuffer, MAXBUF, data, argsPtr);
1392         va_end(argsPtr);
1393
1394         this->WriteTo(dest, std::string(textbuffer));
1395 }
1396
1397 void User::WriteTo(User *dest, const std::string &data)
1398 {
1399         dest->WriteFrom(this, data);
1400 }
1401
1402
1403 void User::WriteCommon(const char* text, ...)
1404 {
1405         char textbuffer[MAXBUF];
1406         va_list argsPtr;
1407
1408         if (this->registered != REG_ALL)
1409                 return;
1410
1411         va_start(argsPtr, text);
1412         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1413         va_end(argsPtr);
1414
1415         this->WriteCommon(std::string(textbuffer));
1416 }
1417
1418 void User::WriteCommon(const std::string &text)
1419 {
1420         bool sent_to_at_least_one = false;
1421         char tb[MAXBUF];
1422
1423         if (this->registered != REG_ALL)
1424                 return;
1425
1426         uniq_id++;
1427
1428         if (!already_sent)
1429                 InitializeAlreadySent(ServerInstance->SE);
1430
1431         /* We dont want to be doing this n times, just once */
1432         snprintf(tb,MAXBUF,":%s %s",this->GetFullHost().c_str(),text.c_str());
1433         std::string out = tb;
1434
1435         for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1436         {
1437                 CUList* ulist = v->first->GetUsers();
1438                 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1439                 {
1440                         if ((IS_LOCAL(i->first)) && (already_sent[i->first->fd] != uniq_id))
1441                         {
1442                                 already_sent[i->first->fd] = uniq_id;
1443                                 i->first->Write(out);
1444                                 sent_to_at_least_one = true;
1445                         }
1446                 }
1447         }
1448
1449         /*
1450          * if the user was not in any channels, no users will receive the text. Make sure the user
1451          * receives their OWN message for WriteCommon
1452          */
1453         if (!sent_to_at_least_one)
1454         {
1455                 this->Write(std::string(tb));
1456         }
1457 }
1458
1459
1460 /* write a formatted string to all users who share at least one common
1461  * channel, NOT including the source user e.g. for use in QUIT
1462  */
1463
1464 void User::WriteCommonExcept(const char* text, ...)
1465 {
1466         char textbuffer[MAXBUF];
1467         va_list argsPtr;
1468
1469         va_start(argsPtr, text);
1470         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1471         va_end(argsPtr);
1472
1473         this->WriteCommonExcept(std::string(textbuffer));
1474 }
1475
1476 void User::WriteCommonQuit(const std::string &normal_text, const std::string &oper_text)
1477 {
1478         char tb1[MAXBUF];
1479         char tb2[MAXBUF];
1480
1481         if (this->registered != REG_ALL)
1482                 return;
1483
1484         uniq_id++;
1485
1486         if (!already_sent)
1487                 InitializeAlreadySent(ServerInstance->SE);
1488
1489         snprintf(tb1,MAXBUF,":%s QUIT :%s",this->GetFullHost().c_str(),normal_text.c_str());
1490         snprintf(tb2,MAXBUF,":%s QUIT :%s",this->GetFullHost().c_str(),oper_text.c_str());
1491         std::string out1 = tb1;
1492         std::string out2 = tb2;
1493
1494         for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1495         {
1496                 CUList *ulist = v->first->GetUsers();
1497                 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1498                 {
1499                         if (this != i->first)
1500                         {
1501                                 if ((IS_LOCAL(i->first)) && (already_sent[i->first->fd] != uniq_id))
1502                                 {
1503                                         already_sent[i->first->fd] = uniq_id;
1504                                         i->first->Write(IS_OPER(i->first) ? out2 : out1);
1505                                 }
1506                         }
1507                 }
1508         }
1509 }
1510
1511 void User::WriteCommonExcept(const std::string &text)
1512 {
1513         char tb1[MAXBUF];
1514         std::string out1;
1515
1516         if (this->registered != REG_ALL)
1517                 return;
1518
1519         uniq_id++;
1520
1521         if (!already_sent)
1522                 InitializeAlreadySent(ServerInstance->SE);
1523
1524         snprintf(tb1,MAXBUF,":%s %s",this->GetFullHost().c_str(),text.c_str());
1525         out1 = tb1;
1526
1527         for (UCListIter v = this->chans.begin(); v != this->chans.end(); v++)
1528         {
1529                 CUList *ulist = v->first->GetUsers();
1530                 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1531                 {
1532                         if (this != i->first)
1533                         {
1534                                 if ((IS_LOCAL(i->first)) && (already_sent[i->first->fd] != uniq_id))
1535                                 {
1536                                         already_sent[i->first->fd] = uniq_id;
1537                                         i->first->Write(out1);
1538                                 }
1539                         }
1540                 }
1541         }
1542
1543 }
1544
1545 void User::WriteWallOps(const std::string &text)
1546 {
1547         if (!IS_LOCAL(this))
1548                 return;
1549
1550         std::string wallop("WALLOPS :");
1551         wallop.append(text);
1552
1553         for (std::vector<User*>::const_iterator i = ServerInstance->Users->local_users.begin(); i != ServerInstance->Users->local_users.end(); i++)
1554         {
1555                 User* t = *i;
1556                 if (t->IsModeSet('w'))
1557                         this->WriteTo(t,wallop);
1558         }
1559 }
1560
1561 void User::WriteWallOps(const char* text, ...)
1562 {
1563         if (!IS_LOCAL(this))
1564                 return;
1565
1566         char textbuffer[MAXBUF];
1567         va_list argsPtr;
1568
1569         va_start(argsPtr, text);
1570         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1571         va_end(argsPtr);
1572
1573         this->WriteWallOps(std::string(textbuffer));
1574 }
1575
1576 /* return 0 or 1 depending if users u and u2 share one or more common channels
1577  * (used by QUIT, NICK etc which arent channel specific notices)
1578  *
1579  * The old algorithm in 1.0 for this was relatively inefficient, iterating over
1580  * the first users channels then the second users channels within the outer loop,
1581  * therefore it was a maximum of x*y iterations (upon returning 0 and checking
1582  * all possible iterations). However this new function instead checks against the
1583  * channel's userlist in the inner loop which is a std::map<User*,User*>
1584  * and saves us time as we already know what pointer value we are after.
1585  * Don't quote me on the maths as i am not a mathematician or computer scientist,
1586  * but i believe this algorithm is now x+(log y) maximum iterations instead.
1587  */
1588 bool User::SharesChannelWith(User *other)
1589 {
1590         if ((!other) || (this->registered != REG_ALL) || (other->registered != REG_ALL))
1591                 return false;
1592
1593         /* Outer loop */
1594         for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1595         {
1596                 /* Eliminate the inner loop (which used to be ~equal in size to the outer loop)
1597                  * by replacing it with a map::find which *should* be more efficient
1598                  */
1599                 if (i->first->HasUser(other))
1600                         return true;
1601         }
1602         return false;
1603 }
1604
1605 bool User::ChangeName(const char* gecos)
1606 {
1607         if (!this->fullname.compare(gecos))
1608                 return true;
1609
1610         if (IS_LOCAL(this))
1611         {
1612                 int MOD_RESULT = 0;
1613                 FOREACH_RESULT(I_OnChangeLocalUserGECOS,OnChangeLocalUserGECOS(this,gecos));
1614                 if (MOD_RESULT)
1615                         return false;
1616                 FOREACH_MOD(I_OnChangeName,OnChangeName(this,gecos));
1617         }
1618         this->fullname.assign(gecos, 0, ServerInstance->Config->Limits.MaxGecos);
1619
1620         return true;
1621 }
1622
1623 bool User::ChangeDisplayedHost(const char* shost)
1624 {
1625         if (dhost == shost)
1626                 return true;
1627
1628         if (IS_LOCAL(this))
1629         {
1630                 int MOD_RESULT = 0;
1631                 FOREACH_RESULT(I_OnChangeLocalUserHost,OnChangeLocalUserHost(this,shost));
1632                 if (MOD_RESULT)
1633                         return false;
1634                 FOREACH_MOD(I_OnChangeHost,OnChangeHost(this,shost));
1635         }
1636
1637         if (this->ServerInstance->Config->CycleHosts)
1638                 this->WriteCommonExcept("QUIT :Changing hosts");
1639
1640         /* Fix by Om: User::dhost is 65 long, this was truncating some long hosts */
1641         this->dhost.assign(shost, 0, 64);
1642
1643         this->InvalidateCache();
1644
1645         if (this->ServerInstance->Config->CycleHosts)
1646         {
1647                 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1648                 {
1649                         i->first->WriteAllExceptSender(this, false, 0, "JOIN %s", i->first->name.c_str());
1650                         std::string n = this->ServerInstance->Modes->ModeString(this, i->first);
1651                         if (n.length() > 0)
1652                                 i->first->WriteAllExceptSender(this, true, 0, "MODE %s +%s", i->first->name.c_str(), n.c_str());
1653                 }
1654         }
1655
1656         if (IS_LOCAL(this))
1657                 this->WriteNumeric(RPL_YOURDISPLAYEDHOST, "%s %s :is now your displayed host",this->nick.c_str(),this->dhost.c_str());
1658
1659         return true;
1660 }
1661
1662 bool User::ChangeIdent(const char* newident)
1663 {
1664         if (!this->ident.compare(newident))
1665                 return true;
1666
1667         if (this->ServerInstance->Config->CycleHosts)
1668                 this->WriteCommonExcept("%s","QUIT :Changing ident");
1669
1670         this->ident.assign(newident, 0, ServerInstance->Config->Limits.IdentMax + 1);
1671
1672         this->InvalidateCache();
1673
1674         if (this->ServerInstance->Config->CycleHosts)
1675         {
1676                 for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1677                 {
1678                         i->first->WriteAllExceptSender(this, false, 0, "JOIN %s", i->first->name.c_str());
1679                         std::string n = this->ServerInstance->Modes->ModeString(this, i->first);
1680                         if (n.length() > 0)
1681                                 i->first->WriteAllExceptSender(this, true, 0, "MODE %s +%s", i->first->name.c_str(), n.c_str());
1682                 }
1683         }
1684
1685         return true;
1686 }
1687
1688 void User::SendAll(const char* command, const char* text, ...)
1689 {
1690         char textbuffer[MAXBUF];
1691         char formatbuffer[MAXBUF];
1692         va_list argsPtr;
1693
1694         va_start(argsPtr, text);
1695         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1696         va_end(argsPtr);
1697
1698         snprintf(formatbuffer,MAXBUF,":%s %s $* :%s", this->GetFullHost().c_str(), command, textbuffer);
1699         std::string fmt = formatbuffer;
1700
1701         for (std::vector<User*>::const_iterator i = ServerInstance->Users->local_users.begin(); i != ServerInstance->Users->local_users.end(); i++)
1702         {
1703                 (*i)->Write(fmt);
1704         }
1705 }
1706
1707
1708 std::string User::ChannelList(User* source)
1709 {
1710         std::string list;
1711
1712         for (UCListIter i = this->chans.begin(); i != this->chans.end(); i++)
1713         {
1714                 /* If the target is the same as the sender, let them see all their channels.
1715                  * If the channel is NOT private/secret OR the user shares a common channel
1716                  * If the user is an oper, and the <options:operspywhois> option is set.
1717                  */
1718                 if ((source == this) || (IS_OPER(source) && ServerInstance->Config->OperSpyWhois) || (((!i->first->IsModeSet('p')) && (!i->first->IsModeSet('s'))) || (i->first->HasUser(source))))
1719                 {
1720                         list.append(i->first->GetPrefixChar(this)).append(i->first->name).append(" ");
1721                 }
1722         }
1723
1724         return list;
1725 }
1726
1727 void User::SplitChanList(User* dest, const std::string &cl)
1728 {
1729         std::string line;
1730         std::ostringstream prefix;
1731         std::string::size_type start, pos, length;
1732
1733         prefix << this->nick << " " << dest->nick << " :";
1734         line = prefix.str();
1735         int namelen = strlen(ServerInstance->Config->ServerName) + 6;
1736
1737         for (start = 0; (pos = cl.find(' ', start)) != std::string::npos; start = pos+1)
1738         {
1739                 length = (pos == std::string::npos) ? cl.length() : pos;
1740
1741                 if (line.length() + namelen + length - start > 510)
1742                 {
1743                         ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1744                         line = prefix.str();
1745                 }
1746
1747                 if(pos == std::string::npos)
1748                 {
1749                         line.append(cl.substr(start, length - start));
1750                         break;
1751                 }
1752                 else
1753                 {
1754                         line.append(cl.substr(start, length - start + 1));
1755                 }
1756         }
1757
1758         if (line.length())
1759         {
1760                 ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1761         }
1762 }
1763
1764 /*
1765  * Sets a user's connection class.
1766  * If the class name is provided, it will be used. Otherwise, the class will be guessed using host/ip/ident/etc.
1767  * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1768  * then their ip will be taken as 'priority' anyway, so for example,
1769  * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1770  */
1771 ConnectClass* User::SetClass(const std::string &explicit_name)
1772 {
1773         ConnectClass *found = NULL;
1774
1775         if (!IS_LOCAL(this))
1776                 return NULL;
1777
1778         ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "Setting connect class for UID %s", this->uuid.c_str());
1779
1780         if (!explicit_name.empty())
1781         {
1782                 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1783                 {
1784                         ConnectClass* c = *i;
1785
1786                         if (c->GetDisabled())
1787                                 continue; // can't possibly match, removed from conf
1788
1789                         if (explicit_name == c->GetName())
1790                         {
1791                                 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "Explicitly set to %s", explicit_name.c_str());
1792                                 found = c;
1793                         }
1794                 }
1795         }
1796         else
1797         {
1798                 for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1799                 {
1800                         ConnectClass* c = *i;
1801
1802                         if (c->GetType() == CC_ALLOW)
1803                         {
1804                                 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "ALLOW %s %d %s", c->GetHost().c_str(), c->GetPort(), c->GetName().c_str());
1805                         }
1806                         else
1807                         {
1808                                 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "DENY %s %d %s", c->GetHost().c_str(), c->GetPort(), c->GetName().c_str());
1809                         }
1810
1811                         /* if it's disabled, we can't match this one. */
1812                         if (c->GetDisabled())
1813                         {
1814                                 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "Class disabled");
1815                                 continue;
1816                         }
1817
1818                         /* check if host matches.. */
1819                         if (!InspIRCd::MatchCIDR(this->GetIPString(), c->GetHost(), NULL) && 
1820                             !InspIRCd::MatchCIDR(this->host, c->GetHost(), NULL))
1821                         {
1822                                 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "No host match (for %s)", c->GetHost().c_str());
1823                                 continue;
1824                         }
1825
1826                         /*
1827                          * deny change if change will take class over the limit check it HERE, not after we found a matching class,
1828                          * because we should attempt to find another class if this one doesn't match us. -- w00t
1829                          */
1830                         if (c->limit && (c->RefCount + 1 >= c->limit))
1831                         {
1832                                 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "OOPS: Connect class limit (%lu) hit, denying", c->limit);
1833                                 continue;
1834                         }
1835
1836                         /* if it requires a port ... */
1837                         if (c->GetPort())
1838                         {
1839                                 ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "Requires port (%d)", c->GetPort());
1840
1841                                 /* and our port doesn't match, fail. */
1842                                 if (this->GetPort() != c->GetPort())
1843                                 {
1844                                         ServerInstance->Logs->Log("CONNECTCLASS", DEBUG, "Port match failed (%d)", this->GetPort());
1845                                         continue;
1846                                 }
1847                         }
1848
1849                         /* we stop at the first class that meets ALL critera. */
1850                         found = c;
1851                         break;
1852                 }
1853         }
1854
1855         /*
1856          * Okay, assuming we found a class that matches.. switch us into that class, keeping refcounts up to date.
1857          */
1858         if (found)
1859         {
1860                 /* only fiddle with refcounts if they are already in a class .. */
1861                 if (this->MyClass)
1862                 {
1863                         if (found == this->MyClass) // no point changing this shit :P
1864                                 return this->MyClass;
1865                         this->MyClass->RefCount--;
1866                         ServerInstance->Logs->Log("USERS", DEBUG, "Untying user from connect class -- refcount: %lu", this->MyClass->RefCount);
1867                 }
1868
1869                 this->MyClass = found;
1870                 this->MyClass->RefCount++;
1871                 ServerInstance->Logs->Log("USERS", DEBUG, "User tied to new class -- connect refcount now: %lu", this->MyClass->RefCount);
1872         }
1873
1874         return this->MyClass;
1875 }
1876
1877 /* looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1878  * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1879  * then their ip will be taken as 'priority' anyway, so for example,
1880  * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1881  */
1882 ConnectClass* User::GetClass()
1883 {
1884         return this->MyClass;
1885 }
1886
1887 void User::PurgeEmptyChannels()
1888 {
1889         std::vector<Channel*> to_delete;
1890
1891         // firstly decrement the count on each channel
1892         for (UCListIter f = this->chans.begin(); f != this->chans.end(); f++)
1893         {
1894                 f->first->RemoveAllPrefixes(this);
1895                 if (f->first->DelUser(this) == 0)
1896                 {
1897                         /* No users left in here, mark it for deletion */
1898                         try
1899                         {
1900                                 to_delete.push_back(f->first);
1901                         }
1902                         catch (...)
1903                         {
1904                                 ServerInstance->Logs->Log("USERS", DEBUG,"Exception in User::PurgeEmptyChannels to_delete.push_back()");
1905                         }
1906                 }
1907         }
1908
1909         for (std::vector<Channel*>::iterator n = to_delete.begin(); n != to_delete.end(); n++)
1910         {
1911                 Channel* thischan = *n;
1912                 chan_hash::iterator i2 = ServerInstance->chanlist->find(thischan->name);
1913                 if (i2 != ServerInstance->chanlist->end())
1914                 {
1915                         FOREACH_MOD(I_OnChannelDelete,OnChannelDelete(i2->second));
1916                         delete i2->second;
1917                         ServerInstance->chanlist->erase(i2);
1918                         this->chans.erase(*n);
1919                 }
1920         }
1921
1922         this->UnOper();
1923 }
1924
1925 void User::ShowMOTD()
1926 {
1927         if (!ServerInstance->Config->MOTD.size())
1928         {
1929                 this->WriteNumeric(ERR_NOMOTD, "%s :Message of the day file is missing.",this->nick.c_str());
1930                 return;
1931         }
1932         this->WriteNumeric(RPL_MOTDSTART, "%s :%s message of the day", this->nick.c_str(), ServerInstance->Config->ServerName);
1933
1934         for (file_cache::iterator i = ServerInstance->Config->MOTD.begin(); i != ServerInstance->Config->MOTD.end(); i++)
1935                 this->WriteNumeric(RPL_MOTD, "%s :- %s",this->nick.c_str(),i->c_str());
1936
1937         this->WriteNumeric(RPL_ENDOFMOTD, "%s :End of message of the day.", this->nick.c_str());
1938 }
1939
1940 void User::ShowRULES()
1941 {
1942         if (!ServerInstance->Config->RULES.size())
1943         {
1944                 this->WriteNumeric(ERR_NORULES, "%s :RULES File is missing",this->nick.c_str());
1945                 return;
1946         }
1947
1948         this->WriteNumeric(RPL_RULESTART, "%s :- %s Server Rules -",this->nick.c_str(),ServerInstance->Config->ServerName);
1949
1950         for (file_cache::iterator i = ServerInstance->Config->RULES.begin(); i != ServerInstance->Config->RULES.end(); i++)
1951                 this->WriteNumeric(RPL_RULES, "%s :- %s",this->nick.c_str(),i->c_str());
1952
1953         this->WriteNumeric(RPL_RULESEND, "%s :End of RULES command.",this->nick.c_str());
1954 }
1955
1956 void User::HandleEvent(EventType et, int errornum)
1957 {
1958         if (this->quitting) // drop everything, user is due to be quit
1959                 return;
1960
1961         switch (et)
1962         {
1963                 case EVENT_READ:
1964                         ServerInstance->ProcessUser(this);
1965                 break;
1966                 case EVENT_WRITE:
1967                         this->FlushWriteBuf();
1968                 break;
1969                 case EVENT_ERROR:
1970                         ServerInstance->Users->QuitUser(this, errornum ? strerror(errornum) : "Client closed the connection");
1971                 break;
1972         }
1973 }
1974
1975 void User::SetOperQuit(const std::string &oquit)
1976 {
1977         operquitmsg = oquit;
1978 }
1979
1980 const std::string& User::GetOperQuit()
1981 {
1982         return operquitmsg;
1983 }
1984
1985 void User::IncreasePenalty(int increase)
1986 {
1987         this->Penalty += increase;
1988 }
1989
1990 void User::DecreasePenalty(int decrease)
1991 {
1992         this->Penalty -= decrease;
1993 }
1994
1995 VisData::VisData()
1996 {
1997 }
1998
1999 VisData::~VisData()
2000 {
2001 }
2002
2003 bool VisData::VisibleTo(User* user)
2004 {
2005         return true;
2006 }
2007