relay.c 109 KB

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