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