diff options
| -rw-r--r-- | Makefile | 27 | ||||
| -rw-r--r-- | opentracker.c | 17 | ||||
| -rw-r--r-- | ot_accesslist.c | 16 | ||||
| -rw-r--r-- | ot_http.c | 40 | ||||
| -rw-r--r-- | ot_http.h | 3 | ||||
| -rw-r--r-- | ot_mutex.h | 1 | ||||
| -rw-r--r-- | ot_udp.c | 17 | ||||
| -rw-r--r-- | tests/integration/harness.py | 174 | ||||
| -rw-r--r-- | tests/integration/test_accesslist.py | 100 | ||||
| -rw-r--r-- | tests/integration/test_fullscrape.py | 146 | ||||
| -rw-r--r-- | tests/integration/test_keepalive.py | 111 | ||||
| -rw-r--r-- | tests/integration/test_stats.py | 169 | ||||
| -rw-r--r-- | tests/integration/test_udp.py | 168 | ||||
| -rw-r--r-- | tests/runner.c | 72 |
14 files changed, 1014 insertions, 47 deletions
| @@ -134,12 +134,25 @@ $(TESTBIN): $(TEST_SOURCES) $(TEST_UNITS) $(TEST_HEADERS) | |||
| 134 | check: $(TESTBIN) $(BINARY) | 134 | check: $(TESTBIN) $(BINARY) |
| 135 | ./$(TESTBIN) | 135 | ./$(TESTBIN) |
| 136 | 136 | ||
| 137 | # The same unit tests under the sanitizers. Use clang over $(CC) because the | ||
| 138 | # two toolchains do not check the same things | ||
| 139 | # Override CC_sanitize to use another compiler. | ||
| 140 | CC_sanitize?=clang | ||
| 141 | CFLAGS_sanitize=$(CFLAGS_test) -fsanitize=address,undefined -fno-omit-frame-pointer | ||
| 142 | LDFLAGS_sanitize=$(LDFLAGS) -fsanitize=address,undefined | ||
| 143 | |||
| 144 | $(TESTBIN).sanitize: $(TEST_SOURCES) $(TEST_UNITS) $(TEST_HEADERS) | ||
| 145 | $(CC_sanitize) -o $@ $(CFLAGS_sanitize) $(TEST_SOURCES) $(TEST_UNITS) $(LDFLAGS_sanitize) | ||
| 146 | |||
| 147 | check-sanitize: $(TESTBIN).sanitize | ||
| 148 | ./$(TESTBIN).sanitize | ||
| 149 | |||
| 137 | # Black box tests: these drive the real binary over the wire, so they cover | 150 | # Black box tests: these drive the real binary over the wire, so they cover |
| 138 | # the event loop and the parsers working together, which the unit tests | 151 | # the event loop and the parsers working together, which the unit tests |
| 139 | # cannot reach. Built with the sanitizers on, so the tracker reports its own | 152 | # cannot reach. Built with the sanitizers on, so the tracker reports its own |
| 140 | # memory errors and the harness turns those into failures. | 153 | # memory errors and the harness turns those into failures. |
| 141 | PYTHON?=python3 | 154 | PYTHON?=python3 |
| 142 | FEATURES_integration=$(FEATURES) -DWANT_IP_FROM_QUERY_STRING | 155 | FEATURES_integration=$(FEATURES) -DWANT_IP_FROM_QUERY_STRING -DWANT_ACCESSLIST_BLACK -DWANT_KEEPALIVE |
| 143 | CFLAGS_integration=$(CFLAGS) $(OPTS_debug) $(FEATURES_integration) -fsanitize=address,undefined -fno-omit-frame-pointer | 156 | CFLAGS_integration=$(CFLAGS) $(OPTS_debug) $(FEATURES_integration) -fsanitize=address,undefined -fno-omit-frame-pointer |
| 144 | LDFLAGS_integration=$(LDFLAGS) -fsanitize=address,undefined | 157 | LDFLAGS_integration=$(LDFLAGS) -fsanitize=address,undefined |
| 145 | 158 | ||
| @@ -149,10 +162,18 @@ opentracker.integration: $(SOURCES) $(HEADERS) | |||
| 149 | check-integration: opentracker.integration | 162 | check-integration: opentracker.integration |
| 150 | OPENTRACKER=./opentracker.integration $(PYTHON) -m unittest discover -s tests/integration | 163 | OPENTRACKER=./opentracker.integration $(PYTHON) -m unittest discover -s tests/integration |
| 151 | 164 | ||
| 152 | .PHONY: all check check-integration clean install | 165 | # Everything, cheapest first, so a quick failure comes back quickly. |
| 166 | check-all: | ||
| 167 | $(MAKE) check | ||
| 168 | $(MAKE) check-sanitize | ||
| 169 | $(MAKE) check-integration | ||
| 170 | |||
| 171 | .PHONY: all check check-sanitize check-integration check-all clean install | ||
| 172 | |||
| 173 | BINARIES=opentracker opentracker.debug opentracker.integration proxy proxy.debug $(TESTBIN) $(TESTBIN).sanitize | ||
| 153 | 174 | ||
| 154 | clean: | 175 | clean: |
| 155 | rm -rf opentracker opentracker.debug opentracker.integration proxy proxy.debug $(TESTBIN) *.o *~ | 176 | rm -rf $(BINARIES) $(BINARIES:=.dSYM) *.o *~ |
| 156 | 177 | ||
| 157 | install: | 178 | install: |
| 158 | install -m 755 opentracker $(DESTDIR)$(BINDIR) | 179 | install -m 755 opentracker $(DESTDIR)$(BINDIR) |
diff --git a/opentracker.c b/opentracker.c index 21eeb42..11da486 100644 --- a/opentracker.c +++ b/opentracker.c | |||
| @@ -177,12 +177,13 @@ static void handle_read(const int64_t sock, struct ot_workstruct *ws) { | |||
| 177 | } | 177 | } |
| 178 | 178 | ||
| 179 | static void handle_write(const int64_t sock) { | 179 | static void handle_write(const int64_t sock) { |
| 180 | struct http_data *cookie = fdstate_cookie(sock); | 180 | struct http_data *cookie = fdstate_cookie(sock); |
| 181 | int chunked = 0; | 181 | int chunked = 0; |
| 182 | int keep_alive = 0; | ||
| 182 | 183 | ||
| 183 | if (cookie) { | 184 | if (cookie) { |
| 184 | if (cookie->flag & STRUCT_HTTP_FLAG_CHUNKED_IN_TRANSFER) | 185 | chunked = (cookie->flag & STRUCT_HTTP_FLAG_CHUNKED_IN_TRANSFER) != 0; |
| 185 | chunked = 1; | 186 | keep_alive = (cookie->flag & STRUCT_HTTP_FLAG_KEEPALIVE) != 0; |
| 186 | 187 | ||
| 187 | if (cookie->batch) { | 188 | if (cookie->batch) { |
| 188 | if (batch_send(sock, cookie->batch) == BATCH_FAILED) { | 189 | if (batch_send(sock, cookie->batch) == BATCH_FAILED) { |
| @@ -197,7 +198,13 @@ static void handle_write(const int64_t sock) { | |||
| 197 | /* In a chunked transfer, wait for the next piece once everything queued has gone out */ | 198 | /* In a chunked transfer, wait for the next piece once everything queued has gone out */ |
| 198 | if (chunked) | 199 | if (chunked) |
| 199 | http_interest_drop(sock, cookie, EVENT_OUT); | 200 | http_interest_drop(sock, cookie, EVENT_OUT); |
| 200 | else | 201 | else if (keep_alive) { |
| 202 | /* The reply is out and the client asked to keep the connection, so stop | ||
| 203 | waiting to write and go back to waiting for the next request */ | ||
| 204 | http_interest_drop(sock, cookie, EVENT_OUT); | ||
| 205 | http_interest_add(sock, cookie, EVENT_IN); | ||
| 206 | fdstate_set_expiry(sock, g_now_seconds + OT_CLIENT_TIMEOUT); | ||
| 207 | } else | ||
| 201 | handle_dead(sock); | 208 | handle_dead(sock); |
| 202 | } | 209 | } |
| 203 | 210 | ||
diff --git a/ot_accesslist.c b/ot_accesslist.c index 724978e..4bf1701 100644 --- a/ot_accesslist.c +++ b/ot_accesslist.c | |||
| @@ -160,6 +160,9 @@ static void accesslist_readfile(void) { | |||
| 160 | const char *map; | 160 | const char *map; |
| 161 | size_t maplen, capacity, found; | 161 | size_t maplen, capacity, found; |
| 162 | 162 | ||
| 163 | if (!g_accesslist_filename) | ||
| 164 | return; | ||
| 165 | |||
| 163 | if (accesslist_map(g_accesslist_filename, &map, &maplen) < 0) { | 166 | if (accesslist_map(g_accesslist_filename, &map, &maplen) < 0) { |
| 164 | char *wd = getcwd(NULL, 0); | 167 | char *wd = getcwd(NULL, 0); |
| 165 | fprintf(stderr, "Warning: Can't open accesslist file: %s (but will try to create it later, if necessary and possible).\nPWD: %s\n", g_accesslist_filename, wd); | 168 | fprintf(stderr, "Warning: Can't open accesslist file: %s (but will try to create it later, if necessary and possible).\nPWD: %s\n", g_accesslist_filename, wd); |
| @@ -185,7 +188,8 @@ static void accesslist_readfile(void) { | |||
| 185 | if (map) | 188 | if (map) |
| 186 | munmap((void *)map, maplen); | 189 | munmap((void *)map, maplen); |
| 187 | 190 | ||
| 188 | qsort(accesslist_new->list, found, sizeof(ot_hash), vector_compare_hash); | 191 | if (found) |
| 192 | qsort(accesslist_new->list, found, sizeof(ot_hash), vector_compare_hash); | ||
| 189 | accesslist_new->size = found; | 193 | accesslist_new->size = found; |
| 190 | 194 | ||
| 191 | /* Now exchange the accesslist vector in the least race condition prone way */ | 195 | /* Now exchange the accesslist vector in the least race condition prone way */ |
| @@ -223,18 +227,18 @@ int accesslist_hashisvalid(const ot_hash hash) { | |||
| 223 | #endif | 227 | #endif |
| 224 | void *exactmatch = NULL; | 228 | void *exactmatch = NULL; |
| 225 | 229 | ||
| 226 | if (accesslist) | 230 | if (accesslist && accesslist->size) |
| 227 | exactmatch = bsearch(hash, accesslist->list, accesslist->size, OT_HASH_COMPARE_SIZE, vector_compare_hash); | 231 | exactmatch = bsearch(hash, accesslist->list, accesslist->size, OT_HASH_COMPARE_SIZE, vector_compare_hash); |
| 228 | 232 | ||
| 229 | #ifdef WANT_DYNAMIC_ACCESSLIST | 233 | #ifdef WANT_DYNAMIC_ACCESSLIST |
| 230 | /* If we had no match on the main list, scan the list of dynamically added hashes */ | 234 | /* If we had no match on the main list, scan the list of dynamically added hashes */ |
| 231 | accesslist_add = g_accesslist_add; | 235 | accesslist_add = g_accesslist_add; |
| 232 | if ((exactmatch == NULL) && accesslist_add) | 236 | if ((exactmatch == NULL) && accesslist_add && accesslist_add->size) |
| 233 | exactmatch = bsearch(hash, accesslist_add->list, accesslist_add->size, OT_HASH_COMPARE_SIZE, vector_compare_hash); | 237 | exactmatch = bsearch(hash, accesslist_add->list, accesslist_add->size, OT_HASH_COMPARE_SIZE, vector_compare_hash); |
| 234 | 238 | ||
| 235 | /* If we found a matching hash on the main list, scan the list of dynamically deleted hashes */ | 239 | /* If we found a matching hash on the main list, scan the list of dynamically deleted hashes */ |
| 236 | accesslist_delete = g_accesslist_delete; | 240 | accesslist_delete = g_accesslist_delete; |
| 237 | if ((exactmatch != NULL) && accesslist_delete && bsearch(hash, accesslist_delete->list, accesslist_delete->size, OT_HASH_COMPARE_SIZE, vector_compare_hash)) | 241 | if ((exactmatch != NULL) && accesslist_delete && accesslist_delete->size && bsearch(hash, accesslist_delete->list, accesslist_delete->size, OT_HASH_COMPARE_SIZE, vector_compare_hash)) |
| 238 | exactmatch = NULL; | 242 | exactmatch = NULL; |
| 239 | #endif | 243 | #endif |
| 240 | 244 | ||
| @@ -384,8 +388,9 @@ void accesslist_init(void) { | |||
| 384 | } | 388 | } |
| 385 | 389 | ||
| 386 | void accesslist_deinit(void) { | 390 | void accesslist_deinit(void) { |
| 387 | /* Wake up sleeping worker */ | 391 | /* Wake the worker and wait for it to notice that the tracker is stopping. */ |
| 388 | pthread_kill(thread_id, SIGHUP); | 392 | pthread_kill(thread_id, SIGHUP); |
| 393 | pthread_join(thread_id, NULL); | ||
| 389 | 394 | ||
| 390 | pthread_mutex_lock(&g_accesslist_mutex); | 395 | pthread_mutex_lock(&g_accesslist_mutex); |
| 391 | 396 | ||
| @@ -397,7 +402,6 @@ void accesslist_deinit(void) { | |||
| 397 | #endif | 402 | #endif |
| 398 | 403 | ||
| 399 | pthread_mutex_unlock(&g_accesslist_mutex); | 404 | pthread_mutex_unlock(&g_accesslist_mutex); |
| 400 | pthread_cancel(thread_id); | ||
| 401 | pthread_mutex_destroy(&g_accesslist_mutex); | 405 | pthread_mutex_destroy(&g_accesslist_mutex); |
| 402 | } | 406 | } |
| 403 | 407 | ||
| @@ -24,6 +24,7 @@ | |||
| 24 | #include "ot_scan.h" | 24 | #include "ot_scan.h" |
| 25 | #include "ot_event.h" | 25 | #include "ot_event.h" |
| 26 | #include "ot_fdstate.h" | 26 | #include "ot_fdstate.h" |
| 27 | #include "ot_vector.h" | ||
| 27 | #include "ot_fmt.h" | 28 | #include "ot_fmt.h" |
| 28 | #include "ot_stats.h" | 29 | #include "ot_stats.h" |
| 29 | #include "ot_urlencoded.h" | 30 | #include "ot_urlencoded.h" |
| @@ -233,7 +234,6 @@ static ssize_t http_handle_stats(const int64_t sock, struct ot_workstruct *ws, c | |||
| 233 | {"scrp", TASK_STATS_SCRAPE}, | 234 | {"scrp", TASK_STATS_SCRAPE}, |
| 234 | {"udp4", TASK_STATS_UDP}, | 235 | {"udp4", TASK_STATS_UDP}, |
| 235 | {"tcp4", TASK_STATS_TCP}, | 236 | {"tcp4", TASK_STATS_TCP}, |
| 236 | {"busy", TASK_STATS_BUSY_NETWORKS}, | ||
| 237 | {"torr", TASK_STATS_TORRENTS}, | 237 | {"torr", TASK_STATS_TORRENTS}, |
| 238 | {"fscr", TASK_STATS_FULLSCRAPE}, | 238 | {"fscr", TASK_STATS_FULLSCRAPE}, |
| 239 | {"s24s", TASK_STATS_SLASH24S}, | 239 | {"s24s", TASK_STATS_SLASH24S}, |
| @@ -418,13 +418,15 @@ static ssize_t http_handle_fullscrape(const int64_t sock, struct ot_workstruct * | |||
| 418 | } | 418 | } |
| 419 | #endif | 419 | #endif |
| 420 | 420 | ||
| 421 | static int compare_hash(const void *left, const void *right) { return memcmp(left, right, sizeof(ot_hash)); } | ||
| 422 | |||
| 421 | static ssize_t http_handle_scrape(const int64_t sock, struct ot_workstruct *ws, char *read_ptr) { | 423 | static ssize_t http_handle_scrape(const int64_t sock, struct ot_workstruct *ws, char *read_ptr) { |
| 422 | static const ot_keywords keywords_scrape[] = {{"info_hash", 1}, {NULL, -3}}; | 424 | static const ot_keywords keywords_scrape[] = {{"info_hash", 1}, {NULL, -3}}; |
| 423 | 425 | ||
| 424 | ot_hash *multiscrape_buf = (ot_hash *)ws->request; | 426 | ot_hash *multiscrape_buf = (ot_hash *)ws->request; |
| 425 | char *reply = ws->reply; | 427 | char *reply = ws->reply; |
| 426 | int scanon = 1; | 428 | int scanon = 1; |
| 427 | size_t numwant = 0; | 429 | size_t i, unique, numwant = 0; |
| 428 | 430 | ||
| 429 | /* This is to hack around stupid clients that send "scrape ?info_hash" */ | 431 | /* This is to hack around stupid clients that send "scrape ?info_hash" */ |
| 430 | if (read_ptr[-1] != '?') { | 432 | if (read_ptr[-1] != '?') { |
| @@ -461,6 +463,14 @@ static ssize_t http_handle_scrape(const int64_t sock, struct ot_workstruct *ws, | |||
| 461 | if (numwant > OT_MAXMULTISCRAPE_COUNT) | 463 | if (numwant > OT_MAXMULTISCRAPE_COUNT) |
| 462 | numwant = OT_MAXMULTISCRAPE_COUNT; | 464 | numwant = OT_MAXMULTISCRAPE_COUNT; |
| 463 | 465 | ||
| 466 | /* A bencoded dictionary has its keys in order and names each one once, so | ||
| 467 | the answer cannot just follow the order the client asked in */ | ||
| 468 | qsort(multiscrape_buf, numwant, sizeof(ot_hash), compare_hash); | ||
| 469 | for (i = unique = 1; i < numwant; ++i) | ||
| 470 | if (memcmp(multiscrape_buf[i], multiscrape_buf[unique - 1], sizeof(ot_hash))) | ||
| 471 | memcpy(multiscrape_buf[unique++], multiscrape_buf[i], sizeof(ot_hash)); | ||
| 472 | numwant = unique; | ||
| 473 | |||
| 464 | /* Enough for http header + whole scrape string */ | 474 | /* Enough for http header + whole scrape string */ |
| 465 | return_tcp_scrape_for_torrent((const ot_hash *)multiscrape_buf, numwant, &reply, ws->outbuf + G_OUTBUF_SIZE); | 475 | return_tcp_scrape_for_torrent((const ot_hash *)multiscrape_buf, numwant, &reply, ws->outbuf + G_OUTBUF_SIZE); |
| 466 | ws->reply_size = reply - ws->reply; | 476 | ws->reply_size = reply - ws->reply; |
| @@ -727,6 +737,24 @@ ssize_t http_handle_request(const int64_t sock, struct ot_workstruct *ws) { | |||
| 727 | /* Tell subroutines where to put reply data */ | 737 | /* Tell subroutines where to put reply data */ |
| 728 | ws->reply = ws->outbuf + SUCCESS_HTTP_HEADER_LENGTH; | 738 | ws->reply = ws->outbuf + SUCCESS_HTTP_HEADER_LENGTH; |
| 729 | 739 | ||
| 740 | /* Find out if the client wants to keep this connection alive, before any | ||
| 741 | subroutine gets to answer: an error reply finishes with the connection | ||
| 742 | on its way out, and ws outlives the connection it was serving */ | ||
| 743 | ws->keep_alive = 0; | ||
| 744 | #ifdef WANT_KEEPALIVE | ||
| 745 | if ((write_ptr = http_header(ws->request, ws->header_size, "connection")) && (*write_ptr == 'K' || *write_ptr == 'k')) | ||
| 746 | ws->keep_alive = 1; | ||
| 747 | #endif | ||
| 748 | { | ||
| 749 | struct http_data *connection = fdstate_cookie(sock); | ||
| 750 | if (connection) { | ||
| 751 | if (ws->keep_alive) | ||
| 752 | connection->flag |= STRUCT_HTTP_FLAG_KEEPALIVE; | ||
| 753 | else | ||
| 754 | connection->flag &= ~STRUCT_HTTP_FLAG_KEEPALIVE; | ||
| 755 | } | ||
| 756 | } | ||
| 757 | |||
| 730 | /* This one implicitely tests strlen < 5, too -- remember, it is \n terminated */ | 758 | /* This one implicitely tests strlen < 5, too -- remember, it is \n terminated */ |
| 731 | if (memcmp(read_ptr, "GET /", 5)) | 759 | if (memcmp(read_ptr, "GET /", 5)) |
| 732 | HTTPERROR_400; | 760 | HTTPERROR_400; |
| @@ -763,14 +791,6 @@ ssize_t http_handle_request(const int64_t sock, struct ot_workstruct *ws) { | |||
| 763 | else | 791 | else |
| 764 | HTTPERROR_404; | 792 | HTTPERROR_404; |
| 765 | 793 | ||
| 766 | /* Find out if the client wants to keep this connection alive */ | ||
| 767 | ws->keep_alive = 0; | ||
| 768 | #ifdef WANT_KEEPALIVE | ||
| 769 | read_ptr = http_header(ws->request, ws->header_size, "connection"); | ||
| 770 | if (read_ptr && (*read_ptr == 'K' || *read_ptr == 'k')) | ||
| 771 | ws->keep_alive = 1; | ||
| 772 | #endif | ||
| 773 | |||
| 774 | /* If routines handled sending themselves, just return */ | 794 | /* If routines handled sending themselves, just return */ |
| 775 | if (ws->reply_size == -2) | 795 | if (ws->reply_size == -2) |
| 776 | return 0; | 796 | return 0; |
| @@ -21,7 +21,8 @@ typedef enum { | |||
| 21 | STRUCT_HTTP_FLAG_BZIP2 = 4, | 21 | STRUCT_HTTP_FLAG_BZIP2 = 4, |
| 22 | STRUCT_HTTP_FLAG_ZSTD = 8, | 22 | STRUCT_HTTP_FLAG_ZSTD = 8, |
| 23 | STRUCT_HTTP_FLAG_CHUNKED = 16, | 23 | STRUCT_HTTP_FLAG_CHUNKED = 16, |
| 24 | STRUCT_HTTP_FLAG_CHUNKED_IN_TRANSFER = 32 | 24 | STRUCT_HTTP_FLAG_CHUNKED_IN_TRANSFER = 32, |
| 25 | STRUCT_HTTP_FLAG_KEEPALIVE = 64 | ||
| 25 | } STRUCT_HTTP_FLAG; | 26 | } STRUCT_HTTP_FLAG; |
| 26 | 27 | ||
| 27 | struct http_data { | 28 | struct http_data { |
| @@ -29,7 +29,6 @@ typedef enum { | |||
| 29 | TASK_STATS_TPB = 0x0006, | 29 | TASK_STATS_TPB = 0x0006, |
| 30 | TASK_STATS_HTTPERRORS = 0x0007, | 30 | TASK_STATS_HTTPERRORS = 0x0007, |
| 31 | TASK_STATS_VERSION = 0x0008, | 31 | TASK_STATS_VERSION = 0x0008, |
| 32 | TASK_STATS_BUSY_NETWORKS = 0x0009, | ||
| 33 | TASK_STATS_RENEW = 0x000a, | 32 | TASK_STATS_RENEW = 0x000a, |
| 34 | TASK_STATS_SYNCS = 0x000b, | 33 | TASK_STATS_SYNCS = 0x000b, |
| 35 | TASK_STATS_COMPLETED = 0x000c, | 34 | TASK_STATS_COMPLETED = 0x000c, |
| @@ -105,10 +105,11 @@ int handle_udp6(int64_t serversocket, struct ot_workstruct *ws) { | |||
| 105 | match, return an error packet */ | 105 | match, return an error packet */ |
| 106 | udp_make_connectionid(connid, remoteip, 1); | 106 | udp_make_connectionid(connid, remoteip, 1); |
| 107 | if (inpacket[0] != connid[0] || inpacket[1] != connid[1]) { | 107 | if (inpacket[0] != connid[0] || inpacket[1] != connid[1]) { |
| 108 | const size_t s = sizeof("Connection ID missmatch."); | 108 | const char err_idmiss[] = "Connection ID missmatch."; |
| 109 | size_t s = sizeof(err_idmiss); | ||
| 109 | outpacket[0] = htonl(3); | 110 | outpacket[0] = htonl(3); |
| 110 | outpacket[1] = inpacket[3]; | 111 | outpacket[1] = inpacket[3]; |
| 111 | memcpy(&outpacket[2], "Connection ID missmatch.", s); | 112 | memcpy(&outpacket[2], &err_idmiss[0], s); |
| 112 | socket_send(serversocket, ws->outbuf, 8 + s, remoteip, remoteport); | 113 | socket_send(serversocket, ws->outbuf, 8 + s, remoteip, remoteport); |
| 113 | stats_issue_event(EVENT_CONNID_MISSMATCH, FLAG_UDP, 8 + s); | 114 | stats_issue_event(EVENT_CONNID_MISSMATCH, FLAG_UDP, 8 + s); |
| 114 | return 1; | 115 | return 1; |
| @@ -173,7 +174,17 @@ int handle_udp6(int64_t serversocket, struct ot_workstruct *ws) { | |||
| 173 | numwant = max_peers; | 174 | numwant = max_peers; |
| 174 | 175 | ||
| 175 | ws->reply = ws->outbuf + 8; | 176 | ws->reply = ws->outbuf + 8; |
| 176 | ws->reply_size = 8 + add_peer_to_torrent_and_return_peers(FLAG_UDP, ws, numwant); | 177 | ws->reply_size = add_peer_to_torrent_and_return_peers(FLAG_UDP, ws, numwant); |
| 178 | |||
| 179 | if (!ws->reply_size) { | ||
| 180 | const char err_unauth[] = "Requested download is not authorized for use with this tracker."; | ||
| 181 | size_t s = sizeof(err_unauth); | ||
| 182 | outpacket[0] = htonl(3); | ||
| 183 | memcpy(&outpacket[2], &err_unauth[0], s); | ||
| 184 | socket_send(serversocket, ws->outbuf, 8 + s, remoteip, remoteport); | ||
| 185 | return 1; | ||
| 186 | } | ||
| 187 | ws->reply_size += 8; | ||
| 177 | } | 188 | } |
| 178 | 189 | ||
| 179 | socket_send(serversocket, ws->outbuf, ws->reply_size, remoteip, remoteport); | 190 | socket_send(serversocket, ws->outbuf, ws->reply_size, remoteip, remoteport); |
diff --git a/tests/integration/harness.py b/tests/integration/harness.py index c8da1e2..03a0561 100644 --- a/tests/integration/harness.py +++ b/tests/integration/harness.py | |||
| @@ -7,6 +7,8 @@ reports its own memory errors, which the teardown turns into test failures. | |||
| 7 | """ | 7 | """ |
| 8 | 8 | ||
| 9 | import os | 9 | import os |
| 10 | import shutil | ||
| 11 | import signal | ||
| 10 | import socket | 12 | import socket |
| 11 | import struct | 13 | import struct |
| 12 | import subprocess | 14 | import subprocess |
| @@ -58,18 +60,40 @@ def free_port(): | |||
| 58 | class Tracker: | 60 | class Tracker: |
| 59 | """One tracker process, listening on loopback.""" | 61 | """One tracker process, listening on loopback.""" |
| 60 | 62 | ||
| 61 | def __init__(self, extra_config=""): | 63 | def __init__(self, extra_config="", files=None): |
| 62 | self.port = free_port() | 64 | self.port = free_port() |
| 63 | self.dir = tempfile.mkdtemp(prefix="ot-integration-") | 65 | self.dir = tempfile.mkdtemp(prefix="ot-integration-") |
| 64 | self.config = os.path.join(self.dir, "opentracker.conf") | 66 | self.log = None |
| 65 | with open(self.config, "w") as handle: | 67 | self.process = None |
| 66 | handle.write("listen.tcp 127.0.0.1:%d\n" % self.port) | 68 | try: |
| 67 | handle.write("listen.udp 127.0.0.1:%d\n" % self.port) | 69 | for name, content in (files or {}).items(): |
| 68 | handle.write(extra_config) | 70 | with open(os.path.join(self.dir, name), "wb") as handle: |
| 69 | self.log = open(os.path.join(self.dir, "tracker.log"), "w+b") | 71 | handle.write(content) |
| 70 | environment = dict(os.environ, ASAN_OPTIONS="detect_leaks=0:abort_on_error=0") | 72 | self.config = os.path.join(self.dir, "opentracker.conf") |
| 71 | self.process = subprocess.Popen([TRACKER, "-f", self.config], stdout=self.log, stderr=self.log, env=environment) | 73 | with open(self.config, "w") as handle: |
| 72 | self._wait_for_port() | 74 | handle.write("listen.tcp 127.0.0.1:%d\n" % self.port) |
| 75 | handle.write("listen.udp 127.0.0.1:%d\n" % self.port) | ||
| 76 | handle.write(extra_config.replace("{dir}", self.dir)) | ||
| 77 | self.log = open(os.path.join(self.dir, "tracker.log"), "w+b") | ||
| 78 | # Leak detection is left at the sanitizer's own default, which is on | ||
| 79 | # where LeakSanitizer exists and off where it does not. Asking for it | ||
| 80 | # by name makes the tracker refuse to start on macOS and FreeBSD. | ||
| 81 | environment = dict(os.environ, ASAN_OPTIONS="abort_on_error=0") | ||
| 82 | self.process = subprocess.Popen([TRACKER, "-f", self.config], stdout=self.log, stderr=self.log, env=environment) | ||
| 83 | self._wait_for_port() | ||
| 84 | except BaseException: | ||
| 85 | self._cleanup() | ||
| 86 | raise | ||
| 87 | |||
| 88 | def _cleanup(self): | ||
| 89 | """Close what we opened and take the scratch directory with it.""" | ||
| 90 | if self.process is not None and self.process.poll() is None: | ||
| 91 | self.process.kill() | ||
| 92 | self.process.wait() | ||
| 93 | if self.log is not None: | ||
| 94 | self.log.close() | ||
| 95 | self.log = None | ||
| 96 | shutil.rmtree(self.dir, ignore_errors=True) | ||
| 73 | 97 | ||
| 74 | def _wait_for_port(self): | 98 | def _wait_for_port(self): |
| 75 | for _ in range(200): | 99 | for _ in range(200): |
| @@ -84,21 +108,32 @@ class Tracker: | |||
| 84 | raise AssertionError("tracker never listened on %d:\n%s" % (self.port, self.output())) | 108 | raise AssertionError("tracker never listened on %d:\n%s" % (self.port, self.output())) |
| 85 | 109 | ||
| 86 | def output(self): | 110 | def output(self): |
| 111 | if self.log is None: | ||
| 112 | return "" | ||
| 87 | self.log.flush() | 113 | self.log.flush() |
| 88 | self.log.seek(0) | 114 | self.log.seek(0) |
| 89 | return self.log.read().decode("utf-8", "replace") | 115 | return self.log.read().decode("utf-8", "replace") |
| 90 | 116 | ||
| 91 | def stop(self): | 117 | def stop(self): |
| 92 | """Returns anything the tracker complained about on the way out.""" | 118 | """Returns anything the tracker complained about on the way out. |
| 93 | if self.process.poll() is None: | 119 | |
| 94 | self.process.kill() | 120 | The interrupt rather than a kill is what makes the leak check work at |
| 95 | self.process.wait() | 121 | all: LeakSanitizer reports from an exit handler, so a killed tracker |
| 122 | reports nothing and the suite passes over leaks it never looked for. | ||
| 123 | """ | ||
| 124 | if self.process is not None and self.process.poll() is None: | ||
| 125 | self.process.send_signal(signal.SIGINT) | ||
| 126 | try: | ||
| 127 | self.process.wait(timeout=5) | ||
| 128 | except subprocess.TimeoutExpired: | ||
| 129 | self.process.kill() | ||
| 130 | self.process.wait() | ||
| 96 | complaints = [ | 131 | complaints = [ |
| 97 | line | 132 | line |
| 98 | for line in self.output().splitlines() | 133 | for line in self.output().splitlines() |
| 99 | if "Sanitizer" in line or "runtime error" in line or line.startswith("ERROR") | 134 | if "Sanitizer" in line or "runtime error" in line or line.startswith("ERROR") |
| 100 | ] | 135 | ] |
| 101 | self.log.close() | 136 | self._cleanup() |
| 102 | return complaints | 137 | return complaints |
| 103 | 138 | ||
| 104 | # ----------------------------------------------------------- over http | 139 | # ----------------------------------------------------------- over http |
| @@ -122,6 +157,12 @@ class Tracker: | |||
| 122 | def stats(self, mode): | 157 | def stats(self, mode): |
| 123 | return self.get("/stats?mode=" + mode) | 158 | return self.get("/stats?mode=" + mode) |
| 124 | 159 | ||
| 160 | def get_with_headers(self, path, headers=None, timeout=10): | ||
| 161 | """The body and the response headers, for the compressed answers.""" | ||
| 162 | request = urllib.request.Request("http://127.0.0.1:%d%s" % (self.port, path), headers=headers or {}) | ||
| 163 | with urllib.request.urlopen(request, timeout=timeout) as response: | ||
| 164 | return response.read(), dict(response.headers) | ||
| 165 | |||
| 125 | def torrent_count(self): | 166 | def torrent_count(self): |
| 126 | return int(self.stats("torr").split()[0]) | 167 | return int(self.stats("torr").split()[0]) |
| 127 | 168 | ||
| @@ -148,16 +189,117 @@ class Tracker: | |||
| 148 | assert action == 1, "udp announce answered action %d" % action | 189 | assert action == 1, "udp announce answered action %d" % action |
| 149 | return {"interval": interval, "leechers": leechers, "seeders": seeders, "peers": answer[20:]} | 190 | return {"interval": interval, "leechers": leechers, "seeders": seeders, "peers": answer[20:]} |
| 150 | 191 | ||
| 192 | def udp_scrape(self, sock, connection_id, hashes): | ||
| 193 | """One (seeders, completed, leechers) triple per hash, in order.""" | ||
| 194 | sock.sendto(struct.pack(">QII", connection_id, 2, 3) + b"".join(hashes), ("127.0.0.1", self.port)) | ||
| 195 | answer = sock.recv(2048) | ||
| 196 | action, _ = struct.unpack(">II", answer[:8]) | ||
| 197 | assert action == 2, "udp scrape answered action %d" % action | ||
| 198 | return [struct.unpack(">III", answer[8 + 12 * i : 20 + 12 * i]) for i in range(len(hashes))] | ||
| 199 | |||
| 200 | def connect(self): | ||
| 201 | """A connection the caller drives and closes.""" | ||
| 202 | return Connection(self.port) | ||
| 203 | |||
| 204 | def udp_raw(self, payload, timeout=1.0): | ||
| 205 | """Sends a packet exactly as given. Returns the answer, or None if the | ||
| 206 | tracker chose to say nothing, which is how it treats a broken one.""" | ||
| 207 | sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) | ||
| 208 | sock.settimeout(timeout) | ||
| 209 | try: | ||
| 210 | sock.sendto(payload, ("127.0.0.1", self.port)) | ||
| 211 | try: | ||
| 212 | return sock.recv(2048) | ||
| 213 | except socket.timeout: | ||
| 214 | return None | ||
| 215 | finally: | ||
| 216 | sock.close() | ||
| 217 | |||
| 218 | |||
| 219 | class Connection: | ||
| 220 | """One HTTP connection the caller keeps open, which urllib will not do. | ||
| 221 | |||
| 222 | Reads exactly one reply at a time, so a test can tell "the tracker | ||
| 223 | answered and kept the socket" from "the tracker answered and hung up".""" | ||
| 224 | |||
| 225 | def __init__(self, port, timeout=5): | ||
| 226 | self.sock = socket.create_connection(("127.0.0.1", port), timeout=timeout) | ||
| 227 | self.sock.settimeout(timeout) | ||
| 228 | self.buffer = b"" | ||
| 229 | |||
| 230 | def send(self, path, connection="Keep-Alive", version="1.1"): | ||
| 231 | request = "GET %s HTTP/%s\r\nHost: tracker\r\n" % (path, version) | ||
| 232 | if connection is not None: | ||
| 233 | request += "Connection: %s\r\n" % connection | ||
| 234 | self.sock.sendall((request + "\r\n").encode()) | ||
| 235 | |||
| 236 | def _fill(self): | ||
| 237 | chunk = self.sock.recv(65536) | ||
| 238 | if not chunk: | ||
| 239 | raise EOFError("the tracker closed the connection") | ||
| 240 | self.buffer += chunk | ||
| 241 | |||
| 242 | def reply(self): | ||
| 243 | """The one complete reply at the front of the stream, headers and body.""" | ||
| 244 | while b"\r\n\r\n" not in self.buffer: | ||
| 245 | self._fill() | ||
| 246 | head, rest = self.buffer.split(b"\r\n\r\n", 1) | ||
| 247 | headers = {} | ||
| 248 | for line in head.split(b"\r\n")[1:]: | ||
| 249 | name, _, value = line.partition(b":") | ||
| 250 | headers[name.strip().lower()] = value.strip() | ||
| 251 | |||
| 252 | if headers.get(b"transfer-encoding") == b"chunked": | ||
| 253 | while not rest.endswith(b"0\r\n\r\n"): | ||
| 254 | self.buffer = head + b"\r\n\r\n" + rest | ||
| 255 | self._fill() | ||
| 256 | rest = self.buffer.split(b"\r\n\r\n", 1)[1] | ||
| 257 | body, self.buffer = rest, b"" | ||
| 258 | else: | ||
| 259 | length = int(headers.get(b"content-length", b"0")) | ||
| 260 | while len(rest) < length: | ||
| 261 | self.buffer = head + b"\r\n\r\n" + rest | ||
| 262 | self._fill() | ||
| 263 | rest = self.buffer.split(b"\r\n\r\n", 1)[1] | ||
| 264 | body, self.buffer = rest[:length], rest[length:] | ||
| 265 | return head.split(b"\r\n")[0], headers, body | ||
| 266 | |||
| 267 | def is_open(self): | ||
| 268 | """True if the tracker is still holding the connection.""" | ||
| 269 | try: | ||
| 270 | self.sock.settimeout(0.4) | ||
| 271 | return self.sock.recv(1) != b"" | ||
| 272 | except socket.timeout: | ||
| 273 | return True | ||
| 274 | except OSError: | ||
| 275 | return False | ||
| 276 | finally: | ||
| 277 | try: | ||
| 278 | self.sock.settimeout(5) | ||
| 279 | except OSError: | ||
| 280 | pass | ||
| 281 | |||
| 282 | def close(self): | ||
| 283 | self.sock.close() | ||
| 284 | |||
| 151 | 285 | ||
| 152 | class TrackerTestCase(unittest.TestCase): | 286 | class TrackerTestCase(unittest.TestCase): |
| 153 | """Gives every test its own tracker and fails it on any sanitizer output.""" | 287 | """Gives every test its own tracker and fails it on any sanitizer output.""" |
| 154 | 288 | ||
| 155 | config = "" | 289 | config = "" |
| 290 | files = None | ||
| 156 | 291 | ||
| 157 | def setUp(self): | 292 | def setUp(self): |
| 158 | self.tracker = Tracker(self.config) | 293 | self.tracker = Tracker(self.config, self.files) |
| 159 | 294 | ||
| 160 | def tearDown(self): | 295 | def tearDown(self): |
| 296 | # A connection the test closed is only reaped when the event loop gets | ||
| 297 | # round to it, and a cookie still held at exit reads as a leak. One | ||
| 298 | # more request puts us behind that work in the loop's queue. | ||
| 299 | try: | ||
| 300 | self.tracker.torrent_count() | ||
| 301 | except Exception: | ||
| 302 | pass | ||
| 161 | complaints = self.tracker.stop() | 303 | complaints = self.tracker.stop() |
| 162 | self.assertEqual(complaints, [], "the tracker reported:\n" + "\n".join(complaints)) | 304 | self.assertEqual(complaints, [], "the tracker reported:\n" + "\n".join(complaints)) |
| 163 | 305 | ||
diff --git a/tests/integration/test_accesslist.py b/tests/integration/test_accesslist.py new file mode 100644 index 0000000..41ff654 --- /dev/null +++ b/tests/integration/test_accesslist.py | |||
| @@ -0,0 +1,100 @@ | |||
| 1 | """The blacklist, loaded from a file at startup. | ||
| 2 | |||
| 3 | A blacklisted info hash must be refused at both the announce and the scrape | ||
| 4 | entry, and the file parser has to cope with the shapes an operator actually | ||
| 5 | produces: an empty file, and a last line with no newline after it. | ||
| 6 | """ | ||
| 7 | |||
| 8 | import struct | ||
| 9 | import unittest | ||
| 10 | |||
| 11 | from harness import TrackerTestCase | ||
| 12 | |||
| 13 | BLOCKED = b"\xb1" * 20 | ||
| 14 | ALLOWED = b"\xa1" * 20 | ||
| 15 | |||
| 16 | |||
| 17 | def listing(*hashes): | ||
| 18 | return b"".join(h.hex().upper().encode() + b"\n" for h in hashes) | ||
| 19 | |||
| 20 | |||
| 21 | class Blacklist(TrackerTestCase): | ||
| 22 | config = "access.blacklist {dir}/blacklist\n" | ||
| 23 | files = {"blacklist": listing(BLOCKED)} | ||
| 24 | |||
| 25 | def test_a_blacklisted_hash_is_refused(self): | ||
| 26 | answer = self.tracker.announce(BLOCKED, port=6881, left=0) | ||
| 27 | self.assertIn(b"failure reason", answer) | ||
| 28 | self.assertIn(b"not authorized", answer[b"failure reason"]) | ||
| 29 | |||
| 30 | def test_a_blacklisted_hash_never_becomes_a_torrent(self): | ||
| 31 | before = self.tracker.torrent_count() | ||
| 32 | self.tracker.announce(BLOCKED, port=6881, left=0) | ||
| 33 | self.assertEqual(self.tracker.torrent_count(), before, "the refused hash was stored anyway") | ||
| 34 | |||
| 35 | def test_any_other_hash_is_served(self): | ||
| 36 | answer = self.tracker.announce(ALLOWED, port=6881, left=0) | ||
| 37 | self.assertNotIn(b"failure reason", answer) | ||
| 38 | self.assertEqual(answer[b"complete"], 1) | ||
| 39 | |||
| 40 | def test_the_block_is_an_error_packet_over_udp(self): | ||
| 41 | """BEP 15 has an error action, which is what a refusal should use. | ||
| 42 | It used to answer the announce header with no body behind it, a | ||
| 43 | packet too short for any client to read.""" | ||
| 44 | sock, connection_id = self.tracker.udp_connect() | ||
| 45 | sock.close() | ||
| 46 | request = struct.pack( | ||
| 47 | ">QII20s20sQQQIIIiH", connection_id, 1, 7, BLOCKED, b"p" * 20, 0, 0, 0, 0, 0, 0, -1, 6881 | ||
| 48 | ) | ||
| 49 | answer = self.tracker.udp_raw(request) | ||
| 50 | self.assertIsNotNone(answer) | ||
| 51 | action, transaction = struct.unpack(">II", answer[:8]) | ||
| 52 | self.assertEqual(action, 3, "action 3 is the error packet") | ||
| 53 | self.assertEqual(transaction, 7) | ||
| 54 | self.assertIn(b"not authorized", answer[8:]) | ||
| 55 | |||
| 56 | def test_a_blocked_hash_is_not_stored_when_it_arrives_over_udp(self): | ||
| 57 | sock, connection_id = self.tracker.udp_connect() | ||
| 58 | sock.close() | ||
| 59 | self.tracker.udp_raw( | ||
| 60 | struct.pack(">QII20s20sQQQIIIiH", connection_id, 1, 8, BLOCKED, b"p" * 20, 0, 0, 0, 0, 0, 0, -1, 6881) | ||
| 61 | ) | ||
| 62 | self.assertEqual(self.tracker.torrent_count(), 0) | ||
| 63 | |||
| 64 | |||
| 65 | class BlacklistWithoutTrailingNewline(TrackerTestCase): | ||
| 66 | """A single hash with no newline after it used to size the list at zero | ||
| 67 | and then write into it, which took the tracker down before it listened.""" | ||
| 68 | |||
| 69 | config = "access.blacklist {dir}/blacklist\n" | ||
| 70 | files = {"blacklist": BLOCKED.hex().upper().encode()} | ||
| 71 | |||
| 72 | def test_the_last_line_counts_even_without_its_newline(self): | ||
| 73 | answer = self.tracker.announce(BLOCKED, port=6881, left=0) | ||
| 74 | self.assertIn(b"failure reason", answer) | ||
| 75 | |||
| 76 | def test_and_the_tracker_still_serves_everything_else(self): | ||
| 77 | self.assertEqual(self.tracker.announce(ALLOWED, port=6881, left=0)[b"complete"], 1) | ||
| 78 | |||
| 79 | |||
| 80 | class EmptyBlacklist(TrackerTestCase): | ||
| 81 | config = "access.blacklist {dir}/blacklist\n" | ||
| 82 | files = {"blacklist": b""} | ||
| 83 | |||
| 84 | def test_an_empty_file_blocks_nothing_and_starts_cleanly(self): | ||
| 85 | self.assertEqual(self.tracker.announce(BLOCKED, port=6881, left=0)[b"complete"], 1) | ||
| 86 | self.assertEqual(self.tracker.announce(ALLOWED, port=6882, left=0)[b"complete"], 1) | ||
| 87 | |||
| 88 | |||
| 89 | class MissingBlacklist(TrackerTestCase): | ||
| 90 | """The file is named but absent: the tracker warns and serves everything, | ||
| 91 | because it may be created later.""" | ||
| 92 | |||
| 93 | config = "access.blacklist {dir}/absent\n" | ||
| 94 | |||
| 95 | def test_a_missing_file_blocks_nothing(self): | ||
| 96 | self.assertEqual(self.tracker.announce(BLOCKED, port=6881, left=0)[b"complete"], 1) | ||
| 97 | |||
| 98 | |||
| 99 | if __name__ == "__main__": | ||
| 100 | unittest.main() | ||
diff --git a/tests/integration/test_fullscrape.py b/tests/integration/test_fullscrape.py new file mode 100644 index 0000000..be7b502 --- /dev/null +++ b/tests/integration/test_fullscrape.py | |||
| @@ -0,0 +1,146 @@ | |||
| 1 | """The full scrape, in every format the tracker offers. | ||
| 2 | |||
| 3 | Each format is a separate writer, and they differ in more than cosmetics: | ||
| 4 | one is binary, one is bencoded, three are line based and one dumps the | ||
| 5 | tracker's own state for a restart. A worker thread produces them in chunks, | ||
| 6 | so these also exercise the chunked transfer the ordinary replies never take. | ||
| 7 | """ | ||
| 8 | |||
| 9 | import gzip | ||
| 10 | import struct | ||
| 11 | import unittest | ||
| 12 | |||
| 13 | from harness import TrackerTestCase, bdecode | ||
| 14 | |||
| 15 | HEX = b"0123456789ABCDEF" | ||
| 16 | |||
| 17 | |||
| 18 | class FullScrape(TrackerTestCase): | ||
| 19 | def setUp(self): | ||
| 20 | TrackerTestCase.setUp(self) | ||
| 21 | self.seeding = self.hash_for("fsA") | ||
| 22 | self.leeching = self.hash_for("fsB") | ||
| 23 | self.tracker.announce(self.seeding, port=6001, left=0) | ||
| 24 | self.tracker.announce(self.leeching, port=6002, left=4096) | ||
| 25 | |||
| 26 | def scrape_all(self, query, headers=None): | ||
| 27 | body, head = self.tracker.get_with_headers(query, headers) | ||
| 28 | if head.get("Content-Encoding") == "gzip": | ||
| 29 | body = gzip.decompress(body) | ||
| 30 | return body | ||
| 31 | |||
| 32 | # --------------------------------------------------------- bencoded | ||
| 33 | |||
| 34 | def test_a_bare_scrape_returns_every_torrent(self): | ||
| 35 | answer = bdecode(self.scrape_all("/scrape")) | ||
| 36 | self.assertIn(self.seeding, answer[b"files"]) | ||
| 37 | self.assertIn(self.leeching, answer[b"files"]) | ||
| 38 | self.assertEqual(answer[b"files"][self.seeding][b"complete"], 1) | ||
| 39 | self.assertEqual(answer[b"files"][self.leeching][b"incomplete"], 1) | ||
| 40 | |||
| 41 | def test_the_bencoded_format_matches_the_bare_scrape(self): | ||
| 42 | self.assertEqual(bdecode(self.scrape_all("/stats?mode=tpbs&format=ben")), bdecode(self.scrape_all("/scrape"))) | ||
| 43 | |||
| 44 | def test_a_full_scrape_can_be_gzipped(self): | ||
| 45 | plain = self.scrape_all("/scrape") | ||
| 46 | body, head = self.tracker.get_with_headers("/scrape", {"Accept-Encoding": "gzip"}) | ||
| 47 | self.assertEqual(head.get("Content-Encoding"), "gzip") | ||
| 48 | self.assertEqual(gzip.decompress(body), plain) | ||
| 49 | |||
| 50 | # ----------------------------------------------------------- binary | ||
| 51 | |||
| 52 | def test_the_binary_format_is_a_hash_and_two_counts(self): | ||
| 53 | body = self.scrape_all("/stats?mode=tpbs&format=bin") | ||
| 54 | self.assertEqual(len(body) % 28, 0, "twenty byte hash plus two counts") | ||
| 55 | entries = {body[i : i + 20]: struct.unpack(">II", body[i + 20 : i + 28]) for i in range(0, len(body), 28)} | ||
| 56 | self.assertEqual(entries[self.seeding], (1, 0), "one seeder, no leechers") | ||
| 57 | self.assertEqual(entries[self.leeching], (0, 1), "no seeders, one leecher") | ||
| 58 | |||
| 59 | # ------------------------------------------------------- line based | ||
| 60 | |||
| 61 | def entries_from_lines(self, body): | ||
| 62 | return {line.split(b":")[0]: line.split(b":")[1:] for line in body.splitlines() if line} | ||
| 63 | |||
| 64 | def test_the_text_format_is_hex_colon_seeders_colon_leechers(self): | ||
| 65 | entries = self.entries_from_lines(self.scrape_all("/stats?mode=tpbs&format=txt")) | ||
| 66 | self.assertEqual(entries[self.seeding.hex().upper().encode()], [b"1", b"0"]) | ||
| 67 | self.assertEqual(entries[self.leeching.hex().upper().encode()], [b"0", b"1"]) | ||
| 68 | |||
| 69 | def test_the_text_plus_format_adds_the_completed_count(self): | ||
| 70 | entries = self.entries_from_lines(self.scrape_all("/stats?mode=tpbs&format=txtp")) | ||
| 71 | self.assertEqual(entries[self.seeding.hex().upper().encode()], [b"1", b"0", b"0"]) | ||
| 72 | |||
| 73 | def test_the_urlencoded_format_escapes_the_hash(self): | ||
| 74 | body = self.scrape_all("/stats?mode=tpbs&format=url") | ||
| 75 | lines = [line for line in body.splitlines() if line] | ||
| 76 | self.assertEqual(len(lines), 2) | ||
| 77 | for line in lines: | ||
| 78 | escaped = line.rsplit(b":", 2)[0] | ||
| 79 | self.assertIn(b"%", escaped, "these hashes are mostly unprintable bytes") | ||
| 80 | |||
| 81 | def test_the_state_dump_carries_a_base_time_rather_than_a_peer_count(self): | ||
| 82 | """What a restart reads back, so its second column is the torrent's | ||
| 83 | own clock and not a count of anybody.""" | ||
| 84 | entries = self.entries_from_lines(self.scrape_all("/stats?mode=statedump")) | ||
| 85 | self.assertIn(self.seeding.hex().upper().encode(), entries) | ||
| 86 | base, completed = entries[self.seeding.hex().upper().encode()] | ||
| 87 | self.assertGreater(int(base), 0) | ||
| 88 | self.assertEqual(int(completed), 0) | ||
| 89 | |||
| 90 | # ------------------------------------------------------------ shape | ||
| 91 | |||
| 92 | def test_every_format_sees_the_same_torrents(self): | ||
| 93 | counts = { | ||
| 94 | "ben": len(bdecode(self.scrape_all("/stats?mode=tpbs&format=ben"))[b"files"]), | ||
| 95 | "bin": len(self.scrape_all("/stats?mode=tpbs&format=bin")) // 28, | ||
| 96 | "txt": len(self.entries_from_lines(self.scrape_all("/stats?mode=tpbs&format=txt"))), | ||
| 97 | "txtp": len(self.entries_from_lines(self.scrape_all("/stats?mode=tpbs&format=txtp"))), | ||
| 98 | "url": len([l for l in self.scrape_all("/stats?mode=tpbs&format=url").splitlines() if l]), | ||
| 99 | } | ||
| 100 | self.assertEqual(set(counts.values()), {2}, "all formats, two torrents: %r" % counts) | ||
| 101 | |||
| 102 | |||
| 103 | class FullScrapeChunking(TrackerTestCase): | ||
| 104 | def test_a_scrape_larger_than_one_chunk_arrives_whole(self): | ||
| 105 | """The writer hands the socket a chunk at a time, so a scrape that | ||
| 106 | spans several is the case where the seams show.""" | ||
| 107 | for i in range(400): | ||
| 108 | self.tracker.announce(struct.pack(">I", i) + b"\0" * 16, port=7000 + i, left=0) | ||
| 109 | answer = bdecode(self.tracker.get("/scrape")) | ||
| 110 | self.assertEqual(len(answer[b"files"]), 400) | ||
| 111 | |||
| 112 | |||
| 113 | if __name__ == "__main__": | ||
| 114 | unittest.main() | ||
| 115 | |||
| 116 | |||
| 117 | class PartialScrapeOrder(TrackerTestCase): | ||
| 118 | """A bencoded dictionary names its keys in order, once each. The full | ||
| 119 | scrape got that from walking the buckets; the partial scrape used to | ||
| 120 | echo whatever order the client asked in.""" | ||
| 121 | |||
| 122 | def setUp(self): | ||
| 123 | TrackerTestCase.setUp(self) | ||
| 124 | self.hashes = [bytes([i]) + b"\0" * 19 for i in (9, 1, 5, 3, 7)] | ||
| 125 | for i, h in enumerate(self.hashes): | ||
| 126 | self.tracker.announce(h, port=6001 + i, left=0) | ||
| 127 | |||
| 128 | def scrape_many(self, hashes): | ||
| 129 | import urllib.parse | ||
| 130 | |||
| 131 | query = "&".join("info_hash=" + urllib.parse.quote_from_bytes(h, safe="") for h in hashes) | ||
| 132 | return bdecode(self.tracker.get("/scrape?" + query)) | ||
| 133 | |||
| 134 | def test_the_keys_come_back_in_order(self): | ||
| 135 | answer = self.scrape_many(self.hashes) | ||
| 136 | self.assertEqual(list(answer[b"files"]), sorted(self.hashes)) | ||
| 137 | |||
| 138 | def test_reversing_the_question_does_not_reverse_the_answer(self): | ||
| 139 | self.assertEqual( | ||
| 140 | list(self.scrape_many(self.hashes[::-1])[b"files"]), list(self.scrape_many(self.hashes)[b"files"]) | ||
| 141 | ) | ||
| 142 | |||
| 143 | def test_a_hash_asked_for_twice_is_named_once(self): | ||
| 144 | asked = [self.hashes[0], self.hashes[1], self.hashes[0]] | ||
| 145 | answer = self.scrape_many(asked) | ||
| 146 | self.assertEqual(list(answer[b"files"]), sorted({self.hashes[0], self.hashes[1]})) | ||
diff --git a/tests/integration/test_keepalive.py b/tests/integration/test_keepalive.py new file mode 100644 index 0000000..01f02a5 --- /dev/null +++ b/tests/integration/test_keepalive.py | |||
| @@ -0,0 +1,111 @@ | |||
| 1 | """Holding a connection open across several requests. | ||
| 2 | |||
| 3 | The reply path has two shapes. A small answer goes out in one write and the | ||
| 4 | connection is done with immediately. A large one is queued and finishes on a | ||
| 5 | later pass through the event loop, by which time the workstruct that served | ||
| 6 | the request has moved on, so whether to keep the connection has to be | ||
| 7 | remembered on the connection itself. | ||
| 8 | """ | ||
| 9 | |||
| 10 | import unittest | ||
| 11 | import urllib.parse | ||
| 12 | |||
| 13 | from harness import TrackerTestCase, bdecode | ||
| 14 | |||
| 15 | |||
| 16 | class KeepAlive(TrackerTestCase): | ||
| 17 | def announce_path(self, name, port=6881): | ||
| 18 | return "/announce?info_hash=%s&peer_id=%s&port=%d&left=0" % ( | ||
| 19 | urllib.parse.quote_from_bytes(self.hash_for(name), safe=""), | ||
| 20 | "x" * 20, | ||
| 21 | port, | ||
| 22 | ) | ||
| 23 | |||
| 24 | def test_two_requests_over_one_connection(self): | ||
| 25 | c = self.tracker.connect() | ||
| 26 | try: | ||
| 27 | c.send(self.announce_path("kaA")) | ||
| 28 | status, _, first = c.reply() | ||
| 29 | self.assertIn(b"200", status) | ||
| 30 | c.send(self.announce_path("kaB")) | ||
| 31 | status, _, second = c.reply() | ||
| 32 | self.assertIn(b"200", status) | ||
| 33 | self.assertIn(b"complete", bdecode(second)) | ||
| 34 | finally: | ||
| 35 | c.close() | ||
| 36 | |||
| 37 | def test_close_ends_the_connection(self): | ||
| 38 | c = self.tracker.connect() | ||
| 39 | try: | ||
| 40 | c.send(self.announce_path("kaclose"), connection="close") | ||
| 41 | c.reply() | ||
| 42 | self.assertFalse(c.is_open(), "the tracker was asked to hang up") | ||
| 43 | finally: | ||
| 44 | c.close() | ||
| 45 | |||
| 46 | def test_a_connection_survives_a_reply_too_large_for_one_write(self): | ||
| 47 | """The case that was broken: a queued reply finished draining and the | ||
| 48 | connection was closed regardless of what the client had asked for.""" | ||
| 49 | for i in range(400): | ||
| 50 | self.tracker.announce(bytes([i // 256, i % 256]) + b"\0" * 18, port=7000 + i, left=0) | ||
| 51 | |||
| 52 | c = self.tracker.connect() | ||
| 53 | try: | ||
| 54 | c.send("/scrape") | ||
| 55 | status, headers, body = c.reply() | ||
| 56 | self.assertIn(b"200", status) | ||
| 57 | self.assertGreater(len(body), 16384, "this reply has to outgrow one write") | ||
| 58 | |||
| 59 | c.send(self.announce_path("kaafter")) | ||
| 60 | status, _, after = c.reply() | ||
| 61 | self.assertIn(b"200", status) | ||
| 62 | self.assertIn(b"complete", bdecode(after)) | ||
| 63 | finally: | ||
| 64 | c.close() | ||
| 65 | |||
| 66 | def test_several_requests_in_a_row(self): | ||
| 67 | c = self.tracker.connect() | ||
| 68 | try: | ||
| 69 | for i in range(20): | ||
| 70 | c.send(self.announce_path("karow%d" % i)) | ||
| 71 | status, _, body = c.reply() | ||
| 72 | self.assertIn(b"200", status) | ||
| 73 | self.assertEqual(self.tracker.torrent_count(), 20) | ||
| 74 | finally: | ||
| 75 | c.close() | ||
| 76 | |||
| 77 | def test_without_the_header_the_connection_is_not_held(self): | ||
| 78 | """HTTP/1.1 calls a connection persistent unless told otherwise; this | ||
| 79 | tracker holds one only when asked by name. Pinned as it is.""" | ||
| 80 | c = self.tracker.connect() | ||
| 81 | try: | ||
| 82 | c.send(self.announce_path("kanone"), connection=None) | ||
| 83 | c.reply() | ||
| 84 | self.assertFalse(c.is_open()) | ||
| 85 | finally: | ||
| 86 | c.close() | ||
| 87 | |||
| 88 | def test_the_error_path_does_not_hold_the_connection(self): | ||
| 89 | c = self.tracker.connect() | ||
| 90 | try: | ||
| 91 | c.send("/announce?info_hash=short") | ||
| 92 | status, _, _ = c.reply() | ||
| 93 | self.assertIn(b"400", status) | ||
| 94 | finally: | ||
| 95 | c.close() | ||
| 96 | |||
| 97 | def test_an_error_after_a_kept_connection_is_still_an_error(self): | ||
| 98 | """The keep-alive decision used to be taken after the handler had run, | ||
| 99 | so an error reply inherited whatever the previous request wanted.""" | ||
| 100 | c = self.tracker.connect() | ||
| 101 | try: | ||
| 102 | c.send(self.announce_path("kabefore")) | ||
| 103 | self.assertIn(b"200", c.reply()[0]) | ||
| 104 | c.send("/announce?info_hash=short") | ||
| 105 | self.assertIn(b"400", c.reply()[0]) | ||
| 106 | finally: | ||
| 107 | c.close() | ||
| 108 | |||
| 109 | |||
| 110 | if __name__ == "__main__": | ||
| 111 | unittest.main() | ||
diff --git a/tests/integration/test_stats.py b/tests/integration/test_stats.py new file mode 100644 index 0000000..820b917 --- /dev/null +++ b/tests/integration/test_stats.py | |||
| @@ -0,0 +1,169 @@ | |||
| 1 | """The /stats endpoint. | ||
| 2 | |||
| 3 | Each mode is its own writer into a fixed buffer, so these pin the shape of | ||
| 4 | every one of them and, where the number means something, that it moves when | ||
| 5 | the thing it counts happens. | ||
| 6 | """ | ||
| 7 | |||
| 8 | import ipaddress | ||
| 9 | import re | ||
| 10 | import socket | ||
| 11 | import unittest | ||
| 12 | import urllib.error | ||
| 13 | import xml.etree.ElementTree | ||
| 14 | |||
| 15 | from harness import TrackerTestCase | ||
| 16 | |||
| 17 | # The modes a default build answers. "tpbs" and "statedump" are full scrapes | ||
| 18 | # and belong to test_fullscrape; "fulllog" and "woodpeckers" sit behind | ||
| 19 | # feature flags this build does not set. | ||
| 20 | MRTG_MODES = ["peer", "conn", "scrp", "udp4", "tcp4", "torr", "fscr", "completed", "syncs"] | ||
| 21 | TEXT_MODES = ["herr", "s24s", "top10", "top100", "renew", "version"] | ||
| 22 | |||
| 23 | |||
| 24 | class StatsShape(TrackerTestCase): | ||
| 25 | def test_every_mode_answers_something(self): | ||
| 26 | for mode in MRTG_MODES + TEXT_MODES + ["everything"]: | ||
| 27 | self.assertTrue(self.tracker.stats(mode), "mode %s answered empty" % mode) | ||
| 28 | |||
| 29 | def test_an_mrtg_mode_opens_with_two_numbers(self): | ||
| 30 | """MRTG reads the first two lines as counters and the rest as labels, | ||
| 31 | so the order matters to something outside this project.""" | ||
| 32 | for mode in MRTG_MODES: | ||
| 33 | lines = self.tracker.stats(mode).splitlines() | ||
| 34 | self.assertGreaterEqual(len(lines), 2, "mode %s" % mode) | ||
| 35 | for line in lines[:2]: | ||
| 36 | self.assertRegex(line, rb"^\d+$", "mode %s line %r" % (mode, line)) | ||
| 37 | |||
| 38 | def test_the_busy_mode_is_gone(self): | ||
| 39 | """It was listed in the mode table and implemented nowhere, so it only | ||
| 40 | ever answered 500. Removed rather than written: picking poisoning | ||
| 41 | networks out stopped being meaningful once consumer lines became bot | ||
| 42 | hosts and v6 made the address space too large to watch.""" | ||
| 43 | with self.assertRaises(urllib.error.HTTPError) as caught: | ||
| 44 | self.tracker.stats("busy") | ||
| 45 | self.assertEqual(caught.exception.code, 400, "an unknown mode, like any other") | ||
| 46 | |||
| 47 | def test_an_unknown_mode_is_refused(self): | ||
| 48 | with self.assertRaises(urllib.error.HTTPError) as caught: | ||
| 49 | self.tracker.stats("nosuchmode") | ||
| 50 | self.assertEqual(caught.exception.code, 400) | ||
| 51 | |||
| 52 | def test_everything_is_well_formed_xml(self): | ||
| 53 | root = xml.etree.ElementTree.fromstring(self.tracker.stats("everything").decode()) | ||
| 54 | self.assertEqual(root.tag, "stats") | ||
| 55 | self.assertIsNotNone(root.find("torrents/count_mutex")) | ||
| 56 | self.assertIsNotNone(root.find("connections/tcp/announce")) | ||
| 57 | |||
| 58 | def test_version_names_a_commit(self): | ||
| 59 | self.assertIn(b"opentracker", self.tracker.stats("version").lower() + b"opentracker") | ||
| 60 | self.assertRegex(self.tracker.stats("version"), rb"https?://") | ||
| 61 | |||
| 62 | |||
| 63 | class StatsCount(TrackerTestCase): | ||
| 64 | def test_the_torrent_count_follows_the_torrents(self): | ||
| 65 | before = self.tracker.torrent_count() | ||
| 66 | self.tracker.announce(self.hash_for("statA"), port=6001, left=0) | ||
| 67 | self.assertEqual(self.tracker.torrent_count(), before + 1) | ||
| 68 | self.tracker.announce(self.hash_for("statB"), port=6002, left=0) | ||
| 69 | self.assertEqual(self.tracker.torrent_count(), before + 2) | ||
| 70 | |||
| 71 | def test_the_peer_count_separates_seeders_from_the_rest(self): | ||
| 72 | self.tracker.announce(self.hash_for("statpeers"), port=6001, left=0) | ||
| 73 | self.tracker.announce(self.hash_for("statpeers"), port=6002, left=4096) | ||
| 74 | peers, seeds = self.tracker.stats("peer").splitlines()[:2] | ||
| 75 | self.assertEqual(int(peers), 2) | ||
| 76 | self.assertEqual(int(seeds), 1) | ||
| 77 | |||
| 78 | def test_the_completed_count_follows_the_completed_event(self): | ||
| 79 | before = int(self.tracker.stats("completed").splitlines()[0]) | ||
| 80 | self.tracker.announce(self.hash_for("statdone"), port=6001, left=0, event="completed") | ||
| 81 | self.assertEqual(int(self.tracker.stats("completed").splitlines()[0]), before + 1) | ||
| 82 | |||
| 83 | def test_a_bad_request_is_counted_as_an_http_error(self): | ||
| 84 | before = self.tracker.stats("herr") | ||
| 85 | try: | ||
| 86 | self.tracker.stats("nosuchmode") | ||
| 87 | except urllib.error.HTTPError: | ||
| 88 | pass | ||
| 89 | after = self.tracker.stats("herr") | ||
| 90 | self.assertNotEqual(before, after, "no error counter moved") | ||
| 91 | |||
| 92 | def test_the_tcp_counter_follows_tcp_requests(self): | ||
| 93 | before = int(self.tracker.stats("tcp4").splitlines()[0]) | ||
| 94 | for _ in range(3): | ||
| 95 | self.tracker.announce(self.hash_for("stattcp"), port=6001, left=0) | ||
| 96 | self.assertGreaterEqual(int(self.tracker.stats("tcp4").splitlines()[0]), before + 3) | ||
| 97 | |||
| 98 | def test_the_udp_counter_follows_udp_requests(self): | ||
| 99 | before = int(self.tracker.stats("udp4").splitlines()[0]) | ||
| 100 | sock, connection_id = self.tracker.udp_connect() | ||
| 101 | try: | ||
| 102 | self.tracker.udp_announce(sock, connection_id, self.hash_for("statudp"), left=0) | ||
| 103 | finally: | ||
| 104 | sock.close() | ||
| 105 | self.assertGreater(int(self.tracker.stats("udp4").splitlines()[0]), before) | ||
| 106 | |||
| 107 | def test_the_scrape_counter_follows_scrapes(self): | ||
| 108 | before = int(self.tracker.stats("scrp").splitlines()[0]) | ||
| 109 | self.tracker.scrape(self.hash_for("statscrape")) | ||
| 110 | self.assertEqual(int(self.tracker.stats("scrp").splitlines()[0]), before + 1) | ||
| 111 | |||
| 112 | |||
| 113 | class StatsTop(TrackerTestCase): | ||
| 114 | def test_the_top_list_ranks_by_peer_count(self): | ||
| 115 | busy = self.hash_for("topbusy") | ||
| 116 | quiet = self.hash_for("topquiet") | ||
| 117 | for port in range(6001, 6006): | ||
| 118 | self.tracker.announce(busy, port=port, left=0) | ||
| 119 | self.tracker.announce(quiet, port=6100, left=0) | ||
| 120 | |||
| 121 | body = self.tracker.stats("top10") | ||
| 122 | self.assertIn(b"Top 10 torrents by peers", body) | ||
| 123 | ranked = re.findall(rb"\t(\d+)\t([0-9A-F]{40})", body.split(b"by seeds")[0]) | ||
| 124 | self.assertEqual(ranked[0][1], busy.hex().upper().encode(), "the busy torrent ranks first") | ||
| 125 | self.assertEqual(int(ranked[0][0]), 5) | ||
| 126 | |||
| 127 | def test_the_top_list_has_three_sections(self): | ||
| 128 | self.tracker.announce(self.hash_for("topsections"), port=6001, left=0) | ||
| 129 | body = self.tracker.stats("top100") | ||
| 130 | for heading in (b"by peers", b"by seeds", b"by leechers"): | ||
| 131 | self.assertIn(heading, body) | ||
| 132 | |||
| 133 | |||
| 134 | class StatsNetworks(TrackerTestCase): | ||
| 135 | def source_address(self): | ||
| 136 | """Which address the tracker sees us from is not ours to choose: a | ||
| 137 | FreeBSD jail relocates a loopback connection to the jail's own | ||
| 138 | address, so ask the socket rather than assume 127.0.0.1.""" | ||
| 139 | probe = socket.create_connection(("127.0.0.1", self.tracker.port), timeout=5) | ||
| 140 | try: | ||
| 141 | return probe.getsockname()[0] | ||
| 142 | finally: | ||
| 143 | probe.close() | ||
| 144 | |||
| 145 | def test_the_slash24_report_names_the_announcing_network(self): | ||
| 146 | source = self.source_address() | ||
| 147 | self.tracker.announce(self.hash_for("s24"), port=6001, left=0) | ||
| 148 | body = self.tracker.stats("s24s") | ||
| 149 | self.assertIn(b"Networks, limit /28:", body) | ||
| 150 | self.assertIn(b"Networks, limit /24:", body) | ||
| 151 | |||
| 152 | # The prefix is the first three address bytes of a v4 peer, left | ||
| 153 | # aligned in a sixteen byte buffer and then printed by the v6 | ||
| 154 | # formatter, so 127.0.0.0/24 reads as "7f00::" rather than as the | ||
| 155 | # network an operator asked about. Pinned as it is, not blessed. | ||
| 156 | prefix = socket.inet_aton(source)[:3] + b"\0" * 13 | ||
| 157 | self.assertIn(str(ipaddress.IPv6Address(prefix)).encode(), body) | ||
| 158 | |||
| 159 | def test_the_report_counts_one_network_per_announcing_address(self): | ||
| 160 | for port in (6001, 6002, 6003): | ||
| 161 | self.tracker.announce(self.hash_for("s24count"), port=port, left=0) | ||
| 162 | lines = [line for line in self.tracker.stats("s24s").splitlines() if b":" in line and b"limit" not in line] | ||
| 163 | self.assertEqual(len(lines), 2, "one line under each of the two limits") | ||
| 164 | for line in lines: | ||
| 165 | self.assertEqual(int(line.split(b":")[0]), 3, "three peers from the one network") | ||
| 166 | |||
| 167 | |||
| 168 | if __name__ == "__main__": | ||
| 169 | unittest.main() | ||
diff --git a/tests/integration/test_udp.py b/tests/integration/test_udp.py new file mode 100644 index 0000000..1cb2389 --- /dev/null +++ b/tests/integration/test_udp.py | |||
| @@ -0,0 +1,168 @@ | |||
| 1 | """The UDP tracker protocol, BEP 15. | ||
| 2 | |||
| 3 | The HTTP tests cover the torrent store; these cover the packet handling in | ||
| 4 | front of it, which has its own framing, its own connection id and its own | ||
| 5 | rules about what to answer and what to ignore. | ||
| 6 | """ | ||
| 7 | |||
| 8 | import socket | ||
| 9 | import struct | ||
| 10 | import unittest | ||
| 11 | |||
| 12 | from harness import TrackerTestCase | ||
| 13 | |||
| 14 | MAGIC = 0x41727101980 | ||
| 15 | |||
| 16 | |||
| 17 | class UdpProtocol(TrackerTestCase): | ||
| 18 | def test_connect_echoes_the_transaction_id(self): | ||
| 19 | sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) | ||
| 20 | sock.settimeout(5) | ||
| 21 | try: | ||
| 22 | sock.sendto(struct.pack(">QII", MAGIC, 0, 0xDEADBEEF), ("127.0.0.1", self.tracker.port)) | ||
| 23 | action, transaction, connection_id = struct.unpack(">IIQ", sock.recv(2048)[:16]) | ||
| 24 | self.assertEqual(action, 0) | ||
| 25 | self.assertEqual(transaction, 0xDEADBEEF) | ||
| 26 | self.assertNotEqual(connection_id, 0) | ||
| 27 | finally: | ||
| 28 | sock.close() | ||
| 29 | |||
| 30 | def test_the_connection_id_is_stable_for_one_peer(self): | ||
| 31 | first, id_one = self.tracker.udp_connect() | ||
| 32 | second, id_two = self.tracker.udp_connect() | ||
| 33 | try: | ||
| 34 | self.assertEqual(id_one, id_two) | ||
| 35 | finally: | ||
| 36 | first.close() | ||
| 37 | second.close() | ||
| 38 | |||
| 39 | def test_a_wrong_connection_id_is_refused(self): | ||
| 40 | payload = struct.pack(">QII20s20sQQQIIIiH", 0, 1, 2, self.hash_for("udpbad"), b"p" * 20, 0, 0, 0, 0, 0, 0, -1, 6881) | ||
| 41 | answer = self.tracker.udp_raw(payload) | ||
| 42 | self.assertIsNotNone(answer, "expected an error packet") | ||
| 43 | action, transaction = struct.unpack(">II", answer[:8]) | ||
| 44 | self.assertEqual(action, 3, "action 3 is the error packet") | ||
| 45 | self.assertIn(b"Connection ID missmatch", answer[8:]) | ||
| 46 | |||
| 47 | def test_a_packet_shorter_than_the_header_is_ignored(self): | ||
| 48 | self.assertIsNone(self.tracker.udp_raw(b"\x00" * 15)) | ||
| 49 | |||
| 50 | def test_an_unknown_action_is_ignored(self): | ||
| 51 | self.assertIsNone(self.tracker.udp_raw(struct.pack(">QII", MAGIC, 9, 1))) | ||
| 52 | |||
| 53 | def test_connect_requires_the_protocol_magic(self): | ||
| 54 | self.assertIsNone(self.tracker.udp_raw(struct.pack(">QII", MAGIC + 1, 0, 1))) | ||
| 55 | |||
| 56 | def test_an_announce_cut_short_is_ignored(self): | ||
| 57 | sock, connection_id = self.tracker.udp_connect() | ||
| 58 | try: | ||
| 59 | self.assertIsNone(self.tracker.udp_raw(struct.pack(">QII", connection_id, 1, 1) + b"\0" * 40)) | ||
| 60 | finally: | ||
| 61 | sock.close() | ||
| 62 | |||
| 63 | |||
| 64 | class UdpAnnounce(TrackerTestCase): | ||
| 65 | def test_a_seeder_is_counted_as_a_seeder(self): | ||
| 66 | sock, connection_id = self.tracker.udp_connect() | ||
| 67 | try: | ||
| 68 | answer = self.tracker.udp_announce(sock, connection_id, self.hash_for("udpseed"), left=0) | ||
| 69 | self.assertEqual(answer["seeders"], 1) | ||
| 70 | self.assertEqual(answer["leechers"], 0) | ||
| 71 | self.assertGreater(answer["interval"], 0) | ||
| 72 | finally: | ||
| 73 | sock.close() | ||
| 74 | |||
| 75 | def test_a_leecher_is_counted_as_a_leecher(self): | ||
| 76 | sock, connection_id = self.tracker.udp_connect() | ||
| 77 | try: | ||
| 78 | answer = self.tracker.udp_announce(sock, connection_id, self.hash_for("udpleech"), left=1024) | ||
| 79 | self.assertEqual(answer["seeders"], 0) | ||
| 80 | self.assertEqual(answer["leechers"], 1) | ||
| 81 | finally: | ||
| 82 | sock.close() | ||
| 83 | |||
| 84 | def test_stopped_removes_the_peer(self): | ||
| 85 | info_hash = self.hash_for("udpstop") | ||
| 86 | sock, connection_id = self.tracker.udp_connect() | ||
| 87 | try: | ||
| 88 | self.tracker.udp_announce(sock, connection_id, info_hash, left=0) | ||
| 89 | self.tracker.udp_announce(sock, connection_id, info_hash, left=0, event=3) | ||
| 90 | answer = self.tracker.udp_announce(sock, connection_id, info_hash, left=1024) | ||
| 91 | self.assertEqual(answer["seeders"], 0, "the seeder announced stopped") | ||
| 92 | finally: | ||
| 93 | sock.close() | ||
| 94 | |||
| 95 | def test_an_announce_over_udp_is_visible_over_http(self): | ||
| 96 | """One torrent store behind both bearers, not two.""" | ||
| 97 | info_hash = self.hash_for("udpcross") | ||
| 98 | sock, connection_id = self.tracker.udp_connect() | ||
| 99 | try: | ||
| 100 | self.tracker.udp_announce(sock, connection_id, info_hash, left=0) | ||
| 101 | finally: | ||
| 102 | sock.close() | ||
| 103 | scrape = self.tracker.scrape(info_hash) | ||
| 104 | self.assertEqual(scrape[b"files"][info_hash][b"complete"], 1) | ||
| 105 | |||
| 106 | def test_the_peer_list_carries_the_announcing_peer(self): | ||
| 107 | info_hash = self.hash_for("udppeers") | ||
| 108 | sock, connection_id = self.tracker.udp_connect() | ||
| 109 | try: | ||
| 110 | answer = self.tracker.udp_announce(sock, connection_id, info_hash, left=0, port=6881) | ||
| 111 | self.assertEqual(len(answer["peers"]) % 6, 0, "v4 peers are six bytes each") | ||
| 112 | self.assertGreaterEqual(len(answer["peers"]), 6) | ||
| 113 | self.assertEqual(struct.unpack(">H", answer["peers"][4:6])[0], 6881) | ||
| 114 | finally: | ||
| 115 | sock.close() | ||
| 116 | |||
| 117 | |||
| 118 | class UdpScrape(TrackerTestCase): | ||
| 119 | def test_scrape_reports_the_swarm(self): | ||
| 120 | info_hash = self.hash_for("udpscrape") | ||
| 121 | sock, connection_id = self.tracker.udp_connect() | ||
| 122 | try: | ||
| 123 | self.tracker.udp_announce(sock, connection_id, info_hash, left=0) | ||
| 124 | seeders, completed, leechers = self.tracker.udp_scrape(sock, connection_id, [info_hash])[0] | ||
| 125 | self.assertEqual(seeders, 1) | ||
| 126 | self.assertEqual(leechers, 0) | ||
| 127 | self.assertEqual(completed, 0) | ||
| 128 | finally: | ||
| 129 | sock.close() | ||
| 130 | |||
| 131 | def test_an_unknown_hash_scrapes_as_empty(self): | ||
| 132 | sock, connection_id = self.tracker.udp_connect() | ||
| 133 | try: | ||
| 134 | self.assertEqual(self.tracker.udp_scrape(sock, connection_id, [self.hash_for("udpnone")])[0], (0, 0, 0)) | ||
| 135 | finally: | ||
| 136 | sock.close() | ||
| 137 | |||
| 138 | def test_several_hashes_answer_in_order(self): | ||
| 139 | seeding = self.hash_for("udpmultiA") | ||
| 140 | leeching = self.hash_for("udpmultiB") | ||
| 141 | sock, connection_id = self.tracker.udp_connect() | ||
| 142 | try: | ||
| 143 | self.tracker.udp_announce(sock, connection_id, seeding, left=0) | ||
| 144 | self.tracker.udp_announce(sock, connection_id, leeching, left=1024) | ||
| 145 | answers = self.tracker.udp_scrape(sock, connection_id, [seeding, leeching]) | ||
| 146 | self.assertEqual(answers[0][0], 1, "first hash is the seeded one") | ||
| 147 | self.assertEqual(answers[1][2], 1, "second hash is the leeched one") | ||
| 148 | finally: | ||
| 149 | sock.close() | ||
| 150 | |||
| 151 | |||
| 152 | class UdpWorkersConfiguredAfterTheListener(TrackerTestCase): | ||
| 153 | """The harness writes its listen lines first, so this directive lands | ||
| 154 | below them: the position a config file should not care about.""" | ||
| 155 | |||
| 156 | config = "listen.udp.workers 4\n" | ||
| 157 | |||
| 158 | def test_the_tracker_starts_and_still_answers_udp(self): | ||
| 159 | sock, connection_id = self.tracker.udp_connect() | ||
| 160 | try: | ||
| 161 | answer = self.tracker.udp_announce(sock, connection_id, self.hash_for("udpworkers"), left=0) | ||
| 162 | self.assertEqual(answer["seeders"], 1) | ||
| 163 | finally: | ||
| 164 | sock.close() | ||
| 165 | |||
| 166 | |||
| 167 | if __name__ == "__main__": | ||
| 168 | unittest.main() | ||
diff --git a/tests/runner.c b/tests/runner.c index a92315e..71a5e2a 100644 --- a/tests/runner.c +++ b/tests/runner.c | |||
| @@ -4,7 +4,11 @@ | |||
| 4 | $id$ */ | 4 | $id$ */ |
| 5 | 5 | ||
| 6 | /* System */ | 6 | /* System */ |
| 7 | #include <stdio.h> | ||
| 8 | #include <stdlib.h> | ||
| 7 | #include <string.h> | 9 | #include <string.h> |
| 10 | #include <sys/wait.h> | ||
| 11 | #include <unistd.h> | ||
| 8 | 12 | ||
| 9 | /* Opentracker */ | 13 | /* Opentracker */ |
| 10 | #include "test.h" | 14 | #include "test.h" |
| @@ -31,15 +35,79 @@ static const struct module modules[] = {{"ot_urlencoded", test_urlencoded}, | |||
| 31 | {"ot_accesslist", test_accesslist}, | 35 | {"ot_accesslist", test_accesslist}, |
| 32 | {NULL, NULL}}; | 36 | {NULL, NULL}}; |
| 33 | 37 | ||
| 34 | /* Run every module, or only those whose name contains argv[1] */ | 38 | struct tally { |
| 39 | unsigned long checks; | ||
| 40 | unsigned long failures; | ||
| 41 | }; | ||
| 42 | |||
| 43 | /* Each module runs in a child of its own, so that a crash or a sanitizer | ||
| 44 | abort costs that module's results rather than every module after it. The | ||
| 45 | child reports its tally through a pipe; one that dies without reporting is | ||
| 46 | counted as a failure under its own name. */ | ||
| 47 | static void run_forked(const struct module *m) { | ||
| 48 | struct tally tally = {0, 0}; | ||
| 49 | int pipefd[2], status = 0; | ||
| 50 | pid_t child; | ||
| 51 | ssize_t got; | ||
| 52 | |||
| 53 | if (pipe(pipefd)) { | ||
| 54 | test_failf(__FILE__, __LINE__, "pipe failed, cannot isolate %s", m->name); | ||
| 55 | return; | ||
| 56 | } | ||
| 57 | |||
| 58 | fflush(stdout); /* or the child inherits a copy and prints it again */ | ||
| 59 | child = fork(); | ||
| 60 | if (child < 0) { | ||
| 61 | close(pipefd[0]); | ||
| 62 | close(pipefd[1]); | ||
| 63 | test_failf(__FILE__, __LINE__, "fork failed, cannot isolate %s", m->name); | ||
| 64 | return; | ||
| 65 | } | ||
| 66 | |||
| 67 | if (!child) { | ||
| 68 | close(pipefd[0]); | ||
| 69 | test_checks = test_failures = 0; | ||
| 70 | m->run(); | ||
| 71 | tally.checks = test_checks; | ||
| 72 | tally.failures = test_failures; | ||
| 73 | if (write(pipefd[1], &tally, sizeof(tally)) != (ssize_t)sizeof(tally)) | ||
| 74 | _exit(1); | ||
| 75 | fflush(stdout); | ||
| 76 | _exit(0); | ||
| 77 | } | ||
| 78 | |||
| 79 | close(pipefd[1]); | ||
| 80 | got = read(pipefd[0], &tally, sizeof(tally)); | ||
| 81 | close(pipefd[0]); | ||
| 82 | while (waitpid(child, &status, 0) < 0) | ||
| 83 | ; | ||
| 84 | |||
| 85 | if (got == (ssize_t)sizeof(tally)) { | ||
| 86 | test_checks += tally.checks; | ||
| 87 | test_failures += tally.failures; | ||
| 88 | } | ||
| 89 | if (got != (ssize_t)sizeof(tally) || !WIFEXITED(status) || WEXITSTATUS(status)) | ||
| 90 | test_failf(__FILE__, __LINE__, "%s did not run to the end", m->name); | ||
| 91 | } | ||
| 92 | |||
| 93 | /* Run every module, or only those whose name contains argv[1]. | ||
| 94 | OT_TEST_FORK=0 keeps everything in one process, which is what a debugger | ||
| 95 | wants. */ | ||
| 35 | int main(int argc, char **argv) { | 96 | int main(int argc, char **argv) { |
| 97 | const char *fork_setting = getenv("OT_TEST_FORK"); | ||
| 98 | int isolate = !fork_setting || strcmp(fork_setting, "0"); | ||
| 36 | const struct module *m; | 99 | const struct module *m; |
| 37 | 100 | ||
| 38 | for (m = modules; m->name; ++m) { | 101 | for (m = modules; m->name; ++m) { |
| 39 | if (argc > 1 && !strstr(m->name, argv[1])) | 102 | if (argc > 1 && !strstr(m->name, argv[1])) |
| 40 | continue; | 103 | continue; |
| 41 | test_module(m->name); | 104 | test_module(m->name); |
| 42 | m->run(); | 105 | if (!isolate) { |
| 106 | m->run(); | ||
| 107 | continue; | ||
| 108 | } | ||
| 109 | test_case("the module runs to the end"); | ||
| 110 | run_forked(m); | ||
| 43 | } | 111 | } |
| 44 | 112 | ||
| 45 | return test_summary(); | 113 | return test_summary(); |
