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