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