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