]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd.cpp
Fixed max channel length
[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)
520         {
521                 cname[CHANMAX] = '\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                                                 std::stringstream dcmds(DisabledCommands);
2046                                                 while (!dcmds.eof())
2047                                                 {
2048                                                         std::string thiscmd;
2049                                                         dcmds >> thiscmd;
2050                                                         if (!strcasecmp(thiscmd.c_str(),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                                                 }
2057                                         }
2058                                         if ((user->registered == 7) || (!strncmp(command,"USER",4)) || (!strncmp(command,"NICK",4)) || (!strncmp(command,"PASS",4)))
2059                                         {
2060                                                 if (cmdlist[i].handler_function)
2061                                                 {
2062                                                         
2063                                                         /* ikky /stats counters */
2064                                                         if (temp)
2065                                                         {
2066                                                                 cmdlist[i].use_count++;
2067                                                                 cmdlist[i].total_bytes+=strlen(temp);
2068                                                         }
2069
2070                                                         int MOD_RESULT = 0;
2071                                                         FOREACH_RESULT(OnPreCommand(command,command_p,items,user));
2072                                                         if (MOD_RESULT == 1) {
2073                                                                 return;
2074                                                         }
2075
2076                                                         /* WARNING: nothing may come after the
2077                                                          * command handler call, as the handler
2078                                                          * may free the user structure! */
2079
2080                                                         cmdlist[i].handler_function(command_p,items,user);
2081                                                 }
2082                                                 return;
2083                                         }
2084                                         else
2085                                         {
2086                                                 WriteServ(user->fd,"451 %s :You have not registered",command);
2087                                                 return;
2088                                         }
2089                                 }
2090                                 cmd_found = 1;
2091                         }
2092                 }
2093         }
2094         if ((!cmd_found) && (user))
2095         {
2096                 statsUnknown++;
2097                 WriteServ(user->fd,"421 %s %s :Unknown command",user->nick,command);
2098         }
2099 }
2100
2101 bool removecommands(const char* source)
2102 {
2103         bool go_again = true;
2104         while (go_again)
2105         {
2106                 go_again = false;
2107                 for (std::deque<command_t>::iterator i = cmdlist.begin(); i != cmdlist.end(); i++)
2108                 {
2109                         if (!strcmp(i->source,source))
2110                         {
2111                                 log(DEBUG,"removecommands(%s) Removing dependent command: %s",i->source,i->command);
2112                                 cmdlist.erase(i);
2113                                 go_again = true;
2114                                 break;
2115                         }
2116                 }
2117         }
2118         return true;
2119 }
2120
2121
2122 void process_buffer(const char* cmdbuf,userrec *user)
2123 {
2124         if (!user)
2125         {
2126                 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2127                 return;
2128         }
2129         char cmd[MAXBUF];
2130         if (!cmdbuf)
2131         {
2132                 log(DEFAULT,"*** BUG *** process_buffer was given an invalid parameter");
2133                 return;
2134         }
2135         if (!cmdbuf[0])
2136         {
2137                 return;
2138         }
2139         while (*cmdbuf == ' ') cmdbuf++; // strip leading spaces
2140
2141         strlcpy(cmd,cmdbuf,MAXBUF);
2142         if (!cmd[0])
2143         {
2144                 return;
2145         }
2146         int sl = strlen(cmd)-1;
2147         if ((cmd[sl] == 13) || (cmd[sl] == 10))
2148         {
2149                 cmd[sl] = '\0';
2150         }
2151         sl = strlen(cmd)-1;
2152         if ((cmd[sl] == 13) || (cmd[sl] == 10))
2153         {
2154                 cmd[sl] = '\0';
2155         }
2156         sl = strlen(cmd)-1;
2157         while (cmd[sl] == ' ') // strip trailing spaces
2158         {
2159                 cmd[sl] = '\0';
2160                 sl = strlen(cmd)-1;
2161         }
2162
2163         if (!cmd[0])
2164         {
2165                 return;
2166         }
2167         log(DEBUG,"CMDIN: %s %s",user->nick,cmd);
2168         tidystring(cmd);
2169         if ((user) && (cmd))
2170         {
2171                 process_command(user,cmd);
2172         }
2173 }
2174
2175 void DoSync(serverrec* serv, char* tcp_host)
2176 {
2177         char data[MAXBUF];
2178         log(DEBUG,"Sending sync");
2179         // send start of sync marker: Y <timestamp>
2180         // at this point the ircd receiving it starts broadcasting this netburst to all ircds
2181         // except the ones its receiving it from.
2182         snprintf(data,MAXBUF,"%s Y %lu",CreateSum().c_str(),(unsigned long)TIME);
2183         serv->SendPacket(data,tcp_host);
2184         // send users and channels
2185
2186         NetSendMyRoutingTable();
2187
2188         // send all routing table and uline voodoo. The ordering of these commands is IMPORTANT!
2189         for (int j = 0; j < 32; j++)
2190         {
2191                 if (me[j] != NULL)
2192                 {
2193                         for (int k = 0; k < me[j]->connectors.size(); k++)
2194                         {
2195                                 if (is_uline(me[j]->connectors[k].GetServerName().c_str()))
2196                                 {
2197                                         snprintf(data,MAXBUF,"%s H %s",CreateSum().c_str(),me[j]->connectors[k].GetServerName().c_str());
2198                                         serv->SendPacket(data,tcp_host);
2199                                 }
2200                         }
2201                 }
2202         }
2203
2204         // send our version for the remote side to cache
2205         snprintf(data,MAXBUF,"%s v %s %s",CreateSum().c_str(),ServerName,GetVersionString().c_str());
2206         serv->SendPacket(data,tcp_host);
2207
2208         // sync the users and channels, give the modules a look-in.
2209         for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
2210         {
2211                 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);
2212                 serv->SendPacket(data,tcp_host);
2213                 if (strchr(u->second->modes,'o'))
2214                 {
2215                         snprintf(data,MAXBUF,"%s | %s %s",CreateSum().c_str(),u->second->nick,u->second->oper);
2216                         serv->SendPacket(data,tcp_host);
2217                 }
2218                 for (int i = 0; i <= MODCOUNT; i++)
2219                 {
2220                         string_list l = modules[i]->OnUserSync(u->second);
2221                         for (int j = 0; j < l.size(); j++)
2222                         {
2223                                 snprintf(data,MAXBUF,"%s %s",CreateSum().c_str(),l[j].c_str());
2224                                 serv->SendPacket(data,tcp_host);
2225                         }
2226                 }
2227                 char* chl = chlist(u->second,u->second);
2228                 if (strcmp(chl,""))
2229                 {
2230                         snprintf(data,MAXBUF,"%s J %s %s",CreateSum().c_str(),u->second->nick,chl);
2231                         serv->SendPacket(data,tcp_host);
2232                 }
2233         }
2234         // send channel modes, topics etc...
2235         for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
2236         {
2237                 snprintf(data,MAXBUF,"M %s +%s",c->second->name,chanmodes(c->second));
2238                 serv->SendPacket(data,tcp_host);
2239                 for (int i = 0; i <= MODCOUNT; i++)
2240                 {
2241                         string_list l = modules[i]->OnChannelSync(c->second);
2242                         for (int j = 0; j < l.size(); j++)
2243                         {
2244                                 snprintf(data,MAXBUF,"%s %s",CreateSum().c_str(),l[j].c_str());
2245                                 serv->SendPacket(data,tcp_host);
2246                         }
2247                 }
2248                 if (c->second->topic[0])
2249                 {
2250                         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);
2251                         serv->SendPacket(data,tcp_host);
2252                 }
2253                 // send current banlist
2254                 
2255                 for (BanList::iterator b = c->second->bans.begin(); b != c->second->bans.end(); b++)
2256                 {
2257                         snprintf(data,MAXBUF,"%s M %s +b %s",CreateSum().c_str(),c->second->name,b->data);
2258                         serv->SendPacket(data,tcp_host);
2259                 }
2260         }
2261         // sync global zlines, glines, etc
2262         sync_xlines(serv,tcp_host);
2263
2264         snprintf(data,MAXBUF,"%s F %lu",CreateSum().c_str(),(unsigned long)TIME);
2265         serv->SendPacket(data,tcp_host);
2266         log(DEBUG,"Sent sync");
2267         // ircd sends its serverlist after the end of sync here
2268 }
2269
2270
2271 void NetSendMyRoutingTable()
2272 {
2273         // send out a line saying what is reachable to us.
2274         // E.g. if A is linked to B C and D, send out:
2275         // $ A B C D
2276         // if its only linked to B and D send out:
2277         // $ A B D
2278         // if it has no links, dont even send out the line at all.
2279         char buffer[MAXBUF];
2280         snprintf(buffer,MAXBUF,"$ %s",ServerName);
2281         bool sendit = false;
2282         for (int i = 0; i < 32; i++)
2283         {
2284                 if (me[i] != NULL)
2285                 {
2286                         for (int j = 0; j < me[i]->connectors.size(); j++)
2287                         {
2288                                 if ((me[i]->connectors[j].GetState() != STATE_DISCONNECTED) || (is_uline(me[i]->connectors[j].GetServerName().c_str())))
2289                                 {
2290                                         strlcat(buffer," ",MAXBUF);
2291                                         strlcat(buffer,me[i]->connectors[j].GetServerName().c_str(),MAXBUF);
2292                                         sendit = true;
2293                                 }
2294                         }
2295                 }
2296         }
2297         if (sendit)
2298                 NetSendToAll(buffer);
2299 }
2300
2301
2302 void DoSplit(const char* params)
2303 {
2304         bool go_again = true;
2305         while (go_again)
2306         {
2307                 go_again = false;
2308                 for (int i = 0; i < 32; i++)
2309                 {
2310                         if (me[i] != NULL)
2311                         {
2312                                 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2313                                 {
2314                                         if (!strcasecmp(j->GetServerName().c_str(),params))
2315                                         {
2316                                                 j->routes.clear();
2317                                                 j->CloseConnection();
2318                                                 me[i]->connectors.erase(j);
2319                                                 go_again = true;
2320                                                 break;
2321                                         }
2322                                 }
2323                         }
2324                 }
2325         }
2326         log(DEBUG,"Removed server. Will remove clients...");
2327         // iterate through the userlist and remove all users on this server.
2328         // because we're dealing with a mesh, we dont have to deal with anything
2329         // "down-route" from this server (nice huh)
2330         go_again = true;
2331         char reason[MAXBUF];
2332         snprintf(reason,MAXBUF,"%s %s",ServerName,params);
2333         while (go_again)
2334         {
2335                 go_again = false;
2336                 for (user_hash::const_iterator u = clientlist.begin(); u != clientlist.end(); u++)
2337                 {
2338                         if (!strcasecmp(u->second->server,params))
2339                         {
2340                                 kill_link(u->second,reason);
2341                                 go_again = true;
2342                                 break;
2343                         }
2344                 }
2345         }
2346         has_been_netsplit = true;
2347 }
2348
2349 // removes a server. Will NOT remove its users!
2350
2351 void RemoveServer(const char* name)
2352 {
2353         bool go_again = true;
2354         while (go_again)
2355         {
2356                 go_again = false;
2357                 for (int i = 0; i < 32; i++)
2358                 {
2359                         if (me[i] != NULL)
2360                         {
2361                                 for (vector<ircd_connector>::iterator j = me[i]->connectors.begin(); j != me[i]->connectors.end(); j++)
2362                                 {
2363                                         if (!strcasecmp(j->GetServerName().c_str(),name))
2364                                         {
2365                                                 j->routes.clear();
2366                                                 j->CloseConnection();
2367                                                 me[i]->connectors.erase(j);
2368                                                 go_again = true;
2369                                                 break;
2370                                         }
2371                                 }
2372                         }
2373                 }
2374         }
2375 }
2376
2377
2378 char MODERR[MAXBUF];
2379
2380 char* ModuleError()
2381 {
2382         return MODERR;
2383 }
2384
2385 void erase_factory(int j)
2386 {
2387         int v = 0;
2388         for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
2389         {
2390                 if (v == j)
2391                 {
2392                         factory.erase(t);
2393                         factory.push_back(NULL);
2394                         return;
2395                 }
2396                 v++;
2397         }
2398 }
2399
2400 void erase_module(int j)
2401 {
2402         int v1 = 0;
2403         for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
2404         {
2405                 if (v1 == j)
2406                 {
2407                         delete *m;
2408                         modules.erase(m);
2409                         modules.push_back(NULL);
2410                         break;
2411                 }
2412                 v1++;
2413         }
2414         int v2 = 0;
2415         for (std::vector<std::string>::iterator v = module_names.begin(); v != module_names.end(); v++)
2416         {
2417                 if (v2 == j)
2418                 {
2419                        module_names.erase(v);
2420                        break;
2421                 }
2422                 v2++;
2423         }
2424
2425 }
2426
2427 bool UnloadModule(const char* filename)
2428 {
2429         std::string filename_str = filename;
2430         for (int j = 0; j != module_names.size(); j++)
2431         {
2432                 if (module_names[j] == filename_str)
2433                 {
2434                         if (modules[j]->GetVersion().Flags & VF_STATIC)
2435                         {
2436                                 log(DEFAULT,"Failed to unload STATIC module %s",filename);
2437                                 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
2438                                 return false;
2439                         }
2440                         // found the module
2441                         log(DEBUG,"Deleting module...");
2442                         erase_module(j);
2443                         log(DEBUG,"Erasing module entry...");
2444                         erase_factory(j);
2445                         log(DEBUG,"Removing dependent commands...");
2446                         removecommands(filename);
2447                         log(DEFAULT,"Module %s unloaded",filename);
2448                         MODCOUNT--;
2449                         return true;
2450                 }
2451         }
2452         log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
2453         snprintf(MODERR,MAXBUF,"Module not loaded");
2454         return false;
2455 }
2456
2457 bool LoadModule(const char* filename)
2458 {
2459         char modfile[MAXBUF];
2460 #ifdef STATIC_LINK
2461         snprintf(modfile,MAXBUF,"%s",filename);
2462 #else
2463         snprintf(modfile,MAXBUF,"%s/%s",ModPath,filename);
2464 #endif
2465         std::string filename_str = filename;
2466 #ifndef STATIC_LINK
2467         if (!DirValid(modfile))
2468         {
2469                 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
2470                 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
2471                 return false;
2472         }
2473 #endif
2474         log(DEBUG,"Loading module: %s",modfile);
2475 #ifndef STATIC_LINK
2476         if (FileExists(modfile))
2477         {
2478 #endif
2479                 for (int j = 0; j < module_names.size(); j++)
2480                 {
2481                         if (module_names[j] == filename_str)
2482                         {
2483                                 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
2484                                 snprintf(MODERR,MAXBUF,"Module already loaded");
2485                                 return false;
2486                         }
2487                 }
2488                 ircd_module* a = new ircd_module(modfile);
2489                 factory[MODCOUNT+1] = a;
2490                 if (factory[MODCOUNT+1]->LastError())
2491                 {
2492                         log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
2493                         snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
2494                         MODCOUNT--;
2495                         return false;
2496                 }
2497                 if (factory[MODCOUNT+1]->factory)
2498                 {
2499                         Module* m = factory[MODCOUNT+1]->factory->CreateModule();
2500                         modules[MODCOUNT+1] = m;
2501                         /* save the module and the module's classfactory, if
2502                          * this isnt done, random crashes can occur :/ */
2503                         module_names.push_back(filename);
2504                 }
2505                 else
2506                 {
2507                         log(DEFAULT,"Unable to load %s",modfile);
2508                         snprintf(MODERR,MAXBUF,"Factory function failed!");
2509                         return false;
2510                 }
2511 #ifndef STATIC_LINK
2512         }
2513         else
2514         {
2515                 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
2516                 snprintf(MODERR,MAXBUF,"Module file could not be found");
2517                 return false;
2518         }
2519 #endif
2520         MODCOUNT++;
2521         return true;
2522 }
2523
2524
2525 bool GotServer(std::string name)
2526 {
2527         for (int j = 0; j < 32; j++)
2528         {
2529                 if (me[j] != NULL)
2530                 {
2531                         for (int k = 0; k < me[j]->connectors.size(); k++)
2532                         {
2533                                 if (name == me[j]->connectors[k].GetServerName())
2534                                 {
2535                                         return true;
2536                                 }
2537                         }
2538                 }
2539         }
2540         return false;
2541 }
2542
2543
2544 int InspIRCd(char** argv, int argc)
2545 {
2546         struct sockaddr_in client,server;
2547         char addrs[MAXBUF][255];
2548         int incomingSockfd, result = TRUE;
2549         socklen_t length;
2550         int count = 0;
2551         int selectResult = 0, selectResult2 = 0;
2552         char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
2553         fd_set selectFds;
2554         timeval tv;
2555
2556         std::string logpath = GetFullProgDir(argv,argc) + "/ircd.log";
2557         log_file = fopen(logpath.c_str(),"a+");
2558         if (!log_file)
2559         {
2560                 printf("ERROR: Could not write to logfile %s, bailing!\n\n",logpath.c_str());
2561                 Exit(ERROR);
2562         }
2563
2564 #ifdef IS_CYGWIN
2565         printf("Logging to ircd.log...\n");
2566 #else
2567         printf("Logging to %s...\n",logpath.c_str());
2568 #endif
2569
2570         log(DEFAULT,"$Id$");
2571         if (geteuid() == 0)
2572         {
2573                 printf("WARNING!!! You are running an irc server as ROOT!!! DO NOT DO THIS!!!\n\n");
2574                 Exit(ERROR);
2575                 log(DEFAULT,"InspIRCd: startup: not starting with UID 0!");
2576         }
2577         SetupCommandTable();
2578         log(DEBUG,"InspIRCd: startup: default command table set up");
2579         
2580         ReadConfig(true,NULL);
2581         if (DieValue[0])
2582         { 
2583                 printf("WARNING: %s\n\n",DieValue);
2584                 log(DEFAULT,"Ut-Oh, somebody didn't read their config file: '%s'",DieValue);
2585                 exit(0); 
2586         }  
2587         log(DEBUG,"InspIRCd: startup: read config");
2588
2589         int clientportcount = 0, serverportcount = 0;
2590
2591         for (count = 0; count < ConfValueEnum("bind",&config_f); count++)
2592         {
2593                 ConfValue("bind","port",count,configToken,&config_f);
2594                 ConfValue("bind","address",count,Addr,&config_f);
2595                 ConfValue("bind","type",count,Type,&config_f);
2596                 if (!strcmp(Type,"servers"))
2597                 {
2598                         char Default[MAXBUF];
2599                         strcpy(Default,"no");
2600                         ConfValue("bind","default",count,Default,&config_f);
2601                         if (strchr(Default,'y'))
2602                         {
2603                                 defaultRoute = serverportcount;
2604                                 log(DEBUG,"InspIRCd: startup: binding '%s:%s' is default server route",Addr,configToken);
2605                         }
2606                         me[serverportcount] = new serverrec(ServerName,100L,false);
2607                         if (!me[serverportcount]->CreateListener(Addr,atoi(configToken)))
2608                         {
2609                                 log(DEFAULT,"Warning: Failed to bind port %lu",(unsigned long)atoi(configToken));
2610                                 printf("Warning: Failed to bind port %lu\n",(unsigned long)atoi(configToken));
2611                         }
2612                         else
2613                         {
2614                                 serverportcount++;
2615                         }
2616                 }
2617                 else
2618                 {
2619                         ports[clientportcount] = atoi(configToken);
2620                         strlcpy(addrs[clientportcount],Addr,256);
2621                         clientportcount++;
2622                 }
2623                 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
2624         }
2625         portCount = clientportcount;
2626         SERVERportCount = serverportcount;
2627           
2628         log(DEBUG,"InspIRCd: startup: read %lu total client ports and %lu total server ports",(unsigned long)portCount,(unsigned long)SERVERportCount);
2629         log(DEBUG,"InspIRCd: startup: InspIRCd is now starting!");
2630         
2631         printf("\n");
2632         
2633         /* BugFix By Craig! :p */
2634         MODCOUNT = -1;
2635         for (count = 0; count < ConfValueEnum("module",&config_f); count++)
2636         {
2637                 ConfValue("module","name",count,configToken,&config_f);
2638                 printf("Loading module... \033[1;32m%s\033[0m\n",configToken);
2639                 if (!LoadModule(configToken))
2640                 {
2641                         log(DEFAULT,"Exiting due to a module loader error.");
2642                         printf("\nThere was an error loading a module: %s\n\nYou might want to do './inspircd start' instead of 'bin/inspircd'\n\n",ModuleError());
2643                         Exit(0);
2644                 }
2645         }
2646         log(DEFAULT,"Total loaded modules: %lu",(unsigned long)MODCOUNT+1);
2647         
2648         startup_time = time(NULL);
2649           
2650         char PID[MAXBUF];
2651         ConfValue("pid","file",0,PID,&config_f);
2652         // write once here, to try it out and make sure its ok
2653         WritePID(PID);
2654           
2655         /* setup select call */
2656 #ifndef USE_KQUEUE
2657         FD_ZERO(&selectFds);
2658 #endif
2659         log(DEBUG,"InspIRCd: startup: zero selects");
2660         log(VERBOSE,"InspIRCd: startup: portCount = %lu", (unsigned long)portCount);
2661         
2662         for (count = 0; count < portCount; count++)
2663         {
2664                 if ((openSockfd[boundPortCount] = OpenTCPSocket()) == ERROR)
2665                 {
2666                         log(DEBUG,"InspIRCd: startup: bad fd %lu",(unsigned long)openSockfd[boundPortCount]);
2667                         return(ERROR);
2668                 }
2669                 if (BindSocket(openSockfd[boundPortCount],client,server,ports[count],addrs[count]) == ERROR)
2670                 {
2671                         log(DEFAULT,"InspIRCd: startup: failed to bind port %lu",(unsigned long)ports[count]);
2672                 }
2673                 else    /* well we at least bound to one socket so we'll continue */
2674                 {
2675                         boundPortCount++;
2676                 }
2677         }
2678         
2679         log(DEBUG,"InspIRCd: startup: total bound ports %lu",(unsigned long)boundPortCount);
2680           
2681         /* if we didn't bind to anything then abort */
2682         if (boundPortCount == 0)
2683         {
2684                 log(DEFAULT,"InspIRCd: startup: no ports bound, bailing!");
2685                 printf("\nERROR: Was not able to bind any of %lu ports! Please check your configuration.\n\n", (unsigned long)portCount);
2686                 return (ERROR);
2687         }
2688         
2689
2690         printf("\nInspIRCd is now running!\n");
2691
2692         if (nofork)
2693         {
2694                 log(VERBOSE,"Not forking as -nofork was specified");
2695         }
2696         else
2697         {
2698                 if (DaemonSeed() == ERROR)
2699                 {
2700                         log(DEFAULT,"InspIRCd: startup: can't daemonise");
2701                         printf("ERROR: could not go into daemon mode. Shutting down.\n");
2702                         Exit(ERROR);
2703                 }
2704         }
2705
2706         // BUGFIX: We cannot initialize this before forking, as the kqueue data is not inherited by child processes!
2707 #ifdef USE_KQUEUE
2708         kq = kqueue();
2709         lkq = kqueue();
2710         skq = kqueue();
2711         if ((kq == -1) || (lkq == -1) || (skq == -1))
2712         {
2713                 log(DEFAULT,"main: kqueue() failed!");
2714                 printf("ERROR: could not initialise kqueue event system. Shutting down.\n");
2715                 Exit(ERROR);
2716         }
2717 #endif
2718
2719 #ifdef USE_EPOLL
2720         ep = epoll_create(MAXCLIENTS);
2721         lep = epoll_create(32);
2722         sep = epoll_create(128);
2723         if ((ep == -1) || (lep == -1) || (sep == -1))
2724         {
2725                 log(DEFAULT,"main: epoll_create() failed!");
2726                 printf("ERROR: could not initialise epoll event system. Shutting down.\n");
2727                 Exit(ERROR);
2728         }
2729 #endif
2730
2731 #ifdef USE_EPOLL
2732         log(DEFAULT,"epoll socket engine is enabled. Filling listen list. boundPortcount=%d",boundPortCount);
2733         for (count = 0; count < boundPortCount; count++)
2734         {
2735                 struct epoll_event ev;
2736                 log(DEBUG,"epoll: Add listening socket to events, ep=%d socket=%d",lep,openSockfd[count]);
2737                 ev.events = EPOLLIN | EPOLLET;
2738                 ev.data.fd = openSockfd[count];
2739                 int i = epoll_ctl(lep, EPOLL_CTL_ADD, openSockfd[count], &ev);
2740                 if (i < 0)
2741                 {
2742                         log(DEFAULT,"main: add listen ports, epoll_ctl failed!");
2743                         printf("ERROR: could not initialise listening sockets in epoll list. Shutting down.\n");
2744                         Exit(ERROR);
2745                 }
2746                 
2747         }
2748         for (int t = 0; t != SERVERportCount; t++)
2749         {
2750                 struct epoll_event ev;
2751                 log(DEBUG,"epoll: Add listening server socket to events, ep=%d socket=%d",sep,me[t]->fd);
2752                 ev.events = EPOLLIN | EPOLLET;
2753                 ev.data.fd = me[t]->fd;
2754                 int i = epoll_ctl(sep, EPOLL_CTL_ADD, me[t]->fd, &ev);
2755                 if (i == -1)
2756                 {
2757                         log(DEFAULT,"main: add server listen ports, epoll_ctl failed!");
2758                         printf("ERROR: could not initialise server listening sockets in epoll list. Shutting down.\n");
2759                         Exit(ERROR);
2760                 }
2761         }
2762 #else
2763 #ifdef USE_KQUEUE
2764         log(DEFAULT,"kqueue socket engine is enabled. Filling listen list.");
2765         for (count = 0; count < boundPortCount; count++)
2766         {
2767                 struct kevent ke;
2768                 log(DEBUG,"kqueue: Add listening socket to events, kq=%d socket=%d",lkq,openSockfd[count]);
2769                 EV_SET(&ke, openSockfd[count], EVFILT_READ, EV_ADD, 0, MaxConn, NULL);
2770                 int i = kevent(lkq, &ke, 1, 0, 0, NULL);
2771                 if (i == -1)
2772                 {
2773                         log(DEFAULT,"main: add listen ports to kqueue failed!");
2774                         printf("ERROR: could not initialise listening sockets in kqueue. Shutting down.\n");
2775                         Exit(ERROR);
2776                 }
2777         }
2778         for (int t = 0; t != SERVERportCount; t++)
2779         {
2780                 struct kevent ke;
2781                 if (me[t])
2782                 {
2783                         log(DEBUG,"kqueue: Add listening SERVER socket to events, kq=%d socket=%d",skq,me[t]->fd);
2784                         EV_SET(&ke, me[t]->fd, EVFILT_READ, EV_ADD, 0, MaxConn, NULL);
2785                         int i = kevent(skq, &ke, 1, 0, 0, NULL);
2786                         if (i == -1)
2787                         {
2788                                 log(DEFAULT,"main: add server listen ports to kqueue failed!");
2789                                 printf("ERROR: could not initialise listening server sockets in kqueue. Shutting down.\n");
2790                                 Exit(ERROR);
2791                         }
2792                 }
2793         }
2794
2795
2796 #else
2797         log(DEFAULT,"Using standard select socket engine.");
2798 #endif
2799 #endif
2800
2801         WritePID(PID);
2802
2803         length = sizeof (client);
2804         char tcp_msg[MAXBUF],tcp_host[MAXBUF],tcp_sum[MAXBUF];
2805
2806 #ifdef USE_KQUEUE
2807         struct kevent ke;
2808         struct kevent ke_list[33];
2809         struct timespec ts;
2810 #endif
2811 #ifdef USE_EPOLL
2812         struct epoll_event event[33];
2813 #endif
2814         fd_set serverfds;
2815         timeval tvs;
2816         tvs.tv_usec = 10000L;
2817         tvs.tv_sec = 0;
2818         tv.tv_sec = 0;
2819         tv.tv_usec = 10000L;
2820         char data[65536];
2821         timeval tval;
2822         fd_set sfd;
2823         tval.tv_usec = 10000L;
2824         tval.tv_sec = 0;
2825         int total_in_this_set = 0;
2826         int i = 0, v = 0, j = 0, cycle_iter = 0;
2827         bool expire_run = false;
2828           
2829         /* main loop, this never returns */
2830         for (;;)
2831         {
2832 #ifdef _POSIX_PRIORITY_SCHEDULING
2833                 sched_yield();
2834 #endif
2835 #ifdef USE_SELECT
2836                 FD_ZERO(&sfd);
2837 #endif
2838                 // we only read time() once per iteration rather than tons of times!
2839                 OLDTIME = TIME;
2840                 TIME = time(NULL);
2841
2842                 dns_poll();
2843
2844                 // *FIX* Instead of closing sockets in kill_link when they receive the ERROR :blah line, we should queue
2845                 // them in a list, then reap the list every second or so.
2846                 if (((TIME % 5) == 0) && (!expire_run))
2847                 {
2848                         for (int i = 0; i < ConfValueEnum("link",&config_f); i++)
2849                         {
2850                                 char Link_ServerName[MAXBUF],Link_AConn[MAXBUF];
2851                                 ConfValue("link","name",i,Link_ServerName,&config_f);
2852                                 ConfValue("link","autoconnect",i,Link_AConn,&config_f);
2853                                 if ((Link_AConn[0]) && (!GotServer(Link_ServerName)))
2854                                 {
2855                                         autoconnects::iterator a = autoconns.find(std::string(Link_ServerName));
2856                                         if (a != autoconns.end())
2857                                         {
2858                                                 if (TIME > a->second)
2859                                                 {
2860                                                         ConnectServer(Link_ServerName,NULL);
2861                                                         a->second = TIME + atoi(Link_AConn);
2862                                                 }
2863                                         }
2864                                 }
2865                         }
2866
2867                         expire_lines();
2868                         FOREACH_MOD OnBackgroundTimer(TIME);
2869                         expire_run = true;
2870                         continue;
2871                 }
2872                 if ((TIME % 5) == 1)
2873                         expire_run = false;
2874                 
2875                 // fix by brain - this must be below any manipulation of the hashmap by modules
2876                 user_hash::iterator count2 = clientlist.begin();
2877
2878 #ifdef USE_EPOLL
2879                 i = epoll_wait(sep, event, 1, EP_DELAY);
2880                 if (i > 0)
2881                 {
2882                         log(DEBUG,"epoll: Listening server socket event, i=%d, event.data.fd=%d",i,event[0].data.fd);
2883                         for (int x = 0; x != SERVERportCount; x++)
2884                         {
2885                                 if ((me[x]) && (event[0].data.fd == me[x]->fd))
2886                                 {
2887 #endif
2888 #ifdef USE_KQUEUE
2889                 ts.tv_sec = 0;
2890                 ts.tv_nsec = 30000L;
2891                 i = kevent(skq, NULL, 0, &ke, 1, &ts);
2892                 if (i > 0)
2893                 {
2894                         log(DEBUG,"kqueue: Listening server socket event, i=%d, ke.ident=%d",i,ke.ident);
2895                         for (int x = 0; x != SERVERportCount; x++)
2896                         {
2897                                 if ((me[x]) && (ke.ident == me[x]->fd))
2898                                 {
2899
2900 #endif
2901 #ifdef USE_SELECT
2902                 FD_ZERO(&serverfds);
2903                 for (int x = 0; x != SERVERportCount; x++)
2904                 {
2905                         if (me[x])
2906                                 FD_SET(me[x]->fd, &serverfds);
2907                 }
2908                 tvs.tv_usec = 30000L;
2909                 tvs.tv_sec = 0;
2910                 int servresult = select(FD_SETSIZE, &serverfds, NULL, NULL, &tvs);
2911                 if (servresult > 0)
2912                 {
2913                         for (int x = 0; x != SERVERportCount; x++)
2914                         {
2915                                 if ((me[x]) && (FD_ISSET (me[x]->fd, &serverfds)))
2916                                 {
2917 #endif
2918                                         char remotehost[MAXBUF],resolved[MAXBUF];
2919                                         length = sizeof (client);
2920                                         incomingSockfd = accept (me[x]->fd, (sockaddr *) &client, &length);
2921                                         if (incomingSockfd != -1)
2922                                         {
2923                                                 strlcpy(remotehost,(char *)inet_ntoa(client.sin_addr),MAXBUF);
2924                                                 if(CleanAndResolve(resolved, remotehost) != TRUE)
2925                                                 {
2926                                                         strlcpy(resolved,remotehost,MAXBUF);
2927                                                 }
2928                                                 // add to this connections ircd_connector vector
2929                                                 // *FIX* - we need the LOCAL port not the remote port in &client!
2930                                                 me[x]->AddIncoming(incomingSockfd,resolved,me[x]->port);
2931                                         }
2932                                 }
2933                         }
2934                 }
2935      
2936                 std::deque<std::string> msgs;
2937                 std::deque<std::string> sums;
2938                 for (int x = 0; x < SERVERportCount; x++)
2939                 {
2940                         if (me[x])
2941                                 me[x]->FlushWriteBuffers();
2942                         sums.clear();
2943                         msgs.clear();
2944                         while ((me[x]) && (me[x]->RecvPacket(msgs, tcp_host, sums))) // returns 0 or more lines (can be multiple lines!)
2945                         {
2946                                 has_been_netsplit = false;
2947                                 for (int ctr = 0; ctr < msgs.size(); ctr++)
2948                                 {
2949                                         strlcpy(tcp_msg,msgs[ctr].c_str(),MAXBUF);
2950                                         strlcpy(tcp_sum,sums[ctr].c_str(),MAXBUF);
2951                                         log(DEBUG,"Processing: %s",tcp_msg);
2952                                         if (!tcp_msg[0])
2953                                         {
2954                                                 log(DEBUG,"Invalid string from %s [route%lu]",tcp_host,(unsigned long)x);
2955                                                 break;
2956                                         }
2957                                         // during a netburst, send all data to all other linked servers
2958                                         if ((((nb_start>0) && (tcp_msg[0] != 'Y') && (tcp_msg[0] != 'X') && (tcp_msg[0] != 'F'))) || (is_uline(tcp_host)))
2959                                         {
2960                                                 if (is_uline(tcp_host))
2961                                                 {
2962                                                         if ((tcp_msg[0] != 'Y') && (tcp_msg[0] != 'X') && (tcp_msg[0] != 'F'))
2963                                                         {
2964                                                                 NetSendToAllExcept_WithSum(tcp_host,tcp_msg,tcp_sum);
2965                                                         }
2966                                                 }
2967                                                 else
2968                                                         NetSendToAllExcept_WithSum(tcp_host,tcp_msg,tcp_sum);
2969                                         }
2970                                         std::string msg = tcp_msg;
2971                                         FOREACH_MOD OnPacketReceive(msg,tcp_host);
2972                                         strlcpy(tcp_msg,msg.c_str(),MAXBUF);
2973                                         if (me[x])
2974                                                 handle_link_packet(tcp_msg, tcp_host, me[x], tcp_sum);
2975                                         if (!me[x]->FindHost(tcp_host))
2976                                         {
2977                                                 log(DEBUG,"Connector gone, bailing!");
2978                                                 goto label;
2979                                         }
2980                                 }
2981                                 goto label;
2982                         }
2983                 }
2984         
2985         while (count2 != clientlist.end())
2986         {
2987 #ifdef USE_SELECT
2988                 FD_ZERO(&sfd);
2989 #endif
2990
2991                 total_in_this_set = 0;
2992
2993                 user_hash::iterator xcount = count2;
2994                 user_hash::iterator endingiter = count2;
2995
2996                 if (count2 == clientlist.end()) break;
2997
2998                 userrec* curr = NULL;
2999
3000                 if (count2->second)
3001                         curr = count2->second;
3002
3003                 if ((long)curr == -1)
3004                         goto label;
3005
3006                 if ((curr) && (curr->fd != 0))
3007                 {
3008 #ifdef _POSIX_PRIORITY_SCHEDULING
3009         sched_yield();
3010 #endif
3011                         // assemble up to 64 sockets into an fd_set
3012                         // to implement a pooling mechanism.
3013                         //
3014                         // This should be up to 64x faster than the
3015                         // old implementation.
3016 #ifdef USE_SELECT
3017                         while (total_in_this_set < 1024)
3018                         {
3019                                 if (count2 != clientlist.end())
3020                                 {
3021                                         curr = count2->second;
3022                                         if ((long)curr == -1)
3023                                                 goto label;
3024                                         int currfd = curr->fd;
3025                                         // we don't check the state of remote users.
3026                                         if ((currfd != -1) && (currfd != FD_MAGIC_NUMBER))
3027                                         {
3028                                                 curr->FlushWriteBuf();
3029                                                 if (curr->GetWriteError() != "")
3030                                                 {
3031                                                         log(DEBUG,"InspIRCd: write error: %s",curr->GetWriteError().c_str());
3032                                                         kill_link(curr,curr->GetWriteError().c_str());
3033                                                         goto label;
3034                                                 }
3035
3036                                                 FD_SET (curr->fd, &sfd);
3037
3038                                                 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
3039                                                 // their connection class.
3040                                                 if ((TIME > curr->timeout) && (curr->registered != 7)) 
3041                                                 {
3042                                                         log(DEBUG,"InspIRCd: registration timeout: %s",curr->nick);
3043                                                         kill_link(curr,"Registration timeout");
3044                                                         goto label;
3045                                                 }
3046                                                 if ((TIME > curr->signon) && (curr->registered == 3) && (AllModulesReportReady(curr)))
3047                                                 {
3048                                                         log(DEBUG,"signon exceed, registered=3, and modules ready, OK");
3049                                                         curr->dns_done = true;
3050                                                         statsDnsBad++;
3051                                                         FullConnectUser(curr);
3052                                                         if (fd_ref_table[currfd] != curr) // something changed, bail pronto
3053                                                                 goto label;                                                        
3054                                                 }
3055                                                 if ((curr->dns_done) && (curr->registered == 3) && (AllModulesReportReady(curr))) // both NICK and USER... and DNS
3056                                                 {
3057                                                         log(DEBUG,"dns done, registered=3, and modules ready, OK");
3058                                                         FullConnectUser(curr);
3059                                                         if (fd_ref_table[currfd] != curr) // something changed, bail pronto
3060                                                                 goto label;
3061                                                 }
3062                                                 if ((TIME > curr->nping) && (isnick(curr->nick)) && (curr->registered == 7))
3063                                                 {
3064                                                         if ((!curr->lastping) && (curr->registered == 7))
3065                                                         {
3066                                                                 log(DEBUG,"InspIRCd: ping timeout: %s",curr->nick);
3067                                                                 kill_link(curr,"Ping timeout");
3068                                                                 goto label;
3069                                                         }
3070                                                         Write(curr->fd,"PING :%s",ServerName);
3071                                                         log(DEBUG,"InspIRCd: pinging: %s",curr->nick);
3072                                                         curr->lastping = 0;
3073                                                         curr->nping = TIME+curr->pingmax;       // was hard coded to 120
3074                                                 }
3075                                         }
3076                                         count2++;
3077                                         total_in_this_set++;
3078                                 }
3079                                 else break;
3080                         }
3081                         endingiter = count2;
3082                         count2 = xcount; // roll back to where we were
3083 #else
3084                         // 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.
3085                         // TODO: We dont need to do all this EVERY loop iteration, tone down the visits to this if we're using kqueue.
3086                         cycle_iter++;
3087                         if (cycle_iter > 20) while (count2 != clientlist.end())
3088                         {
3089                                 cycle_iter = 0;
3090                                 if (count2 != clientlist.end())
3091                                 {
3092                                         curr = count2->second;
3093                                         if ((long)curr == -1)
3094                                                 goto label;
3095                                         int currfd = curr->fd;
3096                                         // we don't check the state of remote users.
3097                                         if ((currfd != -1) && (currfd != FD_MAGIC_NUMBER))
3098                                         {
3099
3100                                                 curr->FlushWriteBuf();
3101                                                 if (curr->GetWriteError() != "")
3102                                                 {
3103                                                         log(DEBUG,"InspIRCd: write error: %s",curr->GetWriteError().c_str());
3104                                                         kill_link(curr,curr->GetWriteError().c_str());
3105                                                         goto label;
3106                                                 }
3107
3108                                                 // registration timeout -- didnt send USER/NICK/HOST in the time specified in
3109                                                 // their connection class.
3110                                                 if ((TIME > curr->timeout) && (curr->registered != 7))
3111                                                 {
3112                                                         log(DEBUG,"InspIRCd: registration timeout: %s",curr->nick);
3113                                                         kill_link(curr,"Registration timeout");
3114                                                         goto label;
3115
3116                                                 }
3117                                                 if ((TIME > curr->signon) && (curr->registered == 3) && (AllModulesReportReady(curr)))
3118                                                 {
3119                                                         log(DEBUG,"signon exceed, registered=3, and modules ready, OK: %d %d",TIME,curr->signon);
3120                                                         curr->dns_done = true;
3121                                                         statsDnsBad++;
3122                                                         FullConnectUser(curr);
3123                                                         if (fd_ref_table[currfd] != curr) // something changed, bail pronto
3124                                                                 goto label;
3125                                                 }
3126                                                 if ((curr->dns_done) && (curr->registered == 3) && (AllModulesReportReady(curr)))
3127                                                 {
3128                                                         log(DEBUG,"dns done, registered=3, and modules ready, OK");
3129                                                         FullConnectUser(curr);
3130                                                         if (fd_ref_table[currfd] != curr) // something changed, bail pronto
3131                                                                 goto label;
3132                                                 }
3133                                                 if ((TIME > curr->nping) && (isnick(curr->nick)) && (curr->registered == 7))
3134                                                 {
3135                                                         if ((!curr->lastping) && (curr->registered == 7))
3136                                                         {
3137                                                                 log(DEBUG,"InspIRCd: ping timeout: %s",curr->nick);
3138                                                                 kill_link(curr,"Ping timeout");
3139                                                                 goto label;
3140                                                         }
3141                                                         Write(curr->fd,"PING :%s",ServerName);
3142                                                         log(DEBUG,"InspIRCd: pinging: %s",curr->nick);
3143                                                         curr->lastping = 0;
3144                                                         curr->nping = TIME+curr->pingmax;       // was hard coded to 120
3145                                                 }
3146                                         }
3147                                 }
3148                                 else break;
3149                                 count2++;
3150                         }
3151                         // increment the counter right to the end of the list, as kqueue processes everything in one go
3152 #endif
3153         
3154                         v = 0;
3155 #ifdef USE_EPOLL
3156                         int i = epoll_wait(ep, event, 1, 5);
3157                         if (i > 0)
3158                         {
3159                                 log(DEBUG,"epoll_wait call: ep=%d, i=%d",ep,i);
3160                                 // EPOLL: we asked epoll_wait for ONE fd which is ready. Do something.
3161                                 userrec* cu = fd_ref_table[event[0].data.fd];
3162 #endif
3163 #ifdef USE_KQUEUE
3164                         ts.tv_sec = 0;
3165                         ts.tv_nsec = 1000L;
3166                         // for now, we only read 1 event. We could read soooo many more :)
3167                         int i = kevent(kq, NULL, 0, &ke, 1, &ts);
3168                         if (i > 0)
3169                         {
3170                                 log(DEBUG,"kevent call: kq=%d, i=%d",kq,i);
3171                                 // KQUEUE: kevent gives us ONE fd which is ready to have something done to it. Do something to it.
3172                                 userrec* cu = fd_ref_table[ke.ident];
3173 #endif
3174 #ifdef USE_SELECT
3175                         tval.tv_sec = 0;
3176                         tval.tv_usec = 1000L;
3177                         selectResult2 = select(FD_SETSIZE, &sfd, NULL, NULL, &tval);
3178                         // now loop through all of the items in this pool if any are waiting
3179                         if ((selectResult2 > 0) && (xcount != clientlist.end()))
3180                         for (user_hash::iterator count2a = xcount; count2a != endingiter; count2a++)
3181                         {
3182                                 // SELECT: we have to iterate...
3183                                 if (count2a == clientlist.end())
3184                                         break;
3185                                 userrec* cu = count2a->second;
3186 #endif
3187
3188 #ifdef _POSIX_PRIORITY_SCHEDULING
3189                                 sched_yield();
3190 #endif
3191                                 result = EAGAIN;
3192 #ifdef USE_EPOLL
3193                                 // EPOLL: We already know we have a valid FD. No checks needed.
3194                                 if ((cu->fd != FD_MAGIC_NUMBER) && (cu->fd != -1))
3195 #endif
3196 #ifdef USE_KQUEUE
3197                                 // KQUEUE: We already know we have a valid FD. No checks needed.
3198                                 if ((cu->fd != FD_MAGIC_NUMBER) && (cu->fd != -1))
3199 #endif
3200 #ifdef USE_SELECT
3201                                 // SELECT: We don't know if our FD is valid.
3202                                 if ((cu->fd != FD_MAGIC_NUMBER) && (cu->fd != -1) && (FD_ISSET (cu->fd, &sfd)))
3203 #endif
3204                                 {
3205                                         log(DEBUG,"Data waiting on socket %d",cu->fd);
3206                                         int MOD_RESULT = 0;
3207                                         int result2 = 0;
3208                                         FOREACH_RESULT(OnRawSocketRead(cu->fd,data,65535,result2));
3209                                         if (!MOD_RESULT)
3210                                         {
3211                                                 result = cu->ReadData(data, 65535);
3212                                         }
3213                                         else result = result2;
3214                                         log(DEBUG,"Read result: %d",result);
3215                                         if (result)
3216                                         {
3217                                                 statsRecv += result;
3218                                                 // perform a check on the raw buffer as an array (not a string!) to remove
3219                                                 // characters 0 and 7 which are illegal in the RFC - replace them with spaces.
3220                                                 // hopefully this should stop even more people whining about "Unknown command: *"
3221                                                 for (int checker = 0; checker < result; checker++)
3222                                                 {
3223                                                         if ((data[checker] == 0) || (data[checker] == 7))
3224                                                                 data[checker] = ' ';
3225                                                 }
3226                                                 if (result > 0)
3227                                                         data[result] = '\0';
3228                                                 userrec* current = cu;
3229                                                 int currfd = current->fd;
3230                                                 int floodlines = 0;
3231                                                 // add the data to the users buffer
3232                                                 if (result > 0)
3233                                                 if (!current->AddBuffer(data))
3234                                                 {
3235                                                         // AddBuffer returned false, theres too much data in the user's buffer and theyre up to no good.
3236                                                         if (current->registered == 7)
3237                                                         {
3238                                                                 kill_link(current,"RecvQ exceeded");
3239                                                         }
3240                                                         else
3241                                                         {
3242                                                                 WriteOpers("*** Excess flood from %s",current->ip);
3243                                                                 log(DEFAULT,"Excess flood from: %s",current->ip);
3244                                                                 add_zline(120,ServerName,"Flood from unregistered connection",current->ip);
3245                                                                 apply_lines();
3246                                                         }
3247                                                         goto label;
3248                                                 }
3249                                                 if (current->recvq.length() > NetBufferSize)
3250                                                 {
3251                                                         if (current->registered == 7)
3252                                                         {
3253                                                                 kill_link(current,"RecvQ exceeded");
3254                                                         }
3255                                                         else
3256                                                         {
3257                                                                 WriteOpers("*** Excess flood from %s",current->ip);
3258                                                                 log(DEFAULT,"Excess flood from: %s",current->ip);
3259                                                                 add_zline(120,ServerName,"Flood from unregistered connection",current->ip);
3260                                                                 apply_lines();
3261                                                         }
3262                                                         goto label;
3263                                                 }
3264                                                 // while there are complete lines to process...
3265                                                 while (current->BufferIsReady())
3266                                                 {
3267                                                         floodlines++;
3268                                                         if (TIME > current->reset_due)
3269                                                         {
3270                                                                 current->reset_due = TIME + current->threshold;
3271                                                                 current->lines_in = 0;
3272                                                         }
3273                                                         current->lines_in++;
3274                                                         if (current->lines_in > current->flood)
3275                                                         {
3276                                                                 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3277                                                                 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3278                                                                 kill_link(current,"Excess flood");
3279                                                                 goto label;
3280                                                         }
3281                                                         if ((floodlines > current->flood) && (current->flood != 0))
3282                                                         {
3283                                                                 if (current->registered == 7)
3284                                                                 {
3285                                                                         log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3286                                                                         WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3287                                                                         kill_link(current,"Excess flood");
3288                                                                 }
3289                                                                 else
3290                                                                 {
3291                                                                         add_zline(120,ServerName,"Flood from unregistered connection",current->ip);
3292                                                                         apply_lines();
3293                                                                 }
3294                                                                 goto label;
3295                                                         }
3296                                                         char sanitized[MAXBUF];
3297                                                         // use GetBuffer to copy single lines into the sanitized string
3298                                                         std::string single_line = current->GetBuffer();
3299                                                         current->bytes_in += single_line.length();
3300                                                         current->cmds_in++;
3301                                                         if (single_line.length()>512)
3302                                                         {
3303                                                                 log(DEFAULT,"Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3304                                                                 WriteOpers("*** Excess flood from: %s!%s@%s",current->nick,current->ident,current->host);
3305                                                                 kill_link(current,"Excess flood");
3306                                                                 goto label;
3307                                                         }
3308                                                         strlcpy(sanitized,single_line.c_str(),MAXBUF);
3309                                                         if (*sanitized)
3310                                                         {
3311                                                                 userrec* old_comp = fd_ref_table[currfd];
3312                                                                 // we're gonna re-scan to check if the nick is gone, after every
3313                                                                 // command - if it has, we're gonna bail
3314                                                                 process_buffer(sanitized,current);
3315                                                                 // look for the user's record in case it's changed... if theyve quit,
3316                                                                 // we cant do anything more with their buffer, so bail.
3317                                                                 // there used to be an ugly, slow loop here. Now we have a reference
3318                                                                 // table, life is much easier (and FASTER)
3319                                                                 userrec* new_comp = fd_ref_table[currfd];
3320                                                                 if ((currfd < 0) || (!fd_ref_table[currfd]) || (old_comp != new_comp))
3321                                                                         goto label;
3322
3323                                                         }
3324                                                 }
3325                                                 goto label;
3326                                         }
3327
3328                                         if ((result == -1) && (errno != EAGAIN) && (errno != EINTR))
3329                                         {
3330                                                 log(DEBUG,"killing: %s",cu->nick);
3331                                                 kill_link(cu,strerror(errno));
3332                                                 goto label;
3333                                         }
3334                                 }
3335                                 // result EAGAIN means nothing read
3336                                 if (result == EAGAIN)
3337                                 {
3338                                 }
3339                                 else
3340                                 if (result == 0)
3341                                 {
3342 #ifdef USE_SELECT
3343                                         if (count2->second)
3344                                         {
3345 #endif
3346                                                 log(DEBUG,"InspIRCd: Exited: %s",cu->nick);
3347                                                 kill_link(cu,"Client exited");
3348                                                 // must bail here? kill_link removes the hash, corrupting the iterator
3349                                                 log(DEBUG,"Bailing from client exit");
3350                                                 goto label;
3351 #ifdef USE_SELECT
3352                                         }
3353 #endif
3354                                 }
3355                                 else if (result > 0)
3356                                 {
3357                                 }
3358                         }
3359                 }
3360                 for (int q = 0; q < total_in_this_set; q++)
3361                 {
3362                         count2++;
3363                 }
3364         }
3365
3366 #ifdef _POSIX_PRIORITY_SCHEDULING
3367         sched_yield();
3368 #endif
3369         
3370 #ifdef USE_SELECT
3371         // set up select call
3372         for (count = 0; count < boundPortCount; count++)
3373         {
3374                 FD_SET (openSockfd[count], &selectFds);
3375         }
3376
3377         tv.tv_usec = 30000L;
3378         selectResult = select(MAXSOCKS, &selectFds, NULL, NULL, &tv);
3379
3380         /* select is reporting a waiting socket. Poll them all to find out which */
3381         if (selectResult > 0)
3382         {
3383                 for (count = 0; count < boundPortCount; count++)
3384                 {
3385                         if (FD_ISSET (openSockfd[count], &selectFds))
3386                         {
3387 #endif
3388 #ifdef USE_KQUEUE
3389         ts.tv_sec = 0;
3390         ts.tv_nsec = 30000L;
3391         i = kevent(lkq, NULL, 0, ke_list, 32, &ts);
3392         if (i > 0) for (j = 0; j < i; j++)
3393         {
3394                 log(DEBUG,"kqueue: Listening socket event, i=%d, ke.ident=%d",i,ke_list[j].ident);
3395                 // this isnt as efficient as it could be, we could create a reference table
3396                 // to reference bound ports by fd, but this isnt a big bottleneck as the actual
3397                 // number of listening ports on the average ircd is a small number (less than 20)
3398                 // compared to the number of clients (possibly over 2000)
3399                 for (count = 0; count < boundPortCount; count++)
3400                 {
3401                         if (ke_list[j].ident == openSockfd[count])
3402                         {
3403 #endif
3404 #ifdef USE_EPOLL
3405         i = epoll_wait(lep, event, 32, EP_DELAY);
3406         if (i > 0) for (j = 0; j < i; j++)
3407         {
3408                 log(DEBUG,"epoll: Listening socket event, i=%d,events[j].data.fd=%d",i,event[j].data.fd);
3409                 for (count = 0; count < boundPortCount; count++)
3410                 {
3411                         if (event[j].data.fd == openSockfd[count])
3412                         {
3413 #endif
3414                                 char target[MAXBUF], resolved[MAXBUF];
3415                                 length = sizeof (client);
3416                                 incomingSockfd = accept (openSockfd[count], (struct sockaddr *) &client, &length);
3417                               
3418                                 strlcpy (target, (char *) inet_ntoa (client.sin_addr), MAXBUF);
3419                                 strlcpy (resolved, target, MAXBUF);
3420                         
3421                                 if (incomingSockfd < 0)
3422                                 {
3423                                         WriteOpers("*** WARNING: Accept failed on port %lu (%s)",(unsigned long)ports[count],target);
3424                                         log(DEBUG,"InspIRCd: accept failed: %lu",(unsigned long)ports[count]);
3425                                         statsRefused++;
3426                                 }
3427                                 else
3428                                 {
3429                                         FOREACH_MOD OnRawSocketAccept(incomingSockfd, resolved, ports[count]);
3430                                         statsAccept++;
3431                                         AddClient(incomingSockfd, resolved, ports[count], false, inet_ntoa (client.sin_addr));
3432                                         log(DEBUG,"InspIRCd: adding client on port %lu fd=%lu",(unsigned long)ports[count],(unsigned long)incomingSockfd);
3433                                 }
3434                         }
3435                 }
3436         }
3437         label:
3438         if (0) {};
3439 #ifdef _POSIX_PRIORITY_SCHEDULING
3440         sched_yield();
3441         sched_yield();
3442 #endif
3443 }
3444 /* not reached */
3445 close (incomingSockfd);
3446 }
3447