Compare commits

...
67 Commits
Author SHA1 Message Date
github-actions[bot] e28d86d7e4 Update version files for 1.0.4 2026-11-21 09:08:54 +00:00
Vladimir Dubrovin 7da58510d0 Commit as 1.0.4 2026-11-21 12:08:39 +03:00
Vladimir Dubrovin 8b298657ce socks: a SOCKS4a request is not a connect to the null address
C/C++ CI Linux / ubuntu-24.04-arm (push) Canceled after 0s
C/C++ CI Linux / ubuntu-latest (push) Canceled after 0s
C/C++ CI MacOS / macos-15 (push) Canceled after 0s
C/C++ CI Windows / windows-2022 (push) Canceled after 0s
C/C++ CI cmake / macos-15 (push) Canceled after 0s
C/C++ CI cmake / ubuntu-24.04-arm (push) Canceled after 0s
C/C++ CI cmake / ubuntu-latest (push) Canceled after 0s
C/C++ CI cmake / windows-2022 (push) Canceled after 0s
C/C++ CI cmake / ubuntu-latest (wolfSSL) (push) Canceled after 0s
2026-11-18 21:37:33 +03:00
Vladimir Dubrovin 84f6ee6ce4 auth: the pre-authorization of a UDP ASSOCIATE is not cached 2026-11-18 20:43:59 +03:00
Vladimir Dubrovin 37eaa4f2a9 socks: a UDP association is not relayed direct when its parent fails 2026-11-18 20:43:58 +03:00
Vladimir Dubrovin 46297ecf7e socks: a host name with control bytes or spaces is refused where it is read 2026-11-18 20:43:58 +03:00
Vladimir Dubrovin 734c968030 smtpp: a login name of a port alone names no destination 2026-11-18 20:43:58 +03:00
Vladimir Dubrovin 5babf687f6 proxy: credentials of an earlier request not inherited by the next
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI MacOS / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI Windows / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
C/C++ CI cmake / ubuntu-latest (wolfSSL) (push) Has been cancelled
2026-11-13 17:38:47 +03:00
Vladimir Dubrovin 3894d25a02 httpsrv: credentials of an earlier request not inherited by the next 2026-11-13 17:14:36 +03:00
Vladimir Dubrovin 9a2351abeb tlspr: a ServerHello too short for the extensions length refused (#1286)
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI MacOS / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI Windows / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
C/C++ CI cmake / ubuntu-latest (wolfSSL) (push) Has been cancelled
2026-11-10 15:20:08 +03:00
Vladimir Dubrovin 99e72a1417 httpsrv: a limit exceeded answered with 503, not ignored
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI MacOS / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI Windows / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
C/C++ CI cmake / ubuntu-latest (wolfSSL) (push) Has been cancelled
Authorization reports 10 when a limit of the service was exceeded,
which every other child answers with 503; the http server took it as
success and answered the request anyway. It now says 503 for itself,
after the body of the request is drained as any answer here does.

(cherry picked from commit 5a2e9d27c3)
2026-11-08 14:40:00 +03:00
Vladimir Dubrovin 9d2616e8ba httpsrv: a dot-dot segment of a path refused, with either separator
A path ending in a backslashed dot-dot, or carrying one in a form the
checks did not name, was taken as it stood. Any dot-dot segment is now
refused wherever it is and whichever separator carries it, and a path
ending in a bare dot of either kind.

(cherry picked from commit c0eb7a65c6)
2026-11-08 14:40:00 +03:00
Vladimir Dubrovin 78385588ec pcre: a rule with no ACL a match data of its own, not itself
A rule whose ACL was missing was handed to the filters as the
connection's data, which they read as a match data block and freed:
a pointer into the configuration, dereferenced as another type and
given back to malloc. A rule without an ACL now skips the check and
goes on with a block of its own, and nothing a filter is given is
ever the rule itself.

(cherry picked from commit a7e5a8b48b)
2026-11-08 14:40:00 +03:00
github-actions[bot] 4d79d68af6 Update version files for 1.0.3
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI MacOS / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI Windows / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
C/C++ CI cmake / ubuntu-latest (wolfSSL) (push) Has been cancelled
Update version files / version (push) Has been cancelled
2026-11-07 08:50:16 +00:00
Vladimir Dubrovin a355fc7ba5 commit as 1.0.3 2026-11-07 11:50:02 +03:00
Vladimir Dubrovin 14e87dbd78 pcre: a match data of the connection's own, not of the rule's
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI MacOS / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI Windows / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
C/C++ CI cmake / ubuntu-latest (wolfSSL) (push) Has been cancelled
Every connection matching a pcre rule matched on the one match data
block of the rule, which pcre2_match() writes into: two connections
matching at the same time wrote the same block, a race that corrupts
memory and brings the process down after a while under load. A
connection that passes the rule's ACL now makes a match data block of
its own when it starts and frees it when it ends; the match context is
kept, as it is only read while matching.
2026-11-02 12:22:20 +03:00
Vladimir Dubrovin 629a978c00 help: the features of the build listed, and the tests skip what they need
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI MacOS / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI Windows / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
C/C++ CI cmake / ubuntu-latest (wolfSSL) (push) Has been cancelled
3proxy --help (and the usage message of a bad invocation) now lists
what the build was made with: TLS and its backend, RADIUS, PCRE, IPv6,
UNIX sockets, the built-in HTTP server, transparency, ODBC and the
optional proxy services. The test runner reads the list before the
first case and the cases state the features they need with
t.skip_unless(), so a build without a feature skips its cases instead
of failing them; a binary too old to report anything skips the cases
with needs and runs the rest.
2026-10-30 14:24:46 +03:00
Vladimir Dubrovin a75b488aaf radius: the reply hashed with the secret, and taken only from the server asked
The reply digest copied the shared secret right after the received
bytes, so a reply of 4100 bytes with a secret of 17 or more characters
wrote up to 47 bytes of it past the reply buffer on the stack, before
the reply was authenticated. The digest is now taken over the reply
and the secret in place, with nothing written past the reply, and it
fails closed when the hash cannot be made. A reply is also taken only
from the address and port of the server the request went to, and only
when its identifier and length field match the request, all before any
digest work; the reply's sender was never checked before.
2026-10-30 13:47:21 +03:00
Vladimir Dubrovin e9714fa4df resolve: the PTR answer of dnsname walked inside its record data
The label walk of a DNS PTR answer ran to the end of the whole message,
not to the end of the record's data, and took a compression pointer for
a label length, so it could write past the end of the answer buffer on
the stack. An answer of 3841 bytes or more reached past the buffer
itself. A record that ended exactly at the end of the message was also
read one byte past it. The walk now stops at the end of the record's
data, a name that does not end there, or one that is compressed or
empty is not accepted, and the answer loop reads nothing past the
message.
2026-10-30 12:42:39 +03:00
Vladimir Dubrovin 9be415b731 StringsPlugin: a line's end cut off without reading past it
load_string() put a NUL where a line read from the file had its CR or
LF, and stepped over it as well as over the character after: past the
line's NUL terminator, into what was left in the buffer from longer
lines before, or past its end, writing NULs wherever it found CR or LF.
The line is cut at its first CR or LF instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit e396da2696)
2026-10-28 12:02:37 +03:00
Vladimir DubrovinandClaude Opus 5.5 371e78691d Windows: an error set where socket errors are read
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI MacOS / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI Windows / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
C/C++ CI cmake / ubuntu-latest (wolfSSL) (push) Has been cancelled
errno is WSAGetLastError() on Windows, but seterrno3() set the C
library's errno there: the EAGAIN of a TLS read or write wanting the
socket again was not seen as one, and the error left was whatever the
socket call before had set. seterrno3() sets the socket error now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 15:11:25 +03:00
Vladimir DubrovinandClaude Opus 5.5 a5129f85c7 ftppr: the server's answer to USER reaches the client (#1284)
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Waiting to run
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-latest) (push) Waiting to run
C/C++ CI MacOS / ${{ matrix.target }} (macos-15) (push) Waiting to run
C/C++ CI Windows / ${{ matrix.target }} (windows-2022) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (macos-15) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-latest) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (windows-2022) (push) Waiting to run
C/C++ CI cmake / ubuntu-latest (wolfSSL) (push) Waiting to run
A server which logs in on USER alone (230, anonymous FTP often does) or
refuses it had its answer read but not handed back: ftplogin() gave the
length of what it read only for the answer to PASS. The client, told
331 by ftppr and waiting for the answer to its PASS, waited until the
time out. The answer to USER is the client's now when there is no PASS.

