Compare commits

..
24 Commits
Author SHA1 Message Date
rofl0r bc87de3482 Release 1.11.0 2021-04-16 13:47:21 +01:00
rofl0r 11a4f6c5cf reverse: ensure paths always end with a slash 2021-03-28 20:36:55 +01:00
rofl0r 64badd6b37 htab: prevent filling up of table with tombstones
as pointed out by @craigbarnes [0], using the latest fix for
the tombstone issue, it's possible to provoke a situation
that causes an endless loop when all free slots in the table
are filled up with tombstones and htab_find() is called.

therefore we need to account for those as well when deciding
if there's a need to call resize() so there's never more than
75% of the table used by either dead or live items.
the resize() serves as a rehash which gets rid of all deleted
entries, and it might cause the table size to shrink if
htab_insert() is called after a lot of items have been removed.

[0]: https://github.com/rofl0r/htab/issues/1#issuecomment-800094442

testcase:

    #include <assert.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include "hsearch.h"

    #define HTAB_OOM_TEST
    #include "hsearch.c"

    static char *xstrdup(const char *str)
    {
        char *dup = strdup(str);
        assert(dup);
        return dup;
    }

    void utoa(unsigned number, char* buffer) {
            int lentest, len = 0, i, start = 0;

            lentest = number;
            do {
                    len++;
                    lentest /= 10;
            } while(lentest);
            buffer[start+len] = 0;
            do {
                    i = number % 10;
                    buffer[start+len - 1] = '0' + i;
                    number -= i;
                    len -= 1;
                    number /= 10;
            } while (number);
    }

    #define TESTSIZE 8
    #define KEEP 1

    static char* notorious[TESTSIZE];

    static void prep() {
    	srand(0);
    	char buf[16];
    	size_t filled = 0;
    	while(filled < TESTSIZE) {
    		utoa(rand(), buf);
    		size_t idx = keyhash(buf) & (TESTSIZE-1);
    		if(!notorious[idx]) {
    			notorious[idx] = xstrdup(buf);
    			++filled;
    		}
    	}
    }

    int main(void)
    {
    	struct htab *h = htab_create(TESTSIZE);
    	size_t i;
    	assert(h);

    	prep();
    	for(i=0; i<TESTSIZE; ++i) {
    		char *key = notorious[i];
    		printf("[%zu] = \"%s\"\n", i, key);
    		int r = htab_insert(h, key, HTV_N(42));
    		if(!r == 1) {
    			printf("element %zu couldn't be inserted\n", i);
    			break;
    		}
    		assert(r == 1);
    		// Ensure newly inserted entry can be found
    		assert(htab_find(h, key));
    		if(i >= KEEP) htab_delete(h, key);
    	}

    	htab_find(h, "looooop");

    	return 0;
    }
2021-03-28 20:33:17 +01:00
rofl0r 48860bbe26 refactor html-error so send_http_headers() can take extra arg
we already required an extra argument inside the headers sent
for 401 and 407 error responses, move those to sent_http_error_message()
and refactor send_http_headers() to always take the extra argument.
in calling sites where the extra arg isn't needed, use "".
2021-03-28 20:24:23 +01:00
rofl0r c4231e58bf orderedmap: fix memory leak when using orderedmap_remove()
closes #351
2021-03-14 16:06:10 +00:00
rofl0r 38934921c4 htab_delete(): fix failure to set tombstone
we can't just set an item's key to zero and be done with a deletion,
because this will break the item search chain.
a deleted item requires a special marker, also known as tombstone.
when searching for an item, all slots with a tombstone need to treated
as if they were in use, but when inserting an item such a slot needs
to be filled with the new item.

a common procedure is to rehash the table when the number of deleted
items crosses a certain threshold, though for simplicity we leave this
task to the resize() function which does the same thing anyway when
the hashtable grows.

this allows to fix the issue quite elegantly and with almost no
additional overhead, so we don't penalize applications that do very
few deletions.
2021-03-14 01:57:21 +00:00
rofl0r 4147e917d6 configure: check whether gperf is compatible
closes #337
2021-02-13 09:53:55 +00:00
rofl0r adad565c03 http-message: fix UB passing long to format string expecting int 2020-10-19 20:33:04 +01:00
rofl0r db5c0e99b4 reqs: fix UB passing ssize_t to format string expecting int 2020-10-19 20:30:10 +01:00
rofl0r 8ebbd50cb2 log: replace non-mt-safe localtime() with localtime_r() 2020-10-19 20:26:12 +01:00
rofl0r 732bdd0f56 replace usage of non-threadsafe gmtime() with gmtime_r()
the latter is a standard POSIX function too.
2020-10-19 20:21:26 +01:00
Anton Khirnov 3bb14e0440 Allow multiple Bind directives.
Try all the addresses specified with Bind in order. This is necessary
e.g. for maintaining IPv4+6 connectivity while still being restricted to
one interface.
2020-10-19 20:08:31 +01:00
Anton Khirnov 2b49ef0e0f sock: add missing format specifier to log_message() 2020-10-19 20:08:31 +01:00
rofl0r f7c616d2b9 log.c: fix format string args 2020-10-19 20:08:31 +01:00
rofl0r cc0a7eb9a2 html-error: move common.h inclusion back to top
this seems to cause an implicit declaration of snprintf() thanks to
feature test macro hell.
2020-10-19 20:08:31 +01:00
rofl0r e20aa221ff conf: move inclusion of common.h back to the start
otherwise the feature-test-macros won't kick in as they should.

should fix #329
2020-10-01 15:25:35 +01:00
rofl0r 8d27503cc3 acl: fix regression using ipv6 with netmask
introduced in 0ad8904b40

