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