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