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