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