relay.c 68 KB

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