main.c 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366
  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. if (tor_init_libevent_rng() < 0) {
  594. log_warn(LD_NET, "Problem initializing libevent RNG.");
  595. }
  596. /* Scan/clean unparseable descriptors; after reading config */
  597. routerparse_init();
  598. return 0;
  599. }
  600. /** A lockfile structure, used to prevent two Tors from messing with the
  601. * data directory at once. If this variable is non-NULL, we're holding
  602. * the lockfile. */
  603. static tor_lockfile_t *lockfile = NULL;
  604. /** Try to grab the lock file described in <b>options</b>, if we do not
  605. * already have it. If <b>err_if_locked</b> is true, warn if somebody else is
  606. * holding the lock, and exit if we can't get it after waiting. Otherwise,
  607. * return -1 if we can't get the lockfile. Return 0 on success.
  608. */
  609. int
  610. try_locking(const or_options_t *options, int err_if_locked)
  611. {
  612. if (lockfile)
  613. return 0;
  614. else {
  615. char *fname = options_get_datadir_fname(options, "lock");
  616. int already_locked = 0;
  617. tor_lockfile_t *lf = tor_lockfile_lock(fname, 0, &already_locked);
  618. tor_free(fname);
  619. if (!lf) {
  620. if (err_if_locked && already_locked) {
  621. int r;
  622. log_warn(LD_GENERAL, "It looks like another Tor process is running "
  623. "with the same data directory. Waiting 5 seconds to see "
  624. "if it goes away.");
  625. #ifndef _WIN32
  626. sleep(5);
  627. #else
  628. Sleep(5000);
  629. #endif
  630. r = try_locking(options, 0);
  631. if (r<0) {
  632. log_err(LD_GENERAL, "No, it's still there. Exiting.");
  633. return -1;
  634. }
  635. return r;
  636. }
  637. return -1;
  638. }
  639. lockfile = lf;
  640. return 0;
  641. }
  642. }
  643. /** Return true iff we've successfully acquired the lock file. */
  644. int
  645. have_lockfile(void)
  646. {
  647. return lockfile != NULL;
  648. }
  649. /** If we have successfully acquired the lock file, release it. */
  650. void
  651. release_lockfile(void)
  652. {
  653. if (lockfile) {
  654. tor_lockfile_unlock(lockfile);
  655. lockfile = NULL;
  656. }
  657. }
  658. /**
  659. * Remove the specified file, and log a warning if the operation fails for
  660. * any reason other than the file not existing. Ignores NULL filenames.
  661. */
  662. void
  663. tor_remove_file(const char *filename)
  664. {
  665. if (filename && tor_unlink(filename) != 0 && errno != ENOENT) {
  666. log_warn(LD_FS, "Couldn't unlink %s: %s",
  667. filename, strerror(errno));
  668. }
  669. }
  670. /** Read/create keys as needed, and echo our fingerprint to stdout. */
  671. static int
  672. do_list_fingerprint(void)
  673. {
  674. char buf[FINGERPRINT_LEN+1];
  675. crypto_pk_t *k;
  676. const char *nickname = get_options()->Nickname;
  677. sandbox_disable_getaddrinfo_cache();
  678. if (!server_mode(get_options())) {
  679. log_err(LD_GENERAL,
  680. "Clients don't have long-term identity keys. Exiting.");
  681. return -1;
  682. }
  683. tor_assert(nickname);
  684. if (init_keys() < 0) {
  685. log_err(LD_GENERAL,"Error initializing keys; exiting.");
  686. return -1;
  687. }
  688. if (!(k = get_server_identity_key())) {
  689. log_err(LD_GENERAL,"Error: missing identity key.");
  690. return -1;
  691. }
  692. if (crypto_pk_get_fingerprint(k, buf, 1)<0) {
  693. log_err(LD_BUG, "Error computing fingerprint");
  694. return -1;
  695. }
  696. printf("%s %s\n", nickname, buf);
  697. return 0;
  698. }
  699. /** Entry point for password hashing: take the desired password from
  700. * the command line, and print its salted hash to stdout. **/
  701. static void
  702. do_hash_password(void)
  703. {
  704. char output[256];
  705. char key[S2K_RFC2440_SPECIFIER_LEN+DIGEST_LEN];
  706. crypto_rand(key, S2K_RFC2440_SPECIFIER_LEN-1);
  707. key[S2K_RFC2440_SPECIFIER_LEN-1] = (uint8_t)96; /* Hash 64 K of data. */
  708. secret_to_key_rfc2440(key+S2K_RFC2440_SPECIFIER_LEN, DIGEST_LEN,
  709. get_options()->command_arg, strlen(get_options()->command_arg),
  710. key);
  711. base16_encode(output, sizeof(output), key, sizeof(key));
  712. printf("16:%s\n",output);
  713. }
  714. /** Entry point for configuration dumping: write the configuration to
  715. * stdout. */
  716. static int
  717. do_dump_config(void)
  718. {
  719. const or_options_t *options = get_options();
  720. const char *arg = options->command_arg;
  721. int how;
  722. char *opts;
  723. if (!strcmp(arg, "short")) {
  724. how = OPTIONS_DUMP_MINIMAL;
  725. } else if (!strcmp(arg, "non-builtin")) {
  726. how = OPTIONS_DUMP_DEFAULTS;
  727. } else if (!strcmp(arg, "full")) {
  728. how = OPTIONS_DUMP_ALL;
  729. } else {
  730. fprintf(stderr, "No valid argument to --dump-config found!\n");
  731. fprintf(stderr, "Please select 'short', 'non-builtin', or 'full'.\n");
  732. return -1;
  733. }
  734. opts = options_dump(options, how);
  735. printf("%s", opts);
  736. tor_free(opts);
  737. return 0;
  738. }
  739. static void
  740. init_addrinfo(void)
  741. {
  742. if (! server_mode(get_options()) ||
  743. (get_options()->Address && strlen(get_options()->Address) > 0)) {
  744. /* We don't need to seed our own hostname, because we won't be calling
  745. * resolve_my_address on it.
  746. */
  747. return;
  748. }
  749. char hname[256];
  750. // host name to sandbox
  751. gethostname(hname, sizeof(hname));
  752. tor_add_addrinfo(hname);
  753. }
  754. static sandbox_cfg_t*
  755. sandbox_init_filter(void)
  756. {
  757. const or_options_t *options = get_options();
  758. sandbox_cfg_t *cfg = sandbox_cfg_new();
  759. int i;
  760. sandbox_cfg_allow_openat_filename(&cfg,
  761. get_cachedir_fname("cached-status"));
  762. #define OPEN(name) \
  763. sandbox_cfg_allow_open_filename(&cfg, tor_strdup(name))
  764. #define OPEN_DATADIR(name) \
  765. sandbox_cfg_allow_open_filename(&cfg, get_datadir_fname(name))
  766. #define OPEN_DATADIR2(name, name2) \
  767. sandbox_cfg_allow_open_filename(&cfg, get_datadir_fname2((name), (name2)))
  768. #define OPEN_DATADIR_SUFFIX(name, suffix) do { \
  769. OPEN_DATADIR(name); \
  770. OPEN_DATADIR(name suffix); \
  771. } while (0)
  772. #define OPEN_DATADIR2_SUFFIX(name, name2, suffix) do { \
  773. OPEN_DATADIR2(name, name2); \
  774. OPEN_DATADIR2(name, name2 suffix); \
  775. } while (0)
  776. #define OPEN_KEY_DIRECTORY() \
  777. sandbox_cfg_allow_open_filename(&cfg, tor_strdup(options->KeyDirectory))
  778. #define OPEN_CACHEDIR(name) \
  779. sandbox_cfg_allow_open_filename(&cfg, get_cachedir_fname(name))
  780. #define OPEN_CACHEDIR_SUFFIX(name, suffix) do { \
  781. OPEN_CACHEDIR(name); \
  782. OPEN_CACHEDIR(name suffix); \
  783. } while (0)
  784. #define OPEN_KEYDIR(name) \
  785. sandbox_cfg_allow_open_filename(&cfg, get_keydir_fname(name))
  786. #define OPEN_KEYDIR_SUFFIX(name, suffix) do { \
  787. OPEN_KEYDIR(name); \
  788. OPEN_KEYDIR(name suffix); \
  789. } while (0)
  790. OPEN(options->DataDirectory);
  791. OPEN_KEY_DIRECTORY();
  792. OPEN_CACHEDIR_SUFFIX("cached-certs", ".tmp");
  793. OPEN_CACHEDIR_SUFFIX("cached-consensus", ".tmp");
  794. OPEN_CACHEDIR_SUFFIX("unverified-consensus", ".tmp");
  795. OPEN_CACHEDIR_SUFFIX("unverified-microdesc-consensus", ".tmp");
  796. OPEN_CACHEDIR_SUFFIX("cached-microdesc-consensus", ".tmp");
  797. OPEN_CACHEDIR_SUFFIX("cached-microdescs", ".tmp");
  798. OPEN_CACHEDIR_SUFFIX("cached-microdescs.new", ".tmp");
  799. OPEN_CACHEDIR_SUFFIX("cached-descriptors", ".tmp");
  800. OPEN_CACHEDIR_SUFFIX("cached-descriptors.new", ".tmp");
  801. OPEN_CACHEDIR("cached-descriptors.tmp.tmp");
  802. OPEN_CACHEDIR_SUFFIX("cached-extrainfo", ".tmp");
  803. OPEN_CACHEDIR_SUFFIX("cached-extrainfo.new", ".tmp");
  804. OPEN_CACHEDIR("cached-extrainfo.tmp.tmp");
  805. OPEN_DATADIR_SUFFIX("state", ".tmp");
  806. OPEN_DATADIR_SUFFIX("sr-state", ".tmp");
  807. OPEN_DATADIR_SUFFIX("unparseable-desc", ".tmp");
  808. OPEN_DATADIR_SUFFIX("v3-status-votes", ".tmp");
  809. OPEN_DATADIR("key-pinning-journal");
  810. OPEN("/dev/srandom");
  811. OPEN("/dev/urandom");
  812. OPEN("/dev/random");
  813. OPEN("/etc/hosts");
  814. OPEN("/proc/meminfo");
  815. if (options->BridgeAuthoritativeDir)
  816. OPEN_DATADIR_SUFFIX("networkstatus-bridges", ".tmp");
  817. if (authdir_mode(options))
  818. OPEN_DATADIR("approved-routers");
  819. if (options->ServerDNSResolvConfFile)
  820. sandbox_cfg_allow_open_filename(&cfg,
  821. tor_strdup(options->ServerDNSResolvConfFile));
  822. else
  823. sandbox_cfg_allow_open_filename(&cfg, tor_strdup("/etc/resolv.conf"));
  824. for (i = 0; i < 2; ++i) {
  825. if (get_torrc_fname(i)) {
  826. sandbox_cfg_allow_open_filename(&cfg, tor_strdup(get_torrc_fname(i)));
  827. }
  828. }
  829. SMARTLIST_FOREACH(options->FilesOpenedByIncludes, char *, f, {
  830. OPEN(f);
  831. });
  832. #define RENAME_SUFFIX(name, suffix) \
  833. sandbox_cfg_allow_rename(&cfg, \
  834. get_datadir_fname(name suffix), \
  835. get_datadir_fname(name))
  836. #define RENAME_SUFFIX2(prefix, name, suffix) \
  837. sandbox_cfg_allow_rename(&cfg, \
  838. get_datadir_fname2(prefix, name suffix), \
  839. get_datadir_fname2(prefix, name))
  840. #define RENAME_CACHEDIR_SUFFIX(name, suffix) \
  841. sandbox_cfg_allow_rename(&cfg, \
  842. get_cachedir_fname(name suffix), \
  843. get_cachedir_fname(name))
  844. #define RENAME_KEYDIR_SUFFIX(name, suffix) \
  845. sandbox_cfg_allow_rename(&cfg, \
  846. get_keydir_fname(name suffix), \
  847. get_keydir_fname(name))
  848. RENAME_CACHEDIR_SUFFIX("cached-certs", ".tmp");
  849. RENAME_CACHEDIR_SUFFIX("cached-consensus", ".tmp");
  850. RENAME_CACHEDIR_SUFFIX("unverified-consensus", ".tmp");
  851. RENAME_CACHEDIR_SUFFIX("unverified-microdesc-consensus", ".tmp");
  852. RENAME_CACHEDIR_SUFFIX("cached-microdesc-consensus", ".tmp");
  853. RENAME_CACHEDIR_SUFFIX("cached-microdescs", ".tmp");
  854. RENAME_CACHEDIR_SUFFIX("cached-microdescs", ".new");
  855. RENAME_CACHEDIR_SUFFIX("cached-microdescs.new", ".tmp");
  856. RENAME_CACHEDIR_SUFFIX("cached-descriptors", ".tmp");
  857. RENAME_CACHEDIR_SUFFIX("cached-descriptors", ".new");
  858. RENAME_CACHEDIR_SUFFIX("cached-descriptors.new", ".tmp");
  859. RENAME_CACHEDIR_SUFFIX("cached-extrainfo", ".tmp");
  860. RENAME_CACHEDIR_SUFFIX("cached-extrainfo", ".new");
  861. RENAME_CACHEDIR_SUFFIX("cached-extrainfo.new", ".tmp");
  862. RENAME_SUFFIX("state", ".tmp");
  863. RENAME_SUFFIX("sr-state", ".tmp");
  864. RENAME_SUFFIX("unparseable-desc", ".tmp");
  865. RENAME_SUFFIX("v3-status-votes", ".tmp");
  866. if (options->BridgeAuthoritativeDir)
  867. RENAME_SUFFIX("networkstatus-bridges", ".tmp");
  868. #define STAT_DATADIR(name) \
  869. sandbox_cfg_allow_stat_filename(&cfg, get_datadir_fname(name))
  870. #define STAT_CACHEDIR(name) \
  871. sandbox_cfg_allow_stat_filename(&cfg, get_cachedir_fname(name))
  872. #define STAT_DATADIR2(name, name2) \
  873. sandbox_cfg_allow_stat_filename(&cfg, get_datadir_fname2((name), (name2)))
  874. #define STAT_KEY_DIRECTORY() \
  875. sandbox_cfg_allow_stat_filename(&cfg, tor_strdup(options->KeyDirectory))
  876. STAT_DATADIR(NULL);
  877. STAT_DATADIR("lock");
  878. STAT_DATADIR("state");
  879. STAT_DATADIR("router-stability");
  880. STAT_CACHEDIR("cached-extrainfo.new");
  881. {
  882. smartlist_t *files = smartlist_new();
  883. tor_log_get_logfile_names(files);
  884. SMARTLIST_FOREACH(files, char *, file_name, {
  885. /* steals reference */
  886. sandbox_cfg_allow_open_filename(&cfg, file_name);
  887. });
  888. smartlist_free(files);
  889. }
  890. {
  891. smartlist_t *files = smartlist_new();
  892. smartlist_t *dirs = smartlist_new();
  893. hs_service_lists_fnames_for_sandbox(files, dirs);
  894. SMARTLIST_FOREACH(files, char *, file_name, {
  895. char *tmp_name = NULL;
  896. tor_asprintf(&tmp_name, "%s.tmp", file_name);
  897. sandbox_cfg_allow_rename(&cfg,
  898. tor_strdup(tmp_name), tor_strdup(file_name));
  899. /* steals references */
  900. sandbox_cfg_allow_open_filename(&cfg, file_name);
  901. sandbox_cfg_allow_open_filename(&cfg, tmp_name);
  902. });
  903. SMARTLIST_FOREACH(dirs, char *, dir, {
  904. /* steals reference */
  905. sandbox_cfg_allow_stat_filename(&cfg, dir);
  906. });
  907. smartlist_free(files);
  908. smartlist_free(dirs);
  909. }
  910. {
  911. char *fname;
  912. if ((fname = get_controller_cookie_file_name())) {
  913. sandbox_cfg_allow_open_filename(&cfg, fname);
  914. }
  915. if ((fname = get_ext_or_auth_cookie_file_name())) {
  916. sandbox_cfg_allow_open_filename(&cfg, fname);
  917. }
  918. }
  919. SMARTLIST_FOREACH_BEGIN(get_configured_ports(), port_cfg_t *, port) {
  920. if (!port->is_unix_addr)
  921. continue;
  922. /* When we open an AF_UNIX address, we want permission to open the
  923. * directory that holds it. */
  924. char *dirname = tor_strdup(port->unix_addr);
  925. if (get_parent_directory(dirname) == 0) {
  926. OPEN(dirname);
  927. }
  928. tor_free(dirname);
  929. sandbox_cfg_allow_chmod_filename(&cfg, tor_strdup(port->unix_addr));
  930. sandbox_cfg_allow_chown_filename(&cfg, tor_strdup(port->unix_addr));
  931. } SMARTLIST_FOREACH_END(port);
  932. if (options->DirPortFrontPage) {
  933. sandbox_cfg_allow_open_filename(&cfg,
  934. tor_strdup(options->DirPortFrontPage));
  935. }
  936. // orport
  937. if (server_mode(get_options())) {
  938. OPEN_KEYDIR_SUFFIX("secret_id_key", ".tmp");
  939. OPEN_KEYDIR_SUFFIX("secret_onion_key", ".tmp");
  940. OPEN_KEYDIR_SUFFIX("secret_onion_key_ntor", ".tmp");
  941. OPEN_KEYDIR("secret_id_key.old");
  942. OPEN_KEYDIR("secret_onion_key.old");
  943. OPEN_KEYDIR("secret_onion_key_ntor.old");
  944. OPEN_KEYDIR_SUFFIX("ed25519_master_id_secret_key", ".tmp");
  945. OPEN_KEYDIR_SUFFIX("ed25519_master_id_secret_key_encrypted", ".tmp");
  946. OPEN_KEYDIR_SUFFIX("ed25519_master_id_public_key", ".tmp");
  947. OPEN_KEYDIR_SUFFIX("ed25519_signing_secret_key", ".tmp");
  948. OPEN_KEYDIR_SUFFIX("ed25519_signing_secret_key_encrypted", ".tmp");
  949. OPEN_KEYDIR_SUFFIX("ed25519_signing_public_key", ".tmp");
  950. OPEN_KEYDIR_SUFFIX("ed25519_signing_cert", ".tmp");
  951. OPEN_DATADIR2_SUFFIX("stats", "bridge-stats", ".tmp");
  952. OPEN_DATADIR2_SUFFIX("stats", "dirreq-stats", ".tmp");
  953. OPEN_DATADIR2_SUFFIX("stats", "entry-stats", ".tmp");
  954. OPEN_DATADIR2_SUFFIX("stats", "exit-stats", ".tmp");
  955. OPEN_DATADIR2_SUFFIX("stats", "buffer-stats", ".tmp");
  956. OPEN_DATADIR2_SUFFIX("stats", "conn-stats", ".tmp");
  957. OPEN_DATADIR2_SUFFIX("stats", "hidserv-stats", ".tmp");
  958. OPEN_DATADIR("approved-routers");
  959. OPEN_DATADIR_SUFFIX("fingerprint", ".tmp");
  960. OPEN_DATADIR_SUFFIX("hashed-fingerprint", ".tmp");
  961. OPEN_DATADIR_SUFFIX("router-stability", ".tmp");
  962. OPEN("/etc/resolv.conf");
  963. RENAME_SUFFIX("fingerprint", ".tmp");
  964. RENAME_KEYDIR_SUFFIX("secret_onion_key_ntor", ".tmp");
  965. RENAME_KEYDIR_SUFFIX("secret_id_key", ".tmp");
  966. RENAME_KEYDIR_SUFFIX("secret_id_key.old", ".tmp");
  967. RENAME_KEYDIR_SUFFIX("secret_onion_key", ".tmp");
  968. RENAME_KEYDIR_SUFFIX("secret_onion_key.old", ".tmp");
  969. RENAME_SUFFIX2("stats", "bridge-stats", ".tmp");
  970. RENAME_SUFFIX2("stats", "dirreq-stats", ".tmp");
  971. RENAME_SUFFIX2("stats", "entry-stats", ".tmp");
  972. RENAME_SUFFIX2("stats", "exit-stats", ".tmp");
  973. RENAME_SUFFIX2("stats", "buffer-stats", ".tmp");
  974. RENAME_SUFFIX2("stats", "conn-stats", ".tmp");
  975. RENAME_SUFFIX2("stats", "hidserv-stats", ".tmp");
  976. RENAME_SUFFIX("hashed-fingerprint", ".tmp");
  977. RENAME_SUFFIX("router-stability", ".tmp");
  978. RENAME_KEYDIR_SUFFIX("ed25519_master_id_secret_key", ".tmp");
  979. RENAME_KEYDIR_SUFFIX("ed25519_master_id_secret_key_encrypted", ".tmp");
  980. RENAME_KEYDIR_SUFFIX("ed25519_master_id_public_key", ".tmp");
  981. RENAME_KEYDIR_SUFFIX("ed25519_signing_secret_key", ".tmp");
  982. RENAME_KEYDIR_SUFFIX("ed25519_signing_cert", ".tmp");
  983. sandbox_cfg_allow_rename(&cfg,
  984. get_keydir_fname("secret_onion_key"),
  985. get_keydir_fname("secret_onion_key.old"));
  986. sandbox_cfg_allow_rename(&cfg,
  987. get_keydir_fname("secret_onion_key_ntor"),
  988. get_keydir_fname("secret_onion_key_ntor.old"));
  989. STAT_KEY_DIRECTORY();
  990. OPEN_DATADIR("stats");
  991. STAT_DATADIR("stats");
  992. STAT_DATADIR2("stats", "dirreq-stats");
  993. consdiffmgr_register_with_sandbox(&cfg);
  994. }
  995. init_addrinfo();
  996. return cfg;
  997. }
  998. int
  999. run_tor_main_loop(void)
  1000. {
  1001. handle_signals();
  1002. timers_initialize();
  1003. initialize_mainloop_events();
  1004. /* load the private keys, if we're supposed to have them, and set up the
  1005. * TLS context. */
  1006. if (! client_identity_key_is_set()) {
  1007. if (init_keys() < 0) {
  1008. log_err(LD_OR, "Error initializing keys; exiting");
  1009. return -1;
  1010. }
  1011. }
  1012. /* Set up our buckets */
  1013. connection_bucket_init();
  1014. /* initialize the bootstrap status events to know we're starting up */
  1015. control_event_bootstrap(BOOTSTRAP_STATUS_STARTING, 0);
  1016. /* Initialize the keypinning log. */
  1017. if (authdir_mode_v3(get_options())) {
  1018. char *fname = get_datadir_fname("key-pinning-journal");
  1019. int r = 0;
  1020. if (keypin_load_journal(fname)<0) {
  1021. log_err(LD_DIR, "Error loading key-pinning journal: %s",strerror(errno));
  1022. r = -1;
  1023. }
  1024. if (keypin_open_journal(fname)<0) {
  1025. log_err(LD_DIR, "Error opening key-pinning journal: %s",strerror(errno));
  1026. r = -1;
  1027. }
  1028. tor_free(fname);
  1029. if (r)
  1030. return r;
  1031. }
  1032. {
  1033. /* This is the old name for key-pinning-journal. These got corrupted
  1034. * in a couple of cases by #16530, so we started over. See #16580 for
  1035. * the rationale and for other options we didn't take. We can remove
  1036. * this code once all the authorities that ran 0.2.7.1-alpha-dev are
  1037. * upgraded.
  1038. */
  1039. char *fname = get_datadir_fname("key-pinning-entries");
  1040. unlink(fname);
  1041. tor_free(fname);
  1042. }
  1043. if (trusted_dirs_reload_certs()) {
  1044. log_warn(LD_DIR,
  1045. "Couldn't load all cached v3 certificates. Starting anyway.");
  1046. }
  1047. if (router_reload_consensus_networkstatus()) {
  1048. return -1;
  1049. }
  1050. /* load the routers file, or assign the defaults. */
  1051. if (router_reload_router_list()) {
  1052. return -1;
  1053. }
  1054. /* load the networkstatuses. (This launches a download for new routers as
  1055. * appropriate.)
  1056. */
  1057. const time_t now = time(NULL);
  1058. directory_info_has_arrived(now, 1, 0);
  1059. if (server_mode(get_options()) || dir_server_mode(get_options())) {
  1060. /* launch cpuworkers. Need to do this *after* we've read the onion key. */
  1061. cpu_init();
  1062. }
  1063. consdiffmgr_enable_background_compression();
  1064. /* Setup shared random protocol subsystem. */
  1065. if (authdir_mode_v3(get_options())) {
  1066. if (sr_init(1) < 0) {
  1067. return -1;
  1068. }
  1069. }
  1070. /* initialize dns resolve map, spawn workers if needed */
  1071. if (dns_init() < 0) {
  1072. if (get_options()->ServerDNSAllowBrokenConfig)
  1073. log_warn(LD_GENERAL, "Couldn't set up any working nameservers. "
  1074. "Network not up yet? Will try again soon.");
  1075. else {
  1076. log_err(LD_GENERAL,"Error initializing dns subsystem; exiting. To "
  1077. "retry instead, set the ServerDNSAllowBrokenResolvConf option.");
  1078. }
  1079. }
  1080. #ifdef HAVE_SYSTEMD
  1081. {
  1082. const int r = sd_notify(0, "READY=1");
  1083. if (r < 0) {
  1084. log_warn(LD_GENERAL, "Unable to send readiness to systemd: %s",
  1085. strerror(r));
  1086. } else if (r > 0) {
  1087. log_notice(LD_GENERAL, "Signaled readiness to systemd");
  1088. } else {
  1089. log_info(LD_GENERAL, "Systemd NOTIFY_SOCKET not present.");
  1090. }
  1091. }
  1092. #endif /* defined(HAVE_SYSTEMD) */
  1093. return do_main_loop();
  1094. }
  1095. /** Install the publish/subscribe relationships for all the subsystems. */
  1096. static void
  1097. pubsub_install(void)
  1098. {
  1099. pubsub_builder_t *builder = pubsub_builder_new();
  1100. int r = subsystems_add_pubsub(builder);
  1101. tor_assert(r == 0);
  1102. r = tor_mainloop_connect_pubsub(builder); // consumes builder
  1103. tor_assert(r == 0);
  1104. }
  1105. /** Connect the mainloop to its publish/subscribe message delivery events if
  1106. * appropriate, and configure the global channels appropriately. */
  1107. static void
  1108. pubsub_connect(void)
  1109. {
  1110. if (get_options()->command == CMD_RUN_TOR) {
  1111. tor_mainloop_connect_pubsub_events();
  1112. /* XXXX For each pubsub channel, its delivery strategy should be set at
  1113. * this XXXX point, using tor_mainloop_set_delivery_strategy().
  1114. */
  1115. tor_mainloop_set_delivery_strategy("orconn", DELIV_IMMEDIATE);
  1116. tor_mainloop_set_delivery_strategy("ocirc", DELIV_IMMEDIATE);
  1117. }
  1118. }
  1119. /* Main entry point for the Tor process. Called from tor_main(), and by
  1120. * anybody embedding Tor. */
  1121. int
  1122. tor_run_main(const tor_main_configuration_t *tor_cfg)
  1123. {
  1124. int result = 0;
  1125. #ifdef EVENT_SET_MEM_FUNCTIONS_IMPLEMENTED
  1126. event_set_mem_functions(tor_malloc_, tor_realloc_, tor_free_);
  1127. #endif
  1128. subsystems_init();
  1129. init_protocol_warning_severity_level();
  1130. int argc = tor_cfg->argc + tor_cfg->argc_owned;
  1131. char **argv = tor_calloc(argc, sizeof(char*));
  1132. memcpy(argv, tor_cfg->argv, tor_cfg->argc*sizeof(char*));
  1133. if (tor_cfg->argc_owned)
  1134. memcpy(argv + tor_cfg->argc, tor_cfg->argv_owned,
  1135. tor_cfg->argc_owned*sizeof(char*));
  1136. #ifdef NT_SERVICE
  1137. {
  1138. int done = 0;
  1139. result = nt_service_parse_options(argc, argv, &done);
  1140. if (done) {
  1141. goto done;
  1142. }
  1143. }
  1144. #endif /* defined(NT_SERVICE) */
  1145. pubsub_install();
  1146. {
  1147. int init_rv = tor_init(argc, argv);
  1148. if (init_rv) {
  1149. tor_free_all(0);
  1150. result = (init_rv < 0) ? -1 : 0;
  1151. goto done;
  1152. }
  1153. }
  1154. pubsub_connect();
  1155. if (get_options()->Sandbox && get_options()->command == CMD_RUN_TOR) {
  1156. sandbox_cfg_t* cfg = sandbox_init_filter();
  1157. if (sandbox_init(cfg)) {
  1158. tor_free(argv);
  1159. log_err(LD_BUG,"Failed to create syscall sandbox filter");
  1160. tor_free_all(0);
  1161. return -1;
  1162. }
  1163. tor_make_getaddrinfo_cache_active();
  1164. // registering libevent rng
  1165. #ifdef HAVE_EVUTIL_SECURE_RNG_SET_URANDOM_DEVICE_FILE
  1166. evutil_secure_rng_set_urandom_device_file(
  1167. (char*) sandbox_intern_string("/dev/urandom"));
  1168. #endif
  1169. }
  1170. switch (get_options()->command) {
  1171. case CMD_RUN_TOR:
  1172. #ifdef NT_SERVICE
  1173. nt_service_set_state(SERVICE_RUNNING);
  1174. #endif
  1175. result = run_tor_main_loop();
  1176. break;
  1177. case CMD_KEYGEN:
  1178. result = load_ed_keys(get_options(), time(NULL)) < 0;
  1179. break;
  1180. case CMD_KEY_EXPIRATION:
  1181. init_keys();
  1182. result = log_cert_expiration();
  1183. break;
  1184. case CMD_LIST_FINGERPRINT:
  1185. result = do_list_fingerprint();
  1186. break;
  1187. case CMD_HASH_PASSWORD:
  1188. do_hash_password();
  1189. result = 0;
  1190. break;
  1191. case CMD_VERIFY_CONFIG:
  1192. if (quiet_level == 0)
  1193. printf("Configuration was valid\n");
  1194. result = 0;
  1195. break;
  1196. case CMD_DUMP_CONFIG:
  1197. result = do_dump_config();
  1198. break;
  1199. case CMD_RUN_UNITTESTS: /* only set by test.c */
  1200. default:
  1201. log_warn(LD_BUG,"Illegal command number %d: internal error.",
  1202. get_options()->command);
  1203. result = -1;
  1204. }
  1205. tor_cleanup();
  1206. done:
  1207. tor_free(argv);
  1208. return result;
  1209. }