main.c 43 KB

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