]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd.cpp
Added reference to userprocess.h
[user/henk/code/inspircd.git] / src / inspircd.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  Inspire is copyright (C) 2002-2005 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 /* Now with added unF! ;) */
18
19 using namespace std;
20
21 #include "inspircd_config.h"
22 #include "inspircd.h"
23 #include "inspircd_io.h"
24 #include "inspircd_util.h"
25 #include <unistd.h>
26 #include <fcntl.h>
27 #include <sys/errno.h>
28 #include <sys/ioctl.h>
29 #include <sys/utsname.h>
30 #include <time.h>
31 #include <string>
32 #ifdef GCC3
33 #include <ext/hash_map>
34 #else
35 #include <hash_map>
36 #endif
37 #include <map>
38 #include <sstream>
39 #include <vector>
40 #include <deque>
41 #include <sched.h>
42 #ifdef THREADED_DNS
43 #include <pthread.h>
44 #endif
45 #include "users.h"
46 #include "ctables.h"
47 #include "globals.h"
48 #include "modules.h"
49 #include "dynamic.h"
50 #include "wildcard.h"
51 #include "message.h"
52 #include "mode.h"
53 #include "commands.h"
54 #include "xline.h"
55 #include "inspstring.h"
56 #include "dnsqueue.h"
57 #include "helperfuncs.h"
58 #include "hashcomp.h"
59 #include "socketengine.h"
60 #include "userprocess.h"
61 #include "socket.h"
62 #include "dns.h"
63
64 int LogLevel = DEFAULT;
65 char ServerName[MAXBUF];
66 char Network[MAXBUF];
67 char ServerDesc[MAXBUF];
68 char AdminName[MAXBUF];
69 char AdminEmail[MAXBUF];
70 char AdminNick[MAXBUF];
71 char diepass[MAXBUF];
72 char restartpass[MAXBUF];
73 char motd[MAXBUF];
74 char rules[MAXBUF];
75 char list[MAXBUF];
76 char PrefixQuit[MAXBUF];
77 char DieValue[MAXBUF];
78 char DNSServer[MAXBUF];
79 char data[65536];
80 int debugging =  0;
81 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
82 int WHOWAS_MAX = 100;  // default 100 people maximum in the WHOWAS list
83 int DieDelay  =  5;
84 time_t startup_time = time(NULL);
85 int NetBufferSize = 10240;      // NetBufferSize used as the buffer size for all read() ops
86 int MaxConn = SOMAXCONN;        // size of accept() backlog (128 by default on *BSD)
87 unsigned int SoftLimit = MAXCLIENTS;
88 extern int MaxWhoResults;
89 time_t nb_start = 0;
90 int dns_timeout = 5;
91
92 char DisabledCommands[MAXBUF];
93
94 bool AllowHalfop = true;
95 bool AllowProtect = true;
96 bool AllowFounder = true;
97
98 extern std::vector<Module*> modules;
99 std::vector<std::string> module_names;
100 extern std::vector<ircd_module*> factory;
101
102 std::vector<InspSocket*> module_sockets;
103
104 extern int MODCOUNT;
105 int openSockfd[MAXSOCKS];
106 bool nofork = false;
107 bool unlimitcore = false;
108 struct sockaddr_in client,server;
109 char addrs[MAXBUF][255];
110 socklen_t length;
111 char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
112
113 extern InspSocket* socket_ref[65535];
114
115 time_t TIME = time(NULL), OLDTIME = time(NULL);
116
117 SocketEngine* SE = NULL;
118
119 bool has_been_netsplit = false;
120 extern std::vector<std::string> include_stack;
121
122 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, irc::StrHashComp> user_hash;
123 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, irc::StrHashComp> chan_hash;
124 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, irc::InAddr_HashComp> address_cache;
125 typedef nspace::hash_map<std::string, WhoWasUser*, nspace::hash<string>, irc::StrHashComp> whowas_hash;
126 typedef std::deque<command_t> command_table;
127 typedef std::map<std::string,time_t> autoconnects;
128 typedef std::vector<std::string> servernamelist;
129
130 // This table references users by file descriptor.
131 // its an array to make it VERY fast, as all lookups are referenced
132 // by an integer, meaning there is no need for a scan/search operation.
133 userrec* fd_ref_table[65536];
134
135 int statsAccept = 0, statsRefused = 0, statsUnknown = 0, statsCollisions = 0, statsDns = 0, statsDnsGood = 0, statsDnsBad = 0, statsConnects = 0, statsSent= 0, statsRecv = 0;
136
137 Server* MyServer = new Server;
138
139 FILE *log_file;
140
141 user_hash clientlist;
142 chan_hash chanlist;
143 whowas_hash whowas;
144 command_table cmdlist;
145 autoconnects autoconns;
146 file_cache MOTD;
147 file_cache RULES;
148 address_cache IP;
149
150 ClassVector Classes;
151 servernamelist servernames;
152
153 struct linger linger = { 0 };
154 char MyExecutable[1024];
155 int boundPortCount = 0;
156 int portCount = 0, SERVERportCount = 0, ports[MAXSOCKS];
157
158 char ModPath[MAXBUF];
159
160 /* prototypes */
161
162 int has_channel(userrec *u, chanrec *c);
163 int usercount(chanrec *c);
164 int usercount_i(chanrec *c);
165 char* Passwd(userrec *user);
166 bool IsDenied(userrec *user);
167 void AddWhoWas(userrec* u);
168
169 std::stringstream config_f(stringstream::in | stringstream::out);
170
171 std::vector<userrec*> all_opers;
172
173 char lowermap[255];
174
175 void AddOper(userrec* user)
176 {
177         log(DEBUG,"Oper added to optimization list");
178         all_opers.push_back(user);
179 }
180
181 void AddServerName(std::string servername)
182 {
183         log(DEBUG,"Adding server name: %s",servername.c_str());
184         for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
185         {
186                 if (*a == servername)
187                         return;
188         }
189         servernames.push_back(servername);
190 }
191
192 const char* FindServerNamePtr(std::string servername)
193 {
194         for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
195         {
196                 if (*a == servername)
197                         return a->c_str();
198         }
199         AddServerName(servername);
200         return FindServerNamePtr(servername);
201 }
202
203 void DeleteOper(userrec* user)
204 {
205         for (std::vector<userrec*>::iterator a = all_opers.begin(); a < all_opers.end(); a++)
206         {
207                 if (*a == user)
208                 {
209                         log(DEBUG,"Oper removed from optimization list");
210                         all_opers.erase(a);
211                         return;
212                 }
213         }
214 }
215
216 std::string GetRevision()
217 {
218         char Revision[] = "$Revision$";
219         char *s1 = Revision;
220         char *savept;
221         char *v2 = strtok_r(s1," ",&savept);
222         s1 = savept;
223         v2 = strtok_r(s1," ",&savept);
224         s1 = savept;
225         return std::string(v2);
226 }
227
228
229 std::string getservername()
230 {
231         return ServerName;
232 }
233
234 std::string getserverdesc()
235 {
236         return ServerDesc;
237 }
238
239 std::string getnetworkname()
240 {
241         return Network;
242 }
243
244 std::string getadminname()
245 {
246         return AdminName;
247 }
248
249 std::string getadminemail()
250 {
251         return AdminEmail;
252 }
253
254 std::string getadminnick()
255 {
256         return AdminNick;
257 }
258
259 void ReadConfig(bool bail, userrec* user)
260 {
261         char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF],MW[MAXBUF],MCON[MAXBUF];
262         char AH[MAXBUF],AP[MAXBUF],AF[MAXBUF],DNT[MAXBUF],pfreq[MAXBUF],thold[MAXBUF],sqmax[MAXBUF],rqmax[MAXBUF],SLIMT[MAXBUF];
263         ConnectClass c;
264         std::stringstream errstr;
265         include_stack.clear();
266         
267         if (!LoadConf(CONFIG_FILE,&config_f,&errstr))
268         {
269                 errstr.seekg(0);
270                 log(DEFAULT,"There were errors in your configuration:\n%s",errstr.str().c_str());
271                 if (bail)
272                 {
273                         printf("There were errors in your configuration:\n%s",errstr.str().c_str());
274                         Exit(0);
275                 }
276                 else
277                 {
278                         char dataline[1024];
279                         if (user)
280                         {
281                                 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
282                                 while (!errstr.eof())
283                                 {
284                                         errstr.getline(dataline,1024);
285                                         WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline);
286                                 }
287                         }
288                         else
289                         {
290                                 WriteOpers("There were errors in the configuration file:");
291                                 while (!errstr.eof())
292                                 {
293                                         errstr.getline(dataline,1024);
294                                         WriteOpers(dataline);
295                                 }
296                         }
297                         return;
298                 }
299         }
300           
301         ConfValue("server","name",0,ServerName,&config_f);
302         ConfValue("server","description",0,ServerDesc,&config_f);
303         ConfValue("server","network",0,Network,&config_f);
304         ConfValue("admin","name",0,AdminName,&config_f);
305         ConfValue("admin","email",0,AdminEmail,&config_f);
306         ConfValue("admin","nick",0,AdminNick,&config_f);
307         ConfValue("files","motd",0,motd,&config_f);
308         ConfValue("files","rules",0,rules,&config_f);
309         ConfValue("power","diepass",0,diepass,&config_f);
310         ConfValue("power","pause",0,pauseval,&config_f);
311         ConfValue("power","restartpass",0,restartpass,&config_f);
312         ConfValue("options","prefixquit",0,PrefixQuit,&config_f);
313         ConfValue("die","value",0,DieValue,&config_f);
314         ConfValue("options","loglevel",0,dbg,&config_f);
315         ConfValue("options","netbuffersize",0,NB,&config_f);
316         ConfValue("options","maxwho",0,MW,&config_f);
317         ConfValue("options","allowhalfop",0,AH,&config_f);
318         ConfValue("options","allowprotect",0,AP,&config_f);
319         ConfValue("options","allowfounder",0,AF,&config_f);
320         ConfValue("dns","server",0,DNSServer,&config_f);
321         ConfValue("dns","timeout",0,DNT,&config_f);
322         ConfValue("options","moduledir",0,ModPath,&config_f);
323         ConfValue("disabled","commands",0,DisabledCommands,&config_f);
324         ConfValue("options","somaxconn",0,MCON,&config_f);
325         ConfValue("options","softlimit",0,SLIMT,&config_f);
326
327         SoftLimit = atoi(SLIMT);
328         if ((SoftLimit < 1) || (SoftLimit > MAXCLIENTS))
329         {
330                 log(DEFAULT,"WARNING: <options:softlimit> value is greater than %d or less than 0, set to %d.",MAXCLIENTS,MAXCLIENTS);
331                 SoftLimit = MAXCLIENTS;
332         }
333         MaxConn = atoi(MCON);
334         if (MaxConn > SOMAXCONN)
335                 log(DEFAULT,"WARNING: <options:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
336         NetBufferSize = atoi(NB);
337         MaxWhoResults = atoi(MW);
338         dns_timeout = atoi(DNT);
339         if (!dns_timeout)
340                 dns_timeout = 5;
341         if (!MaxConn)
342                 MaxConn = SOMAXCONN;
343         if (!DNSServer[0])
344                 strlcpy(DNSServer,"127.0.0.1",MAXBUF);
345         if (!ModPath[0])
346                 strlcpy(ModPath,MOD_PATH,MAXBUF);
347         AllowHalfop = ((!strcasecmp(AH,"true")) || (!strcasecmp(AH,"1")) || (!strcasecmp(AH,"yes")));
348         AllowProtect = ((!strcasecmp(AP,"true")) || (!strcasecmp(AP,"1")) || (!strcasecmp(AP,"yes")));
349         AllowFounder = ((!strcasecmp(AF,"true")) || (!strcasecmp(AF,"1")) || (!strcasecmp(AF,"yes")));
350         if ((!NetBufferSize) || (NetBufferSize > 65535) || (NetBufferSize < 1024))
351         {
352                 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
353                 NetBufferSize = 10240;
354         }
355         if ((!MaxWhoResults) || (MaxWhoResults > 65535) || (MaxWhoResults < 1))
356         {
357                 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
358                 MaxWhoResults = 128;
359         }
360         if (!strcmp(dbg,"debug"))
361                 LogLevel = DEBUG;
362         if (!strcmp(dbg,"verbose"))
363                 LogLevel = VERBOSE;
364         if (!strcmp(dbg,"default"))
365                 LogLevel = DEFAULT;
366         if (!strcmp(dbg,"sparse"))
367                 LogLevel = SPARSE;
368         if (!strcmp(dbg,"none"))
369                 LogLevel = NONE;
370         readfile(MOTD,motd);
371         log(DEFAULT,"Reading message of the day...");
372         readfile(RULES,rules);
373         log(DEFAULT,"Reading connect classes...");
374         Classes.clear();
375         for (int i = 0; i < ConfValueEnum("connect",&config_f); i++)
376         {
377                 strcpy(Value,"");
378                 ConfValue("connect","allow",i,Value,&config_f);
379                 ConfValue("connect","timeout",i,timeout,&config_f);
380                 ConfValue("connect","flood",i,flood,&config_f);
381                 ConfValue("connect","pingfreq",i,pfreq,&config_f);
382                 ConfValue("connect","threshold",i,thold,&config_f);
383                 ConfValue("connect","sendq",i,sqmax,&config_f);
384                 ConfValue("connect","recvq",i,rqmax,&config_f);
385                 if (Value[0])
386                 {
387                         strlcpy(c.host,Value,MAXBUF);
388                         c.type = CC_ALLOW;
389                         strlcpy(Value,"",MAXBUF);
390                         ConfValue("connect","password",i,Value,&config_f);
391                         strlcpy(c.pass,Value,MAXBUF);
392                         c.registration_timeout = 90; // default is 2 minutes
393                         c.pingtime = 120;
394                         c.flood = atoi(flood);
395                         c.threshold = 5;
396                         c.sendqmax = 262144; // 256k
397                         c.recvqmax = 4096;   // 4k
398                         if (atoi(thold)>0)
399                         {
400                                 c.threshold = atoi(thold);
401                         }
402                         if (atoi(sqmax)>0)
403                         {
404                                 c.sendqmax = atoi(sqmax);
405                         }
406                         if (atoi(rqmax)>0)
407                         {
408                                 c.recvqmax = atoi(rqmax);
409                         }
410                         if (atoi(timeout)>0)
411                         {
412                                 c.registration_timeout = atoi(timeout);
413                         }
414                         if (atoi(pfreq)>0)
415                         {
416                                 c.pingtime = atoi(pfreq);
417                         }
418                         Classes.push_back(c);
419                         log(DEBUG,"Read connect class type ALLOW, host=%s password=%s timeout=%lu flood=%lu",c.host,c.pass,(unsigned long)c.registration_timeout,(unsigned long)c.flood);
420                 }
421                 else
422                 {
423                         ConfValue("connect","deny",i,Value,&config_f);
424                         strlcpy(c.host,Value,MAXBUF);
425                         c.type = CC_DENY;
426                         Classes.push_back(c);
427                         log(DEBUG,"Read connect class type DENY, host=%s",c.host);
428                 }
429         
430         }
431         log(DEFAULT,"Reading K lines,Q lines and Z lines from config...");
432         read_xline_defaults();
433         log(DEFAULT,"Applying K lines, Q lines and Z lines...");
434         apply_lines();
435
436         autoconns.clear();
437         for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
438         {
439                 char Link_ServerName[MAXBUF],Link_AConn[MAXBUF];
440                 ConfValue("link","name",i,Link_ServerName,&config_f);
441                 ConfValue("link","autoconnect",i,Link_AConn,&config_f);
442                 if (strcmp(Link_AConn,""))
443                 {
444                         autoconns[std::string(Link_ServerName)] = atoi(Link_AConn) + time(NULL);
445                 }
446         }
447
448
449         log(DEFAULT,"Done reading configuration file, InspIRCd is now starting.");
450         if (!bail)
451         {
452                 log(DEFAULT,"Adding and removing modules due to rehash...");
453
454                 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
455
456                 // store the old module names
457                 for (std::vector<std::string>::iterator t = module_names.begin(); t != module_names.end(); t++)
458                 {
459                         old_module_names.push_back(*t);
460                 }
461
462                 // get the new module names
463                 for (int count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
464                 {
465                         ConfValue("module","name",count2,Value,&config_f);
466                         new_module_names.push_back(Value);
467                 }
468
469                 // now create a list of new modules that are due to be loaded
470                 // and a seperate list of modules which are due to be unloaded
471                 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
472                 {
473                         bool added = true;
474                         for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
475                         {
476                                 if (*old == *_new)
477                                         added = false;
478                         }
479                         if (added)
480                                 added_modules.push_back(*_new);
481                 }
482                 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
483                 {
484                         bool removed = true;
485                         for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
486                         {
487                                 if (*newm == *oldm)
488                                         removed = false;
489                         }
490                         if (removed)
491                                 removed_modules.push_back(*oldm);
492                 }
493                 // now we have added_modules, a vector of modules to be loaded, and removed_modules, a vector of modules
494                 // to be removed.
495                 int rem = 0, add = 0;
496                 if (!removed_modules.empty())
497                 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
498                 {
499                         if (UnloadModule(removing->c_str()))
500                         {
501                                 WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
502                                 WriteServ(user->fd,"973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
503                                 rem++;
504                         }
505                         else
506                         {
507                                 WriteServ(user->fd,"972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ModuleError());
508                         }
509                 }
510                 if (!added_modules.empty())
511                 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
512                 {
513                         if (LoadModule(adding->c_str()))
514                         {
515                                 WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
516                                 WriteServ(user->fd,"975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
517                                 add++;
518                         }
519                         else
520                         {
521                                 WriteServ(user->fd,"974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ModuleError());
522                         }
523                 }
524                 log(DEFAULT,"Successfully unloaded %lu of %lu modules and loaded %lu of %lu modules.",(unsigned long)rem,(unsigned long)removed_modules.size(),(unsigned long)add,(unsigned long)added_modules.size());
525         }
526 }
527
528
529 /* add a channel to a user, creating the record for it if needed and linking
530  * it to the user record */
531
532 chanrec* add_channel(userrec *user, const char* cn, const char* key, bool override)
533 {
534         if ((!user) || (!cn))
535         {
536                 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
537                 return 0;
538         }
539
540         chanrec* Ptr;
541         int created = 0;
542         char cname[MAXBUF];
543
544         strncpy(cname,cn,MAXBUF);
545         
546         // we MUST declare this wherever we use FOREACH_RESULT
547         int MOD_RESULT = 0;
548
549         if (strlen(cname) > CHANMAX)
550         {
551                 cname[CHANMAX] = '\0';
552         }
553
554         log(DEBUG,"add_channel: %s %s",user->nick,cname);
555         
556         if ((FindChan(cname)) && (has_channel(user,FindChan(cname))))
557         {
558                 return NULL; // already on the channel!
559         }
560
561
562         if (!FindChan(cname))
563         {
564                 if (!strcasecmp(ServerName,user->server))
565                 {
566                         MOD_RESULT = 0;
567                         FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
568                         if (MOD_RESULT == 1) {
569                                 return NULL;
570                         }
571                 }
572
573                 /* create a new one */
574                 log(DEBUG,"add_channel: creating: %s",cname);
575                 {
576                         chanlist[cname] = new chanrec();
577
578                         strlcpy(chanlist[cname]->name, cname,CHANMAX);
579                         chanlist[cname]->binarymodes = CM_TOPICLOCK | CM_NOEXTERNAL;
580                         chanlist[cname]->created = TIME;
581                         strcpy(chanlist[cname]->topic, "");
582                         strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
583                         chanlist[cname]->topicset = 0;
584                         Ptr = chanlist[cname];
585                         log(DEBUG,"add_channel: created: %s",cname);
586                         /* set created to 2 to indicate user
587                          * is the first in the channel
588                          * and should be given ops */
589                         created = 2;
590                 }
591         }
592         else
593         {
594                 /* channel exists, just fish out a pointer to its struct */
595                 Ptr = FindChan(cname);
596                 if (Ptr)
597                 {
598                         log(DEBUG,"add_channel: joining to: %s",Ptr->name);
599                         
600                         // remote users are allowed us to bypass channel modes
601                         // and bans (used by servers)
602                         if (!strcasecmp(ServerName,user->server))
603                         {
604                                 log(DEBUG,"Not overriding...");
605                                 MOD_RESULT = 0;
606                                 FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
607                                 if (MOD_RESULT == 1) {
608                                         return NULL;
609                                 }
610                                 log(DEBUG,"MOD_RESULT=%d",MOD_RESULT);
611                                 
612                                 if (!MOD_RESULT) 
613                                 {
614                                         log(DEBUG,"add_channel: checking key, invite, etc");
615                                         MOD_RESULT = 0;
616                                         FOREACH_RESULT(OnCheckKey(user, Ptr, key ? key : ""));
617                                         if (MOD_RESULT == 0)
618                                         {
619                                                 if (Ptr->key[0])
620                                                 {
621                                                         log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
622                                                         if (!key)
623                                                         {
624                                                                 log(DEBUG,"add_channel: no key given in JOIN");
625                                                                 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
626                                                                 return NULL;
627                                                         }
628                                                         else
629                                                         {
630                                                                 if (strcasecmp(key,Ptr->key))
631                                                                 {
632                                                                         log(DEBUG,"add_channel: bad key given in JOIN");
633                                                                         WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
634                                                                         return NULL;
635                                                                 }
636                                                         }
637                                                 }
638                                                 log(DEBUG,"add_channel: no key");
639                                         }
640                                         MOD_RESULT = 0;
641                                         FOREACH_RESULT(OnCheckInvite(user, Ptr));
642                                         if (MOD_RESULT == 0)
643                                         {
644                                                 if (Ptr->binarymodes & CM_INVITEONLY)
645                                                 {
646                                                         log(DEBUG,"add_channel: channel is +i");
647                                                         if (user->IsInvited(Ptr->name))
648                                                         {
649                                                                 /* user was invited to channel */
650                                                                 /* there may be an optional channel NOTICE here */
651                                                         }
652                                                         else
653                                                         {
654                                                                 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
655                                                                 return NULL;
656                                                         }
657                                                 }
658                                                 log(DEBUG,"add_channel: channel is not +i");
659                                         }
660                                         MOD_RESULT = 0;
661                                         FOREACH_RESULT(OnCheckLimit(user, Ptr));
662                                         if (MOD_RESULT == 0)
663                                         {
664                                                 if (Ptr->limit)
665                                                 {
666                                                         if (usercount(Ptr) >= Ptr->limit)
667                                                         {
668                                                                 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
669                                                                 return NULL;
670                                                         }
671                                                 }
672                                         }
673                                         log(DEBUG,"add_channel: about to walk banlist");
674                                         MOD_RESULT = 0;
675                                         FOREACH_RESULT(OnCheckBan(user, Ptr));
676                                         if (MOD_RESULT == 0)
677                                         {
678                                                 /* check user against the channel banlist */
679                                                 if (Ptr)
680                                                 {
681                                                         if (Ptr->bans.size())
682                                                         {
683                                                                 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
684                                                                 {
685                                                                         if (match(user->GetFullHost(),i->data))
686                                                                         {
687                                                                                 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
688                                                                                 return NULL;
689                                                                         }
690                                                                 }
691                                                         }
692                                                 }
693                                                 log(DEBUG,"add_channel: bans checked");
694                                         }
695                                 
696                                 }
697                                 
698
699                                 if ((Ptr) && (user))
700                                 {
701                                         user->RemoveInvite(Ptr->name);
702                                 }
703         
704                                 log(DEBUG,"add_channel: invites removed");
705
706                         }
707                         else
708                         {
709                                 log(DEBUG,"Overridden checks");
710                         }
711
712                         
713                 }
714                 created = 1;
715         }
716
717         log(DEBUG,"Passed channel checks");
718         
719         for (int index =0; index != MAXCHANS; index++)
720         {
721                 log(DEBUG,"Check location %d",index);
722                 if (user->chans[index].channel == NULL)
723                 {
724                         log(DEBUG,"Adding into their channel list at location %d",index);
725
726                         if (created == 2) 
727                         {
728                                 /* first user in is given ops */
729                                 user->chans[index].uc_modes = UCMODE_OP;
730                         }
731                         else
732                         {
733                                 user->chans[index].uc_modes = 0;
734                         }
735                         user->chans[index].channel = Ptr;
736                         Ptr->AddUser((char*)user);
737                         WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
738                         
739                         log(DEBUG,"Sent JOIN to client");
740
741                         if (Ptr->topicset)
742                         {
743                                 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
744                                 WriteServ(user->fd,"333 %s %s %s %lu", user->nick, Ptr->name, Ptr->setby, (unsigned long)Ptr->topicset);
745                         }
746                         userlist(user,Ptr);
747                         WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
748                         //WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
749                         //WriteServ(user->fd,"329 %s %s %lu", user->nick, Ptr->name, (unsigned long)Ptr->created);
750                         FOREACH_MOD OnUserJoin(user,Ptr);
751                         return Ptr;
752                 }
753         }
754         log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
755         WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
756         return NULL;
757 }
758
759 /* remove a channel from a users record, and remove the record from memory
760  * if the channel has become empty */
761
762 chanrec* del_channel(userrec *user, const char* cname, const char* reason, bool local)
763 {
764         if ((!user) || (!cname))
765         {
766                 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
767                 return NULL;
768         }
769
770         chanrec* Ptr;
771
772         if ((!cname) || (!user))
773         {
774                 return NULL;
775         }
776
777         Ptr = FindChan(cname);
778         
779         if (!Ptr)
780         {
781                 return NULL;
782         }
783
784         FOREACH_MOD OnUserPart(user,Ptr);
785         log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
786         
787         for (int i =0; i != MAXCHANS; i++)
788         {
789                 /* zap it from the channel list of the user */
790                 if (user->chans[i].channel == Ptr)
791                 {
792                         if (reason)
793                         {
794                                 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
795                         }
796                         else
797                         {
798                                 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
799                         }
800                         user->chans[i].uc_modes = 0;
801                         user->chans[i].channel = NULL;
802                         log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
803                         break;
804                 }
805         }
806
807         Ptr->DelUser((char*)user);
808         
809         /* if there are no users left on the channel */
810         if (!usercount(Ptr))
811         {
812                 chan_hash::iterator iter = chanlist.find(Ptr->name);
813
814                 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
815
816                 /* kill the record */
817                 if (iter != chanlist.end())
818                 {
819                         log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
820                         delete Ptr;
821                         chanlist.erase(iter);
822                 }
823         }
824
825         return NULL;
826 }
827
828
829 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
830 {
831         if ((!src) || (!user) || (!Ptr) || (!reason))
832         {
833                 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
834                 return;
835         }
836
837         if ((!Ptr) || (!user) || (!src))
838         {
839                 return;
840         }
841
842         log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
843
844         if (!has_channel(user,Ptr))
845         {
846                 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
847                 return;
848         }
849
850         int MOD_RESULT = 0;
851         FOREACH_RESULT(OnAccessCheck(src,user,Ptr,AC_KICK));
852         if ((MOD_RESULT == ACR_DENY) && (!is_uline(src->server)))
853                 return;
854
855         if ((MOD_RESULT == ACR_DEFAULT) || (!is_uline(src->server)))
856         {
857                 if ((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr)))
858                 {
859                         if (cstatus(src,Ptr) == STATUS_HOP)
860                         {
861                                 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
862                         }
863                         else
864                         {
865                                 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
866                         }
867                         
868                         return;
869                 }
870         }
871
872         if (!is_uline(src->server))
873         {
874                 MOD_RESULT = 0;
875                 FOREACH_RESULT(OnUserPreKick(src,user,Ptr,reason));
876                 if (MOD_RESULT)
877                         return;
878         }
879
880         FOREACH_MOD OnUserKick(src,user,Ptr,reason);
881
882         for (int i =0; i != MAXCHANS; i++)
883         {
884                 /* zap it from the channel list of the user */
885                 if (user->chans[i].channel)
886                 if (!strcasecmp(user->chans[i].channel->name,Ptr->name))
887                 {
888                         WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
889                         user->chans[i].uc_modes = 0;
890                         user->chans[i].channel = NULL;
891                         log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
892                         break;
893                 }
894         }
895
896         Ptr->DelUser((char*)user);
897
898         /* if there are no users left on the channel */
899         if (!usercount(Ptr))
900         {
901                 chan_hash::iterator iter = chanlist.find(Ptr->name);
902
903                 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
904
905                 /* kill the record */
906                 if (iter != chanlist.end())
907                 {
908                         log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
909                         delete Ptr;
910                         chanlist.erase(iter);
911                 }
912         }
913 }
914
915
916
917
918 /* This function pokes and hacks at a parameter list like the following:
919  *
920  * PART #winbot,#darkgalaxy :m00!
921  *
922  * to turn it into a series of individual calls like this:
923  *
924  * PART #winbot :m00!
925  * PART #darkgalaxy :m00!
926  *
927  * The seperate calls are sent to a callback function provided by the caller
928  * (the caller will usually call itself recursively). The callback function
929  * must be a command handler. Calling this function on a line with no list causes
930  * no action to be taken. You must provide a starting and ending parameter number
931  * where the range of the list can be found, useful if you have a terminating
932  * parameter as above which is actually not part of the list, or parameters
933  * before the actual list as well. This code is used by many functions which
934  * can function as "one to list" (see the RFC) */
935
936 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
937 {
938         char plist[MAXBUF];
939         char *param;
940         char *pars[32];
941         char blog[32][MAXBUF];
942         char blog2[32][MAXBUF];
943         int j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
944         char keystr[MAXBUF];
945         char moo[MAXBUF];
946
947         for (int i = 0; i <32; i++)
948                 strcpy(blog[i],"");
949
950         for (int i = 0; i <32; i++)
951                 strcpy(blog2[i],"");
952
953         strcpy(moo,"");
954         for (int i = 0; i <10; i++)
955         {
956                 if (!parameters[i])
957                 {
958                         parameters[i] = moo;
959                 }
960         }
961         if (joins)
962         {
963                 if (pcnt > 1) /* we have a key to copy */
964                 {
965                         strlcpy(keystr,parameters[1],MAXBUF);
966                 }
967         }
968
969         if (!parameters[start])
970         {
971                 return 0;
972         }
973         if (!strchr(parameters[start],','))
974         {
975                 return 0;
976         }
977         strcpy(plist,"");
978         for (int i = start; i <= end; i++)
979         {
980                 if (parameters[i])
981                 {
982                         strlcat(plist,parameters[i],MAXBUF);
983                 }
984         }
985         
986         j = 0;
987         param = plist;
988
989         t = strlen(plist);
990         for (int i = 0; i < t; i++)
991         {
992                 if (plist[i] == ',')
993                 {
994                         plist[i] = '\0';
995                         strlcpy(blog[j++],param,MAXBUF);
996                         param = plist+i+1;
997                         if (j>20)
998                         {
999                                 WriteServ(u->fd,"407 %s %s :Too many targets in list, message not delivered.",u->nick,blog[j-1]);
1000                                 return 1;
1001                         }
1002                 }
1003         }
1004         strlcpy(blog[j++],param,MAXBUF);
1005         total = j;
1006
1007         if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
1008         {
1009                 strcat(keystr,",");
1010         }
1011         
1012         if ((joins) && (keystr))
1013         {
1014                 if (strchr(keystr,','))
1015                 {
1016                         j = 0;
1017                         param = keystr;
1018                         t2 = strlen(keystr);
1019                         for (int i = 0; i < t2; i++)
1020                         {
1021                                 if (keystr[i] == ',')
1022                                 {
1023                                         keystr[i] = '\0';
1024                                         strlcpy(blog2[j++],param,MAXBUF);
1025                                         param = keystr+i+1;
1026                                 }
1027                         }
1028                         strlcpy(blog2[j++],param,MAXBUF);
1029                         total2 = j;
1030                 }
1031         }
1032
1033         for (j = 0; j < total; j++)
1034         {
1035                 if (blog[j])
1036                 {
1037                         pars[0] = blog[j];
1038                 }
1039                 for (q = end; q < pcnt-1; q++)
1040                 {
1041                         if (parameters[q+1])
1042                         {
1043                                 pars[q-end+1] = parameters[q+1];
1044                         }
1045                 }
1046                 if ((joins) && (parameters[1]))
1047                 {
1048                         if (pcnt > 1)
1049                         {
1050                                 pars[1] = blog2[j];
1051                         }
1052                         else
1053                         {
1054                                 pars[1] = NULL;
1055                         }
1056                 }
1057                 /* repeatedly call the function with the hacked parameter list */
1058                 if ((joins) && (pcnt > 1))
1059                 {
1060                         if (pars[1])
1061                         {
1062                                 // pars[1] already set up and containing key from blog2[j]
1063                                 fn(pars,2,u);
1064                         }
1065                         else
1066                         {
1067                                 pars[1] = parameters[1];
1068                                 fn(pars,2,u);
1069                         }
1070                 }
1071                 else
1072                 {
1073                         fn(pars,pcnt-(end-start),u);
1074                 }
1075         }
1076
1077         return 1;
1078 }
1079
1080
1081
1082 void kill_link(userrec *user,const char* r)
1083 {
1084         user_hash::iterator iter = clientlist.find(user->nick);
1085         
1086         char reason[MAXBUF];
1087         
1088         strncpy(reason,r,MAXBUF);
1089
1090         if (strlen(reason)>MAXQUIT)
1091         {
1092                 reason[MAXQUIT-1] = '\0';
1093         }
1094
1095         log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1096         Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1097         log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
1098
1099         if (user->registered == 7) {
1100                 FOREACH_MOD OnUserQuit(user,reason);
1101                 WriteCommonExcept(user,"QUIT :%s",reason);
1102         }
1103
1104         user->FlushWriteBuf();
1105
1106         FOREACH_MOD OnUserDisconnect(user);
1107
1108         if (user->fd > -1)
1109         {
1110                 FOREACH_MOD OnRawSocketClose(user->fd);
1111                 SE->DelFd(user->fd);
1112                 user->CloseSocket();
1113         }
1114
1115         // this must come before the WriteOpers so that it doesnt try to fill their buffer with anything
1116         // if they were an oper with +s.
1117         if (user->registered == 7) {
1118                 purge_empty_chans(user);
1119                 // fix by brain: only show local quits because we only show local connects (it just makes SENSE)
1120                 if (!strcmp(user->server,ServerName))
1121                         WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
1122                 AddWhoWas(user);
1123         }
1124
1125         if (iter != clientlist.end())
1126         {
1127                 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
1128                 if (user->fd > -1)
1129                         fd_ref_table[user->fd] = NULL;
1130                 clientlist.erase(iter);
1131         }
1132         delete user;
1133 }
1134
1135 void kill_link_silent(userrec *user,const char* r)
1136 {
1137         user_hash::iterator iter = clientlist.find(user->nick);
1138         
1139         char reason[MAXBUF];
1140         
1141         strncpy(reason,r,MAXBUF);
1142
1143         if (strlen(reason)>MAXQUIT)
1144         {
1145                 reason[MAXQUIT-1] = '\0';
1146         }
1147
1148         log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1149         Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1150         log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
1151
1152         user->FlushWriteBuf();
1153
1154         if (user->registered == 7) {
1155                 FOREACH_MOD OnUserQuit(user,reason);
1156                 WriteCommonExcept(user,"QUIT :%s",reason);
1157         }
1158
1159         FOREACH_MOD OnUserDisconnect(user);
1160
1161         if (user->fd > -1)
1162         {
1163                 FOREACH_MOD OnRawSocketClose(user->fd);
1164                 SE->DelFd(user->fd);
1165                 user->CloseSocket();
1166         }
1167
1168         if (user->registered == 7) {
1169                 purge_empty_chans(user);
1170         }
1171         
1172         if (iter != clientlist.end())
1173         {
1174                 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
1175                 if (user->fd > -1)
1176                         fd_ref_table[user->fd] = NULL;
1177                 clientlist.erase(iter);
1178         }
1179         delete user;
1180 }
1181
1182
1183 int main(int argc, char** argv)
1184 {
1185         Start();
1186         srand(time(NULL));
1187         log(DEBUG,"*** InspIRCd starting up!");
1188         if (!FileExists(CONFIG_FILE))
1189         {
1190                 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
1191                 log(DEFAULT,"main: no config");
1192                 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
1193                 Exit(ERROR);
1194         }
1195         if (argc > 1) {
1196                 for (int i = 1; i < argc; i++)
1197                 {
1198                         if (!strcmp(argv[i],"-nofork")) {
1199                                 nofork = true;
1200                         }
1201                         if (!strcmp(argv[i],"-wait")) {
1202                                 sleep(6);
1203                         }
1204                         if (!strcmp(argv[i],"-nolimit")) {
1205                                 unlimitcore = true;
1206                         }
1207                 }
1208         }
1209
1210         strlcpy(MyExecutable,argv[0],MAXBUF);
1211         
1212         // initialize the lowercase mapping table
1213         for (unsigned int cn = 0; cn < 256; cn++)
1214                 lowermap[cn] = cn;
1215         // lowercase the uppercase chars
1216         for (unsigned int cn = 65; cn < 91; cn++)
1217                 lowermap[cn] = tolower(cn);
1218         // now replace the specific chars for scandanavian comparison
1219         lowermap[(unsigned)'['] = '{';
1220         lowermap[(unsigned)']'] = '}';
1221         lowermap[(unsigned)'\\'] = '|';
1222
1223         if (InspIRCd(argv,argc) == ERROR)
1224         {
1225                 log(DEFAULT,"main: daemon function bailed");
1226                 printf("ERROR: could not initialise. Shutting down.\n");
1227                 Exit(ERROR);
1228         }
1229         Exit(TRUE);
1230         return 0;
1231 }
1232
1233 template<typename T> inline string ConvToStr(const T &in)
1234 {
1235         stringstream tmp;
1236         if (!(tmp << in)) return string();
1237         return tmp.str();
1238 }
1239
1240 /* re-allocates a nick in the user_hash after they change nicknames,
1241  * returns a pointer to the new user as it may have moved */
1242
1243 userrec* ReHashNick(char* Old, char* New)
1244 {
1245         //user_hash::iterator newnick;
1246         user_hash::iterator oldnick = clientlist.find(Old);
1247
1248         log(DEBUG,"ReHashNick: %s %s",Old,New);
1249         
1250         if (!strcasecmp(Old,New))
1251         {
1252                 log(DEBUG,"old nick is new nick, skipping");
1253                 return oldnick->second;
1254         }
1255         
1256         if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
1257
1258         log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
1259
1260         userrec* olduser = oldnick->second;
1261         clientlist[New] = olduser;
1262         clientlist.erase(oldnick);
1263
1264         log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
1265         
1266         return clientlist[New];
1267 }
1268
1269 /* adds or updates an entry in the whowas list */
1270 void AddWhoWas(userrec* u)
1271 {
1272         whowas_hash::iterator iter = whowas.find(u->nick);
1273         WhoWasUser *a = new WhoWasUser();
1274         strlcpy(a->nick,u->nick,NICKMAX);
1275         strlcpy(a->ident,u->ident,IDENTMAX);
1276         strlcpy(a->dhost,u->dhost,160);
1277         strlcpy(a->host,u->host,160);
1278         strlcpy(a->fullname,u->fullname,MAXGECOS);
1279         strlcpy(a->server,u->server,256);
1280         a->signon = u->signon;
1281
1282         /* MAX_WHOWAS:   max number of /WHOWAS items
1283          * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
1284          *               can be replaced by a newer one
1285          */
1286         
1287         if (iter == whowas.end())
1288         {
1289                 if (whowas.size() >= (unsigned)WHOWAS_MAX)
1290                 {
1291                         for (whowas_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
1292                         {
1293                                 // 3600 seconds in an hour ;)
1294                                 if ((i->second->signon)<(TIME-(WHOWAS_STALE*3600)))
1295                                 {
1296                                         // delete the old one
1297                                         if (i->second) delete i->second;
1298                                         // replace with new one
1299                                         i->second = a;
1300                                         log(DEBUG,"added WHOWAS entry, purged an old record");
1301                                         return;
1302                                 }
1303                         }
1304                         // no space left and user doesnt exist. Don't leave ram in use!
1305                         log(DEBUG,"Not able to update whowas (list at WHOWAS_MAX entries and trying to add new?), freeing excess ram");
1306                         delete a;
1307                 }
1308                 else
1309                 {
1310                         log(DEBUG,"added fresh WHOWAS entry");
1311                         whowas[a->nick] = a;
1312                 }
1313         }
1314         else
1315         {
1316                 log(DEBUG,"updated WHOWAS entry");
1317                 if (iter->second) delete iter->second;
1318                 iter->second = a;
1319         }
1320 }
1321
1322 #ifdef THREADED_DNS
1323 void* dns_task(void* arg)
1324 {
1325         userrec* u = (userrec*)arg;
1326         log(DEBUG,"DNS thread for user %s",u->nick);
1327         DNS dns1;
1328         DNS dns2;
1329         std::string host;
1330         std::string ip;
1331         if (dns1.ReverseLookup(u->ip))
1332         {
1333                 log(DEBUG,"DNS Step 1");
1334                 while (!dns1.HasResult())
1335                 {
1336                         usleep(100);
1337                 }
1338                 host = dns1.GetResult();
1339                 if (host != "")
1340                 {
1341                         log(DEBUG,"DNS Step 2: '%s'",host.c_str());
1342                         if (dns2.ForwardLookup(host))
1343                         {
1344                                 while (!dns2.HasResult())
1345                                 {
1346                                         usleep(100);
1347                                 }
1348                                 ip = dns2.GetResultIP();
1349                                 log(DEBUG,"DNS Step 3 '%s'(%d) '%s'(%d)",ip.c_str(),ip.length(),u->ip,strlen(u->ip));
1350                                 if (ip == std::string(u->ip))
1351                                 {
1352                                         log(DEBUG,"DNS Step 4");
1353                                         if (host.length() < 160)
1354                                         {
1355                                                 log(DEBUG,"DNS Step 5");
1356                                                 strcpy(u->host,host.c_str());
1357                                                 strcpy(u->dhost,host.c_str());
1358                                         }
1359                                 }
1360                         }
1361                 }
1362         }
1363         u->dns_done = true;
1364         return NULL;
1365 }
1366 #endif
1367
1368 /* add a client connection to the sockets list */
1369 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
1370 {
1371         string tempnick;
1372         char tn2[MAXBUF];
1373         user_hash::iterator iter;
1374
1375         tempnick = ConvToStr(socket) + "-unknown";
1376         sprintf(tn2,"%lu-unknown",(unsigned long)socket);
1377
1378         iter = clientlist.find(tempnick);
1379
1380         // fix by brain.
1381         // as these nicknames are 'RFC impossible', we can be sure nobody is going to be
1382         // using one as a registered connection. As theyre per fd, we can also safely assume
1383         // that we wont have collisions. Therefore, if the nick exists in the list, its only
1384         // used by a dead socket, erase the iterator so that the new client may reclaim it.
1385         // this was probably the cause of 'server ignores me when i hammer it with reconnects'
1386         // issue in earlier alphas/betas
1387         if (iter != clientlist.end())
1388         {
1389                 userrec* goner = iter->second;
1390                 delete goner;
1391                 clientlist.erase(iter);
1392         }
1393
1394         /*
1395          * It is OK to access the value here this way since we know
1396          * it exists, we just created it above.
1397          *
1398          * At NO other time should you access a value in a map or a
1399          * hash_map this way.
1400          */
1401         clientlist[tempnick] = new userrec();
1402
1403         NonBlocking(socket);
1404         log(DEBUG,"AddClient: %lu %s %d %s",(unsigned long)socket,host,port,ip);
1405
1406         clientlist[tempnick]->fd = socket;
1407         strlcpy(clientlist[tempnick]->nick, tn2,NICKMAX);
1408         strlcpy(clientlist[tempnick]->host, host,160);
1409         strlcpy(clientlist[tempnick]->dhost, host,160);
1410         clientlist[tempnick]->server = (char*)FindServerNamePtr(ServerName);
1411         strlcpy(clientlist[tempnick]->ident, "unknown",IDENTMAX);
1412         clientlist[tempnick]->registered = 0;
1413         clientlist[tempnick]->signon = TIME+dns_timeout;
1414         clientlist[tempnick]->lastping = 1;
1415         clientlist[tempnick]->port = port;
1416         strlcpy(clientlist[tempnick]->ip,ip,16);
1417
1418         // set the registration timeout for this user
1419         unsigned long class_regtimeout = 90;
1420         int class_flood = 0;
1421         long class_threshold = 5;
1422         long class_sqmax = 262144;      // 256kb
1423         long class_rqmax = 4096;        // 4k
1424
1425         for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
1426         {
1427                 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
1428                 {
1429                         class_regtimeout = (unsigned long)i->registration_timeout;
1430                         class_flood = i->flood;
1431                         clientlist[tempnick]->pingmax = i->pingtime;
1432                         class_threshold = i->threshold;
1433                         class_sqmax = i->sendqmax;
1434                         class_rqmax = i->recvqmax;
1435                         break;
1436                 }
1437         }
1438
1439         clientlist[tempnick]->nping = TIME+clientlist[tempnick]->pingmax+dns_timeout;
1440         clientlist[tempnick]->timeout = TIME+class_regtimeout;
1441         clientlist[tempnick]->flood = class_flood;
1442         clientlist[tempnick]->threshold = class_threshold;
1443         clientlist[tempnick]->sendqmax = class_sqmax;
1444         clientlist[tempnick]->recvqmax = class_rqmax;
1445
1446         for (int i = 0; i < MAXCHANS; i++)
1447         {
1448                 clientlist[tempnick]->chans[i].channel = NULL;
1449                 clientlist[tempnick]->chans[i].uc_modes = 0;
1450         }
1451
1452         if (clientlist.size() > SoftLimit)
1453         {
1454                 kill_link(clientlist[tempnick],"No more connections allowed");
1455                 return;
1456         }
1457
1458         if (clientlist.size() >= MAXCLIENTS)
1459         {
1460                 kill_link(clientlist[tempnick],"No more connections allowed");
1461                 return;
1462         }
1463
1464         // this is done as a safety check to keep the file descriptors within range of fd_ref_table.
1465         // its a pretty big but for the moment valid assumption:
1466         // file descriptors are handed out starting at 0, and are recycled as theyre freed.
1467         // therefore if there is ever an fd over 65535, 65536 clients must be connected to the
1468         // irc server at once (or the irc server otherwise initiating this many connections, files etc)
1469         // which for the time being is a physical impossibility (even the largest networks dont have more
1470         // than about 10,000 users on ONE server!)
1471         if ((unsigned)socket > 65534)
1472         {
1473                 kill_link(clientlist[tempnick],"Server is full");
1474                 return;
1475         }
1476                 
1477
1478         char* e = matches_exception(ip);
1479         if (!e)
1480         {
1481                 char* r = matches_zline(ip);
1482                 if (r)
1483                 {
1484                         char reason[MAXBUF];
1485                         snprintf(reason,MAXBUF,"Z-Lined: %s",r);
1486                         kill_link(clientlist[tempnick],reason);
1487                         return;
1488                 }
1489         }
1490         fd_ref_table[socket] = clientlist[tempnick];
1491         SE->AddFd(socket,true,X_ESTAB_CLIENT);
1492 }
1493
1494 /* shows the message of the day, and any other on-logon stuff */
1495 void FullConnectUser(userrec* user)
1496 {
1497         statsConnects++;
1498         user->idle_lastmsg = TIME;
1499         log(DEBUG,"ConnectUser: %s",user->nick);
1500
1501         if ((strcmp(Passwd(user),"")) && (!user->haspassed))
1502         {
1503                 kill_link(user,"Invalid password");
1504                 return;
1505         }
1506         if (IsDenied(user))
1507         {
1508                 kill_link(user,"Unauthorised connection");
1509                 return;
1510         }
1511
1512         char match_against[MAXBUF];
1513         snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
1514         char* e = matches_exception(match_against);
1515         if (!e)
1516         {
1517                 char* r = matches_gline(match_against);
1518                 if (r)
1519                 {
1520                         char reason[MAXBUF];
1521                         snprintf(reason,MAXBUF,"G-Lined: %s",r);
1522                         kill_link_silent(user,reason);
1523                         return;
1524                 }
1525                 r = matches_kline(user->host);
1526                 if (r)
1527                 {
1528                         char reason[MAXBUF];
1529                         snprintf(reason,MAXBUF,"K-Lined: %s",r);
1530                         kill_link_silent(user,reason);
1531                         return;
1532                 }
1533         }
1534
1535
1536         WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
1537         WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
1538         WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
1539         WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
1540         WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
1541         // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
1542         std::stringstream v;
1543         v << "WALLCHOPS MODES=13 CHANTYPES=# PREFIX=(ohv)@%+ MAP SAFELIST MAXCHANNELS=" << MAXCHANS;
1544         v << " MAXBANS=60 NICKLEN=" << NICKMAX;
1545         v << " TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=20 AWAYLEN=" << MAXAWAY << " CHANMODES=ohvb,k,l,psmnti NETWORK=";
1546         v << Network;
1547         std::string data005 = v.str();
1548         FOREACH_MOD On005Numeric(data005);
1549         // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
1550         // so i'd better split it :)
1551         std::stringstream out(data005);
1552         std::string token = "";
1553         std::string line5 = "";
1554         int token_counter = 0;
1555         while (!out.eof())
1556         {
1557                 out >> token;
1558                 line5 = line5 + token + " ";
1559                 token_counter++;
1560                 if ((token_counter >= 13) || (out.eof() == true))
1561                 {
1562                         WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
1563                         line5 = "";
1564                         token_counter = 0;
1565                 }
1566         }
1567         ShowMOTD(user);
1568
1569         // fix 3 by brain, move registered = 7 below these so that spurious modes and host changes dont go out
1570         // onto the network and produce 'fake direction'
1571         FOREACH_MOD OnUserConnect(user);
1572         FOREACH_MOD OnGlobalConnect(user);
1573         user->registered = 7;
1574         WriteOpers("*** Client connecting on port %lu: %s!%s@%s [%s]",(unsigned long)user->port,user->nick,user->ident,user->host,user->ip);
1575 }
1576
1577
1578 /* shows the message of the day, and any other on-logon stuff */
1579 void ConnectUser(userrec *user)
1580 {
1581         // dns is already done, things are fast. no need to wait for dns to complete just pass them straight on
1582         if ((user->dns_done) && (user->registered >= 3) && (AllModulesReportReady(user)))
1583         {
1584                 FullConnectUser(user);
1585         }
1586 }
1587
1588 std::string GetVersionString()
1589 {
1590         char Revision[] = "$Revision$";
1591         char versiondata[MAXBUF];
1592         char *s1 = Revision;
1593         char *savept;
1594         char *v2 = strtok_r(s1," ",&savept);
1595         s1 = savept;
1596         v2 = strtok_r(s1," ",&savept);
1597         s1 = savept;
1598 #ifdef THREADED_DNS
1599         char dnsengine[] = "multithread";
1600 #else
1601         char dnsengine[] = "singlethread";
1602 #endif
1603         snprintf(versiondata,MAXBUF,"%s Rev. %s %s :%s [FLAGS=%lu,%s,%s]",VERSION,v2,ServerName,SYSTEM,(unsigned long)OPTIMISATION,SE->GetName().c_str(),dnsengine);
1604         return versiondata;
1605 }
1606
1607 void handle_version(char **parameters, int pcnt, userrec *user)
1608 {
1609         WriteServ(user->fd,"351 %s :%s",user->nick,GetVersionString().c_str());
1610 }
1611
1612
1613 bool is_valid_cmd(const char* commandname, int pcnt, userrec * user)
1614 {
1615         for (unsigned int i = 0; i < cmdlist.size(); i++)
1616         {
1617                 if (!strcasecmp(cmdlist[i].command,commandname))
1618                 {
1619                         if (cmdlist[i].handler_function)
1620                         {
1621                                 if ((pcnt>=cmdlist[i].min_params) && (strcasecmp(cmdlist[i].source,"<core>")))
1622                                 {
1623                                         if ((strchr(user->modes,cmdlist[i].flags_needed)) || (!cmdlist[i].flags_needed))
1624                                         {
1625                                                 if (cmdlist[i].flags_needed)
1626                                                 {
1627                                                         if ((user->HasPermission((char*)commandname)) || (is_uline(user->server)))
1628                                                         {
1629                                                                 return true;
1630                                                         }
1631                                                         else
1632                                                         {
1633                                                                 return false;
1634                                                         }
1635                                                 }
1636                                                 return true;
1637                                         }
1638                                 }
1639                         }
1640                 }
1641         }
1642         return false;
1643 }
1644
1645 // calls a handler function for a command
1646
1647 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
1648 {
1649         for (unsigned int i = 0; i < cmdlist.size(); i++)
1650         {
1651                 if (!strcasecmp(cmdlist[i].command,commandname))
1652                 {
1653                         if (cmdlist[i].handler_function)
1654                         {
1655                                 if (pcnt>=cmdlist[i].min_params)
1656                                 {
1657                                         if ((strchr(user->modes,cmdlist[i].flags_needed)) || (!cmdlist[i].flags_needed))
1658                                         {
1659                                                 if (cmdlist[i].flags_needed)
1660                                                 {
1661                                                         if ((user->HasPermission((char*)commandname)) || (is_uline(user->server)))
1662                                                         {
1663                                                                 cmdlist[i].handler_function(parameters,pcnt,user);
1664                                                         }
1665                                                 }
1666                                                 else
1667                                                 {
1668                                                         cmdlist[i].handler_function(parameters,pcnt,user);
1669                                                 }
1670                                         }
1671                                 }
1672                         }
1673                 }
1674         }
1675 }
1676
1677
1678 void force_nickchange(userrec* user,const char* newnick)
1679 {
1680         char nick[MAXBUF];
1681         int MOD_RESULT = 0;
1682         
1683         strcpy(nick,"");
1684
1685         FOREACH_RESULT(OnUserPreNick(user,newnick));
1686         if (MOD_RESULT) {
1687                 statsCollisions++;
1688                 kill_link(user,"Nickname collision");
1689                 return;
1690         }
1691         if (matches_qline(newnick))
1692         {
1693                 statsCollisions++;
1694                 kill_link(user,"Nickname collision");
1695                 return;
1696         }
1697         
1698         if (user)
1699         {
1700                 if (newnick)
1701                 {
1702                         strncpy(nick,newnick,MAXBUF);
1703                 }
1704                 if (user->registered == 7)
1705                 {
1706                         char* pars[1];
1707                         pars[0] = nick;
1708                         handle_nick(pars,1,user);
1709                 }
1710         }
1711 }
1712                                 
1713
1714 int process_parameters(char **command_p,char *parameters)
1715 {
1716         int j = 0;
1717         int q = strlen(parameters);
1718         if (!q)
1719         {
1720                 /* no parameters, command_p invalid! */
1721                 return 0;
1722         }
1723         if (parameters[0] == ':')
1724         {
1725                 command_p[0] = parameters+1;
1726                 return 1;
1727         }
1728         if (q)
1729         {
1730                 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
1731                 {
1732                         /* only one parameter */
1733                         command_p[0] = parameters;
1734                         if (parameters[0] == ':')
1735                         {
1736                                 if (strchr(parameters,' ') != NULL)
1737                                 {
1738                                         command_p[0]++;
1739                                 }
1740                         }
1741                         return 1;
1742                 }
1743         }
1744         command_p[j++] = parameters;
1745         for (int i = 0; i <= q; i++)
1746         {
1747                 if (parameters[i] == ' ')
1748                 {
1749                         command_p[j++] = parameters+i+1;
1750                         parameters[i] = '\0';
1751                         if (command_p[j-1][0] == ':')
1752                         {
1753                                 *command_p[j-1]++; /* remove dodgy ":" */
1754                                 break;
1755                                 /* parameter like this marks end of the sequence */
1756                         }
1757                 }
1758         }
1759         return j; /* returns total number of items in the list */
1760 }
1761
1762 void process_command(userrec *user, char* cmd)
1763 {
1764         char *parameters;
1765         char *command;
1766         char *command_p[127];
1767         char p[MAXBUF], temp[MAXBUF];
1768         int j, items, cmd_found;
1769
1770         for (int i = 0; i < 127; i++)
1771                 command_p[i] = NULL;
1772
1773         if (!user)
1774         {
1775                 return;
1776         }
1777         if (!cmd)
1778         {
1779                 return;
1780         }
1781         if (!cmd[0])
1782         {
1783                 return;
1784         }
1785         
1786         int total_params = 0;
1787         if (strlen(cmd)>2)
1788         {
1789                 for (unsigned int q = 0; q < strlen(cmd)-1; q++)
1790                 {
1791                         if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
1792                         {
1793                                 total_params++;
1794                                 // found a 'trailing', we dont count them after this.
1795                                 break;
1796                         }
1797                         if (cmd[q] == ' ')
1798                                 total_params++;
1799                 }
1800         }
1801
1802         // another phidjit bug...
1803         if (total_params > 126)
1804         {
1805                 *(strchr(cmd,' ')) = '\0';
1806                 WriteServ(user->fd,"421 %s %s :Too many parameters given",user->nick,cmd);
1807                 return;
1808         }
1809
1810         strlcpy(temp,cmd,MAXBUF);
1811         
1812         std::string tmp = cmd;
1813         for (int i = 0; i <= MODCOUNT; i++)
1814         {
1815                 std::string oldtmp = tmp;
1816                 modules[i]->OnServerRaw(tmp,true,user);
1817                 if (oldtmp != tmp)
1818                 {
1819                         log(DEBUG,"A Module changed the input string!");
1820                         log(DEBUG,"New string: %s",tmp.c_str());
1821                         log(DEBUG,"Old string: %s",oldtmp.c_str());
1822                         break;
1823                 }
1824         }
1825         strlcpy(cmd,tmp.c_str(),MAXBUF);
1826         strlcpy(temp,cmd,MAXBUF);
1827
1828         if (!strchr(cmd,' '))
1829         {
1830                 /* no parameters, lets skip the formalities and not chop up
1831                  * the string */
1832                 log(DEBUG,"About to preprocess command with no params");
1833                 items = 0;
1834                 command_p[0] = NULL;
1835                 parameters = NULL;
1836                 for (unsigned int i = 0; i <= strlen(cmd); i++)
1837                 {
1838                         cmd[i] = toupper(cmd[i]);
1839                 }
1840                 command = cmd;
1841         }
1842         else
1843         {
1844                 strcpy(cmd,"");
1845                 j = 0;
1846                 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
1847                 for (unsigned int i = 0; i < strlen(temp); i++)
1848                 {
1849                         if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
1850                         {
1851                                 cmd[j++] = temp[i];
1852                                 cmd[j] = 0;
1853                         }
1854                 }
1855                 /* split the full string into a command plus parameters */
1856                 parameters = p;
1857                 strcpy(p," ");
1858                 command = cmd;
1859                 if (strchr(cmd,' '))
1860                 {
1861                         for (unsigned int i = 0; i <= strlen(cmd); i++)
1862                         {
1863                                 /* capitalise the command ONLY, leave params intact */
1864                                 cmd[i] = toupper(cmd[i]);
1865                                 /* are we nearly there yet?! :P */
1866                                 if (cmd[i] == ' ')
1867                                 {
1868                                         command = cmd;
1869                                         parameters = cmd+i+1;
1870                                         cmd[i] = '\0';
1871                                         break;
1872                                 }
1873                         }
1874                 }
1875                 else
1876                 {
1877                         for (unsigned int i = 0; i <= strlen(cmd); i++)
1878                         {
1879                                 cmd[i] = toupper(cmd[i]);
1880                         }
1881                 }
1882
1883         }
1884         cmd_found = 0;
1885         
1886         if (strlen(command)>MAXCOMMAND)
1887         {
1888                 WriteServ(user->fd,"421 %s %s :Command too long",user->nick,command);
1889                 return;
1890         }
1891         
1892         for (unsigned int x = 0; x < strlen(command); x++)
1893         {
1894                 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
1895                 {
1896                         if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
1897                         {
1898                                 if (strchr("@!\"$%^&*(){}[]_=+;:'#~,<>/?\\|`",command[x]))
1899                                 {
1900                                         statsUnknown++;
1901                                         WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
1902                                         return;
1903                                 }
1904                         }
1905                 }
1906         }
1907
1908         for (unsigned int i = 0; i != cmdlist.size(); i++)
1909         {
1910                 if (cmdlist[i].command[0])
1911                 {
1912                         if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
1913                         {
1914                                 if (parameters)
1915                                 {
1916                                         if (parameters[0])
1917                                         {
1918                                                 items = process_parameters(command_p,parameters);
1919                                         }
1920                                         else
1921                                         {
1922                                                 items = 0;
1923                                                 command_p[0] = NULL;
1924                                         }
1925                                 }
1926                                 else
1927                                 {
1928                                         items = 0;
1929                                         command_p[0] = NULL;
1930                                 }
1931                                 
1932                                 if (user)
1933                                 {
1934                                         /* activity resets the ping pending timer */
1935                                         user->nping = TIME + user->pingmax;
1936                                         if ((items) < cmdlist[i].min_params)
1937                                         {
1938                                                 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
1939                                                 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
1940                                                 return;
1941                                         }
1942                                         if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
1943                                         {
1944                                                 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
1945                                                 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
1946                                                 cmd_found = 1;
1947                                                 return;
1948                                         }
1949                                         if ((cmdlist[i].flags_needed) && (!user->HasPermission(command)))
1950                                         {
1951                                                 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
1952                                                 WriteServ(user->fd,"481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command);
1953                                                 cmd_found = 1;
1954                                                 return;
1955                                         }
1956                                         /* if the command isnt USER, PASS, or NICK, and nick is empty,
1957                                          * deny command! */
1958                                         if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
1959                                         {
1960                                                 if ((!isnick(user->nick)) || (user->registered != 7))
1961                                                 {
1962                                                         log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
1963                                                         WriteServ(user->fd,"451 %s :You have not registered",command);
1964                                                         return;
1965                                                 }
1966                                         }
1967                                         if ((user->registered == 7) && (!strchr(user->modes,'o')))
1968                                         {
1969                                                 std::stringstream dcmds(DisabledCommands);
1970                                                 while (!dcmds.eof())
1971                                                 {
1972                                                         std::string thiscmd;
1973                                                         dcmds >> thiscmd;
1974                                                         if (!strcasecmp(thiscmd.c_str(),command))
1975                                                         {
1976                                                                 // command is disabled!
1977                                                                 WriteServ(user->fd,"421 %s %s :This command has been disabled.",user->nick,command);
1978                                                                 return;
1979                                                         }
1980                                                 }
1981                                         }
1982                                         if ((user->registered == 7) || (!strncmp(command,"USER",4)) || (!strncmp(command,"NICK",4)) || (!strncmp(command,"PASS",4)))
1983                                         {
1984                                                 if (cmdlist[i].handler_function)
1985                                                 {
1986                                                         
1987                                                         /* ikky /stats counters */
1988                                                         if (temp)
1989                                                         {
1990                                                                 cmdlist[i].use_count++;
1991                                                                 cmdlist[i].total_bytes+=strlen(temp);
1992                                                         }
1993
1994                                                         int MOD_RESULT = 0;
1995                                                         FOREACH_RESULT(OnPreCommand(command,command_p,items,user));
1996                                                         if (MOD_RESULT == 1) {
1997                                                                 return;
1998                                                         }
1999
2000                                                         /* WARNING: nothing may come after the
2001                                                          * command handler call, as the handler
2002                                                          * may free the user structure! */
2003
2004                                                         cmdlist[i].handler_function(command_p,items,user);
2005                                                 }
2006                                                 return;
2007                                         }
2008                                         else
2009                                         {
2010                                                 WriteServ(user->fd,"451 %s :You have not registered",command);
2011                                                 return;
2012                                         }
2013                                 }
2014                                 cmd_found = 1;
2015                         }
2016                 }
2017         }
2018         if ((!cmd_found) && (user))
2019         {
2020                 statsUnknown++;
2021                 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
2022         }
2023 }
2024
2025 bool removecommands(const char* source)
2026 {
2027         bool go_again = true;
2028         while (go_again)
2029         {
2030                 go_again = false;
2031                 for (std::deque<command_t>::iterator i = cmdlist.begin(); i != cmdlist.end(); i++)
2032                 {
2033                         if (!strcmp(i->source,source))
2034                         {
2035                                 log(DEBUG,"removecommands(%s) Removing dependent command: %s",i->source,i->command);
2036                                 cmdlist.erase(i);
2037                                 go_again = true;
2038                                 break;
2039                         }
2040                 }
2041         }
2042         return true;
2043 }
2044
2045
2046 void process_buffer(const char* cmdbuf,userrec *user)
2047 {
2048         if (!user)
2049         {
2050                 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2051                 return;
2052         }
2053         char cmd[MAXBUF];
2054         if (!cmdbuf)
2055         {
2056                 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2057                 return;
2058         }
2059         if (!cmdbuf[0])
2060         {
2061                 return;
2062         }
2063         while (*cmdbuf == ' ') cmdbuf++; // strip leading spaces
2064
2065         strlcpy(cmd,cmdbuf,MAXBUF);
2066         if (!cmd[0])
2067         {
2068                 return;
2069         }
2070         int sl = strlen(cmd)-1;
2071         if ((cmd[sl] == 13) || (cmd[sl] == 10))
2072         {
2073                 cmd[sl] = '\0';
2074         }
2075         sl = strlen(cmd)-1;
2076         if ((cmd[sl] == 13) || (cmd[sl] == 10))
2077         {
2078                 cmd[sl] = '\0';
2079         }
2080         sl = strlen(cmd)-1;
2081         while (cmd[sl] == ' ') // strip trailing spaces
2082         {
2083                 cmd[sl] = '\0';
2084                 sl = strlen(cmd)-1;
2085         }
2086
2087         if (!cmd[0])
2088         {
2089                 return;
2090         }
2091         log(DEBUG,"CMDIN: %s %s",user->nick,cmd);
2092         tidystring(cmd);
2093         if ((user) && (cmd))
2094         {
2095                 process_command(user,cmd);
2096         }
2097 }
2098
2099 char MODERR[MAXBUF];
2100
2101 char* ModuleError()
2102 {
2103         return MODERR;
2104 }
2105
2106 void erase_factory(int j)
2107 {
2108         int v = 0;
2109         for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
2110         {
2111                 if (v == j)
2112                 {
2113                         factory.erase(t);
2114                         factory.push_back(NULL);
2115                         return;
2116                 }
2117                 v++;
2118         }
2119 }
2120
2121 void erase_module(int j)
2122 {
2123         int v1 = 0;
2124         for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
2125         {
2126                 if (v1 == j)
2127                 {
2128                         delete *m;
2129                         modules.erase(m);
2130                         modules.push_back(NULL);
2131                         break;
2132                 }
2133                 v1++;
2134         }
2135         int v2 = 0;
2136         for (std::vector<std::string>::iterator v = module_names.begin(); v != module_names.end(); v++)
2137         {
2138                 if (v2 == j)
2139                 {
2140                        module_names.erase(v);
2141                        break;
2142                 }
2143                 v2++;
2144         }
2145
2146 }
2147
2148 bool UnloadModule(const char* filename)
2149 {
2150         std::string filename_str = filename;
2151         for (unsigned int j = 0; j != module_names.size(); j++)
2152         {
2153                 if (module_names[j] == filename_str)
2154                 {
2155                         if (modules[j]->GetVersion().Flags & VF_STATIC)
2156                         {
2157                                 log(DEFAULT,"Failed to unload STATIC module %s",filename);
2158                                 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
2159                                 return false;
2160                         }
2161                         /* Give the module a chance to tidy out all its metadata */
2162                         for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
2163                         {
2164                                 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
2165                         }
2166                         for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
2167                         {
2168                                 modules[j]->OnCleanup(TYPE_USER,u->second);
2169                         }
2170                         FOREACH_MOD OnUnloadModule(modules[j],module_names[j]);
2171                         // found the module
2172                         log(DEBUG,"Deleting module...");
2173                         erase_module(j);
2174                         log(DEBUG,"Erasing module entry...");
2175                         erase_factory(j);
2176                         log(DEBUG,"Removing dependent commands...");
2177                         removecommands(filename);
2178                         log(DEFAULT,"Module %s unloaded",filename);
2179                         MODCOUNT--;
2180                         return true;
2181                 }
2182         }
2183         log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
2184         snprintf(MODERR,MAXBUF,"Module not loaded");
2185         return false;
2186 }
2187
2188 bool LoadModule(const char* filename)
2189 {
2190         char modfile[MAXBUF];
2191 #ifdef STATIC_LINK
2192         snprintf(modfile,MAXBUF,"%s",filename);
2193 #else
2194         snprintf(modfile,MAXBUF,"%s/%s",ModPath,filename);
2195 #endif
2196         std::string filename_str = filename;
2197 #ifndef STATIC_LINK
2198         if (!DirValid(modfile))
2199         {
2200                 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
2201                 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
2202                 return false;
2203         }
2204 #endif
2205         log(DEBUG,"Loading module: %s",modfile);
2206 #ifndef STATIC_LINK
2207         if (FileExists(modfile))
2208         {
2209 #endif
2210                 for (unsigned int j = 0; j < module_names.size(); j++)
2211                 {
2212                         if (module_names[j] == filename_str)
2213                         {
2214                                 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
2215                                 snprintf(MODERR,MAXBUF,"Module already loaded");
2216                                 return false;
2217                         }
2218                 }
2219                 ircd_module* a = new ircd_module(modfile);
2220                 factory[MODCOUNT+1] = a;
2221                 if (factory[MODCOUNT+1]->LastError())
2222                 {
2223                         log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
2224                         snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
2225                         MODCOUNT--;
2226                         return false;
2227                 }
2228                 if (factory[MODCOUNT+1]->factory)
2229                 {
2230                         Module* m = factory[MODCOUNT+1]->factory->CreateModule(MyServer);
2231                         modules[MODCOUNT+1] = m;
2232                         /* save the module and the module's classfactory, if
2233                          * this isnt done, random crashes can occur :/ */
2234                         module_names.push_back(filename);
2235                 }
2236                 else
2237                 {
2238                         log(DEFAULT,"Unable to load %s",modfile);
2239                         snprintf(MODERR,MAXBUF,"Factory function failed!");
2240                         return false;
2241                 }
2242 #ifndef STATIC_LINK
2243         }
2244         else
2245         {
2246                 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
2247                 snprintf(MODERR,MAXBUF,"Module file could not be found");
2248                 return false;
2249         }
2250 #endif
2251         MODCOUNT++;
2252         FOREACH_MOD OnLoadModule(modules[MODCOUNT],filename_str);
2253         return true;
2254 }
2255
2256 int BindPorts()
2257 {
2258         int clientportcount = 0;
2259         for (int count = 0; count < ConfValueEnum("bind",&config_f); count++)
2260         {
2261                 ConfValue("bind","port",count,configToken,&config_f);
2262                 ConfValue("bind","address",count,Addr,&config_f);
2263                 ConfValue("bind","type",count,Type,&config_f);
2264                 if (strcmp(Type,"servers"))
2265                 {
2266                         // modules handle server bind types now,
2267                         // its not a typo in the strcmp.
2268                         ports[clientportcount] = atoi(configToken);
2269                         strlcpy(addrs[clientportcount],Addr,256);
2270                         clientportcount++;
2271                         log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
2272                 }
2273         }
2274         portCount = clientportcount;
2275
2276         for (int count = 0; count < portCount; count++)
2277         {
2278                 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
2279                 {
2280                         log(DEBUG,"InspIRCd: startup: bad fd %lu",(unsigned long)openSockfd[boundPortCount]);
2281                         return(ERROR);
2282                 }
2283                 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
2284                 {
2285                         log(DEFAULT,"InspIRCd: startup: failed to bind port %lu",(unsigned long)ports[count]);
2286                 }
2287                 else    /* well we at least bound to one socket so we'll continue */
2288                 {
2289                         boundPortCount++;
2290                 }
2291         }
2292
2293         /* if we didn't bind to anything then abort */
2294         if (!boundPortCount)
2295         {
2296                 log(DEFAULT,"InspIRCd: startup: no ports bound, bailing!");
2297                 printf("\nERROR: Was not able to bind any of %lu ports! Please check your configuration.\n\n", (unsigned long)portCount);
2298                 return (ERROR);
2299         }
2300
2301         return boundPortCount;
2302 }
2303
2304 int InspIRCd(char** argv, int argc)
2305 {
2306         bool expire_run = false;
2307         std::vector<int> activefds;
2308         int incomingSockfd;
2309         userrec* cu = NULL;
2310         InspSocket* s = NULL;
2311         InspSocket* s_del = NULL;
2312         char target[MAXBUF];
2313         unsigned int numberactive;
2314
2315         /* Beta 7 moved all this stuff out of the main function
2316          * into smaller sub-functions, much tidier -- Brain
2317          */
2318         OpenLog(argv, argc);
2319         CheckRoot();
2320         SetupCommandTable();
2321         ReadConfig(true,NULL);
2322         AddServerName(ServerName);
2323         CheckDie();
2324         boundPortCount = BindPorts();
2325
2326         printf("\n");
2327         startup_time = time(NULL);
2328           
2329         char PID[MAXBUF];
2330         ConfValue("pid","file",0,PID,&config_f);
2331         // write once here, to try it out and make sure its ok
2332         WritePID(PID);
2333         
2334         if (!nofork)
2335         {
2336                 if (DaemonSeed() == ERROR)
2337                 {
2338                         printf("ERROR: could not go into daemon mode. Shutting down.\n");
2339                         Exit(ERROR);
2340                 }
2341         }
2342
2343         /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
2344          * initialize the socket engine.
2345          */
2346         SE = new SocketEngine();
2347
2348         /* We must load the modules AFTER initializing the socket engine, now */
2349         LoadAllModules();
2350
2351         printf("\nInspIRCd is now running!\n");
2352         if (!nofork)
2353         {
2354                 freopen("/dev/null","w",stdout);
2355                 freopen("/dev/null","w",stderr);
2356         }
2357
2358         /* Add the listening sockets used for client inbound connections
2359          * to the socket engine
2360          */
2361         for (int count = 0; count < portCount; count++)
2362                 SE->AddFd(openSockfd[count],true,X_LISTEN);
2363
2364         WritePID(PID);
2365
2366         /* main loop, this never returns */
2367         for (;;)
2368         {
2369                 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
2370                  * Once per loop iteration is pleanty.
2371                  */
2372                 OLDTIME = TIME;
2373                 TIME = time(NULL);
2374
2375                 /* Run background module timers every few seconds
2376                  * (the docs say modules shouldnt rely on accurate
2377                  * timing using this event, so we dont have to
2378                  * time this exactly).
2379                  */
2380                 if (((TIME % 8) == 0) && (!expire_run))
2381                 {
2382                         expire_lines();
2383                         FOREACH_MOD OnBackgroundTimer(TIME);
2384                         expire_run = true;
2385                         continue;
2386                 }
2387                 if ((TIME % 8) == 1)
2388                         expire_run = false;
2389                 
2390                 /* Once a second, do the background processing */
2391                 if (TIME != OLDTIME)
2392                         while (DoBackgroundUserStuff(TIME));
2393
2394                 /* Call the socket engine to wait on the active
2395                  * file descriptors. The socket engine has everything's
2396                  * descriptors in its list... dns, modules, users,
2397                  * servers... so its nice and easy, just one call.
2398                  */
2399                 SE->Wait(activefds);
2400
2401                 /**
2402                  * Now process each of the fd's. For users, we have a fast
2403                  * lookup table which can find a user by file descriptor, so
2404                  * processing them by fd isnt expensive. If we have a lot of
2405                  * listening ports or module sockets though, things could get
2406                  * ugly.
2407                  */
2408                 numberactive = activefds.size();
2409                 for (unsigned int activefd = 0; activefd < numberactive; activefd++)
2410                 {
2411                         int socket_type = SE->GetType(activefds[activefd]);
2412                         switch (socket_type)
2413                         {
2414                                 case X_ESTAB_CLIENT:
2415
2416                                         cu = fd_ref_table[activefds[activefd]];
2417                                         if (cu)
2418                                                 ProcessUser(cu);
2419
2420                                 break;
2421
2422                                 case X_ESTAB_MODULE:
2423
2424                                         /* Process module-owned sockets.
2425                                          * Modules are encouraged to inherit their sockets from
2426                                          * InspSocket so we can process them neatly like this.
2427                                          */
2428                                         s = socket_ref[activefds[activefd]];
2429
2430                                         if ((s) && (!s->Poll()))
2431                                         {
2432                                                 log(DEBUG,"Socket poll returned false, close and bail");
2433                                                 SE->DelFd(s->GetFd());
2434                                                 for (std::vector<InspSocket*>::iterator a = module_sockets.begin(); a < module_sockets.end(); a++)
2435                                                 {
2436                                                         s_del = (InspSocket*)*a;
2437                                                         if ((s_del) && (s_del->GetFd() == activefds[activefd]))
2438                                                         {
2439                                                                 module_sockets.erase(a);
2440                                                                 break;
2441                                                         }
2442                                                 }
2443                                                 s->Close();
2444                                                 delete s;
2445                                         }
2446
2447                                 break;
2448
2449                                 case X_ESTAB_DNS:
2450
2451                                         /* When we are using single-threaded dns,
2452                                          * the sockets for dns end up in our mainloop.
2453                                          * When we are using multi-threaded dns,
2454                                          * each thread has its own basic poll() loop
2455                                          * within it, making them 'fire and forget'
2456                                          * and independent of the mainloop.
2457                                          */
2458                                         log(DEBUG,"Got a ready socket of type X_ESTAB_DNS");
2459 #ifndef THREADED_DNS
2460                                         dns_poll(activefds[activefd]);
2461 #endif
2462                                 break;
2463                                 
2464                                 case X_LISTEN:
2465
2466                                         /* It's a listener */
2467                                         for (int count = 0; count < boundPortCount; count++)
2468                                         {
2469                                                 if (activefds[activefd] == openSockfd[count])
2470                                                 {
2471                                                         length = sizeof (client);
2472                                                         incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
2473                                                         log(DEBUG,"Accepted socket %d",incomingSockfd);
2474                                                         strlcpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
2475                                                         /* Years and years ago, we used to resolve here
2476                                                          * using gethostbyaddr(). That is sucky and we
2477                                                          * don't do that any more...
2478                                                          */
2479                                                         if (incomingSockfd >= 0)
2480                                                         {
2481                                                                 FOREACH_MOD OnRawSocketAccept(incomingSockfd, target, ports[count]);
2482                                                                 statsAccept++;
2483                                                                 AddClient(incomingSockfd, target, ports[count], false, inet_ntoa (client.sin_addr));
2484                                                                 log(DEBUG,"Adding client on port %lu fd=%lu",(unsigned long)ports[count],(unsigned long)incomingSockfd);
2485                                                         }
2486                                                         else
2487                                                         {
2488                                                                 WriteOpers("*** WARNING: accept() failed on port %lu (%s)",(unsigned long)ports[count],target);
2489                                                                 log(DEBUG,"accept failed: %lu",(unsigned long)ports[count]);
2490                                                                 statsRefused++;
2491                                                         }
2492                                                         /* We've found out what port it belongs on,
2493                                                          * no need to iterate the rest
2494                                                          */
2495                                                         break;
2496                                                 }
2497                                         }
2498                                 break;
2499
2500                                 default:
2501                                         /* Something went wrong if we're in here.
2502                                          * In fact, so wrong, im not quite sure
2503                                          * what we would do, so for now, its going
2504                                          * to safely do bugger all.
2505                                          */
2506                                 break;
2507                         }
2508                 }
2509
2510         }
2511         /* This is never reached -- we hope! */
2512         return 0;
2513 }
2514