relay.c 43 KB

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