main.c 45 KB

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