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