relay.c 46 KB

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