]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/users.cpp
327d0b5bb836d0d401d2e1664cf778650dd3b102
[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 userrec::Oper(const std::string &opertype)
619 {
620         this->modes[UM_OPERATOR] = 1;
621         WriteServ(this->fd, "MODE %s :+o", this->nick);
622         FOREACH_MOD(I_OnOper, OnOper(this, opertype));
623         log(DEFAULT,"OPER: %s!%s@%s opered as type: %s", this->nick, this->ident, this->host, opertype.c_str());
624         strlcpy(this->oper, opertype.c_str(), NICKMAX - 1);
625         all_opers.push_back(this);
626         FOREACH_MOD(I_OnPostOper,OnPostOper(this, opertype));
627 }
628
629 void userrec::UnOper()
630 {
631         if (*this->oper)
632         {
633                 *this->oper = 0;
634                 this->modes[UM_OPERATOR] = 0;
635                 for (std::vector<userrec*>::iterator a = all_opers.begin(); a < all_opers.end(); a++)
636                 {
637                         if (*a == this)
638                         {
639                                 log(DEBUG,"Oper removed from optimization list");
640                                 all_opers.erase(a);
641                                 return;
642                         }
643                 }
644         }
645 }
646
647 void userrec::QuitUser(userrec *user,const std::string &quitreason)
648 {
649         user_hash::iterator iter = clientlist.find(user->nick);
650
651 /*
652  * I'm pretty sure returning here is causing a desync when part of the net thinks a user is gone,
653  * and another part doesn't. We want to broadcast the quit/kill before bailing so the net stays in sync.
654  *
655  * I can't imagine this blowing up, so I'm commenting it out. We still check
656  * before playing with a bad iterator below in our if(). DISCUSS THIS BEFORE YOU DO ANYTHING. --w00t
657  *
658  *      if (iter == clientlist.end())
659  *              return;
660  */
661         std::string reason = quitreason;
662
663         if (reason.length() > MAXQUIT - 1)
664                 reason.resize(MAXQUIT - 1);
665         
666         if (IS_LOCAL(user))
667                 Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason.c_str());
668
669         if (user->registered == REG_ALL)
670         {
671                 purge_empty_chans(user);
672                 FOREACH_MOD(I_OnUserQuit,OnUserQuit(user,reason));
673                 WriteCommonExcept(user,"QUIT :%s",reason.c_str());
674         }
675
676         if (IS_LOCAL(user))
677                 user->FlushWriteBuf();
678
679         FOREACH_MOD(I_OnUserDisconnect,OnUserDisconnect(user));
680
681         if (IS_LOCAL(user))
682         {
683                 if (Config->GetIOHook(user->GetPort()))
684                 {
685                         try
686                         {
687                                 Config->GetIOHook(user->GetPort())->OnRawSocketClose(user->fd);
688                         }
689                         catch (ModuleException& modexcept)
690                         {
691                                 log(DEBUG,"Module exception cought: %s",modexcept.GetReason());
692                         }
693                 }
694                 
695                 ServerInstance->SE->DelFd(user->fd);
696                 user->CloseSocket();
697         }
698
699         /*
700          * this must come before the WriteOpers so that it doesnt try to fill their buffer with anything
701          * if they were an oper with +s.
702          *
703          * XXX -
704          * In the current implementation, we only show local quits, as we only show local connects. With 
705          * the proposed implmentation of snomasks however, this will likely change in the (near?) future.
706          */
707         if (user->registered == REG_ALL)
708         {
709                 if (IS_LOCAL(user))
710                         WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason.c_str());
711                 user->AddToWhoWas();
712         }
713
714         if (iter != clientlist.end())
715         {
716                 log(DEBUG,"deleting user hash value %lx",(unsigned long)user);
717                 if (IS_LOCAL(user))
718                 {
719                         fd_ref_table[user->fd] = NULL;
720                         if (find(local_users.begin(),local_users.end(),user) != local_users.end())
721                                 local_users.erase(find(local_users.begin(),local_users.end(),user));
722                 }
723                 clientlist.erase(iter);
724                 DELETE(user);
725         }
726 }
727
728 WhoWasGroup::WhoWasGroup(userrec* user) : host(NULL), dhost(NULL), ident(NULL), server(NULL), gecos(NULL), signon(user->signon)
729 {
730         this->host = strdup(user->host);
731         this->dhost = strdup(user->dhost);
732         this->ident = strdup(user->ident);
733         this->server = user->server;
734         this->gecos = strdup(user->fullname);
735 }
736
737 WhoWasGroup::~WhoWasGroup()
738 {
739         if (host)
740                 free(host);
741         if (dhost)
742                 free(dhost);
743         if (ident)
744                 free(ident);
745         if (gecos)
746                 free(gecos);
747 }
748
749 /* adds or updates an entry in the whowas list */
750 void userrec::AddToWhoWas()
751 {
752         whowas_users::iterator iter = whowas.find(this->nick);
753
754         if (iter == whowas.end())
755         {
756                 whowas_set* n = new whowas_set;
757                 WhoWasGroup *a = new WhoWasGroup(this);
758                 n->push_back(a);
759                 whowas[this->nick] = n;
760         }
761         else
762         {
763                 whowas_set* group = (whowas_set*)iter->second;
764
765                 if (group->size() > 10)
766                 {
767                         WhoWasGroup *a = (WhoWasGroup*)*(group->begin());
768                         DELETE(a);
769                         group->pop_front();
770                 }
771
772                 WhoWasGroup *a = new WhoWasGroup(this);
773                 group->push_back(a);
774         }
775 }
776
777 /* every hour, run this function which removes all entries over 3 days */
778 void MaintainWhoWas(time_t TIME)
779 {
780         for (whowas_users::iterator iter = whowas.begin(); iter != whowas.end(); iter++)
781         {
782                 whowas_set* n = (whowas_set*)iter->second;
783                 if (n->size())
784                 {
785                         while ((n->begin() != n->end()) && ((*n->begin())->signon < TIME - 259200)) // 3 days
786                         {
787                                 WhoWasGroup *a = *(n->begin());
788                                 DELETE(a);
789                                 n->erase(n->begin());
790                         }
791                 }
792         }
793 }
794
795 /* add a client connection to the sockets list */
796 void AddClient(int socket, int port, bool iscached, insp_inaddr ip)
797 {
798         std::string tempnick = ConvToStr(socket) + "-unknown";
799         user_hash::iterator iter = clientlist.find(tempnick);
800         const char *ipaddr = insp_ntoa(ip);
801         userrec* _new;
802         int j = 0;
803
804         /*
805          * fix by brain.
806          * as these nicknames are 'RFC impossible', we can be sure nobody is going to be
807          * using one as a registered connection. As they are per fd, we can also safely assume
808          * that we wont have collisions. Therefore, if the nick exists in the list, its only
809          * used by a dead socket, erase the iterator so that the new client may reclaim it.
810          * this was probably the cause of 'server ignores me when i hammer it with reconnects'
811          * issue in earlier alphas/betas
812          */
813         if (iter != clientlist.end())
814         {
815                 userrec* goner = iter->second;
816                 DELETE(goner);
817                 clientlist.erase(iter);
818         }
819
820         log(DEBUG,"AddClient: %d %d %s",socket,port,ipaddr);
821         
822         _new = new userrec();
823         clientlist[tempnick] = _new;
824         _new->fd = socket;
825         strlcpy(_new->nick,tempnick.c_str(),NICKMAX-1);
826
827         _new->server = FindServerNamePtr(Config->ServerName);
828         /* We don't need range checking here, we KNOW 'unknown\0' will fit into the ident field. */
829         strcpy(_new->ident, "unknown");
830
831         _new->registered = REG_NONE;
832         _new->signon = TIME + Config->dns_timeout;
833         _new->lastping = 1;
834
835         log(DEBUG,"Setting socket addresses");
836         _new->SetSockAddr(AF_FAMILY, ipaddr, port);
837         log(DEBUG,"Socket addresses set.");
838
839         /* Smarter than your average bear^H^H^H^Hset of strlcpys. */
840         for (const char* temp = _new->GetIPString(); *temp && j < 64; temp++, j++)
841                 _new->dhost[j] = _new->host[j] = *temp;
842         _new->dhost[j] = _new->host[j] = 0;
843                         
844         // set the registration timeout for this user
845         unsigned long class_regtimeout = 90;
846         int class_flood = 0;
847         long class_threshold = 5;
848         long class_sqmax = 262144;      // 256kb
849         long class_rqmax = 4096;        // 4k
850
851         for (ClassVector::iterator i = Config->Classes.begin(); i != Config->Classes.end(); i++)
852         {
853                 if ((i->type == CC_ALLOW) && (match(ipaddr,i->host.c_str(),true)))
854                 {
855                         class_regtimeout = (unsigned long)i->registration_timeout;
856                         class_flood = i->flood;
857                         _new->pingmax = i->pingtime;
858                         class_threshold = i->threshold;
859                         class_sqmax = i->sendqmax;
860                         class_rqmax = i->recvqmax;
861                         break;
862                 }
863         }
864
865         _new->nping = TIME + _new->pingmax + Config->dns_timeout;
866         _new->timeout = TIME+class_regtimeout;
867         _new->flood = class_flood;
868         _new->threshold = class_threshold;
869         _new->sendqmax = class_sqmax;
870         _new->recvqmax = class_rqmax;
871
872         fd_ref_table[socket] = _new;
873         local_users.push_back(_new);
874
875         if (local_users.size() > Config->SoftLimit)
876         {
877                 userrec::QuitUser(_new,"No more connections allowed");
878                 return;
879         }
880
881         if (local_users.size() >= MAXCLIENTS)
882         {
883                 userrec::QuitUser(_new,"No more connections allowed");
884                 return;
885         }
886
887         /*
888          * XXX -
889          * this is done as a safety check to keep the file descriptors within range of fd_ref_table.
890          * its a pretty big but for the moment valid assumption:
891          * file descriptors are handed out starting at 0, and are recycled as theyre freed.
892          * therefore if there is ever an fd over 65535, 65536 clients must be connected to the
893          * irc server at once (or the irc server otherwise initiating this many connections, files etc)
894          * which for the time being is a physical impossibility (even the largest networks dont have more
895          * than about 10,000 users on ONE server!)
896          */
897         if ((unsigned)socket >= MAX_DESCRIPTORS)
898         {
899                 userrec::QuitUser(_new,"Server is full");
900                 return;
901         }
902         char* e = matches_exception(ipaddr);
903         if (!e)
904         {
905                 char* r = matches_zline(ipaddr);
906                 if (r)
907                 {
908                         char reason[MAXBUF];
909                         snprintf(reason,MAXBUF,"Z-Lined: %s",r);
910                         userrec::QuitUser(_new,reason);
911                         return;
912                 }
913         }
914
915         if (socket > -1)
916         {
917                 if (!ServerInstance->SE->AddFd(socket,true,X_ESTAB_CLIENT))
918                 {
919                         userrec::QuitUser(_new, "Internal error handling connection");
920                         return;
921                 }
922         }
923
924         WriteServ(_new->fd,"NOTICE Auth :*** Looking up your hostname...");
925 }
926
927 long FindMatchingGlobal(userrec* user)
928 {
929         char u1[1024];
930         char u2[1024];
931         long x = 0;
932         for (user_hash::const_iterator a = clientlist.begin(); a != clientlist.end(); a++)
933         {
934                 /* We have to match ip's as strings - we don't know what protocol
935                  * a remote user may be using
936                  */
937                 if (!strcasecmp(a->second->GetIPString(u1), user->GetIPString(u2)))
938                                 x++;
939         }
940         return x;
941 }
942
943 long FindMatchingLocal(userrec* user)
944 {
945         long x = 0;
946         for (std::vector<userrec*>::const_iterator a = local_users.begin(); a != local_users.end(); a++)
947         {
948                 userrec* comp = *a;
949 #ifdef IPV6
950                 /* I dont think theres any faster way of matching two ipv6 addresses than memcmp */
951                 in6_addr* s1 = &(((sockaddr_in6*)comp->ip)->sin6_addr);
952                 in6_addr* s2 = &(((sockaddr_in6*)user->ip)->sin6_addr);
953                 if (!memcmp(s1->s6_addr, s2->s6_addr, sizeof(in6_addr)))
954                         x++;
955 #else
956                 in_addr* s1 = &((sockaddr_in*)comp->ip)->sin_addr;
957                 in_addr* s2 = &((sockaddr_in*)user->ip)->sin_addr;
958                 if (s1->s_addr == s2->s_addr)
959                         x++;
960 #endif
961         }
962         return x;
963 }
964
965 void FullConnectUser(userrec* user, CullList* Goners)
966 {
967         ServerInstance->stats->statsConnects++;
968         user->idle_lastmsg = TIME;
969         log(DEBUG,"ConnectUser: %s",user->nick);
970
971         ConnectClass a = GetClass(user);
972         
973         if (a.type == CC_DENY)
974         {
975                 Goners->AddItem(user,"Unauthorised connection");
976                 return;
977         }
978         
979         if ((*(a.pass.c_str())) && (!user->haspassed))
980         {
981                 Goners->AddItem(user,"Invalid password");
982                 return;
983         }
984         
985         if (FindMatchingLocal(user) > a.maxlocal)
986         {
987                 Goners->AddItem(user,"No more connections allowed from your host via this connect class (local)");
988                 WriteOpers("*** WARNING: maximum LOCAL connections (%ld) exceeded for IP %s",a.maxlocal,user->GetIPString());
989                 return;
990         }
991         else if (FindMatchingGlobal(user) > a.maxglobal)
992         {
993                 Goners->AddItem(user,"No more connections allowed from your host via this connect class (global)");
994                 WriteOpers("*** WARNING: maximum GLOBAL connections (%ld) exceeded for IP %s",a.maxglobal,user->GetIPString());
995                 return;
996         }
997
998         char match_against[MAXBUF];
999         snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
1000         char* e = matches_exception(match_against);
1001         
1002         if (!e)
1003         {
1004                 char* r = matches_gline(match_against);
1005                 
1006                 if (r)
1007                 {
1008                         char reason[MAXBUF];
1009                         snprintf(reason,MAXBUF,"G-Lined: %s",r);
1010                         Goners->AddItem(user,reason);
1011                         return;
1012                 }
1013                 
1014                 r = matches_kline(match_against);
1015                 
1016                 if (r)
1017                 {
1018                         char reason[MAXBUF];
1019                         snprintf(reason,MAXBUF,"K-Lined: %s",r);
1020                         Goners->AddItem(user,reason);
1021                         return;
1022                 }
1023         }
1024
1025
1026         WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Config->Network);
1027         WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Config->Network,user->nick,user->ident,user->host);
1028         WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,Config->ServerName,VERSION);
1029         WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
1030         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());
1031         
1032         // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
1033         // so i'd better split it :)
1034         std::stringstream out(Config->data005);
1035         std::string token = "";
1036         std::string line5 = "";
1037         int token_counter = 0;
1038         
1039         while (!out.eof())
1040         {
1041                 out >> token;
1042                 line5 = line5 + token + " ";
1043                 token_counter++;
1044                 
1045                 if ((token_counter >= 13) || (out.eof() == true))
1046                 {
1047                         WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
1048                         line5 = "";
1049                         token_counter = 0;
1050                 }
1051         }
1052         
1053         ShowMOTD(user);
1054
1055         /*
1056          * fix 3 by brain, move registered = 7 below these so that spurious modes and host
1057          * changes dont go out onto the network and produce 'fake direction'.
1058          */
1059         FOREACH_MOD(I_OnUserConnect,OnUserConnect(user));
1060         FOREACH_MOD(I_OnGlobalConnect,OnGlobalConnect(user));
1061         user->registered = REG_ALL;
1062         WriteOpers("*** Client connecting on port %d: %s!%s@%s [%s]",user->GetPort(),user->nick,user->ident,user->host,user->GetIPString());
1063 }
1064
1065 /** ReHashNick()
1066  * re-allocates a nick in the user_hash after they change nicknames,
1067  * returns a pointer to the new user as it may have moved
1068  */
1069 userrec* ReHashNick(const char* Old, const char* New)
1070 {
1071         //user_hash::iterator newnick;
1072         user_hash::iterator oldnick = clientlist.find(Old);
1073
1074         log(DEBUG,"ReHashNick: %s %s",Old,New);
1075
1076         if (!strcasecmp(Old,New))
1077         {
1078                 log(DEBUG,"old nick is new nick, skipping");
1079                 return oldnick->second;
1080         }
1081
1082         if (oldnick == clientlist.end())
1083                 return NULL; /* doesnt exist */
1084
1085         log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
1086
1087         userrec* olduser = oldnick->second;
1088         clientlist[New] = olduser;
1089         clientlist.erase(oldnick);
1090
1091         log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
1092
1093         return clientlist[New];
1094 }
1095
1096 void force_nickchange(userrec* user,const char* newnick)
1097 {
1098         char nick[MAXBUF];
1099         int MOD_RESULT = 0;
1100
1101         *nick = 0;
1102
1103         FOREACH_RESULT(I_OnUserPreNick,OnUserPreNick(user,newnick));
1104         
1105         if (MOD_RESULT)
1106         {
1107                 ServerInstance->stats->statsCollisions++;
1108                 userrec::QuitUser(user,"Nickname collision");
1109                 return;
1110         }
1111         
1112         if (matches_qline(newnick))
1113         {
1114                 ServerInstance->stats->statsCollisions++;
1115                 userrec::QuitUser(user,"Nickname collision");
1116                 return;
1117         }
1118
1119         if (user)
1120         {
1121                 if (newnick)
1122                 {
1123                         strlcpy(nick,newnick,MAXBUF-1);
1124                 }
1125
1126                 if (user->registered == REG_ALL)
1127                 {
1128                         const char* pars[1];
1129                         pars[0] = nick;
1130                         std::string cmd = "NICK";
1131
1132                         ServerInstance->Parser->CallHandler(cmd,pars,1,user);
1133                 }
1134         }
1135 }
1136
1137 void userrec::SetSockAddr(int protocol_family, const char* ip, int port)
1138 {
1139         switch (protocol_family)
1140         {
1141 #ifdef SUPPORT_IP6LINKS
1142                 case AF_INET6:
1143                 {
1144                         log(DEBUG,"Set inet6 protocol address");
1145                         sockaddr_in6* sin = new sockaddr_in6;
1146                         sin->sin6_family = AF_INET6;
1147                         sin->sin6_port = port;
1148                         inet_pton(AF_INET6, ip, &sin->sin6_addr);
1149                         this->ip = (sockaddr*)sin;
1150                 }
1151                 break;
1152 #endif
1153                 case AF_INET:
1154                 {
1155                         log(DEBUG,"Set inet4 protocol address");
1156                         sockaddr_in* sin = new sockaddr_in;
1157                         sin->sin_family = AF_INET;
1158                         sin->sin_port = port;
1159                         inet_pton(AF_INET, ip, &sin->sin_addr);
1160                         this->ip = (sockaddr*)sin;
1161                 }
1162                 break;
1163                 default:
1164                         log(DEBUG,"Ut oh, I dont know protocol %d to be set on '%s'!", protocol_family, this->nick);
1165                 break;
1166         }
1167 }
1168
1169 int userrec::GetPort()
1170 {
1171         if (this->ip == NULL)
1172                 return 0;
1173
1174         switch (this->GetProtocolFamily())
1175         {
1176 #ifdef SUPPORT_IP6LINKS
1177                 case AF_INET6:
1178                 {
1179                         sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1180                         return sin->sin6_port;
1181                 }
1182                 break;
1183 #endif
1184                 case AF_INET:
1185                 {
1186                         sockaddr_in* sin = (sockaddr_in*)this->ip;
1187                         return sin->sin_port;
1188                 }
1189                 break;
1190                 default:
1191                         log(DEBUG,"Ut oh, '%s' has an unknown protocol family!",this->nick);
1192                 break;
1193         }
1194         return 0;
1195 }
1196
1197 int userrec::GetProtocolFamily()
1198 {
1199         if (this->ip == NULL)
1200                 return 0;
1201
1202         sockaddr_in* sin = (sockaddr_in*)this->ip;
1203         return sin->sin_family;
1204 }
1205
1206 const char* userrec::GetIPString()
1207 {
1208         static char buf[1024];
1209         static char temp[1024];
1210
1211         if (this->ip == NULL)
1212                 return "";
1213
1214         switch (this->GetProtocolFamily())
1215         {
1216 #ifdef SUPPORT_IP6LINKS
1217                 case AF_INET6:
1218                 {
1219                         sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1220                         inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(buf));
1221                         /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1222                         if (*buf == ':')
1223                         {
1224                                 strlcpy(&temp[1], buf, sizeof(temp));
1225                                 *temp = '0';
1226                                 return temp;
1227                         }
1228                         return buf;
1229                 }
1230                 break;
1231 #endif
1232                 case AF_INET:
1233                 {
1234                         sockaddr_in* sin = (sockaddr_in*)this->ip;
1235                         inet_ntop(sin->sin_family, &sin->sin_addr, buf, sizeof(buf));
1236                         return buf;
1237                 }
1238                 break;
1239                 default:
1240                         log(DEBUG,"Ut oh, '%s' has an unknown protocol family!",this->nick);
1241                 break;
1242         }
1243         return "";
1244 }
1245
1246 const char* userrec::GetIPString(char* buf)
1247 {
1248         static char temp[1024];
1249
1250         if (this->ip == NULL)
1251         {
1252                 *buf = 0;
1253                 return buf;
1254         }
1255
1256         switch (this->GetProtocolFamily())
1257         {
1258 #ifdef SUPPORT_IP6LINKS
1259                 case AF_INET6:
1260                 {
1261                         sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1262                         inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(buf));
1263                         /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1264                         if (*buf == ':')
1265                         {
1266                                 strlcpy(&temp[1], buf, sizeof(temp));
1267                                 *temp = '0';
1268                                 strlcpy(buf, temp, sizeof(temp));
1269                         }
1270                         return buf;
1271                 }
1272                 break;
1273 #endif
1274                 case AF_INET:
1275                 {
1276                         sockaddr_in* sin = (sockaddr_in*)this->ip;
1277                         inet_ntop(sin->sin_family, &sin->sin_addr, buf, sizeof(buf));
1278                         return buf;
1279                 }
1280                 break;
1281
1282                 default:
1283                         log(DEBUG,"Ut oh, '%s' has an unknown protocol family!",this->nick);
1284                 break;
1285         }
1286         return "";
1287 }
1288