{# 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.items() %}
                {% if conf_key == intf_tag and conf_inf.ipaddr 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 not cp_zone_item.interface_hostaddr %}
      # interface address not found    {% elif 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 %}
    {% if cp_zone_item.interface_hostaddr %}
      {% do cp_zone_item.update({'redirect_host_match':cp_zone_item.interface_hostaddr.replace('.','\.') ~ ':' ~ (cp_zone_item.zoneid|int + 8000) }) %}
    {% endif %}

#############################################################################################
###  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_deflate",
                             "mod_status",
                             "mod_rewrite",
                             "mod_proxy",
                             "mod_setenv",
                             "mod_extforward",
                             "mod_openssl",
                            )

#### 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  }}

## Redirect response code to use
url.redirect-code        = 302

##
$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")
	}
	ssl.engine = "disable"
}
$SERVER["socket"] == "[::]:{{ cp_zone_item.zoneid|int + 9000 }}" {
	$HTTP["host"] =~ "([^:/]+)" {
		url.redirect = ( "(.*)" => "{{cp_zone_item.redirect_host}}?redirurl=%1$1")
	}
	ssl.engine = "disable"
}

setenv.set-request-header = ("zoneid" => "{{cp_zone_item.zoneid}}")
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               = "OPNsense"

#### 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.openssl.ssl-conf-cmd = (
    "MinProtocol" => "TLSv1.2",
    "Options" => "-ServerPreference",
    "CipherString" => "EECDH+AESGCM:AES256+EECDH:CHACHA20:!SHA1:!SHA256:!SHA384"
)
{% else %}
ssl.engine = "disable"
{% endif %}

#### compress module
deflate.cache-dir        = "/tmp/"
deflate.mimetypes        = ("text/plain", "text/html", "text/css", "image/png", "image/svg+xml")

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

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

#### 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",
  ".svg"          =>      "image/svg+xml",
  ".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 %}
