]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd.cpp
Changed revision id's to std::string
[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 std::string 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 std::string(v2);
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         user->FlushWriteBuf();
1085
1086         FOREACH_MOD OnUserDisconnect(user);
1087
1088         if (user->fd > -1)
1089         {
1090                 FOREACH_MOD OnRawSocketClose(user->fd);
1091 #ifdef USE_KQUEUE
1092                 struct kevent ke;
1093                 EV_SET(&ke, user->fd, EVFILT_READ, EV_DELETE, 0, 0, NULL);
1094                 int i = kevent(kq, &ke, 1, 0, 0, NULL);
1095                 if (i == -1)
1096                 {
1097                         log(DEBUG,"kqueue: Failed to remove user from queue!");
1098                 }
1099 #endif
1100 #ifdef USE_EPOLL
1101                 struct epoll_event ev;
1102                 ev.events = EPOLLIN | EPOLLET;
1103                 ev.data.fd = user->fd;
1104                 int i = epoll_ctl(ep, EPOLL_CTL_DEL, user->fd, &ev);
1105                 if (i < 0)
1106                 {
1107                         log(DEBUG,"epoll: List deletion failure!");
1108                 }
1109 #endif
1110                 shutdown(user->fd,2);
1111                 close(user->fd);
1112         }
1113
1114         // this must come before the WriteOpers so that it doesnt try to fill their buffer with anything
1115         // if they were an oper with +s.
1116         if (user->registered == 7) {
1117                 purge_empty_chans(user);
1118                 WriteOpers("*** Client exiting: %s!%s@%s [%s]",user->nick,user->ident,user->host,reason);
1119                 AddWhoWas(user);
1120         }
1121
1122         if (iter != clientlist.end())
1123         {
1124                 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
1125                 if (user->fd > -1)
1126                         fd_ref_table[user->fd] = NULL;
1127                 clientlist.erase(iter);
1128         }
1129         delete user;
1130 }
1131
1132 void kill_link_silent(userrec *user,const char* r)
1133 {
1134         user_hash::iterator iter = clientlist.find(user->nick);
1135         
1136         char reason[MAXBUF];
1137         
1138         strncpy(reason,r,MAXBUF);
1139
1140         if (strlen(reason)>MAXQUIT)
1141         {
1142                 reason[MAXQUIT-1] = '\0';
1143         }
1144
1145         log(DEBUG,"kill_link: %s '%s'",user->nick,reason);
1146         Write(user->fd,"ERROR :Closing link (%s@%s) [%s]",user->ident,user->host,reason);
1147         log(DEBUG,"closing fd %lu",(unsigned long)user->fd);
1148
1149         user->FlushWriteBuf();
1150
1151         if (user->registered == 7) {
1152                 FOREACH_MOD OnUserQuit(user);
1153                 WriteCommonExcept(user,"QUIT :%s",reason);
1154
1155                 // Q token must go to ALL servers!!!
1156                 char buffer[MAXBUF];
1157                 snprintf(buffer,MAXBUF,"Q %s :%s",user->nick,reason);
1158                 NetSendToAll(buffer);
1159         }
1160
1161         FOREACH_MOD OnUserDisconnect(user);
1162
1163         if (user->fd > -1)
1164         {
1165                 FOREACH_MOD OnRawSocketClose(user->fd);
1166 #ifdef USE_KQUEUE
1167                 struct kevent ke;
1168                 EV_SET(&ke, user->fd, EVFILT_READ, EV_DELETE, 0, 0, NULL);
1169                 int i = kevent(kq, &ke, 1, 0, 0, NULL);
1170                 if (i == -1)
1171                 {
1172                         log(DEBUG,"kqueue: Failed to remove user from queue!");
1173                 }
1174 #endif
1175 #ifdef USE_EPOLL
1176                 struct epoll_event ev;
1177                 ev.events = EPOLLIN | EPOLLET;
1178                 ev.data.fd = user->fd;
1179                 int i = epoll_ctl(ep, EPOLL_CTL_DEL, user->fd, &ev);
1180                 if (i < 0)
1181                 {
1182                         log(DEBUG,"epoll: List deletion failure!");
1183                 }
1184 #endif
1185                 shutdown(user->fd,2);
1186                 close(user->fd);
1187         }
1188
1189         if (user->registered == 7) {
1190                 purge_empty_chans(user);
1191         }
1192         
1193         if (iter != clientlist.end())
1194         {
1195                 log(DEBUG,"deleting user hash value %lu",(unsigned long)user);
1196                 if (user->fd > -1)
1197                         fd_ref_table[user->fd] = NULL;
1198                 clientlist.erase(iter);
1199         }
1200         delete user;
1201 }
1202
1203
1204 int main(int argc, char** argv)
1205 {
1206         Start();
1207         srand(time(NULL));
1208         log(DEBUG,"*** InspIRCd starting up!");
1209         if (!FileExists(CONFIG_FILE))
1210         {
1211                 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
1212                 log(DEFAULT,"main: no config");
1213                 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
1214                 Exit(ERROR);
1215         }
1216         if (argc > 1) {
1217                 for (int i = 1; i < argc; i++)
1218                 {
1219                         if (!strcmp(argv[i],"-nofork")) {
1220                                 nofork = true;
1221                         }
1222                         if (!strcmp(argv[i],"-wait")) {
1223                                 sleep(6);
1224                         }
1225                         if (!strcmp(argv[i],"-nolimit")) {
1226                                 unlimitcore = true;
1227                         }
1228                 }
1229         }
1230         strlcpy(MyExecutable,argv[0],MAXBUF);
1231         
1232         // initialize the lowercase mapping table
1233         for (int cn = 0; cn < 256; cn++)
1234                 lowermap[cn] = cn;
1235         // lowercase the uppercase chars
1236         for (int cn = 65; cn < 91; cn++)
1237                 lowermap[cn] = tolower(cn);
1238         // now replace the specific chars for scandanavian comparison
1239         lowermap['['] = '{';
1240         lowermap[']'] = '}';
1241         lowermap['\\'] = '|';
1242
1243         if (InspIRCd(argv,argc) == ERROR)
1244         {
1245                 log(DEFAULT,"main: daemon function bailed");
1246                 printf("ERROR: could not initialise. Shutting down.\n");
1247                 Exit(ERROR);
1248         }
1249         Exit(TRUE);
1250         return 0;
1251 }
1252
1253 template<typename T> inline string ConvToStr(const T &in)
1254 {
1255         stringstream tmp;
1256         if (!(tmp << in)) return string();
1257         return tmp.str();
1258 }
1259
1260 /* re-allocates a nick in the user_hash after they change nicknames,
1261  * returns a pointer to the new user as it may have moved */
1262
1263 userrec* ReHashNick(char* Old, char* New)
1264 {
1265         //user_hash::iterator newnick;
1266         user_hash::iterator oldnick = clientlist.find(Old);
1267
1268         log(DEBUG,"ReHashNick: %s %s",Old,New);
1269         
1270         if (!strcasecmp(Old,New))
1271         {
1272                 log(DEBUG,"old nick is new nick, skipping");
1273                 return oldnick->second;
1274         }
1275         
1276         if (oldnick == clientlist.end()) return NULL; /* doesnt exist */
1277
1278         log(DEBUG,"ReHashNick: Found hashed nick %s",Old);
1279
1280         userrec* olduser = oldnick->second;
1281         clientlist[New] = olduser;
1282         clientlist.erase(oldnick);
1283
1284         log(DEBUG,"ReHashNick: Nick rehashed as %s",New);
1285         
1286         return clientlist[New];
1287 }
1288
1289 /* adds or updates an entry in the whowas list */
1290 void AddWhoWas(userrec* u)
1291 {
1292         whowas_hash::iterator iter = whowas.find(u->nick);
1293         WhoWasUser *a = new WhoWasUser();
1294         strlcpy(a->nick,u->nick,NICKMAX);
1295         strlcpy(a->ident,u->ident,15);
1296         strlcpy(a->dhost,u->dhost,160);
1297         strlcpy(a->host,u->host,160);
1298         strlcpy(a->fullname,u->fullname,128);
1299         strlcpy(a->server,u->server,256);
1300         a->signon = u->signon;
1301
1302         /* MAX_WHOWAS:   max number of /WHOWAS items
1303          * WHOWAS_STALE: number of hours before a WHOWAS item is marked as stale and
1304          *               can be replaced by a newer one
1305          */
1306         
1307         if (iter == whowas.end())
1308         {
1309                 if (whowas.size() >= WHOWAS_MAX)
1310                 {
1311                         for (whowas_hash::iterator i = whowas.begin(); i != whowas.end(); i++)
1312                         {
1313                                 // 3600 seconds in an hour ;)
1314                                 if ((i->second->signon)<(TIME-(WHOWAS_STALE*3600)))
1315                                 {
1316                                         // delete the old one
1317                                         if (i->second) delete i->second;
1318                                         // replace with new one
1319                                         i->second = a;
1320                                         log(DEBUG,"added WHOWAS entry, purged an old record");
1321                                         return;
1322                                 }
1323                         }
1324                         // no space left and user doesnt exist. Don't leave ram in use!
1325                         log(DEBUG,"Not able to update whowas (list at WHOWAS_MAX entries and trying to add new?), freeing excess ram");
1326                         delete a;
1327                 }
1328                 else
1329                 {
1330                         log(DEBUG,"added fresh WHOWAS entry");
1331                         whowas[a->nick] = a;
1332                 }
1333         }
1334         else
1335         {
1336                 log(DEBUG,"updated WHOWAS entry");
1337                 if (iter->second) delete iter->second;
1338                 iter->second = a;
1339         }
1340 }
1341
1342
1343 /* add a client connection to the sockets list */
1344 void AddClient(int socket, char* host, int port, bool iscached, char* ip)
1345 {
1346         string tempnick;
1347         char tn2[MAXBUF];
1348         user_hash::iterator iter;
1349
1350         tempnick = ConvToStr(socket) + "-unknown";
1351         sprintf(tn2,"%lu-unknown",(unsigned long)socket);
1352
1353         iter = clientlist.find(tempnick);
1354
1355         // fix by brain.
1356         // as these nicknames are 'RFC impossible', we can be sure nobody is going to be
1357         // using one as a registered connection. As theyre per fd, we can also safely assume
1358         // that we wont have collisions. Therefore, if the nick exists in the list, its only
1359         // used by a dead socket, erase the iterator so that the new client may reclaim it.
1360         // this was probably the cause of 'server ignores me when i hammer it with reconnects'
1361         // issue in earlier alphas/betas
1362         if (iter != clientlist.end())
1363         {
1364                 userrec* goner = iter->second;
1365                 delete goner;
1366                 clientlist.erase(iter);
1367         }
1368
1369         /*
1370          * It is OK to access the value here this way since we know
1371          * it exists, we just created it above.
1372          *
1373          * At NO other time should you access a value in a map or a
1374          * hash_map this way.
1375          */
1376         clientlist[tempnick] = new userrec();
1377
1378         NonBlocking(socket);
1379         log(DEBUG,"AddClient: %lu %s %d %s",(unsigned long)socket,host,port,ip);
1380
1381         clientlist[tempnick]->fd = socket;
1382         strncpy(clientlist[tempnick]->nick, tn2,NICKMAX);
1383         strncpy(clientlist[tempnick]->host, host,160);
1384         strncpy(clientlist[tempnick]->dhost, host,160);
1385         strncpy(clientlist[tempnick]->server, ServerName,256);
1386         strncpy(clientlist[tempnick]->ident, "unknown",15);
1387         clientlist[tempnick]->registered = 0;
1388         clientlist[tempnick]->signon = TIME+dns_timeout;
1389         clientlist[tempnick]->lastping = 1;
1390         clientlist[tempnick]->port = port;
1391         strncpy(clientlist[tempnick]->ip,ip,16);
1392
1393         // set the registration timeout for this user
1394         unsigned long class_regtimeout = 90;
1395         int class_flood = 0;
1396         long class_threshold = 5;
1397         long class_sqmax = 262144;      // 256kb
1398         long class_rqmax = 4096;        // 4k
1399
1400         for (ClassVector::iterator i = Classes.begin(); i != Classes.end(); i++)
1401         {
1402                 if (match(clientlist[tempnick]->host,i->host) && (i->type == CC_ALLOW))
1403                 {
1404                         class_regtimeout = (unsigned long)i->registration_timeout;
1405                         class_flood = i->flood;
1406                         clientlist[tempnick]->pingmax = i->pingtime;
1407                         class_threshold = i->threshold;
1408                         class_sqmax = i->sendqmax;
1409                         class_rqmax = i->recvqmax;
1410                         break;
1411                 }
1412         }
1413
1414         clientlist[tempnick]->nping = TIME+clientlist[tempnick]->pingmax+dns_timeout;
1415         clientlist[tempnick]->timeout = TIME+class_regtimeout;
1416         clientlist[tempnick]->flood = class_flood;
1417         clientlist[tempnick]->threshold = class_threshold;
1418         clientlist[tempnick]->sendqmax = class_sqmax;
1419         clientlist[tempnick]->recvqmax = class_rqmax;
1420
1421         for (int i = 0; i < MAXCHANS; i++)
1422         {
1423                 clientlist[tempnick]->chans[i].channel = NULL;
1424                 clientlist[tempnick]->chans[i].uc_modes = 0;
1425         }
1426
1427         if (clientlist.size() == MAXCLIENTS)
1428         {
1429                 kill_link(clientlist[tempnick],"No more connections allowed in this class");
1430                 return;
1431         }
1432
1433         // this is done as a safety check to keep the file descriptors within range of fd_ref_table.
1434         // its a pretty big but for the moment valid assumption:
1435         // file descriptors are handed out starting at 0, and are recycled as theyre freed.
1436         // therefore if there is ever an fd over 65535, 65536 clients must be connected to the
1437         // irc server at once (or the irc server otherwise initiating this many connections, files etc)
1438         // which for the time being is a physical impossibility (even the largest networks dont have more
1439         // than about 10,000 users on ONE server!)
1440         if (socket > 65534)
1441         {
1442                 kill_link(clientlist[tempnick],"Server is full");
1443                 return;
1444         }
1445                 
1446
1447         char* e = matches_exception(ip);
1448         if (!e)
1449         {
1450                 char* r = matches_zline(ip);
1451                 if (r)
1452                 {
1453                         char reason[MAXBUF];
1454                         snprintf(reason,MAXBUF,"Z-Lined: %s",r);
1455                         kill_link(clientlist[tempnick],reason);
1456                         return;
1457                 }
1458         }
1459         fd_ref_table[socket] = clientlist[tempnick];
1460
1461 #ifdef USE_EPOLL
1462         struct epoll_event ev;
1463         log(DEBUG,"epoll: Adduser to events, ep=%d socket=%d",ep,socket);
1464         ev.events = EPOLLIN | EPOLLET;
1465         ev.data.fd = socket;
1466         int i = epoll_ctl(ep, EPOLL_CTL_ADD, socket, &ev);
1467         if (i < 0)
1468         {
1469                 log(DEBUG,"epoll: List insertion failure!");
1470         }
1471 #endif
1472 #ifdef USE_KQUEUE
1473         struct kevent ke;
1474         log(DEBUG,"kqueue: Add user to events, kq=%d socket=%d",kq,socket);
1475         EV_SET(&ke, socket, EVFILT_READ, EV_ADD, 0, 0, NULL);
1476         int i = kevent(kq, &ke, 1, 0, 0, NULL);
1477         if (i == -1)
1478         {
1479                 log(DEBUG,"kqueue: List insertion failure!");
1480         }
1481
1482 #endif
1483 }
1484
1485 /* shows the message of the day, and any other on-logon stuff */
1486 void FullConnectUser(userrec* user)
1487 {
1488         statsConnects++;
1489         user->idle_lastmsg = TIME;
1490         log(DEBUG,"ConnectUser: %s",user->nick);
1491
1492         if ((strcmp(Passwd(user),"")) && (!user->haspassed))
1493         {
1494                 kill_link(user,"Invalid password");
1495                 return;
1496         }
1497         if (IsDenied(user))
1498         {
1499                 kill_link(user,"Unauthorised connection");
1500                 return;
1501         }
1502
1503         char match_against[MAXBUF];
1504         snprintf(match_against,MAXBUF,"%s@%s",user->ident,user->host);
1505         char* e = matches_exception(match_against);
1506         if (!e)
1507         {
1508                 char* r = matches_gline(match_against);
1509                 if (r)
1510                 {
1511                         char reason[MAXBUF];
1512                         snprintf(reason,MAXBUF,"G-Lined: %s",r);
1513                         kill_link_silent(user,reason);
1514                         return;
1515                 }
1516                 r = matches_kline(user->host);
1517                 if (r)
1518                 {
1519                         char reason[MAXBUF];
1520                         snprintf(reason,MAXBUF,"K-Lined: %s",r);
1521                         kill_link_silent(user,reason);
1522                         return;
1523                 }
1524         }
1525
1526         // fix by brain: move this below the xline checks to prevent spurious quits going onto the net that dont belong
1527         user->registered = 7;
1528
1529         WriteServ(user->fd,"NOTICE Auth :Welcome to \002%s\002!",Network);
1530         WriteServ(user->fd,"001 %s :Welcome to the %s IRC Network %s!%s@%s",user->nick,Network,user->nick,user->ident,user->host);
1531         WriteServ(user->fd,"002 %s :Your host is %s, running version %s",user->nick,ServerName,VERSION);
1532         WriteServ(user->fd,"003 %s :This server was created %s %s",user->nick,__TIME__,__DATE__);
1533         WriteServ(user->fd,"004 %s %s %s iowghraAsORVSxNCWqBzvdHtGI lvhopsmntikrRcaqOALQbSeKVfHGCuzN",user->nick,ServerName,VERSION);
1534         // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
1535         std::stringstream v;
1536         v << "MESHED WALLCHOPS MODES=13 CHANTYPES=# PREFIX=(ohv)@%+ MAP SAFELIST MAXCHANNELS=" << MAXCHANS;
1537         v << " MAXBANS=60 NICKLEN=" << NICKMAX;
1538         v << " TOPICLEN=307 KICKLEN=307 MAXTARGETS=20 AWAYLEN=307 CHANMODES=ohvb,k,l,psmnti NETWORK=";
1539         v << Network;
1540         std::string data005 = v.str();
1541         FOREACH_MOD On005Numeric(data005);
1542         // anfl @ #ratbox, efnet reminded me that according to the RFC this cant contain more than 13 tokens per line...
1543         // so i'd better split it :)
1544         std::stringstream out(data005);
1545         std::string token = "";
1546         std::string line5 = "";
1547         int token_counter = 0;
1548         while (!out.eof())
1549         {
1550                 out >> token;
1551                 line5 = line5 + token + " ";
1552                 token_counter++;
1553                 if ((token_counter >= 13) || (out.eof() == true))
1554                 {
1555                         WriteServ(user->fd,"005 %s %s:are supported by this server",user->nick,line5.c_str());
1556                         line5 = "";
1557                         token_counter = 0;
1558                 }
1559         }
1560         ShowMOTD(user);
1561
1562         char buffer[MAXBUF];
1563         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);
1564         NetSendToAll(buffer);
1565
1566         // fix by brain: these should be AFTER the N token, so other servers know what the HELL we're on about... :)
1567         FOREACH_MOD OnUserConnect(user);
1568         WriteOpers("*** Client connecting on port %lu: %s!%s@%s [%s]",(unsigned long)user->port,user->nick,user->ident,user->host,user->ip);
1569 }
1570
1571
1572 /* shows the message of the day, and any other on-logon stuff */
1573 void ConnectUser(userrec *user)
1574 {
1575         // dns is already done, things are fast. no need to wait for dns to complete just pass them straight on
1576         if ((user->dns_done) && (user->registered >= 3) && (AllModulesReportReady(user)))
1577         {
1578                 FullConnectUser(user);
1579         }
1580 }
1581
1582 std::string GetVersionString()
1583 {
1584         char Revision[] = "$Revision$";
1585         char versiondata[MAXBUF];
1586         char *s1 = Revision;
1587         char *savept;
1588         char *v2 = strtok_r(s1," ",&savept);
1589         s1 = savept;
1590         v2 = strtok_r(s1," ",&savept);
1591         s1 = savept;
1592 #ifdef USE_KQUEUE
1593         char socketengine[] = "kqueue";
1594 #endif
1595 #ifdef USE_SELECT
1596         char socketengine[] = "select";
1597 #endif
1598 #ifdef USE_EPOLL
1599         char socketengine[] = "epoll";
1600 #endif
1601         snprintf(versiondata,MAXBUF,"%s Rev. %s %s :%s (O=%lu) [SE=%s]",VERSION,v2,ServerName,SYSTEM,(unsigned long)OPTIMISATION,socketengine);
1602         return versiondata;
1603 }
1604
1605 void handle_version(char **parameters, int pcnt, userrec *user)
1606 {
1607         if (!pcnt)
1608         {
1609                 WriteServ(user->fd,"351 %s :%s",user->nick,GetVersionString().c_str());
1610         }
1611         else
1612         {
1613                 if (!strcmp(parameters[0],"*"))
1614                 {
1615                         for (int j = 0; j < 32; j++)
1616                         {
1617                                 if (me[j] != NULL)
1618                                 {
1619                                         for (int x = 0; x < me[j]->connectors.size(); x++)
1620                                         {
1621                                                 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());
1622                                         }
1623                                 }
1624                         }
1625                         return;
1626                 }
1627                 if (match(ServerName,parameters[0]))
1628                 {
1629                         WriteServ(user->fd,"351 %s :%s",user->nick,GetVersionString().c_str());
1630                         return;
1631                 }
1632                 bool displayed = false, found = false;
1633                 for (int j = 0; j < 32; j++)
1634                 {
1635                         if (me[j] != NULL)
1636                         {
1637                                 for (int x = 0; x < me[j]->connectors.size(); x++)
1638                                 {
1639                                         if (match(me[j]->connectors[x].GetServerName().c_str(),parameters[0]))
1640                                         {
1641                                                 found = true;
1642                                                 if ((me[j]->connectors[x].GetVersionString() != "") && (!displayed))
1643                                                 {
1644                                                         displayed = true;
1645                                                         WriteServ(user->fd,"351 %s :%s",user->nick,me[j]->connectors[x].GetVersionString().c_str());
1646                                                 }
1647                                         }
1648                                 }
1649                         }
1650                 }
1651                 if ((!displayed) && (found))
1652                 {
1653                         WriteServ(user->fd,"402 %s %s :Server %s has no version information",user->nick,parameters[0],parameters[0]);
1654                         return;
1655                 }
1656                 if (!found)
1657                 {
1658                         WriteServ(user->fd,"402 %s %s :No such server",user->nick,parameters[0]);
1659                 }
1660         }
1661         return;
1662 }
1663
1664
1665 // calls a handler function for a command
1666
1667 void call_handler(const char* commandname,char **parameters, int pcnt, userrec *user)
1668 {
1669                 for (int i = 0; i < cmdlist.size(); i++)
1670                 {
1671                         if (!strcasecmp(cmdlist[i].command,commandname))
1672                         {
1673                                 if (cmdlist[i].handler_function)
1674                                 {
1675                                         if (pcnt>=cmdlist[i].min_params)
1676                                         {
1677                                                 if (strchr(user->modes,cmdlist[i].flags_needed))
1678                                                 {
1679                                                         cmdlist[i].handler_function(parameters,pcnt,user);
1680                                                 }
1681                                         }
1682                                 }
1683                         }
1684                 }
1685 }
1686
1687 void DoSplitEveryone()
1688 {
1689         bool go_again = true;
1690         while (go_again)
1691         {
1692                 go_again = false;
1693                 for (int i = 0; i < 32; i++)
1694                 {
1695                         if (me[i] != NULL)
1696                         {
1697                                 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
1698                                 {
1699                                         if (strcasecmp(j->GetServerName().c_str(),ServerName))
1700                                         {
1701                                                 j->routes.clear();
1702                                                 j->CloseConnection();
1703                                                 me[i]->connectors.erase(j);
1704                                                 go_again = true;
1705                                                 break;
1706                                         }
1707                                 }
1708                         }
1709                 }
1710         }
1711         log(DEBUG,"Removed server. Will remove clients...");
1712         // iterate through the userlist and remove all users on this server.
1713         // because we're dealing with a mesh, we dont have to deal with anything
1714         // "down-route" from this server (nice huh)
1715         go_again = true;
1716         char reason[MAXBUF];
1717         while (go_again)
1718         {
1719                 go_again = false;
1720                 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
1721                 {
1722                         if (strcasecmp(u->second->server,ServerName))
1723                         {
1724                                 snprintf(reason,MAXBUF,"%s %s",ServerName,u->second->server);
1725                                 kill_link(u->second,reason);
1726                                 go_again = true;
1727                                 break;
1728                         }
1729                 }
1730         }
1731 }
1732
1733
1734
1735 void force_nickchange(userrec* user,const char* newnick)
1736 {
1737         char nick[MAXBUF];
1738         int MOD_RESULT = 0;
1739         
1740         strcpy(nick,"");
1741
1742         FOREACH_RESULT(OnUserPreNick(user,newnick));
1743         if (MOD_RESULT) {
1744                 statsCollisions++;
1745                 kill_link(user,"Nickname collision");
1746                 return;
1747         }
1748         if (matches_qline(newnick))
1749         {
1750                 statsCollisions++;
1751                 kill_link(user,"Nickname collision");
1752                 return;
1753         }
1754         
1755         if (user)
1756         {
1757                 if (newnick)
1758                 {
1759                         strncpy(nick,newnick,MAXBUF);
1760                 }
1761                 if (user->registered == 7)
1762                 {
1763                         char* pars[1];
1764                         pars[0] = nick;
1765                         handle_nick(pars,1,user);
1766                 }
1767         }
1768 }
1769                                 
1770
1771 int process_parameters(char **command_p,char *parameters)
1772 {
1773         int j = 0;
1774         int q = strlen(parameters);
1775         if (!q)
1776         {
1777                 /* no parameters, command_p invalid! */
1778                 return 0;
1779         }
1780         if (parameters[0] == ':')
1781         {
1782                 command_p[0] = parameters+1;
1783                 return 1;
1784         }
1785         if (q)
1786         {
1787                 if ((strchr(parameters,' ')==NULL) || (parameters[0] == ':'))
1788                 {
1789                         /* only one parameter */
1790                         command_p[0] = parameters;
1791                         if (parameters[0] == ':')
1792                         {
1793                                 if (strchr(parameters,' ') != NULL)
1794                                 {
1795                                         command_p[0]++;
1796                                 }
1797                         }
1798                         return 1;
1799                 }
1800         }
1801         command_p[j++] = parameters;
1802         for (int i = 0; i <= q; i++)
1803         {
1804                 if (parameters[i] == ' ')
1805                 {
1806                         command_p[j++] = parameters+i+1;
1807                         parameters[i] = '\0';
1808                         if (command_p[j-1][0] == ':')
1809                         {
1810                                 *command_p[j-1]++; /* remove dodgy ":" */
1811                                 break;
1812                                 /* parameter like this marks end of the sequence */
1813                         }
1814                 }
1815         }
1816         return j; /* returns total number of items in the list */
1817 }
1818
1819 void process_command(userrec *user, char* cmd)
1820 {
1821         char *parameters;
1822         char *command;
1823         char *command_p[127];
1824         char p[MAXBUF], temp[MAXBUF];
1825         int j, items, cmd_found;
1826
1827         for (int i = 0; i < 127; i++)
1828                 command_p[i] = NULL;
1829
1830         if (!user)
1831         {
1832                 return;
1833         }
1834         if (!cmd)
1835         {
1836                 return;
1837         }
1838         if (!cmd[0])
1839         {
1840                 return;
1841         }
1842         
1843         int total_params = 0;
1844         if (strlen(cmd)>2)
1845         {
1846                 for (int q = 0; q < strlen(cmd)-1; q++)
1847                 {
1848                         if ((cmd[q] == ' ') && (cmd[q+1] == ':'))
1849                         {
1850                                 total_params++;
1851                                 // found a 'trailing', we dont count them after this.
1852                                 break;
1853                         }
1854                         if (cmd[q] == ' ')
1855                                 total_params++;
1856                 }
1857         }
1858
1859         // another phidjit bug...
1860         if (total_params > 126)
1861         {
1862                 *(strchr(cmd,' ')) = '\0';
1863                 WriteServ(user->fd,"421 %s %s :Too many parameters given",user->nick,cmd);
1864                 return;
1865         }
1866
1867         strlcpy(temp,cmd,MAXBUF);
1868         
1869         std::string tmp = cmd;
1870         for (int i = 0; i <= MODCOUNT; i++)
1871         {
1872                 std::string oldtmp = tmp;
1873                 modules[i]->OnServerRaw(tmp,true,user);
1874                 if (oldtmp != tmp)
1875                 {
1876                         log(DEBUG,"A Module changed the input string!");
1877                         log(DEBUG,"New string: %s",tmp.c_str());
1878                         log(DEBUG,"Old string: %s",oldtmp.c_str());
1879                         break;
1880                 }
1881         }
1882         strlcpy(cmd,tmp.c_str(),MAXBUF);
1883         strlcpy(temp,cmd,MAXBUF);
1884
1885         if (!strchr(cmd,' '))
1886         {
1887                 /* no parameters, lets skip the formalities and not chop up
1888                  * the string */
1889                 log(DEBUG,"About to preprocess command with no params");
1890                 items = 0;
1891                 command_p[0] = NULL;
1892                 parameters = NULL;
1893                 for (int i = 0; i <= strlen(cmd); i++)
1894                 {
1895                         cmd[i] = toupper(cmd[i]);
1896                 }
1897                 command = cmd;
1898         }
1899         else
1900         {
1901                 strcpy(cmd,"");
1902                 j = 0;
1903                 /* strip out extraneous linefeeds through mirc's crappy pasting (thanks Craig) */
1904                 for (int i = 0; i < strlen(temp); i++)
1905                 {
1906                         if ((temp[i] != 10) && (temp[i] != 13) && (temp[i] != 0) && (temp[i] != 7))
1907                         {
1908                                 cmd[j++] = temp[i];
1909                                 cmd[j] = 0;
1910                         }
1911                 }
1912                 /* split the full string into a command plus parameters */
1913                 parameters = p;
1914                 strcpy(p," ");
1915                 command = cmd;
1916                 if (strchr(cmd,' '))
1917                 {
1918                         for (int i = 0; i <= strlen(cmd); i++)
1919                         {
1920                                 /* capitalise the command ONLY, leave params intact */
1921                                 cmd[i] = toupper(cmd[i]);
1922                                 /* are we nearly there yet?! :P */
1923                                 if (cmd[i] == ' ')
1924                                 {
1925                                         command = cmd;
1926                                         parameters = cmd+i+1;
1927                                         cmd[i] = '\0';
1928                                         break;
1929                                 }
1930                         }
1931                 }
1932                 else
1933                 {
1934                         for (int i = 0; i <= strlen(cmd); i++)
1935                         {
1936                                 cmd[i] = toupper(cmd[i]);
1937                         }
1938                 }
1939
1940         }
1941         cmd_found = 0;
1942         
1943         if (strlen(command)>MAXCOMMAND)
1944         {
1945                 WriteServ(user->fd,"421 %s %s :Command too long",user->nick,command);
1946                 return;
1947         }
1948         
1949         for (int x = 0; x < strlen(command); x++)
1950         {
1951                 if (((command[x] < 'A') || (command[x] > 'Z')) && (command[x] != '.'))
1952                 {
1953                         if (((command[x] < '0') || (command[x]> '9')) && (command[x] != '-'))
1954                         {
1955                                 if (strchr("@!\"$%^&*(){}[]_=+;:'#~,<>/?\\|`",command[x]))
1956                                 {
1957                                         statsUnknown++;
1958                                         WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
1959                                         return;
1960                                 }
1961                         }
1962                 }
1963         }
1964
1965         for (int i = 0; i != cmdlist.size(); i++)
1966         {
1967                 if (cmdlist[i].command[0])
1968                 {
1969                         if (strlen(command)>=(strlen(cmdlist[i].command))) if (!strncmp(command, cmdlist[i].command,MAXCOMMAND))
1970                         {
1971                                 if (parameters)
1972                                 {
1973                                         if (parameters[0])
1974                                         {
1975                                                 items = process_parameters(command_p,parameters);
1976                                         }
1977                                         else
1978                                         {
1979                                                 items = 0;
1980                                                 command_p[0] = NULL;
1981                                         }
1982                                 }
1983                                 else
1984                                 {
1985                                         items = 0;
1986                                         command_p[0] = NULL;
1987                                 }
1988                                 
1989                                 if (user)
1990                                 {
1991                                         /* activity resets the ping pending timer */
1992                                         user->nping = TIME + user->pingmax;
1993                                         if ((items) < cmdlist[i].min_params)
1994                                         {
1995                                                 log(DEBUG,"process_command: not enough parameters: %s %s",user->nick,command);
1996                                                 WriteServ(user->fd,"461 %s %s :Not enough parameters",user->nick,command);
1997                                                 return;
1998                                         }
1999                                         if ((!strchr(user->modes,cmdlist[i].flags_needed)) && (cmdlist[i].flags_needed))
2000                                         {
2001                                                 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
2002                                                 WriteServ(user->fd,"481 %s :Permission Denied- You do not have the required operator privilages",user->nick);
2003                                                 cmd_found = 1;
2004                                                 return;
2005                                         }
2006                                         if ((cmdlist[i].flags_needed) && (!user->HasPermission(command)))
2007                                         {
2008                                                 log(DEBUG,"process_command: permission denied: %s %s",user->nick,command);
2009                                                 WriteServ(user->fd,"481 %s :Permission Denied- Oper type %s does not have access to command %s",user->nick,user->oper,command);
2010                                                 cmd_found = 1;
2011                                                 return;
2012                                         }
2013                                         /* if the command isnt USER, PASS, or NICK, and nick is empty,
2014                                          * deny command! */
2015                                         if ((strncmp(command,"USER",4)) && (strncmp(command,"NICK",4)) && (strncmp(command,"PASS",4)))
2016                                         {
2017                                                 if ((!isnick(user->nick)) || (user->registered != 7))
2018                                                 {
2019                                                         log(DEBUG,"process_command: not registered: %s %s",user->nick,command);
2020                                                         WriteServ(user->fd,"451 %s :You have not registered",command);
2021                                                         return;
2022                                                 }
2023                                         }
2024                                         if ((user->registered == 7) && (!strchr(user->modes,'o')))
2025                                         {
2026                                                 char* mycmd;
2027                                                 char* savept2;
2028                                                 mycmd = strtok_r(DisabledCommands," ",&savept2);
2029                                                 while (mycmd)
2030                                                 {
2031                                                         if (!strcasecmp(mycmd,command))
2032                                                         {
2033                                                                 // command is disabled!
2034                                                                 WriteServ(user->fd,"421 %s %s :This command has been disabled.",user->nick,command);
2035                                                                 return;
2036                                                         }
2037                                                         mycmd = strtok_r(NULL," ",&savept2);
2038                                                 }
2039         
2040
2041                                         }
2042                                         if ((user->registered == 7) || (!strncmp(command,"USER",4)) || (!strncmp(command,"NICK",4)) || (!strncmp(command,"PASS",4)))
2043                                         {
2044                                                 if (cmdlist[i].handler_function)
2045                                                 {
2046                                                         
2047                                                         /* ikky /stats counters */
2048                                                         if (temp)
2049                                                         {
2050                                                                 cmdlist[i].use_count++;
2051                                                                 cmdlist[i].total_bytes+=strlen(temp);
2052                                                         }
2053
2054                                                         int MOD_RESULT = 0;
2055                                                         FOREACH_RESULT(OnPreCommand(command,command_p,items,user));
2056                                                         if (MOD_RESULT == 1) {
2057                                                                 return;
2058                                                         }
2059
2060                                                         /* WARNING: nothing may come after the
2061                                                          * command handler call, as the handler
2062                                                          * may free the user structure! */
2063
2064                                                         cmdlist[i].handler_function(command_p,items,user);
2065                                                 }
2066                                                 return;
2067                                         }
2068                                         else
2069                                         {
2070                                                 WriteServ(user->fd,"451 %s :You have not registered",command);
2071                                                 return;
2072                                         }
2073                                 }
2074                                 cmd_found = 1;
2075                         }
2076                 }
2077         }
2078         if ((!cmd_found) && (user))
2079         {
2080                 statsUnknown++;
2081                 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
2082         }
2083 }
2084
2085 bool removecommands(const char* source)
2086 {
2087         bool go_again = true;
2088         while (go_again)
2089         {
2090                 go_again = false;
2091                 for (std::deque<command_t>::iterator i = cmdlist.begin(); i != cmdlist.end(); i++)
2092                 {
2093                         if (!strcmp(i->source,source))
2094                         {
2095                                 log(DEBUG,"removecommands(%s) Removing dependent command: %s",i->source,i->command);
2096                                 cmdlist.erase(i);
2097                                 go_again = true;
2098                                 break;
2099                         }
2100                 }
2101         }
2102         return true;
2103 }
2104
2105
2106 void process_buffer(const char* cmdbuf,userrec *user)
2107 {
2108         if (!user)
2109         {
2110                 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2111                 return;
2112         }
2113         char cmd[MAXBUF];
2114         if (!cmdbuf)
2115         {
2116                 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2117                 return;
2118         }
2119         if (!cmdbuf[0])
2120         {
2121                 return;
2122         }
2123         while (*cmdbuf == ' ') cmdbuf++; // strip leading spaces
2124
2125         strlcpy(cmd,cmdbuf,MAXBUF);
2126         if (!cmd[0])
2127         {
2128                 return;
2129         }
2130         int sl = strlen(cmd)-1;
2131         if ((cmd[sl] == 13) || (cmd[sl] == 10))
2132         {
2133                 cmd[sl] = '\0';
2134         }
2135         sl = strlen(cmd)-1;
2136         if ((cmd[sl] == 13) || (cmd[sl] == 10))
2137         {
2138                 cmd[sl] = '\0';
2139         }
2140         sl = strlen(cmd)-1;
2141         while (cmd[sl] == ' ') // strip trailing spaces
2142         {
2143                 cmd[sl] = '\0';
2144                 sl = strlen(cmd)-1;
2145         }
2146
2147         if (!cmd[0])
2148         {
2149                 return;
2150         }
2151         log(DEBUG,"CMDIN: %s %s",user->nick,cmd);
2152         tidystring(cmd);
2153         if ((user) && (cmd))
2154         {
2155                 process_command(user,cmd);
2156         }
2157 }
2158
2159 void DoSync(serverrec* serv, char* tcp_host)
2160 {
2161         char data[MAXBUF];
2162         log(DEBUG,"Sending sync");
2163         // send start of sync marker: Y <timestamp>
2164         // at this point the ircd receiving it starts broadcasting this netburst to all ircds
2165         // except the ones its receiving it from.
2166         snprintf(data,MAXBUF,"%s Y %lu",CreateSum().c_str(),(unsigned long)TIME);
2167         serv->SendPacket(data,tcp_host);
2168         // send users and channels
2169
2170         NetSendMyRoutingTable();
2171
2172         // send all routing table and uline voodoo. The ordering of these commands is IMPORTANT!
2173         for (int j = 0; j < 32; j++)
2174         {
2175                 if (me[j] != NULL)
2176                 {
2177                         for (int k = 0; k < me[j]->connectors.size(); k++)
2178                         {
2179                                 if (is_uline(me[j]->connectors[k].GetServerName().c_str()))
2180                                 {
2181                                         snprintf(data,MAXBUF,"%s H %s",CreateSum().c_str(),me[j]->connectors[k].GetServerName().c_str());
2182                                         serv->SendPacket(data,tcp_host);
2183                                 }
2184                         }
2185                 }
2186         }
2187
2188         // send our version for the remote side to cache
2189         snprintf(data,MAXBUF,"%s v %s %s",CreateSum().c_str(),ServerName,GetVersionString().c_str());
2190         serv->SendPacket(data,tcp_host);
2191
2192         // sync the users and channels, give the modules a look-in.
2193         for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
2194         {
2195                 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);
2196                 serv->SendPacket(data,tcp_host);
2197                 if (strchr(u->second->modes,'o'))
2198                 {
2199                         snprintf(data,MAXBUF,"%s | %s %s",CreateSum().c_str(),u->second->nick,u->second->oper);
2200                         serv->SendPacket(data,tcp_host);
2201                 }
2202                 for (int i = 0; i <= MODCOUNT; i++)
2203                 {
2204                         string_list l = modules[i]->OnUserSync(u->second);
2205                         for (int j = 0; j < l.size(); j++)
2206                         {
2207                                 snprintf(data,MAXBUF,"%s %s",CreateSum().c_str(),l[j].c_str());
2208                                 serv->SendPacket(data,tcp_host);
2209                         }
2210                 }
2211                 char* chl = chlist(u->second,u->second);
2212                 if (strcmp(chl,""))
2213                 {
2214                         snprintf(data,MAXBUF,"%s J %s %s",CreateSum().c_str(),u->second->nick,chl);
2215                         serv->SendPacket(data,tcp_host);
2216                 }
2217         }
2218         // send channel modes, topics etc...
2219         for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
2220         {
2221                 snprintf(data,MAXBUF,"M %s +%s",c->second->name,chanmodes(c->second));
2222                 serv->SendPacket(data,tcp_host);
2223                 for (int i = 0; i <= MODCOUNT; i++)
2224                 {
2225                         string_list l = modules[i]->OnChannelSync(c->second);
2226                         for (int j = 0; j < l.size(); j++)
2227                         {
2228                                 snprintf(data,MAXBUF,"%s %s",CreateSum().c_str(),l[j].c_str());
2229                                 serv->SendPacket(data,tcp_host);
2230                         }
2231                 }
2232                 if (c->second->topic[0])
2233                 {
2234                         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);
2235                         serv->SendPacket(data,tcp_host);
2236                 }
2237                 // send current banlist
2238                 
2239                 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
2240                 {
2241                         snprintf(data,MAXBUF,"%s M %s +b %s",CreateSum().c_str(),c->second->name,b->data);
2242                         serv->SendPacket(data,tcp_host);
2243                 }
2244         }
2245         // sync global zlines, glines, etc
2246         sync_xlines(serv,tcp_host);
2247
2248         snprintf(data,MAXBUF,"%s F %lu",CreateSum().c_str(),(unsigned long)TIME);
2249         serv->SendPacket(data,tcp_host);
2250         log(DEBUG,"Sent sync");
2251         // ircd sends its serverlist after the end of sync here
2252 }
2253
2254
2255 void NetSendMyRoutingTable()
2256 {
2257         // send out a line saying what is reachable to us.
2258         // E.g. if A is linked to B C and D, send out:
2259         // $ A B C D
2260         // if its only linked to B and D send out:
2261         // $ A B D
2262         // if it has no links, dont even send out the line at all.
2263         char buffer[MAXBUF];
2264         snprintf(buffer,MAXBUF,"$ %s",ServerName);
2265         bool sendit = false;
2266         for (int i = 0; i < 32; i++)
2267         {
2268                 if (me[i] != NULL)
2269                 {
2270                         for (int j = 0; j < me[i]->connectors.size(); j++)
2271                         {
2272                                 if ((me[i]->connectors[j].GetState() != STATE_DISCONNECTED) || (is_uline(me[i]->connectors[j].GetServerName().c_str())))
2273                                 {
2274                                         strlcat(buffer," ",MAXBUF);
2275                                         strlcat(buffer,me[i]->connectors[j].GetServerName().c_str(),MAXBUF);
2276                                         sendit = true;
2277                                 }
2278                         }
2279                 }
2280         }
2281         if (sendit)
2282                 NetSendToAll(buffer);
2283 }
2284
2285
2286 void DoSplit(const char* params)
2287 {
2288         bool go_again = true;
2289         while (go_again)
2290         {
2291                 go_again = false;
2292                 for (int i = 0; i < 32; i++)
2293                 {
2294                         if (me[i] != NULL)
2295                         {
2296                                 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2297                                 {
2298                                         if (!strcasecmp(j->GetServerName().c_str(),params))
2299                                         {
2300                                                 j->routes.clear();
2301                                                 j->CloseConnection();
2302                                                 me[i]->connectors.erase(j);
2303                                                 go_again = true;
2304                                                 break;
2305                                         }
2306                                 }
2307                         }
2308                 }
2309         }
2310         log(DEBUG,"Removed server. Will remove clients...");
2311         // iterate through the userlist and remove all users on this server.
2312         // because we're dealing with a mesh, we dont have to deal with anything
2313         // "down-route" from this server (nice huh)
2314         go_again = true;
2315         char reason[MAXBUF];
2316         snprintf(reason,MAXBUF,"%s %s",ServerName,params);
2317         while (go_again)
2318         {
2319                 go_again = false;
2320                 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
2321                 {
2322                         if (!strcasecmp(u->second->server,params))
2323                         {
2324                                 kill_link(u->second,reason);
2325                                 go_again = true;
2326                                 break;
2327                         }
2328                 }
2329         }
2330 }
2331
2332 // removes a server. Will NOT remove its users!
2333
2334 void RemoveServer(const char* name)
2335 {
2336         bool go_again = true;
2337         while (go_again)
2338         {
2339                 go_again = false;
2340                 for (int i = 0; i < 32; i++)
2341                 {
2342                         if (me[i] != NULL)
2343                         {
2344                                 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2345                                 {
2346                                         if (!strcasecmp(j->GetServerName().c_str(),name))
2347                                         {
2348                                                 j->routes.clear();
2349                                                 j->CloseConnection();
2350                                                 me[i]->connectors.erase(j);
2351                                                 go_again = true;
2352                                                 break;
2353                                         }
2354                                 }
2355                         }
2356                 }
2357         }
2358 }
2359
2360
2361 char MODERR[MAXBUF];
2362
2363 char* ModuleError()
2364 {
2365         return MODERR;
2366 }
2367
2368 void erase_factory(int j)
2369 {
2370         int v = 0;
2371         for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
2372         {
2373                 if (v == j)
2374                 {
2375                         factory.erase(t);
2376                         factory.push_back(NULL);
2377                         return;
2378                 }
2379                 v++;
2380         }
2381 }
2382
2383 void erase_module(int j)
2384 {
2385         int v1 = 0;
2386         for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
2387         {
2388                 if (v1 == j)
2389                 {
2390                         delete *m;
2391                         modules.erase(m);
2392                         modules.push_back(NULL);
2393                         break;
2394                 }
2395                 v1++;
2396         }
2397         int v2 = 0;
2398         for (std::vector<std::string>::iterator v = module_names.begin(); v != module_names.end(); v++)
2399         {
2400                 if (v2 == j)
2401                 {
2402                        module_names.erase(v);
2403                        break;
2404                 }
2405                 v2++;
2406         }
2407
2408 }
2409
2410 bool UnloadModule(const char* filename)
2411 {
2412         std::string filename_str = filename;
2413         for (int j = 0; j != module_names.size(); j++)
2414         {
2415                 if (module_names[j] == filename_str)
2416                 {
2417                         if (modules[j]->GetVersion().Flags & VF_STATIC)
2418                         {
2419                                 log(DEFAULT,"Failed to unload STATIC module %s",filename);
2420                                 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
2421                                 return false;
2422                         }
2423                         // found the module
2424                         log(DEBUG,"Deleting module...");
2425                         erase_module(j);
2426                         log(DEBUG,"Erasing module entry...");
2427                         erase_factory(j);
2428                         log(DEBUG,"Removing dependent commands...");
2429                         removecommands(filename);
2430                         log(DEFAULT,"Module %s unloaded",filename);
2431                         MODCOUNT--;
2432                         return true;
2433                 }
2434         }
2435         log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
2436         snprintf(MODERR,MAXBUF,"Module not loaded");
2437         return false;
2438 }
2439
2440 bool LoadModule(const char* filename)
2441 {
2442         char modfile[MAXBUF];
2443 #ifdef STATIC_LINK
2444         snprintf(modfile,MAXBUF,"%s",filename);
2445 #else
2446         snprintf(modfile,MAXBUF,"%s/%s",ModPath,filename);
2447 #endif
2448         std::string filename_str = filename;
2449 #ifndef STATIC_LINK
2450         if (!DirValid(modfile))
2451         {
2452                 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
2453                 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
2454                 return false;
2455         }
2456 #endif
2457         log(DEBUG,"Loading module: %s",modfile);
2458 #ifndef STATIC_LINK
2459         if (FileExists(modfile))
2460         {
2461 #endif
2462                 for (int j = 0; j < module_names.size(); j++)
2463                 {
2464                         if (module_names[j] == filename_str)
2465                         {
2466                                 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
2467                                 snprintf(MODERR,MAXBUF,"Module already loaded");
2468                                 return false;
2469                         }
2470                 }
2471                 ircd_module* a = new ircd_module(modfile);
2472                 factory[MODCOUNT+1] = a;
2473                 if (factory[MODCOUNT+1]->LastError())
2474                 {
2475                         log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
2476                         snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
2477                         MODCOUNT--;
2478                         return false;
2479                 }
2480                 if (factory[MODCOUNT+1]->factory)
2481                 {
2482                         Module* m = factory[MODCOUNT+1]->factory->CreateModule();
2483                         modules[MODCOUNT+1] = m;
2484                         /* save the module and the module's classfactory, if
2485                          * this isnt done, random crashes can occur :/ */
2486                         module_names.push_back(filename);
2487                 }
2488                 else
2489                 {
2490                         log(DEFAULT,"Unable to load %s",modfile);
2491                         snprintf(MODERR,MAXBUF,"Factory function failed!");
2492                         return false;
2493                 }
2494 #ifndef STATIC_LINK
2495         }
2496         else
2497         {
2498                 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
2499                 snprintf(MODERR,MAXBUF,"Module file could not be found");
2500                 return false;
2501         }
2502 #endif
2503         MODCOUNT++;
2504         return true;
2505 }
2506
2507 int InspIRCd(char** argv, int argc)
2508 {
2509         struct sockaddr_in client,server;
2510         char addrs[MAXBUF][255];
2511         int incomingSockfd, result = TRUE;
2512         socklen_t length;
2513         int count = 0;
2514         int selectResult = 0, selectResult2 = 0;
2515         char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
2516         fd_set selectFds;
2517         timeval tv;
2518
2519         std::string logpath = GetFullProgDir(argv,argc) + "/ircd.log";
2520         log_file = fopen(logpath.c_str(),"a+");
2521         if (!log_file)
2522         {
2523                 printf("ERROR: Could not write to logfile %s, bailing!\n\n",logpath.c_str());
2524                 Exit(ERROR);
2525         }
2526
2527 #ifdef IS_CYGWIN
2528         printf("Logging to ircd.log...\n");
2529 #else
2530         printf("Logging to %s...\n",logpath.c_str());
2531 #endif
2532
2533         log(DEFAULT,"$Id$");
2534         if (geteuid() == 0)
2535         {
2536                 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
2537                 Exit(ERROR);
2538                 log(DEFAULT,"InspIRCd: startup: not starting with UID 0!");
2539         }
2540         SetupCommandTable();
2541         log(DEBUG,"InspIRCd: startup: default command table set up");
2542         
2543         ReadConfig(true,NULL);
2544         if (DieValue[0])
2545         { 
2546                 printf("WARNING: %s\n\n",DieValue);
2547                 log(DEFAULT,"Ut-Oh, somebody didn't read their config file: '%s'",DieValue);
2548                 exit(0); 
2549         }  
2550         log(DEBUG,"InspIRCd: startup: read config");
2551
2552         int clientportcount = 0, serverportcount = 0;
2553
2554         for (count = 0; count < ConfValueEnum("bind",&config_f); count++)
2555         {
2556                 ConfValue("bind","port",count,configToken,&config_f);
2557                 ConfValue("bind","address",count,Addr,&config_f);
2558                 ConfValue("bind","type",count,Type,&config_f);
2559                 if (!strcmp(Type,"servers"))
2560                 {
2561                         char Default[MAXBUF];
2562                         strcpy(Default,"no");
2563                         ConfValue("bind","default",count,Default,&config_f);
2564                         if (strchr(Default,'y'))
2565                         {
2566                                 defaultRoute = serverportcount;
2567                                 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
2568                         }
2569                         me[serverportcount] = new serverrec(ServerName,100L,false);
2570                         if (!me[serverportcount]->CreateListener(Addr,atoi(configToken)))
2571                         {
2572                                 log(DEFAULT,"Warning: Failed to bind port %lu",(unsigned long)atoi(configToken));
2573                                 printf("Warning: Failed to bind port %lu\n",(unsigned long)atoi(configToken));
2574                         }
2575                         else
2576                         {
2577                                 serverportcount++;
2578                         }
2579                 }
2580                 else
2581                 {
2582                         ports[clientportcount] = atoi(configToken);
2583                         strlcpy(addrs[clientportcount],Addr,256);
2584                         clientportcount++;
2585                 }
2586                 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
2587         }
2588         portCount = clientportcount;
2589         SERVERportCount = serverportcount;
2590           
2591         log(DEBUG,"InspIRCd: startup: read %lu total client ports and %lu total server ports",(unsigned long)portCount,(unsigned long)SERVERportCount);
2592         log(DEBUG,"InspIRCd: startup: InspIRCd is now starting!");
2593         
2594         printf("\n");
2595         
2596         /* BugFix By Craig! :p */
2597         MODCOUNT = -1;
2598         for (count = 0; count < ConfValueEnum("module",&config_f); count++)
2599         {
2600                 ConfValue("module","name",count,configToken,&config_f);
2601                 printf("Loading module... \033[1;32m%s\033[0m\n",configToken);
2602                 if (!LoadModule(configToken))
2603                 {
2604                         log(DEFAULT,"Exiting due to a module loader error.");
2605                         printf("\nThere was an error loading a module: %s\n\nYou might want to do './inspircd start' instead of 'bin/inspircd'\n\n",ModuleError());
2606                         Exit(0);
2607                 }
2608         }
2609         log(DEFAULT,"Total loaded modules: %lu",(unsigned long)MODCOUNT+1);
2610         
2611         startup_time = time(NULL);
2612           
2613         char PID[MAXBUF];
2614         ConfValue("pid","file",0,PID,&config_f);
2615         // write once here, to try it out and make sure its ok
2616         WritePID(PID);
2617           
2618         /* setup select call */
2619 #ifndef USE_KQUEUE
2620         FD_ZERO(&selectFds);
2621 #endif
2622         log(DEBUG,"InspIRCd: startup: zero selects");
2623         log(VERBOSE,"InspIRCd: startup: portCount = %lu", (unsigned long)portCount);
2624         
2625         for (count = 0; count < portCount; count++)
2626         {
2627                 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
2628                 {
2629                         log(DEBUG,"InspIRCd: startup: bad fd %lu",(unsigned long)openSockfd[boundPortCount]);
2630                         return(ERROR);
2631                 }
2632                 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
2633                 {
2634                         log(DEFAULT,"InspIRCd: startup: failed to bind port %lu",(unsigned long)ports[count]);
2635                 }
2636                 else    /* well we at least bound to one socket so we'll continue */
2637                 {
2638                         boundPortCount++;
2639                 }
2640         }
2641         
2642         log(DEBUG,"InspIRCd: startup: total bound ports %lu",(unsigned long)boundPortCount);
2643           
2644         /* if we didn't bind to anything then abort */
2645         if (boundPortCount == 0)
2646         {
2647                 log(DEFAULT,"InspIRCd: startup: no ports bound, bailing!");
2648                 printf("\nERROR: Was not able to bind any of %lu ports! Please check your configuration.\n\n", (unsigned long)portCount);
2649                 return (ERROR);
2650         }
2651         
2652
2653         printf("\nInspIRCd is now running!\n");
2654
2655         if (nofork)
2656         {
2657                 log(VERBOSE,"Not forking as -nofork was specified");
2658         }
2659         else
2660         {
2661                 if (DaemonSeed() == ERROR)
2662                 {
2663                         log(DEFAULT,"InspIRCd: startup: can't daemonise");
2664                         printf("ERROR: could not go into daemon mode. Shutting down.\n");
2665                         Exit(ERROR);
2666                 }
2667         }
2668
2669         // BUGFIX: We cannot initialize this before forking, as the kqueue data is not inherited by child processes!
2670 #ifdef USE_KQUEUE
2671         kq = kqueue();
2672         lkq = kqueue();
2673         skq = kqueue();
2674         if ((kq == -1) || (lkq == -1) || (skq == -1))
2675         {
2676                 log(DEFAULT,"main: kqueue() failed!");
2677                 printf("ERROR: could not initialise kqueue event system. Shutting down.\n");
2678                 Exit(ERROR);
2679         }
2680 #endif
2681
2682 #ifdef USE_EPOLL
2683         ep = epoll_create(MAXCLIENTS);
2684         lep = epoll_create(32);
2685         sep = epoll_create(128);
2686         if ((ep == -1) || (lep == -1) || (sep == -1))
2687         {
2688                 log(DEFAULT,"main: epoll_create() failed!");
2689                 printf("ERROR: could not initialise epoll event system. Shutting down.\n");
2690                 Exit(ERROR);
2691         }
2692 #endif
2693
2694 #ifdef USE_EPOLL
2695         log(DEFAULT,"epoll socket engine is enabled. Filling listen list. boundPortcount=%d",boundPortCount);
2696         for (count = 0; count < boundPortCount; count++)
2697         {
2698                 struct epoll_event ev;
2699                 log(DEBUG,"epoll: Add listening socket to events, ep=%d socket=%d",lep,openSockfd[count]);
2700                 ev.events = EPOLLIN | EPOLLET;
2701                 ev.data.fd = openSockfd[count];
2702                 int i = epoll_ctl(lep, EPOLL_CTL_ADD, openSockfd[count], &ev);
2703                 if (i < 0)
2704                 {
2705                         log(DEFAULT,"main: add listen ports, epoll_ctl failed!");
2706                         printf("ERROR: could not initialise listening sockets in epoll list. Shutting down.\n");
2707                         Exit(ERROR);
2708                 }
2709                 
2710         }
2711         for (int t = 0; t != SERVERportCount; t++)
2712         {
2713                 struct epoll_event ev;
2714                 log(DEBUG,"epoll: Add listening server socket to events, ep=%d socket=%d",sep,me[t]->fd);
2715                 ev.events = EPOLLIN | EPOLLET;
2716                 ev.data.fd = me[t]->fd;
2717                 int i = epoll_ctl(sep, EPOLL_CTL_ADD, me[t]->fd, &ev);
2718                 if (i == -1)
2719                 {
2720                         log(DEFAULT,"main: add server listen ports, epoll_ctl failed!");
2721                         printf("ERROR: could not initialise server listening sockets in epoll list. Shutting down.\n");
2722                         Exit(ERROR);
2723                 }
2724         }
2725 #else
2726 #ifdef USE_KQUEUE
2727         log(DEFAULT,"kqueue socket engine is enabled. Filling listen list.");
2728         for (count = 0; count < boundPortCount; count++)
2729         {
2730                 struct kevent ke;
2731                 log(DEBUG,"kqueue: Add listening socket to events, kq=%d socket=%d",lkq,openSockfd[count]);
2732                 EV_SET(&ke, openSockfd[count], EVFILT_READ, EV_ADD, 0, MaxConn, NULL);
2733                 int i = kevent(lkq, &ke, 1, 0, 0, NULL);
2734                 if (i == -1)
2735                 {
2736                         log(DEFAULT,"main: add listen ports to kqueue failed!");
2737                         printf("ERROR: could not initialise listening sockets in kqueue. Shutting down.\n");
2738                         Exit(ERROR);
2739                 }
2740         }
2741         for (int t = 0; t != SERVERportCount; t++)
2742         {
2743                 struct kevent ke;
2744                 if (me[t])
2745                 {
2746                         log(DEBUG,"kqueue: Add listening SERVER socket to events, kq=%d socket=%d",skq,me[t]->fd);
2747                         EV_SET(&ke, me[t]->fd, EVFILT_READ, EV_ADD, 0, MaxConn, NULL);
2748                         int i = kevent(skq, &ke, 1, 0, 0, NULL);
2749                         if (i == -1)
2750                         {
2751                                 log(DEFAULT,"main: add server listen ports to kqueue failed!");
2752                                 printf("ERROR: could not initialise listening server sockets in kqueue. Shutting down.\n");
2753                                 Exit(ERROR);
2754                         }
2755                 }
2756         }
2757
2758
2759 #else
2760         log(DEFAULT,"Using standard select socket engine.");
2761 #endif
2762 #endif
2763
2764         WritePID(PID);
2765
2766         length = sizeof (client);
2767         char tcp_msg[MAXBUF],tcp_host[MAXBUF],tcp_sum[MAXBUF];
2768
2769 #ifdef USE_KQUEUE
2770         struct kevent ke;
2771         struct kevent ke_list[33];
2772         struct timespec ts;
2773 #endif
2774 #ifdef USE_EPOLL
2775         struct epoll_event event[33];
2776 #endif
2777         fd_set serverfds;
2778         timeval tvs;
2779         tvs.tv_usec = 10000L;
2780         tvs.tv_sec = 0;
2781         tv.tv_sec = 0;
2782         tv.tv_usec = 10000L;
2783         char data[65536];
2784         timeval tval;
2785         fd_set sfd;
2786         tval.tv_usec = 10000L;
2787         tval.tv_sec = 0;
2788         int total_in_this_set = 0;
2789         int i = 0, v = 0, j = 0, cycle_iter = 0;
2790         bool expire_run = false;
2791           
2792         /* main loop, this never returns */
2793         for (;;)
2794         {
2795 #ifdef _POSIX_PRIORITY_SCHEDULING
2796                 sched_yield();
2797 #endif
2798 #ifdef USE_SELECT
2799                 FD_ZERO(&sfd);
2800 #endif
2801                 // we only read time() once per iteration rather than tons of times!
2802                 OLDTIME = TIME;
2803                 TIME = time(NULL);
2804
2805                 dns_poll();
2806
2807                 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
2808                 // them in a list, then reap the list every second or so.
2809                 if (((TIME % 5) == 0) && (!expire_run))
2810                 {
2811                         expire_lines();
2812                         FOREACH_MOD OnBackgroundTimer(TIME);
2813                         expire_run = true;
2814                         continue;
2815                 }
2816                 if ((TIME % 5) == 1)
2817                         expire_run = false;
2818                 
2819                 // fix by brain - this must be below any manipulation of the hashmap by modules
2820                 user_hash::iterator count2 = clientlist.begin();
2821
2822 #ifdef USE_EPOLL
2823                 i = epoll_wait(sep, event, 1, EP_DELAY);
2824                 if (i > 0)
2825                 {
2826                         log(DEBUG,"epoll: Listening server socket event, i=%d, event.data.fd=%d",i,event[0].data.fd);
2827                         for (int x = 0; x != SERVERportCount; x++)
2828                         {
2829                                 if ((me[x]) && (event[0].data.fd == me[x]->fd))
2830                                 {
2831 #endif
2832 #ifdef USE_KQUEUE
2833                 ts.tv_sec = 0;
2834                 ts.tv_nsec = 30000L;
2835                 i = kevent(skq, NULL, 0, &ke, 1, &ts);
2836                 if (i > 0)
2837                 {
2838                         log(DEBUG,"kqueue: Listening server socket event, i=%d, ke.ident=%d",i,ke.ident);
2839                         for (int x = 0; x != SERVERportCount; x++)
2840                         {
2841                                 if ((me[x]) && (ke.ident == me[x]->fd))
2842                                 {
2843
2844 #endif
2845 #ifdef USE_SELECT
2846                 FD_ZERO(&serverfds);
2847                 for (int x = 0; x != SERVERportCount; x++)
2848                 {
2849                         if (me[x])
2850                                 FD_SET(me[x]->fd, &serverfds);
2851                 }
2852                 tvs.tv_usec = 30000L;
2853                 tvs.tv_sec = 0;
2854                 int servresult = select(FD_SETSIZE, &serverfds, NULL, NULL, &tvs);
2855                 if (servresult > 0)
2856                 {
2857                         for (int x = 0; x != SERVERportCount; x++)
2858                         {
2859                                 if ((me[x]) && (FD_ISSET (me[x]->fd, &serverfds)))
2860                                 {
2861 #endif
2862                                         char remotehost[MAXBUF],resolved[MAXBUF];
2863                                         length = sizeof (client);
2864                                         incomingSockfd = accept (me[x]->fd, (sockaddr *) &client, &length);
2865                                         if (incomingSockfd != -1)
2866                                         {
2867                                                 strlcpy(remotehost,(char *)inet_ntoa(client.sin_addr),MAXBUF);
2868                                                 if(CleanAndResolve(resolved, remotehost) != TRUE)
2869                                                 {
2870                                                         strlcpy(resolved,remotehost,MAXBUF);
2871                                                 }
2872                                                 // add to this connections ircd_connector vector
2873                                                 // *FIX* - we need the LOCAL port not the remote port in &client!
2874                                                 me[x]->AddIncoming(incomingSockfd,resolved,me[x]->port);
2875                                         }
2876                                 }
2877                         }
2878                 }
2879      
2880                 std::deque<std::string> msgs;
2881                 std::deque<std::string> sums;
2882                 for (int x = 0; x < SERVERportCount; x++)
2883                 {
2884                         sums.clear();
2885                         msgs.clear();
2886                         while ((me[x]) && (me[x]->RecvPacket(msgs, tcp_host, sums))) // returns 0 or more lines (can be multiple lines!)
2887                         {
2888                                 for (int ctr = 0; ctr < msgs.size(); ctr++)
2889                                 {
2890                                         strlcpy(tcp_msg,msgs[ctr].c_str(),MAXBUF);
2891                                         strlcpy(tcp_sum,msgs[ctr].c_str(),MAXBUF);
2892                                         log(DEBUG,"Processing: %s",tcp_msg);
2893                                         if (!tcp_msg[0])
2894                                         {
2895                                                 log(DEBUG,"Invalid string from %s [route%lu]",tcp_host,(unsigned long)x);
2896                                                 break;
2897                                         }
2898                                         // during a netburst, send all data to all other linked servers
2899                                         if ((((nb_start>0) && (tcp_msg[0] != 'Y') && (tcp_msg[0] != 'X') && (tcp_msg[0] != 'F'))) || (is_uline(tcp_host)))
2900                                         {
2901                                                 if (is_uline(tcp_host))
2902                                                 {
2903                                                         if ((tcp_msg[0] != 'Y') && (tcp_msg[0] != 'X') && (tcp_msg[0] != 'F'))
2904                                                         {
2905                                                                 NetSendToAllExcept_WithSum(tcp_host,tcp_msg,tcp_sum);
2906                                                         }
2907                                                 }
2908                                                 else
2909                                                         NetSendToAllExcept_WithSum(tcp_host,tcp_msg,tcp_sum);
2910                                         }
2911                                         std::string msg = tcp_msg;
2912                                         FOREACH_MOD OnPacketReceive(msg,tcp_host);
2913                                         strlcpy(tcp_msg,msg.c_str(),MAXBUF);
2914                                         if (me[x])
2915                                                 handle_link_packet(tcp_msg, tcp_host, me[x], tcp_sum);
2916                                 }
2917                                         sums.clear();   // we're done, clear the list for the next operation
2918                                         msgs.clear();
2919                         }
2920                 }
2921         
2922         while (count2 != clientlist.end())
2923         {
2924 #ifdef USE_SELECT
2925                 FD_ZERO(&sfd);
2926 #endif
2927
2928                 total_in_this_set = 0;
2929
2930                 user_hash::iterator xcount = count2;
2931                 user_hash::iterator endingiter = count2;
2932
2933                 if (count2 == clientlist.end()) break;
2934
2935                 userrec* curr = NULL;
2936
2937                 if (count2->second)
2938                         curr = count2->second;
2939
2940                 if ((long)curr == -1)
2941                         goto label;
2942
2943                 if ((curr) && (curr->fd != 0))
2944                 {
2945 #ifdef _POSIX_PRIORITY_SCHEDULING
2946         sched_yield();
2947 #endif
2948                         // assemble up to 64 sockets into an fd_set
2949                         // to implement a pooling mechanism.
2950                         //
2951                         // This should be up to 64x faster than the
2952                         // old implementation.
2953 #ifdef USE_SELECT
2954                         while (total_in_this_set < 1024)
2955                         {
2956                                 if (count2 != clientlist.end())
2957                                 {
2958                                         curr = count2->second;
2959                                         if ((long)curr == -1)
2960                                                 goto label;
2961                                         int currfd = curr->fd;
2962                                         // we don't check the state of remote users.
2963                                         if ((currfd != -1) && (currfd != FD_MAGIC_NUMBER))
2964                                         {
2965                                                 curr->FlushWriteBuf();
2966                                                 if (curr->GetWriteError() != "")
2967                                                 {
2968                                                         log(DEBUG,"InspIRCd: write error: %s",curr->GetWriteError().c_str());
2969                                                         kill_link(curr,curr->GetWriteError().c_str());
2970                                                         goto label;
2971                                                 }
2972
2973                                                 FD_SET (curr->fd, &sfd);
2974
2975                                                 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
2976                                                 // their connection class.
2977                                                 if ((TIME > curr->timeout) && (curr->registered != 7)) 
2978                                                 {
2979                                                         log(DEBUG,"InspIRCd: registration timeout: %s",curr->nick);
2980                                                         kill_link(curr,"Registration timeout");
2981                                                         goto label;
2982                                                 }
2983                                                 if ((TIME > curr->signon) && (curr->registered == 3) && (AllModulesReportReady(curr)))
2984                                                 {
2985                                                         log(DEBUG,"signon exceed, registered=3, and modules ready, OK");
2986                                                         curr->dns_done = true;
2987                                                         statsDnsBad++;
2988                                                         FullConnectUser(curr);
2989                                                         if (fd_ref_table[currfd] != curr) // something changed, bail pronto
2990                                                                 goto label;                                                        
2991                                                 }
2992                                                 if ((curr->dns_done) && (curr->registered == 3) && (AllModulesReportReady(curr))) // both NICK and USER... and DNS
2993                                                 {
2994                                                         log(DEBUG,"dns done, registered=3, and modules ready, OK");
2995                                                         FullConnectUser(curr);
2996                                                         if (fd_ref_table[currfd] != curr) // something changed, bail pronto
2997                                                                 goto label;
2998                                                 }
2999                                                 if ((TIME > curr->nping) && (isnick(curr->nick)) && (curr->registered == 7))
3000                                                 {
3001                                                         if ((!curr->lastping) && (curr->registered == 7))
3002                                                         {
3003                                                                 log(DEBUG,"InspIRCd: ping timeout: %s",curr->nick);
3004                                                                 kill_link(curr,"Ping timeout");
3005                                                                 goto label;
3006                                                         }
3007                                                         Write(curr->fd,"PING :%s",ServerName);
3008                                                         log(DEBUG,"InspIRCd: pinging: %s",curr->nick);
3009                                                         curr->lastping = 0;
3010                                                         curr->nping = TIME+curr->pingmax;       // was hard coded to 120
3011                                                 }
3012                                         }
3013                                         count2++;
3014                                         total_in_this_set++;
3015                                 }
3016                                 else break;
3017                         }
3018                         endingiter = count2;
3019                         count2 = xcount; // roll back to where we were
3020 #else
3021                         // 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.
3022                         // TODO: We dont need to do all this EVERY loop iteration, tone down the visits to this if we're using kqueue.
3023                         cycle_iter++;
3024                         if (cycle_iter > 20) while (count2 != clientlist.end())
3025                         {
3026                                 cycle_iter = 0;
3027                                 if (count2 != clientlist.end())
3028                                 {
3029                                         curr = count2->second;
3030                                         if ((long)curr == -1)
3031                                                 goto label;
3032                                         int currfd = curr->fd;
3033                                         // we don't check the state of remote users.
3034                                         if ((currfd != -1) && (currfd != FD_MAGIC_NUMBER))
3035                                         {
3036
3037                                                 curr->FlushWriteBuf();
3038                                                 if (curr->GetWriteError() != "")
3039                                                 {
3040                                                         log(DEBUG,"InspIRCd: write error: %s",curr->GetWriteError().c_str());
3041                                                         kill_link(curr,curr->GetWriteError().c_str());
3042                                                         goto label;
3043                                                 }
3044
3045                                                 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
3046                                                 // their connection class.
3047                                                 if ((TIME > curr->timeout) && (curr->registered != 7))
3048                                                 {
3049                                                         log(DEBUG,"InspIRCd: registration timeout: %s",curr->nick);
3050                                                         kill_link(curr,"Registration timeout");
3051                                                         goto label;
3052
3053                                                 }
3054                                                 if ((TIME > curr->signon) && (curr->registered == 3) && (AllModulesReportReady(curr)))
3055                                                 {
3056                                                         log(DEBUG,"signon exceed, registered=3, and modules ready, OK: %d %d",TIME,curr->signon);
3057                                                         curr->dns_done = true;
3058                                                         statsDnsBad++;
3059                                                         FullConnectUser(curr);
3060                                                         if (fd_ref_table[currfd] != curr) // something changed, bail pronto
3061                                                                 goto label;
3062                                                 }
3063                                                 if ((curr->dns_done) && (curr->registered == 3) && (AllModulesReportReady(curr)))
3064                                                 {
3065                                                         log(DEBUG,"dns done, registered=3, and modules ready, OK");
3066                                                         FullConnectUser(curr);
3067                                                         if (fd_ref_table[currfd] != curr) // something changed, bail pronto
3068                                                                 goto label;
3069                                                 }
3070                                                 if ((TIME > curr->nping) && (isnick(curr->nick)) && (curr->registered == 7))
3071                                                 {
3072                                                         if ((!curr->lastping) && (curr->registered == 7))
3073                                                         {
3074                                                                 log(DEBUG,"InspIRCd: ping timeout: %s",curr->nick);
3075                                                                 kill_link(curr,"Ping timeout");
3076                                                                 goto label;
3077                                                         }
3078                                                         Write(curr->fd,"PING :%s",ServerName);
3079                                                         log(DEBUG,"InspIRCd: pinging: %s",curr->nick);
3080                                                         curr->lastping = 0;
3081                                                         curr->nping = TIME+curr->pingmax;       // was hard coded to 120
3082                                                 }
3083                                         }
3084                                 }
3085                                 else break;
3086                                 count2++;
3087                         }
3088                         // increment the counter right to the end of the list, as kqueue processes everything in one go
3089 #endif
3090         
3091                         v = 0;
3092 #ifdef USE_EPOLL
3093                         int i = epoll_wait(ep, event, 1, 5);
3094                         if (i > 0)
3095                         {
3096                                 log(DEBUG,"epoll_wait call: ep=%d, i=%d",ep,i);
3097                                 // EPOLL: we asked epoll_wait for ONE fd which is ready. Do something.
3098                                 userrec* cu = fd_ref_table[event[0].data.fd];
3099 #endif
3100 #ifdef USE_KQUEUE
3101                         ts.tv_sec = 0;
3102                         ts.tv_nsec = 1000L;
3103                         // for now, we only read 1 event. We could read soooo many more :)
3104                         int i = kevent(kq, NULL, 0, &ke, 1, &ts);
3105                         if (i > 0)
3106                         {
3107                                 log(DEBUG,"kevent call: kq=%d, i=%d",kq,i);
3108                                 // KQUEUE: kevent gives us ONE fd which is ready to have something done to it. Do something to it.
3109                                 userrec* cu = fd_ref_table[ke.ident];
3110 #endif
3111 #ifdef USE_SELECT
3112                         tval.tv_sec = 0;
3113                         tval.tv_usec = 1000L;
3114                         selectResult2 = select(FD_SETSIZE, &sfd, NULL, NULL, &tval);
3115                         // now loop through all of the items in this pool if any are waiting
3116                         if ((selectResult2 > 0) && (xcount != clientlist.end()))
3117                         for (user_hash::iterator count2a = xcount; count2a != endingiter; count2a++)
3118                         {
3119                                 // SELECT: we have to iterate...
3120                                 if (count2a == clientlist.end())
3121                                         break;
3122                                 userrec* cu = count2a->second;
3123 #endif
3124
3125 #ifdef _POSIX_PRIORITY_SCHEDULING
3126                                 sched_yield();
3127 #endif
3128                                 result = EAGAIN;
3129 #ifdef USE_EPOLL
3130                                 // EPOLL: We already know we have a valid FD. No checks needed.
3131                                 if ((cu->fd != FD_MAGIC_NUMBER) && (cu->fd != -1))
3132 #endif
3133 #ifdef USE_KQUEUE
3134                                 // KQUEUE: We already know we have a valid FD. No checks needed.
3135                                 if ((cu->fd != FD_MAGIC_NUMBER) && (cu->fd != -1))
3136 #endif
3137 #ifdef USE_SELECT
3138                                 // SELECT: We don't know if our FD is valid.
3139                                 if ((cu->fd != FD_MAGIC_NUMBER) && (cu->fd != -1) && (FD_ISSET (cu->fd, &sfd)))
3140 #endif
3141                                 {
3142                                         log(DEBUG,"Data waiting on socket %d",cu->fd);
3143                                         int MOD_RESULT = 0;
3144                                         int result2 = 0;
3145                                         FOREACH_RESULT(OnRawSocketRead(cu->fd,data,65535,result2));
3146                                         if (!MOD_RESULT)
3147                                         {
3148                                                 result = read(cu->fd, data, 65535);
3149                                         }
3150                                         else result = result2;
3151                                         log(DEBUG,"Read result: %d",result);
3152                                         if (result)
3153                                         {
3154                                                 statsRecv += result;
3155                                                 // perform a check on the raw buffer as an array (not a string!) to remove
3156                                                 // characters 0 and 7 which are illegal in the RFC - replace them with spaces.
3157                                                 // hopefully this should stop even more people whining about "Unknown command: *"
3158                                                 for (int checker = 0; checker < result; checker++)
3159                                                 {
3160                                                         if ((data[checker] == 0) || (data[checker] == 7))
3161                                                                 data[checker] = ' ';
3162                                                 }
3163                                                 if (result > 0)
3164                                                         data[result] = '\0';
3165                                                 userrec* current = cu;
3166                                                 int currfd = current->fd;
3167                                                 int floodlines = 0;
3168                                                 // add the data to the users buffer
3169                                                 if (result > 0)
3170                                                 if (!current->AddBuffer(data))
3171                                                 {
3172                                                         // AddBuffer returned false, theres too much data in the user's buffer and theyre up to no good.
3173                                                         if (current->registered == 7)
3174                                                         {
3175                                                                 kill_link(current,"RecvQ exceeded");
3176                                                         }
3177                                                         else
3178                                                         {
3179                                                                 WriteOpers("*** Excess flood from %s",current->ip);
3180                                                                 log(DEFAULT,"Excess flood from: %s",current->ip);
3181                                                                 add_zline(120,ServerName,"Flood from unregistered connection",current->ip);
3182                                                                 apply_lines();
3183                                                         }
3184                                                         goto label;
3185                                                 }
3186                                                 if (current->recvq.length() > NetBufferSize)
3187                                                 {
3188                                                         if (current->registered == 7)
3189                                                         {
3190                                                                 kill_link(current,"RecvQ exceeded");
3191                                                         }
3192                                                         else
3193                                                         {
3194                                                                 WriteOpers("*** Excess flood from %s",current->ip);
3195                                                                 log(DEFAULT,"Excess flood from: %s",current->ip);
3196                                                                 add_zline(120,ServerName,"Flood from unregistered connection",current->ip);
3197                                                                 apply_lines();
3198                                                         }
3199                                                         goto label;
3200                                                 }
3201                                                 // while there are complete lines to process...
3202                                                 while (current->BufferIsReady())
3203                                                 {
3204                                                         floodlines++;
3205                                                         if (TIME > current->reset_due)
3206                                                         {
3207                                                                 current->reset_due = TIME + current->threshold;
3208                                                                 current->lines_in = 0;
3209                                                         }
3210                                                         current->lines_in++;
3211                                                         if (current->lines_in > current->flood)
3212                                                         {
3213                                                                 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3214                                                                 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3215                                                                 kill_link(current,"Excess flood");
3216                                                                 goto label;
3217                                                         }
3218                                                         if ((floodlines > current->flood) && (current->flood != 0))
3219                                                         {
3220                                                                 if (current->registered == 7)
3221                                                                 {
3222                                                                         log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3223                                                                         WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3224                                                                         kill_link(current,"Excess flood");
3225                                                                 }
3226                                                                 else
3227                                                                 {
3228                                                                         add_zline(120,ServerName,"Flood from unregistered connection",current->ip);
3229                                                                         apply_lines();
3230                                                                 }
3231                                                                 goto label;
3232                                                         }
3233                                                         char sanitized[MAXBUF];
3234                                                         // use GetBuffer to copy single lines into the sanitized string
3235                                                         std::string single_line = current->GetBuffer();
3236                                                         current->bytes_in += single_line.length();
3237                                                         current->cmds_in++;
3238                                                         if (single_line.length()>512)
3239                                                         {
3240                                                                 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3241                                                                 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3242                                                                 kill_link(current,"Excess flood");
3243                                                                 goto label;
3244                                                         }
3245                                                         strlcpy(sanitized,single_line.c_str(),MAXBUF);
3246                                                         if (*sanitized)
3247                                                         {
3248                                                                 userrec* old_comp = fd_ref_table[currfd];
3249                                                                 // we're gonna re-scan to check if the nick is gone, after every
3250                                                                 // command - if it has, we're gonna bail
3251                                                                 process_buffer(sanitized,current);
3252                                                                 // look for the user's record in case it's changed... if theyve quit,
3253                                                                 // we cant do anything more with their buffer, so bail.
3254                                                                 // there used to be an ugly, slow loop here. Now we have a reference
3255                                                                 // table, life is much easier (and FASTER)
3256                                                                 userrec* new_comp = fd_ref_table[currfd];
3257                                                                 if ((currfd < 0) || (!fd_ref_table[currfd]) || (old_comp != new_comp))
3258                                                                         goto label;
3259
3260                                                         }
3261                                                 }
3262                                                 goto label;
3263                                         }
3264
3265                                         if ((result == -1) && (errno != EAGAIN) && (errno != EINTR))
3266                                         {
3267                                                 log(DEBUG,"killing: %s",cu->nick);
3268                                                 kill_link(cu,strerror(errno));
3269                                                 goto label;
3270                                         }
3271                                 }
3272                                 // result EAGAIN means nothing read
3273                                 if (result == EAGAIN)
3274                                 {
3275                                 }
3276                                 else
3277                                 if (result == 0)
3278                                 {
3279 #ifdef USE_SELECT
3280                                         if (count2->second)
3281                                         {
3282 #endif
3283                                                 log(DEBUG,"InspIRCd: Exited: %s",cu->nick);
3284                                                 kill_link(cu,"Client exited");
3285                                                 // must bail here? kill_link removes the hash, corrupting the iterator
3286                                                 log(DEBUG,"Bailing from client exit");
3287                                                 goto label;
3288 #ifdef USE_SELECT
3289                                         }
3290 #endif
3291                                 }
3292                                 else if (result > 0)
3293                                 {
3294                                 }
3295                         }
3296                 }
3297                 for (int q = 0; q < total_in_this_set; q++)
3298                 {
3299                         count2++;
3300                 }
3301         }
3302
3303 #ifdef _POSIX_PRIORITY_SCHEDULING
3304         sched_yield();
3305 #endif
3306         
3307 #ifdef USE_SELECT
3308         // set up select call
3309         for (count = 0; count < boundPortCount; count++)
3310         {
3311                 FD_SET (openSockfd[count], &selectFds);
3312         }
3313
3314         tv.tv_usec = 30000L;
3315         selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
3316
3317         /* select is reporting a waiting socket. Poll them all to find out which */
3318         if (selectResult > 0)
3319         {
3320                 for (count = 0; count < boundPortCount; count++)
3321                 {
3322                         if (FD_ISSET (openSockfd[count], &selectFds))
3323                         {
3324 #endif
3325 #ifdef USE_KQUEUE
3326         ts.tv_sec = 0;
3327         ts.tv_nsec = 30000L;
3328         i = kevent(lkq, NULL, 0, ke_list, 32, &ts);
3329         if (i > 0) for (j = 0; j < i; j++)
3330         {
3331                 log(DEBUG,"kqueue: Listening socket event, i=%d, ke.ident=%d",i,ke_list[j].ident);
3332                 // this isnt as efficient as it could be, we could create a reference table
3333                 // to reference bound ports by fd, but this isnt a big bottleneck as the actual
3334                 // number of listening ports on the average ircd is a small number (less than 20)
3335                 // compared to the number of clients (possibly over 2000)
3336                 for (count = 0; count < boundPortCount; count++)
3337                 {
3338                         if (ke_list[j].ident == openSockfd[count])
3339                         {
3340 #endif
3341 #ifdef USE_EPOLL
3342         i = epoll_wait(lep, event, 32, EP_DELAY);
3343         if (i > 0) for (j = 0; j < i; j++)
3344         {
3345                 log(DEBUG,"epoll: Listening socket event, i=%d,events[j].data.fd=%d",i,event[j].data.fd);
3346                 for (count = 0; count < boundPortCount; count++)
3347                 {
3348                         if (event[j].data.fd == openSockfd[count])
3349                         {
3350 #endif
3351                                 char target[MAXBUF], resolved[MAXBUF];
3352                                 length = sizeof (client);
3353                                 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
3354                               
3355                                 strlcpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
3356                                 strlcpy (resolved, target, MAXBUF);
3357                         
3358                                 if (incomingSockfd < 0)
3359                                 {
3360                                         WriteOpers("*** WARNING: Accept failed on port %lu (%s)",(unsigned long)ports[count],target);
3361                                         log(DEBUG,"InspIRCd: accept failed: %lu",(unsigned long)ports[count]);
3362                                         statsRefused++;
3363                                 }
3364                                 else
3365                                 {
3366                                         FOREACH_MOD OnRawSocketAccept(incomingSockfd, resolved, ports[count]);
3367                                         statsAccept++;
3368                                         AddClient(incomingSockfd, resolved, ports[count], false, inet_ntoa (client.sin_addr));
3369                                         log(DEBUG,"InspIRCd: adding client on port %lu fd=%lu",(unsigned long)ports[count],(unsigned long)incomingSockfd);
3370                                 }
3371                         }
3372                 }
3373         }
3374         label:
3375         if (0) {};
3376 #ifdef _POSIX_PRIORITY_SCHEDULING
3377         sched_yield();
3378         sched_yield();
3379 #endif
3380 }
3381 /* not reached */
3382 close (incomingSockfd);
3383 }
3384