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