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