connection_edge.c 127 KB

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