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