summaryrefslogtreecommitdiff
path: root/src/ot_http.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/ot_http.c')
-rw-r--r--src/ot_http.c831
1 files changed, 831 insertions, 0 deletions
diff --git a/src/ot_http.c b/src/ot_http.c
new file mode 100644
index 0000000..2e21546
--- /dev/null
+++ b/src/ot_http.c
@@ -0,0 +1,831 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#define _GNU_SOURCE
6#include <arpa/inet.h>
7#include <errno.h>
8#include <pthread.h>
9#include <stdio.h>
10#include <stdlib.h>
11#include <string.h>
12#include <strings.h>
13#include <sys/types.h>
14#include <unistd.h>
15
16/* Opentracker */
17#include "ot_accesslist.h"
18#include "ot_fullscrape.h"
19#include "ot_http.h"
20#include "ot_iovec.h"
21#include "ot_ip.h"
22#include "ot_mutex.h"
23#include "ot_workqueue.h"
24#include "ot_scan.h"
25#include "ot_event.h"
26#include "ot_fdstate.h"
27#include "ot_vector.h"
28#include "ot_fmt.h"
29#include "ot_stats.h"
30#include "ot_urlencoded.h"
31#include "trackerlogic.h"
32
33#define OT_MAXMULTISCRAPE_COUNT 64
34extern const char *g_redirecturl;
35
36const char *g_stats_path;
37ssize_t g_stats_path_len;
38
39enum { SUCCESS_HTTP_HEADER_LENGTH = 80, SUCCESS_HTTP_SIZE_OFF = 17 };
40
41struct http_data *http_adopt(const int64_t sock) {
42 struct http_data *cookie = fdstate_cookie(sock), *heap;
43 int interest;
44
45 if (!cookie || !(cookie->flag & STRUCT_HTTP_FLAG_ONSTACK))
46 return cookie;
47
48 if (!(heap = malloc(sizeof(*heap))))
49 return NULL;
50
51 *heap = *cookie;
52 heap->flag &= ~STRUCT_HTTP_FLAG_ONSTACK;
53
54 /* Publishing the cookie is what lets another thread reach this connection,
55 so nothing may touch it afterwards, not even to read what it asked for */
56 interest = heap->interest;
57 fdstate_set_cookie((int)sock, heap);
58
59 if (event_add((int)sock, interest, fdstate_generation((int)sock)) == -1) {
60 fdstate_set_cookie((int)sock, cookie);
61 free(heap);
62 return NULL;
63 }
64 return heap;
65}
66
67/* Give up a connection: the one place that knows everything hanging off it. */
68void http_close(const int64_t sock) {
69 struct http_data *cookie = fdstate_cookie(sock);
70
71 fdstate_close((int)sock);
72
73 if (cookie) {
74 if (cookie->batch)
75 batch_reset(cookie->batch);
76 free(cookie->batch);
77 buf_reset(&cookie->request);
78 if (cookie->flag & (STRUCT_HTTP_FLAG_WAITINGFORTASK | STRUCT_HTTP_FLAG_CHUNKED_IN_TRANSFER))
79 workqueue_canceltask(sock);
80 if (!(cookie->flag & STRUCT_HTTP_FLAG_ONSTACK))
81 free(cookie);
82 }
83
84 event_close((int)sock);
85}
86
87static void http_senddata(const int64_t sock, struct ot_workstruct *ws) {
88 struct http_data *cookie = fdstate_cookie(sock);
89 ssize_t written_size;
90
91 if (!cookie) {
92 http_close(sock);
93 return;
94 }
95
96 /* whoever sends data is not interested in its input buffer */
97 if (ws->keep_alive && ws->header_size != ws->request_size) {
98 size_t rest = ws->request_size - ws->header_size;
99 if (cookie->request.data) {
100 memmove(cookie->request.data, ws->request + ws->header_size, rest);
101 buf_truncate(&cookie->request, rest);
102 } else if (buf_cat(&cookie->request, ws->request + ws->header_size, rest)) {
103 /* Without room for what the client pipelined behind this request, answer
104 this one and let the connection close, rather than keeping it open
105 around a request we have silently dropped */
106 buf_reset(&cookie->request);
107 ws->keep_alive = 0;
108 }
109 } else
110 buf_reset(&cookie->request);
111
112 written_size = write(sock, ws->reply, ws->reply_size);
113 /* A send buffer with no room in it is not a failure: nothing went out, so
114 the whole reply goes into the batch below and leaves when the socket
115 drains. Only a real error ends the connection here. */
116 if (written_size < 0 && (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR))
117 written_size = 0;
118
119 if ((written_size < 0) || ((written_size == ws->reply_size) && !ws->keep_alive)) {
120 http_close(sock);
121 return;
122 }
123
124 if (written_size < ws->reply_size) {
125 char *outbuf;
126
127 if (!(outbuf = malloc(ws->reply_size - written_size))) {
128 http_close(sock);
129 return;
130 }
131
132 memcpy(outbuf, ws->reply + written_size, ws->reply_size - written_size);
133 if (!cookie->batch) {
134 cookie->batch = calloc(1, sizeof(ot_batch));
135 if (!cookie->batch) {
136 free(outbuf);
137 http_close(sock);
138 return;
139 }
140 }
141
142 batch_add(cookie->batch, outbuf, ws->reply_size - written_size);
143
144 /* Reset any connections potentially near their timeout */
145 if (!ws->keep_alive)
146 fdstate_set_expiry(sock, time_future_seconds(OT_CLIENT_TIMEOUT_SEND));
147 http_interest_set(sock, cookie, EVENT_OUT);
148 }
149}
150
151#define HTTPERROR_302 return http_issue_error(sock, ws, CODE_HTTPERROR_302)
152#define HTTPERROR_400 return http_issue_error(sock, ws, CODE_HTTPERROR_400)
153#define HTTPERROR_400_PARAM return http_issue_error(sock, ws, CODE_HTTPERROR_400_PARAM)
154#define HTTPERROR_400_COMPACT return http_issue_error(sock, ws, CODE_HTTPERROR_400_COMPACT)
155#define HTTPERROR_400_DOUBLEHASH return http_issue_error(sock, ws, CODE_HTTPERROR_400_PARAM)
156#define HTTPERROR_402_NOTMODEST return http_issue_error(sock, ws, CODE_HTTPERROR_402_NOTMODEST)
157#define HTTPERROR_403_IP return http_issue_error(sock, ws, CODE_HTTPERROR_403_IP)
158#define HTTPERROR_404 return http_issue_error(sock, ws, CODE_HTTPERROR_404)
159#define HTTPERROR_500 return http_issue_error(sock, ws, CODE_HTTPERROR_500)
160/* A connection is either being read or being written, never both, so what it
161 waits for is set outright rather than added to and taken away again. The
162 event layer only hears about it when the answer changes. */
163void http_interest_set(const int64_t sock, struct http_data *cookie, int what) {
164 if (cookie->interest == what)
165 return;
166 cookie->interest = what;
167 /* Still on a stack, so not in the event loop yet: whoever adopts this
168 connection registers whatever it asked for last */
169 if (cookie->flag & STRUCT_HTTP_FLAG_ONSTACK)
170 return;
171 event_modify((int)sock, what, fdstate_generation((int)sock));
172}
173
174ssize_t http_issue_error(const int64_t sock, struct ot_workstruct *ws, int code) {
175 const char *error_code[] = {"302 Found", "400 Invalid Request", "400 Invalid Request", "400 Invalid Request", "402 Payment Required",
176 "403 Not Modest", "403 Access Denied", "404 Not Found", "500 Internal Server Error"};
177 const char *title = error_code[code];
178
179 ws->reply = ws->outbuf;
180 if (code == CODE_HTTPERROR_302)
181 ws->reply_size = snprintf(ws->reply, G_OUTBUF_SIZE, "HTTP/1.0 302 Found\r\nContent-Length: 0\r\nLocation: %s\r\n\r\n", g_redirecturl);
182 else
183 ws->reply_size = snprintf(ws->reply, G_OUTBUF_SIZE, "HTTP/1.0 %s\r\nContent-Type: text/html\r\nContent-Length: %zd\r\n\r\n<title>%s</title>\n", title,
184 strlen(title) + 16 - 4, title + 4);
185
186#ifdef _DEBUG_HTTPERROR
187 fprintf(stderr, "DEBUG: invalid request was: %s\n", ws->debugbuf);
188#endif
189 stats_issue_event(ws, EVENT_FAILED, FLAG_TCP, code);
190 http_senddata(sock, ws);
191 return ws->reply_size = -2;
192}
193
194ssize_t http_sendiovecdata(const int64_t sock, struct ot_workstruct *ws, size_t iovec_entries, struct iovec *iovector, int is_partial) {
195 struct http_data *cookie = fdstate_cookie(sock);
196 char *header;
197 const char *encoding = "";
198 size_t header_size, size = iovec_length(&iovec_entries, (const struct iovec **)&iovector);
199
200 /* No cookie? Bad socket. Leave. */
201 if (!cookie) {
202 iovec_free(&iovec_entries, &iovector);
203 HTTPERROR_500;
204 }
205
206 /* Descriptor numbers get recycled, so a result can only belong to this
207 connection if this connection is in fact waiting for one. */
208 if (!(cookie->flag & (STRUCT_HTTP_FLAG_WAITINGFORTASK | STRUCT_HTTP_FLAG_CHUNKED_IN_TRANSFER))) {
209 iovec_free(&iovec_entries, &iovector);
210 return 0;
211 }
212
213 /* If this socket collected request in a buffer, free it now */
214 buf_reset(&cookie->request);
215
216 /* If we came here, wait for the answer is over */
217 if (cookie->flag & STRUCT_HTTP_FLAG_WAITINGFORTASK) {
218 http_interest_set(sock, cookie, 0);
219 cookie->flag &= ~STRUCT_HTTP_FLAG_WAITINGFORTASK;
220 }
221
222 if (iovec_entries) {
223
224 if (cookie->flag & STRUCT_HTTP_FLAG_ZSTD)
225 encoding = "Content-Encoding: zstd\r\n";
226 else if (cookie->flag & STRUCT_HTTP_FLAG_GZIP)
227 encoding = "Content-Encoding: gzip\r\n";
228 else if (cookie->flag & STRUCT_HTTP_FLAG_BZIP2)
229 encoding = "Content-Encoding: bzip2\r\n";
230
231 if (!(cookie->flag & STRUCT_HTTP_FLAG_CHUNKED))
232 header_size = asprintf(&header, "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n%sContent-Length: %zd\r\n\r\n", encoding, size);
233 else {
234 if (!(cookie->flag & STRUCT_HTTP_FLAG_CHUNKED_IN_TRANSFER)) {
235 header_size =
236 asprintf(&header, "HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\n%sTransfer-Encoding: chunked\r\n\r\n%zx\r\n", encoding, size);
237 cookie->flag |= STRUCT_HTTP_FLAG_CHUNKED_IN_TRANSFER;
238 } else
239 header_size = asprintf(&header, "%zx\r\n", size);
240 }
241 if (!header) {
242 iovec_free(&iovec_entries, &iovector);
243 HTTPERROR_500;
244 }
245
246 if (!cookie->batch) {
247 cookie->batch = calloc(1, sizeof(ot_batch));
248 if (!cookie->batch) {
249 free(header);
250 iovec_free(&iovec_entries, &iovector);
251 HTTPERROR_500;
252 }
253 }
254
255 batch_add(cookie->batch, header, header_size);
256 batch_add_vector(cookie->batch, iovector, iovec_entries);
257 free(iovector);
258
259 if (cookie->flag & STRUCT_HTTP_FLAG_CHUNKED_IN_TRANSFER)
260 batch_add_copy(cookie->batch, "\r\n", 2);
261 }
262
263 if ((cookie->flag & STRUCT_HTTP_FLAG_CHUNKED_IN_TRANSFER) && cookie->batch && !is_partial) {
264 batch_add_copy(cookie->batch, "0\r\n\r\n", 5);
265 cookie->flag &= ~STRUCT_HTTP_FLAG_CHUNKED_IN_TRANSFER;
266 }
267
268 fdstate_set_expiry(sock, time_future_seconds(OT_CLIENT_TIMEOUT_SEND));
269 http_interest_set(sock, cookie, EVENT_OUT);
270 return 0;
271}
272
273static ssize_t http_handle_stats(const int64_t sock, struct ot_workstruct *ws, char *read_ptr) {
274 static const ot_keywords keywords_main[] = {{"mode", 1}, {"format", 2}, {"info_hash", 3}, {NULL, -3}};
275 static const ot_keywords keywords_mode[] = {{"peer", TASK_STATS_PEERS},
276 {"conn", TASK_STATS_CONNS},
277 {"scrp", TASK_STATS_SCRAPE},
278 {"udp4", TASK_STATS_UDP},
279 {"tcp4", TASK_STATS_TCP},
280 {"torr", TASK_STATS_TORRENTS},
281 {"fscr", TASK_STATS_FULLSCRAPE},
282 {"tpbs", TASK_STATS_TPB},
283 {"herr", TASK_STATS_HTTPERRORS},
284 {"completed", TASK_STATS_COMPLETED},
285 {"top100", TASK_STATS_TOP100},
286 {"top10", TASK_STATS_TOP10},
287 {"renew", TASK_STATS_RENEW},
288 {"syncs", TASK_STATS_SYNCS},
289 {"everything", TASK_STATS_EVERYTHING},
290 {"statedump", TASK_FULLSCRAPE_TRACKERSTATE},
291 {"woodpeckers", TASK_STATS_WOODPECKERS},
292#ifdef WANT_LOG_NUMWANT
293 {"numwants", TASK_STATS_NUMWANTS},
294#endif
295 {NULL, -3}};
296 static const ot_keywords keywords_format[] = {{"bin", TASK_FULLSCRAPE_TPB_BINARY}, {"ben", TASK_FULLSCRAPE},
297 {"url", TASK_FULLSCRAPE_TPB_URLENCODED}, {"txt", TASK_FULLSCRAPE_TPB_ASCII},
298 {"txtp", TASK_FULLSCRAPE_TPB_ASCII_PLUS}, {NULL, -3}};
299
300 struct http_data *cookie = fdstate_cookie(sock);
301 char *reply;
302 int mode = TASK_STATS_PEERS, scanon = 1, format = 0;
303
304 /* A socket without one is a dead socket, which is what http_sendiovecdata
305 already answers 500 to. */
306 if (!cookie)
307 HTTPERROR_500;
308
309#ifdef WANT_RESTRICT_STATS
310 if (!accesslist_is_blessed(cookie->ip, OT_PERMISSION_MAY_STAT))
311 HTTPERROR_403_IP;
312#endif
313
314 while (scanon) {
315 switch (urlencoded_match_keyword(keywords_main, &read_ptr, ws->request + ws->request_size, SCAN_SEARCHPATH_PARAM)) {
316 case -2:
317 scanon = 0;
318 break; /* TERMINATOR */
319 case -1:
320 HTTPERROR_400_PARAM; /* PARSE ERROR */
321 case -3:
322 urlencoded_skip_value(&read_ptr);
323 break;
324 case 1: /* matched "mode" */
325 if ((mode = urlencoded_match_keyword(keywords_mode, &read_ptr, ws->request + ws->request_size, SCAN_SEARCHPATH_VALUE)) <= 0)
326 HTTPERROR_400_PARAM;
327 break;
328 case 2: /* matched "format" */
329 if ((format = urlencoded_match_keyword(keywords_format, &read_ptr, ws->request + ws->request_size, SCAN_SEARCHPATH_VALUE)) <= 0)
330 HTTPERROR_400_PARAM;
331 break;
332 case 3:
333 HTTPERROR_400_PARAM; /* If the stats URL was mistakenly added as announce URL, return a 400 */
334 }
335 }
336
337#ifdef WANT_FULLSCRAPE
338 if (mode == TASK_FULLSCRAPE_TRACKERSTATE) {
339 format = mode;
340 mode = TASK_STATS_TPB;
341 }
342
343 if (mode == TASK_STATS_TPB) {
344#ifdef WANT_RESTRICT_FULLSCRAPE
345 if (!accesslist_is_blessed(cookie->ip, OT_PERMISSION_MAY_FULLSCRAPE))
346 HTTPERROR_403_IP;
347#endif
348#ifdef WANT_COMPRESSION_GZIP
349 ws->request[ws->request_size - 1] = 0;
350#ifndef WANT_COMPRESSION_GZIP_ALWAYS
351 if (strstr(read_ptr - 1, "gzip")) {
352#endif
353 cookie->flag |= STRUCT_HTTP_FLAG_GZIP;
354 format |= TASK_FLAG_GZIP;
355#ifndef WANT_COMPRESSION_GZIP_ALWAYS
356 }
357#endif
358#endif
359 cookie->flag |= STRUCT_HTTP_FLAG_WAITINGFORTASK | STRUCT_HTTP_FLAG_CHUNKED;
360
361 /* Clients waiting for us should not easily timeout */
362 fdstate_set_expiry(sock, 0);
363 http_interest_set(sock, cookie, 0);
364
365 /* Everything this connection needs has been written, so it can be given
366 a home of its own and only then be made reachable by a worker thread */
367 if (!http_adopt(sock))
368 HTTPERROR_500;
369 ws->handed_off = 1;
370 fullscrape_deliver(sock, format);
371 return ws->reply_size = -2;
372 }
373#endif
374
375 /* default format for now */
376 if ((mode & TASK_CLASS_MASK) == TASK_STATS) {
377
378 cookie->flag |= STRUCT_HTTP_FLAG_WAITINGFORTASK;
379
380 /* Complex stats also include expensive memory debugging tools */
381 fdstate_set_expiry(sock, 0);
382 http_interest_set(sock, cookie, 0);
383
384 if (!http_adopt(sock))
385 HTTPERROR_500;
386 ws->handed_off = 1;
387 stats_deliver(sock, mode);
388 return ws->reply_size = -2;
389 }
390
391 /* Simple stats can be answerred immediately */
392 reply = ws->reply;
393 return_stats_for_tracker(&reply, ws->outbuf + G_OUTBUF_SIZE, mode, 0);
394 return ws->reply_size = reply - ws->reply;
395}
396
397#ifdef WANT_MODEST_FULLSCRAPES
398static pthread_mutex_t g_modest_fullscrape_mutex = PTHREAD_MUTEX_INITIALIZER;
399static ot_vector g_modest_fullscrape_timeouts;
400typedef struct {
401 ot_ip6 ip;
402 ot_time last_fullscrape;
403} ot_scrape_log;
404#endif
405
406#ifdef WANT_FULLSCRAPE
407static ssize_t http_handle_fullscrape(const int64_t sock, struct ot_workstruct *ws) {
408 struct http_data *cookie = fdstate_cookie(sock);
409 int format = 0;
410
411 if (!cookie)
412 HTTPERROR_500;
413
414#ifdef WANT_RESTRICT_FULLSCRAPE
415 if (!accesslist_is_blessed(cookie->ip, OT_PERMISSION_MAY_FULLSCRAPE))
416 HTTPERROR_403_IP;
417#endif
418
419#ifdef WANT_MODEST_FULLSCRAPES
420 {
421 ot_scrape_log this_peer, *new_peer;
422 int exactmatch;
423 memcpy(this_peer.ip, cookie->ip, sizeof(ot_ip6));
424 this_peer.last_fullscrape = time_now_seconds();
425 pthread_mutex_lock(&g_modest_fullscrape_mutex);
426 new_peer = vector_find_or_insert(&g_modest_fullscrape_timeouts, &this_peer, sizeof(ot_scrape_log), sizeof(ot_ip6), &exactmatch);
427 if (!new_peer) {
428 pthread_mutex_unlock(&g_modest_fullscrape_mutex);
429 HTTPERROR_500;
430 }
431 if (exactmatch && time_since_seconds(new_peer->last_fullscrape) < OT_MODEST_PEER_TIMEOUT) {
432 pthread_mutex_unlock(&g_modest_fullscrape_mutex);
433 HTTPERROR_402_NOTMODEST;
434 }
435 memcpy(new_peer, &this_peer, sizeof(ot_scrape_log));
436 pthread_mutex_unlock(&g_modest_fullscrape_mutex);
437 }
438#endif
439
440
441#if defined(WANT_COMPRESSION_GZIP) || defined(WANT_COMPRESSION_ZSTD)
442 ws->request[ws->request_size - 1] = 0;
443#ifdef WANT_COMPRESSION_GZIP
444 if (strstr(ws->request, "gzip")) {
445 cookie->flag |= STRUCT_HTTP_FLAG_GZIP;
446 format |= TASK_FLAG_GZIP;
447 }
448#endif
449#ifdef WANT_COMPRESSION_ZSTD
450 if (strstr(ws->request, "zstd")) {
451 cookie->flag |= STRUCT_HTTP_FLAG_ZSTD;
452 format |= TASK_FLAG_ZSTD;
453 }
454#endif
455
456#if defined(WANT_COMPRESSION_ZSTD) && defined(WANT_COMPRESSION_ZSTD_ALWAYS)
457 cookie->flag |= STRUCT_HTTP_FLAG_ZSTD;
458 format |= TASK_FLAG_ZSTD;
459#endif
460
461#if defined(WANT_COMPRESSION_GZIP) && defined(WANT_COMPRESSION_GZIP_ALWAYS)
462 cookie->flag |= STRUCT_HTTP_FLAG_GZIP;
463 format |= TASK_FLAG_GZIP;
464#endif
465#endif
466
467 stats_issue_event(ws, EVENT_FULLSCRAPE_REQUEST, 0, (uintptr_t)cookie->ip);
468
469#ifdef _DEBUG_HTTPERROR
470 fprintf(stderr, "%s", ws->debugbuf);
471#endif
472
473 /* Pass this task to the worker thread */
474 cookie->flag |= STRUCT_HTTP_FLAG_WAITINGFORTASK | STRUCT_HTTP_FLAG_CHUNKED;
475 /* Clients waiting for us should not easily timeout */
476 fdstate_set_expiry(sock, 0);
477 http_interest_set(sock, cookie, 0);
478
479 if (!http_adopt(sock))
480 HTTPERROR_500;
481 ws->handed_off = 1;
482 fullscrape_deliver(sock, format);
483 return ws->reply_size = -2;
484}
485#endif
486
487static int compare_hash(const void *left, const void *right) { return memcmp(left, right, sizeof(ot_hash)); }
488
489static ssize_t http_handle_scrape(const int64_t sock, struct ot_workstruct *ws, char *read_ptr) {
490 static const ot_keywords keywords_scrape[] = {{"info_hash", 1}, {NULL, -3}};
491
492 ot_hash *multiscrape_buf = (ot_hash *)ws->request;
493 char *reply = ws->reply;
494 int scanon = 1;
495 size_t i, unique, numwant = 0;
496
497 /* This is to hack around stupid clients that send "scrape ?info_hash" */
498 if (read_ptr[-1] != '?') {
499 while ((*read_ptr != '?') && (*read_ptr != '\n'))
500 ++read_ptr;
501 if (*read_ptr == '\n')
502 HTTPERROR_400_PARAM;
503 ++read_ptr;
504 }
505
506 while (scanon) {
507 switch (urlencoded_match_keyword(keywords_scrape, &read_ptr, ws->request + ws->request_size, SCAN_SEARCHPATH_PARAM)) {
508 case -2:
509 scanon = 0;
510 break; /* TERMINATOR */
511 default:
512 HTTPERROR_400_PARAM; /* PARSE ERROR */
513 case -3:
514 urlencoded_skip_value(&read_ptr);
515 break;
516 case 1: /* matched "info_hash" */
517 {
518 /* ignore this, when we have less than 20 bytes */
519 ot_hash *slot = multiscrape_buf + numwant++;
520 if (urlencoded_parse(&read_ptr, (char *)slot, (char *)(slot + 1), SCAN_SEARCHPATH_VALUE) != (ssize_t)sizeof(ot_hash))
521 HTTPERROR_400_PARAM;
522 } break;
523 }
524 }
525
526 /* No info_hash found? Inform user */
527 if (!numwant)
528 HTTPERROR_400_PARAM;
529
530 /* Limit number of hashes to process */
531 if (numwant > OT_MAXMULTISCRAPE_COUNT)
532 numwant = OT_MAXMULTISCRAPE_COUNT;
533
534 /* A bencoded dictionary has its keys in order and names each one once, so
535 the answer cannot just follow the order the client asked in */
536 qsort(multiscrape_buf, numwant, sizeof(ot_hash), compare_hash);
537 for (i = unique = 1; i < numwant; ++i)
538 if (memcmp(multiscrape_buf[i], multiscrape_buf[unique - 1], sizeof(ot_hash)))
539 memmove(multiscrape_buf[unique++], multiscrape_buf[i], sizeof(ot_hash));
540 numwant = unique;
541
542 /* Enough for http header + whole scrape string */
543 return_tcp_scrape_for_torrent((const ot_hash *)multiscrape_buf, numwant, &reply, ws->outbuf + G_OUTBUF_SIZE);
544 ws->reply_size = reply - ws->reply;
545 stats_issue_event(ws, EVENT_SCRAPE, FLAG_TCP, ws->reply_size);
546 return ws->reply_size;
547}
548
549#ifdef WANT_LOG_NUMWANT
550unsigned long long numwants[201];
551#endif
552
553#if defined(WANT_KEEPALIVE) || defined(WANT_IP_FROM_PROXY)
554static char *http_header(char *data, size_t byte_count, const char *header) {
555 size_t i;
556 long sl = strlen(header);
557 for (i = 0; i + sl + 2 < byte_count; ++i) {
558 if (data[i] != '\n' || data[i + sl + 1] != ':')
559 continue;
560 if (strncasecmp(data + i + 1, header, sl))
561 continue;
562 data += i + sl + 2;
563 while (*data == ' ' || *data == '\t')
564 ++data;
565 return data;
566 }
567 return 0;
568}
569#endif
570
571static ot_keywords keywords_announce[] = {{"port", 1}, {"left", 2}, {"event", 3}, {"numwant", 4}, {"compact", 5}, {"compact6", 5}, {"info_hash", 6},
572#ifdef WANT_IP_FROM_QUERY_STRING
573 {"ip", 7},
574#endif
575 {"peer_id", 8}, {NULL, -3}};
576static ot_keywords keywords_announce_event[] = {{"completed", 1}, {"stopped", 2}, {NULL, -3}};
577
578/* For the replies that are one fixed string and nothing else, where the only
579 thing the caller wants back is how long it turned out */
580static ssize_t reply_literal(struct ot_workstruct *ws, const char *text) {
581 char *reply = ws->reply;
582
583 fmt_bytes(&reply, ws->outbuf + G_OUTBUF_SIZE, text, strlen(text));
584 return reply - ws->reply;
585}
586
587static ssize_t http_handle_announce(const int64_t sock, struct ot_workstruct *ws, char *read_ptr) {
588 size_t numwant;
589 int64_t tmp;
590 int scanon;
591 unsigned short port = 0;
592 char *write_ptr;
593 ssize_t len;
594 struct http_data *cookie = fdstate_cookie(sock);
595
596 /* This is to hack around stupid clients that send "announce ?info_hash" */
597 if (read_ptr[-1] != '?') {
598 while ((*read_ptr != '?') && (*read_ptr != '\n'))
599 ++read_ptr;
600 if (*read_ptr == '\n')
601 HTTPERROR_400_PARAM;
602 ++read_ptr;
603 }
604
605#ifdef WANT_IP_FROM_PROXY
606 if (accesslist_is_blessed(cookie->ip, OT_PERMISSION_MAY_PROXY)) {
607 ot_ip6 proxied_ip;
608 char *fwd = http_header(ws->request, ws->header_size, "x-forwarded-for");
609 if (fwd && ip_parse(fwd, proxied_ip)) {
610 OT_SETIP(ws->peer, proxied_ip);
611 } else
612 OT_SETIP(ws->peer, cookie->ip);
613 } else
614#endif
615 OT_SETIP(ws->peer, cookie->ip);
616
617 ws->peer_id = NULL;
618 ws->hash = NULL;
619
620 OT_SETPORT(ws->peer, &port);
621 OT_PEERFLAG(ws->peer) = 0;
622 numwant = 50;
623 scanon = 1;
624
625 while (scanon) {
626 switch (urlencoded_match_keyword(keywords_announce, &read_ptr, ws->request + ws->request_size, SCAN_SEARCHPATH_PARAM)) {
627 case -2:
628 scanon = 0;
629 break; /* TERMINATOR */
630 case -1:
631 HTTPERROR_400_PARAM; /* PARSE ERROR */
632 case -3:
633 urlencoded_skip_value(&read_ptr);
634 break;
635 case 1: /* matched "port" */
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 < 0) || (tmp > 0xffff))
638 HTTPERROR_400_PARAM;
639 port = htons((uint16_t)tmp);
640 OT_SETPORT(&ws->peer, &port);
641 break;
642 case 2: /* matched "left" */
643 if ((len = urlencoded_parse(&read_ptr, write_ptr = read_ptr, ws->request + ws->request_size, SCAN_SEARCHPATH_VALUE)) <= 0)
644 HTTPERROR_400_PARAM;
645 if (scan_int(write_ptr, len, &tmp))
646 tmp = 0;
647 if (!tmp)
648 OT_PEERFLAG(&ws->peer) |= PEER_FLAG_SEEDING;
649 break;
650 case 3: /* matched "event" */
651 switch (urlencoded_match_keyword(keywords_announce_event, &read_ptr, ws->request + ws->request_size, SCAN_SEARCHPATH_VALUE)) {
652 case -1:
653 HTTPERROR_400_PARAM;
654 case 1: /* matched "completed" */
655 OT_PEERFLAG(&ws->peer) |= PEER_FLAG_COMPLETED;
656 break;
657 case 2: /* matched "stopped" */
658 OT_PEERFLAG(&ws->peer) |= PEER_FLAG_STOPPED;
659 break;
660 default:
661 break;
662 }
663 break;
664 case 4: /* matched "numwant" */
665 len = urlencoded_parse(&read_ptr, write_ptr = read_ptr, ws->request + ws->request_size, SCAN_SEARCHPATH_VALUE);
666 if ((len <= 0) || scan_int(write_ptr, len, &tmp))
667 HTTPERROR_400_PARAM;
668 if (tmp < 0)
669 tmp = 50;
670 if (tmp > 200)
671 tmp = 200;
672 numwant = (size_t)tmp;
673 break;
674 case 5: /* matched "compact" */
675 len = urlencoded_parse(&read_ptr, write_ptr = read_ptr, ws->request + ws->request_size, SCAN_SEARCHPATH_VALUE);
676 if ((len <= 0) || scan_int(write_ptr, len, &tmp))
677 HTTPERROR_400_PARAM;
678 if (!tmp)
679 HTTPERROR_400_COMPACT;
680 break;
681 case 6: /* matched "info_hash" */
682 if (ws->hash)
683 HTTPERROR_400_DOUBLEHASH;
684 /* ignore this, when we have less than 20 bytes */
685 if (urlencoded_parse(&read_ptr, write_ptr = read_ptr, ws->request + ws->request_size, SCAN_SEARCHPATH_VALUE) != 20)
686 HTTPERROR_400_PARAM;
687 ws->hash = (ot_hash *)write_ptr;
688 break;
689#ifdef WANT_IP_FROM_QUERY_STRING
690 case 7: /* matched "ip" */
691 {
692 char *tmp_buf1 = ws->reply, *tmp_buf2 = ws->reply + 16;
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);
695 if (len <= 0)
696 HTTPERROR_400_PARAM;
697 tmp_buf2[len] = 0;
698 if (ip_parse(tmp_buf2, tmp_buf1) != (size_t)len)
699 HTTPERROR_400_PARAM;
700 OT_SETIP(&ws->peer, tmp_buf1);
701 } break;
702#endif
703 case 8: /* matched "peer_id" */
704 /* ignore this, when we have less than 20 bytes */
705 if (urlencoded_parse(&read_ptr, write_ptr = read_ptr, ws->request + ws->request_size, SCAN_SEARCHPATH_VALUE) != 20)
706 HTTPERROR_400_PARAM;
707 ws->peer_id = write_ptr;
708 break;
709 }
710 }
711
712#ifdef WANT_LOG_NUMWANT
713 numwants[numwant]++;
714#endif
715
716 /* XXX DEBUG
717 stats_issue_event(ws, EVENT_ACCEPT, FLAG_TCP, (uintptr_t)ws->reply );
718 */
719
720 /* Scanned whole query string */
721 if (!ws->hash)
722 return ws->reply_size = reply_literal(ws, "d14:failure reason80:Your client forgot to send your torrent's info_hash. Please upgrade your client.e");
723
724 if (OT_PEERFLAG(&ws->peer) & PEER_FLAG_STOPPED)
725 ws->reply_size = remove_peer_from_torrent(FLAG_TCP, ws);
726 else
727 ws->reply_size = add_peer_to_torrent_and_return_peers(FLAG_TCP, ws, numwant);
728
729 stats_issue_event(ws, EVENT_ANNOUNCE, FLAG_TCP, ws->reply_size);
730 return ws->reply_size;
731}
732
733ssize_t http_handle_request(const int64_t sock, struct ot_workstruct *ws) {
734 ssize_t reply_off, len;
735 char *read_ptr = ws->request, *write_ptr;
736
737#ifdef _DEBUG_HTTPERROR
738 reply_off = ws->request_size;
739 if (ws->request_size >= G_DEBUGBUF_SIZE)
740 reply_off = G_DEBUGBUF_SIZE - 1;
741 memcpy(ws->debugbuf, ws->request, reply_off);
742 ws->debugbuf[reply_off] = 0;
743#endif
744
745 /* Tell subroutines where to put reply data */
746 ws->reply = ws->outbuf + SUCCESS_HTTP_HEADER_LENGTH;
747
748 /* Find out if the client wants to keep this connection alive, before any
749 subroutine gets to answer: an error reply finishes with the connection
750 on its way out, and ws outlives the connection it was serving */
751 ws->keep_alive = 0;
752 ws->handed_off = 0;
753#ifdef WANT_KEEPALIVE
754 if ((write_ptr = http_header(ws->request, ws->header_size, "connection")) && (*write_ptr == 'K' || *write_ptr == 'k'))
755 ws->keep_alive = 1;
756#endif
757 {
758 struct http_data *connection = fdstate_cookie(sock);
759 if (connection) {
760 if (ws->keep_alive)
761 connection->flag |= STRUCT_HTTP_FLAG_KEEPALIVE;
762 else
763 connection->flag &= ~STRUCT_HTTP_FLAG_KEEPALIVE;
764 }
765 }
766
767 /* The request need not be NUL terminated and can be shorter than the literal */
768 if (ws->request_size < 5 || memcmp(read_ptr, "GET /", 5))
769 HTTPERROR_400;
770
771 /* Skip leading '/' */
772 for (read_ptr += 4; *read_ptr == '/'; ++read_ptr)
773 ;
774
775 /* Try to parse the request.
776 In reality we abandoned requiring the url to be correct. This now
777 only decodes url encoded characters, we check for announces and
778 scrapes by looking for "a*" or "sc" */
779 len = urlencoded_parse(&read_ptr, write_ptr = read_ptr, ws->request + ws->request_size, SCAN_PATH);
780
781 /* If parsing returned an error, leave with not found */
782 if (g_redirecturl && (len == -2))
783 HTTPERROR_302;
784 if (len <= 0)
785 HTTPERROR_404;
786
787 /* This is the hardcore match for announce*/
788 if ((*write_ptr == 'a') || (*write_ptr == '?'))
789 http_handle_announce(sock, ws, read_ptr);
790#ifdef WANT_FULLSCRAPE
791 else if (ws->request + ws->request_size - write_ptr >= 12 && !memcmp(write_ptr, "scrape HTTP/", 12))
792 http_handle_fullscrape(sock, ws);
793#endif
794 /* This is the hardcore match for scrape */
795 else if (!memcmp(write_ptr, "sc", 2))
796 http_handle_scrape(sock, ws, read_ptr);
797 /* All the rest is matched the standard way */
798 else if (len == g_stats_path_len && !memcmp(write_ptr, g_stats_path, len))
799 http_handle_stats(sock, ws, read_ptr);
800 else
801 HTTPERROR_404;
802
803 /* If routines handled sending themselves, just return */
804 if (ws->reply_size == -2)
805 return 0;
806 /* If routine failed, let http error take over */
807 if (ws->reply_size <= 0)
808 HTTPERROR_500;
809
810 /* This one is rather ugly, so I take you step by step through it.
811
812 1. In order to avoid having two buffers, one for header and one for content, we allow all above functions from trackerlogic to
813 write to a fixed location, leaving SUCCESS_HTTP_HEADER_LENGTH bytes in our work buffer, which is enough for the static string
814 plus dynamic space needed to expand our Content-Length value. We reserve SUCCESS_HTTP_SIZE_OFF for its expansion and calculate
815 the space NOT needed to expand in reply_off
816 */
817 reply_off = SUCCESS_HTTP_SIZE_OFF - snprintf(ws->outbuf, 0, "%zd", ws->reply_size);
818 ws->reply = ws->outbuf + reply_off;
819
820 /* 2. Now we write the header so that its terminating '\0' lands exactly one byte before the content starts. The bound is the
821 space step 1 reserved, so the '\0' falls where step 3 expects it. Complete packet size is increased by size of header plus
822 one byte '\n', we will copy over '\0' in next step */
823 ws->reply_size += 1 + snprintf(ws->reply, (size_t)(SUCCESS_HTTP_HEADER_LENGTH - reply_off),
824 "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: %zd\r\n\r", ws->reply_size);
825
826 /* 3. Finally we join both blocks neatly */
827 ws->outbuf[SUCCESS_HTTP_HEADER_LENGTH - 1] = '\n';
828
829 http_senddata(sock, ws);
830 return ws->reply_size;
831}