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