relay.c 42 KB

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