relay.c 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364
  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-2012, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file relay.c
  8. * \brief Handle relay cell encryption/decryption, plus packaging and
  9. * receiving from circuits, plus queuing on circuits.
  10. **/
  11. #define RELAY_PRIVATE
  12. #include "or.h"
  13. #include "buffers.h"
  14. #include "channel.h"
  15. #include "circuitbuild.h"
  16. #include "circuitlist.h"
  17. #include "config.h"
  18. #include "connection.h"
  19. #include "connection_edge.h"
  20. #include "connection_or.h"
  21. #include "control.h"
  22. #include "geoip.h"
  23. #include "main.h"
  24. #include "mempool.h"
  25. #include "networkstatus.h"
  26. #include "nodelist.h"
  27. #include "policies.h"
  28. #include "reasons.h"
  29. #include "relay.h"
  30. #include "rendcommon.h"
  31. #include "router.h"
  32. #include "routerlist.h"
  33. #include "routerparse.h"
  34. static edge_connection_t *relay_lookup_conn(circuit_t *circ, cell_t *cell,
  35. cell_direction_t cell_direction,
  36. crypt_path_t *layer_hint);
  37. static int connection_edge_process_relay_cell(cell_t *cell, circuit_t *circ,
  38. edge_connection_t *conn,
  39. crypt_path_t *layer_hint);
  40. static void circuit_consider_sending_sendme(circuit_t *circ,
  41. crypt_path_t *layer_hint);
  42. static void circuit_resume_edge_reading(circuit_t *circ,
  43. crypt_path_t *layer_hint);
  44. static int circuit_resume_edge_reading_helper(edge_connection_t *conn,
  45. circuit_t *circ,
  46. crypt_path_t *layer_hint);
  47. static int circuit_consider_stop_edge_reading(circuit_t *circ,
  48. crypt_path_t *layer_hint);
  49. static int circuit_queue_streams_are_blocked(circuit_t *circ);
  50. /** Stop reading on edge connections when we have this many cells
  51. * waiting on the appropriate queue. */
  52. #define CELL_QUEUE_HIGHWATER_SIZE 256
  53. /** Start reading from edge connections again when we get down to this many
  54. * cells. */
  55. #define CELL_QUEUE_LOWWATER_SIZE 64
  56. /** Stats: how many relay cells have originated at this hop, or have
  57. * been relayed onward (not recognized at this hop)?
  58. */
  59. uint64_t stats_n_relay_cells_relayed = 0;
  60. /** Stats: how many relay cells have been delivered to streams at this
  61. * hop?
  62. */
  63. uint64_t stats_n_relay_cells_delivered = 0;
  64. /** Update digest from the payload of cell. Assign integrity part to
  65. * cell.
  66. */
  67. static void
  68. relay_set_digest(crypto_digest_t *digest, cell_t *cell)
  69. {
  70. char integrity[4];
  71. relay_header_t rh;
  72. crypto_digest_add_bytes(digest, (char*)cell->payload, CELL_PAYLOAD_SIZE);
  73. crypto_digest_get_digest(digest, integrity, 4);
  74. // log_fn(LOG_DEBUG,"Putting digest of %u %u %u %u into relay cell.",
  75. // integrity[0], integrity[1], integrity[2], integrity[3]);
  76. relay_header_unpack(&rh, cell->payload);
  77. memcpy(rh.integrity, integrity, 4);
  78. relay_header_pack(cell->payload, &rh);
  79. }
  80. /** Does the digest for this circuit indicate that this cell is for us?
  81. *
  82. * Update digest from the payload of cell (with the integrity part set
  83. * to 0). If the integrity part is valid, return 1, else restore digest
  84. * and cell to their original state and return 0.
  85. */
  86. static int
  87. relay_digest_matches(crypto_digest_t *digest, cell_t *cell)
  88. {
  89. char received_integrity[4], calculated_integrity[4];
  90. relay_header_t rh;
  91. crypto_digest_t *backup_digest=NULL;
  92. backup_digest = crypto_digest_dup(digest);
  93. relay_header_unpack(&rh, cell->payload);
  94. memcpy(received_integrity, rh.integrity, 4);
  95. memset(rh.integrity, 0, 4);
  96. relay_header_pack(cell->payload, &rh);
  97. // log_fn(LOG_DEBUG,"Reading digest of %u %u %u %u from relay cell.",
  98. // received_integrity[0], received_integrity[1],
  99. // received_integrity[2], received_integrity[3]);
  100. crypto_digest_add_bytes(digest, (char*) cell->payload, CELL_PAYLOAD_SIZE);
  101. crypto_digest_get_digest(digest, calculated_integrity, 4);
  102. if (tor_memneq(received_integrity, calculated_integrity, 4)) {
  103. // log_fn(LOG_INFO,"Recognized=0 but bad digest. Not recognizing.");
  104. // (%d vs %d).", received_integrity, calculated_integrity);
  105. /* restore digest to its old form */
  106. crypto_digest_assign(digest, backup_digest);
  107. /* restore the relay header */
  108. memcpy(rh.integrity, received_integrity, 4);
  109. relay_header_pack(cell->payload, &rh);
  110. crypto_digest_free(backup_digest);
  111. return 0;
  112. }
  113. crypto_digest_free(backup_digest);
  114. return 1;
  115. }
  116. /** Apply <b>cipher</b> to CELL_PAYLOAD_SIZE bytes of <b>in</b>
  117. * (in place).
  118. *
  119. * If <b>encrypt_mode</b> is 1 then encrypt, else decrypt.
  120. *
  121. * Return -1 if the crypto fails, else return 0.
  122. */
  123. static int
  124. relay_crypt_one_payload(crypto_cipher_t *cipher, uint8_t *in,
  125. int encrypt_mode)
  126. {
  127. int r;
  128. (void)encrypt_mode;
  129. r = crypto_cipher_crypt_inplace(cipher, (char*) in, CELL_PAYLOAD_SIZE);
  130. if (r) {
  131. log_warn(LD_BUG,"Error during relay encryption");
  132. return -1;
  133. }
  134. return 0;
  135. }
  136. /** Receive a relay cell:
  137. * - Crypt it (encrypt if headed toward the origin or if we <b>are</b> the
  138. * origin; decrypt if we're headed toward the exit).
  139. * - Check if recognized (if exitward).
  140. * - If recognized and the digest checks out, then find if there's a stream
  141. * that the cell is intended for, and deliver it to the right
  142. * connection_edge.
  143. * - If not recognized, then we need to relay it: append it to the appropriate
  144. * cell_queue on <b>circ</b>.
  145. *
  146. * Return -<b>reason</b> on failure.
  147. */
  148. int
  149. circuit_receive_relay_cell(cell_t *cell, circuit_t *circ,
  150. cell_direction_t cell_direction)
  151. {
  152. channel_t *chan = NULL;
  153. crypt_path_t *layer_hint=NULL;
  154. char recognized=0;
  155. int reason;
  156. tor_assert(cell);
  157. tor_assert(circ);
  158. tor_assert(cell_direction == CELL_DIRECTION_OUT ||
  159. cell_direction == CELL_DIRECTION_IN);
  160. if (circ->marked_for_close)
  161. return 0;
  162. if (relay_crypt(circ, cell, cell_direction, &layer_hint, &recognized) < 0) {
  163. log_warn(LD_BUG,"relay crypt failed. Dropping connection.");
  164. return -END_CIRC_REASON_INTERNAL;
  165. }
  166. if (recognized) {
  167. edge_connection_t *conn = relay_lookup_conn(circ, cell, cell_direction,
  168. layer_hint);
  169. if (cell_direction == CELL_DIRECTION_OUT) {
  170. ++stats_n_relay_cells_delivered;
  171. log_debug(LD_OR,"Sending away from origin.");
  172. if ((reason=connection_edge_process_relay_cell(cell, circ, conn, NULL))
  173. < 0) {
  174. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  175. "connection_edge_process_relay_cell (away from origin) "
  176. "failed.");
  177. return reason;
  178. }
  179. }
  180. if (cell_direction == CELL_DIRECTION_IN) {
  181. ++stats_n_relay_cells_delivered;
  182. log_debug(LD_OR,"Sending to origin.");
  183. if ((reason = connection_edge_process_relay_cell(cell, circ, conn,
  184. layer_hint)) < 0) {
  185. log_warn(LD_OR,
  186. "connection_edge_process_relay_cell (at origin) failed.");
  187. return reason;
  188. }
  189. }
  190. return 0;
  191. }
  192. /* not recognized. pass it on. */
  193. if (cell_direction == CELL_DIRECTION_OUT) {
  194. cell->circ_id = circ->n_circ_id; /* switch it */
  195. chan = circ->n_chan;
  196. } else if (! CIRCUIT_IS_ORIGIN(circ)) {
  197. cell->circ_id = TO_OR_CIRCUIT(circ)->p_circ_id; /* switch it */
  198. chan = TO_OR_CIRCUIT(circ)->p_chan;
  199. } else {
  200. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  201. "Dropping unrecognized inbound cell on origin circuit.");
  202. return 0;
  203. }
  204. if (!chan) {
  205. // XXXX Can this splice stuff be done more cleanly?
  206. if (! CIRCUIT_IS_ORIGIN(circ) &&
  207. TO_OR_CIRCUIT(circ)->rend_splice &&
  208. cell_direction == CELL_DIRECTION_OUT) {
  209. or_circuit_t *splice = TO_OR_CIRCUIT(circ)->rend_splice;
  210. tor_assert(circ->purpose == CIRCUIT_PURPOSE_REND_ESTABLISHED);
  211. tor_assert(splice->base_.purpose == CIRCUIT_PURPOSE_REND_ESTABLISHED);
  212. cell->circ_id = splice->p_circ_id;
  213. cell->command = CELL_RELAY; /* can't be relay_early anyway */
  214. if ((reason = circuit_receive_relay_cell(cell, TO_CIRCUIT(splice),
  215. CELL_DIRECTION_IN)) < 0) {
  216. log_warn(LD_REND, "Error relaying cell across rendezvous; closing "
  217. "circuits");
  218. /* XXXX Do this here, or just return -1? */
  219. circuit_mark_for_close(circ, -reason);
  220. return reason;
  221. }
  222. return 0;
  223. }
  224. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  225. "Didn't recognize cell, but circ stops here! Closing circ.");
  226. return -END_CIRC_REASON_TORPROTOCOL;
  227. }
  228. log_debug(LD_OR,"Passing on unrecognized cell.");
  229. ++stats_n_relay_cells_relayed; /* XXXX no longer quite accurate {cells}
  230. * we might kill the circ before we relay
  231. * the cells. */
  232. append_cell_to_circuit_queue(circ, chan, cell, cell_direction, 0);
  233. return 0;
  234. }
  235. /** Do the appropriate en/decryptions for <b>cell</b> arriving on
  236. * <b>circ</b> in direction <b>cell_direction</b>.
  237. *
  238. * If cell_direction == CELL_DIRECTION_IN:
  239. * - If we're at the origin (we're the OP), for hops 1..N,
  240. * decrypt cell. If recognized, stop.
  241. * - Else (we're not the OP), encrypt one hop. Cell is not recognized.
  242. *
  243. * If cell_direction == CELL_DIRECTION_OUT:
  244. * - decrypt one hop. Check if recognized.
  245. *
  246. * If cell is recognized, set *recognized to 1, and set
  247. * *layer_hint to the hop that recognized it.
  248. *
  249. * Return -1 to indicate that we should mark the circuit for close,
  250. * else return 0.
  251. */
  252. int
  253. relay_crypt(circuit_t *circ, cell_t *cell, cell_direction_t cell_direction,
  254. crypt_path_t **layer_hint, char *recognized)
  255. {
  256. relay_header_t rh;
  257. tor_assert(circ);
  258. tor_assert(cell);
  259. tor_assert(recognized);
  260. tor_assert(cell_direction == CELL_DIRECTION_IN ||
  261. cell_direction == CELL_DIRECTION_OUT);
  262. if (cell_direction == CELL_DIRECTION_IN) {
  263. if (CIRCUIT_IS_ORIGIN(circ)) { /* We're at the beginning of the circuit.
  264. * We'll want to do layered decrypts. */
  265. crypt_path_t *thishop, *cpath = TO_ORIGIN_CIRCUIT(circ)->cpath;
  266. thishop = cpath;
  267. if (thishop->state != CPATH_STATE_OPEN) {
  268. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  269. "Relay cell before first created cell? Closing.");
  270. return -1;
  271. }
  272. do { /* Remember: cpath is in forward order, that is, first hop first. */
  273. tor_assert(thishop);
  274. if (relay_crypt_one_payload(thishop->b_crypto, cell->payload, 0) < 0)
  275. return -1;
  276. relay_header_unpack(&rh, cell->payload);
  277. if (rh.recognized == 0) {
  278. /* it's possibly recognized. have to check digest to be sure. */
  279. if (relay_digest_matches(thishop->b_digest, cell)) {
  280. *recognized = 1;
  281. *layer_hint = thishop;
  282. return 0;
  283. }
  284. }
  285. thishop = thishop->next;
  286. } while (thishop != cpath && thishop->state == CPATH_STATE_OPEN);
  287. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  288. "Incoming cell at client not recognized. Closing.");
  289. return -1;
  290. } else { /* we're in the middle. Just one crypt. */
  291. if (relay_crypt_one_payload(TO_OR_CIRCUIT(circ)->p_crypto,
  292. cell->payload, 1) < 0)
  293. return -1;
  294. // log_fn(LOG_DEBUG,"Skipping recognized check, because we're not "
  295. // "the client.");
  296. }
  297. } else /* cell_direction == CELL_DIRECTION_OUT */ {
  298. /* we're in the middle. Just one crypt. */
  299. if (relay_crypt_one_payload(TO_OR_CIRCUIT(circ)->n_crypto,
  300. cell->payload, 0) < 0)
  301. return -1;
  302. relay_header_unpack(&rh, cell->payload);
  303. if (rh.recognized == 0) {
  304. /* it's possibly recognized. have to check digest to be sure. */
  305. if (relay_digest_matches(TO_OR_CIRCUIT(circ)->n_digest, cell)) {
  306. *recognized = 1;
  307. return 0;
  308. }
  309. }
  310. }
  311. return 0;
  312. }
  313. /** Package a relay cell from an edge:
  314. * - Encrypt it to the right layer
  315. * - Append it to the appropriate cell_queue on <b>circ</b>.
  316. */
  317. static int
  318. circuit_package_relay_cell(cell_t *cell, circuit_t *circ,
  319. cell_direction_t cell_direction,
  320. crypt_path_t *layer_hint, streamid_t on_stream)
  321. {
  322. channel_t *chan; /* where to send the cell */
  323. if (cell_direction == CELL_DIRECTION_OUT) {
  324. crypt_path_t *thishop; /* counter for repeated crypts */
  325. chan = circ->n_chan;
  326. if (!CIRCUIT_IS_ORIGIN(circ) || !chan) {
  327. log_warn(LD_BUG,"outgoing relay cell has n_chan==NULL. Dropping.");
  328. return 0; /* just drop it */
  329. }
  330. relay_set_digest(layer_hint->f_digest, cell);
  331. thishop = layer_hint;
  332. /* moving from farthest to nearest hop */
  333. do {
  334. tor_assert(thishop);
  335. /* XXXX RD This is a bug, right? */
  336. log_debug(LD_OR,"crypting a layer of the relay cell.");
  337. if (relay_crypt_one_payload(thishop->f_crypto, cell->payload, 1) < 0) {
  338. return -1;
  339. }
  340. thishop = thishop->prev;
  341. } while (thishop != TO_ORIGIN_CIRCUIT(circ)->cpath->prev);
  342. } else { /* incoming cell */
  343. or_circuit_t *or_circ;
  344. if (CIRCUIT_IS_ORIGIN(circ)) {
  345. /* We should never package an _incoming_ cell from the circuit
  346. * origin; that means we messed up somewhere. */
  347. log_warn(LD_BUG,"incoming relay cell at origin circuit. Dropping.");
  348. assert_circuit_ok(circ);
  349. return 0; /* just drop it */
  350. }
  351. or_circ = TO_OR_CIRCUIT(circ);
  352. chan = or_circ->p_chan;
  353. relay_set_digest(or_circ->p_digest, cell);
  354. if (relay_crypt_one_payload(or_circ->p_crypto, cell->payload, 1) < 0)
  355. return -1;
  356. }
  357. ++stats_n_relay_cells_relayed;
  358. append_cell_to_circuit_queue(circ, chan, cell, cell_direction, on_stream);
  359. return 0;
  360. }
  361. /** If cell's stream_id matches the stream_id of any conn that's
  362. * attached to circ, return that conn, else return NULL.
  363. */
  364. static edge_connection_t *
  365. relay_lookup_conn(circuit_t *circ, cell_t *cell,
  366. cell_direction_t cell_direction, crypt_path_t *layer_hint)
  367. {
  368. edge_connection_t *tmpconn;
  369. relay_header_t rh;
  370. relay_header_unpack(&rh, cell->payload);
  371. if (!rh.stream_id)
  372. return NULL;
  373. /* IN or OUT cells could have come from either direction, now
  374. * that we allow rendezvous *to* an OP.
  375. */
  376. if (CIRCUIT_IS_ORIGIN(circ)) {
  377. for (tmpconn = TO_ORIGIN_CIRCUIT(circ)->p_streams; tmpconn;
  378. tmpconn=tmpconn->next_stream) {
  379. if (rh.stream_id == tmpconn->stream_id &&
  380. !tmpconn->base_.marked_for_close &&
  381. tmpconn->cpath_layer == layer_hint) {
  382. log_debug(LD_APP,"found conn for stream %d.", rh.stream_id);
  383. return tmpconn;
  384. }
  385. }
  386. } else {
  387. for (tmpconn = TO_OR_CIRCUIT(circ)->n_streams; tmpconn;
  388. tmpconn=tmpconn->next_stream) {
  389. if (rh.stream_id == tmpconn->stream_id &&
  390. !tmpconn->base_.marked_for_close) {
  391. log_debug(LD_EXIT,"found conn for stream %d.", rh.stream_id);
  392. if (cell_direction == CELL_DIRECTION_OUT ||
  393. connection_edge_is_rendezvous_stream(tmpconn))
  394. return tmpconn;
  395. }
  396. }
  397. for (tmpconn = TO_OR_CIRCUIT(circ)->resolving_streams; tmpconn;
  398. tmpconn=tmpconn->next_stream) {
  399. if (rh.stream_id == tmpconn->stream_id &&
  400. !tmpconn->base_.marked_for_close) {
  401. log_debug(LD_EXIT,"found conn for stream %d.", rh.stream_id);
  402. return tmpconn;
  403. }
  404. }
  405. }
  406. return NULL; /* probably a begin relay cell */
  407. }
  408. /** Pack the relay_header_t host-order structure <b>src</b> into
  409. * network-order in the buffer <b>dest</b>. See tor-spec.txt for details
  410. * about the wire format.
  411. */
  412. void
  413. relay_header_pack(uint8_t *dest, const relay_header_t *src)
  414. {
  415. set_uint8(dest, src->command);
  416. set_uint16(dest+1, htons(src->recognized));
  417. set_uint16(dest+3, htons(src->stream_id));
  418. memcpy(dest+5, src->integrity, 4);
  419. set_uint16(dest+9, htons(src->length));
  420. }
  421. /** Unpack the network-order buffer <b>src</b> into a host-order
  422. * relay_header_t structure <b>dest</b>.
  423. */
  424. void
  425. relay_header_unpack(relay_header_t *dest, const uint8_t *src)
  426. {
  427. dest->command = get_uint8(src);
  428. dest->recognized = ntohs(get_uint16(src+1));
  429. dest->stream_id = ntohs(get_uint16(src+3));
  430. memcpy(dest->integrity, src+5, 4);
  431. dest->length = ntohs(get_uint16(src+9));
  432. }
  433. /** Convert the relay <b>command</b> into a human-readable string. */
  434. static const char *
  435. relay_command_to_string(uint8_t command)
  436. {
  437. switch (command) {
  438. case RELAY_COMMAND_BEGIN: return "BEGIN";
  439. case RELAY_COMMAND_DATA: return "DATA";
  440. case RELAY_COMMAND_END: return "END";
  441. case RELAY_COMMAND_CONNECTED: return "CONNECTED";
  442. case RELAY_COMMAND_SENDME: return "SENDME";
  443. case RELAY_COMMAND_EXTEND: return "EXTEND";
  444. case RELAY_COMMAND_EXTENDED: return "EXTENDED";
  445. case RELAY_COMMAND_TRUNCATE: return "TRUNCATE";
  446. case RELAY_COMMAND_TRUNCATED: return "TRUNCATED";
  447. case RELAY_COMMAND_DROP: return "DROP";
  448. case RELAY_COMMAND_RESOLVE: return "RESOLVE";
  449. case RELAY_COMMAND_RESOLVED: return "RESOLVED";
  450. case RELAY_COMMAND_BEGIN_DIR: return "BEGIN_DIR";
  451. case RELAY_COMMAND_ESTABLISH_INTRO: return "ESTABLISH_INTRO";
  452. case RELAY_COMMAND_ESTABLISH_RENDEZVOUS: return "ESTABLISH_RENDEZVOUS";
  453. case RELAY_COMMAND_INTRODUCE1: return "INTRODUCE1";
  454. case RELAY_COMMAND_INTRODUCE2: return "INTRODUCE2";
  455. case RELAY_COMMAND_RENDEZVOUS1: return "RENDEZVOUS1";
  456. case RELAY_COMMAND_RENDEZVOUS2: return "RENDEZVOUS2";
  457. case RELAY_COMMAND_INTRO_ESTABLISHED: return "INTRO_ESTABLISHED";
  458. case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
  459. return "RENDEZVOUS_ESTABLISHED";
  460. case RELAY_COMMAND_INTRODUCE_ACK: return "INTRODUCE_ACK";
  461. default: return "(unrecognized)";
  462. }
  463. }
  464. /** Make a relay cell out of <b>relay_command</b> and <b>payload</b>, and send
  465. * it onto the open circuit <b>circ</b>. <b>stream_id</b> is the ID on
  466. * <b>circ</b> for the stream that's sending the relay cell, or 0 if it's a
  467. * control cell. <b>cpath_layer</b> is NULL for OR->OP cells, or the
  468. * destination hop for OP->OR cells.
  469. *
  470. * If you can't send the cell, mark the circuit for close and return -1. Else
  471. * return 0.
  472. */
  473. int
  474. relay_send_command_from_edge(streamid_t stream_id, circuit_t *circ,
  475. uint8_t relay_command, const char *payload,
  476. size_t payload_len, crypt_path_t *cpath_layer)
  477. {
  478. cell_t cell;
  479. relay_header_t rh;
  480. cell_direction_t cell_direction;
  481. /* XXXX NM Split this function into a separate versions per circuit type? */
  482. tor_assert(circ);
  483. tor_assert(payload_len <= RELAY_PAYLOAD_SIZE);
  484. memset(&cell, 0, sizeof(cell_t));
  485. cell.command = CELL_RELAY;
  486. if (cpath_layer) {
  487. cell.circ_id = circ->n_circ_id;
  488. cell_direction = CELL_DIRECTION_OUT;
  489. } else if (! CIRCUIT_IS_ORIGIN(circ)) {
  490. cell.circ_id = TO_OR_CIRCUIT(circ)->p_circ_id;
  491. cell_direction = CELL_DIRECTION_IN;
  492. } else {
  493. return -1;
  494. }
  495. memset(&rh, 0, sizeof(rh));
  496. rh.command = relay_command;
  497. rh.stream_id = stream_id;
  498. rh.length = payload_len;
  499. relay_header_pack(cell.payload, &rh);
  500. if (payload_len)
  501. memcpy(cell.payload+RELAY_HEADER_SIZE, payload, payload_len);
  502. log_debug(LD_OR,"delivering %d cell %s.", relay_command,
  503. cell_direction == CELL_DIRECTION_OUT ? "forward" : "backward");
  504. /* If we are sending an END cell and this circuit is used for a tunneled
  505. * directory request, advance its state. */
  506. if (relay_command == RELAY_COMMAND_END && circ->dirreq_id)
  507. geoip_change_dirreq_state(circ->dirreq_id, DIRREQ_TUNNELED,
  508. DIRREQ_END_CELL_SENT);
  509. if (cell_direction == CELL_DIRECTION_OUT && circ->n_chan) {
  510. /* if we're using relaybandwidthrate, this conn wants priority */
  511. channel_timestamp_client(circ->n_chan);
  512. }
  513. if (cell_direction == CELL_DIRECTION_OUT) {
  514. origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
  515. if (origin_circ->remaining_relay_early_cells > 0 &&
  516. (relay_command == RELAY_COMMAND_EXTEND ||
  517. cpath_layer != origin_circ->cpath)) {
  518. /* If we've got any relay_early cells left and (we're sending
  519. * an extend cell or we're not talking to the first hop), use
  520. * one of them. Don't worry about the conn protocol version:
  521. * append_cell_to_circuit_queue will fix it up. */
  522. cell.command = CELL_RELAY_EARLY;
  523. --origin_circ->remaining_relay_early_cells;
  524. log_debug(LD_OR, "Sending a RELAY_EARLY cell; %d remaining.",
  525. (int)origin_circ->remaining_relay_early_cells);
  526. /* Memorize the command that is sent as RELAY_EARLY cell; helps debug
  527. * task 878. */
  528. origin_circ->relay_early_commands[
  529. origin_circ->relay_early_cells_sent++] = relay_command;
  530. } else if (relay_command == RELAY_COMMAND_EXTEND) {
  531. /* If no RELAY_EARLY cells can be sent over this circuit, log which
  532. * commands have been sent as RELAY_EARLY cells before; helps debug
  533. * task 878. */
  534. smartlist_t *commands_list = smartlist_new();
  535. int i = 0;
  536. char *commands = NULL;
  537. for (; i < origin_circ->relay_early_cells_sent; i++)
  538. smartlist_add(commands_list, (char *)
  539. relay_command_to_string(origin_circ->relay_early_commands[i]));
  540. commands = smartlist_join_strings(commands_list, ",", 0, NULL);
  541. log_warn(LD_BUG, "Uh-oh. We're sending a RELAY_COMMAND_EXTEND cell, "
  542. "but we have run out of RELAY_EARLY cells on that circuit. "
  543. "Commands sent before: %s", commands);
  544. tor_free(commands);
  545. smartlist_free(commands_list);
  546. }
  547. }
  548. if (circuit_package_relay_cell(&cell, circ, cell_direction, cpath_layer,
  549. stream_id) < 0) {
  550. log_warn(LD_BUG,"circuit_package_relay_cell failed. Closing.");
  551. circuit_mark_for_close(circ, END_CIRC_REASON_INTERNAL);
  552. return -1;
  553. }
  554. return 0;
  555. }
  556. /** Make a relay cell out of <b>relay_command</b> and <b>payload</b>, and
  557. * send it onto the open circuit <b>circ</b>. <b>fromconn</b> is the stream
  558. * that's sending the relay cell, or NULL if it's a control cell.
  559. * <b>cpath_layer</b> is NULL for OR->OP cells, or the destination hop
  560. * for OP->OR cells.
  561. *
  562. * If you can't send the cell, mark the circuit for close and
  563. * return -1. Else return 0.
  564. */
  565. int
  566. connection_edge_send_command(edge_connection_t *fromconn,
  567. uint8_t relay_command, const char *payload,
  568. size_t payload_len)
  569. {
  570. /* XXXX NM Split this function into a separate versions per circuit type? */
  571. circuit_t *circ;
  572. crypt_path_t *cpath_layer = fromconn->cpath_layer;
  573. tor_assert(fromconn);
  574. circ = fromconn->on_circuit;
  575. if (fromconn->base_.marked_for_close) {
  576. log_warn(LD_BUG,
  577. "called on conn that's already marked for close at %s:%d.",
  578. fromconn->base_.marked_for_close_file,
  579. fromconn->base_.marked_for_close);
  580. return 0;
  581. }
  582. if (!circ) {
  583. if (fromconn->base_.type == CONN_TYPE_AP) {
  584. log_info(LD_APP,"no circ. Closing conn.");
  585. connection_mark_unattached_ap(EDGE_TO_ENTRY_CONN(fromconn),
  586. END_STREAM_REASON_INTERNAL);
  587. } else {
  588. log_info(LD_EXIT,"no circ. Closing conn.");
  589. fromconn->edge_has_sent_end = 1; /* no circ to send to */
  590. fromconn->end_reason = END_STREAM_REASON_INTERNAL;
  591. connection_mark_for_close(TO_CONN(fromconn));
  592. }
  593. return -1;
  594. }
  595. return relay_send_command_from_edge(fromconn->stream_id, circ,
  596. relay_command, payload,
  597. payload_len, cpath_layer);
  598. }
  599. /** How many times will I retry a stream that fails due to DNS
  600. * resolve failure or misc error?
  601. */
  602. #define MAX_RESOLVE_FAILURES 3
  603. /** Return 1 if reason is something that you should retry if you
  604. * get the end cell before you've connected; else return 0. */
  605. static int
  606. edge_reason_is_retriable(int reason)
  607. {
  608. return reason == END_STREAM_REASON_HIBERNATING ||
  609. reason == END_STREAM_REASON_RESOURCELIMIT ||
  610. reason == END_STREAM_REASON_EXITPOLICY ||
  611. reason == END_STREAM_REASON_RESOLVEFAILED ||
  612. reason == END_STREAM_REASON_MISC ||
  613. reason == END_STREAM_REASON_NOROUTE;
  614. }
  615. /** Called when we receive an END cell on a stream that isn't open yet,
  616. * from the client side.
  617. * Arguments are as for connection_edge_process_relay_cell().
  618. */
  619. static int
  620. connection_ap_process_end_not_open(
  621. relay_header_t *rh, cell_t *cell, origin_circuit_t *circ,
  622. entry_connection_t *conn, crypt_path_t *layer_hint)
  623. {
  624. struct in_addr in;
  625. node_t *exitrouter;
  626. int reason = *(cell->payload+RELAY_HEADER_SIZE);
  627. int control_reason = reason | END_STREAM_REASON_FLAG_REMOTE;
  628. edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
  629. (void) layer_hint; /* unused */
  630. if (rh->length > 0 && edge_reason_is_retriable(reason) &&
  631. /* avoid retry if rend */
  632. !connection_edge_is_rendezvous_stream(edge_conn)) {
  633. const char *chosen_exit_digest =
  634. circ->build_state->chosen_exit->identity_digest;
  635. log_info(LD_APP,"Address '%s' refused due to '%s'. Considering retrying.",
  636. safe_str(conn->socks_request->address),
  637. stream_end_reason_to_string(reason));
  638. exitrouter = node_get_mutable_by_id(chosen_exit_digest);
  639. switch (reason) {
  640. case END_STREAM_REASON_EXITPOLICY:
  641. if (rh->length >= 5) {
  642. uint32_t addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+1));
  643. int ttl;
  644. if (!addr) {
  645. log_info(LD_APP,"Address '%s' resolved to 0.0.0.0. Closing,",
  646. safe_str(conn->socks_request->address));
  647. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  648. return 0;
  649. }
  650. if (rh->length >= 9)
  651. ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+5));
  652. else
  653. ttl = -1;
  654. if (get_options()->ClientDNSRejectInternalAddresses &&
  655. is_internal_IP(addr, 0)) {
  656. log_info(LD_APP,"Address '%s' resolved to internal. Closing,",
  657. safe_str(conn->socks_request->address));
  658. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  659. return 0;
  660. }
  661. client_dns_set_addressmap(conn->socks_request->address, addr,
  662. conn->chosen_exit_name, ttl);
  663. }
  664. /* check if he *ought* to have allowed it */
  665. if (exitrouter &&
  666. (rh->length < 5 ||
  667. (tor_inet_aton(conn->socks_request->address, &in) &&
  668. !conn->chosen_exit_name))) {
  669. log_info(LD_APP,
  670. "Exitrouter %s seems to be more restrictive than its exit "
  671. "policy. Not using this router as exit for now.",
  672. node_describe(exitrouter));
  673. policies_set_node_exitpolicy_to_reject_all(exitrouter);
  674. }
  675. /* rewrite it to an IP if we learned one. */
  676. if (addressmap_rewrite(conn->socks_request->address,
  677. sizeof(conn->socks_request->address),
  678. NULL, NULL)) {
  679. control_event_stream_status(conn, STREAM_EVENT_REMAP, 0);
  680. }
  681. if (conn->chosen_exit_optional ||
  682. conn->chosen_exit_retries) {
  683. /* stop wanting a specific exit */
  684. conn->chosen_exit_optional = 0;
  685. /* A non-zero chosen_exit_retries can happen if we set a
  686. * TrackHostExits for this address under a port that the exit
  687. * relay allows, but then try the same address with a different
  688. * port that it doesn't allow to exit. We shouldn't unregister
  689. * the mapping, since it is probably still wanted on the
  690. * original port. But now we give away to the exit relay that
  691. * we probably have a TrackHostExits on it. So be it. */
  692. conn->chosen_exit_retries = 0;
  693. tor_free(conn->chosen_exit_name); /* clears it */
  694. }
  695. if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
  696. return 0;
  697. /* else, conn will get closed below */
  698. break;
  699. case END_STREAM_REASON_CONNECTREFUSED:
  700. if (!conn->chosen_exit_optional)
  701. break; /* break means it'll close, below */
  702. /* Else fall through: expire this circuit, clear the
  703. * chosen_exit_name field, and try again. */
  704. case END_STREAM_REASON_RESOLVEFAILED:
  705. case END_STREAM_REASON_TIMEOUT:
  706. case END_STREAM_REASON_MISC:
  707. case END_STREAM_REASON_NOROUTE:
  708. if (client_dns_incr_failures(conn->socks_request->address)
  709. < MAX_RESOLVE_FAILURES) {
  710. /* We haven't retried too many times; reattach the connection. */
  711. circuit_log_path(LOG_INFO,LD_APP,circ);
  712. /* Mark this circuit "unusable for new streams". */
  713. /* XXXX024 this is a kludgy way to do this. */
  714. tor_assert(circ->base_.timestamp_dirty);
  715. circ->base_.timestamp_dirty -= get_options()->MaxCircuitDirtiness;
  716. if (conn->chosen_exit_optional) {
  717. /* stop wanting a specific exit */
  718. conn->chosen_exit_optional = 0;
  719. tor_free(conn->chosen_exit_name); /* clears it */
  720. }
  721. if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
  722. return 0;
  723. /* else, conn will get closed below */
  724. } else {
  725. log_notice(LD_APP,
  726. "Have tried resolving or connecting to address '%s' "
  727. "at %d different places. Giving up.",
  728. safe_str(conn->socks_request->address),
  729. MAX_RESOLVE_FAILURES);
  730. /* clear the failures, so it will have a full try next time */
  731. client_dns_clear_failures(conn->socks_request->address);
  732. }
  733. break;
  734. case END_STREAM_REASON_HIBERNATING:
  735. case END_STREAM_REASON_RESOURCELIMIT:
  736. if (exitrouter) {
  737. policies_set_node_exitpolicy_to_reject_all(exitrouter);
  738. }
  739. if (conn->chosen_exit_optional) {
  740. /* stop wanting a specific exit */
  741. conn->chosen_exit_optional = 0;
  742. tor_free(conn->chosen_exit_name); /* clears it */
  743. }
  744. if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
  745. return 0;
  746. /* else, will close below */
  747. break;
  748. } /* end switch */
  749. log_info(LD_APP,"Giving up on retrying; conn can't be handled.");
  750. }
  751. log_info(LD_APP,
  752. "Edge got end (%s) before we're connected. Marking for close.",
  753. stream_end_reason_to_string(rh->length > 0 ? reason : -1));
  754. circuit_log_path(LOG_INFO,LD_APP,circ);
  755. /* need to test because of detach_retriable */
  756. if (!ENTRY_TO_CONN(conn)->marked_for_close)
  757. connection_mark_unattached_ap(conn, control_reason);
  758. return 0;
  759. }
  760. /** Helper: change the socks_request-&gt;address field on conn to the
  761. * dotted-quad representation of <b>new_addr</b> (given in host order),
  762. * and send an appropriate REMAP event. */
  763. static void
  764. remap_event_helper(entry_connection_t *conn, uint32_t new_addr)
  765. {
  766. struct in_addr in;
  767. in.s_addr = htonl(new_addr);
  768. tor_inet_ntoa(&in, conn->socks_request->address,
  769. sizeof(conn->socks_request->address));
  770. control_event_stream_status(conn, STREAM_EVENT_REMAP,
  771. REMAP_STREAM_SOURCE_EXIT);
  772. }
  773. /** An incoming relay cell has arrived from circuit <b>circ</b> to
  774. * stream <b>conn</b>.
  775. *
  776. * The arguments here are the same as in
  777. * connection_edge_process_relay_cell() below; this function is called
  778. * from there when <b>conn</b> is defined and not in an open state.
  779. */
  780. static int
  781. connection_edge_process_relay_cell_not_open(
  782. relay_header_t *rh, cell_t *cell, circuit_t *circ,
  783. edge_connection_t *conn, crypt_path_t *layer_hint)
  784. {
  785. if (rh->command == RELAY_COMMAND_END) {
  786. if (CIRCUIT_IS_ORIGIN(circ) && conn->base_.type == CONN_TYPE_AP) {
  787. return connection_ap_process_end_not_open(rh, cell,
  788. TO_ORIGIN_CIRCUIT(circ),
  789. EDGE_TO_ENTRY_CONN(conn),
  790. layer_hint);
  791. } else {
  792. /* we just got an 'end', don't need to send one */
  793. conn->edge_has_sent_end = 1;
  794. conn->end_reason = *(cell->payload+RELAY_HEADER_SIZE) |
  795. END_STREAM_REASON_FLAG_REMOTE;
  796. connection_mark_for_close(TO_CONN(conn));
  797. return 0;
  798. }
  799. }
  800. if (conn->base_.type == CONN_TYPE_AP &&
  801. rh->command == RELAY_COMMAND_CONNECTED) {
  802. entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
  803. tor_assert(CIRCUIT_IS_ORIGIN(circ));
  804. if (conn->base_.state != AP_CONN_STATE_CONNECT_WAIT) {
  805. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  806. "Got 'connected' while not in state connect_wait. Dropping.");
  807. return 0;
  808. }
  809. conn->base_.state = AP_CONN_STATE_OPEN;
  810. log_info(LD_APP,"'connected' received after %d seconds.",
  811. (int)(time(NULL) - conn->base_.timestamp_lastread));
  812. if (rh->length >= 4) {
  813. uint32_t addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE));
  814. int ttl;
  815. if (!addr || (get_options()->ClientDNSRejectInternalAddresses &&
  816. is_internal_IP(addr, 0))) {
  817. log_info(LD_APP, "...but it claims the IP address was %s. Closing.",
  818. fmt_addr32(addr));
  819. connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
  820. connection_mark_unattached_ap(entry_conn,
  821. END_STREAM_REASON_TORPROTOCOL);
  822. return 0;
  823. }
  824. if (rh->length >= 8)
  825. ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+4));
  826. else
  827. ttl = -1;
  828. client_dns_set_addressmap(entry_conn->socks_request->address, addr,
  829. entry_conn->chosen_exit_name, ttl);
  830. remap_event_helper(entry_conn, addr);
  831. }
  832. circuit_log_path(LOG_INFO,LD_APP,TO_ORIGIN_CIRCUIT(circ));
  833. /* don't send a socks reply to transparent conns */
  834. tor_assert(entry_conn->socks_request != NULL);
  835. if (!entry_conn->socks_request->has_finished)
  836. connection_ap_handshake_socks_reply(entry_conn, NULL, 0, 0);
  837. /* Was it a linked dir conn? If so, a dir request just started to
  838. * fetch something; this could be a bootstrap status milestone. */
  839. log_debug(LD_APP, "considering");
  840. if (TO_CONN(conn)->linked_conn &&
  841. TO_CONN(conn)->linked_conn->type == CONN_TYPE_DIR) {
  842. connection_t *dirconn = TO_CONN(conn)->linked_conn;
  843. log_debug(LD_APP, "it is! %d", dirconn->purpose);
  844. switch (dirconn->purpose) {
  845. case DIR_PURPOSE_FETCH_CERTIFICATE:
  846. if (consensus_is_waiting_for_certs())
  847. control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_KEYS, 0);
  848. break;
  849. case DIR_PURPOSE_FETCH_CONSENSUS:
  850. control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_STATUS, 0);
  851. break;
  852. case DIR_PURPOSE_FETCH_SERVERDESC:
  853. control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_DESCRIPTORS,
  854. count_loading_descriptors_progress());
  855. break;
  856. }
  857. }
  858. /* This is definitely a success, so forget about any pending data we
  859. * had sent. */
  860. if (entry_conn->pending_optimistic_data) {
  861. generic_buffer_free(entry_conn->pending_optimistic_data);
  862. entry_conn->pending_optimistic_data = NULL;
  863. }
  864. /* handle anything that might have queued */
  865. if (connection_edge_package_raw_inbuf(conn, 1, NULL) < 0) {
  866. /* (We already sent an end cell if possible) */
  867. connection_mark_for_close(TO_CONN(conn));
  868. return 0;
  869. }
  870. return 0;
  871. }
  872. if (conn->base_.type == CONN_TYPE_AP &&
  873. rh->command == RELAY_COMMAND_RESOLVED) {
  874. int ttl;
  875. int answer_len;
  876. uint8_t answer_type;
  877. entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
  878. if (conn->base_.state != AP_CONN_STATE_RESOLVE_WAIT) {
  879. log_fn(LOG_PROTOCOL_WARN, LD_APP, "Got a 'resolved' cell while "
  880. "not in state resolve_wait. Dropping.");
  881. return 0;
  882. }
  883. tor_assert(SOCKS_COMMAND_IS_RESOLVE(entry_conn->socks_request->command));
  884. answer_len = cell->payload[RELAY_HEADER_SIZE+1];
  885. if (rh->length < 2 || answer_len+2>rh->length) {
  886. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  887. "Dropping malformed 'resolved' cell");
  888. connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TORPROTOCOL);
  889. return 0;
  890. }
  891. answer_type = cell->payload[RELAY_HEADER_SIZE];
  892. if (rh->length >= answer_len+6)
  893. ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+
  894. 2+answer_len));
  895. else
  896. ttl = -1;
  897. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
  898. uint32_t addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+2));
  899. if (get_options()->ClientDNSRejectInternalAddresses &&
  900. is_internal_IP(addr, 0)) {
  901. log_info(LD_APP,"Got a resolve with answer %s. Rejecting.",
  902. fmt_addr32(addr));
  903. connection_ap_handshake_socks_resolved(entry_conn,
  904. RESOLVED_TYPE_ERROR_TRANSIENT,
  905. 0, NULL, 0, TIME_MAX);
  906. connection_mark_unattached_ap(entry_conn,
  907. END_STREAM_REASON_TORPROTOCOL);
  908. return 0;
  909. }
  910. }
  911. connection_ap_handshake_socks_resolved(entry_conn,
  912. answer_type,
  913. cell->payload[RELAY_HEADER_SIZE+1], /*answer_len*/
  914. cell->payload+RELAY_HEADER_SIZE+2, /*answer*/
  915. ttl,
  916. -1);
  917. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
  918. uint32_t addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+2));
  919. remap_event_helper(entry_conn, addr);
  920. }
  921. connection_mark_unattached_ap(entry_conn,
  922. END_STREAM_REASON_DONE |
  923. END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
  924. return 0;
  925. }
  926. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  927. "Got an unexpected relay command %d, in state %d (%s). Dropping.",
  928. rh->command, conn->base_.state,
  929. conn_state_to_string(conn->base_.type, conn->base_.state));
  930. return 0; /* for forward compatibility, don't kill the circuit */
  931. // connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
  932. // connection_mark_for_close(conn);
  933. // return -1;
  934. }
  935. /** An incoming relay cell has arrived on circuit <b>circ</b>. If
  936. * <b>conn</b> is NULL this is a control cell, else <b>cell</b> is
  937. * destined for <b>conn</b>.
  938. *
  939. * If <b>layer_hint</b> is defined, then we're the origin of the
  940. * circuit, and it specifies the hop that packaged <b>cell</b>.
  941. *
  942. * Return -reason if you want to warn and tear down the circuit, else 0.
  943. */
  944. static int
  945. connection_edge_process_relay_cell(cell_t *cell, circuit_t *circ,
  946. edge_connection_t *conn,
  947. crypt_path_t *layer_hint)
  948. {
  949. static int num_seen=0;
  950. relay_header_t rh;
  951. unsigned domain = layer_hint?LD_APP:LD_EXIT;
  952. int reason;
  953. int optimistic_data = 0; /* Set to 1 if we receive data on a stream
  954. * that's in the EXIT_CONN_STATE_RESOLVING
  955. * or EXIT_CONN_STATE_CONNECTING states. */
  956. tor_assert(cell);
  957. tor_assert(circ);
  958. relay_header_unpack(&rh, cell->payload);
  959. // log_fn(LOG_DEBUG,"command %d stream %d", rh.command, rh.stream_id);
  960. num_seen++;
  961. log_debug(domain, "Now seen %d relay cells here (command %d, stream %d).",
  962. num_seen, rh.command, rh.stream_id);
  963. if (rh.length > RELAY_PAYLOAD_SIZE) {
  964. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  965. "Relay cell length field too long. Closing circuit.");
  966. return - END_CIRC_REASON_TORPROTOCOL;
  967. }
  968. /* either conn is NULL, in which case we've got a control cell, or else
  969. * conn points to the recognized stream. */
  970. if (conn && !connection_state_is_open(TO_CONN(conn))) {
  971. if (conn->base_.type == CONN_TYPE_EXIT &&
  972. (conn->base_.state == EXIT_CONN_STATE_CONNECTING ||
  973. conn->base_.state == EXIT_CONN_STATE_RESOLVING) &&
  974. rh.command == RELAY_COMMAND_DATA) {
  975. /* Allow DATA cells to be delivered to an exit node in state
  976. * EXIT_CONN_STATE_CONNECTING or EXIT_CONN_STATE_RESOLVING.
  977. * This speeds up HTTP, for example. */
  978. optimistic_data = 1;
  979. } else {
  980. return connection_edge_process_relay_cell_not_open(
  981. &rh, cell, circ, conn, layer_hint);
  982. }
  983. }
  984. switch (rh.command) {
  985. case RELAY_COMMAND_DROP:
  986. // log_info(domain,"Got a relay-level padding cell. Dropping.");
  987. return 0;
  988. case RELAY_COMMAND_BEGIN:
  989. case RELAY_COMMAND_BEGIN_DIR:
  990. if (layer_hint &&
  991. circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
  992. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  993. "Relay begin request unsupported at AP. Dropping.");
  994. return 0;
  995. }
  996. if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED &&
  997. layer_hint != TO_ORIGIN_CIRCUIT(circ)->cpath->prev) {
  998. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  999. "Relay begin request to Hidden Service "
  1000. "from intermediary node. Dropping.");
  1001. return 0;
  1002. }
  1003. if (conn) {
  1004. log_fn(LOG_PROTOCOL_WARN, domain,
  1005. "Begin cell for known stream. Dropping.");
  1006. return 0;
  1007. }
  1008. if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
  1009. /* Assign this circuit and its app-ward OR connection a unique ID,
  1010. * so that we can measure download times. The local edge and dir
  1011. * connection will be assigned the same ID when they are created
  1012. * and linked. */
  1013. static uint64_t next_id = 0;
  1014. circ->dirreq_id = ++next_id;
  1015. TO_OR_CIRCUIT(circ)->p_chan->dirreq_id = circ->dirreq_id;
  1016. }
  1017. return connection_exit_begin_conn(cell, circ);
  1018. case RELAY_COMMAND_DATA:
  1019. ++stats_n_data_cells_received;
  1020. if (( layer_hint && --layer_hint->deliver_window < 0) ||
  1021. (!layer_hint && --circ->deliver_window < 0)) {
  1022. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1023. "(relay data) circ deliver_window below 0. Killing.");
  1024. if (conn) {
  1025. /* XXXX Do we actually need to do this? Will killing the circuit
  1026. * not send an END and mark the stream for close as appropriate? */
  1027. connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
  1028. connection_mark_for_close(TO_CONN(conn));
  1029. }
  1030. return -END_CIRC_REASON_TORPROTOCOL;
  1031. }
  1032. log_debug(domain,"circ deliver_window now %d.", layer_hint ?
  1033. layer_hint->deliver_window : circ->deliver_window);
  1034. circuit_consider_sending_sendme(circ, layer_hint);
  1035. if (!conn) {
  1036. log_info(domain,"data cell dropped, unknown stream (streamid %d).",
  1037. rh.stream_id);
  1038. return 0;
  1039. }
  1040. if (--conn->deliver_window < 0) { /* is it below 0 after decrement? */
  1041. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1042. "(relay data) conn deliver_window below 0. Killing.");
  1043. return -END_CIRC_REASON_TORPROTOCOL;
  1044. }
  1045. stats_n_data_bytes_received += rh.length;
  1046. connection_write_to_buf((char*)(cell->payload + RELAY_HEADER_SIZE),
  1047. rh.length, TO_CONN(conn));
  1048. if (!optimistic_data) {
  1049. /* Only send a SENDME if we're not getting optimistic data; otherwise
  1050. * a SENDME could arrive before the CONNECTED.
  1051. */
  1052. connection_edge_consider_sending_sendme(conn);
  1053. }
  1054. return 0;
  1055. case RELAY_COMMAND_END:
  1056. reason = rh.length > 0 ?
  1057. get_uint8(cell->payload+RELAY_HEADER_SIZE) : END_STREAM_REASON_MISC;
  1058. if (!conn) {
  1059. log_info(domain,"end cell (%s) dropped, unknown stream.",
  1060. stream_end_reason_to_string(reason));
  1061. return 0;
  1062. }
  1063. /* XXX add to this log_fn the exit node's nickname? */
  1064. log_info(domain,"%d: end cell (%s) for stream %d. Removing stream.",
  1065. conn->base_.s,
  1066. stream_end_reason_to_string(reason),
  1067. conn->stream_id);
  1068. if (conn->base_.type == CONN_TYPE_AP) {
  1069. entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
  1070. if (entry_conn->socks_request &&
  1071. !entry_conn->socks_request->has_finished)
  1072. log_warn(LD_BUG,
  1073. "open stream hasn't sent socks answer yet? Closing.");
  1074. }
  1075. /* We just *got* an end; no reason to send one. */
  1076. conn->edge_has_sent_end = 1;
  1077. if (!conn->end_reason)
  1078. conn->end_reason = reason | END_STREAM_REASON_FLAG_REMOTE;
  1079. if (!conn->base_.marked_for_close) {
  1080. /* only mark it if not already marked. it's possible to
  1081. * get the 'end' right around when the client hangs up on us. */
  1082. connection_mark_and_flush(TO_CONN(conn));
  1083. }
  1084. return 0;
  1085. case RELAY_COMMAND_EXTEND: {
  1086. static uint64_t total_n_extend=0, total_nonearly=0;
  1087. total_n_extend++;
  1088. if (rh.stream_id) {
  1089. log_fn(LOG_PROTOCOL_WARN, domain,
  1090. "'extend' cell received for non-zero stream. Dropping.");
  1091. return 0;
  1092. }
  1093. if (cell->command != CELL_RELAY_EARLY &&
  1094. !networkstatus_get_param(NULL,"AllowNonearlyExtend",0,0,1)) {
  1095. #define EARLY_WARNING_INTERVAL 3600
  1096. static ratelim_t early_warning_limit =
  1097. RATELIM_INIT(EARLY_WARNING_INTERVAL);
  1098. char *m;
  1099. if (cell->command == CELL_RELAY) {
  1100. ++total_nonearly;
  1101. if ((m = rate_limit_log(&early_warning_limit, approx_time()))) {
  1102. double percentage = ((double)total_nonearly)/total_n_extend;
  1103. percentage *= 100;
  1104. log_fn(LOG_PROTOCOL_WARN, domain, "EXTEND cell received, "
  1105. "but not via RELAY_EARLY. Dropping.%s", m);
  1106. log_fn(LOG_PROTOCOL_WARN, domain, " (We have dropped %.02f%% of "
  1107. "all EXTEND cells for this reason)", percentage);
  1108. tor_free(m);
  1109. }
  1110. } else {
  1111. log_fn(LOG_WARN, domain,
  1112. "EXTEND cell received, in a cell with type %d! Dropping.",
  1113. cell->command);
  1114. }
  1115. return 0;
  1116. }
  1117. return circuit_extend(cell, circ);
  1118. }
  1119. case RELAY_COMMAND_EXTENDED:
  1120. if (!layer_hint) {
  1121. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1122. "'extended' unsupported at non-origin. Dropping.");
  1123. return 0;
  1124. }
  1125. log_debug(domain,"Got an extended cell! Yay.");
  1126. if ((reason = circuit_finish_handshake(TO_ORIGIN_CIRCUIT(circ),
  1127. CELL_CREATED,
  1128. cell->payload+RELAY_HEADER_SIZE)) < 0) {
  1129. log_warn(domain,"circuit_finish_handshake failed.");
  1130. return reason;
  1131. }
  1132. if ((reason=circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ)))<0) {
  1133. log_info(domain,"circuit_send_next_onion_skin() failed.");
  1134. return reason;
  1135. }
  1136. return 0;
  1137. case RELAY_COMMAND_TRUNCATE:
  1138. if (layer_hint) {
  1139. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  1140. "'truncate' unsupported at origin. Dropping.");
  1141. return 0;
  1142. }
  1143. if (circ->n_chan) {
  1144. uint8_t trunc_reason = get_uint8(cell->payload + RELAY_HEADER_SIZE);
  1145. circuit_clear_cell_queue(circ, circ->n_chan);
  1146. channel_send_destroy(circ->n_circ_id, circ->n_chan,
  1147. trunc_reason);
  1148. circuit_set_n_circid_chan(circ, 0, NULL);
  1149. }
  1150. log_debug(LD_EXIT, "Processed 'truncate', replying.");
  1151. {
  1152. char payload[1];
  1153. payload[0] = (char)END_CIRC_REASON_REQUESTED;
  1154. relay_send_command_from_edge(0, circ, RELAY_COMMAND_TRUNCATED,
  1155. payload, sizeof(payload), NULL);
  1156. }
  1157. return 0;
  1158. case RELAY_COMMAND_TRUNCATED:
  1159. if (!layer_hint) {
  1160. log_fn(LOG_PROTOCOL_WARN, LD_EXIT,
  1161. "'truncated' unsupported at non-origin. Dropping.");
  1162. return 0;
  1163. }
  1164. circuit_truncated(TO_ORIGIN_CIRCUIT(circ), layer_hint,
  1165. get_uint8(cell->payload + RELAY_HEADER_SIZE));
  1166. return 0;
  1167. case RELAY_COMMAND_CONNECTED:
  1168. if (conn) {
  1169. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1170. "'connected' unsupported while open. Closing circ.");
  1171. return -END_CIRC_REASON_TORPROTOCOL;
  1172. }
  1173. log_info(domain,
  1174. "'connected' received, no conn attached anymore. Ignoring.");
  1175. return 0;
  1176. case RELAY_COMMAND_SENDME:
  1177. if (!rh.stream_id) {
  1178. if (layer_hint) {
  1179. if (layer_hint->package_window + CIRCWINDOW_INCREMENT >
  1180. CIRCWINDOW_START_MAX) {
  1181. /*XXXX024: Downgrade this back to LOG_PROTOCOL_WARN after a while*/
  1182. log_fn(LOG_WARN, LD_PROTOCOL,
  1183. "Bug/attack: unexpected sendme cell from exit relay. "
  1184. "Closing circ.");
  1185. return -END_CIRC_REASON_TORPROTOCOL;
  1186. }
  1187. layer_hint->package_window += CIRCWINDOW_INCREMENT;
  1188. log_debug(LD_APP,"circ-level sendme at origin, packagewindow %d.",
  1189. layer_hint->package_window);
  1190. circuit_resume_edge_reading(circ, layer_hint);
  1191. } else {
  1192. if (circ->package_window + CIRCWINDOW_INCREMENT >
  1193. CIRCWINDOW_START_MAX) {
  1194. /*XXXX024: Downgrade this back to LOG_PROTOCOL_WARN after a while*/
  1195. log_fn(LOG_WARN, LD_PROTOCOL,
  1196. "Bug/attack: unexpected sendme cell from client. "
  1197. "Closing circ.");
  1198. return -END_CIRC_REASON_TORPROTOCOL;
  1199. }
  1200. circ->package_window += CIRCWINDOW_INCREMENT;
  1201. log_debug(LD_APP,
  1202. "circ-level sendme at non-origin, packagewindow %d.",
  1203. circ->package_window);
  1204. circuit_resume_edge_reading(circ, layer_hint);
  1205. }
  1206. return 0;
  1207. }
  1208. if (!conn) {
  1209. log_info(domain,"sendme cell dropped, unknown stream (streamid %d).",
  1210. rh.stream_id);
  1211. return 0;
  1212. }
  1213. conn->package_window += STREAMWINDOW_INCREMENT;
  1214. log_debug(domain,"stream-level sendme, packagewindow now %d.",
  1215. conn->package_window);
  1216. if (circuit_queue_streams_are_blocked(circ)) {
  1217. /* Still waiting for queue to flush; don't touch conn */
  1218. return 0;
  1219. }
  1220. connection_start_reading(TO_CONN(conn));
  1221. /* handle whatever might still be on the inbuf */
  1222. if (connection_edge_package_raw_inbuf(conn, 1, NULL) < 0) {
  1223. /* (We already sent an end cell if possible) */
  1224. connection_mark_for_close(TO_CONN(conn));
  1225. return 0;
  1226. }
  1227. return 0;
  1228. case RELAY_COMMAND_RESOLVE:
  1229. if (layer_hint) {
  1230. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  1231. "resolve request unsupported at AP; dropping.");
  1232. return 0;
  1233. } else if (conn) {
  1234. log_fn(LOG_PROTOCOL_WARN, domain,
  1235. "resolve request for known stream; dropping.");
  1236. return 0;
  1237. } else if (circ->purpose != CIRCUIT_PURPOSE_OR) {
  1238. log_fn(LOG_PROTOCOL_WARN, domain,
  1239. "resolve request on circ with purpose %d; dropping",
  1240. circ->purpose);
  1241. return 0;
  1242. }
  1243. connection_exit_begin_resolve(cell, TO_OR_CIRCUIT(circ));
  1244. return 0;
  1245. case RELAY_COMMAND_RESOLVED:
  1246. if (conn) {
  1247. log_fn(LOG_PROTOCOL_WARN, domain,
  1248. "'resolved' unsupported while open. Closing circ.");
  1249. return -END_CIRC_REASON_TORPROTOCOL;
  1250. }
  1251. log_info(domain,
  1252. "'resolved' received, no conn attached anymore. Ignoring.");
  1253. return 0;
  1254. case RELAY_COMMAND_ESTABLISH_INTRO:
  1255. case RELAY_COMMAND_ESTABLISH_RENDEZVOUS:
  1256. case RELAY_COMMAND_INTRODUCE1:
  1257. case RELAY_COMMAND_INTRODUCE2:
  1258. case RELAY_COMMAND_INTRODUCE_ACK:
  1259. case RELAY_COMMAND_RENDEZVOUS1:
  1260. case RELAY_COMMAND_RENDEZVOUS2:
  1261. case RELAY_COMMAND_INTRO_ESTABLISHED:
  1262. case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
  1263. rend_process_relay_cell(circ, layer_hint,
  1264. rh.command, rh.length,
  1265. cell->payload+RELAY_HEADER_SIZE);
  1266. return 0;
  1267. }
  1268. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1269. "Received unknown relay command %d. Perhaps the other side is using "
  1270. "a newer version of Tor? Dropping.",
  1271. rh.command);
  1272. return 0; /* for forward compatibility, don't kill the circuit */
  1273. }
  1274. /** How many relay_data cells have we built, ever? */
  1275. uint64_t stats_n_data_cells_packaged = 0;
  1276. /** How many bytes of data have we put in relay_data cells have we built,
  1277. * ever? This would be RELAY_PAYLOAD_SIZE*stats_n_data_cells_packaged if
  1278. * every relay cell we ever sent were completely full of data. */
  1279. uint64_t stats_n_data_bytes_packaged = 0;
  1280. /** How many relay_data cells have we received, ever? */
  1281. uint64_t stats_n_data_cells_received = 0;
  1282. /** How many bytes of data have we received relay_data cells, ever? This would
  1283. * be RELAY_PAYLOAD_SIZE*stats_n_data_cells_packaged if every relay cell we
  1284. * ever received were completely full of data. */
  1285. uint64_t stats_n_data_bytes_received = 0;
  1286. /** If <b>conn</b> has an entire relay payload of bytes on its inbuf (or
  1287. * <b>package_partial</b> is true), and the appropriate package windows aren't
  1288. * empty, grab a cell and send it down the circuit.
  1289. *
  1290. * If *<b>max_cells</b> is given, package no more than max_cells. Decrement
  1291. * *<b>max_cells</b> by the number of cells packaged.
  1292. *
  1293. * Return -1 (and send a RELAY_COMMAND_END cell if necessary) if conn should
  1294. * be marked for close, else return 0.
  1295. */
  1296. int
  1297. connection_edge_package_raw_inbuf(edge_connection_t *conn, int package_partial,
  1298. int *max_cells)
  1299. {
  1300. size_t bytes_to_process, length;
  1301. char payload[CELL_PAYLOAD_SIZE];
  1302. circuit_t *circ;
  1303. const unsigned domain = conn->base_.type == CONN_TYPE_AP ? LD_APP : LD_EXIT;
  1304. int sending_from_optimistic = 0;
  1305. const int sending_optimistically =
  1306. conn->base_.type == CONN_TYPE_AP &&
  1307. conn->base_.state != AP_CONN_STATE_OPEN;
  1308. entry_connection_t *entry_conn =
  1309. conn->base_.type == CONN_TYPE_AP ? EDGE_TO_ENTRY_CONN(conn) : NULL;
  1310. crypt_path_t *cpath_layer = conn->cpath_layer;
  1311. tor_assert(conn);
  1312. if (conn->base_.marked_for_close) {
  1313. log_warn(LD_BUG,
  1314. "called on conn that's already marked for close at %s:%d.",
  1315. conn->base_.marked_for_close_file, conn->base_.marked_for_close);
  1316. return 0;
  1317. }
  1318. if (max_cells && *max_cells <= 0)
  1319. return 0;
  1320. repeat_connection_edge_package_raw_inbuf:
  1321. circ = circuit_get_by_edge_conn(conn);
  1322. if (!circ) {
  1323. log_info(domain,"conn has no circuit! Closing.");
  1324. conn->end_reason = END_STREAM_REASON_CANT_ATTACH;
  1325. return -1;
  1326. }
  1327. if (circuit_consider_stop_edge_reading(circ, cpath_layer))
  1328. return 0;
  1329. if (conn->package_window <= 0) {
  1330. log_info(domain,"called with package_window %d. Skipping.",
  1331. conn->package_window);
  1332. connection_stop_reading(TO_CONN(conn));
  1333. return 0;
  1334. }
  1335. sending_from_optimistic = entry_conn &&
  1336. entry_conn->sending_optimistic_data != NULL;
  1337. if (PREDICT_UNLIKELY(sending_from_optimistic)) {
  1338. bytes_to_process = generic_buffer_len(entry_conn->sending_optimistic_data);
  1339. if (PREDICT_UNLIKELY(!bytes_to_process)) {
  1340. log_warn(LD_BUG, "sending_optimistic_data was non-NULL but empty");
  1341. bytes_to_process = connection_get_inbuf_len(TO_CONN(conn));
  1342. sending_from_optimistic = 0;
  1343. }
  1344. } else {
  1345. bytes_to_process = connection_get_inbuf_len(TO_CONN(conn));
  1346. }
  1347. if (!bytes_to_process)
  1348. return 0;
  1349. if (!package_partial && bytes_to_process < RELAY_PAYLOAD_SIZE)
  1350. return 0;
  1351. if (bytes_to_process > RELAY_PAYLOAD_SIZE) {
  1352. length = RELAY_PAYLOAD_SIZE;
  1353. } else {
  1354. length = bytes_to_process;
  1355. }
  1356. stats_n_data_bytes_packaged += length;
  1357. stats_n_data_cells_packaged += 1;
  1358. if (PREDICT_UNLIKELY(sending_from_optimistic)) {
  1359. /* XXXX We could be more efficient here by sometimes packing
  1360. * previously-sent optimistic data in the same cell with data
  1361. * from the inbuf. */
  1362. generic_buffer_get(entry_conn->sending_optimistic_data, payload, length);
  1363. if (!generic_buffer_len(entry_conn->sending_optimistic_data)) {
  1364. generic_buffer_free(entry_conn->sending_optimistic_data);
  1365. entry_conn->sending_optimistic_data = NULL;
  1366. }
  1367. } else {
  1368. connection_fetch_from_buf(payload, length, TO_CONN(conn));
  1369. }
  1370. log_debug(domain,"(%d) Packaging %d bytes (%d waiting).", conn->base_.s,
  1371. (int)length, (int)connection_get_inbuf_len(TO_CONN(conn)));
  1372. if (sending_optimistically && !sending_from_optimistic) {
  1373. /* This is new optimistic data; remember it in case we need to detach and
  1374. retry */
  1375. if (!entry_conn->pending_optimistic_data)
  1376. entry_conn->pending_optimistic_data = generic_buffer_new();
  1377. generic_buffer_add(entry_conn->pending_optimistic_data, payload, length);
  1378. }
  1379. if (connection_edge_send_command(conn, RELAY_COMMAND_DATA,
  1380. payload, length) < 0 )
  1381. /* circuit got marked for close, don't continue, don't need to mark conn */
  1382. return 0;
  1383. if (!cpath_layer) { /* non-rendezvous exit */
  1384. tor_assert(circ->package_window > 0);
  1385. circ->package_window--;
  1386. } else { /* we're an AP, or an exit on a rendezvous circ */
  1387. tor_assert(cpath_layer->package_window > 0);
  1388. cpath_layer->package_window--;
  1389. }
  1390. if (--conn->package_window <= 0) { /* is it 0 after decrement? */
  1391. connection_stop_reading(TO_CONN(conn));
  1392. log_debug(domain,"conn->package_window reached 0.");
  1393. circuit_consider_stop_edge_reading(circ, cpath_layer);
  1394. return 0; /* don't process the inbuf any more */
  1395. }
  1396. log_debug(domain,"conn->package_window is now %d",conn->package_window);
  1397. if (max_cells) {
  1398. *max_cells -= 1;
  1399. if (*max_cells <= 0)
  1400. return 0;
  1401. }
  1402. /* handle more if there's more, or return 0 if there isn't */
  1403. goto repeat_connection_edge_package_raw_inbuf;
  1404. }
  1405. /** Called when we've just received a relay data cell, when
  1406. * we've just finished flushing all bytes to stream <b>conn</b>,
  1407. * or when we've flushed *some* bytes to the stream <b>conn</b>.
  1408. *
  1409. * If conn->outbuf is not too full, and our deliver window is
  1410. * low, send back a suitable number of stream-level sendme cells.
  1411. */
  1412. void
  1413. connection_edge_consider_sending_sendme(edge_connection_t *conn)
  1414. {
  1415. circuit_t *circ;
  1416. if (connection_outbuf_too_full(TO_CONN(conn)))
  1417. return;
  1418. circ = circuit_get_by_edge_conn(conn);
  1419. if (!circ) {
  1420. /* this can legitimately happen if the destroy has already
  1421. * arrived and torn down the circuit */
  1422. log_info(LD_APP,"No circuit associated with conn. Skipping.");
  1423. return;
  1424. }
  1425. while (conn->deliver_window <= STREAMWINDOW_START - STREAMWINDOW_INCREMENT) {
  1426. log_debug(conn->base_.type == CONN_TYPE_AP ?LD_APP:LD_EXIT,
  1427. "Outbuf %d, Queuing stream sendme.",
  1428. (int)conn->base_.outbuf_flushlen);
  1429. conn->deliver_window += STREAMWINDOW_INCREMENT;
  1430. if (connection_edge_send_command(conn, RELAY_COMMAND_SENDME,
  1431. NULL, 0) < 0) {
  1432. log_warn(LD_APP,"connection_edge_send_command failed. Skipping.");
  1433. return; /* the circuit's closed, don't continue */
  1434. }
  1435. }
  1436. }
  1437. /** The circuit <b>circ</b> has received a circuit-level sendme
  1438. * (on hop <b>layer_hint</b>, if we're the OP). Go through all the
  1439. * attached streams and let them resume reading and packaging, if
  1440. * their stream windows allow it.
  1441. */
  1442. static void
  1443. circuit_resume_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
  1444. {
  1445. if (circuit_queue_streams_are_blocked(circ)) {
  1446. log_debug(layer_hint?LD_APP:LD_EXIT,"Too big queue, no resuming");
  1447. return;
  1448. }
  1449. log_debug(layer_hint?LD_APP:LD_EXIT,"resuming");
  1450. if (CIRCUIT_IS_ORIGIN(circ))
  1451. circuit_resume_edge_reading_helper(TO_ORIGIN_CIRCUIT(circ)->p_streams,
  1452. circ, layer_hint);
  1453. else
  1454. circuit_resume_edge_reading_helper(TO_OR_CIRCUIT(circ)->n_streams,
  1455. circ, layer_hint);
  1456. }
  1457. /** A helper function for circuit_resume_edge_reading() above.
  1458. * The arguments are the same, except that <b>conn</b> is the head
  1459. * of a linked list of edge streams that should each be considered.
  1460. */
  1461. static int
  1462. circuit_resume_edge_reading_helper(edge_connection_t *first_conn,
  1463. circuit_t *circ,
  1464. crypt_path_t *layer_hint)
  1465. {
  1466. edge_connection_t *conn;
  1467. int n_packaging_streams, n_streams_left;
  1468. int packaged_this_round;
  1469. int cells_on_queue;
  1470. int cells_per_conn;
  1471. edge_connection_t *chosen_stream = NULL;
  1472. /* How many cells do we have space for? It will be the minimum of
  1473. * the number needed to exhaust the package window, and the minimum
  1474. * needed to fill the cell queue. */
  1475. int max_to_package = circ->package_window;
  1476. if (CIRCUIT_IS_ORIGIN(circ)) {
  1477. cells_on_queue = circ->n_chan_cells.n;
  1478. } else {
  1479. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  1480. cells_on_queue = or_circ->p_chan_cells.n;
  1481. }
  1482. if (CELL_QUEUE_HIGHWATER_SIZE - cells_on_queue < max_to_package)
  1483. max_to_package = CELL_QUEUE_HIGHWATER_SIZE - cells_on_queue;
  1484. /* Once we used to start listening on the streams in the order they
  1485. * appeared in the linked list. That leads to starvation on the
  1486. * streams that appeared later on the list, since the first streams
  1487. * would always get to read first. Instead, we just pick a random
  1488. * stream on the list, and enable reading for streams starting at that
  1489. * point (and wrapping around as if the list were circular). It would
  1490. * probably be better to actually remember which streams we've
  1491. * serviced in the past, but this is simple and effective. */
  1492. /* Select a stream uniformly at random from the linked list. We
  1493. * don't need cryptographic randomness here. */
  1494. {
  1495. int num_streams = 0;
  1496. for (conn = first_conn; conn; conn = conn->next_stream) {
  1497. num_streams++;
  1498. if ((tor_weak_random() % num_streams)==0)
  1499. chosen_stream = conn;
  1500. /* Invariant: chosen_stream has been chosen uniformly at random from
  1501. * among the first num_streams streams on first_conn. */
  1502. }
  1503. }
  1504. /* Count how many non-marked streams there are that have anything on
  1505. * their inbuf, and enable reading on all of the connections. */
  1506. n_packaging_streams = 0;
  1507. /* Activate reading starting from the chosen stream */
  1508. for (conn=chosen_stream; conn; conn = conn->next_stream) {
  1509. /* Start reading for the streams starting from here */
  1510. if (conn->base_.marked_for_close || conn->package_window <= 0)
  1511. continue;
  1512. if (!layer_hint || conn->cpath_layer == layer_hint) {
  1513. connection_start_reading(TO_CONN(conn));
  1514. if (connection_get_inbuf_len(TO_CONN(conn)) > 0)
  1515. ++n_packaging_streams;
  1516. }
  1517. }
  1518. /* Go back and do the ones we skipped, circular-style */
  1519. for (conn = first_conn; conn != chosen_stream; conn = conn->next_stream) {
  1520. if (conn->base_.marked_for_close || conn->package_window <= 0)
  1521. continue;
  1522. if (!layer_hint || conn->cpath_layer == layer_hint) {
  1523. connection_start_reading(TO_CONN(conn));
  1524. if (connection_get_inbuf_len(TO_CONN(conn)) > 0)
  1525. ++n_packaging_streams;
  1526. }
  1527. }
  1528. if (n_packaging_streams == 0) /* avoid divide-by-zero */
  1529. return 0;
  1530. again:
  1531. cells_per_conn = CEIL_DIV(max_to_package, n_packaging_streams);
  1532. packaged_this_round = 0;
  1533. n_streams_left = 0;
  1534. /* Iterate over all connections. Package up to cells_per_conn cells on
  1535. * each. Update packaged_this_round with the total number of cells
  1536. * packaged, and n_streams_left with the number that still have data to
  1537. * package.
  1538. */
  1539. for (conn=first_conn; conn; conn=conn->next_stream) {
  1540. if (conn->base_.marked_for_close || conn->package_window <= 0)
  1541. continue;
  1542. if (!layer_hint || conn->cpath_layer == layer_hint) {
  1543. int n = cells_per_conn, r;
  1544. /* handle whatever might still be on the inbuf */
  1545. r = connection_edge_package_raw_inbuf(conn, 1, &n);
  1546. /* Note how many we packaged */
  1547. packaged_this_round += (cells_per_conn-n);
  1548. if (r<0) {
  1549. /* Problem while packaging. (We already sent an end cell if
  1550. * possible) */
  1551. connection_mark_for_close(TO_CONN(conn));
  1552. continue;
  1553. }
  1554. /* If there's still data to read, we'll be coming back to this stream. */
  1555. if (connection_get_inbuf_len(TO_CONN(conn)))
  1556. ++n_streams_left;
  1557. /* If the circuit won't accept any more data, return without looking
  1558. * at any more of the streams. Any connections that should be stopped
  1559. * have already been stopped by connection_edge_package_raw_inbuf. */
  1560. if (circuit_consider_stop_edge_reading(circ, layer_hint))
  1561. return -1;
  1562. /* XXXX should we also stop immediately if we fill up the cell queue?
  1563. * Probably. */
  1564. }
  1565. }
  1566. /* If we made progress, and we are willing to package more, and there are
  1567. * any streams left that want to package stuff... try again!
  1568. */
  1569. if (packaged_this_round && packaged_this_round < max_to_package &&
  1570. n_streams_left) {
  1571. max_to_package -= packaged_this_round;
  1572. n_packaging_streams = n_streams_left;
  1573. goto again;
  1574. }
  1575. return 0;
  1576. }
  1577. /** Check if the package window for <b>circ</b> is empty (at
  1578. * hop <b>layer_hint</b> if it's defined).
  1579. *
  1580. * If yes, tell edge streams to stop reading and return 1.
  1581. * Else return 0.
  1582. */
  1583. static int
  1584. circuit_consider_stop_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
  1585. {
  1586. edge_connection_t *conn = NULL;
  1587. unsigned domain = layer_hint ? LD_APP : LD_EXIT;
  1588. if (!layer_hint) {
  1589. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  1590. log_debug(domain,"considering circ->package_window %d",
  1591. circ->package_window);
  1592. if (circ->package_window <= 0) {
  1593. log_debug(domain,"yes, not-at-origin. stopped.");
  1594. for (conn = or_circ->n_streams; conn; conn=conn->next_stream)
  1595. connection_stop_reading(TO_CONN(conn));
  1596. return 1;
  1597. }
  1598. return 0;
  1599. }
  1600. /* else, layer hint is defined, use it */
  1601. log_debug(domain,"considering layer_hint->package_window %d",
  1602. layer_hint->package_window);
  1603. if (layer_hint->package_window <= 0) {
  1604. log_debug(domain,"yes, at-origin. stopped.");
  1605. for (conn = TO_ORIGIN_CIRCUIT(circ)->p_streams; conn;
  1606. conn=conn->next_stream) {
  1607. if (conn->cpath_layer == layer_hint)
  1608. connection_stop_reading(TO_CONN(conn));
  1609. }
  1610. return 1;
  1611. }
  1612. return 0;
  1613. }
  1614. /** Check if the deliver_window for circuit <b>circ</b> (at hop
  1615. * <b>layer_hint</b> if it's defined) is low enough that we should
  1616. * send a circuit-level sendme back down the circuit. If so, send
  1617. * enough sendmes that the window would be overfull if we sent any
  1618. * more.
  1619. */
  1620. static void
  1621. circuit_consider_sending_sendme(circuit_t *circ, crypt_path_t *layer_hint)
  1622. {
  1623. // log_fn(LOG_INFO,"Considering: layer_hint is %s",
  1624. // layer_hint ? "defined" : "null");
  1625. while ((layer_hint ? layer_hint->deliver_window : circ->deliver_window) <=
  1626. CIRCWINDOW_START - CIRCWINDOW_INCREMENT) {
  1627. log_debug(LD_CIRC,"Queuing circuit sendme.");
  1628. if (layer_hint)
  1629. layer_hint->deliver_window += CIRCWINDOW_INCREMENT;
  1630. else
  1631. circ->deliver_window += CIRCWINDOW_INCREMENT;
  1632. if (relay_send_command_from_edge(0, circ, RELAY_COMMAND_SENDME,
  1633. NULL, 0, layer_hint) < 0) {
  1634. log_warn(LD_CIRC,
  1635. "relay_send_command_from_edge failed. Circuit's closed.");
  1636. return; /* the circuit's closed, don't continue */
  1637. }
  1638. }
  1639. }
  1640. #ifdef ACTIVE_CIRCUITS_PARANOIA
  1641. #define assert_cmux_ok_paranoid(chan) \
  1642. assert_circuit_mux_okay(chan)
  1643. #else
  1644. #define assert_cmux_ok_paranoid(chan)
  1645. #endif
  1646. /** The total number of cells we have allocated from the memory pool. */
  1647. static int total_cells_allocated = 0;
  1648. /** A memory pool to allocate packed_cell_t objects. */
  1649. static mp_pool_t *cell_pool = NULL;
  1650. /** Memory pool to allocate insertion_time_elem_t objects used for cell
  1651. * statistics. */
  1652. static mp_pool_t *it_pool = NULL;
  1653. /** Allocate structures to hold cells. */
  1654. void
  1655. init_cell_pool(void)
  1656. {
  1657. tor_assert(!cell_pool);
  1658. cell_pool = mp_pool_new(sizeof(packed_cell_t), 128*1024);
  1659. }
  1660. /** Free all storage used to hold cells (and insertion times if we measure
  1661. * cell statistics). */
  1662. void
  1663. free_cell_pool(void)
  1664. {
  1665. /* Maybe we haven't called init_cell_pool yet; need to check for it. */
  1666. if (cell_pool) {
  1667. mp_pool_destroy(cell_pool);
  1668. cell_pool = NULL;
  1669. }
  1670. if (it_pool) {
  1671. mp_pool_destroy(it_pool);
  1672. it_pool = NULL;
  1673. }
  1674. }
  1675. /** Free excess storage in cell pool. */
  1676. void
  1677. clean_cell_pool(void)
  1678. {
  1679. tor_assert(cell_pool);
  1680. mp_pool_clean(cell_pool, 0, 1);
  1681. }
  1682. /** Release storage held by <b>cell</b>. */
  1683. static INLINE void
  1684. packed_cell_free_unchecked(packed_cell_t *cell)
  1685. {
  1686. --total_cells_allocated;
  1687. mp_pool_release(cell);
  1688. }
  1689. /** Allocate and return a new packed_cell_t. */
  1690. static INLINE packed_cell_t *
  1691. packed_cell_new(void)
  1692. {
  1693. ++total_cells_allocated;
  1694. return mp_pool_get(cell_pool);
  1695. }
  1696. /** Return a packed cell used outside by channel_t lower layer */
  1697. void
  1698. packed_cell_free(packed_cell_t *cell)
  1699. {
  1700. packed_cell_free_unchecked(cell);
  1701. }
  1702. /** Log current statistics for cell pool allocation at log level
  1703. * <b>severity</b>. */
  1704. void
  1705. dump_cell_pool_usage(int severity)
  1706. {
  1707. circuit_t *c;
  1708. int n_circs = 0;
  1709. int n_cells = 0;
  1710. for (c = circuit_get_global_list_(); c; c = c->next) {
  1711. n_cells += c->n_chan_cells.n;
  1712. if (!CIRCUIT_IS_ORIGIN(c))
  1713. n_cells += TO_OR_CIRCUIT(c)->p_chan_cells.n;
  1714. ++n_circs;
  1715. }
  1716. log(severity, LD_MM, "%d cells allocated on %d circuits. %d cells leaked.",
  1717. n_cells, n_circs, total_cells_allocated - n_cells);
  1718. mp_pool_log_status(cell_pool, severity);
  1719. }
  1720. /** Allocate a new copy of packed <b>cell</b>. */
  1721. static INLINE packed_cell_t *
  1722. packed_cell_copy(const cell_t *cell, int wide_circ_ids)
  1723. {
  1724. packed_cell_t *c = packed_cell_new();
  1725. cell_pack(c, cell, wide_circ_ids);
  1726. c->next = NULL;
  1727. return c;
  1728. }
  1729. /** Append <b>cell</b> to the end of <b>queue</b>. */
  1730. void
  1731. cell_queue_append(cell_queue_t *queue, packed_cell_t *cell)
  1732. {
  1733. if (queue->tail) {
  1734. tor_assert(!queue->tail->next);
  1735. queue->tail->next = cell;
  1736. } else {
  1737. queue->head = cell;
  1738. }
  1739. queue->tail = cell;
  1740. cell->next = NULL;
  1741. ++queue->n;
  1742. }
  1743. /** Append a newly allocated copy of <b>cell</b> to the end of <b>queue</b> */
  1744. void
  1745. cell_queue_append_packed_copy(cell_queue_t *queue, const cell_t *cell,
  1746. int wide_circ_ids)
  1747. {
  1748. packed_cell_t *copy = packed_cell_copy(cell, wide_circ_ids);
  1749. /* Remember the time when this cell was put in the queue. */
  1750. if (get_options()->CellStatistics) {
  1751. struct timeval now;
  1752. uint32_t added;
  1753. insertion_time_queue_t *it_queue = queue->insertion_times;
  1754. if (!it_pool)
  1755. it_pool = mp_pool_new(sizeof(insertion_time_elem_t), 1024);
  1756. tor_gettimeofday_cached(&now);
  1757. #define SECONDS_IN_A_DAY 86400L
  1758. added = (uint32_t)(((now.tv_sec % SECONDS_IN_A_DAY) * 100L)
  1759. + ((uint32_t)now.tv_usec / (uint32_t)10000L));
  1760. if (!it_queue) {
  1761. it_queue = tor_malloc_zero(sizeof(insertion_time_queue_t));
  1762. queue->insertion_times = it_queue;
  1763. }
  1764. if (it_queue->last && it_queue->last->insertion_time == added) {
  1765. it_queue->last->counter++;
  1766. } else {
  1767. insertion_time_elem_t *elem = mp_pool_get(it_pool);
  1768. elem->next = NULL;
  1769. elem->insertion_time = added;
  1770. elem->counter = 1;
  1771. if (it_queue->last) {
  1772. it_queue->last->next = elem;
  1773. it_queue->last = elem;
  1774. } else {
  1775. it_queue->first = it_queue->last = elem;
  1776. }
  1777. }
  1778. }
  1779. cell_queue_append(queue, copy);
  1780. }
  1781. /** Remove and free every cell in <b>queue</b>. */
  1782. void
  1783. cell_queue_clear(cell_queue_t *queue)
  1784. {
  1785. packed_cell_t *cell, *next;
  1786. cell = queue->head;
  1787. while (cell) {
  1788. next = cell->next;
  1789. packed_cell_free_unchecked(cell);
  1790. cell = next;
  1791. }
  1792. queue->head = queue->tail = NULL;
  1793. queue->n = 0;
  1794. if (queue->insertion_times) {
  1795. while (queue->insertion_times->first) {
  1796. insertion_time_elem_t *elem = queue->insertion_times->first;
  1797. queue->insertion_times->first = elem->next;
  1798. mp_pool_release(elem);
  1799. }
  1800. tor_free(queue->insertion_times);
  1801. }
  1802. }
  1803. /** Extract and return the cell at the head of <b>queue</b>; return NULL if
  1804. * <b>queue</b> is empty. */
  1805. static INLINE packed_cell_t *
  1806. cell_queue_pop(cell_queue_t *queue)
  1807. {
  1808. packed_cell_t *cell = queue->head;
  1809. if (!cell)
  1810. return NULL;
  1811. queue->head = cell->next;
  1812. if (cell == queue->tail) {
  1813. tor_assert(!queue->head);
  1814. queue->tail = NULL;
  1815. }
  1816. --queue->n;
  1817. return cell;
  1818. }
  1819. /**
  1820. * Update the number of cells available on the circuit's n_chan or p_chan's
  1821. * circuit mux.
  1822. */
  1823. void
  1824. update_circuit_on_cmux(circuit_t *circ, cell_direction_t direction)
  1825. {
  1826. channel_t *chan = NULL;
  1827. or_circuit_t *or_circ = NULL;
  1828. circuitmux_t *cmux = NULL;
  1829. tor_assert(circ);
  1830. /* Okay, get the channel */
  1831. if (direction == CELL_DIRECTION_OUT) {
  1832. chan = circ->n_chan;
  1833. } else {
  1834. or_circ = TO_OR_CIRCUIT(circ);
  1835. chan = or_circ->p_chan;
  1836. }
  1837. tor_assert(chan);
  1838. tor_assert(chan->cmux);
  1839. /* Now get the cmux */
  1840. cmux = chan->cmux;
  1841. /* Cmux sanity check */
  1842. tor_assert(circuitmux_is_circuit_attached(cmux, circ));
  1843. tor_assert(circuitmux_attached_circuit_direction(cmux, circ) == direction);
  1844. assert_cmux_ok_paranoid(chan);
  1845. /* Update the number of cells we have for the circuit mux */
  1846. if (direction == CELL_DIRECTION_OUT) {
  1847. circuitmux_set_num_cells(cmux, circ, circ->n_chan_cells.n);
  1848. } else {
  1849. circuitmux_set_num_cells(cmux, circ, or_circ->p_chan_cells.n);
  1850. }
  1851. assert_cmux_ok_paranoid(chan);
  1852. }
  1853. /** Remove all circuits from the cmux on <b>chan</b>. */
  1854. void
  1855. channel_unlink_all_circuits(channel_t *chan)
  1856. {
  1857. tor_assert(chan);
  1858. tor_assert(chan->cmux);
  1859. circuitmux_detach_all_circuits(chan->cmux);
  1860. chan->num_n_circuits = 0;
  1861. chan->num_p_circuits = 0;
  1862. }
  1863. /** Block (if <b>block</b> is true) or unblock (if <b>block</b> is false)
  1864. * every edge connection that is using <b>circ</b> to write to <b>chan</b>,
  1865. * and start or stop reading as appropriate.
  1866. *
  1867. * If <b>stream_id</b> is nonzero, block only the edge connection whose
  1868. * stream_id matches it.
  1869. *
  1870. * Returns the number of streams whose status we changed.
  1871. */
  1872. static int
  1873. set_streams_blocked_on_circ(circuit_t *circ, channel_t *chan,
  1874. int block, streamid_t stream_id)
  1875. {
  1876. edge_connection_t *edge = NULL;
  1877. int n = 0;
  1878. if (circ->n_chan == chan) {
  1879. circ->streams_blocked_on_n_chan = block;
  1880. if (CIRCUIT_IS_ORIGIN(circ))
  1881. edge = TO_ORIGIN_CIRCUIT(circ)->p_streams;
  1882. } else {
  1883. circ->streams_blocked_on_p_chan = block;
  1884. tor_assert(!CIRCUIT_IS_ORIGIN(circ));
  1885. edge = TO_OR_CIRCUIT(circ)->n_streams;
  1886. }
  1887. for (; edge; edge = edge->next_stream) {
  1888. connection_t *conn = TO_CONN(edge);
  1889. if (stream_id && edge->stream_id != stream_id)
  1890. continue;
  1891. if (edge->edge_blocked_on_circ != block) {
  1892. ++n;
  1893. edge->edge_blocked_on_circ = block;
  1894. }
  1895. if (!conn->read_event && !HAS_BUFFEREVENT(conn)) {
  1896. /* This connection is a placeholder for something; probably a DNS
  1897. * request. It can't actually stop or start reading.*/
  1898. continue;
  1899. }
  1900. if (block) {
  1901. if (connection_is_reading(conn))
  1902. connection_stop_reading(conn);
  1903. } else {
  1904. /* Is this right? */
  1905. if (!connection_is_reading(conn))
  1906. connection_start_reading(conn);
  1907. }
  1908. }
  1909. return n;
  1910. }
  1911. /** Pull as many cells as possible (but no more than <b>max</b>) from the
  1912. * queue of the first active circuit on <b>chan</b>, and write them to
  1913. * <b>chan</b>-&gt;outbuf. Return the number of cells written. Advance
  1914. * the active circuit pointer to the next active circuit in the ring. */
  1915. int
  1916. channel_flush_from_first_active_circuit(channel_t *chan, int max)
  1917. {
  1918. circuitmux_t *cmux = NULL;
  1919. int n_flushed = 0;
  1920. cell_queue_t *queue;
  1921. circuit_t *circ;
  1922. or_circuit_t *or_circ;
  1923. int streams_blocked;
  1924. packed_cell_t *cell;
  1925. /* Get the cmux */
  1926. tor_assert(chan);
  1927. tor_assert(chan->cmux);
  1928. cmux = chan->cmux;
  1929. /* Main loop: pick a circuit, send a cell, update the cmux */
  1930. while (n_flushed < max) {
  1931. circ = circuitmux_get_first_active_circuit(cmux);
  1932. /* If it returns NULL, no cells left to send */
  1933. if (!circ) break;
  1934. assert_cmux_ok_paranoid(chan);
  1935. if (circ->n_chan == chan) {
  1936. queue = &circ->n_chan_cells;
  1937. streams_blocked = circ->streams_blocked_on_n_chan;
  1938. } else {
  1939. or_circ = TO_OR_CIRCUIT(circ);
  1940. tor_assert(or_circ->p_chan == chan);
  1941. queue = &TO_OR_CIRCUIT(circ)->p_chan_cells;
  1942. streams_blocked = circ->streams_blocked_on_p_chan;
  1943. }
  1944. /* Circuitmux told us this was active, so it should have cells */
  1945. tor_assert(queue->n > 0);
  1946. /*
  1947. * Get just one cell here; once we've sent it, that can change the circuit
  1948. * selection, so we have to loop around for another even if this circuit
  1949. * has more than one.
  1950. */
  1951. cell = cell_queue_pop(queue);
  1952. /* Calculate the exact time that this cell has spent in the queue. */
  1953. if (get_options()->CellStatistics && !CIRCUIT_IS_ORIGIN(circ)) {
  1954. struct timeval tvnow;
  1955. uint32_t flushed;
  1956. uint32_t cell_waiting_time;
  1957. insertion_time_queue_t *it_queue = queue->insertion_times;
  1958. tor_gettimeofday_cached(&tvnow);
  1959. flushed = (uint32_t)((tvnow.tv_sec % SECONDS_IN_A_DAY) * 100L +
  1960. (uint32_t)tvnow.tv_usec / (uint32_t)10000L);
  1961. if (!it_queue || !it_queue->first) {
  1962. log_info(LD_GENERAL, "Cannot determine insertion time of cell. "
  1963. "Looks like the CellStatistics option was "
  1964. "recently enabled.");
  1965. } else {
  1966. insertion_time_elem_t *elem = it_queue->first;
  1967. or_circ = TO_OR_CIRCUIT(circ);
  1968. cell_waiting_time =
  1969. (uint32_t)((flushed * 10L + SECONDS_IN_A_DAY * 1000L -
  1970. elem->insertion_time * 10L) %
  1971. (SECONDS_IN_A_DAY * 1000L));
  1972. #undef SECONDS_IN_A_DAY
  1973. elem->counter--;
  1974. if (elem->counter < 1) {
  1975. it_queue->first = elem->next;
  1976. if (elem == it_queue->last)
  1977. it_queue->last = NULL;
  1978. mp_pool_release(elem);
  1979. }
  1980. or_circ->total_cell_waiting_time += cell_waiting_time;
  1981. or_circ->processed_cells++;
  1982. }
  1983. }
  1984. /* If we just flushed our queue and this circuit is used for a
  1985. * tunneled directory request, possibly advance its state. */
  1986. if (queue->n == 0 && chan->dirreq_id)
  1987. geoip_change_dirreq_state(chan->dirreq_id,
  1988. DIRREQ_TUNNELED,
  1989. DIRREQ_CIRC_QUEUE_FLUSHED);
  1990. /* Now send the cell */
  1991. channel_write_packed_cell(chan, cell);
  1992. cell = NULL;
  1993. /*
  1994. * Don't packed_cell_free_unchecked(cell) here because the channel will
  1995. * do so when it gets out of the channel queue (probably already did, in
  1996. * which case that was an immediate double-free bug).
  1997. */
  1998. /* Update the counter */
  1999. ++n_flushed;
  2000. /*
  2001. * Now update the cmux; tell it we've just sent a cell, and how many
  2002. * we have left.
  2003. */
  2004. circuitmux_notify_xmit_cells(cmux, circ, 1);
  2005. circuitmux_set_num_cells(cmux, circ, queue->n);
  2006. if (queue->n == 0)
  2007. log_debug(LD_GENERAL, "Made a circuit inactive.");
  2008. /* Is the cell queue low enough to unblock all the streams that are waiting
  2009. * to write to this circuit? */
  2010. if (streams_blocked && queue->n <= CELL_QUEUE_LOWWATER_SIZE)
  2011. set_streams_blocked_on_circ(circ, chan, 0, 0); /* unblock streams */
  2012. /* If n_flushed < max still, loop around and pick another circuit */
  2013. }
  2014. /* Okay, we're done sending now */
  2015. assert_cmux_ok_paranoid(chan);
  2016. return n_flushed;
  2017. }
  2018. /** Add <b>cell</b> to the queue of <b>circ</b> writing to <b>chan</b>
  2019. * transmitting in <b>direction</b>. */
  2020. void
  2021. append_cell_to_circuit_queue(circuit_t *circ, channel_t *chan,
  2022. cell_t *cell, cell_direction_t direction,
  2023. streamid_t fromstream)
  2024. {
  2025. cell_queue_t *queue;
  2026. int streams_blocked;
  2027. if (circ->marked_for_close)
  2028. return;
  2029. if (direction == CELL_DIRECTION_OUT) {
  2030. queue = &circ->n_chan_cells;
  2031. streams_blocked = circ->streams_blocked_on_n_chan;
  2032. } else {
  2033. or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
  2034. queue = &orcirc->p_chan_cells;
  2035. streams_blocked = circ->streams_blocked_on_p_chan;
  2036. }
  2037. cell_queue_append_packed_copy(queue, cell, chan->wide_circ_ids);
  2038. /* If we have too many cells on the circuit, we should stop reading from
  2039. * the edge streams for a while. */
  2040. if (!streams_blocked && queue->n >= CELL_QUEUE_HIGHWATER_SIZE)
  2041. set_streams_blocked_on_circ(circ, chan, 1, 0); /* block streams */
  2042. if (streams_blocked && fromstream) {
  2043. /* This edge connection is apparently not blocked; block it. */
  2044. set_streams_blocked_on_circ(circ, chan, 1, fromstream);
  2045. }
  2046. update_circuit_on_cmux(circ, direction);
  2047. if (queue->n == 1) {
  2048. /* This was the first cell added to the queue. We just made this
  2049. * circuit active. */
  2050. log_debug(LD_GENERAL, "Made a circuit active.");
  2051. }
  2052. if (!channel_has_queued_writes(chan)) {
  2053. /* There is no data at all waiting to be sent on the outbuf. Add a
  2054. * cell, so that we can notice when it gets flushed, flushed_some can
  2055. * get called, and we can start putting more data onto the buffer then.
  2056. */
  2057. log_debug(LD_GENERAL, "Primed a buffer.");
  2058. channel_flush_from_first_active_circuit(chan, 1);
  2059. }
  2060. }
  2061. /** Append an encoded value of <b>addr</b> to <b>payload_out</b>, which must
  2062. * have at least 18 bytes of free space. The encoding is, as specified in
  2063. * tor-spec.txt:
  2064. * RESOLVED_TYPE_IPV4 or RESOLVED_TYPE_IPV6 [1 byte]
  2065. * LENGTH [1 byte]
  2066. * ADDRESS [length bytes]
  2067. * Return the number of bytes added, or -1 on error */
  2068. int
  2069. append_address_to_payload(uint8_t *payload_out, const tor_addr_t *addr)
  2070. {
  2071. uint32_t a;
  2072. switch (tor_addr_family(addr)) {
  2073. case AF_INET:
  2074. payload_out[0] = RESOLVED_TYPE_IPV4;
  2075. payload_out[1] = 4;
  2076. a = tor_addr_to_ipv4n(addr);
  2077. memcpy(payload_out+2, &a, 4);
  2078. return 6;
  2079. case AF_INET6:
  2080. payload_out[0] = RESOLVED_TYPE_IPV6;
  2081. payload_out[1] = 16;
  2082. memcpy(payload_out+2, tor_addr_to_in6_addr8(addr), 16);
  2083. return 18;
  2084. case AF_UNSPEC:
  2085. default:
  2086. return -1;
  2087. }
  2088. }
  2089. /** Given <b>payload_len</b> bytes at <b>payload</b>, starting with an address
  2090. * encoded as by append_address_to_payload(), try to decode the address into
  2091. * *<b>addr_out</b>. Return the next byte in the payload after the address on
  2092. * success, or NULL on failure. */
  2093. const uint8_t *
  2094. decode_address_from_payload(tor_addr_t *addr_out, const uint8_t *payload,
  2095. int payload_len)
  2096. {
  2097. if (payload_len < 2)
  2098. return NULL;
  2099. if (payload_len < 2+payload[1])
  2100. return NULL;
  2101. switch (payload[0]) {
  2102. case RESOLVED_TYPE_IPV4:
  2103. if (payload[1] != 4)
  2104. return NULL;
  2105. tor_addr_from_ipv4n(addr_out, get_uint32(payload+2));
  2106. break;
  2107. case RESOLVED_TYPE_IPV6:
  2108. if (payload[1] != 16)
  2109. return NULL;
  2110. tor_addr_from_ipv6_bytes(addr_out, (char*)(payload+2));
  2111. break;
  2112. default:
  2113. tor_addr_make_unspec(addr_out);
  2114. break;
  2115. }
  2116. return payload + 2 + payload[1];
  2117. }
  2118. /** Remove all the cells queued on <b>circ</b> for <b>chan</b>. */
  2119. void
  2120. circuit_clear_cell_queue(circuit_t *circ, channel_t *chan)
  2121. {
  2122. cell_queue_t *queue;
  2123. cell_direction_t direction;
  2124. if (circ->n_chan == chan) {
  2125. queue = &circ->n_chan_cells;
  2126. direction = CELL_DIRECTION_OUT;
  2127. } else {
  2128. or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
  2129. tor_assert(orcirc->p_chan == chan);
  2130. queue = &orcirc->p_chan_cells;
  2131. direction = CELL_DIRECTION_IN;
  2132. }
  2133. /* Clear the queue */
  2134. cell_queue_clear(queue);
  2135. /* Update the cell counter in the cmux */
  2136. update_circuit_on_cmux(circ, direction);
  2137. }
  2138. /** Fail with an assert if the circuit mux on chan is corrupt
  2139. */
  2140. void
  2141. assert_circuit_mux_okay(channel_t *chan)
  2142. {
  2143. tor_assert(chan);
  2144. tor_assert(chan->cmux);
  2145. circuitmux_assert_okay(chan->cmux);
  2146. }
  2147. /** Return 1 if we shouldn't restart reading on this circuit, even if
  2148. * we get a SENDME. Else return 0.
  2149. */
  2150. static int
  2151. circuit_queue_streams_are_blocked(circuit_t *circ)
  2152. {
  2153. if (CIRCUIT_IS_ORIGIN(circ)) {
  2154. return circ->streams_blocked_on_n_chan;
  2155. } else {
  2156. return circ->streams_blocked_on_p_chan;
  2157. }
  2158. }