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