Script 'mail_helper' called by obssrc
Hello community,

here is the log from the commit of package 3proxy for openSUSE:Factory checked 
in at 2026-11-21 21:47:56
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Comparing /work/SRC/openSUSE:Factory/3proxy (Old)
 and      /work/SRC/openSUSE:Factory/.3proxy.new.1340718 (New)
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Package is "3proxy"

Sat Nov 21 21:47:56 2026 rev:10 rq:1399620 version:1.0.4

Changes:
--------
--- /work/SRC/openSUSE:Factory/3proxy/3proxy.changes    2026-11-07 
23:34:54.549239480 +0100
+++ /work/SRC/openSUSE:Factory/.3proxy.new.1340718/3proxy.changes       
2026-11-21 21:49:57.590140160 +0100
@@ -1,0 +2,6 @@
+Sat Nov 21 11:04:31 UTC 2026 - Илья Индиго <[email protected]>
+
+- Updated to 1.0.4
+  * https://github.com/3proxy/3proxy/releases/tag/1.0.4
+
+-------------------------------------------------------------------

Old:
----
  3proxy-1.0.3.tar.gz

New:
----
  3proxy-1.0.4.tar.gz

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Other differences:
------------------
++++++ 3proxy.spec ++++++
--- /var/tmp/diff_new_pack.bBmZwg/_old  2026-11-21 21:49:58.355172835 +0100
+++ /var/tmp/diff_new_pack.bBmZwg/_new  2026-11-21 21:49:58.357172921 +0100
@@ -21,7 +21,7 @@
 %define _group  proxy
 %define _home   %{_localstatedir}/lib/%{name}
 Name:           3proxy
-Version:        1.0.3
+Version:        1.0.4
 Release:        0
 Summary:        Tiny proxy servers set
 License:        Apache-2.0 OR BSD-3-Clause OR GPL-2.0-or-later OR 
LGPL-2.1-or-later

++++++ 3proxy-1.0.3.tar.gz -> 3proxy-1.0.4.tar.gz ++++++
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' old/3proxy-1.0.3/CHANGELOG new/3proxy-1.0.4/CHANGELOG
--- old/3proxy-1.0.3/CHANGELOG  2026-11-07 09:50:16.000000000 +0100
+++ new/3proxy-1.0.4/CHANGELOG  2026-11-21 10:08:54.000000000 +0100
@@ -1,13 +1,13 @@
-3proxy-1.0.3 Released November, 7 2026
+3proxy-1.0.4 Released November, 21 2026
 
-! 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
+! 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
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' old/3proxy-1.0.3/CHANGELOG.rus 
new/3proxy-1.0.4/CHANGELOG.rus
--- old/3proxy-1.0.3/CHANGELOG.rus      2026-11-07 09:50:16.000000000 +0100
+++ new/3proxy-1.0.4/CHANGELOG.rus      2026-11-21 10:08:54.000000000 +0100
@@ -1,13 +1,13 @@
-3proxy-1.0.3 Вышел 7 Ноября 2026
+3proxy-1.0.4 Вышел 21 Ноября 2026
 
