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