relay.c 46 KB

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