The test case logs in through ftppr to a server answering 230, a
multiline 230, 331 then 230, 530, and 331 then 530.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 17:39:25 +03:00
github-actions[bot] 33dce70177 Update HTML documentation from man pages
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI MacOS / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI Windows / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
C/C++ CI cmake / ubuntu-latest (wolfSSL) (push) Has been cancelled
Update HTML documentation / docs (push) Has been cancelled
Update wiki / wiki (push) Has been cancelled
2026-10-25 15:55:05 +00:00
Vladimir DubrovinandClaude Opus 5.5 d770c51761 -B: the TLS ClientHello split at the SNI, which -s is taken for splice
tlspr splits the ClientHello it passes in the middle of the server name
(SNI) when the service has s_option, set by -s. In builds with splice()
(Linux, the default there) -s is splice for every service but UDP ones,
admin and httpsrv, so the split was never made, and the How-To's SNI
break did nothing on Linux.

-B sets it whatever the build: for TCP services but admin and httpsrv,
where s_option has a meaning of its own. -s still does it where it is
not splice. The How-To, 3proxy.cfg(5) and tlspr(8) give -B.

Fixes #1283

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 18:53:03 +03:00
Vladimir DubrovinandClaude Opus 5.5 aaa36f1dd1 Outgoing connections bound with IP_BIND_ADDRESS_NO_PORT
The socket of a connection to the destination is bound to the external
address before connect(), with port 0 unless a range is given. bind()
then takes an ephemeral port for the socket alone: not one in use
towards another destination, nor one of a connection still closing in
TIME_WAIT, which connect() would reuse. With many connections the range
runs out and bind() fails, result 12, or searches long for a port: 7 ms
a call was seen. The more connections are open at once, the sooner:
with event loops, serving more of them at once, the client of every
tenth connection or so of a saturated relay got its end at once.

