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