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