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