main.c 43 KB

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