relay.c 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  4. * Copyright (c) 2007-2010, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file relay.c
  8. * \brief Handle relay cell encryption/decryption, plus packaging and
  9. * receiving from circuits, plus queuing on circuits.
  10. **/
  11. #include "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 (cell_direction == CELL_DIRECTION_OUT && circ->n_conn) {
  482. /* if we're using relaybandwidthrate, this conn wants priority */
  483. circ->n_conn->client_used = approx_time();
  484. }
  485. if (cell_direction == CELL_DIRECTION_OUT) {
  486. origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
  487. if (origin_circ->remaining_relay_early_cells > 0 &&
  488. (relay_command == RELAY_COMMAND_EXTEND ||
  489. (cpath_layer != origin_circ->cpath &&
  490. !CIRCUIT_PURPOSE_IS_ESTABLISHED_REND(circ->purpose)))) {
  491. /* If we've got any relay_early cells left, and we're sending
  492. * an extend cell or (we're not talking to the first hop and we're
  493. * not talking to a rendezvous circuit), use one of them.
  494. * Don't worry about the conn protocol version:
  495. * append_cell_to_circuit_queue will fix it up. */
  496. /* XXX For now, clients don't use RELAY_EARLY cells when sending
  497. * relay cells on rendezvous circuits. See bug 1038. Eventually,
  498. * we can take this behavior away in favor of having clients avoid
  499. * rendezvous points running 0.2.1.3-alpha through 0.2.1.18. -RD */
  500. cell.command = CELL_RELAY_EARLY;
  501. --origin_circ->remaining_relay_early_cells;
  502. log_debug(LD_OR, "Sending a RELAY_EARLY cell; %d remaining.",
  503. (int)origin_circ->remaining_relay_early_cells);
  504. /* Memorize the command that is sent as RELAY_EARLY cell; helps debug
  505. * task 878. */
  506. origin_circ->relay_early_commands[
  507. origin_circ->relay_early_cells_sent++] = relay_command;
  508. } else if (relay_command == RELAY_COMMAND_EXTEND) {
  509. /* If no RELAY_EARLY cells can be sent over this circuit, log which
  510. * commands have been sent as RELAY_EARLY cells before; helps debug
  511. * task 878. */
  512. smartlist_t *commands_list = smartlist_create();
  513. int i = 0;
  514. char *commands = NULL;
  515. for (; i < origin_circ->relay_early_cells_sent; i++)
  516. smartlist_add(commands_list, (char *)
  517. relay_command_to_string(origin_circ->relay_early_commands[i]));
  518. commands = smartlist_join_strings(commands_list, ",", 0, NULL);
  519. log_warn(LD_BUG, "Uh-oh. We're sending a RELAY_COMMAND_EXTEND cell, "
  520. "but we have run out of RELAY_EARLY cells on that circuit. "
  521. "Commands sent before: %s", commands);
  522. tor_free(commands);
  523. smartlist_free(commands_list);
  524. }
  525. }
  526. if (circuit_package_relay_cell(&cell, circ, cell_direction, cpath_layer)
  527. < 0) {
  528. log_warn(LD_BUG,"circuit_package_relay_cell failed. Closing.");
  529. circuit_mark_for_close(circ, END_CIRC_REASON_INTERNAL);
  530. return -1;
  531. }
  532. return 0;
  533. }
  534. /** Make a relay cell out of <b>relay_command</b> and <b>payload</b>, and
  535. * send it onto the open circuit <b>circ</b>. <b>fromconn</b> is the stream
  536. * that's sending the relay cell, or NULL if it's a control cell.
  537. * <b>cpath_layer</b> is NULL for OR->OP cells, or the destination hop
  538. * for OP->OR cells.
  539. *
  540. * If you can't send the cell, mark the circuit for close and
  541. * return -1. Else return 0.
  542. */
  543. int
  544. connection_edge_send_command(edge_connection_t *fromconn,
  545. uint8_t relay_command, const char *payload,
  546. size_t payload_len)
  547. {
  548. /* XXXX NM Split this function into a separate versions per circuit type? */
  549. circuit_t *circ;
  550. tor_assert(fromconn);
  551. circ = fromconn->on_circuit;
  552. if (fromconn->_base.marked_for_close) {
  553. log_warn(LD_BUG,
  554. "called on conn that's already marked for close at %s:%d.",
  555. fromconn->_base.marked_for_close_file,
  556. fromconn->_base.marked_for_close);
  557. return 0;
  558. }
  559. if (!circ) {
  560. if (fromconn->_base.type == CONN_TYPE_AP) {
  561. log_info(LD_APP,"no circ. Closing conn.");
  562. connection_mark_unattached_ap(fromconn, END_STREAM_REASON_INTERNAL);
  563. } else {
  564. log_info(LD_EXIT,"no circ. Closing conn.");
  565. fromconn->edge_has_sent_end = 1; /* no circ to send to */
  566. fromconn->end_reason = END_STREAM_REASON_INTERNAL;
  567. connection_mark_for_close(TO_CONN(fromconn));
  568. }
  569. return -1;
  570. }
  571. return relay_send_command_from_edge(fromconn->stream_id, circ,
  572. relay_command, payload,
  573. payload_len, fromconn->cpath_layer);
  574. }
  575. /** How many times will I retry a stream that fails due to DNS
  576. * resolve failure or misc error?
  577. */
  578. #define MAX_RESOLVE_FAILURES 3
  579. /** Return 1 if reason is something that you should retry if you
  580. * get the end cell before you've connected; else return 0. */
  581. static int
  582. edge_reason_is_retriable(int reason)
  583. {
  584. return reason == END_STREAM_REASON_HIBERNATING ||
  585. reason == END_STREAM_REASON_RESOURCELIMIT ||
  586. reason == END_STREAM_REASON_EXITPOLICY ||
  587. reason == END_STREAM_REASON_RESOLVEFAILED ||
  588. reason == END_STREAM_REASON_MISC ||
  589. reason == END_STREAM_REASON_NOROUTE;
  590. }
  591. /** Called when we receive an END cell on a stream that isn't open yet,
  592. * from the client side.
  593. * Arguments are as for connection_edge_process_relay_cell().
  594. */
  595. static int
  596. connection_ap_process_end_not_open(
  597. relay_header_t *rh, cell_t *cell, origin_circuit_t *circ,
  598. edge_connection_t *conn, crypt_path_t *layer_hint)
  599. {
  600. struct in_addr in;
  601. routerinfo_t *exitrouter;
  602. int reason = *(cell->payload+RELAY_HEADER_SIZE);
  603. int control_reason = reason | END_STREAM_REASON_FLAG_REMOTE;
  604. (void) layer_hint; /* unused */
  605. if (rh->length > 0 && edge_reason_is_retriable(reason) &&
  606. !connection_edge_is_rendezvous_stream(conn) /* avoid retry if rend */
  607. ) {
  608. log_info(LD_APP,"Address '%s' refused due to '%s'. Considering retrying.",
  609. safe_str(conn->socks_request->address),
  610. stream_end_reason_to_string(reason));
  611. exitrouter =
  612. router_get_by_digest(circ->build_state->chosen_exit->identity_digest);
  613. switch (reason) {
  614. case END_STREAM_REASON_EXITPOLICY:
  615. if (rh->length >= 5) {
  616. uint32_t addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+1));
  617. int ttl;
  618. if (!addr) {
  619. log_info(LD_APP,"Address '%s' resolved to 0.0.0.0. Closing,",
  620. safe_str(conn->socks_request->address));
  621. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  622. return 0;
  623. }
  624. if (rh->length >= 9)
  625. ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+5));
  626. else
  627. ttl = -1;
  628. if (get_options()->ClientDNSRejectInternalAddresses &&
  629. is_internal_IP(addr, 0)) {
  630. log_info(LD_APP,"Address '%s' resolved to internal. Closing,",
  631. safe_str(conn->socks_request->address));
  632. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  633. return 0;
  634. }
  635. client_dns_set_addressmap(conn->socks_request->address, addr,
  636. conn->chosen_exit_name, ttl);
  637. }
  638. /* check if he *ought* to have allowed it */
  639. if (exitrouter &&
  640. (rh->length < 5 ||
  641. (tor_inet_aton(conn->socks_request->address, &in) &&
  642. !conn->chosen_exit_name))) {
  643. log_info(LD_APP,
  644. "Exitrouter '%s' seems to be more restrictive than its exit "
  645. "policy. Not using this router as exit for now.",
  646. exitrouter->nickname);
  647. policies_set_router_exitpolicy_to_reject_all(exitrouter);
  648. }
  649. /* rewrite it to an IP if we learned one. */
  650. if (addressmap_rewrite(conn->socks_request->address,
  651. sizeof(conn->socks_request->address),
  652. NULL)) {
  653. control_event_stream_status(conn, STREAM_EVENT_REMAP, 0);
  654. }
  655. if (conn->chosen_exit_optional ||
  656. conn->chosen_exit_retries) {
  657. /* stop wanting a specific exit */
  658. conn->chosen_exit_optional = 0;
  659. /* A non-zero chosen_exit_retries can happen if we set a
  660. * TrackHostExits for this address under a port that the exit
  661. * relay allows, but then try the same address with a different
  662. * port that it doesn't allow to exit. We shouldn't unregister
  663. * the mapping, since it is probably still wanted on the
  664. * original port. But now we give away to the exit relay that
  665. * we probably have a TrackHostExits on it. So be it. */
  666. conn->chosen_exit_retries = 0;
  667. tor_free(conn->chosen_exit_name); /* clears it */
  668. }
  669. if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
  670. return 0;
  671. /* else, conn will get closed below */
  672. break;
  673. case END_STREAM_REASON_CONNECTREFUSED:
  674. if (!conn->chosen_exit_optional)
  675. break; /* break means it'll close, below */
  676. /* Else fall through: expire this circuit, clear the
  677. * chosen_exit_name field, and try again. */
  678. case END_STREAM_REASON_RESOLVEFAILED:
  679. case END_STREAM_REASON_TIMEOUT:
  680. case END_STREAM_REASON_MISC:
  681. case END_STREAM_REASON_NOROUTE:
  682. if (client_dns_incr_failures(conn->socks_request->address)
  683. < MAX_RESOLVE_FAILURES) {
  684. /* We haven't retried too many times; reattach the connection. */
  685. circuit_log_path(LOG_INFO,LD_APP,circ);
  686. tor_assert(circ->_base.timestamp_dirty);
  687. circ->_base.timestamp_dirty -= get_options()->MaxCircuitDirtiness;
  688. if (conn->chosen_exit_optional) {
  689. /* stop wanting a specific exit */
  690. conn->chosen_exit_optional = 0;
  691. tor_free(conn->chosen_exit_name); /* clears it */
  692. }
  693. if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
  694. return 0;
  695. /* else, conn will get closed below */
  696. } else {
  697. log_notice(LD_APP,
  698. "Have tried resolving or connecting to address '%s' "
  699. "at %d different places. Giving up.",
  700. safe_str(conn->socks_request->address),
  701. MAX_RESOLVE_FAILURES);
  702. /* clear the failures, so it will have a full try next time */
  703. client_dns_clear_failures(conn->socks_request->address);
  704. }
  705. break;
  706. case END_STREAM_REASON_HIBERNATING:
  707. case END_STREAM_REASON_RESOURCELIMIT:
  708. if (exitrouter) {
  709. policies_set_router_exitpolicy_to_reject_all(exitrouter);
  710. }
  711. if (conn->chosen_exit_optional) {
  712. /* stop wanting a specific exit */
  713. conn->chosen_exit_optional = 0;
  714. tor_free(conn->chosen_exit_name); /* clears it */
  715. }
  716. if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
  717. return 0;
  718. /* else, will close below */
  719. break;
  720. } /* end switch */
  721. log_info(LD_APP,"Giving up on retrying; conn can't be handled.");
  722. }
  723. log_info(LD_APP,
  724. "Edge got end (%s) before we're connected. Marking for close.",
  725. stream_end_reason_to_string(rh->length > 0 ? reason : -1));
  726. circuit_log_path(LOG_INFO,LD_APP,circ);
  727. /* need to test because of detach_retriable */
  728. if (!conn->_base.marked_for_close)
  729. connection_mark_unattached_ap(conn, control_reason);
  730. return 0;
  731. }
  732. /** Helper: change the socks_request-&gt;address field on conn to the
  733. * dotted-quad representation of <b>new_addr</b> (given in host order),
  734. * and send an appropriate REMAP event. */
  735. static void
  736. remap_event_helper(edge_connection_t *conn, uint32_t new_addr)
  737. {
  738. struct in_addr in;
  739. in.s_addr = htonl(new_addr);
  740. tor_inet_ntoa(&in, conn->socks_request->address,
  741. sizeof(conn->socks_request->address));
  742. control_event_stream_status(conn, STREAM_EVENT_REMAP,
  743. REMAP_STREAM_SOURCE_EXIT);
  744. }
  745. /** An incoming relay cell has arrived from circuit <b>circ</b> to
  746. * stream <b>conn</b>.
  747. *
  748. * The arguments here are the same as in
  749. * connection_edge_process_relay_cell() below; this function is called
  750. * from there when <b>conn</b> is defined and not in an open state.
  751. */
  752. static int
  753. connection_edge_process_relay_cell_not_open(
  754. relay_header_t *rh, cell_t *cell, circuit_t *circ,
  755. edge_connection_t *conn, crypt_path_t *layer_hint)
  756. {
  757. if (rh->command == RELAY_COMMAND_END) {
  758. if (CIRCUIT_IS_ORIGIN(circ) && conn->_base.type == CONN_TYPE_AP) {
  759. return connection_ap_process_end_not_open(rh, cell,
  760. TO_ORIGIN_CIRCUIT(circ), conn,
  761. layer_hint);
  762. } else {
  763. /* we just got an 'end', don't need to send one */
  764. conn->edge_has_sent_end = 1;
  765. conn->end_reason = *(cell->payload+RELAY_HEADER_SIZE) |
  766. END_STREAM_REASON_FLAG_REMOTE;
  767. connection_mark_for_close(TO_CONN(conn));
  768. return 0;
  769. }
  770. }
  771. if (conn->_base.type == CONN_TYPE_AP &&
  772. rh->command == RELAY_COMMAND_CONNECTED) {
  773. tor_assert(CIRCUIT_IS_ORIGIN(circ));
  774. if (conn->_base.state != AP_CONN_STATE_CONNECT_WAIT) {
  775. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  776. "Got 'connected' while not in state connect_wait. Dropping.");
  777. return 0;
  778. }
  779. conn->_base.state = AP_CONN_STATE_OPEN;
  780. log_info(LD_APP,"'connected' received after %d seconds.",
  781. (int)(time(NULL) - conn->_base.timestamp_lastread));
  782. if (rh->length >= 4) {
  783. uint32_t addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE));
  784. int ttl;
  785. if (!addr || (get_options()->ClientDNSRejectInternalAddresses &&
  786. is_internal_IP(addr, 0))) {
  787. char buf[INET_NTOA_BUF_LEN];
  788. struct in_addr a;
  789. a.s_addr = htonl(addr);
  790. tor_inet_ntoa(&a, buf, sizeof(buf));
  791. log_info(LD_APP,
  792. "...but it claims the IP address was %s. Closing.", buf);
  793. connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
  794. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  795. return 0;
  796. }
  797. if (rh->length >= 8)
  798. ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+4));
  799. else
  800. ttl = -1;
  801. client_dns_set_addressmap(conn->socks_request->address, addr,
  802. conn->chosen_exit_name, ttl);
  803. remap_event_helper(conn, addr);
  804. }
  805. circuit_log_path(LOG_INFO,LD_APP,TO_ORIGIN_CIRCUIT(circ));
  806. /* don't send a socks reply to transparent conns */
  807. if (!conn->socks_request->has_finished)
  808. connection_ap_handshake_socks_reply(conn, NULL, 0, 0);
  809. /* Was it a linked dir conn? If so, a dir request just started to
  810. * fetch something; this could be a bootstrap status milestone. */
  811. log_debug(LD_APP, "considering");
  812. if (TO_CONN(conn)->linked_conn &&
  813. TO_CONN(conn)->linked_conn->type == CONN_TYPE_DIR) {
  814. connection_t *dirconn = TO_CONN(conn)->linked_conn;
  815. log_debug(LD_APP, "it is! %d", dirconn->purpose);
  816. switch (dirconn->purpose) {
  817. case DIR_PURPOSE_FETCH_CERTIFICATE:
  818. if (consensus_is_waiting_for_certs())
  819. control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_KEYS, 0);
  820. break;
  821. case DIR_PURPOSE_FETCH_CONSENSUS:
  822. control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_STATUS, 0);
  823. break;
  824. case DIR_PURPOSE_FETCH_SERVERDESC:
  825. control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_DESCRIPTORS,
  826. count_loading_descriptors_progress());
  827. break;
  828. }
  829. }
  830. /* handle anything that might have queued */
  831. if (connection_edge_package_raw_inbuf(conn, 1) < 0) {
  832. /* (We already sent an end cell if possible) */
  833. connection_mark_for_close(TO_CONN(conn));
  834. return 0;
  835. }
  836. return 0;
  837. }
  838. if (conn->_base.type == CONN_TYPE_AP &&
  839. rh->command == RELAY_COMMAND_RESOLVED) {
  840. int ttl;
  841. int answer_len;
  842. uint8_t answer_type;
  843. if (conn->_base.state != AP_CONN_STATE_RESOLVE_WAIT) {
  844. log_fn(LOG_PROTOCOL_WARN, LD_APP, "Got a 'resolved' cell while "
  845. "not in state resolve_wait. Dropping.");
  846. return 0;
  847. }
  848. tor_assert(SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command));
  849. answer_len = cell->payload[RELAY_HEADER_SIZE+1];
  850. if (rh->length < 2 || answer_len+2>rh->length) {
  851. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  852. "Dropping malformed 'resolved' cell");
  853. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  854. return 0;
  855. }
  856. answer_type = cell->payload[RELAY_HEADER_SIZE];
  857. if (rh->length >= answer_len+6)
  858. ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+
  859. 2+answer_len));
  860. else
  861. ttl = -1;
  862. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
  863. uint32_t addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+2));
  864. if (get_options()->ClientDNSRejectInternalAddresses &&
  865. is_internal_IP(addr, 0)) {
  866. char buf[INET_NTOA_BUF_LEN];
  867. struct in_addr a;
  868. a.s_addr = htonl(addr);
  869. tor_inet_ntoa(&a, buf, sizeof(buf));
  870. log_info(LD_APP,"Got a resolve with answer %s. Rejecting.", buf);
  871. connection_ap_handshake_socks_resolved(conn,
  872. RESOLVED_TYPE_ERROR_TRANSIENT,
  873. 0, NULL, 0, TIME_MAX);
  874. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  875. return 0;
  876. }
  877. }
  878. connection_ap_handshake_socks_resolved(conn,
  879. answer_type,
  880. cell->payload[RELAY_HEADER_SIZE+1], /*answer_len*/
  881. cell->payload+RELAY_HEADER_SIZE+2, /*answer*/
  882. ttl,
  883. -1);
  884. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
  885. uint32_t addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+2));
  886. remap_event_helper(conn, addr);
  887. }
  888. connection_mark_unattached_ap(conn,
  889. END_STREAM_REASON_DONE |
  890. END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
  891. return 0;
  892. }
  893. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  894. "Got an unexpected relay command %d, in state %d (%s). Dropping.",
  895. rh->command, conn->_base.state,
  896. conn_state_to_string(conn->_base.type, conn->_base.state));
  897. return 0; /* for forward compatibility, don't kill the circuit */
  898. // connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
  899. // connection_mark_for_close(conn);
  900. // return -1;
  901. }
  902. /** An incoming relay cell has arrived on circuit <b>circ</b>. If
  903. * <b>conn</b> is NULL this is a control cell, else <b>cell</b> is
  904. * destined for <b>conn</b>.
  905. *
  906. * If <b>layer_hint</b> is defined, then we're the origin of the
  907. * circuit, and it specifies the hop that packaged <b>cell</b>.
  908. *
  909. * Return -reason if you want to warn and tear down the circuit, else 0.
  910. */
  911. static int
  912. connection_edge_process_relay_cell(cell_t *cell, circuit_t *circ,
  913. edge_connection_t *conn,
  914. crypt_path_t *layer_hint)
  915. {
  916. static int num_seen=0;
  917. relay_header_t rh;
  918. unsigned domain = layer_hint?LD_APP:LD_EXIT;
  919. int reason;
  920. tor_assert(cell);
  921. tor_assert(circ);
  922. relay_header_unpack(&rh, cell->payload);
  923. // log_fn(LOG_DEBUG,"command %d stream %d", rh.command, rh.stream_id);
  924. num_seen++;
  925. log_debug(domain, "Now seen %d relay cells here.", num_seen);
  926. if (rh.length > RELAY_PAYLOAD_SIZE) {
  927. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  928. "Relay cell length field too long. Closing circuit.");
  929. return - END_CIRC_REASON_TORPROTOCOL;
  930. }
  931. /* either conn is NULL, in which case we've got a control cell, or else
  932. * conn points to the recognized stream. */
  933. if (conn && !connection_state_is_open(TO_CONN(conn)))
  934. return connection_edge_process_relay_cell_not_open(
  935. &rh, cell, circ, conn, layer_hint);
  936. switch (rh.command) {
  937. case RELAY_COMMAND_DROP:
  938. // log_info(domain,"Got a relay-level padding cell. Dropping.");
  939. return 0;
  940. case RELAY_COMMAND_BEGIN:
  941. case RELAY_COMMAND_BEGIN_DIR:
  942. if (layer_hint &&
  943. circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
  944. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  945. "Relay begin request unsupported at AP. Dropping.");
  946. return 0;
  947. }
  948. if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED &&
  949. layer_hint != TO_ORIGIN_CIRCUIT(circ)->cpath->prev) {
  950. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  951. "Relay begin request to Hidden Service "
  952. "from intermediary node. Dropping.");
  953. return 0;
  954. }
  955. if (conn) {
  956. log_fn(LOG_PROTOCOL_WARN, domain,
  957. "Begin cell for known stream. Dropping.");
  958. return 0;
  959. }
  960. return connection_exit_begin_conn(cell, circ);
  961. case RELAY_COMMAND_DATA:
  962. ++stats_n_data_cells_received;
  963. if (( layer_hint && --layer_hint->deliver_window < 0) ||
  964. (!layer_hint && --circ->deliver_window < 0)) {
  965. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  966. "(relay data) circ deliver_window below 0. Killing.");
  967. connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
  968. connection_mark_for_close(TO_CONN(conn));
  969. return -END_CIRC_REASON_TORPROTOCOL;
  970. }
  971. log_debug(domain,"circ deliver_window now %d.", layer_hint ?
  972. layer_hint->deliver_window : circ->deliver_window);
  973. circuit_consider_sending_sendme(circ, layer_hint);
  974. if (!conn) {
  975. log_info(domain,"data cell dropped, unknown stream (streamid %d).",
  976. rh.stream_id);
  977. return 0;
  978. }
  979. if (--conn->deliver_window < 0) { /* is it below 0 after decrement? */
  980. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  981. "(relay data) conn deliver_window below 0. Killing.");
  982. return -END_CIRC_REASON_TORPROTOCOL;
  983. }
  984. stats_n_data_bytes_received += rh.length;
  985. connection_write_to_buf(cell->payload + RELAY_HEADER_SIZE,
  986. rh.length, TO_CONN(conn));
  987. connection_edge_consider_sending_sendme(conn);
  988. return 0;
  989. case RELAY_COMMAND_END:
  990. reason = rh.length > 0 ?
  991. *(uint8_t *)(cell->payload+RELAY_HEADER_SIZE) : END_STREAM_REASON_MISC;
  992. if (!conn) {
  993. log_info(domain,"end cell (%s) dropped, unknown stream.",
  994. stream_end_reason_to_string(reason));
  995. return 0;
  996. }
  997. /* XXX add to this log_fn the exit node's nickname? */
  998. log_info(domain,"%d: end cell (%s) for stream %d. Removing stream.",
  999. conn->_base.s,
  1000. stream_end_reason_to_string(reason),
  1001. conn->stream_id);
  1002. if (conn->socks_request && !conn->socks_request->has_finished)
  1003. log_warn(LD_BUG,
  1004. "open stream hasn't sent socks answer yet? Closing.");
  1005. /* We just *got* an end; no reason to send one. */
  1006. conn->edge_has_sent_end = 1;
  1007. if (!conn->end_reason)
  1008. conn->end_reason = reason | END_STREAM_REASON_FLAG_REMOTE;
  1009. if (!conn->_base.marked_for_close) {
  1010. /* only mark it if not already marked. it's possible to
  1011. * get the 'end' right around when the client hangs up on us. */
  1012. connection_mark_for_close(TO_CONN(conn));
  1013. conn->_base.hold_open_until_flushed = 1;
  1014. }
  1015. return 0;
  1016. case RELAY_COMMAND_EXTEND:
  1017. if (conn) {
  1018. log_fn(LOG_PROTOCOL_WARN, domain,
  1019. "'extend' cell received for non-zero stream. Dropping.");
  1020. return 0;
  1021. }
  1022. return circuit_extend(cell, circ);
  1023. case RELAY_COMMAND_EXTENDED:
  1024. if (!layer_hint) {
  1025. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1026. "'extended' unsupported at non-origin. Dropping.");
  1027. return 0;
  1028. }
  1029. log_debug(domain,"Got an extended cell! Yay.");
  1030. if ((reason = circuit_finish_handshake(TO_ORIGIN_CIRCUIT(circ),
  1031. CELL_CREATED,
  1032. cell->payload+RELAY_HEADER_SIZE)) < 0) {
  1033. log_warn(domain,"circuit_finish_handshake failed.");
  1034. return reason;
  1035. }
  1036. if ((reason=circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ)))<0) {
  1037. log_info(domain,"circuit_send_next_onion_skin() failed.");
  1038. return reason;
  1039. }
  1040. return 0;
  1041. case RELAY_COMMAND_TRUNCATE:
  1042. if (layer_hint) {
  1043. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  1044. "'truncate' unsupported at origin. Dropping.");
  1045. return 0;
  1046. }
  1047. if (circ->n_conn) {
  1048. uint8_t trunc_reason = *(uint8_t*)(cell->payload + RELAY_HEADER_SIZE);
  1049. connection_or_send_destroy(circ->n_circ_id, circ->n_conn,
  1050. trunc_reason);
  1051. circuit_set_n_circid_orconn(circ, 0, NULL);
  1052. }
  1053. log_debug(LD_EXIT, "Processed 'truncate', replying.");
  1054. {
  1055. char payload[1];
  1056. payload[0] = (char)END_CIRC_REASON_REQUESTED;
  1057. relay_send_command_from_edge(0, circ, RELAY_COMMAND_TRUNCATED,
  1058. payload, sizeof(payload), NULL);
  1059. }
  1060. return 0;
  1061. case RELAY_COMMAND_TRUNCATED:
  1062. if (!layer_hint) {
  1063. log_fn(LOG_PROTOCOL_WARN, LD_EXIT,
  1064. "'truncated' unsupported at non-origin. Dropping.");
  1065. return 0;
  1066. }
  1067. circuit_truncated(TO_ORIGIN_CIRCUIT(circ), layer_hint);
  1068. return 0;
  1069. case RELAY_COMMAND_CONNECTED:
  1070. if (conn) {
  1071. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1072. "'connected' unsupported while open. Closing circ.");
  1073. return -END_CIRC_REASON_TORPROTOCOL;
  1074. }
  1075. log_info(domain,
  1076. "'connected' received, no conn attached anymore. Ignoring.");
  1077. return 0;
  1078. case RELAY_COMMAND_SENDME:
  1079. if (!conn) {
  1080. if (layer_hint) {
  1081. layer_hint->package_window += CIRCWINDOW_INCREMENT;
  1082. log_debug(LD_APP,"circ-level sendme at origin, packagewindow %d.",
  1083. layer_hint->package_window);
  1084. circuit_resume_edge_reading(circ, layer_hint);
  1085. } else {
  1086. circ->package_window += CIRCWINDOW_INCREMENT;
  1087. log_debug(LD_APP,
  1088. "circ-level sendme at non-origin, packagewindow %d.",
  1089. circ->package_window);
  1090. circuit_resume_edge_reading(circ, layer_hint);
  1091. }
  1092. return 0;
  1093. }
  1094. conn->package_window += STREAMWINDOW_INCREMENT;
  1095. log_debug(domain,"stream-level sendme, packagewindow now %d.",
  1096. conn->package_window);
  1097. connection_start_reading(TO_CONN(conn));
  1098. /* handle whatever might still be on the inbuf */
  1099. if (connection_edge_package_raw_inbuf(conn, 1) < 0) {
  1100. /* (We already sent an end cell if possible) */
  1101. connection_mark_for_close(TO_CONN(conn));
  1102. return 0;
  1103. }
  1104. return 0;
  1105. case RELAY_COMMAND_RESOLVE:
  1106. if (layer_hint) {
  1107. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  1108. "resolve request unsupported at AP; dropping.");
  1109. return 0;
  1110. } else if (conn) {
  1111. log_fn(LOG_PROTOCOL_WARN, domain,
  1112. "resolve request for known stream; dropping.");
  1113. return 0;
  1114. } else if (circ->purpose != CIRCUIT_PURPOSE_OR) {
  1115. log_fn(LOG_PROTOCOL_WARN, domain,
  1116. "resolve request on circ with purpose %d; dropping",
  1117. circ->purpose);
  1118. return 0;
  1119. }
  1120. connection_exit_begin_resolve(cell, TO_OR_CIRCUIT(circ));
  1121. return 0;
  1122. case RELAY_COMMAND_RESOLVED:
  1123. if (conn) {
  1124. log_fn(LOG_PROTOCOL_WARN, domain,
  1125. "'resolved' unsupported while open. Closing circ.");
  1126. return -END_CIRC_REASON_TORPROTOCOL;
  1127. }
  1128. log_info(domain,
  1129. "'resolved' received, no conn attached anymore. Ignoring.");
  1130. return 0;
  1131. case RELAY_COMMAND_ESTABLISH_INTRO:
  1132. case RELAY_COMMAND_ESTABLISH_RENDEZVOUS:
  1133. case RELAY_COMMAND_INTRODUCE1:
  1134. case RELAY_COMMAND_INTRODUCE2:
  1135. case RELAY_COMMAND_INTRODUCE_ACK:
  1136. case RELAY_COMMAND_RENDEZVOUS1:
  1137. case RELAY_COMMAND_RENDEZVOUS2:
  1138. case RELAY_COMMAND_INTRO_ESTABLISHED:
  1139. case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
  1140. rend_process_relay_cell(circ, layer_hint,
  1141. rh.command, rh.length,
  1142. cell->payload+RELAY_HEADER_SIZE);
  1143. return 0;
  1144. }
  1145. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1146. "Received unknown relay command %d. Perhaps the other side is using "
  1147. "a newer version of Tor? Dropping.",
  1148. rh.command);
  1149. return 0; /* for forward compatibility, don't kill the circuit */
  1150. }
  1151. /** How many relay_data cells have we built, ever? */
  1152. uint64_t stats_n_data_cells_packaged = 0;
  1153. /** How many bytes of data have we put in relay_data cells have we built,
  1154. * ever? This would be RELAY_PAYLOAD_SIZE*stats_n_data_cells_packaged if
  1155. * every relay cell we ever sent were completely full of data. */
  1156. uint64_t stats_n_data_bytes_packaged = 0;
  1157. /** How many relay_data cells have we received, ever? */
  1158. uint64_t stats_n_data_cells_received = 0;
  1159. /** How many bytes of data have we received relay_data cells, ever? This would
  1160. * be RELAY_PAYLOAD_SIZE*stats_n_data_cells_packaged if every relay cell we
  1161. * ever received were completely full of data. */
  1162. uint64_t stats_n_data_bytes_received = 0;
  1163. /** While conn->inbuf has an entire relay payload of bytes on it,
  1164. * and the appropriate package windows aren't empty, grab a cell
  1165. * and send it down the circuit.
  1166. *
  1167. * Return -1 (and send a RELAY_COMMAND_END cell if necessary) if conn should
  1168. * be marked for close, else return 0.
  1169. */
  1170. int
  1171. connection_edge_package_raw_inbuf(edge_connection_t *conn, int package_partial)
  1172. {
  1173. size_t amount_to_process, length;
  1174. char payload[CELL_PAYLOAD_SIZE];
  1175. circuit_t *circ;
  1176. unsigned domain = conn->cpath_layer ? LD_APP : LD_EXIT;
  1177. tor_assert(conn);
  1178. if (conn->_base.marked_for_close) {
  1179. log_warn(LD_BUG,
  1180. "called on conn that's already marked for close at %s:%d.",
  1181. conn->_base.marked_for_close_file, conn->_base.marked_for_close);
  1182. return 0;
  1183. }
  1184. repeat_connection_edge_package_raw_inbuf:
  1185. circ = circuit_get_by_edge_conn(conn);
  1186. if (!circ) {
  1187. log_info(domain,"conn has no circuit! Closing.");
  1188. conn->end_reason = END_STREAM_REASON_CANT_ATTACH;
  1189. return -1;
  1190. }
  1191. if (circuit_consider_stop_edge_reading(circ, conn->cpath_layer))
  1192. return 0;
  1193. if (conn->package_window <= 0) {
  1194. log_info(domain,"called with package_window %d. Skipping.",
  1195. conn->package_window);
  1196. connection_stop_reading(TO_CONN(conn));
  1197. return 0;
  1198. }
  1199. amount_to_process = buf_datalen(conn->_base.inbuf);
  1200. if (!amount_to_process)
  1201. return 0;
  1202. if (!package_partial && amount_to_process < RELAY_PAYLOAD_SIZE)
  1203. return 0;
  1204. if (amount_to_process > RELAY_PAYLOAD_SIZE) {
  1205. length = RELAY_PAYLOAD_SIZE;
  1206. } else {
  1207. length = amount_to_process;
  1208. }
  1209. stats_n_data_bytes_packaged += length;
  1210. stats_n_data_cells_packaged += 1;
  1211. connection_fetch_from_buf(payload, length, TO_CONN(conn));
  1212. log_debug(domain,"(%d) Packaging %d bytes (%d waiting).", conn->_base.s,
  1213. (int)length, (int)buf_datalen(conn->_base.inbuf));
  1214. if (connection_edge_send_command(conn, RELAY_COMMAND_DATA,
  1215. payload, length) < 0 )
  1216. /* circuit got marked for close, don't continue, don't need to mark conn */
  1217. return 0;
  1218. if (!conn->cpath_layer) { /* non-rendezvous exit */
  1219. tor_assert(circ->package_window > 0);
  1220. circ->package_window--;
  1221. } else { /* we're an AP, or an exit on a rendezvous circ */
  1222. tor_assert(conn->cpath_layer->package_window > 0);
  1223. conn->cpath_layer->package_window--;
  1224. }
  1225. if (--conn->package_window <= 0) { /* is it 0 after decrement? */
  1226. connection_stop_reading(TO_CONN(conn));
  1227. log_debug(domain,"conn->package_window reached 0.");
  1228. circuit_consider_stop_edge_reading(circ, conn->cpath_layer);
  1229. return 0; /* don't process the inbuf any more */
  1230. }
  1231. log_debug(domain,"conn->package_window is now %d",conn->package_window);
  1232. /* handle more if there's more, or return 0 if there isn't */
  1233. goto repeat_connection_edge_package_raw_inbuf;
  1234. }
  1235. /** Called when we've just received a relay data cell, or when
  1236. * we've just finished flushing all bytes to stream <b>conn</b>.
  1237. *
  1238. * If conn->outbuf is not too full, and our deliver window is
  1239. * low, send back a suitable number of stream-level sendme cells.
  1240. */
  1241. void
  1242. connection_edge_consider_sending_sendme(edge_connection_t *conn)
  1243. {
  1244. circuit_t *circ;
  1245. if (connection_outbuf_too_full(TO_CONN(conn)))
  1246. return;
  1247. circ = circuit_get_by_edge_conn(conn);
  1248. if (!circ) {
  1249. /* this can legitimately happen if the destroy has already
  1250. * arrived and torn down the circuit */
  1251. log_info(LD_APP,"No circuit associated with conn. Skipping.");
  1252. return;
  1253. }
  1254. while (conn->deliver_window <= STREAMWINDOW_START - STREAMWINDOW_INCREMENT) {
  1255. log_debug(conn->cpath_layer?LD_APP:LD_EXIT,
  1256. "Outbuf %d, Queuing stream sendme.",
  1257. (int)conn->_base.outbuf_flushlen);
  1258. conn->deliver_window += STREAMWINDOW_INCREMENT;
  1259. if (connection_edge_send_command(conn, RELAY_COMMAND_SENDME,
  1260. NULL, 0) < 0) {
  1261. log_warn(LD_APP,"connection_edge_send_command failed. Skipping.");
  1262. return; /* the circuit's closed, don't continue */
  1263. }
  1264. }
  1265. }
  1266. /** The circuit <b>circ</b> has received a circuit-level sendme
  1267. * (on hop <b>layer_hint</b>, if we're the OP). Go through all the
  1268. * attached streams and let them resume reading and packaging, if
  1269. * their stream windows allow it.
  1270. */
  1271. static void
  1272. circuit_resume_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
  1273. {
  1274. log_debug(layer_hint?LD_APP:LD_EXIT,"resuming");
  1275. if (CIRCUIT_IS_ORIGIN(circ))
  1276. circuit_resume_edge_reading_helper(TO_ORIGIN_CIRCUIT(circ)->p_streams,
  1277. circ, layer_hint);
  1278. else
  1279. circuit_resume_edge_reading_helper(TO_OR_CIRCUIT(circ)->n_streams,
  1280. circ, layer_hint);
  1281. }
  1282. /** A helper function for circuit_resume_edge_reading() above.
  1283. * The arguments are the same, except that <b>conn</b> is the head
  1284. * of a linked list of edge streams that should each be considered.
  1285. */
  1286. static int
  1287. circuit_resume_edge_reading_helper(edge_connection_t *conn,
  1288. circuit_t *circ,
  1289. crypt_path_t *layer_hint)
  1290. {
  1291. for ( ; conn; conn=conn->next_stream) {
  1292. if (conn->_base.marked_for_close)
  1293. continue;
  1294. if ((!layer_hint && conn->package_window > 0) ||
  1295. (layer_hint && conn->package_window > 0 &&
  1296. conn->cpath_layer == layer_hint)) {
  1297. connection_start_reading(TO_CONN(conn));
  1298. /* handle whatever might still be on the inbuf */
  1299. if (connection_edge_package_raw_inbuf(conn, 1)<0) {
  1300. /* (We already sent an end cell if possible) */
  1301. connection_mark_for_close(TO_CONN(conn));
  1302. continue;
  1303. }
  1304. /* If the circuit won't accept any more data, return without looking
  1305. * at any more of the streams. Any connections that should be stopped
  1306. * have already been stopped by connection_edge_package_raw_inbuf. */
  1307. if (circuit_consider_stop_edge_reading(circ, layer_hint))
  1308. return -1;
  1309. }
  1310. }
  1311. return 0;
  1312. }
  1313. /** Check if the package window for <b>circ</b> is empty (at
  1314. * hop <b>layer_hint</b> if it's defined).
  1315. *
  1316. * If yes, tell edge streams to stop reading and return 1.
  1317. * Else return 0.
  1318. */
  1319. static int
  1320. circuit_consider_stop_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
  1321. {
  1322. edge_connection_t *conn = NULL;
  1323. unsigned domain = layer_hint ? LD_APP : LD_EXIT;
  1324. if (!layer_hint) {
  1325. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  1326. log_debug(domain,"considering circ->package_window %d",
  1327. circ->package_window);
  1328. if (circ->package_window <= 0) {
  1329. log_debug(domain,"yes, not-at-origin. stopped.");
  1330. for (conn = or_circ->n_streams; conn; conn=conn->next_stream)
  1331. connection_stop_reading(TO_CONN(conn));
  1332. return 1;
  1333. }
  1334. return 0;
  1335. }
  1336. /* else, layer hint is defined, use it */
  1337. log_debug(domain,"considering layer_hint->package_window %d",
  1338. layer_hint->package_window);
  1339. if (layer_hint->package_window <= 0) {
  1340. log_debug(domain,"yes, at-origin. stopped.");
  1341. for (conn = TO_ORIGIN_CIRCUIT(circ)->p_streams; conn;
  1342. conn=conn->next_stream)
  1343. if (conn->cpath_layer == layer_hint)
  1344. connection_stop_reading(TO_CONN(conn));
  1345. return 1;
  1346. }
  1347. return 0;
  1348. }
  1349. /** Check if the deliver_window for circuit <b>circ</b> (at hop
  1350. * <b>layer_hint</b> if it's defined) is low enough that we should
  1351. * send a circuit-level sendme back down the circuit. If so, send
  1352. * enough sendmes that the window would be overfull if we sent any
  1353. * more.
  1354. */
  1355. static void
  1356. circuit_consider_sending_sendme(circuit_t *circ, crypt_path_t *layer_hint)
  1357. {
  1358. // log_fn(LOG_INFO,"Considering: layer_hint is %s",
  1359. // layer_hint ? "defined" : "null");
  1360. while ((layer_hint ? layer_hint->deliver_window : circ->deliver_window) <=
  1361. CIRCWINDOW_START - CIRCWINDOW_INCREMENT) {
  1362. log_debug(LD_CIRC,"Queuing circuit sendme.");
  1363. if (layer_hint)
  1364. layer_hint->deliver_window += CIRCWINDOW_INCREMENT;
  1365. else
  1366. circ->deliver_window += CIRCWINDOW_INCREMENT;
  1367. if (relay_send_command_from_edge(0, circ, RELAY_COMMAND_SENDME,
  1368. NULL, 0, layer_hint) < 0) {
  1369. log_warn(LD_CIRC,
  1370. "relay_send_command_from_edge failed. Circuit's closed.");
  1371. return; /* the circuit's closed, don't continue */
  1372. }
  1373. }
  1374. }
  1375. /** Stop reading on edge connections when we have this many cells
  1376. * waiting on the appropriate queue. */
  1377. #define CELL_QUEUE_HIGHWATER_SIZE 256
  1378. /** Start reading from edge connections again when we get down to this many
  1379. * cells. */
  1380. #define CELL_QUEUE_LOWWATER_SIZE 64
  1381. #ifdef ACTIVE_CIRCUITS_PARANOIA
  1382. #define assert_active_circuits_ok_paranoid(conn) \
  1383. assert_active_circuits_ok(conn)
  1384. #else
  1385. #define assert_active_circuits_ok_paranoid(conn)
  1386. #endif
  1387. /** The total number of cells we have allocated from the memory pool. */
  1388. static int total_cells_allocated = 0;
  1389. /** A memory pool to allocate packed_cell_t objects. */
  1390. static mp_pool_t *cell_pool = NULL;
  1391. /** Allocate structures to hold cells. */
  1392. void
  1393. init_cell_pool(void)
  1394. {
  1395. tor_assert(!cell_pool);
  1396. cell_pool = mp_pool_new(sizeof(packed_cell_t), 128*1024);
  1397. }
  1398. /** Free all storage used to hold cells. */
  1399. void
  1400. free_cell_pool(void)
  1401. {
  1402. /* Maybe we haven't called init_cell_pool yet; need to check for it. */
  1403. if (cell_pool) {
  1404. mp_pool_destroy(cell_pool);
  1405. cell_pool = NULL;
  1406. }
  1407. }
  1408. /** Free excess storage in cell pool. */
  1409. void
  1410. clean_cell_pool(void)
  1411. {
  1412. tor_assert(cell_pool);
  1413. mp_pool_clean(cell_pool, 0, 1);
  1414. }
  1415. /** Release storage held by <b>cell</b>. */
  1416. static INLINE void
  1417. packed_cell_free(packed_cell_t *cell)
  1418. {
  1419. --total_cells_allocated;
  1420. mp_pool_release(cell);
  1421. }
  1422. /** Allocate and return a new packed_cell_t. */
  1423. static INLINE packed_cell_t *
  1424. packed_cell_alloc(void)
  1425. {
  1426. ++total_cells_allocated;
  1427. return mp_pool_get(cell_pool);
  1428. }
  1429. /** Log current statistics for cell pool allocation at log level
  1430. * <b>severity</b>. */
  1431. void
  1432. dump_cell_pool_usage(int severity)
  1433. {
  1434. circuit_t *c;
  1435. int n_circs = 0;
  1436. int n_cells = 0;
  1437. for (c = _circuit_get_global_list(); c; c = c->next) {
  1438. n_cells += c->n_conn_cells.n;
  1439. if (!CIRCUIT_IS_ORIGIN(c))
  1440. n_cells += TO_OR_CIRCUIT(c)->p_conn_cells.n;
  1441. ++n_circs;
  1442. }
  1443. log(severity, LD_MM, "%d cells allocated on %d circuits. %d cells leaked.",
  1444. n_cells, n_circs, total_cells_allocated - n_cells);
  1445. mp_pool_log_status(cell_pool, severity);
  1446. }
  1447. /** Allocate a new copy of packed <b>cell</b>. */
  1448. static INLINE packed_cell_t *
  1449. packed_cell_copy(const cell_t *cell)
  1450. {
  1451. packed_cell_t *c = packed_cell_alloc();
  1452. cell_pack(c, cell);
  1453. c->next = NULL;
  1454. return c;
  1455. }
  1456. /** Append <b>cell</b> to the end of <b>queue</b>. */
  1457. void
  1458. cell_queue_append(cell_queue_t *queue, packed_cell_t *cell)
  1459. {
  1460. if (queue->tail) {
  1461. tor_assert(!queue->tail->next);
  1462. queue->tail->next = cell;
  1463. } else {
  1464. queue->head = cell;
  1465. }
  1466. queue->tail = cell;
  1467. cell->next = NULL;
  1468. ++queue->n;
  1469. }
  1470. /** Append a newly allocated copy of <b>cell</b> to the end of <b>queue</b> */
  1471. void
  1472. cell_queue_append_packed_copy(cell_queue_t *queue, const cell_t *cell)
  1473. {
  1474. cell_queue_append(queue, packed_cell_copy(cell));
  1475. }
  1476. /** Remove and free every cell in <b>queue</b>. */
  1477. void
  1478. cell_queue_clear(cell_queue_t *queue)
  1479. {
  1480. packed_cell_t *cell, *next;
  1481. cell = queue->head;
  1482. while (cell) {
  1483. next = cell->next;
  1484. packed_cell_free(cell);
  1485. cell = next;
  1486. }
  1487. queue->head = queue->tail = NULL;
  1488. queue->n = 0;
  1489. }
  1490. /** Extract and return the cell at the head of <b>queue</b>; return NULL if
  1491. * <b>queue</b> is empty. */
  1492. static INLINE packed_cell_t *
  1493. cell_queue_pop(cell_queue_t *queue)
  1494. {
  1495. packed_cell_t *cell = queue->head;
  1496. if (!cell)
  1497. return NULL;
  1498. queue->head = cell->next;
  1499. if (cell == queue->tail) {
  1500. tor_assert(!queue->head);
  1501. queue->tail = NULL;
  1502. }
  1503. --queue->n;
  1504. return cell;
  1505. }
  1506. /** Return a pointer to the "next_active_on_{n,p}_conn" pointer of <b>circ</b>,
  1507. * depending on whether <b>conn</b> matches n_conn or p_conn. */
  1508. static INLINE circuit_t **
  1509. next_circ_on_conn_p(circuit_t *circ, or_connection_t *conn)
  1510. {
  1511. tor_assert(circ);
  1512. tor_assert(conn);
  1513. if (conn == circ->n_conn) {
  1514. return &circ->next_active_on_n_conn;
  1515. } else {
  1516. or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
  1517. tor_assert(conn == orcirc->p_conn);
  1518. return &orcirc->next_active_on_p_conn;
  1519. }
  1520. }
  1521. /** Return a pointer to the "prev_active_on_{n,p}_conn" pointer of <b>circ</b>,
  1522. * depending on whether <b>conn</b> matches n_conn or p_conn. */
  1523. static INLINE circuit_t **
  1524. prev_circ_on_conn_p(circuit_t *circ, or_connection_t *conn)
  1525. {
  1526. tor_assert(circ);
  1527. tor_assert(conn);
  1528. if (conn == circ->n_conn) {
  1529. return &circ->prev_active_on_n_conn;
  1530. } else {
  1531. or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
  1532. tor_assert(conn == orcirc->p_conn);
  1533. return &orcirc->prev_active_on_p_conn;
  1534. }
  1535. }
  1536. /** Add <b>circ</b> to the list of circuits with pending cells on
  1537. * <b>conn</b>. No effect if <b>circ</b> is already unlinked. */
  1538. void
  1539. make_circuit_active_on_conn(circuit_t *circ, or_connection_t *conn)
  1540. {
  1541. circuit_t **nextp = next_circ_on_conn_p(circ, conn);
  1542. circuit_t **prevp = prev_circ_on_conn_p(circ, conn);
  1543. if (*nextp && *prevp) {
  1544. /* Already active. */
  1545. return;
  1546. }
  1547. if (! conn->active_circuits) {
  1548. conn->active_circuits = circ;
  1549. *prevp = *nextp = circ;
  1550. } else {
  1551. circuit_t *head = conn->active_circuits;
  1552. circuit_t *old_tail = *prev_circ_on_conn_p(head, conn);
  1553. *next_circ_on_conn_p(old_tail, conn) = circ;
  1554. *nextp = head;
  1555. *prev_circ_on_conn_p(head, conn) = circ;
  1556. *prevp = old_tail;
  1557. }
  1558. assert_active_circuits_ok_paranoid(conn);
  1559. }
  1560. /** Remove <b>circ</b> to the list of circuits with pending cells on
  1561. * <b>conn</b>. No effect if <b>circ</b> is already unlinked. */
  1562. void
  1563. make_circuit_inactive_on_conn(circuit_t *circ, or_connection_t *conn)
  1564. {
  1565. circuit_t **nextp = next_circ_on_conn_p(circ, conn);
  1566. circuit_t **prevp = prev_circ_on_conn_p(circ, conn);
  1567. circuit_t *next = *nextp, *prev = *prevp;
  1568. if (!next && !prev) {
  1569. /* Already inactive. */
  1570. return;
  1571. }
  1572. tor_assert(next && prev);
  1573. tor_assert(*prev_circ_on_conn_p(next, conn) == circ);
  1574. tor_assert(*next_circ_on_conn_p(prev, conn) == circ);
  1575. if (next == circ) {
  1576. conn->active_circuits = NULL;
  1577. } else {
  1578. *prev_circ_on_conn_p(next, conn) = prev;
  1579. *next_circ_on_conn_p(prev, conn) = next;
  1580. if (conn->active_circuits == circ)
  1581. conn->active_circuits = next;
  1582. }
  1583. *prevp = *nextp = NULL;
  1584. assert_active_circuits_ok_paranoid(conn);
  1585. }
  1586. /** Remove all circuits from the list of circuits with pending cells on
  1587. * <b>conn</b>. */
  1588. void
  1589. connection_or_unlink_all_active_circs(or_connection_t *orconn)
  1590. {
  1591. circuit_t *head = orconn->active_circuits;
  1592. circuit_t *cur = head;
  1593. if (! head)
  1594. return;
  1595. do {
  1596. circuit_t *next = *next_circ_on_conn_p(cur, orconn);
  1597. *prev_circ_on_conn_p(cur, orconn) = NULL;
  1598. *next_circ_on_conn_p(cur, orconn) = NULL;
  1599. cur = next;
  1600. } while (cur != head);
  1601. orconn->active_circuits = NULL;
  1602. }
  1603. /** Block (if <b>block</b> is true) or unblock (if <b>block</b> is false)
  1604. * every edge connection that is using <b>circ</b> to write to <b>orconn</b>,
  1605. * and start or stop reading as appropriate. */
  1606. static void
  1607. set_streams_blocked_on_circ(circuit_t *circ, or_connection_t *orconn,
  1608. int block)
  1609. {
  1610. edge_connection_t *edge = NULL;
  1611. if (circ->n_conn == orconn) {
  1612. circ->streams_blocked_on_n_conn = block;
  1613. if (CIRCUIT_IS_ORIGIN(circ))
  1614. edge = TO_ORIGIN_CIRCUIT(circ)->p_streams;
  1615. } else {
  1616. circ->streams_blocked_on_p_conn = block;
  1617. tor_assert(!CIRCUIT_IS_ORIGIN(circ));
  1618. edge = TO_OR_CIRCUIT(circ)->n_streams;
  1619. }
  1620. for (; edge; edge = edge->next_stream) {
  1621. connection_t *conn = TO_CONN(edge);
  1622. edge->edge_blocked_on_circ = block;
  1623. if (!conn->read_event) {
  1624. /* This connection is a placeholder for something; probably a DNS
  1625. * request. It can't actually stop or start reading.*/
  1626. continue;
  1627. }
  1628. if (block) {
  1629. if (connection_is_reading(conn))
  1630. connection_stop_reading(conn);
  1631. } else {
  1632. /* Is this right? */
  1633. if (!connection_is_reading(conn))
  1634. connection_start_reading(conn);
  1635. }
  1636. }
  1637. }
  1638. /** Pull as many cells as possible (but no more than <b>max</b>) from the
  1639. * queue of the first active circuit on <b>conn</b>, and write then to
  1640. * <b>conn</b>-&gt;outbuf. Return the number of cells written. Advance
  1641. * the active circuit pointer to the next active circuit in the ring. */
  1642. int
  1643. connection_or_flush_from_first_active_circuit(or_connection_t *conn, int max,
  1644. time_t now)
  1645. {
  1646. int n_flushed;
  1647. cell_queue_t *queue;
  1648. circuit_t *circ;
  1649. int streams_blocked;
  1650. circ = conn->active_circuits;
  1651. if (!circ) return 0;
  1652. assert_active_circuits_ok_paranoid(conn);
  1653. if (circ->n_conn == conn) {
  1654. queue = &circ->n_conn_cells;
  1655. streams_blocked = circ->streams_blocked_on_n_conn;
  1656. } else {
  1657. queue = &TO_OR_CIRCUIT(circ)->p_conn_cells;
  1658. streams_blocked = circ->streams_blocked_on_p_conn;
  1659. }
  1660. tor_assert(*next_circ_on_conn_p(circ,conn));
  1661. for (n_flushed = 0; n_flushed < max && queue->head; ) {
  1662. packed_cell_t *cell = cell_queue_pop(queue);
  1663. tor_assert(*next_circ_on_conn_p(circ,conn));
  1664. connection_write_to_buf(cell->body, CELL_NETWORK_SIZE, TO_CONN(conn));
  1665. packed_cell_free(cell);
  1666. ++n_flushed;
  1667. if (circ != conn->active_circuits) {
  1668. /* If this happens, the current circuit just got made inactive by
  1669. * a call in connection_write_to_buf(). That's nothing to worry about:
  1670. * circuit_make_inactive_on_conn() already advanced conn->active_circuits
  1671. * for us.
  1672. */
  1673. assert_active_circuits_ok_paranoid(conn);
  1674. goto done;
  1675. }
  1676. }
  1677. tor_assert(*next_circ_on_conn_p(circ,conn));
  1678. assert_active_circuits_ok_paranoid(conn);
  1679. conn->active_circuits = *next_circ_on_conn_p(circ, conn);
  1680. /* Is the cell queue low enough to unblock all the streams that are waiting
  1681. * to write to this circuit? */
  1682. if (streams_blocked && queue->n <= CELL_QUEUE_LOWWATER_SIZE)
  1683. set_streams_blocked_on_circ(circ, conn, 0); /* unblock streams */
  1684. /* Did we just ran out of cells on this queue? */
  1685. if (queue->n == 0) {
  1686. log_debug(LD_GENERAL, "Made a circuit inactive.");
  1687. make_circuit_inactive_on_conn(circ, conn);
  1688. }
  1689. done:
  1690. if (n_flushed)
  1691. conn->timestamp_last_added_nonpadding = now;
  1692. return n_flushed;
  1693. }
  1694. /** Add <b>cell</b> to the queue of <b>circ</b> writing to <b>orconn</b>
  1695. * transmitting in <b>direction</b>. */
  1696. void
  1697. append_cell_to_circuit_queue(circuit_t *circ, or_connection_t *orconn,
  1698. cell_t *cell, cell_direction_t direction)
  1699. {
  1700. cell_queue_t *queue;
  1701. int streams_blocked;
  1702. if (direction == CELL_DIRECTION_OUT) {
  1703. queue = &circ->n_conn_cells;
  1704. streams_blocked = circ->streams_blocked_on_n_conn;
  1705. } else {
  1706. or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
  1707. queue = &orcirc->p_conn_cells;
  1708. streams_blocked = circ->streams_blocked_on_p_conn;
  1709. }
  1710. if (cell->command == CELL_RELAY_EARLY && orconn->link_proto < 2) {
  1711. /* V1 connections don't understand RELAY_EARLY. */
  1712. cell->command = CELL_RELAY;
  1713. }
  1714. cell_queue_append_packed_copy(queue, cell);
  1715. /* If we have too many cells on the circuit, we should stop reading from
  1716. * the edge streams for a while. */
  1717. if (!streams_blocked && queue->n >= CELL_QUEUE_HIGHWATER_SIZE)
  1718. set_streams_blocked_on_circ(circ, orconn, 1); /* block streams */
  1719. if (queue->n == 1) {
  1720. /* This was the first cell added to the queue. We need to make this
  1721. * circuit active. */
  1722. log_debug(LD_GENERAL, "Made a circuit active.");
  1723. make_circuit_active_on_conn(circ, orconn);
  1724. }
  1725. if (! buf_datalen(orconn->_base.outbuf)) {
  1726. /* There is no data at all waiting to be sent on the outbuf. Add a
  1727. * cell, so that we can notice when it gets flushed, flushed_some can
  1728. * get called, and we can start putting more data onto the buffer then.
  1729. */
  1730. log_debug(LD_GENERAL, "Primed a buffer.");
  1731. connection_or_flush_from_first_active_circuit(orconn, 1, approx_time());
  1732. }
  1733. }
  1734. /** Append an encoded value of <b>addr</b> to <b>payload_out</b>, which must
  1735. * have at least 18 bytes of free space. The encoding is, as specified in
  1736. * tor-spec.txt:
  1737. * RESOLVED_TYPE_IPV4 or RESOLVED_TYPE_IPV6 [1 byte]
  1738. * LENGTH [1 byte]
  1739. * ADDRESS [length bytes]
  1740. * Return the number of bytes added, or -1 on error */
  1741. int
  1742. append_address_to_payload(char *payload_out, const tor_addr_t *addr)
  1743. {
  1744. uint32_t a;
  1745. switch (tor_addr_family(addr)) {
  1746. case AF_INET:
  1747. payload_out[0] = RESOLVED_TYPE_IPV4;
  1748. payload_out[1] = 4;
  1749. a = tor_addr_to_ipv4n(addr);
  1750. memcpy(payload_out+2, &a, 4);
  1751. return 6;
  1752. case AF_INET6:
  1753. payload_out[0] = RESOLVED_TYPE_IPV6;
  1754. payload_out[1] = 16;
  1755. memcpy(payload_out+2, tor_addr_to_in6_addr8(addr), 16);
  1756. return 18;
  1757. case AF_UNSPEC:
  1758. default:
  1759. return -1;
  1760. }
  1761. }
  1762. /** Given <b>payload_len</b> bytes at <b>payload</b>, starting with an address
  1763. * encoded as by append_address_to_payload(), try to decode the address into
  1764. * *<b>addr_out</b>. Return the next byte in the payload after the address on
  1765. * success, or NULL on failure. */
  1766. const char *
  1767. decode_address_from_payload(tor_addr_t *addr_out, const char *payload,
  1768. int payload_len)
  1769. {
  1770. if (payload_len < 2)
  1771. return NULL;
  1772. if (payload_len < 2+(uint8_t)payload[1])
  1773. return NULL;
  1774. switch (payload[0]) {
  1775. case RESOLVED_TYPE_IPV4:
  1776. if (payload[1] != 4)
  1777. return NULL;
  1778. tor_addr_from_ipv4n(addr_out, get_uint32(payload+2));
  1779. break;
  1780. case RESOLVED_TYPE_IPV6:
  1781. if (payload[1] != 16)
  1782. return NULL;
  1783. tor_addr_from_ipv6_bytes(addr_out, payload+2);
  1784. break;
  1785. default:
  1786. tor_addr_make_unspec(addr_out);
  1787. break;
  1788. }
  1789. return payload + 2 + (uint8_t)payload[1];
  1790. }
  1791. /** Fail with an assert if the active circuits ring on <b>orconn</b> is
  1792. * corrupt. */
  1793. void
  1794. assert_active_circuits_ok(or_connection_t *orconn)
  1795. {
  1796. circuit_t *head = orconn->active_circuits;
  1797. circuit_t *cur = head;
  1798. if (! head)
  1799. return;
  1800. do {
  1801. circuit_t *next = *next_circ_on_conn_p(cur, orconn);
  1802. circuit_t *prev = *prev_circ_on_conn_p(cur, orconn);
  1803. tor_assert(next);
  1804. tor_assert(prev);
  1805. tor_assert(*next_circ_on_conn_p(prev, orconn) == cur);
  1806. tor_assert(*prev_circ_on_conn_p(next, orconn) == cur);
  1807. cur = next;
  1808. } while (cur != head);
  1809. }