]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd_io.cpp
Tidyup of ServerConf::Read about half done (works)
[user/henk/code/inspircd.git] / src / inspircd_io.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd is copyright (C) 2002-2006 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 using namespace std;
18
19 #include "inspircd_config.h"
20 #include <sys/time.h>
21 #include <sys/resource.h>
22 #include <sys/types.h>
23 #include <string>
24 #include <unistd.h>
25 #include <sstream>
26 #include <iostream>
27 #include <fstream>
28 #include "inspircd.h"
29 #include "inspircd_io.h"
30 #include "inspstring.h"
31 #include "helperfuncs.h"
32 #include "userprocess.h"
33 #include "xline.h"
34
35 extern ServerConfig *Config;
36 extern InspIRCd* ServerInstance;
37 extern int openSockfd[MAXSOCKS];
38 extern time_t TIME;
39
40 extern int MODCOUNT;
41 extern std::vector<Module*> modules;
42 extern std::vector<ircd_module*> factory;
43
44 ServerConfig::ServerConfig()
45 {
46         this->ClearStack();
47         *TempDir = *ServerName = *Network = *ServerDesc = *AdminName = '\0';
48         *HideWhoisServer = *AdminEmail = *AdminNick = *diepass = *restartpass = '\0';
49         *CustomVersion = *motd = *rules = *PrefixQuit = *DieValue = *DNSServer = '\0';
50         *OperOnlyStats = *ModPath = *MyExecutable = *DisabledCommands = *PID = '\0';
51         log_file = NULL;
52         nofork = HideBans = HideSplits = unlimitcore = false;
53         AllowHalfop = true;
54         dns_timeout = DieDelay = 5;
55         MaxTargets = 20;
56         NetBufferSize = 10240;
57         SoftLimit = MAXCLIENTS;
58         MaxConn = SOMAXCONN;
59         MaxWhoResults = 100;
60         debugging = 0;
61         LogLevel = DEFAULT;
62         maxbans.clear();
63 }
64
65 void ServerConfig::ClearStack()
66 {
67         include_stack.clear();
68 }
69
70 Module* ServerConfig::GetIOHook(int port)
71 {
72         std::map<int,Module*>::iterator x = IOHookModule.find(port);
73         return (x != IOHookModule.end() ? x->second : NULL);
74 }
75
76 bool ServerConfig::AddIOHook(int port, Module* iomod)
77 {
78         if (!GetIOHook(port))
79         {
80                 IOHookModule[port] = iomod;
81                 return true;
82         }
83         else
84         {
85                 ModuleException err("Port already hooked by another module");
86                 throw(err);
87                 return false;
88         }
89 }
90
91 bool ServerConfig::DelIOHook(int port)
92 {
93         std::map<int,Module*>::iterator x = IOHookModule.find(port);
94         if (x != IOHookModule.end())
95         {
96                 IOHookModule.erase(x);
97                 return true;
98         }
99         return false;
100 }
101
102 bool ServerConfig::CheckOnce(char* tag, bool bail, userrec* user)
103 {
104         int count = ConfValueEnum(tag,&Config->config_f);
105         if (count > 1)
106         {
107                 if (bail)
108                 {
109                         printf("There were errors in your configuration:\nYou have more than one <%s> tag, this is not permitted.\n",tag);
110                         Exit(0);
111                 }
112                 else
113                 {
114                         if (user)
115                         {
116                                 WriteServ(user->fd,"There were errors in your configuration:");
117                                 WriteServ(user->fd,"You have more than one <%s> tag, this is not permitted.\n",tag);
118                         }
119                         else
120                         {
121                                 WriteOpers("There were errors in the configuration file:");
122                                 WriteOpers("You have more than one <%s> tag, this is not permitted.\n",tag);
123                         }
124                 }
125                 return false;
126         }
127         if (count < 1)
128         {
129                 if (bail)
130                 {
131                         printf("There were errors in your configuration:\nYou have not defined a <%s> tag, this is required.\n",tag);
132                         Exit(0);
133                 }
134                 else
135                 {
136                         if (user)
137                         {
138                                 WriteServ(user->fd,"There were errors in your configuration:");
139                                 WriteServ(user->fd,"You have not defined a <%s> tag, this is required.",tag);
140                         }
141                         else
142                         {
143                                 WriteOpers("There were errors in the configuration file:");
144                                 WriteOpers("You have not defined a <%s> tag, this is required.",tag);
145                         }
146                 }
147                 return false;
148         }
149         return true;
150 }
151
152 typedef bool (*Validator)(const char*, const char*, void*);
153
154 enum ConfigDataType { DT_NOTHING, DT_INTEGER, DT_CHARPTR, DT_BOOLEAN };
155
156 struct InitialConfig {
157         char* tag;
158         char* value;
159         void* val;
160         int datatype;
161         Validator validation_function;
162 };
163
164 bool NoValidation(const char* tag, const char* value, void* data)
165 {
166         log(DEBUG,"No validation for <%s:%s>",tag,value);
167         return true;
168 }
169
170 bool ValidateTempDir(const char* tag, const char* value, void* data)
171 {
172         char* x = (char*)data;
173         if (!*x)
174                strlcpy(x,"/tmp",1024);
175         return true;
176 }
177  
178 bool ValidateMaxTargets(const char* tag, const char* value, void* data)
179 {
180         int* x = (int*)data;
181         if ((*x < 0) || (*x > 31))
182         {
183                 log(DEFAULT,"WARNING: <options:maxtargets> value is greater than 31 or less than 0, set to 20.");
184                 *x = 20;
185         }
186         return true;
187 }
188
189 bool ValidateSoftLimit(const char* tag, const char* value, void* data)
190 {
191         int* x = (int*)data;    
192         if ((*x < 1) || (*x > MAXCLIENTS))
193         {
194                 log(DEFAULT,"WARNING: <options:softlimit> value is greater than %d or less than 0, set to %d.",MAXCLIENTS,MAXCLIENTS);
195                 *x = MAXCLIENTS;
196         }
197         return true;
198 }
199
200 bool ValidateMaxConn(const char* tag, const char* value, void* data)
201 {
202         int* x = (int*)data;    
203         if (*x > SOMAXCONN)
204                 log(DEFAULT,"WARNING: <options:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
205         if (!*x)
206                 *x = SOMAXCONN;
207         return true;
208 }
209
210 bool ValidateDnsTimeout(const char* tag, const char* value, void* data)
211 {
212         int* x = (int*)data;
213         if (!*x)
214                 *x = 5;
215         return true;
216 }
217
218 bool ValidateDnsServer(const char* tag, const char* value, void* data)
219 {
220         char* x = (char*)data;
221         if (!*x)
222         {
223                 // attempt to look up their nameserver from /etc/resolv.conf
224                 log(DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
225                 ifstream resolv("/etc/resolv.conf");
226                 std::string nameserver;
227                 bool found_server = false;
228          
229                 if (resolv.is_open())
230                 {
231                         while (resolv >> nameserver)
232                         {
233                                 if ((nameserver == "nameserver") && (!found_server))
234                                 {
235                                         resolv >> nameserver;
236                                         strlcpy(x,nameserver.c_str(),MAXBUF);
237                                         found_server = true;
238                                         log(DEFAULT,"<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",nameserver.c_str());
239                                 }
240                         }
241                                 
242                         if (!found_server)
243                         {
244                                 log(DEFAULT,"/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
245                                 strlcpy(x,"127.0.0.1",MAXBUF);
246                         }
247                 }
248                 else
249                 {
250                         log(DEFAULT,"/etc/resolv.conf can't be opened! Defaulting to nameserver '127.0.0.1'!");
251                         strlcpy(x,"127.0.0.1",MAXBUF);
252                 }
253         }
254         return true;
255 }
256
257 bool ValidateModPath(const char* tag, const char* value, void* data)
258 {
259         char* x = (char*)data;  
260         if (!*x)
261                 strlcpy(x,MOD_PATH,MAXBUF);
262         return true;
263 }
264
265
266 bool ValidateServerName(const char* tag, const char* value, void* data)
267 {
268         char* x = (char*)data;
269         if (!strchr(x,'.'))
270         {
271                 log(DEFAULT,"WARNING: <server:name> '%s' is not a fully-qualified domain name. Changed to '%s%c'",x,x,'.');
272                 charlcat(x,'.',MAXBUF);
273         }
274         strlower(x);
275         return true;
276 }
277
278 bool ValidateNetBufferSize(const char* tag, const char* value, void* data)
279 {
280         if ((!Config->NetBufferSize) || (Config->NetBufferSize > 65535) || (Config->NetBufferSize < 1024))
281         {
282                 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
283                 Config->NetBufferSize = 10240;
284         }
285         return true;
286 }
287
288 bool ValidateMaxWho(const char* tag, const char* value, void* data)
289 {
290         if ((!Config->MaxWhoResults) || (Config->MaxWhoResults > 65535) || (Config->MaxWhoResults < 1))
291         {
292                 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
293                 Config->MaxWhoResults = 128;
294         }
295         return true;
296 }
297
298 bool ValidateLogLevel(const char* tag, const char* value, void* data)
299 {
300         const char* dbg = (const char*)data;
301         Config->LogLevel = DEFAULT;                        
302         if (!strcmp(dbg,"debug"))
303         {
304                 Config->LogLevel = DEBUG;
305                 Config->debugging = 1;
306         }
307         else if (!strcmp(dbg,"verbose"))
308                 Config->LogLevel = VERBOSE;
309         else if (!strcmp(dbg,"default"))
310                 Config->LogLevel = DEFAULT;
311         else if (!strcmp(dbg,"sparse"))
312                 Config->LogLevel = SPARSE;
313         else if (!strcmp(dbg,"none"))
314                 Config->LogLevel = NONE;
315         return true;
316 }
317
318 bool ValidateMotd(const char* tag, const char* value, void* data)
319 {
320         readfile(Config->MOTD,Config->motd);
321         return true;
322 }
323
324 bool ValidateRules(const char* tag, const char* value, void* data)
325 {
326         readfile(Config->RULES,Config->rules);
327         return true;
328 }
329
330
331 void ServerConfig::Read(bool bail, userrec* user)
332 {
333         char debug[MAXBUF];
334
335         static InitialConfig Values[] = {
336                 {"options",     "softlimit",            &this->SoftLimit,               DT_INTEGER, ValidateSoftLimit},
337                 {"options",     "somaxconn",            &this->MaxConn,                 DT_INTEGER, ValidateMaxConn},
338                 {"server",      "name",                 &this->ServerName,              DT_CHARPTR, ValidateServerName},
339                 {"server",      "description",          &this->ServerDesc,              DT_CHARPTR, ValidateServerName},
340                 {"server",      "network",              &this->Network,                 DT_CHARPTR, NoValidation},
341                 {"admin",       "name",                 &this->AdminName,               DT_CHARPTR, NoValidation},
342                 {"admin",       "email",                &this->AdminEmail,              DT_CHARPTR, NoValidation},
343                 {"admin",       "nick",                 &this->AdminNick,               DT_CHARPTR, NoValidation},
344                 {"files",       "motd",                 &this->motd,                    DT_CHARPTR, ValidateMotd},
345                 {"files",       "rules",                &this->rules,                   DT_CHARPTR, ValidateRules},
346                 {"power",       "diepass",              &this->diepass,                 DT_CHARPTR, NoValidation},      
347                 {"power",       "pauseval",             &this->DieDelay,                DT_INTEGER, NoValidation},
348                 {"power",       "restartpass",          &this->restartpass,             DT_CHARPTR, NoValidation},
349                 {"options",     "prefixquit",           &this->PrefixQuit,              DT_CHARPTR, NoValidation},
350                 {"die",         "value",                &this->DieValue,                DT_CHARPTR, NoValidation},
351                 {"options",     "loglevel",             &debug,                         DT_CHARPTR, ValidateLogLevel},
352                 {"options",     "netbuffersize",        &this->NetBufferSize,           DT_INTEGER, ValidateNetBufferSize},
353                 {"options",     "maxwho",               &this->MaxWhoResults,           DT_INTEGER, ValidateMaxWho},
354                 {"options",     "allowhalfop",          &this->AllowHalfop,             DT_BOOLEAN, NoValidation},
355                 {"dns",         "server",               &this->DNSServer,               DT_CHARPTR, ValidateDnsServer},
356                 {"dns",         "timeout",              &this->dns_timeout,             DT_INTEGER, ValidateDnsTimeout},
357                 {"options",     "moduledir",            &this->ModPath,                 DT_CHARPTR, ValidateModPath},
358                 {"disabled",    "commands",             &this->DisabledCommands,        DT_CHARPTR, NoValidation},
359                 {"options",     "operonlystats",        &this->OperOnlyStats,           DT_CHARPTR, NoValidation},
360                 {"options",     "customversion",        &this->CustomVersion,           DT_CHARPTR, NoValidation},
361                 {"options",     "hidesplits",           &this->HideSplits,              DT_BOOLEAN, NoValidation},
362                 {"options",     "hidebans",             &this->HideBans,                DT_BOOLEAN, NoValidation},
363                 {"options",     "hidewhois",            &this->HideWhoisServer,         DT_CHARPTR, NoValidation},
364                 {"options",     "tempdir",              &this->TempDir,                 DT_CHARPTR, ValidateTempDir},
365                 {NULL}
366         };
367
368         //
369         char timeout[MAXBUF],flood[MAXBUF],pfreq[MAXBUF],thold[MAXBUF],sqmax[MAXBUF],rqmax[MAXBUF];
370         char localmax[MAXBUF],globalmax[MAXBUF],ServName[MAXBUF],Value[MAXBUF];
371
372         ConnectClass c;
373         std::stringstream errstr;
374         
375         include_stack.clear();
376
377         if (!LoadConf(CONFIG_FILE,&Config->config_f,&errstr))
378         {
379                 errstr.seekg(0);
380                 log(DEFAULT,"There were errors in your configuration:\n%s",errstr.str().c_str());
381
382                 if (bail)
383                 {
384                         printf("There were errors in your configuration:\n%s",errstr.str().c_str());
385                         Exit(0);
386                 }
387                 else
388                 {
389                         char dataline[1024];
390
391                         if (user)
392                         {
393                                 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
394                                 while (!errstr.eof())
395                                 {
396                                         errstr.getline(dataline,1024);
397                                         WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline);
398                                 }
399                         }
400                         else
401                         {
402                                 WriteOpers("There were errors in the configuration file:");
403                                 while (!errstr.eof())
404                                 {
405                                         errstr.getline(dataline,1024);
406                                         WriteOpers(dataline);
407                                 }
408                         }
409
410                         return;
411                 }
412         }
413
414         /* Check we dont have more than one of singular tags
415          */
416         if (!CheckOnce("server",bail,user) || !CheckOnce("admin",bail,user) || !CheckOnce("files",bail,user)
417                 || !CheckOnce("power",bail,user) || !CheckOnce("options",bail,user) || !CheckOnce("pid",bail,user))
418         {
419                 return;
420         }
421
422         char* convert;
423         for (int Index = 0; Values[Index].tag; Index++)
424         {
425                 int* val_i = (int*) Values[Index].val;
426                 char* val_c = (char*) Values[Index].val;
427
428                 switch (Values[Index].datatype)
429                 {
430                         case DT_CHARPTR:
431                                 ConfValue(Values[Index].tag, Values[Index].value, 0, val_c, &this->config_f);
432                         break;
433
434                         case DT_INTEGER:
435                                 convert = new char[MAXBUF];
436                                 ConfValue(Values[Index].tag, Values[Index].value, 0, convert, &this->config_f);
437                                 *val_i = atoi(convert);
438                                 delete[] convert;
439                         break;
440
441                         case DT_BOOLEAN:
442                                 convert = new char[MAXBUF];
443                                 ConfValue(Values[Index].tag, Values[Index].value, 0, convert, &this->config_f);
444                                 *val_i = ((*convert == tolower('y')) || (*convert == tolower('t')) || (*convert == '1'));
445                                 delete[] convert;
446                         break;
447
448                         case DT_NOTHING:
449                         break;
450                 }
451
452                 Values[Index].validation_function(Values[Index].tag, Values[Index].value, Values[Index].val);
453         }
454
455         log(DEFAULT,"Reading connect classes...");
456         Classes.clear();
457
458         for (int i = 0; i < ConfValueEnum("connect",&Config->config_f); i++)
459         {
460                 *Value = 0;
461                 ConfValue("connect","allow",i,Value,&Config->config_f);
462                 ConfValue("connect","timeout",i,timeout,&Config->config_f);
463                 ConfValue("connect","flood",i,flood,&Config->config_f);
464                 ConfValue("connect","pingfreq",i,pfreq,&Config->config_f);
465                 ConfValue("connect","threshold",i,thold,&Config->config_f);
466                 ConfValue("connect","sendq",i,sqmax,&Config->config_f);
467                 ConfValue("connect","recvq",i,rqmax,&Config->config_f);
468                 ConfValue("connect","localmax",i,localmax,&Config->config_f);
469                 ConfValue("connect","globalmax",i,globalmax,&Config->config_f);
470
471                 if (*Value)
472                 {
473                         c.host = Value;
474                         c.type = CC_ALLOW;
475                         strlcpy(Value,"",MAXBUF);
476                         ConfValue("connect","password",i,Value,&Config->config_f);
477                         c.pass = Value;
478                         c.registration_timeout = 90; // default is 2 minutes
479                         c.pingtime = 120;
480                         c.flood = atoi(flood);
481                         c.threshold = 5;
482                         c.sendqmax = 262144; // 256k
483                         c.recvqmax = 4096;   // 4k
484                         c.maxlocal = 3;
485                         c.maxglobal = 3;
486
487                         if (atoi(localmax)>0)
488                         {
489                                 c.maxlocal = atoi(localmax);
490                         }
491
492                         if (atoi(globalmax)>0)
493                         {
494                                 c.maxglobal = atoi(globalmax);
495                         }
496
497                         if (atoi(thold)>0)
498                         {
499                                 c.threshold = atoi(thold);
500                         }
501                         else
502                         {
503                                 c.threshold = 1;
504                                 c.flood = 999;
505                                 log(DEFAULT,"Warning: Connect allow line '%s' has no flood/threshold settings. Setting this tag to 999 lines in 1 second.",c.host.c_str());
506                         }
507
508                         if (atoi(sqmax)>0)
509                         {
510                                 c.sendqmax = atoi(sqmax);
511                         }
512                         if (atoi(rqmax)>0)
513                         {
514                                 c.recvqmax = atoi(rqmax);
515                         }
516                         if (atoi(timeout)>0)
517                         {
518                                 c.registration_timeout = atoi(timeout);
519                         }
520                         if (atoi(pfreq)>0)
521                         {
522                                 c.pingtime = atoi(pfreq);
523                         }
524
525                         Classes.push_back(c);
526                 }
527                 else
528                 {
529                         ConfValue("connect","deny",i,Value,&Config->config_f);
530                         c.host = Value;
531                         c.type = CC_DENY;
532                         Classes.push_back(c);
533                         log(DEBUG,"Read connect class type DENY, host=%s",c.host.c_str());
534                 }
535         }
536
537         Config->ulines.clear();
538
539         for (int i = 0; i < ConfValueEnum("uline",&Config->config_f); i++)
540         {   
541                 ConfValue("uline","server",i,ServName,&Config->config_f);
542                 {
543                         log(DEBUG,"Read ULINE '%s'",ServName);
544                         Config->ulines.push_back(ServName);
545                 }
546         }
547
548         maxbans.clear();
549         char CM1[MAXBUF],CM2[MAXBUF];
550
551         for (int count = 0; count < Config->ConfValueEnum("banlist",&Config->config_f); count++)
552         {
553                 Config->ConfValue("banlist","chan",count,CM1,&Config->config_f);
554                 Config->ConfValue("banlist","limit",count,CM2,&Config->config_f);
555                 maxbans[CM1] = atoi(CM2);
556         }
557
558         ReadClassesAndTypes();
559         log(DEFAULT,"Reading K lines,Q lines and Z lines from config...");
560         read_xline_defaults();
561         log(DEFAULT,"Applying K lines, Q lines and Z lines...");
562         apply_lines(APPLY_ALL);
563
564         ConfValue("pid","file",0,Config->PID,&Config->config_f);
565         // write once here, to try it out and make sure its ok
566         WritePID(Config->PID);
567
568         log(DEFAULT,"Done reading configuration file, InspIRCd is now starting.");
569         if (!bail)
570         {
571                 log(DEFAULT,"Adding and removing modules due to rehash...");
572
573                 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
574
575                 // store the old module names
576                 for (std::vector<std::string>::iterator t = module_names.begin(); t != module_names.end(); t++)
577                 {
578                         old_module_names.push_back(*t);
579                 }
580
581                 // get the new module names
582                 for (int count2 = 0; count2 < ConfValueEnum("module",&Config->config_f); count2++)
583                 {
584                         ConfValue("module","name",count2,Value,&Config->config_f);
585                         new_module_names.push_back(Value);
586                 }
587
588                 // now create a list of new modules that are due to be loaded
589                 // and a seperate list of modules which are due to be unloaded
590                 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
591                 {
592                         bool added = true;
593
594                         for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
595                         {
596                                 if (*old == *_new)
597                                         added = false;
598                         }
599
600                         if (added)
601                                 added_modules.push_back(*_new);
602                 }
603
604                 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
605                 {
606                         bool removed = true;
607                         for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
608                         {
609                                 if (*newm == *oldm)
610                                         removed = false;
611                         }
612
613                         if (removed)
614                                 removed_modules.push_back(*oldm);
615                 }
616
617                 /*
618                  * now we have added_modules, a vector of modules to be loaded,
619                  * and removed_modules, a vector of modules
620                  * to be removed.
621                  */
622                 int rem = 0, add = 0;
623                 if (!removed_modules.empty())
624                         for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
625                         {
626                                 if (ServerInstance->UnloadModule(removing->c_str()))
627                                 {
628                                         WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
629
630                                         if (user)
631                                                 WriteServ(user->fd,"973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
632
633                                         rem++;
634                                 }
635                                 else
636                                 {
637                                         if (user)
638                                                 WriteServ(user->fd,"972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ServerInstance->ModuleError());
639                                 }
640                         }
641
642                 if (!added_modules.empty())
643                 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
644                 {
645                         if (ServerInstance->LoadModule(adding->c_str()))
646                         {
647                                 WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
648
649                                 if (user)
650                                         WriteServ(user->fd,"975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
651
652                                 add++;
653                         }
654                         else
655                         {
656                                 if (user)
657                                         WriteServ(user->fd,"974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ServerInstance->ModuleError());
658                         }
659                 }
660
661                 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());
662         }
663 }
664
665
666 void Exit (int status)
667 {
668         if (Config->log_file)
669                 fclose(Config->log_file);
670         send_error("Server shutdown.");
671         exit (status);
672 }
673
674 void Killed(int status)
675 {
676         if (Config->log_file)
677                 fclose(Config->log_file);
678         send_error("Server terminated.");
679         exit(status);
680 }
681
682 char* CleanFilename(char* name)
683 {
684         char* p = name + strlen(name);
685         while ((p != name) && (*p != '/')) p--;
686         return (p != name ? ++p : p);
687 }
688
689
690 void Rehash(int status)
691 {
692         WriteOpers("Rehashing config file %s due to SIGHUP",CleanFilename(CONFIG_FILE));
693         fclose(Config->log_file);
694         OpenLog(NULL,0);
695         Config->Read(false,NULL);
696         FOREACH_MOD(I_OnRehash,OnRehash(""));
697 }
698
699
700
701 void Start (void)
702 {
703         printf("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
704         printf("(C) ChatSpike Development team.\033[0m\n\n");
705         printf("Developers:\033[1;32m Brain, FrostyCoolSlug, w00t, Om\033[0m\n");
706         printf("Others:\033[1;32m See /INFO Output\033[0m\n");
707         printf("Name concept:\033[1;32m   Lord_Zathras\033[0m\n\n");
708 }
709
710 void WritePID(std::string filename)
711 {
712         ofstream outfile(filename.c_str());
713         if (outfile.is_open())
714         {
715                 outfile << getpid();
716                 outfile.close();
717         }
718         else
719         {
720                 printf("Failed to write PID-file '%s', exiting.\n",filename.c_str());
721                 log(DEFAULT,"Failed to write PID-file '%s', exiting.",filename.c_str());
722                 Exit(0);
723         }
724 }
725
726 void SetSignals()
727 {
728         signal (SIGALRM, SIG_IGN);
729         signal (SIGHUP, Rehash);
730         signal (SIGPIPE, SIG_IGN);
731         signal (SIGTERM, Exit);
732         signal (SIGSEGV, Error);
733 }
734
735
736 int DaemonSeed (void)
737 {
738         int childpid;
739         if ((childpid = fork ()) < 0)
740                 return (ERROR);
741         else if (childpid > 0)
742         {
743                 /* We wait a few seconds here, so that the shell prompt doesnt come back over the output */
744                 sleep(6);
745                 exit (0);
746         }
747         setsid ();
748         umask (007);
749         printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
750
751         if (Config->unlimitcore)
752         {
753                 rlimit rl;
754                 if (getrlimit(RLIMIT_CORE, &rl) == -1)
755                 {
756                         log(DEFAULT,"Failed to getrlimit()!");
757                         return(FALSE);
758                 }
759                 else
760                 {
761                         rl.rlim_cur = rl.rlim_max;
762                         if (setrlimit(RLIMIT_CORE, &rl) == -1)
763                                 log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
764                 }
765         }
766   
767         return (TRUE);
768 }
769
770
771 /* Make Sure Modules Are Avaliable!
772  * (BugFix By Craig.. See? I do work! :p)
773  * Modified by brain, requires const char*
774  * to work with other API functions
775  */
776
777 bool FileExists (const char* file)
778 {
779         FILE *input;
780         if ((input = fopen (file, "r")) == NULL)
781         {
782                 return(false);
783         }
784         else
785         {
786                 fclose (input);
787                 return(true);
788         }
789 }
790
791 /* ConfProcess does the following things to a config line in the following order:
792  *
793  * Processes the line for syntax errors as shown below
794  *  (1) Line void of quotes or equals (a malformed, illegal tag format)
795  *  (2) Odd number of quotes on the line indicating a missing quote
796  *  (3) number of equals signs not equal to number of quotes / 2 (missing an equals sign)
797  *  (4) Spaces between the opening bracket (<) and the keyword
798  *  (5) Spaces between a keyword and an equals sign
799  *  (6) Spaces between an equals sign and a quote
800  * Removes trailing spaces
801  * Removes leading spaces
802  * Converts tabs to spaces
803  * Turns multiple spaces that are outside of quotes into single spaces
804  */
805
806 std::string ServerConfig::ConfProcess(char* buffer, long linenumber, std::stringstream* errorstream, bool &error, std::string filename)
807 {
808         long number_of_quotes = 0;
809         long number_of_equals = 0;
810         bool has_open_bracket = false;
811         bool in_quotes = false;
812         error = false;
813         if (!buffer)
814         {
815                 return "";
816         }
817         // firstly clean up the line by stripping spaces from the start and end and converting tabs to spaces
818         for (char* d = buffer; *d; d++)
819                 if (*d == 9)
820                         *d = ' ';
821         while (*buffer == ' ') buffer++;
822         while ((buffer[strlen(buffer)-1] == ' ') && (*buffer)) buffer[strlen(buffer)-1] = '\0';
823
824         // empty lines are syntactically valid, as are comments
825         if (!(*buffer) || buffer[0] == '#')
826                 return "";
827
828         for (unsigned int c = 0; c < strlen(buffer); c++)
829         {
830                 // convert all spaces that are OUTSIDE quotes into hardspace (0xA0) as this will make them easier to
831                 // search and replace later :)
832                 if ((!in_quotes) && (buffer[c] == ' '))
833                         buffer[c] = '\xA0';
834                 if ((buffer[c] == '<') && (!in_quotes))
835                 {
836                         has_open_bracket = true;
837                         if (strlen(buffer) == 1)
838                         {
839                                 *errorstream << "Tag without identifier at " << filename << ":" << linenumber << endl;
840                                 error = true;
841                                 return "";
842                         }
843                         else if ((tolower(buffer[c+1]) < 'a') || (tolower(buffer[c+1]) > 'z'))
844                         {
845                                 *errorstream << "Invalid characters in identifier at " << filename << ":" << linenumber << endl;
846                                 error = true;
847                                 return "";
848                         }
849                 }
850                 if (buffer[c] == '"')
851                 {
852                         number_of_quotes++;
853                         in_quotes = (!in_quotes);
854                 }
855                 if ((buffer[c] == '=') && (!in_quotes))
856                 {
857                         number_of_equals++;
858                         if (strlen(buffer) == c)
859                         {
860                                 *errorstream << "Variable without a value at " << filename << ":" << linenumber << endl;
861                                 error = true;
862                                 return "";
863                         }
864                         else if (buffer[c+1] != '"')
865                         {
866                                 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
867                                 error = true;
868                                 return "";
869                         }
870                         else if (!c)
871                         {
872                                 *errorstream << "Value without a variable (line starts with '=') at " << filename << ":" << linenumber << endl;
873                                 error = true;
874                                 return "";
875                         }
876                         else if (buffer[c-1] == '\xA0')
877                         {
878                                 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
879                                 error = true;
880                                 return "";
881                         }
882                 }
883         }
884         // no quotes, and no equals. something freaky.
885         if ((!number_of_quotes) || (!number_of_equals) && (strlen(buffer)>2) && (buffer[0]=='<'))
886         {
887                 *errorstream << "Malformed tag at " << filename << ":" << linenumber << endl;
888                 error = true;
889                 return "";
890         }
891         // odd number of quotes. thats just wrong.
892         if ((number_of_quotes % 2) != 0)
893         {
894                 *errorstream << "Missing \" at " << filename << ":" << linenumber << endl;
895                 error = true;
896                 return "";
897         }
898         if (number_of_equals < (number_of_quotes/2))
899         {
900                 *errorstream << "Missing '=' at " << filename << ":" << linenumber << endl;
901         }
902         if (number_of_equals > (number_of_quotes/2))
903         {
904                 *errorstream << "Too many '=' at " << filename << ":" << linenumber << endl;
905         }
906
907         std::string parsedata = buffer;
908         // turn multispace into single space
909         while (parsedata.find("\xA0\xA0") != std::string::npos)
910         {
911                 parsedata.erase(parsedata.find("\xA0\xA0"),1);
912         }
913
914         // turn our hardspace back into softspace
915         for (unsigned int d = 0; d < parsedata.length(); d++)
916         {
917                 if (parsedata[d] == '\xA0')
918                         parsedata[d] = ' ';
919         }
920
921         // and we're done, the line is fine!
922         return parsedata;
923 }
924
925 int ServerConfig::fgets_safe(char* buffer, size_t maxsize, FILE* &file)
926 {
927         char c_read = '\0';
928         unsigned int bufptr = 0;
929         while ((!feof(file)) && (c_read != '\n') && (c_read != '\r') && (bufptr < maxsize))
930         {
931                 c_read = fgetc(file);
932                 if ((c_read != '\n') && (c_read != '\r'))
933                         buffer[bufptr++] = c_read;
934         }
935         buffer[bufptr] = '\0';
936         return bufptr;
937 }
938
939 bool ServerConfig::LoadConf(const char* filename, std::stringstream *target, std::stringstream* errorstream)
940 {
941         target->str("");
942         errorstream->str("");
943         long linenumber = 1;
944         // first, check that the file exists before we try to do anything with it
945         if (!FileExists(filename))
946         {
947                 *errorstream << "File " << filename << " not found." << endl;
948                 return false;
949         }
950         // Fix the chmod of the file to restrict it to the current user and group
951         chmod(filename,0600);
952         for (unsigned int t = 0; t < include_stack.size(); t++)
953         {
954                 if (std::string(filename) == include_stack[t])
955                 {
956                         *errorstream << "File " << filename << " is included recursively (looped inclusion)." << endl;
957                         return false;
958                 }
959         }
960         include_stack.push_back(filename);
961         // now open it
962         FILE* conf = fopen(filename,"r");
963         char buffer[MAXBUF];
964         if (conf)
965         {
966                 while (!feof(conf))
967                 {
968                         if (fgets_safe(buffer, MAXBUF, conf))
969                         {
970                                 if ((!feof(conf)) && (buffer) && (strlen(buffer)))
971                                 {
972                                         if ((buffer[0] != '#') && (buffer[0] != '\r')  && (buffer[0] != '\n'))
973                                         {
974                                                 if (!strncmp(buffer,"<include file=\"",15))
975                                                 {
976                                                         char* buf = buffer;
977                                                         char confpath[10240],newconf[10240];
978                                                         // include file directive
979                                                         buf += 15;      // advance to filename
980                                                         for (unsigned int j = 0; j < strlen(buf); j++)
981                                                         {
982                                                                 if (buf[j] == '\\')
983                                                                         buf[j] = '/';
984                                                                 if (buf[j] == '"')
985                                                                 {
986                                                                         buf[j] = '\0';
987                                                                         break;
988                                                                 }
989                                                         }
990                                                         log(DEBUG,"Opening included file '%s'",buf);
991                                                         if (*buf != '/')
992                                                         {
993                                                                 strlcpy(confpath,CONFIG_FILE,10240);
994                                                                 if (strstr(confpath,"/inspircd.conf"))
995                                                                 {
996                                                                         // leaves us with just the path
997                                                                         *(strstr(confpath,"/inspircd.conf")) = '\0';
998                                                                 }
999                                                                 snprintf(newconf,10240,"%s/%s",confpath,buf);
1000                                                         }
1001                                                         else strlcpy(newconf,buf,10240);
1002                                                         std::stringstream merge(stringstream::in | stringstream::out);
1003                                                         // recursively call LoadConf and get the new data, use the same errorstream
1004                                                         if (LoadConf(newconf, &merge, errorstream))
1005                                                         {
1006                                                                 // append to the end of the file
1007                                                                 std::string newstuff = merge.str();
1008                                                                 *target << newstuff;
1009                                                         }
1010                                                         else
1011                                                         {
1012                                                                 // the error propogates up to its parent recursively
1013                                                                 // causing the config reader to bail at the top level.
1014                                                                 fclose(conf);
1015                                                                 return false;
1016                                                         }
1017                                                 }
1018                                                 else
1019                                                 {
1020                                                         bool error = false;
1021                                                         std::string data = this->ConfProcess(buffer,linenumber++,errorstream,error,filename);
1022                                                         if (error)
1023                                                         {
1024                                                                 return false;
1025                                                         }
1026                                                         *target << data;
1027                                                 }
1028                                         }
1029                                         else linenumber++;
1030                                 }
1031                         }
1032                 }
1033                 fclose(conf);
1034         }
1035         target->seekg(0);
1036         return true;
1037 }
1038
1039 /* Counts the number of tags of a certain type within the config file, e.g. to enumerate opers */
1040
1041 int ServerConfig::EnumConf(std::stringstream *config, const char* tag)
1042 {
1043         int ptr = 0;
1044         char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
1045         int in_token, in_quotes, tptr, idx = 0;
1046
1047         std::string x = config->str();
1048         const char* buf = x.c_str();
1049         long bptr = 0;
1050         long len = config->str().length();
1051         
1052         ptr = 0;
1053         in_token = 0;
1054         in_quotes = 0;
1055         lastc = '\0';
1056         while (bptr<len)
1057         {
1058                 lastc = c;
1059                 c = buf[bptr++];
1060                 if ((c == '#') && (lastc == '\n'))
1061                 {
1062                         while ((c != '\n') && (bptr<len))
1063                         {
1064                                 lastc = c;
1065                                 c = buf[bptr++];
1066                         }
1067                 }
1068                 if ((c == '<') && (!in_quotes))
1069                 {
1070                         tptr = 0;
1071                         in_token = 1;
1072                         do {
1073                                 c = buf[bptr++];
1074                                 if (c != ' ')
1075                                 {
1076                                         c_tag[tptr++] = c;
1077                                         c_tag[tptr] = '\0';
1078                                 }
1079                         } while (c != ' ');
1080                 }
1081                 if (c == '"')
1082                 {
1083                         in_quotes = (!in_quotes);
1084                 }
1085                 if ((c == '>') && (!in_quotes))
1086                 {
1087                         in_token = 0;
1088                         if (!strcmp(c_tag,tag))
1089                         {
1090                                 /* correct tag, but wrong index */
1091                                 idx++;
1092                         }
1093                         c_tag[0] = '\0';
1094                         buffer[0] = '\0';
1095                         ptr = 0;
1096                         tptr = 0;
1097                 }
1098                 if (c != '>')
1099                 {
1100                         if ((in_token) && (c != '\n') && (c != '\r'))
1101                         {
1102                                 buffer[ptr++] = c;
1103                                 buffer[ptr] = '\0';
1104                         }
1105                 }
1106         }
1107         return idx;
1108 }
1109
1110 /* Counts the number of values within a certain tag */
1111
1112 int ServerConfig::EnumValues(std::stringstream *config, const char* tag, int index)
1113 {
1114         int ptr = 0;
1115         char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
1116         int in_token, in_quotes, tptr, idx = 0;
1117         
1118         bool correct_tag = false;
1119         int num_items = 0;
1120
1121         const char* buf = config->str().c_str();
1122         long bptr = 0;
1123         long len = strlen(buf);
1124         
1125         ptr = 0;
1126         in_token = 0;
1127         in_quotes = 0;
1128         lastc = '\0';
1129         while (bptr<len)
1130         {
1131                 lastc = c;
1132                 c = buf[bptr++];
1133                 if ((c == '#') && (lastc == '\n'))
1134                 {
1135                         while ((c != '\n') && (bptr<len))
1136                         {
1137                                 lastc = c;
1138                                 c = buf[bptr++];
1139                         }
1140                 }
1141                 if ((c == '<') && (!in_quotes))
1142                 {
1143                         tptr = 0;
1144                         in_token = 1;
1145                         do {
1146                                 c = buf[bptr++];
1147                                 if (c != ' ')
1148                                 {
1149                                         c_tag[tptr++] = c;
1150                                         c_tag[tptr] = '\0';
1151                                         
1152                                         if ((!strcmp(c_tag,tag)) && (idx == index))
1153                                         {
1154                                                 correct_tag = true;
1155                                         }
1156                                 }
1157                         } while (c != ' ');
1158                 }
1159                 if (c == '"')
1160                 {
1161                         in_quotes = (!in_quotes);
1162                 }
1163                 
1164                 if ( (correct_tag) && (!in_quotes) && ( (c == ' ') || (c == '\n') || (c == '\r') ) )
1165                 {
1166                         num_items++;
1167                 }
1168                 if ((c == '>') && (!in_quotes))
1169                 {
1170                         in_token = 0;
1171                         if (correct_tag)
1172                                 correct_tag = false;
1173                         if (!strcmp(c_tag,tag))
1174                         {
1175                                 /* correct tag, but wrong index */
1176                                 idx++;
1177                         }
1178                         c_tag[0] = '\0';
1179                         buffer[0] = '\0';
1180                         ptr = 0;
1181                         tptr = 0;
1182                 }
1183                 if (c != '>')
1184                 {
1185                         if ((in_token) && (c != '\n') && (c != '\r'))
1186                         {
1187                                 buffer[ptr++] = c;
1188                                 buffer[ptr] = '\0';
1189                         }
1190                 }
1191         }
1192         return num_items+1;
1193 }
1194
1195
1196
1197 int ServerConfig::ConfValueEnum(char* tag, std::stringstream* config)
1198 {
1199         return EnumConf(config,tag);
1200 }
1201
1202
1203
1204 /* Retrieves a value from the config file. If there is more than one value of the specified
1205  * key and section (e.g. for opers etc) then the index value specifies which to retreive, e.g.
1206  *
1207  * ConfValue("oper","name",2,result);
1208  */
1209
1210 int ServerConfig::ReadConf(std::stringstream *config, const char* tag, const char* var, int index, char *result)
1211 {
1212         int ptr = 0;
1213         char buffer[65535], c_tag[MAXBUF], c, lastc;
1214         int in_token, in_quotes, tptr, idx = 0;
1215         char* key;
1216
1217         std::string x = config->str();
1218         const char* buf = x.c_str();
1219         long bptr = 0;
1220         long len = config->str().length();
1221         
1222         ptr = 0;
1223         in_token = 0;
1224         in_quotes = 0;
1225         lastc = '\0';
1226         c_tag[0] = '\0';
1227         buffer[0] = '\0';
1228         while (bptr<len)
1229         {
1230                 lastc = c;
1231                 c = buf[bptr++];
1232                 // FIX: Treat tabs as spaces
1233                 if (c == 9)
1234                         c = 32;
1235                 if ((c == '<') && (!in_quotes))
1236                 {
1237                         tptr = 0;
1238                         in_token = 1;
1239                         do {
1240                                 c = buf[bptr++];
1241                                 if (c != ' ')
1242                                 {
1243                                         c_tag[tptr++] = c;
1244                                         c_tag[tptr] = '\0';
1245                                 }
1246                         // FIX: Tab can follow a tagname as well as space.
1247                         } while ((c != ' ') && (c != 9));
1248                 }
1249                 if (c == '"')
1250                 {
1251                         in_quotes = (!in_quotes);
1252                 }
1253                 if ((c == '>') && (!in_quotes))
1254                 {
1255                         in_token = 0;
1256                         if (idx == index)
1257                         {
1258                                 if (!strcmp(c_tag,tag))
1259                                 {
1260                                         if ((buffer) && (c_tag) && (var))
1261                                         {
1262                                                 key = strstr(buffer,var);
1263                                                 if (!key)
1264                                                 {
1265                                                         /* value not found in tag */
1266                                                         *result = 0;
1267                                                         return 0;
1268                                                 }
1269                                                 else
1270                                                 {
1271                                                         key+=strlen(var);
1272                                                         while (*key !='"')
1273                                                         {
1274                                                                 if (!*key)
1275                                                                 {
1276                                                                         /* missing quote */
1277                                                                         *result = 0;
1278                                                                         return 0;
1279                                                                 }
1280                                                                 key++;
1281                                                         }
1282                                                         key++;
1283                                                         for (unsigned j = 0; j < strlen(key); j++)
1284                                                         {
1285                                                                 if (key[j] == '"')
1286                                                                 {
1287                                                                         key[j] = '\0';
1288                                                                 }
1289                                                         }
1290                                                         strlcpy(result,key,MAXBUF);
1291                                                         return 1;
1292                                                 }
1293                                         }
1294                                 }
1295                         }
1296                         if (!strcmp(c_tag,tag))
1297                         {
1298                                 /* correct tag, but wrong index */
1299                                 idx++;
1300                         }
1301                         c_tag[0] = '\0';
1302                         buffer[0] = '\0';
1303                         ptr = 0;
1304                         tptr = 0;
1305                 }
1306                 if (c != '>')
1307                 {
1308                         if ((in_token) && (c != '\n') && (c != '\r'))
1309                         {
1310                                 buffer[ptr++] = c;
1311                                 buffer[ptr] = '\0';
1312                         }
1313                 }
1314         }
1315         *result = 0; // value or its tag not found at all
1316         return 0;
1317 }
1318
1319
1320
1321 int ServerConfig::ConfValue(char* tag, char* var, int index, char *result,std::stringstream *config)
1322 {
1323         ReadConf(config, tag, var, index, result);
1324         return 0;
1325 }
1326
1327
1328
1329 // This will bind a socket to a port. It works for UDP/TCP
1330 int BindSocket (int sockfd, struct sockaddr_in client, struct sockaddr_in server, int port, char* addr)
1331 {
1332         memset((char *)&server,0,sizeof(server));
1333         struct in_addr addy;
1334         inet_aton(addr,&addy);
1335         server.sin_family = AF_INET;
1336         if (!*addr)
1337         {
1338                 server.sin_addr.s_addr = htonl(INADDR_ANY);
1339         }
1340         else
1341         {
1342                 server.sin_addr = addy;
1343         }
1344         server.sin_port = htons(port);
1345         if (bind(sockfd,(struct sockaddr*)&server,sizeof(server))<0)
1346         {
1347                 return(ERROR);
1348         }
1349         else
1350         {
1351                 listen(sockfd, Config->MaxConn);
1352                 return(TRUE);
1353         }
1354 }
1355
1356
1357 // Open a TCP Socket
1358 int OpenTCPSocket (void)
1359 {
1360         int sockfd;
1361         int on = 1;
1362         struct linger linger = { 0 };
1363   
1364         if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) < 0)
1365                 return (ERROR);
1366         else
1367         {
1368                 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on));
1369                 /* This is BSD compatible, setting l_onoff to 0 is *NOT* http://web.irc.org/mla/ircd-dev/msg02259.html */
1370                 linger.l_onoff = 1;
1371                 linger.l_linger = 1;
1372                 setsockopt(sockfd, SOL_SOCKET, SO_LINGER, (const char*)&linger,sizeof(linger));
1373                 return (sockfd);
1374         }
1375 }
1376
1377 int BindPorts()
1378 {
1379         char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
1380         sockaddr_in client,server;
1381         int clientportcount = 0;
1382         int BoundPortCount = 0;
1383
1384         for (int count = 0; count < Config->ConfValueEnum("bind",&Config->config_f); count++)
1385         {
1386                 Config->ConfValue("bind","port",count,configToken,&Config->config_f);
1387                 Config->ConfValue("bind","address",count,Addr,&Config->config_f);
1388                 Config->ConfValue("bind","type",count,Type,&Config->config_f);
1389
1390                 if ((!*Type) || (!strcmp(Type,"clients")))
1391                 {
1392                         // modules handle server bind types now
1393                         Config->ports[clientportcount] = atoi(configToken);
1394
1395                         // If the client put bind "*", this is an unrealism.
1396                         // We don't actually support this as documented, but
1397                         // i got fed up of people trying it, so now it converts
1398                         // it to an empty string meaning the same 'bind to all'.
1399                         if (*Addr == '*')
1400                                 *Addr = 0;
1401
1402                         strlcpy(Config->addrs[clientportcount],Addr,256);
1403                         clientportcount++;
1404                         log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
1405                 }
1406         }
1407
1408         int PortCount = clientportcount;
1409
1410         for (int count = 0; count < PortCount; count++)
1411         {
1412                 if ((openSockfd[BoundPortCount] = OpenTCPSocket()) == ERROR)
1413                 {
1414                         log(DEBUG,"InspIRCd: startup: bad fd %lu binding port [%s:%d]",(unsigned long)openSockfd[BoundPortCount],Config->addrs[count],(unsigned long)Config->ports[count]);
1415                         return(ERROR);
1416                 }
1417
1418                 if (BindSocket(openSockfd[BoundPortCount],client,server,Config->ports[count],Config->addrs[count]) == ERROR)
1419                 {
1420                         log(DEFAULT,"InspIRCd: startup: failed to bind port [%s:%lu]: %s",Config->addrs[count],(unsigned long)Config->ports[count],strerror(errno));
1421                 }
1422                 else
1423                 {
1424                         /* well we at least bound to one socket so we'll continue */
1425                         BoundPortCount++;
1426                 }
1427         }
1428
1429         /* if we didn't bind to anything then abort */
1430         if (!BoundPortCount)
1431         {
1432                 log(DEFAULT,"InspIRCd: startup: no ports bound, bailing!");
1433                 printf("\nERROR: Was not able to bind any of %lu ports! Please check your configuration.\n\n", (unsigned long)PortCount);
1434                 return (ERROR);
1435         }
1436
1437         return BoundPortCount;
1438 }
1439