relay.c 68 KB

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