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