-! Исправление: аутентификация RADIUS: дайджест ответа копировал общий секрет 
сразу за принятыми байтами, так что ответ размером 4100 байт с секретом в 17 и 
более символов записывал до 47 байт секрета за буфер ответа на стеке, ещё до 
проверки подлинности ответа; дайджест теперь вычисляется по ответу и секрету на 
месте, ничего не записывая за буфер, а ответ принимается только с адреса и 
порта сервера, которому был адресован запрос, с совпадающими с запросом 
идентификатором и длиной: раньше отправитель ответа не проверялся вовсе
-! Исправление: ответ PTR от сервера имён мог записать данные за буфер ответа 
на стеке: обход имён шёл до конца всего сообщения вместо конца данных записи и 
мог принять байт-указатель сжатия за длину метки (ответ размером 3841 байт и 
более выходил за сам буфер); теперь обход останавливается в конце данных 
записи, а сжатое, пустое или обрезанное имя не принимается
-! Исправление: каждое соединение, проверяемое правилом pcre: (или regex:), 
сопоставлялось с единственным блоком данных сопоставления правила, в который 
пишет pcre2_match(): два соединения, сопоставляемые одновременно, конкурировали 
за него и портили память, приводя процесс к падению под нагрузкой; теперь 
каждое соединение получает собственный блок данных сопоставления
-! Исправление: TLS: чтение, возможное только после записи, или запись только 
после чтения (например, когда TLS 1.3 отвечает на обновление ключей, а сокет 
больше не принимает данные) завершало соединение с ошибкой; каждый TLS-сокет 
теперь помнит, чего ждут его незавершённые чтение и запись, и poll() TLS-уровня 
ждёт именно этого
-! Исправление: Windows: чтение или запись TLS, требующая повторного обращения 
к сокету, не распознавалась, и соединение завершалось с посторонней ошибкой: в 
месте чтения ошибки сокета устанавливалась ошибка libc (errno)
-! Исправление: клиент обратного соединения (connect back, -R) оставался в 
accept() в ожидании соединения, которое забрал другой клиент той же службы, до 
следующего соединения, переживая свой тайм-аут и перезагрузку конфигурации; 
сокет обратного соединения теперь неблокирующий, и accept() без соединения не 
считается попыткой клиента
-! Исправление: ftppr: ответ сервера, входящего по одному USER (230, как часто 
бывает у анонимного FTP) или отказывающего во входе, прочитывался, но не 
передавался клиенту, который оставался ждать ответа на свой PASS до тайм-аута 
(#1284)
-! Исправление: плагины: StringsPlugin, обрезая строку таблицы строк на её 
конце, записывал NUL за строкой, в остатки в буфере от прочитанных раньше более 
длинных строк или за его конец; FilePlugin передавал в socksend() состояние TLS 
соединения вместо параметров клиента, и отправка таблицы строк по 
TLS-соединению читала состояние TLS как clientparam
-+ -B (для TCP-служб) разбивает проходящий через tlspr ClientHello TLS 
посередине имени сервера (SNI), чтобы системы DPI, не собирающие его заново, не 
видели имя хоста; TCP_NODELAY, устанавливаемый по умолчанию, выключать нельзя, 
иначе ядро может снова склеить сегменты; -s сохраняет тот же эффект там, где -s 
не означает splice (#1283)
-+ 3proxy --help (и сообщение об использовании при неверном запуске) 
перечисляет, с чем собран бинарник: TLS и его серверная библиотека, RADIUS, 
PCRE, IPv6, сокеты Unix, встроенный HTTP-сервер, прозрачное проксирование, ODBC 
и необязательные прокси-службы
-+ Исходящее соединение, привязываемое к внешнему адресу, на Linux 4.2 и новее 
привязывается с IP_BIND_ADDRESS_NO_PORT: порт выбирает connect() для пары с 
адресом назначения, поэтому порты, занятые соединениями к другим адресам или 
закрывающиеся в TIME_WAIT, больше не исчерпывают эфемерный диапазон; bind() 
больше не завершался с результатом 12 при большом числе соединений и не тратил 
миллисекунды на поиск порта
+! Исправление: socks: запрос SOCKS4a отвергался как соединение с нулевым 
адресом, хотя в SOCKS4a нулевой адрес означает, что назначение — имя, следующее 
за ним
+! Исправление: auth: UDP ASSOCIATE проходит предварительную авторизацию, не 
зная назначения, от которого зависят её правила, поэтому её вердикт относится 
только к этой ассоциации и не сохраняется для последующих запросов
+! Исправление: socks: UDP-ассоциация передавалась напрямую при сбое родителя, 
хотя правила требовали родителя; теперь она отвергается
+! Исправление: socks: имя хоста с управляющими байтами или пробелами 
принималось как есть; теперь оно отвергается там, где читается
+! Исправление: smtpp: имя входа из одного порта, без хоста, задавало порт, но 
не называло назначения для соединения; такое имя входа теперь отвергается
+! Исправление: proxy: учётные данные раннего запроса в сохранённом соединении 
решали и для последующих запросов; теперь каждый запрос авторизуется своими 
учётными данными
+! Исправление: встроенный http-сервер (httpsrv): учётные данные раннего 
запроса в сохранённом соединении решали и для последующих запросов; теперь 
каждый запрос авторизуется своими учётными данными
+! Исправление: tlspr: ServerHello TLS, слишком короткий для объявленной длины 
расширений, читался за его концом; теперь он отвергается (#1286)
+! Исправление: httpsrv: запрос, для которого превышен лимит службы, всё равно 
выполнялся: 503, которой отвечают остальные службы, принималась за успех; 
теперь отвечается 503, после того как тело запроса прочитано
+! Исправление: httpsrv: путь, оканчивающийся экранированной точкой-точкой или 
несущий её в форме, которую проверки не называли, принимался как есть; теперь 
любой сегмент точка-точка отвергается, где бы он ни был и каким бы разделителем 
ни был записан, как и путь, оканчивающийся одиночной точкой любого вида
+! Исправление: pcre: правило без ACL передавалось фильтрам как данные 
соединения, и они читали его как блок данных сопоставления и освобождали: 
указатель в конфигурацию, разыменованный как другой тип и возвращённый malloc; 
теперь правило без ACL пропускает проверку и идёт со своим блоком
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' old/3proxy-1.0.3/RELEASE new/3proxy-1.0.4/RELEASE
--- old/3proxy-1.0.3/RELEASE    2026-11-07 09:50:16.000000000 +0100
+++ new/3proxy-1.0.4/RELEASE    2026-11-21 10:08:54.000000000 +0100
@@ -1 +1 @@
-1.0.3
\ No newline at end of file
+1.0.4
\ No newline at end of file
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' old/3proxy-1.0.3/debian/changelog 
new/3proxy-1.0.4/debian/changelog
--- old/3proxy-1.0.3/debian/changelog   2026-11-07 09:50:16.000000000 +0100
+++ new/3proxy-1.0.4/debian/changelog   2026-11-21 10:08:54.000000000 +0100
@@ -1,3 +1,9 @@
+3proxy (1.0.4-1) buster; urgency=medium
+
+  *3proxy 1.0.4 initial build
+
+ -- z3APA3A <[email protected]>  Sat, 21 Nov 2026 09:08:54 +0000
+
 3proxy (1.0.3-1) buster; urgency=medium
 
   *3proxy 1.0.3 initial build
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' old/3proxy-1.0.3/doc/changelog/1/0/4 
new/3proxy-1.0.4/doc/changelog/1/0/4
--- old/3proxy-1.0.3/doc/changelog/1/0/4        1970-01-01 01:00:00.000000000 
+0100
+++ new/3proxy-1.0.4/doc/changelog/1/0/4        2026-11-21 10:08:54.000000000 
+0100
@@ -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
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' old/3proxy-1.0.3/scripts/rh/3proxy.spec 
new/3proxy-1.0.4/scripts/rh/3proxy.spec
--- old/3proxy-1.0.3/scripts/rh/3proxy.spec     2026-11-07 09:50:16.000000000 
+0100
+++ new/3proxy-1.0.4/scripts/rh/3proxy.spec     2026-11-21 10:08:54.000000000 
+0100
@@ -1,5 +1,5 @@
 Name:           3proxy
-Version:        1.0.3
+Version:        1.0.4
 Release:        1%{?dist}
 Summary:        3proxy tiny proxy server
 License:        GPL/LGPL/Apache/BSD
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' old/3proxy-1.0.3/src/auth.c new/3proxy-1.0.4/src/auth.c
--- old/3proxy-1.0.3/src/auth.c 2026-11-07 09:50:16.000000000 +0100
+++ new/3proxy-1.0.4/src/auth.c 2026-11-21 10:08:54.000000000 +0100
@@ -125,7 +125,10 @@
                        if(authfuncs->authorize &&
                                (res = (*authfuncs->authorize)(param)))
                                        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=""};
 
                            if(param->username) {
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' old/3proxy-1.0.3/src/common.c 
new/3proxy-1.0.4/src/common.c
--- old/3proxy-1.0.3/src/common.c       2026-11-07 09:50:16.000000000 +0100
+++ new/3proxy-1.0.4/src/common.c       2026-11-21 10:08:54.000000000 +0100
@@ -542,11 +542,26 @@
        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){
        char *sp=NULL,*se=NULL;
        int ret = 0;
 
        if(!hostname || !*hostname)return 2;
+       if(badhostname(hostname)) return 1;
        if(*hostname == '[') se=strchr(hostname, ']');
        if ((sp = strchr(se?se:hostname, ':'))) {
                if(strchr(sp+1, ':'))sp = NULL;
@@ -560,6 +575,9 @@
                        port = atoi(sp+1);
                        *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);
                return 0;
        }
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' old/3proxy-1.0.3/src/httpsrv.c 
new/3proxy-1.0.4/src/httpsrv.c
--- old/3proxy-1.0.3/src/httpsrv.c      2026-11-07 09:50:16.000000000 +0100
+++ new/3proxy-1.0.4/src/httpsrv.c      2026-11-21 10:08:54.000000000 +0100
@@ -430,11 +430,12 @@
 #endif
        }
        if(!strncmp(path, "./", 2) || !strncmp(path, "../", 3)) return 1;
-       if(strstr(path, "/./") || strstr(path, "/../")) return 1;
-       if(strstr(path, "\\.\\") || strstr(path, "\\..\\")) return 1;
+       /* a dot-dot segment, with either separator, wherever it is in the
+          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);
-       if(p - path >= 2 && !strcmp(p - 2, "/.")) return 1;
-       if(p - path >= 3 && !strcmp(p - 3, "/..")) return 1;
+       if(p - path >= 2 && (!strcmp(p - 2, "/.") || !strcmp(p - 2, "\\."))) 
return 1;
        return 0;
 }
 
@@ -1495,16 +1496,27 @@
                        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
                   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);
                RETURN(i);
        }
@@ -1606,6 +1618,23 @@
                r.lasthost = lasthost;
                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);
                handoff = r.handoff;
                if(r.raw) free(r.raw);
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' old/3proxy-1.0.3/src/pcre.c new/3proxy-1.0.4/src/pcre.c
--- old/3proxy-1.0.3/src/pcre.c 2026-11-07 09:50:16.000000000 +0100
+++ new/3proxy-1.0.4/src/pcre.c 2026-11-21 10:08:54.000000000 +0100
@@ -264,13 +264,14 @@
        struct pcre_filter_data *rule = (struct pcre_filter_data *)fo;
        struct pcre_client_data *pcd;
 
-       *fc = fo;
+       *fc = NULL;
        if(!fo) return PASS;
-       if(!rule->acl) return CONTINUE;
-       memset (&tmpace, 0, sizeof(struct ace));
-       tmpace.src = rule->acl->src;
-       res = pl->ACLMatches(&tmpace, param);
-       if(!res) return PASS;
+       if(rule->acl){
+               memset (&tmpace, 0, sizeof(struct ace));
+               tmpace.src = rule->acl->src;
+               res = pl->ACLMatches(&tmpace, param);
+               if(!res) return PASS;
+       }
        /* the connection goes on with a match data of its own */
        if(!(pcd = pl->mallocfunc(sizeof(struct pcre_client_data)))){
                *fc = NULL;
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' old/3proxy-1.0.3/src/proxy.c new/3proxy-1.0.4/src/proxy.c
--- old/3proxy-1.0.3/src/proxy.c        2026-11-07 09:50:16.000000000 +0100
+++ new/3proxy-1.0.4/src/proxy.c        2026-11-21 10:08:54.000000000 +0100
@@ -340,6 +340,27 @@
  clhdrofs_req = -1;
  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){
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' old/3proxy-1.0.3/src/proxy.h new/3proxy-1.0.4/src/proxy.h
--- old/3proxy-1.0.3/src/proxy.h        2026-11-07 09:50:16.000000000 +0100
+++ new/3proxy-1.0.4/src/proxy.h        2026-11-21 10:08:54.000000000 +0100
@@ -370,6 +370,7 @@
 int hashresolv(struct hashtable *ht, void* name, void* value, uint32_t *ttl);
 
 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 parseusername(char *username, struct clientparam *param, int extpasswd);
 int parseconnusername(char *username, struct clientparam *param, int 
extpasswd, uint16_t port);
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' old/3proxy-1.0.3/src/smtpp.c new/3proxy-1.0.4/src/smtpp.c
--- old/3proxy-1.0.3/src/smtpp.c        2026-11-07 09:50:16.000000000 +0100
+++ new/3proxy-1.0.4/src/smtpp.c        2026-11-21 10:08:54.000000000 +0100
@@ -197,6 +197,10 @@
        }
  }
 
