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