Where the system has IP_BIND_ADDRESS_NO_PORT (Linux 4.2), the port is
left to connect() for a socket that is going to connect: chosen for
the pair with the destination, together with IP_LOCAL_PORT_RANGE when
a range is given.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 16:34:14 +03:00
Vladimir DubrovinandClaude Opus 5.5 b56e5aff2b ftppr: the data socket towards the client from the socket functions
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Waiting to run
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-latest) (push) Waiting to run
C/C++ CI MacOS / ${{ matrix.target }} (macos-15) (push) Waiting to run
C/C++ CI Windows / ${{ matrix.target }} (windows-2022) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (macos-15) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-latest) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (windows-2022) (push) Waiting to run
C/C++ CI cmake / ubuntu-latest (wolfSSL) (push) Waiting to run
It was made with socket(), past the socket functions of the service,
which the rest of its life went through.

(cherry picked from commit 7718ffa)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 20:56:15 +03:00
Vladimir DubrovinandClaude Opus 5.5 0c80c9f526 Connect back: a connection one client takes leaves the others waiting
The clients of a -R service all wait for the connection back on the
same listening socket, which was blocking: one connection woke them
all, one took it, and the others were left in accept() until the next,
past their time out and through a reload. The socket is non-blocking,
and an accept() which finds nothing, the connection taken by another
client or gone, is not one of the client's tries. nonblock() makes a
socket non-blocking, acceptagain() tells such an accept().
(cherry picked from commit 126c7d0)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 20:56:15 +03:00
Vladimir DubrovinandClaude Opus 5.5 62fd5e3a8d TLS: a read needing to write, or a write to read, waits for it
A read TLS could do only once it wrote, or a write once it read, was an
error which ended the connection, as when TLS 1.3 answers a key update
while the socket cannot take more. Each TLS socket remembers what a read
and a write it could not do wait for, and the poll of the TLS layer
waits for it instead of what was asked: whatever that gets is the
caller's chance to try again, revents what it asked for, and its events
are given back as they were.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 20:15:05 +03:00
Vladimir DubrovinandClaude Opus 5.5 50bc4b4e27 FilePlugin: socksend() given no clientparam, not a TLS state for one
socksend() takes the client's parameters, and was passed the socket
functions' state instead: NULL, the global functions used then, as
intended, but on a TLS connection the state of its TLS layer, which
socksend() read as a clientparam.
(cherry picked from commit 718798c)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 20:07:13 +03:00
Vladimir DubrovinandClaude Opus 5.5 b0b796823d README: branches, devel is 1.1 and experimental 2.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 16:17:28 +03:00
Vladimir DubrovinandClaude Opus 5.5 ef70f3223f Release builds: rpm x86-64 and OpenWrt on ubuntu-24.04
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Waiting to run
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-latest) (push) Waiting to run
C/C++ CI MacOS / ${{ matrix.target }} (macos-15) (push) Waiting to run
C/C++ CI Windows / ${{ matrix.target }} (windows-2022) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (macos-15) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-latest) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (windows-2022) (push) Waiting to run
C/C++ CI cmake / ubuntu-latest (wolfSSL) (push) Waiting to run
Update version files / version (push) Has been cancelled
ubuntu-latest is now 26.04. Its rpm 6 runs the signing command of
.rpmmacros without taking its second word as argv[0], so gpg got the
"gpg" there as a file name and every rpm of 1.0.2 failed to sign. The
OpenWrt 24.10 SDK refuses its install, which is not GNU's. arm64 already
builds on ubuntu-24.04-arm.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 14:45:26 +03:00
Vladimir Dubrovin 001e2874c5 Update SECURITY.md
Update supported versions
2026-10-24 14:29:22 +03:00
github-actions[bot] 72a32eecd5 Update version files for 1.0.2 2026-10-24 11:21:41 +00:00
Vladimir Dubrovin 9a4602872d Release as 1.0.2 2026-10-24 14:21:29 +03:00
Vladimir DubrovinandClaude Opus 5.5 615fa9b5fc Sockets: sends with MSG_NOSIGNAL where the system has it
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Waiting to run
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-latest) (push) Waiting to run
C/C++ CI MacOS / ${{ matrix.target }} (macos-15) (push) Waiting to run
C/C++ CI Windows / ${{ matrix.target }} (windows-2022) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (macos-15) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-latest) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (windows-2022) (push) Waiting to run
C/C++ CI cmake / ubuntu-latest (wolfSSL) (push) Waiting to run
A peer gone is then an error of the send rather than SIGPIPE. SIGPIPE
stays ignored for what cannot pass the flag: TLS writes and splice().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 16:56:41 +03:00
Vladimir DubrovinandClaude Opus 5.5 3081a05cf7 MITM: a serial number of its own when wolfSSL cannot copy the source's
wolfSSL built with WOLFSSL_QT, as Ubuntu 26.04's 5.9.1 is, returns a
serial number without the ASN.1 header its X509_set_serialNumber()
requires, so every certificate copy failed. The copy then gets a
positive serial number from the hash of the source certificate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 16:56:41 +03:00
Vladimir DubrovinandClaude Opus 5.5 e13c8d518f SIGPIPE ignored before any service starts, and in standalone services
3proxy ignored SIGPIPE only after readconfig(), which starts the
services: a client gone while written to in the meantime killed the
process (as auto's case saw on macOS). Standalone services never ignored
it. Sends pass no MSG_NOSIGNAL, so this is the only guard.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 16:56:41 +03:00
Vladimir DubrovinandClaude Opus 5.5 99795d8dfe sockrecvfrom: poll again when a readable socket has nothing to read
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Waiting to run
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-latest) (push) Waiting to run
C/C++ CI MacOS / ${{ matrix.target }} (macos-15) (push) Waiting to run
C/C++ CI Windows / ${{ matrix.target }} (windows-2022) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (macos-15) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-latest) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (windows-2022) (push) Waiting to run
C/C++ CI cmake / ubuntu-latest (wolfSSL) (push) Waiting to run
sockrecvfrom() polled once and then read in a loop for as long as the
read failed with EAGAIN. Over TLS a socket is readable when only a part
of a record has come, and the read fails with EAGAIN until the rest
does: a client sending half a record and then nothing kept a thread
taking all of a CPU, and the read never timed out. On EAGAIN the socket
is now polled again, the read repeated at once only for EINTR.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 16:03:21 +03:00
Vladimir DubrovinandClaude Opus 5.5 94a83d126f dnspr: only the answer to the query asked is relayed
dnspr relayed to the client whatever came first to the socket it asked
the name server from, from any address, under any id. Now:

