connection_edge.c 142 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870
  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-2016, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file connection_edge.c
  8. * \brief Handle edge streams.
  9. *
  10. * An edge_connection_t is a subtype of a connection_t, and represents two
  11. * critical concepts in Tor: a stream, and an edge connection. From the Tor
  12. * protocol's point of view, a stream is a bi-directional channel that is
  13. * multiplexed on a single circuit. Each stream on a circuit is identified
  14. * with a separate 16-bit stream ID, local to the (circuit,exit) pair.
  15. * Streams are created in response to client requests.
  16. *
  17. * An edge connection is one thing that can implement a stream: it is either a
  18. * TCP application socket that has arrived via (e.g.) a SOCKS request, or an
  19. * exit connection.
  20. *
  21. * Not every instance of edge_connection_t truly represents an edge connction,
  22. * however. (Sorry!) We also create edge_connection_t objects for streams that
  23. * we will not be handling with TCP. The types of these streams are:
  24. * <ul>
  25. * <li>DNS lookup streams, created on the client side in response to
  26. * a UDP DNS request received on a DNSPort, or a RESOLVE command
  27. * on a controller.
  28. * <li>DNS lookup streams, created on the exit side in response to
  29. * a RELAY_RESOLVE cell from a client.
  30. * <li>Tunneled directory streams, created on the directory cache side
  31. * in response to a RELAY_BEGINDIR cell. These streams attach directly
  32. * to a dir_connection_t object without ever using TCP.
  33. * </ul>
  34. *
  35. * This module handles general-purpose functionality having to do with
  36. * edge_connection_t. On the client side, it accepts various types of
  37. * application requests on SocksPorts, TransPorts, and NATDPorts, and
  38. * creates streams appropriately.
  39. *
  40. * This module is also responsible for implementing stream isolation:
  41. * ensuring that streams that should not be linkable to one another are
  42. * kept to different circuits.
  43. *
  44. * On the exit side, this module handles the various stream-creating
  45. * type of RELAY cells by launching appropriate outgoing connections,
  46. * DNS requests, or directory connection objects.
  47. *
  48. * And for all edge connections, this module is responsible for handling
  49. * incoming and outdoing data as it arrives or leaves in the relay.c
  50. * module. (Outgoing data will be packaged in
  51. * connection_edge_process_inbuf() as it calls
  52. * connection_edge_package_raw_inbuf(); incoming data from RELAY_DATA
  53. * cells is applied in connection_edge_process_relay_cell().)
  54. **/
  55. #define CONNECTION_EDGE_PRIVATE
  56. #include "or.h"
  57. #include "backtrace.h"
  58. #include "addressmap.h"
  59. #include "buffers.h"
  60. #include "channel.h"
  61. #include "circpathbias.h"
  62. #include "circuitlist.h"
  63. #include "circuituse.h"
  64. #include "config.h"
  65. #include "connection.h"
  66. #include "connection_edge.h"
  67. #include "connection_or.h"
  68. #include "control.h"
  69. #include "dns.h"
  70. #include "dnsserv.h"
  71. #include "directory.h"
  72. #include "dirserv.h"
  73. #include "hibernate.h"
  74. #include "hs_common.h"
  75. #include "main.h"
  76. #include "nodelist.h"
  77. #include "policies.h"
  78. #include "reasons.h"
  79. #include "relay.h"
  80. #include "rendclient.h"
  81. #include "rendcommon.h"
  82. #include "rendservice.h"
  83. #include "rephist.h"
  84. #include "router.h"
  85. #include "routerlist.h"
  86. #include "routerset.h"
  87. #include "circuitbuild.h"
  88. #ifdef HAVE_LINUX_TYPES_H
  89. #include <linux/types.h>
  90. #endif
  91. #ifdef HAVE_LINUX_NETFILTER_IPV4_H
  92. #include <linux/netfilter_ipv4.h>
  93. #define TRANS_NETFILTER
  94. #define TRANS_NETFILTER_IPV4
  95. #endif
  96. #ifdef HAVE_LINUX_IF_H
  97. #include <linux/if.h>
  98. #endif
  99. #ifdef HAVE_LINUX_NETFILTER_IPV6_IP6_TABLES_H
  100. #include <linux/netfilter_ipv6/ip6_tables.h>
  101. #if defined(IP6T_SO_ORIGINAL_DST)
  102. #define TRANS_NETFILTER
  103. #define TRANS_NETFILTER_IPV6
  104. #endif
  105. #endif
  106. #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
  107. #include <net/if.h>
  108. #include <net/pfvar.h>
  109. #define TRANS_PF
  110. #endif
  111. #ifdef IP_TRANSPARENT
  112. #define TRANS_TPROXY
  113. #endif
  114. #define SOCKS4_GRANTED 90
  115. #define SOCKS4_REJECT 91
  116. static int connection_ap_handshake_process_socks(entry_connection_t *conn);
  117. static int connection_ap_process_natd(entry_connection_t *conn);
  118. static int connection_exit_connect_dir(edge_connection_t *exitconn);
  119. static int consider_plaintext_ports(entry_connection_t *conn, uint16_t port);
  120. static int connection_ap_supports_optimistic_data(const entry_connection_t *);
  121. /** An AP stream has failed/finished. If it hasn't already sent back
  122. * a socks reply, send one now (based on endreason). Also set
  123. * has_sent_end to 1, and mark the conn.
  124. */
  125. MOCK_IMPL(void,
  126. connection_mark_unattached_ap_,(entry_connection_t *conn, int endreason,
  127. int line, const char *file))
  128. {
  129. connection_t *base_conn = ENTRY_TO_CONN(conn);
  130. edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
  131. tor_assert(base_conn->type == CONN_TYPE_AP);
  132. ENTRY_TO_EDGE_CONN(conn)->edge_has_sent_end = 1; /* no circ yet */
  133. /* If this is a rendezvous stream and it is failing without ever
  134. * being attached to a circuit, assume that an attempt to connect to
  135. * the destination hidden service has just ended.
  136. *
  137. * XXXX This condition doesn't limit to only streams failing
  138. * without ever being attached. That sloppiness should be harmless,
  139. * but we should fix it someday anyway. */
  140. if ((edge_conn->on_circuit != NULL || edge_conn->edge_has_sent_end) &&
  141. connection_edge_is_rendezvous_stream(edge_conn)) {
  142. rend_client_note_connection_attempt_ended(edge_conn->rend_data);
  143. }
  144. if (base_conn->marked_for_close) {
  145. /* This call will warn as appropriate. */
  146. connection_mark_for_close_(base_conn, line, file);
  147. return;
  148. }
  149. if (!conn->socks_request->has_finished) {
  150. if (endreason & END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED)
  151. log_warn(LD_BUG,
  152. "stream (marked at %s:%d) sending two socks replies?",
  153. file, line);
  154. if (SOCKS_COMMAND_IS_CONNECT(conn->socks_request->command))
  155. connection_ap_handshake_socks_reply(conn, NULL, 0, endreason);
  156. else if (SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command))
  157. connection_ap_handshake_socks_resolved(conn,
  158. RESOLVED_TYPE_ERROR_TRANSIENT,
  159. 0, NULL, -1, -1);
  160. else /* unknown or no handshake at all. send no response. */
  161. conn->socks_request->has_finished = 1;
  162. }
  163. connection_mark_and_flush_(base_conn, line, file);
  164. ENTRY_TO_EDGE_CONN(conn)->end_reason = endreason;
  165. }
  166. /** There was an EOF. Send an end and mark the connection for close.
  167. */
  168. int
  169. connection_edge_reached_eof(edge_connection_t *conn)
  170. {
  171. if (connection_get_inbuf_len(TO_CONN(conn)) &&
  172. connection_state_is_open(TO_CONN(conn))) {
  173. /* it still has stuff to process. don't let it die yet. */
  174. return 0;
  175. }
  176. log_info(LD_EDGE,"conn (fd "TOR_SOCKET_T_FORMAT") reached eof. Closing.",
  177. conn->base_.s);
  178. if (!conn->base_.marked_for_close) {
  179. /* only mark it if not already marked. it's possible to
  180. * get the 'end' right around when the client hangs up on us. */
  181. connection_edge_end(conn, END_STREAM_REASON_DONE);
  182. if (conn->base_.type == CONN_TYPE_AP) {
  183. /* eof, so don't send a socks reply back */
  184. if (EDGE_TO_ENTRY_CONN(conn)->socks_request)
  185. EDGE_TO_ENTRY_CONN(conn)->socks_request->has_finished = 1;
  186. }
  187. connection_mark_for_close(TO_CONN(conn));
  188. }
  189. return 0;
  190. }
  191. /** Handle new bytes on conn->inbuf based on state:
  192. * - If it's waiting for socks info, try to read another step of the
  193. * socks handshake out of conn->inbuf.
  194. * - If it's waiting for the original destination, fetch it.
  195. * - If it's open, then package more relay cells from the stream.
  196. * - Else, leave the bytes on inbuf alone for now.
  197. *
  198. * Mark and return -1 if there was an unexpected error with the conn,
  199. * else return 0.
  200. */
  201. int
  202. connection_edge_process_inbuf(edge_connection_t *conn, int package_partial)
  203. {
  204. tor_assert(conn);
  205. switch (conn->base_.state) {
  206. case AP_CONN_STATE_SOCKS_WAIT:
  207. if (connection_ap_handshake_process_socks(EDGE_TO_ENTRY_CONN(conn)) <0) {
  208. /* already marked */
  209. return -1;
  210. }
  211. return 0;
  212. case AP_CONN_STATE_NATD_WAIT:
  213. if (connection_ap_process_natd(EDGE_TO_ENTRY_CONN(conn)) < 0) {
  214. /* already marked */
  215. return -1;
  216. }
  217. return 0;
  218. case AP_CONN_STATE_OPEN:
  219. case EXIT_CONN_STATE_OPEN:
  220. if (connection_edge_package_raw_inbuf(conn, package_partial, NULL) < 0) {
  221. /* (We already sent an end cell if possible) */
  222. connection_mark_for_close(TO_CONN(conn));
  223. return -1;
  224. }
  225. return 0;
  226. case AP_CONN_STATE_CONNECT_WAIT:
  227. if (connection_ap_supports_optimistic_data(EDGE_TO_ENTRY_CONN(conn))) {
  228. log_info(LD_EDGE,
  229. "data from edge while in '%s' state. Sending it anyway. "
  230. "package_partial=%d, buflen=%ld",
  231. conn_state_to_string(conn->base_.type, conn->base_.state),
  232. package_partial,
  233. (long)connection_get_inbuf_len(TO_CONN(conn)));
  234. if (connection_edge_package_raw_inbuf(conn, package_partial, NULL)<0) {
  235. /* (We already sent an end cell if possible) */
  236. connection_mark_for_close(TO_CONN(conn));
  237. return -1;
  238. }
  239. return 0;
  240. }
  241. /* Fall through if the connection is on a circuit without optimistic
  242. * data support. */
  243. case EXIT_CONN_STATE_CONNECTING:
  244. case AP_CONN_STATE_RENDDESC_WAIT:
  245. case AP_CONN_STATE_CIRCUIT_WAIT:
  246. case AP_CONN_STATE_RESOLVE_WAIT:
  247. case AP_CONN_STATE_CONTROLLER_WAIT:
  248. log_info(LD_EDGE,
  249. "data from edge while in '%s' state. Leaving it on buffer.",
  250. conn_state_to_string(conn->base_.type, conn->base_.state));
  251. return 0;
  252. }
  253. log_warn(LD_BUG,"Got unexpected state %d. Closing.",conn->base_.state);
  254. tor_fragile_assert();
  255. connection_edge_end(conn, END_STREAM_REASON_INTERNAL);
  256. connection_mark_for_close(TO_CONN(conn));
  257. return -1;
  258. }
  259. /** This edge needs to be closed, because its circuit has closed.
  260. * Mark it for close and return 0.
  261. */
  262. int
  263. connection_edge_destroy(circid_t circ_id, edge_connection_t *conn)
  264. {
  265. if (!conn->base_.marked_for_close) {
  266. log_info(LD_EDGE, "CircID %u: At an edge. Marking connection for close.",
  267. (unsigned) circ_id);
  268. if (conn->base_.type == CONN_TYPE_AP) {
  269. entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
  270. connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_DESTROY);
  271. control_event_stream_bandwidth(conn);
  272. control_event_stream_status(entry_conn, STREAM_EVENT_CLOSED,
  273. END_STREAM_REASON_DESTROY);
  274. conn->end_reason |= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED;
  275. } else {
  276. /* closing the circuit, nothing to send an END to */
  277. conn->edge_has_sent_end = 1;
  278. conn->end_reason = END_STREAM_REASON_DESTROY;
  279. conn->end_reason |= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED;
  280. connection_mark_and_flush(TO_CONN(conn));
  281. }
  282. }
  283. conn->cpath_layer = NULL;
  284. conn->on_circuit = NULL;
  285. return 0;
  286. }
  287. /** Send a raw end cell to the stream with ID <b>stream_id</b> out over the
  288. * <b>circ</b> towards the hop identified with <b>cpath_layer</b>. If this
  289. * is not a client connection, set the relay end cell's reason for closing
  290. * as <b>reason</b> */
  291. static int
  292. relay_send_end_cell_from_edge(streamid_t stream_id, circuit_t *circ,
  293. uint8_t reason, crypt_path_t *cpath_layer)
  294. {
  295. char payload[1];
  296. if (CIRCUIT_PURPOSE_IS_CLIENT(circ->purpose)) {
  297. /* Never send the server an informative reason code; it doesn't need to
  298. * know why the client stream is failing. */
  299. reason = END_STREAM_REASON_MISC;
  300. }
  301. payload[0] = (char) reason;
  302. return relay_send_command_from_edge(stream_id, circ, RELAY_COMMAND_END,
  303. payload, 1, cpath_layer);
  304. }
  305. /** Send a relay end cell from stream <b>conn</b> down conn's circuit, and
  306. * remember that we've done so. If this is not a client connection, set the
  307. * relay end cell's reason for closing as <b>reason</b>.
  308. *
  309. * Return -1 if this function has already been called on this conn,
  310. * else return 0.
  311. */
  312. int
  313. connection_edge_end(edge_connection_t *conn, uint8_t reason)
  314. {
  315. char payload[RELAY_PAYLOAD_SIZE];
  316. size_t payload_len=1;
  317. circuit_t *circ;
  318. uint8_t control_reason = reason;
  319. if (conn->edge_has_sent_end) {
  320. log_warn(LD_BUG,"(Harmless.) Calling connection_edge_end (reason %d) "
  321. "on an already ended stream?", reason);
  322. tor_fragile_assert();
  323. return -1;
  324. }
  325. if (conn->base_.marked_for_close) {
  326. log_warn(LD_BUG,
  327. "called on conn that's already marked for close at %s:%d.",
  328. conn->base_.marked_for_close_file, conn->base_.marked_for_close);
  329. return 0;
  330. }
  331. circ = circuit_get_by_edge_conn(conn);
  332. if (circ && CIRCUIT_PURPOSE_IS_CLIENT(circ->purpose)) {
  333. /* If this is a client circuit, don't send the server an informative
  334. * reason code; it doesn't need to know why the client stream is
  335. * failing. */
  336. reason = END_STREAM_REASON_MISC;
  337. }
  338. payload[0] = (char)reason;
  339. if (reason == END_STREAM_REASON_EXITPOLICY &&
  340. !connection_edge_is_rendezvous_stream(conn)) {
  341. int addrlen;
  342. if (tor_addr_family(&conn->base_.addr) == AF_INET) {
  343. set_uint32(payload+1, tor_addr_to_ipv4n(&conn->base_.addr));
  344. addrlen = 4;
  345. } else {
  346. memcpy(payload+1, tor_addr_to_in6_addr8(&conn->base_.addr), 16);
  347. addrlen = 16;
  348. }
  349. set_uint32(payload+1+addrlen, htonl(dns_clip_ttl(conn->address_ttl)));
  350. payload_len += 4+addrlen;
  351. }
  352. if (circ && !circ->marked_for_close) {
  353. log_debug(LD_EDGE,"Sending end on conn (fd "TOR_SOCKET_T_FORMAT").",
  354. conn->base_.s);
  355. connection_edge_send_command(conn, RELAY_COMMAND_END,
  356. payload, payload_len);
  357. } else {
  358. log_debug(LD_EDGE,"No circ to send end on conn "
  359. "(fd "TOR_SOCKET_T_FORMAT").",
  360. conn->base_.s);
  361. }
  362. conn->edge_has_sent_end = 1;
  363. conn->end_reason = control_reason;
  364. return 0;
  365. }
  366. /** An error has just occurred on an operation on an edge connection
  367. * <b>conn</b>. Extract the errno; convert it to an end reason, and send an
  368. * appropriate relay end cell to the other end of the connection's circuit.
  369. **/
  370. int
  371. connection_edge_end_errno(edge_connection_t *conn)
  372. {
  373. uint8_t reason;
  374. tor_assert(conn);
  375. reason = errno_to_stream_end_reason(tor_socket_errno(conn->base_.s));
  376. return connection_edge_end(conn, reason);
  377. }
  378. /** We just wrote some data to <b>conn</b>; act appropriately.
  379. *
  380. * (That is, if it's open, consider sending a stream-level sendme cell if we
  381. * have just flushed enough.)
  382. */
  383. int
  384. connection_edge_flushed_some(edge_connection_t *conn)
  385. {
  386. switch (conn->base_.state) {
  387. case AP_CONN_STATE_OPEN:
  388. case EXIT_CONN_STATE_OPEN:
  389. connection_edge_consider_sending_sendme(conn);
  390. break;
  391. }
  392. return 0;
  393. }
  394. /** Connection <b>conn</b> has finished writing and has no bytes left on
  395. * its outbuf.
  396. *
  397. * If it's in state 'open', stop writing, consider responding with a
  398. * sendme, and return.
  399. * Otherwise, stop writing and return.
  400. *
  401. * If <b>conn</b> is broken, mark it for close and return -1, else
  402. * return 0.
  403. */
  404. int
  405. connection_edge_finished_flushing(edge_connection_t *conn)
  406. {
  407. tor_assert(conn);
  408. switch (conn->base_.state) {
  409. case AP_CONN_STATE_OPEN:
  410. case EXIT_CONN_STATE_OPEN:
  411. connection_edge_consider_sending_sendme(conn);
  412. return 0;
  413. case AP_CONN_STATE_SOCKS_WAIT:
  414. case AP_CONN_STATE_NATD_WAIT:
  415. case AP_CONN_STATE_RENDDESC_WAIT:
  416. case AP_CONN_STATE_CIRCUIT_WAIT:
  417. case AP_CONN_STATE_CONNECT_WAIT:
  418. case AP_CONN_STATE_CONTROLLER_WAIT:
  419. case AP_CONN_STATE_RESOLVE_WAIT:
  420. return 0;
  421. default:
  422. log_warn(LD_BUG, "Called in unexpected state %d.",conn->base_.state);
  423. tor_fragile_assert();
  424. return -1;
  425. }
  426. return 0;
  427. }
  428. /** Longest size for the relay payload of a RELAY_CONNECTED cell that we're
  429. * able to generate. */
  430. /* 4 zero bytes; 1 type byte; 16 byte IPv6 address; 4 byte TTL. */
  431. #define MAX_CONNECTED_CELL_PAYLOAD_LEN 25
  432. /** Set the buffer at <b>payload_out</b> -- which must have at least
  433. * MAX_CONNECTED_CELL_PAYLOAD_LEN bytes available -- to the body of a
  434. * RELAY_CONNECTED cell indicating that we have connected to <b>addr</b>, and
  435. * that the name resolution that led us to <b>addr</b> will be valid for
  436. * <b>ttl</b> seconds. Return -1 on error, or the number of bytes used on
  437. * success. */
  438. STATIC int
  439. connected_cell_format_payload(uint8_t *payload_out,
  440. const tor_addr_t *addr,
  441. uint32_t ttl)
  442. {
  443. const sa_family_t family = tor_addr_family(addr);
  444. int connected_payload_len;
  445. /* should be needless */
  446. memset(payload_out, 0, MAX_CONNECTED_CELL_PAYLOAD_LEN);
  447. if (family == AF_INET) {
  448. set_uint32(payload_out, tor_addr_to_ipv4n(addr));
  449. connected_payload_len = 4;
  450. } else if (family == AF_INET6) {
  451. set_uint32(payload_out, 0);
  452. set_uint8(payload_out + 4, 6);
  453. memcpy(payload_out + 5, tor_addr_to_in6_addr8(addr), 16);
  454. connected_payload_len = 21;
  455. } else {
  456. return -1;
  457. }
  458. set_uint32(payload_out + connected_payload_len, htonl(dns_clip_ttl(ttl)));
  459. connected_payload_len += 4;
  460. tor_assert(connected_payload_len <= MAX_CONNECTED_CELL_PAYLOAD_LEN);
  461. return connected_payload_len;
  462. }
  463. /** Connected handler for exit connections: start writing pending
  464. * data, deliver 'CONNECTED' relay cells as appropriate, and check
  465. * any pending data that may have been received. */
  466. int
  467. connection_edge_finished_connecting(edge_connection_t *edge_conn)
  468. {
  469. connection_t *conn;
  470. tor_assert(edge_conn);
  471. tor_assert(edge_conn->base_.type == CONN_TYPE_EXIT);
  472. conn = TO_CONN(edge_conn);
  473. tor_assert(conn->state == EXIT_CONN_STATE_CONNECTING);
  474. log_info(LD_EXIT,"Exit connection to %s:%u (%s) established.",
  475. escaped_safe_str(conn->address), conn->port,
  476. safe_str(fmt_and_decorate_addr(&conn->addr)));
  477. rep_hist_note_exit_stream_opened(conn->port);
  478. conn->state = EXIT_CONN_STATE_OPEN;
  479. connection_watch_events(conn, READ_EVENT); /* stop writing, keep reading */
  480. if (connection_get_outbuf_len(conn)) /* in case there are any queued relay
  481. * cells */
  482. connection_start_writing(conn);
  483. /* deliver a 'connected' relay cell back through the circuit. */
  484. if (connection_edge_is_rendezvous_stream(edge_conn)) {
  485. if (connection_edge_send_command(edge_conn,
  486. RELAY_COMMAND_CONNECTED, NULL, 0) < 0)
  487. return 0; /* circuit is closed, don't continue */
  488. } else {
  489. uint8_t connected_payload[MAX_CONNECTED_CELL_PAYLOAD_LEN];
  490. int connected_payload_len =
  491. connected_cell_format_payload(connected_payload, &conn->addr,
  492. edge_conn->address_ttl);
  493. if (connected_payload_len < 0)
  494. return -1;
  495. if (connection_edge_send_command(edge_conn,
  496. RELAY_COMMAND_CONNECTED,
  497. (char*)connected_payload, connected_payload_len) < 0)
  498. return 0; /* circuit is closed, don't continue */
  499. }
  500. tor_assert(edge_conn->package_window > 0);
  501. /* in case the server has written anything */
  502. return connection_edge_process_inbuf(edge_conn, 1);
  503. }
  504. /** A list of all the entry_connection_t * objects that are not marked
  505. * for close, and are in AP_CONN_STATE_CIRCUIT_WAIT.
  506. *
  507. * (Right now, we check in several places to make sure that this list is
  508. * correct. When it's incorrect, we'll fix it, and log a BUG message.)
  509. */
  510. static smartlist_t *pending_entry_connections = NULL;
  511. static int untried_pending_connections = 0;
  512. /** Common code to connection_(ap|exit)_about_to_close. */
  513. static void
  514. connection_edge_about_to_close(edge_connection_t *edge_conn)
  515. {
  516. if (!edge_conn->edge_has_sent_end) {
  517. connection_t *conn = TO_CONN(edge_conn);
  518. log_warn(LD_BUG, "(Harmless.) Edge connection (marked at %s:%d) "
  519. "hasn't sent end yet?",
  520. conn->marked_for_close_file, conn->marked_for_close);
  521. tor_fragile_assert();
  522. }
  523. }
  524. /** Called when we're about to finally unlink and free an AP (client)
  525. * connection: perform necessary accounting and cleanup */
  526. void
  527. connection_ap_about_to_close(entry_connection_t *entry_conn)
  528. {
  529. circuit_t *circ;
  530. edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(entry_conn);
  531. connection_t *conn = ENTRY_TO_CONN(entry_conn);
  532. connection_edge_about_to_close(edge_conn);
  533. if (entry_conn->socks_request->has_finished == 0) {
  534. /* since conn gets removed right after this function finishes,
  535. * there's no point trying to send back a reply at this point. */
  536. log_warn(LD_BUG,"Closing stream (marked at %s:%d) without sending"
  537. " back a socks reply.",
  538. conn->marked_for_close_file, conn->marked_for_close);
  539. }
  540. if (!edge_conn->end_reason) {
  541. log_warn(LD_BUG,"Closing stream (marked at %s:%d) without having"
  542. " set end_reason.",
  543. conn->marked_for_close_file, conn->marked_for_close);
  544. }
  545. if (entry_conn->dns_server_request) {
  546. log_warn(LD_BUG,"Closing stream (marked at %s:%d) without having"
  547. " replied to DNS request.",
  548. conn->marked_for_close_file, conn->marked_for_close);
  549. dnsserv_reject_request(entry_conn);
  550. }
  551. if (TO_CONN(edge_conn)->state == AP_CONN_STATE_CIRCUIT_WAIT) {
  552. smartlist_remove(pending_entry_connections, entry_conn);
  553. }
  554. #if 1
  555. /* Check to make sure that this isn't in pending_entry_connections if it
  556. * didn't actually belong there. */
  557. if (TO_CONN(edge_conn)->type == CONN_TYPE_AP) {
  558. connection_ap_warn_and_unmark_if_pending_circ(entry_conn,
  559. "about_to_close");
  560. }
  561. #endif
  562. control_event_stream_bandwidth(edge_conn);
  563. control_event_stream_status(entry_conn, STREAM_EVENT_CLOSED,
  564. edge_conn->end_reason);
  565. circ = circuit_get_by_edge_conn(edge_conn);
  566. if (circ)
  567. circuit_detach_stream(circ, edge_conn);
  568. }
  569. /** Called when we're about to finally unlink and free an exit
  570. * connection: perform necessary accounting and cleanup */
  571. void
  572. connection_exit_about_to_close(edge_connection_t *edge_conn)
  573. {
  574. circuit_t *circ;
  575. connection_t *conn = TO_CONN(edge_conn);
  576. connection_edge_about_to_close(edge_conn);
  577. circ = circuit_get_by_edge_conn(edge_conn);
  578. if (circ)
  579. circuit_detach_stream(circ, edge_conn);
  580. if (conn->state == EXIT_CONN_STATE_RESOLVING) {
  581. connection_dns_remove(edge_conn);
  582. }
  583. }
  584. /** Define a schedule for how long to wait between retrying
  585. * application connections. Rather than waiting a fixed amount of
  586. * time between each retry, we wait 10 seconds each for the first
  587. * two tries, and 15 seconds for each retry after
  588. * that. Hopefully this will improve the expected user experience. */
  589. static int
  590. compute_retry_timeout(entry_connection_t *conn)
  591. {
  592. int timeout = get_options()->CircuitStreamTimeout;
  593. if (timeout) /* if our config options override the default, use them */
  594. return timeout;
  595. if (conn->num_socks_retries < 2) /* try 0 and try 1 */
  596. return 10;
  597. return 15;
  598. }
  599. /** Find all general-purpose AP streams waiting for a response that sent their
  600. * begin/resolve cell too long ago. Detach from their current circuit, and
  601. * mark their current circuit as unsuitable for new streams. Then call
  602. * connection_ap_handshake_attach_circuit() to attach to a new circuit (if
  603. * available) or launch a new one.
  604. *
  605. * For rendezvous streams, simply give up after SocksTimeout seconds (with no
  606. * retry attempt).
  607. */
  608. void
  609. connection_ap_expire_beginning(void)
  610. {
  611. edge_connection_t *conn;
  612. entry_connection_t *entry_conn;
  613. circuit_t *circ;
  614. time_t now = time(NULL);
  615. const or_options_t *options = get_options();
  616. int severity;
  617. int cutoff;
  618. int seconds_idle, seconds_since_born;
  619. smartlist_t *conns = get_connection_array();
  620. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
  621. if (base_conn->type != CONN_TYPE_AP || base_conn->marked_for_close)
  622. continue;
  623. entry_conn = TO_ENTRY_CONN(base_conn);
  624. conn = ENTRY_TO_EDGE_CONN(entry_conn);
  625. /* if it's an internal linked connection, don't yell its status. */
  626. severity = (tor_addr_is_null(&base_conn->addr) && !base_conn->port)
  627. ? LOG_INFO : LOG_NOTICE;
  628. seconds_idle = (int)( now - base_conn->timestamp_lastread );
  629. seconds_since_born = (int)( now - base_conn->timestamp_created );
  630. if (base_conn->state == AP_CONN_STATE_OPEN)
  631. continue;
  632. /* We already consider SocksTimeout in
  633. * connection_ap_handshake_attach_circuit(), but we need to consider
  634. * it here too because controllers that put streams in controller_wait
  635. * state never ask Tor to attach the circuit. */
  636. if (AP_CONN_STATE_IS_UNATTACHED(base_conn->state)) {
  637. if (seconds_since_born >= options->SocksTimeout) {
  638. log_fn(severity, LD_APP,
  639. "Tried for %d seconds to get a connection to %s:%d. "
  640. "Giving up. (%s)",
  641. seconds_since_born,
  642. safe_str_client(entry_conn->socks_request->address),
  643. entry_conn->socks_request->port,
  644. conn_state_to_string(CONN_TYPE_AP, base_conn->state));
  645. connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TIMEOUT);
  646. }
  647. continue;
  648. }
  649. /* We're in state connect_wait or resolve_wait now -- waiting for a
  650. * reply to our relay cell. See if we want to retry/give up. */
  651. cutoff = compute_retry_timeout(entry_conn);
  652. if (seconds_idle < cutoff)
  653. continue;
  654. circ = circuit_get_by_edge_conn(conn);
  655. if (!circ) { /* it's vanished? */
  656. log_info(LD_APP,"Conn is waiting (address %s), but lost its circ.",
  657. safe_str_client(entry_conn->socks_request->address));
  658. connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TIMEOUT);
  659. continue;
  660. }
  661. if (circ->purpose == CIRCUIT_PURPOSE_C_REND_JOINED) {
  662. if (seconds_idle >= options->SocksTimeout) {
  663. log_fn(severity, LD_REND,
  664. "Rend stream is %d seconds late. Giving up on address"
  665. " '%s.onion'.",
  666. seconds_idle,
  667. safe_str_client(entry_conn->socks_request->address));
  668. /* Roll back path bias use state so that we probe the circuit
  669. * if nothing else succeeds on it */
  670. pathbias_mark_use_rollback(TO_ORIGIN_CIRCUIT(circ));
  671. connection_edge_end(conn, END_STREAM_REASON_TIMEOUT);
  672. connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TIMEOUT);
  673. }
  674. continue;
  675. }
  676. if (circ->purpose != CIRCUIT_PURPOSE_C_GENERAL &&
  677. circ->purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT &&
  678. circ->purpose != CIRCUIT_PURPOSE_PATH_BIAS_TESTING) {
  679. log_warn(LD_BUG, "circuit->purpose == CIRCUIT_PURPOSE_C_GENERAL failed. "
  680. "The purpose on the circuit was %s; it was in state %s, "
  681. "path_state %s.",
  682. circuit_purpose_to_string(circ->purpose),
  683. circuit_state_to_string(circ->state),
  684. CIRCUIT_IS_ORIGIN(circ) ?
  685. pathbias_state_to_string(TO_ORIGIN_CIRCUIT(circ)->path_state) :
  686. "none");
  687. }
  688. log_fn(cutoff < 15 ? LOG_INFO : severity, LD_APP,
  689. "We tried for %d seconds to connect to '%s' using exit %s."
  690. " Retrying on a new circuit.",
  691. seconds_idle,
  692. safe_str_client(entry_conn->socks_request->address),
  693. conn->cpath_layer ?
  694. extend_info_describe(conn->cpath_layer->extend_info):
  695. "*unnamed*");
  696. /* send an end down the circuit */
  697. connection_edge_end(conn, END_STREAM_REASON_TIMEOUT);
  698. /* un-mark it as ending, since we're going to reuse it */
  699. conn->edge_has_sent_end = 0;
  700. conn->end_reason = 0;
  701. /* make us not try this circuit again, but allow
  702. * current streams on it to survive if they can */
  703. mark_circuit_unusable_for_new_conns(TO_ORIGIN_CIRCUIT(circ));
  704. /* give our stream another 'cutoff' seconds to try */
  705. conn->base_.timestamp_lastread += cutoff;
  706. if (entry_conn->num_socks_retries < 250) /* avoid overflow */
  707. entry_conn->num_socks_retries++;
  708. /* move it back into 'pending' state, and try to attach. */
  709. if (connection_ap_detach_retriable(entry_conn, TO_ORIGIN_CIRCUIT(circ),
  710. END_STREAM_REASON_TIMEOUT)<0) {
  711. if (!base_conn->marked_for_close)
  712. connection_mark_unattached_ap(entry_conn,
  713. END_STREAM_REASON_CANT_ATTACH);
  714. }
  715. } SMARTLIST_FOREACH_END(base_conn);
  716. }
  717. /**
  718. * As connection_ap_attach_pending, but first scans the entire connection
  719. * array to see if any elements are missing.
  720. */
  721. void
  722. connection_ap_rescan_and_attach_pending(void)
  723. {
  724. entry_connection_t *entry_conn;
  725. smartlist_t *conns = get_connection_array();
  726. if (PREDICT_UNLIKELY(NULL == pending_entry_connections))
  727. pending_entry_connections = smartlist_new();
  728. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
  729. if (conn->marked_for_close ||
  730. conn->type != CONN_TYPE_AP ||
  731. conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
  732. continue;
  733. entry_conn = TO_ENTRY_CONN(conn);
  734. tor_assert(entry_conn);
  735. if (! smartlist_contains(pending_entry_connections, entry_conn)) {
  736. log_warn(LD_BUG, "Found a connection %p that was supposed to be "
  737. "in pending_entry_connections, but wasn't. No worries; "
  738. "adding it.",
  739. pending_entry_connections);
  740. untried_pending_connections = 1;
  741. connection_ap_mark_as_pending_circuit(entry_conn);
  742. }
  743. } SMARTLIST_FOREACH_END(conn);
  744. connection_ap_attach_pending(1);
  745. }
  746. #ifdef DEBUGGING_17659
  747. #define UNMARK() do { \
  748. entry_conn->marked_pending_circ_line = 0; \
  749. entry_conn->marked_pending_circ_file = 0; \
  750. } while (0)
  751. #else
  752. #define UNMARK() do { } while (0)
  753. #endif
  754. /** Tell any AP streams that are listed as waiting for a new circuit to try
  755. * again. If there is an available circuit for a stream, attach it. Otherwise,
  756. * launch a new circuit.
  757. *
  758. * If <b>retry</b> is false, only check the list if it contains at least one
  759. * streams that we have not yet tried to attach to a circuit.
  760. */
  761. void
  762. connection_ap_attach_pending(int retry)
  763. {
  764. if (PREDICT_UNLIKELY(!pending_entry_connections)) {
  765. return;
  766. }
  767. if (untried_pending_connections == 0 && !retry)
  768. return;
  769. /* Don't allow any modifications to list while we are iterating over
  770. * it. We'll put streams back on this list if we can't attach them
  771. * immediately. */
  772. smartlist_t *pending = pending_entry_connections;
  773. pending_entry_connections = smartlist_new();
  774. SMARTLIST_FOREACH_BEGIN(pending,
  775. entry_connection_t *, entry_conn) {
  776. connection_t *conn = ENTRY_TO_CONN(entry_conn);
  777. tor_assert(conn && entry_conn);
  778. if (conn->marked_for_close) {
  779. UNMARK();
  780. continue;
  781. }
  782. if (conn->magic != ENTRY_CONNECTION_MAGIC) {
  783. log_warn(LD_BUG, "%p has impossible magic value %u.",
  784. entry_conn, (unsigned)conn->magic);
  785. UNMARK();
  786. continue;
  787. }
  788. if (conn->state != AP_CONN_STATE_CIRCUIT_WAIT) {
  789. log_warn(LD_BUG, "%p is no longer in circuit_wait. Its current state "
  790. "is %s. Why is it on pending_entry_connections?",
  791. entry_conn,
  792. conn_state_to_string(conn->type, conn->state));
  793. UNMARK();
  794. continue;
  795. }
  796. /* Okay, we're through the sanity checks. Try to handle this stream. */
  797. if (connection_ap_handshake_attach_circuit(entry_conn) < 0) {
  798. if (!conn->marked_for_close)
  799. connection_mark_unattached_ap(entry_conn,
  800. END_STREAM_REASON_CANT_ATTACH);
  801. }
  802. if (! conn->marked_for_close &&
  803. conn->type == CONN_TYPE_AP &&
  804. conn->state == AP_CONN_STATE_CIRCUIT_WAIT) {
  805. /* Is it still waiting for a circuit? If so, we didn't attach it,
  806. * so it's still pending. Put it back on the list.
  807. */
  808. if (!smartlist_contains(pending_entry_connections, entry_conn)) {
  809. smartlist_add(pending_entry_connections, entry_conn);
  810. continue;
  811. }
  812. }
  813. /* If we got here, then we either closed the connection, or
  814. * we attached it. */
  815. UNMARK();
  816. } SMARTLIST_FOREACH_END(entry_conn);
  817. smartlist_free(pending);
  818. untried_pending_connections = 0;
  819. }
  820. /** Mark <b>entry_conn</b> as needing to get attached to a circuit.
  821. *
  822. * And <b>entry_conn</b> must be in AP_CONN_STATE_CIRCUIT_WAIT,
  823. * should not already be pending a circuit. The circuit will get
  824. * launched or the connection will get attached the next time we
  825. * call connection_ap_attach_pending().
  826. */
  827. void
  828. connection_ap_mark_as_pending_circuit_(entry_connection_t *entry_conn,
  829. const char *fname, int lineno)
  830. {
  831. connection_t *conn = ENTRY_TO_CONN(entry_conn);
  832. tor_assert(conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
  833. tor_assert(conn->magic == ENTRY_CONNECTION_MAGIC);
  834. if (conn->marked_for_close)
  835. return;
  836. if (PREDICT_UNLIKELY(NULL == pending_entry_connections))
  837. pending_entry_connections = smartlist_new();
  838. if (PREDICT_UNLIKELY(smartlist_contains(pending_entry_connections,
  839. entry_conn))) {
  840. log_warn(LD_BUG, "What?? pending_entry_connections already contains %p! "
  841. "(Called from %s:%d.)",
  842. entry_conn, fname, lineno);
  843. #ifdef DEBUGGING_17659
  844. const char *f2 = entry_conn->marked_pending_circ_file;
  845. log_warn(LD_BUG, "(Previously called from %s:%d.)\n",
  846. f2 ? f2 : "<NULL>",
  847. entry_conn->marked_pending_circ_line);
  848. #endif
  849. log_backtrace(LOG_WARN, LD_BUG, "To debug, this may help");
  850. return;
  851. }
  852. #ifdef DEBUGGING_17659
  853. entry_conn->marked_pending_circ_line = (uint16_t) lineno;
  854. entry_conn->marked_pending_circ_file = fname;
  855. #endif
  856. untried_pending_connections = 1;
  857. smartlist_add(pending_entry_connections, entry_conn);
  858. /* Work-around for bug 19969: we handle pending_entry_connections at
  859. * the end of run_main_loop_once(), but in many cases that function will
  860. * take a very long time, if ever, to finish its call to event_base_loop().
  861. *
  862. * So the fix is to tell it right now that it ought to finish its loop at
  863. * its next available opportunity.
  864. */
  865. tell_event_loop_to_finish();
  866. }
  867. /** Mark <b>entry_conn</b> as no longer waiting for a circuit. */
  868. void
  869. connection_ap_mark_as_non_pending_circuit(entry_connection_t *entry_conn)
  870. {
  871. if (PREDICT_UNLIKELY(NULL == pending_entry_connections))
  872. return;
  873. UNMARK();
  874. smartlist_remove(pending_entry_connections, entry_conn);
  875. }
  876. /* DOCDOC */
  877. void
  878. connection_ap_warn_and_unmark_if_pending_circ(entry_connection_t *entry_conn,
  879. const char *where)
  880. {
  881. if (pending_entry_connections &&
  882. smartlist_contains(pending_entry_connections, entry_conn)) {
  883. log_warn(LD_BUG, "What was %p doing in pending_entry_connections in %s?",
  884. entry_conn, where);
  885. connection_ap_mark_as_non_pending_circuit(entry_conn);
  886. }
  887. }
  888. /** Tell any AP streams that are waiting for a one-hop tunnel to
  889. * <b>failed_digest</b> that they are going to fail. */
  890. /* XXXX We should get rid of this function, and instead attach
  891. * one-hop streams to circ->p_streams so they get marked in
  892. * circuit_mark_for_close like normal p_streams. */
  893. void
  894. connection_ap_fail_onehop(const char *failed_digest,
  895. cpath_build_state_t *build_state)
  896. {
  897. entry_connection_t *entry_conn;
  898. char digest[DIGEST_LEN];
  899. smartlist_t *conns = get_connection_array();
  900. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
  901. if (conn->marked_for_close ||
  902. conn->type != CONN_TYPE_AP ||
  903. conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
  904. continue;
  905. entry_conn = TO_ENTRY_CONN(conn);
  906. if (!entry_conn->want_onehop)
  907. continue;
  908. if (hexdigest_to_digest(entry_conn->chosen_exit_name, digest) < 0 ||
  909. tor_memneq(digest, failed_digest, DIGEST_LEN))
  910. continue;
  911. if (tor_digest_is_zero(digest)) {
  912. /* we don't know the digest; have to compare addr:port */
  913. tor_addr_t addr;
  914. if (!build_state || !build_state->chosen_exit ||
  915. !entry_conn->socks_request) {
  916. continue;
  917. }
  918. if (tor_addr_parse(&addr, entry_conn->socks_request->address)<0 ||
  919. !tor_addr_eq(&build_state->chosen_exit->addr, &addr) ||
  920. build_state->chosen_exit->port != entry_conn->socks_request->port)
  921. continue;
  922. }
  923. log_info(LD_APP, "Closing one-hop stream to '%s/%s' because the OR conn "
  924. "just failed.", entry_conn->chosen_exit_name,
  925. entry_conn->socks_request->address);
  926. connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TIMEOUT);
  927. } SMARTLIST_FOREACH_END(conn);
  928. }
  929. /** A circuit failed to finish on its last hop <b>info</b>. If there
  930. * are any streams waiting with this exit node in mind, but they
  931. * don't absolutely require it, make them give up on it.
  932. */
  933. void
  934. circuit_discard_optional_exit_enclaves(extend_info_t *info)
  935. {
  936. entry_connection_t *entry_conn;
  937. const node_t *r1, *r2;
  938. smartlist_t *conns = get_connection_array();
  939. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
  940. if (conn->marked_for_close ||
  941. conn->type != CONN_TYPE_AP ||
  942. conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
  943. continue;
  944. entry_conn = TO_ENTRY_CONN(conn);
  945. if (!entry_conn->chosen_exit_optional &&
  946. !entry_conn->chosen_exit_retries)
  947. continue;
  948. r1 = node_get_by_nickname(entry_conn->chosen_exit_name, 0);
  949. r2 = node_get_by_id(info->identity_digest);
  950. if (!r1 || !r2 || r1 != r2)
  951. continue;
  952. tor_assert(entry_conn->socks_request);
  953. if (entry_conn->chosen_exit_optional) {
  954. log_info(LD_APP, "Giving up on enclave exit '%s' for destination %s.",
  955. safe_str_client(entry_conn->chosen_exit_name),
  956. escaped_safe_str_client(entry_conn->socks_request->address));
  957. entry_conn->chosen_exit_optional = 0;
  958. tor_free(entry_conn->chosen_exit_name); /* clears it */
  959. /* if this port is dangerous, warn or reject it now that we don't
  960. * think it'll be using an enclave. */
  961. consider_plaintext_ports(entry_conn, entry_conn->socks_request->port);
  962. }
  963. if (entry_conn->chosen_exit_retries) {
  964. if (--entry_conn->chosen_exit_retries == 0) { /* give up! */
  965. clear_trackexithost_mappings(entry_conn->chosen_exit_name);
  966. tor_free(entry_conn->chosen_exit_name); /* clears it */
  967. /* if this port is dangerous, warn or reject it now that we don't
  968. * think it'll be using an enclave. */
  969. consider_plaintext_ports(entry_conn, entry_conn->socks_request->port);
  970. }
  971. }
  972. } SMARTLIST_FOREACH_END(conn);
  973. }
  974. /** The AP connection <b>conn</b> has just failed while attaching or
  975. * sending a BEGIN or resolving on <b>circ</b>, but another circuit
  976. * might work. Detach the circuit, and either reattach it, launch a
  977. * new circuit, tell the controller, or give up as appropriate.
  978. *
  979. * Returns -1 on err, 1 on success, 0 on not-yet-sure.
  980. */
  981. int
  982. connection_ap_detach_retriable(entry_connection_t *conn,
  983. origin_circuit_t *circ,
  984. int reason)
  985. {
  986. control_event_stream_status(conn, STREAM_EVENT_FAILED_RETRIABLE, reason);
  987. ENTRY_TO_CONN(conn)->timestamp_lastread = time(NULL);
  988. /* Roll back path bias use state so that we probe the circuit
  989. * if nothing else succeeds on it */
  990. pathbias_mark_use_rollback(circ);
  991. if (conn->pending_optimistic_data) {
  992. buf_set_to_copy(&conn->sending_optimistic_data,
  993. conn->pending_optimistic_data);
  994. }
  995. if (!get_options()->LeaveStreamsUnattached || conn->use_begindir) {
  996. /* If we're attaching streams ourself, or if this connection is
  997. * a tunneled directory connection, then just attach it. */
  998. ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_CIRCUIT_WAIT;
  999. circuit_detach_stream(TO_CIRCUIT(circ),ENTRY_TO_EDGE_CONN(conn));
  1000. connection_ap_mark_as_pending_circuit(conn);
  1001. } else {
  1002. CONNECTION_AP_EXPECT_NONPENDING(conn);
  1003. ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_CONTROLLER_WAIT;
  1004. circuit_detach_stream(TO_CIRCUIT(circ),ENTRY_TO_EDGE_CONN(conn));
  1005. }
  1006. return 0;
  1007. }
  1008. /** Check if <b>conn</b> is using a dangerous port. Then warn and/or
  1009. * reject depending on our config options. */
  1010. static int
  1011. consider_plaintext_ports(entry_connection_t *conn, uint16_t port)
  1012. {
  1013. const or_options_t *options = get_options();
  1014. int reject = smartlist_contains_int_as_string(
  1015. options->RejectPlaintextPorts, port);
  1016. if (smartlist_contains_int_as_string(options->WarnPlaintextPorts, port)) {
  1017. log_warn(LD_APP, "Application request to port %d: this port is "
  1018. "commonly used for unencrypted protocols. Please make sure "
  1019. "you don't send anything you would mind the rest of the "
  1020. "Internet reading!%s", port, reject ? " Closing." : "");
  1021. control_event_client_status(LOG_WARN, "DANGEROUS_PORT PORT=%d RESULT=%s",
  1022. port, reject ? "REJECT" : "WARN");
  1023. }
  1024. if (reject) {
  1025. log_info(LD_APP, "Port %d listed in RejectPlaintextPorts. Closing.", port);
  1026. connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
  1027. return -1;
  1028. }
  1029. return 0;
  1030. }
  1031. /** How many times do we try connecting with an exit configured via
  1032. * TrackHostExits before concluding that it won't work any more and trying a
  1033. * different one? */
  1034. #define TRACKHOSTEXITS_RETRIES 5
  1035. /** Call connection_ap_handshake_rewrite_and_attach() unless a controller
  1036. * asked us to leave streams unattached. Return 0 in that case.
  1037. *
  1038. * See connection_ap_handshake_rewrite_and_attach()'s
  1039. * documentation for arguments and return value.
  1040. */
  1041. int
  1042. connection_ap_rewrite_and_attach_if_allowed(entry_connection_t *conn,
  1043. origin_circuit_t *circ,
  1044. crypt_path_t *cpath)
  1045. {
  1046. const or_options_t *options = get_options();
  1047. if (options->LeaveStreamsUnattached) {
  1048. CONNECTION_AP_EXPECT_NONPENDING(conn);
  1049. ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_CONTROLLER_WAIT;
  1050. return 0;
  1051. }
  1052. return connection_ap_handshake_rewrite_and_attach(conn, circ, cpath);
  1053. }
  1054. /* Try to perform any map-based rewriting of the target address in
  1055. * <b>conn</b>, filling in the fields of <b>out</b> as we go, and modifying
  1056. * conn->socks_request.address as appropriate.
  1057. */
  1058. STATIC void
  1059. connection_ap_handshake_rewrite(entry_connection_t *conn,
  1060. rewrite_result_t *out)
  1061. {
  1062. socks_request_t *socks = conn->socks_request;
  1063. const or_options_t *options = get_options();
  1064. tor_addr_t addr_tmp;
  1065. /* Initialize all the fields of 'out' to reasonable defaults */
  1066. out->automap = 0;
  1067. out->exit_source = ADDRMAPSRC_NONE;
  1068. out->map_expires = TIME_MAX;
  1069. out->end_reason = 0;
  1070. out->should_close = 0;
  1071. out->orig_address[0] = 0;
  1072. /* We convert all incoming addresses to lowercase. */
  1073. tor_strlower(socks->address);
  1074. /* Remember the original address. */
  1075. strlcpy(out->orig_address, socks->address, sizeof(out->orig_address));
  1076. log_debug(LD_APP,"Client asked for %s:%d",
  1077. safe_str_client(socks->address),
  1078. socks->port);
  1079. /* Check for whether this is a .exit address. By default, those are
  1080. * disallowed when they're coming straight from the client, but you're
  1081. * allowed to have them in MapAddress commands and so forth. */
  1082. if (!strcmpend(socks->address, ".exit") && !options->AllowDotExit) {
  1083. log_warn(LD_APP, "The \".exit\" notation is disabled in Tor due to "
  1084. "security risks. Set AllowDotExit in your torrc to enable "
  1085. "it (at your own risk).");
  1086. control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
  1087. escaped(socks->address));
  1088. out->end_reason = END_STREAM_REASON_TORPROTOCOL;
  1089. out->should_close = 1;
  1090. return;
  1091. }
  1092. /* Remember the original address so we can tell the user about what
  1093. * they actually said, not just what it turned into. */
  1094. /* XXX yes, this is the same as out->orig_address above. One is
  1095. * in the output, and one is in the connection. */
  1096. if (! conn->original_dest_address) {
  1097. /* Is the 'if' necessary here? XXXX */
  1098. conn->original_dest_address = tor_strdup(conn->socks_request->address);
  1099. }
  1100. /* First, apply MapAddress and MAPADDRESS mappings. We need to do
  1101. * these only for non-reverse lookups, since they don't exist for those.
  1102. * We also need to do this before we consider automapping, since we might
  1103. * e.g. resolve irc.oftc.net into irconionaddress.onion, at which point
  1104. * we'd need to automap it. */
  1105. if (socks->command != SOCKS_COMMAND_RESOLVE_PTR) {
  1106. const unsigned rewrite_flags = AMR_FLAG_USE_MAPADDRESS;
  1107. if (addressmap_rewrite(socks->address, sizeof(socks->address),
  1108. rewrite_flags, &out->map_expires, &out->exit_source)) {
  1109. control_event_stream_status(conn, STREAM_EVENT_REMAP,
  1110. REMAP_STREAM_SOURCE_CACHE);
  1111. }
  1112. }
  1113. /* Now see if we need to create or return an existing Hostname->IP
  1114. * automapping. Automapping happens when we're asked to resolve a
  1115. * hostname, and AutomapHostsOnResolve is set, and the hostname has a
  1116. * suffix listed in AutomapHostsSuffixes. It's a handy feature
  1117. * that lets you have Tor assign e.g. IPv6 addresses for .onion
  1118. * names, and return them safely from DNSPort.
  1119. */
  1120. if (socks->command == SOCKS_COMMAND_RESOLVE &&
  1121. tor_addr_parse(&addr_tmp, socks->address)<0 &&
  1122. options->AutomapHostsOnResolve) {
  1123. /* Check the suffix... */
  1124. out->automap = addressmap_address_should_automap(socks->address, options);
  1125. if (out->automap) {
  1126. /* If we get here, then we should apply an automapping for this. */
  1127. const char *new_addr;
  1128. /* We return an IPv4 address by default, or an IPv6 address if we
  1129. * are allowed to do so. */
  1130. int addr_type = RESOLVED_TYPE_IPV4;
  1131. if (conn->socks_request->socks_version != 4) {
  1132. if (!conn->entry_cfg.ipv4_traffic ||
  1133. (conn->entry_cfg.ipv6_traffic && conn->entry_cfg.prefer_ipv6) ||
  1134. conn->entry_cfg.prefer_ipv6_virtaddr)
  1135. addr_type = RESOLVED_TYPE_IPV6;
  1136. }
  1137. /* Okay, register the target address as automapped, and find the new
  1138. * address we're supposed to give as a resolve answer. (Return a cached
  1139. * value if we've looked up this address before.
  1140. */
  1141. new_addr = addressmap_register_virtual_address(
  1142. addr_type, tor_strdup(socks->address));
  1143. if (! new_addr) {
  1144. log_warn(LD_APP, "Unable to automap address %s",
  1145. escaped_safe_str(socks->address));
  1146. out->end_reason = END_STREAM_REASON_INTERNAL;
  1147. out->should_close = 1;
  1148. return;
  1149. }
  1150. log_info(LD_APP, "Automapping %s to %s",
  1151. escaped_safe_str_client(socks->address),
  1152. safe_str_client(new_addr));
  1153. strlcpy(socks->address, new_addr, sizeof(socks->address));
  1154. }
  1155. }
  1156. /* Now handle reverse lookups, if they're in the cache. This doesn't
  1157. * happen too often, since client-side DNS caching is off by default,
  1158. * and very deprecated. */
  1159. if (socks->command == SOCKS_COMMAND_RESOLVE_PTR) {
  1160. unsigned rewrite_flags = 0;
  1161. if (conn->entry_cfg.use_cached_ipv4_answers)
  1162. rewrite_flags |= AMR_FLAG_USE_IPV4_DNS;
  1163. if (conn->entry_cfg.use_cached_ipv6_answers)
  1164. rewrite_flags |= AMR_FLAG_USE_IPV6_DNS;
  1165. if (addressmap_rewrite_reverse(socks->address, sizeof(socks->address),
  1166. rewrite_flags, &out->map_expires)) {
  1167. char *result = tor_strdup(socks->address);
  1168. /* remember _what_ is supposed to have been resolved. */
  1169. tor_snprintf(socks->address, sizeof(socks->address), "REVERSE[%s]",
  1170. out->orig_address);
  1171. connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_HOSTNAME,
  1172. strlen(result), (uint8_t*)result,
  1173. -1,
  1174. out->map_expires);
  1175. tor_free(result);
  1176. out->end_reason = END_STREAM_REASON_DONE |
  1177. END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED;
  1178. out->should_close = 1;
  1179. return;
  1180. }
  1181. /* Hang on, did we find an answer saying that this is a reverse lookup for
  1182. * an internal address? If so, we should reject it if we're configured to
  1183. * do so. */
  1184. if (options->ClientDNSRejectInternalAddresses) {
  1185. /* Don't let people try to do a reverse lookup on 10.0.0.1. */
  1186. tor_addr_t addr;
  1187. int ok;
  1188. ok = tor_addr_parse_PTR_name(
  1189. &addr, socks->address, AF_UNSPEC, 1);
  1190. if (ok == 1 && tor_addr_is_internal(&addr, 0)) {
  1191. connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_ERROR,
  1192. 0, NULL, -1, TIME_MAX);
  1193. out->end_reason = END_STREAM_REASON_SOCKSPROTOCOL |
  1194. END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED;
  1195. out->should_close = 1;
  1196. return;
  1197. }
  1198. }
  1199. }
  1200. /* If we didn't automap it before, then this is still the address that
  1201. * came straight from the user, mapped according to any
  1202. * MapAddress/MAPADDRESS commands. Now apply other mappings,
  1203. * including previously registered Automap entries (IP back to
  1204. * hostname), TrackHostExits entries, and client-side DNS cache
  1205. * entries (if they're turned on).
  1206. */
  1207. if (socks->command != SOCKS_COMMAND_RESOLVE_PTR &&
  1208. !out->automap) {
  1209. unsigned rewrite_flags = AMR_FLAG_USE_AUTOMAP | AMR_FLAG_USE_TRACKEXIT;
  1210. addressmap_entry_source_t exit_source2;
  1211. if (conn->entry_cfg.use_cached_ipv4_answers)
  1212. rewrite_flags |= AMR_FLAG_USE_IPV4_DNS;
  1213. if (conn->entry_cfg.use_cached_ipv6_answers)
  1214. rewrite_flags |= AMR_FLAG_USE_IPV6_DNS;
  1215. if (addressmap_rewrite(socks->address, sizeof(socks->address),
  1216. rewrite_flags, &out->map_expires, &exit_source2)) {
  1217. control_event_stream_status(conn, STREAM_EVENT_REMAP,
  1218. REMAP_STREAM_SOURCE_CACHE);
  1219. }
  1220. if (out->exit_source == ADDRMAPSRC_NONE) {
  1221. /* If it wasn't a .exit before, maybe it turned into a .exit. Remember
  1222. * the original source of a .exit. */
  1223. out->exit_source = exit_source2;
  1224. }
  1225. }
  1226. /* Check to see whether we're about to use an address in the virtual
  1227. * range without actually having gotten it from an Automap. */
  1228. if (!out->automap && address_is_in_virtual_range(socks->address)) {
  1229. /* This address was probably handed out by
  1230. * client_dns_get_unmapped_address, but the mapping was discarded for some
  1231. * reason. Or the user typed in a virtual address range manually. We
  1232. * *don't* want to send the address through Tor; that's likely to fail,
  1233. * and may leak information.
  1234. */
  1235. log_warn(LD_APP,"Missing mapping for virtual address '%s'. Refusing.",
  1236. safe_str_client(socks->address));
  1237. out->end_reason = END_STREAM_REASON_INTERNAL;
  1238. out->should_close = 1;
  1239. return;
  1240. }
  1241. }
  1242. /** Connection <b>conn</b> just finished its socks handshake, or the
  1243. * controller asked us to take care of it. If <b>circ</b> is defined,
  1244. * then that's where we'll want to attach it. Otherwise we have to
  1245. * figure it out ourselves.
  1246. *
  1247. * First, parse whether it's a .exit address, remap it, and so on. Then
  1248. * if it's for a general circuit, try to attach it to a circuit (or launch
  1249. * one as needed), else if it's for a rendezvous circuit, fetch a
  1250. * rendezvous descriptor first (or attach/launch a circuit if the
  1251. * rendezvous descriptor is already here and fresh enough).
  1252. *
  1253. * The stream will exit from the hop
  1254. * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
  1255. * <b>cpath</b> is NULL.
  1256. */
  1257. int
  1258. connection_ap_handshake_rewrite_and_attach(entry_connection_t *conn,
  1259. origin_circuit_t *circ,
  1260. crypt_path_t *cpath)
  1261. {
  1262. socks_request_t *socks = conn->socks_request;
  1263. const or_options_t *options = get_options();
  1264. connection_t *base_conn = ENTRY_TO_CONN(conn);
  1265. time_t now = time(NULL);
  1266. rewrite_result_t rr;
  1267. /* First we'll do the rewrite part. Let's see if we get a reasonable
  1268. * answer.
  1269. */
  1270. memset(&rr, 0, sizeof(rr));
  1271. connection_ap_handshake_rewrite(conn,&rr);
  1272. if (rr.should_close) {
  1273. /* connection_ap_handshake_rewrite told us to close the connection:
  1274. * either because it sent back an answer, or because it sent back an
  1275. * error */
  1276. connection_mark_unattached_ap(conn, rr.end_reason);
  1277. if (END_STREAM_REASON_DONE == (rr.end_reason & END_STREAM_REASON_MASK))
  1278. return 0;
  1279. else
  1280. return -1;
  1281. }
  1282. const time_t map_expires = rr.map_expires;
  1283. const int automap = rr.automap;
  1284. const addressmap_entry_source_t exit_source = rr.exit_source;
  1285. /* Now, we parse the address to see if it's an .onion or .exit or
  1286. * other special address.
  1287. */
  1288. const hostname_type_t addresstype = parse_extended_hostname(socks->address);
  1289. /* Now see whether the hostname is bogus. This could happen because of an
  1290. * onion hostname whose format we don't recognize. */
  1291. if (addresstype == BAD_HOSTNAME) {
  1292. control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
  1293. escaped(socks->address));
  1294. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1295. return -1;
  1296. }
  1297. /* If this is a .exit hostname, strip off the .name.exit part, and
  1298. * see whether we're willing to connect there, and and otherwise handle the
  1299. * .exit address.
  1300. *
  1301. * We'll set chosen_exit_name and/or close the connection as appropriate.
  1302. */
  1303. if (addresstype == EXIT_HOSTNAME) {
  1304. /* If StrictNodes is not set, then .exit overrides ExcludeNodes but
  1305. * not ExcludeExitNodes. */
  1306. routerset_t *excludeset = options->StrictNodes ?
  1307. options->ExcludeExitNodesUnion_ : options->ExcludeExitNodes;
  1308. const node_t *node = NULL;
  1309. /* If this .exit was added by an AUTOMAP, then it came straight from
  1310. * a user. Make sure that options->AllowDotExit permits that! */
  1311. if (exit_source == ADDRMAPSRC_AUTOMAP && !options->AllowDotExit) {
  1312. /* Whoops; this one is stale. It must have gotten added earlier,
  1313. * when AllowDotExit was on. */
  1314. log_warn(LD_APP,"Stale automapped address for '%s.exit', with "
  1315. "AllowDotExit disabled. Refusing.",
  1316. safe_str_client(socks->address));
  1317. control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
  1318. escaped(socks->address));
  1319. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1320. return -1;
  1321. }
  1322. /* Double-check to make sure there are no .exits coming from
  1323. * impossible/weird sources. */
  1324. if (exit_source == ADDRMAPSRC_DNS ||
  1325. (exit_source == ADDRMAPSRC_NONE && !options->AllowDotExit)) {
  1326. /* It shouldn't be possible to get a .exit address from any of these
  1327. * sources. */
  1328. log_warn(LD_BUG,"Address '%s.exit', with impossible source for the "
  1329. ".exit part. Refusing.",
  1330. safe_str_client(socks->address));
  1331. control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
  1332. escaped(socks->address));
  1333. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1334. return -1;
  1335. }
  1336. tor_assert(!automap);
  1337. /* Now, find the character before the .(name) part.
  1338. * (The ".exit" part got stripped off by "parse_extended_hostname").
  1339. *
  1340. * We're going to put the exit name into conn->chosen_exit_name, and
  1341. * look up a node correspondingly. */
  1342. char *s = strrchr(socks->address,'.');
  1343. if (s) {
  1344. /* The address was of the form "(stuff).(name).exit */
  1345. if (s[1] != '\0') {
  1346. /* Looks like a real .exit one. */
  1347. conn->chosen_exit_name = tor_strdup(s+1);
  1348. node = node_get_by_nickname(conn->chosen_exit_name, 1);
  1349. if (exit_source == ADDRMAPSRC_TRACKEXIT) {
  1350. /* We 5 tries before it expires the addressmap */
  1351. conn->chosen_exit_retries = TRACKHOSTEXITS_RETRIES;
  1352. }
  1353. *s = 0;
  1354. } else {
  1355. /* Oops, the address was (stuff)..exit. That's not okay. */
  1356. log_warn(LD_APP,"Malformed exit address '%s.exit'. Refusing.",
  1357. safe_str_client(socks->address));
  1358. control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
  1359. escaped(socks->address));
  1360. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1361. return -1;
  1362. }
  1363. } else {
  1364. /* It looks like they just asked for "foo.exit". That's a special
  1365. * form that means (foo's address).foo.exit. */
  1366. conn->chosen_exit_name = tor_strdup(socks->address);
  1367. node = node_get_by_nickname(conn->chosen_exit_name, 1);
  1368. if (node) {
  1369. *socks->address = 0;
  1370. node_get_address_string(node, socks->address, sizeof(socks->address));
  1371. }
  1372. }
  1373. /* Now make sure that the chosen exit exists... */
  1374. if (!node) {
  1375. log_warn(LD_APP,
  1376. "Unrecognized relay in exit address '%s.exit'. Refusing.",
  1377. safe_str_client(socks->address));
  1378. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1379. return -1;
  1380. }
  1381. /* ...and make sure that it isn't excluded. */
  1382. if (routerset_contains_node(excludeset, node)) {
  1383. log_warn(LD_APP,
  1384. "Excluded relay in exit address '%s.exit'. Refusing.",
  1385. safe_str_client(socks->address));
  1386. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1387. return -1;
  1388. }
  1389. /* XXXX-1090 Should we also allow foo.bar.exit if ExitNodes is set and
  1390. Bar is not listed in it? I say yes, but our revised manpage branch
  1391. implies no. */
  1392. }
  1393. /* Now, we handle everything that isn't a .onion address. */
  1394. if (addresstype != ONION_HOSTNAME) {
  1395. /* Not a hidden-service request. It's either a hostname or an IP,
  1396. * possibly with a .exit that we stripped off. We're going to check
  1397. * if we're allowed to connect/resolve there, and then launch the
  1398. * appropriate request. */
  1399. /* Check for funny characters in the address. */
  1400. if (address_is_invalid_destination(socks->address, 1)) {
  1401. control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
  1402. escaped(socks->address));
  1403. log_warn(LD_APP,
  1404. "Destination '%s' seems to be an invalid hostname. Failing.",
  1405. safe_str_client(socks->address));
  1406. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1407. return -1;
  1408. }
  1409. #ifdef ENABLE_TOR2WEB_MODE
  1410. /* If we're running in Tor2webMode, we don't allow anything BUT .onion
  1411. * addresses. */
  1412. if (options->Tor2webMode) {
  1413. log_warn(LD_APP, "Refusing to connect to non-hidden-service hostname "
  1414. "or IP address %s because tor2web mode is enabled.",
  1415. safe_str_client(socks->address));
  1416. connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
  1417. return -1;
  1418. }
  1419. #endif
  1420. /* socks->address is a non-onion hostname or IP address.
  1421. * If we can't do any non-onion requests, refuse the connection.
  1422. * If we have a hostname but can't do DNS, refuse the connection.
  1423. * If we have an IP address, but we can't use that address family,
  1424. * refuse the connection.
  1425. *
  1426. * If we can do DNS requests, and we can use at least one address family,
  1427. * then we have to resolve the address first. Then we'll know if it
  1428. * resolves to a usable address family. */
  1429. /* First, check if all non-onion traffic is disabled */
  1430. if (!conn->entry_cfg.dns_request && !conn->entry_cfg.ipv4_traffic
  1431. && !conn->entry_cfg.ipv6_traffic) {
  1432. log_warn(LD_APP, "Refusing to connect to non-hidden-service hostname "
  1433. "or IP address %s because Port has OnionTrafficOnly set (or "
  1434. "NoDNSRequest, NoIPv4Traffic, and NoIPv6Traffic).",
  1435. safe_str_client(socks->address));
  1436. connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
  1437. return -1;
  1438. }
  1439. /* Then check if we have a hostname or IP address, and whether DNS or
  1440. * the IP address family are permitted. Reject if not. */
  1441. tor_addr_t dummy_addr;
  1442. int socks_family = tor_addr_parse(&dummy_addr, socks->address);
  1443. /* family will be -1 for a non-onion hostname that's not an IP */
  1444. if (socks_family == -1) {
  1445. if (!conn->entry_cfg.dns_request) {
  1446. log_warn(LD_APP, "Refusing to connect to hostname %s "
  1447. "because Port has NoDNSRequest set.",
  1448. safe_str_client(socks->address));
  1449. connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
  1450. return -1;
  1451. }
  1452. } else if (socks_family == AF_INET) {
  1453. if (!conn->entry_cfg.ipv4_traffic) {
  1454. log_warn(LD_APP, "Refusing to connect to IPv4 address %s because "
  1455. "Port has NoIPv4Traffic set.",
  1456. safe_str_client(socks->address));
  1457. connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
  1458. return -1;
  1459. }
  1460. } else if (socks_family == AF_INET6) {
  1461. if (!conn->entry_cfg.ipv6_traffic) {
  1462. log_warn(LD_APP, "Refusing to connect to IPv6 address %s because "
  1463. "Port has NoIPv6Traffic set.",
  1464. safe_str_client(socks->address));
  1465. connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
  1466. return -1;
  1467. }
  1468. } else {
  1469. tor_assert_nonfatal_unreached_once();
  1470. }
  1471. /* See if this is a hostname lookup that we can answer immediately.
  1472. * (For example, an attempt to look up the IP address for an IP address.)
  1473. */
  1474. if (socks->command == SOCKS_COMMAND_RESOLVE) {
  1475. tor_addr_t answer;
  1476. /* Reply to resolves immediately if we can. */
  1477. if (tor_addr_parse(&answer, socks->address) >= 0) {/* is it an IP? */
  1478. /* remember _what_ is supposed to have been resolved. */
  1479. strlcpy(socks->address, rr.orig_address, sizeof(socks->address));
  1480. connection_ap_handshake_socks_resolved_addr(conn, &answer, -1,
  1481. map_expires);
  1482. connection_mark_unattached_ap(conn,
  1483. END_STREAM_REASON_DONE |
  1484. END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
  1485. return 0;
  1486. }
  1487. tor_assert(!automap);
  1488. rep_hist_note_used_resolve(now); /* help predict this next time */
  1489. }
  1490. /* Now see if this is a connect request that we can reject immediately */
  1491. if (socks->command == SOCKS_COMMAND_CONNECT) {
  1492. /* Special handling for attempts to connect */
  1493. tor_assert(!automap);
  1494. /* Don't allow connections to port 0. */
  1495. if (socks->port == 0) {
  1496. log_notice(LD_APP,"Application asked to connect to port 0. Refusing.");
  1497. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1498. return -1;
  1499. }
  1500. /* You can't make connections to internal addresses, by default.
  1501. * Exceptions are begindir requests (where the address is meaningless,
  1502. * or cases where you've hand-configured a particular exit, thereby
  1503. * making the local address meaningful. */
  1504. if (options->ClientRejectInternalAddresses &&
  1505. !conn->use_begindir && !conn->chosen_exit_name && !circ) {
  1506. /* If we reach this point then we don't want to allow internal
  1507. * addresses. Check if we got one. */
  1508. tor_addr_t addr;
  1509. if (tor_addr_hostname_is_local(socks->address) ||
  1510. (tor_addr_parse(&addr, socks->address) >= 0 &&
  1511. tor_addr_is_internal(&addr, 0))) {
  1512. /* If this is an explicit private address with no chosen exit node,
  1513. * then we really don't want to try to connect to it. That's
  1514. * probably an error. */
  1515. if (conn->is_transparent_ap) {
  1516. #define WARN_INTRVL_LOOP 300
  1517. static ratelim_t loop_warn_limit = RATELIM_INIT(WARN_INTRVL_LOOP);
  1518. char *m;
  1519. if ((m = rate_limit_log(&loop_warn_limit, approx_time()))) {
  1520. log_warn(LD_NET,
  1521. "Rejecting request for anonymous connection to private "
  1522. "address %s on a TransPort or NATDPort. Possible loop "
  1523. "in your NAT rules?%s", safe_str_client(socks->address),
  1524. m);
  1525. tor_free(m);
  1526. }
  1527. } else {
  1528. #define WARN_INTRVL_PRIV 300
  1529. static ratelim_t priv_warn_limit = RATELIM_INIT(WARN_INTRVL_PRIV);
  1530. char *m;
  1531. if ((m = rate_limit_log(&priv_warn_limit, approx_time()))) {
  1532. log_warn(LD_NET,
  1533. "Rejecting SOCKS request for anonymous connection to "
  1534. "private address %s.%s",
  1535. safe_str_client(socks->address),m);
  1536. tor_free(m);
  1537. }
  1538. }
  1539. connection_mark_unattached_ap(conn, END_STREAM_REASON_PRIVATE_ADDR);
  1540. return -1;
  1541. }
  1542. } /* end "if we should check for internal addresses" */
  1543. /* Okay. We're still doing a CONNECT, and it wasn't a private
  1544. * address. Here we do special handling for literal IP addresses,
  1545. * to see if we should reject this preemptively, and to set up
  1546. * fields in conn->entry_cfg to tell the exit what AF we want. */
  1547. {
  1548. tor_addr_t addr;
  1549. /* XXX Duplicate call to tor_addr_parse. */
  1550. if (tor_addr_parse(&addr, socks->address) >= 0) {
  1551. /* If we reach this point, it's an IPv4 or an IPv6 address. */
  1552. sa_family_t family = tor_addr_family(&addr);
  1553. if ((family == AF_INET && ! conn->entry_cfg.ipv4_traffic) ||
  1554. (family == AF_INET6 && ! conn->entry_cfg.ipv6_traffic)) {
  1555. /* You can't do an IPv4 address on a v6-only socks listener,
  1556. * or vice versa. */
  1557. log_warn(LD_NET, "Rejecting SOCKS request for an IP address "
  1558. "family that this listener does not support.");
  1559. connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
  1560. return -1;
  1561. } else if (family == AF_INET6 && socks->socks_version == 4) {
  1562. /* You can't make a socks4 request to an IPv6 address. Socks4
  1563. * doesn't support that. */
  1564. log_warn(LD_NET, "Rejecting SOCKS4 request for an IPv6 address.");
  1565. connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
  1566. return -1;
  1567. } else if (socks->socks_version == 4 &&
  1568. !conn->entry_cfg.ipv4_traffic) {
  1569. /* You can't do any kind of Socks4 request when IPv4 is forbidden.
  1570. *
  1571. * XXX raise this check outside the enclosing block? */
  1572. log_warn(LD_NET, "Rejecting SOCKS4 request on a listener with "
  1573. "no IPv4 traffic supported.");
  1574. connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
  1575. return -1;
  1576. } else if (family == AF_INET6) {
  1577. /* Tell the exit: we won't accept any ipv4 connection to an IPv6
  1578. * address. */
  1579. conn->entry_cfg.ipv4_traffic = 0;
  1580. } else if (family == AF_INET) {
  1581. /* Tell the exit: we won't accept any ipv6 connection to an IPv4
  1582. * address. */
  1583. conn->entry_cfg.ipv6_traffic = 0;
  1584. }
  1585. }
  1586. }
  1587. /* we never allow IPv6 answers on socks4. (TODO: Is this smart?) */
  1588. if (socks->socks_version == 4)
  1589. conn->entry_cfg.ipv6_traffic = 0;
  1590. /* Still handling CONNECT. Now, check for exit enclaves. (Which we
  1591. * don't do on BEGINDIR, or when there is a chosen exit.)
  1592. *
  1593. * TODO: Should we remove this? Exit enclaves are nutty and don't
  1594. * work very well
  1595. */
  1596. if (!conn->use_begindir && !conn->chosen_exit_name && !circ) {
  1597. /* see if we can find a suitable enclave exit */
  1598. const node_t *r =
  1599. router_find_exact_exit_enclave(socks->address, socks->port);
  1600. if (r) {
  1601. log_info(LD_APP,
  1602. "Redirecting address %s to exit at enclave router %s",
  1603. safe_str_client(socks->address), node_describe(r));
  1604. /* use the hex digest, not nickname, in case there are two
  1605. routers with this nickname */
  1606. conn->chosen_exit_name =
  1607. tor_strdup(hex_str(r->identity, DIGEST_LEN));
  1608. conn->chosen_exit_optional = 1;
  1609. }
  1610. }
  1611. /* Still handling CONNECT: warn or reject if it's using a dangerous
  1612. * port. */
  1613. if (!conn->use_begindir && !conn->chosen_exit_name && !circ)
  1614. if (consider_plaintext_ports(conn, socks->port) < 0)
  1615. return -1;
  1616. /* Remember the port so that we will predict that more requests
  1617. there will happen in the future. */
  1618. if (!conn->use_begindir) {
  1619. /* help predict this next time */
  1620. rep_hist_note_used_port(now, socks->port);
  1621. }
  1622. } else if (socks->command == SOCKS_COMMAND_RESOLVE_PTR) {
  1623. rep_hist_note_used_resolve(now); /* help predict this next time */
  1624. /* no extra processing needed */
  1625. } else {
  1626. /* We should only be doing CONNECT or RESOLVE! */
  1627. tor_fragile_assert();
  1628. }
  1629. /* Okay. At this point we've set chosen_exit_name if needed, rewritten the
  1630. * address, and decided not to reject it for any number of reasons. Now
  1631. * mark the connection as waiting for a circuit, and try to attach it!
  1632. */
  1633. base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  1634. /* If we were given a circuit to attach to, try to attach. Otherwise,
  1635. * try to find a good one and attach to that. */
  1636. int rv;
  1637. if (circ) {
  1638. rv = connection_ap_handshake_attach_chosen_circuit(conn, circ, cpath);
  1639. } else {
  1640. /* We'll try to attach it at the next event loop, or whenever
  1641. * we call connection_ap_attach_pending() */
  1642. connection_ap_mark_as_pending_circuit(conn);
  1643. rv = 0;
  1644. }
  1645. /* If the above function returned 0 then we're waiting for a circuit.
  1646. * if it returned 1, we're attached. Both are okay. But if it returned
  1647. * -1, there was an error, so make sure the connection is marked, and
  1648. * return -1. */
  1649. if (rv < 0) {
  1650. if (!base_conn->marked_for_close)
  1651. connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
  1652. return -1;
  1653. }
  1654. return 0;
  1655. } else {
  1656. /* If we get here, it's a request for a .onion address! */
  1657. tor_assert(!automap);
  1658. /* If .onion address requests are disabled, refuse the request */
  1659. if (!conn->entry_cfg.onion_traffic) {
  1660. log_warn(LD_APP, "Onion address %s requested from a port with .onion "
  1661. "disabled", safe_str_client(socks->address));
  1662. connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
  1663. return -1;
  1664. }
  1665. /* Check whether it's RESOLVE or RESOLVE_PTR. We don't handle those
  1666. * for hidden service addresses. */
  1667. if (SOCKS_COMMAND_IS_RESOLVE(socks->command)) {
  1668. /* if it's a resolve request, fail it right now, rather than
  1669. * building all the circuits and then realizing it won't work. */
  1670. log_warn(LD_APP,
  1671. "Resolve requests to hidden services not allowed. Failing.");
  1672. connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_ERROR,
  1673. 0,NULL,-1,TIME_MAX);
  1674. connection_mark_unattached_ap(conn,
  1675. END_STREAM_REASON_SOCKSPROTOCOL |
  1676. END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
  1677. return -1;
  1678. }
  1679. /* If we were passed a circuit, then we need to fail. .onion addresses
  1680. * only work when we launch our own circuits for now. */
  1681. if (circ) {
  1682. log_warn(LD_CONTROL, "Attachstream to a circuit is not "
  1683. "supported for .onion addresses currently. Failing.");
  1684. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1685. return -1;
  1686. }
  1687. /* Look up if we have client authorization configured for this hidden
  1688. * service. If we do, associate it with the rend_data. */
  1689. rend_service_authorization_t *client_auth =
  1690. rend_client_lookup_service_authorization(socks->address);
  1691. const uint8_t *cookie = NULL;
  1692. rend_auth_type_t auth_type = REND_NO_AUTH;
  1693. if (client_auth) {
  1694. log_info(LD_REND, "Using previously configured client authorization "
  1695. "for hidden service request.");
  1696. auth_type = client_auth->auth_type;
  1697. cookie = client_auth->descriptor_cookie;
  1698. }
  1699. /* Fill in the rend_data field so we can start doing a connection to
  1700. * a hidden service. */
  1701. rend_data_t *rend_data = ENTRY_TO_EDGE_CONN(conn)->rend_data =
  1702. rend_data_client_create(socks->address, NULL, (char *) cookie,
  1703. auth_type);
  1704. if (rend_data == NULL) {
  1705. return -1;
  1706. }
  1707. const char *onion_address = rend_data_get_address(rend_data);
  1708. log_info(LD_REND,"Got a hidden service request for ID '%s'",
  1709. safe_str_client(onion_address));
  1710. /* Lookup the given onion address. If invalid, stop right now.
  1711. * Otherwise, we might have it in the cache or not. */
  1712. unsigned int refetch_desc = 0;
  1713. rend_cache_entry_t *entry = NULL;
  1714. const int rend_cache_lookup_result =
  1715. rend_cache_lookup_entry(onion_address, -1, &entry);
  1716. if (rend_cache_lookup_result < 0) {
  1717. switch (-rend_cache_lookup_result) {
  1718. case EINVAL:
  1719. /* We should already have rejected this address! */
  1720. log_warn(LD_BUG,"Invalid service name '%s'",
  1721. safe_str_client(onion_address));
  1722. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1723. return -1;
  1724. case ENOENT:
  1725. /* We didn't have this; we should look it up. */
  1726. refetch_desc = 1;
  1727. break;
  1728. default:
  1729. log_warn(LD_BUG, "Unknown cache lookup error %d",
  1730. rend_cache_lookup_result);
  1731. return -1;
  1732. }
  1733. }
  1734. /* Help predict that we'll want to do hidden service circuits in the
  1735. * future. We're not sure if it will need a stable circuit yet, but
  1736. * we know we'll need *something*. */
  1737. rep_hist_note_used_internal(now, 0, 1);
  1738. /* Now we have a descriptor but is it usable or not? If not, refetch.
  1739. * Also, a fetch could have been requested if the onion address was not
  1740. * found in the cache previously. */
  1741. if (refetch_desc || !rend_client_any_intro_points_usable(entry)) {
  1742. connection_ap_mark_as_non_pending_circuit(conn);
  1743. base_conn->state = AP_CONN_STATE_RENDDESC_WAIT;
  1744. log_info(LD_REND, "Unknown descriptor %s. Fetching.",
  1745. safe_str_client(onion_address));
  1746. rend_client_refetch_v2_renddesc(rend_data);
  1747. return 0;
  1748. }
  1749. /* We have the descriptor! So launch a connection to the HS. */
  1750. base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  1751. log_info(LD_REND, "Descriptor is here. Great.");
  1752. /* We'll try to attach it at the next event loop, or whenever
  1753. * we call connection_ap_attach_pending() */
  1754. connection_ap_mark_as_pending_circuit(conn);
  1755. return 0;
  1756. }
  1757. return 0; /* unreached but keeps the compiler happy */
  1758. }
  1759. #ifdef TRANS_PF
  1760. static int pf_socket = -1;
  1761. int
  1762. get_pf_socket(void)
  1763. {
  1764. int pf;
  1765. /* This should be opened before dropping privileges. */
  1766. if (pf_socket >= 0)
  1767. return pf_socket;
  1768. #ifdef OPENBSD
  1769. /* only works on OpenBSD */
  1770. pf = tor_open_cloexec("/dev/pf", O_RDONLY, 0);
  1771. #else
  1772. /* works on NetBSD and FreeBSD */
  1773. pf = tor_open_cloexec("/dev/pf", O_RDWR, 0);
  1774. #endif
  1775. if (pf < 0) {
  1776. log_warn(LD_NET, "open(\"/dev/pf\") failed: %s", strerror(errno));
  1777. return -1;
  1778. }
  1779. pf_socket = pf;
  1780. return pf_socket;
  1781. }
  1782. #endif
  1783. #if defined(TRANS_NETFILTER) || defined(TRANS_PF) || defined(TRANS_TPROXY)
  1784. /** Try fill in the address of <b>req</b> from the socket configured
  1785. * with <b>conn</b>. */
  1786. static int
  1787. destination_from_socket(entry_connection_t *conn, socks_request_t *req)
  1788. {
  1789. struct sockaddr_storage orig_dst;
  1790. socklen_t orig_dst_len = sizeof(orig_dst);
  1791. tor_addr_t addr;
  1792. #ifdef TRANS_TRPOXY
  1793. if (options->TransProxyType_parsed == TPT_TPROXY) {
  1794. if (getsockname(ENTRY_TO_CONN(conn)->s, (struct sockaddr*)&orig_dst,
  1795. &orig_dst_len) < 0) {
  1796. int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
  1797. log_warn(LD_NET, "getsockname() failed: %s", tor_socket_strerror(e));
  1798. return -1;
  1799. }
  1800. goto done;
  1801. }
  1802. #endif
  1803. #ifdef TRANS_NETFILTER
  1804. int rv = -1;
  1805. switch (ENTRY_TO_CONN(conn)->socket_family) {
  1806. #ifdef TRANS_NETFILTER_IPV4
  1807. case AF_INET:
  1808. rv = getsockopt(ENTRY_TO_CONN(conn)->s, SOL_IP, SO_ORIGINAL_DST,
  1809. (struct sockaddr*)&orig_dst, &orig_dst_len);
  1810. break;
  1811. #endif
  1812. #ifdef TRANS_NETFILTER_IPV6
  1813. case AF_INET6:
  1814. rv = getsockopt(ENTRY_TO_CONN(conn)->s, SOL_IPV6, IP6T_SO_ORIGINAL_DST,
  1815. (struct sockaddr*)&orig_dst, &orig_dst_len);
  1816. break;
  1817. #endif
  1818. default:
  1819. log_warn(LD_BUG,
  1820. "Received transparent data from an unsuported socket family %d",
  1821. ENTRY_TO_CONN(conn)->socket_family);
  1822. return -1;
  1823. }
  1824. if (rv < 0) {
  1825. int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
  1826. log_warn(LD_NET, "getsockopt() failed: %s", tor_socket_strerror(e));
  1827. return -1;
  1828. }
  1829. goto done;
  1830. #elif defined(TRANS_PF)
  1831. if (getsockname(ENTRY_TO_CONN(conn)->s, (struct sockaddr*)&orig_dst,
  1832. &orig_dst_len) < 0) {
  1833. int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
  1834. log_warn(LD_NET, "getsockname() failed: %s", tor_socket_strerror(e));
  1835. return -1;
  1836. }
  1837. goto done;
  1838. #else
  1839. (void)conn;
  1840. (void)req;
  1841. log_warn(LD_BUG, "Unable to determine destination from socket.");
  1842. return -1;
  1843. #endif
  1844. done:
  1845. tor_addr_from_sockaddr(&addr, (struct sockaddr*)&orig_dst, &req->port);
  1846. tor_addr_to_str(req->address, &addr, sizeof(req->address), 1);
  1847. return 0;
  1848. }
  1849. #endif
  1850. #ifdef TRANS_PF
  1851. static int
  1852. destination_from_pf(entry_connection_t *conn, socks_request_t *req)
  1853. {
  1854. struct sockaddr_storage proxy_addr;
  1855. socklen_t proxy_addr_len = sizeof(proxy_addr);
  1856. struct sockaddr *proxy_sa = (struct sockaddr*) &proxy_addr;
  1857. struct pfioc_natlook pnl;
  1858. tor_addr_t addr;
  1859. int pf = -1;
  1860. if (getsockname(ENTRY_TO_CONN(conn)->s, (struct sockaddr*)&proxy_addr,
  1861. &proxy_addr_len) < 0) {
  1862. int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
  1863. log_warn(LD_NET, "getsockname() to determine transocks destination "
  1864. "failed: %s", tor_socket_strerror(e));
  1865. return -1;
  1866. }
  1867. #ifdef __FreeBSD__
  1868. if (get_options()->TransProxyType_parsed == TPT_IPFW) {
  1869. /* ipfw(8) is used and in this case getsockname returned the original
  1870. destination */
  1871. if (tor_addr_from_sockaddr(&addr, proxy_sa, &req->port) < 0) {
  1872. tor_fragile_assert();
  1873. return -1;
  1874. }
  1875. tor_addr_to_str(req->address, &addr, sizeof(req->address), 0);
  1876. return 0;
  1877. }
  1878. #endif
  1879. memset(&pnl, 0, sizeof(pnl));
  1880. pnl.proto = IPPROTO_TCP;
  1881. pnl.direction = PF_OUT;
  1882. if (proxy_sa->sa_family == AF_INET) {
  1883. struct sockaddr_in *sin = (struct sockaddr_in *)proxy_sa;
  1884. pnl.af = AF_INET;
  1885. pnl.saddr.v4.s_addr = tor_addr_to_ipv4n(&ENTRY_TO_CONN(conn)->addr);
  1886. pnl.sport = htons(ENTRY_TO_CONN(conn)->port);
  1887. pnl.daddr.v4.s_addr = sin->sin_addr.s_addr;
  1888. pnl.dport = sin->sin_port;
  1889. } else if (proxy_sa->sa_family == AF_INET6) {
  1890. struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)proxy_sa;
  1891. pnl.af = AF_INET6;
  1892. memcpy(&pnl.saddr.v6, tor_addr_to_in6(&ENTRY_TO_CONN(conn)->addr),
  1893. sizeof(struct in6_addr));
  1894. pnl.sport = htons(ENTRY_TO_CONN(conn)->port);
  1895. memcpy(&pnl.daddr.v6, &sin6->sin6_addr, sizeof(struct in6_addr));
  1896. pnl.dport = sin6->sin6_port;
  1897. } else {
  1898. log_warn(LD_NET, "getsockname() gave an unexpected address family (%d)",
  1899. (int)proxy_sa->sa_family);
  1900. return -1;
  1901. }
  1902. pf = get_pf_socket();
  1903. if (pf<0)
  1904. return -1;
  1905. if (ioctl(pf, DIOCNATLOOK, &pnl) < 0) {
  1906. log_warn(LD_NET, "ioctl(DIOCNATLOOK) failed: %s", strerror(errno));
  1907. return -1;
  1908. }
  1909. if (pnl.af == AF_INET) {
  1910. tor_addr_from_ipv4n(&addr, pnl.rdaddr.v4.s_addr);
  1911. } else if (pnl.af == AF_INET6) {
  1912. tor_addr_from_in6(&addr, &pnl.rdaddr.v6);
  1913. } else {
  1914. tor_fragile_assert();
  1915. return -1;
  1916. }
  1917. tor_addr_to_str(req->address, &addr, sizeof(req->address), 1);
  1918. req->port = ntohs(pnl.rdport);
  1919. return 0;
  1920. }
  1921. #endif
  1922. /** Fetch the original destination address and port from a
  1923. * system-specific interface and put them into a
  1924. * socks_request_t as if they came from a socks request.
  1925. *
  1926. * Return -1 if an error prevents fetching the destination,
  1927. * else return 0.
  1928. */
  1929. static int
  1930. connection_ap_get_original_destination(entry_connection_t *conn,
  1931. socks_request_t *req)
  1932. {
  1933. #ifdef TRANS_NETFILTER
  1934. return destination_from_socket(conn, req);
  1935. #elif defined(TRANS_PF)
  1936. const or_options_t *options = get_options();
  1937. if (options->TransProxyType_parsed == TPT_PF_DIVERT)
  1938. return destination_from_socket(conn, req);
  1939. if (options->TransProxyType_parsed == TPT_DEFAULT ||
  1940. options->TransProxyType_parsed == TPT_IPFW)
  1941. return destination_from_pf(conn, req);
  1942. (void)conn;
  1943. (void)req;
  1944. log_warn(LD_BUG, "Proxy destination determination mechanism %s unknown.",
  1945. options->TransProxyType);
  1946. return -1;
  1947. #else
  1948. (void)conn;
  1949. (void)req;
  1950. log_warn(LD_BUG, "Called connection_ap_get_original_destination, but no "
  1951. "transparent proxy method was configured.");
  1952. return -1;
  1953. #endif
  1954. }
  1955. /** connection_edge_process_inbuf() found a conn in state
  1956. * socks_wait. See if conn->inbuf has the right bytes to proceed with
  1957. * the socks handshake.
  1958. *
  1959. * If the handshake is complete, send it to
  1960. * connection_ap_handshake_rewrite_and_attach().
  1961. *
  1962. * Return -1 if an unexpected error with conn occurs (and mark it for close),
  1963. * else return 0.
  1964. */
  1965. static int
  1966. connection_ap_handshake_process_socks(entry_connection_t *conn)
  1967. {
  1968. socks_request_t *socks;
  1969. int sockshere;
  1970. const or_options_t *options = get_options();
  1971. int had_reply = 0;
  1972. connection_t *base_conn = ENTRY_TO_CONN(conn);
  1973. tor_assert(conn);
  1974. tor_assert(base_conn->type == CONN_TYPE_AP);
  1975. tor_assert(base_conn->state == AP_CONN_STATE_SOCKS_WAIT);
  1976. tor_assert(conn->socks_request);
  1977. socks = conn->socks_request;
  1978. log_debug(LD_APP,"entered.");
  1979. sockshere = fetch_from_buf_socks(base_conn->inbuf, socks,
  1980. options->TestSocks, options->SafeSocks);
  1981. if (socks->replylen) {
  1982. had_reply = 1;
  1983. connection_write_to_buf((const char*)socks->reply, socks->replylen,
  1984. base_conn);
  1985. socks->replylen = 0;
  1986. if (sockshere == -1) {
  1987. /* An invalid request just got a reply, no additional
  1988. * one is necessary. */
  1989. socks->has_finished = 1;
  1990. }
  1991. }
  1992. if (sockshere == 0) {
  1993. log_debug(LD_APP,"socks handshake not all here yet.");
  1994. return 0;
  1995. } else if (sockshere == -1) {
  1996. if (!had_reply) {
  1997. log_warn(LD_APP,"Fetching socks handshake failed. Closing.");
  1998. connection_ap_handshake_socks_reply(conn, NULL, 0,
  1999. END_STREAM_REASON_SOCKSPROTOCOL);
  2000. }
  2001. connection_mark_unattached_ap(conn,
  2002. END_STREAM_REASON_SOCKSPROTOCOL |
  2003. END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
  2004. return -1;
  2005. } /* else socks handshake is done, continue processing */
  2006. if (SOCKS_COMMAND_IS_CONNECT(socks->command))
  2007. control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
  2008. else
  2009. control_event_stream_status(conn, STREAM_EVENT_NEW_RESOLVE, 0);
  2010. return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
  2011. }
  2012. /** connection_init_accepted_conn() found a new trans AP conn.
  2013. * Get the original destination and send it to
  2014. * connection_ap_handshake_rewrite_and_attach().
  2015. *
  2016. * Return -1 if an unexpected error with conn (and it should be marked
  2017. * for close), else return 0.
  2018. */
  2019. int
  2020. connection_ap_process_transparent(entry_connection_t *conn)
  2021. {
  2022. socks_request_t *socks;
  2023. tor_assert(conn);
  2024. tor_assert(conn->socks_request);
  2025. socks = conn->socks_request;
  2026. /* pretend that a socks handshake completed so we don't try to
  2027. * send a socks reply down a transparent conn */
  2028. socks->command = SOCKS_COMMAND_CONNECT;
  2029. socks->has_finished = 1;
  2030. log_debug(LD_APP,"entered.");
  2031. if (connection_ap_get_original_destination(conn, socks) < 0) {
  2032. log_warn(LD_APP,"Fetching original destination failed. Closing.");
  2033. connection_mark_unattached_ap(conn,
  2034. END_STREAM_REASON_CANT_FETCH_ORIG_DEST);
  2035. return -1;
  2036. }
  2037. /* we have the original destination */
  2038. control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
  2039. return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
  2040. }
  2041. /** connection_edge_process_inbuf() found a conn in state natd_wait. See if
  2042. * conn-\>inbuf has the right bytes to proceed. See FreeBSD's libalias(3) and
  2043. * ProxyEncodeTcpStream() in src/lib/libalias/alias_proxy.c for the encoding
  2044. * form of the original destination.
  2045. *
  2046. * If the original destination is complete, send it to
  2047. * connection_ap_handshake_rewrite_and_attach().
  2048. *
  2049. * Return -1 if an unexpected error with conn (and it should be marked
  2050. * for close), else return 0.
  2051. */
  2052. static int
  2053. connection_ap_process_natd(entry_connection_t *conn)
  2054. {
  2055. char tmp_buf[36], *tbuf, *daddr;
  2056. size_t tlen = 30;
  2057. int err, port_ok;
  2058. socks_request_t *socks;
  2059. tor_assert(conn);
  2060. tor_assert(ENTRY_TO_CONN(conn)->state == AP_CONN_STATE_NATD_WAIT);
  2061. tor_assert(conn->socks_request);
  2062. socks = conn->socks_request;
  2063. log_debug(LD_APP,"entered.");
  2064. /* look for LF-terminated "[DEST ip_addr port]"
  2065. * where ip_addr is a dotted-quad and port is in string form */
  2066. err = connection_fetch_from_buf_line(ENTRY_TO_CONN(conn), tmp_buf, &tlen);
  2067. if (err == 0)
  2068. return 0;
  2069. if (err < 0) {
  2070. log_warn(LD_APP,"NATD handshake failed (DEST too long). Closing");
  2071. connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
  2072. return -1;
  2073. }
  2074. if (strcmpstart(tmp_buf, "[DEST ")) {
  2075. log_warn(LD_APP,"NATD handshake was ill-formed; closing. The client "
  2076. "said: %s",
  2077. escaped(tmp_buf));
  2078. connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
  2079. return -1;
  2080. }
  2081. daddr = tbuf = &tmp_buf[0] + 6; /* after end of "[DEST " */
  2082. if (!(tbuf = strchr(tbuf, ' '))) {
  2083. log_warn(LD_APP,"NATD handshake was ill-formed; closing. The client "
  2084. "said: %s",
  2085. escaped(tmp_buf));
  2086. connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
  2087. return -1;
  2088. }
  2089. *tbuf++ = '\0';
  2090. /* pretend that a socks handshake completed so we don't try to
  2091. * send a socks reply down a natd conn */
  2092. strlcpy(socks->address, daddr, sizeof(socks->address));
  2093. socks->port = (uint16_t)
  2094. tor_parse_long(tbuf, 10, 1, 65535, &port_ok, &daddr);
  2095. if (!port_ok) {
  2096. log_warn(LD_APP,"NATD handshake failed; port %s is ill-formed or out "
  2097. "of range.", escaped(tbuf));
  2098. connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
  2099. return -1;
  2100. }
  2101. socks->command = SOCKS_COMMAND_CONNECT;
  2102. socks->has_finished = 1;
  2103. control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
  2104. ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_CIRCUIT_WAIT;
  2105. return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
  2106. }
  2107. /** Iterate over the two bytes of stream_id until we get one that is not
  2108. * already in use; return it. Return 0 if can't get a unique stream_id.
  2109. */
  2110. streamid_t
  2111. get_unique_stream_id_by_circ(origin_circuit_t *circ)
  2112. {
  2113. edge_connection_t *tmpconn;
  2114. streamid_t test_stream_id;
  2115. uint32_t attempts=0;
  2116. again:
  2117. test_stream_id = circ->next_stream_id++;
  2118. if (++attempts > 1<<16) {
  2119. /* Make sure we don't loop forever if all stream_id's are used. */
  2120. log_warn(LD_APP,"No unused stream IDs. Failing.");
  2121. return 0;
  2122. }
  2123. if (test_stream_id == 0)
  2124. goto again;
  2125. for (tmpconn = circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream)
  2126. if (tmpconn->stream_id == test_stream_id)
  2127. goto again;
  2128. return test_stream_id;
  2129. }
  2130. /** Return true iff <b>conn</b> is linked to a circuit and configured to use
  2131. * an exit that supports optimistic data. */
  2132. static int
  2133. connection_ap_supports_optimistic_data(const entry_connection_t *conn)
  2134. {
  2135. const edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
  2136. /* We can only send optimistic data if we're connected to an open
  2137. general circuit. */
  2138. if (edge_conn->on_circuit == NULL ||
  2139. edge_conn->on_circuit->state != CIRCUIT_STATE_OPEN ||
  2140. (edge_conn->on_circuit->purpose != CIRCUIT_PURPOSE_C_GENERAL &&
  2141. edge_conn->on_circuit->purpose != CIRCUIT_PURPOSE_C_REND_JOINED))
  2142. return 0;
  2143. return conn->may_use_optimistic_data;
  2144. }
  2145. /** Return a bitmask of BEGIN_FLAG_* flags that we should transmit in the
  2146. * RELAY_BEGIN cell for <b>ap_conn</b>. */
  2147. static uint32_t
  2148. connection_ap_get_begincell_flags(entry_connection_t *ap_conn)
  2149. {
  2150. edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
  2151. const node_t *exitnode = NULL;
  2152. const crypt_path_t *cpath_layer = edge_conn->cpath_layer;
  2153. uint32_t flags = 0;
  2154. /* No flags for begindir */
  2155. if (ap_conn->use_begindir)
  2156. return 0;
  2157. /* No flags for hidden services. */
  2158. if (edge_conn->on_circuit->purpose != CIRCUIT_PURPOSE_C_GENERAL)
  2159. return 0;
  2160. /* If only IPv4 is supported, no flags */
  2161. if (ap_conn->entry_cfg.ipv4_traffic && !ap_conn->entry_cfg.ipv6_traffic)
  2162. return 0;
  2163. if (! cpath_layer ||
  2164. ! cpath_layer->extend_info)
  2165. return 0;
  2166. if (!ap_conn->entry_cfg.ipv4_traffic)
  2167. flags |= BEGIN_FLAG_IPV4_NOT_OK;
  2168. exitnode = node_get_by_id(cpath_layer->extend_info->identity_digest);
  2169. if (ap_conn->entry_cfg.ipv6_traffic && exitnode) {
  2170. tor_addr_t a;
  2171. tor_addr_make_null(&a, AF_INET6);
  2172. if (compare_tor_addr_to_node_policy(&a, ap_conn->socks_request->port,
  2173. exitnode)
  2174. != ADDR_POLICY_REJECTED) {
  2175. /* Only say "IPv6 OK" if the exit node supports IPv6. Otherwise there's
  2176. * no point. */
  2177. flags |= BEGIN_FLAG_IPV6_OK;
  2178. }
  2179. }
  2180. if (flags == BEGIN_FLAG_IPV6_OK) {
  2181. /* When IPv4 and IPv6 are both allowed, consider whether to say we
  2182. * prefer IPv6. Otherwise there's no point in declaring a preference */
  2183. if (ap_conn->entry_cfg.prefer_ipv6)
  2184. flags |= BEGIN_FLAG_IPV6_PREFERRED;
  2185. }
  2186. if (flags == BEGIN_FLAG_IPV4_NOT_OK) {
  2187. log_warn(LD_EDGE, "I'm about to ask a node for a connection that I "
  2188. "am telling it to fulfil with neither IPv4 nor IPv6. That's "
  2189. "not going to work. Did you perhaps ask for an IPv6 address "
  2190. "on an IPv4Only port, or vice versa?");
  2191. }
  2192. return flags;
  2193. }
  2194. /** Write a relay begin cell, using destaddr and destport from ap_conn's
  2195. * socks_request field, and send it down circ.
  2196. *
  2197. * If ap_conn is broken, mark it for close and return -1. Else return 0.
  2198. */
  2199. int
  2200. connection_ap_handshake_send_begin(entry_connection_t *ap_conn)
  2201. {
  2202. char payload[CELL_PAYLOAD_SIZE];
  2203. int payload_len;
  2204. int begin_type;
  2205. const or_options_t *options = get_options();
  2206. origin_circuit_t *circ;
  2207. edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
  2208. connection_t *base_conn = TO_CONN(edge_conn);
  2209. tor_assert(edge_conn->on_circuit);
  2210. circ = TO_ORIGIN_CIRCUIT(edge_conn->on_circuit);
  2211. tor_assert(base_conn->type == CONN_TYPE_AP);
  2212. tor_assert(base_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
  2213. tor_assert(ap_conn->socks_request);
  2214. tor_assert(SOCKS_COMMAND_IS_CONNECT(ap_conn->socks_request->command));
  2215. edge_conn->stream_id = get_unique_stream_id_by_circ(circ);
  2216. if (edge_conn->stream_id==0) {
  2217. /* XXXX+ Instead of closing this stream, we should make it get
  2218. * retried on another circuit. */
  2219. connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
  2220. /* Mark this circuit "unusable for new streams". */
  2221. mark_circuit_unusable_for_new_conns(circ);
  2222. return -1;
  2223. }
  2224. /* Set up begin cell flags. */
  2225. edge_conn->begincell_flags = connection_ap_get_begincell_flags(ap_conn);
  2226. tor_snprintf(payload,RELAY_PAYLOAD_SIZE, "%s:%d",
  2227. (circ->base_.purpose == CIRCUIT_PURPOSE_C_GENERAL) ?
  2228. ap_conn->socks_request->address : "",
  2229. ap_conn->socks_request->port);
  2230. payload_len = (int)strlen(payload)+1;
  2231. if (payload_len <= RELAY_PAYLOAD_SIZE - 4 && edge_conn->begincell_flags) {
  2232. set_uint32(payload + payload_len, htonl(edge_conn->begincell_flags));
  2233. payload_len += 4;
  2234. }
  2235. log_info(LD_APP,
  2236. "Sending relay cell %d on circ %u to begin stream %d.",
  2237. (int)ap_conn->use_begindir,
  2238. (unsigned)circ->base_.n_circ_id,
  2239. edge_conn->stream_id);
  2240. begin_type = ap_conn->use_begindir ?
  2241. RELAY_COMMAND_BEGIN_DIR : RELAY_COMMAND_BEGIN;
  2242. /* Check that circuits are anonymised, based on their type. */
  2243. if (begin_type == RELAY_COMMAND_BEGIN) {
  2244. /* This connection is a standard OR connection.
  2245. * Make sure its path length is anonymous, or that we're in a
  2246. * non-anonymous mode. */
  2247. assert_circ_anonymity_ok(circ, options);
  2248. } else if (begin_type == RELAY_COMMAND_BEGIN_DIR) {
  2249. /* This connection is a begindir directory connection.
  2250. * Look at the linked directory connection to access the directory purpose.
  2251. * (This must be non-NULL, because we're doing begindir.) */
  2252. tor_assert(base_conn->linked);
  2253. connection_t *linked_dir_conn_base = base_conn->linked_conn;
  2254. tor_assert(linked_dir_conn_base);
  2255. /* Sensitive directory connections must have an anonymous path length.
  2256. * Otherwise, directory connections are typically one-hop.
  2257. * This matches the earlier check for directory connection path anonymity
  2258. * in directory_initiate_command_rend(). */
  2259. if (purpose_needs_anonymity(linked_dir_conn_base->purpose,
  2260. TO_DIR_CONN(linked_dir_conn_base)->router_purpose,
  2261. TO_DIR_CONN(linked_dir_conn_base)->requested_resource)) {
  2262. assert_circ_anonymity_ok(circ, options);
  2263. }
  2264. } else {
  2265. /* This code was written for the two connection types BEGIN and BEGIN_DIR
  2266. */
  2267. tor_assert_unreached();
  2268. }
  2269. if (connection_edge_send_command(edge_conn, begin_type,
  2270. begin_type == RELAY_COMMAND_BEGIN ? payload : NULL,
  2271. begin_type == RELAY_COMMAND_BEGIN ? payload_len : 0) < 0)
  2272. return -1; /* circuit is closed, don't continue */
  2273. edge_conn->package_window = STREAMWINDOW_START;
  2274. edge_conn->deliver_window = STREAMWINDOW_START;
  2275. base_conn->state = AP_CONN_STATE_CONNECT_WAIT;
  2276. log_info(LD_APP,"Address/port sent, ap socket "TOR_SOCKET_T_FORMAT
  2277. ", n_circ_id %u",
  2278. base_conn->s, (unsigned)circ->base_.n_circ_id);
  2279. control_event_stream_status(ap_conn, STREAM_EVENT_SENT_CONNECT, 0);
  2280. /* If there's queued-up data, send it now */
  2281. if ((connection_get_inbuf_len(base_conn) ||
  2282. ap_conn->sending_optimistic_data) &&
  2283. connection_ap_supports_optimistic_data(ap_conn)) {
  2284. log_info(LD_APP, "Sending up to %ld + %ld bytes of queued-up data",
  2285. (long)connection_get_inbuf_len(base_conn),
  2286. ap_conn->sending_optimistic_data ?
  2287. (long)buf_datalen(ap_conn->sending_optimistic_data) : 0);
  2288. if (connection_edge_package_raw_inbuf(edge_conn, 1, NULL) < 0) {
  2289. connection_mark_for_close(base_conn);
  2290. }
  2291. }
  2292. return 0;
  2293. }
  2294. /** Write a relay resolve cell, using destaddr and destport from ap_conn's
  2295. * socks_request field, and send it down circ.
  2296. *
  2297. * If ap_conn is broken, mark it for close and return -1. Else return 0.
  2298. */
  2299. int
  2300. connection_ap_handshake_send_resolve(entry_connection_t *ap_conn)
  2301. {
  2302. int payload_len, command;
  2303. const char *string_addr;
  2304. char inaddr_buf[REVERSE_LOOKUP_NAME_BUF_LEN];
  2305. origin_circuit_t *circ;
  2306. edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
  2307. connection_t *base_conn = TO_CONN(edge_conn);
  2308. tor_assert(edge_conn->on_circuit);
  2309. circ = TO_ORIGIN_CIRCUIT(edge_conn->on_circuit);
  2310. tor_assert(base_conn->type == CONN_TYPE_AP);
  2311. tor_assert(base_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
  2312. tor_assert(ap_conn->socks_request);
  2313. tor_assert(circ->base_.purpose == CIRCUIT_PURPOSE_C_GENERAL);
  2314. command = ap_conn->socks_request->command;
  2315. tor_assert(SOCKS_COMMAND_IS_RESOLVE(command));
  2316. edge_conn->stream_id = get_unique_stream_id_by_circ(circ);
  2317. if (edge_conn->stream_id==0) {
  2318. /* XXXX+ Instead of closing this stream, we should make it get
  2319. * retried on another circuit. */
  2320. connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
  2321. /* Mark this circuit "unusable for new streams". */
  2322. mark_circuit_unusable_for_new_conns(circ);
  2323. return -1;
  2324. }
  2325. if (command == SOCKS_COMMAND_RESOLVE) {
  2326. string_addr = ap_conn->socks_request->address;
  2327. payload_len = (int)strlen(string_addr)+1;
  2328. } else {
  2329. /* command == SOCKS_COMMAND_RESOLVE_PTR */
  2330. const char *a = ap_conn->socks_request->address;
  2331. tor_addr_t addr;
  2332. int r;
  2333. /* We're doing a reverse lookup. The input could be an IP address, or
  2334. * could be an .in-addr.arpa or .ip6.arpa address */
  2335. r = tor_addr_parse_PTR_name(&addr, a, AF_UNSPEC, 1);
  2336. if (r <= 0) {
  2337. log_warn(LD_APP, "Rejecting ill-formed reverse lookup of %s",
  2338. safe_str_client(a));
  2339. connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
  2340. return -1;
  2341. }
  2342. r = tor_addr_to_PTR_name(inaddr_buf, sizeof(inaddr_buf), &addr);
  2343. if (r < 0) {
  2344. log_warn(LD_BUG, "Couldn't generate reverse lookup hostname of %s",
  2345. safe_str_client(a));
  2346. connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
  2347. return -1;
  2348. }
  2349. string_addr = inaddr_buf;
  2350. payload_len = (int)strlen(inaddr_buf)+1;
  2351. tor_assert(payload_len <= (int)sizeof(inaddr_buf));
  2352. }
  2353. log_debug(LD_APP,
  2354. "Sending relay cell to begin stream %d.", edge_conn->stream_id);
  2355. if (connection_edge_send_command(edge_conn,
  2356. RELAY_COMMAND_RESOLVE,
  2357. string_addr, payload_len) < 0)
  2358. return -1; /* circuit is closed, don't continue */
  2359. if (!base_conn->address) {
  2360. /* This might be unnecessary. XXXX */
  2361. base_conn->address = tor_addr_to_str_dup(&base_conn->addr);
  2362. }
  2363. base_conn->state = AP_CONN_STATE_RESOLVE_WAIT;
  2364. log_info(LD_APP,"Address sent for resolve, ap socket "TOR_SOCKET_T_FORMAT
  2365. ", n_circ_id %u",
  2366. base_conn->s, (unsigned)circ->base_.n_circ_id);
  2367. control_event_stream_status(ap_conn, STREAM_EVENT_SENT_RESOLVE, 0);
  2368. return 0;
  2369. }
  2370. /** Make an AP connection_t linked to the connection_t <b>partner</b>. make a
  2371. * new linked connection pair, and attach one side to the conn, connection_add
  2372. * it, initialize it to circuit_wait, and call
  2373. * connection_ap_handshake_attach_circuit(conn) on it.
  2374. *
  2375. * Return the newly created end of the linked connection pair, or -1 if error.
  2376. */
  2377. entry_connection_t *
  2378. connection_ap_make_link(connection_t *partner,
  2379. char *address, uint16_t port,
  2380. const char *digest,
  2381. int session_group, int isolation_flags,
  2382. int use_begindir, int want_onehop)
  2383. {
  2384. entry_connection_t *conn;
  2385. connection_t *base_conn;
  2386. log_info(LD_APP,"Making internal %s tunnel to %s:%d ...",
  2387. want_onehop ? "direct" : "anonymized",
  2388. safe_str_client(address), port);
  2389. conn = entry_connection_new(CONN_TYPE_AP, tor_addr_family(&partner->addr));
  2390. base_conn = ENTRY_TO_CONN(conn);
  2391. base_conn->linked = 1; /* so that we can add it safely below. */
  2392. /* populate conn->socks_request */
  2393. /* leave version at zero, so the socks_reply is empty */
  2394. conn->socks_request->socks_version = 0;
  2395. conn->socks_request->has_finished = 0; /* waiting for 'connected' */
  2396. strlcpy(conn->socks_request->address, address,
  2397. sizeof(conn->socks_request->address));
  2398. conn->socks_request->port = port;
  2399. conn->socks_request->command = SOCKS_COMMAND_CONNECT;
  2400. conn->want_onehop = want_onehop;
  2401. conn->use_begindir = use_begindir;
  2402. if (use_begindir) {
  2403. conn->chosen_exit_name = tor_malloc(HEX_DIGEST_LEN+2);
  2404. conn->chosen_exit_name[0] = '$';
  2405. tor_assert(digest);
  2406. base16_encode(conn->chosen_exit_name+1,HEX_DIGEST_LEN+1,
  2407. digest, DIGEST_LEN);
  2408. }
  2409. /* Populate isolation fields. */
  2410. conn->socks_request->listener_type = CONN_TYPE_DIR_LISTENER;
  2411. conn->original_dest_address = tor_strdup(address);
  2412. conn->entry_cfg.session_group = session_group;
  2413. conn->entry_cfg.isolation_flags = isolation_flags;
  2414. base_conn->address = tor_strdup("(Tor_internal)");
  2415. tor_addr_make_unspec(&base_conn->addr);
  2416. base_conn->port = 0;
  2417. connection_link_connections(partner, base_conn);
  2418. if (connection_add(base_conn) < 0) { /* no space, forget it */
  2419. connection_free(base_conn);
  2420. return NULL;
  2421. }
  2422. base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  2423. control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
  2424. /* attaching to a dirty circuit is fine */
  2425. connection_ap_mark_as_pending_circuit(conn);
  2426. log_info(LD_APP,"... application connection created and linked.");
  2427. return conn;
  2428. }
  2429. /** Notify any interested controller connections about a new hostname resolve
  2430. * or resolve error. Takes the same arguments as does
  2431. * connection_ap_handshake_socks_resolved(). */
  2432. static void
  2433. tell_controller_about_resolved_result(entry_connection_t *conn,
  2434. int answer_type,
  2435. size_t answer_len,
  2436. const char *answer,
  2437. int ttl,
  2438. time_t expires)
  2439. {
  2440. expires = time(NULL) + ttl;
  2441. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len >= 4) {
  2442. char *cp = tor_dup_ip(ntohl(get_uint32(answer)));
  2443. control_event_address_mapped(conn->socks_request->address,
  2444. cp, expires, NULL, 0);
  2445. tor_free(cp);
  2446. } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
  2447. char *cp = tor_strndup(answer, answer_len);
  2448. control_event_address_mapped(conn->socks_request->address,
  2449. cp, expires, NULL, 0);
  2450. tor_free(cp);
  2451. } else {
  2452. control_event_address_mapped(conn->socks_request->address,
  2453. "<error>", time(NULL)+ttl,
  2454. "error=yes", 0);
  2455. }
  2456. }
  2457. /**
  2458. * As connection_ap_handshake_socks_resolved, but take a tor_addr_t to send
  2459. * as the answer.
  2460. */
  2461. void
  2462. connection_ap_handshake_socks_resolved_addr(entry_connection_t *conn,
  2463. const tor_addr_t *answer,
  2464. int ttl,
  2465. time_t expires)
  2466. {
  2467. if (tor_addr_family(answer) == AF_INET) {
  2468. uint32_t a = tor_addr_to_ipv4n(answer); /* network order */
  2469. connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_IPV4,4,
  2470. (uint8_t*)&a,
  2471. ttl, expires);
  2472. } else if (tor_addr_family(answer) == AF_INET6) {
  2473. const uint8_t *a = tor_addr_to_in6_addr8(answer);
  2474. connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_IPV6,16,
  2475. a,
  2476. ttl, expires);
  2477. } else {
  2478. log_warn(LD_BUG, "Got called with address of unexpected family %d",
  2479. tor_addr_family(answer));
  2480. connection_ap_handshake_socks_resolved(conn,
  2481. RESOLVED_TYPE_ERROR,0,NULL,-1,-1);
  2482. }
  2483. }
  2484. /** Send an answer to an AP connection that has requested a DNS lookup via
  2485. * SOCKS. The type should be one of RESOLVED_TYPE_(IPV4|IPV6|HOSTNAME) or -1
  2486. * for unreachable; the answer should be in the format specified in the socks
  2487. * extensions document. <b>ttl</b> is the ttl for the answer, or -1 on
  2488. * certain errors or for values that didn't come via DNS. <b>expires</b> is
  2489. * a time when the answer expires, or -1 or TIME_MAX if there's a good TTL.
  2490. **/
  2491. /* XXXX the use of the ttl and expires fields is nutty. Let's make this
  2492. * interface and those that use it less ugly. */
  2493. MOCK_IMPL(void,
  2494. connection_ap_handshake_socks_resolved,(entry_connection_t *conn,
  2495. int answer_type,
  2496. size_t answer_len,
  2497. const uint8_t *answer,
  2498. int ttl,
  2499. time_t expires))
  2500. {
  2501. char buf[384];
  2502. size_t replylen;
  2503. if (ttl >= 0) {
  2504. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
  2505. tor_addr_t a;
  2506. tor_addr_from_ipv4n(&a, get_uint32(answer));
  2507. if (! tor_addr_is_null(&a)) {
  2508. client_dns_set_addressmap(conn,
  2509. conn->socks_request->address, &a,
  2510. conn->chosen_exit_name, ttl);
  2511. }
  2512. } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
  2513. tor_addr_t a;
  2514. tor_addr_from_ipv6_bytes(&a, (char*)answer);
  2515. if (! tor_addr_is_null(&a)) {
  2516. client_dns_set_addressmap(conn,
  2517. conn->socks_request->address, &a,
  2518. conn->chosen_exit_name, ttl);
  2519. }
  2520. } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
  2521. char *cp = tor_strndup((char*)answer, answer_len);
  2522. client_dns_set_reverse_addressmap(conn,
  2523. conn->socks_request->address,
  2524. cp,
  2525. conn->chosen_exit_name, ttl);
  2526. tor_free(cp);
  2527. }
  2528. }
  2529. if (ENTRY_TO_EDGE_CONN(conn)->is_dns_request) {
  2530. if (conn->dns_server_request) {
  2531. /* We had a request on our DNS port: answer it. */
  2532. dnsserv_resolved(conn, answer_type, answer_len, (char*)answer, ttl);
  2533. conn->socks_request->has_finished = 1;
  2534. return;
  2535. } else {
  2536. /* This must be a request from the controller. Since answers to those
  2537. * requests are not cached, they do not generate an ADDRMAP event on
  2538. * their own. */
  2539. tell_controller_about_resolved_result(conn, answer_type, answer_len,
  2540. (char*)answer, ttl, expires);
  2541. conn->socks_request->has_finished = 1;
  2542. return;
  2543. }
  2544. /* We shouldn't need to free conn here; it gets marked by the caller. */
  2545. }
  2546. if (conn->socks_request->socks_version == 4) {
  2547. buf[0] = 0x00; /* version */
  2548. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
  2549. buf[1] = SOCKS4_GRANTED;
  2550. set_uint16(buf+2, 0);
  2551. memcpy(buf+4, answer, 4); /* address */
  2552. replylen = SOCKS4_NETWORK_LEN;
  2553. } else { /* "error" */
  2554. buf[1] = SOCKS4_REJECT;
  2555. memset(buf+2, 0, 6);
  2556. replylen = SOCKS4_NETWORK_LEN;
  2557. }
  2558. } else if (conn->socks_request->socks_version == 5) {
  2559. /* SOCKS5 */
  2560. buf[0] = 0x05; /* version */
  2561. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
  2562. buf[1] = SOCKS5_SUCCEEDED;
  2563. buf[2] = 0; /* reserved */
  2564. buf[3] = 0x01; /* IPv4 address type */
  2565. memcpy(buf+4, answer, 4); /* address */
  2566. set_uint16(buf+8, 0); /* port == 0. */
  2567. replylen = 10;
  2568. } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
  2569. buf[1] = SOCKS5_SUCCEEDED;
  2570. buf[2] = 0; /* reserved */
  2571. buf[3] = 0x04; /* IPv6 address type */
  2572. memcpy(buf+4, answer, 16); /* address */
  2573. set_uint16(buf+20, 0); /* port == 0. */
  2574. replylen = 22;
  2575. } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
  2576. buf[1] = SOCKS5_SUCCEEDED;
  2577. buf[2] = 0; /* reserved */
  2578. buf[3] = 0x03; /* Domainname address type */
  2579. buf[4] = (char)answer_len;
  2580. memcpy(buf+5, answer, answer_len); /* address */
  2581. set_uint16(buf+5+answer_len, 0); /* port == 0. */
  2582. replylen = 5+answer_len+2;
  2583. } else {
  2584. buf[1] = SOCKS5_HOST_UNREACHABLE;
  2585. memset(buf+2, 0, 8);
  2586. replylen = 10;
  2587. }
  2588. } else {
  2589. /* no socks version info; don't send anything back */
  2590. return;
  2591. }
  2592. connection_ap_handshake_socks_reply(conn, buf, replylen,
  2593. (answer_type == RESOLVED_TYPE_IPV4 ||
  2594. answer_type == RESOLVED_TYPE_IPV6 ||
  2595. answer_type == RESOLVED_TYPE_HOSTNAME) ?
  2596. 0 : END_STREAM_REASON_RESOLVEFAILED);
  2597. }
  2598. /** Send a socks reply to stream <b>conn</b>, using the appropriate
  2599. * socks version, etc, and mark <b>conn</b> as completed with SOCKS
  2600. * handshaking.
  2601. *
  2602. * If <b>reply</b> is defined, then write <b>replylen</b> bytes of it to conn
  2603. * and return, else reply based on <b>endreason</b> (one of
  2604. * END_STREAM_REASON_*). If <b>reply</b> is undefined, <b>endreason</b> can't
  2605. * be 0 or REASON_DONE. Send endreason to the controller, if appropriate.
  2606. */
  2607. void
  2608. connection_ap_handshake_socks_reply(entry_connection_t *conn, char *reply,
  2609. size_t replylen, int endreason)
  2610. {
  2611. char buf[256];
  2612. socks5_reply_status_t status =
  2613. stream_end_reason_to_socks5_response(endreason);
  2614. tor_assert(conn->socks_request); /* make sure it's an AP stream */
  2615. if (!SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command)) {
  2616. control_event_stream_status(conn, status==SOCKS5_SUCCEEDED ?
  2617. STREAM_EVENT_SUCCEEDED : STREAM_EVENT_FAILED,
  2618. endreason);
  2619. }
  2620. /* Flag this stream's circuit as having completed a stream successfully
  2621. * (for path bias) */
  2622. if (status == SOCKS5_SUCCEEDED ||
  2623. endreason == END_STREAM_REASON_RESOLVEFAILED ||
  2624. endreason == END_STREAM_REASON_CONNECTREFUSED ||
  2625. endreason == END_STREAM_REASON_CONNRESET ||
  2626. endreason == END_STREAM_REASON_NOROUTE ||
  2627. endreason == END_STREAM_REASON_RESOURCELIMIT) {
  2628. if (!conn->edge_.on_circuit ||
  2629. !CIRCUIT_IS_ORIGIN(conn->edge_.on_circuit)) {
  2630. if (endreason != END_STREAM_REASON_RESOLVEFAILED) {
  2631. log_info(LD_BUG,
  2632. "No origin circuit for successful SOCKS stream "U64_FORMAT
  2633. ". Reason: %d",
  2634. U64_PRINTF_ARG(ENTRY_TO_CONN(conn)->global_identifier),
  2635. endreason);
  2636. }
  2637. /*
  2638. * Else DNS remaps and failed hidden service lookups can send us
  2639. * here with END_STREAM_REASON_RESOLVEFAILED; ignore it
  2640. *
  2641. * Perhaps we could make the test more precise; we can tell hidden
  2642. * services by conn->edge_.renddata != NULL; anything analogous for
  2643. * the DNS remap case?
  2644. */
  2645. } else {
  2646. // XXX: Hrmm. It looks like optimistic data can't go through this
  2647. // codepath, but someone should probably test it and make sure.
  2648. // We don't want to mark optimistically opened streams as successful.
  2649. pathbias_mark_use_success(TO_ORIGIN_CIRCUIT(conn->edge_.on_circuit));
  2650. }
  2651. }
  2652. if (conn->socks_request->has_finished) {
  2653. log_warn(LD_BUG, "(Harmless.) duplicate calls to "
  2654. "connection_ap_handshake_socks_reply.");
  2655. return;
  2656. }
  2657. if (replylen) { /* we already have a reply in mind */
  2658. connection_write_to_buf(reply, replylen, ENTRY_TO_CONN(conn));
  2659. conn->socks_request->has_finished = 1;
  2660. return;
  2661. }
  2662. if (conn->socks_request->socks_version == 4) {
  2663. memset(buf,0,SOCKS4_NETWORK_LEN);
  2664. buf[1] = (status==SOCKS5_SUCCEEDED ? SOCKS4_GRANTED : SOCKS4_REJECT);
  2665. /* leave version, destport, destip zero */
  2666. connection_write_to_buf(buf, SOCKS4_NETWORK_LEN, ENTRY_TO_CONN(conn));
  2667. } else if (conn->socks_request->socks_version == 5) {
  2668. size_t buf_len;
  2669. memset(buf,0,sizeof(buf));
  2670. if (tor_addr_family(&conn->edge_.base_.addr) == AF_INET) {
  2671. buf[0] = 5; /* version 5 */
  2672. buf[1] = (char)status;
  2673. buf[2] = 0;
  2674. buf[3] = 1; /* ipv4 addr */
  2675. /* 4 bytes for the header, 2 bytes for the port, 4 for the address. */
  2676. buf_len = 10;
  2677. } else { /* AF_INET6. */
  2678. buf[0] = 5; /* version 5 */
  2679. buf[1] = (char)status;
  2680. buf[2] = 0;
  2681. buf[3] = 4; /* ipv6 addr */
  2682. /* 4 bytes for the header, 2 bytes for the port, 16 for the address. */
  2683. buf_len = 22;
  2684. }
  2685. connection_write_to_buf(buf,buf_len,ENTRY_TO_CONN(conn));
  2686. }
  2687. /* If socks_version isn't 4 or 5, don't send anything.
  2688. * This can happen in the case of AP bridges. */
  2689. conn->socks_request->has_finished = 1;
  2690. return;
  2691. }
  2692. /** Read a RELAY_BEGIN or RELAY_BEGINDIR cell from <b>cell</b>, decode it, and
  2693. * place the result in <b>bcell</b>. On success return 0; on failure return
  2694. * <0 and set *<b>end_reason_out</b> to the end reason we should send back to
  2695. * the client.
  2696. *
  2697. * Return -1 in the case where want to send a RELAY_END cell, and < -1 when
  2698. * we don't.
  2699. **/
  2700. STATIC int
  2701. begin_cell_parse(const cell_t *cell, begin_cell_t *bcell,
  2702. uint8_t *end_reason_out)
  2703. {
  2704. relay_header_t rh;
  2705. const uint8_t *body, *nul;
  2706. memset(bcell, 0, sizeof(*bcell));
  2707. *end_reason_out = END_STREAM_REASON_MISC;
  2708. relay_header_unpack(&rh, cell->payload);
  2709. if (rh.length > RELAY_PAYLOAD_SIZE) {
  2710. return -2; /*XXXX why not TORPROTOCOL? */
  2711. }
  2712. bcell->stream_id = rh.stream_id;
  2713. if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
  2714. bcell->is_begindir = 1;
  2715. return 0;
  2716. } else if (rh.command != RELAY_COMMAND_BEGIN) {
  2717. log_warn(LD_BUG, "Got an unexpected command %d", (int)rh.command);
  2718. *end_reason_out = END_STREAM_REASON_INTERNAL;
  2719. return -1;
  2720. }
  2721. body = cell->payload + RELAY_HEADER_SIZE;
  2722. nul = memchr(body, 0, rh.length);
  2723. if (! nul) {
  2724. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  2725. "Relay begin cell has no \\0. Closing.");
  2726. *end_reason_out = END_STREAM_REASON_TORPROTOCOL;
  2727. return -1;
  2728. }
  2729. if (tor_addr_port_split(LOG_PROTOCOL_WARN,
  2730. (char*)(body),
  2731. &bcell->address,&bcell->port)<0) {
  2732. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  2733. "Unable to parse addr:port in relay begin cell. Closing.");
  2734. *end_reason_out = END_STREAM_REASON_TORPROTOCOL;
  2735. return -1;
  2736. }
  2737. if (bcell->port == 0) {
  2738. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  2739. "Missing port in relay begin cell. Closing.");
  2740. tor_free(bcell->address);
  2741. *end_reason_out = END_STREAM_REASON_TORPROTOCOL;
  2742. return -1;
  2743. }
  2744. if (body + rh.length >= nul + 4)
  2745. bcell->flags = ntohl(get_uint32(nul+1));
  2746. return 0;
  2747. }
  2748. /** A relay 'begin' or 'begin_dir' cell has arrived, and either we are
  2749. * an exit hop for the circuit, or we are the origin and it is a
  2750. * rendezvous begin.
  2751. *
  2752. * Launch a new exit connection and initialize things appropriately.
  2753. *
  2754. * If it's a rendezvous stream, call connection_exit_connect() on
  2755. * it.
  2756. *
  2757. * For general streams, call dns_resolve() on it first, and only call
  2758. * connection_exit_connect() if the dns answer is already known.
  2759. *
  2760. * Note that we don't call connection_add() on the new stream! We wait
  2761. * for connection_exit_connect() to do that.
  2762. *
  2763. * Return -(some circuit end reason) if we want to tear down <b>circ</b>.
  2764. * Else return 0.
  2765. */
  2766. int
  2767. connection_exit_begin_conn(cell_t *cell, circuit_t *circ)
  2768. {
  2769. edge_connection_t *n_stream;
  2770. relay_header_t rh;
  2771. char *address = NULL;
  2772. uint16_t port = 0;
  2773. or_circuit_t *or_circ = NULL;
  2774. const or_options_t *options = get_options();
  2775. begin_cell_t bcell;
  2776. int rv;
  2777. uint8_t end_reason=0;
  2778. assert_circuit_ok(circ);
  2779. if (!CIRCUIT_IS_ORIGIN(circ))
  2780. or_circ = TO_OR_CIRCUIT(circ);
  2781. relay_header_unpack(&rh, cell->payload);
  2782. if (rh.length > RELAY_PAYLOAD_SIZE)
  2783. return -END_CIRC_REASON_TORPROTOCOL;
  2784. /* Note: we have to use relay_send_command_from_edge here, not
  2785. * connection_edge_end or connection_edge_send_command, since those require
  2786. * that we have a stream connected to a circuit, and we don't connect to a
  2787. * circuit until we have a pending/successful resolve. */
  2788. if (!server_mode(options) &&
  2789. circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
  2790. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  2791. "Relay begin cell at non-server. Closing.");
  2792. relay_send_end_cell_from_edge(rh.stream_id, circ,
  2793. END_STREAM_REASON_EXITPOLICY, NULL);
  2794. return 0;
  2795. }
  2796. rv = begin_cell_parse(cell, &bcell, &end_reason);
  2797. if (rv < -1) {
  2798. return -END_CIRC_REASON_TORPROTOCOL;
  2799. } else if (rv == -1) {
  2800. tor_free(bcell.address);
  2801. relay_send_end_cell_from_edge(rh.stream_id, circ, end_reason, NULL);
  2802. return 0;
  2803. }
  2804. if (! bcell.is_begindir) {
  2805. /* Steal reference */
  2806. address = bcell.address;
  2807. port = bcell.port;
  2808. if (or_circ && or_circ->p_chan) {
  2809. if (!options->AllowSingleHopExits &&
  2810. (or_circ->is_first_hop ||
  2811. (!connection_or_digest_is_known_relay(
  2812. or_circ->p_chan->identity_digest) &&
  2813. should_refuse_unknown_exits(options)))) {
  2814. /* Don't let clients use us as a single-hop proxy, unless the user
  2815. * has explicitly allowed that in the config. It attracts attackers
  2816. * and users who'd be better off with, well, single-hop proxies.
  2817. */
  2818. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  2819. "Attempt by %s to open a stream %s. Closing.",
  2820. safe_str(channel_get_canonical_remote_descr(or_circ->p_chan)),
  2821. or_circ->is_first_hop ? "on first hop of circuit" :
  2822. "from unknown relay");
  2823. relay_send_end_cell_from_edge(rh.stream_id, circ,
  2824. or_circ->is_first_hop ?
  2825. END_STREAM_REASON_TORPROTOCOL :
  2826. END_STREAM_REASON_MISC,
  2827. NULL);
  2828. tor_free(address);
  2829. return 0;
  2830. }
  2831. }
  2832. } else if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
  2833. if (!directory_permits_begindir_requests(options) ||
  2834. circ->purpose != CIRCUIT_PURPOSE_OR) {
  2835. relay_send_end_cell_from_edge(rh.stream_id, circ,
  2836. END_STREAM_REASON_NOTDIRECTORY, NULL);
  2837. return 0;
  2838. }
  2839. /* Make sure to get the 'real' address of the previous hop: the
  2840. * caller might want to know whether the remote IP address has changed,
  2841. * and we might already have corrected base_.addr[ess] for the relay's
  2842. * canonical IP address. */
  2843. if (or_circ && or_circ->p_chan)
  2844. address = tor_strdup(channel_get_actual_remote_address(or_circ->p_chan));
  2845. else
  2846. address = tor_strdup("127.0.0.1");
  2847. port = 1; /* XXXX This value is never actually used anywhere, and there
  2848. * isn't "really" a connection here. But we
  2849. * need to set it to something nonzero. */
  2850. } else {
  2851. log_warn(LD_BUG, "Got an unexpected command %d", (int)rh.command);
  2852. relay_send_end_cell_from_edge(rh.stream_id, circ,
  2853. END_STREAM_REASON_INTERNAL, NULL);
  2854. return 0;
  2855. }
  2856. if (! options->IPv6Exit) {
  2857. /* I don't care if you prefer IPv6; I can't give you any. */
  2858. bcell.flags &= ~BEGIN_FLAG_IPV6_PREFERRED;
  2859. /* If you don't want IPv4, I can't help. */
  2860. if (bcell.flags & BEGIN_FLAG_IPV4_NOT_OK) {
  2861. tor_free(address);
  2862. relay_send_end_cell_from_edge(rh.stream_id, circ,
  2863. END_STREAM_REASON_EXITPOLICY, NULL);
  2864. return 0;
  2865. }
  2866. }
  2867. log_debug(LD_EXIT,"Creating new exit connection.");
  2868. /* The 'AF_INET' here is temporary; we might need to change it later in
  2869. * connection_exit_connect(). */
  2870. n_stream = edge_connection_new(CONN_TYPE_EXIT, AF_INET);
  2871. /* Remember the tunneled request ID in the new edge connection, so that
  2872. * we can measure download times. */
  2873. n_stream->dirreq_id = circ->dirreq_id;
  2874. n_stream->base_.purpose = EXIT_PURPOSE_CONNECT;
  2875. n_stream->begincell_flags = bcell.flags;
  2876. n_stream->stream_id = rh.stream_id;
  2877. n_stream->base_.port = port;
  2878. /* leave n_stream->s at -1, because it's not yet valid */
  2879. n_stream->package_window = STREAMWINDOW_START;
  2880. n_stream->deliver_window = STREAMWINDOW_START;
  2881. if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED) {
  2882. origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
  2883. log_info(LD_REND,"begin is for rendezvous. configuring stream.");
  2884. n_stream->base_.address = tor_strdup("(rendezvous)");
  2885. n_stream->base_.state = EXIT_CONN_STATE_CONNECTING;
  2886. n_stream->rend_data = rend_data_dup(origin_circ->rend_data);
  2887. tor_assert(connection_edge_is_rendezvous_stream(n_stream));
  2888. assert_circuit_ok(circ);
  2889. const int r = rend_service_set_connection_addr_port(n_stream, origin_circ);
  2890. if (r < 0) {
  2891. log_info(LD_REND,"Didn't find rendezvous service (port %d)",
  2892. n_stream->base_.port);
  2893. /* Send back reason DONE because we want to make hidden service port
  2894. * scanning harder thus instead of returning that the exit policy
  2895. * didn't match, which makes it obvious that the port is closed,
  2896. * return DONE and kill the circuit. That way, a user (malicious or
  2897. * not) needs one circuit per bad port unless it matches the policy of
  2898. * the hidden service. */
  2899. relay_send_end_cell_from_edge(rh.stream_id, circ,
  2900. END_STREAM_REASON_DONE,
  2901. origin_circ->cpath->prev);
  2902. connection_free(TO_CONN(n_stream));
  2903. tor_free(address);
  2904. /* Drop the circuit here since it might be someone deliberately
  2905. * scanning the hidden service ports. Note that this mitigates port
  2906. * scanning by adding more work on the attacker side to successfully
  2907. * scan but does not fully solve it. */
  2908. if (r < -1)
  2909. return END_CIRC_AT_ORIGIN;
  2910. else
  2911. return 0;
  2912. }
  2913. assert_circuit_ok(circ);
  2914. log_debug(LD_REND,"Finished assigning addr/port");
  2915. n_stream->cpath_layer = origin_circ->cpath->prev; /* link it */
  2916. /* add it into the linked list of p_streams on this circuit */
  2917. n_stream->next_stream = origin_circ->p_streams;
  2918. n_stream->on_circuit = circ;
  2919. origin_circ->p_streams = n_stream;
  2920. assert_circuit_ok(circ);
  2921. origin_circ->rend_data->nr_streams++;
  2922. connection_exit_connect(n_stream);
  2923. /* For path bias: This circuit was used successfully */
  2924. pathbias_mark_use_success(origin_circ);
  2925. tor_free(address);
  2926. return 0;
  2927. }
  2928. tor_strlower(address);
  2929. n_stream->base_.address = address;
  2930. n_stream->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
  2931. /* default to failed, change in dns_resolve if it turns out not to fail */
  2932. if (we_are_hibernating()) {
  2933. relay_send_end_cell_from_edge(rh.stream_id, circ,
  2934. END_STREAM_REASON_HIBERNATING, NULL);
  2935. connection_free(TO_CONN(n_stream));
  2936. return 0;
  2937. }
  2938. n_stream->on_circuit = circ;
  2939. if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
  2940. tor_addr_t tmp_addr;
  2941. tor_assert(or_circ);
  2942. if (or_circ->p_chan &&
  2943. channel_get_addr_if_possible(or_circ->p_chan, &tmp_addr)) {
  2944. tor_addr_copy(&n_stream->base_.addr, &tmp_addr);
  2945. }
  2946. return connection_exit_connect_dir(n_stream);
  2947. }
  2948. log_debug(LD_EXIT,"about to start the dns_resolve().");
  2949. /* send it off to the gethostbyname farm */
  2950. switch (dns_resolve(n_stream)) {
  2951. case 1: /* resolve worked; now n_stream is attached to circ. */
  2952. assert_circuit_ok(circ);
  2953. log_debug(LD_EXIT,"about to call connection_exit_connect().");
  2954. connection_exit_connect(n_stream);
  2955. return 0;
  2956. case -1: /* resolve failed */
  2957. relay_send_end_cell_from_edge(rh.stream_id, circ,
  2958. END_STREAM_REASON_RESOLVEFAILED, NULL);
  2959. /* n_stream got freed. don't touch it. */
  2960. break;
  2961. case 0: /* resolve added to pending list */
  2962. assert_circuit_ok(circ);
  2963. break;
  2964. }
  2965. return 0;
  2966. }
  2967. /**
  2968. * Called when we receive a RELAY_COMMAND_RESOLVE cell 'cell' along the
  2969. * circuit <b>circ</b>;
  2970. * begin resolving the hostname, and (eventually) reply with a RESOLVED cell.
  2971. */
  2972. int
  2973. connection_exit_begin_resolve(cell_t *cell, or_circuit_t *circ)
  2974. {
  2975. edge_connection_t *dummy_conn;
  2976. relay_header_t rh;
  2977. assert_circuit_ok(TO_CIRCUIT(circ));
  2978. relay_header_unpack(&rh, cell->payload);
  2979. if (rh.length > RELAY_PAYLOAD_SIZE)
  2980. return -1;
  2981. /* This 'dummy_conn' only exists to remember the stream ID
  2982. * associated with the resolve request; and to make the
  2983. * implementation of dns.c more uniform. (We really only need to
  2984. * remember the circuit, the stream ID, and the hostname to be
  2985. * resolved; but if we didn't store them in a connection like this,
  2986. * the housekeeping in dns.c would get way more complicated.)
  2987. */
  2988. dummy_conn = edge_connection_new(CONN_TYPE_EXIT, AF_INET);
  2989. dummy_conn->stream_id = rh.stream_id;
  2990. dummy_conn->base_.address = tor_strndup(
  2991. (char*)cell->payload+RELAY_HEADER_SIZE,
  2992. rh.length);
  2993. dummy_conn->base_.port = 0;
  2994. dummy_conn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
  2995. dummy_conn->base_.purpose = EXIT_PURPOSE_RESOLVE;
  2996. dummy_conn->on_circuit = TO_CIRCUIT(circ);
  2997. /* send it off to the gethostbyname farm */
  2998. switch (dns_resolve(dummy_conn)) {
  2999. case -1: /* Impossible to resolve; a resolved cell was sent. */
  3000. /* Connection freed; don't touch it. */
  3001. return 0;
  3002. case 1: /* The result was cached; a resolved cell was sent. */
  3003. if (!dummy_conn->base_.marked_for_close)
  3004. connection_free(TO_CONN(dummy_conn));
  3005. return 0;
  3006. case 0: /* resolve added to pending list */
  3007. assert_circuit_ok(TO_CIRCUIT(circ));
  3008. break;
  3009. }
  3010. return 0;
  3011. }
  3012. /** Helper: Return true and set *<b>why_rejected</b> to an optional clarifying
  3013. * message message iff we do not allow connections to <b>addr</b>:<b>port</b>.
  3014. */
  3015. static int
  3016. my_exit_policy_rejects(const tor_addr_t *addr,
  3017. uint16_t port,
  3018. const char **why_rejected)
  3019. {
  3020. if (router_compare_to_my_exit_policy(addr, port)) {
  3021. *why_rejected = "";
  3022. return 1;
  3023. } else if (tor_addr_family(addr) == AF_INET6 && !get_options()->IPv6Exit) {
  3024. *why_rejected = " (IPv6 address without IPv6Exit configured)";
  3025. return 1;
  3026. }
  3027. return 0;
  3028. }
  3029. /** Connect to conn's specified addr and port. If it worked, conn
  3030. * has now been added to the connection_array.
  3031. *
  3032. * Send back a connected cell. Include the resolved IP of the destination
  3033. * address, but <em>only</em> if it's a general exit stream. (Rendezvous
  3034. * streams must not reveal what IP they connected to.)
  3035. */
  3036. void
  3037. connection_exit_connect(edge_connection_t *edge_conn)
  3038. {
  3039. const tor_addr_t *addr;
  3040. uint16_t port;
  3041. connection_t *conn = TO_CONN(edge_conn);
  3042. int socket_error = 0, result;
  3043. const char *why_failed_exit_policy = NULL;
  3044. /* Apply exit policy to non-rendezvous connections. */
  3045. if (! connection_edge_is_rendezvous_stream(edge_conn) &&
  3046. my_exit_policy_rejects(&edge_conn->base_.addr,
  3047. edge_conn->base_.port,
  3048. &why_failed_exit_policy)) {
  3049. if (BUG(!why_failed_exit_policy))
  3050. why_failed_exit_policy = "";
  3051. log_info(LD_EXIT,"%s:%d failed exit policy%s. Closing.",
  3052. escaped_safe_str_client(conn->address), conn->port,
  3053. why_failed_exit_policy);
  3054. connection_edge_end(edge_conn, END_STREAM_REASON_EXITPOLICY);
  3055. circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
  3056. connection_free(conn);
  3057. return;
  3058. }
  3059. #ifdef HAVE_SYS_UN_H
  3060. if (conn->socket_family != AF_UNIX) {
  3061. #else
  3062. {
  3063. #endif /* defined(HAVE_SYS_UN_H) */
  3064. addr = &conn->addr;
  3065. port = conn->port;
  3066. if (tor_addr_family(addr) == AF_INET6)
  3067. conn->socket_family = AF_INET6;
  3068. log_debug(LD_EXIT, "about to try connecting");
  3069. result = connection_connect(conn, conn->address,
  3070. addr, port, &socket_error);
  3071. #ifdef HAVE_SYS_UN_H
  3072. } else {
  3073. /*
  3074. * In the AF_UNIX case, we expect to have already had conn->port = 1,
  3075. * tor_addr_make_unspec(conn->addr) (cf. the way we mark in the incoming
  3076. * case in connection_handle_listener_read()), and conn->address should
  3077. * have the socket path to connect to.
  3078. */
  3079. tor_assert(conn->address && strlen(conn->address) > 0);
  3080. log_debug(LD_EXIT, "about to try connecting");
  3081. result = connection_connect_unix(conn, conn->address, &socket_error);
  3082. #endif /* defined(HAVE_SYS_UN_H) */
  3083. }
  3084. switch (result) {
  3085. case -1: {
  3086. int reason = errno_to_stream_end_reason(socket_error);
  3087. connection_edge_end(edge_conn, reason);
  3088. circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
  3089. connection_free(conn);
  3090. return;
  3091. }
  3092. case 0:
  3093. conn->state = EXIT_CONN_STATE_CONNECTING;
  3094. connection_watch_events(conn, READ_EVENT | WRITE_EVENT);
  3095. /* writable indicates finish;
  3096. * readable/error indicates broken link in windows-land. */
  3097. return;
  3098. /* case 1: fall through */
  3099. }
  3100. conn->state = EXIT_CONN_STATE_OPEN;
  3101. if (connection_get_outbuf_len(conn)) {
  3102. /* in case there are any queued data cells, from e.g. optimistic data */
  3103. connection_watch_events(conn, READ_EVENT|WRITE_EVENT);
  3104. } else {
  3105. connection_watch_events(conn, READ_EVENT);
  3106. }
  3107. /* also, deliver a 'connected' cell back through the circuit. */
  3108. if (connection_edge_is_rendezvous_stream(edge_conn)) {
  3109. /* don't send an address back! */
  3110. connection_edge_send_command(edge_conn,
  3111. RELAY_COMMAND_CONNECTED,
  3112. NULL, 0);
  3113. } else { /* normal stream */
  3114. uint8_t connected_payload[MAX_CONNECTED_CELL_PAYLOAD_LEN];
  3115. int connected_payload_len =
  3116. connected_cell_format_payload(connected_payload, &conn->addr,
  3117. edge_conn->address_ttl);
  3118. if (connected_payload_len < 0) {
  3119. connection_edge_end(edge_conn, END_STREAM_REASON_INTERNAL);
  3120. circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
  3121. connection_free(conn);
  3122. return;
  3123. }
  3124. connection_edge_send_command(edge_conn,
  3125. RELAY_COMMAND_CONNECTED,
  3126. (char*)connected_payload,
  3127. connected_payload_len);
  3128. }
  3129. }
  3130. /** Given an exit conn that should attach to us as a directory server, open a
  3131. * bridge connection with a linked connection pair, create a new directory
  3132. * conn, and join them together. Return 0 on success (or if there was an
  3133. * error we could send back an end cell for). Return -(some circuit end
  3134. * reason) if the circuit needs to be torn down. Either connects
  3135. * <b>exitconn</b>, frees it, or marks it, as appropriate.
  3136. */
  3137. static int
  3138. connection_exit_connect_dir(edge_connection_t *exitconn)
  3139. {
  3140. dir_connection_t *dirconn = NULL;
  3141. or_circuit_t *circ = TO_OR_CIRCUIT(exitconn->on_circuit);
  3142. log_info(LD_EXIT, "Opening local connection for anonymized directory exit");
  3143. exitconn->base_.state = EXIT_CONN_STATE_OPEN;
  3144. dirconn = dir_connection_new(tor_addr_family(&exitconn->base_.addr));
  3145. tor_addr_copy(&dirconn->base_.addr, &exitconn->base_.addr);
  3146. dirconn->base_.port = 0;
  3147. dirconn->base_.address = tor_strdup(exitconn->base_.address);
  3148. dirconn->base_.type = CONN_TYPE_DIR;
  3149. dirconn->base_.purpose = DIR_PURPOSE_SERVER;
  3150. dirconn->base_.state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
  3151. /* Note that the new dir conn belongs to the same tunneled request as
  3152. * the edge conn, so that we can measure download times. */
  3153. dirconn->dirreq_id = exitconn->dirreq_id;
  3154. connection_link_connections(TO_CONN(dirconn), TO_CONN(exitconn));
  3155. if (connection_add(TO_CONN(exitconn))<0) {
  3156. connection_edge_end(exitconn, END_STREAM_REASON_RESOURCELIMIT);
  3157. connection_free(TO_CONN(exitconn));
  3158. connection_free(TO_CONN(dirconn));
  3159. return 0;
  3160. }
  3161. /* link exitconn to circ, now that we know we can use it. */
  3162. exitconn->next_stream = circ->n_streams;
  3163. circ->n_streams = exitconn;
  3164. if (connection_add(TO_CONN(dirconn))<0) {
  3165. connection_edge_end(exitconn, END_STREAM_REASON_RESOURCELIMIT);
  3166. connection_close_immediate(TO_CONN(exitconn));
  3167. connection_mark_for_close(TO_CONN(exitconn));
  3168. connection_free(TO_CONN(dirconn));
  3169. return 0;
  3170. }
  3171. connection_start_reading(TO_CONN(dirconn));
  3172. connection_start_reading(TO_CONN(exitconn));
  3173. if (connection_edge_send_command(exitconn,
  3174. RELAY_COMMAND_CONNECTED, NULL, 0) < 0) {
  3175. connection_mark_for_close(TO_CONN(exitconn));
  3176. connection_mark_for_close(TO_CONN(dirconn));
  3177. return 0;
  3178. }
  3179. return 0;
  3180. }
  3181. /** Return 1 if <b>conn</b> is a rendezvous stream, or 0 if
  3182. * it is a general stream.
  3183. */
  3184. int
  3185. connection_edge_is_rendezvous_stream(edge_connection_t *conn)
  3186. {
  3187. tor_assert(conn);
  3188. if (conn->rend_data)
  3189. return 1;
  3190. return 0;
  3191. }
  3192. /** Return 1 if router <b>exit_node</b> is likely to allow stream <b>conn</b>
  3193. * to exit from it, or 0 if it probably will not allow it.
  3194. * (We might be uncertain if conn's destination address has not yet been
  3195. * resolved.)
  3196. */
  3197. int
  3198. connection_ap_can_use_exit(const entry_connection_t *conn,
  3199. const node_t *exit_node)
  3200. {
  3201. const or_options_t *options = get_options();
  3202. tor_assert(conn);
  3203. tor_assert(conn->socks_request);
  3204. tor_assert(exit_node);
  3205. /* If a particular exit node has been requested for the new connection,
  3206. * make sure the exit node of the existing circuit matches exactly.
  3207. */
  3208. if (conn->chosen_exit_name) {
  3209. const node_t *chosen_exit =
  3210. node_get_by_nickname(conn->chosen_exit_name, 1);
  3211. if (!chosen_exit || tor_memneq(chosen_exit->identity,
  3212. exit_node->identity, DIGEST_LEN)) {
  3213. /* doesn't match */
  3214. // log_debug(LD_APP,"Requested node '%s', considering node '%s'. No.",
  3215. // conn->chosen_exit_name, exit->nickname);
  3216. return 0;
  3217. }
  3218. }
  3219. if (conn->use_begindir) {
  3220. /* Internal directory fetches do not count as exiting. */
  3221. return 1;
  3222. }
  3223. if (conn->socks_request->command == SOCKS_COMMAND_CONNECT) {
  3224. tor_addr_t addr, *addrp = NULL;
  3225. addr_policy_result_t r;
  3226. if (0 == tor_addr_parse(&addr, conn->socks_request->address)) {
  3227. addrp = &addr;
  3228. } else if (!conn->entry_cfg.ipv4_traffic && conn->entry_cfg.ipv6_traffic) {
  3229. tor_addr_make_null(&addr, AF_INET6);
  3230. addrp = &addr;
  3231. } else if (conn->entry_cfg.ipv4_traffic && !conn->entry_cfg.ipv6_traffic) {
  3232. tor_addr_make_null(&addr, AF_INET);
  3233. addrp = &addr;
  3234. }
  3235. r = compare_tor_addr_to_node_policy(addrp, conn->socks_request->port,
  3236. exit_node);
  3237. if (r == ADDR_POLICY_REJECTED)
  3238. return 0; /* We know the address, and the exit policy rejects it. */
  3239. if (r == ADDR_POLICY_PROBABLY_REJECTED && !conn->chosen_exit_name)
  3240. return 0; /* We don't know the addr, but the exit policy rejects most
  3241. * addresses with this port. Since the user didn't ask for
  3242. * this node, err on the side of caution. */
  3243. } else if (SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command)) {
  3244. /* Don't send DNS requests to non-exit servers by default. */
  3245. if (!conn->chosen_exit_name && node_exit_policy_rejects_all(exit_node))
  3246. return 0;
  3247. }
  3248. if (routerset_contains_node(options->ExcludeExitNodesUnion_, exit_node)) {
  3249. /* Not a suitable exit. Refuse it. */
  3250. return 0;
  3251. }
  3252. return 1;
  3253. }
  3254. /** If address is of the form "y.onion" with a well-formed handle y:
  3255. * Put a NUL after y, lower-case it, and return ONION_HOSTNAME.
  3256. *
  3257. * If address is of the form "x.y.onion" with a well-formed handle x:
  3258. * Drop "x.", put a NUL after y, lower-case it, and return ONION_HOSTNAME.
  3259. *
  3260. * If address is of the form "y.onion" with a badly-formed handle y:
  3261. * Return BAD_HOSTNAME and log a message.
  3262. *
  3263. * If address is of the form "y.exit":
  3264. * Put a NUL after y and return EXIT_HOSTNAME.
  3265. *
  3266. * Otherwise:
  3267. * Return NORMAL_HOSTNAME and change nothing.
  3268. */
  3269. hostname_type_t
  3270. parse_extended_hostname(char *address)
  3271. {
  3272. char *s;
  3273. char *q;
  3274. char query[REND_SERVICE_ID_LEN_BASE32+1];
  3275. s = strrchr(address,'.');
  3276. if (!s)
  3277. return NORMAL_HOSTNAME; /* no dot, thus normal */
  3278. if (!strcmp(s+1,"exit")) {
  3279. *s = 0; /* NUL-terminate it */
  3280. return EXIT_HOSTNAME; /* .exit */
  3281. }
  3282. if (strcmp(s+1,"onion"))
  3283. return NORMAL_HOSTNAME; /* neither .exit nor .onion, thus normal */
  3284. /* so it is .onion */
  3285. *s = 0; /* NUL-terminate it */
  3286. /* locate a 'sub-domain' component, in order to remove it */
  3287. q = strrchr(address, '.');
  3288. if (q == address) {
  3289. goto failed; /* reject sub-domain, as DNS does */
  3290. }
  3291. q = (NULL == q) ? address : q + 1;
  3292. if (strlcpy(query, q, REND_SERVICE_ID_LEN_BASE32+1) >=
  3293. REND_SERVICE_ID_LEN_BASE32+1)
  3294. goto failed;
  3295. if (q != address) {
  3296. memmove(address, q, strlen(q) + 1 /* also get \0 */);
  3297. }
  3298. if (rend_valid_service_id(query)) {
  3299. return ONION_HOSTNAME; /* success */
  3300. }
  3301. failed:
  3302. /* otherwise, return to previous state and return 0 */
  3303. *s = '.';
  3304. log_warn(LD_APP, "Invalid onion hostname %s; rejecting",
  3305. safe_str_client(address));
  3306. return BAD_HOSTNAME;
  3307. }
  3308. /** Return true iff the (possibly NULL) <b>alen</b>-byte chunk of memory at
  3309. * <b>a</b> is equal to the (possibly NULL) <b>blen</b>-byte chunk of memory
  3310. * at <b>b</b>. */
  3311. static int
  3312. memeq_opt(const char *a, size_t alen, const char *b, size_t blen)
  3313. {
  3314. if (a == NULL) {
  3315. return (b == NULL);
  3316. } else if (b == NULL) {
  3317. return 0;
  3318. } else if (alen != blen) {
  3319. return 0;
  3320. } else {
  3321. return tor_memeq(a, b, alen);
  3322. }
  3323. }
  3324. /**
  3325. * Return true iff none of the isolation flags and fields in <b>conn</b>
  3326. * should prevent it from being attached to <b>circ</b>.
  3327. */
  3328. int
  3329. connection_edge_compatible_with_circuit(const entry_connection_t *conn,
  3330. const origin_circuit_t *circ)
  3331. {
  3332. const uint8_t iso = conn->entry_cfg.isolation_flags;
  3333. const socks_request_t *sr = conn->socks_request;
  3334. /* If circ has never been used for an isolated connection, we can
  3335. * totally use it for this one. */
  3336. if (!circ->isolation_values_set)
  3337. return 1;
  3338. /* If circ has been used for connections having more than one value
  3339. * for some field f, it will have the corresponding bit set in
  3340. * isolation_flags_mixed. If isolation_flags_mixed has any bits
  3341. * in common with iso, then conn must be isolated from at least
  3342. * one stream that has been attached to circ. */
  3343. if ((iso & circ->isolation_flags_mixed) != 0) {
  3344. /* For at least one field where conn is isolated, the circuit
  3345. * already has mixed streams. */
  3346. return 0;
  3347. }
  3348. if (! conn->original_dest_address) {
  3349. log_warn(LD_BUG, "Reached connection_edge_compatible_with_circuit without "
  3350. "having set conn->original_dest_address");
  3351. ((entry_connection_t*)conn)->original_dest_address =
  3352. tor_strdup(conn->socks_request->address);
  3353. }
  3354. if ((iso & ISO_STREAM) &&
  3355. (circ->associated_isolated_stream_global_id !=
  3356. ENTRY_TO_CONN(conn)->global_identifier))
  3357. return 0;
  3358. if ((iso & ISO_DESTPORT) && conn->socks_request->port != circ->dest_port)
  3359. return 0;
  3360. if ((iso & ISO_DESTADDR) &&
  3361. strcasecmp(conn->original_dest_address, circ->dest_address))
  3362. return 0;
  3363. if ((iso & ISO_SOCKSAUTH) &&
  3364. (! memeq_opt(sr->username, sr->usernamelen,
  3365. circ->socks_username, circ->socks_username_len) ||
  3366. ! memeq_opt(sr->password, sr->passwordlen,
  3367. circ->socks_password, circ->socks_password_len)))
  3368. return 0;
  3369. if ((iso & ISO_CLIENTPROTO) &&
  3370. (conn->socks_request->listener_type != circ->client_proto_type ||
  3371. conn->socks_request->socks_version != circ->client_proto_socksver))
  3372. return 0;
  3373. if ((iso & ISO_CLIENTADDR) &&
  3374. !tor_addr_eq(&ENTRY_TO_CONN(conn)->addr, &circ->client_addr))
  3375. return 0;
  3376. if ((iso & ISO_SESSIONGRP) &&
  3377. conn->entry_cfg.session_group != circ->session_group)
  3378. return 0;
  3379. if ((iso & ISO_NYM_EPOCH) && conn->nym_epoch != circ->nym_epoch)
  3380. return 0;
  3381. return 1;
  3382. }
  3383. /**
  3384. * If <b>dry_run</b> is false, update <b>circ</b>'s isolation flags and fields
  3385. * to reflect having had <b>conn</b> attached to it, and return 0. Otherwise,
  3386. * if <b>dry_run</b> is true, then make no changes to <b>circ</b>, and return
  3387. * a bitfield of isolation flags that we would have to set in
  3388. * isolation_flags_mixed to add <b>conn</b> to <b>circ</b>, or -1 if
  3389. * <b>circ</b> has had no streams attached to it.
  3390. */
  3391. int
  3392. connection_edge_update_circuit_isolation(const entry_connection_t *conn,
  3393. origin_circuit_t *circ,
  3394. int dry_run)
  3395. {
  3396. const socks_request_t *sr = conn->socks_request;
  3397. if (! conn->original_dest_address) {
  3398. log_warn(LD_BUG, "Reached connection_update_circuit_isolation without "
  3399. "having set conn->original_dest_address");
  3400. ((entry_connection_t*)conn)->original_dest_address =
  3401. tor_strdup(conn->socks_request->address);
  3402. }
  3403. if (!circ->isolation_values_set) {
  3404. if (dry_run)
  3405. return -1;
  3406. circ->associated_isolated_stream_global_id =
  3407. ENTRY_TO_CONN(conn)->global_identifier;
  3408. circ->dest_port = conn->socks_request->port;
  3409. circ->dest_address = tor_strdup(conn->original_dest_address);
  3410. circ->client_proto_type = conn->socks_request->listener_type;
  3411. circ->client_proto_socksver = conn->socks_request->socks_version;
  3412. tor_addr_copy(&circ->client_addr, &ENTRY_TO_CONN(conn)->addr);
  3413. circ->session_group = conn->entry_cfg.session_group;
  3414. circ->nym_epoch = conn->nym_epoch;
  3415. circ->socks_username = sr->username ?
  3416. tor_memdup(sr->username, sr->usernamelen) : NULL;
  3417. circ->socks_password = sr->password ?
  3418. tor_memdup(sr->password, sr->passwordlen) : NULL;
  3419. circ->socks_username_len = sr->usernamelen;
  3420. circ->socks_password_len = sr->passwordlen;
  3421. circ->isolation_values_set = 1;
  3422. return 0;
  3423. } else {
  3424. uint8_t mixed = 0;
  3425. if (conn->socks_request->port != circ->dest_port)
  3426. mixed |= ISO_DESTPORT;
  3427. if (strcasecmp(conn->original_dest_address, circ->dest_address))
  3428. mixed |= ISO_DESTADDR;
  3429. if (!memeq_opt(sr->username, sr->usernamelen,
  3430. circ->socks_username, circ->socks_username_len) ||
  3431. !memeq_opt(sr->password, sr->passwordlen,
  3432. circ->socks_password, circ->socks_password_len))
  3433. mixed |= ISO_SOCKSAUTH;
  3434. if ((conn->socks_request->listener_type != circ->client_proto_type ||
  3435. conn->socks_request->socks_version != circ->client_proto_socksver))
  3436. mixed |= ISO_CLIENTPROTO;
  3437. if (!tor_addr_eq(&ENTRY_TO_CONN(conn)->addr, &circ->client_addr))
  3438. mixed |= ISO_CLIENTADDR;
  3439. if (conn->entry_cfg.session_group != circ->session_group)
  3440. mixed |= ISO_SESSIONGRP;
  3441. if (conn->nym_epoch != circ->nym_epoch)
  3442. mixed |= ISO_NYM_EPOCH;
  3443. if (dry_run)
  3444. return mixed;
  3445. if ((mixed & conn->entry_cfg.isolation_flags) != 0) {
  3446. log_warn(LD_BUG, "Updating a circuit with seemingly incompatible "
  3447. "isolation flags.");
  3448. }
  3449. circ->isolation_flags_mixed |= mixed;
  3450. return 0;
  3451. }
  3452. }
  3453. /**
  3454. * Clear the isolation settings on <b>circ</b>.
  3455. *
  3456. * This only works on an open circuit that has never had a stream attached to
  3457. * it, and whose isolation settings are hypothetical. (We set hypothetical
  3458. * isolation settings on circuits as we're launching them, so that we
  3459. * know whether they can handle more streams or whether we need to launch
  3460. * even more circuits. Once the circuit is open, if it turns out that
  3461. * we no longer have any streams to attach to it, we clear the isolation flags
  3462. * and data so that other streams can have a chance.)
  3463. */
  3464. void
  3465. circuit_clear_isolation(origin_circuit_t *circ)
  3466. {
  3467. if (circ->isolation_any_streams_attached) {
  3468. log_warn(LD_BUG, "Tried to clear the isolation status of a dirty circuit");
  3469. return;
  3470. }
  3471. if (TO_CIRCUIT(circ)->state != CIRCUIT_STATE_OPEN) {
  3472. log_warn(LD_BUG, "Tried to clear the isolation status of a non-open "
  3473. "circuit");
  3474. return;
  3475. }
  3476. circ->isolation_values_set = 0;
  3477. circ->isolation_flags_mixed = 0;
  3478. circ->associated_isolated_stream_global_id = 0;
  3479. circ->client_proto_type = 0;
  3480. circ->client_proto_socksver = 0;
  3481. circ->dest_port = 0;
  3482. tor_addr_make_unspec(&circ->client_addr);
  3483. tor_free(circ->dest_address);
  3484. circ->session_group = -1;
  3485. circ->nym_epoch = 0;
  3486. if (circ->socks_username) {
  3487. memwipe(circ->socks_username, 0x11, circ->socks_username_len);
  3488. tor_free(circ->socks_username);
  3489. }
  3490. if (circ->socks_password) {
  3491. memwipe(circ->socks_password, 0x05, circ->socks_password_len);
  3492. tor_free(circ->socks_password);
  3493. }
  3494. circ->socks_username_len = circ->socks_password_len = 0;
  3495. }
  3496. /** Free all storage held in module-scoped variables for connection_edge.c */
  3497. void
  3498. connection_edge_free_all(void)
  3499. {
  3500. untried_pending_connections = 0;
  3501. smartlist_free(pending_entry_connections);
  3502. pending_entry_connections = NULL;
  3503. }