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