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