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