main.c 70 KB

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