main.c 45 KB

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