main.c 45 KB

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