main.c 47 KB

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