relay.c 46 KB

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