relay.c 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. const char relay_c_id[] =
  7. "$Id$";
  8. /**
  9. * \file relay.c
  10. * \brief Handle relay cell encryption/decryption, plus packaging and
  11. * receiving from circuits.
  12. **/
  13. #include "or.h"
  14. static int relay_crypt(circuit_t *circ, cell_t *cell, int 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. int cell_direction);
  18. static int
  19. connection_edge_process_relay_cell(cell_t *cell, circuit_t *circ,
  20. edge_connection_t *conn,
  21. crypt_path_t *layer_hint);
  22. static void
  23. circuit_consider_sending_sendme(circuit_t *circ, crypt_path_t *layer_hint);
  24. static void
  25. circuit_resume_edge_reading(circuit_t *circ, crypt_path_t *layer_hint);
  26. static int
  27. circuit_resume_edge_reading_helper(edge_connection_t *conn,
  28. circuit_t *circ,
  29. crypt_path_t *layer_hint);
  30. static int
  31. circuit_consider_stop_edge_reading(circuit_t *circ, crypt_path_t *layer_hint);
  32. /** Stats: how many relay cells have originated at this hop, or have
  33. * been relayed onward (not recognized at this hop)?
  34. */
  35. uint64_t stats_n_relay_cells_relayed = 0;
  36. /** Stats: how many relay cells have been delivered to streams at this
  37. * hop?
  38. */
  39. uint64_t stats_n_relay_cells_delivered = 0;
  40. /** Update digest from the payload of cell. Assign integrity part to
  41. * cell.
  42. */
  43. static void
  44. relay_set_digest(crypto_digest_env_t *digest, cell_t *cell)
  45. {
  46. char integrity[4];
  47. relay_header_t rh;
  48. crypto_digest_add_bytes(digest, cell->payload, CELL_PAYLOAD_SIZE);
  49. crypto_digest_get_digest(digest, integrity, 4);
  50. // log_fn(LOG_DEBUG,"Putting digest of %u %u %u %u into relay cell.",
  51. // integrity[0], integrity[1], integrity[2], integrity[3]);
  52. relay_header_unpack(&rh, cell->payload);
  53. memcpy(rh.integrity, integrity, 4);
  54. relay_header_pack(cell->payload, &rh);
  55. }
  56. /** Does the digest for this circuit indicate that this cell is for us?
  57. *
  58. * Update digest from the payload of cell (with the integrity part set
  59. * to 0). If the integrity part is valid, return 1, else restore digest
  60. * and cell to their original state and return 0.
  61. */
  62. static int
  63. relay_digest_matches(crypto_digest_env_t *digest, cell_t *cell)
  64. {
  65. char received_integrity[4], calculated_integrity[4];
  66. relay_header_t rh;
  67. crypto_digest_env_t *backup_digest=NULL;
  68. backup_digest = crypto_digest_dup(digest);
  69. relay_header_unpack(&rh, cell->payload);
  70. memcpy(received_integrity, rh.integrity, 4);
  71. memset(rh.integrity, 0, 4);
  72. relay_header_pack(cell->payload, &rh);
  73. // log_fn(LOG_DEBUG,"Reading digest of %u %u %u %u from relay cell.",
  74. // received_integrity[0], received_integrity[1],
  75. // received_integrity[2], received_integrity[3]);
  76. crypto_digest_add_bytes(digest, cell->payload, CELL_PAYLOAD_SIZE);
  77. crypto_digest_get_digest(digest, calculated_integrity, 4);
  78. if (memcmp(received_integrity, calculated_integrity, 4)) {
  79. // log_fn(LOG_INFO,"Recognized=0 but bad digest. Not recognizing.");
  80. // (%d vs %d).", received_integrity, calculated_integrity);
  81. /* restore digest to its old form */
  82. crypto_digest_assign(digest, backup_digest);
  83. /* restore the relay header */
  84. memcpy(rh.integrity, received_integrity, 4);
  85. relay_header_pack(cell->payload, &rh);
  86. crypto_free_digest_env(backup_digest);
  87. return 0;
  88. }
  89. crypto_free_digest_env(backup_digest);
  90. return 1;
  91. }
  92. /** Apply <b>cipher</b> to CELL_PAYLOAD_SIZE bytes of <b>in</b>
  93. * (in place).
  94. *
  95. * If <b>encrypt_mode</b> is 1 then encrypt, else decrypt.
  96. *
  97. * Return -1 if the crypto fails, else return 0.
  98. */
  99. static int
  100. relay_crypt_one_payload(crypto_cipher_env_t *cipher, char *in,
  101. int encrypt_mode)
  102. {
  103. char out[CELL_PAYLOAD_SIZE]; /* 'in' must be this size too */
  104. int r;
  105. if (encrypt_mode)
  106. r = crypto_cipher_encrypt(cipher, out, in, CELL_PAYLOAD_SIZE);
  107. else
  108. r = crypto_cipher_decrypt(cipher, out, in, CELL_PAYLOAD_SIZE);
  109. if (r) {
  110. log_warn(LD_BUG,"Error during relay encryption");
  111. return -1;
  112. }
  113. memcpy(in,out,CELL_PAYLOAD_SIZE);
  114. return 0;
  115. }
  116. /** Receive a relay cell:
  117. * - Crypt it (encrypt APward, decrypt at AP, decrypt exitward).
  118. * - Check if recognized (if exitward).
  119. * - If recognized and the digest checks out, then find if there's
  120. * a conn that the cell is intended for, and deliver it to
  121. * connection_edge.
  122. * - Else connection_or_write_cell_to_buf to the conn on the other
  123. * side of the circuit.
  124. *
  125. * Return -reason on failure.
  126. */
  127. int
  128. circuit_receive_relay_cell(cell_t *cell, circuit_t *circ, int cell_direction)
  129. {
  130. or_connection_t *or_conn=NULL;
  131. crypt_path_t *layer_hint=NULL;
  132. char recognized=0;
  133. int reason;
  134. tor_assert(cell);
  135. tor_assert(circ);
  136. tor_assert(cell_direction == CELL_DIRECTION_OUT ||
  137. cell_direction == CELL_DIRECTION_IN);
  138. if (circ->marked_for_close)
  139. return 0;
  140. if (relay_crypt(circ, cell, cell_direction, &layer_hint, &recognized) < 0) {
  141. log_warn(LD_BUG,"relay crypt failed. Dropping connection.");
  142. return -END_CIRC_REASON_INTERNAL;
  143. }
  144. if (recognized) {
  145. edge_connection_t *conn = relay_lookup_conn(circ, cell, cell_direction);
  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. // XXXX NM WARN.
  178. return 0;
  179. }
  180. if (!or_conn) {
  181. // XXXX Can this splice stuff be done more cleanly?
  182. if (! CIRCUIT_IS_ORIGIN(circ) &&
  183. TO_OR_CIRCUIT(circ)->rend_splice &&
  184. cell_direction == CELL_DIRECTION_OUT) {
  185. or_circuit_t *splice = TO_OR_CIRCUIT(circ)->rend_splice;
  186. tor_assert(circ->purpose == CIRCUIT_PURPOSE_REND_ESTABLISHED);
  187. tor_assert(splice->_base.purpose == CIRCUIT_PURPOSE_REND_ESTABLISHED);
  188. cell->circ_id = splice->p_circ_id;
  189. if ((reason = circuit_receive_relay_cell(cell, TO_CIRCUIT(splice),
  190. CELL_DIRECTION_IN)) < 0) {
  191. log_warn(LD_REND, "Error relaying cell across rendezvous; closing "
  192. "circuits");
  193. /* XXXX Do this here, or just return -1? */
  194. circuit_mark_for_close(circ, -reason);
  195. return reason;
  196. }
  197. return 0;
  198. }
  199. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  200. "Didn't recognize cell, but circ stops here! Closing circ.");
  201. return -END_CIRC_REASON_TORPROTOCOL;
  202. }
  203. log_debug(LD_OR,"Passing on unrecognized cell.");
  204. ++stats_n_relay_cells_relayed;
  205. connection_or_write_cell_to_buf(cell, or_conn);
  206. return 0;
  207. }
  208. /** Do the appropriate en/decryptions for <b>cell</b> arriving on
  209. * <b>circ</b> in direction <b>cell_direction</b>.
  210. *
  211. * If cell_direction == CELL_DIRECTION_IN:
  212. * - If we're at the origin (we're the OP), for hops 1..N,
  213. * decrypt cell. If recognized, stop.
  214. * - Else (we're not the OP), encrypt one hop. Cell is not recognized.
  215. *
  216. * If cell_direction == CELL_DIRECTION_OUT:
  217. * - decrypt one hop. Check if recognized.
  218. *
  219. * If cell is recognized, set *recognized to 1, and set
  220. * *layer_hint to the hop that recognized it.
  221. *
  222. * Return -1 to indicate that we should mark the circuit for close,
  223. * else return 0.
  224. */
  225. static int
  226. relay_crypt(circuit_t *circ, cell_t *cell, int cell_direction,
  227. crypt_path_t **layer_hint, char *recognized)
  228. {
  229. relay_header_t rh;
  230. tor_assert(circ);
  231. tor_assert(cell);
  232. tor_assert(recognized);
  233. tor_assert(cell_direction == CELL_DIRECTION_IN ||
  234. cell_direction == CELL_DIRECTION_OUT);
  235. if (cell_direction == CELL_DIRECTION_IN) {
  236. if (CIRCUIT_IS_ORIGIN(circ)) { /* We're at the beginning of the circuit.
  237. * We'll want to do layered decrypts. */
  238. crypt_path_t *thishop, *cpath = TO_ORIGIN_CIRCUIT(circ)->cpath;
  239. thishop = cpath;
  240. if (thishop->state != CPATH_STATE_OPEN) {
  241. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  242. "Relay cell before first created cell? Closing.");
  243. return -1;
  244. }
  245. do { /* Remember: cpath is in forward order, that is, first hop first. */
  246. tor_assert(thishop);
  247. if (relay_crypt_one_payload(thishop->b_crypto, cell->payload, 0) < 0)
  248. return -1;
  249. relay_header_unpack(&rh, cell->payload);
  250. if (rh.recognized == 0) {
  251. /* it's possibly recognized. have to check digest to be sure. */
  252. if (relay_digest_matches(thishop->b_digest, cell)) {
  253. *recognized = 1;
  254. *layer_hint = thishop;
  255. return 0;
  256. }
  257. }
  258. thishop = thishop->next;
  259. } while (thishop != cpath && thishop->state == CPATH_STATE_OPEN);
  260. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  261. "Incoming cell at client not recognized. Closing.");
  262. return -1;
  263. } else { /* we're in the middle. Just one crypt. */
  264. if (relay_crypt_one_payload(TO_OR_CIRCUIT(circ)->p_crypto,
  265. cell->payload, 1) < 0)
  266. return -1;
  267. // log_fn(LOG_DEBUG,"Skipping recognized check, because we're not "
  268. // "the client.");
  269. }
  270. } else /* cell_direction == CELL_DIRECTION_OUT */ {
  271. /* we're in the middle. Just one crypt. */
  272. if (relay_crypt_one_payload(TO_OR_CIRCUIT(circ)->n_crypto,
  273. cell->payload, 0) < 0)
  274. return -1;
  275. relay_header_unpack(&rh, cell->payload);
  276. if (rh.recognized == 0) {
  277. /* it's possibly recognized. have to check digest to be sure. */
  278. if (relay_digest_matches(TO_OR_CIRCUIT(circ)->n_digest, cell)) {
  279. *recognized = 1;
  280. return 0;
  281. }
  282. }
  283. }
  284. return 0;
  285. }
  286. /** Package a relay cell from an edge:
  287. * - Encrypt it to the right layer
  288. * - connection_or_write_cell_to_buf to the right conn
  289. */
  290. static int
  291. circuit_package_relay_cell(cell_t *cell, circuit_t *circ,
  292. int cell_direction,
  293. crypt_path_t *layer_hint)
  294. {
  295. or_connection_t *conn; /* where to send the cell */
  296. if (cell_direction == CELL_DIRECTION_OUT) {
  297. crypt_path_t *thishop; /* counter for repeated crypts */
  298. conn = circ->n_conn;
  299. if (!CIRCUIT_IS_ORIGIN(circ) || !conn) {
  300. log_warn(LD_BUG,"outgoing relay cell has n_conn==NULL. Dropping.");
  301. return 0; /* just drop it */
  302. }
  303. relay_set_digest(layer_hint->f_digest, cell);
  304. thishop = layer_hint;
  305. /* moving from farthest to nearest hop */
  306. do {
  307. tor_assert(thishop);
  308. /* XXXX RD This is a bug, right? */
  309. log_debug(LD_OR,"crypting a layer of the relay cell.");
  310. if (relay_crypt_one_payload(thishop->f_crypto, cell->payload, 1) < 0) {
  311. return -1;
  312. }
  313. thishop = thishop->prev;
  314. } while (thishop != TO_ORIGIN_CIRCUIT(circ)->cpath->prev);
  315. } else { /* incoming cell */
  316. or_circuit_t *or_circ;
  317. if (CIRCUIT_IS_ORIGIN(circ)) {
  318. /* XXXX RD This is a bug, right? */
  319. log_warn(LD_BUG,"incoming relay cell at origin circuit. Dropping.");
  320. assert_circuit_ok(circ);
  321. return 0; /* just drop it */
  322. }
  323. or_circ = TO_OR_CIRCUIT(circ);
  324. conn = or_circ->p_conn;
  325. relay_set_digest(or_circ->p_digest, cell);
  326. if (relay_crypt_one_payload(or_circ->p_crypto, cell->payload, 1) < 0)
  327. return -1;
  328. }
  329. ++stats_n_relay_cells_relayed;
  330. connection_or_write_cell_to_buf(cell, conn);
  331. return 0;
  332. }
  333. /** If cell's stream_id matches the stream_id of any conn that's
  334. * attached to circ, return that conn, else return NULL.
  335. */
  336. static edge_connection_t *
  337. relay_lookup_conn(circuit_t *circ, cell_t *cell, int cell_direction)
  338. {
  339. edge_connection_t *tmpconn;
  340. relay_header_t rh;
  341. relay_header_unpack(&rh, cell->payload);
  342. if (!rh.stream_id)
  343. return NULL;
  344. /* IN or OUT cells could have come from either direction, now
  345. * that we allow rendezvous *to* an OP.
  346. */
  347. if (CIRCUIT_IS_ORIGIN(circ)) {
  348. for (tmpconn = TO_ORIGIN_CIRCUIT(circ)->p_streams; tmpconn;
  349. tmpconn=tmpconn->next_stream) {
  350. if (rh.stream_id == tmpconn->stream_id &&
  351. !tmpconn->_base.marked_for_close) {
  352. log_debug(LD_APP,"found conn for stream %d.", rh.stream_id);
  353. return tmpconn;
  354. }
  355. }
  356. } else {
  357. for (tmpconn = TO_OR_CIRCUIT(circ)->n_streams; tmpconn;
  358. tmpconn=tmpconn->next_stream) {
  359. if (rh.stream_id == tmpconn->stream_id &&
  360. !tmpconn->_base.marked_for_close) {
  361. log_debug(LD_EXIT,"found conn for stream %d.", rh.stream_id);
  362. if (cell_direction == CELL_DIRECTION_OUT ||
  363. connection_edge_is_rendezvous_stream(tmpconn))
  364. return tmpconn;
  365. }
  366. }
  367. for (tmpconn = TO_OR_CIRCUIT(circ)->resolving_streams; tmpconn;
  368. tmpconn=tmpconn->next_stream) {
  369. if (rh.stream_id == tmpconn->stream_id &&
  370. !tmpconn->_base.marked_for_close) {
  371. log_debug(LD_EXIT,"found conn for stream %d.", rh.stream_id);
  372. return tmpconn;
  373. }
  374. }
  375. }
  376. return NULL; /* probably a begin relay cell */
  377. }
  378. /** Pack the relay_header_t host-order structure <b>src</b> into
  379. * network-order in the buffer <b>dest</b>. See tor-spec.txt for details
  380. * about the wire format.
  381. */
  382. void
  383. relay_header_pack(char *dest, const relay_header_t *src)
  384. {
  385. *(uint8_t*)(dest) = src->command;
  386. set_uint16(dest+1, htons(src->recognized));
  387. set_uint16(dest+3, htons(src->stream_id));
  388. memcpy(dest+5, src->integrity, 4);
  389. set_uint16(dest+9, htons(src->length));
  390. }
  391. /** Unpack the network-order buffer <b>src</b> into a host-order
  392. * relay_header_t structure <b>dest</b>.
  393. */
  394. void
  395. relay_header_unpack(relay_header_t *dest, const char *src)
  396. {
  397. dest->command = *(uint8_t*)(src);
  398. dest->recognized = ntohs(get_uint16(src+1));
  399. dest->stream_id = ntohs(get_uint16(src+3));
  400. memcpy(dest->integrity, src+5, 4);
  401. dest->length = ntohs(get_uint16(src+9));
  402. }
  403. /** Make a relay cell out of <b>relay_command</b> and <b>payload</b>, and send
  404. * it onto the open circuit <b>circ</b>. <b>stream_id</b> is the ID on
  405. * <b>circ</b> for the stream that's sending the relay cell, or 0 if it's a
  406. * control cell. <b>cpath_layer</b> is NULL for OR->OP cells, or the
  407. * destination hop for OP->OR cells.
  408. *
  409. * If you can't send the cell, mark the circuit for close and return -1. Else
  410. * return 0.
  411. */
  412. int
  413. relay_send_command_from_edge(uint16_t stream_id, circuit_t *circ,
  414. int relay_command, const char *payload,
  415. size_t payload_len, crypt_path_t *cpath_layer)
  416. {
  417. cell_t cell;
  418. relay_header_t rh;
  419. int cell_direction;
  420. /* XXXX NM Split this function into a separate versions per circuit type? */
  421. tor_assert(circ);
  422. memset(&cell, 0, sizeof(cell_t));
  423. cell.command = CELL_RELAY;
  424. if (cpath_layer) {
  425. cell.circ_id = circ->n_circ_id;
  426. cell_direction = CELL_DIRECTION_OUT;
  427. } else if (! CIRCUIT_IS_ORIGIN(circ)) {
  428. cell.circ_id = TO_OR_CIRCUIT(circ)->p_circ_id;
  429. cell_direction = CELL_DIRECTION_IN;
  430. } else {
  431. return -1;
  432. }
  433. memset(&rh, 0, sizeof(rh));
  434. rh.command = relay_command;
  435. rh.stream_id = stream_id;
  436. rh.length = payload_len;
  437. relay_header_pack(cell.payload, &rh);
  438. if (payload_len) {
  439. tor_assert(payload_len <= RELAY_PAYLOAD_SIZE);
  440. memcpy(cell.payload+RELAY_HEADER_SIZE, payload, payload_len);
  441. }
  442. log_debug(LD_OR,"delivering %d cell %s.", relay_command,
  443. cell_direction == CELL_DIRECTION_OUT ? "forward" : "backward");
  444. if (circuit_package_relay_cell(&cell, circ, cell_direction, cpath_layer)
  445. < 0) {
  446. log_warn(LD_BUG,"circuit_package_relay_cell failed. Closing.");
  447. circuit_mark_for_close(circ, END_CIRC_REASON_INTERNAL);
  448. return -1;
  449. }
  450. return 0;
  451. }
  452. /** Make a relay cell out of <b>relay_command</b> and <b>payload</b>, and
  453. * send it onto the open circuit <b>circ</b>. <b>fromconn</b> is the stream
  454. * that's sending the relay cell, or NULL if it's a control cell.
  455. * <b>cpath_layer</b> is NULL for OR->OP cells, or the destination hop
  456. * for OP->OR cells.
  457. *
  458. * If you can't send the cell, mark the circuit for close and
  459. * return -1. Else return 0.
  460. */
  461. int
  462. connection_edge_send_command(edge_connection_t *fromconn, circuit_t *circ,
  463. int relay_command, const char *payload,
  464. size_t payload_len, crypt_path_t *cpath_layer)
  465. {
  466. /* XXXX NM Split this function into a separate versions per circuit type? */
  467. if (fromconn && fromconn->_base.marked_for_close) {
  468. log_warn(LD_BUG,
  469. "Bug: called on conn that's already marked for close at %s:%d.",
  470. fromconn->_base.marked_for_close_file,
  471. fromconn->_base.marked_for_close);
  472. return 0;
  473. }
  474. if (!circ) {
  475. tor_assert(fromconn);
  476. if (fromconn->_base.type == CONN_TYPE_AP) {
  477. log_info(LD_APP,"no circ. Closing conn.");
  478. connection_mark_unattached_ap(fromconn, END_STREAM_REASON_INTERNAL);
  479. } else {
  480. log_info(LD_EXIT,"no circ. Closing conn.");
  481. fromconn->_base.edge_has_sent_end = 1; /* no circ to send to */
  482. fromconn->end_reason = END_STREAM_REASON_INTERNAL;
  483. connection_mark_for_close(TO_CONN(fromconn));
  484. }
  485. return -1;
  486. }
  487. return relay_send_command_from_edge(fromconn ? fromconn->stream_id : 0,
  488. circ, relay_command, payload,
  489. payload_len, cpath_layer);
  490. }
  491. /** Translate <b>reason</b>, which came from a relay 'end' cell,
  492. * into a static const string describing why the stream is closing.
  493. * <b>reason</b> is -1 if no reason was provided.
  494. */
  495. static const char *
  496. connection_edge_end_reason_str(int reason)
  497. {
  498. switch (reason) {
  499. case -1:
  500. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  501. "End cell arrived with length 0. Should be at least 1.");
  502. return "MALFORMED";
  503. case END_STREAM_REASON_MISC: return "misc error";
  504. case END_STREAM_REASON_RESOLVEFAILED: return "resolve failed";
  505. case END_STREAM_REASON_CONNECTREFUSED: return "connection refused";
  506. case END_STREAM_REASON_EXITPOLICY: return "exit policy failed";
  507. case END_STREAM_REASON_DESTROY: return "destroyed";
  508. case END_STREAM_REASON_DONE: return "closed normally";
  509. case END_STREAM_REASON_TIMEOUT: return "gave up (timeout)";
  510. case END_STREAM_REASON_HIBERNATING: return "server is hibernating";
  511. case END_STREAM_REASON_INTERNAL: return "internal error at server";
  512. case END_STREAM_REASON_RESOURCELIMIT: return "server out of resources";
  513. case END_STREAM_REASON_CONNRESET: return "connection reset";
  514. case END_STREAM_REASON_TORPROTOCOL: return "Tor protocol error";
  515. case END_STREAM_REASON_NOTDIRECTORY: return "not a directory";
  516. default:
  517. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  518. "Reason for ending (%d) not recognized.",reason);
  519. return "unknown";
  520. }
  521. }
  522. /** Translate <b>reason</b> (as from a relay 'end' cell) into an
  523. * appropriate SOCKS5 reply code.
  524. * DODCDOC 0
  525. */
  526. socks5_reply_status_t
  527. connection_edge_end_reason_socks5_response(int reason)
  528. {
  529. switch (reason) {
  530. case 0:
  531. return SOCKS5_SUCCEEDED;
  532. case END_STREAM_REASON_MISC:
  533. return SOCKS5_GENERAL_ERROR;
  534. case END_STREAM_REASON_RESOLVEFAILED:
  535. return SOCKS5_HOST_UNREACHABLE;
  536. case END_STREAM_REASON_CONNECTREFUSED:
  537. return SOCKS5_CONNECTION_REFUSED;
  538. case END_STREAM_REASON_EXITPOLICY:
  539. return SOCKS5_NOT_ALLOWED;
  540. case END_STREAM_REASON_DESTROY:
  541. return SOCKS5_GENERAL_ERROR;
  542. case END_STREAM_REASON_DONE:
  543. return SOCKS5_SUCCEEDED;
  544. case END_STREAM_REASON_TIMEOUT:
  545. return SOCKS5_TTL_EXPIRED;
  546. case END_STREAM_REASON_RESOURCELIMIT:
  547. return SOCKS5_GENERAL_ERROR;
  548. case END_STREAM_REASON_HIBERNATING:
  549. return SOCKS5_GENERAL_ERROR;
  550. case END_STREAM_REASON_INTERNAL:
  551. return SOCKS5_GENERAL_ERROR;
  552. case END_STREAM_REASON_CONNRESET:
  553. return SOCKS5_CONNECTION_REFUSED;
  554. case END_STREAM_REASON_TORPROTOCOL:
  555. return SOCKS5_GENERAL_ERROR;
  556. case END_STREAM_REASON_ALREADY_SOCKS_REPLIED:
  557. return SOCKS5_SUCCEEDED; /* never used */
  558. case END_STREAM_REASON_CANT_ATTACH:
  559. return SOCKS5_GENERAL_ERROR;
  560. case END_STREAM_REASON_NET_UNREACHABLE:
  561. return SOCKS5_NET_UNREACHABLE;
  562. case END_STREAM_REASON_SOCKSPROTOCOL:
  563. return SOCKS5_GENERAL_ERROR;
  564. default:
  565. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  566. "Reason for ending (%d) not recognized; "
  567. "sending generic socks error.", reason);
  568. return SOCKS5_GENERAL_ERROR;
  569. }
  570. }
  571. /* We need to use a few macros to deal with the fact that Windows
  572. * decided that their sockets interface should be a permakludge.
  573. * E_CASE is for errors where windows has both a EFOO and a WSAEFOO
  574. * version, and S_CASE is for errors where windows has only a WSAEFOO
  575. * version. (The E is for 'error', the S is for 'socket'). */
  576. #ifdef MS_WINDOWS
  577. #define E_CASE(s) case s: case WSA ## s
  578. #define S_CASE(s) case WSA ## s
  579. #else
  580. #define E_CASE(s) case s
  581. #define S_CASE(s) case s
  582. #endif
  583. /** Given an errno from a failed exit connection, return a reason code
  584. * appropriate for use in a RELAY END cell.
  585. */
  586. int
  587. errno_to_end_reason(int e)
  588. {
  589. switch (e) {
  590. case EPIPE:
  591. return END_STREAM_REASON_DONE;
  592. E_CASE(EBADF):
  593. E_CASE(EFAULT):
  594. E_CASE(EINVAL):
  595. S_CASE(EISCONN):
  596. S_CASE(ENOTSOCK):
  597. S_CASE(EPROTONOSUPPORT):
  598. S_CASE(EAFNOSUPPORT):
  599. E_CASE(EACCES):
  600. S_CASE(ENOTCONN):
  601. S_CASE(ENETUNREACH):
  602. return END_STREAM_REASON_INTERNAL;
  603. S_CASE(ECONNREFUSED):
  604. return END_STREAM_REASON_CONNECTREFUSED;
  605. S_CASE(ECONNRESET):
  606. return END_STREAM_REASON_CONNRESET;
  607. S_CASE(ETIMEDOUT):
  608. return END_STREAM_REASON_TIMEOUT;
  609. S_CASE(ENOBUFS):
  610. case ENOMEM:
  611. case ENFILE:
  612. E_CASE(EMFILE):
  613. return END_STREAM_REASON_RESOURCELIMIT;
  614. default:
  615. log_info(LD_EXIT, "Didn't recognize errno %d (%s); telling the client "
  616. "that we are ending a stream for 'misc' reason.",
  617. e, tor_socket_strerror(e));
  618. return END_STREAM_REASON_MISC;
  619. }
  620. }
  621. /** How many times will I retry a stream that fails due to DNS
  622. * resolve failure or misc error?
  623. */
  624. #define MAX_RESOLVE_FAILURES 3
  625. /** Return 1 if reason is something that you should retry if you
  626. * get the end cell before you've connected; else return 0. */
  627. static int
  628. edge_reason_is_retriable(int reason)
  629. {
  630. return reason == END_STREAM_REASON_HIBERNATING ||
  631. reason == END_STREAM_REASON_RESOURCELIMIT ||
  632. reason == END_STREAM_REASON_EXITPOLICY ||
  633. reason == END_STREAM_REASON_RESOLVEFAILED ||
  634. reason == END_STREAM_REASON_MISC;
  635. }
  636. /** Called when we receive an END cell on a stream that isn't open yet.
  637. * Arguments are as for connection_edge_process_relay_cell().
  638. */
  639. static int
  640. connection_edge_process_end_not_open(
  641. relay_header_t *rh, cell_t *cell, origin_circuit_t *circ,
  642. edge_connection_t *conn, crypt_path_t *layer_hint)
  643. {
  644. struct in_addr in;
  645. routerinfo_t *exitrouter;
  646. int reason = *(cell->payload+RELAY_HEADER_SIZE);
  647. int control_reason = reason | END_STREAM_REASON_FLAG_REMOTE;
  648. (void) layer_hint; /* unused */
  649. if (rh->length > 0 && edge_reason_is_retriable(reason) &&
  650. conn->_base.type == CONN_TYPE_AP) {
  651. log_info(LD_APP,"Address '%s' refused due to '%s'. Considering retrying.",
  652. safe_str(conn->socks_request->address),
  653. connection_edge_end_reason_str(reason));
  654. exitrouter =
  655. router_get_by_digest(circ->build_state->chosen_exit->identity_digest);
  656. switch (reason) {
  657. case END_STREAM_REASON_EXITPOLICY:
  658. if (rh->length >= 5) {
  659. uint32_t addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+1));
  660. int ttl;
  661. if (!addr) {
  662. log_info(LD_APP,"Address '%s' resolved to 0.0.0.0. Closing,",
  663. safe_str(conn->socks_request->address));
  664. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  665. return 0;
  666. }
  667. if (rh->length >= 9)
  668. ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+5));
  669. else
  670. ttl = -1;
  671. client_dns_set_addressmap(conn->socks_request->address, addr,
  672. conn->chosen_exit_name, ttl);
  673. }
  674. /* check if he *ought* to have allowed it */
  675. if (exitrouter &&
  676. (rh->length < 5 ||
  677. (tor_inet_aton(conn->socks_request->address, &in) &&
  678. !conn->chosen_exit_name))) {
  679. log_notice(LD_APP,
  680. "Exitrouter '%s' seems to be more restrictive than its exit "
  681. "policy. Not using this router as exit for now.",
  682. exitrouter->nickname);
  683. addr_policy_free(exitrouter->exit_policy);
  684. exitrouter->exit_policy =
  685. router_parse_addr_policy_from_string("reject *:*", -1);
  686. }
  687. /* rewrite it to an IP if we learned one. */
  688. addressmap_rewrite(conn->socks_request->address,
  689. sizeof(conn->socks_request->address));
  690. if (conn->_base.chosen_exit_optional) {
  691. /* stop wanting a specific exit */
  692. conn->_base.chosen_exit_optional = 0;
  693. tor_free(conn->chosen_exit_name); /* clears it */
  694. }
  695. if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
  696. return 0;
  697. /* else, conn will get closed below */
  698. break;
  699. case END_STREAM_REASON_CONNECTREFUSED:
  700. if (!conn->_base.chosen_exit_optional)
  701. break; /* break means it'll close, below */
  702. /* Else fall through: expire this circuit, clear the
  703. * chosen_exit_name field, and try again. */
  704. case END_STREAM_REASON_RESOLVEFAILED:
  705. case END_STREAM_REASON_TIMEOUT:
  706. case END_STREAM_REASON_MISC:
  707. if (client_dns_incr_failures(conn->socks_request->address)
  708. < MAX_RESOLVE_FAILURES) {
  709. /* We haven't retried too many times; reattach the connection. */
  710. circuit_log_path(LOG_INFO,LD_APP,circ);
  711. tor_assert(circ->_base.timestamp_dirty);
  712. circ->_base.timestamp_dirty -= get_options()->MaxCircuitDirtiness;
  713. if (conn->_base.chosen_exit_optional) {
  714. /* stop wanting a specific exit */
  715. conn->_base.chosen_exit_optional = 0;
  716. tor_free(conn->chosen_exit_name); /* clears it */
  717. }
  718. if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
  719. return 0;
  720. /* else, conn will get closed below */
  721. } else {
  722. log_notice(LD_APP,
  723. "Have tried resolving or connecting to address '%s' "
  724. "at %d different places. Giving up.",
  725. safe_str(conn->socks_request->address),
  726. MAX_RESOLVE_FAILURES);
  727. /* clear the failures, so it will have a full try next time */
  728. client_dns_clear_failures(conn->socks_request->address);
  729. }
  730. break;
  731. case END_STREAM_REASON_HIBERNATING:
  732. case END_STREAM_REASON_RESOURCELIMIT:
  733. if (exitrouter) {
  734. addr_policy_free(exitrouter->exit_policy);
  735. exitrouter->exit_policy =
  736. router_parse_addr_policy_from_string("reject *:*", -1);
  737. }
  738. if (conn->_base.chosen_exit_optional) {
  739. /* stop wanting a specific exit */
  740. conn->_base.chosen_exit_optional = 0;
  741. tor_free(conn->chosen_exit_name); /* clears it */
  742. }
  743. if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
  744. return 0;
  745. /* else, will close below */
  746. break;
  747. } /* end switch */
  748. log_info(LD_APP,"Giving up on retrying; conn can't be handled.");
  749. }
  750. log_info(LD_APP,
  751. "Edge got end (%s) before we're connected. Marking for close.",
  752. connection_edge_end_reason_str(rh->length > 0 ? reason : -1));
  753. if (conn->_base.type == CONN_TYPE_AP) {
  754. circuit_log_path(LOG_INFO,LD_APP,circ);
  755. connection_mark_unattached_ap(conn, control_reason);
  756. } else {
  757. /* we just got an 'end', don't need to send one */
  758. conn->_base.edge_has_sent_end = 1;
  759. conn->end_reason = control_reason;
  760. connection_mark_for_close(TO_CONN(conn));
  761. }
  762. return 0;
  763. }
  764. /** An incoming relay cell has arrived from circuit <b>circ</b> to
  765. * stream <b>conn</b>.
  766. *
  767. * The arguments here are the same as in
  768. * connection_edge_process_relay_cell() below; this function is called
  769. * from there when <b>conn</b> is defined and not in an open state.
  770. */
  771. static int
  772. connection_edge_process_relay_cell_not_open(
  773. relay_header_t *rh, cell_t *cell, circuit_t *circ,
  774. edge_connection_t *conn, crypt_path_t *layer_hint)
  775. {
  776. if (rh->command == RELAY_COMMAND_END) {
  777. if (CIRCUIT_IS_ORIGIN(circ))
  778. return connection_edge_process_end_not_open(rh, cell,
  779. TO_ORIGIN_CIRCUIT(circ), conn,
  780. layer_hint);
  781. else
  782. return 0;
  783. }
  784. if (conn->_base.type == CONN_TYPE_AP &&
  785. rh->command == RELAY_COMMAND_CONNECTED) {
  786. tor_assert(CIRCUIT_IS_ORIGIN(circ));
  787. if (conn->_base.state != AP_CONN_STATE_CONNECT_WAIT) {
  788. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  789. "Got 'connected' while not in state connect_wait. Dropping.");
  790. return 0;
  791. }
  792. // log_fn(LOG_INFO,"Connected! Notifying application.");
  793. conn->_base.state = AP_CONN_STATE_OPEN;
  794. log_info(LD_APP,"'connected' received after %d seconds.",
  795. (int)(time(NULL) - conn->_base.timestamp_lastread));
  796. if (rh->length >= 4) {
  797. uint32_t addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE));
  798. int ttl;
  799. if (!addr) {
  800. log_info(LD_APP,
  801. "...but it claims the IP address was 0.0.0.0. Closing.");
  802. connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL,
  803. conn->cpath_layer);
  804. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  805. return 0;
  806. }
  807. if (rh->length >= 8)
  808. ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+4));
  809. else
  810. ttl = -1;
  811. client_dns_set_addressmap(conn->socks_request->address, addr,
  812. conn->chosen_exit_name, ttl);
  813. }
  814. circuit_log_path(LOG_INFO,LD_APP,TO_ORIGIN_CIRCUIT(circ));
  815. /* don't send a socks reply to transparent conns */
  816. if (!conn->socks_request->has_finished)
  817. connection_ap_handshake_socks_reply(conn, NULL, 0, 0);
  818. /* handle anything that might have queued */
  819. if (connection_edge_package_raw_inbuf(conn, 1) < 0) {
  820. /* (We already sent an end cell if possible) */
  821. connection_mark_for_close(TO_CONN(conn));
  822. return 0;
  823. }
  824. return 0;
  825. }
  826. if (conn->_base.type == CONN_TYPE_AP &&
  827. rh->command == RELAY_COMMAND_RESOLVED) {
  828. int ttl;
  829. int answer_len;
  830. if (conn->_base.state != AP_CONN_STATE_RESOLVE_WAIT) {
  831. log_fn(LOG_PROTOCOL_WARN, LD_APP, "Got a 'resolved' cell while "
  832. "not in state resolve_wait. Dropping.");
  833. return 0;
  834. }
  835. tor_assert(conn->socks_request->command == SOCKS_COMMAND_RESOLVE ||
  836. conn->socks_request->command == SOCKS_COMMAND_RESOLVE_PTR);
  837. answer_len = cell->payload[RELAY_HEADER_SIZE+1];
  838. if (rh->length < 2 || answer_len+2>rh->length) {
  839. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  840. "Dropping malformed 'resolved' cell");
  841. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  842. return 0;
  843. }
  844. if (rh->length >= answer_len+6)
  845. ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+
  846. 2+answer_len));
  847. else
  848. ttl = -1;
  849. connection_ap_handshake_socks_resolved(conn,
  850. cell->payload[RELAY_HEADER_SIZE], /*answer_type*/
  851. cell->payload[RELAY_HEADER_SIZE+1], /*answer_len*/
  852. cell->payload+RELAY_HEADER_SIZE+2, /*answer*/
  853. ttl);
  854. connection_mark_unattached_ap(conn,
  855. END_STREAM_REASON_ALREADY_SOCKS_REPLIED);
  856. return 0;
  857. }
  858. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  859. "Got an unexpected relay command %d, in state %d (%s). Dropping.",
  860. rh->command, conn->_base.state,
  861. conn_state_to_string(conn->_base.type, conn->_base.state));
  862. return 0; /* for forward compatibility, don't kill the circuit */
  863. // connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL,
  864. // conn->cpath_layer);
  865. // connection_mark_for_close(conn);
  866. // return -1;
  867. }
  868. /** An incoming relay cell has arrived on circuit <b>circ</b>. If
  869. * <b>conn</b> is NULL this is a control cell, else <b>cell</b> is
  870. * destined for <b>conn</b>.
  871. *
  872. * If <b>layer_hint</b> is defined, then we're the origin of the
  873. * circuit, and it specifies the hop that packaged <b>cell</b>.
  874. *
  875. * Return -reason if you want to warn and tear down the circuit, else 0.
  876. */
  877. static int
  878. connection_edge_process_relay_cell(cell_t *cell, circuit_t *circ,
  879. edge_connection_t *conn,
  880. crypt_path_t *layer_hint)
  881. {
  882. static int num_seen=0;
  883. relay_header_t rh;
  884. unsigned domain = layer_hint?LD_APP:LD_EXIT;
  885. int reason;
  886. tor_assert(cell);
  887. tor_assert(circ);
  888. relay_header_unpack(&rh, cell->payload);
  889. // log_fn(LOG_DEBUG,"command %d stream %d", rh.command, rh.stream_id);
  890. num_seen++;
  891. log_debug(domain, "Now seen %d relay cells here.", num_seen);
  892. if (rh.length > RELAY_PAYLOAD_SIZE) {
  893. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  894. "Relay cell length field too long. Closing circuit.");
  895. return - END_CIRC_REASON_TORPROTOCOL;
  896. }
  897. /* either conn is NULL, in which case we've got a control cell, or else
  898. * conn points to the recognized stream. */
  899. if (conn && !connection_state_is_open(TO_CONN(conn)))
  900. return connection_edge_process_relay_cell_not_open(
  901. &rh, cell, circ, conn, layer_hint);
  902. switch (rh.command) {
  903. case RELAY_COMMAND_DROP:
  904. // log_info(domain,"Got a relay-level padding cell. Dropping.");
  905. return 0;
  906. case RELAY_COMMAND_BEGIN:
  907. case RELAY_COMMAND_BEGIN_DIR:
  908. if (layer_hint &&
  909. circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
  910. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  911. "Relay begin request unsupported at AP. Dropping.");
  912. return 0;
  913. }
  914. if (conn) {
  915. log_fn(LOG_PROTOCOL_WARN, domain,
  916. "Begin cell for known stream. Dropping.");
  917. return 0;
  918. }
  919. return connection_exit_begin_conn(cell, circ);
  920. case RELAY_COMMAND_DATA:
  921. ++stats_n_data_cells_received;
  922. if (( layer_hint && --layer_hint->deliver_window < 0) ||
  923. (!layer_hint && --circ->deliver_window < 0)) {
  924. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  925. "(relay data) circ deliver_window below 0. Killing.");
  926. connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL,
  927. conn->cpath_layer);
  928. connection_mark_for_close(TO_CONN(conn));
  929. return -END_CIRC_REASON_TORPROTOCOL;
  930. }
  931. log_debug(domain,"circ deliver_window now %d.", layer_hint ?
  932. layer_hint->deliver_window : circ->deliver_window);
  933. circuit_consider_sending_sendme(circ, layer_hint);
  934. if (!conn) {
  935. log_info(domain,"data cell dropped, unknown stream.");
  936. return 0;
  937. }
  938. if (--conn->deliver_window < 0) { /* is it below 0 after decrement? */
  939. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  940. "(relay data) conn deliver_window below 0. Killing.");
  941. return -END_CIRC_REASON_TORPROTOCOL;
  942. }
  943. stats_n_data_bytes_received += rh.length;
  944. connection_write_to_buf(cell->payload + RELAY_HEADER_SIZE,
  945. rh.length, TO_CONN(conn));
  946. connection_edge_consider_sending_sendme(conn);
  947. return 0;
  948. case RELAY_COMMAND_END:
  949. reason = rh.length > 0 ?
  950. *(uint8_t *)(cell->payload+RELAY_HEADER_SIZE) : END_STREAM_REASON_MISC;
  951. if (!conn) {
  952. log_info(domain,"end cell (%s) dropped, unknown stream.",
  953. connection_edge_end_reason_str(reason));
  954. return 0;
  955. }
  956. /* XXX add to this log_fn the exit node's nickname? */
  957. log_info(domain,"%d: end cell (%s) for stream %d. Removing stream.",
  958. conn->_base.s,
  959. connection_edge_end_reason_str(reason),
  960. conn->stream_id);
  961. if (conn->socks_request && !conn->socks_request->has_finished)
  962. log_warn(LD_BUG,
  963. "Bug: open stream hasn't sent socks answer yet? Closing.");
  964. /* We just *got* an end; no reason to send one. */
  965. conn->_base.edge_has_sent_end = 1;
  966. if (!conn->end_reason)
  967. conn->end_reason = reason | END_STREAM_REASON_FLAG_REMOTE;
  968. if (!conn->_base.marked_for_close) {
  969. /* only mark it if not already marked. it's possible to
  970. * get the 'end' right around when the client hangs up on us. */
  971. connection_mark_for_close(TO_CONN(conn));
  972. conn->_base.hold_open_until_flushed = 1;
  973. }
  974. return 0;
  975. case RELAY_COMMAND_EXTEND:
  976. if (conn) {
  977. log_fn(LOG_PROTOCOL_WARN, domain,
  978. "'extend' cell received for non-zero stream. Dropping.");
  979. return 0;
  980. }
  981. return circuit_extend(cell, circ);
  982. case RELAY_COMMAND_EXTENDED:
  983. if (!layer_hint) {
  984. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  985. "'extended' unsupported at non-origin. Dropping.");
  986. return 0;
  987. }
  988. log_debug(domain,"Got an extended cell! Yay.");
  989. if ((reason = circuit_finish_handshake(TO_ORIGIN_CIRCUIT(circ),
  990. CELL_CREATED,
  991. cell->payload+RELAY_HEADER_SIZE)) < 0) {
  992. log_warn(domain,"circuit_finish_handshake failed.");
  993. return reason;
  994. }
  995. if ((reason=circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ)))<0) {
  996. log_info(domain,"circuit_send_next_onion_skin() failed.");
  997. return reason;
  998. }
  999. return 0;
  1000. case RELAY_COMMAND_TRUNCATE:
  1001. if (layer_hint) {
  1002. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  1003. "'truncate' unsupported at origin. Dropping.");
  1004. return 0;
  1005. }
  1006. if (circ->n_conn) {
  1007. uint8_t reason = *(uint8_t*)(cell->payload + RELAY_HEADER_SIZE);
  1008. connection_or_send_destroy(circ->n_circ_id, circ->n_conn, reason);
  1009. circuit_set_n_circid_orconn(circ, 0, NULL);
  1010. }
  1011. log_debug(LD_EXIT, "Processed 'truncate', replying.");
  1012. {
  1013. char payload[1];
  1014. payload[0] = (char)END_CIRC_REASON_REQUESTED;
  1015. connection_edge_send_command(NULL, circ, RELAY_COMMAND_TRUNCATED,
  1016. payload, sizeof(payload), NULL);
  1017. }
  1018. return 0;
  1019. case RELAY_COMMAND_TRUNCATED:
  1020. if (!layer_hint) {
  1021. log_fn(LOG_PROTOCOL_WARN, LD_EXIT,
  1022. "'truncated' unsupported at non-origin. Dropping.");
  1023. return 0;
  1024. }
  1025. circuit_truncated(TO_ORIGIN_CIRCUIT(circ), layer_hint);
  1026. return 0;
  1027. case RELAY_COMMAND_CONNECTED:
  1028. if (conn) {
  1029. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1030. "'connected' unsupported while open. Closing circ.");
  1031. return -END_CIRC_REASON_TORPROTOCOL;
  1032. }
  1033. log_info(domain,
  1034. "'connected' received, no conn attached anymore. Ignoring.");
  1035. return 0;
  1036. case RELAY_COMMAND_SENDME:
  1037. if (!conn) {
  1038. if (layer_hint) {
  1039. layer_hint->package_window += CIRCWINDOW_INCREMENT;
  1040. log_debug(LD_APP,"circ-level sendme at origin, packagewindow %d.",
  1041. layer_hint->package_window);
  1042. circuit_resume_edge_reading(circ, layer_hint);
  1043. } else {
  1044. circ->package_window += CIRCWINDOW_INCREMENT;
  1045. log_debug(LD_APP,
  1046. "circ-level sendme at non-origin, packagewindow %d.",
  1047. circ->package_window);
  1048. circuit_resume_edge_reading(circ, layer_hint);
  1049. }
  1050. return 0;
  1051. }
  1052. conn->package_window += STREAMWINDOW_INCREMENT;
  1053. log_debug(domain,"stream-level sendme, packagewindow now %d.",
  1054. conn->package_window);
  1055. connection_start_reading(TO_CONN(conn));
  1056. /* handle whatever might still be on the inbuf */
  1057. if (connection_edge_package_raw_inbuf(conn, 1) < 0) {
  1058. /* (We already sent an end cell if possible) */
  1059. connection_mark_for_close(TO_CONN(conn));
  1060. return 0;
  1061. }
  1062. return 0;
  1063. case RELAY_COMMAND_RESOLVE:
  1064. if (layer_hint) {
  1065. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  1066. "resolve request unsupported at AP; dropping.");
  1067. return 0;
  1068. } else if (conn) {
  1069. log_fn(LOG_PROTOCOL_WARN, domain,
  1070. "resolve request for known stream; dropping.");
  1071. return 0;
  1072. } else if (circ->purpose != CIRCUIT_PURPOSE_OR) {
  1073. log_fn(LOG_PROTOCOL_WARN, domain,
  1074. "resolve request on circ with purpose %d; dropping",
  1075. circ->purpose);
  1076. return 0;
  1077. }
  1078. connection_exit_begin_resolve(cell, TO_OR_CIRCUIT(circ));
  1079. return 0;
  1080. case RELAY_COMMAND_RESOLVED:
  1081. if (conn) {
  1082. log_fn(LOG_PROTOCOL_WARN, domain,
  1083. "'resolved' unsupported while open. Closing circ.");
  1084. return -END_CIRC_REASON_TORPROTOCOL;
  1085. }
  1086. log_info(domain,
  1087. "'resolved' received, no conn attached anymore. Ignoring.");
  1088. return 0;
  1089. case RELAY_COMMAND_ESTABLISH_INTRO:
  1090. case RELAY_COMMAND_ESTABLISH_RENDEZVOUS:
  1091. case RELAY_COMMAND_INTRODUCE1:
  1092. case RELAY_COMMAND_INTRODUCE2:
  1093. case RELAY_COMMAND_INTRODUCE_ACK:
  1094. case RELAY_COMMAND_RENDEZVOUS1:
  1095. case RELAY_COMMAND_RENDEZVOUS2:
  1096. case RELAY_COMMAND_INTRO_ESTABLISHED:
  1097. case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
  1098. rend_process_relay_cell(circ, rh.command, rh.length,
  1099. cell->payload+RELAY_HEADER_SIZE);
  1100. return 0;
  1101. }
  1102. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1103. "Received unknown relay command %d. Perhaps the other side is using "
  1104. "a newer version of Tor? Dropping.",
  1105. rh.command);
  1106. return 0; /* for forward compatibility, don't kill the circuit */
  1107. }
  1108. uint64_t stats_n_data_cells_packaged = 0;
  1109. uint64_t stats_n_data_bytes_packaged = 0;
  1110. uint64_t stats_n_data_cells_received = 0;
  1111. uint64_t stats_n_data_bytes_received = 0;
  1112. /** While conn->inbuf has an entire relay payload of bytes on it,
  1113. * and the appropriate package windows aren't empty, grab a cell
  1114. * and send it down the circuit.
  1115. *
  1116. * Return -1 (and send a RELAY_END cell if necessary) if conn should
  1117. * be marked for close, else return 0.
  1118. */
  1119. int
  1120. connection_edge_package_raw_inbuf(edge_connection_t *conn, int package_partial)
  1121. {
  1122. size_t amount_to_process, length;
  1123. char payload[CELL_PAYLOAD_SIZE];
  1124. circuit_t *circ;
  1125. unsigned domain = conn->cpath_layer ? LD_APP : LD_EXIT;
  1126. tor_assert(conn);
  1127. if (conn->_base.marked_for_close) {
  1128. log_warn(LD_BUG,
  1129. "Bug: called on conn that's already marked for close at %s:%d.",
  1130. conn->_base.marked_for_close_file, conn->_base.marked_for_close);
  1131. return 0;
  1132. }
  1133. repeat_connection_edge_package_raw_inbuf:
  1134. circ = circuit_get_by_edge_conn(conn);
  1135. if (!circ) {
  1136. log_info(domain,"conn has no circuit! Closing.");
  1137. conn->end_reason = END_STREAM_REASON_CANT_ATTACH;
  1138. return -1;
  1139. }
  1140. if (circuit_consider_stop_edge_reading(circ, conn->cpath_layer))
  1141. return 0;
  1142. if (conn->package_window <= 0) {
  1143. log_info(domain,"called with package_window %d. Skipping.",
  1144. conn->package_window);
  1145. connection_stop_reading(TO_CONN(conn));
  1146. return 0;
  1147. }
  1148. amount_to_process = buf_datalen(conn->_base.inbuf);
  1149. if (!amount_to_process)
  1150. return 0;
  1151. if (!package_partial && amount_to_process < RELAY_PAYLOAD_SIZE)
  1152. return 0;
  1153. if (amount_to_process > RELAY_PAYLOAD_SIZE) {
  1154. length = RELAY_PAYLOAD_SIZE;
  1155. } else {
  1156. length = amount_to_process;
  1157. }
  1158. stats_n_data_bytes_packaged += length;
  1159. stats_n_data_cells_packaged += 1;
  1160. connection_fetch_from_buf(payload, length, TO_CONN(conn));
  1161. log_debug(domain,"(%d) Packaging %d bytes (%d waiting).", conn->_base.s,
  1162. (int)length, (int)buf_datalen(conn->_base.inbuf));
  1163. if (connection_edge_send_command(conn, circ, RELAY_COMMAND_DATA,
  1164. payload, length, conn->cpath_layer) < 0)
  1165. /* circuit got marked for close, don't continue, don't need to mark conn */
  1166. return 0;
  1167. if (!conn->cpath_layer) { /* non-rendezvous exit */
  1168. tor_assert(circ->package_window > 0);
  1169. circ->package_window--;
  1170. } else { /* we're an AP, or an exit on a rendezvous circ */
  1171. tor_assert(conn->cpath_layer->package_window > 0);
  1172. conn->cpath_layer->package_window--;
  1173. }
  1174. if (--conn->package_window <= 0) { /* is it 0 after decrement? */
  1175. connection_stop_reading(TO_CONN(conn));
  1176. log_debug(domain,"conn->package_window reached 0.");
  1177. circuit_consider_stop_edge_reading(circ, conn->cpath_layer);
  1178. return 0; /* don't process the inbuf any more */
  1179. }
  1180. log_debug(domain,"conn->package_window is now %d",conn->package_window);
  1181. /* handle more if there's more, or return 0 if there isn't */
  1182. goto repeat_connection_edge_package_raw_inbuf;
  1183. }
  1184. /** Called when we've just received a relay data cell, or when
  1185. * we've just finished flushing all bytes to stream <b>conn</b>.
  1186. *
  1187. * If conn->outbuf is not too full, and our deliver window is
  1188. * low, send back a suitable number of stream-level sendme cells.
  1189. */
  1190. void
  1191. connection_edge_consider_sending_sendme(edge_connection_t *conn)
  1192. {
  1193. circuit_t *circ;
  1194. if (connection_outbuf_too_full(TO_CONN(conn)))
  1195. return;
  1196. circ = circuit_get_by_edge_conn(conn);
  1197. if (!circ) {
  1198. /* this can legitimately happen if the destroy has already
  1199. * arrived and torn down the circuit */
  1200. log_info(LD_APP,"No circuit associated with conn. Skipping.");
  1201. return;
  1202. }
  1203. while (conn->deliver_window < STREAMWINDOW_START - STREAMWINDOW_INCREMENT) {
  1204. log_debug(conn->cpath_layer?LD_APP:LD_EXIT,
  1205. "Outbuf %d, Queueing stream sendme.",
  1206. (int)conn->_base.outbuf_flushlen);
  1207. conn->deliver_window += STREAMWINDOW_INCREMENT;
  1208. if (connection_edge_send_command(conn, circ, RELAY_COMMAND_SENDME,
  1209. NULL, 0, conn->cpath_layer) < 0) {
  1210. log_warn(LD_APP,"connection_edge_send_command failed. Returning.");
  1211. return; /* the circuit's closed, don't continue */
  1212. }
  1213. }
  1214. }
  1215. /** The circuit <b>circ</b> has received a circuit-level sendme
  1216. * (on hop <b>layer_hint</b>, if we're the OP). Go through all the
  1217. * attached streams and let them resume reading and packaging, if
  1218. * their stream windows allow it.
  1219. */
  1220. static void
  1221. circuit_resume_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
  1222. {
  1223. log_debug(layer_hint?LD_APP:LD_EXIT,"resuming");
  1224. if (CIRCUIT_IS_ORIGIN(circ))
  1225. circuit_resume_edge_reading_helper(TO_ORIGIN_CIRCUIT(circ)->p_streams,
  1226. circ, layer_hint);
  1227. else
  1228. circuit_resume_edge_reading_helper(TO_OR_CIRCUIT(circ)->n_streams,
  1229. circ, layer_hint);
  1230. }
  1231. /** A helper function for circuit_resume_edge_reading() above.
  1232. * The arguments are the same, except that <b>conn</b> is the head
  1233. * of a linked list of edge streams that should each be considered.
  1234. */
  1235. static int
  1236. circuit_resume_edge_reading_helper(edge_connection_t *conn,
  1237. circuit_t *circ,
  1238. crypt_path_t *layer_hint)
  1239. {
  1240. for ( ; conn; conn=conn->next_stream) {
  1241. if (conn->_base.marked_for_close)
  1242. continue;
  1243. if ((!layer_hint && conn->package_window > 0) ||
  1244. (layer_hint && conn->package_window > 0 &&
  1245. conn->cpath_layer == layer_hint)) {
  1246. connection_start_reading(TO_CONN(conn));
  1247. /* handle whatever might still be on the inbuf */
  1248. if (connection_edge_package_raw_inbuf(conn, 1)<0) {
  1249. /* (We already sent an end cell if possible) */
  1250. connection_mark_for_close(TO_CONN(conn));
  1251. continue;
  1252. }
  1253. /* If the circuit won't accept any more data, return without looking
  1254. * at any more of the streams. Any connections that should be stopped
  1255. * have already been stopped by connection_edge_package_raw_inbuf. */
  1256. if (circuit_consider_stop_edge_reading(circ, layer_hint))
  1257. return -1;
  1258. }
  1259. }
  1260. return 0;
  1261. }
  1262. /** Check if the package window for <b>circ</b> is empty (at
  1263. * hop <b>layer_hint</b> if it's defined).
  1264. *
  1265. * If yes, tell edge streams to stop reading and return 1.
  1266. * Else return 0.
  1267. */
  1268. static int
  1269. circuit_consider_stop_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
  1270. {
  1271. edge_connection_t *conn = NULL;
  1272. unsigned domain = layer_hint ? LD_APP : LD_EXIT;
  1273. if (!layer_hint) {
  1274. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  1275. log_debug(domain,"considering circ->package_window %d",
  1276. circ->package_window);
  1277. if (circ->package_window <= 0) {
  1278. log_debug(domain,"yes, not-at-origin. stopped.");
  1279. for (conn = or_circ->n_streams; conn; conn=conn->next_stream)
  1280. connection_stop_reading(TO_CONN(conn));
  1281. return 1;
  1282. }
  1283. return 0;
  1284. }
  1285. /* else, layer hint is defined, use it */
  1286. log_debug(domain,"considering layer_hint->package_window %d",
  1287. layer_hint->package_window);
  1288. if (layer_hint->package_window <= 0) {
  1289. log_debug(domain,"yes, at-origin. stopped.");
  1290. #if 0
  1291. // XXXX NM DEAD CODE.
  1292. for (conn = circ->n_streams; conn; conn=conn->next_stream)
  1293. if (conn->cpath_layer == layer_hint)
  1294. connection_stop_reading(conn);
  1295. #endif
  1296. for (conn = TO_ORIGIN_CIRCUIT(circ)->p_streams; conn;
  1297. conn=conn->next_stream)
  1298. if (conn->cpath_layer == layer_hint)
  1299. connection_stop_reading(TO_CONN(conn));
  1300. return 1;
  1301. }
  1302. return 0;
  1303. }
  1304. /** Check if the deliver_window for circuit <b>circ</b> (at hop
  1305. * <b>layer_hint</b> if it's defined) is low enough that we should
  1306. * send a circuit-level sendme back down the circuit. If so, send
  1307. * enough sendmes that the window would be overfull if we sent any
  1308. * more.
  1309. */
  1310. static void
  1311. circuit_consider_sending_sendme(circuit_t *circ, crypt_path_t *layer_hint)
  1312. {
  1313. // log_fn(LOG_INFO,"Considering: layer_hint is %s",
  1314. // layer_hint ? "defined" : "null");
  1315. while ((layer_hint ? layer_hint->deliver_window : circ->deliver_window) <
  1316. CIRCWINDOW_START - CIRCWINDOW_INCREMENT) {
  1317. log_debug(LD_CIRC,"Queueing circuit sendme.");
  1318. if (layer_hint)
  1319. layer_hint->deliver_window += CIRCWINDOW_INCREMENT;
  1320. else
  1321. circ->deliver_window += CIRCWINDOW_INCREMENT;
  1322. if (connection_edge_send_command(NULL, circ, RELAY_COMMAND_SENDME,
  1323. NULL, 0, layer_hint) < 0) {
  1324. log_warn(LD_CIRC,
  1325. "connection_edge_send_command failed. Circuit's closed.");
  1326. return; /* the circuit's closed, don't continue */
  1327. }
  1328. }
  1329. }