- the query goes to the name server under a random id of its own, the
  client's put back in what is relayed to it;
- an answer over UDP is taken only from the address and port of the
  name server asked, anything else read past until DNS_TO runs out;
- the answer must have that id, be a response, and carry the question
  asked byte for byte, over UDP and TCP alike (a TCP answer that does
  not is error 834).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 12:04:18 +03:00
Vladimir DubrovinandClaude Opus 5.5 4edb94d09e Read TLS records ahead with OpenSSL 1.1.0 and later
Read-ahead was off, so OpenSSL read every record in two calls, its
header and then its body. It was off because ssl_poll() asks
ssl_pending(), and SSL_pending() does not count data read ahead and not
yet decrypted: poll() would wait while data waits in OpenSSL.
SSL_has_pending() does count it. With OpenSSL 1.1.0 and later, which
have it, ssl_pending() uses it and records are read ahead; with older
ones and wolfSSL nothing changes.

SSL_has_pending() is also true when only a part of a record has been
read ahead, which is no data yet: poll() would then return at once, over
and over and without its timeout, until the rest came. ssl_pending()
says so only when decrypted data waits, or when what was read ahead
makes a whole record (SSL_peek() of one byte, the sockets not blocking);
otherwise the socket is polled for the rest.

Decrypting TLS streams takes 9-14% less time for the same data (ARM).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 12:04:08 +03:00
Vladimir DubrovinandClaude Opus 5.5 4a90c65a6a Ignore the bench load generator binaries
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Waiting to run
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-latest) (push) Waiting to run
C/C++ CI MacOS / ${{ matrix.target }} (macos-15) (push) Waiting to run
C/C++ CI Windows / ${{ matrix.target }} (windows-2022) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (macos-15) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-latest) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (windows-2022) (push) Waiting to run
C/C++ CI cmake / ubuntu-latest (wolfSSL) (push) Waiting to run
bench/mix/build.sh builds them; a checkout switched from devel, where
bench/mix/.gitignore covers them, keeps them as untracked files.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 20:37:16 +03:00
Vladimir DubrovinandClaude Opus 5.5 364286d6d9 Free the HTTP proxy's request buffer while a connection waits
proxychild() allocated its 64 KB buffer for headers once and kept it
for the life of the connection: for a CONNECT tunnel all the time data
was relayed, and for a kept-alive connection between its requests.
With 2000 tunnels that was 128 MB, with 20000 mostly idle connections
over a gigabyte.

