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