relay.c 86 KB

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