The buffer is now freed before a tunnel starts relaying, and when a
kept-alive connection has waited a second for its next request; it is
allocated again once the next request starts coming. logurl() takes a
copy of its own for a request it logs after its buffer was freed.

2000 tunnels: 339 to 213 MB; 20000 connections, 3000 exchanges a
second: 2.65 to 1.63 GB through the HTTP proxy, 2.66 to 1.42 GB through
CONNECT; busy kept-alive connections within 1.5% of before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 20:37:16 +03:00
Vladimir DubrovinandClaude Opus 5.5 07bedfa64c tests: parent_ports tells an ephemeral port from the window by several
On Linux the port windows lie within net.ipv4.ip_local_port_range, as
the kernel honours no other, so the ephemeral port of a request the
range does not apply to falls into the 50-port window now and then
(CI saw 34001 in 33968-34017). The case now makes five such requests
and wants one of them outside the window: bound to it, all would be in.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 12:58:43 +03:00
Vladimir DubrovinandClaude Opus 5.5 ef4969da19 Unix sockets: no addresses on streams, abstract names, tcppm port 0
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI MacOS / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI Windows / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
C/C++ CI cmake / ubuntu-latest (wolfSSL) (push) Has been cancelled
On Linux a proxy listening on a Unix socket relayed only the first
bytes of an answer (result 95): sockmap() read with recvfrom() into the
client's address, which for a Unix stream socket Linux fills with an
empty AF_UNIX one, and then sent with sendto() to that address, which a
connected Unix stream socket refuses. A TCP connection has no use for
addresses: sockmap() now sends and receives with NULL ones, and
connect-back sends its command with socksend() and reads the answer
with sockrecvfrom() without an address, which a NULL sin now allows.

