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