relay.c 49 KB

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