示例#1
0
文件: option.cpp 项目: Jasonudoo/hhvm
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,""));
    }
  }
}
示例#2
0
// 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());
      }
    }
  }
}
示例#3
0
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();
    }
  }
}
示例#4
0
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(""));
    }
  }
}
示例#5
0
文件: option.cpp 项目: Jasonudoo/hhvm
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"]);
    }
  }
}
示例#6
0
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;
  }
}
示例#7
0
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);
}
示例#8
0
文件: config.cpp 项目: atdt/hhvm
// 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);
        }
      }
    }
  }
示例#9
0
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;
  }
}
示例#10
0
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;
      }
    }
  }
}
示例#11
0
// 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());
      }
    }
  }
}
示例#12
0
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();
}
示例#13
0
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();
}
示例#14
0
void VirtualHost::init(const IniSetting::Map& ini, Hdf vh) {
  m_name = vh.getName();

  const char *prefix = Config::Get(ini, vh["Prefix"], "");
  const char *pattern = Config::Get(ini, vh["Pattern"], "");
  const char *pathTranslation = Config::Get(ini, vh["PathTranslation"], "");
  Hdf overwrite = vh["overwrite"];

  if (prefix) m_prefix = prefix;
  if (pattern) {
    m_pattern = format_pattern(pattern, false);
    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 += '/';
    }
  }
  initRuntimeOption(ini, overwrite);

  Config::Bind(m_disabled, ini, vh["Disabled"], false);

  Config::Bind(m_checkExistenceBeforeRewrite, ini,
               vh["CheckExistenceBeforeRewrite"], true);

  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 = format_pattern(Config::GetString(ini, hdf["pattern"], ""), true);
    Config::Bind(rule.to, ini, hdf["to"], "");
    Config::Bind(rule.qsa, ini, hdf["qsa"], false);
    Config::Bind(rule.redirect, ini, hdf["redirect"], 0);
    Config::Bind(rule.encode_backrefs, ini, hdf["encode_backrefs"], false);

    if (rule.pattern.empty() || rule.to.empty()) {
      throw std::runtime_error("Invalid 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 = format_pattern(Config::GetString(ini, chdf["pattern"], ""), true);
      if (cond.pattern.empty()) {
        throw std::runtime_error("Invalid rewrite rule: (empty cond pattern)");
      }
      const char *type = Config::Get(ini, chdf["type"]);
      if (type) {
        if (strcasecmp(type, "host") == 0) {
          cond.type = RewriteCond::Type::Host;
        } else if (strcasecmp(type, "request") == 0) {
          cond.type = RewriteCond::Type::Request;
        } else {
          throw std::runtime_error("Invalid rewrite rule: (invalid "
            "cond type)");
        }
      } else {
        cond.type = RewriteCond::Type::Request;
      }
      Config::Bind(cond.negate, ini, chdf["negate"], false);
    }

  }

  if (vh["IpBlockMap"].firstChild().exists()) {
    Hdf ipblocks = vh["IpBlockMap"];
    m_ipBlocks = std::make_shared<IpBlockMap>(ini, ipblocks);
  }

  Hdf logFilters = vh["LogFilters"];
  for (Hdf hdf = logFilters.firstChild(); hdf.exists(); hdf = hdf.next()) {
    QueryStringFilter filter;
    filter.urlPattern = format_pattern(Config::GetString(ini, hdf["url"], ""), true);
    Config::Bind(filter.replaceWith, ini, hdf["value"], "");
    filter.replaceWith = "\\1=" + filter.replaceWith;

    std::string pattern = Config::GetString(ini, hdf["pattern"], "");
    std::vector<std::string> names;
    Config::Get(ini, hdf["params"], 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 = format_pattern(pattern, false);
      }
    } else if (!names.empty()) {
      throw std::runtime_error("Invalid log filter: (cannot specify "
        "both params and pattern)");
    }

    filter.namePattern = pattern;
    m_queryStringFilters.push_back(filter);
  }

  Config::Get(ini, vh["ServerVariables"], m_serverVars);
  Config::Bind(m_serverName, ini, vh["ServerName"]);
}
示例#15
0
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();
}
示例#16
0
void Option::Load(const IniSetting::Map& ini, Hdf &config) {
  LoadRootHdf(ini, config, "IncludeRoots", IncludeRoots);
  LoadRootHdf(ini, config, "AutoloadRoots", AutoloadRoots);

  Config::Bind(PackageFiles, ini, config, "PackageFiles", PackageFiles);
  Config::Bind(IncludeSearchPaths, ini, config, "IncludeSearchPaths");
  Config::Bind(PackageDirectories, ini, config, "PackageDirectories");
  Config::Bind(PackageExcludeDirs, ini, config, "PackageExcludeDirs");
  Config::Bind(PackageExcludeFiles, ini, config, "PackageExcludeFiles");
  Config::Bind(PackageExcludePatterns, ini, config, "PackageExcludePatterns");
  Config::Bind(PackageExcludeStaticDirs, ini,
               config, "PackageExcludeStaticDirs");
  Config::Bind(PackageExcludeStaticFiles, ini,
               config, "PackageExcludeStaticFiles");
  Config::Bind(PackageExcludeStaticFiles, ini,
               config, "PackageExcludeStaticPatterns");
  Config::Bind(CachePHPFile, ini, config, "CachePHPFile");

  Config::Bind(ParseOnDemandDirs, ini, config, "ParseOnDemandDirs");

  {
    std::string tmp;

#define READ_CG_OPTION(name)                    \
    tmp = Config::GetString(ini, config, "CodeGeneration."#name); \
    if (!tmp.empty()) {                         \
      name = OptionStrings.add(tmp.c_str());    \
    }

    READ_CG_OPTION(IdPrefix);
    READ_CG_OPTION(LambdaPrefix);
  }

  Config::Bind(DynamicInvokeFunctions, ini, config, "DynamicInvokeFunctions");
  Config::Bind(VolatileClasses, ini, config, "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, "", "", false)]
             = hdf.getName();
    }
  }

  {
    // Repo
    {
      // Repo Central
      Config::Bind(RepoCentralPath, ini, config, "Repo.Central.Path");
    }
    Config::Bind(RepoDebugInfo, ini, config, "Repo.DebugInfo", false);
  }

  {
    // AutoloadMap
    Config::Bind(AutoloadClassMap, ini, config, "AutoloadMap.class");
    Config::Bind(AutoloadFuncMap, ini, config, "AutoloadMap.function");
    Config::Bind(AutoloadConstMap, ini, config, "AutoloadMap.constant");
    Config::Bind(AutoloadRoot, ini, config, "AutoloadMap.root");
  }

  Config::Bind(HardTypeHints, ini, config, "HardTypeHints", true);
  Config::Bind(HardReturnTypeHints, ini, config, "HardReturnTypeHints", false);
  Config::Bind(HardConstProp, ini, config, "HardConstProp", true);

  Config::Bind(EnableHipHopSyntax, ini, config, "EnableHipHopSyntax");
  Config::Bind(EnableZendCompat, ini, config, "EnableZendCompat");
  Config::Bind(JitEnableRenameFunction, ini, config, "JitEnableRenameFunction");
  Config::Bind(EnableHipHopExperimentalSyntax, ini,
               config, "EnableHipHopExperimentalSyntax");
  Config::Bind(EnableShortTags, ini, config, "EnableShortTags", true);

  {
    // Hack
    Config::Bind(IntsOverflowToInts, ini, config,
                 "Hack.Lang.IntsOverflowToInts", EnableHipHopSyntax);
    Config::Bind(StrictArrayFillKeys, ini, config,
                 "Hack.Lang.StrictArrayFillKeys");
    Config::Bind(DisallowDynamicVarEnvFuncs, ini, config,
                 "Hack.Lang.DisallowDynamicVarEnvFuncs");
  }

  Config::Bind(EnableAspTags, ini, config, "EnableAspTags");

  Config::Bind(EnableXHP, 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;
  }

  Config::Bind(ParserThreadCount, ini, config, "ParserThreadCount", 0);
  if (ParserThreadCount <= 0) {
    ParserThreadCount = Process::GetCPUCount();
  }

  // Just to silence warnings until we remove them from various config files
  (void)Config::GetByte(ini, config, "EnableEval", 0);
  (void)Config::GetBool(ini, config, "AllDynamic", true);

  Config::Bind(AllVolatile, ini, config, "AllVolatile");

  Config::Bind(GenerateDocComments, ini, config, "GenerateDocComments", true);
  Config::Bind(DumpAst, ini, config, "DumpAst", false);
  Config::Bind(WholeProgram, ini, config, "WholeProgram", true);
  Config::Bind(UseHHBBC, ini, config, "UseHHBBC", UseHHBBC);

  // Temporary, during file-cache migration.
  Config::Bind(FileCache::UseNewCache, ini, config, "UseNewCache", false);
}
示例#17
0
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);
}
示例#18
0
void RuntimeOption::Load(Hdf &config) {
  PidFile = config["PidFile"].getString("www.pid");

  // Tier overwrites
  {
    Hdf tiers = config["Tiers"];
    string hostname = Process::GetHostName();
    for (Hdf hdf = tiers.firstChild(); hdf.exists(); hdf = hdf.next()) {
      string pattern = hdf["machine"].getString();
      if (!pattern.empty()) {
        Variant ret = preg_match(String(pattern.c_str(), pattern.size(),
                                        AttachLiteral),
                                 String(hostname.c_str(), hostname.size(),
                                        AttachLiteral));
        if (ret.toInt64() > 0) {
          Tier = hdf.getName();
          config.copy(hdf["overwrite"]);
          // no break here, so we can continue to match more overwrites
        }
      }
    }
  }

  {
    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();
    Logger::MaxMessagesPerRequest =
      logger["MaxMessagesPerRequest"].getInt32(-1);

    Logger::UseLogFile = logger["UseLogFile"].getBool(true);
    if (Logger::UseLogFile) {
      LogFile = logger["File"].getString();
    }

    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);

    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;
        }
        AccessLogs.
          push_back(pair<string, string>(fname, hdf["Format"].
                                         getString(AccessLogDefaultFormat)));
      }
    }

    AdminLogFormat = logger["AdminLogFormat"].getString("%h %t %s %U");
    AdminLogFile = logger["AdminLogFile"].getString();
  }
  {
    Hdf error = config["ErrorHandling"];
    NoInfiniteLoopDetection = error["NoInfiniteLoopDetection"].getBool();
    NoInfiniteRecursionDetection =
      error["NoInfiniteRecursionDetection"].getBool();
    ThrowBadTypeExceptions = error["ThrowBadTypeExceptions"].getBool();
    ThrowNotices = error["ThrowNotices"].getBool();
    AssertActive = error["AssertActive"].getBool();
    AssertWarning = error["AssertWarning"].getBool();
  }
  {
    Hdf rlimit = config["ResourceLimit"];
    setResourceLimit(RLIMIT_CORE,   rlimit, "CoreFileSize");
    setResourceLimit(RLIMIT_NOFILE, rlimit, "MaxSocket");
    setResourceLimit(RLIMIT_DATA,   rlimit, "RSS");
    MaxRSS = rlimit["RSS"].getInt64(0);
  }
  {
    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);
    ServerThreadCount = server["ThreadCount"].getInt32(50);
    PageletServerThreadCount = server["PageletServerThreadCount"].getInt32(0);
    RequestTimeoutSeconds = server["RequestTimeoutSeconds"].getInt32(-1);
    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);
    EnableKeepAlive = server["EnableKeepAlive"].getBool(true);
    EnableEarlyFlush = server["EnableEarlyFlush"].getBool(true);
    ForceChunkedEncoding = server["ForceChunkedEncoding"].getBool();
    MaxPostSize = (server["MaxPostSize"].getInt32(8)) * (1 << 20);
    UploadMaxFileSize = (server["MaxPostSize"].getInt32(10)) * (1 << 20);
    EnableFileUploads = server["EnableFileUploads"].getBool(true);
    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");

    SourceRoot = server["SourceRoot"].getString();
    if (!SourceRoot.empty() && SourceRoot[SourceRoot.length() - 1] != '/') {
      SourceRoot += '/';
    }
    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++) {
      string &path = IncludeSearchPaths[i];
      if (!path.empty() && path[path.length() - 1] != '/') {
        path += '/';
      }
    }
    IncludeSearchPaths.insert(IncludeSearchPaths.begin(), "./");

    FileCache = server["FileCache"].getString();
    DefaultDocument = server["DefaultDocument"].getString();
    ErrorDocument404 = server["ErrorDocument404"].getString();
    normalizePath(ErrorDocument404);
    FatalErrorMessage = server["FatalErrorMessage"].getString();
    FontPath = server["FontPath"].getString();
    if (!FontPath.empty() && FontPath[FontPath.length() - 1] != '/') {
      FontPath += "/";
    }
    EnableStaticContentCache =
      server["EnableStaticContentCache"].getBool(true);
    EnableStaticContentFromDisk =
      server["EnableStaticContentFromDisk"].getBool(true);

    RTTIDirectory = server["RTTIDirectory"].getString("/tmp/");
    if (!RTTIDirectory.empty() &&
        RTTIDirectory[RTTIDirectory.length() - 1] != '/') {
      RTTIDirectory += "/";
    }
    EnableCliRTTI = server["EnableCliRTTI"].getBool();

    StartupDocument = server["StartupDocument"].getString();
    normalizePath(StartupDocument);
    WarmupDocument = server["WarmupDocument"].getString();
    RequestInitFunction = server["RequestInitFunction"].getString();
    server["ThreadDocuments"].get(ThreadDocuments);
    for (unsigned int i = 0; i < ThreadDocuments.size(); i++) {
      normalizePath(ThreadDocuments[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);

    EnableMemoryManager = server["EnableMemoryManager"].getBool();
    CheckMemory = server["CheckMemory"].getBool();
    UseZendArray = server["UseZendArray"].getBool(true);

    Hdf apc = server["APC"];
    EnableApc = apc["EnableApc"].getBool(true);
    ApcUseSharedMemory = apc["UseSharedMemory"].getBool();
    ApcSharedMemorySize = apc["SharedMemorySize"].getInt32(1024 /* 1GB */);
    ApcPrimeLibrary = apc["PrimeLibrary"].getString();
    ApcLoadThread = apc["LoadThread"].getInt16(2);
    apc["CompletionKeys"].get(ApcCompletionKeys);

    string apcTableType = apc["TableType"].getString("hash");
    if (strcasecmp(apcTableType.c_str(), "hash") == 0) {
      ApcTableType = ApcHashTable;
    } else if (strcasecmp(apcTableType.c_str(), "lfu") == 0) {
      ApcTableType = ApcLfuTable;
    } 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");
    }

    ApcUseLockedRefs = apc["UseLockedRefs"].getBool();
    ApcExpireOnSets = apc["ExpireOnSets"].getBool();
    ApcPurgeFrequency = apc["PurgeFrequency"].getInt32(4096);

    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);

    SharedStores::Create();

    LightProcessFilePrefix =
      server["LightProcessFilePrefix"].getString("./lightprocess");
    LightProcessCount = server["LightProcessCount"].getInt32(0);

    InjectedStacktrace = server["InjectedStacktrace"].getBool();

    ForceServerNameToHeader = server["ForceServerNameToHeader"].getBool();
  }
  {
    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["ServerThreadCount"].getInt32(0);
    XboxServerPort = xbox["ServerPort"].getInt32(0);
    XboxDefaultLocalTimeoutMilliSeconds =
      xbox["DefaultLocalTimeoutMilliSeconds"].getInt32(500);
    XboxDefaultRemoteTimeoutSeconds =
      xbox["DefaultRemoteTimeoutSeconds"].getInt32(5);
    XboxServerInfoMaxRequest = xbox["ServerInfoMaxRequest"].getInt32(500);
    XboxServerInfoDuration = xbox["ServerInfoDuration"].getInt32(120);
    XboxServerInfoWarmupDoc = xbox["ServerInfoWarmupDoc"].get("");
    XboxServerInfoReqInitFunc = xbox["ServerInfoReqInitFunc"].get("");
    XboxProcessMessageFunc =
      xbox["ProcessMessageFunc"].get("xbox_process_message");
  }
  {
    Hdf content = config["StaticFile"];
    content["Extensions"].get(StaticFileExtensions);
    content["Generators"].get(StaticFileGenerators);
  }
  {
    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);
  }
  {
    Hdf mysql = config["MySQL"];
    MySQLReadOnly = mysql["ReadOnly"].getBool();
    MySQLLocalize = mysql["Localize"].getBool();
    MySQLConnectTimeout = mysql["ConnectTimeout"].getInt32(1000);
    MySQLReadTimeout = mysql["ReadTimeout"].getInt32(1000);
    MySQLSlowQueryThreshold = mysql["SlowQueryThreshold"].getInt32(1000);
    MySQLKillOnTimeout = mysql["KillOnTimeout"].getBool();
  }
  {
    Hdf http = config["Http"];
    HttpDefaultTimeout = http["DefaultTimeout"].getInt32(30);
    HttpSlowQueryThreshold = http["SlowQueryThreshold"].getInt32(5000);
  }
  {
    Hdf sandbox = config["Sandbox"];
    SocketDefaultTimeout = sandbox["SocketDefaultTimeout"].getInt16(5);
    LocalMemcache = sandbox["LocalMemcache"].getBool();
    MemcacheReadOnly = sandbox["MemcacheReadOnly"].getBool();
  }
  {
    Hdf debug = config["Debug"];
    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();
    }
  }
  {
    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();
    EnableSQLStats = stats["SQL"].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
  }
  {
    config["ServerVariables"].get(ServerVariables);
    config["EnvVariables"].get(EnvVariables);
  }
  {
    Hdf eval = config["Eval"];
    EnableXHP = eval["EnableXHP"].getBool(true);
    EnableStrict = eval["EnableStrict"].getBool(0);
    StrictLevel = eval["StrictLevel"].getInt32(1); // StrictBasic
    StrictFatal = eval["StrictFatal"].getBool();
    EvalBytecodeInterpreter = eval["BytecodeInterpreter"].getBool(false);
    DumpBytecode = eval["DumpBytecode"].getBool(false);
  }
  {
    Hdf sandbox = config["Sandbox"];
    SandboxMode = sandbox["SandboxMode"].getBool();
    SandboxPattern = format_pattern(sandbox["Pattern"].getString());
    SandboxHome = sandbox["Home"].getString();
    SandboxConfFile = sandbox["ConfFile"].getString();
    sandbox["ServerVariables"].get(SandboxServerVariables);
  }
  {
    Hdf mail = config["Mail"];
    SendmailPath = mail["SendmailPath"].getString("sendmail -t -i");
    MailForceExtraParameters = mail["ForceExtraParameters"].getString();
  }
}
示例#19
0
文件: option.cpp 项目: Jasonudoo/hhvm
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();
}
示例#20
0
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);

    // 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(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(true);
    AllVolatile = config["AllVolatile"].getBool();

    GenerateSourceInfo = config["GenerateSourceInfo"].getBool(false);
    UseVirtualDispatch = config["UseVirtualDispatch"].getBool(false);

    OnLoad();
}