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