]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/users.cpp
Extra safety checks
[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(),true)))
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         char u1[1024];
921         char u2[1024];
922         long x = 0;
923         for (user_hash::const_iterator a = clientlist.begin(); a != clientlist.end(); a++)
924         {
925                 /* We have to match ip's as strings - we don't know what protocol
926                  * a remote user may be using
927                  */
928                 if (!strcasecmp(a->second->GetIPString(u1), user->GetIPString(u2)))
929                                 x++;
930         }
931         return x;
932 }
933
934 long FindMatchingLocal(userrec* user)
935 {
936         long x = 0;
937         for (std::vector<userrec*>::const_iterator a = local_users.begin(); a != local_users.end(); a++)
938         {
939                 userrec* comp = *a;
940 #ifdef IPV6
941                 /* I dont think theres any faster way of matching two ipv6 addresses than memcmp */
942                 in6_addr* s1 = &(((sockaddr_in6*)comp->ip)->sin6_addr);
943                 in6_addr* s2 = &(((sockaddr_in6*)user->ip)->sin6_addr);
944                 if (!memcmp(s1->s6_addr, s2->s6_addr, sizeof(in6_addr)))
945                         x++;
946 #else
947                 in_addr* s1 = &((sockaddr_in*)comp->ip)->sin_addr;
948                 in_addr* s2 = &((sockaddr_in*)user->ip)->sin_addr;
949                 if (s1->s_addr == s2->s_addr)
950                         x++;
951 #endif
952         }
953         return x;
954 }
955
956 void FullConnectUser(userrec* user, CullList* Goners)
957 {
958         ServerInstance->stats->statsConnects++;
959         user->idle_lastmsg = TIME;
960         log(DEBUG,"ConnectUser: %s",user->nick);
961
962         ConnectClass a = GetClass(user);
963         
964         if (a.type == CC_DENY)
965         {
966                 Goners->AddItem(user,"Unauthorised connection");
967                 return;
968         }
969         
970         if ((*(a.pass.c_str())) && (!user->haspassed))
971         {
972                 Goners->AddItem(user,"Invalid password");
973                 return;
974         }
975         
976         if (FindMatchingLocal(user) > a.maxlocal)
977         {
978                 Goners->AddItem(user,"No more connections allowed from your host via this connect class (local)");
979                 WriteOpers("*** WARNING: maximum LOCAL connections (%ld) exceeded for IP %s",a.maxlocal,user->GetIPString());
980                 return;
981         }
982         else if (FindMatchingGlobal(user) > a.maxglobal)
983         {
984                 Goners->AddItem(user,"No more connections allowed from your host via this connect class (global)");
985                 WriteOpers("*** WARNING: maximum GLOBAL connections (%ld) exceeded for IP %s",a.maxglobal,user->GetIPString());
986                 return;
987         }
988
989         char match_against[MAXBUF];
990         snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
991         char* e = matches_exception(match_against);
992         
993         if (!e)
994         {
995                 char* r = matches_gline(match_against);
996                 
997                 if (r)
998                 {
999                         char reason[MAXBUF];
1000                         snprintf(reason,MAXBUF,"G-Lined: %s",r);
1001                         Goners->AddItem(user,reason);
1002                         return;
1003                 }
1004                 
1005                 r = matches_kline(match_against);
1006                 
1007                 if (r)
1008                 {
1009                         char reason[MAXBUF];
1010                         snprintf(reason,MAXBUF,"K-Lined: %s",r);
1011                         Goners->AddItem(user,reason);
1012                         return;
1013                 }
1014         }
1015
1016
1017         WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Config->Network);
1018         WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Config->Network,user->nick,user->ident,user->host);
1019         WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,Config->ServerName,VERSION);
1020         WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
1021         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());
1022         
1023         // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
1024         // so i'd better split it :)
1025         std::stringstream out(Config->data005);
1026         std::string token = "";
1027         std::string line5 = "";
1028         int token_counter = 0;
1029         
1030         while (!out.eof())
1031         {
1032                 out >> token;
1033                 line5 = line5 + token + " ";
1034                 token_counter++;
1035                 
1036                 if ((token_counter >= 13) || (out.eof() == true))
1037                 {
1038                         WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
1039                         line5 = "";
1040                         token_counter = 0;
1041                 }
1042         }
1043         
1044         ShowMOTD(user);
1045
1046         /*
1047          * fix 3 by brain, move registered = 7 below these so that spurious modes and host
1048          * changes dont go out onto the network and produce 'fake direction'.
1049          */
1050         FOREACH_MOD(I_OnUserConnect,OnUserConnect(user));
1051         FOREACH_MOD(I_OnGlobalConnect,OnGlobalConnect(user));
1052         user->registered = REG_ALL;
1053         WriteOpers("*** Client connecting on port %d: %s!%s@%s [%s]",user->GetPort(),user->nick,user->ident,user->host,user->GetIPString());
1054 }
1055
1056 /** ReHashNick()
1057  * re-allocates a nick in the user_hash after they change nicknames,
1058  * returns a pointer to the new user as it may have moved
1059  */
1060 userrec* ReHashNick(const char* Old, const char* New)
1061 {
1062         //user_hash::iterator newnick;
1063         user_hash::iterator oldnick = clientlist.find(Old);
1064
1065         log(DEBUG,"ReHashNick: %s %s",Old,New);
1066
1067         if (!strcasecmp(Old,New))
1068         {
1069                 log(DEBUG,"old nick is new nick, skipping");
1070                 return oldnick->second;
1071         }
1072
1073         if (oldnick == clientlist.end())
1074                 return NULL; /* doesnt exist */
1075
1076         log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
1077
1078         userrec* olduser = oldnick->second;
1079         clientlist[New] = olduser;
1080         clientlist.erase(oldnick);
1081
1082         log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
1083
1084         return clientlist[New];
1085 }
1086
1087 void force_nickchange(userrec* user,const char* newnick)
1088 {
1089         char nick[MAXBUF];
1090         int MOD_RESULT = 0;
1091
1092         *nick = 0;
1093
1094         FOREACH_RESULT(I_OnUserPreNick,OnUserPreNick(user,newnick));
1095         
1096         if (MOD_RESULT)
1097         {
1098                 ServerInstance->stats->statsCollisions++;
1099                 kill_link(user,"Nickname collision");
1100                 return;
1101         }
1102         
1103         if (matches_qline(newnick))
1104         {
1105                 ServerInstance->stats->statsCollisions++;
1106                 kill_link(user,"Nickname collision");
1107                 return;
1108         }
1109
1110         if (user)
1111         {
1112                 if (newnick)
1113                 {
1114                         strlcpy(nick,newnick,MAXBUF-1);
1115                 }
1116
1117                 if (user->registered == REG_ALL)
1118                 {
1119                         const char* pars[1];
1120                         pars[0] = nick;
1121                         std::string cmd = "NICK";
1122
1123                         ServerInstance->Parser->CallHandler(cmd,pars,1,user);
1124                 }
1125         }
1126 }
1127
1128 void userrec::SetSockAddr(int protocol_family, const char* ip, int port)
1129 {
1130         switch (protocol_family)
1131         {
1132 #ifdef SUPPORT_IP6LINKS
1133                 case AF_INET6:
1134                 {
1135                         log(DEBUG,"Set inet6 protocol address");
1136                         sockaddr_in6* sin = new sockaddr_in6;
1137                         sin->sin6_family = AF_INET6;
1138                         sin->sin6_port = port;
1139                         inet_pton(AF_INET6, ip, &sin->sin6_addr);
1140                         this->ip = (sockaddr*)sin;
1141                 }
1142                 break;
1143 #endif
1144                 case AF_INET:
1145                 {
1146                         log(DEBUG,"Set inet4 protocol address");
1147                         sockaddr_in* sin = new sockaddr_in;
1148                         sin->sin_family = AF_INET;
1149                         sin->sin_port = port;
1150                         inet_pton(AF_INET, ip, &sin->sin_addr);
1151                         this->ip = (sockaddr*)sin;
1152                 }
1153                 break;
1154                 default:
1155                         log(DEBUG,"Ut oh, I dont know protocol %d to be set on '%s'!", protocol_family, this->nick);
1156                 break;
1157         }
1158 }
1159
1160 int userrec::GetPort()
1161 {
1162         if (this->ip == NULL)
1163                 return 0;
1164
1165         switch (this->GetProtocolFamily())
1166         {
1167 #ifdef SUPPORT_IP6LINKS
1168                 case AF_INET6:
1169                 {
1170                         sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1171                         return sin->sin6_port;
1172                 }
1173                 break;
1174 #endif
1175                 case AF_INET:
1176                 {
1177                         sockaddr_in* sin = (sockaddr_in*)this->ip;
1178                         return sin->sin_port;
1179                 }
1180                 break;
1181                 default:
1182                         log(DEBUG,"Ut oh, '%s' has an unknown protocol family!",this->nick);
1183                 break;
1184         }
1185         return 0;
1186 }
1187
1188 int userrec::GetProtocolFamily()
1189 {
1190         if (this->ip == NULL)
1191                 return 0;
1192
1193         sockaddr_in* sin = (sockaddr_in*)this->ip;
1194         return sin->sin_family;
1195 }
1196
1197 const char* userrec::GetIPString()
1198 {
1199         static char buf[1024];
1200         static char temp[1024];
1201
1202         if (this->ip == NULL)
1203                 return "";
1204
1205         switch (this->GetProtocolFamily())
1206         {
1207 #ifdef SUPPORT_IP6LINKS
1208                 case AF_INET6:
1209                 {
1210                         sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1211                         inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(buf));
1212                         /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1213                         if (*buf == ':')
1214                         {
1215                                 strlcpy(&temp[1], buf, sizeof(temp));
1216                                 *temp = '0';
1217                                 return temp;
1218                         }
1219                         return buf;
1220                 }
1221                 break;
1222 #endif
1223                 case AF_INET:
1224                 {
1225                         sockaddr_in* sin = (sockaddr_in*)this->ip;
1226                         inet_ntop(sin->sin_family, &sin->sin_addr, buf, sizeof(buf));
1227                         return buf;
1228                 }
1229                 break;
1230                 default:
1231                         log(DEBUG,"Ut oh, '%s' has an unknown protocol family!",this->nick);
1232                 break;
1233         }
1234         return "";
1235 }
1236
1237 const char* userrec::GetIPString(char* buf)
1238 {
1239         static char temp[1024];
1240
1241         if (this->ip == NULL)
1242         {
1243                 *buf = 0;
1244                 return buf;
1245         }
1246
1247         switch (this->GetProtocolFamily())
1248         {
1249 #ifdef SUPPORT_IP6LINKS
1250                 case AF_INET6:
1251                 {
1252                         sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1253                         inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(buf));
1254                         /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1255                         if (*buf == ':')
1256                         {
1257                                 strlcpy(&temp[1], buf, sizeof(temp));
1258                                 *temp = '0';
1259                                 strlcpy(buf, temp, sizeof(temp));
1260                         }
1261                         return buf;
1262                 }
1263                 break;
1264 #endif
1265                 case AF_INET:
1266                 {
1267                         sockaddr_in* sin = (sockaddr_in*)this->ip;
1268                         inet_ntop(sin->sin_family, &sin->sin_addr, buf, sizeof(buf));
1269                         return buf;
1270                 }
1271                 break;
1272
1273                 default:
1274                         log(DEBUG,"Ut oh, '%s' has an unknown protocol family!",this->nick);
1275                 break;
1276         }
1277         return "";
1278 }
1279