]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/users.cpp
dd075b044a3beadcafc285ea1ee33432bcfb3533
[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 <stdarg.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 irc::whowas::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                                 this->bound_user->WriteServ("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                                 this->bound_user->WriteServ("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                         this->bound_user->WriteServ("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                 this->bound_user->WriteServ("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         this->WriteServ("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                 user->Write("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 namespace irc
729 {
730         namespace whowas
731         {
732
733                 WhoWasGroup::WhoWasGroup(userrec* user) : host(NULL), dhost(NULL), ident(NULL), server(NULL), gecos(NULL), signon(user->signon)
734                 {
735                         this->host = strdup(user->host);
736                         this->dhost = strdup(user->dhost);
737                         this->ident = strdup(user->ident);
738                         this->server = user->server;
739                         this->gecos = strdup(user->fullname);
740                 }
741
742                 WhoWasGroup::~WhoWasGroup()
743                 {
744                         if (host)
745                                 free(host);
746                         if (dhost)
747                                 free(dhost);
748                         if (ident)
749                                 free(ident);
750                         if (gecos)
751                                 free(gecos);
752                 }
753
754                 /* every hour, run this function which removes all entries over 3 days */
755                 void MaintainWhoWas(time_t TIME)
756                 {
757                         for (whowas_users::iterator iter = ::whowas.begin(); iter != ::whowas.end(); iter++)
758                         {
759                                 whowas_set* n = (whowas_set*)iter->second;
760                                 if (n->size())
761                                 {
762                                         while ((n->begin() != n->end()) && ((*n->begin())->signon < TIME - 259200)) // 3 days
763                                         {
764                                                 WhoWasGroup *a = *(n->begin());
765                                                 DELETE(a);
766                                                 n->erase(n->begin());
767                                         }
768                                 }
769                         }
770                 }
771         };
772 };
773
774 /* adds or updates an entry in the whowas list */
775 void userrec::AddToWhoWas()
776 {
777         irc::whowas::whowas_users::iterator iter = whowas.find(this->nick);
778
779         if (iter == whowas.end())
780         {
781                 irc::whowas::whowas_set* n = new irc::whowas::whowas_set;
782                 irc::whowas::WhoWasGroup *a = new irc::whowas::WhoWasGroup(this);
783                 n->push_back(a);
784                 whowas[this->nick] = n;
785         }
786         else
787         {
788                 irc::whowas::whowas_set* group = (irc::whowas::whowas_set*)iter->second;
789
790                 if (group->size() > 10)
791                 {
792                         irc::whowas::WhoWasGroup *a = (irc::whowas::WhoWasGroup*)*(group->begin());
793                         DELETE(a);
794                         group->pop_front();
795                 }
796
797                 irc::whowas::WhoWasGroup *a = new irc::whowas::WhoWasGroup(this);
798                 group->push_back(a);
799         }
800 }
801
802 /* add a client connection to the sockets list */
803 void userrec::AddClient(int socket, int port, bool iscached, insp_inaddr ip)
804 {
805         std::string tempnick = ConvToStr(socket) + "-unknown";
806         user_hash::iterator iter = clientlist.find(tempnick);
807         const char *ipaddr = insp_ntoa(ip);
808         userrec* _new;
809         int j = 0;
810
811         /*
812          * fix by brain.
813          * as these nicknames are 'RFC impossible', we can be sure nobody is going to be
814          * using one as a registered connection. As they are per fd, we can also safely assume
815          * that we wont have collisions. Therefore, if the nick exists in the list, its only
816          * used by a dead socket, erase the iterator so that the new client may reclaim it.
817          * this was probably the cause of 'server ignores me when i hammer it with reconnects'
818          * issue in earlier alphas/betas
819          */
820         if (iter != clientlist.end())
821         {
822                 userrec* goner = iter->second;
823                 DELETE(goner);
824                 clientlist.erase(iter);
825         }
826
827         log(DEBUG,"AddClient: %d %d %s",socket,port,ipaddr);
828         
829         _new = new userrec();
830         clientlist[tempnick] = _new;
831         _new->fd = socket;
832         strlcpy(_new->nick,tempnick.c_str(),NICKMAX-1);
833
834         _new->server = FindServerNamePtr(Config->ServerName);
835         /* We don't need range checking here, we KNOW 'unknown\0' will fit into the ident field. */
836         strcpy(_new->ident, "unknown");
837
838         _new->registered = REG_NONE;
839         _new->signon = TIME + Config->dns_timeout;
840         _new->lastping = 1;
841
842         log(DEBUG,"Setting socket addresses");
843         _new->SetSockAddr(AF_FAMILY, ipaddr, port);
844         log(DEBUG,"Socket addresses set.");
845
846         /* Smarter than your average bear^H^H^H^Hset of strlcpys. */
847         for (const char* temp = _new->GetIPString(); *temp && j < 64; temp++, j++)
848                 _new->dhost[j] = _new->host[j] = *temp;
849         _new->dhost[j] = _new->host[j] = 0;
850                         
851         // set the registration timeout for this user
852         unsigned long class_regtimeout = 90;
853         int class_flood = 0;
854         long class_threshold = 5;
855         long class_sqmax = 262144;      // 256kb
856         long class_rqmax = 4096;        // 4k
857
858         for (ClassVector::iterator i = Config->Classes.begin(); i != Config->Classes.end(); i++)
859         {
860                 if ((i->type == CC_ALLOW) && (match(ipaddr,i->host.c_str(),true)))
861                 {
862                         class_regtimeout = (unsigned long)i->registration_timeout;
863                         class_flood = i->flood;
864                         _new->pingmax = i->pingtime;
865                         class_threshold = i->threshold;
866                         class_sqmax = i->sendqmax;
867                         class_rqmax = i->recvqmax;
868                         break;
869                 }
870         }
871
872         _new->nping = TIME + _new->pingmax + Config->dns_timeout;
873         _new->timeout = TIME+class_regtimeout;
874         _new->flood = class_flood;
875         _new->threshold = class_threshold;
876         _new->sendqmax = class_sqmax;
877         _new->recvqmax = class_rqmax;
878
879         fd_ref_table[socket] = _new;
880         local_users.push_back(_new);
881
882         if (local_users.size() > Config->SoftLimit)
883         {
884                 userrec::QuitUser(_new,"No more connections allowed");
885                 return;
886         }
887
888         if (local_users.size() >= MAXCLIENTS)
889         {
890                 userrec::QuitUser(_new,"No more connections allowed");
891                 return;
892         }
893
894         /*
895          * XXX -
896          * this is done as a safety check to keep the file descriptors within range of fd_ref_table.
897          * its a pretty big but for the moment valid assumption:
898          * file descriptors are handed out starting at 0, and are recycled as theyre freed.
899          * therefore if there is ever an fd over 65535, 65536 clients must be connected to the
900          * irc server at once (or the irc server otherwise initiating this many connections, files etc)
901          * which for the time being is a physical impossibility (even the largest networks dont have more
902          * than about 10,000 users on ONE server!)
903          */
904         if ((unsigned)socket >= MAX_DESCRIPTORS)
905         {
906                 userrec::QuitUser(_new,"Server is full");
907                 return;
908         }
909         char* e = matches_exception(ipaddr);
910         if (!e)
911         {
912                 char* r = matches_zline(ipaddr);
913                 if (r)
914                 {
915                         char reason[MAXBUF];
916                         snprintf(reason,MAXBUF,"Z-Lined: %s",r);
917                         userrec::QuitUser(_new,reason);
918                         return;
919                 }
920         }
921
922         if (socket > -1)
923         {
924                 if (!ServerInstance->SE->AddFd(socket,true,X_ESTAB_CLIENT))
925                 {
926                         userrec::QuitUser(_new, "Internal error handling connection");
927                         return;
928                 }
929         }
930
931         _new->WriteServ("NOTICE Auth :*** Looking up your hostname...");
932 }
933
934 long userrec::GlobalCloneCount()
935 {
936         char u1[1024];
937         char u2[1024];
938         long x = 0;
939         for (user_hash::const_iterator a = clientlist.begin(); a != clientlist.end(); a++)
940         {
941                 /* We have to match ip's as strings - we don't know what protocol
942                  * a remote user may be using
943                  */
944                 if (!strcasecmp(a->second->GetIPString(u1), this->GetIPString(u2)))
945                                 x++;
946         }
947         return x;
948 }
949
950 long userrec::LocalCloneCount()
951 {
952         long x = 0;
953         for (std::vector<userrec*>::const_iterator a = local_users.begin(); a != local_users.end(); a++)
954         {
955                 userrec* comp = *a;
956 #ifdef IPV6
957                 /* I dont think theres any faster way of matching two ipv6 addresses than memcmp */
958                 in6_addr* s1 = &(((sockaddr_in6*)comp->ip)->sin6_addr);
959                 in6_addr* s2 = &(((sockaddr_in6*)this->ip)->sin6_addr);
960                 if (!memcmp(s1->s6_addr, s2->s6_addr, sizeof(in6_addr)))
961                         x++;
962 #else
963                 in_addr* s1 = &((sockaddr_in*)comp->ip)->sin_addr;
964                 in_addr* s2 = &((sockaddr_in*)this->ip)->sin_addr;
965                 if (s1->s_addr == s2->s_addr)
966                         x++;
967 #endif
968         }
969         return x;
970 }
971
972 void userrec::FullConnect(CullList* Goners)
973 {
974         ServerInstance->stats->statsConnects++;
975         this->idle_lastmsg = TIME;
976
977         ConnectClass a = GetClass(this);
978
979         if (a.type == CC_DENY)
980         {
981                 Goners->AddItem(this,"Unauthorised connection");
982                 return;
983         }
984         
985         if ((*(a.pass.c_str())) && (!this->haspassed))
986         {
987                 Goners->AddItem(this,"Invalid password");
988                 return;
989         }
990         
991         if (this->LocalCloneCount() > a.maxlocal)
992         {
993                 Goners->AddItem(this, "No more connections allowed from your host via this connect class (local)");
994                 WriteOpers("*** WARNING: maximum LOCAL connections (%ld) exceeded for IP %s", a.maxlocal, this->GetIPString());
995                 return;
996         }
997         else if (this->GlobalCloneCount() > a.maxglobal)
998         {
999                 Goners->AddItem(this, "No more connections allowed from your host via this connect class (global)");
1000                 WriteOpers("*** WARNING: maximum GLOBAL connections (%ld) exceeded for IP %s",a.maxglobal, this->GetIPString());
1001                 return;
1002         }
1003
1004         char match_against[MAXBUF];
1005         snprintf(match_against,MAXBUF,"%s@%s", this->ident, this->host);
1006         char* e = matches_exception(match_against);
1007
1008         if (!e)
1009         {
1010                 char* r = matches_gline(match_against);
1011                 
1012                 if (r)
1013                 {
1014                         char reason[MAXBUF];
1015                         snprintf(reason,MAXBUF,"G-Lined: %s",r);
1016                         Goners->AddItem(this, reason);
1017                         return;
1018                 }
1019                 
1020                 r = matches_kline(match_against);
1021                 
1022                 if (r)
1023                 {
1024                         char reason[MAXBUF];
1025                         snprintf(reason,MAXBUF,"K-Lined: %s",r);
1026                         Goners->AddItem(this, reason);
1027                         return;
1028                 }
1029         }
1030
1031
1032         this->WriteServ("NOTICE Auth :Welcome to \002%s\002!",Config->Network);
1033         this->WriteServ("001 %s :Welcome to the %s IRC Network %s!%s@%s",this->nick, Config->Network, this->nick, this->ident, this->host);
1034         this->WriteServ("002 %s :Your host is %s, running version %s",this->nick,Config->ServerName,VERSION);
1035         this->WriteServ("003 %s :This server was created %s %s", this->nick, __TIME__, __DATE__);
1036         this->WriteServ("004 %s %s %s %s %s %s", this->nick, Config->ServerName, VERSION, ServerInstance->ModeGrok->UserModeList().c_str(), ServerInstance->ModeGrok->ChannelModeList().c_str(), ServerInstance->ModeGrok->ParaModeList().c_str());
1037
1038         // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
1039         // so i'd better split it :)
1040         std::stringstream out(Config->data005);
1041         std::string token = "";
1042         std::string line5 = "";
1043         int token_counter = 0;
1044         
1045         while (!out.eof())
1046         {
1047                 out >> token;
1048                 line5 = line5 + token + " ";
1049                 token_counter++;
1050                 
1051                 if ((token_counter >= 13) || (out.eof() == true))
1052                 {
1053                         this->WriteServ("005 %s %s:are supported by this server", this->nick, line5.c_str());
1054                         line5 = "";
1055                         token_counter = 0;
1056                 }
1057         }
1058         
1059         ShowMOTD(this);
1060
1061         /*
1062          * fix 3 by brain, move registered = 7 below these so that spurious modes and host
1063          * changes dont go out onto the network and produce 'fake direction'.
1064          */
1065         FOREACH_MOD(I_OnUserConnect,OnUserConnect(this));
1066         FOREACH_MOD(I_OnGlobalConnect,OnGlobalConnect(this));
1067         this->registered = REG_ALL;
1068         WriteOpers("*** Client connecting on port %d: %s!%s@%s [%s]", this->GetPort(), this->nick, this->ident, this->host, this->GetIPString());
1069 }
1070
1071 /** userrec::UpdateNick()
1072  * re-allocates a nick in the user_hash after they change nicknames,
1073  * returns a pointer to the new user as it may have moved
1074  */
1075 userrec* userrec::UpdateNickHash(const char* New)
1076 {
1077         //user_hash::iterator newnick;
1078         user_hash::iterator oldnick = clientlist.find(this->nick);
1079
1080         if (!strcasecmp(this->nick,New))
1081                 return oldnick->second;
1082
1083         if (oldnick == clientlist.end())
1084                 return NULL; /* doesnt exist */
1085
1086         userrec* olduser = oldnick->second;
1087         clientlist[New] = olduser;
1088         clientlist.erase(oldnick);
1089         return clientlist[New];
1090 }
1091
1092 bool userrec::ForceNickChange(const char* newnick)
1093 {
1094         char nick[MAXBUF];
1095         int MOD_RESULT = 0;
1096
1097         *nick = 0;
1098
1099         FOREACH_RESULT(I_OnUserPreNick,OnUserPreNick(this, newnick));
1100         
1101         if (MOD_RESULT)
1102         {
1103                 ServerInstance->stats->statsCollisions++;
1104                 return false;
1105         }
1106         
1107         if (matches_qline(newnick))
1108         {
1109                 ServerInstance->stats->statsCollisions++;
1110                 return false;
1111         }
1112
1113         if (newnick)
1114         {
1115                 strlcpy(this->nick, newnick, NICKMAX - 1);
1116         }
1117         if (this->registered == REG_ALL)
1118         {
1119                 const char* pars[1];
1120                 pars[0] = nick;
1121                 std::string cmd = "NICK";
1122                 ServerInstance->Parser->CallHandler(cmd, pars, 1, this);
1123         }
1124         return true;
1125 }
1126
1127 void userrec::SetSockAddr(int protocol_family, const char* ip, int port)
1128 {
1129         switch (protocol_family)
1130         {
1131 #ifdef SUPPORT_IP6LINKS
1132                 case AF_INET6:
1133                 {
1134                         log(DEBUG,"Set inet6 protocol address");
1135                         sockaddr_in6* sin = new sockaddr_in6;
1136                         sin->sin6_family = AF_INET6;
1137                         sin->sin6_port = port;
1138                         inet_pton(AF_INET6, ip, &sin->sin6_addr);
1139                         this->ip = (sockaddr*)sin;
1140                 }
1141                 break;
1142 #endif
1143                 case AF_INET:
1144                 {
1145                         log(DEBUG,"Set inet4 protocol address");
1146                         sockaddr_in* sin = new sockaddr_in;
1147                         sin->sin_family = AF_INET;
1148                         sin->sin_port = port;
1149                         inet_pton(AF_INET, ip, &sin->sin_addr);
1150                         this->ip = (sockaddr*)sin;
1151                 }
1152                 break;
1153                 default:
1154                         log(DEBUG,"Ut oh, I dont know protocol %d to be set on '%s'!", protocol_family, this->nick);
1155                 break;
1156         }
1157 }
1158
1159 int userrec::GetPort()
1160 {
1161         if (this->ip == NULL)
1162                 return 0;
1163
1164         switch (this->GetProtocolFamily())
1165         {
1166 #ifdef SUPPORT_IP6LINKS
1167                 case AF_INET6:
1168                 {
1169                         sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1170                         return sin->sin6_port;
1171                 }
1172                 break;
1173 #endif
1174                 case AF_INET:
1175                 {
1176                         sockaddr_in* sin = (sockaddr_in*)this->ip;
1177                         return sin->sin_port;
1178                 }
1179                 break;
1180                 default:
1181                         log(DEBUG,"Ut oh, '%s' has an unknown protocol family!",this->nick);
1182                 break;
1183         }
1184         return 0;
1185 }
1186
1187 int userrec::GetProtocolFamily()
1188 {
1189         if (this->ip == NULL)
1190                 return 0;
1191
1192         sockaddr_in* sin = (sockaddr_in*)this->ip;
1193         return sin->sin_family;
1194 }
1195
1196 const char* userrec::GetIPString()
1197 {
1198         static char buf[1024];
1199         static char temp[1024];
1200
1201         if (this->ip == NULL)
1202                 return "";
1203
1204         switch (this->GetProtocolFamily())
1205         {
1206 #ifdef SUPPORT_IP6LINKS
1207                 case AF_INET6:
1208                 {
1209                         sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1210                         inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(buf));
1211                         /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1212                         if (*buf == ':')
1213                         {
1214                                 strlcpy(&temp[1], buf, sizeof(temp));
1215                                 *temp = '0';
1216                                 return temp;
1217                         }
1218                         return buf;
1219                 }
1220                 break;
1221 #endif
1222                 case AF_INET:
1223                 {
1224                         sockaddr_in* sin = (sockaddr_in*)this->ip;
1225                         inet_ntop(sin->sin_family, &sin->sin_addr, buf, sizeof(buf));
1226                         return buf;
1227                 }
1228                 break;
1229                 default:
1230                         log(DEBUG,"Ut oh, '%s' has an unknown protocol family!",this->nick);
1231                 break;
1232         }
1233         return "";
1234 }
1235
1236 const char* userrec::GetIPString(char* buf)
1237 {
1238         static char temp[1024];
1239
1240         if (this->ip == NULL)
1241         {
1242                 *buf = 0;
1243                 return buf;
1244         }
1245
1246         switch (this->GetProtocolFamily())
1247         {
1248 #ifdef SUPPORT_IP6LINKS
1249                 case AF_INET6:
1250                 {
1251                         sockaddr_in6* sin = (sockaddr_in6*)this->ip;
1252                         inet_ntop(sin->sin6_family, &sin->sin6_addr, buf, sizeof(buf));
1253                         /* IP addresses starting with a : on irc are a Bad Thing (tm) */
1254                         if (*buf == ':')
1255                         {
1256                                 strlcpy(&temp[1], buf, sizeof(temp));
1257                                 *temp = '0';
1258                                 strlcpy(buf, temp, sizeof(temp));
1259                         }
1260                         return buf;
1261                 }
1262                 break;
1263 #endif
1264                 case AF_INET:
1265                 {
1266                         sockaddr_in* sin = (sockaddr_in*)this->ip;
1267                         inet_ntop(sin->sin_family, &sin->sin_addr, buf, sizeof(buf));
1268                         return buf;
1269                 }
1270                 break;
1271
1272                 default:
1273                         log(DEBUG,"Ut oh, '%s' has an unknown protocol family!",this->nick);
1274                 break;
1275         }
1276         return "";
1277 }
1278
1279
1280 void userrec::Write(const std::string &text)
1281 {
1282         char tb[MAXBUF];
1283         int bytes;
1284
1285         if ((this->fd < 0) || (this->fd > MAX_DESCRIPTORS))
1286                 return;
1287
1288         bytes = snprintf(tb,MAXBUF,"%s\r\n",text.c_str());
1289
1290         if (Config->GetIOHook(this->GetPort()))
1291         {
1292                 try
1293                 {
1294                         Config->GetIOHook(this->GetPort())->OnRawSocketWrite(this->fd,tb,bytes);
1295                 }
1296                 catch (ModuleException& modexcept)
1297                 {
1298                         log(DEBUG,"Module exception caught: %s",modexcept.GetReason());
1299                 }
1300         }
1301         else
1302         {
1303                 this->AddWriteBuf(tb);
1304         }
1305         ServerInstance->stats->statsSent += bytes;
1306 }
1307
1308 /** Write()
1309  */
1310 void userrec::Write(const char *text, ...)
1311 {
1312         va_list argsPtr;
1313         char textbuffer[MAXBUF];
1314
1315         va_start(argsPtr, text);
1316         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1317         va_end(argsPtr);
1318
1319         this->Write(std::string(textbuffer));
1320 }
1321
1322 void userrec::WriteServ(const std::string& text)
1323 {
1324         char textbuffer[MAXBUF];
1325
1326         snprintf(textbuffer,MAXBUF,":%s %s",Config->ServerName,text.c_str());
1327         this->Write(std::string(textbuffer));
1328 }
1329
1330 /** WriteServ()
1331  *  Same as Write(), except `text' is prefixed with `:server.name '.
1332  */
1333 void userrec::WriteServ(const char* text, ...)
1334 {
1335         va_list argsPtr;
1336         char textbuffer[MAXBUF];
1337
1338         va_start(argsPtr, text);
1339         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1340         va_end(argsPtr);
1341
1342         this->WriteServ(std::string(textbuffer));
1343 }
1344
1345
1346 void userrec::WriteFrom(userrec *user, const std::string &text)
1347 {
1348         char tb[MAXBUF];
1349
1350         snprintf(tb,MAXBUF,":%s %s",user->GetFullHost(),text.c_str());
1351         
1352         this->Write(std::string(tb));
1353 }
1354
1355
1356 /* write text from an originating user to originating user */
1357
1358 void userrec::WriteFrom(userrec *user, const char* text, ...)
1359 {
1360         va_list argsPtr;
1361         char textbuffer[MAXBUF];
1362
1363         va_start(argsPtr, text);
1364         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
1365         va_end(argsPtr);
1366
1367         this->WriteFrom(user, std::string(textbuffer));
1368 }
1369
1370
1371 /* write text to an destination user from a source user (e.g. user privmsg) */
1372
1373 void userrec::WriteTo(userrec *dest, const char *data, ...)
1374 {
1375         char textbuffer[MAXBUF];
1376         va_list argsPtr;
1377
1378         va_start(argsPtr, data);
1379         vsnprintf(textbuffer, MAXBUF, data, argsPtr);
1380         va_end(argsPtr);
1381
1382         this->WriteTo(dest, std::string(textbuffer));
1383 }
1384
1385 void userrec::WriteTo(userrec *dest, const std::string &data)
1386 {
1387         dest->WriteFrom(this, data);
1388 }
1389
1390