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