]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/configreader.cpp
Executable include for MOTD and more
[user/henk/code/inspircd.git] / src / configreader.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2010 InspIRCd Development Team
6  * See: http://wiki.inspircd.org/Credits
7  *
8  * This program is free but copyrighted software; see
9  *          the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 /* $Core */
15 /* $CopyInstall: conf/inspircd.quotes.example $(CONPATH) */
16 /* $CopyInstall: conf/inspircd.rules.example $(CONPATH) */
17 /* $CopyInstall: conf/inspircd.motd.example $(CONPATH) */
18 /* $CopyInstall: conf/inspircd.helpop-full.example $(CONPATH) */
19 /* $CopyInstall: conf/inspircd.helpop.example $(CONPATH) */
20 /* $CopyInstall: conf/inspircd.censor.example $(CONPATH) */
21 /* $CopyInstall: conf/inspircd.filter.example $(CONPATH) */
22 /* $CopyInstall: conf/inspircd.conf.example $(CONPATH) */
23 /* $CopyInstall: conf/modules.conf.example $(CONPATH) */
24 /* $CopyInstall: conf/opers.conf.example $(CONPATH) */
25 /* $CopyInstall: conf/links.conf.example $(CONPATH) */
26 /* $CopyInstall: tools/gdbargs $(BASE)/.gdbargs */
27
28 #include "inspircd.h"
29 #include <fstream>
30 #include "xline.h"
31 #include "exitcodes.h"
32 #include "commands/cmd_whowas.h"
33 #include "configparser.h"
34
35 ServerConfig::ServerConfig()
36 {
37         WhoWasGroupSize = WhoWasMaxGroups = WhoWasMaxKeep = 0;
38         NoUserDns = OperSpyWhois = HideBans = HideSplits = UndernetMsgPrefix = false;
39         CycleHosts = InvBypassModes = true;
40         dns_timeout = 5;
41         MaxTargets = 20;
42         NetBufferSize = 10240;
43         SoftLimit = ServerInstance->SE->GetMaxFds();
44         MaxConn = SOMAXCONN;
45         MaxChans = 20;
46         OperMaxChans = 30;
47         c_ipv4_range = 32;
48         c_ipv6_range = 128;
49 }
50
51 void ServerConfig::Update005()
52 {
53         std::stringstream out(data005);
54         std::vector<std::string> data;
55         std::string token;
56         while (out >> token)
57                 data.push_back(token);
58         sort(data.begin(), data.end());
59
60         std::string line5;
61         isupport.clear();
62         for(unsigned int i=0; i < data.size(); i++)
63         {
64                 token = data[i];
65                 line5 = line5 + token + " ";
66                 if (i % 13 == 12)
67                 {
68                         line5.append(":are supported by this server");
69                         isupport.push_back(line5);
70                         line5.clear();
71                 }
72         }
73         if (!line5.empty())
74         {
75                 line5.append(":are supported by this server");
76                 isupport.push_back(line5);
77         }
78 }
79
80 void ServerConfig::Send005(User* user)
81 {
82         for (std::vector<std::string>::iterator line = ServerInstance->Config->isupport.begin(); line != ServerInstance->Config->isupport.end(); line++)
83                 user->WriteNumeric(RPL_ISUPPORT, "%s %s", user->nick.c_str(), line->c_str());
84 }
85
86 template<typename T, typename V>
87 static void range(T& value, V min, V max, V def, const char* msg)
88 {
89         if (value >= (T)min && value <= (T)max)
90                 return;
91         ServerInstance->Logs->Log("CONFIG", DEFAULT,
92                 "WARNING: %s value of %ld is not between %ld and %ld; set to %ld.",
93                 msg, (long)value, (long)min, (long)max, (long)def);
94         value = def;
95 }
96
97
98 static void ValidIP(const std::string& ip, const std::string& key)
99 {
100         irc::sockets::sockaddrs dummy;
101         if (!irc::sockets::aptosa(ip, 0, dummy))
102                 throw CoreException("The value of "+key+" is not an IP address");
103 }
104
105 static void ValidHost(const std::string& p, const std::string& msg)
106 {
107         int num_dots = 0;
108         if (p.empty() || p[0] == '.')
109                 throw CoreException("The value of "+msg+" is not a valid hostname");
110         for (unsigned int i=0;i < p.length();i++)
111         {
112                 switch (p[i])
113                 {
114                         case ' ':
115                                 throw CoreException("The value of "+msg+" is not a valid hostname");
116                         case '.':
117                                 num_dots++;
118                         break;
119                 }
120         }
121         if (num_dots == 0)
122                 throw CoreException("The value of "+msg+" is not a valid hostname");
123 }
124
125 bool ServerConfig::ApplyDisabledCommands(const std::string& data)
126 {
127         std::stringstream dcmds(data);
128         std::string thiscmd;
129
130         /* Enable everything first */
131         for (Commandtable::iterator x = ServerInstance->Parser->cmdlist.begin(); x != ServerInstance->Parser->cmdlist.end(); x++)
132                 x->second->Disable(false);
133
134         /* Now disable all the ones which the user wants disabled */
135         while (dcmds >> thiscmd)
136         {
137                 Commandtable::iterator cm = ServerInstance->Parser->cmdlist.find(thiscmd);
138                 if (cm != ServerInstance->Parser->cmdlist.end())
139                 {
140                         cm->second->Disable(true);
141                 }
142         }
143         return true;
144 }
145
146 #ifdef WINDOWS
147 // Note: the windows validator is in win32wrapper.cpp
148 void FindDNS(std::string& server);
149 #else
150 static void FindDNS(std::string& server)
151 {
152         if (!server.empty())
153                 return;
154
155         // attempt to look up their nameserver from /etc/resolv.conf
156         ServerInstance->Logs->Log("CONFIG",DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
157
158         std::ifstream resolv("/etc/resolv.conf");
159
160         while (resolv >> server)
161         {
162                 if (server == "nameserver")
163                 {
164                         resolv >> server;
165                         ServerInstance->Logs->Log("CONFIG",DEFAULT,"<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",server.c_str());
166                         return;
167                 }
168         }
169
170         ServerInstance->Logs->Log("CONFIG",DEFAULT,"/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
171         server = "127.0.0.1";
172 }
173 #endif
174
175 static void ReadXLine(ServerConfig* conf, const std::string& tag, const std::string& key, XLineFactory* make)
176 {
177         ConfigTagList tags = conf->ConfTags(tag);
178         for(ConfigIter i = tags.first; i != tags.second; ++i)
179         {
180                 ConfigTag* ctag = i->second;
181                 std::string mask;
182                 if (!ctag->readString(key, mask))
183                         throw CoreException("<"+tag+":"+key+"> missing at " + ctag->getTagLocation());
184                 std::string reason = ctag->getString("reason", "<Config>");
185                 XLine* xl = make->Generate(ServerInstance->Time(), 0, "<Config>", reason, mask);
186                 if (!ServerInstance->XLines->AddLine(xl, NULL))
187                         delete xl;
188         }
189 }
190
191 typedef std::map<std::string, ConfigTag*> LocalIndex;
192 void ServerConfig::CrossCheckOperClassType()
193 {
194         LocalIndex operclass;
195         ConfigTagList tags = ConfTags("class");
196         for(ConfigIter i = tags.first; i != tags.second; ++i)
197         {
198                 ConfigTag* tag = i->second;
199                 std::string name = tag->getString("name");
200                 if (name.empty())
201                         throw CoreException("<class:name> missing from tag at " + tag->getTagLocation());
202                 operclass[name] = tag;
203         }
204         tags = ConfTags("type");
205         for(ConfigIter i = tags.first; i != tags.second; ++i)
206         {
207                 ConfigTag* tag = i->second;
208                 std::string name = tag->getString("name");
209                 if (name.empty())
210                         throw CoreException("<type:name> is missing from tag at " + tag->getTagLocation());
211
212                 if (!ServerInstance->IsNick(name.c_str(), Limits.NickMax))
213                         throw CoreException("<type:name> is invalid (value '" + name + "')");
214
215                 OperInfo* ifo = new OperInfo;
216                 oper_blocks[" " + name] = ifo;
217                 ifo->name = name;
218                 ifo->type_block = tag;
219
220                 std::string classname;
221                 irc::spacesepstream str(tag->getString("classes"));
222                 while (str.GetToken(classname))
223                 {
224                         LocalIndex::iterator cls = operclass.find(classname);
225                         if (cls == operclass.end())
226                                 throw CoreException("Oper type " + name + " has missing class " + classname);
227                         ifo->class_blocks.push_back(cls->second);
228                 }
229         }
230
231         tags = ConfTags("oper");
232         for(ConfigIter i = tags.first; i != tags.second; ++i)
233         {
234                 ConfigTag* tag = i->second;
235
236                 std::string name = tag->getString("name");
237                 if (name.empty())
238                         throw CoreException("<oper:name> missing from tag at " + tag->getTagLocation());
239
240                 std::string type = tag->getString("type");
241                 OperIndex::iterator tblk = oper_blocks.find(" " + type);
242                 if (tblk == oper_blocks.end())
243                         throw CoreException("Oper block " + name + " has missing type " + type);
244                 if (oper_blocks.find(name) != oper_blocks.end())
245                         throw CoreException("Duplicate oper block with name " + name);
246
247                 OperInfo* ifo = new OperInfo;
248                 ifo->name = type;
249                 ifo->oper_block = tag;
250                 ifo->type_block = tblk->second->type_block;
251                 ifo->class_blocks.assign(tblk->second->class_blocks.begin(), tblk->second->class_blocks.end());
252                 oper_blocks[name] = ifo;
253         }
254 }
255
256 void ServerConfig::CrossCheckConnectBlocks(ServerConfig* current)
257 {
258         typedef std::map<std::string, ConnectClass*> ClassMap;
259         ClassMap oldBlocksByMask;
260         if (current)
261         {
262                 for(ClassVector::iterator i = current->Classes.begin(); i != current->Classes.end(); ++i)
263                 {
264                         ConnectClass* c = *i;
265                         if (c->name.substr(0, 8) != "unnamed-")
266                         {
267                                 oldBlocksByMask["n" + c->name] = c;
268                         }
269                         else if (c->type == CC_ALLOW || c->type == CC_DENY)
270                         {
271                                 std::string typeMask = (c->type == CC_ALLOW) ? "a" : "d";
272                                 typeMask += c->host;
273                                 oldBlocksByMask[typeMask] = c;
274                         }
275                 }
276         }
277
278         int blk_count = config_data.count("connect");
279         if (blk_count == 0)
280         {
281                 // No connect blocks found; make a trivial default block
282                 std::vector<KeyVal>* items;
283                 ConfigTag* tag = ConfigTag::create("connect", "<auto>", 0, items);
284                 items->push_back(std::make_pair("allow", "*"));
285                 config_data.insert(std::make_pair("connect", tag));
286                 blk_count = 1;
287         }
288
289         Classes.resize(blk_count);
290         std::map<std::string, int> names;
291
292         bool try_again = true;
293         for(int tries=0; try_again; tries++)
294         {
295                 try_again = false;
296                 ConfigTagList tags = ConfTags("connect");
297                 int i=0;
298                 for(ConfigIter it = tags.first; it != tags.second; ++it, ++i)
299                 {
300                         ConfigTag* tag = it->second;
301                         if (Classes[i])
302                                 continue;
303
304                         ConnectClass* parent = NULL;
305                         std::string parentName = tag->getString("parent");
306                         if (!parentName.empty())
307                         {
308                                 std::map<std::string,int>::iterator parentIter = names.find(parentName);
309                                 if (parentIter == names.end())
310                                 {
311                                         try_again = true;
312                                         // couldn't find parent this time. If it's the last time, we'll never find it.
313                                         if (tries >= blk_count)
314                                                 throw CoreException("Could not find parent connect class \"" + parentName + "\" for connect block at " + tag->getTagLocation());
315                                         continue;
316                                 }
317                                 parent = Classes[parentIter->second];
318                         }
319
320                         std::string name = tag->getString("name");
321                         std::string mask, typeMask;
322                         char type;
323
324                         if (tag->readString("allow", mask, false))
325                         {
326                                 type = CC_ALLOW;
327                                 typeMask = 'a' + mask;
328                         }
329                         else if (tag->readString("deny", mask, false))
330                         {
331                                 type = CC_DENY;
332                                 typeMask = 'd' + mask;
333                         }
334                         else if (!name.empty())
335                         {
336                                 type = CC_NAMED;
337                                 mask = name;
338                                 typeMask = 'n' + mask;
339                         }
340                         else
341                         {
342                                 throw CoreException("Connect class must have allow, deny, or name specified at " + tag->getTagLocation());
343                         }
344
345                         if (name.empty())
346                         {
347                                 name = "unnamed-" + ConvToStr(i);
348                         }
349                         else
350                         {
351                                 typeMask = 'n' + name;
352                         }
353
354                         if (names.find(name) != names.end())
355                                 throw CoreException("Two connect classes with name \"" + name + "\" defined!");
356                         names[name] = i;
357
358                         ConnectClass* me = parent ? 
359                                 new ConnectClass(tag, type, mask, *parent) :
360                                 new ConnectClass(tag, type, mask);
361
362                         me->name = name;
363
364                         me->registration_timeout = tag->getInt("timeout", me->registration_timeout);
365                         me->pingtime = tag->getInt("pingfreq", me->pingtime);
366                         std::string sendq;
367                         if (tag->readString("sendq", sendq))
368                         {
369                                 // attempt to guess a good hard/soft sendq from a single value
370                                 long value = atol(sendq.c_str());
371                                 if (value > 16384)
372                                         me->softsendqmax = value / 16;
373                                 else
374                                         me->softsendqmax = value;
375                                 me->hardsendqmax = value * 8;
376                         }
377                         me->softsendqmax = tag->getInt("softsendq", me->softsendqmax);
378                         me->hardsendqmax = tag->getInt("hardsendq", me->hardsendqmax);
379                         me->recvqmax = tag->getInt("recvq", me->recvqmax);
380                         me->penaltythreshold = tag->getInt("threshold", me->penaltythreshold);
381                         me->commandrate = tag->getInt("commandrate", me->commandrate);
382                         me->fakelag = tag->getBool("fakelag", me->fakelag);
383                         me->maxlocal = tag->getInt("localmax", me->maxlocal);
384                         me->maxglobal = tag->getInt("globalmax", me->maxglobal);
385                         me->maxchans = tag->getInt("maxchans", me->maxchans);
386                         me->limit = tag->getInt("limit", me->limit);
387
388                         ClassMap::iterator oldMask = oldBlocksByMask.find(typeMask);
389                         if (oldMask != oldBlocksByMask.end())
390                         {
391                                 ConnectClass* old = oldMask->second;
392                                 oldBlocksByMask.erase(oldMask);
393                                 old->Update(me);
394                                 delete me;
395                                 me = old;
396                         }
397                         Classes[i] = me;
398                 }
399         }
400 }
401
402 /** Represents a deprecated configuration tag.
403  */
404 struct Deprecated
405 {
406         /** Tag name
407          */
408         const char* tag;
409         /** Tag value
410          */
411         const char* value;
412         /** Reason for deprecation
413          */
414         const char* reason;
415 };
416
417 static const Deprecated ChangedConfig[] = {
418         {"options", "hidelinks",                "has been moved to <security:hidelinks> as of 1.2a3"},
419         {"options", "hidewhois",                "has been moved to <security:hidewhois> as of 1.2a3"},
420         {"options", "userstats",                "has been moved to <security:userstats> as of 1.2a3"},
421         {"options", "customversion",    "has been moved to <security:customversion> as of 1.2a3"},
422         {"options", "hidesplits",               "has been moved to <security:hidesplits> as of 1.2a3"},
423         {"options", "hidebans",         "has been moved to <security:hidebans> as of 1.2a3"},
424         {"options", "hidekills",                "has been moved to <security:hidekills> as of 1.2a3"},
425         {"options", "operspywhois",             "has been moved to <security:operspywhois> as of 1.2a3"},
426         {"options", "announceinvites",  "has been moved to <security:announceinvites> as of 1.2a3"},
427         {"options", "hidemodes",                "has been moved to <security:hidemodes> as of 1.2a3"},
428         {"options", "maxtargets",               "has been moved to <security:maxtargets> as of 1.2a3"},
429         {"options",     "nouserdns",            "has been moved to <performance:nouserdns> as of 1.2a3"},
430         {"options",     "maxwho",               "has been moved to <performance:maxwho> as of 1.2a3"},
431         {"options",     "softlimit",            "has been moved to <performance:softlimit> as of 1.2a3"},
432         {"options", "somaxconn",                "has been moved to <performance:somaxconn> as of 1.2a3"},
433         {"options", "netbuffersize",    "has been moved to <performance:netbuffersize> as of 1.2a3"},
434         {"options", "maxwho",           "has been moved to <performance:maxwho> as of 1.2a3"},
435         {"options",     "loglevel",             "1.2 does not use the loglevel value. Please define <log> tags instead."},
436         {"die",     "value",            "you need to reread your config"},
437 };
438
439 void ServerConfig::Fill()
440 {
441         ConfigTag* options = ConfValue("options");
442         ConfigTag* security = ConfValue("security");
443         diepass = ConfValue("power")->getString("diepass");
444         restartpass = ConfValue("power")->getString("restartpass");
445         powerhash = ConfValue("power")->getString("hash");
446         PrefixQuit = options->getString("prefixquit");
447         SuffixQuit = options->getString("suffixquit");
448         FixedQuit = options->getString("fixedquit");
449         PrefixPart = options->getString("prefixpart");
450         SuffixPart = options->getString("suffixpart");
451         FixedPart = options->getString("fixedpart");
452         SoftLimit = ConfValue("performance")->getInt("softlimit", ServerInstance->SE->GetMaxFds());
453         MaxConn = ConfValue("performance")->getInt("somaxconn", SOMAXCONN);
454         MoronBanner = options->getString("moronbanner", "You're banned!");
455         ServerName = ConfValue("server")->getString("name");
456         ServerDesc = ConfValue("server")->getString("description", "Configure Me");
457         Network = ConfValue("server")->getString("network", "Network");
458         sid = ConfValue("server")->getString("id", "");
459         AdminName = ConfValue("admin")->getString("name", "");
460         AdminEmail = ConfValue("admin")->getString("email", "null@example.com");
461         AdminNick = ConfValue("admin")->getString("nick", "admin");
462         ModPath = ConfValue("path")->getString("moduledir", MOD_PATH);
463         NetBufferSize = ConfValue("performance")->getInt("netbuffersize", 10240);
464         dns_timeout = ConfValue("dns")->getInt("timeout", 5);
465         DisabledCommands = ConfValue("disabled")->getString("commands", "");
466         DisabledDontExist = ConfValue("disabled")->getBool("fakenonexistant");
467         UserStats = security->getString("userstats");
468         CustomVersion = security->getString("customversion");
469         HideSplits = security->getBool("hidesplits");
470         HideBans = security->getBool("hidebans");
471         HideWhoisServer = security->getString("hidewhois");
472         HideKillsServer = security->getString("hidekills");
473         OperSpyWhois = security->getBool("operspywhois");
474         RestrictBannedUsers = security->getBool("restrictbannedusers", true);
475         GenericOper = security->getBool("genericoper");
476         NoUserDns = ConfValue("performance")->getBool("nouserdns");
477         SyntaxHints = options->getBool("syntaxhints");
478         CycleHosts = options->getBool("cyclehosts");
479         UndernetMsgPrefix = options->getBool("ircumsgprefix");
480         FullHostInTopic = options->getBool("hostintopic");
481         MaxTargets = security->getInt("maxtargets", 20);
482         DefaultModes = options->getString("defaultmodes", "nt");
483         PID = ConfValue("pid")->getString("file");
484         WhoWasGroupSize = ConfValue("whowas")->getInt("groupsize");
485         WhoWasMaxGroups = ConfValue("whowas")->getInt("maxgroups");
486         WhoWasMaxKeep = ServerInstance->Duration(ConfValue("whowas")->getString("maxkeep"));
487         DieValue = ConfValue("die")->getString("value");
488         MaxChans = ConfValue("channels")->getInt("users", 20);
489         OperMaxChans = ConfValue("channels")->getInt("opers", 60);
490         c_ipv4_range = ConfValue("cidr")->getInt("ipv4clone", 32);
491         c_ipv6_range = ConfValue("cidr")->getInt("ipv6clone", 128);
492         Limits.NickMax = ConfValue("limits")->getInt("maxnick", 32);
493         Limits.ChanMax = ConfValue("limits")->getInt("maxchan", 64);
494         Limits.MaxModes = ConfValue("limits")->getInt("maxmodes", 20);
495         Limits.IdentMax = ConfValue("limits")->getInt("maxident", 11);
496         Limits.MaxQuit = ConfValue("limits")->getInt("maxquit", 255);
497         Limits.MaxTopic = ConfValue("limits")->getInt("maxtopic", 307);
498         Limits.MaxKick = ConfValue("limits")->getInt("maxkick", 255);
499         Limits.MaxGecos = ConfValue("limits")->getInt("maxgecos", 128);
500         Limits.MaxAway = ConfValue("limits")->getInt("maxaway", 200);
501         InvBypassModes = options->getBool("invitebypassmodes", true);
502
503         range(SoftLimit, 10, ServerInstance->SE->GetMaxFds(), ServerInstance->SE->GetMaxFds(), "<performance:softlimit>");
504         range(MaxConn, 0, SOMAXCONN, SOMAXCONN, "<performance:somaxconn>");
505         range(MaxTargets, 1, 31, 20, "<security:maxtargets>");
506         range(NetBufferSize, 1024, 65534, 10240, "<performance:netbuffersize>");
507         range(WhoWasGroupSize, 0, 10000, 10, "<whowas:groupsize>");
508         range(WhoWasMaxGroups, 0, 1000000, 10240, "<whowas:maxgroups>");
509         range(WhoWasMaxKeep, 3600, INT_MAX, 3600, "<whowas:maxkeep>");
510
511         ValidIP(DNSServer, "<dns:server>");
512         ValidHost(ServerName, "<server:name>");
513         if (!sid.empty() && !ServerInstance->IsSID(sid))
514                 throw CoreException(sid + " is not a valid server ID. A server ID must be 3 characters long, with the first character a digit and the next two characters a digit or letter.");
515
516         ConfigTagList tags = ConfTags("uline");
517         for(ConfigIter i = tags.first; i != tags.second; ++i)
518         {
519                 ConfigTag* tag = i->second;
520                 std::string server;
521                 if (!tag->readString("server", server))
522                         throw CoreException("<uline> tag missing server at " + tag->getTagLocation());
523                 ulines[assign(server)] = tag->getBool("silent");
524         }
525
526         tags = ConfTags("banlist");
527         for(ConfigIter i = tags.first; i != tags.second; ++i)
528         {
529                 ConfigTag* tag = i->second;
530                 std::string chan;
531                 if (!tag->readString("chan", chan))
532                         throw CoreException("<banlist> tag missing chan at " + tag->getTagLocation());
533                 maxbans[chan] = tag->getInt("limit");
534         }
535
536         ReadXLine(this, "badip", "ipmask", ServerInstance->XLines->GetFactory("Z"));
537         ReadXLine(this, "badnick", "nick", ServerInstance->XLines->GetFactory("Q"));
538         ReadXLine(this, "badhost", "host", ServerInstance->XLines->GetFactory("K"));
539         ReadXLine(this, "exception", "host", ServerInstance->XLines->GetFactory("E"));
540
541         memset(DisabledUModes, 0, sizeof(DisabledUModes));
542         for (const unsigned char* p = (const unsigned char*)ConfValue("disabled")->getString("usermodes").c_str(); *p; ++p)
543         {
544                 if (*p < 'A' || *p > ('A' + 64)) throw CoreException(std::string("Invalid usermode ")+(char)*p+" was found.");
545                 DisabledUModes[*p - 'A'] = 1;
546         }
547
548         memset(DisabledCModes, 0, sizeof(DisabledCModes));
549         for (const unsigned char* p = (const unsigned char*)ConfValue("disabled")->getString("chanmodes").c_str(); *p; ++p)
550         {
551                 if (*p < 'A' || *p > ('A' + 64)) throw CoreException(std::string("Invalid chanmode ")+(char)*p+" was found.");
552                 DisabledCModes[*p - 'A'] = 1;
553         }
554
555         memset(HideModeLists, 0, sizeof(HideModeLists));
556         for (const unsigned char* p = (const unsigned char*)ConfValue("security")->getString("hidemodes").c_str(); *p; ++p)
557                 HideModeLists[*p] = true;
558
559         std::string v = security->getString("announceinvites");
560
561         if (v == "ops")
562                 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_OPS;
563         else if (v == "all")
564                 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_ALL;
565         else if (v == "dynamic")
566                 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_DYNAMIC;
567         else
568                 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_NONE;
569
570         Limits.Finalise();
571 }
572
573 // WARNING: it is not safe to use most of the codebase in this function, as it
574 // will run in the config reader thread
575 void ServerConfig::Read()
576 {
577         /* Load and parse the config file, if there are any errors then explode */
578
579         ParseStack stack(this);
580         try
581         {
582                 valid = stack.ParseFile(ServerInstance->ConfigFileName, 0);
583         }
584         catch (CoreException& err)
585         {
586                 valid = false;
587                 errstr << err.GetReason();
588         }
589         if (valid)
590         {
591                 DNSServer = ConfValue("dns")->getString("server");
592                 FindDNS(DNSServer);
593         }
594 }
595
596 void ServerConfig::Apply(ServerConfig* old, const std::string &useruid)
597 {
598         valid = true;
599
600         /* The stuff in here may throw CoreException, be sure we're in a position to catch it. */
601         try
602         {
603                 for (int Index = 0; Index * sizeof(Deprecated) < sizeof(ChangedConfig); Index++)
604                 {
605                         std::string dummy;
606                         if (ConfValue(ChangedConfig[Index].tag)->readString(ChangedConfig[Index].value, dummy, true))
607                                 errstr << "Your configuration contains a deprecated value: <"
608                                         << ChangedConfig[Index].tag << ":" << ChangedConfig[Index].value << "> - " << ChangedConfig[Index].reason
609                                         << " (at " << ConfValue(ChangedConfig[Index].tag)->getTagLocation() << ")\n";
610                 }
611
612                 Fill();
613
614                 // Handle special items
615                 CrossCheckOperClassType();
616                 CrossCheckConnectBlocks(old);
617         }
618         catch (CoreException &ce)
619         {
620                 errstr << ce.GetReason();
621         }
622
623         // write once here, to try it out and make sure its ok
624         ServerInstance->WritePID(this->PID);
625
626         // Check errors before dealing with failed binds, since continuing on failed bind is wanted in some circumstances.
627         valid = errstr.str().empty();
628
629         /*
630          * These values can only be set on boot. Keep their old values. Do it before we send messages so we actually have a servername.
631          */
632         if (old)
633         {
634                 this->ServerName = old->ServerName;
635                 this->sid = old->sid;
636                 this->cmdline = old->cmdline;
637
638                 // Same for ports... they're bound later on first run.
639                 FailedPortList pl;
640                 ServerInstance->BindPorts(pl);
641                 if (pl.size())
642                 {
643                         errstr << "Not all your client ports could be bound.\nThe following port(s) failed to bind:\n";
644
645                         int j = 1;
646                         for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
647                         {
648                                 char buf[MAXBUF];
649                                 snprintf(buf, MAXBUF, "%d.   Address: %s   Reason: %s\n", j, i->first.empty() ? "<all>" : i->first.c_str(), i->second.c_str());
650                                 errstr << buf;
651                         }
652                 }
653         }
654
655         User* user = useruid.empty() ? NULL : ServerInstance->FindNick(useruid);
656
657         if (!valid)
658                 ServerInstance->Logs->Log("CONFIG",DEFAULT, "There were errors in your configuration file:");
659
660         while (errstr.good())
661         {
662                 std::string line;
663                 getline(errstr, line, '\n');
664                 if (!line.empty())
665                 {
666                         if (user)
667                                 user->WriteServ("NOTICE %s :*** %s", user->nick.c_str(), line.c_str());
668                         else
669                                 ServerInstance->SNO->WriteGlobalSno('a', line);
670                 }
671
672                 if (!old)
673                 {
674                         // Starting up, so print it out so it's seen. XXX this is a bit of a hack.
675                         printf("%s\n", line.c_str());
676                 }
677         }
678
679         errstr.clear();
680         errstr.str(std::string());
681
682         /* No old configuration -> initial boot, nothing more to do here */
683         if (!old)
684         {
685                 if (!valid)
686                 {
687                         ServerInstance->Exit(EXIT_STATUS_CONFIG);
688                 }
689
690                 return;
691         }
692
693         // If there were errors processing configuration, don't touch modules.
694         if (!valid)
695                 return;
696
697         ApplyModules(user);
698
699         if (user)
700                 user->WriteServ("NOTICE %s :*** Successfully rehashed server.", user->nick.c_str());
701         ServerInstance->SNO->WriteGlobalSno('a', "*** Successfully rehashed server.");
702 }
703
704 void ServerConfig::ApplyModules(User* user)
705 {
706         Module* whowas = ServerInstance->Modules->Find("cmd_whowas.so");
707         if (whowas)
708                 WhowasRequest(NULL, whowas, WhowasRequest::WHOWAS_PRUNE).Send();
709
710         const std::vector<std::string> v = ServerInstance->Modules->GetAllModuleNames(0);
711         std::vector<std::string> added_modules;
712         std::set<std::string> removed_modules(v.begin(), v.end());
713
714         ConfigTagList tags = ConfTags("module");
715         for(ConfigIter i = tags.first; i != tags.second; ++i)
716         {
717                 ConfigTag* tag = i->second;
718                 std::string name;
719                 if (tag->readString("name", name))
720                 {
721                         // if this module is already loaded, the erase will succeed, so we need do nothing
722                         // otherwise, we need to add the module (which will be done later)
723                         if (removed_modules.erase(name) == 0)
724                                 added_modules.push_back(name);
725                 }
726         }
727
728         if (ConfValue("options")->getBool("allowhalfop") && removed_modules.erase("m_halfop.so") == 0)
729                 added_modules.push_back("m_halfop.so");
730
731         for (std::set<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
732         {
733                 // Don't remove cmd_*.so, just remove m_*.so
734                 if (removing->c_str()[0] == 'c')
735                         continue;
736                 Module* m = ServerInstance->Modules->Find(*removing);
737                 if (m && ServerInstance->Modules->Unload(m))
738                 {
739                         ServerInstance->SNO->WriteGlobalSno('a', "*** REHASH UNLOADED MODULE: %s",removing->c_str());
740
741                         if (user)
742                                 user->WriteNumeric(RPL_UNLOADEDMODULE, "%s %s :Module %s successfully unloaded.",user->nick.c_str(), removing->c_str(), removing->c_str());
743                         else
744                                 ServerInstance->SNO->WriteGlobalSno('a', "Module %s successfully unloaded.", removing->c_str());
745                 }
746                 else
747                 {
748                         if (user)
749                                 user->WriteNumeric(ERR_CANTUNLOADMODULE, "%s %s :Failed to unload module %s: %s",user->nick.c_str(), removing->c_str(), removing->c_str(), ServerInstance->Modules->LastError().c_str());
750                         else
751                                  ServerInstance->SNO->WriteGlobalSno('a', "Failed to unload module %s: %s", removing->c_str(), ServerInstance->Modules->LastError().c_str());
752                 }
753         }
754
755         for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
756         {
757                 if (ServerInstance->Modules->Load(adding->c_str()))
758                 {
759                         ServerInstance->SNO->WriteGlobalSno('a', "*** REHASH LOADED MODULE: %s",adding->c_str());
760                         if (user)
761                                 user->WriteNumeric(RPL_LOADEDMODULE, "%s %s :Module %s successfully loaded.",user->nick.c_str(), adding->c_str(), adding->c_str());
762                         else
763                                 ServerInstance->SNO->WriteGlobalSno('a', "Module %s successfully loaded.", adding->c_str());
764                 }
765                 else
766                 {
767                         if (user)
768                                 user->WriteNumeric(ERR_CANTLOADMODULE, "%s %s :Failed to load module %s: %s",user->nick.c_str(), adding->c_str(), adding->c_str(), ServerInstance->Modules->LastError().c_str());
769                         else
770                                 ServerInstance->SNO->WriteGlobalSno('a', "Failed to load module %s: %s", adding->c_str(), ServerInstance->Modules->LastError().c_str());
771                 }
772         }
773 }
774
775 bool ServerConfig::StartsWithWindowsDriveLetter(const std::string &path)
776 {
777         return (path.length() > 2 && isalpha(path[0]) && path[1] == ':');
778 }
779
780 ConfigTag* ServerConfig::ConfValue(const std::string &tag)
781 {
782         ConfigDataHash::iterator iter = config_data.find(tag);
783         if (iter == config_data.end())
784                 return NULL;
785         return iter->second;
786 }
787
788 ConfigTagList ServerConfig::ConfTags(const std::string& tag)
789 {
790         return config_data.equal_range(tag);
791 }
792
793 bool ServerConfig::FileExists(const char* file)
794 {
795         struct stat sb;
796         if (stat(file, &sb) == -1)
797                 return false;
798
799         if ((sb.st_mode & S_IFDIR) > 0)
800                 return false;
801
802         FILE *input = fopen(file, "r");
803         if (input == NULL)
804                 return false;
805         else
806         {
807                 fclose(input);
808                 return true;
809         }
810 }
811
812 const char* ServerConfig::CleanFilename(const char* name)
813 {
814         const char* p = name + strlen(name);
815         while ((p != name) && (*p != '/') && (*p != '\\')) p--;
816         return (p != name ? ++p : p);
817 }
818
819 std::string ServerConfig::GetSID()
820 {
821         return sid;
822 }
823
824 void ConfigReaderThread::Run()
825 {
826         Config->Read();
827         done = true;
828 }
829
830 void ConfigReaderThread::Finish()
831 {
832         ServerConfig* old = ServerInstance->Config;
833         ServerInstance->Logs->Log("CONFIG",DEBUG,"Switching to new configuration...");
834         ServerInstance->Logs->CloseLogs();
835         ServerInstance->Config = this->Config;
836         ServerInstance->Logs->OpenFileLogs();
837         Config->Apply(old, TheUserUID);
838
839         if (Config->valid)
840         {
841                 /*
842                  * Apply the changed configuration from the rehash.
843                  *
844                  * XXX: The order of these is IMPORTANT, do not reorder them without testing
845                  * thoroughly!!!
846                  */
847                 ServerInstance->XLines->CheckELines();
848                 ServerInstance->XLines->CheckELines();
849                 ServerInstance->XLines->ApplyLines();
850                 ServerInstance->Res->Rehash();
851                 ServerInstance->ResetMaxBans();
852                 Config->ApplyDisabledCommands(Config->DisabledCommands);
853                 User* user = ServerInstance->FindNick(TheUserUID);
854                 FOREACH_MOD(I_OnRehash, OnRehash(user));
855                 ServerInstance->BuildISupport();
856
857                 Config = old;
858         }
859         else
860         {
861                 // whoops, abort!
862                 ServerInstance->Logs->CloseLogs();
863                 ServerInstance->Config = old;
864                 ServerInstance->Logs->OpenFileLogs();
865         }
866 }