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