relay.c 51 KB

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