closes #327
2020-09-30 19:23:34 +01:00
rofl0r 3950a606a4 conf: only treat space and tab as whitespace
other characters in the [[:space:]] set can't possibly be encountered,
and this speeds up parsing by approximately 10%.
2020-09-30 05:31:56 +01:00
rofl0r a8944b93e7 conf: use [0-9] instead of [[:digit:]] for shorter re strings 2020-09-30 05:28:00 +01:00
rofl0r 960972865c print linenumber from all conf-emitted warnings 2020-09-30 05:21:26 +01:00
rofl0r f55c46eb39 log: print timestamps with millisecond precision
this allows easier time measurements for benchmarks.
2020-09-30 05:20:09 +01:00
rofl0r 10494cab8c change loglevel of "Not running as root" message to INFO
there's no reason to display this as warning.
2020-09-30 05:19:16 +01:00
rofl0r 4f1a1663ff conf: remove bogus support for hex literals
the INT regex macro supported a 0x prefix (used e.g. for port numbers),
however following that, only digits were accepted, and not the full
range of hexdigits. it's unlikely this was used, so remove it.

note that the () expression is kept, so we don't have to adjust match
number indices all over the place.
2020-09-30 05:14:57 +01:00
rofl0r 35c8edcf73 speed up build by only including regex.h where needed 2020-09-30 05:13:45 +01:00
22 changed files with 239 additions and 134 deletions

No files matched your search

