tor  0.4.1.0-alpha-dev
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-2019, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
6 
12 #include "core/or/or.h"
13 
14 #include "app/config/config.h"
15 #include "app/config/statefile.h"
16 #include "app/main/main.h"
17 #include "app/main/ntmain.h"
18 #include "app/main/subsysmgr.h"
21 #include "core/mainloop/mainloop.h"
22 #include "core/mainloop/netstatus.h"
23 #include "core/or/channel.h"
24 #include "core/or/channelpadding.h"
25 #include "core/or/circuitpadding.h"
26 #include "core/or/channeltls.h"
27 #include "core/or/circuitlist.h"
29 #include "core/or/command.h"
31 #include "core/or/connection_or.h"
32 #include "core/or/dos.h"
33 #include "core/or/policies.h"
34 #include "core/or/protover.h"
35 #include "core/or/relay.h"
36 #include "core/or/scheduler.h"
37 #include "core/or/status.h"
38 #include "core/or/versions.h"
39 #include "feature/api/tor_api.h"
40 #include "feature/api/tor_api_internal.h"
41 #include "feature/client/addressmap.h"
42 #include "feature/client/bridges.h"
46 #include "feature/dirauth/bwauth.h"
47 #include "feature/dirauth/keypin.h"
49 #include "feature/dircache/consdiffmgr.h"
53 #include "feature/hs/hs_cache.h"
59 #include "feature/relay/dns.h"
60 #include "feature/relay/ext_orport.h"
62 #include "feature/relay/routerkeys.h"
64 #include "feature/rend/rendcache.h"
68 #include "feature/stats/predict_ports.h"
69 #include "feature/stats/rephist.h"
70 #include "lib/compress/compress.h"
71 #include "lib/buf/buffers.h"
74 #include "lib/geoip/geoip.h"
75 #include "lib/net/resolve.h"
76 
77 #include "lib/process/waitpid.h"
78 
79 #include "lib/meminfo/meminfo.h"
80 #include "lib/osinfo/uname.h"
81 #include "lib/sandbox/sandbox.h"
82 #include "lib/fs/lockfile.h"
83 #include "lib/net/resolve.h"
84 #include "lib/tls/tortls.h"
86 #include "lib/encoding/confline.h"
87 #include "lib/evloop/timers.h"
89 #include "lib/version/torversion.h"
90 
91 #include <event2/event.h>
92 
95 #include "feature/dirauth/shared_random.h"
96 
97 #include "core/or/or_connection_st.h"
98 #include "core/or/port_cfg_st.h"
99 
100 #ifdef HAVE_UNISTD_H
101 #include <unistd.h>
102 #endif
103 
104 #ifdef HAVE_SYSTEMD
105 # if defined(__COVERITY__) && !defined(__INCLUDE_LEVEL__)
106 /* Systemd's use of gcc's __INCLUDE_LEVEL__ extension macro appears to confuse
107  * Coverity. Here's a kludge to unconfuse it.
108  */
109 # define __INCLUDE_LEVEL__ 2
110 #endif /* defined(__COVERITY__) && !defined(__INCLUDE_LEVEL__) */
111 #include <systemd/sd-daemon.h>
112 #endif /* defined(HAVE_SYSTEMD) */
113 
114 void evdns_shutdown(int);
115 
116 #ifdef HAVE_RUST
117 // helper function defined in Rust to output a log message indicating if tor is
118 // running with Rust enabled. See src/rust/tor_util
119 void rust_log_welcome_string(void);
120 #endif
121 
122 /********* PROTOTYPES **********/
123 
124 static void dumpmemusage(int severity);
125 static void dumpstats(int severity); /* log stats */
126 static void process_signal(int sig);
127 
128 /********* START VARIABLES **********/
129 
134 int quiet_level = 0;
135 
136 /********* END VARIABLES ************/
137 
140 static int
141 do_hup(void)
142 {
143  const or_options_t *options = get_options();
144 
145  log_notice(LD_GENERAL,"Received reload signal (hup). Reloading config and "
146  "resetting internal state.");
147  if (accounting_is_enabled(options))
148  accounting_record_bandwidth_usage(time(NULL), get_or_state());
149 
152  /* first, reload config variables, in case they've changed */
153  if (options->ReloadTorrcOnSIGHUP) {
154  /* no need to provide argc/v, they've been cached in init_from_config */
155  int init_rv = options_init_from_torrc(0, NULL);
156  if (init_rv < 0) {
157  log_err(LD_CONFIG,"Reading config failed--see warnings above. "
158  "For usage, try -h.");
159  return -1;
160  } else if (BUG(init_rv > 0)) {
161  // LCOV_EXCL_START
162  /* This should be impossible: the only "return 1" cases in
163  * options_init_from_torrc are ones caused by command-line arguments;
164  * but they can't change while Tor is running. */
165  return -1;
166  // LCOV_EXCL_STOP
167  }
168  options = get_options(); /* they have changed now */
169  /* Logs are only truncated the first time they are opened, but were
170  probably intended to be cleaned up on signal. */
171  if (options->TruncateLogFile)
172  truncate_logs();
173  } else {
174  char *msg = NULL;
175  log_notice(LD_GENERAL, "Not reloading config file: the controller told "
176  "us not to.");
177  /* Make stuff get rescanned, reloaded, etc. */
178  if (set_options((or_options_t*)options, &msg) < 0) {
179  if (!msg)
180  msg = tor_strdup("Unknown error");
181  log_warn(LD_GENERAL, "Unable to re-set previous options: %s", msg);
182  tor_free(msg);
183  }
184  }
185  if (authdir_mode(options)) {
186  /* reload the approved-routers file */
187  if (dirserv_load_fingerprint_file() < 0) {
188  /* warnings are logged from dirserv_load_fingerprint_file() directly */
189  log_info(LD_GENERAL, "Error reloading fingerprints. "
190  "Continuing with old list.");
191  }
192  }
193 
194  /* Rotate away from the old dirty circuits. This has to be done
195  * after we've read the new options, but before we start using
196  * circuits for directory fetches. */
198 
199  /* retry appropriate downloads */
202  if (!net_is_disabled())
203  update_networkstatus_downloads(time(NULL));
204 
205  /* We'll retry routerstatus downloads in about 10 seconds; no need to
206  * force a retry there. */
207 
208  if (server_mode(options)) {
209  /* Maybe we've been given a new ed25519 key or certificate?
210  */
211  time_t now = approx_time();
212  int new_signing_key = load_ed_keys(options, now);
213  if (new_signing_key < 0 ||
214  generate_ed_link_cert(options, now, new_signing_key > 0)) {
215  log_warn(LD_OR, "Problem reloading Ed25519 keys; still using old keys.");
216  }
217 
218  /* Update cpuworker and dnsworker processes, so they get up-to-date
219  * configuration options. */
221  dns_reset();
222  }
223  return 0;
224 }
225 
228 static void
229 signal_callback(evutil_socket_t fd, short events, void *arg)
230 {
231  const int *sigptr = arg;
232  const int sig = *sigptr;
233  (void)fd;
234  (void)events;
235 
236  update_current_time(time(NULL));
237  process_signal(sig);
238 }
239 
241 static void
243 {
244  switch (sig)
245  {
246  case SIGTERM:
247  log_notice(LD_GENERAL,"Catching signal TERM, exiting cleanly.");
249  break;
250  case SIGINT:
251  if (!server_mode(get_options())) { /* do it now */
252  log_notice(LD_GENERAL,"Interrupt: exiting cleanly.");
254  return;
255  }
256 #ifdef HAVE_SYSTEMD
257  sd_notify(0, "STOPPING=1");
258 #endif
260  break;
261 #ifdef SIGPIPE
262  case SIGPIPE:
263  log_debug(LD_GENERAL,"Caught SIGPIPE. Ignoring.");
264  break;
265 #endif
266  case SIGUSR1:
267  /* prefer to log it at INFO, but make sure we always see it */
270  break;
271  case SIGUSR2:
273  log_debug(LD_GENERAL,"Caught USR2, going to loglevel debug. "
274  "Send HUP to change back.");
276  break;
277  case SIGHUP:
278 #ifdef HAVE_SYSTEMD
279  sd_notify(0, "RELOADING=1");
280 #endif
281  if (do_hup() < 0) {
282  log_warn(LD_CONFIG,"Restart failed (config error?). Exiting.");
284  return;
285  }
286 #ifdef HAVE_SYSTEMD
287  sd_notify(0, "READY=1");
288 #endif
290  break;
291 #ifdef SIGCHLD
292  case SIGCHLD:
294  break;
295 #endif
296  case SIGNEWNYM: {
297  do_signewnym(time(NULL));
298  break;
299  }
300  case SIGCLEARDNSCACHE:
303  break;
304  case SIGHEARTBEAT:
305  log_heartbeat(time(NULL));
307  break;
308  case SIGACTIVE:
309  /* "SIGACTIVE" counts as ersatz user activity. */
310  note_user_activity(approx_time());
312  break;
313  case SIGDORMANT:
314  /* "SIGDORMANT" means to ignore past user activity */
315  log_notice(LD_GENERAL, "Going dormant because of controller request.");
316  reset_user_activity(0);
317  set_network_participation(false);
318  schedule_rescan_periodic_events();
320  break;
321  }
322 }
323 
327 static void
328 dumpmemusage(int severity)
329 {
331  tor_log(severity, LD_GENERAL, "In rephist: %"PRIu64" used by %d Tors.",
333  dump_routerlist_mem_usage(severity);
334  dump_cell_pool_usage(severity);
335  dump_dns_mem_usage(severity);
336  tor_log_mallinfo(severity);
337 }
338 
341 static void
342 dumpstats(int severity)
343 {
344  time_t now = time(NULL);
345  time_t elapsed;
346  size_t rbuf_cap, wbuf_cap, rbuf_len, wbuf_len;
347 
348  tor_log(severity, LD_GENERAL, "Dumping stats:");
349 
350  SMARTLIST_FOREACH_BEGIN(get_connection_array(), connection_t *, conn) {
351  int i = conn_sl_idx;
352  tor_log(severity, LD_GENERAL,
353  "Conn %d (socket %d) type %d (%s), state %d (%s), created %d secs ago",
354  i, (int)conn->s, conn->type, conn_type_to_string(conn->type),
355  conn->state, conn_state_to_string(conn->type, conn->state),
356  (int)(now - conn->timestamp_created));
357  if (!connection_is_listener(conn)) {
358  tor_log(severity,LD_GENERAL,
359  "Conn %d is to %s:%d.", i,
360  safe_str_client(conn->address),
361  conn->port);
362  tor_log(severity,LD_GENERAL,
363  "Conn %d: %d bytes waiting on inbuf (len %d, last read %d secs ago)",
364  i,
365  (int)connection_get_inbuf_len(conn),
366  (int)buf_allocation(conn->inbuf),
367  (int)(now - conn->timestamp_last_read_allowed));
368  tor_log(severity,LD_GENERAL,
369  "Conn %d: %d bytes waiting on outbuf "
370  "(len %d, last written %d secs ago)",i,
371  (int)connection_get_outbuf_len(conn),
372  (int)buf_allocation(conn->outbuf),
373  (int)(now - conn->timestamp_last_write_allowed));
374  if (conn->type == CONN_TYPE_OR) {
375  or_connection_t *or_conn = TO_OR_CONN(conn);
376  if (or_conn->tls) {
377  if (tor_tls_get_buffer_sizes(or_conn->tls, &rbuf_cap, &rbuf_len,
378  &wbuf_cap, &wbuf_len) == 0) {
379  tor_log(severity, LD_GENERAL,
380  "Conn %d: %d/%d bytes used on OpenSSL read buffer; "
381  "%d/%d bytes used on write buffer.",
382  i, (int)rbuf_len, (int)rbuf_cap, (int)wbuf_len, (int)wbuf_cap);
383  }
384  }
385  }
386  }
387  circuit_dump_by_conn(conn, severity); /* dump info about all the circuits
388  * using this conn */
389  } SMARTLIST_FOREACH_END(conn);
390 
391  channel_dumpstats(severity);
392  channel_listener_dumpstats(severity);
393 
394  tor_log(severity, LD_NET,
395  "Cells processed: %"PRIu64" padding\n"
396  " %"PRIu64" create\n"
397  " %"PRIu64" created\n"
398  " %"PRIu64" relay\n"
399  " (%"PRIu64" relayed)\n"
400  " (%"PRIu64" delivered)\n"
401  " %"PRIu64" destroy",
410  tor_log(severity,LD_NET,"Average packaged cell fullness: %2.3f%%",
411  100*(((double)stats_n_data_bytes_packaged) /
414  tor_log(severity,LD_NET,"Average delivered cell fullness: %2.3f%%",
415  100*(((double)stats_n_data_bytes_received) /
417 
418  cpuworker_log_onionskin_overhead(severity, ONION_HANDSHAKE_TYPE_TAP, "TAP");
419  cpuworker_log_onionskin_overhead(severity, ONION_HANDSHAKE_TYPE_NTOR,"ntor");
420 
421  if (now - time_of_process_start >= 0)
422  elapsed = now - time_of_process_start;
423  else
424  elapsed = 0;
425 
426  if (elapsed) {
427  tor_log(severity, LD_NET,
428  "Average bandwidth: %"PRIu64"/%d = %d bytes/sec reading",
429  (get_bytes_read()),
430  (int)elapsed,
431  (int) (get_bytes_read()/elapsed));
432  tor_log(severity, LD_NET,
433  "Average bandwidth: %"PRIu64"/%d = %d bytes/sec writing",
434  (get_bytes_written()),
435  (int)elapsed,
436  (int) (get_bytes_written()/elapsed));
437  }
438 
439  tor_log(severity, LD_NET, "--------------- Dumping memory information:");
440  dumpmemusage(severity);
441 
442  rep_hist_dump_stats(now,severity);
443  rend_service_dump_stats(severity);
444 }
445 
446 #ifdef _WIN32
447 #define UNIX_ONLY 0
448 #else
449 #define UNIX_ONLY 1
450 #endif
451 
452 static struct {
460  struct event *signal_event;
461 } signal_handlers[] = {
462 #ifdef SIGINT
463  { SIGINT, UNIX_ONLY, NULL }, /* do a controlled slow shutdown */
464 #endif
465 #ifdef SIGTERM
466  { SIGTERM, UNIX_ONLY, NULL }, /* to terminate now */
467 #endif
468 #ifdef SIGPIPE
469  { SIGPIPE, UNIX_ONLY, NULL }, /* otherwise SIGPIPE kills us */
470 #endif
471 #ifdef SIGUSR1
472  { SIGUSR1, UNIX_ONLY, NULL }, /* dump stats */
473 #endif
474 #ifdef SIGUSR2
475  { SIGUSR2, UNIX_ONLY, NULL }, /* go to loglevel debug */
476 #endif
477 #ifdef SIGHUP
478  { SIGHUP, UNIX_ONLY, NULL }, /* to reload config, retry conns, etc */
479 #endif
480 #ifdef SIGXFSZ
481  { SIGXFSZ, UNIX_ONLY, NULL }, /* handle file-too-big resource exhaustion */
482 #endif
483 #ifdef SIGCHLD
484  { SIGCHLD, UNIX_ONLY, NULL }, /* handle dns/cpu workers that exit */
485 #endif
486  /* These are controller-only */
487  { SIGNEWNYM, 0, NULL },
488  { SIGCLEARDNSCACHE, 0, NULL },
489  { SIGHEARTBEAT, 0, NULL },
490  { SIGACTIVE, 0, NULL },
491  { SIGDORMANT, 0, NULL },
492  { -1, -1, NULL }
493 };
494 
497 void
499 {
500  int i;
501  const int enabled = !get_options()->DisableSignalHandlers;
502 
503  for (i = 0; signal_handlers[i].signal_value >= 0; ++i) {
504  /* Signal handlers are only registered with libevent if they need to catch
505  * real POSIX signals. We construct these signal handler events in either
506  * case, though, so that controllers can activate them with the SIGNAL
507  * command.
508  */
509  if (enabled && signal_handlers[i].try_to_register) {
510  signal_handlers[i].signal_event =
511  tor_evsignal_new(tor_libevent_get_base(),
512  signal_handlers[i].signal_value,
514  &signal_handlers[i].signal_value);
515  if (event_add(signal_handlers[i].signal_event, NULL))
516  log_warn(LD_BUG, "Error from libevent when adding "
517  "event for signal %d",
518  signal_handlers[i].signal_value);
519  } else {
520  signal_handlers[i].signal_event =
521  tor_event_new(tor_libevent_get_base(), -1,
522  EV_SIGNAL, signal_callback,
523  &signal_handlers[i].signal_value);
524  }
525  }
526 }
527 
528 /* Cause the signal handler for signal_num to be called in the event loop. */
529 void
530 activate_signal(int signal_num)
531 {
532  int i;
533  for (i = 0; signal_handlers[i].signal_value >= 0; ++i) {
534  if (signal_handlers[i].signal_value == signal_num) {
535  event_active(signal_handlers[i].signal_event, EV_SIGNAL, 1);
536  return;
537  }
538  }
539 }
540 
544 int
545 tor_init(int argc, char *argv[])
546 {
547  char progname[256];
548  int quiet = 0;
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. */
557  rep_hist_init();
558  /* Initialize the service cache. */
559  rend_cache_init();
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 search for the "quiet" option first, since it decides whether we
568  * will log anything at all to the command line. */
569  config_line_t *opts = NULL, *cmdline_opts = NULL;
570  const config_line_t *cl;
571  (void) config_parse_commandline(argc, argv, 1, &opts, &cmdline_opts);
572  for (cl = cmdline_opts; cl; cl = cl->next) {
573  if (!strcmp(cl->key, "--hush"))
574  quiet = 1;
575  if (!strcmp(cl->key, "--quiet") ||
576  !strcmp(cl->key, "--dump-config"))
577  quiet = 2;
578  /* The following options imply --hush */
579  if (!strcmp(cl->key, "--version") || !strcmp(cl->key, "--digests") ||
580  !strcmp(cl->key, "--list-torrc-options") ||
581  !strcmp(cl->key, "--library-versions") ||
582  !strcmp(cl->key, "--hash-password") ||
583  !strcmp(cl->key, "-h") || !strcmp(cl->key, "--help")) {
584  if (quiet < 1)
585  quiet = 1;
586  }
587  }
588  config_free_lines(opts);
589  config_free_lines(cmdline_opts);
590  }
591 
592  /* give it somewhere to log to initially */
593  switch (quiet) {
594  case 2:
595  /* no initial logging */
596  break;
597  case 1:
599  break;
600  default:
602  }
603  quiet_level = quiet;
604 
605  {
606  const char *version = get_version();
607 
608  log_notice(LD_GENERAL, "Tor %s running on %s with Libevent %s, "
609  "%s %s, Zlib %s, Liblzma %s, and Libzstd %s.", version,
610  get_uname(),
614  tor_compress_supports_method(ZLIB_METHOD) ?
615  tor_compress_version_str(ZLIB_METHOD) : "N/A",
616  tor_compress_supports_method(LZMA_METHOD) ?
617  tor_compress_version_str(LZMA_METHOD) : "N/A",
618  tor_compress_supports_method(ZSTD_METHOD) ?
619  tor_compress_version_str(ZSTD_METHOD) : "N/A");
620 
621  log_notice(LD_GENERAL, "Tor can't help you if you use it wrong! "
622  "Learn how to be safe at "
623  "https://www.torproject.org/download/download#warning");
624 
625  if (strstr(version, "alpha") || strstr(version, "beta"))
626  log_notice(LD_GENERAL, "This version is not a stable Tor release. "
627  "Expect more bugs than usual.");
628 
630  }
631 
632 #ifdef HAVE_RUST
633  rust_log_welcome_string();
634 #endif /* defined(HAVE_RUST) */
635 
636  int init_rv = options_init_from_torrc(argc,argv);
637  if (init_rv < 0) {
638  log_err(LD_CONFIG,"Reading config failed--see warnings above.");
639  return -1;
640  } else if (init_rv > 0) {
641  // We succeeded, and should exit anyway -- probably the user just said
642  // "--version" or something like that.
643  return 1;
644  }
645 
646  /* The options are now initialised */
647  const or_options_t *options = get_options();
648 
649  /* Initialize channelpadding and circpad parameters to defaults
650  * until we get a consensus */
651  channelpadding_new_consensus_params(NULL);
653 
654  /* Initialize circuit padding to defaults+torrc until we get a consensus */
656 
657  /* Initialize predicted ports list after loading options */
658  predicted_ports_init();
659 
660 #ifndef _WIN32
661  if (geteuid()==0)
662  log_warn(LD_GENERAL,"You are running Tor as root. You don't need to, "
663  "and you probably shouldn't.");
664 #endif
665 
666  if (crypto_global_init(options->HardwareAccel,
667  options->AccelName,
668  options->AccelDir)) {
669  log_err(LD_BUG, "Unable to initialize OpenSSL. Exiting.");
670  return -1;
671  }
672 
673  if (tor_init_libevent_rng() < 0) {
674  log_warn(LD_NET, "Problem initializing libevent RNG.");
675  }
676 
677  /* Scan/clean unparseable descriptors; after reading config */
679 
680  return 0;
681 }
682 
686 static tor_lockfile_t *lockfile = NULL;
687 
693 int
694 try_locking(const or_options_t *options, int err_if_locked)
695 {
696  if (lockfile)
697  return 0;
698  else {
699  char *fname = options_get_datadir_fname(options, "lock");
700  int already_locked = 0;
701  tor_lockfile_t *lf = tor_lockfile_lock(fname, 0, &already_locked);
702  tor_free(fname);
703  if (!lf) {
704  if (err_if_locked && already_locked) {
705  int r;
706  log_warn(LD_GENERAL, "It looks like another Tor process is running "
707  "with the same data directory. Waiting 5 seconds to see "
708  "if it goes away.");
709 #ifndef _WIN32
710  sleep(5);
711 #else
712  Sleep(5000);
713 #endif
714  r = try_locking(options, 0);
715  if (r<0) {
716  log_err(LD_GENERAL, "No, it's still there. Exiting.");
717  return -1;
718  }
719  return r;
720  }
721  return -1;
722  }
723  lockfile = lf;
724  return 0;
725  }
726 }
727 
729 int
731 {
732  return lockfile != NULL;
733 }
734 
736 void
738 {
739  if (lockfile) {
741  lockfile = NULL;
742  }
743 }
744 
753 void
754 tor_free_all(int postfork)
755 {
756  if (!postfork) {
757  evdns_shutdown(1);
758  }
759  geoip_free_all();
771  dns_free_all();
776  pt_free_all();
789  consdiffmgr_free_all();
790  hs_free_all();
791  dos_free_all();
795 
796  if (!postfork) {
797  config_free_all();
798  or_state_free_all();
799  router_free_all();
800  routerkeys_free_all();
802  }
803  if (!postfork) {
804 #ifndef _WIN32
805  tor_getpwnam(NULL);
806 #endif
807  }
808  /* stuff in main.c */
809 
810  tor_mainloop_free_all();
811 
812  if (!postfork) {
814  }
816 
817  subsystems_shutdown();
818 
819  /* Stuff in util.c and address.c*/
820  if (!postfork) {
821  esc_router_info(NULL);
822  }
823 }
824 
829 void
830 tor_remove_file(const char *filename)
831 {
832  if (filename && tor_unlink(filename) != 0 && errno != ENOENT) {
833  log_warn(LD_FS, "Couldn't unlink %s: %s",
834  filename, strerror(errno));
835  }
836 }
837 
839 void
841 {
842  const or_options_t *options = get_options();
843  if (options->command == CMD_RUN_TOR) {
844  time_t now = time(NULL);
845  /* Remove our pid file. We don't care if there was an error when we
846  * unlink, nothing we could do about it anyways. */
847  tor_remove_file(options->PidFile);
848  /* Remove control port file */
850  /* Remove cookie authentication file */
851  {
852  char *cookie_fname = get_controller_cookie_file_name();
853  tor_remove_file(cookie_fname);
854  tor_free(cookie_fname);
855  }
856  /* Remove Extended ORPort cookie authentication file */
857  {
858  char *cookie_fname = get_ext_or_auth_cookie_file_name();
859  tor_remove_file(cookie_fname);
860  tor_free(cookie_fname);
861  }
862  if (accounting_is_enabled(options))
863  accounting_record_bandwidth_usage(now, get_or_state());
864  or_state_mark_dirty(get_or_state(), 0); /* force an immediate save. */
865  or_state_save(now);
866  if (authdir_mode(options)) {
867  sr_save_and_cleanup();
868  }
869  if (authdir_mode_tests_reachability(options))
872  }
873 
874  timers_shutdown();
875 
876  tor_free_all(0); /* We could move tor_free_all back into the ifdef below
877  later, if it makes shutdown unacceptably slow. But for
878  now, leave it here: it's helped us catch bugs in the
879  past. */
880 }
881 
883 static int
885 {
886  char buf[FINGERPRINT_LEN+1];
887  crypto_pk_t *k;
888  const char *nickname = get_options()->Nickname;
889  sandbox_disable_getaddrinfo_cache();
890  if (!server_mode(get_options())) {
891  log_err(LD_GENERAL,
892  "Clients don't have long-term identity keys. Exiting.");
893  return -1;
894  }
895  tor_assert(nickname);
896  if (init_keys() < 0) {
897  log_err(LD_GENERAL,"Error initializing keys; exiting.");
898  return -1;
899  }
900  if (!(k = get_server_identity_key())) {
901  log_err(LD_GENERAL,"Error: missing identity key.");
902  return -1;
903  }
904  if (crypto_pk_get_fingerprint(k, buf, 1)<0) {
905  log_err(LD_BUG, "Error computing fingerprint");
906  return -1;
907  }
908  printf("%s %s\n", nickname, buf);
909  return 0;
910 }
911 
914 static void
916 {
917 
918  char output[256];
920 
921  crypto_rand(key, S2K_RFC2440_SPECIFIER_LEN-1);
922  key[S2K_RFC2440_SPECIFIER_LEN-1] = (uint8_t)96; /* Hash 64 K of data. */
924  get_options()->command_arg, strlen(get_options()->command_arg),
925  key);
926  base16_encode(output, sizeof(output), key, sizeof(key));
927  printf("16:%s\n",output);
928 }
929 
932 static int
934 {
935  const or_options_t *options = get_options();
936  const char *arg = options->command_arg;
937  int how;
938  char *opts;
939 
940  if (!strcmp(arg, "short")) {
941  how = OPTIONS_DUMP_MINIMAL;
942  } else if (!strcmp(arg, "non-builtin")) {
943  how = OPTIONS_DUMP_DEFAULTS;
944  } else if (!strcmp(arg, "full")) {
945  how = OPTIONS_DUMP_ALL;
946  } else {
947  fprintf(stderr, "No valid argument to --dump-config found!\n");
948  fprintf(stderr, "Please select 'short', 'non-builtin', or 'full'.\n");
949 
950  return -1;
951  }
952 
953  opts = options_dump(options, how);
954  printf("%s", opts);
955  tor_free(opts);
956 
957  return 0;
958 }
959 
960 static void
961 init_addrinfo(void)
962 {
963  if (! server_mode(get_options()) ||
964  (get_options()->Address && strlen(get_options()->Address) > 0)) {
965  /* We don't need to seed our own hostname, because we won't be calling
966  * resolve_my_address on it.
967  */
968  return;
969  }
970  char hname[256];
971 
972  // host name to sandbox
973  gethostname(hname, sizeof(hname));
974  tor_add_addrinfo(hname);
975 }
976 
977 static sandbox_cfg_t*
978 sandbox_init_filter(void)
979 {
980  const or_options_t *options = get_options();
982  int i;
983 
985  get_cachedir_fname("cached-status"));
986 
987 #define OPEN(name) \
988  sandbox_cfg_allow_open_filename(&cfg, tor_strdup(name))
989 
990 #define OPEN_DATADIR(name) \
991  sandbox_cfg_allow_open_filename(&cfg, get_datadir_fname(name))
992 
993 #define OPEN_DATADIR2(name, name2) \
994  sandbox_cfg_allow_open_filename(&cfg, get_datadir_fname2((name), (name2)))
995 
996 #define OPEN_DATADIR_SUFFIX(name, suffix) do { \
997  OPEN_DATADIR(name); \
998  OPEN_DATADIR(name suffix); \
999  } while (0)
1000 
1001 #define OPEN_DATADIR2_SUFFIX(name, name2, suffix) do { \
1002  OPEN_DATADIR2(name, name2); \
1003  OPEN_DATADIR2(name, name2 suffix); \
1004  } while (0)
1005 
1006 #define OPEN_KEY_DIRECTORY() \
1007  sandbox_cfg_allow_open_filename(&cfg, tor_strdup(options->KeyDirectory))
1008 #define OPEN_CACHEDIR(name) \
1009  sandbox_cfg_allow_open_filename(&cfg, get_cachedir_fname(name))
1010 #define OPEN_CACHEDIR_SUFFIX(name, suffix) do { \
1011  OPEN_CACHEDIR(name); \
1012  OPEN_CACHEDIR(name suffix); \
1013  } while (0)
1014 #define OPEN_KEYDIR(name) \
1015  sandbox_cfg_allow_open_filename(&cfg, get_keydir_fname(name))
1016 #define OPEN_KEYDIR_SUFFIX(name, suffix) do { \
1017  OPEN_KEYDIR(name); \
1018  OPEN_KEYDIR(name suffix); \
1019  } while (0)
1020 
1021  OPEN(options->DataDirectory);
1022  OPEN_KEY_DIRECTORY();
1023 
1024  OPEN_CACHEDIR_SUFFIX("cached-certs", ".tmp");
1025  OPEN_CACHEDIR_SUFFIX("cached-consensus", ".tmp");
1026  OPEN_CACHEDIR_SUFFIX("unverified-consensus", ".tmp");
1027  OPEN_CACHEDIR_SUFFIX("unverified-microdesc-consensus", ".tmp");
1028  OPEN_CACHEDIR_SUFFIX("cached-microdesc-consensus", ".tmp");
1029  OPEN_CACHEDIR_SUFFIX("cached-microdescs", ".tmp");
1030  OPEN_CACHEDIR_SUFFIX("cached-microdescs.new", ".tmp");
1031  OPEN_CACHEDIR_SUFFIX("cached-descriptors", ".tmp");
1032  OPEN_CACHEDIR_SUFFIX("cached-descriptors.new", ".tmp");
1033  OPEN_CACHEDIR("cached-descriptors.tmp.tmp");
1034  OPEN_CACHEDIR_SUFFIX("cached-extrainfo", ".tmp");
1035  OPEN_CACHEDIR_SUFFIX("cached-extrainfo.new", ".tmp");
1036  OPEN_CACHEDIR("cached-extrainfo.tmp.tmp");
1037 
1038  OPEN_DATADIR_SUFFIX("state", ".tmp");
1039  OPEN_DATADIR_SUFFIX("sr-state", ".tmp");
1040  OPEN_DATADIR_SUFFIX("unparseable-desc", ".tmp");
1041  OPEN_DATADIR_SUFFIX("v3-status-votes", ".tmp");
1042  OPEN_DATADIR("key-pinning-journal");
1043  OPEN("/dev/srandom");
1044  OPEN("/dev/urandom");
1045  OPEN("/dev/random");
1046  OPEN("/etc/hosts");
1047  OPEN("/proc/meminfo");
1048 
1049  if (options->BridgeAuthoritativeDir)
1050  OPEN_DATADIR_SUFFIX("networkstatus-bridges", ".tmp");
1051 
1052  if (authdir_mode(options))
1053  OPEN_DATADIR("approved-routers");
1054 
1055  if (options->ServerDNSResolvConfFile)
1057  tor_strdup(options->ServerDNSResolvConfFile));
1058  else
1059  sandbox_cfg_allow_open_filename(&cfg, tor_strdup("/etc/resolv.conf"));
1060 
1061  for (i = 0; i < 2; ++i) {
1062  if (get_torrc_fname(i)) {
1063  sandbox_cfg_allow_open_filename(&cfg, tor_strdup(get_torrc_fname(i)));
1064  }
1065  }
1066 
1067  SMARTLIST_FOREACH(options->FilesOpenedByIncludes, char *, f, {
1068  OPEN(f);
1069  });
1070 
1071 #define RENAME_SUFFIX(name, suffix) \
1072  sandbox_cfg_allow_rename(&cfg, \
1073  get_datadir_fname(name suffix), \
1074  get_datadir_fname(name))
1075 
1076 #define RENAME_SUFFIX2(prefix, name, suffix) \
1077  sandbox_cfg_allow_rename(&cfg, \
1078  get_datadir_fname2(prefix, name suffix), \
1079  get_datadir_fname2(prefix, name))
1080 
1081 #define RENAME_CACHEDIR_SUFFIX(name, suffix) \
1082  sandbox_cfg_allow_rename(&cfg, \
1083  get_cachedir_fname(name suffix), \
1084  get_cachedir_fname(name))
1085 
1086 #define RENAME_KEYDIR_SUFFIX(name, suffix) \
1087  sandbox_cfg_allow_rename(&cfg, \
1088  get_keydir_fname(name suffix), \
1089  get_keydir_fname(name))
1090 
1091  RENAME_CACHEDIR_SUFFIX("cached-certs", ".tmp");
1092  RENAME_CACHEDIR_SUFFIX("cached-consensus", ".tmp");
1093  RENAME_CACHEDIR_SUFFIX("unverified-consensus", ".tmp");
1094  RENAME_CACHEDIR_SUFFIX("unverified-microdesc-consensus", ".tmp");
1095  RENAME_CACHEDIR_SUFFIX("cached-microdesc-consensus", ".tmp");
1096  RENAME_CACHEDIR_SUFFIX("cached-microdescs", ".tmp");
1097  RENAME_CACHEDIR_SUFFIX("cached-microdescs", ".new");
1098  RENAME_CACHEDIR_SUFFIX("cached-microdescs.new", ".tmp");
1099  RENAME_CACHEDIR_SUFFIX("cached-descriptors", ".tmp");
1100  RENAME_CACHEDIR_SUFFIX("cached-descriptors", ".new");
1101  RENAME_CACHEDIR_SUFFIX("cached-descriptors.new", ".tmp");
1102  RENAME_CACHEDIR_SUFFIX("cached-extrainfo", ".tmp");
1103  RENAME_CACHEDIR_SUFFIX("cached-extrainfo", ".new");
1104  RENAME_CACHEDIR_SUFFIX("cached-extrainfo.new", ".tmp");
1105 
1106  RENAME_SUFFIX("state", ".tmp");
1107  RENAME_SUFFIX("sr-state", ".tmp");
1108  RENAME_SUFFIX("unparseable-desc", ".tmp");
1109  RENAME_SUFFIX("v3-status-votes", ".tmp");
1110 
1111  if (options->BridgeAuthoritativeDir)
1112  RENAME_SUFFIX("networkstatus-bridges", ".tmp");
1113 
1114 #define STAT_DATADIR(name) \
1115  sandbox_cfg_allow_stat_filename(&cfg, get_datadir_fname(name))
1116 
1117 #define STAT_CACHEDIR(name) \
1118  sandbox_cfg_allow_stat_filename(&cfg, get_cachedir_fname(name))
1119 
1120 #define STAT_DATADIR2(name, name2) \
1121  sandbox_cfg_allow_stat_filename(&cfg, get_datadir_fname2((name), (name2)))
1122 
1123 #define STAT_KEY_DIRECTORY() \
1124  sandbox_cfg_allow_stat_filename(&cfg, tor_strdup(options->KeyDirectory))
1125 
1126  STAT_DATADIR(NULL);
1127  STAT_DATADIR("lock");
1128  STAT_DATADIR("state");
1129  STAT_DATADIR("router-stability");
1130 
1131  STAT_CACHEDIR("cached-extrainfo.new");
1132 
1133  {
1134  smartlist_t *files = smartlist_new();
1136  SMARTLIST_FOREACH(files, char *, file_name, {
1137  /* steals reference */
1138  sandbox_cfg_allow_open_filename(&cfg, file_name);
1139  });
1140  smartlist_free(files);
1141  }
1142 
1143  {
1144  smartlist_t *files = smartlist_new();
1145  smartlist_t *dirs = smartlist_new();
1146  hs_service_lists_fnames_for_sandbox(files, dirs);
1147  SMARTLIST_FOREACH(files, char *, file_name, {
1148  char *tmp_name = NULL;
1149  tor_asprintf(&tmp_name, "%s.tmp", file_name);
1150  sandbox_cfg_allow_rename(&cfg,
1151  tor_strdup(tmp_name), tor_strdup(file_name));
1152  /* steals references */
1153  sandbox_cfg_allow_open_filename(&cfg, file_name);
1154  sandbox_cfg_allow_open_filename(&cfg, tmp_name);
1155  });
1156  SMARTLIST_FOREACH(dirs, char *, dir, {
1157  /* steals reference */
1159  });
1160  smartlist_free(files);
1161  smartlist_free(dirs);
1162  }
1163 
1164  {
1165  char *fname;
1166  if ((fname = get_controller_cookie_file_name())) {
1167  sandbox_cfg_allow_open_filename(&cfg, fname);
1168  }
1169  if ((fname = get_ext_or_auth_cookie_file_name())) {
1170  sandbox_cfg_allow_open_filename(&cfg, fname);
1171  }
1172  }
1173 
1174  SMARTLIST_FOREACH_BEGIN(get_configured_ports(), port_cfg_t *, port) {
1175  if (!port->is_unix_addr)
1176  continue;
1177  /* When we open an AF_UNIX address, we want permission to open the
1178  * directory that holds it. */
1179  char *dirname = tor_strdup(port->unix_addr);
1180  if (get_parent_directory(dirname) == 0) {
1181  OPEN(dirname);
1182  }
1183  tor_free(dirname);
1184  sandbox_cfg_allow_chmod_filename(&cfg, tor_strdup(port->unix_addr));
1185  sandbox_cfg_allow_chown_filename(&cfg, tor_strdup(port->unix_addr));
1186  } SMARTLIST_FOREACH_END(port);
1187 
1188  if (options->DirPortFrontPage) {
1190  tor_strdup(options->DirPortFrontPage));
1191  }
1192 
1193  // orport
1194  if (server_mode(get_options())) {
1195 
1196  OPEN_KEYDIR_SUFFIX("secret_id_key", ".tmp");
1197  OPEN_KEYDIR_SUFFIX("secret_onion_key", ".tmp");
1198  OPEN_KEYDIR_SUFFIX("secret_onion_key_ntor", ".tmp");
1199  OPEN_KEYDIR("secret_id_key.old");
1200  OPEN_KEYDIR("secret_onion_key.old");
1201  OPEN_KEYDIR("secret_onion_key_ntor.old");
1202 
1203  OPEN_KEYDIR_SUFFIX("ed25519_master_id_secret_key", ".tmp");
1204  OPEN_KEYDIR_SUFFIX("ed25519_master_id_secret_key_encrypted", ".tmp");
1205  OPEN_KEYDIR_SUFFIX("ed25519_master_id_public_key", ".tmp");
1206  OPEN_KEYDIR_SUFFIX("ed25519_signing_secret_key", ".tmp");
1207  OPEN_KEYDIR_SUFFIX("ed25519_signing_secret_key_encrypted", ".tmp");
1208  OPEN_KEYDIR_SUFFIX("ed25519_signing_public_key", ".tmp");
1209  OPEN_KEYDIR_SUFFIX("ed25519_signing_cert", ".tmp");
1210 
1211  OPEN_DATADIR2_SUFFIX("stats", "bridge-stats", ".tmp");
1212  OPEN_DATADIR2_SUFFIX("stats", "dirreq-stats", ".tmp");
1213 
1214  OPEN_DATADIR2_SUFFIX("stats", "entry-stats", ".tmp");
1215  OPEN_DATADIR2_SUFFIX("stats", "exit-stats", ".tmp");
1216  OPEN_DATADIR2_SUFFIX("stats", "buffer-stats", ".tmp");
1217  OPEN_DATADIR2_SUFFIX("stats", "conn-stats", ".tmp");
1218  OPEN_DATADIR2_SUFFIX("stats", "hidserv-stats", ".tmp");
1219 
1220  OPEN_DATADIR("approved-routers");
1221  OPEN_DATADIR_SUFFIX("fingerprint", ".tmp");
1222  OPEN_DATADIR_SUFFIX("hashed-fingerprint", ".tmp");
1223  OPEN_DATADIR_SUFFIX("router-stability", ".tmp");
1224 
1225  OPEN("/etc/resolv.conf");
1226 
1227  RENAME_SUFFIX("fingerprint", ".tmp");
1228  RENAME_KEYDIR_SUFFIX("secret_onion_key_ntor", ".tmp");
1229 
1230  RENAME_KEYDIR_SUFFIX("secret_id_key", ".tmp");
1231  RENAME_KEYDIR_SUFFIX("secret_id_key.old", ".tmp");
1232  RENAME_KEYDIR_SUFFIX("secret_onion_key", ".tmp");
1233  RENAME_KEYDIR_SUFFIX("secret_onion_key.old", ".tmp");
1234 
1235  RENAME_SUFFIX2("stats", "bridge-stats", ".tmp");
1236  RENAME_SUFFIX2("stats", "dirreq-stats", ".tmp");
1237  RENAME_SUFFIX2("stats", "entry-stats", ".tmp");
1238  RENAME_SUFFIX2("stats", "exit-stats", ".tmp");
1239  RENAME_SUFFIX2("stats", "buffer-stats", ".tmp");
1240  RENAME_SUFFIX2("stats", "conn-stats", ".tmp");
1241  RENAME_SUFFIX2("stats", "hidserv-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 
1263  consdiffmgr_register_with_sandbox(&cfg);
1264  }
1265 
1266  init_addrinfo();
1267 
1268  return cfg;
1269 }
1270 
1271 int
1272 run_tor_main_loop(void)
1273 {
1274  handle_signals();
1277 
1278  /* load the private keys, if we're supposed to have them, and set up the
1279  * TLS context. */
1280  if (! client_identity_key_is_set()) {
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 
1321  if (trusted_dirs_reload_certs()) {
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. */
1329  if (router_reload_router_list()) {
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  if (server_mode(get_options()) || dir_server_mode(get_options())) {
1339  /* launch cpuworkers. Need to do this *after* we've read the onion key. */
1340  cpu_init();
1341  }
1342  consdiffmgr_enable_background_compression();
1343 
1344  /* Setup shared random protocol subsystem. */
1345  if (authdir_mode_v3(get_options())) {
1346  if (sr_init(1) < 0) {
1347  return -1;
1348  }
1349  }
1350 
1351  /* initialize dns resolve map, spawn workers if needed */
1352  if (dns_init() < 0) {
1353  if (get_options()->ServerDNSAllowBrokenConfig)
1354  log_warn(LD_GENERAL, "Couldn't set up any working nameservers. "
1355  "Network not up yet? Will try again soon.");
1356  else {
1357  log_err(LD_GENERAL,"Error initializing dns subsystem; exiting. To "
1358  "retry instead, set the ServerDNSAllowBrokenResolvConf option.");
1359  }
1360  }
1361 
1362 #ifdef HAVE_SYSTEMD
1363  {
1364  const int r = sd_notify(0, "READY=1");
1365  if (r < 0) {
1366  log_warn(LD_GENERAL, "Unable to send readiness to systemd: %s",
1367  strerror(r));
1368  } else if (r > 0) {
1369  log_notice(LD_GENERAL, "Signaled readiness to systemd");
1370  } else {
1371  log_info(LD_GENERAL, "Systemd NOTIFY_SOCKET not present.");
1372  }
1373  }
1374 #endif /* defined(HAVE_SYSTEMD) */
1375 
1376  return do_main_loop();
1377 }
1378 
1379 /* Main entry point for the Tor process. Called from tor_main(), and by
1380  * anybody embedding Tor. */
1381 int
1383 {
1384  int result = 0;
1385 
1386 #ifdef EVENT_SET_MEM_FUNCTIONS_IMPLEMENTED
1387  event_set_mem_functions(tor_malloc_, tor_realloc_, tor_free_);
1388 #endif
1389 
1390  subsystems_init();
1391 
1393 
1394  int argc = tor_cfg->argc + tor_cfg->argc_owned;
1395  char **argv = tor_calloc(argc, sizeof(char*));
1396  memcpy(argv, tor_cfg->argv, tor_cfg->argc*sizeof(char*));
1397  if (tor_cfg->argc_owned)
1398  memcpy(argv + tor_cfg->argc, tor_cfg->argv_owned,
1399  tor_cfg->argc_owned*sizeof(char*));
1400 
1401 #ifdef NT_SERVICE
1402  {
1403  int done = 0;
1404  result = nt_service_parse_options(argc, argv, &done);
1405  if (done) {
1406  goto done;
1407  }
1408  }
1409 #endif /* defined(NT_SERVICE) */
1410  {
1411  int init_rv = tor_init(argc, argv);
1412  if (init_rv) {
1413  tor_free_all(0);
1414  result = (init_rv < 0) ? -1 : 0;
1415  goto done;
1416  }
1417  }
1418 
1419  if (get_options()->Sandbox && get_options()->command == CMD_RUN_TOR) {
1420  sandbox_cfg_t* cfg = sandbox_init_filter();
1421 
1422  if (sandbox_init(cfg)) {
1423  tor_free(argv);
1424  log_err(LD_BUG,"Failed to create syscall sandbox filter");
1425  tor_free_all(0);
1426  return -1;
1427  }
1428  tor_make_getaddrinfo_cache_active();
1429 
1430  // registering libevent rng
1431 #ifdef HAVE_EVUTIL_SECURE_RNG_SET_URANDOM_DEVICE_FILE
1432  evutil_secure_rng_set_urandom_device_file(
1433  (char*) sandbox_intern_string("/dev/urandom"));
1434 #endif
1435  }
1436 
1437  switch (get_options()->command) {
1438  case CMD_RUN_TOR:
1439 #ifdef NT_SERVICE
1440  nt_service_set_state(SERVICE_RUNNING);
1441 #endif
1442  result = run_tor_main_loop();
1443  break;
1444  case CMD_KEYGEN:
1445  result = load_ed_keys(get_options(), time(NULL)) < 0;
1446  break;
1447  case CMD_KEY_EXPIRATION:
1448  init_keys();
1449  result = log_cert_expiration();
1450  break;
1451  case CMD_LIST_FINGERPRINT:
1452  result = do_list_fingerprint();
1453  break;
1454  case CMD_HASH_PASSWORD:
1455  do_hash_password();
1456  result = 0;
1457  break;
1458  case CMD_VERIFY_CONFIG:
1459  if (quiet_level == 0)
1460  printf("Configuration was valid\n");
1461  result = 0;
1462  break;
1463  case CMD_DUMP_CONFIG:
1464  result = do_dump_config();
1465  break;
1466  case CMD_RUN_UNITTESTS: /* only set by test.c */
1467  default:
1468  log_warn(LD_BUG,"Illegal command number %d: internal error.",
1469  get_options()->command);
1470  result = -1;
1471  }
1472  tor_cleanup();
1473  done:
1474  tor_free(argv);
1475  return result;
1476 }
void timers_initialize(void)
Definition: timers.c:203
#define RELAY_PAYLOAD_SIZE
Definition: or.h:605
void rep_hist_free_all(void)
Definition: rephist.c:2899
uint64_t stats_n_data_cells_received
Definition: relay.c:1971
Header file for dirserv.c.
void dirserv_free_fingerprint_list(void)
char * AccelName
void router_reset_descriptor_download_failures(void)
Definition: routerlist.c:2824
Header for statefile.c.
time_t time_of_process_start
Definition: mainloop.c:145
char * PidFile
Definition: or_options_st.h:70
uint64_t rephist_total_alloc
Definition: rephist.c:104
crypto_pk_t * get_server_identity_key(void)
Definition: router.c:378
void protover_free_all(void)
Definition: protover.c:937
int authdir_mode_tests_reachability(const or_options_t *options)
Definition: authmode.c:59
Header file for channeltls.c.
Header for uname.c.
Header for confline.c.
struct sandbox_cfg_elem sandbox_cfg_t
Definition: sandbox.h:35
void tor_cleanup(void)
Definition: main.c:840
Header file for circuitbuild.c.
tor_lockfile_t * tor_lockfile_lock(const char *filename, int blocking, int *locked_out)
Definition: lockfile.c:63
Common functions for using (pseudo-)random number generators.
void init_protocol_warning_severity_level(void)
Definition: config.c:1148
int have_lockfile(void)
Definition: main.c:730
void notify_pending_waitpid_callbacks(void)
Definition: waitpid.c:141
#define SMARTLIST_FOREACH_BEGIN(sl, type, var)
uint64_t stats_n_relay_cells_relayed
Definition: relay.c:126
Header file for command.c.
Headers for waitpid.c.
void update_current_time(time_t now)
Definition: mainloop.c:2677
void routerparse_free_all(void)
Definition: routerparse.c:1239
Header file for geoip_stats.c.
int options_init_from_torrc(int argc, char **argv)
Definition: config.c:5139
int dir_server_mode(const or_options_t *options)
Definition: routermode.c:20
static void signal_callback(evutil_socket_t fd, short events, void *arg)
Definition: main.c:229
void dump_routerlist_mem_usage(int severity)
Definition: routerlist.c:976
Header file for connection.c.
int control_event_signal(uintptr_t signal_num)
Definition: control.c:6692
char * DataDirectory
Definition: or_options_st.h:55
char * DirPortFrontPage
#define LD_GENERAL
Definition: log.h:59
char * get_controller_cookie_file_name(void)
Definition: control.c:6941
void circuitmux_ewma_free_all(void)
int authdir_mode(const or_options_t *options)
Definition: authmode.c:25
Headers for compress.c.
#define LOG_INFO
Definition: log.h:42
void channel_dumpstats(int severity)
Definition: channel.c:2057
int tor_compress_supports_method(compress_method_t method)
Definition: compress.c:304
Header file for nodelist.c.
void clear_pending_onions(void)
Definition: onion_queue.c:349
void tor_log(int severity, log_domain_mask_t domain, const char *format,...)
Definition: log.c:631
int dns_init(void)
Definition: dns.c:224
Header file for ntmain.c.
int connection_is_listener(connection_t *conn)
Definition: connection.c:4607
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:642
int try_to_register
Definition: main.c:458
int ReloadTorrcOnSIGHUP
int get_min_log_level(void)
Definition: log.c:1446
const struct passwd * tor_getpwnam(const char *username)
Definition: userdb.c:70
void tor_log_get_logfile_names(smartlist_t *out)
Definition: log.c:711
Header file for config.c.
Header file for authcert.c.
#define CONN_TYPE_OR
Definition: connection.h:24
const char * conn_type_to_string(int type)
Definition: connection.c:241
Header file for microdesc.c.
int sandbox_init(sandbox_cfg_t *cfg)
Definition: sandbox.c:1736
Header file for cpuworker.c.
static int do_list_fingerprint(void)
Definition: main.c:884
#define tor_free(p)
Definition: malloc.h:52
int do_main_loop(void)
Definition: mainloop.c:2825
void tor_shutdown_event_loop_and_exit(int exitcode)
Definition: mainloop.c:767
void initialize_mainloop_events(void)
Definition: mainloop.c:2809
void circpad_new_consensus_params(const networkstatus_t *ns)
struct event * signal_event
Definition: main.c:460
uint32_t rephist_total_num
Definition: rephist.c:106
#define LOG_NOTICE
Definition: log.h:47
const char * conn_state_to_string(int type, int state)
Definition: connection.c:273
Header file for mainloop.c.
void add_temp_log(int min_severity)
Definition: log.c:935
void bridges_free_all(void)
Definition: bridges.c:1025
static int do_dump_config(void)
Definition: main.c:933
char * options_dump(const or_options_t *options, int how_to_dump)
Definition: config.c:2983
void dirserv_clear_measured_bw_cache(void)
Definition: bwauth.c:101
int sandbox_cfg_allow_open_filename(sandbox_cfg_t **cfg, char *file)
Definition: sandbox.c:1760
Header for meminfo.c.
static void do_hash_password(void)
Definition: main.c:915
Header file for geoip.c.
Header file for versions.c.
Header file for scheduler*.c.
#define sandbox_intern_string(s)
Definition: sandbox.h:112
struct tor_tls_t * tls
static tor_lockfile_t * lockfile
Definition: main.c:686
Header file for main.c.
int keypin_load_journal(const char *fname)
Definition: keypin.c:452
void connection_dump_buffer_mem_stats(int severity)
Definition: connection.c:5186
or_connection_t * TO_OR_CONN(connection_t *c)
void rend_service_authorization_free_all(void)
Definition: rendclient.c:1145
char * ServerDNSResolvConfFile
void accounting_free_all(void)
Definition: hibernate.c:1254
void tor_lockfile_unlock(tor_lockfile_t *lockfile)
Definition: lockfile.c:121
Header file for directory authority mode.
void circpad_machines_init(void)
int try_locking(const or_options_t *options, int err_if_locked)
Definition: main.c:694
Header file for hibernate.c.
Header file for policies.c.
uint64_t stats_n_data_bytes_received
Definition: relay.c:1975
void handle_signals(void)
Definition: main.c:498
int dirserv_load_fingerprint_file(void)
void router_reset_warnings(void)
Definition: router.c:3150
uint64_t stats_n_relay_cells_processed
Definition: command.c:71
int client_identity_key_is_set(void)
Definition: router.c:416
void rend_cache_free_all(void)
Definition: rendcache.c:231
Header file for channel.c.
const char * crypto_get_library_version_string(void)
Definition: crypto_init.c:182
void directory_info_has_arrived(time_t now, int from_cache, int suppress_logs)
Definition: mainloop.c:1109
uint64_t stats_n_created_cells_processed
Definition: command.c:69
tor_assert(buffer)
int init_keys(void)
Definition: router.c:923
void routerlist_reset_warnings(void)
Definition: routerlist.c:1443
int quiet_level
Definition: main.c:134
void log_set_application_name(const char *name)
Definition: log.c:246
int config_parse_commandline(int argc, char **argv, int ignore_errors, config_line_t **result, config_line_t **cmdline_result)
Definition: config.c:2462
void control_free_all(void)
Definition: control.c:7550
int trusted_dirs_reload_certs(void)
Definition: authcert.c:324
void addressmap_init(void)
Definition: addressmap.c:91
void tor_compress_log_init_warnings(void)
Definition: compress.c:682
enum or_options_t::@28 command
Header file for routermode.c.
int keypin_close_journal(void)
Definition: keypin.c:339
int tor_asprintf(char **strp, const char *fmt,...)
Definition: printf.c:75
uint64_t stats_n_data_bytes_packaged
Definition: relay.c:1969
void dns_free_all(void)
Definition: dns.c:400
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:203
void cpu_init(void)
Definition: cpuworker.c:83
Header file for circuitpadding.c.
void protover_summary_cache_free_all(void)
Definition: versions.c:493
void scheduler_free_all(void)
Definition: scheduler.c:485
#define DIGEST_LEN
Definition: digest_sizes.h:20
int load_ed_keys(const or_options_t *options, time_t now)
Definition: routerkeys.c:55
Header file for sandbox.c.
Header file for rendcache.c.
int log_heartbeat(time_t now)
Definition: status.c:119
Header file for circuitbuild.c.
Public C API for the Tor network service.
Master header file for Tor-specific functionality.
int dns_reset(void)
Definition: dns.c:238
void rep_hist_dump_stats(time_t now, int severity)
Definition: rephist.c:554
void dirserv_free_all(void)
Definition: dirserv.c:911
uint64_t stats_n_padding_cells_processed
Definition: channeltls.c:78
Header file for onion_queue.c.
uint64_t stats_n_relay_cells_delivered
Definition: relay.c:130
Header file for bwauth.c.
int keypin_open_journal(const char *fname)
Definition: keypin.c:305
void release_lockfile(void)
Definition: main.c:737
struct smartlist_t * FilesOpenedByIncludes
Header for crypto_s2k.c.
static void dumpmemusage(int severity)
Definition: main.c:328
void router_free_all(void)
Definition: router.c:3160
char * ControlPortWriteToFile
void routerparse_init(void)
Definition: routerparse.c:1225
Header file for rephist.c.
void circpad_machines_free(void)
void addressmap_free_all(void)
Definition: addressmap.c:329
void config_free_all(void)
Definition: config.c:1022
void entry_guards_free_all(void)
Definition: entrynodes.c:3804
#define LOG_WARN
Definition: log.h:50
const char * tor_libevent_get_version_str(void)
void base16_encode(char *dest, size_t destlen, const char *src, size_t srclen)
Definition: binascii.c:476
void dirvote_free_all(void)
Definition: dirvote.c:3706
int router_reload_consensus_networkstatus(void)
Header file for circuitmux_ewma.c.
void timers_shutdown(void)
Definition: timers.c:232
void tor_free_(void *mem)
Definition: malloc.c:227
void rep_hist_init(void)
Definition: rephist.c:232
void do_signewnym(time_t now)
Definition: mainloop.c:1310
Header file for circuitlist.c.
int tor_run_main(const tor_main_configuration_t *tor_cfg)
Definition: main.c:1382
int BridgeAuthoritativeDir
Header file for rendservice.c.
Header file for process_descs.c.
Headers for transports.c.
void cpuworkers_rotate_keyinfo(void)
Definition: cpuworker.c:188
void truncate_logs(void)
Definition: log.c:1476
#define LD_OR
Definition: log.h:89
void hibernate_begin_shutdown(void)
Definition: hibernate.c:927
void tor_libevent_free_all(void)
void ext_orport_free_all(void)
Definition: ext_orport.c:657
static void process_signal(int sig)
Definition: main.c:242
void circuit_dump_by_conn(connection_t *conn, int severity)
Definition: circuitlist.c:1382
Headers and type declarations for protover.c.
static void dumpstats(int severity)
Definition: main.c:342
#define LD_FS
Definition: log.h:67
const char * esc_router_info(const routerinfo_t *router)
Definition: routerlist.c:3175
#define LD_DIR
Definition: log.h:85
int generate_ed_link_cert(const or_options_t *options, time_t now, int force)
Definition: routerkeys.c:365
void router_reset_status_download_failures(void)
Definition: dirlist.c:103
void channel_free_all(void)
Definition: channel.c:2232
void policies_free_all(void)
Definition: policies.c:3128
int sandbox_cfg_allow_stat_filename(sandbox_cfg_t **cfg, char *file)
Definition: sandbox.c:1774
Header file for connection_edge.c.
uint64_t stats_n_data_cells_packaged
Definition: relay.c:1965
int crypto_pk_get_fingerprint(crypto_pk_t *pk, char *fp_out, int add_space)
Definition: crypto_rsa.c:229
int tor_snprintf(char *str, size_t size, const char *format,...)
Definition: printf.c:27
int tor_init(int argc, char *argv[])
Definition: main.c:545
size_t buf_allocation(const buf_t *buf)
Definition: buffers.c:399
void channel_listener_dumpstats(int severity)
Definition: channel.c:2088
#define S2K_RFC2440_SPECIFIER_LEN
Definition: crypto_s2k.h:21
void circuit_mark_all_dirty_circs_as_unusable(void)
Definition: circuitlist.c:2110
Header for timers.c.
Header file for dirvote.c.
Header file for relay.c.
#define SMARTLIST_FOREACH(sl, type, var, cmd)
void microdesc_free_all(void)
Definition: microdesc.c:898
void nodelist_free_all(void)
Definition: nodelist.c:827
char * command_arg
Definition: or_options_st.h:39
#define FINGERPRINT_LEN
Definition: crypto_rsa.h:34
uint64_t stats_n_create_cells_processed
Definition: command.c:67
void * tor_malloc_(size_t size)
Definition: malloc.c:32
void control_event_bootstrap(bootstrap_status_t status, int progress)
void tor_free_all(int postfork)
Definition: main.c:754
uint64_t stats_n_destroy_cells_processed
Definition: command.c:73
void update_networkstatus_downloads(time_t now)
void switch_logs_debug(void)
Definition: log.c:1461
int set_options(or_options_t *new_val, char **msg)
Definition: config.c:919
void cpuworker_log_onionskin_overhead(int severity, int onionskin_type, const char *onionskin_type_name)
Definition: cpuworker.c:292
void dump_dns_mem_usage(int severity)
Definition: dns.c:2152
Headers for tortls.c.
Header file for control.c.
void circuit_free_all(void)
Definition: circuitlist.c:1279
void channel_tls_free_all(void)
Definition: channeltls.c:295
Header for resolve.c.
void rend_cache_init(void)
Definition: rendcache.c:66
time_t approx_time(void)
Definition: approx_time.c:32
void routerlist_free_all(void)
Definition: routerlist.c:1427
void or_state_mark_dirty(or_state_t *state, time_t when)
Definition: statefile.c:715
int rep_hist_record_mtbf_data(time_t now, int missing_means_down)
Definition: rephist.c:626
int or_state_save(time_t now)
Definition: statefile.c:493
void geoip_stats_free_all(void)
Definition: geoip_stats.c:1402
Header file for hs_cache.c.
int router_reload_router_list(void)
Definition: routerlist.c:457
void tor_log_mallinfo(int severity)
Definition: meminfo.c:43
void networkstatus_free_all(void)
char * get_ext_or_auth_cookie_file_name(void)
Definition: ext_orport.c:127
void * tor_realloc_(void *ptr, size_t size)
Definition: malloc.c:118
Header file for buffers.c.
void connection_bucket_init(void)
Definition: connection.c:3404
int accounting_record_bandwidth_usage(time_t now, or_state_t *state)
Definition: hibernate.c:705
Header file for connection_or.c.
void pt_free_all(void)
Definition: transports.c:1754
void rend_service_dump_stats(int severity)
Definition: rendservice.c:4357
#define LD_NET
Definition: log.h:63
int signal_value
Definition: main.c:455
const char * get_torrc_fname(int defaults_fname)
Definition: config.c:5531
void connection_free_all(void)
Definition: connection.c:5477
void addressmap_clear_transient(void)
Definition: addressmap.c:312
int log_cert_expiration(void)
Definition: routerkeys.c:593
Header for compat_libevent.c.
Header file for rendclient.c.
void tor_init_connection_lists(void)
Definition: mainloop.c:415
const char * tor_compress_version_str(compress_method_t method)
Definition: compress.c:417
void tor_remove_file(const char *filename)
Definition: main.c:830
int get_parent_directory(char *fname)
Definition: path.c:176
Header file for networkstatus.c.
int crypto_global_init(int useAccel, const char *accelName, const char *accelDir)
Definition: crypto_init.c:85
#define LD_BUG
Definition: log.h:83
Header file for dns.c.
Headers for crypto_init.c.
#define LD_CONFIG
Definition: log.h:65
Header file for routerlist.c.
void dump_cell_pool_usage(int severity)
Definition: relay.c:2430
Header file for routerparse.c.
void connection_edge_free_all(void)
void geoip_free_all(void)
Definition: geoip.c:504
static int do_hup(void)
Definition: main.c:141
int sandbox_cfg_allow_openat_filename(sandbox_cfg_t **cfg, char *file)
Definition: sandbox.c:1767
sandbox_cfg_t * sandbox_cfg_new(void)
Definition: sandbox.c:1730
const char * crypto_get_library_name(void)
Definition: crypto_init.c:169
Header for lockfile.c.