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