relay.c 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209
  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[] = "$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 && 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. if (fromconn->type == CONN_TYPE_AP) {
  372. connection_mark_unattached_ap(fromconn, END_STREAM_REASON_INTERNAL);
  373. } else {
  374. fromconn->has_sent_end = 1; /* no circ to send to */
  375. connection_mark_for_close(fromconn);
  376. }
  377. return -1;
  378. }
  379. memset(&cell, 0, sizeof(cell_t));
  380. cell.command = CELL_RELAY;
  381. if (cpath_layer) {
  382. cell.circ_id = circ->n_circ_id;
  383. cell_direction = CELL_DIRECTION_OUT;
  384. } else {
  385. cell.circ_id = circ->p_circ_id;
  386. cell_direction = CELL_DIRECTION_IN;
  387. }
  388. memset(&rh, 0, sizeof(rh));
  389. rh.command = relay_command;
  390. if (fromconn)
  391. rh.stream_id = fromconn->stream_id; /* else it's 0 */
  392. rh.length = payload_len;
  393. relay_header_pack(cell.payload, &rh);
  394. if (payload_len) {
  395. tor_assert(payload_len <= RELAY_PAYLOAD_SIZE);
  396. memcpy(cell.payload+RELAY_HEADER_SIZE, payload, payload_len);
  397. }
  398. log_fn(LOG_DEBUG,"delivering %d cell %s.", relay_command,
  399. cell_direction == CELL_DIRECTION_OUT ? "forward" : "backward");
  400. if (circuit_package_relay_cell(&cell, circ, cell_direction, cpath_layer) < 0) {
  401. log_fn(LOG_WARN,"circuit_package_relay_cell failed. Closing.");
  402. circuit_mark_for_close(circ);
  403. return -1;
  404. }
  405. return 0;
  406. }
  407. /** Translate <b>reason</b>, which came from a relay 'end' cell,
  408. * into a static const string describing why the stream is closing.
  409. * <b>reason</b> is -1 if no reason was provided.
  410. */
  411. static const char *
  412. connection_edge_end_reason_str(int reason) {
  413. switch (reason) {
  414. case -1:
  415. log_fn(LOG_WARN,"End cell arrived with length 0. Should be at least 1.");
  416. return "MALFORMED";
  417. case END_STREAM_REASON_MISC: return "misc error";
  418. case END_STREAM_REASON_RESOLVEFAILED: return "resolve failed";
  419. case END_STREAM_REASON_CONNECTREFUSED: return "connection refused";
  420. case END_STREAM_REASON_EXITPOLICY: return "exit policy failed";
  421. case END_STREAM_REASON_DESTROY: return "destroyed";
  422. case END_STREAM_REASON_DONE: return "closed normally";
  423. case END_STREAM_REASON_TIMEOUT: return "gave up (timeout)";
  424. case END_STREAM_REASON_HIBERNATING: return "server is hibernating";
  425. case END_STREAM_REASON_INTERNAL: return "internal error at server";
  426. case END_STREAM_REASON_RESOURCELIMIT: return "server out of resources";
  427. case END_STREAM_REASON_CONNRESET: return "connection reset";
  428. case END_STREAM_REASON_TORPROTOCOL: return "Tor protocol error";
  429. default:
  430. log_fn(LOG_WARN,"Reason for ending (%d) not recognized.",reason);
  431. return "unknown";
  432. }
  433. }
  434. /** Translate <b>reason</b> (as from a relay 'end' cell) into an
  435. * appropriate SOCKS5 reply code.
  436. */
  437. socks5_reply_status_t
  438. connection_edge_end_reason_socks5_response(int reason)
  439. {
  440. switch (reason) {
  441. case END_STREAM_REASON_MISC:
  442. return SOCKS5_GENERAL_ERROR;
  443. case END_STREAM_REASON_RESOLVEFAILED:
  444. return SOCKS5_HOST_UNREACHABLE;
  445. case END_STREAM_REASON_CONNECTREFUSED:
  446. return SOCKS5_CONNECTION_REFUSED;
  447. case END_STREAM_REASON_EXITPOLICY:
  448. return SOCKS5_NOT_ALLOWED;
  449. case END_STREAM_REASON_DESTROY:
  450. return SOCKS5_GENERAL_ERROR;
  451. case END_STREAM_REASON_DONE:
  452. return SOCKS5_SUCCEEDED;
  453. case END_STREAM_REASON_TIMEOUT:
  454. return SOCKS5_TTL_EXPIRED;
  455. case END_STREAM_REASON_RESOURCELIMIT:
  456. return SOCKS5_GENERAL_ERROR;
  457. case END_STREAM_REASON_HIBERNATING:
  458. return SOCKS5_GENERAL_ERROR;
  459. case END_STREAM_REASON_INTERNAL:
  460. return SOCKS5_GENERAL_ERROR;
  461. case END_STREAM_REASON_CONNRESET:
  462. return SOCKS5_CONNECTION_REFUSED;
  463. case END_STREAM_REASON_TORPROTOCOL:
  464. return SOCKS5_GENERAL_ERROR;
  465. case END_STREAM_REASON_ALREADY_SOCKS_REPLIED:
  466. return SOCKS5_SUCCEEDED; /* never used */
  467. case END_STREAM_REASON_CANT_ATTACH:
  468. return SOCKS5_GENERAL_ERROR;
  469. case END_STREAM_REASON_NET_UNREACHABLE:
  470. return SOCKS5_NET_UNREACHABLE;
  471. default:
  472. log_fn(LOG_WARN,"Reason for ending (%d) not recognized.",reason);
  473. return SOCKS5_GENERAL_ERROR;
  474. }
  475. }
  476. /* We need to use a few macros to deal with the fact that Windows
  477. * decided that their sockets interface should be a permakludge.
  478. * E_CASE is for errors where windows has both a EFOO and a WSAEFOO
  479. * version, and S_CASE is for errors where windows has only a WSAEFOO
  480. * version. (The E is for 'error', the S is for 'socket'). */
  481. #ifdef MS_WINDOWS
  482. #define E_CASE(s) case s: case WSA ## s
  483. #define S_CASE(s) case WSA ## s
  484. #else
  485. #define E_CASE(s) case s
  486. #define S_CASE(s) case s
  487. #endif
  488. int
  489. errno_to_end_reason(int e)
  490. {
  491. switch (e) {
  492. case EPIPE:
  493. return END_STREAM_REASON_DONE;
  494. E_CASE(EBADF):
  495. E_CASE(EFAULT):
  496. E_CASE(EINVAL):
  497. S_CASE(EISCONN):
  498. S_CASE(ENOTSOCK):
  499. S_CASE(EPROTONOSUPPORT):
  500. S_CASE(EAFNOSUPPORT):
  501. E_CASE(EACCES):
  502. S_CASE(ENOTCONN):
  503. S_CASE(ENETUNREACH):
  504. return END_STREAM_REASON_INTERNAL;
  505. S_CASE(ECONNREFUSED):
  506. return END_STREAM_REASON_CONNECTREFUSED;
  507. S_CASE(ECONNRESET):
  508. return END_STREAM_REASON_CONNRESET;
  509. S_CASE(ETIMEDOUT):
  510. return END_STREAM_REASON_TIMEOUT;
  511. S_CASE(ENOBUFS):
  512. case ENOMEM:
  513. case ENFILE:
  514. E_CASE(EMFILE):
  515. return END_STREAM_REASON_RESOURCELIMIT;
  516. default:
  517. log_fn(LOG_INFO, "Didn't recognize errno %d (%s); telling the OP that we are ending a stream for 'misc' reason.",
  518. e, tor_socket_strerror(e));
  519. return END_STREAM_REASON_MISC;
  520. }
  521. }
  522. /** How many times will I retry a stream that fails due to DNS
  523. * resolve failure?
  524. */
  525. #define MAX_RESOLVE_FAILURES 3
  526. /** Return 1 if reason is something that you should retry if you
  527. * get the end cell before you've connected; else return 0. */
  528. static int
  529. edge_reason_is_retriable(int reason) {
  530. return reason == END_STREAM_REASON_HIBERNATING ||
  531. reason == END_STREAM_REASON_RESOURCELIMIT ||
  532. reason == END_STREAM_REASON_EXITPOLICY ||
  533. reason == END_STREAM_REASON_RESOLVEFAILED;
  534. }
  535. static int
  536. connection_edge_process_end_not_open(
  537. relay_header_t *rh, cell_t *cell, circuit_t *circ,
  538. connection_t *conn, crypt_path_t *layer_hint) {
  539. struct in_addr in;
  540. routerinfo_t *exitrouter;
  541. int reason = *(cell->payload+RELAY_HEADER_SIZE);
  542. if (rh->length > 0 && edge_reason_is_retriable(reason)) {
  543. if (conn->type != CONN_TYPE_AP) {
  544. log_fn(LOG_WARN,"Got an end because of %s, but we're not an AP. Closing.",
  545. connection_edge_end_reason_str(reason));
  546. return -1;
  547. }
  548. log_fn(LOG_INFO,"Address '%s' refused due to '%s'. Considering retrying.",
  549. safe_str(conn->socks_request->address),
  550. connection_edge_end_reason_str(reason));
  551. exitrouter = router_get_by_digest(circ->build_state->chosen_exit_digest);
  552. if (!exitrouter) {
  553. log_fn(LOG_INFO,"Skipping broken circ (exit router vanished)");
  554. return 0; /* this circuit is screwed and doesn't know it yet */
  555. }
  556. switch (reason) {
  557. case END_STREAM_REASON_EXITPOLICY:
  558. if (rh->length >= 5) {
  559. uint32_t addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+1));
  560. if (!addr) {
  561. log_fn(LOG_INFO,"Address '%s' resolved to 0.0.0.0. Closing,",
  562. safe_str(conn->socks_request->address));
  563. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  564. return 0;
  565. }
  566. client_dns_set_addressmap(conn->socks_request->address, addr,
  567. conn->chosen_exit_name);
  568. }
  569. /* check if he *ought* to have allowed it */
  570. if (rh->length < 5 ||
  571. (!tor_inet_aton(conn->socks_request->address, &in) &&
  572. !conn->chosen_exit_name)) {
  573. 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);
  574. addr_policy_free(exitrouter->exit_policy);
  575. exitrouter->exit_policy =
  576. router_parse_addr_policy_from_string("reject *:*");
  577. }
  578. if (connection_ap_detach_retriable(conn, circ) >= 0)
  579. return 0;
  580. /* else, conn will get closed below */
  581. break;
  582. case END_STREAM_REASON_RESOLVEFAILED:
  583. if (client_dns_incr_failures(conn->socks_request->address)
  584. < MAX_RESOLVE_FAILURES) {
  585. /* We haven't retried too many times; reattach the connection. */
  586. circuit_log_path(LOG_INFO,circ);
  587. tor_assert(circ->timestamp_dirty);
  588. circ->timestamp_dirty -= get_options()->MaxCircuitDirtiness;
  589. if (connection_ap_detach_retriable(conn, circ) >= 0)
  590. return 0;
  591. /* else, conn will get closed below */
  592. } else {
  593. log_fn(LOG_NOTICE,"Have tried resolving address '%s' at %d different places. Giving up.",
  594. safe_str(conn->socks_request->address), MAX_RESOLVE_FAILURES);
  595. }
  596. break;
  597. case END_STREAM_REASON_HIBERNATING:
  598. case END_STREAM_REASON_RESOURCELIMIT:
  599. addr_policy_free(exitrouter->exit_policy);
  600. exitrouter->exit_policy =
  601. router_parse_addr_policy_from_string("reject *:*");
  602. if (connection_ap_detach_retriable(conn, circ) >= 0)
  603. return 0;
  604. /* else, will close below */
  605. break;
  606. } /* end switch */
  607. log_fn(LOG_INFO,"Giving up on retrying; conn can't be handled.");
  608. }
  609. log_fn(LOG_INFO,"Edge got end (%s) before we're connected. Marking for close.",
  610. connection_edge_end_reason_str(rh->length > 0 ? reason : -1));
  611. if (conn->type == CONN_TYPE_AP) {
  612. circuit_log_path(LOG_INFO,circ);
  613. connection_mark_unattached_ap(conn, reason);
  614. } else {
  615. conn->has_sent_end = 1; /* we just got an 'end', don't need to send one */
  616. connection_mark_for_close(conn);
  617. }
  618. return 0;
  619. }
  620. /** An incoming relay cell has arrived from circuit <b>circ</b> to
  621. * stream <b>conn</b>.
  622. *
  623. * The arguments here are the same as in
  624. * connection_edge_process_relay_cell() below; this function is called
  625. * from there when <b>conn</b> is defined and not in an open state.
  626. */
  627. static int
  628. connection_edge_process_relay_cell_not_open(
  629. relay_header_t *rh, cell_t *cell, circuit_t *circ,
  630. connection_t *conn, crypt_path_t *layer_hint) {
  631. if (rh->command == RELAY_COMMAND_END)
  632. return connection_edge_process_end_not_open(rh, cell, circ, conn, layer_hint);
  633. if (conn->type == CONN_TYPE_AP && rh->command == RELAY_COMMAND_CONNECTED) {
  634. if (conn->state != AP_CONN_STATE_CONNECT_WAIT) {
  635. log_fn(LOG_WARN,"Got 'connected' while not in state connect_wait. Dropping.");
  636. return 0;
  637. }
  638. // log_fn(LOG_INFO,"Connected! Notifying application.");
  639. conn->state = AP_CONN_STATE_OPEN;
  640. log_fn(LOG_INFO,"'connected' received after %d seconds.",
  641. (int)(time(NULL) - conn->timestamp_lastread));
  642. if (rh->length >= 4) {
  643. uint32_t addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE));
  644. if (!addr) {
  645. log_fn(LOG_INFO,"...but it claims the IP address was 0.0.0.0. Closing.");
  646. connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL, conn->cpath_layer);
  647. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  648. return 0;
  649. }
  650. client_dns_set_addressmap(conn->socks_request->address, addr,
  651. conn->chosen_exit_name);
  652. }
  653. circuit_log_path(LOG_INFO,circ);
  654. connection_ap_handshake_socks_reply(conn, NULL, 0, SOCKS5_SUCCEEDED);
  655. /* handle anything that might have queued */
  656. if (connection_edge_package_raw_inbuf(conn, 1) < 0) {
  657. /* (We already sent an end cell if possible) */
  658. connection_mark_for_close(conn);
  659. return 0;
  660. }
  661. return 0;
  662. }
  663. if (conn->type == CONN_TYPE_AP && rh->command == RELAY_COMMAND_RESOLVED) {
  664. if (conn->state != AP_CONN_STATE_RESOLVE_WAIT) {
  665. log_fn(LOG_WARN,"Got a 'resolved' cell while not in state resolve_wait. Dropping.");
  666. return 0;
  667. }
  668. tor_assert(conn->socks_request->command == SOCKS_COMMAND_RESOLVE);
  669. if (rh->length < 2 || cell->payload[RELAY_HEADER_SIZE+1]+2>rh->length) {
  670. log_fn(LOG_WARN, "Dropping malformed 'resolved' cell");
  671. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  672. return 0;
  673. }
  674. connection_ap_handshake_socks_resolved(conn,
  675. cell->payload[RELAY_HEADER_SIZE], /*answer_type*/
  676. cell->payload[RELAY_HEADER_SIZE+1], /*answer_len*/
  677. cell->payload+RELAY_HEADER_SIZE+2); /* answer */
  678. connection_mark_unattached_ap(conn, END_STREAM_REASON_ALREADY_SOCKS_REPLIED);
  679. return 0;
  680. }
  681. log_fn(LOG_WARN,"Got an unexpected relay command %d, in state %d (%s). Closing.",
  682. rh->command, conn->state, conn_state_to_string(conn->type, conn->state));
  683. connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL, conn->cpath_layer);
  684. connection_mark_for_close(conn);
  685. return -1;
  686. }
  687. /** An incoming relay cell has arrived on circuit <b>circ</b>. If
  688. * <b>conn</b> is NULL this is a control cell, else <b>cell</b> is
  689. * destined for <b>conn</b>.
  690. *
  691. * If <b>layer_hint</b> is defined, then we're the origin of the
  692. * circuit, and it specifies the hop that packaged <b>cell</b>.
  693. *
  694. * Return -1 if you want to tear down the circuit, else 0.
  695. */
  696. static int
  697. connection_edge_process_relay_cell(cell_t *cell, circuit_t *circ,
  698. connection_t *conn,
  699. crypt_path_t *layer_hint)
  700. {
  701. static int num_seen=0;
  702. relay_header_t rh;
  703. tor_assert(cell);
  704. tor_assert(circ);
  705. relay_header_unpack(&rh, cell->payload);
  706. // log_fn(LOG_DEBUG,"command %d stream %d", rh.command, rh.stream_id);
  707. num_seen++;
  708. log_fn(LOG_DEBUG,"Now seen %d relay cells here.", num_seen);
  709. /* either conn is NULL, in which case we've got a control cell, or else
  710. * conn points to the recognized stream. */
  711. if (conn && !connection_state_is_open(conn))
  712. return connection_edge_process_relay_cell_not_open(
  713. &rh, cell, circ, conn, layer_hint);
  714. switch (rh.command) {
  715. case RELAY_COMMAND_DROP:
  716. log_fn(LOG_INFO,"Got a relay-level padding cell. Dropping.");
  717. return 0;
  718. case RELAY_COMMAND_BEGIN:
  719. if (layer_hint &&
  720. circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
  721. log_fn(LOG_WARN,"relay begin request unsupported at AP. Dropping.");
  722. return 0;
  723. }
  724. if (conn) {
  725. log_fn(LOG_WARN,"begin cell for known stream. Dropping.");
  726. return 0;
  727. }
  728. connection_exit_begin_conn(cell, circ);
  729. return 0;
  730. case RELAY_COMMAND_DATA:
  731. ++stats_n_data_cells_received;
  732. if (( layer_hint && --layer_hint->deliver_window < 0) ||
  733. (!layer_hint && --circ->deliver_window < 0)) {
  734. log_fn(LOG_WARN,"(relay data) circ deliver_window below 0. Killing.");
  735. connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL, conn->cpath_layer);
  736. connection_mark_for_close(conn);
  737. return -1;
  738. }
  739. log_fn(LOG_DEBUG,"circ deliver_window now %d.", layer_hint ?
  740. layer_hint->deliver_window : circ->deliver_window);
  741. circuit_consider_sending_sendme(circ, layer_hint);
  742. if (!conn) {
  743. log_fn(LOG_INFO,"data cell dropped, unknown stream.");
  744. return 0;
  745. }
  746. if (--conn->deliver_window < 0) { /* is it below 0 after decrement? */
  747. log_fn(LOG_WARN,"(relay data) conn deliver_window below 0. Killing.");
  748. return -1; /* somebody's breaking protocol. kill the whole circuit. */
  749. }
  750. stats_n_data_bytes_received += rh.length;
  751. connection_write_to_buf(cell->payload + RELAY_HEADER_SIZE,
  752. rh.length, conn);
  753. connection_edge_consider_sending_sendme(conn);
  754. return 0;
  755. case RELAY_COMMAND_END:
  756. if (!conn) {
  757. log_fn(LOG_INFO,"end cell (%s) dropped, unknown stream.",
  758. connection_edge_end_reason_str(rh.length > 0 ?
  759. *(char *)(cell->payload+RELAY_HEADER_SIZE) : -1));
  760. return 0;
  761. }
  762. /* XXX add to this log_fn the exit node's nickname? */
  763. log_fn(LOG_INFO,"%d: end cell (%s) for stream %d. Removing stream.",
  764. conn->s,
  765. connection_edge_end_reason_str(rh.length > 0 ?
  766. *(char *)(cell->payload+RELAY_HEADER_SIZE) : -1),
  767. conn->stream_id);
  768. if (conn->socks_request && !conn->socks_request->has_finished)
  769. log_fn(LOG_WARN,"Bug: open stream hasn't sent socks answer yet? Closing.");
  770. #ifdef HALF_OPEN
  771. conn->done_sending = 1;
  772. shutdown(conn->s, 1); /* XXX check return; refactor NM */
  773. if (conn->done_receiving) {
  774. /* We just *got* an end; no reason to send one. */
  775. conn->has_sent_end = 1;
  776. connection_mark_for_close(conn);
  777. conn->hold_open_until_flushed = 1;
  778. }
  779. #else
  780. /* We just *got* an end; no reason to send one. */
  781. conn->has_sent_end = 1;
  782. if (!conn->marked_for_close) {
  783. /* only mark it if not already marked. it's possible to
  784. * get the 'end' right around when the client hangs up on us. */
  785. connection_mark_for_close(conn);
  786. conn->hold_open_until_flushed = 1;
  787. }
  788. #endif
  789. return 0;
  790. case RELAY_COMMAND_EXTEND:
  791. if (conn) {
  792. log_fn(LOG_WARN,"'extend' for non-zero stream. Dropping.");
  793. return 0;
  794. }
  795. return circuit_extend(cell, circ);
  796. case RELAY_COMMAND_EXTENDED:
  797. if (!layer_hint) {
  798. log_fn(LOG_WARN,"'extended' unsupported at non-origin. Dropping.");
  799. return 0;
  800. }
  801. log_fn(LOG_DEBUG,"Got an extended cell! Yay.");
  802. if (circuit_finish_handshake(circ, CELL_CREATED,
  803. cell->payload+RELAY_HEADER_SIZE) < 0) {
  804. log_fn(LOG_WARN,"circuit_finish_handshake failed.");
  805. return -1;
  806. }
  807. if (circuit_send_next_onion_skin(circ)<0) {
  808. log_fn(LOG_INFO,"circuit_send_next_onion_skin() failed.");
  809. return -1;
  810. }
  811. return 0;
  812. case RELAY_COMMAND_TRUNCATE:
  813. if (layer_hint) {
  814. log_fn(LOG_WARN,"'truncate' unsupported at origin. Dropping.");
  815. return 0;
  816. }
  817. if (circ->n_conn) {
  818. connection_send_destroy(circ->n_circ_id, circ->n_conn);
  819. circuit_set_circid_orconn(circ, 0, NULL, N_CONN_CHANGED);
  820. }
  821. log_fn(LOG_DEBUG, "Processed 'truncate', replying.");
  822. connection_edge_send_command(NULL, circ, RELAY_COMMAND_TRUNCATED,
  823. NULL, 0, NULL);
  824. return 0;
  825. case RELAY_COMMAND_TRUNCATED:
  826. if (!layer_hint) {
  827. log_fn(LOG_WARN,"'truncated' unsupported at non-origin. Dropping.");
  828. return 0;
  829. }
  830. circuit_truncated(circ, layer_hint);
  831. return 0;
  832. case RELAY_COMMAND_CONNECTED:
  833. if (conn) {
  834. log_fn(LOG_WARN,"'connected' unsupported while open. Closing circ.");
  835. return -1;
  836. }
  837. log_fn(LOG_INFO,"'connected' received, no conn attached anymore. Ignoring.");
  838. return 0;
  839. case RELAY_COMMAND_SENDME:
  840. if (!conn) {
  841. if (layer_hint) {
  842. layer_hint->package_window += CIRCWINDOW_INCREMENT;
  843. log_fn(LOG_DEBUG,"circ-level sendme at origin, packagewindow %d.",
  844. layer_hint->package_window);
  845. circuit_resume_edge_reading(circ, layer_hint);
  846. } else {
  847. circ->package_window += CIRCWINDOW_INCREMENT;
  848. log_fn(LOG_DEBUG,"circ-level sendme at non-origin, packagewindow %d.",
  849. circ->package_window);
  850. circuit_resume_edge_reading(circ, layer_hint);
  851. }
  852. return 0;
  853. }
  854. conn->package_window += STREAMWINDOW_INCREMENT;
  855. log_fn(LOG_DEBUG,"stream-level sendme, packagewindow now %d.", conn->package_window);
  856. connection_start_reading(conn);
  857. /* handle whatever might still be on the inbuf */
  858. if (connection_edge_package_raw_inbuf(conn, 1) < 0) {
  859. /* (We already sent an end cell if possible) */
  860. connection_mark_for_close(conn);
  861. return 0;
  862. }
  863. return 0;
  864. case RELAY_COMMAND_RESOLVE:
  865. if (layer_hint) {
  866. log_fn(LOG_WARN,"resolve request unsupported at AP; dropping.");
  867. return 0;
  868. } else if (conn) {
  869. log_fn(LOG_WARN, "resolve request for known stream; dropping.");
  870. return 0;
  871. } else if (circ->purpose != CIRCUIT_PURPOSE_OR) {
  872. log_fn(LOG_WARN, "resolve request on circ with purpose %d; dropping",
  873. circ->purpose);
  874. return 0;
  875. }
  876. connection_exit_begin_resolve(cell, circ);
  877. return 0;
  878. case RELAY_COMMAND_RESOLVED:
  879. if (conn) {
  880. log_fn(LOG_WARN,"'resolved' unsupported while open. Closing circ.");
  881. return -1;
  882. }
  883. log_fn(LOG_INFO,"'resolved' received, no conn attached anymore. Ignoring.");
  884. return 0;
  885. case RELAY_COMMAND_ESTABLISH_INTRO:
  886. case RELAY_COMMAND_ESTABLISH_RENDEZVOUS:
  887. case RELAY_COMMAND_INTRODUCE1:
  888. case RELAY_COMMAND_INTRODUCE2:
  889. case RELAY_COMMAND_INTRODUCE_ACK:
  890. case RELAY_COMMAND_RENDEZVOUS1:
  891. case RELAY_COMMAND_RENDEZVOUS2:
  892. case RELAY_COMMAND_INTRO_ESTABLISHED:
  893. case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
  894. rend_process_relay_cell(circ, rh.command, rh.length,
  895. cell->payload+RELAY_HEADER_SIZE);
  896. return 0;
  897. }
  898. log_fn(LOG_WARN,"unknown relay command %d.",rh.command);
  899. return -1;
  900. }
  901. uint64_t stats_n_data_cells_packaged = 0;
  902. uint64_t stats_n_data_bytes_packaged = 0;
  903. uint64_t stats_n_data_cells_received = 0;
  904. uint64_t stats_n_data_bytes_received = 0;
  905. /** While conn->inbuf has an entire relay payload of bytes on it,
  906. * and the appropriate package windows aren't empty, grab a cell
  907. * and send it down the circuit.
  908. *
  909. * Return -1 (and send a RELAY_END cell if necessary) if conn should
  910. * be marked for close, else return 0.
  911. */
  912. int connection_edge_package_raw_inbuf(connection_t *conn, int package_partial) {
  913. size_t amount_to_process, length;
  914. char payload[CELL_PAYLOAD_SIZE];
  915. circuit_t *circ;
  916. tor_assert(conn);
  917. tor_assert(!connection_speaks_cells(conn));
  918. if (conn->marked_for_close) {
  919. log_fn(LOG_WARN,"Bug: called on conn that's already marked for close at %s:%d.",
  920. conn->marked_for_close_file, conn->marked_for_close);
  921. return 0;
  922. }
  923. repeat_connection_edge_package_raw_inbuf:
  924. circ = circuit_get_by_edge_conn(conn);
  925. if (!circ) {
  926. log_fn(LOG_INFO,"conn has no circuit! Closing.");
  927. return -1;
  928. }
  929. if (circuit_consider_stop_edge_reading(circ, conn->cpath_layer))
  930. return 0;
  931. if (conn->package_window <= 0) {
  932. log_fn(LOG_INFO,"called with package_window %d. Skipping.", conn->package_window);
  933. connection_stop_reading(conn);
  934. return 0;
  935. }
  936. amount_to_process = buf_datalen(conn->inbuf);
  937. if (!amount_to_process)
  938. return 0;
  939. if (!package_partial && amount_to_process < RELAY_PAYLOAD_SIZE)
  940. return 0;
  941. if (amount_to_process > RELAY_PAYLOAD_SIZE) {
  942. length = RELAY_PAYLOAD_SIZE;
  943. } else {
  944. length = amount_to_process;
  945. }
  946. stats_n_data_bytes_packaged += length;
  947. stats_n_data_cells_packaged += 1;
  948. connection_fetch_from_buf(payload, length, conn);
  949. log_fn(LOG_DEBUG,"(%d) Packaging %d bytes (%d waiting).", conn->s,
  950. (int)length, (int)buf_datalen(conn->inbuf));
  951. if (connection_edge_send_command(conn, circ, RELAY_COMMAND_DATA,
  952. payload, length, conn->cpath_layer) < 0)
  953. /* circuit got marked for close, don't continue, don't need to mark conn */
  954. return 0;
  955. if (!conn->cpath_layer) { /* non-rendezvous exit */
  956. tor_assert(circ->package_window > 0);
  957. circ->package_window--;
  958. } else { /* we're an AP, or an exit on a rendezvous circ */
  959. tor_assert(conn->cpath_layer->package_window > 0);
  960. conn->cpath_layer->package_window--;
  961. }
  962. if (--conn->package_window <= 0) { /* is it 0 after decrement? */
  963. connection_stop_reading(conn);
  964. log_fn(LOG_DEBUG,"conn->package_window reached 0.");
  965. circuit_consider_stop_edge_reading(circ, conn->cpath_layer);
  966. return 0; /* don't process the inbuf any more */
  967. }
  968. log_fn(LOG_DEBUG,"conn->package_window is now %d",conn->package_window);
  969. /* handle more if there's more, or return 0 if there isn't */
  970. goto repeat_connection_edge_package_raw_inbuf;
  971. }
  972. /** Called when we've just received a relay data cell, or when
  973. * we've just finished flushing all bytes to stream <b>conn</b>.
  974. *
  975. * If conn->outbuf is not too full, and our deliver window is
  976. * low, send back a suitable number of stream-level sendme cells.
  977. */
  978. void connection_edge_consider_sending_sendme(connection_t *conn) {
  979. circuit_t *circ;
  980. if (connection_outbuf_too_full(conn))
  981. return;
  982. circ = circuit_get_by_edge_conn(conn);
  983. if (!circ) {
  984. /* this can legitimately happen if the destroy has already
  985. * arrived and torn down the circuit */
  986. log_fn(LOG_INFO,"No circuit associated with conn. Skipping.");
  987. return;
  988. }
  989. while (conn->deliver_window < STREAMWINDOW_START - STREAMWINDOW_INCREMENT) {
  990. log_fn(LOG_DEBUG,"Outbuf %d, Queueing stream sendme.", (int)conn->outbuf_flushlen);
  991. conn->deliver_window += STREAMWINDOW_INCREMENT;
  992. if (connection_edge_send_command(conn, circ, RELAY_COMMAND_SENDME,
  993. NULL, 0, conn->cpath_layer) < 0) {
  994. log_fn(LOG_WARN,"connection_edge_send_command failed. Returning.");
  995. return; /* the circuit's closed, don't continue */
  996. }
  997. }
  998. }
  999. /** The circuit <b>circ</b> has received a circuit-level sendme
  1000. * (on hop <b>layer_hint</b>, if we're the OP). Go through all the
  1001. * attached streams and let them resume reading and packaging, if
  1002. * their stream windows allow it.
  1003. */
  1004. static void
  1005. circuit_resume_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
  1006. {
  1007. log_fn(LOG_DEBUG,"resuming");
  1008. /* have to check both n_streams and p_streams, to handle rendezvous */
  1009. if (circuit_resume_edge_reading_helper(circ->n_streams, circ, layer_hint) >= 0)
  1010. circuit_resume_edge_reading_helper(circ->p_streams, circ, layer_hint);
  1011. }
  1012. /** A helper function for circuit_resume_edge_reading() above.
  1013. * The arguments are the same, except that <b>conn</b> is the head
  1014. * of a linked list of edge streams that should each be considered.
  1015. */
  1016. static int
  1017. circuit_resume_edge_reading_helper(connection_t *conn,
  1018. circuit_t *circ,
  1019. crypt_path_t *layer_hint) {
  1020. for ( ; conn; conn=conn->next_stream) {
  1021. if (conn->marked_for_close)
  1022. continue;
  1023. if ((!layer_hint && conn->package_window > 0) ||
  1024. (layer_hint && conn->package_window > 0 && conn->cpath_layer == layer_hint)) {
  1025. connection_start_reading(conn);
  1026. /* handle whatever might still be on the inbuf */
  1027. if (connection_edge_package_raw_inbuf(conn, 1)<0) {
  1028. /* (We already sent an end cell if possible) */
  1029. connection_mark_for_close(conn);
  1030. continue;
  1031. }
  1032. /* If the circuit won't accept any more data, return without looking
  1033. * at any more of the streams. Any connections that should be stopped
  1034. * have already been stopped by connection_edge_package_raw_inbuf. */
  1035. if (circuit_consider_stop_edge_reading(circ, layer_hint))
  1036. return -1;
  1037. }
  1038. }
  1039. return 0;
  1040. }
  1041. /** Check if the package window for <b>circ</b> is empty (at
  1042. * hop <b>layer_hint</b> if it's defined).
  1043. *
  1044. * If yes, tell edge streams to stop reading and return 1.
  1045. * Else return 0.
  1046. */
  1047. static int
  1048. circuit_consider_stop_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
  1049. {
  1050. connection_t *conn = NULL;
  1051. if (!layer_hint) {
  1052. log_fn(LOG_DEBUG,"considering circ->package_window %d", circ->package_window);
  1053. if (circ->package_window <= 0) {
  1054. log_fn(LOG_DEBUG,"yes, not-at-origin. stopped.");
  1055. for (conn = circ->n_streams; conn; conn=conn->next_stream)
  1056. connection_stop_reading(conn);
  1057. return 1;
  1058. }
  1059. return 0;
  1060. }
  1061. /* else, layer hint is defined, use it */
  1062. log_fn(LOG_DEBUG,"considering layer_hint->package_window %d", layer_hint->package_window);
  1063. if (layer_hint->package_window <= 0) {
  1064. log_fn(LOG_DEBUG,"yes, at-origin. stopped.");
  1065. for (conn = circ->n_streams; conn; conn=conn->next_stream)
  1066. if (conn->cpath_layer == layer_hint)
  1067. connection_stop_reading(conn);
  1068. for (conn = circ->p_streams; conn; conn=conn->next_stream)
  1069. if (conn->cpath_layer == layer_hint)
  1070. connection_stop_reading(conn);
  1071. return 1;
  1072. }
  1073. return 0;
  1074. }
  1075. /** Check if the deliver_window for circuit <b>circ</b> (at hop
  1076. * <b>layer_hint</b> if it's defined) is low enough that we should
  1077. * send a circuit-level sendme back down the circuit. If so, send
  1078. * enough sendmes that the window would be overfull if we sent any
  1079. * more.
  1080. */
  1081. static void
  1082. circuit_consider_sending_sendme(circuit_t *circ, crypt_path_t *layer_hint)
  1083. {
  1084. // log_fn(LOG_INFO,"Considering: layer_hint is %s",
  1085. // layer_hint ? "defined" : "null");
  1086. while ((layer_hint ? layer_hint->deliver_window : circ->deliver_window) <
  1087. CIRCWINDOW_START - CIRCWINDOW_INCREMENT) {
  1088. log_fn(LOG_DEBUG,"Queueing circuit sendme.");
  1089. if (layer_hint)
  1090. layer_hint->deliver_window += CIRCWINDOW_INCREMENT;
  1091. else
  1092. circ->deliver_window += CIRCWINDOW_INCREMENT;
  1093. if (connection_edge_send_command(NULL, circ, RELAY_COMMAND_SENDME,
  1094. NULL, 0, layer_hint) < 0) {
  1095. log_fn(LOG_WARN,"connection_edge_send_command failed. Circuit's closed.");
  1096. return; /* the circuit's closed, don't continue */
  1097. }
  1098. }
  1099. }