relay.c 117 KB

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