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