relay.c 45 KB

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