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