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