main.c 46 KB

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