relay.c 51 KB

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