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
|
||||
- target: mediatek/filogic
|
||||
arch: aarch64_cortex-a53
|
||||
runs-on: ubuntu-latest
|
||||
# 26.04: the OpenWrt SDK refuses its non-GNU install
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
|
||||
@@ -18,7 +18,8 @@ jobs:
|
||||
strategy:
|
||||
matrix:
|
||||
target:
|
||||
- ubuntu-latest
|
||||
# 26.04: rpm 6 runs %__gpg_sign_cmd differently, signing fails
|
||||
- ubuntu-24.04
|
||||
runs-on: ${{ matrix.target }}
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
@@ -40,6 +40,8 @@ jobs:
|
||||
run: |
|
||||
echo "volatile char VerSion[]=^"3APA3A-3proxy-Internal-Build: 3proxy-%RELEASE%-%NOW%\r\n^";" >>src/3proxy.c
|
||||
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
|
||||
shell: cmd
|
||||
run: |
|
||||
|
||||
@@ -273,3 +273,4 @@ bin/3proxy_udppm
|
||||
build*/*
|
||||
testcerts/
|
||||
/.claude
|
||||
bench/mix/mix-linux-*
|
||||
@@ -1,25 +1,25 @@
|
||||
3proxy-1.0.1 Released October, 10 2026
|
||||
3proxy-1.0.2 Released October, 24 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: -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: SOCKSv5 UDP ASSOCIATE over IPv6: the source address of a datagram was truncated and the reply was sent to the wrong address (#1279)
|
||||
! 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: 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: buffer could be insufficient for the headers the HTTP proxy adds after a pcre_rewrite had grown the request
|
||||
! 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: pcre_extend did nothing, the rules it appended were never consulted; the manual described an argument the command does not take
|
||||
! 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
|
||||
! Fix: null pointer dereference in ftppr on PASS without USER and in smtpp on a user name without a host
|
||||
! 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
|
||||
! 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
|
||||
! 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)
|
||||
+24
-24
@@ -1,25 +1,25 @@
|
||||
3proxy-1.0.1 Вышел 10 Октября 2026
|
||||
3proxy-1.0.2 Вышел 24 Октября 2026
|
||||
|
||||
! Исправление: падение (segmentation fault) при перезагрузке конфигурации (SIGUSR1) на нагруженном сервере: закрывающаяся сессия могла обращаться к службе после того, как перезагрузка её освободила; гонка существовала с 0.9.7, а добавленная в 0.9.9 задержка закрытия (linger) в 5 секунд сделала её гораздо вероятнее (#1278)
|
||||
! Исправление: -Di и -De (привязка к интерфейсу) не применялись к сокетам SOCKSv5 UDP ASSOCIATE и BIND, к соединению данных FTP прокси и к обратному соединению (connect back) (#1277)
|
||||
! Исправление: SOCKSv5 UDP ASSOCIATE по IPv6: адрес отправителя датаграммы обрезался, и ответ отправлялся не на тот адрес (#1279)
|
||||
! Исправление: SOCKSv5 UDP ASSOCIATE: правило доступа с именами хостов срабатывало для любой датаграммы, отправленной на адрес, а не на имя; теперь адрес используется как имя хоста, так же как для запросов TCP
|
||||
! Исправление: запрос, изменённый pcre_rewrite, только записывался в журнал, а при прямом соединении серверу отправлялся без изменений; теперь сервер получает изменённые путь и строку запроса
|
||||
! Исправление: буфера могло не хватить для заголовков, добавляемых HTTP прокси, после того как pcre_rewrite увеличил запрос
|
||||
! Исправление: переполнение буфера в куче в pcre_rewrite: ссылка $N на группу, не участвовавшую в совпадении, выводилась своими цифрами, которые не учитывались при выделении памяти под результат
|
||||
! Исправление: pcre_extend ничего не делал, добавленные им правила никогда не проверялись; в документации был описан аргумент, который команда не принимает
|
||||
! Исправление: сертификаты, создаваемые для TLS MitM (openssl), не содержали идентификаторов ключа субъекта и издателя и отвергались строгой проверкой, в том числе клиентами macOS, OpenSSL с x509_strict и Python 3.13
|
||||
! Исправление: обращение по нулевому указателю в ftppr при PASS без USER и в smtpp при имени пользователя без хоста
|
||||
! Исправление: с wolfSSL на glibc не запускалась ни одна служба: стека потока по умолчанию не хватало для thread-local памяти wolfSSL, pthread_create() завершался ошибкой, о которой не сообщалось
|
||||
! Исправление: 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: доверия он не давал и вызывал ложные срабатывания антивирусов
|
||||
! Исправление: dnspr передавал клиенту то, что первым пришло на сокет, с которого он обращался к серверу имён, с любого адреса и с любым id, так что поддельный ответ мог быть передан клиенту; теперь запрос отправляется со случайным id, и передаётся только ответ от того сервера имён, к которому обращались, с этим id и тем же вопросом
|
||||
! Исправление: клиент, отправивший часть записи TLS и затем ничего, занимал поток на всё процессорное время, и чтение не завершалось по таймауту
|
||||
! Исправление: без -Ne ответ на SOCKS CONNECT и BIND содержал адрес соединения клиента с прокси вместо адреса сокета в сторону назначения: клиенту BIND сообщался собственный порт прокси, и удалённая сторона не могла к нему подключиться (с 0.9.6)
|
||||
! Исправление: клиент, закрывший свою сторону передачи (half-close), мог получить ответ не полностью, на больших ответах без нескольких мегабайт; так же обрезалась загрузка на сервер после того, как сервер закрыл свою сторону
|
||||
! Исправление: при chroot всё местное время становилось UTC и все сообщения syslog терялись: часовой пояс теперь загружается, а syslog подключается до chroot; в описании chroot в 3proxy.cfg(5) перечислено, что ещё нужно внутри chroot для PAM, LDAP и ODBC
|
||||
! Исправление: HTTP прокси закрывал соединение с сервером для клиента с keep-alive и открывал новое, когда менялся только метод запроса (POST после GET к тому же хосту)
|
||||
! Исправление: последний ssl_client_mode в конфигурации действовал для всех служб, а перезагрузка конфигурации меняла его для уже работающих служб
|
||||
! Исправление: утечки памяти: при каждой отвергнутой перезагрузке конфигурации, при каждом неудачном согласовании TLS, пути CA сервера каждой службы с TLS, скомпилированные имена хостов pcre: / regex: в правилах доступа и шаблоны правил httpsrv
|
||||
! Исправление: сокеты Unix: в Linux прокси, слушающий на сокете Unix, передавал только первые байты ответа (результат 95); абстрактный сокет (unix:@NAME) привязывался к имени, дополненному нулями, до которого клиенты не доходили; tcppm отвергал порт 0 для цели unix:, как в примере из документации; при перезагрузке конфигурации файл сокета слушающей службы удалялся
|
||||
! Исправление: SIGPIPE мог завершить 3proxy, если клиент отключался во время запуска служб, а отдельные службы (proxy, socks, ...) — в любой момент; отправка данных использует MSG_NOSIGNAL там, где система его поддерживает
|
||||
! Исправление: TLS MitM не работал ни для одного соединения с wolfSSL, собранным с WOLFSSL_QT (wolfSSL 5.9.1 в Ubuntu 26.04): не удавалось скопировать серийный номер исходного сертификата; в этом случае используется серийный номер, полученный из хеша исходного сертификата
|
||||
! Исправление: Windows: при закрытии соединения сокет мог остаться открытым (SO_LINGER на неблокирующем сокете) или соединение сбрасывалось, пока другая сторона ещё передавала данные, так что конец ответа мог потеряться
|
||||
! Исправление: httpsrv: тело запроса, на который ответ дан без его чтения (например, когда требуется аутентификация), читалось как следующий запрос; клиент, ещё передающий данные при закрытии соединения без keep-alive, мог получить сброс соединения вместо ответа
|
||||
! Исправление: httpsrv в Windows: не работали пути UNC (\\server\share)
|
||||
! Исправление: службы httpsrv и admin и их клиенты назывались ZOMBIE на странице служб admin, в %N журнала и в RADIUS
|
||||
! Исправление: сборка Watcom (lite) не компилировалась, в 1.0.1 для неё не было двоичных файлов
|
||||
+ -s (splice) по направлениям: -s1 — то, что передаёт сервер (скачивание), -s2 — то, что передаёт клиент (загрузка), -s3 — оба; -s без числа использует splice только там, где это выгодно (большие тела, длинные потоки); каналы (pipe) сохраняются с соединением для следующих запросов. splice() снова собирается по умолчанию в Linux и используется только службами с -s
|
||||
+ Опции сокетов (-oc, -os, -ol, -or, -oR) принимают ИМЯ=ЗНАЧЕНИЕ; ИМЯ=0 выключает опцию, в том числе установленную по умолчанию; неизвестное имя или значение, не являющееся числом, — ошибка
|
||||
+ HTTP прокси освобождает буфер запроса размером 64 КБ, пока туннель CONNECT передаёт данные и пока соединение с keep-alive ждёт следующего запроса: 2000 туннелей занимают 213 МБ вместо 339 МБ
|
||||
+ Записи TLS читаются с упреждением (read-ahead) с OpenSSL 1.1.0 и новее: расшифровка занимает на 9-14% меньше процессорного времени
|
||||
+ Более быстрая остановка служб и перезагрузка конфигурации, без фиксированных задержек; соединение, ожидающее свободного места в maxconn, получает его сразу
|
||||
- TCP_NODELAY устанавливается по умолчанию на сокетах прокси-клиент и прокси-сервер; -ocTCP_NODELAY=0 / -osTCP_NODELAY=0 выключает его
|
||||
- HTTP прокси обрабатывает адреса ftp:// только если службе задана новая опция -Xftp (в сборке с FTP=true)
|
||||
+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_PAM "Enable PAM/PamAuth" ON)
|
||||
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_WSAPOLL "Use WSAPoll instead of select() (Windows 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)
|
||||
# ============================================================================
|
||||
|
||||
# Common object library (sockmap, sockgetchar, common, log)
|
||||
# Common object library (sockmap, sockgetchar, common, sem, log)
|
||||
add_library(common_obj OBJECT
|
||||
src/sockmap.c
|
||||
src/sockgetchar.c
|
||||
src/common.c
|
||||
src/sem.c
|
||||
src/log.c
|
||||
)
|
||||
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
|
||||
)
|
||||
|
||||
target_compile_definitions(${PROXY_NAME} PRIVATE
|
||||
WITHMAIN
|
||||
NOPORTMAP
|
||||
)
|
||||
target_compile_definitions(${PROXY_NAME} PRIVATE WITHMAIN)
|
||||
|
||||
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)
|
||||
endif()
|
||||
|
||||
@@ -743,8 +744,12 @@ foreach(PROXY_NAME proxy socks pop3p imapp smtpp ftppr tcppm udppm tlspr)
|
||||
target_compile_definitions(${PROXY_NAME} PRIVATE ANONYMOUS)
|
||||
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")
|
||||
target_compile_definitions(${PROXY_NAME} PRIVATE PORTMAP)
|
||||
else()
|
||||
target_compile_definitions(${PROXY_NAME} PRIVATE NOPORTMAP)
|
||||
endif()
|
||||
|
||||
if(WIN32)
|
||||
|
||||
+4
-4
@@ -4,9 +4,9 @@
|
||||
# add -DWITH_ODBC to CFLAGS and -lodbc to LIBS to compile with ODBC
|
||||
# library support. Add -DSAFESQL for poorely written ODBC library / drivers.
|
||||
#
|
||||
# Linux splice() support is not built by default, it is slower than the
|
||||
# read/write path for most traffic. Add -DWITHSPLICE to CFLAGS to build it,
|
||||
# it must additionally be enabled per service with the -s option.
|
||||
# Linux splice() support is built, but used only by services given the -s
|
||||
# option: it is faster for large transfers and slower for small requests.
|
||||
# Remove -DWITHSPLICE from CFLAGS to build without it.
|
||||
|
||||
BUILDDIR = ../bin/
|
||||
PREFIX ?= 3proxy_
|
||||
@@ -14,7 +14,7 @@ CRYPT_PREFIX ?= $(PREFIX)
|
||||
CC ?= gcc
|
||||
|
||||
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
|
||||
LN ?= ${CC}
|
||||
DCFLAGS ?= -fPIC
|
||||
|
||||
+3
-2
@@ -4,8 +4,9 @@
|
||||
|
||||
| Version | Supported |
|
||||
| ------- | ------------------ |
|
||||
| 0.9.8 | :white_check_mark: |
|
||||
| < 0.9.8 | :x: |
|
||||
| 0.9.9.x (LTS) | :white_check_mark: |
|
||||
| 1.0.x (Main) | :white_check_mark: |
|
||||
| <= 0.9.8 | :x: |
|
||||
|
||||
## Hardening a deployment
|
||||
|
||||
|
||||
Vendored
+6
@@ -1,3 +1,9 @@
|
||||
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 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)
|
||||
+38
-10
@@ -34,7 +34,8 @@ Each connected client requires:
|
||||
<ul>
|
||||
<li>1 thread (process)
|
||||
<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 during authentication or logging for RADIUS authentication or logging.
|
||||
<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.
|
||||
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>
|
||||
|
||||
@@ -641,17 +644,42 @@ monitor "/some/path/3proxy/3proxy.ver"
|
||||
e.g., with "touch /some/path/3proxy/3proxy.ver".
|
||||
</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
|
||||
without the need for bandwidth, e.g., messengers or small web requests,
|
||||
you can eliminate Nagle's algorithm delay with the TCP_NODELAY flag. Usage example:
|
||||
TCP_NODELAY is set by default on client (oc) and server (os)
|
||||
connections: without it, Nagle's algorithm holds back a short write until the
|
||||
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>
|
||||
proxy -osTCP_NODELAY -ocTCP_NODELAY
|
||||
proxy -osTCP_NODELAY=0 -ocTCP_NODELAY=0
|
||||
</pre>
|
||||
sets TCP_NODELAY for client (oc) and server (os) connections.
|
||||
<p>Do not use TCP_NODELAY on slow connections with high delays when
|
||||
connection bandwidth is a bottleneck.
|
||||
|
||||
<h4>Use Splice to Speed Up Large Data Transfers</h4>
|
||||
|
||||
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>
|
||||
|
||||
@@ -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.
|
||||
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
|
||||
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
|
||||
buffer (typically 64K) but keep the request sizes close to the chosen average
|
||||
on large file uploads/downloads.
|
||||
@@ -210,18 +210,30 @@ or hostname, useful in case of dynamic DNS. <b><br>
|
||||
-oR</b><i>OPTIONS</i> options for proxy-to-client
|
||||
(<b>-oc</b>), proxy-to-server (<b>-os</b>), proxy listening
|
||||
(<b>-ol</b>), connect back client (<b>-or</b>), connect back
|
||||
listening (<b>-oR</b>) sockets. Options like TCP_CORK,
|
||||
TCP_NODELAY, TCP_DEFER_ACCEPT, TCP_QUICKACK, TCP_TIMESTAMPS,
|
||||
listening (<b>-oR</b>) sockets. <i>OPTIONS</i> is a comma
|
||||
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,
|
||||
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 (<b>-ol</b>) to prevent that.
|
||||
<b><br>
|
||||
set by default on the listening sockets (<b>-ol</b>,
|
||||
<b>-oR</b>) on Unix; <b>-olSO_REUSEPORT=0</b> 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
|
||||
(<b>-ol</b>) to prevent that. <b><br>
|
||||
-H</b> (for all services) Expect HAProxy PROXY protocol v1
|
||||
header on incoming connection. This allows the proxy to
|
||||
receive real client IP address from HAProxy or other load
|
||||
@@ -236,12 +248,23 @@ second. Useful to minimize polling <b><br>
|
||||
-s</b> <br>
|
||||
(for admin) secure, allow only secure operations, currently
|
||||
only traffic counters view without ability to reset. <br>
|
||||
(for TCP services, Linux) enable splice(). splice() is not
|
||||
built by default and is disabled even when built, because
|
||||
current Linux does not implement SPLICE_F_MOVE, so no real
|
||||
zero-copy takes place and the read/write path is faster for
|
||||
most traffic. Rebuild with -DWITHSPLICE to make -s
|
||||
available, -s0 disables it explicitly. <b><br>
|
||||
(for TCP services, Linux) use splice() to pass data between
|
||||
the client and the server without copying it through 3proxy.
|
||||
<b>-s</b> alone splices both directions where it pays: a
|
||||
body of known length if at least 16K of it is left to read,
|
||||
a stream once it carries large reads, back to copying when
|
||||
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>
|
||||
(for TCP services) a connection closed by any of the sides
|
||||
terminates the session, buffered data is delivered before
|
||||
@@ -277,7 +300,12 @@ client reported) <b><br>
|
||||
-a1</b> (for proxy) anonymous proxy (random client
|
||||
information reported) <b><br>
|
||||
-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)
|
||||
<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>
|
||||
@@ -1300,8 +1328,15 @@ groupname. Unix only.</p>
|
||||
<i><path></i> [<i><uid></i>]
|
||||
[<i><gid></i>] <br>
|
||||
calls chroot(path) and sets gid/uid. Unix only. uid/gid
|
||||
supported since 0.9, can be numeric or
|
||||
username/groupname</p>
|
||||
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
|
||||
(<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>
|
||||
@@ -1590,10 +1625,12 @@ authentication and/or allow/deny ACLs.</p>
|
||||
and FTP are built when they are asked for, and are not in a
|
||||
default build. <b>MAILPROXY=true</b> builds <b>pop3p</b>,
|
||||
<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;
|
||||
with CMake the switches are <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>
|
||||
<b>ftppr</b> and the <b>ftp://</b> scheme of the HTTP proxy,
|
||||
which a <b>proxy</b> service then still has to ask for with
|
||||
<b>-Xftp</b>; with CMake the switches are
|
||||
<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
|
||||
still read. The three mail proxies become <b>tlspr</b>
|
||||
negotiating STARTTLS in that protocol, which is what most of
|
||||
|
||||
+29
-8
@@ -184,8 +184,10 @@ connect to given remote HOST:port instead of listening local connection on -p or
|
||||
.br
|
||||
.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.
|
||||
\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.
|
||||
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
|
||||
.B -H
|
||||
(for all services) Expect HAProxy PROXY protocol v1 header on incoming connection.
|
||||
@@ -200,11 +202,18 @@ delay GRACE_DELAY milliseconds before polling if average polling size is below G
|
||||
(for admin) secure, allow only secure operations, currently only traffic counters
|
||||
view without ability to reset.
|
||||
.br
|
||||
(for TCP services, Linux) enable splice(). splice() is not built by default and
|
||||
is disabled even when built, because current Linux does not implement
|
||||
SPLICE_F_MOVE, so no real zero-copy takes place and the read/write path is faster
|
||||
for most traffic. Rebuild with -DWITHSPLICE to make -s available, -s0 disables it
|
||||
explicitly.
|
||||
(for TCP services, Linux) use splice() to pass data between the client and the
|
||||
server without copying it through 3proxy. \fB-s\fR alone splices both directions where
|
||||
it pays: a body of known length if at least 16K of it is left to read, a stream
|
||||
once it carries large reads, back to copying when they turn small. \fB-s1\fR always
|
||||
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
|
||||
.B -C
|
||||
(for TCP services) a connection closed by any of the sides terminates the
|
||||
@@ -244,6 +253,12 @@ Never ask for username/password
|
||||
.br
|
||||
.B -a2
|
||||
(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
|
||||
Also, all options mentioned for
|
||||
.BR proxy (8)
|
||||
@@ -1373,7 +1388,12 @@ for all threads.
|
||||
.BR chroot
|
||||
\fI<path>\fR [\fI<uid>\fR] [\fI<gid>\fR]
|
||||
.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 stacksize
|
||||
@@ -1639,7 +1659,8 @@ authentication and/or allow/deny ACLs.
|
||||
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
|
||||
\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
|
||||
binaries of those services are built with them and not without.
|
||||
.br
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
Name: 3proxy
|
||||
Version: 1.0.1
|
||||
Version: 1.0.2
|
||||
Release: 1%{?dist}
|
||||
Summary: 3proxy tiny proxy server
|
||||
License: GPL/LGPL/Apache/BSD
|
||||
|
||||
+54
-14
@@ -74,13 +74,8 @@ void __stdcall CommandHandler( DWORD dwCommand )
|
||||
SetStatus( SERVICE_STOP_PENDING, 0, 1 );
|
||||
conf.timetoexit = 1;
|
||||
conf.paused++;
|
||||
Sleep(2000);
|
||||
SetStatus( SERVICE_STOPPED, 0, 0 );
|
||||
#ifdef WITH_ODBC
|
||||
_3proxy_mutex_lock(&log_mutex);
|
||||
close_sql();
|
||||
_3proxy_mutex_unlock(&log_mutex);
|
||||
#endif
|
||||
/* ServiceMain() reports the service stopped once cyclestep() has
|
||||
seen this and the services are done */
|
||||
break;
|
||||
case SERVICE_CONTROL_PAUSE:
|
||||
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_RUNNING, 0, 0 );
|
||||
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
|
||||
|
||||
@@ -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){
|
||||
struct tm *tm;
|
||||
time_t minutecounter;
|
||||
@@ -336,9 +371,7 @@ void cyclestep(void){
|
||||
if(conf.timetoexit){
|
||||
conf.paused++;
|
||||
doschedule();
|
||||
usleep(SLEEPTIME*999);
|
||||
usleep(SLEEPTIME*999);
|
||||
usleep(SLEEPTIME*999);
|
||||
waitservices();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -516,7 +549,13 @@ int WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int
|
||||
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(&runningservices_mutex);
|
||||
_3proxy_mutex_init(&bandlim_mutex);
|
||||
_3proxy_mutex_init(&connlim_mutex);
|
||||
_3proxy_mutex_init(&tc_mutex);
|
||||
@@ -524,7 +563,7 @@ int WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int
|
||||
#ifndef NORADIUS
|
||||
_3proxy_mutex_init(&rad_mutex);
|
||||
#endif
|
||||
if(_3proxy_sem_init(conf.threadinit, 1, 1)){
|
||||
if(_3proxy_sem_init_timed(serviceexited, 0, 0x7fffffff)){
|
||||
fprintf(stderr, "semaphore init failed\n");
|
||||
return 1;
|
||||
}
|
||||
@@ -547,7 +586,9 @@ int WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int
|
||||
res = readconfig(fp);
|
||||
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;
|
||||
|
||||
#ifdef _WIN32
|
||||
@@ -572,7 +613,6 @@ int WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int
|
||||
signal(SIGCONT, mysigpause);
|
||||
signal(SIGTERM, mysigterm);
|
||||
signal(SIGUSR1, mysigusr1);
|
||||
signal(SIGPIPE, SIG_IGN);
|
||||
cyclestep();
|
||||
|
||||
#endif
|
||||
@@ -580,6 +620,6 @@ int WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int
|
||||
CLEARRETURN:
|
||||
|
||||
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
|
||||
$(CC) $(CFLAGS) common.c
|
||||
|
||||
sem$(OBJSUFFICS): sem.c proxy.h structures.h
|
||||
$(CC) $(CFLAGS) sem.c
|
||||
|
||||
plugins$(OBJSUFFICS): plugins.c proxy.h structures.h
|
||||
$(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
|
||||
|
||||
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
|
||||
$(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
|
||||
$(CC) $(CFLAGS) 3proxy.c
|
||||
|
||||
$(BUILDDIR)$(PREFIX)proxy$(EXESUFFICS): sockmap$(OBJSUFFICS) proxy$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) common$(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)
|
||||
$(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) sem$(OBJSUFFICS) base64$(OBJSUFFICS) ftp$(OBJSUFFICS) $(COMPATLIBS) $(LIBS)
|
||||
|
||||
$(BUILDDIR)$(PREFIX)pop3p$(EXESUFFICS): sockmap$(OBJSUFFICS) pop3p$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) common$(OBJSUFFICS) log$(OBJSUFFICS) $(COMPATLIBS)
|
||||
$(LN) $(LNOUT)$(BUILDDIR)$(PREFIX)pop3p$(EXESUFFICS) $(LDFLAGS) sockmap$(OBJSUFFICS) pop3p$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) log$(OBJSUFFICS) common$(OBJSUFFICS) $(COMPATLIBS) $(LIBS)
|
||||
$(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) sem$(OBJSUFFICS) $(COMPATLIBS) $(LIBS)
|
||||
|
||||
$(BUILDDIR)$(PREFIX)imapp$(EXESUFFICS): sockmap$(OBJSUFFICS) imapp$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) common$(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)
|
||||
$(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) sem$(OBJSUFFICS) base64$(OBJSUFFICS) $(COMPATLIBS) $(LIBS)
|
||||
|
||||
$(BUILDDIR)$(PREFIX)smtpp$(EXESUFFICS): sockmap$(OBJSUFFICS) smtpp$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) common$(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)
|
||||
$(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) sem$(OBJSUFFICS) $(COMPATLIBS) $(LIBS)
|
||||
|
||||
$(BUILDDIR)$(PREFIX)ftppr$(EXESUFFICS): sockmap$(OBJSUFFICS) ftppr$(OBJSUFFICS) ftp$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) common$(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)
|
||||
$(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) sem$(OBJSUFFICS) log$(OBJSUFFICS) ftp$(OBJSUFFICS) $(COMPATLIBS) $(LIBS)
|
||||
|
||||
$(BUILDDIR)$(PREFIX)socks$(EXESUFFICS): sockmap$(OBJSUFFICS) udpsockmap$(OBJSUFFICS) socks$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) common$(OBJSUFFICS) log$(OBJSUFFICS)
|
||||
$(LN) $(LNOUT)$(BUILDDIR)$(PREFIX)socks$(EXESUFFICS) $(LDFLAGS) sockmap$(OBJSUFFICS) udpsockmap$(OBJSUFFICS) socks$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) log$(OBJSUFFICS) common$(OBJSUFFICS) $(LIBS)
|
||||
$(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) sem$(OBJSUFFICS) $(LIBS)
|
||||
|
||||
$(BUILDDIR)$(PREFIX)tcppm$(EXESUFFICS): sockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) tcppm$(OBJSUFFICS) common$(OBJSUFFICS) log$(OBJSUFFICS)
|
||||
$(LN) $(LNOUT)$(BUILDDIR)$(PREFIX)tcppm$(EXESUFFICS) $(LDFLAGS) sockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) tcppm$(OBJSUFFICS) log$(OBJSUFFICS) common$(OBJSUFFICS) $(LIBS)
|
||||
$(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) sem$(OBJSUFFICS) $(LIBS)
|
||||
|
||||
$(BUILDDIR)$(PREFIX)udppm$(EXESUFFICS): sockmap$(OBJSUFFICS) udpsockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) udppm$(OBJSUFFICS) common$(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)
|
||||
$(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) sem$(OBJSUFFICS) hash$(OBJSUFFICS) $(LIBS)
|
||||
|
||||
$(BUILDDIR)$(PREFIX)tlspr$(EXESUFFICS): sockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) tlspr$(OBJSUFFICS) common$(OBJSUFFICS) log$(OBJSUFFICS)
|
||||
$(LN) $(LNOUT)$(BUILDDIR)$(PREFIX)tlspr$(EXESUFFICS) $(LDFLAGS) sockmap$(OBJSUFFICS) sockgetchar$(OBJSUFFICS) tlspr$(OBJSUFFICS) log$(OBJSUFFICS) common$(OBJSUFFICS) $(LIBS)
|
||||
$(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) sem$(OBJSUFFICS) $(LIBS)
|
||||
|
||||
mainfunc$(OBJSUFFICS): proxy.h structures.h 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
|
||||
$(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)
|
||||
$(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)
|
||||
$(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) 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)
|
||||
|
||||
+15
-31
@@ -187,33 +187,6 @@ size_t threadstacksize(int extra){
|
||||
if(size < (long)PTHREAD_STACK_MIN) size = (long)PTHREAD_STACK_MIN;
|
||||
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
|
||||
|
||||
struct extparam conf = {
|
||||
@@ -414,7 +387,6 @@ int
|
||||
return shutdown(s, how);
|
||||
}
|
||||
int WINAPI def_closesocket(void* state, SOCKET s){
|
||||
usleep(SLEEPTIME);
|
||||
return closesocket(s);
|
||||
}
|
||||
#else
|
||||
@@ -454,11 +426,18 @@ int
|
||||
#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){
|
||||
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){
|
||||
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){
|
||||
return recv(s, buf, len, flags);
|
||||
@@ -742,7 +721,9 @@ int doconnect(struct clientparam * param){
|
||||
if(param->srv->so._getpeername(param->sostate, param->remsock, (struct sockaddr *)¶m->sinsr, &size)==-1) {return (14);}
|
||||
}
|
||||
else {
|
||||
#ifndef _WIN32
|
||||
struct linger lg = {1,conf.timeouts[LINGER_TO]};
|
||||
#endif
|
||||
int tries = RANGETRIES;
|
||||
|
||||
if(SAISNULL(¶m->sinsr)){
|
||||
@@ -772,9 +753,12 @@ int doconnect(struct clientparam * param){
|
||||
param->sinsl = param->srv->extsa;
|
||||
}
|
||||
*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));
|
||||
#endif
|
||||
if(extbindtodevice(param, param->remsock)) return 12;
|
||||
#ifdef WITH_UN
|
||||
if(*SAFAMILY(¶m->sinsl) != AF_UNIX)
|
||||
|
||||
+61
-23
@@ -38,14 +38,18 @@ _3proxy_mutex_t bandlim_mutex;
|
||||
_3proxy_mutex_t connlim_mutex;
|
||||
_3proxy_mutex_t tc_mutex;
|
||||
_3proxy_mutex_t config_mutex;
|
||||
int runningservices = 0;
|
||||
_3proxy_mutex_t runningservices_mutex;
|
||||
_3proxy_sem_t serviceexited;
|
||||
|
||||
int haveerror = 0;
|
||||
int linenum = 0;
|
||||
|
||||
struct counter_header cheader = {"3CF", (time_t)0};
|
||||
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, ""};
|
||||
|
||||
@@ -75,8 +79,12 @@ DWORD WINAPI startsrv(LPVOID data) {
|
||||
#else
|
||||
void * startsrv(void * data) {
|
||||
#endif
|
||||
struct child *d = (struct child *)data;
|
||||
mainfunc(d->argc, (char **)d->argv);
|
||||
/* counted by start_proxy_thread() before the thread is created */
|
||||
mainrun(data);
|
||||
_3proxy_mutex_lock(&runningservices_mutex);
|
||||
runningservices--;
|
||||
_3proxy_mutex_unlock(&runningservices_mutex);
|
||||
_3proxy_sem_unlock(serviceexited);
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -142,36 +150,45 @@ unsigned char * dologname (unsigned char *buf, unsigned char *name, const unsign
|
||||
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){
|
||||
pthread_t thread;
|
||||
void *service;
|
||||
int res;
|
||||
#ifdef _WIN32
|
||||
HANDLE h;
|
||||
#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
|
||||
#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
|
||||
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
|
||||
if(h)CloseHandle(h);
|
||||
else {
|
||||
#else
|
||||
pthread_attr_init(&pa);
|
||||
pthread_attr_setstacksize(&pa,threadstacksize(conf.stacksize));
|
||||
pthread_attr_setdetachstate(&pa,PTHREAD_CREATE_DETACHED);
|
||||
if(pthread_create(&thread, &pa, startsrv, (void *)chp)){
|
||||
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);
|
||||
}
|
||||
res = pthread_create(&thread, &pa, startsrv, service);
|
||||
pthread_attr_destroy(&pa);
|
||||
if(res){
|
||||
#endif
|
||||
_3proxy_sem_lock(conf.threadinit);
|
||||
_3proxy_sem_unlock(conf.threadinit);
|
||||
if(haveerror) {
|
||||
fprintf(stderr, "Service not started on line: %d%s\n", linenum, haveerror == 2? ": insufficient memory":"");
|
||||
_3proxy_mutex_lock(&runningservices_mutex);
|
||||
runningservices--;
|
||||
_3proxy_mutex_unlock(&runningservices_mutex);
|
||||
maindrop(service);
|
||||
fprintf(stderr, "Failed to create service thread on line %d, try to set larger stacksize\n", linenum);
|
||||
return(40);
|
||||
}
|
||||
return 0;
|
||||
@@ -187,6 +204,9 @@ static int h_proxy(int argc, unsigned char ** argv){
|
||||
childdef.port = 3128;
|
||||
childdef.isudp = 0;
|
||||
childdef.service = S_PROXY;
|
||||
#ifdef WITH_FTP
|
||||
childdef.helpmessage = " -Xftp - fetch ftp:// URLs\n";
|
||||
#endif
|
||||
#ifdef NOIPV6
|
||||
if(!resolvfunc || (resolvfunc == myresolver && !dns_table.poolsize)){
|
||||
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
|
||||
conf.logfunc = logsyslog;
|
||||
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
|
||||
}
|
||||
#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){
|
||||
uid_t uid = 0;
|
||||
gid_t gid = 0;
|
||||
@@ -1920,6 +1949,8 @@ static int h_chroot(int argc, unsigned char **argv){
|
||||
}
|
||||
if(!chrootp){
|
||||
char *p;
|
||||
|
||||
prechroot();
|
||||
if(chroot((char *)argv[1])) {
|
||||
fprintf(stderr, "Unable to chroot %s", argv[1]);
|
||||
return(1);
|
||||
@@ -2263,6 +2294,7 @@ int readconfig(FILE * fp){
|
||||
|
||||
if( !(buf = malloc(bufsize)) || ! (argv = malloc((NPARAMS + 1) * sizeof(unsigned char *))) ) {
|
||||
fprintf(stderr, "No memory for configuration");
|
||||
if(buf) free(buf);
|
||||
return(10);
|
||||
}
|
||||
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);
|
||||
if(argc < 1) {
|
||||
fprintf(stderr, "Parse error line %d\n", linenum);
|
||||
return(11);
|
||||
res = 11;
|
||||
goto DONE;
|
||||
}
|
||||
argv[argc] = NULL;
|
||||
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(argc < cm->minargs || (cm->maxargs && argc > cm->maxargs)){
|
||||
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);
|
||||
if(res > 0){
|
||||
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 != 1)continue;
|
||||
fprintf(stderr, "Unknown command: '%s' line %d\n", argv[0], linenum);
|
||||
return(linenum);
|
||||
res = linenum;
|
||||
goto DONE;
|
||||
}
|
||||
res = 0;
|
||||
DONE:
|
||||
free(buf);
|
||||
free(argv);
|
||||
return 0;
|
||||
return res;
|
||||
|
||||
}
|
||||
|
||||
|
||||
+38
-3
@@ -15,6 +15,12 @@
|
||||
|
||||
#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) {
|
||||
uint32_t ip = 0;
|
||||
@@ -146,6 +152,20 @@ void * dnsprchild(struct clientparam* param) {
|
||||
else ip = 0;
|
||||
}
|
||||
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) {
|
||||
RETURN(818);
|
||||
}
|
||||
@@ -174,9 +194,21 @@ void * dnsprchild(struct clientparam* param) {
|
||||
}
|
||||
param->statscli64 += i;
|
||||
param->nwrites++;
|
||||
len = sockrecvfrom(param, param->remsock, (struct sockaddr *)¶m->sinsr, buf, BUFSIZE, conf.timeouts[DNS_TO]*1000);
|
||||
if(len <= 13) {
|
||||
RETURN(821);
|
||||
/* over UDP only an answer from the name server asked is taken, any
|
||||
other read past while the time for it lasts */
|
||||
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->nreads++;
|
||||
@@ -188,7 +220,10 @@ void * dnsprchild(struct clientparam* param) {
|
||||
len -= 2;
|
||||
if(len < us) len += sockgetlinebuf(param, SERVER, buf+len, us - len, 0, conf.timeouts[SINGLEBYTE_L]);
|
||||
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(socksendto(param, param->clisock, (struct sockaddr *)¶m->sincr, buf, len, conf.timeouts[SINGLEBYTE_L]*1000) != len){
|
||||
RETURN(822);
|
||||
|
||||
+8
-1
@@ -23,14 +23,18 @@ void * ftpprchild(struct clientparam* param) {
|
||||
SOCKET sc = INVALID_SOCKET, ss = INVALID_SOCKET, clidatasock = INVALID_SOCKET;
|
||||
SASIZETYPE sasize;
|
||||
char * req = NULL;
|
||||
#ifndef _WIN32
|
||||
struct linger lg;
|
||||
#endif
|
||||
struct pollfd fds;
|
||||
|
||||
if(!(buf = malloc(BUFSIZE))) RETURN(876);
|
||||
param->ctrlsock = param->clisock;
|
||||
param->operation = CONNECT;
|
||||
#ifndef _WIN32
|
||||
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);}
|
||||
for(;;){
|
||||
i = sockgetlinebuf(param, CLIENT, buf, BUFSIZE - 10, '\n', conf.timeouts[CONNECTION_S]);
|
||||
@@ -262,8 +266,11 @@ void * ftpprchild(struct clientparam* param) {
|
||||
}
|
||||
sc = param->remsock;
|
||||
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, clidatasock, SOL_SOCKET, SO_LINGER, (char *)&lg, sizeof(lg));
|
||||
#endif
|
||||
param->clisock = clidatasock;
|
||||
res = mapsocket(param, conf.timeouts[CONNECTION_S]);
|
||||
if(param->remsock != INVALID_SOCKET) {
|
||||
|
||||
+59
-3
@@ -459,12 +459,12 @@ static int widepath(const char *path, wchar_t *out, int outchars)
|
||||
char *p;
|
||||
|
||||
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);
|
||||
else snprintf(prefixed, sizeof(prefixed), "\\\\?\\%s", path);
|
||||
|
||||
/* 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;
|
||||
}
|
||||
@@ -481,9 +481,19 @@ static int filemeta(const char *path, struct filemeta *m)
|
||||
{
|
||||
#ifdef _WIN32
|
||||
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;
|
||||
|
||||
if(widepath(path, wide, HTTPSRV_LINE) || _wstat64(wide, &st)) return 1;
|
||||
#endif
|
||||
m->size = (uint64_t)st.st_size;
|
||||
m->mtime = st.st_mtime;
|
||||
m->isreg = (st.st_mode & _S_IFREG) != 0;
|
||||
@@ -1114,6 +1124,10 @@ void freehttprules(struct httprule *rule)
|
||||
next = rule->next;
|
||||
if(rule->host.name) free(rule->host.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->ctype) free(rule->ctype);
|
||||
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
|
||||
request line and the headers, exactly as they came, since the proxy code
|
||||
reads them again from the beginning. */
|
||||
@@ -1451,6 +1496,12 @@ static int httpsrv_request(struct clientparam *param, struct httpreq *r)
|
||||
}
|
||||
}
|
||||
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
|
||||
should let the client offer credentials again. */
|
||||
if(i >= 4 && i <= 6) op_authrequired(r);
|
||||
@@ -1573,7 +1624,12 @@ void * httpsrvchild(struct clientparam *param)
|
||||
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;
|
||||
}
|
||||
/* A child named by an access rule takes the connection over, which the
|
||||
|
||||
+49
-7
@@ -140,6 +140,8 @@ char * proxy_stringtable[] = {
|
||||
#define HDRRESERVE 2048
|
||||
#define BUFSIZE (LINESIZE*2)
|
||||
#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)
|
||||
static int proxy_stringtable_len[PST_COUNT];
|
||||
@@ -171,6 +173,20 @@ static int growbuf(unsigned char **buf, int *bufsize, int need){
|
||||
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){
|
||||
void **pp = (void **)p;
|
||||
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 *se;
|
||||
int len;
|
||||
char *own = NULL;
|
||||
|
||||
if(!buf) req = NULL;
|
||||
if(param->res == 555 || param->res == 508) return;
|
||||
if(req) {
|
||||
len = (int)strlen(req);
|
||||
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);
|
||||
buf[LINESIZE - 1] = 0;
|
||||
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);
|
||||
}
|
||||
}
|
||||
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){
|
||||
@@ -285,7 +307,7 @@ void * proxychild(struct clientparam* param) {
|
||||
int clhdrofs_req = -1;
|
||||
int isconnect = 0;
|
||||
int redirect = 0;
|
||||
int prefix = 0, ckeepalive=0;
|
||||
int prefix = 0, hostofs = 0, ckeepalive=0;
|
||||
int ftp = 0;
|
||||
int ssoff = 0;
|
||||
#ifndef ANONYMOUS
|
||||
@@ -309,18 +331,24 @@ void * proxychild(struct clientparam* param) {
|
||||
|
||||
|
||||
if(param->remsock != INVALID_SOCKET) haveconnection = 1;
|
||||
if(!(buf = malloc(BUFSIZE))) {RETURN(21);}
|
||||
bufsize = BUFSIZE;
|
||||
#ifndef ANONYMOUS
|
||||
anonymous = param->srv->anonymous;
|
||||
#endif
|
||||
for(;;){
|
||||
memset(buf, 0, bufsize);
|
||||
inbuf = 0;
|
||||
chunkedcli = 0;
|
||||
clhdrofs_req = -1;
|
||||
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)){
|
||||
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]);
|
||||
if(i<=0) {
|
||||
RETURN((keepalive)?555:(i)?507:508);
|
||||
@@ -354,7 +389,7 @@ for(;;){
|
||||
buf[i] = 0;
|
||||
|
||||
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;
|
||||
if(param->remsock != INVALID_SOCKET){
|
||||
param->srv->so._shutdown(param->sostate, param->remsock, SHUT_RDWR);
|
||||
@@ -387,6 +422,7 @@ for(;;){
|
||||
}
|
||||
#ifdef WITH_FTP
|
||||
else if (!strncasecmp((char *)sb, "ftp://", 6)) {
|
||||
if(!param->srv->allowftp) RETURN(513);
|
||||
ftp = 1;
|
||||
sb += 6;
|
||||
}
|
||||
@@ -411,6 +447,7 @@ for(;;){
|
||||
*se = 0;
|
||||
}
|
||||
prefix = (int)(se - buf);
|
||||
hostofs = (int)(sb - buf);
|
||||
su = (unsigned char*)strrchr((char *)sb, '@');
|
||||
if(su) {
|
||||
su = (unsigned char *)strdup((char *)sb);
|
||||
@@ -973,6 +1010,7 @@ for(;;){
|
||||
freeptr(&req); freeptr(&buf); freeptr(&ftpbase);
|
||||
return (void *)param->redirectfunc;
|
||||
}
|
||||
freeptr(&buf);
|
||||
param->res = mapsocket(param, conf.timeouts[CONNECTION_L]);
|
||||
RETURN(param->res);
|
||||
}
|
||||
@@ -1284,6 +1322,7 @@ for(;;){
|
||||
} while(param->chunked);
|
||||
}
|
||||
if(isconnect && res == 200 && param->operation){
|
||||
freeptr(&buf);
|
||||
RETURN (mapsocket(param, conf.timeouts[CONNECTION_S]));
|
||||
}
|
||||
else if(isconnect){
|
||||
@@ -1357,6 +1396,9 @@ struct proxydef childdef = {
|
||||
S_PROXY,
|
||||
"-a - anonymous proxy\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"
|
||||
#endif
|
||||
+24
-4
@@ -239,6 +239,11 @@ extern struct extparam conf;
|
||||
|
||||
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 udpsockmap(struct clientparam * param, int timeo);
|
||||
int udpbind(struct clientparam * param);
|
||||
@@ -322,13 +327,23 @@ extern _3proxy_sem_t udpinit;
|
||||
#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_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
|
||||
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);
|
||||
int _3proxy_sem_timedlock_f(_3proxy_sem_t *sem, unsigned ms);
|
||||
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_timedlock(x, ms) _3proxy_sem_timedlock_f(&x, (ms))
|
||||
#define _3proxy_sem_unlock(x) _3proxy_sem_unlock_f(&x)
|
||||
#define _3proxy_sem_destroy(x) _3proxy_sem_destroy_f(&x)
|
||||
#endif
|
||||
|
||||
|
||||
@@ -457,6 +472,10 @@ struct dictionary;
|
||||
struct node;
|
||||
struct property;
|
||||
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 connlim_mutex;
|
||||
extern _3proxy_mutex_t tc_mutex;
|
||||
@@ -467,7 +486,7 @@ extern struct datatype datatypes[64];
|
||||
extern struct commands commandhandlers[];
|
||||
|
||||
#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
|
||||
#define mapsocket(a,b) sockmap(a,b, 0)
|
||||
#endif
|
||||
@@ -487,7 +506,8 @@ extern struct socketoptions {
|
||||
int opt;
|
||||
char * optname;
|
||||
} 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);
|
||||
|
||||
#ifdef _WINCE
|
||||
|
||||
+1152
-908
File diff suppressed because it is too large.
Load diff
@@ -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.events = POLLIN;
|
||||
if(conf.timetoexit) return EOF;
|
||||
res = param?param->srv->so._poll(param->sostate, &fds, 1, to):so._poll(so.state, &fds, 1, to);
|
||||
if (res<1) return 0;
|
||||
sasize = sizeof(PROXYSOCKADDRTYPE);
|
||||
do {
|
||||
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);
|
||||
} while (res < 0 && (errno == EAGAIN || errno == EINTR));
|
||||
return res;
|
||||
for(;;){
|
||||
if(conf.timetoexit) return EOF;
|
||||
res = param?param->srv->so._poll(param->sostate, &fds, 1, to):so._poll(so.state, &fds, 1, to);
|
||||
if (res<1) return 0;
|
||||
sasize = sizeof(PROXYSOCKADDRTYPE);
|
||||
/* sin NULL for a stream socket: nothing to learn the address into */
|
||||
do {
|
||||
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){
|
||||
|
||||
+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
|
||||
|
||||
/* 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
|
||||
|
||||
#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. */
|
||||
#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 halfclose = param->srv->halfclose;
|
||||
uint64_t fromclient=0x7fffffffffffffff, fromserver =0x7fffffffffffffff;
|
||||
@@ -60,13 +97,16 @@ int sockmap(struct clientparam * param, int timeo, int usesplice){
|
||||
#endif
|
||||
int HASERROR=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;
|
||||
struct pollfd fds[8];
|
||||
int fdsc = 0;
|
||||
int sleeptime = 0;
|
||||
FILTER_ACTION action;
|
||||
int res = 0;
|
||||
SASIZETYPE sasize;
|
||||
int needaction = 0;
|
||||
int graceclinum=0, gracesrvnum=0, graceclitraf=0, gracesrvtraf=0;
|
||||
time_t gracetime = 0;
|
||||
@@ -76,16 +116,30 @@ int sockmap(struct clientparam * param, int timeo, int usesplice){
|
||||
#ifdef WITHSPLICE
|
||||
uint64_t inclientpipe = 0, inserverpipe = 0;
|
||||
int TOCLIENTPIPE = 0, FROMCLIENTPIPE = 0, TOSERVERPIPE = 0, FROMSERVERPIPE = 0;
|
||||
int pipesrv[2] = {-1,-1};
|
||||
int pipecli[2] = {-1,-1};
|
||||
/* The client's data goes through pipecli, the server's through pipesrv.
|
||||
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(usesplice){
|
||||
TOCLIENTPIPE = FROMCLIENTPIPE = TOSERVERPIPE = FROMSERVERPIPE = 1;
|
||||
TOCLIENTBUF = TOSERVERBUF = 0;
|
||||
if(pipe2(pipecli, O_NONBLOCK) < 0) RETURN (21);
|
||||
if(pipe2(pipesrv, O_NONBLOCK) < 0) RETURN (21);
|
||||
allowcli = (usesplice & SPLICE_UPLOAD) != 0;
|
||||
allowsrv = (usesplice & SPLICE_DOWNLOAD) != 0;
|
||||
autosplice = (usesplice & SPLICE_AUTO) != 0;
|
||||
if(!autosplice){
|
||||
splicecli = allowcli;
|
||||
splicesrv = allowsrv;
|
||||
}
|
||||
TOCLIENTPIPE = FROMCLIENTPIPE = allowcli;
|
||||
TOSERVERPIPE = FROMSERVERPIPE = allowsrv;
|
||||
#else
|
||||
#define splicecli 0
|
||||
#define splicesrv 0
|
||||
#define wantbufcli 0
|
||||
#define wantbufsrv 0
|
||||
#endif
|
||||
|
||||
inserverbuf = param->srvinbuf - param->srvoffset;
|
||||
@@ -108,16 +162,16 @@ int sockmap(struct clientparam * param, int timeo, int usesplice){
|
||||
if(inserverbuf >= fromserver) FROMSERVER = 0;
|
||||
if(inclientbuf >= fromclient) FROMCLIENT = 0;
|
||||
#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
|
||||
{
|
||||
if(fromserver && !param->srvbuf && (!(param->srvbuf=malloc(SRVBUFSIZE)) || !(param->srvbufsize = SRVBUFSIZE))){
|
||||
RETURN (21);
|
||||
}
|
||||
if(fromclient && !param->clibuf && (!(param->clibuf=malloc(SRVBUFSIZE)) || !(param->clibufsize = SRVBUFSIZE))){
|
||||
RETURN (21);
|
||||
}
|
||||
|
||||
/* a spliced direction needs no buffer, only what was read before */
|
||||
if(!splicesrv && fromserver && !param->srvbuf && (!(param->srvbuf=malloc(SRVBUFSIZE)) || !(param->srvbufsize = SRVBUFSIZE))){
|
||||
RETURN (21);
|
||||
}
|
||||
if(!splicecli && fromclient && !param->clibuf && (!(param->clibuf=malloc(SRVBUFSIZE)) || !(param->clibufsize = SRVBUFSIZE))){
|
||||
RETURN (21);
|
||||
}
|
||||
if(param->srvinbuf == param->srvoffset) param->srvinbuf =param->srvoffset = 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;
|
||||
if(fromclient) TOCLIENTBUF = 1;
|
||||
}
|
||||
sasize = SASIZE(¶m->sinsr);
|
||||
res = param->srv->so._sendto(param->sostate, param->remsock, (char *)param->clibuf + param->clioffset, (int)MIN(inclientbuf, fromclient), 0, (struct sockaddr*)¶m->sinsr, sasize);
|
||||
/* a connected stream: no address, which a Unix socket on Linux
|
||||
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) {
|
||||
TOSERVER = 0;
|
||||
if(errno && errno != EAGAIN && errno != EINTR){
|
||||
@@ -267,8 +322,7 @@ log("send to client from buf");
|
||||
if(fromserver) TOSERVERBUF = 1;
|
||||
continue;
|
||||
}
|
||||
sasize = SASIZE(¶m->sincr);
|
||||
res = param->srv->so._sendto(param->sostate, param->clisock, (char *)param->srvbuf + param->srvoffset, (int)MIN(inserverbuf,fromserver), 0, (struct sockaddr*)¶m->sincr, sasize);
|
||||
res = param->srv->so._sendto(param->sostate, param->clisock, (char *)param->srvbuf + param->srvoffset, (int)MIN(inserverbuf,fromserver), 0, NULL, 0);
|
||||
if(res <= 0) {
|
||||
TOCLIENT = 0;
|
||||
if(errno && errno != EAGAIN && errno != EINTR){
|
||||
@@ -292,8 +346,21 @@ log("done send to client from buf");
|
||||
}
|
||||
}
|
||||
#ifdef WITHSPLICE
|
||||
if(usesplice){
|
||||
if(inclientpipe && !inclientbuf && FROMCLIENTPIPE && TOSERVER){
|
||||
/* a direction going back to copying does once its pipe is empty */
|
||||
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
|
||||
log("send to server from pipe");
|
||||
#endif
|
||||
@@ -330,7 +397,7 @@ log(logbuf);
|
||||
}
|
||||
}
|
||||
}
|
||||
if(inserverpipe && !inserverbuf && FROMSERVERPIPE && TOCLIENT){
|
||||
if(splicesrv && inserverpipe && !inserverbuf && FROMSERVERPIPE && TOCLIENT){
|
||||
#ifdef WITHLOG
|
||||
log("send to client from pipe");
|
||||
#endif
|
||||
@@ -360,12 +427,17 @@ log(logbuf);
|
||||
}
|
||||
}
|
||||
}
|
||||
if(fromclient>inclientpipe && FROMCLIENT && TOCLIENTPIPE && !SESSIONEND){
|
||||
int error;
|
||||
socklen_t len=sizeof(error);
|
||||
if(splicecli && !wantbufcli && fromclient>inclientpipe && FROMCLIENT && TOCLIENTPIPE && !SESSIONEND){
|
||||
#ifdef WITHLOG
|
||||
log("read from client to pipe");
|
||||
#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;
|
||||
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
|
||||
@@ -396,19 +468,27 @@ log("done read from client to pipe");
|
||||
graceclinum++;
|
||||
graceclitraf += res;
|
||||
gracesrvnum = gracesrvtraf = 0;
|
||||
if(autosplice && !param->waitclient64){
|
||||
if(res >= SPLICE_SMALL) streakcli = 0;
|
||||
else if(++streakcli > SPLICE_STREAK) wantbufcli = 1;
|
||||
}
|
||||
inclientpipe += res;
|
||||
if(inclientpipe >= MAXSPLICE) TOCLIENTPIPE = 0;
|
||||
needaction = 0;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if(fromserver > inserverpipe && FROMSERVER && TOSERVERPIPE && !SESSIONEND){
|
||||
int error;
|
||||
socklen_t len=sizeof(error);
|
||||
errno = 0;
|
||||
if(splicesrv && !wantbufsrv && fromserver > inserverpipe && FROMSERVER && TOSERVERPIPE && !SESSIONEND){
|
||||
#ifdef WITHLOG
|
||||
log("read from server to pipe\n");
|
||||
#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);
|
||||
#ifdef WITHLOG
|
||||
log("server to pipe splice finished\n");
|
||||
@@ -438,6 +518,10 @@ log("done read from server to pipe\n");
|
||||
gracesrvnum++;
|
||||
gracesrvtraf += res;
|
||||
graceclinum = graceclitraf = 0;
|
||||
if(autosplice && !param->waitserver64){
|
||||
if(res >= SPLICE_SMALL) streaksrv = 0;
|
||||
else if(++streaksrv > SPLICE_STREAK) wantbufsrv = 1;
|
||||
}
|
||||
param->nreads++;
|
||||
param->statssrv64 += res;
|
||||
inserverpipe += res;
|
||||
@@ -452,15 +536,15 @@ log("done read from server to pipe\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
#endif
|
||||
{
|
||||
if(fromclient > inclientbuf && FROMCLIENT && TOCLIENTBUF && !SESSIONEND){
|
||||
if(!splicecli && fromclient > inclientbuf && FROMCLIENT && TOCLIENTBUF && !SESSIONEND){
|
||||
#ifdef WITHLOG
|
||||
log("read from client to buf");
|
||||
#endif
|
||||
sasize = sizeof(param->sincr);
|
||||
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);
|
||||
/* no address: it would overwrite the client's with what a
|
||||
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) {
|
||||
FROMCLIENT = 0;
|
||||
if(res == 0) {
|
||||
@@ -480,6 +564,17 @@ log("done read from client to buf");
|
||||
graceclinum++;
|
||||
graceclitraf += res;
|
||||
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;
|
||||
param->cliinbuf += res;
|
||||
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
|
||||
log("read from server to buf");
|
||||
#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, (struct sockaddr *)¶m->sinsr, &sasize);
|
||||
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);
|
||||
if(res <= 0) {
|
||||
FROMSERVER = 0;
|
||||
if(res == 0) {
|
||||
@@ -513,6 +607,15 @@ log("done read from server to buf");
|
||||
gracesrvnum++;
|
||||
gracesrvtraf += res;
|
||||
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->statssrv64 += res;
|
||||
inserverbuf += res;
|
||||
@@ -553,15 +656,8 @@ log("done read from server to buf");
|
||||
// if(!CLIENTTERMREAD || !CLIENTTERMWRITE){
|
||||
if(!after){
|
||||
fds[fdsc].fd = param->clisock;
|
||||
if(fromclient && !CLIENTTERMREAD && !FROMCLIENT && !SESSIONEND && ((
|
||||
#ifdef WITHSPLICE
|
||||
!usesplice &&
|
||||
#endif
|
||||
TOCLIENTBUF)
|
||||
#ifdef WITHSPLICE
|
||||
|| (usesplice)
|
||||
#endif
|
||||
))
|
||||
if(fromclient && !CLIENTTERMREAD && !FROMCLIENT && !SESSIONEND &&
|
||||
((!splicecli && TOCLIENTBUF) || (splicecli && !wantbufcli)))
|
||||
cli_events |= POLLIN;
|
||||
if(!TOCLIENT && !CLIENTTERMWRITE && (inserverbuf
|
||||
#ifdef WITHSPLICE
|
||||
@@ -569,6 +665,11 @@ log("done read from server to buf");
|
||||
#endif
|
||||
))
|
||||
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){
|
||||
fds[fdsc].fd = param->clisock;
|
||||
fds[fdsc].events = cli_events;
|
||||
@@ -580,6 +681,8 @@ log("wait writing to client");
|
||||
#endif
|
||||
}
|
||||
}
|
||||
else if(!clipolled){
|
||||
}
|
||||
else if(cli_events){
|
||||
if(fds[fdsc].revents & (POLLERR|POLLNVAL)) {
|
||||
CLIENTTERMREAD = 1;
|
||||
@@ -601,27 +704,27 @@ log("ready to write to client");
|
||||
}
|
||||
if(fds[fdsc].revents & (POLLHUP)) {
|
||||
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;
|
||||
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(!after){
|
||||
fds[fdsc].fd = param->remsock;
|
||||
if(fromserver && !SERVERTERMREAD && !FROMSERVER && !SESSIONEND && ((
|
||||
#ifdef WITHSPLICE
|
||||
!usesplice &&
|
||||
#endif
|
||||
TOSERVERBUF)
|
||||
#ifdef WITHSPLICE
|
||||
|| (usesplice)
|
||||
#endif
|
||||
))
|
||||
if(fromserver && !SERVERTERMREAD && !FROMSERVER && !SESSIONEND &&
|
||||
((!splicesrv && TOSERVERBUF) || (splicesrv && !wantbufsrv)))
|
||||
srv_events |= POLLIN;
|
||||
if(!TOSERVER && !SERVERTERMWRITE && (inclientbuf
|
||||
#ifdef WITHSPLICE
|
||||
@@ -629,6 +732,7 @@ log("ready to write to client");
|
||||
#endif
|
||||
))
|
||||
srv_events |= POLLOUT;
|
||||
srvpolled = srv_events || !SERVERHUP;
|
||||
if(srv_events){
|
||||
fds[fdsc].fd = param->remsock;
|
||||
fds[fdsc].events = srv_events;
|
||||
@@ -640,6 +744,8 @@ log("wait writing from server");
|
||||
#endif
|
||||
}
|
||||
}
|
||||
else if(!srvpolled){
|
||||
}
|
||||
else if(srv_events){
|
||||
if(fds[fdsc].revents & (POLLERR|POLLNVAL)) {
|
||||
#ifdef WITHLOG
|
||||
@@ -668,18 +774,24 @@ log("ready to write to server");
|
||||
log("server terminated connection");
|
||||
#endif
|
||||
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;
|
||||
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
|
||||
if(usesplice){
|
||||
if(fromclient>inclientpipe && !TOCLIENTPIPE && inclientpipe < MAXSPLICE){
|
||||
{
|
||||
if(splicecli && fromclient>inclientpipe && !TOCLIENTPIPE && inclientpipe < MAXSPLICE){
|
||||
if(!after){
|
||||
#ifdef WITHLOG
|
||||
log("wait writing to client pipe");
|
||||
@@ -700,7 +812,7 @@ log("ready to write to client pipe");
|
||||
}
|
||||
fdsc++;
|
||||
}
|
||||
if(inclientpipe && !FROMCLIENTPIPE){
|
||||
if(splicecli && inclientpipe && !FROMCLIENTPIPE){
|
||||
if(!after){
|
||||
#ifdef WITHLOG
|
||||
log("wait reading from client pipe");
|
||||
@@ -719,7 +831,7 @@ log("ready reading from client pipe");
|
||||
}
|
||||
fdsc++;
|
||||
}
|
||||
if(fromserver>inserverpipe && !TOSERVERPIPE && inserverpipe < MAXSPLICE){
|
||||
if(splicesrv && fromserver>inserverpipe && !TOSERVERPIPE && inserverpipe < MAXSPLICE){
|
||||
if(!after){
|
||||
#ifdef WITHLOG
|
||||
log("wait writing to server pipe");
|
||||
@@ -738,7 +850,7 @@ log("ready writing to server pipe");
|
||||
}
|
||||
fdsc++;
|
||||
}
|
||||
if(inserverpipe && !FROMSERVERPIPE){
|
||||
if(splicesrv && inserverpipe && !FROMSERVERPIPE){
|
||||
if(!after){
|
||||
#ifdef WITHLOG
|
||||
log("wait reading from server pipe");
|
||||
@@ -819,18 +931,29 @@ log("timeout");
|
||||
else if(inclientpipe || inserverpipe) res = 94;
|
||||
#endif
|
||||
|
||||
if((param->nwrites > 0 && !SERVERTERMWRITE) || (param->nreads > 0 && !CLIENTTERMWRITE))
|
||||
usleep(SLEEPTIME * 10);
|
||||
|
||||
CLEANRET:
|
||||
|
||||
#ifdef WITHSPLICE
|
||||
if(pipecli[0] >= 0) close(pipecli[0]);
|
||||
if(pipecli[1] >= 0) close(pipecli[1]);
|
||||
if(pipesrv[0] >= 0) close(pipesrv[0]);
|
||||
if(pipesrv[1] >= 0) close(pipesrv[1]);
|
||||
/* empty pipes stay with the connection for its next mapping; one still
|
||||
holding data, left by an error or a timeout, cannot be used again */
|
||||
if(inclientpipe && pipecli[0] >= 0){
|
||||
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
|
||||
|
||||
return res;
|
||||
}
|
||||
#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;
|
||||
if(command == 2){
|
||||
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);}
|
||||
}
|
||||
break;
|
||||
@@ -230,7 +230,7 @@ fprintf(stderr, "%hu bound to communicate with server\n", *SAPORT(¶m->sinsl)
|
||||
fflush(stderr);
|
||||
#endif
|
||||
}
|
||||
sasize = SASIZE(¶m->sinsl);
|
||||
sasize = sizeof(param->sinsl);
|
||||
param->srv->so._getsockname(param->sostate, param->remsock, (struct sockaddr *)¶m->sinsl, &sasize);
|
||||
}
|
||||
if(command == 3) {
|
||||
@@ -250,7 +250,7 @@ fflush(stderr);
|
||||
*SAPORT(&sin) = 0;
|
||||
/* the port the client is told to send its datagrams to */
|
||||
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);
|
||||
#if SOCKSTRACE > 0
|
||||
fprintf(stderr, "%hu binded to communicate with client\n",
|
||||
@@ -272,12 +272,17 @@ CLEANRET:
|
||||
int repcode;
|
||||
|
||||
sasize = sizeof(sin);
|
||||
if(command != 3 && param->remsock != INVALID_SOCKET) param->srv->so._getsockname(param->sostate, param->remsock, (struct sockaddr *)&sin, &sasize);
|
||||
if(command != 3 && !SAISNULL(¶m->srv->extNat)){
|
||||
uint16_t port;
|
||||
port = *SAPORT(&sin);
|
||||
sin = param->srv->extNat;
|
||||
*SAPORT(&sin) = port;
|
||||
/* CONNECT and BIND report the address of the socket towards the
|
||||
destination, UDP ASSOCIATE the one the client sends its datagrams
|
||||
to, as does a request which never got a socket of its own */
|
||||
if(command != 3 && param->remsock != INVALID_SOCKET){
|
||||
param->srv->so._getsockname(param->sostate, param->remsock, (struct sockaddr *)&sin, &sasize);
|
||||
if(!SAISNULL(¶m->srv->extNat)){
|
||||
uint16_t port;
|
||||
port = *SAPORT(&sin);
|
||||
sin = param->srv->extNat;
|
||||
*SAPORT(&sin) = port;
|
||||
}
|
||||
}
|
||||
else {
|
||||
param->srv->so._getsockname(param->sostate, param->clisock, (struct sockaddr *)&sin, &sasize);
|
||||
|
||||
@@ -409,7 +409,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_read_ahead((SSL *)((ssl_conn *)ServerConn)->ssl, 0);
|
||||
SSL_set_read_ahead((SSL *)((ssl_conn *)ServerConn)->ssl, SSL_READAHEAD);
|
||||
|
||||
return ServerConn;
|
||||
}
|
||||
@@ -442,7 +442,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_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);
|
||||
|
||||
@@ -772,14 +772,14 @@ static FILTER_ACTION ssl_filter_client(void *fo, struct clientparam * param, voi
|
||||
return REJECT;
|
||||
}
|
||||
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);
|
||||
}
|
||||
return CONTINUE;
|
||||
}
|
||||
|
||||
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)) {
|
||||
return REJECT;
|
||||
}
|
||||
@@ -788,7 +788,7 @@ static FILTER_ACTION ssl_filter_connect(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)) {
|
||||
return REJECT;
|
||||
}
|
||||
@@ -806,7 +806,7 @@ static FILTER_ACTION ssl_filter_predata(void *fc, struct clientparam * param){
|
||||
if(!param->redirectfunc) param->redirectfunc = proxyfunc;
|
||||
return CONTINUE;
|
||||
}
|
||||
else if(PCONF->cli && client_mode == 2) {
|
||||
else if(PCONF->cli && PCONF->client_mode == 2) {
|
||||
if(docli(param)) {
|
||||
return REJECT;
|
||||
}
|
||||
@@ -815,7 +815,7 @@ static FILTER_ACTION ssl_filter_predata(void *fc, 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)) {
|
||||
return REJECT;
|
||||
}
|
||||
@@ -867,6 +867,9 @@ static void ssl_filter_close(void *fo){
|
||||
free(CONFIG->client_ca_file);
|
||||
free(CONFIG->client_ca_dir);
|
||||
free(CONFIG->client_ca_store);
|
||||
free(CONFIG->server_ca_file);
|
||||
free(CONFIG->server_ca_dir);
|
||||
free(CONFIG->server_ca_store);
|
||||
free(CONFIG->client_sni);
|
||||
if(CONFIG->client_alpn_protos.protos_len){
|
||||
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_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
|
||||
//
|
||||
|
||||
+46
-1
@@ -22,6 +22,7 @@
|
||||
#include <wolfssl/openssl/pem.h>
|
||||
#include <wolfssl/openssl/ssl.h>
|
||||
#include <wolfssl/openssl/err.h>
|
||||
#include <wolfssl/openssl/bn.h>
|
||||
#else
|
||||
#include <openssl/crypto.h>
|
||||
#include <openssl/x509.h>
|
||||
@@ -29,6 +30,7 @@
|
||||
#include <openssl/pem.h>
|
||||
#include <openssl/ssl.h>
|
||||
#include <openssl/err.h>
|
||||
#include <openssl/bn.h>
|
||||
#endif
|
||||
|
||||
#include "proxy.h"
|
||||
@@ -115,6 +117,31 @@ static int add_ext(X509 *cert, int nid, const char *value)
|
||||
}
|
||||
#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)
|
||||
{
|
||||
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 */
|
||||
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_issuer_name(dst_cert, X509_get_subject_name(config->CA_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)
|
||||
{
|
||||
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);
|
||||
#endif
|
||||
}
|
||||
|
||||
void ssl_conn_free(SSL_CONN connection)
|
||||
|
||||
+2
-2
@@ -31,8 +31,8 @@ unsigned char * strings[] = {
|
||||
/* 18 */ (unsigned char *)"AUTO",
|
||||
/* 19 */ (unsigned char *)"TLSPR",
|
||||
/* 20 */ (unsigned char *)"IMAPP",
|
||||
/* 21 */ (unsigned char *)"ZOMBIE",
|
||||
/* 22 */ NULL,
|
||||
/* 21 */ (unsigned char *)"HTTPSRV",
|
||||
/* 22 */ (unsigned char *)"ZOMBIE",
|
||||
/* 23 */ NULL,
|
||||
/* 24 */ NULL,
|
||||
#ifndef TPROXY_CONF
|
||||
|
||||
+23
-3
@@ -47,6 +47,7 @@ typedef struct _3proxy_sem_s {
|
||||
pthread_cond_t cond;
|
||||
unsigned count;
|
||||
unsigned maxcount;
|
||||
int monotonic; /* timed waits measured on CLOCK_MONOTONIC */
|
||||
} _3proxy_sem_t;
|
||||
#else
|
||||
#include <winsock2.h>
|
||||
@@ -112,6 +113,7 @@ int
|
||||
|
||||
#ifdef WITH_UN
|
||||
#include <sys/un.h>
|
||||
#include <stddef.h>
|
||||
#endif
|
||||
|
||||
#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_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_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) :
|
||||
#else
|
||||
#define UN_SAPORT(sa)
|
||||
@@ -528,6 +532,14 @@ struct filterp {
|
||||
|
||||
#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 {
|
||||
void * state;
|
||||
@@ -599,6 +611,8 @@ struct srvparam {
|
||||
AUTHFUNC authfunc;
|
||||
PROXYFUNC pf;
|
||||
SOCKET srvsock, cbsock;
|
||||
/* the file of a Unix socket bound to a path, to remove only it */
|
||||
uint64_t undev, unino;
|
||||
int childcount;
|
||||
int maxchild;
|
||||
int backlog;
|
||||
@@ -612,12 +626,13 @@ struct srvparam {
|
||||
int stacksize;
|
||||
int noforce;
|
||||
int anonymous;
|
||||
int clisockopts, srvsockopts, lissockopts, cbcsockopts, cbssockopts;
|
||||
struct sockoptset clisockopts, srvsockopts, lissockopts, cbcsockopts, cbssockopts;
|
||||
int gracetraf, gracenum, gracedelay;
|
||||
int requirecert;
|
||||
int haproxy;
|
||||
int nostarttls;
|
||||
PROXYSERVICE srvstarttls;
|
||||
int allowftp; /* the http proxy fetches ftp:// for this service */
|
||||
uint32_t fakeip;
|
||||
unsigned char fakeip6[16];
|
||||
#ifdef WITHSPLICE
|
||||
@@ -634,6 +649,7 @@ struct srvparam {
|
||||
#endif
|
||||
PROXYSOCKADDRTYPE extsa;
|
||||
_3proxy_mutex_t counter_mutex;
|
||||
_3proxy_sem_t childslots; /* maxchild of them, one held by each child */
|
||||
struct pollfd fds;
|
||||
FILE *stdlog;
|
||||
unsigned char * target;
|
||||
@@ -732,6 +748,11 @@ struct clientparam {
|
||||
*clibuf,
|
||||
*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,
|
||||
srvinbuf,
|
||||
clioffset,
|
||||
@@ -785,7 +806,6 @@ struct filemon {
|
||||
|
||||
|
||||
struct extparam {
|
||||
_3proxy_sem_t threadinit;
|
||||
int *timeouts;
|
||||
struct ace * acl;
|
||||
#ifdef WITH_HTTPSRV
|
||||
|
||||
+1
-1
@@ -140,7 +140,7 @@ int udpbind(struct clientparam *param)
|
||||
return 12;
|
||||
}
|
||||
}
|
||||
sasize = SASIZE(¶m->sinsl);
|
||||
sasize = sizeof(param->sinsl);
|
||||
param->srv->so._getsockname(param->sostate, param->remsock,
|
||||
(struct sockaddr *)¶m->sinsl, &sasize);
|
||||
return 0;
|
||||
|
||||
+4
-4
@@ -1,14 +1,14 @@
|
||||
#ifndef VERSION
|
||||
#define VERSION "3proxy-1.0.1"
|
||||
#define VERSION "3proxy-1.0.2"
|
||||
#endif
|
||||
#ifndef BUILDDATE
|
||||
#define BUILDDATE "261010162101"
|
||||
#define BUILDDATE "261024112140"
|
||||
#endif
|
||||
#define MAJOR3PROXY 1
|
||||
#define SUBMAJOR3PROXY 0
|
||||
#define MINOR3PROXY 1
|
||||
#define MINOR3PROXY 2
|
||||
#define SUBMINOR3PROXY 0
|
||||
#define RELEASE3PROXY "3proxy-1.0.1(" BUILDDATE ")\0"
|
||||
#define RELEASE3PROXY "3proxy-1.0.2(" BUILDDATE ")\0"
|
||||
#ifndef YEAR3PROXY
|
||||
#define YEAR3PROXY "2026"
|
||||
#endif
|
||||
+4
-3
@@ -69,7 +69,7 @@ means to stand on its own should start with one - otherwise an earlier
|
||||
|
||||
## 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,
|
||||
-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
|
||||
@@ -78,12 +78,13 @@ covers, and how much of a fixture it needs.
|
||||
### Traffic limits and accounting
|
||||
|
||||
`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
|
||||
bandwidth limit, and the admin counters page already shows what a counter
|
||||
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
|
||||
|
||||
|
||||
+28
-3
@@ -1,10 +1,12 @@
|
||||
"""The admin interface, now a set of handlers on the HTTP server."""
|
||||
|
||||
import time
|
||||
|
||||
|
||||
def run(t):
|
||||
adm = t.free_port()
|
||||
lim = t.free_port()
|
||||
t.start("admin", f"""
|
||||
server = t.start("admin", f"""
|
||||
log
|
||||
auth iponly
|
||||
allow *
|
||||
@@ -20,17 +22,40 @@ def run(t):
|
||||
|
||||
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 -----------------------------------------
|
||||
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 + "/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")
|
||||
|
||||
counters = t.http(url + "/C")
|
||||
t.contains(counters, "countin", "the counters page names the counter type")
|
||||
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")
|
||||
# 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 -----------
|
||||
main = t.http(url + "/")
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
"""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):
|
||||
# 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()
|
||||
@@ -107,10 +107,16 @@ def run(t):
|
||||
"peer.port")
|
||||
t.in_range(port, MLOW, MHIGH, "CONNECT uses the range its rule sets")
|
||||
|
||||
# a plain GET matches the later rule, which sets no range
|
||||
port = int_field(t.http(origin + "/echo", proxy=method_proxy), "peer.port")
|
||||
t.not_in_range(port, MLOW, MHIGH,
|
||||
"a method outside that rule keeps an ephemeral port")
|
||||
# a plain GET matches the later rule, which sets no range. On Linux the
|
||||
# window lies within the ephemeral range, so an ephemeral port falls in
|
||||
# it now and then by chance: bound to the window every port would, so
|
||||
# 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 --------------------------------
|
||||
# Linux ignores a range outside net.ipv4.ip_local_port_range, and any
|
||||
|
||||
@@ -1,5 +1,29 @@
|
||||
"""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):
|
||||
# --- tcppm ---------------------------------------------------------
|
||||
@@ -40,6 +64,41 @@ def run(t):
|
||||
|
||||
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 ---------------------------------------------------------
|
||||
# something has to be listening for the mapped datagrams to go anywhere
|
||||
echo = t.udp_echo()
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
"""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 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)
|
||||
Reference in new issue
Block a user