An abstract socket name (-iunix:@NAME) was bound with the whole size of
struct sockaddr_un, padded with zeros, so a client naming it by its
bytes, as most do, reached another name. SASIZE() now gives an abstract
address its exact size; getsockname() calls that took SASIZE() of the
old contents as the buffer size take the buffer's size instead.

tcppm refused port 0 for a unix: target, though the manual gives
"tcppm 8080 unix:/var/run/app.sock 0" as the example: the port of a
Unix socket target is ignored, so 0 is allowed.

On a reload the new service bound the path anew and the old one,
closing after it, removed the file, the new service's by then, leaving
nothing to connect to. A service now notes the file it bound (device
and inode) and removes the path on closing only if it is still that
file.

A test case covers a proxy on a Unix socket and on an abstract one on
Linux, tcppm to a Unix socket, a parent reached through one, and a
listening Unix socket across reloads: its file kept and the proxy
answering, and the file removed once no service listens on it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 12:25:13 +03:00
Vladimir DubrovinandClaude Opus 5.5 36ac6e673b Name the HTTPSRV service in the string table
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI MacOS / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI Windows / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (macos-15) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-latest) (push) Has been cancelled
C/C++ CI cmake / ${{ matrix.target }} (windows-2022) (push) Has been cancelled
C/C++ CI cmake / ubuntu-latest (wolfSSL) (push) Has been cancelled
S_HTTPSRV, the type of admin and httpsrv services, was added before
S_ZOMBIE without a name in the string table, so its index held
"ZOMBIE": the admin services page, %N in logs and RADIUS named admin
and httpsrv services and their clients ZOMBIE, and a zombie service had
no name at all (NULL). Index 21 is now "HTTPSRV", 22 "ZOMBIE"; 22 was
unused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 15:36:13 +03:00
Vladimir Dubrovin 292a855f34 Fix memory leaks found under AddressSanitizer
- readconfig() kept its line buffer and argument array on every error
  return, so each refused reload leaked them.
- A filter refusing a connection in filter_client (TLS: a failed
  handshake) was not kept, so its filter_clear never ran and the state
  it made was lost. makefilters() now clears it, and empties the slot
  first: a pooled worker's slot may hold the previous connection's.
- ssl_filter_close() freed the client CA paths but not the server ones,
  for every TLS service set up.
- Compiled patterns were never freed: an ACL's (pcre: and regex: host
  names), an httpsrv rule's. copyacl() shared them between the
  configuration's ACL and each service's copy; each copy now compiles
  its own, and freeacl() and freehttprules() free them.

What LeakSanitizer still reports is OpenSSL's per-thread random
generator state of pooled threads, released only by OpenSSL at exit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 796e9f8156)
2026-10-14 20:15:42 +03:00
Vladimir DubrovinandClaude Opus 5.5 9651848bf1 Fix the Watcom build, and UNC paths in httpsrv on Windows
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Waiting to run
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-latest) (push) Waiting to run
C/C++ CI MacOS / ${{ matrix.target }} (macos-15) (push) Waiting to run
C/C++ CI Windows / ${{ matrix.target }} (windows-2022) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (macos-15) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-latest) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (windows-2022) (push) Waiting to run
C/C++ CI cmake / ubuntu-latest (wolfSSL) (push) Waiting to run
Open Watcom has no struct _stat64 or _wstat64: its 64-bit stat is
struct _stati64 and _wstati64, so httpsrv.c did not compile there and
the 1.0.1 lite build had no binaries.

widepath() compared and wrote '\\\\', a two-character constant, for a
backslash: a UNC path (\\server\share) never took the \\?\UNC\ form,
and forward slashes became backslashes only because the constant was
truncated to its last byte.

