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