]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/users.cpp
fbd4820b44b2abb14f2fed99178c1d06ba0745ac
[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         return false;
310 }
311
312 InvitedList* userrec::GetInviteList()
313 {
314         return &invites;
315 }
316
317 void userrec::InviteTo(irc::string &channel)
318 {
319         Invited i;
320         i.channel = channel;
321         invites.push_back(i);
322 }
323
324 void userrec::RemoveInvite(irc::string &channel)
325 {
326         log(DEBUG,"Removing invites");
327         
328         if (invites.size())
329         {
330                 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
331                 {
332                         irc::string compare = i->channel;
333                         
334                         if (compare == channel)
335                         {
336                                 invites.erase(i);
337                                 return;
338                         }
339                 }
340         }
341 }
342
343 bool userrec::HasPermission(const std::string &command)
344 {
345         char* mycmd;
346         char* savept;
347         char* savept2;
348         
349         /*
350          * users on remote servers can completely bypass all permissions based checks.
351          * This prevents desyncs when one server has different type/class tags to another.
352          * That having been said, this does open things up to the possibility of source changes
353          * allowing remote kills, etc - but if they have access to the src, they most likely have
354          * access to the conf - so it's an end to a means either way.
355          */
356         if (!IS_LOCAL(this))
357                 return true;
358         
359         // are they even an oper at all?
360         if (*this->oper)
361         {
362                 opertype_t::iterator iter_opertype = opertypes.find(this->oper);
363                 if (iter_opertype != opertypes.end())
364                 {
365                         char* Classes = strdup(iter_opertype->second);
366                         char* myclass = strtok_r(Classes," ",&savept);
367                         while (myclass)
368                         {
369                                 operclass_t::iterator iter_operclass = operclass.find(myclass);
370                                 if (iter_operclass != operclass.end())
371                                 {
372                                         char* CommandList = strdup(iter_operclass->second);
373                                         mycmd = strtok_r(CommandList," ",&savept2);
374                                         while (mycmd)
375                                         {
376                                                 if ((!strcasecmp(mycmd,command.c_str())) || (*mycmd == '*'))
377                                                 {
378                                                         free(Classes);
379                                                         free(CommandList);
380                                                         return true;
381                                                 }
382                                                 mycmd = strtok_r(NULL," ",&savept2);
383                                         }
384                                         free(CommandList);
385                                 }
386                                 myclass = strtok_r(NULL," ",&savept);
387                         }
388                         free(Classes);
389                 }
390         }
391         return false;
392 }
393
394
395 bool userrec::AddBuffer(const std::string &a)
396 {
397         std::string b = "";
398
399         /* NB: std::string is arsey about \r and \n and tries to translate them
400          * somehow, so we CANNOT use std::string::find() here :(
401          */
402         for (std::string::const_iterator i = a.begin(); i != a.end(); i++)
403         {
404                 if (*i != '\r')
405                         b += *i;
406         }
407
408         if (b.length())
409                 recvq.append(b);
410
411         if (recvq.length() > (unsigned)this->recvqmax)
412         {
413                 this->SetWriteError("RecvQ exceeded");
414                 WriteOpers("*** User %s RecvQ of %d exceeds connect class maximum of %d",this->nick,recvq.length(),this->recvqmax);
415                 return false;
416         }
417
418         return true;
419 }
420
421 bool userrec::BufferIsReady()
422 {
423         return (recvq.find('\n') != std::string::npos);
424 }
425
426 void userrec::ClearBuffer()
427 {
428         recvq = "";
429 }
430
431 std::string userrec::GetBuffer()
432 {
433         if (!recvq.length())
434                 return "";
435
436         /* Strip any leading \r or \n off the string.
437          * Usually there are only one or two of these,
438          * so its is computationally cheap to do.
439          */
440         while ((*recvq.begin() == '\r') || (*recvq.begin() == '\n'))
441                 recvq.erase(recvq.begin());
442
443         for (std::string::iterator x = recvq.begin(); x != recvq.end(); x++)
444         {
445                 /* Find the first complete line, return it as the
446                  * result, and leave the recvq as whats left
447                  */
448                 if (*x == '\n')
449                 {
450                         std::string ret = std::string(recvq.begin(), x);
451                         recvq.erase(recvq.begin(), x + 1);
452                         return ret;
453                 }
454         }
455         return "";
456 }
457
458 void userrec::AddWriteBuf(const std::string &data)
459 {
460         if (*this->GetWriteError())
461                 return;
462         
463         if (sendq.length() + data.length() > (unsigned)this->sendqmax)
464         {
465                 /*
466                  * Fix by brain - Set the error text BEFORE calling writeopers, because
467                  * if we dont it'll recursively  call here over and over again trying
468                  * to repeatedly add the text to the sendq!
469                  */
470                 this->SetWriteError("SendQ exceeded");
471                 WriteOpers("*** User %s SendQ of %d exceeds connect class maximum of %d",this->nick,sendq.length() + data.length(),this->sendqmax);
472                 return;
473         }
474         
475         sendq.append(data);
476 }
477
478 // send AS MUCH OF THE USERS SENDQ as we are able to (might not be all of it)
479 void userrec::FlushWriteBuf()
480 {
481         if ((sendq.length()) && (this->fd != FD_MAGIC_NUMBER))
482         {
483                 const char* tb = this->sendq.c_str();
484                 int n_sent = write(this->fd,tb,this->sendq.length());
485                 if (n_sent == -1)
486                 {
487                         if (errno != EAGAIN)
488                                 this->SetWriteError(strerror(errno));
489                 }
490                 else
491                 {
492                         // advance the queue
493                         tb += n_sent;
494                         this->sendq = tb;
495                         // update the user's stats counters
496                         this->bytes_out += n_sent;
497                         this->cmds_out++;
498                 }
499         }
500 }
501
502 void userrec::SetWriteError(const std::string &error)
503 {
504         log(DEBUG,"Setting error string for %s to '%s'",this->nick,error.c_str());
505         // don't try to set the error twice, its already set take the first string.
506         if (!this->WriteError.length())
507                 this->WriteError = error;
508 }
509
510 const char* userrec::GetWriteError()
511 {
512         return this->WriteError.c_str();
513 }
514
515 void AddOper(userrec* user)
516 {
517         log(DEBUG,"Oper added to optimization list");
518         all_opers.push_back(user);
519 }
520
521 void DeleteOper(userrec* user)
522 {
523         for (std::vector<userrec*>::iterator a = all_opers.begin(); a < all_opers.end(); a++)
524         {
525                 if (*a == user)
526                 {
527                         log(DEBUG,"Oper removed from optimization list");
528                         all_opers.erase(a);
529                         return;
530                 }
531         }
532 }
533
534 void kill_link(userrec *user,const char* r)
535 {
536         user_hash::iterator iter = clientlist.find(user->nick);
537
538 /*
539  * I'm pretty sure returning here is causing a desync when part of the net thinks a user is gone,
540  * and another part doesn't. We want to broadcast the quit/kill before bailing so the net stays in sync.
541  *
542  * I can't imagine this blowing up, so I'm commenting it out. We still check
543  * before playing with a bad iterator below in our if(). DISCUSS THIS BEFORE YOU DO ANYTHING. --w00t
544  *
545  *      if (iter == clientlist.end())
546  *              return;
547  */
548
549         char reason[MAXBUF];
550
551         strlcpy(reason,r,MAXQUIT-1);
552         log(DEBUG,"kill_link: %s %d '%s'",user->nick,user->fd,reason);
553         
554         if (IS_LOCAL(user))
555                 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
556
557         if (user->registered == 7)
558         {
559                 purge_empty_chans(user);
560                 FOREACH_MOD(I_OnUserQuit,OnUserQuit(user,reason));
561                 WriteCommonExcept(user,"QUIT :%s",reason);
562         }
563
564         if (IS_LOCAL(user))
565                 user->FlushWriteBuf();
566
567         FOREACH_MOD(I_OnUserDisconnect,OnUserDisconnect(user));
568
569         if (IS_LOCAL(user))
570         {
571                 if (Config->GetIOHook(user->port))
572                 {
573                         try
574                         {
575                                 Config->GetIOHook(user->port)->OnRawSocketClose(user->fd);
576                         }
577                         catch (ModuleException& modexcept)
578                         {
579                                 log(DEBUG,"Module exception cought: %s",modexcept.GetReason());
580                         }
581                 }
582                 
583                 ServerInstance->SE->DelFd(user->fd);
584                 user->CloseSocket();
585         }
586
587         /*
588          * this must come before the WriteOpers so that it doesnt try to fill their buffer with anything
589          * if they were an oper with +s.
590          *
591          * XXX -
592          * In the current implementation, we only show local quits, as we only show local connects. With 
593          * the proposed implmentation of snomasks however, this will likely change in the (near?) future.
594          */
595         if (user->registered == 7)
596         {
597                 if (IS_LOCAL(user))
598                         WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
599                 AddWhoWas(user);
600         }
601
602         if (iter != clientlist.end())
603         {
604                 log(DEBUG,"deleting user hash value %lx",(unsigned long)user);
605                 if (IS_LOCAL(user))
606                 {
607                         fd_ref_table[user->fd] = NULL;
608                         if (find(local_users.begin(),local_users.end(),user) != local_users.end())
609                         {
610                                 local_users.erase(find(local_users.begin(),local_users.end(),user));
611                                 log(DEBUG,"Delete local user");
612                         }
613                 }
614                 clientlist.erase(iter);
615                 DELETE(user);
616         }
617 }
618
619 WhoWasGroup::WhoWasGroup(userrec* user) : host(NULL), dhost(NULL), ident(NULL), server(NULL), gecos(NULL), signon(user->signon)
620 {
621         this->host = strdup(user->host);
622         this->dhost = strdup(user->dhost);
623         this->ident = strdup(user->ident);
624         this->server = user->server;
625         this->gecos = strdup(user->fullname);
626 }
627
628 WhoWasGroup::~WhoWasGroup()
629 {
630         if (host)
631                 free(host);
632         if (dhost)
633                 free(dhost);
634         if (ident)
635                 free(ident);
636         if (gecos)
637                 free(gecos);
638 }
639
640 /* adds or updates an entry in the whowas list */
641 void AddWhoWas(userrec* u)
642 {
643         whowas_users::iterator iter = whowas.find(u->nick);
644         
645         if (iter == whowas.end())
646         {
647                 whowas_set* n = new whowas_set;
648                 WhoWasGroup *a = new WhoWasGroup(u);
649                 n->push_back(a);
650                 whowas[u->nick] = n;
651         }
652         else
653         {
654                 whowas_set* group = (whowas_set*)iter->second;
655                 
656                 if (group->size() > 10)
657                 {
658                         WhoWasGroup *a = (WhoWasGroup*)*(group->begin());
659                         DELETE(a);
660                         group->pop_front();
661                 }
662                 
663                 WhoWasGroup *a = new WhoWasGroup(u);
664                 group->push_back(a);
665         }
666 }
667
668 /* every hour, run this function which removes all entries over 3 days */
669 void MaintainWhoWas(time_t TIME)
670 {
671         for (whowas_users::iterator iter = whowas.begin(); iter != whowas.end(); iter++)
672         {
673                 whowas_set* n = (whowas_set*)iter->second;
674                 if (n->size())
675                 {
676                         while ((n->begin() != n->end()) && ((*n->begin())->signon < TIME - 259200)) // 3 days
677                         {
678                                 WhoWasGroup *a = *(n->begin());
679                                 DELETE(a);
680                                 n->erase(n->begin());
681                         }
682                 }
683         }
684 }
685
686 /* add a client connection to the sockets list */
687 void AddClient(int socket, int port, bool iscached, in_addr ip4)
688 {
689         std::string tempnick = ConvToStr(socket) + "-unknown";
690         user_hash::iterator iter = clientlist.find(tempnick);
691         const char *ipaddr = inet_ntoa(ip4);
692         userrec* _new;
693         int j = 0;
694
695         /*
696          * fix by brain.
697          * as these nicknames are 'RFC impossible', we can be sure nobody is going to be
698          * using one as a registered connection. As they are per fd, we can also safely assume
699          * that we wont have collisions. Therefore, if the nick exists in the list, its only
700          * used by a dead socket, erase the iterator so that the new client may reclaim it.
701          * this was probably the cause of 'server ignores me when i hammer it with reconnects'
702          * issue in earlier alphas/betas
703          */
704         if (iter != clientlist.end())
705         {
706                 userrec* goner = iter->second;
707                 DELETE(goner);
708                 clientlist.erase(iter);
709         }
710
711         log(DEBUG,"AddClient: %d %d %s",socket,port,ipaddr);
712         
713         _new = new userrec();
714         clientlist[tempnick] = _new;
715         _new->fd = socket;
716         strlcpy(_new->nick,tempnick.c_str(),NICKMAX-1);
717
718         /* Smarter than your average bear^H^H^H^Hset of strlcpys. */
719         for (const char* temp = ipaddr; *temp && j < 64; temp++, j++)
720                 _new->dhost[j] = _new->host[j] = *temp;
721         _new->dhost[j] = _new->host[j] = 0;
722
723         _new->server = FindServerNamePtr(Config->ServerName);
724         /* We don't need range checking here, we KNOW 'unknown\0' will fit into the ident field. */
725         strcpy(_new->ident, "unknown");
726
727         _new->registered = 0;
728         _new->signon = TIME + Config->dns_timeout;
729         _new->lastping = 1;
730         _new->ip4 = ip4;
731         _new->port = port;
732
733         // set the registration timeout for this user
734         unsigned long class_regtimeout = 90;
735         int class_flood = 0;
736         long class_threshold = 5;
737         long class_sqmax = 262144;      // 256kb
738         long class_rqmax = 4096;        // 4k
739
740         for (ClassVector::iterator i = Config->Classes.begin(); i != Config->Classes.end(); i++)
741         {
742                 if ((i->type == CC_ALLOW) && (match(ipaddr,i->host.c_str())))
743                 {
744                         class_regtimeout = (unsigned long)i->registration_timeout;
745                         class_flood = i->flood;
746                         _new->pingmax = i->pingtime;
747                         class_threshold = i->threshold;
748                         class_sqmax = i->sendqmax;
749                         class_rqmax = i->recvqmax;
750                         break;
751                 }
752         }
753
754         _new->nping = TIME + _new->pingmax + Config->dns_timeout;
755         _new->timeout = TIME+class_regtimeout;
756         _new->flood = class_flood;
757         _new->threshold = class_threshold;
758         _new->sendqmax = class_sqmax;
759         _new->recvqmax = class_rqmax;
760
761         fd_ref_table[socket] = _new;
762         local_users.push_back(_new);
763
764         if (local_users.size() > Config->SoftLimit)
765         {
766                 kill_link(_new,"No more connections allowed");
767                 return;
768         }
769
770         if (local_users.size() >= MAXCLIENTS)
771         {
772                 kill_link(_new,"No more connections allowed");
773                 return;
774         }
775
776         /*
777          * XXX -
778          * this is done as a safety check to keep the file descriptors within range of fd_ref_table.
779          * its a pretty big but for the moment valid assumption:
780          * file descriptors are handed out starting at 0, and are recycled as theyre freed.
781          * therefore if there is ever an fd over 65535, 65536 clients must be connected to the
782          * irc server at once (or the irc server otherwise initiating this many connections, files etc)
783          * which for the time being is a physical impossibility (even the largest networks dont have more
784          * than about 10,000 users on ONE server!)
785          */
786         if ((unsigned)socket >= MAX_DESCRIPTORS)
787         {
788                 kill_link(_new,"Server is full");
789                 return;
790         }
791         char* e = matches_exception(ipaddr);
792         if (!e)
793         {
794                 char* r = matches_zline(ipaddr);
795                 if (r)
796                 {
797                         char reason[MAXBUF];
798                         snprintf(reason,MAXBUF,"Z-Lined: %s",r);
799                         kill_link(_new,reason);
800                         return;
801                 }
802         }
803
804         if (socket > -1)
805         {
806                 ServerInstance->SE->AddFd(socket,true,X_ESTAB_CLIENT);
807         }
808
809         WriteServ(_new->fd,"NOTICE Auth :*** Looking up your hostname...");
810 }
811
812 long FindMatchingGlobal(userrec* user)
813 {
814         long x = 0;
815         for (user_hash::const_iterator a = clientlist.begin(); a != clientlist.end(); a++)
816         {
817                 if (a->second->ip4.s_addr == user->ip4.s_addr)
818                         x++;
819         }
820         return x;
821 }
822
823 long FindMatchingLocal(userrec* user)
824 {
825         long x = 0;
826         for (std::vector<userrec*>::const_iterator a = local_users.begin(); a != local_users.end(); a++)
827         {
828                 userrec* comp = (userrec*)(*a);
829                 if (comp->ip4.s_addr == user->ip4.s_addr)
830                         x++;
831         }
832         return x;
833 }
834
835 void FullConnectUser(userrec* user, CullList* Goners)
836 {
837         ServerInstance->stats->statsConnects++;
838         user->idle_lastmsg = TIME;
839         log(DEBUG,"ConnectUser: %s",user->nick);
840
841         ConnectClass a = GetClass(user);
842         
843         if (a.type == CC_DENY)
844         {
845                 Goners->AddItem(user,"Unauthorised connection");
846                 return;
847         }
848         
849         if ((*(a.pass.c_str())) && (!user->haspassed))
850         {
851                 Goners->AddItem(user,"Invalid password");
852                 return;
853         }
854         
855         if (FindMatchingLocal(user) > a.maxlocal)
856         {
857                 Goners->AddItem(user,"No more connections allowed from your host via this connect class (local)");
858                 WriteOpers("*** WARNING: maximum LOCAL connections (%ld) exceeded for IP %s",a.maxlocal,inet_ntoa(user->ip4));
859                 return;
860         }
861         else if (FindMatchingGlobal(user) > a.maxglobal)
862         {
863                 Goners->AddItem(user,"No more connections allowed from your host via this connect class (global)");
864                 WriteOpers("*** WARNING: maximum GLOBAL connections (%ld) exceeded for IP %s",a.maxglobal,inet_ntoa(user->ip4));
865                 return;
866         }
867
868         char match_against[MAXBUF];
869         snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
870         char* e = matches_exception(match_against);
871         
872         if (!e)
873         {
874                 char* r = matches_gline(match_against);
875                 
876                 if (r)
877                 {
878                         char reason[MAXBUF];
879                         snprintf(reason,MAXBUF,"G-Lined: %s",r);
880                         Goners->AddItem(user,reason);
881                         return;
882                 }
883                 
884                 r = matches_kline(match_against);
885                 
886                 if (r)
887                 {
888                         char reason[MAXBUF];
889                         snprintf(reason,MAXBUF,"K-Lined: %s",r);
890                         Goners->AddItem(user,reason);
891                         return;
892                 }
893         }
894
895
896         WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Config->Network);
897         WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Config->Network,user->nick,user->ident,user->host);
898         WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,Config->ServerName,VERSION);
899         WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
900         WriteServ(user->fd,"004 %s %s %s iowghrasxRVSCWBG lvhopsmntikrcaqbegIOLQRSKVHGCNT vhobeIaqglk",user->nick,Config->ServerName,VERSION);
901         
902         // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
903         // so i'd better split it :)
904         std::stringstream out(Config->data005);
905         std::string token = "";
906         std::string line5 = "";
907         int token_counter = 0;
908         
909         while (!out.eof())
910         {
911                 out >> token;
912                 line5 = line5 + token + " ";
913                 token_counter++;
914                 
915                 if ((token_counter >= 13) || (out.eof() == true))
916                 {
917                         WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
918                         line5 = "";
919                         token_counter = 0;
920                 }
921         }
922         
923         ShowMOTD(user);
924
925         /*
926          * fix 3 by brain, move registered = 7 below these so that spurious modes and host
927          * changes dont go out onto the network and produce 'fake direction'.
928          */
929         FOREACH_MOD(I_OnUserConnect,OnUserConnect(user));
930         FOREACH_MOD(I_OnGlobalConnect,OnGlobalConnect(user));
931         user->registered = 7;
932         WriteOpers("*** Client connecting on port %lu: %s!%s@%s [%s]",(unsigned long)user->port,user->nick,user->ident,user->host,inet_ntoa(user->ip4));
933 }
934
935 /** ReHashNick()
936  * re-allocates a nick in the user_hash after they change nicknames,
937  * returns a pointer to the new user as it may have moved
938  */
939 userrec* ReHashNick(const char* Old, const char* New)
940 {
941         //user_hash::iterator newnick;
942         user_hash::iterator oldnick = clientlist.find(Old);
943
944         log(DEBUG,"ReHashNick: %s %s",Old,New);
945
946         if (!strcasecmp(Old,New))
947         {
948                 log(DEBUG,"old nick is new nick, skipping");
949                 return oldnick->second;
950         }
951
952         if (oldnick == clientlist.end())
953                 return NULL; /* doesnt exist */
954
955         log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
956
957         userrec* olduser = oldnick->second;
958         clientlist[New] = olduser;
959         clientlist.erase(oldnick);
960
961         log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
962
963         return clientlist[New];
964 }
965
966 void force_nickchange(userrec* user,const char* newnick)
967 {
968         char nick[MAXBUF];
969         int MOD_RESULT = 0;
970
971         *nick = 0;
972
973         FOREACH_RESULT(I_OnUserPreNick,OnUserPreNick(user,newnick));
974         
975         if (MOD_RESULT)
976         {
977                 ServerInstance->stats->statsCollisions++;
978                 kill_link(user,"Nickname collision");
979                 return;
980         }
981         
982         if (matches_qline(newnick))
983         {
984                 ServerInstance->stats->statsCollisions++;
985                 kill_link(user,"Nickname collision");
986                 return;
987         }
988
989         if (user)
990         {
991                 if (newnick)
992                 {
993                         strlcpy(nick,newnick,MAXBUF-1);
994                 }
995
996                 if (user->registered == 7)
997                 {
998                         const char* pars[1];
999                         pars[0] = nick;
1000                         std::string cmd = "NICK";
1001
1002                         ServerInstance->Parser->CallHandler(cmd,pars,1,user);
1003                 }
1004         }
1005 }