The Watcom workflow passed although nmake failed; it now fails when
the build does or leaves no 3proxy.exe.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 17:40:16 +03:00
Vladimir Dubrovin c89a7b14c7 Use the service's ssl_client_mode, not the last one configured
ssl_filter_open() copies ssl_client_mode into the service's
configuration, but the filters deciding when to begin TLS towards the
server read the global value instead: the last ssl_client_mode in the
configuration applied to every service, and a reload changed it for the
services still running.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit bab80ef684)
2026-10-13 15:30:03 +03:00
Vladimir Dubrovin 41edaa9757 Leave a hung-up socket out of poll() rather than pass an invalid one
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Waiting to run
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-latest) (push) Waiting to run
C/C++ CI MacOS / ${{ matrix.target }} (macos-15) (push) Waiting to run
C/C++ CI Windows / ${{ matrix.target }} (windows-2022) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (macos-15) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-latest) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (windows-2022) (push) Waiting to run
C/C++ CI cmake / ubuntu-latest (wolfSSL) (push) Waiting to run
A socket which hung up and of which nothing is asked was given to poll()
as INVALID_SOCKET, so that poll() would not return at once for the
hang-up every time. poll() ignores a negative descriptor, but SOCKET is
unsigned on Windows, and WSAPoll fails the whole call for it: sockmap()
ended the session as soon as a client half-closed. Such a socket is now
not in the array at all.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 98fd0f329f)
2026-10-13 13:09:41 +03:00
Vladimir Dubrovin 84dd84a993 Write to a peer that hung up while it still reads, on Windows
sockmap() took a hang-up on a socket it had data to write to for a peer
it could no longer write to. With poll() a hang-up comes once both sides
are shut down, so that held. WSAPoll reports one as soon as the peer has
half-closed, still reading, and a half-closed client got nothing on
Windows: the test added with the previous fix failed there.

The write is now tried, and a peer really gone makes it fail, which
ends the connection as before. WSAPoll keeps reporting the hang-up
whether the socket has room or not, so on Windows room is waited for
with select() first unless poll() reported it too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit ddefa40affb76de267a8be1cf59a183a8eb77e32)
2026-10-13 12:57:19 +03:00
Vladimir Dubrovin 993c1ef95e Deliver the whole answer to a half-closed client
When the client shuts down its sending side, sockmap() shuts down the
server's in turn, and once the server has answered and closed, poll()
reports a hang-up on its socket. A socket sockmap() had nothing to ask
of at that moment, its buffer being full for a slow client, was still
polled, and a hang-up there ended both directions: whatever of the
answer was still unread in the kernel was dropped and the client got an
end of stream in the middle of it, megabytes short with large answers.

