main.c 45 KB

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