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