main.c 43 KB

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