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