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