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