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