]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/configreader.cpp
Checks for negative fd's when adding them to the socketengine so we can generate...
[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         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                 {"pid",                 "file",                         &this->PID,                     DT_CHARPTR, NoValidation},
549                 {NULL}
550         };
551
552         /* These tags can occur multiple times, and therefore they have special code to read them
553          * which is different to the code for reading the singular tags listed above.
554          */
555         static MultiConfig MultiValues[] = {
556
557                 {"connect",
558                                 {"allow",       "deny",         "password",     "timeout",      "pingfreq",     "flood",
559                                 "threshold",    "sendq",        "recvq",        "localmax",     "globalmax",    NULL},
560                                 {DT_CHARPTR,    DT_CHARPTR,     DT_CHARPTR,     DT_INTEGER,     DT_INTEGER,     DT_INTEGER,
561                                  DT_INTEGER,    DT_INTEGER,     DT_INTEGER,     DT_INTEGER,     DT_INTEGER},
562                                 InitConnect, DoConnect, DoneConnect},
563
564                 {"uline",
565                                 {"server",      NULL},
566                                 {DT_CHARPTR},
567                                 InitULine,DoULine,DoneULine},
568
569                 {"banlist",
570                                 {"chan",        "limit",        NULL},
571                                 {DT_CHARPTR,    DT_INTEGER},
572                                 InitMaxBans, DoMaxBans, DoneMaxBans},
573
574                 {"module",
575                                 {"name",        NULL},
576                                 {DT_CHARPTR},
577                                 InitModule, DoModule, DoneModule},
578
579                 {"badip",
580                                 {"reason",      "ipmask",       NULL},
581                                 {DT_CHARPTR,    DT_CHARPTR},
582                                 InitXLine, DoZLine, DoneXLine},
583
584                 {"badnick",
585                                 {"reason",      "nick",         NULL},
586                                 {DT_CHARPTR,    DT_CHARPTR},
587                                 InitXLine, DoQLine, DoneXLine},
588
589                 {"badhost",
590                                 {"reason",      "host",         NULL},
591                                 {DT_CHARPTR,    DT_CHARPTR},
592                                 InitXLine, DoKLine, DoneXLine},
593
594                 {"exception",
595                                 {"reason",      "host",         NULL},
596                                 {DT_CHARPTR,    DT_CHARPTR},
597                                 InitXLine, DoELine, DoneXLine},
598
599                 {"type",
600                                 {"name",        "classes",      NULL},
601                                 {DT_CHARPTR,    DT_CHARPTR},
602                                 InitTypes, DoType, DoneClassesAndTypes},
603
604                 {"class",
605                                 {"name",        "commands",     NULL},
606                                 {DT_CHARPTR,    DT_CHARPTR},
607                                 InitClasses, DoClass, DoneClassesAndTypes},
608
609                 {NULL}
610         };
611
612         include_stack.clear();
613
614         /* Load and parse the config file, if there are any errors then explode */
615         
616         /* Make a copy here so if it fails then we can carry on running with an unaffected config */
617         ConfigDataHash newconfig;
618         
619         if (this->LoadConf(newconfig, CONFIG_FILE, errstr))
620         {
621                 /* If we succeeded, set the ircd config to the new one */
622                 Config->config_data = newconfig;
623                 
624 /*              int c = 1;
625                 std::string last;
626                 
627                 for(ConfigDataHash::const_iterator i = this->config_data.begin(); i != this->config_data.end(); i++)
628                 {
629                         c = (i->first != last) ? 1 : c+1;
630                         last = i->first;
631                         
632                         std::cout << "[" << i->first << " " << c << "/" << this->config_data.count(i->first) << "]" << std::endl;
633                         
634                         for(KeyValList::const_iterator j = i->second.begin(); j != i->second.end(); j++)
635                                 std::cout << "\t" << j->first << " = " << j->second << std::endl;
636                         
637                         std::cout << "[/" << i->first << " " << c << "/" << this->config_data.count(i->first) << "]" << std::endl;
638                 }
639  */     }
640         else
641         {
642                 log(DEFAULT, "There were errors in your configuration:\n%s", errstr.str().c_str());
643
644                 if (bail)
645                 {
646                         /* Unneeded because of the log() aboive? */
647                         printf("There were errors in your configuration:\n%s",errstr.str().c_str());
648                         Exit(0);
649                 }
650                 else
651                 {
652                         std::string errors = errstr.str();
653                         std::string::size_type start;
654                         unsigned int prefixlen;
655                         
656                         start = 0;
657                         /* ":Config->ServerName NOTICE user->nick :" */
658                         prefixlen = strlen(Config->ServerName) + strlen(user->nick) + 11;
659         
660                         if (user)
661                         {
662                                 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
663                                 
664                                 while(start < errors.length())
665                                 {
666                                         WriteServ(user->fd, "NOTICE %s :%s",user->nick, errors.substr(start, 510 - prefixlen).c_str());
667                                         start += 510 - prefixlen;
668                                 }
669                         }
670                         else
671                         {
672                                 WriteOpers("There were errors in the configuration file:");
673                                 
674                                 while(start < errors.length())
675                                 {
676                                         WriteOpers(errors.substr(start, 360).c_str());
677                                         start += 360;
678                                 }
679                         }
680
681                         return;
682                 }
683         }
684
685         /* Check we dont have more than one of singular tags, or any of them missing
686          */
687         for (int Index = 0; Once[Index]; Index++)
688                 if (!CheckOnce(Once[Index],bail,user))
689                         return;
690
691         /* Read the values of all the tags which occur once or not at all, and call their callbacks.
692          */
693         for (int Index = 0; Values[Index].tag; Index++)
694         {
695                 int* val_i = (int*) Values[Index].val;
696                 char* val_c = (char*) Values[Index].val;
697
698                 switch (Values[Index].datatype)
699                 {
700                         case DT_CHARPTR:
701                                 /* Assuming MAXBUF here, potentially unsafe */
702                                 ConfValue(this->config_data, Values[Index].tag, Values[Index].value, 0, val_c, MAXBUF);
703                         break;
704
705                         case DT_INTEGER:
706                                 ConfValueInteger(this->config_data, Values[Index].tag, Values[Index].value, 0, *val_i);
707                         break;
708
709                         case DT_BOOLEAN:
710                                 *val_i = ConfValueBool(this->config_data, Values[Index].tag, Values[Index].value, 0);
711                         break;
712
713                         case DT_NOTHING:
714                         break;
715                 }
716
717                 Values[Index].validation_function(Values[Index].tag, Values[Index].value, Values[Index].val);
718         }
719
720         /* Claim memory for use when reading multiple tags
721          */
722         for (int n = 0; n < 12; n++)
723                 data[n] = new char[MAXBUF];
724
725         /* Read the multiple-tag items (class tags, connect tags, etc)
726          * and call the callbacks associated with them. We have three
727          * callbacks for these, a 'start', 'item' and 'end' callback.
728          */
729         
730         /* XXX - Make this use ConfValueInteger and so on */
731         for (int Index = 0; MultiValues[Index].tag; Index++)
732         {
733                 MultiValues[Index].init_function(MultiValues[Index].tag);
734
735                 int number_of_tags = ConfValueEnum(this->config_data, MultiValues[Index].tag);
736
737                 for (int tagnum = 0; tagnum < number_of_tags; tagnum++)
738                 {
739                         for (int valuenum = 0; MultiValues[Index].items[valuenum]; valuenum++)
740                         {
741                                 ConfValue(this->config_data, MultiValues[Index].tag, MultiValues[Index].items[valuenum], tagnum, data[valuenum], MAXBUF);
742
743                                 switch (MultiValues[Index].datatype[valuenum])
744                                 {
745                                         case DT_CHARPTR:
746                                                 ptr[valuenum] = data[valuenum];
747                                         break;
748                                         case DT_INTEGER:
749                                                 r_i[valuenum] = atoi(data[valuenum]);
750                                                 ptr[valuenum] = &r_i[valuenum];
751                                         break;
752                                         case DT_BOOLEAN:
753                                                 r_i[valuenum] = ((*data[valuenum] == tolower('y')) || (*data[valuenum] == tolower('t')) || (*data[valuenum] == '1'));
754                                                 ptr[valuenum] = &r_i[valuenum];
755                                         break;
756                                         default:
757                                         break;
758                                 }
759                         }
760                         MultiValues[Index].validation_function(MultiValues[Index].tag, (char**)MultiValues[Index].items, ptr, MultiValues[Index].datatype);
761                 }
762
763                 MultiValues[Index].finish_function(MultiValues[Index].tag);
764         }
765
766         /* Free any memory we claimed
767          */
768         for (int n = 0; n < 12; n++)
769                 delete[] data[n];
770
771         // write once here, to try it out and make sure its ok
772         WritePID(Config->PID);
773
774         log(DEFAULT,"Done reading configuration file, InspIRCd is now starting.");
775
776         /* If we're rehashing, let's load any new modules, and unload old ones
777          */
778         if (!bail)
779         {
780                 ServerInstance->stats->BoundPortCount = BindPorts(false);
781
782                 if (!removed_modules.empty())
783                         for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
784                         {
785                                 if (ServerInstance->UnloadModule(removing->c_str()))
786                                 {
787                                         WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
788
789                                         if (user)
790                                                 WriteServ(user->fd,"973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
791
792                                         rem++;
793                                 }
794                                 else
795                                 {
796                                         if (user)
797                                                 WriteServ(user->fd,"972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ServerInstance->ModuleError());
798                                 }
799                         }
800
801                 if (!added_modules.empty())
802                 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
803                 {
804                         if (ServerInstance->LoadModule(adding->c_str()))
805                         {
806                                 WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
807
808                                 if (user)
809                                         WriteServ(user->fd,"975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
810
811                                 add++;
812                         }
813                         else
814                         {
815                                 if (user)
816                                         WriteServ(user->fd,"974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ServerInstance->ModuleError());
817                         }
818                 }
819
820                 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());
821         }
822 }
823
824 bool ServerConfig::LoadConf(ConfigDataHash &target, const char* filename, std::ostringstream &errorstream)
825 {
826         std::ifstream conf(filename);
827         std::string line;
828         char ch;
829         long linenumber;
830         bool in_tag;
831         bool in_quote;
832         bool in_comment;
833         
834         linenumber = 1;
835         in_tag = false;
836         in_quote = false;
837         in_comment = false;
838         
839         /* Check if the file open failed first */
840         if (!conf)
841         {
842                 errorstream << "LoadConf: Couldn't open config file: " << filename << std::endl;
843                 return false;
844         }
845         
846         /* Fix the chmod of the file to restrict it to the current user and group */
847         chmod(filename,0600);
848         
849         for (unsigned int t = 0; t < include_stack.size(); t++)
850         {
851                 if (std::string(filename) == include_stack[t])
852                 {
853                         errorstream << "File " << filename << " is included recursively (looped inclusion)." << std::endl;
854                         return false;
855                 }
856         }
857         
858         /* It's not already included, add it to the list of files we've loaded */
859         include_stack.push_back(filename);
860         
861         /* Start reading characters... */       
862         while(conf.get(ch))
863         {
864                 /*
865                  * Here we try and get individual tags on separate lines,
866                  * this would be so easy if we just made people format
867                  * their config files like that, but they don't so...
868                  * We check for a '<' and then know the line is over when
869                  * we get a '>' not inside quotes. If we find two '<' and
870                  * no '>' then die with an error.
871                  */
872                 
873                 if((ch == '#') && !in_quote)
874                         in_comment = true;
875                 
876                 if(((ch == '\n') || (ch == '\r')) && in_quote)
877                 {
878                         errorstream << "Got a newline within a quoted section, this is probably a typo: " << filename << ":" << linenumber << std::endl;
879                         return false;
880                 }
881                 
882                 switch(ch)
883                 {
884                         case '\n':
885                                 linenumber++;
886                         case '\r':
887                                 in_comment = false;
888                         case '\0':
889                                 continue;
890                         case '\t':
891                                 ch = ' ';
892                 }
893                 
894                 if(in_comment)
895                         continue;
896
897                 /* XXX: Added by Brain, May 1st 2006 - Escaping of characters.
898                  * Note that this WILL NOT usually allow insertion of newlines,
899                  * because a newline is two characters long. Use it primarily to
900                  * insert the " symbol.
901                  *
902                  * Note that this also involves a further check when parsing the line,
903                  * which can be found below.
904                  */
905                 if ((ch == '\\') && (in_quote) && (in_tag))
906                 {
907                         line += ch;
908                         log(DEBUG,"Escape sequence in config line.");
909                         char real_character;
910                         if (conf.get(real_character))
911                         {
912                                 log(DEBUG,"Escaping %c", real_character);
913                                 line += real_character;
914                                 continue;
915                         }
916                         else
917                         {
918                                 errorstream << "End of file after a \\, what did you want to escape?: " << filename << ":" << linenumber << std::endl;
919                                 return false;
920                         }
921                 }
922
923                 line += ch;
924                 
925                 if(ch == '<')
926                 {
927                         if(in_tag)
928                         {
929                                 if(!in_quote)
930                                 {
931                                         errorstream << "Got another opening < when the first one wasn't closed: " << filename << ":" << linenumber << std::endl;
932                                         return false;
933                                 }
934                         }
935                         else
936                         {
937                                 if(in_quote)
938                                 {
939                                         errorstream << "We're in a quote but outside a tag, interesting. " << filename << ":" << linenumber << std::endl;
940                                         return false;
941                                 }
942                                 else
943                                 {
944                                         // errorstream << "Opening new config tag on line " << linenumber << std::endl;
945                                         in_tag = true;
946                                 }
947                         }
948                 }
949                 else if(ch == '"')
950                 {
951                         if(in_tag)
952                         {
953                                 if(in_quote)
954                                 {
955                                         // errorstream << "Closing quote in config tag on line " << linenumber << std::endl;
956                                         in_quote = false;
957                                 }
958                                 else
959                                 {
960                                         // errorstream << "Opening quote in config tag on line " << linenumber << std::endl;
961                                         in_quote = true;
962                                 }
963                         }
964                         else
965                         {
966                                 if(in_quote)
967                                 {
968                                         errorstream << "Found a (closing) \" outside a tag: " << filename << ":" << linenumber << std::endl;
969                                 }
970                                 else
971                                 {
972                                         errorstream << "Found a (opening) \" outside a tag: " << filename << ":" << linenumber << std::endl;
973                                 }
974                         }
975                 }
976                 else if(ch == '>')
977                 {
978                         if(!in_quote)
979                         {
980                                 if(in_tag)
981                                 {
982                                         // errorstream << "Closing config tag on line " << linenumber << std::endl;
983                                         in_tag = false;
984
985                                         /*
986                                          * If this finds an <include> then ParseLine can simply call
987                                          * LoadConf() and load the included config into the same ConfigDataHash
988                                          */
989                                         
990                                         if(!this->ParseLine(target, line, linenumber, errorstream))
991                                                 return false;
992                                         
993                                         line.clear();
994                                 }
995                                 else
996                                 {
997                                         errorstream << "Got a closing > when we weren't inside a tag: " << filename << ":" << linenumber << std::endl;
998                                         return false;
999                                 }
1000                         }
1001                 }
1002         }
1003         
1004         return true;
1005 }
1006
1007 bool ServerConfig::LoadConf(ConfigDataHash &target, const std::string &filename, std::ostringstream &errorstream)
1008 {
1009         return this->LoadConf(target, filename.c_str(), errorstream);
1010 }
1011
1012 bool ServerConfig::ParseLine(ConfigDataHash &target, std::string &line, long linenumber, std::ostringstream &errorstream)
1013 {
1014         std::string tagname;
1015         std::string current_key;
1016         std::string current_value;
1017         KeyValList results;
1018         bool got_name;
1019         bool got_key;
1020         bool in_quote;
1021         
1022         got_name = got_key = in_quote = false;
1023         
1024         // std::cout << "ParseLine(data, '" << line << "', " << linenumber << ", stream)" << std::endl;
1025         
1026         for(std::string::iterator c = line.begin(); c != line.end(); c++)
1027         {
1028                 if(!got_name)
1029                 {
1030                         /* We don't know the tag name yet. */
1031                         
1032                         if(*c != ' ')
1033                         {
1034                                 if(*c != '<')
1035                                 {
1036                                         tagname += *c;
1037                                 }
1038                         }
1039                         else
1040                         {
1041                                 /* We got to a space, we should have the tagname now. */
1042                                 if(tagname.length())
1043                                 {
1044                                         got_name = true;
1045                                 }
1046                         }
1047                 }
1048                 else
1049                 {
1050                         /* We have the tag name */
1051                         if (!got_key)
1052                         {
1053                                 /* We're still reading the key name */
1054                                 if (*c != '=')
1055                                 {
1056                                         if (*c != ' ')
1057                                         {
1058                                                 current_key += *c;
1059                                         }
1060                                 }
1061                                 else
1062                                 {
1063                                         /* We got an '=', end of the key name. */
1064                                         got_key = true;
1065                                 }
1066                         }
1067                         else
1068                         {
1069                                 /* We have the key name, now we're looking for quotes and the value */
1070
1071                                 /* Correctly handle escaped characters here.
1072                                  * See the XXX'ed section above.
1073                                  */
1074                                 if ((*c == '\\') && (in_quote))
1075                                 {
1076                                         c++;
1077                                         current_value += *c;
1078                                         continue;
1079                                 }
1080                                 if (*c == '"')
1081                                 {
1082                                         if (!in_quote)
1083                                         {
1084                                                 /* We're not already in a quote. */
1085                                                 in_quote = true;
1086                                         }
1087                                         else
1088                                         {
1089                                                 /* Leaving quotes, we have the value */
1090                                                 results.push_back(KeyVal(current_key, current_value));
1091                                                 
1092                                                 // std::cout << "<" << tagname << ":" << current_key << "> " << current_value << std::endl;
1093                                                 
1094                                                 in_quote = false;
1095                                                 got_key = false;
1096                                                 
1097                                                 if((tagname == "include") && (current_key == "file"))
1098                                                 {
1099                                                         if(!this->DoInclude(target, current_value, errorstream))
1100                                                                 return false;
1101                                                 }
1102                                                 
1103                                                 current_key.clear();
1104                                                 current_value.clear();
1105                                         }
1106                                 }
1107                                 else
1108                                 {
1109                                         if(in_quote)
1110                                         {
1111                                                 current_value += *c;
1112                                         }
1113                                 }
1114                         }
1115                 }
1116         }
1117         
1118         /* Finished parsing the tag, add it to the config hash */
1119         target.insert(std::pair<std::string, KeyValList > (tagname, results));
1120         
1121         return true;
1122 }
1123
1124 bool ServerConfig::DoInclude(ConfigDataHash &target, const std::string &file, std::ostringstream &errorstream)
1125 {
1126         std::string confpath;
1127         std::string newfile;
1128         std::string::size_type pos;
1129         
1130         confpath = CONFIG_FILE;
1131         newfile = file;
1132         
1133         for (std::string::iterator c = newfile.begin(); c != newfile.end(); c++)
1134         {
1135                 if (*c == '\\')
1136                 {
1137                         *c = '/';
1138                 }
1139         }
1140
1141         if (file[0] != '/')
1142         {
1143                 if((pos = confpath.find("/inspircd.conf")) != std::string::npos)
1144                 {
1145                         /* Leaves us with just the path */
1146                         newfile = confpath.substr(0, pos) + std::string("/") + newfile;
1147                 }
1148                 else
1149                 {
1150                         errorstream << "Couldn't get config path from: " << confpath << std::endl;
1151                         return false;
1152                 }
1153         }
1154         
1155         return LoadConf(target, newfile, errorstream);
1156 }
1157
1158 bool ServerConfig::ConfValue(ConfigDataHash &target, const char* tag, const char* var, int index, char* result, int length)
1159 {
1160         std::string value;
1161         bool r = ConfValue(target, std::string(tag), std::string(var), index, value);
1162         strlcpy(result, value.c_str(), length);
1163         return r;
1164 }
1165
1166 bool ServerConfig::ConfValue(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, std::string &result)
1167 {
1168         ConfigDataHash::size_type pos = index;
1169         if((pos >= 0) && (pos < target.count(tag)))
1170         {
1171                 ConfigDataHash::const_iterator iter = target.find(tag);
1172                 
1173                 for(int i = 0; i < index; i++)
1174                         iter++;
1175                 
1176                 for(KeyValList::const_iterator j = iter->second.begin(); j != iter->second.end(); j++)
1177                 {
1178                         if(j->first == var)
1179                         {
1180                                 result = j->second;
1181                                 return true;
1182                         }
1183                 }
1184         }
1185         else if(pos == 0)
1186         {
1187                 log(DEBUG, "No <%s> tags in config file.", tag.c_str());
1188         }
1189         else
1190         {
1191                 log(DEBUG, "ConfValue got an out-of-range index %d, there are only %d occurences of %s", pos, target.count(tag), tag.c_str());
1192         }
1193         
1194         return false;
1195 }
1196         
1197 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const char* tag, const char* var, int index, int &result)
1198 {
1199         return ConfValueInteger(target, std::string(tag), std::string(var), index, result);
1200 }
1201
1202 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, int &result)
1203 {
1204         std::string value;
1205         std::istringstream stream;
1206         bool r = ConfValue(target, tag, var, index, value);
1207         stream.str(value);
1208         if(!(stream >> result))
1209                 return false;
1210         return r;
1211 }
1212         
1213 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const char* tag, const char* var, int index)
1214 {
1215         return ConfValueBool(target, std::string(tag), std::string(var), index);
1216 }
1217
1218 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const std::string &tag, const std::string &var, int index)
1219 {
1220         std::string result;
1221         if(!ConfValue(target, tag, var, index, result))
1222                 return false;
1223         
1224         return ((result == "yes") || (result == "true") || (result == "1"));
1225 }
1226         
1227 int ServerConfig::ConfValueEnum(ConfigDataHash &target, const char* tag)
1228 {
1229         return target.count(tag);
1230 }
1231
1232 int ServerConfig::ConfValueEnum(ConfigDataHash &target, const std::string &tag)
1233 {
1234         return target.count(tag);
1235 }
1236         
1237 int ServerConfig::ConfVarEnum(ConfigDataHash &target, const char* tag, int index)
1238 {
1239         return ConfVarEnum(target, std::string(tag), index);
1240 }
1241
1242 int ServerConfig::ConfVarEnum(ConfigDataHash &target, const std::string &tag, int index)
1243 {
1244         ConfigDataHash::size_type pos = index;
1245         
1246         if((pos >= 0) && (pos < target.count(tag)))
1247         {
1248                 ConfigDataHash::const_iterator iter = target.find(tag);
1249                 
1250                 for(int i = 0; i < index; i++)
1251                         iter++;
1252                 
1253                 return iter->second.size();
1254         }
1255         else if(pos == 0)
1256         {
1257                 log(DEBUG, "No <%s> tags in config file.", tag.c_str());
1258         }
1259         else
1260         {
1261                 log(DEBUG, "ConfVarEnum got an out-of-range index %d, there are only %d occurences of %s", pos, target.count(tag), tag.c_str());
1262         }
1263         
1264         return 0;
1265 }