+1 -1
View File
@@ -1 +1 @@
1.11.0-rc1 1.11.0
+7
View File
@@ -210,7 +210,14 @@ AH_TEMPLATE([HAVE_GPERF],
[Whether you have gperf installed for faster config parsing.]) [Whether you have gperf installed for faster config parsing.])
if test "x$GPERF" != "x" -a "x$GPERF" != "xno" ; then if test "x$GPERF" != "x" -a "x$GPERF" != "xno" ; then
AS_ECHO_N(["checking whether gperf is recent enough... "])
if "$GPERF" < src/conf-tokens.gperf >/dev/null 2>&1 ; then
AS_ECHO("yes")
AC_DEFINE(HAVE_GPERF) AC_DEFINE(HAVE_GPERF)
else
AM_CONDITIONAL(HAVE_GPERF, false)
AS_ECHO("no")
fi
fi fi
AC_CONFIG_FILES([ AC_CONFIG_FILES([
+2
View File
@@ -58,6 +58,8 @@ only on one specific address.
This allows you to specify which address Tinyproxy will bind This allows you to specify which address Tinyproxy will bind
to for outgoing connections to web servers or upstream proxies. to for outgoing connections to web servers or upstream proxies.
This parameter may be specified multiple times, then Tinyproxy
will try all the specified addresses in order.
=item B<BindSame> =item B<BindSame>
+25 -38
View File
@@ -138,15 +138,12 @@ int
insert_acl (char *location, acl_access_t access_type, acl_list_t *access_list) insert_acl (char *location, acl_access_t access_type, acl_list_t *access_list)
{ {
struct acl_s acl; struct acl_s acl;
int ret; char *mask, ip_dst[IPV6_LEN];
char *p, ip_dst[IPV6_LEN];
assert (location != NULL); assert (location != NULL);
ret = init_access_list(access_list); if (init_access_list(access_list) != 0)
if (ret != 0) {
return -1; return -1;
}
/* /*
* Start populating the access control structure. * Start populating the access control structure.
@@ -154,38 +151,19 @@ insert_acl (char *location, acl_access_t access_type, acl_list_t *access_list)
memset (&acl, 0, sizeof (struct acl_s)); memset (&acl, 0, sizeof (struct acl_s));
acl.access = access_type; acl.access = access_type;
if ((mask = strrchr(location, '/')))
*(mask++) = 0;
/* /*
* Check for a valid IP address (the simplest case) first. * Check for a valid IP address (the simplest case) first.
*/ */
if (full_inet_pton (location, ip_dst) > 0) { if (full_inet_pton (location, ip_dst) > 0) {
acl.type = ACL_NUMERIC; acl.type = ACL_NUMERIC;
memcpy (acl.address.ip.network, ip_dst, IPV6_LEN); memcpy (acl.address.ip.network, ip_dst, IPV6_LEN);
memset (acl.address.ip.mask, 0xff, IPV6_LEN); if(!mask) memset (acl.address.ip.mask, 0xff, IPV6_LEN);
} else { else {
int i;
/* bogus ipv6 ? */
if (strchr (location, ':'))
return -1;
/*
* At this point we're either a hostname or an
* IP address with a slash.
*/
p = strchr (location, '/');
if (p != NULL) {
char dst[sizeof(struct in6_addr)]; char dst[sizeof(struct in6_addr)];
int v6; int v6, i;
/*
* We have a slash, so it's intended to be an
* IP address with mask
*/
*p = '\0';
if (full_inet_pton (location, ip_dst) <= 0)
return -1;
acl.type = ACL_NUMERIC;
/* Check if the IP address before the netmask is /* Check if the IP address before the netmask is
* an IPv6 address */ * an IPv6 address */
if (inet_pton(AF_INET6, location, dst) > 0) if (inet_pton(AF_INET6, location, dst) > 0)
@@ -194,24 +172,33 @@ insert_acl (char *location, acl_access_t access_type, acl_list_t *access_list)
v6 = 0; v6 = 0;
if (fill_netmask_array if (fill_netmask_array
(p + 1, v6, &(acl.address.ip.mask[0]), IPV6_LEN) (mask, v6, &(acl.address.ip.mask[0]), IPV6_LEN)
< 0) < 0)
return -1; goto err;
for (i = 0; i < IPV6_LEN; i++) for (i = 0; i < IPV6_LEN; i++)
acl.address.ip.network[i] = ip_dst[i] & acl.address.ip.network[i] = ip_dst[i] &
acl.address.ip.mask[i]; acl.address.ip.mask[i];
} else {
/* In all likelihood a string */
acl.type = ACL_STRING;
acl.address.string = safestrdup (location);
if (!acl.address.string)
return -1;
} }
} else {
/* either bogus IP or hostname */
/* bogus ipv6 ? */
if (mask || strchr (location, ':'))
goto err;
/* In all likelihood a string */
acl.type = ACL_STRING;
acl.address.string = safestrdup (location);
if (!acl.address.string)
goto err;
} }
if(!sblist_add(*access_list, &acl)) return -1; if(!sblist_add(*access_list, &acl)) return -1;
return 0; return 0;
err:;
/* restore mask for proper error message */
if(mask) *(--mask) = '/';
return -1;
} }
/* /*
-1
View File
@@ -68,7 +68,6 @@
# include <arpa/inet.h> # include <arpa/inet.h>
# include <grp.h> # include <grp.h>
# include <pwd.h> # include <pwd.h>
# include <regex.h>
/* rest - some oddball headers */ /* rest - some oddball headers */
#ifdef HAVE_VALUES_H #ifdef HAVE_VALUES_H
+44 -23
View File
@@ -24,6 +24,7 @@
*/ */
#include "common.h" #include "common.h"
#include <regex.h>
#include "conf.h" #include "conf.h"
#include "acl.h" #include "acl.h"
@@ -48,23 +49,25 @@
* can (and likely should) be used when building the regex for the * can (and likely should) be used when building the regex for the
* given directive. * given directive.
*/ */
#define WS "[[:space:]]+" #define DIGIT "[0-9]"
#define SPACE "[ \t]"
#define WS SPACE "+"
#define STR "\"([^\"]+)\"" #define STR "\"([^\"]+)\""
#define BOOL "(yes|on|no|off)" #define BOOL "(yes|on|no|off)"
#define INT "((0x)?[[:digit:]]+)" #define INT "(()" DIGIT "+)"
#define ALNUM "([-a-z0-9._]+)" #define ALNUM "([-a-z0-9._]+)"
#define USERNAME "([^:]*)" #define USERNAME "([^:]*)"
#define PASSWORD "([^@]*)" #define PASSWORD "([^@]*)"
#define IP "((([0-9]{1,3})\\.){3}[0-9]{1,3})" #define IP "((([0-9]{1,3})\\.){3}[0-9]{1,3})"
#define IPMASK "(" IP "(/[[:digit:]]+)?)" #define IPMASK "(" IP "(/" DIGIT "+)?)"
#define IPV6 "(" \ #define IPV6 "(" \
"(([0-9a-f:]{2,39}))|" \ "(([0-9a-f:]{2,39}))|" \
"(([0-9a-f:]{0,29}:" IP "))" \ "(([0-9a-f:]{0,29}:" IP "))" \
")" ")"
#define IPV6MASK "(" IPV6 "(/[[:digit:]]+)?)" #define IPV6MASK "(" IPV6 "(/" DIGIT "+)?)"
#define BEGIN "^[[:space:]]*" #define BEGIN "^" SPACE "*"
#define END "[[:space:]]*$" #define END SPACE "*$"
/* /*
* Limit the maximum number of substring matches to a reasonably high * Limit the maximum number of substring matches to a reasonably high
@@ -73,6 +76,9 @@
*/ */
#define RE_MAX_MATCHES 24 #define RE_MAX_MATCHES 24
#define CP_WARN(FMT, ...) \
log_message (LOG_WARNING, "line %lu: " FMT, lineno, __VA_ARGS__)
/* /*
* All configuration handling functions are REQUIRED to be defined * All configuration handling functions are REQUIRED to be defined
* with the same function template as below. * with the same function template as below.
@@ -285,6 +291,7 @@ void free_config (struct config_s *conf)
safefree (conf->group); safefree (conf->group);
stringlist_free(conf->basicauth_list); stringlist_free(conf->basicauth_list);
stringlist_free(conf->listen_addrs); stringlist_free(conf->listen_addrs);
stringlist_free(conf->bind_addrs);
#ifdef FILTER_ENABLE #ifdef FILTER_ENABLE
safefree (conf->filter); safefree (conf->filter);
#endif /* FILTER_ENABLE */ #endif /* FILTER_ENABLE */
@@ -296,7 +303,6 @@ void free_config (struct config_s *conf)
free_upstream_list (conf->upstream_list); free_upstream_list (conf->upstream_list);
#endif /* UPSTREAM_SUPPORT */ #endif /* UPSTREAM_SUPPORT */
safefree (conf->pidpath); safefree (conf->pidpath);
safefree (conf->bind_address);
safefree (conf->via_proxy_name); safefree (conf->via_proxy_name);
if (conf->errorpages) { if (conf->errorpages) {
it = 0; it = 0;
@@ -637,9 +643,7 @@ static HANDLE_FUNC (handle_anonymous)
return -1; return -1;
if(anonymous_insert (conf, arg) < 0) { if(anonymous_insert (conf, arg) < 0) {
log_message (LOG_WARNING, CP_WARN ("anonymous_insert() failed: '%s'", arg);
"anonymous_insert() failed: '%s'",
arg);
safefree(arg); safefree(arg);
return -1; return -1;
} }
@@ -767,7 +771,7 @@ static HANDLE_FUNC (handle_group)
} }
static void warn_invalid_address(char *arg, unsigned long lineno) { static void warn_invalid_address(char *arg, unsigned long lineno) {
log_message (LOG_WARNING, "Invalid address %s on line %lu", arg, lineno); CP_WARN ("Invalid address %s", arg);
} }
static HANDLE_FUNC (handle_allow) static HANDLE_FUNC (handle_allow)
@@ -792,12 +796,27 @@ static HANDLE_FUNC (handle_deny)
static HANDLE_FUNC (handle_bind) static HANDLE_FUNC (handle_bind)
{ {
int r = set_string_arg (&conf->bind_address, line, &match[2]); char *arg = get_string_arg (line, &match[2]);
if (arg == NULL) {
return -1;
}
if (conf->bind_addrs == NULL) {
conf->bind_addrs = sblist_new(sizeof(char*), 16);
if (conf->bind_addrs == NULL) {
CP_WARN ("Could not create a list "
"of bind addresses.", "");
safefree(arg);
return -1;
}
}
sblist_add (conf->bind_addrs, &arg);
if (r)
return r;
log_message (LOG_INFO, log_message (LOG_INFO,
"Outgoing connections bound to IP %s", conf->bind_address); "Added bind address [%s] for outgoing connections.", arg);
return 0; return 0;
} }
@@ -812,8 +831,8 @@ static HANDLE_FUNC (handle_listen)
if (conf->listen_addrs == NULL) { if (conf->listen_addrs == NULL) {
conf->listen_addrs = sblist_new(sizeof(char*), 16); conf->listen_addrs = sblist_new(sizeof(char*), 16);
if (conf->listen_addrs == NULL) { if (conf->listen_addrs == NULL) {
log_message(LOG_WARNING, "Could not create a list " CP_WARN ("Could not create a list "
"of listen addresses."); "of listen addresses.", "");
safefree(arg); safefree(arg);
return -1; return -1;
} }
@@ -839,9 +858,7 @@ static HANDLE_FUNC (handle_errorfile)
char *page = get_string_arg (line, &match[4]); char *page = get_string_arg (line, &match[4]);
if(add_new_errorpage (conf, page, err) < 0) { if(add_new_errorpage (conf, page, err) < 0) {
log_message (LOG_WARNING, CP_WARN ("add_new_errorpage() failed: '%s'", page);
"add_new_errorpage() failed: '%s'",
page);
safefree (page); safefree (page);
} }
return 0; return 0;
@@ -1024,6 +1041,7 @@ static HANDLE_FUNC (handle_upstream)
int port, mi; int port, mi;
char *domain = 0, *user = 0, *pass = 0, *tmp; char *domain = 0, *user = 0, *pass = 0, *tmp;
enum proxy_type pt; enum proxy_type pt;
enum upstream_build_error ube;
if (match[3].rm_so != -1) { if (match[3].rm_so != -1) {
tmp = get_string_arg (line, &match[3]); tmp = get_string_arg (line, &match[3]);
@@ -1033,9 +1051,9 @@ static HANDLE_FUNC (handle_upstream)
domain = get_string_arg (line, &match[4]); domain = get_string_arg (line, &match[4]);
if (!domain) if (!domain)
return -1; return -1;
upstream_add (NULL, 0, domain, 0, 0, PT_NONE, &conf->upstream_list); ube = upstream_add (NULL, 0, domain, 0, 0, PT_NONE, &conf->upstream_list);
safefree (domain); safefree (domain);
return 0; goto check_err;
} }
} }
@@ -1065,13 +1083,16 @@ static HANDLE_FUNC (handle_upstream)
if (match[mi].rm_so != -1) if (match[mi].rm_so != -1)
domain = get_string_arg (line, &match[mi]); domain = get_string_arg (line, &match[mi]);
upstream_add (ip, port, domain, user, pass, pt, &conf->upstream_list); ube = upstream_add (ip, port, domain, user, pass, pt, &conf->upstream_list);
safefree (user); safefree (user);
safefree (pass); safefree (pass);
safefree (domain); safefree (domain);
safefree (ip); safefree (ip);
check_err:;
if(ube != UBE_SUCCESS)
CP_WARN("%s", upstream_build_error_string(ube));
return 0; return 0;
} }
+1 -1
View File
@@ -68,7 +68,7 @@ struct config_s {
#endif /* UPSTREAM_SUPPORT */ #endif /* UPSTREAM_SUPPORT */
char *pidpath; char *pidpath;
unsigned int idletimeout; unsigned int idletimeout;
char *bind_address; sblist *bind_addrs;
unsigned int bindsame; unsigned int bindsame;
/* /*
+1
View File
@@ -24,6 +24,7 @@
#include "main.h" #include "main.h"
#include <regex.h>
#include "filter.h" #include "filter.h"
#include "heap.h" #include "heap.h"
#include "log.h" #include "log.h"
+32 -14
View File
@@ -49,6 +49,7 @@ struct htab {
size_t mask; size_t mask;
size_t used; size_t used;
size_t seed; size_t seed;
size_t dead;
}; };
#define MINSIZE 8 #define MINSIZE 8
@@ -107,14 +108,14 @@ static int resize(struct htab *htab, size_t nel)
return 1; return 1;
} }
static struct elem *lookup(struct htab *htab, const char *key, size_t hash) static struct elem *lookup(struct htab *htab, const char *key, size_t hash, size_t dead)
{ {
size_t i, j; size_t i, j;
struct elem *e; struct elem *e;
for (i=hash,j=1; ; i+=j++) { for (i=hash,j=1; ; i+=j++) {
e = htab->elems + (i & htab->mask); e = htab->elems + (i & htab->mask);
if (!e->item.key || if ((!e->item.key && (!e->hash || e->hash == dead)) ||
(e->hash==hash && STRCMP(e->item.key, key)==0)) (e->hash==hash && STRCMP(e->item.key, key)==0))
break; break;
} }
@@ -138,50 +139,67 @@ void htab_destroy(struct htab *htab)
free(htab); free(htab);
} }
static htab_entry *htab_find_item(struct htab *htab, const char* key) static struct elem *htab_find_elem(struct htab *htab, const char* key)
{ {
size_t hash = keyhash(key, htab->seed); size_t hash = keyhash(key, htab->seed);
struct elem *e = lookup(htab, key, hash); struct elem *e = lookup(htab, key, hash, 0);
if (e->item.key) { if (e->item.key) {
return &e->item; return e;
} }
return 0; return 0;
} }
htab_value* htab_find(struct htab *htab, const char* key) htab_value* htab_find(struct htab *htab, const char* key)
{ {
htab_entry *i = htab_find_item(htab, key); struct elem *e = htab_find_elem(htab, key);
if(i) return &i->data; if(!e) return 0;
return 0; return &e->item.data;
}
htab_value* htab_find2(struct htab *htab, const char* key, char **saved_key)
{
struct elem *e = htab_find_elem(htab, key);
if(!e) return 0;
*saved_key = e->item.key;
return &e->item.data;
} }
int htab_delete(struct htab *htab, const char* key) int htab_delete(struct htab *htab, const char* key)
{ {
htab_entry *i = htab_find_item(htab, key); struct elem *e = htab_find_elem(htab, key);
if(!i) return 0; if(!e) return 0;
i->key = 0; e->item.key = 0;
e->hash = 0xdeadc0de;
--htab->used;
++htab->dead;
return 1; return 1;
} }
int htab_insert(struct htab *htab, char* key, htab_value value) int htab_insert(struct htab *htab, char* key, htab_value value)
{ {
size_t hash = keyhash(key, htab->seed); size_t hash = keyhash(key, htab->seed), oh;
struct elem *e = lookup(htab, key, hash); struct elem *e = lookup(htab, key, hash, 0xdeadc0de);
if(e->item.key) { if(e->item.key) {
/* it's not allowed to overwrite existing data */ /* it's not allowed to overwrite existing data */
return 0; return 0;
} }
oh = e->hash; /* save old hash in case it's tombstone marker */
e->item.key = key; e->item.key = key;
e->item.data = value; e->item.data = value;
e->hash = hash; e->hash = hash;
if (++htab->used > htab->mask - htab->mask/4) { if (++htab->used + htab->dead > htab->mask - htab->mask/4) {
if (!resize(htab, 2*htab->used)) { if (!resize(htab, 2*htab->used)) {
htab->used--; htab->used--;
e->item.key = 0; e->item.key = 0;
e->hash = oh;
return 0; return 0;
} }
htab->dead = 0;
} else if (oh == 0xdeadc0de) {
/* re-used tomb */
--htab->dead;
} }
return 1; return 1;
} }
+2
View File
@@ -14,6 +14,8 @@ typedef union htab_value {
struct htab * htab_create(size_t); struct htab * htab_create(size_t);
void htab_destroy(struct htab *); void htab_destroy(struct htab *);
htab_value* htab_find(struct htab *, const char* key); htab_value* htab_find(struct htab *, const char* key);
/* same as htab_find, but can retrieve the saved key (for freeing) */
htab_value* htab_find2(struct htab *htab, const char* key, char **saved_key);
int htab_insert(struct htab *, char*, htab_value); int htab_insert(struct htab *, char*, htab_value);
int htab_delete(struct htab *htab, const char* key); int htab_delete(struct htab *htab, const char* key);
size_t htab_next(struct htab *, size_t iterator, char** key, htab_value **v); size_t htab_next(struct htab *, size_t iterator, char** key, htab_value **v);
+23 -17
View File
@@ -20,9 +20,9 @@
* HTML error pages with variable substitution. * HTML error pages with variable substitution.
*/ */
#include "common.h"
#include "main.h" #include "main.h"
#include "common.h"
#include "buffer.h" #include "buffer.h"
#include "conns.h" #include "conns.h"
#include "heap.h" #include "heap.h"
@@ -31,6 +31,8 @@
#include "utils.h" #include "utils.h"
#include "conf.h" #include "conf.h"
#include <regex.h>
/* /*
* Add an error number -> filename mapping to the errorpages list. * Add an error number -> filename mapping to the errorpages list.
*/ */
@@ -131,7 +133,9 @@ send_html_file (FILE *infile, struct conn_s *connptr)
return 1; return 1;
} }
int send_http_headers (struct conn_s *connptr, int code, const char *message) int send_http_headers (
struct conn_s *connptr, int code,
const char *message, const char *extra)
{ {
const char headers[] = const char headers[] =
"HTTP/1.0 %d %s\r\n" "HTTP/1.0 %d %s\r\n"
@@ -140,21 +144,9 @@ int send_http_headers (struct conn_s *connptr, int code, const char *message)
"%s" "%s"
"Connection: close\r\n" "\r\n"; "Connection: close\r\n" "\r\n";
const char p_auth_str[] =
"Proxy-Authenticate: Basic realm=\""
PACKAGE_NAME "\"\r\n";
const char w_auth_str[] =
"WWW-Authenticate: Basic realm=\""
PACKAGE_NAME "\"\r\n";
/* according to rfc7235, the 407 error must be accompanied by
a Proxy-Authenticate header field. */
const char *add = code == 407 ? p_auth_str : (code == 401 ? w_auth_str : "");
return (write_message (connptr->client_fd, headers, return (write_message (connptr->client_fd, headers,
code, message, PACKAGE, VERSION, code, message, PACKAGE, VERSION,
add)); extra));
} }
/* /*
@@ -178,8 +170,21 @@ int send_http_error_message (struct conn_s *connptr)
"<p><em>Generated by %s version %s.</em></p>\n" "</body>\n" "<p><em>Generated by %s version %s.</em></p>\n" "</body>\n"
"</html>\n"; "</html>\n";
const char p_auth_str[] =
"Proxy-Authenticate: Basic realm=\""
PACKAGE_NAME "\"\r\n";
const char w_auth_str[] =
"WWW-Authenticate: Basic realm=\""
PACKAGE_NAME "\"\r\n";
/* according to rfc7235, the 407 error must be accompanied by
a Proxy-Authenticate header field. */
const char *add = connptr->error_number == 407 ? p_auth_str :
(connptr->error_number == 401 ? w_auth_str : "");
send_http_headers (connptr, connptr->error_number, send_http_headers (connptr, connptr->error_number,
connptr->error_string); connptr->error_string, add);
error_file = get_html_file (connptr->error_number); error_file = get_html_file (connptr->error_number);
if (!(infile = fopen (error_file, "r"))) { if (!(infile = fopen (error_file, "r"))) {
@@ -242,6 +247,7 @@ int add_standard_vars (struct conn_s *connptr)
char errnobuf[16]; char errnobuf[16];
char timebuf[30]; char timebuf[30];
time_t global_time; time_t global_time;
struct tm tm_buf;
snprintf (errnobuf, sizeof errnobuf, "%d", connptr->error_number); snprintf (errnobuf, sizeof errnobuf, "%d", connptr->error_number);
ADD_VAR_RET ("errno", errnobuf); ADD_VAR_RET ("errno", errnobuf);
@@ -257,7 +263,7 @@ int add_standard_vars (struct conn_s *connptr)
global_time = time (NULL); global_time = time (NULL);
strftime (timebuf, sizeof (timebuf), "%a, %d %b %Y %H:%M:%S GMT", strftime (timebuf, sizeof (timebuf), "%a, %d %b %Y %H:%M:%S GMT",
gmtime (&global_time)); gmtime_r (&global_time, &tm_buf));
add_error_variable (connptr, "date", timebuf); add_error_variable (connptr, "date", timebuf);
add_error_variable (connptr, "website", add_error_variable (connptr, "website",
+1 -1
View File
@@ -33,7 +33,7 @@ extern int add_error_variable (struct conn_s *connptr, const char *key,
const char *val); const char *val);
extern int send_html_file (FILE * infile, struct conn_s *connptr); extern int send_html_file (FILE * infile, struct conn_s *connptr);
extern int send_http_headers (struct conn_s *connptr, int code, extern int send_http_headers (struct conn_s *connptr, int code,
const char *message); const char *message, const char *extra);
extern int add_standard_vars (struct conn_s *connptr); extern int add_standard_vars (struct conn_s *connptr);
#endif /* !TINYPROXY_HTML_ERROR_H */ #endif /* !TINYPROXY_HTML_ERROR_H */
+3 -2
View File
@@ -232,6 +232,7 @@ int http_message_send (http_message_t msg, int fd)
char timebuf[30]; char timebuf[30];
time_t global_time; time_t global_time;
unsigned int i; unsigned int i;
struct tm tm_buf;
assert (is_http_message_valid (msg)); assert (is_http_message_valid (msg));
@@ -254,11 +255,11 @@ int http_message_send (http_message_t msg, int fd)
/* Output the date */ /* Output the date */
global_time = time (NULL); global_time = time (NULL);
strftime (timebuf, sizeof (timebuf), "%a, %d %b %Y %H:%M:%S GMT", strftime (timebuf, sizeof (timebuf), "%a, %d %b %Y %H:%M:%S GMT",
gmtime (&global_time)); gmtime_r (&global_time, &tm_buf));
write_message (fd, "Date: %s\r\n", timebuf); write_message (fd, "Date: %s\r\n", timebuf);
/* Output the content-length */ /* Output the content-length */
write_message (fd, "Content-length: %u\r\n", msg->body.length); write_message (fd, "Content-length: %lu\r\n", (unsigned long) msg->body.length);
/* Write the separator between the headers and body */ /* Write the separator between the headers and body */
safe_write (fd, "\r\n", 2); safe_write (fd, "\r\n", 2);
+6 -4
View File
@@ -108,7 +108,8 @@ void set_log_level (int level)
void log_message (int level, const char *fmt, ...) void log_message (int level, const char *fmt, ...)
{ {
va_list args; va_list args;
time_t nowtime; struct timespec nowtime;
struct tm tm_buf;
char time_string[TIME_LENGTH]; char time_string[TIME_LENGTH];
char str[STRING_LENGTH]; char str[STRING_LENGTH];
@@ -174,13 +175,14 @@ void log_message (int level, const char *fmt, ...)
} else { } else {
char *p; char *p;
nowtime = time (NULL); clock_gettime(CLOCK_REALTIME, &nowtime);
/* Format is month day hour:minute:second (24 time) */ /* Format is month day hour:minute:second (24 time) */
strftime (time_string, TIME_LENGTH, "%b %d %H:%M:%S", strftime (time_string, TIME_LENGTH, "%b %d %H:%M:%S",
localtime (&nowtime)); localtime_r (&nowtime.tv_sec, &tm_buf));
snprintf (str, STRING_LENGTH, "%-9s %s [%ld]: ", snprintf (str, STRING_LENGTH, "%-9s %s.%03lu [%ld]: ",
syslog_level[level], time_string, syslog_level[level], time_string,
(unsigned long) nowtime.tv_nsec/1000000ul,
(long int) getpid ()); (long int) getpid ());
/* /*
+1 -1
View File
@@ -381,7 +381,7 @@ main (int argc, char **argv)
if (geteuid () == 0) if (geteuid () == 0)
change_user (argv[0]); change_user (argv[0]);
else else
log_message (LOG_WARNING, log_message (LOG_INFO,
"Not running as root, so not changing UID/GID."); "Not running as root, so not changing UID/GID.");
/* Create log file after we drop privileges */ /* Create log file after we drop privileges */
+7 -2
View File
@@ -81,14 +81,19 @@ char* orderedmap_find(struct orderedmap *o, const char *key) {
int orderedmap_remove(struct orderedmap *o, const char *key) { int orderedmap_remove(struct orderedmap *o, const char *key) {
size_t i; size_t i;
char *lk; char *lk;
htab_value *lv, *v = htab_find(o->map, key); char *sk;
char **sv;
htab_value *lv, *v = htab_find2(o->map, key, &sk);
if(!v) return 0; if(!v) return 0;
htab_delete(o->map, key); sv = sblist_get(o->values, v->n);
free(*sv);
sblist_delete(o->values, v->n); sblist_delete(o->values, v->n);
i = 0; i = 0;
while((i = htab_next(o->map, i, &lk, &lv))) { while((i = htab_next(o->map, i, &lk, &lv))) {
if(lv->n > v->n) lv->n--; if(lv->n > v->n) lv->n--;
} }
htab_delete(o->map, key);
free(sk);
return 1; return 1;
} }
+2 -2
View File
@@ -1454,8 +1454,8 @@ get_request_entity(struct conn_s *connptr)
ret = -1; ret = -1;
} else { } else {
log_message (LOG_INFO, log_message (LOG_INFO,
"Read request entity of %d bytes", "Read request entity of %ld bytes",
nread); (long) nread);
ret = 0; ret = 0;
} }
} else { } else {
+12 -2
View File
@@ -34,6 +34,7 @@ void reversepath_add (const char *path, const char *url,
struct reversepath **reversepath_list) struct reversepath **reversepath_list)
{ {
struct reversepath *reverse; struct reversepath *reverse;
size_t l;
if (url == NULL) { if (url == NULL) {
log_message (LOG_WARNING, log_message (LOG_WARNING,
@@ -65,8 +66,17 @@ void reversepath_add (const char *path, const char *url,
if (!path) if (!path)
reverse->path = safestrdup ("/"); reverse->path = safestrdup ("/");
else else {
reverse->path = safestrdup (path); l = strlen (path);
if (l && path[l-1] == '/')
reverse->path = safestrdup (path);
else {
reverse->path = safemalloc (l + 2);
memcpy (reverse->path, path, l);
reverse->path[l] = '/';
reverse->path[l+1] = 0;
}
}
reverse->url = safestrdup (url); reverse->url = safestrdup (url);
+25 -4
View File
@@ -34,6 +34,7 @@
#include "text.h" #include "text.h"
#include "conf.h" #include "conf.h"
#include "loop.h" #include "loop.h"
#include "sblist.h"
/* /*
* Return a human readable error for getaddrinfo() and getnameinfo(). * Return a human readable error for getaddrinfo() and getnameinfo().
@@ -68,7 +69,7 @@ bind_socket (int sockfd, const char *addr, int family)
n = getaddrinfo (addr, NULL, &hints, &res); n = getaddrinfo (addr, NULL, &hints, &res);
if (n != 0) { if (n != 0) {
log_message (LOG_INFO, log_message (LOG_INFO,
"bind_socket: getaddrinfo failed for %s: ", addr, get_gai_error (n)); "bind_socket: getaddrinfo failed for %s: %s", addr, get_gai_error (n));
return -1; return -1;
} }
@@ -87,6 +88,26 @@ bind_socket (int sockfd, const char *addr, int family)
return sockfd; return sockfd;
} }
/**
* Try binding the given socket to supplied addresses, stopping when one succeeds.
*/
static int
bind_socket_list (int sockfd, sblist *addresses, int family)
{
size_t nb_addresses = sblist_getsize(addresses);
size_t i;
for (i = 0; i < nb_addresses; i++) {
const char *address = *(const char **)sblist_get(addresses, i);
if (bind_socket(sockfd, address, family) >= 0) {
log_message(LOG_INFO, "Bound to %s", address);
return 0;
}
}
return -1;
}
/* /*
* Open a connection to a remote host. It's been re-written to use * Open a connection to a remote host. It's been re-written to use
* the getaddrinfo() library function, which allows for a protocol * the getaddrinfo() library function, which allows for a protocol
@@ -134,9 +155,9 @@ int opensock (const char *host, int port, const char *bind_to)
close (sockfd); close (sockfd);
continue; /* can't bind, so try again */ continue; /* can't bind, so try again */
} }
} else if (config->bind_address) { } else if (config->bind_addrs) {
if (bind_socket (sockfd, config->bind_address, if (bind_socket_list (sockfd, config->bind_addrs,
res->ai_family) < 0) { res->ai_family) < 0) {
close (sockfd); close (sockfd);
continue; /* can't bind, so try again */ continue; /* can't bind, so try again */
} }
+1 -1
View File
@@ -122,7 +122,7 @@ err_minus_one:
add_error_variable (connptr, "deniedconns", denied); add_error_variable (connptr, "deniedconns", denied);
add_error_variable (connptr, "refusedconns", refused); add_error_variable (connptr, "refusedconns", refused);
add_standard_vars (connptr); add_standard_vars (connptr);
send_http_headers (connptr, 200, "Statistic requested"); send_http_headers (connptr, 200, "Statistic requested", "");
send_html_file (statfile, connptr); send_html_file (statfile, connptr);
fclose (statfile); fclose (statfile);
pthread_mutex_unlock(&stats_file_lock); pthread_mutex_unlock(&stats_file_lock);
+30 -19
View File
@@ -43,20 +43,34 @@ proxy_type_name(proxy_type type)
} }
} }
const char* upstream_build_error_string(enum upstream_build_error ube) {
static const char *emap[] = {
[UBE_SUCCESS] = "",
[UBE_OOM] = "Unable to allocate memory in upstream_build()",
[UBE_USERLEN] = "User / pass in upstream config too long",
[UBE_EDOMAIN] = "Nonsense upstream none rule: empty domain",
[UBE_INVHOST] = "Nonsense upstream rule: invalid host or port",
[UBE_INVPARAMS] = "Nonsense upstream rule: invalid parameters",
[UBE_NETMASK] = "Nonsense upstream rule: failed to parse netmask",
};
return emap[ube];
}
/** /**
* Construct an upstream struct from input data. * Construct an upstream struct from input data.
*/ */
static struct upstream *upstream_build (const char *host, int port, const char *domain, static struct upstream *upstream_build (const char *host, int port, const char *domain,
const char *user, const char *pass, const char *user, const char *pass,
proxy_type type) proxy_type type, enum upstream_build_error *ube)
{ {
char *ptr; char *ptr;
struct upstream *up; struct upstream *up;
*ube = UBE_SUCCESS;
up = (struct upstream *) safemalloc (sizeof (struct upstream)); up = (struct upstream *) safemalloc (sizeof (struct upstream));
if (!up) { if (!up) {
log_message (LOG_ERR, *ube = UBE_OOM;
"Unable to allocate memory in upstream_build()");
return NULL; return NULL;
} }
@@ -69,8 +83,7 @@ static struct upstream *upstream_build (const char *host, int port, const char *
ssize_t ret; ssize_t ret;
ret = basicauth_string(user, pass, b, sizeof b); ret = basicauth_string(user, pass, b, sizeof b);
if (ret == 0) { if (ret == 0) {
log_message (LOG_ERR, *ube = UBE_USERLEN;
"User / pass in upstream config too long");
return NULL; return NULL;
} }
up->ua.authstr = safestrdup (b); up->ua.authstr = safestrdup (b);
@@ -83,13 +96,11 @@ static struct upstream *upstream_build (const char *host, int port, const char *
if (domain == NULL) { if (domain == NULL) {
if (type == PT_NONE) { if (type == PT_NONE) {
e_nonedomain:; e_nonedomain:;
log_message (LOG_WARNING, *ube = UBE_EDOMAIN;
"Nonsense upstream none rule: empty domain");
goto fail; goto fail;
} }
if (!host || !host[0] || port < 1) { if (!host || !host[0] || port < 1) {
log_message (LOG_WARNING, *ube = UBE_INVHOST;
"Nonsense upstream rule: invalid host or port");
goto fail; goto fail;
} }
@@ -103,8 +114,7 @@ static struct upstream *upstream_build (const char *host, int port, const char *
if (!domain[0]) goto e_nonedomain; if (!domain[0]) goto e_nonedomain;
} else { } else {
if (!host || !host[0] || !domain[0]) { if (!host || !host[0] || !domain[0]) {
log_message (LOG_WARNING, *ube = UBE_INVPARAMS;
"Nonsense upstream rule: invalid parameters");
goto fail; goto fail;
} }
up->host = safestrdup (host); up->host = safestrdup (host);
@@ -130,8 +140,7 @@ static struct upstream *upstream_build (const char *host, int port, const char *
} }
up->ip = up->ip & up->mask; up->ip = up->ip & up->mask;
} else { } else {
log_message (LOG_WARNING, *ube = UBE_NETMASK;
"Nonsense upstream rule: failed to parse netmask");
goto fail; goto fail;
} }
} else { } else {
@@ -160,15 +169,17 @@ fail:
/* /*
* Add an entry to the upstream list * Add an entry to the upstream list
*/ */
void upstream_add (const char *host, int port, const char *domain, enum upstream_build_error upstream_add (
const char *host, int port, const char *domain,
const char *user, const char *pass, const char *user, const char *pass,
proxy_type type, struct upstream **upstream_list) proxy_type type, struct upstream **upstream_list)
{ {
struct upstream *up; struct upstream *up;
enum upstream_build_error ube;
up = upstream_build (host, port, domain, user, pass, type); up = upstream_build (host, port, domain, user, pass, type, &ube);
if (up == NULL) { if (up == NULL) {
return; return ube;
} }
if (!up->domain && !up->ip) { /* always add default to end */ if (!up->domain && !up->ip) { /* always add default to end */
@@ -184,7 +195,7 @@ void upstream_add (const char *host, int port, const char *domain,
if (!tmp->next) { if (!tmp->next) {
up->next = NULL; up->next = NULL;
tmp->next = up; tmp->next = up;
return; return ube;
} }
tmp = tmp->next; tmp = tmp->next;
@@ -194,14 +205,14 @@ void upstream_add (const char *host, int port, const char *domain,
up->next = *upstream_list; up->next = *upstream_list;
*upstream_list = up; *upstream_list = up;
return; return ube;
upstream_cleanup: upstream_cleanup:
safefree (up->host); safefree (up->host);
safefree (up->domain); safefree (up->domain);
safefree (up); safefree (up);
return; return ube;
} }
/* /*
+13 -1
View File
@@ -27,6 +27,16 @@
#include "common.h" #include "common.h"
enum upstream_build_error {
UBE_SUCCESS = 0,
UBE_OOM,
UBE_USERLEN,
UBE_EDOMAIN,
UBE_INVHOST,
UBE_INVPARAMS,
UBE_NETMASK,
};
/* /*
* Even if upstream support is not compiled into tinyproxy, this * Even if upstream support is not compiled into tinyproxy, this
* structure still needs to be defined. * structure still needs to be defined.
@@ -54,11 +64,13 @@ struct upstream {
#ifdef UPSTREAM_SUPPORT #ifdef UPSTREAM_SUPPORT
const char *proxy_type_name(proxy_type type); const char *proxy_type_name(proxy_type type);
extern void upstream_add (const char *host, int port, const char *domain, extern enum upstream_build_error upstream_add (
const char *host, int port, const char *domain,
const char *user, const char *pass, const char *user, const char *pass,
proxy_type type, struct upstream **upstream_list); proxy_type type, struct upstream **upstream_list);
extern struct upstream *upstream_get (char *host, struct upstream *up); extern struct upstream *upstream_get (char *host, struct upstream *up);
extern void free_upstream_list (struct upstream *up); extern void free_upstream_list (struct upstream *up);
extern const char* upstream_build_error_string(enum upstream_build_error);
#endif /* UPSTREAM_SUPPORT */ #endif /* UPSTREAM_SUPPORT */
#endif /* _TINYPROXY_UPSTREAM_H_ */ #endif /* _TINYPROXY_UPSTREAM_H_ */