<h2>Configurable Options for Compiled Program</h2>

Note that, in this documentation, we used "*" for names that the system doesn't
care. In reality, one may always use a string or a name to better describe a
node's purpose. Listed values are defaults, unless examples.

= Logging

  Log {
    Level = None (default) | Error | Warning | Info | Verbose
    NoSilencer = false
    AlwaysLogUnhandledExceptions = false
    RuntimeErrorReportingLevel = 8191
    ForceErrorReportingLevel = 0
    Header = false
    HeaderMangle = 0
    NativeStackTrace = true
    MaxMessagesPerRequest = -1

- Level, NoSilencer, AlwaysLogUnhandledExceptions, RuntimeErrorReportingLevel,
  ForceErrorReportingLevel

These settings control different logging levels. NoSilencer means even when
silencer operator @ is used, still output errors. Unhandled exceptions are
PHP fatal errors, and AlwaysLogUnhandledExceptions will make sure they get
logged even if a user's error handler is installed for them. We also provided
RuntimeErrorReportingLevel for compatibility with PHP. ForceErrorReportingLevel
is a bitmask that will be ORed with RuntimeErrorReportingLevel to determine the
actual error reporting level.

- Header, NativeStackTrace

These settings control log line formats. Header includes timestamp, process id,
thread id, request id (counted from 1 since server starts), message id
(counted from 1 since request started) and extra header text from command line
option (see util/logger.cpp for implementation).

There are two kinds of stacktraces: (1) C++ stacktrace, which is hex-encoded
and printed on every line of logging right after header. These stacktraces can
be translated into human readable frames by running "-m translate" with the
compiled program. (2) PHP stacktrace from code injection. Generated C++ code
injects stacktrace preparation code into every frame of functions and methods.

- HeaderMangle

This setting controls logging of potentially malicious headers.  If
HeaderMangle is greater than 0, then HipHop will log one in every n
requests where a header collision has occurred.  Such collisions
almost certainly indicate a malicious attempt to set headers which are
either set or filtered by a proxy.

- MaxMessagesPerRequest

Controls maximum number of messages each request can log, in case some pages
flood error logs.

    # error log settings
    UseLogFile = true
    File = filename
    UseSyslog = false

    # access log settings
    AccessLogDefaultFormat = %h %l %u %t \"%r\" %>s %b
    Access {
      * {
        File = filename
        Format = some Apache access log format string
      }
      * {
        File = another filename
        Format = some Apache access log format string
      }
    }

    # admin server logging
    AdminLog {
      File = filename
      Format = %h %t %s %U
    }
  }

= Error Handling

  ErrorHandling {
    # Bitmask of error constants to upgrade to E_USER_ERROR. Only E_WARNING,
    # E_USER_WARNING, E_NOTICE, and E_USER_NOTICE are supported.
    UpgradeLevel = 0 (default)
    CallUserHandlerOnFatals = false
    NoInfiniteRecursionDetection = false
    NoticeFrequency = 1    # 1 out of these many notices to log
    WarningFrequency = 1   # 1 out of these many warnings to log
  }

= Resource Limits

  ResourceLimit {
    CoreFileSize = 0           # in bytes
    MaxSocket = 0
    SocketDefaultTimeout = 60  # in seconds
    MaxSQLRowCount = 0
    SerializationSizeLimit = 0
  }

