summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--DESIGN17
-rw-r--r--src/opentracker.c22
-rw-r--r--src/ot_accesslist.c3
-rw-r--r--src/ot_config.c6
-rw-r--r--src/ot_event.c9
-rw-r--r--src/ot_fdstate.c12
-rw-r--r--src/ot_fdstate.h8
-rw-r--r--src/ot_fullscrape.c12
-rw-r--r--src/ot_http.c11
-rw-r--r--src/ot_socket.c14
-rw-r--r--src/ot_socket.h2
-rw-r--r--src/ot_stats.c2
-rw-r--r--src/ot_tcp.c12
-rw-r--r--src/ot_udp.c176
-rw-r--r--src/ot_workqueue.c35
-rw-r--r--src/ot_workqueue.h2
-rw-r--r--src/trackerlogic.c45
-rw-r--r--src/trackerlogic.h12
-rw-r--r--tests/integration/test_announce.py15
-rw-r--r--tests/integration/test_udp.py52
-rw-r--r--tests/t_socket.c19
-rw-r--r--tests/t_workqueue.c52
22 files changed, 402 insertions, 136 deletions
diff --git a/DESIGN b/DESIGN
index 480aa9b..7933223 100644
--- a/DESIGN
+++ b/DESIGN
@@ -57,6 +57,13 @@ A socket is read or written, never both. http_interest_set replaces an
57add-and-drop pair so that the invariant cannot be broken by accident, and the 57add-and-drop pair so that the invariant cannot be broken by accident, and the
58event layer hears about a change once instead of twice. 58event layer hears about a change once instead of twice.
59 59
60A task belongs to a connection, not to a descriptor number. The queue files
61it under the number, and the kernel hands that number to the next connection
62the moment this one closes. So a connection that is owed an answer is not
63read from, closing it cancels every task filed under its number, and a result
64carries the generation the descriptor had when the task was pushed, which the
65main loop holds against the current one before it sends anything.
66
60Accept waits until the client's request has arrived: TCP_DEFER_ACCEPT on 67Accept waits until the client's request has arrived: TCP_DEFER_ACCEPT on
61Linux, the accf_data filter on FreeBSD. Measured against a flood of silent 68Linux, the accf_data filter on FreeBSD. Measured against a flood of silent
62connections, the filter serves more requests than no filter, not fewer, so it 69connections, the filter serves more requests than no filter, not fewer, so it
@@ -207,6 +214,16 @@ packet arriving in that window created the torrent, and the saved state for it
207was then dropped on the exactmatch add_torrent_from_saved_state bails on, 214was then dropped on the exactmatch add_torrent_from_saved_state bails on,
208losing that torrent's completed count. 215losing that torrent's completed count.
209 216
217A udp address somebody else holds is warned about and bound all the same.
218Linux permits the second bind when both sockets set SO_REUSEADDR, which the
219tracker always does, and FreeBSD when both asked to share the port, which it
220does for a group of workers. The two then take or split each other's datagrams
221without either noticing. Every udp entry is probed before the first of them is
222bound, with a socket that asks for no sharing, so that an overlap within the
223tracker's own configuration is not mistaken for a stranger. TCP is not probed:
224there the bind itself fails unless a balanced group was asked for, and on
225Linux a probe would also trip over the connections a restart leaves behind.
226
210Teardown stops the cleaner first. It is the one worker that calls into other 227Teardown stops the cleaner first. It is the one worker that calls into other
211modules, accesslist_cleanup and stats_cleanup, so stopping it after them left 228modules, accesslist_cleanup and stats_cleanup, so stopping it after them left
212it locking a mutex accesslist_deinit had already destroyed: five shutdowns in 229it locking a mutex accesslist_deinit had already destroyed: five shutdowns in
diff --git a/src/opentracker.c b/src/opentracker.c
index 759a6d0..81b4df6 100644
--- a/src/opentracker.c
+++ b/src/opentracker.c
@@ -25,6 +25,7 @@
25#include "ot_config.h" 25#include "ot_config.h"
26#include "ot_hex.h" 26#include "ot_hex.h"
27#include "ot_http.h" 27#include "ot_http.h"
28#include "ot_iovec.h"
28#include "ot_ip.h" 29#include "ot_ip.h"
29#include "ot_livesync.h" 30#include "ot_livesync.h"
30#include "ot_mutex.h" 31#include "ot_mutex.h"
@@ -107,6 +108,7 @@ static void *server_mainloop(void *args) {
107 struct iovec *iovector; 108 struct iovec *iovector;
108 size_t iovec_entries; 109 size_t iovec_entries;
109 int is_partial; 110 int is_partial;
111 uint32_t generation;
110 112
111 (void)args; 113 (void)args;
112 114
@@ -149,8 +151,13 @@ static void *server_mainloop(void *args) {
149 } 151 }
150 } 152 }
151 153
152 while ((sock = workqueue_popresult(&iovec_entries, &iovector, &is_partial)) != -1) 154 while ((sock = workqueue_popresult(&iovec_entries, &iovector, &is_partial, &generation)) != -1) {
155 if (fdstate_generation((int)sock) != generation) {
156 iovec_free(&iovec_entries, &iovector);
157 continue;
158 }
153 http_sendiovecdata(sock, &ws, iovec_entries, iovector, is_partial); 159 http_sendiovecdata(sock, &ws, iovec_entries, iovector, is_partial);
160 }
154 161
155 if (time_is_past(next_timeout_check)) { 162 if (time_is_past(next_timeout_check)) {
156 int cursor = 0; 163 int cursor = 0;
@@ -220,6 +227,16 @@ static void listen_bind_one(ot_listen *entry) {
220#endif 227#endif
221} 228}
222 229
230static void listen_warn_if_taken(const ot_listen *entry) {
231 char address[64];
232
233 if (entry->proto != FLAG_UDP || !socket_udp_is_taken(entry->ip, entry->port))
234 return;
235
236 address[ip_format(address, entry->ip)] = 0;
237 fprintf(stderr, "Warning: udp address [%s]:%d is already in use, by another tracker instance perhaps.\n", address, entry->port);
238}
239
223/* Bound in the order the entries were given. 240/* Bound in the order the entries were given.
224 Note: On macOS SO_REUSEPORT delivers everything to the socket that bound last. */ 241 Note: On macOS SO_REUSEPORT delivers everything to the socket that bound last. */
225static void listen_bind_all(void) { 242static void listen_bind_all(void) {
@@ -227,6 +244,9 @@ static void listen_bind_all(void) {
227 ot_listen *entries = config_listen_entries(&count); 244 ot_listen *entries = config_listen_entries(&count);
228 245
229 for (i = 0; i < count; ++i) 246 for (i = 0; i < count; ++i)
247 listen_warn_if_taken(entries + i);
248
249 for (i = 0; i < count; ++i)
230 listen_bind_one(entries + i); 250 listen_bind_one(entries + i);
231} 251}
232 252
diff --git a/src/ot_accesslist.c b/src/ot_accesslist.c
index fdf631e..5d4f059 100644
--- a/src/ot_accesslist.c
+++ b/src/ot_accesslist.c
@@ -281,8 +281,7 @@ static void *accesslist_adddel_worker(const char *fifoname, ot_accesslist *_
281 return NULL; 281 return NULL;
282 } 282 }
283 } else { 283 } else {
284 int error = mkfifo(fifoname, 0755); 284 if (mkfifo(fifoname, 0600) && errno != EEXIST) {
285 if (error && error != EEXIST) {
286 fprintf(stderr, "Error when starting dynamic accesslists: Couldn't create FIFO at %s, error: %s\n", fifoname, strerror(errno)); 285 fprintf(stderr, "Error when starting dynamic accesslists: Couldn't create FIFO at %s, error: %s\n", fifoname, strerror(errno));
287 return NULL; 286 return NULL;
288 } 287 }
diff --git a/src/ot_config.c b/src/ot_config.c
index a4c2a47..e689314 100644
--- a/src/ot_config.c
+++ b/src/ot_config.c
@@ -485,10 +485,10 @@ static void listen_resolve_defaults(void) {
485 /* A tcp worker hands a connection it cannot finish to the event loop, 485 /* A tcp worker hands a connection it cannot finish to the event loop,
486 which only one thread may touch where the set is ours rather than the 486 which only one thread may touch where the set is ours rather than the
487 kernel's */ 487 kernel's */
488 if (entry->proto == FLAG_TCP && entry->workers > 1 && !event_can_share()) { 488 if (entry->proto == FLAG_TCP && entry->workers > 0 && !event_can_share()) {
489 fprintf(stderr, "Warning: Multiple workers impossible on this platform with event mechanism %s chosen.\n", 489 fprintf(stderr, "Warning: tcp workers impossible on this platform with event mechanism %s chosen.\n",
490 event_mechanism()); 490 event_mechanism());
491 entry->workers = 1; 491 entry->workers = 0;
492 } 492 }
493 } 493 }
494} 494}
diff --git a/src/ot_event.c b/src/ot_event.c
index 6062f70..cc575f6 100644
--- a/src/ot_event.c
+++ b/src/ot_event.c
@@ -143,7 +143,7 @@ void event_deinit(void) {
143 back untouched. */ 143 back untouched. */
144static int event_change(int fd, int what, uint32_t generation, int deleting) { 144static int event_change(int fd, int what, uint32_t generation, int deleting) {
145 struct kevent change[2], result[2]; 145 struct kevent change[2], result[2];
146 void *udata = (void *)(uintptr_t)(((uint64_t)generation << 32) | (uint32_t)fd); 146 void *udata = (void *)(uintptr_t)generation;
147 int succeeded = 0, count, i; 147 int succeeded = 0, count, i;
148 148
149 EV_SET(&change[0], (uintptr_t)fd, EVFILT_READ, 149 EV_SET(&change[0], (uintptr_t)fd, EVFILT_READ,
@@ -206,11 +206,10 @@ int event_wait(ot_event *out, int max, int timeout_ms) {
206 if ((count = kevent(g_kqueue, NULL, 0, g_ready, max, deadline)) == -1) 206 if ((count = kevent(g_kqueue, NULL, 0, g_ready, max, deadline)) == -1)
207 return errno == EINTR ? 0 : -1; 207 return errno == EINTR ? 0 : -1;
208 for (i = 0; i < count; ++i) { 208 for (i = 0; i < count; ++i) {
209 uint64_t udata = (uint64_t)(uintptr_t)g_ready[i].udata; 209 int eof = (g_ready[i].flags & (EV_EOF | EV_ERROR)) != 0;
210 int eof = (g_ready[i].flags & (EV_EOF | EV_ERROR)) != 0;
211 210
212 out[i].fd = (int)(uint32_t)udata; 211 out[i].fd = (int)g_ready[i].ident;
213 out[i].generation = (uint32_t)(udata >> 32); 212 out[i].generation = (uint32_t)(uintptr_t)g_ready[i].udata;
214 out[i].what = ((g_ready[i].filter == EVFILT_READ || eof) ? EVENT_IN : 0) | 213 out[i].what = ((g_ready[i].filter == EVFILT_READ || eof) ? EVENT_IN : 0) |
215 ((g_ready[i].filter == EVFILT_WRITE || eof) ? EVENT_OUT : 0); 214 ((g_ready[i].filter == EVFILT_WRITE || eof) ? EVENT_OUT : 0);
216 } 215 }
diff --git a/src/ot_fdstate.c b/src/ot_fdstate.c
index 8e4bd89..bbb25d2 100644
--- a/src/ot_fdstate.c
+++ b/src/ot_fdstate.c
@@ -24,7 +24,7 @@ enum { FD_FREE, FD_IDLE, FD_BUSY, FD_CLOSING };
24typedef struct { 24typedef struct {
25 _Atomic uint64_t state; 25 _Atomic uint64_t state;
26 _Atomic(void *) cookie; 26 _Atomic(void *) cookie;
27 _Atomic ot_time expiry; 27 _Atomic unsigned long expiry;
28} ot_fdslot; 28} ot_fdslot;
29 29
30/* A descriptor the kernel can hand out is below the limit it was handed out 30/* A descriptor the kernel can hand out is below the limit it was handed out
@@ -72,7 +72,7 @@ static ot_fdslot *fdstate_slot(int fd) {
72 return g_slots + fd; 72 return g_slots + fd;
73} 73}
74 74
75uint32_t fdstate_open(int fd, void *cookie, ot_time expiry) { 75uint32_t fdstate_open(int fd, void *cookie, unsigned long expiry) {
76 ot_fdslot *slot = fdstate_slot(fd); 76 ot_fdslot *slot = fdstate_slot(fd);
77 uint64_t word; 77 uint64_t word;
78 78
@@ -132,10 +132,10 @@ void fdstate_release(int fd) {
132 atomic_store_explicit(&slot->state, FD_SET_ST(word, FD_IDLE), memory_order_release); 132 atomic_store_explicit(&slot->state, FD_SET_ST(word, FD_IDLE), memory_order_release);
133} 133}
134 134
135int fdstate_claim_expired(int fd, ot_time now) { 135int fdstate_claim_expired(int fd, unsigned long now) {
136 ot_fdslot *slot = fdstate_slot(fd); 136 ot_fdslot *slot = fdstate_slot(fd);
137 uint64_t word; 137 uint64_t word;
138 ot_time expiry; 138 unsigned long expiry;
139 139
140 if (!slot) 140 if (!slot)
141 return 0; 141 return 0;
@@ -168,7 +168,7 @@ void fdstate_close(int fd) {
168 atomic_store_explicit(&slot->state, FD_WORD(FD_GEN(word) + 1, FD_FREE), memory_order_release); 168 atomic_store_explicit(&slot->state, FD_WORD(FD_GEN(word) + 1, FD_FREE), memory_order_release);
169} 169}
170 170
171int fdstate_next_expired(ot_time now, int *cursor) { 171int fdstate_next_expired(unsigned long now, int *cursor) {
172 size_t highest = atomic_load_explicit(&g_slot_highest, memory_order_relaxed); 172 size_t highest = atomic_load_explicit(&g_slot_highest, memory_order_relaxed);
173 173
174 for (; (size_t)*cursor <= highest; ++*cursor) 174 for (; (size_t)*cursor <= highest; ++*cursor)
@@ -194,7 +194,7 @@ void fdstate_set_cookie(int fd, void *cookie) {
194 atomic_store_explicit(&slot->cookie, cookie, memory_order_release); 194 atomic_store_explicit(&slot->cookie, cookie, memory_order_release);
195} 195}
196 196
197void fdstate_set_expiry(int fd, ot_time expiry) { 197void fdstate_set_expiry(int fd, unsigned long expiry) {
198 ot_fdslot *slot = fdstate_slot(fd); 198 ot_fdslot *slot = fdstate_slot(fd);
199 199
200 if (slot) 200 if (slot)
diff --git a/src/ot_fdstate.h b/src/ot_fdstate.h
index 60fe070..20f469d 100644
--- a/src/ot_fdstate.h
+++ b/src/ot_fdstate.h
@@ -27,7 +27,7 @@ size_t fdstate_slots(void);
27 27
28/* Take a freshly accepted descriptor into the table and return the 28/* Take a freshly accepted descriptor into the table and return the
29 generation to quote when asking for it back. expiry of 0 never expires. */ 29 generation to quote when asking for it back. expiry of 0 never expires. */
30uint32_t fdstate_open(int fd, void *cookie, ot_time expiry); 30uint32_t fdstate_open(int fd, void *cookie, unsigned long expiry);
31 31
32/* Which generation a descriptor currently carries, to check an event that 32/* Which generation a descriptor currently carries, to check an event that
33 was handed out earlier against the connection living there now. */ 33 was handed out earlier against the connection living there now. */
@@ -40,7 +40,7 @@ void fdstate_release(int fd);
40 40
41/* The cleaner's side of the same thing: takes the descriptor only if nobody 41/* The cleaner's side of the same thing: takes the descriptor only if nobody
42 is working on it and it really has expired. Never waits. */ 42 is working on it and it really has expired. Never waits. */
43int fdstate_claim_expired(int fd, ot_time now); 43int fdstate_claim_expired(int fd, unsigned long now);
44 44
45/* Give the descriptor up. The generation is bumped here, which has to happen 45/* Give the descriptor up. The generation is bumped here, which has to happen
46 before close(2) so that the kernel cannot reissue the number while events 46 before close(2) so that the kernel cannot reissue the number while events
@@ -50,13 +50,13 @@ void fdstate_close(int fd);
50/* Walks the table for descriptors that have expired, handing back one at a 50/* Walks the table for descriptors that have expired, handing back one at a
51 time until it returns -1. The cursor belongs to the caller, so several 51 time until it returns -1. The cursor belongs to the caller, so several
52 sweepers can run without sharing anything. */ 52 sweepers can run without sharing anything. */
53int fdstate_next_expired(ot_time now, int *cursor); 53int fdstate_next_expired(unsigned long now, int *cursor);
54 54
55/* Both only valid while the caller holds the descriptor. */ 55/* Both only valid while the caller holds the descriptor. */
56void *fdstate_cookie(int fd); 56void *fdstate_cookie(int fd);
57 57
58/* Hand the slot a different cookie, for a connection whose state has moved */ 58/* Hand the slot a different cookie, for a connection whose state has moved */
59void fdstate_set_cookie(int fd, void *cookie); 59void fdstate_set_cookie(int fd, void *cookie);
60void fdstate_set_expiry(int fd, ot_time expiry); 60void fdstate_set_expiry(int fd, unsigned long expiry);
61 61
62#endif 62#endif
diff --git a/src/ot_fullscrape.c b/src/ot_fullscrape.c
index 0cd1910..00c08e0 100644
--- a/src/ot_fullscrape.c
+++ b/src/ot_fullscrape.c
@@ -121,9 +121,8 @@ static void fullscrape_write_one( ot_tasktype mode, char **cursor, ot_torrent *t
121 case TASK_FULLSCRAPE_TPB_BINARY: 121 case TASK_FULLSCRAPE_TPB_BINARY:
122 memcpy(r, *hash, sizeof(ot_hash)); 122 memcpy(r, *hash, sizeof(ot_hash));
123 r += sizeof(ot_hash); 123 r += sizeof(ot_hash);
124 *(uint32_t *)(r + 0) = htonl((uint32_t)seed_count); 124 pack_uint32(&r, (uint32_t)seed_count);
125 *(uint32_t *)(r + 4) = htonl((uint32_t)(peer_count - seed_count)); 125 pack_uint32(&r, (uint32_t)(peer_count - seed_count));
126 r += 8;
127 break; 126 break;
128 case TASK_FULLSCRAPE_TPB_URLENCODED: 127 case TASK_FULLSCRAPE_TPB_URLENCODED:
129 r += urlencoded_format(r, *hash, sizeof(ot_hash)); 128 r += urlencoded_format(r, *hash, sizeof(ot_hash));
@@ -382,7 +381,7 @@ static void fullscrape_make_zstd(int taskid, ot_tasktype mode) {
382 381
383 /* Check if there still is enough buffer left */ 382 /* Check if there still is enough buffer left */
384 while (outbuf.pos + OT_SCRAPE_MAXENTRYLEN > outbuf.size) { 383 while (outbuf.pos + OT_SCRAPE_MAXENTRYLEN > outbuf.size) {
385 iovector.iov_len = outbuf.size; 384 iovector.iov_len = outbuf.pos;
386 385
387 if (workqueue_pushchunked(taskid, &iovector)) { 386 if (workqueue_pushchunked(taskid, &iovector)) {
388 free(iovector.iov_base); 387 free(iovector.iov_base);
@@ -420,6 +419,11 @@ static void fullscrape_make_zstd(int taskid, ot_tasktype mode) {
420 inbuf.src = (const void *)"ee"; 419 inbuf.src = (const void *)"ee";
421 inbuf.size = strlen("ee"); 420 inbuf.size = strlen("ee");
422 inbuf.pos = 0; 421 inbuf.pos = 0;
422 } else {
423 /* Nothing more to feed, and with no torrent written nothing was set */
424 inbuf.src = (const void *)"";
425 inbuf.size = 0;
426 inbuf.pos = 0;
423 } 427 }
424 428
425 more_bytes = ZSTD_compressStream2(zstream, &outbuf, &inbuf, ZSTD_e_end); 429 more_bytes = ZSTD_compressStream2(zstream, &outbuf, &inbuf, ZSTD_e_end);
diff --git a/src/ot_http.c b/src/ot_http.c
index 70176c3..2e21546 100644
--- a/src/ot_http.c
+++ b/src/ot_http.c
@@ -141,9 +141,9 @@ static void http_senddata(const int64_t sock, struct ot_workstruct *ws) {
141 141
142 batch_add(cookie->batch, outbuf, ws->reply_size - written_size); 142 batch_add(cookie->batch, outbuf, ws->reply_size - written_size);
143 143
144 /* writeable short data sockets just have a tcp timeout */ 144 /* Reset any connections potentially near their timeout */
145 if (!ws->keep_alive) 145 if (!ws->keep_alive)
146 fdstate_set_expiry(sock, 0); 146 fdstate_set_expiry(sock, time_future_seconds(OT_CLIENT_TIMEOUT_SEND));
147 http_interest_set(sock, cookie, EVENT_OUT); 147 http_interest_set(sock, cookie, EVENT_OUT);
148 } 148 }
149} 149}
@@ -536,7 +536,7 @@ static ssize_t http_handle_scrape(const int64_t sock, struct ot_workstruct *ws,
536 qsort(multiscrape_buf, numwant, sizeof(ot_hash), compare_hash); 536 qsort(multiscrape_buf, numwant, sizeof(ot_hash), compare_hash);
537 for (i = unique = 1; i < numwant; ++i) 537 for (i = unique = 1; i < numwant; ++i)
538 if (memcmp(multiscrape_buf[i], multiscrape_buf[unique - 1], sizeof(ot_hash))) 538 if (memcmp(multiscrape_buf[i], multiscrape_buf[unique - 1], sizeof(ot_hash)))
539 memcpy(multiscrape_buf[unique++], multiscrape_buf[i], sizeof(ot_hash)); 539 memmove(multiscrape_buf[unique++], multiscrape_buf[i], sizeof(ot_hash));
540 numwant = unique; 540 numwant = unique;
541 541
542 /* Enough for http header + whole scrape string */ 542 /* Enough for http header + whole scrape string */
@@ -634,7 +634,7 @@ static ssize_t http_handle_announce(const int64_t sock, struct ot_workstruct
634 break; 634 break;
635 case 1: /* matched "port" */ 635 case 1: /* matched "port" */
636 len = urlencoded_parse(&read_ptr, write_ptr = read_ptr, ws->request + ws->request_size, SCAN_SEARCHPATH_VALUE); 636 len = urlencoded_parse(&read_ptr, write_ptr = read_ptr, ws->request + ws->request_size, SCAN_SEARCHPATH_VALUE);
637 if ((len <= 0) || scan_int(write_ptr, len, &tmp) || (tmp > 0xffff)) 637 if ((len <= 0) || scan_int(write_ptr, len, &tmp) || (tmp < 0) || (tmp > 0xffff))
638 HTTPERROR_400_PARAM; 638 HTTPERROR_400_PARAM;
639 port = htons((uint16_t)tmp); 639 port = htons((uint16_t)tmp);
640 OT_SETPORT(&ws->peer, &port); 640 OT_SETPORT(&ws->peer, &port);
@@ -690,7 +690,8 @@ static ssize_t http_handle_announce(const int64_t sock, struct ot_workstruct
690 case 7: /* matched "ip" */ 690 case 7: /* matched "ip" */
691 { 691 {
692 char *tmp_buf1 = ws->reply, *tmp_buf2 = ws->reply + 16; 692 char *tmp_buf1 = ws->reply, *tmp_buf2 = ws->reply + 16;
693 len = urlencoded_parse(&read_ptr, tmp_buf2, ws->outbuf + G_OUTBUF_SIZE, SCAN_SEARCHPATH_VALUE); 693 /* One short of the end, for the terminator below */
694 len = urlencoded_parse(&read_ptr, tmp_buf2, ws->outbuf + G_OUTBUF_SIZE - 1, SCAN_SEARCHPATH_VALUE);
694 if (len <= 0) 695 if (len <= 0)
695 HTTPERROR_400_PARAM; 696 HTTPERROR_400_PARAM;
696 tmp_buf2[len] = 0; 697 tmp_buf2[len] = 0;
diff --git a/src/ot_socket.c b/src/ot_socket.c
index b6a1803..8b17080 100644
--- a/src/ot_socket.c
+++ b/src/ot_socket.c
@@ -161,6 +161,20 @@ int socket_udp_bind(const ot_ip6 ip, uint16_t port, socket_sharing sharing) {
161 return s; 161 return s;
162} 162}
163 163
164int socket_udp_is_taken(const ot_ip6 ip, uint16_t port) {
165 struct sockaddr_in6 sa;
166 int s = socket_v6(SOCK_DGRAM), taken;
167
168 if (s == -1)
169 return 0;
170
171 /* Asking for no sharing at all is refused whatever the holder allowed */
172 sockaddr_from_ip(&sa, ip, port);
173 taken = bind(s, (struct sockaddr *)&sa, sizeof(sa)) == -1 && errno == EADDRINUSE;
174 close(s);
175 return taken;
176}
177
164int socket_tcp_connect(const ot_ip6 srcip, uint16_t srcport, const ot_ip6 dstip, uint16_t dstport) { 178int socket_tcp_connect(const ot_ip6 srcip, uint16_t srcport, const ot_ip6 dstip, uint16_t dstport) {
165 struct sockaddr_in6 sa; 179 struct sockaddr_in6 sa;
166 int s = socket_v6(SOCK_STREAM); 180 int s = socket_v6(SOCK_STREAM);
diff --git a/src/ot_socket.h b/src/ot_socket.h
index 5c1d840..33446e4 100644
--- a/src/ot_socket.h
+++ b/src/ot_socket.h
@@ -32,6 +32,8 @@ int socket_can_balance(void);
32int socket_tcp_listen(const ot_ip6 ip, uint16_t port, socket_sharing sharing); 32int socket_tcp_listen(const ot_ip6 ip, uint16_t port, socket_sharing sharing);
33int socket_udp_bind(const ot_ip6 ip, uint16_t port, socket_sharing sharing); 33int socket_udp_bind(const ot_ip6 ip, uint16_t port, socket_sharing sharing);
34 34
35int socket_udp_is_taken(const ot_ip6 ip, uint16_t port);
36
35int socket_tcp_connect(const ot_ip6 srcip, uint16_t srcport, const ot_ip6 dstip, uint16_t dstport); 37int socket_tcp_connect(const ot_ip6 srcip, uint16_t srcport, const ot_ip6 dstip, uint16_t dstport);
36int socket_is_connected(int s); 38int socket_is_connected(int s);
37int socket_accept(int s, ot_ip6 ip, uint16_t *port); 39int socket_accept(int s, ot_ip6 ip, uint16_t *port);
diff --git a/src/ot_stats.c b/src/ot_stats.c
index ba780d3..95f3cff 100644
--- a/src/ot_stats.c
+++ b/src/ot_stats.c
@@ -83,7 +83,7 @@ static void counters_total(unsigned long long *total) {
83 pthread_mutex_unlock(&g_counter_mutex); 83 pthread_mutex_unlock(&g_counter_mutex);
84} 84}
85 85
86#define COUNT(index, by) atomic_fetch_add_explicit(ws->counters + (index), (unsigned long long)(by), memory_order_relaxed) 86#define COUNT(index, by) atomic_fetch_add_explicit(ws->counters + (index), (unsigned long)(by), memory_order_relaxed)
87 87
88static const char *ot_failed_request_names[] = { 88static const char *ot_failed_request_names[] = {
89 "302 Redirect", "400 Parse Error", "400 Invalid Parameter", "400 Invalid Parameter (compact=0)", "400 Not Modest", 89 "302 Redirect", "400 Parse Error", "400 Invalid Parameter", "400 Invalid Parameter (compact=0)", "400 Not Modest",
diff --git a/src/ot_tcp.c b/src/ot_tcp.c
index 5d7b78f..67a0ebc 100644
--- a/src/ot_tcp.c
+++ b/src/ot_tcp.c
@@ -44,9 +44,19 @@ static ssize_t header_complete(char *request, ssize_t byte_count) {
44 44
45void tcp_read(const int64_t sock, struct ot_workstruct *ws) { 45void tcp_read(const int64_t sock, struct ot_workstruct *ws) {
46 struct http_data *cookie = fdstate_cookie(sock); 46 struct http_data *cookie = fdstate_cookie(sock);
47 ssize_t byte_count = read((int)sock, ws->inbuf, G_INBUF_SIZE); 47 ssize_t byte_count;
48 uint32_t generation; 48 uint32_t generation;
49 49
50 /* We're not supposed to read from a socket that waits for
51 our answer. Prevent its reply from being sent to the next
52 generation on that fd. */
53 if (cookie->flag & (STRUCT_HTTP_FLAG_WAITINGFORTASK | STRUCT_HTTP_FLAG_CHUNKED_IN_TRANSFER)) {
54 http_close(sock);
55 return;
56 }
57
58 byte_count = read((int)sock, ws->inbuf, G_INBUF_SIZE);
59
50 if (byte_count == 0 || (byte_count == -1 && errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR)) { 60 if (byte_count == 0 || (byte_count == -1 && errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR)) {
51 http_close(sock); 61 http_close(sock);
52 return; 62 return;
diff --git a/src/ot_udp.c b/src/ot_udp.c
index 9e8e3c4..609089b 100644
--- a/src/ot_udp.c
+++ b/src/ot_udp.c
@@ -19,6 +19,9 @@
19#include "ot_udp.h" 19#include "ot_udp.h"
20#include "trackerlogic.h" 20#include "trackerlogic.h"
21 21
22/* BEP 15: "Up to about 74 torrents can be scraped at once" */
23#define OT_MAX_SCRAPE_UDP 74
24
22static uint32_t g_rijndael_round_key[44] = {0}; 25static uint32_t g_rijndael_round_key[44] = {0};
23static volatile uint32_t g_key_of_the_hour[2] = {0}; 26static volatile uint32_t g_key_of_the_hour[2] = {0};
24static volatile ot_time g_hour_of_the_key; 27static volatile ot_time g_hour_of_the_key;
@@ -61,18 +64,71 @@ static void udp_make_connectionid(uint32_t connid[2], const ot_ip6 remoteip, int
61 connid[1] = crypt[2] ^ crypt[3]; 64 connid[1] = crypt[2] ^ crypt[3];
62} 65}
63 66
67/* BEP 15 packet layouts, as byte offsets into the datagram */
68enum {
69 /* Every request starts alike */
70 UDP_REQUEST_CONNECTION_ID_OFFSET = 0,
71 UDP_REQUEST_ACTION_OFFSET = 8,
72 UDP_REQUEST_TRANSACTION_ID_OFFSET = 12,
73 UDP_REQUEST_HEADER_SIZE = 16,
74
75 UDP_ANNOUNCE_INFO_HASH_OFFSET = 16,
76 UDP_ANNOUNCE_LEFT_OFFSET = 64, /* 64 bit */
77 UDP_ANNOUNCE_EVENT_OFFSET = 80,
78 UDP_ANNOUNCE_NUM_WANT_OFFSET = 92,
79 UDP_ANNOUNCE_PORT_OFFSET = 96, /* 16 bit */
80 UDP_ANNOUNCE_SIZE = 98,
81
82 UDP_SCRAPE_INFO_HASH_OFFSET = 16,
83
84 /* And so does every reply */
85 UDP_REPLY_ACTION_OFFSET = 0,
86 UDP_REPLY_TRANSACTION_ID_OFFSET = 4,
87 UDP_REPLY_HEADER_SIZE = 8
88};
89
90enum { UDP_ACTION_CONNECT = 0, UDP_ACTION_ANNOUNCE = 1, UDP_ACTION_SCRAPE = 2, UDP_ACTION_ERROR = 3 };
91enum { UDP_EVENT_COMPLETED = 1, UDP_EVENT_STOPPED = 3 };
92
93/* What a client puts where the connection id goes, when it asks for one */
94static const uint8_t g_udp_protocol_id[8] = {0x00, 0x00, 0x04, 0x17, 0x27, 0x10, 0x19, 0x80};
95
96static uint32_t udp_read32(const char *packet, size_t offset) {
97 uint32_t value;
98 memcpy(&value, packet + offset, sizeof(value));
99 return ntohl(value);
100}
101
102/* Returns where the rest of the reply goes */
103static char *udp_reply_header(char *reply, uint32_t action, const char *request) {
104 action = htonl(action);
105 memcpy(reply + UDP_REPLY_ACTION_OFFSET, &action, sizeof(action));
106 memcpy(reply + UDP_REPLY_TRANSACTION_ID_OFFSET, request + UDP_REQUEST_TRANSACTION_ID_OFFSET, sizeof(uint32_t));
107 return reply + UDP_REPLY_HEADER_SIZE;
108}
109
110static void udp_send_error(int64_t serversocket, struct ot_workstruct *ws, const char *message, const ot_ip6 remoteip, uint16_t remoteport) {
111 size_t size = strlen(message) + 1;
112 char *reply = udp_reply_header(ws->outbuf, UDP_ACTION_ERROR, ws->inbuf);
113
114 memcpy(reply, message, size);
115 ws->reply_size = UDP_REPLY_HEADER_SIZE + size;
116 socket_send(serversocket, ws->outbuf, ws->reply_size, remoteip, remoteport);
117}
118
64/* UDP implementation according to http://xbtt.sourceforge.net/udp_tracker_protocol.html */ 119/* UDP implementation according to http://xbtt.sourceforge.net/udp_tracker_protocol.html */
65int handle_udp6(int64_t serversocket, struct ot_workstruct *ws) { 120int handle_udp6(int64_t serversocket, struct ot_workstruct *ws) {
66 ot_ip6 remoteip; 121 ot_ip6 remoteip;
67 uint32_t *inpacket = (uint32_t *)ws->inbuf; 122 const char *request = ws->inbuf;
68 uint32_t *outpacket = (uint32_t *)ws->outbuf; 123 char *reply;
69 uint32_t left, event; 124 uint32_t left, event, numwant;
70 uint32_t connid[2]; 125 uint32_t connid[2];
71 uint32_t action; 126 uint32_t action;
72 uint16_t port, remoteport; 127 uint16_t port, remoteport;
73 size_t byte_count, scrape_count; 128 size_t byte_count, scrape_count, max_peers, i;
129 ot_hash *hashes;
74 130
75 ssize_t result = socket_recv(serversocket, ws->inbuf, G_INBUF_SIZE, remoteip, &remoteport); 131 ssize_t result = socket_recv(serversocket, ws->inbuf, G_INBUF_SIZE, remoteip, &remoteport);
76 if (result <= 0) 132 if (result <= 0)
77 return 0; 133 return 0;
78 byte_count = (size_t)result; 134 byte_count = (size_t)result;
@@ -81,12 +137,12 @@ int handle_udp6(int64_t serversocket, struct ot_workstruct *ws) {
81 stats_issue_event(ws, EVENT_READ, FLAG_UDP, byte_count); 137 stats_issue_event(ws, EVENT_READ, FLAG_UDP, byte_count);
82 138
83 /* Minimum udp tracker packet size, also catches error */ 139 /* Minimum udp tracker packet size, also catches error */
84 if (byte_count < 16) 140 if (byte_count < UDP_REQUEST_HEADER_SIZE)
85 return 1; 141 return 1;
86 142
87 /* Get action to take. Ignore error messages and broken packets */ 143 /* Get action to take. Ignore error messages and broken packets */
88 action = ntohl(inpacket[2]); 144 action = udp_read32(request, UDP_REQUEST_ACTION_OFFSET);
89 if (action > 2) 145 if (action > UDP_ACTION_SCRAPE)
90 return 1; 146 return 1;
91 147
92 /* Generate the connection id we give out and expect to and from 148 /* Generate the connection id we give out and expect to and from
@@ -97,110 +153,98 @@ int handle_udp6(int64_t serversocket, struct ot_workstruct *ws) {
97 ws->hash = NULL; 153 ws->hash = NULL;
98 ws->peer_id = NULL; 154 ws->peer_id = NULL;
99 155
100 /* If action is not 0 (connect), then we expect the derived 156 /* If action is not connect, then we expect the derived
101 connection id in first 64 bit */ 157 connection id in first 64 bit */
102 if ((action > 0) && (inpacket[0] != connid[0] || inpacket[1] != connid[1])) { 158 if (action != UDP_ACTION_CONNECT && memcmp(request + UDP_REQUEST_CONNECTION_ID_OFFSET, connid, sizeof(connid))) {
103 /* If connection id does not match, try the one that was 159 /* If connection id does not match, try the one that was
104 valid in the previous hour. Only if this also does not 160 valid in the previous hour. Only if this also does not
105 match, return an error packet */ 161 match, return an error packet */
106 udp_make_connectionid(connid, remoteip, 1); 162 udp_make_connectionid(connid, remoteip, 1);
107 if (inpacket[0] != connid[0] || inpacket[1] != connid[1]) { 163 if (memcmp(request + UDP_REQUEST_CONNECTION_ID_OFFSET, connid, sizeof(connid))) {
108 const char err_idmiss[] = "Connection ID missmatch."; 164 static const char err_idmiss[] = "Connection ID missmatch.";
109 size_t s = sizeof(err_idmiss); 165
110 outpacket[0] = htonl(3); 166 /* Nobody has vouched for this address yet, so it is not sent more
111 outpacket[1] = inpacket[3]; 167 than was sent in its name */
112 memcpy(&outpacket[2], &err_idmiss[0], s); 168 if (byte_count >= UDP_REPLY_HEADER_SIZE + sizeof(err_idmiss))
113 socket_send(serversocket, ws->outbuf, 8 + s, remoteip, remoteport); 169 udp_send_error(serversocket, ws, err_idmiss, remoteip, remoteport);
114 stats_issue_event(ws, EVENT_CONNID_MISSMATCH, FLAG_UDP, 8 + s); 170 stats_issue_event(ws, EVENT_CONNID_MISSMATCH, FLAG_UDP, byte_count);
115 return 1; 171 return 1;
116 } 172 }
117 } 173 }
118 174
119 switch (action) { 175 switch (action) {
120 case 0: /* This is a connect action */ 176 case UDP_ACTION_CONNECT:
121 /* look for udp bittorrent magic id */ 177 if (memcmp(request + UDP_REQUEST_CONNECTION_ID_OFFSET, g_udp_protocol_id, sizeof(g_udp_protocol_id)))
122 if ((ntohl(inpacket[0]) != 0x00000417) || (ntohl(inpacket[1]) != 0x27101980))
123 return 1; 178 return 1;
124 179
125 outpacket[0] = 0; 180 reply = udp_reply_header(ws->outbuf, UDP_ACTION_CONNECT, request);
126 outpacket[1] = inpacket[3]; 181 memcpy(reply, connid, sizeof(connid));
127 outpacket[2] = connid[0]; 182 reply += sizeof(connid);
128 outpacket[3] = connid[1];
129 183
130 socket_send(serversocket, ws->outbuf, 16, remoteip, remoteport); 184 socket_send(serversocket, ws->outbuf, reply - ws->outbuf, remoteip, remoteport);
131 stats_issue_event(ws, EVENT_CONNECT, FLAG_UDP, 16); 185 stats_issue_event(ws, EVENT_CONNECT, FLAG_UDP, reply - ws->outbuf);
132 break; 186 break;
133 case 1: /* This is an announce action */ 187
134 /* Minimum udp announce packet size */ 188 case UDP_ACTION_ANNOUNCE:
135 if (byte_count < 98) 189 if (byte_count < UDP_ANNOUNCE_SIZE)
136 return 1; 190 return 1;
137 191
138 /* We do only want to know, if it is zero */ 192 /* We do only want to know, if it is zero */
139 left = inpacket[64 / 4] | inpacket[68 / 4]; 193 left = udp_read32(request, UDP_ANNOUNCE_LEFT_OFFSET) | udp_read32(request, UDP_ANNOUNCE_LEFT_OFFSET + sizeof(uint32_t));
194 event = udp_read32(request, UDP_ANNOUNCE_EVENT_OFFSET);
195 numwant = udp_read32(request, UDP_ANNOUNCE_NUM_WANT_OFFSET);
196 ws->hash = (ot_hash *)(ws->inbuf + UDP_ANNOUNCE_INFO_HASH_OFFSET);
140 197
141 event = ntohl(inpacket[80 / 4]); 198 /* The peer keeps its port the way it came over the wire */
142 port = *(uint16_t *)(((char *)inpacket) + 96); 199 memcpy(&port, request + UDP_ANNOUNCE_PORT_OFFSET, sizeof(port));
143 ws->hash = (ot_hash *)(((char *)inpacket) + 16);
144 200
145 OT_SETIP(ws->peer, remoteip); 201 OT_SETIP(ws->peer, remoteip);
146 OT_SETPORT(ws->peer, &port); 202 OT_SETPORT(ws->peer, &port);
147 OT_PEERFLAG(ws->peer) = 0; 203 OT_PEERFLAG(ws->peer) = 0;
148 204
149 switch (event) { 205 if (event == UDP_EVENT_COMPLETED)
150 case 1:
151 OT_PEERFLAG(ws->peer) |= PEER_FLAG_COMPLETED; 206 OT_PEERFLAG(ws->peer) |= PEER_FLAG_COMPLETED;
152 break; 207 if (event == UDP_EVENT_STOPPED)
153 case 3:
154 OT_PEERFLAG(ws->peer) |= PEER_FLAG_STOPPED; 208 OT_PEERFLAG(ws->peer) |= PEER_FLAG_STOPPED;
155 break;
156 default:
157 break;
158 }
159
160 if (!left) 209 if (!left)
161 OT_PEERFLAG(ws->peer) |= PEER_FLAG_SEEDING; 210 OT_PEERFLAG(ws->peer) |= PEER_FLAG_SEEDING;
162 211
163 outpacket[0] = htonl(1); /* announce action */ 212 ws->reply = udp_reply_header(ws->outbuf, UDP_ACTION_ANNOUNCE, request);
164 outpacket[1] = inpacket[12 / 4];
165 213
166 if (OT_PEERFLAG(ws->peer) & PEER_FLAG_STOPPED) { /* Peer is gone. */ 214 if (OT_PEERFLAG(ws->peer) & PEER_FLAG_STOPPED) { /* Peer is gone. */
167 ws->reply = ws->outbuf;
168 ws->reply_size = remove_peer_from_torrent(FLAG_UDP, ws); 215 ws->reply_size = remove_peer_from_torrent(FLAG_UDP, ws);
169 } else { 216 } else {
170 /* Limit amount of peers to OT_MAX_PEERS_UDP */ 217 /* List of peers should fit in a single UDP packet */
171 uint32_t numwant = ntohl(inpacket[92 / 4]); 218 max_peers = ip_is_v4mapped(remoteip) ? OT_MAX_PEERS_UDP4 : OT_MAX_PEERS_UDP6;
172 size_t max_peers = ip_is_v4mapped(remoteip) ? OT_MAX_PEERS_UDP4 : OT_MAX_PEERS_UDP6;
173 if (numwant > max_peers) 219 if (numwant > max_peers)
174 numwant = max_peers; 220 numwant = max_peers;
175 221
176 ws->reply = ws->outbuf + 8;
177 ws->reply_size = add_peer_to_torrent_and_return_peers(FLAG_UDP, ws, numwant); 222 ws->reply_size = add_peer_to_torrent_and_return_peers(FLAG_UDP, ws, numwant);
178 223
179 /* The announce path answers a refusal itself, so nothing is left here 224 /* The announce path answers a refusal itself, so nothing is left here
180 but a tracker that could not get the memory to track the torrent */ 225 but a tracker that could not get the memory to track the torrent */
181 if (!ws->reply_size) { 226 if (!ws->reply_size) {
182 const char err_resources[] = "Tracker is out of resources, try again later."; 227 udp_send_error(serversocket, ws, "Tracker is out of resources, try again later.", remoteip, remoteport);
183 size_t s = sizeof(err_resources);
184 outpacket[0] = htonl(3);
185 memcpy(&outpacket[2], &err_resources[0], s);
186 socket_send(serversocket, ws->outbuf, 8 + s, remoteip, remoteport);
187 return 1; 228 return 1;
188 } 229 }
189 ws->reply_size += 8;
190 } 230 }
231 ws->reply_size += UDP_REPLY_HEADER_SIZE;
191 232
192 socket_send(serversocket, ws->outbuf, ws->reply_size, remoteip, remoteport); 233 socket_send(serversocket, ws->outbuf, ws->reply_size, remoteip, remoteport);
193 stats_issue_event(ws, EVENT_ANNOUNCE, FLAG_UDP, ws->reply_size); 234 stats_issue_event(ws, EVENT_ANNOUNCE, FLAG_UDP, ws->reply_size);
194 break; 235 break;
195 236
196 case 2: /* This is a scrape action */ 237 case UDP_ACTION_SCRAPE:
197 outpacket[0] = htonl(2); /* scrape action */ 238 scrape_count = (byte_count - UDP_SCRAPE_INFO_HASH_OFFSET) / sizeof(ot_hash);
198 outpacket[1] = inpacket[12 / 4]; 239 if (scrape_count > OT_MAX_SCRAPE_UDP)
240 scrape_count = OT_MAX_SCRAPE_UDP;
199 241
200 for (scrape_count = 0; (scrape_count * 20 < byte_count - 16) && (scrape_count <= 74); scrape_count++) 242 hashes = (ot_hash *)(ws->inbuf + UDP_SCRAPE_INFO_HASH_OFFSET);
201 return_udp_scrape_for_torrent(*(ot_hash *)(((char *)inpacket) + 16 + 20 * scrape_count), ((char *)outpacket) + 8 + 12 * scrape_count); 243 reply = udp_reply_header(ws->outbuf, UDP_ACTION_SCRAPE, request);
244 for (i = 0; i < scrape_count; ++i)
245 reply += return_udp_scrape_for_torrent(hashes[i], reply);
202 246
203 socket_send(serversocket, ws->outbuf, 8 + 12 * scrape_count, remoteip, remoteport); 247 socket_send(serversocket, ws->outbuf, reply - ws->outbuf, remoteip, remoteport);
204 stats_issue_event(ws, EVENT_SCRAPE, FLAG_UDP, scrape_count); 248 stats_issue_event(ws, EVENT_SCRAPE, FLAG_UDP, scrape_count);
205 break; 249 break;
206 } 250 }
diff --git a/src/ot_workqueue.c b/src/ot_workqueue.c
index 56a7cd2..cdefddc 100644
--- a/src/ot_workqueue.c
+++ b/src/ot_workqueue.c
@@ -9,6 +9,7 @@
9#include <unistd.h> 9#include <unistd.h>
10 10
11/* Opentracker */ 11/* Opentracker */
12#include "ot_fdstate.h"
12#include "ot_iovec.h" 13#include "ot_iovec.h"
13#include "ot_workqueue.h" 14#include "ot_workqueue.h"
14#include "trackerlogic.h" 15#include "trackerlogic.h"
@@ -20,6 +21,7 @@ struct ot_task {
20 ot_taskid taskid; 21 ot_taskid taskid;
21 ot_tasktype tasktype; 22 ot_tasktype tasktype;
22 int64_t sock; 23 int64_t sock;
24 uint32_t generation;
23 size_t iovec_entries; 25 size_t iovec_entries;
24 struct iovec *iovec; 26 struct iovec *iovec;
25 struct ot_task *next; 27 struct ot_task *next;
@@ -40,6 +42,7 @@ int workqueue_pushtask(int64_t sock, ot_tasktype tasktype) {
40 task->taskid = 0; 42 task->taskid = 0;
41 task->tasktype = tasktype; 43 task->tasktype = tasktype;
42 task->sock = sock; 44 task->sock = sock;
45 task->generation = fdstate_generation((int)sock);
43 task->iovec_entries = 0; 46 task->iovec_entries = 0;
44 task->iovec = NULL; 47 task->iovec = NULL;
45 task->next = 0; 48 task->next = 0;
@@ -65,22 +68,25 @@ void workqueue_canceltask(int64_t sock) {
65 /* Want exclusive access to tasklist */ 68 /* Want exclusive access to tasklist */
66 pthread_mutex_lock(&tasklist_mutex); 69 pthread_mutex_lock(&tasklist_mutex);
67 70
68 for (task = &tasklist; *task; task = &((*task)->next)) 71 task = &tasklist;
69 if ((*task)->sock == sock) { 72 while (*task) {
70 struct iovec *iovec = (*task)->iovec; 73 struct ot_task *ptask = *task;
71 struct ot_task *ptask = *task; 74 size_t i;
72 size_t i;
73
74 /* Free task's iovec, the buffers it points at and the vector itself */
75 for (i = 0; i < (*task)->iovec_entries; ++i)
76 free(iovec[i].iov_base);
77 free(iovec);
78 75
79 *task = (*task)->next; 76 if (ptask->sock != sock) {
80 free(ptask); 77 task = &ptask->next;
81 break; 78 continue;
82 } 79 }
83 80
81 /* Free task's iovec, the buffers it points at and the vector itself */
82 for (i = 0; i < ptask->iovec_entries; ++i)
83 free(ptask->iovec[i].iov_base);
84 free(ptask->iovec);
85
86 *task = ptask->next;
87 free(ptask);
88 }
89
84 /* Release lock */ 90 /* Release lock */
85 pthread_mutex_unlock(&tasklist_mutex); 91 pthread_mutex_unlock(&tasklist_mutex);
86} 92}
@@ -190,7 +196,7 @@ int workqueue_pushchunked(ot_taskid taskid, struct iovec *iovec) {
190 return task ? 0 : -1; 196 return task ? 0 : -1;
191} 197}
192 198
193int64_t workqueue_popresult(size_t *iovec_entries, struct iovec **iovec, int *is_partial) { 199int64_t workqueue_popresult(size_t *iovec_entries, struct iovec **iovec, int *is_partial, uint32_t *generation) {
194 struct ot_task **task; 200 struct ot_task **task;
195 int64_t sock = -1; 201 int64_t sock = -1;
196 202
@@ -205,6 +211,7 @@ int64_t workqueue_popresult(size_t *iovec_entries, struct iovec **iovec, int *is
205 *iovec_entries = ptask->iovec_entries; 211 *iovec_entries = ptask->iovec_entries;
206 *iovec = ptask->iovec; 212 *iovec = ptask->iovec;
207 sock = ptask->sock; 213 sock = ptask->sock;
214 *generation = ptask->generation;
208 215
209 if ((*task)->tasktype == TASK_DONE) { 216 if ((*task)->tasktype == TASK_DONE) {
210 *task = ptask->next; 217 *task = ptask->next;
diff --git a/src/ot_workqueue.h b/src/ot_workqueue.h
index d8f30d6..982292e 100644
--- a/src/ot_workqueue.h
+++ b/src/ot_workqueue.h
@@ -64,7 +64,7 @@ void workqueue_pushsuccess(ot_taskid taskid);
64ot_taskid workqueue_poptask(ot_tasktype *tasktype); 64ot_taskid workqueue_poptask(ot_tasktype *tasktype);
65int workqueue_pushresult(ot_taskid taskid, size_t iovec_entries, struct iovec *iovector); 65int workqueue_pushresult(ot_taskid taskid, size_t iovec_entries, struct iovec *iovector);
66int workqueue_pushchunked(ot_taskid taskid, struct iovec *iovec); 66int workqueue_pushchunked(ot_taskid taskid, struct iovec *iovec);
67int64_t workqueue_popresult(size_t *iovec_entries, struct iovec **iovector, int *is_partial); 67int64_t workqueue_popresult(size_t *iovec_entries, struct iovec **iovector, int *is_partial, uint32_t *generation);
68 68
69void workqueue_init(void); 69void workqueue_init(void);
70void workqueue_deinit(void); 70void workqueue_deinit(void);
diff --git a/src/trackerlogic.c b/src/trackerlogic.c
index 1f56a2c..0b032e1 100644
--- a/src/trackerlogic.c
+++ b/src/trackerlogic.c
@@ -94,10 +94,11 @@ size_t add_peer_to_torrent_and_return_peers(PROTO_FLAG proto, struct ot_workstru
94 return strlen(invalid_hash); 94 return strlen(invalid_hash);
95 } 95 }
96 if (proto == FLAG_UDP) { 96 if (proto == FLAG_UDP) {
97 ((uint32_t *)ws->reply)[0] = htonl(OT_CLIENT_REJECT_INTERVAL_RANDOM); 97 char *r = ws->reply;
98 ((uint32_t *)ws->reply)[1] = 0; 98 pack_uint32(&r, OT_CLIENT_REJECT_INTERVAL_RANDOM);
99 ((uint32_t *)ws->reply)[2] = 0; 99 pack_uint32(&r, 0);
100 return 12; 100 pack_uint32(&r, 0);
101 return r - ws->reply;
101 } 102 }
102 return 0; 103 return 0;
103 } 104 }
@@ -297,10 +298,9 @@ static size_t return_peers_for_torrent_udp(struct ot_workstruct *ws, ot_torrent
297 if (amount > list_count) 298 if (amount > list_count)
298 amount = list_count; 299 amount = list_count;
299 300
300 *(uint32_t *)(r + 0) = htonl(OT_CLIENT_REQUEST_INTERVAL_RANDOM); 301 pack_uint32(&r, OT_CLIENT_REQUEST_INTERVAL_RANDOM);
301 *(uint32_t *)(r + 4) = htonl(peer_count - seed_count); 302 pack_uint32(&r, peer_count - seed_count);
302 *(uint32_t *)(r + 8) = htonl(seed_count); 303 pack_uint32(&r, seed_count);
303 r += 12;
304 304
305 if (amount) { 305 if (amount) {
306 if (amount == list_count) 306 if (amount == list_count)
@@ -400,23 +400,25 @@ size_t return_udp_scrape_for_torrent(ot_hash const hash, char *reply) {
400 ot_vector *torrents_list = mutex_bucket_lock_by_hash(hash); 400 ot_vector *torrents_list = mutex_bucket_lock_by_hash(hash);
401 ot_torrent *torrent = vector_binary_search(hash, torrents_list->data, torrents_list->size, sizeof(ot_torrent), OT_HASH_COMPARE_SIZE, &exactmatch); 401 ot_torrent *torrent = vector_binary_search(hash, torrents_list->data, torrents_list->size, sizeof(ot_torrent), OT_HASH_COMPARE_SIZE, &exactmatch);
402 402
403 if (!exactmatch) { 403 uint32_t seeders = 0, completed = 0, leechers = 0;
404 memset(reply, 0, 12); 404 char *r = reply;
405 } else {
406 uint32_t *r = (uint32_t *)reply;
407 405
406 if (exactmatch) {
408 if (clean_single_torrent(torrent)) { 407 if (clean_single_torrent(torrent)) {
409 vector_remove_torrent(torrents_list, torrent); 408 vector_remove_torrent(torrents_list, torrent);
410 memset(reply, 0, 12);
411 delta_torrentcount = -1; 409 delta_torrentcount = -1;
412 } else { 410 } else {
413 r[0] = htonl(torrent_seed_count(torrent)); 411 seeders = torrent_seed_count(torrent);
414 r[1] = htonl(torrent->down_count); 412 completed = torrent->down_count;
415 r[2] = htonl(torrent_peer_count(torrent) - torrent_seed_count(torrent)); 413 leechers = torrent_peer_count(torrent) - torrent_seed_count(torrent);
416 } 414 }
417 } 415 }
418 mutex_bucket_unlock_by_hash(hash, delta_torrentcount); 416 mutex_bucket_unlock_by_hash(hash, delta_torrentcount);
419 return 12; 417
418 pack_uint32(&r, seeders);
419 pack_uint32(&r, completed);
420 pack_uint32(&r, leechers);
421 return r - reply;
420} 422}
421 423
422/* Fetches scrape info for a specific torrent */ 424/* Fetches scrape info for a specific torrent */
@@ -485,10 +487,11 @@ size_t remove_peer_from_torrent(PROTO_FLAG proto, struct ot_workstruct *ws) {
485 487
486 /* Handle UDP reply */ 488 /* Handle UDP reply */
487 if (proto == FLAG_UDP) { 489 if (proto == FLAG_UDP) {
488 ((uint32_t *)ws->reply)[2] = htonl(OT_CLIENT_REQUEST_INTERVAL_RANDOM); 490 char *r = ws->reply;
489 ((uint32_t *)ws->reply)[3] = htonl(peer_count - seed_count); 491 pack_uint32(&r, OT_CLIENT_REQUEST_INTERVAL_RANDOM);
490 ((uint32_t *)ws->reply)[4] = htonl(seed_count); 492 pack_uint32(&r, peer_count - seed_count);
491 ws->reply_size = 20; 493 pack_uint32(&r, seed_count);
494 ws->reply_size = r - ws->reply;
492 } 495 }
493 496
494 mutex_bucket_unlock_by_hash(*ws->hash, 0); 497 mutex_bucket_unlock_by_hash(*ws->hash, 0);
diff --git a/src/trackerlogic.h b/src/trackerlogic.h
index dd8a48c..a05c790 100644
--- a/src/trackerlogic.h
+++ b/src/trackerlogic.h
@@ -4,10 +4,12 @@
4#ifndef OT_TRACKERLOGIC_H__ 4#ifndef OT_TRACKERLOGIC_H__
5#define OT_TRACKERLOGIC_H__ 5#define OT_TRACKERLOGIC_H__
6 6
7#include <arpa/inet.h>
7#include <signal.h> 8#include <signal.h>
8#include <stdatomic.h> 9#include <stdatomic.h>
9#include <stdint.h> 10#include <stdint.h>
10#include <stdlib.h> 11#include <stdlib.h>
12#include <string.h>
11#include <sys/time.h> 13#include <sys/time.h>
12#include <sys/types.h> 14#include <sys/types.h>
13#include <time.h> 15#include <time.h>
@@ -124,6 +126,14 @@ static inline int time_is_past(ot_time deadline) { return time_now_seconds() > d
124 survive a restart, and the clock above counts from boot. */ 126 survive a restart, and the clock above counts from boot. */
125static inline ot_time time_wall_minutes(void) { return time(NULL) / 60; } 127static inline ot_time time_wall_minutes(void) { return time(NULL) / 60; }
126 128
129/* Appends a 32 bit value in network byte order to a binary reply and
130 advances the cursor. The caller has made sure of the room. */
131static inline void pack_uint32(char **cursor, uint32_t value) {
132 value = htonl(value);
133 memcpy(*cursor, &value, sizeof(value));
134 *cursor += sizeof(value);
135}
136
127/* Cleared from the interrupt handler and read by every worker */ 137/* Cleared from the interrupt handler and read by every worker */
128extern _Atomic int g_opentracker_running; 138extern _Atomic int g_opentracker_running;
129 139
@@ -221,7 +231,7 @@ enum {
221}; 231};
222 232
223/* One statistic. Used when workers report stats to their workstruct */ 233/* One statistic. Used when workers report stats to their workstruct */
224typedef _Atomic unsigned long long ot_counter; 234typedef _Atomic unsigned long ot_counter;
225 235
226/* What each thread counts for itself. The two runs at the end are indexed by 236/* What each thread counts for itself. The two runs at the end are indexed by
227 the http error code and by the age in minutes of a renewed peer */ 237 the http error code and by the age in minutes of a renewed peer */
diff --git a/tests/integration/test_announce.py b/tests/integration/test_announce.py
index ffbc07b..2d21417 100644
--- a/tests/integration/test_announce.py
+++ b/tests/integration/test_announce.py
@@ -118,9 +118,24 @@ class AnnounceRejects(TrackerTestCase):
118 def test_a_port_out_of_range_is_rejected(self): 118 def test_a_port_out_of_range_is_rejected(self):
119 self.assert_rejected("info_hash=" + "a" * 20 + "&peer_id=" + "b" * 20 + "&port=65536&left=0") 119 self.assert_rejected("info_hash=" + "a" * 20 + "&peer_id=" + "b" * 20 + "&port=65536&left=0")
120 120
121 def test_a_negative_port_is_rejected(self):
122 self.assert_rejected("info_hash=" + "a" * 20 + "&peer_id=" + "b" * 20 + "&port=-1&left=0")
123
121 def test_a_port_that_is_not_a_number_is_rejected(self): 124 def test_a_port_that_is_not_a_number_is_rejected(self):
122 self.assert_rejected("info_hash=" + "a" * 20 + "&peer_id=" + "b" * 20 + "&port=abc&left=0") 125 self.assert_rejected("info_hash=" + "a" * 20 + "&peer_id=" + "b" * 20 + "&port=abc&left=0")
123 126
127 def test_an_ip_that_fills_the_reply_buffer_is_refused(self):
128 """The value is decoded into the reply buffer and then terminated, so
129 the longest one that fits has to leave room for the terminator. 8096
130 bytes is what lies between where it is decoded and the buffer's end."""
131 connection = self.tracker.connect()
132 try:
133 connection.sock.sendall(b"GET /a?ip=" + b"1" * 8096 + b"\n\n")
134 status, _, _ = connection.reply()
135 self.assertTrue(status.startswith(b"HTTP/1.0 400"), status)
136 finally:
137 connection.close()
138
124 def test_two_info_hashes_are_rejected(self): 139 def test_two_info_hashes_are_rejected(self):
125 self.assert_rejected("info_hash=" + "a" * 20 + "&info_hash=" + "c" * 20 + "&peer_id=" + "b" * 20 + "&port=6881&left=0") 140 self.assert_rejected("info_hash=" + "a" * 20 + "&info_hash=" + "c" * 20 + "&peer_id=" + "b" * 20 + "&port=6881&left=0")
126 141
diff --git a/tests/integration/test_udp.py b/tests/integration/test_udp.py
index 1cb2389..8a255ec 100644
--- a/tests/integration/test_udp.py
+++ b/tests/integration/test_udp.py
@@ -9,7 +9,7 @@ import socket
9import struct 9import struct
10import unittest 10import unittest
11 11
12from harness import TrackerTestCase 12from harness import Tracker, TrackerTestCase
13 13
14MAGIC = 0x41727101980 14MAGIC = 0x41727101980
15 15
@@ -44,6 +44,17 @@ class UdpProtocol(TrackerTestCase):
44 self.assertEqual(action, 3, "action 3 is the error packet") 44 self.assertEqual(action, 3, "action 3 is the error packet")
45 self.assertIn(b"Connection ID missmatch", answer[8:]) 45 self.assertIn(b"Connection ID missmatch", answer[8:])
46 46
47 def test_a_wrong_connection_id_is_not_answered_with_more_than_was_sent(self):
48 """The sender's address is unverified at this point, so the error
49 must not be a way to throw bytes at somebody else."""
50 scrape = struct.pack(">QII", 0, 2, 3) + self.hash_for("udpbadscrape")
51 answer = self.tracker.udp_raw(scrape)
52 self.assertIsNotNone(answer, "a whole scrape is long enough to be told")
53 self.assertLessEqual(len(answer), len(scrape))
54 self.assertIsNone(self.tracker.udp_raw(scrape[:16]))
55 self.assertIsNone(self.tracker.udp_raw(scrape[: len(answer) - 1]))
56 self.assertIsNotNone(self.tracker.udp_raw(scrape[: len(answer)]))
57
47 def test_a_packet_shorter_than_the_header_is_ignored(self): 58 def test_a_packet_shorter_than_the_header_is_ignored(self):
48 self.assertIsNone(self.tracker.udp_raw(b"\x00" * 15)) 59 self.assertIsNone(self.tracker.udp_raw(b"\x00" * 15))
49 60
@@ -148,6 +159,28 @@ class UdpScrape(TrackerTestCase):
148 finally: 159 finally:
149 sock.close() 160 sock.close()
150 161
162 def test_a_hash_cut_short_is_not_scraped(self):
163 """What follows the last whole hash is not a hash, and the bytes that
164 would complete it are not the client's."""
165 info_hash = self.hash_for("udpcut")
166 sock, connection_id = self.tracker.udp_connect()
167 try:
168 sock.sendto(
169 struct.pack(">QII", connection_id, 2, 3) + info_hash + b"\x00" * 7, ("127.0.0.1", self.tracker.port)
170 )
171 self.assertEqual(len(sock.recv(2048)), 8 + 12)
172 finally:
173 sock.close()
174
175 def test_a_scrape_answers_no_more_hashes_than_the_protocol_allows(self):
176 sock, connection_id = self.tracker.udp_connect()
177 try:
178 hashes = b"".join(self.hash_for("udpmany%d" % n) for n in range(80))
179 sock.sendto(struct.pack(">QII", connection_id, 2, 4) + hashes, ("127.0.0.1", self.tracker.port))
180 self.assertEqual(len(sock.recv(2048)), 8 + 12 * 74)
181 finally:
182 sock.close()
183
151 184
152class UdpWorkersConfiguredAfterTheListener(TrackerTestCase): 185class UdpWorkersConfiguredAfterTheListener(TrackerTestCase):
153 """The harness writes its listen lines first, so this directive lands 186 """The harness writes its listen lines first, so this directive lands
@@ -166,3 +199,20 @@ class UdpWorkersConfiguredAfterTheListener(TrackerTestCase):
166 199
167if __name__ == "__main__": 200if __name__ == "__main__":
168 unittest.main() 201 unittest.main()
202
203
204class UdpAddressAlreadyTaken(TrackerTestCase):
205 def test_a_second_tracker_on_the_same_udp_address_says_so(self):
206 """Linux lets it start all the same, and from then on the two take
207 each other's packets. FreeBSD refuses the bind that follows, and the
208 warning is then what explains the refusal."""
209 try:
210 second = Tracker("listen.udp 127.0.0.1:%d\n" % self.tracker.port)
211 except AssertionError as refused:
212 said = str(refused)
213 else:
214 said = second.output()
215 second.stop()
216 second._cleanup()
217 self.assertIn("is already in use", said)
218 self.assertNotIn("is already in use", self.tracker.output())
diff --git a/tests/t_socket.c b/tests/t_socket.c
index 8e917a3..6f07f95 100644
--- a/tests/t_socket.c
+++ b/tests/t_socket.c
@@ -342,6 +342,24 @@ static void case_bind_failure(void) {
342 CHECK_INT(next_descriptor(), before); 342 CHECK_INT(next_descriptor(), before);
343} 343}
344 344
345/* The holder binds the way the tracker does, which lets a second socket in
346 beside it, and that is what the probe is there to see through. */
347static void case_a_taken_udp_address_is_noticed(void) {
348 char ip[16];
349 uint16_t port;
350 int holder;
351
352 test_case("a udp address somebody holds is reported as taken");
353 holder = socket_udp_bind(ip_loopback, 0, SOCKET_SHARED);
354 CHECK(holder != -1);
355 bound_address(holder, ip, &port);
356 CHECK_INT(socket_udp_is_taken(ip_loopback, port), 1);
357
358 test_case("and as free again once it is let go");
359 close(holder);
360 CHECK_INT(socket_udp_is_taken(ip_loopback, port), 0);
361}
362
345#ifdef WANT_SYNC_LIVE 363#ifdef WANT_SYNC_LIVE
346/* Reading an IPv4 multicast option back: Linux answers with an int, the BSDs 364/* Reading an IPv4 multicast option back: Linux answers with an int, the BSDs
347 with a single byte, so ask how much was written. */ 365 with a single byte, so ask how much was written. */
@@ -391,6 +409,7 @@ void test_socket(void) {
391 case_deferred_accept(); 409 case_deferred_accept();
392 case_connect_refused(); 410 case_connect_refused();
393 case_bind_failure(); 411 case_bind_failure();
412 case_a_taken_udp_address_is_noticed();
394#ifdef WANT_SYNC_LIVE 413#ifdef WANT_SYNC_LIVE
395 case_mcast_sender(); 414 case_mcast_sender();
396#endif 415#endif
diff --git a/tests/t_workqueue.c b/tests/t_workqueue.c
index c454e5b..660d882 100644
--- a/tests/t_workqueue.c
+++ b/tests/t_workqueue.c
@@ -6,6 +6,7 @@
6#include <string.h> 6#include <string.h>
7 7
8/* Opentracker */ 8/* Opentracker */
9#include "ot_fdstate.h"
9#include "ot_workqueue.h" 10#include "ot_workqueue.h"
10#include "test.h" 11#include "test.h"
11 12
@@ -96,10 +97,61 @@ static void case_cancelled_task_is_not_handed_out(void) {
96 workqueue_canceltask(48); 97 workqueue_canceltask(48);
97} 98}
98 99
100/* Tasks are filed under a descriptor number, and the number is handed to the
101 next connection the moment this one closes. */
102
103static void case_cancel_takes_every_task_of_the_socket(void) {
104 ot_tasktype asked;
105
106 test_case("cancelling a socket leaves none of its tasks behind");
107 CHECK_INT(workqueue_pushtask(49, TASK_FULLSCRAPE_TPB_ASCII), 0);
108 CHECK_INT(workqueue_pushtask(49, TASK_FULLSCRAPE_TPB_BINARY), 0);
109 CHECK_INT(workqueue_pushtask(50, TASK_FULLSCRAPE), 0);
110 workqueue_canceltask(49);
111
112 asked = TASK_FULLSCRAPE;
113 CHECK(workqueue_poptask(&asked) != 0);
114 CHECK_INT(asked, TASK_FULLSCRAPE);
115 workqueue_canceltask(50);
116}
117
118static void case_result_names_the_connection_that_asked(void) {
119 ot_tasktype asked = TASK_STATS;
120 ot_taskid taskid;
121 struct iovec *iovector;
122 size_t iovec_entries;
123 int is_partial;
124 uint32_t asked_under, answered_under = ~0u;
125
126 CHECK_INT(fdstate_init(), 0);
127 asked_under = fdstate_open(51, NULL, 0);
128
129 test_case("a result comes back with the generation its task was pushed under");
130 CHECK_INT(workqueue_pushtask(51, TASK_STATS_PEERS), 0);
131 taskid = workqueue_poptask(&asked);
132 CHECK(taskid != 0);
133
134 /* The connection goes away without cancelling and the number is reused */
135 fdstate_close(51);
136 fdstate_open(51, NULL, 0);
137
138 CHECK_INT(workqueue_pushresult(taskid, 0, NULL), 0);
139 CHECK_INT(workqueue_popresult(&iovec_entries, &iovector, &is_partial, &answered_under), 51);
140 CHECK_INT(answered_under, asked_under);
141
142 test_case("which is no longer the one the descriptor carries");
143 CHECK(fdstate_generation(51) != answered_under);
144
145 fdstate_close(51);
146 fdstate_deinit();
147}
148
99void test_workqueue(void) { 149void test_workqueue(void) {
100 case_task_goes_to_its_own_class(); 150 case_task_goes_to_its_own_class();
101 case_flags_survive_the_queue(); 151 case_flags_survive_the_queue();
102 case_classes_do_not_cross(); 152 case_classes_do_not_cross();
103 case_every_task_gets_its_own_id(); 153 case_every_task_gets_its_own_id();
104 case_cancelled_task_is_not_handed_out(); 154 case_cancelled_task_is_not_handed_out();
155 case_cancel_takes_every_task_of_the_socket();
156 case_result_names_the_connection_that_asked();
105} 157}