relay.c 109 KB

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