relay.c 73 KB

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