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