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