main.c 42 KB

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