main.c 43 KB

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