relay.c 65 KB

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