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