main.c 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2007, Roger Dingledine, Nick Mathewson. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. const char main_c_id[] =
  7. "$Id$";
  8. /**
  9. * \file main.c
  10. * \brief Toplevel module. Handles signals, multiplexes between
  11. * connections, implements main loop, and drives scheduled events.
  12. **/
  13. #include "or.h"
  14. #ifdef USE_DMALLOC
  15. #include <dmalloc.h>
  16. #endif
  17. void evdns_shutdown(int);
  18. /********* PROTOTYPES **********/
  19. static void dumpmemusage(int severity);
  20. static void dumpstats(int severity); /* log stats */
  21. static void conn_read_callback(int fd, short event, void *_conn);
  22. static void conn_write_callback(int fd, short event, void *_conn);
  23. static void signal_callback(int fd, short events, void *arg);
  24. static void second_elapsed_callback(int fd, short event, void *args);
  25. static int conn_close_if_marked(int i);
  26. static void connection_start_reading_from_linked_conn(connection_t *conn);
  27. static int connection_should_read_from_linked_conn(connection_t *conn);
  28. /********* START VARIABLES **********/
  29. int global_read_bucket; /**< Max number of bytes I can read this second. */
  30. int global_write_bucket; /**< Max number of bytes I can write this second. */
  31. /** Max number of relayed (bandwidth class 1) bytes I can read this second. */
  32. int global_relayed_read_bucket;
  33. /** Max number of relayed (bandwidth class 1) bytes I can write this second. */
  34. int global_relayed_write_bucket;
  35. /** What was the read bucket before the last call to prepare_for_pool?
  36. * (used to determine how many bytes we've read). */
  37. static int stats_prev_global_read_bucket;
  38. /** What was the write bucket before the last call to prepare_for_pool?
  39. * (used to determine how many bytes we've written). */
  40. static int stats_prev_global_write_bucket;
  41. /* XXX we might want to keep stats about global_relayed_*_bucket too. Or not.*/
  42. /** How many bytes have we read/written since we started the process? */
  43. static uint64_t stats_n_bytes_read = 0;
  44. static uint64_t stats_n_bytes_written = 0;
  45. /** What time did this process start up? */
  46. long time_of_process_start = 0;
  47. /** How many seconds have we been running? */
  48. long stats_n_seconds_working = 0;
  49. /** When do we next download a directory? */
  50. static time_t time_to_fetch_directory = 0;
  51. /** When do we next download a running-routers summary? */
  52. static time_t time_to_fetch_running_routers = 0;
  53. /** When do we next launch DNS wildcarding checks? */
  54. static time_t time_to_check_for_correct_dns = 0;
  55. /** How often will we honor SIGNEWNYM requests? */
  56. #define MAX_SIGNEWNYM_RATE 10
  57. /** When did we last process a SIGNEWNYM request? */
  58. static time_t time_of_last_signewnym = 0;
  59. /** Is there a signewnym request we're currently waiting to handle? */
  60. static int signewnym_is_pending = 0;
  61. /** Smartlist of all open connections. */
  62. static smartlist_t *connection_array = NULL;
  63. /** List of connections that have been marked for close and need to be freed
  64. * and removed from connection_array. */
  65. static smartlist_t *closeable_connection_lst = NULL;
  66. /** List of linked connections that are currently reading data into their
  67. * inbuf from their partner's outbuf. */
  68. static smartlist_t *active_linked_connection_lst = NULL;
  69. /** Flag: Set to true iff we entered the current libevent main loop via
  70. * <b>loop_once</b>. If so, there's no need to trigger a loopexit in order
  71. * to handle linked connections. */
  72. static int called_loop_once = 0;
  73. /** We set this to 1 when we've opened a circuit, so we can print a log
  74. * entry to inform the user that Tor is working. */
  75. int has_completed_circuit=0;
  76. /** If our router descriptor ever goes this long without being regenerated
  77. * because something changed, we force an immediate regenerate-and-upload. */
  78. #define FORCE_REGENERATE_DESCRIPTOR_INTERVAL (18*60*60)
  79. /** How often do we check whether part of our router info has changed in a way
  80. * that would require an upload? */
  81. #define CHECK_DESCRIPTOR_INTERVAL (60)
  82. /** How often do we (as a router) check whether our IP address has changed? */
  83. #define CHECK_IPADDRESS_INTERVAL (15*60)
  84. /** How often do we check buffers and pools for empty space that can be
  85. * deallocated? */
  86. #define MEM_SHRINK_INTERVAL (60)
  87. /** How often do we check for router descriptors that we should download? */
  88. #define DESCRIPTOR_RETRY_INTERVAL (10)
  89. /** How often do we 'forgive' undownloadable router descriptors and attempt
  90. * to download them again? */
  91. #define DESCRIPTOR_FAILURE_RESET_INTERVAL (60*60)
  92. /** How often do we add more entropy to OpenSSL's RNG pool? */
  93. #define ENTROPY_INTERVAL (60*60)
  94. /** How long do we let a directory connection stall before expiring it? */
  95. #define DIR_CONN_MAX_STALL (5*60)
  96. /** How old do we let a connection to an OR get before deciding it's
  97. * obsolete? */
  98. #define TIME_BEFORE_OR_CONN_IS_OBSOLETE (60*60*24*7)
  99. /** How long do we let OR connections handshake before we decide that
  100. * they are obsolete? */
  101. #define TLS_HANDSHAKE_TIMEOUT (60)
  102. /** How often do we write hidden service usage statistics to disk? */
  103. #define WRITE_HSUSAGE_INTERVAL (900)
  104. /********* END VARIABLES ************/
  105. /****************************************************************************
  106. *
  107. * This section contains accessors and other methods on the connection_array
  108. * variables (which are global within this file and unavailable outside it).
  109. *
  110. ****************************************************************************/
  111. /** Add <b>conn</b> to the array of connections that we can poll on. The
  112. * connection's socket must be set; the connection starts out
  113. * non-reading and non-writing.
  114. */
  115. int
  116. connection_add(connection_t *conn)
  117. {
  118. tor_assert(conn);
  119. tor_assert(conn->s >= 0 ||
  120. conn->linked ||
  121. (conn->type == CONN_TYPE_AP &&
  122. TO_EDGE_CONN(conn)->is_dns_request));
  123. tor_assert(conn->conn_array_index == -1); /* can only connection_add once */
  124. conn->conn_array_index = smartlist_len(connection_array);
  125. smartlist_add(connection_array, conn);
  126. if (conn->s >= 0 || conn->linked) {
  127. conn->read_event = tor_malloc_zero(sizeof(struct event));
  128. conn->write_event = tor_malloc_zero(sizeof(struct event));
  129. event_set(conn->read_event, conn->s, EV_READ|EV_PERSIST,
  130. conn_read_callback, conn);
  131. event_set(conn->write_event, conn->s, EV_WRITE|EV_PERSIST,
  132. conn_write_callback, conn);
  133. }
  134. log_debug(LD_NET,"new conn type %s, socket %d, n_conns %d.",
  135. conn_type_to_string(conn->type), conn->s,
  136. smartlist_len(connection_array));
  137. return 0;
  138. }
  139. /** Remove the connection from the global list, and remove the
  140. * corresponding poll entry. Calling this function will shift the last
  141. * connection (if any) into the position occupied by conn.
  142. */
  143. int
  144. connection_remove(connection_t *conn)
  145. {
  146. int current_index;
  147. connection_t *tmp;
  148. tor_assert(conn);
  149. log_debug(LD_NET,"removing socket %d (type %s), n_conns now %d",
  150. conn->s, conn_type_to_string(conn->type),
  151. smartlist_len(connection_array));
  152. tor_assert(conn->conn_array_index >= 0);
  153. current_index = conn->conn_array_index;
  154. connection_unregister_events(conn); /* This is redundant, but cheap. */
  155. if (current_index == smartlist_len(connection_array)-1) { /* at the end */
  156. smartlist_del(connection_array, current_index);
  157. return 0;
  158. }
  159. /* replace this one with the one at the end */
  160. smartlist_del(connection_array, current_index);
  161. tmp = smartlist_get(connection_array, current_index);
  162. tmp->conn_array_index = current_index;
  163. return 0;
  164. }
  165. /** If <b>conn</b> is an edge conn, remove it from the list
  166. * of conn's on this circuit. If it's not on an edge,
  167. * flush and send destroys for all circuits on this conn.
  168. *
  169. * Remove it from connection_array (if applicable) and
  170. * from closeable_connection_list.
  171. *
  172. * Then free it.
  173. */
  174. static void
  175. connection_unlink(connection_t *conn)
  176. {
  177. connection_about_to_close_connection(conn);
  178. if (conn->conn_array_index >= 0) {
  179. connection_remove(conn);
  180. }
  181. if (conn->linked_conn) {
  182. conn->linked_conn->linked_conn = NULL;
  183. if (! conn->linked_conn->marked_for_close &&
  184. conn->linked_conn->reading_from_linked_conn)
  185. connection_start_reading(conn->linked_conn);
  186. conn->linked_conn = NULL;
  187. }
  188. smartlist_remove(closeable_connection_lst, conn);
  189. smartlist_remove(active_linked_connection_lst, conn);
  190. if (conn->type == CONN_TYPE_EXIT) {
  191. assert_connection_edge_not_dns_pending(TO_EDGE_CONN(conn));
  192. }
  193. if (conn->type == CONN_TYPE_OR) {
  194. if (!tor_digest_is_zero(TO_OR_CONN(conn)->identity_digest))
  195. connection_or_remove_from_identity_map(TO_OR_CONN(conn));
  196. }
  197. connection_free(conn);
  198. }
  199. /** Schedule <b>conn</b> to be closed. **/
  200. void
  201. add_connection_to_closeable_list(connection_t *conn)
  202. {
  203. tor_assert(!smartlist_isin(closeable_connection_lst, conn));
  204. tor_assert(conn->marked_for_close);
  205. assert_connection_ok(conn, time(NULL));
  206. smartlist_add(closeable_connection_lst, conn);
  207. }
  208. /** Return 1 if conn is on the closeable list, else return 0. */
  209. int
  210. connection_is_on_closeable_list(connection_t *conn)
  211. {
  212. return smartlist_isin(closeable_connection_lst, conn);
  213. }
  214. /** Return true iff conn is in the current poll array. */
  215. int
  216. connection_in_array(connection_t *conn)
  217. {
  218. return smartlist_isin(connection_array, conn);
  219. }
  220. /** Set <b>*array</b> to an array of all connections, and <b>*n</b>
  221. * to the length of the array. <b>*array</b> and <b>*n</b> must not
  222. * be modified.
  223. */
  224. smartlist_t *
  225. get_connection_array(void)
  226. {
  227. return connection_array;
  228. }
  229. /** Set the event mask on <b>conn</b> to <b>events</b>. (The event
  230. * mask is a bitmask whose bits are EV_READ and EV_WRITE.)
  231. */
  232. void
  233. connection_watch_events(connection_t *conn, short events)
  234. {
  235. if (events & EV_READ)
  236. connection_start_reading(conn);
  237. else
  238. connection_stop_reading(conn);
  239. if (events & EV_WRITE)
  240. connection_start_writing(conn);
  241. else
  242. connection_stop_writing(conn);
  243. }
  244. /** Return true iff <b>conn</b> is listening for read events. */
  245. int
  246. connection_is_reading(connection_t *conn)
  247. {
  248. tor_assert(conn);
  249. return conn->reading_from_linked_conn ||
  250. (conn->read_event && event_pending(conn->read_event, EV_READ, NULL));
  251. }
  252. /** Tell the main loop to stop notifying <b>conn</b> of any read events. */
  253. void
  254. connection_stop_reading(connection_t *conn)
  255. {
  256. tor_assert(conn);
  257. tor_assert(conn->read_event);
  258. if (conn->linked) {
  259. conn->reading_from_linked_conn = 0;
  260. connection_stop_reading_from_linked_conn(conn);
  261. } else {
  262. if (event_del(conn->read_event))
  263. log_warn(LD_NET, "Error from libevent setting read event state for %d "
  264. "to unwatched: %s",
  265. conn->s,
  266. tor_socket_strerror(tor_socket_errno(conn->s)));
  267. }
  268. }
  269. /** Tell the main loop to start notifying <b>conn</b> of any read events. */
  270. void
  271. connection_start_reading(connection_t *conn)
  272. {
  273. tor_assert(conn);
  274. tor_assert(conn->read_event);
  275. if (conn->linked) {
  276. conn->reading_from_linked_conn = 1;
  277. if (connection_should_read_from_linked_conn(conn))
  278. connection_start_reading_from_linked_conn(conn);
  279. } else {
  280. if (event_add(conn->read_event, NULL))
  281. log_warn(LD_NET, "Error from libevent setting read event state for %d "
  282. "to watched: %s",
  283. conn->s,
  284. tor_socket_strerror(tor_socket_errno(conn->s)));
  285. }
  286. }
  287. /** Return true iff <b>conn</b> is listening for write events. */
  288. int
  289. connection_is_writing(connection_t *conn)
  290. {
  291. tor_assert(conn);
  292. return conn->writing_to_linked_conn ||
  293. (conn->write_event && event_pending(conn->write_event, EV_WRITE, NULL));
  294. }
  295. /** Tell the main loop to stop notifying <b>conn</b> of any write events. */
  296. void
  297. connection_stop_writing(connection_t *conn)
  298. {
  299. tor_assert(conn);
  300. tor_assert(conn->write_event);
  301. if (conn->linked) {
  302. conn->writing_to_linked_conn = 0;
  303. if (conn->linked_conn)
  304. connection_stop_reading_from_linked_conn(conn->linked_conn);
  305. } else {
  306. if (event_del(conn->write_event))
  307. log_warn(LD_NET, "Error from libevent setting write event state for %d "
  308. "to unwatched: %s",
  309. conn->s,
  310. tor_socket_strerror(tor_socket_errno(conn->s)));
  311. }
  312. }
  313. /** Tell the main loop to start notifying <b>conn</b> of any write events. */
  314. void
  315. connection_start_writing(connection_t *conn)
  316. {
  317. tor_assert(conn);
  318. tor_assert(conn->write_event);
  319. if (conn->linked) {
  320. conn->writing_to_linked_conn = 1;
  321. if (conn->linked_conn &&
  322. connection_should_read_from_linked_conn(conn->linked_conn))
  323. connection_start_reading_from_linked_conn(conn->linked_conn);
  324. } else {
  325. if (event_add(conn->write_event, NULL))
  326. log_warn(LD_NET, "Error from libevent setting write event state for %d "
  327. "to watched: %s",
  328. conn->s,
  329. tor_socket_strerror(tor_socket_errno(conn->s)));
  330. }
  331. }
  332. /** Return true iff <b>conn</b> is linked conn, and reading from the conn
  333. * linked to it would be good and feasible. (Reading is "feasible" if the
  334. * other conn exists and has data in its outbuf, and is "good" if we have our
  335. * reading_from_linked_conn flag set and the other conn has its
  336. * writing_to_linked_conn flag set.)*/
  337. static int
  338. connection_should_read_from_linked_conn(connection_t *conn)
  339. {
  340. if (conn->linked && conn->reading_from_linked_conn) {
  341. if (! conn->linked_conn ||
  342. (conn->linked_conn->writing_to_linked_conn &&
  343. buf_datalen(conn->linked_conn->outbuf)))
  344. return 1;
  345. }
  346. return 0;
  347. }
  348. /** Helper: Tell the main loop to begin reading bytes into <b>conn</b> from
  349. * its linked connection, if it is not doing so already. Called by
  350. * connection_start_reading and connection_start_writing as appropriate. */
  351. static void
  352. connection_start_reading_from_linked_conn(connection_t *conn)
  353. {
  354. tor_assert(conn);
  355. tor_assert(conn->linked == 1);
  356. if (!conn->active_on_link) {
  357. conn->active_on_link = 1;
  358. smartlist_add(active_linked_connection_lst, conn);
  359. if (!called_loop_once) {
  360. /* This is the first event on the list; we won't be in LOOP_ONCE mode,
  361. * so we need to make sure that the event_loop() actually exits at the
  362. * end of its run through the current connections and
  363. * lets us activate read events for linked connections. */
  364. struct timeval tv = { 0, 0 };
  365. event_loopexit(&tv);
  366. }
  367. } else {
  368. tor_assert(smartlist_isin(active_linked_connection_lst, conn));
  369. }
  370. }
  371. /** Tell the main loop to stop reading bytes into <b>conn</b> from its linked
  372. * connection, if is currently doing so. Called by connection_stop_reading,
  373. * connection_stop_writing, and connection_read. */
  374. void
  375. connection_stop_reading_from_linked_conn(connection_t *conn)
  376. {
  377. tor_assert(conn);
  378. tor_assert(conn->linked == 1);
  379. if (conn->active_on_link) {
  380. conn->active_on_link = 0;
  381. /* XXXX020 maybe we should keep an index here so we can smartlist_del
  382. * cleanly. */
  383. smartlist_remove(active_linked_connection_lst, conn);
  384. } else {
  385. tor_assert(!smartlist_isin(active_linked_connection_lst, conn));
  386. }
  387. }
  388. /** Close all connections that have been scheduled to get closed. */
  389. static void
  390. close_closeable_connections(void)
  391. {
  392. int i;
  393. for (i = 0; i < smartlist_len(closeable_connection_lst); ) {
  394. connection_t *conn = smartlist_get(closeable_connection_lst, i);
  395. if (conn->conn_array_index < 0) {
  396. connection_unlink(conn); /* blow it away right now */
  397. } else {
  398. if (!conn_close_if_marked(conn->conn_array_index))
  399. ++i;
  400. }
  401. }
  402. }
  403. /** Libevent callback: this gets invoked when (connection_t*)<b>conn</b> has
  404. * some data to read. */
  405. static void
  406. conn_read_callback(int fd, short event, void *_conn)
  407. {
  408. connection_t *conn = _conn;
  409. (void)fd;
  410. (void)event;
  411. log_debug(LD_NET,"socket %d wants to read.",conn->s);
  412. assert_connection_ok(conn, time(NULL));
  413. if (connection_handle_read(conn) < 0) {
  414. if (!conn->marked_for_close) {
  415. #ifndef MS_WINDOWS
  416. log_warn(LD_BUG,"Unhandled error on read for %s connection "
  417. "(fd %d); removing",
  418. conn_type_to_string(conn->type), conn->s);
  419. tor_fragile_assert();
  420. #endif
  421. if (CONN_IS_EDGE(conn))
  422. connection_edge_end_errno(TO_EDGE_CONN(conn));
  423. connection_mark_for_close(conn);
  424. }
  425. }
  426. assert_connection_ok(conn, time(NULL));
  427. if (smartlist_len(closeable_connection_lst))
  428. close_closeable_connections();
  429. }
  430. /** Libevent callback: this gets invoked when (connection_t*)<b>conn</b> has
  431. * some data to write. */
  432. static void
  433. conn_write_callback(int fd, short events, void *_conn)
  434. {
  435. connection_t *conn = _conn;
  436. (void)fd;
  437. (void)events;
  438. LOG_FN_CONN(conn, (LOG_DEBUG, LD_NET, "socket %d wants to write.",conn->s));
  439. assert_connection_ok(conn, time(NULL));
  440. if (connection_handle_write(conn, 0) < 0) {
  441. if (!conn->marked_for_close) {
  442. /* this connection is broken. remove it. */
  443. log_fn(LOG_WARN,LD_BUG,
  444. "unhandled error on write for %s connection (fd %d); removing",
  445. conn_type_to_string(conn->type), conn->s);
  446. tor_fragile_assert();
  447. if (CONN_IS_EDGE(conn)) {
  448. /* otherwise we cry wolf about duplicate close */
  449. edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
  450. if (!edge_conn->end_reason)
  451. edge_conn->end_reason = END_STREAM_REASON_INTERNAL;
  452. conn->edge_has_sent_end = 1;
  453. }
  454. /* XXX020 do we need a close-immediate here, so we don't try to flush? */
  455. connection_mark_for_close(conn);
  456. }
  457. }
  458. assert_connection_ok(conn, time(NULL));
  459. if (smartlist_len(closeable_connection_lst))
  460. close_closeable_connections();
  461. }
  462. /** If the connection at connection_array[i] is marked for close, then:
  463. * - If it has data that it wants to flush, try to flush it.
  464. * - If it _still_ has data to flush, and conn->hold_open_until_flushed is
  465. * true, then leave the connection open and return.
  466. * - Otherwise, remove the connection from connection_array and from
  467. * all other lists, close it, and free it.
  468. * Returns 1 if the connection was closed, 0 otherwise.
  469. */
  470. static int
  471. conn_close_if_marked(int i)
  472. {
  473. connection_t *conn;
  474. int retval;
  475. time_t now;
  476. conn = smartlist_get(connection_array, i);
  477. if (!conn->marked_for_close)
  478. return 0; /* nothing to see here, move along */
  479. now = time(NULL);
  480. assert_connection_ok(conn, now);
  481. assert_all_pending_dns_resolves_ok();
  482. log_debug(LD_NET,"Cleaning up connection (fd %d).",conn->s);
  483. if ((conn->s >= 0 || conn->linked_conn) && connection_wants_to_flush(conn)) {
  484. /* s == -1 means it's an incomplete edge connection, or that the socket
  485. * has already been closed as unflushable. */
  486. int sz = connection_bucket_write_limit(conn, now);
  487. if (!conn->hold_open_until_flushed)
  488. log_info(LD_NET,
  489. "Conn (addr %s, fd %d, type %s, state %d) marked, but wants "
  490. "to flush %d bytes. (Marked at %s:%d)",
  491. escaped_safe_str(conn->address),
  492. conn->s, conn_type_to_string(conn->type), conn->state,
  493. (int)conn->outbuf_flushlen,
  494. conn->marked_for_close_file, conn->marked_for_close);
  495. if (conn->linked_conn) {
  496. retval = move_buf_to_buf(conn->linked_conn->inbuf, conn->outbuf,
  497. &conn->outbuf_flushlen);
  498. if (retval >= 0) {
  499. /* The linked conn will notice that it has data when it notices that
  500. * we're gone. */
  501. connection_start_reading_from_linked_conn(conn->linked_conn);
  502. }
  503. /* XXXX020 Downgrade to debug. */
  504. log_info(LD_GENERAL, "Flushed last %d bytes from a linked conn; "
  505. "%d left; flushlen %d; wants-to-flush==%d", retval,
  506. (int)buf_datalen(conn->outbuf),
  507. (int)conn->outbuf_flushlen,
  508. connection_wants_to_flush(conn));
  509. } else if (connection_speaks_cells(conn)) {
  510. if (conn->state == OR_CONN_STATE_OPEN) {
  511. retval = flush_buf_tls(TO_OR_CONN(conn)->tls, conn->outbuf, sz,
  512. &conn->outbuf_flushlen);
  513. } else
  514. retval = -1; /* never flush non-open broken tls connections */
  515. } else {
  516. retval = flush_buf(conn->s, conn->outbuf, sz, &conn->outbuf_flushlen);
  517. }
  518. if (retval >= 0 && /* Technically, we could survive things like
  519. TLS_WANT_WRITE here. But don't bother for now. */
  520. conn->hold_open_until_flushed && connection_wants_to_flush(conn)) {
  521. if (retval > 0)
  522. LOG_FN_CONN(conn, (LOG_INFO,LD_NET,
  523. "Holding conn (fd %d) open for more flushing.",
  524. conn->s));
  525. /* XXX020 should we reset timestamp_lastwritten here? */
  526. return 0;
  527. }
  528. if (connection_wants_to_flush(conn)) {
  529. int severity;
  530. if (conn->type == CONN_TYPE_EXIT ||
  531. (conn->type == CONN_TYPE_OR && server_mode(get_options())) ||
  532. (conn->type == CONN_TYPE_DIR && conn->purpose == DIR_PURPOSE_SERVER))
  533. severity = LOG_INFO;
  534. else
  535. severity = LOG_NOTICE;
  536. /* XXXX Maybe allow this to happen a certain amount per hour; it usually
  537. * is meaningless. */
  538. log_fn(severity, LD_NET, "We stalled too much while trying to write %d "
  539. "bytes to address %s. If this happens a lot, either "
  540. "something is wrong with your network connection, or "
  541. "something is wrong with theirs. "
  542. "(fd %d, type %s, state %d, marked at %s:%d).",
  543. (int)buf_datalen(conn->outbuf),
  544. escaped_safe_str(conn->address), conn->s,
  545. conn_type_to_string(conn->type), conn->state,
  546. conn->marked_for_close_file,
  547. conn->marked_for_close);
  548. }
  549. }
  550. connection_unlink(conn); /* unlink, remove, free */
  551. return 1;
  552. }
  553. /** We've just tried every dirserver we know about, and none of
  554. * them were reachable. Assume the network is down. Change state
  555. * so next time an application connection arrives we'll delay it
  556. * and try another directory fetch. Kill off all the circuit_wait
  557. * streams that are waiting now, since they will all timeout anyway.
  558. */
  559. void
  560. directory_all_unreachable(time_t now)
  561. {
  562. connection_t *conn;
  563. (void)now;
  564. stats_n_seconds_working=0; /* reset it */
  565. while ((conn = connection_get_by_type_state(CONN_TYPE_AP,
  566. AP_CONN_STATE_CIRCUIT_WAIT))) {
  567. edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
  568. log_notice(LD_NET,
  569. "Is your network connection down? "
  570. "Failing connection to '%s:%d'.",
  571. safe_str(edge_conn->socks_request->address),
  572. edge_conn->socks_request->port);
  573. connection_mark_unattached_ap(edge_conn,
  574. END_STREAM_REASON_NET_UNREACHABLE);
  575. }
  576. control_event_general_status(LOG_ERR, "DIR_ALL_UNREACHABLE");
  577. }
  578. /** This function is called whenever we successfully pull down some new
  579. * network statuses or server descriptors. */
  580. void
  581. directory_info_has_arrived(time_t now, int from_cache)
  582. {
  583. or_options_t *options = get_options();
  584. if (!router_have_minimum_dir_info()) {
  585. log(LOG_NOTICE, LD_DIR,
  586. "I learned some more directory information, but not enough to "
  587. "build a circuit.");
  588. update_router_descriptor_downloads(now);
  589. return;
  590. } else {
  591. /* Don't even bother trying to get extrainfo until the rest of our
  592. * directory info is up-to-date */
  593. if (options->DownloadExtraInfo)
  594. update_extrainfo_downloads(now);
  595. }
  596. if (server_mode(options) && !we_are_hibernating() && !from_cache &&
  597. (has_completed_circuit || !any_predicted_circuits(now)))
  598. consider_testing_reachability(1, 1);
  599. }
  600. /** Perform regular maintenance tasks for a single connection. This
  601. * function gets run once per second per connection by run_scheduled_events.
  602. */
  603. static void
  604. run_connection_housekeeping(int i, time_t now)
  605. {
  606. cell_t cell;
  607. connection_t *conn = smartlist_get(connection_array, i);
  608. or_options_t *options = get_options();
  609. or_connection_t *or_conn;
  610. if (conn->outbuf && !buf_datalen(conn->outbuf) && conn->type == CONN_TYPE_OR)
  611. TO_OR_CONN(conn)->timestamp_lastempty = now;
  612. if (conn->marked_for_close) {
  613. /* nothing to do here */
  614. return;
  615. }
  616. /* Expire any directory connections that haven't been active (sent
  617. * if a server or received if a client) for 5 min */
  618. if (conn->type == CONN_TYPE_DIR &&
  619. ((DIR_CONN_IS_SERVER(conn) &&
  620. conn->timestamp_lastwritten + DIR_CONN_MAX_STALL < now) ||
  621. (!DIR_CONN_IS_SERVER(conn) &&
  622. conn->timestamp_lastread + DIR_CONN_MAX_STALL < now))) {
  623. log_info(LD_DIR,"Expiring wedged directory conn (fd %d, purpose %d)",
  624. conn->s, conn->purpose);
  625. /* This check is temporary; it's to let us know whether we should consider
  626. * parsing partial serverdesc responses. */
  627. if (conn->purpose == DIR_PURPOSE_FETCH_SERVERDESC &&
  628. buf_datalen(conn->inbuf)>=1024) {
  629. log_info(LD_DIR,"Trying to extract information from wedged server desc "
  630. "download.");
  631. connection_dir_reached_eof(TO_DIR_CONN(conn));
  632. } else {
  633. connection_mark_for_close(conn);
  634. }
  635. return;
  636. }
  637. if (!connection_speaks_cells(conn))
  638. return; /* we're all done here, the rest is just for OR conns */
  639. or_conn = TO_OR_CONN(conn);
  640. if (!conn->or_is_obsolete) {
  641. if (conn->timestamp_created + TIME_BEFORE_OR_CONN_IS_OBSOLETE < now) {
  642. log_info(LD_OR,
  643. "Marking OR conn to %s:%d obsolete (fd %d, %d secs old).",
  644. conn->address, conn->port, conn->s,
  645. (int)(now - conn->timestamp_created));
  646. conn->or_is_obsolete = 1;
  647. } else {
  648. or_connection_t *best =
  649. connection_or_get_by_identity_digest(or_conn->identity_digest);
  650. if (best && best != or_conn &&
  651. (conn->state == OR_CONN_STATE_OPEN ||
  652. now > conn->timestamp_created + TLS_HANDSHAKE_TIMEOUT)) {
  653. /* We only mark as obsolete connections that already are in
  654. * OR_CONN_STATE_OPEN, i.e. that have finished their TLS handshaking.
  655. * This is necessary because authorities judge whether a router is
  656. * reachable based on whether they were able to TLS handshake with it
  657. * recently. Without this check we would expire connections too
  658. * early for router->last_reachable to be updated.
  659. */
  660. log_info(LD_OR,
  661. "Marking duplicate conn to %s:%d obsolete "
  662. "(fd %d, %d secs old).",
  663. conn->address, conn->port, conn->s,
  664. (int)(now - conn->timestamp_created));
  665. conn->or_is_obsolete = 1;
  666. }
  667. }
  668. }
  669. if (conn->or_is_obsolete && !or_conn->n_circuits) {
  670. /* no unmarked circs -- mark it now */
  671. log_info(LD_OR,
  672. "Expiring non-used OR connection to fd %d (%s:%d) [Obsolete].",
  673. conn->s, conn->address, conn->port);
  674. connection_mark_for_close(conn);
  675. conn->hold_open_until_flushed = 1;
  676. return;
  677. }
  678. /* If we haven't written to an OR connection for a while, then either nuke
  679. the connection or send a keepalive, depending. */
  680. if (now >= conn->timestamp_lastwritten + options->KeepalivePeriod) {
  681. routerinfo_t *router = router_get_by_digest(or_conn->identity_digest);
  682. if (!connection_state_is_open(conn)) {
  683. log_info(LD_OR,"Expiring non-open OR connection to fd %d (%s:%d).",
  684. conn->s,conn->address, conn->port);
  685. connection_mark_for_close(conn);
  686. conn->hold_open_until_flushed = 1;
  687. } else if (we_are_hibernating() && !or_conn->n_circuits &&
  688. !buf_datalen(conn->outbuf)) {
  689. log_info(LD_OR,"Expiring non-used OR connection to fd %d (%s:%d) "
  690. "[Hibernating or exiting].",
  691. conn->s,conn->address, conn->port);
  692. connection_mark_for_close(conn);
  693. conn->hold_open_until_flushed = 1;
  694. } else if (!clique_mode(options) && !or_conn->n_circuits &&
  695. (!router || !server_mode(options) ||
  696. !router_is_clique_mode(router))) {
  697. log_info(LD_OR,"Expiring non-used OR connection to fd %d (%s:%d) "
  698. "[Not in clique mode].",
  699. conn->s,conn->address, conn->port);
  700. connection_mark_for_close(conn);
  701. conn->hold_open_until_flushed = 1;
  702. } else if (
  703. now >= or_conn->timestamp_lastempty + options->KeepalivePeriod*10 &&
  704. now >= conn->timestamp_lastwritten + options->KeepalivePeriod*10) {
  705. log_fn(LOG_PROTOCOL_WARN,LD_PROTOCOL,
  706. "Expiring stuck OR connection to fd %d (%s:%d). (%d bytes to "
  707. "flush; %d seconds since last write)",
  708. conn->s, conn->address, conn->port,
  709. (int)buf_datalen(conn->outbuf),
  710. (int)(now-conn->timestamp_lastwritten));
  711. connection_mark_for_close(conn);
  712. } else if (!buf_datalen(conn->outbuf)) {
  713. /* either in clique mode, or we've got a circuit. send a padding cell. */
  714. log_fn(LOG_DEBUG,LD_OR,"Sending keepalive to (%s:%d)",
  715. conn->address, conn->port);
  716. memset(&cell,0,sizeof(cell_t));
  717. cell.command = CELL_PADDING;
  718. connection_or_write_cell_to_buf(&cell, or_conn);
  719. }
  720. }
  721. }
  722. /** Perform regular maintenance tasks. This function gets run once per
  723. * second by prepare_for_poll.
  724. */
  725. static void
  726. run_scheduled_events(time_t now)
  727. {
  728. static time_t last_rotated_certificate = 0;
  729. static time_t time_to_check_listeners = 0;
  730. static time_t time_to_check_descriptor = 0;
  731. static time_t time_to_check_ipaddress = 0;
  732. static time_t time_to_shrink_memory = 0;
  733. static time_t time_to_try_getting_descriptors = 0;
  734. static time_t time_to_reset_descriptor_failures = 0;
  735. static time_t time_to_add_entropy = 0;
  736. static time_t time_to_write_hs_statistics = 0;
  737. static time_t time_to_downrate_stability = 0;
  738. #define SAVE_STABILITY_INTERVAL (30*60)
  739. static time_t time_to_save_stability = 0;
  740. or_options_t *options = get_options();
  741. int i;
  742. int have_dir_info;
  743. /** 0. See if we've been asked to shut down and our timeout has
  744. * expired; or if our bandwidth limits are exhausted and we
  745. * should hibernate; or if it's time to wake up from hibernation.
  746. */
  747. consider_hibernation(now);
  748. /* 0b. If we've deferred a signewnym, make sure it gets handled
  749. * eventually */
  750. if (signewnym_is_pending &&
  751. time_of_last_signewnym + MAX_SIGNEWNYM_RATE <= now) {
  752. log(LOG_INFO, LD_CONTROL, "Honoring delayed NEWNYM request");
  753. circuit_expire_all_dirty_circs();
  754. addressmap_clear_transient();
  755. time_of_last_signewnym = now;
  756. signewnym_is_pending = 0;
  757. }
  758. /** 1a. Every MIN_ONION_KEY_LIFETIME seconds, rotate the onion keys,
  759. * shut down and restart all cpuworkers, and update the directory if
  760. * necessary.
  761. */
  762. if (server_mode(options) &&
  763. get_onion_key_set_at()+MIN_ONION_KEY_LIFETIME < now) {
  764. log_info(LD_GENERAL,"Rotating onion key.");
  765. rotate_onion_key();
  766. cpuworkers_rotate();
  767. if (router_rebuild_descriptor(1)<0) {
  768. log_info(LD_CONFIG, "Couldn't rebuild router descriptor");
  769. }
  770. if (advertised_server_mode())
  771. router_upload_dir_desc_to_dirservers(0);
  772. }
  773. if (time_to_try_getting_descriptors < now) {
  774. /* XXXX Maybe we should do this every 10sec when not enough info,
  775. * and every 60sec when we have enough info -NM Great idea -RD */
  776. update_router_descriptor_downloads(now);
  777. update_extrainfo_downloads(now);
  778. if (options->UseBridges)
  779. fetch_bridge_descriptors(now);
  780. time_to_try_getting_descriptors = now + DESCRIPTOR_RETRY_INTERVAL;
  781. }
  782. if (time_to_reset_descriptor_failures < now) {
  783. router_reset_descriptor_download_failures();
  784. time_to_reset_descriptor_failures =
  785. now + DESCRIPTOR_FAILURE_RESET_INTERVAL;
  786. }
  787. /** 1b. Every MAX_SSL_KEY_LIFETIME seconds, we change our TLS context. */
  788. if (!last_rotated_certificate)
  789. last_rotated_certificate = now;
  790. if (last_rotated_certificate+MAX_SSL_KEY_LIFETIME < now) {
  791. log_info(LD_GENERAL,"Rotating tls context.");
  792. if (tor_tls_context_new(get_identity_key(), options->Nickname,
  793. MAX_SSL_KEY_LIFETIME) < 0) {
  794. log_warn(LD_BUG, "Error reinitializing TLS context");
  795. /* XXX is it a bug here, that we just keep going? */
  796. }
  797. last_rotated_certificate = now;
  798. /* XXXX We should rotate TLS connections as well; this code doesn't change
  799. * them at all. */
  800. }
  801. if (time_to_add_entropy == 0)
  802. time_to_add_entropy = now + ENTROPY_INTERVAL;
  803. if (time_to_add_entropy < now) {
  804. /* We already seeded once, so don't die on failure. */
  805. crypto_seed_rng();
  806. time_to_add_entropy = now + ENTROPY_INTERVAL;
  807. }
  808. /** 1c. If we have to change the accounting interval or record
  809. * bandwidth used in this accounting interval, do so. */
  810. if (accounting_is_enabled(options))
  811. accounting_run_housekeeping(now);
  812. if (now % 10 == 0 && (authdir_mode_tests_reachability(options)) &&
  813. !we_are_hibernating()) {
  814. /* try to determine reachability of the other Tor servers */
  815. dirserv_test_reachability(now, 0);
  816. }
  817. /** 1d. DOCDOC */
  818. if (time_to_downrate_stability < now)
  819. time_to_downrate_stability = rep_hist_downrate_old_runs(now);
  820. if (authdir_mode_tests_reachability(options)) {
  821. if (!time_to_save_stability)
  822. time_to_save_stability = now + SAVE_STABILITY_INTERVAL;
  823. if (time_to_save_stability < now) {
  824. if (rep_hist_record_mtbf_data()<0) {
  825. log_warn(LD_GENERAL, "Couldn't store mtbf data.");
  826. }
  827. time_to_save_stability = now + SAVE_STABILITY_INTERVAL;
  828. }
  829. }
  830. /** 2. Periodically, we consider getting a new directory, getting a
  831. * new running-routers list, and/or force-uploading our descriptor
  832. * (if we've passed our internal checks). */
  833. if (time_to_fetch_directory < now) {
  834. /* Only caches actually need to fetch directories now. */
  835. if (options->DirPort && !authdir_mode_v1(options)) {
  836. /* XXX020 actually, we should only do this if we want to advertise
  837. * our dirport. not simply if we configured one. -RD */
  838. if (any_trusted_dir_is_v1_authority() &&
  839. !should_delay_dir_fetches(options))
  840. directory_get_from_dirserver(DIR_PURPOSE_FETCH_DIR,
  841. ROUTER_PURPOSE_GENERAL, NULL, 1);
  842. }
  843. /** How often do we (as a cache) fetch a new V1 directory? */
  844. #define V1_DIR_FETCH_PERIOD (6*60*60)
  845. time_to_fetch_directory = now + V1_DIR_FETCH_PERIOD;
  846. }
  847. /* Caches need to fetch running_routers; directory clients don't. */
  848. if (options->DirPort && time_to_fetch_running_routers < now) {
  849. if (!authdir_mode_v1(options) && !should_delay_dir_fetches(options)) {
  850. directory_get_from_dirserver(DIR_PURPOSE_FETCH_RUNNING_LIST,
  851. ROUTER_PURPOSE_GENERAL, NULL, 1);
  852. }
  853. /** How often do we (as a cache) fetch a new V1 runningrouters document? */
  854. #ifdef FULL_V1_DIRECTORIES
  855. #define V1_RUNNINGROUTERS_FETCH_PERIOD (30*60)
  856. #else
  857. #define V1_RUNNINGROUTERS_FETCH_PERIOD (6*60*60)
  858. #endif
  859. time_to_fetch_running_routers = now + V1_RUNNINGROUTERS_FETCH_PERIOD;
  860. /* Also, take this chance to remove old information from rephist
  861. * and the rend cache. */
  862. rep_history_clean(now - options->RephistTrackTime);
  863. rend_cache_clean();
  864. /* XXX020 we only clean this stuff if DirPort is set?! -RD */
  865. }
  866. /* 2b. Once per minute, regenerate and upload the descriptor if the old
  867. * one is inaccurate. */
  868. if (time_to_check_descriptor < now) {
  869. static int dirport_reachability_count = 0;
  870. time_to_check_descriptor = now + CHECK_DESCRIPTOR_INTERVAL;
  871. check_descriptor_bandwidth_changed(now);
  872. if (time_to_check_ipaddress < now) {
  873. time_to_check_ipaddress = now + CHECK_IPADDRESS_INTERVAL;
  874. check_descriptor_ipaddress_changed(now);
  875. }
  876. mark_my_descriptor_dirty_if_older_than(
  877. now - FORCE_REGENERATE_DESCRIPTOR_INTERVAL);
  878. consider_publishable_server(0);
  879. /* also, check religiously for reachability, if it's within the first
  880. * 20 minutes of our uptime. */
  881. if (server_mode(options) &&
  882. (has_completed_circuit || !any_predicted_circuits(now)) &&
  883. stats_n_seconds_working < TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT &&
  884. !we_are_hibernating()) {
  885. consider_testing_reachability(1, dirport_reachability_count==0);
  886. if (++dirport_reachability_count > 5)
  887. dirport_reachability_count = 0;
  888. }
  889. /* If any networkstatus documents are no longer recent, we need to
  890. * update all the descriptors' running status. */
  891. /* purge obsolete entries */
  892. routerlist_remove_old_routers();
  893. networkstatus_list_clean(now);
  894. networkstatus_list_update_recent(now);
  895. routers_update_all_from_networkstatus(now);
  896. /* Also, once per minute, check whether we want to download any
  897. * networkstatus documents.
  898. */
  899. update_networkstatus_downloads(now);
  900. }
  901. /** 2c. Let directory voting happen. */
  902. if (authdir_mode_v3(options))
  903. dirvote_act(now);
  904. /** 3a. Every second, we examine pending circuits and prune the
  905. * ones which have been pending for more than a few seconds.
  906. * We do this before step 4, so it can try building more if
  907. * it's not comfortable with the number of available circuits.
  908. */
  909. circuit_expire_building(now);
  910. /** 3b. Also look at pending streams and prune the ones that 'began'
  911. * a long time ago but haven't gotten a 'connected' yet.
  912. * Do this before step 4, so we can put them back into pending
  913. * state to be picked up by the new circuit.
  914. */
  915. connection_ap_expire_beginning();
  916. /** 3c. And expire connections that we've held open for too long.
  917. */
  918. connection_expire_held_open();
  919. /** 3d. And every 60 seconds, we relaunch listeners if any died. */
  920. if (!we_are_hibernating() && time_to_check_listeners < now) {
  921. /* 0 means "only launch the ones that died." */
  922. retry_all_listeners(NULL, NULL);
  923. time_to_check_listeners = now+60;
  924. }
  925. /** 4. Every second, we try a new circuit if there are no valid
  926. * circuits. Every NewCircuitPeriod seconds, we expire circuits
  927. * that became dirty more than MaxCircuitDirtiness seconds ago,
  928. * and we make a new circ if there are no clean circuits.
  929. */
  930. have_dir_info = router_have_minimum_dir_info();
  931. if (have_dir_info && !we_are_hibernating())
  932. circuit_build_needed_circs(now);
  933. /** 5. We do housekeeping for each connection... */
  934. for (i=0;i<smartlist_len(connection_array);i++) {
  935. run_connection_housekeeping(i, now);
  936. }
  937. if (time_to_shrink_memory < now) {
  938. SMARTLIST_FOREACH(connection_array, connection_t *, conn, {
  939. if (conn->outbuf)
  940. buf_shrink(conn->outbuf);
  941. if (conn->inbuf)
  942. buf_shrink(conn->inbuf);
  943. });
  944. clean_cell_pool();
  945. buf_shrink_freelists(0);
  946. time_to_shrink_memory = now + MEM_SHRINK_INTERVAL;
  947. }
  948. /** 6. And remove any marked circuits... */
  949. circuit_close_all_marked();
  950. /** 7. And upload service descriptors if necessary. */
  951. if (has_completed_circuit && !we_are_hibernating())
  952. rend_consider_services_upload(now);
  953. /** 8. and blow away any connections that need to die. have to do this now,
  954. * because if we marked a conn for close and left its socket -1, then
  955. * we'll pass it to poll/select and bad things will happen.
  956. */
  957. close_closeable_connections();
  958. /** 8b. And if anything in our state is ready to get flushed to disk, we
  959. * flush it. */
  960. or_state_save(now);
  961. /** 9. and if we're a server, check whether our DNS is telling stories to
  962. * us. */
  963. if (server_mode(options) && time_to_check_for_correct_dns < now) {
  964. if (!time_to_check_for_correct_dns) {
  965. time_to_check_for_correct_dns = now + 60 + crypto_rand_int(120);
  966. } else {
  967. dns_launch_correctness_checks();
  968. time_to_check_for_correct_dns = now + 12*3600 +
  969. crypto_rand_int(12*3600);
  970. }
  971. }
  972. /** 10. write hidden service usage statistic to disk */
  973. if (options->HSAuthorityRecordStats && time_to_write_hs_statistics < now) {
  974. hs_usage_write_statistics_to_file(now);
  975. time_to_write_hs_statistics = now+WRITE_HSUSAGE_INTERVAL;
  976. }
  977. }
  978. /** Libevent timer: used to invoke second_elapsed_callback() once per
  979. * second. */
  980. static struct event *timeout_event = NULL;
  981. /** Number of libevent errors in the last second: we die if we get too many. */
  982. static int n_libevent_errors = 0;
  983. /** Libevent callback: invoked once every second. */
  984. static void
  985. second_elapsed_callback(int fd, short event, void *args)
  986. {
  987. /* XXXX This could be sensibly refactored into multiple callbacks, and we
  988. * could use libevent's timers for this rather than checking the current
  989. * time against a bunch of timeouts every second. */
  990. static struct timeval one_second;
  991. static long current_second = 0;
  992. struct timeval now;
  993. size_t bytes_written;
  994. size_t bytes_read;
  995. int seconds_elapsed;
  996. or_options_t *options = get_options();
  997. (void)fd;
  998. (void)event;
  999. (void)args;
  1000. if (!timeout_event) {
  1001. timeout_event = tor_malloc_zero(sizeof(struct event));
  1002. evtimer_set(timeout_event, second_elapsed_callback, NULL);
  1003. one_second.tv_sec = 1;
  1004. one_second.tv_usec = 0;
  1005. }
  1006. n_libevent_errors = 0;
  1007. /* log_fn(LOG_NOTICE, "Tick."); */
  1008. tor_gettimeofday(&now);
  1009. /* the second has rolled over. check more stuff. */
  1010. bytes_written = stats_prev_global_write_bucket - global_write_bucket;
  1011. bytes_read = stats_prev_global_read_bucket - global_read_bucket;
  1012. seconds_elapsed = current_second ? (now.tv_sec - current_second) : 0;
  1013. stats_n_bytes_read += bytes_read;
  1014. stats_n_bytes_written += bytes_written;
  1015. if (accounting_is_enabled(options) && seconds_elapsed >= 0)
  1016. accounting_add_bytes(bytes_read, bytes_written, seconds_elapsed);
  1017. control_event_bandwidth_used((uint32_t)bytes_read,(uint32_t)bytes_written);
  1018. control_event_stream_bandwidth_used();
  1019. if (seconds_elapsed > 0)
  1020. connection_bucket_refill(seconds_elapsed, now.tv_sec);
  1021. stats_prev_global_read_bucket = global_read_bucket;
  1022. stats_prev_global_write_bucket = global_write_bucket;
  1023. if (server_mode(options) &&
  1024. !we_are_hibernating() &&
  1025. seconds_elapsed > 0 &&
  1026. stats_n_seconds_working / TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT !=
  1027. (stats_n_seconds_working+seconds_elapsed) /
  1028. TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT) {
  1029. /* every 20 minutes, check and complain if necessary */
  1030. routerinfo_t *me = router_get_my_routerinfo();
  1031. if (me && !check_whether_orport_reachable())
  1032. log_warn(LD_CONFIG,"Your server (%s:%d) has not managed to confirm that "
  1033. "its ORPort is reachable. Please check your firewalls, ports, "
  1034. "address, /etc/hosts file, etc.",
  1035. me->address, me->or_port);
  1036. if (me && !check_whether_dirport_reachable())
  1037. log_warn(LD_CONFIG,
  1038. "Your server (%s:%d) has not managed to confirm that its "
  1039. "DirPort is reachable. Please check your firewalls, ports, "
  1040. "address, /etc/hosts file, etc.",
  1041. me->address, me->dir_port);
  1042. }
  1043. /** If more than this many seconds have elapsed, probably the clock
  1044. * jumped: doesn't count. */
  1045. #define NUM_JUMPED_SECONDS_BEFORE_WARN 100
  1046. if (seconds_elapsed < -NUM_JUMPED_SECONDS_BEFORE_WARN ||
  1047. seconds_elapsed >= NUM_JUMPED_SECONDS_BEFORE_WARN) {
  1048. circuit_note_clock_jumped(seconds_elapsed);
  1049. /* XXX if the time jumps *back* many months, do our events in
  1050. * run_scheduled_events() recover? I don't think they do. -RD */
  1051. } else if (seconds_elapsed > 0)
  1052. stats_n_seconds_working += seconds_elapsed;
  1053. run_scheduled_events(now.tv_sec);
  1054. current_second = now.tv_sec; /* remember which second it is, for next time */
  1055. #if 0
  1056. if (current_second % 300 == 0) {
  1057. rep_history_clean(current_second - options->RephistTrackTime);
  1058. dumpmemusage(get_min_log_level()<LOG_INFO ?
  1059. get_min_log_level() : LOG_INFO);
  1060. }
  1061. #endif
  1062. if (evtimer_add(timeout_event, &one_second))
  1063. log_err(LD_NET,
  1064. "Error from libevent when setting one-second timeout event");
  1065. }
  1066. #ifndef MS_WINDOWS
  1067. /** Called when a possibly ignorable libevent error occurs; ensures that we
  1068. * don't get into an infinite loop by ignoring too many errors from
  1069. * libevent. */
  1070. static int
  1071. got_libevent_error(void)
  1072. {
  1073. if (++n_libevent_errors > 8) {
  1074. log_err(LD_NET, "Too many libevent errors in one second; dying");
  1075. return -1;
  1076. }
  1077. return 0;
  1078. }
  1079. #endif
  1080. #define UPTIME_CUTOFF_FOR_NEW_BANDWIDTH_TEST (6*60*60)
  1081. /** Called when our IP address seems to have changed. <b>at_interface</b>
  1082. * should be true if we detected a change in our interface, and false if we
  1083. * detected a change in our published address. */
  1084. void
  1085. ip_address_changed(int at_interface)
  1086. {
  1087. int server = server_mode(get_options());
  1088. if (at_interface) {
  1089. if (! server) {
  1090. /* Okay, change our keys. */
  1091. init_keys();
  1092. }
  1093. } else {
  1094. if (server) {
  1095. if (stats_n_seconds_working > UPTIME_CUTOFF_FOR_NEW_BANDWIDTH_TEST)
  1096. reset_bandwidth_test();
  1097. stats_n_seconds_working = 0;
  1098. router_reset_reachability();
  1099. mark_my_descriptor_dirty();
  1100. }
  1101. }
  1102. dns_servers_relaunch_checks();
  1103. }
  1104. /** Forget what we've learned about the correctness of our DNS servers, and
  1105. * start learning again. */
  1106. void
  1107. dns_servers_relaunch_checks(void)
  1108. {
  1109. if (server_mode(get_options())) {
  1110. dns_reset_correctness_checks();
  1111. time_to_check_for_correct_dns = 0;
  1112. }
  1113. }
  1114. /** Called when we get a SIGHUP: reload configuration files and keys,
  1115. * retry all connections, re-upload all descriptors, and so on. */
  1116. static int
  1117. do_hup(void)
  1118. {
  1119. or_options_t *options = get_options();
  1120. #ifdef USE_DMALLOC
  1121. dmalloc_log_stats();
  1122. dmalloc_log_changed(0, 1, 0, 0);
  1123. #endif
  1124. log_notice(LD_GENERAL,"Received reload signal (hup). Reloading config.");
  1125. if (accounting_is_enabled(options))
  1126. accounting_record_bandwidth_usage(time(NULL), get_or_state());
  1127. router_reset_warnings();
  1128. routerlist_reset_warnings();
  1129. addressmap_clear_transient();
  1130. /* first, reload config variables, in case they've changed */
  1131. /* no need to provide argc/v, they've been cached inside init_from_config */
  1132. if (options_init_from_torrc(0, NULL) < 0) {
  1133. log_err(LD_CONFIG,"Reading config failed--see warnings above. "
  1134. "For usage, try -h.");
  1135. return -1;
  1136. }
  1137. options = get_options(); /* they have changed now */
  1138. if (authdir_mode_handles_descs(options)) {
  1139. /* reload the approved-routers file */
  1140. if (dirserv_load_fingerprint_file() < 0) {
  1141. /* warnings are logged from dirserv_load_fingerprint_file() directly */
  1142. log_info(LD_GENERAL, "Error reloading fingerprints. "
  1143. "Continuing with old list.");
  1144. }
  1145. }
  1146. /* Rotate away from the old dirty circuits. This has to be done
  1147. * after we've read the new options, but before we start using
  1148. * circuits for directory fetches. */
  1149. circuit_expire_all_dirty_circs();
  1150. /* retry appropriate downloads */
  1151. router_reset_status_download_failures();
  1152. router_reset_descriptor_download_failures();
  1153. update_networkstatus_downloads(time(NULL));
  1154. /* We'll retry routerstatus downloads in about 10 seconds; no need to
  1155. * force a retry there. */
  1156. if (server_mode(options)) {
  1157. // const char *descriptor;
  1158. mark_my_descriptor_dirty();
  1159. /* Restart cpuworker and dnsworker processes, so they get up-to-date
  1160. * configuration options. */
  1161. cpuworkers_rotate();
  1162. dns_reset();
  1163. }
  1164. return 0;
  1165. }
  1166. /** Tor main loop. */
  1167. static int
  1168. do_main_loop(void)
  1169. {
  1170. int loop_result;
  1171. time_t now;
  1172. /* initialize dns resolve map, spawn workers if needed */
  1173. if (dns_init() < 0) {
  1174. log_err(LD_GENERAL,"Error initializing dns subsystem; exiting");
  1175. return -1;
  1176. }
  1177. handle_signals(1);
  1178. /* load the private keys, if we're supposed to have them, and set up the
  1179. * TLS context. */
  1180. if (! identity_key_is_set()) {
  1181. if (init_keys() < 0) {
  1182. log_err(LD_BUG,"Error initializing keys; exiting");
  1183. return -1;
  1184. }
  1185. }
  1186. /* Set up the packed_cell_t memory pool. */
  1187. init_cell_pool();
  1188. /* Set up our buckets */
  1189. connection_bucket_init();
  1190. stats_prev_global_read_bucket = global_read_bucket;
  1191. stats_prev_global_write_bucket = global_write_bucket;
  1192. /* load the routers file, or assign the defaults. */
  1193. if (router_reload_router_list()) {
  1194. return -1;
  1195. }
  1196. /* load the networkstatuses. (This launches a download for new routers as
  1197. * appropriate.)
  1198. */
  1199. if (router_reload_networkstatus()) {
  1200. return -1;
  1201. }
  1202. if (router_reload_consensus_networkstatus()) {
  1203. return -1;
  1204. }
  1205. now = time(NULL);
  1206. directory_info_has_arrived(now, 1);
  1207. if (authdir_mode_tests_reachability(get_options())) {
  1208. /* the directory is already here, run startup things */
  1209. dirserv_test_reachability(now, 1);
  1210. }
  1211. if (server_mode(get_options())) {
  1212. /* launch cpuworkers. Need to do this *after* we've read the onion key. */
  1213. cpu_init();
  1214. }
  1215. /* set up once-a-second callback. */
  1216. second_elapsed_callback(0,0,NULL);
  1217. for (;;) {
  1218. if (nt_service_is_stopping())
  1219. return 0;
  1220. #ifndef MS_WINDOWS
  1221. /* Make it easier to tell whether libevent failure is our fault or not. */
  1222. errno = 0;
  1223. #endif
  1224. /* All active linked conns should get their read events activated. */
  1225. SMARTLIST_FOREACH(active_linked_connection_lst, connection_t *, conn,
  1226. event_active(conn->read_event, EV_READ, 1));
  1227. called_loop_once = smartlist_len(active_linked_connection_lst) ? 1 : 0;
  1228. /* poll until we have an event, or the second ends, or until we have
  1229. * some active linked connections to trigger events for. */
  1230. loop_result = event_loop(called_loop_once ? EVLOOP_ONCE : 0);
  1231. /* let catch() handle things like ^c, and otherwise don't worry about it */
  1232. if (loop_result < 0) {
  1233. int e = tor_socket_errno(-1);
  1234. /* let the program survive things like ^z */
  1235. if (e != EINTR && !ERRNO_IS_EINPROGRESS(e)) {
  1236. #ifdef HAVE_EVENT_GET_METHOD
  1237. log_err(LD_NET,"libevent call with %s failed: %s [%d]",
  1238. event_get_method(), tor_socket_strerror(e), e);
  1239. #else
  1240. log_err(LD_NET,"libevent call failed: %s [%d]",
  1241. tor_socket_strerror(e), e);
  1242. #endif
  1243. return -1;
  1244. #ifndef MS_WINDOWS
  1245. } else if (e == EINVAL) {
  1246. log_warn(LD_NET, "EINVAL from libevent: should you upgrade libevent?");
  1247. if (got_libevent_error())
  1248. return -1;
  1249. #endif
  1250. } else {
  1251. if (ERRNO_IS_EINPROGRESS(e))
  1252. log_warn(LD_BUG,
  1253. "libevent call returned EINPROGRESS? Please report.");
  1254. log_debug(LD_NET,"libevent call interrupted.");
  1255. /* You can't trust the results of this poll(). Go back to the
  1256. * top of the big for loop. */
  1257. continue;
  1258. }
  1259. }
  1260. /* refilling buckets and sending cells happens at the beginning of the
  1261. * next iteration of the loop, inside prepare_for_poll()
  1262. * XXXX020 No longer so; fix comment.
  1263. */
  1264. }
  1265. }
  1266. /** Used to implement the SIGNAL control command: if we accept
  1267. * <b>the_signal</b> as a remote pseudo-signal, act on it. */
  1268. /* We don't re-use catch() here because:
  1269. * 1. We handle a different set of signals than those allowed in catch.
  1270. * 2. Platforms without signal() are unlikely to define SIGfoo.
  1271. * 3. The control spec is defined to use fixed numeric signal values
  1272. * which just happen to match the unix values.
  1273. */
  1274. void
  1275. control_signal_act(int the_signal)
  1276. {
  1277. switch (the_signal)
  1278. {
  1279. case 1:
  1280. signal_callback(0,0,(void*)(uintptr_t)SIGHUP);
  1281. break;
  1282. case 2:
  1283. signal_callback(0,0,(void*)(uintptr_t)SIGINT);
  1284. break;
  1285. case 10:
  1286. signal_callback(0,0,(void*)(uintptr_t)SIGUSR1);
  1287. break;
  1288. case 12:
  1289. signal_callback(0,0,(void*)(uintptr_t)SIGUSR2);
  1290. break;
  1291. case 15:
  1292. signal_callback(0,0,(void*)(uintptr_t)SIGTERM);
  1293. break;
  1294. case SIGNEWNYM:
  1295. signal_callback(0,0,(void*)(uintptr_t)SIGNEWNYM);
  1296. break;
  1297. case SIGCLEARDNSCACHE:
  1298. signal_callback(0,0,(void*)(uintptr_t)SIGCLEARDNSCACHE);
  1299. break;
  1300. default:
  1301. log_warn(LD_BUG, "Unrecognized signal number %d.", the_signal);
  1302. break;
  1303. }
  1304. }
  1305. /** Libevent callback: invoked when we get a signal.
  1306. */
  1307. static void
  1308. signal_callback(int fd, short events, void *arg)
  1309. {
  1310. uintptr_t sig = (uintptr_t)arg;
  1311. (void)fd;
  1312. (void)events;
  1313. switch (sig)
  1314. {
  1315. case SIGTERM:
  1316. log_notice(LD_GENERAL,"Catching signal TERM, exiting cleanly.");
  1317. tor_cleanup();
  1318. exit(0);
  1319. break;
  1320. case SIGINT:
  1321. if (!server_mode(get_options())) { /* do it now */
  1322. log_notice(LD_GENERAL,"Interrupt: exiting cleanly.");
  1323. tor_cleanup();
  1324. exit(0);
  1325. }
  1326. hibernate_begin_shutdown();
  1327. break;
  1328. #ifdef SIGPIPE
  1329. case SIGPIPE:
  1330. log_debug(LD_GENERAL,"Caught sigpipe. Ignoring.");
  1331. break;
  1332. #endif
  1333. case SIGUSR1:
  1334. /* prefer to log it at INFO, but make sure we always see it */
  1335. dumpstats(get_min_log_level()<LOG_INFO ? get_min_log_level() : LOG_INFO);
  1336. break;
  1337. case SIGUSR2:
  1338. switch_logs_debug();
  1339. log_debug(LD_GENERAL,"Caught USR2, going to loglevel debug. "
  1340. "Send HUP to change back.");
  1341. break;
  1342. case SIGHUP:
  1343. if (do_hup() < 0) {
  1344. log_warn(LD_CONFIG,"Restart failed (config error?). Exiting.");
  1345. tor_cleanup();
  1346. exit(1);
  1347. }
  1348. break;
  1349. #ifdef SIGCHLD
  1350. case SIGCHLD:
  1351. while (waitpid(-1,NULL,WNOHANG) > 0) ; /* keep reaping until no more
  1352. zombies */
  1353. break;
  1354. #endif
  1355. case SIGNEWNYM: {
  1356. time_t now = time(NULL);
  1357. if (time_of_last_signewnym + MAX_SIGNEWNYM_RATE > now) {
  1358. signewnym_is_pending = 1;
  1359. log(LOG_NOTICE, LD_CONTROL,
  1360. "Rate limiting NEWNYM request: delaying by %d second(s)",
  1361. (int)(MAX_SIGNEWNYM_RATE+time_of_last_signewnym-now));
  1362. } else {
  1363. /* XXX020 refactor someday: these two calls are in
  1364. * run_scheduled_events() above too, and they should be in just
  1365. * one place. */
  1366. circuit_expire_all_dirty_circs();
  1367. addressmap_clear_transient();
  1368. time_of_last_signewnym = now;
  1369. }
  1370. break;
  1371. }
  1372. case SIGCLEARDNSCACHE:
  1373. addressmap_clear_transient();
  1374. break;
  1375. }
  1376. }
  1377. extern uint64_t rephist_total_alloc;
  1378. extern uint32_t rephist_total_num;
  1379. /**
  1380. * Write current memory usage information to the log.
  1381. */
  1382. static void
  1383. dumpmemusage(int severity)
  1384. {
  1385. connection_dump_buffer_mem_stats(severity);
  1386. log(severity, LD_GENERAL, "In rephist: "U64_FORMAT" used by %d Tors.",
  1387. U64_PRINTF_ARG(rephist_total_alloc), rephist_total_num);
  1388. dump_routerlist_mem_usage(severity);
  1389. dump_cell_pool_usage(severity);
  1390. buf_dump_freelist_sizes(severity);
  1391. tor_log_mallinfo(severity);
  1392. }
  1393. /** Write all statistics to the log, with log level 'severity'. Called
  1394. * in response to a SIGUSR1. */
  1395. static void
  1396. dumpstats(int severity)
  1397. {
  1398. time_t now = time(NULL);
  1399. time_t elapsed;
  1400. log(severity, LD_GENERAL, "Dumping stats:");
  1401. SMARTLIST_FOREACH(connection_array, connection_t *, conn,
  1402. {
  1403. int i = conn_sl_idx;
  1404. log(severity, LD_GENERAL,
  1405. "Conn %d (socket %d) type %d (%s), state %d (%s), created %d secs ago",
  1406. i, conn->s, conn->type, conn_type_to_string(conn->type),
  1407. conn->state, conn_state_to_string(conn->type, conn->state),
  1408. (int)(now - conn->timestamp_created));
  1409. if (!connection_is_listener(conn)) {
  1410. log(severity,LD_GENERAL,
  1411. "Conn %d is to %s:%d.", i,
  1412. safe_str(conn->address), conn->port);
  1413. log(severity,LD_GENERAL,
  1414. "Conn %d: %d bytes waiting on inbuf (len %d, last read %d secs ago)",
  1415. i,
  1416. (int)buf_datalen(conn->inbuf),
  1417. (int)buf_capacity(conn->inbuf),
  1418. (int)(now - conn->timestamp_lastread));
  1419. log(severity,LD_GENERAL,
  1420. "Conn %d: %d bytes waiting on outbuf "
  1421. "(len %d, last written %d secs ago)",i,
  1422. (int)buf_datalen(conn->outbuf),
  1423. (int)buf_capacity(conn->outbuf),
  1424. (int)(now - conn->timestamp_lastwritten));
  1425. }
  1426. circuit_dump_by_conn(conn, severity); /* dump info about all the circuits
  1427. * using this conn */
  1428. });
  1429. log(severity, LD_NET,
  1430. "Cells processed: "U64_FORMAT" padding\n"
  1431. " "U64_FORMAT" create\n"
  1432. " "U64_FORMAT" created\n"
  1433. " "U64_FORMAT" relay\n"
  1434. " ("U64_FORMAT" relayed)\n"
  1435. " ("U64_FORMAT" delivered)\n"
  1436. " "U64_FORMAT" destroy",
  1437. U64_PRINTF_ARG(stats_n_padding_cells_processed),
  1438. U64_PRINTF_ARG(stats_n_create_cells_processed),
  1439. U64_PRINTF_ARG(stats_n_created_cells_processed),
  1440. U64_PRINTF_ARG(stats_n_relay_cells_processed),
  1441. U64_PRINTF_ARG(stats_n_relay_cells_relayed),
  1442. U64_PRINTF_ARG(stats_n_relay_cells_delivered),
  1443. U64_PRINTF_ARG(stats_n_destroy_cells_processed));
  1444. if (stats_n_data_cells_packaged)
  1445. log(severity,LD_NET,"Average packaged cell fullness: %2.3f%%",
  1446. 100*(U64_TO_DBL(stats_n_data_bytes_packaged) /
  1447. U64_TO_DBL(stats_n_data_cells_packaged*RELAY_PAYLOAD_SIZE)) );
  1448. if (stats_n_data_cells_received)
  1449. log(severity,LD_NET,"Average delivered cell fullness: %2.3f%%",
  1450. 100*(U64_TO_DBL(stats_n_data_bytes_received) /
  1451. U64_TO_DBL(stats_n_data_cells_received*RELAY_PAYLOAD_SIZE)) );
  1452. if (now - time_of_process_start >= 0)
  1453. elapsed = now - time_of_process_start;
  1454. else
  1455. elapsed = 0;
  1456. if (elapsed) {
  1457. log(severity, LD_NET,
  1458. "Average bandwidth: "U64_FORMAT"/%d = %d bytes/sec reading",
  1459. U64_PRINTF_ARG(stats_n_bytes_read),
  1460. (int)elapsed,
  1461. (int) (stats_n_bytes_read/elapsed));
  1462. log(severity, LD_NET,
  1463. "Average bandwidth: "U64_FORMAT"/%d = %d bytes/sec writing",
  1464. U64_PRINTF_ARG(stats_n_bytes_written),
  1465. (int)elapsed,
  1466. (int) (stats_n_bytes_written/elapsed));
  1467. }
  1468. log(severity, LD_NET, "--------------- Dumping memory information:");
  1469. dumpmemusage(severity);
  1470. rep_hist_dump_stats(now,severity);
  1471. rend_service_dump_stats(severity);
  1472. dump_pk_ops(severity);
  1473. dump_distinct_digest_count(severity);
  1474. }
  1475. /** Called by exit() as we shut down the process.
  1476. */
  1477. static void
  1478. exit_function(void)
  1479. {
  1480. /* NOTE: If we ever daemonize, this gets called immediately. That's
  1481. * okay for now, because we only use this on Windows. */
  1482. #ifdef MS_WINDOWS
  1483. WSACleanup();
  1484. #endif
  1485. }
  1486. /** Set up the signal handlers for either parent or child. */
  1487. void
  1488. handle_signals(int is_parent)
  1489. {
  1490. #ifndef MS_WINDOWS /* do signal stuff only on unix */
  1491. int i;
  1492. static int signals[] = {
  1493. SIGINT, /* do a controlled slow shutdown */
  1494. SIGTERM, /* to terminate now */
  1495. SIGPIPE, /* otherwise sigpipe kills us */
  1496. SIGUSR1, /* dump stats */
  1497. SIGUSR2, /* go to loglevel debug */
  1498. SIGHUP, /* to reload config, retry conns, etc */
  1499. #ifdef SIGXFSZ
  1500. SIGXFSZ, /* handle file-too-big resource exhaustion */
  1501. #endif
  1502. SIGCHLD, /* handle dns/cpu workers that exit */
  1503. -1 };
  1504. static struct event signal_events[16]; /* bigger than it has to be. */
  1505. if (is_parent) {
  1506. for (i = 0; signals[i] >= 0; ++i) {
  1507. signal_set(&signal_events[i], signals[i], signal_callback,
  1508. (void*)(uintptr_t)signals[i]);
  1509. if (signal_add(&signal_events[i], NULL))
  1510. log_warn(LD_BUG, "Error from libevent when adding event for signal %d",
  1511. signals[i]);
  1512. }
  1513. } else {
  1514. struct sigaction action;
  1515. action.sa_flags = 0;
  1516. sigemptyset(&action.sa_mask);
  1517. action.sa_handler = SIG_IGN;
  1518. sigaction(SIGINT, &action, NULL);
  1519. sigaction(SIGTERM, &action, NULL);
  1520. sigaction(SIGPIPE, &action, NULL);
  1521. sigaction(SIGUSR1, &action, NULL);
  1522. sigaction(SIGUSR2, &action, NULL);
  1523. sigaction(SIGHUP, &action, NULL);
  1524. #ifdef SIGXFSZ
  1525. sigaction(SIGXFSZ, &action, NULL);
  1526. #endif
  1527. }
  1528. #else /* MS windows */
  1529. (void)is_parent;
  1530. #endif /* signal stuff */
  1531. }
  1532. /** Main entry point for the Tor command-line client.
  1533. */
  1534. static int
  1535. tor_init(int argc, char *argv[])
  1536. {
  1537. char buf[256];
  1538. time_of_process_start = time(NULL);
  1539. if (!connection_array)
  1540. connection_array = smartlist_create();
  1541. if (!closeable_connection_lst)
  1542. closeable_connection_lst = smartlist_create();
  1543. if (!active_linked_connection_lst)
  1544. active_linked_connection_lst = smartlist_create();
  1545. /* Have the log set up with our application name. */
  1546. tor_snprintf(buf, sizeof(buf), "Tor %s", get_version());
  1547. log_set_application_name(buf);
  1548. /* Initialize threading. */
  1549. tor_threads_init();
  1550. /* Initialize the history structures. */
  1551. rep_hist_init();
  1552. /* Initialize the service cache. */
  1553. rend_cache_init();
  1554. addressmap_init(); /* Init the client dns cache. Do it always, since it's
  1555. * cheap. */
  1556. /* give it somewhere to log to initially */
  1557. add_temp_log();
  1558. log(LOG_NOTICE, LD_GENERAL, "Tor v%s. This is experimental software. "
  1559. "Do not rely on it for strong anonymity. (Running on %s)",get_version(),
  1560. get_uname());
  1561. if (network_init()<0) {
  1562. log_err(LD_BUG,"Error initializing network; exiting.");
  1563. return -1;
  1564. }
  1565. atexit(exit_function);
  1566. if (options_init_from_torrc(argc,argv) < 0) {
  1567. log_err(LD_CONFIG,"Reading config failed--see warnings above.");
  1568. return -1;
  1569. }
  1570. #ifndef MS_WINDOWS
  1571. if (geteuid()==0)
  1572. log_warn(LD_GENERAL,"You are running Tor as root. You don't need to, "
  1573. "and you probably shouldn't.");
  1574. #endif
  1575. crypto_global_init(get_options()->HardwareAccel);
  1576. if (crypto_seed_rng()) {
  1577. log_err(LD_BUG, "Unable to seed random number generator. Exiting.");
  1578. return -1;
  1579. }
  1580. return 0;
  1581. }
  1582. /** Free all memory that we might have allocated somewhere.
  1583. * If <b>postfork</b>, we are a worker process and we want to free
  1584. * only the parts of memory that we won't touch. If !<b>postfork</b>,
  1585. * Tor is shutting down and we should free everything.
  1586. *
  1587. * Helps us find the real leaks with dmalloc and the like. Also valgrind
  1588. * should then report 0 reachable in its leak report (in an ideal world --
  1589. * in practice libevent, ssl, libc etc never quite free everything). */
  1590. void
  1591. tor_free_all(int postfork)
  1592. {
  1593. if (!postfork) {
  1594. evdns_shutdown(1);
  1595. }
  1596. dirvote_free_all();
  1597. routerlist_free_all();
  1598. addressmap_free_all();
  1599. set_exit_redirects(NULL); /* free the registered exit redirects */
  1600. dirserv_free_all();
  1601. rend_service_free_all();
  1602. rend_cache_free_all();
  1603. rep_hist_free_all();
  1604. hs_usage_free_all();
  1605. dns_free_all();
  1606. clear_pending_onions();
  1607. circuit_free_all();
  1608. entry_guards_free_all();
  1609. connection_free_all();
  1610. buf_shrink_freelists(1);
  1611. policies_free_all();
  1612. if (!postfork) {
  1613. config_free_all();
  1614. router_free_all();
  1615. }
  1616. free_cell_pool();
  1617. tor_tls_free_all();
  1618. /* stuff in main.c */
  1619. smartlist_free(connection_array);
  1620. smartlist_free(closeable_connection_lst);
  1621. smartlist_free(active_linked_connection_lst);
  1622. tor_free(timeout_event);
  1623. /* Stuff in util.c */
  1624. if (!postfork) {
  1625. escaped(NULL);
  1626. esc_router_info(NULL);
  1627. logs_free_all(); /* free log strings. do this last so logs keep working. */
  1628. }
  1629. }
  1630. /** Do whatever cleanup is necessary before shutting Tor down. */
  1631. void
  1632. tor_cleanup(void)
  1633. {
  1634. or_options_t *options = get_options();
  1635. /* Remove our pid file. We don't care if there was an error when we
  1636. * unlink, nothing we could do about it anyways. */
  1637. if (options->command == CMD_RUN_TOR) {
  1638. if (options->PidFile)
  1639. unlink(options->PidFile);
  1640. if (accounting_is_enabled(options))
  1641. accounting_record_bandwidth_usage(time(NULL), get_or_state());
  1642. or_state_mark_dirty(get_or_state(), 0); /* force an immediate save. */
  1643. or_state_save(time(NULL));
  1644. if (authdir_mode_tests_reachability(options))
  1645. rep_hist_record_mtbf_data();
  1646. }
  1647. #ifdef USE_DMALLOC
  1648. dmalloc_log_stats();
  1649. #endif
  1650. tor_free_all(0); /* We could move tor_free_all back into the ifdef below
  1651. later, if it makes shutdown unacceptably slow. But for
  1652. now, leave it here: it's helped us catch bugs in the
  1653. past. */
  1654. crypto_global_cleanup();
  1655. #ifdef USE_DMALLOC
  1656. dmalloc_log_unfreed();
  1657. dmalloc_shutdown();
  1658. #endif
  1659. }
  1660. /** Read/create keys as needed, and echo our fingerprint to stdout. */
  1661. static int
  1662. do_list_fingerprint(void)
  1663. {
  1664. char buf[FINGERPRINT_LEN+1];
  1665. crypto_pk_env_t *k;
  1666. const char *nickname = get_options()->Nickname;
  1667. if (!server_mode(get_options())) {
  1668. log_err(LD_GENERAL,
  1669. "Clients don't have long-term identity keys. Exiting.\n");
  1670. return -1;
  1671. }
  1672. tor_assert(nickname);
  1673. if (init_keys() < 0) {
  1674. log_err(LD_BUG,"Error initializing keys; can't display fingerprint");
  1675. return -1;
  1676. }
  1677. if (!(k = get_identity_key())) {
  1678. log_err(LD_GENERAL,"Error: missing identity key.");
  1679. return -1;
  1680. }
  1681. if (crypto_pk_get_fingerprint(k, buf, 1)<0) {
  1682. log_err(LD_BUG, "Error computing fingerprint");
  1683. return -1;
  1684. }
  1685. printf("%s %s\n", nickname, buf);
  1686. return 0;
  1687. }
  1688. /** Entry point for password hashing: take the desired password from
  1689. * the command line, and print its salted hash to stdout. **/
  1690. static void
  1691. do_hash_password(void)
  1692. {
  1693. char output[256];
  1694. char key[S2K_SPECIFIER_LEN+DIGEST_LEN];
  1695. crypto_rand(key, S2K_SPECIFIER_LEN-1);
  1696. key[S2K_SPECIFIER_LEN-1] = (uint8_t)96; /* Hash 64 K of data. */
  1697. secret_to_key(key+S2K_SPECIFIER_LEN, DIGEST_LEN,
  1698. get_options()->command_arg, strlen(get_options()->command_arg),
  1699. key);
  1700. base16_encode(output, sizeof(output), key, sizeof(key));
  1701. printf("16:%s\n",output);
  1702. }
  1703. #ifdef USE_DMALLOC
  1704. #include <openssl/crypto.h>
  1705. static void
  1706. _tor_dmalloc_free(void *p)
  1707. {
  1708. tor_free(p);
  1709. }
  1710. #endif
  1711. /** Main entry point for the Tor process. Called from main(). */
  1712. /* This function is distinct from main() only so we can link main.c into
  1713. * the unittest binary without conflicting with the unittests' main. */
  1714. int
  1715. tor_main(int argc, char *argv[])
  1716. {
  1717. int result = 0;
  1718. #ifdef USE_DMALLOC
  1719. int r = CRYPTO_set_mem_ex_functions(_tor_malloc, _tor_realloc,
  1720. _tor_dmalloc_free);
  1721. log_notice(LD_CONFIG, "Set up dmalloc; returned %d", r);
  1722. #endif
  1723. #ifdef NT_SERVICE
  1724. if ((result = nt_service_parse_options(argv, argc)))
  1725. return result;
  1726. #endif
  1727. if (tor_init(argc, argv)<0)
  1728. return -1;
  1729. switch (get_options()->command) {
  1730. case CMD_RUN_TOR:
  1731. #ifdef NT_SERVICE
  1732. nt_service_set_state(SERVICE_RUNNING);
  1733. #endif
  1734. result = do_main_loop();
  1735. break;
  1736. case CMD_LIST_FINGERPRINT:
  1737. result = do_list_fingerprint();
  1738. break;
  1739. case CMD_HASH_PASSWORD:
  1740. do_hash_password();
  1741. result = 0;
  1742. break;
  1743. case CMD_VERIFY_CONFIG:
  1744. printf("Configuration was valid\n");
  1745. result = 0;
  1746. break;
  1747. case CMD_RUN_UNITTESTS: /* only set by test.c */
  1748. default:
  1749. log_warn(LD_BUG,"Illegal command number %d: internal error.",
  1750. get_options()->command);
  1751. result = -1;
  1752. }
  1753. tor_cleanup();
  1754. return result;
  1755. }