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