summaryrefslogtreecommitdiff
path: root/src/opentracker.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/opentracker.c')
-rw-r--r--src/opentracker.c473
1 files changed, 473 insertions, 0 deletions
diff --git a/src/opentracker.c b/src/opentracker.c
new file mode 100644
index 0000000..81b4df6
--- /dev/null
+++ b/src/opentracker.c
@@ -0,0 +1,473 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever.
3 Some of the stuff below is stolen from Fefes example libowfat httpd. */
4
5/* System */
6#include <ctype.h>
7#include <errno.h>
8#include <limits.h>
9#include <pthread.h>
10#include <grp.h>
11#include <pwd.h>
12#include <signal.h>
13#include <stdint.h>
14#include <stdio.h>
15#include <stdlib.h>
16#include <string.h>
17#include <sys/socket.h>
18#include <unistd.h>
19#ifdef WANT_SYSLOGS
20#include <syslog.h>
21#endif
22
23/* Opentracker */
24#include "ot_accesslist.h"
25#include "ot_config.h"
26#include "ot_hex.h"
27#include "ot_http.h"
28#include "ot_iovec.h"
29#include "ot_ip.h"
30#include "ot_livesync.h"
31#include "ot_mutex.h"
32#include "ot_workqueue.h"
33#include "ot_random.h"
34#include "ot_scan.h"
35#include "ot_event.h"
36#include "ot_fdstate.h"
37#include "ot_socket.h"
38#include "ot_stats.h"
39#include "ot_tcp.h"
40#include "ot_udp.h"
41#include "ot_worker.h"
42#include "trackerlogic.h"
43
44/* Globals */
45uint32_t g_tracker_id;
46_Atomic int g_opentracker_running = 1;
47int g_self_pipe[2];
48
49static void panic(const char *routine) __attribute__((noreturn));
50static void panic(const char *routine) {
51 fprintf(stderr, "%s: %s\n", routine, strerror(errno));
52 exit(111);
53}
54
55/* Say we are stopping, wake the loop, and let main do the work on its own
56 stack. Everything other than SIGINT falls through and does nothing, which
57 is what OT_SIGNAL_WAKE wants: returning from the read is all it is for. */
58static void signal_handler(int s) {
59 if (s == SIGINT) {
60 const char byte = 0;
61 int saved = errno;
62
63 /* Any new interrupt signal quits the application */
64 signal(SIGINT, SIG_DFL);
65
66 /* Tell all other threads to not acquire any new lock on a bucket
67 but cancel their operations and return */
68 g_opentracker_running = 0;
69
70 (void)!write(g_self_pipe[1], &byte, 1);
71 errno = saved;
72 }
73}
74
75static void defaul_signal_handlers(void) {
76 sigset_t signal_mask;
77 sigemptyset(&signal_mask);
78 sigaddset(&signal_mask, SIGPIPE);
79 sigaddset(&signal_mask, SIGHUP);
80 sigaddset(&signal_mask, SIGINT);
81 sigaddset(&signal_mask, SIGALRM);
82 pthread_sigmask(SIG_BLOCK, &signal_mask, NULL);
83}
84
85static void install_signal_handlers(void) {
86 struct sigaction sa;
87 sigset_t signal_mask;
88 sigemptyset(&signal_mask);
89
90 sa.sa_handler = signal_handler;
91 sigemptyset(&sa.sa_mask);
92 sa.sa_flags = 0;
93 if ((sigaction(SIGINT, &sa, NULL) == -1) || (sigaction(SIGALRM, &sa, NULL) == -1) ||
94 (sigaction(OT_SIGNAL_WAKE, &sa, NULL) == -1))
95 panic("install_signal_handlers");
96
97 sigaddset(&signal_mask, SIGINT);
98 pthread_sigmask(SIG_UNBLOCK, &signal_mask, NULL);
99}
100
101
102/* How many ready descriptors one wait hands back at a time */
103#define OT_EVENT_BATCH 512
104
105static void *server_mainloop(void *args) {
106 struct ot_workstruct ws;
107 time_t next_timeout_check = time_future_seconds(OT_CLIENT_TIMEOUT_CHECKINTERVAL);
108 struct iovec *iovector;
109 size_t iovec_entries;
110 int is_partial;
111 uint32_t generation;
112
113 (void)args;
114
115 if (workstruct_init(&ws, G_INBUF_SIZE) == -1)
116 panic("Initializing worker failed");
117
118 while (g_opentracker_running) {
119 ot_event ready[OT_EVENT_BATCH];
120 int64_t sock;
121 int count, i;
122
123 count = event_wait(ready, OT_EVENT_BATCH, OT_CLIENT_TIMEOUT_CHECKINTERVAL * 1000);
124
125 for (i = 0; i < count; ++i) {
126 const void *cookie;
127
128 sock = ready[i].fd;
129 /* A descriptor closed earlier in this same batch may already have been
130 handed out again by accept, so an event is only ours if the
131 generation it was registered under is still the one in place */
132 if (fdstate_generation((int)sock) != ready[i].generation)
133 continue;
134 cookie = fdstate_cookie((int)sock);
135
136 if ((intptr_t)cookie == FLAG_TCP)
137 tcp_accept(sock, &ws);
138 else if ((intptr_t)cookie == FLAG_UDP)
139 handle_udp6(sock, &ws);
140 else if ((intptr_t)cookie == FLAG_SELFPIPE)
141 while (read((int)sock, ws.inbuf, G_INBUF_SIZE) > 0)
142 ;
143 else if (fdstate_claim((int)sock, ready[i].generation)) {
144 if (ready[i].what & EVENT_IN)
145 tcp_read(sock, &ws);
146 /* The read may have closed it, so look again before writing */
147 if ((ready[i].what & EVENT_OUT) && fdstate_generation((int)sock) == ready[i].generation)
148 tcp_write(sock);
149 if (fdstate_generation((int)sock) == ready[i].generation)
150 fdstate_release((int)sock);
151 }
152 }
153
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 }
159 http_sendiovecdata(sock, &ws, iovec_entries, iovector, is_partial);
160 }
161
162 if (time_is_past(next_timeout_check)) {
163 int cursor = 0;
164
165 while ((sock = fdstate_next_expired(time_now_seconds(), &cursor)) != -1)
166 http_close(sock);
167 next_timeout_check = time_future_seconds(OT_CLIENT_TIMEOUT_CHECKINTERVAL);
168 }
169
170 livesync_ticker();
171 }
172
173 /* This work struct is about to go out of scope, so hand its tally over
174 before anything can read it there */
175 workstruct_deinit(&ws);
176 return 0;
177}
178
179
180/* A group of sockets sharing one address only spreads datagrams if every
181 member asked for it before binding, the first one included, so whether
182 this entry will have workers has to be known here. */
183static socket_sharing listen_sharing_for(const ot_listen *entry) {
184 if (entry->proto != FLAG_MCA && entry->workers > 1 && socket_can_balance())
185 return SOCKET_BALANCED;
186 return entry->shared ? SOCKET_SHARED : SOCKET_EXCLUSIVE;
187}
188
189static void listen_bind_one(ot_listen *entry) {
190 socket_sharing sharing = listen_sharing_for(entry);
191
192#ifdef _DEBUG
193 {
194 const char *protos[] = {"TCP", "UDP", "UDP mcast"};
195 char _debug[512];
196 int off = snprintf(_debug, sizeof(_debug), "Binding socket type %s to address [", protos[entry->proto]);
197 off += ip_format(_debug + off, entry->ip);
198 snprintf(_debug + off, sizeof(_debug) - off, "]:%d...", entry->port);
199 fputs(_debug, stderr);
200 }
201#endif
202
203#ifdef WANT_SYNC_LIVE
204 if (entry->proto == FLAG_MCA) {
205 livesync_bind_mcast(entry->ip, entry->port);
206#ifdef _DEBUG
207 fputs(" success.\n", stderr);
208#endif
209 return;
210 }
211#endif
212
213 if (entry->proto == FLAG_TCP) {
214 if ((entry->sock = socket_tcp_listen(entry->ip, entry->port, sharing)) == -1)
215 panic("socket_tcp_listen");
216 socket_defer_accept((int)entry->sock);
217 } else {
218 if ((entry->sock = socket_udp_bind(entry->ip, entry->port, sharing)) == -1)
219 panic("socket_udp_bind");
220 }
221
222 if (event_add((int)entry->sock, EVENT_IN, fdstate_open(entry->sock, (void *)entry->proto, 0)) == -1)
223 panic("event_add");
224
225#ifdef _DEBUG
226 fputs(" success.\n", stderr);
227#endif
228}
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
240/* Bound in the order the entries were given.
241 Note: On macOS SO_REUSEPORT delivers everything to the socket that bound last. */
242static void listen_bind_all(void) {
243 size_t count, i;
244 ot_listen *entries = config_listen_entries(&count);
245
246 for (i = 0; i < count; ++i)
247 listen_warn_if_taken(entries + i);
248
249 for (i = 0; i < count; ++i)
250 listen_bind_one(entries + i);
251}
252
253/* The socket the event loop was using is passed to the first worker.
254 If start up tests show that the kernel can spread connections over
255 a group bound to one address, every worker binds one of its own.
256 If not, all workers call accept on the first. */
257static void listen_start_tcp_workers(void) {
258 size_t count, i;
259 ot_listen *entries = config_listen_entries(&count);
260
261 for (i = 0; i < count; ++i) {
262 ot_listen *entry = entries + i;
263 int balance = listen_sharing_for(entry) == SOCKET_BALANCED;
264 int worker;
265
266 if (entry->proto != FLAG_TCP || entry->workers <= 0)
267 continue;
268
269 event_del((int)entry->sock);
270 tcp_worker_install(entry->sock);
271
272 for (worker = 1; worker < entry->workers; ++worker) {
273 int64_t sock = entry->sock;
274
275 if (balance) {
276 sock = socket_tcp_listen(entry->ip, entry->port, SOCKET_BALANCED);
277 if (sock == -1) {
278 fprintf(stderr, "Warning: could not bind another socket for tcp worker %d: %s. Sharing the first instead.\n", worker,
279 strerror(errno));
280 sock = entry->sock;
281 }
282 }
283 tcp_worker_install(sock);
284 }
285 }
286}
287
288static void listen_start_udp_workers(void) {
289 size_t count, i;
290 ot_listen *entries = config_listen_entries(&count);
291
292 udp_init();
293
294 for (i = 0; i < count; ++i) {
295 ot_listen *entry = entries + i;
296 int balance = listen_sharing_for(entry) == SOCKET_BALANCED;
297 int worker;
298
299 if (entry->proto != FLAG_UDP || entry->workers <= 0)
300 continue;
301
302 event_del((int)entry->sock);
303 udp_worker_install(entry->sock);
304
305 for (worker = 1; worker < entry->workers; ++worker) {
306 int64_t sock = entry->sock;
307
308 if (balance) {
309 sock = socket_udp_bind(entry->ip, entry->port, SOCKET_BALANCED);
310 if (sock == -1) {
311 fprintf(stderr, "Warning: could not bind another socket for udp worker %d: %s. Sharing the first instead.\n", worker, strerror(errno));
312 sock = entry->sock;
313 }
314 }
315 udp_worker_install(sock);
316 }
317 }
318}
319
320void load_state(const char *const state_filename) {
321 FILE *state_filehandle;
322 char inbuf[512];
323 ot_hash infohash;
324 uint64_t touched, downcount;
325 int consumed;
326
327 /* The file records the minute a torrent was last touched, by the clock that
328 survives a restart */
329 uint64_t now = (uint64_t)time_wall_minutes();
330
331 state_filehandle = fopen(state_filename, "r");
332
333 if (state_filehandle == NULL) {
334 fprintf(stderr, "Warning: Can't open config file: %s.", state_filename);
335 return;
336 }
337
338 /* We do ignore anything that is not of the form "^[:xdigit:]:\d+:\d+" */
339 while (fgets(inbuf, sizeof(inbuf), state_filehandle)) {
340 size_t i;
341
342 if (!hex_to_hash(infohash, inbuf))
343 continue;
344 i = 2 * sizeof(ot_hash);
345
346 if (inbuf[i++] != ':' || !(consumed = scan_uint(inbuf + i, &touched, now)))
347 continue;
348 i += consumed;
349 if (inbuf[i++] != ':' || !(consumed = scan_uint(inbuf + i, &downcount, SIZE_MAX)))
350 continue;
351 add_torrent_from_saved_state(infohash, (ot_time)(now - touched), (size_t)downcount);
352 }
353
354 fclose(state_filehandle);
355}
356
357int drop_privileges(const char *const serveruser, const char *const serverdir) {
358 struct passwd *pws = NULL;
359
360#ifdef _DEBUG
361 if (!geteuid())
362 fprintf(stderr, "Dropping to user %s.\n", serveruser);
363 if (serverdir)
364 fprintf(stderr, "ch%s'ing to directory %s.\n", geteuid() ? "dir" : "root", serverdir);
365#endif
366
367 /* Grab pws entry before chrooting */
368 pws = getpwnam(serveruser);
369 endpwent();
370
371 if (geteuid() == 0) {
372 /* Running as root: chroot and drop privileges */
373 if (serverdir && chroot(serverdir)) {
374 fprintf(stderr, "Could not chroot to %s, because: %s\n", serverdir, strerror(errno));
375 return -1;
376 }
377
378 if (chdir("/"))
379 panic("chdir() failed after chrooting: ");
380
381 /* If we can't find server user, revert to nobody's default uid */
382 if (!pws) {
383 fprintf(stderr, "Warning: Could not get password entry for %s. Reverting to uid -2.\n", serveruser);
384 if (setgroups(0, NULL) || setegid((gid_t)-2) || setgid((gid_t)-2) || setuid((uid_t)-2) || seteuid((uid_t)-2))
385 panic("Could not set uid to value -2");
386 } else {
387 if (setgroups(0, NULL) || setegid(pws->pw_gid) || setgid(pws->pw_gid) || setuid(pws->pw_uid) || seteuid(pws->pw_uid))
388 panic("Could not set uid to specified value");
389 }
390
391 if (geteuid() == 0 || getegid() == 0)
392 panic("Still running with root privileges?!");
393 } else {
394 /* Normal user, just chdir() */
395 if (serverdir && chdir(serverdir)) {
396 fprintf(stderr, "Could not chroot to %s, because: %s\n", serverdir, strerror(errno));
397 return -1;
398 }
399 }
400
401 return 0;
402}
403
404/* Maintain our copy of the clock. time() on BSDs is very expensive. */
405int main(int argc, char **argv) {
406
407 random_init();
408 if (fdstate_init() == -1)
409 panic("fdstate_init");
410 if (event_init() == -1)
411 panic("event_init");
412 config_parse(argc, argv);
413
414 listen_bind_all();
415
416 defaul_signal_handlers();
417
418#ifdef WANT_SYSLOGS
419 openlog("opentracker", 0, LOG_USER);
420 setlogmask(LOG_UPTO(LOG_INFO));
421#endif
422
423 if (drop_privileges(g_serveruser ? g_serveruser : "nobody", g_serverdir) == -1)
424 panic("drop_privileges failed, exiting. Last error");
425
426
427 /* Create our self pipe which allows us to interrupt mainloops
428 wait in case some data is available to send out */
429 if (pipe(g_self_pipe) == -1)
430 panic("selfpipe failed: ");
431 /* Both ends have to be non blocking: the loop drains the read end until it
432 is empty, and a worker nudging a full pipe has already made its point */
433 socket_set_blocking(g_self_pipe[0], 0);
434 socket_set_blocking(g_self_pipe[1], 0);
435 if (event_add(g_self_pipe[0], EVENT_IN, fdstate_open(g_self_pipe[0], (void *)FLAG_SELFPIPE, 0)) == -1)
436 panic("selfpipe event_add");
437
438 /* Before any thread exists, so none of them runs with a signal still at its
439 default disposition */
440 install_signal_handlers();
441
442 /* Init all sub systems. This call may fail with an exit() */
443 trackerlogic_init();
444
445#ifdef _DEBUG_RANDOMTORRENTS
446 fprintf(stderr, "DEBUG: Generating %d random peers on random torrents. This may take a while. (Setting RANDOMTORRENTS in trackerlogic.h)\n", RANDOMTORRENTS);
447 trackerlogic_add_random_torrents(RANDOMTORRENTS);
448 fprintf(stderr, "... done.\n");
449#endif
450
451 if (g_statefile)
452 load_state(g_statefile);
453
454 /* Nothing that adds a peer runs before the state file has been read */
455 livesync_init();
456 listen_start_tcp_workers();
457 listen_start_udp_workers();
458
459 server_mainloop(0);
460 worker_stop_all();
461 livesync_deinit();
462
463 /* No thread is serving any more, so the teardown can run where a debugger
464 and the sanitizers can follow it */
465 trackerlogic_deinit();
466#ifdef WANT_SYSLOGS
467 closelog();
468#endif
469
470 event_deinit();
471 fdstate_deinit();
472 return 0;
473}