main.c 47 KB

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