diff --git a/CHANGES b/CHANGES index 8e7382b4..1236a2ad 100644 --- a/CHANGES +++ b/CHANGES @@ -1,14 +1,445 @@ -Changes with nginx 1.16.1 13 Aug 2019 +Changes with nginx 1.21.0 25 May 2021 + + *) Security: 1-byte memory overwrite might occur during DNS server + response processing if the "resolver" directive was used, allowing an + attacker who is able to forge UDP packets from the DNS server to + cause worker process crash or, potentially, arbitrary code execution + (CVE-2021-23017). + + *) Feature: variables support in the "proxy_ssl_certificate", + "proxy_ssl_certificate_key" "grpc_ssl_certificate", + "grpc_ssl_certificate_key", "uwsgi_ssl_certificate", and + "uwsgi_ssl_certificate_key" directives. + + *) Feature: the "max_errors" directive in the mail proxy module. + + *) Feature: the mail proxy module supports POP3 and IMAP pipelining. + + *) Feature: the "fastopen" parameter of the "listen" directive in the + stream module. + Thanks to Anbang Wen. + + *) Bugfix: special characters were not escaped during automatic redirect + with appended trailing slash. + + *) Bugfix: connections with clients in the mail proxy module might be + closed unexpectedly when using SMTP pipelining. + + +Changes with nginx 1.19.10 13 Apr 2021 + + *) Change: the default value of the "keepalive_requests" directive was + changed to 1000. + + *) Feature: the "keepalive_time" directive. + + *) Feature: the $connection_time variable. + + *) Workaround: "gzip filter failed to use preallocated memory" alerts + appeared in logs when using zlib-ng. + + +Changes with nginx 1.19.9 30 Mar 2021 + + *) Bugfix: nginx could not be built with the mail proxy module, but + without the ngx_mail_ssl_module; the bug had appeared in 1.19.8. + + *) Bugfix: "upstream sent response body larger than indicated content + length" errors might occur when working with gRPC backends; the bug + had appeared in 1.19.1. + + *) Bugfix: nginx might not close a connection till keepalive timeout + expiration if the connection was closed by the client while + discarding the request body. + + *) Bugfix: nginx might not detect that a connection was already closed + by the client when waiting for auth_delay or limit_req delay, or when + working with backends. + + *) Bugfix: in the eventport method. + + +Changes with nginx 1.19.8 09 Mar 2021 + + *) Feature: flags in the "proxy_cookie_flags" directive can now contain + variables. + + *) Feature: the "proxy_protocol" parameter of the "listen" directive, + the "proxy_protocol" and "set_real_ip_from" directives in mail proxy. + + *) Bugfix: HTTP/2 connections were immediately closed when using + "keepalive_timeout 0"; the bug had appeared in 1.19.7. + + *) Bugfix: some errors were logged as unknown if nginx was built with + glibc 2.32. + + *) Bugfix: in the eventport method. + + +Changes with nginx 1.19.7 16 Feb 2021 + + *) Change: connections handling in HTTP/2 has been changed to better + match HTTP/1.x; the "http2_recv_timeout", "http2_idle_timeout", and + "http2_max_requests" directives have been removed, the + "keepalive_timeout" and "keepalive_requests" directives should be + used instead. + + *) Change: the "http2_max_field_size" and "http2_max_header_size" + directives have been removed, the "large_client_header_buffers" + directive should be used instead. + + *) Feature: now, if free worker connections are exhausted, nginx starts + closing not only keepalive connections, but also connections in + lingering close. + + *) Bugfix: "zero size buf in output" alerts might appear in logs if an + upstream server returned an incorrect response during unbuffered + proxying; the bug had appeared in 1.19.1. + + *) Bugfix: HEAD requests were handled incorrectly if the "return" + directive was used with the "image_filter" or "xslt_stylesheet" + directives. + + *) Bugfix: in the "add_trailer" directive. + + +Changes with nginx 1.19.6 15 Dec 2020 + + *) Bugfix: "no live upstreams" errors if a "server" inside "upstream" + block was marked as "down". + + *) Bugfix: a segmentation fault might occur in a worker process if HTTPS + was used; the bug had appeared in 1.19.5. + + *) Bugfix: nginx returned the 400 response on requests like + "GET http://example.com?args HTTP/1.0". + + *) Bugfix: in the ngx_http_flv_module and ngx_http_mp4_module. + Thanks to Chris Newton. + + +Changes with nginx 1.19.5 24 Nov 2020 + + *) Feature: the -e switch. + + *) Feature: the same source files can now be specified in different + modules while building addon modules. + + *) Bugfix: SSL shutdown did not work when lingering close was used. + + *) Bugfix: "upstream sent frame for closed stream" errors might occur + when working with gRPC backends. + + *) Bugfix: in request body filters internal API. + + +Changes with nginx 1.19.4 27 Oct 2020 + + *) Feature: the "ssl_conf_command", "proxy_ssl_conf_command", + "grpc_ssl_conf_command", and "uwsgi_ssl_conf_command" directives. + + *) Feature: the "ssl_reject_handshake" directive. + + *) Feature: the "proxy_smtp_auth" directive in mail proxy. + + +Changes with nginx 1.19.3 29 Sep 2020 + + *) Feature: the ngx_stream_set_module. + + *) Feature: the "proxy_cookie_flags" directive. + + *) Feature: the "userid_flags" directive. + + *) Bugfix: the "stale-if-error" cache control extension was erroneously + applied if backend returned a response with status code 500, 502, + 503, 504, 403, 404, or 429. + + *) Bugfix: "[crit] cache file ... has too long header" messages might + appear in logs if caching was used and the backend returned responses + with the "Vary" header line. + + *) Workaround: "[crit] SSL_write() failed" messages might appear in logs + when using OpenSSL 1.1.1. + + *) Bugfix: "SSL_shutdown() failed (SSL: ... bad write retry)" messages + might appear in logs; the bug had appeared in 1.19.2. + + *) Bugfix: a segmentation fault might occur in a worker process when + using HTTP/2 if errors with code 400 were redirected to a proxied + location using the "error_page" directive. + + *) Bugfix: socket leak when using HTTP/2 and subrequests in the njs + module. + + +Changes with nginx 1.19.2 11 Aug 2020 + + *) Change: now nginx starts closing keepalive connections before all + free worker connections are exhausted, and logs a warning about this + to the error log. + + *) Change: optimization of client request body reading when using + chunked transfer encoding. + + *) Bugfix: memory leak if the "ssl_ocsp" directive was used. + + *) Bugfix: "zero size buf in output" alerts might appear in logs if a + FastCGI server returned an incorrect response; the bug had appeared + in 1.19.1. + + *) Bugfix: a segmentation fault might occur in a worker process if + different large_client_header_buffers sizes were used in different + virtual servers. + + *) Bugfix: SSL shutdown might not work. + + *) Bugfix: "SSL_shutdown() failed (SSL: ... bad write retry)" messages + might appear in logs. + + *) Bugfix: in the ngx_http_slice_module. + + *) Bugfix: in the ngx_http_xslt_filter_module. + + +Changes with nginx 1.19.1 07 Jul 2020 + + *) Change: the "lingering_close", "lingering_time", and + "lingering_timeout" directives now work when using HTTP/2. + + *) Change: now extra data sent by a backend are always discarded. + + *) Change: now after receiving a too short response from a FastCGI + server nginx tries to send the available part of the response to the + client, and then closes the client connection. + + *) Change: now after receiving a response with incorrect length from a + gRPC backend nginx stops response processing with an error. + + *) Feature: the "min_free" parameter of the "proxy_cache_path", + "fastcgi_cache_path", "scgi_cache_path", and "uwsgi_cache_path" + directives. + Thanks to Adam Bambuch. + + *) Bugfix: nginx did not delete unix domain listen sockets during + graceful shutdown on the SIGQUIT signal. + + *) Bugfix: zero length UDP datagrams were not proxied. + + *) Bugfix: proxying to uwsgi backends using SSL might not work. + Thanks to Guanzhong Chen. + + *) Bugfix: in error handling when using the "ssl_ocsp" directive. + + *) Bugfix: on XFS and NFS file systems disk cache size might be + calculated incorrectly. + + *) Bugfix: "negative size buf in writer" alerts might appear in logs if + a memcached server returned a malformed response. + + +Changes with nginx 1.19.0 26 May 2020 + + *) Feature: client certificate validation with OCSP. + + *) Bugfix: "upstream sent frame for closed stream" errors might occur + when working with gRPC backends. + + *) Bugfix: OCSP stapling might not work if the "resolver" directive was + not specified. + + *) Bugfix: connections with incorrect HTTP/2 preface were not logged. + + +Changes with nginx 1.17.10 14 Apr 2020 + + *) Feature: the "auth_delay" directive. + + +Changes with nginx 1.17.9 03 Mar 2020 + + *) Change: now nginx does not allow several "Host" request header lines. + + *) Bugfix: nginx ignored additional "Transfer-Encoding" request header + lines. + + *) Bugfix: socket leak when using HTTP/2. + + *) Bugfix: a segmentation fault might occur in a worker process if OCSP + stapling was used. + + *) Bugfix: in the ngx_http_mp4_module. + + *) Bugfix: nginx used status code 494 instead of 400 if errors with code + 494 were redirected with the "error_page" directive. + + *) Bugfix: socket leak when using subrequests in the njs module and the + "aio" directive. + + +Changes with nginx 1.17.8 21 Jan 2020 + + *) Feature: variables support in the "grpc_pass" directive. + + *) Bugfix: a timeout might occur while handling pipelined requests in an + SSL connection; the bug had appeared in 1.17.5. + + *) Bugfix: in the "debug_points" directive when using HTTP/2. + Thanks to Daniil Bondarev. + + +Changes with nginx 1.17.7 24 Dec 2019 + + *) Bugfix: a segmentation fault might occur on start or during + reconfiguration if the "rewrite" directive with an empty replacement + string was used in the configuration. + + *) Bugfix: a segmentation fault might occur in a worker process if the + "break" directive was used with the "alias" directive or with the + "proxy_pass" directive with a URI. + + *) Bugfix: the "Location" response header line might contain garbage if + the request URI was rewritten to the one containing a null character. + + *) Bugfix: requests with bodies were handled incorrectly when returning + redirections with the "error_page" directive; the bug had appeared in + 0.7.12. + + *) Bugfix: socket leak when using HTTP/2. + + *) Bugfix: a timeout might occur while handling pipelined requests in an + SSL connection; the bug had appeared in 1.17.5. + + *) Bugfix: in the ngx_http_dav_module. + + +Changes with nginx 1.17.6 19 Nov 2019 + + *) Feature: the $proxy_protocol_server_addr and + $proxy_protocol_server_port variables. + + *) Feature: the "limit_conn_dry_run" directive. + + *) Feature: the $limit_req_status and $limit_conn_status variables. + + +Changes with nginx 1.17.5 22 Oct 2019 + + *) Feature: now nginx uses ioctl(FIONREAD), if available, to avoid + reading from a fast connection for a long time. + + *) Bugfix: incomplete escaped characters at the end of the request URI + were ignored. + + *) Bugfix: "/." and "/.." at the end of the request URI were not + normalized. + + *) Bugfix: in the "merge_slashes" directive. + + *) Bugfix: in the "ignore_invalid_headers" directive. + Thanks to Alan Kemp. + + *) Bugfix: nginx could not be built with MinGW-w64 gcc 8.1 or newer. + + +Changes with nginx 1.17.4 24 Sep 2019 + + *) Change: better detection of incorrect client behavior in HTTP/2. + + *) Change: in handling of not fully read client request body when + returning errors in HTTP/2. + + *) Bugfix: the "worker_shutdown_timeout" directive might not work when + using HTTP/2. + + *) Bugfix: a segmentation fault might occur in a worker process when + using HTTP/2 and the "proxy_request_buffering" directive. + + *) Bugfix: the ECONNABORTED error log level was "crit" instead of + "error" on Windows when using SSL. + + *) Bugfix: nginx ignored extra data when using chunked transfer + encoding. + + *) Bugfix: nginx always returned the 500 error if the "return" directive + was used and an error occurred during reading client request body. + + *) Bugfix: in memory allocation error handling. + + +Changes with nginx 1.17.3 13 Aug 2019 *) Security: when using HTTP/2 a client might cause excessive memory consumption and CPU usage (CVE-2019-9511, CVE-2019-9513, CVE-2019-9516). + *) Bugfix: "zero size buf" alerts might appear in logs when using + gzipping; the bug had appeared in 1.17.2. + + *) Bugfix: a segmentation fault might occur in a worker process if the + "resolver" directive was used in SMTP proxy. + + +Changes with nginx 1.17.2 23 Jul 2019 + + *) Change: minimum supported zlib version is 1.2.0.4. + Thanks to Ilya Leoshkevich. -Changes with nginx 1.16.0 23 Apr 2019 + *) Change: the $r->internal_redirect() embedded perl method now expects + escaped URIs. + + *) Feature: it is now possible to switch to a named location using the + $r->internal_redirect() embedded perl method. + + *) Bugfix: in error handling in embedded perl. + + *) Bugfix: a segmentation fault might occur on start or during + reconfiguration if hash bucket size larger than 64 kilobytes was used + in the configuration. + + *) Bugfix: nginx might hog CPU during unbuffered proxying and when + proxying WebSocket connections if the select, poll, or /dev/poll + methods were used. + + *) Bugfix: in the ngx_http_xslt_filter_module. + + *) Bugfix: in the ngx_http_ssi_filter_module. + + +Changes with nginx 1.17.1 25 Jun 2019 + + *) Feature: the "limit_req_dry_run" directive. + + *) Feature: when using the "hash" directive inside the "upstream" block + an empty hash key now triggers round-robin balancing. + Thanks to Niklas Keller. + + *) Bugfix: a segmentation fault might occur in a worker process if + caching was used along with the "image_filter" directive, and errors + with code 415 were redirected with the "error_page" directive; the + bug had appeared in 1.11.10. + + *) Bugfix: a segmentation fault might occur in a worker process if + embedded perl was used; the bug had appeared in 1.7.3. + + +Changes with nginx 1.17.0 21 May 2019 + + *) Feature: variables support in the "limit_rate" and "limit_rate_after" + directives. + + *) Feature: variables support in the "proxy_upload_rate" and + "proxy_download_rate" directives in the stream module. + + *) Change: minimum supported OpenSSL version is 0.9.8. + + *) Change: now the postpone filter is always built. + + *) Bugfix: the "include" directive did not work inside the "if" and + "limit_except" blocks. - *) 1.16.x stable branch. + *) Bugfix: in byte ranges processing. Changes with nginx 1.15.12 16 Apr 2019 diff --git a/CHANGES.ru b/CHANGES.ru index 5d60f417..224aa048 100644 --- a/CHANGES.ru +++ b/CHANGES.ru @@ -1,14 +1,473 @@ -Изменения в nginx 1.16.1 13.08.2019 +<<<<<<< HEAD +Изменения в nginx 1.21.0 25.05.2021 + + *) Безопасность: при использовании директивы resolver во время обработки + ответа DNS-сервера могла происходить перезапись одного байта памяти, + что позволяло атакующему, имеющему возможность подделывать UDP-пакеты + от DNS-сервера, вызвать падение рабочего процесса или, потенциально, + выполнение произвольного кода (CVE-2021-23017). + + *) Добавление: директивы proxy_ssl_certificate, + proxy_ssl_certificate_key, grpc_ssl_certificate, + grpc_ssl_certificate_key, uwsgi_ssl_certificate и + uwsgi_ssl_certificate_key поддерживают переменные. + + *) Добавление: директива max_errors в почтовом прокси-сервере. + + *) Добавление: почтовый прокси-сервер поддерживает POP3 и IMAP + pipelining. + + *) Добавление: параметр fastopen директивы listen в модуле stream. + Спасибо Anbang Wen. + + *) Исправление: специальные символы не экранировались при автоматическом + перенаправлении с добавлением завершающего слэша. + + *) Исправление: при использовании SMTP pipelining соединения с клиентами + в почтовом прокси-сервере могли неожиданно закрываться. + + +Изменения в nginx 1.19.10 13.04.2021 + + *) Изменение: в директиве keepalive_requests значение по умолчанию + изменено на 1000. + + *) Добавление: директива keepalive_time. + + *) Добавление: переменная $connection_time. + + *) Изменение: при использовании zlib-ng в логах появлялись сообщения + "gzip filter failed to use preallocated memory". + + +Изменения в nginx 1.19.9 30.03.2021 + + *) Исправление: nginx не собирался с почтовым прокси-сервером, но без + модуля ngx_mail_ssl_module; ошибка появилась в 1.19.8. + + *) Исправление: при работе с gRPC-бэкендами могли возникать ошибки + "upstream sent response body larger than indicated content length"; + ошибка появилась в 1.19.1. + + *) Исправление: если клиент закрывал соединение в момент отбрасывания + тела запроса, nginx мог не закрыть соединение до истечения + keepalive-таймаута. + + *) Исправление: при ожидании задержки limit_req или auth_delay, а также + при работе с бэкендами nginx мог не обнаружить, что соединение уже + закрыто клиентом. + + *) Исправление: в методе обработки соединений eventport. + + +Изменения в nginx 1.19.8 09.03.2021 + + *) Добавление: в директиве proxy_cookie_flags теперь флаги можно + задавать с помощью переменных. + + *) Добавление: параметр proxy_protocol в директиве listen, директивы + proxy_protocol и set_real_ip_from в почтовом прокси-сервере. + + *) Исправление: HTTP/2-соединения сразу закрывались при использовании + "keepalive_timeout 0"; ошибка появилась в 1.19.7. + + *) Исправление: некоторые ошибки логгировались как неизвестные, если + nginx был собран с glibc 2.32. + + *) Исправление: в методе обработки соединений eventport. + + +Изменения в nginx 1.19.7 16.02.2021 + + *) Изменение: обработка соединений в HTTP/2 была изменена и теперь более + соответствует HTTP/1.x; директивы http2_recv_timeout, + http2_idle_timeout и http2_max_requests упразднены, вместо них + следует использовать директивы keepalive_timeout и + keepalive_requests. + + *) Изменение: директивы http2_max_field_size и http2_max_header_size + упразднены, вместо них следует использовать директиву + large_client_header_buffers. + + *) Добавление: теперь при исчерпании свободных соединений nginx + закрывает не только keepalive-соединения, но и соединения в lingering + close. + + *) Исправление: в логах могли появляться сообщения "zero size buf in + output", если бэкенд возвращал некорректный ответ при + небуферизированном проксировании; ошибка появилась в 1.19.1. + + *) Исправление: при использовании директивы return вместе с image_filter + или xslt_stylesheet HEAD-запросы обрабатывались некорректно. + + *) Исправление: в директиве add_trailer. + + +Изменения в nginx 1.19.6 15.12.2020 + + *) Исправление: ошибки "no live upstreams", если server в блоке upstream + был помечен как down. + + *) Исправление: при использовании HTTPS в рабочем процессе мог произойти + segmentation fault; ошибка появилась в 1.19.5. + + *) Исправление: nginx возвращал ошибку 400 на запросы вида + "GET http://example.com?args HTTP/1.0". + + *) Исправление: в модулях ngx_http_flv_module и ngx_http_mp4_module. + Спасибо Chris Newton. + + +Изменения в nginx 1.19.5 24.11.2020 + + *) Добавление: ключ -e. + + *) Добавление: при сборке дополнительных модулей теперь можно указывать + одни и те же исходные файлы в разных модулях. + + *) Исправление: SSL shutdown не работал при закрытии соединений с + ожиданием дополнительных данных (lingering close). + + *) Исправление: при работе с gRPC-бэкендами могли возникать ошибки + "upstream sent frame for closed stream". + + *) Исправление: во внутреннем API для обработки тела запроса. + + +Изменения в nginx 1.19.4 27.10.2020 + + *) Добавление: директивы ssl_conf_command, proxy_ssl_conf_command, + grpc_ssl_conf_command и uwsgi_ssl_conf_command. + + *) Добавление: директива ssl_reject_handshake. + + *) Добавление: директива proxy_smtp_auth в почтовом прокси-сервере. + + +Изменения в nginx 1.19.3 29.09.2020 + + *) Добавление: модуль ngx_stream_set_module. + + *) Добавление: директива proxy_cookie_flags. + + *) Добавление: директива userid_flags. + + *) Исправление: расширение управления кэшированием stale-if-error + ошибочно применялось, если бэкенд возвращал ответ с кодом 500, 502, + 503, 504, 403, 404 или 429. + + *) Исправление: если использовалось кэширование и бэкенд возвращал + ответы с строкой заголовка Vary, в логах могли появляться сообщения + "[crit] cache file ... has too long header". + + *) Изменение: при использовании OpenSSL 1.1.1 в логах могли появляться + сообщения "[crit] SSL_write() failed". + + *) Исправление: в логах могли появляться сообщения "SSL_shutdown() + failed (SSL: ... bad write retry)"; ошибка появилась в 1.19.2. + + *) Исправление: при использовании HTTP/2 в рабочем процессе мог + произойти segmentation fault, если ошибки с кодом 400 с помощью + директивы error_page перенаправлялись в проксируемый location. + + *) Исправление: утечки сокетов при использовании HTTP/2 и подзапросов в + модуле njs. + + +Изменения в nginx 1.19.2 11.08.2020 + + *) Изменение: теперь nginx начинает закрывать keepalive-соединения, не + дожидаясь исчерпания всех свободных соединений, а также пишет об этом + предупреждение в лог ошибок. + + *) Изменение: оптимизация чтения тела запроса при использовании chunked + transfer encoding. + + *) Исправление: утечки памяти при использовании директивы ssl_ocsp. + + *) Исправление: в логах могли появляться сообщения "zero size buf in + output", если FastCGI-сервер возвращал некорректный ответ; ошибка + появилась в 1.19.1. + + *) Исправление: в рабочем процессе мог произойти segmentation fault, + если размеры large_client_header_buffers отличались в разных + виртуальных серверах. + + *) Исправление: SSL shutdown мог не работать. + + *) Исправление: в логах могли появляться сообщения "SSL_shutdown() + failed (SSL: ... bad write retry)". + + *) Исправление: в модуле ngx_http_slice_module. + + *) Исправление: в модуле ngx_http_xslt_filter_module. + + +Изменения в nginx 1.19.1 07.07.2020 + + *) Изменение: директивы lingering_close, lingering_time и + lingering_timeout теперь работают при использовании HTTP/2. + + *) Изменение: теперь лишние данные, присланные бэкендом, всегда + отбрасываются. + + *) Изменение: теперь при получении слишком короткого ответа от + FastCGI-сервера nginx пытается отправить клиенту доступную часть + ответа, после чего закрывает соединение с клиентом. + + *) Изменение: теперь при получении ответа некорректной длины от + gRPC-бэкенда nginx прекращает обработку ответа с ошибкой. + + *) Добавление: параметр min_free в директивах proxy_cache_path, + fastcgi_cache_path, scgi_cache_path и uwsgi_cache_path. + Спасибо Adam Bambuch. + + *) Исправление: nginx не удалял unix domain listen-сокеты при плавном + завершении по сигналу SIGQUIT. + + *) Исправление: UDP-пакеты нулевого размера не проксировались. + + *) Исправление: проксирование на uwsgi-бэкенды с использованием SSL + могло не работать. + Спасибо Guanzhong Chen. + + *) Исправление: в обработке ошибок при использовании директивы ssl_ocsp. + + *) Исправление: при использовании файловых систем XFS и NFS размер кэша + на диске мог считаться некорректно. + + *) Исправление: если сервер memcached возвращал некорректный ответ, в + логах могли появляться сообщения "negative size buf in writer". + + +Изменения в nginx 1.19.0 26.05.2020 + + *) Добавление: проверка клиентских сертификатов с помощью OCSP. + + *) Исправление: при работе с gRPC-бэкендами могли возникать ошибки + "upstream sent frame for closed stream". + + *) Исправление: OCSP stapling мог не работать, если не была указана + директива resolver. + + *) Исправление: соединения с некорректным HTTP/2 preface не + логгировались. + + +Изменения в nginx 1.17.10 14.04.2020 + + *) Добавление: директива auth_delay. + + +Изменения в nginx 1.17.9 03.03.2020 + + *) Изменение: теперь nginx не разрешает несколько строк "Host" в + заголовке запроса. + + *) Исправление: nginx игнорировал дополнительные строки + "Transfer-Encoding" в заголовке запроса. + +======= +Изменения в nginx 1.18.0 21.04.2020 + + *) Стабильная ветка 1.18.x. + + +Изменения в nginx 1.17.10 14.04.2020 + + *) Добавление: директива auth_delay. + + +Изменения в nginx 1.17.9 03.03.2020 + + *) Изменение: теперь nginx не разрешает несколько строк "Host" в + заголовке запроса. + + *) Исправление: nginx игнорировал дополнительные строки + "Transfer-Encoding" в заголовке запроса. + +>>>>>>> debian/1.18.0-5 + *) Исправление: утечки сокетов при использовании HTTP/2. + + *) Исправление: в рабочем процессе мог произойти segmentation fault, + если использовался OCSP stapling. + + *) Исправление: в модуле ngx_http_mp4_module. + + *) Исправление: при перенаправлении ошибок с кодом 494 с помощью + директивы error_page nginx возвращал ответ с кодом 494 вместо 400. + + *) Исправление: утечки сокетов при использовании подзапросов в модуле + njs и директивы aio. + + +Изменения в nginx 1.17.8 21.01.2020 + + *) Добавление: директива grpc_pass поддерживает переменные. + + *) Исправление: при обработке pipelined-запросов по SSL-соединению мог + произойти таймаут; ошибка появилась в 1.17.5. + + *) Исправление: в директиве debug_points при использовании HTTP/2. + Спасибо Даниилу Бондареву. + + +Изменения в nginx 1.17.7 24.12.2019 + + *) Исправление: на старте или во время переконфигурации мог произойти + segmentation fault, если в конфигурации использовалась директива + rewrite с пустой строкой замены. + + *) Исправление: в рабочем процессе мог произойти segmentation fault, + если директива break использовалась совместно с директивой alias или + директивой proxy_pass с URI. + + *) Исправление: строка Location заголовка ответа могла содержать мусор, + если URI запроса был изменён на URI, содержащий нулевой символ. + + *) Исправление: при возврате перенаправлений с помощью директивы + error_page запросы с телом обрабатывались некорректно; ошибка + появилась в 0.7.12. + + *) Исправление: утечки сокетов при использовании HTTP/2. + + *) Исправление: при обработке pipelined-запросов по SSL-соединению мог + произойти таймаут; ошибка появилась в 1.17.5. + + *) Исправление: в модуле ngx_http_dav_module. + + +Изменения в nginx 1.17.6 19.11.2019 + + *) Добавление: переменные $proxy_protocol_server_addr и + $proxy_protocol_server_port. + + *) Добавление: директива limit_conn_dry_run. + + *) Добавление: переменные $limit_req_status и $limit_conn_status. + + +Изменения в nginx 1.17.5 22.10.2019 + + *) Добавление: теперь nginx использует вызов ioctl(FIONREAD), если он + доступен, чтобы избежать чтения из быстрого соединения в течение + долгого времени. + + *) Исправление: неполные закодированные символы в конце URI запроса + игнорировались. + + *) Исправление: "/." и "/.." в конце URI запроса не нормализовывались. + + *) Исправление: в директиве merge_slashes. + + *) Исправление: в директиве ignore_invalid_headers. + Спасибо Alan Kemp. + + *) Исправление: nginx не собирался с MinGW-w64 gcc 8.1 и новее. + + +Изменения в nginx 1.17.4 24.09.2019 + + *) Изменение: улучшено детектирование некорректного поведения клиентов в + HTTP/2. + + *) Изменение: в обработке непрочитанного тела запроса при возврате + ошибок в HTTP/2. + + *) Исправление: директива worker_shutdown_timeout могла не работать при + использовании HTTP/2. + + *) Исправление: при использовании HTTP/2 и директивы + proxy_request_buffering в рабочем процессе мог произойти segmentation + fault. + + *) Исправление: на Windows при использовании SSL уровень записи в лог + ошибки ECONNABORTED был "crit" вместо "error". + + *) Исправление: nginx игнорировал лишние данные при использовании + chunked transfer encoding. + + *) Исправление: если использовалась директива return и при чтении тела + запроса возникала ошибка, nginx всегда возвращал ошибку 500. + + *) Исправление: в обработке ошибок выделения памяти. + + +Изменения в nginx 1.17.3 13.08.2019 *) Безопасность: при использовании HTTP/2 клиент мог вызвать чрезмерное потребление памяти и ресурсов процессора (CVE-2019-9511, CVE-2019-9513, CVE-2019-9516). + *) Исправление: при использовании сжатия в логах могли появляться + сообщения "zero size buf"; ошибка появилась в 1.17.2. + + *) Исправление: при использовании директивы resolver в SMTP + прокси-сервере в рабочем процессе мог произойти segmentation fault. + + +Изменения в nginx 1.17.2 23.07.2019 + + *) Изменение: минимальная поддерживаемая версия zlib - 1.2.0.4. + Спасибо Илье Леошкевичу. + + *) Изменение: метод $r->internal_redirect() встроенного перла теперь + ожидает закодированный URI. + + *) Добавление: теперь с помощью метода $r->internal_redirect() + встроенного перла можно перейти в именованный location. + + *) Исправление: в обработке ошибок во встроенном перле. + + *) Исправление: на старте или во время переконфигурации мог произойти + segmentation fault, если в конфигурации использовалось значение hash + bucket size больше 64 килобайт. + + *) Исправление: при использовании методов обработки соединений select, + poll и /dev/poll nginx мог нагружать процессор во время + небуферизованного проксирования и при проксировании + WebSocket-соединений. + + *) Исправление: в модуле ngx_http_xslt_filter_module. + + *) Исправление: в модуле ngx_http_ssi_filter_module. + + +Изменения в nginx 1.17.1 25.06.2019 + + *) Добавление: директива limit_req_dry_run. -Изменения в nginx 1.16.0 23.04.2019 + *) Добавление: при использовании директивы hash в блоке upstream пустой + ключ хэширования теперь приводит к переключению на round-robin + балансировку. + Спасибо Niklas Keller. - *) Стабильная ветка 1.16.x. + *) Исправление: в рабочем процессе мог произойти segmentation fault, + если использовалось кэширование и директива image_filter, а ошибки с + кодом 415 перенаправлялись с помощью директивы error_page; ошибка + появилась в 1.11.10. + + *) Исправление: в рабочем процессе мог произойти segmentation fault, + если использовался встроенный перл; ошибка появилась в 1.7.3. + + +Изменения в nginx 1.17.0 21.05.2019 + + *) Добавление: директивы limit_rate и limit_rate_after поддерживают + переменные. + + *) Добавление: директивы proxy_upload_rate и proxy_download_rate в + модуле stream поддерживают переменные. + + *) Изменение: минимальная поддерживаемая версия OpenSSL - 0.9.8. + + *) Изменение: теперь postpone-фильтр собирается всегда. + + *) Исправление: директива include не работала в блоках if и + limit_except. + + *) Исправление: в обработке byte ranges. Изменения в nginx 1.15.12 16.04.2019 @@ -154,6 +613,60 @@ *) Изменение: уровень логгирования ошибок SSL "no suitable key share" и "no suitable signature algorithm" понижен с уровня crit до info. +<<<<<<< HEAD + + +Изменения в nginx 1.15.3 28.08.2018 + + *) Добавление: теперь TLSv1.3 можно использовать с BoringSSL. + + *) Добавление: директива ssl_early_data, сейчас доступна при + использовании BoringSSL. + + *) Добавление: директивы keepalive_timeout и keepalive_requests в блоке + upstream. + + *) Исправление: модуль ngx_http_dav_module при копировании файла поверх + существующего файла с помощью метода COPY не обнулял целевой файл. + + *) Исправление: модуль ngx_http_dav_module при перемещении файла между + файловыми системами с помощью метода MOVE устанавливал нулевые права + доступа на результирующий файл и не сохранял время изменения файла. + + *) Исправление: модуль ngx_http_dav_module при копировании файла с + помощью метода COPY для результирующего файла использовал права + доступа по умолчанию. + + *) Изменение: некоторые клиенты могли не работать при использовании + HTTP/2; ошибка появилась в 1.13.5. + + *) Исправление: nginx не собирался с LibreSSL 2.8.0. + + +Изменения в nginx 1.15.2 24.07.2018 + + *) Добавление: переменная $ssl_preread_protocol в модуле + ngx_stream_ssl_preread_module. + + *) Добавление: теперь при использовании директивы + reset_timedout_connection nginx сбрасывает соединения, закрываемые с + кодом 444. + + *) Изменение: уровень логгирования ошибок SSL "http request", "https + proxy request", "unsupported protocol" и "version too low" понижен с + уровня crit до info. + + *) Исправление: запросы к DNS-серверу не отправлялись повторно, если при + первой попытке отправки происходила ошибка. + + *) Исправление: параметр reuseport директивы listen игнорировался, если + количество рабочих процессов было задано после директивы listen. + + *) Исправление: при использовании OpenSSL 1.1.0 и новее директиву + ssl_prefer_server_ciphers нельзя было выключить в виртуальном + сервере, если она была включена в сервере по умолчанию. + +======= Изменения в nginx 1.15.3 28.08.2018 @@ -206,6 +719,7 @@ ssl_prefer_server_ciphers нельзя было выключить в виртуальном сервере, если она была включена в сервере по умолчанию. +>>>>>>> debian/1.18.0-5 *) Исправление: повторное использование SSL-сессий к бэкендам не работало с протоколом TLS 1.3. diff --git a/LICENSE b/LICENSE index c63e0ba4..b1c558b5 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,11 @@ /* +<<<<<<< HEAD + * Copyright (C) 2002-2021 Igor Sysoev + * Copyright (C) 2011-2021 Nginx, Inc. +======= * Copyright (C) 2002-2019 Igor Sysoev * Copyright (C) 2011-2019 Nginx, Inc. +>>>>>>> debian/1.18.0-5 * All rights reserved. * * Redistribution and use in source and binary forms, with or without diff --git a/auto/init b/auto/init index 910f5294..f816dfc4 100644 --- a/auto/init +++ b/auto/init @@ -48,4 +48,6 @@ default: build clean: rm -rf Makefile $NGX_OBJS + +.PHONY: default clean END diff --git a/auto/install b/auto/install index d884487a..c764fdd2 100644 --- a/auto/install +++ b/auto/install @@ -215,4 +215,6 @@ upgrade: test -f $NGX_PID_PATH.oldbin kill -QUIT \`cat $NGX_PID_PATH.oldbin\` + +.PHONY: build install modules upgrade END diff --git a/auto/make b/auto/make index 34c40cdd..ef7c9f69 100644 --- a/auto/make +++ b/auto/make @@ -313,7 +313,7 @@ $ngx_obj: \$(CORE_DEPS) \$(HTTP_DEPS)$ngx_cont$ngx_src END fi - done + done fi @@ -343,7 +343,7 @@ $ngx_obj: \$(CORE_DEPS) \$(MAIL_DEPS)$ngx_cont$ngx_src $ngx_cc$ngx_tab$ngx_objout$ngx_obj$ngx_tab$ngx_src$NGX_AUX END - done + done fi @@ -373,7 +373,7 @@ $ngx_obj: \$(CORE_DEPS) \$(STREAM_DEPS)$ngx_cont$ngx_src $ngx_cc$ngx_tab$ngx_objout$ngx_obj$ngx_tab$ngx_src$NGX_AUX END - done + done fi @@ -399,7 +399,7 @@ $ngx_obj: \$(CORE_DEPS) $ngx_cont$ngx_src $ngx_cc$ngx_tab$ngx_objout$ngx_obj$ngx_tab$ngx_src$NGX_AUX END - done + done fi @@ -431,7 +431,7 @@ $ngx_obj: \$(ADDON_DEPS)$ngx_cont$ngx_src $ngx_cc$ngx_tab$ngx_objout$ngx_obj$ngx_tab$ngx_src$NGX_AUX END - done + done fi @@ -502,6 +502,7 @@ fi for ngx_module in $DYNAMIC_MODULES do eval ngx_module_srcs="\$${ngx_module}_SRCS" + eval ngx_module_shrd="\$${ngx_module}_SHRD" eval eval ngx_module_libs="\\\"\$${ngx_module}_LIBS\\\"" eval ngx_module_modules="\$${ngx_module}_MODULES" @@ -567,7 +568,7 @@ END | sed -e "s/\(.*\.\)c/\1$ngx_objext/"` ngx_module_objs= - for ngx_src in $ngx_module_srcs + for ngx_src in $ngx_module_srcs $ngx_module_shrd do case "$ngx_src" in src/*) diff --git a/auto/module b/auto/module index a2b578db..3857d04c 100644 --- a/auto/module +++ b/auto/module @@ -17,7 +17,6 @@ if [ "$ngx_module_link" = DYNAMIC ]; then done DYNAMIC_MODULES="$DYNAMIC_MODULES $ngx_module" - eval ${ngx_module}_SRCS=\"$ngx_module_srcs\" eval ${ngx_module}_MODULES=\"$ngx_module_name\" @@ -31,6 +30,30 @@ if [ "$ngx_module_link" = DYNAMIC ]; then eval ${ngx_module}_ORDER=\"$ngx_module_order\" fi + srcs= + shrd= + for src in $ngx_module_srcs + do + found=no + for old in $DYNAMIC_MODULES_SRCS + do + if [ $src = $old ]; then + found=yes + break + fi + done + + if [ $found = no ]; then + srcs="$srcs $src" + else + shrd="$shrd $src" + fi + done + eval ${ngx_module}_SRCS=\"$srcs\" + eval ${ngx_module}_SHRD=\"$shrd\" + + DYNAMIC_MODULES_SRCS="$DYNAMIC_MODULES_SRCS $srcs" + if test -n "$ngx_module_incs"; then CORE_INCS="$CORE_INCS $ngx_module_incs" fi @@ -107,7 +130,24 @@ elif [ "$ngx_module_link" = ADDON ]; then eval ${ngx_module_type}_MODULES=\"\$${ngx_module_type}_MODULES \ $ngx_module_name\" - NGX_ADDON_SRCS="$NGX_ADDON_SRCS $ngx_module_srcs" + srcs= + for src in $ngx_module_srcs + do + found=no + for old in $NGX_ADDON_SRCS + do + if [ $src = $old ]; then + found=yes + break + fi + done + + if [ $found = no ]; then + srcs="$srcs $src" + fi + done + + NGX_ADDON_SRCS="$NGX_ADDON_SRCS $srcs" if test -n "$ngx_module_incs"; then eval ${ngx_var}_INCS=\"\$${ngx_var}_INCS $ngx_module_incs\" diff --git a/auto/modules b/auto/modules index 09bfcb08..f5a45978 100644 --- a/auto/modules +++ b/auto/modules @@ -102,21 +102,6 @@ if [ $HTTP = YES ]; then fi - if [ $HTTP_SSI = YES ]; then - HTTP_POSTPONE=YES - fi - - - if [ $HTTP_SLICE = YES ]; then - HTTP_POSTPONE=YES - fi - - - if [ $HTTP_ADDITION = YES ]; then - HTTP_POSTPONE=YES - fi - - # the module order is important # ngx_http_static_module # ngx_http_gzip_static_module @@ -252,13 +237,13 @@ if [ $HTTP = YES ]; then . auto/module fi - if [ $HTTP_POSTPONE = YES ]; then + if :; then ngx_module_name=ngx_http_postpone_filter_module ngx_module_incs= ngx_module_deps= ngx_module_srcs=src/http/ngx_http_postpone_filter_module.c ngx_module_libs= - ngx_module_link=$HTTP_POSTPONE + ngx_module_link=YES . auto/module fi @@ -1000,6 +985,12 @@ if [ $MAIL != NO ]; then ngx_module_srcs=src/mail/ngx_mail_proxy_module.c . auto/module + + ngx_module_name=ngx_mail_realip_module + ngx_module_deps= + ngx_module_srcs=src/mail/ngx_mail_realip_module.c + + . auto/module fi @@ -1134,6 +1125,16 @@ if [ $STREAM != NO ]; then . auto/module fi + if [ $STREAM_SET = YES ]; then + ngx_module_name=ngx_stream_set_module + ngx_module_deps= + ngx_module_srcs=src/stream/ngx_stream_set_module.c + ngx_module_libs= + ngx_module_link=$STREAM_SET + + . auto/module + fi + if [ $STREAM_UPSTREAM_HASH = YES ]; then ngx_module_name=ngx_stream_upstream_hash_module ngx_module_deps= diff --git a/auto/options b/auto/options index d8b421b0..80be906e 100644 --- a/auto/options +++ b/auto/options @@ -60,7 +60,6 @@ HTTP_GZIP=YES HTTP_SSL=NO HTTP_V2=NO HTTP_SSI=YES -HTTP_POSTPONE=NO HTTP_REALIP=NO HTTP_XSLT=NO HTTP_IMAGE_FILTER=NO @@ -125,6 +124,7 @@ STREAM_GEOIP=NO STREAM_MAP=YES STREAM_SPLIT_CLIENTS=YES STREAM_RETURN=YES +STREAM_SET=YES STREAM_UPSTREAM_HASH=YES STREAM_UPSTREAM_LEAST_CONN=YES STREAM_UPSTREAM_RANDOM=YES @@ -132,8 +132,10 @@ STREAM_UPSTREAM_ZONE=YES STREAM_SSL_PREREAD=NO DYNAMIC_MODULES= +DYNAMIC_MODULES_SRCS= NGX_ADDONS= +NGX_ADDON_SRCS= NGX_ADDON_DEPS= DYNAMIC_ADDONS= @@ -325,6 +327,7 @@ use the \"--with-mail_ssl_module\" option instead" --without-stream_split_clients_module) STREAM_SPLIT_CLIENTS=NO ;; --without-stream_return_module) STREAM_RETURN=NO ;; + --without-stream_set_module) STREAM_SET=NO ;; --without-stream_upstream_hash_module) STREAM_UPSTREAM_HASH=NO ;; --without-stream_upstream_least_conn_module) @@ -539,6 +542,7 @@ cat << END --without-stream_split_clients_module disable ngx_stream_split_clients_module --without-stream_return_module disable ngx_stream_return_module + --without-stream_set_module disable ngx_stream_set_module --without-stream_upstream_hash_module disable ngx_stream_upstream_hash_module --without-stream_upstream_least_conn_module diff --git a/auto/os/linux b/auto/os/linux index 5e280eca..74b58702 100644 --- a/auto/os/linux +++ b/auto/os/linux @@ -86,6 +86,31 @@ if [ $ngx_found = yes ]; then ee.data.ptr = NULL; epoll_ctl(efd, EPOLL_CTL_ADD, fd, &ee)" . auto/feature + + + # eventfd() + + ngx_feature="eventfd()" + ngx_feature_name="NGX_HAVE_EVENTFD" + ngx_feature_run=no + ngx_feature_incs="#include " + ngx_feature_path= + ngx_feature_libs= + ngx_feature_test="(void) eventfd(0, 0)" + . auto/feature + + if [ $ngx_found = yes ]; then + have=NGX_HAVE_SYS_EVENTFD_H . auto/have + fi + + + if [ $ngx_found = no ]; then + + ngx_feature="eventfd() (SYS_eventfd)" + ngx_feature_incs="#include " + ngx_feature_test="(void) SYS_eventfd" + . auto/feature + fi fi diff --git a/auto/unix b/auto/unix index 43d3b25a..86710198 100644 --- a/auto/unix +++ b/auto/unix @@ -582,29 +582,6 @@ Currently file AIO is supported on FreeBSD 4.3+ and Linux 2.6.22+ only END exit 1 fi - -else - - ngx_feature="eventfd()" - ngx_feature_name="NGX_HAVE_EVENTFD" - ngx_feature_run=no - ngx_feature_incs="#include " - ngx_feature_path= - ngx_feature_libs= - ngx_feature_test="(void) eventfd(0, 0)" - . auto/feature - - if [ $ngx_found = yes ]; then - have=NGX_HAVE_SYS_EVENTFD_H . auto/have - fi - - if [ $ngx_found = no ]; then - - ngx_feature="eventfd() (SYS_eventfd)" - ngx_feature_incs="#include " - ngx_feature_test="(void) SYS_eventfd" - . auto/feature - fi fi @@ -727,56 +704,44 @@ ngx_feature_test="char buf[1]; struct iovec vec[1]; ssize_t n; . auto/feature -ngx_feature="sys_nerr" -ngx_feature_name="NGX_SYS_NERR" -ngx_feature_run=value -ngx_feature_incs='#include - #include ' +# strerrordesc_np(), introduced in glibc 2.32 + +ngx_feature="strerrordesc_np()" +ngx_feature_name="NGX_HAVE_STRERRORDESC_NP" +ngx_feature_run=no +ngx_feature_incs='#include ' ngx_feature_path= ngx_feature_libs= -ngx_feature_test='printf("%d", sys_nerr);' +ngx_feature_test="char *p; p = strerrordesc_np(0); + if (p == NULL) return 1" . auto/feature if [ $ngx_found = no ]; then - # Cygiwn defines _sys_nerr - ngx_feature="_sys_nerr" + ngx_feature="sys_nerr" ngx_feature_name="NGX_SYS_NERR" ngx_feature_run=value ngx_feature_incs='#include #include ' ngx_feature_path= ngx_feature_libs= - ngx_feature_test='printf("%d", _sys_nerr);' + ngx_feature_test='printf("%d", sys_nerr);' . auto/feature fi if [ $ngx_found = no ]; then - # Solaris has no sys_nerr - ngx_feature='maximum errno' - ngx_feature_name=NGX_SYS_NERR + # Cygiwn defines _sys_nerr + ngx_feature="_sys_nerr" + ngx_feature_name="NGX_SYS_NERR" ngx_feature_run=value ngx_feature_incs='#include - #include #include ' ngx_feature_path= ngx_feature_libs= - ngx_feature_test='int n; - char *p; - for (n = 1; n < 1000; n++) { - errno = 0; - p = strerror(n); - if (errno == EINVAL - || p == NULL - || strncmp(p, "Unknown error", 13) == 0) - { - break; - } - } - printf("%d", n);' + ngx_feature_test='printf("%d", _sys_nerr);' . auto/feature fi @@ -943,6 +908,18 @@ ngx_feature_test="int i = FIONBIO; printf(\"%d\", i)" . auto/feature +ngx_feature="ioctl(FIONREAD)" +ngx_feature_name="NGX_HAVE_FIONREAD" +ngx_feature_run=no +ngx_feature_incs="#include + #include + $NGX_INCLUDE_SYS_FILIO_H" +ngx_feature_path= +ngx_feature_libs= +ngx_feature_test="int i = FIONREAD; printf(\"%d\", i)" +. auto/feature + + ngx_feature="struct tm.tm_gmtoff" ngx_feature_name="NGX_HAVE_GMTOFF" ngx_feature_run=no diff --git a/conf/mime.types b/conf/mime.types index 29612569..b53f7f7e 100644 --- a/conf/mime.types +++ b/conf/mime.types @@ -51,6 +51,7 @@ types { application/vnd.openxmlformats-officedocument.wordprocessingml.document docx; application/vnd.wap.wmlc wmlc; + application/wasm wasm; application/x-7z-compressed 7z; application/x-cocoa cco; application/x-java-archive-diff jardiff; diff --git a/configure b/configure index 7e6e33a7..b7c507a7 100755 --- a/configure +++ b/configure @@ -58,6 +58,10 @@ if [ "$NGX_PLATFORM" != win32 ]; then . auto/unix fi +# Debian +# Make sure signature stays the same on all nginx flavors +have=NGX_HTTP_HEADERS . auto/have + . auto/threads . auto/modules . auto/lib/conf @@ -87,6 +91,10 @@ have=NGX_PID_PATH value="\"$NGX_PID_PATH\"" . auto/define have=NGX_LOCK_PATH value="\"$NGX_LOCK_PATH\"" . auto/define have=NGX_ERROR_LOG_PATH value="\"$NGX_ERROR_LOG_PATH\"" . auto/define +if [ ".$NGX_ERROR_LOG_PATH" = "." ]; then + have=NGX_ERROR_LOG_STDERR . auto/have +fi + have=NGX_HTTP_LOG_PATH value="\"$NGX_HTTP_LOG_PATH\"" . auto/define have=NGX_HTTP_CLIENT_TEMP_PATH value="\"$NGX_HTTP_CLIENT_TEMP_PATH\"" . auto/define diff --git a/contrib/vim/syntax/nginx.vim b/contrib/vim/syntax/nginx.vim index 6bee7a2e..1a3a7b7d 100644 --- a/contrib/vim/syntax/nginx.vim +++ b/contrib/vim/syntax/nginx.vim @@ -333,6 +333,7 @@ syn keyword ngxDirective contained js_access syn keyword ngxDirective contained js_content syn keyword ngxDirective contained js_filter syn keyword ngxDirective contained js_include +syn keyword ngxDirective contained js_path syn keyword ngxDirective contained js_preread syn keyword ngxDirective contained js_set syn keyword ngxDirective contained keepalive @@ -353,6 +354,7 @@ syn keyword ngxDirective contained limit_conn_zone syn keyword ngxDirective contained limit_rate syn keyword ngxDirective contained limit_rate_after syn keyword ngxDirective contained limit_req +syn keyword ngxDirective contained limit_req_dry_run syn keyword ngxDirective contained limit_req_log_level syn keyword ngxDirective contained limit_req_status syn keyword ngxDirective contained limit_req_zone @@ -472,6 +474,7 @@ syn keyword ngxDirective contained proxy_requests syn keyword ngxDirective contained proxy_responses syn keyword ngxDirective contained proxy_send_lowat syn keyword ngxDirective contained proxy_send_timeout +syn keyword ngxDirective contained proxy_session_drop syn keyword ngxDirective contained proxy_set_body syn keyword ngxDirective contained proxy_set_header syn keyword ngxDirective contained proxy_socket_keepalive @@ -1325,6 +1328,7 @@ syn keyword ngxDirectiveThirdParty contained lua_check_client_abort syn keyword ngxDirectiveThirdParty contained lua_code_cache syn keyword ngxDirectiveThirdParty contained lua_fake_shm syn keyword ngxDirectiveThirdParty contained lua_http10_buffering +syn keyword ngxDirectiveThirdParty contained lua_load_resty_core syn keyword ngxDirectiveThirdParty contained lua_malloc_trim syn keyword ngxDirectiveThirdParty contained lua_max_pending_timers syn keyword ngxDirectiveThirdParty contained lua_max_running_timers @@ -1779,6 +1783,7 @@ syn keyword ngxDirectiveThirdParty contained vod_expires_live_time_dependent syn keyword ngxDirectiveThirdParty contained vod_fallback_upstream_location syn keyword ngxDirectiveThirdParty contained vod_force_continuous_timestamps syn keyword ngxDirectiveThirdParty contained vod_force_playlist_type_vod +syn keyword ngxDirectiveThirdParty contained vod_force_sequence_index syn keyword ngxDirectiveThirdParty contained vod_gop_look_ahead syn keyword ngxDirectiveThirdParty contained vod_gop_look_behind syn keyword ngxDirectiveThirdParty contained vod_ignore_edit_list diff --git a/debian/changelog b/debian/changelog index a692f860..b2c8dc3d 100644 --- a/debian/changelog +++ b/debian/changelog @@ -1,28 +1,11 @@ -nginx (1.16.1-2) unstable; urgency=medium - - * http-lua: Downgrade to 0.10.13 (Closes: #941917) - Temporary fix FTBFS on architectures where Luajit is not available. - - -- Christos Trochalakis Sat, 12 Oct 2019 17:59:23 +0300 - -nginx (1.16.1-1) unstable; urgency=medium - - * New upstream version (Closes: #929200) - * Follow stable 1.16 releases (Closes: #929199) - * Drop already included debian patches - * http-ndk: Upgrade to 0.3.1 - * http-lua: Upgrade to 0.10.15 - - -- Christos Trochalakis Mon, 09 Sep 2019 18:24:43 +0300 - -nginx (1.14.2-3) unstable; urgency=high +nginx (1.14.2-2+deb10u1) buster-security; urgency=high * Backport upstream fixes for 3 CVEs (Closes: #935037) Those fixes affect Nginx HTTP/2 implementation, which might cause excessive memory consumption and CPU usage. (CVE-2019-9511, CVE-2019-9513, CVE-2019-9516). - -- Christos Trochalakis Mon, 19 Aug 2019 11:30:08 +0300 + -- Christos Trochalakis Tue, 13 Aug 2019 21:10:28 +0300 nginx (1.14.2-2) unstable; urgency=medium diff --git a/debian/compat b/debian/compat deleted file mode 100644 index f599e28b..00000000 --- a/debian/compat +++ /dev/null @@ -1 +0,0 @@ -10 diff --git a/debian/conf/fastcgi.conf b/debian/conf/fastcgi.conf index 091738c6..d53a628d 100644 --- a/debian/conf/fastcgi.conf +++ b/debian/conf/fastcgi.conf @@ -18,6 +18,7 @@ fastcgi_param SERVER_SOFTWARE nginx/$nginx_version; fastcgi_param REMOTE_ADDR $remote_addr; fastcgi_param REMOTE_PORT $remote_port; +fastcgi_param REMOTE_USER $remote_user; fastcgi_param SERVER_ADDR $server_addr; fastcgi_param SERVER_PORT $server_port; fastcgi_param SERVER_NAME $server_name; diff --git a/debian/conf/fastcgi_params b/debian/conf/fastcgi_params index 28decb95..69c43877 100644 --- a/debian/conf/fastcgi_params +++ b/debian/conf/fastcgi_params @@ -17,6 +17,7 @@ fastcgi_param SERVER_SOFTWARE nginx/$nginx_version; fastcgi_param REMOTE_ADDR $remote_addr; fastcgi_param REMOTE_PORT $remote_port; +fastcgi_param REMOTE_USER $remote_user; fastcgi_param SERVER_ADDR $server_addr; fastcgi_param SERVER_PORT $server_port; fastcgi_param SERVER_NAME $server_name; diff --git a/debian/conf/nginx.conf b/debian/conf/nginx.conf index 132f680d..136753ea 100644 --- a/debian/conf/nginx.conf +++ b/debian/conf/nginx.conf @@ -16,8 +16,6 @@ http { sendfile on; tcp_nopush on; - tcp_nodelay on; - keepalive_timeout 65; types_hash_max_size 2048; # server_tokens off; @@ -31,7 +29,7 @@ http { # SSL Settings ## - ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE + ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; ## @@ -66,17 +64,17 @@ http { #mail { # # See sample authentication script at: # # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript -# +# # # auth_http localhost/auth.php; # # pop3_capabilities "TOP" "USER"; # # imap_capabilities "IMAP4rev1" "UIDPLUS"; -# +# # server { # listen localhost:110; # protocol pop3; # proxy on; # } -# +# # server { # listen localhost:143; # protocol imap; diff --git a/debian/conf/sites-available/default b/debian/conf/sites-available/default index f5c5e1b7..c5af9146 100644 --- a/debian/conf/sites-available/default +++ b/debian/conf/sites-available/default @@ -57,7 +57,7 @@ server { # include snippets/fastcgi-php.conf; # # # With php-fpm (or other unix sockets): - # fastcgi_pass unix:/run/php/php7.3-fpm.sock; + # fastcgi_pass unix:/run/php/php7.4-fpm.sock; # # With php-cgi (or other tcp sockets): # fastcgi_pass 127.0.0.1:9000; #} diff --git a/debian/control b/debian/control index 409dc22b..fe24d3e6 100644 --- a/debian/control +++ b/debian/control @@ -2,8 +2,9 @@ Source: nginx Section: httpd Priority: optional Maintainer: Debian Nginx Maintainers -Uploaders: Christos Trochalakis -Build-Depends: debhelper (>= 10), +Uploaders: Christos Trochalakis , + Ondřej Nový , +Build-Depends: debhelper-compat (= 13), dpkg-dev (>= 1.15.5), libexpat-dev, libgd-dev, @@ -11,6 +12,7 @@ Build-Depends: debhelper (>= 10), libhiredis-dev, liblua5.1-0-dev [!i386 !amd64 !kfreebsd-i386 !armel !armhf !powerpc !powerpcspe !mips !mipsel], libluajit-5.1-dev [i386 amd64 kfreebsd-i386 armel armhf powerpc powerpcspe mips mipsel], + libmaxminddb-dev, libmhash-dev, libpam0g-dev, libpcre3-dev, @@ -20,23 +22,24 @@ Build-Depends: debhelper (>= 10), po-debconf, quilt, zlib1g-dev -Standards-Version: 4.3.0 +Standards-Version: 4.5.0 Homepage: https://nginx.net Vcs-Git: https://salsa.debian.org/nginx-team/nginx.git Vcs-Browser: https://salsa.debian.org/nginx-team/nginx +Rules-Requires-Root: no Package: nginx Architecture: all -Depends: nginx-full (<< ${source:Version}.1~) | nginx-light (<< ${source:Version}.1~) | nginx-extras (<< ${source:Version}.1~), - nginx-full (>= ${source:Version}) | nginx-light (>= ${source:Version}) | nginx-extras (>= ${source:Version}), +Depends: nginx-core (<< ${source:Version}.1~) | nginx-full (<< ${source:Version}.1~) | nginx-light (<< ${source:Version}.1~) | nginx-extras (<< ${source:Version}.1~), + nginx-core (>= ${source:Version}) | nginx-full (>= ${source:Version}) | nginx-light (>= ${source:Version}) | nginx-extras (>= ${source:Version}), ${misc:Depends} Description: small, powerful, scalable web/proxy server Nginx ("engine X") is a high-performance web and reverse proxy server created by Igor Sysoev. It can be used both as a standalone web server and as a proxy to reduce the load on back-end HTTP or mail servers. . - This is a dependency package to install either nginx-full (by default), - nginx-light or nginx-extras. + This is a dependency package to install either nginx-core (by default), + nginx-full, nginx-light or nginx-extras. Package: nginx-doc Architecture: all @@ -63,22 +66,21 @@ Description: small, powerful, scalable web/proxy server - common files This package contains base configuration files used by all versions of nginx. -Package: nginx-full +Package: nginx-core Architecture: any -Depends: libnginx-mod-http-auth-pam (= ${binary:Version}), - libnginx-mod-http-dav-ext (= ${binary:Version}), - libnginx-mod-http-echo (= ${binary:Version}), - libnginx-mod-http-geoip (= ${binary:Version}), +Depends: libnginx-mod-http-geoip (= ${binary:Version}), libnginx-mod-http-image-filter (= ${binary:Version}), - libnginx-mod-http-subs-filter (= ${binary:Version}), - libnginx-mod-http-upstream-fair (= ${binary:Version}), libnginx-mod-http-xslt-filter (= ${binary:Version}), libnginx-mod-mail (= ${binary:Version}), libnginx-mod-stream (= ${binary:Version}), + libnginx-mod-stream-geoip (= ${binary:Version}), nginx-common (= ${source:Version}), + iproute2, ${misc:Depends}, ${shlibs:Depends} -Breaks: nginx (<< 1.4.5-1) +Breaks: nginx (<< 1.4.5-1), + nginx-full (<< 1.18.0-1), +Replaces: nginx-full (<< 1.18.0-1), Provides: httpd, httpd-cgi, nginx Conflicts: nginx-extras, nginx-light Suggests: nginx-doc (= ${source:Version}) @@ -87,9 +89,47 @@ Description: nginx web/proxy server (standard version) created by Igor Sysoev. It can be used both as a standalone web server and as a proxy to reduce the load on back-end HTTP or mail servers. . - This package provides a version of nginx with the complete set of + This package provides a version of nginx identical to that of nginx-full, + but without any third-party modules, and only modules in the original + nginx code base. + . + STANDARD HTTP MODULES: Core, Access, Auth Basic, Auto Index, Browser, Empty + GIF, FastCGI, Geo, Limit Connections, Limit Requests, Map, Memcached, Proxy, + Referer, Rewrite, SCGI, Split Clients, UWSGI. + . + OPTIONAL HTTP MODULES: Addition, Auth Request, Charset, WebDAV, GeoIP, Gunzip, + Gzip, Gzip Precompression, Headers, HTTP/2, Image Filter, Index, Log, Real IP, + Slice, SSI, SSL, SSL Preread, Stub Status, Substitution, Thread Pool, + Upstream, User ID, XSLT. + . + OPTIONAL MAIL MODULES: Mail Core, Auth HTTP, Proxy, SSL, IMAP, POP3, SMTP. + . + OPTIONAL STREAM MODULES: Stream Core, GeoIP + +Package: nginx-full +Architecture: all +Depends: libnginx-mod-http-auth-pam, + libnginx-mod-http-dav-ext, + libnginx-mod-http-echo, + libnginx-mod-http-geoip2, + libnginx-mod-http-subs-filter, + libnginx-mod-http-upstream-fair, + libnginx-mod-stream-geoip2, + nginx-core (>= ${source:Version}), + nginx-core (<< ${source:Version}.1~), + ${misc:Depends}, + ${shlibs:Depends} +Breaks: nginx (<< 1.4.5-1) +Provides: httpd, httpd-cgi, nginx +Suggests: nginx-doc (= ${source:Version}) +Description: nginx web/proxy server (standard version with 3rd parties) + Nginx ("engine X") is a high-performance web and reverse proxy server + created by Igor Sysoev. It can be used both as a standalone web server + and as a proxy to reduce the load on back-end HTTP or mail servers. + . + This metapackage provides a version of nginx with the complete set of standard modules included (but omitting some of those included in - nginx-extra). + nginx-extras). . STANDARD HTTP MODULES: Core, Access, Auth Basic, Auto Index, Browser, Empty GIF, FastCGI, Geo, Limit Connections, Limit Requests, Map, Memcached, Proxy, @@ -100,20 +140,23 @@ Description: nginx web/proxy server (standard version) Slice, SSI, SSL, Stream, SSL Preread, Stub Status, Substitution, Thread Pool, Upstream, User ID, XSLT. . - MAIL MODULES: Mail Core, Auth HTTP, Proxy, SSL, IMAP, POP3, SMTP. + OPTIONAL MAIL MODULES: Mail Core, Auth HTTP, Proxy, SSL, IMAP, POP3, SMTP. + . + OPTIONAL STREAM MODULES: Stream Core, GeoIP, GeoIP2 . - THIRD PARTY MODULES: Auth PAM, DAV Ext, Echo, HTTP Substitutions, Upstream - Fair Queue. + THIRD PARTY MODULES: Auth PAM, DAV Ext, Echo, GeoIP2, HTTP Substitutions + Upstream Fair Queue. Package: nginx-light Architecture: any Depends: libnginx-mod-http-echo (= ${binary:Version}), nginx-common (= ${source:Version}), + iproute2, ${misc:Depends}, ${shlibs:Depends} Breaks: nginx (<< 1.4.5-1) Provides: httpd, httpd-cgi, nginx -Conflicts: nginx-extras, nginx-full +Conflicts: nginx-extras, nginx-core Suggests: nginx-doc (= ${source:Version}) Description: nginx web/proxy server (basic version) Nginx ("engine X") is a high-performance web and reverse proxy server @@ -140,6 +183,7 @@ Depends: libnginx-mod-http-auth-pam (= ${binary:Version}), libnginx-mod-http-echo (= ${binary:Version}), libnginx-mod-http-fancyindex (= ${binary:Version}), libnginx-mod-http-geoip (= ${binary:Version}), + libnginx-mod-http-geoip2 (= ${binary:Version}), libnginx-mod-http-headers-more-filter (= ${binary:Version}), libnginx-mod-http-image-filter (= ${binary:Version}), libnginx-mod-http-lua (= ${binary:Version}), @@ -151,12 +195,15 @@ Depends: libnginx-mod-http-auth-pam (= ${binary:Version}), libnginx-mod-mail (= ${binary:Version}), libnginx-mod-nchan (= ${binary:Version}), libnginx-mod-stream (= ${binary:Version}), + libnginx-mod-stream-geoip (= ${binary:Version}), + libnginx-mod-stream-geoip2 (= ${binary:Version}), nginx-common (= ${source:Version}), + iproute2, ${misc:Depends}, ${shlibs:Depends} Breaks: nginx (<< 1.4.5-1) Provides: httpd, httpd-cgi, nginx -Conflicts: nginx-full, nginx-light +Conflicts: nginx-core, nginx-light Suggests: nginx-doc (= ${source:Version}) Description: nginx web/proxy server (extended version) Nginx ("engine X") is a high-performance web and reverse proxy server @@ -174,18 +221,20 @@ Description: nginx web/proxy server (extended version) OPTIONAL HTTP MODULES: Addition, Auth Request, Charset, WebDAV, FLV, GeoIP, Gunzip, Gzip, Gzip Precompression, Headers, HTTP/2, Image Filter, Index, Log, MP4, Embedded Perl, Random Index, Real IP, Slice, Secure Link, SSI, SSL, - Stream, SSL Preread, Stub Status, Substitution, Thread Pool, Upstream, - User ID, XSLT. + SSL Preread, Stub Status, Substitution, Thread Pool, Upstream, User ID, XSLT. . - MAIL MODULES: Mail Core, Auth HTTP, Proxy, SSL, IMAP, POP3, SMTP. + OPTIONAL MAIL MODULES: Mail Core, Auth HTTP, Proxy, SSL, IMAP, POP3, SMTP. + . + OPTIONAL STREAM MODULES: Stream, GeoIP, GeoIP2 . THIRD PARTY MODULES: Auth PAM, Cache Purge, DAV Ext, Echo, Fancy Index, - Headers More, Embedded Lua, HTTP Substitutions, Nchan, Upload Progress, + GeoIP2, Headers More, Embedded Lua, HTTP Substitutions, Nchan, Upload Progress, Upstream Fair Queue. Package: libnginx-mod-http-geoip Architecture: any -Depends: ${misc:Depends}, ${shlibs:Depends} +Depends: ${misc:Depends}, ${shlibs:Depends}, +Recommends: nginx, Description: GeoIP HTTP module for Nginx The ngx_http_geoip module creates variables with values depending on the client IP address, using the precompiled MaxMind databases. @@ -193,9 +242,21 @@ Description: GeoIP HTTP module for Nginx Those variables include country, region, city, latitude, longitude, postal code, etc. +Package: libnginx-mod-http-geoip2 +Architecture: any +Depends: ${misc:Depends}, ${shlibs:Depends}, +Recommends: nginx, +Description: GeoIP2 HTTP module for Nginx + The ngx_http_geoip2 module creates variables with values depending on the + client IP address, using the precompiled MaxMind GeoIP2 databases. + . + Those variables include country, region, city, latitude, longitude, postal + code, etc. + Package: libnginx-mod-http-image-filter Architecture: any -Depends: ${misc:Depends}, ${shlibs:Depends} +Depends: ${misc:Depends}, ${shlibs:Depends}, +Recommends: nginx, Description: HTTP image filter module for Nginx The ngx_http_image_filter module is a filter that transforms images in JPEG, GIF, and PNG formats. @@ -205,7 +266,8 @@ Description: HTTP image filter module for Nginx Package: libnginx-mod-http-xslt-filter Architecture: any -Depends: ${misc:Depends}, ${shlibs:Depends} +Depends: ${misc:Depends}, ${shlibs:Depends}, +Recommends: nginx, Description: XSLT Transformation module for Nginx The ngx_http_xslt_filter module is a filter that transforms XML responses using one or more XSLT stylesheets. @@ -215,7 +277,8 @@ Description: XSLT Transformation module for Nginx Package: libnginx-mod-mail Architecture: any -Depends: ${misc:Depends}, ${shlibs:Depends} +Depends: ${misc:Depends}, ${shlibs:Depends}, +Recommends: nginx, Description: Mail module for Nginx The nginx_mail module adds mail proxy support to nginx. . @@ -224,7 +287,8 @@ Description: Mail module for Nginx Package: libnginx-mod-stream Architecture: any -Depends: ${misc:Depends}, ${shlibs:Depends} +Depends: ${misc:Depends}, ${shlibs:Depends}, +Recommends: nginx, Description: Stream module for Nginx The nginx_stream module adds stream proxy support to nginx. . @@ -232,9 +296,34 @@ Description: Stream module for Nginx also supports ACLs/connection limiting and configuring multiple operational parameters. +Package: libnginx-mod-stream-geoip +Architecture: any +Depends: ${misc:Depends}, ${shlibs:Depends}, + libnginx-mod-stream (= ${binary:Version}), +Recommends: nginx, +Description: GeoIP Stream module for Nginx + The ngx_stream_geoip module creates variables with values depending on the + client IP address, using the precompiled MaxMind databases. + . + Those variables include country, region, city, latitude, longitude, postal + code, etc. + +Package: libnginx-mod-stream-geoip2 +Architecture: any +Depends: ${misc:Depends}, ${shlibs:Depends}, + libnginx-mod-stream (= ${binary:Version}), +Recommends: nginx, +Description: GeoIP2 Stream module for Nginx + The ngx_stream_geoip2 module creates variables with values depending on the + client IP address, using the precompiled MaxMind GeoIP2 databases. + . + Those variables include country, region, city, latitude, longitude, postal + code, etc. + Package: libnginx-mod-http-perl Architecture: any -Depends: ${misc:Depends}, ${perl:Depends}, ${shlibs:Depends} +Depends: ${misc:Depends}, ${perl:Depends}, ${shlibs:Depends}, +Recommends: nginx, Replaces: nginx-extras (<< 1.9.14-1) Description: Perl module for Nginx Embed Perl runtime into nginx. @@ -246,7 +335,8 @@ Description: Perl module for Nginx Package: libnginx-mod-http-auth-pam Architecture: any -Depends: ${misc:Depends}, ${shlibs:Depends} +Depends: ${misc:Depends}, ${shlibs:Depends}, +Recommends: nginx, Description: PAM authentication module for Nginx The nginx_http_auth_pam module enables authentication using PAM. . @@ -257,7 +347,8 @@ Package: libnginx-mod-http-lua Architecture: any Depends: libnginx-mod-http-ndk (= ${binary:Version}), ${misc:Depends}, - ${shlibs:Depends} + ${shlibs:Depends}, +Recommends: nginx, Description: Lua module for Nginx Embed Lua runtime into nginx. . @@ -268,7 +359,8 @@ Description: Lua module for Nginx Package: libnginx-mod-http-ndk Architecture: any -Depends: ${misc:Depends}, ${shlibs:Depends} +Depends: ${misc:Depends}, ${shlibs:Depends}, +Recommends: nginx, Description: Nginx Development Kit module The NDK is an Nginx module that is designed to extend the core functionality of the excellent Nginx webserver in a way that can be used as a basis of other @@ -281,7 +373,8 @@ Description: Nginx Development Kit module Package: libnginx-mod-nchan Architecture: any -Depends: ${misc:Depends}, ${shlibs:Depends} +Depends: ${misc:Depends}, ${shlibs:Depends}, +Recommends: nginx, Description: Fast, flexible pub/sub server for Nginx Nchan is a scalable, flexible pub/sub server for the modern web, It can be configured as a standalone server, or as a shim between your application and @@ -294,7 +387,8 @@ Description: Fast, flexible pub/sub server for Nginx Package: libnginx-mod-http-echo Architecture: any -Depends: ${misc:Depends}, ${shlibs:Depends} +Depends: ${misc:Depends}, ${shlibs:Depends}, +Recommends: nginx, Description: Bring echo and more shell style goodies to Nginx Echo module wraps lots of Nginx internal APIs for streaming input and output, parallel/sequential subrequests, timers and sleeping, as well as various meta @@ -315,7 +409,8 @@ Description: Bring echo and more shell style goodies to Nginx Package: libnginx-mod-http-upstream-fair Architecture: any -Depends: ${misc:Depends}, ${shlibs:Depends} +Depends: ${misc:Depends}, ${shlibs:Depends}, +Recommends: nginx, Description: Nginx Upstream Fair Proxy Load Balancer The Nginx fair proxy balancer enhances the standard round-robin load balancer provided with Nginx so that it tracks busy backend servers and adjusts @@ -323,7 +418,8 @@ Description: Nginx Upstream Fair Proxy Load Balancer Package: libnginx-mod-http-headers-more-filter Architecture: any -Depends: ${misc:Depends}, ${shlibs:Depends} +Depends: ${misc:Depends}, ${shlibs:Depends}, +Recommends: nginx, Description: Set and clear input and output headers for Nginx The Headers More module allows you to add, set, or clear any output or input header that you specify. @@ -334,7 +430,8 @@ Description: Set and clear input and output headers for Nginx Package: libnginx-mod-http-cache-purge Architecture: any -Depends: ${misc:Depends}, ${shlibs:Depends} +Depends: ${misc:Depends}, ${shlibs:Depends}, +Recommends: nginx, Description: Purge content from Nginx caches Cache Purge module adds purging capabilities to Nginx. It allows purging content from caches used by all of Nginx proxy modules, like FastCGI, Proxy, @@ -342,7 +439,8 @@ Description: Purge content from Nginx caches Package: libnginx-mod-http-fancyindex Architecture: any -Depends: ${misc:Depends}, ${shlibs:Depends} +Depends: ${misc:Depends}, ${shlibs:Depends}, +Suggests: nginx, Description: Fancy indexes module for the Nginx The Fancy Index module makes possible the generation of file listings, like the built-in autoindex module does, but adding a touch of style by introducing @@ -350,7 +448,8 @@ Description: Fancy indexes module for the Nginx Package: libnginx-mod-http-uploadprogress Architecture: any -Depends: ${misc:Depends}, ${shlibs:Depends} +Depends: ${misc:Depends}, ${shlibs:Depends}, +Recommends: nginx, Description: Upload progress system for Nginx Upload progress module is an implementation of an upload progress system, that monitors RFC1867 POST uploads as they are transmitted to upstream servers. @@ -361,7 +460,8 @@ Description: Upload progress system for Nginx Package: libnginx-mod-http-subs-filter Architecture: any -Depends: ${misc:Depends}, ${shlibs:Depends} +Depends: ${misc:Depends}, ${shlibs:Depends}, +Recommends: nginx, Description: Substitution filter module for Nginx Subsitution Nginx module can do both regular expression and fixed string substitutions on response bodies. The module is quite different from Nginx's @@ -370,7 +470,8 @@ Description: Substitution filter module for Nginx Package: libnginx-mod-http-dav-ext Architecture: any -Depends: ${misc:Depends}, ${shlibs:Depends} +Depends: ${misc:Depends}, ${shlibs:Depends}, +Recommends: nginx, Description: WebDAV missing commands support for Nginx WebDAV Ext module complements the Nginx WebDAV module to provide a full WebDAV support. @@ -379,7 +480,8 @@ Description: WebDAV missing commands support for Nginx Package: libnginx-mod-rtmp Architecture: any -Depends: ${misc:Depends}, ${shlibs:Depends} +Depends: ${misc:Depends}, ${shlibs:Depends}, +Recommends: nginx, Description: RTMP support for Nginx The nginx RTMP module is a fully-featured streaming solution implemented in nginx. diff --git a/debian/copyright b/debian/copyright index 66a44d87..c2a5f970 100644 --- a/debian/copyright +++ b/debian/copyright @@ -3,12 +3,12 @@ Upstream-Name: nginx Source: https://nginx.org/en/download.html Files: * -Copyright: 2002-2014 Igor Sysoev - 2011-2014 Nginx, Inc. - Maxim Dounin - Valentin V. Bartenev - Roman Arutyunyan - Ruslan Ermilov +Copyright: 2002-2019, Igor Sysoev + 2011-2019, Nginx, Inc. + Maxim Dounin + Valentin V. Bartenev + Roman Arutyunyan + Ruslan Ermilov License: BSD-2-clause Files: src/core/ngx_murmurhash.c @@ -17,10 +17,16 @@ License: BSD-2-clause Files: src/http/modules/ngx_http_scgi_module.c src/http/modules/ngx_http_uwsgi_module.c -Copyright: Copyright (C) Igor Sysoev - Copyright (C) Nginx, Inc. - 2009-2010 Unbit S.a.s. - 2008 Manlio Perillo (manlio.perillo@gmail.com) +Copyright: 2009-2010, Unbit S.a.s. + 2008, Manlio Perillo (manlio.perillo@gmail.com) + Igor Sysoev + Nginx, Inc. +License: BSD-2-clause + +Files: src/http/v2/ngx_http_v2_huff_encode.c +Copyright: 2015, Vlad Krasnov + Nginx, Inc. + Valentin V. Bartenev License: BSD-2-clause Files: contrib/geo2nginx.pl @@ -35,73 +41,103 @@ Copyright: 2007-2009, Fabio Tranchitella 2011 Dmitry E. Oboukhov 2011-2013, Cyril Lavier 2013-2016, Christos Trochalakis + 2019-2020, Thomas Ward + 2020, Ondřej Nový License: BSD-2-clause Files: debian/modules/http-headers-more-filter/* -Copyright: Copyright (c) 2009-2014, Yichun "agentzh" Zhang (章亦春) , CloudFlare Inc. - Copyright (c) 2010-2013, Bernd Dorn - Copyright (c) Igor Sysoev +Copyright: 2009-2017, Yichun "agentzh" Zhang (章亦春) , CloudFlare Inc. + 2010-2013, Bernd Dorn + Igor Sysoev +License: BSD-2-clause + +Files: debian/modules/http-geoip2/* +Copyright: 2014, Lee Valentine License: BSD-2-clause Files: debian/modules/http-ndk/* -Copyright: Marcus Clyne +Copyright: 2010-2018, Marcus Clyne License: BSD-3-clause Files: debian/modules/http-ndk/src/hash/md5.h debian/modules/http-ndk/src/hash/sha.h -Copyright: Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) +Copyright: 1995-1998, Eric Young License: BSD-4-clause +Files: debian/modules/http-ndk/src/hash/murmurhash2.c +Copyright: Austin Appleby +License: BSD-3-clause + Files: debian/modules/http-auth-pam/* -Copyright: 2008-2013, Sergio Talens Oliag +Copyright: 2008-2020, Sergio Talens Oliag License: BSD-2-clause Files: debian/modules/http-echo/* -Copyright: Copyright (c) 2009-2014, Yichun "agentzh" Zhang +Copyright: 2009-2014, Yichun "agentzh" Zhang License: BSD-2-clause Files: debian/modules/http-lua/* -Copyright: Copyright (C) 2009-2014, by Xiaozhe Wang (chaoslawful) . - Copyright (C) 2009-2014, by Yichun "agentzh" Zhang (章亦春) , CloudFlare Inc. +Copyright: 2009-2017, by Xiaozhe Wang (chaoslawful) . + 2009-2018, by Yichun "agentzh" Zhang (章亦春) , OpenResty Inc. License: BSD-2-clause +Files: debian/modules/http-lua/t/lib/CRC32.lua +Copyright: 2007-2008, Neil Richardson (nrich@iinet.net.au) +License: Expat + Files: debian/modules/http-upstream-fair/* -Copyright: Copyright (c) 2007 Grzegorz Nosek - Igor Sysoev +Copyright: 2007, Grzegorz Nosek + Igor Sysoev License: BSD-2-clause Files: debian/modules/nchan/* -Copyright: 2009-2016 Leo Ponomarev -License: MIT +Copyright: 2009-2016, Leo Ponomarev (slact) + 2014, Wandenberg Peixoto + Alexander Lyalin + Rogério Carvalho Schneider +License: Expat + +Files: debian/modules/nchan/src/store/redis/hiredis/* +Copyright: 2006-2014, Salvatore Sanfilippo + 2010-2011, Pieter Noordhuis + 2015, Matt Stancliff + Jan-Erik Rediger +License: BSD-3-clause Files: debian/modules/nchan/src/store/redis/cmp.* -Copyright: 2015 Charles Gunyon -License: MIT +Copyright: 2017, Charles Gunyon +License: Expat Files: debian/modules/http-uploadprogress/* -Copyright: Brice Figureau +Copyright: 2007, Brice Figureau 2002-2007, Igor Sysoev License: BSD-2-clause Files: debian/modules/http-cache-purge/* -Copyright: 2009-2012, FRiCKLE , - 2009-2012, Piotr Sikora +Copyright: 2009-2014, FRiCKLE , + 2009-2014, Piotr Sikora License: BSD-2-clause Files: debian/modules/http-dav-ext/* -Copyright: Arutyunyan Roman +Copyright: 2012-2018, Roman Arutyunyan License: BSD-2-clause Files: debian/modules/http-fancyindex/* -Copyright: Copyright (c) Adrian Perez +Copyright: 2007-2016, Adrian Perez License: BSD-2-clause Files: debian/modules/http-subs-filter/* -Copyright: Copyright (C) 2014 by Weibin Yao +Copyright: 2014, Weibin Yao License: BSD-2-clause +Files: debian/modules/http-subs-filter/test/* +Copyright: 2009-2011, Taobao Inc., Alibaba Group + Antoine BONAVITA "" + agentzh (章亦春) "" +License: BSD-3-clause + Files: debian/modules/rtmp/* -Copyright: Copyright (C) 2012-2014, Roman Arutyunyan +Copyright: 2012-2014, Roman Arutyunyan License: BSD-2-clause License: BSD-2-clause @@ -181,7 +217,7 @@ License: BSD-4-clause OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -License: MIT +License: Expat Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the diff --git a/debian/gbp.conf b/debian/gbp.conf index a14a6992..b5fb2c91 100644 --- a/debian/gbp.conf +++ b/debian/gbp.conf @@ -2,3 +2,5 @@ pristine-tar = True upstream-branch = upstream upstream-tag = upstream/%(version)s +dist=buster +debian-branch=buster diff --git a/debian/gitlab-ci.yml b/debian/gitlab-ci.yml new file mode 100644 index 00000000..557434c8 --- /dev/null +++ b/debian/gitlab-ci.yml @@ -0,0 +1,8 @@ +--- +include: + - https://salsa.debian.org/salsa-ci-team/pipeline/raw/master/salsa-ci.yml + - https://salsa.debian.org/salsa-ci-team/pipeline/raw/master/pipeline-jobs.yml + +# Disable reprotest which is failing now +variables: + SALSA_CI_DISABLE_REPROTEST: 1 diff --git a/debian/libnginx-mod-http-geoip2.nginx b/debian/libnginx-mod-http-geoip2.nginx new file mode 100755 index 00000000..78c206f2 --- /dev/null +++ b/debian/libnginx-mod-http-geoip2.nginx @@ -0,0 +1,13 @@ +#!/usr/bin/perl -w + +use File::Basename; + +# Guess module name +$module = basename($0, '.nginx'); +$module =~ s/^libnginx-mod-//; + +$modulepath = $module; +$modulepath =~ s/-/_/g; + +print "mod debian/build-extras/objs/ngx_${modulepath}_module.so\n"; +print "mod debian/libnginx-mod.conf/mod-${module}.conf\n"; diff --git a/debian/libnginx-mod-stream-geoip.nginx b/debian/libnginx-mod-stream-geoip.nginx new file mode 100755 index 00000000..9acb1030 --- /dev/null +++ b/debian/libnginx-mod-stream-geoip.nginx @@ -0,0 +1,13 @@ +#!/usr/bin/perl -w + +use File::Basename; + +# Guess module name +$module = basename($0, '.nginx'); +$module =~ s/^libnginx-mod-//; + +$modulepath = $module; +$modulepath =~ s/-/_/g; + +print "mod debian/build-extras/objs/ngx_${modulepath}_module.so\n"; +print "mod debian/libnginx-mod.conf/mod-${module}.conf 70\n"; diff --git a/debian/libnginx-mod-stream-geoip2.nginx b/debian/libnginx-mod-stream-geoip2.nginx new file mode 100755 index 00000000..9acb1030 --- /dev/null +++ b/debian/libnginx-mod-stream-geoip2.nginx @@ -0,0 +1,13 @@ +#!/usr/bin/perl -w + +use File::Basename; + +# Guess module name +$module = basename($0, '.nginx'); +$module =~ s/^libnginx-mod-//; + +$modulepath = $module; +$modulepath =~ s/-/_/g; + +print "mod debian/build-extras/objs/ngx_${modulepath}_module.so\n"; +print "mod debian/libnginx-mod.conf/mod-${module}.conf 70\n"; diff --git a/debian/libnginx-mod.conf/mod-http-geoip2.conf b/debian/libnginx-mod.conf/mod-http-geoip2.conf new file mode 100644 index 00000000..9441b290 --- /dev/null +++ b/debian/libnginx-mod.conf/mod-http-geoip2.conf @@ -0,0 +1 @@ +load_module modules/ngx_http_geoip2_module.so; diff --git a/debian/libnginx-mod.conf/mod-stream-geoip.conf b/debian/libnginx-mod.conf/mod-stream-geoip.conf new file mode 100644 index 00000000..7195856a --- /dev/null +++ b/debian/libnginx-mod.conf/mod-stream-geoip.conf @@ -0,0 +1 @@ +load_module modules/ngx_stream_geoip_module.so; diff --git a/debian/libnginx-mod.conf/mod-stream-geoip2.conf b/debian/libnginx-mod.conf/mod-stream-geoip2.conf new file mode 100644 index 00000000..4072597a --- /dev/null +++ b/debian/libnginx-mod.conf/mod-stream-geoip2.conf @@ -0,0 +1 @@ +load_module modules/ngx_stream_geoip2_module.so; diff --git a/debian/modules/control b/debian/modules/control index f27ca7c9..e980b2ff 100644 --- a/debian/modules/control +++ b/debian/modules/control @@ -8,14 +8,18 @@ Homepage: https://github.com/simpl/ngx_devel_kit/ Version: 0.3.1 Module: http-auth-pam -Homepage: https://github.com/stogh/ngx_http_auth_pam_module -Version: 1.5.1 +Homepage: https://github.com/sto/ngx_http_auth_pam_module +Version: 1.5.2 Module: http-echo Homepage: https://github.com/agentzh/echo-nginx-module Version: v0.61 Files-Excluded: .gitignore .gitattributes .travis.yml +Module: http-geoip2 +Homepage: https://github.com/leev/ngx_http_geoip2_module +Version: 3.3 + Module: http-lua Homepage: https://github.com/openresty/lua-nginx-module Version: 0.10.13 @@ -34,8 +38,8 @@ Patch: Module: nchan Homepage: https://github.com/slact/nchan -Version: 1.0.8 -Files-Excluded: dev nchan_logo.png NchanSubscriber.js src/hiredis +Version: 1.2.7 +Files-Excluded: dev nchan_logo.png NchanSubscriber.js src/hiredis nchan Module: http-uploadprogress Homepage: https://github.com/masterzen/nginx-upload-progress-module @@ -55,7 +59,7 @@ Version: 3.0.0 Module: http-fancyindex Homepage: https://github.com/aperezdc/ngx-fancyindex -Version: 0.4.3 +Version: 0.4.4 Files-Excluded: .gitignore .travis.yml Module: http-subs-filter diff --git a/debian/modules/http-auth-pam/ChangeLog b/debian/modules/http-auth-pam/ChangeLog index d45eae40..084c99a9 100644 --- a/debian/modules/http-auth-pam/ChangeLog +++ b/debian/modules/http-auth-pam/ChangeLog @@ -1,6 +1,14 @@ +2020-06-23 sto@mixinet.net + + * Version 1.5.2. + * Log authentication errors as errors instead of debug (patch provided by + Juha Koho, see https://github.com/sto/ngx_http_auth_pam_module/pull/11) + * Send client IP address to PAM (patch provided by Marcin Łojewski, see + https://github.com/sto/ngx_http_auth_pam_module/pull/14) + 2016-04-06 sto@iti.es - * Version 1.5.1. + * Version 1.5.1. * Fix building alongside other modules in nginx 1.9.11+ (patch provided by Graham Edgecombe ) diff --git a/debian/modules/http-auth-pam/LICENSE b/debian/modules/http-auth-pam/LICENSE index b2d93242..a9d6313d 100644 --- a/debian/modules/http-auth-pam/LICENSE +++ b/debian/modules/http-auth-pam/LICENSE @@ -1,5 +1,5 @@ /* - * Copyright (C) 2008-2016 Sergio Talens Oliag + * Copyright (C) 2008-2020 Sergio Talens Oliag * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions diff --git a/debian/modules/http-auth-pam/README.md b/debian/modules/http-auth-pam/README.md index a4eea455..975bafe2 100644 --- a/debian/modules/http-auth-pam/README.md +++ b/debian/modules/http-auth-pam/README.md @@ -75,11 +75,11 @@ If you want use the ``pam_exec.so`` plugin for request based authentication the module can add to the PAM environment the ``HOST`` and ``REQUEST`` variables if you set the ``auth_pam_set_pam_env`` flag:: - location /pam_exec_protected { - auth_pam "Exec Zone"; - auth_pam_service_name "nginx_exec"; - auth_pam_set_pam_env on; - } + location /pam_exec_protected { + auth_pam "Exec Zone"; + auth_pam_service_name "nginx_exec"; + auth_pam_set_pam_env on; + } With this configuration if you access an URL like: diff --git a/debian/modules/http-auth-pam/VERSION b/debian/modules/http-auth-pam/VERSION index c239c60c..4cda8f19 100644 --- a/debian/modules/http-auth-pam/VERSION +++ b/debian/modules/http-auth-pam/VERSION @@ -1 +1 @@ -1.5 +1.5.2 diff --git a/debian/modules/http-auth-pam/ngx_http_auth_pam_module.c b/debian/modules/http-auth-pam/ngx_http_auth_pam_module.c index 167a37fe..55eeb928 100644 --- a/debian/modules/http-auth-pam/ngx_http_auth_pam_module.c +++ b/debian/modules/http-auth-pam/ngx_http_auth_pam_module.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2008-2016 Sergio Talens-Oliag + * Copyright (C) 2008-2020 Sergio Talens-Oliag * * Based on nginx's 'ngx_http_auth_basic_module.c' by Igor Sysoev and apache's * 'mod_auth_pam.c' by Ingo Luetkebolhe. @@ -182,7 +182,7 @@ ngx_auth_pam_talker(int num_msg, const struct pam_message ** msg, case PAM_PROMPT_ECHO_OFF: response[i].resp = strdup((const char *)ainfo->password.data); break; - case PAM_ERROR_MSG: + case PAM_ERROR_MSG: ngx_log_error(NGX_LOG_ERR, ainfo->log, 0, "PAM: \'%s\'.", msg[i]->msg); break; @@ -335,12 +335,21 @@ ngx_http_auth_pam_authenticate(ngx_http_request_t *r, (const char *) ainfo.username.data, &conv_info, &pamh)) != PAM_SUCCESS) { - ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, + ngx_log_error(NGX_LOG_CRIT, r->connection->log, 0, "PAM: Could not start pam service: %s", pam_strerror(pamh, rc)); return NGX_HTTP_INTERNAL_SERVER_ERROR; } + /* send client IP address to PAM */ + char *client_ip_addr = ngx_strncpy_s(r->connection->addr_text, r->pool); + if ((rc = pam_set_item(pamh, PAM_RHOST, client_ip_addr)) != PAM_SUCCESS) { + ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, + "PAM: Could not set item PAM_RHOST: %s", + pam_strerror(pamh, rc)); + return NGX_HTTP_INTERNAL_SERVER_ERROR; + } + if (alcf->set_pam_env) { add_request_info_to_pam_env(pamh, r); } @@ -348,7 +357,7 @@ ngx_http_auth_pam_authenticate(ngx_http_request_t *r, /* try to authenticate user, log error on failure */ if ((rc = pam_authenticate(pamh, PAM_DISALLOW_NULL_AUTHTOK)) != PAM_SUCCESS) { - ngx_log_debug2(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, + ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "PAM: user '%s' - not authenticated: %s", ainfo.username.data, pam_strerror(pamh, rc)); pam_end(pamh, PAM_SUCCESS); @@ -357,8 +366,8 @@ ngx_http_auth_pam_authenticate(ngx_http_request_t *r, /* check that the account is healthy */ if ((rc = pam_acct_mgmt(pamh, PAM_DISALLOW_NULL_AUTHTOK)) != PAM_SUCCESS) { - ngx_log_debug2(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, - "PAM: user '%s' - invalid account: %s", + ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, + "PAM: user '%s' - invalid account: %s", ainfo.username.data, pam_strerror(pamh, rc)); pam_end(pamh, PAM_SUCCESS); return ngx_http_auth_pam_set_realm(r, &alcf->realm); diff --git a/debian/modules/http-fancyindex/CHANGELOG.md b/debian/modules/http-fancyindex/CHANGELOG.md index 580ec92a..57569e8f 100644 --- a/debian/modules/http-fancyindex/CHANGELOG.md +++ b/debian/modules/http-fancyindex/CHANGELOG.md @@ -3,6 +3,24 @@ All notable changes to this project will be documented in this file. ## [Unreleased] +## [0.4.4] - 2020-02-19 +### Added +- New option `fancyindex_hide_parent_dir`, which disables generating + links to parent directories in listings. (Patch by Kawai Ryota + <>.) + +### Changed +- Each table row is now separated by a new line (as a matter of fact, + a `CRLF` sequence), which makes it easier to parse output using simple + text tools. (Patch by Anders Trier <>.) +- Some corrections and additions to the README file. (Patches by Nicolas + Carpi <> and David Beitey <>.) + +### Fixed +- Use correct character references for `&` characters in table sorter URLs + within the template (Patch by David Beitey <>.) +- Properly encode filenames when used as URI components. + ## [0.4.3] - 2018-07-03 ### Added - Table cells now have class names, which allows for better CSS styling. @@ -130,7 +148,8 @@ All notable changes to this project will be documented in this file. - `NEWS.rst` file, to act as change log. -[Unreleased]: https://github.com/aperezdc/ngx-fancyindex/compare/v0.4.3...HEAD +[Unreleased]: https://github.com/aperezdc/ngx-fancyindex/compare/v0.4.4...HEAD +[0.4.4]: https://github.com/aperezdc/ngx-fancyindex/compare/v0.4.3...v0.4.4 [0.4.3]: https://github.com/aperezdc/ngx-fancyindex/compare/v0.4.2...v0.4.3 [0.4.2]: https://github.com/aperezdc/ngx-fancyindex/compare/v0.4.1...v0.4.2 [0.4.1]: https://github.com/aperezdc/ngx-fancyindex/compare/v0.4.0...v0.4.1 diff --git a/debian/modules/http-fancyindex/HACKING.md b/debian/modules/http-fancyindex/HACKING.md index 07485174..4c8608a1 100644 --- a/debian/modules/http-fancyindex/HACKING.md +++ b/debian/modules/http-fancyindex/HACKING.md @@ -21,4 +21,9 @@ is known to work flawlessly. Just do: $ awk -f template.awk template.html > template.h If your copy of `awk` is not the GNU implementation, you will need to -install it and use `gawk` instead in the command line above. +install it and use `gawk` instead in the command line above. + +This includes macOS where the current built-in `awk` (currently version +20070501 at time of testing on 10.13.6) doesn't apply correctly and causes +characters to be omitted from the output. `gawk` can be installed with a +package manager such as [Homebrew](https://brew.sh). diff --git a/debian/modules/http-fancyindex/README.rst b/debian/modules/http-fancyindex/README.rst index b282b8b1..4d178da1 100644 --- a/debian/modules/http-fancyindex/README.rst +++ b/debian/modules/http-fancyindex/README.rst @@ -11,7 +11,7 @@ Nginx Fancy Index module The Fancy Index module makes possible the generation of file listings, like the built-in `autoindex `__ module does, but adding a touch of style. This is possible because the module -module allows a certain degree of customization of the generated content: +allows a certain degree of customization of the generated content: * Custom headers. Either local or stored remotely. * Custom footers. Either local or stored remotely. @@ -52,7 +52,7 @@ versions in the 0.6 series by applying ``nginx-0.6-support.patch``, but this is unsupported (YMMV). In order to use the ``fancyindex_header_`` and ``fancyindex_footer_`` directives -you will also need the `ngx_http_addition_module `_ +you will also need the `ngx_http_addition_module `_ built into Nginx. @@ -217,7 +217,7 @@ fancyindex_header into Nginx. fancyindex_show_path -~~~~~~~~~~~~~~~~~ +~~~~~~~~~~~~~~~~~~~~ :Syntax: *fancyindex_show_path* [*on* | *off*] :Default: fancyindex_show_path on :Context: http, server, location @@ -247,6 +247,14 @@ fancyindex_hide_symlinks :Description: When enabled, generated listings will not contain symbolic links. +fancyindex_hide_parent_dir +~~~~~~~~~~~~~~~~~~~~~~~~ +:Syntax: *fancyindex_hide_parent_dir* [*on* | *off*] +:Default: fancyindex_hide_parent_dir off +:Context: http, server, location +:Description: + When enabled, it will not show parent directory. + fancyindex_localtime ~~~~~~~~~~~~~~~~~~~~ :Syntax: *fancyindex_localtime* [*on* | *off*] @@ -262,7 +270,7 @@ fancyindex_time_format :Context: http, server, location :Description: Format string used for timestamps. The format specifiers are a subset of - those supported by the `strftime `_ + those supported by the `strftime `_ function, and the behavior is locale-independent (for example, day and month names are always in English). The supported formats are: @@ -295,6 +303,6 @@ fancyindex_time_format * ``%Y``: Year as a decimal number including the century. -.. _nginx: http://nginx.net +.. _nginx: https://nginx.org .. vim:ft=rst:spell:spelllang=en: diff --git a/debian/modules/http-fancyindex/ngx_http_fancyindex_module.c b/debian/modules/http-fancyindex/ngx_http_fancyindex_module.c index 64f98a12..9ce5a381 100644 --- a/debian/modules/http-fancyindex/ngx_http_fancyindex_module.c +++ b/debian/modules/http-fancyindex/ngx_http_fancyindex_module.c @@ -154,6 +154,7 @@ typedef struct { ngx_uint_t name_length; /**< Maximum length of file names in bytes. */ ngx_flag_t hide_symlinks;/**< Hide symbolic links in listings. */ ngx_flag_t show_path; /**< Whether to display or not the path + '' after the header */ + ngx_flag_t hide_parent; /**< Hide parent directory. */ ngx_str_t header; /**< File name for header, or empty if none. */ ngx_str_t footer; /**< File name for footer, or empty if none. */ @@ -258,7 +259,7 @@ static char *ngx_http_fancyindex_ignore(ngx_conf_t *cf, void *conf); static uintptr_t - ngx_fancyindex_escape_uri(u_char *dst, u_char*src, size_t size); + ngx_fancyindex_escape_filename(u_char *dst, u_char*src, size_t size); /* * These are used only once per handler invocation. We can tell GCC to @@ -361,6 +362,13 @@ static ngx_command_t ngx_http_fancyindex_commands[] = { offsetof(ngx_http_fancyindex_loc_conf_t, show_path), NULL }, + { ngx_string("fancyindex_hide_parent_dir"), + NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_FLAG, + ngx_conf_set_flag_slot, + NGX_HTTP_LOC_CONF_OFFSET, + offsetof(ngx_http_fancyindex_loc_conf_t, hide_parent), + NULL }, + { ngx_string("fancyindex_time_format"), NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_FLAG, ngx_conf_set_str_slot, @@ -410,8 +418,15 @@ static const ngx_str_t css_href_post = ngx_string("\" type=\"text/css\"/>\n"); +#ifdef NGX_ESCAPE_URI_COMPONENT +static inline uintptr_t +ngx_fancyindex_escape_filename(u_char *dst, u_char *src, size_t size) +{ + return ngx_escape_uri(dst, src, size, NGX_ESCAPE_URI_COMPONENT); +} +#else /* !NGX_ESCAPE_URI_COMPONENT */ static uintptr_t -ngx_fancyindex_escape_uri(u_char *dst, u_char *src, size_t size) +ngx_fancyindex_escape_filename(u_char *dst, u_char *src, size_t size) { /* * The ngx_escape_uri() function will not escape colons or the @@ -483,6 +498,7 @@ ngx_fancyindex_escape_uri(u_char *dst, u_char *src, size_t size) return escapes + uescapes; } } +#endif /* NGX_ESCAPE_URI_COMPONENT */ static ngx_inline ngx_buf_t* @@ -716,9 +732,9 @@ make_content_buf( return ngx_http_fancyindex_error(r, &dir, &path); ngx_cpystrn(entry->name.data, ngx_de_name(&dir), len + 1); - entry->escape = 2 * ngx_fancyindex_escape_uri(NULL, - ngx_de_name(&dir), - len); + entry->escape = 2 * ngx_fancyindex_escape_filename(NULL, + ngx_de_name(&dir), + len); entry->dir = ngx_de_is_dir(&dir); entry->mtime = ngx_de_mtime(&dir); @@ -901,7 +917,7 @@ make_content_buf( tp = ngx_timeofday(); /* "Parent dir" entry, always first if displayed */ - if (r->uri.len > 1) { + if (r->uri.len > 1 && alcf->hide_parent == 0) { b->last = ngx_cpymem_ssz(b->last, "" "Parent directory/" "-" "-" - ""); + "" + CRLF); } /* Entries for directories and files */ @@ -922,9 +939,9 @@ make_content_buf( b->last = ngx_cpymem_ssz(b->last, "last, - entry[i].name.data, - entry[i].name.len); + ngx_fancyindex_escape_filename(b->last, + entry[i].name.data, + entry[i].name.len); b->last += entry[i].name.len + entry[i].escape; @@ -1315,6 +1332,7 @@ ngx_http_fancyindex_create_loc_conf(ngx_conf_t *cf) conf->ignore = NGX_CONF_UNSET_PTR; conf->hide_symlinks = NGX_CONF_UNSET; conf->show_path = NGX_CONF_UNSET; + conf->hide_parent = NGX_CONF_UNSET; return conf; } @@ -1343,6 +1361,7 @@ ngx_http_fancyindex_merge_loc_conf(ngx_conf_t *cf, void *parent, void *child) ngx_conf_merge_ptr_value(conf->ignore, prev->ignore, NULL); ngx_conf_merge_value(conf->hide_symlinks, prev->hide_symlinks, 0); + ngx_conf_merge_value(conf->hide_parent, prev->hide_parent, 0); /* Just make sure we haven't disabled the show_path directive without providing a custom header */ if (conf->show_path == 0 && conf->header.len == 0) diff --git a/debian/modules/http-fancyindex/t/06-hide_parent.test b/debian/modules/http-fancyindex/t/06-hide_parent.test new file mode 100644 index 00000000..494c9587 --- /dev/null +++ b/debian/modules/http-fancyindex/t/06-hide_parent.test @@ -0,0 +1,23 @@ +#! /bin/bash +cat <<--- +This test check the output using "fancyindex_hide_parent_dir on" +-- +use pup +nginx_start 'fancyindex_hide_parent_dir on;' + +content=$( fetch /child-directory/ ) + +# Check page title +[[ $(pup -p title text{} <<< "${content}") = "Index of /child-directory/" ]] + +# Check table headers +[[ $(pup -n body table tbody tr:first-child td <<< "${content}") -eq 3 ]] +{ + read -r name_label + read -r size_label + read -r date_label +} < <( pup -p body table tbody tr:first-child td text{} <<< "${content}" ) +[[ ${name_label} != Parent\ Directory/ ]] +[[ ${name_label} = empty-file.txt ]] +[[ ${size_label} != - ]] +[[ ${date_label} != - ]] diff --git a/debian/modules/http-fancyindex/t/bug95-square-brackets.test b/debian/modules/http-fancyindex/t/bug95-square-brackets.test new file mode 100644 index 00000000..16e1ddc0 --- /dev/null +++ b/debian/modules/http-fancyindex/t/bug95-square-brackets.test @@ -0,0 +1,19 @@ +#! /bin/bash +cat <<--- +Bug #95: FancyIndex does not encode square brackets +https://github.com/aperezdc/ngx-fancyindex/issues/95 +-- +use pup + +# Prepare a directory with a file that contains square brackets in the name. +mkdir -p "${TESTDIR}/bug95" +touch "${TESTDIR}"/bug95/'bug[95].txt' + +nginx_start +content=$(fetch /bug95/) +test -n "${content}" || fail 'Empty response' + +expected_href='bug%5B95%5D.txt' +obtained_href=$(pup -p body tbody 'tr:nth-child(2)' a 'attr{href}' <<< "${content}") +test "${expected_href}" = "${obtained_href}" || \ + fail 'Expected: %s - Obtained: %s' "${expected_href}" "${obtained_href}" diff --git a/debian/modules/http-fancyindex/t/child-directory/empty-file.txt b/debian/modules/http-fancyindex/t/child-directory/empty-file.txt new file mode 100644 index 00000000..e69de29b diff --git a/debian/modules/http-fancyindex/template.h b/debian/modules/http-fancyindex/template.h index 27b95006..2d6604be 100644 --- a/debian/modules/http-fancyindex/template.h +++ b/debian/modules/http-fancyindex/template.h @@ -57,9 +57,9 @@ static const u_char t06_list1[] = "" "" "" "" -"" -"" -"" +"" +"" +"" "" "" "\n" diff --git a/debian/modules/http-fancyindex/template.html b/debian/modules/http-fancyindex/template.html index 8e478f81..b2a31745 100644 --- a/debian/modules/http-fancyindex/template.html +++ b/debian/modules/http-fancyindex/template.html @@ -55,9 +55,9 @@

Index of

File Name  ↓ File Size  ↓ Date  ↓ File Name  ↓ File Size  ↓ Date  ↓ 
- - - + + + diff --git a/debian/modules/http-geoip2/LICENSE b/debian/modules/http-geoip2/LICENSE new file mode 100644 index 00000000..fdc13a7f --- /dev/null +++ b/debian/modules/http-geoip2/LICENSE @@ -0,0 +1,23 @@ +Copyright (c) 2014, Lee Valentine +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, this + list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/debian/modules/http-geoip2/README.md b/debian/modules/http-geoip2/README.md new file mode 100644 index 00000000..a5aec977 --- /dev/null +++ b/debian/modules/http-geoip2/README.md @@ -0,0 +1,133 @@ +Description +=========== + +**ngx_http_geoip2_module** - creates variables with values from the maxmind geoip2 databases based on the client IP (default) or from a specific variable (supports both IPv4 and IPv6) + +The module now supports nginx streams and can be used in the same way the http module can be used. + +## Installing +First install [libmaxminddb](https://github.com/maxmind/libmaxminddb) as described in its [README.md +file](https://github.com/maxmind/libmaxminddb/blob/master/README.md#installing-from-a-tarball). + +#### Download nginx source +``` +wget http://nginx.org/download/nginx-VERSION.tar.gz +tar zxvf nginx-VERSION.tar.gz +cd nginx-VERSION +``` + +##### To build as a dynamic module (nginx 1.9.11+): +``` +./configure --add-dynamic-module=/path/to/ngx_http_geoip2_module +make +make install +``` + +This will produce ```objs/ngx_http_geoip2_module.so```. It can be copied to your nginx module path manually if you wish. + +Add the following line to your nginx.conf: +``` +load_module modules/ngx_http_geoip2_module.so; +``` + +##### To build as a static module: +``` +./configure --add-module=/path/to/ngx_http_geoip2_module +make +make install +``` + +## Download Maxmind GeoLite2 Database (optional) +The free GeoLite2 databases are available from [Maxminds website](http://dev.maxmind.com/geoip/geoip2/geolite2/) + +[GeoLite2 City](http://geolite.maxmind.com/download/geoip/database/GeoLite2-City.mmdb.gz) +[GeoLite2 Country](http://geolite.maxmind.com/download/geoip/database/GeoLite2-Country.mmdb.gz) + +## Example Usage: +``` +http { + ... + geoip2 /etc/maxmind-country.mmdb { + auto_reload 5m; + $geoip2_metadata_country_build metadata build_epoch; + $geoip2_data_country_code default=US source=$variable_with_ip country iso_code; + $geoip2_data_country_name country names en; + } + + geoip2 /etc/maxmind-city.mmdb { + $geoip2_data_city_name default=London city names en; + } + .... + + fastcgi_param COUNTRY_CODE $geoip2_data_country_code; + fastcgi_param COUNTRY_NAME $geoip2_data_country_name; + fastcgi_param CITY_NAME $geoip2_data_city_name; + .... +} + +stream { + ... + geoip2 /etc/maxmind-country.mmdb { + $geoip2_data_country_code default=US source=$remote_addr country iso_code; + } + ... +} +``` + +##### Metadata: +Retrieve metadata regarding the geoip database. +``` +$variable_name metadata +``` +Available fields: + - build_epoch: the build timestamp of the maxmind database. + - last_check: the last time the database was checked for changes (when using auto_reload) + - last_change: the last time the database was reloaded (when using auto_reload) + +##### Autoreload (default: disabled): +Enabling auto reload will have nginx check the modification time of the database at the specified +interval and reload it if it has changed. +``` +auto_reload +``` + +##### GeoIP: +``` +$variable_name [default= + "iso_code": + "US" + "names": + { + "de": + "USA" + "en": + "United States" + } + } + } + +$ mmdblookup --file /usr/share/GeoIP/GeoIP2-Country.mmdb --ip 8.8.8.8 country names en + + "United States" +``` + +This translates to: + +``` +$country_name "default=United States" source=$remote_addr country names en +``` diff --git a/debian/modules/http-geoip2/config b/debian/modules/http-geoip2/config new file mode 100644 index 00000000..48bf15d3 --- /dev/null +++ b/debian/modules/http-geoip2/config @@ -0,0 +1,43 @@ +ngx_feature="MaxmindDB library" +ngx_feature_name= +ngx_feature_run=no +ngx_feature_incs="#include " +ngx_feature_libs=-lmaxminddb +ngx_feature_test="MMDB_s mmdb" +. auto/feature + +ngx_addon_name="ngx_geoip2_module" + +if [ $ngx_found = yes ]; then + if test -n "$ngx_module_link"; then + if [ $HTTP != NO ]; then + ngx_module_type=HTTP + ngx_module_name="ngx_http_geoip2_module" + ngx_module_incs= + ngx_module_deps= + ngx_module_srcs="$ngx_addon_dir/ngx_http_geoip2_module.c" + ngx_module_libs="$ngx_feature_libs" + . auto/module + fi + + nginx_version=`awk '/^#define nginx_version / {print $3}' src/core/nginx.h` + if [ $STREAM != NO -a $nginx_version -gt 1011001 ]; then + ngx_module_type=STREAM + ngx_module_name="ngx_stream_geoip2_module" + ngx_module_incs= + ngx_module_deps= + ngx_module_srcs="$ngx_addon_dir/ngx_stream_geoip2_module.c" + ngx_module_libs="$ngx_feature_libs" + . auto/module + fi + else + HTTP_MODULES="$HTTP_MODULES ngx_http_geoip2_module" + NGX_ADDON_SRCS="$NGX_ADDON_SRCS $ngx_addon_dir/ngx_http_geoip2_module.c" + CORE_LIBS="$CORE_LIBS $ngx_feature_libs" + fi +else + cat << END +$0: error: the geoip2 module requires the maxminddb library. +END + exit 1 +fi diff --git a/debian/modules/http-geoip2/ngx_http_geoip2_module.c b/debian/modules/http-geoip2/ngx_http_geoip2_module.c new file mode 100644 index 00000000..d27c94d4 --- /dev/null +++ b/debian/modules/http-geoip2/ngx_http_geoip2_module.c @@ -0,0 +1,793 @@ +/* + * Copyright (C) Lee Valentine + * + * Based on nginx's 'ngx_http_geoip_module.c' by Igor Sysoev + */ + + +#include +#include +#include + +#include + + +typedef struct { + MMDB_s mmdb; + MMDB_lookup_result_s result; + time_t last_check; + time_t last_change; + time_t check_interval; +#if (NGX_HAVE_INET6) + uint8_t address[16]; +#else + unsigned long address; +#endif + ngx_queue_t queue; +} ngx_http_geoip2_db_t; + +typedef struct { + ngx_queue_t databases; + ngx_array_t *proxies; + ngx_flag_t proxy_recursive; +} ngx_http_geoip2_conf_t; + +typedef struct { + ngx_http_geoip2_db_t *database; + const char **lookup; + ngx_str_t default_value; + ngx_http_complex_value_t source; +} ngx_http_geoip2_ctx_t; + +typedef struct { + ngx_http_geoip2_db_t *database; + ngx_str_t metavalue; +} ngx_http_geoip2_metadata_t; + + +static ngx_int_t ngx_http_geoip2_variable(ngx_http_request_t *r, + ngx_http_variable_value_t *v, uintptr_t data); +static ngx_int_t ngx_http_geoip2_metadata(ngx_http_request_t *r, + ngx_http_variable_value_t *v, uintptr_t data); +static void *ngx_http_geoip2_create_conf(ngx_conf_t *cf); +static char *ngx_http_geoip2_init_conf(ngx_conf_t *cf, void *conf); +static char *ngx_http_geoip2(ngx_conf_t *cf, ngx_command_t *cmd, + void *conf); +static char *ngx_http_geoip2_parse_config(ngx_conf_t *cf, ngx_command_t *dummy, + void *conf); +static char *ngx_http_geoip2_add_variable(ngx_conf_t *cf, ngx_command_t *dummy, + void *conf); +static char *ngx_http_geoip2_add_variable_geodata(ngx_conf_t *cf, + ngx_http_geoip2_db_t *database); +static char *ngx_http_geoip2_add_variable_metadata(ngx_conf_t *cf, + ngx_http_geoip2_db_t *database); +static char *ngx_http_geoip2_proxy(ngx_conf_t *cf, ngx_command_t *cmd, + void *conf); +static ngx_int_t ngx_http_geoip2_cidr_value(ngx_conf_t *cf, ngx_str_t *net, + ngx_cidr_t *cidr); +static void ngx_http_geoip2_cleanup(void *data); +static ngx_int_t ngx_http_geoip2_init(ngx_conf_t *cf); + + +#define FORMAT(fmt, ...) do { \ + p = ngx_palloc(r->pool, NGX_OFF_T_LEN); \ + if (p == NULL) { \ + return NGX_ERROR; \ + } \ + v->len = ngx_sprintf(p, fmt, __VA_ARGS__) - p; \ + v->data = p; \ +} while (0) + +static ngx_command_t ngx_http_geoip2_commands[] = { + + { ngx_string("geoip2"), + NGX_HTTP_MAIN_CONF|NGX_CONF_BLOCK|NGX_CONF_TAKE1, + ngx_http_geoip2, + NGX_HTTP_MAIN_CONF_OFFSET, + 0, + NULL }, + + { ngx_string("geoip2_proxy"), + NGX_HTTP_MAIN_CONF|NGX_CONF_TAKE1, + ngx_http_geoip2_proxy, + NGX_HTTP_MAIN_CONF_OFFSET, + 0, + NULL }, + + { ngx_string("geoip2_proxy_recursive"), + NGX_HTTP_MAIN_CONF|NGX_CONF_FLAG, + ngx_conf_set_flag_slot, + NGX_HTTP_MAIN_CONF_OFFSET, + offsetof(ngx_http_geoip2_conf_t, proxy_recursive), + NULL }, + + ngx_null_command +}; + + +static ngx_http_module_t ngx_http_geoip2_module_ctx = { + NULL, /* preconfiguration */ + ngx_http_geoip2_init, /* postconfiguration */ + + ngx_http_geoip2_create_conf, /* create main configuration */ + ngx_http_geoip2_init_conf, /* init main configuration */ + + NULL, /* create server configuration */ + NULL, /* merge server configuration */ + + NULL, /* create location configuration */ + NULL /* merge location configuration */ +}; + + +ngx_module_t ngx_http_geoip2_module = { + NGX_MODULE_V1, + &ngx_http_geoip2_module_ctx, /* module context */ + ngx_http_geoip2_commands, /* module directives */ + NGX_HTTP_MODULE, /* module type */ + NULL, /* init master */ + NULL, /* init module */ + NULL, /* init process */ + NULL, /* init thread */ + NULL, /* exit thread */ + NULL, /* exit process */ + NULL, /* exit master */ + NGX_MODULE_V1_PADDING +}; + + +static ngx_int_t +ngx_http_geoip2_variable(ngx_http_request_t *r, ngx_http_variable_value_t *v, + uintptr_t data) +{ + ngx_http_geoip2_ctx_t *geoip2 = (ngx_http_geoip2_ctx_t *) data; + ngx_http_geoip2_db_t *database = geoip2->database; + int mmdb_error; + MMDB_entry_data_s entry_data; + ngx_http_geoip2_conf_t *gcf; + ngx_addr_t addr; + ngx_array_t *xfwd; + u_char *p; + ngx_str_t val; + +#if (NGX_HAVE_INET6) + uint8_t address[16], *addressp = address; +#else + unsigned long address; +#endif + + if (geoip2->source.value.len > 0) { + if (ngx_http_complex_value(r, &geoip2->source, &val) != NGX_OK) { + goto not_found; + } + + if (ngx_parse_addr(r->pool, &addr, val.data, val.len) != NGX_OK) { + goto not_found; + } + } else { + gcf = ngx_http_get_module_main_conf(r, ngx_http_geoip2_module); + addr.sockaddr = r->connection->sockaddr; + addr.socklen = r->connection->socklen; + + xfwd = &r->headers_in.x_forwarded_for; + + if (xfwd->nelts > 0 && gcf->proxies != NULL) { + (void) ngx_http_get_forwarded_addr(r, &addr, xfwd, NULL, + gcf->proxies, gcf->proxy_recursive); + } + } + + switch (addr.sockaddr->sa_family) { + case AF_INET: +#if (NGX_HAVE_INET6) + ngx_memset(addressp, 0, 12); + ngx_memcpy(addressp + 12, &((struct sockaddr_in *) + addr.sockaddr)->sin_addr.s_addr, 4); + break; + + case AF_INET6: + ngx_memcpy(addressp, &((struct sockaddr_in6 *) + addr.sockaddr)->sin6_addr.s6_addr, 16); +#else + address = ((struct sockaddr_in *)addr.sockaddr)->sin_addr.s_addr; +#endif + break; + + default: + goto not_found; + } + +#if (NGX_HAVE_INET6) + if (ngx_memcmp(&address, &database->address, sizeof(address)) + != 0) { +#else + if (address != database->address) { +#endif + memcpy(&database->address, &address, sizeof(address)); + database->result = MMDB_lookup_sockaddr(&database->mmdb, + addr.sockaddr, &mmdb_error); + + if (mmdb_error != MMDB_SUCCESS) { + goto not_found; + } + } + + if (!database->result.found_entry + || MMDB_aget_value(&database->result.entry, &entry_data, + geoip2->lookup) != MMDB_SUCCESS) { + goto not_found; + } + + if (!entry_data.has_data) { + goto not_found; + } + + switch (entry_data.type) { + case MMDB_DATA_TYPE_BOOLEAN: + FORMAT("%d", entry_data.boolean); + break; + case MMDB_DATA_TYPE_UTF8_STRING: + v->len = entry_data.data_size; + v->data = ngx_pnalloc(r->pool, v->len); + if (v->data == NULL) { + return NGX_ERROR; + } + ngx_memcpy(v->data, (u_char *) entry_data.utf8_string, v->len); + break; + case MMDB_DATA_TYPE_BYTES: + v->len = entry_data.data_size; + v->data = ngx_pnalloc(r->pool, v->len); + if (v->data == NULL) { + return NGX_ERROR; + } + ngx_memcpy(v->data, (u_char *) entry_data.bytes, v->len); + break; + case MMDB_DATA_TYPE_FLOAT: + FORMAT("%.5f", entry_data.float_value); + break; + case MMDB_DATA_TYPE_DOUBLE: + FORMAT("%.5f", entry_data.double_value); + break; + case MMDB_DATA_TYPE_UINT16: + FORMAT("%uD", entry_data.uint16); + break; + case MMDB_DATA_TYPE_UINT32: + FORMAT("%uD", entry_data.uint32); + break; + case MMDB_DATA_TYPE_INT32: + FORMAT("%D", entry_data.int32); + break; + case MMDB_DATA_TYPE_UINT64: + FORMAT("%uL", entry_data.uint64); + break; + case MMDB_DATA_TYPE_UINT128: ; +#if MMDB_UINT128_IS_BYTE_ARRAY + uint8_t *val = (uint8_t *)entry_data.uint128; + FORMAT( "0x%02x%02x%02x%02x%02x%02x%02x%02x" + "%02x%02x%02x%02x%02x%02x%02x%02x", + val[0], val[1], val[2], val[3], + val[4], val[5], val[6], val[7], + val[8], val[9], val[10], val[11], + val[12], val[13], val[14], val[15]); +#else + mmdb_uint128_t val = entry_data.uint128; + FORMAT("0x%016uxL%016uxL", + (uint64_t) (val >> 64), (uint64_t) val); +#endif + break; + default: + goto not_found; + } + + v->valid = 1; + v->no_cacheable = 0; + v->not_found = 0; + + return NGX_OK; + +not_found: + if (geoip2->default_value.len > 0) { + v->data = geoip2->default_value.data; + v->len = geoip2->default_value.len; + + v->valid = 1; + v->no_cacheable = 0; + v->not_found = 0; + } else { + v->not_found = 1; + } + + return NGX_OK; +} + + +static ngx_int_t +ngx_http_geoip2_metadata(ngx_http_request_t *r, ngx_http_variable_value_t *v, + uintptr_t data) +{ + ngx_http_geoip2_metadata_t *metadata = (ngx_http_geoip2_metadata_t *) data; + ngx_http_geoip2_db_t *database = metadata->database; + u_char *p; + + if (ngx_strncmp(metadata->metavalue.data, "build_epoch", 11) == 0) { + FORMAT("%uL", database->mmdb.metadata.build_epoch); + } else if (ngx_strncmp(metadata->metavalue.data, "last_check", 10) == 0) { + FORMAT("%T", database->last_check); + } else if (ngx_strncmp(metadata->metavalue.data, "last_change", 11) == 0) { + FORMAT("%T", database->last_change); + } else { + v->not_found = 1; + return NGX_OK; + } + + v->valid = 1; + v->no_cacheable = 0; + v->not_found = 0; + + return NGX_OK; +} + + +static void * +ngx_http_geoip2_create_conf(ngx_conf_t *cf) +{ + ngx_pool_cleanup_t *cln; + ngx_http_geoip2_conf_t *conf; + + conf = ngx_pcalloc(cf->pool, sizeof(ngx_http_geoip2_conf_t)); + if (conf == NULL) { + return NULL; + } + + conf->proxy_recursive = NGX_CONF_UNSET; + + cln = ngx_pool_cleanup_add(cf->pool, 0); + if (cln == NULL) { + return NULL; + } + + ngx_queue_init(&conf->databases); + + cln->handler = ngx_http_geoip2_cleanup; + cln->data = conf; + + return conf; +} + + +static char * +ngx_http_geoip2(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) +{ + ngx_http_geoip2_conf_t *gcf = conf; + ngx_str_t *value; + int status; + ngx_http_geoip2_db_t *database; + char *rv; + ngx_conf_t save; + ngx_queue_t *q; + + value = cf->args->elts; + + if (value[1].data && value[1].data[0] != '/') { + if (ngx_conf_full_name(cf->cycle, &value[1], 0) != NGX_OK) { + return NGX_CONF_ERROR; + } + } + + if (!ngx_queue_empty(&gcf->databases)) { + for (q = ngx_queue_head(&gcf->databases); + q != ngx_queue_sentinel(&gcf->databases); + q = ngx_queue_next(q)) + { + database = ngx_queue_data(q, ngx_http_geoip2_db_t, queue); + if (ngx_strcmp(value[1].data, database->mmdb.filename) == 0) { + ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, + "Duplicate GeoIP2 mmdb - %V", &value[1]); + return NGX_CONF_ERROR; + } + } + } + + database = ngx_pcalloc(cf->pool, sizeof(ngx_http_geoip2_db_t)); + if (database == NULL) { + return NGX_CONF_ERROR; + } + + ngx_queue_insert_tail(&gcf->databases, &database->queue); + database->last_check = database->last_change = ngx_time(); + + status = MMDB_open((char *) value[1].data, MMDB_MODE_MMAP, &database->mmdb); + + if (status != MMDB_SUCCESS) { + ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, + "MMDB_open(\"%V\") failed - %s", &value[1], + MMDB_strerror(status)); + return NGX_CONF_ERROR; + } + + save = *cf; + cf->handler = ngx_http_geoip2_parse_config; + cf->handler_conf = (void *) database; + + rv = ngx_conf_parse(cf, NULL); + *cf = save; + return rv; +} + + +static char * +ngx_http_geoip2_parse_config(ngx_conf_t *cf, ngx_command_t *dummy, void *conf) +{ + ngx_http_geoip2_db_t *database; + ngx_str_t *value; + time_t interval; + + value = cf->args->elts; + + if (value[0].data[0] == '$') { + return ngx_http_geoip2_add_variable(cf, dummy, conf); + } + + if (value[0].len == 11 + && ngx_strncmp(value[0].data, "auto_reload", 11) == 0) { + if ((int) cf->args->nelts != 2) { + ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, + "invalid number of arguments for auto_reload"); + return NGX_CONF_ERROR; + } + + interval = ngx_parse_time(&value[1], true); + + if (interval == (time_t) NGX_ERROR) { + ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, + "invalid interval for auto_reload \"%V\"", + value[1]); + return NGX_CONF_ERROR; + } + + + database = (ngx_http_geoip2_db_t *) conf; + database->check_interval = interval; + return NGX_CONF_OK; + } + + ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, + "invalid setting \"%V\"", &value[0]); + return NGX_CONF_ERROR; +} + + +static char * +ngx_http_geoip2_add_variable(ngx_conf_t *cf, ngx_command_t *dummy, void *conf) +{ + ngx_http_geoip2_db_t *database; + ngx_str_t *value; + int nelts; + + value = cf->args->elts; + + if (value[0].data[0] != '$') { + ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, + "invalid variable name \"%V\"", &value[0]); + return NGX_CONF_ERROR; + } + + value[0].len--; + value[0].data++; + + nelts = (int) cf->args->nelts; + database = (ngx_http_geoip2_db_t *) conf; + + if (nelts > 0 && value[1].len == 8 && ngx_strncmp(value[1].data, "metadata", 8) == 0) { + return ngx_http_geoip2_add_variable_metadata(cf, database); + } + + return ngx_http_geoip2_add_variable_geodata(cf, database); +} + + +static char * +ngx_http_geoip2_add_variable_metadata(ngx_conf_t *cf, ngx_http_geoip2_db_t *database) +{ + ngx_http_geoip2_metadata_t *metadata; + ngx_str_t *value, name; + ngx_http_variable_t *var; + + metadata = ngx_pcalloc(cf->pool, sizeof(ngx_http_geoip2_metadata_t)); + if (metadata == NULL) { + return NGX_CONF_ERROR; + } + + value = cf->args->elts; + name = value[0]; + + metadata->database = database; + metadata->metavalue = value[2]; + + var = ngx_http_add_variable(cf, &name, NGX_HTTP_VAR_CHANGEABLE); + if (var == NULL) { + return NGX_CONF_ERROR; + } + + var->get_handler = ngx_http_geoip2_metadata; + var->data = (uintptr_t) metadata; + + return NGX_CONF_OK; +} + + +static char * +ngx_http_geoip2_add_variable_geodata(ngx_conf_t *cf, ngx_http_geoip2_db_t *database) +{ + ngx_http_geoip2_ctx_t *geoip2; + ngx_http_compile_complex_value_t ccv; + ngx_str_t *value, name, source; + ngx_http_variable_t *var; + int i, nelts, idx; + + geoip2 = ngx_pcalloc(cf->pool, sizeof(ngx_http_geoip2_ctx_t)); + if (geoip2 == NULL) { + return NGX_CONF_ERROR; + } + + geoip2->database = database; + ngx_str_null(&source); + + value = cf->args->elts; + name = value[0]; + + nelts = (int) cf->args->nelts; + idx = 1; + + if (nelts > idx) { + for (i = idx; i < nelts; i++) { + if (ngx_strnstr(value[idx].data, "=", value[idx].len) == NULL) { + break; + } + + if (value[idx].len > 8 && ngx_strncmp(value[idx].data, "default=", 8) == 0) { + if (geoip2->default_value.len > 0) { + ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, + "default has already been declared for \"$%V\"", &name); + return NGX_CONF_ERROR; + } + + geoip2->default_value.len = value[idx].len - 8; + geoip2->default_value.data = value[idx].data + 8; + } else if (value[idx].len > 7 && ngx_strncmp(value[idx].data, "source=", 7) == 0) { + if (source.len > 0) { + ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, + "source has already been declared for \"$%V\"", &name); + return NGX_CONF_ERROR; + } + + source.len = value[idx].len - 7; + source.data = value[idx].data + 7; + + if (source.data[0] != '$') { + ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, + "invalid source variable name \"%V\"", &source); + return NGX_CONF_ERROR; + } + + ngx_memzero(&ccv, sizeof(ngx_http_compile_complex_value_t)); + ccv.cf = cf; + ccv.value = &source; + ccv.complex_value = &geoip2->source; + + if (ngx_http_compile_complex_value(&ccv) != NGX_OK) { + ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, + "unable to compile \"%V\" for \"$%V\"", &source, &name); + return NGX_CONF_ERROR; + } + } else { + ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, + "invalid setting \"%V\" for \"$%V\"", &value[idx], &name); + return NGX_CONF_ERROR; + } + + idx++; + } + } + + var = ngx_http_add_variable(cf, &name, NGX_HTTP_VAR_CHANGEABLE); + if (var == NULL) { + return NGX_CONF_ERROR; + } + + geoip2->lookup = ngx_pcalloc(cf->pool, sizeof(const char *) * + (cf->args->nelts - (idx - 1))); + + if (geoip2->lookup == NULL) { + return NGX_CONF_ERROR; + } + + for (i = idx; i < nelts; i++) { + geoip2->lookup[i - idx] = (char *) value[i].data; + } + geoip2->lookup[i - idx] = NULL; + + var->get_handler = ngx_http_geoip2_variable; + var->data = (uintptr_t) geoip2; + + return NGX_CONF_OK; +} + + +static char * +ngx_http_geoip2_init_conf(ngx_conf_t *cf, void *conf) +{ + ngx_http_geoip2_conf_t *gcf = conf; + ngx_conf_init_value(gcf->proxy_recursive, 0); + return NGX_CONF_OK; +} + + +static char * +ngx_http_geoip2_proxy(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) +{ + ngx_http_geoip2_conf_t *gcf = conf; + ngx_str_t *value; + ngx_cidr_t cidr, *c; + + value = cf->args->elts; + + if (ngx_http_geoip2_cidr_value(cf, &value[1], &cidr) != NGX_OK) { + return NGX_CONF_ERROR; + } + + if (gcf->proxies == NULL) { + gcf->proxies = ngx_array_create(cf->pool, 4, sizeof(ngx_cidr_t)); + if (gcf->proxies == NULL) { + return NGX_CONF_ERROR; + } + } + + c = ngx_array_push(gcf->proxies); + if (c == NULL) { + return NGX_CONF_ERROR; + } + + *c = cidr; + + return NGX_CONF_OK; +} + + +static ngx_int_t +ngx_http_geoip2_cidr_value(ngx_conf_t *cf, ngx_str_t *net, ngx_cidr_t *cidr) +{ + ngx_int_t rc; + + if (ngx_strcmp(net->data, "255.255.255.255") == 0) { + cidr->family = AF_INET; + cidr->u.in.addr = 0xffffffff; + cidr->u.in.mask = 0xffffffff; + + return NGX_OK; + } + + rc = ngx_ptocidr(net, cidr); + + if (rc == NGX_ERROR) { + ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, + "invalid network \"%V\"", net); + return NGX_ERROR; + } + + if (rc == NGX_DONE) { + ngx_conf_log_error(NGX_LOG_WARN, cf, 0, + "low address bits of %V are meaningless", net); + } + + return NGX_OK; +} + + +static void +ngx_http_geoip2_cleanup(void *data) +{ + ngx_http_geoip2_conf_t *gcf = data; + ngx_queue_t *q; + ngx_http_geoip2_db_t *database; + + while (!ngx_queue_empty(&gcf->databases)) { + q = ngx_queue_head(&gcf->databases); + ngx_queue_remove(q); + database = ngx_queue_data(q, ngx_http_geoip2_db_t, queue); + MMDB_close(&database->mmdb); + } +} + + +static ngx_int_t +ngx_http_geoip2_log_handler(ngx_http_request_t *r) +{ + int status; + MMDB_s tmpdb; + ngx_queue_t *q; + ngx_file_info_t fi; + ngx_http_geoip2_db_t *database; + ngx_http_geoip2_conf_t *gcf; + + ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, + "geoip2 http log handler"); + + gcf = ngx_http_get_module_main_conf(r, ngx_http_geoip2_module); + + if (ngx_queue_empty(&gcf->databases)) { + return NGX_OK; + } + + for (q = ngx_queue_head(&gcf->databases); + q != ngx_queue_sentinel(&gcf->databases); + q = ngx_queue_next(q)) + { + database = ngx_queue_data(q, ngx_http_geoip2_db_t, queue); + if (database->check_interval == 0) { + continue; + } + + if ((database->last_check + database->check_interval) + > ngx_time()) + { + continue; + } + + database->last_check = ngx_time(); + + if (ngx_file_info(database->mmdb.filename, &fi) == NGX_FILE_ERROR) { + ngx_log_error(NGX_LOG_EMERG, r->connection->log, ngx_errno, + ngx_file_info_n " \"%s\" failed", + database->mmdb.filename); + + continue; + } + + if (ngx_file_mtime(&fi) <= database->last_change) { + continue; + } + + /* do the reload */ + + ngx_memzero(&tmpdb, sizeof(MMDB_s)); + status = MMDB_open(database->mmdb.filename, MMDB_MODE_MMAP, &tmpdb); + + if (status != MMDB_SUCCESS) { + ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, + "MMDB_open(\"%s\") failed to reload - %s", + database->mmdb.filename, MMDB_strerror(status)); + + continue; + } + + database->last_change = ngx_file_mtime(&fi); + MMDB_close(&database->mmdb); + database->mmdb = tmpdb; + + ngx_log_error(NGX_LOG_INFO, r->connection->log, 0, + "Reload MMDB \"%s\"", + database->mmdb.filename); + } + + return NGX_OK; +} + + +static ngx_int_t +ngx_http_geoip2_init(ngx_conf_t *cf) +{ + ngx_http_handler_pt *h; + ngx_http_core_main_conf_t *cmcf; + + cmcf = ngx_http_conf_get_module_main_conf(cf, ngx_http_core_module); + + h = ngx_array_push(&cmcf->phases[NGX_HTTP_LOG_PHASE].handlers); + if (h == NULL) { + return NGX_ERROR; + } + + *h = ngx_http_geoip2_log_handler; + + return NGX_OK; +} diff --git a/debian/modules/http-geoip2/ngx_stream_geoip2_module.c b/debian/modules/http-geoip2/ngx_stream_geoip2_module.c new file mode 100644 index 00000000..eb590827 --- /dev/null +++ b/debian/modules/http-geoip2/ngx_stream_geoip2_module.c @@ -0,0 +1,694 @@ +/* + * Copyright (C) Lee Valentine + * Copyright (C) Andrei Belov + * + * Based on nginx's 'ngx_stream_geoip_module.c' by Igor Sysoev + */ + + +#include +#include +#include + +#include + + +typedef struct { + MMDB_s mmdb; + MMDB_lookup_result_s result; + time_t last_check; + time_t last_change; + time_t check_interval; +#if (NGX_HAVE_INET6) + uint8_t address[16]; +#else + unsigned long address; +#endif + ngx_queue_t queue; +} ngx_stream_geoip2_db_t; + +typedef struct { + ngx_queue_t databases; +} ngx_stream_geoip2_conf_t; + +typedef struct { + ngx_stream_geoip2_db_t *database; + const char **lookup; + ngx_str_t default_value; + ngx_stream_complex_value_t source; +} ngx_stream_geoip2_ctx_t; + +typedef struct { + ngx_stream_geoip2_db_t *database; + ngx_str_t metavalue; +} ngx_stream_geoip2_metadata_t; + + +static ngx_int_t ngx_stream_geoip2_variable(ngx_stream_session_t *s, + ngx_stream_variable_value_t *v, uintptr_t data); +static ngx_int_t ngx_stream_geoip2_metadata(ngx_stream_session_t *s, + ngx_stream_variable_value_t *v, uintptr_t data); +static void *ngx_stream_geoip2_create_conf(ngx_conf_t *cf); +static char *ngx_stream_geoip2(ngx_conf_t *cf, ngx_command_t *cmd, + void *conf); +static char *ngx_stream_geoip2_parse_config(ngx_conf_t *cf, ngx_command_t *dummy, + void *conf); +static char *ngx_stream_geoip2(ngx_conf_t *cf, ngx_command_t *cmd, + void *conf); +static char *ngx_stream_geoip2_add_variable(ngx_conf_t *cf, ngx_command_t *dummy, + void *conf); +static char *ngx_stream_geoip2_add_variable_geodata(ngx_conf_t *cf, + ngx_stream_geoip2_db_t *database); +static char *ngx_stream_geoip2_add_variable_metadata(ngx_conf_t *cf, + ngx_stream_geoip2_db_t *database); +static void ngx_stream_geoip2_cleanup(void *data); +static ngx_int_t ngx_stream_geoip2_init(ngx_conf_t *cf); + + +#define FORMAT(fmt, ...) do { \ + p = ngx_palloc(s->connection->pool, NGX_OFF_T_LEN); \ + if (p == NULL) { \ + return NGX_ERROR; \ + } \ + v->len = ngx_sprintf(p, fmt, __VA_ARGS__) - p; \ + v->data = p; \ +} while (0) + +static ngx_command_t ngx_stream_geoip2_commands[] = { + + { ngx_string("geoip2"), + NGX_STREAM_MAIN_CONF|NGX_CONF_BLOCK|NGX_CONF_TAKE1, + ngx_stream_geoip2, + NGX_STREAM_MAIN_CONF_OFFSET, + 0, + NULL }, + + ngx_null_command +}; + + +static ngx_stream_module_t ngx_stream_geoip2_module_ctx = { + NULL, /* preconfiguration */ + ngx_stream_geoip2_init, /* postconfiguration */ + + ngx_stream_geoip2_create_conf, /* create main configuration */ + NULL, /* init main configuration */ + + NULL, /* create server configuration */ + NULL /* merge server configuration */ +}; + + +ngx_module_t ngx_stream_geoip2_module = { + NGX_MODULE_V1, + &ngx_stream_geoip2_module_ctx, /* module context */ + ngx_stream_geoip2_commands, /* module directives */ + NGX_STREAM_MODULE, /* module type */ + NULL, /* init master */ + NULL, /* init module */ + NULL, /* init process */ + NULL, /* init thread */ + NULL, /* exit thread */ + NULL, /* exit process */ + NULL, /* exit master */ + NGX_MODULE_V1_PADDING +}; + + +static ngx_int_t +ngx_stream_geoip2_variable(ngx_stream_session_t *s, ngx_stream_variable_value_t *v, + uintptr_t data) +{ + int mmdb_error; + u_char *p; + ngx_str_t val; + ngx_addr_t addr; + MMDB_entry_data_s entry_data; + ngx_stream_geoip2_ctx_t *geoip2 = (ngx_stream_geoip2_ctx_t *) data; + ngx_stream_geoip2_db_t *database = geoip2->database; + +#if (NGX_HAVE_INET6) + uint8_t address[16], *addressp = address; +#else + unsigned long address; +#endif + + if (geoip2->source.value.len > 0) { + if (ngx_stream_complex_value(s, &geoip2->source, &val) != NGX_OK) { + goto not_found; + } + + if (ngx_parse_addr(s->connection->pool, &addr, val.data, val.len) != NGX_OK) { + goto not_found; + } + } else { + addr.sockaddr = s->connection->sockaddr; + addr.socklen = s->connection->socklen; + } + + switch (addr.sockaddr->sa_family) { + case AF_INET: +#if (NGX_HAVE_INET6) + ngx_memset(addressp, 0, 12); + ngx_memcpy(addressp + 12, &((struct sockaddr_in *) + addr.sockaddr)->sin_addr.s_addr, 4); + break; + + case AF_INET6: + ngx_memcpy(addressp, &((struct sockaddr_in6 *) + addr.sockaddr)->sin6_addr.s6_addr, 16); +#else + address = ((struct sockaddr_in *)addr.sockaddr)->sin_addr.s_addr; +#endif + break; + + default: + goto not_found; + } + +#if (NGX_HAVE_INET6) + if (ngx_memcmp(&address, &database->address, sizeof(address)) != 0) { +#else + if (address != database->address) { +#endif + memcpy(&database->address, &address, sizeof(address)); + database->result = MMDB_lookup_sockaddr(&database->mmdb, + addr.sockaddr, &mmdb_error); + + if (mmdb_error != MMDB_SUCCESS) { + goto not_found; + } + } + + if (!database->result.found_entry + || MMDB_aget_value(&database->result.entry, &entry_data, geoip2->lookup) + != MMDB_SUCCESS) + { + goto not_found; + } + + if (!entry_data.has_data) { + goto not_found; + } + + switch (entry_data.type) { + case MMDB_DATA_TYPE_BOOLEAN: + FORMAT("%d", entry_data.boolean); + break; + case MMDB_DATA_TYPE_UTF8_STRING: + v->len = entry_data.data_size; + v->data = ngx_pnalloc(s->connection->pool, v->len); + if (v->data == NULL) { + return NGX_ERROR; + } + ngx_memcpy(v->data, (u_char *) entry_data.utf8_string, v->len); + break; + case MMDB_DATA_TYPE_BYTES: + v->len = entry_data.data_size; + v->data = ngx_pnalloc(s->connection->pool, v->len); + if (v->data == NULL) { + return NGX_ERROR; + } + ngx_memcpy(v->data, (u_char *) entry_data.bytes, v->len); + break; + case MMDB_DATA_TYPE_FLOAT: + FORMAT("%.5f", entry_data.float_value); + break; + case MMDB_DATA_TYPE_DOUBLE: + FORMAT("%.5f", entry_data.double_value); + break; + case MMDB_DATA_TYPE_UINT16: + FORMAT("%uD", entry_data.uint16); + break; + case MMDB_DATA_TYPE_UINT32: + FORMAT("%uD", entry_data.uint32); + break; + case MMDB_DATA_TYPE_INT32: + FORMAT("%D", entry_data.int32); + break; + case MMDB_DATA_TYPE_UINT64: + FORMAT("%uL", entry_data.uint64); + break; + case MMDB_DATA_TYPE_UINT128: ; +#if MMDB_UINT128_IS_BYTE_ARRAY + uint8_t *val = (uint8_t *) entry_data.uint128; + FORMAT("0x%02x%02x%02x%02x%02x%02x%02x%02x" + "%02x%02x%02x%02x%02x%02x%02x%02x", + val[0], val[1], val[2], val[3], + val[4], val[5], val[6], val[7], + val[8], val[9], val[10], val[11], + val[12], val[13], val[14], val[15]); +#else + mmdb_uint128_t val = entry_data.uint128; + FORMAT("0x%016uxL%016uxL", + (uint64_t) (val >> 64), (uint64_t) val); +#endif + break; + default: + goto not_found; + } + + v->valid = 1; + v->no_cacheable = 0; + v->not_found = 0; + + return NGX_OK; + +not_found: + if (geoip2->default_value.len > 0) { + v->data = geoip2->default_value.data; + v->len = geoip2->default_value.len; + + v->valid = 1; + v->no_cacheable = 0; + v->not_found = 0; + + return NGX_OK; + } + + v->not_found = 1; + + return NGX_OK; +} + + +static ngx_int_t +ngx_stream_geoip2_metadata(ngx_stream_session_t *s, ngx_stream_variable_value_t *v, + uintptr_t data) +{ + ngx_stream_geoip2_metadata_t *metadata = (ngx_stream_geoip2_metadata_t *) data; + ngx_stream_geoip2_db_t *database = metadata->database; + u_char *p; + + if (ngx_strncmp(metadata->metavalue.data, "build_epoch", 11) == 0) { + FORMAT("%uL", database->mmdb.metadata.build_epoch); + } else if (ngx_strncmp(metadata->metavalue.data, "last_check", 10) == 0) { + FORMAT("%T", database->last_check); + } else if (ngx_strncmp(metadata->metavalue.data, "last_change", 11) == 0) { + FORMAT("%T", database->last_change); + } else { + v->not_found = 1; + return NGX_OK; + } + + v->valid = 1; + v->no_cacheable = 0; + v->not_found = 0; + + return NGX_OK; +} + + +static void * +ngx_stream_geoip2_create_conf(ngx_conf_t *cf) +{ + ngx_pool_cleanup_t *cln; + ngx_stream_geoip2_conf_t *conf; + + conf = ngx_pcalloc(cf->pool, sizeof(ngx_stream_geoip2_conf_t)); + if (conf == NULL) { + return NULL; + } + + cln = ngx_pool_cleanup_add(cf->pool, 0); + if (cln == NULL) { + return NULL; + } + + ngx_queue_init(&conf->databases); + + cln->handler = ngx_stream_geoip2_cleanup; + cln->data = conf; + + return conf; +} + + +static char * +ngx_stream_geoip2(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) +{ + int status; + char *rv; + ngx_str_t *value; + ngx_conf_t save; + ngx_stream_geoip2_db_t *database; + ngx_stream_geoip2_conf_t *gcf = conf; + ngx_queue_t *q; + + value = cf->args->elts; + + if (value[1].data && value[1].data[0] != '/') { + if (ngx_conf_full_name(cf->cycle, &value[1], 0) != NGX_OK) { + return NGX_CONF_ERROR; + } + } + + if (!ngx_queue_empty(&gcf->databases)) { + for (q = ngx_queue_head(&gcf->databases); + q != ngx_queue_sentinel(&gcf->databases); + q = ngx_queue_next(q)) + { + database = ngx_queue_data(q, ngx_stream_geoip2_db_t, queue); + if (ngx_strcmp(value[1].data, database->mmdb.filename) == 0) { + ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, + "Duplicate GeoIP2 mmdb - %V", &value[1]); + return NGX_CONF_ERROR; + } + } + } + + database = ngx_pcalloc(cf->pool, sizeof(ngx_stream_geoip2_db_t)); + if (database == NULL) { + return NGX_CONF_ERROR; + } + + ngx_queue_insert_tail(&gcf->databases, &database->queue); + database->last_check = database->last_change = ngx_time(); + + status = MMDB_open((char *) value[1].data, MMDB_MODE_MMAP, &database->mmdb); + + if (status != MMDB_SUCCESS) { + ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, + "MMDB_open(\"%V\") failed - %s", &value[1], + MMDB_strerror(status)); + return NGX_CONF_ERROR; + } + + save = *cf; + cf->handler = ngx_stream_geoip2_parse_config; + cf->handler_conf = (void *) database; + + rv = ngx_conf_parse(cf, NULL); + *cf = save; + return rv; +} + + +static char * +ngx_stream_geoip2_parse_config(ngx_conf_t *cf, ngx_command_t *dummy, void *conf) +{ + ngx_stream_geoip2_db_t *database; + ngx_str_t *value; + time_t interval; + + value = cf->args->elts; + + if (value[0].data[0] == '$') { + return ngx_stream_geoip2_add_variable(cf, dummy, conf); + } + + if (value[0].len == 11 + && ngx_strncmp(value[0].data, "auto_reload", 11) == 0) { + if ((int) cf->args->nelts != 2) { + ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, + "invalid number of arguments for auto_reload"); + return NGX_CONF_ERROR; + } + + interval = ngx_parse_time(&value[1], true); + + if (interval == (time_t) NGX_ERROR) { + ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, + "invalid interval for auto_reload \"%V\"", + value[1]); + return NGX_CONF_ERROR; + } + + + database = (ngx_stream_geoip2_db_t *) conf; + database->check_interval = interval; + return NGX_CONF_OK; + } + + ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, + "invalid setting \"%V\"", &value[0]); + return NGX_CONF_ERROR; +} + + +static char * +ngx_stream_geoip2_add_variable(ngx_conf_t *cf, ngx_command_t *dummy, void *conf) +{ + ngx_stream_geoip2_db_t *database; + ngx_str_t *value; + int nelts; + + value = cf->args->elts; + + if (value[0].data[0] != '$') { + ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, + "invalid variable name \"%V\"", &value[0]); + return NGX_CONF_ERROR; + } + + value[0].len--; + value[0].data++; + + nelts = (int) cf->args->nelts; + database = (ngx_stream_geoip2_db_t *) conf; + + if (nelts > 0 && value[1].len == 8 && ngx_strncmp(value[1].data, "metadata", 8) == 0) { + return ngx_stream_geoip2_add_variable_metadata(cf, database); + } + + return ngx_stream_geoip2_add_variable_geodata(cf, database); +} + + +static char * +ngx_stream_geoip2_add_variable_metadata(ngx_conf_t *cf, ngx_stream_geoip2_db_t *database) +{ + ngx_stream_geoip2_metadata_t *metadata; + ngx_str_t *value, name; + ngx_stream_variable_t *var; + + metadata = ngx_pcalloc(cf->pool, sizeof(ngx_stream_geoip2_metadata_t)); + if (metadata == NULL) { + return NGX_CONF_ERROR; + } + + value = cf->args->elts; + name = value[0]; + + metadata->database = database; + metadata->metavalue = value[2]; + + var = ngx_stream_add_variable(cf, &name, NGX_STREAM_VAR_CHANGEABLE); + if (var == NULL) { + return NGX_CONF_ERROR; + } + + var->get_handler = ngx_stream_geoip2_metadata; + var->data = (uintptr_t) metadata; + + return NGX_CONF_OK; +} + + +static char * +ngx_stream_geoip2_add_variable_geodata(ngx_conf_t *cf, ngx_stream_geoip2_db_t *database) +{ + ngx_stream_geoip2_ctx_t *geoip2; + ngx_stream_compile_complex_value_t ccv; + ngx_str_t *value, name, source; + ngx_stream_variable_t *var; + int i, nelts, idx; + + geoip2 = ngx_pcalloc(cf->pool, sizeof(ngx_stream_geoip2_ctx_t)); + if (geoip2 == NULL) { + return NGX_CONF_ERROR; + } + + geoip2->database = database; + ngx_str_null(&source); + + value = cf->args->elts; + name = value[0]; + + nelts = (int) cf->args->nelts; + idx = 1; + + if (nelts > idx) { + for (i = idx; i < nelts; i++) { + if (ngx_strnstr(value[idx].data, "=", value[idx].len) == NULL) { + break; + } + + if (value[idx].len > 8 && ngx_strncmp(value[idx].data, "default=", 8) == 0) { + if (geoip2->default_value.len > 0) { + ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, + "default has already been declared for \"$%V\"", &name); + return NGX_CONF_ERROR; + } + + geoip2->default_value.len = value[idx].len - 8; + geoip2->default_value.data = value[idx].data + 8; + + } else if (value[idx].len > 7 && ngx_strncmp(value[idx].data, "source=", 7) == 0) { + if (source.len > 0) { + ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, + "source has already been declared for \"$%V\"", &name); + return NGX_CONF_ERROR; + } + + source.len = value[idx].len - 7; + source.data = value[idx].data + 7; + + if (source.data[0] != '$') { + ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, + "invalid source variable name \"%V\"", &source); + return NGX_CONF_ERROR; + } + + ngx_memzero(&ccv, sizeof(ngx_stream_compile_complex_value_t)); + ccv.cf = cf; + ccv.value = &source; + ccv.complex_value = &geoip2->source; + + if (ngx_stream_compile_complex_value(&ccv) != NGX_OK) { + ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, + "unable to compile \"%V\" for \"$%V\"", &source, &name); + return NGX_CONF_ERROR; + } + + } else { + ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, + "invalid setting \"%V\" for \"$%V\"", &value[idx], &name); + return NGX_CONF_ERROR; + } + + idx++; + } + } + + var = ngx_stream_add_variable(cf, &name, NGX_STREAM_VAR_CHANGEABLE); + if (var == NULL) { + return NGX_CONF_ERROR; + } + + geoip2->lookup = ngx_pcalloc(cf->pool, + sizeof(const char *) * (cf->args->nelts - (idx - 1))); + + if (geoip2->lookup == NULL) { + return NGX_CONF_ERROR; + } + + for (i = idx; i < nelts; i++) { + geoip2->lookup[i - idx] = (char *) value[i].data; + } + geoip2->lookup[i - idx] = NULL; + + var->get_handler = ngx_stream_geoip2_variable; + var->data = (uintptr_t) geoip2; + + return NGX_CONF_OK; +} + + +static void +ngx_stream_geoip2_cleanup(void *data) +{ + ngx_queue_t *q; + ngx_stream_geoip2_db_t *database; + ngx_stream_geoip2_conf_t *gcf = data; + + while (!ngx_queue_empty(&gcf->databases)) { + q = ngx_queue_head(&gcf->databases); + ngx_queue_remove(q); + database = ngx_queue_data(q, ngx_stream_geoip2_db_t, queue); + MMDB_close(&database->mmdb); + } +} + + +static ngx_int_t +ngx_stream_geoip2_log_handler(ngx_stream_session_t *s) +{ + int status; + MMDB_s tmpdb; + ngx_queue_t *q; + ngx_file_info_t fi; + ngx_stream_geoip2_db_t *database; + ngx_stream_geoip2_conf_t *gcf; + + ngx_log_debug0(NGX_LOG_DEBUG_STREAM, s->connection->log, 0, + "geoip2 stream log handler"); + + gcf = ngx_stream_get_module_main_conf(s, ngx_stream_geoip2_module); + + if (ngx_queue_empty(&gcf->databases)) { + return NGX_OK; + } + + for (q = ngx_queue_head(&gcf->databases); + q != ngx_queue_sentinel(&gcf->databases); + q = ngx_queue_next(q)) + { + database = ngx_queue_data(q, ngx_stream_geoip2_db_t, queue); + if (database->check_interval == 0) { + continue; + } + + if ((database->last_check + database->check_interval) + > ngx_time()) + { + continue; + } + + database->last_check = ngx_time(); + + if (ngx_file_info(database->mmdb.filename, &fi) == NGX_FILE_ERROR) { + ngx_log_error(NGX_LOG_EMERG, s->connection->log, ngx_errno, + ngx_file_info_n " \"%s\" failed", + database->mmdb.filename); + + continue; + } + + if (ngx_file_mtime(&fi) <= database->last_change) { + continue; + } + + /* do the reload */ + + ngx_memzero(&tmpdb, sizeof(MMDB_s)); + status = MMDB_open(database->mmdb.filename, MMDB_MODE_MMAP, &tmpdb); + + if (status != MMDB_SUCCESS) { + ngx_log_error(NGX_LOG_ERR, s->connection->log, 0, + "MMDB_open(\"%s\") failed to reload - %s", + database->mmdb.filename, MMDB_strerror(status)); + + continue; + } + + database->last_change = ngx_file_mtime(&fi); + MMDB_close(&database->mmdb); + database->mmdb = tmpdb; + + ngx_log_error(NGX_LOG_INFO, s->connection->log, 0, + "Reload MMDB \"%s\"", + database->mmdb.filename); + } + + return NGX_OK; +} + + +static ngx_int_t +ngx_stream_geoip2_init(ngx_conf_t *cf) +{ + ngx_stream_handler_pt *h; + ngx_stream_core_main_conf_t *cmcf; + + cmcf = ngx_stream_conf_get_module_main_conf(cf, ngx_stream_core_module); + + h = ngx_array_push(&cmcf->phases[NGX_STREAM_LOG_PHASE].handlers); + if (h == NULL) { + return NGX_ERROR; + } + + *h = ngx_stream_geoip2_log_handler; + + return NGX_OK; +} diff --git a/debian/modules/nchan/README.md b/debian/modules/nchan/README.md index ee43ac9c..152396d0 100644 --- a/debian/modules/nchan/README.md +++ b/debian/modules/nchan/README.md @@ -1,57 +1,56 @@ - + -https://nchan.slact.net +https://nchan.io Nchan is a scalable, flexible pub/sub server for the modern web, built as a module for the [Nginx](http://nginx.org) web server. It can be configured as a standalone server, or as a shim between your application and hundreds, thousands, or millions of live subscribers. It can buffer messages in memory, on-disk, or via [Redis](http://redis.io). All connections are handled asynchronously and distributed among any number of worker processes. It can also scale to many Nginx servers with [Redis](http://redis.io). Messages are [published](#publisher-endpoints) to channels with HTTP `POST` requests or Websocket, and [subscribed](#subscriber-endpoint) also through [Websocket](#websocket), [long-polling](#long-polling), [EventSource](#eventsource) (SSE), old-fashioned [interval polling](#interval-polling), [and](#http-chunked-transfer) [more](#http-multipart-mixed). -In a web browser, you can use Websocket or EventSource directly, or the [NchanSubscriber.js](https://github.com/slact/nchan/blob/master/NchanSubscriber.js) wrapper library. It supports Long-Polling, EventSource, and resumable Websockets, and has a few other added convenience options. +In a web browser, you can use Websocket or EventSource natively, or the [NchanSubscriber.js](https://github.com/slact/nchan.js) wrapper library. It supports Long-Polling, EventSource, and resumable Websockets, and has a few other added convenience options. It's also available on [NPM](https://www.npmjs.com/package/nchan). ## Features - - RESTful, HTTP-native API. - - Supports [Websocket](https://nchan.slact.net/#websocket), [EventSource (Server-Sent Events)](https://nchan.slact.net/#eventsource), [Long-Polling](https://nchan.slact.net/#long-polling) and other HTTP-based subscribers. - - No-repeat, no-loss message delivery guarantees with per-channel configurable message buffers. + - RESTful, HTTP-native [API](#publishing-messages). + - Supports [Websocket](#websocket), [EventSource (Server-Sent Events)](#eventsource), [Long-Polling](#long-polling) and other HTTP-based subscribers. + - Per-channel configurable message buffers with no-repeat, no-loss message delivery guarantees. - Subscribe to [hundreds of channels](#channel-multiplexing) over a single subscriber connection. - - HTTP request [callbacks and hooks](https://nchan.slact.net/details#application-callbacks) for easy integration. - - Introspection with [channel events](https://nchan.slact.net/details#channel-events) and [url for monitoring performance statistics](https://nchan.slact.net/details#nchan_stub_status). - - Fast ephemeral local message storage and optional, slower, persistent storage with [Redis](https://nchan.slact.net/details#connecting-to-a-redis-server). - - Horizontally scalable (using [Redis](https://nchan.slact.net/details#connecting-to-a-redis-server)). - - Highly Available with no single point of failure (using [Redis Cluster](https://nchan.slact.net/details#redis-cluster)). - - + - HTTP request [callbacks and hooks](#hooks-and-callbacks) for easy integration. + - Introspection with [channel events](#channel-events) and [url for monitoring performance statistics](#nchan_stub_status-stats). + - Channel [group](#channel-groups) usage [accounting and limits](#limits-and-accounting). + - Fast, nonblocking [shared-memory local message storage](#memory-storage) and optional, slower, persistent storage with [Redis](#redis). + - Horizontally scalable (using [Redis](#redis)). + - Auto-failover and [high availability](#high-availability) with no single point of failure using [Redis Cluster](#redis-cluster). ## Status and History -The latest Nchan release is v1.0.8 (November 28, 2016) ([changelog](https://nchan.slact.net/changelog)). +The latest Nchan release is 1.2.7 (March 17, 2020) ([changelog](https://nchan.io/changelog)). -The first iteration of Nchan was written in 2009-2010 as the [Nginx HTTP Push Module](https://pushmodule.slact.net), and was vastly refactored into its present state in 2014-2016. The present release is in the **testing** phase. The core features and old functionality are thoroughly tested and stable. Some of the new functionality, especially Redis Cluster may be a bit buggy. +The first iteration of Nchan was written in 2009-2010 as the [Nginx HTTP Push Module](https://pushmodule.slact.net), and was vastly refactored into its present state in 2014-2016. #### Upgrade from Nginx HTTP Push Module -Although Nchan is backwards-compatible with all Push Module configuration directives, some of the more unusual and rarely used settings have been disabled and will be ignored (with a warning). See the [upgrade page](https://nchan.slact.net/upgrade) for a detailed list of changes and improvements, as well as a full list of incompatibilities. +Although Nchan is backwards-compatible with all Push Module configuration directives, some of the more unusual and rarely used settings have been disabled and will be ignored (with a warning). See the [upgrade page](https://nchan.io/upgrade) for a detailed list of changes and improvements, as well as a full list of incompatibilities. ## Does it scale? -benchmarking internal subscriber response times +benchmarking internal subscriber response times Yes it does. Like Nginx, Nchan can easily handle as much traffic as you can throw at it. I've tried to benchmark it, but my benchmarking tools are much slower than Nchan. The data I've gathered is on how long Nchan itself takes to respond to every subscriber after publishing a message -- this excludes TCP handshake times and internal HTTP request parsing. Basically, it measures how Nchan scales assuming all other components are already tuned for scalability. The graphed data are averages of 5 runs with 50-byte messages. -With a well-tuned OS and network stack on commodity server hardware, expect to handle upwards of 300K concurrent subscribers per second at minimal CPU load. Nchan can also be scaled out to multiple Nginx instances using the [Redis storage engine](#nchan_use_redis), and that too can be scaled up beyond a single-point-of-failure by using [Redis Cluster](https://nchan.slact.net/details#using-redis). +With a well-tuned OS and network stack on commodity server hardware, expect to handle upwards of 300K concurrent subscribers per second at minimal CPU load. Nchan can also be scaled out to multiple Nginx instances using the [Redis storage engine](#nchan_use_redis), and that too can be scaled up beyond a single-point-of-failure by using [Redis Cluster](#redis-cluster). -Currently, Nchan's main bottleneck is not CPU load but memory bandwidth. This can be improved significantly in future versions with fewer allocations and better use of contiguous memory pools. Please consider supporting Nchan to speed up the work of memory cache optimization. ## Install #### Download Packages - - [Arch Linux](https://archlinux.org): [nginx-nchan](https://aur.archlinux.org/packages/nginx-nchan/) and [nginx-nchan-git](https://aur.archlinux.org/packages/nginx-nchan-git/) are available in the Arch User Repository. - - Mac OS X: a [homebrew](http://brew.sh) package is available. `brew tap homebrew/nginx; brew install nginx-full --with-nchan-module` - - [Debian](https://www.debian.org/): A dynamic module build for is available in the Debian package repository: [libnginx-mod-nchan](https://packages.debian.org/sid/libnginx-mod-nchan). - Additionally, you can use the pre-built static module packages [nginx-common.deb](https://nchan.slact.net/download/nginx-common.deb) and [nginx-extras.deb](https://nchan.slact.net/download/nginx-extras.deb). Download both and install them with `dpkg -i`, followed by `sudo apt-get -f install`. - - [Ubuntu](http://www.ubuntu.com/): [nginx-common.ubuntu.deb](https://nchan.slact.net/download/nginx-common.ubuntu.deb) and [nginx-extras.ubuntu.deb](https://nchan.slact.net/download/nginx-extras.ubuntu.deb). Download both and install them with `dpkg -i`, followed by `sudo apt-get -f install`. Who knows when Ubuntu will add them to their repository?... - - [Fedora](https://fedoraproject.org): Dynamic module builds for Nginx > 1.10.0 are available: [nginx-mod-nchan.x86_64.rpm](https://nchan.slact.net/download/nginx-mod-nchan.x86-64.rpm), [nginx-mod-nchan.src.rpm](https://nchan.slact.net/download/nginx-mod-nchan.src.rpm). - - A statically compiled binary and associated linux nginx installation files are also [available as a tarball](https://nchan.slact.net/download/nginx-nchan-latest.tar.gz). + - [Arch Linux](https://archlinux.org): [nginx-mod-nchan](https://aur.archlinux.org/packages/nginx-mod-nchan/) and [nginx-mainline-mod-nchan](https://aur.archlinux.org/packages/nginx-mainline-mod-nchan/) are available in the Arch User Repository. + - Mac OS X: a [homebrew](http://brew.sh) package is available. `brew tap denji/nginx; brew install nginx-full --with-nchan-module` + - [Debian](https://www.debian.org/): A dynamic module build is available in the Debian package repository: [libnginx-mod-nchan](https://packages.debian.org/sid/libnginx-mod-nchan). + Additionally, you can use the pre-built static module packages [nginx-common.deb](https://nchan.io/download/nginx-common.deb) and [nginx-extras.deb](https://nchan.io/download/nginx-extras.deb). Download both and install them with `dpkg -i`, followed by `sudo apt-get -f install`. + - [Ubuntu](http://www.ubuntu.com/): [nginx-common.ubuntu.deb](https://nchan.io/download/nginx-common.ubuntu.deb) and [nginx-extras.ubuntu.deb](https://nchan.io/download/nginx-extras.ubuntu.deb). Download both and install them with `dpkg -i`, followed by `sudo apt-get -f install`. Who knows when Ubuntu will add Nchan to their repository?... + - [Fedora](https://fedoraproject.org): Dynamic module builds for Nginx > 1.10.0 are available: [nginx-mod-nchan.x86_64.rpm](https://nchan.io/download/nginx-mod-nchan.x86-64.rpm), [nginx-mod-nchan.src.rpm](https://nchan.io/download/nginx-mod-nchan.src.rpm). + - [Heroku](https://heroku.com): A buildpack for compiling Nchan into Nginx is available: [nchan-buildpack](https://github.com/andjosh/nchan-buildpack). A one-click, readily-deployable app is also available: [nchan-heroku](https://github.com/andjosh/nchan-heroku). + - A statically compiled binary and associated linux nginx installation files are also [available as a tarball](https://nchan.io/download/nginx-nchan-latest.tar.gz). #### Build From Source @@ -62,7 +61,7 @@ Grab the latest copy of Nginx from [nginx.org](http://nginx.org). Grab the lates If you're using Nginx > 1.9.11, you can build Nchan as a [dynamic module](https://www.nginx.com/blog/dynamic-modules-nginx-1-9-11/) with `--add-dynamic-module=path/to/nchan` -Run `make`, `make install`, and enjoy. (Caution, contents may be hot.) +Run `make`, then `make install`. ## Getting Started @@ -87,11 +86,11 @@ http { } ``` -You can now publish messages to channels by `POST`ing data to `/sub?id=channel_id` , and subscribe by pointing Websocket, EventSource, or [NchanSubscriber.js](https://github.com/slact/nchan/blob/master/NchanSubscriber.js) to `sub/?id=channel_id`. It's that simple. +You can now publish messages to channels by `POST`ing data to `/pub?id=channel_id` , and subscribe by pointing Websocket, EventSource, or [NchanSubscriber.js](https://github.com/slact/nchan.js) to `sub/?id=channel_id`. It's that simple. But Nchan is very flexible and highly configurable. So, of course, it can get a lot more complicated... -## Conceptual Overview +### Conceptual Overview The basic unit of most pub/sub solutions is the messaging *channel*. Nchan is no different. Publishers send messages to channels with a certain *channel id*, and subscribers subscribed to those channels receive them. Some number of messages may be buffered for a time in a channel's message buffer before they are deleted. Pretty simple, right? @@ -121,15 +120,26 @@ http { The above maps requests to the URI `/sub` onto the channel `foobar`'s *subscriber endpoint* , and similarly `/pub` onto channel `foobar`'s *publisher endpoint*. -#### Publisher Endpoints +## Publisher Endpoints Publisher endpoints are Nginx config *locations* with the [*`nchan_publisher`*](#nchan_publisher) directive. Messages can be published to a channel by sending HTTP **POST** requests with the message contents to the *publisher endpoint* locations. You can also publish messages through a **Websocket** connection to the same location. +```nginx + location /pub { + #example publisher location + nchan_publisher; + nchan_channel_id foo; + nchan_channel_group test; + nchan_message_buffer_length 50; + nchan_message_timeout 5m; + } +``` + -##### Publishing Messages +### Publishing Messages Requests and websocket messages are responded to with information about the channel at time of message publication. Here's an example from publishing with `curl`: @@ -147,7 +157,7 @@ The response can be in plaintext (as above), JSON, or XML, based on the request' ```console > curl --request POST --data "test message" -H "Accept: text/json" http://127.0.0.2:80/pub - {"messages": 6, "requested": 55, "subscribers": 0, "last_message_id": "1450755317:0" } + {"messages": 5, "requested": 18, "subscribers": 0, "last_message_id": "1450755280:0" } ``` Websocket publishers also receive the same responses when publishing, with the encoding determined by the *`Accept`* header present during the handshake. @@ -156,7 +166,7 @@ The response code for an HTTP request is *`202` Accepted* if no subscribers are Metadata can be added to a message when using an HTTP POST request for publishing. A `Content-Type` header will be associated as the message's content type (and output to Long-Poll, Interval-Poll, and multipart/mixed subscribers). A `X-EventSource-Event` header can also be used to associate an EventSource `event:` line value with a message. -##### Other Publisher Endpoint Actions +### Other Publisher Endpoint Actions **HTTP `GET`** requests return channel information without publishing a message. The response code is `200` if the channel exists, and `404` otherwise: ```console @@ -171,15 +181,32 @@ Metadata can be added to a message when using an HTTP POST request for publishin **HTTP `DELETE`** requests delete a channel and end all subscriber connections. Like the `GET` requests, this returns a `200` status response with channel info if the channel existed, and a `404` otherwise. -For an in-depth explanation of how settings are applied to channels from publisher locations, see the [details page](https://nchan.slact.net/details#publisher-endpoint-configs). +### How Channel Settings Work + +*A channel's configuration is set to the that of its last-used publishing location.* +So, if you want a channel to behave consistently, and want to publish to it from multiple locations, *make sure those locations have the same configuration*. -#### Subscriber Endpoints +You can also can use differently-configured publisher locations to dynamically update a channel's message buffer settings. This can be used to erase messages or to scale an existing channel's message buffer as desired. + +## Subscriber Endpoints Subscriber endpoints are Nginx config *locations* with the [*`nchan_subscriber`*](#nchan_subscriber) directive. Nchan supports several different kinds of subscribers for receiving messages: [*Websocket*](#websocket), [*EventSource*](#eventsource) (Server Sent Events), [*Long-Poll*](#long-polling), [*Interval-Poll*](#interval-polling). [*HTTP chunked transfer*](#http-chunked-transfer), and [*HTTP multipart/mixed*](#http-multipart-mixed). -- ##### Long-Polling +```nginx + location /sub { + #example subscriber location + nchan_subscriber; + nchan_channel_id foo; + nchan_channel_group test; + nchan_subscriber_first_message oldest; + } +``` + + + +- ### Long-Polling The tried-and-true server-push method supported by every browser out there. Initiated by sending an HTTP `GET` request to a channel subscriber endpoint. The long-polling subscriber walks through a channel's message queue via the built-in cache mechanism of HTTP clients, namely with the "`Last-Modified`" and "`Etag`" headers. Explicitly, to receive the next message for given a long-poll subscriber response, send a request with the "`If-Modified-Since`" header set to the previous response's "`Last-Modified`" header, and "`If-None-Match`" likewise set to the previous response's "`Etag`" header. @@ -187,15 +214,16 @@ Nchan supports several different kinds of subscribers for receiving messages: [* A message's associated content type, if present, will be sent to this subscriber with the `Content-Type` header. -- ##### Interval-Polling +- ### Interval-Polling Works just like long-polling, except if the requested message is not yet available, immediately responds with a `304 Not Modified`. - There is no way to differentiate between long-poll and interval-poll subscriber requests, so long-polling must be disabled for a subscriber location if you wish to use interval-polling. + Nchan cannot automatically distinguish between long-poll and interval-poll subscriber requests, so long-polling must be disabled for a subscriber location if you wish to use interval-polling. -- ##### Websocket +- ### Websocket Bidirectional communication for web browsers. Part of the [HTML5 spec](http://www.w3.org/TR/2014/REC-html5-20141028/single-page.html). Nchan supports the latest protocol version 13 ([RFC 6455](https://tools.ietf.org/html/rfc6455)). Initiated by sending a websocket handshake to the desired subscriber endpoint location. - If the websocket connection is closed by the server, the `close` frame will contain the HTTP response code and status line describing the reason for closing the connection. Server-initiated keep-alive pings can be configured with the [`nchan_websocket_ping_interval`](#nchan_websocket_ping_interval) config directive. Websocket extensions are not yet supported. - Messages published through a websocket connection can be forwarded to an upstream application with the [`nchan_publisher_upstream_request`](#nchan_publisher_upstream_request) config directive. + If the websocket connection is closed by the server, the `close` frame will contain the HTTP response code and status line describing the reason for closing the connection. Server-initiated keep-alive pings can be configured with the [`nchan_websocket_ping_interval`](#nchan_websocket_ping_interval) config directive. + Messages are delivered to subscribers in `text` websocket frames, except if a message's `content-type` is "`application/octet-stream`" -- then it is delivered in a `binary` frame. +
Websocket subscribers can use the custom `ws+meta.nchan` subprotocol to receive message metadata with messages, making websocket connections resumable. Messages received with this subprotocol are of the form
   id: message_id
@@ -204,9 +232,24 @@ Nchan supports several different kinds of subscribers for receiving messages: [*
   message_data
   
The `content-type:` line may be omitted. +
+ #### Websocket Publisher + Messages published through a websocket connection can be forwarded to an upstream application with the [`nchan_publisher_upstream_request`](#nchan_publisher_upstream_request) config directive. + Messages published in a binary frame are automatically given the `content-type` "`application/octet-stream`". + #### Permessage-deflate + Nchan version 1.1.8 and above supports the [permessage-deflate protocol extension](https://tools.ietf.org/html/rfc7692). Messages are deflated once when they are published, and then can be broadcast to any number of compatible websocket subscribers. Message deflation is enabled by setting the [`nchan_deflate_message_for_websocket on;`](#nchan_deflate_message_for_websocket) directive in a publisher location. +
+ The deflated data is stored alongside the original message in memory, or, if large enough, on disk. This means more [shared memory](#nchan_shared_memory_size) is necessary when using `nchan_deflate_message_for_websocket`. +
+ Deflation parameters (speed, memory use, strategy, etc.), can be tweaked using the [`nchan_permessage_deflate_compression_window`](#nchan_permessage_deflate_compression_window), [`nchan_permessage_deflate_compression_level`](#nchan_permessage_deflate_compression_level), + [`nchan_permessage_deflate_compression_strategy`](#nchan_permessage_deflate_compression_strategy), and + [`nchan_permessage_deflate_compression_window`](#nchan_permessage_deflate_compression_window) settings. +
+ Nchan also supports the (deprecated) [perframe-deflate extension](https://tools.ietf.org/html/draft-tyoshino-hybi-websocket-perframe-deflate-06) still in use by Safari as `x-webkit-perframe-deflate`. +
-- ##### EventSource +- ### EventSource Also known as [Server-Sent Events](https://en.wikipedia.org/wiki/Server-sent_events) or SSE, it predates Websockets in the [HTML5 spec](http://www.w3.org/TR/2014/REC-html5-20141028/single-page.html), and is a [very simple protocol](http://www.w3.org/TR/eventsource/#event-stream-interpretation). Initiated by sending an HTTP `GET` request to a channel subscriber endpoint with the "`Accept: text/event-stream`" header. Each message `data: ` segment will be prefaced by the message `id: `. @@ -217,7 +260,7 @@ Nchan supports several different kinds of subscribers for receiving messages: [* A message's associated `event` type, if present, will be sent to this subscriber with the `event:` line. -- ##### HTTP [multipart/mixed](http://www.w3.org/Protocols/rfc1341/7_2_Multipart.html#z0) +- ### HTTP [multipart/mixed](http://www.w3.org/Protocols/rfc1341/7_2_Multipart.html#z0) The `multipart/mixed` MIMEtype was conceived for emails, but hey, why not use it for HTTP? It's easy to parse and includes metadata with each message. Initiated by including an `Accept: multipart/mixed` header. The response headers and the unused "preamble" portion of the response body are sent right away, with the boundary string generated randomly for each subscriber. Each subsequent message will be sent as one part of the multipart message, and will include the message time and tag (`Last-Modified` and `Etag`) as well as the optional `Content-Type` headers. @@ -225,11 +268,11 @@ Nchan supports several different kinds of subscribers for receiving messages: [* A message's associated content type, if present, will be sent to this subscriber with the `Content-Type` header. -- ##### HTTP Raw Stream +- ### HTTP Raw Stream A simple subscription method similar to the [streaming subscriber](https://github.com/wandenberg/nginx-push-stream-module/blob/master/docs/directives/subscribers.textile#push_stream_subscriber) of the [Nginx HTTP Push Stream Module](https://github.com/wandenberg/nginx-push-stream-module). Messages are appended to the response body, separated by a newline or configurable by `nchan_subscriber_http_raw_stream_separator`. -- ##### HTTP [Chunked Transfer](http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.6.1) +- ### HTTP [Chunked Transfer](http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.6.1) This subscription method uses the `chunked` `Transfer-Encoding` to receive messages. Initiated by explicitly including `chunked` in the [`TE` header](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.39): `TE: chunked` (or `TE: chunked;q=??` where the qval > 0) @@ -237,9 +280,7 @@ Nchan supports several different kinds of subscribers for receiving messages: [* Unlike the other subscriber types, the `chunked` subscriber cannot be used with http/2 because it dissallows chunked encoding. - - -#### PubSub Endpoint +## PubSub Endpoint PubSub endpoints are Nginx config *locations* with the [*`nchan_pubsub`*](#nchan_pubsub) directive. @@ -249,17 +290,19 @@ requests as subscribers, and all HTTP `POST` as publishers. One simple use case ```nginx location = /pubsub { nchan_pubsub; - nchan_channel_id foobar; + nchan_channel_id foo; + nchan_channel_group test; } ``` -A more applicable setup may set different publisher and subscriber channel ids: +A more interesting setup may set different publisher and subscriber channel ids: ```nginx location = /pubsub { nchan_pubsub; nchan_publisher_channel_id foo; nchan_subscriber_channel_id bar; + nchan_channel_group test; } ``` @@ -267,9 +310,9 @@ Here, subscribers will listen for messages on channel `foo`, and publishers will -### The Channel ID +## The Channel ID -So far the examples have used static channel ids, which is not very useful in practice. It can be set to any nginx *variable*, such as a querystring argument, a header value, or a part of the location url: +So far the examples have used static channel ids, which is not very useful. In practice, the channel id can be set to any nginx *variable*, such as a querystring argument, a header value, or a part of the location url: ```nginx location = /sub_by_ip { @@ -294,9 +337,11 @@ So far the examples have used static channel ids, which is not very useful in pr } ``` +I recommend using the last option, a channel id derived from the request URL via a regular expression. It makes things nice and RESTful. + -#### Channel Multiplexing +### Channel Multiplexing With channel multiplexing, subscribers can subscribe to up to 255 channels per connection. Messages published to all the specified channels will be delivered in-order to the subscriber. There are two ways to enable multiplexing: @@ -325,68 +370,626 @@ For more than 7 channels, `nchan_channel_id_split_delimiter` can be used to spli } ``` -Publishing to multiple channels with a single request is also possible, with similar configuration: +It is also possible to publish to multiple channels with a single request as well as delete multiple channels with a single request, with similar configuration: ```nginx location ~ /multipub/(\w+)/(\w+)$ { nchan_publisher; nchan_channel_id "$1" "$2" "another_channel"; + #POST /multipub/foo/bar will publish to: + # channels 'foo', 'bar', 'another_channel' + #DELETE /multipub/foo/bar will delete: + # channels 'foo', 'bar', 'another_channel' } ``` -`DELETE` requests to a multiplexed channel broadcast the deletion to each of the channels it multiplexes, deletes all their messages and kicks out all clients subscribed to any of the channel ids. +When a channel is deleted, all of its messages are deleted, and all of its subscribers' connection are closed -- including ones subscribing through a multiplexed location. For example, suppose a subscriber is subscribed to channels "foo" and "bar" via a single multiplexed connection. If "foo" is deleted, the connection is closed, and the subscriber therefore loses the "bar" subscription as well. -See the [details page](https://nchan.slact.net/details#securing-channels) for more information about using good IDs and keeping channels secure. +See the [Channel Security](#securing-channels) section about using good IDs and keeping private channels secure. +### Channel Groups + +Channels can be associated with groups to avoid channel ID conflicts: + +```nginx + location /test_pubsub { + nchan_pubsub; + nchan_channel_group "test"; + nchan_channel_id "foo"; + } + + location /pubsub { + nchan_pubsub; + nchan_channel_group "production"; + nchan_channel_id "foo"; + #same channel id, different channel group. Thus, different channel. + } + + location /flexgroup_pubsub { + nchan_pubsub; + nchan_channel_group $arg_group; + nchan_channel_id "foo"; + #group can be set with request variables too + } +``` + +#### Limits and Accounting + +Groups can be used to track aggregate channel usage, as well as set limits on the number of channels, subscribers, stored messages, memory use, etc: + +```nginx + #enable group accounting + nchan_channel_group_accounting on; + + location ~ /pubsub/(\w+)$ { + nchan_pubsub; + nchan_channel_group "limited"; + nchan_channel_id $1; + } + + location ~ /prelimited_pubsub/(\w+)$ { + nchan_pubsub; + nchan_channel_group "limited"; + nchan_channel_id $1; + nchan_group_max_subscribers 100; + nchan_group_max_messages_memory 50M; + } + + location /group { + nchan_channel_group limited; + nchan_group_location; + nchan_group_max_channels $arg_max_channels; + nchan_group_max_messages $arg_max_messages; + nchan_group_max_messages_memory $arg_max_messages_mem; + nchan_group_max_messages_disk $arg_max_messages_disk; + nchan_group_max_subscribers $arg_max_subs; + } +``` + +Here, `/group` is an `nchan_group_location`, which is used for accessing and modifying group data. To get group data, send a `GET` request to a `nchan_group_location`: + +```sh +> curl http://localhost/group + +channels: 10 +subscribers: 0 +messages: 219 +shared memory used by messages: 42362 bytes +disk space used by messages: 0 bytes +limits: + max channels: 0 + max subscribers: 0 + max messages: 0 + max messages shared memory: 0 + max messages disk space: 0 +``` + +By default, the data is returned in human-readable plaintext, but can also be formatted as JSON, XML, or YAML: + +```sh +> curl -H "Accept: text/json" http://localhost/group + +{ + "channels": 21, + "subscribers": 40, + "messages": 53, + "messages_memory": 19941, + "messages_disk": 0, + "limits": { + "channels": 0, + "subscribers": 0, + "messages": 0, + "messages_memory": 0, + "messages_disk": 0 + } +} +``` + +The data in the response are for the single Nchan instance only, regardless of whether Redis is used. A limit of 0 means 'unlimited'. + +Limits can be set per-location, as with the above `/prelimited_pubsub/...` location, or with a POST request to the `nchan_group_location`: +```sh +> curl -X POST "http://localhost/group?max_channels=15&max_subs=1000&max_messages_disk=0.5G" + +channels: 0 +subscribers: 0 +messages: 0 +shared memory used by messages: 0 bytes +disk space used by messages: 0 bytes +limits: + max channels: 15 + max subscribers: 1000 + max messages: 0 + max messages shared memory: 0 + max messages disk space: 536870912 + +``` + +Limits are only applied locally, regardless of whether Redis is enabled. +If a publisher or subscriber request exceeds a group limit, Nchan will respond to it with a `403 Forbidden` response. + + + +## Hooks and Callbacks + + + +### Request Authorization + +This feature, configured with [`nchan_authorize_request`](#nchan_authorize_request), behaves just like the Nginx [http_auth_request module](http://nginx.org/en/docs/http/ngx_http_auth_request_module.html#auth_request_set). + +Consider the configuration: +```nginx + upstream my_app { + server 127.0.0.1:8080; + } + location = /auth { + proxy_pass http://my_app/pubsub_authorize; + proxy_pass_request_body off; + proxy_set_header Content-Length ""; + proxy_set_header X-Subscriber-Type $nchan_subscriber_type; + proxy_set_header X-Publisher-Type $nchan_publisher_type; + proxy_set_header X-Prev-Message-Id $nchan_prev_message_id; + proxy_set_header X-Channel-Id $nchan_channel_id; + proxy_set_header X-Original-URI $request_uri; + proxy_set_header X-Forwarded-For $remote_addr; + } + + location ~ /pubsub/auth/(\w+)$ { + nchan_channel_id $1; + nchan_authorize_request /auth; + nchan_pubsub; + nchan_channel_group test; + } +``` + +Here, any request to the location `/pubsub/auth/<...>` will need to be authorized by your application (`my_app`). Nginx will generate a `GET /pubsub_authorize` request to the application, with additional headers set by the `proxy_set_header` directives. Note that Nchan-specific variables are available for this authorization request. Once your application receives this request, it should decide whether or not to authorize the subscriber. This can be done based on a forwarded session cookie, IP address, or any set of parameters of your choosing. If authorized, it should respond with an empty `200 OK` response. +All non-`2xx` response codes (such as `403 Forbidden`) are intepreted as authorization failures. In this case, the failing response is proxied to the client. + +Note that Websocket and EventSource clients will only try to authorize during the initial handshake request, whereas Long-Poll and Interval-Poll subscribers will need to be authorized each time they request the next message, which may flood your application with too many authorization requests. + + + +### Subscriber Presence + +Subscribers can notify an application when they have subscribed and unsubscribed to a channel using the [`nchan_subscribe_request`](#nchan_subscribe_request) +and [`nchan_unsubscribe_request`](#nchan_unsubscribe_request) settings. +These should point to Nginx locations configured to forward requests to an upstream proxy (your application): + +```nginx + location ~ /sub/(\w+)$ { + nchan_channel_id $1; + nchan_subscribe_request /upstream/sub; + nchan_unsubscribe_request /upstream/unsub; + nchan_subscriber; + nchan_channel_group test; + } + + location = /upstream/unsub { + proxy_pass http://127.0.0.1:9292/unsub; + proxy_ignore_client_abort on; #!!!important!!!! + proxy_set_header X-Subscriber-Type $nchan_subscriber_type; + proxy_set_header X-Channel-Id $nchan_channel_id; + proxy_set_header X-Original-URI $request_uri; + } + location = /upstream/sub { + proxy_pass http://127.0.0.1:9292/sub; + proxy_set_header X-Subscriber-Type $nchan_subscriber_type; + proxy_set_header X-Message-Id $nchan_message_id; + proxy_set_header X-Channel-Id $nchan_channel_id; + proxy_set_header X-Original-URI $request_uri; + } +``` + +In order for `nchan_unsubscribe_request` to work correctly, the location it points to must have `proxy_ignore_client_abort on;`. Otherwise, suddenly aborted subscribers may not trigger an unsubscribe request. + +Note that the subscribe/unsubscribe hooks are **disabled for long-poll and interval-poll clients**, because they would trigger these hooks each time they receive a message. + + + +### Message Forwarding + +Messages can be forwarded to an upstream application before being published using the `nchan_publisher_upstream_request` setting: + +```nginx + location ~ /pub/(\w+)$ { + #publisher endpoint + nchan_channel_id $1; + nchan_pubsub; + nchan_publisher_upstream_request /upstream_pub; + } + + location = /upstream_pub { + proxy_pass http://127.0.0.1:9292/pub; + proxy_set_header X-Publisher-Type $nchan_publisher_type; + proxy_set_header X-Prev-Message-Id $nchan_prev_message_id; + proxy_set_header X-Channel-Id $nchan_channel_id; + proxy_set_header X-Original-URI $request_uri; + } +``` +With this configuration, incoming messages are first `POST`ed to `http://127.0.0.1:9292/pub`. +The upstream response code determines how publishing will proceed: + - `304 Not Modified` publishes the message as received, without modifification. + - `204 No Content` discards the message + - `200 OK` is used for modifying the message. Instead of the original incoming message, the message contained in this HTTP response is published. + +There are two main use cases for `nchan_publisher_upstream_request`: forwarding incoming data from Websocket publishers to an application, and mutating incoming messages. + + + ## Storage Nchan can stores messages in memory, on disk, or via Redis. Memory storage is much faster, whereas Redis has additional overhead as is considerably slower for publishing messages, but offers near unlimited scalability for broadcast use cases with far more subscribers than publishers. - - ### Memory Storage -This storage method uses a segment of shared memory to store messages and channel data. Large messages as determined by Nginx's caching layer are stored on-disk. The size of the memory segment is configured with `nchan_max_reserved_memory`. Data stored here is not persistent, and is lost if Nginx is restarted or reloaded. +This default storage method uses a segment of shared memory to store messages and channel data. Large messages as determined by Nginx's caching layer are stored on-disk. The size of the memory segment is configured with `nchan_shared_memory_size`. Data stored here is not persistent, and is lost if Nginx is restarted or reloaded. ### Redis -Nchan can also store messages and channels on a Redis server, or in a Redis cluster. To use a Redis server, set `nchan_use_redis on;` and set the server url with `nchan_redis_url`. These two settings are inheritable by nested locations, so it is enough to set them within an `http { }` block to enable Redis for all Nchan locations in that block. Different locations can also use different Redis servers. +[Redis](http://redis.io) can be used to add **data persistence** and **horizontal scalability**, **failover** and **high availability** to your Nchan setup. + + -To use a Redis Cluster, the Redis servers acting as cluster nodes need to be configured in an `upstream { }` block: +#### Connecting to a Redis Server +To connect to a single Redis master server, use an `upstream` with `nchan_redis_server` and `nchan_redis_pass` settings: ```nginx +http { + upstream my_redis_server { + nchan_redis_server 127.0.0.1; + } + server { + listen 80; + + location ~ /redis_sub/(\w+)$ { + nchan_subscriber; + nchan_channel_id $1; + nchan_redis_pass my_redis_server; + } + location ~ /redis_pub/(\w+)$ { + nchan_redis_pass my_redis_server; + nchan_publisher; + nchan_channel_id $1; + } + } +} +``` + +All servers with the above configuration connecting to the same redis server share channel and message data. + +Channels that don't use Redis can be configured side-by-side with Redis-backed channels, provided the endpoints never overlap. (This can be ensured, as above, by setting separate `nchan_channel_group`s.). Different locations can also connect to different Redis servers. + +Nchan can work with a single Redis master. It can also auto-discover and use Redis slaves to balance PUBSUB traffic. + + + +#### Redis Cluster +Nchan also supports using Redis Cluster, which adds scalability via sharding channels among cluster nodes. Redis cluster also provides **automatic failover**, **high availability**, and eliminates the single point of failure of one shared Redis server. It is configred and used like so: + +```nginx +http { upstream redis_cluster { nchan_redis_server redis://127.0.0.1:7000; nchan_redis_server redis://127.0.0.1:7001; nchan_redis_server redis://127.0.0.1:7002; + # you don't need to specify all the nodes, they will be autodiscovered + # however, it's recommended that you do specify at least a few master nodes. } + server { + listen 80; + + location ~ /sub/(\w+)$ { + nchan_subscriber; + nchan_channel_id $1; + nchan_redis_pass redis_cluster; + } + location ~ /pub/(\w+)$ { + nchan_publisher; + nchan_channel_id $1; + nchan_redis_pass redis_cluster; + } + } +} ``` -It is best to specify all master cluster nodes, but this is not required -- as long as Nchan can connect to at least 1 node, it will discover and connect to the whole cluster. + + +##### High Availability +Redis Cluster connections are designed to be resilient and try to recover from errors. Interrupted connections will have their commands queued until reconnection, and Nchan will publish any messages it successfully received while disconnected. Nchan is also adaptive to cluster modifications. It will add new nodes and remove them as needed. + +All Nchan servers sharing a Redis server or cluster should have their times synchronized (via ntpd or your favorite ntp daemon). Failure to do so may result in missed or duplicate messages. + +#### Tweaks and Optimizations + +As of version 1.2.0, Nchan uses Redis slaves to load-balance PUBSUB traffic. By default, there is an equal chance that a channel's PUBSUB subscription will go to any master or slave. The [`nchan_redis_subscribe_weights`](#nchan_redis_subscribe_weights) setting is available to fine-tune this load-balancing. + +Also from 1.2.0 onward, [`nchan_redis_optimize_target`](#nchan_redis_optimize_target) can be used to prefer optimizing Redis slaves for CPU or bandwidth. For heavy publishing loads, the tradeoff is very roughly 35% replication bandwidth per slave to 30% CPU load on slaves. + +## Introspection + +There are several ways to see what's happening inside Nchan. These are useful for debugging application integration and for measuring performance. -To use Redis Cluster in an Nchan location, use the `nchan_redis_pass` setting: +### Channel Events + +Channel events are messages automatically published by Nchan when certain events occur in a channel. These are very useful for debugging the use of channels. However, they carry a significant performance overhead and should be used during development, and not in production. + +Channel events are published to special 'meta' channels associated with normal channels. Here's how to configure them: ```nginx - location ~ /pubsub/(\w+)$ { +location ~ /pubsub/(.+)$ { + nchan_pubsub; + nchan_channel_id $1; + nchan_channel_events_channel_id $1; #enables channel events for this location +} + +location ~ /channel_events/(.+) { + #channel events subscriber location + nchan_subscriber; + nchan_channel_group meta; #"meta" is a SPECIAL channel group + nchan_channel_id $1; +} +``` + +Note the `/channel_events/...` location has a *special* `nchan_channel_group`, `meta`. This group is reserved for accessing "channel events channels", or"metachannels". + +Now, say I subscribe to `/channel_events/foo` I will refer to this as the channel events subscriber. + +Let's see what this channel events subscriber receives when I publish messages to + +Subscribing to `/pubsub/foo` produces the channel event +``` +subscriber_enqueue foo +``` + +Publishing a message to `/pubsub/foo`: +``` +channel_publish foo +``` + +Unsubscribing from `/pubsub/foo`: +``` +subscriber_dequeue foo +``` + +Deleting `/pubsub/foo` (with HTTP `DELETE /pubsub/foo`): +``` +channel_delete foo +``` + +The event string itself is configirable with [nchan_channel_event_string](#nchan_channel_event_string). By default, it is set to `$nchan_channel_event $nchan_channel_id`. +This string can use any Nginx and [Nchan variables](/#variables). + + +### nchan_stub_status Stats + +Like Nginx's [stub_status](https://nginx.org/en/docs/http/ngx_http_stub_status_module.html), +`nchan_stub_status` is used to get performance metrics. + +```nginx + location /nchan_stub_status { + nchan_stub_status; + } +``` + +Sending a GET request to this location produces the response: + +```text +total published messages: 1906 +stored messages: 1249 +shared memory used: 1824K +channels: 80 +subscribers: 90 +redis pending commands: 0 +redis connected servers: 0 +total interprocess alerts received: 1059634 +interprocess alerts in transit: 0 +interprocess queued alerts: 0 +total interprocess send delay: 0 +total interprocess receive delay: 0 +nchan version: 1.1.5 +``` + +Here's what each line means, and how to interpret it: + - `total published messages`: Number of messages published to all channels through this Nchan server. + - `stored messages`: Number of messages currently buffered in memory + - `shared memory used`: Total shared memory used for buffering messages, storing channel information, and other purposes. This value should be comfortably below `nchan_shared_memory_size`. + - `channels`: Number of channels present on this Nchan server. + - `subscribers`: Number of subscribers to all channels on this Nchan server. + - `redis pending commands`: Number of commands sent to Redis that are awaiting a reply. May spike during high load, especially if the Redis server is overloaded. Should tend towards 0. + - `redis connected servers`: Number of redis servers to which Nchan is currently connected. + - `total interprocess alerts received`: Number of interprocess communication packets transmitted between Nginx workers processes for Nchan. Can grow at 100-10000 per second at high load. + - `interprocess alerts in transit`: Number of interprocess communication packets in transit between Nginx workers. May be nonzero during high load, but should always tend toward 0 over time. + - `interprocess queued alerts`: Number of interprocess communication packets waiting to be sent. May be nonzero during high load, but should always tend toward 0 over time. + - `total interprocess send delay`: Total amount of time interprocess communication packets spend being queued if delayed. May increase during high load. + - `total interprocess receive delay`: Total amount of time interprocess communication packets spend in transit if delayed. May increase during high load. + - `nchan_version`: current version of Nchan. Available for version 1.1.5 and above. + +Additionally, when there is at least one `nchan_stub_status` location, the following Nginx variables are available: + - `$nchan_stub_status_total_published_messages` + - `$nchan_stub_status_stored_messages` + - `$nchan_stub_status_shared_memory_used` + - `$nchan_stub_status_channels` + - `$nchan_stub_status_subscribers` + - `$nchan_stub_status_redis_pending_commands` + - `$nchan_stub_status_redis_connected_servers` + - `$nchan_stub_status_total_ipc_alerts_received` + - `$nchan_stub_status_ipc_queued_alerts` + - `$nchan_stub_status_total_ipc_send_delay` + - `$nchan_stub_status_total_ipc_receive_delay` + + +## Securing Channels + +### Securing Publisher Endpoints +Consider the use case of an application where authenticated users each use a private, dedicated channel for live updates. The configuration might look like this: + +```nginx +http { + server { + #available only on localhost + listen 127.0.0.1:8080; + location ~ /pub/(\w+)$ { + nchan_publisher; + nchan_channel_group my_app_group; + nchan_channel_id $1; + } + } + + server { + #available to the world + listen 80; + + location ~ /sub/(\w+)$ { + nchan_subscriber; + nchan_channel_group my_app_group; + nchan_channel_id $1; + } + } +} + +``` + +Here, the subscriber endpoint is available on a public-facing port 80, and the publisher endpoint is only available on localhost, so can be accessed only by applications residing on that machine. Another way to limit access to the publisher endpoint is by using the allow/deny settings: + +```nginx + + server { + #available to the world + listen 80; + location ~ /pub/(\w+)$ { + allow 127.0.0.1; + deny all; + nchan_publisher; + nchan_channel_group my_app_group; + nchan_channel_id $1; + } +``` + +Here, only the local IP 127.0.0.1 is allowed to use the publisher location, even though it is defined in a non-localhost server block. + +### Keeping a Channel Private + +A Channel ID that is meant to be private should be treated with the same care as a session ID token. Considering the above use case of one-channel-per-user, how can we ensure that only the authenticated user, and no one else, is able to access his channel? + +First, if you intend on securing the channel contents, you must use TLS/SSL: + +```nginx +http { + server { + #available only on localhost + listen 127.0.0.1:8080; + #...publisher endpoint config + } + server { + #available to the world + listen 443 ssl; + #SSL config goes here + location ~ /sub/(\w+)$ { + nchan_subscriber; + nchan_channel_group my_app_group; + nchan_channel_id $1; + } + } +} +``` + +Now that you have a secure connection between the subscriber client and the server, you don't need to worry about the channel ID or messages being passively intercepted. This is a minimum requirement for secure message delivery, but it is not sufficient. + +You must also take care to do at least one of the following: + - [Generate good, high-entropy Channel IDs](#good-ids). + - [Authorize all subscribers with the `nchan_authorize_request` config directive](#request-authorization). + - [Authorize subscribers and hide channel IDs with the "`X-Accel-Redirect`" mechanism](#x-accel-redirect). + +#### Good IDs + +An ID that can be guessed is an ID that can be hijacked. If you are not authenticating subscribers (as described below), a channel ID should be impossible to guess. Use at least 128 bits of entropy to generate a random token, associate it with the authenticated user, and share it only with the user's client. Do not reuse tokens, just as you would not reuse session IDs. + +#### X-Accel-Redirect + +This feature uses the [X-Accel feature](https://www.nginx.com/resources/wiki/start/topics/examples/x-accel) of Nginx upstream proxies to perform an internal request to a subscriber endpoint. +It allows a subscriber client to be authenticated by your application, and then redirected by nginx internally to a location chosen by your appplication (such as a publisher or subscriber endpoint). This makes it possible to have securely authenticated clients that are unaware of the channel id they are subscribed to. + +Consider the following configuration: +```nginx +upstream upstream_app { + server 127.0.0.1:8080; +} + +server { + listen 80; + + location = /sub_upstream { + proxy_pass http://upstream_app/subscriber_x_accel_redirect; + proxy_set_header X-Forwarded-For $remote_addr; + } + + location ~ /sub/internal/(\w+)$ { + internal; #this location only accessible for internal nginx redirects + nchan_subscriber; nchan_channel_id $1; - nchan_pubsub; - nchan_redis_pass redis_cluster; + nchan_channel_group test; } +} +``` +As commented, `/sub/internal/` is inaccessible from the outside: +```console +> curl -v http://127.0.0.1/sub/internal/foo + + < HTTP/1.1 404 Not Found + < Server: nginx/1.9.5 + < + + 404 Not Found + +

404 Not Found

+
nginx/1.9.5
+ + ``` -Note that `nchan_redis_pass` implies `nchan_use_redis on;`, and that this setting is *not* inherited by nested locations. +But if a request is made to `/sub_upstream`, it gets forwarded to your application (`my_app`) on port 8080 with the url `/subscriber_x_accel_redirect`. +Note that you can set any forwarded headers here like any [`proxy_pass`](http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_pass) Nginx location, +but unlike the case with `nchan_authorize_request`, Nchan-specific variables are not available. -When connecting several Nchan servers to the same Redis server (or cluster), the servers **must have their times synced up**. Failure to do so may result in missing and duplicated messages. +Now, your application must be set up to handle the request to `/subscriber_x_accel_redirect`. You should make sure the client is properly authenticated (maybe using a session cookie), and generate an associated channel id. If authentication fails, respond with a normal `403 Forbidden` response. You can also pass extra information about the failure in the response body and headers. -See the [details page](https://nchan.slact.net/details#using-redis) for more information on using Redis. +If your application successfully authenticates the subscriber request, you now need to instruct Nginx to issue an internal redirect to `/sub/internal/my_channel_id`. +This is accomplished by responding with an empty `200 OK` response that includes two headers: +- `X-Accel-Redirect: /sub/internal/my_channel_id` +- `X-Accel-Buffering: no` - +In the presence of these headers, Nginx will not forward your app's response to the client, and instead will *internally* redirect to `/sub/internal/my_channel_id`. +This will behave as if the client had requested the subscriber endpoint location directly. + +Thus using X-Accel-Redirect it is possible to both authenticate all subscribers *and* keep channel IDs completely hidden from subscribers. + +This method is especially useful for EventSource and Websocket subscribers. Long-Polling subscribers will need to be re-authenticated for every new message, which may flood your application with too many authentication requests. + +### Revoking Channel Authorization + +In some cases, you may want to revoke a particular subscriber's authorization for a given channel (e.g., if the user's permissions are changed). If the channel is unique to the subscriber, this is simply accomplished by deleting the channel. The same can be achieved for shared channels by subscribing each subscriber to both the shared channel and a subscriber-specific channel via a multiplexed connection. Deleting the subscriber-specific channel will terminate the subscriber''s connection, thereby also terminating their subscription to the shared channel. Consider the following configuration: + +```nginx +location ~ /sub/(\w+) { + nchan_subscriber; + nchan_channel_id shared_$1 user_$arg_userid; + nchan_authorize_request /authorize; +} +location /pub/user { + nchan_publisher; + nchan_channel_id user_$arg_userid; +} +``` + +A request to `/sub/foo?userid=1234` will subscribe to channels "shared_foo" and "user_1234" via a multiplexed connection. If you later send a `DELETE` request to `/pub/user?userid=1234`, this subscriber will be disconnected and therefore unsubscribed from both "user_1234" and "shared_foo". + ## Variables Nchan makes several variables usabled in the config file: @@ -401,13 +1004,16 @@ Nchan makes several variables usabled in the config file: For subscriber locations, this variable is set to the subscriber type (websocket, longpoll, etc.). - `$nchan_publisher_type` - For subscriber locations, this variable is set to the subscriber type (http or websocket). + For publisher locations, this variable is set to the subscriber type (http or websocket). - `$nchan_prev_message_id`, `$nchan_message_id` The current and previous (if applicable) message id for publisher request or subscriber response. - `$nchan_channel_event` For channel events, this is the event name. Useful when configuring `nchan_channel_event_string`. + +- `$nchan_version` + Current Nchan version. Available since 1.1.5. Additionally, `nchan_stub_status` data is also exposed as variables. These are available only when `nchan_stub_status` is enabled on at least one location: @@ -440,18 +1046,72 @@ Additionally, `nchan_stub_status` data is also exposed as variables. These are a > Split the channel id into several ids for multiplexing using the delimiter string provided. [more details](#channel-multiplexing) +- **nchan_deflate_message_for_websocket** `[ on | off ]` + arguments: 1 + default: `off` + context: server, location + > Store a compressed (deflated) copy of the message along with the original to be sent to websocket clients supporting the permessage-deflate protocol extension + - **nchan_eventsource_event** arguments: 1 default: `(none)` context: server, location, if > Set the EventSource `event:` line to this value. When used in a publisher location, overrides the published message's `X-EventSource-Event` header and associates the message with the given value. When used in a subscriber location, overrides all messages' associated `event:` string with the given value. +- **nchan_eventsource_ping_comment** + arguments: 1 + default: `(empty)` + context: server, location, if + > Set the EventSource comment `: ...` line for periodic pings from server to client. Newlines are not allowed. If empty, no comment is sent with the ping. + +- **nchan_eventsource_ping_data** + arguments: 1 + default: `(empty)` + context: server, location, if + > Set the EventSource `data:` line for periodic pings from server to client. Newlines are not allowed. If empty, no data is sent with the ping. + +- **nchan_eventsource_ping_event** + arguments: 1 + default: `ping` + context: server, location, if + > Set the EventSource `event:` line for periodic pings from server to client. Newlines are not allowed. If empty, no event type is sent with the ping. + +- **nchan_eventsource_ping_interval** ` (seconds)` + arguments: 1 + default: `0 (none)` + context: server, location, if + > Interval for sending ping messages to EventSource subscribers. Disabled by default. + - **nchan_longpoll_multipart_response** `[ off | on | raw ]` arguments: 1 default: `off` context: server, location, if > when set to 'on', enable sending multiple messages in a single longpoll response, separated using the multipart/mixed content-type scheme. If there is only one available message in response to a long-poll request, it is sent unmodified. This is useful for high-latency long-polling connections as a way to minimize round-trips to the server. When set to 'raw', sends multiple messages using the http-raw-stream message separator. +- **nchan_permessage_deflate_compression_level** `[ 0-9 ]` + arguments: 1 + default: `6` + context: http + > Compression level for the `deflate` algorithm used in websocket's permessage-deflate extension. 0: no compression, 1: fastest, worst, 9: slowest, best + +- **nchan_permessage_deflate_compression_memlevel** `[ 1-9 ]` + arguments: 1 + default: `8` + context: http + > Memory level for the `deflate` algorithm used in websocket's permessage-deflate extension. How much memory should be allocated for the internal compression state. 1 - minimum memory, slow and reduces compression ratio; 9 - maximum memory for optimal speed + +- **nchan_permessage_deflate_compression_strategy** `[ default | filtered | huffman-only | rle | fixed ]` + arguments: 1 + default: `default` + context: http + > Compression strategy for the `deflate` algorithm used in websocket's permessage-deflate extension. Use 'default' for normal data, For details see [zlib's section on copression strategies](http://zlib.net/manual.html#Advanced) + +- **nchan_permessage_deflate_compression_window** `[ 9-15 ]` + arguments: 1 + default: `10` + context: http + > Compression window for the `deflate` algorithm used in websocket's permessage-deflate extension. The base two logarithm of the window size (the size of the history buffer). The bigger the window, the better the compression, but the more memory used by the compressor. + - **nchan_publisher** `[ http | websocket ]` arguments: 0 - 2 default: `http websocket` @@ -471,7 +1131,7 @@ Additionally, `nchan_stub_status` data is also exposed as variables. These are a context: server, location, if > Send POST request to internal location (which may proxy to an upstream server) with published message in the request body. Useful for bridging websocket publishers with HTTP applications, or for transforming message via upstream application before publishing to a channel. > The upstream response code determines how publishing will proceed. A `200 OK` will publish the message from the upstream response's body. A `304 Not Modified` will publish the message as it was received from the publisher. A `204 No Content` will result in the message not being published. - [more details](https://nchan.slact.net/details#message-publishing-callbacks) + [more details](#message-forwarding) - **nchan_pubsub** `[ http | websocket | eventsource | longpoll | intervalpoll | chunked | multipart-mixed | http-raw-stream ]` arguments: 0 - 6 @@ -480,6 +1140,12 @@ Additionally, `nchan_stub_status` data is also exposed as variables. These are a > Defines a server or location as a pubsub endpoint. For long-polling, GETs subscribe. and POSTs publish. For Websockets, publishing data on a connection does not yield a channel metadata response. Without additional configuration, this turns a location into an echo server. [more details](#pubsub-endpoint) +- **nchan_subscribe_request** `` + arguments: 1 + context: server, location, if + > Send GET request to internal location (which may proxy to an upstream server) after subscribing. Disabled for longpoll and interval-polling subscribers. + [more details](#subscriber-presence) + - **nchan_subscriber** `[ websocket | eventsource | longpoll | intervalpoll | chunked | multipart-mixed | http-raw-stream ]` arguments: 0 - 5 default: `websocket eventsource longpoll chunked multipart-mixed` @@ -535,37 +1201,111 @@ Additionally, `nchan_stub_status` data is also exposed as variables. These are a legacy name: push_subscriber_timeout > Maximum time a subscriber may wait for a message before being disconnected. If you don't want a subscriber's connection to timeout, set this to 0. When possible, the subscriber will get a response with a `408 Request Timeout` status; otherwise the subscriber will simply be disconnected. +- **nchan_unsubscribe_request** `` + arguments: 1 + context: server, location, if + > Send GET request to internal location (which may proxy to an upstream server) after unsubscribing. Disabled for longpoll and interval-polling subscribers. + [more details](#subscriber-presence) + +- **nchan_websocket_client_heartbeat** ` ` + arguments: 2 + default: `none (disabled)` + context: server, location, if + > Most browser Websocket clients do not allow manually sending PINGs to the server. To overcome this limitation, this setting can be used to set up a PING/PONG message/response connection heartbeat. When the client sends the server message *heartbeat_in* (PING), the server automatically responds with *heartbeat_out* (PONG). + - **nchan_websocket_ping_interval** ` (seconds)` arguments: 1 default: `0 (none)` context: server, location, if > Interval for sending websocket ping frames. Disabled by default. +- **nchan_access_control_allow_credentials** + arguments: 1 + default: `on` + context: http, server, location, if + > When enabled, sets the [Cross-Origin Resource Sharing (CORS)](https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS) `Access-Control-Allow-Credentials` header to `true`. + +- **nchan_access_control_allow_origin** `` + arguments: 1 + default: `$http_origin` + context: http, server, location, if + > Set the [Cross-Origin Resource Sharing (CORS)](https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS) `Access-Control-Allow-Origin` header to this value. If the incoming request's `Origin` header does not match this value, respond with a `403 Forbidden`. Multiple origins can be provided in a single argument separated with a space. + - **nchan_authorize_request** `` arguments: 1 context: server, location, if > Send GET request to internal location (which may proxy to an upstream server) for authorization of a publisher or subscriber request. A 200 response authorizes the request, a 403 response forbids it. - [more details](https://nchan.slact.net/details#request-authorization) + [more details](#request-authorization) -- **nchan_subscribe_request** `` +- **nchan_channel_group** `` arguments: 1 + default: `(none)` context: server, location, if - > Send GET request to internal location (which may proxy to an upstream server) after subscribing. Disabled for longpoll and interval-polling subscribers. - [more details](https://nchan.slact.net/details#subsribe-and-unsubscribe-callbacks) + legacy name: push_channel_group + > The accounting and security group a channel belongs to. Works like a prefix string to the channel id. Can be set with nginx variables. -- **nchan_unsubscribe_request** `` +- **nchan_channel_group_accounting** arguments: 1 - context: server, location, if - > Send GET request to internal location (which may proxy to an upstream server) after unsubscribing. Disabled for longpoll and interval-polling subscribers. - [more details](https://nchan.slact.net/details#subsribe-and-unsubscribe-callbacks) + default: `off` + context: server, location + > Enable tracking channel, subscriber, and message information on a per-channel-group basis. Can be used to place upper limits on channel groups. + +- **nchan_group_location** `[ get | set | delete | off ]` + arguments: 0 - 3 + default: `get set delete` + context: location + > Group information and configuration location. GET request for group info, POST to set limits, DELETE to delete all channels in group. -- **nchan_max_reserved_memory** `` +- **nchan_group_max_channels** `` arguments: 1 - default: `32M` - context: http - legacy name: push_max_reserved_memory - > The size of the shared memory chunk this module will use for message queuing and buffering. - [more details](#memory-storage) + default: `0 (unlimited)` + context: location + > Maximum number of channels allowed in the group. + +- **nchan_group_max_messages** `` + arguments: 1 + default: `0 (unlimited)` + context: location + > Maximum number of messages allowed for all the channels in the group. + +- **nchan_group_max_messages_disk** `` + arguments: 1 + default: `0 (unlimited)` + context: location + > Maximum amount of disk space allowed for the messages of all the channels in the group. + +- **nchan_group_max_messages_memory** `` + arguments: 1 + default: `0 (unlimited)` + context: location + > Maximum amount of shared memory allowed for the messages of all the channels in the group. + +- **nchan_group_max_subscribers** `` + arguments: 1 + default: `0 (unlimited)` + context: location + > Maximum number of subscribers allowed for the messages of all the channels in the group. + +- **nchan_max_channel_id_length** `` + arguments: 1 + default: `1024` + context: http, server, location + legacy name: push_max_channel_id_length + > Maximum permissible channel id length (number of characters). This settings applies to ids before they may be split by the `nchan_channel_id_split_delimiter` Requests with a channel id that is too long will receive a `403 Forbidden` response. + +- **nchan_max_channel_subscribers** `` + arguments: 1 + default: `0 (unlimited)` + context: http, server, location + legacy name: push_max_channel_subscribers + > Maximum concurrent subscribers to the channel on this Nchan server. Does not include subscribers on other Nchan instances when using a shared Redis server. + +- **nchan_subscribe_existing_channels_only** `[ on | off ]` + arguments: 1 + default: `off` + context: http, server, location + legacy name: push_authorized_channels_only + > Whether or not a subscriber may create a channel by sending a request to a subscriber location. If set to on, a publisher must send a POST or PUT request before a subscriber can request messages on the channel. Otherwise, all subscriber requests to nonexistent channels will get a 403 Forbidden response. - **nchan_message_buffer_length** `[ | ]` arguments: 1 @@ -574,6 +1314,12 @@ Additionally, `nchan_stub_status` data is also exposed as variables. These are a legacy names: push_max_message_buffer_length, push_message_buffer_length > Publisher configuration setting the maximum number of messages to store per channel. A channel's message buffer will retain a maximum of this many most recent messages. An Nginx variable can also be used to set the buffer length dynamically. +- **nchan_message_temp_path** `` + arguments: 1 + default: `` + context: http + > Large messages are stored in temporary files in the `client_body_temp_path` or the `nchan_message_temp_path` if the former is unavailable. Default is the built-in default `client_body_temp_path` + - **nchan_message_timeout** `[
File Name  ↓ File Size  ↓ Date  ↓ File Name  ↓ File Size  ↓ Date  ↓