]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/users.cpp
Whoops, make targets case insensitive when cutting down a comma seperated list
[user/henk/code/inspircd.git] / src / users.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd is copyright (C) 2002-2006 ChatSpike-Dev.
6  *                     E-mail:
7  *              <brain@chatspike.net>
8  *                <Craig@chatspike.net>
9  *     
10  * Written by Craig Edwards, Craig McLure, and others.
11  * This program is free but copyrighted software; see
12  *          the file COPYING for details.
13  *
14  * ---------------------------------------------------
15  */
16
17 #include "configreader.h"
18 #include "channels.h"
19 #include "users.h"
20 #include "inspircd.h"
21 #include <stdarg.h>
22 #include "socketengine.h"
23 #include "wildcard.h"
24 #include "xline.h"
25 #include "cull_list.h"
26
27 static unsigned long already_sent[MAX_DESCRIPTORS] = {0};
28
29 /* XXX: Used for speeding up WriteCommon operations */
30 unsigned long uniq_id = 0;
31
32 bool InitTypes(ServerConfig* conf, const char* tag)
33 {
34         if (conf->opertypes.size())
35         {
36                 conf->GetInstance()->Log(DEBUG,"Currently %d items to clear",conf->opertypes.size());
37                 for (opertype_t::iterator n = conf->opertypes.begin(); n != conf->opertypes.end(); n++)
38                 {
39                         conf->GetInstance()->Log(DEBUG,"Clear item");
40                         if (n->second)
41                                 delete[] n->second;
42                 }
43         }
44         
45         conf->opertypes.clear();
46         return true;
47 }
48
49 bool InitClasses(ServerConfig* conf, const char* tag)
50 {
51         if (conf->operclass.size())
52         {
53                 for (operclass_t::iterator n = conf->operclass.begin(); n != conf->operclass.end(); n++)
54                 {
55                         if (n->second)
56                                 delete[] n->second;
57                 }
58         }
59         
60         conf->operclass.clear();
61         return true;
62 }
63
64 bool DoType(ServerConfig* conf, const char* tag, char** entries, void** values, int* types)
65 {
66         char* TypeName = (char*)values[0];
67         char* Classes = (char*)values[1];
68         
69         conf->opertypes[TypeName] = strdup(Classes);
70         conf->GetInstance()->Log(DEBUG,"Read oper TYPE '%s' with classes '%s'",TypeName,Classes);
71         return true;
72 }
73
74 bool DoClass(ServerConfig* conf, const char* tag, char** entries, void** values, int* types)
75 {
76         char* ClassName = (char*)values[0];
77         char* CommandList = (char*)values[1];
78         
79         conf->operclass[ClassName] = strdup(CommandList);
80         conf->GetInstance()->Log(DEBUG,"Read oper CLASS '%s' with commands '%s'",ClassName,CommandList);
81         return true;
82 }
83
84 bool DoneClassesAndTypes(ServerConfig* conf, const char* tag)
85 {
86         return true;
87 }
88
89 std::string userrec::ProcessNoticeMasks(const char *sm)
90 {
91         bool adding = true, oldadding = false;
92         const char *c = sm;
93         std::string output;
94
95         ServerInstance->Log(DEBUG,"Process notice masks");
96
97         while (c && *c)
98         {
99                 ServerInstance->Log(DEBUG,"Process notice mask %c",*c);
100                 
101                 switch (*c)
102                 {
103                         case '+':
104                                 adding = true;
105                         break;
106                         case '-':
107                                 adding = false;
108                         break;
109                         case '*':
110                                 for (unsigned char d = 'A'; d <= 'z'; d++)
111                                 {
112                                         if (ServerInstance->SNO->IsEnabled(d))
113                                         {
114                                                 if ((!IsNoticeMaskSet(d) && adding) || (IsNoticeMaskSet(d) && !adding))
115                                                 {
116                                                         if ((oldadding != adding) || (!output.length()))
117                                                                 output += (adding ? '+' : '-');
118
119                                                         this->SetNoticeMask(d, adding);
120
121                                                         output += d;
122                                                 }
123                                         }
124                                         oldadding = adding;
125                                 }
126                         break;
127                         default:
128                                 if ((*c >= 'A') && (*c <= 'z') && (ServerInstance->SNO->IsEnabled(*c)))
129                                 {
130                                         if ((!IsNoticeMaskSet(*c) && adding) || (IsNoticeMaskSet(*c) && !adding))
131                                         {
132                                                 if ((oldadding != adding) || (!output.length()))
133                                                         output += (adding ? '+' : '-');
134
135                                                 this->SetNoticeMask(*c, adding);
136
137                                                 output += *c;
138                                         }
139                                 }
140                                 oldadding = adding;
141                         break;
142                 }
143
144                 *c++;
145         }
146
147         return output;
148 }
149
150 void userrec::StartDNSLookup()
151 {
152         ServerInstance->Log(DEBUG,"Commencing reverse lookup");
153         try
154         {
155                 ServerInstance->Log(DEBUG,"Passing instance: %08x",this->ServerInstance);
156                 res_reverse = new UserResolver(this->ServerInstance, this, this->GetIPString(), DNS_QUERY_REVERSE);
157                 this->ServerInstance->AddResolver(res_reverse);
158         }
159         catch (ModuleException& e)
160         {
161                 ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
162         }
163 }
164
165 UserResolver::UserResolver(InspIRCd* Instance, userrec* user, std::string to_resolve, QueryType qt) :
166         Resolver(Instance, to_resolve, qt), bound_user(user)
167 {
168         this->fwd = (qt == DNS_QUERY_A || qt == DNS_QUERY_AAAA);
169         this->bound_fd = user->GetFd();
170 }
171
172 void UserResolver::OnLookupComplete(const std::string &result)
173 {
174         if ((!this->fwd) && (ServerInstance->SE->GetRef(this->bound_fd) == this->bound_user))
175         {
176                 ServerInstance->Log(DEBUG,"Commencing forward lookup");
177                 this->bound_user->stored_host = result;
178                 try
179                 {
180                         /* Check we didnt time out */
181                         if (this->bound_user->registered != REG_ALL)
182                         {
183                                 const char *ip = this->bound_user->GetIPString();
184                                 bound_user->res_forward = new UserResolver(this->ServerInstance, this->bound_user, result, (strstr(ip,"0::ffff:") == ip ? DNS_QUERY_A : DNS_QUERY_AAAA));
185                                 this->ServerInstance->AddResolver(bound_user->res_forward);
186                         }
187                 }
188                 catch (ModuleException& e)
189                 {
190                         ServerInstance->Log(DEBUG,"Error in resolver: %s",e.GetReason());
191                 }
192         }
193         else if ((this->fwd) && (ServerInstance->SE->GetRef(this->bound_fd) == this->bound_user))
194         {
195                 /* Both lookups completed */
196                 std::string result2 = "0::ffff:";
197                 result2.append(result);
198                 if (this->bound_user->GetIPString() == result || this->bound_user->GetIPString() == result2)
199                 {
200                         std::string hostname = this->bound_user->stored_host;
201                         if (hostname.length() < 65)
202                         {
203                                 /* Check we didnt time out */
204                                 if (this->bound_user->registered != REG_ALL)
205                                 {
206                                         /* Hostnames starting with : are not a good thing (tm) */
207                                         if (*(hostname.c_str()) == ':')
208                                                 hostname = "0" + hostname;
209
210                                         this->bound_user->WriteServ("NOTICE Auth :*** Found your hostname (%s)", hostname.c_str());
211                                         this->bound_user->dns_done = true;
212                                         strlcpy(this->bound_user->dhost, hostname.c_str(),64);
213                                         strlcpy(this->bound_user->host, hostname.c_str(),64);
214                                 }
215                         }
216                         else
217                         {
218                                 this->bound_user->WriteServ("NOTICE Auth :*** Your hostname is longer than the maximum of 64 characters, using your IP address (%s) instead.", this->bound_user->GetIPString());
219                         }
220                 }
221                 else
222                 {
223                         this->bound_user->WriteServ("NOTICE Auth :*** Your hostname does not match up with your IP address. Sorry, using your IP address (%s) instead.", this->bound_user->GetIPString());
224                 }
225         }
226 }
227
228 void UserResolver::OnError(ResolverError e, const std::string &errormessage)
229 {
230         if (ServerInstance->SE->GetRef(this->bound_fd) == this->bound_user)
231         {
232                 /* Error message here */
233                 this->bound_user->WriteServ("NOTICE Auth :*** Could not resolve your hostname, using your IP address (%s) instead.", this->bound_user->GetIPString());
234                 this->bound_user->dns_done = true;
235         }
236 }
237
238
239 bool userrec::IsNoticeMaskSet(unsigned char sm)
240 {
241         return (snomasks[sm-65]);
242 }
243
244 void userrec::SetNoticeMask(unsigned char sm, bool value)
245 {
246         snomasks[sm-65] = value;
247 }
248
249 const char* userrec::FormatNoticeMasks()
250 {
251         static char data[MAXBUF];
252         int offset = 0;
253
254         for (int n = 0; n < 64; n++)
255         {
256                 if (snomasks[n])
257                         data[offset++] = n+65;
258         }
259
260         data[offset] = 0;
261         return data;
262 }
263
264
265
266 bool userrec::IsModeSet(unsigned char m)
267 {
268         return (modes[m-65]);
269 }
270
271 void userrec::SetMode(unsigned char m, bool value)
272 {
273         modes[m-65] = value;
274 }
275
276 const char* userrec::FormatModes()
277 {
278         static char data[MAXBUF];
279         int offset = 0;
280         for (int n = 0; n < 64; n++)
281         {
282                 if (modes[n])
283                         data[offset++] = n+65;
284         }
285         data[offset] = 0;
286         return data;
287 }
288
289 userrec::userrec(InspIRCd* Instance) : ServerInstance(Instance)
290 {
291         ServerInstance->Log(DEBUG,"userrec::userrec(): Instance: %08x",ServerInstance);
292         // the PROPER way to do it, AVOID bzero at *ALL* costs
293         *password = *nick = *ident = *host = *dhost = *fullname = *awaymsg = *oper = 0;
294         server = (char*)Instance->FindServerNamePtr(Instance->Config->ServerName);
295         reset_due = ServerInstance->Time();
296         age = ServerInstance->Time(true);
297         lines_in = lastping = signon = idle_lastmsg = nping = registered = 0;
298         ChannelCount = timeout = flood = bytes_in = bytes_out = cmds_in = cmds_out = 0;
299         haspassed = dns_done = false;
300         fd = -1;
301         recvq = "";
302         sendq = "";
303         WriteError = "";
304         res_forward = res_reverse = NULL;
305         ip = NULL;
306         chans.clear();
307         invites.clear();
308         chans.resize(MAXCHANS);
309         memset(modes,0,sizeof(modes));
310         memset(snomasks,0,sizeof(snomasks));
311         
312         for (unsigned int n = 0; n < MAXCHANS; n++)
313         {
314                 chans[n] = new ucrec();
315                 chans[n]->channel = NULL;
316                 chans[n]->uc_modes = 0;
317         }
318 }
319
320 userrec::~userrec()
321 {
322         for (std::vector<ucrec*>::iterator n = chans.begin(); n != chans.end(); n++)
323         {
324                 ucrec* x = (ucrec*)*n;
325                 delete x;
326         }
327
328         if (ip)
329         {
330                 if (this->GetProtocolFamily() == AF_INET)
331                 {
332                         delete (sockaddr_in*)ip;
333                 }
334 #ifdef SUPPORT_IP6LINKS
335                 else
336                 {
337                         delete (sockaddr_in6*)ip;
338                 }
339 #endif
340         }
341 }
342
343 char* userrec::MakeHost()
344 {
345         static char nhost[MAXBUF];
346         /* This is much faster than snprintf */
347         char* t = nhost;
348         for(char* n = ident; *n; n++)
349                 *t++ = *n;
350         *t++ = '@';
351         for(char* n = host; *n; n++)
352                 *t++ = *n;
353         *t = 0;
354         return nhost;
355 }
356
357 char* userrec::MakeHostIP()
358 {
359         static char ihost[MAXBUF];
360         /* This is much faster than snprintf */
361         char* t = ihost;
362         for(char* n = ident; *n; n++)
363                 *t++ = *n;
364         *t++ = '@';
365         for(const char* n = this->GetIPString(); *n; n++)
366                 *t++ = *n;
367         *t = 0;
368         return ihost;
369 }
370
371 void userrec::CloseSocket()
372 {
373         shutdown(this->fd,2);
374         close(this->fd);
375 }
376  
377 char* userrec::GetFullHost()
378 {
379         static char result[MAXBUF];
380         char* t = result;
381         for(char* n = nick; *n; n++)
382                 *t++ = *n;
383         *t++ = '!';
384         for(char* n = ident; *n; n++)
385                 *t++ = *n;
386         *t++ = '@';
387         for(char* n = dhost; *n; n++)
388                 *t++ = *n;
389         *t = 0;
390         return result;
391 }
392
393 char* userrec::MakeWildHost()
394 {
395         static char nresult[MAXBUF];
396         char* t = nresult;
397         *t++ = '*';     *t++ = '!';
398         *t++ = '*';     *t++ = '@';
399         for(char* n = dhost; *n; n++)
400                 *t++ = *n;
401         *t = 0;
402         return nresult;
403 }
404
405 int userrec::ReadData(void* buffer, size_t size)
406 {
407         if (IS_LOCAL(this))
408         {
409                 return read(this->fd, buffer, size);
410         }
411         else
412                 return 0;
413 }
414
415
416 char* userrec::GetFullRealHost()
417 {
418         static char fresult[MAXBUF];
419         char* t = fresult;
420         for(char* n = nick; *n; n++)
421                 *t++ = *n;
422         *t++ = '!';
423         for(char* n = ident; *n; n++)
424                 *t++ = *n;
425         *t++ = '@';
426         for(char* n = host; *n; n++)
427                 *t++ = *n;
428         *t = 0;
429         return fresult;
430 }
431
432 bool userrec::IsInvited(irc::string &channel)
433 {
434         for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
435         {
436                 irc::string compare = i->channel;
437                 
438                 if (compare == channel)
439                 {
440                         return true;
441                 }
442         }
443         return false;
444 }
445
446 InvitedList* userrec::GetInviteList()
447 {
448         return &invites;
449 }
450
451 void userrec::InviteTo(irc::string &channel)
452 {
453         Invited i;
454         i.channel = channel;
455         invites.push_back(i);
456 }
457
458 void userrec::RemoveInvite(irc::string &channel)
459 {
460         ServerInstance->Log(DEBUG,"Removing invites");
461         
462         if (invites.size())
463         {
464                 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
465                 {
466                         irc::string compare = i->channel;
467                         
468                         if (compare == channel)
469                         {
470                                 invites.erase(i);
471                                 return;
472                         }
473                 }
474         }
475 }
476
477 bool userrec::HasPermission(const std::string &command)
478 {
479         char* mycmd;
480         char* savept;
481         char* savept2;
482         
483         /*
484          * users on remote servers can completely bypass all permissions based checks.
485          * This prevents desyncs when one server has different type/class tags to another.
486          * That having been said, this does open things up to the possibility of source changes
487          * allowing remote kills, etc - but if they have access to the src, they most likely have
488          * access to the conf - so it's an end to a means either way.
489          */
490         if (!IS_LOCAL(this))
491                 return true;
492         
493         // are they even an oper at all?
494         if (*this->oper)
495         {
496                 opertype_t::iterator iter_opertype = ServerInstance->Config->opertypes.find(this->oper);
497                 if (iter_opertype != ServerInstance->Config->opertypes.end())
498                 {
499                         char* Classes = strdup(iter_opertype->second);
500                         char* myclass = strtok_r(Classes," ",&savept);
501                         while (myclass)
502                         {
503                                 operclass_t::iterator iter_operclass = ServerInstance->Config->operclass.find(myclass);
504                                 if (iter_operclass != ServerInstance->Config->operclass.end())
505                                 {
506                                         char* CommandList = strdup(iter_operclass->second);
507                                         mycmd = strtok_r(CommandList," ",&savept2);
508                                         while (mycmd)
509                                         {
510                                                 if ((!strcasecmp(mycmd,command.c_str())) || (*mycmd == '*'))
511                                                 {
512                                                         free(Classes);
513                                                         free(CommandList);
514                                                         return true;
515                                                 }
516                                                 mycmd = strtok_r(NULL," ",&savept2);
517                                         }
518                                         free(CommandList);
519                                 }
520                                 myclass = strtok_r(NULL," ",&savept);
521                         }
522                         free(Classes);
523                 }
524         }
525         return false;
526 }
527
528 /** NOTE: We cannot pass a const reference to this method.
529  * The string is changed by the workings of the method,
530  * so that if we pass const ref, we end up copying it to
531  * something we can change anyway. Makes sense to just let
532  * the compiler do that copy for us.
533  */
534 bool userrec::AddBuffer(std::string a)
535 {
536         try
537         {
538                 std::string::size_type i = a.rfind('\r');
539         
540                 while (i != std::string::npos)
541                 {
542                         a.erase(i, 1);
543                         i = a.rfind('\r');
544                 }
545
546                 if (a.length())
547                         recvq.append(a);
548                 
549                 if (recvq.length() > (unsigned)this->recvqmax)
550                 {
551                         this->SetWriteError("RecvQ exceeded");
552                         ServerInstance->WriteOpers("*** User %s RecvQ of %d exceeds connect class maximum of %d",this->nick,recvq.length(),this->recvqmax);
553                         return false;
554                 }
555         
556                 return true;
557         }
558
559         catch (...)
560         {
561                 ServerInstance->Log(DEBUG,"Exception in userrec::AddBuffer()");
562                 return false;
563         }
564 }
565
566 bool userrec::BufferIsReady()
567 {
568         return (recvq.find('\n') != std::string::npos);
569 }
570
571 void userrec::ClearBuffer()
572 {
573         recvq = "";
574 }
575
576 std::string userrec::GetBuffer()
577 {
578         try
579         {
580                 if (!recvq.length())
581                         return "";
582         
583                 /* Strip any leading \r or \n off the string.
584                  * Usually there are only one or two of these,
585                  * so its is computationally cheap to do.
586                  */
587                 while ((*recvq.begin() == '\r') || (*recvq.begin() == '\n'))
588                         recvq.erase(recvq.begin());
589         
590                 for (std::string::iterator x = recvq.begin(); x != recvq.end(); x++)
591                 {
592                         /* Find the first complete line, return it as the
593                          * result, and leave the recvq as whats left
594                          */
595                         if (*x == '\n')
596                         {
597                                 std::string ret = std::string(recvq.begin(), x);
598                                 recvq.erase(recvq.begin(), x + 1);
599                                 return ret;
600                         }
601                 }
602                 return "";
603         }
604
605         catch (...)
606         {
607                 ServerInstance->Log(DEBUG,"Exception in userrec::GetBuffer()");
608                 return "";
609         }
610 }
611
612 void userrec::AddWriteBuf(const std::string &data)
613 {
614         if (*this->GetWriteError())
615                 return;
616         
617         if (sendq.length() + data.length() > (unsigned)this->sendqmax)
618         {
619                 /*
620                  * Fix by brain - Set the error text BEFORE calling writeopers, because
621                  * if we dont it'll recursively  call here over and over again trying
622                  * to repeatedly add the text to the sendq!
623                  */
624                 this->SetWriteError("SendQ exceeded");
625                 ServerInstance->WriteOpers("*** User %s SendQ of %d exceeds connect class maximum of %d",this->nick,sendq.length() + data.length(),this->sendqmax);
626                 return;
627         }
628
629         try 
630         {
631                 if (data.length() > 512)
632                 {
633                         std::string newdata(data);
634                         newdata.resize(510);
635                         newdata.append("\r\n");
636                         sendq.append(newdata);
637                 }
638                 else
639                 {
640                         sendq.append(data);
641                 }
642         }
643         catch (...)
644         {
645                 this->SetWriteError("SendQ exceeded");
646                 ServerInstance->WriteOpers("*** User %s SendQ got an exception",this->nick);
647         }
648 }
649
650 // send AS MUCH OF THE USERS SENDQ as we are able to (might not be all of it)
651 void userrec::FlushWriteBuf()
652 {
653         try
654         {
655                 if ((this->fd == FD_MAGIC_NUMBER) || (*this->GetWriteError()))
656                 {
657                         sendq = "";
658                 }
659                 if ((sendq.length()) && (this->fd != FD_MAGIC_NUMBER))
660                 {
661                         int old_sendq_length = sendq.length();
662                         const char* tb = this->sendq.c_str();
663                         int n_sent = write(this->fd,tb,this->sendq.length());
664                         if (n_sent == -1)
665                         {
666                                 if (errno == EAGAIN)
667                                 {
668                                         ServerInstance->Log(DEBUG,"EAGAIN, want write");
669                                         this->ServerInstance->SE->WantWrite(this);
670                                 }
671                                 else
672                                         this->SetWriteError(strerror(errno));
673                         }
674                         else
675                         {
676                                 /*ServerInstance->Log(DEBUG,"Wrote: %d of %d: %s", n_sent, old_sendq_length, sendq.substr(0, n_sent).c_str());*/
677                                 // advance the queue
678                                 tb += n_sent;
679                                 this->sendq = tb;
680                                 // update the user's stats counters
681                                 this->bytes_out += n_sent;
682                                 this->cmds_out++;
683                                 if (n_sent != old_sendq_length)
684                                 {
685                                         ServerInstance->Log(DEBUG,"Not all written, want write");
686                                         this->ServerInstance->SE->WantWrite(this);
687                                 }
688                         }
689                 }
690         }
691
692         catch (...)
693         {
694                 ServerInstance->Log(DEBUG,"Exception in userrec::FlushWriteBuf()");
695         }
696 }
697
698 void userrec::SetWriteError(const std::string &error)
699 {
700         try
701         {
702                 ServerInstance->Log(DEBUG,"SetWriteError: %s",error.c_str());
703                 // don't try to set the error twice, its already set take the first string.
704                 if (!this->WriteError.length())
705                 {
706                         ServerInstance->Log(DEBUG,"Setting error string for %s to '%s'",this->nick,error.c_str());
707                         this->WriteError = error;
708                 }
709         }
710
711         catch (...)
712         {
713                 ServerInstance->Log(DEBUG,"Exception in userrec::SetWriteError()");
714         }
715 }
716
717 const char* userrec::GetWriteError()
718 {
719         return this->WriteError.c_str();
720 }
721
722 void userrec::Oper(const std::string &opertype)
723 {
724         try
725         {
726                 this->modes[UM_OPERATOR] = 1;
727                 this->WriteServ("MODE %s :+o", this->nick);
728                 FOREACH_MOD(I_OnOper, OnOper(this, opertype));
729                 ServerInstance->Log(DEFAULT,"OPER: %s!%s@%s opered as type: %s", this->nick, this->ident, this->host, opertype.c_str());
730                 strlcpy(this->oper, opertype.c_str(), NICKMAX - 1);
731                 ServerInstance->all_opers.push_back(this);
732                 FOREACH_MOD(I_OnPostOper,OnPostOper(this, opertype));
733         }
734
735         catch (...)
736         {
737                 ServerInstance->Log(DEBUG,"Exception in userrec::Oper()");
738         }
739 }
740
741 void userrec::UnOper()
742 {
743         try
744         {
745                 if (*this->oper)
746                 {
747                         *this->oper = 0;
748                         this->modes[UM_OPERATOR] = 0;
749                         for (std::vector<userrec*>::iterator a = ServerInstance->all_opers.begin(); a < ServerInstance->all_opers.end(); a++)
750                         {
751                                 if (*a == this)
752                                 {
753                                         ServerInstance->Log(DEBUG,"Oper removed from optimization list");
754                                         ServerInstance->all_opers.erase(a);
755                                         return;
756                                 }
757                         }
758                 }
759         }
760
761         catch (...)
762         {
763                 ServerInstance->Log(DEBUG,"Exception in userrec::UnOper()");
764         }
765 }
766
767 void userrec::QuitUser(InspIRCd* Instance, userrec *user, const std::string &quitreason)
768 {
769         user_hash::iterator iter = Instance->clientlist.find(user->nick);
770         std::string reason = quitreason;
771
772         if (reason.length() > MAXQUIT - 1)
773                 reason.resize(MAXQUIT - 1);
774         
775         if (IS_LOCAL(user))
776                 user->Write("ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason.c_str());
777
778         if (user->registered == REG_ALL)
779         {
780                 user->PurgeEmptyChannels();
781                 FOREACH_MOD_I(Instance,I_OnUserQuit,OnUserQuit(user,reason));
782                 user->WriteCommonExcept("QUIT :%s",reason.c_str());
783         }
784
785         if (IS_LOCAL(user))
786                 user->FlushWriteBuf();
787
788         FOREACH_MOD_I(Instance,I_OnUserDisconnect,OnUserDisconnect(user));
789
790         if (IS_LOCAL(user))
791         {
792                 if (Instance->Config->GetIOHook(user->GetPort()))
793                 {
794                         try
795                         {
796                                 Instance->Config->GetIOHook(user->GetPort())->OnRawSocketClose(user->fd);
797                         }
798                         catch (ModuleException& modexcept)
799                         {
800                                 Instance->Log(DEBUG,"Module exception cought: %s",modexcept.GetReason());
801                         }
802                 }
803                 
804                 Instance->SE->DelFd(user);
805                 user->CloseSocket();
806         }
807
808         /*
809          * this must come before the ServerInstance->SNO->WriteToSnoMaskso that it doesnt try to fill their buffer with anything
810          * if they were an oper with +sn +qQ.
811          */
812         if (user->registered == REG_ALL)
813         {
814                 if (IS_LOCAL(user))
815                         Instance->SNO->WriteToSnoMask('q',"Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason.c_str());
816                 else
817                         Instance->SNO->WriteToSnoMask('Q',"Client exiting on server %s: %s!%s@%s [%s]",user->server,user->nick,user->ident,user->host,reason.c_str());
818                 user->AddToWhoWas();
819         }
820
821         if (iter != Instance->clientlist.end())
822         {
823                 Instance->Log(DEBUG,"deleting user hash value %lx",(unsigned long)user);
824                 if (IS_LOCAL(user))
825                 {
826                         if (find(Instance->local_users.begin(),Instance->local_users.end(),user) != Instance->local_users.end())
827                                 Instance->local_users.erase(find(Instance->local_users.begin(),Instance->local_users.end(),user));
828                 }
829                 Instance->clientlist.erase(iter);
830                 DELETE(user);
831         }
832 }
833
834 namespace irc
835 {
836         namespace whowas
837         {
838
839                 WhoWasGroup::WhoWasGroup(userrec* user) : host(NULL), dhost(NULL), ident(NULL), server(NULL), gecos(NULL), signon(user->signon)
840                 {
841                         this->host = strdup(user->host);
842                         this->dhost = strdup(user->dhost);
843                         this->ident = strdup(user->ident);
844                         this->server = user->server;
845                         this->gecos = strdup(user->fullname);
846                 }
847
848                 WhoWasGroup::~WhoWasGroup()
849                 {
850                         if (host)
851                                 free(host);
852                         if (dhost)
853                                 free(dhost);
854                         if (ident)
855                                 free(ident);
856                         if (gecos)
857                                 free(gecos);
858                 }
859
860                 /* every hour, run this function which removes all entries over 3 days */
861                 void MaintainWhoWas(InspIRCd* ServerInstance, time_t t)
862                 {
863                         for (whowas_users::iterator iter = ServerInstance->whowas.begin(); iter != ServerInstance->whowas.end(); iter++)
864                         {
865                                 whowas_set* n = (whowas_set*)iter->second;
866                                 if (n->size())
867                                 {
868                                         while ((n->begin() != n->end()) && ((*n->begin())->signon < t - 259200)) // 3 days
869                                         {
870                                                 WhoWasGroup *a = *(n->begin());
871                                                 DELETE(a);
872                                                 n->erase(n->begin());
873                                         }
874                                 }
875                         }
876                 }
877         };
878 };
879
880 /* adds or updates an entry in the whowas list */
881 void userrec::AddToWhoWas()
882 {
883         irc::whowas::whowas_users::iterator iter = ServerInstance->whowas.find(this->nick);
884
885         ServerInstance->Log(DEBUG,"Add to whowas lists");
886
887         if (iter == ServerInstance->whowas.end())
888         {
889                 ServerInstance->Log(DEBUG,"Adding new whowas set for %s",this->nick);
890                 irc::whowas::whowas_set* n = new irc::whowas::whowas_set;
891                 irc::whowas::WhoWasGroup *a = new irc::whowas::WhoWasGroup(this);
892                 n->push_back(a);
893                 ServerInstance->whowas[this->nick] = n;
894         }
895         else
896         {
897                 irc::whowas::whowas_set* group = (irc::whowas::whowas_set*)iter->second;
898
899                 ServerInstance->Log(DEBUG,"Using existing whowas group for %s",this->nick);
900
901                 if (group->size() > 10)
902                 {
903                         ServerInstance->Log(DEBUG,"Trimming existing group to ten entries for %s",this->nick);
904                         irc::whowas::WhoWasGroup *a = (irc::whowas::WhoWasGroup*)*(group->begin());
905                         DELETE(a);
906                         group->pop_front();
907                 }
908
909                 irc::whowas::WhoWasGroup *a = new irc::whowas::WhoWasGroup(this);
910                 group->push_back(a);
911         }
912 }
913
914 /* add a client connection to the sockets list */
915 void userrec::AddClient(InspIRCd* Instance, int socket, int port, bool iscached, insp_inaddr ip)
916 {
917         std::string tempnick = ConvToStr(socket) + "-unknown";
918         user_hash::iterator iter = Instance->clientlist.find(tempnick);
919         const char *ipaddr = insp_ntoa(ip);
920         userrec* New;
921         int j = 0;
922
923         /*
924          * fix by brain.
925          * as these nicknames are 'RFC impossible', we can be sure nobody is going to be
926          * using one as a registered connection. As they are per fd, we can also safely assume
927          * that we wont have collisions. Therefore, if the nick exists in the list, its only
928          * used by a dead socket, erase the iterator so that the new client may reclaim it.
929          * this was probably the cause of 'server ignores me when i hammer it with reconnects'
930          * issue in earlier alphas/betas
931          */
932         if (iter != Instance->clientlist.end())
933         {
934                 userrec* goner = iter->second;
935                 DELETE(goner);
936                 Instance->clientlist.erase(iter);
937         }
938
939         Instance->Log(DEBUG,"AddClient: %d %d %s",socket,port,ipaddr);
940         
941         New = new userrec(Instance);
942         Instance->clientlist[tempnick] = New;
943         New->fd = socket;
944         strlcpy(New->nick,tempnick.c_str(),NICKMAX-1);
945
946         New->server = Instance->FindServerNamePtr(Instance->Config->ServerName);
947         /* We don't need range checking here, we KNOW 'unknown\0' will fit into the ident field. */
948         strcpy(New->ident, "unknown");
949
950         New->registered = REG_NONE;
951         New->signon = Instance->Time() + Instance->Config->dns_timeout;
952         New->lastping = 1;
953
954         Instance->Log(DEBUG,"Setting socket addresses");
955         New->SetSockAddr(AF_FAMILY, ipaddr, port);
956         Instance->Log(DEBUG,"Socket addresses set.");
957
958         /* Smarter than your average bear^H^H^H^Hset of strlcpys. */
959         for (const char* temp = New->GetIPString(); *temp && j < 64; temp++, j++)
960                 New->dhost[j] = New->host[j] = *temp;
961         New->dhost[j] = New->host[j] = 0;
962         
963         Instance->Log(DEBUG,"Hosts set.");
964
965         // set the registration timeout for this user
966         unsigned long class_regtimeout = 90;
967         int class_flood = 0;
968         long class_threshold = 5;
969         long class_sqmax = 262144;      // 256kb
970         long class_rqmax = 4096;        // 4k
971
972         Instance->Log(DEBUG,"Class stuff set.");
973
974         for (ClassVector::iterator i = Instance->Config->Classes.begin(); i != Instance->Config->Classes.end(); i++)
975         {
976                 if ((i->type == CC_ALLOW) && (match(ipaddr,i->host.c_str(),true)))
977                 {
978                         class_regtimeout = (unsigned long)i->registration_timeout;
979                         class_flood = i->flood;
980                         New->pingmax = i->pingtime;
981                         class_threshold = i->threshold;
982                         class_sqmax = i->sendqmax;
983                         class_rqmax = i->recvqmax;
984                         break;
985                 }
986         }
987
988         Instance->Log(DEBUG,"nping etc set.");
989
990         New->nping = Instance->Time() + New->pingmax + Instance->Config->dns_timeout;
991         New->timeout = Instance->Time() + class_regtimeout;
992         New->flood = class_flood;
993         New->threshold = class_threshold;
994         New->sendqmax = class_sqmax;
995         New->recvqmax = class_rqmax;
996
997         Instance->Log(DEBUG,"Push back to local users.");
998         Instance->local_users.push_back(New);
999
1000         Instance->Log(DEBUG,"Check softlimit: %d %d %d",Instance->local_users.size(), Instance->Config->SoftLimit, MAXCLIENTS);
1001         if ((Instance->local_users.size() > Instance->Config->SoftLimit) || (Instance->local_users.size() >= MAXCLIENTS))
1002         {
1003                 Instance->Log(DEBUG,"Check softlimit failed");
1004                 Instance->WriteOpers("*** Warning: softlimit value has been reached: %d clients", Instance->Config->SoftLimit);
1005                 userrec::QuitUser(Instance, New,"No more connections allowed");
1006                 return;
1007         }
1008
1009         Instance->Log(DEBUG,"Softlimit passed.");
1010
1011         /*
1012          * XXX -
1013          * this is done as a safety check to keep the file descriptors within range of fd_ref_table.
1014          * its a pretty big but for the moment valid assumption:
1015          * file descriptors are handed out starting at 0, and are recycled as theyre freed.
1016          * therefore if there is ever an fd over 65535, 65536 clients must be connected to the
1017          * irc server at once (or the irc server otherwise initiating this many connections, files etc)
1018          * which for the time being is a physical impossibility (even the largest networks dont have more
1019          * than about 10,000 users on ONE server!)
1020          */
1021         if ((unsigned int)socket >= MAX_DESCRIPTORS)
1022         {
1023                 userrec::QuitUser(Instance, New, "Server is full");
1024                 return;
1025         }
1026
1027         Instance->Log(DEBUG,"socket < MAX_DESCRIPTORS passed.");
1028
1029         ELine* e = Instance->XLines->matches_exception(New);
1030         if (!e)
1031         {
1032                 Instance->Log(DEBUG,"Doesnt match eline.");
1033                 ZLine* r = Instance->XLines->matches_zline(ipaddr);
1034                 if (r)
1035                 {
1036                         Instance->Log(DEBUG,"Matches zline.");
1037                         char reason[MAXBUF];
1038                         snprintf(reason,MAXBUF,"Z-Lined: %s",r->reason);
1039                         userrec::QuitUser(Instance, New, reason);
1040                         return;
1041                 }
1042                 Instance->Log(DEBUG,"Doesnt match zline.");
1043         }
1044
1045         Instance->Log(DEBUG,"Check before AddFd.");
1046
1047         if (socket > -1)
1048         {
1049                 Instance->Log(DEBUG,"Adding fd.");
1050                 if (!Instance->SE->AddFd(New))
1051                 {
1052                         Instance->Log(DEBUG,"Oops, fd already exists");
1053                         userrec::QuitUser(Instance, New, "Internal error handling connection");
1054                         return;
1055                 }
1056         }
1057
1058         New->WriteServ("NOTICE Auth :*** Looking up your hostname...");
1059 }
1060
1061 long userrec::GlobalCloneCount()
1062 {
1063         char u2[128];
1064         long x = 0;
1065         strlcpy(u2, this->GetIPString(), 64);
1066
1067         for (user_hash::const_iterator a = ServerInstance->clientlist.begin(); a != ServerInstance->clientlist.end(); a++)
1068         {
1069                 /* We have to match ip's as strings - we don't know what protocol
1070                  * a remote user may be using
1071                  */
1072                 if (strcasecmp(a->second->GetIPString(), u2) == 0)
1073                         x++;
1074         }
1075
1076         return x;
1077 }
1078
1079 long userrec::LocalCloneCount()
1080 {
1081         long x = 0;
1082         for (std::vector<userrec*>::const_iterator a = ServerInstance->local_users.begin(); a != ServerInstance->local_users.end(); a++)
1083         {
1084                 userrec* comp = *a;
1085 #ifdef IPV6
1086                 /* I dont think theres any faster way of matching two ipv6 addresses than memcmp */
1087                 in6_addr* s1 = &(((sockaddr_in6*)comp->ip)->sin6_addr);
1088                 in6_addr* s2 = &(((sockaddr_in6*)this->ip)->sin6_addr);
1089                 if (!memcmp(s1->s6_addr, s2->s6_addr, sizeof(in6_addr)))
1090                         x++;
1091 #else
1092                 in_addr* s1 = &((sockaddr_in*)comp->ip)->sin_addr;
1093                 in_addr* s2 = &((sockaddr_in*)this->ip)->sin_addr;
1094                 if (s1->s_addr == s2->s_addr)
1095                         x++;
1096 #endif
1097         }
1098         return x;
1099 }
1100
1101 void userrec::FullConnect(CullList* Goners)
1102 {
1103         ServerInstance->stats->statsConnects++;
1104         this->idle_lastmsg = ServerInstance->Time();
1105
1106         ConnectClass a = this->GetClass();
1107
1108         if (a.type == CC_DENY)
1109         {
1110                 Goners->AddItem(this,"Unauthorised connection");
1111                 return;
1112         }
1113         
1114         if ((*(a.pass.c_str())) && (!this->haspassed))
1115         {
1116                 Goners->AddItem(this,"Invalid password");
1117                 return;
1118         }
1119         
1120         if (this->LocalCloneCount() > a.maxlocal)
1121         {
1122                 Goners->AddItem(this, "No more connections allowed from your host via this connect class (local)");
1123                 ServerInstance->WriteOpers("*** WARNING: maximum LOCAL connections (%ld) exceeded for IP %s", a.maxlocal, this->GetIPString());
1124                 return;
1125         }
1126         else if (this->GlobalCloneCount() > a.maxglobal)
1127         {
1128                 Goners->AddItem(this, "No more connections allowed from your host via this connect class (global)");
1129                 ServerInstance->WriteOpers("*** WARNING: maximum GLOBAL connections (%ld) exceeded for IP %s",a.maxglobal, this->GetIPString());
1130                 return;
1131         }
1132
1133         ELine* e = ServerInstance->XLines->matches_exception(this);
1134
1135         if (!e)
1136         {
1137                 GLine* r = ServerInstance->XLines->matches_gline(this);
1138                 
1139                 if (r)
1140                 {
1141                         char reason[MAXBUF];
1142                         snprintf(reason,MAXBUF,"G-Lined: %s",r->reason);
1143                         Goners->AddItem(this, reason);
1144                         return;
1145                 }
1146                 
1147                 KLine* n = ServerInstance->XLines->matches_kline(this);
1148                 
1149                 if (n)
1150                 {
1151                         char reason[MAXBUF];
1152                         snprintf(reason,MAXBUF,"K-Lined: %s",n->reason);
1153                         Goners->AddItem(this, reason);
1154                         return;
1155                 }
1156         }
1157
1158
1159         this->WriteServ("NOTICE Auth :Welcome to \002%s\002!",ServerInstance->Config->Network);
1160         this->WriteServ("001 %s :Welcome to the %s IRC Network %s!%s@%s",this->nick, ServerInstance->Config->Network, this->nick, this->ident, this->host);
1161         this->WriteServ("002 %s :Your host is %s, running version %s",this->nick,ServerInstance->Config->ServerName,VERSION);
1162         this->WriteServ("003 %s :This server was created %s %s", this->nick, __TIME__, __DATE__);
1163         this->WriteServ("004 %s %s %s %s %s %s", this->nick, ServerInstance->Config->ServerName, VERSION, ServerInstance->Modes->UserModeList().c_str(), ServerInstance->Modes->ChannelModeList().c_str(), ServerInstance->Modes->ParaModeList().c_str());
1164
1165         // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
1166         // so i'd better split it :)
1167         std::stringstream out(ServerInstance->Config->data005);
1168         std::string token = "";
1169         std::string line5 = "";
1170         int token_counter = 0;
1171         
1172         while (!out.eof())
1173         {
1174                 out >> token;
1175                 line5 = line5 + token + " ";
1176                 token_counter++;
1177                 
1178                 if ((token_counter >= 13) || (out.eof() == true))
1179                 {
1180                         this->WriteServ("005 %s %s:are supported by this server", this->nick, line5.c_str());
1181                         line5 = "";
1182                         token_counter = 0;
1183                 }
1184         }
1185         
1186         this->ShowMOTD();
1187
1188         /*
1189          * fix 3 by brain, move registered = 7 below these so that spurious modes and host
1190          * changes dont go out onto the network and produce 'fake direction'.
1191          */
1192         FOREACH_MOD(I_OnUserConnect,OnUserConnect(this));
1193
1194         this->registered = REG_ALL;
1195
1196         FOREACH_MOD(I_OnPostConnect,OnPostConnect(this));
1197
1198         ServerInstance->SNO->WriteToSnoMask('c',"Client connecting on port %d: %s!%s@%s [%s]", this->GetPort(), this->nick, this->ident, this->host, this->GetIPString());
1199 }
1200
1201 /** userrec::UpdateNick()
1202  * re-allocates a nick in the user_hash after they change nicknames,
1203  * returns a pointer to the new user as it may have moved
1204  */
1205 userrec* userrec::UpdateNickHash(const char* New)
1206 {
1207         try
1208         {
1209                 //user_hash::iterator newnick;
1210                 user_hash::iterator oldnick = ServerInstance->clientlist.find(this->nick);
1211
1212                 if (!strcasecmp(this->nick,New))
1213                         return oldnick->second;
1214
1215                 if (oldnick == ServerInstance->clientlist.end())
1216                         return NULL; /* doesnt exist */
1217
1218                 userrec* olduser = oldnick->second;
1219                 ServerInstance->clientlist[New] = olduser;
1220                 ServerInstance->clientlist.erase(oldnick);
1221                 return ServerInstance->clientlist[New];
1222         }
1223
1224         catch (...)
1225         {
1226                 ServerInstance->Log(DEBUG,"Exception in userrec::UpdateNickHash()");
1227                 return NULL;
1228         }
1229 }
1230
1231 bool userrec::ForceNickChange(const char* newnick)
1232 {
1233         try
1234         {
1235                 int MOD_RESULT = 0;
1236         
1237                 FOREACH_RESULT(I_OnUserPreNick,OnUserPreNick(this, newnick));
1238
1239                 if (MOD_RESULT)
1240                 {
1241                         ServerInstance->stats->statsCollisions++;
1242                         return false;
1243                 }
1244         
1245                 if (ServerInstance->XLines->matches_qline(newnick))
1246                 {
1247                         ServerInstance->stats->statsCollisions++;
1248                         return false;
1249                 }
1250
1251                 if (this->registered == REG_ALL)
1252                 {
1253                         const char* pars[1];
1254                         pars[0] = newnick;
1255                         std::string cmd = "NICK";
1256                         return (ServerInstance->Parser->CallHandler(cmd, pars, 1, this) == CMD_SUCCESS);
1257                 }
1258                 return false;
1259         }
1260
1261         catch (...)
1262         {
1263                 ServerInstance->Log(DEBUG,"Exception in userrec::ForceNickChange()");
1264                 return false;
1265         }
1266 }
1267
1268 void userrec::SetSockAddr(int protocol_family, const char* ip, int port)
1269 {
1270         switch (protocol_family)
1271         {
1272 #ifdef SUPPORT_IP6LINKS
1273                 case AF_INET6:
1274                 {
1275                         ServerInstance->Log(DEBUG,"Set inet6 protocol address");
1276                         sockaddr_in6* sin = new sockaddr_in6;
1277                         sin->sin6_family = AF_INET6;
1278                         sin->sin6_port = port;
1279                         inet_pton(AF_INET6, ip, &sin->sin6_addr);
1280                         this->ip = (sockaddr*)sin;
1281                 }
1282                 break;
1283 #endif
1284                 case AF_INET:
1285                 {
1286                         ServerInstance->Log(DEBUG,"Set inet4 protocol address");
1287                         sockaddr_in* sin = new sockaddr_in;
1288                         sin->sin_family = AF_INET;
1289                         sin->sin_port = port;
1290                         inet_pton(AF_INET, ip, &sin->sin_addr);
1291                         this->ip = (sockaddr*)sin;
1292                 }
1293                 break;
1294                 default:
1295                         ServerInstance->Log(DEBUG,"Ut oh, I dont know protocol %d to be set on '%s'!", protocol_family, this->nick);
1296                 break;
1297         }
1298 }
1299
1300 int userrec::GetPort()
1301 {
1302         if (this->ip == NULL)
1303                 return 0;
1304
1305         switch (this->GetProtocolFamily())
1306         {
1307 #ifdef SUPPORT_IP6LINKS
1308                 case AF_INET6:
1309                 {
1310                         sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1311                         return sin->sin6_port;
1312                 }
1313                 break;
1314 #endif
1315                 case AF_INET:
1316                 {
1317                         sockaddr_in* sin = (sockaddr_in*)this->ip;
1318                         return sin->sin_port;
1319                 }
1320                 break;
1321                 default:
1322                         ServerInstance->Log(DEBUG,"Ut oh, '%s' has an unknown protocol family!",this->nick);
1323                 break;
1324         }
1325         return 0;
1326 }
1327
1328 int userrec::GetProtocolFamily()
1329 {
1330         if (this->ip == NULL)
1331                 return 0;
1332
1333         sockaddr_in* sin = (sockaddr_in*)this->ip;
1334         return sin->sin_family;
1335 }
1336
1337 const char* userrec::GetIPString()
1338 {
1339         static char buf[1024];
1340
1341         if (this->ip == NULL)
1342                 return "";
1343
1344         switch (this->GetProtocolFamily())
1345         {
1346 #ifdef SUPPORT_IP6LINKS
1347                 case AF_INET6:
1348                 {
1349                         static char temp[1024];
1350                 
1351                         sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1352                         inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(buf));
1353                         /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1354                         if (*buf == ':')
1355                         {
1356                                 strlcpy(&temp[1], buf, sizeof(temp) - 1);
1357                                 *temp = '0';
1358                                 return temp;
1359                         }
1360                         return buf;
1361                 }
1362                 break;
1363 #endif
1364                 case AF_INET:
1365                 {
1366                         sockaddr_in* sin = (sockaddr_in*)this->ip;
1367                         inet_ntop(sin->sin_family, &sin->sin_addr, buf, sizeof(buf));
1368                         return buf;
1369                 }
1370                 break;
1371                 default:
1372                         ServerInstance->Log(DEBUG,"Ut oh, '%s' has an unknown protocol family!",this->nick);
1373                 break;
1374         }
1375         return "";
1376 }
1377
1378 const char* userrec::GetIPString(char* buf)
1379 {
1380         if (this->ip == NULL)
1381         {
1382                 *buf = 0;
1383                 return buf;
1384         }
1385
1386         switch (this->GetProtocolFamily())
1387         {
1388 #ifdef SUPPORT_IP6LINKS
1389                 case AF_INET6:
1390                 {
1391                         static char temp[1024];
1392                 
1393                         sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1394                         inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(buf));
1395                         /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1396                         if (*buf == ':')
1397                         {
1398                                 strlcpy(&temp[1], buf, sizeof(temp) - 1);
1399                                 *temp = '0';
1400                                 strlcpy(buf, temp, sizeof(temp));
1401                         }
1402                         return buf;
1403                 }
1404                 break;
1405 #endif
1406                 case AF_INET:
1407                 {
1408                         sockaddr_in* sin = (sockaddr_in*)this->ip;
1409                         inet_ntop(sin->sin_family, &sin->sin_addr, buf, sizeof(buf));
1410                         return buf;
1411                 }
1412                 break;
1413
1414                 default:
1415                         ServerInstance->Log(DEBUG,"Ut oh, '%s' has an unknown protocol family!",this->nick);
1416                 break;
1417         }
1418         return "";
1419 }
1420
1421 /** NOTE: We cannot pass a const reference to this method.
1422  * The string is changed by the workings of the method,
1423  * so that if we pass const ref, we end up copying it to
1424  * something we can change anyway. Makes sense to just let
1425  * the compiler do that copy for us.
1426  */
1427 void userrec::Write(std::string text)
1428 {
1429         if ((this->fd < 0) || (this->fd > MAX_DESCRIPTORS))
1430                 return;
1431
1432         try
1433         {
1434                 text.append("\r\n");
1435         }
1436         catch (...)
1437         {
1438                 ServerInstance->Log(DEBUG,"Exception in userrec::Write() std::string::append");
1439                 return;
1440         }
1441
1442         if (ServerInstance->Config->GetIOHook(this->GetPort()))
1443         {
1444                 try
1445                 {
1446                         ServerInstance->Config->GetIOHook(this->GetPort())->OnRawSocketWrite(this->fd, text.data(), text.length());
1447                 }
1448                 catch (ModuleException& modexcept)
1449                 {
1450                         ServerInstance->Log(DEBUG,"Module exception caught: %s",modexcept.GetReason());
1451                 }
1452         }
1453         else
1454         {
1455                 this->AddWriteBuf(text);
1456         }
1457         ServerInstance->stats->statsSent += text.length();
1458         this->ServerInstance->SE->WantWrite(this);
1459 }
1460
1461 /** Write()
1462  */
1463 void userrec::Write(const char *text, ...)
1464 {
1465         va_list argsPtr;
1466         char textbuffer[MAXBUF];
1467
1468         va_start(argsPtr, text);
1469         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1470         va_end(argsPtr);
1471
1472         this->Write(std::string(textbuffer));
1473 }
1474
1475 void userrec::WriteServ(const std::string& text)
1476 {
1477         char textbuffer[MAXBUF];
1478
1479         snprintf(textbuffer,MAXBUF,":%s %s",ServerInstance->Config->ServerName,text.c_str());
1480         this->Write(std::string(textbuffer));
1481 }
1482
1483 /** WriteServ()
1484  *  Same as Write(), except `text' is prefixed with `:server.name '.
1485  */
1486 void userrec::WriteServ(const char* text, ...)
1487 {
1488         va_list argsPtr;
1489         char textbuffer[MAXBUF];
1490
1491         va_start(argsPtr, text);
1492         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1493         va_end(argsPtr);
1494
1495         this->WriteServ(std::string(textbuffer));
1496 }
1497
1498
1499 void userrec::WriteFrom(userrec *user, const std::string &text)
1500 {
1501         char tb[MAXBUF];
1502
1503         snprintf(tb,MAXBUF,":%s %s",user->GetFullHost(),text.c_str());
1504         
1505         this->Write(std::string(tb));
1506 }
1507
1508
1509 /* write text from an originating user to originating user */
1510
1511 void userrec::WriteFrom(userrec *user, const char* text, ...)
1512 {
1513         va_list argsPtr;
1514         char textbuffer[MAXBUF];
1515
1516         va_start(argsPtr, text);
1517         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1518         va_end(argsPtr);
1519
1520         this->WriteFrom(user, std::string(textbuffer));
1521 }
1522
1523
1524 /* write text to an destination user from a source user (e.g. user privmsg) */
1525
1526 void userrec::WriteTo(userrec *dest, const char *data, ...)
1527 {
1528         char textbuffer[MAXBUF];
1529         va_list argsPtr;
1530
1531         va_start(argsPtr, data);
1532         vsnprintf(textbuffer, MAXBUF, data, argsPtr);
1533         va_end(argsPtr);
1534
1535         this->WriteTo(dest, std::string(textbuffer));
1536 }
1537
1538 void userrec::WriteTo(userrec *dest, const std::string &data)
1539 {
1540         dest->WriteFrom(this, data);
1541 }
1542
1543
1544 void userrec::WriteCommon(const char* text, ...)
1545 {
1546         char textbuffer[MAXBUF];
1547         va_list argsPtr;
1548
1549         if (this->registered != REG_ALL)
1550                 return;
1551
1552         va_start(argsPtr, text);
1553         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1554         va_end(argsPtr);
1555
1556         this->WriteCommon(std::string(textbuffer));
1557 }
1558
1559 void userrec::WriteCommon(const std::string &text)
1560 {
1561         try
1562         {
1563                 bool sent_to_at_least_one = false;
1564         
1565                 if (this->registered != REG_ALL)
1566                         return;
1567         
1568                 uniq_id++;
1569         
1570                 for (std::vector<ucrec*>::const_iterator v = this->chans.begin(); v != this->chans.end(); v++)
1571                 {
1572                         ucrec *n = *v;
1573                         if (n->channel)
1574                         {
1575                                 CUList *ulist= n->channel->GetUsers();
1576                 
1577                                 for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1578                                 {
1579                                         if ((IS_LOCAL(i->second)) && (already_sent[i->second->fd] != uniq_id))
1580                                         {
1581                                                 already_sent[i->second->fd] = uniq_id;
1582                                                 i->second->WriteFrom(this, std::string(text));
1583                                                 sent_to_at_least_one = true;
1584                                         }
1585                                 }
1586                         }
1587                 }
1588         
1589                 /*
1590                  * if the user was not in any channels, no users will receive the text. Make sure the user
1591                  * receives their OWN message for WriteCommon
1592                  */
1593                 if (!sent_to_at_least_one)
1594                 {
1595                         this->WriteFrom(this,std::string(text));
1596                 }
1597         }
1598
1599         catch (...)
1600         {
1601                 ServerInstance->Log(DEBUG,"Exception in userrec::WriteCommon()");
1602         }
1603 }
1604
1605
1606 /* write a formatted string to all users who share at least one common
1607  * channel, NOT including the source user e.g. for use in QUIT
1608  */
1609
1610 void userrec::WriteCommonExcept(const char* text, ...)
1611 {
1612         char textbuffer[MAXBUF];
1613         va_list argsPtr;
1614
1615         va_start(argsPtr, text);
1616         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1617         va_end(argsPtr);
1618
1619         this->WriteCommonExcept(std::string(textbuffer));
1620 }
1621
1622 void userrec::WriteCommonExcept(const std::string &text)
1623 {
1624         bool quit_munge = false;
1625         char oper_quit[MAXBUF];
1626         char textbuffer[MAXBUF];
1627
1628         strlcpy(textbuffer, text.c_str(), MAXBUF);
1629
1630         if (this->registered != REG_ALL)
1631                 return;
1632
1633         uniq_id++;
1634
1635         /* TODO: We need some form of WriteCommonExcept that will send two lines, one line to
1636          * opers and the other line to non-opers, then all this hidebans and hidesplits gunk
1637          * can go byebye.
1638          */
1639         if (ServerInstance->Config->HideSplits)
1640         {
1641                 char* check = textbuffer + 6;
1642
1643                 if (!strncasecmp(textbuffer, "QUIT :",6))
1644                 {
1645                         std::stringstream split(check);
1646                         std::string server_one;
1647                         std::string server_two;
1648
1649                         split >> server_one;
1650                         split >> server_two;
1651
1652                         if ((ServerInstance->FindServerName(server_one)) && (ServerInstance->FindServerName(server_two)))
1653                         {
1654                                 strlcpy(oper_quit,textbuffer,MAXQUIT);
1655                                 strlcpy(check,"*.net *.split",MAXQUIT);
1656                                 quit_munge = true;
1657                         }
1658                 }
1659         }
1660
1661         if ((ServerInstance->Config->HideBans) && (!quit_munge))
1662         {
1663                 if ((!strncasecmp(textbuffer, "QUIT :G-Lined:",14)) || (!strncasecmp(textbuffer, "QUIT :K-Lined:",14))
1664                 || (!strncasecmp(textbuffer, "QUIT :Q-Lined:",14)) || (!strncasecmp(textbuffer, "QUIT :Z-Lined:",14)))
1665                 {
1666                         char* check = textbuffer + 13;
1667                         strlcpy(oper_quit,textbuffer,MAXQUIT);
1668                         *check = 0;  // We don't need to strlcpy, we just chop it from the :
1669                         quit_munge = true;
1670                 }
1671         }
1672
1673         for (std::vector<ucrec*>::const_iterator v = this->chans.begin(); v != this->chans.end(); v++)
1674         {
1675                 ucrec* n = *v;
1676                 if (n->channel)
1677                 {
1678                         CUList *ulist= n->channel->GetUsers();
1679
1680                         for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
1681                         {
1682                                 if (this != i->second)
1683                                 {
1684                                         if ((IS_LOCAL(i->second)) && (already_sent[i->second->fd] != uniq_id))
1685                                         {
1686                                                 already_sent[i->second->fd] = uniq_id;
1687                                                 if (quit_munge)
1688                                                         i->second->WriteFrom(this, *i->second->oper ? std::string(oper_quit) : std::string(textbuffer));
1689                                                 else
1690                                                         i->second->WriteFrom(this, std::string(textbuffer));
1691                                         }
1692                                 }
1693                         }
1694                 }
1695         }
1696
1697 }
1698
1699 void userrec::WriteWallOps(const std::string &text)
1700 {
1701         /* Does nothing if theyre not opered */
1702         if ((!*this->oper) && (IS_LOCAL(this)))
1703                 return;
1704
1705         std::string wallop = "WALLOPS :";
1706
1707         try
1708         {
1709                 wallop.append(text);
1710         }
1711         catch (...)
1712         {
1713                 ServerInstance->Log(DEBUG,"Exception in userrec::Write() std::string::append");
1714                 return;
1715         }
1716
1717         for (std::vector<userrec*>::const_iterator i = ServerInstance->local_users.begin(); i != ServerInstance->local_users.end(); i++)
1718         {
1719                 userrec* t = *i;
1720                 if ((IS_LOCAL(t)) && (t->modes[UM_WALLOPS]))
1721                         this->WriteTo(t,wallop);
1722         }
1723 }
1724
1725 void userrec::WriteWallOps(const char* text, ...)
1726 {       
1727         char textbuffer[MAXBUF];
1728         va_list argsPtr;
1729
1730         va_start(argsPtr, text);
1731         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1732         va_end(argsPtr);                
1733                                         
1734         this->WriteWallOps(std::string(textbuffer));
1735 }                                      
1736
1737 /* return 0 or 1 depending if users u and u2 share one or more common channels
1738  * (used by QUIT, NICK etc which arent channel specific notices)
1739  *
1740  * The old algorithm in 1.0 for this was relatively inefficient, iterating over
1741  * the first users channels then the second users channels within the outer loop,
1742  * therefore it was a maximum of x*y iterations (upon returning 0 and checking
1743  * all possible iterations). However this new function instead checks against the
1744  * channel's userlist in the inner loop which is a std::map<userrec*,userrec*>
1745  * and saves us time as we already know what pointer value we are after.
1746  * Don't quote me on the maths as i am not a mathematician or computer scientist,
1747  * but i believe this algorithm is now x+(log y) maximum iterations instead.
1748  */
1749 bool userrec::SharesChannelWith(userrec *other)
1750 {
1751         if ((!other) || (this->registered != REG_ALL) || (other->registered != REG_ALL))
1752                 return false;
1753
1754         /* Outer loop */
1755         for (std::vector<ucrec*>::const_iterator i = this->chans.begin(); i != this->chans.end(); i++)
1756         {
1757                 /* Fetch the channel from the user */
1758                 ucrec* user_channel = *i;
1759
1760                 if (user_channel->channel)
1761                 {
1762                         /* Eliminate the inner loop (which used to be ~equal in size to the outer loop)
1763                          * by replacing it with a map::find which *should* be more efficient
1764                          */
1765                         if (user_channel->channel->HasUser(other))
1766                                 return true;
1767                 }
1768         }
1769         return false;
1770 }
1771
1772 int userrec::CountChannels()
1773 {
1774         return ChannelCount;
1775 }
1776
1777 void userrec::ModChannelCount(int n)
1778 {
1779         ChannelCount += n;
1780 }
1781
1782 bool userrec::ChangeName(const char* gecos)
1783 {
1784         if (!strcmp(gecos, this->fullname))
1785                 return true;
1786
1787         if (IS_LOCAL(this))
1788         {
1789                 int MOD_RESULT = 0;
1790                 FOREACH_RESULT(I_OnChangeLocalUserGECOS,OnChangeLocalUserGECOS(this,gecos));
1791                 if (MOD_RESULT)
1792                         return false;
1793                 FOREACH_MOD(I_OnChangeName,OnChangeName(this,gecos));
1794         }
1795         strlcpy(this->fullname,gecos,MAXGECOS+1);
1796         return true;
1797 }
1798
1799 bool userrec::ChangeDisplayedHost(const char* host)
1800 {
1801         if (!strcmp(host, this->dhost))
1802                 return true;
1803
1804         if (IS_LOCAL(this))
1805         {
1806                 int MOD_RESULT = 0;
1807                 FOREACH_RESULT(I_OnChangeLocalUserHost,OnChangeLocalUserHost(this,host));
1808                 if (MOD_RESULT)
1809                         return false;
1810                 FOREACH_MOD(I_OnChangeHost,OnChangeHost(this,host));
1811         }
1812         if (this->ServerInstance->Config->CycleHosts)
1813                 this->WriteCommonExcept("%s","QUIT :Changing hosts");
1814
1815         strlcpy(this->dhost,host,63);
1816
1817         if (this->ServerInstance->Config->CycleHosts)
1818         {
1819                 for (std::vector<ucrec*>::const_iterator i = this->chans.begin(); i != this->chans.end(); i++)
1820                 {
1821                         if ((*i)->channel)
1822                         {
1823                                 (*i)->channel->WriteAllExceptSender(this, false, 0, "JOIN %s", (*i)->channel->name);
1824                                 std::string n = this->ServerInstance->Modes->ModeString(this, (*i)->channel);
1825                                 if (n.length() > 0)
1826                                         (*i)->channel->WriteAllExceptSender(this, true, 0, "MODE %s +%s", (*i)->channel->name, n.c_str());
1827                         }
1828                 }
1829         }
1830
1831         if (IS_LOCAL(this))
1832                 this->WriteServ("396 %s %s :is now your hidden host",this->nick,this->dhost);
1833
1834         return true;
1835 }
1836
1837 bool userrec::ChangeIdent(const char* newident)
1838 {
1839         if (!strcmp(newident, this->ident))
1840                 return true;
1841
1842         if (this->ServerInstance->Config->CycleHosts)
1843                 this->WriteCommonExcept("%s","QUIT :Changing ident");
1844
1845         strlcpy(this->ident, newident, IDENTMAX+2);
1846
1847         if (this->ServerInstance->Config->CycleHosts)
1848         {
1849                 for (std::vector<ucrec*>::const_iterator i = this->chans.begin(); i != this->chans.end(); i++)
1850                 {
1851                         if ((*i)->channel)
1852                         {
1853                                 (*i)->channel->WriteAllExceptSender(this, false, 0, "JOIN %s", (*i)->channel->name);
1854                                 std::string n = this->ServerInstance->Modes->ModeString(this, (*i)->channel);
1855                                 if (n.length() > 0)
1856                                         (*i)->channel->WriteAllExceptSender(this, true, 0, "MODE %s +%s", (*i)->channel->name, n.c_str());
1857                         }
1858                 }
1859         }
1860
1861         return true;
1862 }
1863
1864 void userrec::NoticeAll(char* text, ...)
1865 {
1866         char textbuffer[MAXBUF];
1867         char formatbuffer[MAXBUF];
1868         va_list argsPtr;
1869
1870         va_start(argsPtr, text);
1871         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1872         va_end(argsPtr);
1873
1874         snprintf(formatbuffer,MAXBUF,"NOTICE $* :%s",textbuffer);
1875
1876         for (std::vector<userrec*>::const_iterator i = ServerInstance->local_users.begin(); i != ServerInstance->local_users.end(); i++)
1877         {
1878                 userrec* t = *i;
1879                 t->WriteFrom(this, std::string(formatbuffer));
1880         }
1881 }
1882
1883
1884 std::string userrec::ChannelList(userrec* source)
1885 {
1886         try
1887         {
1888                 std::string list;
1889                 for (std::vector<ucrec*>::const_iterator i = this->chans.begin(); i != this->chans.end(); i++)
1890                 {
1891                         ucrec* rec = *i;
1892         
1893                         if(rec->channel && rec->channel->name)
1894                         {
1895                                 /* If the target is the same as the sender, let them see all their channels.
1896                                  * If the channel is NOT private/secret OR the user shares a common channel
1897                                  * If the user is an oper, and the <options:operspywhois> option is set.
1898                                  */
1899                                 if ((source == this) || (*source->oper && ServerInstance->Config->OperSpyWhois) || (((!rec->channel->modes[CM_PRIVATE]) && (!rec->channel->modes[CM_SECRET])) || (rec->channel->HasUser(source))))
1900                                 {
1901                                         list.append(rec->channel->GetPrefixChar(this)).append(rec->channel->name).append(" ");
1902                                 }
1903                         }
1904                 }
1905                 return list;
1906         }
1907         catch (...)
1908         {
1909                 ServerInstance->Log(DEBUG,"Exception in userrec::ChannelList()");
1910                 return "";
1911         }
1912 }
1913
1914 void userrec::SplitChanList(userrec* dest, const std::string &cl)
1915 {
1916         std::string line;
1917         std::ostringstream prefix;
1918         std::string::size_type start, pos, length;
1919
1920         try
1921         {
1922                 prefix << this->nick << " " << dest->nick << " :";
1923                 line = prefix.str();
1924                 int namelen = strlen(ServerInstance->Config->ServerName) + 6;
1925         
1926                 for (start = 0; (pos = cl.find(' ', start)) != std::string::npos; start = pos+1)
1927                 {
1928                         length = (pos == std::string::npos) ? cl.length() : pos;
1929         
1930                         if (line.length() + namelen + length - start > 510)
1931                         {
1932                                 this->Write(line);
1933                                 line = prefix.str();
1934                         }
1935         
1936                         if(pos == std::string::npos)
1937                         {
1938                                 line.append(cl.substr(start, length - start));
1939                                 break;
1940                         }
1941                         else
1942                         {
1943                                 line.append(cl.substr(start, length - start + 1));
1944                         }
1945                 }
1946         
1947                 if (line.length())
1948                 {
1949                         ServerInstance->SendWhoisLine(this, dest, 319, "%s", line.c_str());
1950                 }
1951         }
1952
1953         catch (...)
1954         {
1955                 ServerInstance->Log(DEBUG,"Exception in userrec::SplitChanList()");
1956         }
1957 }
1958
1959
1960 /* looks up a users password for their connection class (<ALLOW>/<DENY> tags)
1961  * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1962  * then their ip will be taken as 'priority' anyway, so for example,
1963  * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1964  */
1965 ConnectClass& userrec::GetClass()
1966 {
1967         for (ClassVector::iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); i++)
1968         {
1969                 if ((match(this->GetIPString(),i->host.c_str(),true)) || (match(this->host,i->host.c_str())))
1970                         return *i;
1971         }
1972
1973         return *(ServerInstance->Config->Classes.begin());
1974 }
1975
1976 void userrec::PurgeEmptyChannels()
1977 {
1978         std::vector<chanrec*> to_delete;
1979
1980         // firstly decrement the count on each channel
1981         for (std::vector<ucrec*>::iterator f = this->chans.begin(); f != this->chans.end(); f++)
1982         {
1983                 ucrec* uc = *f;
1984                 if (uc->channel)
1985                 {
1986                         uc->channel->RemoveAllPrefixes(this);
1987                         if (uc->channel->DelUser(this) == 0)
1988                         {
1989                                 /* No users left in here, mark it for deletion */
1990                                 try
1991                                 {
1992                                         to_delete.push_back(uc->channel);
1993                                 }
1994                                 catch (...)
1995                                 {
1996                                         ServerInstance->Log(DEBUG,"Exception in userrec::PurgeEmptyChannels to_delete.push_back()");
1997                                 }
1998                                 uc->channel = NULL;
1999                         }
2000                 }
2001         }
2002
2003         for (std::vector<chanrec*>::iterator n = to_delete.begin(); n != to_delete.end(); n++)
2004         {
2005                 chanrec* thischan = *n;
2006                 chan_hash::iterator i2 = ServerInstance->chanlist.find(thischan->name);
2007                 if (i2 != ServerInstance->chanlist.end())
2008                 {
2009                         FOREACH_MOD(I_OnChannelDelete,OnChannelDelete(i2->second));
2010                         DELETE(i2->second);
2011                         ServerInstance->chanlist.erase(i2);
2012                 }
2013         }
2014
2015         this->UnOper();
2016 }
2017
2018 void userrec::ShowMOTD()
2019 {
2020         if (!ServerInstance->Config->MOTD.size())
2021         {
2022                 this->WriteServ("422 %s :Message of the day file is missing.",this->nick);
2023                 return;
2024         }
2025         this->WriteServ("375 %s :%s message of the day", this->nick, ServerInstance->Config->ServerName);
2026
2027         for (unsigned int i = 0; i < ServerInstance->Config->MOTD.size(); i++)
2028                 this->WriteServ("372 %s :- %s",this->nick,ServerInstance->Config->MOTD[i].c_str());
2029
2030         this->WriteServ("376 %s :End of message of the day.", this->nick);
2031 }
2032
2033 void userrec::ShowRULES()
2034 {
2035         if (!ServerInstance->Config->RULES.size())
2036         {
2037                 this->WriteServ("NOTICE %s :Rules file is missing.",this->nick);
2038                 return;
2039         }
2040         this->WriteServ("NOTICE %s :%s rules",this->nick,ServerInstance->Config->ServerName);
2041
2042         for (unsigned int i = 0; i < ServerInstance->Config->RULES.size(); i++)
2043                 this->WriteServ("NOTICE %s :%s",this->nick,ServerInstance->Config->RULES[i].c_str());
2044
2045         this->WriteServ("NOTICE %s :End of %s rules.",this->nick,ServerInstance->Config->ServerName);
2046 }
2047
2048 void userrec::HandleEvent(EventType et, int errornum)
2049 {
2050         /* WARNING: May delete this user! */
2051         try
2052         {
2053                 switch (et)
2054                 {
2055                         case EVENT_READ:
2056                                 ServerInstance->ProcessUser(this);
2057                         break;
2058                         case EVENT_WRITE:
2059                                 this->FlushWriteBuf();
2060                         break;
2061                         case EVENT_ERROR:
2062                                 this->SetWriteError(errornum ? strerror(errornum) : "EOF from client");
2063                         break;
2064                 }
2065         }
2066         catch (...)
2067         {
2068                 ServerInstance->Log(DEBUG,"Exception in userrec::HandleEvent intercepted");
2069         }
2070 }
2071