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