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