diff --git a/docker/nginx/conf.d/include/location-skylink b/docker/nginx/conf.d/include/location-skylink index 5aa93666..91284d7d 100644 --- a/docker/nginx/conf.d/include/location-skylink +++ b/docker/nginx/conf.d/include/location-skylink @@ -1,5 +1,61 @@ include /etc/nginx/conf.d/include/cors; -# include /etc/nginx/conf.d/include/proxy-buffer; +include /etc/nginx/conf.d/include/proxy-buffer; +include /etc/nginx/conf.d/include/track-download; +limit_conn downloads_by_ip 100; # ddos protection: max 100 downloads at a time + +# ensure that skylink that we pass around is base64 encoded (transform base32 encoded ones) +# this is important because we want only one format in cache keys and logs +set_by_lua_block $skylink { return require("skynet.skylink").base64(ngx.var.skylink) } + +# $skylink_v1 and $skylink_v2 variables default to the same value but in case the requested skylink was: +# a) skylink v1 - it would not matter, no additional logic is executed +# b) skylink v2 - in a lua block below we will resolve the skylink v2 into skylink v1 and update +# $skylink_v1 variable so then the proxy request to skyd can be cached in nginx (proxy_cache_key +# in proxy-cache-downloads includes $skylink_v1 as a part of the cache key) +set $skylink_v1 $skylink; +set $skylink_v2 $skylink; + +# variable for Skynet-Proof header that we need to inject +# into a response if the request was for skylink v2 +set $skynet_proof ''; + +# default download rate to unlimited +set $limit_rate 0; + +access_by_lua_block { + if require("skynet.account").accounts_enabled() then + -- check if portal is in authenticated only mode + if require("skynet.account").is_access_unauthorized() then + return require("skynet.account").exit_access_unauthorized() + end + + -- check if portal is in subscription only mode + if require("skynet.account").is_access_forbidden() then + return require("skynet.account").exit_access_forbidden() + end + + -- get account limits of currently authenticated user + local limits = require("skynet.account").get_account_limits() + + -- apply download speed limit + ngx.var.limit_rate = limits.download + end +} + +header_filter_by_lua_block { + ngx.header["Skynet-Portal-Api"] = ngx.var.scheme .. "://" .. ngx.var.skynet_portal_domain + ngx.header["Skynet-Server-Api"] = ngx.var.scheme .. "://" .. ngx.var.skynet_server_domain +} + +limit_rate_after 512k; +limit_rate $limit_rate; + +proxy_read_timeout 600; proxy_set_header User-Agent: Sia-Agent; -proxy_pass http://sia:9980/skynet/skylink/$skylink$path$is_args$args; + +# in case the requested skylink was v2 and we already resolved it to skylink v1, we are going to pass resolved +# skylink v1 to skyd to save that extra skylink v2 lookup in skyd but in turn, in case skyd returns a redirect +# we need to rewrite the skylink v1 to skylink v2 in the location header with proxy_redirect +proxy_redirect $skylink_v1 $skylink_v2; +proxy_pass http://sia:9980/skynet/skylink/$skylink_v1$path$is_args$args;