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