relay.c 92 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604
  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-2013, 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. #define RELAY_PRIVATE
  12. #include "or.h"
  13. #include "addressmap.h"
  14. #include "buffers.h"
  15. #include "channel.h"
  16. #include "circuitbuild.h"
  17. #include "circuitlist.h"
  18. #include "config.h"
  19. #include "connection.h"
  20. #include "connection_edge.h"
  21. #include "connection_or.h"
  22. #include "control.h"
  23. #include "geoip.h"
  24. #include "main.h"
  25. #include "mempool.h"
  26. #include "networkstatus.h"
  27. #include "nodelist.h"
  28. #include "onion.h"
  29. #include "policies.h"
  30. #include "reasons.h"
  31. #include "relay.h"
  32. #include "rendcommon.h"
  33. #include "router.h"
  34. #include "routerlist.h"
  35. #include "routerparse.h"
  36. static edge_connection_t *relay_lookup_conn(circuit_t *circ, cell_t *cell,
  37. cell_direction_t cell_direction,
  38. crypt_path_t *layer_hint);
  39. static int connection_edge_process_relay_cell(cell_t *cell, circuit_t *circ,
  40. edge_connection_t *conn,
  41. crypt_path_t *layer_hint);
  42. static void circuit_consider_sending_sendme(circuit_t *circ,
  43. crypt_path_t *layer_hint);
  44. static void circuit_resume_edge_reading(circuit_t *circ,
  45. crypt_path_t *layer_hint);
  46. static int circuit_resume_edge_reading_helper(edge_connection_t *conn,
  47. circuit_t *circ,
  48. crypt_path_t *layer_hint);
  49. static int circuit_consider_stop_edge_reading(circuit_t *circ,
  50. crypt_path_t *layer_hint);
  51. static int circuit_queue_streams_are_blocked(circuit_t *circ);
  52. static void adjust_exit_policy_from_exitpolicy_failure(origin_circuit_t *circ,
  53. entry_connection_t *conn,
  54. node_t *node,
  55. const tor_addr_t *addr);
  56. /** Stop reading on edge connections when we have this many cells
  57. * waiting on the appropriate queue. */
  58. #define CELL_QUEUE_HIGHWATER_SIZE 256
  59. /** Start reading from edge connections again when we get down to this many
  60. * cells. */
  61. #define CELL_QUEUE_LOWWATER_SIZE 64
  62. /** Stats: how many relay cells have originated at this hop, or have
  63. * been relayed onward (not recognized at this hop)?
  64. */
  65. uint64_t stats_n_relay_cells_relayed = 0;
  66. /** Stats: how many relay cells have been delivered to streams at this
  67. * hop?
  68. */
  69. uint64_t stats_n_relay_cells_delivered = 0;
  70. /** Used to tell which stream to read from first on a circuit. */
  71. static tor_weak_rng_t stream_choice_rng = TOR_WEAK_RNG_INIT;
  72. /** Update digest from the payload of cell. Assign integrity part to
  73. * cell.
  74. */
  75. static void
  76. relay_set_digest(crypto_digest_t *digest, cell_t *cell)
  77. {
  78. char integrity[4];
  79. relay_header_t rh;
  80. crypto_digest_add_bytes(digest, (char*)cell->payload, CELL_PAYLOAD_SIZE);
  81. crypto_digest_get_digest(digest, integrity, 4);
  82. // log_fn(LOG_DEBUG,"Putting digest of %u %u %u %u into relay cell.",
  83. // integrity[0], integrity[1], integrity[2], integrity[3]);
  84. relay_header_unpack(&rh, cell->payload);
  85. memcpy(rh.integrity, integrity, 4);
  86. relay_header_pack(cell->payload, &rh);
  87. }
  88. /** Does the digest for this circuit indicate that this cell is for us?
  89. *
  90. * Update digest from the payload of cell (with the integrity part set
  91. * to 0). If the integrity part is valid, return 1, else restore digest
  92. * and cell to their original state and return 0.
  93. */
  94. static int
  95. relay_digest_matches(crypto_digest_t *digest, cell_t *cell)
  96. {
  97. char received_integrity[4], calculated_integrity[4];
  98. relay_header_t rh;
  99. crypto_digest_t *backup_digest=NULL;
  100. backup_digest = crypto_digest_dup(digest);
  101. relay_header_unpack(&rh, cell->payload);
  102. memcpy(received_integrity, rh.integrity, 4);
  103. memset(rh.integrity, 0, 4);
  104. relay_header_pack(cell->payload, &rh);
  105. // log_fn(LOG_DEBUG,"Reading digest of %u %u %u %u from relay cell.",
  106. // received_integrity[0], received_integrity[1],
  107. // received_integrity[2], received_integrity[3]);
  108. crypto_digest_add_bytes(digest, (char*) cell->payload, CELL_PAYLOAD_SIZE);
  109. crypto_digest_get_digest(digest, calculated_integrity, 4);
  110. if (tor_memneq(received_integrity, calculated_integrity, 4)) {
  111. // log_fn(LOG_INFO,"Recognized=0 but bad digest. Not recognizing.");
  112. // (%d vs %d).", received_integrity, calculated_integrity);
  113. /* restore digest to its old form */
  114. crypto_digest_assign(digest, backup_digest);
  115. /* restore the relay header */
  116. memcpy(rh.integrity, received_integrity, 4);
  117. relay_header_pack(cell->payload, &rh);
  118. crypto_digest_free(backup_digest);
  119. return 0;
  120. }
  121. crypto_digest_free(backup_digest);
  122. return 1;
  123. }
  124. /** Apply <b>cipher</b> to CELL_PAYLOAD_SIZE bytes of <b>in</b>
  125. * (in place).
  126. *
  127. * If <b>encrypt_mode</b> is 1 then encrypt, else decrypt.
  128. *
  129. * Return -1 if the crypto fails, else return 0.
  130. */
  131. static int
  132. relay_crypt_one_payload(crypto_cipher_t *cipher, uint8_t *in,
  133. int encrypt_mode)
  134. {
  135. int r;
  136. (void)encrypt_mode;
  137. r = crypto_cipher_crypt_inplace(cipher, (char*) in, CELL_PAYLOAD_SIZE);
  138. if (r) {
  139. log_warn(LD_BUG,"Error during relay encryption");
  140. return -1;
  141. }
  142. return 0;
  143. }
  144. /** Receive a relay cell:
  145. * - Crypt it (encrypt if headed toward the origin or if we <b>are</b> the
  146. * origin; decrypt if we're headed toward the exit).
  147. * - Check if recognized (if exitward).
  148. * - If recognized and the digest checks out, then find if there's a stream
  149. * that the cell is intended for, and deliver it to the right
  150. * connection_edge.
  151. * - If not recognized, then we need to relay it: append it to the appropriate
  152. * cell_queue on <b>circ</b>.
  153. *
  154. * Return -<b>reason</b> on failure.
  155. */
  156. int
  157. circuit_receive_relay_cell(cell_t *cell, circuit_t *circ,
  158. cell_direction_t cell_direction)
  159. {
  160. channel_t *chan = NULL;
  161. crypt_path_t *layer_hint=NULL;
  162. char recognized=0;
  163. int reason;
  164. tor_assert(cell);
  165. tor_assert(circ);
  166. tor_assert(cell_direction == CELL_DIRECTION_OUT ||
  167. cell_direction == CELL_DIRECTION_IN);
  168. if (circ->marked_for_close)
  169. return 0;
  170. if (relay_crypt(circ, cell, cell_direction, &layer_hint, &recognized) < 0) {
  171. log_warn(LD_BUG,"relay crypt failed. Dropping connection.");
  172. return -END_CIRC_REASON_INTERNAL;
  173. }
  174. if (recognized) {
  175. edge_connection_t *conn = NULL;
  176. if (circ->purpose == CIRCUIT_PURPOSE_PATH_BIAS_TESTING) {
  177. pathbias_check_probe_response(circ, cell);
  178. /* We need to drop this cell no matter what to avoid code that expects
  179. * a certain purpose (such as the hidserv code). */
  180. return 0;
  181. }
  182. conn = relay_lookup_conn(circ, cell, cell_direction,
  183. layer_hint);
  184. if (cell_direction == CELL_DIRECTION_OUT) {
  185. ++stats_n_relay_cells_delivered;
  186. log_debug(LD_OR,"Sending away from origin.");
  187. if ((reason=connection_edge_process_relay_cell(cell, circ, conn, NULL))
  188. < 0) {
  189. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  190. "connection_edge_process_relay_cell (away from origin) "
  191. "failed.");
  192. return reason;
  193. }
  194. }
  195. if (cell_direction == CELL_DIRECTION_IN) {
  196. ++stats_n_relay_cells_delivered;
  197. log_debug(LD_OR,"Sending to origin.");
  198. if ((reason = connection_edge_process_relay_cell(cell, circ, conn,
  199. layer_hint)) < 0) {
  200. log_warn(LD_OR,
  201. "connection_edge_process_relay_cell (at origin) failed.");
  202. return reason;
  203. }
  204. }
  205. return 0;
  206. }
  207. /* not recognized. pass it on. */
  208. if (cell_direction == CELL_DIRECTION_OUT) {
  209. cell->circ_id = circ->n_circ_id; /* switch it */
  210. chan = circ->n_chan;
  211. } else if (! CIRCUIT_IS_ORIGIN(circ)) {
  212. cell->circ_id = TO_OR_CIRCUIT(circ)->p_circ_id; /* switch it */
  213. chan = TO_OR_CIRCUIT(circ)->p_chan;
  214. } else {
  215. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  216. "Dropping unrecognized inbound cell on origin circuit.");
  217. /* If we see unrecognized cells on path bias testing circs,
  218. * it's bad mojo. Those circuits need to die.
  219. * XXX: Shouldn't they always die? */
  220. if (circ->purpose == CIRCUIT_PURPOSE_PATH_BIAS_TESTING) {
  221. TO_ORIGIN_CIRCUIT(circ)->path_state = PATH_STATE_USE_FAILED;
  222. return -END_CIRC_REASON_TORPROTOCOL;
  223. } else {
  224. return 0;
  225. }
  226. }
  227. if (!chan) {
  228. // XXXX Can this splice stuff be done more cleanly?
  229. if (! CIRCUIT_IS_ORIGIN(circ) &&
  230. TO_OR_CIRCUIT(circ)->rend_splice &&
  231. cell_direction == CELL_DIRECTION_OUT) {
  232. or_circuit_t *splice = TO_OR_CIRCUIT(circ)->rend_splice;
  233. tor_assert(circ->purpose == CIRCUIT_PURPOSE_REND_ESTABLISHED);
  234. tor_assert(splice->base_.purpose == CIRCUIT_PURPOSE_REND_ESTABLISHED);
  235. cell->circ_id = splice->p_circ_id;
  236. cell->command = CELL_RELAY; /* can't be relay_early anyway */
  237. if ((reason = circuit_receive_relay_cell(cell, TO_CIRCUIT(splice),
  238. CELL_DIRECTION_IN)) < 0) {
  239. log_warn(LD_REND, "Error relaying cell across rendezvous; closing "
  240. "circuits");
  241. /* XXXX Do this here, or just return -1? */
  242. circuit_mark_for_close(circ, -reason);
  243. return reason;
  244. }
  245. return 0;
  246. }
  247. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  248. "Didn't recognize cell, but circ stops here! Closing circ.");
  249. return -END_CIRC_REASON_TORPROTOCOL;
  250. }
  251. log_debug(LD_OR,"Passing on unrecognized cell.");
  252. ++stats_n_relay_cells_relayed; /* XXXX no longer quite accurate {cells}
  253. * we might kill the circ before we relay
  254. * the cells. */
  255. append_cell_to_circuit_queue(circ, chan, cell, cell_direction, 0);
  256. return 0;
  257. }
  258. /** Do the appropriate en/decryptions for <b>cell</b> arriving on
  259. * <b>circ</b> in direction <b>cell_direction</b>.
  260. *
  261. * If cell_direction == CELL_DIRECTION_IN:
  262. * - If we're at the origin (we're the OP), for hops 1..N,
  263. * decrypt cell. If recognized, stop.
  264. * - Else (we're not the OP), encrypt one hop. Cell is not recognized.
  265. *
  266. * If cell_direction == CELL_DIRECTION_OUT:
  267. * - decrypt one hop. Check if recognized.
  268. *
  269. * If cell is recognized, set *recognized to 1, and set
  270. * *layer_hint to the hop that recognized it.
  271. *
  272. * Return -1 to indicate that we should mark the circuit for close,
  273. * else return 0.
  274. */
  275. int
  276. relay_crypt(circuit_t *circ, cell_t *cell, cell_direction_t cell_direction,
  277. crypt_path_t **layer_hint, char *recognized)
  278. {
  279. relay_header_t rh;
  280. tor_assert(circ);
  281. tor_assert(cell);
  282. tor_assert(recognized);
  283. tor_assert(cell_direction == CELL_DIRECTION_IN ||
  284. cell_direction == CELL_DIRECTION_OUT);
  285. if (cell_direction == CELL_DIRECTION_IN) {
  286. if (CIRCUIT_IS_ORIGIN(circ)) { /* We're at the beginning of the circuit.
  287. * We'll want to do layered decrypts. */
  288. crypt_path_t *thishop, *cpath = TO_ORIGIN_CIRCUIT(circ)->cpath;
  289. thishop = cpath;
  290. if (thishop->state != CPATH_STATE_OPEN) {
  291. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  292. "Relay cell before first created cell? Closing.");
  293. return -1;
  294. }
  295. do { /* Remember: cpath is in forward order, that is, first hop first. */
  296. tor_assert(thishop);
  297. if (relay_crypt_one_payload(thishop->b_crypto, cell->payload, 0) < 0)
  298. return -1;
  299. relay_header_unpack(&rh, cell->payload);
  300. if (rh.recognized == 0) {
  301. /* it's possibly recognized. have to check digest to be sure. */
  302. if (relay_digest_matches(thishop->b_digest, cell)) {
  303. *recognized = 1;
  304. *layer_hint = thishop;
  305. return 0;
  306. }
  307. }
  308. thishop = thishop->next;
  309. } while (thishop != cpath && thishop->state == CPATH_STATE_OPEN);
  310. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  311. "Incoming cell at client not recognized. Closing.");
  312. return -1;
  313. } else { /* we're in the middle. Just one crypt. */
  314. if (relay_crypt_one_payload(TO_OR_CIRCUIT(circ)->p_crypto,
  315. cell->payload, 1) < 0)
  316. return -1;
  317. // log_fn(LOG_DEBUG,"Skipping recognized check, because we're not "
  318. // "the client.");
  319. }
  320. } else /* cell_direction == CELL_DIRECTION_OUT */ {
  321. /* we're in the middle. Just one crypt. */
  322. if (relay_crypt_one_payload(TO_OR_CIRCUIT(circ)->n_crypto,
  323. cell->payload, 0) < 0)
  324. return -1;
  325. relay_header_unpack(&rh, cell->payload);
  326. if (rh.recognized == 0) {
  327. /* it's possibly recognized. have to check digest to be sure. */
  328. if (relay_digest_matches(TO_OR_CIRCUIT(circ)->n_digest, cell)) {
  329. *recognized = 1;
  330. return 0;
  331. }
  332. }
  333. }
  334. return 0;
  335. }
  336. /** Package a relay cell from an edge:
  337. * - Encrypt it to the right layer
  338. * - Append it to the appropriate cell_queue on <b>circ</b>.
  339. */
  340. static int
  341. circuit_package_relay_cell(cell_t *cell, circuit_t *circ,
  342. cell_direction_t cell_direction,
  343. crypt_path_t *layer_hint, streamid_t on_stream)
  344. {
  345. channel_t *chan; /* where to send the cell */
  346. if (cell_direction == CELL_DIRECTION_OUT) {
  347. crypt_path_t *thishop; /* counter for repeated crypts */
  348. chan = circ->n_chan;
  349. if (!CIRCUIT_IS_ORIGIN(circ) || !chan) {
  350. log_warn(LD_BUG,"outgoing relay cell has n_chan==NULL. Dropping.");
  351. return 0; /* just drop it */
  352. }
  353. relay_set_digest(layer_hint->f_digest, cell);
  354. thishop = layer_hint;
  355. /* moving from farthest to nearest hop */
  356. do {
  357. tor_assert(thishop);
  358. /* XXXX RD This is a bug, right? */
  359. log_debug(LD_OR,"crypting a layer of the relay cell.");
  360. if (relay_crypt_one_payload(thishop->f_crypto, cell->payload, 1) < 0) {
  361. return -1;
  362. }
  363. thishop = thishop->prev;
  364. } while (thishop != TO_ORIGIN_CIRCUIT(circ)->cpath->prev);
  365. } else { /* incoming cell */
  366. or_circuit_t *or_circ;
  367. if (CIRCUIT_IS_ORIGIN(circ)) {
  368. /* We should never package an _incoming_ cell from the circuit
  369. * origin; that means we messed up somewhere. */
  370. log_warn(LD_BUG,"incoming relay cell at origin circuit. Dropping.");
  371. assert_circuit_ok(circ);
  372. return 0; /* just drop it */
  373. }
  374. or_circ = TO_OR_CIRCUIT(circ);
  375. chan = or_circ->p_chan;
  376. relay_set_digest(or_circ->p_digest, cell);
  377. if (relay_crypt_one_payload(or_circ->p_crypto, cell->payload, 1) < 0)
  378. return -1;
  379. }
  380. ++stats_n_relay_cells_relayed;
  381. append_cell_to_circuit_queue(circ, chan, cell, cell_direction, on_stream);
  382. return 0;
  383. }
  384. /** If cell's stream_id matches the stream_id of any conn that's
  385. * attached to circ, return that conn, else return NULL.
  386. */
  387. static edge_connection_t *
  388. relay_lookup_conn(circuit_t *circ, cell_t *cell,
  389. cell_direction_t cell_direction, crypt_path_t *layer_hint)
  390. {
  391. edge_connection_t *tmpconn;
  392. relay_header_t rh;
  393. relay_header_unpack(&rh, cell->payload);
  394. if (!rh.stream_id)
  395. return NULL;
  396. /* IN or OUT cells could have come from either direction, now
  397. * that we allow rendezvous *to* an OP.
  398. */
  399. if (CIRCUIT_IS_ORIGIN(circ)) {
  400. for (tmpconn = TO_ORIGIN_CIRCUIT(circ)->p_streams; tmpconn;
  401. tmpconn=tmpconn->next_stream) {
  402. if (rh.stream_id == tmpconn->stream_id &&
  403. !tmpconn->base_.marked_for_close &&
  404. tmpconn->cpath_layer == layer_hint) {
  405. log_debug(LD_APP,"found conn for stream %d.", rh.stream_id);
  406. return tmpconn;
  407. }
  408. }
  409. } else {
  410. for (tmpconn = TO_OR_CIRCUIT(circ)->n_streams; tmpconn;
  411. tmpconn=tmpconn->next_stream) {
  412. if (rh.stream_id == tmpconn->stream_id &&
  413. !tmpconn->base_.marked_for_close) {
  414. log_debug(LD_EXIT,"found conn for stream %d.", rh.stream_id);
  415. if (cell_direction == CELL_DIRECTION_OUT ||
  416. connection_edge_is_rendezvous_stream(tmpconn))
  417. return tmpconn;
  418. }
  419. }
  420. for (tmpconn = TO_OR_CIRCUIT(circ)->resolving_streams; tmpconn;
  421. tmpconn=tmpconn->next_stream) {
  422. if (rh.stream_id == tmpconn->stream_id &&
  423. !tmpconn->base_.marked_for_close) {
  424. log_debug(LD_EXIT,"found conn for stream %d.", rh.stream_id);
  425. return tmpconn;
  426. }
  427. }
  428. }
  429. return NULL; /* probably a begin relay cell */
  430. }
  431. /** Pack the relay_header_t host-order structure <b>src</b> into
  432. * network-order in the buffer <b>dest</b>. See tor-spec.txt for details
  433. * about the wire format.
  434. */
  435. void
  436. relay_header_pack(uint8_t *dest, const relay_header_t *src)
  437. {
  438. set_uint8(dest, src->command);
  439. set_uint16(dest+1, htons(src->recognized));
  440. set_uint16(dest+3, htons(src->stream_id));
  441. memcpy(dest+5, src->integrity, 4);
  442. set_uint16(dest+9, htons(src->length));
  443. }
  444. /** Unpack the network-order buffer <b>src</b> into a host-order
  445. * relay_header_t structure <b>dest</b>.
  446. */
  447. void
  448. relay_header_unpack(relay_header_t *dest, const uint8_t *src)
  449. {
  450. dest->command = get_uint8(src);
  451. dest->recognized = ntohs(get_uint16(src+1));
  452. dest->stream_id = ntohs(get_uint16(src+3));
  453. memcpy(dest->integrity, src+5, 4);
  454. dest->length = ntohs(get_uint16(src+9));
  455. }
  456. /** Convert the relay <b>command</b> into a human-readable string. */
  457. static const char *
  458. relay_command_to_string(uint8_t command)
  459. {
  460. switch (command) {
  461. case RELAY_COMMAND_BEGIN: return "BEGIN";
  462. case RELAY_COMMAND_DATA: return "DATA";
  463. case RELAY_COMMAND_END: return "END";
  464. case RELAY_COMMAND_CONNECTED: return "CONNECTED";
  465. case RELAY_COMMAND_SENDME: return "SENDME";
  466. case RELAY_COMMAND_EXTEND: return "EXTEND";
  467. case RELAY_COMMAND_EXTENDED: return "EXTENDED";
  468. case RELAY_COMMAND_TRUNCATE: return "TRUNCATE";
  469. case RELAY_COMMAND_TRUNCATED: return "TRUNCATED";
  470. case RELAY_COMMAND_DROP: return "DROP";
  471. case RELAY_COMMAND_RESOLVE: return "RESOLVE";
  472. case RELAY_COMMAND_RESOLVED: return "RESOLVED";
  473. case RELAY_COMMAND_BEGIN_DIR: return "BEGIN_DIR";
  474. case RELAY_COMMAND_ESTABLISH_INTRO: return "ESTABLISH_INTRO";
  475. case RELAY_COMMAND_ESTABLISH_RENDEZVOUS: return "ESTABLISH_RENDEZVOUS";
  476. case RELAY_COMMAND_INTRODUCE1: return "INTRODUCE1";
  477. case RELAY_COMMAND_INTRODUCE2: return "INTRODUCE2";
  478. case RELAY_COMMAND_RENDEZVOUS1: return "RENDEZVOUS1";
  479. case RELAY_COMMAND_RENDEZVOUS2: return "RENDEZVOUS2";
  480. case RELAY_COMMAND_INTRO_ESTABLISHED: return "INTRO_ESTABLISHED";
  481. case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
  482. return "RENDEZVOUS_ESTABLISHED";
  483. case RELAY_COMMAND_INTRODUCE_ACK: return "INTRODUCE_ACK";
  484. default: return "(unrecognized)";
  485. }
  486. }
  487. /** Make a relay cell out of <b>relay_command</b> and <b>payload</b>, and send
  488. * it onto the open circuit <b>circ</b>. <b>stream_id</b> is the ID on
  489. * <b>circ</b> for the stream that's sending the relay cell, or 0 if it's a
  490. * control cell. <b>cpath_layer</b> is NULL for OR->OP cells, or the
  491. * destination hop for OP->OR cells.
  492. *
  493. * If you can't send the cell, mark the circuit for close and return -1. Else
  494. * return 0.
  495. */
  496. int
  497. relay_send_command_from_edge(streamid_t stream_id, circuit_t *circ,
  498. uint8_t relay_command, const char *payload,
  499. size_t payload_len, crypt_path_t *cpath_layer)
  500. {
  501. cell_t cell;
  502. relay_header_t rh;
  503. cell_direction_t cell_direction;
  504. /* XXXX NM Split this function into a separate versions per circuit type? */
  505. tor_assert(circ);
  506. tor_assert(payload_len <= RELAY_PAYLOAD_SIZE);
  507. memset(&cell, 0, sizeof(cell_t));
  508. cell.command = CELL_RELAY;
  509. if (cpath_layer) {
  510. cell.circ_id = circ->n_circ_id;
  511. cell_direction = CELL_DIRECTION_OUT;
  512. } else if (! CIRCUIT_IS_ORIGIN(circ)) {
  513. cell.circ_id = TO_OR_CIRCUIT(circ)->p_circ_id;
  514. cell_direction = CELL_DIRECTION_IN;
  515. } else {
  516. return -1;
  517. }
  518. memset(&rh, 0, sizeof(rh));
  519. rh.command = relay_command;
  520. rh.stream_id = stream_id;
  521. rh.length = payload_len;
  522. relay_header_pack(cell.payload, &rh);
  523. if (payload_len)
  524. memcpy(cell.payload+RELAY_HEADER_SIZE, payload, payload_len);
  525. log_debug(LD_OR,"delivering %d cell %s.", relay_command,
  526. cell_direction == CELL_DIRECTION_OUT ? "forward" : "backward");
  527. /* If we are sending an END cell and this circuit is used for a tunneled
  528. * directory request, advance its state. */
  529. if (relay_command == RELAY_COMMAND_END && circ->dirreq_id)
  530. geoip_change_dirreq_state(circ->dirreq_id, DIRREQ_TUNNELED,
  531. DIRREQ_END_CELL_SENT);
  532. if (cell_direction == CELL_DIRECTION_OUT && circ->n_chan) {
  533. /* if we're using relaybandwidthrate, this conn wants priority */
  534. channel_timestamp_client(circ->n_chan);
  535. }
  536. if (cell_direction == CELL_DIRECTION_OUT) {
  537. origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
  538. if (origin_circ->remaining_relay_early_cells > 0 &&
  539. (relay_command == RELAY_COMMAND_EXTEND ||
  540. relay_command == RELAY_COMMAND_EXTEND2 ||
  541. cpath_layer != origin_circ->cpath)) {
  542. /* If we've got any relay_early cells left and (we're sending
  543. * an extend cell or we're not talking to the first hop), use
  544. * one of them. Don't worry about the conn protocol version:
  545. * append_cell_to_circuit_queue will fix it up. */
  546. cell.command = CELL_RELAY_EARLY;
  547. --origin_circ->remaining_relay_early_cells;
  548. log_debug(LD_OR, "Sending a RELAY_EARLY cell; %d remaining.",
  549. (int)origin_circ->remaining_relay_early_cells);
  550. /* Memorize the command that is sent as RELAY_EARLY cell; helps debug
  551. * task 878. */
  552. origin_circ->relay_early_commands[
  553. origin_circ->relay_early_cells_sent++] = relay_command;
  554. } else if (relay_command == RELAY_COMMAND_EXTEND ||
  555. relay_command == RELAY_COMMAND_EXTEND2) {
  556. /* If no RELAY_EARLY cells can be sent over this circuit, log which
  557. * commands have been sent as RELAY_EARLY cells before; helps debug
  558. * task 878. */
  559. smartlist_t *commands_list = smartlist_new();
  560. int i = 0;
  561. char *commands = NULL;
  562. for (; i < origin_circ->relay_early_cells_sent; i++)
  563. smartlist_add(commands_list, (char *)
  564. relay_command_to_string(origin_circ->relay_early_commands[i]));
  565. commands = smartlist_join_strings(commands_list, ",", 0, NULL);
  566. log_warn(LD_BUG, "Uh-oh. We're sending a RELAY_COMMAND_EXTEND cell, "
  567. "but we have run out of RELAY_EARLY cells on that circuit. "
  568. "Commands sent before: %s", commands);
  569. tor_free(commands);
  570. smartlist_free(commands_list);
  571. }
  572. }
  573. if (circuit_package_relay_cell(&cell, circ, cell_direction, cpath_layer,
  574. stream_id) < 0) {
  575. log_warn(LD_BUG,"circuit_package_relay_cell failed. Closing.");
  576. circuit_mark_for_close(circ, END_CIRC_REASON_INTERNAL);
  577. return -1;
  578. }
  579. return 0;
  580. }
  581. /** Make a relay cell out of <b>relay_command</b> and <b>payload</b>, and
  582. * send it onto the open circuit <b>circ</b>. <b>fromconn</b> is the stream
  583. * that's sending the relay cell, or NULL if it's a control cell.
  584. * <b>cpath_layer</b> is NULL for OR->OP cells, or the destination hop
  585. * for OP->OR cells.
  586. *
  587. * If you can't send the cell, mark the circuit for close and
  588. * return -1. Else return 0.
  589. */
  590. int
  591. connection_edge_send_command(edge_connection_t *fromconn,
  592. uint8_t relay_command, const char *payload,
  593. size_t payload_len)
  594. {
  595. /* XXXX NM Split this function into a separate versions per circuit type? */
  596. circuit_t *circ;
  597. crypt_path_t *cpath_layer = fromconn->cpath_layer;
  598. tor_assert(fromconn);
  599. circ = fromconn->on_circuit;
  600. if (fromconn->base_.marked_for_close) {
  601. log_warn(LD_BUG,
  602. "called on conn that's already marked for close at %s:%d.",
  603. fromconn->base_.marked_for_close_file,
  604. fromconn->base_.marked_for_close);
  605. return 0;
  606. }
  607. if (!circ) {
  608. if (fromconn->base_.type == CONN_TYPE_AP) {
  609. log_info(LD_APP,"no circ. Closing conn.");
  610. connection_mark_unattached_ap(EDGE_TO_ENTRY_CONN(fromconn),
  611. END_STREAM_REASON_INTERNAL);
  612. } else {
  613. log_info(LD_EXIT,"no circ. Closing conn.");
  614. fromconn->edge_has_sent_end = 1; /* no circ to send to */
  615. fromconn->end_reason = END_STREAM_REASON_INTERNAL;
  616. connection_mark_for_close(TO_CONN(fromconn));
  617. }
  618. return -1;
  619. }
  620. return relay_send_command_from_edge(fromconn->stream_id, circ,
  621. relay_command, payload,
  622. payload_len, cpath_layer);
  623. }
  624. /** How many times will I retry a stream that fails due to DNS
  625. * resolve failure or misc error?
  626. */
  627. #define MAX_RESOLVE_FAILURES 3
  628. /** Return 1 if reason is something that you should retry if you
  629. * get the end cell before you've connected; else return 0. */
  630. static int
  631. edge_reason_is_retriable(int reason)
  632. {
  633. return reason == END_STREAM_REASON_HIBERNATING ||
  634. reason == END_STREAM_REASON_RESOURCELIMIT ||
  635. reason == END_STREAM_REASON_EXITPOLICY ||
  636. reason == END_STREAM_REASON_RESOLVEFAILED ||
  637. reason == END_STREAM_REASON_MISC ||
  638. reason == END_STREAM_REASON_NOROUTE;
  639. }
  640. /** Called when we receive an END cell on a stream that isn't open yet,
  641. * from the client side.
  642. * Arguments are as for connection_edge_process_relay_cell().
  643. */
  644. static int
  645. connection_ap_process_end_not_open(
  646. relay_header_t *rh, cell_t *cell, origin_circuit_t *circ,
  647. entry_connection_t *conn, crypt_path_t *layer_hint)
  648. {
  649. node_t *exitrouter;
  650. int reason = *(cell->payload+RELAY_HEADER_SIZE);
  651. int control_reason;
  652. edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
  653. (void) layer_hint; /* unused */
  654. if (rh->length > 0) {
  655. if (reason == END_STREAM_REASON_TORPROTOCOL ||
  656. reason == END_STREAM_REASON_INTERNAL ||
  657. reason == END_STREAM_REASON_DESTROY) {
  658. /* All three of these reasons could mean a failed tag
  659. * hit the exit and it complained. Do not probe.
  660. * Fail the circuit. */
  661. circ->path_state = PATH_STATE_USE_FAILED;
  662. return -END_CIRC_REASON_TORPROTOCOL;
  663. } else {
  664. /* Path bias: If we get a valid reason code from the exit,
  665. * it wasn't due to tagging.
  666. *
  667. * We rely on recognized+digest being strong enough to make
  668. * tags unlikely to allow us to get tagged, yet 'recognized'
  669. * reason codes here. */
  670. pathbias_mark_use_success(circ);
  671. }
  672. }
  673. if (rh->length == 0) {
  674. reason = END_STREAM_REASON_MISC;
  675. }
  676. control_reason = reason | END_STREAM_REASON_FLAG_REMOTE;
  677. if (edge_reason_is_retriable(reason) &&
  678. /* avoid retry if rend */
  679. !connection_edge_is_rendezvous_stream(edge_conn)) {
  680. const char *chosen_exit_digest =
  681. circ->build_state->chosen_exit->identity_digest;
  682. log_info(LD_APP,"Address '%s' refused due to '%s'. Considering retrying.",
  683. safe_str(conn->socks_request->address),
  684. stream_end_reason_to_string(reason));
  685. exitrouter = node_get_mutable_by_id(chosen_exit_digest);
  686. switch (reason) {
  687. case END_STREAM_REASON_EXITPOLICY: {
  688. tor_addr_t addr;
  689. tor_addr_make_unspec(&addr);
  690. if (rh->length >= 5) {
  691. int ttl = -1;
  692. tor_addr_make_unspec(&addr);
  693. if (rh->length == 5 || rh->length == 9) {
  694. tor_addr_from_ipv4n(&addr,
  695. get_uint32(cell->payload+RELAY_HEADER_SIZE+1));
  696. if (rh->length == 9)
  697. ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+5));
  698. } else if (rh->length == 17 || rh->length == 21) {
  699. tor_addr_from_ipv6_bytes(&addr,
  700. (char*)(cell->payload+RELAY_HEADER_SIZE+1));
  701. if (rh->length == 21)
  702. ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+17));
  703. }
  704. if (tor_addr_is_null(&addr)) {
  705. log_info(LD_APP,"Address '%s' resolved to 0.0.0.0. Closing,",
  706. safe_str(conn->socks_request->address));
  707. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  708. return 0;
  709. }
  710. if ((tor_addr_family(&addr) == AF_INET && !conn->ipv4_traffic_ok) ||
  711. (tor_addr_family(&addr) == AF_INET6 && !conn->ipv6_traffic_ok)) {
  712. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  713. "Got an EXITPOLICY failure on a connection with a "
  714. "mismatched family. Closing.");
  715. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  716. return 0;
  717. }
  718. if (get_options()->ClientDNSRejectInternalAddresses &&
  719. tor_addr_is_internal(&addr, 0)) {
  720. log_info(LD_APP,"Address '%s' resolved to internal. Closing,",
  721. safe_str(conn->socks_request->address));
  722. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  723. return 0;
  724. }
  725. client_dns_set_addressmap(conn,
  726. conn->socks_request->address, &addr,
  727. conn->chosen_exit_name, ttl);
  728. {
  729. char new_addr[TOR_ADDR_BUF_LEN];
  730. tor_addr_to_str(new_addr, &addr, sizeof(new_addr), 1);
  731. if (strcmp(conn->socks_request->address, new_addr)) {
  732. strlcpy(conn->socks_request->address, new_addr,
  733. sizeof(conn->socks_request->address));
  734. control_event_stream_status(conn, STREAM_EVENT_REMAP, 0);
  735. }
  736. }
  737. }
  738. /* check if he *ought* to have allowed it */
  739. adjust_exit_policy_from_exitpolicy_failure(circ,
  740. conn,
  741. exitrouter,
  742. &addr);
  743. if (conn->chosen_exit_optional ||
  744. conn->chosen_exit_retries) {
  745. /* stop wanting a specific exit */
  746. conn->chosen_exit_optional = 0;
  747. /* A non-zero chosen_exit_retries can happen if we set a
  748. * TrackHostExits for this address under a port that the exit
  749. * relay allows, but then try the same address with a different
  750. * port that it doesn't allow to exit. We shouldn't unregister
  751. * the mapping, since it is probably still wanted on the
  752. * original port. But now we give away to the exit relay that
  753. * we probably have a TrackHostExits on it. So be it. */
  754. conn->chosen_exit_retries = 0;
  755. tor_free(conn->chosen_exit_name); /* clears it */
  756. }
  757. if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
  758. return 0;
  759. /* else, conn will get closed below */
  760. break;
  761. }
  762. case END_STREAM_REASON_CONNECTREFUSED:
  763. if (!conn->chosen_exit_optional)
  764. break; /* break means it'll close, below */
  765. /* Else fall through: expire this circuit, clear the
  766. * chosen_exit_name field, and try again. */
  767. case END_STREAM_REASON_RESOLVEFAILED:
  768. case END_STREAM_REASON_TIMEOUT:
  769. case END_STREAM_REASON_MISC:
  770. case END_STREAM_REASON_NOROUTE:
  771. if (client_dns_incr_failures(conn->socks_request->address)
  772. < MAX_RESOLVE_FAILURES) {
  773. /* We haven't retried too many times; reattach the connection. */
  774. circuit_log_path(LOG_INFO,LD_APP,circ);
  775. /* Mark this circuit "unusable for new streams". */
  776. /* XXXX024 this is a kludgy way to do this. */
  777. tor_assert(circ->base_.timestamp_dirty);
  778. circ->base_.timestamp_dirty -= get_options()->MaxCircuitDirtiness;
  779. if (conn->chosen_exit_optional) {
  780. /* stop wanting a specific exit */
  781. conn->chosen_exit_optional = 0;
  782. tor_free(conn->chosen_exit_name); /* clears it */
  783. }
  784. if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
  785. return 0;
  786. /* else, conn will get closed below */
  787. } else {
  788. log_notice(LD_APP,
  789. "Have tried resolving or connecting to address '%s' "
  790. "at %d different places. Giving up.",
  791. safe_str(conn->socks_request->address),
  792. MAX_RESOLVE_FAILURES);
  793. /* clear the failures, so it will have a full try next time */
  794. client_dns_clear_failures(conn->socks_request->address);
  795. }
  796. break;
  797. case END_STREAM_REASON_HIBERNATING:
  798. case END_STREAM_REASON_RESOURCELIMIT:
  799. if (exitrouter) {
  800. policies_set_node_exitpolicy_to_reject_all(exitrouter);
  801. }
  802. if (conn->chosen_exit_optional) {
  803. /* stop wanting a specific exit */
  804. conn->chosen_exit_optional = 0;
  805. tor_free(conn->chosen_exit_name); /* clears it */
  806. }
  807. if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
  808. return 0;
  809. /* else, will close below */
  810. break;
  811. } /* end switch */
  812. log_info(LD_APP,"Giving up on retrying; conn can't be handled.");
  813. }
  814. log_info(LD_APP,
  815. "Edge got end (%s) before we're connected. Marking for close.",
  816. stream_end_reason_to_string(rh->length > 0 ? reason : -1));
  817. circuit_log_path(LOG_INFO,LD_APP,circ);
  818. /* need to test because of detach_retriable */
  819. if (!ENTRY_TO_CONN(conn)->marked_for_close)
  820. connection_mark_unattached_ap(conn, control_reason);
  821. return 0;
  822. }
  823. /** Called when we have gotten an END_REASON_EXITPOLICY failure on <b>circ</b>
  824. * for <b>conn</b>, while attempting to connect via <b>node</b>. If the node
  825. * told us which address it rejected, then <b>addr</b> is that address;
  826. * otherwise it is AF_UNSPEC.
  827. *
  828. * If we are sure the node should have allowed this address, mark the node as
  829. * having a reject *:* exit policy. Otherwise, mark the circuit as unusable
  830. * for this particular address.
  831. **/
  832. static void
  833. adjust_exit_policy_from_exitpolicy_failure(origin_circuit_t *circ,
  834. entry_connection_t *conn,
  835. node_t *node,
  836. const tor_addr_t *addr)
  837. {
  838. int make_reject_all = 0;
  839. const sa_family_t family = tor_addr_family(addr);
  840. if (node) {
  841. tor_addr_t tmp;
  842. int asked_for_family = tor_addr_parse(&tmp, conn->socks_request->address);
  843. if (family == AF_UNSPEC) {
  844. make_reject_all = 1;
  845. } else if (node_exit_policy_is_exact(node, family) &&
  846. asked_for_family != -1 && !conn->chosen_exit_name) {
  847. make_reject_all = 1;
  848. }
  849. if (make_reject_all) {
  850. log_info(LD_APP,
  851. "Exitrouter %s seems to be more restrictive than its exit "
  852. "policy. Not using this router as exit for now.",
  853. node_describe(node));
  854. policies_set_node_exitpolicy_to_reject_all(node);
  855. }
  856. }
  857. if (family != AF_UNSPEC)
  858. addr_policy_append_reject_addr(&circ->prepend_policy, addr);
  859. }
  860. /** Helper: change the socks_request-&gt;address field on conn to the
  861. * dotted-quad representation of <b>new_addr</b>,
  862. * and send an appropriate REMAP event. */
  863. static void
  864. remap_event_helper(entry_connection_t *conn, const tor_addr_t *new_addr)
  865. {
  866. tor_addr_to_str(conn->socks_request->address, new_addr,
  867. sizeof(conn->socks_request->address),
  868. 1);
  869. control_event_stream_status(conn, STREAM_EVENT_REMAP,
  870. REMAP_STREAM_SOURCE_EXIT);
  871. }
  872. /** Extract the contents of a connected cell in <b>cell</b>, whose relay
  873. * header has already been parsed into <b>rh</b>. On success, set
  874. * <b>addr_out</b> to the address we're connected to, and <b>ttl_out</b> to
  875. * the ttl of that address, in seconds, and return 0. On failure, return
  876. * -1. */
  877. int
  878. connected_cell_parse(const relay_header_t *rh, const cell_t *cell,
  879. tor_addr_t *addr_out, int *ttl_out)
  880. {
  881. uint32_t bytes;
  882. const uint8_t *payload = cell->payload + RELAY_HEADER_SIZE;
  883. tor_addr_make_unspec(addr_out);
  884. *ttl_out = -1;
  885. if (rh->length == 0)
  886. return 0;
  887. if (rh->length < 4)
  888. return -1;
  889. bytes = ntohl(get_uint32(payload));
  890. /* If bytes is 0, this is maybe a v6 address. Otherwise it's a v4 address */
  891. if (bytes != 0) {
  892. /* v4 address */
  893. tor_addr_from_ipv4h(addr_out, bytes);
  894. if (rh->length >= 8) {
  895. bytes = ntohl(get_uint32(payload + 4));
  896. if (bytes <= INT32_MAX)
  897. *ttl_out = bytes;
  898. }
  899. } else {
  900. if (rh->length < 25) /* 4 bytes of 0s, 1 addr, 16 ipv4, 4 ttl. */
  901. return -1;
  902. if (get_uint8(payload + 4) != 6)
  903. return -1;
  904. tor_addr_from_ipv6_bytes(addr_out, (char*)(payload + 5));
  905. bytes = ntohl(get_uint32(payload + 21));
  906. if (bytes <= INT32_MAX)
  907. *ttl_out = (int) bytes;
  908. }
  909. return 0;
  910. }
  911. /** An incoming relay cell has arrived from circuit <b>circ</b> to
  912. * stream <b>conn</b>.
  913. *
  914. * The arguments here are the same as in
  915. * connection_edge_process_relay_cell() below; this function is called
  916. * from there when <b>conn</b> is defined and not in an open state.
  917. */
  918. static int
  919. connection_edge_process_relay_cell_not_open(
  920. relay_header_t *rh, cell_t *cell, circuit_t *circ,
  921. edge_connection_t *conn, crypt_path_t *layer_hint)
  922. {
  923. if (rh->command == RELAY_COMMAND_END) {
  924. if (CIRCUIT_IS_ORIGIN(circ) && conn->base_.type == CONN_TYPE_AP) {
  925. return connection_ap_process_end_not_open(rh, cell,
  926. TO_ORIGIN_CIRCUIT(circ),
  927. EDGE_TO_ENTRY_CONN(conn),
  928. layer_hint);
  929. } else {
  930. /* we just got an 'end', don't need to send one */
  931. conn->edge_has_sent_end = 1;
  932. conn->end_reason = *(cell->payload+RELAY_HEADER_SIZE) |
  933. END_STREAM_REASON_FLAG_REMOTE;
  934. connection_mark_for_close(TO_CONN(conn));
  935. return 0;
  936. }
  937. }
  938. if (conn->base_.type == CONN_TYPE_AP &&
  939. rh->command == RELAY_COMMAND_CONNECTED) {
  940. tor_addr_t addr;
  941. int ttl;
  942. entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
  943. tor_assert(CIRCUIT_IS_ORIGIN(circ));
  944. if (conn->base_.state != AP_CONN_STATE_CONNECT_WAIT) {
  945. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  946. "Got 'connected' while not in state connect_wait. Dropping.");
  947. return 0;
  948. }
  949. conn->base_.state = AP_CONN_STATE_OPEN;
  950. log_info(LD_APP,"'connected' received after %d seconds.",
  951. (int)(time(NULL) - conn->base_.timestamp_lastread));
  952. if (connected_cell_parse(rh, cell, &addr, &ttl) < 0) {
  953. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  954. "Got a badly formatted connected cell. Closing.");
  955. connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
  956. connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TORPROTOCOL);
  957. }
  958. if (tor_addr_family(&addr) != AF_UNSPEC) {
  959. const sa_family_t family = tor_addr_family(&addr);
  960. if (tor_addr_is_null(&addr) ||
  961. (get_options()->ClientDNSRejectInternalAddresses &&
  962. tor_addr_is_internal(&addr, 0))) {
  963. log_info(LD_APP, "...but it claims the IP address was %s. Closing.",
  964. fmt_addr(&addr));
  965. connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
  966. connection_mark_unattached_ap(entry_conn,
  967. END_STREAM_REASON_TORPROTOCOL);
  968. return 0;
  969. }
  970. if ((family == AF_INET && ! entry_conn->ipv4_traffic_ok) ||
  971. (family == AF_INET6 && ! entry_conn->ipv6_traffic_ok)) {
  972. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  973. "Got a connected cell to %s with unsupported address family."
  974. " Closing.", fmt_addr(&addr));
  975. connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
  976. connection_mark_unattached_ap(entry_conn,
  977. END_STREAM_REASON_TORPROTOCOL);
  978. return 0;
  979. }
  980. client_dns_set_addressmap(entry_conn,
  981. entry_conn->socks_request->address, &addr,
  982. entry_conn->chosen_exit_name, ttl);
  983. remap_event_helper(entry_conn, &addr);
  984. }
  985. circuit_log_path(LOG_INFO,LD_APP,TO_ORIGIN_CIRCUIT(circ));
  986. /* don't send a socks reply to transparent conns */
  987. tor_assert(entry_conn->socks_request != NULL);
  988. if (!entry_conn->socks_request->has_finished)
  989. connection_ap_handshake_socks_reply(entry_conn, NULL, 0, 0);
  990. /* Was it a linked dir conn? If so, a dir request just started to
  991. * fetch something; this could be a bootstrap status milestone. */
  992. log_debug(LD_APP, "considering");
  993. if (TO_CONN(conn)->linked_conn &&
  994. TO_CONN(conn)->linked_conn->type == CONN_TYPE_DIR) {
  995. connection_t *dirconn = TO_CONN(conn)->linked_conn;
  996. log_debug(LD_APP, "it is! %d", dirconn->purpose);
  997. switch (dirconn->purpose) {
  998. case DIR_PURPOSE_FETCH_CERTIFICATE:
  999. if (consensus_is_waiting_for_certs())
  1000. control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_KEYS, 0);
  1001. break;
  1002. case DIR_PURPOSE_FETCH_CONSENSUS:
  1003. control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_STATUS, 0);
  1004. break;
  1005. case DIR_PURPOSE_FETCH_SERVERDESC:
  1006. control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_DESCRIPTORS,
  1007. count_loading_descriptors_progress());
  1008. break;
  1009. }
  1010. }
  1011. /* This is definitely a success, so forget about any pending data we
  1012. * had sent. */
  1013. if (entry_conn->pending_optimistic_data) {
  1014. generic_buffer_free(entry_conn->pending_optimistic_data);
  1015. entry_conn->pending_optimistic_data = NULL;
  1016. }
  1017. /* handle anything that might have queued */
  1018. if (connection_edge_package_raw_inbuf(conn, 1, NULL) < 0) {
  1019. /* (We already sent an end cell if possible) */
  1020. connection_mark_for_close(TO_CONN(conn));
  1021. return 0;
  1022. }
  1023. return 0;
  1024. }
  1025. if (conn->base_.type == CONN_TYPE_AP &&
  1026. rh->command == RELAY_COMMAND_RESOLVED) {
  1027. int ttl;
  1028. int answer_len;
  1029. uint8_t answer_type;
  1030. entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
  1031. if (conn->base_.state != AP_CONN_STATE_RESOLVE_WAIT) {
  1032. log_fn(LOG_PROTOCOL_WARN, LD_APP, "Got a 'resolved' cell while "
  1033. "not in state resolve_wait. Dropping.");
  1034. return 0;
  1035. }
  1036. tor_assert(SOCKS_COMMAND_IS_RESOLVE(entry_conn->socks_request->command));
  1037. answer_len = cell->payload[RELAY_HEADER_SIZE+1];
  1038. if (rh->length < 2 || answer_len+2>rh->length) {
  1039. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1040. "Dropping malformed 'resolved' cell");
  1041. connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TORPROTOCOL);
  1042. return 0;
  1043. }
  1044. answer_type = cell->payload[RELAY_HEADER_SIZE];
  1045. if (rh->length >= answer_len+6)
  1046. ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+
  1047. 2+answer_len));
  1048. else
  1049. ttl = -1;
  1050. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
  1051. uint32_t addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+2));
  1052. if (get_options()->ClientDNSRejectInternalAddresses &&
  1053. is_internal_IP(addr, 0)) {
  1054. log_info(LD_APP,"Got a resolve with answer %s. Rejecting.",
  1055. fmt_addr32(addr));
  1056. connection_ap_handshake_socks_resolved(entry_conn,
  1057. RESOLVED_TYPE_ERROR_TRANSIENT,
  1058. 0, NULL, 0, TIME_MAX);
  1059. connection_mark_unattached_ap(entry_conn,
  1060. END_STREAM_REASON_TORPROTOCOL);
  1061. return 0;
  1062. }
  1063. }
  1064. connection_ap_handshake_socks_resolved(entry_conn,
  1065. answer_type,
  1066. cell->payload[RELAY_HEADER_SIZE+1], /*answer_len*/
  1067. cell->payload+RELAY_HEADER_SIZE+2, /*answer*/
  1068. ttl,
  1069. -1);
  1070. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
  1071. tor_addr_t addr;
  1072. tor_addr_from_ipv4n(&addr,
  1073. get_uint32(cell->payload+RELAY_HEADER_SIZE+2));
  1074. remap_event_helper(entry_conn, &addr);
  1075. } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
  1076. tor_addr_t addr;
  1077. tor_addr_from_ipv6_bytes(&addr,
  1078. (char*)(cell->payload+RELAY_HEADER_SIZE+2));
  1079. remap_event_helper(entry_conn, &addr);
  1080. }
  1081. connection_mark_unattached_ap(entry_conn,
  1082. END_STREAM_REASON_DONE |
  1083. END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
  1084. return 0;
  1085. }
  1086. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1087. "Got an unexpected relay command %d, in state %d (%s). Dropping.",
  1088. rh->command, conn->base_.state,
  1089. conn_state_to_string(conn->base_.type, conn->base_.state));
  1090. return 0; /* for forward compatibility, don't kill the circuit */
  1091. // connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
  1092. // connection_mark_for_close(conn);
  1093. // return -1;
  1094. }
  1095. /** An incoming relay cell has arrived on circuit <b>circ</b>. If
  1096. * <b>conn</b> is NULL this is a control cell, else <b>cell</b> is
  1097. * destined for <b>conn</b>.
  1098. *
  1099. * If <b>layer_hint</b> is defined, then we're the origin of the
  1100. * circuit, and it specifies the hop that packaged <b>cell</b>.
  1101. *
  1102. * Return -reason if you want to warn and tear down the circuit, else 0.
  1103. */
  1104. static int
  1105. connection_edge_process_relay_cell(cell_t *cell, circuit_t *circ,
  1106. edge_connection_t *conn,
  1107. crypt_path_t *layer_hint)
  1108. {
  1109. static int num_seen=0;
  1110. relay_header_t rh;
  1111. unsigned domain = layer_hint?LD_APP:LD_EXIT;
  1112. int reason;
  1113. int optimistic_data = 0; /* Set to 1 if we receive data on a stream
  1114. * that's in the EXIT_CONN_STATE_RESOLVING
  1115. * or EXIT_CONN_STATE_CONNECTING states. */
  1116. tor_assert(cell);
  1117. tor_assert(circ);
  1118. relay_header_unpack(&rh, cell->payload);
  1119. // log_fn(LOG_DEBUG,"command %d stream %d", rh.command, rh.stream_id);
  1120. num_seen++;
  1121. log_debug(domain, "Now seen %d relay cells here (command %d, stream %d).",
  1122. num_seen, rh.command, rh.stream_id);
  1123. if (rh.length > RELAY_PAYLOAD_SIZE) {
  1124. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1125. "Relay cell length field too long. Closing circuit.");
  1126. return - END_CIRC_REASON_TORPROTOCOL;
  1127. }
  1128. if (rh.stream_id == 0) {
  1129. switch (rh.command) {
  1130. case RELAY_COMMAND_BEGIN:
  1131. case RELAY_COMMAND_CONNECTED:
  1132. case RELAY_COMMAND_DATA:
  1133. case RELAY_COMMAND_END:
  1134. case RELAY_COMMAND_RESOLVE:
  1135. case RELAY_COMMAND_RESOLVED:
  1136. case RELAY_COMMAND_BEGIN_DIR:
  1137. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, "Relay command %d with zero "
  1138. "stream_id. Dropping.", (int)rh.command);
  1139. return 0;
  1140. default:
  1141. ;
  1142. }
  1143. }
  1144. /* either conn is NULL, in which case we've got a control cell, or else
  1145. * conn points to the recognized stream. */
  1146. if (conn && !connection_state_is_open(TO_CONN(conn))) {
  1147. if (conn->base_.type == CONN_TYPE_EXIT &&
  1148. (conn->base_.state == EXIT_CONN_STATE_CONNECTING ||
  1149. conn->base_.state == EXIT_CONN_STATE_RESOLVING) &&
  1150. rh.command == RELAY_COMMAND_DATA) {
  1151. /* Allow DATA cells to be delivered to an exit node in state
  1152. * EXIT_CONN_STATE_CONNECTING or EXIT_CONN_STATE_RESOLVING.
  1153. * This speeds up HTTP, for example. */
  1154. optimistic_data = 1;
  1155. } else {
  1156. return connection_edge_process_relay_cell_not_open(
  1157. &rh, cell, circ, conn, layer_hint);
  1158. }
  1159. }
  1160. switch (rh.command) {
  1161. case RELAY_COMMAND_DROP:
  1162. // log_info(domain,"Got a relay-level padding cell. Dropping.");
  1163. return 0;
  1164. case RELAY_COMMAND_BEGIN:
  1165. case RELAY_COMMAND_BEGIN_DIR:
  1166. if (layer_hint &&
  1167. circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
  1168. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  1169. "Relay begin request unsupported at AP. Dropping.");
  1170. return 0;
  1171. }
  1172. if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED &&
  1173. layer_hint != TO_ORIGIN_CIRCUIT(circ)->cpath->prev) {
  1174. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  1175. "Relay begin request to Hidden Service "
  1176. "from intermediary node. Dropping.");
  1177. return 0;
  1178. }
  1179. if (conn) {
  1180. log_fn(LOG_PROTOCOL_WARN, domain,
  1181. "Begin cell for known stream. Dropping.");
  1182. return 0;
  1183. }
  1184. if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
  1185. /* Assign this circuit and its app-ward OR connection a unique ID,
  1186. * so that we can measure download times. The local edge and dir
  1187. * connection will be assigned the same ID when they are created
  1188. * and linked. */
  1189. static uint64_t next_id = 0;
  1190. circ->dirreq_id = ++next_id;
  1191. TO_OR_CIRCUIT(circ)->p_chan->dirreq_id = circ->dirreq_id;
  1192. }
  1193. return connection_exit_begin_conn(cell, circ);
  1194. case RELAY_COMMAND_DATA:
  1195. ++stats_n_data_cells_received;
  1196. if (( layer_hint && --layer_hint->deliver_window < 0) ||
  1197. (!layer_hint && --circ->deliver_window < 0)) {
  1198. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1199. "(relay data) circ deliver_window below 0. Killing.");
  1200. if (conn) {
  1201. /* XXXX Do we actually need to do this? Will killing the circuit
  1202. * not send an END and mark the stream for close as appropriate? */
  1203. connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
  1204. connection_mark_for_close(TO_CONN(conn));
  1205. }
  1206. return -END_CIRC_REASON_TORPROTOCOL;
  1207. }
  1208. log_debug(domain,"circ deliver_window now %d.", layer_hint ?
  1209. layer_hint->deliver_window : circ->deliver_window);
  1210. circuit_consider_sending_sendme(circ, layer_hint);
  1211. if (!conn) {
  1212. log_info(domain,"data cell dropped, unknown stream (streamid %d).",
  1213. rh.stream_id);
  1214. return 0;
  1215. }
  1216. if (--conn->deliver_window < 0) { /* is it below 0 after decrement? */
  1217. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1218. "(relay data) conn deliver_window below 0. Killing.");
  1219. return -END_CIRC_REASON_TORPROTOCOL;
  1220. }
  1221. stats_n_data_bytes_received += rh.length;
  1222. connection_write_to_buf((char*)(cell->payload + RELAY_HEADER_SIZE),
  1223. rh.length, TO_CONN(conn));
  1224. if (!optimistic_data) {
  1225. /* Only send a SENDME if we're not getting optimistic data; otherwise
  1226. * a SENDME could arrive before the CONNECTED.
  1227. */
  1228. connection_edge_consider_sending_sendme(conn);
  1229. }
  1230. return 0;
  1231. case RELAY_COMMAND_END:
  1232. reason = rh.length > 0 ?
  1233. get_uint8(cell->payload+RELAY_HEADER_SIZE) : END_STREAM_REASON_MISC;
  1234. if (!conn) {
  1235. log_info(domain,"end cell (%s) dropped, unknown stream.",
  1236. stream_end_reason_to_string(reason));
  1237. return 0;
  1238. }
  1239. /* XXX add to this log_fn the exit node's nickname? */
  1240. log_info(domain,TOR_SOCKET_T_FORMAT": end cell (%s) for stream %d. "
  1241. "Removing stream.",
  1242. conn->base_.s,
  1243. stream_end_reason_to_string(reason),
  1244. conn->stream_id);
  1245. if (conn->base_.type == CONN_TYPE_AP) {
  1246. entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
  1247. if (entry_conn->socks_request &&
  1248. !entry_conn->socks_request->has_finished)
  1249. log_warn(LD_BUG,
  1250. "open stream hasn't sent socks answer yet? Closing.");
  1251. }
  1252. /* We just *got* an end; no reason to send one. */
  1253. conn->edge_has_sent_end = 1;
  1254. if (!conn->end_reason)
  1255. conn->end_reason = reason | END_STREAM_REASON_FLAG_REMOTE;
  1256. if (!conn->base_.marked_for_close) {
  1257. /* only mark it if not already marked. it's possible to
  1258. * get the 'end' right around when the client hangs up on us. */
  1259. connection_mark_and_flush(TO_CONN(conn));
  1260. }
  1261. return 0;
  1262. case RELAY_COMMAND_EXTEND:
  1263. case RELAY_COMMAND_EXTEND2: {
  1264. static uint64_t total_n_extend=0, total_nonearly=0;
  1265. total_n_extend++;
  1266. if (rh.stream_id) {
  1267. log_fn(LOG_PROTOCOL_WARN, domain,
  1268. "'extend' cell received for non-zero stream. Dropping.");
  1269. return 0;
  1270. }
  1271. if (cell->command != CELL_RELAY_EARLY &&
  1272. !networkstatus_get_param(NULL,"AllowNonearlyExtend",0,0,1)) {
  1273. #define EARLY_WARNING_INTERVAL 3600
  1274. static ratelim_t early_warning_limit =
  1275. RATELIM_INIT(EARLY_WARNING_INTERVAL);
  1276. char *m;
  1277. if (cell->command == CELL_RELAY) {
  1278. ++total_nonearly;
  1279. if ((m = rate_limit_log(&early_warning_limit, approx_time()))) {
  1280. double percentage = ((double)total_nonearly)/total_n_extend;
  1281. percentage *= 100;
  1282. log_fn(LOG_PROTOCOL_WARN, domain, "EXTEND cell received, "
  1283. "but not via RELAY_EARLY. Dropping.%s", m);
  1284. log_fn(LOG_PROTOCOL_WARN, domain, " (We have dropped %.02f%% of "
  1285. "all EXTEND cells for this reason)", percentage);
  1286. tor_free(m);
  1287. }
  1288. } else {
  1289. log_fn(LOG_WARN, domain,
  1290. "EXTEND cell received, in a cell with type %d! Dropping.",
  1291. cell->command);
  1292. }
  1293. return 0;
  1294. }
  1295. return circuit_extend(cell, circ);
  1296. }
  1297. case RELAY_COMMAND_EXTENDED:
  1298. case RELAY_COMMAND_EXTENDED2:
  1299. if (!layer_hint) {
  1300. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1301. "'extended' unsupported at non-origin. Dropping.");
  1302. return 0;
  1303. }
  1304. log_debug(domain,"Got an extended cell! Yay.");
  1305. {
  1306. extended_cell_t extended_cell;
  1307. if (extended_cell_parse(&extended_cell, rh.command,
  1308. (const uint8_t*)cell->payload+RELAY_HEADER_SIZE,
  1309. rh.length)<0) {
  1310. log_warn(LD_PROTOCOL,
  1311. "Can't parse EXTENDED cell; killing circuit.");
  1312. return -END_CIRC_REASON_TORPROTOCOL;
  1313. }
  1314. if ((reason = circuit_finish_handshake(TO_ORIGIN_CIRCUIT(circ),
  1315. &extended_cell.created_cell)) < 0) {
  1316. log_warn(domain,"circuit_finish_handshake failed.");
  1317. return reason;
  1318. }
  1319. }
  1320. if ((reason=circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ)))<0) {
  1321. log_info(domain,"circuit_send_next_onion_skin() failed.");
  1322. return reason;
  1323. }
  1324. return 0;
  1325. case RELAY_COMMAND_TRUNCATE:
  1326. if (layer_hint) {
  1327. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  1328. "'truncate' unsupported at origin. Dropping.");
  1329. return 0;
  1330. }
  1331. if (circ->n_chan) {
  1332. uint8_t trunc_reason = get_uint8(cell->payload + RELAY_HEADER_SIZE);
  1333. circuit_clear_cell_queue(circ, circ->n_chan);
  1334. channel_send_destroy(circ->n_circ_id, circ->n_chan,
  1335. trunc_reason);
  1336. circuit_set_n_circid_chan(circ, 0, NULL);
  1337. }
  1338. log_debug(LD_EXIT, "Processed 'truncate', replying.");
  1339. {
  1340. char payload[1];
  1341. payload[0] = (char)END_CIRC_REASON_REQUESTED;
  1342. relay_send_command_from_edge(0, circ, RELAY_COMMAND_TRUNCATED,
  1343. payload, sizeof(payload), NULL);
  1344. }
  1345. return 0;
  1346. case RELAY_COMMAND_TRUNCATED:
  1347. if (!layer_hint) {
  1348. log_fn(LOG_PROTOCOL_WARN, LD_EXIT,
  1349. "'truncated' unsupported at non-origin. Dropping.");
  1350. return 0;
  1351. }
  1352. circuit_truncated(TO_ORIGIN_CIRCUIT(circ), layer_hint,
  1353. get_uint8(cell->payload + RELAY_HEADER_SIZE));
  1354. return 0;
  1355. case RELAY_COMMAND_CONNECTED:
  1356. if (conn) {
  1357. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1358. "'connected' unsupported while open. Closing circ.");
  1359. return -END_CIRC_REASON_TORPROTOCOL;
  1360. }
  1361. log_info(domain,
  1362. "'connected' received, no conn attached anymore. Ignoring.");
  1363. return 0;
  1364. case RELAY_COMMAND_SENDME:
  1365. if (!rh.stream_id) {
  1366. if (layer_hint) {
  1367. if (layer_hint->package_window + CIRCWINDOW_INCREMENT >
  1368. CIRCWINDOW_START_MAX) {
  1369. /*XXXX024: Downgrade this back to LOG_PROTOCOL_WARN after a while*/
  1370. log_fn(LOG_WARN, LD_PROTOCOL,
  1371. "Bug/attack: unexpected sendme cell from exit relay. "
  1372. "Closing circ.");
  1373. return -END_CIRC_REASON_TORPROTOCOL;
  1374. }
  1375. layer_hint->package_window += CIRCWINDOW_INCREMENT;
  1376. log_debug(LD_APP,"circ-level sendme at origin, packagewindow %d.",
  1377. layer_hint->package_window);
  1378. circuit_resume_edge_reading(circ, layer_hint);
  1379. } else {
  1380. if (circ->package_window + CIRCWINDOW_INCREMENT >
  1381. CIRCWINDOW_START_MAX) {
  1382. /*XXXX024: Downgrade this back to LOG_PROTOCOL_WARN after a while*/
  1383. log_fn(LOG_WARN, LD_PROTOCOL,
  1384. "Bug/attack: unexpected sendme cell from client. "
  1385. "Closing circ (window %d).",
  1386. circ->package_window);
  1387. return -END_CIRC_REASON_TORPROTOCOL;
  1388. }
  1389. circ->package_window += CIRCWINDOW_INCREMENT;
  1390. log_debug(LD_APP,
  1391. "circ-level sendme at non-origin, packagewindow %d.",
  1392. circ->package_window);
  1393. circuit_resume_edge_reading(circ, layer_hint);
  1394. }
  1395. return 0;
  1396. }
  1397. if (!conn) {
  1398. log_info(domain,"sendme cell dropped, unknown stream (streamid %d).",
  1399. rh.stream_id);
  1400. return 0;
  1401. }
  1402. conn->package_window += STREAMWINDOW_INCREMENT;
  1403. log_debug(domain,"stream-level sendme, packagewindow now %d.",
  1404. conn->package_window);
  1405. if (circuit_queue_streams_are_blocked(circ)) {
  1406. /* Still waiting for queue to flush; don't touch conn */
  1407. return 0;
  1408. }
  1409. connection_start_reading(TO_CONN(conn));
  1410. /* handle whatever might still be on the inbuf */
  1411. if (connection_edge_package_raw_inbuf(conn, 1, NULL) < 0) {
  1412. /* (We already sent an end cell if possible) */
  1413. connection_mark_for_close(TO_CONN(conn));
  1414. return 0;
  1415. }
  1416. return 0;
  1417. case RELAY_COMMAND_RESOLVE:
  1418. if (layer_hint) {
  1419. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  1420. "resolve request unsupported at AP; dropping.");
  1421. return 0;
  1422. } else if (conn) {
  1423. log_fn(LOG_PROTOCOL_WARN, domain,
  1424. "resolve request for known stream; dropping.");
  1425. return 0;
  1426. } else if (circ->purpose != CIRCUIT_PURPOSE_OR) {
  1427. log_fn(LOG_PROTOCOL_WARN, domain,
  1428. "resolve request on circ with purpose %d; dropping",
  1429. circ->purpose);
  1430. return 0;
  1431. }
  1432. connection_exit_begin_resolve(cell, TO_OR_CIRCUIT(circ));
  1433. return 0;
  1434. case RELAY_COMMAND_RESOLVED:
  1435. if (conn) {
  1436. log_fn(LOG_PROTOCOL_WARN, domain,
  1437. "'resolved' unsupported while open. Closing circ.");
  1438. return -END_CIRC_REASON_TORPROTOCOL;
  1439. }
  1440. log_info(domain,
  1441. "'resolved' received, no conn attached anymore. Ignoring.");
  1442. return 0;
  1443. case RELAY_COMMAND_ESTABLISH_INTRO:
  1444. case RELAY_COMMAND_ESTABLISH_RENDEZVOUS:
  1445. case RELAY_COMMAND_INTRODUCE1:
  1446. case RELAY_COMMAND_INTRODUCE2:
  1447. case RELAY_COMMAND_INTRODUCE_ACK:
  1448. case RELAY_COMMAND_RENDEZVOUS1:
  1449. case RELAY_COMMAND_RENDEZVOUS2:
  1450. case RELAY_COMMAND_INTRO_ESTABLISHED:
  1451. case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
  1452. rend_process_relay_cell(circ, layer_hint,
  1453. rh.command, rh.length,
  1454. cell->payload+RELAY_HEADER_SIZE);
  1455. return 0;
  1456. }
  1457. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1458. "Received unknown relay command %d. Perhaps the other side is using "
  1459. "a newer version of Tor? Dropping.",
  1460. rh.command);
  1461. return 0; /* for forward compatibility, don't kill the circuit */
  1462. }
  1463. /** How many relay_data cells have we built, ever? */
  1464. uint64_t stats_n_data_cells_packaged = 0;
  1465. /** How many bytes of data have we put in relay_data cells have we built,
  1466. * ever? This would be RELAY_PAYLOAD_SIZE*stats_n_data_cells_packaged if
  1467. * every relay cell we ever sent were completely full of data. */
  1468. uint64_t stats_n_data_bytes_packaged = 0;
  1469. /** How many relay_data cells have we received, ever? */
  1470. uint64_t stats_n_data_cells_received = 0;
  1471. /** How many bytes of data have we received relay_data cells, ever? This would
  1472. * be RELAY_PAYLOAD_SIZE*stats_n_data_cells_packaged if every relay cell we
  1473. * ever received were completely full of data. */
  1474. uint64_t stats_n_data_bytes_received = 0;
  1475. /** If <b>conn</b> has an entire relay payload of bytes on its inbuf (or
  1476. * <b>package_partial</b> is true), and the appropriate package windows aren't
  1477. * empty, grab a cell and send it down the circuit.
  1478. *
  1479. * If *<b>max_cells</b> is given, package no more than max_cells. Decrement
  1480. * *<b>max_cells</b> by the number of cells packaged.
  1481. *
  1482. * Return -1 (and send a RELAY_COMMAND_END cell if necessary) if conn should
  1483. * be marked for close, else return 0.
  1484. */
  1485. int
  1486. connection_edge_package_raw_inbuf(edge_connection_t *conn, int package_partial,
  1487. int *max_cells)
  1488. {
  1489. size_t bytes_to_process, length;
  1490. char payload[CELL_PAYLOAD_SIZE];
  1491. circuit_t *circ;
  1492. const unsigned domain = conn->base_.type == CONN_TYPE_AP ? LD_APP : LD_EXIT;
  1493. int sending_from_optimistic = 0;
  1494. entry_connection_t *entry_conn =
  1495. conn->base_.type == CONN_TYPE_AP ? EDGE_TO_ENTRY_CONN(conn) : NULL;
  1496. const int sending_optimistically =
  1497. entry_conn &&
  1498. conn->base_.type == CONN_TYPE_AP &&
  1499. conn->base_.state != AP_CONN_STATE_OPEN;
  1500. crypt_path_t *cpath_layer = conn->cpath_layer;
  1501. tor_assert(conn);
  1502. if (conn->base_.marked_for_close) {
  1503. log_warn(LD_BUG,
  1504. "called on conn that's already marked for close at %s:%d.",
  1505. conn->base_.marked_for_close_file, conn->base_.marked_for_close);
  1506. return 0;
  1507. }
  1508. if (max_cells && *max_cells <= 0)
  1509. return 0;
  1510. repeat_connection_edge_package_raw_inbuf:
  1511. circ = circuit_get_by_edge_conn(conn);
  1512. if (!circ) {
  1513. log_info(domain,"conn has no circuit! Closing.");
  1514. conn->end_reason = END_STREAM_REASON_CANT_ATTACH;
  1515. return -1;
  1516. }
  1517. if (circuit_consider_stop_edge_reading(circ, cpath_layer))
  1518. return 0;
  1519. if (conn->package_window <= 0) {
  1520. log_info(domain,"called with package_window %d. Skipping.",
  1521. conn->package_window);
  1522. connection_stop_reading(TO_CONN(conn));
  1523. return 0;
  1524. }
  1525. sending_from_optimistic = entry_conn &&
  1526. entry_conn->sending_optimistic_data != NULL;
  1527. if (PREDICT_UNLIKELY(sending_from_optimistic)) {
  1528. bytes_to_process = generic_buffer_len(entry_conn->sending_optimistic_data);
  1529. if (PREDICT_UNLIKELY(!bytes_to_process)) {
  1530. log_warn(LD_BUG, "sending_optimistic_data was non-NULL but empty");
  1531. bytes_to_process = connection_get_inbuf_len(TO_CONN(conn));
  1532. sending_from_optimistic = 0;
  1533. }
  1534. } else {
  1535. bytes_to_process = connection_get_inbuf_len(TO_CONN(conn));
  1536. }
  1537. if (!bytes_to_process)
  1538. return 0;
  1539. if (!package_partial && bytes_to_process < RELAY_PAYLOAD_SIZE)
  1540. return 0;
  1541. if (bytes_to_process > RELAY_PAYLOAD_SIZE) {
  1542. length = RELAY_PAYLOAD_SIZE;
  1543. } else {
  1544. length = bytes_to_process;
  1545. }
  1546. stats_n_data_bytes_packaged += length;
  1547. stats_n_data_cells_packaged += 1;
  1548. if (PREDICT_UNLIKELY(sending_from_optimistic)) {
  1549. /* XXXX We could be more efficient here by sometimes packing
  1550. * previously-sent optimistic data in the same cell with data
  1551. * from the inbuf. */
  1552. generic_buffer_get(entry_conn->sending_optimistic_data, payload, length);
  1553. if (!generic_buffer_len(entry_conn->sending_optimistic_data)) {
  1554. generic_buffer_free(entry_conn->sending_optimistic_data);
  1555. entry_conn->sending_optimistic_data = NULL;
  1556. }
  1557. } else {
  1558. connection_fetch_from_buf(payload, length, TO_CONN(conn));
  1559. }
  1560. log_debug(domain,TOR_SOCKET_T_FORMAT": Packaging %d bytes (%d waiting).",
  1561. conn->base_.s,
  1562. (int)length, (int)connection_get_inbuf_len(TO_CONN(conn)));
  1563. if (sending_optimistically && !sending_from_optimistic) {
  1564. /* This is new optimistic data; remember it in case we need to detach and
  1565. retry */
  1566. if (!entry_conn->pending_optimistic_data)
  1567. entry_conn->pending_optimistic_data = generic_buffer_new();
  1568. generic_buffer_add(entry_conn->pending_optimistic_data, payload, length);
  1569. }
  1570. if (connection_edge_send_command(conn, RELAY_COMMAND_DATA,
  1571. payload, length) < 0 )
  1572. /* circuit got marked for close, don't continue, don't need to mark conn */
  1573. return 0;
  1574. if (!cpath_layer) { /* non-rendezvous exit */
  1575. tor_assert(circ->package_window > 0);
  1576. circ->package_window--;
  1577. } else { /* we're an AP, or an exit on a rendezvous circ */
  1578. tor_assert(cpath_layer->package_window > 0);
  1579. cpath_layer->package_window--;
  1580. }
  1581. if (--conn->package_window <= 0) { /* is it 0 after decrement? */
  1582. connection_stop_reading(TO_CONN(conn));
  1583. log_debug(domain,"conn->package_window reached 0.");
  1584. circuit_consider_stop_edge_reading(circ, cpath_layer);
  1585. return 0; /* don't process the inbuf any more */
  1586. }
  1587. log_debug(domain,"conn->package_window is now %d",conn->package_window);
  1588. if (max_cells) {
  1589. *max_cells -= 1;
  1590. if (*max_cells <= 0)
  1591. return 0;
  1592. }
  1593. /* handle more if there's more, or return 0 if there isn't */
  1594. goto repeat_connection_edge_package_raw_inbuf;
  1595. }
  1596. /** Called when we've just received a relay data cell, when
  1597. * we've just finished flushing all bytes to stream <b>conn</b>,
  1598. * or when we've flushed *some* bytes to the stream <b>conn</b>.
  1599. *
  1600. * If conn->outbuf is not too full, and our deliver window is
  1601. * low, send back a suitable number of stream-level sendme cells.
  1602. */
  1603. void
  1604. connection_edge_consider_sending_sendme(edge_connection_t *conn)
  1605. {
  1606. circuit_t *circ;
  1607. if (connection_outbuf_too_full(TO_CONN(conn)))
  1608. return;
  1609. circ = circuit_get_by_edge_conn(conn);
  1610. if (!circ) {
  1611. /* this can legitimately happen if the destroy has already
  1612. * arrived and torn down the circuit */
  1613. log_info(LD_APP,"No circuit associated with conn. Skipping.");
  1614. return;
  1615. }
  1616. while (conn->deliver_window <= STREAMWINDOW_START - STREAMWINDOW_INCREMENT) {
  1617. log_debug(conn->base_.type == CONN_TYPE_AP ?LD_APP:LD_EXIT,
  1618. "Outbuf %d, Queuing stream sendme.",
  1619. (int)conn->base_.outbuf_flushlen);
  1620. conn->deliver_window += STREAMWINDOW_INCREMENT;
  1621. if (connection_edge_send_command(conn, RELAY_COMMAND_SENDME,
  1622. NULL, 0) < 0) {
  1623. log_warn(LD_APP,"connection_edge_send_command failed. Skipping.");
  1624. return; /* the circuit's closed, don't continue */
  1625. }
  1626. }
  1627. }
  1628. /** The circuit <b>circ</b> has received a circuit-level sendme
  1629. * (on hop <b>layer_hint</b>, if we're the OP). Go through all the
  1630. * attached streams and let them resume reading and packaging, if
  1631. * their stream windows allow it.
  1632. */
  1633. static void
  1634. circuit_resume_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
  1635. {
  1636. if (circuit_queue_streams_are_blocked(circ)) {
  1637. log_debug(layer_hint?LD_APP:LD_EXIT,"Too big queue, no resuming");
  1638. return;
  1639. }
  1640. log_debug(layer_hint?LD_APP:LD_EXIT,"resuming");
  1641. if (CIRCUIT_IS_ORIGIN(circ))
  1642. circuit_resume_edge_reading_helper(TO_ORIGIN_CIRCUIT(circ)->p_streams,
  1643. circ, layer_hint);
  1644. else
  1645. circuit_resume_edge_reading_helper(TO_OR_CIRCUIT(circ)->n_streams,
  1646. circ, layer_hint);
  1647. }
  1648. void
  1649. stream_choice_seed_weak_rng(void)
  1650. {
  1651. crypto_seed_weak_rng(&stream_choice_rng);
  1652. }
  1653. /** A helper function for circuit_resume_edge_reading() above.
  1654. * The arguments are the same, except that <b>conn</b> is the head
  1655. * of a linked list of edge streams that should each be considered.
  1656. */
  1657. static int
  1658. circuit_resume_edge_reading_helper(edge_connection_t *first_conn,
  1659. circuit_t *circ,
  1660. crypt_path_t *layer_hint)
  1661. {
  1662. edge_connection_t *conn;
  1663. int n_packaging_streams, n_streams_left;
  1664. int packaged_this_round;
  1665. int cells_on_queue;
  1666. int cells_per_conn;
  1667. edge_connection_t *chosen_stream = NULL;
  1668. int max_to_package;
  1669. if (first_conn == NULL) {
  1670. /* Don't bother to try to do the rest of this if there are no connections
  1671. * to resume. */
  1672. return 0;
  1673. }
  1674. /* How many cells do we have space for? It will be the minimum of
  1675. * the number needed to exhaust the package window, and the minimum
  1676. * needed to fill the cell queue. */
  1677. max_to_package = circ->package_window;
  1678. if (CIRCUIT_IS_ORIGIN(circ)) {
  1679. cells_on_queue = circ->n_chan_cells.n;
  1680. } else {
  1681. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  1682. cells_on_queue = or_circ->p_chan_cells.n;
  1683. }
  1684. if (CELL_QUEUE_HIGHWATER_SIZE - cells_on_queue < max_to_package)
  1685. max_to_package = CELL_QUEUE_HIGHWATER_SIZE - cells_on_queue;
  1686. /* Once we used to start listening on the streams in the order they
  1687. * appeared in the linked list. That leads to starvation on the
  1688. * streams that appeared later on the list, since the first streams
  1689. * would always get to read first. Instead, we just pick a random
  1690. * stream on the list, and enable reading for streams starting at that
  1691. * point (and wrapping around as if the list were circular). It would
  1692. * probably be better to actually remember which streams we've
  1693. * serviced in the past, but this is simple and effective. */
  1694. /* Select a stream uniformly at random from the linked list. We
  1695. * don't need cryptographic randomness here. */
  1696. {
  1697. int num_streams = 0;
  1698. for (conn = first_conn; conn; conn = conn->next_stream) {
  1699. num_streams++;
  1700. if (tor_weak_random_one_in_n(&stream_choice_rng, num_streams)) {
  1701. chosen_stream = conn;
  1702. }
  1703. /* Invariant: chosen_stream has been chosen uniformly at random from
  1704. * among the first num_streams streams on first_conn.
  1705. *
  1706. * (Note that we iterate over every stream on the circuit, so that after
  1707. * we've considered the first stream, we've chosen it with P=1; and
  1708. * after we consider the second stream, we've switched to it with P=1/2
  1709. * and stayed with the first stream with P=1/2; and after we've
  1710. * considered the third stream, we've switched to it with P=1/3 and
  1711. * remained with one of the first two streams with P=(2/3), giving each
  1712. * one P=(1/2)(2/3) )=(1/3).) */
  1713. }
  1714. }
  1715. /* Count how many non-marked streams there are that have anything on
  1716. * their inbuf, and enable reading on all of the connections. */
  1717. n_packaging_streams = 0;
  1718. /* Activate reading starting from the chosen stream */
  1719. for (conn=chosen_stream; conn; conn = conn->next_stream) {
  1720. /* Start reading for the streams starting from here */
  1721. if (conn->base_.marked_for_close || conn->package_window <= 0)
  1722. continue;
  1723. if (!layer_hint || conn->cpath_layer == layer_hint) {
  1724. connection_start_reading(TO_CONN(conn));
  1725. if (connection_get_inbuf_len(TO_CONN(conn)) > 0)
  1726. ++n_packaging_streams;
  1727. }
  1728. }
  1729. /* Go back and do the ones we skipped, circular-style */
  1730. for (conn = first_conn; conn != chosen_stream; conn = conn->next_stream) {
  1731. if (conn->base_.marked_for_close || conn->package_window <= 0)
  1732. continue;
  1733. if (!layer_hint || conn->cpath_layer == layer_hint) {
  1734. connection_start_reading(TO_CONN(conn));
  1735. if (connection_get_inbuf_len(TO_CONN(conn)) > 0)
  1736. ++n_packaging_streams;
  1737. }
  1738. }
  1739. if (n_packaging_streams == 0) /* avoid divide-by-zero */
  1740. return 0;
  1741. again:
  1742. cells_per_conn = CEIL_DIV(max_to_package, n_packaging_streams);
  1743. packaged_this_round = 0;
  1744. n_streams_left = 0;
  1745. /* Iterate over all connections. Package up to cells_per_conn cells on
  1746. * each. Update packaged_this_round with the total number of cells
  1747. * packaged, and n_streams_left with the number that still have data to
  1748. * package.
  1749. */
  1750. for (conn=first_conn; conn; conn=conn->next_stream) {
  1751. if (conn->base_.marked_for_close || conn->package_window <= 0)
  1752. continue;
  1753. if (!layer_hint || conn->cpath_layer == layer_hint) {
  1754. int n = cells_per_conn, r;
  1755. /* handle whatever might still be on the inbuf */
  1756. r = connection_edge_package_raw_inbuf(conn, 1, &n);
  1757. /* Note how many we packaged */
  1758. packaged_this_round += (cells_per_conn-n);
  1759. if (r<0) {
  1760. /* Problem while packaging. (We already sent an end cell if
  1761. * possible) */
  1762. connection_mark_for_close(TO_CONN(conn));
  1763. continue;
  1764. }
  1765. /* If there's still data to read, we'll be coming back to this stream. */
  1766. if (connection_get_inbuf_len(TO_CONN(conn)))
  1767. ++n_streams_left;
  1768. /* If the circuit won't accept any more data, return without looking
  1769. * at any more of the streams. Any connections that should be stopped
  1770. * have already been stopped by connection_edge_package_raw_inbuf. */
  1771. if (circuit_consider_stop_edge_reading(circ, layer_hint))
  1772. return -1;
  1773. /* XXXX should we also stop immediately if we fill up the cell queue?
  1774. * Probably. */
  1775. }
  1776. }
  1777. /* If we made progress, and we are willing to package more, and there are
  1778. * any streams left that want to package stuff... try again!
  1779. */
  1780. if (packaged_this_round && packaged_this_round < max_to_package &&
  1781. n_streams_left) {
  1782. max_to_package -= packaged_this_round;
  1783. n_packaging_streams = n_streams_left;
  1784. goto again;
  1785. }
  1786. return 0;
  1787. }
  1788. /** Check if the package window for <b>circ</b> is empty (at
  1789. * hop <b>layer_hint</b> if it's defined).
  1790. *
  1791. * If yes, tell edge streams to stop reading and return 1.
  1792. * Else return 0.
  1793. */
  1794. static int
  1795. circuit_consider_stop_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
  1796. {
  1797. edge_connection_t *conn = NULL;
  1798. unsigned domain = layer_hint ? LD_APP : LD_EXIT;
  1799. if (!layer_hint) {
  1800. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  1801. log_debug(domain,"considering circ->package_window %d",
  1802. circ->package_window);
  1803. if (circ->package_window <= 0) {
  1804. log_debug(domain,"yes, not-at-origin. stopped.");
  1805. for (conn = or_circ->n_streams; conn; conn=conn->next_stream)
  1806. connection_stop_reading(TO_CONN(conn));
  1807. return 1;
  1808. }
  1809. return 0;
  1810. }
  1811. /* else, layer hint is defined, use it */
  1812. log_debug(domain,"considering layer_hint->package_window %d",
  1813. layer_hint->package_window);
  1814. if (layer_hint->package_window <= 0) {
  1815. log_debug(domain,"yes, at-origin. stopped.");
  1816. for (conn = TO_ORIGIN_CIRCUIT(circ)->p_streams; conn;
  1817. conn=conn->next_stream) {
  1818. if (conn->cpath_layer == layer_hint)
  1819. connection_stop_reading(TO_CONN(conn));
  1820. }
  1821. return 1;
  1822. }
  1823. return 0;
  1824. }
  1825. /** Check if the deliver_window for circuit <b>circ</b> (at hop
  1826. * <b>layer_hint</b> if it's defined) is low enough that we should
  1827. * send a circuit-level sendme back down the circuit. If so, send
  1828. * enough sendmes that the window would be overfull if we sent any
  1829. * more.
  1830. */
  1831. static void
  1832. circuit_consider_sending_sendme(circuit_t *circ, crypt_path_t *layer_hint)
  1833. {
  1834. // log_fn(LOG_INFO,"Considering: layer_hint is %s",
  1835. // layer_hint ? "defined" : "null");
  1836. while ((layer_hint ? layer_hint->deliver_window : circ->deliver_window) <=
  1837. CIRCWINDOW_START - CIRCWINDOW_INCREMENT) {
  1838. log_debug(LD_CIRC,"Queuing circuit sendme.");
  1839. if (layer_hint)
  1840. layer_hint->deliver_window += CIRCWINDOW_INCREMENT;
  1841. else
  1842. circ->deliver_window += CIRCWINDOW_INCREMENT;
  1843. if (relay_send_command_from_edge(0, circ, RELAY_COMMAND_SENDME,
  1844. NULL, 0, layer_hint) < 0) {
  1845. log_warn(LD_CIRC,
  1846. "relay_send_command_from_edge failed. Circuit's closed.");
  1847. return; /* the circuit's closed, don't continue */
  1848. }
  1849. }
  1850. }
  1851. #ifdef ACTIVE_CIRCUITS_PARANOIA
  1852. #define assert_cmux_ok_paranoid(chan) \
  1853. assert_circuit_mux_okay(chan)
  1854. #else
  1855. #define assert_cmux_ok_paranoid(chan)
  1856. #endif
  1857. /** The total number of cells we have allocated from the memory pool. */
  1858. static int total_cells_allocated = 0;
  1859. /** A memory pool to allocate packed_cell_t objects. */
  1860. static mp_pool_t *cell_pool = NULL;
  1861. /** Memory pool to allocate insertion_time_elem_t objects used for cell
  1862. * statistics. */
  1863. static mp_pool_t *it_pool = NULL;
  1864. /** Allocate structures to hold cells. */
  1865. void
  1866. init_cell_pool(void)
  1867. {
  1868. tor_assert(!cell_pool);
  1869. cell_pool = mp_pool_new(sizeof(packed_cell_t), 128*1024);
  1870. }
  1871. /** Free all storage used to hold cells (and insertion times if we measure
  1872. * cell statistics). */
  1873. void
  1874. free_cell_pool(void)
  1875. {
  1876. /* Maybe we haven't called init_cell_pool yet; need to check for it. */
  1877. if (cell_pool) {
  1878. mp_pool_destroy(cell_pool);
  1879. cell_pool = NULL;
  1880. }
  1881. if (it_pool) {
  1882. mp_pool_destroy(it_pool);
  1883. it_pool = NULL;
  1884. }
  1885. }
  1886. /** Free excess storage in cell pool. */
  1887. void
  1888. clean_cell_pool(void)
  1889. {
  1890. tor_assert(cell_pool);
  1891. mp_pool_clean(cell_pool, 0, 1);
  1892. }
  1893. /** Release storage held by <b>cell</b>. */
  1894. static INLINE void
  1895. packed_cell_free_unchecked(packed_cell_t *cell)
  1896. {
  1897. --total_cells_allocated;
  1898. mp_pool_release(cell);
  1899. }
  1900. /** Allocate and return a new packed_cell_t. */
  1901. static INLINE packed_cell_t *
  1902. packed_cell_new(void)
  1903. {
  1904. ++total_cells_allocated;
  1905. return mp_pool_get(cell_pool);
  1906. }
  1907. /** Return a packed cell used outside by channel_t lower layer */
  1908. void
  1909. packed_cell_free(packed_cell_t *cell)
  1910. {
  1911. packed_cell_free_unchecked(cell);
  1912. }
  1913. /** Log current statistics for cell pool allocation at log level
  1914. * <b>severity</b>. */
  1915. void
  1916. dump_cell_pool_usage(int severity)
  1917. {
  1918. circuit_t *c;
  1919. int n_circs = 0;
  1920. int n_cells = 0;
  1921. for (c = circuit_get_global_list_(); c; c = c->next) {
  1922. n_cells += c->n_chan_cells.n;
  1923. if (!CIRCUIT_IS_ORIGIN(c))
  1924. n_cells += TO_OR_CIRCUIT(c)->p_chan_cells.n;
  1925. ++n_circs;
  1926. }
  1927. tor_log(severity, LD_MM,
  1928. "%d cells allocated on %d circuits. %d cells leaked.",
  1929. n_cells, n_circs, total_cells_allocated - n_cells);
  1930. mp_pool_log_status(cell_pool, severity);
  1931. }
  1932. /** Allocate a new copy of packed <b>cell</b>. */
  1933. static INLINE packed_cell_t *
  1934. packed_cell_copy(const cell_t *cell, int wide_circ_ids)
  1935. {
  1936. packed_cell_t *c = packed_cell_new();
  1937. cell_pack(c, cell, wide_circ_ids);
  1938. c->next = NULL;
  1939. return c;
  1940. }
  1941. /** Append <b>cell</b> to the end of <b>queue</b>. */
  1942. void
  1943. cell_queue_append(cell_queue_t *queue, packed_cell_t *cell)
  1944. {
  1945. if (queue->tail) {
  1946. tor_assert(!queue->tail->next);
  1947. queue->tail->next = cell;
  1948. } else {
  1949. queue->head = cell;
  1950. }
  1951. queue->tail = cell;
  1952. cell->next = NULL;
  1953. ++queue->n;
  1954. }
  1955. /** Append a newly allocated copy of <b>cell</b> to the end of <b>queue</b> */
  1956. void
  1957. cell_queue_append_packed_copy(cell_queue_t *queue, const cell_t *cell,
  1958. int wide_circ_ids)
  1959. {
  1960. packed_cell_t *copy = packed_cell_copy(cell, wide_circ_ids);
  1961. /* Remember the time when this cell was put in the queue. */
  1962. if (get_options()->CellStatistics) {
  1963. struct timeval now;
  1964. uint32_t added;
  1965. insertion_time_queue_t *it_queue = queue->insertion_times;
  1966. if (!it_pool)
  1967. it_pool = mp_pool_new(sizeof(insertion_time_elem_t), 1024);
  1968. tor_gettimeofday_cached(&now);
  1969. #define SECONDS_IN_A_DAY 86400L
  1970. added = (uint32_t)(((now.tv_sec % SECONDS_IN_A_DAY) * 100L)
  1971. + ((uint32_t)now.tv_usec / (uint32_t)10000L));
  1972. if (!it_queue) {
  1973. it_queue = tor_malloc_zero(sizeof(insertion_time_queue_t));
  1974. queue->insertion_times = it_queue;
  1975. }
  1976. if (it_queue->last && it_queue->last->insertion_time == added) {
  1977. it_queue->last->counter++;
  1978. } else {
  1979. insertion_time_elem_t *elem = mp_pool_get(it_pool);
  1980. elem->next = NULL;
  1981. elem->insertion_time = added;
  1982. elem->counter = 1;
  1983. if (it_queue->last) {
  1984. it_queue->last->next = elem;
  1985. it_queue->last = elem;
  1986. } else {
  1987. it_queue->first = it_queue->last = elem;
  1988. }
  1989. }
  1990. }
  1991. cell_queue_append(queue, copy);
  1992. }
  1993. /** Remove and free every cell in <b>queue</b>. */
  1994. void
  1995. cell_queue_clear(cell_queue_t *queue)
  1996. {
  1997. packed_cell_t *cell, *next;
  1998. cell = queue->head;
  1999. while (cell) {
  2000. next = cell->next;
  2001. packed_cell_free_unchecked(cell);
  2002. cell = next;
  2003. }
  2004. queue->head = queue->tail = NULL;
  2005. queue->n = 0;
  2006. if (queue->insertion_times) {
  2007. while (queue->insertion_times->first) {
  2008. insertion_time_elem_t *elem = queue->insertion_times->first;
  2009. queue->insertion_times->first = elem->next;
  2010. mp_pool_release(elem);
  2011. }
  2012. tor_free(queue->insertion_times);
  2013. }
  2014. }
  2015. /** Extract and return the cell at the head of <b>queue</b>; return NULL if
  2016. * <b>queue</b> is empty. */
  2017. static INLINE packed_cell_t *
  2018. cell_queue_pop(cell_queue_t *queue)
  2019. {
  2020. packed_cell_t *cell = queue->head;
  2021. if (!cell)
  2022. return NULL;
  2023. queue->head = cell->next;
  2024. if (cell == queue->tail) {
  2025. tor_assert(!queue->head);
  2026. queue->tail = NULL;
  2027. }
  2028. --queue->n;
  2029. return cell;
  2030. }
  2031. /**
  2032. * Update the number of cells available on the circuit's n_chan or p_chan's
  2033. * circuit mux.
  2034. */
  2035. void
  2036. update_circuit_on_cmux_(circuit_t *circ, cell_direction_t direction,
  2037. const char *file, int lineno)
  2038. {
  2039. channel_t *chan = NULL;
  2040. or_circuit_t *or_circ = NULL;
  2041. circuitmux_t *cmux = NULL;
  2042. tor_assert(circ);
  2043. /* Okay, get the channel */
  2044. if (direction == CELL_DIRECTION_OUT) {
  2045. chan = circ->n_chan;
  2046. } else {
  2047. or_circ = TO_OR_CIRCUIT(circ);
  2048. chan = or_circ->p_chan;
  2049. }
  2050. tor_assert(chan);
  2051. tor_assert(chan->cmux);
  2052. /* Now get the cmux */
  2053. cmux = chan->cmux;
  2054. /* Cmux sanity check */
  2055. if (! circuitmux_is_circuit_attached(cmux, circ)) {
  2056. log_warn(LD_BUG, "called on non-attachd circuit from %s:%d",
  2057. file, lineno);
  2058. return;
  2059. }
  2060. tor_assert(circuitmux_attached_circuit_direction(cmux, circ) == direction);
  2061. assert_cmux_ok_paranoid(chan);
  2062. /* Update the number of cells we have for the circuit mux */
  2063. if (direction == CELL_DIRECTION_OUT) {
  2064. circuitmux_set_num_cells(cmux, circ, circ->n_chan_cells.n);
  2065. } else {
  2066. circuitmux_set_num_cells(cmux, circ, or_circ->p_chan_cells.n);
  2067. }
  2068. assert_cmux_ok_paranoid(chan);
  2069. }
  2070. /** Remove all circuits from the cmux on <b>chan</b>. */
  2071. void
  2072. channel_unlink_all_circuits(channel_t *chan)
  2073. {
  2074. tor_assert(chan);
  2075. tor_assert(chan->cmux);
  2076. circuitmux_detach_all_circuits(chan->cmux);
  2077. chan->num_n_circuits = 0;
  2078. chan->num_p_circuits = 0;
  2079. }
  2080. /** Block (if <b>block</b> is true) or unblock (if <b>block</b> is false)
  2081. * every edge connection that is using <b>circ</b> to write to <b>chan</b>,
  2082. * and start or stop reading as appropriate.
  2083. *
  2084. * If <b>stream_id</b> is nonzero, block only the edge connection whose
  2085. * stream_id matches it.
  2086. *
  2087. * Returns the number of streams whose status we changed.
  2088. */
  2089. static int
  2090. set_streams_blocked_on_circ(circuit_t *circ, channel_t *chan,
  2091. int block, streamid_t stream_id)
  2092. {
  2093. edge_connection_t *edge = NULL;
  2094. int n = 0;
  2095. if (circ->n_chan == chan) {
  2096. circ->streams_blocked_on_n_chan = block;
  2097. if (CIRCUIT_IS_ORIGIN(circ))
  2098. edge = TO_ORIGIN_CIRCUIT(circ)->p_streams;
  2099. } else {
  2100. circ->streams_blocked_on_p_chan = block;
  2101. tor_assert(!CIRCUIT_IS_ORIGIN(circ));
  2102. edge = TO_OR_CIRCUIT(circ)->n_streams;
  2103. }
  2104. for (; edge; edge = edge->next_stream) {
  2105. connection_t *conn = TO_CONN(edge);
  2106. if (stream_id && edge->stream_id != stream_id)
  2107. continue;
  2108. if (edge->edge_blocked_on_circ != block) {
  2109. ++n;
  2110. edge->edge_blocked_on_circ = block;
  2111. }
  2112. if (!conn->read_event && !HAS_BUFFEREVENT(conn)) {
  2113. /* This connection is a placeholder for something; probably a DNS
  2114. * request. It can't actually stop or start reading.*/
  2115. continue;
  2116. }
  2117. if (block) {
  2118. if (connection_is_reading(conn))
  2119. connection_stop_reading(conn);
  2120. } else {
  2121. /* Is this right? */
  2122. if (!connection_is_reading(conn))
  2123. connection_start_reading(conn);
  2124. }
  2125. }
  2126. return n;
  2127. }
  2128. /** Pull as many cells as possible (but no more than <b>max</b>) from the
  2129. * queue of the first active circuit on <b>chan</b>, and write them to
  2130. * <b>chan</b>-&gt;outbuf. Return the number of cells written. Advance
  2131. * the active circuit pointer to the next active circuit in the ring. */
  2132. int
  2133. channel_flush_from_first_active_circuit(channel_t *chan, int max)
  2134. {
  2135. circuitmux_t *cmux = NULL;
  2136. int n_flushed = 0;
  2137. cell_queue_t *queue;
  2138. circuit_t *circ;
  2139. or_circuit_t *or_circ;
  2140. int streams_blocked;
  2141. packed_cell_t *cell;
  2142. /* Get the cmux */
  2143. tor_assert(chan);
  2144. tor_assert(chan->cmux);
  2145. cmux = chan->cmux;
  2146. /* Main loop: pick a circuit, send a cell, update the cmux */
  2147. while (n_flushed < max) {
  2148. circ = circuitmux_get_first_active_circuit(cmux);
  2149. /* If it returns NULL, no cells left to send */
  2150. if (!circ) break;
  2151. assert_cmux_ok_paranoid(chan);
  2152. if (circ->n_chan == chan) {
  2153. queue = &circ->n_chan_cells;
  2154. streams_blocked = circ->streams_blocked_on_n_chan;
  2155. } else {
  2156. or_circ = TO_OR_CIRCUIT(circ);
  2157. tor_assert(or_circ->p_chan == chan);
  2158. queue = &TO_OR_CIRCUIT(circ)->p_chan_cells;
  2159. streams_blocked = circ->streams_blocked_on_p_chan;
  2160. }
  2161. /* Circuitmux told us this was active, so it should have cells */
  2162. tor_assert(queue->n > 0);
  2163. /*
  2164. * Get just one cell here; once we've sent it, that can change the circuit
  2165. * selection, so we have to loop around for another even if this circuit
  2166. * has more than one.
  2167. */
  2168. cell = cell_queue_pop(queue);
  2169. /* Calculate the exact time that this cell has spent in the queue. */
  2170. if (get_options()->CellStatistics && !CIRCUIT_IS_ORIGIN(circ)) {
  2171. struct timeval tvnow;
  2172. uint32_t flushed;
  2173. uint32_t cell_waiting_time;
  2174. insertion_time_queue_t *it_queue = queue->insertion_times;
  2175. tor_gettimeofday_cached(&tvnow);
  2176. flushed = (uint32_t)((tvnow.tv_sec % SECONDS_IN_A_DAY) * 100L +
  2177. (uint32_t)tvnow.tv_usec / (uint32_t)10000L);
  2178. if (!it_queue || !it_queue->first) {
  2179. log_info(LD_GENERAL, "Cannot determine insertion time of cell. "
  2180. "Looks like the CellStatistics option was "
  2181. "recently enabled.");
  2182. } else {
  2183. insertion_time_elem_t *elem = it_queue->first;
  2184. or_circ = TO_OR_CIRCUIT(circ);
  2185. cell_waiting_time =
  2186. (uint32_t)((flushed * 10L + SECONDS_IN_A_DAY * 1000L -
  2187. elem->insertion_time * 10L) %
  2188. (SECONDS_IN_A_DAY * 1000L));
  2189. #undef SECONDS_IN_A_DAY
  2190. elem->counter--;
  2191. if (elem->counter < 1) {
  2192. it_queue->first = elem->next;
  2193. if (elem == it_queue->last)
  2194. it_queue->last = NULL;
  2195. mp_pool_release(elem);
  2196. }
  2197. or_circ->total_cell_waiting_time += cell_waiting_time;
  2198. or_circ->processed_cells++;
  2199. }
  2200. }
  2201. /* If we just flushed our queue and this circuit is used for a
  2202. * tunneled directory request, possibly advance its state. */
  2203. if (queue->n == 0 && chan->dirreq_id)
  2204. geoip_change_dirreq_state(chan->dirreq_id,
  2205. DIRREQ_TUNNELED,
  2206. DIRREQ_CIRC_QUEUE_FLUSHED);
  2207. /* Now send the cell */
  2208. channel_write_packed_cell(chan, cell);
  2209. cell = NULL;
  2210. /*
  2211. * Don't packed_cell_free_unchecked(cell) here because the channel will
  2212. * do so when it gets out of the channel queue (probably already did, in
  2213. * which case that was an immediate double-free bug).
  2214. */
  2215. /* Update the counter */
  2216. ++n_flushed;
  2217. /*
  2218. * Now update the cmux; tell it we've just sent a cell, and how many
  2219. * we have left.
  2220. */
  2221. circuitmux_notify_xmit_cells(cmux, circ, 1);
  2222. circuitmux_set_num_cells(cmux, circ, queue->n);
  2223. if (queue->n == 0)
  2224. log_debug(LD_GENERAL, "Made a circuit inactive.");
  2225. /* Is the cell queue low enough to unblock all the streams that are waiting
  2226. * to write to this circuit? */
  2227. if (streams_blocked && queue->n <= CELL_QUEUE_LOWWATER_SIZE)
  2228. set_streams_blocked_on_circ(circ, chan, 0, 0); /* unblock streams */
  2229. /* If n_flushed < max still, loop around and pick another circuit */
  2230. }
  2231. /* Okay, we're done sending now */
  2232. assert_cmux_ok_paranoid(chan);
  2233. return n_flushed;
  2234. }
  2235. /** Add <b>cell</b> to the queue of <b>circ</b> writing to <b>chan</b>
  2236. * transmitting in <b>direction</b>. */
  2237. void
  2238. append_cell_to_circuit_queue(circuit_t *circ, channel_t *chan,
  2239. cell_t *cell, cell_direction_t direction,
  2240. streamid_t fromstream)
  2241. {
  2242. cell_queue_t *queue;
  2243. int streams_blocked;
  2244. if (circ->marked_for_close)
  2245. return;
  2246. if (direction == CELL_DIRECTION_OUT) {
  2247. queue = &circ->n_chan_cells;
  2248. streams_blocked = circ->streams_blocked_on_n_chan;
  2249. } else {
  2250. or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
  2251. queue = &orcirc->p_chan_cells;
  2252. streams_blocked = circ->streams_blocked_on_p_chan;
  2253. }
  2254. cell_queue_append_packed_copy(queue, cell, chan->wide_circ_ids);
  2255. /* If we have too many cells on the circuit, we should stop reading from
  2256. * the edge streams for a while. */
  2257. if (!streams_blocked && queue->n >= CELL_QUEUE_HIGHWATER_SIZE)
  2258. set_streams_blocked_on_circ(circ, chan, 1, 0); /* block streams */
  2259. if (streams_blocked && fromstream) {
  2260. /* This edge connection is apparently not blocked; block it. */
  2261. set_streams_blocked_on_circ(circ, chan, 1, fromstream);
  2262. }
  2263. update_circuit_on_cmux(circ, direction);
  2264. if (queue->n == 1) {
  2265. /* This was the first cell added to the queue. We just made this
  2266. * circuit active. */
  2267. log_debug(LD_GENERAL, "Made a circuit active.");
  2268. }
  2269. if (!channel_has_queued_writes(chan)) {
  2270. /* There is no data at all waiting to be sent on the outbuf. Add a
  2271. * cell, so that we can notice when it gets flushed, flushed_some can
  2272. * get called, and we can start putting more data onto the buffer then.
  2273. */
  2274. log_debug(LD_GENERAL, "Primed a buffer.");
  2275. channel_flush_from_first_active_circuit(chan, 1);
  2276. }
  2277. }
  2278. /** Append an encoded value of <b>addr</b> to <b>payload_out</b>, which must
  2279. * have at least 18 bytes of free space. The encoding is, as specified in
  2280. * tor-spec.txt:
  2281. * RESOLVED_TYPE_IPV4 or RESOLVED_TYPE_IPV6 [1 byte]
  2282. * LENGTH [1 byte]
  2283. * ADDRESS [length bytes]
  2284. * Return the number of bytes added, or -1 on error */
  2285. int
  2286. append_address_to_payload(uint8_t *payload_out, const tor_addr_t *addr)
  2287. {
  2288. uint32_t a;
  2289. switch (tor_addr_family(addr)) {
  2290. case AF_INET:
  2291. payload_out[0] = RESOLVED_TYPE_IPV4;
  2292. payload_out[1] = 4;
  2293. a = tor_addr_to_ipv4n(addr);
  2294. memcpy(payload_out+2, &a, 4);
  2295. return 6;
  2296. case AF_INET6:
  2297. payload_out[0] = RESOLVED_TYPE_IPV6;
  2298. payload_out[1] = 16;
  2299. memcpy(payload_out+2, tor_addr_to_in6_addr8(addr), 16);
  2300. return 18;
  2301. case AF_UNSPEC:
  2302. default:
  2303. return -1;
  2304. }
  2305. }
  2306. /** Given <b>payload_len</b> bytes at <b>payload</b>, starting with an address
  2307. * encoded as by append_address_to_payload(), try to decode the address into
  2308. * *<b>addr_out</b>. Return the next byte in the payload after the address on
  2309. * success, or NULL on failure. */
  2310. const uint8_t *
  2311. decode_address_from_payload(tor_addr_t *addr_out, const uint8_t *payload,
  2312. int payload_len)
  2313. {
  2314. if (payload_len < 2)
  2315. return NULL;
  2316. if (payload_len < 2+payload[1])
  2317. return NULL;
  2318. switch (payload[0]) {
  2319. case RESOLVED_TYPE_IPV4:
  2320. if (payload[1] != 4)
  2321. return NULL;
  2322. tor_addr_from_ipv4n(addr_out, get_uint32(payload+2));
  2323. break;
  2324. case RESOLVED_TYPE_IPV6:
  2325. if (payload[1] != 16)
  2326. return NULL;
  2327. tor_addr_from_ipv6_bytes(addr_out, (char*)(payload+2));
  2328. break;
  2329. default:
  2330. tor_addr_make_unspec(addr_out);
  2331. break;
  2332. }
  2333. return payload + 2 + payload[1];
  2334. }
  2335. /** Remove all the cells queued on <b>circ</b> for <b>chan</b>. */
  2336. void
  2337. circuit_clear_cell_queue(circuit_t *circ, channel_t *chan)
  2338. {
  2339. cell_queue_t *queue;
  2340. cell_direction_t direction;
  2341. if (circ->n_chan == chan) {
  2342. queue = &circ->n_chan_cells;
  2343. direction = CELL_DIRECTION_OUT;
  2344. } else {
  2345. or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
  2346. tor_assert(orcirc->p_chan == chan);
  2347. queue = &orcirc->p_chan_cells;
  2348. direction = CELL_DIRECTION_IN;
  2349. }
  2350. /* Clear the queue */
  2351. cell_queue_clear(queue);
  2352. /* Update the cell counter in the cmux */
  2353. if (chan->cmux && circuitmux_is_circuit_attached(chan->cmux, circ))
  2354. update_circuit_on_cmux(circ, direction);
  2355. }
  2356. /** Fail with an assert if the circuit mux on chan is corrupt
  2357. */
  2358. void
  2359. assert_circuit_mux_okay(channel_t *chan)
  2360. {
  2361. tor_assert(chan);
  2362. tor_assert(chan->cmux);
  2363. circuitmux_assert_okay(chan->cmux);
  2364. }
  2365. /** Return 1 if we shouldn't restart reading on this circuit, even if
  2366. * we get a SENDME. Else return 0.
  2367. */
  2368. static int
  2369. circuit_queue_streams_are_blocked(circuit_t *circ)
  2370. {
  2371. if (CIRCUIT_IS_ORIGIN(circ)) {
  2372. return circ->streams_blocked_on_n_chan;
  2373. } else {
  2374. return circ->streams_blocked_on_p_chan;
  2375. }
  2376. }