]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd.cpp
MaxClients -> MAXCLIENTS
[user/henk/code/inspircd.git] / src / inspircd.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  Inspire is copyright (C) 2002-2004 ChatSpike-Dev.
6  *                       E-mail:
7  *                <brain@chatspike.net>
8  *                <Craig@chatspike.net>
9  *     
10  * Written by Craig Edwards, Craig McLure, and others.
11  * This program is free but copyrighted software; see
12  *            the file COPYING for details.
13  *
14  * ---------------------------------------------------
15  */
16
17 /* 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 50
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 #include "connection.h"
55 #include "users.h"
56 #include "servers.h"
57 #include "ctables.h"
58 #include "globals.h"
59 #include "modules.h"
60 #include "dynamic.h"
61 #include "wildcard.h"
62 #include "message.h"
63 #include "mode.h"
64 #include "commands.h"
65 #include "xline.h"
66 #include "inspstring.h"
67 #include "dnsqueue.h"
68 #include "helperfuncs.h"
69 #include "hashcomp.h"
70
71 int LogLevel = DEFAULT;
72 char ServerName[MAXBUF];
73 char Network[MAXBUF];
74 char ServerDesc[MAXBUF];
75 char AdminName[MAXBUF];
76 char AdminEmail[MAXBUF];
77 char AdminNick[MAXBUF];
78 char diepass[MAXBUF];
79 char restartpass[MAXBUF];
80 char motd[MAXBUF];
81 char rules[MAXBUF];
82 char list[MAXBUF];
83 char PrefixQuit[MAXBUF];
84 char DieValue[MAXBUF];
85 char DNSServer[MAXBUF];
86 int debugging =  0;
87 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
88 int WHOWAS_MAX = 100;  // default 100 people maximum in the WHOWAS list
89 int DieDelay  =  5;
90 time_t startup_time = time(NULL);
91 int NetBufferSize = 10240;      // NetBufferSize used as the buffer size for all read() ops
92 int MaxConn = SOMAXCONN;        // size of accept() backlog (128 by default on *BSD)
93 unsigned int SoftLimit = MAXCLIENTS;
94 extern int MaxWhoResults;
95 time_t nb_start = 0;
96 int dns_timeout = 5;
97
98 char DisabledCommands[MAXBUF];
99
100 bool AllowHalfop = true;
101 bool AllowProtect = true;
102 bool AllowFounder = true;
103
104 extern std::vector<Module*> modules;
105 std::vector<std::string> module_names;
106 extern std::vector<ircd_module*> factory;
107
108 extern int MODCOUNT;
109 int openSockfd[MAXSOCKS];
110 bool nofork = false;
111 bool unlimitcore = false;
112
113 time_t TIME = time(NULL), OLDTIME = time(NULL);
114
115 #ifdef USE_KQUEUE
116 int kq, lkq, skq;
117 #endif
118
119 #ifdef USE_EPOLL
120 int ep, lep, sep;
121 #endif
122
123 bool has_been_netsplit = false;
124 extern std::vector<std::string> include_stack;
125
126 typedef nspace::hash_map<std::string, userrec*, nspace::hash<string>, irc::StrHashComp> user_hash;
127 typedef nspace::hash_map<std::string, chanrec*, nspace::hash<string>, irc::StrHashComp> chan_hash;
128 typedef nspace::hash_map<in_addr,string*, nspace::hash<in_addr>, irc::InAddr_HashComp> address_cache;
129 typedef nspace::hash_map<std::string, WhoWasUser*, nspace::hash<string>, irc::StrHashComp> whowas_hash;
130 typedef std::deque<command_t> command_table;
131 typedef std::map<std::string,time_t> autoconnects;
132 typedef std::vector<std::string> servernamelist;
133
134 // This table references users by file descriptor.
135 // its an array to make it VERY fast, as all lookups are referenced
136 // by an integer, meaning there is no need for a scan/search operation.
137 userrec* fd_ref_table[65536];
138
139 int statsAccept = 0, statsRefused = 0, statsUnknown = 0, statsCollisions = 0, statsDns = 0, statsDnsGood = 0, statsDnsBad = 0, statsConnects = 0, statsSent= 0, statsRecv = 0;
140
141 serverrec* me[32];
142
143 FILE *log_file;
144
145 user_hash clientlist;
146 chan_hash chanlist;
147 whowas_hash whowas;
148 command_table cmdlist;
149 autoconnects autoconns;
150 file_cache MOTD;
151 file_cache RULES;
152 address_cache IP;
153
154 ClassVector Classes;
155 servernamelist servernames;
156
157 struct linger linger = { 0 };
158 char MyExecutable[1024];
159 int boundPortCount = 0;
160 int portCount = 0, SERVERportCount = 0, ports[MAXSOCKS];
161 int defaultRoute = 0;
162 char ModPath[MAXBUF];
163
164 /* prototypes */
165
166 int has_channel(userrec *u, chanrec *c);
167 int usercount(chanrec *c);
168 int usercount_i(chanrec *c);
169 char* Passwd(userrec *user);
170 bool IsDenied(userrec *user);
171 void AddWhoWas(userrec* u);
172
173 std::vector<long> auth_cookies;
174 std::stringstream config_f(stringstream::in | stringstream::out);
175
176 std::vector<userrec*> all_opers;
177
178 char lowermap[255];
179
180 void AddOper(userrec* user)
181 {
182         log(DEBUG,"Oper added to optimization list");
183         all_opers.push_back(user);
184 }
185
186 void AddServerName(std::string servername)
187 {
188         log(DEBUG,"Adding server name: %s",servername.c_str());
189         for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
190         {
191                 if (*a == servername)
192                         return;
193         }
194         servernames.push_back(servername);
195 }
196
197 const char* FindServerNamePtr(std::string servername)
198 {
199         for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
200         {
201                 if (*a == servername)
202                         return a->c_str();
203         }
204         return "";
205 }
206
207 void DeleteOper(userrec* user)
208 {
209         for (std::vector<userrec*>::iterator a = all_opers.begin(); a < all_opers.end(); a++)
210         {
211                 if (*a == user)
212                 {
213                         log(DEBUG,"Oper removed from optimization list");
214                         all_opers.erase(a);
215                         return;
216                 }
217         }
218 }
219
220 std::string GetRevision()
221 {
222         char Revision[] = "$Revision$";
223         char *s1 = Revision;
224         char *savept;
225         char *v2 = strtok_r(s1," ",&savept);
226         s1 = savept;
227         v2 = strtok_r(s1," ",&savept);
228         s1 = savept;
229         return std::string(v2);
230 }
231
232
233 std::string getservername()
234 {
235         return ServerName;
236 }
237
238 std::string getserverdesc()
239 {
240         return ServerDesc;
241 }
242
243 std::string getnetworkname()
244 {
245         return Network;
246 }
247
248 std::string getadminname()
249 {
250         return AdminName;
251 }
252
253 std::string getadminemail()
254 {
255         return AdminEmail;
256 }
257
258 std::string getadminnick()
259 {
260         return AdminNick;
261 }
262
263 void ReadConfig(bool bail, userrec* user)
264 {
265         char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF],MW[MAXBUF],MCON[MAXBUF];
266         char AH[MAXBUF],AP[MAXBUF],AF[MAXBUF],DNT[MAXBUF],pfreq[MAXBUF],thold[MAXBUF],sqmax[MAXBUF],rqmax[MAXBUF],SLIMT[MAXBUF];
267         ConnectClass c;
268         std::stringstream errstr;
269         include_stack.clear();
270         
271         if (!LoadConf(CONFIG_FILE,&config_f,&errstr))
272         {
273                 errstr.seekg(0);
274                 log(DEFAULT,"There were errors in your configuration:\n%s",errstr.str().c_str());
275                 if (bail)
276                 {
277                         printf("There were errors in your configuration:\n%s",errstr.str().c_str());
278                         Exit(0);
279                 }
280                 else
281                 {
282                         char dataline[1024];
283                         if (user)
284                         {
285                                 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
286                                 while (!errstr.eof())
287                                 {
288                                         errstr.getline(dataline,1024);
289                                         WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline);
290                                 }
291                         }
292                         else
293                         {
294                                 WriteOpers("There were errors in the configuration file:",user->nick);
295                                 while (!errstr.eof())
296                                 {
297                                         errstr.getline(dataline,1024);
298                                         WriteOpers(dataline);
299                                 }
300                         }
301                         return;
302                 }
303         }
304           
305         ConfValue("server","name",0,ServerName,&config_f);
306         ConfValue("server","description",0,ServerDesc,&config_f);
307         ConfValue("server","network",0,Network,&config_f);
308         ConfValue("admin","name",0,AdminName,&config_f);
309         ConfValue("admin","email",0,AdminEmail,&config_f);
310         ConfValue("admin","nick",0,AdminNick,&config_f);
311         ConfValue("files","motd",0,motd,&config_f);
312         ConfValue("files","rules",0,rules,&config_f);
313         ConfValue("power","diepass",0,diepass,&config_f);
314         ConfValue("power","pause",0,pauseval,&config_f);
315         ConfValue("power","restartpass",0,restartpass,&config_f);
316         ConfValue("options","prefixquit",0,PrefixQuit,&config_f);
317         ConfValue("die","value",0,DieValue,&config_f);
318         ConfValue("options","loglevel",0,dbg,&config_f);
319         ConfValue("options","netbuffersize",0,NB,&config_f);
320         ConfValue("options","maxwho",0,MW,&config_f);
321         ConfValue("options","allowhalfop",0,AH,&config_f);
322         ConfValue("options","allowprotect",0,AP,&config_f);
323         ConfValue("options","allowfounder",0,AF,&config_f);
324         ConfValue("dns","server",0,DNSServer,&config_f);
325         ConfValue("dns","timeout",0,DNT,&config_f);
326         ConfValue("options","moduledir",0,ModPath,&config_f);
327         ConfValue("disabled","commands",0,DisabledCommands,&config_f);
328         ConfValue("options","somaxconn",0,MCON,&config_f);
329         ConfValue("options","softlimit",0,SLIMT,&config_f);
330
331         SoftLimit = atoi(SLIMT);
332         if ((SoftLimit < 0) || (SoftLimit > MAXCLIENTS))
333         {
334                 log(DEFAULT,"WARNING: <options:softlimit> value is greater than %d or less than 0, set to %d.",MAXCLIENTS,MAXCLIENTS);
335                 SoftLimit = MAXCLIENTS;
336         }
337         MaxConn = atoi(MCON);
338         if (MaxConn > SOMAXCONN)
339                 log(DEFAULT,"WARNING: <options:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
340         NetBufferSize = atoi(NB);
341         MaxWhoResults = atoi(MW);
342         dns_timeout = atoi(DNT);
343         if (!dns_timeout)
344                 dns_timeout = 5;
345         if (!MaxConn)
346                 MaxConn = SOMAXCONN;
347         if (!DNSServer[0])
348                 strlcpy(DNSServer,"127.0.0.1",MAXBUF);
349         if (!ModPath[0])
350                 strlcpy(ModPath,MOD_PATH,MAXBUF);
351         AllowHalfop = ((!strcasecmp(AH,"true")) || (!strcasecmp(AH,"1")) || (!strcasecmp(AH,"yes")));
352         AllowProtect = ((!strcasecmp(AP,"true")) || (!strcasecmp(AP,"1")) || (!strcasecmp(AP,"yes")));
353         AllowFounder = ((!strcasecmp(AF,"true")) || (!strcasecmp(AF,"1")) || (!strcasecmp(AF,"yes")));
354         if ((!NetBufferSize) || (NetBufferSize > 65535) || (NetBufferSize < 1024))
355         {
356                 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
357                 NetBufferSize = 10240;
358         }
359         if ((!MaxWhoResults) || (MaxWhoResults > 65535) || (MaxWhoResults < 1))
360         {
361                 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
362                 MaxWhoResults = 128;
363         }
364         if (!strcmp(dbg,"debug"))
365                 LogLevel = DEBUG;
366         if (!strcmp(dbg,"verbose"))
367                 LogLevel = VERBOSE;
368         if (!strcmp(dbg,"default"))
369                 LogLevel = DEFAULT;
370         if (!strcmp(dbg,"sparse"))
371                 LogLevel = SPARSE;
372         if (!strcmp(dbg,"none"))
373                 LogLevel = NONE;
374         readfile(MOTD,motd);
375         log(DEFAULT,"Reading message of the day...");
376         readfile(RULES,rules);
377         log(DEFAULT,"Reading connect classes...");
378         Classes.clear();
379         for (int i = 0; i < ConfValueEnum("connect",&config_f); i++)
380         {
381                 strcpy(Value,"");
382                 ConfValue("connect","allow",i,Value,&config_f);
383                 ConfValue("connect","timeout",i,timeout,&config_f);
384                 ConfValue("connect","flood",i,flood,&config_f);
385                 ConfValue("connect","pingfreq",i,pfreq,&config_f);
386                 ConfValue("connect","threshold",i,thold,&config_f);
387                 ConfValue("connect","sendq",i,sqmax,&config_f);
388                 ConfValue("connect","recvq",i,rqmax,&config_f);
389                 if (Value[0])
390                 {
391                         strlcpy(c.host,Value,MAXBUF);
392                         c.type = CC_ALLOW;
393                         strlcpy(Value,"",MAXBUF);
394                         ConfValue("connect","password",i,Value,&config_f);
395                         strlcpy(c.pass,Value,MAXBUF);
396                         c.registration_timeout = 90; // default is 2 minutes
397                         c.pingtime = 120;
398                         c.flood = atoi(flood);
399                         c.threshold = 5;
400                         c.sendqmax = 262144; // 256k
401                         c.recvqmax = 4096;   // 4k
402                         if (atoi(thold)>0)
403                         {
404                                 c.threshold = atoi(thold);
405                         }
406                         if (atoi(sqmax)>0)
407                         {
408                                 c.sendqmax = atoi(sqmax);
409                         }
410                         if (atoi(rqmax)>0)
411                         {
412                                 c.recvqmax = atoi(rqmax);
413                         }
414                         if (atoi(timeout)>0)
415                         {
416                                 c.registration_timeout = atoi(timeout);
417                         }
418                         if (atoi(pfreq)>0)
419                         {
420                                 c.pingtime = atoi(pfreq);
421                         }
422                         Classes.push_back(c);
423                         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);
424                 }
425                 else
426                 {
427                         ConfValue("connect","deny",i,Value,&config_f);
428                         strlcpy(c.host,Value,MAXBUF);
429                         c.type = CC_DENY;
430                         Classes.push_back(c);
431                         log(DEBUG,"Read connect class type DENY, host=%s",c.host);
432                 }
433         
434         }
435         log(DEFAULT,"Reading K lines,Q lines and Z lines from config...");
436         read_xline_defaults();
437         log(DEFAULT,"Applying K lines, Q lines and Z lines...");
438         apply_lines();
439
440         autoconns.clear();
441         for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
442         {
443                 char Link_ServerName[MAXBUF],Link_AConn[MAXBUF];
444                 ConfValue("link","name",i,Link_ServerName,&config_f);
445                 ConfValue("link","autoconnect",i,Link_AConn,&config_f);
446                 if (strcmp(Link_AConn,""))
447                 {
448                         autoconns[std::string(Link_ServerName)] = atoi(Link_AConn) + time(NULL);
449                 }
450         }
451
452
453         log(DEFAULT,"Done reading configuration file, InspIRCd is now starting.");
454         if (!bail)
455         {
456                 log(DEFAULT,"Adding and removing modules due to rehash...");
457
458                 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
459
460                 // store the old module names
461                 for (std::vector<std::string>::iterator t = module_names.begin(); t != module_names.end(); t++)
462                 {
463                         old_module_names.push_back(*t);
464                 }
465
466                 // get the new module names
467                 for (int count2 = 0; count2 < ConfValueEnum("module",&config_f); count2++)
468                 {
469                         ConfValue("module","name",count2,Value,&config_f);
470                         new_module_names.push_back(Value);
471                 }
472
473                 // now create a list of new modules that are due to be loaded
474                 // and a seperate list of modules which are due to be unloaded
475                 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
476                 {
477                         bool added = true;
478                         for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
479                         {
480                                 if (*old == *_new)
481                                         added = false;
482                         }
483                         if (added)
484                                 added_modules.push_back(*_new);
485                 }
486                 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
487                 {
488                         bool removed = true;
489                         for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
490                         {
491                                 if (*newm == *oldm)
492                                         removed = false;
493                         }
494                         if (removed)
495                                 removed_modules.push_back(*oldm);
496                 }
497                 // now we have added_modules, a vector of modules to be loaded, and removed_modules, a vector of modules
498                 // to be removed.
499                 int rem = 0, add = 0;
500                 if (!removed_modules.empty())
501                 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
502                 {
503                         if (UnloadModule(removing->c_str()))
504                         {
505                                 WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
506                                 WriteServ(user->fd,"973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
507                                 rem++;
508                         }
509                         else
510                         {
511                                 WriteServ(user->fd,"972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ModuleError());
512                         }
513                 }
514                 if (!added_modules.empty())
515                 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
516                 {
517                         if (LoadModule(adding->c_str()))
518                         {
519                                 WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
520                                 WriteServ(user->fd,"975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
521                                 add++;
522                         }
523                         else
524                         {
525                                 WriteServ(user->fd,"974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ModuleError());
526                         }
527                 }
528                 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());
529         }
530 }
531
532
533 /* add a channel to a user, creating the record for it if needed and linking
534  * it to the user record */
535
536 chanrec* add_channel(userrec *user, const char* cn, const char* key, bool override)
537 {
538         if ((!user) || (!cn))
539         {
540                 log(DEFAULT,"*** BUG *** add_channel was given an invalid parameter");
541                 return 0;
542         }
543
544         chanrec* Ptr;
545         int created = 0;
546         char cname[MAXBUF];
547
548         strncpy(cname,cn,MAXBUF);
549         
550         // we MUST declare this wherever we use FOREACH_RESULT
551         int MOD_RESULT = 0;
552
553         if (strlen(cname) > CHANMAX)
554         {
555                 cname[CHANMAX] = '\0';
556         }
557
558         log(DEBUG,"add_channel: %s %s",user->nick,cname);
559         
560         if ((FindChan(cname)) && (has_channel(user,FindChan(cname))))
561         {
562                 return NULL; // already on the channel!
563         }
564
565
566         if (!FindChan(cname))
567         {
568                 MOD_RESULT = 0;
569                 FOREACH_RESULT(OnUserPreJoin(user,NULL,cname));
570                 if (MOD_RESULT == 1) {
571                         return NULL;
572                 }
573
574                 /* create a new one */
575                 log(DEBUG,"add_channel: creating: %s",cname);
576                 {
577                         chanlist[cname] = new chanrec();
578
579                         strlcpy(chanlist[cname]->name, cname,CHANMAX);
580                         chanlist[cname]->binarymodes = CM_TOPICLOCK | CM_NOEXTERNAL;
581                         chanlist[cname]->created = TIME;
582                         strcpy(chanlist[cname]->topic, "");
583                         strncpy(chanlist[cname]->setby, user->nick,NICKMAX);
584                         chanlist[cname]->topicset = 0;
585                         Ptr = chanlist[cname];
586                         log(DEBUG,"add_channel: created: %s",cname);
587                         /* set created to 2 to indicate user
588                          * is the first in the channel
589                          * and should be given ops */
590                         created = 2;
591                 }
592         }
593         else
594         {
595                 /* channel exists, just fish out a pointer to its struct */
596                 Ptr = FindChan(cname);
597                 if (Ptr)
598                 {
599                         log(DEBUG,"add_channel: joining to: %s",Ptr->name);
600                         
601                         // the override flag allows us to bypass channel modes
602                         // and bans (used by servers)
603                         if ((!override) || (!strcasecmp(user->server,ServerName)))
604                         {
605                                 log(DEBUG,"Not overriding...");
606                                 MOD_RESULT = 0;
607                                 FOREACH_RESULT(OnUserPreJoin(user,Ptr,cname));
608                                 if (MOD_RESULT == 1) {
609                                         return NULL;
610                                 }
611                                 log(DEBUG,"MOD_RESULT=%d",MOD_RESULT);
612                                 
613                                 if (!MOD_RESULT) 
614                                 {
615                                         log(DEBUG,"add_channel: checking key, invite, etc");
616                                         MOD_RESULT = 0;
617                                         FOREACH_RESULT(OnCheckKey(user, Ptr, key ? key : ""));
618                                         if (MOD_RESULT == 0)
619                                         {
620                                                 if (Ptr->key[0])
621                                                 {
622                                                         log(DEBUG,"add_channel: %s has key %s",Ptr->name,Ptr->key);
623                                                         if (!key)
624                                                         {
625                                                                 log(DEBUG,"add_channel: no key given in JOIN");
626                                                                 WriteServ(user->fd,"475 %s %s :Cannot join channel (Requires key)",user->nick, Ptr->name);
627                                                                 return NULL;
628                                                         }
629                                                         else
630                                                         {
631                                                                 if (strcasecmp(key,Ptr->key))
632                                                                 {
633                                                                         log(DEBUG,"add_channel: bad key given in JOIN");
634                                                                         WriteServ(user->fd,"475 %s %s :Cannot join channel (Incorrect key)",user->nick, Ptr->name);
635                                                                         return NULL;
636                                                                 }
637                                                         }
638                                                 }
639                                                 log(DEBUG,"add_channel: no key");
640                                         }
641                                         MOD_RESULT = 0;
642                                         FOREACH_RESULT(OnCheckInvite(user, Ptr));
643                                         if (MOD_RESULT == 0)
644                                         {
645                                                 if (Ptr->binarymodes & CM_INVITEONLY)
646                                                 {
647                                                         log(DEBUG,"add_channel: channel is +i");
648                                                         if (user->IsInvited(Ptr->name))
649                                                         {
650                                                                 /* user was invited to channel */
651                                                                 /* there may be an optional channel NOTICE here */
652                                                         }
653                                                         else
654                                                         {
655                                                                 WriteServ(user->fd,"473 %s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
656                                                                 return NULL;
657                                                         }
658                                                 }
659                                                 log(DEBUG,"add_channel: channel is not +i");
660                                         }
661                                         MOD_RESULT = 0;
662                                         FOREACH_RESULT(OnCheckLimit(user, Ptr));
663                                         if (MOD_RESULT == 0)
664                                         {
665                                                 if (Ptr->limit)
666                                                 {
667                                                         if (usercount(Ptr) >= Ptr->limit)
668                                                         {
669                                                                 WriteServ(user->fd,"471 %s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
670                                                                 return NULL;
671                                                         }
672                                                 }
673                                         }
674                                         log(DEBUG,"add_channel: about to walk banlist");
675                                         MOD_RESULT = 0;
676                                         FOREACH_RESULT(OnCheckBan(user, Ptr));
677                                         if (MOD_RESULT == 0)
678                                         {
679                                                 /* check user against the channel banlist */
680                                                 if (Ptr)
681                                                 {
682                                                         if (Ptr->bans.size())
683                                                         {
684                                                                 for (BanList::iterator i = Ptr->bans.begin(); i != Ptr->bans.end(); i++)
685                                                                 {
686                                                                         if (match(user->GetFullHost(),i->data))
687                                                                         {
688                                                                                 WriteServ(user->fd,"474 %s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
689                                                                                 return NULL;
690                                                                         }
691                                                                 }
692                                                         }
693                                                 }
694                                                 log(DEBUG,"add_channel: bans checked");
695                                         }
696                                 
697                                 }
698                                 
699
700                                 if ((Ptr) && (user))
701                                 {
702                                         user->RemoveInvite(Ptr->name);
703                                 }
704         
705                                 log(DEBUG,"add_channel: invites removed");
706
707                         }
708                         else
709                         {
710                                 log(DEBUG,"Overridden checks");
711                         }
712
713                         
714                 }
715                 created = 1;
716         }
717
718         log(DEBUG,"Passed channel checks");
719         
720         for (int index =0; index != MAXCHANS; index++)
721         {
722                 log(DEBUG,"Check location %d",index);
723                 if (user->chans[index].channel == NULL)
724                 {
725                         log(DEBUG,"Adding into their channel list at location %d",index);
726
727                         if (created == 2) 
728                         {
729                                 /* first user in is given ops */
730                                 user->chans[index].uc_modes = UCMODE_OP;
731                         }
732                         else
733                         {
734                                 user->chans[index].uc_modes = 0;
735                         }
736                         user->chans[index].channel = Ptr;
737                         Ptr->AddUser((char*)user);
738                         WriteChannel(Ptr,user,"JOIN :%s",Ptr->name);
739                         
740                         if (!override) // we're not overriding... so this isnt part of a netburst, broadcast it.
741                         {
742                                 // use the stamdard J token with no privilages.
743                                 char buffer[MAXBUF];
744                                 if (created == 2)
745                                 {
746                                         snprintf(buffer,MAXBUF,"J %s @%s",user->nick,Ptr->name);
747                                 }
748                                 else
749                                 {
750                                         snprintf(buffer,MAXBUF,"J %s %s",user->nick,Ptr->name);
751                                 }
752                                 NetSendToAll(buffer);
753                         }
754
755                         log(DEBUG,"Sent JOIN to client");
756
757                         if (Ptr->topicset)
758                         {
759                                 WriteServ(user->fd,"332 %s %s :%s", user->nick, Ptr->name, Ptr->topic);
760                                 WriteServ(user->fd,"333 %s %s %s %lu", user->nick, Ptr->name, Ptr->setby, (unsigned long)Ptr->topicset);
761                         }
762                         userlist(user,Ptr);
763                         WriteServ(user->fd,"366 %s %s :End of /NAMES list.", user->nick, Ptr->name);
764                         //WriteServ(user->fd,"324 %s %s +%s",user->nick, Ptr->name,chanmodes(Ptr));
765                         //WriteServ(user->fd,"329 %s %s %lu", user->nick, Ptr->name, (unsigned long)Ptr->created);
766                         FOREACH_MOD OnUserJoin(user,Ptr);
767                         return Ptr;
768                 }
769         }
770         log(DEBUG,"add_channel: user channel max exceeded: %s %s",user->nick,cname);
771         WriteServ(user->fd,"405 %s %s :You are on too many channels",user->nick, cname);
772         return NULL;
773 }
774
775 /* remove a channel from a users record, and remove the record from memory
776  * if the channel has become empty */
777
778 chanrec* del_channel(userrec *user, const char* cname, const char* reason, bool local)
779 {
780         if ((!user) || (!cname))
781         {
782                 log(DEFAULT,"*** BUG *** del_channel was given an invalid parameter");
783                 return NULL;
784         }
785
786         chanrec* Ptr;
787
788         if ((!cname) || (!user))
789         {
790                 return NULL;
791         }
792
793         Ptr = FindChan(cname);
794         
795         if (!Ptr)
796         {
797                 return NULL;
798         }
799
800         FOREACH_MOD OnUserPart(user,Ptr);
801         log(DEBUG,"del_channel: removing: %s %s",user->nick,Ptr->name);
802         
803         for (int i =0; i != MAXCHANS; i++)
804         {
805                 /* zap it from the channel list of the user */
806                 if (user->chans[i].channel == Ptr)
807                 {
808                         if (reason)
809                         {
810                                 WriteChannel(Ptr,user,"PART %s :%s",Ptr->name, reason);
811
812                                 if (!local)
813                                 {
814                                         char buffer[MAXBUF];
815                                         snprintf(buffer,MAXBUF,"L %s %s :%s",user->nick,Ptr->name,reason);
816                                         NetSendToAll(buffer);
817                                 }
818
819                                 
820                         }
821                         else
822                         {
823                                 if (!local)
824                                 {
825                                         char buffer[MAXBUF];
826                                         snprintf(buffer,MAXBUF,"L %s %s :",user->nick,Ptr->name);
827                                         NetSendToAll(buffer);
828                                 }
829                         
830                                 WriteChannel(Ptr,user,"PART :%s",Ptr->name);
831                         }
832                         user->chans[i].uc_modes = 0;
833                         user->chans[i].channel = NULL;
834                         log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
835                         break;
836                 }
837         }
838
839         Ptr->DelUser((char*)user);
840         
841         /* if there are no users left on the channel */
842         if (!usercount(Ptr))
843         {
844                 chan_hash::iterator iter = chanlist.find(Ptr->name);
845
846                 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
847
848                 /* kill the record */
849                 if (iter != chanlist.end())
850                 {
851                         log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
852                         delete Ptr;
853                         chanlist.erase(iter);
854                 }
855         }
856
857         return NULL;
858 }
859
860
861 void kick_channel(userrec *src,userrec *user, chanrec *Ptr, char* reason)
862 {
863         if ((!src) || (!user) || (!Ptr) || (!reason))
864         {
865                 log(DEFAULT,"*** BUG *** kick_channel was given an invalid parameter");
866                 return;
867         }
868
869         if ((!Ptr) || (!user) || (!src))
870         {
871                 return;
872         }
873
874         log(DEBUG,"kick_channel: removing: %s %s %s",user->nick,Ptr->name,src->nick);
875
876         if (!has_channel(user,Ptr))
877         {
878                 WriteServ(src->fd,"441 %s %s %s :They are not on that channel",src->nick, user->nick, Ptr->name);
879                 return;
880         }
881
882         int MOD_RESULT = 0;
883         FOREACH_RESULT(OnAccessCheck(src,user,Ptr,AC_KICK));
884         if (MOD_RESULT == ACR_DENY)
885                 return;
886
887         if (MOD_RESULT == ACR_DEFAULT)
888         {
889                 if (((cstatus(src,Ptr) < STATUS_HOP) || (cstatus(src,Ptr) < cstatus(user,Ptr))) && (!is_uline(src->server)))
890                 {
891                         if (cstatus(src,Ptr) == STATUS_HOP)
892                         {
893                                 WriteServ(src->fd,"482 %s %s :You must be a channel operator",src->nick, Ptr->name);
894                         }
895                         else
896                         {
897                                 WriteServ(src->fd,"482 %s %s :You must be at least a half-operator to change modes on this channel",src->nick, Ptr->name);
898                         }
899                         
900                         return;
901                 }
902         }
903
904         MOD_RESULT = 0;
905         FOREACH_RESULT(OnUserPreKick(src,user,Ptr,reason));
906         if (MOD_RESULT)
907                 return;
908
909         FOREACH_MOD OnUserKick(src,user,Ptr,reason);
910
911         for (int i =0; i != MAXCHANS; i++)
912         {
913                 /* zap it from the channel list of the user */
914                 if (user->chans[i].channel)
915                 if (!strcasecmp(user->chans[i].channel->name,Ptr->name))
916                 {
917                         WriteChannel(Ptr,src,"KICK %s %s :%s",Ptr->name, user->nick, reason);
918                         user->chans[i].uc_modes = 0;
919                         user->chans[i].channel = NULL;
920                         log(DEBUG,"del_channel: unlinked: %s %s",user->nick,Ptr->name);
921                         break;
922                 }
923         }
924
925         Ptr->DelUser((char*)user);
926
927         /* if there are no users left on the channel */
928         if (!usercount(Ptr))
929         {
930                 chan_hash::iterator iter = chanlist.find(Ptr->name);
931
932                 log(DEBUG,"del_channel: destroying channel: %s",Ptr->name);
933
934                 /* kill the record */
935                 if (iter != chanlist.end())
936                 {
937                         log(DEBUG,"del_channel: destroyed: %s",Ptr->name);
938                         delete Ptr;
939                         chanlist.erase(iter);
940                 }
941         }
942 }
943
944
945
946
947 /* This function pokes and hacks at a parameter list like the following:
948  *
949  * PART #winbot,#darkgalaxy :m00!
950  *
951  * to turn it into a series of individual calls like this:
952  *
953  * PART #winbot :m00!
954  * PART #darkgalaxy :m00!
955  *
956  * The seperate calls are sent to a callback function provided by the caller
957  * (the caller will usually call itself recursively). The callback function
958  * must be a command handler. Calling this function on a line with no list causes
959  * no action to be taken. You must provide a starting and ending parameter number
960  * where the range of the list can be found, useful if you have a terminating
961  * parameter as above which is actually not part of the list, or parameters
962  * before the actual list as well. This code is used by many functions which
963  * can function as "one to list" (see the RFC) */
964
965 int loop_call(handlerfunc fn, char **parameters, int pcnt, userrec *u, int start, int end, int joins)
966 {
967         char plist[MAXBUF];
968         char *param;
969         char *pars[32];
970         char blog[32][MAXBUF];
971         char blog2[32][MAXBUF];
972         int j = 0, q = 0, total = 0, t = 0, t2 = 0, total2 = 0;
973         char keystr[MAXBUF];
974         char moo[MAXBUF];
975
976         for (int i = 0; i <32; i++)
977                 strcpy(blog[i],"");
978
979         for (int i = 0; i <32; i++)
980                 strcpy(blog2[i],"");
981
982         strcpy(moo,"");
983         for (int i = 0; i <10; i++)
984         {
985                 if (!parameters[i])
986                 {
987                         parameters[i] = moo;
988                 }
989         }
990         if (joins)
991         {
992                 if (pcnt > 1) /* we have a key to copy */
993                 {
994                         strlcpy(keystr,parameters[1],MAXBUF);
995                 }
996         }
997
998         if (!parameters[start])
999         {
1000                 return 0;
1001         }
1002         if (!strchr(parameters[start],','))
1003         {
1004                 return 0;
1005         }
1006         strcpy(plist,"");
1007         for (int i = start; i <= end; i++)
1008         {
1009                 if (parameters[i])
1010                 {
1011                         strlcat(plist,parameters[i],MAXBUF);
1012                 }
1013         }
1014         
1015         j = 0;
1016         param = plist;
1017
1018         t = strlen(plist);
1019         for (int i = 0; i < t; i++)
1020         {
1021                 if (plist[i] == ',')
1022                 {
1023                         plist[i] = '\0';
1024                         strlcpy(blog[j++],param,MAXBUF);
1025                         param = plist+i+1;
1026                         if (j>20)
1027                         {
1028                                 WriteServ(u->fd,"407 %s %s :Too many targets in list, message not delivered.",u->nick,blog[j-1]);
1029                                 return 1;
1030                         }
1031                 }
1032         }
1033         strlcpy(blog[j++],param,MAXBUF);
1034         total = j;
1035
1036         if ((joins) && (keystr) && (total>0)) // more than one channel and is joining
1037         {
1038                 strcat(keystr,",");
1039         }
1040         
1041         if ((joins) && (keystr))
1042         {
1043                 if (strchr(keystr,','))
1044                 {
1045                         j = 0;
1046                         param = keystr;
1047                         t2 = strlen(keystr);
1048                         for (int i = 0; i < t2; i++)
1049                         {
1050                                 if (keystr[i] == ',')
1051                                 {
1052                                         keystr[i] = '\0';
1053                                         strlcpy(blog2[j++],param,MAXBUF);
1054                                         param = keystr+i+1;
1055                                 }
1056                         }
1057                         strlcpy(blog2[j++],param,MAXBUF);
1058                         total2 = j;
1059                 }
1060         }
1061
1062         for (j = 0; j < total; j++)
1063         {
1064                 if (blog[j])
1065                 {
1066                         pars[0] = blog[j];
1067                 }
1068                 for (q = end; q < pcnt-1; q++)
1069                 {
1070                         if (parameters[q+1])
1071                         {
1072                                 pars[q-end+1] = parameters[q+1];
1073                         }
1074                 }
1075                 if ((joins) && (parameters[1]))
1076                 {
1077                         if (pcnt > 1)
1078                         {
1079                                 pars[1] = blog2[j];
1080                         }
1081                         else
1082                         {
1083                                 pars[1] = NULL;
1084                         }
1085                 }
1086                 /* repeatedly call the function with the hacked parameter list */
1087                 if ((joins) && (pcnt > 1))
1088                 {
1089                         if (pars[1])
1090                         {
1091                                 // pars[1] already set up and containing key from blog2[j]
1092                                 fn(pars,2,u);
1093                         }
1094                         else
1095                         {
1096                                 pars[1] = parameters[1];
1097                                 fn(pars,2,u);
1098                         }
1099                 }
1100                 else
1101                 {
1102                         fn(pars,pcnt-(end-start),u);
1103                 }
1104         }
1105
1106         return 1;
1107 }
1108
1109
1110
1111 void kill_link(userrec *user,const char* r)
1112 {
1113         user_hash::iterator iter = clientlist.find(user->nick);
1114         
1115         char reason[MAXBUF];
1116         
1117         strncpy(reason,r,MAXBUF);
1118
1119         if (strlen(reason)>MAXQUIT)
1120         {
1121                 reason[MAXQUIT-1] = '\0';
1122         }
1123
1124         log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1125         Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1126         log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
1127
1128         if (user->registered == 7) {
1129                 FOREACH_MOD OnUserQuit(user);
1130                 WriteCommonExcept(user,"QUIT :%s",reason);
1131
1132                 // Q token must go to ALL servers!!!
1133                 char buffer[MAXBUF];
1134                 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
1135                 NetSendToAll(buffer);
1136         }
1137
1138         user->FlushWriteBuf();
1139
1140         FOREACH_MOD OnUserDisconnect(user);
1141
1142         if (user->fd > -1)
1143         {
1144                 FOREACH_MOD OnRawSocketClose(user->fd);
1145 #ifdef USE_KQUEUE
1146                 struct kevent ke;
1147                 EV_SET(&ke, user->fd, EVFILT_READ, EV_DELETE, 0, 0, NULL);
1148                 int i = kevent(kq, &ke, 1, 0, 0, NULL);
1149                 if (i == -1)
1150                 {
1151                         log(DEBUG,"kqueue: Failed to remove user from queue!");
1152                 }
1153 #endif
1154 #ifdef USE_EPOLL
1155                 struct epoll_event ev;
1156                 ev.events = EPOLLIN | EPOLLET;
1157                 ev.data.fd = user->fd;
1158                 int i = epoll_ctl(ep, EPOLL_CTL_DEL, user->fd, &ev);
1159                 if (i < 0)
1160                 {
1161                         log(DEBUG,"epoll: List deletion failure!");
1162                 }
1163 #endif
1164                 user->CloseSocket();
1165         }
1166
1167         // this must come before the WriteOpers so that it doesnt try to fill their buffer with anything
1168         // if they were an oper with +s.
1169         if (user->registered == 7) {
1170                 purge_empty_chans(user);
1171                 // fix by brain: only show local quits because we only show local connects (it just makes SENSE)
1172                 if (!strcmp(user->server,ServerName))
1173                         WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
1174                 AddWhoWas(user);
1175         }
1176
1177         if (iter != clientlist.end())
1178         {
1179                 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
1180                 if (user->fd > -1)
1181                         fd_ref_table[user->fd] = NULL;
1182                 clientlist.erase(iter);
1183         }
1184         delete user;
1185 }
1186
1187 void kill_link_silent(userrec *user,const char* r)
1188 {
1189         user_hash::iterator iter = clientlist.find(user->nick);
1190         
1191         char reason[MAXBUF];
1192         
1193         strncpy(reason,r,MAXBUF);
1194
1195         if (strlen(reason)>MAXQUIT)
1196         {
1197                 reason[MAXQUIT-1] = '\0';
1198         }
1199
1200         log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1201         Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1202         log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
1203
1204         user->FlushWriteBuf();
1205
1206         if (user->registered == 7) {
1207                 FOREACH_MOD OnUserQuit(user);
1208                 WriteCommonExcept(user,"QUIT :%s",reason);
1209
1210                 // Q token must go to ALL servers!!!
1211                 char buffer[MAXBUF];
1212                 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
1213                 NetSendToAll(buffer);
1214         }
1215
1216         FOREACH_MOD OnUserDisconnect(user);
1217
1218         if (user->fd > -1)
1219         {
1220                 FOREACH_MOD OnRawSocketClose(user->fd);
1221 #ifdef USE_KQUEUE
1222                 struct kevent ke;
1223                 EV_SET(&ke, user->fd, EVFILT_READ, EV_DELETE, 0, 0, NULL);
1224                 int i = kevent(kq, &ke, 1, 0, 0, NULL);
1225                 if (i == -1)
1226                 {
1227                         log(DEBUG,"kqueue: Failed to remove user from queue!");
1228                 }
1229 #endif
1230 #ifdef USE_EPOLL
1231                 struct epoll_event ev;
1232                 ev.events = EPOLLIN | EPOLLET;
1233                 ev.data.fd = user->fd;
1234                 int i = epoll_ctl(ep, EPOLL_CTL_DEL, user->fd, &ev);
1235                 if (i < 0)
1236                 {
1237                         log(DEBUG,"epoll: List deletion failure!");
1238                 }
1239 #endif
1240                 user->CloseSocket();
1241         }
1242
1243         if (user->registered == 7) {
1244                 purge_empty_chans(user);
1245         }
1246         
1247         if (iter != clientlist.end())
1248         {
1249                 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
1250                 if (user->fd > -1)
1251                         fd_ref_table[user->fd] = NULL;
1252                 clientlist.erase(iter);
1253         }
1254         delete user;
1255 }
1256
1257
1258 int main(int argc, char** argv)
1259 {
1260         Start();
1261         srand(time(NULL));
1262         log(DEBUG,"*** InspIRCd starting up!");
1263         if (!FileExists(CONFIG_FILE))
1264         {
1265                 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
1266                 log(DEFAULT,"main: no config");
1267                 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
1268                 Exit(ERROR);
1269         }
1270         if (argc > 1) {
1271                 for (int i = 1; i < argc; i++)
1272                 {
1273                         if (!strcmp(argv[i],"-nofork")) {
1274                                 nofork = true;
1275                         }
1276                         if (!strcmp(argv[i],"-wait")) {
1277                                 sleep(6);
1278                         }
1279                         if (!strcmp(argv[i],"-nolimit")) {
1280                                 unlimitcore = true;
1281                         }
1282                 }
1283         }
1284         strlcpy(MyExecutable,argv[0],MAXBUF);
1285         
1286         // initialize the lowercase mapping table
1287         for (unsigned int cn = 0; cn < 256; cn++)
1288                 lowermap[cn] = cn;
1289         // lowercase the uppercase chars
1290         for (unsigned int cn = 65; cn < 91; cn++)
1291                 lowermap[cn] = tolower(cn);
1292         // now replace the specific chars for scandanavian comparison
1293         lowermap[(unsigned)'['] = '{';
1294         lowermap[(unsigned)']'] = '}';
1295         lowermap[(unsigned)'\\'] = '|';
1296
1297         if (InspIRCd(argv,argc) == ERROR)
1298         {
1299                 log(DEFAULT,"main: daemon function bailed");
1300                 printf("ERROR: could not initialise. Shutting down.\n");
1301                 Exit(ERROR);
1302         }
1303         Exit(TRUE);
1304         return 0;
1305 }
1306
1307 template<typename T> inline string ConvToStr(const T &in)
1308 {
1309         stringstream tmp;
1310         if (!(tmp << in)) return string();
1311         return tmp.str();
1312 }
1313
1314 /* re-allocates a nick in the user_hash after they change nicknames,
1315  * returns a pointer to the new user as it may have moved */
1316
1317 userrec* ReHashNick(char* Old, char* New)
1318 {
1319         //user_hash::iterator newnick;
1320         user_hash::iterator oldnick = clientlist.find(Old);
1321
1322         log(DEBUG,"ReHashNick: %s %s",Old,New);
1323         
1324         if (!strcasecmp(Old,New))
1325         {
1326                 log(DEBUG,"old nick is new nick, skipping");
1327                 return oldnick->second;
1328         }
1329         
1330         if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
1331
1332         log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
1333
1334         userrec* olduser = oldnick->second;
1335         clientlist[New] = olduser;
1336         clientlist.erase(oldnick);
1337
1338         log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
1339         
1340         return clientlist[New];
1341 }
1342
1343 /* adds or updates an entry in the whowas list */
1344 void AddWhoWas(userrec* u)
1345 {
1346         whowas_hash::iterator iter = whowas.find(u->nick);
1347         WhoWasUser *a = new WhoWasUser();
1348         strlcpy(a->nick,u->nick,NICKMAX);
1349         strlcpy(a->ident,u->ident,IDENTMAX);
1350         strlcpy(a->dhost,u->dhost,160);
1351         strlcpy(a->host,u->host,160);
1352         strlcpy(a->fullname,u->fullname,MAXGECOS);
1353         strlcpy(a->server,u->server,256);
1354         a->signon = u->signon;
1355
1356         /* MAX_WHOWAS:   max number of /WHOWAS items
1357          * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
1358          *               can be replaced by a newer one
1359          */
1360         
1361         if (iter == whowas.end())
1362         {
1363                 if (whowas.size() >= (unsigned)WHOWAS_MAX)
1364                 {
1365                         for (whowas_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
1366                         {
1367                                 // 3600 seconds in an hour ;)
1368                                 if ((i->second->signon)<(TIME-(WHOWAS_STALE*3600)))
1369                                 {
1370                                         // delete the old one
1371                                         if (i->second) delete i->second;
1372                                         // replace with new one
1373                                         i->second = a;
1374                                         log(DEBUG,"added WHOWAS entry, purged an old record");
1375                                         return;
1376                                 }
1377                         }
1378                         // no space left and user doesnt exist. Don't leave ram in use!
1379                         log(DEBUG,"Not able to update whowas (list at WHOWAS_MAX entries and trying to add new?), freeing excess ram");
1380                         delete a;
1381                 }
1382                 else
1383                 {
1384                         log(DEBUG,"added fresh WHOWAS entry");
1385                         whowas[a->nick] = a;
1386                 }
1387         }
1388         else
1389         {
1390                 log(DEBUG,"updated WHOWAS entry");
1391                 if (iter->second) delete iter->second;
1392                 iter->second = a;
1393         }
1394 }
1395
1396
1397 /* add a client connection to the sockets list */
1398 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
1399 {
1400         string tempnick;
1401         char tn2[MAXBUF];
1402         user_hash::iterator iter;
1403
1404         tempnick = ConvToStr(socket) + "-unknown";
1405         sprintf(tn2,"%lu-unknown",(unsigned long)socket);
1406
1407         iter = clientlist.find(tempnick);
1408
1409         // fix by brain.
1410         // as these nicknames are 'RFC impossible', we can be sure nobody is going to be
1411         // using one as a registered connection. As theyre per fd, we can also safely assume
1412         // that we wont have collisions. Therefore, if the nick exists in the list, its only
1413         // used by a dead socket, erase the iterator so that the new client may reclaim it.
1414         // this was probably the cause of 'server ignores me when i hammer it with reconnects'
1415         // issue in earlier alphas/betas
1416         if (iter != clientlist.end())
1417         {
1418                 userrec* goner = iter->second;
1419                 delete goner;
1420                 clientlist.erase(iter);
1421         }
1422
1423         /*
1424          * It is OK to access the value here this way since we know
1425          * it exists, we just created it above.
1426          *
1427          * At NO other time should you access a value in a map or a
1428          * hash_map this way.
1429          */
1430         clientlist[tempnick] = new userrec();
1431
1432         NonBlocking(socket);
1433         log(DEBUG,"AddClient: %lu %s %d %s",(unsigned long)socket,host,port,ip);
1434
1435         clientlist[tempnick]->fd = socket;
1436         strlcpy(clientlist[tempnick]->nick, tn2,NICKMAX);
1437         strlcpy(clientlist[tempnick]->host, host,160);
1438         strlcpy(clientlist[tempnick]->dhost, host,160);
1439         clientlist[tempnick]->server = (char*)FindServerNamePtr(ServerName);
1440         strlcpy(clientlist[tempnick]->ident, "unknown",IDENTMAX);
1441         clientlist[tempnick]->registered = 0;
1442         clientlist[tempnick]->signon = TIME+dns_timeout;
1443         clientlist[tempnick]->lastping = 1;
1444         clientlist[tempnick]->port = port;
1445         strlcpy(clientlist[tempnick]->ip,ip,16);
1446
1447         // set the registration timeout for this user
1448         unsigned long class_regtimeout = 90;
1449         int class_flood = 0;
1450         long class_threshold = 5;
1451         long class_sqmax = 262144;      // 256kb
1452         long class_rqmax = 4096;        // 4k
1453
1454         for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
1455         {
1456                 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
1457                 {
1458                         class_regtimeout = (unsigned long)i->registration_timeout;
1459                         class_flood = i->flood;
1460                         clientlist[tempnick]->pingmax = i->pingtime;
1461                         class_threshold = i->threshold;
1462                         class_sqmax = i->sendqmax;
1463                         class_rqmax = i->recvqmax;
1464                         break;
1465                 }
1466         }
1467
1468         clientlist[tempnick]->nping = TIME+clientlist[tempnick]->pingmax+dns_timeout;
1469         clientlist[tempnick]->timeout = TIME+class_regtimeout;
1470         clientlist[tempnick]->flood = class_flood;
1471         clientlist[tempnick]->threshold = class_threshold;
1472         clientlist[tempnick]->sendqmax = class_sqmax;
1473         clientlist[tempnick]->recvqmax = class_rqmax;
1474
1475         for (int i = 0; i < MAXCHANS; i++)
1476         {
1477                 clientlist[tempnick]->chans[i].channel = NULL;
1478                 clientlist[tempnick]->chans[i].uc_modes = 0;
1479         }
1480
1481         if (clientlist.size() > SoftLimit)
1482         {
1483                 kill_link(clientlist[tempnick],"No more connections allowed");
1484                 return;
1485         }
1486
1487         if (clientlist.size() >= MAXCLIENTS)
1488         {
1489                 kill_link(clientlist[tempnick],"No more connections allowed");
1490                 return;
1491         }
1492
1493         // this is done as a safety check to keep the file descriptors within range of fd_ref_table.
1494         // its a pretty big but for the moment valid assumption:
1495         // file descriptors are handed out starting at 0, and are recycled as theyre freed.
1496         // therefore if there is ever an fd over 65535, 65536 clients must be connected to the
1497         // irc server at once (or the irc server otherwise initiating this many connections, files etc)
1498         // which for the time being is a physical impossibility (even the largest networks dont have more
1499         // than about 10,000 users on ONE server!)
1500         if ((unsigned)socket > 65534)
1501         {
1502                 kill_link(clientlist[tempnick],"Server is full");
1503                 return;
1504         }
1505                 
1506
1507         char* e = matches_exception(ip);
1508         if (!e)
1509         {
1510                 char* r = matches_zline(ip);
1511                 if (r)
1512                 {
1513                         char reason[MAXBUF];
1514                         snprintf(reason,MAXBUF,"Z-Lined: %s",r);
1515                         kill_link(clientlist[tempnick],reason);
1516                         return;
1517                 }
1518         }
1519         fd_ref_table[socket] = clientlist[tempnick];
1520
1521 #ifdef USE_EPOLL
1522         struct epoll_event ev;
1523         log(DEBUG,"epoll: Adduser to events, ep=%d socket=%d",ep,socket);
1524         ev.events = EPOLLIN | EPOLLET;
1525         ev.data.fd = socket;
1526         int i = epoll_ctl(ep, EPOLL_CTL_ADD, socket, &ev);
1527         if (i < 0)
1528         {
1529                 log(DEBUG,"epoll: List insertion failure!");
1530         }
1531 #endif
1532 #ifdef USE_KQUEUE
1533         struct kevent ke;
1534         log(DEBUG,"kqueue: Add user to events, kq=%d socket=%d",kq,socket);
1535         EV_SET(&ke, socket, EVFILT_READ, EV_ADD, 0, 0, NULL);
1536         int i = kevent(kq, &ke, 1, 0, 0, NULL);
1537         if (i == -1)
1538         {
1539                 log(DEBUG,"kqueue: List insertion failure!");
1540         }
1541
1542 #endif
1543 }
1544
1545 /* shows the message of the day, and any other on-logon stuff */
1546 void FullConnectUser(userrec* user)
1547 {
1548         statsConnects++;
1549         user->idle_lastmsg = TIME;
1550         log(DEBUG,"ConnectUser: %s",user->nick);
1551
1552         if ((strcmp(Passwd(user),"")) && (!user->haspassed))
1553         {
1554                 kill_link(user,"Invalid password");
1555                 return;
1556         }
1557         if (IsDenied(user))
1558         {
1559                 kill_link(user,"Unauthorised connection");
1560                 return;
1561         }
1562
1563         char match_against[MAXBUF];
1564         snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
1565         char* e = matches_exception(match_against);
1566         if (!e)
1567         {
1568                 char* r = matches_gline(match_against);
1569                 if (r)
1570                 {
1571                         char reason[MAXBUF];
1572                         snprintf(reason,MAXBUF,"G-Lined: %s",r);
1573                         kill_link_silent(user,reason);
1574                         return;
1575                 }
1576                 r = matches_kline(user->host);
1577                 if (r)
1578                 {
1579                         char reason[MAXBUF];
1580                         snprintf(reason,MAXBUF,"K-Lined: %s",r);
1581                         kill_link_silent(user,reason);
1582                         return;
1583                 }
1584         }
1585
1586         // fix by brain: move this below the xline checks to prevent spurious quits going onto the net that dont belong
1587         user->registered = 7;
1588
1589         WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
1590         WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
1591         WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
1592         WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
1593         WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
1594         // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
1595         std::stringstream v;
1596         v << "MESHED WALLCHOPS MODES=13 CHANTYPES=# PREFIX=(ohv)@%+ MAP SAFELIST MAXCHANNELS=" << MAXCHANS;
1597         v << " MAXBANS=60 NICKLEN=" << NICKMAX;
1598         v << " TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=20 AWAYLEN=" << MAXAWAY << " CHANMODES=ohvb,k,l,psmnti NETWORK=";
1599         v << Network;
1600         std::string data005 = v.str();
1601         FOREACH_MOD On005Numeric(data005);
1602         // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
1603         // so i'd better split it :)
1604         std::stringstream out(data005);
1605         std::string token = "";
1606         std::string line5 = "";
1607         int token_counter = 0;
1608         while (!out.eof())
1609         {
1610                 out >> token;
1611                 line5 = line5 + token + " ";
1612                 token_counter++;
1613                 if ((token_counter >= 13) || (out.eof() == true))
1614                 {
1615                         WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
1616                         line5 = "";
1617                         token_counter = 0;
1618                 }
1619         }
1620         ShowMOTD(user);
1621
1622         char buffer[MAXBUF];
1623         snprintf(buffer,MAXBUF,"N %lu %s %s %s %s +%s %s %s :%s",(unsigned long)user->age,user->nick,user->host,user->dhost,user->ident,user->modes,user->ip,ServerName,user->fullname);
1624         NetSendToAll(buffer);
1625
1626         // fix by brain: these should be AFTER the N token, so other servers know what the HELL we're on about... :)
1627         FOREACH_MOD OnUserConnect(user);
1628         FOREACH_MOD OnGlobalConnect(user);
1629         WriteOpers("*** Client connecting on port %lu: %s!%s@%s [%s]",(unsigned long)user->port,user->nick,user->ident,user->host,user->ip);
1630 }
1631
1632
1633 /* shows the message of the day, and any other on-logon stuff */
1634 void ConnectUser(userrec *user)
1635 {
1636         // dns is already done, things are fast. no need to wait for dns to complete just pass them straight on
1637         if ((user->dns_done) && (user->registered >= 3) && (AllModulesReportReady(user)))
1638         {
1639                 FullConnectUser(user);
1640         }
1641 }
1642
1643 std::string GetVersionString()
1644 {
1645         char Revision[] = "$Revision$";
1646         char versiondata[MAXBUF];
1647         char *s1 = Revision;
1648         char *savept;
1649         char *v2 = strtok_r(s1," ",&savept);
1650         s1 = savept;
1651         v2 = strtok_r(s1," ",&savept);
1652         s1 = savept;
1653 #ifdef USE_KQUEUE
1654         char socketengine[] = "kqueue";
1655 #endif
1656 #ifdef USE_SELECT
1657         char socketengine[] = "select";
1658 #endif
1659 #ifdef USE_EPOLL
1660         char socketengine[] = "epoll";
1661 #endif
1662         snprintf(versiondata,MAXBUF,"%s Rev. %s %s :%s (O=%lu) [SE=%s]",VERSION,v2,ServerName,SYSTEM,(unsigned long)OPTIMISATION,socketengine);
1663         return versiondata;
1664 }
1665
1666 void handle_version(char **parameters, int pcnt, userrec *user)
1667 {
1668         if (!pcnt)
1669         {
1670                 WriteServ(user->fd,"351 %s :%s",user->nick,GetVersionString().c_str());
1671         }
1672         else
1673         {
1674                 if (!strcmp(parameters[0],"*"))
1675                 {
1676                         for (int j = 0; j < 32; j++)
1677                         {
1678                                 if (me[j] != NULL)
1679                                 {
1680                                         for (unsigned int x = 0; x < me[j]->connectors.size(); x++)
1681                                         {
1682                                                 WriteServ(user->fd,"351 %s :Server %d:%d (%s): %s",user->nick,j,x,me[j]->connectors[x].GetServerName().c_str(),me[j]->connectors[x].GetVersionString().c_str());
1683                                         }
1684                                 }
1685                         }
1686                         return;
1687                 }
1688                 if (match(ServerName,parameters[0]))
1689                 {
1690                         WriteServ(user->fd,"351 %s :%s",user->nick,GetVersionString().c_str());
1691                         return;
1692                 }
1693                 bool displayed = false, found = false;
1694                 for (int j = 0; j < 32; j++)
1695                 {
1696                         if (me[j] != NULL)
1697                         {
1698                                 for (unsigned int x = 0; x < me[j]->connectors.size(); x++)
1699                                 {
1700                                         if (match(me[j]->connectors[x].GetServerName().c_str(),parameters[0]))
1701                                         {
1702                                                 found = true;
1703                                                 if ((me[j]->connectors[x].GetVersionString() != "") && (!displayed))
1704                                                 {
1705                                                         displayed = true;
1706                                                         WriteServ(user->fd,"351 %s :%s",user->nick,me[j]->connectors[x].GetVersionString().c_str());
1707                                                 }
1708                                         }
1709                                 }
1710                         }
1711                 }
1712                 if ((!displayed) && (found))
1713                 {
1714                         WriteServ(user->fd,"402 %s %s :Server %s has no version information",user->nick,parameters[0],parameters[0]);
1715                         return;
1716                 }
1717                 if (!found)
1718                 {
1719                         WriteServ(user->fd,"402 %s %s :No such server",user->nick,parameters[0]);
1720                 }
1721         }
1722         return;
1723 }
1724
1725
1726 // calls a handler function for a command
1727
1728 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
1729 {
1730                 for (unsigned int i = 0; i < cmdlist.size(); i++)
1731                 {
1732                         if (!strcasecmp(cmdlist[i].command,commandname))
1733                         {
1734                                 if (cmdlist[i].handler_function)
1735                                 {
1736                                         if (pcnt>=cmdlist[i].min_params)
1737                                         {
1738                                                 if (strchr(user->modes,cmdlist[i].flags_needed))
1739                                                 {
1740                                                         cmdlist[i].handler_function(parameters,pcnt,user);
1741                                                 }
1742                                         }
1743                                 }
1744                         }
1745                 }
1746 }
1747
1748 void DoSplitEveryone()
1749 {
1750         bool go_again = true;
1751         while (go_again)
1752         {
1753                 go_again = false;
1754                 for (int i = 0; i < 32; i++)
1755                 {
1756                         if (me[i] != NULL)
1757                         {
1758                                 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
1759                                 {
1760                                         if (strcasecmp(j->GetServerName().c_str(),ServerName))
1761                                         {
1762                                                 j->routes.clear();
1763                                                 j->CloseConnection();
1764                                                 me[i]->connectors.erase(j);
1765                                                 go_again = true;
1766                                                 break;
1767                                         }
1768                                 }
1769                         }
1770                 }
1771         }
1772         log(DEBUG,"Removed server. Will remove clients...");
1773         // iterate through the userlist and remove all users on this server.
1774         // because we're dealing with a mesh, we dont have to deal with anything
1775         // "down-route" from this server (nice huh)
1776         go_again = true;
1777         char reason[MAXBUF];
1778         while (go_again)
1779         {
1780                 go_again = false;
1781                 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
1782                 {
1783                         if (strcasecmp(u->second->server,ServerName))
1784                         {
1785                                 snprintf(reason,MAXBUF,"%s %s",ServerName,u->second->server);
1786                                 kill_link(u->second,reason);
1787                                 go_again = true;
1788                                 break;
1789                         }
1790                 }
1791         }
1792         has_been_netsplit = true;
1793 }
1794
1795
1796
1797 void force_nickchange(userrec* user,const char* newnick)
1798 {
1799         char nick[MAXBUF];
1800         int MOD_RESULT = 0;
1801         
1802         strcpy(nick,"");
1803
1804         FOREACH_RESULT(OnUserPreNick(user,newnick));
1805         if (MOD_RESULT) {
1806                 statsCollisions++;
1807                 kill_link(user,"Nickname collision");
1808                 return;
1809         }
1810         if (matches_qline(newnick))
1811         {
1812                 statsCollisions++;
1813                 kill_link(user,"Nickname collision");
1814                 return;
1815         }
1816         
1817         if (user)
1818         {
1819                 if (newnick)
1820                 {
1821                         strncpy(nick,newnick,MAXBUF);
1822                 }
1823                 if (user->registered == 7)
1824                 {
1825                         char* pars[1];
1826                         pars[0] = nick;
1827                         handle_nick(pars,1,user);
1828                 }
1829         }
1830 }
1831                                 
1832
1833 int process_parameters(char **command_p,char *parameters)
1834 {
1835         int j = 0;
1836         int q = strlen(parameters);
1837         if (!q)
1838         {
1839                 /* no parameters, command_p invalid! */
1840                 return 0;
1841         }
1842         if (parameters[0] == ':')
1843         {
1844                 command_p[0] = parameters+1;
1845                 return 1;
1846         }
1847         if (q)
1848         {
1849                 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
1850                 {
1851                         /* only one parameter */
1852                         command_p[0] = parameters;
1853                         if (parameters[0] == ':')
1854                         {
1855                                 if (strchr(parameters,' ') != NULL)
1856                                 {
1857                                         command_p[0]++;
1858                                 }
1859                         }
1860                         return 1;
1861                 }
1862         }
1863         command_p[j++] = parameters;
1864         for (int i = 0; i <= q; i++)
1865         {
1866                 if (parameters[i] == ' ')
1867                 {
1868                         command_p[j++] = parameters+i+1;
1869                         parameters[i] = '\0';
1870                         if (command_p[j-1][0] == ':')
1871                         {
1872                                 *command_p[j-1]++; /* remove dodgy ":" */
1873                                 break;
1874                                 /* parameter like this marks end of the sequence */
1875                         }
1876                 }
1877         }
1878         return j; /* returns total number of items in the list */
1879 }
1880
1881 void process_command(userrec *user, char* cmd)
1882 {
1883         char *parameters;
1884         char *command;
1885         char *command_p[127];
1886         char p[MAXBUF], temp[MAXBUF];
1887         int j, items, cmd_found;
1888
1889         for (int i = 0; i < 127; i++)
1890                 command_p[i] = NULL;
1891
1892         if (!user)
1893         {
1894                 return;
1895         }
1896         if (!cmd)
1897         {
1898                 return;
1899         }
1900         if (!cmd[0])
1901         {
1902                 return;
1903         }
1904         
1905         int total_params = 0;
1906         if (strlen(cmd)>2)
1907         {
1908                 for (unsigned int q = 0; q < strlen(cmd)-1; q++)
1909                 {
1910                         if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
1911                         {
1912                                 total_params++;
1913                                 // found a 'trailing', we dont count them after this.
1914                                 break;
1915                         }
1916                         if (cmd[q] == ' ')
1917                                 total_params++;
1918                 }
1919         }
1920
1921         // another phidjit bug...
1922         if (total_params > 126)
1923         {
1924                 *(strchr(cmd,' ')) = '\0';
1925                 WriteServ(user->fd,"421 %s %s :Too many parameters given",user->nick,cmd);
1926                 return;
1927         }
1928
1929         strlcpy(temp,cmd,MAXBUF);
1930         
1931         std::string tmp = cmd;
1932         for (int i = 0; i <= MODCOUNT; i++)
1933         {
1934                 std::string oldtmp = tmp;
1935                 modules[i]->OnServerRaw(tmp,true,user);
1936                 if (oldtmp != tmp)
1937                 {
1938                         log(DEBUG,"A Module changed the input string!");
1939                         log(DEBUG,"New string: %s",tmp.c_str());
1940                         log(DEBUG,"Old string: %s",oldtmp.c_str());
1941                         break;
1942                 }
1943         }
1944         strlcpy(cmd,tmp.c_str(),MAXBUF);
1945         strlcpy(temp,cmd,MAXBUF);
1946
1947         if (!strchr(cmd,' '))
1948         {
1949                 /* no parameters, lets skip the formalities and not chop up
1950                  * the string */
1951                 log(DEBUG,"About to preprocess command with no params");
1952                 items = 0;
1953                 command_p[0] = NULL;
1954                 parameters = NULL;
1955                 for (unsigned int i = 0; i <= strlen(cmd); i++)
1956                 {
1957                         cmd[i] = toupper(cmd[i]);
1958                 }
1959                 command = cmd;
1960         }
1961         else
1962         {
1963                 strcpy(cmd,"");
1964                 j = 0;
1965                 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
1966                 for (unsigned int i = 0; i < strlen(temp); i++)
1967                 {
1968                         if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
1969                         {
1970                                 cmd[j++] = temp[i];
1971                                 cmd[j] = 0;
1972                         }
1973                 }
1974                 /* split the full string into a command plus parameters */
1975                 parameters = p;
1976                 strcpy(p," ");
1977                 command = cmd;
1978                 if (strchr(cmd,' '))
1979                 {
1980                         for (unsigned int i = 0; i <= strlen(cmd); i++)
1981                         {
1982                                 /* capitalise the command ONLY, leave params intact */
1983                                 cmd[i] = toupper(cmd[i]);
1984                                 /* are we nearly there yet?! :P */
1985                                 if (cmd[i] == ' ')
1986                                 {
1987                                         command = cmd;
1988                                         parameters = cmd+i+1;
1989                                         cmd[i] = '\0';
1990                                         break;
1991                                 }
1992                         }
1993                 }
1994                 else
1995                 {
1996                         for (unsigned int i = 0; i <= strlen(cmd); i++)
1997                         {
1998                                 cmd[i] = toupper(cmd[i]);
1999                         }
2000                 }
2001
2002         }
2003         cmd_found = 0;
2004         
2005         if (strlen(command)>MAXCOMMAND)
2006         {
2007                 WriteServ(user->fd,"421 %s %s :Command too long",user->nick,command);
2008                 return;
2009         }
2010         
2011         for (unsigned int x = 0; x < strlen(command); x++)
2012         {
2013                 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
2014                 {
2015                         if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
2016                         {
2017                                 if (strchr("@!\"$%^&*(){}[]_=+;:'#~,<>/?\\|`",command[x]))
2018                                 {
2019                                         statsUnknown++;
2020                                         WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
2021                                         return;
2022                                 }
2023                         }
2024                 }
2025         }
2026
2027         for (unsigned int i = 0; i != cmdlist.size(); i++)
2028         {
2029                 if (cmdlist[i].command[0])
2030                 {
2031                         if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
2032                         {
2033                                 if (parameters)
2034                                 {
2035                                         if (parameters[0])
2036                                         {
2037                                                 items = process_parameters(command_p,parameters);
2038                                         }
2039                                         else
2040                                         {
2041                                                 items = 0;
2042                                                 command_p[0] = NULL;
2043                                         }
2044                                 }
2045                                 else
2046                                 {
2047                                         items = 0;
2048                                         command_p[0] = NULL;
2049                                 }
2050                                 
2051                                 if (user)
2052                                 {
2053                                         /* activity resets the ping pending timer */
2054                                         user->nping = TIME + user->pingmax;
2055                                         if ((items) < cmdlist[i].min_params)
2056                                         {
2057                                                 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
2058                                                 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
2059                                                 return;
2060                                         }
2061                                         if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
2062                                         {
2063                                                 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
2064                                                 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
2065                                                 cmd_found = 1;
2066                                                 return;
2067                                         }
2068                                         if ((cmdlist[i].flags_needed) && (!user->HasPermission(command)))
2069                                         {
2070                                                 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
2071                                                 WriteServ(user->fd,"481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command);
2072                                                 cmd_found = 1;
2073                                                 return;
2074                                         }
2075                                         /* if the command isnt USER, PASS, or NICK, and nick is empty,
2076                                          * deny command! */
2077                                         if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
2078                                         {
2079                                                 if ((!isnick(user->nick)) || (user->registered != 7))
2080                                                 {
2081                                                         log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
2082                                                         WriteServ(user->fd,"451 %s :You have not registered",command);
2083                                                         return;
2084                                                 }
2085                                         }
2086                                         if ((user->registered == 7) && (!strchr(user->modes,'o')))
2087                                         {
2088                                                 std::stringstream dcmds(DisabledCommands);
2089                                                 while (!dcmds.eof())
2090                                                 {
2091                                                         std::string thiscmd;
2092                                                         dcmds >> thiscmd;
2093                                                         if (!strcasecmp(thiscmd.c_str(),command))
2094                                                         {
2095                                                                 // command is disabled!
2096                                                                 WriteServ(user->fd,"421 %s %s :This command has been disabled.",user->nick,command);
2097                                                                 return;
2098                                                         }
2099                                                 }
2100                                         }
2101                                         if ((user->registered == 7) || (!strncmp(command,"USER",4)) || (!strncmp(command,"NICK",4)) || (!strncmp(command,"PASS",4)))
2102                                         {
2103                                                 if (cmdlist[i].handler_function)
2104                                                 {
2105                                                         
2106                                                         /* ikky /stats counters */
2107                                                         if (temp)
2108                                                         {
2109                                                                 cmdlist[i].use_count++;
2110                                                                 cmdlist[i].total_bytes+=strlen(temp);
2111                                                         }
2112
2113                                                         int MOD_RESULT = 0;
2114                                                         FOREACH_RESULT(OnPreCommand(command,command_p,items,user));
2115                                                         if (MOD_RESULT == 1) {
2116                                                                 return;
2117                                                         }
2118
2119                                                         /* WARNING: nothing may come after the
2120                                                          * command handler call, as the handler
2121                                                          * may free the user structure! */
2122
2123                                                         cmdlist[i].handler_function(command_p,items,user);
2124                                                 }
2125                                                 return;
2126                                         }
2127                                         else
2128                                         {
2129                                                 WriteServ(user->fd,"451 %s :You have not registered",command);
2130                                                 return;
2131                                         }
2132                                 }
2133                                 cmd_found = 1;
2134                         }
2135                 }
2136         }
2137         if ((!cmd_found) && (user))
2138         {
2139                 statsUnknown++;
2140                 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
2141         }
2142 }
2143
2144 bool removecommands(const char* source)
2145 {
2146         bool go_again = true;
2147         while (go_again)
2148         {
2149                 go_again = false;
2150                 for (std::deque<command_t>::iterator i = cmdlist.begin(); i != cmdlist.end(); i++)
2151                 {
2152                         if (!strcmp(i->source,source))
2153                         {
2154                                 log(DEBUG,"removecommands(%s) Removing dependent command: %s",i->source,i->command);
2155                                 cmdlist.erase(i);
2156                                 go_again = true;
2157                                 break;
2158                         }
2159                 }
2160         }
2161         return true;
2162 }
2163
2164
2165 void process_buffer(const char* cmdbuf,userrec *user)
2166 {
2167         if (!user)
2168         {
2169                 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2170                 return;
2171         }
2172         char cmd[MAXBUF];
2173         if (!cmdbuf)
2174         {
2175                 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2176                 return;
2177         }
2178         if (!cmdbuf[0])
2179         {
2180                 return;
2181         }
2182         while (*cmdbuf == ' ') cmdbuf++; // strip leading spaces
2183
2184         strlcpy(cmd,cmdbuf,MAXBUF);
2185         if (!cmd[0])
2186         {
2187                 return;
2188         }
2189         int sl = strlen(cmd)-1;
2190         if ((cmd[sl] == 13) || (cmd[sl] == 10))
2191         {
2192                 cmd[sl] = '\0';
2193         }
2194         sl = strlen(cmd)-1;
2195         if ((cmd[sl] == 13) || (cmd[sl] == 10))
2196         {
2197                 cmd[sl] = '\0';
2198         }
2199         sl = strlen(cmd)-1;
2200         while (cmd[sl] == ' ') // strip trailing spaces
2201         {
2202                 cmd[sl] = '\0';
2203                 sl = strlen(cmd)-1;
2204         }
2205
2206         if (!cmd[0])
2207         {
2208                 return;
2209         }
2210         log(DEBUG,"CMDIN: %s %s",user->nick,cmd);
2211         tidystring(cmd);
2212         if ((user) && (cmd))
2213         {
2214                 process_command(user,cmd);
2215         }
2216 }
2217
2218 void DoSync(serverrec* serv, char* tcp_host)
2219 {
2220         char data[MAXBUF];
2221         log(DEBUG,"Sending sync");
2222         // send start of sync marker: Y <timestamp>
2223         // at this point the ircd receiving it starts broadcasting this netburst to all ircds
2224         // except the ones its receiving it from.
2225         snprintf(data,MAXBUF,"%s Y %lu",CreateSum().c_str(),(unsigned long)TIME);
2226         serv->SendPacket(data,tcp_host);
2227         // send users and channels
2228
2229         NetSendMyRoutingTable();
2230
2231         // send all routing table and uline voodoo. The ordering of these commands is IMPORTANT!
2232         for (int j = 0; j < 32; j++)
2233         {
2234                 if (me[j] != NULL)
2235                 {
2236                         for (unsigned int k = 0; k < me[j]->connectors.size(); k++)
2237                         {
2238                                 if (is_uline(me[j]->connectors[k].GetServerName().c_str()))
2239                                 {
2240                                         snprintf(data,MAXBUF,"%s H %s",CreateSum().c_str(),me[j]->connectors[k].GetServerName().c_str());
2241                                         serv->SendPacket(data,tcp_host);
2242                                 }
2243                         }
2244                 }
2245         }
2246
2247         // send our version for the remote side to cache
2248         snprintf(data,MAXBUF,"%s v %s %s",CreateSum().c_str(),ServerName,GetVersionString().c_str());
2249         serv->SendPacket(data,tcp_host);
2250
2251         // sync the users and channels, give the modules a look-in.
2252         for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
2253         {
2254                 snprintf(data,MAXBUF,"%s N %lu %s %s %s %s +%s %s %s :%s",CreateSum().c_str(),(unsigned long)u->second->age,u->second->nick,u->second->host,u->second->dhost,u->second->ident,u->second->modes,u->second->ip,u->second->server,u->second->fullname);
2255                 serv->SendPacket(data,tcp_host);
2256                 if (strchr(u->second->modes,'o'))
2257                 {
2258                         snprintf(data,MAXBUF,"%s | %s %s",CreateSum().c_str(),u->second->nick,u->second->oper);
2259                         serv->SendPacket(data,tcp_host);
2260                 }
2261                 for (int i = 0; i <= MODCOUNT; i++)
2262                 {
2263                         string_list l = modules[i]->OnUserSync(u->second);
2264                         for (unsigned int j = 0; j < l.size(); j++)
2265                         {
2266                                 snprintf(data,MAXBUF,"%s %s",CreateSum().c_str(),l[j].c_str());
2267                                 serv->SendPacket(data,tcp_host);
2268                         }
2269                 }
2270                 char* chl = chlist(u->second,u->second);
2271                 if (strcmp(chl,""))
2272                 {
2273                         snprintf(data,MAXBUF,"%s J %s %s",CreateSum().c_str(),u->second->nick,chl);
2274                         serv->SendPacket(data,tcp_host);
2275                 }
2276         }
2277         // send channel modes, topics etc...
2278         for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
2279         {
2280                 snprintf(data,MAXBUF,"M %s +%s",c->second->name,chanmodes(c->second));
2281                 serv->SendPacket(data,tcp_host);
2282                 for (int i = 0; i <= MODCOUNT; i++)
2283                 {
2284                         string_list l = modules[i]->OnChannelSync(c->second);
2285                         for (unsigned int j = 0; j < l.size(); j++)
2286                         {
2287                                 snprintf(data,MAXBUF,"%s %s",CreateSum().c_str(),l[j].c_str());
2288                                 serv->SendPacket(data,tcp_host);
2289                         }
2290                 }
2291                 if (c->second->topic[0])
2292                 {
2293                         snprintf(data,MAXBUF,"%s T %lu %s %s :%s",CreateSum().c_str(),(unsigned long)c->second->topicset,c->second->setby,c->second->name,c->second->topic);
2294                         serv->SendPacket(data,tcp_host);
2295                 }
2296                 // send current banlist
2297                 
2298                 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
2299                 {
2300                         snprintf(data,MAXBUF,"%s M %s +b %s",CreateSum().c_str(),c->second->name,b->data);
2301                         serv->SendPacket(data,tcp_host);
2302                 }
2303         }
2304         // sync global zlines, glines, etc
2305         sync_xlines(serv,tcp_host);
2306
2307         snprintf(data,MAXBUF,"%s F %lu",CreateSum().c_str(),(unsigned long)TIME);
2308         serv->SendPacket(data,tcp_host);
2309         log(DEBUG,"Sent sync");
2310         // ircd sends its serverlist after the end of sync here
2311 }
2312
2313
2314 void NetSendMyRoutingTable()
2315 {
2316         // send out a line saying what is reachable to us.
2317         // E.g. if A is linked to B C and D, send out:
2318         // $ A B C D
2319         // if its only linked to B and D send out:
2320         // $ A B D
2321         // if it has no links, dont even send out the line at all.
2322         char buffer[MAXBUF];
2323         snprintf(buffer,MAXBUF,"$ %s",ServerName);
2324         bool sendit = false;
2325         for (int i = 0; i < 32; i++)
2326         {
2327                 if (me[i] != NULL)
2328                 {
2329                         for (unsigned int j = 0; j < me[i]->connectors.size(); j++)
2330                         {
2331                                 if ((me[i]->connectors[j].GetState() != STATE_DISCONNECTED) || (is_uline(me[i]->connectors[j].GetServerName().c_str())))
2332                                 {
2333                                         strlcat(buffer," ",MAXBUF);
2334                                         strlcat(buffer,me[i]->connectors[j].GetServerName().c_str(),MAXBUF);
2335                                         sendit = true;
2336                                 }
2337                         }
2338                 }
2339         }
2340         if (sendit)
2341                 NetSendToAll(buffer);
2342 }
2343
2344
2345 void DoSplit(const char* params)
2346 {
2347         bool go_again = true;
2348         while (go_again)
2349         {
2350                 go_again = false;
2351                 for (int i = 0; i < 32; i++)
2352                 {
2353                         if (me[i] != NULL)
2354                         {
2355                                 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2356                                 {
2357                                         if (!strcasecmp(j->GetServerName().c_str(),params))
2358                                         {
2359                                                 j->routes.clear();
2360                                                 j->CloseConnection();
2361                                                 me[i]->connectors.erase(j);
2362                                                 go_again = true;
2363                                                 break;
2364                                         }
2365                                 }
2366                         }
2367                 }
2368         }
2369         log(DEBUG,"Removed server. Will remove clients...");
2370         // iterate through the userlist and remove all users on this server.
2371         // because we're dealing with a mesh, we dont have to deal with anything
2372         // "down-route" from this server (nice huh)
2373         go_again = true;
2374         char reason[MAXBUF];
2375         snprintf(reason,MAXBUF,"%s %s",ServerName,params);
2376         while (go_again)
2377         {
2378                 go_again = false;
2379                 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
2380                 {
2381                         if (!strcasecmp(u->second->server,params))
2382                         {
2383                                 kill_link(u->second,reason);
2384                                 go_again = true;
2385                                 break;
2386                         }
2387                 }
2388         }
2389         has_been_netsplit = true;
2390 }
2391
2392 // removes a server. Will NOT remove its users!
2393
2394 void RemoveServer(const char* name)
2395 {
2396         bool go_again = true;
2397         while (go_again)
2398         {
2399                 go_again = false;
2400                 for (int i = 0; i < 32; i++)
2401                 {
2402                         if (me[i] != NULL)
2403                         {
2404                                 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2405                                 {
2406                                         if (!strcasecmp(j->GetServerName().c_str(),name))
2407                                         {
2408                                                 j->routes.clear();
2409                                                 j->CloseConnection();
2410                                                 me[i]->connectors.erase(j);
2411                                                 go_again = true;
2412                                                 break;
2413                                         }
2414                                 }
2415                         }
2416                 }
2417         }
2418 }
2419
2420
2421 char MODERR[MAXBUF];
2422
2423 char* ModuleError()
2424 {
2425         return MODERR;
2426 }
2427
2428 void erase_factory(int j)
2429 {
2430         int v = 0;
2431         for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
2432         {
2433                 if (v == j)
2434                 {
2435                         factory.erase(t);
2436                         factory.push_back(NULL);
2437                         return;
2438                 }
2439                 v++;
2440         }
2441 }
2442
2443 void erase_module(int j)
2444 {
2445         int v1 = 0;
2446         for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
2447         {
2448                 if (v1 == j)
2449                 {
2450                         delete *m;
2451                         modules.erase(m);
2452                         modules.push_back(NULL);
2453                         break;
2454                 }
2455                 v1++;
2456         }
2457         int v2 = 0;
2458         for (std::vector<std::string>::iterator v = module_names.begin(); v != module_names.end(); v++)
2459         {
2460                 if (v2 == j)
2461                 {
2462                        module_names.erase(v);
2463                        break;
2464                 }
2465                 v2++;
2466         }
2467
2468 }
2469
2470 bool UnloadModule(const char* filename)
2471 {
2472         std::string filename_str = filename;
2473         for (unsigned int j = 0; j != module_names.size(); j++)
2474         {
2475                 if (module_names[j] == filename_str)
2476                 {
2477                         if (modules[j]->GetVersion().Flags & VF_STATIC)
2478                         {
2479                                 log(DEFAULT,"Failed to unload STATIC module %s",filename);
2480                                 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
2481                                 return false;
2482                         }
2483                         // found the module
2484                         log(DEBUG,"Deleting module...");
2485                         erase_module(j);
2486                         log(DEBUG,"Erasing module entry...");
2487                         erase_factory(j);
2488                         log(DEBUG,"Removing dependent commands...");
2489                         removecommands(filename);
2490                         log(DEFAULT,"Module %s unloaded",filename);
2491                         MODCOUNT--;
2492                         return true;
2493                 }
2494         }
2495         log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
2496         snprintf(MODERR,MAXBUF,"Module not loaded");
2497         return false;
2498 }
2499
2500 bool LoadModule(const char* filename)
2501 {
2502         char modfile[MAXBUF];
2503 #ifdef STATIC_LINK
2504         snprintf(modfile,MAXBUF,"%s",filename);
2505 #else
2506         snprintf(modfile,MAXBUF,"%s/%s",ModPath,filename);
2507 #endif
2508         std::string filename_str = filename;
2509 #ifndef STATIC_LINK
2510         if (!DirValid(modfile))
2511         {
2512                 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
2513                 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
2514                 return false;
2515         }
2516 #endif
2517         log(DEBUG,"Loading module: %s",modfile);
2518 #ifndef STATIC_LINK
2519         if (FileExists(modfile))
2520         {
2521 #endif
2522                 for (unsigned int j = 0; j < module_names.size(); j++)
2523                 {
2524                         if (module_names[j] == filename_str)
2525                         {
2526                                 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
2527                                 snprintf(MODERR,MAXBUF,"Module already loaded");
2528                                 return false;
2529                         }
2530                 }
2531                 ircd_module* a = new ircd_module(modfile);
2532                 factory[MODCOUNT+1] = a;
2533                 if (factory[MODCOUNT+1]->LastError())
2534                 {
2535                         log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
2536                         snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
2537                         MODCOUNT--;
2538                         return false;
2539                 }
2540                 if (factory[MODCOUNT+1]->factory)
2541                 {
2542                         Module* m = factory[MODCOUNT+1]->factory->CreateModule();
2543                         modules[MODCOUNT+1] = m;
2544                         /* save the module and the module's classfactory, if
2545                          * this isnt done, random crashes can occur :/ */
2546                         module_names.push_back(filename);
2547                 }
2548                 else
2549                 {
2550                         log(DEFAULT,"Unable to load %s",modfile);
2551                         snprintf(MODERR,MAXBUF,"Factory function failed!");
2552                         return false;
2553                 }
2554 #ifndef STATIC_LINK
2555         }
2556         else
2557         {
2558                 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
2559                 snprintf(MODERR,MAXBUF,"Module file could not be found");
2560                 return false;
2561         }
2562 #endif
2563         MODCOUNT++;
2564         return true;
2565 }
2566
2567
2568 bool GotServer(std::string name)
2569 {
2570         for (int j = 0; j < 32; j++)
2571         {
2572                 if (me[j] != NULL)
2573                 {
2574                         for (unsigned int k = 0; k < me[j]->connectors.size(); k++)
2575                         {
2576                                 if (name == me[j]->connectors[k].GetServerName())
2577                                 {
2578                                         return true;
2579                                 }
2580                         }
2581                 }
2582         }
2583         return false;
2584 }
2585
2586
2587 int InspIRCd(char** argv, int argc)
2588 {
2589         struct sockaddr_in client,server;
2590         char addrs[MAXBUF][255];
2591         int incomingSockfd, result = TRUE;
2592         socklen_t length;
2593         int count = 0;
2594 #ifdef USE_SELECT
2595         int selectResult = 0, selectResult2 = 0;
2596         fd_set selectFds;
2597 #endif
2598         char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
2599         timeval tv;
2600
2601         std::string logpath = GetFullProgDir(argv,argc) + "/ircd.log";
2602         log_file = fopen(logpath.c_str(),"a+");
2603         if (!log_file)
2604         {
2605                 printf("ERROR: Could not write to logfile %s, bailing!\n\n",logpath.c_str());
2606                 Exit(ERROR);
2607         }
2608
2609 #ifdef IS_CYGWIN
2610         printf("Logging to ircd.log...\n");
2611 #else
2612         printf("Logging to %s...\n",logpath.c_str());
2613 #endif
2614
2615         log(DEFAULT,"$Id$");
2616         if (geteuid() == 0)
2617         {
2618                 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
2619                 Exit(ERROR);
2620                 log(DEFAULT,"InspIRCd: startup: not starting with UID 0!");
2621         }
2622         SetupCommandTable();
2623         log(DEBUG,"InspIRCd: startup: default command table set up");
2624         
2625         ReadConfig(true,NULL);
2626         if (DieValue[0])
2627         { 
2628                 printf("WARNING: %s\n\n",DieValue);
2629                 log(DEFAULT,"Ut-Oh, somebody didn't read their config file: '%s'",DieValue);
2630                 exit(0); 
2631         }  
2632         log(DEBUG,"InspIRCd: startup: read config");
2633
2634         AddServerName(ServerName);
2635
2636         int clientportcount = 0, serverportcount = 0;
2637
2638         for (count = 0; count < ConfValueEnum("bind",&config_f); count++)
2639         {
2640                 ConfValue("bind","port",count,configToken,&config_f);
2641                 ConfValue("bind","address",count,Addr,&config_f);
2642                 ConfValue("bind","type",count,Type,&config_f);
2643                 if (!strcmp(Type,"servers"))
2644                 {
2645                         char Default[MAXBUF];
2646                         strcpy(Default,"no");
2647                         ConfValue("bind","default",count,Default,&config_f);
2648                         if (strchr(Default,'y'))
2649                         {
2650                                 defaultRoute = serverportcount;
2651                                 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
2652                         }
2653                         me[serverportcount] = new serverrec(ServerName,100L,false);
2654                         if (!me[serverportcount]->CreateListener(Addr,atoi(configToken)))
2655                         {
2656                                 log(DEFAULT,"Warning: Failed to bind port %lu",(unsigned long)atoi(configToken));
2657                                 printf("Warning: Failed to bind port %lu\n",(unsigned long)atoi(configToken));
2658                         }
2659                         else
2660                         {
2661                                 serverportcount++;
2662                         }
2663                 }
2664                 else
2665                 {
2666                         ports[clientportcount] = atoi(configToken);
2667                         strlcpy(addrs[clientportcount],Addr,256);
2668                         clientportcount++;
2669                 }
2670                 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
2671         }
2672         portCount = clientportcount;
2673         SERVERportCount = serverportcount;
2674           
2675         log(DEBUG,"InspIRCd: startup: read %lu total client ports and %lu total server ports",(unsigned long)portCount,(unsigned long)SERVERportCount);
2676         log(DEBUG,"InspIRCd: startup: InspIRCd is now starting!");
2677         
2678         printf("\n");
2679         
2680         /* BugFix By Craig! :p */
2681         MODCOUNT = -1;
2682         for (count = 0; count < ConfValueEnum("module",&config_f); count++)
2683         {
2684                 ConfValue("module","name",count,configToken,&config_f);
2685                 printf("Loading module... \033[1;32m%s\033[0m\n",configToken);
2686                 if (!LoadModule(configToken))
2687                 {
2688                         log(DEFAULT,"Exiting due to a module loader error.");
2689                         printf("\nThere was an error loading a module: %s\n\nYou might want to do './inspircd start' instead of 'bin/inspircd'\n\n",ModuleError());
2690                         Exit(0);
2691                 }
2692         }
2693         log(DEFAULT,"Total loaded modules: %lu",(unsigned long)MODCOUNT+1);
2694         
2695         startup_time = time(NULL);
2696           
2697         char PID[MAXBUF];
2698         ConfValue("pid","file",0,PID,&config_f);
2699         // write once here, to try it out and make sure its ok
2700         WritePID(PID);
2701           
2702         /* setup select call */
2703 #ifdef USE_SELECT
2704         FD_ZERO(&selectFds);
2705 #endif
2706         log(DEBUG,"InspIRCd: startup: zero selects");
2707         log(VERBOSE,"InspIRCd: startup: portCount = %lu", (unsigned long)portCount);
2708         
2709         for (count = 0; count < portCount; count++)
2710         {
2711                 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
2712                 {
2713                         log(DEBUG,"InspIRCd: startup: bad fd %lu",(unsigned long)openSockfd[boundPortCount]);
2714                         return(ERROR);
2715                 }
2716                 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
2717                 {
2718                         log(DEFAULT,"InspIRCd: startup: failed to bind port %lu",(unsigned long)ports[count]);
2719                 }
2720                 else    /* well we at least bound to one socket so we'll continue */
2721                 {
2722                         boundPortCount++;
2723                 }
2724         }
2725         
2726         log(DEBUG,"InspIRCd: startup: total bound ports %lu",(unsigned long)boundPortCount);
2727           
2728         /* if we didn't bind to anything then abort */
2729         if (boundPortCount == 0)
2730         {
2731                 log(DEFAULT,"InspIRCd: startup: no ports bound, bailing!");
2732                 printf("\nERROR: Was not able to bind any of %lu ports! Please check your configuration.\n\n", (unsigned long)portCount);
2733                 return (ERROR);
2734         }
2735         
2736
2737         printf("\nInspIRCd is now running!\n");
2738
2739         if (nofork)
2740         {
2741                 log(VERBOSE,"Not forking as -nofork was specified");
2742         }
2743         else
2744         {
2745                 if (DaemonSeed() == ERROR)
2746                 {
2747                         log(DEFAULT,"InspIRCd: startup: can't daemonise");
2748                         printf("ERROR: could not go into daemon mode. Shutting down.\n");
2749                         Exit(ERROR);
2750                 }
2751         }
2752
2753         // BUGFIX: We cannot initialize this before forking, as the kqueue data is not inherited by child processes!
2754 #ifdef USE_KQUEUE
2755         kq = kqueue();
2756         lkq = kqueue();
2757         skq = kqueue();
2758         if ((kq == -1) || (lkq == -1) || (skq == -1))
2759         {
2760                 log(DEFAULT,"main: kqueue() failed!");
2761                 printf("ERROR: could not initialise kqueue event system. Shutting down.\n");
2762                 Exit(ERROR);
2763         }
2764 #endif
2765
2766 #ifdef USE_EPOLL
2767         ep = epoll_create(MAXCLIENTS);
2768         lep = epoll_create(32);
2769         sep = epoll_create(128);
2770         if ((ep == -1) || (lep == -1) || (sep == -1))
2771         {
2772                 log(DEFAULT,"main: epoll_create() failed!");
2773                 printf("ERROR: could not initialise epoll event system. Shutting down.\n");
2774                 Exit(ERROR);
2775         }
2776 #endif
2777
2778 #ifdef USE_EPOLL
2779         log(DEFAULT,"epoll socket engine is enabled. Filling listen list. boundPortcount=%d",boundPortCount);
2780         for (count = 0; count < boundPortCount; count++)
2781         {
2782                 struct epoll_event ev;
2783                 log(DEBUG,"epoll: Add listening socket to events, ep=%d socket=%d",lep,openSockfd[count]);
2784                 ev.events = EPOLLIN | EPOLLET;
2785                 ev.data.fd = openSockfd[count];
2786                 int i = epoll_ctl(lep, EPOLL_CTL_ADD, openSockfd[count], &ev);
2787                 if (i < 0)
2788                 {
2789                         log(DEFAULT,"main: add listen ports, epoll_ctl failed!");
2790                         printf("ERROR: could not initialise listening sockets in epoll list. Shutting down.\n");
2791                         Exit(ERROR);
2792                 }
2793                 
2794         }
2795         for (int t = 0; t != SERVERportCount; t++)
2796         {
2797                 struct epoll_event ev;
2798                 log(DEBUG,"epoll: Add listening server socket to events, ep=%d socket=%d",sep,me[t]->fd);
2799                 ev.events = EPOLLIN | EPOLLET;
2800                 ev.data.fd = me[t]->fd;
2801                 int i = epoll_ctl(sep, EPOLL_CTL_ADD, me[t]->fd, &ev);
2802                 if (i == -1)
2803                 {
2804                         log(DEFAULT,"main: add server listen ports, epoll_ctl failed!");
2805                         printf("ERROR: could not initialise server listening sockets in epoll list. Shutting down.\n");
2806                         Exit(ERROR);
2807                 }
2808         }
2809 #else
2810 #ifdef USE_KQUEUE
2811         log(DEFAULT,"kqueue socket engine is enabled. Filling listen list.");
2812         for (count = 0; count < boundPortCount; count++)
2813         {
2814                 struct kevent ke;
2815                 log(DEBUG,"kqueue: Add listening socket to events, kq=%d socket=%d",lkq,openSockfd[count]);
2816                 EV_SET(&ke, openSockfd[count], EVFILT_READ, EV_ADD, 0, MaxConn, NULL);
2817                 int i = kevent(lkq, &ke, 1, 0, 0, NULL);
2818                 if (i == -1)
2819                 {
2820                         log(DEFAULT,"main: add listen ports to kqueue failed!");
2821                         printf("ERROR: could not initialise listening sockets in kqueue. Shutting down.\n");
2822                         Exit(ERROR);
2823                 }
2824         }
2825         for (int t = 0; t != SERVERportCount; t++)
2826         {
2827                 struct kevent ke;
2828                 if (me[t])
2829                 {
2830                         log(DEBUG,"kqueue: Add listening SERVER socket to events, kq=%d socket=%d",skq,me[t]->fd);
2831                         EV_SET(&ke, me[t]->fd, EVFILT_READ, EV_ADD, 0, MaxConn, NULL);
2832                         int i = kevent(skq, &ke, 1, 0, 0, NULL);
2833                         if (i == -1)
2834                         {
2835                                 log(DEFAULT,"main: add server listen ports to kqueue failed!");
2836                                 printf("ERROR: could not initialise listening server sockets in kqueue. Shutting down.\n");
2837                                 Exit(ERROR);
2838                         }
2839                 }
2840         }
2841
2842
2843 #else
2844         log(DEFAULT,"Using standard select socket engine.");
2845 #endif
2846 #endif
2847
2848         WritePID(PID);
2849
2850         length = sizeof (client);
2851         char tcp_msg[MAXBUF],tcp_host[MAXBUF],tcp_sum[MAXBUF];
2852
2853 #ifdef USE_KQUEUE
2854         struct kevent ke;
2855         struct kevent ke_list[33];
2856         struct timespec ts;
2857 #endif
2858 #ifdef USE_EPOLL
2859         struct epoll_event event[33];
2860 #endif
2861 #ifdef USE_SELECT
2862         fd_set serverfds;
2863         fd_set sfd;
2864 #endif
2865         timeval tvs;
2866         tvs.tv_usec = 10000L;
2867         tvs.tv_sec = 0;
2868         tv.tv_sec = 0;
2869         tv.tv_usec = 10000L;
2870         char data[65536];
2871         timeval tval;
2872         tval.tv_usec = 10000L;
2873         tval.tv_sec = 0;
2874         int total_in_this_set = 0;
2875         int i = 0, v = 0, j = 0, cycle_iter = 0;
2876         bool expire_run = false;
2877           
2878         /* main loop, this never returns */
2879         for (;;)
2880         {
2881 #ifdef _POSIX_PRIORITY_SCHEDULING
2882                 sched_yield();
2883 #endif
2884 #ifdef USE_SELECT
2885                 FD_ZERO(&sfd);
2886 #endif
2887                 // we only read time() once per iteration rather than tons of times!
2888                 OLDTIME = TIME;
2889                 TIME = time(NULL);
2890
2891                 dns_poll();
2892
2893                 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
2894                 // them in a list, then reap the list every second or so.
2895                 if (((TIME % 5) == 0) && (!expire_run))
2896                 {
2897                         for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
2898                         {
2899                                 char Link_ServerName[MAXBUF],Link_AConn[MAXBUF];
2900                                 ConfValue("link","name",i,Link_ServerName,&config_f);
2901                                 ConfValue("link","autoconnect",i,Link_AConn,&config_f);
2902                                 if ((Link_AConn[0]) && (!GotServer(Link_ServerName)))
2903                                 {
2904                                         autoconnects::iterator a = autoconns.find(std::string(Link_ServerName));
2905                                         if (a != autoconns.end())
2906                                         {
2907                                                 if (TIME > a->second)
2908                                                 {
2909                                                         ConnectServer(Link_ServerName,NULL);
2910                                                         a->second = TIME + atoi(Link_AConn);
2911                                                 }
2912                                         }
2913                                 }
2914                         }
2915
2916                         expire_lines();
2917                         FOREACH_MOD OnBackgroundTimer(TIME);
2918                         expire_run = true;
2919                         continue;
2920                 }
2921                 if ((TIME % 5) == 1)
2922                         expire_run = false;
2923                 
2924                 // fix by brain - this must be below any manipulation of the hashmap by modules
2925                 user_hash::iterator count2 = clientlist.begin();
2926
2927 #ifdef USE_EPOLL
2928                 i = epoll_wait(sep, event, 1, EP_DELAY);
2929                 if (i > 0)
2930                 {
2931                         log(DEBUG,"epoll: Listening server socket event, i=%d, event.data.fd=%d",i,event[0].data.fd);
2932                         for (int x = 0; x != SERVERportCount; x++)
2933                         {
2934                                 if ((me[x]) && ((unsigned)event[0].data.fd == (unsigned)me[x]->fd))
2935                                 {
2936 #endif
2937 #ifdef USE_KQUEUE
2938                 ts.tv_sec = 0;
2939                 ts.tv_nsec = 30000L;
2940                 i = kevent(skq, NULL, 0, &ke, 1, &ts);
2941                 if (i > 0)
2942                 {
2943                         log(DEBUG,"kqueue: Listening server socket event, i=%d, ke.ident=%d",i,ke.ident);
2944                         for (int x = 0; x != SERVERportCount; x++)
2945                         {
2946                                 if ((me[x]) && ((unsigned)ke.ident == (unsigned)me[x]->fd))
2947                                 {
2948
2949 #endif
2950 #ifdef USE_SELECT
2951                 FD_ZERO(&serverfds);
2952                 for (int x = 0; x != SERVERportCount; x++)
2953                 {
2954                         if (me[x])
2955                                 FD_SET(me[x]->fd, &serverfds);
2956                 }
2957                 tvs.tv_usec = 30000L;
2958                 tvs.tv_sec = 0;
2959                 int servresult = select(FD_SETSIZE, &serverfds, NULL, NULL, &tvs);
2960                 if (servresult > 0)
2961                 {
2962                         for (int x = 0; x != SERVERportCount; x++)
2963                         {
2964                                 if ((me[x]) && (FD_ISSET (me[x]->fd, &serverfds)))
2965                                 {
2966 #endif
2967                                         char remotehost[MAXBUF],resolved[MAXBUF];
2968                                         length = sizeof (client);
2969                                         incomingSockfd = accept (me[x]->fd, (sockaddr *) &client, &length);
2970                                         if (incomingSockfd != -1)
2971                                         {
2972                                                 strlcpy(remotehost,(char *)inet_ntoa(client.sin_addr),MAXBUF);
2973                                                 if(CleanAndResolve(resolved, remotehost) != TRUE)
2974                                                 {
2975                                                         strlcpy(resolved,remotehost,MAXBUF);
2976                                                 }
2977                                                 // add to this connections ircd_connector vector
2978                                                 // *FIX* - we need the LOCAL port not the remote port in &client!
2979                                                 me[x]->AddIncoming(incomingSockfd,resolved,me[x]->port);
2980                                         }
2981                                 }
2982                         }
2983                 }
2984      
2985                 std::deque<std::string> msgs;
2986                 std::deque<std::string> sums;
2987                 for (int x = 0; x < SERVERportCount; x++)
2988                 {
2989                         if (me[x])
2990                                 me[x]->FlushWriteBuffers();
2991                         sums.clear();
2992                         msgs.clear();
2993                         while ((me[x]) && (me[x]->RecvPacket(msgs, tcp_host, sums))) // returns 0 or more lines (can be multiple lines!)
2994                         {
2995                                 has_been_netsplit = false;
2996                                 for (unsigned int ctr = 0; ctr < msgs.size(); ctr++)
2997                                 {
2998                                         strlcpy(tcp_msg,msgs[ctr].c_str(),MAXBUF);
2999                                         strlcpy(tcp_sum,sums[ctr].c_str(),MAXBUF);
3000                                         log(DEBUG,"Processing: %s",tcp_msg);
3001                                         if (!tcp_msg[0])
3002                                         {
3003                                                 log(DEBUG,"Invalid string from %s [route%lu]",tcp_host,(unsigned long)x);
3004                                                 break;
3005                                         }
3006                                         // during a netburst, send all data to all other linked servers
3007                                         if ((((nb_start>0) && (tcp_msg[0] != 'Y') && (tcp_msg[0] != 'X') && (tcp_msg[0] != 'F'))) || (is_uline(tcp_host)))
3008                                         {
3009                                                 if (is_uline(tcp_host))
3010                                                 {
3011                                                         if ((tcp_msg[0] != 'Y') && (tcp_msg[0] != 'X') && (tcp_msg[0] != 'F'))
3012                                                         {
3013                                                                 NetSendToAllExcept_WithSum(tcp_host,tcp_msg,tcp_sum);
3014                                                         }
3015                                                 }
3016                                                 else
3017                                                         NetSendToAllExcept_WithSum(tcp_host,tcp_msg,tcp_sum);
3018                                         }
3019                                         std::string msg = tcp_msg;
3020                                         FOREACH_MOD OnPacketReceive(msg,tcp_host);
3021                                         strlcpy(tcp_msg,msg.c_str(),MAXBUF);
3022                                         if (me[x])
3023                                                 handle_link_packet(tcp_msg, tcp_host, me[x], tcp_sum);
3024                                         if (!me[x]->FindHost(tcp_host))
3025                                         {
3026                                                 log(DEBUG,"Connector gone, bailing!");
3027                                                 goto label;
3028                                         }
3029                                 }
3030                                 goto label;
3031                         }
3032                 }
3033         
3034         while (count2 != clientlist.end())
3035         {
3036 #ifdef USE_SELECT
3037                 FD_ZERO(&sfd);
3038 #endif
3039
3040                 total_in_this_set = 0;
3041
3042                 user_hash::iterator xcount = count2;
3043                 user_hash::iterator endingiter = count2;
3044
3045                 if (count2 == clientlist.end()) break;
3046
3047                 userrec* curr = NULL;
3048
3049                 if (count2->second)
3050                         curr = count2->second;
3051
3052                 if ((long)curr == -1)
3053                         goto label;
3054
3055                 if ((curr) && (curr->fd != 0))
3056                 {
3057 #ifdef _POSIX_PRIORITY_SCHEDULING
3058         sched_yield();
3059 #endif
3060                         // assemble up to 64 sockets into an fd_set
3061                         // to implement a pooling mechanism.
3062                         //
3063                         // This should be up to 64x faster than the
3064                         // old implementation.
3065 #ifdef USE_SELECT
3066                         while (total_in_this_set < 1024)
3067                         {
3068                                 if (count2 != clientlist.end())
3069                                 {
3070                                         curr = count2->second;
3071                                         if ((long)curr == -1)
3072                                                 goto label;
3073                                         int currfd = curr->fd;
3074                                         // we don't check the state of remote users.
3075                                         if ((currfd != -1) && (currfd != FD_MAGIC_NUMBER))
3076                                         {
3077                                                 curr->FlushWriteBuf();
3078                                                 if (curr->GetWriteError() != "")
3079                                                 {
3080                                                         log(DEBUG,"InspIRCd: write error: %s",curr->GetWriteError().c_str());
3081                                                         kill_link(curr,curr->GetWriteError().c_str());
3082                                                         goto label;
3083                                                 }
3084
3085                                                 FD_SET (curr->fd, &sfd);
3086
3087                                                 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
3088                                                 // their connection class.
3089                                                 if ((TIME > curr->timeout) && (curr->registered != 7)) 
3090                                                 {
3091                                                         log(DEBUG,"InspIRCd: registration timeout: %s",curr->nick);
3092                                                         kill_link(curr,"Registration timeout");
3093                                                         goto label;
3094                                                 }
3095                                                 if ((TIME > curr->signon) && (curr->registered == 3) && (AllModulesReportReady(curr)))
3096                                                 {
3097                                                         log(DEBUG,"signon exceed, registered=3, and modules ready, OK");
3098                                                         curr->dns_done = true;
3099                                                         statsDnsBad++;
3100                                                         FullConnectUser(curr);
3101                                                         if (fd_ref_table[currfd] != curr) // something changed, bail pronto
3102                                                                 goto label;                                                        
3103                                                 }
3104                                                 if ((curr->dns_done) && (curr->registered == 3) && (AllModulesReportReady(curr))) // both NICK and USER... and DNS
3105                                                 {
3106                                                         log(DEBUG,"dns done, registered=3, and modules ready, OK");
3107                                                         FullConnectUser(curr);
3108                                                         if (fd_ref_table[currfd] != curr) // something changed, bail pronto
3109                                                                 goto label;
3110                                                 }
3111                                                 if ((TIME > curr->nping) && (isnick(curr->nick)) && (curr->registered == 7))
3112                                                 {
3113                                                         if ((!curr->lastping) && (curr->registered == 7))
3114                                                         {
3115                                                                 log(DEBUG,"InspIRCd: ping timeout: %s",curr->nick);
3116                                                                 kill_link(curr,"Ping timeout");
3117                                                                 goto label;
3118                                                         }
3119                                                         Write(curr->fd,"PING :%s",ServerName);
3120                                                         log(DEBUG,"InspIRCd: pinging: %s",curr->nick);
3121                                                         curr->lastping = 0;
3122                                                         curr->nping = TIME+curr->pingmax;       // was hard coded to 120
3123                                                 }
3124                                         }
3125                                         count2++;
3126                                         total_in_this_set++;
3127                                 }
3128                                 else break;
3129                         }
3130                         endingiter = count2;
3131                         count2 = xcount; // roll back to where we were
3132 #else
3133                         // KQUEUE and EPOLL: We don't go through a loop to fill the fd_set so instead we must manually do this loop every now and again.
3134                         // TODO: We dont need to do all this EVERY loop iteration, tone down the visits to this if we're using kqueue.
3135                         cycle_iter++;
3136                         if (cycle_iter > 20) while (count2 != clientlist.end())
3137                         {
3138                                 cycle_iter = 0;
3139                                 if (count2 != clientlist.end())
3140                                 {
3141                                         curr = count2->second;
3142                                         if ((long)curr == -1)
3143                                                 goto label;
3144                                         int currfd = curr->fd;
3145                                         // we don't check the state of remote users.
3146                                         if ((currfd != -1) && (currfd != FD_MAGIC_NUMBER))
3147                                         {
3148
3149                                                 curr->FlushWriteBuf();
3150                                                 if (curr->GetWriteError() != "")
3151                                                 {
3152                                                         log(DEBUG,"InspIRCd: write error: %s",curr->GetWriteError().c_str());
3153                                                         kill_link(curr,curr->GetWriteError().c_str());
3154                                                         goto label;
3155                                                 }
3156
3157                                                 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
3158                                                 // their connection class.
3159                                                 if (((unsigned)TIME > (unsigned)curr->timeout) && (curr->registered != 7))
3160                                                 {
3161                                                         log(DEBUG,"InspIRCd: registration timeout: %s",curr->nick);
3162                                                         kill_link(curr,"Registration timeout");
3163                                                         goto label;
3164
3165                                                 }
3166                                                 if ((TIME > curr->signon) && (curr->registered == 3) && (AllModulesReportReady(curr)))
3167                                                 {
3168                                                         log(DEBUG,"signon exceed, registered=3, and modules ready, OK: %d %d",TIME,curr->signon);
3169                                                         curr->dns_done = true;
3170                                                         statsDnsBad++;
3171                                                         FullConnectUser(curr);
3172                                                         if (fd_ref_table[currfd] != curr) // something changed, bail pronto
3173                                                                 goto label;
3174                                                 }
3175                                                 if ((curr->dns_done) && (curr->registered == 3) && (AllModulesReportReady(curr)))
3176                                                 {
3177                                                         log(DEBUG,"dns done, registered=3, and modules ready, OK");
3178                                                         FullConnectUser(curr);
3179                                                         if (fd_ref_table[currfd] != curr) // something changed, bail pronto
3180                                                                 goto label;
3181                                                 }
3182                                                 if ((TIME > curr->nping) && (isnick(curr->nick)) && (curr->registered == 7))
3183                                                 {
3184                                                         if ((!curr->lastping) && (curr->registered == 7))
3185                                                         {
3186                                                                 log(DEBUG,"InspIRCd: ping timeout: %s",curr->nick);
3187                                                                 kill_link(curr,"Ping timeout");
3188                                                                 goto label;
3189                                                         }
3190                                                         Write(curr->fd,"PING :%s",ServerName);
3191                                                         log(DEBUG,"InspIRCd: pinging: %s",curr->nick);
3192                                                         curr->lastping = 0;
3193                                                         curr->nping = TIME+curr->pingmax;       // was hard coded to 120
3194                                                 }
3195                                         }
3196                                 }
3197                                 else break;
3198                                 count2++;
3199                         }
3200                         // increment the counter right to the end of the list, as kqueue processes everything in one go
3201 #endif
3202         
3203                         v = 0;
3204 #ifdef USE_EPOLL
3205                         int i = epoll_wait(ep, event, 1, 5);
3206                         if (i > 0)
3207                         {
3208                                 log(DEBUG,"epoll_wait call: ep=%d, i=%d",ep,i);
3209                                 // EPOLL: we asked epoll_wait for ONE fd which is ready. Do something.
3210                                 userrec* cu = fd_ref_table[event[0].data.fd];
3211 #endif
3212 #ifdef USE_KQUEUE
3213                         ts.tv_sec = 0;
3214                         ts.tv_nsec = 1000L;
3215                         // for now, we only read 1 event. We could read soooo many more :)
3216                         int i = kevent(kq, NULL, 0, &ke, 1, &ts);
3217                         if (i > 0)
3218                         {
3219                                 log(DEBUG,"kevent call: kq=%d, i=%d",kq,i);
3220                                 // KQUEUE: kevent gives us ONE fd which is ready to have something done to it. Do something to it.
3221                                 userrec* cu = fd_ref_table[ke.ident];
3222 #endif
3223 #ifdef USE_SELECT
3224                         tval.tv_sec = 0;
3225                         tval.tv_usec = 1000L;
3226                         selectResult2 = select(FD_SETSIZE, &sfd, NULL, NULL, &tval);
3227                         // now loop through all of the items in this pool if any are waiting
3228                         if ((selectResult2 > 0) && (xcount != clientlist.end()))
3229                         for (user_hash::iterator count2a = xcount; count2a != endingiter; count2a++)
3230                         {
3231                                 // SELECT: we have to iterate...
3232                                 if (count2a == clientlist.end())
3233                                         break;
3234                                 userrec* cu = count2a->second;
3235 #endif
3236
3237 #ifdef _POSIX_PRIORITY_SCHEDULING
3238                                 sched_yield();
3239 #endif
3240                                 result = EAGAIN;
3241 #ifdef USE_EPOLL
3242                                 // EPOLL: We already know we have a valid FD. No checks needed.
3243                                 if ((cu->fd != FD_MAGIC_NUMBER) && (cu->fd != -1))
3244 #endif
3245 #ifdef USE_KQUEUE
3246                                 // KQUEUE: We already know we have a valid FD. No checks needed.
3247                                 if ((cu->fd != FD_MAGIC_NUMBER) && (cu->fd != -1))
3248 #endif
3249 #ifdef USE_SELECT
3250                                 // SELECT: We don't know if our FD is valid.
3251                                 if ((cu->fd != FD_MAGIC_NUMBER) && (cu->fd != -1) && (FD_ISSET (cu->fd, &sfd)))
3252 #endif
3253                                 {
3254                                         log(DEBUG,"Data waiting on socket %d",cu->fd);
3255                                         int MOD_RESULT = 0;
3256                                         int result2 = 0;
3257                                         FOREACH_RESULT(OnRawSocketRead(cu->fd,data,65535,result2));
3258                                         if (!MOD_RESULT)
3259                                         {
3260                                                 result = cu->ReadData(data, 65535);
3261                                         }
3262                                         else result = result2;
3263                                         log(DEBUG,"Read result: %d",result);
3264                                         if (result)
3265                                         {
3266                                                 statsRecv += result;
3267                                                 // perform a check on the raw buffer as an array (not a string!) to remove
3268                                                 // characters 0 and 7 which are illegal in the RFC - replace them with spaces.
3269                                                 // hopefully this should stop even more people whining about "Unknown command: *"
3270                                                 for (int checker = 0; checker < result; checker++)
3271                                                 {
3272                                                         if ((data[checker] == 0) || (data[checker] == 7))
3273                                                                 data[checker] = ' ';
3274                                                 }
3275                                                 if (result > 0)
3276                                                         data[result] = '\0';
3277                                                 userrec* current = cu;
3278                                                 int currfd = current->fd;
3279                                                 int floodlines = 0;
3280                                                 // add the data to the users buffer
3281                                                 if (result > 0)
3282                                                 if (!current->AddBuffer(data))
3283                                                 {
3284                                                         // AddBuffer returned false, theres too much data in the user's buffer and theyre up to no good.
3285                                                         if (current->registered == 7)
3286                                                         {
3287                                                                 kill_link(current,"RecvQ exceeded");
3288                                                         }
3289                                                         else
3290                                                         {
3291                                                                 WriteOpers("*** Excess flood from %s",current->ip);
3292                                                                 log(DEFAULT,"Excess flood from: %s",current->ip);
3293                                                                 add_zline(120,ServerName,"Flood from unregistered connection",current->ip);
3294                                                                 apply_lines();
3295                                                         }
3296                                                         goto label;
3297                                                 }
3298                                                 if (current->recvq.length() > (unsigned)NetBufferSize)
3299                                                 {
3300                                                         if (current->registered == 7)
3301                                                         {
3302                                                                 kill_link(current,"RecvQ exceeded");
3303                                                         }
3304                                                         else
3305                                                         {
3306                                                                 WriteOpers("*** Excess flood from %s",current->ip);
3307                                                                 log(DEFAULT,"Excess flood from: %s",current->ip);
3308                                                                 add_zline(120,ServerName,"Flood from unregistered connection",current->ip);
3309                                                                 apply_lines();
3310                                                         }
3311                                                         goto label;
3312                                                 }
3313                                                 // while there are complete lines to process...
3314                                                 while (current->BufferIsReady())
3315                                                 {
3316                                                         floodlines++;
3317                                                         if (TIME > current->reset_due)
3318                                                         {
3319                                                                 current->reset_due = TIME + current->threshold;
3320                                                                 current->lines_in = 0;
3321                                                         }
3322                                                         current->lines_in++;
3323                                                         if (current->lines_in > current->flood)
3324                                                         {
3325                                                                 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3326                                                                 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3327                                                                 kill_link(current,"Excess flood");
3328                                                                 goto label;
3329                                                         }
3330                                                         if ((floodlines > current->flood) && (current->flood != 0))
3331                                                         {
3332                                                                 if (current->registered == 7)
3333                                                                 {
3334                                                                         log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3335                                                                         WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3336                                                                         kill_link(current,"Excess flood");
3337                                                                 }
3338                                                                 else
3339                                                                 {
3340                                                                         add_zline(120,ServerName,"Flood from unregistered connection",current->ip);
3341                                                                         apply_lines();
3342                                                                 }
3343                                                                 goto label;
3344                                                         }
3345                                                         char sanitized[MAXBUF];
3346                                                         // use GetBuffer to copy single lines into the sanitized string
3347                                                         std::string single_line = current->GetBuffer();
3348                                                         current->bytes_in += single_line.length();
3349                                                         current->cmds_in++;
3350                                                         if (single_line.length()>512)
3351                                                         {
3352                                                                 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3353                                                                 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3354                                                                 kill_link(current,"Excess flood");
3355                                                                 goto label;
3356                                                         }
3357                                                         strlcpy(sanitized,single_line.c_str(),MAXBUF);
3358                                                         if (*sanitized)
3359                                                         {
3360                                                                 userrec* old_comp = fd_ref_table[currfd];
3361                                                                 // we're gonna re-scan to check if the nick is gone, after every
3362                                                                 // command - if it has, we're gonna bail
3363                                                                 process_buffer(sanitized,current);
3364                                                                 // look for the user's record in case it's changed... if theyve quit,
3365                                                                 // we cant do anything more with their buffer, so bail.
3366                                                                 // there used to be an ugly, slow loop here. Now we have a reference
3367                                                                 // table, life is much easier (and FASTER)
3368                                                                 userrec* new_comp = fd_ref_table[currfd];
3369                                                                 if ((currfd < 0) || (!fd_ref_table[currfd]) || (old_comp != new_comp))
3370                                                                         goto label;
3371
3372                                                         }
3373                                                 }
3374                                                 goto label;
3375                                         }
3376
3377                                         if ((result == -1) && (errno != EAGAIN) && (errno != EINTR))
3378                                         {
3379                                                 log(DEBUG,"killing: %s",cu->nick);
3380                                                 kill_link(cu,strerror(errno));
3381                                                 goto label;
3382                                         }
3383                                 }
3384                                 // result EAGAIN means nothing read
3385                                 if (result == EAGAIN)
3386                                 {
3387                                 }
3388                                 else
3389                                 if (result == 0)
3390                                 {
3391 #ifdef USE_SELECT
3392                                         if (count2->second)
3393                                         {
3394 #endif
3395                                                 log(DEBUG,"InspIRCd: Exited: %s",cu->nick);
3396                                                 kill_link(cu,"Client exited");
3397                                                 // must bail here? kill_link removes the hash, corrupting the iterator
3398                                                 log(DEBUG,"Bailing from client exit");
3399                                                 goto label;
3400 #ifdef USE_SELECT
3401                                         }
3402 #endif
3403                                 }
3404                                 else if (result > 0)
3405                                 {
3406                                 }
3407                         }
3408                 }
3409                 for (int q = 0; q < total_in_this_set; q++)
3410                 {
3411                         count2++;
3412                 }
3413         }
3414
3415 #ifdef _POSIX_PRIORITY_SCHEDULING
3416         sched_yield();
3417 #endif
3418         
3419 #ifdef USE_SELECT
3420         // set up select call
3421         for (count = 0; count < boundPortCount; count++)
3422         {
3423                 FD_SET (openSockfd[count], &selectFds);
3424         }
3425
3426         tv.tv_usec = 30000L;
3427         selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
3428
3429         /* select is reporting a waiting socket. Poll them all to find out which */
3430         if (selectResult > 0)
3431         {
3432                 for (count = 0; count < boundPortCount; count++)
3433                 {
3434                         if (FD_ISSET (openSockfd[count], &selectFds))
3435                         {
3436 #endif
3437 #ifdef USE_KQUEUE
3438         ts.tv_sec = 0;
3439         ts.tv_nsec = 30000L;
3440         i = kevent(lkq, NULL, 0, ke_list, 32, &ts);
3441         if (i > 0) for (j = 0; j < i; j++)
3442         {
3443                 log(DEBUG,"kqueue: Listening socket event, i=%d, ke.ident=%d",i,ke_list[j].ident);
3444                 // this isnt as efficient as it could be, we could create a reference table
3445                 // to reference bound ports by fd, but this isnt a big bottleneck as the actual
3446                 // number of listening ports on the average ircd is a small number (less than 20)
3447                 // compared to the number of clients (possibly over 2000)
3448                 for (count = 0; count < boundPortCount; count++)
3449                 {
3450                         if ((unsigned)ke_list[j].ident == (unsigned)openSockfd[count])
3451                         {
3452 #endif
3453 #ifdef USE_EPOLL
3454         i = epoll_wait(lep, event, 32, EP_DELAY);
3455         if (i > 0) for (j = 0; j < i; j++)
3456         {
3457                 log(DEBUG,"epoll: Listening socket event, i=%d,events[j].data.fd=%d",i,event[j].data.fd);
3458                 for (count = 0; count < boundPortCount; count++)
3459                 {
3460                         if ((unsigned)event[j].data.fd == (unsigned)openSockfd[count])
3461                         {
3462 #endif
3463                                 char target[MAXBUF], resolved[MAXBUF];
3464                                 length = sizeof (client);
3465                                 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
3466                               
3467                                 strlcpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
3468                                 strlcpy (resolved, target, MAXBUF);
3469                         
3470                                 if (incomingSockfd < 0)
3471                                 {
3472                                         WriteOpers("*** WARNING: Accept failed on port %lu (%s)",(unsigned long)ports[count],target);
3473                                         log(DEBUG,"InspIRCd: accept failed: %lu",(unsigned long)ports[count]);
3474                                         statsRefused++;
3475                                 }
3476                                 else
3477                                 {
3478                                         FOREACH_MOD OnRawSocketAccept(incomingSockfd, resolved, ports[count]);
3479                                         statsAccept++;
3480                                         AddClient(incomingSockfd, resolved, ports[count], false, inet_ntoa (client.sin_addr));
3481                                         log(DEBUG,"InspIRCd: adding client on port %lu fd=%lu",(unsigned long)ports[count],(unsigned long)incomingSockfd);
3482                                 }
3483                         }
3484                 }
3485         }
3486         label:
3487         if (0) {};
3488 #ifdef _POSIX_PRIORITY_SCHEDULING
3489         sched_yield();
3490         sched_yield();
3491 #endif
3492 }
3493 /* not reached */
3494 close (incomingSockfd);
3495 return 0;
3496 }
3497