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