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