]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/configreader.cpp
add <whowas> config option to control whowas behaviour. *may break*
[user/henk/code/inspircd.git] / src / configreader.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 #include "configreader.h"
18 #include <sstream>
19 #include <fstream>
20 #include "inspircd.h"
21 #include "xline.h"
22
23 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
24
25 ServerConfig::ServerConfig(InspIRCd* Instance) : ServerInstance(Instance)
26 {
27         this->ClearStack();
28         *TempDir = *ServerName = *Network = *ServerDesc = *AdminName = '\0';
29         *HideWhoisServer = *AdminEmail = *AdminNick = *diepass = *restartpass = '\0';
30         *CustomVersion = *motd = *rules = *PrefixQuit = *DieValue = *DNSServer = '\0';
31         *UserStats = *ModPath = *MyExecutable = *DisabledCommands = *PID = '\0';
32         log_file = NULL;
33         NoUserDns = forcedebug = OperSpyWhois = nofork = HideBans = HideSplits = false;
34         CycleHosts = writelog = AllowHalfop = true;
35         dns_timeout = DieDelay = 5;
36         MaxTargets = 20;
37         NetBufferSize = 10240;
38         SoftLimit = MAXCLIENTS;
39         MaxConn = SOMAXCONN;
40         MaxWhoResults = 100;
41         debugging = 0;
42         LogLevel = DEFAULT;
43         maxbans.clear();
44         WhoWasGroupSize = 10;
45         WhoWasMaxGroups = WhoWasGroupSize * MAXCLIENTS;
46         WhoWasMaxKeep = 3600*24*3; // 3 days
47 }
48
49 void ServerConfig::ClearStack()
50 {
51         include_stack.clear();
52 }
53
54 Module* ServerConfig::GetIOHook(int port)
55 {
56         std::map<int,Module*>::iterator x = IOHookModule.find(port);
57         return (x != IOHookModule.end() ? x->second : NULL);
58 }
59
60 bool ServerConfig::AddIOHook(int port, Module* iomod)
61 {
62         if (!GetIOHook(port))
63         {
64                 IOHookModule[port] = iomod;
65                 return true;
66         }
67         else
68         {
69                 ModuleException err("Port already hooked by another module");
70                 throw(err);
71                 return false;
72         }
73 }
74
75 bool ServerConfig::DelIOHook(int port)
76 {
77         std::map<int,Module*>::iterator x = IOHookModule.find(port);
78         if (x != IOHookModule.end())
79         {
80                 IOHookModule.erase(x);
81                 return true;
82         }
83         return false;
84 }
85
86 bool ServerConfig::CheckOnce(char* tag, bool bail, userrec* user)
87 {
88         int count = ConfValueEnum(this->config_data, tag);
89         
90         if (count > 1)
91         {
92                 if (bail)
93                 {
94                         printf("There were errors in your configuration:\nYou have more than one <%s> tag, this is not permitted.\n",tag);
95                         InspIRCd::Exit(ERROR);
96                 }
97                 else
98                 {
99                         if (user)
100                         {
101                                 user->WriteServ("There were errors in your configuration:");
102                                 user->WriteServ("You have more than one <%s> tag, this is not permitted.\n",tag);
103                         }
104                         else
105                         {
106                                 ServerInstance->WriteOpers("There were errors in the configuration file:");
107                                 ServerInstance->WriteOpers("You have more than one <%s> tag, this is not permitted.\n",tag);
108                         }
109                 }
110                 return false;
111         }
112         if (count < 1)
113         {
114                 if (bail)
115                 {
116                         printf("There were errors in your configuration:\nYou have not defined a <%s> tag, this is required.\n",tag);
117                         InspIRCd::Exit(ERROR);
118                 }
119                 else
120                 {
121                         if (user)
122                         {
123                                 user->WriteServ("There were errors in your configuration:");
124                                 user->WriteServ("You have not defined a <%s> tag, this is required.",tag);
125                         }
126                         else
127                         {
128                                 ServerInstance->WriteOpers("There were errors in the configuration file:");
129                                 ServerInstance->WriteOpers("You have not defined a <%s> tag, this is required.",tag);
130                         }
131                 }
132                 return false;
133         }
134         return true;
135 }
136
137 bool NoValidation(ServerConfig* conf, const char* tag, const char* value, void* data)
138 {
139         conf->GetInstance()->Log(DEBUG,"No validation for <%s:%s>",tag,value);
140         return true;
141 }
142
143 bool ValidateTempDir(ServerConfig* conf, const char* tag, const char* value, void* data)
144 {
145         char* x = (char*)data;
146         if (!*x)
147                 strlcpy(x,"/tmp",1024);
148         return true;
149 }
150  
151 bool ValidateMaxTargets(ServerConfig* conf, const char* tag, const char* value, void* data)
152 {
153         int* x = (int*)data;
154         if ((*x < 0) || (*x > 31))
155         {
156                 conf->GetInstance()->Log(DEFAULT,"WARNING: <options:maxtargets> value is greater than 31 or less than 0, set to 20.");
157                 *x = 20;
158         }
159         return true;
160 }
161
162 bool ValidateSoftLimit(ServerConfig* conf, const char* tag, const char* value, void* data)
163 {
164         int* x = (int*)data;    
165         if ((*x < 1) || (*x > MAXCLIENTS))
166         {
167                 conf->GetInstance()->Log(DEFAULT,"WARNING: <options:softlimit> value is greater than %d or less than 0, set to %d.",MAXCLIENTS,MAXCLIENTS);
168                 *x = MAXCLIENTS;
169         }
170         return true;
171 }
172
173 bool ValidateMaxConn(ServerConfig* conf, const char* tag, const char* value, void* data)
174 {
175         int* x = (int*)data;    
176         if (*x > SOMAXCONN)
177                 conf->GetInstance()->Log(DEFAULT,"WARNING: <options:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
178         if (!*x)
179                 *x = SOMAXCONN;
180         return true;
181 }
182
183 bool ValidateDnsTimeout(ServerConfig* conf, const char* tag, const char* value, void* data)
184 {
185         int* x = (int*)data;
186         if (!*x)
187                 *x = 5;
188         return true;
189 }
190
191 bool InitializeDisabledCommands(const char* data, InspIRCd* ServerInstance)
192 {
193         std::stringstream dcmds(data);
194         std::string thiscmd;
195
196         /* Enable everything first */
197         for (nspace::hash_map<std::string,command_t*>::iterator x = ServerInstance->Parser->cmdlist.begin(); x != ServerInstance->Parser->cmdlist.end(); x++)
198                 x->second->Disable(false);
199
200         /* Now disable all the ones which the user wants disabled */
201         while (dcmds >> thiscmd)
202         {
203                 nspace::hash_map<std::string,command_t*>::iterator cm = ServerInstance->Parser->cmdlist.find(thiscmd);
204                 if (cm != ServerInstance->Parser->cmdlist.end())
205                 {
206                         ServerInstance->Log(DEBUG,"Disabling command '%s'",cm->second->command.c_str());
207                         cm->second->Disable(true);
208                 }
209         }
210         return true;
211 }
212
213 bool ValidateDnsServer(ServerConfig* conf, const char* tag, const char* value, void* data)
214 {
215         char* x = (char*)data;
216         if (!*x)
217         {
218                 // attempt to look up their nameserver from /etc/resolv.conf
219                 conf->GetInstance()->Log(DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
220                 ifstream resolv("/etc/resolv.conf");
221                 std::string nameserver;
222                 bool found_server = false;
223
224                 if (resolv.is_open())
225                 {
226                         while (resolv >> nameserver)
227                         {
228                                 if ((nameserver == "nameserver") && (!found_server))
229                                 {
230                                         resolv >> nameserver;
231                                         strlcpy(x,nameserver.c_str(),MAXBUF);
232                                         found_server = true;
233                                         conf->GetInstance()->Log(DEFAULT,"<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",nameserver.c_str());
234                                 }
235                         }
236
237                         if (!found_server)
238                         {
239                                 conf->GetInstance()->Log(DEFAULT,"/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
240                                 strlcpy(x,"127.0.0.1",MAXBUF);
241                         }
242                 }
243                 else
244                 {
245                         conf->GetInstance()->Log(DEFAULT,"/etc/resolv.conf can't be opened! Defaulting to nameserver '127.0.0.1'!");
246                         strlcpy(x,"127.0.0.1",MAXBUF);
247                 }
248         }
249         return true;
250 }
251
252 bool ValidateModPath(ServerConfig* conf, const char* tag, const char* value, void* data)
253 {
254         char* x = (char*)data;  
255         if (!*x)
256                 strlcpy(x,MOD_PATH,MAXBUF);
257         return true;
258 }
259
260
261 bool ValidateServerName(ServerConfig* conf, const char* tag, const char* value, void* data)
262 {
263         char* x = (char*)data;
264         if (!strchr(x,'.'))
265         {
266                 conf->GetInstance()->Log(DEFAULT,"WARNING: <server:name> '%s' is not a fully-qualified domain name. Changed to '%s%c'",x,x,'.');
267                 charlcat(x,'.',MAXBUF);
268         }
269         //strlower(x);
270         return true;
271 }
272
273 bool ValidateNetBufferSize(ServerConfig* conf, const char* tag, const char* value, void* data)
274 {
275         if ((!conf->NetBufferSize) || (conf->NetBufferSize > 65535) || (conf->NetBufferSize < 1024))
276         {
277                 conf->GetInstance()->Log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
278                 conf->NetBufferSize = 10240;
279         }
280         return true;
281 }
282
283 bool ValidateMaxWho(ServerConfig* conf, const char* tag, const char* value, void* data)
284 {
285         if ((!conf->MaxWhoResults) || (conf->MaxWhoResults > 65535) || (conf->MaxWhoResults < 1))
286         {
287                 conf->GetInstance()->Log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
288                 conf->MaxWhoResults = 128;
289         }
290         return true;
291 }
292
293 bool ValidateLogLevel(ServerConfig* conf, const char* tag, const char* value, void* data)
294 {
295         const char* dbg = (const char*)data;
296         conf->LogLevel = DEFAULT;
297         if (!strcmp(dbg,"debug"))
298         {
299                 conf->LogLevel = DEBUG;
300                 conf->debugging = 1;
301         }
302         else if (!strcmp(dbg,"verbose"))
303                 conf->LogLevel = VERBOSE;
304         else if (!strcmp(dbg,"default"))
305                 conf->LogLevel = DEFAULT;
306         else if (!strcmp(dbg,"sparse"))
307                 conf->LogLevel = SPARSE;
308         else if (!strcmp(dbg,"none"))
309                 conf->LogLevel = NONE;
310         return true;
311 }
312
313 bool ValidateMotd(ServerConfig* conf, const char* tag, const char* value, void* data)
314 {
315         conf->ReadFile(conf->MOTD,conf->motd);
316         return true;
317 }
318
319 bool ValidateRules(ServerConfig* conf, const char* tag, const char* value, void* data)
320 {
321         conf->ReadFile(conf->RULES,conf->rules);
322         return true;
323 }
324
325 bool ValidateWhoWas(ServerConfig* conf, const char* tag, const char* value, void* data)
326 {
327         const char* max = (const char*)data;
328         conf->WhoWasMaxKeep = conf->GetInstance()->Duration(max);
329
330         if (conf->WhoWasGroupSize < 0)
331                 conf->WhoWasGroupSize = 0;
332
333         if (conf->WhoWasMaxGroups < 0)
334                 conf->WhoWasMaxGroups = 0;
335
336         if (conf->WhoWasMaxKeep < 3600)
337                 conf->WhoWasMaxKeep = 3600;
338
339         irc::whowas::PruneWhoWas(conf->GetInstance(), conf->GetInstance()->Time());
340         return true;
341 }
342
343 /* Callback called before processing the first <connect> tag
344  */
345 bool InitConnect(ServerConfig* conf, const char* tag)
346 {
347         conf->GetInstance()->Log(DEFAULT,"Reading connect classes...");
348         conf->Classes.clear();
349         return true;
350 }
351
352 /* Callback called to process a single <connect> tag
353  */
354 bool DoConnect(ServerConfig* conf, const char* tag, char** entries, void** values, int* types)
355 {
356         ConnectClass c;
357         char* allow = (char*)values[0]; /* Yeah, there are a lot of values. Live with it. */
358         char* deny = (char*)values[1];
359         char* password = (char*)values[2];
360         int* timeout = (int*)values[3];
361         int* pingfreq = (int*)values[4];
362         int* flood = (int*)values[5];
363         int* threshold = (int*)values[6];
364         int* sendq = (int*)values[7];
365         int* recvq = (int*)values[8];
366         int* localmax = (int*)values[9];
367         int* globalmax = (int*)values[10];
368
369         if (*allow)
370         {
371                 c.host = allow;
372                 c.type = CC_ALLOW;
373                 c.pass = password;
374                 c.registration_timeout = *timeout;
375                 c.pingtime = *pingfreq;
376                 c.flood = *flood;
377                 c.threshold = *threshold;
378                 c.sendqmax = *sendq;
379                 c.recvqmax = *recvq;
380                 c.maxlocal = *localmax;
381                 c.maxglobal = *globalmax;
382
383
384                 if (c.maxlocal == 0)
385                         c.maxlocal = 3;
386                 if (c.maxglobal == 0)
387                         c.maxglobal = 3;
388                 if (c.threshold == 0)
389                 {
390                         c.threshold = 1;
391                         c.flood = 999;
392                         conf->GetInstance()->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());
393                 }
394                 if (c.sendqmax == 0)
395                         c.sendqmax = 262114;
396                 if (c.recvqmax == 0)
397                         c.recvqmax = 4096;
398                 if (c.registration_timeout == 0)
399                         c.registration_timeout = 90;
400                 if (c.pingtime == 0)
401                         c.pingtime = 120;
402                 conf->Classes.push_back(c);
403         }
404         else
405         {
406                 c.host = deny;
407                 c.type = CC_DENY;
408                 conf->Classes.push_back(c);
409                 conf->GetInstance()->Log(DEBUG,"Read connect class type DENY, host=%s",deny);
410         }
411
412         return true;
413 }
414
415 /* Callback called when there are no more <connect> tags
416  */
417 bool DoneConnect(ServerConfig* conf, const char* tag)
418 {
419         conf->GetInstance()->Log(DEBUG,"DoneConnect called for tag: %s",tag);
420         return true;
421 }
422
423 /* Callback called before processing the first <uline> tag
424  */
425 bool InitULine(ServerConfig* conf, const char* tag)
426 {
427         conf->ulines.clear();
428         return true;
429 }
430
431 /* Callback called to process a single <uline> tag
432  */
433 bool DoULine(ServerConfig* conf, const char* tag, char** entries, void** values, int* types)
434 {
435         char* server = (char*)values[0];
436         conf->GetInstance()->Log(DEBUG,"Read ULINE '%s'",server);
437         conf->ulines.push_back(server);
438         return true;
439 }
440
441 /* Callback called when there are no more <uline> tags
442  */
443 bool DoneULine(ServerConfig* conf, const char* tag)
444 {
445         return true;
446 }
447
448 /* Callback called before processing the first <module> tag
449  */
450 bool InitModule(ServerConfig* conf, const char* tag)
451 {
452         old_module_names.clear();
453         new_module_names.clear();
454         added_modules.clear();
455         removed_modules.clear();
456         for (std::vector<std::string>::iterator t = conf->module_names.begin(); t != conf->module_names.end(); t++)
457         {
458                 old_module_names.push_back(*t);
459         }
460         return true;
461 }
462
463 /* Callback called to process a single <module> tag
464  */
465 bool DoModule(ServerConfig* conf, const char* tag, char** entries, void** values, int* types)
466 {
467         char* modname = (char*)values[0];
468         new_module_names.push_back(modname);
469         return true;
470 }
471
472 /* Callback called when there are no more <module> tags
473  */
474 bool DoneModule(ServerConfig* conf, const char* tag)
475 {
476         // now create a list of new modules that are due to be loaded
477         // and a seperate list of modules which are due to be unloaded
478         for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
479         {
480                 bool added = true;
481
482                 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
483                 {
484                         if (*old == *_new)
485                                 added = false;
486                 }
487
488                 if (added)
489                         added_modules.push_back(*_new);
490         }
491
492         for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
493         {
494                 bool removed = true;
495                 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
496                 {
497                         if (*newm == *oldm)
498                                 removed = false;
499                 }
500
501                 if (removed)
502                         removed_modules.push_back(*oldm);
503         }
504         return true;
505 }
506
507 /* Callback called before processing the first <banlist> tag
508  */
509 bool InitMaxBans(ServerConfig* conf, const char* tag)
510 {
511         conf->maxbans.clear();
512         return true;
513 }
514
515 /* Callback called to process a single <banlist> tag
516  */
517 bool DoMaxBans(ServerConfig* conf, const char* tag, char** entries, void** values, int* types)
518 {
519         char* channel = (char*)values[0];
520         int* limit = (int*)values[1];
521         conf->maxbans[channel] = *limit;
522         return true;
523 }
524
525 /* Callback called when there are no more <banlist> tags.
526  */
527 bool DoneMaxBans(ServerConfig* conf, const char* tag)
528 {
529         return true;
530 }
531
532 void ServerConfig::Read(bool bail, userrec* user)
533 {
534         char debug[MAXBUF];             /* Temporary buffer for debugging value */
535         char maxkeep[MAXBUF];   /* Temporary buffer for WhoWasMaxKeep value */
536         char* data[12];                 /* Temporary buffers for reading multiple occurance tags into */
537         void* ptr[12];                  /* Temporary pointers for passing to callbacks */
538         int r_i[12];                    /* Temporary array for casting */
539         int rem = 0, add = 0;           /* Number of modules added, number of modules removed */
540         std::ostringstream errstr;      /* String stream containing the error output */
541
542         /* These tags MUST occur and must ONLY occur once in the config file */
543         static char* Once[] = { "server", "admin", "files", "power", "options", NULL };
544
545         /* These tags can occur ONCE or not at all */
546         static InitialConfig Values[] = {
547                 {"options",             "softlimit",                    &this->SoftLimit,               DT_INTEGER, ValidateSoftLimit},
548                 {"options",             "somaxconn",                    &this->MaxConn,                 DT_INTEGER, ValidateMaxConn},
549                 {"server",              "name",                         &this->ServerName,              DT_CHARPTR, ValidateServerName},
550                 {"server",              "description",                  &this->ServerDesc,              DT_CHARPTR, NoValidation},
551                 {"server",              "network",                      &this->Network,                 DT_CHARPTR, NoValidation},
552                 {"admin",               "name",                         &this->AdminName,               DT_CHARPTR, NoValidation},
553                 {"admin",               "email",                        &this->AdminEmail,              DT_CHARPTR, NoValidation},
554                 {"admin",               "nick",                         &this->AdminNick,               DT_CHARPTR, NoValidation},
555                 {"files",               "motd",                         &this->motd,                    DT_CHARPTR, ValidateMotd},
556                 {"files",               "rules",                        &this->rules,                   DT_CHARPTR, ValidateRules},
557                 {"power",               "diepass",                      &this->diepass,                 DT_CHARPTR, NoValidation},      
558                 {"power",               "pause",                        &this->DieDelay,                DT_INTEGER, NoValidation},
559                 {"power",               "restartpass",                  &this->restartpass,             DT_CHARPTR, NoValidation},
560                 {"options",             "prefixquit",                   &this->PrefixQuit,              DT_CHARPTR, NoValidation},
561                 {"die",                 "value",                        &this->DieValue,                DT_CHARPTR, NoValidation},
562                 {"options",             "loglevel",                     &debug,                         DT_CHARPTR, ValidateLogLevel},
563                 {"options",             "netbuffersize",                &this->NetBufferSize,           DT_INTEGER, ValidateNetBufferSize},
564                 {"options",             "maxwho",                       &this->MaxWhoResults,           DT_INTEGER, ValidateMaxWho},
565                 {"options",             "allowhalfop",                  &this->AllowHalfop,             DT_BOOLEAN, NoValidation},
566                 {"dns",                 "server",                       &this->DNSServer,               DT_CHARPTR, ValidateDnsServer},
567                 {"dns",                 "timeout",                      &this->dns_timeout,             DT_INTEGER, ValidateDnsTimeout},
568                 {"options",             "moduledir",                    &this->ModPath,                 DT_CHARPTR, ValidateModPath},
569                 {"disabled",            "commands",                     &this->DisabledCommands,        DT_CHARPTR, NoValidation},
570                 {"options",             "userstats",                    &this->UserStats,               DT_CHARPTR, NoValidation},
571                 {"options",             "customversion",                &this->CustomVersion,           DT_CHARPTR, NoValidation},
572                 {"options",             "hidesplits",                   &this->HideSplits,              DT_BOOLEAN, NoValidation},
573                 {"options",             "hidebans",                     &this->HideBans,                DT_BOOLEAN, NoValidation},
574                 {"options",             "hidewhois",                    &this->HideWhoisServer,         DT_CHARPTR, NoValidation},
575                 {"options",             "operspywhois",                 &this->OperSpyWhois,            DT_BOOLEAN, NoValidation},
576                 {"options",             "tempdir",                      &this->TempDir,                 DT_CHARPTR, ValidateTempDir},
577                 {"options",             "nouserdns",                    &this->NoUserDns,               DT_BOOLEAN, NoValidation},
578                 {"options",             "syntaxhints",                  &this->SyntaxHints,             DT_BOOLEAN, NoValidation},
579                 {"options",             "cyclehosts",                   &this->CycleHosts,              DT_BOOLEAN, NoValidation},
580                 {"pid",                 "file",                         &this->PID,                     DT_CHARPTR, NoValidation},
581                 {"whowas",              "groupsize",                    &this->WhoWasGroupSize,         DT_INTEGER, NoValidation},
582                 {"whowas",              "maxgroups",                    &this->WhoWasMaxGroups,         DT_INTEGER, NoValidation},
583                 {"whowas",              "maxkeep",                      &maxkeep,                       DT_CHARPTR, ValidateWhoWas},
584                 {NULL}
585         };
586
587         /* These tags can occur multiple times, and therefore they have special code to read them
588          * which is different to the code for reading the singular tags listed above.
589          */
590         static MultiConfig MultiValues[] = {
591
592                 {"connect",
593                                 {"allow",       "deny",         "password",     "timeout",      "pingfreq",     "flood",
594                                 "threshold",    "sendq",        "recvq",        "localmax",     "globalmax",    NULL},
595                                 {DT_CHARPTR,    DT_CHARPTR,     DT_CHARPTR,     DT_INTEGER,     DT_INTEGER,     DT_INTEGER,
596                                  DT_INTEGER,    DT_INTEGER,     DT_INTEGER,     DT_INTEGER,     DT_INTEGER},
597                                 InitConnect, DoConnect, DoneConnect},
598
599                 {"uline",
600                                 {"server",      NULL},
601                                 {DT_CHARPTR},
602                                 InitULine,DoULine,DoneULine},
603
604                 {"banlist",
605                                 {"chan",        "limit",        NULL},
606                                 {DT_CHARPTR,    DT_INTEGER},
607                                 InitMaxBans, DoMaxBans, DoneMaxBans},
608
609                 {"module",
610                                 {"name",        NULL},
611                                 {DT_CHARPTR},
612                                 InitModule, DoModule, DoneModule},
613
614                 {"badip",
615                                 {"reason",      "ipmask",       NULL},
616                                 {DT_CHARPTR,    DT_CHARPTR},
617                                 InitXLine, DoZLine, DoneXLine},
618
619                 {"badnick",
620                                 {"reason",      "nick",         NULL},
621                                 {DT_CHARPTR,    DT_CHARPTR},
622                                 InitXLine, DoQLine, DoneXLine},
623
624                 {"badhost",
625                                 {"reason",      "host",         NULL},
626                                 {DT_CHARPTR,    DT_CHARPTR},
627                                 InitXLine, DoKLine, DoneXLine},
628
629                 {"exception",
630                                 {"reason",      "host",         NULL},
631                                 {DT_CHARPTR,    DT_CHARPTR},
632                                 InitXLine, DoELine, DoneXLine},
633
634                 {"type",
635                                 {"name",        "classes",      NULL},
636                                 {DT_CHARPTR,    DT_CHARPTR},
637                                 InitTypes, DoType, DoneClassesAndTypes},
638
639                 {"class",
640                                 {"name",        "commands",     NULL},
641                                 {DT_CHARPTR,    DT_CHARPTR},
642                                 InitClasses, DoClass, DoneClassesAndTypes},
643
644                 {NULL}
645         };
646
647         include_stack.clear();
648
649         /* Load and parse the config file, if there are any errors then explode */
650         
651         /* Make a copy here so if it fails then we can carry on running with an unaffected config */
652         ConfigDataHash newconfig;
653         
654         if (this->LoadConf(newconfig, CONFIG_FILE, errstr))
655         {
656                 /* If we succeeded, set the ircd config to the new one */
657                 this->config_data = newconfig;  
658         }
659         else
660         {
661                 ServerInstance->Log(DEFAULT, "There were errors in your configuration:\n%s", errstr.str().c_str());
662
663                 if (bail)
664                 {
665                         /* Unneeded because of the ServerInstance->Log() aboive? */
666                         printf("There were errors in your configuration:\n%s",errstr.str().c_str());
667                         InspIRCd::Exit(ERROR);
668                 }
669                 else
670                 {
671                         std::string errors = errstr.str();
672                         std::string::size_type start;
673                         unsigned int prefixlen;
674                         
675                         start = 0;
676                         /* ":ServerInstance->Config->ServerName NOTICE user->nick :" */
677                         prefixlen = strlen(this->ServerName) + strlen(user->nick) + 11;
678         
679                         if (user)
680                         {
681                                 user->WriteServ("NOTICE %s :There were errors in the configuration file:",user->nick);
682                                 
683                                 while(start < errors.length())
684                                 {
685                                         user->WriteServ("NOTICE %s :%s",user->nick, errors.substr(start, 510 - prefixlen).c_str());
686                                         start += 510 - prefixlen;
687                                 }
688                         }
689                         else
690                         {
691                                 ServerInstance->WriteOpers("There were errors in the configuration file:");
692                                 
693                                 while(start < errors.length())
694                                 {
695                                         ServerInstance->WriteOpers(errors.substr(start, 360).c_str());
696                                         start += 360;
697                                 }
698                         }
699
700                         return;
701                 }
702         }
703
704         /* Check we dont have more than one of singular tags, or any of them missing
705          */
706         for (int Index = 0; Once[Index]; Index++)
707                 if (!CheckOnce(Once[Index],bail,user))
708                         return;
709
710         /* Read the values of all the tags which occur once or not at all, and call their callbacks.
711          */
712         for (int Index = 0; Values[Index].tag; Index++)
713         {
714                 int* val_i = (int*) Values[Index].val;
715                 char* val_c = (char*) Values[Index].val;
716
717                 switch (Values[Index].datatype)
718                 {
719                         case DT_CHARPTR:
720                                 /* Assuming MAXBUF here, potentially unsafe */
721                                 ConfValue(this->config_data, Values[Index].tag, Values[Index].value, 0, val_c, MAXBUF);
722                         break;
723
724                         case DT_INTEGER:
725                                 ConfValueInteger(this->config_data, Values[Index].tag, Values[Index].value, 0, *val_i);
726                         break;
727
728                         case DT_BOOLEAN:
729                                 *val_i = ConfValueBool(this->config_data, Values[Index].tag, Values[Index].value, 0);
730                         break;
731
732                         case DT_NOTHING:
733                         break;
734                 }
735
736                 Values[Index].validation_function(this, Values[Index].tag, Values[Index].value, Values[Index].val);
737         }
738
739         /* Claim memory for use when reading multiple tags
740          */
741         for (int n = 0; n < 12; n++)
742                 data[n] = new char[MAXBUF];
743
744         /* Read the multiple-tag items (class tags, connect tags, etc)
745          * and call the callbacks associated with them. We have three
746          * callbacks for these, a 'start', 'item' and 'end' callback.
747          */
748         
749         /* XXX - Make this use ConfValueInteger and so on */
750         for (int Index = 0; MultiValues[Index].tag; Index++)
751         {
752                 MultiValues[Index].init_function(this, MultiValues[Index].tag);
753
754                 int number_of_tags = ConfValueEnum(this->config_data, MultiValues[Index].tag);
755
756                 for (int tagnum = 0; tagnum < number_of_tags; tagnum++)
757                 {
758                         for (int valuenum = 0; MultiValues[Index].items[valuenum]; valuenum++)
759                         {
760                                 ConfValue(this->config_data, MultiValues[Index].tag, MultiValues[Index].items[valuenum], tagnum, data[valuenum], MAXBUF);
761
762                                 switch (MultiValues[Index].datatype[valuenum])
763                                 {
764                                         case DT_CHARPTR:
765                                                 ptr[valuenum] = data[valuenum];
766                                         break;
767                                         case DT_INTEGER:
768                                                 r_i[valuenum] = atoi(data[valuenum]);
769                                                 ptr[valuenum] = &r_i[valuenum];
770                                         break;
771                                         case DT_BOOLEAN:
772                                                 r_i[valuenum] = ((*data[valuenum] == tolower('y')) || (*data[valuenum] == tolower('t')) || (*data[valuenum] == '1'));
773                                                 ptr[valuenum] = &r_i[valuenum];
774                                         break;
775                                         default:
776                                         break;
777                                 }
778                         }
779                         MultiValues[Index].validation_function(this, MultiValues[Index].tag, (char**)MultiValues[Index].items, ptr, MultiValues[Index].datatype);
780                 }
781
782                 MultiValues[Index].finish_function(this, MultiValues[Index].tag);
783         }
784
785         /* Free any memory we claimed
786          */
787         for (int n = 0; n < 12; n++)
788                 delete[] data[n];
789
790         // write once here, to try it out and make sure its ok
791         ServerInstance->WritePID(this->PID);
792
793         ServerInstance->Log(DEFAULT,"Done reading configuration file, InspIRCd is now starting.");
794
795         /* If we're rehashing, let's load any new modules, and unload old ones
796          */
797         if (!bail)
798         {
799                 int found_ports = 0;
800                 FailedPortList pl;
801                 ServerInstance->stats->BoundPortCount = ServerInstance->BindPorts(false, found_ports, pl);
802
803                 if (pl.size())
804                 {
805                         user->WriteServ("NOTICE %s :*** Not all your client ports could be bound.", user->nick);
806                         user->WriteServ("NOTICE %s :*** The following port%s failed to bind:", user->nick, found_ports - ServerInstance->stats->BoundPortCount != 1 ? "s" : "");
807                         int j = 1;
808                         for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
809                         {
810                                 user->WriteServ("NOTICE %s :*** %d.   IP: %s     Port: %lu", user->nick, j, i->first.empty() ? "<all>" : i->first.c_str(), (unsigned long)i->second);
811                         }
812                 }
813
814                 if (!removed_modules.empty())
815                         for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
816                         {
817                                 if (ServerInstance->UnloadModule(removing->c_str()))
818                                 {
819                                         ServerInstance->WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
820
821                                         if (user)
822                                                 user->WriteServ("973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
823
824                                         rem++;
825                                 }
826                                 else
827                                 {
828                                         if (user)
829                                                 user->WriteServ("972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ServerInstance->ModuleError());
830                                 }
831                         }
832
833                 if (!added_modules.empty())
834                 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
835                 {
836                         if (ServerInstance->LoadModule(adding->c_str()))
837                         {
838                                 ServerInstance->WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
839
840                                 if (user)
841                                         user->WriteServ("975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
842
843                                 add++;
844                         }
845                         else
846                         {
847                                 if (user)
848                                         user->WriteServ("974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ServerInstance->ModuleError());
849                         }
850                 }
851
852                 ServerInstance->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());
853         }
854 }
855
856 bool ServerConfig::LoadConf(ConfigDataHash &target, const char* filename, std::ostringstream &errorstream)
857 {
858         std::ifstream conf(filename);
859         std::string line;
860         char ch;
861         long linenumber;
862         bool in_tag;
863         bool in_quote;
864         bool in_comment;
865         
866         linenumber = 1;
867         in_tag = false;
868         in_quote = false;
869         in_comment = false;
870         
871         /* Check if the file open failed first */
872         if (!conf)
873         {
874                 errorstream << "LoadConf: Couldn't open config file: " << filename << std::endl;
875                 return false;
876         }
877         
878         /* Fix the chmod of the file to restrict it to the current user and group */
879         chmod(filename,0600);
880         
881         for (unsigned int t = 0; t < include_stack.size(); t++)
882         {
883                 if (std::string(filename) == include_stack[t])
884                 {
885                         errorstream << "File " << filename << " is included recursively (looped inclusion)." << std::endl;
886                         return false;
887                 }
888         }
889         
890         /* It's not already included, add it to the list of files we've loaded */
891         include_stack.push_back(filename);
892         
893         /* Start reading characters... */       
894         while(conf.get(ch))
895         {
896                 /*
897                  * Here we try and get individual tags on separate lines,
898                  * this would be so easy if we just made people format
899                  * their config files like that, but they don't so...
900                  * We check for a '<' and then know the line is over when
901                  * we get a '>' not inside quotes. If we find two '<' and
902                  * no '>' then die with an error.
903                  */
904                 
905                 if((ch == '#') && !in_quote)
906                         in_comment = true;
907                 
908                 if(((ch == '\n') || (ch == '\r')) && in_quote)
909                 {
910                         errorstream << "Got a newline within a quoted section, this is probably a typo: " << filename << ":" << linenumber << std::endl;
911                         return false;
912                 }
913                 
914                 switch(ch)
915                 {
916                         case '\n':
917                                 linenumber++;
918                         case '\r':
919                                 in_comment = false;
920                         case '\0':
921                                 continue;
922                         case '\t':
923                                 ch = ' ';
924                 }
925                 
926                 if(in_comment)
927                         continue;
928
929                 /* XXX: Added by Brain, May 1st 2006 - Escaping of characters.
930                  * Note that this WILL NOT usually allow insertion of newlines,
931                  * because a newline is two characters long. Use it primarily to
932                  * insert the " symbol.
933                  *
934                  * Note that this also involves a further check when parsing the line,
935                  * which can be found below.
936                  */
937                 if ((ch == '\\') && (in_quote) && (in_tag))
938                 {
939                         line += ch;
940                         ServerInstance->Log(DEBUG,"Escape sequence in config line.");
941                         char real_character;
942                         if (conf.get(real_character))
943                         {
944                                 ServerInstance->Log(DEBUG,"Escaping %c", real_character);
945                                 if (real_character == 'n')
946                                         real_character = '\n';
947                                 line += real_character;
948                                 continue;
949                         }
950                         else
951                         {
952                                 errorstream << "End of file after a \\, what did you want to escape?: " << filename << ":" << linenumber << std::endl;
953                                 return false;
954                         }
955                 }
956
957                 line += ch;
958                 
959                 if(ch == '<')
960                 {
961                         if(in_tag)
962                         {
963                                 if(!in_quote)
964                                 {
965                                         errorstream << "Got another opening < when the first one wasn't closed: " << filename << ":" << linenumber << std::endl;
966                                         return false;
967                                 }
968                         }
969                         else
970                         {
971                                 if(in_quote)
972                                 {
973                                         errorstream << "We're in a quote but outside a tag, interesting. " << filename << ":" << linenumber << std::endl;
974                                         return false;
975                                 }
976                                 else
977                                 {
978                                         // errorstream << "Opening new config tag on line " << linenumber << std::endl;
979                                         in_tag = true;
980                                 }
981                         }
982                 }
983                 else if(ch == '"')
984                 {
985                         if(in_tag)
986                         {
987                                 if(in_quote)
988                                 {
989                                         // errorstream << "Closing quote in config tag on line " << linenumber << std::endl;
990                                         in_quote = false;
991                                 }
992                                 else
993                                 {
994                                         // errorstream << "Opening quote in config tag on line " << linenumber << std::endl;
995                                         in_quote = true;
996                                 }
997                         }
998                         else
999                         {
1000                                 if(in_quote)
1001                                 {
1002                                         errorstream << "Found a (closing) \" outside a tag: " << filename << ":" << linenumber << std::endl;
1003                                 }
1004                                 else
1005                                 {
1006                                         errorstream << "Found a (opening) \" outside a tag: " << filename << ":" << linenumber << std::endl;
1007                                 }
1008                         }
1009                 }
1010                 else if(ch == '>')
1011                 {
1012                         if(!in_quote)
1013                         {
1014                                 if(in_tag)
1015                                 {
1016                                         // errorstream << "Closing config tag on line " << linenumber << std::endl;
1017                                         in_tag = false;
1018
1019                                         /*
1020                                          * If this finds an <include> then ParseLine can simply call
1021                                          * LoadConf() and load the included config into the same ConfigDataHash
1022                                          */
1023                                         
1024                                         if(!this->ParseLine(target, line, linenumber, errorstream))
1025                                                 return false;
1026                                         
1027                                         line.clear();
1028                                 }
1029                                 else
1030                                 {
1031                                         errorstream << "Got a closing > when we weren't inside a tag: " << filename << ":" << linenumber << std::endl;
1032                                         return false;
1033                                 }
1034                         }
1035                 }
1036         }
1037         
1038         return true;
1039 }
1040
1041 bool ServerConfig::LoadConf(ConfigDataHash &target, const std::string &filename, std::ostringstream &errorstream)
1042 {
1043         return this->LoadConf(target, filename.c_str(), errorstream);
1044 }
1045
1046 bool ServerConfig::ParseLine(ConfigDataHash &target, std::string &line, long linenumber, std::ostringstream &errorstream)
1047 {
1048         std::string tagname;
1049         std::string current_key;
1050         std::string current_value;
1051         KeyValList results;
1052         bool got_name;
1053         bool got_key;
1054         bool in_quote;
1055         
1056         got_name = got_key = in_quote = false;
1057         
1058         // std::cout << "ParseLine(data, '" << line << "', " << linenumber << ", stream)" << std::endl;
1059         
1060         for(std::string::iterator c = line.begin(); c != line.end(); c++)
1061         {
1062                 if(!got_name)
1063                 {
1064                         /* We don't know the tag name yet. */
1065                         
1066                         if(*c != ' ')
1067                         {
1068                                 if(*c != '<')
1069                                 {
1070                                         tagname += *c;
1071                                 }
1072                         }
1073                         else
1074                         {
1075                                 /* We got to a space, we should have the tagname now. */
1076                                 if(tagname.length())
1077                                 {
1078                                         got_name = true;
1079                                 }
1080                         }
1081                 }
1082                 else
1083                 {
1084                         /* We have the tag name */
1085                         if (!got_key)
1086                         {
1087                                 /* We're still reading the key name */
1088                                 if (*c != '=')
1089                                 {
1090                                         if (*c != ' ')
1091                                         {
1092                                                 current_key += *c;
1093                                         }
1094                                 }
1095                                 else
1096                                 {
1097                                         /* We got an '=', end of the key name. */
1098                                         got_key = true;
1099                                 }
1100                         }
1101                         else
1102                         {
1103                                 /* We have the key name, now we're looking for quotes and the value */
1104
1105                                 /* Correctly handle escaped characters here.
1106                                  * See the XXX'ed section above.
1107                                  */
1108                                 if ((*c == '\\') && (in_quote))
1109                                 {
1110                                         c++;
1111                                         if (*c == 'n')
1112                                                 current_value += '\n';
1113                                         else
1114                                                 current_value += *c;
1115                                         continue;
1116                                 }
1117                                 if (*c == '"')
1118                                 {
1119                                         if (!in_quote)
1120                                         {
1121                                                 /* We're not already in a quote. */
1122                                                 in_quote = true;
1123                                         }
1124                                         else
1125                                         {
1126                                                 /* Leaving quotes, we have the value */
1127                                                 results.push_back(KeyVal(current_key, current_value));
1128                                                 
1129                                                 // std::cout << "<" << tagname << ":" << current_key << "> " << current_value << std::endl;
1130                                                 
1131                                                 in_quote = false;
1132                                                 got_key = false;
1133                                                 
1134                                                 if((tagname == "include") && (current_key == "file"))
1135                                                 {
1136                                                         if(!this->DoInclude(target, current_value, errorstream))
1137                                                                 return false;
1138                                                 }
1139                                                 
1140                                                 current_key.clear();
1141                                                 current_value.clear();
1142                                         }
1143                                 }
1144                                 else
1145                                 {
1146                                         if(in_quote)
1147                                         {
1148                                                 current_value += *c;
1149                                         }
1150                                 }
1151                         }
1152                 }
1153         }
1154         
1155         /* Finished parsing the tag, add it to the config hash */
1156         target.insert(std::pair<std::string, KeyValList > (tagname, results));
1157         
1158         return true;
1159 }
1160
1161 bool ServerConfig::DoInclude(ConfigDataHash &target, const std::string &file, std::ostringstream &errorstream)
1162 {
1163         std::string confpath;
1164         std::string newfile;
1165         std::string::size_type pos;
1166         
1167         confpath = CONFIG_FILE;
1168         newfile = file;
1169         
1170         for (std::string::iterator c = newfile.begin(); c != newfile.end(); c++)
1171         {
1172                 if (*c == '\\')
1173                 {
1174                         *c = '/';
1175                 }
1176         }
1177
1178         if (file[0] != '/')
1179         {
1180                 if((pos = confpath.find("/inspircd.conf")) != std::string::npos)
1181                 {
1182                         /* Leaves us with just the path */
1183                         newfile = confpath.substr(0, pos) + std::string("/") + newfile;
1184                 }
1185                 else
1186                 {
1187                         errorstream << "Couldn't get config path from: " << confpath << std::endl;
1188                         return false;
1189                 }
1190         }
1191         
1192         return LoadConf(target, newfile, errorstream);
1193 }
1194
1195 bool ServerConfig::ConfValue(ConfigDataHash &target, const char* tag, const char* var, int index, char* result, int length)
1196 {
1197         std::string value;
1198         bool r = ConfValue(target, std::string(tag), std::string(var), index, value);
1199         strlcpy(result, value.c_str(), length);
1200         return r;
1201 }
1202
1203 bool ServerConfig::ConfValue(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, std::string &result)
1204 {
1205         ConfigDataHash::size_type pos = index;
1206         if((pos >= 0) && (pos < target.count(tag)))
1207         {
1208                 ConfigDataHash::const_iterator iter = target.find(tag);
1209                 
1210                 for(int i = 0; i < index; i++)
1211                         iter++;
1212                 
1213                 for(KeyValList::const_iterator j = iter->second.begin(); j != iter->second.end(); j++)
1214                 {
1215                         if(j->first == var)
1216                         {
1217                                 result = j->second;
1218                                 return true;
1219                         }
1220                 }
1221         }
1222         else if(pos == 0)
1223         {
1224                 ServerInstance->Log(DEBUG, "No <%s> tags in config file.", tag.c_str());
1225         }
1226         else
1227         {
1228                 ServerInstance->Log(DEBUG, "ConfValue got an out-of-range index %d, there are only %d occurences of %s", pos, target.count(tag), tag.c_str());
1229         }
1230         
1231         return false;
1232 }
1233         
1234 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const char* tag, const char* var, int index, int &result)
1235 {
1236         return ConfValueInteger(target, std::string(tag), std::string(var), index, result);
1237 }
1238
1239 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, int &result)
1240 {
1241         std::string value;
1242         std::istringstream stream;
1243         bool r = ConfValue(target, tag, var, index, value);
1244         stream.str(value);
1245         if(!(stream >> result))
1246                 return false;
1247         return r;
1248 }
1249         
1250 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const char* tag, const char* var, int index)
1251 {
1252         return ConfValueBool(target, std::string(tag), std::string(var), index);
1253 }
1254
1255 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const std::string &tag, const std::string &var, int index)
1256 {
1257         std::string result;
1258         if(!ConfValue(target, tag, var, index, result))
1259                 return false;
1260         
1261         return ((result == "yes") || (result == "true") || (result == "1"));
1262 }
1263         
1264 int ServerConfig::ConfValueEnum(ConfigDataHash &target, const char* tag)
1265 {
1266         return target.count(tag);
1267 }
1268
1269 int ServerConfig::ConfValueEnum(ConfigDataHash &target, const std::string &tag)
1270 {
1271         return target.count(tag);
1272 }
1273         
1274 int ServerConfig::ConfVarEnum(ConfigDataHash &target, const char* tag, int index)
1275 {
1276         return ConfVarEnum(target, std::string(tag), index);
1277 }
1278
1279 int ServerConfig::ConfVarEnum(ConfigDataHash &target, const std::string &tag, int index)
1280 {
1281         ConfigDataHash::size_type pos = index;
1282         
1283         if((pos >= 0) && (pos < target.count(tag)))
1284         {
1285                 ConfigDataHash::const_iterator iter = target.find(tag);
1286                 
1287                 for(int i = 0; i < index; i++)
1288                         iter++;
1289                 
1290                 return iter->second.size();
1291         }
1292         else if(pos == 0)
1293         {
1294                 ServerInstance->Log(DEBUG, "No <%s> tags in config file.", tag.c_str());
1295         }
1296         else
1297         {
1298                 ServerInstance->Log(DEBUG, "ConfVarEnum got an out-of-range index %d, there are only %d occurences of %s", pos, target.count(tag), tag.c_str());
1299         }
1300         
1301         return 0;
1302 }
1303
1304 /** Read the contents of a file located by `fname' into a file_cache pointed at by `F'.
1305  */
1306 bool ServerConfig::ReadFile(file_cache &F, const char* fname)
1307 {
1308         FILE* file;
1309         char linebuf[MAXBUF];
1310
1311         F.clear();
1312         
1313         if (*fname != '/')
1314         {
1315                 std::string::size_type pos;
1316                 std::string confpath = CONFIG_FILE;
1317                 if((pos = confpath.find("/inspircd.conf")) != std::string::npos)
1318                 {
1319                         /* Leaves us with just the path */
1320                         std::string newfile = confpath.substr(0, pos) + std::string("/") + fname;
1321                         file =  fopen(newfile.c_str(), "r");
1322                         
1323                 }
1324         }
1325         else
1326                 file =  fopen(fname, "r");
1327
1328         if (file)
1329         {
1330                 while (!feof(file))
1331                 {
1332                         fgets(linebuf, sizeof(linebuf), file);
1333                         linebuf[strlen(linebuf)-1] = 0;
1334
1335                         if (!feof(file))
1336                         {
1337                                 F.push_back(*linebuf ? linebuf : " ");
1338                         }
1339                 }
1340
1341                 fclose(file);
1342         }
1343         else
1344                 return false;
1345
1346         return true;
1347 }
1348
1349 bool ServerConfig::FileExists(const char* file)
1350 {
1351         FILE *input;
1352         if ((input = fopen (file, "r")) == NULL)
1353         {
1354                 return false;
1355         }
1356         else
1357         {
1358                 fclose(input);
1359                 return true;
1360         }
1361 }
1362
1363 char* ServerConfig::CleanFilename(char* name)
1364 {
1365         char* p = name + strlen(name);
1366         while ((p != name) && (*p != '/')) p--;
1367         return (p != name ? ++p : p);
1368 }
1369
1370
1371 bool ServerConfig::DirValid(const char* dirandfile)
1372 {
1373         char work[MAXBUF];
1374         char buffer[MAXBUF];
1375         char otherdir[MAXBUF];
1376         int p;
1377
1378         strlcpy(work, dirandfile, MAXBUF);
1379         p = strlen(work);
1380
1381         // we just want the dir
1382         while (*work)
1383         {
1384                 if (work[p] == '/')
1385                 {
1386                         work[p] = '\0';
1387                         break;
1388                 }
1389
1390                 work[p--] = '\0';
1391         }
1392
1393         // Get the current working directory
1394         if (getcwd(buffer, MAXBUF ) == NULL )
1395                 return false;
1396
1397         chdir(work);
1398
1399         if (getcwd(otherdir, MAXBUF ) == NULL )
1400                 return false;
1401
1402         chdir(buffer);
1403
1404         size_t t = strlen(work);
1405
1406         if (strlen(otherdir) >= t)
1407         {
1408                 otherdir[t] = '\0';
1409
1410                 if (!strcmp(otherdir,work))
1411                 {
1412                         return true;
1413                 }
1414
1415                 return false;
1416         }
1417         else
1418         {
1419                 return false;
1420         }
1421 }
1422
1423 std::string ServerConfig::GetFullProgDir(char** argv, int argc)
1424 {
1425         char work[MAXBUF];
1426         char buffer[MAXBUF];
1427         char otherdir[MAXBUF];
1428         int p;
1429
1430         strlcpy(work,argv[0],MAXBUF);
1431         p = strlen(work);
1432
1433         // we just want the dir
1434         while (*work)
1435         {
1436                 if (work[p] == '/')
1437                 {
1438                         work[p] = '\0';
1439                         break;
1440                 }
1441
1442                 work[p--] = '\0';
1443         }
1444
1445         // Get the current working directory
1446         if (getcwd(buffer, MAXBUF) == NULL)
1447                 return "";
1448
1449         chdir(work);
1450
1451         if (getcwd(otherdir, MAXBUF) == NULL)
1452                 return "";
1453
1454         chdir(buffer);
1455         return otherdir;
1456 }
1457
1458 InspIRCd* ServerConfig::GetInstance()
1459 {
1460         return ServerInstance;
1461 }
1462