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