Tor 0.5.0.0-alpha-dev
Loading...
Searching...
No Matches
main.c
Go to the documentation of this file.
1/* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4 * Copyright (c) 2007-2021, The Tor Project, Inc. */
5/* See LICENSE for licensing information */
6
7/**
8 * \file main.c
9 * \brief Invocation module. Initializes subsystems and runs the main loop.
10 **/
11
12#include "core/or/or.h"
13
14#include "app/config/config.h"
17#include "app/main/main.h"
18#include "app/main/ntmain.h"
20#include "app/main/shutdown.h"
21#include "app/main/subsysmgr.h"
27#include "core/or/channel.h"
28#include "core/or/channelpadding.h"
32#include "core/or/circuitlist.h"
33#include "core/or/command.h"
35#include "core/or/relay.h"
36#include "core/or/status.h"
37#include "feature/api/tor_api.h"
48#include "feature/hs/hs_dos.h"
53#include "feature/relay/dns.h"
61#include "lib/buf/buffers.h"
66#include "lib/net/resolve.h"
67#include "lib/trace/trace.h"
68
69#include "lib/process/waitpid.h"
71
72#include "lib/meminfo/meminfo.h"
73#include "lib/osinfo/uname.h"
74#include "lib/osinfo/libc.h"
75#include "lib/sandbox/sandbox.h"
76#include "lib/fs/lockfile.h"
77#include "lib/tls/tortls.h"
80#include "lib/evloop/timers.h"
83
84#include <event2/event.h>
85
88
90#include "core/or/port_cfg_st.h"
91
92#ifdef HAVE_UNISTD_H
93#include <unistd.h>
94#endif
95
96#ifdef HAVE_SYSTEMD
97# if defined(__COVERITY__) && !defined(__INCLUDE_LEVEL__)
98/* Systemd's use of gcc's __INCLUDE_LEVEL__ extension macro appears to confuse
99 * Coverity. Here's a kludge to unconfuse it.
100 */
101# define __INCLUDE_LEVEL__ 2
102#endif /* defined(__COVERITY__) && !defined(__INCLUDE_LEVEL__) */
103#include <systemd/sd-daemon.h>
104#endif /* defined(HAVE_SYSTEMD) */
105
106/********* PROTOTYPES **********/
107
108static void dumpmemusage(int severity);
109static void dumpstats(int severity); /* log stats */
110static void process_signal(int sig);
111
112/** Called when we get a SIGHUP: reload configuration files and keys,
113 * retry all connections, and so on. */
114static int
116{
117 const or_options_t *options = get_options();
118
119 log_notice(LD_GENERAL,"Received reload signal (hup). Reloading config and "
120 "resetting internal state.");
121 if (accounting_is_enabled(options))
123
126 /* first, reload config variables, in case they've changed */
127 if (options->ReloadTorrcOnSIGHUP) {
128 /* no need to provide argc/v, they've been cached in init_from_config */
129 int init_rv = options_init_from_torrc(0, NULL);
130 if (init_rv < 0) {
131 log_err(LD_CONFIG,"Reading config failed--see warnings above. "
132 "For usage, try -h.");
133 return -1;
134 } else if (BUG(init_rv > 0)) {
135 // LCOV_EXCL_START
136 /* This should be impossible: the only "return 1" cases in
137 * options_init_from_torrc are ones caused by command-line arguments;
138 * but they can't change while Tor is running. */
139 return -1;
140 // LCOV_EXCL_STOP
141 }
142 options = get_options(); /* they have changed now */
143 /* Logs are only truncated the first time they are opened, but were
144 probably intended to be cleaned up on signal. */
145 if (options->TruncateLogFile)
147 } else {
148 char *msg = NULL;
149 log_notice(LD_GENERAL, "Not reloading config file: the controller told "
150 "us not to.");
151 /* Make stuff get rescanned, reloaded, etc. */
152 if (set_options((or_options_t*)options, &msg) < 0) {
153 if (!msg)
154 msg = tor_strdup("Unknown error");
155 log_warn(LD_GENERAL, "Unable to re-set previous options: %s", msg);
156 tor_free(msg);
157 }
158 }
159 if (authdir_mode(options)) {
160 /* reload the approved-routers file */
162 /* warnings are logged from dirserv_load_fingerprint_file() directly */
163 log_info(LD_GENERAL, "Error reloading fingerprints. "
164 "Continuing with old list.");
165 }
166 }
167
168 /* Check if onion keys were manually rotated? */
169 if (options->ManualOnionKeyRotation)
171
172 /* Rotate away from the old dirty circuits. This has to be done
173 * after we've read the new options, but before we start using
174 * circuits for directory fetches. */
176
177 /* retry appropriate downloads */
180 if (!net_is_disabled())
182
183 /* We'll retry routerstatus downloads in about 10 seconds; no need to
184 * force a retry there. */
185
186 if (server_mode(options)) {
187 /* Maybe we've been given a new ed25519 key or certificate?
188 */
189 time_t now = approx_time();
190 int new_signing_key = load_ed_keys(options, now);
191 if (new_signing_key < 0 ||
192 generate_ed_link_cert(options, now, new_signing_key > 0)) {
193 log_warn(LD_OR, "Problem reloading Ed25519 keys; still using old keys.");
194 }
195 if (load_family_id_keys(options,
197 log_warn(LD_OR, "Problem reloading family ID keys; "
198 "still using old keys.");
199 }
200
201 /* Update cpuworker and dnsworker processes, so they get up-to-date
202 * configuration options. */
204 dns_reset();
205 }
206 return 0;
207}
208
209/** Libevent callback: invoked when we get a signal.
210 */
211static void
212signal_callback(evutil_socket_t fd, short events, void *arg)
213{
214 const int *sigptr = arg;
215 const int sig = *sigptr;
216 (void)fd;
217 (void)events;
218
219 update_current_time(time(NULL));
220 process_signal(sig);
221}
222
223/** Do the work of acting on a signal received in <b>sig</b> */
224static void
226{
227 switch (sig)
228 {
229 case SIGTERM:
230 log_notice(LD_GENERAL,"Catching signal TERM, exiting cleanly.");
232 break;
233 case SIGINT:
234 if (!server_mode(get_options())) { /* do it now */
235 log_notice(LD_GENERAL,"Interrupt: exiting cleanly.");
237 return;
238 }
239#ifdef HAVE_SYSTEMD
240 sd_notify(0, "STOPPING=1");
241#endif
243 break;
244#ifdef SIGPIPE
245 case SIGPIPE:
246 log_debug(LD_GENERAL,"Caught SIGPIPE. Ignoring.");
247 break;
248#endif
249 case SIGUSR1:
250 /* prefer to log it at INFO, but make sure we always see it */
253 break;
254 case SIGUSR2:
256 log_debug(LD_GENERAL,"Caught USR2, going to loglevel debug. "
257 "Send HUP to change back.");
259 break;
260 case SIGHUP:
261#ifdef HAVE_SYSTEMD
262 sd_notify(0, "RELOADING=1");
263#endif
264 if (do_hup() < 0) {
265 log_warn(LD_CONFIG,"Restart failed (config error?). Exiting.");
267 return;
268 }
269#ifdef HAVE_SYSTEMD
270 sd_notify(0, "READY=1");
271#endif
273 break;
274#ifdef SIGCHLD
275 case SIGCHLD:
277 break;
278#endif
279 case SIGNEWNYM: {
280 do_signewnym(time(NULL));
281 break;
282 }
283 case SIGCLEARDNSCACHE:
286 break;
287 case SIGHEARTBEAT:
288 log_heartbeat(time(NULL));
290 break;
291 case SIGACTIVE:
292 /* "SIGACTIVE" counts as ersatz user activity. */
295 break;
296 case SIGDORMANT:
297 /* "SIGDORMANT" means to ignore past user activity */
298 log_notice(LD_GENERAL, "Going dormant because of controller request.");
303 break;
304 }
305}
306
307#ifdef _WIN32
308/** Activate SIGINT on receiving a control signal in console. */
309static BOOL WINAPI
310process_win32_console_ctrl(DWORD ctrl_type)
311{
312 /* Ignore type of the ctrl signal */
313 (void) ctrl_type;
314
315 activate_signal(SIGINT);
316 return TRUE;
317}
318#endif /* defined(_WIN32) */
319
320/**
321 * Write current memory usage information to the log.
322 */
323static void
324dumpmemusage(int severity)
325{
327 tor_log(severity, LD_GENERAL, "In rephist: %"PRIu64" used by %d Tors.",
330 dump_cell_pool_usage(severity);
331 dump_dns_mem_usage(severity);
332}
333
334/** Write all statistics to the log, with log level <b>severity</b>. Called
335 * in response to a SIGUSR1. */
336static void
337dumpstats(int severity)
338{
339 time_t now = time(NULL);
340 time_t elapsed;
341 size_t rbuf_cap, wbuf_cap, rbuf_len, wbuf_len;
342
343 tor_log(severity, LD_GENERAL, "Dumping stats:");
344
346 int i = conn_sl_idx;
347 tor_log(severity, LD_GENERAL,
348 "Conn %d (socket %d) is a %s, created %d secs ago",
349 i, (int)conn->s,
351 (int)(now - conn->timestamp_created));
352 if (!connection_is_listener(conn)) {
353 tor_log(severity,LD_GENERAL,
354 "Conn %d: %d bytes waiting on inbuf (len %d, last read %d secs ago)",
355 i,
356 (int)connection_get_inbuf_len(conn),
357 (int)buf_allocation(conn->inbuf),
358 (int)(now - conn->timestamp_last_read_allowed));
359 tor_log(severity,LD_GENERAL,
360 "Conn %d: %d bytes waiting on outbuf "
361 "(len %d, last written %d secs ago)",i,
362 (int)connection_get_outbuf_len(conn),
363 (int)buf_allocation(conn->outbuf),
364 (int)(now - conn->timestamp_last_write_allowed));
365 if (conn->type == CONN_TYPE_OR) {
366 or_connection_t *or_conn = TO_OR_CONN(conn);
367 if (or_conn->tls) {
368 if (tor_tls_get_buffer_sizes(or_conn->tls, &rbuf_cap, &rbuf_len,
369 &wbuf_cap, &wbuf_len) == 0) {
370 tor_log(severity, LD_GENERAL,
371 "Conn %d: %d/%d bytes used on OpenSSL read buffer; "
372 "%d/%d bytes used on write buffer.",
373 i, (int)rbuf_len, (int)rbuf_cap, (int)wbuf_len, (int)wbuf_cap);
374 }
375 }
376 }
377 }
378 circuit_dump_by_conn(conn, severity); /* dump info about all the circuits
379 * using this conn */
380 } SMARTLIST_FOREACH_END(conn);
381
382 channel_dumpstats(severity);
384
385 // TODO CGO: Use of RELAY_PAYLOAD_SIZE_MAX may make this a bit wrong.
386 tor_log(severity, LD_NET,
387 "Cells processed: %"PRIu64" padding\n"
388 " %"PRIu64" create\n"
389 " %"PRIu64" created\n"
390 " %"PRIu64" relay\n"
391 " (%"PRIu64" relayed)\n"
392 " (%"PRIu64" delivered)\n"
393 " %"PRIu64" destroy",
402 tor_log(severity,LD_NET,"Average packaged cell fullness: %2.3f%%",
403 100*(((double)stats_n_data_bytes_packaged) /
406 tor_log(severity,LD_NET,"Average delivered cell fullness: %2.3f%%",
407 100*(((double)stats_n_data_bytes_received) /
409
410 cpuworker_log_onionskin_overhead(severity, ONION_HANDSHAKE_TYPE_TAP, "TAP");
411 cpuworker_log_onionskin_overhead(severity, ONION_HANDSHAKE_TYPE_NTOR,"ntor");
412
413 if (now - time_of_process_start >= 0)
414 elapsed = now - time_of_process_start;
415 else
416 elapsed = 0;
417
418 if (elapsed) {
419 tor_log(severity, LD_NET,
420 "Average bandwidth: %"PRIu64"/%d = %d bytes/sec reading",
421 (get_bytes_read()),
422 (int)elapsed,
423 (int) (get_bytes_read()/elapsed));
424 tor_log(severity, LD_NET,
425 "Average bandwidth: %"PRIu64"/%d = %d bytes/sec writing",
427 (int)elapsed,
428 (int) (get_bytes_written()/elapsed));
429 }
430
431 tor_log(severity, LD_NET, "--------------- Dumping memory information:");
432 dumpmemusage(severity);
433
434 rep_hist_dump_stats(now,severity);
435 hs_service_dump_stats(severity);
436}
437
438#ifdef _WIN32
439#define UNIX_ONLY 0
440#else
441#define UNIX_ONLY 1
442#endif
443
444static struct {
445 /** A numeric code for this signal. Must match the signal value if
446 * try_to_register is true. */
448 /** True if we should try to register this signal with libevent and catch
449 * corresponding posix signals. False otherwise. */
451 /** Pointer to hold the event object constructed for this signal. */
452 struct event *signal_event;
453} signal_handlers[] = {
454#ifdef SIGINT
455 { SIGINT, UNIX_ONLY, NULL }, /* do a controlled slow shutdown */
456#endif
457#ifdef SIGTERM
458 { SIGTERM, UNIX_ONLY, NULL }, /* to terminate now */
459#endif
460#ifdef SIGPIPE
461 { SIGPIPE, UNIX_ONLY, NULL }, /* otherwise SIGPIPE kills us */
462#endif
463#ifdef SIGUSR1
464 { SIGUSR1, UNIX_ONLY, NULL }, /* dump stats */
465#endif
466#ifdef SIGUSR2
467 { SIGUSR2, UNIX_ONLY, NULL }, /* go to loglevel debug */
468#endif
469#ifdef SIGHUP
470 { SIGHUP, UNIX_ONLY, NULL }, /* to reload config, retry conns, etc */
471#endif
472#ifdef SIGXFSZ
473 { SIGXFSZ, UNIX_ONLY, NULL }, /* handle file-too-big resource exhaustion */
474#endif
475#ifdef SIGCHLD
476 { SIGCHLD, UNIX_ONLY, NULL }, /* handle dns/cpu workers that exit */
477#endif
478 /* These are controller-only */
479 { SIGNEWNYM, 0, NULL },
480 { SIGCLEARDNSCACHE, 0, NULL },
481 { SIGHEARTBEAT, 0, NULL },
482 { SIGACTIVE, 0, NULL },
483 { SIGDORMANT, 0, NULL },
484 { -1, -1, NULL }
485};
486
487/** Set up the signal handler events for this process, and register them
488 * with libevent if appropriate. */
489void
491{
492 int i;
493 const int enabled = !get_options()->DisableSignalHandlers;
494
495 for (i = 0; signal_handlers[i].signal_value >= 0; ++i) {
496 /* Signal handlers are only registered with libevent if they need to catch
497 * real POSIX signals. We construct these signal handler events in either
498 * case, though, so that controllers can activate them with the SIGNAL
499 * command.
500 */
501 if (enabled && signal_handlers[i].try_to_register) {
502 signal_handlers[i].signal_event =
503 tor_evsignal_new(tor_libevent_get_base(),
504 signal_handlers[i].signal_value,
506 &signal_handlers[i].signal_value);
507 if (event_add(signal_handlers[i].signal_event, NULL))
508 log_warn(LD_BUG, "Error from libevent when adding "
509 "event for signal %d",
510 signal_handlers[i].signal_value);
511 } else {
512 signal_handlers[i].signal_event =
513 tor_event_new(tor_libevent_get_base(), -1,
514 EV_SIGNAL, signal_callback,
515 &signal_handlers[i].signal_value);
516 }
517 }
518
519#ifdef _WIN32
520 /* Windows lacks traditional POSIX signals but WinAPI provides a function
521 * to handle control signals like Ctrl+C in the console, we can use this to
522 * simulate the SIGINT signal */
523 if (enabled) SetConsoleCtrlHandler(process_win32_console_ctrl, TRUE);
524#endif /* defined(_WIN32) */
525}
526
527/* Cause the signal handler for signal_num to be called in the event loop. */
528void
529activate_signal(int signal_num)
530{
531 int i;
532 for (i = 0; signal_handlers[i].signal_value >= 0; ++i) {
533 if (signal_handlers[i].signal_value == signal_num) {
534 event_active(signal_handlers[i].signal_event, EV_SIGNAL, 1);
535 return;
536 }
537 }
538}
539
540/** Main entry point for the Tor command-line client. Return 0 on "success",
541 * negative on "failure", and positive on "success and exit".
542 */
543int
544tor_init(int argc, char *argv[])
545{
546 char progname[256];
548 bool running_tor = false;
549
550 time_of_process_start = time(NULL);
552 /* Have the log set up with our application name. */
553 tor_snprintf(progname, sizeof(progname), "Tor %s", get_version());
554 log_set_application_name(progname);
555
556 /* Initialize the history structures. */
558 bwhist_init();
559 /* Initialize the service cache. */
560 addressmap_init(); /* Init the client dns cache. Do it always, since it's
561 * cheap. */
562
563 /* Initialize the HS subsystem. */
564 hs_init();
565
566 {
567 /* We check for the "quiet"/"hush" settings first, since they decide
568 whether we log anything at all to stdout. */
569 parsed_cmdline_t *cmdline;
570 cmdline = config_parse_commandline(argc, argv, 1);
571 if (cmdline) {
572 quiet = cmdline->quiet_level;
573 running_tor = (cmdline->command == CMD_RUN_TOR);
574 }
575 parsed_cmdline_free(cmdline);
576 }
577
578 /* give it somewhere to log to initially */
581
582 {
583 const char *version = get_version();
584
585 log_notice(LD_GENERAL, "Tor %s running on %s with Libevent %s, "
586 "%s %s, Zlib %s, Liblzma %s, Libzstd %s and %s %s as libc.",
587 version,
588 get_uname(),
592 tor_compress_supports_method(ZLIB_METHOD) ?
593 tor_compress_version_str(ZLIB_METHOD) : "N/A",
594 tor_compress_supports_method(LZMA_METHOD) ?
595 tor_compress_version_str(LZMA_METHOD) : "N/A",
596 tor_compress_supports_method(ZSTD_METHOD) ?
597 tor_compress_version_str(ZSTD_METHOD) : "N/A",
599 tor_libc_get_name() : "Unknown",
601
602 log_notice(LD_GENERAL, "Tor can't help you if you use it wrong! "
603 "Learn how to be safe at "
604 "https://support.torproject.org/faq/staying-anonymous/");
605
606 if (strstr(version, "alpha") || strstr(version, "beta"))
607 log_notice(LD_GENERAL, "This version is not a stable Tor release. "
608 "Expect more bugs than usual.");
609
610 if (strlen(risky_option_list) && running_tor) {
611 log_warn(LD_GENERAL, "This build of Tor has been compiled with one "
612 "or more options that might make it less reliable or secure! "
613 "They are:%s", risky_option_list);
614 }
615
617 }
618
619 /* Warn _if_ the tracing subsystem is built in. */
620 tracing_log_warning();
621
622 int init_rv = options_init_from_torrc(argc,argv);
623 if (init_rv < 0) {
624 log_err(LD_CONFIG,"Reading config failed--see warnings above.");
625 return -1;
626 } else if (init_rv > 0) {
627 // We succeeded, and should exit anyway -- probably the user just said
628 // "--version" or something like that.
629 return 1;
630 }
631
632 /* Initialize channelpadding and circpad parameters to defaults
633 * until we get a consensus */
638
639 /* Initialize circuit padding to defaults+torrc until we get a consensus */
641
642 /* Initialize hidden service DoS subsystem. We need to do this once the
643 * configuration object has been set because it can be accessed. */
644 hs_dos_init();
645
646 /* Initialize predicted ports list after loading options */
647 predicted_ports_init();
648
649#ifndef _WIN32
650 if (geteuid()==0)
651 log_warn(LD_GENERAL,"You are running Tor as root. You don't need to, "
652 "and you probably shouldn't.");
653#endif
654
655 /* Scan/clean unparseable descriptors; after reading config */
657
658 return 0;
659}
660
661/** A lockfile structure, used to prevent two Tors from messing with the
662 * data directory at once. If this variable is non-NULL, we're holding
663 * the lockfile. */
665
666/** Try to grab the lock file described in <b>options</b>, if we do not
667 * already have it. If <b>err_if_locked</b> is true, warn if somebody else is
668 * holding the lock, and exit if we can't get it after waiting. Otherwise,
669 * return -1 if we can't get the lockfile. Return 0 on success.
670 */
671int
672try_locking(const or_options_t *options, int err_if_locked)
673{
674 if (lockfile)
675 return 0;
676 else {
677 char *fname = options_get_datadir_fname(options, "lock");
678 int already_locked = 0;
679 tor_lockfile_t *lf = tor_lockfile_lock(fname, 0, &already_locked);
680 tor_free(fname);
681 if (!lf) {
682 if (err_if_locked && already_locked) {
683 int r;
684 log_warn(LD_GENERAL, "It looks like another Tor process is running "
685 "with the same data directory. Waiting 5 seconds to see "
686 "if it goes away.");
687#ifndef _WIN32
688 sleep(5);
689#else
690 Sleep(5000);
691#endif
692 r = try_locking(options, 0);
693 if (r<0) {
694 log_err(LD_GENERAL, "No, it's still there. Exiting.");
695 return -1;
696 }
697 return r;
698 }
699 return -1;
700 }
701 lockfile = lf;
702 return 0;
703 }
704}
705
706/** Return true iff we've successfully acquired the lock file. */
707int
709{
710 return lockfile != NULL;
711}
712
713/** If we have successfully acquired the lock file, release it. */
714void
716{
717 if (lockfile) {
719 lockfile = NULL;
720 }
721}
722
723/**
724 * Remove the specified file, and log a warning if the operation fails for
725 * any reason other than the file not existing. Ignores NULL filenames.
726 */
727void
728tor_remove_file(const char *filename)
729{
730 if (filename && tor_unlink(filename) != 0 && errno != ENOENT) {
731 log_warn(LD_FS, "Couldn't unlink %s: %s",
732 filename, strerror(errno));
733 }
734}
735
736/** Read/create keys as needed, and echo our fingerprint to stdout. */
737static int
739{
740 const or_options_t *options = get_options();
741 const char *arg = options->command_arg;
742 char rsa[FINGERPRINT_LEN + 1];
743 crypto_pk_t *k;
744 const ed25519_public_key_t *edkey;
745 const char *nickname = options->Nickname;
746 sandbox_disable_getaddrinfo_cache();
747
748 bool show_rsa = !strcmp(arg, "") || !strcmp(arg, "rsa");
749 bool show_ed25519 = !strcmp(arg, "ed25519");
750 if (!show_rsa && !show_ed25519) {
751 log_err(LD_GENERAL,
752 "If you give a key type, you must specify 'rsa' or 'ed25519'. Exiting.");
753 return -1;
754 }
755
756 if (!server_mode(options)) {
757 log_err(LD_GENERAL,
758 "Clients don't have long-term identity keys. Exiting.");
759 return -1;
760 }
761 tor_assert(nickname);
762 if (init_keys() < 0) {
763 log_err(LD_GENERAL, "Error initializing keys; exiting.");
764 return -1;
765 }
766 if (!(k = get_server_identity_key())) {
767 log_err(LD_GENERAL, "Error: missing RSA identity key.");
768 return -1;
769 }
770 if (crypto_pk_get_fingerprint(k, rsa, 1) < 0) {
771 log_err(LD_BUG, "Error computing RSA fingerprint");
772 return -1;
773 }
774 if (!(edkey = get_master_identity_key())) {
775 log_err(LD_GENERAL,"Error: missing ed25519 identity key.");
776 return -1;
777 }
778 if (show_rsa) {
779 printf("%s %s\n", nickname, rsa);
780 }
781 if (show_ed25519) {
782 char ed25519[ED25519_BASE64_LEN + 1];
783 digest256_to_base64(ed25519, (const char *) edkey->pubkey);
784 printf("%s %s\n", nickname, ed25519);
785 }
786 return 0;
787}
788
789/** Entry point for password hashing: take the desired password from
790 * the command line, and print its salted hash to stdout. **/
791static void
793{
794
795 char output[256];
797
799 key[S2K_RFC2440_SPECIFIER_LEN-1] = (uint8_t)96; /* Hash 64 K of data. */
801 get_options()->command_arg, strlen(get_options()->command_arg),
802 key);
803 base16_encode(output, sizeof(output), key, sizeof(key));
804 printf("16:%s\n",output);
805}
806
807/** Entry point for configuration dumping: write the configuration to
808 * stdout. */
809static int
811{
812 const or_options_t *options = get_options();
813 const char *arg = options->command_arg;
814 int how;
815 char *opts;
816
817 if (!strcmp(arg, "short")) {
818 how = OPTIONS_DUMP_MINIMAL;
819 } else if (!strcmp(arg, "non-builtin")) {
820 // Deprecated since 0.4.5.1-alpha.
821 fprintf(stderr, "'non-builtin' is deprecated; use 'short' instead.\n");
822 how = OPTIONS_DUMP_MINIMAL;
823 } else if (!strcmp(arg, "full")) {
824 how = OPTIONS_DUMP_ALL;
825 } else {
826 fprintf(stderr, "No valid argument to --dump-config found!\n");
827 fprintf(stderr, "Please select 'short' or 'full'.\n");
828
829 return -1;
830 }
831
832 opts = options_dump(options, how);
833 printf("%s", opts);
834 tor_free(opts);
835
836 return 0;
837}
838
839/** Implement --keygen-family; create a family ID key and write it to a file.
840 */
841static int
842do_keygen_family(const char *fname_base)
843{
845 char *fname_key = NULL, *fname_id = NULL, *id_contents = NULL;
846 int r = -1;
847
848 if (BUG(!fname_base))
849 goto done;
850
851 tor_asprintf(&fname_key, "%s.secret_family_key", fname_base);
852 tor_asprintf(&fname_id, "%s.public_family_id", fname_base);
853
854 if (create_family_id_key(fname_key, &pk) < 0)
855 goto done;
856 tor_asprintf(&id_contents, "%s\n", ed25519_fmt(&pk));
857 if (write_str_to_file(fname_id, id_contents, 0) < 0)
858 goto done;
859
860 printf("# Generated %s\n", fname_key);
861 printf("FamilyId %s\n", ed25519_fmt(&pk));
862
863 r = 0;
864
865 done:
866 tor_free(fname_key);
867 tor_free(fname_id);
868 tor_free(id_contents);
869 return r;
870}
871
872/** Implement --keygen-onion; create an onion key and write it to a file.
873 */
874static int
875do_keygen_onion_key(const char *fname)
876{
877 int result = -1;
879
880 if (BUG(! fname))
881 goto done;
882
883 /* Generate new onion key. */
884 if (curve25519_keypair_generate(&keys, /* extra strong */ 1) < 0)
885 goto done;
886
887 /* Save it to disk. */
888 if (curve25519_keypair_write_to_file(&keys, fname, "onion") < 0)
889 goto done;
890
891 printf("Saved new Onion Key in file: %s\n", fname);
892
893 /* All good. */
894 result = 0;
895
896 done:
897 memwipe(&keys, 0, sizeof(keys));
898 return result;
899}
900
901static void
902init_addrinfo(void)
903{
904 if (! server_mode(get_options()) || get_options()->Address) {
905 /* We don't need to seed our own hostname, because we won't be calling
906 * resolve_my_address on it.
907 */
908 return;
909 }
910 char hname[256];
911
912 // host name to sandbox
913 gethostname(hname, sizeof(hname));
914 tor_add_addrinfo(hname);
915}
916
917static sandbox_cfg_t*
918sandbox_init_filter(void)
919{
920 const or_options_t *options = get_options();
922
924 get_cachedir_fname("cached-status"));
925
926#define OPEN(name) \
927 sandbox_cfg_allow_open_filename(&cfg, tor_strdup(name))
928
929#define OPENDIR(dir) \
930 sandbox_cfg_allow_opendir_dirname(&cfg, tor_strdup(dir))
931
932#define OPEN_DATADIR(name) \
933 sandbox_cfg_allow_open_filename(&cfg, get_datadir_fname(name))
934
935#define OPEN_DATADIR2(name, name2) \
936 sandbox_cfg_allow_open_filename(&cfg, get_datadir_fname2((name), (name2)))
937
938#define OPEN_DATADIR_SUFFIX(name, suffix) do { \
939 OPEN_DATADIR(name); \
940 OPEN_DATADIR(name suffix); \
941 } while (0)
942
943#define OPEN_DATADIR2_SUFFIX(name, name2, suffix) do { \
944 OPEN_DATADIR2(name, name2); \
945 OPEN_DATADIR2(name, name2 suffix); \
946 } while (0)
947
948// KeyDirectory is a directory, but it is only opened in check_private_dir
949// which calls open instead of opendir
950#define OPEN_KEY_DIRECTORY() \
951 OPEN(options->KeyDirectory)
952#define OPEN_CACHEDIR(name) \
953 sandbox_cfg_allow_open_filename(&cfg, get_cachedir_fname(name))
954#define OPEN_CACHEDIR_SUFFIX(name, suffix) do { \
955 OPEN_CACHEDIR(name); \
956 OPEN_CACHEDIR(name suffix); \
957 } while (0)
958#define OPEN_KEYDIR(name) \
959 sandbox_cfg_allow_open_filename(&cfg, get_keydir_fname(name))
960#define OPEN_KEYDIR_SUFFIX(name, suffix) do { \
961 OPEN_KEYDIR(name); \
962 OPEN_KEYDIR(name suffix); \
963 } while (0)
964
965 // DataDirectory is a directory, but it is only opened in check_private_dir
966 // which calls open instead of opendir
967 OPEN(options->DataDirectory);
968 OPEN_KEY_DIRECTORY();
969
970 OPEN_CACHEDIR_SUFFIX("cached-certs", ".tmp");
971 OPEN_CACHEDIR_SUFFIX("cached-consensus", ".tmp");
972 OPEN_CACHEDIR_SUFFIX("unverified-consensus", ".tmp");
973 OPEN_CACHEDIR_SUFFIX("unverified-microdesc-consensus", ".tmp");
974 OPEN_CACHEDIR_SUFFIX("cached-microdesc-consensus", ".tmp");
975 OPEN_CACHEDIR_SUFFIX("cached-microdescs", ".tmp");
976 OPEN_CACHEDIR_SUFFIX("cached-microdescs.new", ".tmp");
977 OPEN_CACHEDIR_SUFFIX("cached-descriptors", ".tmp");
978 OPEN_CACHEDIR_SUFFIX("cached-descriptors.new", ".tmp");
979 OPEN_CACHEDIR("cached-descriptors.tmp.tmp");
980 OPEN_CACHEDIR_SUFFIX("cached-extrainfo", ".tmp");
981 OPEN_CACHEDIR_SUFFIX("cached-extrainfo.new", ".tmp");
982 OPEN_CACHEDIR("cached-extrainfo.tmp.tmp");
983
984 OPEN_DATADIR_SUFFIX("state", ".tmp");
985 OPEN_DATADIR_SUFFIX("sr-state", ".tmp");
986 OPEN_DATADIR_SUFFIX("unparseable-desc", ".tmp");
987 OPEN_DATADIR_SUFFIX("v3-status-votes", ".tmp");
988 OPEN_DATADIR("key-pinning-journal");
989 OPEN("/dev/srandom");
990 OPEN("/dev/urandom");
991 OPEN("/dev/random");
992 OPEN("/etc/hosts");
993 OPEN("/proc/meminfo");
994
995#ifdef HAVE_MODULE_RELAY
996 {
997 smartlist_t *family_id_files =
998 list_family_key_files(options, options->FamilyKeyDirectory);
999
1000 SMARTLIST_FOREACH(family_id_files, const char *, fn,
1001 OPEN(fn));
1002
1003 SMARTLIST_FOREACH(family_id_files, char *, cp, tor_free(cp));
1004 smartlist_free(family_id_files);
1005 }
1006#endif
1007
1008 if (options->BridgeAuthoritativeDir)
1009 OPEN_DATADIR_SUFFIX("networkstatus-bridges", ".tmp");
1010
1011 if (authdir_mode(options)) {
1012 OPEN_DATADIR("approved-routers");
1013 OPEN_DATADIR_SUFFIX("my-consensus-microdesc", ".tmp");
1014 OPEN_DATADIR_SUFFIX("my-consensus-ns", ".tmp");
1015 if (options->V3BandwidthsFile) {
1016 log_notice(LD_GENERAL, "Adding V3BandwidthsFile %s to sandboxing set.",
1017 options->V3BandwidthsFile);
1018 OPEN(options->V3BandwidthsFile);
1019 }
1020 }
1021
1022 if (options->ServerDNSResolvConfFile)
1024 tor_strdup(options->ServerDNSResolvConfFile));
1025 else
1026 sandbox_cfg_allow_open_filename(&cfg, tor_strdup("/etc/resolv.conf"));
1027
1028 const char *torrc_defaults_fname = get_torrc_fname(1);
1031 }
1032 const char *torrc_fname = get_torrc_fname(0);
1033 if (torrc_fname) {
1035 // allow torrc backup and torrc.tmp to make SAVECONF work
1036 char *torrc_bck = NULL;
1038 sandbox_cfg_allow_rename(&cfg, tor_strdup(torrc_fname), torrc_bck);
1039 char *torrc_tmp = NULL;
1040 tor_asprintf(&torrc_tmp, "%s.tmp", torrc_fname);
1041 sandbox_cfg_allow_rename(&cfg, torrc_tmp, tor_strdup(torrc_fname));
1042 sandbox_cfg_allow_open_filename(&cfg, tor_strdup(torrc_tmp));
1043 // we need to stat the existing backup file
1044 sandbox_cfg_allow_stat_filename(&cfg, tor_strdup(torrc_bck));
1045 }
1046
1047 SMARTLIST_FOREACH(options->FilesOpenedByIncludes, char *, f, {
1048 if (file_status(f) == FN_DIR) {
1049 OPENDIR(f);
1050 } else {
1051 OPEN(f);
1052 }
1053 });
1054
1055#define RENAME_SUFFIX(name, suffix) \
1056 sandbox_cfg_allow_rename(&cfg, \
1057 get_datadir_fname(name suffix), \
1058 get_datadir_fname(name))
1059
1060#define RENAME_SUFFIX2(prefix, name, suffix) \
1061 sandbox_cfg_allow_rename(&cfg, \
1062 get_datadir_fname2(prefix, name suffix), \
1063 get_datadir_fname2(prefix, name))
1064
1065#define RENAME_CACHEDIR_SUFFIX(name, suffix) \
1066 sandbox_cfg_allow_rename(&cfg, \
1067 get_cachedir_fname(name suffix), \
1068 get_cachedir_fname(name))
1069
1070#define RENAME_KEYDIR_SUFFIX(name, suffix) \
1071 sandbox_cfg_allow_rename(&cfg, \
1072 get_keydir_fname(name suffix), \
1073 get_keydir_fname(name))
1074
1075 RENAME_CACHEDIR_SUFFIX("cached-certs", ".tmp");
1076 RENAME_CACHEDIR_SUFFIX("cached-consensus", ".tmp");
1077 RENAME_CACHEDIR_SUFFIX("unverified-consensus", ".tmp");
1078 RENAME_CACHEDIR_SUFFIX("unverified-microdesc-consensus", ".tmp");
1079 RENAME_CACHEDIR_SUFFIX("cached-microdesc-consensus", ".tmp");
1080 RENAME_CACHEDIR_SUFFIX("cached-microdescs", ".tmp");
1081 RENAME_CACHEDIR_SUFFIX("cached-microdescs", ".new");
1082 RENAME_CACHEDIR_SUFFIX("cached-microdescs.new", ".tmp");
1083 RENAME_CACHEDIR_SUFFIX("cached-descriptors", ".tmp");
1084 RENAME_CACHEDIR_SUFFIX("cached-descriptors", ".new");
1085 RENAME_CACHEDIR_SUFFIX("cached-descriptors.new", ".tmp");
1086 RENAME_CACHEDIR_SUFFIX("cached-extrainfo", ".tmp");
1087 RENAME_CACHEDIR_SUFFIX("cached-extrainfo", ".new");
1088 RENAME_CACHEDIR_SUFFIX("cached-extrainfo.new", ".tmp");
1089
1090 RENAME_SUFFIX("state", ".tmp");
1091 RENAME_SUFFIX("sr-state", ".tmp");
1092 RENAME_SUFFIX("unparseable-desc", ".tmp");
1093 RENAME_SUFFIX("v3-status-votes", ".tmp");
1094
1095 if (options->BridgeAuthoritativeDir)
1096 RENAME_SUFFIX("networkstatus-bridges", ".tmp");
1097
1098 if (authdir_mode(options)) {
1099 RENAME_SUFFIX("my-consensus-microdesc", ".tmp");
1100 RENAME_SUFFIX("my-consensus-ns", ".tmp");
1101
1102 sandbox_cfg_allow_rename(&cfg,
1103 get_datadir_fname("my-consensus-microdesc"),
1104 get_datadir_fname("consensus-transparency-microdesc"));
1105 sandbox_cfg_allow_rename(&cfg,
1106 get_datadir_fname("my-consensus-ns"),
1107 get_datadir_fname("consensus-transparency-ns"));
1108 }
1109
1110#define STAT_DATADIR(name) \
1111 sandbox_cfg_allow_stat_filename(&cfg, get_datadir_fname(name))
1112
1113#define STAT_CACHEDIR(name) \
1114 sandbox_cfg_allow_stat_filename(&cfg, get_cachedir_fname(name))
1115
1116#define STAT_DATADIR2(name, name2) \
1117 sandbox_cfg_allow_stat_filename(&cfg, get_datadir_fname2((name), (name2)))
1118
1119#define STAT_KEY_DIRECTORY() \
1120 sandbox_cfg_allow_stat_filename(&cfg, tor_strdup(options->KeyDirectory))
1121
1122 STAT_DATADIR(NULL);
1123 STAT_DATADIR("lock");
1124 STAT_DATADIR("state");
1125 STAT_DATADIR("router-stability");
1126
1127 STAT_CACHEDIR("cached-extrainfo.new");
1128
1129 {
1130 smartlist_t *files = smartlist_new();
1132 SMARTLIST_FOREACH(files, char *, file_name, {
1133 /* steals reference */
1134 sandbox_cfg_allow_open_filename(&cfg, file_name);
1135 });
1136 smartlist_free(files);
1137 }
1138
1139 {
1140 smartlist_t *files = smartlist_new();
1141 smartlist_t *dirs = smartlist_new();
1143 SMARTLIST_FOREACH(files, char *, file_name, {
1144 char *tmp_name = NULL;
1145 tor_asprintf(&tmp_name, "%s.tmp", file_name);
1146 sandbox_cfg_allow_rename(&cfg,
1147 tor_strdup(tmp_name), tor_strdup(file_name));
1148 /* steals references */
1149 sandbox_cfg_allow_open_filename(&cfg, file_name);
1150 sandbox_cfg_allow_open_filename(&cfg, tmp_name);
1151 });
1152 SMARTLIST_FOREACH(dirs, char *, dir, {
1153 /* steals reference */
1155 });
1156 smartlist_free(files);
1157 smartlist_free(dirs);
1158 }
1159
1160 {
1161 char *fname;
1162 if ((fname = get_controller_cookie_file_name())) {
1164 }
1165 if ((fname = get_ext_or_auth_cookie_file_name())) {
1167 }
1168 }
1169
1171 if (!port->is_unix_addr)
1172 continue;
1173 /* When we open an AF_UNIX address, we want permission to open the
1174 * directory that holds it. */
1175 char *dirname = tor_strdup(port->unix_addr);
1176 if (get_parent_directory(dirname) == 0) {
1177 OPENDIR(dirname);
1178 }
1179 tor_free(dirname);
1180 sandbox_cfg_allow_chmod_filename(&cfg, tor_strdup(port->unix_addr));
1181 sandbox_cfg_allow_chown_filename(&cfg, tor_strdup(port->unix_addr));
1182 } SMARTLIST_FOREACH_END(port);
1183
1184 if (options->DirPortFrontPage) {
1186 tor_strdup(options->DirPortFrontPage));
1187 }
1188
1189 // orport
1190 if (server_mode(get_options())) {
1191
1192 OPEN_KEYDIR_SUFFIX("secret_id_key", ".tmp");
1193 OPEN_KEYDIR_SUFFIX("secret_onion_key", ".tmp");
1194 OPEN_KEYDIR_SUFFIX("secret_onion_key_ntor", ".tmp");
1195 OPEN_KEYDIR("secret_id_key.old");
1196 OPEN_KEYDIR("secret_onion_key.old");
1197 OPEN_KEYDIR("secret_onion_key_ntor.old");
1198
1199 OPEN_KEYDIR_SUFFIX("ed25519_master_id_secret_key", ".tmp");
1200 OPEN_KEYDIR_SUFFIX("ed25519_master_id_secret_key_encrypted", ".tmp");
1201 OPEN_KEYDIR_SUFFIX("ed25519_master_id_public_key", ".tmp");
1202 OPEN_KEYDIR_SUFFIX("ed25519_signing_secret_key", ".tmp");
1203 OPEN_KEYDIR_SUFFIX("ed25519_signing_secret_key_encrypted", ".tmp");
1204 OPEN_KEYDIR_SUFFIX("ed25519_signing_public_key", ".tmp");
1205 OPEN_KEYDIR_SUFFIX("ed25519_signing_cert", ".tmp");
1206
1207 OPEN_DATADIR2_SUFFIX("stats", "bridge-stats", ".tmp");
1208 OPEN_DATADIR2_SUFFIX("stats", "dirreq-stats", ".tmp");
1209
1210 OPEN_DATADIR2_SUFFIX("stats", "entry-stats", ".tmp");
1211 OPEN_DATADIR2_SUFFIX("stats", "exit-stats", ".tmp");
1212 OPEN_DATADIR2_SUFFIX("stats", "buffer-stats", ".tmp");
1213 OPEN_DATADIR2_SUFFIX("stats", "conn-stats", ".tmp");
1214 OPEN_DATADIR2_SUFFIX("stats", "hidserv-stats", ".tmp");
1215 OPEN_DATADIR2_SUFFIX("stats", "hidserv-v3-stats", ".tmp");
1216
1217 OPEN_DATADIR("approved-routers");
1218 OPEN_DATADIR_SUFFIX("fingerprint", ".tmp");
1219 OPEN_DATADIR_SUFFIX("fingerprint-ed25519", ".tmp");
1220 OPEN_DATADIR_SUFFIX("hashed-fingerprint", ".tmp");
1221 OPEN_DATADIR_SUFFIX("router-stability", ".tmp");
1222
1223 OPEN("/etc/resolv.conf");
1224
1225 RENAME_SUFFIX("fingerprint", ".tmp");
1226 RENAME_SUFFIX("fingerprint-ed25519", ".tmp");
1227 RENAME_KEYDIR_SUFFIX("secret_onion_key_ntor", ".tmp");
1228
1229 RENAME_KEYDIR_SUFFIX("secret_id_key", ".tmp");
1230 RENAME_KEYDIR_SUFFIX("secret_id_key.old", ".tmp");
1231 RENAME_KEYDIR_SUFFIX("secret_onion_key", ".tmp");
1232 RENAME_KEYDIR_SUFFIX("secret_onion_key.old", ".tmp");
1233
1234 RENAME_SUFFIX2("stats", "bridge-stats", ".tmp");
1235 RENAME_SUFFIX2("stats", "dirreq-stats", ".tmp");
1236 RENAME_SUFFIX2("stats", "entry-stats", ".tmp");
1237 RENAME_SUFFIX2("stats", "exit-stats", ".tmp");
1238 RENAME_SUFFIX2("stats", "buffer-stats", ".tmp");
1239 RENAME_SUFFIX2("stats", "conn-stats", ".tmp");
1240 RENAME_SUFFIX2("stats", "hidserv-stats", ".tmp");
1241 RENAME_SUFFIX2("stats", "hidserv-v3-stats", ".tmp");
1242 RENAME_SUFFIX("hashed-fingerprint", ".tmp");
1243 RENAME_SUFFIX("router-stability", ".tmp");
1244
1245 RENAME_KEYDIR_SUFFIX("ed25519_master_id_secret_key", ".tmp");
1246 RENAME_KEYDIR_SUFFIX("ed25519_master_id_secret_key_encrypted", ".tmp");
1247 RENAME_KEYDIR_SUFFIX("ed25519_master_id_public_key", ".tmp");
1248 RENAME_KEYDIR_SUFFIX("ed25519_signing_secret_key", ".tmp");
1249 RENAME_KEYDIR_SUFFIX("ed25519_signing_cert", ".tmp");
1250
1251 sandbox_cfg_allow_rename(&cfg,
1252 get_keydir_fname("secret_onion_key"),
1253 get_keydir_fname("secret_onion_key.old"));
1254 sandbox_cfg_allow_rename(&cfg,
1255 get_keydir_fname("secret_onion_key_ntor"),
1256 get_keydir_fname("secret_onion_key_ntor.old"));
1257
1258 STAT_KEY_DIRECTORY();
1259 OPEN_DATADIR("stats");
1260 STAT_DATADIR("stats");
1261 STAT_DATADIR2("stats", "dirreq-stats");
1262
1264 }
1265
1266 init_addrinfo();
1267
1268 return cfg;
1269}
1270
1271int
1272run_tor_main_loop(void)
1273{
1277
1278 /* load the private keys, if we're supposed to have them, and set up the
1279 * TLS context. */
1281 if (init_keys() < 0) {
1282 log_err(LD_OR, "Error initializing keys; exiting");
1283 return -1;
1284 }
1285 }
1286
1287 /* Set up our buckets */
1289
1290 /* initialize the bootstrap status events to know we're starting up */
1291 control_event_bootstrap(BOOTSTRAP_STATUS_STARTING, 0);
1292
1293 /* Initialize the keypinning log. */
1294 if (authdir_mode_v3(get_options())) {
1295 char *fname = get_datadir_fname("key-pinning-journal");
1296 int r = 0;
1297 if (keypin_load_journal(fname)<0) {
1298 log_err(LD_DIR, "Error loading key-pinning journal: %s",strerror(errno));
1299 r = -1;
1300 }
1301 if (keypin_open_journal(fname)<0) {
1302 log_err(LD_DIR, "Error opening key-pinning journal: %s",strerror(errno));
1303 r = -1;
1304 }
1305 tor_free(fname);
1306 if (r)
1307 return r;
1308 }
1309 {
1310 /* This is the old name for key-pinning-journal. These got corrupted
1311 * in a couple of cases by #16530, so we started over. See #16580 for
1312 * the rationale and for other options we didn't take. We can remove
1313 * this code once all the authorities that ran 0.2.7.1-alpha-dev are
1314 * upgraded.
1315 */
1316 char *fname = get_datadir_fname("key-pinning-entries");
1317 unlink(fname);
1318 tor_free(fname);
1319 }
1320
1322 log_warn(LD_DIR,
1323 "Couldn't load all cached v3 certificates. Starting anyway.");
1324 }
1326 return -1;
1327 }
1328 /* load the routers file, or assign the defaults. */
1330 return -1;
1331 }
1332 /* load the networkstatuses. (This launches a download for new routers as
1333 * appropriate.)
1334 */
1335 const time_t now = time(NULL);
1336 directory_info_has_arrived(now, 1, 0);
1337
1338 /* launch cpuworkers. Need to do this *after* we've read the onion key. */
1339 /* launch them always for all tors, now that clients can solve onion PoWs. */
1340 if (cpuworker_init() == -1)
1341 return -1;
1342
1344
1345 /* Setup shared random protocol subsystem. */
1346 if (authdir_mode_v3(get_options())) {
1347 if (sr_init(1) < 0) {
1348 return -1;
1349 }
1350 }
1351
1352 /* initialize dns resolve map, spawn workers if needed */
1353 if (dns_init() < 0) {
1354 if (get_options()->ServerDNSAllowBrokenConfig)
1355 log_warn(LD_GENERAL, "Couldn't set up any working nameservers. "
1356 "Network not up yet? Will try again soon.");
1357 else {
1358 log_err(LD_GENERAL,"Error initializing dns subsystem; exiting. To "
1359 "retry instead, set the ServerDNSAllowBrokenResolvConf option.");
1360 }
1361 }
1362
1363#ifdef HAVE_SYSTEMD
1364 {
1365 const int r = sd_notify(0, "READY=1");
1366 if (r < 0) {
1367 log_warn(LD_GENERAL, "Unable to send readiness to systemd: %s",
1368 strerror(r));
1369 } else if (r > 0) {
1370 log_notice(LD_GENERAL, "Signaled readiness to systemd");
1371 } else {
1372 log_info(LD_GENERAL, "Systemd NOTIFY_SOCKET not present.");
1373 }
1374 }
1375#endif /* defined(HAVE_SYSTEMD) */
1376
1377 return do_main_loop();
1378}
1379
1380/** Install the publish/subscribe relationships for all the subsystems. */
1381void
1383{
1385 int r = subsystems_add_pubsub(builder);
1386 tor_assert(r == 0);
1387 r = tor_mainloop_connect_pubsub(builder); // consumes builder
1388 tor_assert(r == 0);
1389}
1390
1391/** Connect the mainloop to its publish/subscribe message delivery events if
1392 * appropriate, and configure the global channels appropriately. */
1393void
1395{
1396 if (get_options()->command == CMD_RUN_TOR) {
1398 /* XXXX For each pubsub channel, its delivery strategy should be set at
1399 * this XXXX point, using tor_mainloop_set_delivery_strategy().
1400 */
1403 }
1404}
1405
1406/* Main entry point for the Tor process. Called from tor_main(), and by
1407 * anybody embedding Tor. */
1408int
1410{
1411 int result = 0;
1412
1413#ifdef EVENT_SET_MEM_FUNCTIONS_IMPLEMENTED
1414 event_set_mem_functions(tor_malloc_, tor_realloc_, tor_free_);
1415#endif
1416
1418
1420
1421 int argc = tor_cfg->argc + tor_cfg->argc_owned;
1422 char **argv = tor_calloc(argc, sizeof(char*));
1423 memcpy(argv, tor_cfg->argv, tor_cfg->argc*sizeof(char*));
1424 if (tor_cfg->argc_owned)
1425 memcpy(argv + tor_cfg->argc, tor_cfg->argv_owned,
1426 tor_cfg->argc_owned*sizeof(char*));
1427
1428 int done = 0;
1429 result = nt_service_parse_options(argc, argv, &done);
1430 if (POSSIBLE(done))
1431 goto done;
1432
1434
1435 {
1436 int init_rv = tor_init(argc, argv);
1437 if (init_rv) {
1438 tor_free_all(0);
1439 result = (init_rv < 0) ? -1 : 0;
1440 goto done;
1441 }
1442 }
1443
1445
1446 if (get_options()->Sandbox && get_options()->command == CMD_RUN_TOR) {
1447#ifdef ENABLE_FRAGILE_HARDENING
1448 log_warn(LD_CONFIG, "Sandbox is enabled but this Tor was built using "
1449 "fragile compiler hardening. The sandbox may be unable to filter "
1450 "requests to open files and directories and its overall "
1451 "effectiveness will be reduced.");
1452#endif
1453
1454 sandbox_cfg_t* cfg = sandbox_init_filter();
1455
1456 if (sandbox_init(cfg)) {
1457 tor_free(argv);
1458 log_err(LD_BUG,"Failed to create syscall sandbox filter");
1459 tor_free_all(0);
1460 return -1;
1461 }
1462 tor_make_getaddrinfo_cache_active();
1463
1464 // registering libevent rng
1465#ifdef HAVE_EVUTIL_SECURE_RNG_SET_URANDOM_DEVICE_FILE
1466 evutil_secure_rng_set_urandom_device_file(
1467 (char*) sandbox_intern_string("/dev/urandom"));
1468#endif
1469 }
1470
1471 switch (get_options()->command) {
1472 case CMD_RUN_TOR:
1473 nt_service_set_state(SERVICE_RUNNING);
1474 result = run_tor_main_loop();
1475 break;
1476 case CMD_KEYGEN:
1477 result = load_ed_keys(get_options(), time(NULL)) < 0;
1478 break;
1479 case CMD_KEYGEN_FAMILY:
1480 result = do_keygen_family(get_options()->command_arg);
1481 break;
1482 case CMD_KEYGEN_ONION:
1483 result = do_keygen_onion_key(get_options()->command_arg);
1484 break;
1485 case CMD_KEY_EXPIRATION:
1486 init_keys();
1487 result = log_cert_expiration();
1488 break;
1490 result = do_list_fingerprint();
1491 break;
1492 case CMD_HASH_PASSWORD:
1494 result = 0;
1495 break;
1496 case CMD_VERIFY_CONFIG:
1497 if (quiet_level == QUIET_NONE)
1498 printf("Configuration was valid\n");
1499 result = 0;
1500 break;
1501 case CMD_DUMP_CONFIG:
1502 result = do_dump_config();
1503 break;
1504 case CMD_RUN_UNITTESTS: /* only set by test.c */
1505 case CMD_IMMEDIATE: /* Handled in config.c */
1506 default:
1507 log_warn(LD_BUG,"Illegal command number %d: internal error.",
1508 get_options()->command);
1509 result = -1;
1510 }
1511 tor_cleanup();
1512 done:
1513 tor_free(argv);
1514 return result;
1515}
void addressmap_init(void)
Definition addressmap.c:90
void addressmap_clear_transient(void)
Definition addressmap.c:311
Header for addressmap.c.
time_t approx_time(void)
Definition approx_time.c:32
int trusted_dirs_reload_certs(void)
Definition authcert.c:324
Header file for authcert.c.
Header file for directory authority mode.
void base16_encode(char *dest, size_t destlen, const char *src, size_t srclen)
Definition binascii.c:478
size_t buf_allocation(const buf_t *buf)
Definition buffers.c:401
Header file for buffers.c.
void bwhist_init(void)
Definition bwhist.c:139
Header for feature/stats/bwhist.c.
void channel_dumpstats(int severity)
Definition channel.c:2077
void channel_listener_dumpstats(int severity)
Definition channel.c:2108
Header file for channel.c.
void channelpadding_new_consensus_params(const networkstatus_t *ns)
uint64_t stats_n_padding_cells_processed
Definition channeltls.c:84
void circuit_mark_all_dirty_circs_as_unusable(void)
void circuit_dump_by_conn(connection_t *conn, int severity)
Header file for circuitlist.c.
void circpad_machines_init(void)
void circpad_new_consensus_params(const networkstatus_t *ns)
Header file for circuitpadding.c.
uint64_t stats_n_created_cells_processed
Definition command.c:70
uint64_t stats_n_destroy_cells_processed
Definition command.c:74
uint64_t stats_n_relay_cells_processed
Definition command.c:72
uint64_t stats_n_create_cells_processed
Definition command.c:68
Header file for command.c.
#define POSSIBLE(expr)
const char * tor_libevent_get_version_str(void)
struct event_base * tor_libevent_get_base(void)
Header for compat_libevent.c.
const char * tor_compress_version_str(compress_method_t method)
Definition compress.c:430
int tor_compress_supports_method(compress_method_t method)
Definition compress.c:317
void tor_compress_log_init_warnings(void)
Definition compress.c:695
Headers for compress.c.
const char * get_torrc_fname(int defaults_fname)
Definition config.c:4788
const smartlist_t * get_configured_ports(void)
Definition config.c:6737
int options_init_from_torrc(int argc, char **argv)
Definition config.c:4494
int quiet
Definition config.c:2481
static char * torrc_defaults_fname
Definition config.c:907
void init_protocol_warning_severity_level(void)
Definition config.c:1198
char * options_dump(const or_options_t *options, int how_to_dump)
Definition config.c:2955
static char * torrc_fname
Definition config.c:905
const or_options_t * get_options(void)
Definition config.c:949
int set_options(or_options_t *new_val, char **msg)
Definition config.c:985
tor_cmdline_mode_t command
Definition config.c:2479
parsed_cmdline_t * config_parse_commandline(int argc, char **argv, int ignore_errors)
Definition config.c:2558
Header file for config.c.
#define CONFIG_BACKUP_PATTERN
Definition config.h:48
Header for confline.c.
void congestion_control_new_consensus_params(const networkstatus_t *ns)
Public APIs for congestion control.
void flow_control_new_consensus_params(const networkstatus_t *ns)
APIs for stream flow control on congestion controlled circuits.
int connection_is_listener(connection_t *conn)
void connection_dump_buffer_mem_stats(int severity)
void connection_bucket_init(void)
const char * connection_describe(const connection_t *conn)
Definition connection.c:541
Header file for connection.c.
#define CONN_TYPE_OR
Definition connection.h:44
or_connection_t * TO_OR_CONN(connection_t *c)
Header file for connection_or.c.
void consdiffmgr_enable_background_compression(void)
int consdiffmgr_register_with_sandbox(struct sandbox_cfg_elem_t **cfg)
Header for consdiffmgr.c.
Header file for control.c.
char * get_controller_cookie_file_name(void)
Header file for control_auth.c.
void control_event_bootstrap(bootstrap_status_t status, int progress)
int control_event_signal(uintptr_t signal_num)
Header file for control_events.c.
int cpuworker_init(void)
Definition cpuworker.c:118
void cpuworker_log_onionskin_overhead(int severity, int onionskin_type, const char *onionskin_type_name)
Definition cpuworker.c:354
void cpuworkers_rotate_keyinfo(void)
Definition cpuworker.c:250
Header file for cpuworker.c.
int curve25519_keypair_write_to_file(const curve25519_keypair_t *keypair, const char *fname, const char *tag)
int curve25519_keypair_generate(curve25519_keypair_t *keypair_out, int extra_strong)
void digest256_to_base64(char *d64, const char *digest)
const char * ed25519_fmt(const ed25519_public_key_t *pkey)
Header for crypto_format.c.
const char * crypto_get_library_version_string(void)
const char * crypto_get_library_name(void)
Headers for crypto_init.c.
void crypto_rand(char *to, size_t n)
Common functions for using (pseudo-)random number generators.
int crypto_pk_get_fingerprint(crypto_pk_t *pk, char *fp_out, int add_space)
Definition crypto_rsa.c:229
#define FINGERPRINT_LEN
Definition crypto_rsa.h:34
void secret_to_key_rfc2440(char *key_out, size_t key_out_len, const char *secret, size_t secret_len, const char *s2k_specifier)
Definition crypto_s2k.c:205
Header for crypto_s2k.c.
#define S2K_RFC2440_SPECIFIER_LEN
Definition crypto_s2k.h:21
void memwipe(void *mem, uint8_t byte, size_t sz)
Definition crypto_util.c:55
Common functions for cryptographic routines.
#define DIGEST_LEN
void router_reset_status_download_failures(void)
Definition dirlist.c:151
int dns_reset(void)
Definition dns.c:253
Header file for dns.c.
Header for ext_orport.c.
int accounting_record_bandwidth_usage(time_t now, or_state_t *state)
Definition hibernate.c:705
int accounting_is_enabled(const or_options_t *options)
Definition hibernate.c:305
void hibernate_begin_shutdown(void)
Definition hibernate.c:927
Header file for hibernate.c.
void hs_init(void)
Definition hs_common.c:1700
void hs_dos_init(void)
Definition hs_dos.c:226
Header file containing denial of service defenses for the HS subsystem for all versions.
void hs_service_lists_fnames_for_sandbox(smartlist_t *file_list, smartlist_t *dir_list)
void hs_service_dump_stats(int severity)
Header file containing service data for the HS subsystem.
int keypin_load_journal(const char *fname)
Definition keypin.c:448
int keypin_open_journal(const char *fname)
Definition keypin.c:301
Header for keypin.c.
const char * tor_libc_get_version_str(void)
Definition libc.c:51
const char * tor_libc_get_name(void)
Definition libc.c:36
Header for lib/osinfo/libc.c.
tor_lockfile_t * tor_lockfile_lock(const char *filename, int blocking, int *locked_out)
Definition lockfile.c:63
void tor_lockfile_unlock(tor_lockfile_t *lockfile)
Definition lockfile.c:121
Header for lockfile.c.
void tor_log(int severity, log_domain_mask_t domain, const char *format,...)
Definition log.c:591
void truncate_logs(void)
Definition log.c:1462
void switch_logs_debug(void)
Definition log.c:1447
int get_min_log_level(void)
Definition log.c:1432
void log_set_application_name(const char *name)
Definition log.c:212
void tor_log_get_logfile_names(smartlist_t *out)
Definition log.c:684
#define LD_OR
Definition log.h:92
#define LD_FS
Definition log.h:70
#define LD_BUG
Definition log.h:86
#define LD_NET
Definition log.h:66
#define LD_GENERAL
Definition log.h:62
#define LD_DIR
Definition log.h:88
#define LD_CONFIG
Definition log.h:68
#define LOG_INFO
Definition log.h:45
static tor_lockfile_t * lockfile
Definition main.c:664
int tor_run_main(const tor_main_configuration_t *tor_cfg)
Definition main.c:1409
static int do_keygen_onion_key(const char *fname)
Definition main.c:875
static int do_dump_config(void)
Definition main.c:810
static int do_list_fingerprint(void)
Definition main.c:738
struct event * signal_event
Definition main.c:452
void release_lockfile(void)
Definition main.c:715
static void do_hash_password(void)
Definition main.c:792
int tor_init(int argc, char *argv[])
Definition main.c:544
int try_locking(const or_options_t *options, int err_if_locked)
Definition main.c:672
static int do_keygen_family(const char *fname_base)
Definition main.c:842
static void process_signal(int sig)
Definition main.c:225
static void dumpstats(int severity)
Definition main.c:337
int have_lockfile(void)
Definition main.c:708
static void dumpmemusage(int severity)
Definition main.c:324
int signal_value
Definition main.c:447
int try_to_register
Definition main.c:450
static void signal_callback(evutil_socket_t fd, short events, void *arg)
Definition main.c:212
void tor_remove_file(const char *filename)
Definition main.c:728
static int do_hup(void)
Definition main.c:115
void handle_signals(void)
Definition main.c:490
void pubsub_install(void)
Definition main.c:1382
void pubsub_connect(void)
Definition main.c:1394
Header file for main.c.
uint64_t get_bytes_read(void)
Definition mainloop.c:455
void update_current_time(time_t now)
Definition mainloop.c:2226
void do_signewnym(time_t now)
Definition mainloop.c:1326
void initialize_mainloop_events(void)
Definition mainloop.c:2362
int do_main_loop(void)
Definition mainloop.c:2376
void schedule_rescan_periodic_events(void)
Definition mainloop.c:1585
smartlist_t * get_connection_array(void)
Definition mainloop.c:443
void tor_shutdown_event_loop_and_exit(int exitcode)
Definition mainloop.c:773
void tor_init_connection_lists(void)
Definition mainloop.c:404
void directory_info_has_arrived(time_t now, int from_cache, int suppress_logs)
Definition mainloop.c:1124
uint64_t get_bytes_written(void)
Definition mainloop.c:465
time_t time_of_process_start
Definition mainloop.c:142
Header file for mainloop.c.
int tor_mainloop_connect_pubsub(struct pubsub_builder_t *builder)
void tor_mainloop_connect_pubsub_events(void)
int tor_mainloop_set_delivery_strategy(const char *msg_channel_name, deliv_strategy_t strategy)
Header for mainloop_pubsub.c.
@ DELIV_IMMEDIATE
void tor_free_(void *mem)
Definition malloc.c:227
void * tor_malloc_(size_t size)
Definition malloc.c:32
void * tor_realloc_(void *ptr, size_t size)
Definition malloc.c:118
#define tor_free(p)
Definition malloc.h:56
Header for meminfo.c.
int net_is_disabled(void)
Definition netstatus.c:25
void set_network_participation(bool participation)
Definition netstatus.c:101
void reset_user_activity(time_t now)
Definition netstatus.c:82
void note_user_activity(time_t now)
Definition netstatus.c:63
Header for netstatus.c.
void update_networkstatus_downloads(time_t now)
networkstatus_t * networkstatus_get_latest_consensus(void)
int router_reload_consensus_networkstatus(void)
Header file for networkstatus.c.
Header file for ntmain.c.
Master header file for Tor-specific functionality.
#define RELAY_PAYLOAD_SIZE_MAX
Definition or.h:576
OR connection structure.
int get_parent_directory(char *fname)
Definition path.c:196
Listener port configuration structure.
Header file for predict_ports.c.
int tor_asprintf(char **strp, const char *fmt,...)
Definition printf.c:75
int tor_snprintf(char *str, size_t size, const char *format,...)
Definition printf.c:27
int dirserv_load_fingerprint_file(void)
Header file for process_descs.c.
pubsub_builder_t * pubsub_builder_new(void)
Header used for constructing the OO publish-subscribe facility.
struct pubsub_builder_t pubsub_builder_t
quiet_level_t quiet_level
Definition quiet_level.c:20
void add_default_log_for_quiet_level(quiet_level_t quiet)
Definition quiet_level.c:24
Declare the quiet_level enumeration and global.
quiet_level_t
Definition quiet_level.h:16
@ QUIET_NONE
Definition quiet_level.h:18
uint64_t stats_n_data_cells_received
Definition relay.c:2183
void dump_cell_pool_usage(int severity)
Definition relay.c:2677
uint64_t stats_n_relay_cells_relayed
Definition relay.c:137
uint64_t stats_n_data_cells_packaged
Definition relay.c:2177
uint64_t stats_n_data_bytes_received
Definition relay.c:2187
uint64_t stats_n_relay_cells_delivered
Definition relay.c:141
uint64_t stats_n_data_bytes_packaged
Definition relay.c:2181
Header file for relay.c.
uint64_t rephist_total_alloc
Definition rephist.c:95
void rep_hist_init(void)
Definition rephist.c:625
void rep_hist_dump_stats(time_t now, int severity)
Definition rephist.c:946
uint32_t rephist_total_num
Definition rephist.c:97
Header file for rephist.c.
Header for resolve.c.
const char risky_option_list[]
Header for risky_options.c.
void router_reset_warnings(void)
Definition router.c:3733
void router_reload_manual_onion_keys(void)
Definition router.c:587
int init_keys(void)
Definition router.c:1073
int client_identity_key_is_set(void)
Definition router.c:466
smartlist_t * list_family_key_files(const or_options_t *options, const char *keydir)
Definition routerkeys.c:782
Header for routerkeys.c.
void dump_routerlist_mem_usage(int severity)
int router_reload_router_list(void)
Definition routerlist.c:458
void routerlist_reset_warnings(void)
void router_reset_descriptor_download_failures(void)
Header file for routerlist.c.
Header file for routermode.c.
void routerparse_init(void)
Header file for routerparse.c.
int sandbox_cfg_allow_open_filename(sandbox_cfg_t **cfg, char *file)
Definition sandbox.c:2322
int sandbox_cfg_allow_stat_filename(sandbox_cfg_t **cfg, char *file)
Definition sandbox.c:2343
sandbox_cfg_t * sandbox_cfg_new(void)
Definition sandbox.c:2292
int sandbox_init(sandbox_cfg_t *cfg)
Definition sandbox.c:2298
int sandbox_cfg_allow_openat_filename(sandbox_cfg_t **cfg, char *file)
Definition sandbox.c:2329
Header file for sandbox.c.
struct sandbox_cfg_elem_t sandbox_cfg_t
Definition sandbox.h:38
#define sandbox_intern_string(s)
Definition sandbox.h:113
int sr_init(int save_to_disk)
This file contains ABI/API of the shared random protocol defined in proposal #250....
void tor_free_all(int postfork)
Definition shutdown.c:111
void tor_cleanup(void)
Definition shutdown.c:60
Header file for shutdown.c.
smartlist_t * smartlist_new(void)
#define SMARTLIST_FOREACH_BEGIN(sl, type, var)
#define SMARTLIST_FOREACH(sl, type, var, cmd)
or_state_t * get_or_state(void)
Definition statefile.c:220
Header for statefile.c.
int log_heartbeat(time_t now)
Definition status.c:184
Header for status.c.
struct tor_tls_t * tls
char * command_arg
char * ServerDNSResolvConfFile
char * FamilyKeyDirectory
int ManualOnionKeyRotation
struct smartlist_t * FilesOpenedByIncludes
char * V3BandwidthsFile
char * DirPortFrontPage
char * DataDirectory
int BridgeAuthoritativeDir
quiet_level_t quiet_level
Definition config.h:203
tor_cmdline_mode_t command
Definition config.h:199
int subsystems_add_pubsub(pubsub_builder_t *builder)
Definition subsysmgr.c:195
int subsystems_init(void)
Definition subsysmgr.c:114
Header for subsysmgr.c.
void timers_initialize(void)
Definition timers.c:205
Header for timers.c.
Public C API for the Tor network service.
Internal declarations for in-process Tor API.
@ CMD_HASH_PASSWORD
@ CMD_LIST_FINGERPRINT
@ CMD_VERIFY_CONFIG
@ CMD_RUN_TOR
@ CMD_KEY_EXPIRATION
@ CMD_KEYGEN
@ CMD_DUMP_CONFIG
@ CMD_IMMEDIATE
@ CMD_KEYGEN_ONION
@ CMD_KEYGEN_FAMILY
@ CMD_RUN_UNITTESTS
Headers for tortls.c.
int tor_tls_get_buffer_sizes(tor_tls_t *tls, size_t *rbuf_capacity, size_t *rbuf_bytes, size_t *wbuf_capacity, size_t *wbuf_bytes)
Definition tortls_nss.c:636
Header for version.c.
const char * get_version(void)
Definition version.c:38
Header for trace.c.
const char * get_uname(void)
Definition uname.c:67
Header for uname.c.
#define tor_assert(expr)
Definition util_bug.h:103
void notify_pending_waitpid_callbacks(void)
Definition waitpid.c:141
Headers for waitpid.c.
#define ED25519_BASE64_LEN