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