mirror of
https://github.com/3proxy/3proxy.git
synced 2026-11-26 23:59:41 +08:00
Compare commits
No files matched your search
@@ -30,7 +30,8 @@ jobs:
|
|||||||
arch: arm_cortex-a7_neon-vfpv4
|
arch: arm_cortex-a7_neon-vfpv4
|
||||||
- target: mediatek/filogic
|
- target: mediatek/filogic
|
||||||
arch: aarch64_cortex-a53
|
arch: aarch64_cortex-a53
|
||||||
runs-on: ubuntu-latest
|
# 26.04: the OpenWrt SDK refuses its non-GNU install
|
||||||
|
runs-on: ubuntu-24.04
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v7
|
- uses: actions/checkout@v7
|
||||||
|
|
||||||
|
|||||||
@@ -18,7 +18,8 @@ jobs:
|
|||||||
strategy:
|
strategy:
|
||||||
matrix:
|
matrix:
|
||||||
target:
|
target:
|
||||||
- ubuntu-latest
|
# 26.04: rpm 6 runs %__gpg_sign_cmd differently, signing fails
|
||||||
|
- ubuntu-24.04
|
||||||
runs-on: ${{ matrix.target }}
|
runs-on: ${{ matrix.target }}
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v7
|
- uses: actions/checkout@v7
|
||||||
|
|||||||
@@ -40,6 +40,8 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
echo "volatile char VerSion[]=^"3APA3A-3proxy-Internal-Build: 3proxy-%RELEASE%-%NOW%\r\n^";" >>src/3proxy.c
|
echo "volatile char VerSion[]=^"3APA3A-3proxy-Internal-Build: 3proxy-%RELEASE%-%NOW%\r\n^";" >>src/3proxy.c
|
||||||
nmake /F Makefile.watcom
|
nmake /F Makefile.watcom
|
||||||
|
if errorlevel 1 exit /b 1
|
||||||
|
if not exist bin\3proxy.exe (echo bin\3proxy.exe was not built & exit /b 1)
|
||||||
- name: make dist dir
|
- name: make dist dir
|
||||||
shell: cmd
|
shell: cmd
|
||||||
run: |
|
run: |
|
||||||
|
|||||||
@@ -273,3 +273,4 @@ bin/3proxy_udppm
|
|||||||
build*/*
|
build*/*
|
||||||
testcerts/
|
testcerts/
|
||||||
/.claude
|
/.claude
|
||||||
|
bench/mix/mix-linux-*
|
||||||
@@ -1,25 +1,13 @@
|
|||||||
3proxy-1.0.1 Released October, 10 2026
|
3proxy-1.0.3 Released November, 7 2026
|
||||||
|
|
||||||
! Fix: crash (segmentation fault) on configuration reload (SIGUSR1) on a busy server: a closing session could still use its service after the reload had freed it; the race existed since 0.9.7, the 5 second linger added in 0.9.9 made it much more likely (#1278)
|
! Fix: RADIUS authentication: the reply digest copied the shared secret right after the received bytes, so a reply of 4100 bytes with a secret of 17 or more characters wrote up to 47 bytes of it past the reply buffer on the stack, before the reply was authenticated; the digest is hashed over the reply and the secret in place now, with nothing written past the reply, and a reply is taken only from the address and port of the server the request went to, with the request's identifier and length, which was never checked before
|
||||||
! Fix: -Di and -De (bind to interface) were not applied to SOCKSv5 UDP ASSOCIATE and BIND sockets, the FTP proxy data connection and connect back (#1277)
|
! Fix: the PTR answer of a name server could write past the answer buffer on the stack: the label walk ran to the end of the whole message instead of the end of the record's data and could take a compression pointer for a label length (an answer of 3841 bytes or more reached past the buffer itself); the walk now stops at the end of the record's data, and a compressed, empty or truncated name is not accepted
|
||||||
! Fix: SOCKSv5 UDP ASSOCIATE over IPv6: the source address of a datagram was truncated and the reply was sent to the wrong address (#1279)
|
! Fix: every connection matching a pcre: (or regex:) rule matched on the one match data block of the rule, which pcre2_match() writes into: two connections matching at the same time raced and corrupted memory, bringing the process down under load; a connection now makes a match data block of its own
|
||||||
! Fix: SOCKSv5 UDP ASSOCIATE: an access rule with host names matched any datagram sent to a literal address; the address is used as the host name now, as it is for TCP requests
|
! Fix: TLS: a read which could only be done once a write was, or a write once a read was (a TLS 1.3 key update answered while the socket cannot take more, for example), ended the connection with an error; each TLS socket remembers now what its pending read and write wait for, and the poll of the TLS layer waits for that
|
||||||
! Fix: a request rewritten with pcre_rewrite was only logged and was sent unchanged to the server on a direct connection; the rewritten path and query are what the server receives now
|
! Fix: Windows: a TLS read or write which wanted the socket again was not seen as one and dropped the connection with an unrelated error: the C library's errno was set where the socket error is read
|
||||||
! Fix: buffer could be insufficient for the headers the HTTP proxy adds after a pcre_rewrite had grown the request
|
! Fix: a client of a connect back (-R) service stayed in accept() for the connection another client of the same service took, until the next one came, past its time out and through a configuration reload; the connect back socket is non-blocking now, and an accept() with nothing to take does not count as one of the client's tries
|
||||||
! Fix: heap buffer overflow in pcre_rewrite: a $N reference to a group which did not match was written out as its digits, which the space allocated for the result did not count
|
! Fix: ftppr: the answer of a server which logs in on USER alone (230, as anonymous FTP often does) or refuses the login was read but never handed to the client, which was left waiting for the answer to its PASS until the time out (#1284)
|
||||||
! Fix: pcre_extend did nothing, the rules it appended were never consulted; the manual described an argument the command does not take
|
! Fix: plugins: StringsPlugin, cutting a string table line at its end, wrote NULs past the line, into what the buffer kept of longer lines read before or past its end; FilePlugin passed the TLS state of the connection where the client's parameters were expected, so sending a string table over a TLS connection read a TLS state as a clientparam
|
||||||
! Fix: certificates generated for TLS MitM (openssl) carried no subject and authority key identifiers and were refused by strict verifiers, including macOS clients, OpenSSL with x509_strict and Python 3.13
|
+ -B (for TCP services) splits the TLS ClientHello passed through tlspr in the middle of the server name (SNI), so DPI systems which do not reassemble it do not see the host name; TCP_NODELAY, set by default, must not be turned off, or the kernel may join the segments again; -s keeps the same effect where -s is not splice (#1283)
|
||||||
! Fix: null pointer dereference in ftppr on PASS without USER and in smtpp on a user name without a host
|
+ 3proxy --help (and the usage message of a bad invocation) lists what the build was made with: TLS and its backend, RADIUS, PCRE, IPv6, UNIX sockets, the built-in HTTP server, transparency, ODBC and the optional proxy services
|
||||||
! Fix: no service started with wolfSSL on glibc: the default thread stack was too small for wolfSSL thread-local storage, pthread_create() failed and the failure was not reported
|
+ An outgoing connection bound to an external address is bound with IP_BIND_ADDRESS_NO_PORT on Linux 4.2 and later: the port is chosen by connect() for the pair with the destination, so ports in use towards other destinations or closing in TIME_WAIT do not run the ephemeral range out; bind() no longer failed with result 12 or searched long for a port under many connections
|
||||||
! Fix: dnspr did not work on Windows; Windows builds answer UDP from a socket of their own again
|
|
||||||
+ Built-in HTTP server: httpsrv service with http rules to serve files (cached or with sendfile / TransmitFile), redirects, rewrites, fixed replies and proxypass to forward requests as the proxy does, so one port can serve both a site and a proxy; admin is httpsrv with the administration pages
|
|
||||||
+ Host names in access rules may be regular expressions with a pcre: (or regex:) prefix
|
|
||||||
+ transparent / notransparent commands: transparent proxying is built in (netfilter on Linux, pf on BSD, socket for divert-to and ipfw fwd), TransparentPlugin is removed and a configuration loading it keeps working
|
|
||||||
+ parent: weight may be written as a fraction (.5) or a percentage (50%); weight 0 is a fallback parent used only when every weighted parent of its group has failed; a failed parent is left out of the next attempt of the same connection
|
|
||||||
+ parent extport / intport: range of local ports for outgoing connections and for sockets facing the client (UDP ASSOCIATE, FTP data)
|
|
||||||
+ A parent given by host name is resolved for each connection when nserver is used, instead of once on configuration load
|
|
||||||
+ $$ in the configuration stands for a single dollar sign, a dollar inside quotes is ordinary text
|
|
||||||
+ OpenWrt package (procd init script, UCI configuration) and OpenWrt builds for mipsel_24kc, mips_24kc, arm_cortex-a7_neon-vfpv4 and aarch64_cortex-a53
|
|
||||||
- pop3p, imapp, smtpp and ftppr are not in a default build: build with MAILPROXY=true and FTP=true (CMake: 3PROXY_USE_MAILPROXY, 3PROXY_USE_FTP); without them the mail proxies run as tlspr negotiating STARTTLS, and ftppr refuses clients
|
|
||||||
- FTP over HTTP proxy (ftp:// URLs) is not in a default build either and has to be enabled explicitly: build with FTP=true (CMake: 3PROXY_USE_FTP), without it the HTTP proxy does not fetch ftp:// URLs
|
|
||||||
- Windows binaries are no longer signed with a self-signed Authenticode certificate, it gave no trust and triggered antivirus false positives
|
|
||||||
+12
-24
@@ -1,25 +1,13 @@
|
|||||||
3proxy-1.0.1 Вышел 10 Октября 2026
|
3proxy-1.0.3 Вышел 7 Ноября 2026
|
||||||
|
|
||||||
! Исправление: падение (segmentation fault) при перезагрузке конфигурации (SIGUSR1) на нагруженном сервере: закрывающаяся сессия могла обращаться к службе после того, как перезагрузка её освободила; гонка существовала с 0.9.7, а добавленная в 0.9.9 задержка закрытия (linger) в 5 секунд сделала её гораздо вероятнее (#1278)
|
! Исправление: аутентификация RADIUS: дайджест ответа копировал общий секрет сразу за принятыми байтами, так что ответ размером 4100 байт с секретом в 17 и более символов записывал до 47 байт секрета за буфер ответа на стеке, ещё до проверки подлинности ответа; дайджест теперь вычисляется по ответу и секрету на месте, ничего не записывая за буфер, а ответ принимается только с адреса и порта сервера, которому был адресован запрос, с совпадающими с запросом идентификатором и длиной: раньше отправитель ответа не проверялся вовсе
|
||||||
! Исправление: -Di и -De (привязка к интерфейсу) не применялись к сокетам SOCKSv5 UDP ASSOCIATE и BIND, к соединению данных FTP прокси и к обратному соединению (connect back) (#1277)
|
! Исправление: ответ PTR от сервера имён мог записать данные за буфер ответа на стеке: обход имён шёл до конца всего сообщения вместо конца данных записи и мог принять байт-указатель сжатия за длину метки (ответ размером 3841 байт и более выходил за сам буфер); теперь обход останавливается в конце данных записи, а сжатое, пустое или обрезанное имя не принимается
|
||||||
! Исправление: SOCKSv5 UDP ASSOCIATE по IPv6: адрес отправителя датаграммы обрезался, и ответ отправлялся не на тот адрес (#1279)
|
! Исправление: каждое соединение, проверяемое правилом pcre: (или regex:), сопоставлялось с единственным блоком данных сопоставления правила, в который пишет pcre2_match(): два соединения, сопоставляемые одновременно, конкурировали за него и портили память, приводя процесс к падению под нагрузкой; теперь каждое соединение получает собственный блок данных сопоставления
|
||||||
! Исправление: SOCKSv5 UDP ASSOCIATE: правило доступа с именами хостов срабатывало для любой датаграммы, отправленной на адрес, а не на имя; теперь адрес используется как имя хоста, так же как для запросов TCP
|
! Исправление: TLS: чтение, возможное только после записи, или запись только после чтения (например, когда TLS 1.3 отвечает на обновление ключей, а сокет больше не принимает данные) завершало соединение с ошибкой; каждый TLS-сокет теперь помнит, чего ждут его незавершённые чтение и запись, и poll() TLS-уровня ждёт именно этого
|
||||||
! Исправление: запрос, изменённый pcre_rewrite, только записывался в журнал, а при прямом соединении серверу отправлялся без изменений; теперь сервер получает изменённые путь и строку запроса
|
! Исправление: Windows: чтение или запись TLS, требующая повторного обращения к сокету, не распознавалась, и соединение завершалось с посторонней ошибкой: в месте чтения ошибки сокета устанавливалась ошибка libc (errno)
|
||||||
! Исправление: буфера могло не хватить для заголовков, добавляемых HTTP прокси, после того как pcre_rewrite увеличил запрос
|
! Исправление: клиент обратного соединения (connect back, -R) оставался в accept() в ожидании соединения, которое забрал другой клиент той же службы, до следующего соединения, переживая свой тайм-аут и перезагрузку конфигурации; сокет обратного соединения теперь неблокирующий, и accept() без соединения не считается попыткой клиента
|
||||||
! Исправление: переполнение буфера в куче в pcre_rewrite: ссылка $N на группу, не участвовавшую в совпадении, выводилась своими цифрами, которые не учитывались при выделении памяти под результат
|
! Исправление: ftppr: ответ сервера, входящего по одному USER (230, как часто бывает у анонимного FTP) или отказывающего во входе, прочитывался, но не передавался клиенту, который оставался ждать ответа на свой PASS до тайм-аута (#1284)
|
||||||
! Исправление: pcre_extend ничего не делал, добавленные им правила никогда не проверялись; в документации был описан аргумент, который команда не принимает
|
! Исправление: плагины: StringsPlugin, обрезая строку таблицы строк на её конце, записывал NUL за строкой, в остатки в буфере от прочитанных раньше более длинных строк или за его конец; FilePlugin передавал в socksend() состояние TLS соединения вместо параметров клиента, и отправка таблицы строк по TLS-соединению читала состояние TLS как clientparam
|
||||||
! Исправление: сертификаты, создаваемые для TLS MitM (openssl), не содержали идентификаторов ключа субъекта и издателя и отвергались строгой проверкой, в том числе клиентами macOS, OpenSSL с x509_strict и Python 3.13
|
+ -B (для TCP-служб) разбивает проходящий через tlspr ClientHello TLS посередине имени сервера (SNI), чтобы системы DPI, не собирающие его заново, не видели имя хоста; TCP_NODELAY, устанавливаемый по умолчанию, выключать нельзя, иначе ядро может снова склеить сегменты; -s сохраняет тот же эффект там, где -s не означает splice (#1283)
|
||||||
! Исправление: обращение по нулевому указателю в ftppr при PASS без USER и в smtpp при имени пользователя без хоста
|
+ 3proxy --help (и сообщение об использовании при неверном запуске) перечисляет, с чем собран бинарник: TLS и его серверная библиотека, RADIUS, PCRE, IPv6, сокеты Unix, встроенный HTTP-сервер, прозрачное проксирование, ODBC и необязательные прокси-службы
|
||||||
! Исправление: с wolfSSL на glibc не запускалась ни одна служба: стека потока по умолчанию не хватало для thread-local памяти wolfSSL, pthread_create() завершался ошибкой, о которой не сообщалось
|
+ Исходящее соединение, привязываемое к внешнему адресу, на Linux 4.2 и новее привязывается с IP_BIND_ADDRESS_NO_PORT: порт выбирает connect() для пары с адресом назначения, поэтому порты, занятые соединениями к другим адресам или закрывающиеся в TIME_WAIT, больше не исчерпывают эфемерный диапазон; bind() больше не завершался с результатом 12 при большом числе соединений и не тратил миллисекунды на поиск порта
|
||||||
! Исправление: dnspr не работал в Windows; сборки для Windows снова отвечают по UDP с отдельного сокета
|
|
||||||
+ Встроенный HTTP сервер: служба httpsrv с правилами http для отдачи файлов (из кэша или через sendfile / TransmitFile), перенаправлений, перезаписи, фиксированных ответов и proxypass для передачи запроса прокси, так что один порт может обслуживать и сайт, и прокси; admin — это httpsrv со страницами администрирования
|
|
||||||
+ Имена хостов в правилах доступа могут быть регулярными выражениями с префиксом pcre: (или regex:)
|
|
||||||
+ Команды transparent / notransparent: прозрачное проксирование встроено в 3proxy (netfilter в Linux, pf в BSD, socket для divert-to и ipfw fwd), TransparentPlugin удалён, конфигурация, загружающая его, продолжает работать
|
|
||||||
+ parent: вес можно задавать дробью (.5) или в процентах (50%); вес 0 означает резервный parent, который используется только когда отказали все parent его группы с ненулевым весом; отказавший parent исключается из следующей попытки того же соединения
|
|
||||||
+ parent extport / intport: диапазон локальных портов для исходящих соединений и для сокетов на стороне клиента (UDP ASSOCIATE, данные FTP)
|
|
||||||
+ parent, заданный именем хоста, разрешается для каждого соединения, если используется nserver, а не один раз при загрузке конфигурации
|
|
||||||
+ $$ в конфигурации обозначает одиночный знак доллара, доллар в кавычках — обычный символ
|
|
||||||
+ Пакет для OpenWrt (скрипт запуска procd, конфигурация UCI) и сборки OpenWrt для mipsel_24kc, mips_24kc, arm_cortex-a7_neon-vfpv4 и aarch64_cortex-a53
|
|
||||||
- pop3p, imapp, smtpp и ftppr не входят в сборку по умолчанию: собирайте с MAILPROXY=true и FTP=true (CMake: 3PROXY_USE_MAILPROXY, 3PROXY_USE_FTP); без них почтовые прокси работают как tlspr с согласованием STARTTLS, а ftppr отказывает клиентам
|
|
||||||
- FTP через HTTP прокси (адреса ftp://) также не входит в сборку по умолчанию и должен быть включён явно: собирайте с FTP=true (CMake: 3PROXY_USE_FTP), без этого HTTP прокси не обрабатывает адреса ftp://
|
|
||||||
- Двоичные файлы для Windows больше не подписываются самоподписанным сертификатом Authenticode: доверия он не давал и вызывал ложные срабатывания антивирусов
|
|
||||||
+12
-7
@@ -63,7 +63,7 @@ option(3PROXY_USE_OPENSSL "Enable TLS/SSL support via OpenSSL (fallback when wol
|
|||||||
option(3PROXY_USE_PCRE2 "Enable PCRE2 regex filtering" ON)
|
option(3PROXY_USE_PCRE2 "Enable PCRE2 regex filtering" ON)
|
||||||
option(3PROXY_USE_PAM "Enable PAM/PamAuth" ON)
|
option(3PROXY_USE_PAM "Enable PAM/PamAuth" ON)
|
||||||
option(3PROXY_USE_ODBC "Enable ODBC support (Unix only, always ON on Windows)" OFF)
|
option(3PROXY_USE_ODBC "Enable ODBC support (Unix only, always ON on Windows)" OFF)
|
||||||
option(3PROXY_USE_SPLICE "Build Linux splice() support, slower than read/write for most traffic (Linux only)" OFF)
|
option(3PROXY_USE_SPLICE "Build Linux splice() support, used by services given -s (Linux only)" ON)
|
||||||
option(3PROXY_USE_POLL "Use poll() instead of select() (Unix only)" ON)
|
option(3PROXY_USE_POLL "Use poll() instead of select() (Unix only)" ON)
|
||||||
option(3PROXY_USE_WSAPOLL "Use WSAPoll instead of select() (Windows only)" ON)
|
option(3PROXY_USE_WSAPOLL "Use WSAPoll instead of select() (Windows only)" ON)
|
||||||
option(3PROXY_USE_NETFILTER "Enable Linux netfilter support (Linux only)" ON)
|
option(3PROXY_USE_NETFILTER "Enable Linux netfilter support (Linux only)" ON)
|
||||||
@@ -415,11 +415,12 @@ set(3PROXY_CORE_SOURCES
|
|||||||
# Object libraries for common sources (shared between executables)
|
# Object libraries for common sources (shared between executables)
|
||||||
# ============================================================================
|
# ============================================================================
|
||||||
|
|
||||||
# Common object library (sockmap, sockgetchar, common, log)
|
# Common object library (sockmap, sockgetchar, common, sem, log)
|
||||||
add_library(common_obj OBJECT
|
add_library(common_obj OBJECT
|
||||||
src/sockmap.c
|
src/sockmap.c
|
||||||
src/sockgetchar.c
|
src/sockgetchar.c
|
||||||
src/common.c
|
src/common.c
|
||||||
|
src/sem.c
|
||||||
src/log.c
|
src/log.c
|
||||||
)
|
)
|
||||||
target_include_directories(common_obj PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src)
|
target_include_directories(common_obj PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src)
|
||||||
@@ -728,12 +729,12 @@ foreach(PROXY_NAME proxy socks pop3p imapp smtpp ftppr tcppm udppm tlspr)
|
|||||||
${CMAKE_CURRENT_SOURCE_DIR}/src
|
${CMAKE_CURRENT_SOURCE_DIR}/src
|
||||||
)
|
)
|
||||||
|
|
||||||
target_compile_definitions(${PROXY_NAME} PRIVATE
|
target_compile_definitions(${PROXY_NAME} PRIVATE WITHMAIN)
|
||||||
WITHMAIN
|
|
||||||
NOPORTMAP
|
|
||||||
)
|
|
||||||
|
|
||||||
if(NOT PROXY_NAME STREQUAL "udppm")
|
# each takes the main loop of its kind only: udppm UDP, the others TCP
|
||||||
|
if(PROXY_NAME STREQUAL "udppm")
|
||||||
|
target_compile_definitions(${PROXY_NAME} PRIVATE NOTCPMAIN)
|
||||||
|
else()
|
||||||
target_compile_definitions(${PROXY_NAME} PRIVATE NOUDPMAIN)
|
target_compile_definitions(${PROXY_NAME} PRIVATE NOUDPMAIN)
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
@@ -743,8 +744,12 @@ foreach(PROXY_NAME proxy socks pop3p imapp smtpp ftppr tcppm udppm tlspr)
|
|||||||
target_compile_definitions(${PROXY_NAME} PRIVATE ANONYMOUS)
|
target_compile_definitions(${PROXY_NAME} PRIVATE ANONYMOUS)
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
|
# port mappers take port, host and port as arguments, the others options
|
||||||
|
# only; one of the two is defined, as in src/Makefile.inc
|
||||||
if(PROXY_NAME STREQUAL "tcppm" OR PROXY_NAME STREQUAL "udppm" OR PROXY_NAME STREQUAL "tlspr")
|
if(PROXY_NAME STREQUAL "tcppm" OR PROXY_NAME STREQUAL "udppm" OR PROXY_NAME STREQUAL "tlspr")
|
||||||
target_compile_definitions(${PROXY_NAME} PRIVATE PORTMAP)
|
target_compile_definitions(${PROXY_NAME} PRIVATE PORTMAP)
|
||||||
|
else()
|
||||||
|
target_compile_definitions(${PROXY_NAME} PRIVATE NOPORTMAP)
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
if(WIN32)
|
if(WIN32)
|
||||||
|
|||||||
+4
-4
@@ -4,9 +4,9 @@
|
|||||||
# add -DWITH_ODBC to CFLAGS and -lodbc to LIBS to compile with ODBC
|
# add -DWITH_ODBC to CFLAGS and -lodbc to LIBS to compile with ODBC
|
||||||
# library support. Add -DSAFESQL for poorely written ODBC library / drivers.
|
# library support. Add -DSAFESQL for poorely written ODBC library / drivers.
|
||||||
#
|
#
|
||||||
# Linux splice() support is not built by default, it is slower than the
|
# Linux splice() support is built, but used only by services given the -s
|
||||||
# read/write path for most traffic. Add -DWITHSPLICE to CFLAGS to build it,
|
# option: it is faster for large transfers and slower for small requests.
|
||||||
# it must additionally be enabled per service with the -s option.
|
# Remove -DWITHSPLICE from CFLAGS to build without it.
|
||||||
|
|
||||||
BUILDDIR = ../bin/
|
BUILDDIR = ../bin/
|
||||||
PREFIX ?= 3proxy_
|
PREFIX ?= 3proxy_
|
||||||
@@ -14,7 +14,7 @@ CRYPT_PREFIX ?= $(PREFIX)
|
|||||||
CC ?= gcc
|
CC ?= gcc
|
||||||
|
|
||||||
CFLAGS ?= -O3 -flto
|
CFLAGS ?= -O3 -flto
|
||||||
CFLAGS += -fno-strict-aliasing -c -pthread -D_GNU_SOURCE -DGETHOSTBYNAME_R -D_THREAD_SAFE -D_REENTRANT -DFD_SETSIZE=4096 -DWITH_POLL -DWITH_NETFILTER -D WITH_UN
|
CFLAGS += -fno-strict-aliasing -c -pthread -DWITHSPLICE -D_GNU_SOURCE -DGETHOSTBYNAME_R -D_THREAD_SAFE -D_REENTRANT -DFD_SETSIZE=4096 -DWITH_POLL -DWITH_NETFILTER -D WITH_UN
|
||||||
COUT = -o
|
COUT = -o
|
||||||
LN ?= ${CC}
|
LN ?= ${CC}
|
||||||
DCFLAGS ?= -fPIC
|
DCFLAGS ?= -fPIC
|
||||||
|
|||||||
@@ -8,7 +8,8 @@
|
|||||||
|
|
||||||
- **Master** (current/latest) branch - 3proxy 1.0
|
- **Master** (current/latest) branch - 3proxy 1.0
|
||||||
- **0.9** (LTS) branch - 3proxy 0.9.9.x
|
- **0.9** (LTS) branch - 3proxy 0.9.9.x
|
||||||
- **Devel** branch - 3proxy 2.0-devel (don't use it)
|
- **Devel** branch - 3proxy 1.1 (development, don't use it in production)
|
||||||
|
- **Experimental** branch - 3proxy 2.0 (experimental, don't use it)
|
||||||
|
|
||||||
### Binaries (deb / rpm / Windows zip)
|
### Binaries (deb / rpm / Windows zip)
|
||||||
|
|
||||||
|
|||||||
+3
-2
@@ -4,8 +4,9 @@
|
|||||||
|
|
||||||
| Version | Supported |
|
| Version | Supported |
|
||||||
| ------- | ------------------ |
|
| ------- | ------------------ |
|
||||||
| 0.9.8 | :white_check_mark: |
|
| 0.9.9.x (LTS) | :white_check_mark: |
|
||||||
| < 0.9.8 | :x: |
|
| 1.0.x (Main) | :white_check_mark: |
|
||||||
|
| <= 0.9.8 | :x: |
|
||||||
|
|
||||||
## Hardening a deployment
|
## Hardening a deployment
|
||||||
|
|
||||||
|
|||||||
Vendored
+12
@@ -1,3 +1,15 @@
|
|||||||
|
3proxy (1.0.3-1) buster; urgency=medium
|
||||||
|
|
||||||
|
*3proxy 1.0.3 initial build
|
||||||
|
|
||||||
|
-- z3APA3A <3apa3a@3proxy.org> Sat, 07 Nov 2026 08:50:16 +0000
|
||||||
|
|
||||||
|
3proxy (1.0.2-1) buster; urgency=medium
|
||||||
|
|
||||||
|
*3proxy 1.0.2 initial build
|
||||||
|
|
||||||
|
-- z3APA3A <3apa3a@3proxy.org> Sat, 24 Oct 2026 11:21:40 +0000
|
||||||
|
|
||||||
3proxy (1.0.1-1) buster; urgency=medium
|
3proxy (1.0.1-1) buster; urgency=medium
|
||||||
|
|
||||||
*3proxy 1.0.1 initial build
|
*3proxy 1.0.1 initial build
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
! Fix: dnspr relayed to the client whatever came first to the socket it asked the name server from, from any address and under any id, so a forged answer could be passed on; the query now goes out under a random id, and only an answer from the name server asked, with that id and the same question, is relayed
|
||||||
|
! Fix: a client sending a part of a TLS record and then nothing kept a thread taking all of a CPU, and the read never timed out
|
||||||
|
! Fix: without -Ne, the reply to SOCKS CONNECT and BIND gave the address of the client's connection to the proxy instead of the socket towards the destination: a BIND client was told the proxy's own port and the peer could never reach it (since 0.9.6)
|
||||||
|
! Fix: a client which shut down its sending side (half-close) could get the answer cut short, megabytes short with large answers; likewise an upload after the server half-closed
|
||||||
|
! Fix: with chroot every local time was UTC and every syslog message was lost: the time zone is loaded and syslog connected before chroot; the chroot entry of 3proxy.cfg(5) lists what PAM, LDAP and ODBC still need inside the chroot
|
||||||
|
! Fix: the HTTP proxy closed the server connection of a kept-alive client and opened another one when only the request method changed (a POST after a GET to the same host)
|
||||||
|
! Fix: the last ssl_client_mode in the configuration applied to every service, and a reload changed it for the services still running
|
||||||
|
! Fix: memory leaks: on every refused configuration reload, on every failed TLS handshake, the server CA paths of every TLS service, compiled pcre: / regex: host names of access rules and patterns of httpsrv rules
|
||||||
|
! Fix: Unix sockets: on Linux a proxy listening on a Unix socket relayed only the first bytes of an answer (result 95); an abstract socket (unix:@NAME) was bound under a name padded with zeros, which clients did not reach; tcppm refused port 0 for a unix: target, as given in the manual's example; on a reload the socket file of a listening service was removed
|
||||||
|
! Fix: SIGPIPE could kill 3proxy when a client was gone while services were starting, and standalone services (proxy, socks, ...) at any time; sends use MSG_NOSIGNAL where the system has it
|
||||||
|
! Fix: TLS MitM failed for every connection with wolfSSL built with WOLFSSL_QT (wolfSSL 5.9.1 of Ubuntu 26.04): the source certificate's serial number could not be copied; a serial number made from the hash of the source certificate is used then
|
||||||
|
! Fix: Windows: closing a connection could leave its socket open (SO_LINGER on a non-blocking socket) or reset it while the peer still sent, so the end of an answer could be lost
|
||||||
|
! Fix: httpsrv: the body of a request answered without being read (for example when authentication is required) was read as the next request; a client still sending when a connection without keep-alive closed could get a reset instead of the answer
|
||||||
|
! Fix: httpsrv on Windows: UNC paths (\\server\share) did not work
|
||||||
|
! Fix: httpsrv and admin services and their clients were named ZOMBIE on the admin services page, in %N of logs and in RADIUS
|
||||||
|
! Fix: the Watcom (lite) build did not compile, 1.0.1 had no binaries for it
|
||||||
|
+ -s (splice) per direction: -s1 splices what the server sends (downloads), -s2 what the client sends (uploads), -s3 both; -s alone splices only where it pays (large bodies, long streams); pipes are kept with the connection for its next requests. splice() is built by default on Linux again and is used only by services given -s
|
||||||
|
+ Socket options (-oc, -os, -ol, -or, -oR) take NAME=VALUE; NAME=0 turns an option off, also one set by default; an unknown name or a value which is not a number is an error
|
||||||
|
+ The HTTP proxy frees its 64 KB request buffer while a CONNECT tunnel relays data and while a kept-alive connection waits for its next request: 2000 tunnels take 213 MB instead of 339 MB
|
||||||
|
+ TLS records are read ahead with OpenSSL 1.1.0 and later: decrypting takes 9-14% less CPU
|
||||||
|
+ Faster service stop and configuration reload, no fixed delays; a connection waiting for a free maxconn slot gets it at once
|
||||||
|
- TCP_NODELAY is set by default on proxy-to-client and proxy-to-server sockets; -ocTCP_NODELAY=0 / -osTCP_NODELAY=0 turns it off
|
||||||
|
- The HTTP proxy fetches ftp:// URLs only when the service is given the new -Xftp option (in a build with FTP=true)
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
! Fix: RADIUS authentication: the reply digest copied the shared secret right after the received bytes, so a reply of 4100 bytes with a secret of 17 or more characters wrote up to 47 bytes of it past the reply buffer on the stack, before the reply was authenticated; the digest is hashed over the reply and the secret in place now, with nothing written past the reply, and a reply is taken only from the address and port of the server the request went to, with the request's identifier and length, which was never checked before
|
||||||
|
! Fix: the PTR answer of a name server could write past the answer buffer on the stack: the label walk ran to the end of the whole message instead of the end of the record's data and could take a compression pointer for a label length (an answer of 3841 bytes or more reached past the buffer itself); the walk now stops at the end of the record's data, and a compressed, empty or truncated name is not accepted
|
||||||
|
! Fix: every connection matching a pcre: (or regex:) rule matched on the one match data block of the rule, which pcre2_match() writes into: two connections matching at the same time raced and corrupted memory, bringing the process down under load; a connection now makes a match data block of its own
|
||||||
|
! Fix: TLS: a read which could only be done once a write was, or a write once a read was (a TLS 1.3 key update answered while the socket cannot take more, for example), ended the connection with an error; each TLS socket remembers now what its pending read and write wait for, and the poll of the TLS layer waits for that
|
||||||
|
! Fix: Windows: a TLS read or write which wanted the socket again was not seen as one and dropped the connection with an unrelated error: the C library's errno was set where the socket error is read
|
||||||
|
! Fix: a client of a connect back (-R) service stayed in accept() for the connection another client of the same service took, until the next one came, past its time out and through a configuration reload; the connect back socket is non-blocking now, and an accept() with nothing to take does not count as one of the client's tries
|
||||||
|
! Fix: ftppr: the answer of a server which logs in on USER alone (230, as anonymous FTP often does) or refuses the login was read but never handed to the client, which was left waiting for the answer to its PASS until the time out (#1284)
|
||||||
|
! Fix: plugins: StringsPlugin, cutting a string table line at its end, wrote NULs past the line, into what the buffer kept of longer lines read before or past its end; FilePlugin passed the TLS state of the connection where the client's parameters were expected, so sending a string table over a TLS connection read a TLS state as a clientparam
|
||||||
|
+ -B (for TCP services) splits the TLS ClientHello passed through tlspr in the middle of the server name (SNI), so DPI systems which do not reassemble it do not see the host name; TCP_NODELAY, set by default, must not be turned off, or the kernel may join the segments again; -s keeps the same effect where -s is not splice (#1283)
|
||||||
|
+ 3proxy --help (and the usage message of a bad invocation) lists what the build was made with: TLS and its backend, RADIUS, PCRE, IPv6, UNIX sockets, the built-in HTTP server, transparency, ODBC and the optional proxy services
|
||||||
|
+ An outgoing connection bound to an external address is bound with IP_BIND_ADDRESS_NO_PORT on Linux 4.2 and later: the port is chosen by connect() for the pair with the destination, so ports in use towards other destinations or closing in TIME_WAIT do not run the ephemeral range out; bind() no longer failed with result 12 or searched long for a port under many connections
|
||||||
+38
-10
@@ -34,7 +34,8 @@ Each connected client requires:
|
|||||||
<ul>
|
<ul>
|
||||||
<li>1 thread (process)
|
<li>1 thread (process)
|
||||||
<li>2 sockets (file descriptors). For FTP, 4 sockets are required.
|
<li>2 sockets (file descriptors). For FTP, 4 sockets are required.
|
||||||
<br>Up to 128K of kernel buffer memory. This is the theoretical maximum; actual numbers depend on connection quality and traffic amount.
|
<br>With splice() (Linux, -s), a pipe (2 file descriptors) for each spliced direction: up to 4 more file descriptors, 6 for FTP.
|
||||||
|
<br>Up to 128K (up to 256K with splice()) of kernel buffer memory. This is the theoretical maximum; actual numbers depend on connection quality and traffic amount.
|
||||||
<br>1 additional socket (file descriptor) during name resolution for non-cached names
|
<br>1 additional socket (file descriptor) during name resolution for non-cached names
|
||||||
<br>1 additional socket during authentication or logging for RADIUS authentication or logging.
|
<br>1 additional socket during authentication or logging for RADIUS authentication or logging.
|
||||||
<li>1 ephemeral port (3 ephemeral ports for FTP connections).
|
<li>1 ephemeral port (3 ephemeral ports for FTP connections).
|
||||||
@@ -279,6 +280,8 @@ tuning anything else.
|
|||||||
|
|
||||||
If 3proxy is used in a VPS environment, there can be additional limitations.
|
If 3proxy is used in a VPS environment, there can be additional limitations.
|
||||||
For example, kernel resources, system CPU usage, and IOCTLs can be limited differently, and this can become a bottleneck.
|
For example, kernel resources, system CPU usage, and IOCTLs can be limited differently, and this can become a bottleneck.
|
||||||
|
splice() (see below) moves work into the kernel, so where the hosting limits kernel resources
|
||||||
|
(seen as nearly 100% CPU usage without any real activity of the application) do not enable it.
|
||||||
|
|
||||||
<h4>Extending the Ephemeral Port Range</h4>
|
<h4>Extending the Ephemeral Port Range</h4>
|
||||||
|
|
||||||
@@ -641,17 +644,42 @@ monitor "/some/path/3proxy/3proxy.ver"
|
|||||||
e.g., with "touch /some/path/3proxy/3proxy.ver".
|
e.g., with "touch /some/path/3proxy/3proxy.ver".
|
||||||
</ol>
|
</ol>
|
||||||
|
|
||||||
<h4>Use TCP_NODELAY to Speed Up Connections with Small Amounts of Data</h4>
|
<h4>TCP_NODELAY for Connections with Small Amounts of Data</h4>
|
||||||
|
|
||||||
If most requests require an exchange with a small amount of data in both directions
|
TCP_NODELAY is set by default on client (oc) and server (os)
|
||||||
without the need for bandwidth, e.g., messengers or small web requests,
|
connections: without it, Nagle's algorithm holds back a short write until the
|
||||||
you can eliminate Nagle's algorithm delay with the TCP_NODELAY flag. Usage example:
|
previous one is acknowledged, and a peer delays its acknowledgement, so a reply
|
||||||
|
written in more than one part (e.g. HTTP headers, then a short body) waits tens
|
||||||
|
of milliseconds. On slow connections with high delays, where the bandwidth is the
|
||||||
|
bottleneck and fewer packets matter more than latency, it can be turned off:
|
||||||
<pre>
|
<pre>
|
||||||
proxy -osTCP_NODELAY -ocTCP_NODELAY
|
proxy -osTCP_NODELAY=0 -ocTCP_NODELAY=0
|
||||||
</pre>
|
</pre>
|
||||||
sets TCP_NODELAY for client (oc) and server (os) connections.
|
|
||||||
<p>Do not use TCP_NODELAY on slow connections with high delays when
|
<h4>Use Splice to Speed Up Large Data Transfers</h4>
|
||||||
connection bandwidth is a bottleneck.
|
|
||||||
|
On Linux, splice() passes data between the client and the server connections
|
||||||
|
through a kernel pipe, without copying it into the 3proxy process. Linux builds
|
||||||
|
include it, but a service uses it only when given the -s option:
|
||||||
|
<pre>
|
||||||
|
proxy -s
|
||||||
|
socks -s
|
||||||
|
tcppm -s3 8080 192.168.1.1 80
|
||||||
|
</pre>
|
||||||
|
-s alone splices both directions where it pays: an HTTP body of known length if at
|
||||||
|
least 16K of it is left to read, a stream (CONNECT, SOCKS, tcppm) once it carries
|
||||||
|
large reads, going back to copying when they turn small. -s1 always splices what the
|
||||||
|
server sends to the client (downloads), -s2 what the client sends to the server
|
||||||
|
(uploads), -s3 both; -s5, -s6 and -s7 (the same as -s) do it for those directions
|
||||||
|
only where it pays. -s0, the default, turns it off. In builds without it (CMake option 3PROXY_USE_SPLICE=OFF,
|
||||||
|
or -DWITHSPLICE removed from the Makefile) -s is accepted and ignored.
|
||||||
|
<p>splice() pays off when most of the traffic is large transfers: in the
|
||||||
|
<a href="https://github.com/3proxy/3proxy/blob/devel/bench/RESULTS.md">benchmarks</a> it moved
|
||||||
|
1.3 to 2.1 times more data than the read/write path at 40-55% less CPU per gigabyte.
|
||||||
|
It does not help small requests and short connections, which go slower with it, and
|
||||||
|
every spliced direction needs a pipe (two file descriptors) and more kernel
|
||||||
|
buffer memory. Data filters are not applied to spliced data.
|
||||||
|
<p>TCP_NODELAY and splice() do not conflict and can be combined on high-speed connections.
|
||||||
|
|
||||||
<h4>Add Grace Delay to Reduce System Calls</h4>
|
<h4>Add Grace Delay to Reduce System Calls</h4>
|
||||||
|
|
||||||
@@ -661,7 +689,7 @@ the minimal number of packets in the same direction to apply the algorithm,
|
|||||||
and the last value is the delay added after polling and prior to reading data.
|
and the last value is the delay added after polling and prior to reading data.
|
||||||
The example above adds a 10-millisecond delay before reading data if the average
|
The example above adds a 10-millisecond delay before reading data if the average
|
||||||
polling size is below 8000 bytes and 3 read operations have been made in the same
|
polling size is below 8000 bytes and 3 read operations have been made in the same
|
||||||
direction. <pre>logdump 1 1</pre> is useful
|
direction. It's especially useful with splice. <pre>logdump 1 1</pre> is useful
|
||||||
to see how grace delays work; choose a delay value to avoid filling the read
|
to see how grace delays work; choose a delay value to avoid filling the read
|
||||||
buffer (typically 64K) but keep the request sizes close to the chosen average
|
buffer (typically 64K) but keep the request sizes close to the chosen average
|
||||||
on large file uploads/downloads.
|
on large file uploads/downloads.
|
||||||
@@ -648,16 +648,16 @@ see <a href="#DNSPR">How to set up a DNS proxy (dnspr)</a>.
|
|||||||
<br>tlspr can be used as a parent with the "tls" type to implement SNI splitting for DPI bypass (similar to NoDPI/GoodByeDPI).
|
<br>tlspr can be used as a parent with the "tls" type to implement SNI splitting for DPI bypass (similar to NoDPI/GoodByeDPI).
|
||||||
The client sends the first part of the TLS ClientHello, tlspr splits it at the SNI extension and sends it in two TCP packets,
|
The client sends the first part of the TLS ClientHello, tlspr splits it at the SNI extension and sends it in two TCP packets,
|
||||||
which can bypass some DPI systems that look for blocked hostnames in TLS handshakes.
|
which can bypass some DPI systems that look for blocked hostnames in TLS handshakes.
|
||||||
<br>To enable SNI break, use <code>parent ... tls 0.0.0.0 0</code> and the <code>-s</code> option on the listening service with TCP_NODELAY:
|
<br>To enable SNI break, use <code>parent ... tls 0.0.0.0 0</code> and the <code>-B</code> option on the listening service:
|
||||||
</p><pre>
|
</p><pre>
|
||||||
auth iponly
|
auth iponly
|
||||||
allow *
|
allow *
|
||||||
parent 1000 tls 0.0.0.0 0
|
parent 1000 tls 0.0.0.0 0
|
||||||
allow *
|
allow *
|
||||||
proxy -s -i127.0.0.1 -ocTCP_NODELAY -osTCP_NODELAY -p1443
|
proxy -B -i127.0.0.1 -p1443
|
||||||
</pre>
|
</pre>
|
||||||
<p>
|
<p>
|
||||||
TCP_NODELAY is required to prevent the kernel from merging the split packets.
|
TCP_NODELAY, set by default, is required to prevent the kernel from merging the split packets: do not turn it off with -ocTCP_NODELAY=0 or -osTCP_NODELAY=0.
|
||||||
</p>
|
</p>
|
||||||
<p>
|
<p>
|
||||||
<b>Configuration examples:</b>
|
<b>Configuration examples:</b>
|
||||||
|
|||||||
@@ -656,16 +656,16 @@ iptables -t nat -A PREROUTING -p tcp -m multiport --dports 443,993,465 -j REDIRE
|
|||||||
<br>tlspr может использоваться как родительский прокси типа "tls" для реализации SNI-фрагментации (аналог NoDPI/GoodByeDPI).
|
<br>tlspr может использоваться как родительский прокси типа "tls" для реализации SNI-фрагментации (аналог NoDPI/GoodByeDPI).
|
||||||
Клиент отправляет первую часть TLS ClientHello, tlspr разбивает его на расширении SNI и отправляет двумя TCP-пакетами,
|
Клиент отправляет первую часть TLS ClientHello, tlspr разбивает его на расширении SNI и отправляет двумя TCP-пакетами,
|
||||||
что позволяет обойти некоторые DPI-системы, ищущие заблокированные имена хостов в TLS-рукопожатиях.
|
что позволяет обойти некоторые DPI-системы, ищущие заблокированные имена хостов в TLS-рукопожатиях.
|
||||||
<br>Для включения SNI break используйте <code>parent ... tls 0.0.0.0 0</code> и опцию <code>-s</code> на слушающем сервисе с TCP_NODELAY:
|
<br>Для включения SNI break используйте <code>parent ... tls 0.0.0.0 0</code> и опцию <code>-B</code> на слушающем сервисе:
|
||||||
</p><pre>
|
</p><pre>
|
||||||
auth iponly
|
auth iponly
|
||||||
allow *
|
allow *
|
||||||
parent 1000 tls 0.0.0.0 0
|
parent 1000 tls 0.0.0.0 0
|
||||||
allow *
|
allow *
|
||||||
proxy -s -i127.0.0.1 -ocTCP_NODELAY -osTCP_NODELAY -p1443
|
proxy -B -i127.0.0.1 -p1443
|
||||||
</pre>
|
</pre>
|
||||||
<p>
|
<p>
|
||||||
TCP_NODELAY необходим, чтобы ядро не объединяло разделенные пакеты.
|
TCP_NODELAY, установленный по умолчанию, необходим, чтобы ядро не объединяло разделенные пакеты: не отключайте его опциями -ocTCP_NODELAY=0 или -osTCP_NODELAY=0.
|
||||||
</p>
|
</p>
|
||||||
<p>
|
<p>
|
||||||
<b>Примеры конфигурации:</b>
|
<b>Примеры конфигурации:</b>
|
||||||
|
|||||||
@@ -210,18 +210,30 @@ or hostname, useful in case of dynamic DNS. <b><br>
|
|||||||
-oR</b><i>OPTIONS</i> options for proxy-to-client
|
-oR</b><i>OPTIONS</i> options for proxy-to-client
|
||||||
(<b>-oc</b>), proxy-to-server (<b>-os</b>), proxy listening
|
(<b>-oc</b>), proxy-to-server (<b>-os</b>), proxy listening
|
||||||
(<b>-ol</b>), connect back client (<b>-or</b>), connect back
|
(<b>-ol</b>), connect back client (<b>-or</b>), connect back
|
||||||
listening (<b>-oR</b>) sockets. Options like TCP_CORK,
|
listening (<b>-oR</b>) sockets. <i>OPTIONS</i> is a comma
|
||||||
TCP_NODELAY, TCP_DEFER_ACCEPT, TCP_QUICKACK, TCP_TIMESTAMPS,
|
separated list of <i>NAME</i> or <i>NAME</i>=<i>VALUE</i>; a
|
||||||
|
name alone sets the option to 1 (TCP_MAXSEG to the value of
|
||||||
|
<b>maxseg</b>), and <i>NAME</i>=0 turns it off. Options add
|
||||||
|
to the defaults and to the options given earlier for the
|
||||||
|
same socket. An unknown name or a value which is not a
|
||||||
|
number is an error. TCP_NODELAY is set by default on
|
||||||
|
proxy-to-client and proxy-to-server sockets, so a reply
|
||||||
|
written in several parts is not delayed by Nagle’s
|
||||||
|
algorithm; use <b>-ocTCP_NODELAY=0</b> or
|
||||||
|
<b>-osTCP_NODELAY=0</b> to turn it off, e.g. to send fewer
|
||||||
|
packets on slow links. Options like TCP_CORK, TCP_NODELAY,
|
||||||
|
TCP_DEFER_ACCEPT, TCP_QUICKACK, TCP_TIMESTAMPS,
|
||||||
TCP_FASTOPEN, SO_REUSEADDR, SO_REUSEPORT,
|
TCP_FASTOPEN, SO_REUSEADDR, SO_REUSEPORT,
|
||||||
SO_EXCLUSIVEADDRUSE, SO_PORT_SCALABILITY,
|
SO_EXCLUSIVEADDRUSE, SO_PORT_SCALABILITY,
|
||||||
SO_REUSE_UNICASTPORT, SO_KEEPALIVE, SO_DONTROUTE may be
|
SO_REUSE_UNICASTPORT, SO_KEEPALIVE, SO_DONTROUTE may be
|
||||||
supported depending on OS. SO_REUSEADDR and SO_REUSEPORT are
|
supported depending on OS. SO_REUSEADDR and SO_REUSEPORT are
|
||||||
set on the listening socket by default on Unix. On Windows
|
set by default on the listening sockets (<b>-ol</b>,
|
||||||
SO_REUSEADDR is not set: it is not required to rebind a
|
<b>-oR</b>) on Unix; <b>-olSO_REUSEPORT=0</b> turns one off.
|
||||||
listening port and it only lets another local process bind
|
On Windows SO_REUSEADDR is not set: it is not required to
|
||||||
the same address and port. Use SO_EXCLUSIVEADDRUSE (Windows)
|
rebind a listening port and it only lets another local
|
||||||
on the listening socket (<b>-ol</b>) to prevent that.
|
process bind the same address and port. Use
|
||||||
<b><br>
|
SO_EXCLUSIVEADDRUSE (Windows) on the listening socket
|
||||||
|
(<b>-ol</b>) to prevent that. <b><br>
|
||||||
-H</b> (for all services) Expect HAProxy PROXY protocol v1
|
-H</b> (for all services) Expect HAProxy PROXY protocol v1
|
||||||
header on incoming connection. This allows the proxy to
|
header on incoming connection. This allows the proxy to
|
||||||
receive real client IP address from HAProxy or other load
|
receive real client IP address from HAProxy or other load
|
||||||
@@ -233,15 +245,34 @@ delay GRACE_DELAY milliseconds before polling if average
|
|||||||
polling size is below GRACE_TRAFF bytes and GRACE_NUM read
|
polling size is below GRACE_TRAFF bytes and GRACE_NUM read
|
||||||
operations in a single direction are detected within 1
|
operations in a single direction are detected within 1
|
||||||
second. Useful to minimize polling <b><br>
|
second. Useful to minimize polling <b><br>
|
||||||
|
-B</b> (for TCP services) split the TLS ClientHello across
|
||||||
|
two TCP segments in the middle of the server name (SNI) when
|
||||||
|
it is passed through tlspr, as with <b>parent ... tls
|
||||||
|
0.0.0.0 0</b>: some DPI systems looking for blocked host
|
||||||
|
names do not reassemble it. TCP_NODELAY, set by default,
|
||||||
|
must not be turned off, or the kernel may join the segments
|
||||||
|
again. In builds without splice() <b>-s</b> does the same.
|
||||||
|
<b><br>
|
||||||
-s</b> <br>
|
-s</b> <br>
|
||||||
(for admin) secure, allow only secure operations, currently
|
(for admin) secure, allow only secure operations, currently
|
||||||
only traffic counters view without ability to reset. <br>
|
only traffic counters view without ability to reset. <br>
|
||||||
(for TCP services, Linux) enable splice(). splice() is not
|
(for TCP services, Linux) use splice() to pass data between
|
||||||
built by default and is disabled even when built, because
|
the client and the server without copying it through 3proxy.
|
||||||
current Linux does not implement SPLICE_F_MOVE, so no real
|
<b>-s</b> alone splices both directions where it pays: a
|
||||||
zero-copy takes place and the read/write path is faster for
|
body of known length if at least 16K of it is left to read,
|
||||||
most traffic. Rebuild with -DWITHSPLICE to make -s
|
a stream once it carries large reads, back to copying when
|
||||||
available, -s0 disables it explicitly. <b><br>
|
they turn small. <b>-s1</b> always splices what the server
|
||||||
|
sends to the client (downloads), <b>-s2</b> what the client
|
||||||
|
sends (uploads), <b>-s3</b> both; adding 4 (<b>-s5</b>,
|
||||||
|
<b>-s6</b>, <b>-s7</b>, the last the same as <b>-s</b>)
|
||||||
|
splices those directions only where it pays. <b>-s0</b>, the
|
||||||
|
default, turns it off. splice() suits large transfers: they
|
||||||
|
go faster and use less CPU; small requests go slower with
|
||||||
|
it. A spliced direction needs a pipe (two file descriptors),
|
||||||
|
made when first needed and kept for the connection, and more
|
||||||
|
kernel memory; data filters are not applied to spliced data.
|
||||||
|
Available in builds with WITHSPLICE, the default on Linux.
|
||||||
|
<b><br>
|
||||||
-C</b> <br>
|
-C</b> <br>
|
||||||
(for TCP services) a connection closed by any of the sides
|
(for TCP services) a connection closed by any of the sides
|
||||||
terminates the session, buffered data is delivered before
|
terminates the session, buffered data is delivered before
|
||||||
@@ -277,7 +308,12 @@ client reported) <b><br>
|
|||||||
-a1</b> (for proxy) anonymous proxy (random client
|
-a1</b> (for proxy) anonymous proxy (random client
|
||||||
information reported) <b><br>
|
information reported) <b><br>
|
||||||
-a2</b> (for proxy) generate Via: and X-Forwarded-For:
|
-a2</b> (for proxy) generate Via: and X-Forwarded-For:
|
||||||
instead of Forwarded: <br>
|
instead of Forwarded: <b><br>
|
||||||
|
-Xftp</b> (for proxy) fetch <b>ftp://</b> URLs, in a build
|
||||||
|
with FTP support. Without this the scheme is not one the
|
||||||
|
service knows, whatever the build: fetching it opens a
|
||||||
|
second connection and builds a listing, which a service
|
||||||
|
serving http has no use for. <br>
|
||||||
Also, all options mentioned for <b>proxy</b>(8)
|
Also, all options mentioned for <b>proxy</b>(8)
|
||||||
<b>socks</b>(8) <b>pop3p</b>(8) <b>imapp</b>(8)
|
<b>socks</b>(8) <b>pop3p</b>(8) <b>imapp</b>(8)
|
||||||
<b>tcppm</b>(8) <b>udppm</b>(8) <b>ftppr</b>(8) <br>
|
<b>tcppm</b>(8) <b>udppm</b>(8) <b>ftppr</b>(8) <br>
|
||||||
@@ -1300,8 +1336,15 @@ groupname. Unix only.</p>
|
|||||||
<i><path></i> [<i><uid></i>]
|
<i><path></i> [<i><uid></i>]
|
||||||
[<i><gid></i>] <br>
|
[<i><gid></i>] <br>
|
||||||
calls chroot(path) and sets gid/uid. Unix only. uid/gid
|
calls chroot(path) and sets gid/uid. Unix only. uid/gid
|
||||||
supported since 0.9, can be numeric or
|
supported since 0.9, can be numeric or username/groupname.
|
||||||
username/groupname</p>
|
The time zone and the syslog connection are set up before
|
||||||
|
the call. Plugins which read their own configuration or load
|
||||||
|
modules while running need them inside the chroot: PAM
|
||||||
|
(<i>/etc/pam.d</i> and the modules it names, read for every
|
||||||
|
authentication), LDAP (<i>ldap.conf</i> and, for ldaps, the
|
||||||
|
CA certificates), ODBC (<i>odbc.ini</i>, <i>odbcinst.ini</i>
|
||||||
|
and the driver libraries, loaded again whenever the
|
||||||
|
connection is reopened).</p>
|
||||||
|
|
||||||
|
|
||||||
<p style="margin-left:9%; margin-top: 1em"><b>stacksize</b>
|
<p style="margin-left:9%; margin-top: 1em"><b>stacksize</b>
|
||||||
@@ -1590,10 +1633,12 @@ authentication and/or allow/deny ACLs.</p>
|
|||||||
and FTP are built when they are asked for, and are not in a
|
and FTP are built when they are asked for, and are not in a
|
||||||
default build. <b>MAILPROXY=true</b> builds <b>pop3p</b>,
|
default build. <b>MAILPROXY=true</b> builds <b>pop3p</b>,
|
||||||
<b>imapp</b> and <b>smtpp</b>, and <b>FTP=true</b> builds
|
<b>imapp</b> and <b>smtpp</b>, and <b>FTP=true</b> builds
|
||||||
<b>ftppr</b> and the <b>ftp://</b> scheme of the HTTP proxy;
|
<b>ftppr</b> and the <b>ftp://</b> scheme of the HTTP proxy,
|
||||||
with CMake the switches are <b>-D3PROXY_USE_MAILPROXY=ON</b>
|
which a <b>proxy</b> service then still has to ask for with
|
||||||
and <b>-D3PROXY_USE_FTP=ON</b>. The standalone binaries of
|
<b>-Xftp</b>; with CMake the switches are
|
||||||
those services are built with them and not without. <br>
|
<b>-D3PROXY_USE_MAILPROXY=ON</b> and
|
||||||
|
<b>-D3PROXY_USE_FTP=ON</b>. The standalone binaries of those
|
||||||
|
services are built with them and not without. <br>
|
||||||
A configuration naming a service which was not built is
|
A configuration naming a service which was not built is
|
||||||
still read. The three mail proxies become <b>tlspr</b>
|
still read. The three mail proxies become <b>tlspr</b>
|
||||||
negotiating STARTTLS in that protocol, which is what most of
|
negotiating STARTTLS in that protocol, which is what most of
|
||||||
|
|||||||
@@ -230,15 +230,16 @@ a certificate (not compatible with TLS 1.3)</p></td></tr>
|
|||||||
<td width="4%">
|
<td width="4%">
|
||||||
|
|
||||||
|
|
||||||
<p><b>-s</b></p></td>
|
<p><b>-B</b></p></td>
|
||||||
<td width="5%"></td>
|
<td width="5%"></td>
|
||||||
<td width="82%">
|
<td width="82%">
|
||||||
|
|
||||||
|
|
||||||
<p>Split the TLS Client HELLO packet across multiple TCP
|
<p>Split the TLS Client HELLO packet across two TCP
|
||||||
segments to make SNI-based DPI detection harder. An optional
|
segments, in the middle of the SNI, to make SNI-based DPI
|
||||||
numeric value can follow (e.g. <b>-s1</b>) to control the
|
detection harder. In builds without splice() <b>-s</b> does
|
||||||
splitting behaviour.</p></td></tr>
|
the same; with splice() (Linux) <b>-s</b> is splice, see
|
||||||
|
<b>3proxy.cfg</b>(5).</p> </td></tr>
|
||||||
</table>
|
</table>
|
||||||
|
|
||||||
<p style="margin-left:9%;"><b>-Ximap | -Xpop3 |
|
<p style="margin-left:9%;"><b>-Ximap | -Xpop3 |
|
||||||
|
|||||||
+36
-8
@@ -184,8 +184,10 @@ connect to given remote HOST:port instead of listening local connection on -p or
|
|||||||
.br
|
.br
|
||||||
.B -oc\fIOPTIONS\fB, -os\fIOPTIONS\fB, -ol\fIOPTIONS\fB, -or\fIOPTIONS\fB, -oR\fIOPTIONS\fR
|
.B -oc\fIOPTIONS\fB, -os\fIOPTIONS\fB, -ol\fIOPTIONS\fB, -or\fIOPTIONS\fB, -oR\fIOPTIONS\fR
|
||||||
options for proxy-to-client (\fB-oc\fR), proxy-to-server (\fB-os\fR), proxy listening (\fB-ol\fR), connect back client (\fB-or\fR), connect back listening (\fB-oR\fR) sockets.
|
options for proxy-to-client (\fB-oc\fR), proxy-to-server (\fB-os\fR), proxy listening (\fB-ol\fR), connect back client (\fB-or\fR), connect back listening (\fB-oR\fR) sockets.
|
||||||
|
\fIOPTIONS\fR is a comma separated list of \fINAME\fR or \fINAME\fR=\fIVALUE\fR; a name alone sets the option to 1 (TCP_MAXSEG to the value of \fBmaxseg\fR), and \fINAME\fR=0 turns it off. Options add to the defaults and to the options given earlier for the same socket. An unknown name or a value which is not a number is an error.
|
||||||
|
TCP_NODELAY is set by default on proxy-to-client and proxy-to-server sockets, so a reply written in several parts is not delayed by Nagle's algorithm; use \fB-ocTCP_NODELAY=0\fR or \fB-osTCP_NODELAY=0\fR to turn it off, e.g. to send fewer packets on slow links.
|
||||||
Options like TCP_CORK, TCP_NODELAY, TCP_DEFER_ACCEPT, TCP_QUICKACK, TCP_TIMESTAMPS, TCP_FASTOPEN, SO_REUSEADDR, SO_REUSEPORT, SO_EXCLUSIVEADDRUSE, SO_PORT_SCALABILITY, SO_REUSE_UNICASTPORT, SO_KEEPALIVE, SO_DONTROUTE may be supported depending on OS.
|
Options like TCP_CORK, TCP_NODELAY, TCP_DEFER_ACCEPT, TCP_QUICKACK, TCP_TIMESTAMPS, TCP_FASTOPEN, SO_REUSEADDR, SO_REUSEPORT, SO_EXCLUSIVEADDRUSE, SO_PORT_SCALABILITY, SO_REUSE_UNICASTPORT, SO_KEEPALIVE, SO_DONTROUTE may be supported depending on OS.
|
||||||
SO_REUSEADDR and SO_REUSEPORT are set on the listening socket by default on Unix. On Windows SO_REUSEADDR is not set: it is not required to rebind a listening port and it only lets another local process bind the same address and port. Use SO_EXCLUSIVEADDRUSE (Windows) on the listening socket (\fB-ol\fR) to prevent that.
|
SO_REUSEADDR and SO_REUSEPORT are set by default on the listening sockets (\fB-ol\fR, \fB-oR\fR) on Unix; \fB-olSO_REUSEPORT=0\fR turns one off. On Windows SO_REUSEADDR is not set: it is not required to rebind a listening port and it only lets another local process bind the same address and port. Use SO_EXCLUSIVEADDRUSE (Windows) on the listening socket (\fB-ol\fR) to prevent that.
|
||||||
.br
|
.br
|
||||||
.B -H
|
.B -H
|
||||||
(for all services) Expect HAProxy PROXY protocol v1 header on incoming connection.
|
(for all services) Expect HAProxy PROXY protocol v1 header on incoming connection.
|
||||||
@@ -196,15 +198,29 @@ any protocol-specific data.
|
|||||||
.B -g(\fIGRACE_TRAFF\fB,\fIGRACE_NUM\fB,\fIGRACE_DELAY\fR)
|
.B -g(\fIGRACE_TRAFF\fB,\fIGRACE_NUM\fB,\fIGRACE_DELAY\fR)
|
||||||
delay GRACE_DELAY milliseconds before polling if average polling size is below GRACE_TRAFF bytes and GRACE_NUM read operations in a single direction are detected within 1 second. Useful to minimize polling
|
delay GRACE_DELAY milliseconds before polling if average polling size is below GRACE_TRAFF bytes and GRACE_NUM read operations in a single direction are detected within 1 second. Useful to minimize polling
|
||||||
.br
|
.br
|
||||||
|
.B -B
|
||||||
|
(for TCP services) split the TLS ClientHello across two TCP segments in the
|
||||||
|
middle of the server name (SNI) when it is passed through tlspr, as with
|
||||||
|
\fBparent ... tls 0.0.0.0 0\fR: some DPI systems looking for blocked host names
|
||||||
|
do not reassemble it. TCP_NODELAY, set by default, must not be turned off, or the
|
||||||
|
kernel may join the segments again. In builds without splice() \fB-s\fR does the same.
|
||||||
|
.br
|
||||||
.B -s
|
.B -s
|
||||||
(for admin) secure, allow only secure operations, currently only traffic counters
|
(for admin) secure, allow only secure operations, currently only traffic counters
|
||||||
view without ability to reset.
|
view without ability to reset.
|
||||||
.br
|
.br
|
||||||
(for TCP services, Linux) enable splice(). splice() is not built by default and
|
(for TCP services, Linux) use splice() to pass data between the client and the
|
||||||
is disabled even when built, because current Linux does not implement
|
server without copying it through 3proxy. \fB-s\fR alone splices both directions where
|
||||||
SPLICE_F_MOVE, so no real zero-copy takes place and the read/write path is faster
|
it pays: a body of known length if at least 16K of it is left to read, a stream
|
||||||
for most traffic. Rebuild with -DWITHSPLICE to make -s available, -s0 disables it
|
once it carries large reads, back to copying when they turn small. \fB-s1\fR always
|
||||||
explicitly.
|
splices what the server sends to the client (downloads), \fB-s2\fR what the client
|
||||||
|
sends (uploads), \fB-s3\fR both; adding 4 (\fB-s5\fR, \fB-s6\fR, \fB-s7\fR, the last the same as
|
||||||
|
\fB-s\fR) splices those directions only where it pays. \fB-s0\fR, the default, turns it
|
||||||
|
off. splice() suits large transfers: they go faster and use less CPU; small
|
||||||
|
requests go slower with it. A spliced direction needs a pipe (two file
|
||||||
|
descriptors), made when first needed and kept for the connection, and more
|
||||||
|
kernel memory; data filters are not applied to spliced data. Available in builds
|
||||||
|
with WITHSPLICE, the default on Linux.
|
||||||
.br
|
.br
|
||||||
.B -C
|
.B -C
|
||||||
(for TCP services) a connection closed by any of the sides terminates the
|
(for TCP services) a connection closed by any of the sides terminates the
|
||||||
@@ -244,6 +260,12 @@ Never ask for username/password
|
|||||||
.br
|
.br
|
||||||
.B -a2
|
.B -a2
|
||||||
(for proxy) generate Via: and X-Forwarded-For: instead of Forwarded:
|
(for proxy) generate Via: and X-Forwarded-For: instead of Forwarded:
|
||||||
|
.br
|
||||||
|
.B -Xftp
|
||||||
|
(for proxy) fetch \fBftp://\fR URLs, in a build with FTP support. Without
|
||||||
|
this the scheme is not one the service knows, whatever the build: fetching it
|
||||||
|
opens a second connection and builds a listing, which a service serving http
|
||||||
|
has no use for.
|
||||||
.br
|
.br
|
||||||
Also, all options mentioned for
|
Also, all options mentioned for
|
||||||
.BR proxy (8)
|
.BR proxy (8)
|
||||||
@@ -1373,7 +1395,12 @@ for all threads.
|
|||||||
.BR chroot
|
.BR chroot
|
||||||
\fI<path>\fR [\fI<uid>\fR] [\fI<gid>\fR]
|
\fI<path>\fR [\fI<uid>\fR] [\fI<gid>\fR]
|
||||||
.br
|
.br
|
||||||
calls chroot(path) and sets gid/uid. Unix only. uid/gid supported since 0.9, can be numeric or username/groupname
|
calls chroot(path) and sets gid/uid. Unix only. uid/gid supported since 0.9, can be numeric or username/groupname.
|
||||||
|
The time zone and the syslog connection are set up before the call.
|
||||||
|
Plugins which read their own configuration or load modules while running need them inside the chroot:
|
||||||
|
PAM (\fI/etc/pam.d\fR and the modules it names, read for every authentication),
|
||||||
|
LDAP (\fIldap.conf\fR and, for ldaps, the CA certificates),
|
||||||
|
ODBC (\fIodbc.ini\fR, \fIodbcinst.ini\fR and the driver libraries, loaded again whenever the connection is reopened).
|
||||||
|
|
||||||
.br
|
.br
|
||||||
.BR stacksize
|
.BR stacksize
|
||||||
@@ -1639,7 +1666,8 @@ authentication and/or allow/deny ACLs.
|
|||||||
The mail proxies and FTP are built when they are asked for, and are not in a
|
The mail proxies and FTP are built when they are asked for, and are not in a
|
||||||
default build. \fBMAILPROXY=true\fR builds \fBpop3p\fR, \fBimapp\fR and
|
default build. \fBMAILPROXY=true\fR builds \fBpop3p\fR, \fBimapp\fR and
|
||||||
\fBsmtpp\fR, and \fBFTP=true\fR builds \fBftppr\fR and the \fBftp://\fR
|
\fBsmtpp\fR, and \fBFTP=true\fR builds \fBftppr\fR and the \fBftp://\fR
|
||||||
scheme of the HTTP proxy; with CMake the switches are
|
scheme of the HTTP proxy, which a \fBproxy\fR service then still has to ask
|
||||||
|
for with \fB-Xftp\fR; with CMake the switches are
|
||||||
\fB-D3PROXY_USE_MAILPROXY=ON\fR and \fB-D3PROXY_USE_FTP=ON\fR. The standalone
|
\fB-D3PROXY_USE_MAILPROXY=ON\fR and \fB-D3PROXY_USE_FTP=ON\fR. The standalone
|
||||||
binaries of those services are built with them and not without.
|
binaries of those services are built with them and not without.
|
||||||
.br
|
.br
|
||||||
|
|||||||
+2
-2
@@ -76,8 +76,8 @@ destination_port. Port to establish outgoing connections. Required unless the Tr
|
|||||||
.B -c
|
.B -c
|
||||||
TLS_CHECK_LEVEL. 0 (default) - allow non-TLS traffic to pass, 1 - require TLS, only check client HELLO packet, 2 - require TLS, check both client and server HELLO, 3 - require TLS, check that the server sends a certificate (not compatible with TLS 1.3), 4 - require mutual TLS, check that the server sends a certificate request and the client sends a certificate (not compatible with TLS 1.3)
|
TLS_CHECK_LEVEL. 0 (default) - allow non-TLS traffic to pass, 1 - require TLS, only check client HELLO packet, 2 - require TLS, check both client and server HELLO, 3 - require TLS, check that the server sends a certificate (not compatible with TLS 1.3), 4 - require mutual TLS, check that the server sends a certificate request and the client sends a certificate (not compatible with TLS 1.3)
|
||||||
.TP
|
.TP
|
||||||
.B -s
|
.B -B
|
||||||
Split the TLS Client HELLO packet across multiple TCP segments to make SNI-based DPI detection harder. An optional numeric value can follow (e.g. \fB-s1\fR) to control the splitting behaviour.
|
Split the TLS Client HELLO packet across two TCP segments, in the middle of the SNI, to make SNI-based DPI detection harder. In builds without splice() \fB-s\fR does the same; with splice() (Linux) \fB-s\fR is splice, see \fB3proxy.cfg\fR(5).
|
||||||
.TP
|
.TP
|
||||||
.B -Ximap | -Xpop3 | -Xsmtp
|
.B -Ximap | -Xpop3 | -Xsmtp
|
||||||
STARTTLS mode for the given protocol. The proxy speaks the plaintext protocol
|
STARTTLS mode for the given protocol. The proxy speaks the plaintext protocol
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
Name: 3proxy
|
Name: 3proxy
|
||||||
Version: 1.0.1
|
Version: 1.0.3
|
||||||
Release: 1%{?dist}
|
Release: 1%{?dist}
|
||||||
Summary: 3proxy tiny proxy server
|
Summary: 3proxy tiny proxy server
|
||||||
License: GPL/LGPL/Apache/BSD
|
License: GPL/LGPL/Apache/BSD
|
||||||
|
|||||||
+75
-25
@@ -74,13 +74,8 @@ void __stdcall CommandHandler( DWORD dwCommand )
|
|||||||
SetStatus( SERVICE_STOP_PENDING, 0, 1 );
|
SetStatus( SERVICE_STOP_PENDING, 0, 1 );
|
||||||
conf.timetoexit = 1;
|
conf.timetoexit = 1;
|
||||||
conf.paused++;
|
conf.paused++;
|
||||||
Sleep(2000);
|
/* ServiceMain() reports the service stopped once cyclestep() has
|
||||||
SetStatus( SERVICE_STOPPED, 0, 0 );
|
seen this and the services are done */
|
||||||
#ifdef WITH_ODBC
|
|
||||||
_3proxy_mutex_lock(&log_mutex);
|
|
||||||
close_sql();
|
|
||||||
_3proxy_mutex_unlock(&log_mutex);
|
|
||||||
#endif
|
|
||||||
break;
|
break;
|
||||||
case SERVICE_CONTROL_PAUSE:
|
case SERVICE_CONTROL_PAUSE:
|
||||||
SetStatus( SERVICE_PAUSE_PENDING, 0, 1 );
|
SetStatus( SERVICE_PAUSE_PENDING, 0, 1 );
|
||||||
@@ -106,6 +101,13 @@ void __stdcall ServiceMain(int argc, unsigned char* argv[] )
|
|||||||
SetStatus( SERVICE_START_PENDING, 0, 1 );
|
SetStatus( SERVICE_START_PENDING, 0, 1 );
|
||||||
SetStatus( SERVICE_RUNNING, 0, 0 );
|
SetStatus( SERVICE_RUNNING, 0, 0 );
|
||||||
cyclestep();
|
cyclestep();
|
||||||
|
#ifdef WITH_ODBC
|
||||||
|
_3proxy_mutex_lock(&log_mutex);
|
||||||
|
close_sql();
|
||||||
|
_3proxy_mutex_unlock(&log_mutex);
|
||||||
|
#endif
|
||||||
|
/* the last thing: the process may be ended once this is reported */
|
||||||
|
SetStatus( SERVICE_STOPPED, 0, 0 );
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
@@ -240,6 +242,39 @@ void dumpcounters(struct trafcount *tlin, int counterd){
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Lets the services finish before the process exits, for EXITWAIT ms at
|
||||||
|
most: each one waits for its connections, and a connection may hang on
|
||||||
|
its peer. Posts left over from reloads are consumed on the way, the
|
||||||
|
count decides. */
|
||||||
|
#define EXITWAIT 3000
|
||||||
|
static unsigned long nowms(void){
|
||||||
|
#ifdef _WIN32
|
||||||
|
return (unsigned long)GetTickCount();
|
||||||
|
#else
|
||||||
|
struct timeval tv;
|
||||||
|
|
||||||
|
gettimeofday(&tv, NULL);
|
||||||
|
return (unsigned long)tv.tv_sec * 1000 + tv.tv_usec / 1000;
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
static void waitservices(void){
|
||||||
|
unsigned long start = nowms(), passed;
|
||||||
|
|
||||||
|
for(;;){
|
||||||
|
int n;
|
||||||
|
|
||||||
|
_3proxy_mutex_lock(&runningservices_mutex);
|
||||||
|
n = runningservices;
|
||||||
|
_3proxy_mutex_unlock(&runningservices_mutex);
|
||||||
|
if(!n) return;
|
||||||
|
/* a clock set back makes this huge, which ends the wait as well */
|
||||||
|
passed = nowms() - start;
|
||||||
|
if(passed >= EXITWAIT) return;
|
||||||
|
if(_3proxy_sem_timedlock(serviceexited, (unsigned)(EXITWAIT - passed))) return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
void cyclestep(void){
|
void cyclestep(void){
|
||||||
struct tm *tm;
|
struct tm *tm;
|
||||||
time_t minutecounter;
|
time_t minutecounter;
|
||||||
@@ -336,9 +371,7 @@ void cyclestep(void){
|
|||||||
if(conf.timetoexit){
|
if(conf.timetoexit){
|
||||||
conf.paused++;
|
conf.paused++;
|
||||||
doschedule();
|
doschedule();
|
||||||
usleep(SLEEPTIME*999);
|
waitservices();
|
||||||
usleep(SLEEPTIME*999);
|
|
||||||
usleep(SLEEPTIME*999);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -349,6 +382,21 @@ void cyclestep(void){
|
|||||||
#define RETURN(x) {res = x; goto CLEARRETURN;}
|
#define RETURN(x) {res = x; goto CLEARRETURN;}
|
||||||
|
|
||||||
|
|
||||||
|
static void printusage(struct extparam *cconf, int argc, char * argv[]){
|
||||||
|
|
||||||
|
fprintf(stderr, "Usage: %s [conffile]\n", argv[0]);
|
||||||
|
#ifdef _WIN32
|
||||||
|
fprintf(stderr, "\n\t%s --install [conffile]\n\tto install as service\n"
|
||||||
|
"\n\t%s --remove\n\tto remove service\n", argv[0], argv[0]);
|
||||||
|
#else
|
||||||
|
fprintf(stderr, "\n if conffile is missing, configuration is expected from stdin\n");
|
||||||
|
#endif
|
||||||
|
fprintf(stderr, "\n\t%s --help\n\tthis message\n", argv[0]);
|
||||||
|
fprintf(stderr, "available socket options:\n\t%s\n", printopts("\n\t"));
|
||||||
|
fprintf(stderr, "built with:\n\t%s\n", printfeatures("\n\t"));
|
||||||
|
fprintf(stderr, "\n%s %s\n%s\n", cconf->stringtable[2], cconf->stringtable[3], copyright);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
#ifndef _WINCE
|
#ifndef _WINCE
|
||||||
int main(int argc, char * argv[]) {
|
int main(int argc, char * argv[]) {
|
||||||
@@ -391,6 +439,10 @@ int WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int
|
|||||||
#endif
|
#endif
|
||||||
|
|
||||||
conf.stringtable = strings;
|
conf.stringtable = strings;
|
||||||
|
if(argc == 2 && (!strcmp((char *)argv[1], "--help") || !strcmp((char *)argv[1], "-h"))) {
|
||||||
|
printusage(&conf, argc, argv);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
#ifdef _WIN32
|
#ifdef _WIN32
|
||||||
#ifndef _WINCE
|
#ifndef _WINCE
|
||||||
if((argc == 2 || argc == 3)&& !strcmp((char *)argv[1], "--install")) {
|
if((argc == 2 || argc == 3)&& !strcmp((char *)argv[1], "--install")) {
|
||||||
@@ -503,20 +555,17 @@ int WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int
|
|||||||
}
|
}
|
||||||
if(argc > 2 || !(fp)) {
|
if(argc > 2 || !(fp)) {
|
||||||
|
|
||||||
fprintf(stderr, "Usage: %s [conffile]\n", argv[0]);
|
printusage(&conf, argc, argv);
|
||||||
#ifdef _WIN32
|
|
||||||
fprintf(stderr, "\n\t%s --install [conffile]\n\tto install as service\n"
|
|
||||||
"\n\t%s --remove\n\tto remove service\n", argv[0], argv[0]);
|
|
||||||
#else
|
|
||||||
fprintf(stderr, "\n if conffile is missing, configuration is expected from stdin\n");
|
|
||||||
#endif
|
|
||||||
fprintf(stderr, "available socket options:\n\t%s\n", printopts("\n\t"));
|
|
||||||
fprintf(stderr, "\n%s %s\n%s\n", conf.stringtable[2], conf.stringtable[3], copyright);
|
|
||||||
|
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#ifndef _WIN32
|
||||||
|
/* before readconfig() starts the services: a client gone while it is
|
||||||
|
written to is an error, not the end */
|
||||||
|
signal(SIGPIPE, SIG_IGN);
|
||||||
|
#endif
|
||||||
_3proxy_mutex_init(&config_mutex);
|
_3proxy_mutex_init(&config_mutex);
|
||||||
|
_3proxy_mutex_init(&runningservices_mutex);
|
||||||
_3proxy_mutex_init(&bandlim_mutex);
|
_3proxy_mutex_init(&bandlim_mutex);
|
||||||
_3proxy_mutex_init(&connlim_mutex);
|
_3proxy_mutex_init(&connlim_mutex);
|
||||||
_3proxy_mutex_init(&tc_mutex);
|
_3proxy_mutex_init(&tc_mutex);
|
||||||
@@ -524,7 +573,7 @@ int WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int
|
|||||||
#ifndef NORADIUS
|
#ifndef NORADIUS
|
||||||
_3proxy_mutex_init(&rad_mutex);
|
_3proxy_mutex_init(&rad_mutex);
|
||||||
#endif
|
#endif
|
||||||
if(_3proxy_sem_init(conf.threadinit, 1, 1)){
|
if(_3proxy_sem_init_timed(serviceexited, 0, 0x7fffffff)){
|
||||||
fprintf(stderr, "semaphore init failed\n");
|
fprintf(stderr, "semaphore init failed\n");
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
@@ -547,7 +596,9 @@ int WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int
|
|||||||
res = readconfig(fp);
|
res = readconfig(fp);
|
||||||
conf.version++;
|
conf.version++;
|
||||||
|
|
||||||
if(res) RETURN(res);
|
/* readconfig() names the failing line, which an exit status would cut
|
||||||
|
to 8 bits: a failed configuration exits with 1 */
|
||||||
|
if(res) RETURN(1);
|
||||||
fclose(fp); fp = NULL;
|
fclose(fp); fp = NULL;
|
||||||
|
|
||||||
#ifdef _WIN32
|
#ifdef _WIN32
|
||||||
@@ -572,7 +623,6 @@ int WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int
|
|||||||
signal(SIGCONT, mysigpause);
|
signal(SIGCONT, mysigpause);
|
||||||
signal(SIGTERM, mysigterm);
|
signal(SIGTERM, mysigterm);
|
||||||
signal(SIGUSR1, mysigusr1);
|
signal(SIGUSR1, mysigusr1);
|
||||||
signal(SIGPIPE, SIG_IGN);
|
|
||||||
cyclestep();
|
cyclestep();
|
||||||
|
|
||||||
#endif
|
#endif
|
||||||
@@ -580,6 +630,6 @@ int WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int
|
|||||||
CLEARRETURN:
|
CLEARRETURN:
|
||||||
|
|
||||||
if(fp && fp != stdin) {fclose(fp); fp = NULL;}
|
if(fp && fp != stdin) {fclose(fp); fp = NULL;}
|
||||||
return 0;
|
return res;
|
||||||
|
|
||||||
}
|
}
|
||||||
+24
-21
@@ -13,6 +13,9 @@ udpsockmap$(OBJSUFFICS): udpsockmap.c proxy.h structures.h
|
|||||||
common$(OBJSUFFICS): common.c proxy.h structures.h
|
common$(OBJSUFFICS): common.c proxy.h structures.h
|
||||||
$(CC) $(CFLAGS) common.c
|
$(CC) $(CFLAGS) common.c
|
||||||
|
|
||||||
|
sem$(OBJSUFFICS): sem.c proxy.h structures.h
|
||||||
|
$(CC) $(CFLAGS) sem.c
|
||||||
|
|
||||||
plugins$(OBJSUFFICS): plugins.c proxy.h structures.h
|
plugins$(OBJSUFFICS): plugins.c proxy.h structures.h
|
||||||
$(CC) $(CFLAGS) plugins.c
|
$(CC) $(CFLAGS) plugins.c
|
||||||
|
|
||||||
@@ -44,7 +47,7 @@ tcppm$(OBJSUFFICS): tcppm.c proxy.h structures.h proxymain.c
|
|||||||
$(CC) $(CFLAGS) $(DEFINEOPTION)WITHMAIN $(DEFINEOPTION)PORTMAP $(DEFINEOPTION)NOUDPMAIN tcppm.c
|
$(CC) $(CFLAGS) $(DEFINEOPTION)WITHMAIN $(DEFINEOPTION)PORTMAP $(DEFINEOPTION)NOUDPMAIN tcppm.c
|
||||||
|
|
||||||
udppm$(OBJSUFFICS): udppm.c proxy.h structures.h proxymain.c
|
udppm$(OBJSUFFICS): udppm.c proxy.h structures.h proxymain.c
|
||||||
$(CC) $(CFLAGS) $(DEFINEOPTION)WITHMAIN $(DEFINEOPTION)PORTMAP udppm.c
|
$(CC) $(CFLAGS) $(DEFINEOPTION)WITHMAIN $(DEFINEOPTION)PORTMAP $(DEFINEOPTION)NOTCPMAIN udppm.c
|
||||||
|
|
||||||
tlspr$(OBJSUFFICS): tlspr.c proxy.h structures.h proxymain.c
|
tlspr$(OBJSUFFICS): tlspr.c proxy.h structures.h proxymain.c
|
||||||
$(CC) $(CFLAGS) $(DEFINEOPTION)WITHMAIN $(DEFINEOPTION)PORTMAP $(DEFINEOPTION)NOUDPMAIN tlspr.c
|
$(CC) $(CFLAGS) $(DEFINEOPTION)WITHMAIN $(DEFINEOPTION)PORTMAP $(DEFINEOPTION)NOUDPMAIN tlspr.c
|
||||||
@@ -56,32 +59,32 @@ socks$(OBJSUFFICS): socks.c proxy.h structures.h proxymain.c
|
|||||||
3proxy$(OBJSUFFICS): 3proxy.c proxy.h structures.h
|
3proxy$(OBJSUFFICS): 3proxy.c proxy.h structures.h
|
||||||
$(CC) $(CFLAGS) 3proxy.c
|
$(CC) $(CFLAGS) 3proxy.c
|
||||||
|
|
||||||
$(BUILDDIR)$(PREFIX)proxy$(EXESUFFICS): sockmap$(OBJSUFFICS) proxy$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) common$(OBJSUFFICS) log$(OBJSUFFICS) base64$(OBJSUFFICS) ftp$(OBJSUFFICS) $(COMPATLIBS)
|
$(BUILDDIR)$(PREFIX)proxy$(EXESUFFICS): sockmap$(OBJSUFFICS) proxy$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) common$(OBJSUFFICS) sem$(OBJSUFFICS) log$(OBJSUFFICS) base64$(OBJSUFFICS) ftp$(OBJSUFFICS) $(COMPATLIBS)
|
||||||
$(LN) $(LNOUT)$(BUILDDIR)$(PREFIX)proxy$(EXESUFFICS) $(LDFLAGS) sockmap$(OBJSUFFICS) proxy$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) log$(OBJSUFFICS) common$(OBJSUFFICS) base64$(OBJSUFFICS) ftp$(OBJSUFFICS) $(COMPATLIBS) $(LIBS)
|
$(LN) $(LNOUT)$(BUILDDIR)$(PREFIX)proxy$(EXESUFFICS) $(LDFLAGS) sockmap$(OBJSUFFICS) proxy$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) log$(OBJSUFFICS) common$(OBJSUFFICS) sem$(OBJSUFFICS) base64$(OBJSUFFICS) ftp$(OBJSUFFICS) $(COMPATLIBS) $(LIBS)
|
||||||
|
|
||||||
$(BUILDDIR)$(PREFIX)pop3p$(EXESUFFICS): sockmap$(OBJSUFFICS) pop3p$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) common$(OBJSUFFICS) log$(OBJSUFFICS) $(COMPATLIBS)
|
$(BUILDDIR)$(PREFIX)pop3p$(EXESUFFICS): sockmap$(OBJSUFFICS) pop3p$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) common$(OBJSUFFICS) sem$(OBJSUFFICS) log$(OBJSUFFICS) $(COMPATLIBS)
|
||||||
$(LN) $(LNOUT)$(BUILDDIR)$(PREFIX)pop3p$(EXESUFFICS) $(LDFLAGS) sockmap$(OBJSUFFICS) pop3p$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) log$(OBJSUFFICS) common$(OBJSUFFICS) $(COMPATLIBS) $(LIBS)
|
$(LN) $(LNOUT)$(BUILDDIR)$(PREFIX)pop3p$(EXESUFFICS) $(LDFLAGS) sockmap$(OBJSUFFICS) pop3p$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) log$(OBJSUFFICS) common$(OBJSUFFICS) sem$(OBJSUFFICS) $(COMPATLIBS) $(LIBS)
|
||||||
|
|
||||||
$(BUILDDIR)$(PREFIX)imapp$(EXESUFFICS): sockmap$(OBJSUFFICS) imapp$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) common$(OBJSUFFICS) log$(OBJSUFFICS) base64$(OBJSUFFICS) $(COMPATLIBS)
|
$(BUILDDIR)$(PREFIX)imapp$(EXESUFFICS): sockmap$(OBJSUFFICS) imapp$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) common$(OBJSUFFICS) sem$(OBJSUFFICS) log$(OBJSUFFICS) base64$(OBJSUFFICS) $(COMPATLIBS)
|
||||||
$(LN) $(LNOUT)$(BUILDDIR)$(PREFIX)imapp$(EXESUFFICS) $(LDFLAGS) sockmap$(OBJSUFFICS) imapp$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) log$(OBJSUFFICS) common$(OBJSUFFICS) base64$(OBJSUFFICS) $(COMPATLIBS) $(LIBS)
|
$(LN) $(LNOUT)$(BUILDDIR)$(PREFIX)imapp$(EXESUFFICS) $(LDFLAGS) sockmap$(OBJSUFFICS) imapp$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) log$(OBJSUFFICS) common$(OBJSUFFICS) sem$(OBJSUFFICS) base64$(OBJSUFFICS) $(COMPATLIBS) $(LIBS)
|
||||||
|
|
||||||
$(BUILDDIR)$(PREFIX)smtpp$(EXESUFFICS): sockmap$(OBJSUFFICS) smtpp$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) common$(OBJSUFFICS) log$(OBJSUFFICS) base64$(OBJSUFFICS) $(COMPATLIBS)
|
$(BUILDDIR)$(PREFIX)smtpp$(EXESUFFICS): sockmap$(OBJSUFFICS) smtpp$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) common$(OBJSUFFICS) sem$(OBJSUFFICS) log$(OBJSUFFICS) base64$(OBJSUFFICS) $(COMPATLIBS)
|
||||||
$(LN) $(LNOUT)$(BUILDDIR)$(PREFIX)smtpp$(EXESUFFICS) $(LDFLAGS) sockmap$(OBJSUFFICS) smtpp$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) base64$(OBJSUFFICS) log$(OBJSUFFICS) common$(OBJSUFFICS) $(COMPATLIBS) $(LIBS)
|
$(LN) $(LNOUT)$(BUILDDIR)$(PREFIX)smtpp$(EXESUFFICS) $(LDFLAGS) sockmap$(OBJSUFFICS) smtpp$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) base64$(OBJSUFFICS) log$(OBJSUFFICS) common$(OBJSUFFICS) sem$(OBJSUFFICS) $(COMPATLIBS) $(LIBS)
|
||||||
|
|
||||||
$(BUILDDIR)$(PREFIX)ftppr$(EXESUFFICS): sockmap$(OBJSUFFICS) ftppr$(OBJSUFFICS) ftp$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) common$(OBJSUFFICS) log$(OBJSUFFICS) $(COMPATLIBS)
|
$(BUILDDIR)$(PREFIX)ftppr$(EXESUFFICS): sockmap$(OBJSUFFICS) ftppr$(OBJSUFFICS) ftp$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) common$(OBJSUFFICS) sem$(OBJSUFFICS) log$(OBJSUFFICS) $(COMPATLIBS)
|
||||||
$(LN) $(LNOUT)$(BUILDDIR)$(PREFIX)ftppr$(EXESUFFICS) $(LDFLAGS) sockmap$(OBJSUFFICS) ftppr$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) common$(OBJSUFFICS) log$(OBJSUFFICS) ftp$(OBJSUFFICS) $(COMPATLIBS) $(LIBS)
|
$(LN) $(LNOUT)$(BUILDDIR)$(PREFIX)ftppr$(EXESUFFICS) $(LDFLAGS) sockmap$(OBJSUFFICS) ftppr$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) common$(OBJSUFFICS) sem$(OBJSUFFICS) log$(OBJSUFFICS) ftp$(OBJSUFFICS) $(COMPATLIBS) $(LIBS)
|
||||||
|
|
||||||
$(BUILDDIR)$(PREFIX)socks$(EXESUFFICS): sockmap$(OBJSUFFICS) udpsockmap$(OBJSUFFICS) socks$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) common$(OBJSUFFICS) log$(OBJSUFFICS)
|
$(BUILDDIR)$(PREFIX)socks$(EXESUFFICS): sockmap$(OBJSUFFICS) udpsockmap$(OBJSUFFICS) socks$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) common$(OBJSUFFICS) sem$(OBJSUFFICS) log$(OBJSUFFICS)
|
||||||
$(LN) $(LNOUT)$(BUILDDIR)$(PREFIX)socks$(EXESUFFICS) $(LDFLAGS) sockmap$(OBJSUFFICS) udpsockmap$(OBJSUFFICS) socks$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) log$(OBJSUFFICS) common$(OBJSUFFICS) $(LIBS)
|
$(LN) $(LNOUT)$(BUILDDIR)$(PREFIX)socks$(EXESUFFICS) $(LDFLAGS) sockmap$(OBJSUFFICS) udpsockmap$(OBJSUFFICS) socks$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) log$(OBJSUFFICS) common$(OBJSUFFICS) sem$(OBJSUFFICS) $(LIBS)
|
||||||
|
|
||||||
$(BUILDDIR)$(PREFIX)tcppm$(EXESUFFICS): sockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) tcppm$(OBJSUFFICS) common$(OBJSUFFICS) log$(OBJSUFFICS)
|
$(BUILDDIR)$(PREFIX)tcppm$(EXESUFFICS): sockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) tcppm$(OBJSUFFICS) common$(OBJSUFFICS) sem$(OBJSUFFICS) log$(OBJSUFFICS)
|
||||||
$(LN) $(LNOUT)$(BUILDDIR)$(PREFIX)tcppm$(EXESUFFICS) $(LDFLAGS) sockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) tcppm$(OBJSUFFICS) log$(OBJSUFFICS) common$(OBJSUFFICS) $(LIBS)
|
$(LN) $(LNOUT)$(BUILDDIR)$(PREFIX)tcppm$(EXESUFFICS) $(LDFLAGS) sockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) tcppm$(OBJSUFFICS) log$(OBJSUFFICS) common$(OBJSUFFICS) sem$(OBJSUFFICS) $(LIBS)
|
||||||
|
|
||||||
$(BUILDDIR)$(PREFIX)udppm$(EXESUFFICS): sockmap$(OBJSUFFICS) udpsockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) udppm$(OBJSUFFICS) common$(OBJSUFFICS) log$(OBJSUFFICS) hash$(OBJSUFFICS)
|
$(BUILDDIR)$(PREFIX)udppm$(EXESUFFICS): sockmap$(OBJSUFFICS) udpsockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) udppm$(OBJSUFFICS) common$(OBJSUFFICS) sem$(OBJSUFFICS) log$(OBJSUFFICS) hash$(OBJSUFFICS)
|
||||||
$(LN) $(LNOUT)$(BUILDDIR)$(PREFIX)udppm$(EXESUFFICS) $(LDFLAGS) sockmap$(OBJSUFFICS) udpsockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) udppm$(OBJSUFFICS) log$(OBJSUFFICS) common$(OBJSUFFICS) hash$(OBJSUFFICS) $(LIBS)
|
$(LN) $(LNOUT)$(BUILDDIR)$(PREFIX)udppm$(EXESUFFICS) $(LDFLAGS) sockmap$(OBJSUFFICS) udpsockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) udppm$(OBJSUFFICS) log$(OBJSUFFICS) common$(OBJSUFFICS) sem$(OBJSUFFICS) hash$(OBJSUFFICS) $(LIBS)
|
||||||
|
|
||||||
$(BUILDDIR)$(PREFIX)tlspr$(EXESUFFICS): sockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) tlspr$(OBJSUFFICS) common$(OBJSUFFICS) log$(OBJSUFFICS)
|
$(BUILDDIR)$(PREFIX)tlspr$(EXESUFFICS): sockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) tlspr$(OBJSUFFICS) common$(OBJSUFFICS) sem$(OBJSUFFICS) log$(OBJSUFFICS)
|
||||||
$(LN) $(LNOUT)$(BUILDDIR)$(PREFIX)tlspr$(EXESUFFICS) $(LDFLAGS) sockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) tlspr$(OBJSUFFICS) log$(OBJSUFFICS) common$(OBJSUFFICS) $(LIBS)
|
$(LN) $(LNOUT)$(BUILDDIR)$(PREFIX)tlspr$(EXESUFFICS) $(LDFLAGS) sockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) tlspr$(OBJSUFFICS) log$(OBJSUFFICS) common$(OBJSUFFICS) sem$(OBJSUFFICS) $(LIBS)
|
||||||
|
|
||||||
mainfunc$(OBJSUFFICS): proxy.h structures.h proxymain.c
|
mainfunc$(OBJSUFFICS): proxy.h structures.h proxymain.c
|
||||||
$(CC) $(COUT)mainfunc$(OBJSUFFICS) $(CFLAGS) $(DEFINEOPTION)MODULEMAINFUNC=mainfunc proxymain.c
|
$(CC) $(COUT)mainfunc$(OBJSUFFICS) $(CFLAGS) $(DEFINEOPTION)MODULEMAINFUNC=mainfunc proxymain.c
|
||||||
@@ -194,6 +197,6 @@ ssl$(OBJSUFFICS): ssl.c structures.h proxy.h ssl.h
|
|||||||
pcre$(OBJSUFFICS): pcre.c structures.h
|
pcre$(OBJSUFFICS): pcre.c structures.h
|
||||||
$(CC) $(COUT)pcre$(OBJSUFFICS) $(CFLAGS) $(DEFINEOPTION)WITH_PCRE pcre.c
|
$(CC) $(COUT)pcre$(OBJSUFFICS) $(CFLAGS) $(DEFINEOPTION)WITH_PCRE pcre.c
|
||||||
|
|
||||||
$(BUILDDIR)3proxy$(EXESUFFICS): 3proxy$(OBJSUFFICS) mainfunc$(OBJSUFFICS) srvproxy$(OBJSUFFICS) srvpop3p$(OBJSUFFICS) srvimapp$(OBJSUFFICS) srvsmtpp$(OBJSUFFICS) srvftppr$(OBJSUFFICS) srvsocks$(OBJSUFFICS) srvtcppm$(OBJSUFFICS) srvtlspr$(OBJSUFFICS) srvauto$(OBJSUFFICS) srvudppm$(OBJSUFFICS) sockmap$(OBJSUFFICS) udpsockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) common$(OBJSUFFICS) auth$(OBJSUFFICS) acl$(OBJSUFFICS) limiter$(OBJSUFFICS) redirect$(OBJSUFFICS) authradius$(OBJSUFFICS) hash$(OBJSUFFICS) hashtables$(OBJSUFFICS) resolve$(OBJSUFFICS) sql$(OBJSUFFICS) conf$(OBJSUFFICS) log$(OBJSUFFICS) datatypes$(OBJSUFFICS) md4$(OBJSUFFICS) md5$(OBJSUFFICS) blake2$(OBJSUFFICS) 3proxy_crypt$(OBJSUFFICS) base64$(OBJSUFFICS) ftp$(OBJSUFFICS) stringtable$(OBJSUFFICS) $(HTTPSRV_OBJS) srvdnspr$(OBJSUFFICS) plugins$(OBJSUFFICS) mdhash$(OBJSUFFICS) $(SSL_OBJS) $(PCRE_OBJS) $(TRANSPARENT_OBJS) $(COMPATLIBS) $(VERSIONDEP)
|
$(BUILDDIR)3proxy$(EXESUFFICS): 3proxy$(OBJSUFFICS) mainfunc$(OBJSUFFICS) srvproxy$(OBJSUFFICS) srvpop3p$(OBJSUFFICS) srvimapp$(OBJSUFFICS) srvsmtpp$(OBJSUFFICS) srvftppr$(OBJSUFFICS) srvsocks$(OBJSUFFICS) srvtcppm$(OBJSUFFICS) srvtlspr$(OBJSUFFICS) srvauto$(OBJSUFFICS) srvudppm$(OBJSUFFICS) sockmap$(OBJSUFFICS) udpsockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) common$(OBJSUFFICS) sem$(OBJSUFFICS) auth$(OBJSUFFICS) acl$(OBJSUFFICS) limiter$(OBJSUFFICS) redirect$(OBJSUFFICS) authradius$(OBJSUFFICS) hash$(OBJSUFFICS) hashtables$(OBJSUFFICS) resolve$(OBJSUFFICS) sql$(OBJSUFFICS) conf$(OBJSUFFICS) log$(OBJSUFFICS) datatypes$(OBJSUFFICS) md4$(OBJSUFFICS) md5$(OBJSUFFICS) blake2$(OBJSUFFICS) 3proxy_crypt$(OBJSUFFICS) base64$(OBJSUFFICS) ftp$(OBJSUFFICS) stringtable$(OBJSUFFICS) $(HTTPSRV_OBJS) srvdnspr$(OBJSUFFICS) plugins$(OBJSUFFICS) mdhash$(OBJSUFFICS) $(SSL_OBJS) $(PCRE_OBJS) $(TRANSPARENT_OBJS) $(COMPATLIBS) $(VERSIONDEP)
|
||||||
$(LN) $(LNOUT)$(BUILDDIR)3proxy$(EXESUFFICS) $(LDFLAGS) $(VERFILE) 3proxy$(OBJSUFFICS) mainfunc$(OBJSUFFICS) auth$(OBJSUFFICS) acl$(OBJSUFFICS) limiter$(OBJSUFFICS) redirect$(OBJSUFFICS) authradius$(OBJSUFFICS) hash$(OBJSUFFICS) hashtables$(OBJSUFFICS) resolve$(OBJSUFFICS) sql$(OBJSUFFICS) conf$(OBJSUFFICS) datatypes$(OBJSUFFICS) srvauto$(OBJSUFFICS) srvproxy$(OBJSUFFICS) srvpop3p$(OBJSUFFICS) srvimapp$(OBJSUFFICS) srvsmtpp$(OBJSUFFICS) srvftppr$(OBJSUFFICS) srvsocks$(OBJSUFFICS) srvtcppm$(OBJSUFFICS) srvtlspr$(OBJSUFFICS) srvudppm$(OBJSUFFICS) sockmap$(OBJSUFFICS) udpsockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) common$(OBJSUFFICS) log$(OBJSUFFICS) 3proxy_crypt$(OBJSUFFICS) md4$(OBJSUFFICS) md5$(OBJSUFFICS) blake2$(OBJSUFFICS) base64$(OBJSUFFICS) ftp$(OBJSUFFICS) stringtable$(OBJSUFFICS) $(HTTPSRV_OBJS) srvdnspr$(OBJSUFFICS) plugins$(OBJSUFFICS) mdhash$(OBJSUFFICS) $(SSL_OBJS) $(PCRE_OBJS) $(TRANSPARENT_OBJS) $(COMPATLIBS) $(LIBS) $(PCRE_LIBS)
|
$(LN) $(LNOUT)$(BUILDDIR)3proxy$(EXESUFFICS) $(LDFLAGS) $(VERFILE) 3proxy$(OBJSUFFICS) mainfunc$(OBJSUFFICS) auth$(OBJSUFFICS) acl$(OBJSUFFICS) limiter$(OBJSUFFICS) redirect$(OBJSUFFICS) authradius$(OBJSUFFICS) hash$(OBJSUFFICS) hashtables$(OBJSUFFICS) resolve$(OBJSUFFICS) sql$(OBJSUFFICS) conf$(OBJSUFFICS) datatypes$(OBJSUFFICS) srvauto$(OBJSUFFICS) srvproxy$(OBJSUFFICS) srvpop3p$(OBJSUFFICS) srvimapp$(OBJSUFFICS) srvsmtpp$(OBJSUFFICS) srvftppr$(OBJSUFFICS) srvsocks$(OBJSUFFICS) srvtcppm$(OBJSUFFICS) srvtlspr$(OBJSUFFICS) srvudppm$(OBJSUFFICS) sockmap$(OBJSUFFICS) udpsockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) common$(OBJSUFFICS) sem$(OBJSUFFICS) log$(OBJSUFFICS) 3proxy_crypt$(OBJSUFFICS) md4$(OBJSUFFICS) md5$(OBJSUFFICS) blake2$(OBJSUFFICS) base64$(OBJSUFFICS) ftp$(OBJSUFFICS) stringtable$(OBJSUFFICS) $(HTTPSRV_OBJS) srvdnspr$(OBJSUFFICS) plugins$(OBJSUFFICS) mdhash$(OBJSUFFICS) $(SSL_OBJS) $(PCRE_OBJS) $(TRANSPARENT_OBJS) $(COMPATLIBS) $(LIBS) $(PCRE_LIBS)
|
||||||
|
|
||||||
+23
-4
@@ -198,12 +198,20 @@ static int calc_replydigest(char *packet, char *original, const char *secret, in
|
|||||||
int secretlen;
|
int secretlen;
|
||||||
uint8_t calc_digest[AUTH_VECTOR_LEN];
|
uint8_t calc_digest[AUTH_VECTOR_LEN];
|
||||||
uint8_t calc_vector[AUTH_VECTOR_LEN];
|
uint8_t calc_vector[AUTH_VECTOR_LEN];
|
||||||
|
unsigned int dlen = AUTH_VECTOR_LEN;
|
||||||
|
mdh_ctx *ctx;
|
||||||
|
|
||||||
memcpy(calc_vector, packet + 4, AUTH_VECTOR_LEN);
|
memcpy(calc_vector, packet + 4, AUTH_VECTOR_LEN);
|
||||||
memcpy(packet + 4, original, AUTH_VECTOR_LEN);
|
memcpy(packet + 4, original, AUTH_VECTOR_LEN);
|
||||||
secretlen = strlen(secret);
|
secretlen = strlen(secret);
|
||||||
memcpy(packet + len, secret, secretlen);
|
/* hash the reply, then the secret: nothing is written past the reply */
|
||||||
md5_calc(calc_digest, (u_char *)packet, len + secretlen);
|
if(!(ctx = mdh_init(MDH_MD5, 16))) return 2;
|
||||||
|
if(!mdh_update(ctx, packet, len) || !mdh_update(ctx, secret, secretlen) ||
|
||||||
|
!mdh_final(ctx, calc_digest, &dlen)) {
|
||||||
|
mdh_free(ctx);
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
mdh_free(ctx);
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Return 0 if OK, 2 if not OK.
|
* Return 0 if OK, 2 if not OK.
|
||||||
@@ -298,6 +306,7 @@ int radsend(struct clientparam * param, int auth, int stop){
|
|||||||
int total_length;
|
int total_length;
|
||||||
int len;
|
int len;
|
||||||
PROXYSOCKADDRTYPE saremote;
|
PROXYSOCKADDRTYPE saremote;
|
||||||
|
PROXYSOCKADDRTYPE safrom;
|
||||||
struct pollfd fds[1];
|
struct pollfd fds[1];
|
||||||
char vector[AUTH_VECTOR_LEN];
|
char vector[AUTH_VECTOR_LEN];
|
||||||
radius_packet_t packet, rpacket;
|
radius_packet_t packet, rpacket;
|
||||||
@@ -568,15 +577,25 @@ int radsend(struct clientparam * param, int auth, int stop){
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
salen = sizeof(saremote);
|
salen = sizeof(safrom);
|
||||||
|
|
||||||
data_len = so._recvfrom(so.state, remsock, (char *)&rpacket, sizeof(packet)-16,
|
data_len = so._recvfrom(so.state, remsock, (char *)&rpacket, sizeof(packet)-16,
|
||||||
0, (struct sockaddr *)&saremote, &salen);
|
0, (struct sockaddr *)&safrom, &salen);
|
||||||
|
|
||||||
|
|
||||||
if (data_len < 20) {
|
if (data_len < 20) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
/* the reply must come from the server we asked */
|
||||||
|
if(*SAFAMILY(&safrom) != *SAFAMILY(&saremote) ||
|
||||||
|
memcmp(SAADDR(&safrom), SAADDR(&saremote), SAADDRLEN(&saremote)) ||
|
||||||
|
*SAPORT(&safrom) != *SAPORT(&saremote)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
/* and answer this request, and be of its own length */
|
||||||
|
if(data_len != ntohs(rpacket.length) || rpacket.id != packet.id) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
if( auth && rpacket.code != PW_AUTHENTICATION_ACK &&
|
if( auth && rpacket.code != PW_AUTHENTICATION_ACK &&
|
||||||
rpacket.code != PW_AUTHENTICATION_REJECT ){
|
rpacket.code != PW_AUTHENTICATION_REJECT ){
|
||||||
|
|||||||
+51
-31
@@ -187,33 +187,6 @@ size_t threadstacksize(int extra){
|
|||||||
if(size < (long)PTHREAD_STACK_MIN) size = (long)PTHREAD_STACK_MIN;
|
if(size < (long)PTHREAD_STACK_MIN) size = (long)PTHREAD_STACK_MIN;
|
||||||
return (size_t)size;
|
return (size_t)size;
|
||||||
}
|
}
|
||||||
|
|
||||||
int _3proxy_sem_init_f(_3proxy_sem_t *sem, unsigned count, unsigned maxcount){
|
|
||||||
sem->count = count;
|
|
||||||
sem->maxcount = maxcount;
|
|
||||||
if(pthread_mutex_init(&sem->mutex, NULL)) return 1;
|
|
||||||
if(pthread_cond_init(&sem->cond, NULL)){
|
|
||||||
pthread_mutex_destroy(&sem->mutex);
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
void _3proxy_sem_lock_f(_3proxy_sem_t *sem){
|
|
||||||
pthread_mutex_lock(&sem->mutex);
|
|
||||||
while(!sem->count) pthread_cond_wait(&sem->cond, &sem->mutex);
|
|
||||||
sem->count--;
|
|
||||||
pthread_mutex_unlock(&sem->mutex);
|
|
||||||
}
|
|
||||||
|
|
||||||
void _3proxy_sem_unlock_f(_3proxy_sem_t *sem){
|
|
||||||
pthread_mutex_lock(&sem->mutex);
|
|
||||||
if(sem->count < sem->maxcount){
|
|
||||||
sem->count++;
|
|
||||||
pthread_cond_signal(&sem->cond);
|
|
||||||
}
|
|
||||||
pthread_mutex_unlock(&sem->mutex);
|
|
||||||
}
|
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
struct extparam conf = {
|
struct extparam conf = {
|
||||||
@@ -414,7 +387,6 @@ int
|
|||||||
return shutdown(s, how);
|
return shutdown(s, how);
|
||||||
}
|
}
|
||||||
int WINAPI def_closesocket(void* state, SOCKET s){
|
int WINAPI def_closesocket(void* state, SOCKET s){
|
||||||
usleep(SLEEPTIME);
|
|
||||||
return closesocket(s);
|
return closesocket(s);
|
||||||
}
|
}
|
||||||
#else
|
#else
|
||||||
@@ -454,11 +426,18 @@ int
|
|||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* a peer gone is an error of the send, not SIGPIPE, where the system can
|
||||||
|
say so for a call: SIGPIPE is ignored too, for TLS and splice() */
|
||||||
|
#ifdef MSG_NOSIGNAL
|
||||||
|
#define SENDFLAGS MSG_NOSIGNAL
|
||||||
|
#else
|
||||||
|
#define SENDFLAGS 0
|
||||||
|
#endif
|
||||||
ssize_t def_send(void* state, SOCKET s, const void *msg, size_t len, int flags){
|
ssize_t def_send(void* state, SOCKET s, const void *msg, size_t len, int flags){
|
||||||
return send(s, msg, len, flags);
|
return send(s, msg, len, flags | SENDFLAGS);
|
||||||
}
|
}
|
||||||
ssize_t def_sendto(void* state, SOCKET s, const void *msg, size_t len, int flags, const struct sockaddr *to, socklen_t tolen){
|
ssize_t def_sendto(void* state, SOCKET s, const void *msg, size_t len, int flags, const struct sockaddr *to, socklen_t tolen){
|
||||||
return sendto(s, msg, len, flags, to, tolen);
|
return sendto(s, msg, len, flags | SENDFLAGS, to, tolen);
|
||||||
}
|
}
|
||||||
ssize_t def_recv(void* state, SOCKET s, void *buf, size_t len, int flags){
|
ssize_t def_recv(void* state, SOCKET s, void *buf, size_t len, int flags){
|
||||||
return recv(s, buf, len, flags);
|
return recv(s, buf, len, flags);
|
||||||
@@ -655,6 +634,26 @@ int parseconnusername(char *username, struct clientparam *param, int extpasswd,
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/* What waits for a socket waits in poll(): a call on it never does. */
|
||||||
|
void nonblock(SOCKET sock){
|
||||||
|
#ifdef _WIN32
|
||||||
|
unsigned long ul = 1;
|
||||||
|
ioctlsocket(sock, FIONBIO, &ul);
|
||||||
|
#else
|
||||||
|
fcntl(sock, F_SETFL, O_NONBLOCK | fcntl(sock, F_GETFL));
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
/* accept() with nothing to accept: another took it, or it was gone */
|
||||||
|
int acceptagain(void){
|
||||||
|
#ifdef _WIN32
|
||||||
|
int err = WSAGetLastError();
|
||||||
|
return err == WSAEWOULDBLOCK || err == WSAECONNRESET || err == WSAEINTR;
|
||||||
|
#else
|
||||||
|
return errno == EAGAIN || errno == EWOULDBLOCK || errno == ECONNABORTED || errno == EINTR;
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
int connectwithpoll(struct clientparam *param, SOCKET sock, struct sockaddr *sa, SASIZETYPE size, int to){
|
int connectwithpoll(struct clientparam *param, SOCKET sock, struct sockaddr *sa, SASIZETYPE size, int to){
|
||||||
struct pollfd fds[1];
|
struct pollfd fds[1];
|
||||||
#ifdef _WIN32
|
#ifdef _WIN32
|
||||||
@@ -742,7 +741,9 @@ int doconnect(struct clientparam * param){
|
|||||||
if(param->srv->so._getpeername(param->sostate, param->remsock, (struct sockaddr *)¶m->sinsr, &size)==-1) {return (14);}
|
if(param->srv->so._getpeername(param->sostate, param->remsock, (struct sockaddr *)¶m->sinsr, &size)==-1) {return (14);}
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
|
#ifndef _WIN32
|
||||||
struct linger lg = {1,conf.timeouts[LINGER_TO]};
|
struct linger lg = {1,conf.timeouts[LINGER_TO]};
|
||||||
|
#endif
|
||||||
int tries = RANGETRIES;
|
int tries = RANGETRIES;
|
||||||
|
|
||||||
if(SAISNULL(¶m->sinsr)){
|
if(SAISNULL(¶m->sinsr)){
|
||||||
@@ -772,10 +773,29 @@ int doconnect(struct clientparam * param){
|
|||||||
param->sinsl = param->srv->extsa;
|
param->sinsl = param->srv->extsa;
|
||||||
}
|
}
|
||||||
*SAPORT(¶m->sinsl) = 0;
|
*SAPORT(¶m->sinsl) = 0;
|
||||||
setopts(param->remsock, param->srv->srvsockopts);
|
setopts(param->remsock, ¶m->srv->srvsockopts);
|
||||||
|
|
||||||
|
#ifndef _WIN32
|
||||||
|
/* not on Windows, see the accepting side in proxymain.c */
|
||||||
param->srv->so._setsockopt(param->sostate, param->remsock, SOL_SOCKET, SO_LINGER, (char *)&lg, sizeof(lg));
|
param->srv->so._setsockopt(param->sostate, param->remsock, SOL_SOCKET, SO_LINGER, (char *)&lg, sizeof(lg));
|
||||||
|
#endif
|
||||||
if(extbindtodevice(param, param->remsock)) return 12;
|
if(extbindtodevice(param, param->remsock)) return 12;
|
||||||
|
#ifdef IP_BIND_ADDRESS_NO_PORT
|
||||||
|
/* A port the kernel chooses is chosen by connect(), for the pair with
|
||||||
|
the destination: one in use towards another destination, or closing
|
||||||
|
from an earlier connection, does as well. bind() would take one of
|
||||||
|
its own, and with many connections find none left, or search long
|
||||||
|
for it. */
|
||||||
|
if((param->operation >= 256 || (param->operation & CONNECT) || param->redirected)
|
||||||
|
# ifdef WITH_UN
|
||||||
|
&& *SAFAMILY(¶m->sinsl) != AF_UNIX
|
||||||
|
# endif
|
||||||
|
){
|
||||||
|
int one = 1;
|
||||||
|
|
||||||
|
param->srv->so._setsockopt(param->sostate, param->remsock, IPPROTO_IP, IP_BIND_ADDRESS_NO_PORT, (char *)&one, sizeof(one));
|
||||||
|
}
|
||||||
|
#endif
|
||||||
#ifdef WITH_UN
|
#ifdef WITH_UN
|
||||||
if(*SAFAMILY(¶m->sinsl) != AF_UNIX)
|
if(*SAFAMILY(¶m->sinsl) != AF_UNIX)
|
||||||
#endif
|
#endif
|
||||||
|
|||||||
+61
-23
@@ -38,14 +38,18 @@ _3proxy_mutex_t bandlim_mutex;
|
|||||||
_3proxy_mutex_t connlim_mutex;
|
_3proxy_mutex_t connlim_mutex;
|
||||||
_3proxy_mutex_t tc_mutex;
|
_3proxy_mutex_t tc_mutex;
|
||||||
_3proxy_mutex_t config_mutex;
|
_3proxy_mutex_t config_mutex;
|
||||||
|
int runningservices = 0;
|
||||||
|
_3proxy_mutex_t runningservices_mutex;
|
||||||
|
_3proxy_sem_t serviceexited;
|
||||||
|
|
||||||
int haveerror = 0;
|
|
||||||
int linenum = 0;
|
int linenum = 0;
|
||||||
|
|
||||||
struct counter_header cheader = {"3CF", (time_t)0};
|
struct counter_header cheader = {"3CF", (time_t)0};
|
||||||
struct counter_record crecord;
|
struct counter_record crecord;
|
||||||
|
|
||||||
int mainfunc (int argc, char** argv);
|
int mainprepare(int argc, char** argv, void **service);
|
||||||
|
int mainrun(void *service);
|
||||||
|
void maindrop(void *service);
|
||||||
|
|
||||||
struct proxydef childdef = {NULL, 0, 0, S_NOSERVICE, ""};
|
struct proxydef childdef = {NULL, 0, 0, S_NOSERVICE, ""};
|
||||||
|
|
||||||
@@ -75,8 +79,12 @@ DWORD WINAPI startsrv(LPVOID data) {
|
|||||||
#else
|
#else
|
||||||
void * startsrv(void * data) {
|
void * startsrv(void * data) {
|
||||||
#endif
|
#endif
|
||||||
struct child *d = (struct child *)data;
|
/* counted by start_proxy_thread() before the thread is created */
|
||||||
mainfunc(d->argc, (char **)d->argv);
|
mainrun(data);
|
||||||
|
_3proxy_mutex_lock(&runningservices_mutex);
|
||||||
|
runningservices--;
|
||||||
|
_3proxy_mutex_unlock(&runningservices_mutex);
|
||||||
|
_3proxy_sem_unlock(serviceexited);
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -142,36 +150,45 @@ unsigned char * dologname (unsigned char *buf, unsigned char *name, const unsign
|
|||||||
return buf;
|
return buf;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* The service is set up here, in the thread reading the configuration, so
|
||||||
|
an error in its options stops the configuration; its own thread then
|
||||||
|
listens and serves. */
|
||||||
int start_proxy_thread(struct child * chp){
|
int start_proxy_thread(struct child * chp){
|
||||||
pthread_t thread;
|
pthread_t thread;
|
||||||
|
void *service;
|
||||||
|
int res;
|
||||||
#ifdef _WIN32
|
#ifdef _WIN32
|
||||||
HANDLE h;
|
HANDLE h;
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
_3proxy_sem_lock(conf.threadinit);
|
if((res = mainprepare(chp->argc, (char **)chp->argv, &service))) {
|
||||||
|
fprintf(stderr, "Service not started on line: %d%s\n", linenum, res == 2? ": insufficient memory":"");
|
||||||
|
return(40);
|
||||||
|
}
|
||||||
|
_3proxy_mutex_lock(&runningservices_mutex);
|
||||||
|
runningservices++;
|
||||||
|
_3proxy_mutex_unlock(&runningservices_mutex);
|
||||||
#ifdef _WIN32
|
#ifdef _WIN32
|
||||||
#ifndef _WINCE
|
#ifndef _WINCE
|
||||||
h = (HANDLE)_beginthreadex((LPSECURITY_ATTRIBUTES )NULL, 16384+conf.stacksize, (void *)startsrv, (void *) chp, (DWORD)0, &thread);
|
h = (HANDLE)_beginthreadex((LPSECURITY_ATTRIBUTES )NULL, 16384+conf.stacksize, (void *)startsrv, service, (DWORD)0, &thread);
|
||||||
#else
|
#else
|
||||||
h = (HANDLE)CreateThread((LPSECURITY_ATTRIBUTES )NULL, 16384+conf.stacksize, (void *)startsrv, (void *) chp, (DWORD)0, &thread);
|
h = (HANDLE)CreateThread((LPSECURITY_ATTRIBUTES )NULL, 16384+conf.stacksize, (void *)startsrv, service, (DWORD)0, &thread);
|
||||||
#endif
|
#endif
|
||||||
if(h)CloseHandle(h);
|
if(h)CloseHandle(h);
|
||||||
|
else {
|
||||||
#else
|
#else
|
||||||
pthread_attr_init(&pa);
|
pthread_attr_init(&pa);
|
||||||
pthread_attr_setstacksize(&pa,threadstacksize(conf.stacksize));
|
pthread_attr_setstacksize(&pa,threadstacksize(conf.stacksize));
|
||||||
pthread_attr_setdetachstate(&pa,PTHREAD_CREATE_DETACHED);
|
pthread_attr_setdetachstate(&pa,PTHREAD_CREATE_DETACHED);
|
||||||
if(pthread_create(&thread, &pa, startsrv, (void *)chp)){
|
res = pthread_create(&thread, &pa, startsrv, service);
|
||||||
pthread_attr_destroy(&pa);
|
|
||||||
fprintf(stderr, "Failed to create service thread on line %d, try to set larger stacksize\n", linenum);
|
|
||||||
_3proxy_sem_unlock(conf.threadinit);
|
|
||||||
return(40);
|
|
||||||
}
|
|
||||||
pthread_attr_destroy(&pa);
|
pthread_attr_destroy(&pa);
|
||||||
|
if(res){
|
||||||
#endif
|
#endif
|
||||||
_3proxy_sem_lock(conf.threadinit);
|
_3proxy_mutex_lock(&runningservices_mutex);
|
||||||
_3proxy_sem_unlock(conf.threadinit);
|
runningservices--;
|
||||||
if(haveerror) {
|
_3proxy_mutex_unlock(&runningservices_mutex);
|
||||||
fprintf(stderr, "Service not started on line: %d%s\n", linenum, haveerror == 2? ": insufficient memory":"");
|
maindrop(service);
|
||||||
|
fprintf(stderr, "Failed to create service thread on line %d, try to set larger stacksize\n", linenum);
|
||||||
return(40);
|
return(40);
|
||||||
}
|
}
|
||||||
return 0;
|
return 0;
|
||||||
@@ -187,6 +204,9 @@ static int h_proxy(int argc, unsigned char ** argv){
|
|||||||
childdef.port = 3128;
|
childdef.port = 3128;
|
||||||
childdef.isudp = 0;
|
childdef.isudp = 0;
|
||||||
childdef.service = S_PROXY;
|
childdef.service = S_PROXY;
|
||||||
|
#ifdef WITH_FTP
|
||||||
|
childdef.helpmessage = " -Xftp - fetch ftp:// URLs\n";
|
||||||
|
#endif
|
||||||
#ifdef NOIPV6
|
#ifdef NOIPV6
|
||||||
if(!resolvfunc || (resolvfunc == myresolver && !dns_table.poolsize)){
|
if(!resolvfunc || (resolvfunc == myresolver && !dns_table.poolsize)){
|
||||||
fprintf(stderr, "[line %d] Warning: no nserver/nscache configured, proxy may run very slow\n", linenum);
|
fprintf(stderr, "[line %d] Warning: no nserver/nscache configured, proxy may run very slow\n", linenum);
|
||||||
@@ -358,7 +378,8 @@ static int h_log(int argc, unsigned char ** argv){
|
|||||||
#ifndef _WIN32
|
#ifndef _WIN32
|
||||||
conf.logfunc = logsyslog;
|
conf.logfunc = logsyslog;
|
||||||
if(notchanged) return 0;
|
if(notchanged) return 0;
|
||||||
openlog((char *)conf.logtarget+1, LOG_PID, LOG_DAEMON);
|
/* connected now: after a chroot there is no /dev/log to find */
|
||||||
|
openlog((char *)conf.logtarget+1, LOG_PID | LOG_NDELAY, LOG_DAEMON);
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
#ifdef WITH_ODBC
|
#ifdef WITH_ODBC
|
||||||
@@ -1901,6 +1922,14 @@ static int h_setgid(int argc, unsigned char **argv){
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/* What the C library reads on first use from files a chroot hides, read
|
||||||
|
while they can still be found: the time zone, without which every time
|
||||||
|
is UTC. Names looked up through the system cannot be helped this way, the
|
||||||
|
hosts file and resolv.conf are read again for lookups to come. */
|
||||||
|
static void prechroot(void){
|
||||||
|
tzset();
|
||||||
|
}
|
||||||
|
|
||||||
static int h_chroot(int argc, unsigned char **argv){
|
static int h_chroot(int argc, unsigned char **argv){
|
||||||
uid_t uid = 0;
|
uid_t uid = 0;
|
||||||
gid_t gid = 0;
|
gid_t gid = 0;
|
||||||
@@ -1920,6 +1949,8 @@ static int h_chroot(int argc, unsigned char **argv){
|
|||||||
}
|
}
|
||||||
if(!chrootp){
|
if(!chrootp){
|
||||||
char *p;
|
char *p;
|
||||||
|
|
||||||
|
prechroot();
|
||||||
if(chroot((char *)argv[1])) {
|
if(chroot((char *)argv[1])) {
|
||||||
fprintf(stderr, "Unable to chroot %s", argv[1]);
|
fprintf(stderr, "Unable to chroot %s", argv[1]);
|
||||||
return(1);
|
return(1);
|
||||||
@@ -2263,6 +2294,7 @@ int readconfig(FILE * fp){
|
|||||||
|
|
||||||
if( !(buf = malloc(bufsize)) || ! (argv = malloc((NPARAMS + 1) * sizeof(unsigned char *))) ) {
|
if( !(buf = malloc(bufsize)) || ! (argv = malloc((NPARAMS + 1) * sizeof(unsigned char *))) ) {
|
||||||
fprintf(stderr, "No memory for configuration");
|
fprintf(stderr, "No memory for configuration");
|
||||||
|
if(buf) free(buf);
|
||||||
return(10);
|
return(10);
|
||||||
}
|
}
|
||||||
for (linenum = 1; fgets((char *)buf, STRINGBUF, fp); linenum++){
|
for (linenum = 1; fgets((char *)buf, STRINGBUF, fp); linenum++){
|
||||||
@@ -2272,7 +2304,8 @@ int readconfig(FILE * fp){
|
|||||||
argc = parsestr (buf, argv, NPARAMS-1, &buf, &inbuf, &bufsize);
|
argc = parsestr (buf, argv, NPARAMS-1, &buf, &inbuf, &bufsize);
|
||||||
if(argc < 1) {
|
if(argc < 1) {
|
||||||
fprintf(stderr, "Parse error line %d\n", linenum);
|
fprintf(stderr, "Parse error line %d\n", linenum);
|
||||||
return(11);
|
res = 11;
|
||||||
|
goto DONE;
|
||||||
}
|
}
|
||||||
argv[argc] = NULL;
|
argv[argc] = NULL;
|
||||||
if(!strcmp((char *)argv[0], "end") && argc == 1) {
|
if(!strcmp((char *)argv[0], "end") && argc == 1) {
|
||||||
@@ -2284,23 +2317,28 @@ int readconfig(FILE * fp){
|
|||||||
if(!strcmp((char *)argv[0], (char *)cm->command)){
|
if(!strcmp((char *)argv[0], (char *)cm->command)){
|
||||||
if(argc < cm->minargs || (cm->maxargs && argc > cm->maxargs)){
|
if(argc < cm->minargs || (cm->maxargs && argc > cm->maxargs)){
|
||||||
fprintf(stderr, "Command: '%s' wrong number of arguments , line %d\n", argv[0], linenum);
|
fprintf(stderr, "Command: '%s' wrong number of arguments , line %d\n", argv[0], linenum);
|
||||||
return(linenum);
|
res = linenum;
|
||||||
|
goto DONE;
|
||||||
}
|
}
|
||||||
res = (*cm->handler)(argc, argv);
|
res = (*cm->handler)(argc, argv);
|
||||||
if(res > 0){
|
if(res > 0){
|
||||||
fprintf(stderr, "Command: '%s' failed with code %d, line %d\n", argv[0], res, linenum);
|
fprintf(stderr, "Command: '%s' failed with code %d, line %d\n", argv[0], res, linenum);
|
||||||
return(linenum);
|
res = linenum;
|
||||||
|
goto DONE;
|
||||||
}
|
}
|
||||||
if(!res) break;
|
if(!res) break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if(res != 1)continue;
|
if(res != 1)continue;
|
||||||
fprintf(stderr, "Unknown command: '%s' line %d\n", argv[0], linenum);
|
fprintf(stderr, "Unknown command: '%s' line %d\n", argv[0], linenum);
|
||||||
return(linenum);
|
res = linenum;
|
||||||
|
goto DONE;
|
||||||
}
|
}
|
||||||
|
res = 0;
|
||||||
|
DONE:
|
||||||
free(buf);
|
free(buf);
|
||||||
free(argv);
|
free(argv);
|
||||||
return 0;
|
return res;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+38
-3
@@ -15,6 +15,12 @@
|
|||||||
|
|
||||||
#define BUFSIZE 16384
|
#define BUFSIZE 16384
|
||||||
|
|
||||||
|
/* An answer to the query asked: our id, a response, and the question
|
||||||
|
byte for byte. */
|
||||||
|
static int dnsanswer(const unsigned char *buf, int len, const unsigned char *q, int qend){
|
||||||
|
return len >= qend && buf[0] == q[0] && buf[1] == q[1] && (buf[2] & 0x80) &&
|
||||||
|
buf[4] == q[4] && buf[5] == q[5] && !memcmp(buf + 12, q + 12, qend - 12);
|
||||||
|
}
|
||||||
|
|
||||||
void * dnsprchild(struct clientparam* param) {
|
void * dnsprchild(struct clientparam* param) {
|
||||||
uint32_t ip = 0;
|
uint32_t ip = 0;
|
||||||
@@ -146,6 +152,20 @@ void * dnsprchild(struct clientparam* param) {
|
|||||||
else ip = 0;
|
else ip = 0;
|
||||||
}
|
}
|
||||||
if(!ip && numservers){
|
if(!ip && numservers){
|
||||||
|
/* the question, to check the answer against; the name server is
|
||||||
|
asked under an id of our own, the client's put back in its answer */
|
||||||
|
unsigned char question[1024], cid[2];
|
||||||
|
int qend = (len < i)? len : i;
|
||||||
|
unsigned short id = (unsigned short)myrand();
|
||||||
|
PROXYSOCKADDRTYPE from;
|
||||||
|
time_t deadline;
|
||||||
|
int to;
|
||||||
|
|
||||||
|
cid[0] = buf[0];
|
||||||
|
cid[1] = buf[1];
|
||||||
|
buf[0] = (unsigned char)(id >> 8);
|
||||||
|
buf[1] = (unsigned char)(id & 0xff);
|
||||||
|
memcpy(question, buf, qend);
|
||||||
if((param->remsock=param->srv->so._socket(param->sostate, SASOCK(&nservers[0].addr), nservers[0].usetcp? SOCK_STREAM:SOCK_DGRAM, nservers[0].usetcp?IPPROTO_TCP:IPPROTO_UDP)) == INVALID_SOCKET) {
|
if((param->remsock=param->srv->so._socket(param->sostate, SASOCK(&nservers[0].addr), nservers[0].usetcp? SOCK_STREAM:SOCK_DGRAM, nservers[0].usetcp?IPPROTO_TCP:IPPROTO_UDP)) == INVALID_SOCKET) {
|
||||||
RETURN(818);
|
RETURN(818);
|
||||||
}
|
}
|
||||||
@@ -174,9 +194,21 @@ void * dnsprchild(struct clientparam* param) {
|
|||||||
}
|
}
|
||||||
param->statscli64 += i;
|
param->statscli64 += i;
|
||||||
param->nwrites++;
|
param->nwrites++;
|
||||||
len = sockrecvfrom(param, param->remsock, (struct sockaddr *)¶m->sinsr, buf, BUFSIZE, conf.timeouts[DNS_TO]*1000);
|
/* over UDP only an answer from the name server asked is taken, any
|
||||||
if(len <= 13) {
|
other read past while the time for it lasts */
|
||||||
RETURN(821);
|
deadline = time(NULL) + conf.timeouts[DNS_TO];
|
||||||
|
for(;;){
|
||||||
|
to = (int)(deadline - time(NULL));
|
||||||
|
if(to <= 0) RETURN(821);
|
||||||
|
len = sockrecvfrom(param, param->remsock, (struct sockaddr *)&from, buf, BUFSIZE, to*1000);
|
||||||
|
if(len <= 13) {
|
||||||
|
RETURN(821);
|
||||||
|
}
|
||||||
|
if(nservers[0].usetcp) break;
|
||||||
|
if(*SAFAMILY(&from) == *SAFAMILY(¶m->sinsr) &&
|
||||||
|
!memcmp(SAADDR(&from), SAADDR(¶m->sinsr), SAADDRLEN(¶m->sinsr)) &&
|
||||||
|
*SAPORT(&from) == *SAPORT(¶m->sinsr) &&
|
||||||
|
dnsanswer(buf, len, question, qend)) break;
|
||||||
}
|
}
|
||||||
param->statssrv64 += len;
|
param->statssrv64 += len;
|
||||||
param->nreads++;
|
param->nreads++;
|
||||||
@@ -188,7 +220,10 @@ void * dnsprchild(struct clientparam* param) {
|
|||||||
len -= 2;
|
len -= 2;
|
||||||
if(len < us) len += sockgetlinebuf(param, SERVER, buf+len, us - len, 0, conf.timeouts[SINGLEBYTE_L]);
|
if(len < us) len += sockgetlinebuf(param, SERVER, buf+len, us - len, 0, conf.timeouts[SINGLEBYTE_L]);
|
||||||
if(len != us) RETURN(832);
|
if(len != us) RETURN(832);
|
||||||
|
if(!dnsanswer(buf, len, question, qend)) RETURN(834);
|
||||||
}
|
}
|
||||||
|
buf[0] = cid[0];
|
||||||
|
buf[1] = cid[1];
|
||||||
if(buf[6] || buf[7]){
|
if(buf[6] || buf[7]){
|
||||||
if(socksendto(param, param->clisock, (struct sockaddr *)¶m->sincr, buf, len, conf.timeouts[SINGLEBYTE_L]*1000) != len){
|
if(socksendto(param, param->clisock, (struct sockaddr *)¶m->sincr, buf, len, conf.timeouts[SINGLEBYTE_L]*1000) != len){
|
||||||
RETURN(822);
|
RETURN(822);
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ int ftplogin(struct clientparam *param, char *nbuf, int *innbuf) {
|
|||||||
if(i < 3) return 706;
|
if(i < 3) return 706;
|
||||||
buf[i] = 0;
|
buf[i] = 0;
|
||||||
if(atoi(buf)/100 != 2) {
|
if(atoi(buf)/100 != 2) {
|
||||||
*innbuf = i;
|
if(innbuf)*innbuf = i;
|
||||||
return 702;
|
return 702;
|
||||||
}
|
}
|
||||||
sprintf(buf, "USER %.128s\r\n", param->extusername?param->extusername:(unsigned char *)"anonymous");
|
sprintf(buf, "USER %.128s\r\n", param->extusername?param->extusername:(unsigned char *)"anonymous");
|
||||||
@@ -77,6 +77,9 @@ int ftplogin(struct clientparam *param, char *nbuf, int *innbuf) {
|
|||||||
return 701;
|
return 701;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
/* USER answered at once, logged in (230) or refused: that answer is
|
||||||
|
the client's, waiting for one to its PASS */
|
||||||
|
else if(innbuf)*innbuf = i;
|
||||||
if(res != 2) {
|
if(res != 2) {
|
||||||
return 700;
|
return 700;
|
||||||
}
|
}
|
||||||
|
|||||||
+9
-2
@@ -23,14 +23,18 @@ void * ftpprchild(struct clientparam* param) {
|
|||||||
SOCKET sc = INVALID_SOCKET, ss = INVALID_SOCKET, clidatasock = INVALID_SOCKET;
|
SOCKET sc = INVALID_SOCKET, ss = INVALID_SOCKET, clidatasock = INVALID_SOCKET;
|
||||||
SASIZETYPE sasize;
|
SASIZETYPE sasize;
|
||||||
char * req = NULL;
|
char * req = NULL;
|
||||||
|
#ifndef _WIN32
|
||||||
struct linger lg;
|
struct linger lg;
|
||||||
|
#endif
|
||||||
struct pollfd fds;
|
struct pollfd fds;
|
||||||
|
|
||||||
if(!(buf = malloc(BUFSIZE))) RETURN(876);
|
if(!(buf = malloc(BUFSIZE))) RETURN(876);
|
||||||
param->ctrlsock = param->clisock;
|
param->ctrlsock = param->clisock;
|
||||||
param->operation = CONNECT;
|
param->operation = CONNECT;
|
||||||
|
#ifndef _WIN32
|
||||||
lg.l_onoff = 1;
|
lg.l_onoff = 1;
|
||||||
lg.l_linger = conf.timeouts[STRING_L];;
|
lg.l_linger = conf.timeouts[STRING_L];
|
||||||
|
#endif
|
||||||
if(socksend(param, param->ctrlsock, (unsigned char *)"220 Ready\r\n", 11, conf.timeouts[STRING_S])!=11) {RETURN (801);}
|
if(socksend(param, param->ctrlsock, (unsigned char *)"220 Ready\r\n", 11, conf.timeouts[STRING_S])!=11) {RETURN (801);}
|
||||||
for(;;){
|
for(;;){
|
||||||
i = sockgetlinebuf(param, CLIENT, buf, BUFSIZE - 10, '\n', conf.timeouts[CONNECTION_S]);
|
i = sockgetlinebuf(param, CLIENT, buf, BUFSIZE - 10, '\n', conf.timeouts[CONNECTION_S]);
|
||||||
@@ -128,7 +132,7 @@ void * ftpprchild(struct clientparam* param) {
|
|||||||
param->srv->so._closesocket(param->sostate, clidatasock);
|
param->srv->so._closesocket(param->sostate, clidatasock);
|
||||||
clidatasock = INVALID_SOCKET;
|
clidatasock = INVALID_SOCKET;
|
||||||
}
|
}
|
||||||
if ((clidatasock=socket(SASOCK(¶m->sincl), SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET) {RETURN(821);}
|
if ((clidatasock=param->srv->so._socket(param->sostate, SASOCK(¶m->sincl), SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET) {RETURN(821);}
|
||||||
if(intbindtodevice(param, clidatasock)){RETURN(822);}
|
if(intbindtodevice(param, clidatasock)){RETURN(822);}
|
||||||
*SAPORT(¶m->sincl) = 0;
|
*SAPORT(¶m->sincl) = 0;
|
||||||
if(bindwithrange(param, clidatasock, ¶m->sincl, param->intport)){RETURN(822);}
|
if(bindwithrange(param, clidatasock, ¶m->sincl, param->intport)){RETURN(822);}
|
||||||
@@ -262,8 +266,11 @@ void * ftpprchild(struct clientparam* param) {
|
|||||||
}
|
}
|
||||||
sc = param->remsock;
|
sc = param->remsock;
|
||||||
param->remsock = ss;
|
param->remsock = ss;
|
||||||
|
#ifndef _WIN32
|
||||||
|
/* not on Windows, see the accepting side in proxymain.c */
|
||||||
param->srv->so._setsockopt(param->sostate, param->remsock, SOL_SOCKET, SO_LINGER, (char *)&lg, sizeof(lg));
|
param->srv->so._setsockopt(param->sostate, param->remsock, SOL_SOCKET, SO_LINGER, (char *)&lg, sizeof(lg));
|
||||||
param->srv->so._setsockopt(param->sostate, clidatasock, SOL_SOCKET, SO_LINGER, (char *)&lg, sizeof(lg));
|
param->srv->so._setsockopt(param->sostate, clidatasock, SOL_SOCKET, SO_LINGER, (char *)&lg, sizeof(lg));
|
||||||
|
#endif
|
||||||
param->clisock = clidatasock;
|
param->clisock = clidatasock;
|
||||||
res = mapsocket(param, conf.timeouts[CONNECTION_S]);
|
res = mapsocket(param, conf.timeouts[CONNECTION_S]);
|
||||||
if(param->remsock != INVALID_SOCKET) {
|
if(param->remsock != INVALID_SOCKET) {
|
||||||
|
|||||||
+59
-3
@@ -459,12 +459,12 @@ static int widepath(const char *path, wchar_t *out, int outchars)
|
|||||||
char *p;
|
char *p;
|
||||||
|
|
||||||
if(!strncmp(path, "\\\\?\\", 4)) snprintf(prefixed, sizeof(prefixed), "%s", path);
|
if(!strncmp(path, "\\\\?\\", 4)) snprintf(prefixed, sizeof(prefixed), "%s", path);
|
||||||
else if(path[0] == '\\\\' && path[1] == '\\\\')
|
else if(path[0] == '\\' && path[1] == '\\')
|
||||||
snprintf(prefixed, sizeof(prefixed), "\\\\?\\UNC\\%s", path + 2);
|
snprintf(prefixed, sizeof(prefixed), "\\\\?\\UNC\\%s", path + 2);
|
||||||
else snprintf(prefixed, sizeof(prefixed), "\\\\?\\%s", path);
|
else snprintf(prefixed, sizeof(prefixed), "\\\\?\\%s", path);
|
||||||
|
|
||||||
/* the extended form takes no forward slashes */
|
/* the extended form takes no forward slashes */
|
||||||
for(p = prefixed; *p; p++) if(*p == '/') *p = '\\\\';
|
for(p = prefixed; *p; p++) if(*p == '/') *p = '\\';
|
||||||
|
|
||||||
return MultiByteToWideChar(CP_UTF8, 0, prefixed, -1, out, outchars) > 0? 0 : 1;
|
return MultiByteToWideChar(CP_UTF8, 0, prefixed, -1, out, outchars) > 0? 0 : 1;
|
||||||
}
|
}
|
||||||
@@ -481,9 +481,19 @@ static int filemeta(const char *path, struct filemeta *m)
|
|||||||
{
|
{
|
||||||
#ifdef _WIN32
|
#ifdef _WIN32
|
||||||
wchar_t wide[HTTPSRV_LINE];
|
wchar_t wide[HTTPSRV_LINE];
|
||||||
|
#ifdef __WATCOMC__
|
||||||
|
/* Open Watcom has the 64-bit stat under its older name */
|
||||||
|
#ifndef _S_IFREG
|
||||||
|
#define _S_IFREG S_IFREG
|
||||||
|
#endif
|
||||||
|
struct _stati64 st;
|
||||||
|
|
||||||
|
if(widepath(path, wide, HTTPSRV_LINE) || _wstati64(wide, &st)) return 1;
|
||||||
|
#else
|
||||||
struct _stat64 st;
|
struct _stat64 st;
|
||||||
|
|
||||||
if(widepath(path, wide, HTTPSRV_LINE) || _wstat64(wide, &st)) return 1;
|
if(widepath(path, wide, HTTPSRV_LINE) || _wstat64(wide, &st)) return 1;
|
||||||
|
#endif
|
||||||
m->size = (uint64_t)st.st_size;
|
m->size = (uint64_t)st.st_size;
|
||||||
m->mtime = st.st_mtime;
|
m->mtime = st.st_mtime;
|
||||||
m->isreg = (st.st_mode & _S_IFREG) != 0;
|
m->isreg = (st.st_mode & _S_IFREG) != 0;
|
||||||
@@ -1114,6 +1124,10 @@ void freehttprules(struct httprule *rule)
|
|||||||
next = rule->next;
|
next = rule->next;
|
||||||
if(rule->host.name) free(rule->host.name);
|
if(rule->host.name) free(rule->host.name);
|
||||||
if(rule->url.name) free(rule->url.name);
|
if(rule->url.name) free(rule->url.name);
|
||||||
|
#ifdef WITH_PCRE
|
||||||
|
if(rule->host.re) pcre_pattern_free(rule->host.re);
|
||||||
|
if(rule->url.re) pcre_pattern_free(rule->url.re);
|
||||||
|
#endif
|
||||||
if(rule->params) free(rule->params);
|
if(rule->params) free(rule->params);
|
||||||
if(rule->ctype) free(rule->ctype);
|
if(rule->ctype) free(rule->ctype);
|
||||||
if(rule->hdrs) free(rule->hdrs);
|
if(rule->hdrs) free(rule->hdrs);
|
||||||
@@ -1154,6 +1168,37 @@ static void httpsrv_drain(struct clientparam *param, uint64_t len)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Ends a connection this server is closing while the client may still be
|
||||||
|
sending: a body which was not read, or a request sent behind one answered
|
||||||
|
with a close. Closing with that unread resets the connection, and the
|
||||||
|
client loses the answer. The sending side is shut down instead and what
|
||||||
|
arrives is thrown away until the client closes too, for a bounded time
|
||||||
|
and amount, which is what lets the answer be read. */
|
||||||
|
static void httpsrv_linger(struct clientparam *param)
|
||||||
|
{
|
||||||
|
char buf[HTTPSRV_BLOCK];
|
||||||
|
struct pollfd fd;
|
||||||
|
uint64_t left = HTTPSRV_MAXBODY;
|
||||||
|
time_t deadline = time(NULL) + conf.timeouts[LINGER_TO];
|
||||||
|
|
||||||
|
if(param->clisock == INVALID_SOCKET) return;
|
||||||
|
if(param->srv->so._shutdown(param->sostate, param->clisock, SHUT_WR)) return;
|
||||||
|
while(left){
|
||||||
|
int timeo = (int)(deadline - time(NULL));
|
||||||
|
int got;
|
||||||
|
|
||||||
|
if(timeo <= 0) break;
|
||||||
|
memset(&fd, 0, sizeof(fd));
|
||||||
|
fd.fd = param->clisock;
|
||||||
|
fd.events = POLLIN;
|
||||||
|
if(param->srv->so._poll(param->sostate, &fd, 1, timeo * 1000) <= 0) break;
|
||||||
|
got = (int)param->srv->so._recv(param->sostate, param->clisock, buf,
|
||||||
|
(left > sizeof(buf))? (int)sizeof(buf) : (int)left, 0);
|
||||||
|
if(got <= 0) break;
|
||||||
|
left -= (uint64_t)got;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/* Keeps the request as the client wrote it. Only what a handoff needs: the
|
/* Keeps the request as the client wrote it. Only what a handoff needs: the
|
||||||
request line and the headers, exactly as they came, since the proxy code
|
request line and the headers, exactly as they came, since the proxy code
|
||||||
reads them again from the beginning. */
|
reads them again from the beginning. */
|
||||||
@@ -1451,6 +1496,12 @@ static int httpsrv_request(struct clientparam *param, struct httpreq *r)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if(i && i != 10){
|
if(i && i != 10){
|
||||||
|
/* The body goes before the answer, as for any answer this server
|
||||||
|
gives: left in the stream it would be read as the next request. */
|
||||||
|
if(!r->drained){
|
||||||
|
if(r->contentlen) httpsrv_drain(param, r->contentlen);
|
||||||
|
r->drained = 1;
|
||||||
|
}
|
||||||
/* 4 no credentials, 5 unknown user, 6 wrong password: all of them
|
/* 4 no credentials, 5 unknown user, 6 wrong password: all of them
|
||||||
should let the client offer credentials again. */
|
should let the client offer credentials again. */
|
||||||
if(i >= 4 && i <= 6) op_authrequired(r);
|
if(i >= 4 && i <= 6) op_authrequired(r);
|
||||||
@@ -1573,7 +1624,12 @@ void * httpsrvchild(struct clientparam *param)
|
|||||||
dolog(param, (unsigned char *)logbuf);
|
dolog(param, (unsigned char *)logbuf);
|
||||||
}
|
}
|
||||||
|
|
||||||
if(handoff || !r.keepalive) break;
|
if(handoff) break;
|
||||||
|
if(!r.keepalive){
|
||||||
|
/* the client may still be sending; let it read the answer */
|
||||||
|
httpsrv_linger(param);
|
||||||
|
break;
|
||||||
|
}
|
||||||
first = 0;
|
first = 0;
|
||||||
}
|
}
|
||||||
/* A child named by an access rule takes the connection over, which the
|
/* A child named by an access rule takes the connection over, which the
|
||||||
|
|||||||
+38
-9
@@ -220,6 +220,14 @@ struct pcre_filter_data {
|
|||||||
struct ace *acl;
|
struct ace *acl;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/* What a connection matches with: pcre2_match() writes into its match
|
||||||
|
data, so a thread matching on the rule's own one would race every
|
||||||
|
other thread doing the same. */
|
||||||
|
struct pcre_client_data {
|
||||||
|
struct pcre_filter_data *pcrefd;
|
||||||
|
pcre2_match_data * match_data;
|
||||||
|
};
|
||||||
|
|
||||||
static void pcre_data_free(struct pcre_filter_data *pcrefd){
|
static void pcre_data_free(struct pcre_filter_data *pcrefd){
|
||||||
_3proxy_mutex_lock(&pcre_mutex);
|
_3proxy_mutex_lock(&pcre_mutex);
|
||||||
pcrefd->users--;
|
pcrefd->users--;
|
||||||
@@ -253,16 +261,30 @@ static void* pcre_filter_open(void * idata, struct srvparam * param){
|
|||||||
static FILTER_ACTION pcre_filter_client(void *fo, struct clientparam * param, void** fc){
|
static FILTER_ACTION pcre_filter_client(void *fo, struct clientparam * param, void** fc){
|
||||||
int res;
|
int res;
|
||||||
struct ace tmpace;
|
struct ace tmpace;
|
||||||
|
struct pcre_filter_data *rule = (struct pcre_filter_data *)fo;
|
||||||
|
struct pcre_client_data *pcd;
|
||||||
|
|
||||||
*fc = fo;
|
*fc = fo;
|
||||||
if(!fo) return PASS;
|
if(!fo) return PASS;
|
||||||
#define pcrefd ((struct pcre_filter_data *)fo)
|
if(!rule->acl) return CONTINUE;
|
||||||
if(!pcrefd->acl) return CONTINUE;
|
|
||||||
memset (&tmpace, 0, sizeof(struct ace));
|
memset (&tmpace, 0, sizeof(struct ace));
|
||||||
tmpace.src = pcrefd->acl->src;
|
tmpace.src = rule->acl->src;
|
||||||
res = pl->ACLMatches(&tmpace, param);
|
res = pl->ACLMatches(&tmpace, param);
|
||||||
#undef pcrefd
|
if(!res) return PASS;
|
||||||
return (res)? CONTINUE:PASS;
|
/* the connection goes on with a match data of its own */
|
||||||
|
if(!(pcd = pl->mallocfunc(sizeof(struct pcre_client_data)))){
|
||||||
|
*fc = NULL;
|
||||||
|
return rule->action;
|
||||||
|
}
|
||||||
|
pcd->pcrefd = rule;
|
||||||
|
pcd->match_data = NULL;
|
||||||
|
if(rule->re && !(pcd->match_data = pcre2_match_data_create_from_pattern(rule->re, NULL))){
|
||||||
|
pl->freefunc(pcd);
|
||||||
|
*fc = NULL;
|
||||||
|
return rule->action;
|
||||||
|
}
|
||||||
|
*fc = pcd;
|
||||||
|
return CONTINUE;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* What a rewritten buffer keeps free for its caller to append to. */
|
/* What a rewritten buffer keeps free for its caller to append to. */
|
||||||
@@ -277,7 +299,8 @@ static FILTER_ACTION pcre_filter_buffer(void *fc, struct clientparam *param, uns
|
|||||||
char * replace;
|
char * replace;
|
||||||
char * tmpbuf, *target, *newbuf;
|
char * tmpbuf, *target, *newbuf;
|
||||||
int nreplaces=0;
|
int nreplaces=0;
|
||||||
#define pcrefd ((struct pcre_filter_data *)fc)
|
struct pcre_client_data *pcd = (struct pcre_client_data *)fc;
|
||||||
|
#define pcrefd (pcd->pcrefd)
|
||||||
|
|
||||||
for(acl = pcrefd->acl; acl; acl=acl->next){
|
for(acl = pcrefd->acl; acl; acl=acl->next){
|
||||||
if(pl->ACLMatches(acl, param)){
|
if(pl->ACLMatches(acl, param)){
|
||||||
@@ -290,9 +313,9 @@ static FILTER_ACTION pcre_filter_buffer(void *fc, struct clientparam *param, uns
|
|||||||
for(; offset < *length_p; nreplaces++){
|
for(; offset < *length_p; nreplaces++){
|
||||||
int repsz;
|
int repsz;
|
||||||
|
|
||||||
count = pcre2_match(pcrefd->re, (PCRE2_SPTR)*buf_p, *length_p, offset, 0, pcrefd->match_data, pcrefd->match_context);
|
count = pcre2_match(pcrefd->re, (PCRE2_SPTR)*buf_p, *length_p, offset, 0, pcd->match_data, pcrefd->match_context);
|
||||||
if(count <= 0) break;
|
if(count <= 0) break;
|
||||||
ovector = pcre2_get_ovector_pointer(pcrefd->match_data);
|
ovector = pcre2_get_ovector_pointer(pcd->match_data);
|
||||||
if(ovector[0] > (PCRE2_SIZE)*length_p || ovector[1] > (PCRE2_SIZE)*length_p || ovector[1] < ovector[0]) break;
|
if(ovector[0] > (PCRE2_SIZE)*length_p || ovector[1] > (PCRE2_SIZE)*length_p || ovector[1] < ovector[0]) break;
|
||||||
if(!(replace = pcrefd->replace) || param->nooverwritefilter) return pcrefd->action;
|
if(!(replace = pcrefd->replace) || param->nooverwritefilter) return pcrefd->action;
|
||||||
|
|
||||||
@@ -376,7 +399,13 @@ static FILTER_ACTION pcre_filter_buffer(void *fc, struct clientparam *param, uns
|
|||||||
#undef pcrefd
|
#undef pcrefd
|
||||||
}
|
}
|
||||||
|
|
||||||
static void pcre_filter_clear(void *fo){
|
static void pcre_filter_clear(void *fc){
|
||||||
|
struct pcre_client_data *pcd = (struct pcre_client_data *)fc;
|
||||||
|
|
||||||
|
if(pcd){
|
||||||
|
if(pcd->match_data) pcre2_match_data_free(pcd->match_data);
|
||||||
|
pl->freefunc(pcd);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
static void pcre_filter_close(void *fo){
|
static void pcre_filter_close(void *fo){
|
||||||
|
|||||||
@@ -286,7 +286,7 @@ void processcallbacks(struct fp_stream *fps, int what, char *msg, int size){
|
|||||||
case GOT_SMTP_REQ:
|
case GOT_SMTP_REQ:
|
||||||
case GOT_SMTP_DATA:
|
case GOT_SMTP_DATA:
|
||||||
fps->state = FLUSH_DATA;
|
fps->state = FLUSH_DATA;
|
||||||
pl->socksend(fps->fpd.cp->sostate,fps->fpd.cp->clisock, (unsigned char *)fp_stringtable[1], (int)strlen((char *)fp_stringtable[1]), pl->conf->timeouts[STRING_S]);
|
pl->socksend(NULL, fps->fpd.cp->clisock, (unsigned char *)fp_stringtable[1], (int)strlen((char *)fp_stringtable[1]), pl->conf->timeouts[STRING_S]);
|
||||||
fps->state = state;
|
fps->state = state;
|
||||||
break;
|
break;
|
||||||
case GOT_HTTP_REQUEST:
|
case GOT_HTTP_REQUEST:
|
||||||
@@ -298,7 +298,7 @@ void processcallbacks(struct fp_stream *fps, int what, char *msg, int size){
|
|||||||
case GOT_HTTP_SRVDATA:
|
case GOT_HTTP_SRVDATA:
|
||||||
if(!fps->serversent){
|
if(!fps->serversent){
|
||||||
fps->state = FLUSH_DATA;
|
fps->state = FLUSH_DATA;
|
||||||
pl->socksend(fps->fpd.cp->sostate, fps->fpd.cp->clisock, (unsigned char *)fp_stringtable[0], (int)strlen((char *)fp_stringtable[0]), pl->conf->timeouts[STRING_S]);
|
pl->socksend(NULL, fps->fpd.cp->clisock, (unsigned char *)fp_stringtable[0], (int)strlen((char *)fp_stringtable[0]), pl->conf->timeouts[STRING_S]);
|
||||||
fps->state = state;
|
fps->state = state;
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
@@ -306,7 +306,7 @@ void processcallbacks(struct fp_stream *fps, int what, char *msg, int size){
|
|||||||
case GOT_FTP_REQ:
|
case GOT_FTP_REQ:
|
||||||
case GOT_FTP_SRVDATA:
|
case GOT_FTP_SRVDATA:
|
||||||
fps->state = FLUSH_DATA;
|
fps->state = FLUSH_DATA;
|
||||||
pl->socksend(fps->fpd.cp->sostate, fps->fpd.cp->ctrlsock, (unsigned char *)fp_stringtable[1], (int)strlen((char *)fp_stringtable[1]), pl->conf->timeouts[STRING_S]);
|
pl->socksend(NULL, fps->fpd.cp->ctrlsock, (unsigned char *)fp_stringtable[1], (int)strlen((char *)fp_stringtable[1]), pl->conf->timeouts[STRING_S]);
|
||||||
fps->state = state;
|
fps->state = state;
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
@@ -358,7 +358,7 @@ static int copyfdtosock(struct fp_stream * fps, DIRECTION which, long len){
|
|||||||
if(fps->serversent >= fps->srvhdrwritten){
|
if(fps->serversent >= fps->srvhdrwritten){
|
||||||
sprintf(fps->buf, "%lx\r\n", len);
|
sprintf(fps->buf, "%lx\r\n", len);
|
||||||
sendchunk = (int)strlen(fps->buf);
|
sendchunk = (int)strlen(fps->buf);
|
||||||
if(pl->socksend(fps->fpd.cp->sostate, fps->fpd.cp->clisock, (unsigned char *)fps->buf, sendchunk, pl->conf->timeouts[STRING_S]) != sendchunk){
|
if(pl->socksend(NULL, fps->fpd.cp->clisock, (unsigned char *)fps->buf, sendchunk, pl->conf->timeouts[STRING_S]) != sendchunk){
|
||||||
return -4;
|
return -4;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -397,13 +397,13 @@ static int copyfdtosock(struct fp_stream * fps, DIRECTION which, long len){
|
|||||||
#endif
|
#endif
|
||||||
return -3;
|
return -3;
|
||||||
}
|
}
|
||||||
if(pl->socksend(fps->fpd.cp->sostate, sock, (unsigned char *)fps->buf, res, pl->conf->timeouts[STRING_S]) != res) {
|
if(pl->socksend(NULL, sock, (unsigned char *)fps->buf, res, pl->conf->timeouts[STRING_S]) != res) {
|
||||||
return -4;
|
return -4;
|
||||||
}
|
}
|
||||||
len -= res;
|
len -= res;
|
||||||
}
|
}
|
||||||
if(sendchunk){
|
if(sendchunk){
|
||||||
if(pl->socksend(fps->fpd.cp->sostate, sock, (unsigned char *)"\r\n", 2, pl->conf->timeouts[STRING_S]) != 2)
|
if(pl->socksend(NULL, sock, (unsigned char *)"\r\n", 2, pl->conf->timeouts[STRING_S]) != 2)
|
||||||
return -4;
|
return -4;
|
||||||
}
|
}
|
||||||
fps->state = state;
|
fps->state = state;
|
||||||
|
|||||||
@@ -61,14 +61,9 @@ char **load_string(FILE *f,int max_count_str, int *countloadstr,
|
|||||||
|
|
||||||
if (strstr(tmpbuf1,"[end]")==NULL)
|
if (strstr(tmpbuf1,"[end]")==NULL)
|
||||||
{
|
{
|
||||||
/* find and replace \n \r*/
|
/* the line's end cut off: what the file says with \n is what is
|
||||||
rstr = tmpbuf1;
|
sent */
|
||||||
while (*rstr!='\0')
|
tmpbuf1[strcspn(tmpbuf1, "\r\n")] = '\0';
|
||||||
{
|
|
||||||
if (*rstr=='\r' || *rstr=='\n' )
|
|
||||||
{ *rstr='\0'; rstr++; }
|
|
||||||
rstr++;
|
|
||||||
}
|
|
||||||
|
|
||||||
while ((rstr=strstr(tmpbuf1,"\\n")))
|
while ((rstr=strstr(tmpbuf1,"\\n")))
|
||||||
{
|
{
|
||||||
|
|||||||
+49
-7
@@ -140,6 +140,8 @@ char * proxy_stringtable[] = {
|
|||||||
#define HDRRESERVE 2048
|
#define HDRRESERVE 2048
|
||||||
#define BUFSIZE (LINESIZE*2)
|
#define BUFSIZE (LINESIZE*2)
|
||||||
#define FTPBUFSIZE 1536
|
#define FTPBUFSIZE 1536
|
||||||
|
/* seconds a connection waits for its next request before its buffer is freed */
|
||||||
|
#define IDLEBUF 1
|
||||||
|
|
||||||
#define PST_COUNT (sizeof(proxy_stringtable)/sizeof(proxy_stringtable[0]) - 1)
|
#define PST_COUNT (sizeof(proxy_stringtable)/sizeof(proxy_stringtable[0]) - 1)
|
||||||
static int proxy_stringtable_len[PST_COUNT];
|
static int proxy_stringtable_len[PST_COUNT];
|
||||||
@@ -171,6 +173,20 @@ static int growbuf(unsigned char **buf, int *bufsize, int need){
|
|||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Whether a request line names the host the previous one did, whatever its
|
||||||
|
method: the connection to the server is kept for the same host only, and
|
||||||
|
a POST after a GET to it is no reason to open another one. */
|
||||||
|
static int samehost(const unsigned char *line, int len, const unsigned char *host, int hostlen){
|
||||||
|
const unsigned char *p = (const unsigned char *)memchr(line, ' ', len);
|
||||||
|
|
||||||
|
if(!p || hostlen <= 0) return 0;
|
||||||
|
p++;
|
||||||
|
if(!strncasecmp((const char *)p, "http://", 7)) p += 7;
|
||||||
|
if((int)(p - line) + hostlen >= len || strncasecmp((const char *)p, (const char *)host, hostlen))
|
||||||
|
return 0;
|
||||||
|
return p[hostlen] == '/' || p[hostlen] == ' ';
|
||||||
|
}
|
||||||
|
|
||||||
static void freeptr(void *p){
|
static void freeptr(void *p){
|
||||||
void **pp = (void **)p;
|
void **pp = (void **)p;
|
||||||
if(*pp) { free(*pp); *pp = NULL; }
|
if(*pp) { free(*pp); *pp = NULL; }
|
||||||
@@ -200,11 +216,16 @@ static void logurl(struct clientparam * param, char * buf, char * req, int ftp){
|
|||||||
char *sb;
|
char *sb;
|
||||||
char *se;
|
char *se;
|
||||||
int len;
|
int len;
|
||||||
|
char *own = NULL;
|
||||||
|
|
||||||
if(!buf) req = NULL;
|
if(param->res == 555 || param->res == 508) return;
|
||||||
if(req) {
|
if(req) {
|
||||||
len = (int)strlen(req);
|
len = (int)strlen(req);
|
||||||
if(len > (LINESIZE - 1)) len = LINESIZE - 1;
|
if(len > (LINESIZE - 1)) len = LINESIZE - 1;
|
||||||
|
/* a tunnel gave its buffer back before it was relayed */
|
||||||
|
if(!buf && !(buf = own = malloc(LINESIZE))) req = NULL;
|
||||||
|
}
|
||||||
|
if(req) {
|
||||||
memcpy(buf, req, len + 1);
|
memcpy(buf, req, len + 1);
|
||||||
buf[LINESIZE - 1] = 0;
|
buf[LINESIZE - 1] = 0;
|
||||||
sb = strchr(buf, '\r');
|
sb = strchr(buf, '\r');
|
||||||
@@ -213,7 +234,8 @@ static void logurl(struct clientparam * param, char * buf, char * req, int ftp){
|
|||||||
memmove(se, sb, strlen(sb)+1);
|
memmove(se, sb, strlen(sb)+1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if(param->res != 555 && param->res != 508)dolog(param, (unsigned char *)(req?buf:NULL));
|
dolog(param, (unsigned char *)(req?buf:NULL));
|
||||||
|
free(own);
|
||||||
}
|
}
|
||||||
|
|
||||||
void decodeurl(unsigned char *s, int allowcr){
|
void decodeurl(unsigned char *s, int allowcr){
|
||||||
@@ -285,7 +307,7 @@ void * proxychild(struct clientparam* param) {
|
|||||||
int clhdrofs_req = -1;
|
int clhdrofs_req = -1;
|
||||||
int isconnect = 0;
|
int isconnect = 0;
|
||||||
int redirect = 0;
|
int redirect = 0;
|
||||||
int prefix = 0, ckeepalive=0;
|
int prefix = 0, hostofs = 0, ckeepalive=0;
|
||||||
int ftp = 0;
|
int ftp = 0;
|
||||||
int ssoff = 0;
|
int ssoff = 0;
|
||||||
#ifndef ANONYMOUS
|
#ifndef ANONYMOUS
|
||||||
@@ -309,18 +331,24 @@ void * proxychild(struct clientparam* param) {
|
|||||||
|
|
||||||
|
|
||||||
if(param->remsock != INVALID_SOCKET) haveconnection = 1;
|
if(param->remsock != INVALID_SOCKET) haveconnection = 1;
|
||||||
if(!(buf = malloc(BUFSIZE))) {RETURN(21);}
|
|
||||||
bufsize = BUFSIZE;
|
|
||||||
#ifndef ANONYMOUS
|
#ifndef ANONYMOUS
|
||||||
anonymous = param->srv->anonymous;
|
anonymous = param->srv->anonymous;
|
||||||
#endif
|
#endif
|
||||||
for(;;){
|
for(;;){
|
||||||
memset(buf, 0, bufsize);
|
|
||||||
inbuf = 0;
|
inbuf = 0;
|
||||||
chunkedcli = 0;
|
chunkedcli = 0;
|
||||||
clhdrofs_req = -1;
|
clhdrofs_req = -1;
|
||||||
param->nolongdatfilter = 0;
|
param->nolongdatfilter = 0;
|
||||||
|
|
||||||
|
/* A connection waiting a while for its next request, or a tunnel, holds
|
||||||
|
no buffer: it is taken again once a request starts coming. */
|
||||||
|
if(buf && param->cliinbuf == param->clioffset){
|
||||||
|
memset(fds, 0, sizeof(fds));
|
||||||
|
fds[0].fd = param->clisock;
|
||||||
|
fds[0].events = POLLIN;
|
||||||
|
if(param->srv->so._poll(param->sostate, fds, 1, IDLEBUF * 1000) == 0) freeptr(&buf);
|
||||||
|
}
|
||||||
|
if(buf) memset(buf, 0, bufsize);
|
||||||
|
|
||||||
if(keepalive && (param->cliinbuf == param->clioffset) && (param->remsock != INVALID_SOCKET)){
|
if(keepalive && (param->cliinbuf == param->clioffset) && (param->remsock != INVALID_SOCKET)){
|
||||||
memset(fds, 0, sizeof(fds));
|
memset(fds, 0, sizeof(fds));
|
||||||
@@ -346,6 +374,13 @@ for(;;){
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if(!buf){
|
||||||
|
if(sockgetcharcli(param, conf.timeouts[STRING_L], 0) == EOF) RETURN((keepalive)?555:508);
|
||||||
|
param->clioffset--;
|
||||||
|
if(!(buf = malloc(BUFSIZE))) {RETURN(21);}
|
||||||
|
bufsize = BUFSIZE;
|
||||||
|
memset(buf, 0, bufsize);
|
||||||
|
}
|
||||||
i = sockgetlinebuf(param, CLIENT, buf, LINESIZE - 1, '\n', conf.timeouts[STRING_L]);
|
i = sockgetlinebuf(param, CLIENT, buf, LINESIZE - 1, '\n', conf.timeouts[STRING_L]);
|
||||||
if(i<=0) {
|
if(i<=0) {
|
||||||
RETURN((keepalive)?555:(i)?507:508);
|
RETURN((keepalive)?555:(i)?507:508);
|
||||||
@@ -354,7 +389,7 @@ for(;;){
|
|||||||
buf[i] = 0;
|
buf[i] = 0;
|
||||||
|
|
||||||
if(req) {
|
if(req) {
|
||||||
if(!param->transparent && !param->srv->transparent && (i<=prefix || strncasecmp((char *)buf, (char *)req, prefix))){
|
if(!param->transparent && !param->srv->transparent && !samehost(buf, i, req + hostofs, prefix - hostofs)){
|
||||||
ckeepalive = 0;
|
ckeepalive = 0;
|
||||||
if(param->remsock != INVALID_SOCKET){
|
if(param->remsock != INVALID_SOCKET){
|
||||||
param->srv->so._shutdown(param->sostate, param->remsock, SHUT_RDWR);
|
param->srv->so._shutdown(param->sostate, param->remsock, SHUT_RDWR);
|
||||||
@@ -387,6 +422,7 @@ for(;;){
|
|||||||
}
|
}
|
||||||
#ifdef WITH_FTP
|
#ifdef WITH_FTP
|
||||||
else if (!strncasecmp((char *)sb, "ftp://", 6)) {
|
else if (!strncasecmp((char *)sb, "ftp://", 6)) {
|
||||||
|
if(!param->srv->allowftp) RETURN(513);
|
||||||
ftp = 1;
|
ftp = 1;
|
||||||
sb += 6;
|
sb += 6;
|
||||||
}
|
}
|
||||||
@@ -411,6 +447,7 @@ for(;;){
|
|||||||
*se = 0;
|
*se = 0;
|
||||||
}
|
}
|
||||||
prefix = (int)(se - buf);
|
prefix = (int)(se - buf);
|
||||||
|
hostofs = (int)(sb - buf);
|
||||||
su = (unsigned char*)strrchr((char *)sb, '@');
|
su = (unsigned char*)strrchr((char *)sb, '@');
|
||||||
if(su) {
|
if(su) {
|
||||||
su = (unsigned char *)strdup((char *)sb);
|
su = (unsigned char *)strdup((char *)sb);
|
||||||
@@ -973,6 +1010,7 @@ for(;;){
|
|||||||
freeptr(&req); freeptr(&buf); freeptr(&ftpbase);
|
freeptr(&req); freeptr(&buf); freeptr(&ftpbase);
|
||||||
return (void *)param->redirectfunc;
|
return (void *)param->redirectfunc;
|
||||||
}
|
}
|
||||||
|
freeptr(&buf);
|
||||||
param->res = mapsocket(param, conf.timeouts[CONNECTION_L]);
|
param->res = mapsocket(param, conf.timeouts[CONNECTION_L]);
|
||||||
RETURN(param->res);
|
RETURN(param->res);
|
||||||
}
|
}
|
||||||
@@ -1284,6 +1322,7 @@ for(;;){
|
|||||||
} while(param->chunked);
|
} while(param->chunked);
|
||||||
}
|
}
|
||||||
if(isconnect && res == 200 && param->operation){
|
if(isconnect && res == 200 && param->operation){
|
||||||
|
freeptr(&buf);
|
||||||
RETURN (mapsocket(param, conf.timeouts[CONNECTION_S]));
|
RETURN (mapsocket(param, conf.timeouts[CONNECTION_S]));
|
||||||
}
|
}
|
||||||
else if(isconnect){
|
else if(isconnect){
|
||||||
@@ -1357,6 +1396,9 @@ struct proxydef childdef = {
|
|||||||
S_PROXY,
|
S_PROXY,
|
||||||
"-a - anonymous proxy\r\n"
|
"-a - anonymous proxy\r\n"
|
||||||
"-a1 - anonymous proxy with random client IP spoofing\r\n"
|
"-a1 - anonymous proxy with random client IP spoofing\r\n"
|
||||||
|
#ifdef WITH_FTP
|
||||||
|
"-Xftp - fetch ftp:// URLs\r\n"
|
||||||
|
#endif
|
||||||
};
|
};
|
||||||
#include "proxymain.c"
|
#include "proxymain.c"
|
||||||
#endif
|
#endif
|
||||||
+29
-5
@@ -191,7 +191,8 @@ size_t threadstacksize(int extra);
|
|||||||
#ifndef strncasecmp
|
#ifndef strncasecmp
|
||||||
#define strncasecmp strnicmp
|
#define strncasecmp strnicmp
|
||||||
#endif
|
#endif
|
||||||
#define seterrno3(x) _set_errno(x)
|
/* errno is WSAGetLastError() here */
|
||||||
|
#define seterrno3(x) WSASetLastError(x)
|
||||||
#else
|
#else
|
||||||
#define seterrno3(x) (errno = x)
|
#define seterrno3(x) (errno = x)
|
||||||
#endif
|
#endif
|
||||||
@@ -239,6 +240,11 @@ extern struct extparam conf;
|
|||||||
|
|
||||||
extern int timeouts[12];
|
extern int timeouts[12];
|
||||||
|
|
||||||
|
/* directions sockmap() passes with splice(): -s1, -s2, -s3; with
|
||||||
|
SPLICE_AUTO (-s alone, -s5 to -s7) only when it pays */
|
||||||
|
#define SPLICE_DOWNLOAD 1
|
||||||
|
#define SPLICE_UPLOAD 2
|
||||||
|
#define SPLICE_AUTO 4
|
||||||
int sockmap(struct clientparam * param, int timeo, int usesplice);
|
int sockmap(struct clientparam * param, int timeo, int usesplice);
|
||||||
int udpsockmap(struct clientparam * param, int timeo);
|
int udpsockmap(struct clientparam * param, int timeo);
|
||||||
int udpbind(struct clientparam * param);
|
int udpbind(struct clientparam * param);
|
||||||
@@ -322,13 +328,23 @@ extern _3proxy_sem_t udpinit;
|
|||||||
#define _3proxy_sem_init(x, count, maxcount) (((x) = CreateSemaphore(NULL, (count), (maxcount), NULL))? 0 : 1)
|
#define _3proxy_sem_init(x, count, maxcount) (((x) = CreateSemaphore(NULL, (count), (maxcount), NULL))? 0 : 1)
|
||||||
#define _3proxy_sem_lock(x) WaitForSingleObject(x, INFINITE)
|
#define _3proxy_sem_lock(x) WaitForSingleObject(x, INFINITE)
|
||||||
#define _3proxy_sem_unlock(x) ReleaseSemaphore(x, 1, NULL)
|
#define _3proxy_sem_unlock(x) ReleaseSemaphore(x, 1, NULL)
|
||||||
|
#define _3proxy_sem_init_timed(x, count, maxcount) _3proxy_sem_init(x, (count), (maxcount))
|
||||||
|
#define _3proxy_sem_timedlock(x, ms) (WaitForSingleObject(x, ms) != WAIT_OBJECT_0)
|
||||||
|
#define _3proxy_sem_destroy(x) CloseHandle(x)
|
||||||
#else
|
#else
|
||||||
int _3proxy_sem_init_f(_3proxy_sem_t *sem, unsigned count, unsigned maxcount);
|
int _3proxy_sem_init_f(_3proxy_sem_t *sem, unsigned count, unsigned maxcount, int timed);
|
||||||
void _3proxy_sem_lock_f(_3proxy_sem_t *sem);
|
void _3proxy_sem_lock_f(_3proxy_sem_t *sem);
|
||||||
|
int _3proxy_sem_timedlock_f(_3proxy_sem_t *sem, unsigned ms);
|
||||||
void _3proxy_sem_unlock_f(_3proxy_sem_t *sem);
|
void _3proxy_sem_unlock_f(_3proxy_sem_t *sem);
|
||||||
#define _3proxy_sem_init(x, count, maxcount) _3proxy_sem_init_f(&x, (count), (maxcount))
|
void _3proxy_sem_destroy_f(_3proxy_sem_t *sem);
|
||||||
|
#define _3proxy_sem_init(x, count, maxcount) _3proxy_sem_init_f(&x, (count), (maxcount), 0)
|
||||||
|
/* for a semaphore waited on with a timeout: the wait is not stretched or cut
|
||||||
|
short by the system time being changed, where the platform allows it */
|
||||||
|
#define _3proxy_sem_init_timed(x, count, maxcount) _3proxy_sem_init_f(&x, (count), (maxcount), 1)
|
||||||
#define _3proxy_sem_lock(x) _3proxy_sem_lock_f(&x)
|
#define _3proxy_sem_lock(x) _3proxy_sem_lock_f(&x)
|
||||||
|
#define _3proxy_sem_timedlock(x, ms) _3proxy_sem_timedlock_f(&x, (ms))
|
||||||
#define _3proxy_sem_unlock(x) _3proxy_sem_unlock_f(&x)
|
#define _3proxy_sem_unlock(x) _3proxy_sem_unlock_f(&x)
|
||||||
|
#define _3proxy_sem_destroy(x) _3proxy_sem_destroy_f(&x)
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
|
||||||
@@ -390,6 +406,8 @@ unsigned char * dologname (unsigned char *buf, unsigned char *name, const unsign
|
|||||||
int readconfig(FILE * fp);
|
int readconfig(FILE * fp);
|
||||||
void initcommands(void);
|
void initcommands(void);
|
||||||
int connectwithpoll(struct clientparam *param, SOCKET sock, struct sockaddr *sa, SASIZETYPE size, int to);
|
int connectwithpoll(struct clientparam *param, SOCKET sock, struct sockaddr *sa, SASIZETYPE size, int to);
|
||||||
|
void nonblock(SOCKET sock);
|
||||||
|
int acceptagain(void);
|
||||||
int bindwithrange(struct clientparam *param, SOCKET sock, PROXYSOCKADDRTYPE *sa, uint32_t range);
|
int bindwithrange(struct clientparam *param, SOCKET sock, PROXYSOCKADDRTYPE *sa, uint32_t range);
|
||||||
int bindtodevice(struct sockfuncs *sf, void *state, SOCKET sock, const char *device, int family);
|
int bindtodevice(struct sockfuncs *sf, void *state, SOCKET sock, const char *device, int family);
|
||||||
int extbindtodevice(struct clientparam *param, SOCKET sock);
|
int extbindtodevice(struct clientparam *param, SOCKET sock);
|
||||||
@@ -457,6 +475,10 @@ struct dictionary;
|
|||||||
struct node;
|
struct node;
|
||||||
struct property;
|
struct property;
|
||||||
extern _3proxy_mutex_t config_mutex;
|
extern _3proxy_mutex_t config_mutex;
|
||||||
|
/* services running, and a post each time one of them has finished */
|
||||||
|
extern int runningservices;
|
||||||
|
extern _3proxy_mutex_t runningservices_mutex;
|
||||||
|
extern _3proxy_sem_t serviceexited;
|
||||||
extern _3proxy_mutex_t bandlim_mutex;
|
extern _3proxy_mutex_t bandlim_mutex;
|
||||||
extern _3proxy_mutex_t connlim_mutex;
|
extern _3proxy_mutex_t connlim_mutex;
|
||||||
extern _3proxy_mutex_t tc_mutex;
|
extern _3proxy_mutex_t tc_mutex;
|
||||||
@@ -467,7 +489,7 @@ extern struct datatype datatypes[64];
|
|||||||
extern struct commands commandhandlers[];
|
extern struct commands commandhandlers[];
|
||||||
|
|
||||||
#ifdef WITHSPLICE
|
#ifdef WITHSPLICE
|
||||||
#define mapsocket(a,b) ((a->srv->usesplice && !a->ndatfilterssrv && !a->ndatfilterscli)?sockmap(a,b,1):sockmap(a,b,0))
|
#define mapsocket(a,b) ((a->srv->usesplice && !a->ndatfilterssrv && !a->ndatfilterscli)?sockmap(a,b,a->srv->usesplice):sockmap(a,b,0))
|
||||||
#else
|
#else
|
||||||
#define mapsocket(a,b) sockmap(a,b, 0)
|
#define mapsocket(a,b) sockmap(a,b, 0)
|
||||||
#endif
|
#endif
|
||||||
@@ -487,8 +509,10 @@ extern struct socketoptions {
|
|||||||
int opt;
|
int opt;
|
||||||
char * optname;
|
char * optname;
|
||||||
} sockopts[];
|
} sockopts[];
|
||||||
void setopts(SOCKET s, int opts);
|
int getopts(const char *s, struct sockoptset *opts);
|
||||||
|
void setopts(SOCKET s, const struct sockoptset *opts);
|
||||||
char * printopts(char *sep);
|
char * printopts(char *sep);
|
||||||
|
char * printfeatures(char *sep);
|
||||||
|
|
||||||
#ifdef _WINCE
|
#ifdef _WINCE
|
||||||
char * CEToUnicode (const char *str);
|
char * CEToUnicode (const char *str);
|
||||||
|
|||||||
+1227
-908
File diff suppressed because it is too large.
Load diff
+7
-4
@@ -167,6 +167,7 @@ uint32_t udpresolve(int af, unsigned char * name, unsigned char * value, uint32_
|
|||||||
k += 4;
|
k += 4;
|
||||||
if(na > 255) na = 255; /* somebody is very evil */
|
if(na > 255) na = 255; /* somebody is very evil */
|
||||||
for (j = 0; j < na; j++) { /* now there should be answers */
|
for (j = 0; j < na; j++) { /* now there should be answers */
|
||||||
|
if(k >= len) break;
|
||||||
while(buf[k] < 192 && buf[k] !=0 && (k+buf[k]+14) < len) k+= (buf[k] + 1);
|
while(buf[k] < 192 && buf[k] !=0 && (k+buf[k]+14) < len) k+= (buf[k] + 1);
|
||||||
if(!buf[k]) k--;
|
if(!buf[k]) k--;
|
||||||
if((k+(af == AF_INET6?28:16)) > len) {
|
if((k+(af == AF_INET6?28:16)) > len) {
|
||||||
@@ -195,12 +196,14 @@ uint32_t udpresolve(int af, unsigned char * name, unsigned char * value, uint32_
|
|||||||
k+= (12 + flen);
|
k+= (12 + flen);
|
||||||
continue; /* we need A PTR */
|
continue; /* we need A PTR */
|
||||||
}
|
}
|
||||||
for (s2 = buf + k + 12; s2 < (buf + k + 12 + len) && *s2; ){
|
s1 = buf + k + 12 + flen; /* the end of this record's data, inside the answer */
|
||||||
s1 = s2 + ((unsigned)*s2) + 1;
|
for (s2 = buf + k + 12; s2 < s1 && *s2 && *s2 < 64; ){
|
||||||
|
unsigned char *next = s2 + ((unsigned)*s2) + 1;
|
||||||
*s2 = '.';
|
*s2 = '.';
|
||||||
s2 = s1;
|
s2 = next;
|
||||||
}
|
}
|
||||||
*s2 = 0;
|
if(s2 >= s1 || *s2 || s2 == buf + k + 12)
|
||||||
|
break; /* the name runs past its data, is compressed or empty */
|
||||||
if(param->username)free(param->username);
|
if(param->username)free(param->username);
|
||||||
param->username = (unsigned char *)strdup ((char *)buf + k + 13);
|
param->username = (unsigned char *)strdup ((char *)buf + k + 13);
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,110 @@
|
|||||||
|
/*
|
||||||
|
3APA3A simplest proxy server
|
||||||
|
(c) 2002-2026 by Vladimir Dubrovin <vlad@3proxy.org>
|
||||||
|
|
||||||
|
please read License Agreement
|
||||||
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
/* Counting semaphores for POSIX systems, built on a mutex and a condition
|
||||||
|
variable: unnamed POSIX semaphores are not available everywhere (macOS)
|
||||||
|
and have no timed wait there. Windows uses its own semaphores, see proxy.h. */
|
||||||
|
|
||||||
|
#include "proxy.h"
|
||||||
|
|
||||||
|
#ifndef _WIN32
|
||||||
|
/* macOS has CLOCK_MONOTONIC but no pthread_condattr_setclock(); a relative
|
||||||
|
wait is used there instead, which the system time does not affect either */
|
||||||
|
#if defined(CLOCK_MONOTONIC) && !defined(__APPLE__)
|
||||||
|
#define SEM_MONOTONIC
|
||||||
|
#endif
|
||||||
|
|
||||||
|
int _3proxy_sem_init_f(_3proxy_sem_t *sem, unsigned count, unsigned maxcount, int timed){
|
||||||
|
int res;
|
||||||
|
|
||||||
|
sem->count = count;
|
||||||
|
sem->maxcount = maxcount;
|
||||||
|
sem->monotonic = 0;
|
||||||
|
if(pthread_mutex_init(&sem->mutex, NULL)) return 1;
|
||||||
|
#ifdef SEM_MONOTONIC
|
||||||
|
if(timed){
|
||||||
|
pthread_condattr_t attr;
|
||||||
|
|
||||||
|
if(!pthread_condattr_init(&attr)){
|
||||||
|
if(!pthread_condattr_setclock(&attr, CLOCK_MONOTONIC)) sem->monotonic = 1;
|
||||||
|
res = pthread_cond_init(&sem->cond, &attr);
|
||||||
|
pthread_condattr_destroy(&attr);
|
||||||
|
}
|
||||||
|
else res = pthread_cond_init(&sem->cond, NULL);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
#endif
|
||||||
|
res = pthread_cond_init(&sem->cond, NULL);
|
||||||
|
if(res){
|
||||||
|
pthread_mutex_destroy(&sem->mutex);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
void _3proxy_sem_lock_f(_3proxy_sem_t *sem){
|
||||||
|
pthread_mutex_lock(&sem->mutex);
|
||||||
|
while(!sem->count) pthread_cond_wait(&sem->cond, &sem->mutex);
|
||||||
|
sem->count--;
|
||||||
|
pthread_mutex_unlock(&sem->mutex);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Returns 0 with the semaphore taken, nonzero if ms passed first. */
|
||||||
|
int _3proxy_sem_timedlock_f(_3proxy_sem_t *sem, unsigned ms){
|
||||||
|
struct timespec ts;
|
||||||
|
int res = 0;
|
||||||
|
|
||||||
|
#ifdef __APPLE__
|
||||||
|
ts.tv_sec = ms / 1000;
|
||||||
|
ts.tv_nsec = (long)(ms % 1000) * 1000000;
|
||||||
|
pthread_mutex_lock(&sem->mutex);
|
||||||
|
while(!sem->count && !res) res = pthread_cond_timedwait_relative_np(&sem->cond, &sem->mutex, &ts);
|
||||||
|
#else
|
||||||
|
/* the deadline is on the clock the condition variable was set up with */
|
||||||
|
#ifdef SEM_MONOTONIC
|
||||||
|
if(sem->monotonic) clock_gettime(CLOCK_MONOTONIC, &ts);
|
||||||
|
else
|
||||||
|
#endif
|
||||||
|
{
|
||||||
|
struct timeval tv;
|
||||||
|
|
||||||
|
gettimeofday(&tv, NULL);
|
||||||
|
ts.tv_sec = tv.tv_sec;
|
||||||
|
ts.tv_nsec = tv.tv_usec * 1000;
|
||||||
|
}
|
||||||
|
ts.tv_sec += ms / 1000;
|
||||||
|
ts.tv_nsec += (long)(ms % 1000) * 1000000;
|
||||||
|
if(ts.tv_nsec >= 1000000000){
|
||||||
|
ts.tv_sec++;
|
||||||
|
ts.tv_nsec -= 1000000000;
|
||||||
|
}
|
||||||
|
pthread_mutex_lock(&sem->mutex);
|
||||||
|
while(!sem->count && !res) res = pthread_cond_timedwait(&sem->cond, &sem->mutex, &ts);
|
||||||
|
#endif
|
||||||
|
if(sem->count){
|
||||||
|
sem->count--;
|
||||||
|
res = 0;
|
||||||
|
}
|
||||||
|
pthread_mutex_unlock(&sem->mutex);
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
void _3proxy_sem_unlock_f(_3proxy_sem_t *sem){
|
||||||
|
pthread_mutex_lock(&sem->mutex);
|
||||||
|
if(sem->count < sem->maxcount){
|
||||||
|
sem->count++;
|
||||||
|
pthread_cond_signal(&sem->cond);
|
||||||
|
}
|
||||||
|
pthread_mutex_unlock(&sem->mutex);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _3proxy_sem_destroy_f(_3proxy_sem_t *sem){
|
||||||
|
pthread_cond_destroy(&sem->cond);
|
||||||
|
pthread_mutex_destroy(&sem->mutex);
|
||||||
|
}
|
||||||
|
#endif
|
||||||
+15
-8
@@ -60,14 +60,21 @@ int sockrecvfrom(struct clientparam *param, SOCKET sock, struct sockaddr * sin,
|
|||||||
|
|
||||||
fds.fd = sock;
|
fds.fd = sock;
|
||||||
fds.events = POLLIN;
|
fds.events = POLLIN;
|
||||||
if(conf.timetoexit) return EOF;
|
for(;;){
|
||||||
res = param?param->srv->so._poll(param->sostate, &fds, 1, to):so._poll(so.state, &fds, 1, to);
|
if(conf.timetoexit) return EOF;
|
||||||
if (res<1) return 0;
|
res = param?param->srv->so._poll(param->sostate, &fds, 1, to):so._poll(so.state, &fds, 1, to);
|
||||||
sasize = sizeof(PROXYSOCKADDRTYPE);
|
if (res<1) return 0;
|
||||||
do {
|
sasize = sizeof(PROXYSOCKADDRTYPE);
|
||||||
res = param?param->srv->so._recvfrom(param->sostate, sock, (char *)buf, bufsize, 0, (struct sockaddr *)sin, &sasize):so._recvfrom(so.state, sock, (char *)buf, bufsize, 0, (struct sockaddr *)sin, &sasize);
|
/* sin NULL for a stream socket: nothing to learn the address into */
|
||||||
} while (res < 0 && (errno == EAGAIN || errno == EINTR));
|
do {
|
||||||
return res;
|
res = param?param->srv->so._recvfrom(param->sostate, sock, (char *)buf, bufsize, 0, (struct sockaddr *)sin, sin? &sasize : NULL):so._recvfrom(so.state, sock, (char *)buf, bufsize, 0, (struct sockaddr *)sin, sin? &sasize : NULL);
|
||||||
|
} while (res < 0 && errno == EINTR);
|
||||||
|
/* readable and still nothing to read: over TLS a record not yet
|
||||||
|
whole. Read again, without polling, it would only be the same until
|
||||||
|
the rest came, a loop taking all of a CPU and never timing out: the
|
||||||
|
socket is polled for it instead. */
|
||||||
|
if(res >= 0 || errno != EAGAIN) return res;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
int sockgetcharcli(struct clientparam * param, int timeosec, int timeousec){
|
int sockgetcharcli(struct clientparam * param, int timeosec, int timeousec){
|
||||||
|
|||||||
+197
-74
@@ -39,6 +39,18 @@ ssize_t splice(int fd_in, loff_t *off_in, int fd_out, loff_t *off_out, size_t le
|
|||||||
|
|
||||||
#define MAXSPLICE 65536
|
#define MAXSPLICE 65536
|
||||||
|
|
||||||
|
/* With SPLICE_AUTO, when a direction allowed to splice actually does
|
||||||
|
(without it, an allowed direction always does).
|
||||||
|
A body of known length is spliced if at least SPLICE_MIN of it is left
|
||||||
|
to read once what is already buffered is counted: a smaller one, or one
|
||||||
|
read whole with its headers, is cheaper to copy.
|
||||||
|
A stream of unknown length starts copied and is spliced after
|
||||||
|
SPLICE_STREAK reads in a row of at least SPLICE_MIN each, and goes back to
|
||||||
|
copying after SPLICE_STREAK+1 splices in a row of less than SPLICE_SMALL. */
|
||||||
|
#define SPLICE_MIN 16384
|
||||||
|
#define SPLICE_SMALL 4096
|
||||||
|
#define SPLICE_STREAK 2
|
||||||
|
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#define MIN(a,b) ((a>b)?b:a)
|
#define MIN(a,b) ((a>b)?b:a)
|
||||||
@@ -49,6 +61,31 @@ ssize_t splice(int fd_in, loff_t *off_in, int fd_out, loff_t *off_out, size_t le
|
|||||||
before the sockets are closed. */
|
before the sockets are closed. */
|
||||||
#define SESSIONEND (!halfclose && (CLIENTTERMREAD || SERVERTERMREAD))
|
#define SESSIONEND (!halfclose && (CLIENTTERMREAD || SERVERTERMREAD))
|
||||||
|
|
||||||
|
/* A hang-up on a socket there is data to write to. With poll() it comes
|
||||||
|
once both sides are shut down, and the write tried then fails, which ends
|
||||||
|
it. WSAPoll reports it as soon as the peer has half-closed, a peer still
|
||||||
|
reading, and keeps reporting it whether the socket has room or not: room
|
||||||
|
is waited for with select() then, up to timeo seconds. Returns whether to
|
||||||
|
try the write. */
|
||||||
|
static int hupwrite(SOCKET s, short revents, int timeo){
|
||||||
|
#ifdef _WIN32
|
||||||
|
if(!(revents & POLLOUT)){
|
||||||
|
fd_set wfd;
|
||||||
|
struct timeval tv;
|
||||||
|
|
||||||
|
FD_ZERO(&wfd);
|
||||||
|
FD_SET(s, &wfd);
|
||||||
|
tv.tv_sec = timeo;
|
||||||
|
tv.tv_usec = 0;
|
||||||
|
if(select(0, NULL, &wfd, NULL, &tv) < 1) return 0;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* usesplice is a mask of the directions passed with splice() rather than
|
||||||
|
through a buffer: SPLICE_DOWNLOAD, server to client, and SPLICE_UPLOAD,
|
||||||
|
client to server. */
|
||||||
int sockmap(struct clientparam * param, int timeo, int usesplice){
|
int sockmap(struct clientparam * param, int timeo, int usesplice){
|
||||||
int halfclose = param->srv->halfclose;
|
int halfclose = param->srv->halfclose;
|
||||||
uint64_t fromclient=0x7fffffffffffffff, fromserver =0x7fffffffffffffff;
|
uint64_t fromclient=0x7fffffffffffffff, fromserver =0x7fffffffffffffff;
|
||||||
@@ -60,13 +97,16 @@ int sockmap(struct clientparam * param, int timeo, int usesplice){
|
|||||||
#endif
|
#endif
|
||||||
int HASERROR=0;
|
int HASERROR=0;
|
||||||
int CLIENTTERMREAD = 0, CLIENTTERMWRITE = 0, SERVERTERMREAD = 0, SERVERTERMWRITE = 0;
|
int CLIENTTERMREAD = 0, CLIENTTERMWRITE = 0, SERVERTERMREAD = 0, SERVERTERMWRITE = 0;
|
||||||
|
/* the side has hung up: closed by the peer after its own was shut down */
|
||||||
|
int CLIENTHUP = 0, SERVERHUP = 0;
|
||||||
|
/* whether the side's socket is in this round's poll() */
|
||||||
|
int clipolled = 1, srvpolled = 1;
|
||||||
int after = 0;
|
int after = 0;
|
||||||
struct pollfd fds[8];
|
struct pollfd fds[8];
|
||||||
int fdsc = 0;
|
int fdsc = 0;
|
||||||
int sleeptime = 0;
|
int sleeptime = 0;
|
||||||
FILTER_ACTION action;
|
FILTER_ACTION action;
|
||||||
int res = 0;
|
int res = 0;
|
||||||
SASIZETYPE sasize;
|
|
||||||
int needaction = 0;
|
int needaction = 0;
|
||||||
int graceclinum=0, gracesrvnum=0, graceclitraf=0, gracesrvtraf=0;
|
int graceclinum=0, gracesrvnum=0, graceclitraf=0, gracesrvtraf=0;
|
||||||
time_t gracetime = 0;
|
time_t gracetime = 0;
|
||||||
@@ -76,16 +116,30 @@ int sockmap(struct clientparam * param, int timeo, int usesplice){
|
|||||||
#ifdef WITHSPLICE
|
#ifdef WITHSPLICE
|
||||||
uint64_t inclientpipe = 0, inserverpipe = 0;
|
uint64_t inclientpipe = 0, inserverpipe = 0;
|
||||||
int TOCLIENTPIPE = 0, FROMCLIENTPIPE = 0, TOSERVERPIPE = 0, FROMSERVERPIPE = 0;
|
int TOCLIENTPIPE = 0, FROMCLIENTPIPE = 0, TOSERVERPIPE = 0, FROMSERVERPIPE = 0;
|
||||||
int pipesrv[2] = {-1,-1};
|
/* The client's data goes through pipecli, the server's through pipesrv.
|
||||||
int pipecli[2] = {-1,-1};
|
They belong to the connection: made when first needed, kept for the
|
||||||
|
next mapping, closed with the connection. */
|
||||||
|
int *pipecli = param->pipecli, *pipesrv = param->pipesrv;
|
||||||
|
/* allowed to splice (-s), splicing now, and a run of reads counted
|
||||||
|
towards switching; wantbuf: go back to copying once the pipe is empty */
|
||||||
|
int allowcli = 0, allowsrv = 0, splicecli = 0, splicesrv = 0, autosplice;
|
||||||
|
int streakcli = 0, streaksrv = 0, wantbufcli = 0, wantbufsrv = 0;
|
||||||
|
|
||||||
if((!param->nolongdatfilter && (param->ndatfilterscli > 0 || param->ndatfilterssrv))) usesplice = 0;
|
if((!param->nolongdatfilter && (param->ndatfilterscli > 0 || param->ndatfilterssrv))) usesplice = 0;
|
||||||
if(usesplice){
|
allowcli = (usesplice & SPLICE_UPLOAD) != 0;
|
||||||
TOCLIENTPIPE = FROMCLIENTPIPE = TOSERVERPIPE = FROMSERVERPIPE = 1;
|
allowsrv = (usesplice & SPLICE_DOWNLOAD) != 0;
|
||||||
TOCLIENTBUF = TOSERVERBUF = 0;
|
autosplice = (usesplice & SPLICE_AUTO) != 0;
|
||||||
if(pipe2(pipecli, O_NONBLOCK) < 0) RETURN (21);
|
if(!autosplice){
|
||||||
if(pipe2(pipesrv, O_NONBLOCK) < 0) RETURN (21);
|
splicecli = allowcli;
|
||||||
|
splicesrv = allowsrv;
|
||||||
}
|
}
|
||||||
|
TOCLIENTPIPE = FROMCLIENTPIPE = allowcli;
|
||||||
|
TOSERVERPIPE = FROMSERVERPIPE = allowsrv;
|
||||||
|
#else
|
||||||
|
#define splicecli 0
|
||||||
|
#define splicesrv 0
|
||||||
|
#define wantbufcli 0
|
||||||
|
#define wantbufsrv 0
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
inserverbuf = param->srvinbuf - param->srvoffset;
|
inserverbuf = param->srvinbuf - param->srvoffset;
|
||||||
@@ -108,16 +162,16 @@ int sockmap(struct clientparam * param, int timeo, int usesplice){
|
|||||||
if(inserverbuf >= fromserver) FROMSERVER = 0;
|
if(inserverbuf >= fromserver) FROMSERVER = 0;
|
||||||
if(inclientbuf >= fromclient) FROMCLIENT = 0;
|
if(inclientbuf >= fromclient) FROMCLIENT = 0;
|
||||||
#ifdef WITHSPLICE
|
#ifdef WITHSPLICE
|
||||||
if(!usesplice)
|
/* a body of known length large enough is spliced from the start */
|
||||||
|
if(autosplice && allowsrv && param->waitserver64 && fromserver > inserverbuf && fromserver - inserverbuf >= SPLICE_MIN) splicesrv = 1;
|
||||||
|
if(autosplice && allowcli && param->waitclient64 && fromclient > inclientbuf && fromclient - inclientbuf >= SPLICE_MIN) splicecli = 1;
|
||||||
#endif
|
#endif
|
||||||
{
|
/* a spliced direction needs no buffer, only what was read before */
|
||||||
if(fromserver && !param->srvbuf && (!(param->srvbuf=malloc(SRVBUFSIZE)) || !(param->srvbufsize = SRVBUFSIZE))){
|
if(!splicesrv && fromserver && !param->srvbuf && (!(param->srvbuf=malloc(SRVBUFSIZE)) || !(param->srvbufsize = SRVBUFSIZE))){
|
||||||
RETURN (21);
|
RETURN (21);
|
||||||
}
|
}
|
||||||
if(fromclient && !param->clibuf && (!(param->clibuf=malloc(SRVBUFSIZE)) || !(param->clibufsize = SRVBUFSIZE))){
|
if(!splicecli && fromclient && !param->clibuf && (!(param->clibuf=malloc(SRVBUFSIZE)) || !(param->clibufsize = SRVBUFSIZE))){
|
||||||
RETURN (21);
|
RETURN (21);
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
if(param->srvinbuf == param->srvoffset) param->srvinbuf =param->srvoffset = 0;
|
if(param->srvinbuf == param->srvoffset) param->srvinbuf =param->srvoffset = 0;
|
||||||
if(param->cliinbuf == param->clioffset) param->cliinbuf =param->clioffset = 0;
|
if(param->cliinbuf == param->clioffset) param->cliinbuf =param->clioffset = 0;
|
||||||
@@ -220,8 +274,9 @@ log("send to server from buf");
|
|||||||
param->clioffset = param->cliinbuf = 0;
|
param->clioffset = param->cliinbuf = 0;
|
||||||
if(fromclient) TOCLIENTBUF = 1;
|
if(fromclient) TOCLIENTBUF = 1;
|
||||||
}
|
}
|
||||||
sasize = SASIZE(¶m->sinsr);
|
/* a connected stream: no address, which a Unix socket on Linux
|
||||||
res = param->srv->so._sendto(param->sostate, param->remsock, (char *)param->clibuf + param->clioffset, (int)MIN(inclientbuf, fromclient), 0, (struct sockaddr*)¶m->sinsr, sasize);
|
would refuse */
|
||||||
|
res = param->srv->so._sendto(param->sostate, param->remsock, (char *)param->clibuf + param->clioffset, (int)MIN(inclientbuf, fromclient), 0, NULL, 0);
|
||||||
if(res <= 0) {
|
if(res <= 0) {
|
||||||
TOSERVER = 0;
|
TOSERVER = 0;
|
||||||
if(errno && errno != EAGAIN && errno != EINTR){
|
if(errno && errno != EAGAIN && errno != EINTR){
|
||||||
@@ -267,8 +322,7 @@ log("send to client from buf");
|
|||||||
if(fromserver) TOSERVERBUF = 1;
|
if(fromserver) TOSERVERBUF = 1;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
sasize = SASIZE(¶m->sincr);
|
res = param->srv->so._sendto(param->sostate, param->clisock, (char *)param->srvbuf + param->srvoffset, (int)MIN(inserverbuf,fromserver), 0, NULL, 0);
|
||||||
res = param->srv->so._sendto(param->sostate, param->clisock, (char *)param->srvbuf + param->srvoffset, (int)MIN(inserverbuf,fromserver), 0, (struct sockaddr*)¶m->sincr, sasize);
|
|
||||||
if(res <= 0) {
|
if(res <= 0) {
|
||||||
TOCLIENT = 0;
|
TOCLIENT = 0;
|
||||||
if(errno && errno != EAGAIN && errno != EINTR){
|
if(errno && errno != EAGAIN && errno != EINTR){
|
||||||
@@ -292,8 +346,21 @@ log("done send to client from buf");
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
#ifdef WITHSPLICE
|
#ifdef WITHSPLICE
|
||||||
if(usesplice){
|
/* a direction going back to copying does once its pipe is empty */
|
||||||
if(inclientpipe && !inclientbuf && FROMCLIENTPIPE && TOSERVER){
|
if(wantbufcli && !inclientpipe){
|
||||||
|
splicecli = wantbufcli = streakcli = 0;
|
||||||
|
if(!param->clibuf && (!(param->clibuf=malloc(SRVBUFSIZE)) || !(param->clibufsize = SRVBUFSIZE))) RETURN (21);
|
||||||
|
if(param->cliinbuf < param->clibufsize) TOCLIENTBUF = 1;
|
||||||
|
}
|
||||||
|
if(wantbufsrv && !inserverpipe){
|
||||||
|
splicesrv = wantbufsrv = streaksrv = 0;
|
||||||
|
if(!param->srvbuf && (!(param->srvbuf=malloc(SRVBUFSIZE)) || !(param->srvbufsize = SRVBUFSIZE))) RETURN (21);
|
||||||
|
if(param->srvinbuf < param->srvbufsize) TOSERVERBUF = 1;
|
||||||
|
}
|
||||||
|
{
|
||||||
|
/* each direction goes through its pipe if spliced, through its
|
||||||
|
buffer otherwise; what was in the buffer before is sent first */
|
||||||
|
if(splicecli && inclientpipe && !inclientbuf && FROMCLIENTPIPE && TOSERVER){
|
||||||
#ifdef WITHLOG
|
#ifdef WITHLOG
|
||||||
log("send to server from pipe");
|
log("send to server from pipe");
|
||||||
#endif
|
#endif
|
||||||
@@ -330,7 +397,7 @@ log(logbuf);
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if(inserverpipe && !inserverbuf && FROMSERVERPIPE && TOCLIENT){
|
if(splicesrv && inserverpipe && !inserverbuf && FROMSERVERPIPE && TOCLIENT){
|
||||||
#ifdef WITHLOG
|
#ifdef WITHLOG
|
||||||
log("send to client from pipe");
|
log("send to client from pipe");
|
||||||
#endif
|
#endif
|
||||||
@@ -360,12 +427,17 @@ log(logbuf);
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if(fromclient>inclientpipe && FROMCLIENT && TOCLIENTPIPE && !SESSIONEND){
|
if(splicecli && !wantbufcli && fromclient>inclientpipe && FROMCLIENT && TOCLIENTPIPE && !SESSIONEND){
|
||||||
int error;
|
|
||||||
socklen_t len=sizeof(error);
|
|
||||||
#ifdef WITHLOG
|
#ifdef WITHLOG
|
||||||
log("read from client to pipe");
|
log("read from client to pipe");
|
||||||
#endif
|
#endif
|
||||||
|
if(pipecli[0] < 0 && pipe2(pipecli, O_NONBLOCK) < 0){
|
||||||
|
/* no pipe to be had: copy instead */
|
||||||
|
allowcli = splicecli = TOCLIENTPIPE = FROMCLIENTPIPE = 0;
|
||||||
|
if(!param->clibuf && (!(param->clibuf=malloc(SRVBUFSIZE)) || !(param->clibufsize = SRVBUFSIZE))) RETURN (21);
|
||||||
|
if(param->cliinbuf < param->clibufsize) TOCLIENTBUF = 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
errno = 0;
|
errno = 0;
|
||||||
res = splice(param->clisock, NULL, pipecli[1], NULL, (int)MIN((uint64_t)MAXSPLICE - inclientpipe, (uint64_t)fromclient-inclientpipe), SPLICE_F_NONBLOCK|SPLICE_F_MOVE);
|
res = splice(param->clisock, NULL, pipecli[1], NULL, (int)MIN((uint64_t)MAXSPLICE - inclientpipe, (uint64_t)fromclient-inclientpipe), SPLICE_F_NONBLOCK|SPLICE_F_MOVE);
|
||||||
#ifdef WITHLOG
|
#ifdef WITHLOG
|
||||||
@@ -396,19 +468,27 @@ log("done read from client to pipe");
|
|||||||
graceclinum++;
|
graceclinum++;
|
||||||
graceclitraf += res;
|
graceclitraf += res;
|
||||||
gracesrvnum = gracesrvtraf = 0;
|
gracesrvnum = gracesrvtraf = 0;
|
||||||
|
if(autosplice && !param->waitclient64){
|
||||||
|
if(res >= SPLICE_SMALL) streakcli = 0;
|
||||||
|
else if(++streakcli > SPLICE_STREAK) wantbufcli = 1;
|
||||||
|
}
|
||||||
inclientpipe += res;
|
inclientpipe += res;
|
||||||
if(inclientpipe >= MAXSPLICE) TOCLIENTPIPE = 0;
|
if(inclientpipe >= MAXSPLICE) TOCLIENTPIPE = 0;
|
||||||
needaction = 0;
|
needaction = 0;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if(fromserver > inserverpipe && FROMSERVER && TOSERVERPIPE && !SESSIONEND){
|
if(splicesrv && !wantbufsrv && fromserver > inserverpipe && FROMSERVER && TOSERVERPIPE && !SESSIONEND){
|
||||||
int error;
|
|
||||||
socklen_t len=sizeof(error);
|
|
||||||
errno = 0;
|
|
||||||
#ifdef WITHLOG
|
#ifdef WITHLOG
|
||||||
log("read from server to pipe\n");
|
log("read from server to pipe\n");
|
||||||
#endif
|
#endif
|
||||||
|
if(pipesrv[0] < 0 && pipe2(pipesrv, O_NONBLOCK) < 0){
|
||||||
|
allowsrv = splicesrv = TOSERVERPIPE = FROMSERVERPIPE = 0;
|
||||||
|
if(!param->srvbuf && (!(param->srvbuf=malloc(SRVBUFSIZE)) || !(param->srvbufsize = SRVBUFSIZE))) RETURN (21);
|
||||||
|
if(param->srvinbuf < param->srvbufsize) TOSERVERBUF = 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
errno = 0;
|
||||||
res = splice(param->remsock, NULL, pipesrv[1], NULL, MIN(MAXSPLICE - inserverpipe, fromserver - inserverpipe), SPLICE_F_NONBLOCK|SPLICE_F_MOVE);
|
res = splice(param->remsock, NULL, pipesrv[1], NULL, MIN(MAXSPLICE - inserverpipe, fromserver - inserverpipe), SPLICE_F_NONBLOCK|SPLICE_F_MOVE);
|
||||||
#ifdef WITHLOG
|
#ifdef WITHLOG
|
||||||
log("server to pipe splice finished\n");
|
log("server to pipe splice finished\n");
|
||||||
@@ -438,6 +518,10 @@ log("done read from server to pipe\n");
|
|||||||
gracesrvnum++;
|
gracesrvnum++;
|
||||||
gracesrvtraf += res;
|
gracesrvtraf += res;
|
||||||
graceclinum = graceclitraf = 0;
|
graceclinum = graceclitraf = 0;
|
||||||
|
if(autosplice && !param->waitserver64){
|
||||||
|
if(res >= SPLICE_SMALL) streaksrv = 0;
|
||||||
|
else if(++streaksrv > SPLICE_STREAK) wantbufsrv = 1;
|
||||||
|
}
|
||||||
param->nreads++;
|
param->nreads++;
|
||||||
param->statssrv64 += res;
|
param->statssrv64 += res;
|
||||||
inserverpipe += res;
|
inserverpipe += res;
|
||||||
@@ -452,15 +536,15 @@ log("done read from server to pipe\n");
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else
|
|
||||||
#endif
|
#endif
|
||||||
{
|
{
|
||||||
if(fromclient > inclientbuf && FROMCLIENT && TOCLIENTBUF && !SESSIONEND){
|
if(!splicecli && fromclient > inclientbuf && FROMCLIENT && TOCLIENTBUF && !SESSIONEND){
|
||||||
#ifdef WITHLOG
|
#ifdef WITHLOG
|
||||||
log("read from client to buf");
|
log("read from client to buf");
|
||||||
#endif
|
#endif
|
||||||
sasize = sizeof(param->sincr);
|
/* no address: it would overwrite the client's with what a
|
||||||
res = param->srv->so._recvfrom(param->sostate, param->clisock, (char *)param->clibuf + param->cliinbuf, (int)MIN((uint64_t)param->clibufsize - param->cliinbuf, fromclient-inclientbuf), 0, (struct sockaddr *)¶m->sincr, &sasize);
|
stream socket gives, an empty one for a Unix socket */
|
||||||
|
res = param->srv->so._recvfrom(param->sostate, param->clisock, (char *)param->clibuf + param->cliinbuf, (int)MIN((uint64_t)param->clibufsize - param->cliinbuf, fromclient-inclientbuf), 0, NULL, NULL);
|
||||||
if(res <= 0) {
|
if(res <= 0) {
|
||||||
FROMCLIENT = 0;
|
FROMCLIENT = 0;
|
||||||
if(res == 0) {
|
if(res == 0) {
|
||||||
@@ -480,6 +564,17 @@ log("done read from client to buf");
|
|||||||
graceclinum++;
|
graceclinum++;
|
||||||
graceclitraf += res;
|
graceclitraf += res;
|
||||||
gracesrvnum = gracesrvtraf = 0;
|
gracesrvnum = gracesrvtraf = 0;
|
||||||
|
#ifdef WITHSPLICE
|
||||||
|
if(autosplice && allowcli && !param->waitclient64){
|
||||||
|
if(res < SPLICE_MIN) streakcli = 0;
|
||||||
|
else if(++streakcli >= SPLICE_STREAK){
|
||||||
|
/* a stream: splice from now on, after what is
|
||||||
|
buffered has been sent */
|
||||||
|
splicecli = TOCLIENTPIPE = FROMCLIENTPIPE = 1;
|
||||||
|
streakcli = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endif
|
||||||
inclientbuf += res;
|
inclientbuf += res;
|
||||||
param->cliinbuf += res;
|
param->cliinbuf += res;
|
||||||
if(param->clibufsize == param->cliinbuf) TOCLIENTBUF = 0;
|
if(param->clibufsize == param->cliinbuf) TOCLIENTBUF = 0;
|
||||||
@@ -488,12 +583,11 @@ log("done read from client to buf");
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if(fromserver > inserverbuf && FROMSERVER && TOSERVERBUF && !SESSIONEND){
|
if(!splicesrv && fromserver > inserverbuf && FROMSERVER && TOSERVERBUF && !SESSIONEND){
|
||||||
#ifdef WITHLOG
|
#ifdef WITHLOG
|
||||||
log("read from server to buf");
|
log("read from server to buf");
|
||||||
#endif
|
#endif
|
||||||
sasize = sizeof(param->sinsr);
|
res = param->srv->so._recvfrom(param->sostate, param->remsock, (char *)param->srvbuf + param->srvinbuf, (int)MIN((uint64_t)param->srvbufsize - param->srvinbuf, fromserver-inserverbuf), 0, NULL, NULL);
|
||||||
res = param->srv->so._recvfrom(param->sostate, param->remsock, (char *)param->srvbuf + param->srvinbuf, (int)MIN((uint64_t)param->srvbufsize - param->srvinbuf, fromserver-inserverbuf), 0, (struct sockaddr *)¶m->sinsr, &sasize);
|
|
||||||
if(res <= 0) {
|
if(res <= 0) {
|
||||||
FROMSERVER = 0;
|
FROMSERVER = 0;
|
||||||
if(res == 0) {
|
if(res == 0) {
|
||||||
@@ -513,6 +607,15 @@ log("done read from server to buf");
|
|||||||
gracesrvnum++;
|
gracesrvnum++;
|
||||||
gracesrvtraf += res;
|
gracesrvtraf += res;
|
||||||
graceclinum = graceclitraf = 0;
|
graceclinum = graceclitraf = 0;
|
||||||
|
#ifdef WITHSPLICE
|
||||||
|
if(autosplice && allowsrv && !param->waitserver64){
|
||||||
|
if(res < SPLICE_MIN) streaksrv = 0;
|
||||||
|
else if(++streaksrv >= SPLICE_STREAK){
|
||||||
|
splicesrv = TOSERVERPIPE = FROMSERVERPIPE = 1;
|
||||||
|
streaksrv = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endif
|
||||||
param->nreads++;
|
param->nreads++;
|
||||||
param->statssrv64 += res;
|
param->statssrv64 += res;
|
||||||
inserverbuf += res;
|
inserverbuf += res;
|
||||||
@@ -553,15 +656,8 @@ log("done read from server to buf");
|
|||||||
// if(!CLIENTTERMREAD || !CLIENTTERMWRITE){
|
// if(!CLIENTTERMREAD || !CLIENTTERMWRITE){
|
||||||
if(!after){
|
if(!after){
|
||||||
fds[fdsc].fd = param->clisock;
|
fds[fdsc].fd = param->clisock;
|
||||||
if(fromclient && !CLIENTTERMREAD && !FROMCLIENT && !SESSIONEND && ((
|
if(fromclient && !CLIENTTERMREAD && !FROMCLIENT && !SESSIONEND &&
|
||||||
#ifdef WITHSPLICE
|
((!splicecli && TOCLIENTBUF) || (splicecli && !wantbufcli)))
|
||||||
!usesplice &&
|
|
||||||
#endif
|
|
||||||
TOCLIENTBUF)
|
|
||||||
#ifdef WITHSPLICE
|
|
||||||
|| (usesplice)
|
|
||||||
#endif
|
|
||||||
))
|
|
||||||
cli_events |= POLLIN;
|
cli_events |= POLLIN;
|
||||||
if(!TOCLIENT && !CLIENTTERMWRITE && (inserverbuf
|
if(!TOCLIENT && !CLIENTTERMWRITE && (inserverbuf
|
||||||
#ifdef WITHSPLICE
|
#ifdef WITHSPLICE
|
||||||
@@ -569,6 +665,11 @@ log("done read from server to buf");
|
|||||||
#endif
|
#endif
|
||||||
))
|
))
|
||||||
cli_events |= POLLOUT;
|
cli_events |= POLLOUT;
|
||||||
|
/* poll() reports a hang-up whatever is asked, and would
|
||||||
|
return at once every time: the socket is left out then,
|
||||||
|
rather than given as an invalid one, which WSAPoll takes
|
||||||
|
for an error */
|
||||||
|
clipolled = cli_events || !CLIENTHUP;
|
||||||
if(cli_events){
|
if(cli_events){
|
||||||
fds[fdsc].fd = param->clisock;
|
fds[fdsc].fd = param->clisock;
|
||||||
fds[fdsc].events = cli_events;
|
fds[fdsc].events = cli_events;
|
||||||
@@ -580,6 +681,8 @@ log("wait writing to client");
|
|||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
else if(!clipolled){
|
||||||
|
}
|
||||||
else if(cli_events){
|
else if(cli_events){
|
||||||
if(fds[fdsc].revents & (POLLERR|POLLNVAL)) {
|
if(fds[fdsc].revents & (POLLERR|POLLNVAL)) {
|
||||||
CLIENTTERMREAD = 1;
|
CLIENTTERMREAD = 1;
|
||||||
@@ -601,27 +704,27 @@ log("ready to write to client");
|
|||||||
}
|
}
|
||||||
if(fds[fdsc].revents & (POLLHUP)) {
|
if(fds[fdsc].revents & (POLLHUP)) {
|
||||||
if(fds[fdsc].events & POLLIN) FROMCLIENT = 1;
|
if(fds[fdsc].events & POLLIN) FROMCLIENT = 1;
|
||||||
if(fds[fdsc].events & POLLOUT) CLIENTTERMWRITE = 1;
|
if(fds[fdsc].events & POLLOUT){
|
||||||
|
if(hupwrite(param->clisock, fds[fdsc].revents, timeo)) TOCLIENT = 1;
|
||||||
|
else CLIENTTERMWRITE = 1;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else if(fds[fdsc].revents & (POLLERR|POLLNVAL|POLLHUP)) {
|
} else if(fds[fdsc].revents & (POLLERR|POLLNVAL)) {
|
||||||
CLIENTTERMREAD = 1;
|
CLIENTTERMREAD = 1;
|
||||||
CLIENTTERMWRITE = 1;
|
CLIENTTERMWRITE = 1;
|
||||||
|
} else if(fds[fdsc].revents & POLLHUP) {
|
||||||
|
/* what the client sent before it closed is still to be
|
||||||
|
read, once the buffer has room for it */
|
||||||
|
CLIENTHUP = 1;
|
||||||
}
|
}
|
||||||
fdsc++;
|
if(clipolled) fdsc++;
|
||||||
|
|
||||||
// if(!SERVERTERMREAD || !SERVERTERMWRITE){
|
// if(!SERVERTERMREAD || !SERVERTERMWRITE){
|
||||||
if(!after){
|
if(!after){
|
||||||
fds[fdsc].fd = param->remsock;
|
fds[fdsc].fd = param->remsock;
|
||||||
if(fromserver && !SERVERTERMREAD && !FROMSERVER && !SESSIONEND && ((
|
if(fromserver && !SERVERTERMREAD && !FROMSERVER && !SESSIONEND &&
|
||||||
#ifdef WITHSPLICE
|
((!splicesrv && TOSERVERBUF) || (splicesrv && !wantbufsrv)))
|
||||||
!usesplice &&
|
|
||||||
#endif
|
|
||||||
TOSERVERBUF)
|
|
||||||
#ifdef WITHSPLICE
|
|
||||||
|| (usesplice)
|
|
||||||
#endif
|
|
||||||
))
|
|
||||||
srv_events |= POLLIN;
|
srv_events |= POLLIN;
|
||||||
if(!TOSERVER && !SERVERTERMWRITE && (inclientbuf
|
if(!TOSERVER && !SERVERTERMWRITE && (inclientbuf
|
||||||
#ifdef WITHSPLICE
|
#ifdef WITHSPLICE
|
||||||
@@ -629,6 +732,7 @@ log("ready to write to client");
|
|||||||
#endif
|
#endif
|
||||||
))
|
))
|
||||||
srv_events |= POLLOUT;
|
srv_events |= POLLOUT;
|
||||||
|
srvpolled = srv_events || !SERVERHUP;
|
||||||
if(srv_events){
|
if(srv_events){
|
||||||
fds[fdsc].fd = param->remsock;
|
fds[fdsc].fd = param->remsock;
|
||||||
fds[fdsc].events = srv_events;
|
fds[fdsc].events = srv_events;
|
||||||
@@ -640,6 +744,8 @@ log("wait writing from server");
|
|||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
else if(!srvpolled){
|
||||||
|
}
|
||||||
else if(srv_events){
|
else if(srv_events){
|
||||||
if(fds[fdsc].revents & (POLLERR|POLLNVAL)) {
|
if(fds[fdsc].revents & (POLLERR|POLLNVAL)) {
|
||||||
#ifdef WITHLOG
|
#ifdef WITHLOG
|
||||||
@@ -668,18 +774,24 @@ log("ready to write to server");
|
|||||||
log("server terminated connection");
|
log("server terminated connection");
|
||||||
#endif
|
#endif
|
||||||
if(fds[fdsc].events & POLLIN) FROMSERVER = 1;
|
if(fds[fdsc].events & POLLIN) FROMSERVER = 1;
|
||||||
if(fds[fdsc].events & POLLOUT) SERVERTERMWRITE = 1;
|
if(fds[fdsc].events & POLLOUT){
|
||||||
|
if(hupwrite(param->remsock, fds[fdsc].revents, timeo)) TOSERVER = 1;
|
||||||
|
else SERVERTERMWRITE = 1;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else if(fds[fdsc].revents & (POLLERR|POLLNVAL|POLLHUP)) {
|
} else if(fds[fdsc].revents & (POLLERR|POLLNVAL)) {
|
||||||
SERVERTERMREAD = 1;
|
SERVERTERMREAD = 1;
|
||||||
SERVERTERMWRITE = 1;
|
SERVERTERMWRITE = 1;
|
||||||
|
} else if(fds[fdsc].revents & POLLHUP) {
|
||||||
|
/* the rest of the answer may still be waiting to be read */
|
||||||
|
SERVERHUP = 1;
|
||||||
}
|
}
|
||||||
fdsc++;
|
if(srvpolled) fdsc++;
|
||||||
// }
|
// }
|
||||||
#ifdef WITHSPLICE
|
#ifdef WITHSPLICE
|
||||||
if(usesplice){
|
{
|
||||||
if(fromclient>inclientpipe && !TOCLIENTPIPE && inclientpipe < MAXSPLICE){
|
if(splicecli && fromclient>inclientpipe && !TOCLIENTPIPE && inclientpipe < MAXSPLICE){
|
||||||
if(!after){
|
if(!after){
|
||||||
#ifdef WITHLOG
|
#ifdef WITHLOG
|
||||||
log("wait writing to client pipe");
|
log("wait writing to client pipe");
|
||||||
@@ -700,7 +812,7 @@ log("ready to write to client pipe");
|
|||||||
}
|
}
|
||||||
fdsc++;
|
fdsc++;
|
||||||
}
|
}
|
||||||
if(inclientpipe && !FROMCLIENTPIPE){
|
if(splicecli && inclientpipe && !FROMCLIENTPIPE){
|
||||||
if(!after){
|
if(!after){
|
||||||
#ifdef WITHLOG
|
#ifdef WITHLOG
|
||||||
log("wait reading from client pipe");
|
log("wait reading from client pipe");
|
||||||
@@ -719,7 +831,7 @@ log("ready reading from client pipe");
|
|||||||
}
|
}
|
||||||
fdsc++;
|
fdsc++;
|
||||||
}
|
}
|
||||||
if(fromserver>inserverpipe && !TOSERVERPIPE && inserverpipe < MAXSPLICE){
|
if(splicesrv && fromserver>inserverpipe && !TOSERVERPIPE && inserverpipe < MAXSPLICE){
|
||||||
if(!after){
|
if(!after){
|
||||||
#ifdef WITHLOG
|
#ifdef WITHLOG
|
||||||
log("wait writing to server pipe");
|
log("wait writing to server pipe");
|
||||||
@@ -738,7 +850,7 @@ log("ready writing to server pipe");
|
|||||||
}
|
}
|
||||||
fdsc++;
|
fdsc++;
|
||||||
}
|
}
|
||||||
if(inserverpipe && !FROMSERVERPIPE){
|
if(splicesrv && inserverpipe && !FROMSERVERPIPE){
|
||||||
if(!after){
|
if(!after){
|
||||||
#ifdef WITHLOG
|
#ifdef WITHLOG
|
||||||
log("wait reading from server pipe");
|
log("wait reading from server pipe");
|
||||||
@@ -819,18 +931,29 @@ log("timeout");
|
|||||||
else if(inclientpipe || inserverpipe) res = 94;
|
else if(inclientpipe || inserverpipe) res = 94;
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
if((param->nwrites > 0 && !SERVERTERMWRITE) || (param->nreads > 0 && !CLIENTTERMWRITE))
|
|
||||||
usleep(SLEEPTIME * 10);
|
|
||||||
|
|
||||||
CLEANRET:
|
CLEANRET:
|
||||||
|
|
||||||
#ifdef WITHSPLICE
|
#ifdef WITHSPLICE
|
||||||
if(pipecli[0] >= 0) close(pipecli[0]);
|
/* empty pipes stay with the connection for its next mapping; one still
|
||||||
if(pipecli[1] >= 0) close(pipecli[1]);
|
holding data, left by an error or a timeout, cannot be used again */
|
||||||
if(pipesrv[0] >= 0) close(pipesrv[0]);
|
if(inclientpipe && pipecli[0] >= 0){
|
||||||
if(pipesrv[1] >= 0) close(pipesrv[1]);
|
close(pipecli[0]);
|
||||||
|
close(pipecli[1]);
|
||||||
|
pipecli[0] = pipecli[1] = -1;
|
||||||
|
}
|
||||||
|
if(inserverpipe && pipesrv[0] >= 0){
|
||||||
|
close(pipesrv[0]);
|
||||||
|
close(pipesrv[1]);
|
||||||
|
pipesrv[0] = pipesrv[1] = -1;
|
||||||
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
return res;
|
return res;
|
||||||
}
|
}
|
||||||
#undef SESSIONEND
|
#undef SESSIONEND
|
||||||
|
#ifndef WITHSPLICE
|
||||||
|
#undef splicecli
|
||||||
|
#undef splicesrv
|
||||||
|
#undef wantbufcli
|
||||||
|
#undef wantbufsrv
|
||||||
|
#endif
|
||||||
+14
-9
@@ -184,7 +184,7 @@ void * sockschild(struct clientparam* param) {
|
|||||||
param->operation = command == 2?BIND:UDPASSOC;
|
param->operation = command == 2?BIND:UDPASSOC;
|
||||||
if(command == 2){
|
if(command == 2){
|
||||||
if ((param->remsock=param->srv->so._socket(param->sostate, SASOCK(¶m->req), SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET) {RETURN (11);}
|
if ((param->remsock=param->srv->so._socket(param->sostate, SASOCK(¶m->req), SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET) {RETURN (11);}
|
||||||
setopts(param->remsock, param->srv->lissockopts);
|
setopts(param->remsock, ¶m->srv->lissockopts);
|
||||||
if(extbindtodevice(param, param->remsock)) {RETURN (12);}
|
if(extbindtodevice(param, param->remsock)) {RETURN (12);}
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
@@ -230,7 +230,7 @@ fprintf(stderr, "%hu bound to communicate with server\n", *SAPORT(¶m->sinsl)
|
|||||||
fflush(stderr);
|
fflush(stderr);
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
sasize = SASIZE(¶m->sinsl);
|
sasize = sizeof(param->sinsl);
|
||||||
param->srv->so._getsockname(param->sostate, param->remsock, (struct sockaddr *)¶m->sinsl, &sasize);
|
param->srv->so._getsockname(param->sostate, param->remsock, (struct sockaddr *)¶m->sinsl, &sasize);
|
||||||
}
|
}
|
||||||
if(command == 3) {
|
if(command == 3) {
|
||||||
@@ -250,7 +250,7 @@ fflush(stderr);
|
|||||||
*SAPORT(&sin) = 0;
|
*SAPORT(&sin) = 0;
|
||||||
/* the port the client is told to send its datagrams to */
|
/* the port the client is told to send its datagrams to */
|
||||||
if(bindwithrange(param, param->clisock, &sin, param->intport)) {RETURN (12);}
|
if(bindwithrange(param, param->clisock, &sin, param->intport)) {RETURN (12);}
|
||||||
sasize = SASIZE(&sin);
|
sasize = sizeof(sin);
|
||||||
param->srv->so._getsockname(param->sostate, param->clisock, (struct sockaddr *)&sin, &sasize);
|
param->srv->so._getsockname(param->sostate, param->clisock, (struct sockaddr *)&sin, &sasize);
|
||||||
#if SOCKSTRACE > 0
|
#if SOCKSTRACE > 0
|
||||||
fprintf(stderr, "%hu binded to communicate with client\n",
|
fprintf(stderr, "%hu binded to communicate with client\n",
|
||||||
@@ -272,12 +272,17 @@ CLEANRET:
|
|||||||
int repcode;
|
int repcode;
|
||||||
|
|
||||||
sasize = sizeof(sin);
|
sasize = sizeof(sin);
|
||||||
if(command != 3 && param->remsock != INVALID_SOCKET) param->srv->so._getsockname(param->sostate, param->remsock, (struct sockaddr *)&sin, &sasize);
|
/* CONNECT and BIND report the address of the socket towards the
|
||||||
if(command != 3 && !SAISNULL(¶m->srv->extNat)){
|
destination, UDP ASSOCIATE the one the client sends its datagrams
|
||||||
uint16_t port;
|
to, as does a request which never got a socket of its own */
|
||||||
port = *SAPORT(&sin);
|
if(command != 3 && param->remsock != INVALID_SOCKET){
|
||||||
sin = param->srv->extNat;
|
param->srv->so._getsockname(param->sostate, param->remsock, (struct sockaddr *)&sin, &sasize);
|
||||||
*SAPORT(&sin) = port;
|
if(!SAISNULL(¶m->srv->extNat)){
|
||||||
|
uint16_t port;
|
||||||
|
port = *SAPORT(&sin);
|
||||||
|
sin = param->srv->extNat;
|
||||||
|
*SAPORT(&sin) = port;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
param->srv->so._getsockname(param->sostate, param->clisock, (struct sockaddr *)&sin, &sasize);
|
param->srv->so._getsockname(param->sostate, param->clisock, (struct sockaddr *)&sin, &sasize);
|
||||||
|
|||||||
@@ -74,6 +74,9 @@ static int client_mode = 0;
|
|||||||
struct SSLsock {
|
struct SSLsock {
|
||||||
SOCKET s;
|
SOCKET s;
|
||||||
SSL_CONN conn;
|
SSL_CONN conn;
|
||||||
|
/* what a read and a write which could not be done wait for, POLLIN
|
||||||
|
or POLLOUT, 0 once one is: TLS may have to write to read */
|
||||||
|
short rwant, wwant;
|
||||||
};
|
};
|
||||||
|
|
||||||
struct SSLstate {
|
struct SSLstate {
|
||||||
@@ -102,10 +105,12 @@ static void addSSL(
|
|||||||
if (cli_s != INVALID_SOCKET){
|
if (cli_s != INVALID_SOCKET){
|
||||||
SOSTATE->cli.s = cli_s;
|
SOSTATE->cli.s = cli_s;
|
||||||
SOSTATE->cli.conn = cli_conn;
|
SOSTATE->cli.conn = cli_conn;
|
||||||
|
SOSTATE->cli.rwant = SOSTATE->cli.wwant = 0;
|
||||||
}
|
}
|
||||||
if (srv_s != INVALID_SOCKET){
|
if (srv_s != INVALID_SOCKET){
|
||||||
SOSTATE->srv.s = srv_s;
|
SOSTATE->srv.s = srv_s;
|
||||||
SOSTATE->srv.conn = srv_conn;
|
SOSTATE->srv.conn = srv_conn;
|
||||||
|
SOSTATE->srv.rwant = SOSTATE->srv.wwant = 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -136,12 +141,14 @@ static ssize_t ssl_send(void *state, SOCKET s, const void *msg, size_t len, int
|
|||||||
int res, err;
|
int res, err;
|
||||||
if((res = ssl_write(sslq->conn, (void *)msg, len)) <= 0){
|
if((res = ssl_write(sslq->conn, (void *)msg, len)) <= 0){
|
||||||
err = SSL_get_error((SSL *)((ssl_conn*)sslq->conn)->ssl, res);
|
err = SSL_get_error((SSL *)((ssl_conn*)sslq->conn)->ssl, res);
|
||||||
if (err == SSL_ERROR_WANT_WRITE){
|
if (err == SSL_ERROR_WANT_WRITE || err == SSL_ERROR_WANT_READ){
|
||||||
|
sslq->wwant = (err == SSL_ERROR_WANT_READ)? POLLIN : POLLOUT;
|
||||||
seterrno3(EAGAIN);
|
seterrno3(EAGAIN);
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
else seterrno3(err);
|
else seterrno3(err);
|
||||||
}
|
}
|
||||||
|
else sslq->wwant = 0;
|
||||||
return res;
|
return res;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -158,14 +165,16 @@ static ssize_t ssl_sendto(void *state, SOCKET s, const void *msg, size_t len, in
|
|||||||
|
|
||||||
if ((sslq = searchSSL(state, s))){
|
if ((sslq = searchSSL(state, s))){
|
||||||
int res, err;
|
int res, err;
|
||||||
if((res = ssl_write(sslq->conn, (void *)msg, len)) <= 0) {
|
if((res = ssl_write(sslq->conn, (void *)msg, len)) <= 0){
|
||||||
err = SSL_get_error((SSL *)((ssl_conn*)sslq->conn)->ssl, res);
|
err = SSL_get_error((SSL *)((ssl_conn*)sslq->conn)->ssl, res);
|
||||||
if (err == SSL_ERROR_WANT_WRITE){
|
if (err == SSL_ERROR_WANT_WRITE || err == SSL_ERROR_WANT_READ){
|
||||||
|
sslq->wwant = (err == SSL_ERROR_WANT_READ)? POLLIN : POLLOUT;
|
||||||
seterrno3(EAGAIN);
|
seterrno3(EAGAIN);
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
else seterrno3(err);
|
else seterrno3(err);
|
||||||
}
|
}
|
||||||
|
else sslq->wwant = 0;
|
||||||
return res;
|
return res;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -183,12 +192,14 @@ static ssize_t ssl_recvfrom(void *state, SOCKET s, void *msg, size_t len, int f
|
|||||||
int res, err;
|
int res, err;
|
||||||
if((res = ssl_read(sslq->conn, (void *)msg, len)) <= 0) {
|
if((res = ssl_read(sslq->conn, (void *)msg, len)) <= 0) {
|
||||||
err = SSL_get_error((SSL *)((ssl_conn*)sslq->conn)->ssl, res);
|
err = SSL_get_error((SSL *)((ssl_conn*)sslq->conn)->ssl, res);
|
||||||
if (err == SSL_ERROR_WANT_READ) {
|
if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) {
|
||||||
|
sslq->rwant = (err == SSL_ERROR_WANT_WRITE)? POLLOUT : POLLIN;
|
||||||
seterrno3(EAGAIN);
|
seterrno3(EAGAIN);
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
else seterrno3(err);
|
else seterrno3(err);
|
||||||
}
|
}
|
||||||
|
else sslq->rwant = 0;
|
||||||
return res;
|
return res;
|
||||||
}
|
}
|
||||||
return sso._recvfrom(sso.state, s, msg, len, flags, from, fromlen);
|
return sso._recvfrom(sso.state, s, msg, len, flags, from, fromlen);
|
||||||
@@ -205,12 +216,14 @@ static ssize_t ssl_recv(void *state, SOCKET s, void *msg, size_t len, int flags)
|
|||||||
int res, err;
|
int res, err;
|
||||||
if((res = ssl_read(sslq->conn, (void *)msg, len)) <= 0) {
|
if((res = ssl_read(sslq->conn, (void *)msg, len)) <= 0) {
|
||||||
err = SSL_get_error((SSL *)((ssl_conn*)sslq->conn)->ssl, res);
|
err = SSL_get_error((SSL *)((ssl_conn*)sslq->conn)->ssl, res);
|
||||||
if (err == SSL_ERROR_WANT_READ) {
|
if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) {
|
||||||
|
sslq->rwant = (err == SSL_ERROR_WANT_WRITE)? POLLOUT : POLLIN;
|
||||||
seterrno3(EAGAIN);
|
seterrno3(EAGAIN);
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
else seterrno3(err);
|
else seterrno3(err);
|
||||||
}
|
}
|
||||||
|
else sslq->rwant = 0;
|
||||||
return res;
|
return res;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -235,6 +248,8 @@ static int ssl_poll(void *state, struct pollfd *fds, nfds_t nfds, int timeout){
|
|||||||
struct SSLsock *sslq = NULL;
|
struct SSLsock *sslq = NULL;
|
||||||
unsigned int i;
|
unsigned int i;
|
||||||
int ret = 0;
|
int ret = 0;
|
||||||
|
short own[64], *events = own, ev;
|
||||||
|
|
||||||
for(i = 0; i < nfds; i++){
|
for(i = 0; i < nfds; i++){
|
||||||
if((fds[i].events & POLLIN) && (sslq = searchSSL(state, fds[i].fd)) && ssl_pending(sslq->conn)){
|
if((fds[i].events & POLLIN) && (sslq = searchSSL(state, fds[i].fd)) && ssl_pending(sslq->conn)){
|
||||||
fds[i].revents = POLLIN;
|
fds[i].revents = POLLIN;
|
||||||
@@ -243,8 +258,29 @@ static int ssl_poll(void *state, struct pollfd *fds, nfds_t nfds, int timeout){
|
|||||||
else fds[i].revents = 0;
|
else fds[i].revents = 0;
|
||||||
}
|
}
|
||||||
if(ret) return ret;
|
if(ret) return ret;
|
||||||
|
for(i = 0; i < nfds; i++) if((sslq = searchSSL(state, fds[i].fd)) && (sslq->rwant || sslq->wwant)) break;
|
||||||
|
if(i == nfds) return sso._poll(state, fds, nfds, timeout);
|
||||||
|
|
||||||
|
/* A read or a write TLS could not do waits for what TLS needs, a read
|
||||||
|
for the socket to be writable: whatever that gets is the caller's
|
||||||
|
chance to try again, revents what it asked for, and its events are
|
||||||
|
given back as they were. */
|
||||||
|
if(nfds > sizeof(own)/sizeof(own[0]) && !(events = malloc(nfds * sizeof(*events)))) return -1;
|
||||||
|
for(i = 0; i < nfds; i++){
|
||||||
|
events[i] = fds[i].events;
|
||||||
|
if(!(sslq = searchSSL(state, fds[i].fd))) continue;
|
||||||
|
ev = fds[i].events & ~(POLLIN|POLLOUT);
|
||||||
|
if(fds[i].events & POLLIN) ev |= sslq->rwant? sslq->rwant : POLLIN;
|
||||||
|
if(fds[i].events & POLLOUT) ev |= sslq->wwant? sslq->wwant : POLLOUT;
|
||||||
|
fds[i].events = ev;
|
||||||
|
}
|
||||||
ret = sso._poll(state, fds, nfds, timeout);
|
ret = sso._poll(state, fds, nfds, timeout);
|
||||||
|
for(i = 0; i < nfds; i++){
|
||||||
|
if(ret > 0 && fds[i].events != events[i] && (fds[i].revents & ~(POLLERR|POLLHUP|POLLNVAL)))
|
||||||
|
fds[i].revents = events[i] | (fds[i].revents & (POLLERR|POLLHUP|POLLNVAL));
|
||||||
|
fds[i].events = events[i];
|
||||||
|
}
|
||||||
|
if(events != own) free(events);
|
||||||
return ret;
|
return ret;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -409,7 +445,7 @@ SSL_CONN dosrvcon(struct clientparam* param, SSL_CERT* cert){
|
|||||||
}
|
}
|
||||||
|
|
||||||
SSL_set_mode((SSL *)((ssl_conn *)ServerConn)->ssl, SSL_MODE_ENABLE_PARTIAL_WRITE|SSL_MODE_AUTO_RETRY);
|
SSL_set_mode((SSL *)((ssl_conn *)ServerConn)->ssl, SSL_MODE_ENABLE_PARTIAL_WRITE|SSL_MODE_AUTO_RETRY);
|
||||||
SSL_set_read_ahead((SSL *)((ssl_conn *)ServerConn)->ssl, 0);
|
SSL_set_read_ahead((SSL *)((ssl_conn *)ServerConn)->ssl, SSL_READAHEAD);
|
||||||
|
|
||||||
return ServerConn;
|
return ServerConn;
|
||||||
}
|
}
|
||||||
@@ -442,7 +478,7 @@ int domitm(struct clientparam* param){
|
|||||||
}
|
}
|
||||||
|
|
||||||
SSL_set_mode((SSL *)((ssl_conn *)ClientConn)->ssl, SSL_MODE_ENABLE_PARTIAL_WRITE|SSL_MODE_AUTO_RETRY);
|
SSL_set_mode((SSL *)((ssl_conn *)ClientConn)->ssl, SSL_MODE_ENABLE_PARTIAL_WRITE|SSL_MODE_AUTO_RETRY);
|
||||||
SSL_set_read_ahead((SSL *)((ssl_conn *)ClientConn)->ssl, 0);
|
SSL_set_read_ahead((SSL *)((ssl_conn *)ClientConn)->ssl, SSL_READAHEAD);
|
||||||
|
|
||||||
addSSL(param->clisock, ClientConn, param->remsock, ServerConn, param);
|
addSSL(param->clisock, ClientConn, param->remsock, ServerConn, param);
|
||||||
|
|
||||||
@@ -772,14 +808,14 @@ static FILTER_ACTION ssl_filter_client(void *fo, struct clientparam * param, voi
|
|||||||
return REJECT;
|
return REJECT;
|
||||||
}
|
}
|
||||||
SSL_set_mode((SSL *)((ssl_conn *)ClientConn)->ssl, SSL_MODE_ENABLE_PARTIAL_WRITE|SSL_MODE_AUTO_RETRY);
|
SSL_set_mode((SSL *)((ssl_conn *)ClientConn)->ssl, SSL_MODE_ENABLE_PARTIAL_WRITE|SSL_MODE_AUTO_RETRY);
|
||||||
SSL_set_read_ahead((SSL *)((ssl_conn *)ClientConn)->ssl, 0);
|
SSL_set_read_ahead((SSL *)((ssl_conn *)ClientConn)->ssl, SSL_READAHEAD);
|
||||||
addSSL(param->clisock, ClientConn, INVALID_SOCKET, NULL, param);
|
addSSL(param->clisock, ClientConn, INVALID_SOCKET, NULL, param);
|
||||||
}
|
}
|
||||||
return CONTINUE;
|
return CONTINUE;
|
||||||
}
|
}
|
||||||
|
|
||||||
static FILTER_ACTION ssl_filter_connect(void *fc, struct clientparam * param){
|
static FILTER_ACTION ssl_filter_connect(void *fc, struct clientparam * param){
|
||||||
if(PCONF->cli && !client_mode) {
|
if(PCONF->cli && !PCONF->client_mode) {
|
||||||
if(docli(param)) {
|
if(docli(param)) {
|
||||||
return REJECT;
|
return REJECT;
|
||||||
}
|
}
|
||||||
@@ -788,7 +824,7 @@ static FILTER_ACTION ssl_filter_connect(void *fc, struct clientparam * param){
|
|||||||
}
|
}
|
||||||
|
|
||||||
static FILTER_ACTION ssl_filter_afterauth(void *fc, struct clientparam * param){
|
static FILTER_ACTION ssl_filter_afterauth(void *fc, struct clientparam * param){
|
||||||
if(PCONF->cli && client_mode == 1) {
|
if(PCONF->cli && PCONF->client_mode == 1) {
|
||||||
if(docli(param)) {
|
if(docli(param)) {
|
||||||
return REJECT;
|
return REJECT;
|
||||||
}
|
}
|
||||||
@@ -806,7 +842,7 @@ static FILTER_ACTION ssl_filter_predata(void *fc, struct clientparam * param){
|
|||||||
if(!param->redirectfunc) param->redirectfunc = proxyfunc;
|
if(!param->redirectfunc) param->redirectfunc = proxyfunc;
|
||||||
return CONTINUE;
|
return CONTINUE;
|
||||||
}
|
}
|
||||||
else if(PCONF->cli && client_mode == 2) {
|
else if(PCONF->cli && PCONF->client_mode == 2) {
|
||||||
if(docli(param)) {
|
if(docli(param)) {
|
||||||
return REJECT;
|
return REJECT;
|
||||||
}
|
}
|
||||||
@@ -815,7 +851,7 @@ static FILTER_ACTION ssl_filter_predata(void *fc, struct clientparam * param){
|
|||||||
}
|
}
|
||||||
|
|
||||||
static FILTER_ACTION ssl_parent(struct clientparam * param){
|
static FILTER_ACTION ssl_parent(struct clientparam * param){
|
||||||
if(PCONF->cli && client_mode == 3) {
|
if(PCONF->cli && PCONF->client_mode == 3) {
|
||||||
if(docli(param)) {
|
if(docli(param)) {
|
||||||
return REJECT;
|
return REJECT;
|
||||||
}
|
}
|
||||||
@@ -867,6 +903,9 @@ static void ssl_filter_close(void *fo){
|
|||||||
free(CONFIG->client_ca_file);
|
free(CONFIG->client_ca_file);
|
||||||
free(CONFIG->client_ca_dir);
|
free(CONFIG->client_ca_dir);
|
||||||
free(CONFIG->client_ca_store);
|
free(CONFIG->client_ca_store);
|
||||||
|
free(CONFIG->server_ca_file);
|
||||||
|
free(CONFIG->server_ca_dir);
|
||||||
|
free(CONFIG->server_ca_store);
|
||||||
free(CONFIG->client_sni);
|
free(CONFIG->client_sni);
|
||||||
if(CONFIG->client_alpn_protos.protos_len){
|
if(CONFIG->client_alpn_protos.protos_len){
|
||||||
free(CONFIG->client_alpn_protos.protos);
|
free(CONFIG->client_alpn_protos.protos);
|
||||||
|
|||||||
@@ -76,6 +76,16 @@ int ssl_read(SSL_CONN connection, void * buf, int bufsize);
|
|||||||
int ssl_write(SSL_CONN connection, void * buf, int bufsize);
|
int ssl_write(SSL_CONN connection, void * buf, int bufsize);
|
||||||
int ssl_pending(SSL_CONN connection);
|
int ssl_pending(SSL_CONN connection);
|
||||||
|
|
||||||
|
/* TLS records are read ahead, a buffer at a time rather than two reads for
|
||||||
|
each record, where what is read ahead and not yet decrypted shows as
|
||||||
|
pending (SSL_has_pending(), OpenSSL 1.1.0 and later): poll() would wait
|
||||||
|
on it otherwise. */
|
||||||
|
#if !defined(WITH_WOLFSSL) && defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x10100000L
|
||||||
|
#define SSL_READAHEAD 1
|
||||||
|
#else
|
||||||
|
#define SSL_READAHEAD 0
|
||||||
|
#endif
|
||||||
|
|
||||||
//
|
//
|
||||||
// Release of opaque structures
|
// Release of opaque structures
|
||||||
//
|
//
|
||||||
|
|||||||
+46
-1
@@ -22,6 +22,7 @@
|
|||||||
#include <wolfssl/openssl/pem.h>
|
#include <wolfssl/openssl/pem.h>
|
||||||
#include <wolfssl/openssl/ssl.h>
|
#include <wolfssl/openssl/ssl.h>
|
||||||
#include <wolfssl/openssl/err.h>
|
#include <wolfssl/openssl/err.h>
|
||||||
|
#include <wolfssl/openssl/bn.h>
|
||||||
#else
|
#else
|
||||||
#include <openssl/crypto.h>
|
#include <openssl/crypto.h>
|
||||||
#include <openssl/x509.h>
|
#include <openssl/x509.h>
|
||||||
@@ -29,6 +30,7 @@
|
|||||||
#include <openssl/pem.h>
|
#include <openssl/pem.h>
|
||||||
#include <openssl/ssl.h>
|
#include <openssl/ssl.h>
|
||||||
#include <openssl/err.h>
|
#include <openssl/err.h>
|
||||||
|
#include <openssl/bn.h>
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#include "proxy.h"
|
#include "proxy.h"
|
||||||
@@ -115,6 +117,31 @@ static int add_ext(X509 *cert, int nid, const char *value)
|
|||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
/* A serial number of the copy's own, when the source's cannot be set back:
|
||||||
|
* positive, from the hash of the source certificate, so the same for the
|
||||||
|
* same certificate and different for another. wolfSSL built with
|
||||||
|
* WOLFSSL_QT, as Ubuntu 26.04 has it, returns a serial number without the
|
||||||
|
* ASN.1 header its own X509_set_serialNumber() requires.
|
||||||
|
*/
|
||||||
|
static int set_serial_hash(X509 *cert, const unsigned char *hash)
|
||||||
|
{
|
||||||
|
unsigned char serial[16];
|
||||||
|
BIGNUM *bn;
|
||||||
|
ASN1_INTEGER *ai;
|
||||||
|
int res = 0;
|
||||||
|
|
||||||
|
memcpy(serial, hash, sizeof(serial));
|
||||||
|
serial[0] &= 0x7f;
|
||||||
|
if(!serial[0]) serial[0] = 1;
|
||||||
|
if(!(bn = BN_bin2bn(serial, sizeof(serial), NULL))) return 0;
|
||||||
|
if((ai = BN_to_ASN1_INTEGER(bn, NULL))){
|
||||||
|
res = X509_set_serialNumber(cert, ai);
|
||||||
|
ASN1_INTEGER_free(ai);
|
||||||
|
}
|
||||||
|
BN_free(bn);
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
SSL_CERT ssl_copy_cert(SSL_CERT cert, SSL_CONFIG *config)
|
SSL_CERT ssl_copy_cert(SSL_CERT cert, SSL_CONFIG *config)
|
||||||
{
|
{
|
||||||
int err = -1;
|
int err = -1;
|
||||||
@@ -162,7 +189,8 @@ SSL_CERT ssl_copy_cert(SSL_CERT cert, SSL_CONFIG *config)
|
|||||||
}
|
}
|
||||||
/* v3 is required, extensions are added below */
|
/* v3 is required, extensions are added below */
|
||||||
X509_set_version(dst_cert, 2);
|
X509_set_version(dst_cert, 2);
|
||||||
if(!X509_set_serialNumber(dst_cert, X509_get_serialNumber(src_cert))
|
if((!X509_set_serialNumber(dst_cert, X509_get_serialNumber(src_cert))
|
||||||
|
&& !set_serial_hash(dst_cert, hash_sha256))
|
||||||
|| !X509_set_subject_name(dst_cert, X509_get_subject_name(src_cert))
|
|| !X509_set_subject_name(dst_cert, X509_get_subject_name(src_cert))
|
||||||
|| !X509_set_issuer_name(dst_cert, X509_get_subject_name(config->CA_cert))){
|
|| !X509_set_issuer_name(dst_cert, X509_get_subject_name(config->CA_cert))){
|
||||||
X509_free(dst_cert);
|
X509_free(dst_cert);
|
||||||
@@ -261,8 +289,25 @@ int ssl_write(SSL_CONN connection, void * buf, int bufsize)
|
|||||||
int ssl_pending(SSL_CONN connection)
|
int ssl_pending(SSL_CONN connection)
|
||||||
{
|
{
|
||||||
ssl_conn *conn = (ssl_conn *) connection;
|
ssl_conn *conn = (ssl_conn *) connection;
|
||||||
|
#if SSL_READAHEAD
|
||||||
|
char c;
|
||||||
|
int res;
|
||||||
|
|
||||||
|
if(SSL_pending(conn->ssl) > 0) return 1;
|
||||||
|
if(!SSL_has_pending(conn->ssl)) return 0;
|
||||||
|
/* Read ahead and not decrypted: a record, or only a part of one. A
|
||||||
|
part is no data, and saying so would have poll() return at once,
|
||||||
|
again and again, without its timeout, until the rest came: it is
|
||||||
|
pending only once the record is whole (or the connection ended),
|
||||||
|
the socket polled for the rest otherwise. The sockets are not
|
||||||
|
blocking, so this does not wait. */
|
||||||
|
res = SSL_peek(conn->ssl, &c, 1);
|
||||||
|
if(res > 0) return 1;
|
||||||
|
res = SSL_get_error(conn->ssl, res);
|
||||||
|
return res != SSL_ERROR_WANT_READ && res != SSL_ERROR_WANT_WRITE;
|
||||||
|
#else
|
||||||
return SSL_pending(conn->ssl);
|
return SSL_pending(conn->ssl);
|
||||||
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
void ssl_conn_free(SSL_CONN connection)
|
void ssl_conn_free(SSL_CONN connection)
|
||||||
|
|||||||
+2
-2
@@ -31,8 +31,8 @@ unsigned char * strings[] = {
|
|||||||
/* 18 */ (unsigned char *)"AUTO",
|
/* 18 */ (unsigned char *)"AUTO",
|
||||||
/* 19 */ (unsigned char *)"TLSPR",
|
/* 19 */ (unsigned char *)"TLSPR",
|
||||||
/* 20 */ (unsigned char *)"IMAPP",
|
/* 20 */ (unsigned char *)"IMAPP",
|
||||||
/* 21 */ (unsigned char *)"ZOMBIE",
|
/* 21 */ (unsigned char *)"HTTPSRV",
|
||||||
/* 22 */ NULL,
|
/* 22 */ (unsigned char *)"ZOMBIE",
|
||||||
/* 23 */ NULL,
|
/* 23 */ NULL,
|
||||||
/* 24 */ NULL,
|
/* 24 */ NULL,
|
||||||
#ifndef TPROXY_CONF
|
#ifndef TPROXY_CONF
|
||||||
|
|||||||
+23
-3
@@ -47,6 +47,7 @@ typedef struct _3proxy_sem_s {
|
|||||||
pthread_cond_t cond;
|
pthread_cond_t cond;
|
||||||
unsigned count;
|
unsigned count;
|
||||||
unsigned maxcount;
|
unsigned maxcount;
|
||||||
|
int monotonic; /* timed waits measured on CLOCK_MONOTONIC */
|
||||||
} _3proxy_sem_t;
|
} _3proxy_sem_t;
|
||||||
#else
|
#else
|
||||||
#include <winsock2.h>
|
#include <winsock2.h>
|
||||||
@@ -112,6 +113,7 @@ int
|
|||||||
|
|
||||||
#ifdef WITH_UN
|
#ifdef WITH_UN
|
||||||
#include <sys/un.h>
|
#include <sys/un.h>
|
||||||
|
#include <stddef.h>
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#define ALLOW 0
|
#define ALLOW 0
|
||||||
@@ -159,7 +161,9 @@ int
|
|||||||
#define UN_SAADDR(sa) (((struct sockaddr_un *)sa)->sun_family == AF_UNIX)? (unsigned char *)((struct sockaddr_un *)sa)->sun_path :
|
#define UN_SAADDR(sa) (((struct sockaddr_un *)sa)->sun_family == AF_UNIX)? (unsigned char *)((struct sockaddr_un *)sa)->sun_path :
|
||||||
#define UN_SAADDRLEN(sa) (((struct sockaddr_un *)sa)->sun_family == AF_UNIX)? (int)sizeof(((struct sockaddr_un *)sa)->sun_path) :
|
#define UN_SAADDRLEN(sa) (((struct sockaddr_un *)sa)->sun_family == AF_UNIX)? (int)sizeof(((struct sockaddr_un *)sa)->sun_path) :
|
||||||
#define UN_SASOCK(sa) (((struct sockaddr_un *)sa)->sun_family == AF_UNIX)? PF_UNIX :
|
#define UN_SASOCK(sa) (((struct sockaddr_un *)sa)->sun_family == AF_UNIX)? PF_UNIX :
|
||||||
#define UN_SASIZE(sa) (((struct sockaddr_un *)sa)->sun_family == AF_UNIX)? sizeof(struct sockaddr_un) :
|
/* an abstract name (Linux) is its bytes after the leading 0, no more:
|
||||||
|
padded with zeros it would be another name */
|
||||||
|
#define UN_SASIZE(sa) (((struct sockaddr_un *)sa)->sun_family == AF_UNIX)? (((struct sockaddr_un *)sa)->sun_path[0] || !((struct sockaddr_un *)sa)->sun_path[1]? sizeof(struct sockaddr_un) : offsetof(struct sockaddr_un, sun_path) + 1 + strlen(((struct sockaddr_un *)sa)->sun_path + 1)) :
|
||||||
#define UN_SAISNULL(sa) (((struct sockaddr_un *)sa)->sun_family == AF_UNIX)? (((struct sockaddr_un *)sa)->sun_path[0] == 0 && ((struct sockaddr_un *)sa)->sun_path[1] == 0) :
|
#define UN_SAISNULL(sa) (((struct sockaddr_un *)sa)->sun_family == AF_UNIX)? (((struct sockaddr_un *)sa)->sun_path[0] == 0 && ((struct sockaddr_un *)sa)->sun_path[1] == 0) :
|
||||||
#else
|
#else
|
||||||
#define UN_SAPORT(sa)
|
#define UN_SAPORT(sa)
|
||||||
@@ -528,6 +532,14 @@ struct filterp {
|
|||||||
|
|
||||||
#define MAX_FILTERS 16
|
#define MAX_FILTERS 16
|
||||||
|
|
||||||
|
/* Socket options for one kind of socket, -oc and the like: which of
|
||||||
|
sockopts[] are given, by their index there, and the value of each. */
|
||||||
|
#define MAXSOCKOPTS 32
|
||||||
|
struct sockoptset {
|
||||||
|
unsigned set;
|
||||||
|
int value[MAXSOCKOPTS];
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
struct sockfuncs {
|
struct sockfuncs {
|
||||||
void * state;
|
void * state;
|
||||||
@@ -599,6 +611,8 @@ struct srvparam {
|
|||||||
AUTHFUNC authfunc;
|
AUTHFUNC authfunc;
|
||||||
PROXYFUNC pf;
|
PROXYFUNC pf;
|
||||||
SOCKET srvsock, cbsock;
|
SOCKET srvsock, cbsock;
|
||||||
|
/* the file of a Unix socket bound to a path, to remove only it */
|
||||||
|
uint64_t undev, unino;
|
||||||
int childcount;
|
int childcount;
|
||||||
int maxchild;
|
int maxchild;
|
||||||
int backlog;
|
int backlog;
|
||||||
@@ -612,12 +626,13 @@ struct srvparam {
|
|||||||
int stacksize;
|
int stacksize;
|
||||||
int noforce;
|
int noforce;
|
||||||
int anonymous;
|
int anonymous;
|
||||||
int clisockopts, srvsockopts, lissockopts, cbcsockopts, cbssockopts;
|
struct sockoptset clisockopts, srvsockopts, lissockopts, cbcsockopts, cbssockopts;
|
||||||
int gracetraf, gracenum, gracedelay;
|
int gracetraf, gracenum, gracedelay;
|
||||||
int requirecert;
|
int requirecert;
|
||||||
int haproxy;
|
int haproxy;
|
||||||
int nostarttls;
|
int nostarttls;
|
||||||
PROXYSERVICE srvstarttls;
|
PROXYSERVICE srvstarttls;
|
||||||
|
int allowftp; /* the http proxy fetches ftp:// for this service */
|
||||||
uint32_t fakeip;
|
uint32_t fakeip;
|
||||||
unsigned char fakeip6[16];
|
unsigned char fakeip6[16];
|
||||||
#ifdef WITHSPLICE
|
#ifdef WITHSPLICE
|
||||||
@@ -634,6 +649,7 @@ struct srvparam {
|
|||||||
#endif
|
#endif
|
||||||
PROXYSOCKADDRTYPE extsa;
|
PROXYSOCKADDRTYPE extsa;
|
||||||
_3proxy_mutex_t counter_mutex;
|
_3proxy_mutex_t counter_mutex;
|
||||||
|
_3proxy_sem_t childslots; /* maxchild of them, one held by each child */
|
||||||
struct pollfd fds;
|
struct pollfd fds;
|
||||||
FILE *stdlog;
|
FILE *stdlog;
|
||||||
unsigned char * target;
|
unsigned char * target;
|
||||||
@@ -732,6 +748,11 @@ struct clientparam {
|
|||||||
*clibuf,
|
*clibuf,
|
||||||
*srvbuf;
|
*srvbuf;
|
||||||
|
|
||||||
|
/* splice() pipes for the client's and the server's data, -1 until
|
||||||
|
made; kept for the life of the connection */
|
||||||
|
int pipecli[2],
|
||||||
|
pipesrv[2];
|
||||||
|
|
||||||
unsigned cliinbuf,
|
unsigned cliinbuf,
|
||||||
srvinbuf,
|
srvinbuf,
|
||||||
clioffset,
|
clioffset,
|
||||||
@@ -785,7 +806,6 @@ struct filemon {
|
|||||||
|
|
||||||
|
|
||||||
struct extparam {
|
struct extparam {
|
||||||
_3proxy_sem_t threadinit;
|
|
||||||
int *timeouts;
|
int *timeouts;
|
||||||
struct ace * acl;
|
struct ace * acl;
|
||||||
#ifdef WITH_HTTPSRV
|
#ifdef WITH_HTTPSRV
|
||||||
|
|||||||
+1
-1
@@ -140,7 +140,7 @@ int udpbind(struct clientparam *param)
|
|||||||
return 12;
|
return 12;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
sasize = SASIZE(¶m->sinsl);
|
sasize = sizeof(param->sinsl);
|
||||||
param->srv->so._getsockname(param->sostate, param->remsock,
|
param->srv->so._getsockname(param->sostate, param->remsock,
|
||||||
(struct sockaddr *)¶m->sinsl, &sasize);
|
(struct sockaddr *)¶m->sinsl, &sasize);
|
||||||
return 0;
|
return 0;
|
||||||
|
|||||||
+4
-4
@@ -1,14 +1,14 @@
|
|||||||
#ifndef VERSION
|
#ifndef VERSION
|
||||||
#define VERSION "3proxy-1.0.1"
|
#define VERSION "3proxy-1.0.3"
|
||||||
#endif
|
#endif
|
||||||
#ifndef BUILDDATE
|
#ifndef BUILDDATE
|
||||||
#define BUILDDATE "261010162101"
|
#define BUILDDATE "261107085016"
|
||||||
#endif
|
#endif
|
||||||
#define MAJOR3PROXY 1
|
#define MAJOR3PROXY 1
|
||||||
#define SUBMAJOR3PROXY 0
|
#define SUBMAJOR3PROXY 0
|
||||||
#define MINOR3PROXY 1
|
#define MINOR3PROXY 3
|
||||||
#define SUBMINOR3PROXY 0
|
#define SUBMINOR3PROXY 0
|
||||||
#define RELEASE3PROXY "3proxy-1.0.1(" BUILDDATE ")\0"
|
#define RELEASE3PROXY "3proxy-1.0.3(" BUILDDATE ")\0"
|
||||||
#ifndef YEAR3PROXY
|
#ifndef YEAR3PROXY
|
||||||
#define YEAR3PROXY "2026"
|
#define YEAR3PROXY "2026"
|
||||||
#endif
|
#endif
|
||||||
+12
-3
@@ -13,6 +13,14 @@ skips itself when that is missing or the build has no TLS support. With no
|
|||||||
`--bin` it looks in `bin/`, then `build/bin/`, then the per-configuration
|
`--bin` it looks in `bin/`, then `build/bin/`, then the per-configuration
|
||||||
directories a multi-configuration CMake generator uses.
|
directories a multi-configuration CMake generator uses.
|
||||||
|
|
||||||
|
The binary reports what it was built with in `3proxy --help` (a `built
|
||||||
|
with:` list), and the runner reads that before the first case: a case names
|
||||||
|
the features it needs with `if not t.skip_unless("ssl"): return`, and
|
||||||
|
skips on a build without them instead of failing. A binary too old to
|
||||||
|
report its features skips every case that needs one, and the cases with no
|
||||||
|
feature needs still run; some cases also probe at runtime, as a build can
|
||||||
|
leave a feature compiled in but unusable.
|
||||||
|
|
||||||
The proxy under test is also the origin server the tests talk to: the `http`
|
The proxy under test is also the origin server the tests talk to: the `http`
|
||||||
command's `echo` operation reports back how a request arrived - method, path,
|
command's `echo` operation reports back how a request arrived - method, path,
|
||||||
query, host, and the source port it came from - and `data` generates a body
|
query, host, and the source port it came from - and `data` generates a body
|
||||||
@@ -69,7 +77,7 @@ means to stand on its own should start with one - otherwise an earlier
|
|||||||
|
|
||||||
## What is not covered yet
|
## What is not covered yet
|
||||||
|
|
||||||
41 of the 112 configuration commands appear in a test, and the count says
|
42 of the 112 configuration commands appear in a test, and the count says
|
||||||
nothing about service options: the IPv6 case, for instance, exercises -4,
|
nothing about service options: the IPv6 case, for instance, exercises -4,
|
||||||
-6, -46, -64 and -i without adding a command to it. What follows is
|
-6, -46, -64 and -i without adding a command to it. What follows is
|
||||||
roughly the order worth working through: how much of the product a gap
|
roughly the order worth working through: how much of the product a gap
|
||||||
@@ -78,12 +86,13 @@ covers, and how much of a fixture it needs.
|
|||||||
### Traffic limits and accounting
|
### Traffic limits and accounting
|
||||||
|
|
||||||
`bandlimin` `bandlimout` `nobandlimin` `nobandlimout` `connlim` `noconnlim`
|
`bandlimin` `bandlimout` `nobandlimin` `nobandlimout` `connlim` `noconnlim`
|
||||||
`countin` `countout` `countall` and the `no*` forms, `maxconn`.
|
`countin` `countout` `countall` and the `no*` forms.
|
||||||
|
|
||||||
Cheap and worth doing first: `data?size=` and a stopwatch measure a
|
Cheap and worth doing first: `data?size=` and a stopwatch measure a
|
||||||
bandwidth limit, and the admin counters page already shows what a counter
|
bandwidth limit, and the admin counters page already shows what a counter
|
||||||
holds. `countin` appears in a configuration today but nothing checks that it
|
holds. `countin` appears in a configuration today but nothing checks that it
|
||||||
counts. `connlim` and `maxconn` need concurrent connections.
|
counts. `connlim` needs concurrent connections, held open the way the
|
||||||
|
`maxconn` case holds them.
|
||||||
|
|
||||||
### The mail proxies
|
### The mail proxies
|
||||||
|
|
||||||
|
|||||||
+30
-3
@@ -1,10 +1,14 @@
|
|||||||
"""The admin interface, now a set of handlers on the HTTP server."""
|
"""The admin interface, now a set of handlers on the HTTP server."""
|
||||||
|
|
||||||
|
import time
|
||||||
|
|
||||||
|
|
||||||
def run(t):
|
def run(t):
|
||||||
|
if not t.skip_unless("httpsrv"):
|
||||||
|
return
|
||||||
adm = t.free_port()
|
adm = t.free_port()
|
||||||
lim = t.free_port()
|
lim = t.free_port()
|
||||||
t.start("admin", f"""
|
server = t.start("admin", f"""
|
||||||
log
|
log
|
||||||
auth iponly
|
auth iponly
|
||||||
allow *
|
allow *
|
||||||
@@ -20,17 +24,40 @@ def run(t):
|
|||||||
|
|
||||||
url = f"http://127.0.0.1:{adm}"
|
url = f"http://127.0.0.1:{adm}"
|
||||||
|
|
||||||
|
def reload(path):
|
||||||
|
"""Ask for a reload and wait for it to be done. It happens on the next
|
||||||
|
tick of the main loop, at most a second later; both old services stop
|
||||||
|
and the new ones start, and a request in between is refused (Windows
|
||||||
|
cannot bind a port still listening) or reset."""
|
||||||
|
before = server.output()
|
||||||
|
accepting = before.count("Accepting connections")
|
||||||
|
exiting = before.count("Exiting thread")
|
||||||
|
reply = t.http(url + path)
|
||||||
|
deadline = time.time() + 10
|
||||||
|
while time.time() < deadline:
|
||||||
|
now = server.output()
|
||||||
|
if (now.count("Accepting connections") >= accepting + 2
|
||||||
|
and now.count("Exiting thread") >= exiting + 2):
|
||||||
|
break
|
||||||
|
time.sleep(0.05)
|
||||||
|
return reply
|
||||||
|
|
||||||
# --- the predefined pages -----------------------------------------
|
# --- the predefined pages -----------------------------------------
|
||||||
t.eq(200, t.http(url + "/").status, "the main page")
|
t.eq(200, t.http(url + "/").status, "the main page")
|
||||||
t.eq(200, t.http(url + "/C").status, "the counters page")
|
t.eq(200, t.http(url + "/C").status, "the counters page")
|
||||||
t.eq(200, t.http(url + "/R").status, "the reload page")
|
t.eq(200, reload("/R").status, "the reload page")
|
||||||
t.eq(200, t.http(url + "/S").status, "the services page")
|
t.eq(200, t.http(url + "/S").status, "the services page")
|
||||||
|
|
||||||
counters = t.http(url + "/C")
|
counters = t.http(url + "/C")
|
||||||
t.contains(counters, "countin", "the counters page names the counter type")
|
t.contains(counters, "countin", "the counters page names the counter type")
|
||||||
t.contains(counters, "<tr>", "the counters page renders a table")
|
t.contains(counters, "<tr>", "the counters page renders a table")
|
||||||
t.contains(t.http(url + "/R"), "Reload", "the reload page confirms the request")
|
t.contains(reload("/R"), "Reload", "the reload page confirms the request")
|
||||||
t.contains(t.http(url + "/S"), "<", "the services page returns markup")
|
t.contains(t.http(url + "/S"), "<", "the services page returns markup")
|
||||||
|
# admin and httpsrv services are of type HTTPSRV, named as such, not as
|
||||||
|
# the zombie a stopped service is
|
||||||
|
services = t.http(url + "/S")
|
||||||
|
t.contains(services, "CDATA[HTTPSRV]", "the services page names the admin service HTTPSRV")
|
||||||
|
t.not_contains(services, "CDATA[ZOMBIE]", "and no running service a zombie")
|
||||||
|
|
||||||
# --- the menu no longer offers the removed config editor -----------
|
# --- the menu no longer offers the removed config editor -----------
|
||||||
main = t.http(url + "/")
|
main = t.http(url + "/")
|
||||||
|
|||||||
+3
-1
@@ -7,7 +7,9 @@ handshake and the service supplies the port.
|
|||||||
|
|
||||||
|
|
||||||
def run(t):
|
def run(t):
|
||||||
certs = t.certs()
|
if not t.skip_unless("httpsrv"):
|
||||||
|
return
|
||||||
|
certs = t.certs() if t.has("ssl") else None
|
||||||
plain = t.free_port()
|
plain = t.free_port()
|
||||||
port = t.free_port()
|
port = t.free_port()
|
||||||
secure = t.free_port() if certs else None
|
secure = t.free_port() if certs else None
|
||||||
|
|||||||
@@ -0,0 +1,108 @@
|
|||||||
|
"""The FTP proxy logging in to its server: whatever the server answers the
|
||||||
|
login with reaches the client, which waits for the answer to its PASS."""
|
||||||
|
|
||||||
|
import socket
|
||||||
|
import threading
|
||||||
|
|
||||||
|
# what the server answers USER with, and PASS if it asks for one
|
||||||
|
LOGINS = {
|
||||||
|
"230 to USER": ([b"230 Anonymous user logged in"], None),
|
||||||
|
"multiline 230 to USER": ([b"230-Welcome", b"230-to the server", b"230 Login successful."], None),
|
||||||
|
"331 to USER, 230 to PASS": ([b"331 Please specify the password."], [b"230 Login successful."]),
|
||||||
|
"530 to USER": ([b"530 Not allowed here"], None),
|
||||||
|
"331 to USER, 530 to PASS": ([b"331 Please specify the password."], [b"530 Login incorrect."]),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def ftp_server(listener, user, password):
|
||||||
|
"""Greets, answers the login as told, then NOOP and QUIT."""
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
c, _ = listener.accept()
|
||||||
|
except OSError:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
f = c.makefile("rb")
|
||||||
|
c.sendall(b"220 Fake FTP\r\n")
|
||||||
|
if not f.readline().upper().startswith(b"USER "):
|
||||||
|
continue
|
||||||
|
c.sendall(b"".join(line + b"\r\n" for line in user))
|
||||||
|
if password is not None:
|
||||||
|
if not f.readline().upper().startswith(b"PASS "):
|
||||||
|
continue
|
||||||
|
c.sendall(b"".join(line + b"\r\n" for line in password))
|
||||||
|
for line in f:
|
||||||
|
if line.upper().startswith(b"NOOP"):
|
||||||
|
c.sendall(b"200 NOOP ok\r\n")
|
||||||
|
elif line.upper().startswith(b"QUIT"):
|
||||||
|
c.sendall(b"221 Bye\r\n")
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
c.sendall(b"502 Not implemented\r\n")
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
c.close()
|
||||||
|
|
||||||
|
|
||||||
|
def reply(f):
|
||||||
|
"""The last line of a reply, multiline or not; empty at the end or on a
|
||||||
|
time out."""
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
line = f.readline()
|
||||||
|
except OSError:
|
||||||
|
return b""
|
||||||
|
if not line:
|
||||||
|
return b""
|
||||||
|
if len(line) < 4 or line[3:4] != b"-":
|
||||||
|
return line.rstrip()
|
||||||
|
|
||||||
|
|
||||||
|
def run(t):
|
||||||
|
if not t.skip_unless("ftppr"):
|
||||||
|
return
|
||||||
|
servers = {}
|
||||||
|
for name, (user, password) in LOGINS.items():
|
||||||
|
listener = socket.socket()
|
||||||
|
listener.bind(("127.0.0.1", 0))
|
||||||
|
listener.listen(5)
|
||||||
|
threading.Thread(target=ftp_server, args=(listener, user, password), daemon=True).start()
|
||||||
|
servers[name] = listener
|
||||||
|
|
||||||
|
port = t.free_port()
|
||||||
|
t.start("ftppr", f"""
|
||||||
|
log
|
||||||
|
auth none
|
||||||
|
ftppr -p{port}
|
||||||
|
""", ports=[port])
|
||||||
|
|
||||||
|
# without WITH_FTP the service closes the connection at once
|
||||||
|
s = socket.create_connection(("127.0.0.1", port), timeout=5)
|
||||||
|
built = reply(s.makefile("rb"))
|
||||||
|
s.close()
|
||||||
|
if not built:
|
||||||
|
t.skip("the FTP proxy (not built in this configuration)")
|
||||||
|
for listener in servers.values():
|
||||||
|
listener.close()
|
||||||
|
t.stop_all()
|
||||||
|
return
|
||||||
|
|
||||||
|
for name, listener in servers.items():
|
||||||
|
s = socket.create_connection(("127.0.0.1", port), timeout=5)
|
||||||
|
f = s.makefile("rb")
|
||||||
|
reply(f)
|
||||||
|
s.sendall(b"USER anonymous@127.0.0.1:%d\r\n" % listener.getsockname()[1])
|
||||||
|
reply(f)
|
||||||
|
s.sendall(b"PASS test@example.com\r\n")
|
||||||
|
got = reply(f)
|
||||||
|
ok = LOGINS[name][1] if LOGINS[name][1] is not None else LOGINS[name][0]
|
||||||
|
t.eq(ok[-1][:3], got[:3], f"{name}: the client gets the server's answer")
|
||||||
|
if got.startswith(b"230"):
|
||||||
|
s.sendall(b"NOOP\r\n")
|
||||||
|
t.eq(b"200", reply(f)[:3], f"{name}: and the session goes on")
|
||||||
|
s.close()
|
||||||
|
|
||||||
|
for listener in servers.values():
|
||||||
|
listener.close()
|
||||||
|
t.stop_all()
|
||||||
@@ -2,6 +2,8 @@
|
|||||||
|
|
||||||
|
|
||||||
def run(t):
|
def run(t):
|
||||||
|
if not t.skip_unless("httpsrv"):
|
||||||
|
return
|
||||||
srv = t.free_port()
|
srv = t.free_port()
|
||||||
openport = t.free_port()
|
openport = t.free_port()
|
||||||
t.start("httpsrv_auth", f"""
|
t.start("httpsrv_auth", f"""
|
||||||
|
|||||||
@@ -8,6 +8,8 @@ import os
|
|||||||
|
|
||||||
|
|
||||||
def run(t):
|
def run(t):
|
||||||
|
if not t.skip_unless("httpsrv"):
|
||||||
|
return
|
||||||
root = os.path.join(t.tmpdir, "web")
|
root = os.path.join(t.tmpdir, "web")
|
||||||
os.makedirs(os.path.join(root, "picts", "set"), exist_ok=True)
|
os.makedirs(os.path.join(root, "picts", "set"), exist_ok=True)
|
||||||
with open(os.path.join(root, "a.html"), "w") as fp:
|
with open(os.path.join(root, "a.html"), "w") as fp:
|
||||||
|
|||||||
@@ -10,6 +10,8 @@ import os
|
|||||||
|
|
||||||
|
|
||||||
def run(t):
|
def run(t):
|
||||||
|
if not t.skip_unless("httpsrv"):
|
||||||
|
return
|
||||||
root = os.path.join(t.tmpdir, "ka")
|
root = os.path.join(t.tmpdir, "ka")
|
||||||
os.makedirs(root, exist_ok=True)
|
os.makedirs(root, exist_ok=True)
|
||||||
with open(os.path.join(root, "a.html"), "w") as fp:
|
with open(os.path.join(root, "a.html"), "w") as fp:
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import time
|
|||||||
|
|
||||||
|
|
||||||
def run(t):
|
def run(t):
|
||||||
|
if not t.skip_unless("httpsrv"):
|
||||||
|
return
|
||||||
srv = t.free_port()
|
srv = t.free_port()
|
||||||
t.start("httpsrv_ops", f"""
|
t.start("httpsrv_ops", f"""
|
||||||
log
|
log
|
||||||
|
|||||||
@@ -6,6 +6,8 @@ most of them away before they ever reached the server.
|
|||||||
|
|
||||||
|
|
||||||
def run(t):
|
def run(t):
|
||||||
|
if not t.skip_unless("httpsrv"):
|
||||||
|
return
|
||||||
srv = t.free_port()
|
srv = t.free_port()
|
||||||
t.start("httpsrv_parsing", f"""
|
t.start("httpsrv_parsing", f"""
|
||||||
log
|
log
|
||||||
|
|||||||
@@ -9,6 +9,8 @@ import os
|
|||||||
|
|
||||||
|
|
||||||
def run(t):
|
def run(t):
|
||||||
|
if not t.skip_unless("httpsrv"):
|
||||||
|
return
|
||||||
root = os.path.join(t.tmpdir, "pp")
|
root = os.path.join(t.tmpdir, "pp")
|
||||||
os.makedirs(root, exist_ok=True)
|
os.makedirs(root, exist_ok=True)
|
||||||
with open(os.path.join(root, "a.html"), "w") as fp:
|
with open(os.path.join(root, "a.html"), "w") as fp:
|
||||||
|
|||||||
@@ -2,6 +2,8 @@
|
|||||||
|
|
||||||
|
|
||||||
def run(t):
|
def run(t):
|
||||||
|
if not t.skip_unless("httpsrv"):
|
||||||
|
return
|
||||||
srv = t.free_port()
|
srv = t.free_port()
|
||||||
srv2 = t.free_port()
|
srv2 = t.free_port()
|
||||||
t.start("httpsrv_rules", f"""
|
t.start("httpsrv_rules", f"""
|
||||||
|
|||||||
@@ -7,6 +7,8 @@ nscache6: nscache holds the IPv4 side and nothing else.
|
|||||||
|
|
||||||
|
|
||||||
def run(t):
|
def run(t):
|
||||||
|
if not t.skip_unless("httpsrv", "ipv6"):
|
||||||
|
return
|
||||||
if not t.has_ipv6():
|
if not t.has_ipv6():
|
||||||
t.skip("IPv6 (this machine has no IPv6 loopback)")
|
t.skip("IPv6 (this machine has no IPv6 loopback)")
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -0,0 +1,109 @@
|
|||||||
|
"""maxconn: a service serves at most that many connections at once, and a
|
||||||
|
connection over the limit waits for one of them to finish."""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import signal
|
||||||
|
import socket
|
||||||
|
import time
|
||||||
|
|
||||||
|
|
||||||
|
def run(t):
|
||||||
|
if not t.skip_unless("httpsrv"):
|
||||||
|
return
|
||||||
|
# The origin runs in a process of its own, so the limit only applies to
|
||||||
|
# the mapper in front of it.
|
||||||
|
origin = t.free_port()
|
||||||
|
t.start("maxconn_origin", f"""
|
||||||
|
auth iponly
|
||||||
|
allow *
|
||||||
|
http echo * /echo**
|
||||||
|
httpsrv -p{origin}
|
||||||
|
""", ports=[origin])
|
||||||
|
|
||||||
|
mapped = t.free_port()
|
||||||
|
server = t.start("maxconn", f"""
|
||||||
|
log
|
||||||
|
maxconn 2
|
||||||
|
auth iponly
|
||||||
|
allow *
|
||||||
|
tcppm {mapped} 127.0.0.1 {origin}
|
||||||
|
""", ports=[mapped])
|
||||||
|
|
||||||
|
def connect():
|
||||||
|
sock = socket.create_connection(("127.0.0.1", mapped), 5)
|
||||||
|
opened.append(sock)
|
||||||
|
return sock
|
||||||
|
|
||||||
|
def served(sock, timeout):
|
||||||
|
"""Ask over a kept alive connection; True once the whole reply is in,
|
||||||
|
so the connection is ready for the next request."""
|
||||||
|
sock.sendall(b"GET /echo HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n")
|
||||||
|
sock.settimeout(timeout)
|
||||||
|
data = b""
|
||||||
|
try:
|
||||||
|
while b"\r\n\r\n" not in data:
|
||||||
|
chunk = sock.recv(4096)
|
||||||
|
if not chunk:
|
||||||
|
return False
|
||||||
|
data += chunk
|
||||||
|
head, body = data.split(b"\r\n\r\n", 1)
|
||||||
|
length = 0
|
||||||
|
for line in head.split(b"\r\n")[1:]:
|
||||||
|
name, _, value = line.partition(b":")
|
||||||
|
if name.strip().lower() == b"content-length":
|
||||||
|
length = int(value)
|
||||||
|
while len(body) < length:
|
||||||
|
chunk = sock.recv(4096)
|
||||||
|
if not chunk:
|
||||||
|
return False
|
||||||
|
body += chunk
|
||||||
|
return head.startswith(b"HTTP/1.1 200")
|
||||||
|
except OSError:
|
||||||
|
return False
|
||||||
|
|
||||||
|
opened = []
|
||||||
|
try:
|
||||||
|
# the probe that saw the port open holds a slot until its session
|
||||||
|
# ends, so wait for both slots to be free before taking them
|
||||||
|
deadline = time.time() + 5
|
||||||
|
while True:
|
||||||
|
first, second = connect(), connect()
|
||||||
|
both = served(first, 1) and served(second, 1)
|
||||||
|
if both or time.time() > deadline:
|
||||||
|
break
|
||||||
|
first.close()
|
||||||
|
second.close()
|
||||||
|
t.eq(True, both, "two connections are served under maxconn 2")
|
||||||
|
|
||||||
|
third = connect()
|
||||||
|
t.eq(False, served(third, 1.5),
|
||||||
|
"a third connection waits while both slots are held")
|
||||||
|
t.contains(t.wait_output(server, "too many connected clients"),
|
||||||
|
"too many connected clients",
|
||||||
|
"a service at its limit says so in the log")
|
||||||
|
|
||||||
|
first.close()
|
||||||
|
t.eq(True, served(third, 5),
|
||||||
|
"the waiting connection is served once a slot is freed")
|
||||||
|
t.eq(True, served(second, 5),
|
||||||
|
"a connection holding a slot keeps being served")
|
||||||
|
|
||||||
|
if os.name == "nt":
|
||||||
|
t.skip("reload while at the limit (no SIGUSR1 on Windows)")
|
||||||
|
else:
|
||||||
|
waiting = connect()
|
||||||
|
t.eq(False, served(waiting, 1),
|
||||||
|
"the limit holds again with two connections open")
|
||||||
|
server.proc.send_signal(signal.SIGUSR1)
|
||||||
|
# A connection made the instant the signal arrives can land on
|
||||||
|
# the listener being replaced and be reset; give the new service
|
||||||
|
# the moment it needs.
|
||||||
|
time.sleep(1.5)
|
||||||
|
fresh = connect()
|
||||||
|
t.eq(True, served(fresh, 5),
|
||||||
|
"a reload while the limit is reached starts a service with "
|
||||||
|
"its slots free")
|
||||||
|
t.eq(None, server.proc.poll(), "the process survives the reload")
|
||||||
|
finally:
|
||||||
|
for sock in opened:
|
||||||
|
sock.close()
|
||||||
@@ -30,6 +30,8 @@ def wait_served(server, needle, count, since=0, timeout=5.0):
|
|||||||
|
|
||||||
|
|
||||||
def run(t):
|
def run(t):
|
||||||
|
if not t.skip_unless("httpsrv"):
|
||||||
|
return
|
||||||
srv = t.free_port()
|
srv = t.free_port()
|
||||||
good = t.free_port()
|
good = t.free_port()
|
||||||
spare = t.free_port()
|
spare = t.free_port()
|
||||||
|
|||||||
@@ -46,6 +46,8 @@ UNHONOURED = (1, 99)
|
|||||||
|
|
||||||
|
|
||||||
def run(t):
|
def run(t):
|
||||||
|
if not t.skip_unless("httpsrv"):
|
||||||
|
return
|
||||||
srv = t.free_port()
|
srv = t.free_port()
|
||||||
prx = t.free_port()
|
prx = t.free_port()
|
||||||
sks = t.free_port()
|
sks = t.free_port()
|
||||||
@@ -107,10 +109,16 @@ def run(t):
|
|||||||
"peer.port")
|
"peer.port")
|
||||||
t.in_range(port, MLOW, MHIGH, "CONNECT uses the range its rule sets")
|
t.in_range(port, MLOW, MHIGH, "CONNECT uses the range its rule sets")
|
||||||
|
|
||||||
# a plain GET matches the later rule, which sets no range
|
# a plain GET matches the later rule, which sets no range. On Linux the
|
||||||
port = int_field(t.http(origin + "/echo", proxy=method_proxy), "peer.port")
|
# window lies within the ephemeral range, so an ephemeral port falls in
|
||||||
t.not_in_range(port, MLOW, MHIGH,
|
# it now and then by chance: bound to the window every port would, so
|
||||||
"a method outside that rule keeps an ephemeral port")
|
# one of a few outside it tells them apart.
|
||||||
|
ports = [int_field(t.http(origin + "/echo", proxy=method_proxy), "peer.port")
|
||||||
|
for _ in range(5)]
|
||||||
|
outside = [p for p in ports if isinstance(p, int) and not MLOW <= p <= MHIGH]
|
||||||
|
t.ok(f"a method outside that rule keeps an ephemeral port ({ports})") if outside else \
|
||||||
|
t.fail("a method outside that rule keeps an ephemeral port",
|
||||||
|
f"some outside {MLOW}-{MHIGH}", ports)
|
||||||
|
|
||||||
# --- a range the platform cannot honour --------------------------------
|
# --- a range the platform cannot honour --------------------------------
|
||||||
# Linux ignores a range outside net.ipv4.ip_local_port_range, and any
|
# Linux ignores a range outside net.ipv4.ip_local_port_range, and any
|
||||||
|
|||||||
@@ -37,6 +37,8 @@ def wait_served(server, needle, count, since=0, timeout=5.0):
|
|||||||
|
|
||||||
|
|
||||||
def run(t):
|
def run(t):
|
||||||
|
if not t.skip_unless("httpsrv"):
|
||||||
|
return
|
||||||
adm = t.free_port()
|
adm = t.free_port()
|
||||||
prx = t.free_port()
|
prx = t.free_port()
|
||||||
dummy = t.free_port()
|
dummy = t.free_port()
|
||||||
|
|||||||
@@ -20,6 +20,8 @@ def _has_pcre(t):
|
|||||||
|
|
||||||
|
|
||||||
def run(t):
|
def run(t):
|
||||||
|
if not t.skip_unless("httpsrv", "pcre"):
|
||||||
|
return
|
||||||
if not _has_pcre(t):
|
if not _has_pcre(t):
|
||||||
t.skip("PCRE (this build has no PCRE support)")
|
t.skip("PCRE (this build has no PCRE support)")
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -1,7 +1,33 @@
|
|||||||
"""The port mappers: tcppm forwards a TCP port, udppm a UDP one."""
|
"""The port mappers: tcppm forwards a TCP port, udppm a UDP one."""
|
||||||
|
|
||||||
|
import socket
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
|
||||||
|
HALFCLOSE_SIZE = 20000000
|
||||||
|
|
||||||
|
|
||||||
|
def halfclose_origin(listener):
|
||||||
|
"""Answers each connection which asks for something with HALFCLOSE_SIZE
|
||||||
|
bytes, then waits for the client's end of the stream and closes. The
|
||||||
|
connections waiting for the service to start ask nothing."""
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
c, _ = listener.accept()
|
||||||
|
except OSError:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
if c.recv(1000):
|
||||||
|
c.sendall(b"x" * HALFCLOSE_SIZE)
|
||||||
|
c.recv(10)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
c.close()
|
||||||
|
|
||||||
|
|
||||||
def run(t):
|
def run(t):
|
||||||
|
if not t.skip_unless("httpsrv"):
|
||||||
|
return
|
||||||
# --- tcppm ---------------------------------------------------------
|
# --- tcppm ---------------------------------------------------------
|
||||||
origin = t.free_port()
|
origin = t.free_port()
|
||||||
mapped = t.free_port()
|
mapped = t.free_port()
|
||||||
@@ -40,6 +66,41 @@ def run(t):
|
|||||||
|
|
||||||
t.stop_all()
|
t.stop_all()
|
||||||
|
|
||||||
|
# A client which shuts down its sending side still gets the whole answer,
|
||||||
|
# even when it reads slowly: the server has finished and closed by then,
|
||||||
|
# and the rest of the answer waits in the proxy's buffer and the kernel's.
|
||||||
|
listener = socket.socket()
|
||||||
|
listener.bind(("127.0.0.1", 0))
|
||||||
|
listener.listen(1)
|
||||||
|
threading.Thread(target=halfclose_origin, args=(listener,), daemon=True).start()
|
||||||
|
halfclosed = t.free_port()
|
||||||
|
t.start("portmap_halfclose", f"""
|
||||||
|
log
|
||||||
|
auth none
|
||||||
|
tcppm {halfclosed} 127.0.0.1 {listener.getsockname()[1]}
|
||||||
|
""", ports=[halfclosed])
|
||||||
|
s = socket.socket()
|
||||||
|
s.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 32768)
|
||||||
|
s.settimeout(30)
|
||||||
|
got = 0
|
||||||
|
try:
|
||||||
|
s.connect(("127.0.0.1", halfclosed))
|
||||||
|
s.sendall(b"request")
|
||||||
|
s.shutdown(socket.SHUT_WR)
|
||||||
|
time.sleep(1)
|
||||||
|
while True:
|
||||||
|
d = s.recv(65536)
|
||||||
|
if not d:
|
||||||
|
break
|
||||||
|
got += len(d)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
s.close()
|
||||||
|
listener.close()
|
||||||
|
t.eq(HALFCLOSE_SIZE, got, "a half-closed client reading slowly gets the whole answer")
|
||||||
|
|
||||||
|
t.stop_all()
|
||||||
|
|
||||||
# --- udppm ---------------------------------------------------------
|
# --- udppm ---------------------------------------------------------
|
||||||
# something has to be listening for the mapped datagrams to go anywhere
|
# something has to be listening for the mapped datagrams to go anywhere
|
||||||
echo = t.udp_echo()
|
echo = t.udp_echo()
|
||||||
|
|||||||
@@ -6,6 +6,8 @@ from a clean list.
|
|||||||
|
|
||||||
|
|
||||||
def run(t):
|
def run(t):
|
||||||
|
if not t.skip_unless("httpsrv"):
|
||||||
|
return
|
||||||
srv = t.free_port()
|
srv = t.free_port()
|
||||||
other = t.free_port()
|
other = t.free_port()
|
||||||
prx = t.free_port()
|
prx = t.free_port()
|
||||||
|
|||||||
@@ -2,6 +2,8 @@
|
|||||||
|
|
||||||
|
|
||||||
def run(t):
|
def run(t):
|
||||||
|
if not t.skip_unless("httpsrv"):
|
||||||
|
return
|
||||||
srv = t.free_port()
|
srv = t.free_port()
|
||||||
sks = t.free_port()
|
sks = t.free_port()
|
||||||
sauth = t.free_port()
|
sauth = t.free_port()
|
||||||
|
|||||||
@@ -11,6 +11,8 @@ def _no_tls(t, server):
|
|||||||
|
|
||||||
|
|
||||||
def run(t):
|
def run(t):
|
||||||
|
if not t.skip_unless("httpsrv", "ssl"):
|
||||||
|
return
|
||||||
certs = t.certs()
|
certs = t.certs()
|
||||||
if not certs:
|
if not certs:
|
||||||
t.skip("TLS (openssl is not available to generate certificates)")
|
t.skip("TLS (openssl is not available to generate certificates)")
|
||||||
|
|||||||
@@ -2,6 +2,8 @@
|
|||||||
|
|
||||||
|
|
||||||
def run(t):
|
def run(t):
|
||||||
|
if not t.skip_unless("httpsrv", "ssl"):
|
||||||
|
return
|
||||||
certs = t.certs()
|
certs = t.certs()
|
||||||
if not certs:
|
if not certs:
|
||||||
t.skip("tlspr (openssl is not available to generate certificates)")
|
t.skip("tlspr (openssl is not available to generate certificates)")
|
||||||
|
|||||||
@@ -39,6 +39,8 @@ def _config(t, name, body):
|
|||||||
|
|
||||||
|
|
||||||
def run(t):
|
def run(t):
|
||||||
|
if not t.skip_unless("httpsrv"):
|
||||||
|
return
|
||||||
# --- the command and its modes ------------------------------------
|
# --- the command and its modes ------------------------------------
|
||||||
# These need no redirection, so they run wherever the feature is built.
|
# These need no redirection, so they run wherever the feature is built.
|
||||||
out = _config(t, "transparent_probe", "log\ntransparent")
|
out = _config(t, "transparent_probe", "log\ntransparent")
|
||||||
|
|||||||
@@ -0,0 +1,141 @@
|
|||||||
|
"""Unix domain sockets: a service listening on one (-iunix:PATH, and on
|
||||||
|
Linux an abstract -iunix:@NAME), tcppm forwarding to one (DSTADDR
|
||||||
|
unix:PATH), a parent reached through one (parent ... unix:PATH), and a
|
||||||
|
listening one across reloads: each reload's service binding it anew, its
|
||||||
|
file kept while a service listens on it and removed once none does."""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import socket
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
|
||||||
|
|
||||||
|
def unix_get(path, url, timeout=10):
|
||||||
|
"""A GET for url sent to the proxy at the Unix socket path (a leading @
|
||||||
|
for an abstract one): (status, body length), or (None, error)."""
|
||||||
|
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||||
|
s.settimeout(timeout)
|
||||||
|
try:
|
||||||
|
s.connect("\0" + path[1:] if path.startswith("@") else path)
|
||||||
|
s.sendall(f"GET {url} HTTP/1.0\r\nHost: unix\r\n\r\n".encode())
|
||||||
|
got = b""
|
||||||
|
while True:
|
||||||
|
b = s.recv(65536)
|
||||||
|
if not b:
|
||||||
|
break
|
||||||
|
got += b
|
||||||
|
except OSError as e:
|
||||||
|
return None, str(e)
|
||||||
|
finally:
|
||||||
|
s.close()
|
||||||
|
head, _, body = got.partition(b"\r\n\r\n")
|
||||||
|
try:
|
||||||
|
return int(head.split()[1]), len(body)
|
||||||
|
except (IndexError, ValueError):
|
||||||
|
return None, head[:80]
|
||||||
|
|
||||||
|
|
||||||
|
def run(t):
|
||||||
|
if not t.skip_unless("httpsrv", "unix"):
|
||||||
|
return
|
||||||
|
if not hasattr(socket, "AF_UNIX") or sys.platform.startswith("win"):
|
||||||
|
t.skip("Unix domain sockets (not on this platform)")
|
||||||
|
return
|
||||||
|
|
||||||
|
origin = t.free_port()
|
||||||
|
mapped = t.free_port()
|
||||||
|
chained = t.free_port()
|
||||||
|
adm = t.free_port()
|
||||||
|
path = os.path.join(t.tmpdir, "px.sock")
|
||||||
|
abstract = f"@3proxy-test-{os.getpid()}" if sys.platform.startswith("linux") else None
|
||||||
|
url = f"http://127.0.0.1:{origin}/data?size=1000"
|
||||||
|
|
||||||
|
def config(unix=True):
|
||||||
|
services = f"""
|
||||||
|
flush
|
||||||
|
auth iponly
|
||||||
|
allow *
|
||||||
|
proxy -iunix:{path}
|
||||||
|
""" if unix else ""
|
||||||
|
if unix and abstract:
|
||||||
|
services += f"""
|
||||||
|
proxy -iunix:{abstract}
|
||||||
|
"""
|
||||||
|
if unix:
|
||||||
|
services += f"""
|
||||||
|
flush
|
||||||
|
auth iponly
|
||||||
|
allow *
|
||||||
|
tcppm {mapped} unix:{path} 0
|
||||||
|
|
||||||
|
flush
|
||||||
|
auth iponly
|
||||||
|
allow *
|
||||||
|
parent 1000 http unix:{path} 0
|
||||||
|
proxy -p{chained}
|
||||||
|
"""
|
||||||
|
return f"""
|
||||||
|
log
|
||||||
|
auth iponly
|
||||||
|
allow *
|
||||||
|
http data * /data
|
||||||
|
httpsrv -p{origin}
|
||||||
|
{services}
|
||||||
|
flush
|
||||||
|
auth iponly
|
||||||
|
allow *
|
||||||
|
admin -p{adm}
|
||||||
|
"""
|
||||||
|
|
||||||
|
server = t.start("unixsock", config(), ports=[origin, mapped, chained, adm])
|
||||||
|
# a build without Unix sockets (NO_UN) never makes the file
|
||||||
|
deadline = time.time() + 5
|
||||||
|
while time.time() < deadline and not os.path.exists(path):
|
||||||
|
time.sleep(0.05)
|
||||||
|
if not os.path.exists(path):
|
||||||
|
t.skip("Unix domain sockets (not supported by this build)")
|
||||||
|
return
|
||||||
|
|
||||||
|
# --- a proxy listening on a Unix socket ---------------------------------
|
||||||
|
t.eq((200, 1000), unix_get(path, url), "a proxy listening on a Unix socket answers")
|
||||||
|
if abstract:
|
||||||
|
t.eq((200, 1000), unix_get(abstract, url),
|
||||||
|
"a proxy listening on an abstract Unix socket answers")
|
||||||
|
|
||||||
|
# --- tcppm forwarding to a Unix socket: the proxy behind it answers -----
|
||||||
|
r = t.http(url, proxy=f"127.0.0.1:{mapped}")
|
||||||
|
t.eq(200, r.status, "tcppm forwards a TCP port to a Unix socket")
|
||||||
|
t.eq(1000, r.length, "and the whole answer comes back through it")
|
||||||
|
|
||||||
|
# --- a parent reached through a Unix socket ------------------------------
|
||||||
|
r = t.http(url, proxy=f"127.0.0.1:{chained}")
|
||||||
|
t.eq(200, r.status, "a proxy chains to a parent on a Unix socket")
|
||||||
|
t.eq(1000, r.length, "and the whole answer comes back through the chain")
|
||||||
|
|
||||||
|
# --- reloads: each new service binds the path anew; the old one, closing
|
||||||
|
# after, must not remove the new one's file ----------------------------
|
||||||
|
for i in range(3):
|
||||||
|
before = server.output().count("Accepting connections")
|
||||||
|
t.write_config("unixsock", config())
|
||||||
|
t.http(f"http://127.0.0.1:{adm}/R")
|
||||||
|
deadline = time.time() + 10
|
||||||
|
while time.time() < deadline and server.output().count("Accepting connections") < before + 5:
|
||||||
|
time.sleep(0.05)
|
||||||
|
# the old services stop within a second of each reload
|
||||||
|
time.sleep(1.5)
|
||||||
|
t.ok("after three reloads the socket file is still there") if os.path.exists(path) else \
|
||||||
|
t.fail("after three reloads the socket file is still there", path, "missing")
|
||||||
|
t.eq((200, 1000), unix_get(path, url), "and the proxy answers on it")
|
||||||
|
|
||||||
|
# --- no service listens there any more: the file goes -------------------
|
||||||
|
t.write_config("unixsock", config(unix=False))
|
||||||
|
t.http(f"http://127.0.0.1:{adm}/R")
|
||||||
|
deadline = time.time() + 5
|
||||||
|
while time.time() < deadline and os.path.exists(path):
|
||||||
|
time.sleep(0.1)
|
||||||
|
t.ok("once no service listens on it the socket file is removed") \
|
||||||
|
if not os.path.exists(path) else \
|
||||||
|
t.fail("once no service listens on it the socket file is removed", "no file", path)
|
||||||
|
got = unix_get(path, url, timeout=2)
|
||||||
|
t.ok("and nothing answers there") if got[0] is None else \
|
||||||
|
t.fail("and nothing answers there", "no connection", got)
|
||||||
+21
-1
@@ -122,10 +122,11 @@ class Failure(Exception):
|
|||||||
class Tester:
|
class Tester:
|
||||||
"""The API a case runs against: start servers, make requests, assert."""
|
"""The API a case runs against: start servers, make requests, assert."""
|
||||||
|
|
||||||
def __init__(self, binary, tmpdir, case):
|
def __init__(self, binary, tmpdir, case, features=None):
|
||||||
self.binary = binary
|
self.binary = binary
|
||||||
self.tmpdir = tmpdir
|
self.tmpdir = tmpdir
|
||||||
self.case = case
|
self.case = case
|
||||||
|
self.features = features if features is not None else frozenset()
|
||||||
self.servers = []
|
self.servers = []
|
||||||
self.checks = []
|
self.checks = []
|
||||||
self.timeout = 10
|
self.timeout = 10
|
||||||
@@ -135,6 +136,25 @@ class Tester:
|
|||||||
self.logs = []
|
self.logs = []
|
||||||
self.udp_servers = []
|
self.udp_servers = []
|
||||||
|
|
||||||
|
# ---- build features ----------------------------------------------
|
||||||
|
|
||||||
|
def has(self, *names):
|
||||||
|
"""Whether the binary reports every named feature."""
|
||||||
|
return all(name in self.features for name in names)
|
||||||
|
|
||||||
|
def skip_unless(self, *names):
|
||||||
|
"""Skip what needs a feature the binary was built without.
|
||||||
|
|
||||||
|
Returns False after recording the skip, so a case says
|
||||||
|
`if not t.skip_unless("ssl"): return` and keeps its checks out of
|
||||||
|
the failed count on a build that cannot pass them.
|
||||||
|
"""
|
||||||
|
missing = [name for name in names if name not in self.features]
|
||||||
|
if not missing:
|
||||||
|
return True
|
||||||
|
self.skip("built without: " + ", ".join(missing))
|
||||||
|
return False
|
||||||
|
|
||||||
# ---- servers -----------------------------------------------------
|
# ---- servers -----------------------------------------------------
|
||||||
|
|
||||||
def has_ipv6(self):
|
def has_ipv6(self):
|
||||||
|
|||||||
+34
-1
@@ -47,6 +47,37 @@ def load_case(path):
|
|||||||
return name, module
|
return name, module
|
||||||
|
|
||||||
|
|
||||||
|
def built_features(binary):
|
||||||
|
"""The features the binary reports in `3proxy --help`, as a set.
|
||||||
|
|
||||||
|
A binary too old to have the list, or one that cannot be run at all,
|
||||||
|
reports nothing: every case that needs a feature then skips, and the
|
||||||
|
ones that need none still run.
|
||||||
|
"""
|
||||||
|
import subprocess
|
||||||
|
try:
|
||||||
|
done = subprocess.run([binary, "--help"], stdout=subprocess.PIPE,
|
||||||
|
stderr=subprocess.STDOUT, timeout=15)
|
||||||
|
text = done.stdout.decode("utf-8", "replace")
|
||||||
|
except (OSError, subprocess.SubprocessError):
|
||||||
|
return frozenset()
|
||||||
|
features = set()
|
||||||
|
collecting = False
|
||||||
|
for line in text.splitlines():
|
||||||
|
stripped = line.strip()
|
||||||
|
if line.startswith("built with:"):
|
||||||
|
collecting = True
|
||||||
|
rest = stripped[len("built with:"):].strip()
|
||||||
|
if rest:
|
||||||
|
features.update(rest.split())
|
||||||
|
continue
|
||||||
|
if collecting:
|
||||||
|
if not line[:1].isspace() or not stripped:
|
||||||
|
break
|
||||||
|
features.update(stripped.split())
|
||||||
|
return frozenset(features)
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
parser = argparse.ArgumentParser()
|
parser = argparse.ArgumentParser()
|
||||||
parser.add_argument("pattern", nargs="?", default="",
|
parser.add_argument("pattern", nargs="?", default="",
|
||||||
@@ -75,7 +106,9 @@ def main():
|
|||||||
return 2
|
return 2
|
||||||
|
|
||||||
tmpdir = tempfile.mkdtemp(prefix="3proxy-tests.")
|
tmpdir = tempfile.mkdtemp(prefix="3proxy-tests.")
|
||||||
|
features = built_features(binary)
|
||||||
print(f"3proxy tests: {binary}")
|
print(f"3proxy tests: {binary}")
|
||||||
|
print(f"built with: {' '.join(sorted(features)) or '(nothing reported)'}")
|
||||||
print(f"working in: {tmpdir}\n")
|
print(f"working in: {tmpdir}\n")
|
||||||
|
|
||||||
passed = failed = skipped = 0
|
passed = failed = skipped = 0
|
||||||
@@ -85,7 +118,7 @@ def main():
|
|||||||
for path in paths:
|
for path in paths:
|
||||||
name, module = load_case(path)
|
name, module = load_case(path)
|
||||||
print(f" {name}")
|
print(f" {name}")
|
||||||
tester = Tester(binary, tmpdir, name)
|
tester = Tester(binary, tmpdir, name, features)
|
||||||
error = None
|
error = None
|
||||||
try:
|
try:
|
||||||
module.run(tester)
|
module.run(tester)
|
||||||
|
|||||||
Reference in new issue
Block a user