void Option::LoadRootHdf(const Hdf &roots, map<string, string> &map) { if (roots.exists()) { for (Hdf hdf = roots.firstChild(); hdf.exists(); hdf = hdf.next()) { map[hdf["root"].get()] = hdf["path"].get(); } } }
void Option::LoadRootHdf(const IniSetting::Map& ini, const Hdf &roots, vector<string> &vec) { if (roots.exists()) { for (Hdf hdf = roots.firstChild(); hdf.exists(); hdf = hdf.next()) { vec.push_back(Config::GetString(ini, hdf,"")); } } }
void Option::LoadRootHdf(const Hdf &roots, vector<string> &vec) { if (roots.exists()) { for (Hdf hdf = roots.firstChild(); hdf.exists(); hdf = hdf.next()) { vec.push_back(hdf.getString("")); } } }
// No `ini` binding yet. Hdf still takes precedence but will be removed // once we have made all options ini-aware. All new settings should // use the ini path of this method (i.e., pass a bogus Hdf or keep it null) void Config::Iterate(std::function<void (const IniSettingMap&, const Hdf&, const std::string&)> cb, const IniSettingMap &ini, const Hdf& config, const std::string &name, const bool prepend_hhvm /* = true */) { // We shouldn't be passing a leaf here. That's why name is not // optional. assert(!name.empty()); Hdf hdf = config[name]; if (hdf.exists() && !hdf.isEmpty()) { for (Hdf c = hdf.firstChild(); c.exists(); c = c.next()) { cb(IniSetting::Map::object, c, ""); } } else { Hdf empty; auto ini_name = IniName(name, prepend_hhvm); auto* ini_value = ini_iterate(ini, ini_name); if (ini_value && ini_value->isObject()) { for (auto& pair : ini_value->items()) { cb(pair.second, empty, pair.first.data()); } } } }
void Option::LoadRootHdf(const IniSetting::Map& ini, const Hdf &roots, map<string, string> &map) { if (roots.exists()) { for (Hdf hdf = roots.firstChild(); hdf.exists(); hdf = hdf.next()) { map[Config::Get(ini, hdf["root"])] = Config::Get(ini, hdf["path"]); } } }
void Option::LoadRootHdf(const IniSetting::Map& ini, const Hdf &roots, const std::string& name, std::map<std::string, std::string> &map) { if (roots.exists()) { for (Hdf hdf = roots[name].firstChild(); hdf.exists(); hdf = hdf.next()) { map[Config::Get(ini, hdf, "root", "", false)] = Config::Get(ini, hdf, "path", "", false); } } }
void Hdf::configGet(std::map<std::string, std::string, stdltistr> &values) const { values.clear(); for (Hdf hdf = firstChild(); hdf.exists(); hdf = hdf.next()) { values[hdf.getName()] = hdf.configGetString(""); } }
bool Hdf::lintImpl(std::vector<std::string> &names, const std::vector<std::string> &excludes, bool visited) { unsigned int size = names.size(); bool childVisited = false; for (Hdf hdf = firstChild(false); hdf.exists(); hdf = hdf.next(false)) { if (hdf.lintImpl(names, excludes, visited)) { childVisited = true; } } bool meVisited = childVisited || hdf_is_visited(getRaw()); std::string fullname = getFullPath(); if (!fullname.empty()) { if (meVisited == visited) { bool excluded = false; for (unsigned int i = 0; i < excludes.size(); i++) { if (match(fullname, excludes[i])) { excluded = true; break; } } if (!excluded) { if (!visited) { names.resize(size); // so reports about my children are gone } names.push_back(fullname); } } } return meVisited; }
// Hdf takes precedence, as usual. No `ini` binding yet. void Config::Iterate(const IniSettingMap &ini, const Hdf &hdf, std::function<void (const IniSettingMap&, const Hdf&)> cb) { if (hdf.exists()) { for (Hdf c = hdf.firstChild(); c.exists(); c = c.next()) { cb(ini, c); } } else { auto ini_name = IniName(hdf); auto* ini_value = ini.get_ptr(ini_name); if (ini_value && ini_value->isObject()) { for (auto& val : ini_value->values()) { cb(val, hdf); } } } }
void ReplayTransport::replayInputImpl() { String postData = StringUtil::UUDecode(m_hdf["post"].get("")); m_postData = string(postData.data(), postData.size()); m_requestHeaders.clear(); for (Hdf hdf = m_hdf["headers"].firstChild(); hdf.exists(); hdf = hdf.next()) { m_requestHeaders[hdf["name"].get("")].push_back(hdf["value"].get("")); } }
void IpBlockMap::LoadIpList(hphp_string_map<bool> &ips, Hdf hdf, bool allow) { for (Hdf child = hdf.firstChild(); child.exists(); child = child.next()) { string ip = child.getString(); size_t pos = ip.find('/'); if (pos != string::npos) { ip = ip.substr(0, pos); } ips[ip] = allow; } }
// No `ini` binding yet. Hdf still takes precedence but will be removed // once we have made all options ini-aware. All new settings should // use the ini path of this method (i.e., pass a bogus Hdf or keep it null) void Config::Iterate(std::function<void (const IniSettingMap&, const Hdf&, const std::string&)> cb, const IniSettingMap &ini, const Hdf& config, const std::string &name, const bool prepend_hhvm /* = true */) { Hdf hdf = name.empty() ? config : config[name]; if (hdf.exists() && !hdf.isEmpty()) { for (Hdf c = hdf.firstChild(); c.exists(); c = c.next()) { cb(IniSetting::Map::object, c, ""); } } else { Hdf empty; auto ini_value = name.empty() ? ini : ini_iterate(ini, IniName(name, prepend_hhvm)); if (ini_value.isArray()) { for (ArrayIter iter(ini_value.toArray()); iter; ++iter) { cb(iter.second(), empty, iter.first().toString().toCppString()); } } } }
FilesMatch::FilesMatch(const IniSetting::Map& ini, const Hdf& vh) { if (vh.exists()) { m_pattern = format_pattern(vh["pattern"].configGetString(), true); vh["headers"].configGet(m_headers); } else { m_pattern = format_pattern( ini[String("pattern")].toString().toCppString(), true ); for (ArrayIter iter(ini[String("headers")].toArray()); iter; ++iter) { m_headers.push_back(iter.second().toString().toCppString()); } } }
void Hdf::lint(std::vector<std::string> &names, const char *excludePatternNode /* = "LintExcludePatterns" */, bool visited /* = false */) { std::vector<std::string> patterns; if (excludePatternNode && *excludePatternNode) { for (Hdf hdf = operator[](excludePatternNode).firstChild(); hdf.exists(); hdf = hdf.next()) { std::string value = hdf.configGetString(); if (!value.empty()) { patterns.push_back(value); } } } lintImpl(names, patterns, visited); }
void Extension::LoadModules(Hdf hdf) { // Load up any dynamic extensions std::string path = hdf["DynamicExtensionPath"].getString("."); for (Hdf ext = hdf["DynamicExtensions"].firstChild(); ext.exists(); ext = ext.next()) { std::string extLoc = ext.getString(); if (extLoc.empty()) { continue; } if (extLoc[0] != '/') { extLoc = path + "/" + extLoc; } // Extensions are self-registering, // so we bring in the SO then // throw away its handle. void *ptr = dlopen(extLoc.c_str()); if (!ptr) { throw Exception("Could not open extension %s: %s", extLoc.c_str(), dlerror()); } auto getModule = (Extension *(*)())dlsym(ptr, "getModule"); if (!getModule) { throw Exception("Could not load extension %s: %s (%s)", extLoc.c_str(), "getModule() symbol not defined.", dlerror()); } Extension *mod = getModule(); if (mod->m_hhvmAPIVersion != HHVM_API_VERSION) { throw Exception("Could not use extension %s: " "Compiled with HHVM API Version %" PRId64 ", " "this version of HHVM expects %ld", extLoc.c_str(), mod->m_hhvmAPIVersion, HHVM_API_VERSION); } mod->setDSOName(extLoc); } // Invoke Extension::moduleLoad() callbacks assert(s_registered_extensions); for (ExtensionMap::const_iterator iter = s_registered_extensions->begin(); iter != s_registered_extensions->end(); ++iter) { iter->second->moduleLoad(hdf); } }
IpBlockMap::IpBlockMap(Hdf config) { for (Hdf hdf = config.firstChild(); hdf.exists(); hdf = hdf.next()) { AclPtr acl(new Acl()); bool allow = hdf["AllowFirst"].getBool(false); if (allow) { LoadIpList(acl->ips, hdf["Ip.Deny"], false); LoadIpList(acl->ips, hdf["Ip.Allow"], true); } else { LoadIpList(acl->ips, hdf["Ip.Allow"], true); LoadIpList(acl->ips, hdf["Ip.Deny"], false); } string location = hdf["Location"].getString(); if (!location.empty() && location[0] == '/') { location = location.substr(1); } m_acls[location] = acl; } }
void IpBlockMap::LoadIpList(AclPtr acl, Hdf hdf, bool allow) { for (Hdf child = hdf.firstChild(); child.exists(); child = child.next()) { string ip = child.getString(); unsigned int start, end; if (ReadIPv4Address(ip.c_str(), start, end)) { ASSERT(end >= start); if (end - start < 1024) { for (unsigned int i = start; i <= end; i++) { acl->ips[i] = allow; } } else { acl->ranges.resize(acl->ranges.size() + 1); IpRange &range = acl->ranges.back(); range.start = start; range.end = end; range.allow = allow; } } } }
Variant ArrayUtil::FromHdf(const Hdf &hdf) { if (hdf.firstChild().exists()) { Array ret = Array::Create(); const char *value = hdf.get(); if (value) { ret.set(s_default, String(value, CopyString)); } for (Hdf child = hdf.firstChild(); child.exists(); child = child.next()) { ret.set(String(child.getName()), FromHdf(child)); } return ret; } const char *value = hdf.get(""); if (strcasecmp(value, "false") == 0 || strcasecmp(value, "no") == 0 || strcasecmp(value, "off") == 0) { return false; } if (strcasecmp(value, "true") == 0 || strcasecmp(value, "yes") == 0 || strcasecmp(value, "on") == 0) { return true; } int64_t lval; double dval; int len = strlen(value); DataType ret = is_numeric_string(value, len, &lval, &dval, 0); switch (ret) { case KindOfInt64: return lval; case KindOfDouble: return dval; default: break; } return String(value, len, CopyString); }
void Hdf::setVisited(bool visited /* = true */) { hdf_set_visited(getRaw(), visited ? 1 : 0); for (Hdf hdf = firstChild(false); hdf.exists(); hdf = hdf.next(false)) { hdf.setVisited(visited); } }
void Option::Load(Hdf &config) { LoadRootHdf(config["IncludeRoots"], IncludeRoots); LoadRootHdf(config["AutoloadRoots"], AutoloadRoots); config["PackageFiles"].get(PackageFiles); config["IncludeSearchPaths"].get(IncludeSearchPaths); config["PackageDirectories"].get(PackageDirectories); config["PackageExcludeDirs"].get(PackageExcludeDirs); config["PackageExcludeFiles"].get(PackageExcludeFiles); config["PackageExcludePatterns"].get(PackageExcludePatterns); config["PackageExcludeStaticDirs"].get(PackageExcludeStaticDirs); config["PackageExcludeStaticFiles"].get(PackageExcludeStaticFiles); config["PackageExcludeStaticPatterns"].get(PackageExcludeStaticPatterns); CachePHPFile = config["CachePHPFile"].getBool(); config["ParseOnDemandDirs"].get(ParseOnDemandDirs); { Hdf cg = config["CodeGeneration"]; string tmp; #define READ_CG_OPTION(name) \ tmp = cg[#name].getString(); \ if (!tmp.empty()) { \ name = OptionStrings.add(tmp.c_str()); \ } READ_CG_OPTION(IdPrefix); READ_CG_OPTION(LabelEscape); READ_CG_OPTION(LambdaPrefix); } int count = 0; for (Hdf hdf = config["SepExtensions"].firstChild(); hdf.exists(); hdf = hdf.next()) { ++count; } SepExtensions.resize(count); count = 0; for (Hdf hdf = config["SepExtensions"].firstChild(); hdf.exists(); hdf = hdf.next()) { SepExtensionOptions &options = SepExtensions[count++]; options.name = hdf.getName(); options.soname = hdf["soname"].getString(); options.include_path = hdf["include"].getString(); options.lib_path = hdf["libpath"].getString(); options.shared = hdf["shared"].getBool(); } config["DynamicFunctionPrefix"].get(DynamicFunctionPrefixes); config["DynamicFunctionPostfix"].get(DynamicFunctionPostfixes); config["DynamicMethodPrefix"].get(DynamicMethodPrefixes); config["DynamicInvokeFunctions"].get(DynamicInvokeFunctions); config["VolatileClasses"].get(VolatileClasses); // build map from function names to sections for (Hdf hdf = config["FunctionSections"].firstChild(); hdf.exists(); hdf = hdf.next()) { for (Hdf hdfFunc = hdf.firstChild(); hdfFunc.exists(); hdfFunc = hdfFunc.next()) { FunctionSections[hdfFunc.getString()] = hdf.getName(); } } { Hdf repo = config["Repo"]; { Hdf repoCentral = repo["Central"]; RepoCentralPath = repoCentral["Path"].getString(); } RepoDebugInfo = repo["DebugInfo"].getBool(false); } { Hdf autoloadMap = config["AutoloadMap"]; autoloadMap["class"].get(AutoloadClassMap); autoloadMap["function"].get(AutoloadFuncMap); autoloadMap["constant"].get(AutoloadConstMap); AutoloadRoot = autoloadMap["root"].getString(); } HardTypeHints = config["HardTypeHints"].getBool(true); EnableHipHopSyntax = config["EnableHipHopSyntax"].getBool(); JitEnableRenameFunction = config["JitEnableRenameFunction"].getBool(); EnableHipHopExperimentalSyntax = config["EnableHipHopExperimentalSyntax"].getBool(); EnableShortTags = config["EnableShortTags"].getBool(true); EnableAspTags = config["EnableAspTags"].getBool(); EnableXHP = config["EnableXHP"].getBool(true); ParserThreadCount = config["ParserThreadCount"].getInt32(0); if (ParserThreadCount <= 0) { ParserThreadCount = Process::GetCPUCount(); } EnableFinallyStatement = config["EnableFinallyStatement"].getBool(); EnableEval = (EvalLevel)config["EnableEval"].getByte(0); AllDynamic = config["AllDynamic"].getBool(true); AllVolatile = config["AllVolatile"].getBool(); GenerateCppLibCode = config["GenerateCppLibCode"].getBool(false); GenerateSourceInfo = config["GenerateSourceInfo"].getBool(false); GenerateDocComments = config["GenerateDocComments"].getBool(true); UseVirtualDispatch = config["UseVirtualDispatch"].getBool(false); EliminateDeadCode = config["EliminateDeadCode"].getBool(true); CopyProp = config["CopyProp"].getBool(false); LocalCopyProp = config["LocalCopyProp"].getBool(true); StringLoopOpts = config["StringLoopOpts"].getBool(true); AutoInline = config["AutoInline"].getInt32(0); ControlFlow = config["ControlFlow"].getBool(true); VariableCoalescing = config["VariableCoalescing"].getBool(false); ArrayAccessIdempotent = config["ArrayAccessIdempotent"].getBool(false); DumpAst = config["DumpAst"].getBool(false); WholeProgram = config["WholeProgram"].getBool(true); if (m_hookHandler) m_hookHandler(config); OnLoad(); }
void VirtualHost::init(Hdf vh) { m_name = vh.getName(); const char *prefix = vh["Prefix"].get(""); const char *pattern = vh["Pattern"].get(""); const char *pathTranslation = vh["PathTranslation"].get(""); Hdf overwrite = vh["overwrite"]; initRuntimeOption(overwrite); if (prefix) m_prefix = prefix; if (pattern) { m_pattern = Util::format_pattern(pattern, true); if (!m_pattern.empty()) { m_pattern += "i"; // case-insensitive } } if (pathTranslation) { m_pathTranslation = pathTranslation; if (!m_pathTranslation.empty() && m_pathTranslation[m_pathTranslation.length() - 1] != '/') { m_pathTranslation += '/'; } } m_disabled = vh["Disabled"].getBool(false); m_documentRoot = RuntimeOption::SourceRoot + m_pathTranslation; if (!m_documentRoot.empty() && m_documentRoot[m_documentRoot.length() - 1] == '/') { m_documentRoot = m_documentRoot.substr(0, m_documentRoot.length() - 1); } Hdf rewriteRules = vh["RewriteRules"]; for (Hdf hdf = rewriteRules.firstChild(); hdf.exists(); hdf = hdf.next()) { RewriteRule dummy; m_rewriteRules.push_back(dummy); RewriteRule &rule = m_rewriteRules.back(); rule.pattern = Util::format_pattern(hdf["pattern"].getString(""), true); rule.to = hdf["to"].getString(""); rule.qsa = hdf["qsa"].getBool(false); rule.redirect = hdf["redirect"].getInt16(0); if (rule.pattern.empty() || rule.to.empty()) { throw InvalidArgumentException("rewrite rule", "(empty pattern or to)"); } Hdf rewriteConds = hdf["conditions"]; for (Hdf chdf = rewriteConds.firstChild(); chdf.exists(); chdf = chdf.next()) { RewriteCond dummy; rule.rewriteConds.push_back(dummy); RewriteCond &cond = rule.rewriteConds.back(); cond.pattern = Util::format_pattern(chdf["pattern"].getString(""), true); if (cond.pattern.empty()) { throw InvalidArgumentException("rewrite rule", "(empty cond pattern)"); } const char *type = chdf["type"].get(); if (type) { if (strcasecmp(type, "host") == 0) { cond.type = RewriteCond::Host; } else if (strcasecmp(type, "request") == 0) { cond.type = RewriteCond::Request; } else { throw InvalidArgumentException("rewrite rule", "(invalid cond type)"); } } else { cond.type = RewriteCond::Request; } cond.negate = chdf["negate"].getBool(false); } } if (vh["IpBlockMap"].firstChild().exists()) { Hdf ipblocks = vh["IpBlockMap"]; m_ipBlocks = IpBlockMapPtr(new IpBlockMap(ipblocks)); } Hdf logFilters = vh["LogFilters"]; for (Hdf hdf = logFilters.firstChild(); hdf.exists(); hdf = hdf.next()) { QueryStringFilter filter; filter.urlPattern = Util::format_pattern(hdf["url"].getString(""), true); filter.replaceWith = hdf["value"].getString(""); filter.replaceWith = "\\1=" + filter.replaceWith; string pattern = hdf["pattern"].getString(""); vector<string> names; hdf["params"].get(names); if (pattern.empty()) { for (unsigned int i = 0; i < names.size(); i++) { if (pattern.empty()) { pattern = "(?<=[&\?])("; } else { pattern += "|"; } pattern += names[i]; } if (!pattern.empty()) { pattern += ")=.*?(?=(&|$))"; pattern = Util::format_pattern(pattern, false); } } else if (!names.empty()) { throw InvalidArgumentException ("log filter", "(cannot specify both params and pattern)"); } filter.namePattern = pattern; m_queryStringFilters.push_back(filter); } vh["ServerVariables"].get(m_serverVars); m_serverName = vh["ServerName"].getString(); }
void Option::Load(Hdf &config) { LoadRootHdf(config["IncludeRoots"], IncludeRoots); LoadRootHdf(config["AutoloadRoots"], AutoloadRoots); config["IncludeSearchPaths"].get(IncludeSearchPaths); config["PackageDirectories"].get(PackageDirectories); config["PackageExcludeDirs"].get(PackageExcludeDirs); config["PackageExcludeFiles"].get(PackageExcludeFiles); config["PackageExcludeStaticFiles"].get(PackageExcludeStaticFiles); CachePHPFile = config["CachePHPFile"].getBool(); { Hdf cg = config["CodeGeneration"]; string tmp; #define READ_CG_OPTION(name) \ tmp = cg[#name].getString(); \ if (!tmp.empty()) { \ name = OptionStrings.add(tmp.c_str()); \ } READ_CG_OPTION(IdPrefix); READ_CG_OPTION(LambdaPrefix); READ_CG_OPTION(FunctionPrefix); READ_CG_OPTION(BuiltinFunctionPrefix); READ_CG_OPTION(InvokePrefix); READ_CG_OPTION(CreateObjectPrefix); READ_CG_OPTION(PseudoMainPrefix); READ_CG_OPTION(VariablePrefix); READ_CG_OPTION(GlobalVariablePrefix); READ_CG_OPTION(StaticVariablePrefix); READ_CG_OPTION(ScalarArrayName); READ_CG_OPTION(SystemScalarArrayName); READ_CG_OPTION(ClassPrefix); READ_CG_OPTION(ClassStaticsPrefix); READ_CG_OPTION(ClassStaticsObjectPrefix); READ_CG_OPTION(ClassStaticsIdGetterPrefix); READ_CG_OPTION(ClassStaticInitializerPrefix); READ_CG_OPTION(ClassStaticInitializerFlagPrefix); READ_CG_OPTION(ClassWrapperFunctionPrefix); READ_CG_OPTION(ObjectPrefix); READ_CG_OPTION(ObjectStaticPrefix); READ_CG_OPTION(SmartPtrPrefix); READ_CG_OPTION(MethodPrefix); READ_CG_OPTION(MethodImplPrefix); READ_CG_OPTION(PropertyPrefix); READ_CG_OPTION(StaticPropertyPrefix); READ_CG_OPTION(ConstantPrefix); READ_CG_OPTION(ClassConstantPrefix); READ_CG_OPTION(ExceptionPrefix); READ_CG_OPTION(TempVariablePrefix); READ_CG_OPTION(EvalOrderTempPrefix); READ_CG_OPTION(SilencerPrefix); READ_CG_OPTION(EvalInvokePrefix); READ_CG_OPTION(TempPrefix); READ_CG_OPTION(MapPrefix); READ_CG_OPTION(IterPrefix); READ_CG_OPTION(InitPrefix); READ_CG_OPTION(FFIFnPrefix); READ_CG_OPTION(SystemFilePrefix); READ_CG_OPTION(UserFilePrefix); READ_CG_OPTION(ClassHeaderPrefix); READ_CG_OPTION(ClusterPrefix); READ_CG_OPTION(FFIFilePrefix); } int count = 0; for (Hdf hdf = config["SepExtensions"].firstChild(); hdf.exists(); hdf = hdf.next()) { ++count; } SepExtensions.resize(count); count = 0; for (Hdf hdf = config["SepExtensions"].firstChild(); hdf.exists(); hdf = hdf.next()) { SepExtensionOptions &options = SepExtensions[count++]; options.name = hdf.getName(); options.soname = hdf["soname"].getString(); options.include_path = hdf["include"].getString(); options.lib_path = hdf["libpath"].getString(); options.shared = hdf["shared"].getBool(); } config["DynamicFunctionPrefix"].get(DynamicFunctionPrefixes); config["DynamicFunctionPostfix"].get(DynamicFunctionPostfixes); config["DynamicMethodPrefix"].get(DynamicMethodPrefixes); config["DynamicInvokeFunctions"].get(DynamicInvokeFunctions); config["VolatileClasses"].get(VolatileClasses); ScalarArrayFileCount = config["ScalarArrayFileCount"].getByte(1); if (ScalarArrayFileCount <= 0) ScalarArrayFileCount = 1; LiteralStringFileCount = config["LiteralStringFileCount"].getInt32(1); if (LiteralStringFileCount <= 0) LiteralStringFileCount = 1; ScalarArrayOverflowLimit = config["ScalarArrayOverflowLimit"].getInt32(2000); if (ScalarArrayOverflowLimit <= 0) ScalarArrayOverflowLimit = 2000; FlibDirectory = config["FlibDirectory"].getString(); EnableXHP = config["EnableXHP"].getBool(); RTTIOutputFile = config["RTTIOutputFile"].getString(); EnableEval = (EvalLevel)config["EnableEval"].getByte(0); AllDynamic = config["AllDynamic"].getBool(); AllVolatile = config["AllVolatile"].getBool(); OnLoad(); }
void Hdf::configGet(std::set<std::string, stdltistr> &values) const { values.clear(); for (Hdf hdf = firstChild(); hdf.exists(); hdf = hdf.next()) { values.insert(hdf.configGetString("")); } }
void Hdf::configGet(std::vector<std::string> &values) const { values.clear(); for (Hdf hdf = firstChild(); hdf.exists(); hdf = hdf.next()) { values.push_back(hdf.configGetString("")); } }
void Hdf::configGet(boost::container::flat_set<std::string> &values) const { values.clear(); for (Hdf hdf = firstChild(); hdf.exists(); hdf = hdf.next()) { values.insert(hdf.configGetString("")); } }
void RuntimeOption::Load(Hdf &config, StringVec *overwrites /* = NULL */) { // Machine metrics string hostname, tier, cpu; { Hdf machine = config["Machine"]; hostname = machine["name"].getString(); if (hostname.empty()) { hostname = Process::GetHostName(); } tier = machine["tier"].getString(); cpu = machine["cpu"].getString(); if (cpu.empty()) { cpu = Process::GetCPUModel(); } } // Tier overwrites { Hdf tiers = config["Tiers"]; for (Hdf hdf = tiers.firstChild(); hdf.exists(); hdf = hdf.next()) { if (matchHdfPattern(hostname, hdf["machine"]) && matchHdfPattern(tier, hdf["tier"]) && matchHdfPattern(cpu, hdf["cpu"])) { Tier = hdf.getName(); config.copy(hdf["overwrite"]); // no break here, so we can continue to match more overwrites } hdf["overwrite"].setVisited(); // avoid lint complaining } } // More overwrites if (overwrites) { for (unsigned int i = 0; i < overwrites->size(); i++) { config.fromString(overwrites->at(i).c_str()); } } PidFile = config["PidFile"].getString("www.pid"); { Hdf logger = config["Log"]; if (logger["Level"] == "None") { Logger::LogLevel = Logger::LogNone; } else if (logger["Level"] == "Error") { Logger::LogLevel = Logger::LogError; } else if (logger["Level"] == "Warning") { Logger::LogLevel = Logger::LogWarning; } else if (logger["Level"] == "Info") { Logger::LogLevel = Logger::LogInfo; } else if (logger["Level"] == "Verbose") { Logger::LogLevel = Logger::LogVerbose; } Logger::LogHeader = logger["Header"].getBool(); bool logInjectedStackTrace = logger["InjectedStackTrace"].getBool(); if (logInjectedStackTrace) { Logger::SetTheLogger(new ExtendedLogger()); ExtendedLogger::EnabledByDefault = true; } Logger::LogNativeStackTrace = logger["NativeStackTrace"].getBool(true); Logger::MaxMessagesPerRequest = logger["MaxMessagesPerRequest"].getInt32(-1); Logger::UseLogFile = logger["UseLogFile"].getBool(true); Logger::UseCronolog = logger["UseCronolog"].getBool(false); if (Logger::UseLogFile) { LogFile = logger["File"].getString(); LogFileSymLink = logger["SymLink"].getString(); } Logger::DropCacheChunkSize = logger["DropCacheChunkSize"].getInt32(1 << 20); AlwaysEscapeLog = logger["AlwaysEscapeLog"].getBool(false); Hdf aggregator = logger["Aggregator"]; Logger::UseLogAggregator = aggregator.getBool(); LogAggregatorFile = aggregator["File"].getString(); LogAggregatorDatabase = aggregator["Database"].getString(); LogAggregatorSleepSeconds = aggregator["SleepSeconds"].getInt16(10); AlwaysLogUnhandledExceptions = logger["AlwaysLogUnhandledExceptions"].getBool(true); NoSilencer = logger["NoSilencer"].getBool(); EnableApplicationLog = logger["ApplicationLog"].getBool(true); RuntimeErrorReportingLevel = logger["RuntimeErrorReportingLevel"].getInt32(ErrorConstants::HPHP_ALL); AccessLogDefaultFormat = logger["AccessLogDefaultFormat"]. getString("%h %l %u %t \"%r\" %>s %b"); { Hdf access = logger["Access"]; for (Hdf hdf = access.firstChild(); hdf.exists(); hdf = hdf.next()) { string fname = hdf["File"].getString(); if (fname.empty()) { continue; } string symLink = hdf["SymLink"].getString(); AccessLogs. push_back(AccessLogFileData(fname, symLink, hdf["Format"]. getString(AccessLogDefaultFormat))); } } AdminLogFormat = logger["AdminLog.Format"].getString("%h %t %s %U"); AdminLogFile = logger["AdminLog.File"].getString(); AdminLogSymLink = logger["AdminLog.SymLink"].getString(); } { Hdf error = config["ErrorHandling"]; /* Remove this, once its removed from production configs */ (void)error["NoInfiniteLoopDetection"].getBool(); MaxSerializedStringSize = error["MaxSerializedStringSize"].getInt32(64 * 1024 * 1024); CallUserHandlerOnFatals = error["CallUserHandlerOnFatals"].getBool(true); MaxLoopCount = error["MaxLoopCount"].getInt32(0); NoInfiniteRecursionDetection = error["NoInfiniteRecursionDetection"].getBool(); ThrowBadTypeExceptions = error["ThrowBadTypeExceptions"].getBool(); ThrowTooManyArguments = error["ThrowTooManyArguments"].getBool(); WarnTooManyArguments = error["WarnTooManyArguments"].getBool(); ThrowMissingArguments = error["ThrowMissingArguments"].getBool(); ThrowInvalidArguments = error["ThrowInvalidArguments"].getBool(); EnableHipHopErrors = error["EnableHipHopErrors"].getBool(true); AssertActive = error["AssertActive"].getBool(); AssertWarning = error["AssertWarning"].getBool(); NoticeFrequency = error["NoticeFrequency"].getInt32(1); WarningFrequency = error["WarningFrequency"].getInt32(1); } { Hdf rlimit = config["ResourceLimit"]; setResourceLimit(RLIMIT_CORE, rlimit, "CoreFileSize"); setResourceLimit(RLIMIT_NOFILE, rlimit, "MaxSocket"); setResourceLimit(RLIMIT_DATA, rlimit, "RSS"); MaxRSS = rlimit["MaxRSS"].getInt64(0); SocketDefaultTimeout = rlimit["SocketDefaultTimeout"].getInt16(5); MaxRSSPollingCycle = rlimit["MaxRSSPollingCycle"].getInt64(0); DropCacheCycle = rlimit["DropCacheCycle"].getInt64(0); MaxSQLRowCount = rlimit["MaxSQLRowCount"].getInt64(0); MaxMemcacheKeyCount = rlimit["MaxMemcacheKeyCount"].getInt64(0); SerializationSizeLimit = rlimit["SerializationSizeLimit"].getInt64(0); StringOffsetLimit = rlimit["StringOffsetLimit"].getInt64(10 * 1024 * 1024); } { Hdf server = config["Server"]; Host = server["Host"].getString(); DefaultServerNameSuffix = server["DefaultServerNameSuffix"].getString(); ServerIP = server["IP"].getString("0.0.0.0"); ServerPrimaryIP = Util::GetPrimaryIP(); ServerPort = server["Port"].getInt16(80); ServerBacklog = server["Backlog"].getInt16(128); ServerConnectionLimit = server["ConnectionLimit"].getInt16(0); ServerThreadCount = server["ThreadCount"].getInt32(50); ServerThreadRoundRobin = server["ThreadRoundRobin"].getBool(); ServerThreadDropCacheTimeoutSeconds = server["ThreadDropCacheTimeoutSeconds"].getInt32(0); ServerThreadJobLIFO = server["ThreadJobLIFO"].getBool(); RequestTimeoutSeconds = server["RequestTimeoutSeconds"].getInt32(0); RequestMemoryMaxBytes = server["RequestMemoryMaxBytes"].getInt64(-1); ResponseQueueCount = server["ResponseQueueCount"].getInt32(0); if (ResponseQueueCount <= 0) { ResponseQueueCount = ServerThreadCount / 10; if (ResponseQueueCount <= 0) ResponseQueueCount = 1; } ServerGracefulShutdownWait = server["GracefulShutdownWait"].getInt16(0); ServerHarshShutdown = server["HarshShutdown"].getBool(true); ServerEvilShutdown = server["EvilShutdown"].getBool(true); ServerDanglingWait = server["DanglingWait"].getInt16(0); if (ServerGracefulShutdownWait < ServerDanglingWait) { ServerGracefulShutdownWait = ServerDanglingWait; } GzipCompressionLevel = server["GzipCompressionLevel"].getInt16(3); ForceCompressionURL = server["ForceCompression"]["URL"].getString(); ForceCompressionCookie = server["ForceCompression"]["Cookie"].getString(); ForceCompressionParam = server["ForceCompression"]["Param"].getString(); EnableMagicQuotesGpc = server["EnableMagicQuotesGpc"].getBool(); EnableKeepAlive = server["EnableKeepAlive"].getBool(true); ExposeHPHP = server["ExposeHPHP"].getBool(true); ExposeXFBServer = server["ExposeXFBServer"].getBool(); ConnectionTimeoutSeconds = server["ConnectionTimeoutSeconds"].getInt16(-1); EnableOutputBuffering = server["EnableOutputBuffering"].getBool(); OutputHandler = server["OutputHandler"].getString(); ImplicitFlush = server["ImplicitFlush"].getBool(); EnableEarlyFlush = server["EnableEarlyFlush"].getBool(true); ForceChunkedEncoding = server["ForceChunkedEncoding"].getBool(); MaxPostSize = (server["MaxPostSize"].getInt32(100)) * (1LL << 20); AlwaysPopulateRawPostData = server["AlwaysPopulateRawPostData"].getBool(); LibEventSyncSend = server["LibEventSyncSend"].getBool(true); TakeoverFilename = server["TakeoverFilename"].getString(); ExpiresActive = server["ExpiresActive"].getBool(true); ExpiresDefault = server["ExpiresDefault"].getInt32(2592000); if (ExpiresDefault < 0) ExpiresDefault = 2592000; DefaultCharsetName = server["DefaultCharsetName"].getString("utf-8"); RequestBodyReadLimit = server["RequestBodyReadLimit"].getInt32(-1); EnableSSL = server["EnableSSL"].getBool(); SSLPort = server["SSLPort"].getInt16(443); SSLCertificateFile = server["SSLCertificateFile"].getString(); SSLCertificateKeyFile = server["SSLCertificateKeyFile"].getString(); SourceRoot = Util::normalizeDir(server["SourceRoot"].getString()); if (!SourceRoot.empty()) { // Guaranteed empty on empty load so avoid setting FileCache::SourceRoot // since it may not be initialized FileCache::SourceRoot = SourceRoot; } server["IncludeSearchPaths"].get(IncludeSearchPaths); for (unsigned int i = 0; i < IncludeSearchPaths.size(); i++) { IncludeSearchPaths[i] = Util::normalizeDir(IncludeSearchPaths[i]); } IncludeSearchPaths.insert(IncludeSearchPaths.begin(), "./"); FileCache = server["FileCache"].getString(); DefaultDocument = server["DefaultDocument"].getString(); ErrorDocument404 = server["ErrorDocument404"].getString(); normalizePath(ErrorDocument404); ErrorDocument500 = server["ErrorDocument500"].getString(); normalizePath(ErrorDocument500); FatalErrorMessage = server["FatalErrorMessage"].getString(); FontPath = Util::normalizeDir(server["FontPath"].getString()); EnableStaticContentCache = server["EnableStaticContentCache"].getBool(true); EnableStaticContentFromDisk = server["EnableStaticContentFromDisk"].getBool(true); EnableOnDemandUncompress = server["EnableOnDemandUncompress"].getBool(true); EnableStaticContentMMap = server["EnableStaticContentMMap"].getBool(true); if (EnableStaticContentMMap) { EnableOnDemandUncompress = true; } RTTIDirectory = Util::normalizeDir(server["RTTIDirectory"].getString("/tmp/")); EnableCliRTTI = server["EnableCliRTTI"].getBool(); Utf8izeReplace = server["Utf8izeReplace"].getBool(true); StartupDocument = server["StartupDocument"].getString(); normalizePath(StartupDocument); WarmupDocument = server["WarmupDocument"].getString(); RequestInitFunction = server["RequestInitFunction"].getString(); RequestInitDocument = server["RequestInitDocument"].getString(); server["ThreadDocuments"].get(ThreadDocuments); for (unsigned int i = 0; i < ThreadDocuments.size(); i++) { normalizePath(ThreadDocuments[i]); } server["ThreadLoopDocuments"].get(ThreadLoopDocuments); for (unsigned int i = 0; i < ThreadLoopDocuments.size(); i++) { normalizePath(ThreadLoopDocuments[i]); } SafeFileAccess = server["SafeFileAccess"].getBool(); server["AllowedDirectories"].get(AllowedDirectories); for (unsigned int i = 0; i < AllowedDirectories.size(); i++) { string &directory = AllowedDirectories[i]; char resolved_path[PATH_MAX]; if (realpath(directory.c_str(), resolved_path) && directory != resolved_path) { RuntimeOption::AllowedDirectories.push_back(resolved_path); } } server["AllowedFiles"].get(AllowedFiles); server["ForbiddenFileExtensions"].get(ForbiddenFileExtensions); EnableMemoryManager = server["EnableMemoryManager"].getBool(true); CheckMemory = server["CheckMemory"].getBool(); UseHphpArray = server["UseHphpArray"].getBool(false); UseSmallArray = server["UseSmallArray"].getBool(false); UseDirectCopy = server["UseDirectCopy"].getBool(false); AlwaysUseRelativePath = server["AlwaysUseRelativePath"].getBool(false); Hdf apc = server["APC"]; EnableApc = apc["EnableApc"].getBool(true); EnableConstLoad = apc["EnableConstLoad"].getBool(false); ForceConstLoadToAPC = apc["ForceConstLoadToAPC"].getBool(true); ApcPrimeLibrary = apc["PrimeLibrary"].getString(); ApcLoadThread = apc["LoadThread"].getInt16(2); apc["CompletionKeys"].get(ApcCompletionKeys); string apcTableType = apc["TableType"].getString("concurrent"); if (strcasecmp(apcTableType.c_str(), "hash") == 0) { ApcTableType = ApcHashTable; } else if (strcasecmp(apcTableType.c_str(), "concurrent") == 0) { ApcTableType = ApcConcurrentTable; } else { throw InvalidArgumentException("apc table type", "Invalid table type"); } string apcLockType = apc["LockType"].getString("readwritelock"); if (strcasecmp(apcLockType.c_str(), "readwritelock") == 0) { ApcTableLockType = ApcReadWriteLock; } else if (strcasecmp(apcLockType.c_str(), "mutex") == 0) { ApcTableLockType = ApcMutex; } else { throw InvalidArgumentException("apc lock type", "Invalid lock type"); } ApcExpireOnSets = apc["ExpireOnSets"].getBool(); ApcPurgeFrequency = apc["PurgeFrequency"].getInt32(4096); ApcAllowObj = apc["AllowObject"].getBool(); ApcKeyMaturityThreshold = apc["KeyMaturityThreshold"].getInt32(20); ApcMaximumCapacity = apc["MaximumCapacity"].getInt64(0); ApcKeyFrequencyUpdatePeriod = apc["KeyFrequencyUpdatePeriod"]. getInt32(1000); Hdf dns = server["DnsCache"]; EnableDnsCache = dns["Enable"].getBool(); DnsCacheTTL = dns["TTL"].getInt32(600); // 10 minutes DnsCacheKeyMaturityThreshold = dns["KeyMaturityThreshold"].getInt32(20); DnsCacheMaximumCapacity = dns["MaximumCapacity"].getInt64(0); DnsCacheKeyFrequencyUpdatePeriod = dns["KeyFrequencyUpdatePeriod"]. getInt32(1000); Hdf upload = server["Upload"]; UploadMaxFileSize = (upload["UploadMaxFileSize"].getInt32(100)) * (1LL << 20); UploadTmpDir = upload["UploadTmpDir"].getString("/tmp"); RuntimeOption::AllowedDirectories.push_back(UploadTmpDir); EnableFileUploads = upload["EnableFileUploads"].getBool(true); EnableUploadProgress = upload["EnableUploadProgress"].getBool(); Rfc1867Freq = upload["Rfc1867Freq"].getInt32(256 * 1024); if (Rfc1867Freq < 0) Rfc1867Freq = 256 * 1024; Rfc1867Prefix = upload["Rfc1867Prefix"].getString("vupload_"); Rfc1867Name = upload["Rfc1867Name"].getString("video_ptoken"); ImageMemoryMaxBytes = server["ImageMemoryMaxBytes"].getInt64(0); if (ImageMemoryMaxBytes == 0) { ImageMemoryMaxBytes = UploadMaxFileSize * 2; } SharedStores::Create(); LightProcessFilePrefix = server["LightProcessFilePrefix"].getString("./lightprocess"); LightProcessCount = server["LightProcessCount"].getInt32(0); InjectedStackTrace = server["InjectedStackTrace"].getBool(true); InjectedStackTraceLimit = server["InjectedStackTraceLimit"].getInt32(-1); ForceServerNameToHeader = server["ForceServerNameToHeader"].getBool(); ServerUser = server["User"].getString(""); } { Hdf hosts = config["VirtualHost"]; if (hosts.exists()) { for (Hdf hdf = hosts.firstChild(); hdf.exists(); hdf = hdf.next()) { if (hdf.getName() == "default") { VirtualHost::GetDefault().init(hdf); } else { VirtualHostPtr host(new VirtualHost(hdf)); VirtualHosts.push_back(host); } } for (unsigned int i = 0; i < VirtualHosts.size(); i++) { if (!VirtualHosts[i]->valid()) { throw InvalidArgumentException("virtual host", "missing prefix or pattern"); } } } } { Hdf ipblocks = config["IpBlockMap"]; IpBlocks = IpBlockMapPtr(new IpBlockMap(ipblocks)); } { Hdf satellites = config["Satellites"]; if (satellites.exists()) { for (Hdf hdf = satellites.firstChild(); hdf.exists(); hdf = hdf.next()) { SatelliteServerInfoPtr satellite(new SatelliteServerInfo(hdf)); SatelliteServerInfos.push_back(satellite); if (satellite->getType() == SatelliteServer::KindOfRPCServer) { XboxPassword = satellite->getPassword(); } } } } { Hdf xbox = config["Xbox"]; XboxServerThreadCount = xbox["ServerInfo.ThreadCount"].getInt32(0); XboxServerPort = xbox["ServerInfo.Port"].getInt32(0); XboxDefaultLocalTimeoutMilliSeconds = xbox["DefaultLocalTimeoutMilliSeconds"].getInt32(500); XboxDefaultRemoteTimeoutSeconds = xbox["DefaultRemoteTimeoutSeconds"].getInt32(5); XboxServerInfoMaxRequest = xbox["ServerInfo.MaxRequest"].getInt32(500); XboxServerInfoDuration = xbox["ServerInfo.MaxDuration"].getInt32(120); XboxServerInfoWarmupDoc = xbox["ServerInfo.WarmupDocument"].get(""); XboxServerInfoReqInitFunc = xbox["ServerInfo.RequestInitFunction"].get(""); XboxServerInfoReqInitDoc = xbox["ServerInfo.RequestInitDocument"].get(""); XboxProcessMessageFunc = xbox["ProcessMessageFunc"].get("xbox_process_message"); } { Hdf pagelet = config["PageletServer"]; PageletServerThreadCount = pagelet["ThreadCount"].getInt32(0); PageletServerThreadRoundRobin = pagelet["ThreadRoundRobin"].getBool(); PageletServerThreadDropCacheTimeoutSeconds = pagelet["ThreadDropCacheTimeoutSeconds"].getInt32(0); } { FiberCount = config["Fiber.ThreadCount"].getInt32(Process::GetCPUCount()); } { Hdf content = config["StaticFile"]; content["Extensions"].get(StaticFileExtensions); content["Generators"].get(StaticFileGenerators); Hdf matches = content["FilesMatch"]; if (matches.exists()) { for (Hdf hdf = matches.firstChild(); hdf.exists(); hdf = hdf.next()) { FilesMatches.push_back(FilesMatchPtr(new FilesMatch(hdf))); } } } { Hdf admin = config["AdminServer"]; AdminServerPort = admin["Port"].getInt16(8088); AdminThreadCount = admin["ThreadCount"].getInt32(1); AdminPassword = admin["Password"].getString(); } { Hdf proxy = config["Proxy"]; ProxyOrigin = proxy["Origin"].getString(); ProxyRetry = proxy["Retry"].getInt16(3); UseServeURLs = proxy["ServeURLs"].getBool(); proxy["ServeURLs"].get(ServeURLs); UseProxyURLs = proxy["ProxyURLs"].getBool(); ProxyPercentage = proxy["Percentage"].getByte(0); proxy["ProxyURLs"].get(ProxyURLs); proxy["ProxyPatterns"].get(ProxyPatterns); } { Hdf mysql = config["MySQL"]; MySQLReadOnly = mysql["ReadOnly"].getBool(); MySQLLocalize = mysql["Localize"].getBool(); MySQLConnectTimeout = mysql["ConnectTimeout"].getInt32(1000); MySQLReadTimeout = mysql["ReadTimeout"].getInt32(1000); MySQLWaitTimeout = mysql["WaitTimeout"].getInt32(-1); MySQLSlowQueryThreshold = mysql["SlowQueryThreshold"].getInt32(1000); MySQLKillOnTimeout = mysql["KillOnTimeout"].getBool(); } { Hdf http = config["Http"]; HttpDefaultTimeout = http["DefaultTimeout"].getInt32(30); HttpSlowQueryThreshold = http["SlowQueryThreshold"].getInt32(5000); } { Hdf debug = config["Debug"]; NativeStackTrace = debug["NativeStackTrace"].getBool(); StackTrace::Enabled = NativeStackTrace; TranslateLeakStackTrace = debug["TranslateLeakStackTrace"].getBool(); FullBacktrace = debug["FullBacktrace"].getBool(); ServerStackTrace = debug["ServerStackTrace"].getBool(); ServerErrorMessage = debug["ServerErrorMessage"].getBool(); TranslateSource = debug["TranslateSource"].getBool(); RecordInput = debug["RecordInput"].getBool(); ClearInputOnSuccess = debug["ClearInputOnSuccess"].getBool(true); ProfilerOutputDir = debug["ProfilerOutputDir"].getString("/tmp"); CoreDumpEmail = debug["CoreDumpEmail"].getString(); if (!CoreDumpEmail.empty()) { StackTrace::ReportEmail = CoreDumpEmail; } CoreDumpReport = debug["CoreDumpReport"].getBool(true); if (CoreDumpReport) { StackTrace::InstallReportOnErrors(); } std::string reportDirectory = debug["CoreDumpReportDirectory"].getString(); if (!reportDirectory.empty()) { StackTraceBase::ReportDirectory = reportDirectory; } LocalMemcache = debug["LocalMemcache"].getBool(); MemcacheReadOnly = debug["MemcacheReadOnly"].getBool(); { Hdf simpleCounter = debug["SimpleCounter"]; SimpleCounter::SampleStackCount = simpleCounter["SampleStackCount"].getInt32(0); SimpleCounter::SampleStackDepth = simpleCounter["SampleStackDepth"].getInt32(5); } } { Hdf stats = config["Stats"]; EnableStats = stats.getBool(); // main switch EnableWebStats = stats["Web"].getBool(); EnableMemoryStats = stats["Memory"].getBool(); EnableMallocStats = stats["Malloc"].getBool(); EnableAPCStats = stats["APC"].getBool(); EnableAPCKeyStats = stats["APCKey"].getBool(); EnableMemcacheStats = stats["Memcache"].getBool(); EnableMemcacheKeyStats = stats["MemcacheKey"].getBool(); EnableSQLStats = stats["SQL"].getBool(); EnableSQLTableStats = stats["SQLTable"].getBool(); EnableNetworkIOStatus = stats["NetworkIO"].getBool(); if (EnableStats && EnableMallocStats) { LeakDetectable::EnableMallocStats(true); } StatsXSL = stats["XSL"].getString(); StatsXSLProxy = stats["XSLProxy"].getString(); StatsSlotDuration = stats["SlotDuration"].getInt32(10 * 60); // 10 minutes StatsMaxSlot = stats["MaxSlot"].getInt32(12 * 6); // 12 hours { Hdf apcSize = stats["APCSize"]; EnableAPCSizeStats = apcSize["Enable"].getBool(); EnableAPCSizeGroup = apcSize["Group"].getBool(); apcSize["SpecialPrefix"].get(APCSizeSpecialPrefix); for (unsigned int i = 0; i < APCSizeSpecialPrefix.size(); i++) { string &prefix = APCSizeSpecialPrefix[i]; string prefixReplace = prefix + "{A}"; APCSizePrefixReplace.push_back(prefixReplace); } apcSize["SpecialMiddle"].get(APCSizeSpecialMiddle); for (unsigned int i = 0; i < APCSizeSpecialMiddle.size(); i++) { string &middle = APCSizeSpecialMiddle[i]; string middleReplace = "{A}" + middle + "{A}"; APCSizeMiddleReplace.push_back(middleReplace); } apcSize["SkipPrefix"].get(APCSizeSkipPrefix); EnableAPCSizeDetail = apcSize["Individual"].getBool(); EnableAPCFetchStats = apcSize["FetchStats"].getBool(); if (EnableAPCFetchStats) EnableAPCSizeDetail = true; if (EnableAPCSizeDetail) EnableAPCSizeGroup = true; APCSizeCountPrime = apcSize["CountPrime"].getBool(); } EnableHotProfiler = stats["EnableHotProfiler"].getBool(true); ProfilerTraceBuffer = stats["ProfilerTraceBuffer"].getInt32(2000000); ProfilerTraceExpansion = stats["ProfilerTraceExpansion"].getDouble(1.2); ProfilerMaxTraceBuffer = stats["ProfilerMaxTraceBuffer"].getInt32(0); } { config["ServerVariables"].get(ServerVariables); config["EnvVariables"].get(EnvVariables); } { Hdf eval = config["Eval"]; EnableHipHopSyntax = eval["EnableHipHopSyntax"].getBool(); EnableHipHopExperimentalSyntax = eval["EnableHipHopExperimentalSyntax"].getBool(); EnableShortTags= eval["EnableShortTags"].getBool(true); if (EnableShortTags) ScannerType |= Scanner::AllowShortTags; else ScannerType &= ~Scanner::AllowShortTags; EnableAspTags = eval["EnableAspTags"].getBool(); if (EnableAspTags) ScannerType |= Scanner::AllowAspTags; else ScannerType &= ~Scanner::AllowAspTags; EnableXHP = eval["EnableXHP"].getBool(true); EnableObjDestructCall = eval["EnableObjDestructCall"].getBool(false); CheckSymLink = eval["CheckSymLink"].getBool(false); NativeXHP = eval["NativeXHP"].getBool(true); if (EnableXHP && !NativeXHP) ScannerType |= Scanner::PreprocessXHP; else ScannerType &= ~Scanner::PreprocessXHP; EnableStrict = eval["EnableStrict"].getBool(); StrictLevel = eval["StrictLevel"].getInt32(1); // StrictBasic StrictFatal = eval["StrictFatal"].getBool(); RecordCodeCoverage = eval["RecordCodeCoverage"].getBool(); CodeCoverageOutputFile = eval["CodeCoverageOutputFile"].getString(); { Hdf debugger = eval["Debugger"]; EnableDebugger = debugger["EnableDebugger"].getBool(); EnableDebuggerServer = debugger["EnableDebuggerServer"].getBool(); DebuggerServerPort = debugger["Port"].getInt16(8089); DebuggerStartupDocument = debugger["StartupDocument"].getString(); DebuggerDefaultSandboxPath = debugger["DefaultSandboxPath"].getString(); DebuggerDefaultRpcPort = debugger["RPC.DefaultPort"].getInt16(8083); DebuggerDefaultRpcAuth = debugger["RPC.DefaultAuth"].getString(); DebuggerRpcHostDomain = debugger["RPC.HostDomain"].getString(); DebuggerDefaultRpcTimeout = debugger["RPC.DefaultTimeout"].getInt32(30); } } { Hdf sandbox = config["Sandbox"]; SandboxMode = sandbox["SandboxMode"].getBool(); SandboxPattern = Util::format_pattern (sandbox["Pattern"].getString(), true); SandboxHome = sandbox["Home"].getString(); SandboxFallback = sandbox["Fallback"].getString(); SandboxConfFile = sandbox["ConfFile"].getString(); SandboxFromCommonRoot = sandbox["FromCommonRoot"].getBool(); SandboxDirectoriesRoot = sandbox["DirectoriesRoot"].getString(); SandboxLogsRoot = sandbox["LogsRoot"].getString(); sandbox["ServerVariables"].get(SandboxServerVariables); } { Hdf mail = config["Mail"]; SendmailPath = mail["SendmailPath"].getString("sendmail -t -i"); MailForceExtraParameters = mail["ForceExtraParameters"].getString(); } { Hdf preg = config["Preg"]; PregBacktraceLimit = preg["BacktraceLimit"].getInt32(100000); PregRecursionLimit = preg["RecursionLimit"].getInt32(100000); } Extension::LoadModules(config); }
void Option::Load(Hdf &config) { LoadRootHdf(config["IncludeRoots"], IncludeRoots); LoadRootHdf(config["AutoloadRoots"], AutoloadRoots); config["PackageFiles"].get(PackageFiles); config["IncludeSearchPaths"].get(IncludeSearchPaths); config["PackageDirectories"].get(PackageDirectories); config["PackageExcludeDirs"].get(PackageExcludeDirs); config["PackageExcludeFiles"].get(PackageExcludeFiles); config["PackageExcludePatterns"].get(PackageExcludePatterns); config["PackageExcludeStaticDirs"].get(PackageExcludeStaticDirs); config["PackageExcludeStaticFiles"].get(PackageExcludeStaticFiles); config["PackageExcludeStaticPatterns"].get(PackageExcludeStaticPatterns); CachePHPFile = config["CachePHPFile"].getBool(); config["ParseOnDemandDirs"].get(ParseOnDemandDirs); { Hdf cg = config["CodeGeneration"]; string tmp; #define READ_CG_OPTION(name) \ tmp = cg[#name].getString(); \ if (!tmp.empty()) { \ name = OptionStrings.add(tmp.c_str()); \ } READ_CG_OPTION(IdPrefix); READ_CG_OPTION(LabelEscape); READ_CG_OPTION(LambdaPrefix); READ_CG_OPTION(FunctionPrefix); READ_CG_OPTION(BuiltinFunctionPrefix); READ_CG_OPTION(InvokePrefix); READ_CG_OPTION(CreateObjectPrefix); READ_CG_OPTION(PseudoMainPrefix); READ_CG_OPTION(VariablePrefix); READ_CG_OPTION(GlobalVariablePrefix); READ_CG_OPTION(StaticVariablePrefix); READ_CG_OPTION(ScalarArrayName); READ_CG_OPTION(SystemScalarArrayName); READ_CG_OPTION(ClassPrefix); READ_CG_OPTION(ClassStaticsPrefix); READ_CG_OPTION(ClassStaticsObjectPrefix); READ_CG_OPTION(ClassStaticsCallbackPrefix); READ_CG_OPTION(ClassStaticsIdGetterPrefix); READ_CG_OPTION(ClassStaticInitializerPrefix); READ_CG_OPTION(ClassStaticInitializerFlagPrefix); READ_CG_OPTION(ClassWrapperFunctionPrefix); READ_CG_OPTION(ObjectPrefix); READ_CG_OPTION(ObjectStaticPrefix); READ_CG_OPTION(SmartPtrPrefix); READ_CG_OPTION(MethodPrefix); READ_CG_OPTION(MethodWrapperPrefix); READ_CG_OPTION(MethodImplPrefix); READ_CG_OPTION(PropertyPrefix); READ_CG_OPTION(StaticPropertyPrefix); READ_CG_OPTION(ConstantPrefix); READ_CG_OPTION(ClassConstantPrefix); READ_CG_OPTION(ExceptionPrefix); READ_CG_OPTION(TempVariablePrefix); READ_CG_OPTION(EvalOrderTempPrefix); READ_CG_OPTION(SilencerPrefix); READ_CG_OPTION(EvalInvokePrefix); READ_CG_OPTION(TempPrefix); READ_CG_OPTION(MapPrefix); READ_CG_OPTION(IterPrefix); READ_CG_OPTION(InitPrefix); READ_CG_OPTION(FFIFnPrefix); READ_CG_OPTION(SystemFilePrefix); READ_CG_OPTION(UserFilePrefix); READ_CG_OPTION(ClassHeaderPrefix); READ_CG_OPTION(ClusterPrefix); READ_CG_OPTION(FFIFilePrefix); } int count = 0; for (Hdf hdf = config["SepExtensions"].firstChild(); hdf.exists(); hdf = hdf.next()) { ++count; } SepExtensions.resize(count); count = 0; for (Hdf hdf = config["SepExtensions"].firstChild(); hdf.exists(); hdf = hdf.next()) { SepExtensionOptions &options = SepExtensions[count++]; options.name = hdf.getName(); options.soname = hdf["soname"].getString(); options.include_path = hdf["include"].getString(); options.lib_path = hdf["libpath"].getString(); options.shared = hdf["shared"].getBool(); } config["DynamicFunctionPrefix"].get(DynamicFunctionPrefixes); config["DynamicFunctionPostfix"].get(DynamicFunctionPostfixes); config["DynamicMethodPrefix"].get(DynamicMethodPrefixes); config["DynamicInvokeFunctions"].get(DynamicInvokeFunctions); config["VolatileClasses"].get(VolatileClasses); // build map from function names to sections for (Hdf hdf = config["FunctionSections"].firstChild(); hdf.exists(); hdf = hdf.next()) { for (Hdf hdfFunc = hdf.firstChild(); hdfFunc.exists(); hdfFunc = hdfFunc.next()) { FunctionSections[hdfFunc.getString()] = hdf.getName(); } } ScalarArrayFileCount = config["ScalarArrayFileCount"].getByte(1); if (ScalarArrayFileCount <= 0) ScalarArrayFileCount = 1; LiteralStringFileCount = config["LiteralStringFileCount"].getInt32(10); if (LiteralStringFileCount <= 0) LiteralStringFileCount = 10; HardTypeHints = config["HardTypeHints"].getBool(true); ScalarArrayOverflowLimit = config["ScalarArrayOverflowLimit"].getInt32(2000); if (ScalarArrayOverflowLimit <= 0) ScalarArrayOverflowLimit = 2000; if (UseNamedScalarArray) { ScalarArrayOptimization = true; ScalarArrayCompression = true; } EnableShortTags = config["EnableShortTags"].getBool(true); if (EnableShortTags) ScannerType |= Scanner::AllowShortTags; else ScannerType &= ~Scanner::AllowShortTags; EnableAspTags = config["EnableAspTags"].getBool(); if (EnableAspTags) ScannerType |= Scanner::AllowAspTags; else ScannerType &= ~Scanner::AllowAspTags; EnableXHP = config["EnableXHP"].getBool(); if (EnableXHP) ScannerType |= Scanner::PreprocessXHP; else ScannerType &= ~Scanner::PreprocessXHP; ParserThreadCount = config["ParserThreadCount"].getInt32(0); if (ParserThreadCount <= 0) { ParserThreadCount = Process::GetCPUCount() * 2; } RTTIOutputFile = config["RTTIOutputFile"].getString(); EnableEval = (EvalLevel)config["EnableEval"].getByte(0); AllDynamic = config["AllDynamic"].getBool(true); AllVolatile = config["AllVolatile"].getBool(); GenerateCppLibCode = config["GenerateCppLibCode"].getBool(false); GenerateSourceInfo = config["GenerateSourceInfo"].getBool(false); GenerateDocComments = config["GenerateDocComments"].getBool(true); UseVirtualDispatch = config["UseVirtualDispatch"].getBool(false); EliminateDeadCode = config["EliminateDeadCode"].getBool(true); LocalCopyProp = config["LocalCopyProp"].getBool(true); StringLoopOpts = config["StringLoopOpts"].getBool(true); AutoInline = config["AutoInline"].getBool(false); if (m_hookHandler) m_hookHandler(config); OnLoad(); }
void Hdf::get(hphp_string_imap<std::string> &values) const { values.clear(); for (Hdf hdf = firstChild(); hdf.exists(); hdf = hdf.next()) { values[hdf.getName()] = hdf.getString(""); } }
void Option::Load(const IniSetting::Map& ini, Hdf &config) { LoadRootHdf(ini, config["IncludeRoots"], IncludeRoots); LoadRootHdf(ini, config["AutoloadRoots"], AutoloadRoots); Config::Get(ini, config["PackageFiles"], PackageFiles); Config::Get(ini, config["IncludeSearchPaths"], IncludeSearchPaths); Config::Get(ini, config["PackageDirectories"], PackageDirectories); Config::Get(ini, config["PackageExcludeDirs"], PackageExcludeDirs); Config::Get(ini, config["PackageExcludeFiles"], PackageExcludeFiles); Config::Get(ini, config["PackageExcludePatterns"], PackageExcludePatterns); Config::Get(ini, config["PackageExcludeStaticDirs"], PackageExcludeStaticDirs); Config::Get(ini, config["PackageExcludeStaticFiles"], PackageExcludeStaticFiles); Config::Get(ini, config["PackageExcludeStaticPatterns"], PackageExcludeStaticPatterns); CachePHPFile = Config::GetBool(ini, config["CachePHPFile"]); Config::Get(ini, config["ParseOnDemandDirs"], ParseOnDemandDirs); { Hdf cg = config["CodeGeneration"]; string tmp; #define READ_CG_OPTION(name) \ tmp = Config::GetString(ini, cg[#name]); \ if (!tmp.empty()) { \ name = OptionStrings.add(tmp.c_str()); \ } READ_CG_OPTION(IdPrefix); READ_CG_OPTION(LambdaPrefix); } Config::Get(ini, config["DynamicFunctionPrefix"], DynamicFunctionPrefixes); Config::Get(ini, config["DynamicFunctionPostfix"], DynamicFunctionPostfixes); Config::Get(ini, config["DynamicMethodPrefix"], DynamicMethodPrefixes); Config::Get(ini, config["DynamicInvokeFunctions"], DynamicInvokeFunctions); Config::Get(ini, config["VolatileClasses"], VolatileClasses); // build map from function names to sections for (Hdf hdf = config["FunctionSections"].firstChild(); hdf.exists(); hdf = hdf.next()) { for (Hdf hdfFunc = hdf.firstChild(); hdfFunc.exists(); hdfFunc = hdfFunc.next()) { FunctionSections[Config::GetString(ini, hdfFunc)] = hdf.getName(); } } { Hdf repo = config["Repo"]; { Hdf repoCentral = repo["Central"]; RepoCentralPath = Config::GetString(ini, repoCentral["Path"]); } RepoDebugInfo = Config::GetBool(ini, repo["DebugInfo"], false); } { Hdf autoloadMap = config["AutoloadMap"]; Config::Get(ini, autoloadMap["class"], AutoloadClassMap); Config::Get(ini, autoloadMap["function"], AutoloadFuncMap); Config::Get(ini, autoloadMap["constant"], AutoloadConstMap); AutoloadRoot = Config::GetString(ini, autoloadMap["root"]); } HardTypeHints = Config::GetBool(ini, config["HardTypeHints"], true); HardConstProp = Config::GetBool(ini, config["HardConstProp"], true); EnableHipHopSyntax = Config::GetBool(ini, config["EnableHipHopSyntax"]); EnableZendCompat = Config::GetBool(ini, config["EnableZendCompat"]); JitEnableRenameFunction = Config::GetBool(ini, config["JitEnableRenameFunction"]); EnableHipHopExperimentalSyntax = Config::GetBool(ini, config["EnableHipHopExperimentalSyntax"]); EnableShortTags = Config::GetBool(ini, config["EnableShortTags"], true); { const Hdf& lang = config["Hack"]["Lang"]; IntsOverflowToInts = Config::GetBool(ini, lang["IntsOverflowToInts"], EnableHipHopSyntax); StrictArrayFillKeys = Config::GetHackStrictOption(ini, lang["StrictArrayFillKeys"], EnableHipHopSyntax); } EnableAspTags = Config::GetBool(ini, config["EnableAspTags"]); EnableXHP = Config::GetBool(ini, config["EnableXHP"], false); if (EnableHipHopSyntax) { // If EnableHipHopSyntax is true, it forces EnableXHP to true // regardless of how it was set in the config EnableXHP = true; } ParserThreadCount = Config::GetInt32(ini, config["ParserThreadCount"], 0); if (ParserThreadCount <= 0) { ParserThreadCount = Process::GetCPUCount(); } EnableEval = (EvalLevel) Config::GetByte(ini, config["EnableEval"], 0); AllDynamic = Config::GetBool(ini, config["AllDynamic"], true); AllVolatile = Config::GetBool(ini, config["AllVolatile"]); GenerateDocComments = Config::GetBool(ini, config["GenerateDocComments"], true); EliminateDeadCode = Config::GetBool(ini, config["EliminateDeadCode"], true); CopyProp = Config::GetBool(ini, config["CopyProp"], false); LocalCopyProp = Config::GetBool(ini, config["LocalCopyProp"], true); StringLoopOpts = Config::GetBool(ini, config["StringLoopOpts"], true); AutoInline = Config::GetInt32(ini, config["AutoInline"], 0); ControlFlow = Config::GetBool(ini, config["ControlFlow"], true); VariableCoalescing = Config::GetBool(ini, config["VariableCoalescing"], false); ArrayAccessIdempotent = Config::GetBool(ini, config["ArrayAccessIdempotent"], false); DumpAst = Config::GetBool(ini, config["DumpAst"], false); WholeProgram = Config::GetBool(ini, config["WholeProgram"], true); UseHHBBC = Config::GetBool(ini, config["UseHHBBC"], UseHHBBC); // Temporary, during file-cache migration. FileCache::UseNewCache = Config::GetBool(ini, config["UseNewCache"], false); OnLoad(); }
void SourceRootInfo::createFromUserConfig() { String homePath = String(RuntimeOption::SandboxHome) + "/" + m_user + "/"; { struct stat hstat; if (stat(homePath.c_str(), &hstat) != 0) { if (!RuntimeOption::SandboxFallback.empty()) { homePath = String(RuntimeOption::SandboxFallback) + "/" + m_user + "/"; if (stat(homePath.c_str(), &hstat) != 0) { m_sandboxCond = SandboxOff; return; } } } } string confpath = string(homePath.c_str()) + RuntimeOption::SandboxConfFile; Hdf config, serverVars; String sp, lp, alp, userOverride; try { config.open(confpath); userOverride = config["user_override"].get(); Hdf sboxConf = config[m_sandbox.c_str()]; if (sboxConf.exists()) { sp = sboxConf["path"].get(); lp = sboxConf["log"].get(); alp = sboxConf["accesslog"].get(); serverVars = sboxConf["ServerVars"]; } } catch (HdfException &e) { Logger::Error("%s ignored: %s", confpath.c_str(), e.getMessage().c_str()); } if (serverVars.exists()) { for (Hdf hdf = serverVars.firstChild(); hdf.exists(); hdf = hdf.next()) { m_serverVars.set(String(hdf.getName()), String(hdf.getString())); } } if (!userOverride.empty()) { m_user = std::move(userOverride); } if (m_sandbox == "default") { if (sp.isNull()) { sp = "www/"; } } if (sp.isNull()) { m_sandboxCond = SandboxError; return; } if (sp.charAt(0) == '/') { m_path = std::move(sp); } else { m_path = homePath + sp; } if (m_path.charAt(m_path.size() - 1) != '/') { m_path += "/"; } if (!lp.isNull()) { if (lp.charAt(0) != '/') { lp = homePath + lp; } if (!Logger::SetThreadLog(lp.c_str())) { Logger::Warning("Sandbox error log %s could not be opened", lp.c_str()); } } if (!alp.isNull()) { if (alp.charAt(0) != '/') { alp = homePath + alp; } if (!HttpRequestHandler::GetAccessLog().setThreadLog(alp.c_str())) { Logger::Warning("Sandbox access log %s could not be opened", alp.c_str()); } } }