Compare commits

...
15 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
16 changed files with 141 additions and 54 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.])
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)
else
AM_CONDITIONAL(HAVE_GPERF, false)
AS_ECHO("no")
fi
fi
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
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>
+20 -5
View File
@@ -291,6 +291,7 @@ void free_config (struct config_s *conf)
safefree (conf->group);
stringlist_free(conf->basicauth_list);
stringlist_free(conf->listen_addrs);
stringlist_free(conf->bind_addrs);
#ifdef FILTER_ENABLE
safefree (conf->filter);
#endif /* FILTER_ENABLE */
@@ -302,7 +303,6 @@ void free_config (struct config_s *conf)
free_upstream_list (conf->upstream_list);
#endif /* UPSTREAM_SUPPORT */
safefree (conf->pidpath);
safefree (conf->bind_address);
safefree (conf->via_proxy_name);
if (conf->errorpages) {
it = 0;
@@ -796,12 +796,27 @@ static HANDLE_FUNC (handle_deny)
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,
"Outgoing connections bound to IP %s", conf->bind_address);
"Added bind address [%s] for outgoing connections.", arg);
return 0;
}
+1 -1
View File
@@ -68,7 +68,7 @@ struct config_s {
#endif /* UPSTREAM_SUPPORT */
char *pidpath;
unsigned int idletimeout;
char *bind_address;
sblist *bind_addrs;
unsigned int bindsame;
/*
+32 -14
View File
@@ -49,6 +49,7 @@ struct htab {
size_t mask;
size_t used;
size_t seed;
size_t dead;
};
#define MINSIZE 8
@@ -107,14 +108,14 @@ static int resize(struct htab *htab, size_t nel)
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;
struct elem *e;
for (i=hash,j=1; ; i+=j++) {
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))
break;
}
@@ -138,50 +139,67 @@ void htab_destroy(struct htab *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);
struct elem *e = lookup(htab, key, hash);
struct elem *e = lookup(htab, key, hash, 0);
if (e->item.key) {
return &e->item;
return e;
}
return 0;
}
htab_value* htab_find(struct htab *htab, const char* key)
{
htab_entry *i = htab_find_item(htab, key);
if(i) return &i->data;
return 0;
struct elem *e = htab_find_elem(htab, key);
if(!e) 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)
{
htab_entry *i = htab_find_item(htab, key);
if(!i) return 0;
i->key = 0;
struct elem *e = htab_find_elem(htab, key);
if(!e) return 0;
e->item.key = 0;
e->hash = 0xdeadc0de;
--htab->used;
++htab->dead;
return 1;
}
int htab_insert(struct htab *htab, char* key, htab_value value)
{
size_t hash = keyhash(key, htab->seed);
struct elem *e = lookup(htab, key, hash);
size_t hash = keyhash(key, htab->seed), oh;
struct elem *e = lookup(htab, key, hash, 0xdeadc0de);
if(e->item.key) {
/* it's not allowed to overwrite existing data */
return 0;
}
oh = e->hash; /* save old hash in case it's tombstone marker */
e->item.key = key;
e->item.data = value;
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)) {
htab->used--;
e->item.key = 0;
e->hash = oh;
return 0;
}
htab->dead = 0;
} else if (oh == 0xdeadc0de) {
/* re-used tomb */
--htab->dead;
}
return 1;
}
+2
View File
@@ -14,6 +14,8 @@ typedef union htab_value {
struct htab * htab_create(size_t);
void htab_destroy(struct htab *);
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_delete(struct htab *htab, const char* key);
size_t htab_next(struct htab *, size_t iterator, char** key, htab_value **v);
+23 -18
View File
@@ -20,10 +20,9 @@
* HTML error pages with variable substitution.
*/
#include <regex.h>
#include "common.h"
#include "main.h"
#include "common.h"
#include "buffer.h"
#include "conns.h"
#include "heap.h"
@@ -32,6 +31,8 @@
#include "utils.h"
#include "conf.h"
#include <regex.h>
/*
* Add an error number -> filename mapping to the errorpages list.
*/
@@ -132,7 +133,9 @@ send_html_file (FILE *infile, struct conn_s *connptr)
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[] =
"HTTP/1.0 %d %s\r\n"
@@ -141,21 +144,9 @@ int send_http_headers (struct conn_s *connptr, int code, const char *message)
"%s"
"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,
code, message, PACKAGE, VERSION,
add));
extra));
}
/*
@@ -179,8 +170,21 @@ int send_http_error_message (struct conn_s *connptr)
"<p><em>Generated by %s version %s.</em></p>\n" "</body>\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,
connptr->error_string);
connptr->error_string, add);
error_file = get_html_file (connptr->error_number);
if (!(infile = fopen (error_file, "r"))) {
@@ -243,6 +247,7 @@ int add_standard_vars (struct conn_s *connptr)
char errnobuf[16];
char timebuf[30];
time_t global_time;
struct tm tm_buf;
snprintf (errnobuf, sizeof errnobuf, "%d", connptr->error_number);
ADD_VAR_RET ("errno", errnobuf);
@@ -258,7 +263,7 @@ int add_standard_vars (struct conn_s *connptr)
global_time = time (NULL);
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, "website",
+1 -1
View File
@@ -33,7 +33,7 @@ extern int add_error_variable (struct conn_s *connptr, const char *key,
const char *val);
extern int send_html_file (FILE * infile, struct conn_s *connptr);
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);
#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];
time_t global_time;
unsigned int i;
struct tm tm_buf;
assert (is_http_message_valid (msg));
@@ -254,11 +255,11 @@ int http_message_send (http_message_t msg, int fd)
/* Output the date */
global_time = time (NULL);
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);
/* 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 */
safe_write (fd, "\r\n", 2);
+4 -3
View File
@@ -109,6 +109,7 @@ void log_message (int level, const char *fmt, ...)
{
va_list args;
struct timespec nowtime;
struct tm tm_buf;
char time_string[TIME_LENGTH];
char str[STRING_LENGTH];
@@ -177,11 +178,11 @@ void log_message (int level, const char *fmt, ...)
clock_gettime(CLOCK_REALTIME, &nowtime);
/* Format is month day hour:minute:second (24 time) */
strftime (time_string, TIME_LENGTH, "%b %d %H:%M:%S",
localtime (&nowtime.tv_sec));
localtime_r (&nowtime.tv_sec, &tm_buf));
snprintf (str, STRING_LENGTH, "%-9s %s.%03u [%ld]: ",
snprintf (str, STRING_LENGTH, "%-9s %s.%03lu [%ld]: ",
syslog_level[level], time_string,
nowtime.tv_nsec/1000000u,
(unsigned long) nowtime.tv_nsec/1000000ul,
(long int) getpid ());
/*
+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) {
size_t i;
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;
htab_delete(o->map, key);
sv = sblist_get(o->values, v->n);
free(*sv);
sblist_delete(o->values, v->n);
i = 0;
while((i = htab_next(o->map, i, &lk, &lv))) {
if(lv->n > v->n) lv->n--;
}
htab_delete(o->map, key);
free(sk);
return 1;
}
+2 -2
View File
@@ -1454,8 +1454,8 @@ get_request_entity(struct conn_s *connptr)
ret = -1;
} else {
log_message (LOG_INFO,
"Read request entity of %d bytes",
nread);
"Read request entity of %ld bytes",
(long) nread);
ret = 0;
}
} else {
+11 -1
View File
@@ -34,6 +34,7 @@ void reversepath_add (const char *path, const char *url,
struct reversepath **reversepath_list)
{
struct reversepath *reverse;
size_t l;
if (url == NULL) {
log_message (LOG_WARNING,
@@ -65,8 +66,17 @@ void reversepath_add (const char *path, const char *url,
if (!path)
reverse->path = safestrdup ("/");
else
else {
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);
+24 -3
View File
@@ -34,6 +34,7 @@
#include "text.h"
#include "conf.h"
#include "loop.h"
#include "sblist.h"
/*
* 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);
if (n != 0) {
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;
}
@@ -87,6 +88,26 @@ bind_socket (int sockfd, const char *addr, int family)
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
* the getaddrinfo() library function, which allows for a protocol
@@ -134,8 +155,8 @@ int opensock (const char *host, int port, const char *bind_to)
close (sockfd);
continue; /* can't bind, so try again */
}
} else if (config->bind_address) {
if (bind_socket (sockfd, config->bind_address,
} else if (config->bind_addrs) {
if (bind_socket_list (sockfd, config->bind_addrs,
res->ai_family) < 0) {
close (sockfd);
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, "refusedconns", refused);
add_standard_vars (connptr);
send_http_headers (connptr, 200, "Statistic requested");
send_http_headers (connptr, 200, "Statistic requested", "");
send_html_file (statfile, connptr);
fclose (statfile);
pthread_mutex_unlock(&stats_file_lock);