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