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