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