relay.c 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  4. * Copyright (c) 2007-2008, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /* $Id$ */
  7. const char relay_c_id[] =
  8. "$Id$";
  9. /**
  10. * \file relay.c
  11. * \brief Handle relay cell encryption/decryption, plus packaging and
  12. * receiving from circuits, plus queueing on circuits.
  13. **/
  14. #include "or.h"
  15. #include "mempool.h"
  16. static int relay_crypt(circuit_t *circ, cell_t *cell, int cell_direction,
  17. crypt_path_t **layer_hint, char *recognized);
  18. static edge_connection_t *relay_lookup_conn(circuit_t *circ, cell_t *cell,
  19. int cell_direction,
  20. crypt_path_t *layer_hint);
  21. static int
  22. connection_edge_process_relay_cell(cell_t *cell, circuit_t *circ,
  23. edge_connection_t *conn,
  24. crypt_path_t *layer_hint);
  25. static void
  26. circuit_consider_sending_sendme(circuit_t *circ, crypt_path_t *layer_hint);
  27. static void
  28. circuit_resume_edge_reading(circuit_t *circ, crypt_path_t *layer_hint);
  29. static int
  30. circuit_resume_edge_reading_helper(edge_connection_t *conn,
  31. circuit_t *circ,
  32. crypt_path_t *layer_hint);
  33. static int
  34. circuit_consider_stop_edge_reading(circuit_t *circ, crypt_path_t *layer_hint);
  35. /** Stats: how many relay cells have originated at this hop, or have
  36. * been relayed onward (not recognized at this hop)?
  37. */
  38. uint64_t stats_n_relay_cells_relayed = 0;
  39. /** Stats: how many relay cells have been delivered to streams at this
  40. * hop?
  41. */
  42. uint64_t stats_n_relay_cells_delivered = 0;
  43. /** Update digest from the payload of cell. Assign integrity part to
  44. * cell.
  45. */
  46. static void
  47. relay_set_digest(crypto_digest_env_t *digest, cell_t *cell)
  48. {
  49. char integrity[4];
  50. relay_header_t rh;
  51. crypto_digest_add_bytes(digest, cell->payload, CELL_PAYLOAD_SIZE);
  52. crypto_digest_get_digest(digest, integrity, 4);
  53. // log_fn(LOG_DEBUG,"Putting digest of %u %u %u %u into relay cell.",
  54. // integrity[0], integrity[1], integrity[2], integrity[3]);
  55. relay_header_unpack(&rh, cell->payload);
  56. memcpy(rh.integrity, integrity, 4);
  57. relay_header_pack(cell->payload, &rh);
  58. }
  59. /** Does the digest for this circuit indicate that this cell is for us?
  60. *
  61. * Update digest from the payload of cell (with the integrity part set
  62. * to 0). If the integrity part is valid, return 1, else restore digest
  63. * and cell to their original state and return 0.
  64. */
  65. static int
  66. relay_digest_matches(crypto_digest_env_t *digest, cell_t *cell)
  67. {
  68. char received_integrity[4], calculated_integrity[4];
  69. relay_header_t rh;
  70. crypto_digest_env_t *backup_digest=NULL;
  71. backup_digest = crypto_digest_dup(digest);
  72. relay_header_unpack(&rh, cell->payload);
  73. memcpy(received_integrity, rh.integrity, 4);
  74. memset(rh.integrity, 0, 4);
  75. relay_header_pack(cell->payload, &rh);
  76. // log_fn(LOG_DEBUG,"Reading digest of %u %u %u %u from relay cell.",
  77. // received_integrity[0], received_integrity[1],
  78. // received_integrity[2], received_integrity[3]);
  79. crypto_digest_add_bytes(digest, cell->payload, CELL_PAYLOAD_SIZE);
  80. crypto_digest_get_digest(digest, calculated_integrity, 4);
  81. if (memcmp(received_integrity, calculated_integrity, 4)) {
  82. // log_fn(LOG_INFO,"Recognized=0 but bad digest. Not recognizing.");
  83. // (%d vs %d).", received_integrity, calculated_integrity);
  84. /* restore digest to its old form */
  85. crypto_digest_assign(digest, backup_digest);
  86. /* restore the relay header */
  87. memcpy(rh.integrity, received_integrity, 4);
  88. relay_header_pack(cell->payload, &rh);
  89. crypto_free_digest_env(backup_digest);
  90. return 0;
  91. }
  92. crypto_free_digest_env(backup_digest);
  93. return 1;
  94. }
  95. /** Apply <b>cipher</b> to CELL_PAYLOAD_SIZE bytes of <b>in</b>
  96. * (in place).
  97. *
  98. * If <b>encrypt_mode</b> is 1 then encrypt, else decrypt.
  99. *
  100. * Return -1 if the crypto fails, else return 0.
  101. */
  102. static int
  103. relay_crypt_one_payload(crypto_cipher_env_t *cipher, char *in,
  104. int encrypt_mode)
  105. {
  106. char out[CELL_PAYLOAD_SIZE]; /* 'in' must be this size too */
  107. int r;
  108. if (encrypt_mode)
  109. r = crypto_cipher_encrypt(cipher, out, in, CELL_PAYLOAD_SIZE);
  110. else
  111. r = crypto_cipher_decrypt(cipher, out, in, CELL_PAYLOAD_SIZE);
  112. if (r) {
  113. log_warn(LD_BUG,"Error during relay encryption");
  114. return -1;
  115. }
  116. memcpy(in,out,CELL_PAYLOAD_SIZE);
  117. return 0;
  118. }
  119. /** Receive a relay cell:
  120. * - Crypt it (encrypt if headed toward the origin or if we <b>are</b> the
  121. * origin; decrypt if we're headed toward the exit).
  122. * - Check if recognized (if exitward).
  123. * - If recognized and the digest checks out, then find if there's a stream
  124. * that the cell is intended for, and deliver it to the right
  125. * connection_edge.
  126. * - If not recognized, then we need to relay it: append it to the appropriate
  127. * cell_queue on <b>circ</b>.
  128. *
  129. * Return -<b>reason</b> on failure.
  130. */
  131. int
  132. circuit_receive_relay_cell(cell_t *cell, circuit_t *circ, int cell_direction)
  133. {
  134. or_connection_t *or_conn=NULL;
  135. crypt_path_t *layer_hint=NULL;
  136. char recognized=0;
  137. int reason;
  138. tor_assert(cell);
  139. tor_assert(circ);
  140. tor_assert(cell_direction == CELL_DIRECTION_OUT ||
  141. cell_direction == CELL_DIRECTION_IN);
  142. if (circ->marked_for_close)
  143. return 0;
  144. if (relay_crypt(circ, cell, cell_direction, &layer_hint, &recognized) < 0) {
  145. log_warn(LD_BUG,"relay crypt failed. Dropping connection.");
  146. return -END_CIRC_REASON_INTERNAL;
  147. }
  148. if (recognized) {
  149. edge_connection_t *conn = relay_lookup_conn(circ, cell, cell_direction,
  150. layer_hint);
  151. if (cell_direction == CELL_DIRECTION_OUT) {
  152. ++stats_n_relay_cells_delivered;
  153. log_debug(LD_OR,"Sending away from origin.");
  154. if ((reason=connection_edge_process_relay_cell(cell, circ, conn, NULL))
  155. < 0) {
  156. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  157. "connection_edge_process_relay_cell (away from origin) "
  158. "failed.");
  159. return reason;
  160. }
  161. }
  162. if (cell_direction == CELL_DIRECTION_IN) {
  163. ++stats_n_relay_cells_delivered;
  164. log_debug(LD_OR,"Sending to origin.");
  165. if ((reason = connection_edge_process_relay_cell(cell, circ, conn,
  166. layer_hint)) < 0) {
  167. log_warn(LD_OR,
  168. "connection_edge_process_relay_cell (at origin) failed.");
  169. return reason;
  170. }
  171. }
  172. return 0;
  173. }
  174. /* not recognized. pass it on. */
  175. if (cell_direction == CELL_DIRECTION_OUT) {
  176. cell->circ_id = circ->n_circ_id; /* switch it */
  177. or_conn = circ->n_conn;
  178. } else if (! CIRCUIT_IS_ORIGIN(circ)) {
  179. cell->circ_id = TO_OR_CIRCUIT(circ)->p_circ_id; /* switch it */
  180. or_conn = TO_OR_CIRCUIT(circ)->p_conn;
  181. } else {
  182. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  183. "Dropping unrecognized inbound cell on origin circuit.");
  184. return 0;
  185. }
  186. if (!or_conn) {
  187. // XXXX Can this splice stuff be done more cleanly?
  188. if (! CIRCUIT_IS_ORIGIN(circ) &&
  189. TO_OR_CIRCUIT(circ)->rend_splice &&
  190. cell_direction == CELL_DIRECTION_OUT) {
  191. or_circuit_t *splice = TO_OR_CIRCUIT(circ)->rend_splice;
  192. tor_assert(circ->purpose == CIRCUIT_PURPOSE_REND_ESTABLISHED);
  193. tor_assert(splice->_base.purpose == CIRCUIT_PURPOSE_REND_ESTABLISHED);
  194. cell->circ_id = splice->p_circ_id;
  195. if ((reason = circuit_receive_relay_cell(cell, TO_CIRCUIT(splice),
  196. CELL_DIRECTION_IN)) < 0) {
  197. log_warn(LD_REND, "Error relaying cell across rendezvous; closing "
  198. "circuits");
  199. /* XXXX Do this here, or just return -1? */
  200. circuit_mark_for_close(circ, -reason);
  201. return reason;
  202. }
  203. return 0;
  204. }
  205. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  206. "Didn't recognize cell, but circ stops here! Closing circ.");
  207. return -END_CIRC_REASON_TORPROTOCOL;
  208. }
  209. log_debug(LD_OR,"Passing on unrecognized cell.");
  210. ++stats_n_relay_cells_relayed; /* XXXX no longer quite accurate {cells}
  211. * we might kill the circ before we relay
  212. * the cells. */
  213. append_cell_to_circuit_queue(circ, or_conn, cell, cell_direction);
  214. return 0;
  215. }
  216. /** Do the appropriate en/decryptions for <b>cell</b> arriving on
  217. * <b>circ</b> in direction <b>cell_direction</b>.
  218. *
  219. * If cell_direction == CELL_DIRECTION_IN:
  220. * - If we're at the origin (we're the OP), for hops 1..N,
  221. * decrypt cell. If recognized, stop.
  222. * - Else (we're not the OP), encrypt one hop. Cell is not recognized.
  223. *
  224. * If cell_direction == CELL_DIRECTION_OUT:
  225. * - decrypt one hop. Check if recognized.
  226. *
  227. * If cell is recognized, set *recognized to 1, and set
  228. * *layer_hint to the hop that recognized it.
  229. *
  230. * Return -1 to indicate that we should mark the circuit for close,
  231. * else return 0.
  232. */
  233. static int
  234. relay_crypt(circuit_t *circ, cell_t *cell, int cell_direction,
  235. crypt_path_t **layer_hint, char *recognized)
  236. {
  237. relay_header_t rh;
  238. tor_assert(circ);
  239. tor_assert(cell);
  240. tor_assert(recognized);
  241. tor_assert(cell_direction == CELL_DIRECTION_IN ||
  242. cell_direction == CELL_DIRECTION_OUT);
  243. if (cell_direction == CELL_DIRECTION_IN) {
  244. if (CIRCUIT_IS_ORIGIN(circ)) { /* We're at the beginning of the circuit.
  245. * We'll want to do layered decrypts. */
  246. crypt_path_t *thishop, *cpath = TO_ORIGIN_CIRCUIT(circ)->cpath;
  247. thishop = cpath;
  248. if (thishop->state != CPATH_STATE_OPEN) {
  249. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  250. "Relay cell before first created cell? Closing.");
  251. return -1;
  252. }
  253. do { /* Remember: cpath is in forward order, that is, first hop first. */
  254. tor_assert(thishop);
  255. if (relay_crypt_one_payload(thishop->b_crypto, cell->payload, 0) < 0)
  256. return -1;
  257. relay_header_unpack(&rh, cell->payload);
  258. if (rh.recognized == 0) {
  259. /* it's possibly recognized. have to check digest to be sure. */
  260. if (relay_digest_matches(thishop->b_digest, cell)) {
  261. *recognized = 1;
  262. *layer_hint = thishop;
  263. return 0;
  264. }
  265. }
  266. thishop = thishop->next;
  267. } while (thishop != cpath && thishop->state == CPATH_STATE_OPEN);
  268. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  269. "Incoming cell at client not recognized. Closing.");
  270. return -1;
  271. } else { /* we're in the middle. Just one crypt. */
  272. if (relay_crypt_one_payload(TO_OR_CIRCUIT(circ)->p_crypto,
  273. cell->payload, 1) < 0)
  274. return -1;
  275. // log_fn(LOG_DEBUG,"Skipping recognized check, because we're not "
  276. // "the client.");
  277. }
  278. } else /* cell_direction == CELL_DIRECTION_OUT */ {
  279. /* we're in the middle. Just one crypt. */
  280. if (relay_crypt_one_payload(TO_OR_CIRCUIT(circ)->n_crypto,
  281. cell->payload, 0) < 0)
  282. return -1;
  283. relay_header_unpack(&rh, cell->payload);
  284. if (rh.recognized == 0) {
  285. /* it's possibly recognized. have to check digest to be sure. */
  286. if (relay_digest_matches(TO_OR_CIRCUIT(circ)->n_digest, cell)) {
  287. *recognized = 1;
  288. return 0;
  289. }
  290. }
  291. }
  292. return 0;
  293. }
  294. /** Package a relay cell from an edge:
  295. * - Encrypt it to the right layer
  296. * - Append it to the appropriate cell_queue on <b>circ</b>.
  297. */
  298. static int
  299. circuit_package_relay_cell(cell_t *cell, circuit_t *circ,
  300. int cell_direction,
  301. crypt_path_t *layer_hint)
  302. {
  303. or_connection_t *conn; /* where to send the cell */
  304. if (cell_direction == CELL_DIRECTION_OUT) {
  305. crypt_path_t *thishop; /* counter for repeated crypts */
  306. conn = circ->n_conn;
  307. if (!CIRCUIT_IS_ORIGIN(circ) || !conn) {
  308. log_warn(LD_BUG,"outgoing relay cell has n_conn==NULL. Dropping.");
  309. return 0; /* just drop it */
  310. }
  311. relay_set_digest(layer_hint->f_digest, cell);
  312. thishop = layer_hint;
  313. /* moving from farthest to nearest hop */
  314. do {
  315. tor_assert(thishop);
  316. /* XXXX RD This is a bug, right? */
  317. log_debug(LD_OR,"crypting a layer of the relay cell.");
  318. if (relay_crypt_one_payload(thishop->f_crypto, cell->payload, 1) < 0) {
  319. return -1;
  320. }
  321. thishop = thishop->prev;
  322. } while (thishop != TO_ORIGIN_CIRCUIT(circ)->cpath->prev);
  323. } else { /* incoming cell */
  324. or_circuit_t *or_circ;
  325. if (CIRCUIT_IS_ORIGIN(circ)) {
  326. /* We should never package an _incoming_ cell from the circuit
  327. * origin; that means we messed up somewhere. */
  328. log_warn(LD_BUG,"incoming relay cell at origin circuit. Dropping.");
  329. assert_circuit_ok(circ);
  330. return 0; /* just drop it */
  331. }
  332. or_circ = TO_OR_CIRCUIT(circ);
  333. conn = or_circ->p_conn;
  334. relay_set_digest(or_circ->p_digest, cell);
  335. if (relay_crypt_one_payload(or_circ->p_crypto, cell->payload, 1) < 0)
  336. return -1;
  337. }
  338. ++stats_n_relay_cells_relayed;
  339. append_cell_to_circuit_queue(circ, conn, cell, cell_direction);
  340. return 0;
  341. }
  342. /** If cell's stream_id matches the stream_id of any conn that's
  343. * attached to circ, return that conn, else return NULL.
  344. */
  345. static edge_connection_t *
  346. relay_lookup_conn(circuit_t *circ, cell_t *cell, int cell_direction,
  347. crypt_path_t *layer_hint)
  348. {
  349. edge_connection_t *tmpconn;
  350. relay_header_t rh;
  351. relay_header_unpack(&rh, cell->payload);
  352. if (!rh.stream_id)
  353. return NULL;
  354. /* IN or OUT cells could have come from either direction, now
  355. * that we allow rendezvous *to* an OP.
  356. */
  357. if (CIRCUIT_IS_ORIGIN(circ)) {
  358. for (tmpconn = TO_ORIGIN_CIRCUIT(circ)->p_streams; tmpconn;
  359. tmpconn=tmpconn->next_stream) {
  360. if (rh.stream_id == tmpconn->stream_id &&
  361. !tmpconn->_base.marked_for_close &&
  362. tmpconn->cpath_layer == layer_hint) {
  363. log_debug(LD_APP,"found conn for stream %d.", rh.stream_id);
  364. return tmpconn;
  365. }
  366. }
  367. } else {
  368. for (tmpconn = TO_OR_CIRCUIT(circ)->n_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. if (cell_direction == CELL_DIRECTION_OUT ||
  374. connection_edge_is_rendezvous_stream(tmpconn))
  375. return tmpconn;
  376. }
  377. }
  378. for (tmpconn = TO_OR_CIRCUIT(circ)->resolving_streams; tmpconn;
  379. tmpconn=tmpconn->next_stream) {
  380. if (rh.stream_id == tmpconn->stream_id &&
  381. !tmpconn->_base.marked_for_close) {
  382. log_debug(LD_EXIT,"found conn for stream %d.", rh.stream_id);
  383. return tmpconn;
  384. }
  385. }
  386. }
  387. return NULL; /* probably a begin relay cell */
  388. }
  389. /** Pack the relay_header_t host-order structure <b>src</b> into
  390. * network-order in the buffer <b>dest</b>. See tor-spec.txt for details
  391. * about the wire format.
  392. */
  393. void
  394. relay_header_pack(char *dest, const relay_header_t *src)
  395. {
  396. *(uint8_t*)(dest) = src->command;
  397. set_uint16(dest+1, htons(src->recognized));
  398. set_uint16(dest+3, htons(src->stream_id));
  399. memcpy(dest+5, src->integrity, 4);
  400. set_uint16(dest+9, htons(src->length));
  401. }
  402. /** Unpack the network-order buffer <b>src</b> into a host-order
  403. * relay_header_t structure <b>dest</b>.
  404. */
  405. void
  406. relay_header_unpack(relay_header_t *dest, const char *src)
  407. {
  408. dest->command = *(uint8_t*)(src);
  409. dest->recognized = ntohs(get_uint16(src+1));
  410. dest->stream_id = ntohs(get_uint16(src+3));
  411. memcpy(dest->integrity, src+5, 4);
  412. dest->length = ntohs(get_uint16(src+9));
  413. }
  414. /** Make a relay cell out of <b>relay_command</b> and <b>payload</b>, and send
  415. * it onto the open circuit <b>circ</b>. <b>stream_id</b> is the ID on
  416. * <b>circ</b> for the stream that's sending the relay cell, or 0 if it's a
  417. * control cell. <b>cpath_layer</b> is NULL for OR->OP cells, or the
  418. * destination hop for OP->OR cells.
  419. *
  420. * If you can't send the cell, mark the circuit for close and return -1. Else
  421. * return 0.
  422. */
  423. int
  424. relay_send_command_from_edge(uint16_t stream_id, circuit_t *circ,
  425. int relay_command, const char *payload,
  426. size_t payload_len, crypt_path_t *cpath_layer)
  427. {
  428. cell_t cell;
  429. relay_header_t rh;
  430. int cell_direction;
  431. /* XXXX NM Split this function into a separate versions per circuit type? */
  432. tor_assert(circ);
  433. memset(&cell, 0, sizeof(cell_t));
  434. cell.command = CELL_RELAY;
  435. if (cpath_layer) {
  436. cell.circ_id = circ->n_circ_id;
  437. cell_direction = CELL_DIRECTION_OUT;
  438. } else if (! CIRCUIT_IS_ORIGIN(circ)) {
  439. cell.circ_id = TO_OR_CIRCUIT(circ)->p_circ_id;
  440. cell_direction = CELL_DIRECTION_IN;
  441. } else {
  442. return -1;
  443. }
  444. memset(&rh, 0, sizeof(rh));
  445. rh.command = relay_command;
  446. rh.stream_id = stream_id;
  447. rh.length = payload_len;
  448. relay_header_pack(cell.payload, &rh);
  449. if (payload_len) {
  450. tor_assert(payload_len <= RELAY_PAYLOAD_SIZE);
  451. memcpy(cell.payload+RELAY_HEADER_SIZE, payload, payload_len);
  452. }
  453. log_debug(LD_OR,"delivering %d cell %s.", relay_command,
  454. cell_direction == CELL_DIRECTION_OUT ? "forward" : "backward");
  455. if (cell_direction == CELL_DIRECTION_OUT && circ->n_conn) {
  456. /* if we're using relaybandwidthrate, this conn wants priority */
  457. /* XXXX020 the call to time() seems little too frequent */
  458. circ->n_conn->client_used = time(NULL);
  459. }
  460. if (circuit_package_relay_cell(&cell, circ, cell_direction, cpath_layer)
  461. < 0) {
  462. log_warn(LD_BUG,"circuit_package_relay_cell failed. Closing.");
  463. circuit_mark_for_close(circ, END_CIRC_REASON_INTERNAL);
  464. return -1;
  465. }
  466. return 0;
  467. }
  468. /** Make a relay cell out of <b>relay_command</b> and <b>payload</b>, and
  469. * send it onto the open circuit <b>circ</b>. <b>fromconn</b> is the stream
  470. * that's sending the relay cell, or NULL if it's a control cell.
  471. * <b>cpath_layer</b> is NULL for OR->OP cells, or the destination hop
  472. * for OP->OR cells.
  473. *
  474. * If you can't send the cell, mark the circuit for close and
  475. * return -1. Else return 0.
  476. */
  477. int
  478. connection_edge_send_command(edge_connection_t *fromconn,
  479. int relay_command, const char *payload,
  480. size_t payload_len)
  481. {
  482. /* XXXX NM Split this function into a separate versions per circuit type? */
  483. circuit_t *circ;
  484. tor_assert(fromconn);
  485. circ = fromconn->on_circuit;
  486. if (fromconn->_base.marked_for_close) {
  487. log_warn(LD_BUG,
  488. "called on conn that's already marked for close at %s:%d.",
  489. fromconn->_base.marked_for_close_file,
  490. fromconn->_base.marked_for_close);
  491. return 0;
  492. }
  493. if (!circ) {
  494. if (fromconn->_base.type == CONN_TYPE_AP) {
  495. log_info(LD_APP,"no circ. Closing conn.");
  496. connection_mark_unattached_ap(fromconn, END_STREAM_REASON_INTERNAL);
  497. } else {
  498. log_info(LD_EXIT,"no circ. Closing conn.");
  499. fromconn->_base.edge_has_sent_end = 1; /* no circ to send to */
  500. fromconn->end_reason = END_STREAM_REASON_INTERNAL;
  501. connection_mark_for_close(TO_CONN(fromconn));
  502. }
  503. return -1;
  504. }
  505. return relay_send_command_from_edge(fromconn->stream_id, circ,
  506. relay_command, payload,
  507. payload_len, fromconn->cpath_layer);
  508. }
  509. /** Translate <b>reason</b>, which came from a relay 'end' cell,
  510. * into a static const string describing why the stream is closing.
  511. * <b>reason</b> is -1 if no reason was provided.
  512. */
  513. static const char *
  514. connection_edge_end_reason_str(int reason)
  515. {
  516. switch (reason) {
  517. case -1:
  518. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  519. "End cell arrived with length 0. Should be at least 1.");
  520. return "MALFORMED";
  521. case END_STREAM_REASON_MISC: return "misc error";
  522. case END_STREAM_REASON_RESOLVEFAILED: return "resolve failed";
  523. case END_STREAM_REASON_CONNECTREFUSED: return "connection refused";
  524. case END_STREAM_REASON_EXITPOLICY: return "exit policy failed";
  525. case END_STREAM_REASON_DESTROY: return "destroyed";
  526. case END_STREAM_REASON_DONE: return "closed normally";
  527. case END_STREAM_REASON_TIMEOUT: return "gave up (timeout)";
  528. case END_STREAM_REASON_HIBERNATING: return "server is hibernating";
  529. case END_STREAM_REASON_INTERNAL: return "internal error at server";
  530. case END_STREAM_REASON_RESOURCELIMIT: return "server out of resources";
  531. case END_STREAM_REASON_CONNRESET: return "connection reset";
  532. case END_STREAM_REASON_TORPROTOCOL: return "Tor protocol error";
  533. case END_STREAM_REASON_NOTDIRECTORY: return "not a directory";
  534. default:
  535. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  536. "Reason for ending (%d) not recognized.",reason);
  537. return "unknown";
  538. }
  539. }
  540. /** Translate <b>reason</b> (as from a relay 'end' cell) into an
  541. * appropriate SOCKS5 reply code.
  542. *
  543. * A reason of 0 means that we're not actually expecting to send
  544. * this code back to the socks client; we just call it 'succeeded'
  545. * to keep things simple.
  546. */
  547. socks5_reply_status_t
  548. connection_edge_end_reason_socks5_response(int reason)
  549. {
  550. switch (reason & END_STREAM_REASON_MASK) {
  551. case 0:
  552. return SOCKS5_SUCCEEDED;
  553. case END_STREAM_REASON_MISC:
  554. return SOCKS5_GENERAL_ERROR;
  555. case END_STREAM_REASON_RESOLVEFAILED:
  556. return SOCKS5_HOST_UNREACHABLE;
  557. case END_STREAM_REASON_CONNECTREFUSED:
  558. return SOCKS5_CONNECTION_REFUSED;
  559. case END_STREAM_REASON_ENTRYPOLICY:
  560. return SOCKS5_NOT_ALLOWED;
  561. case END_STREAM_REASON_EXITPOLICY:
  562. return SOCKS5_NOT_ALLOWED;
  563. case END_STREAM_REASON_DESTROY:
  564. return SOCKS5_GENERAL_ERROR;
  565. case END_STREAM_REASON_DONE:
  566. return SOCKS5_SUCCEEDED;
  567. case END_STREAM_REASON_TIMEOUT:
  568. return SOCKS5_TTL_EXPIRED;
  569. case END_STREAM_REASON_RESOURCELIMIT:
  570. return SOCKS5_GENERAL_ERROR;
  571. case END_STREAM_REASON_HIBERNATING:
  572. return SOCKS5_GENERAL_ERROR;
  573. case END_STREAM_REASON_INTERNAL:
  574. return SOCKS5_GENERAL_ERROR;
  575. case END_STREAM_REASON_CONNRESET:
  576. return SOCKS5_CONNECTION_REFUSED;
  577. case END_STREAM_REASON_TORPROTOCOL:
  578. return SOCKS5_GENERAL_ERROR;
  579. case END_STREAM_REASON_CANT_ATTACH:
  580. return SOCKS5_GENERAL_ERROR;
  581. case END_STREAM_REASON_NET_UNREACHABLE:
  582. return SOCKS5_NET_UNREACHABLE;
  583. case END_STREAM_REASON_SOCKSPROTOCOL:
  584. return SOCKS5_GENERAL_ERROR;
  585. default:
  586. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  587. "Reason for ending (%d) not recognized; "
  588. "sending generic socks error.", reason);
  589. return SOCKS5_GENERAL_ERROR;
  590. }
  591. }
  592. /* We need to use a few macros to deal with the fact that Windows
  593. * decided that their sockets interface should be a permakludge.
  594. * E_CASE is for errors where windows has both a EFOO and a WSAEFOO
  595. * version, and S_CASE is for errors where windows has only a WSAEFOO
  596. * version. (The E is for 'error', the S is for 'socket'). */
  597. #ifdef MS_WINDOWS
  598. #define E_CASE(s) case s: case WSA ## s
  599. #define S_CASE(s) case WSA ## s
  600. #else
  601. #define E_CASE(s) case s
  602. #define S_CASE(s) case s
  603. #endif
  604. /** Given an errno from a failed exit connection, return a reason code
  605. * appropriate for use in a RELAY END cell.
  606. */
  607. int
  608. errno_to_end_reason(int e)
  609. {
  610. switch (e) {
  611. case EPIPE:
  612. return END_STREAM_REASON_DONE;
  613. E_CASE(EBADF):
  614. E_CASE(EFAULT):
  615. E_CASE(EINVAL):
  616. S_CASE(EISCONN):
  617. S_CASE(ENOTSOCK):
  618. S_CASE(EPROTONOSUPPORT):
  619. S_CASE(EAFNOSUPPORT):
  620. E_CASE(EACCES):
  621. S_CASE(ENOTCONN):
  622. S_CASE(ENETUNREACH):
  623. return END_STREAM_REASON_INTERNAL;
  624. S_CASE(ECONNREFUSED):
  625. return END_STREAM_REASON_CONNECTREFUSED;
  626. S_CASE(ECONNRESET):
  627. return END_STREAM_REASON_CONNRESET;
  628. S_CASE(ETIMEDOUT):
  629. return END_STREAM_REASON_TIMEOUT;
  630. S_CASE(ENOBUFS):
  631. case ENOMEM:
  632. case ENFILE:
  633. E_CASE(EMFILE):
  634. return END_STREAM_REASON_RESOURCELIMIT;
  635. default:
  636. log_info(LD_EXIT, "Didn't recognize errno %d (%s); telling the client "
  637. "that we are ending a stream for 'misc' reason.",
  638. e, tor_socket_strerror(e));
  639. return END_STREAM_REASON_MISC;
  640. }
  641. }
  642. /** How many times will I retry a stream that fails due to DNS
  643. * resolve failure or misc error?
  644. */
  645. #define MAX_RESOLVE_FAILURES 3
  646. /** Return 1 if reason is something that you should retry if you
  647. * get the end cell before you've connected; else return 0. */
  648. static int
  649. edge_reason_is_retriable(int reason)
  650. {
  651. return reason == END_STREAM_REASON_HIBERNATING ||
  652. reason == END_STREAM_REASON_RESOURCELIMIT ||
  653. reason == END_STREAM_REASON_EXITPOLICY ||
  654. reason == END_STREAM_REASON_RESOLVEFAILED ||
  655. reason == END_STREAM_REASON_MISC;
  656. }
  657. /** Called when we receive an END cell on a stream that isn't open yet.
  658. * Arguments are as for connection_edge_process_relay_cell().
  659. */
  660. static int
  661. connection_edge_process_end_not_open(
  662. relay_header_t *rh, cell_t *cell, origin_circuit_t *circ,
  663. edge_connection_t *conn, crypt_path_t *layer_hint)
  664. {
  665. struct in_addr in;
  666. routerinfo_t *exitrouter;
  667. int reason = *(cell->payload+RELAY_HEADER_SIZE);
  668. int control_reason = reason | END_STREAM_REASON_FLAG_REMOTE;
  669. (void) layer_hint; /* unused */
  670. if (rh->length > 0 && edge_reason_is_retriable(reason) &&
  671. conn->_base.type == CONN_TYPE_AP) {
  672. log_info(LD_APP,"Address '%s' refused due to '%s'. Considering retrying.",
  673. safe_str(conn->socks_request->address),
  674. connection_edge_end_reason_str(reason));
  675. exitrouter =
  676. router_get_by_digest(circ->build_state->chosen_exit->identity_digest);
  677. switch (reason) {
  678. case END_STREAM_REASON_EXITPOLICY:
  679. if (rh->length >= 5) {
  680. uint32_t addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+1));
  681. int ttl;
  682. if (!addr) {
  683. log_info(LD_APP,"Address '%s' resolved to 0.0.0.0. Closing,",
  684. safe_str(conn->socks_request->address));
  685. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  686. return 0;
  687. }
  688. if (rh->length >= 9)
  689. ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+5));
  690. else
  691. ttl = -1;
  692. client_dns_set_addressmap(conn->socks_request->address, addr,
  693. conn->chosen_exit_name, ttl);
  694. }
  695. /* check if he *ought* to have allowed it */
  696. if (exitrouter &&
  697. (rh->length < 5 ||
  698. (tor_inet_aton(conn->socks_request->address, &in) &&
  699. !conn->chosen_exit_name))) {
  700. log_notice(LD_APP,
  701. "Exitrouter '%s' seems to be more restrictive than its exit "
  702. "policy. Not using this router as exit for now.",
  703. exitrouter->nickname);
  704. policies_set_router_exitpolicy_to_reject_all(exitrouter);
  705. }
  706. /* rewrite it to an IP if we learned one. */
  707. if (addressmap_rewrite(conn->socks_request->address,
  708. sizeof(conn->socks_request->address),
  709. NULL)) {
  710. control_event_stream_status(conn, STREAM_EVENT_REMAP, 0);
  711. }
  712. if (conn->_base.chosen_exit_optional) {
  713. /* stop wanting a specific exit */
  714. conn->_base.chosen_exit_optional = 0;
  715. tor_free(conn->chosen_exit_name); /* clears it */
  716. }
  717. if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
  718. return 0;
  719. /* else, conn will get closed below */
  720. break;
  721. case END_STREAM_REASON_CONNECTREFUSED:
  722. if (!conn->_base.chosen_exit_optional)
  723. break; /* break means it'll close, below */
  724. /* Else fall through: expire this circuit, clear the
  725. * chosen_exit_name field, and try again. */
  726. case END_STREAM_REASON_RESOLVEFAILED:
  727. case END_STREAM_REASON_TIMEOUT:
  728. case END_STREAM_REASON_MISC:
  729. if (client_dns_incr_failures(conn->socks_request->address)
  730. < MAX_RESOLVE_FAILURES) {
  731. /* We haven't retried too many times; reattach the connection. */
  732. circuit_log_path(LOG_INFO,LD_APP,circ);
  733. tor_assert(circ->_base.timestamp_dirty);
  734. circ->_base.timestamp_dirty -= get_options()->MaxCircuitDirtiness;
  735. if (conn->_base.chosen_exit_optional) {
  736. /* stop wanting a specific exit */
  737. conn->_base.chosen_exit_optional = 0;
  738. tor_free(conn->chosen_exit_name); /* clears it */
  739. }
  740. if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
  741. return 0;
  742. /* else, conn will get closed below */
  743. } else {
  744. log_notice(LD_APP,
  745. "Have tried resolving or connecting to address '%s' "
  746. "at %d different places. Giving up.",
  747. safe_str(conn->socks_request->address),
  748. MAX_RESOLVE_FAILURES);
  749. /* clear the failures, so it will have a full try next time */
  750. client_dns_clear_failures(conn->socks_request->address);
  751. }
  752. break;
  753. case END_STREAM_REASON_HIBERNATING:
  754. case END_STREAM_REASON_RESOURCELIMIT:
  755. if (exitrouter) {
  756. policies_set_router_exitpolicy_to_reject_all(exitrouter);
  757. }
  758. if (conn->_base.chosen_exit_optional) {
  759. /* stop wanting a specific exit */
  760. conn->_base.chosen_exit_optional = 0;
  761. tor_free(conn->chosen_exit_name); /* clears it */
  762. }
  763. if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
  764. return 0;
  765. /* else, will close below */
  766. break;
  767. } /* end switch */
  768. log_info(LD_APP,"Giving up on retrying; conn can't be handled.");
  769. }
  770. log_info(LD_APP,
  771. "Edge got end (%s) before we're connected. Marking for close.",
  772. connection_edge_end_reason_str(rh->length > 0 ? reason : -1));
  773. if (conn->_base.type == CONN_TYPE_AP) {
  774. circuit_log_path(LOG_INFO,LD_APP,circ);
  775. connection_mark_unattached_ap(conn, control_reason);
  776. } else {
  777. /* we just got an 'end', don't need to send one */
  778. conn->_base.edge_has_sent_end = 1;
  779. conn->end_reason = control_reason;
  780. connection_mark_for_close(TO_CONN(conn));
  781. }
  782. return 0;
  783. }
  784. /** Helper: change the socks_request-&gt;address field on conn to the
  785. * dotted-quad representation of <b>new_addr</b> (given in host order),
  786. * and send an appropriate REMAP event. */
  787. static void
  788. remap_event_helper(edge_connection_t *conn, uint32_t new_addr)
  789. {
  790. struct in_addr in;
  791. in.s_addr = htonl(new_addr);
  792. tor_inet_ntoa(&in, conn->socks_request->address,
  793. sizeof(conn->socks_request->address));
  794. control_event_stream_status(conn, STREAM_EVENT_REMAP,
  795. REMAP_STREAM_SOURCE_EXIT);
  796. }
  797. /** An incoming relay cell has arrived from circuit <b>circ</b> to
  798. * stream <b>conn</b>.
  799. *
  800. * The arguments here are the same as in
  801. * connection_edge_process_relay_cell() below; this function is called
  802. * from there when <b>conn</b> is defined and not in an open state.
  803. */
  804. static int
  805. connection_edge_process_relay_cell_not_open(
  806. relay_header_t *rh, cell_t *cell, circuit_t *circ,
  807. edge_connection_t *conn, crypt_path_t *layer_hint)
  808. {
  809. if (rh->command == RELAY_COMMAND_END) {
  810. if (CIRCUIT_IS_ORIGIN(circ))
  811. return connection_edge_process_end_not_open(rh, cell,
  812. TO_ORIGIN_CIRCUIT(circ), conn,
  813. layer_hint);
  814. else
  815. return 0;
  816. }
  817. if (conn->_base.type == CONN_TYPE_AP &&
  818. rh->command == RELAY_COMMAND_CONNECTED) {
  819. tor_assert(CIRCUIT_IS_ORIGIN(circ));
  820. if (conn->_base.state != AP_CONN_STATE_CONNECT_WAIT) {
  821. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  822. "Got 'connected' while not in state connect_wait. Dropping.");
  823. return 0;
  824. }
  825. conn->_base.state = AP_CONN_STATE_OPEN;
  826. log_info(LD_APP,"'connected' received after %d seconds.",
  827. (int)(time(NULL) - conn->_base.timestamp_lastread));
  828. if (rh->length >= 4) {
  829. uint32_t addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE));
  830. int ttl;
  831. if (!addr || (get_options()->ClientDNSRejectInternalAddresses &&
  832. is_internal_IP(addr, 0))) {
  833. char buf[INET_NTOA_BUF_LEN];
  834. struct in_addr a;
  835. a.s_addr = htonl(addr);
  836. tor_inet_ntoa(&a, buf, sizeof(buf));
  837. log_info(LD_APP,
  838. "...but it claims the IP address was %s. Closing.", buf);
  839. connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
  840. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  841. return 0;
  842. }
  843. if (rh->length >= 8)
  844. ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+4));
  845. else
  846. ttl = -1;
  847. client_dns_set_addressmap(conn->socks_request->address, addr,
  848. conn->chosen_exit_name, ttl);
  849. remap_event_helper(conn, addr);
  850. }
  851. circuit_log_path(LOG_INFO,LD_APP,TO_ORIGIN_CIRCUIT(circ));
  852. /* don't send a socks reply to transparent conns */
  853. if (!conn->socks_request->has_finished)
  854. connection_ap_handshake_socks_reply(conn, NULL, 0, 0);
  855. /* handle anything that might have queued */
  856. if (connection_edge_package_raw_inbuf(conn, 1) < 0) {
  857. /* (We already sent an end cell if possible) */
  858. connection_mark_for_close(TO_CONN(conn));
  859. return 0;
  860. }
  861. return 0;
  862. }
  863. if (conn->_base.type == CONN_TYPE_AP &&
  864. rh->command == RELAY_COMMAND_RESOLVED) {
  865. int ttl;
  866. int answer_len;
  867. uint8_t answer_type;
  868. if (conn->_base.state != AP_CONN_STATE_RESOLVE_WAIT) {
  869. log_fn(LOG_PROTOCOL_WARN, LD_APP, "Got a 'resolved' cell while "
  870. "not in state resolve_wait. Dropping.");
  871. return 0;
  872. }
  873. tor_assert(SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command));
  874. answer_len = cell->payload[RELAY_HEADER_SIZE+1];
  875. if (rh->length < 2 || answer_len+2>rh->length) {
  876. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  877. "Dropping malformed 'resolved' cell");
  878. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  879. return 0;
  880. }
  881. answer_type = cell->payload[RELAY_HEADER_SIZE];
  882. if (rh->length >= answer_len+6)
  883. ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+
  884. 2+answer_len));
  885. else
  886. ttl = -1;
  887. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len >= 4) {
  888. uint32_t addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+2));
  889. if (get_options()->ClientDNSRejectInternalAddresses &&
  890. is_internal_IP(addr, 0)) {
  891. char buf[INET_NTOA_BUF_LEN];
  892. struct in_addr a;
  893. a.s_addr = htonl(addr);
  894. tor_inet_ntoa(&a, buf, sizeof(buf));
  895. log_info(LD_APP,"Got a resolve with answer %s. Rejecting.", buf);
  896. connection_ap_handshake_socks_resolved(conn,
  897. RESOLVED_TYPE_ERROR_TRANSIENT,
  898. 0, NULL, 0, TIME_MAX);
  899. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  900. return 0;
  901. }
  902. }
  903. connection_ap_handshake_socks_resolved(conn,
  904. answer_type,
  905. cell->payload[RELAY_HEADER_SIZE+1], /*answer_len*/
  906. cell->payload+RELAY_HEADER_SIZE+2, /*answer*/
  907. ttl,
  908. -1);
  909. if (answer_type == RESOLVED_TYPE_IPV4) {
  910. uint32_t addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+2));
  911. remap_event_helper(conn, addr);
  912. }
  913. connection_mark_unattached_ap(conn,
  914. END_STREAM_REASON_DONE |
  915. END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
  916. return 0;
  917. }
  918. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  919. "Got an unexpected relay command %d, in state %d (%s). Dropping.",
  920. rh->command, conn->_base.state,
  921. conn_state_to_string(conn->_base.type, conn->_base.state));
  922. return 0; /* for forward compatibility, don't kill the circuit */
  923. // connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
  924. // connection_mark_for_close(conn);
  925. // return -1;
  926. }
  927. /** An incoming relay cell has arrived on circuit <b>circ</b>. If
  928. * <b>conn</b> is NULL this is a control cell, else <b>cell</b> is
  929. * destined for <b>conn</b>.
  930. *
  931. * If <b>layer_hint</b> is defined, then we're the origin of the
  932. * circuit, and it specifies the hop that packaged <b>cell</b>.
  933. *
  934. * Return -reason if you want to warn and tear down the circuit, else 0.
  935. */
  936. static int
  937. connection_edge_process_relay_cell(cell_t *cell, circuit_t *circ,
  938. edge_connection_t *conn,
  939. crypt_path_t *layer_hint)
  940. {
  941. static int num_seen=0;
  942. relay_header_t rh;
  943. unsigned domain = layer_hint?LD_APP:LD_EXIT;
  944. int reason;
  945. tor_assert(cell);
  946. tor_assert(circ);
  947. relay_header_unpack(&rh, cell->payload);
  948. // log_fn(LOG_DEBUG,"command %d stream %d", rh.command, rh.stream_id);
  949. num_seen++;
  950. log_debug(domain, "Now seen %d relay cells here.", num_seen);
  951. if (rh.length > RELAY_PAYLOAD_SIZE) {
  952. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  953. "Relay cell length field too long. Closing circuit.");
  954. return - END_CIRC_REASON_TORPROTOCOL;
  955. }
  956. /* either conn is NULL, in which case we've got a control cell, or else
  957. * conn points to the recognized stream. */
  958. if (conn && !connection_state_is_open(TO_CONN(conn)))
  959. return connection_edge_process_relay_cell_not_open(
  960. &rh, cell, circ, conn, layer_hint);
  961. switch (rh.command) {
  962. case RELAY_COMMAND_DROP:
  963. // log_info(domain,"Got a relay-level padding cell. Dropping.");
  964. return 0;
  965. case RELAY_COMMAND_BEGIN:
  966. case RELAY_COMMAND_BEGIN_DIR:
  967. if (layer_hint &&
  968. circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
  969. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  970. "Relay begin request unsupported at AP. Dropping.");
  971. return 0;
  972. }
  973. if (conn) {
  974. log_fn(LOG_PROTOCOL_WARN, domain,
  975. "Begin cell for known stream. Dropping.");
  976. return 0;
  977. }
  978. return connection_exit_begin_conn(cell, circ);
  979. case RELAY_COMMAND_DATA:
  980. ++stats_n_data_cells_received;
  981. if (( layer_hint && --layer_hint->deliver_window < 0) ||
  982. (!layer_hint && --circ->deliver_window < 0)) {
  983. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  984. "(relay data) circ deliver_window below 0. Killing.");
  985. connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
  986. connection_mark_for_close(TO_CONN(conn));
  987. return -END_CIRC_REASON_TORPROTOCOL;
  988. }
  989. log_debug(domain,"circ deliver_window now %d.", layer_hint ?
  990. layer_hint->deliver_window : circ->deliver_window);
  991. circuit_consider_sending_sendme(circ, layer_hint);
  992. if (!conn) {
  993. log_info(domain,"data cell dropped, unknown stream.");
  994. return 0;
  995. }
  996. if (--conn->deliver_window < 0) { /* is it below 0 after decrement? */
  997. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  998. "(relay data) conn deliver_window below 0. Killing.");
  999. return -END_CIRC_REASON_TORPROTOCOL;
  1000. }
  1001. stats_n_data_bytes_received += rh.length;
  1002. connection_write_to_buf(cell->payload + RELAY_HEADER_SIZE,
  1003. rh.length, TO_CONN(conn));
  1004. connection_edge_consider_sending_sendme(conn);
  1005. return 0;
  1006. case RELAY_COMMAND_END:
  1007. reason = rh.length > 0 ?
  1008. *(uint8_t *)(cell->payload+RELAY_HEADER_SIZE) : END_STREAM_REASON_MISC;
  1009. if (!conn) {
  1010. log_info(domain,"end cell (%s) dropped, unknown stream.",
  1011. connection_edge_end_reason_str(reason));
  1012. return 0;
  1013. }
  1014. /* XXX add to this log_fn the exit node's nickname? */
  1015. log_info(domain,"%d: end cell (%s) for stream %d. Removing stream.",
  1016. conn->_base.s,
  1017. connection_edge_end_reason_str(reason),
  1018. conn->stream_id);
  1019. if (conn->socks_request && !conn->socks_request->has_finished)
  1020. log_warn(LD_BUG,
  1021. "open stream hasn't sent socks answer yet? Closing.");
  1022. /* We just *got* an end; no reason to send one. */
  1023. conn->_base.edge_has_sent_end = 1;
  1024. if (!conn->end_reason)
  1025. conn->end_reason = reason | END_STREAM_REASON_FLAG_REMOTE;
  1026. if (!conn->_base.marked_for_close) {
  1027. /* only mark it if not already marked. it's possible to
  1028. * get the 'end' right around when the client hangs up on us. */
  1029. connection_mark_for_close(TO_CONN(conn));
  1030. conn->_base.hold_open_until_flushed = 1;
  1031. }
  1032. return 0;
  1033. case RELAY_COMMAND_EXTEND:
  1034. if (conn) {
  1035. log_fn(LOG_PROTOCOL_WARN, domain,
  1036. "'extend' cell received for non-zero stream. Dropping.");
  1037. return 0;
  1038. }
  1039. return circuit_extend(cell, circ);
  1040. case RELAY_COMMAND_EXTENDED:
  1041. if (!layer_hint) {
  1042. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1043. "'extended' unsupported at non-origin. Dropping.");
  1044. return 0;
  1045. }
  1046. log_debug(domain,"Got an extended cell! Yay.");
  1047. if ((reason = circuit_finish_handshake(TO_ORIGIN_CIRCUIT(circ),
  1048. CELL_CREATED,
  1049. cell->payload+RELAY_HEADER_SIZE)) < 0) {
  1050. log_warn(domain,"circuit_finish_handshake failed.");
  1051. return reason;
  1052. }
  1053. if ((reason=circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ)))<0) {
  1054. log_info(domain,"circuit_send_next_onion_skin() failed.");
  1055. return reason;
  1056. }
  1057. return 0;
  1058. case RELAY_COMMAND_TRUNCATE:
  1059. if (layer_hint) {
  1060. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  1061. "'truncate' unsupported at origin. Dropping.");
  1062. return 0;
  1063. }
  1064. if (circ->n_conn) {
  1065. uint8_t trunc_reason = *(uint8_t*)(cell->payload + RELAY_HEADER_SIZE);
  1066. connection_or_send_destroy(circ->n_circ_id, circ->n_conn,
  1067. trunc_reason);
  1068. circuit_set_n_circid_orconn(circ, 0, NULL);
  1069. }
  1070. log_debug(LD_EXIT, "Processed 'truncate', replying.");
  1071. {
  1072. char payload[1];
  1073. payload[0] = (char)END_CIRC_REASON_REQUESTED;
  1074. relay_send_command_from_edge(0, circ, RELAY_COMMAND_TRUNCATED,
  1075. payload, sizeof(payload), NULL);
  1076. }
  1077. return 0;
  1078. case RELAY_COMMAND_TRUNCATED:
  1079. if (!layer_hint) {
  1080. log_fn(LOG_PROTOCOL_WARN, LD_EXIT,
  1081. "'truncated' unsupported at non-origin. Dropping.");
  1082. return 0;
  1083. }
  1084. circuit_truncated(TO_ORIGIN_CIRCUIT(circ), layer_hint);
  1085. return 0;
  1086. case RELAY_COMMAND_CONNECTED:
  1087. if (conn) {
  1088. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1089. "'connected' unsupported while open. Closing circ.");
  1090. return -END_CIRC_REASON_TORPROTOCOL;
  1091. }
  1092. log_info(domain,
  1093. "'connected' received, no conn attached anymore. Ignoring.");
  1094. return 0;
  1095. case RELAY_COMMAND_SENDME:
  1096. if (!conn) {
  1097. if (layer_hint) {
  1098. layer_hint->package_window += CIRCWINDOW_INCREMENT;
  1099. log_debug(LD_APP,"circ-level sendme at origin, packagewindow %d.",
  1100. layer_hint->package_window);
  1101. circuit_resume_edge_reading(circ, layer_hint);
  1102. } else {
  1103. circ->package_window += CIRCWINDOW_INCREMENT;
  1104. log_debug(LD_APP,
  1105. "circ-level sendme at non-origin, packagewindow %d.",
  1106. circ->package_window);
  1107. circuit_resume_edge_reading(circ, layer_hint);
  1108. }
  1109. return 0;
  1110. }
  1111. conn->package_window += STREAMWINDOW_INCREMENT;
  1112. log_debug(domain,"stream-level sendme, packagewindow now %d.",
  1113. conn->package_window);
  1114. connection_start_reading(TO_CONN(conn));
  1115. /* handle whatever might still be on the inbuf */
  1116. if (connection_edge_package_raw_inbuf(conn, 1) < 0) {
  1117. /* (We already sent an end cell if possible) */
  1118. connection_mark_for_close(TO_CONN(conn));
  1119. return 0;
  1120. }
  1121. return 0;
  1122. case RELAY_COMMAND_RESOLVE:
  1123. if (layer_hint) {
  1124. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  1125. "resolve request unsupported at AP; dropping.");
  1126. return 0;
  1127. } else if (conn) {
  1128. log_fn(LOG_PROTOCOL_WARN, domain,
  1129. "resolve request for known stream; dropping.");
  1130. return 0;
  1131. } else if (circ->purpose != CIRCUIT_PURPOSE_OR) {
  1132. log_fn(LOG_PROTOCOL_WARN, domain,
  1133. "resolve request on circ with purpose %d; dropping",
  1134. circ->purpose);
  1135. return 0;
  1136. }
  1137. connection_exit_begin_resolve(cell, TO_OR_CIRCUIT(circ));
  1138. return 0;
  1139. case RELAY_COMMAND_RESOLVED:
  1140. if (conn) {
  1141. log_fn(LOG_PROTOCOL_WARN, domain,
  1142. "'resolved' unsupported while open. Closing circ.");
  1143. return -END_CIRC_REASON_TORPROTOCOL;
  1144. }
  1145. log_info(domain,
  1146. "'resolved' received, no conn attached anymore. Ignoring.");
  1147. return 0;
  1148. case RELAY_COMMAND_ESTABLISH_INTRO:
  1149. case RELAY_COMMAND_ESTABLISH_RENDEZVOUS:
  1150. case RELAY_COMMAND_INTRODUCE1:
  1151. case RELAY_COMMAND_INTRODUCE2:
  1152. case RELAY_COMMAND_INTRODUCE_ACK:
  1153. case RELAY_COMMAND_RENDEZVOUS1:
  1154. case RELAY_COMMAND_RENDEZVOUS2:
  1155. case RELAY_COMMAND_INTRO_ESTABLISHED:
  1156. case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
  1157. rend_process_relay_cell(circ, rh.command, rh.length,
  1158. cell->payload+RELAY_HEADER_SIZE);
  1159. return 0;
  1160. }
  1161. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1162. "Received unknown relay command %d. Perhaps the other side is using "
  1163. "a newer version of Tor? Dropping.",
  1164. rh.command);
  1165. return 0; /* for forward compatibility, don't kill the circuit */
  1166. }
  1167. uint64_t stats_n_data_cells_packaged = 0;
  1168. uint64_t stats_n_data_bytes_packaged = 0;
  1169. uint64_t stats_n_data_cells_received = 0;
  1170. uint64_t stats_n_data_bytes_received = 0;
  1171. /** While conn->inbuf has an entire relay payload of bytes on it,
  1172. * and the appropriate package windows aren't empty, grab a cell
  1173. * and send it down the circuit.
  1174. *
  1175. * Return -1 (and send a RELAY_END cell if necessary) if conn should
  1176. * be marked for close, else return 0.
  1177. */
  1178. int
  1179. connection_edge_package_raw_inbuf(edge_connection_t *conn, int package_partial)
  1180. {
  1181. size_t amount_to_process, length;
  1182. char payload[CELL_PAYLOAD_SIZE];
  1183. circuit_t *circ;
  1184. unsigned domain = conn->cpath_layer ? LD_APP : LD_EXIT;
  1185. tor_assert(conn);
  1186. if (conn->_base.marked_for_close) {
  1187. log_warn(LD_BUG,
  1188. "called on conn that's already marked for close at %s:%d.",
  1189. conn->_base.marked_for_close_file, conn->_base.marked_for_close);
  1190. return 0;
  1191. }
  1192. repeat_connection_edge_package_raw_inbuf:
  1193. circ = circuit_get_by_edge_conn(conn);
  1194. if (!circ) {
  1195. log_info(domain,"conn has no circuit! Closing.");
  1196. conn->end_reason = END_STREAM_REASON_CANT_ATTACH;
  1197. return -1;
  1198. }
  1199. if (circuit_consider_stop_edge_reading(circ, conn->cpath_layer))
  1200. return 0;
  1201. if (conn->package_window <= 0) {
  1202. log_info(domain,"called with package_window %d. Skipping.",
  1203. conn->package_window);
  1204. connection_stop_reading(TO_CONN(conn));
  1205. return 0;
  1206. }
  1207. amount_to_process = buf_datalen(conn->_base.inbuf);
  1208. if (!amount_to_process)
  1209. return 0;
  1210. if (!package_partial && amount_to_process < RELAY_PAYLOAD_SIZE)
  1211. return 0;
  1212. if (amount_to_process > RELAY_PAYLOAD_SIZE) {
  1213. length = RELAY_PAYLOAD_SIZE;
  1214. } else {
  1215. length = amount_to_process;
  1216. }
  1217. stats_n_data_bytes_packaged += length;
  1218. stats_n_data_cells_packaged += 1;
  1219. connection_fetch_from_buf(payload, length, TO_CONN(conn));
  1220. log_debug(domain,"(%d) Packaging %d bytes (%d waiting).", conn->_base.s,
  1221. (int)length, (int)buf_datalen(conn->_base.inbuf));
  1222. if (connection_edge_send_command(conn, RELAY_COMMAND_DATA,
  1223. payload, length) < 0 )
  1224. /* circuit got marked for close, don't continue, don't need to mark conn */
  1225. return 0;
  1226. if (!conn->cpath_layer) { /* non-rendezvous exit */
  1227. tor_assert(circ->package_window > 0);
  1228. circ->package_window--;
  1229. } else { /* we're an AP, or an exit on a rendezvous circ */
  1230. tor_assert(conn->cpath_layer->package_window > 0);
  1231. conn->cpath_layer->package_window--;
  1232. }
  1233. if (--conn->package_window <= 0) { /* is it 0 after decrement? */
  1234. connection_stop_reading(TO_CONN(conn));
  1235. log_debug(domain,"conn->package_window reached 0.");
  1236. circuit_consider_stop_edge_reading(circ, conn->cpath_layer);
  1237. return 0; /* don't process the inbuf any more */
  1238. }
  1239. log_debug(domain,"conn->package_window is now %d",conn->package_window);
  1240. /* handle more if there's more, or return 0 if there isn't */
  1241. goto repeat_connection_edge_package_raw_inbuf;
  1242. }
  1243. /** Called when we've just received a relay data cell, or when
  1244. * we've just finished flushing all bytes to stream <b>conn</b>.
  1245. *
  1246. * If conn->outbuf is not too full, and our deliver window is
  1247. * low, send back a suitable number of stream-level sendme cells.
  1248. */
  1249. void
  1250. connection_edge_consider_sending_sendme(edge_connection_t *conn)
  1251. {
  1252. circuit_t *circ;
  1253. if (connection_outbuf_too_full(TO_CONN(conn)))
  1254. return;
  1255. circ = circuit_get_by_edge_conn(conn);
  1256. if (!circ) {
  1257. /* this can legitimately happen if the destroy has already
  1258. * arrived and torn down the circuit */
  1259. log_info(LD_APP,"No circuit associated with conn. Skipping.");
  1260. return;
  1261. }
  1262. while (conn->deliver_window < STREAMWINDOW_START - STREAMWINDOW_INCREMENT) {
  1263. log_debug(conn->cpath_layer?LD_APP:LD_EXIT,
  1264. "Outbuf %d, Queueing stream sendme.",
  1265. (int)conn->_base.outbuf_flushlen);
  1266. conn->deliver_window += STREAMWINDOW_INCREMENT;
  1267. if (connection_edge_send_command(conn, RELAY_COMMAND_SENDME,
  1268. NULL, 0) < 0) {
  1269. log_warn(LD_APP,"connection_edge_send_command failed. Skipping.");
  1270. return; /* the circuit's closed, don't continue */
  1271. }
  1272. }
  1273. }
  1274. /** The circuit <b>circ</b> has received a circuit-level sendme
  1275. * (on hop <b>layer_hint</b>, if we're the OP). Go through all the
  1276. * attached streams and let them resume reading and packaging, if
  1277. * their stream windows allow it.
  1278. */
  1279. static void
  1280. circuit_resume_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
  1281. {
  1282. log_debug(layer_hint?LD_APP:LD_EXIT,"resuming");
  1283. if (CIRCUIT_IS_ORIGIN(circ))
  1284. circuit_resume_edge_reading_helper(TO_ORIGIN_CIRCUIT(circ)->p_streams,
  1285. circ, layer_hint);
  1286. else
  1287. circuit_resume_edge_reading_helper(TO_OR_CIRCUIT(circ)->n_streams,
  1288. circ, layer_hint);
  1289. }
  1290. /** A helper function for circuit_resume_edge_reading() above.
  1291. * The arguments are the same, except that <b>conn</b> is the head
  1292. * of a linked list of edge streams that should each be considered.
  1293. */
  1294. static int
  1295. circuit_resume_edge_reading_helper(edge_connection_t *conn,
  1296. circuit_t *circ,
  1297. crypt_path_t *layer_hint)
  1298. {
  1299. for ( ; conn; conn=conn->next_stream) {
  1300. if (conn->_base.marked_for_close)
  1301. continue;
  1302. if ((!layer_hint && conn->package_window > 0) ||
  1303. (layer_hint && conn->package_window > 0 &&
  1304. conn->cpath_layer == layer_hint)) {
  1305. connection_start_reading(TO_CONN(conn));
  1306. /* handle whatever might still be on the inbuf */
  1307. if (connection_edge_package_raw_inbuf(conn, 1)<0) {
  1308. /* (We already sent an end cell if possible) */
  1309. connection_mark_for_close(TO_CONN(conn));
  1310. continue;
  1311. }
  1312. /* If the circuit won't accept any more data, return without looking
  1313. * at any more of the streams. Any connections that should be stopped
  1314. * have already been stopped by connection_edge_package_raw_inbuf. */
  1315. if (circuit_consider_stop_edge_reading(circ, layer_hint))
  1316. return -1;
  1317. }
  1318. }
  1319. return 0;
  1320. }
  1321. /** Check if the package window for <b>circ</b> is empty (at
  1322. * hop <b>layer_hint</b> if it's defined).
  1323. *
  1324. * If yes, tell edge streams to stop reading and return 1.
  1325. * Else return 0.
  1326. */
  1327. static int
  1328. circuit_consider_stop_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
  1329. {
  1330. edge_connection_t *conn = NULL;
  1331. unsigned domain = layer_hint ? LD_APP : LD_EXIT;
  1332. if (!layer_hint) {
  1333. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  1334. log_debug(domain,"considering circ->package_window %d",
  1335. circ->package_window);
  1336. if (circ->package_window <= 0) {
  1337. log_debug(domain,"yes, not-at-origin. stopped.");
  1338. for (conn = or_circ->n_streams; conn; conn=conn->next_stream)
  1339. connection_stop_reading(TO_CONN(conn));
  1340. return 1;
  1341. }
  1342. return 0;
  1343. }
  1344. /* else, layer hint is defined, use it */
  1345. log_debug(domain,"considering layer_hint->package_window %d",
  1346. layer_hint->package_window);
  1347. if (layer_hint->package_window <= 0) {
  1348. log_debug(domain,"yes, at-origin. stopped.");
  1349. for (conn = TO_ORIGIN_CIRCUIT(circ)->p_streams; conn;
  1350. conn=conn->next_stream)
  1351. if (conn->cpath_layer == layer_hint)
  1352. connection_stop_reading(TO_CONN(conn));
  1353. return 1;
  1354. }
  1355. return 0;
  1356. }
  1357. /** Check if the deliver_window for circuit <b>circ</b> (at hop
  1358. * <b>layer_hint</b> if it's defined) is low enough that we should
  1359. * send a circuit-level sendme back down the circuit. If so, send
  1360. * enough sendmes that the window would be overfull if we sent any
  1361. * more.
  1362. */
  1363. static void
  1364. circuit_consider_sending_sendme(circuit_t *circ, crypt_path_t *layer_hint)
  1365. {
  1366. // log_fn(LOG_INFO,"Considering: layer_hint is %s",
  1367. // layer_hint ? "defined" : "null");
  1368. while ((layer_hint ? layer_hint->deliver_window : circ->deliver_window) <
  1369. CIRCWINDOW_START - CIRCWINDOW_INCREMENT) {
  1370. log_debug(LD_CIRC,"Queueing circuit sendme.");
  1371. if (layer_hint)
  1372. layer_hint->deliver_window += CIRCWINDOW_INCREMENT;
  1373. else
  1374. circ->deliver_window += CIRCWINDOW_INCREMENT;
  1375. if (relay_send_command_from_edge(0, circ, RELAY_COMMAND_SENDME,
  1376. NULL, 0, layer_hint) < 0) {
  1377. log_warn(LD_CIRC,
  1378. "connection_edge_send_command failed. Circuit's closed.");
  1379. return; /* the circuit's closed, don't continue */
  1380. }
  1381. }
  1382. }
  1383. /** Stop reading on edge connections when we have this many cells
  1384. * waiting on the appropriate queue. */
  1385. #define CELL_QUEUE_HIGHWATER_SIZE 256
  1386. /** Start reading from edge connections again when we get down to this many
  1387. * cells. */
  1388. #define CELL_QUEUE_LOWWATER_SIZE 64
  1389. #ifdef ACTIVE_CIRCUITS_PARANOIA
  1390. #define assert_active_circuits_ok_paranoid(conn) \
  1391. assert_active_circuits_ok(conn)
  1392. #else
  1393. #define assert_active_circuits_ok_paranoid(conn)
  1394. #endif
  1395. /** The total number of cells we have allocated from the memory pool. */
  1396. static int total_cells_allocated = 0;
  1397. #ifdef ENABLE_CELL_POOL /* Defined in ./configure. True by default. */
  1398. /* XXX020 make cell pools the only option once we know they work and improve
  1399. * matters? -RD */
  1400. static mp_pool_t *cell_pool = NULL;
  1401. /** Allocate structures to hold cells. */
  1402. void
  1403. init_cell_pool(void)
  1404. {
  1405. tor_assert(!cell_pool);
  1406. cell_pool = mp_pool_new(sizeof(packed_cell_t), 1<<19);
  1407. }
  1408. /** Free all storage used to hold cells. */
  1409. void
  1410. free_cell_pool(void)
  1411. {
  1412. /* Maybe we haven't called init_cell_pool yet; need to check for it. */
  1413. if (cell_pool) {
  1414. mp_pool_destroy(cell_pool);
  1415. cell_pool = NULL;
  1416. }
  1417. }
  1418. /** Free excess storage in cell pool. */
  1419. void
  1420. clean_cell_pool(void)
  1421. {
  1422. tor_assert(cell_pool);
  1423. mp_pool_clean(cell_pool, -1);
  1424. }
  1425. /** Release storage held by <b>cell</b>. */
  1426. static INLINE void
  1427. packed_cell_free(packed_cell_t *cell)
  1428. {
  1429. --total_cells_allocated;
  1430. mp_pool_release(cell);
  1431. }
  1432. /** Allocate and return a new packed_cell_t. */
  1433. static INLINE packed_cell_t *
  1434. packed_cell_alloc(void)
  1435. {
  1436. ++total_cells_allocated;
  1437. return mp_pool_get(cell_pool);
  1438. }
  1439. void
  1440. dump_cell_pool_usage(int severity)
  1441. {
  1442. circuit_t *c;
  1443. int n_circs = 0;
  1444. int n_cells = 0;
  1445. for (c = _circuit_get_global_list(); c; c = c->next) {
  1446. n_cells += c->n_conn_cells.n;
  1447. if (!CIRCUIT_IS_ORIGIN(c))
  1448. n_cells += TO_OR_CIRCUIT(c)->p_conn_cells.n;
  1449. ++n_circs;
  1450. }
  1451. log(severity, LD_MM, "%d cells allocated on %d circuits. %d cells leaked.",
  1452. n_cells, n_circs, total_cells_allocated - n_cells);
  1453. mp_pool_log_status(cell_pool, severity);
  1454. }
  1455. #else
  1456. /* ENABLE_CELL_POOL isn't defined: here are some stubs to use tor_malloc()
  1457. * and tor_free() instead. */
  1458. void
  1459. init_cell_pool(void)
  1460. {
  1461. }
  1462. void
  1463. free_cell_pool(void)
  1464. {
  1465. }
  1466. void
  1467. clean_cell_pool(void)
  1468. {
  1469. }
  1470. static INLINE void
  1471. packed_cell_free(packed_cell_t *cell)
  1472. {
  1473. --total_cells_allocated;
  1474. tor_free(cell);
  1475. }
  1476. static INLINE packed_cell_t *
  1477. packed_cell_alloc(void)
  1478. {
  1479. ++total_cells_allocated;
  1480. return tor_malloc(sizeof(packed_cell_t));
  1481. }
  1482. void
  1483. dump_cell_pool_usage(int severity)
  1484. {
  1485. (void) severity;
  1486. }
  1487. #endif
  1488. /** Allocate a new copy of packed <b>cell</b>. */
  1489. static INLINE packed_cell_t *
  1490. packed_cell_copy(const cell_t *cell)
  1491. {
  1492. packed_cell_t *c = packed_cell_alloc();
  1493. cell_pack(c, cell);
  1494. c->next = NULL;
  1495. return c;
  1496. }
  1497. /** Append <b>cell</b> to the end of <b>queue</b>. */
  1498. void
  1499. cell_queue_append(cell_queue_t *queue, packed_cell_t *cell)
  1500. {
  1501. if (queue->tail) {
  1502. tor_assert(!queue->tail->next);
  1503. queue->tail->next = cell;
  1504. } else {
  1505. queue->head = cell;
  1506. }
  1507. queue->tail = cell;
  1508. cell->next = NULL;
  1509. ++queue->n;
  1510. }
  1511. /** Append a newly allocated copy of <b>cell</b> to the end of <b>queue</b> */
  1512. void
  1513. cell_queue_append_packed_copy(cell_queue_t *queue, const cell_t *cell)
  1514. {
  1515. cell_queue_append(queue, packed_cell_copy(cell));
  1516. }
  1517. /** Remove and free every cell in <b>queue</b>. */
  1518. void
  1519. cell_queue_clear(cell_queue_t *queue)
  1520. {
  1521. packed_cell_t *cell, *next;
  1522. cell = queue->head;
  1523. while (cell) {
  1524. next = cell->next;
  1525. packed_cell_free(cell);
  1526. cell = next;
  1527. }
  1528. queue->head = queue->tail = NULL;
  1529. queue->n = 0;
  1530. }
  1531. /** Extract and return the cell at the head of <b>queue</b>; return NULL if
  1532. * <b>queue</b> is empty. */
  1533. static INLINE packed_cell_t *
  1534. cell_queue_pop(cell_queue_t *queue)
  1535. {
  1536. packed_cell_t *cell = queue->head;
  1537. if (!cell)
  1538. return NULL;
  1539. queue->head = cell->next;
  1540. if (cell == queue->tail) {
  1541. tor_assert(!queue->head);
  1542. queue->tail = NULL;
  1543. }
  1544. --queue->n;
  1545. return cell;
  1546. }
  1547. /** Return a pointer to the "next_active_on_{n,p}_conn" pointer of <b>circ</b>,
  1548. * depending on whether <b>conn</b> matches n_conn or p_conn. */
  1549. static INLINE circuit_t **
  1550. next_circ_on_conn_p(circuit_t *circ, or_connection_t *conn)
  1551. {
  1552. tor_assert(circ);
  1553. tor_assert(conn);
  1554. if (conn == circ->n_conn) {
  1555. return &circ->next_active_on_n_conn;
  1556. } else {
  1557. or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
  1558. tor_assert(conn == orcirc->p_conn);
  1559. return &orcirc->next_active_on_p_conn;
  1560. }
  1561. }
  1562. /** Return a pointer to the "prev_active_on_{n,p}_conn" pointer of <b>circ</b>,
  1563. * depending on whether <b>conn</b> matches n_conn or p_conn. */
  1564. static INLINE circuit_t **
  1565. prev_circ_on_conn_p(circuit_t *circ, or_connection_t *conn)
  1566. {
  1567. tor_assert(circ);
  1568. tor_assert(conn);
  1569. if (conn == circ->n_conn) {
  1570. return &circ->prev_active_on_n_conn;
  1571. } else {
  1572. or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
  1573. tor_assert(conn == orcirc->p_conn);
  1574. return &orcirc->prev_active_on_p_conn;
  1575. }
  1576. }
  1577. /** Add <b>circ</b> to the list of circuits with pending cells on
  1578. * <b>conn</b>. No effect if <b>circ</b> is already unlinked. */
  1579. void
  1580. make_circuit_active_on_conn(circuit_t *circ, or_connection_t *conn)
  1581. {
  1582. circuit_t **nextp = next_circ_on_conn_p(circ, conn);
  1583. circuit_t **prevp = prev_circ_on_conn_p(circ, conn);
  1584. if (*nextp && *prevp) {
  1585. /* Already active. */
  1586. return;
  1587. }
  1588. if (! conn->active_circuits) {
  1589. conn->active_circuits = circ;
  1590. *prevp = *nextp = circ;
  1591. } else {
  1592. circuit_t *head = conn->active_circuits;
  1593. circuit_t *old_tail = *prev_circ_on_conn_p(head, conn);
  1594. *next_circ_on_conn_p(old_tail, conn) = circ;
  1595. *nextp = head;
  1596. *prev_circ_on_conn_p(head, conn) = circ;
  1597. *prevp = old_tail;
  1598. }
  1599. assert_active_circuits_ok_paranoid(conn);
  1600. }
  1601. /** Remove <b>circ</b> to the list of circuits with pending cells on
  1602. * <b>conn</b>. No effect if <b>circ</b> is already unlinked. */
  1603. void
  1604. make_circuit_inactive_on_conn(circuit_t *circ, or_connection_t *conn)
  1605. {
  1606. circuit_t **nextp = next_circ_on_conn_p(circ, conn);
  1607. circuit_t **prevp = prev_circ_on_conn_p(circ, conn);
  1608. circuit_t *next = *nextp, *prev = *prevp;
  1609. if (!next && !prev) {
  1610. /* Already inactive. */
  1611. return;
  1612. }
  1613. tor_assert(next && prev);
  1614. tor_assert(*prev_circ_on_conn_p(next, conn) == circ);
  1615. tor_assert(*next_circ_on_conn_p(prev, conn) == circ);
  1616. if (next == circ) {
  1617. conn->active_circuits = NULL;
  1618. } else {
  1619. *prev_circ_on_conn_p(next, conn) = prev;
  1620. *next_circ_on_conn_p(prev, conn) = next;
  1621. if (conn->active_circuits == circ)
  1622. conn->active_circuits = next;
  1623. }
  1624. *prevp = *nextp = NULL;
  1625. assert_active_circuits_ok_paranoid(conn);
  1626. }
  1627. /** Remove all circuits from the list of circuits with pending cells on
  1628. * <b>conn</b>. */
  1629. void
  1630. connection_or_unlink_all_active_circs(or_connection_t *orconn)
  1631. {
  1632. circuit_t *head = orconn->active_circuits;
  1633. circuit_t *cur = head;
  1634. if (! head)
  1635. return;
  1636. do {
  1637. circuit_t *next = *next_circ_on_conn_p(cur, orconn);
  1638. *prev_circ_on_conn_p(cur, orconn) = NULL;
  1639. *next_circ_on_conn_p(cur, orconn) = NULL;
  1640. cur = next;
  1641. } while (cur != head);
  1642. orconn->active_circuits = NULL;
  1643. }
  1644. /** Block (if <b>block</b> is true) or unblock (if <b>block</b> is false)
  1645. * every edge connection that is using <b>circ</b> to write to <b>orconn</b>,
  1646. * and start or stop reading as appropriate. */
  1647. static void
  1648. set_streams_blocked_on_circ(circuit_t *circ, or_connection_t *orconn,
  1649. int block)
  1650. {
  1651. edge_connection_t *edge = NULL;
  1652. if (circ->n_conn == orconn) {
  1653. circ->streams_blocked_on_n_conn = block;
  1654. if (CIRCUIT_IS_ORIGIN(circ))
  1655. edge = TO_ORIGIN_CIRCUIT(circ)->p_streams;
  1656. } else {
  1657. circ->streams_blocked_on_p_conn = block;
  1658. tor_assert(!CIRCUIT_IS_ORIGIN(circ));
  1659. edge = TO_OR_CIRCUIT(circ)->n_streams;
  1660. }
  1661. for (; edge; edge = edge->next_stream) {
  1662. connection_t *conn = TO_CONN(edge);
  1663. conn->edge_blocked_on_circ = block;
  1664. if (block) {
  1665. if (connection_is_reading(conn))
  1666. connection_stop_reading(conn);
  1667. } else {
  1668. /* Is this right? */
  1669. if (!connection_is_reading(conn))
  1670. connection_start_reading(conn);
  1671. }
  1672. }
  1673. }
  1674. /** Pull as many cells as possible (but no more than <b>max</b>) from the
  1675. * queue of the first active circuit on <b>conn</b>, and write then to
  1676. * <b>conn</b>-&gt;outbuf. Return the number of cells written. Advance
  1677. * the active circuit pointer to the next active circuit in the ring. */
  1678. int
  1679. connection_or_flush_from_first_active_circuit(or_connection_t *conn, int max)
  1680. {
  1681. int n_flushed;
  1682. cell_queue_t *queue;
  1683. circuit_t *circ;
  1684. int streams_blocked;
  1685. circ = conn->active_circuits;
  1686. if (!circ) return 0;
  1687. assert_active_circuits_ok_paranoid(conn);
  1688. if (circ->n_conn == conn) {
  1689. queue = &circ->n_conn_cells;
  1690. streams_blocked = circ->streams_blocked_on_n_conn;
  1691. } else {
  1692. queue = &TO_OR_CIRCUIT(circ)->p_conn_cells;
  1693. streams_blocked = circ->streams_blocked_on_p_conn;
  1694. }
  1695. tor_assert(*next_circ_on_conn_p(circ,conn));
  1696. for (n_flushed = 0; n_flushed < max && queue->head; ) {
  1697. packed_cell_t *cell = cell_queue_pop(queue);
  1698. tor_assert(*next_circ_on_conn_p(circ,conn));
  1699. connection_write_to_buf(cell->body, CELL_NETWORK_SIZE, TO_CONN(conn));
  1700. packed_cell_free(cell);
  1701. ++n_flushed;
  1702. if (circ != conn->active_circuits) {
  1703. /* If this happens, the current circuit just got made inactive by
  1704. * a call in connection_write_to_buf(). That's nothing to worry about:
  1705. * circuit_make_inactive_on_conn() already advanced conn->active_circuits
  1706. * for us.
  1707. */
  1708. assert_active_circuits_ok_paranoid(conn);
  1709. return n_flushed;
  1710. }
  1711. }
  1712. tor_assert(*next_circ_on_conn_p(circ,conn));
  1713. assert_active_circuits_ok_paranoid(conn);
  1714. conn->active_circuits = *next_circ_on_conn_p(circ, conn);
  1715. /* Is the cell queue low enough to unblock all the streams that are waiting
  1716. * to write to this circuit? */
  1717. if (streams_blocked && queue->n <= CELL_QUEUE_LOWWATER_SIZE)
  1718. set_streams_blocked_on_circ(circ, conn, 0); /* unblock streams */
  1719. /* Did we just ran out of cells on this queue? */
  1720. if (queue->n == 0) {
  1721. log_debug(LD_GENERAL, "Made a circuit inactive.");
  1722. make_circuit_inactive_on_conn(circ, conn);
  1723. }
  1724. return n_flushed;
  1725. }
  1726. /** Add <b>cell</b> to the queue of <b>circ</b> writing to <b>orconn</b>
  1727. * transmitting in <b>direction</b>. */
  1728. void
  1729. append_cell_to_circuit_queue(circuit_t *circ, or_connection_t *orconn,
  1730. cell_t *cell, int direction)
  1731. {
  1732. cell_queue_t *queue;
  1733. int streams_blocked;
  1734. if (direction == CELL_DIRECTION_OUT) {
  1735. queue = &circ->n_conn_cells;
  1736. streams_blocked = circ->streams_blocked_on_n_conn;
  1737. } else {
  1738. or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
  1739. queue = &orcirc->p_conn_cells;
  1740. streams_blocked = circ->streams_blocked_on_p_conn;
  1741. }
  1742. if (cell->command == CELL_RELAY_EARLY && orconn->link_proto < 2) {
  1743. /* V1 connections don't understand RELAY_EARLY. */
  1744. cell->command = CELL_RELAY;
  1745. }
  1746. cell_queue_append_packed_copy(queue, cell);
  1747. /* If we have too many cells on the circuit, we should stop reading from
  1748. * the edge streams for a while. */
  1749. if (!streams_blocked && queue->n >= CELL_QUEUE_HIGHWATER_SIZE)
  1750. set_streams_blocked_on_circ(circ, orconn, 1); /* block streams */
  1751. if (queue->n == 1) {
  1752. /* This was the first cell added to the queue. We need to make this
  1753. * circuit active. */
  1754. log_debug(LD_GENERAL, "Made a circuit active.");
  1755. make_circuit_active_on_conn(circ, orconn);
  1756. }
  1757. if (! buf_datalen(orconn->_base.outbuf)) {
  1758. /* There is no data at all waiting to be sent on the outbuf. Add a
  1759. * cell, so that we can notice when it gets flushed, flushed_some can
  1760. * get called, and we can start putting more data onto the buffer then.
  1761. */
  1762. log_debug(LD_GENERAL, "Primed a buffer.");
  1763. connection_or_flush_from_first_active_circuit(orconn, 1);
  1764. }
  1765. }
  1766. /** Fail with an assert if the active circuits ring on <b>orconn</b> is
  1767. * corrupt. */
  1768. void
  1769. assert_active_circuits_ok(or_connection_t *orconn)
  1770. {
  1771. circuit_t *head = orconn->active_circuits;
  1772. circuit_t *cur = head;
  1773. if (! head)
  1774. return;
  1775. do {
  1776. circuit_t *next = *next_circ_on_conn_p(cur, orconn);
  1777. circuit_t *prev = *prev_circ_on_conn_p(cur, orconn);
  1778. tor_assert(next);
  1779. tor_assert(prev);
  1780. tor_assert(*next_circ_on_conn_p(prev, orconn) == cur);
  1781. tor_assert(*prev_circ_on_conn_p(next, orconn) == cur);
  1782. cur = next;
  1783. } while (cur != head);
  1784. }