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