{# select Captiveportal zone item #}
{% set cp_zone_item = [] %}
{% for item in helpers.toList('OPNsense.captiveportal.zones.zone') %}
    {% if TARGET_FILTERS['OPNsense.captiveportal.zones.zone.' ~ loop.index0] or TARGET_FILTERS['OPNsense.captiveportal.zones.zone'] %}
        {# found zone, search for interface ip #}
        {% for intf_tag in item.interfaces.split(',') %}
            {% for conf_key, conf_inf in interfaces.iteritems() %}
                {% if conf_key == intf_tag and conf_inf.ipaddr != 'dhcp' %}
                    {% do item.update({'interface_hostaddr':conf_inf.ipaddr}) %}
                {% endif %}
            {% endfor %}
        {% endfor %}
        {% do cp_zone_item.append(item) %}
    {% endif %}
{% endfor %}
{% set cp_zone_item = cp_zone_item[0]|default(None) %}

{% if cp_zone_item != None %}
    {% if cp_zone_item.servername|default("") != "" %}
      {% do cp_zone_item.update({'interface_hostaddr':cp_zone_item.servername}) %}
    {% endif %}

    {# generate zone redirect address #}
    {% if cp_zone_item.certificate|default("") != "" %}
      # ssl enabled, redirect to https
      {% do cp_zone_item.update({'redirect_host':'https://'+cp_zone_item.interface_hostaddr + ':'  ~ (cp_zone_item.zoneid|int + 8000) ~ '/index.html'}) %}
    {% else %}
      # ssl disabled, redirect to http
      {% do cp_zone_item.update({'redirect_host':'http://'+cp_zone_item.interface_hostaddr + ':'  ~ (cp_zone_item.zoneid|int + 8000) ~ '/index.html'}) %}
    {% endif %}
    {% do cp_zone_item.update({'redirect_host_match':cp_zone_item.interface_hostaddr.replace('.','\.') ~ ':' ~ (cp_zone_item.zoneid|int + 8000) }) %}


#############################################################################################
###  Captive portal zone {{ cp_zone_item.zoneid  }} lighttpd.conf  BEGIN
###  -- listen on port {{ cp_zone_item.zoneid|int + 8000  }} for primary (ssl) connections
###  -- forward on port {{ cp_zone_item.zoneid|int + 9000  }} for plain http redirection
#############################################################################################
#
#### modules to load
server.modules           = ( "mod_expire",
                             "mod_auth",
                             "mod_redirect",
                             "mod_access",
                             "mod_evasive",
                             "mod_compress",
                             "mod_status",
                             "mod_rewrite",
                             "mod_proxy",
                             "mod_setenv",
                             "mod_extforward"
                            )

#### performance options (aggressive timeouts)
server.max-keep-alive-requests = 6
server.max-keep-alive-idle = 15
server.max-read-idle     = 15
server.max-write-idle    = 15

## number of child worker processes to spawn (0 for lightly loaded sites)
# server.max-worker      = 0

## number of file descriptors (leave off for lighty loaded sites)
# server.max-fds         = 512

## maximum concurrent connections the server will accept (1/2 of server.max-fds)
# server.max-connections = 256

## single client connection bandwidth limit in kilobytes (0=unlimited)
connection.kbytes-per-second = 0

## global server bandwidth limit in kilobytes (0=unlimited)
server.kbytes-per-second = 0

#### bind to interface (default: all interfaces)
server.bind              = "0.0.0.0"

#### bind to port
server.port              = {{ cp_zone_item.zoneid|int + 8000  }}

##
$HTTP["host"] !~ "(.*{{cp_zone_item.redirect_host_match}}.*)" {
	$HTTP["host"] =~ "([^:/]+)" {
		url.redirect = ( "^(.*)$" => "{{cp_zone_item.redirect_host}}?redirurl=%1$1")
	}
}

## redirect http traffic to http(s) main target
$SERVER["socket"] == ":{{ cp_zone_item.zoneid|int + 9000 }}" {
	$HTTP["host"] =~ "([^:/]+)" {
		url.redirect = ( "^(.*)$" => "{{cp_zone_item.redirect_host}}?redirurl=%1$1")
	}
}
$SERVER["socket"] == "[::]:{{ cp_zone_item.zoneid|int + 9000 }}" {
	$HTTP["host"] =~ "([^:/]+)" {
		url.redirect = ( "(.*)" => "{{cp_zone_item.redirect_host}}?redirurl=%1$1")
	}
}

proxy.server = ( "/api/captiveportal/access/" => (
		( "host" => "127.0.0.1",
		  "port" => 8999 )
	)
)
extforward.headers = ("X-Real-Ip")
server.upload-dirs = ( "/tmp/" )
setenv.add-response-header = ( "Cache-Control" => "no-store, no-cache, must-revalidate, post-check=0, pre-check=0" )
etag.use-inode = "disable"
etag.use-mtime = "disable"
etag.use-size = "disable"


#### run daemon as uid (default: don't care)
server.username          = "www"

#### run daemon as gid (default: don't care)
server.groupname         = "www"

#### set the pid file (newsyslog)
server.pid-file          = "/var/run/lighttpd-cp-zone-{{cp_zone_item.zoneid}}.pid"

#### errors to syslog
server.errorlog-use-syslog="enable"

#### name the server daemon publicly displays
server.tag               = "lighttpd"

#### static document-root
server.document-root     = "/htdocs/"

#### chroot() to captive portal zone directory
server.chroot            = "/var/captiveportal/zone{{cp_zone_item.zoneid}}"

#### files to check for if .../ is requested
index-file.names         = ( "index.html" )

#### disable auto index directory listings
dir-listing.activate     = "disable"

##
## ssl configuration
##
{% if cp_zone_item.certificate|default("") != "" %}
ssl.engine = "enable"
ssl.pemfile = "/var/etc/cert-cp-zone{{cp_zone_item.zoneid}}.pem"
{# set ca-file if ca is provided #}
{% for certItem in helpers.toList('cert') %}
{%    if certItem.refid == cp_zone_item.certificate and certItem.caref %}
ssl.ca-file = "/var/etc/ca-cp-zone{{cp_zone_item.zoneid}}.pem"
{%    endif %}
{% endfor %}

ssl.use-sslv2 = "disable"
ssl.use-sslv3 = "disable"
ssl.cipher-list = "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA"
{% else %}
ssl.engine               = "disable"
{% endif %}

#### compress module
compress.cache-dir       = "/tmp/"
compress.filetype        = ("text/plain", "text/html", "text/css", "image/png")

#### expire module
expire.url               = ( "" => "access plus 6 hours")

#### error pages
server.errorfile-prefix  = "/htdocs/errors/errorcode-"

#### mod_evasive
evasive.max-conns-per-ip = 250

#### limit request method "POST" size in kilobytes (KB)
server.max-request-size    = 2

#### disable multi range requests
server.range-requests    = "disable"

#### disable symlinks
server.follow-symlink    = "disable"

#### ONLY serve files with all lowercase file names
server.force-lowercase-filenames = "disable"

#### mimetype mapping
mimetype.assign             = (
  ".pdf"          =>      "application/pdf",
  ".sig"          =>      "application/pgp-signature",
  ".spl"          =>      "application/futuresplash",
  ".class"        =>      "application/octet-stream",
  ".ps"           =>      "application/postscript",
  ".torrent"      =>      "application/x-bittorrent",
  ".dvi"          =>      "application/x-dvi",
  ".gz"           =>      "application/x-gzip",
  ".pac"          =>      "application/x-ns-proxy-autoconfig",
  ".swf"          =>      "application/x-shockwave-flash",
  ".tar.gz"       =>      "application/x-tgz",
  ".tgz"          =>      "application/x-tgz",
  ".tar"          =>      "application/x-tar",
  ".zip"          =>      "application/zip",
  ".mp3"          =>      "audio/mpeg",
  ".m3u"          =>      "audio/x-mpegurl",
  ".wma"          =>      "audio/x-ms-wma",
  ".wax"          =>      "audio/x-ms-wax",
  ".ogg"          =>      "application/ogg",
  ".wav"          =>      "audio/x-wav",
  ".gif"          =>      "image/gif",
  ".jpg"          =>      "image/jpeg",
  ".jpeg"         =>      "image/jpeg",
  ".png"          =>      "image/png",
  ".xbm"          =>      "image/x-xbitmap",
  ".xpm"          =>      "image/x-xpixmap",
  ".xwd"          =>      "image/x-xwindowdump",
  ".css"          =>      "text/css",
  ".html"         =>      "text/html",
  ".htm"          =>      "text/html",
  ".js"           =>      "text/javascript",
  ".asc"          =>      "text/plain",
  ".c"            =>      "text/plain",
  ".cpp"          =>      "text/plain",
  ".log"          =>      "text/plain",
  ".conf"         =>      "text/plain",
  ".text"         =>      "text/plain",
  ".txt"          =>      "text/plain",
  ".dtd"          =>      "text/xml",
  ".xml"          =>      "text/xml",
  ".mpeg"         =>      "video/mpeg",
  ".mpg"          =>      "video/mpeg",
  ".mov"          =>      "video/quicktime",
  ".qt"           =>      "video/quicktime",
  ".avi"          =>      "video/x-msvideo",
  ".asf"          =>      "video/x-ms-asf",
  ".asx"          =>      "video/x-ms-asf",
  ".wmv"          =>      "video/x-ms-wmv",
  ".bz2"          =>      "application/x-bzip",
  ".tbz"          =>      "application/x-bzip-compressed-tar",
  ".tar.bz2"      =>      "application/x-bzip-compressed-tar"
 )
#
#######################################################
###  Captive Portal lighttpd.conf  END
#######################################################
{% endif %}