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