relay.c 45 KB

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