A hang-up on such a socket now only marks it: what is left is read
once the buffer has room, up to the end of the stream as usual. Errors
still end the connection. Since poll() reports a hang-up whatever is
asked, the socket is left out of poll() while nothing is asked of it.
The same holds for the client's side, for an upload cut short after the
server half-closes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 8c87b43a2a)
2026-10-13 12:21:59 +03:00
github-actions[bot] 5bc60d8bb3 Update HTML documentation from man pages
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Waiting to run
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-latest) (push) Waiting to run
C/C++ CI MacOS / ${{ matrix.target }} (macos-15) (push) Waiting to run
C/C++ CI Windows / ${{ matrix.target }} (windows-2022) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (macos-15) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-latest) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (windows-2022) (push) Waiting to run
C/C++ CI cmake / ubuntu-latest (wolfSSL) (push) Waiting to run
Update HTML documentation / docs (push) Has been cancelled
Update wiki / wiki (push) Has been cancelled
2026-10-12 18:59:26 +00:00
Vladimir DubrovinandClaude Opus 5.5 1a66393b25 Keep the server connection when only the request method changes
A kept-alive client connection reuses the connection to the server while
requests go to the same host. The check compared the start of the request
line up to the end of the host, method included, so a POST after a GET to
the same host, or a GET after a POST, closed the server connection and
opened another one. Only the host and port are compared now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 21:57:20 +03:00
Vladimir DubrovinandClaude Opus 5.5 b5e9459d64 Load the time zone and connect syslog before chroot
The C library reads /etc/localtime on the first use of local time and
connects to /dev/log on the first syslog() call. With a chroot before
either, every local time became UTC and every syslog message was lost.
The time zone is now loaded before chroot() and openlog() connects at
once. The chroot entry of 3proxy.cfg(5) lists what PAM, LDAP and ODBC
still need inside the chroot.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 18:16:22 +03:00
Vladimir DubrovinandClaude Opus 5.5 206c923d6c Fix SOCKS CONNECT and BIND replies reporting the client side address
Without -Ne, the reply to CONNECT and BIND named the local address of the
client's connection to the proxy instead of the socket towards the
destination: the branch meant for UDP ASSOCIATE also took these. A BIND
client was told the proxy's own port and the peer could never reach the
listener. Introduced with -Ne / -Ni (0c8be90).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 18:03:07 +03:00
github-actions[bot] 6a3cb4128d Update HTML documentation from man pages
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Waiting to run
C/C++ CI Linux / ${{ matrix.target }} (ubuntu-latest) (push) Waiting to run
C/C++ CI MacOS / ${{ matrix.target }} (macos-15) (push) Waiting to run
C/C++ CI Windows / ${{ matrix.target }} (windows-2022) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (macos-15) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-24.04-arm) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (ubuntu-latest) (push) Waiting to run
C/C++ CI cmake / ${{ matrix.target }} (windows-2022) (push) Waiting to run
C/C++ CI cmake / ubuntu-latest (wolfSSL) (push) Waiting to run
Update HTML documentation / docs (push) Waiting to run
Update wiki / wiki (push) Waiting to run
2026-10-12 11:04:32 +00:00
Vladimir DubrovinandClaude Opus 5.5 94fc4a7116 highload.html: benchmark figures, linked on devel
The benchmarks live on the devel branch only, so link to their results
there; master has no bench/.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 13:59:20 +03:00
Vladimir Dubrovin 89d2131094 Reorganize service config parsing / main loop 2026-10-12 13:58:57 +03:00
Vladimir DubrovinandClaude Opus 5.5 b00e3b9a9c splice() per direction, pipes per connection, automatic mode
-s takes the directions to splice: -s1 what the server sends (downloads),
-s2 what the client sends (uploads), -s3 both. -s alone (-s7) splices both
only where it pays, as -s5 and -s6 do for one direction:
- a body of known length is spliced if at least 16K of it is left to read
  once what is already buffered is counted, so an answer read whole with
  its headers is just copied;
- a stream of unknown length starts copied, is spliced after 2 reads in a
  row of at least 16K, and goes back to copying after 3 splices in a row
  of less than 4K, once its pipe is empty.

Pipes are made when a direction first splices and kept with the
connection for its next mappings, so a kept-alive connection no longer
makes and closes two pipes per request; one left holding data by an
error or a timeout is closed. The direction not spliced keeps its buffer.

Before, -s spliced both directions and every mapping made both pipes,
which made small answers slower than without splice: with kept-alive
50K answers 2 pipe2() and 4 close() per request, now none.

Also corrects the default buffer size in the -b help (65536 for TCP).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 13:58:48 +03:00
Vladimir Dubrovin ee5a7588f8 Fix -s for httpsrv 2026-10-12 13:58:48 +03:00
Vladimir Dubrovin 30ffaff182 Support = in socket options, make TCP_NODELAY default 2026-10-12 13:58:48 +03:00
Vladimir Dubrovin 5c78d1a342 Return splice support in default builds 2026-10-12 13:58:48 +03:00
Vladimir Dubrovin 1cea4fef4b Fix socket draining / lingering 2026-10-12 13:58:48 +03:00
Vladimir DubrovinandClaude Opus 5.5 24ac413fc5 Tests: wait for the reload requested in the admin case
The reload asked for through /R happens on the next tick of the main
loop, and between the old services stopping and the new ones starting a
request is refused: on Windows the new listener cannot bind the port
until the old one has closed it, and retries with a growing delay. When
the tick fell inside the case, every request after it failed with
ConnectionRefusedError (MSVC run of 98e8dfb). The case now waits for
both services to have restarted after each /R.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 13:58:48 +03:00
Vladimir Dubrovin c6e290b8e6 Remove sleeps on proxy termination 2026-10-12 13:58:48 +03:00
Vladimir Dubrovin 77f8870c5d Change waiting loops to semaphores for child counters 2026-10-12 13:58:48 +03:00
Vladimir Dubrovin d4eaf5acc8 -Xftp flag for http proxy 2026-10-12 13:58:48 +03:00
80 changed files with 3467 additions and 1320 deletions

No files matched your search

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