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