relay.c 109 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060
  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-2017, 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. * This is a core modules that makes Tor work. It's responsible for
  12. * dealing with RELAY cells (the ones that travel more than one hop along a
  13. * circuit), by:
  14. * <ul>
  15. * <li>constructing relays cells,
  16. * <li>encrypting relay cells,
  17. * <li>decrypting relay cells,
  18. * <li>demultiplexing relay cells as they arrive on a connection,
  19. * <li>queueing relay cells for retransmission,
  20. * <li>or handling relay cells that are for us to receive (as an exit or a
  21. * client).
  22. * </ul>
  23. *
  24. * RELAY cells are generated throughout the code at the client or relay side,
  25. * using relay_send_command_from_edge() or one of the functions like
  26. * connection_edge_send_command() that calls it. Of particular interest is
  27. * connection_edge_package_raw_inbuf(), which takes information that has
  28. * arrived on an edge connection socket, and packages it as a RELAY_DATA cell
  29. * -- this is how information is actually sent across the Tor network. The
  30. * cryptography for these functions is handled deep in
  31. * circuit_package_relay_cell(), which either adds a single layer of
  32. * encryption (if we're an exit), or multiple layers (if we're the origin of
  33. * the circuit). After construction and encryption, the RELAY cells are
  34. * passed to append_cell_to_circuit_queue(), which queues them for
  35. * transmission and tells the circuitmux (see circuitmux.c) that the circuit
  36. * is waiting to send something.
  37. *
  38. * Incoming RELAY cells arrive at circuit_receive_relay_cell(), called from
  39. * command.c. There they are decrypted and, if they are for us, are passed to
  40. * connection_edge_process_relay_cell(). If they're not for us, they're
  41. * re-queued for retransmission again with append_cell_to_circuit_queue().
  42. *
  43. * The connection_edge_process_relay_cell() function handles all the different
  44. * types of relay cells, launching requests or transmitting data as needed.
  45. **/
  46. #define RELAY_PRIVATE
  47. #include "or.h"
  48. #include "addressmap.h"
  49. #include "backtrace.h"
  50. #include "buffers.h"
  51. #include "channel.h"
  52. #include "circpathbias.h"
  53. #include "circuitbuild.h"
  54. #include "circuitlist.h"
  55. #include "circuituse.h"
  56. #include "compress.h"
  57. #include "config.h"
  58. #include "connection.h"
  59. #include "connection_edge.h"
  60. #include "connection_or.h"
  61. #include "control.h"
  62. #include "crypto_rand.h"
  63. #include "crypto_util.h"
  64. #include "directory.h"
  65. #include "geoip.h"
  66. #include "hs_cache.h"
  67. #include "main.h"
  68. #include "networkstatus.h"
  69. #include "nodelist.h"
  70. #include "onion.h"
  71. #include "policies.h"
  72. #include "reasons.h"
  73. #include "relay.h"
  74. #include "relay_crypto.h"
  75. #include "rendcache.h"
  76. #include "rendcommon.h"
  77. #include "router.h"
  78. #include "routerlist.h"
  79. #include "routerparse.h"
  80. #include "scheduler.h"
  81. #include "rephist.h"
  82. #include "dir_connection_st.h"
  83. #include "entry_connection_st.h"
  84. #include "or_circuit_st.h"
  85. #include "origin_circuit_st.h"
  86. static edge_connection_t *relay_lookup_conn(circuit_t *circ, cell_t *cell,
  87. cell_direction_t cell_direction,
  88. crypt_path_t *layer_hint);
  89. static void circuit_consider_sending_sendme(circuit_t *circ,
  90. crypt_path_t *layer_hint);
  91. static void circuit_resume_edge_reading(circuit_t *circ,
  92. crypt_path_t *layer_hint);
  93. static int circuit_resume_edge_reading_helper(edge_connection_t *conn,
  94. circuit_t *circ,
  95. crypt_path_t *layer_hint);
  96. static int circuit_consider_stop_edge_reading(circuit_t *circ,
  97. crypt_path_t *layer_hint);
  98. static int circuit_queue_streams_are_blocked(circuit_t *circ);
  99. static void adjust_exit_policy_from_exitpolicy_failure(origin_circuit_t *circ,
  100. entry_connection_t *conn,
  101. node_t *node,
  102. const tor_addr_t *addr);
  103. /** Stop reading on edge connections when we have this many cells
  104. * waiting on the appropriate queue. */
  105. #define CELL_QUEUE_HIGHWATER_SIZE 256
  106. /** Start reading from edge connections again when we get down to this many
  107. * cells. */
  108. #define CELL_QUEUE_LOWWATER_SIZE 64
  109. /** Stats: how many relay cells have originated at this hop, or have
  110. * been relayed onward (not recognized at this hop)?
  111. */
  112. uint64_t stats_n_relay_cells_relayed = 0;
  113. /** Stats: how many relay cells have been delivered to streams at this
  114. * hop?
  115. */
  116. uint64_t stats_n_relay_cells_delivered = 0;
  117. /** Stats: how many circuits have we closed due to the cell queue limit being
  118. * reached (see append_cell_to_circuit_queue()) */
  119. uint64_t stats_n_circ_max_cell_reached = 0;
  120. /** Used to tell which stream to read from first on a circuit. */
  121. static tor_weak_rng_t stream_choice_rng = TOR_WEAK_RNG_INIT;
  122. /**
  123. * Update channel usage state based on the type of relay cell and
  124. * circuit properties.
  125. *
  126. * This is needed to determine if a client channel is being
  127. * used for application traffic, and if a relay channel is being
  128. * used for multihop circuits and application traffic. The decision
  129. * to pad in channelpadding.c depends upon this info (as well as
  130. * consensus parameters) to decide what channels to pad.
  131. */
  132. static void
  133. circuit_update_channel_usage(circuit_t *circ, cell_t *cell)
  134. {
  135. if (CIRCUIT_IS_ORIGIN(circ)) {
  136. /*
  137. * The client state was first set much earlier in
  138. * circuit_send_next_onion_skin(), so we can start padding as early as
  139. * possible.
  140. *
  141. * However, if padding turns out to be expensive, we may want to not do
  142. * it until actual application traffic starts flowing (which is controlled
  143. * via consensus param nf_pad_before_usage).
  144. *
  145. * So: If we're an origin circuit and we've created a full length circuit,
  146. * then any CELL_RELAY cell means application data. Increase the usage
  147. * state of the channel to indicate this.
  148. *
  149. * We want to wait for CELL_RELAY specifically here, so we know that
  150. * the channel was definitely being used for data and not for extends.
  151. * By default, we pad as soon as a channel has been used for *any*
  152. * circuits, so this state is irrelevant to the padding decision in
  153. * the default case. However, if padding turns out to be expensive,
  154. * we would like the ability to avoid padding until we're absolutely
  155. * sure that a channel is used for enough application data to be worth
  156. * padding.
  157. *
  158. * (So it does not matter that CELL_RELAY_EARLY can actually contain
  159. * application data. This is only a load reducing option and that edge
  160. * case does not matter if we're desperately trying to reduce overhead
  161. * anyway. See also consensus parameter nf_pad_before_usage).
  162. */
  163. if (BUG(!circ->n_chan))
  164. return;
  165. if (circ->n_chan->channel_usage == CHANNEL_USED_FOR_FULL_CIRCS &&
  166. cell->command == CELL_RELAY) {
  167. circ->n_chan->channel_usage = CHANNEL_USED_FOR_USER_TRAFFIC;
  168. }
  169. } else {
  170. /* If we're a relay circuit, the question is more complicated. Basically:
  171. * we only want to pad connections that carry multihop (anonymous)
  172. * circuits.
  173. *
  174. * We assume we're more than one hop if either the previous hop
  175. * is not a client, or if the previous hop is a client and there's
  176. * a next hop. Then, circuit traffic starts at RELAY_EARLY, and
  177. * user application traffic starts when we see RELAY cells.
  178. */
  179. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  180. if (BUG(!or_circ->p_chan))
  181. return;
  182. if (!channel_is_client(or_circ->p_chan) ||
  183. (channel_is_client(or_circ->p_chan) && circ->n_chan)) {
  184. if (cell->command == CELL_RELAY_EARLY) {
  185. if (or_circ->p_chan->channel_usage < CHANNEL_USED_FOR_FULL_CIRCS) {
  186. or_circ->p_chan->channel_usage = CHANNEL_USED_FOR_FULL_CIRCS;
  187. }
  188. } else if (cell->command == CELL_RELAY) {
  189. or_circ->p_chan->channel_usage = CHANNEL_USED_FOR_USER_TRAFFIC;
  190. }
  191. }
  192. }
  193. }
  194. /** Receive a relay cell:
  195. * - Crypt it (encrypt if headed toward the origin or if we <b>are</b> the
  196. * origin; decrypt if we're headed toward the exit).
  197. * - Check if recognized (if exitward).
  198. * - If recognized and the digest checks out, then find if there's a stream
  199. * that the cell is intended for, and deliver it to the right
  200. * connection_edge.
  201. * - If not recognized, then we need to relay it: append it to the appropriate
  202. * cell_queue on <b>circ</b>.
  203. *
  204. * Return -<b>reason</b> on failure.
  205. */
  206. int
  207. circuit_receive_relay_cell(cell_t *cell, circuit_t *circ,
  208. cell_direction_t cell_direction)
  209. {
  210. channel_t *chan = NULL;
  211. crypt_path_t *layer_hint=NULL;
  212. char recognized=0;
  213. int reason;
  214. tor_assert(cell);
  215. tor_assert(circ);
  216. tor_assert(cell_direction == CELL_DIRECTION_OUT ||
  217. cell_direction == CELL_DIRECTION_IN);
  218. if (circ->marked_for_close)
  219. return 0;
  220. if (relay_decrypt_cell(circ, cell, cell_direction, &layer_hint, &recognized)
  221. < 0) {
  222. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  223. "relay crypt failed. Dropping connection.");
  224. return -END_CIRC_REASON_INTERNAL;
  225. }
  226. circuit_update_channel_usage(circ, cell);
  227. if (recognized) {
  228. edge_connection_t *conn = NULL;
  229. if (circ->purpose == CIRCUIT_PURPOSE_PATH_BIAS_TESTING) {
  230. pathbias_check_probe_response(circ, cell);
  231. /* We need to drop this cell no matter what to avoid code that expects
  232. * a certain purpose (such as the hidserv code). */
  233. return 0;
  234. }
  235. conn = relay_lookup_conn(circ, cell, cell_direction, layer_hint);
  236. if (cell_direction == CELL_DIRECTION_OUT) {
  237. ++stats_n_relay_cells_delivered;
  238. log_debug(LD_OR,"Sending away from origin.");
  239. if ((reason=connection_edge_process_relay_cell(cell, circ, conn, NULL))
  240. < 0) {
  241. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  242. "connection_edge_process_relay_cell (away from origin) "
  243. "failed.");
  244. return reason;
  245. }
  246. }
  247. if (cell_direction == CELL_DIRECTION_IN) {
  248. ++stats_n_relay_cells_delivered;
  249. log_debug(LD_OR,"Sending to origin.");
  250. if ((reason = connection_edge_process_relay_cell(cell, circ, conn,
  251. layer_hint)) < 0) {
  252. /* If a client is trying to connect to unknown hidden service port,
  253. * END_CIRC_AT_ORIGIN is sent back so we can then close the circuit.
  254. * Do not log warn as this is an expected behavior for a service. */
  255. if (reason != END_CIRC_AT_ORIGIN) {
  256. log_warn(LD_OR,
  257. "connection_edge_process_relay_cell (at origin) failed.");
  258. }
  259. return reason;
  260. }
  261. }
  262. return 0;
  263. }
  264. /* not recognized. pass it on. */
  265. if (cell_direction == CELL_DIRECTION_OUT) {
  266. cell->circ_id = circ->n_circ_id; /* switch it */
  267. chan = circ->n_chan;
  268. } else if (! CIRCUIT_IS_ORIGIN(circ)) {
  269. cell->circ_id = TO_OR_CIRCUIT(circ)->p_circ_id; /* switch it */
  270. chan = TO_OR_CIRCUIT(circ)->p_chan;
  271. } else {
  272. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  273. "Dropping unrecognized inbound cell on origin circuit.");
  274. /* If we see unrecognized cells on path bias testing circs,
  275. * it's bad mojo. Those circuits need to die.
  276. * XXX: Shouldn't they always die? */
  277. if (circ->purpose == CIRCUIT_PURPOSE_PATH_BIAS_TESTING) {
  278. TO_ORIGIN_CIRCUIT(circ)->path_state = PATH_STATE_USE_FAILED;
  279. return -END_CIRC_REASON_TORPROTOCOL;
  280. } else {
  281. return 0;
  282. }
  283. }
  284. if (!chan) {
  285. // XXXX Can this splice stuff be done more cleanly?
  286. if (! CIRCUIT_IS_ORIGIN(circ) &&
  287. TO_OR_CIRCUIT(circ)->rend_splice &&
  288. cell_direction == CELL_DIRECTION_OUT) {
  289. or_circuit_t *splice_ = TO_OR_CIRCUIT(circ)->rend_splice;
  290. tor_assert(circ->purpose == CIRCUIT_PURPOSE_REND_ESTABLISHED);
  291. tor_assert(splice_->base_.purpose == CIRCUIT_PURPOSE_REND_ESTABLISHED);
  292. cell->circ_id = splice_->p_circ_id;
  293. cell->command = CELL_RELAY; /* can't be relay_early anyway */
  294. if ((reason = circuit_receive_relay_cell(cell, TO_CIRCUIT(splice_),
  295. CELL_DIRECTION_IN)) < 0) {
  296. log_warn(LD_REND, "Error relaying cell across rendezvous; closing "
  297. "circuits");
  298. /* XXXX Do this here, or just return -1? */
  299. circuit_mark_for_close(circ, -reason);
  300. return reason;
  301. }
  302. return 0;
  303. }
  304. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  305. "Didn't recognize cell, but circ stops here! Closing circ.");
  306. return -END_CIRC_REASON_TORPROTOCOL;
  307. }
  308. log_debug(LD_OR,"Passing on unrecognized cell.");
  309. ++stats_n_relay_cells_relayed; /* XXXX no longer quite accurate {cells}
  310. * we might kill the circ before we relay
  311. * the cells. */
  312. append_cell_to_circuit_queue(circ, chan, cell, cell_direction, 0);
  313. return 0;
  314. }
  315. /** Package a relay cell from an edge:
  316. * - Encrypt it to the right layer
  317. * - Append it to the appropriate cell_queue on <b>circ</b>.
  318. */
  319. static int
  320. circuit_package_relay_cell(cell_t *cell, circuit_t *circ,
  321. cell_direction_t cell_direction,
  322. crypt_path_t *layer_hint, streamid_t on_stream,
  323. const char *filename, int lineno)
  324. {
  325. channel_t *chan; /* where to send the cell */
  326. if (circ->marked_for_close) {
  327. /* Circuit is marked; send nothing. */
  328. return 0;
  329. }
  330. if (cell_direction == CELL_DIRECTION_OUT) {
  331. chan = circ->n_chan;
  332. if (!chan) {
  333. log_warn(LD_BUG,"outgoing relay cell sent from %s:%d has n_chan==NULL."
  334. " Dropping. Circuit is in state %s (%d), and is "
  335. "%smarked for close. (%s:%d, %d)", filename, lineno,
  336. circuit_state_to_string(circ->state), circ->state,
  337. circ->marked_for_close ? "" : "not ",
  338. circ->marked_for_close_file?circ->marked_for_close_file:"",
  339. circ->marked_for_close, circ->marked_for_close_reason);
  340. if (CIRCUIT_IS_ORIGIN(circ)) {
  341. circuit_log_path(LOG_WARN, LD_BUG, TO_ORIGIN_CIRCUIT(circ));
  342. }
  343. log_backtrace(LOG_WARN,LD_BUG,"");
  344. return 0; /* just drop it */
  345. }
  346. if (!CIRCUIT_IS_ORIGIN(circ)) {
  347. log_warn(LD_BUG,"outgoing relay cell sent from %s:%d on non-origin "
  348. "circ. Dropping.", filename, lineno);
  349. log_backtrace(LOG_WARN,LD_BUG,"");
  350. return 0; /* just drop it */
  351. }
  352. relay_encrypt_cell_outbound(cell, TO_ORIGIN_CIRCUIT(circ), layer_hint);
  353. /* Update circ written totals for control port */
  354. origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
  355. ocirc->n_written_circ_bw = tor_add_u32_nowrap(ocirc->n_written_circ_bw,
  356. CELL_PAYLOAD_SIZE);
  357. } else { /* incoming cell */
  358. if (CIRCUIT_IS_ORIGIN(circ)) {
  359. /* We should never package an _incoming_ cell from the circuit
  360. * origin; that means we messed up somewhere. */
  361. log_warn(LD_BUG,"incoming relay cell at origin circuit. Dropping.");
  362. assert_circuit_ok(circ);
  363. return 0; /* just drop it */
  364. }
  365. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  366. relay_encrypt_cell_inbound(cell, or_circ);
  367. chan = or_circ->p_chan;
  368. }
  369. ++stats_n_relay_cells_relayed;
  370. append_cell_to_circuit_queue(circ, chan, cell, cell_direction, on_stream);
  371. return 0;
  372. }
  373. /** If cell's stream_id matches the stream_id of any conn that's
  374. * attached to circ, return that conn, else return NULL.
  375. */
  376. static edge_connection_t *
  377. relay_lookup_conn(circuit_t *circ, cell_t *cell,
  378. cell_direction_t cell_direction, crypt_path_t *layer_hint)
  379. {
  380. edge_connection_t *tmpconn;
  381. relay_header_t rh;
  382. relay_header_unpack(&rh, cell->payload);
  383. if (!rh.stream_id)
  384. return NULL;
  385. /* IN or OUT cells could have come from either direction, now
  386. * that we allow rendezvous *to* an OP.
  387. */
  388. if (CIRCUIT_IS_ORIGIN(circ)) {
  389. for (tmpconn = TO_ORIGIN_CIRCUIT(circ)->p_streams; tmpconn;
  390. tmpconn=tmpconn->next_stream) {
  391. if (rh.stream_id == tmpconn->stream_id &&
  392. !tmpconn->base_.marked_for_close &&
  393. tmpconn->cpath_layer == layer_hint) {
  394. log_debug(LD_APP,"found conn for stream %d.", rh.stream_id);
  395. return tmpconn;
  396. }
  397. }
  398. } else {
  399. for (tmpconn = TO_OR_CIRCUIT(circ)->n_streams; tmpconn;
  400. tmpconn=tmpconn->next_stream) {
  401. if (rh.stream_id == tmpconn->stream_id &&
  402. !tmpconn->base_.marked_for_close) {
  403. log_debug(LD_EXIT,"found conn for stream %d.", rh.stream_id);
  404. if (cell_direction == CELL_DIRECTION_OUT ||
  405. connection_edge_is_rendezvous_stream(tmpconn))
  406. return tmpconn;
  407. }
  408. }
  409. for (tmpconn = TO_OR_CIRCUIT(circ)->resolving_streams; tmpconn;
  410. tmpconn=tmpconn->next_stream) {
  411. if (rh.stream_id == tmpconn->stream_id &&
  412. !tmpconn->base_.marked_for_close) {
  413. log_debug(LD_EXIT,"found conn for stream %d.", rh.stream_id);
  414. return tmpconn;
  415. }
  416. }
  417. }
  418. return NULL; /* probably a begin relay cell */
  419. }
  420. /** Pack the relay_header_t host-order structure <b>src</b> into
  421. * network-order in the buffer <b>dest</b>. See tor-spec.txt for details
  422. * about the wire format.
  423. */
  424. void
  425. relay_header_pack(uint8_t *dest, const relay_header_t *src)
  426. {
  427. set_uint8(dest, src->command);
  428. set_uint16(dest+1, htons(src->recognized));
  429. set_uint16(dest+3, htons(src->stream_id));
  430. memcpy(dest+5, src->integrity, 4);
  431. set_uint16(dest+9, htons(src->length));
  432. }
  433. /** Unpack the network-order buffer <b>src</b> into a host-order
  434. * relay_header_t structure <b>dest</b>.
  435. */
  436. void
  437. relay_header_unpack(relay_header_t *dest, const uint8_t *src)
  438. {
  439. dest->command = get_uint8(src);
  440. dest->recognized = ntohs(get_uint16(src+1));
  441. dest->stream_id = ntohs(get_uint16(src+3));
  442. memcpy(dest->integrity, src+5, 4);
  443. dest->length = ntohs(get_uint16(src+9));
  444. }
  445. /** Convert the relay <b>command</b> into a human-readable string. */
  446. static const char *
  447. relay_command_to_string(uint8_t command)
  448. {
  449. static char buf[64];
  450. switch (command) {
  451. case RELAY_COMMAND_BEGIN: return "BEGIN";
  452. case RELAY_COMMAND_DATA: return "DATA";
  453. case RELAY_COMMAND_END: return "END";
  454. case RELAY_COMMAND_CONNECTED: return "CONNECTED";
  455. case RELAY_COMMAND_SENDME: return "SENDME";
  456. case RELAY_COMMAND_EXTEND: return "EXTEND";
  457. case RELAY_COMMAND_EXTENDED: return "EXTENDED";
  458. case RELAY_COMMAND_TRUNCATE: return "TRUNCATE";
  459. case RELAY_COMMAND_TRUNCATED: return "TRUNCATED";
  460. case RELAY_COMMAND_DROP: return "DROP";
  461. case RELAY_COMMAND_RESOLVE: return "RESOLVE";
  462. case RELAY_COMMAND_RESOLVED: return "RESOLVED";
  463. case RELAY_COMMAND_BEGIN_DIR: return "BEGIN_DIR";
  464. case RELAY_COMMAND_ESTABLISH_INTRO: return "ESTABLISH_INTRO";
  465. case RELAY_COMMAND_ESTABLISH_RENDEZVOUS: return "ESTABLISH_RENDEZVOUS";
  466. case RELAY_COMMAND_INTRODUCE1: return "INTRODUCE1";
  467. case RELAY_COMMAND_INTRODUCE2: return "INTRODUCE2";
  468. case RELAY_COMMAND_RENDEZVOUS1: return "RENDEZVOUS1";
  469. case RELAY_COMMAND_RENDEZVOUS2: return "RENDEZVOUS2";
  470. case RELAY_COMMAND_INTRO_ESTABLISHED: return "INTRO_ESTABLISHED";
  471. case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
  472. return "RENDEZVOUS_ESTABLISHED";
  473. case RELAY_COMMAND_INTRODUCE_ACK: return "INTRODUCE_ACK";
  474. case RELAY_COMMAND_EXTEND2: return "EXTEND2";
  475. case RELAY_COMMAND_EXTENDED2: return "EXTENDED2";
  476. default:
  477. tor_snprintf(buf, sizeof(buf), "Unrecognized relay command %u",
  478. (unsigned)command);
  479. return buf;
  480. }
  481. }
  482. /** Make a relay cell out of <b>relay_command</b> and <b>payload</b>, and send
  483. * it onto the open circuit <b>circ</b>. <b>stream_id</b> is the ID on
  484. * <b>circ</b> for the stream that's sending the relay cell, or 0 if it's a
  485. * control cell. <b>cpath_layer</b> is NULL for OR->OP cells, or the
  486. * destination hop for OP->OR cells.
  487. *
  488. * If you can't send the cell, mark the circuit for close and return -1. Else
  489. * return 0.
  490. */
  491. MOCK_IMPL(int,
  492. relay_send_command_from_edge_,(streamid_t stream_id, circuit_t *circ,
  493. uint8_t relay_command, const char *payload,
  494. size_t payload_len, crypt_path_t *cpath_layer,
  495. const char *filename, int lineno))
  496. {
  497. cell_t cell;
  498. relay_header_t rh;
  499. cell_direction_t cell_direction;
  500. /* XXXX NM Split this function into a separate versions per circuit type? */
  501. tor_assert(circ);
  502. tor_assert(payload_len <= RELAY_PAYLOAD_SIZE);
  503. memset(&cell, 0, sizeof(cell_t));
  504. cell.command = CELL_RELAY;
  505. if (CIRCUIT_IS_ORIGIN(circ)) {
  506. tor_assert(cpath_layer);
  507. cell.circ_id = circ->n_circ_id;
  508. cell_direction = CELL_DIRECTION_OUT;
  509. } else {
  510. tor_assert(! cpath_layer);
  511. cell.circ_id = TO_OR_CIRCUIT(circ)->p_circ_id;
  512. cell_direction = CELL_DIRECTION_IN;
  513. }
  514. memset(&rh, 0, sizeof(rh));
  515. rh.command = relay_command;
  516. rh.stream_id = stream_id;
  517. rh.length = payload_len;
  518. relay_header_pack(cell.payload, &rh);
  519. if (payload_len)
  520. memcpy(cell.payload+RELAY_HEADER_SIZE, payload, payload_len);
  521. log_debug(LD_OR,"delivering %d cell %s.", relay_command,
  522. cell_direction == CELL_DIRECTION_OUT ? "forward" : "backward");
  523. if (relay_command == RELAY_COMMAND_DROP)
  524. rep_hist_padding_count_write(PADDING_TYPE_DROP);
  525. /* If we are sending an END cell and this circuit is used for a tunneled
  526. * directory request, advance its state. */
  527. if (relay_command == RELAY_COMMAND_END && circ->dirreq_id)
  528. geoip_change_dirreq_state(circ->dirreq_id, DIRREQ_TUNNELED,
  529. DIRREQ_END_CELL_SENT);
  530. if (cell_direction == CELL_DIRECTION_OUT && circ->n_chan) {
  531. /* if we're using relaybandwidthrate, this conn wants priority */
  532. channel_timestamp_client(circ->n_chan);
  533. }
  534. if (cell_direction == CELL_DIRECTION_OUT) {
  535. origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
  536. if (origin_circ->remaining_relay_early_cells > 0 &&
  537. (relay_command == RELAY_COMMAND_EXTEND ||
  538. relay_command == RELAY_COMMAND_EXTEND2 ||
  539. cpath_layer != origin_circ->cpath)) {
  540. /* If we've got any relay_early cells left and (we're sending
  541. * an extend cell or we're not talking to the first hop), use
  542. * one of them. Don't worry about the conn protocol version:
  543. * append_cell_to_circuit_queue will fix it up. */
  544. cell.command = CELL_RELAY_EARLY;
  545. --origin_circ->remaining_relay_early_cells;
  546. log_debug(LD_OR, "Sending a RELAY_EARLY cell; %d remaining.",
  547. (int)origin_circ->remaining_relay_early_cells);
  548. /* Memorize the command that is sent as RELAY_EARLY cell; helps debug
  549. * task 878. */
  550. origin_circ->relay_early_commands[
  551. origin_circ->relay_early_cells_sent++] = relay_command;
  552. } else if (relay_command == RELAY_COMMAND_EXTEND ||
  553. relay_command == RELAY_COMMAND_EXTEND2) {
  554. /* If no RELAY_EARLY cells can be sent over this circuit, log which
  555. * commands have been sent as RELAY_EARLY cells before; helps debug
  556. * task 878. */
  557. smartlist_t *commands_list = smartlist_new();
  558. int i = 0;
  559. char *commands = NULL;
  560. for (; i < origin_circ->relay_early_cells_sent; i++)
  561. smartlist_add(commands_list, (char *)
  562. relay_command_to_string(origin_circ->relay_early_commands[i]));
  563. commands = smartlist_join_strings(commands_list, ",", 0, NULL);
  564. log_warn(LD_BUG, "Uh-oh. We're sending a RELAY_COMMAND_EXTEND cell, "
  565. "but we have run out of RELAY_EARLY cells on that circuit. "
  566. "Commands sent before: %s", commands);
  567. tor_free(commands);
  568. smartlist_free(commands_list);
  569. }
  570. /* Let's assume we're well-behaved: Anything that we decide to send is
  571. * valid, delivered data. */
  572. circuit_sent_valid_data(origin_circ, rh.length);
  573. }
  574. if (circuit_package_relay_cell(&cell, circ, cell_direction, cpath_layer,
  575. stream_id, filename, lineno) < 0) {
  576. log_warn(LD_BUG,"circuit_package_relay_cell failed. Closing.");
  577. circuit_mark_for_close(circ, END_CIRC_REASON_INTERNAL);
  578. return -1;
  579. }
  580. return 0;
  581. }
  582. /** Make a relay cell out of <b>relay_command</b> and <b>payload</b>, and
  583. * send it onto the open circuit <b>circ</b>. <b>fromconn</b> is the stream
  584. * that's sending the relay cell, or NULL if it's a control cell.
  585. * <b>cpath_layer</b> is NULL for OR->OP cells, or the destination hop
  586. * for OP->OR cells.
  587. *
  588. * If you can't send the cell, mark the circuit for close and
  589. * return -1. Else return 0.
  590. */
  591. int
  592. connection_edge_send_command(edge_connection_t *fromconn,
  593. uint8_t relay_command, const char *payload,
  594. size_t payload_len)
  595. {
  596. /* XXXX NM Split this function into a separate versions per circuit type? */
  597. circuit_t *circ;
  598. crypt_path_t *cpath_layer = fromconn->cpath_layer;
  599. tor_assert(fromconn);
  600. circ = fromconn->on_circuit;
  601. if (fromconn->base_.marked_for_close) {
  602. log_warn(LD_BUG,
  603. "called on conn that's already marked for close at %s:%d.",
  604. fromconn->base_.marked_for_close_file,
  605. fromconn->base_.marked_for_close);
  606. return 0;
  607. }
  608. if (!circ) {
  609. if (fromconn->base_.type == CONN_TYPE_AP) {
  610. log_info(LD_APP,"no circ. Closing conn.");
  611. connection_mark_unattached_ap(EDGE_TO_ENTRY_CONN(fromconn),
  612. END_STREAM_REASON_INTERNAL);
  613. } else {
  614. log_info(LD_EXIT,"no circ. Closing conn.");
  615. fromconn->edge_has_sent_end = 1; /* no circ to send to */
  616. fromconn->end_reason = END_STREAM_REASON_INTERNAL;
  617. connection_mark_for_close(TO_CONN(fromconn));
  618. }
  619. return -1;
  620. }
  621. if (circ->marked_for_close) {
  622. /* The circuit has been marked, but not freed yet. When it's freed, it
  623. * will mark this connection for close. */
  624. return -1;
  625. }
  626. #ifdef MEASUREMENTS_21206
  627. /* Keep track of the number of RELAY_DATA cells sent for directory
  628. * connections. */
  629. connection_t *linked_conn = TO_CONN(fromconn)->linked_conn;
  630. if (linked_conn && linked_conn->type == CONN_TYPE_DIR) {
  631. ++(TO_DIR_CONN(linked_conn)->data_cells_sent);
  632. }
  633. #endif /* defined(MEASUREMENTS_21206) */
  634. return relay_send_command_from_edge(fromconn->stream_id, circ,
  635. relay_command, payload,
  636. payload_len, cpath_layer);
  637. }
  638. /** How many times will I retry a stream that fails due to DNS
  639. * resolve failure or misc error?
  640. */
  641. #define MAX_RESOLVE_FAILURES 3
  642. /** Return 1 if reason is something that you should retry if you
  643. * get the end cell before you've connected; else return 0. */
  644. static int
  645. edge_reason_is_retriable(int reason)
  646. {
  647. return reason == END_STREAM_REASON_HIBERNATING ||
  648. reason == END_STREAM_REASON_RESOURCELIMIT ||
  649. reason == END_STREAM_REASON_EXITPOLICY ||
  650. reason == END_STREAM_REASON_RESOLVEFAILED ||
  651. reason == END_STREAM_REASON_MISC ||
  652. reason == END_STREAM_REASON_NOROUTE;
  653. }
  654. /** Called when we receive an END cell on a stream that isn't open yet,
  655. * from the client side.
  656. * Arguments are as for connection_edge_process_relay_cell().
  657. */
  658. static int
  659. connection_ap_process_end_not_open(
  660. relay_header_t *rh, cell_t *cell, origin_circuit_t *circ,
  661. entry_connection_t *conn, crypt_path_t *layer_hint)
  662. {
  663. node_t *exitrouter;
  664. int reason = *(cell->payload+RELAY_HEADER_SIZE);
  665. int control_reason;
  666. edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
  667. (void) layer_hint; /* unused */
  668. if (rh->length > 0) {
  669. if (reason == END_STREAM_REASON_TORPROTOCOL ||
  670. reason == END_STREAM_REASON_DESTROY) {
  671. /* Both of these reasons could mean a failed tag
  672. * hit the exit and it complained. Do not probe.
  673. * Fail the circuit. */
  674. circ->path_state = PATH_STATE_USE_FAILED;
  675. return -END_CIRC_REASON_TORPROTOCOL;
  676. } else if (reason == END_STREAM_REASON_INTERNAL) {
  677. /* We can't infer success or failure, since older Tors report
  678. * ENETUNREACH as END_STREAM_REASON_INTERNAL. */
  679. } else {
  680. /* Path bias: If we get a valid reason code from the exit,
  681. * it wasn't due to tagging.
  682. *
  683. * We rely on recognized+digest being strong enough to make
  684. * tags unlikely to allow us to get tagged, yet 'recognized'
  685. * reason codes here. */
  686. pathbias_mark_use_success(circ);
  687. }
  688. }
  689. /* This end cell is now valid. */
  690. circuit_read_valid_data(circ, rh->length);
  691. if (rh->length == 0) {
  692. reason = END_STREAM_REASON_MISC;
  693. }
  694. control_reason = reason | END_STREAM_REASON_FLAG_REMOTE;
  695. if (edge_reason_is_retriable(reason) &&
  696. /* avoid retry if rend */
  697. !connection_edge_is_rendezvous_stream(edge_conn)) {
  698. const char *chosen_exit_digest =
  699. circ->build_state->chosen_exit->identity_digest;
  700. log_info(LD_APP,"Address '%s' refused due to '%s'. Considering retrying.",
  701. safe_str(conn->socks_request->address),
  702. stream_end_reason_to_string(reason));
  703. exitrouter = node_get_mutable_by_id(chosen_exit_digest);
  704. switch (reason) {
  705. case END_STREAM_REASON_EXITPOLICY: {
  706. tor_addr_t addr;
  707. tor_addr_make_unspec(&addr);
  708. if (rh->length >= 5) {
  709. int ttl = -1;
  710. tor_addr_make_unspec(&addr);
  711. if (rh->length == 5 || rh->length == 9) {
  712. tor_addr_from_ipv4n(&addr,
  713. get_uint32(cell->payload+RELAY_HEADER_SIZE+1));
  714. if (rh->length == 9)
  715. ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+5));
  716. } else if (rh->length == 17 || rh->length == 21) {
  717. tor_addr_from_ipv6_bytes(&addr,
  718. (char*)(cell->payload+RELAY_HEADER_SIZE+1));
  719. if (rh->length == 21)
  720. ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+17));
  721. }
  722. if (tor_addr_is_null(&addr)) {
  723. log_info(LD_APP,"Address '%s' resolved to 0.0.0.0. Closing,",
  724. safe_str(conn->socks_request->address));
  725. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  726. return 0;
  727. }
  728. if ((tor_addr_family(&addr) == AF_INET &&
  729. !conn->entry_cfg.ipv4_traffic) ||
  730. (tor_addr_family(&addr) == AF_INET6 &&
  731. !conn->entry_cfg.ipv6_traffic)) {
  732. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  733. "Got an EXITPOLICY failure on a connection with a "
  734. "mismatched family. Closing.");
  735. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  736. return 0;
  737. }
  738. if (get_options()->ClientDNSRejectInternalAddresses &&
  739. tor_addr_is_internal(&addr, 0)) {
  740. log_info(LD_APP,"Address '%s' resolved to internal. Closing,",
  741. safe_str(conn->socks_request->address));
  742. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  743. return 0;
  744. }
  745. client_dns_set_addressmap(conn,
  746. conn->socks_request->address, &addr,
  747. conn->chosen_exit_name, ttl);
  748. {
  749. char new_addr[TOR_ADDR_BUF_LEN];
  750. tor_addr_to_str(new_addr, &addr, sizeof(new_addr), 1);
  751. if (strcmp(conn->socks_request->address, new_addr)) {
  752. strlcpy(conn->socks_request->address, new_addr,
  753. sizeof(conn->socks_request->address));
  754. control_event_stream_status(conn, STREAM_EVENT_REMAP, 0);
  755. }
  756. }
  757. }
  758. /* check if the exit *ought* to have allowed it */
  759. adjust_exit_policy_from_exitpolicy_failure(circ,
  760. conn,
  761. exitrouter,
  762. &addr);
  763. if (conn->chosen_exit_optional ||
  764. conn->chosen_exit_retries) {
  765. /* stop wanting a specific exit */
  766. conn->chosen_exit_optional = 0;
  767. /* A non-zero chosen_exit_retries can happen if we set a
  768. * TrackHostExits for this address under a port that the exit
  769. * relay allows, but then try the same address with a different
  770. * port that it doesn't allow to exit. We shouldn't unregister
  771. * the mapping, since it is probably still wanted on the
  772. * original port. But now we give away to the exit relay that
  773. * we probably have a TrackHostExits on it. So be it. */
  774. conn->chosen_exit_retries = 0;
  775. tor_free(conn->chosen_exit_name); /* clears it */
  776. }
  777. if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
  778. return 0;
  779. /* else, conn will get closed below */
  780. break;
  781. }
  782. case END_STREAM_REASON_CONNECTREFUSED:
  783. if (!conn->chosen_exit_optional)
  784. break; /* break means it'll close, below */
  785. /* Else fall through: expire this circuit, clear the
  786. * chosen_exit_name field, and try again. */
  787. /* Falls through. */
  788. case END_STREAM_REASON_RESOLVEFAILED:
  789. case END_STREAM_REASON_TIMEOUT:
  790. case END_STREAM_REASON_MISC:
  791. case END_STREAM_REASON_NOROUTE:
  792. if (client_dns_incr_failures(conn->socks_request->address)
  793. < MAX_RESOLVE_FAILURES) {
  794. /* We haven't retried too many times; reattach the connection. */
  795. circuit_log_path(LOG_INFO,LD_APP,circ);
  796. /* Mark this circuit "unusable for new streams". */
  797. mark_circuit_unusable_for_new_conns(circ);
  798. if (conn->chosen_exit_optional) {
  799. /* stop wanting a specific exit */
  800. conn->chosen_exit_optional = 0;
  801. tor_free(conn->chosen_exit_name); /* clears it */
  802. }
  803. if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
  804. return 0;
  805. /* else, conn will get closed below */
  806. } else {
  807. log_notice(LD_APP,
  808. "Have tried resolving or connecting to address '%s' "
  809. "at %d different places. Giving up.",
  810. safe_str(conn->socks_request->address),
  811. MAX_RESOLVE_FAILURES);
  812. /* clear the failures, so it will have a full try next time */
  813. client_dns_clear_failures(conn->socks_request->address);
  814. }
  815. break;
  816. case END_STREAM_REASON_HIBERNATING:
  817. case END_STREAM_REASON_RESOURCELIMIT:
  818. if (exitrouter) {
  819. policies_set_node_exitpolicy_to_reject_all(exitrouter);
  820. }
  821. if (conn->chosen_exit_optional) {
  822. /* stop wanting a specific exit */
  823. conn->chosen_exit_optional = 0;
  824. tor_free(conn->chosen_exit_name); /* clears it */
  825. }
  826. if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
  827. return 0;
  828. /* else, will close below */
  829. break;
  830. } /* end switch */
  831. log_info(LD_APP,"Giving up on retrying; conn can't be handled.");
  832. }
  833. log_info(LD_APP,
  834. "Edge got end (%s) before we're connected. Marking for close.",
  835. stream_end_reason_to_string(rh->length > 0 ? reason : -1));
  836. circuit_log_path(LOG_INFO,LD_APP,circ);
  837. /* need to test because of detach_retriable */
  838. if (!ENTRY_TO_CONN(conn)->marked_for_close)
  839. connection_mark_unattached_ap(conn, control_reason);
  840. return 0;
  841. }
  842. /** Called when we have gotten an END_REASON_EXITPOLICY failure on <b>circ</b>
  843. * for <b>conn</b>, while attempting to connect via <b>node</b>. If the node
  844. * told us which address it rejected, then <b>addr</b> is that address;
  845. * otherwise it is AF_UNSPEC.
  846. *
  847. * If we are sure the node should have allowed this address, mark the node as
  848. * having a reject *:* exit policy. Otherwise, mark the circuit as unusable
  849. * for this particular address.
  850. **/
  851. static void
  852. adjust_exit_policy_from_exitpolicy_failure(origin_circuit_t *circ,
  853. entry_connection_t *conn,
  854. node_t *node,
  855. const tor_addr_t *addr)
  856. {
  857. int make_reject_all = 0;
  858. const sa_family_t family = tor_addr_family(addr);
  859. if (node) {
  860. tor_addr_t tmp;
  861. int asked_for_family = tor_addr_parse(&tmp, conn->socks_request->address);
  862. if (family == AF_UNSPEC) {
  863. make_reject_all = 1;
  864. } else if (node_exit_policy_is_exact(node, family) &&
  865. asked_for_family != -1 && !conn->chosen_exit_name) {
  866. make_reject_all = 1;
  867. }
  868. if (make_reject_all) {
  869. log_info(LD_APP,
  870. "Exitrouter %s seems to be more restrictive than its exit "
  871. "policy. Not using this router as exit for now.",
  872. node_describe(node));
  873. policies_set_node_exitpolicy_to_reject_all(node);
  874. }
  875. }
  876. if (family != AF_UNSPEC)
  877. addr_policy_append_reject_addr(&circ->prepend_policy, addr);
  878. }
  879. /** Helper: change the socks_request-&gt;address field on conn to the
  880. * dotted-quad representation of <b>new_addr</b>,
  881. * and send an appropriate REMAP event. */
  882. static void
  883. remap_event_helper(entry_connection_t *conn, const tor_addr_t *new_addr)
  884. {
  885. tor_addr_to_str(conn->socks_request->address, new_addr,
  886. sizeof(conn->socks_request->address),
  887. 1);
  888. control_event_stream_status(conn, STREAM_EVENT_REMAP,
  889. REMAP_STREAM_SOURCE_EXIT);
  890. }
  891. /** Extract the contents of a connected cell in <b>cell</b>, whose relay
  892. * header has already been parsed into <b>rh</b>. On success, set
  893. * <b>addr_out</b> to the address we're connected to, and <b>ttl_out</b> to
  894. * the ttl of that address, in seconds, and return 0. On failure, return
  895. * -1.
  896. *
  897. * Note that the resulting address can be UNSPEC if the connected cell had no
  898. * address (as for a stream to an union service or a tunneled directory
  899. * connection), and that the ttl can be absent (in which case <b>ttl_out</b>
  900. * is set to -1). */
  901. STATIC int
  902. connected_cell_parse(const relay_header_t *rh, const cell_t *cell,
  903. tor_addr_t *addr_out, int *ttl_out)
  904. {
  905. uint32_t bytes;
  906. const uint8_t *payload = cell->payload + RELAY_HEADER_SIZE;
  907. tor_addr_make_unspec(addr_out);
  908. *ttl_out = -1;
  909. if (rh->length == 0)
  910. return 0;
  911. if (rh->length < 4)
  912. return -1;
  913. bytes = ntohl(get_uint32(payload));
  914. /* If bytes is 0, this is maybe a v6 address. Otherwise it's a v4 address */
  915. if (bytes != 0) {
  916. /* v4 address */
  917. tor_addr_from_ipv4h(addr_out, bytes);
  918. if (rh->length >= 8) {
  919. bytes = ntohl(get_uint32(payload + 4));
  920. if (bytes <= INT32_MAX)
  921. *ttl_out = bytes;
  922. }
  923. } else {
  924. if (rh->length < 25) /* 4 bytes of 0s, 1 addr, 16 ipv4, 4 ttl. */
  925. return -1;
  926. if (get_uint8(payload + 4) != 6)
  927. return -1;
  928. tor_addr_from_ipv6_bytes(addr_out, (char*)(payload + 5));
  929. bytes = ntohl(get_uint32(payload + 21));
  930. if (bytes <= INT32_MAX)
  931. *ttl_out = (int) bytes;
  932. }
  933. return 0;
  934. }
  935. /** Drop all storage held by <b>addr</b>. */
  936. STATIC void
  937. address_ttl_free_(address_ttl_t *addr)
  938. {
  939. if (!addr)
  940. return;
  941. tor_free(addr->hostname);
  942. tor_free(addr);
  943. }
  944. /** Parse a resolved cell in <b>cell</b>, with parsed header in <b>rh</b>.
  945. * Return -1 on parse error. On success, add one or more newly allocated
  946. * address_ttl_t to <b>addresses_out</b>; set *<b>errcode_out</b> to
  947. * one of 0, RESOLVED_TYPE_ERROR, or RESOLVED_TYPE_ERROR_TRANSIENT, and
  948. * return 0. */
  949. STATIC int
  950. resolved_cell_parse(const cell_t *cell, const relay_header_t *rh,
  951. smartlist_t *addresses_out, int *errcode_out)
  952. {
  953. const uint8_t *cp;
  954. uint8_t answer_type;
  955. size_t answer_len;
  956. address_ttl_t *addr;
  957. size_t remaining;
  958. int errcode = 0;
  959. smartlist_t *addrs;
  960. tor_assert(cell);
  961. tor_assert(rh);
  962. tor_assert(addresses_out);
  963. tor_assert(errcode_out);
  964. *errcode_out = 0;
  965. if (rh->length > RELAY_PAYLOAD_SIZE)
  966. return -1;
  967. addrs = smartlist_new();
  968. cp = cell->payload + RELAY_HEADER_SIZE;
  969. remaining = rh->length;
  970. while (remaining) {
  971. const uint8_t *cp_orig = cp;
  972. if (remaining < 2)
  973. goto err;
  974. answer_type = *cp++;
  975. answer_len = *cp++;
  976. if (remaining < 2 + answer_len + 4) {
  977. goto err;
  978. }
  979. if (answer_type == RESOLVED_TYPE_IPV4) {
  980. if (answer_len != 4) {
  981. goto err;
  982. }
  983. addr = tor_malloc_zero(sizeof(*addr));
  984. tor_addr_from_ipv4n(&addr->addr, get_uint32(cp));
  985. cp += 4;
  986. addr->ttl = ntohl(get_uint32(cp));
  987. cp += 4;
  988. smartlist_add(addrs, addr);
  989. } else if (answer_type == RESOLVED_TYPE_IPV6) {
  990. if (answer_len != 16)
  991. goto err;
  992. addr = tor_malloc_zero(sizeof(*addr));
  993. tor_addr_from_ipv6_bytes(&addr->addr, (const char*) cp);
  994. cp += 16;
  995. addr->ttl = ntohl(get_uint32(cp));
  996. cp += 4;
  997. smartlist_add(addrs, addr);
  998. } else if (answer_type == RESOLVED_TYPE_HOSTNAME) {
  999. if (answer_len == 0) {
  1000. goto err;
  1001. }
  1002. addr = tor_malloc_zero(sizeof(*addr));
  1003. addr->hostname = tor_memdup_nulterm(cp, answer_len);
  1004. cp += answer_len;
  1005. addr->ttl = ntohl(get_uint32(cp));
  1006. cp += 4;
  1007. smartlist_add(addrs, addr);
  1008. } else if (answer_type == RESOLVED_TYPE_ERROR_TRANSIENT ||
  1009. answer_type == RESOLVED_TYPE_ERROR) {
  1010. errcode = answer_type;
  1011. /* Ignore the error contents */
  1012. cp += answer_len + 4;
  1013. } else {
  1014. cp += answer_len + 4;
  1015. }
  1016. tor_assert(((ssize_t)remaining) >= (cp - cp_orig));
  1017. remaining -= (cp - cp_orig);
  1018. }
  1019. if (errcode && smartlist_len(addrs) == 0) {
  1020. /* Report an error only if there were no results. */
  1021. *errcode_out = errcode;
  1022. }
  1023. smartlist_add_all(addresses_out, addrs);
  1024. smartlist_free(addrs);
  1025. return 0;
  1026. err:
  1027. /* On parse error, don't report any results */
  1028. SMARTLIST_FOREACH(addrs, address_ttl_t *, a, address_ttl_free(a));
  1029. smartlist_free(addrs);
  1030. return -1;
  1031. }
  1032. /** Helper for connection_edge_process_resolved_cell: given an error code,
  1033. * an entry_connection, and a list of address_ttl_t *, report the best answer
  1034. * to the entry_connection. */
  1035. static void
  1036. connection_ap_handshake_socks_got_resolved_cell(entry_connection_t *conn,
  1037. int error_code,
  1038. smartlist_t *results)
  1039. {
  1040. address_ttl_t *addr_ipv4 = NULL;
  1041. address_ttl_t *addr_ipv6 = NULL;
  1042. address_ttl_t *addr_hostname = NULL;
  1043. address_ttl_t *addr_best = NULL;
  1044. /* If it's an error code, that's easy. */
  1045. if (error_code) {
  1046. tor_assert(error_code == RESOLVED_TYPE_ERROR ||
  1047. error_code == RESOLVED_TYPE_ERROR_TRANSIENT);
  1048. connection_ap_handshake_socks_resolved(conn,
  1049. error_code,0,NULL,-1,-1);
  1050. return;
  1051. }
  1052. /* Get the first answer of each type. */
  1053. SMARTLIST_FOREACH_BEGIN(results, address_ttl_t *, addr) {
  1054. if (addr->hostname) {
  1055. if (!addr_hostname) {
  1056. addr_hostname = addr;
  1057. }
  1058. } else if (tor_addr_family(&addr->addr) == AF_INET) {
  1059. if (!addr_ipv4 && conn->entry_cfg.ipv4_traffic) {
  1060. addr_ipv4 = addr;
  1061. }
  1062. } else if (tor_addr_family(&addr->addr) == AF_INET6) {
  1063. if (!addr_ipv6 && conn->entry_cfg.ipv6_traffic) {
  1064. addr_ipv6 = addr;
  1065. }
  1066. }
  1067. } SMARTLIST_FOREACH_END(addr);
  1068. /* Now figure out which type we wanted to deliver. */
  1069. if (conn->socks_request->command == SOCKS_COMMAND_RESOLVE_PTR) {
  1070. if (addr_hostname) {
  1071. connection_ap_handshake_socks_resolved(conn,
  1072. RESOLVED_TYPE_HOSTNAME,
  1073. strlen(addr_hostname->hostname),
  1074. (uint8_t*)addr_hostname->hostname,
  1075. addr_hostname->ttl,-1);
  1076. } else {
  1077. connection_ap_handshake_socks_resolved(conn,
  1078. RESOLVED_TYPE_ERROR,0,NULL,-1,-1);
  1079. }
  1080. return;
  1081. }
  1082. if (conn->entry_cfg.prefer_ipv6) {
  1083. addr_best = addr_ipv6 ? addr_ipv6 : addr_ipv4;
  1084. } else {
  1085. addr_best = addr_ipv4 ? addr_ipv4 : addr_ipv6;
  1086. }
  1087. /* Now convert it to the ugly old interface */
  1088. if (! addr_best) {
  1089. connection_ap_handshake_socks_resolved(conn,
  1090. RESOLVED_TYPE_ERROR,0,NULL,-1,-1);
  1091. return;
  1092. }
  1093. connection_ap_handshake_socks_resolved_addr(conn,
  1094. &addr_best->addr,
  1095. addr_best->ttl,
  1096. -1);
  1097. remap_event_helper(conn, &addr_best->addr);
  1098. }
  1099. /** Handle a RELAY_COMMAND_RESOLVED cell that we received on a non-open AP
  1100. * stream. */
  1101. STATIC int
  1102. connection_edge_process_resolved_cell(edge_connection_t *conn,
  1103. const cell_t *cell,
  1104. const relay_header_t *rh)
  1105. {
  1106. entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
  1107. smartlist_t *resolved_addresses = NULL;
  1108. int errcode = 0;
  1109. if (conn->base_.state != AP_CONN_STATE_RESOLVE_WAIT) {
  1110. log_fn(LOG_PROTOCOL_WARN, LD_APP, "Got a 'resolved' cell while "
  1111. "not in state resolve_wait. Dropping.");
  1112. return 0;
  1113. }
  1114. tor_assert(SOCKS_COMMAND_IS_RESOLVE(entry_conn->socks_request->command));
  1115. resolved_addresses = smartlist_new();
  1116. if (resolved_cell_parse(cell, rh, resolved_addresses, &errcode)) {
  1117. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1118. "Dropping malformed 'resolved' cell");
  1119. connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TORPROTOCOL);
  1120. goto done;
  1121. }
  1122. if (get_options()->ClientDNSRejectInternalAddresses) {
  1123. int orig_len = smartlist_len(resolved_addresses);
  1124. SMARTLIST_FOREACH_BEGIN(resolved_addresses, address_ttl_t *, addr) {
  1125. if (addr->hostname == NULL && tor_addr_is_internal(&addr->addr, 0)) {
  1126. log_info(LD_APP, "Got a resolved cell with answer %s; dropping that "
  1127. "answer.",
  1128. safe_str_client(fmt_addr(&addr->addr)));
  1129. address_ttl_free(addr);
  1130. SMARTLIST_DEL_CURRENT(resolved_addresses, addr);
  1131. }
  1132. } SMARTLIST_FOREACH_END(addr);
  1133. if (orig_len && smartlist_len(resolved_addresses) == 0) {
  1134. log_info(LD_APP, "Got a resolved cell with only private addresses; "
  1135. "dropping it.");
  1136. connection_ap_handshake_socks_resolved(entry_conn,
  1137. RESOLVED_TYPE_ERROR_TRANSIENT,
  1138. 0, NULL, 0, TIME_MAX);
  1139. connection_mark_unattached_ap(entry_conn,
  1140. END_STREAM_REASON_TORPROTOCOL);
  1141. goto done;
  1142. }
  1143. }
  1144. /* This is valid data at this point. Count it */
  1145. if (conn->on_circuit && CIRCUIT_IS_ORIGIN(conn->on_circuit)) {
  1146. circuit_read_valid_data(TO_ORIGIN_CIRCUIT(conn->on_circuit),
  1147. rh->length);
  1148. }
  1149. connection_ap_handshake_socks_got_resolved_cell(entry_conn,
  1150. errcode,
  1151. resolved_addresses);
  1152. connection_mark_unattached_ap(entry_conn,
  1153. END_STREAM_REASON_DONE |
  1154. END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
  1155. done:
  1156. SMARTLIST_FOREACH(resolved_addresses, address_ttl_t *, addr,
  1157. address_ttl_free(addr));
  1158. smartlist_free(resolved_addresses);
  1159. return 0;
  1160. }
  1161. /** An incoming relay cell has arrived from circuit <b>circ</b> to
  1162. * stream <b>conn</b>.
  1163. *
  1164. * The arguments here are the same as in
  1165. * connection_edge_process_relay_cell() below; this function is called
  1166. * from there when <b>conn</b> is defined and not in an open state.
  1167. */
  1168. static int
  1169. connection_edge_process_relay_cell_not_open(
  1170. relay_header_t *rh, cell_t *cell, circuit_t *circ,
  1171. edge_connection_t *conn, crypt_path_t *layer_hint)
  1172. {
  1173. if (rh->command == RELAY_COMMAND_END) {
  1174. if (CIRCUIT_IS_ORIGIN(circ) && conn->base_.type == CONN_TYPE_AP) {
  1175. return connection_ap_process_end_not_open(rh, cell,
  1176. TO_ORIGIN_CIRCUIT(circ),
  1177. EDGE_TO_ENTRY_CONN(conn),
  1178. layer_hint);
  1179. } else {
  1180. /* we just got an 'end', don't need to send one */
  1181. conn->edge_has_sent_end = 1;
  1182. conn->end_reason = *(cell->payload+RELAY_HEADER_SIZE) |
  1183. END_STREAM_REASON_FLAG_REMOTE;
  1184. connection_mark_for_close(TO_CONN(conn));
  1185. return 0;
  1186. }
  1187. }
  1188. if (conn->base_.type == CONN_TYPE_AP &&
  1189. rh->command == RELAY_COMMAND_CONNECTED) {
  1190. tor_addr_t addr;
  1191. int ttl;
  1192. entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
  1193. tor_assert(CIRCUIT_IS_ORIGIN(circ));
  1194. if (conn->base_.state != AP_CONN_STATE_CONNECT_WAIT) {
  1195. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  1196. "Got 'connected' while not in state connect_wait. Dropping.");
  1197. return 0;
  1198. }
  1199. CONNECTION_AP_EXPECT_NONPENDING(entry_conn);
  1200. conn->base_.state = AP_CONN_STATE_OPEN;
  1201. log_info(LD_APP,"'connected' received for circid %u streamid %d "
  1202. "after %d seconds.",
  1203. (unsigned)circ->n_circ_id,
  1204. rh->stream_id,
  1205. (int)(time(NULL) - conn->base_.timestamp_last_read_allowed));
  1206. if (connected_cell_parse(rh, cell, &addr, &ttl) < 0) {
  1207. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  1208. "Got a badly formatted connected cell. Closing.");
  1209. connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
  1210. connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TORPROTOCOL);
  1211. return 0;
  1212. }
  1213. if (tor_addr_family(&addr) != AF_UNSPEC) {
  1214. /* The family is not UNSPEC: so we were given an address in the
  1215. * connected cell. (This is normal, except for BEGINDIR and onion
  1216. * service streams.) */
  1217. const sa_family_t family = tor_addr_family(&addr);
  1218. if (tor_addr_is_null(&addr) ||
  1219. (get_options()->ClientDNSRejectInternalAddresses &&
  1220. tor_addr_is_internal(&addr, 0))) {
  1221. log_info(LD_APP, "...but it claims the IP address was %s. Closing.",
  1222. fmt_addr(&addr));
  1223. connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
  1224. connection_mark_unattached_ap(entry_conn,
  1225. END_STREAM_REASON_TORPROTOCOL);
  1226. return 0;
  1227. }
  1228. if ((family == AF_INET && ! entry_conn->entry_cfg.ipv4_traffic) ||
  1229. (family == AF_INET6 && ! entry_conn->entry_cfg.ipv6_traffic)) {
  1230. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  1231. "Got a connected cell to %s with unsupported address family."
  1232. " Closing.", fmt_addr(&addr));
  1233. connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
  1234. connection_mark_unattached_ap(entry_conn,
  1235. END_STREAM_REASON_TORPROTOCOL);
  1236. return 0;
  1237. }
  1238. client_dns_set_addressmap(entry_conn,
  1239. entry_conn->socks_request->address, &addr,
  1240. entry_conn->chosen_exit_name, ttl);
  1241. remap_event_helper(entry_conn, &addr);
  1242. }
  1243. circuit_log_path(LOG_INFO,LD_APP,TO_ORIGIN_CIRCUIT(circ));
  1244. /* don't send a socks reply to transparent conns */
  1245. tor_assert(entry_conn->socks_request != NULL);
  1246. if (!entry_conn->socks_request->has_finished) {
  1247. connection_ap_handshake_socks_reply(entry_conn, NULL, 0, 0);
  1248. }
  1249. /* Was it a linked dir conn? If so, a dir request just started to
  1250. * fetch something; this could be a bootstrap status milestone. */
  1251. log_debug(LD_APP, "considering");
  1252. if (TO_CONN(conn)->linked_conn &&
  1253. TO_CONN(conn)->linked_conn->type == CONN_TYPE_DIR) {
  1254. connection_t *dirconn = TO_CONN(conn)->linked_conn;
  1255. log_debug(LD_APP, "it is! %d", dirconn->purpose);
  1256. switch (dirconn->purpose) {
  1257. case DIR_PURPOSE_FETCH_CERTIFICATE:
  1258. if (consensus_is_waiting_for_certs())
  1259. control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_KEYS, 0);
  1260. break;
  1261. case DIR_PURPOSE_FETCH_CONSENSUS:
  1262. control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_STATUS, 0);
  1263. break;
  1264. case DIR_PURPOSE_FETCH_SERVERDESC:
  1265. case DIR_PURPOSE_FETCH_MICRODESC:
  1266. if (TO_DIR_CONN(dirconn)->router_purpose == ROUTER_PURPOSE_GENERAL)
  1267. control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_DESCRIPTORS,
  1268. count_loading_descriptors_progress());
  1269. break;
  1270. }
  1271. }
  1272. /* This is definitely a success, so forget about any pending data we
  1273. * had sent. */
  1274. if (entry_conn->pending_optimistic_data) {
  1275. buf_free(entry_conn->pending_optimistic_data);
  1276. entry_conn->pending_optimistic_data = NULL;
  1277. }
  1278. /* This is valid data at this point. Count it */
  1279. circuit_read_valid_data(TO_ORIGIN_CIRCUIT(circ), rh->length);
  1280. /* handle anything that might have queued */
  1281. if (connection_edge_package_raw_inbuf(conn, 1, NULL) < 0) {
  1282. /* (We already sent an end cell if possible) */
  1283. connection_mark_for_close(TO_CONN(conn));
  1284. return 0;
  1285. }
  1286. return 0;
  1287. }
  1288. if (conn->base_.type == CONN_TYPE_AP &&
  1289. rh->command == RELAY_COMMAND_RESOLVED) {
  1290. return connection_edge_process_resolved_cell(conn, cell, rh);
  1291. }
  1292. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1293. "Got an unexpected relay command %d, in state %d (%s). Dropping.",
  1294. rh->command, conn->base_.state,
  1295. conn_state_to_string(conn->base_.type, conn->base_.state));
  1296. return 0; /* for forward compatibility, don't kill the circuit */
  1297. // connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
  1298. // connection_mark_for_close(conn);
  1299. // return -1;
  1300. }
  1301. /** An incoming relay cell has arrived on circuit <b>circ</b>. If
  1302. * <b>conn</b> is NULL this is a control cell, else <b>cell</b> is
  1303. * destined for <b>conn</b>.
  1304. *
  1305. * If <b>layer_hint</b> is defined, then we're the origin of the
  1306. * circuit, and it specifies the hop that packaged <b>cell</b>.
  1307. *
  1308. * Return -reason if you want to warn and tear down the circuit, else 0.
  1309. */
  1310. STATIC int
  1311. connection_edge_process_relay_cell(cell_t *cell, circuit_t *circ,
  1312. edge_connection_t *conn,
  1313. crypt_path_t *layer_hint)
  1314. {
  1315. static int num_seen=0;
  1316. relay_header_t rh;
  1317. unsigned domain = layer_hint?LD_APP:LD_EXIT;
  1318. int reason;
  1319. int optimistic_data = 0; /* Set to 1 if we receive data on a stream
  1320. * that's in the EXIT_CONN_STATE_RESOLVING
  1321. * or EXIT_CONN_STATE_CONNECTING states. */
  1322. tor_assert(cell);
  1323. tor_assert(circ);
  1324. relay_header_unpack(&rh, cell->payload);
  1325. // log_fn(LOG_DEBUG,"command %d stream %d", rh.command, rh.stream_id);
  1326. num_seen++;
  1327. log_debug(domain, "Now seen %d relay cells here (command %d, stream %d).",
  1328. num_seen, rh.command, rh.stream_id);
  1329. if (rh.length > RELAY_PAYLOAD_SIZE) {
  1330. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1331. "Relay cell length field too long. Closing circuit.");
  1332. return - END_CIRC_REASON_TORPROTOCOL;
  1333. }
  1334. if (rh.stream_id == 0) {
  1335. switch (rh.command) {
  1336. case RELAY_COMMAND_BEGIN:
  1337. case RELAY_COMMAND_CONNECTED:
  1338. case RELAY_COMMAND_END:
  1339. case RELAY_COMMAND_RESOLVE:
  1340. case RELAY_COMMAND_RESOLVED:
  1341. case RELAY_COMMAND_BEGIN_DIR:
  1342. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, "Relay command %d with zero "
  1343. "stream_id. Dropping.", (int)rh.command);
  1344. return 0;
  1345. default:
  1346. ;
  1347. }
  1348. }
  1349. /* either conn is NULL, in which case we've got a control cell, or else
  1350. * conn points to the recognized stream. */
  1351. if (conn && !connection_state_is_open(TO_CONN(conn))) {
  1352. if (conn->base_.type == CONN_TYPE_EXIT &&
  1353. (conn->base_.state == EXIT_CONN_STATE_CONNECTING ||
  1354. conn->base_.state == EXIT_CONN_STATE_RESOLVING) &&
  1355. rh.command == RELAY_COMMAND_DATA) {
  1356. /* Allow DATA cells to be delivered to an exit node in state
  1357. * EXIT_CONN_STATE_CONNECTING or EXIT_CONN_STATE_RESOLVING.
  1358. * This speeds up HTTP, for example. */
  1359. optimistic_data = 1;
  1360. } else if (rh.stream_id == 0 && rh.command == RELAY_COMMAND_DATA) {
  1361. log_warn(LD_BUG, "Somehow I had a connection that matched a "
  1362. "data cell with stream ID 0.");
  1363. } else {
  1364. return connection_edge_process_relay_cell_not_open(
  1365. &rh, cell, circ, conn, layer_hint);
  1366. }
  1367. }
  1368. switch (rh.command) {
  1369. case RELAY_COMMAND_DROP:
  1370. rep_hist_padding_count_read(PADDING_TYPE_DROP);
  1371. // log_info(domain,"Got a relay-level padding cell. Dropping.");
  1372. return 0;
  1373. case RELAY_COMMAND_BEGIN:
  1374. case RELAY_COMMAND_BEGIN_DIR:
  1375. if (layer_hint &&
  1376. circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
  1377. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  1378. "Relay begin request unsupported at AP. Dropping.");
  1379. return 0;
  1380. }
  1381. if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED &&
  1382. layer_hint != TO_ORIGIN_CIRCUIT(circ)->cpath->prev) {
  1383. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  1384. "Relay begin request to Hidden Service "
  1385. "from intermediary node. Dropping.");
  1386. return 0;
  1387. }
  1388. if (conn) {
  1389. log_fn(LOG_PROTOCOL_WARN, domain,
  1390. "Begin cell for known stream. Dropping.");
  1391. return 0;
  1392. }
  1393. if (rh.command == RELAY_COMMAND_BEGIN_DIR &&
  1394. circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
  1395. /* Assign this circuit and its app-ward OR connection a unique ID,
  1396. * so that we can measure download times. The local edge and dir
  1397. * connection will be assigned the same ID when they are created
  1398. * and linked. */
  1399. static uint64_t next_id = 0;
  1400. circ->dirreq_id = ++next_id;
  1401. TO_OR_CIRCUIT(circ)->p_chan->dirreq_id = circ->dirreq_id;
  1402. }
  1403. return connection_exit_begin_conn(cell, circ);
  1404. case RELAY_COMMAND_DATA:
  1405. ++stats_n_data_cells_received;
  1406. if (( layer_hint && --layer_hint->deliver_window < 0) ||
  1407. (!layer_hint && --circ->deliver_window < 0)) {
  1408. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1409. "(relay data) circ deliver_window below 0. Killing.");
  1410. if (conn) {
  1411. /* XXXX Do we actually need to do this? Will killing the circuit
  1412. * not send an END and mark the stream for close as appropriate? */
  1413. connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
  1414. connection_mark_for_close(TO_CONN(conn));
  1415. }
  1416. return -END_CIRC_REASON_TORPROTOCOL;
  1417. }
  1418. log_debug(domain,"circ deliver_window now %d.", layer_hint ?
  1419. layer_hint->deliver_window : circ->deliver_window);
  1420. circuit_consider_sending_sendme(circ, layer_hint);
  1421. if (rh.stream_id == 0) {
  1422. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, "Relay data cell with zero "
  1423. "stream_id. Dropping.");
  1424. return 0;
  1425. } else if (!conn) {
  1426. log_info(domain,"data cell dropped, unknown stream (streamid %d).",
  1427. rh.stream_id);
  1428. return 0;
  1429. }
  1430. if (--conn->deliver_window < 0) { /* is it below 0 after decrement? */
  1431. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1432. "(relay data) conn deliver_window below 0. Killing.");
  1433. return -END_CIRC_REASON_TORPROTOCOL;
  1434. }
  1435. /* Total all valid application bytes delivered */
  1436. if (CIRCUIT_IS_ORIGIN(circ) && rh.length > 0) {
  1437. circuit_read_valid_data(TO_ORIGIN_CIRCUIT(circ), rh.length);
  1438. }
  1439. stats_n_data_bytes_received += rh.length;
  1440. connection_buf_add((char*)(cell->payload + RELAY_HEADER_SIZE),
  1441. rh.length, TO_CONN(conn));
  1442. #ifdef MEASUREMENTS_21206
  1443. /* Count number of RELAY_DATA cells received on a linked directory
  1444. * connection. */
  1445. connection_t *linked_conn = TO_CONN(conn)->linked_conn;
  1446. if (linked_conn && linked_conn->type == CONN_TYPE_DIR) {
  1447. ++(TO_DIR_CONN(linked_conn)->data_cells_received);
  1448. }
  1449. #endif /* defined(MEASUREMENTS_21206) */
  1450. if (!optimistic_data) {
  1451. /* Only send a SENDME if we're not getting optimistic data; otherwise
  1452. * a SENDME could arrive before the CONNECTED.
  1453. */
  1454. connection_edge_consider_sending_sendme(conn);
  1455. }
  1456. return 0;
  1457. case RELAY_COMMAND_END:
  1458. reason = rh.length > 0 ?
  1459. get_uint8(cell->payload+RELAY_HEADER_SIZE) : END_STREAM_REASON_MISC;
  1460. if (!conn) {
  1461. log_info(domain,"end cell (%s) dropped, unknown stream.",
  1462. stream_end_reason_to_string(reason));
  1463. return 0;
  1464. }
  1465. /* XXX add to this log_fn the exit node's nickname? */
  1466. log_info(domain,TOR_SOCKET_T_FORMAT": end cell (%s) for stream %d. "
  1467. "Removing stream.",
  1468. conn->base_.s,
  1469. stream_end_reason_to_string(reason),
  1470. conn->stream_id);
  1471. if (conn->base_.type == CONN_TYPE_AP) {
  1472. entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
  1473. if (entry_conn->socks_request &&
  1474. !entry_conn->socks_request->has_finished)
  1475. log_warn(LD_BUG,
  1476. "open stream hasn't sent socks answer yet? Closing.");
  1477. }
  1478. /* We just *got* an end; no reason to send one. */
  1479. conn->edge_has_sent_end = 1;
  1480. if (!conn->end_reason)
  1481. conn->end_reason = reason | END_STREAM_REASON_FLAG_REMOTE;
  1482. if (!conn->base_.marked_for_close) {
  1483. /* only mark it if not already marked. it's possible to
  1484. * get the 'end' right around when the client hangs up on us. */
  1485. connection_mark_and_flush(TO_CONN(conn));
  1486. /* Total all valid application bytes delivered */
  1487. if (CIRCUIT_IS_ORIGIN(circ)) {
  1488. circuit_read_valid_data(TO_ORIGIN_CIRCUIT(circ), rh.length);
  1489. }
  1490. }
  1491. return 0;
  1492. case RELAY_COMMAND_EXTEND:
  1493. case RELAY_COMMAND_EXTEND2: {
  1494. static uint64_t total_n_extend=0, total_nonearly=0;
  1495. total_n_extend++;
  1496. if (rh.stream_id) {
  1497. log_fn(LOG_PROTOCOL_WARN, domain,
  1498. "'extend' cell received for non-zero stream. Dropping.");
  1499. return 0;
  1500. }
  1501. if (cell->command != CELL_RELAY_EARLY &&
  1502. !networkstatus_get_param(NULL,"AllowNonearlyExtend",0,0,1)) {
  1503. #define EARLY_WARNING_INTERVAL 3600
  1504. static ratelim_t early_warning_limit =
  1505. RATELIM_INIT(EARLY_WARNING_INTERVAL);
  1506. char *m;
  1507. if (cell->command == CELL_RELAY) {
  1508. ++total_nonearly;
  1509. if ((m = rate_limit_log(&early_warning_limit, approx_time()))) {
  1510. double percentage = ((double)total_nonearly)/total_n_extend;
  1511. percentage *= 100;
  1512. log_fn(LOG_PROTOCOL_WARN, domain, "EXTEND cell received, "
  1513. "but not via RELAY_EARLY. Dropping.%s", m);
  1514. log_fn(LOG_PROTOCOL_WARN, domain, " (We have dropped %.02f%% of "
  1515. "all EXTEND cells for this reason)", percentage);
  1516. tor_free(m);
  1517. }
  1518. } else {
  1519. log_fn(LOG_WARN, domain,
  1520. "EXTEND cell received, in a cell with type %d! Dropping.",
  1521. cell->command);
  1522. }
  1523. return 0;
  1524. }
  1525. return circuit_extend(cell, circ);
  1526. }
  1527. case RELAY_COMMAND_EXTENDED:
  1528. case RELAY_COMMAND_EXTENDED2:
  1529. if (!layer_hint) {
  1530. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1531. "'extended' unsupported at non-origin. Dropping.");
  1532. return 0;
  1533. }
  1534. log_debug(domain,"Got an extended cell! Yay.");
  1535. {
  1536. extended_cell_t extended_cell;
  1537. if (extended_cell_parse(&extended_cell, rh.command,
  1538. (const uint8_t*)cell->payload+RELAY_HEADER_SIZE,
  1539. rh.length)<0) {
  1540. log_warn(LD_PROTOCOL,
  1541. "Can't parse EXTENDED cell; killing circuit.");
  1542. return -END_CIRC_REASON_TORPROTOCOL;
  1543. }
  1544. if ((reason = circuit_finish_handshake(TO_ORIGIN_CIRCUIT(circ),
  1545. &extended_cell.created_cell)) < 0) {
  1546. circuit_mark_for_close(circ, -reason);
  1547. return 0; /* We don't want to cause a warning, so we mark the circuit
  1548. * here. */
  1549. }
  1550. }
  1551. if ((reason=circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ)))<0) {
  1552. log_info(domain,"circuit_send_next_onion_skin() failed.");
  1553. return reason;
  1554. }
  1555. /* Total all valid bytes delivered. */
  1556. if (CIRCUIT_IS_ORIGIN(circ)) {
  1557. circuit_read_valid_data(TO_ORIGIN_CIRCUIT(circ), rh.length);
  1558. }
  1559. return 0;
  1560. case RELAY_COMMAND_TRUNCATE:
  1561. if (layer_hint) {
  1562. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  1563. "'truncate' unsupported at origin. Dropping.");
  1564. return 0;
  1565. }
  1566. if (circ->n_hop) {
  1567. if (circ->n_chan)
  1568. log_warn(LD_BUG, "n_chan and n_hop set on the same circuit!");
  1569. extend_info_free(circ->n_hop);
  1570. circ->n_hop = NULL;
  1571. tor_free(circ->n_chan_create_cell);
  1572. circuit_set_state(circ, CIRCUIT_STATE_OPEN);
  1573. }
  1574. if (circ->n_chan) {
  1575. uint8_t trunc_reason = get_uint8(cell->payload + RELAY_HEADER_SIZE);
  1576. circuit_clear_cell_queue(circ, circ->n_chan);
  1577. channel_send_destroy(circ->n_circ_id, circ->n_chan,
  1578. trunc_reason);
  1579. circuit_set_n_circid_chan(circ, 0, NULL);
  1580. }
  1581. log_debug(LD_EXIT, "Processed 'truncate', replying.");
  1582. {
  1583. char payload[1];
  1584. payload[0] = (char)END_CIRC_REASON_REQUESTED;
  1585. relay_send_command_from_edge(0, circ, RELAY_COMMAND_TRUNCATED,
  1586. payload, sizeof(payload), NULL);
  1587. }
  1588. return 0;
  1589. case RELAY_COMMAND_TRUNCATED:
  1590. if (!layer_hint) {
  1591. log_fn(LOG_PROTOCOL_WARN, LD_EXIT,
  1592. "'truncated' unsupported at non-origin. Dropping.");
  1593. return 0;
  1594. }
  1595. circuit_truncated(TO_ORIGIN_CIRCUIT(circ), layer_hint,
  1596. get_uint8(cell->payload + RELAY_HEADER_SIZE));
  1597. return 0;
  1598. case RELAY_COMMAND_CONNECTED:
  1599. if (conn) {
  1600. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1601. "'connected' unsupported while open. Closing circ.");
  1602. return -END_CIRC_REASON_TORPROTOCOL;
  1603. }
  1604. log_info(domain,
  1605. "'connected' received on circid %u for streamid %d, "
  1606. "no conn attached anymore. Ignoring.",
  1607. (unsigned)circ->n_circ_id, rh.stream_id);
  1608. return 0;
  1609. case RELAY_COMMAND_SENDME:
  1610. if (!rh.stream_id) {
  1611. if (layer_hint) {
  1612. if (layer_hint->package_window + CIRCWINDOW_INCREMENT >
  1613. CIRCWINDOW_START_MAX) {
  1614. static struct ratelim_t exit_warn_ratelim = RATELIM_INIT(600);
  1615. log_fn_ratelim(&exit_warn_ratelim, LOG_WARN, LD_PROTOCOL,
  1616. "Unexpected sendme cell from exit relay. "
  1617. "Closing circ.");
  1618. return -END_CIRC_REASON_TORPROTOCOL;
  1619. }
  1620. layer_hint->package_window += CIRCWINDOW_INCREMENT;
  1621. log_debug(LD_APP,"circ-level sendme at origin, packagewindow %d.",
  1622. layer_hint->package_window);
  1623. circuit_resume_edge_reading(circ, layer_hint);
  1624. /* We count circuit-level sendme's as valid delivered data because
  1625. * they are rate limited. Note that we cannot count stream
  1626. * sendme's because the other end could send as many as they like.
  1627. */
  1628. if (CIRCUIT_IS_ORIGIN(circ)) {
  1629. circuit_read_valid_data(TO_ORIGIN_CIRCUIT(circ),
  1630. rh.length);
  1631. }
  1632. } else {
  1633. if (circ->package_window + CIRCWINDOW_INCREMENT >
  1634. CIRCWINDOW_START_MAX) {
  1635. static struct ratelim_t client_warn_ratelim = RATELIM_INIT(600);
  1636. log_fn_ratelim(&client_warn_ratelim,LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1637. "Unexpected sendme cell from client. "
  1638. "Closing circ (window %d).",
  1639. circ->package_window);
  1640. return -END_CIRC_REASON_TORPROTOCOL;
  1641. }
  1642. circ->package_window += CIRCWINDOW_INCREMENT;
  1643. log_debug(LD_APP,
  1644. "circ-level sendme at non-origin, packagewindow %d.",
  1645. circ->package_window);
  1646. circuit_resume_edge_reading(circ, layer_hint);
  1647. }
  1648. return 0;
  1649. }
  1650. if (!conn) {
  1651. log_info(domain,"sendme cell dropped, unknown stream (streamid %d).",
  1652. rh.stream_id);
  1653. return 0;
  1654. }
  1655. conn->package_window += STREAMWINDOW_INCREMENT;
  1656. log_debug(domain,"stream-level sendme, packagewindow now %d.",
  1657. conn->package_window);
  1658. if (circuit_queue_streams_are_blocked(circ)) {
  1659. /* Still waiting for queue to flush; don't touch conn */
  1660. return 0;
  1661. }
  1662. connection_start_reading(TO_CONN(conn));
  1663. /* handle whatever might still be on the inbuf */
  1664. if (connection_edge_package_raw_inbuf(conn, 1, NULL) < 0) {
  1665. /* (We already sent an end cell if possible) */
  1666. connection_mark_for_close(TO_CONN(conn));
  1667. return 0;
  1668. }
  1669. return 0;
  1670. case RELAY_COMMAND_RESOLVE:
  1671. if (layer_hint) {
  1672. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  1673. "resolve request unsupported at AP; dropping.");
  1674. return 0;
  1675. } else if (conn) {
  1676. log_fn(LOG_PROTOCOL_WARN, domain,
  1677. "resolve request for known stream; dropping.");
  1678. return 0;
  1679. } else if (circ->purpose != CIRCUIT_PURPOSE_OR) {
  1680. log_fn(LOG_PROTOCOL_WARN, domain,
  1681. "resolve request on circ with purpose %d; dropping",
  1682. circ->purpose);
  1683. return 0;
  1684. }
  1685. connection_exit_begin_resolve(cell, TO_OR_CIRCUIT(circ));
  1686. return 0;
  1687. case RELAY_COMMAND_RESOLVED:
  1688. if (conn) {
  1689. log_fn(LOG_PROTOCOL_WARN, domain,
  1690. "'resolved' unsupported while open. Closing circ.");
  1691. return -END_CIRC_REASON_TORPROTOCOL;
  1692. }
  1693. log_info(domain,
  1694. "'resolved' received, no conn attached anymore. Ignoring.");
  1695. return 0;
  1696. case RELAY_COMMAND_ESTABLISH_INTRO:
  1697. case RELAY_COMMAND_ESTABLISH_RENDEZVOUS:
  1698. case RELAY_COMMAND_INTRODUCE1:
  1699. case RELAY_COMMAND_INTRODUCE2:
  1700. case RELAY_COMMAND_INTRODUCE_ACK:
  1701. case RELAY_COMMAND_RENDEZVOUS1:
  1702. case RELAY_COMMAND_RENDEZVOUS2:
  1703. case RELAY_COMMAND_INTRO_ESTABLISHED:
  1704. case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
  1705. rend_process_relay_cell(circ, layer_hint,
  1706. rh.command, rh.length,
  1707. cell->payload+RELAY_HEADER_SIZE);
  1708. return 0;
  1709. }
  1710. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1711. "Received unknown relay command %d. Perhaps the other side is using "
  1712. "a newer version of Tor? Dropping.",
  1713. rh.command);
  1714. return 0; /* for forward compatibility, don't kill the circuit */
  1715. }
  1716. /** How many relay_data cells have we built, ever? */
  1717. uint64_t stats_n_data_cells_packaged = 0;
  1718. /** How many bytes of data have we put in relay_data cells have we built,
  1719. * ever? This would be RELAY_PAYLOAD_SIZE*stats_n_data_cells_packaged if
  1720. * every relay cell we ever sent were completely full of data. */
  1721. uint64_t stats_n_data_bytes_packaged = 0;
  1722. /** How many relay_data cells have we received, ever? */
  1723. uint64_t stats_n_data_cells_received = 0;
  1724. /** How many bytes of data have we received relay_data cells, ever? This would
  1725. * be RELAY_PAYLOAD_SIZE*stats_n_data_cells_packaged if every relay cell we
  1726. * ever received were completely full of data. */
  1727. uint64_t stats_n_data_bytes_received = 0;
  1728. /** If <b>conn</b> has an entire relay payload of bytes on its inbuf (or
  1729. * <b>package_partial</b> is true), and the appropriate package windows aren't
  1730. * empty, grab a cell and send it down the circuit.
  1731. *
  1732. * If *<b>max_cells</b> is given, package no more than max_cells. Decrement
  1733. * *<b>max_cells</b> by the number of cells packaged.
  1734. *
  1735. * Return -1 (and send a RELAY_COMMAND_END cell if necessary) if conn should
  1736. * be marked for close, else return 0.
  1737. */
  1738. int
  1739. connection_edge_package_raw_inbuf(edge_connection_t *conn, int package_partial,
  1740. int *max_cells)
  1741. {
  1742. size_t bytes_to_process, length;
  1743. char payload[CELL_PAYLOAD_SIZE];
  1744. circuit_t *circ;
  1745. const unsigned domain = conn->base_.type == CONN_TYPE_AP ? LD_APP : LD_EXIT;
  1746. int sending_from_optimistic = 0;
  1747. entry_connection_t *entry_conn =
  1748. conn->base_.type == CONN_TYPE_AP ? EDGE_TO_ENTRY_CONN(conn) : NULL;
  1749. const int sending_optimistically =
  1750. entry_conn &&
  1751. conn->base_.type == CONN_TYPE_AP &&
  1752. conn->base_.state != AP_CONN_STATE_OPEN;
  1753. crypt_path_t *cpath_layer = conn->cpath_layer;
  1754. tor_assert(conn);
  1755. if (conn->base_.marked_for_close) {
  1756. log_warn(LD_BUG,
  1757. "called on conn that's already marked for close at %s:%d.",
  1758. conn->base_.marked_for_close_file, conn->base_.marked_for_close);
  1759. return 0;
  1760. }
  1761. if (max_cells && *max_cells <= 0)
  1762. return 0;
  1763. repeat_connection_edge_package_raw_inbuf:
  1764. circ = circuit_get_by_edge_conn(conn);
  1765. if (!circ) {
  1766. log_info(domain,"conn has no circuit! Closing.");
  1767. conn->end_reason = END_STREAM_REASON_CANT_ATTACH;
  1768. return -1;
  1769. }
  1770. if (circuit_consider_stop_edge_reading(circ, cpath_layer))
  1771. return 0;
  1772. if (conn->package_window <= 0) {
  1773. log_info(domain,"called with package_window %d. Skipping.",
  1774. conn->package_window);
  1775. connection_stop_reading(TO_CONN(conn));
  1776. return 0;
  1777. }
  1778. sending_from_optimistic = entry_conn &&
  1779. entry_conn->sending_optimistic_data != NULL;
  1780. if (PREDICT_UNLIKELY(sending_from_optimistic)) {
  1781. bytes_to_process = buf_datalen(entry_conn->sending_optimistic_data);
  1782. if (PREDICT_UNLIKELY(!bytes_to_process)) {
  1783. log_warn(LD_BUG, "sending_optimistic_data was non-NULL but empty");
  1784. bytes_to_process = connection_get_inbuf_len(TO_CONN(conn));
  1785. sending_from_optimistic = 0;
  1786. }
  1787. } else {
  1788. bytes_to_process = connection_get_inbuf_len(TO_CONN(conn));
  1789. }
  1790. if (!bytes_to_process)
  1791. return 0;
  1792. if (!package_partial && bytes_to_process < RELAY_PAYLOAD_SIZE)
  1793. return 0;
  1794. if (bytes_to_process > RELAY_PAYLOAD_SIZE) {
  1795. length = RELAY_PAYLOAD_SIZE;
  1796. } else {
  1797. length = bytes_to_process;
  1798. }
  1799. stats_n_data_bytes_packaged += length;
  1800. stats_n_data_cells_packaged += 1;
  1801. if (PREDICT_UNLIKELY(sending_from_optimistic)) {
  1802. /* XXXX We could be more efficient here by sometimes packing
  1803. * previously-sent optimistic data in the same cell with data
  1804. * from the inbuf. */
  1805. buf_get_bytes(entry_conn->sending_optimistic_data, payload, length);
  1806. if (!buf_datalen(entry_conn->sending_optimistic_data)) {
  1807. buf_free(entry_conn->sending_optimistic_data);
  1808. entry_conn->sending_optimistic_data = NULL;
  1809. }
  1810. } else {
  1811. connection_buf_get_bytes(payload, length, TO_CONN(conn));
  1812. }
  1813. log_debug(domain,TOR_SOCKET_T_FORMAT": Packaging %d bytes (%d waiting).",
  1814. conn->base_.s,
  1815. (int)length, (int)connection_get_inbuf_len(TO_CONN(conn)));
  1816. if (sending_optimistically && !sending_from_optimistic) {
  1817. /* This is new optimistic data; remember it in case we need to detach and
  1818. retry */
  1819. if (!entry_conn->pending_optimistic_data)
  1820. entry_conn->pending_optimistic_data = buf_new();
  1821. buf_add(entry_conn->pending_optimistic_data, payload, length);
  1822. }
  1823. if (connection_edge_send_command(conn, RELAY_COMMAND_DATA,
  1824. payload, length) < 0 )
  1825. /* circuit got marked for close, don't continue, don't need to mark conn */
  1826. return 0;
  1827. if (!cpath_layer) { /* non-rendezvous exit */
  1828. tor_assert(circ->package_window > 0);
  1829. circ->package_window--;
  1830. } else { /* we're an AP, or an exit on a rendezvous circ */
  1831. tor_assert(cpath_layer->package_window > 0);
  1832. cpath_layer->package_window--;
  1833. }
  1834. if (--conn->package_window <= 0) { /* is it 0 after decrement? */
  1835. connection_stop_reading(TO_CONN(conn));
  1836. log_debug(domain,"conn->package_window reached 0.");
  1837. circuit_consider_stop_edge_reading(circ, cpath_layer);
  1838. return 0; /* don't process the inbuf any more */
  1839. }
  1840. log_debug(domain,"conn->package_window is now %d",conn->package_window);
  1841. if (max_cells) {
  1842. *max_cells -= 1;
  1843. if (*max_cells <= 0)
  1844. return 0;
  1845. }
  1846. /* handle more if there's more, or return 0 if there isn't */
  1847. goto repeat_connection_edge_package_raw_inbuf;
  1848. }
  1849. /** Called when we've just received a relay data cell, when
  1850. * we've just finished flushing all bytes to stream <b>conn</b>,
  1851. * or when we've flushed *some* bytes to the stream <b>conn</b>.
  1852. *
  1853. * If conn->outbuf is not too full, and our deliver window is
  1854. * low, send back a suitable number of stream-level sendme cells.
  1855. */
  1856. void
  1857. connection_edge_consider_sending_sendme(edge_connection_t *conn)
  1858. {
  1859. circuit_t *circ;
  1860. if (connection_outbuf_too_full(TO_CONN(conn)))
  1861. return;
  1862. circ = circuit_get_by_edge_conn(conn);
  1863. if (!circ) {
  1864. /* this can legitimately happen if the destroy has already
  1865. * arrived and torn down the circuit */
  1866. log_info(LD_APP,"No circuit associated with conn. Skipping.");
  1867. return;
  1868. }
  1869. while (conn->deliver_window <= STREAMWINDOW_START - STREAMWINDOW_INCREMENT) {
  1870. log_debug(conn->base_.type == CONN_TYPE_AP ?LD_APP:LD_EXIT,
  1871. "Outbuf %d, Queuing stream sendme.",
  1872. (int)conn->base_.outbuf_flushlen);
  1873. conn->deliver_window += STREAMWINDOW_INCREMENT;
  1874. if (connection_edge_send_command(conn, RELAY_COMMAND_SENDME,
  1875. NULL, 0) < 0) {
  1876. log_warn(LD_APP,"connection_edge_send_command failed. Skipping.");
  1877. return; /* the circuit's closed, don't continue */
  1878. }
  1879. }
  1880. }
  1881. /** The circuit <b>circ</b> has received a circuit-level sendme
  1882. * (on hop <b>layer_hint</b>, if we're the OP). Go through all the
  1883. * attached streams and let them resume reading and packaging, if
  1884. * their stream windows allow it.
  1885. */
  1886. static void
  1887. circuit_resume_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
  1888. {
  1889. if (circuit_queue_streams_are_blocked(circ)) {
  1890. log_debug(layer_hint?LD_APP:LD_EXIT,"Too big queue, no resuming");
  1891. return;
  1892. }
  1893. log_debug(layer_hint?LD_APP:LD_EXIT,"resuming");
  1894. if (CIRCUIT_IS_ORIGIN(circ))
  1895. circuit_resume_edge_reading_helper(TO_ORIGIN_CIRCUIT(circ)->p_streams,
  1896. circ, layer_hint);
  1897. else
  1898. circuit_resume_edge_reading_helper(TO_OR_CIRCUIT(circ)->n_streams,
  1899. circ, layer_hint);
  1900. }
  1901. void
  1902. stream_choice_seed_weak_rng(void)
  1903. {
  1904. crypto_seed_weak_rng(&stream_choice_rng);
  1905. }
  1906. /** A helper function for circuit_resume_edge_reading() above.
  1907. * The arguments are the same, except that <b>conn</b> is the head
  1908. * of a linked list of edge streams that should each be considered.
  1909. */
  1910. static int
  1911. circuit_resume_edge_reading_helper(edge_connection_t *first_conn,
  1912. circuit_t *circ,
  1913. crypt_path_t *layer_hint)
  1914. {
  1915. edge_connection_t *conn;
  1916. int n_packaging_streams, n_streams_left;
  1917. int packaged_this_round;
  1918. int cells_on_queue;
  1919. int cells_per_conn;
  1920. edge_connection_t *chosen_stream = NULL;
  1921. int max_to_package;
  1922. if (first_conn == NULL) {
  1923. /* Don't bother to try to do the rest of this if there are no connections
  1924. * to resume. */
  1925. return 0;
  1926. }
  1927. /* How many cells do we have space for? It will be the minimum of
  1928. * the number needed to exhaust the package window, and the minimum
  1929. * needed to fill the cell queue. */
  1930. max_to_package = circ->package_window;
  1931. if (CIRCUIT_IS_ORIGIN(circ)) {
  1932. cells_on_queue = circ->n_chan_cells.n;
  1933. } else {
  1934. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  1935. cells_on_queue = or_circ->p_chan_cells.n;
  1936. }
  1937. if (CELL_QUEUE_HIGHWATER_SIZE - cells_on_queue < max_to_package)
  1938. max_to_package = CELL_QUEUE_HIGHWATER_SIZE - cells_on_queue;
  1939. /* Once we used to start listening on the streams in the order they
  1940. * appeared in the linked list. That leads to starvation on the
  1941. * streams that appeared later on the list, since the first streams
  1942. * would always get to read first. Instead, we just pick a random
  1943. * stream on the list, and enable reading for streams starting at that
  1944. * point (and wrapping around as if the list were circular). It would
  1945. * probably be better to actually remember which streams we've
  1946. * serviced in the past, but this is simple and effective. */
  1947. /* Select a stream uniformly at random from the linked list. We
  1948. * don't need cryptographic randomness here. */
  1949. {
  1950. int num_streams = 0;
  1951. for (conn = first_conn; conn; conn = conn->next_stream) {
  1952. num_streams++;
  1953. if (tor_weak_random_one_in_n(&stream_choice_rng, num_streams)) {
  1954. chosen_stream = conn;
  1955. }
  1956. /* Invariant: chosen_stream has been chosen uniformly at random from
  1957. * among the first num_streams streams on first_conn.
  1958. *
  1959. * (Note that we iterate over every stream on the circuit, so that after
  1960. * we've considered the first stream, we've chosen it with P=1; and
  1961. * after we consider the second stream, we've switched to it with P=1/2
  1962. * and stayed with the first stream with P=1/2; and after we've
  1963. * considered the third stream, we've switched to it with P=1/3 and
  1964. * remained with one of the first two streams with P=(2/3), giving each
  1965. * one P=(1/2)(2/3) )=(1/3).) */
  1966. }
  1967. }
  1968. /* Count how many non-marked streams there are that have anything on
  1969. * their inbuf, and enable reading on all of the connections. */
  1970. n_packaging_streams = 0;
  1971. /* Activate reading starting from the chosen stream */
  1972. for (conn=chosen_stream; conn; conn = conn->next_stream) {
  1973. /* Start reading for the streams starting from here */
  1974. if (conn->base_.marked_for_close || conn->package_window <= 0)
  1975. continue;
  1976. if (!layer_hint || conn->cpath_layer == layer_hint) {
  1977. connection_start_reading(TO_CONN(conn));
  1978. if (connection_get_inbuf_len(TO_CONN(conn)) > 0)
  1979. ++n_packaging_streams;
  1980. }
  1981. }
  1982. /* Go back and do the ones we skipped, circular-style */
  1983. for (conn = first_conn; conn != chosen_stream; conn = conn->next_stream) {
  1984. if (conn->base_.marked_for_close || conn->package_window <= 0)
  1985. continue;
  1986. if (!layer_hint || conn->cpath_layer == layer_hint) {
  1987. connection_start_reading(TO_CONN(conn));
  1988. if (connection_get_inbuf_len(TO_CONN(conn)) > 0)
  1989. ++n_packaging_streams;
  1990. }
  1991. }
  1992. if (n_packaging_streams == 0) /* avoid divide-by-zero */
  1993. return 0;
  1994. again:
  1995. cells_per_conn = CEIL_DIV(max_to_package, n_packaging_streams);
  1996. packaged_this_round = 0;
  1997. n_streams_left = 0;
  1998. /* Iterate over all connections. Package up to cells_per_conn cells on
  1999. * each. Update packaged_this_round with the total number of cells
  2000. * packaged, and n_streams_left with the number that still have data to
  2001. * package.
  2002. */
  2003. for (conn=first_conn; conn; conn=conn->next_stream) {
  2004. if (conn->base_.marked_for_close || conn->package_window <= 0)
  2005. continue;
  2006. if (!layer_hint || conn->cpath_layer == layer_hint) {
  2007. int n = cells_per_conn, r;
  2008. /* handle whatever might still be on the inbuf */
  2009. r = connection_edge_package_raw_inbuf(conn, 1, &n);
  2010. /* Note how many we packaged */
  2011. packaged_this_round += (cells_per_conn-n);
  2012. if (r<0) {
  2013. /* Problem while packaging. (We already sent an end cell if
  2014. * possible) */
  2015. connection_mark_for_close(TO_CONN(conn));
  2016. continue;
  2017. }
  2018. /* If there's still data to read, we'll be coming back to this stream. */
  2019. if (connection_get_inbuf_len(TO_CONN(conn)))
  2020. ++n_streams_left;
  2021. /* If the circuit won't accept any more data, return without looking
  2022. * at any more of the streams. Any connections that should be stopped
  2023. * have already been stopped by connection_edge_package_raw_inbuf. */
  2024. if (circuit_consider_stop_edge_reading(circ, layer_hint))
  2025. return -1;
  2026. /* XXXX should we also stop immediately if we fill up the cell queue?
  2027. * Probably. */
  2028. }
  2029. }
  2030. /* If we made progress, and we are willing to package more, and there are
  2031. * any streams left that want to package stuff... try again!
  2032. */
  2033. if (packaged_this_round && packaged_this_round < max_to_package &&
  2034. n_streams_left) {
  2035. max_to_package -= packaged_this_round;
  2036. n_packaging_streams = n_streams_left;
  2037. goto again;
  2038. }
  2039. return 0;
  2040. }
  2041. /** Check if the package window for <b>circ</b> is empty (at
  2042. * hop <b>layer_hint</b> if it's defined).
  2043. *
  2044. * If yes, tell edge streams to stop reading and return 1.
  2045. * Else return 0.
  2046. */
  2047. static int
  2048. circuit_consider_stop_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
  2049. {
  2050. edge_connection_t *conn = NULL;
  2051. unsigned domain = layer_hint ? LD_APP : LD_EXIT;
  2052. if (!layer_hint) {
  2053. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  2054. log_debug(domain,"considering circ->package_window %d",
  2055. circ->package_window);
  2056. if (circ->package_window <= 0) {
  2057. log_debug(domain,"yes, not-at-origin. stopped.");
  2058. for (conn = or_circ->n_streams; conn; conn=conn->next_stream)
  2059. connection_stop_reading(TO_CONN(conn));
  2060. return 1;
  2061. }
  2062. return 0;
  2063. }
  2064. /* else, layer hint is defined, use it */
  2065. log_debug(domain,"considering layer_hint->package_window %d",
  2066. layer_hint->package_window);
  2067. if (layer_hint->package_window <= 0) {
  2068. log_debug(domain,"yes, at-origin. stopped.");
  2069. for (conn = TO_ORIGIN_CIRCUIT(circ)->p_streams; conn;
  2070. conn=conn->next_stream) {
  2071. if (conn->cpath_layer == layer_hint)
  2072. connection_stop_reading(TO_CONN(conn));
  2073. }
  2074. return 1;
  2075. }
  2076. return 0;
  2077. }
  2078. /** Check if the deliver_window for circuit <b>circ</b> (at hop
  2079. * <b>layer_hint</b> if it's defined) is low enough that we should
  2080. * send a circuit-level sendme back down the circuit. If so, send
  2081. * enough sendmes that the window would be overfull if we sent any
  2082. * more.
  2083. */
  2084. static void
  2085. circuit_consider_sending_sendme(circuit_t *circ, crypt_path_t *layer_hint)
  2086. {
  2087. // log_fn(LOG_INFO,"Considering: layer_hint is %s",
  2088. // layer_hint ? "defined" : "null");
  2089. while ((layer_hint ? layer_hint->deliver_window : circ->deliver_window) <=
  2090. CIRCWINDOW_START - CIRCWINDOW_INCREMENT) {
  2091. log_debug(LD_CIRC,"Queuing circuit sendme.");
  2092. if (layer_hint)
  2093. layer_hint->deliver_window += CIRCWINDOW_INCREMENT;
  2094. else
  2095. circ->deliver_window += CIRCWINDOW_INCREMENT;
  2096. if (relay_send_command_from_edge(0, circ, RELAY_COMMAND_SENDME,
  2097. NULL, 0, layer_hint) < 0) {
  2098. log_warn(LD_CIRC,
  2099. "relay_send_command_from_edge failed. Circuit's closed.");
  2100. return; /* the circuit's closed, don't continue */
  2101. }
  2102. }
  2103. }
  2104. /** The total number of cells we have allocated. */
  2105. static size_t total_cells_allocated = 0;
  2106. /** Release storage held by <b>cell</b>. */
  2107. static inline void
  2108. packed_cell_free_unchecked(packed_cell_t *cell)
  2109. {
  2110. --total_cells_allocated;
  2111. tor_free(cell);
  2112. }
  2113. /** Allocate and return a new packed_cell_t. */
  2114. STATIC packed_cell_t *
  2115. packed_cell_new(void)
  2116. {
  2117. ++total_cells_allocated;
  2118. return tor_malloc_zero(sizeof(packed_cell_t));
  2119. }
  2120. /** Return a packed cell used outside by channel_t lower layer */
  2121. void
  2122. packed_cell_free_(packed_cell_t *cell)
  2123. {
  2124. if (!cell)
  2125. return;
  2126. packed_cell_free_unchecked(cell);
  2127. }
  2128. /** Log current statistics for cell pool allocation at log level
  2129. * <b>severity</b>. */
  2130. void
  2131. dump_cell_pool_usage(int severity)
  2132. {
  2133. int n_circs = 0;
  2134. int n_cells = 0;
  2135. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, c) {
  2136. n_cells += c->n_chan_cells.n;
  2137. if (!CIRCUIT_IS_ORIGIN(c))
  2138. n_cells += TO_OR_CIRCUIT(c)->p_chan_cells.n;
  2139. ++n_circs;
  2140. }
  2141. SMARTLIST_FOREACH_END(c);
  2142. tor_log(severity, LD_MM,
  2143. "%d cells allocated on %d circuits. %d cells leaked.",
  2144. n_cells, n_circs, (int)total_cells_allocated - n_cells);
  2145. }
  2146. /** Allocate a new copy of packed <b>cell</b>. */
  2147. static inline packed_cell_t *
  2148. packed_cell_copy(const cell_t *cell, int wide_circ_ids)
  2149. {
  2150. packed_cell_t *c = packed_cell_new();
  2151. cell_pack(c, cell, wide_circ_ids);
  2152. return c;
  2153. }
  2154. /** Append <b>cell</b> to the end of <b>queue</b>. */
  2155. void
  2156. cell_queue_append(cell_queue_t *queue, packed_cell_t *cell)
  2157. {
  2158. TOR_SIMPLEQ_INSERT_TAIL(&queue->head, cell, next);
  2159. ++queue->n;
  2160. }
  2161. /** Append a newly allocated copy of <b>cell</b> to the end of the
  2162. * <b>exitward</b> (or app-ward) <b>queue</b> of <b>circ</b>. If
  2163. * <b>use_stats</b> is true, record statistics about the cell.
  2164. */
  2165. void
  2166. cell_queue_append_packed_copy(circuit_t *circ, cell_queue_t *queue,
  2167. int exitward, const cell_t *cell,
  2168. int wide_circ_ids, int use_stats)
  2169. {
  2170. packed_cell_t *copy = packed_cell_copy(cell, wide_circ_ids);
  2171. (void)circ;
  2172. (void)exitward;
  2173. (void)use_stats;
  2174. copy->inserted_timestamp = monotime_coarse_get_stamp();
  2175. cell_queue_append(queue, copy);
  2176. }
  2177. /** Initialize <b>queue</b> as an empty cell queue. */
  2178. void
  2179. cell_queue_init(cell_queue_t *queue)
  2180. {
  2181. memset(queue, 0, sizeof(cell_queue_t));
  2182. TOR_SIMPLEQ_INIT(&queue->head);
  2183. }
  2184. /** Remove and free every cell in <b>queue</b>. */
  2185. void
  2186. cell_queue_clear(cell_queue_t *queue)
  2187. {
  2188. packed_cell_t *cell;
  2189. while ((cell = TOR_SIMPLEQ_FIRST(&queue->head))) {
  2190. TOR_SIMPLEQ_REMOVE_HEAD(&queue->head, next);
  2191. packed_cell_free_unchecked(cell);
  2192. }
  2193. TOR_SIMPLEQ_INIT(&queue->head);
  2194. queue->n = 0;
  2195. }
  2196. /** Extract and return the cell at the head of <b>queue</b>; return NULL if
  2197. * <b>queue</b> is empty. */
  2198. STATIC packed_cell_t *
  2199. cell_queue_pop(cell_queue_t *queue)
  2200. {
  2201. packed_cell_t *cell = TOR_SIMPLEQ_FIRST(&queue->head);
  2202. if (!cell)
  2203. return NULL;
  2204. TOR_SIMPLEQ_REMOVE_HEAD(&queue->head, next);
  2205. --queue->n;
  2206. return cell;
  2207. }
  2208. /** Initialize <b>queue</b> as an empty cell queue. */
  2209. void
  2210. destroy_cell_queue_init(destroy_cell_queue_t *queue)
  2211. {
  2212. memset(queue, 0, sizeof(destroy_cell_queue_t));
  2213. TOR_SIMPLEQ_INIT(&queue->head);
  2214. }
  2215. /** Remove and free every cell in <b>queue</b>. */
  2216. void
  2217. destroy_cell_queue_clear(destroy_cell_queue_t *queue)
  2218. {
  2219. destroy_cell_t *cell;
  2220. while ((cell = TOR_SIMPLEQ_FIRST(&queue->head))) {
  2221. TOR_SIMPLEQ_REMOVE_HEAD(&queue->head, next);
  2222. tor_free(cell);
  2223. }
  2224. TOR_SIMPLEQ_INIT(&queue->head);
  2225. queue->n = 0;
  2226. }
  2227. /** Extract and return the cell at the head of <b>queue</b>; return NULL if
  2228. * <b>queue</b> is empty. */
  2229. STATIC destroy_cell_t *
  2230. destroy_cell_queue_pop(destroy_cell_queue_t *queue)
  2231. {
  2232. destroy_cell_t *cell = TOR_SIMPLEQ_FIRST(&queue->head);
  2233. if (!cell)
  2234. return NULL;
  2235. TOR_SIMPLEQ_REMOVE_HEAD(&queue->head, next);
  2236. --queue->n;
  2237. return cell;
  2238. }
  2239. /** Append a destroy cell for <b>circid</b> to <b>queue</b>. */
  2240. void
  2241. destroy_cell_queue_append(destroy_cell_queue_t *queue,
  2242. circid_t circid,
  2243. uint8_t reason)
  2244. {
  2245. destroy_cell_t *cell = tor_malloc_zero(sizeof(destroy_cell_t));
  2246. cell->circid = circid;
  2247. cell->reason = reason;
  2248. /* Not yet used, but will be required for OOM handling. */
  2249. cell->inserted_timestamp = monotime_coarse_get_stamp();
  2250. TOR_SIMPLEQ_INSERT_TAIL(&queue->head, cell, next);
  2251. ++queue->n;
  2252. }
  2253. /** Convert a destroy_cell_t to a newly allocated cell_t. Frees its input. */
  2254. static packed_cell_t *
  2255. destroy_cell_to_packed_cell(destroy_cell_t *inp, int wide_circ_ids)
  2256. {
  2257. packed_cell_t *packed = packed_cell_new();
  2258. cell_t cell;
  2259. memset(&cell, 0, sizeof(cell));
  2260. cell.circ_id = inp->circid;
  2261. cell.command = CELL_DESTROY;
  2262. cell.payload[0] = inp->reason;
  2263. cell_pack(packed, &cell, wide_circ_ids);
  2264. tor_free(inp);
  2265. return packed;
  2266. }
  2267. /** Return the total number of bytes used for each packed_cell in a queue.
  2268. * Approximate. */
  2269. size_t
  2270. packed_cell_mem_cost(void)
  2271. {
  2272. return sizeof(packed_cell_t);
  2273. }
  2274. /* DOCDOC */
  2275. size_t
  2276. cell_queues_get_total_allocation(void)
  2277. {
  2278. return total_cells_allocated * packed_cell_mem_cost();
  2279. }
  2280. /** How long after we've been low on memory should we try to conserve it? */
  2281. #define MEMORY_PRESSURE_INTERVAL (30*60)
  2282. /** The time at which we were last low on memory. */
  2283. static time_t last_time_under_memory_pressure = 0;
  2284. /** Check whether we've got too much space used for cells. If so,
  2285. * call the OOM handler and return 1. Otherwise, return 0. */
  2286. STATIC int
  2287. cell_queues_check_size(void)
  2288. {
  2289. time_t now = time(NULL);
  2290. size_t alloc = cell_queues_get_total_allocation();
  2291. alloc += buf_get_total_allocation();
  2292. alloc += tor_compress_get_total_allocation();
  2293. const size_t rend_cache_total = rend_cache_get_total_allocation();
  2294. alloc += rend_cache_total;
  2295. const size_t geoip_client_cache_total =
  2296. geoip_client_cache_total_allocation();
  2297. alloc += geoip_client_cache_total;
  2298. if (alloc >= get_options()->MaxMemInQueues_low_threshold) {
  2299. last_time_under_memory_pressure = approx_time();
  2300. if (alloc >= get_options()->MaxMemInQueues) {
  2301. /* If we're spending over 20% of the memory limit on hidden service
  2302. * descriptors, free them until we're down to 10%. Do the same for geoip
  2303. * client cache. */
  2304. if (rend_cache_total > get_options()->MaxMemInQueues / 5) {
  2305. const size_t bytes_to_remove =
  2306. rend_cache_total - (size_t)(get_options()->MaxMemInQueues / 10);
  2307. alloc -= hs_cache_handle_oom(now, bytes_to_remove);
  2308. }
  2309. if (geoip_client_cache_total > get_options()->MaxMemInQueues / 5) {
  2310. const size_t bytes_to_remove =
  2311. geoip_client_cache_total -
  2312. (size_t)(get_options()->MaxMemInQueues / 10);
  2313. alloc -= geoip_client_cache_handle_oom(now, bytes_to_remove);
  2314. }
  2315. circuits_handle_oom(alloc);
  2316. return 1;
  2317. }
  2318. }
  2319. return 0;
  2320. }
  2321. /** Return true if we've been under memory pressure in the last
  2322. * MEMORY_PRESSURE_INTERVAL seconds. */
  2323. int
  2324. have_been_under_memory_pressure(void)
  2325. {
  2326. return last_time_under_memory_pressure + MEMORY_PRESSURE_INTERVAL
  2327. < approx_time();
  2328. }
  2329. /**
  2330. * Update the number of cells available on the circuit's n_chan or p_chan's
  2331. * circuit mux.
  2332. */
  2333. void
  2334. update_circuit_on_cmux_(circuit_t *circ, cell_direction_t direction,
  2335. const char *file, int lineno)
  2336. {
  2337. channel_t *chan = NULL;
  2338. or_circuit_t *or_circ = NULL;
  2339. circuitmux_t *cmux = NULL;
  2340. tor_assert(circ);
  2341. /* Okay, get the channel */
  2342. if (direction == CELL_DIRECTION_OUT) {
  2343. chan = circ->n_chan;
  2344. } else {
  2345. or_circ = TO_OR_CIRCUIT(circ);
  2346. chan = or_circ->p_chan;
  2347. }
  2348. tor_assert(chan);
  2349. tor_assert(chan->cmux);
  2350. /* Now get the cmux */
  2351. cmux = chan->cmux;
  2352. /* Cmux sanity check */
  2353. if (! circuitmux_is_circuit_attached(cmux, circ)) {
  2354. log_warn(LD_BUG, "called on non-attached circuit from %s:%d",
  2355. file, lineno);
  2356. return;
  2357. }
  2358. tor_assert(circuitmux_attached_circuit_direction(cmux, circ) == direction);
  2359. /* Update the number of cells we have for the circuit mux */
  2360. if (direction == CELL_DIRECTION_OUT) {
  2361. circuitmux_set_num_cells(cmux, circ, circ->n_chan_cells.n);
  2362. } else {
  2363. circuitmux_set_num_cells(cmux, circ, or_circ->p_chan_cells.n);
  2364. }
  2365. }
  2366. /** Remove all circuits from the cmux on <b>chan</b>.
  2367. *
  2368. * If <b>circuits_out</b> is non-NULL, add all detached circuits to
  2369. * <b>circuits_out</b>.
  2370. **/
  2371. void
  2372. channel_unlink_all_circuits(channel_t *chan, smartlist_t *circuits_out)
  2373. {
  2374. tor_assert(chan);
  2375. tor_assert(chan->cmux);
  2376. circuitmux_detach_all_circuits(chan->cmux, circuits_out);
  2377. chan->num_n_circuits = 0;
  2378. chan->num_p_circuits = 0;
  2379. }
  2380. /** Block (if <b>block</b> is true) or unblock (if <b>block</b> is false)
  2381. * every edge connection that is using <b>circ</b> to write to <b>chan</b>,
  2382. * and start or stop reading as appropriate.
  2383. *
  2384. * If <b>stream_id</b> is nonzero, block only the edge connection whose
  2385. * stream_id matches it.
  2386. *
  2387. * Returns the number of streams whose status we changed.
  2388. */
  2389. static int
  2390. set_streams_blocked_on_circ(circuit_t *circ, channel_t *chan,
  2391. int block, streamid_t stream_id)
  2392. {
  2393. edge_connection_t *edge = NULL;
  2394. int n = 0;
  2395. if (circ->n_chan == chan) {
  2396. circ->streams_blocked_on_n_chan = block;
  2397. if (CIRCUIT_IS_ORIGIN(circ))
  2398. edge = TO_ORIGIN_CIRCUIT(circ)->p_streams;
  2399. } else {
  2400. circ->streams_blocked_on_p_chan = block;
  2401. tor_assert(!CIRCUIT_IS_ORIGIN(circ));
  2402. edge = TO_OR_CIRCUIT(circ)->n_streams;
  2403. }
  2404. for (; edge; edge = edge->next_stream) {
  2405. connection_t *conn = TO_CONN(edge);
  2406. if (stream_id && edge->stream_id != stream_id)
  2407. continue;
  2408. if (edge->edge_blocked_on_circ != block) {
  2409. ++n;
  2410. edge->edge_blocked_on_circ = block;
  2411. }
  2412. if (!conn->read_event) {
  2413. /* This connection is a placeholder for something; probably a DNS
  2414. * request. It can't actually stop or start reading.*/
  2415. continue;
  2416. }
  2417. if (block) {
  2418. if (connection_is_reading(conn))
  2419. connection_stop_reading(conn);
  2420. } else {
  2421. /* Is this right? */
  2422. if (!connection_is_reading(conn))
  2423. connection_start_reading(conn);
  2424. }
  2425. }
  2426. return n;
  2427. }
  2428. /** Extract the command from a packed cell. */
  2429. static uint8_t
  2430. packed_cell_get_command(const packed_cell_t *cell, int wide_circ_ids)
  2431. {
  2432. if (wide_circ_ids) {
  2433. return get_uint8(cell->body+4);
  2434. } else {
  2435. return get_uint8(cell->body+2);
  2436. }
  2437. }
  2438. /** Extract the circuit ID from a packed cell. */
  2439. circid_t
  2440. packed_cell_get_circid(const packed_cell_t *cell, int wide_circ_ids)
  2441. {
  2442. if (wide_circ_ids) {
  2443. return ntohl(get_uint32(cell->body));
  2444. } else {
  2445. return ntohs(get_uint16(cell->body));
  2446. }
  2447. }
  2448. /** Pull as many cells as possible (but no more than <b>max</b>) from the
  2449. * queue of the first active circuit on <b>chan</b>, and write them to
  2450. * <b>chan</b>-&gt;outbuf. Return the number of cells written. Advance
  2451. * the active circuit pointer to the next active circuit in the ring. */
  2452. MOCK_IMPL(int,
  2453. channel_flush_from_first_active_circuit, (channel_t *chan, int max))
  2454. {
  2455. circuitmux_t *cmux = NULL;
  2456. int n_flushed = 0;
  2457. cell_queue_t *queue;
  2458. destroy_cell_queue_t *destroy_queue=NULL;
  2459. circuit_t *circ;
  2460. or_circuit_t *or_circ;
  2461. int streams_blocked;
  2462. packed_cell_t *cell;
  2463. /* Get the cmux */
  2464. tor_assert(chan);
  2465. tor_assert(chan->cmux);
  2466. cmux = chan->cmux;
  2467. /* Main loop: pick a circuit, send a cell, update the cmux */
  2468. while (n_flushed < max) {
  2469. circ = circuitmux_get_first_active_circuit(cmux, &destroy_queue);
  2470. if (destroy_queue) {
  2471. destroy_cell_t *dcell;
  2472. /* this code is duplicated from some of the logic below. Ugly! XXXX */
  2473. /* If we are given a destroy_queue here, then it is required to be
  2474. * nonempty... */
  2475. tor_assert(destroy_queue->n > 0);
  2476. dcell = destroy_cell_queue_pop(destroy_queue);
  2477. /* ...and pop() will always yield a cell from a nonempty queue. */
  2478. tor_assert(dcell);
  2479. /* frees dcell */
  2480. cell = destroy_cell_to_packed_cell(dcell, chan->wide_circ_ids);
  2481. /* Send the DESTROY cell. It is very unlikely that this fails but just
  2482. * in case, get rid of the channel. */
  2483. if (channel_write_packed_cell(chan, cell) < 0) {
  2484. /* The cell has been freed. */
  2485. channel_mark_for_close(chan);
  2486. continue;
  2487. }
  2488. /* Update the cmux destroy counter */
  2489. circuitmux_notify_xmit_destroy(cmux);
  2490. cell = NULL;
  2491. ++n_flushed;
  2492. continue;
  2493. }
  2494. /* If it returns NULL, no cells left to send */
  2495. if (!circ) break;
  2496. if (circ->n_chan == chan) {
  2497. queue = &circ->n_chan_cells;
  2498. streams_blocked = circ->streams_blocked_on_n_chan;
  2499. } else {
  2500. or_circ = TO_OR_CIRCUIT(circ);
  2501. tor_assert(or_circ->p_chan == chan);
  2502. queue = &TO_OR_CIRCUIT(circ)->p_chan_cells;
  2503. streams_blocked = circ->streams_blocked_on_p_chan;
  2504. }
  2505. /* Circuitmux told us this was active, so it should have cells */
  2506. if (/*BUG(*/ queue->n == 0 /*)*/) {
  2507. log_warn(LD_BUG, "Found a supposedly active circuit with no cells "
  2508. "to send. Trying to recover.");
  2509. circuitmux_set_num_cells(cmux, circ, 0);
  2510. if (! circ->marked_for_close)
  2511. circuit_mark_for_close(circ, END_CIRC_REASON_INTERNAL);
  2512. continue;
  2513. }
  2514. tor_assert(queue->n > 0);
  2515. /*
  2516. * Get just one cell here; once we've sent it, that can change the circuit
  2517. * selection, so we have to loop around for another even if this circuit
  2518. * has more than one.
  2519. */
  2520. cell = cell_queue_pop(queue);
  2521. /* Calculate the exact time that this cell has spent in the queue. */
  2522. if (get_options()->CellStatistics ||
  2523. get_options()->TestingEnableCellStatsEvent) {
  2524. uint32_t timestamp_now = monotime_coarse_get_stamp();
  2525. uint32_t msec_waiting =
  2526. (uint32_t) monotime_coarse_stamp_units_to_approx_msec(
  2527. timestamp_now - cell->inserted_timestamp);
  2528. if (get_options()->CellStatistics && !CIRCUIT_IS_ORIGIN(circ)) {
  2529. or_circ = TO_OR_CIRCUIT(circ);
  2530. or_circ->total_cell_waiting_time += msec_waiting;
  2531. or_circ->processed_cells++;
  2532. }
  2533. if (get_options()->TestingEnableCellStatsEvent) {
  2534. uint8_t command = packed_cell_get_command(cell, chan->wide_circ_ids);
  2535. testing_cell_stats_entry_t *ent =
  2536. tor_malloc_zero(sizeof(testing_cell_stats_entry_t));
  2537. ent->command = command;
  2538. ent->waiting_time = msec_waiting / 10;
  2539. ent->removed = 1;
  2540. if (circ->n_chan == chan)
  2541. ent->exitward = 1;
  2542. if (!circ->testing_cell_stats)
  2543. circ->testing_cell_stats = smartlist_new();
  2544. smartlist_add(circ->testing_cell_stats, ent);
  2545. }
  2546. }
  2547. /* If we just flushed our queue and this circuit is used for a
  2548. * tunneled directory request, possibly advance its state. */
  2549. if (queue->n == 0 && chan->dirreq_id)
  2550. geoip_change_dirreq_state(chan->dirreq_id,
  2551. DIRREQ_TUNNELED,
  2552. DIRREQ_CIRC_QUEUE_FLUSHED);
  2553. /* Now send the cell. It is very unlikely that this fails but just in
  2554. * case, get rid of the channel. */
  2555. if (channel_write_packed_cell(chan, cell) < 0) {
  2556. /* The cell has been freed at this point. */
  2557. channel_mark_for_close(chan);
  2558. continue;
  2559. }
  2560. cell = NULL;
  2561. /*
  2562. * Don't packed_cell_free_unchecked(cell) here because the channel will
  2563. * do so when it gets out of the channel queue (probably already did, in
  2564. * which case that was an immediate double-free bug).
  2565. */
  2566. /* Update the counter */
  2567. ++n_flushed;
  2568. /*
  2569. * Now update the cmux; tell it we've just sent a cell, and how many
  2570. * we have left.
  2571. */
  2572. circuitmux_notify_xmit_cells(cmux, circ, 1);
  2573. circuitmux_set_num_cells(cmux, circ, queue->n);
  2574. if (queue->n == 0)
  2575. log_debug(LD_GENERAL, "Made a circuit inactive.");
  2576. /* Is the cell queue low enough to unblock all the streams that are waiting
  2577. * to write to this circuit? */
  2578. if (streams_blocked && queue->n <= CELL_QUEUE_LOWWATER_SIZE)
  2579. set_streams_blocked_on_circ(circ, chan, 0, 0); /* unblock streams */
  2580. /* If n_flushed < max still, loop around and pick another circuit */
  2581. }
  2582. /* Okay, we're done sending now */
  2583. return n_flushed;
  2584. }
  2585. /* Minimum value is the maximum circuit window size.
  2586. *
  2587. * SENDME cells makes it that we can control how many cells can be inflight on
  2588. * a circuit from end to end. This logic makes it that on any circuit cell
  2589. * queue, we have a maximum of cells possible.
  2590. *
  2591. * Because the Tor protocol allows for a client to exit at any hop in a
  2592. * circuit and a circuit can be of a maximum of 8 hops, so in theory the
  2593. * normal worst case will be the circuit window start value times the maximum
  2594. * number of hops (8). Having more cells then that means something is wrong.
  2595. *
  2596. * However, because padding cells aren't counted in the package window, we set
  2597. * the maximum size to a reasonably large size for which we expect that we'll
  2598. * never reach in theory. And if we ever do because of future changes, we'll
  2599. * be able to control it with a consensus parameter.
  2600. *
  2601. * XXX: Unfortunately, END cells aren't accounted for in the circuit window
  2602. * which means that for instance if a client opens 8001 streams, the 8001
  2603. * following END cells will queue up in the circuit which will get closed if
  2604. * the max limit is 8000. Which is sad because it is allowed by the Tor
  2605. * protocol. But, we need an upper bound on circuit queue in order to avoid
  2606. * DoS memory pressure so the default size is a middle ground between not
  2607. * having any limit and having a very restricted one. This is why we can also
  2608. * control it through a consensus parameter. */
  2609. #define RELAY_CIRC_CELL_QUEUE_SIZE_MIN CIRCWINDOW_START_MAX
  2610. /* We can't have a consensus parameter above this value. */
  2611. #define RELAY_CIRC_CELL_QUEUE_SIZE_MAX INT32_MAX
  2612. /* Default value is set to a large value so we can handle padding cells
  2613. * properly which aren't accounted for in the SENDME window. Default is 50000
  2614. * allowed cells in the queue resulting in ~25MB. */
  2615. #define RELAY_CIRC_CELL_QUEUE_SIZE_DEFAULT \
  2616. (50 * RELAY_CIRC_CELL_QUEUE_SIZE_MIN)
  2617. /* The maximum number of cell a circuit queue can contain. This is updated at
  2618. * every new consensus and controlled by a parameter. */
  2619. static int32_t max_circuit_cell_queue_size =
  2620. RELAY_CIRC_CELL_QUEUE_SIZE_DEFAULT;
  2621. /* Called when the consensus has changed. At this stage, the global consensus
  2622. * object has NOT been updated. It is called from
  2623. * notify_before_networkstatus_changes(). */
  2624. void
  2625. relay_consensus_has_changed(const networkstatus_t *ns)
  2626. {
  2627. tor_assert(ns);
  2628. /* Update the circuit max cell queue size from the consensus. */
  2629. max_circuit_cell_queue_size =
  2630. networkstatus_get_param(ns, "circ_max_cell_queue_size",
  2631. RELAY_CIRC_CELL_QUEUE_SIZE_DEFAULT,
  2632. RELAY_CIRC_CELL_QUEUE_SIZE_MIN,
  2633. RELAY_CIRC_CELL_QUEUE_SIZE_MAX);
  2634. }
  2635. /** Add <b>cell</b> to the queue of <b>circ</b> writing to <b>chan</b>
  2636. * transmitting in <b>direction</b>.
  2637. *
  2638. * The given <b>cell</b> is copied onto the circuit queue so the caller must
  2639. * cleanup the memory.
  2640. *
  2641. * This function is part of the fast path. */
  2642. void
  2643. append_cell_to_circuit_queue(circuit_t *circ, channel_t *chan,
  2644. cell_t *cell, cell_direction_t direction,
  2645. streamid_t fromstream)
  2646. {
  2647. or_circuit_t *orcirc = NULL;
  2648. cell_queue_t *queue;
  2649. int streams_blocked;
  2650. int exitward;
  2651. if (circ->marked_for_close)
  2652. return;
  2653. exitward = (direction == CELL_DIRECTION_OUT);
  2654. if (exitward) {
  2655. queue = &circ->n_chan_cells;
  2656. streams_blocked = circ->streams_blocked_on_n_chan;
  2657. } else {
  2658. orcirc = TO_OR_CIRCUIT(circ);
  2659. queue = &orcirc->p_chan_cells;
  2660. streams_blocked = circ->streams_blocked_on_p_chan;
  2661. }
  2662. if (PREDICT_UNLIKELY(queue->n >= max_circuit_cell_queue_size)) {
  2663. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  2664. "%s circuit has %d cells in its queue, maximum allowed is %d. "
  2665. "Closing circuit for safety reasons.",
  2666. (exitward) ? "Outbound" : "Inbound", queue->n,
  2667. max_circuit_cell_queue_size);
  2668. circuit_mark_for_close(circ, END_CIRC_REASON_RESOURCELIMIT);
  2669. stats_n_circ_max_cell_reached++;
  2670. return;
  2671. }
  2672. /* Very important that we copy to the circuit queue because all calls to
  2673. * this function use the stack for the cell memory. */
  2674. cell_queue_append_packed_copy(circ, queue, exitward, cell,
  2675. chan->wide_circ_ids, 1);
  2676. /* Check and run the OOM if needed. */
  2677. if (PREDICT_UNLIKELY(cell_queues_check_size())) {
  2678. /* We ran the OOM handler which might have closed this circuit. */
  2679. if (circ->marked_for_close)
  2680. return;
  2681. }
  2682. /* If we have too many cells on the circuit, we should stop reading from
  2683. * the edge streams for a while. */
  2684. if (!streams_blocked && queue->n >= CELL_QUEUE_HIGHWATER_SIZE)
  2685. set_streams_blocked_on_circ(circ, chan, 1, 0); /* block streams */
  2686. if (streams_blocked && fromstream) {
  2687. /* This edge connection is apparently not blocked; block it. */
  2688. set_streams_blocked_on_circ(circ, chan, 1, fromstream);
  2689. }
  2690. update_circuit_on_cmux(circ, direction);
  2691. if (queue->n == 1) {
  2692. /* This was the first cell added to the queue. We just made this
  2693. * circuit active. */
  2694. log_debug(LD_GENERAL, "Made a circuit active.");
  2695. }
  2696. /* New way: mark this as having waiting cells for the scheduler */
  2697. scheduler_channel_has_waiting_cells(chan);
  2698. }
  2699. /** Append an encoded value of <b>addr</b> to <b>payload_out</b>, which must
  2700. * have at least 18 bytes of free space. The encoding is, as specified in
  2701. * tor-spec.txt:
  2702. * RESOLVED_TYPE_IPV4 or RESOLVED_TYPE_IPV6 [1 byte]
  2703. * LENGTH [1 byte]
  2704. * ADDRESS [length bytes]
  2705. * Return the number of bytes added, or -1 on error */
  2706. int
  2707. append_address_to_payload(uint8_t *payload_out, const tor_addr_t *addr)
  2708. {
  2709. uint32_t a;
  2710. switch (tor_addr_family(addr)) {
  2711. case AF_INET:
  2712. payload_out[0] = RESOLVED_TYPE_IPV4;
  2713. payload_out[1] = 4;
  2714. a = tor_addr_to_ipv4n(addr);
  2715. memcpy(payload_out+2, &a, 4);
  2716. return 6;
  2717. case AF_INET6:
  2718. payload_out[0] = RESOLVED_TYPE_IPV6;
  2719. payload_out[1] = 16;
  2720. memcpy(payload_out+2, tor_addr_to_in6_addr8(addr), 16);
  2721. return 18;
  2722. case AF_UNSPEC:
  2723. default:
  2724. return -1;
  2725. }
  2726. }
  2727. /** Given <b>payload_len</b> bytes at <b>payload</b>, starting with an address
  2728. * encoded as by append_address_to_payload(), try to decode the address into
  2729. * *<b>addr_out</b>. Return the next byte in the payload after the address on
  2730. * success, or NULL on failure. */
  2731. const uint8_t *
  2732. decode_address_from_payload(tor_addr_t *addr_out, const uint8_t *payload,
  2733. int payload_len)
  2734. {
  2735. if (payload_len < 2)
  2736. return NULL;
  2737. if (payload_len < 2+payload[1])
  2738. return NULL;
  2739. switch (payload[0]) {
  2740. case RESOLVED_TYPE_IPV4:
  2741. if (payload[1] != 4)
  2742. return NULL;
  2743. tor_addr_from_ipv4n(addr_out, get_uint32(payload+2));
  2744. break;
  2745. case RESOLVED_TYPE_IPV6:
  2746. if (payload[1] != 16)
  2747. return NULL;
  2748. tor_addr_from_ipv6_bytes(addr_out, (char*)(payload+2));
  2749. break;
  2750. default:
  2751. tor_addr_make_unspec(addr_out);
  2752. break;
  2753. }
  2754. return payload + 2 + payload[1];
  2755. }
  2756. /** Remove all the cells queued on <b>circ</b> for <b>chan</b>. */
  2757. void
  2758. circuit_clear_cell_queue(circuit_t *circ, channel_t *chan)
  2759. {
  2760. cell_queue_t *queue;
  2761. cell_direction_t direction;
  2762. if (circ->n_chan == chan) {
  2763. queue = &circ->n_chan_cells;
  2764. direction = CELL_DIRECTION_OUT;
  2765. } else {
  2766. or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
  2767. tor_assert(orcirc->p_chan == chan);
  2768. queue = &orcirc->p_chan_cells;
  2769. direction = CELL_DIRECTION_IN;
  2770. }
  2771. /* Clear the queue */
  2772. cell_queue_clear(queue);
  2773. /* Update the cell counter in the cmux */
  2774. if (chan->cmux && circuitmux_is_circuit_attached(chan->cmux, circ))
  2775. update_circuit_on_cmux(circ, direction);
  2776. }
  2777. /** Return 1 if we shouldn't restart reading on this circuit, even if
  2778. * we get a SENDME. Else return 0.
  2779. */
  2780. static int
  2781. circuit_queue_streams_are_blocked(circuit_t *circ)
  2782. {
  2783. if (CIRCUIT_IS_ORIGIN(circ)) {
  2784. return circ->streams_blocked_on_n_chan;
  2785. } else {
  2786. return circ->streams_blocked_on_p_chan;
  2787. }
  2788. }