main.c 47 KB

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