= Server

  PidFile = pid filename

  # $_SERVER['name'] = value
  ServerVariables {
    name = value
  }

  # $_ENV['name'] = value
  EnvVariables {
    name = value
  }

  Server {
    Host = www.default_domain.com
    IP = 0.0.0.0
    Port = 80
    Type = proxygen | fastcgi
    ThreadCount = 50
    ThreadDropCacheTimeoutSeconds = 0
    ThreadJobLIFO = false

    SourceRoot = path to source files and static contents
    IncludeSearchPaths {
      * = some path
      * = another path
    }
    # Recommend to turn this on when all the file paths in the file invoke
    # table are relative for faster dynamic file inclusion.
    AlwaysUseRelativePath = false

    RequestTimeoutSeconds = -1
    RequestMemoryMaxBytes = 0

    # maximum POST Content-Length
    MaxPostSize = 10MB
    # maximum memory size for image processing
    ImageMemoryMaxBytes = Upload.UploadMaxFileSize * 2

    # If ServerName is not specified for a virtual host, use prefix + this
    # suffix to compose one. If "Pattern" was specified, matched pattern,
    # either by parentheses for the first match or without parentheses for
    # the whole pattern, will be used as prefix for DefaultServerNameSuffix.
    DefaultServerNameSuffix = default_domain.com

    # Forcing $_SERVER['SERVER_NAME'] to come from request header
    ForceServerNameToHeader = false

    # Print file paths traversed onto the 404 page
    PathDebug = false

    # startup options
    TakeoverFilename = filename   # for port takeover between server instances
    DefaultDocument = index.php
    StartupDocument = filename
    RequestInitFunction = function_name
    RequestInitDocument = filename
    ErrorDocument404 = 404.php
    ErrorDocument500 = 500.php
    FatalErrorMessage = some string

    # shutdown options
    GracefulShutdownWait = 0   # in seconds
    HarshShutdown = true
    EvilShutdown = true

    # SSL options
    EnableSSL = false
    SSLPort = 443
    SSLCertificateFile = <certificate file> # similar to apache
    SSLCertificateKeyFile = <certificate file> # similar to apache

- GracefulShutdownWait, HarshShutdown, EvilShutdown

Graceful shutdown will try admin /stop command and it waits for number of
seconds specified by GracefulShutdownWait. Harsh shutdown looks for pid file
and try to kill that process. Evil shutdown kills anything listening on the
server port it's trying to grab.

    # HTTP settings
    GzipCompressionLevel = 3
    EnableKeepAlive = true
    EnableOutputBuffering = false
    OutputHandler =
    ImplicitFlush = false
    EnableEarlyFlush = true
    ForceChunkedEncoding = false
    MaxPostSize = 8  # in MB

To further control idle connections, set
    ConnectionTimeoutSeconds = <some value>
This parameter controls how long the server will timeout a connection after
idle on read or write. It takes effect when EnableKeepAlive is enabled.

- EnableEarlyFlush, ForceChunkedEncoding

EnableEarlyFlush allows chunked encoding responses, and ForceChunkedEncoding
will only send chunked encoding responses, unless client doesn't understand.

    # static contents
    FileCache = filename
    EnableStaticContentFromDisk = true
    ExpiresActive = true
    ExpiresDefault = 2592000
    DefaultCharsetName = UTF-8

- EnableStaticContentFromDisk

A static content cache creates one single file from all static contents,
including css, js, html, images and any other non-PHP files (or even PHP files,
if CachePHPFile is turned on for compiler options). Normally this is prepared
by compiler at compilation time, but it can also be prepared at run-time, if
SourceRoot points to real file directory and EnableStaticContentFromDisk is
true. Otherwise, use FileCache to point to the static content cache file
created by the compiler.

NOTE: the FileCache should be set with absolute path

- ExpiresActive, ExpiresDefault, DefaultCharsetName

These control static content's response headers. DefaultCharsetName is also
used for PHP responses in case no other charset has been set explicitly.

    # file access control
    SafeFileAccess = false
    FontPath = where to look for font files
    AllowedDirectories {
      * = /tmp
    }
    AllowedFiles {
      * = specific file to allow
    }

    # files with these extensions cannot be executed
    ForbiddenFileExtensions {
      * = ...
    }

    APC {
      EnableApc = true
      PrimeLibrary = filename
      LoadThread = 2
      CompletionKeys {
        * = key name
      }

- APC Priming

There is a way to prepare APC items in dry format, serialized in binary files,
and these files can be loaded (or "primed") extremely fast at startup time.
To prepare these .cpp files, check apc_sample_serializer.php for one way
of doing it. Once prepared, we can compiled them into .so that can be loaded
through PrimeLibrary option. The loading can be done in parallel with
LoadThread count of threads. Once loading is done, it can write to APC with
some specified keys in CompletionKeys to tell web application about priming.


      ExpireOnSets = false
      PurgeFrequency = 4096

- ExpireOnSets, PurgeFrequency

ExpireOnSets turns on item purging on expiration, and it's only done once per
PurgeFrequency of sets.


    # Light process has very little forking cost, because they are pre-forked
    # Recommend to turn it on for faster shell command execution.
    LightProcessFilePrefix = ./lightprocess
    LightProcessCount = 0

    # Uploads
    Upload {
      UploadMaxFileSize = 100 # Size in MB
      UploadTmpDir = /tmp/
      EnableFileUploads = true
      EnableUploadProgress = false
      Rfc1867Freq = 262144 # 256K
      Rfc1867Prefix = vupload_
      Rfc1867Name = video_ptoken
    }
  }

= Virtual Hosts

  # default IpBlockMap that applies to all URLs, if exists
  IpBlockMap {
    * {
      Location = /url
      AllowFirst = false
      Ip {
        Allow {
          * = 127.0.0.1
          * = 192.0.0.0/8
        }
        Deny {
          * = 192.1.0.0
        }
      }
    }
  }

  VirtualHost {
    * {
      Disabled = false
      Prefix = prefix.
      Pattern = regex pattern
      PathTranslation = html
      CheckExistenceBeforeRewrite = true
      ServerName =
      ServerVariables {
        name = value
      }

      RewriteRules {
        * {
          pattern = regex pattern same as Apache's
          to = target format same as Apache's
          qsa = false
          redirect = 0 (default: off) | 302 | 301 | other status code

          conditions {
            * {
              pattern = regex pattern to match
              type = host | request
              negate = false
            }
          }
        }
      }

      IpBlockMap {
        # in same format as the IpBlockMap example above
      }

      # Remove certain query string parameters from access log.
      LogFilters {
        * {
          # regex pattern to match a URL
          url = (empty means matching all URLs)

          # names of parameters to remove from query string
          params = {
            * = parameter name
          }

          # alternatively, use regex pattern to replace with empty string.
          pattern = (empty means hiding entire query string)

          # optionally, specify what values to replace with
          value = (by default it's empty, removing the query parameter)
        }
      }
    }
  }

- CheckExistenceBeforeRewrite

With this setting, rewrite rules will not be applied for files that exist in
the original path. This is the default behavior. Set this to false if one wants
to block access to certain files (ex. .htaccess.)

= Administration Server

  AdminServer {
    Port = 8088
    ThreadCount = 1
    Password =
  }

= Satellite Servers

  Satellites {
    * {
      Type = RPCServer | InternalPageServer

      Port = 0  # disabled
      ThreadCount = 5

      # only for RPCServer
      MaxRequest = 500
      MaxDuration = 120    # in seconds
      TimeoutSeconds = 30  # default to RequestTimeoutSeconds
      RequestInitFunction = on_init
      RequestInitDocument = filename
      Password = authentication

      # only for InternalPageServer
      BlockMainServer = true
      URLs {
        * = pattern
      }
    }
  }

- RPCServer

Please refer to its documentation for more details.

- Internal Page Server

Serves internal pages over a private port. These pages will become unavailable
to main HTTP port if BlockMainServer is turned on. Use URLs to specify regex
patterns for pages to server over this port.

  Xbox {
    ServerInfo {
      ThreadCount = 0
      Port = 0
      MaxRequest = 500
      MaxDuration = 120
      RequestInitFunction =
      RequestInitDocument =
    }
    ProcessMessageFunc = xbox_process_message
    DefaultLocalTimeoutMilliSeconds = 500
    DefaultRemoteTimeoutSeconds = 5
  }

- Xbox Server

An xbox server provides cross-machine communication, similar to a message
queuing system. It also allows local processing of messages, then working as
a multithreading facility for PHP execution. More documentation will be coming
for xbox applications.

  PageletServer {
    ThreadCount = 0
  }

- Pagelet Server

A pagelet server is essentially the same as local CURL, except it's more
efficient. This allows parallel execution of a web page, preparing two panels
or iframes at the same time.

= Proxy Server

  Proxy {
    Origin = the server to proxy to
    Retry = 3

    # serve these URLs and proxy all others, trumping ProxyURLs settings
    ServeURLs = false
    ServeURLs {
      * = urls not to proxy
    }

    # proxy these URLs
    ProxyURLs = false
    ProxyURLs {
      * = urls to proxy
    }
    # proxy these patterns
    ProxyPatterns {
      * = patterns to proxy
    }
    # proxy this percentage of pages
    Percentage = 0
  }

- ServeURLs, ProxyURLs

Please note that these two settings are mutually exclusive, and you may turn on
just one. When ProxyURLs is on, you may choose to use ProxyURLs, ProxyPatterns
or Percentage or any combination of them to specify how it should be proxied.

= Static Content

  StaticFile {
    Extensions {
      bmp = image/bmp
    }
    Generators {
      * = static_resource.php
    }
    FilesMatch {
      * {
        pattern = .*\.(dll|exe)
        headers {
          * = Content-Disposition: attachment
        }
      }
    }
  }

- Generators

In addition to Static Content Cache, we also support Dynamic Content Cache. If
static_resource.php generates identical files given the same HTTP input, it
can be listed under Generators, so its generated content can be cached for
next requests.

= Stats

  Stats = false
  Stats {
    Web = false
    Memory = false
    Malloc = false
    APC = false
    SQL = false
    SQLTable = false
    NetworkIO = false

    XSL = xsl filename
    XSLProxy = url to get the xsl file

    SlotDuration = 600  # in seconds
    MaxSlot = 72        # 10 minutes x 72 = 12 hours

    APCSize {
      Enable = false
      CountPrime = false
      Group = false
      Individual = false
      FetchStats = false
      SpecialPrefix {
        * = sv:/
      }
      SpecialMiddle {
        * = :sv:/
      }
    }
  }

= Debug Settings

  Debug {
    ServerErrorMessage = false

    RecordInput = false
    ClearInputOnSuccess = true

    ProfilerOutputDir = /tmp

    CoreDumpEmail = email address
    CoreDumpReport = true
    CoreDumpReportDirectory = /tmp

    StackTraceTimeout = 0
  }

- ServerErrorMessage

This setting turns on error messages in HTTP responses.

- RecordInput, ClearInputOnSuccess

With these two settings, we can easily capture an HTTP request in a file that
can be replayed with "-m replay" from the compiled program at command line.
We can easily gdb that way to debug any problems. Watch error log for recorded
file's location. ClearInputOnSuccess can automatically delete requests that
had 200 responses and it's useful to capture 500 errors on production without
capturing good responses.

- StackTraceTimeout

This specifies the maximum number of seconds spent for generating a stack trace
when hhvm is crashed. The default is 0 which means no timeout. This can be set
to prevent from deadlocks in the backtrace handler.

- APCSize

There are options for APC size profiling. If enabled, APC overall size will be
updated every time a store or delete happens. This allows querying apc stats
on admin port. 'CountPrime' controls whether size stats includes primed keys.
'Group' controls whether stats break-down by key groups get profiled.
'SpecialPrefix' and 'SpecialMiddle' are used for aggregating some keys groups.
'Individual' controls whether size profiling is enabled for each key, which
could incur some space overhead. 'FetchStats' can be enabled to also profile
apc_fetch, which further increases time overhead.
'FetchStats' implies 'Individual', and 'Individual' implies 'Group'

= Sandbox Environment

A sandbox has pre-defined setup that maps some directory to be source root of
a web server, hence eliminating a lot of setups.

  Sandbox {
    SandboxMode = false
    Pattern = www.[user]-[sandbox].[machine].facebook.com
    Home = /home
    ConfFile = ~/.hphp

    ServerVariables {
      name = value
    }
  }

- Sandbox Configuration

First, pick a name. "default" has special meaning, then URL would be
www.[user].[machine].facebook.com. Say the name is "sandbox", the configuration
will look like this,

  [sandbox].path = path
  [sandbox].log = path
  [sandbox].accesslog = path

"path" points to PHP source files. "log" points to error log location and
"accesslog" points to access log location.

== Debugger Configuration

By default, HHVM does not listen for connections from the HipHop
Debugger (hphpd). To enable this you need to first setup the sandbox
environment described above, then add the following to your config:

  Eval.Debugger {
    EnableDebugger = true
    EnableDebuggerServer = true
    Port = 8089
    DefaultSandboxPath = path to source files, similar to Server.SourceRoot
  }

This will cause HHVM to start a debugger server, and you should see an
entry in the log indicating the debugger server has started before the
entry about all servers having been started.

- Machine Sharing

The benefit is, same server can have one "Sandbox" configuration, and many
users can use the same machine serving their own source files.

= HPHPi Settings

  Eval {
    CheckSymLink = true

    EnableHipHopSyntax = false

    EnableShortTags = true   # is <? allowed
    EnableXHP = true         # XHP extension
    NativeXHP = true         # Use HPHP to directly handle XHP

    VMStackElms = 16384      # Maximum stack size

    # debugger
    Debugger {
      EnableDebugger = false
      EnableDebuggerServer = false
      Port = 8089
      StartupDocument =
      DefaultSandboxPath =

      RPC {
        DefaultPort = 8083
        DefaultAuth =
        HostDomain =
        DefaultTimeout = 30
      }
    }

    TimeoutsUseWallTime = true
    CheckFlushOnUserClose = true

    # Causes HHVM to disallow constructs that are unavailable when Repo.Authoritative
    # is active, without requiring you to run in Repo.Authoritative.
    AuthoritativeMode = true

    # experimental, please ignore
    BytecodeInterpreter = false
    DumpBytecode = false
    RecordCodeCoverage = false
    CodeCoverageOutputFile =
  }

- CheckSymLink

Determines whether or not to follow symlinks (and, from a performance
standpoint, make the associated realpath() calls needed) when resolving
includes/requires and loading code. This is enabled by default for parity with
the reference implementation. If not needed for a particular application and/or
configuration, disable this when tuning.

- TimeoutsUseWallTime

Determines whether or not to interpret set_time_limit timeouts as wall time or
CPU time (which the reference implementation uses.) Defaults to wall time.

- CheckFlushOnUserClose

Determines whether or not close() for user streams (registered by
stream_wrapper_register) will consider the return value of the implicit call to
flush() when calculating its return value.

= MySQL

  MySQL {
    ReadOnly = false
    ConnectTimeout = 1000      # in ms
    ReadTimeout = 1000         # in ms
    WaitTimeout = -1           # in ms, -1 means "don't set"
    SlowQueryThreshold = 1000  # in ms, log slow queries as errors
    KillOnTimeout = false
    Socket =                   # Default location to look for mysql.sock
    TypedResults = true
  }

- KillOnTimeout

When a query takes long time to execute on server, client has a chance to
kill it to avoid extra server cost by turning on KillOnTimeout.

- TypedResults

Zend returns strings and NULL only for MySQL results, not integers or floats.
HHVM return ints (and, sometimes, actual doubles). This behavior can be
disabled by setting TypedResults to false.

= HTTP Monitoring

  Http {
    DefaultTimeout = 30         # in seconds
    SlowQueryThreshold = 5000   # in ms, log slow HTTP requests as errors
  }

= Mail

  Mail {
    SendmailPath = sendmail -t -i
    ForceExtraParameters =
  }

= PCRE

  Preg {
   BacktraceLimit = 100000
   RecursionLimit = 100000
  }

- Eval.PCRETableSize

The number of patterns which can be stored in the PCRE cache.

- Eval.PCRECacheType

May be "static", for a very fast cache which never evicts, "lru", for a cache
which evicts the least-recently used item when full, or "scalable" for a cache
which is slightly slower than "lru" at low concurrency but much faster for a
high-concurrency tight-loop workload.

Default: scalable.

- Eval.PCREExpireInterval

If Eval.PCRECacheType is set to "static", then setting this to an integer
number of seconds will cause the cache to be regularly cleared after the
specified number of seconds.

For "lru" and "scalable" type caches, this is not necessary and not supported.

=  Tier overwrites

  Tiers {
    * {
      machine = /regex pattern/
      overwrite {
        # any config settings described in this documentation
      }
    }
  }

This feature allows a machine to overwrite configurations just by matching
machine names with specified regex pattern. This block of configuration can
appear at any location of the file, even at top.

= PHP File Extensions

By default any file with .php in the URL is treated as PHP source code and is
passed through to the execution engine for processing. This configuration option
allows other file extensions to be treated similarly. Note that .php is
automatically treated as such and does not need to be specified in this list.

    PhpFile {
        Extensions {
            phpt = application/x-phpt
            hphp = application/x-hhvm-php
        }
    }

The content type is not used and is just for descriptive purposes.
