]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/users.cpp
5afed6fe14b5395871bba8ad7b4aa5669a048e0f
[user/henk/code/inspircd.git] / src / users.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  Inspire is copyright (C) 2002-2004 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 using namespace std;
18
19 #include "inspircd_config.h" 
20 #include "channels.h"
21 #include "connection.h"
22 #include "users.h"
23 #include "inspircd.h"
24 #include <stdio.h>
25 #ifdef THREADED_DNS
26 #include <pthread.h>
27 #include <signal.h>
28 #endif
29 #include "inspstring.h"
30 #include "commands.h"
31 #include "helperfuncs.h"
32
33 extern ServerConfig* Config;
34 extern time_t TIME;
35 std::vector<userrec*> all_opers;
36
37 userrec::userrec()
38 {
39         // the PROPER way to do it, AVOID bzero at *ALL* costs
40         strcpy(nick,"");
41         strcpy(ip,"127.0.0.1");
42         timeout = 0;
43         strcpy(ident,"");
44         strcpy(host,"");
45         strcpy(dhost,"");
46         strcpy(fullname,"");
47         strcpy(modes,"");
48         server = (char*)FindServerNamePtr(Config->ServerName);
49         strcpy(awaymsg,"");
50         strcpy(oper,"");
51         reset_due = TIME;
52         lines_in = 0;
53         fd = lastping = signon = idle_lastmsg = nping = registered = 0;
54         flood = port = bytes_in = bytes_out = cmds_in = cmds_out = 0;
55         haspassed = false;
56         dns_done = false;
57         recvq = "";
58         sendq = "";
59         chans.clear();
60         invites.clear();
61 }
62
63 userrec::~userrec()
64 {
65 }
66
67 void userrec::CloseSocket()
68 {
69         shutdown(this->fd,2);
70         close(this->fd);
71 }
72  
73 char* userrec::GetFullHost()
74 {
75         static char result[MAXBUF];
76         snprintf(result,MAXBUF,"%s!%s@%s",nick,ident,dhost);
77         return result;
78 }
79
80 int userrec::ReadData(void* buffer, size_t size)
81 {
82         if (this->fd > -1)
83         {
84                 return read(this->fd, buffer, size);
85         }
86         else return 0;
87 }
88
89
90 char* userrec::GetFullRealHost()
91 {
92         static char fresult[MAXBUF];
93         snprintf(fresult,MAXBUF,"%s!%s@%s",nick,ident,host);
94         return fresult;
95 }
96
97 bool userrec::IsInvited(irc::string &channel)
98 {
99         for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
100         {
101                 irc::string compare = i->channel;
102                 if (compare == channel)
103                 {
104                         return true;
105                 }
106         }
107         return false;
108 }
109
110 InvitedList* userrec::GetInviteList()
111 {
112         return &invites;
113 }
114
115 void userrec::InviteTo(irc::string &channel)
116 {
117         Invited i;
118         i.channel = channel;
119         invites.push_back(i);
120 }
121
122 void userrec::RemoveInvite(irc::string &channel)
123 {
124         log(DEBUG,"Removing invites");
125         if (invites.size())
126         {
127                 for (InvitedList::iterator i = invites.begin(); i != invites.end(); i++)
128                 {
129                         if (i->channel)
130                         {
131                                 irc::string compare = i->channel;
132                                 if (compare == channel)
133                                 {
134                                         invites.erase(i);
135                                         return;
136                                 }
137                         }
138                 }
139         }
140 }
141
142 bool userrec::HasPermission(std::string &command)
143 {
144         char TypeName[MAXBUF],Classes[MAXBUF],ClassName[MAXBUF],CommandList[MAXBUF];
145         char* mycmd;
146         char* savept;
147         char* savept2;
148         
149         // users on u-lined servers can completely bypass
150         // all permissions based checks.
151         //
152         // of course, if this is sent to a remote server and this
153         // server is not ulined there, then that other server
154         // silently drops the command.
155         if (is_uline(this->server))
156                 return true;
157         
158         // are they even an oper at all?
159         if (strchr(this->modes,'o'))
160         {
161                 for (int j =0; j < Config->ConfValueEnum("type",&Config->config_f); j++)
162                 {
163                         Config->ConfValue("type","name",j,TypeName,&Config->config_f);
164                         if (!strcmp(TypeName,this->oper))
165                         {
166                                 Config->ConfValue("type","classes",j,Classes,&Config->config_f);
167                                 char* myclass = strtok_r(Classes," ",&savept);
168                                 while (myclass)
169                                 {
170                                         for (int k =0; k < Config->ConfValueEnum("class",&Config->config_f); k++)
171                                         {
172                                                 Config->ConfValue("class","name",k,ClassName,&Config->config_f);
173                                                 if (!strcmp(ClassName,myclass))
174                                                 {
175                                                         Config->ConfValue("class","commands",k,CommandList,&Config->config_f);
176                                                         mycmd = strtok_r(CommandList," ",&savept2);
177                                                         while (mycmd)
178                                                         {
179                                                                 if ((!strcasecmp(mycmd,command.c_str())) || (*mycmd == '*'))
180                                                                 {
181                                                                         return true;
182                                                                 }
183                                                                 mycmd = strtok_r(NULL," ",&savept2);
184                                                         }
185                                                 }
186                                         }
187                                         myclass = strtok_r(NULL," ",&savept);
188                                 }
189                         }
190                 }
191         }
192         return false;
193 }
194
195
196 bool userrec::AddBuffer(std::string a)
197 {
198         std::string b = "";
199         for (unsigned int i = 0; i < a.length(); i++)
200                 if ((a[i] != '\r') && (a[i] != '\0') && (a[i] != 7))
201                         b = b + a[i];
202         std::stringstream stream(recvq);
203         stream << b;
204         recvq = stream.str();
205         unsigned int i = 0;
206         // count the size of the first line in the buffer.
207         while (i < recvq.length())
208         {
209                 if (recvq[i++] == '\n')
210                         break;
211         }
212         if (recvq.length() > (unsigned)this->recvqmax)
213         {
214                 this->SetWriteError("RecvQ exceeded");
215                 WriteOpers("*** User %s RecvQ of %d exceeds connect class maximum of %d",this->nick,recvq.length(),this->recvqmax);
216         }
217         // return false if we've had more than 600 characters WITHOUT
218         // a carriage return (this is BAD, drop the socket)
219         return (i < 600);
220 }
221
222 bool userrec::BufferIsReady()
223 {
224         for (unsigned int i = 0; i < recvq.length(); i++)
225                 if (recvq[i] == '\n')
226                         return true;
227         return false;
228 }
229
230 void userrec::ClearBuffer()
231 {
232         recvq = "";
233 }
234
235 std::string userrec::GetBuffer()
236 {
237         if (recvq == "")
238                 return "";
239         char* line = (char*)recvq.c_str();
240         std::string ret = "";
241         while ((*line != '\n') && (strlen(line)))
242         {
243                 ret = ret + *line;
244                 line++;
245         }
246         if ((*line == '\n') || (*line == '\r'))
247                 line++;
248         recvq = line;
249         return ret;
250 }
251
252 void userrec::AddWriteBuf(std::string data)
253 {
254         if (this->GetWriteError() != "")
255                 return;
256         if (sendq.length() + data.length() > (unsigned)this->sendqmax)
257         {
258                 WriteOpers("*** User %s SendQ of %d exceeds connect class maximum of %d",this->nick,sendq.length() + data.length(),this->sendqmax);
259                 this->SetWriteError("SendQ exceeded");
260                 return;
261         }
262         std::stringstream stream;
263         stream << sendq << data;
264         sendq = stream.str();
265 }
266
267 // send AS MUCH OF THE USERS SENDQ as we are able to (might not be all of it)
268 void userrec::FlushWriteBuf()
269 {
270         if (sendq.length())
271         {
272                 char* tb = (char*)this->sendq.c_str();
273                 int n_sent = write(this->fd,tb,this->sendq.length());
274                 if (n_sent == -1)
275                 {
276                         this->SetWriteError(strerror(errno));
277                 }
278                 else
279                 {
280                         // advance the queue
281                         tb += n_sent;
282                         this->sendq = tb;
283                         // update the user's stats counters
284                         this->bytes_out += n_sent;
285                         this->cmds_out++;
286                 }
287         }
288 }
289
290 void userrec::SetWriteError(std::string error)
291 {
292         log(DEBUG,"Setting error string for %s to '%s'",this->nick,error.c_str());
293         // don't try to set the error twice, its already set take the first string.
294         if (this->WriteError == "")
295                 this->WriteError = error;
296 }
297
298 std::string userrec::GetWriteError()
299 {
300         return this->WriteError;
301 }
302
303 void AddOper(userrec* user)
304 {
305         log(DEBUG,"Oper added to optimization list");
306         all_opers.push_back(user);
307 }
308
309 void DeleteOper(userrec* user)
310 {
311         for (std::vector<userrec*>::iterator a = all_opers.begin(); a < all_opers.end(); a++)
312         {
313                 if (*a == user)
314                 {
315                         log(DEBUG,"Oper removed from optimization list");
316                         all_opers.erase(a);
317                         return;
318                 }
319         }
320 }
321
322 void kill_link(userrec *user,const char* r)
323 {
324         user_hash::iterator iter = clientlist.find(user->nick);
325
326         char reason[MAXBUF];
327
328         strncpy(reason,r,MAXBUF);
329
330         if (strlen(reason)>MAXQUIT)
331         {
332                 reason[MAXQUIT-1] = '\0';
333         }
334
335         log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
336         Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
337         log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
338
339         if (user->registered == 7) {
340                 FOREACH_MOD OnUserQuit(user,reason);
341                 WriteCommonExcept(user,"QUIT :%s",reason);
342         }
343
344         user->FlushWriteBuf();
345
346         FOREACH_MOD OnUserDisconnect(user);
347
348         if (user->fd > -1)
349         {
350                 FOREACH_MOD OnRawSocketClose(user->fd);
351                 SE->DelFd(user->fd);
352                 user->CloseSocket();
353         }
354
355         // this must come before the WriteOpers so that it doesnt try to fill their buffer with anything
356         // if they were an oper with +s.
357         if (user->registered == 7) {
358                 purge_empty_chans(user);
359                 // fix by brain: only show local quits because we only show local connects (it just makes SENSE)
360                 if (user->fd > -1)
361                         WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
362                 AddWhoWas(user);
363         }
364
365         if (iter != clientlist.end())
366         {
367                 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
368                 if (user->fd > -1)
369                         fd_ref_table[user->fd] = NULL;
370                 clientlist.erase(iter);
371         }
372         delete user;
373 }
374
375 void kill_link_silent(userrec *user,const char* r)
376 {
377         user_hash::iterator iter = clientlist.find(user->nick);
378
379         char reason[MAXBUF];
380
381         strncpy(reason,r,MAXBUF);
382
383         if (strlen(reason)>MAXQUIT)
384         {
385                 reason[MAXQUIT-1] = '\0';
386         }
387
388         log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
389         Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
390         log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
391
392         user->FlushWriteBuf();
393
394         if (user->registered == 7) {
395                 FOREACH_MOD OnUserQuit(user,reason);
396                 WriteCommonExcept(user,"QUIT :%s",reason);
397         }
398
399         FOREACH_MOD OnUserDisconnect(user);
400
401         if (user->fd > -1)
402         {
403                 FOREACH_MOD OnRawSocketClose(user->fd);
404                 SE->DelFd(user->fd);
405                 user->CloseSocket();
406         }
407
408         if (user->registered == 7) {
409                 purge_empty_chans(user);
410         }
411
412         if (iter != clientlist.end())
413         {
414                 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
415                 if (user->fd > -1)
416                         fd_ref_table[user->fd] = NULL;
417                 clientlist.erase(iter);
418         }
419         delete user;
420 }
421
422
423 /* adds or updates an entry in the whowas list */
424 void AddWhoWas(userrec* u)
425 {
426         whowas_hash::iterator iter = whowas.find(u->nick);
427         WhoWasUser *a = new WhoWasUser();
428         strlcpy(a->nick,u->nick,NICKMAX);
429         strlcpy(a->ident,u->ident,IDENTMAX);
430         strlcpy(a->dhost,u->dhost,160);
431         strlcpy(a->host,u->host,160);
432         strlcpy(a->fullname,u->fullname,MAXGECOS);
433         strlcpy(a->server,u->server,256);
434         a->signon = u->signon;
435
436         /* MAX_WHOWAS:   max number of /WHOWAS items
437          * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
438          *               can be replaced by a newer one
439          */
440
441         if (iter == whowas.end())
442         {
443                 if (whowas.size() >= (unsigned)WHOWAS_MAX)
444                 {
445                         for (whowas_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
446                         {
447                                 // 3600 seconds in an hour ;)
448                                 if ((i->second->signon)<(TIME-(WHOWAS_STALE*3600)))
449                                 {
450                                         // delete the old one
451                                         if (i->second) delete i->second;
452                                         // replace with new one
453                                         i->second = a;
454                                         log(DEBUG,"added WHOWAS entry, purged an old record");
455                                         return;
456                                 }
457                         }
458                         // no space left and user doesnt exist. Don't leave ram in use!
459                         log(DEBUG,"Not able to update whowas (list at WHOWAS_MAX entries and trying to add new?), freeing excess ram");
460                         delete a;
461                 }
462                 else
463                 {
464                         log(DEBUG,"added fresh WHOWAS entry");
465                         whowas[a->nick] = a;
466                 }
467         }
468         else
469         {
470                 log(DEBUG,"updated WHOWAS entry");
471                 if (iter->second) delete iter->second;
472                 iter->second = a;
473         }
474 }
475
476 /* add a client connection to the sockets list */
477 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
478 {
479         string tempnick;
480         char tn2[MAXBUF];
481         user_hash::iterator iter;
482
483         tempnick = ConvToStr(socket) + "-unknown";
484         sprintf(tn2,"%lu-unknown",(unsigned long)socket);
485
486         iter = clientlist.find(tempnick);
487
488         // fix by brain.
489         // as these nicknames are 'RFC impossible', we can be sure nobody is going to be
490         // using one as a registered connection. As theyre per fd, we can also safely assume
491         // that we wont have collisions. Therefore, if the nick exists in the list, its only
492         // used by a dead socket, erase the iterator so that the new client may reclaim it.
493         // this was probably the cause of 'server ignores me when i hammer it with reconnects'
494         // issue in earlier alphas/betas
495         if (iter != clientlist.end())
496         {
497                 userrec* goner = iter->second;
498                 delete goner;
499                 clientlist.erase(iter);
500         }
501
502         /*
503          * It is OK to access the value here this way since we know
504          * it exists, we just created it above.
505          *
506          * At NO other time should you access a value in a map or a
507          * hash_map this way.
508          */
509         clientlist[tempnick] = new userrec();
510
511         NonBlocking(socket);
512         log(DEBUG,"AddClient: %lu %s %d %s",(unsigned long)socket,host,port,ip);
513
514         clientlist[tempnick]->fd = socket;
515         strlcpy(clientlist[tempnick]->nick, tn2,NICKMAX);
516         strlcpy(clientlist[tempnick]->host, host,160);
517         strlcpy(clientlist[tempnick]->dhost, host,160);
518         clientlist[tempnick]->server = (char*)FindServerNamePtr(Config->ServerName);
519         strlcpy(clientlist[tempnick]->ident, "unknown",IDENTMAX);
520         clientlist[tempnick]->registered = 0;
521         clientlist[tempnick]->signon = TIME + Config->dns_timeout;
522         clientlist[tempnick]->lastping = 1;
523         clientlist[tempnick]->port = port;
524         strlcpy(clientlist[tempnick]->ip,ip,16);
525
526         // set the registration timeout for this user
527         unsigned long class_regtimeout = 90;
528         int class_flood = 0;
529         long class_threshold = 5;
530         long class_sqmax = 262144;      // 256kb
531         long class_rqmax = 4096;        // 4k
532
533         for (ClassVector::iterator i = Config->Classes.begin(); i != Config->Classes.end(); i++)
534         {
535                 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
536                 {
537                         class_regtimeout = (unsigned long)i->registration_timeout;
538                         class_flood = i->flood;
539                         clientlist[tempnick]->pingmax = i->pingtime;
540                         class_threshold = i->threshold;
541                         class_sqmax = i->sendqmax;
542                         class_rqmax = i->recvqmax;
543                         break;
544                 }
545         }
546
547         clientlist[tempnick]->nping = TIME+clientlist[tempnick]->pingmax + Config->dns_timeout;
548         clientlist[tempnick]->timeout = TIME+class_regtimeout;
549         clientlist[tempnick]->flood = class_flood;
550         clientlist[tempnick]->threshold = class_threshold;
551         clientlist[tempnick]->sendqmax = class_sqmax;
552         clientlist[tempnick]->recvqmax = class_rqmax;
553
554         ucrec a;
555         a.channel = NULL;
556         a.uc_modes = 0;
557         for (int i = 0; i < MAXCHANS; i++)
558                 clientlist[tempnick]->chans.push_back(a);
559
560         if (clientlist.size() > Config->SoftLimit)
561         {
562                 kill_link(clientlist[tempnick],"No more connections allowed");
563                 return;
564         }
565
566         if (clientlist.size() >= MAXCLIENTS)
567         {
568                 kill_link(clientlist[tempnick],"No more connections allowed");
569                 return;
570         }
571
572         // this is done as a safety check to keep the file descriptors within range of fd_ref_table.
573         // its a pretty big but for the moment valid assumption:
574         // file descriptors are handed out starting at 0, and are recycled as theyre freed.
575         // therefore if there is ever an fd over 65535, 65536 clients must be connected to the
576         // irc server at once (or the irc server otherwise initiating this many connections, files etc)
577         // which for the time being is a physical impossibility (even the largest networks dont have more
578         // than about 10,000 users on ONE server!)
579         if ((unsigned)socket > 65534)
580         {
581                 kill_link(clientlist[tempnick],"Server is full");
582                 return;
583         }
584         char* e = matches_exception(ip);
585         if (!e)
586         {
587                 char* r = matches_zline(ip);
588                 if (r)
589                 {
590                         char reason[MAXBUF];
591                         snprintf(reason,MAXBUF,"Z-Lined: %s",r);
592                         kill_link(clientlist[tempnick],reason);
593                         return;
594                 }
595         }
596         fd_ref_table[socket] = clientlist[tempnick];
597         SE->AddFd(socket,true,X_ESTAB_CLIENT);
598 }
599
600 void FullConnectUser(userrec* user)
601 {
602         stats->statsConnects++;
603         user->idle_lastmsg = TIME;
604         log(DEBUG,"ConnectUser: %s",user->nick);
605
606         if ((strcmp(Passwd(user),"")) && (!user->haspassed))
607         {
608                 kill_link(user,"Invalid password");
609                 return;
610         }
611         if (IsDenied(user))
612         {
613                 kill_link(user,"Unauthorised connection");
614                 return;
615         }
616
617         char match_against[MAXBUF];
618         snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
619         char* e = matches_exception(match_against);
620         if (!e)
621         {
622                 char* r = matches_gline(match_against);
623                 if (r)
624                 {
625                         char reason[MAXBUF];
626                         snprintf(reason,MAXBUF,"G-Lined: %s",r);
627                         kill_link_silent(user,reason);
628                         return;
629                 }
630                 r = matches_kline(user->host);
631                 if (r)
632                 {
633                         char reason[MAXBUF];
634                         snprintf(reason,MAXBUF,"K-Lined: %s",r);
635                         kill_link_silent(user,reason);
636                         return;
637                 }
638         }
639
640
641         WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Config->Network);
642         WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Config->Network,user->nick,user->ident,user->host);
643         WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,Config->ServerName,VERSION);
644         WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
645         WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,Config->ServerName,VERSION);
646         // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
647         std::stringstream v;
648         v << "WALLCHOPS MODES=13 CHANTYPES=# PREFIX=(ohv)@%+ MAP SAFELIST MAXCHANNELS=" << MAXCHANS;
649         v << " MAXBANS=60 NICKLEN=" << NICKMAX;
650         v << " TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=20 AWAYLEN=" << MAXAWAY << " CHANMODES=ohvb,k,l,psmnti NETWORK=";
651         v << Config->Network;
652         std::string data005 = v.str();
653         FOREACH_MOD On005Numeric(data005);
654         // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
655         // so i'd better split it :)
656         std::stringstream out(data005);
657         std::string token = "";
658         std::string line5 = "";
659         int token_counter = 0;
660         while (!out.eof())
661         {
662                 out >> token;
663                 line5 = line5 + token + " ";
664                 token_counter++;
665                 if ((token_counter >= 13) || (out.eof() == true))
666                 {
667                         WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
668                         line5 = "";
669                         token_counter = 0;
670                 }
671         }
672         ShowMOTD(user);
673
674         // fix 3 by brain, move registered = 7 below these so that spurious modes and host changes dont go out
675         // onto the network and produce 'fake direction'
676         FOREACH_MOD OnUserConnect(user);
677         FOREACH_MOD OnGlobalConnect(user);
678         user->registered = 7;
679         WriteOpers("*** Client connecting on port %lu: %s!%s@%s [%s]",(unsigned long)user->port,user->nick,user->ident,user->host,user->ip);
680 }
681
682
683 /* shows the message of the day, and any other on-logon stuff */
684 void ConnectUser(userrec *user)
685 {
686         // dns is already done, things are fast. no need to wait for dns to complete just pass them straight on
687         if ((user->dns_done) && (user->registered >= 3) && (AllModulesReportReady(user)))
688         {
689                 FullConnectUser(user);
690         }
691 }
692