relay.c 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388
  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-2010, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file relay.c
  8. * \brief Handle relay cell encryption/decryption, plus packaging and
  9. * receiving from circuits, plus queuing on circuits.
  10. **/
  11. #include <math.h>
  12. #include "or.h"
  13. #include "mempool.h"
  14. static int relay_crypt(circuit_t *circ, cell_t *cell,
  15. cell_direction_t cell_direction,
  16. crypt_path_t **layer_hint, char *recognized);
  17. static edge_connection_t *relay_lookup_conn(circuit_t *circ, cell_t *cell,
  18. cell_direction_t cell_direction,
  19. crypt_path_t *layer_hint);
  20. static int
  21. connection_edge_process_relay_cell(cell_t *cell, circuit_t *circ,
  22. edge_connection_t *conn,
  23. crypt_path_t *layer_hint);
  24. static void
  25. circuit_consider_sending_sendme(circuit_t *circ, crypt_path_t *layer_hint);
  26. static void
  27. circuit_resume_edge_reading(circuit_t *circ, crypt_path_t *layer_hint);
  28. static int
  29. circuit_resume_edge_reading_helper(edge_connection_t *conn,
  30. circuit_t *circ,
  31. crypt_path_t *layer_hint);
  32. static int
  33. circuit_consider_stop_edge_reading(circuit_t *circ, crypt_path_t *layer_hint);
  34. /** Cache the current hi-res time; the cache gets reset when libevent
  35. * calls us. */
  36. static struct timeval cached_time_hires = {0, 0};
  37. static void
  38. tor_gettimeofday_cached(struct timeval *tv)
  39. {
  40. if (cached_time_hires.tv_sec == 0) {
  41. tor_gettimeofday(&cached_time_hires);
  42. }
  43. *tv = cached_time_hires;
  44. }
  45. void
  46. tor_gettimeofday_cache_clear(void)
  47. {
  48. cached_time_hires.tv_sec = 0;
  49. }
  50. /** Stats: how many relay cells have originated at this hop, or have
  51. * been relayed onward (not recognized at this hop)?
  52. */
  53. uint64_t stats_n_relay_cells_relayed = 0;
  54. /** Stats: how many relay cells have been delivered to streams at this
  55. * hop?
  56. */
  57. uint64_t stats_n_relay_cells_delivered = 0;
  58. /** Update digest from the payload of cell. Assign integrity part to
  59. * cell.
  60. */
  61. static void
  62. relay_set_digest(crypto_digest_env_t *digest, cell_t *cell)
  63. {
  64. char integrity[4];
  65. relay_header_t rh;
  66. crypto_digest_add_bytes(digest, cell->payload, CELL_PAYLOAD_SIZE);
  67. crypto_digest_get_digest(digest, integrity, 4);
  68. // log_fn(LOG_DEBUG,"Putting digest of %u %u %u %u into relay cell.",
  69. // integrity[0], integrity[1], integrity[2], integrity[3]);
  70. relay_header_unpack(&rh, cell->payload);
  71. memcpy(rh.integrity, integrity, 4);
  72. relay_header_pack(cell->payload, &rh);
  73. }
  74. /** Does the digest for this circuit indicate that this cell is for us?
  75. *
  76. * Update digest from the payload of cell (with the integrity part set
  77. * to 0). If the integrity part is valid, return 1, else restore digest
  78. * and cell to their original state and return 0.
  79. */
  80. static int
  81. relay_digest_matches(crypto_digest_env_t *digest, cell_t *cell)
  82. {
  83. char received_integrity[4], calculated_integrity[4];
  84. relay_header_t rh;
  85. crypto_digest_env_t *backup_digest=NULL;
  86. backup_digest = crypto_digest_dup(digest);
  87. relay_header_unpack(&rh, cell->payload);
  88. memcpy(received_integrity, rh.integrity, 4);
  89. memset(rh.integrity, 0, 4);
  90. relay_header_pack(cell->payload, &rh);
  91. // log_fn(LOG_DEBUG,"Reading digest of %u %u %u %u from relay cell.",
  92. // received_integrity[0], received_integrity[1],
  93. // received_integrity[2], received_integrity[3]);
  94. crypto_digest_add_bytes(digest, cell->payload, CELL_PAYLOAD_SIZE);
  95. crypto_digest_get_digest(digest, calculated_integrity, 4);
  96. if (memcmp(received_integrity, calculated_integrity, 4)) {
  97. // log_fn(LOG_INFO,"Recognized=0 but bad digest. Not recognizing.");
  98. // (%d vs %d).", received_integrity, calculated_integrity);
  99. /* restore digest to its old form */
  100. crypto_digest_assign(digest, backup_digest);
  101. /* restore the relay header */
  102. memcpy(rh.integrity, received_integrity, 4);
  103. relay_header_pack(cell->payload, &rh);
  104. crypto_free_digest_env(backup_digest);
  105. return 0;
  106. }
  107. crypto_free_digest_env(backup_digest);
  108. return 1;
  109. }
  110. /** Apply <b>cipher</b> to CELL_PAYLOAD_SIZE bytes of <b>in</b>
  111. * (in place).
  112. *
  113. * If <b>encrypt_mode</b> is 1 then encrypt, else decrypt.
  114. *
  115. * Return -1 if the crypto fails, else return 0.
  116. */
  117. static int
  118. relay_crypt_one_payload(crypto_cipher_env_t *cipher, char *in,
  119. int encrypt_mode)
  120. {
  121. int r;
  122. (void)encrypt_mode;
  123. r = crypto_cipher_crypt_inplace(cipher, in, CELL_PAYLOAD_SIZE);
  124. if (r) {
  125. log_warn(LD_BUG,"Error during relay encryption");
  126. return -1;
  127. }
  128. return 0;
  129. }
  130. /** Receive a relay cell:
  131. * - Crypt it (encrypt if headed toward the origin or if we <b>are</b> the
  132. * origin; decrypt if we're headed toward the exit).
  133. * - Check if recognized (if exitward).
  134. * - If recognized and the digest checks out, then find if there's a stream
  135. * that the cell is intended for, and deliver it to the right
  136. * connection_edge.
  137. * - If not recognized, then we need to relay it: append it to the appropriate
  138. * cell_queue on <b>circ</b>.
  139. *
  140. * Return -<b>reason</b> on failure.
  141. */
  142. int
  143. circuit_receive_relay_cell(cell_t *cell, circuit_t *circ,
  144. cell_direction_t cell_direction)
  145. {
  146. or_connection_t *or_conn=NULL;
  147. crypt_path_t *layer_hint=NULL;
  148. char recognized=0;
  149. int reason;
  150. tor_assert(cell);
  151. tor_assert(circ);
  152. tor_assert(cell_direction == CELL_DIRECTION_OUT ||
  153. cell_direction == CELL_DIRECTION_IN);
  154. if (circ->marked_for_close)
  155. return 0;
  156. if (relay_crypt(circ, cell, cell_direction, &layer_hint, &recognized) < 0) {
  157. log_warn(LD_BUG,"relay crypt failed. Dropping connection.");
  158. return -END_CIRC_REASON_INTERNAL;
  159. }
  160. if (recognized) {
  161. edge_connection_t *conn = relay_lookup_conn(circ, cell, cell_direction,
  162. layer_hint);
  163. if (cell_direction == CELL_DIRECTION_OUT) {
  164. ++stats_n_relay_cells_delivered;
  165. log_debug(LD_OR,"Sending away from origin.");
  166. if ((reason=connection_edge_process_relay_cell(cell, circ, conn, NULL))
  167. < 0) {
  168. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  169. "connection_edge_process_relay_cell (away from origin) "
  170. "failed.");
  171. return reason;
  172. }
  173. }
  174. if (cell_direction == CELL_DIRECTION_IN) {
  175. ++stats_n_relay_cells_delivered;
  176. log_debug(LD_OR,"Sending to origin.");
  177. if ((reason = connection_edge_process_relay_cell(cell, circ, conn,
  178. layer_hint)) < 0) {
  179. log_warn(LD_OR,
  180. "connection_edge_process_relay_cell (at origin) failed.");
  181. return reason;
  182. }
  183. }
  184. return 0;
  185. }
  186. /* not recognized. pass it on. */
  187. if (cell_direction == CELL_DIRECTION_OUT) {
  188. cell->circ_id = circ->n_circ_id; /* switch it */
  189. or_conn = circ->n_conn;
  190. } else if (! CIRCUIT_IS_ORIGIN(circ)) {
  191. cell->circ_id = TO_OR_CIRCUIT(circ)->p_circ_id; /* switch it */
  192. or_conn = TO_OR_CIRCUIT(circ)->p_conn;
  193. } else {
  194. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  195. "Dropping unrecognized inbound cell on origin circuit.");
  196. return 0;
  197. }
  198. if (!or_conn) {
  199. // XXXX Can this splice stuff be done more cleanly?
  200. if (! CIRCUIT_IS_ORIGIN(circ) &&
  201. TO_OR_CIRCUIT(circ)->rend_splice &&
  202. cell_direction == CELL_DIRECTION_OUT) {
  203. or_circuit_t *splice = TO_OR_CIRCUIT(circ)->rend_splice;
  204. tor_assert(circ->purpose == CIRCUIT_PURPOSE_REND_ESTABLISHED);
  205. tor_assert(splice->_base.purpose == CIRCUIT_PURPOSE_REND_ESTABLISHED);
  206. cell->circ_id = splice->p_circ_id;
  207. cell->command = CELL_RELAY; /* can't be relay_early anyway */
  208. if ((reason = circuit_receive_relay_cell(cell, TO_CIRCUIT(splice),
  209. CELL_DIRECTION_IN)) < 0) {
  210. log_warn(LD_REND, "Error relaying cell across rendezvous; closing "
  211. "circuits");
  212. /* XXXX Do this here, or just return -1? */
  213. circuit_mark_for_close(circ, -reason);
  214. return reason;
  215. }
  216. return 0;
  217. }
  218. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  219. "Didn't recognize cell, but circ stops here! Closing circ.");
  220. return -END_CIRC_REASON_TORPROTOCOL;
  221. }
  222. log_debug(LD_OR,"Passing on unrecognized cell.");
  223. ++stats_n_relay_cells_relayed; /* XXXX no longer quite accurate {cells}
  224. * we might kill the circ before we relay
  225. * the cells. */
  226. append_cell_to_circuit_queue(circ, or_conn, cell, cell_direction);
  227. return 0;
  228. }
  229. /** Do the appropriate en/decryptions for <b>cell</b> arriving on
  230. * <b>circ</b> in direction <b>cell_direction</b>.
  231. *
  232. * If cell_direction == CELL_DIRECTION_IN:
  233. * - If we're at the origin (we're the OP), for hops 1..N,
  234. * decrypt cell. If recognized, stop.
  235. * - Else (we're not the OP), encrypt one hop. Cell is not recognized.
  236. *
  237. * If cell_direction == CELL_DIRECTION_OUT:
  238. * - decrypt one hop. Check if recognized.
  239. *
  240. * If cell is recognized, set *recognized to 1, and set
  241. * *layer_hint to the hop that recognized it.
  242. *
  243. * Return -1 to indicate that we should mark the circuit for close,
  244. * else return 0.
  245. */
  246. static int
  247. relay_crypt(circuit_t *circ, cell_t *cell, cell_direction_t cell_direction,
  248. crypt_path_t **layer_hint, char *recognized)
  249. {
  250. relay_header_t rh;
  251. tor_assert(circ);
  252. tor_assert(cell);
  253. tor_assert(recognized);
  254. tor_assert(cell_direction == CELL_DIRECTION_IN ||
  255. cell_direction == CELL_DIRECTION_OUT);
  256. if (cell_direction == CELL_DIRECTION_IN) {
  257. if (CIRCUIT_IS_ORIGIN(circ)) { /* We're at the beginning of the circuit.
  258. * We'll want to do layered decrypts. */
  259. crypt_path_t *thishop, *cpath = TO_ORIGIN_CIRCUIT(circ)->cpath;
  260. thishop = cpath;
  261. if (thishop->state != CPATH_STATE_OPEN) {
  262. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  263. "Relay cell before first created cell? Closing.");
  264. return -1;
  265. }
  266. do { /* Remember: cpath is in forward order, that is, first hop first. */
  267. tor_assert(thishop);
  268. if (relay_crypt_one_payload(thishop->b_crypto, cell->payload, 0) < 0)
  269. return -1;
  270. relay_header_unpack(&rh, cell->payload);
  271. if (rh.recognized == 0) {
  272. /* it's possibly recognized. have to check digest to be sure. */
  273. if (relay_digest_matches(thishop->b_digest, cell)) {
  274. *recognized = 1;
  275. *layer_hint = thishop;
  276. return 0;
  277. }
  278. }
  279. thishop = thishop->next;
  280. } while (thishop != cpath && thishop->state == CPATH_STATE_OPEN);
  281. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  282. "Incoming cell at client not recognized. Closing.");
  283. return -1;
  284. } else { /* we're in the middle. Just one crypt. */
  285. if (relay_crypt_one_payload(TO_OR_CIRCUIT(circ)->p_crypto,
  286. cell->payload, 1) < 0)
  287. return -1;
  288. // log_fn(LOG_DEBUG,"Skipping recognized check, because we're not "
  289. // "the client.");
  290. }
  291. } else /* cell_direction == CELL_DIRECTION_OUT */ {
  292. /* we're in the middle. Just one crypt. */
  293. if (relay_crypt_one_payload(TO_OR_CIRCUIT(circ)->n_crypto,
  294. cell->payload, 0) < 0)
  295. return -1;
  296. relay_header_unpack(&rh, cell->payload);
  297. if (rh.recognized == 0) {
  298. /* it's possibly recognized. have to check digest to be sure. */
  299. if (relay_digest_matches(TO_OR_CIRCUIT(circ)->n_digest, cell)) {
  300. *recognized = 1;
  301. return 0;
  302. }
  303. }
  304. }
  305. return 0;
  306. }
  307. /** Package a relay cell from an edge:
  308. * - Encrypt it to the right layer
  309. * - Append it to the appropriate cell_queue on <b>circ</b>.
  310. */
  311. static int
  312. circuit_package_relay_cell(cell_t *cell, circuit_t *circ,
  313. cell_direction_t cell_direction,
  314. crypt_path_t *layer_hint)
  315. {
  316. or_connection_t *conn; /* where to send the cell */
  317. if (cell_direction == CELL_DIRECTION_OUT) {
  318. crypt_path_t *thishop; /* counter for repeated crypts */
  319. conn = circ->n_conn;
  320. if (!CIRCUIT_IS_ORIGIN(circ) || !conn) {
  321. log_warn(LD_BUG,"outgoing relay cell has n_conn==NULL. Dropping.");
  322. return 0; /* just drop it */
  323. }
  324. relay_set_digest(layer_hint->f_digest, cell);
  325. thishop = layer_hint;
  326. /* moving from farthest to nearest hop */
  327. do {
  328. tor_assert(thishop);
  329. /* XXXX RD This is a bug, right? */
  330. log_debug(LD_OR,"crypting a layer of the relay cell.");
  331. if (relay_crypt_one_payload(thishop->f_crypto, cell->payload, 1) < 0) {
  332. return -1;
  333. }
  334. thishop = thishop->prev;
  335. } while (thishop != TO_ORIGIN_CIRCUIT(circ)->cpath->prev);
  336. } else { /* incoming cell */
  337. or_circuit_t *or_circ;
  338. if (CIRCUIT_IS_ORIGIN(circ)) {
  339. /* We should never package an _incoming_ cell from the circuit
  340. * origin; that means we messed up somewhere. */
  341. log_warn(LD_BUG,"incoming relay cell at origin circuit. Dropping.");
  342. assert_circuit_ok(circ);
  343. return 0; /* just drop it */
  344. }
  345. or_circ = TO_OR_CIRCUIT(circ);
  346. conn = or_circ->p_conn;
  347. relay_set_digest(or_circ->p_digest, cell);
  348. if (relay_crypt_one_payload(or_circ->p_crypto, cell->payload, 1) < 0)
  349. return -1;
  350. }
  351. ++stats_n_relay_cells_relayed;
  352. append_cell_to_circuit_queue(circ, conn, cell, cell_direction);
  353. return 0;
  354. }
  355. /** If cell's stream_id matches the stream_id of any conn that's
  356. * attached to circ, return that conn, else return NULL.
  357. */
  358. static edge_connection_t *
  359. relay_lookup_conn(circuit_t *circ, cell_t *cell,
  360. cell_direction_t cell_direction, crypt_path_t *layer_hint)
  361. {
  362. edge_connection_t *tmpconn;
  363. relay_header_t rh;
  364. relay_header_unpack(&rh, cell->payload);
  365. if (!rh.stream_id)
  366. return NULL;
  367. /* IN or OUT cells could have come from either direction, now
  368. * that we allow rendezvous *to* an OP.
  369. */
  370. if (CIRCUIT_IS_ORIGIN(circ)) {
  371. for (tmpconn = TO_ORIGIN_CIRCUIT(circ)->p_streams; tmpconn;
  372. tmpconn=tmpconn->next_stream) {
  373. if (rh.stream_id == tmpconn->stream_id &&
  374. !tmpconn->_base.marked_for_close &&
  375. tmpconn->cpath_layer == layer_hint) {
  376. log_debug(LD_APP,"found conn for stream %d.", rh.stream_id);
  377. return tmpconn;
  378. }
  379. }
  380. } else {
  381. for (tmpconn = TO_OR_CIRCUIT(circ)->n_streams; tmpconn;
  382. tmpconn=tmpconn->next_stream) {
  383. if (rh.stream_id == tmpconn->stream_id &&
  384. !tmpconn->_base.marked_for_close) {
  385. log_debug(LD_EXIT,"found conn for stream %d.", rh.stream_id);
  386. if (cell_direction == CELL_DIRECTION_OUT ||
  387. connection_edge_is_rendezvous_stream(tmpconn))
  388. return tmpconn;
  389. }
  390. }
  391. for (tmpconn = TO_OR_CIRCUIT(circ)->resolving_streams; tmpconn;
  392. tmpconn=tmpconn->next_stream) {
  393. if (rh.stream_id == tmpconn->stream_id &&
  394. !tmpconn->_base.marked_for_close) {
  395. log_debug(LD_EXIT,"found conn for stream %d.", rh.stream_id);
  396. return tmpconn;
  397. }
  398. }
  399. }
  400. return NULL; /* probably a begin relay cell */
  401. }
  402. /** Pack the relay_header_t host-order structure <b>src</b> into
  403. * network-order in the buffer <b>dest</b>. See tor-spec.txt for details
  404. * about the wire format.
  405. */
  406. void
  407. relay_header_pack(char *dest, const relay_header_t *src)
  408. {
  409. *(uint8_t*)(dest) = src->command;
  410. set_uint16(dest+1, htons(src->recognized));
  411. set_uint16(dest+3, htons(src->stream_id));
  412. memcpy(dest+5, src->integrity, 4);
  413. set_uint16(dest+9, htons(src->length));
  414. }
  415. /** Unpack the network-order buffer <b>src</b> into a host-order
  416. * relay_header_t structure <b>dest</b>.
  417. */
  418. void
  419. relay_header_unpack(relay_header_t *dest, const char *src)
  420. {
  421. dest->command = *(uint8_t*)(src);
  422. dest->recognized = ntohs(get_uint16(src+1));
  423. dest->stream_id = ntohs(get_uint16(src+3));
  424. memcpy(dest->integrity, src+5, 4);
  425. dest->length = ntohs(get_uint16(src+9));
  426. }
  427. /** Convert the relay <b>command</b> into a human-readable string. */
  428. static const char *
  429. relay_command_to_string(uint8_t command)
  430. {
  431. switch (command) {
  432. case RELAY_COMMAND_BEGIN: return "BEGIN";
  433. case RELAY_COMMAND_DATA: return "DATA";
  434. case RELAY_COMMAND_END: return "END";
  435. case RELAY_COMMAND_CONNECTED: return "CONNECTED";
  436. case RELAY_COMMAND_SENDME: return "SENDME";
  437. case RELAY_COMMAND_EXTEND: return "EXTEND";
  438. case RELAY_COMMAND_EXTENDED: return "EXTENDED";
  439. case RELAY_COMMAND_TRUNCATE: return "TRUNCATE";
  440. case RELAY_COMMAND_TRUNCATED: return "TRUNCATED";
  441. case RELAY_COMMAND_DROP: return "DROP";
  442. case RELAY_COMMAND_RESOLVE: return "RESOLVE";
  443. case RELAY_COMMAND_RESOLVED: return "RESOLVED";
  444. case RELAY_COMMAND_BEGIN_DIR: return "BEGIN_DIR";
  445. case RELAY_COMMAND_ESTABLISH_INTRO: return "ESTABLISH_INTRO";
  446. case RELAY_COMMAND_ESTABLISH_RENDEZVOUS: return "ESTABLISH_RENDEZVOUS";
  447. case RELAY_COMMAND_INTRODUCE1: return "INTRODUCE1";
  448. case RELAY_COMMAND_INTRODUCE2: return "INTRODUCE2";
  449. case RELAY_COMMAND_RENDEZVOUS1: return "RENDEZVOUS1";
  450. case RELAY_COMMAND_RENDEZVOUS2: return "RENDEZVOUS2";
  451. case RELAY_COMMAND_INTRO_ESTABLISHED: return "INTRO_ESTABLISHED";
  452. case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
  453. return "RENDEZVOUS_ESTABLISHED";
  454. case RELAY_COMMAND_INTRODUCE_ACK: return "INTRODUCE_ACK";
  455. default: return "(unrecognized)";
  456. }
  457. }
  458. /** Make a relay cell out of <b>relay_command</b> and <b>payload</b>, and send
  459. * it onto the open circuit <b>circ</b>. <b>stream_id</b> is the ID on
  460. * <b>circ</b> for the stream that's sending the relay cell, or 0 if it's a
  461. * control cell. <b>cpath_layer</b> is NULL for OR->OP cells, or the
  462. * destination hop for OP->OR cells.
  463. *
  464. * If you can't send the cell, mark the circuit for close and return -1. Else
  465. * return 0.
  466. */
  467. int
  468. relay_send_command_from_edge(uint16_t stream_id, circuit_t *circ,
  469. uint8_t relay_command, const char *payload,
  470. size_t payload_len, crypt_path_t *cpath_layer)
  471. {
  472. cell_t cell;
  473. relay_header_t rh;
  474. cell_direction_t cell_direction;
  475. /* XXXX NM Split this function into a separate versions per circuit type? */
  476. tor_assert(circ);
  477. tor_assert(payload_len <= RELAY_PAYLOAD_SIZE);
  478. memset(&cell, 0, sizeof(cell_t));
  479. cell.command = CELL_RELAY;
  480. if (cpath_layer) {
  481. cell.circ_id = circ->n_circ_id;
  482. cell_direction = CELL_DIRECTION_OUT;
  483. } else if (! CIRCUIT_IS_ORIGIN(circ)) {
  484. cell.circ_id = TO_OR_CIRCUIT(circ)->p_circ_id;
  485. cell_direction = CELL_DIRECTION_IN;
  486. } else {
  487. return -1;
  488. }
  489. memset(&rh, 0, sizeof(rh));
  490. rh.command = relay_command;
  491. rh.stream_id = stream_id;
  492. rh.length = payload_len;
  493. relay_header_pack(cell.payload, &rh);
  494. if (payload_len)
  495. memcpy(cell.payload+RELAY_HEADER_SIZE, payload, payload_len);
  496. log_debug(LD_OR,"delivering %d cell %s.", relay_command,
  497. cell_direction == CELL_DIRECTION_OUT ? "forward" : "backward");
  498. /* If we are sending an END cell and this circuit is used for a tunneled
  499. * directory request, advance its state. */
  500. if (relay_command == RELAY_COMMAND_END && circ->dirreq_id)
  501. geoip_change_dirreq_state(circ->dirreq_id, DIRREQ_TUNNELED,
  502. DIRREQ_END_CELL_SENT);
  503. if (cell_direction == CELL_DIRECTION_OUT && circ->n_conn) {
  504. /* if we're using relaybandwidthrate, this conn wants priority */
  505. circ->n_conn->client_used = approx_time();
  506. }
  507. if (cell_direction == CELL_DIRECTION_OUT) {
  508. origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
  509. if (origin_circ->remaining_relay_early_cells > 0 &&
  510. (relay_command == RELAY_COMMAND_EXTEND ||
  511. (cpath_layer != origin_circ->cpath &&
  512. !CIRCUIT_PURPOSE_IS_ESTABLISHED_REND(circ->purpose)))) {
  513. /* If we've got any relay_early cells left, and we're sending
  514. * an extend cell or (we're not talking to the first hop and we're
  515. * not talking to a rendezvous circuit), use one of them.
  516. * Don't worry about the conn protocol version:
  517. * append_cell_to_circuit_queue will fix it up. */
  518. /* XXX For now, clients don't use RELAY_EARLY cells when sending
  519. * relay cells on rendezvous circuits. See bug 1038. Once no relays
  520. * (and thus no rendezvous points) are running 0.2.1.3-alpha through
  521. * 0.2.1.18, we can take out that exception. -RD */
  522. cell.command = CELL_RELAY_EARLY;
  523. --origin_circ->remaining_relay_early_cells;
  524. log_debug(LD_OR, "Sending a RELAY_EARLY cell; %d remaining.",
  525. (int)origin_circ->remaining_relay_early_cells);
  526. /* Memorize the command that is sent as RELAY_EARLY cell; helps debug
  527. * task 878. */
  528. origin_circ->relay_early_commands[
  529. origin_circ->relay_early_cells_sent++] = relay_command;
  530. } else if (relay_command == RELAY_COMMAND_EXTEND) {
  531. /* If no RELAY_EARLY cells can be sent over this circuit, log which
  532. * commands have been sent as RELAY_EARLY cells before; helps debug
  533. * task 878. */
  534. smartlist_t *commands_list = smartlist_create();
  535. int i = 0;
  536. char *commands = NULL;
  537. for (; i < origin_circ->relay_early_cells_sent; i++)
  538. smartlist_add(commands_list, (char *)
  539. relay_command_to_string(origin_circ->relay_early_commands[i]));
  540. commands = smartlist_join_strings(commands_list, ",", 0, NULL);
  541. log_warn(LD_BUG, "Uh-oh. We're sending a RELAY_COMMAND_EXTEND cell, "
  542. "but we have run out of RELAY_EARLY cells on that circuit. "
  543. "Commands sent before: %s", commands);
  544. tor_free(commands);
  545. smartlist_free(commands_list);
  546. }
  547. }
  548. if (circuit_package_relay_cell(&cell, circ, cell_direction, cpath_layer)
  549. < 0) {
  550. log_warn(LD_BUG,"circuit_package_relay_cell failed. Closing.");
  551. circuit_mark_for_close(circ, END_CIRC_REASON_INTERNAL);
  552. return -1;
  553. }
  554. return 0;
  555. }
  556. /** Make a relay cell out of <b>relay_command</b> and <b>payload</b>, and
  557. * send it onto the open circuit <b>circ</b>. <b>fromconn</b> is the stream
  558. * that's sending the relay cell, or NULL if it's a control cell.
  559. * <b>cpath_layer</b> is NULL for OR->OP cells, or the destination hop
  560. * for OP->OR cells.
  561. *
  562. * If you can't send the cell, mark the circuit for close and
  563. * return -1. Else return 0.
  564. */
  565. int
  566. connection_edge_send_command(edge_connection_t *fromconn,
  567. uint8_t relay_command, const char *payload,
  568. size_t payload_len)
  569. {
  570. /* XXXX NM Split this function into a separate versions per circuit type? */
  571. circuit_t *circ;
  572. tor_assert(fromconn);
  573. circ = fromconn->on_circuit;
  574. if (fromconn->_base.marked_for_close) {
  575. log_warn(LD_BUG,
  576. "called on conn that's already marked for close at %s:%d.",
  577. fromconn->_base.marked_for_close_file,
  578. fromconn->_base.marked_for_close);
  579. return 0;
  580. }
  581. if (!circ) {
  582. if (fromconn->_base.type == CONN_TYPE_AP) {
  583. log_info(LD_APP,"no circ. Closing conn.");
  584. connection_mark_unattached_ap(fromconn, END_STREAM_REASON_INTERNAL);
  585. } else {
  586. log_info(LD_EXIT,"no circ. Closing conn.");
  587. fromconn->edge_has_sent_end = 1; /* no circ to send to */
  588. fromconn->end_reason = END_STREAM_REASON_INTERNAL;
  589. connection_mark_for_close(TO_CONN(fromconn));
  590. }
  591. return -1;
  592. }
  593. return relay_send_command_from_edge(fromconn->stream_id, circ,
  594. relay_command, payload,
  595. payload_len, fromconn->cpath_layer);
  596. }
  597. /** How many times will I retry a stream that fails due to DNS
  598. * resolve failure or misc error?
  599. */
  600. #define MAX_RESOLVE_FAILURES 3
  601. /** Return 1 if reason is something that you should retry if you
  602. * get the end cell before you've connected; else return 0. */
  603. static int
  604. edge_reason_is_retriable(int reason)
  605. {
  606. return reason == END_STREAM_REASON_HIBERNATING ||
  607. reason == END_STREAM_REASON_RESOURCELIMIT ||
  608. reason == END_STREAM_REASON_EXITPOLICY ||
  609. reason == END_STREAM_REASON_RESOLVEFAILED ||
  610. reason == END_STREAM_REASON_MISC;
  611. }
  612. /** Called when we receive an END cell on a stream that isn't open yet,
  613. * from the client side.
  614. * Arguments are as for connection_edge_process_relay_cell().
  615. */
  616. static int
  617. connection_ap_process_end_not_open(
  618. relay_header_t *rh, cell_t *cell, origin_circuit_t *circ,
  619. edge_connection_t *conn, crypt_path_t *layer_hint)
  620. {
  621. struct in_addr in;
  622. routerinfo_t *exitrouter;
  623. int reason = *(cell->payload+RELAY_HEADER_SIZE);
  624. int control_reason = reason | END_STREAM_REASON_FLAG_REMOTE;
  625. (void) layer_hint; /* unused */
  626. if (rh->length > 0 && edge_reason_is_retriable(reason) &&
  627. !connection_edge_is_rendezvous_stream(conn) /* avoid retry if rend */
  628. ) {
  629. log_info(LD_APP,"Address '%s' refused due to '%s'. Considering retrying.",
  630. safe_str(conn->socks_request->address),
  631. stream_end_reason_to_string(reason));
  632. exitrouter =
  633. router_get_by_digest(circ->build_state->chosen_exit->identity_digest);
  634. switch (reason) {
  635. case END_STREAM_REASON_EXITPOLICY:
  636. if (rh->length >= 5) {
  637. uint32_t addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+1));
  638. int ttl;
  639. if (!addr) {
  640. log_info(LD_APP,"Address '%s' resolved to 0.0.0.0. Closing,",
  641. safe_str(conn->socks_request->address));
  642. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  643. return 0;
  644. }
  645. if (rh->length >= 9)
  646. ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+5));
  647. else
  648. ttl = -1;
  649. if (get_options()->ClientDNSRejectInternalAddresses &&
  650. is_internal_IP(addr, 0)) {
  651. log_info(LD_APP,"Address '%s' resolved to internal. Closing,",
  652. safe_str(conn->socks_request->address));
  653. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  654. return 0;
  655. }
  656. client_dns_set_addressmap(conn->socks_request->address, addr,
  657. conn->chosen_exit_name, ttl);
  658. }
  659. /* check if he *ought* to have allowed it */
  660. if (exitrouter &&
  661. (rh->length < 5 ||
  662. (tor_inet_aton(conn->socks_request->address, &in) &&
  663. !conn->chosen_exit_name))) {
  664. log_info(LD_APP,
  665. "Exitrouter '%s' seems to be more restrictive than its exit "
  666. "policy. Not using this router as exit for now.",
  667. exitrouter->nickname);
  668. policies_set_router_exitpolicy_to_reject_all(exitrouter);
  669. }
  670. /* rewrite it to an IP if we learned one. */
  671. if (addressmap_rewrite(conn->socks_request->address,
  672. sizeof(conn->socks_request->address),
  673. NULL)) {
  674. control_event_stream_status(conn, STREAM_EVENT_REMAP, 0);
  675. }
  676. if (conn->chosen_exit_optional ||
  677. conn->chosen_exit_retries) {
  678. /* stop wanting a specific exit */
  679. conn->chosen_exit_optional = 0;
  680. /* A non-zero chosen_exit_retries can happen if we set a
  681. * TrackHostExits for this address under a port that the exit
  682. * relay allows, but then try the same address with a different
  683. * port that it doesn't allow to exit. We shouldn't unregister
  684. * the mapping, since it is probably still wanted on the
  685. * original port. But now we give away to the exit relay that
  686. * we probably have a TrackHostExits on it. So be it. */
  687. conn->chosen_exit_retries = 0;
  688. tor_free(conn->chosen_exit_name); /* clears it */
  689. }
  690. if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
  691. return 0;
  692. /* else, conn will get closed below */
  693. break;
  694. case END_STREAM_REASON_CONNECTREFUSED:
  695. if (!conn->chosen_exit_optional)
  696. break; /* break means it'll close, below */
  697. /* Else fall through: expire this circuit, clear the
  698. * chosen_exit_name field, and try again. */
  699. case END_STREAM_REASON_RESOLVEFAILED:
  700. case END_STREAM_REASON_TIMEOUT:
  701. case END_STREAM_REASON_MISC:
  702. if (client_dns_incr_failures(conn->socks_request->address)
  703. < MAX_RESOLVE_FAILURES) {
  704. /* We haven't retried too many times; reattach the connection. */
  705. circuit_log_path(LOG_INFO,LD_APP,circ);
  706. tor_assert(circ->_base.timestamp_dirty);
  707. circ->_base.timestamp_dirty -= get_options()->MaxCircuitDirtiness;
  708. if (conn->chosen_exit_optional) {
  709. /* stop wanting a specific exit */
  710. conn->chosen_exit_optional = 0;
  711. tor_free(conn->chosen_exit_name); /* clears it */
  712. }
  713. if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
  714. return 0;
  715. /* else, conn will get closed below */
  716. } else {
  717. log_notice(LD_APP,
  718. "Have tried resolving or connecting to address '%s' "
  719. "at %d different places. Giving up.",
  720. safe_str(conn->socks_request->address),
  721. MAX_RESOLVE_FAILURES);
  722. /* clear the failures, so it will have a full try next time */
  723. client_dns_clear_failures(conn->socks_request->address);
  724. }
  725. break;
  726. case END_STREAM_REASON_HIBERNATING:
  727. case END_STREAM_REASON_RESOURCELIMIT:
  728. if (exitrouter) {
  729. policies_set_router_exitpolicy_to_reject_all(exitrouter);
  730. }
  731. if (conn->chosen_exit_optional) {
  732. /* stop wanting a specific exit */
  733. conn->chosen_exit_optional = 0;
  734. tor_free(conn->chosen_exit_name); /* clears it */
  735. }
  736. if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
  737. return 0;
  738. /* else, will close below */
  739. break;
  740. } /* end switch */
  741. log_info(LD_APP,"Giving up on retrying; conn can't be handled.");
  742. }
  743. log_info(LD_APP,
  744. "Edge got end (%s) before we're connected. Marking for close.",
  745. stream_end_reason_to_string(rh->length > 0 ? reason : -1));
  746. circuit_log_path(LOG_INFO,LD_APP,circ);
  747. /* need to test because of detach_retriable */
  748. if (!conn->_base.marked_for_close)
  749. connection_mark_unattached_ap(conn, control_reason);
  750. return 0;
  751. }
  752. /** Helper: change the socks_request-&gt;address field on conn to the
  753. * dotted-quad representation of <b>new_addr</b> (given in host order),
  754. * and send an appropriate REMAP event. */
  755. static void
  756. remap_event_helper(edge_connection_t *conn, uint32_t new_addr)
  757. {
  758. struct in_addr in;
  759. in.s_addr = htonl(new_addr);
  760. tor_inet_ntoa(&in, conn->socks_request->address,
  761. sizeof(conn->socks_request->address));
  762. control_event_stream_status(conn, STREAM_EVENT_REMAP,
  763. REMAP_STREAM_SOURCE_EXIT);
  764. }
  765. /** An incoming relay cell has arrived from circuit <b>circ</b> to
  766. * stream <b>conn</b>.
  767. *
  768. * The arguments here are the same as in
  769. * connection_edge_process_relay_cell() below; this function is called
  770. * from there when <b>conn</b> is defined and not in an open state.
  771. */
  772. static int
  773. connection_edge_process_relay_cell_not_open(
  774. relay_header_t *rh, cell_t *cell, circuit_t *circ,
  775. edge_connection_t *conn, crypt_path_t *layer_hint)
  776. {
  777. if (rh->command == RELAY_COMMAND_END) {
  778. if (CIRCUIT_IS_ORIGIN(circ) && conn->_base.type == CONN_TYPE_AP) {
  779. return connection_ap_process_end_not_open(rh, cell,
  780. TO_ORIGIN_CIRCUIT(circ), conn,
  781. layer_hint);
  782. } else {
  783. /* we just got an 'end', don't need to send one */
  784. conn->edge_has_sent_end = 1;
  785. conn->end_reason = *(cell->payload+RELAY_HEADER_SIZE) |
  786. END_STREAM_REASON_FLAG_REMOTE;
  787. connection_mark_for_close(TO_CONN(conn));
  788. return 0;
  789. }
  790. }
  791. if (conn->_base.type == CONN_TYPE_AP &&
  792. rh->command == RELAY_COMMAND_CONNECTED) {
  793. tor_assert(CIRCUIT_IS_ORIGIN(circ));
  794. if (conn->_base.state != AP_CONN_STATE_CONNECT_WAIT) {
  795. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  796. "Got 'connected' while not in state connect_wait. Dropping.");
  797. return 0;
  798. }
  799. conn->_base.state = AP_CONN_STATE_OPEN;
  800. log_info(LD_APP,"'connected' received after %d seconds.",
  801. (int)(time(NULL) - conn->_base.timestamp_lastread));
  802. if (rh->length >= 4) {
  803. uint32_t addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE));
  804. int ttl;
  805. if (!addr || (get_options()->ClientDNSRejectInternalAddresses &&
  806. is_internal_IP(addr, 0))) {
  807. char buf[INET_NTOA_BUF_LEN];
  808. struct in_addr a;
  809. a.s_addr = htonl(addr);
  810. tor_inet_ntoa(&a, buf, sizeof(buf));
  811. log_info(LD_APP,
  812. "...but it claims the IP address was %s. Closing.", buf);
  813. connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
  814. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  815. return 0;
  816. }
  817. if (rh->length >= 8)
  818. ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+4));
  819. else
  820. ttl = -1;
  821. client_dns_set_addressmap(conn->socks_request->address, addr,
  822. conn->chosen_exit_name, ttl);
  823. remap_event_helper(conn, addr);
  824. }
  825. circuit_log_path(LOG_INFO,LD_APP,TO_ORIGIN_CIRCUIT(circ));
  826. /* don't send a socks reply to transparent conns */
  827. if (!conn->socks_request->has_finished)
  828. connection_ap_handshake_socks_reply(conn, NULL, 0, 0);
  829. /* Was it a linked dir conn? If so, a dir request just started to
  830. * fetch something; this could be a bootstrap status milestone. */
  831. log_debug(LD_APP, "considering");
  832. if (TO_CONN(conn)->linked_conn &&
  833. TO_CONN(conn)->linked_conn->type == CONN_TYPE_DIR) {
  834. connection_t *dirconn = TO_CONN(conn)->linked_conn;
  835. log_debug(LD_APP, "it is! %d", dirconn->purpose);
  836. switch (dirconn->purpose) {
  837. case DIR_PURPOSE_FETCH_CERTIFICATE:
  838. if (consensus_is_waiting_for_certs())
  839. control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_KEYS, 0);
  840. break;
  841. case DIR_PURPOSE_FETCH_CONSENSUS:
  842. control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_STATUS, 0);
  843. break;
  844. case DIR_PURPOSE_FETCH_SERVERDESC:
  845. control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_DESCRIPTORS,
  846. count_loading_descriptors_progress());
  847. break;
  848. }
  849. }
  850. /* handle anything that might have queued */
  851. if (connection_edge_package_raw_inbuf(conn, 1) < 0) {
  852. /* (We already sent an end cell if possible) */
  853. connection_mark_for_close(TO_CONN(conn));
  854. return 0;
  855. }
  856. return 0;
  857. }
  858. if (conn->_base.type == CONN_TYPE_AP &&
  859. rh->command == RELAY_COMMAND_RESOLVED) {
  860. int ttl;
  861. int answer_len;
  862. uint8_t answer_type;
  863. if (conn->_base.state != AP_CONN_STATE_RESOLVE_WAIT) {
  864. log_fn(LOG_PROTOCOL_WARN, LD_APP, "Got a 'resolved' cell while "
  865. "not in state resolve_wait. Dropping.");
  866. return 0;
  867. }
  868. tor_assert(SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command));
  869. answer_len = cell->payload[RELAY_HEADER_SIZE+1];
  870. if (rh->length < 2 || answer_len+2>rh->length) {
  871. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  872. "Dropping malformed 'resolved' cell");
  873. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  874. return 0;
  875. }
  876. answer_type = cell->payload[RELAY_HEADER_SIZE];
  877. if (rh->length >= answer_len+6)
  878. ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+
  879. 2+answer_len));
  880. else
  881. ttl = -1;
  882. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
  883. uint32_t addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+2));
  884. if (get_options()->ClientDNSRejectInternalAddresses &&
  885. is_internal_IP(addr, 0)) {
  886. char buf[INET_NTOA_BUF_LEN];
  887. struct in_addr a;
  888. a.s_addr = htonl(addr);
  889. tor_inet_ntoa(&a, buf, sizeof(buf));
  890. log_info(LD_APP,"Got a resolve with answer %s. Rejecting.", buf);
  891. connection_ap_handshake_socks_resolved(conn,
  892. RESOLVED_TYPE_ERROR_TRANSIENT,
  893. 0, NULL, 0, TIME_MAX);
  894. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  895. return 0;
  896. }
  897. }
  898. connection_ap_handshake_socks_resolved(conn,
  899. answer_type,
  900. cell->payload[RELAY_HEADER_SIZE+1], /*answer_len*/
  901. cell->payload+RELAY_HEADER_SIZE+2, /*answer*/
  902. ttl,
  903. -1);
  904. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
  905. uint32_t addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+2));
  906. remap_event_helper(conn, addr);
  907. }
  908. connection_mark_unattached_ap(conn,
  909. END_STREAM_REASON_DONE |
  910. END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
  911. return 0;
  912. }
  913. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  914. "Got an unexpected relay command %d, in state %d (%s). Dropping.",
  915. rh->command, conn->_base.state,
  916. conn_state_to_string(conn->_base.type, conn->_base.state));
  917. return 0; /* for forward compatibility, don't kill the circuit */
  918. // connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
  919. // connection_mark_for_close(conn);
  920. // return -1;
  921. }
  922. /** An incoming relay cell has arrived on circuit <b>circ</b>. If
  923. * <b>conn</b> is NULL this is a control cell, else <b>cell</b> is
  924. * destined for <b>conn</b>.
  925. *
  926. * If <b>layer_hint</b> is defined, then we're the origin of the
  927. * circuit, and it specifies the hop that packaged <b>cell</b>.
  928. *
  929. * Return -reason if you want to warn and tear down the circuit, else 0.
  930. */
  931. static int
  932. connection_edge_process_relay_cell(cell_t *cell, circuit_t *circ,
  933. edge_connection_t *conn,
  934. crypt_path_t *layer_hint)
  935. {
  936. static int num_seen=0;
  937. relay_header_t rh;
  938. unsigned domain = layer_hint?LD_APP:LD_EXIT;
  939. int reason;
  940. tor_assert(cell);
  941. tor_assert(circ);
  942. relay_header_unpack(&rh, cell->payload);
  943. // log_fn(LOG_DEBUG,"command %d stream %d", rh.command, rh.stream_id);
  944. num_seen++;
  945. log_debug(domain, "Now seen %d relay cells here (command %d, stream %d).",
  946. num_seen, rh.command, rh.stream_id);
  947. if (rh.length > RELAY_PAYLOAD_SIZE) {
  948. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  949. "Relay cell length field too long. Closing circuit.");
  950. return - END_CIRC_REASON_TORPROTOCOL;
  951. }
  952. /* either conn is NULL, in which case we've got a control cell, or else
  953. * conn points to the recognized stream. */
  954. if (conn && !connection_state_is_open(TO_CONN(conn)))
  955. return connection_edge_process_relay_cell_not_open(
  956. &rh, cell, circ, conn, layer_hint);
  957. switch (rh.command) {
  958. case RELAY_COMMAND_DROP:
  959. // log_info(domain,"Got a relay-level padding cell. Dropping.");
  960. return 0;
  961. case RELAY_COMMAND_BEGIN:
  962. case RELAY_COMMAND_BEGIN_DIR:
  963. if (layer_hint &&
  964. circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
  965. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  966. "Relay begin request unsupported at AP. Dropping.");
  967. return 0;
  968. }
  969. if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED &&
  970. layer_hint != TO_ORIGIN_CIRCUIT(circ)->cpath->prev) {
  971. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  972. "Relay begin request to Hidden Service "
  973. "from intermediary node. Dropping.");
  974. return 0;
  975. }
  976. if (conn) {
  977. log_fn(LOG_PROTOCOL_WARN, domain,
  978. "Begin cell for known stream. Dropping.");
  979. return 0;
  980. }
  981. if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
  982. /* Assign this circuit and its app-ward OR connection a unique ID,
  983. * so that we can measure download times. The local edge and dir
  984. * connection will be assigned the same ID when they are created
  985. * and linked. */
  986. static uint64_t next_id = 0;
  987. circ->dirreq_id = ++next_id;
  988. TO_CONN(TO_OR_CIRCUIT(circ)->p_conn)->dirreq_id = circ->dirreq_id;
  989. }
  990. return connection_exit_begin_conn(cell, circ);
  991. case RELAY_COMMAND_DATA:
  992. ++stats_n_data_cells_received;
  993. if (( layer_hint && --layer_hint->deliver_window < 0) ||
  994. (!layer_hint && --circ->deliver_window < 0)) {
  995. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  996. "(relay data) circ deliver_window below 0. Killing.");
  997. connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
  998. connection_mark_for_close(TO_CONN(conn));
  999. return -END_CIRC_REASON_TORPROTOCOL;
  1000. }
  1001. log_debug(domain,"circ deliver_window now %d.", layer_hint ?
  1002. layer_hint->deliver_window : circ->deliver_window);
  1003. circuit_consider_sending_sendme(circ, layer_hint);
  1004. if (!conn) {
  1005. log_info(domain,"data cell dropped, unknown stream (streamid %d).",
  1006. rh.stream_id);
  1007. return 0;
  1008. }
  1009. if (--conn->deliver_window < 0) { /* is it below 0 after decrement? */
  1010. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1011. "(relay data) conn deliver_window below 0. Killing.");
  1012. return -END_CIRC_REASON_TORPROTOCOL;
  1013. }
  1014. stats_n_data_bytes_received += rh.length;
  1015. connection_write_to_buf(cell->payload + RELAY_HEADER_SIZE,
  1016. rh.length, TO_CONN(conn));
  1017. connection_edge_consider_sending_sendme(conn);
  1018. return 0;
  1019. case RELAY_COMMAND_END:
  1020. reason = rh.length > 0 ?
  1021. *(uint8_t *)(cell->payload+RELAY_HEADER_SIZE) : END_STREAM_REASON_MISC;
  1022. if (!conn) {
  1023. log_info(domain,"end cell (%s) dropped, unknown stream.",
  1024. stream_end_reason_to_string(reason));
  1025. return 0;
  1026. }
  1027. /* XXX add to this log_fn the exit node's nickname? */
  1028. log_info(domain,"%d: end cell (%s) for stream %d. Removing stream.",
  1029. conn->_base.s,
  1030. stream_end_reason_to_string(reason),
  1031. conn->stream_id);
  1032. if (conn->socks_request && !conn->socks_request->has_finished)
  1033. log_warn(LD_BUG,
  1034. "open stream hasn't sent socks answer yet? Closing.");
  1035. /* We just *got* an end; no reason to send one. */
  1036. conn->edge_has_sent_end = 1;
  1037. if (!conn->end_reason)
  1038. conn->end_reason = reason | END_STREAM_REASON_FLAG_REMOTE;
  1039. if (!conn->_base.marked_for_close) {
  1040. /* only mark it if not already marked. it's possible to
  1041. * get the 'end' right around when the client hangs up on us. */
  1042. connection_mark_for_close(TO_CONN(conn));
  1043. conn->_base.hold_open_until_flushed = 1;
  1044. }
  1045. return 0;
  1046. case RELAY_COMMAND_EXTEND:
  1047. if (conn) {
  1048. log_fn(LOG_PROTOCOL_WARN, domain,
  1049. "'extend' cell received for non-zero stream. Dropping.");
  1050. return 0;
  1051. }
  1052. return circuit_extend(cell, circ);
  1053. case RELAY_COMMAND_EXTENDED:
  1054. if (!layer_hint) {
  1055. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1056. "'extended' unsupported at non-origin. Dropping.");
  1057. return 0;
  1058. }
  1059. log_debug(domain,"Got an extended cell! Yay.");
  1060. if ((reason = circuit_finish_handshake(TO_ORIGIN_CIRCUIT(circ),
  1061. CELL_CREATED,
  1062. cell->payload+RELAY_HEADER_SIZE)) < 0) {
  1063. log_warn(domain,"circuit_finish_handshake failed.");
  1064. return reason;
  1065. }
  1066. if ((reason=circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ)))<0) {
  1067. log_info(domain,"circuit_send_next_onion_skin() failed.");
  1068. return reason;
  1069. }
  1070. return 0;
  1071. case RELAY_COMMAND_TRUNCATE:
  1072. if (layer_hint) {
  1073. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  1074. "'truncate' unsupported at origin. Dropping.");
  1075. return 0;
  1076. }
  1077. if (circ->n_conn) {
  1078. uint8_t trunc_reason = *(uint8_t*)(cell->payload + RELAY_HEADER_SIZE);
  1079. connection_or_send_destroy(circ->n_circ_id, circ->n_conn,
  1080. trunc_reason);
  1081. circuit_set_n_circid_orconn(circ, 0, NULL);
  1082. }
  1083. log_debug(LD_EXIT, "Processed 'truncate', replying.");
  1084. {
  1085. char payload[1];
  1086. payload[0] = (char)END_CIRC_REASON_REQUESTED;
  1087. relay_send_command_from_edge(0, circ, RELAY_COMMAND_TRUNCATED,
  1088. payload, sizeof(payload), NULL);
  1089. }
  1090. return 0;
  1091. case RELAY_COMMAND_TRUNCATED:
  1092. if (!layer_hint) {
  1093. log_fn(LOG_PROTOCOL_WARN, LD_EXIT,
  1094. "'truncated' unsupported at non-origin. Dropping.");
  1095. return 0;
  1096. }
  1097. circuit_truncated(TO_ORIGIN_CIRCUIT(circ), layer_hint);
  1098. return 0;
  1099. case RELAY_COMMAND_CONNECTED:
  1100. if (conn) {
  1101. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1102. "'connected' unsupported while open. Closing circ.");
  1103. return -END_CIRC_REASON_TORPROTOCOL;
  1104. }
  1105. log_info(domain,
  1106. "'connected' received, no conn attached anymore. Ignoring.");
  1107. return 0;
  1108. case RELAY_COMMAND_SENDME:
  1109. if (!conn) {
  1110. if (layer_hint) {
  1111. layer_hint->package_window += CIRCWINDOW_INCREMENT;
  1112. log_debug(LD_APP,"circ-level sendme at origin, packagewindow %d.",
  1113. layer_hint->package_window);
  1114. circuit_resume_edge_reading(circ, layer_hint);
  1115. } else {
  1116. circ->package_window += CIRCWINDOW_INCREMENT;
  1117. log_debug(LD_APP,
  1118. "circ-level sendme at non-origin, packagewindow %d.",
  1119. circ->package_window);
  1120. circuit_resume_edge_reading(circ, layer_hint);
  1121. }
  1122. return 0;
  1123. }
  1124. conn->package_window += STREAMWINDOW_INCREMENT;
  1125. log_debug(domain,"stream-level sendme, packagewindow now %d.",
  1126. conn->package_window);
  1127. connection_start_reading(TO_CONN(conn));
  1128. /* handle whatever might still be on the inbuf */
  1129. if (connection_edge_package_raw_inbuf(conn, 1) < 0) {
  1130. /* (We already sent an end cell if possible) */
  1131. connection_mark_for_close(TO_CONN(conn));
  1132. return 0;
  1133. }
  1134. return 0;
  1135. case RELAY_COMMAND_RESOLVE:
  1136. if (layer_hint) {
  1137. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  1138. "resolve request unsupported at AP; dropping.");
  1139. return 0;
  1140. } else if (conn) {
  1141. log_fn(LOG_PROTOCOL_WARN, domain,
  1142. "resolve request for known stream; dropping.");
  1143. return 0;
  1144. } else if (circ->purpose != CIRCUIT_PURPOSE_OR) {
  1145. log_fn(LOG_PROTOCOL_WARN, domain,
  1146. "resolve request on circ with purpose %d; dropping",
  1147. circ->purpose);
  1148. return 0;
  1149. }
  1150. connection_exit_begin_resolve(cell, TO_OR_CIRCUIT(circ));
  1151. return 0;
  1152. case RELAY_COMMAND_RESOLVED:
  1153. if (conn) {
  1154. log_fn(LOG_PROTOCOL_WARN, domain,
  1155. "'resolved' unsupported while open. Closing circ.");
  1156. return -END_CIRC_REASON_TORPROTOCOL;
  1157. }
  1158. log_info(domain,
  1159. "'resolved' received, no conn attached anymore. Ignoring.");
  1160. return 0;
  1161. case RELAY_COMMAND_ESTABLISH_INTRO:
  1162. case RELAY_COMMAND_ESTABLISH_RENDEZVOUS:
  1163. case RELAY_COMMAND_INTRODUCE1:
  1164. case RELAY_COMMAND_INTRODUCE2:
  1165. case RELAY_COMMAND_INTRODUCE_ACK:
  1166. case RELAY_COMMAND_RENDEZVOUS1:
  1167. case RELAY_COMMAND_RENDEZVOUS2:
  1168. case RELAY_COMMAND_INTRO_ESTABLISHED:
  1169. case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
  1170. rend_process_relay_cell(circ, layer_hint,
  1171. rh.command, rh.length,
  1172. cell->payload+RELAY_HEADER_SIZE);
  1173. return 0;
  1174. }
  1175. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1176. "Received unknown relay command %d. Perhaps the other side is using "
  1177. "a newer version of Tor? Dropping.",
  1178. rh.command);
  1179. return 0; /* for forward compatibility, don't kill the circuit */
  1180. }
  1181. /** How many relay_data cells have we built, ever? */
  1182. uint64_t stats_n_data_cells_packaged = 0;
  1183. /** How many bytes of data have we put in relay_data cells have we built,
  1184. * ever? This would be RELAY_PAYLOAD_SIZE*stats_n_data_cells_packaged if
  1185. * every relay cell we ever sent were completely full of data. */
  1186. uint64_t stats_n_data_bytes_packaged = 0;
  1187. /** How many relay_data cells have we received, ever? */
  1188. uint64_t stats_n_data_cells_received = 0;
  1189. /** How many bytes of data have we received relay_data cells, ever? This would
  1190. * be RELAY_PAYLOAD_SIZE*stats_n_data_cells_packaged if every relay cell we
  1191. * ever received were completely full of data. */
  1192. uint64_t stats_n_data_bytes_received = 0;
  1193. /** While conn->inbuf has an entire relay payload of bytes on it,
  1194. * and the appropriate package windows aren't empty, grab a cell
  1195. * and send it down the circuit.
  1196. *
  1197. * Return -1 (and send a RELAY_COMMAND_END cell if necessary) if conn should
  1198. * be marked for close, else return 0.
  1199. */
  1200. int
  1201. connection_edge_package_raw_inbuf(edge_connection_t *conn, int package_partial)
  1202. {
  1203. size_t amount_to_process, length;
  1204. char payload[CELL_PAYLOAD_SIZE];
  1205. circuit_t *circ;
  1206. unsigned domain = conn->cpath_layer ? LD_APP : LD_EXIT;
  1207. tor_assert(conn);
  1208. if (conn->_base.marked_for_close) {
  1209. log_warn(LD_BUG,
  1210. "called on conn that's already marked for close at %s:%d.",
  1211. conn->_base.marked_for_close_file, conn->_base.marked_for_close);
  1212. return 0;
  1213. }
  1214. repeat_connection_edge_package_raw_inbuf:
  1215. circ = circuit_get_by_edge_conn(conn);
  1216. if (!circ) {
  1217. log_info(domain,"conn has no circuit! Closing.");
  1218. conn->end_reason = END_STREAM_REASON_CANT_ATTACH;
  1219. return -1;
  1220. }
  1221. if (circuit_consider_stop_edge_reading(circ, conn->cpath_layer))
  1222. return 0;
  1223. if (conn->package_window <= 0) {
  1224. log_info(domain,"called with package_window %d. Skipping.",
  1225. conn->package_window);
  1226. connection_stop_reading(TO_CONN(conn));
  1227. return 0;
  1228. }
  1229. amount_to_process = buf_datalen(conn->_base.inbuf);
  1230. if (!amount_to_process)
  1231. return 0;
  1232. if (!package_partial && amount_to_process < RELAY_PAYLOAD_SIZE)
  1233. return 0;
  1234. if (amount_to_process > RELAY_PAYLOAD_SIZE) {
  1235. length = RELAY_PAYLOAD_SIZE;
  1236. } else {
  1237. length = amount_to_process;
  1238. }
  1239. stats_n_data_bytes_packaged += length;
  1240. stats_n_data_cells_packaged += 1;
  1241. connection_fetch_from_buf(payload, length, TO_CONN(conn));
  1242. log_debug(domain,"(%d) Packaging %d bytes (%d waiting).", conn->_base.s,
  1243. (int)length, (int)buf_datalen(conn->_base.inbuf));
  1244. if (connection_edge_send_command(conn, RELAY_COMMAND_DATA,
  1245. payload, length) < 0 )
  1246. /* circuit got marked for close, don't continue, don't need to mark conn */
  1247. return 0;
  1248. if (!conn->cpath_layer) { /* non-rendezvous exit */
  1249. tor_assert(circ->package_window > 0);
  1250. circ->package_window--;
  1251. } else { /* we're an AP, or an exit on a rendezvous circ */
  1252. tor_assert(conn->cpath_layer->package_window > 0);
  1253. conn->cpath_layer->package_window--;
  1254. }
  1255. if (--conn->package_window <= 0) { /* is it 0 after decrement? */
  1256. connection_stop_reading(TO_CONN(conn));
  1257. log_debug(domain,"conn->package_window reached 0.");
  1258. circuit_consider_stop_edge_reading(circ, conn->cpath_layer);
  1259. return 0; /* don't process the inbuf any more */
  1260. }
  1261. log_debug(domain,"conn->package_window is now %d",conn->package_window);
  1262. /* handle more if there's more, or return 0 if there isn't */
  1263. goto repeat_connection_edge_package_raw_inbuf;
  1264. }
  1265. /** Called when we've just received a relay data cell, or when
  1266. * we've just finished flushing all bytes to stream <b>conn</b>.
  1267. *
  1268. * If conn->outbuf is not too full, and our deliver window is
  1269. * low, send back a suitable number of stream-level sendme cells.
  1270. */
  1271. void
  1272. connection_edge_consider_sending_sendme(edge_connection_t *conn)
  1273. {
  1274. circuit_t *circ;
  1275. if (connection_outbuf_too_full(TO_CONN(conn)))
  1276. return;
  1277. circ = circuit_get_by_edge_conn(conn);
  1278. if (!circ) {
  1279. /* this can legitimately happen if the destroy has already
  1280. * arrived and torn down the circuit */
  1281. log_info(LD_APP,"No circuit associated with conn. Skipping.");
  1282. return;
  1283. }
  1284. while (conn->deliver_window <= STREAMWINDOW_START - STREAMWINDOW_INCREMENT) {
  1285. log_debug(conn->cpath_layer?LD_APP:LD_EXIT,
  1286. "Outbuf %d, Queuing stream sendme.",
  1287. (int)conn->_base.outbuf_flushlen);
  1288. conn->deliver_window += STREAMWINDOW_INCREMENT;
  1289. if (connection_edge_send_command(conn, RELAY_COMMAND_SENDME,
  1290. NULL, 0) < 0) {
  1291. log_warn(LD_APP,"connection_edge_send_command failed. Skipping.");
  1292. return; /* the circuit's closed, don't continue */
  1293. }
  1294. }
  1295. }
  1296. /** The circuit <b>circ</b> has received a circuit-level sendme
  1297. * (on hop <b>layer_hint</b>, if we're the OP). Go through all the
  1298. * attached streams and let them resume reading and packaging, if
  1299. * their stream windows allow it.
  1300. */
  1301. static void
  1302. circuit_resume_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
  1303. {
  1304. log_debug(layer_hint?LD_APP:LD_EXIT,"resuming");
  1305. if (CIRCUIT_IS_ORIGIN(circ))
  1306. circuit_resume_edge_reading_helper(TO_ORIGIN_CIRCUIT(circ)->p_streams,
  1307. circ, layer_hint);
  1308. else
  1309. circuit_resume_edge_reading_helper(TO_OR_CIRCUIT(circ)->n_streams,
  1310. circ, layer_hint);
  1311. }
  1312. /** A helper function for circuit_resume_edge_reading() above.
  1313. * The arguments are the same, except that <b>conn</b> is the head
  1314. * of a linked list of edge streams that should each be considered.
  1315. */
  1316. static int
  1317. circuit_resume_edge_reading_helper(edge_connection_t *conn,
  1318. circuit_t *circ,
  1319. crypt_path_t *layer_hint)
  1320. {
  1321. for ( ; conn; conn=conn->next_stream) {
  1322. if (conn->_base.marked_for_close)
  1323. continue;
  1324. if ((!layer_hint && conn->package_window > 0) ||
  1325. (layer_hint && conn->package_window > 0 &&
  1326. conn->cpath_layer == layer_hint)) {
  1327. connection_start_reading(TO_CONN(conn));
  1328. /* handle whatever might still be on the inbuf */
  1329. if (connection_edge_package_raw_inbuf(conn, 1)<0) {
  1330. /* (We already sent an end cell if possible) */
  1331. connection_mark_for_close(TO_CONN(conn));
  1332. continue;
  1333. }
  1334. /* If the circuit won't accept any more data, return without looking
  1335. * at any more of the streams. Any connections that should be stopped
  1336. * have already been stopped by connection_edge_package_raw_inbuf. */
  1337. if (circuit_consider_stop_edge_reading(circ, layer_hint))
  1338. return -1;
  1339. }
  1340. }
  1341. return 0;
  1342. }
  1343. /** Check if the package window for <b>circ</b> is empty (at
  1344. * hop <b>layer_hint</b> if it's defined).
  1345. *
  1346. * If yes, tell edge streams to stop reading and return 1.
  1347. * Else return 0.
  1348. */
  1349. static int
  1350. circuit_consider_stop_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
  1351. {
  1352. edge_connection_t *conn = NULL;
  1353. unsigned domain = layer_hint ? LD_APP : LD_EXIT;
  1354. if (!layer_hint) {
  1355. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  1356. log_debug(domain,"considering circ->package_window %d",
  1357. circ->package_window);
  1358. if (circ->package_window <= 0) {
  1359. log_debug(domain,"yes, not-at-origin. stopped.");
  1360. for (conn = or_circ->n_streams; conn; conn=conn->next_stream)
  1361. connection_stop_reading(TO_CONN(conn));
  1362. return 1;
  1363. }
  1364. return 0;
  1365. }
  1366. /* else, layer hint is defined, use it */
  1367. log_debug(domain,"considering layer_hint->package_window %d",
  1368. layer_hint->package_window);
  1369. if (layer_hint->package_window <= 0) {
  1370. log_debug(domain,"yes, at-origin. stopped.");
  1371. for (conn = TO_ORIGIN_CIRCUIT(circ)->p_streams; conn;
  1372. conn=conn->next_stream)
  1373. if (conn->cpath_layer == layer_hint)
  1374. connection_stop_reading(TO_CONN(conn));
  1375. return 1;
  1376. }
  1377. return 0;
  1378. }
  1379. /** Check if the deliver_window for circuit <b>circ</b> (at hop
  1380. * <b>layer_hint</b> if it's defined) is low enough that we should
  1381. * send a circuit-level sendme back down the circuit. If so, send
  1382. * enough sendmes that the window would be overfull if we sent any
  1383. * more.
  1384. */
  1385. static void
  1386. circuit_consider_sending_sendme(circuit_t *circ, crypt_path_t *layer_hint)
  1387. {
  1388. // log_fn(LOG_INFO,"Considering: layer_hint is %s",
  1389. // layer_hint ? "defined" : "null");
  1390. while ((layer_hint ? layer_hint->deliver_window : circ->deliver_window) <=
  1391. CIRCWINDOW_START - CIRCWINDOW_INCREMENT) {
  1392. log_debug(LD_CIRC,"Queuing circuit sendme.");
  1393. if (layer_hint)
  1394. layer_hint->deliver_window += CIRCWINDOW_INCREMENT;
  1395. else
  1396. circ->deliver_window += CIRCWINDOW_INCREMENT;
  1397. if (relay_send_command_from_edge(0, circ, RELAY_COMMAND_SENDME,
  1398. NULL, 0, layer_hint) < 0) {
  1399. log_warn(LD_CIRC,
  1400. "relay_send_command_from_edge failed. Circuit's closed.");
  1401. return; /* the circuit's closed, don't continue */
  1402. }
  1403. }
  1404. }
  1405. /** Stop reading on edge connections when we have this many cells
  1406. * waiting on the appropriate queue. */
  1407. #define CELL_QUEUE_HIGHWATER_SIZE 256
  1408. /** Start reading from edge connections again when we get down to this many
  1409. * cells. */
  1410. #define CELL_QUEUE_LOWWATER_SIZE 64
  1411. #ifdef ACTIVE_CIRCUITS_PARANOIA
  1412. #define assert_active_circuits_ok_paranoid(conn) \
  1413. assert_active_circuits_ok(conn)
  1414. #else
  1415. #define assert_active_circuits_ok_paranoid(conn)
  1416. #endif
  1417. /** The total number of cells we have allocated from the memory pool. */
  1418. static int total_cells_allocated = 0;
  1419. /** A memory pool to allocate packed_cell_t objects. */
  1420. static mp_pool_t *cell_pool = NULL;
  1421. /** Memory pool to allocate insertion_time_elem_t objects used for cell
  1422. * statistics. */
  1423. static mp_pool_t *it_pool = NULL;
  1424. /** Allocate structures to hold cells. */
  1425. void
  1426. init_cell_pool(void)
  1427. {
  1428. tor_assert(!cell_pool);
  1429. cell_pool = mp_pool_new(sizeof(packed_cell_t), 128*1024);
  1430. }
  1431. /** Free all storage used to hold cells (and insertion times if we measure
  1432. * cell statistics). */
  1433. void
  1434. free_cell_pool(void)
  1435. {
  1436. /* Maybe we haven't called init_cell_pool yet; need to check for it. */
  1437. if (cell_pool) {
  1438. mp_pool_destroy(cell_pool);
  1439. cell_pool = NULL;
  1440. }
  1441. if (it_pool) {
  1442. mp_pool_destroy(it_pool);
  1443. it_pool = NULL;
  1444. }
  1445. }
  1446. /** Free excess storage in cell pool. */
  1447. void
  1448. clean_cell_pool(void)
  1449. {
  1450. tor_assert(cell_pool);
  1451. mp_pool_clean(cell_pool, 0, 1);
  1452. }
  1453. /** Release storage held by <b>cell</b>. */
  1454. static INLINE void
  1455. packed_cell_free_unchecked(packed_cell_t *cell)
  1456. {
  1457. --total_cells_allocated;
  1458. mp_pool_release(cell);
  1459. }
  1460. /** Allocate and return a new packed_cell_t. */
  1461. static INLINE packed_cell_t *
  1462. packed_cell_alloc(void)
  1463. {
  1464. ++total_cells_allocated;
  1465. return mp_pool_get(cell_pool);
  1466. }
  1467. /** Log current statistics for cell pool allocation at log level
  1468. * <b>severity</b>. */
  1469. void
  1470. dump_cell_pool_usage(int severity)
  1471. {
  1472. circuit_t *c;
  1473. int n_circs = 0;
  1474. int n_cells = 0;
  1475. for (c = _circuit_get_global_list(); c; c = c->next) {
  1476. n_cells += c->n_conn_cells.n;
  1477. if (!CIRCUIT_IS_ORIGIN(c))
  1478. n_cells += TO_OR_CIRCUIT(c)->p_conn_cells.n;
  1479. ++n_circs;
  1480. }
  1481. log(severity, LD_MM, "%d cells allocated on %d circuits. %d cells leaked.",
  1482. n_cells, n_circs, total_cells_allocated - n_cells);
  1483. mp_pool_log_status(cell_pool, severity);
  1484. }
  1485. /** Allocate a new copy of packed <b>cell</b>. */
  1486. static INLINE packed_cell_t *
  1487. packed_cell_copy(const cell_t *cell)
  1488. {
  1489. packed_cell_t *c = packed_cell_alloc();
  1490. cell_pack(c, cell);
  1491. c->next = NULL;
  1492. return c;
  1493. }
  1494. /** Append <b>cell</b> to the end of <b>queue</b>. */
  1495. void
  1496. cell_queue_append(cell_queue_t *queue, packed_cell_t *cell)
  1497. {
  1498. if (queue->tail) {
  1499. tor_assert(!queue->tail->next);
  1500. queue->tail->next = cell;
  1501. } else {
  1502. queue->head = cell;
  1503. }
  1504. queue->tail = cell;
  1505. cell->next = NULL;
  1506. ++queue->n;
  1507. }
  1508. /** Append a newly allocated copy of <b>cell</b> to the end of <b>queue</b> */
  1509. void
  1510. cell_queue_append_packed_copy(cell_queue_t *queue, const cell_t *cell)
  1511. {
  1512. packed_cell_t *copy = packed_cell_copy(cell);
  1513. /* Remember the time when this cell was put in the queue. */
  1514. if (get_options()->CellStatistics) {
  1515. struct timeval now;
  1516. uint32_t added;
  1517. insertion_time_queue_t *it_queue = queue->insertion_times;
  1518. if (!it_pool)
  1519. it_pool = mp_pool_new(sizeof(insertion_time_elem_t), 1024);
  1520. tor_gettimeofday_cached(&now);
  1521. #define SECONDS_IN_A_DAY 86400L
  1522. added = (uint32_t)(((now.tv_sec % SECONDS_IN_A_DAY) * 100L)
  1523. + ((uint32_t)now.tv_usec / (uint32_t)10000L));
  1524. if (!it_queue) {
  1525. it_queue = tor_malloc_zero(sizeof(insertion_time_queue_t));
  1526. queue->insertion_times = it_queue;
  1527. }
  1528. if (it_queue->last && it_queue->last->insertion_time == added) {
  1529. it_queue->last->counter++;
  1530. } else {
  1531. insertion_time_elem_t *elem = mp_pool_get(it_pool);
  1532. elem->next = NULL;
  1533. elem->insertion_time = added;
  1534. elem->counter = 1;
  1535. if (it_queue->last) {
  1536. it_queue->last->next = elem;
  1537. it_queue->last = elem;
  1538. } else {
  1539. it_queue->first = it_queue->last = elem;
  1540. }
  1541. }
  1542. }
  1543. cell_queue_append(queue, copy);
  1544. }
  1545. /** Remove and free every cell in <b>queue</b>. */
  1546. void
  1547. cell_queue_clear(cell_queue_t *queue)
  1548. {
  1549. packed_cell_t *cell, *next;
  1550. cell = queue->head;
  1551. while (cell) {
  1552. next = cell->next;
  1553. packed_cell_free_unchecked(cell);
  1554. cell = next;
  1555. }
  1556. queue->head = queue->tail = NULL;
  1557. queue->n = 0;
  1558. if (queue->insertion_times) {
  1559. while (queue->insertion_times->first) {
  1560. insertion_time_elem_t *elem = queue->insertion_times->first;
  1561. queue->insertion_times->first = elem->next;
  1562. mp_pool_release(elem);
  1563. }
  1564. tor_free(queue->insertion_times);
  1565. }
  1566. }
  1567. /** Extract and return the cell at the head of <b>queue</b>; return NULL if
  1568. * <b>queue</b> is empty. */
  1569. static INLINE packed_cell_t *
  1570. cell_queue_pop(cell_queue_t *queue)
  1571. {
  1572. packed_cell_t *cell = queue->head;
  1573. if (!cell)
  1574. return NULL;
  1575. queue->head = cell->next;
  1576. if (cell == queue->tail) {
  1577. tor_assert(!queue->head);
  1578. queue->tail = NULL;
  1579. }
  1580. --queue->n;
  1581. return cell;
  1582. }
  1583. /** Return a pointer to the "next_active_on_{n,p}_conn" pointer of <b>circ</b>,
  1584. * depending on whether <b>conn</b> matches n_conn or p_conn. */
  1585. static INLINE circuit_t **
  1586. next_circ_on_conn_p(circuit_t *circ, or_connection_t *conn)
  1587. {
  1588. tor_assert(circ);
  1589. tor_assert(conn);
  1590. if (conn == circ->n_conn) {
  1591. return &circ->next_active_on_n_conn;
  1592. } else {
  1593. or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
  1594. tor_assert(conn == orcirc->p_conn);
  1595. return &orcirc->next_active_on_p_conn;
  1596. }
  1597. }
  1598. /** Return a pointer to the "prev_active_on_{n,p}_conn" pointer of <b>circ</b>,
  1599. * depending on whether <b>conn</b> matches n_conn or p_conn. */
  1600. static INLINE circuit_t **
  1601. prev_circ_on_conn_p(circuit_t *circ, or_connection_t *conn)
  1602. {
  1603. tor_assert(circ);
  1604. tor_assert(conn);
  1605. if (conn == circ->n_conn) {
  1606. return &circ->prev_active_on_n_conn;
  1607. } else {
  1608. or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
  1609. tor_assert(conn == orcirc->p_conn);
  1610. return &orcirc->prev_active_on_p_conn;
  1611. }
  1612. }
  1613. /** Helper for sorting cell_ewma_t values in their priority queue. */
  1614. static int
  1615. compare_cell_ewma_counts(const void *p1, const void *p2)
  1616. {
  1617. const cell_ewma_t *e1=p1, *e2=p2;
  1618. if (e1->cell_count < e2->cell_count)
  1619. return -1;
  1620. else if (e1->cell_count > e2->cell_count)
  1621. return 1;
  1622. else
  1623. return 0;
  1624. }
  1625. /** Given a cell_ewma_t, return a pointer to the circuit containing it. */
  1626. static circuit_t *
  1627. cell_ewma_to_circuit(cell_ewma_t *ewma)
  1628. {
  1629. if (ewma->is_for_p_conn) {
  1630. /* This is an or_circuit_t's p_cell_ewma. */
  1631. or_circuit_t *orcirc = SUBTYPE_P(ewma, or_circuit_t, p_cell_ewma);
  1632. return TO_CIRCUIT(orcirc);
  1633. } else {
  1634. /* This is some circuit's n_cell_ewma. */
  1635. return SUBTYPE_P(ewma, circuit_t, n_cell_ewma);
  1636. }
  1637. }
  1638. /* ==== Functions for scaling cell_ewma_t ====
  1639. When choosing which cells to relay first, we favor circuits that have been
  1640. quiet recently. This gives better latency on connections that aren't
  1641. pushing lots of data, and makes the network feel more interactive.
  1642. Conceptually, we take an exponentially weighted mean average of the number
  1643. of cells a circuit has sent, and allow active circuits (those with cells to
  1644. relay) to send cells in reverse order of their exponentially-weighted mean
  1645. average (EWMA) cell count. [That is, a cell sent N seconds ago 'counts'
  1646. F^N times as much as a cell sent now, for 0<F<1.0, and we favor the
  1647. circuit that has sent the fewest cells]
  1648. If 'double' had infinite precision, we could do this simply by counting a
  1649. cell sent at startup as having weight 1.0, and a cell sent N seconds later
  1650. as having weight F^-N. This way, we would never need to re-scale
  1651. any already-sent cells.
  1652. To prevent double from overflowing, we could count a cell sent now as
  1653. having weight 1.0 and a cell sent N seconds ago as having weight F^N.
  1654. This, however, would mean we'd need to re-scale *ALL* old circuits every
  1655. time we wanted to send a cell.
  1656. So as a compromise, we divide time into 'ticks' (currently, 10-second
  1657. increments) and say that a cell sent at the start of a current tick is
  1658. worth 1.0, a cell sent N seconds before the start of the current tick is
  1659. worth F^N, and a cell sent N seconds after the start of the current tick is
  1660. worth F^-N. This way we don't overflow, and we don't need to constantly
  1661. rescale.
  1662. */
  1663. /** How long does a tick last (seconds)? */
  1664. #define EWMA_TICK_LEN 10
  1665. /** The default per-tick scale factor, if it hasn't been overridden by a
  1666. * consensus or a configuration setting. zero means "disabled". */
  1667. #define EWMA_DEFAULT_HALFLIFE 0.0
  1668. /** Given a timeval <b>now</b>, compute the cell_ewma tick in which it occurs
  1669. * and the fraction of the tick that has elapsed between the start of the tick
  1670. * and <b>now</b>. Return the former and store the latter in
  1671. * *<b>remainder_out</b>.
  1672. *
  1673. * These tick values are not meant to be shared between Tor instances, or used
  1674. * for other purposes. */
  1675. static unsigned
  1676. cell_ewma_tick_from_timeval(const struct timeval *now,
  1677. double *remainder_out)
  1678. {
  1679. unsigned res = (unsigned) (now->tv_sec / EWMA_TICK_LEN);
  1680. /* rem */
  1681. double rem = (now->tv_sec % EWMA_TICK_LEN) +
  1682. ((double)(now->tv_usec)) / 1.0e6;
  1683. *remainder_out = rem / EWMA_TICK_LEN;
  1684. return res;
  1685. }
  1686. /** Compute and return the current cell_ewma tick. */
  1687. unsigned
  1688. cell_ewma_get_tick(void)
  1689. {
  1690. return ((unsigned)approx_time() / EWMA_TICK_LEN);
  1691. }
  1692. /** The per-tick scale factor to be used when computing cell-count EWMA
  1693. * values. (A cell sent N ticks before the start of the current tick
  1694. * has value ewma_scale_factor ** N.)
  1695. */
  1696. static double ewma_scale_factor = 0.1;
  1697. static int ewma_enabled = 0;
  1698. #define EPSILON 0.00001
  1699. #define LOG_ONEHALF -0.69314718055994529
  1700. /** Adjust the global cell scale factor based on <b>options</b> */
  1701. void
  1702. cell_ewma_set_scale_factor(or_options_t *options, networkstatus_t *consensus)
  1703. {
  1704. int32_t halflife_ms;
  1705. double halflife;
  1706. const char *source;
  1707. if (options && options->CircuitPriorityHalflife >= -EPSILON) {
  1708. halflife = options->CircuitPriorityHalflife;
  1709. source = "CircuitPriorityHalflife in configuration";
  1710. } else if (consensus &&
  1711. (halflife_ms = networkstatus_get_param(
  1712. consensus, "CircPriorityHalflifeMsec", -1) >= 0)) {
  1713. halflife = ((double)halflife_ms)/1000.0;
  1714. source = "CircPriorityHalflifeMsec in consensus";
  1715. } else {
  1716. halflife = EWMA_DEFAULT_HALFLIFE;
  1717. source = "Default value";
  1718. }
  1719. if (halflife <= EPSILON) {
  1720. /* The cell EWMA algorithm is disabled. */
  1721. ewma_scale_factor = 0.1;
  1722. ewma_enabled = 0;
  1723. log_info(LD_OR,
  1724. "Disabled cell_ewma algorithm because of value in %s",
  1725. source);
  1726. } else {
  1727. /* convert halflife into halflife-per-tick. */
  1728. halflife /= EWMA_TICK_LEN;
  1729. /* compute per-tick scale factor. */
  1730. ewma_scale_factor = exp( LOG_ONEHALF / halflife );
  1731. ewma_enabled = 1;
  1732. log_info(LD_OR,
  1733. "Enabled cell_ewma algorithm because of value in %s; "
  1734. "scale factor is %lf per %d seconds",
  1735. source, ewma_scale_factor, EWMA_TICK_LEN);
  1736. }
  1737. }
  1738. /** Return the multiplier necessary to convert the value of a cell sent in
  1739. * 'from_tick' to one sent in 'to_tick'. */
  1740. static INLINE double
  1741. get_scale_factor(unsigned from_tick, unsigned to_tick)
  1742. {
  1743. /* This math can wrap around, but that's okay: unsigned overflow is
  1744. well-defined */
  1745. int diff = (int)(to_tick - from_tick);
  1746. return pow(ewma_scale_factor, diff);
  1747. }
  1748. /** Adjust the cell count of <b>ewma</b> so that it is scaled with respect to
  1749. * <b>cur_tick</b> */
  1750. static void
  1751. scale_single_cell_ewma(cell_ewma_t *ewma, unsigned cur_tick)
  1752. {
  1753. double factor = get_scale_factor(ewma->last_adjusted_tick, cur_tick);
  1754. ewma->cell_count *= factor;
  1755. ewma->last_adjusted_tick = cur_tick;
  1756. }
  1757. /** Adjust the cell count of every active circuit on <b>conn</b> so
  1758. * that they are scaled with respect to <b>cur_tick</b> */
  1759. static void
  1760. scale_active_circuits(or_connection_t *conn, unsigned cur_tick)
  1761. {
  1762. double factor = get_scale_factor(
  1763. conn->active_circuit_pqueue_last_recalibrated,
  1764. cur_tick);
  1765. /** Ordinarily it isn't okay to change the value of an element in a heap,
  1766. * but it's okay here, since we are preserving the order. */
  1767. SMARTLIST_FOREACH(conn->active_circuit_pqueue, cell_ewma_t *, e, {
  1768. tor_assert(e->last_adjusted_tick ==
  1769. conn->active_circuit_pqueue_last_recalibrated);
  1770. e->cell_count *= factor;
  1771. e->last_adjusted_tick = cur_tick;
  1772. });
  1773. conn->active_circuit_pqueue_last_recalibrated = cur_tick;
  1774. }
  1775. /** Rescale <b>ewma</b> to the same scale as <b>conn</b>, and add it to
  1776. * <b>conn</b>'s priority queue of active circuits */
  1777. static void
  1778. add_cell_ewma_to_conn(or_connection_t *conn, cell_ewma_t *ewma)
  1779. {
  1780. tor_assert(ewma->heap_index == -1);
  1781. scale_single_cell_ewma(ewma,
  1782. conn->active_circuit_pqueue_last_recalibrated);
  1783. smartlist_pqueue_add(conn->active_circuit_pqueue,
  1784. compare_cell_ewma_counts,
  1785. STRUCT_OFFSET(cell_ewma_t, heap_index),
  1786. ewma);
  1787. }
  1788. /** Remove <b>ewma</b> from <b>conn</b>'s priority queue of active circuits */
  1789. static void
  1790. remove_cell_ewma_from_conn(or_connection_t *conn, cell_ewma_t *ewma)
  1791. {
  1792. tor_assert(ewma->heap_index != -1);
  1793. smartlist_pqueue_remove(conn->active_circuit_pqueue,
  1794. compare_cell_ewma_counts,
  1795. STRUCT_OFFSET(cell_ewma_t, heap_index),
  1796. ewma);
  1797. }
  1798. /** Remove and return the first cell_ewma_t from conn's priority queue of
  1799. * active circuits. Requires that the priority queue is nonempty. */
  1800. static cell_ewma_t *
  1801. pop_first_cell_ewma_from_conn(or_connection_t *conn)
  1802. {
  1803. return smartlist_pqueue_pop(conn->active_circuit_pqueue,
  1804. compare_cell_ewma_counts,
  1805. STRUCT_OFFSET(cell_ewma_t, heap_index));
  1806. }
  1807. /** Add <b>circ</b> to the list of circuits with pending cells on
  1808. * <b>conn</b>. No effect if <b>circ</b> is already linked. */
  1809. void
  1810. make_circuit_active_on_conn(circuit_t *circ, or_connection_t *conn)
  1811. {
  1812. circuit_t **nextp = next_circ_on_conn_p(circ, conn);
  1813. circuit_t **prevp = prev_circ_on_conn_p(circ, conn);
  1814. if (*nextp && *prevp) {
  1815. /* Already active. */
  1816. return;
  1817. }
  1818. assert_active_circuits_ok_paranoid(conn);
  1819. if (! conn->active_circuits) {
  1820. conn->active_circuits = circ;
  1821. *prevp = *nextp = circ;
  1822. } else {
  1823. circuit_t *head = conn->active_circuits;
  1824. circuit_t *old_tail = *prev_circ_on_conn_p(head, conn);
  1825. *next_circ_on_conn_p(old_tail, conn) = circ;
  1826. *nextp = head;
  1827. *prev_circ_on_conn_p(head, conn) = circ;
  1828. *prevp = old_tail;
  1829. }
  1830. if (circ->n_conn == conn) {
  1831. add_cell_ewma_to_conn(conn, &circ->n_cell_ewma);
  1832. } else {
  1833. or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
  1834. tor_assert(conn == orcirc->p_conn);
  1835. add_cell_ewma_to_conn(conn, &orcirc->p_cell_ewma);
  1836. }
  1837. assert_active_circuits_ok_paranoid(conn);
  1838. }
  1839. /** Remove <b>circ</b> from the list of circuits with pending cells on
  1840. * <b>conn</b>. No effect if <b>circ</b> is already unlinked. */
  1841. void
  1842. make_circuit_inactive_on_conn(circuit_t *circ, or_connection_t *conn)
  1843. {
  1844. circuit_t **nextp = next_circ_on_conn_p(circ, conn);
  1845. circuit_t **prevp = prev_circ_on_conn_p(circ, conn);
  1846. circuit_t *next = *nextp, *prev = *prevp;
  1847. if (!next && !prev) {
  1848. /* Already inactive. */
  1849. return;
  1850. }
  1851. assert_active_circuits_ok_paranoid(conn);
  1852. tor_assert(next && prev);
  1853. tor_assert(*prev_circ_on_conn_p(next, conn) == circ);
  1854. tor_assert(*next_circ_on_conn_p(prev, conn) == circ);
  1855. if (next == circ) {
  1856. conn->active_circuits = NULL;
  1857. } else {
  1858. *prev_circ_on_conn_p(next, conn) = prev;
  1859. *next_circ_on_conn_p(prev, conn) = next;
  1860. if (conn->active_circuits == circ)
  1861. conn->active_circuits = next;
  1862. }
  1863. *prevp = *nextp = NULL;
  1864. if (circ->n_conn == conn) {
  1865. remove_cell_ewma_from_conn(conn, &circ->n_cell_ewma);
  1866. } else {
  1867. or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
  1868. tor_assert(conn == orcirc->p_conn);
  1869. remove_cell_ewma_from_conn(conn, &orcirc->p_cell_ewma);
  1870. }
  1871. assert_active_circuits_ok_paranoid(conn);
  1872. }
  1873. /** Remove all circuits from the list of circuits with pending cells on
  1874. * <b>conn</b>. */
  1875. void
  1876. connection_or_unlink_all_active_circs(or_connection_t *orconn)
  1877. {
  1878. circuit_t *head = orconn->active_circuits;
  1879. circuit_t *cur = head;
  1880. if (! head)
  1881. return;
  1882. do {
  1883. circuit_t *next = *next_circ_on_conn_p(cur, orconn);
  1884. *prev_circ_on_conn_p(cur, orconn) = NULL;
  1885. *next_circ_on_conn_p(cur, orconn) = NULL;
  1886. cur = next;
  1887. } while (cur != head);
  1888. orconn->active_circuits = NULL;
  1889. SMARTLIST_FOREACH(orconn->active_circuit_pqueue, cell_ewma_t *, e,
  1890. e->heap_index = -1);
  1891. smartlist_clear(orconn->active_circuit_pqueue);
  1892. }
  1893. /** Block (if <b>block</b> is true) or unblock (if <b>block</b> is false)
  1894. * every edge connection that is using <b>circ</b> to write to <b>orconn</b>,
  1895. * and start or stop reading as appropriate. */
  1896. static void
  1897. set_streams_blocked_on_circ(circuit_t *circ, or_connection_t *orconn,
  1898. int block)
  1899. {
  1900. edge_connection_t *edge = NULL;
  1901. if (circ->n_conn == orconn) {
  1902. circ->streams_blocked_on_n_conn = block;
  1903. if (CIRCUIT_IS_ORIGIN(circ))
  1904. edge = TO_ORIGIN_CIRCUIT(circ)->p_streams;
  1905. } else {
  1906. circ->streams_blocked_on_p_conn = block;
  1907. tor_assert(!CIRCUIT_IS_ORIGIN(circ));
  1908. edge = TO_OR_CIRCUIT(circ)->n_streams;
  1909. }
  1910. for (; edge; edge = edge->next_stream) {
  1911. connection_t *conn = TO_CONN(edge);
  1912. edge->edge_blocked_on_circ = block;
  1913. if (!conn->read_event) {
  1914. /* This connection is a placeholder for something; probably a DNS
  1915. * request. It can't actually stop or start reading.*/
  1916. continue;
  1917. }
  1918. if (block) {
  1919. if (connection_is_reading(conn))
  1920. connection_stop_reading(conn);
  1921. } else {
  1922. /* Is this right? */
  1923. if (!connection_is_reading(conn))
  1924. connection_start_reading(conn);
  1925. }
  1926. }
  1927. }
  1928. /** Pull as many cells as possible (but no more than <b>max</b>) from the
  1929. * queue of the first active circuit on <b>conn</b>, and write them to
  1930. * <b>conn</b>-&gt;outbuf. Return the number of cells written. Advance
  1931. * the active circuit pointer to the next active circuit in the ring. */
  1932. int
  1933. connection_or_flush_from_first_active_circuit(or_connection_t *conn, int max,
  1934. time_t now)
  1935. {
  1936. int n_flushed;
  1937. cell_queue_t *queue;
  1938. circuit_t *circ;
  1939. int streams_blocked;
  1940. /* The current (hi-res) time */
  1941. struct timeval now_hires;
  1942. /* The EWMA cell counter for the circuit we're flushing. */
  1943. cell_ewma_t *cell_ewma = NULL;
  1944. double ewma_increment = -1;
  1945. circ = conn->active_circuits;
  1946. if (!circ) return 0;
  1947. assert_active_circuits_ok_paranoid(conn);
  1948. /* See if we're doing the ewma circuit selection algorithm. */
  1949. if (ewma_enabled) {
  1950. unsigned tick;
  1951. double fractional_tick;
  1952. tor_gettimeofday_cached(&now_hires);
  1953. tick = cell_ewma_tick_from_timeval(&now_hires, &fractional_tick);
  1954. if (tick != conn->active_circuit_pqueue_last_recalibrated) {
  1955. scale_active_circuits(conn, tick);
  1956. }
  1957. ewma_increment = pow(ewma_scale_factor, -fractional_tick);
  1958. cell_ewma = smartlist_get(conn->active_circuit_pqueue, 0);
  1959. circ = cell_ewma_to_circuit(cell_ewma);
  1960. }
  1961. if (circ->n_conn == conn) {
  1962. queue = &circ->n_conn_cells;
  1963. streams_blocked = circ->streams_blocked_on_n_conn;
  1964. } else {
  1965. queue = &TO_OR_CIRCUIT(circ)->p_conn_cells;
  1966. streams_blocked = circ->streams_blocked_on_p_conn;
  1967. }
  1968. tor_assert(*next_circ_on_conn_p(circ,conn));
  1969. for (n_flushed = 0; n_flushed < max && queue->head; ) {
  1970. packed_cell_t *cell = cell_queue_pop(queue);
  1971. tor_assert(*next_circ_on_conn_p(circ,conn));
  1972. /* Calculate the exact time that this cell has spent in the queue. */
  1973. if (get_options()->CellStatistics && !CIRCUIT_IS_ORIGIN(circ)) {
  1974. struct timeval now;
  1975. uint32_t flushed;
  1976. uint32_t cell_waiting_time;
  1977. insertion_time_queue_t *it_queue = queue->insertion_times;
  1978. tor_gettimeofday_cached(&now);
  1979. flushed = (uint32_t)((now.tv_sec % SECONDS_IN_A_DAY) * 100L +
  1980. (uint32_t)now.tv_usec / (uint32_t)10000L);
  1981. if (!it_queue || !it_queue->first) {
  1982. log_warn(LD_BUG, "Cannot determine insertion time of cell.");
  1983. } else {
  1984. or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
  1985. insertion_time_elem_t *elem = it_queue->first;
  1986. cell_waiting_time =
  1987. (uint32_t)((flushed * 10L + SECONDS_IN_A_DAY * 1000L -
  1988. elem->insertion_time * 10L) %
  1989. (SECONDS_IN_A_DAY * 1000L));
  1990. #undef SECONDS_IN_A_DAY
  1991. elem->counter--;
  1992. if (elem->counter < 1) {
  1993. it_queue->first = elem->next;
  1994. if (elem == it_queue->last)
  1995. it_queue->last = NULL;
  1996. mp_pool_release(elem);
  1997. }
  1998. orcirc->total_cell_waiting_time += cell_waiting_time;
  1999. orcirc->processed_cells++;
  2000. }
  2001. }
  2002. /* If we just flushed our queue and this circuit is used for a
  2003. * tunneled directory request, possibly advance its state. */
  2004. if (queue->n == 0 && TO_CONN(conn)->dirreq_id)
  2005. geoip_change_dirreq_state(TO_CONN(conn)->dirreq_id,
  2006. DIRREQ_TUNNELED,
  2007. DIRREQ_CIRC_QUEUE_FLUSHED);
  2008. connection_write_to_buf(cell->body, CELL_NETWORK_SIZE, TO_CONN(conn));
  2009. packed_cell_free_unchecked(cell);
  2010. ++n_flushed;
  2011. if (cell_ewma) {
  2012. cell_ewma_t *tmp;
  2013. cell_ewma->cell_count += ewma_increment;
  2014. /* We pop and re-add the cell_ewma_t here, not above, since we need to
  2015. * re-add it immediately to keep the priority queue consistent with
  2016. * the linked-list implementation */
  2017. tmp = pop_first_cell_ewma_from_conn(conn);
  2018. tor_assert(tmp == cell_ewma);
  2019. add_cell_ewma_to_conn(conn, cell_ewma);
  2020. }
  2021. if (circ != conn->active_circuits) {
  2022. /* If this happens, the current circuit just got made inactive by
  2023. * a call in connection_write_to_buf(). That's nothing to worry about:
  2024. * circuit_make_inactive_on_conn() already advanced conn->active_circuits
  2025. * for us.
  2026. */
  2027. assert_active_circuits_ok_paranoid(conn);
  2028. goto done;
  2029. }
  2030. }
  2031. tor_assert(*next_circ_on_conn_p(circ,conn));
  2032. assert_active_circuits_ok_paranoid(conn);
  2033. conn->active_circuits = *next_circ_on_conn_p(circ, conn);
  2034. /* Is the cell queue low enough to unblock all the streams that are waiting
  2035. * to write to this circuit? */
  2036. if (streams_blocked && queue->n <= CELL_QUEUE_LOWWATER_SIZE)
  2037. set_streams_blocked_on_circ(circ, conn, 0); /* unblock streams */
  2038. /* Did we just run out of cells on this circuit's queue? */
  2039. if (queue->n == 0) {
  2040. log_debug(LD_GENERAL, "Made a circuit inactive.");
  2041. make_circuit_inactive_on_conn(circ, conn);
  2042. }
  2043. done:
  2044. if (n_flushed)
  2045. conn->timestamp_last_added_nonpadding = now;
  2046. return n_flushed;
  2047. }
  2048. /** Add <b>cell</b> to the queue of <b>circ</b> writing to <b>orconn</b>
  2049. * transmitting in <b>direction</b>. */
  2050. void
  2051. append_cell_to_circuit_queue(circuit_t *circ, or_connection_t *orconn,
  2052. cell_t *cell, cell_direction_t direction)
  2053. {
  2054. cell_queue_t *queue;
  2055. int streams_blocked;
  2056. if (direction == CELL_DIRECTION_OUT) {
  2057. queue = &circ->n_conn_cells;
  2058. streams_blocked = circ->streams_blocked_on_n_conn;
  2059. } else {
  2060. or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
  2061. queue = &orcirc->p_conn_cells;
  2062. streams_blocked = circ->streams_blocked_on_p_conn;
  2063. }
  2064. if (cell->command == CELL_RELAY_EARLY && orconn->link_proto < 2) {
  2065. /* V1 connections don't understand RELAY_EARLY. */
  2066. cell->command = CELL_RELAY;
  2067. }
  2068. cell_queue_append_packed_copy(queue, cell);
  2069. /* If we have too many cells on the circuit, we should stop reading from
  2070. * the edge streams for a while. */
  2071. if (!streams_blocked && queue->n >= CELL_QUEUE_HIGHWATER_SIZE)
  2072. set_streams_blocked_on_circ(circ, orconn, 1); /* block streams */
  2073. if (queue->n == 1) {
  2074. /* This was the first cell added to the queue. We need to make this
  2075. * circuit active. */
  2076. log_debug(LD_GENERAL, "Made a circuit active.");
  2077. make_circuit_active_on_conn(circ, orconn);
  2078. }
  2079. if (! buf_datalen(orconn->_base.outbuf)) {
  2080. /* There is no data at all waiting to be sent on the outbuf. Add a
  2081. * cell, so that we can notice when it gets flushed, flushed_some can
  2082. * get called, and we can start putting more data onto the buffer then.
  2083. */
  2084. log_debug(LD_GENERAL, "Primed a buffer.");
  2085. connection_or_flush_from_first_active_circuit(orconn, 1, approx_time());
  2086. }
  2087. }
  2088. /** Append an encoded value of <b>addr</b> to <b>payload_out</b>, which must
  2089. * have at least 18 bytes of free space. The encoding is, as specified in
  2090. * tor-spec.txt:
  2091. * RESOLVED_TYPE_IPV4 or RESOLVED_TYPE_IPV6 [1 byte]
  2092. * LENGTH [1 byte]
  2093. * ADDRESS [length bytes]
  2094. * Return the number of bytes added, or -1 on error */
  2095. int
  2096. append_address_to_payload(char *payload_out, const tor_addr_t *addr)
  2097. {
  2098. uint32_t a;
  2099. switch (tor_addr_family(addr)) {
  2100. case AF_INET:
  2101. payload_out[0] = RESOLVED_TYPE_IPV4;
  2102. payload_out[1] = 4;
  2103. a = tor_addr_to_ipv4n(addr);
  2104. memcpy(payload_out+2, &a, 4);
  2105. return 6;
  2106. case AF_INET6:
  2107. payload_out[0] = RESOLVED_TYPE_IPV6;
  2108. payload_out[1] = 16;
  2109. memcpy(payload_out+2, tor_addr_to_in6_addr8(addr), 16);
  2110. return 18;
  2111. case AF_UNSPEC:
  2112. default:
  2113. return -1;
  2114. }
  2115. }
  2116. /** Given <b>payload_len</b> bytes at <b>payload</b>, starting with an address
  2117. * encoded as by append_address_to_payload(), try to decode the address into
  2118. * *<b>addr_out</b>. Return the next byte in the payload after the address on
  2119. * success, or NULL on failure. */
  2120. const char *
  2121. decode_address_from_payload(tor_addr_t *addr_out, const char *payload,
  2122. int payload_len)
  2123. {
  2124. if (payload_len < 2)
  2125. return NULL;
  2126. if (payload_len < 2+(uint8_t)payload[1])
  2127. return NULL;
  2128. switch (payload[0]) {
  2129. case RESOLVED_TYPE_IPV4:
  2130. if (payload[1] != 4)
  2131. return NULL;
  2132. tor_addr_from_ipv4n(addr_out, get_uint32(payload+2));
  2133. break;
  2134. case RESOLVED_TYPE_IPV6:
  2135. if (payload[1] != 16)
  2136. return NULL;
  2137. tor_addr_from_ipv6_bytes(addr_out, payload+2);
  2138. break;
  2139. default:
  2140. tor_addr_make_unspec(addr_out);
  2141. break;
  2142. }
  2143. return payload + 2 + (uint8_t)payload[1];
  2144. }
  2145. /** Fail with an assert if the active circuits ring on <b>orconn</b> is
  2146. * corrupt. */
  2147. void
  2148. assert_active_circuits_ok(or_connection_t *orconn)
  2149. {
  2150. circuit_t *head = orconn->active_circuits;
  2151. circuit_t *cur = head;
  2152. int n = 0;
  2153. if (! head)
  2154. return;
  2155. do {
  2156. circuit_t *next = *next_circ_on_conn_p(cur, orconn);
  2157. circuit_t *prev = *prev_circ_on_conn_p(cur, orconn);
  2158. cell_ewma_t *ewma;
  2159. tor_assert(next);
  2160. tor_assert(prev);
  2161. tor_assert(*next_circ_on_conn_p(prev, orconn) == cur);
  2162. tor_assert(*prev_circ_on_conn_p(next, orconn) == cur);
  2163. if (orconn == cur->n_conn) {
  2164. ewma = &cur->n_cell_ewma;
  2165. tor_assert(!ewma->is_for_p_conn);
  2166. } else {
  2167. ewma = &TO_OR_CIRCUIT(cur)->p_cell_ewma;
  2168. tor_assert(ewma->is_for_p_conn);
  2169. }
  2170. tor_assert(ewma->heap_index != -1);
  2171. tor_assert(ewma == smartlist_get(orconn->active_circuit_pqueue,
  2172. ewma->heap_index));
  2173. n++;
  2174. cur = next;
  2175. } while (cur != head);
  2176. tor_assert(n == smartlist_len(orconn->active_circuit_pqueue));
  2177. }