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