+ /* 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
  {
        int action, reqbufsize, reqsize;
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' old/3proxy-1.0.3/src/socks.c new/3proxy-1.0.4/src/socks.c
--- old/3proxy-1.0.3/src/socks.c        2026-11-07 09:50:16.000000000 +0100
+++ new/3proxy-1.0.4/src/socks.c        2026-11-21 10:08:54.000000000 +0100
@@ -119,7 +119,10 @@
                }
                res = socks5_setaddr(param->srv->family, c, buf, &param->req);
                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;
                myinet_ntop(*SAFAMILY(&param->sinsr), SAADDR(&param->sinsr), 
(char *)buf, 64);
                break;
@@ -137,6 +140,7 @@
        default:
                RETURN(997);
  }
+ if(badhostname((char *)buf)) {RETURN(21);}
  if(param->hostname)free(param->hostname);
  param->hostname = (unsigned char *)strdup((char *)buf);
  if(!param->hostname){RETURN(21);}
@@ -159,6 +163,7 @@
                param->service = S_SOCKS45;
                if(sockgetlinebuf(param, CLIENT, buf, BUFSIZE - 1, 0, 
conf.timeouts[STRING_S]) < 0) {RETURN(441);}
                buf[127] = 0;
+               if(badhostname((char *)buf)) {RETURN(21);}
                if(param->hostname)free(param->hostname);
                param->hostname = (unsigned char *)strdup((char *)buf);
                if(!param->hostname){RETURN(21);}
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' old/3proxy-1.0.3/src/tlspr.c new/3proxy-1.0.4/src/tlspr.c
--- old/3proxy-1.0.3/src/tlspr.c        2026-11-07 09:50:16.000000000 +0100
+++ new/3proxy-1.0.4/src/tlspr.c        2026-11-21 10:08:54.000000000 +0100
@@ -224,6 +224,7 @@
     else if(type == 2){
        offset += 3;
     }
+    if((offset + 2) > len) return -6;
     elen = size16(hello+offset);
     offset += 2;
     if(elen+offset != len) return -9;
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' old/3proxy-1.0.3/src/udpsockmap.c 
new/3proxy-1.0.4/src/udpsockmap.c
--- old/3proxy-1.0.3/src/udpsockmap.c   2026-11-07 09:50:16.000000000 +0100
+++ new/3proxy-1.0.4/src/udpsockmap.c   2026-11-21 10:08:54.000000000 +0100
@@ -162,8 +162,10 @@
 /*
  * 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.
- * Returns the authorization result. param->remsock is INVALID_SOCKET if the
- * socket can not be created, in this case the association can not continue.
+ * Returns the authorization result. param->remsock is INVALID_SOCKET when
+ * 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)
 {
@@ -189,9 +191,10 @@
                        param->remsock = INVALID_SOCKET;
                }
                udpreset(param);
+               return res;
        }
-       if (udpbind(param)) return res? res : 11;
-       return res;
+       if (udpbind(param)) return 11;
+       return 0;
 }
 
 int udpsockmap(struct clientparam *param, int timeo)
@@ -281,6 +284,7 @@
                                if (len < 7 + sz) return 485;
                                memcpy(dstnamebuf, base + 5, sz);
                                dstnamebuf[sz] = 0;
+                               if (badhostname(dstnamebuf)) continue;
                                dstname = dstnamebuf;
                                i = 5 + sz;
                                if (!getip46(param->srv->family, (unsigned char 
*)dstnamebuf,
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' old/3proxy-1.0.3/src/version.h 
new/3proxy-1.0.4/src/version.h
--- old/3proxy-1.0.3/src/version.h      2026-11-07 09:50:16.000000000 +0100
+++ new/3proxy-1.0.4/src/version.h      2026-11-21 10:08:54.000000000 +0100
@@ -1,14 +1,14 @@
 #ifndef VERSION
-#define VERSION "3proxy-1.0.3"
+#define VERSION "3proxy-1.0.4"
 #endif
 #ifndef BUILDDATE
-#define BUILDDATE "261107085016"
+#define BUILDDATE "261121090854"
 #endif
 #define MAJOR3PROXY 1
 #define SUBMAJOR3PROXY 0
-#define MINOR3PROXY 3
+#define MINOR3PROXY 4
 #define SUBMINOR3PROXY 0
-#define RELEASE3PROXY "3proxy-1.0.3(" BUILDDATE ")\0"
+#define RELEASE3PROXY "3proxy-1.0.4(" BUILDDATE ")\0"
 #ifndef YEAR3PROXY
 #define YEAR3PROXY "2026"
 #endif
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' old/3proxy-1.0.3/tests/cases/httpsrv_auth.py 
new/3proxy-1.0.4/tests/cases/httpsrv_auth.py
--- old/3proxy-1.0.3/tests/cases/httpsrv_auth.py        2026-11-07 
09:50:16.000000000 +0100
+++ new/3proxy-1.0.4/tests/cases/httpsrv_auth.py        2026-11-21 
10:08:54.000000000 +0100
@@ -1,5 +1,7 @@
 """Authentication and access rules in front of the HTTP server."""
 
+import base64
+
 
 def run(t):
     if not t.skip_unless("httpsrv"):
@@ -49,3 +51,19 @@
 
     t.contains(t.http(url + "/echo", auth=("alice", "secret")), "path=/echo",
                "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")
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' old/3proxy-1.0.3/tests/cases/parent_failover.py 
new/3proxy-1.0.4/tests/cases/parent_failover.py
--- old/3proxy-1.0.3/tests/cases/parent_failover.py     2026-11-07 
09:50:16.000000000 +0100
+++ new/3proxy-1.0.4/tests/cases/parent_failover.py     2026-11-21 
10:08:54.000000000 +0100
@@ -9,9 +9,22 @@
 case here needs at most one parent to fail before a working one is reached.
 """
 
+import socket
+import struct
 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):
     """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)
@@ -152,6 +165,90 @@
     t.eq(1, wait_served(goodp, needle, 1, gmark),
          "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 --------------------------------------
     out = t.run_config("failover_badweight", f"""
         auth iponly
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' old/3proxy-1.0.3/tests/cases/proxy_http.py 
new/3proxy-1.0.4/tests/cases/proxy_http.py
--- old/3proxy-1.0.3/tests/cases/proxy_http.py  2026-11-07 09:50:16.000000000 
+0100
+++ new/3proxy-1.0.4/tests/cases/proxy_http.py  2026-11-21 10:08:54.000000000 
+0100
@@ -4,6 +4,8 @@
 from a clean list.
 """
 
+import base64
+
 
 def run(t):
     if not t.skip_unless("httpsrv"):
@@ -108,3 +110,18 @@
     t.eq(407, t.http(origin + "/echo", proxy=needs_auth,
                      proxy_auth=("alice", "wrong")).status,
          "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")
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' old/3proxy-1.0.3/tests/cases/smtpp.py 
new/3proxy-1.0.4/tests/cases/smtpp.py
--- old/3proxy-1.0.3/tests/cases/smtpp.py       1970-01-01 01:00:00.000000000 
+0100
+++ new/3proxy-1.0.4/tests/cases/smtpp.py       2026-11-21 10:08:54.000000000 
+0100
@@ -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"[email protected]: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")
diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' 
'--exclude=.svnignore' old/3proxy-1.0.3/tests/cases/socks.py 
new/3proxy-1.0.4/tests/cases/socks.py
--- old/3proxy-1.0.3/tests/cases/socks.py       2026-11-07 09:50:16.000000000 
+0100
+++ new/3proxy-1.0.4/tests/cases/socks.py       2026-11-21 10:08:54.000000000 
+0100
@@ -1,5 +1,19 @@
 """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):
     if not t.skip_unless("httpsrv"):
@@ -96,3 +110,121 @@
          "wrong SOCKS5 credentials are refused")
     t.ne(None, t.socks_connect(guarded, "127.0.0.1", srv),
          "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()

Reply via email to