]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/users.cpp
Fix crashbug when exiting a remote client with threaded dns on (oops)
[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 "inspircd_config.h"
18 #include "configreader.h"
19 #include "channels.h"
20 #include "connection.h"
21 #include "users.h"
22 #include "inspircd.h"
23 #include <stdio.h>
24 #ifdef THREADED_DNS
25 #include <pthread.h>
26 #include <signal.h>
27 #endif
28 #include "inspstring.h"
29 #include "commands.h"
30 #include "helperfuncs.h"
31 #include "typedefs.h"
32 #include "socketengine.h"
33 #include "hashcomp.h"
34 #include "message.h"
35 #include "wildcard.h"
36 #include "xline.h"
37 #include "cull_list.h"
38
39 extern InspIRCd* ServerInstance;
40 extern int WHOWAS_STALE;
41 extern int WHOWAS_MAX;
42 extern std::vector<Module*> modules;
43 extern std::vector<ircd_module*> factory;
44 extern std::vector<InspSocket*> module_sockets;
45 extern int MODCOUNT;
46 extern InspSocket* socket_ref[MAX_DESCRIPTORS];
47 extern time_t TIME;
48 extern userrec* fd_ref_table[MAX_DESCRIPTORS];
49 extern ServerConfig *Config;
50 extern user_hash clientlist;
51
52 whowas_users whowas;
53
54 extern std::vector<userrec*> local_users;
55
56 std::vector<userrec*> all_opers;
57
58 typedef std::map<irc::string,char*> opertype_t;
59 typedef opertype_t operclass_t;
60
61 opertype_t opertypes;
62 operclass_t operclass;
63
64 bool InitTypes(const char* tag)
65 {
66         for (opertype_t::iterator n = opertypes.begin(); n != opertypes.end(); n++)
67         {
68                 if (n->second)
69                         delete[] n->second;
70         }
71         
72         opertypes.clear();
73         return true;
74 }
75
76 bool InitClasses(const char* tag)
77 {
78         for (operclass_t::iterator n = operclass.begin(); n != operclass.end(); n++)
79         {
80                 if (n->second)
81                         delete[] n->second;
82         }
83         
84         operclass.clear();
85         return true;
86 }
87
88 bool DoType(const char* tag, char** entries, void** values, int* types)
89 {
90         char* TypeName = (char*)values[0];
91         char* Classes = (char*)values[1];
92         
93         opertypes[TypeName] = strdup(Classes);
94         log(DEBUG,"Read oper TYPE '%s' with classes '%s'",TypeName,Classes);
95         return true;
96 }
97
98 bool DoClass(const char* tag, char** entries, void** values, int* types)
99 {
100         char* ClassName = (char*)values[0];
101         char* CommandList = (char*)values[1];
102         
103         operclass[ClassName] = strdup(CommandList);
104         log(DEBUG,"Read oper CLASS '%s' with commands '%s'",ClassName,CommandList);
105         return true;
106 }
107
108 bool DoneClassesAndTypes(const char* tag)
109 {
110         return true;
111 }
112
113 bool userrec::ProcessNoticeMasks(const char *sm)
114 {
115         bool adding = true;
116         const char *c = sm;
117
118         while (c && *c)
119         {
120                 switch (*c)
121                 {
122                         case '+':
123                                 adding = true;
124                                 break;
125                         case '-':
126                                 adding = false;
127                                 break;
128                         default:
129                                 if ((*c >= 'A') && (*c <= 'z'))
130                                         this->SetNoticeMask(*c, adding);
131                                 break;
132                 }
133
134                 *c++;
135         }
136
137         return true;
138 }
139
140 bool userrec::IsNoticeMaskSet(unsigned char sm)
141 {
142         return (snomasks[sm-65]);
143 }
144
145 void userrec::SetNoticeMask(unsigned char sm, bool value)
146 {
147         snomasks[sm-65] = value;
148 }
149
150 const char* userrec::FormatNoticeMasks()
151 {
152         static char data[MAXBUF];
153         int offset = 0;
154
155         for (int n = 0; n < 64; n++)
156         {
157                 if (snomasks[n])
158                         data[offset++] = n+65;
159         }
160
161         data[offset] = 0;
162         return data;
163 }
164
165
166
167 bool userrec::IsModeSet(unsigned char m)
168 {
169         return (modes[m-65]);
170 }
171
172 void userrec::SetMode(unsigned char m, bool value)
173 {
174         modes[m-65] = value;
175 }
176
177 const char* userrec::FormatModes()
178 {
179         static char data[MAXBUF];
180         int offset = 0;
181         for (int n = 0; n < 64; n++)
182         {
183                 if (modes[n])
184                         data[offset++] = n+65;
185         }
186         data[offset] = 0;
187         return data;
188 }
189
190 userrec::userrec()
191 {
192         // the PROPER way to do it, AVOID bzero at *ALL* costs
193         *password = *nick = *ident = *host = *dhost = *fullname = *awaymsg = *oper = 0;
194         server = (char*)FindServerNamePtr(Config->ServerName);
195         reset_due = TIME;
196         lines_in = fd = lastping = signon = idle_lastmsg = nping = registered = 0;
197         timeout = flood = port = bytes_in = bytes_out = cmds_in = cmds_out = 0;
198         haspassed = dns_done = false;
199         recvq = "";
200         sendq = "";
201         chans.clear();
202         invites.clear();
203         chans.resize(MAXCHANS);
204         memset(modes,0,sizeof(modes));
205         
206         for (unsigned int n = 0; n < MAXCHANS; n++)
207         {
208                 ucrec* x = new ucrec();
209                 chans[n] = x;
210                 x->channel = NULL;
211                 x->uc_modes = 0;
212         }
213 }
214
215 userrec::~userrec()
216 {
217         for (std::vector<ucrec*>::iterator n = chans.begin(); n != chans.end(); n++)
218         {
219                 ucrec* x = (ucrec*)*n;
220                 delete x;
221         }
222 #ifdef THREADED_DNS
223         if ((IS_LOCAL(this)) && (!dns_done) && (registered >= 3))
224         {
225                 pthread_kill(this->dnsthread, SIGTERM);
226         }
227 #endif
228 }
229
230 /* XXX - minor point, other *Host functions return a char *, this one creates it. Might be nice to be consistant? */
231 void userrec::MakeHost(char* nhost)
232 {
233         /* This is much faster than snprintf */
234         char* t = nhost;
235         for(char* n = ident; *n; n++)
236                 *t++ = *n;
237         *t++ = '@';
238         for(char* n = host; *n; n++)
239                 *t++ = *n;
240         *t = 0;
241 }
242
243 void userrec::CloseSocket()
244 {
245         shutdown(this->fd,2);
246         close(this->fd);
247 }
248  
249 char* userrec::GetFullHost()
250 {
251         static char result[MAXBUF];
252         char* t = result;
253         for(char* n = nick; *n; n++)
254                 *t++ = *n;
255         *t++ = '!';
256         for(char* n = ident; *n; n++)
257                 *t++ = *n;
258         *t++ = '@';
259         for(char* n = dhost; *n; n++)
260                 *t++ = *n;
261         *t = 0;
262         return result;
263 }
264
265 char* userrec::MakeWildHost()
266 {
267         static char nresult[MAXBUF];
268         char* t = nresult;
269         *t++ = '*';     *t++ = '!';
270         *t++ = '*';     *t++ = '@';
271         for(char* n = dhost; *n; n++)
272                 *t++ = *n;
273         *t = 0;
274         return nresult;
275 }
276
277 int userrec::ReadData(void* buffer, size_t size)
278 {
279         if (this->fd > -1)
280         {
281                 return read(this->fd, buffer, size);
282         }
283         else
284                 return 0;
285 }
286
287
288 char* userrec::GetFullRealHost()
289 {
290         static char fresult[MAXBUF];
291         char* t = fresult;
292         for(char* n = nick; *n; n++)
293                 *t++ = *n;
294         *t++ = '!';
295         for(char* n = ident; *n; n++)
296                 *t++ = *n;
297         *t++ = '@';
298         for(char* n = host; *n; n++)
299                 *t++ = *n;
300         *t = 0;
301         return fresult;
302 }
303
304 bool userrec::IsInvited(irc::string &channel)
305 {
306         for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
307         {
308                 irc::string compare = i->channel;
309                 
310                 if (compare == channel)
311                 {
312                         return true;
313                 }
314         }
315         return false;
316 }
317
318 InvitedList* userrec::GetInviteList()
319 {
320         return &invites;
321 }
322
323 void userrec::InviteTo(irc::string &channel)
324 {
325         Invited i;
326         i.channel = channel;
327         invites.push_back(i);
328 }
329
330 void userrec::RemoveInvite(irc::string &channel)
331 {
332         log(DEBUG,"Removing invites");
333         
334         if (invites.size())
335         {
336                 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
337                 {
338                         irc::string compare = i->channel;
339                         
340                         if (compare == channel)
341                         {
342                                 invites.erase(i);
343                                 return;
344                         }
345                 }
346         }
347 }
348
349 bool userrec::HasPermission(const std::string &command)
350 {
351         char* mycmd;
352         char* savept;
353         char* savept2;
354         
355         /*
356          * users on remote servers can completely bypass all permissions based checks.
357          * This prevents desyncs when one server has different type/class tags to another.
358          * That having been said, this does open things up to the possibility of source changes
359          * allowing remote kills, etc - but if they have access to the src, they most likely have
360          * access to the conf - so it's an end to a means either way.
361          */
362         if (!IS_LOCAL(this))
363                 return true;
364         
365         // are they even an oper at all?
366         if (*this->oper)
367         {
368                 opertype_t::iterator iter_opertype = opertypes.find(this->oper);
369                 if (iter_opertype != opertypes.end())
370                 {
371                         char* Classes = strdup(iter_opertype->second);
372                         char* myclass = strtok_r(Classes," ",&savept);
373                         while (myclass)
374                         {
375                                 operclass_t::iterator iter_operclass = operclass.find(myclass);
376                                 if (iter_operclass != operclass.end())
377                                 {
378                                         char* CommandList = strdup(iter_operclass->second);
379                                         mycmd = strtok_r(CommandList," ",&savept2);
380                                         while (mycmd)
381                                         {
382                                                 if ((!strcasecmp(mycmd,command.c_str())) || (*mycmd == '*'))
383                                                 {
384                                                         free(Classes);
385                                                         free(CommandList);
386                                                         return true;
387                                                 }
388                                                 mycmd = strtok_r(NULL," ",&savept2);
389                                         }
390                                         free(CommandList);
391                                 }
392                                 myclass = strtok_r(NULL," ",&savept);
393                         }
394                         free(Classes);
395                 }
396         }
397         return false;
398 }
399
400
401 bool userrec::AddBuffer(const std::string &a)
402 {
403         std::string b = "";
404
405         /* NB: std::string is arsey about \r and \n and tries to translate them
406          * somehow, so we CANNOT use std::string::find() here :(
407          */
408         for (std::string::const_iterator i = a.begin(); i != a.end(); i++)
409         {
410                 if (*i != '\r')
411                         b += *i;
412         }
413
414         if (b.length())
415                 recvq.append(b);
416
417         if (recvq.length() > (unsigned)this->recvqmax)
418         {
419                 this->SetWriteError("RecvQ exceeded");
420                 WriteOpers("*** User %s RecvQ of %d exceeds connect class maximum of %d",this->nick,recvq.length(),this->recvqmax);
421                 return false;
422         }
423
424         return true;
425 }
426
427 bool userrec::BufferIsReady()
428 {
429         return (recvq.find('\n') != std::string::npos);
430 }
431
432 void userrec::ClearBuffer()
433 {
434         recvq = "";
435 }
436
437 std::string userrec::GetBuffer()
438 {
439         if (!recvq.length())
440                 return "";
441
442         /* Strip any leading \r or \n off the string.
443          * Usually there are only one or two of these,
444          * so its is computationally cheap to do.
445          */
446         while ((*recvq.begin() == '\r') || (*recvq.begin() == '\n'))
447                 recvq.erase(recvq.begin());
448
449         for (std::string::iterator x = recvq.begin(); x != recvq.end(); x++)
450         {
451                 /* Find the first complete line, return it as the
452                  * result, and leave the recvq as whats left
453                  */
454                 if (*x == '\n')
455                 {
456                         std::string ret = std::string(recvq.begin(), x);
457                         recvq.erase(recvq.begin(), x + 1);
458                         return ret;
459                 }
460         }
461         return "";
462 }
463
464 void userrec::AddWriteBuf(const std::string &data)
465 {
466         if (*this->GetWriteError())
467                 return;
468         
469         if (sendq.length() + data.length() > (unsigned)this->sendqmax)
470         {
471                 /*
472                  * Fix by brain - Set the error text BEFORE calling writeopers, because
473                  * if we dont it'll recursively  call here over and over again trying
474                  * to repeatedly add the text to the sendq!
475                  */
476                 this->SetWriteError("SendQ exceeded");
477                 WriteOpers("*** User %s SendQ of %d exceeds connect class maximum of %d",this->nick,sendq.length() + data.length(),this->sendqmax);
478                 return;
479         }
480         
481         if (data.length() > 512)
482         {
483                 std::string newdata(data);
484                 newdata.resize(510);
485                 newdata.append("\r\n");
486                 sendq.append(newdata);
487         }
488         else
489         {
490                 sendq.append(data);
491         }
492 }
493
494 // send AS MUCH OF THE USERS SENDQ as we are able to (might not be all of it)
495 void userrec::FlushWriteBuf()
496 {
497         if ((sendq.length()) && (this->fd != FD_MAGIC_NUMBER))
498         {
499                 const char* tb = this->sendq.c_str();
500                 int n_sent = write(this->fd,tb,this->sendq.length());
501                 if (n_sent == -1)
502                 {
503                         if (errno != EAGAIN)
504                                 this->SetWriteError(strerror(errno));
505                 }
506                 else
507                 {
508                         // advance the queue
509                         tb += n_sent;
510                         this->sendq = tb;
511                         // update the user's stats counters
512                         this->bytes_out += n_sent;
513                         this->cmds_out++;
514                 }
515         }
516 }
517
518 void userrec::SetWriteError(const std::string &error)
519 {
520         // don't try to set the error twice, its already set take the first string.
521         if (!this->WriteError.length())
522         {
523                 log(DEBUG,"Setting error string for %s to '%s'",this->nick,error.c_str());
524                 this->WriteError = error;
525         }
526 }
527
528 const char* userrec::GetWriteError()
529 {
530         return this->WriteError.c_str();
531 }
532
533 void AddOper(userrec* user)
534 {
535         log(DEBUG,"Oper added to optimization list");
536         all_opers.push_back(user);
537 }
538
539 void DeleteOper(userrec* user)
540 {
541         for (std::vector<userrec*>::iterator a = all_opers.begin(); a < all_opers.end(); a++)
542         {
543                 if (*a == user)
544                 {
545                         log(DEBUG,"Oper removed from optimization list");
546                         all_opers.erase(a);
547                         return;
548                 }
549         }
550 }
551
552 void kill_link(userrec *user,const char* r)
553 {
554         user_hash::iterator iter = clientlist.find(user->nick);
555
556 /*
557  * I'm pretty sure returning here is causing a desync when part of the net thinks a user is gone,
558  * and another part doesn't. We want to broadcast the quit/kill before bailing so the net stays in sync.
559  *
560  * I can't imagine this blowing up, so I'm commenting it out. We still check
561  * before playing with a bad iterator below in our if(). DISCUSS THIS BEFORE YOU DO ANYTHING. --w00t
562  *
563  *      if (iter == clientlist.end())
564  *              return;
565  */
566
567         char reason[MAXBUF];
568
569         strlcpy(reason,r,MAXQUIT-1);
570         log(DEBUG,"kill_link: %s %d '%s'",user->nick,user->fd,reason);
571         
572         if (IS_LOCAL(user))
573                 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
574
575         if (user->registered == 7)
576         {
577                 purge_empty_chans(user);
578                 FOREACH_MOD(I_OnUserQuit,OnUserQuit(user,reason));
579                 WriteCommonExcept(user,"QUIT :%s",reason);
580         }
581
582         if (IS_LOCAL(user))
583                 user->FlushWriteBuf();
584
585         FOREACH_MOD(I_OnUserDisconnect,OnUserDisconnect(user));
586
587         if (IS_LOCAL(user))
588         {
589                 if (Config->GetIOHook(user->port))
590                 {
591                         try
592                         {
593                                 Config->GetIOHook(user->port)->OnRawSocketClose(user->fd);
594                         }
595                         catch (ModuleException& modexcept)
596                         {
597                                 log(DEBUG,"Module exception cought: %s",modexcept.GetReason());
598                         }
599                 }
600                 
601                 ServerInstance->SE->DelFd(user->fd);
602                 user->CloseSocket();
603         }
604
605         /*
606          * this must come before the WriteOpers so that it doesnt try to fill their buffer with anything
607          * if they were an oper with +s.
608          *
609          * XXX -
610          * In the current implementation, we only show local quits, as we only show local connects. With 
611          * the proposed implmentation of snomasks however, this will likely change in the (near?) future.
612          */
613         if (user->registered == 7)
614         {
615                 if (IS_LOCAL(user))
616                         WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
617                 AddWhoWas(user);
618         }
619
620         if (iter != clientlist.end())
621         {
622                 log(DEBUG,"deleting user hash value %lx",(unsigned long)user);
623                 if (IS_LOCAL(user))
624                 {
625                         fd_ref_table[user->fd] = NULL;
626                         if (find(local_users.begin(),local_users.end(),user) != local_users.end())
627                         {
628                                 local_users.erase(find(local_users.begin(),local_users.end(),user));
629                                 log(DEBUG,"Delete local user");
630                         }
631                 }
632                 clientlist.erase(iter);
633                 DELETE(user);
634         }
635 }
636
637 WhoWasGroup::WhoWasGroup(userrec* user) : host(NULL), dhost(NULL), ident(NULL), server(NULL), gecos(NULL), signon(user->signon)
638 {
639         this->host = strdup(user->host);
640         this->dhost = strdup(user->dhost);
641         this->ident = strdup(user->ident);
642         this->server = user->server;
643         this->gecos = strdup(user->fullname);
644 }
645
646 WhoWasGroup::~WhoWasGroup()
647 {
648         if (host)
649                 free(host);
650         if (dhost)
651                 free(dhost);
652         if (ident)
653                 free(ident);
654         if (gecos)
655                 free(gecos);
656 }
657
658 /* adds or updates an entry in the whowas list */
659 void AddWhoWas(userrec* u)
660 {
661         whowas_users::iterator iter = whowas.find(u->nick);
662         
663         if (iter == whowas.end())
664         {
665                 whowas_set* n = new whowas_set;
666                 WhoWasGroup *a = new WhoWasGroup(u);
667                 n->push_back(a);
668                 whowas[u->nick] = n;
669         }
670         else
671         {
672                 whowas_set* group = (whowas_set*)iter->second;
673                 
674                 if (group->size() > 10)
675                 {
676                         WhoWasGroup *a = (WhoWasGroup*)*(group->begin());
677                         DELETE(a);
678                         group->pop_front();
679                 }
680                 
681                 WhoWasGroup *a = new WhoWasGroup(u);
682                 group->push_back(a);
683         }
684 }
685
686 /* every hour, run this function which removes all entries over 3 days */
687 void MaintainWhoWas(time_t TIME)
688 {
689         for (whowas_users::iterator iter = whowas.begin(); iter != whowas.end(); iter++)
690         {
691                 whowas_set* n = (whowas_set*)iter->second;
692                 if (n->size())
693                 {
694                         while ((n->begin() != n->end()) && ((*n->begin())->signon < TIME - 259200)) // 3 days
695                         {
696                                 WhoWasGroup *a = *(n->begin());
697                                 DELETE(a);
698                                 n->erase(n->begin());
699                         }
700                 }
701         }
702 }
703
704 /* add a client connection to the sockets list */
705 void AddClient(int socket, int port, bool iscached, in_addr ip4)
706 {
707         std::string tempnick = ConvToStr(socket) + "-unknown";
708         user_hash::iterator iter = clientlist.find(tempnick);
709         const char *ipaddr = inet_ntoa(ip4);
710         userrec* _new;
711         int j = 0;
712
713         /*
714          * fix by brain.
715          * as these nicknames are 'RFC impossible', we can be sure nobody is going to be
716          * using one as a registered connection. As they are per fd, we can also safely assume
717          * that we wont have collisions. Therefore, if the nick exists in the list, its only
718          * used by a dead socket, erase the iterator so that the new client may reclaim it.
719          * this was probably the cause of 'server ignores me when i hammer it with reconnects'
720          * issue in earlier alphas/betas
721          */
722         if (iter != clientlist.end())
723         {
724                 userrec* goner = iter->second;
725                 DELETE(goner);
726                 clientlist.erase(iter);
727         }
728
729         log(DEBUG,"AddClient: %d %d %s",socket,port,ipaddr);
730         
731         _new = new userrec();
732         clientlist[tempnick] = _new;
733         _new->fd = socket;
734         strlcpy(_new->nick,tempnick.c_str(),NICKMAX-1);
735
736         /* Smarter than your average bear^H^H^H^Hset of strlcpys. */
737         for (const char* temp = ipaddr; *temp && j < 64; temp++, j++)
738                 _new->dhost[j] = _new->host[j] = *temp;
739         _new->dhost[j] = _new->host[j] = 0;
740
741         _new->server = FindServerNamePtr(Config->ServerName);
742         /* We don't need range checking here, we KNOW 'unknown\0' will fit into the ident field. */
743         strcpy(_new->ident, "unknown");
744
745         _new->registered = 0;
746         _new->signon = TIME + Config->dns_timeout;
747         _new->lastping = 1;
748         _new->ip4 = ip4;
749         _new->port = port;
750
751         // set the registration timeout for this user
752         unsigned long class_regtimeout = 90;
753         int class_flood = 0;
754         long class_threshold = 5;
755         long class_sqmax = 262144;      // 256kb
756         long class_rqmax = 4096;        // 4k
757
758         for (ClassVector::iterator i = Config->Classes.begin(); i != Config->Classes.end(); i++)
759         {
760                 if ((i->type == CC_ALLOW) && (match(ipaddr,i->host.c_str())))
761                 {
762                         class_regtimeout = (unsigned long)i->registration_timeout;
763                         class_flood = i->flood;
764                         _new->pingmax = i->pingtime;
765                         class_threshold = i->threshold;
766                         class_sqmax = i->sendqmax;
767                         class_rqmax = i->recvqmax;
768                         break;
769                 }
770         }
771
772         _new->nping = TIME + _new->pingmax + Config->dns_timeout;
773         _new->timeout = TIME+class_regtimeout;
774         _new->flood = class_flood;
775         _new->threshold = class_threshold;
776         _new->sendqmax = class_sqmax;
777         _new->recvqmax = class_rqmax;
778
779         fd_ref_table[socket] = _new;
780         local_users.push_back(_new);
781
782         if (local_users.size() > Config->SoftLimit)
783         {
784                 kill_link(_new,"No more connections allowed");
785                 return;
786         }
787
788         if (local_users.size() >= MAXCLIENTS)
789         {
790                 kill_link(_new,"No more connections allowed");
791                 return;
792         }
793
794         /*
795          * XXX -
796          * this is done as a safety check to keep the file descriptors within range of fd_ref_table.
797          * its a pretty big but for the moment valid assumption:
798          * file descriptors are handed out starting at 0, and are recycled as theyre freed.
799          * therefore if there is ever an fd over 65535, 65536 clients must be connected to the
800          * irc server at once (or the irc server otherwise initiating this many connections, files etc)
801          * which for the time being is a physical impossibility (even the largest networks dont have more
802          * than about 10,000 users on ONE server!)
803          */
804         if ((unsigned)socket >= MAX_DESCRIPTORS)
805         {
806                 kill_link(_new,"Server is full");
807                 return;
808         }
809         char* e = matches_exception(ipaddr);
810         if (!e)
811         {
812                 char* r = matches_zline(ipaddr);
813                 if (r)
814                 {
815                         char reason[MAXBUF];
816                         snprintf(reason,MAXBUF,"Z-Lined: %s",r);
817                         kill_link(_new,reason);
818                         return;
819                 }
820         }
821
822         if (socket > -1)
823         {
824                 ServerInstance->SE->AddFd(socket,true,X_ESTAB_CLIENT);
825         }
826
827         WriteServ(_new->fd,"NOTICE Auth :*** Looking up your hostname...");
828 }
829
830 long FindMatchingGlobal(userrec* user)
831 {
832         long x = 0;
833         for (user_hash::const_iterator a = clientlist.begin(); a != clientlist.end(); a++)
834         {
835                 if (a->second->ip4.s_addr == user->ip4.s_addr)
836                         x++;
837         }
838         return x;
839 }
840
841 long FindMatchingLocal(userrec* user)
842 {
843         long x = 0;
844         for (std::vector<userrec*>::const_iterator a = local_users.begin(); a != local_users.end(); a++)
845         {
846                 userrec* comp = (userrec*)(*a);
847                 if (comp->ip4.s_addr == user->ip4.s_addr)
848                         x++;
849         }
850         return x;
851 }
852
853 void FullConnectUser(userrec* user, CullList* Goners)
854 {
855         ServerInstance->stats->statsConnects++;
856         user->idle_lastmsg = TIME;
857         log(DEBUG,"ConnectUser: %s",user->nick);
858
859         ConnectClass a = GetClass(user);
860         
861         if (a.type == CC_DENY)
862         {
863                 Goners->AddItem(user,"Unauthorised connection");
864                 return;
865         }
866         
867         if ((*(a.pass.c_str())) && (!user->haspassed))
868         {
869                 Goners->AddItem(user,"Invalid password");
870                 return;
871         }
872         
873         if (FindMatchingLocal(user) > a.maxlocal)
874         {
875                 Goners->AddItem(user,"No more connections allowed from your host via this connect class (local)");
876                 WriteOpers("*** WARNING: maximum LOCAL connections (%ld) exceeded for IP %s",a.maxlocal,inet_ntoa(user->ip4));
877                 return;
878         }
879         else if (FindMatchingGlobal(user) > a.maxglobal)
880         {
881                 Goners->AddItem(user,"No more connections allowed from your host via this connect class (global)");
882                 WriteOpers("*** WARNING: maximum GLOBAL connections (%ld) exceeded for IP %s",a.maxglobal,inet_ntoa(user->ip4));
883                 return;
884         }
885
886         char match_against[MAXBUF];
887         snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
888         char* e = matches_exception(match_against);
889         
890         if (!e)
891         {
892                 char* r = matches_gline(match_against);
893                 
894                 if (r)
895                 {
896                         char reason[MAXBUF];
897                         snprintf(reason,MAXBUF,"G-Lined: %s",r);
898                         Goners->AddItem(user,reason);
899                         return;
900                 }
901                 
902                 r = matches_kline(match_against);
903                 
904                 if (r)
905                 {
906                         char reason[MAXBUF];
907                         snprintf(reason,MAXBUF,"K-Lined: %s",r);
908                         Goners->AddItem(user,reason);
909                         return;
910                 }
911         }
912
913
914         WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Config->Network);
915         WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Config->Network,user->nick,user->ident,user->host);
916         WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,Config->ServerName,VERSION);
917         WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
918         WriteServ(user->fd,"004 %s %s %s iowghrasxRVSCWBG lvhopsmntikrcaqbegIOLQRSKVHGCNT vhobeIaqglk",user->nick,Config->ServerName,VERSION);
919         
920         // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
921         // so i'd better split it :)
922         std::stringstream out(Config->data005);
923         std::string token = "";
924         std::string line5 = "";
925         int token_counter = 0;
926         
927         while (!out.eof())
928         {
929                 out >> token;
930                 line5 = line5 + token + " ";
931                 token_counter++;
932                 
933                 if ((token_counter >= 13) || (out.eof() == true))
934                 {
935                         WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
936                         line5 = "";
937                         token_counter = 0;
938                 }
939         }
940         
941         ShowMOTD(user);
942
943         /*
944          * fix 3 by brain, move registered = 7 below these so that spurious modes and host
945          * changes dont go out onto the network and produce 'fake direction'.
946          */
947         FOREACH_MOD(I_OnUserConnect,OnUserConnect(user));
948         FOREACH_MOD(I_OnGlobalConnect,OnGlobalConnect(user));
949         user->registered = 7;
950         WriteOpers("*** Client connecting on port %lu: %s!%s@%s [%s]",(unsigned long)user->port,user->nick,user->ident,user->host,inet_ntoa(user->ip4));
951 }
952
953 /** ReHashNick()
954  * re-allocates a nick in the user_hash after they change nicknames,
955  * returns a pointer to the new user as it may have moved
956  */
957 userrec* ReHashNick(const char* Old, const char* New)
958 {
959         //user_hash::iterator newnick;
960         user_hash::iterator oldnick = clientlist.find(Old);
961
962         log(DEBUG,"ReHashNick: %s %s",Old,New);
963
964         if (!strcasecmp(Old,New))
965         {
966                 log(DEBUG,"old nick is new nick, skipping");
967                 return oldnick->second;
968         }
969
970         if (oldnick == clientlist.end())
971                 return NULL; /* doesnt exist */
972
973         log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
974
975         userrec* olduser = oldnick->second;
976         clientlist[New] = olduser;
977         clientlist.erase(oldnick);
978
979         log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
980
981         return clientlist[New];
982 }
983
984 void force_nickchange(userrec* user,const char* newnick)
985 {
986         char nick[MAXBUF];
987         int MOD_RESULT = 0;
988
989         *nick = 0;
990
991         FOREACH_RESULT(I_OnUserPreNick,OnUserPreNick(user,newnick));
992         
993         if (MOD_RESULT)
994         {
995                 ServerInstance->stats->statsCollisions++;
996                 kill_link(user,"Nickname collision");
997                 return;
998         }
999         
1000         if (matches_qline(newnick))
1001         {
1002                 ServerInstance->stats->statsCollisions++;
1003                 kill_link(user,"Nickname collision");
1004                 return;
1005         }
1006
1007         if (user)
1008         {
1009                 if (newnick)
1010                 {
1011                         strlcpy(nick,newnick,MAXBUF-1);
1012                 }
1013
1014                 if (user->registered == 7)
1015                 {
1016                         const char* pars[1];
1017                         pars[0] = nick;
1018                         std::string cmd = "NICK";
1019
1020                         ServerInstance->Parser->CallHandler(cmd,pars,1,user);
1021                 }
1022         }
1023 }