connection_edge.c 127 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564
  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 (strcmpend(target, ".exit")) {
  874. /* Not a .exit mapping */
  875. continue;
  876. } else if (ent->source != ADDRMAPSRC_TRACKEXIT) {
  877. /* Not a trackexit mapping. */
  878. continue;
  879. }
  880. len = strlen(target);
  881. if (len < 6)
  882. continue; /* malformed. */
  883. dot = target + len - 6; /* dot now points to just before .exit */
  884. while (dot > target && *dot != '.')
  885. dot--;
  886. if (*dot == '.') dot++;
  887. nodename = tor_strndup(dot, len-5-(dot-target));;
  888. node = node_get_by_nickname(nodename, 0);
  889. tor_free(nodename);
  890. if (!node ||
  891. (allow_nodes && !routerset_contains_node(allow_nodes, node)) ||
  892. routerset_contains_node(exclude_nodes, node) ||
  893. !hostname_in_track_host_exits(options, address)) {
  894. /* We don't know this one, or we want to be rid of it. */
  895. addressmap_ent_remove(address, ent);
  896. MAP_DEL_CURRENT(address);
  897. }
  898. } STRMAP_FOREACH_END;
  899. }
  900. /** Remove all AUTOMAP mappings from the addressmap for which the
  901. * source address no longer matches AutomapHostsSuffixes, which is
  902. * no longer allowed by AutomapHostsOnResolve, or for which the
  903. * target address is no longer in the virtual network. */
  904. void
  905. addressmap_clear_invalid_automaps(const or_options_t *options)
  906. {
  907. int clear_all = !options->AutomapHostsOnResolve;
  908. const smartlist_t *suffixes = options->AutomapHostsSuffixes;
  909. if (!addressmap)
  910. return;
  911. if (!suffixes)
  912. clear_all = 1; /* This should be impossible, but let's be sure. */
  913. STRMAP_FOREACH_MODIFY(addressmap, src_address, addressmap_entry_t *, ent) {
  914. int remove = clear_all;
  915. if (ent->source != ADDRMAPSRC_AUTOMAP)
  916. continue; /* not an automap mapping. */
  917. if (!remove) {
  918. int suffix_found = 0;
  919. SMARTLIST_FOREACH(suffixes, const char *, suffix, {
  920. if (!strcasecmpend(src_address, suffix)) {
  921. suffix_found = 1;
  922. break;
  923. }
  924. });
  925. if (!suffix_found)
  926. remove = 1;
  927. }
  928. if (!remove && ! address_is_in_virtual_range(ent->new_address))
  929. remove = 1;
  930. if (remove) {
  931. addressmap_ent_remove(src_address, ent);
  932. MAP_DEL_CURRENT(src_address);
  933. }
  934. } STRMAP_FOREACH_END;
  935. }
  936. /** Remove all entries from the addressmap that were set via the
  937. * configuration file or the command line. */
  938. void
  939. addressmap_clear_configured(void)
  940. {
  941. addressmap_get_mappings(NULL, 0, 0, 0);
  942. }
  943. /** Remove all entries from the addressmap that are set to expire, ever. */
  944. void
  945. addressmap_clear_transient(void)
  946. {
  947. addressmap_get_mappings(NULL, 2, TIME_MAX, 0);
  948. }
  949. /** Clean out entries from the addressmap cache that were
  950. * added long enough ago that they are no longer valid.
  951. */
  952. void
  953. addressmap_clean(time_t now)
  954. {
  955. addressmap_get_mappings(NULL, 2, now, 0);
  956. }
  957. /** Free all the elements in the addressmap, and free the addressmap
  958. * itself. */
  959. void
  960. addressmap_free_all(void)
  961. {
  962. strmap_free(addressmap, addressmap_ent_free);
  963. addressmap = NULL;
  964. strmap_free(virtaddress_reversemap, addressmap_virtaddress_ent_free);
  965. virtaddress_reversemap = NULL;
  966. }
  967. /** Look at address, and rewrite it until it doesn't want any
  968. * more rewrites; but don't get into an infinite loop.
  969. * Don't write more than maxlen chars into address. Return true if the
  970. * address changed; false otherwise. Set *<b>expires_out</b> to the
  971. * expiry time of the result, or to <b>time_max</b> if the result does
  972. * not expire.
  973. */
  974. int
  975. addressmap_rewrite(char *address, size_t maxlen, time_t *expires_out)
  976. {
  977. addressmap_entry_t *ent;
  978. int rewrites;
  979. char *cp;
  980. time_t expires = TIME_MAX;
  981. for (rewrites = 0; rewrites < 16; rewrites++) {
  982. ent = strmap_get(addressmap, address);
  983. if (!ent || !ent->new_address) {
  984. if (expires_out)
  985. *expires_out = expires;
  986. return (rewrites > 0); /* done, no rewrite needed */
  987. }
  988. cp = tor_strdup(escaped_safe_str_client(ent->new_address));
  989. log_info(LD_APP, "Addressmap: rewriting %s to %s",
  990. escaped_safe_str_client(address), cp);
  991. if (ent->expires > 1 && ent->expires < expires)
  992. expires = ent->expires;
  993. tor_free(cp);
  994. strlcpy(address, ent->new_address, maxlen);
  995. }
  996. log_warn(LD_CONFIG,
  997. "Loop detected: we've rewritten %s 16 times! Using it as-is.",
  998. escaped_safe_str_client(address));
  999. /* it's fine to rewrite a rewrite, but don't loop forever */
  1000. if (expires_out)
  1001. *expires_out = TIME_MAX;
  1002. return 1;
  1003. }
  1004. /** If we have a cached reverse DNS entry for the address stored in the
  1005. * <b>maxlen</b>-byte buffer <b>address</b> (typically, a dotted quad) then
  1006. * rewrite to the cached value and return 1. Otherwise return 0. Set
  1007. * *<b>expires_out</b> to the expiry time of the result, or to <b>time_max</b>
  1008. * if the result does not expire. */
  1009. static int
  1010. addressmap_rewrite_reverse(char *address, size_t maxlen, time_t *expires_out)
  1011. {
  1012. size_t len = maxlen + 16;
  1013. char *s = tor_malloc(len), *cp;
  1014. addressmap_entry_t *ent;
  1015. int r = 0;
  1016. tor_snprintf(s, len, "REVERSE[%s]", address);
  1017. ent = strmap_get(addressmap, s);
  1018. if (ent) {
  1019. cp = tor_strdup(escaped_safe_str_client(ent->new_address));
  1020. log_info(LD_APP, "Rewrote reverse lookup %s -> %s",
  1021. escaped_safe_str_client(s), cp);
  1022. tor_free(cp);
  1023. strlcpy(address, ent->new_address, maxlen);
  1024. r = 1;
  1025. }
  1026. if (expires_out)
  1027. *expires_out = (ent && ent->expires > 1) ? ent->expires : TIME_MAX;
  1028. tor_free(s);
  1029. return r;
  1030. }
  1031. /** Return 1 if <b>address</b> is already registered, else return 0. If address
  1032. * is already registered, and <b>update_expires</b> is non-zero, then update
  1033. * the expiry time on the mapping with update_expires if it is a
  1034. * mapping created by TrackHostExits. */
  1035. int
  1036. addressmap_have_mapping(const char *address, int update_expiry)
  1037. {
  1038. addressmap_entry_t *ent;
  1039. if (!(ent=strmap_get_lc(addressmap, address)))
  1040. return 0;
  1041. if (update_expiry && ent->source==ADDRMAPSRC_TRACKEXIT)
  1042. ent->expires=time(NULL) + update_expiry;
  1043. return 1;
  1044. }
  1045. /** Register a request to map <b>address</b> to <b>new_address</b>,
  1046. * which will expire on <b>expires</b> (or 0 if never expires from
  1047. * config file, 1 if never expires from controller, 2 if never expires
  1048. * (virtual address mapping) from the controller.)
  1049. *
  1050. * <b>new_address</b> should be a newly dup'ed string, which we'll use or
  1051. * free as appropriate. We will leave address alone.
  1052. *
  1053. * If <b>new_address</b> is NULL, or equal to <b>address</b>, remove
  1054. * any mappings that exist from <b>address</b>.
  1055. */
  1056. void
  1057. addressmap_register(const char *address, char *new_address, time_t expires,
  1058. addressmap_entry_source_t source)
  1059. {
  1060. addressmap_entry_t *ent;
  1061. ent = strmap_get(addressmap, address);
  1062. if (!new_address || !strcasecmp(address,new_address)) {
  1063. /* Remove the mapping, if any. */
  1064. tor_free(new_address);
  1065. if (ent) {
  1066. addressmap_ent_remove(address,ent);
  1067. strmap_remove(addressmap, address);
  1068. }
  1069. return;
  1070. }
  1071. if (!ent) { /* make a new one and register it */
  1072. ent = tor_malloc_zero(sizeof(addressmap_entry_t));
  1073. strmap_set(addressmap, address, ent);
  1074. } else if (ent->new_address) { /* we need to clean up the old mapping. */
  1075. if (expires > 1) {
  1076. log_info(LD_APP,"Temporary addressmap ('%s' to '%s') not performed, "
  1077. "since it's already mapped to '%s'",
  1078. safe_str_client(address),
  1079. safe_str_client(new_address),
  1080. safe_str_client(ent->new_address));
  1081. tor_free(new_address);
  1082. return;
  1083. }
  1084. if (address_is_in_virtual_range(ent->new_address) &&
  1085. expires != 2) {
  1086. /* XXX This isn't the perfect test; we want to avoid removing
  1087. * mappings set from the control interface _as virtual mapping */
  1088. addressmap_virtaddress_remove(address, ent);
  1089. }
  1090. tor_free(ent->new_address);
  1091. } /* else { we have an in-progress resolve with no mapping. } */
  1092. ent->new_address = new_address;
  1093. ent->expires = expires==2 ? 1 : expires;
  1094. ent->num_resolve_failures = 0;
  1095. ent->source = source;
  1096. log_info(LD_CONFIG, "Addressmap: (re)mapped '%s' to '%s'",
  1097. safe_str_client(address),
  1098. safe_str_client(ent->new_address));
  1099. control_event_address_mapped(address, ent->new_address, expires, NULL);
  1100. }
  1101. /** An attempt to resolve <b>address</b> failed at some OR.
  1102. * Increment the number of resolve failures we have on record
  1103. * for it, and then return that number.
  1104. */
  1105. int
  1106. client_dns_incr_failures(const char *address)
  1107. {
  1108. addressmap_entry_t *ent = strmap_get(addressmap, address);
  1109. if (!ent) {
  1110. ent = tor_malloc_zero(sizeof(addressmap_entry_t));
  1111. ent->expires = time(NULL) + MAX_DNS_ENTRY_AGE;
  1112. strmap_set(addressmap,address,ent);
  1113. }
  1114. if (ent->num_resolve_failures < SHORT_MAX)
  1115. ++ent->num_resolve_failures; /* don't overflow */
  1116. log_info(LD_APP, "Address %s now has %d resolve failures.",
  1117. safe_str_client(address),
  1118. ent->num_resolve_failures);
  1119. return ent->num_resolve_failures;
  1120. }
  1121. /** If <b>address</b> is in the client DNS addressmap, reset
  1122. * the number of resolve failures we have on record for it.
  1123. * This is used when we fail a stream because it won't resolve:
  1124. * otherwise future attempts on that address will only try once.
  1125. */
  1126. void
  1127. client_dns_clear_failures(const char *address)
  1128. {
  1129. addressmap_entry_t *ent = strmap_get(addressmap, address);
  1130. if (ent)
  1131. ent->num_resolve_failures = 0;
  1132. }
  1133. /** Record the fact that <b>address</b> resolved to <b>name</b>.
  1134. * We can now use this in subsequent streams via addressmap_rewrite()
  1135. * so we can more correctly choose an exit that will allow <b>address</b>.
  1136. *
  1137. * If <b>exitname</b> is defined, then append the addresses with
  1138. * ".exitname.exit" before registering the mapping.
  1139. *
  1140. * If <b>ttl</b> is nonnegative, the mapping will be valid for
  1141. * <b>ttl</b>seconds; otherwise, we use the default.
  1142. */
  1143. static void
  1144. client_dns_set_addressmap_impl(const char *address, const char *name,
  1145. const char *exitname,
  1146. int ttl)
  1147. {
  1148. /* <address>.<hex or nickname>.exit\0 or just <address>\0 */
  1149. char extendedaddress[MAX_SOCKS_ADDR_LEN+MAX_VERBOSE_NICKNAME_LEN+10];
  1150. /* 123.123.123.123.<hex or nickname>.exit\0 or just 123.123.123.123\0 */
  1151. char extendedval[INET_NTOA_BUF_LEN+MAX_VERBOSE_NICKNAME_LEN+10];
  1152. tor_assert(address);
  1153. tor_assert(name);
  1154. if (ttl<0)
  1155. ttl = DEFAULT_DNS_TTL;
  1156. else
  1157. ttl = dns_clip_ttl(ttl);
  1158. if (exitname) {
  1159. /* XXXX fails to ever get attempts to get an exit address of
  1160. * google.com.digest[=~]nickname.exit; we need a syntax for this that
  1161. * won't make strict RFC952-compliant applications (like us) barf. */
  1162. tor_snprintf(extendedaddress, sizeof(extendedaddress),
  1163. "%s.%s.exit", address, exitname);
  1164. tor_snprintf(extendedval, sizeof(extendedval),
  1165. "%s.%s.exit", name, exitname);
  1166. } else {
  1167. tor_snprintf(extendedaddress, sizeof(extendedaddress),
  1168. "%s", address);
  1169. tor_snprintf(extendedval, sizeof(extendedval),
  1170. "%s", name);
  1171. }
  1172. addressmap_register(extendedaddress, tor_strdup(extendedval),
  1173. time(NULL) + ttl, ADDRMAPSRC_DNS);
  1174. }
  1175. /** Record the fact that <b>address</b> resolved to <b>val</b>.
  1176. * We can now use this in subsequent streams via addressmap_rewrite()
  1177. * so we can more correctly choose an exit that will allow <b>address</b>.
  1178. *
  1179. * If <b>exitname</b> is defined, then append the addresses with
  1180. * ".exitname.exit" before registering the mapping.
  1181. *
  1182. * If <b>ttl</b> is nonnegative, the mapping will be valid for
  1183. * <b>ttl</b>seconds; otherwise, we use the default.
  1184. */
  1185. void
  1186. client_dns_set_addressmap(const char *address, uint32_t val,
  1187. const char *exitname,
  1188. int ttl)
  1189. {
  1190. struct in_addr in;
  1191. char valbuf[INET_NTOA_BUF_LEN];
  1192. tor_assert(address);
  1193. if (tor_inet_aton(address, &in))
  1194. return; /* If address was an IP address already, don't add a mapping. */
  1195. in.s_addr = htonl(val);
  1196. tor_inet_ntoa(&in,valbuf,sizeof(valbuf));
  1197. client_dns_set_addressmap_impl(address, valbuf, exitname, ttl);
  1198. }
  1199. /** Add a cache entry noting that <b>address</b> (ordinarily a dotted quad)
  1200. * resolved via a RESOLVE_PTR request to the hostname <b>v</b>.
  1201. *
  1202. * If <b>exitname</b> is defined, then append the addresses with
  1203. * ".exitname.exit" before registering the mapping.
  1204. *
  1205. * If <b>ttl</b> is nonnegative, the mapping will be valid for
  1206. * <b>ttl</b>seconds; otherwise, we use the default.
  1207. */
  1208. static void
  1209. client_dns_set_reverse_addressmap(const char *address, const char *v,
  1210. const char *exitname,
  1211. int ttl)
  1212. {
  1213. size_t len = strlen(address) + 16;
  1214. char *s = tor_malloc(len);
  1215. tor_snprintf(s, len, "REVERSE[%s]", address);
  1216. client_dns_set_addressmap_impl(s, v, exitname, ttl);
  1217. tor_free(s);
  1218. }
  1219. /* By default, we hand out 127.192.0.1 through 127.254.254.254.
  1220. * These addresses should map to localhost, so even if the
  1221. * application accidentally tried to connect to them directly (not
  1222. * via Tor), it wouldn't get too far astray.
  1223. *
  1224. * These options are configured by parse_virtual_addr_network().
  1225. */
  1226. /** Which network should we use for virtual IPv4 addresses? Only the first
  1227. * bits of this value are fixed. */
  1228. static uint32_t virtual_addr_network = 0x7fc00000u;
  1229. /** How many bits of <b>virtual_addr_network</b> are fixed? */
  1230. static maskbits_t virtual_addr_netmask_bits = 10;
  1231. /** What's the next virtual address we will hand out? */
  1232. static uint32_t next_virtual_addr = 0x7fc00000u;
  1233. /** Read a netmask of the form 127.192.0.0/10 from "val", and check whether
  1234. * it's a valid set of virtual addresses to hand out in response to MAPADDRESS
  1235. * requests. Return 0 on success; set *msg (if provided) to a newly allocated
  1236. * string and return -1 on failure. If validate_only is false, sets the
  1237. * actual virtual address range to the parsed value. */
  1238. int
  1239. parse_virtual_addr_network(const char *val, int validate_only,
  1240. char **msg)
  1241. {
  1242. uint32_t addr;
  1243. uint16_t port_min, port_max;
  1244. maskbits_t bits;
  1245. if (parse_addr_and_port_range(val, &addr, &bits, &port_min, &port_max)) {
  1246. if (msg) *msg = tor_strdup("Error parsing VirtualAddressNetwork");
  1247. return -1;
  1248. }
  1249. if (port_min != 1 || port_max != 65535) {
  1250. if (msg) *msg = tor_strdup("Can't specify ports on VirtualAddressNetwork");
  1251. return -1;
  1252. }
  1253. if (bits > 16) {
  1254. if (msg) *msg = tor_strdup("VirtualAddressNetwork expects a /16 "
  1255. "network or larger");
  1256. return -1;
  1257. }
  1258. if (validate_only)
  1259. return 0;
  1260. virtual_addr_network = (uint32_t)( addr & (0xfffffffful << (32-bits)) );
  1261. virtual_addr_netmask_bits = bits;
  1262. if (addr_mask_cmp_bits(next_virtual_addr, addr, bits))
  1263. next_virtual_addr = addr;
  1264. return 0;
  1265. }
  1266. /**
  1267. * Return true iff <b>addr</b> is likely to have been returned by
  1268. * client_dns_get_unused_address.
  1269. **/
  1270. static int
  1271. address_is_in_virtual_range(const char *address)
  1272. {
  1273. struct in_addr in;
  1274. tor_assert(address);
  1275. if (!strcasecmpend(address, ".virtual")) {
  1276. return 1;
  1277. } else if (tor_inet_aton(address, &in)) {
  1278. uint32_t addr = ntohl(in.s_addr);
  1279. if (!addr_mask_cmp_bits(addr, virtual_addr_network,
  1280. virtual_addr_netmask_bits))
  1281. return 1;
  1282. }
  1283. return 0;
  1284. }
  1285. /** Increment the value of next_virtual_addr; reset it to the start of the
  1286. * virtual address range if it wraps around.
  1287. */
  1288. static INLINE void
  1289. increment_virtual_addr(void)
  1290. {
  1291. ++next_virtual_addr;
  1292. if (addr_mask_cmp_bits(next_virtual_addr, virtual_addr_network,
  1293. virtual_addr_netmask_bits))
  1294. next_virtual_addr = virtual_addr_network;
  1295. }
  1296. /** Return a newly allocated string holding an address of <b>type</b>
  1297. * (one of RESOLVED_TYPE_{IPV4|HOSTNAME}) that has not yet been mapped,
  1298. * and that is very unlikely to be the address of any real host.
  1299. *
  1300. * May return NULL if we have run out of virtual addresses.
  1301. */
  1302. static char *
  1303. addressmap_get_virtual_address(int type)
  1304. {
  1305. char buf[64];
  1306. tor_assert(addressmap);
  1307. if (type == RESOLVED_TYPE_HOSTNAME) {
  1308. char rand[10];
  1309. do {
  1310. crypto_rand(rand, sizeof(rand));
  1311. base32_encode(buf,sizeof(buf),rand,sizeof(rand));
  1312. strlcat(buf, ".virtual", sizeof(buf));
  1313. } while (strmap_get(addressmap, buf));
  1314. return tor_strdup(buf);
  1315. } else if (type == RESOLVED_TYPE_IPV4) {
  1316. // This is an imperfect estimate of how many addresses are available, but
  1317. // that's ok.
  1318. struct in_addr in;
  1319. uint32_t available = 1u << (32-virtual_addr_netmask_bits);
  1320. while (available) {
  1321. /* Don't hand out any .0 or .255 address. */
  1322. while ((next_virtual_addr & 0xff) == 0 ||
  1323. (next_virtual_addr & 0xff) == 0xff) {
  1324. increment_virtual_addr();
  1325. if (! --available) {
  1326. log_warn(LD_CONFIG, "Ran out of virtual addresses!");
  1327. return NULL;
  1328. }
  1329. }
  1330. in.s_addr = htonl(next_virtual_addr);
  1331. tor_inet_ntoa(&in, buf, sizeof(buf));
  1332. if (!strmap_get(addressmap, buf)) {
  1333. increment_virtual_addr();
  1334. break;
  1335. }
  1336. increment_virtual_addr();
  1337. --available;
  1338. // log_info(LD_CONFIG, "%d addrs available", (int)available);
  1339. if (! available) {
  1340. log_warn(LD_CONFIG, "Ran out of virtual addresses!");
  1341. return NULL;
  1342. }
  1343. }
  1344. return tor_strdup(buf);
  1345. } else {
  1346. log_warn(LD_BUG, "Called with unsupported address type (%d)", type);
  1347. return NULL;
  1348. }
  1349. }
  1350. /** A controller has requested that we map some address of type
  1351. * <b>type</b> to the address <b>new_address</b>. Choose an address
  1352. * that is unlikely to be used, and map it, and return it in a newly
  1353. * allocated string. If another address of the same type is already
  1354. * mapped to <b>new_address</b>, try to return a copy of that address.
  1355. *
  1356. * The string in <b>new_address</b> may be freed or inserted into a map
  1357. * as appropriate. May return NULL if are out of virtual addresses.
  1358. **/
  1359. const char *
  1360. addressmap_register_virtual_address(int type, char *new_address)
  1361. {
  1362. char **addrp;
  1363. virtaddress_entry_t *vent;
  1364. int vent_needs_to_be_added = 0;
  1365. tor_assert(new_address);
  1366. tor_assert(addressmap);
  1367. tor_assert(virtaddress_reversemap);
  1368. vent = strmap_get(virtaddress_reversemap, new_address);
  1369. if (!vent) {
  1370. vent = tor_malloc_zero(sizeof(virtaddress_entry_t));
  1371. vent_needs_to_be_added = 1;
  1372. }
  1373. addrp = (type == RESOLVED_TYPE_IPV4) ?
  1374. &vent->ipv4_address : &vent->hostname_address;
  1375. if (*addrp) {
  1376. addressmap_entry_t *ent = strmap_get(addressmap, *addrp);
  1377. if (ent && ent->new_address &&
  1378. !strcasecmp(new_address, ent->new_address)) {
  1379. tor_free(new_address);
  1380. tor_assert(!vent_needs_to_be_added);
  1381. return tor_strdup(*addrp);
  1382. } else
  1383. log_warn(LD_BUG,
  1384. "Internal confusion: I thought that '%s' was mapped to by "
  1385. "'%s', but '%s' really maps to '%s'. This is a harmless bug.",
  1386. safe_str_client(new_address),
  1387. safe_str_client(*addrp),
  1388. safe_str_client(*addrp),
  1389. ent?safe_str_client(ent->new_address):"(nothing)");
  1390. }
  1391. tor_free(*addrp);
  1392. *addrp = addressmap_get_virtual_address(type);
  1393. if (!*addrp) {
  1394. tor_free(vent);
  1395. tor_free(new_address);
  1396. return NULL;
  1397. }
  1398. log_info(LD_APP, "Registering map from %s to %s", *addrp, new_address);
  1399. if (vent_needs_to_be_added)
  1400. strmap_set(virtaddress_reversemap, new_address, vent);
  1401. addressmap_register(*addrp, new_address, 2, ADDRMAPSRC_AUTOMAP);
  1402. #if 0
  1403. {
  1404. /* Try to catch possible bugs */
  1405. addressmap_entry_t *ent;
  1406. ent = strmap_get(addressmap, *addrp);
  1407. tor_assert(ent);
  1408. tor_assert(!strcasecmp(ent->new_address,new_address));
  1409. vent = strmap_get(virtaddress_reversemap, new_address);
  1410. tor_assert(vent);
  1411. tor_assert(!strcasecmp(*addrp,
  1412. (type == RESOLVED_TYPE_IPV4) ?
  1413. vent->ipv4_address : vent->hostname_address));
  1414. log_info(LD_APP, "Map from %s to %s okay.",
  1415. safe_str_client(*addrp),
  1416. safe_str_client(new_address));
  1417. }
  1418. #endif
  1419. return *addrp;
  1420. }
  1421. /** Return 1 if <b>address</b> has funny characters in it like colons. Return
  1422. * 0 if it's fine, or if we're configured to allow it anyway. <b>client</b>
  1423. * should be true if we're using this address as a client; false if we're
  1424. * using it as a server.
  1425. */
  1426. int
  1427. address_is_invalid_destination(const char *address, int client)
  1428. {
  1429. if (client) {
  1430. if (get_options()->AllowNonRFC953Hostnames)
  1431. return 0;
  1432. } else {
  1433. if (get_options()->ServerDNSAllowNonRFC953Hostnames)
  1434. return 0;
  1435. }
  1436. while (*address) {
  1437. if (TOR_ISALNUM(*address) ||
  1438. *address == '-' ||
  1439. *address == '.' ||
  1440. *address == '_') /* Underscore is not allowed, but Windows does it
  1441. * sometimes, just to thumb its nose at the IETF. */
  1442. ++address;
  1443. else
  1444. return 1;
  1445. }
  1446. return 0;
  1447. }
  1448. /** Iterate over all address mappings which have expiry times between
  1449. * min_expires and max_expires, inclusive. If sl is provided, add an
  1450. * "old-addr new-addr expiry" string to sl for each mapping, omitting
  1451. * the expiry time if want_expiry is false. If sl is NULL, remove the
  1452. * mappings.
  1453. */
  1454. void
  1455. addressmap_get_mappings(smartlist_t *sl, time_t min_expires,
  1456. time_t max_expires, int want_expiry)
  1457. {
  1458. strmap_iter_t *iter;
  1459. const char *key;
  1460. void *_val;
  1461. addressmap_entry_t *val;
  1462. if (!addressmap)
  1463. addressmap_init();
  1464. for (iter = strmap_iter_init(addressmap); !strmap_iter_done(iter); ) {
  1465. strmap_iter_get(iter, &key, &_val);
  1466. val = _val;
  1467. if (val->expires >= min_expires && val->expires <= max_expires) {
  1468. if (!sl) {
  1469. iter = strmap_iter_next_rmv(addressmap,iter);
  1470. addressmap_ent_remove(key, val);
  1471. continue;
  1472. } else if (val->new_address) {
  1473. size_t len = strlen(key)+strlen(val->new_address)+ISO_TIME_LEN+5;
  1474. char *line = tor_malloc(len);
  1475. if (want_expiry) {
  1476. if (val->expires < 3 || val->expires == TIME_MAX)
  1477. tor_snprintf(line, len, "%s %s NEVER", key, val->new_address);
  1478. else {
  1479. char time[ISO_TIME_LEN+1];
  1480. format_iso_time(time, val->expires);
  1481. tor_snprintf(line, len, "%s %s \"%s\"", key, val->new_address,
  1482. time);
  1483. }
  1484. } else {
  1485. tor_snprintf(line, len, "%s %s", key, val->new_address);
  1486. }
  1487. smartlist_add(sl, line);
  1488. }
  1489. }
  1490. iter = strmap_iter_next(addressmap,iter);
  1491. }
  1492. }
  1493. /** Check if <b>conn</b> is using a dangerous port. Then warn and/or
  1494. * reject depending on our config options. */
  1495. static int
  1496. consider_plaintext_ports(entry_connection_t *conn, uint16_t port)
  1497. {
  1498. const or_options_t *options = get_options();
  1499. int reject = smartlist_string_num_isin(options->RejectPlaintextPorts, port);
  1500. if (smartlist_string_num_isin(options->WarnPlaintextPorts, port)) {
  1501. log_warn(LD_APP, "Application request to port %d: this port is "
  1502. "commonly used for unencrypted protocols. Please make sure "
  1503. "you don't send anything you would mind the rest of the "
  1504. "Internet reading!%s", port, reject ? " Closing." : "");
  1505. control_event_client_status(LOG_WARN, "DANGEROUS_PORT PORT=%d RESULT=%s",
  1506. port, reject ? "REJECT" : "WARN");
  1507. }
  1508. if (reject) {
  1509. log_info(LD_APP, "Port %d listed in RejectPlaintextPorts. Closing.", port);
  1510. connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
  1511. return -1;
  1512. }
  1513. return 0;
  1514. }
  1515. /** How many times do we try connecting with an exit configured via
  1516. * TrackHostExits before concluding that it won't work any more and trying a
  1517. * different one? */
  1518. #define TRACKHOSTEXITS_RETRIES 5
  1519. /** Call connection_ap_handshake_rewrite_and_attach() unless a controller
  1520. * asked us to leave streams unattached. Return 0 in that case.
  1521. *
  1522. * See connection_ap_handshake_rewrite_and_attach()'s
  1523. * documentation for arguments and return value.
  1524. */
  1525. int
  1526. connection_ap_rewrite_and_attach_if_allowed(entry_connection_t *conn,
  1527. origin_circuit_t *circ,
  1528. crypt_path_t *cpath)
  1529. {
  1530. const or_options_t *options = get_options();
  1531. if (options->LeaveStreamsUnattached) {
  1532. ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_CONTROLLER_WAIT;
  1533. return 0;
  1534. }
  1535. return connection_ap_handshake_rewrite_and_attach(conn, circ, cpath);
  1536. }
  1537. /** Connection <b>conn</b> just finished its socks handshake, or the
  1538. * controller asked us to take care of it. If <b>circ</b> is defined,
  1539. * then that's where we'll want to attach it. Otherwise we have to
  1540. * figure it out ourselves.
  1541. *
  1542. * First, parse whether it's a .exit address, remap it, and so on. Then
  1543. * if it's for a general circuit, try to attach it to a circuit (or launch
  1544. * one as needed), else if it's for a rendezvous circuit, fetch a
  1545. * rendezvous descriptor first (or attach/launch a circuit if the
  1546. * rendezvous descriptor is already here and fresh enough).
  1547. *
  1548. * The stream will exit from the hop
  1549. * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
  1550. * <b>cpath</b> is NULL.
  1551. */
  1552. int
  1553. connection_ap_handshake_rewrite_and_attach(entry_connection_t *conn,
  1554. origin_circuit_t *circ,
  1555. crypt_path_t *cpath)
  1556. {
  1557. socks_request_t *socks = conn->socks_request;
  1558. hostname_type_t addresstype;
  1559. const or_options_t *options = get_options();
  1560. struct in_addr addr_tmp;
  1561. /* We set this to true if this is an address we should automatically
  1562. * remap to a local address in VirtualAddrNetwork */
  1563. int automap = 0;
  1564. char orig_address[MAX_SOCKS_ADDR_LEN];
  1565. time_t map_expires = TIME_MAX;
  1566. /* This will be set to true iff the address starts out as a non-.exit
  1567. address, and we remap it to one because of an entry in the addressmap. */
  1568. int remapped_to_exit = 0;
  1569. time_t now = time(NULL);
  1570. connection_t *base_conn = ENTRY_TO_CONN(conn);
  1571. tor_strlower(socks->address); /* normalize it */
  1572. strlcpy(orig_address, socks->address, sizeof(orig_address));
  1573. log_debug(LD_APP,"Client asked for %s:%d",
  1574. safe_str_client(socks->address),
  1575. socks->port);
  1576. if (! conn->original_dest_address)
  1577. conn->original_dest_address = tor_strdup(conn->socks_request->address);
  1578. if (socks->command == SOCKS_COMMAND_RESOLVE &&
  1579. !tor_inet_aton(socks->address, &addr_tmp) &&
  1580. options->AutomapHostsOnResolve && options->AutomapHostsSuffixes) {
  1581. SMARTLIST_FOREACH(options->AutomapHostsSuffixes, const char *, cp,
  1582. if (!strcasecmpend(socks->address, cp)) {
  1583. automap = 1;
  1584. break;
  1585. });
  1586. if (automap) {
  1587. const char *new_addr;
  1588. new_addr = addressmap_register_virtual_address(
  1589. RESOLVED_TYPE_IPV4, tor_strdup(socks->address));
  1590. if (! new_addr) {
  1591. log_warn(LD_APP, "Unable to automap address %s",
  1592. escaped_safe_str(socks->address));
  1593. connection_mark_unattached_ap(conn, END_STREAM_REASON_INTERNAL);
  1594. return -1;
  1595. }
  1596. log_info(LD_APP, "Automapping %s to %s",
  1597. escaped_safe_str_client(socks->address),
  1598. safe_str_client(new_addr));
  1599. strlcpy(socks->address, new_addr, sizeof(socks->address));
  1600. }
  1601. }
  1602. if (socks->command == SOCKS_COMMAND_RESOLVE_PTR) {
  1603. if (addressmap_rewrite_reverse(socks->address, sizeof(socks->address),
  1604. &map_expires)) {
  1605. char *result = tor_strdup(socks->address);
  1606. /* remember _what_ is supposed to have been resolved. */
  1607. tor_snprintf(socks->address, sizeof(socks->address), "REVERSE[%s]",
  1608. orig_address);
  1609. connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_HOSTNAME,
  1610. strlen(result), (uint8_t*)result,
  1611. -1,
  1612. map_expires);
  1613. connection_mark_unattached_ap(conn,
  1614. END_STREAM_REASON_DONE |
  1615. END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
  1616. return 0;
  1617. }
  1618. if (options->ClientDNSRejectInternalAddresses) {
  1619. /* Don't let people try to do a reverse lookup on 10.0.0.1. */
  1620. tor_addr_t addr;
  1621. int ok;
  1622. ok = tor_addr_parse_reverse_lookup_name(
  1623. &addr, socks->address, AF_UNSPEC, 1);
  1624. if (ok == 1 && tor_addr_is_internal(&addr, 0)) {
  1625. connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_ERROR,
  1626. 0, NULL, -1, TIME_MAX);
  1627. connection_mark_unattached_ap(conn,
  1628. END_STREAM_REASON_SOCKSPROTOCOL |
  1629. END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
  1630. return -1;
  1631. }
  1632. }
  1633. } else if (!automap) {
  1634. int started_without_chosen_exit = strcasecmpend(socks->address, ".exit");
  1635. /* For address map controls, remap the address. */
  1636. if (addressmap_rewrite(socks->address, sizeof(socks->address),
  1637. &map_expires)) {
  1638. control_event_stream_status(conn, STREAM_EVENT_REMAP,
  1639. REMAP_STREAM_SOURCE_CACHE);
  1640. if (started_without_chosen_exit &&
  1641. !strcasecmpend(socks->address, ".exit") &&
  1642. map_expires < TIME_MAX)
  1643. remapped_to_exit = 1;
  1644. }
  1645. }
  1646. if (!automap && address_is_in_virtual_range(socks->address)) {
  1647. /* This address was probably handed out by client_dns_get_unmapped_address,
  1648. * but the mapping was discarded for some reason. We *don't* want to send
  1649. * the address through Tor; that's likely to fail, and may leak
  1650. * information.
  1651. */
  1652. log_warn(LD_APP,"Missing mapping for virtual address '%s'. Refusing.",
  1653. safe_str_client(socks->address));
  1654. connection_mark_unattached_ap(conn, END_STREAM_REASON_INTERNAL);
  1655. return -1;
  1656. }
  1657. /* Parse the address provided by SOCKS. Modify it in-place if it
  1658. * specifies a hidden-service (.onion) or particular exit node (.exit).
  1659. */
  1660. addresstype = parse_extended_hostname(socks->address,
  1661. remapped_to_exit || options->AllowDotExit);
  1662. if (addresstype == BAD_HOSTNAME) {
  1663. log_warn(LD_APP, "Invalid onion hostname %s; rejecting",
  1664. safe_str_client(socks->address));
  1665. control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
  1666. escaped(socks->address));
  1667. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1668. return -1;
  1669. }
  1670. if (addresstype == EXIT_HOSTNAME) {
  1671. /* foo.exit -- modify conn->chosen_exit_node to specify the exit
  1672. * node, and conn->address to hold only the address portion. */
  1673. char *s = strrchr(socks->address,'.');
  1674. /* If StrictNodes is not set, then .exit overrides ExcludeNodes. */
  1675. routerset_t *excludeset = options->StrictNodes ?
  1676. options->_ExcludeExitNodesUnion : options->ExcludeExitNodes;
  1677. const node_t *node;
  1678. tor_assert(!automap);
  1679. if (s) {
  1680. /* The address was of the form "(stuff).(name).exit */
  1681. if (s[1] != '\0') {
  1682. conn->chosen_exit_name = tor_strdup(s+1);
  1683. node = node_get_by_nickname(conn->chosen_exit_name, 1);
  1684. if (remapped_to_exit) /* 5 tries before it expires the addressmap */
  1685. conn->chosen_exit_retries = TRACKHOSTEXITS_RETRIES;
  1686. *s = 0;
  1687. } else {
  1688. /* Oops, the address was (stuff)..exit. That's not okay. */
  1689. log_warn(LD_APP,"Malformed exit address '%s.exit'. Refusing.",
  1690. safe_str_client(socks->address));
  1691. control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
  1692. escaped(socks->address));
  1693. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1694. return -1;
  1695. }
  1696. } else {
  1697. /* It looks like they just asked for "foo.exit". */
  1698. conn->chosen_exit_name = tor_strdup(socks->address);
  1699. node = node_get_by_nickname(conn->chosen_exit_name, 1);
  1700. if (node) {
  1701. *socks->address = 0;
  1702. node_get_address_string(node, socks->address, sizeof(socks->address));
  1703. }
  1704. }
  1705. /* Now make sure that the chosen exit exists... */
  1706. if (!node) {
  1707. log_warn(LD_APP,
  1708. "Unrecognized relay in exit address '%s.exit'. Refusing.",
  1709. safe_str_client(socks->address));
  1710. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1711. return -1;
  1712. }
  1713. /* ...and make sure that it isn't excluded. */
  1714. if (routerset_contains_node(excludeset, node)) {
  1715. log_warn(LD_APP,
  1716. "Excluded relay in exit address '%s.exit'. Refusing.",
  1717. safe_str_client(socks->address));
  1718. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1719. return -1;
  1720. }
  1721. /* XXXX022-1090 Should we also allow foo.bar.exit if ExitNodes is set and
  1722. Bar is not listed in it? I say yes, but our revised manpage branch
  1723. implies no. */
  1724. }
  1725. if (addresstype != ONION_HOSTNAME) {
  1726. /* not a hidden-service request (i.e. normal or .exit) */
  1727. if (address_is_invalid_destination(socks->address, 1)) {
  1728. control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
  1729. escaped(socks->address));
  1730. log_warn(LD_APP,
  1731. "Destination '%s' seems to be an invalid hostname. Failing.",
  1732. safe_str_client(socks->address));
  1733. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1734. return -1;
  1735. }
  1736. if (socks->command == SOCKS_COMMAND_RESOLVE) {
  1737. uint32_t answer;
  1738. struct in_addr in;
  1739. /* Reply to resolves immediately if we can. */
  1740. if (tor_inet_aton(socks->address, &in)) { /* see if it's an IP already */
  1741. /* leave it in network order */
  1742. answer = in.s_addr;
  1743. /* remember _what_ is supposed to have been resolved. */
  1744. strlcpy(socks->address, orig_address, sizeof(socks->address));
  1745. connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_IPV4,4,
  1746. (uint8_t*)&answer,
  1747. -1,map_expires);
  1748. connection_mark_unattached_ap(conn,
  1749. END_STREAM_REASON_DONE |
  1750. END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
  1751. return 0;
  1752. }
  1753. tor_assert(!automap);
  1754. rep_hist_note_used_resolve(now); /* help predict this next time */
  1755. } else if (socks->command == SOCKS_COMMAND_CONNECT) {
  1756. tor_assert(!automap);
  1757. if (socks->port == 0) {
  1758. log_notice(LD_APP,"Application asked to connect to port 0. Refusing.");
  1759. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1760. return -1;
  1761. }
  1762. if (options->ClientRejectInternalAddresses &&
  1763. !conn->use_begindir && !conn->chosen_exit_name && !circ) {
  1764. tor_addr_t addr;
  1765. if (tor_addr_parse(&addr, socks->address) >= 0 &&
  1766. tor_addr_is_internal(&addr, 0)) {
  1767. /* If this is an explicit private address with no chosen exit node,
  1768. * then we really don't want to try to connect to it. That's
  1769. * probably an error. */
  1770. if (conn->is_transparent_ap) {
  1771. log_warn(LD_NET,
  1772. "Rejecting request for anonymous connection to private "
  1773. "address %s on a TransPort or NATDPort. Possible loop "
  1774. "in your NAT rules?", safe_str_client(socks->address));
  1775. } else {
  1776. log_warn(LD_NET,
  1777. "Rejecting SOCKS request for anonymous connection to "
  1778. "private address %s", safe_str_client(socks->address));
  1779. }
  1780. connection_mark_unattached_ap(conn, END_STREAM_REASON_PRIVATE_ADDR);
  1781. return -1;
  1782. }
  1783. }
  1784. if (!conn->use_begindir && !conn->chosen_exit_name && !circ) {
  1785. /* see if we can find a suitable enclave exit */
  1786. const node_t *r =
  1787. router_find_exact_exit_enclave(socks->address, socks->port);
  1788. if (r) {
  1789. log_info(LD_APP,
  1790. "Redirecting address %s to exit at enclave router %s",
  1791. safe_str_client(socks->address), node_describe(r));
  1792. /* use the hex digest, not nickname, in case there are two
  1793. routers with this nickname */
  1794. conn->chosen_exit_name =
  1795. tor_strdup(hex_str(r->identity, DIGEST_LEN));
  1796. conn->chosen_exit_optional = 1;
  1797. }
  1798. }
  1799. /* warn or reject if it's using a dangerous port */
  1800. if (!conn->use_begindir && !conn->chosen_exit_name && !circ)
  1801. if (consider_plaintext_ports(conn, socks->port) < 0)
  1802. return -1;
  1803. if (!conn->use_begindir) {
  1804. /* help predict this next time */
  1805. rep_hist_note_used_port(now, socks->port);
  1806. }
  1807. } else if (socks->command == SOCKS_COMMAND_RESOLVE_PTR) {
  1808. rep_hist_note_used_resolve(now); /* help predict this next time */
  1809. /* no extra processing needed */
  1810. } else {
  1811. tor_fragile_assert();
  1812. }
  1813. base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  1814. if ((circ && connection_ap_handshake_attach_chosen_circuit(
  1815. conn, circ, cpath) < 0) ||
  1816. (!circ &&
  1817. connection_ap_handshake_attach_circuit(conn) < 0)) {
  1818. if (!base_conn->marked_for_close)
  1819. connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
  1820. return -1;
  1821. }
  1822. return 0;
  1823. } else {
  1824. /* it's a hidden-service request */
  1825. rend_cache_entry_t *entry;
  1826. int r;
  1827. rend_service_authorization_t *client_auth;
  1828. rend_data_t *rend_data;
  1829. tor_assert(!automap);
  1830. if (SOCKS_COMMAND_IS_RESOLVE(socks->command)) {
  1831. /* if it's a resolve request, fail it right now, rather than
  1832. * building all the circuits and then realizing it won't work. */
  1833. log_warn(LD_APP,
  1834. "Resolve requests to hidden services not allowed. Failing.");
  1835. connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_ERROR,
  1836. 0,NULL,-1,TIME_MAX);
  1837. connection_mark_unattached_ap(conn,
  1838. END_STREAM_REASON_SOCKSPROTOCOL |
  1839. END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
  1840. return -1;
  1841. }
  1842. if (circ) {
  1843. log_warn(LD_CONTROL, "Attachstream to a circuit is not "
  1844. "supported for .onion addresses currently. Failing.");
  1845. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1846. return -1;
  1847. }
  1848. ENTRY_TO_EDGE_CONN(conn)->rend_data = rend_data =
  1849. tor_malloc_zero(sizeof(rend_data_t));
  1850. strlcpy(rend_data->onion_address, socks->address,
  1851. sizeof(rend_data->onion_address));
  1852. log_info(LD_REND,"Got a hidden service request for ID '%s'",
  1853. safe_str_client(rend_data->onion_address));
  1854. /* see if we already have it cached */
  1855. r = rend_cache_lookup_entry(rend_data->onion_address, -1, &entry);
  1856. if (r<0) {
  1857. log_warn(LD_BUG,"Invalid service name '%s'",
  1858. safe_str_client(rend_data->onion_address));
  1859. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1860. return -1;
  1861. }
  1862. /* Help predict this next time. We're not sure if it will need
  1863. * a stable circuit yet, but we know we'll need *something*. */
  1864. rep_hist_note_used_internal(now, 0, 1);
  1865. /* Look up if we have client authorization for it. */
  1866. client_auth = rend_client_lookup_service_authorization(
  1867. rend_data->onion_address);
  1868. if (client_auth) {
  1869. log_info(LD_REND, "Using previously configured client authorization "
  1870. "for hidden service request.");
  1871. memcpy(rend_data->descriptor_cookie,
  1872. client_auth->descriptor_cookie, REND_DESC_COOKIE_LEN);
  1873. rend_data->auth_type = client_auth->auth_type;
  1874. }
  1875. if (r==0) {
  1876. base_conn->state = AP_CONN_STATE_RENDDESC_WAIT;
  1877. log_info(LD_REND, "Unknown descriptor %s. Fetching.",
  1878. safe_str_client(rend_data->onion_address));
  1879. rend_client_refetch_v2_renddesc(rend_data);
  1880. } else { /* r > 0 */
  1881. base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  1882. log_info(LD_REND, "Descriptor is here. Great.");
  1883. if (connection_ap_handshake_attach_circuit(conn) < 0) {
  1884. if (!base_conn->marked_for_close)
  1885. connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
  1886. return -1;
  1887. }
  1888. }
  1889. return 0;
  1890. }
  1891. return 0; /* unreached but keeps the compiler happy */
  1892. }
  1893. #ifdef TRANS_PF
  1894. static int pf_socket = -1;
  1895. int
  1896. get_pf_socket(void)
  1897. {
  1898. int pf;
  1899. /* This should be opened before dropping privileges. */
  1900. if (pf_socket >= 0)
  1901. return pf_socket;
  1902. #ifdef OPENBSD
  1903. /* only works on OpenBSD */
  1904. pf = tor_open_cloexec("/dev/pf", O_RDONLY, 0);
  1905. #else
  1906. /* works on NetBSD and FreeBSD */
  1907. pf = tor_open_cloexec("/dev/pf", O_RDWR, 0);
  1908. #endif
  1909. if (pf < 0) {
  1910. log_warn(LD_NET, "open(\"/dev/pf\") failed: %s", strerror(errno));
  1911. return -1;
  1912. }
  1913. pf_socket = pf;
  1914. return pf_socket;
  1915. }
  1916. #endif
  1917. /** Fetch the original destination address and port from a
  1918. * system-specific interface and put them into a
  1919. * socks_request_t as if they came from a socks request.
  1920. *
  1921. * Return -1 if an error prevents fetching the destination,
  1922. * else return 0.
  1923. */
  1924. static int
  1925. connection_ap_get_original_destination(entry_connection_t *conn,
  1926. socks_request_t *req)
  1927. {
  1928. #ifdef TRANS_NETFILTER
  1929. /* Linux 2.4+ */
  1930. struct sockaddr_storage orig_dst;
  1931. socklen_t orig_dst_len = sizeof(orig_dst);
  1932. tor_addr_t addr;
  1933. if (getsockopt(ENTRY_TO_CONN(conn)->s, SOL_IP, SO_ORIGINAL_DST,
  1934. (struct sockaddr*)&orig_dst, &orig_dst_len) < 0) {
  1935. int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
  1936. log_warn(LD_NET, "getsockopt() failed: %s", tor_socket_strerror(e));
  1937. return -1;
  1938. }
  1939. tor_addr_from_sockaddr(&addr, (struct sockaddr*)&orig_dst, &req->port);
  1940. tor_addr_to_str(req->address, &addr, sizeof(req->address), 0);
  1941. return 0;
  1942. #elif defined(TRANS_PF)
  1943. struct sockaddr_storage proxy_addr;
  1944. socklen_t proxy_addr_len = sizeof(proxy_addr);
  1945. struct sockaddr *proxy_sa = (struct sockaddr*) &proxy_addr;
  1946. struct pfioc_natlook pnl;
  1947. tor_addr_t addr;
  1948. int pf = -1;
  1949. if (getsockname(ENTRY_TO_CONN(conn)->s, (struct sockaddr*)&proxy_addr,
  1950. &proxy_addr_len) < 0) {
  1951. int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
  1952. log_warn(LD_NET, "getsockname() to determine transocks destination "
  1953. "failed: %s", tor_socket_strerror(e));
  1954. return -1;
  1955. }
  1956. memset(&pnl, 0, sizeof(pnl));
  1957. pnl.proto = IPPROTO_TCP;
  1958. pnl.direction = PF_OUT;
  1959. if (proxy_sa->sa_family == AF_INET) {
  1960. struct sockaddr_in *sin = (struct sockaddr_in *)proxy_sa;
  1961. pnl.af = AF_INET;
  1962. pnl.saddr.v4.s_addr = tor_addr_to_ipv4n(&ENTRY_TO_CONN(conn)->addr);
  1963. pnl.sport = htons(ENTRY_TO_CONN(conn)->port);
  1964. pnl.daddr.v4.s_addr = sin->sin_addr.s_addr;
  1965. pnl.dport = sin->sin_port;
  1966. } else if (proxy_sa->sa_family == AF_INET6) {
  1967. struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)proxy_sa;
  1968. pnl.af = AF_INET6;
  1969. memcpy(&pnl.saddr.v6, tor_addr_to_in6(&ENTRY_TO_CONN(conn)->addr),
  1970. sizeof(struct in6_addr));
  1971. pnl.sport = htons(ENTRY_TO_CONN(conn)->port);
  1972. memcpy(&pnl.daddr.v6, &sin6->sin6_addr, sizeof(struct in6_addr));
  1973. pnl.dport = sin6->sin6_port;
  1974. } else {
  1975. log_warn(LD_NET, "getsockname() gave an unexpected address family (%d)",
  1976. (int)proxy_sa->sa_family);
  1977. return -1;
  1978. }
  1979. pf = get_pf_socket();
  1980. if (pf<0)
  1981. return -1;
  1982. if (ioctl(pf, DIOCNATLOOK, &pnl) < 0) {
  1983. log_warn(LD_NET, "ioctl(DIOCNATLOOK) failed: %s", strerror(errno));
  1984. return -1;
  1985. }
  1986. if (pnl.af == AF_INET) {
  1987. tor_addr_from_ipv4n(&addr, pnl.rdaddr.v4.s_addr);
  1988. } else if (pnl.af == AF_INET6) {
  1989. tor_addr_from_in6(&addr, &pnl.rdaddr.v6);
  1990. } else {
  1991. tor_fragile_assert();
  1992. return -1;
  1993. }
  1994. tor_addr_to_str(req->address, &addr, sizeof(req->address), 0);
  1995. req->port = ntohs(pnl.rdport);
  1996. return 0;
  1997. #else
  1998. (void)conn;
  1999. (void)req;
  2000. log_warn(LD_BUG, "Called connection_ap_get_original_destination, but no "
  2001. "transparent proxy method was configured.");
  2002. return -1;
  2003. #endif
  2004. }
  2005. /** connection_edge_process_inbuf() found a conn in state
  2006. * socks_wait. See if conn->inbuf has the right bytes to proceed with
  2007. * the socks handshake.
  2008. *
  2009. * If the handshake is complete, send it to
  2010. * connection_ap_handshake_rewrite_and_attach().
  2011. *
  2012. * Return -1 if an unexpected error with conn occurs (and mark it for close),
  2013. * else return 0.
  2014. */
  2015. static int
  2016. connection_ap_handshake_process_socks(entry_connection_t *conn)
  2017. {
  2018. socks_request_t *socks;
  2019. int sockshere;
  2020. const or_options_t *options = get_options();
  2021. int had_reply = 0;
  2022. connection_t *base_conn = ENTRY_TO_CONN(conn);
  2023. tor_assert(conn);
  2024. tor_assert(base_conn->type == CONN_TYPE_AP);
  2025. tor_assert(base_conn->state == AP_CONN_STATE_SOCKS_WAIT);
  2026. tor_assert(conn->socks_request);
  2027. socks = conn->socks_request;
  2028. log_debug(LD_APP,"entered.");
  2029. IF_HAS_BUFFEREVENT(base_conn, {
  2030. struct evbuffer *input = bufferevent_get_input(base_conn->bufev);
  2031. sockshere = fetch_from_evbuffer_socks(input, socks,
  2032. options->TestSocks, options->SafeSocks);
  2033. }) ELSE_IF_NO_BUFFEREVENT {
  2034. sockshere = fetch_from_buf_socks(base_conn->inbuf, socks,
  2035. options->TestSocks, options->SafeSocks);
  2036. };
  2037. if (socks->replylen) {
  2038. had_reply = 1;
  2039. connection_write_to_buf((const char*)socks->reply, socks->replylen,
  2040. base_conn);
  2041. socks->replylen = 0;
  2042. }
  2043. if (sockshere == 0) {
  2044. log_debug(LD_APP,"socks handshake not all here yet.");
  2045. return 0;
  2046. } else if (sockshere == -1) {
  2047. if (!had_reply) {
  2048. log_warn(LD_APP,"Fetching socks handshake failed. Closing.");
  2049. connection_ap_handshake_socks_reply(conn, NULL, 0,
  2050. END_STREAM_REASON_SOCKSPROTOCOL);
  2051. }
  2052. connection_mark_unattached_ap(conn,
  2053. END_STREAM_REASON_SOCKSPROTOCOL |
  2054. END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
  2055. return -1;
  2056. } /* else socks handshake is done, continue processing */
  2057. if (SOCKS_COMMAND_IS_CONNECT(socks->command))
  2058. control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
  2059. else
  2060. control_event_stream_status(conn, STREAM_EVENT_NEW_RESOLVE, 0);
  2061. return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
  2062. }
  2063. /** connection_init_accepted_conn() found a new trans AP conn.
  2064. * Get the original destination and send it to
  2065. * connection_ap_handshake_rewrite_and_attach().
  2066. *
  2067. * Return -1 if an unexpected error with conn (and it should be marked
  2068. * for close), else return 0.
  2069. */
  2070. int
  2071. connection_ap_process_transparent(entry_connection_t *conn)
  2072. {
  2073. socks_request_t *socks;
  2074. tor_assert(conn);
  2075. tor_assert(conn->socks_request);
  2076. socks = conn->socks_request;
  2077. /* pretend that a socks handshake completed so we don't try to
  2078. * send a socks reply down a transparent conn */
  2079. socks->command = SOCKS_COMMAND_CONNECT;
  2080. socks->has_finished = 1;
  2081. log_debug(LD_APP,"entered.");
  2082. if (connection_ap_get_original_destination(conn, socks) < 0) {
  2083. log_warn(LD_APP,"Fetching original destination failed. Closing.");
  2084. connection_mark_unattached_ap(conn,
  2085. END_STREAM_REASON_CANT_FETCH_ORIG_DEST);
  2086. return -1;
  2087. }
  2088. /* we have the original destination */
  2089. control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
  2090. return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
  2091. }
  2092. /** connection_edge_process_inbuf() found a conn in state natd_wait. See if
  2093. * conn-\>inbuf has the right bytes to proceed. See FreeBSD's libalias(3) and
  2094. * ProxyEncodeTcpStream() in src/lib/libalias/alias_proxy.c for the encoding
  2095. * form of the original destination.
  2096. *
  2097. * If the original destination is complete, send it to
  2098. * connection_ap_handshake_rewrite_and_attach().
  2099. *
  2100. * Return -1 if an unexpected error with conn (and it should be marked
  2101. * for close), else return 0.
  2102. */
  2103. static int
  2104. connection_ap_process_natd(entry_connection_t *conn)
  2105. {
  2106. char tmp_buf[36], *tbuf, *daddr;
  2107. size_t tlen = 30;
  2108. int err, port_ok;
  2109. socks_request_t *socks;
  2110. tor_assert(conn);
  2111. tor_assert(ENTRY_TO_CONN(conn)->state == AP_CONN_STATE_NATD_WAIT);
  2112. tor_assert(conn->socks_request);
  2113. socks = conn->socks_request;
  2114. log_debug(LD_APP,"entered.");
  2115. /* look for LF-terminated "[DEST ip_addr port]"
  2116. * where ip_addr is a dotted-quad and port is in string form */
  2117. err = connection_fetch_from_buf_line(ENTRY_TO_CONN(conn), tmp_buf, &tlen);
  2118. if (err == 0)
  2119. return 0;
  2120. if (err < 0) {
  2121. log_warn(LD_APP,"NATD handshake failed (DEST too long). Closing");
  2122. connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
  2123. return -1;
  2124. }
  2125. if (strcmpstart(tmp_buf, "[DEST ")) {
  2126. log_warn(LD_APP,"NATD handshake was ill-formed; closing. The client "
  2127. "said: %s",
  2128. escaped(tmp_buf));
  2129. connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
  2130. return -1;
  2131. }
  2132. daddr = tbuf = &tmp_buf[0] + 6; /* after end of "[DEST " */
  2133. if (!(tbuf = strchr(tbuf, ' '))) {
  2134. log_warn(LD_APP,"NATD handshake was ill-formed; closing. The client "
  2135. "said: %s",
  2136. escaped(tmp_buf));
  2137. connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
  2138. return -1;
  2139. }
  2140. *tbuf++ = '\0';
  2141. /* pretend that a socks handshake completed so we don't try to
  2142. * send a socks reply down a natd conn */
  2143. strlcpy(socks->address, daddr, sizeof(socks->address));
  2144. socks->port = (uint16_t)
  2145. tor_parse_long(tbuf, 10, 1, 65535, &port_ok, &daddr);
  2146. if (!port_ok) {
  2147. log_warn(LD_APP,"NATD handshake failed; port %s is ill-formed or out "
  2148. "of range.", escaped(tbuf));
  2149. connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
  2150. return -1;
  2151. }
  2152. socks->command = SOCKS_COMMAND_CONNECT;
  2153. socks->has_finished = 1;
  2154. control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
  2155. ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_CIRCUIT_WAIT;
  2156. return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
  2157. }
  2158. /** Iterate over the two bytes of stream_id until we get one that is not
  2159. * already in use; return it. Return 0 if can't get a unique stream_id.
  2160. */
  2161. static streamid_t
  2162. get_unique_stream_id_by_circ(origin_circuit_t *circ)
  2163. {
  2164. edge_connection_t *tmpconn;
  2165. streamid_t test_stream_id;
  2166. uint32_t attempts=0;
  2167. again:
  2168. test_stream_id = circ->next_stream_id++;
  2169. if (++attempts > 1<<16) {
  2170. /* Make sure we don't loop forever if all stream_id's are used. */
  2171. log_warn(LD_APP,"No unused stream IDs. Failing.");
  2172. return 0;
  2173. }
  2174. if (test_stream_id == 0)
  2175. goto again;
  2176. for (tmpconn = circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream)
  2177. if (tmpconn->stream_id == test_stream_id)
  2178. goto again;
  2179. return test_stream_id;
  2180. }
  2181. /** Return true iff <b>conn</b> is linked to a circuit and configured to use
  2182. * an exit that supports optimistic data. */
  2183. static int
  2184. connection_ap_supports_optimistic_data(const entry_connection_t *conn)
  2185. {
  2186. const edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
  2187. /* We can only send optimistic data if we're connected to an open
  2188. general circuit. */
  2189. if (edge_conn->on_circuit == NULL ||
  2190. edge_conn->on_circuit->state != CIRCUIT_STATE_OPEN ||
  2191. edge_conn->on_circuit->purpose != CIRCUIT_PURPOSE_C_GENERAL)
  2192. return 0;
  2193. return conn->may_use_optimistic_data;
  2194. }
  2195. /** Write a relay begin cell, using destaddr and destport from ap_conn's
  2196. * socks_request field, and send it down circ.
  2197. *
  2198. * If ap_conn is broken, mark it for close and return -1. Else return 0.
  2199. */
  2200. int
  2201. connection_ap_handshake_send_begin(entry_connection_t *ap_conn)
  2202. {
  2203. char payload[CELL_PAYLOAD_SIZE];
  2204. int payload_len;
  2205. int begin_type;
  2206. origin_circuit_t *circ;
  2207. edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
  2208. connection_t *base_conn = TO_CONN(edge_conn);
  2209. tor_assert(edge_conn->on_circuit);
  2210. circ = TO_ORIGIN_CIRCUIT(edge_conn->on_circuit);
  2211. tor_assert(base_conn->type == CONN_TYPE_AP);
  2212. tor_assert(base_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
  2213. tor_assert(ap_conn->socks_request);
  2214. tor_assert(SOCKS_COMMAND_IS_CONNECT(ap_conn->socks_request->command));
  2215. edge_conn->stream_id = get_unique_stream_id_by_circ(circ);
  2216. if (edge_conn->stream_id==0) {
  2217. /* XXXX023 Instead of closing this stream, we should make it get
  2218. * retried on another circuit. */
  2219. connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
  2220. /* Mark this circuit "unusable for new streams". */
  2221. /* XXXX023 this is a kludgy way to do this. */
  2222. tor_assert(circ->_base.timestamp_dirty);
  2223. circ->_base.timestamp_dirty -= get_options()->MaxCircuitDirtiness;
  2224. return -1;
  2225. }
  2226. tor_snprintf(payload,RELAY_PAYLOAD_SIZE, "%s:%d",
  2227. (circ->_base.purpose == CIRCUIT_PURPOSE_C_GENERAL) ?
  2228. ap_conn->socks_request->address : "",
  2229. ap_conn->socks_request->port);
  2230. payload_len = (int)strlen(payload)+1;
  2231. log_info(LD_APP,
  2232. "Sending relay cell %d to begin stream %d.",
  2233. (int)ap_conn->use_begindir,
  2234. edge_conn->stream_id);
  2235. begin_type = ap_conn->use_begindir ?
  2236. RELAY_COMMAND_BEGIN_DIR : RELAY_COMMAND_BEGIN;
  2237. if (begin_type == RELAY_COMMAND_BEGIN) {
  2238. tor_assert(circ->build_state->onehop_tunnel == 0);
  2239. }
  2240. if (connection_edge_send_command(edge_conn, begin_type,
  2241. begin_type == RELAY_COMMAND_BEGIN ? payload : NULL,
  2242. begin_type == RELAY_COMMAND_BEGIN ? payload_len : 0) < 0)
  2243. return -1; /* circuit is closed, don't continue */
  2244. edge_conn->package_window = STREAMWINDOW_START;
  2245. edge_conn->deliver_window = STREAMWINDOW_START;
  2246. base_conn->state = AP_CONN_STATE_CONNECT_WAIT;
  2247. log_info(LD_APP,"Address/port sent, ap socket %d, n_circ_id %d",
  2248. base_conn->s, circ->_base.n_circ_id);
  2249. control_event_stream_status(ap_conn, STREAM_EVENT_SENT_CONNECT, 0);
  2250. /* If there's queued-up data, send it now */
  2251. if ((connection_get_inbuf_len(base_conn) ||
  2252. ap_conn->sending_optimistic_data) &&
  2253. connection_ap_supports_optimistic_data(ap_conn)) {
  2254. log_info(LD_APP, "Sending up to %ld + %ld bytes of queued-up data",
  2255. (long)connection_get_inbuf_len(base_conn),
  2256. ap_conn->sending_optimistic_data ?
  2257. (long)generic_buffer_len(ap_conn->sending_optimistic_data) : 0);
  2258. if (connection_edge_package_raw_inbuf(edge_conn, 1, NULL) < 0) {
  2259. connection_mark_for_close(base_conn);
  2260. }
  2261. }
  2262. return 0;
  2263. }
  2264. /** Write a relay resolve cell, using destaddr and destport from ap_conn's
  2265. * socks_request field, and send it down circ.
  2266. *
  2267. * If ap_conn is broken, mark it for close and return -1. Else return 0.
  2268. */
  2269. int
  2270. connection_ap_handshake_send_resolve(entry_connection_t *ap_conn)
  2271. {
  2272. int payload_len, command;
  2273. const char *string_addr;
  2274. char inaddr_buf[REVERSE_LOOKUP_NAME_BUF_LEN];
  2275. origin_circuit_t *circ;
  2276. edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
  2277. connection_t *base_conn = TO_CONN(edge_conn);
  2278. tor_assert(edge_conn->on_circuit);
  2279. circ = TO_ORIGIN_CIRCUIT(edge_conn->on_circuit);
  2280. tor_assert(base_conn->type == CONN_TYPE_AP);
  2281. tor_assert(base_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
  2282. tor_assert(ap_conn->socks_request);
  2283. tor_assert(circ->_base.purpose == CIRCUIT_PURPOSE_C_GENERAL);
  2284. command = ap_conn->socks_request->command;
  2285. tor_assert(SOCKS_COMMAND_IS_RESOLVE(command));
  2286. edge_conn->stream_id = get_unique_stream_id_by_circ(circ);
  2287. if (edge_conn->stream_id==0) {
  2288. /* XXXX023 Instead of closing this stream, we should make it get
  2289. * retried on another circuit. */
  2290. connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
  2291. /* Mark this circuit "unusable for new streams". */
  2292. /* XXXX023 this is a kludgy way to do this. */
  2293. tor_assert(circ->_base.timestamp_dirty);
  2294. circ->_base.timestamp_dirty -= get_options()->MaxCircuitDirtiness;
  2295. return -1;
  2296. }
  2297. if (command == SOCKS_COMMAND_RESOLVE) {
  2298. string_addr = ap_conn->socks_request->address;
  2299. payload_len = (int)strlen(string_addr)+1;
  2300. } else {
  2301. /* command == SOCKS_COMMAND_RESOLVE_PTR */
  2302. const char *a = ap_conn->socks_request->address;
  2303. tor_addr_t addr;
  2304. int r;
  2305. /* We're doing a reverse lookup. The input could be an IP address, or
  2306. * could be an .in-addr.arpa or .ip6.arpa address */
  2307. r = tor_addr_parse_reverse_lookup_name(&addr, a, AF_INET, 1);
  2308. if (r <= 0) {
  2309. log_warn(LD_APP, "Rejecting ill-formed reverse lookup of %s",
  2310. safe_str_client(a));
  2311. connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
  2312. return -1;
  2313. }
  2314. r = tor_addr_to_reverse_lookup_name(inaddr_buf, sizeof(inaddr_buf), &addr);
  2315. if (r < 0) {
  2316. log_warn(LD_BUG, "Couldn't generate reverse lookup hostname of %s",
  2317. safe_str_client(a));
  2318. connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
  2319. return -1;
  2320. }
  2321. string_addr = inaddr_buf;
  2322. payload_len = (int)strlen(inaddr_buf)+1;
  2323. tor_assert(payload_len <= (int)sizeof(inaddr_buf));
  2324. }
  2325. log_debug(LD_APP,
  2326. "Sending relay cell to begin stream %d.", edge_conn->stream_id);
  2327. if (connection_edge_send_command(edge_conn,
  2328. RELAY_COMMAND_RESOLVE,
  2329. string_addr, payload_len) < 0)
  2330. return -1; /* circuit is closed, don't continue */
  2331. tor_free(base_conn->address); /* Maybe already set by dnsserv. */
  2332. base_conn->address = tor_strdup("(Tor_internal)");
  2333. base_conn->state = AP_CONN_STATE_RESOLVE_WAIT;
  2334. log_info(LD_APP,"Address sent for resolve, ap socket %d, n_circ_id %d",
  2335. base_conn->s, circ->_base.n_circ_id);
  2336. control_event_stream_status(ap_conn, STREAM_EVENT_NEW, 0);
  2337. control_event_stream_status(ap_conn, STREAM_EVENT_SENT_RESOLVE, 0);
  2338. return 0;
  2339. }
  2340. /** Make an AP connection_t, make a new linked connection pair, and attach
  2341. * one side to the conn, connection_add it, initialize it to circuit_wait,
  2342. * and call connection_ap_handshake_attach_circuit(conn) on it.
  2343. *
  2344. * Return the other end of the linked connection pair, or -1 if error.
  2345. * DOCDOC partner.
  2346. */
  2347. entry_connection_t *
  2348. connection_ap_make_link(connection_t *partner,
  2349. char *address, uint16_t port,
  2350. const char *digest,
  2351. int session_group, int isolation_flags,
  2352. int use_begindir, int want_onehop)
  2353. {
  2354. entry_connection_t *conn;
  2355. connection_t *base_conn;
  2356. log_info(LD_APP,"Making internal %s tunnel to %s:%d ...",
  2357. want_onehop ? "direct" : "anonymized",
  2358. safe_str_client(address), port);
  2359. conn = entry_connection_new(CONN_TYPE_AP, AF_INET);
  2360. base_conn = ENTRY_TO_CONN(conn);
  2361. base_conn->linked = 1; /* so that we can add it safely below. */
  2362. /* populate conn->socks_request */
  2363. /* leave version at zero, so the socks_reply is empty */
  2364. conn->socks_request->socks_version = 0;
  2365. conn->socks_request->has_finished = 0; /* waiting for 'connected' */
  2366. strlcpy(conn->socks_request->address, address,
  2367. sizeof(conn->socks_request->address));
  2368. conn->socks_request->port = port;
  2369. conn->socks_request->command = SOCKS_COMMAND_CONNECT;
  2370. conn->want_onehop = want_onehop;
  2371. conn->use_begindir = use_begindir;
  2372. if (use_begindir) {
  2373. conn->chosen_exit_name = tor_malloc(HEX_DIGEST_LEN+2);
  2374. conn->chosen_exit_name[0] = '$';
  2375. tor_assert(digest);
  2376. base16_encode(conn->chosen_exit_name+1,HEX_DIGEST_LEN+1,
  2377. digest, DIGEST_LEN);
  2378. }
  2379. /* Populate isolation fields. */
  2380. conn->socks_request->listener_type = CONN_TYPE_DIR_LISTENER;
  2381. conn->original_dest_address = tor_strdup(address);
  2382. conn->session_group = session_group;
  2383. conn->isolation_flags = isolation_flags;
  2384. base_conn->address = tor_strdup("(Tor_internal)");
  2385. tor_addr_make_unspec(&base_conn->addr);
  2386. base_conn->port = 0;
  2387. connection_link_connections(partner, base_conn);
  2388. if (connection_add(base_conn) < 0) { /* no space, forget it */
  2389. connection_free(base_conn);
  2390. return NULL;
  2391. }
  2392. base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  2393. control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
  2394. /* attaching to a dirty circuit is fine */
  2395. if (connection_ap_handshake_attach_circuit(conn) < 0) {
  2396. if (!base_conn->marked_for_close)
  2397. connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
  2398. return NULL;
  2399. }
  2400. log_info(LD_APP,"... application connection created and linked.");
  2401. return conn;
  2402. }
  2403. /** Notify any interested controller connections about a new hostname resolve
  2404. * or resolve error. Takes the same arguments as does
  2405. * connection_ap_handshake_socks_resolved(). */
  2406. static void
  2407. tell_controller_about_resolved_result(entry_connection_t *conn,
  2408. int answer_type,
  2409. size_t answer_len,
  2410. const char *answer,
  2411. int ttl,
  2412. time_t expires)
  2413. {
  2414. if (ttl >= 0 && (answer_type == RESOLVED_TYPE_IPV4 ||
  2415. answer_type == RESOLVED_TYPE_HOSTNAME)) {
  2416. return; /* we already told the controller. */
  2417. } else if (answer_type == RESOLVED_TYPE_IPV4 && answer_len >= 4) {
  2418. char *cp = tor_dup_ip(get_uint32(answer));
  2419. control_event_address_mapped(conn->socks_request->address,
  2420. cp, expires, NULL);
  2421. tor_free(cp);
  2422. } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
  2423. char *cp = tor_strndup(answer, answer_len);
  2424. control_event_address_mapped(conn->socks_request->address,
  2425. cp, expires, NULL);
  2426. tor_free(cp);
  2427. } else {
  2428. control_event_address_mapped(conn->socks_request->address,
  2429. "<error>",
  2430. time(NULL)+ttl,
  2431. "error=yes");
  2432. }
  2433. }
  2434. /** Send an answer to an AP connection that has requested a DNS lookup via
  2435. * SOCKS. The type should be one of RESOLVED_TYPE_(IPV4|IPV6|HOSTNAME) or -1
  2436. * for unreachable; the answer should be in the format specified in the socks
  2437. * extensions document. <b>ttl</b> is the ttl for the answer, or -1 on
  2438. * certain errors or for values that didn't come via DNS. <b>expires</b> is
  2439. * a time when the answer expires, or -1 or TIME_MAX if there's a good TTL.
  2440. **/
  2441. /* XXXX023 the use of the ttl and expires fields is nutty. Let's make this
  2442. * interface and those that use it less ugly. */
  2443. void
  2444. connection_ap_handshake_socks_resolved(entry_connection_t *conn,
  2445. int answer_type,
  2446. size_t answer_len,
  2447. const uint8_t *answer,
  2448. int ttl,
  2449. time_t expires)
  2450. {
  2451. char buf[384];
  2452. size_t replylen;
  2453. if (ttl >= 0) {
  2454. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
  2455. uint32_t a = ntohl(get_uint32(answer));
  2456. if (a)
  2457. client_dns_set_addressmap(conn->socks_request->address, a,
  2458. conn->chosen_exit_name, ttl);
  2459. } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
  2460. char *cp = tor_strndup((char*)answer, answer_len);
  2461. client_dns_set_reverse_addressmap(conn->socks_request->address,
  2462. cp,
  2463. conn->chosen_exit_name, ttl);
  2464. tor_free(cp);
  2465. }
  2466. }
  2467. if (ENTRY_TO_EDGE_CONN(conn)->is_dns_request) {
  2468. if (conn->dns_server_request) {
  2469. /* We had a request on our DNS port: answer it. */
  2470. dnsserv_resolved(conn, answer_type, answer_len, (char*)answer, ttl);
  2471. conn->socks_request->has_finished = 1;
  2472. return;
  2473. } else {
  2474. /* This must be a request from the controller. We already sent
  2475. * a mapaddress if there's a ttl. */
  2476. tell_controller_about_resolved_result(conn, answer_type, answer_len,
  2477. (char*)answer, ttl, expires);
  2478. conn->socks_request->has_finished = 1;
  2479. return;
  2480. }
  2481. /* We shouldn't need to free conn here; it gets marked by the caller. */
  2482. }
  2483. if (conn->socks_request->socks_version == 4) {
  2484. buf[0] = 0x00; /* version */
  2485. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
  2486. buf[1] = SOCKS4_GRANTED;
  2487. set_uint16(buf+2, 0);
  2488. memcpy(buf+4, answer, 4); /* address */
  2489. replylen = SOCKS4_NETWORK_LEN;
  2490. } else { /* "error" */
  2491. buf[1] = SOCKS4_REJECT;
  2492. memset(buf+2, 0, 6);
  2493. replylen = SOCKS4_NETWORK_LEN;
  2494. }
  2495. } else if (conn->socks_request->socks_version == 5) {
  2496. /* SOCKS5 */
  2497. buf[0] = 0x05; /* version */
  2498. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
  2499. buf[1] = SOCKS5_SUCCEEDED;
  2500. buf[2] = 0; /* reserved */
  2501. buf[3] = 0x01; /* IPv4 address type */
  2502. memcpy(buf+4, answer, 4); /* address */
  2503. set_uint16(buf+8, 0); /* port == 0. */
  2504. replylen = 10;
  2505. } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
  2506. buf[1] = SOCKS5_SUCCEEDED;
  2507. buf[2] = 0; /* reserved */
  2508. buf[3] = 0x04; /* IPv6 address type */
  2509. memcpy(buf+4, answer, 16); /* address */
  2510. set_uint16(buf+20, 0); /* port == 0. */
  2511. replylen = 22;
  2512. } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
  2513. buf[1] = SOCKS5_SUCCEEDED;
  2514. buf[2] = 0; /* reserved */
  2515. buf[3] = 0x03; /* Domainname address type */
  2516. buf[4] = (char)answer_len;
  2517. memcpy(buf+5, answer, answer_len); /* address */
  2518. set_uint16(buf+5+answer_len, 0); /* port == 0. */
  2519. replylen = 5+answer_len+2;
  2520. } else {
  2521. buf[1] = SOCKS5_HOST_UNREACHABLE;
  2522. memset(buf+2, 0, 8);
  2523. replylen = 10;
  2524. }
  2525. } else {
  2526. /* no socks version info; don't send anything back */
  2527. return;
  2528. }
  2529. connection_ap_handshake_socks_reply(conn, buf, replylen,
  2530. (answer_type == RESOLVED_TYPE_IPV4 ||
  2531. answer_type == RESOLVED_TYPE_IPV6 ||
  2532. answer_type == RESOLVED_TYPE_HOSTNAME) ?
  2533. 0 : END_STREAM_REASON_RESOLVEFAILED);
  2534. }
  2535. /** Send a socks reply to stream <b>conn</b>, using the appropriate
  2536. * socks version, etc, and mark <b>conn</b> as completed with SOCKS
  2537. * handshaking.
  2538. *
  2539. * If <b>reply</b> is defined, then write <b>replylen</b> bytes of it to conn
  2540. * and return, else reply based on <b>endreason</b> (one of
  2541. * END_STREAM_REASON_*). If <b>reply</b> is undefined, <b>endreason</b> can't
  2542. * be 0 or REASON_DONE. Send endreason to the controller, if appropriate.
  2543. */
  2544. void
  2545. connection_ap_handshake_socks_reply(entry_connection_t *conn, char *reply,
  2546. size_t replylen, int endreason)
  2547. {
  2548. char buf[256];
  2549. socks5_reply_status_t status =
  2550. stream_end_reason_to_socks5_response(endreason);
  2551. tor_assert(conn->socks_request); /* make sure it's an AP stream */
  2552. control_event_stream_status(conn,
  2553. status==SOCKS5_SUCCEEDED ? STREAM_EVENT_SUCCEEDED : STREAM_EVENT_FAILED,
  2554. endreason);
  2555. if (conn->socks_request->has_finished) {
  2556. log_warn(LD_BUG, "(Harmless.) duplicate calls to "
  2557. "connection_ap_handshake_socks_reply.");
  2558. return;
  2559. }
  2560. if (replylen) { /* we already have a reply in mind */
  2561. connection_write_to_buf(reply, replylen, ENTRY_TO_CONN(conn));
  2562. conn->socks_request->has_finished = 1;
  2563. return;
  2564. }
  2565. if (conn->socks_request->socks_version == 4) {
  2566. memset(buf,0,SOCKS4_NETWORK_LEN);
  2567. buf[1] = (status==SOCKS5_SUCCEEDED ? SOCKS4_GRANTED : SOCKS4_REJECT);
  2568. /* leave version, destport, destip zero */
  2569. connection_write_to_buf(buf, SOCKS4_NETWORK_LEN, ENTRY_TO_CONN(conn));
  2570. } else if (conn->socks_request->socks_version == 5) {
  2571. buf[0] = 5; /* version 5 */
  2572. buf[1] = (char)status;
  2573. buf[2] = 0;
  2574. buf[3] = 1; /* ipv4 addr */
  2575. memset(buf+4,0,6); /* Set external addr/port to 0.
  2576. The spec doesn't seem to say what to do here. -RD */
  2577. connection_write_to_buf(buf,10,ENTRY_TO_CONN(conn));
  2578. }
  2579. /* If socks_version isn't 4 or 5, don't send anything.
  2580. * This can happen in the case of AP bridges. */
  2581. conn->socks_request->has_finished = 1;
  2582. return;
  2583. }
  2584. /** A relay 'begin' or 'begin_dir' cell has arrived, and either we are
  2585. * an exit hop for the circuit, or we are the origin and it is a
  2586. * rendezvous begin.
  2587. *
  2588. * Launch a new exit connection and initialize things appropriately.
  2589. *
  2590. * If it's a rendezvous stream, call connection_exit_connect() on
  2591. * it.
  2592. *
  2593. * For general streams, call dns_resolve() on it first, and only call
  2594. * connection_exit_connect() if the dns answer is already known.
  2595. *
  2596. * Note that we don't call connection_add() on the new stream! We wait
  2597. * for connection_exit_connect() to do that.
  2598. *
  2599. * Return -(some circuit end reason) if we want to tear down <b>circ</b>.
  2600. * Else return 0.
  2601. */
  2602. int
  2603. connection_exit_begin_conn(cell_t *cell, circuit_t *circ)
  2604. {
  2605. edge_connection_t *n_stream;
  2606. relay_header_t rh;
  2607. char *address=NULL;
  2608. uint16_t port;
  2609. or_circuit_t *or_circ = NULL;
  2610. const or_options_t *options = get_options();
  2611. assert_circuit_ok(circ);
  2612. if (!CIRCUIT_IS_ORIGIN(circ))
  2613. or_circ = TO_OR_CIRCUIT(circ);
  2614. relay_header_unpack(&rh, cell->payload);
  2615. if (rh.length > RELAY_PAYLOAD_SIZE)
  2616. return -1;
  2617. /* Note: we have to use relay_send_command_from_edge here, not
  2618. * connection_edge_end or connection_edge_send_command, since those require
  2619. * that we have a stream connected to a circuit, and we don't connect to a
  2620. * circuit until we have a pending/successful resolve. */
  2621. if (!server_mode(options) &&
  2622. circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
  2623. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  2624. "Relay begin cell at non-server. Closing.");
  2625. relay_send_end_cell_from_edge(rh.stream_id, circ,
  2626. END_STREAM_REASON_EXITPOLICY, NULL);
  2627. return 0;
  2628. }
  2629. if (rh.command == RELAY_COMMAND_BEGIN) {
  2630. if (!memchr(cell->payload+RELAY_HEADER_SIZE, 0, rh.length)) {
  2631. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  2632. "Relay begin cell has no \\0. Closing.");
  2633. relay_send_end_cell_from_edge(rh.stream_id, circ,
  2634. END_STREAM_REASON_TORPROTOCOL, NULL);
  2635. return 0;
  2636. }
  2637. if (addr_port_lookup(LOG_PROTOCOL_WARN,
  2638. (char*)(cell->payload+RELAY_HEADER_SIZE),
  2639. &address,NULL,&port)<0) {
  2640. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  2641. "Unable to parse addr:port in relay begin cell. Closing.");
  2642. relay_send_end_cell_from_edge(rh.stream_id, circ,
  2643. END_STREAM_REASON_TORPROTOCOL, NULL);
  2644. return 0;
  2645. }
  2646. if (port==0) {
  2647. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  2648. "Missing port in relay begin cell. Closing.");
  2649. relay_send_end_cell_from_edge(rh.stream_id, circ,
  2650. END_STREAM_REASON_TORPROTOCOL, NULL);
  2651. tor_free(address);
  2652. return 0;
  2653. }
  2654. if (or_circ && or_circ->p_conn && !options->AllowSingleHopExits &&
  2655. (or_circ->is_first_hop ||
  2656. (!connection_or_digest_is_known_relay(
  2657. or_circ->p_conn->identity_digest) &&
  2658. should_refuse_unknown_exits(options)))) {
  2659. /* Don't let clients use us as a single-hop proxy, unless the user
  2660. * has explicitly allowed that in the config. It attracts attackers
  2661. * and users who'd be better off with, well, single-hop proxies.
  2662. */
  2663. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  2664. "Attempt by %s to open a stream %s. Closing.",
  2665. safe_str(or_circ->p_conn->_base.address),
  2666. or_circ->is_first_hop ? "on first hop of circuit" :
  2667. "from unknown relay");
  2668. relay_send_end_cell_from_edge(rh.stream_id, circ,
  2669. or_circ->is_first_hop ?
  2670. END_STREAM_REASON_TORPROTOCOL :
  2671. END_STREAM_REASON_MISC,
  2672. NULL);
  2673. tor_free(address);
  2674. return 0;
  2675. }
  2676. } else if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
  2677. if (!directory_permits_begindir_requests(options) ||
  2678. circ->purpose != CIRCUIT_PURPOSE_OR) {
  2679. relay_send_end_cell_from_edge(rh.stream_id, circ,
  2680. END_STREAM_REASON_NOTDIRECTORY, NULL);
  2681. return 0;
  2682. }
  2683. /* Make sure to get the 'real' address of the previous hop: the
  2684. * caller might want to know whether his IP address has changed, and
  2685. * we might already have corrected _base.addr[ess] for the relay's
  2686. * canonical IP address. */
  2687. if (or_circ && or_circ->p_conn)
  2688. address = tor_dup_addr(&or_circ->p_conn->real_addr);
  2689. else
  2690. address = tor_strdup("127.0.0.1");
  2691. port = 1; /* XXXX This value is never actually used anywhere, and there
  2692. * isn't "really" a connection here. But we
  2693. * need to set it to something nonzero. */
  2694. } else {
  2695. log_warn(LD_BUG, "Got an unexpected command %d", (int)rh.command);
  2696. relay_send_end_cell_from_edge(rh.stream_id, circ,
  2697. END_STREAM_REASON_INTERNAL, NULL);
  2698. return 0;
  2699. }
  2700. log_debug(LD_EXIT,"Creating new exit connection.");
  2701. n_stream = edge_connection_new(CONN_TYPE_EXIT, AF_INET);
  2702. /* Remember the tunneled request ID in the new edge connection, so that
  2703. * we can measure download times. */
  2704. TO_CONN(n_stream)->dirreq_id = circ->dirreq_id;
  2705. n_stream->_base.purpose = EXIT_PURPOSE_CONNECT;
  2706. n_stream->stream_id = rh.stream_id;
  2707. n_stream->_base.port = port;
  2708. /* leave n_stream->s at -1, because it's not yet valid */
  2709. n_stream->package_window = STREAMWINDOW_START;
  2710. n_stream->deliver_window = STREAMWINDOW_START;
  2711. if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED) {
  2712. origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
  2713. log_info(LD_REND,"begin is for rendezvous. configuring stream.");
  2714. n_stream->_base.address = tor_strdup("(rendezvous)");
  2715. n_stream->_base.state = EXIT_CONN_STATE_CONNECTING;
  2716. n_stream->rend_data = rend_data_dup(origin_circ->rend_data);
  2717. tor_assert(connection_edge_is_rendezvous_stream(n_stream));
  2718. assert_circuit_ok(circ);
  2719. if (rend_service_set_connection_addr_port(n_stream, origin_circ) < 0) {
  2720. log_info(LD_REND,"Didn't find rendezvous service (port %d)",
  2721. n_stream->_base.port);
  2722. relay_send_end_cell_from_edge(rh.stream_id, circ,
  2723. END_STREAM_REASON_EXITPOLICY,
  2724. origin_circ->cpath->prev);
  2725. connection_free(TO_CONN(n_stream));
  2726. tor_free(address);
  2727. return 0;
  2728. }
  2729. assert_circuit_ok(circ);
  2730. log_debug(LD_REND,"Finished assigning addr/port");
  2731. n_stream->cpath_layer = origin_circ->cpath->prev; /* link it */
  2732. /* add it into the linked list of p_streams on this circuit */
  2733. n_stream->next_stream = origin_circ->p_streams;
  2734. n_stream->on_circuit = circ;
  2735. origin_circ->p_streams = n_stream;
  2736. assert_circuit_ok(circ);
  2737. connection_exit_connect(n_stream);
  2738. tor_free(address);
  2739. return 0;
  2740. }
  2741. tor_strlower(address);
  2742. n_stream->_base.address = address;
  2743. n_stream->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
  2744. /* default to failed, change in dns_resolve if it turns out not to fail */
  2745. if (we_are_hibernating()) {
  2746. relay_send_end_cell_from_edge(rh.stream_id, circ,
  2747. END_STREAM_REASON_HIBERNATING, NULL);
  2748. connection_free(TO_CONN(n_stream));
  2749. return 0;
  2750. }
  2751. n_stream->on_circuit = circ;
  2752. if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
  2753. tor_assert(or_circ);
  2754. if (or_circ->p_conn && !tor_addr_is_null(&or_circ->p_conn->real_addr))
  2755. tor_addr_copy(&n_stream->_base.addr, &or_circ->p_conn->real_addr);
  2756. return connection_exit_connect_dir(n_stream);
  2757. }
  2758. log_debug(LD_EXIT,"about to start the dns_resolve().");
  2759. /* send it off to the gethostbyname farm */
  2760. switch (dns_resolve(n_stream)) {
  2761. case 1: /* resolve worked; now n_stream is attached to circ. */
  2762. assert_circuit_ok(circ);
  2763. log_debug(LD_EXIT,"about to call connection_exit_connect().");
  2764. connection_exit_connect(n_stream);
  2765. return 0;
  2766. case -1: /* resolve failed */
  2767. relay_send_end_cell_from_edge(rh.stream_id, circ,
  2768. END_STREAM_REASON_RESOLVEFAILED, NULL);
  2769. /* n_stream got freed. don't touch it. */
  2770. break;
  2771. case 0: /* resolve added to pending list */
  2772. assert_circuit_ok(circ);
  2773. break;
  2774. }
  2775. return 0;
  2776. }
  2777. /**
  2778. * Called when we receive a RELAY_COMMAND_RESOLVE cell 'cell' along the
  2779. * circuit <b>circ</b>;
  2780. * begin resolving the hostname, and (eventually) reply with a RESOLVED cell.
  2781. */
  2782. int
  2783. connection_exit_begin_resolve(cell_t *cell, or_circuit_t *circ)
  2784. {
  2785. edge_connection_t *dummy_conn;
  2786. relay_header_t rh;
  2787. assert_circuit_ok(TO_CIRCUIT(circ));
  2788. relay_header_unpack(&rh, cell->payload);
  2789. if (rh.length > RELAY_PAYLOAD_SIZE)
  2790. return -1;
  2791. /* This 'dummy_conn' only exists to remember the stream ID
  2792. * associated with the resolve request; and to make the
  2793. * implementation of dns.c more uniform. (We really only need to
  2794. * remember the circuit, the stream ID, and the hostname to be
  2795. * resolved; but if we didn't store them in a connection like this,
  2796. * the housekeeping in dns.c would get way more complicated.)
  2797. */
  2798. dummy_conn = edge_connection_new(CONN_TYPE_EXIT, AF_INET);
  2799. dummy_conn->stream_id = rh.stream_id;
  2800. dummy_conn->_base.address = tor_strndup(
  2801. (char*)cell->payload+RELAY_HEADER_SIZE,
  2802. rh.length);
  2803. dummy_conn->_base.port = 0;
  2804. dummy_conn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
  2805. dummy_conn->_base.purpose = EXIT_PURPOSE_RESOLVE;
  2806. dummy_conn->on_circuit = TO_CIRCUIT(circ);
  2807. /* send it off to the gethostbyname farm */
  2808. switch (dns_resolve(dummy_conn)) {
  2809. case -1: /* Impossible to resolve; a resolved cell was sent. */
  2810. /* Connection freed; don't touch it. */
  2811. return 0;
  2812. case 1: /* The result was cached; a resolved cell was sent. */
  2813. if (!dummy_conn->_base.marked_for_close)
  2814. connection_free(TO_CONN(dummy_conn));
  2815. return 0;
  2816. case 0: /* resolve added to pending list */
  2817. assert_circuit_ok(TO_CIRCUIT(circ));
  2818. break;
  2819. }
  2820. return 0;
  2821. }
  2822. /** Connect to conn's specified addr and port. If it worked, conn
  2823. * has now been added to the connection_array.
  2824. *
  2825. * Send back a connected cell. Include the resolved IP of the destination
  2826. * address, but <em>only</em> if it's a general exit stream. (Rendezvous
  2827. * streams must not reveal what IP they connected to.)
  2828. */
  2829. void
  2830. connection_exit_connect(edge_connection_t *edge_conn)
  2831. {
  2832. const tor_addr_t *addr;
  2833. uint16_t port;
  2834. connection_t *conn = TO_CONN(edge_conn);
  2835. int socket_error = 0;
  2836. if (!connection_edge_is_rendezvous_stream(edge_conn) &&
  2837. router_compare_to_my_exit_policy(edge_conn)) {
  2838. log_info(LD_EXIT,"%s:%d failed exit policy. Closing.",
  2839. escaped_safe_str_client(conn->address), conn->port);
  2840. connection_edge_end(edge_conn, END_STREAM_REASON_EXITPOLICY);
  2841. circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
  2842. connection_free(conn);
  2843. return;
  2844. }
  2845. addr = &conn->addr;
  2846. port = conn->port;
  2847. log_debug(LD_EXIT,"about to try connecting");
  2848. switch (connection_connect(conn, conn->address, addr, port, &socket_error)) {
  2849. case -1: {
  2850. int reason = errno_to_stream_end_reason(socket_error);
  2851. connection_edge_end(edge_conn, reason);
  2852. circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
  2853. connection_free(conn);
  2854. return;
  2855. }
  2856. case 0:
  2857. conn->state = EXIT_CONN_STATE_CONNECTING;
  2858. connection_watch_events(conn, READ_EVENT | WRITE_EVENT);
  2859. /* writable indicates finish;
  2860. * readable/error indicates broken link in windows-land. */
  2861. return;
  2862. /* case 1: fall through */
  2863. }
  2864. conn->state = EXIT_CONN_STATE_OPEN;
  2865. if (connection_get_outbuf_len(conn)) {
  2866. /* in case there are any queued data cells */
  2867. log_warn(LD_BUG,"newly connected conn had data waiting!");
  2868. // connection_start_writing(conn);
  2869. }
  2870. IF_HAS_NO_BUFFEREVENT(conn)
  2871. connection_watch_events(conn, READ_EVENT);
  2872. /* also, deliver a 'connected' cell back through the circuit. */
  2873. if (connection_edge_is_rendezvous_stream(edge_conn)) {
  2874. /* rendezvous stream */
  2875. /* don't send an address back! */
  2876. connection_edge_send_command(edge_conn,
  2877. RELAY_COMMAND_CONNECTED,
  2878. NULL, 0);
  2879. } else { /* normal stream */
  2880. char connected_payload[20];
  2881. int connected_payload_len;
  2882. if (tor_addr_family(&conn->addr) == AF_INET) {
  2883. set_uint32(connected_payload, tor_addr_to_ipv4n(&conn->addr));
  2884. connected_payload_len = 4;
  2885. } else {
  2886. memcpy(connected_payload, tor_addr_to_in6_addr8(&conn->addr), 16);
  2887. connected_payload_len = 16;
  2888. }
  2889. set_uint32(connected_payload+connected_payload_len,
  2890. htonl(dns_clip_ttl(edge_conn->address_ttl)));
  2891. connected_payload_len += 4;
  2892. connection_edge_send_command(edge_conn,
  2893. RELAY_COMMAND_CONNECTED,
  2894. connected_payload, connected_payload_len);
  2895. }
  2896. }
  2897. /** Given an exit conn that should attach to us as a directory server, open a
  2898. * bridge connection with a linked connection pair, create a new directory
  2899. * conn, and join them together. Return 0 on success (or if there was an
  2900. * error we could send back an end cell for). Return -(some circuit end
  2901. * reason) if the circuit needs to be torn down. Either connects
  2902. * <b>exitconn</b>, frees it, or marks it, as appropriate.
  2903. */
  2904. static int
  2905. connection_exit_connect_dir(edge_connection_t *exitconn)
  2906. {
  2907. dir_connection_t *dirconn = NULL;
  2908. or_circuit_t *circ = TO_OR_CIRCUIT(exitconn->on_circuit);
  2909. log_info(LD_EXIT, "Opening local connection for anonymized directory exit");
  2910. exitconn->_base.state = EXIT_CONN_STATE_OPEN;
  2911. dirconn = dir_connection_new(AF_INET);
  2912. tor_addr_copy(&dirconn->_base.addr, &exitconn->_base.addr);
  2913. dirconn->_base.port = 0;
  2914. dirconn->_base.address = tor_strdup(exitconn->_base.address);
  2915. dirconn->_base.type = CONN_TYPE_DIR;
  2916. dirconn->_base.purpose = DIR_PURPOSE_SERVER;
  2917. dirconn->_base.state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
  2918. /* Note that the new dir conn belongs to the same tunneled request as
  2919. * the edge conn, so that we can measure download times. */
  2920. TO_CONN(dirconn)->dirreq_id = TO_CONN(exitconn)->dirreq_id;
  2921. connection_link_connections(TO_CONN(dirconn), TO_CONN(exitconn));
  2922. if (connection_add(TO_CONN(exitconn))<0) {
  2923. connection_edge_end(exitconn, END_STREAM_REASON_RESOURCELIMIT);
  2924. connection_free(TO_CONN(exitconn));
  2925. connection_free(TO_CONN(dirconn));
  2926. return 0;
  2927. }
  2928. /* link exitconn to circ, now that we know we can use it. */
  2929. exitconn->next_stream = circ->n_streams;
  2930. circ->n_streams = exitconn;
  2931. if (connection_add(TO_CONN(dirconn))<0) {
  2932. connection_edge_end(exitconn, END_STREAM_REASON_RESOURCELIMIT);
  2933. connection_close_immediate(TO_CONN(exitconn));
  2934. connection_mark_for_close(TO_CONN(exitconn));
  2935. connection_free(TO_CONN(dirconn));
  2936. return 0;
  2937. }
  2938. connection_start_reading(TO_CONN(dirconn));
  2939. connection_start_reading(TO_CONN(exitconn));
  2940. if (connection_edge_send_command(exitconn,
  2941. RELAY_COMMAND_CONNECTED, NULL, 0) < 0) {
  2942. connection_mark_for_close(TO_CONN(exitconn));
  2943. connection_mark_for_close(TO_CONN(dirconn));
  2944. return 0;
  2945. }
  2946. return 0;
  2947. }
  2948. /** Return 1 if <b>conn</b> is a rendezvous stream, or 0 if
  2949. * it is a general stream.
  2950. */
  2951. int
  2952. connection_edge_is_rendezvous_stream(edge_connection_t *conn)
  2953. {
  2954. tor_assert(conn);
  2955. if (conn->rend_data)
  2956. return 1;
  2957. return 0;
  2958. }
  2959. /** Return 1 if router <b>exit</b> is likely to allow stream <b>conn</b>
  2960. * to exit from it, or 0 if it probably will not allow it.
  2961. * (We might be uncertain if conn's destination address has not yet been
  2962. * resolved.)
  2963. */
  2964. int
  2965. connection_ap_can_use_exit(const entry_connection_t *conn, const node_t *exit)
  2966. {
  2967. const or_options_t *options = get_options();
  2968. tor_assert(conn);
  2969. tor_assert(conn->socks_request);
  2970. tor_assert(exit);
  2971. /* If a particular exit node has been requested for the new connection,
  2972. * make sure the exit node of the existing circuit matches exactly.
  2973. */
  2974. if (conn->chosen_exit_name) {
  2975. const node_t *chosen_exit =
  2976. node_get_by_nickname(conn->chosen_exit_name, 1);
  2977. if (!chosen_exit || tor_memneq(chosen_exit->identity,
  2978. exit->identity, DIGEST_LEN)) {
  2979. /* doesn't match */
  2980. // log_debug(LD_APP,"Requested node '%s', considering node '%s'. No.",
  2981. // conn->chosen_exit_name, exit->nickname);
  2982. return 0;
  2983. }
  2984. }
  2985. if (conn->socks_request->command == SOCKS_COMMAND_CONNECT &&
  2986. !conn->use_begindir) {
  2987. struct in_addr in;
  2988. tor_addr_t addr, *addrp = NULL;
  2989. addr_policy_result_t r;
  2990. if (tor_inet_aton(conn->socks_request->address, &in)) {
  2991. tor_addr_from_in(&addr, &in);
  2992. addrp = &addr;
  2993. }
  2994. r = compare_tor_addr_to_node_policy(addrp, conn->socks_request->port,exit);
  2995. if (r == ADDR_POLICY_REJECTED)
  2996. return 0; /* We know the address, and the exit policy rejects it. */
  2997. if (r == ADDR_POLICY_PROBABLY_REJECTED && !conn->chosen_exit_name)
  2998. return 0; /* We don't know the addr, but the exit policy rejects most
  2999. * addresses with this port. Since the user didn't ask for
  3000. * this node, err on the side of caution. */
  3001. } else if (SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command)) {
  3002. /* Don't send DNS requests to non-exit servers by default. */
  3003. if (!conn->chosen_exit_name && node_exit_policy_rejects_all(exit))
  3004. return 0;
  3005. }
  3006. if (routerset_contains_node(options->_ExcludeExitNodesUnion, exit)) {
  3007. /* Not a suitable exit. Refuse it. */
  3008. return 0;
  3009. }
  3010. return 1;
  3011. }
  3012. /** If address is of the form "y.onion" with a well-formed handle y:
  3013. * Put a NUL after y, lower-case it, and return ONION_HOSTNAME.
  3014. *
  3015. * If address is of the form "y.exit" and <b>allowdotexit</b> is true:
  3016. * Put a NUL after y and return EXIT_HOSTNAME.
  3017. *
  3018. * Otherwise:
  3019. * Return NORMAL_HOSTNAME and change nothing.
  3020. */
  3021. hostname_type_t
  3022. parse_extended_hostname(char *address, int allowdotexit)
  3023. {
  3024. char *s;
  3025. char query[REND_SERVICE_ID_LEN_BASE32+1];
  3026. s = strrchr(address,'.');
  3027. if (!s)
  3028. return NORMAL_HOSTNAME; /* no dot, thus normal */
  3029. if (!strcmp(s+1,"exit")) {
  3030. if (allowdotexit) {
  3031. *s = 0; /* NUL-terminate it */
  3032. return EXIT_HOSTNAME; /* .exit */
  3033. } else {
  3034. log_warn(LD_APP, "The \".exit\" notation is disabled in Tor due to "
  3035. "security risks. Set AllowDotExit in your torrc to enable "
  3036. "it.");
  3037. /* FFFF send a controller event too to notify Vidalia users */
  3038. return BAD_HOSTNAME;
  3039. }
  3040. }
  3041. if (strcmp(s+1,"onion"))
  3042. return NORMAL_HOSTNAME; /* neither .exit nor .onion, thus normal */
  3043. /* so it is .onion */
  3044. *s = 0; /* NUL-terminate it */
  3045. if (strlcpy(query, address, REND_SERVICE_ID_LEN_BASE32+1) >=
  3046. REND_SERVICE_ID_LEN_BASE32+1)
  3047. goto failed;
  3048. if (rend_valid_service_id(query)) {
  3049. return ONION_HOSTNAME; /* success */
  3050. }
  3051. failed:
  3052. /* otherwise, return to previous state and return 0 */
  3053. *s = '.';
  3054. return BAD_HOSTNAME;
  3055. }
  3056. /** Return true iff the (possibly NULL) <b>alen</b>-byte chunk of memory at
  3057. * <b>a</b> is equal to the (possibly NULL) <b>blen</b>-byte chunk of memory
  3058. * at <b>b</b>. */
  3059. static int
  3060. memeq_opt(const char *a, size_t alen, const char *b, size_t blen)
  3061. {
  3062. if (a == NULL) {
  3063. return (b == NULL);
  3064. } else if (b == NULL) {
  3065. return 0;
  3066. } else if (alen != blen) {
  3067. return 0;
  3068. } else {
  3069. return tor_memeq(a, b, alen);
  3070. }
  3071. }
  3072. /**
  3073. * Return true iff none of the isolation flags and fields in <b>conn</b>
  3074. * should prevent it from being attached to <b>circ</b>.
  3075. */
  3076. int
  3077. connection_edge_compatible_with_circuit(const entry_connection_t *conn,
  3078. const origin_circuit_t *circ)
  3079. {
  3080. const uint8_t iso = conn->isolation_flags;
  3081. const socks_request_t *sr = conn->socks_request;
  3082. /* If circ has never been used for an isolated connection, we can
  3083. * totally use it for this one. */
  3084. if (!circ->isolation_values_set)
  3085. return 1;
  3086. /* If circ has been used for connections having more than one value
  3087. * for some field f, it will have the corresponding bit set in
  3088. * isolation_flags_mixed. If isolation_flags_mixed has any bits
  3089. * in common with iso, then conn must be isolated from at least
  3090. * one stream that has been attached to circ. */
  3091. if ((iso & circ->isolation_flags_mixed) != 0) {
  3092. /* For at least one field where conn is isolated, the circuit
  3093. * already has mixed streams. */
  3094. return 0;
  3095. }
  3096. if (! conn->original_dest_address) {
  3097. log_warn(LD_BUG, "Reached connection_edge_compatible_with_circuit without "
  3098. "having set conn->original_dest_address");
  3099. ((entry_connection_t*)conn)->original_dest_address =
  3100. tor_strdup(conn->socks_request->address);
  3101. }
  3102. if ((iso & ISO_STREAM) &&
  3103. (circ->associated_isolated_stream_global_id !=
  3104. ENTRY_TO_CONN(conn)->global_identifier))
  3105. return 0;
  3106. if ((iso & ISO_DESTPORT) && conn->socks_request->port != circ->dest_port)
  3107. return 0;
  3108. if ((iso & ISO_DESTADDR) &&
  3109. strcasecmp(conn->original_dest_address, circ->dest_address))
  3110. return 0;
  3111. if ((iso & ISO_SOCKSAUTH) &&
  3112. (! memeq_opt(sr->username, sr->usernamelen,
  3113. circ->socks_username, circ->socks_username_len) ||
  3114. ! memeq_opt(sr->password, sr->passwordlen,
  3115. circ->socks_password, circ->socks_password_len)))
  3116. return 0;
  3117. if ((iso & ISO_CLIENTPROTO) &&
  3118. (conn->socks_request->listener_type != circ->client_proto_type ||
  3119. conn->socks_request->socks_version != circ->client_proto_socksver))
  3120. return 0;
  3121. if ((iso & ISO_CLIENTADDR) &&
  3122. !tor_addr_eq(&ENTRY_TO_CONN(conn)->addr, &circ->client_addr))
  3123. return 0;
  3124. if ((iso & ISO_SESSIONGRP) && conn->session_group != circ->session_group)
  3125. return 0;
  3126. if ((iso & ISO_NYM_EPOCH) && conn->nym_epoch != circ->nym_epoch)
  3127. return 0;
  3128. return 1;
  3129. }
  3130. /**
  3131. * If <b>dry_run</b> is false, update <b>circ</b>'s isolation flags and fields
  3132. * to reflect having had <b>conn</b> attached to it, and return 0. Otherwise,
  3133. * if <b>dry_run</b> is true, then make no changes to <b>circ</b>, and return
  3134. * a bitfield of isolation flags that we would have to set in
  3135. * isolation_flags_mixed to add <b>conn</b> to <b>circ</b>, or -1 if
  3136. * <b>circ</b> has had no streams attached to it.
  3137. */
  3138. int
  3139. connection_edge_update_circuit_isolation(const entry_connection_t *conn,
  3140. origin_circuit_t *circ,
  3141. int dry_run)
  3142. {
  3143. const socks_request_t *sr = conn->socks_request;
  3144. if (! conn->original_dest_address) {
  3145. log_warn(LD_BUG, "Reached connection_update_circuit_isolation without "
  3146. "having set conn->original_dest_address");
  3147. ((entry_connection_t*)conn)->original_dest_address =
  3148. tor_strdup(conn->socks_request->address);
  3149. }
  3150. if (!circ->isolation_values_set) {
  3151. if (dry_run)
  3152. return -1;
  3153. circ->associated_isolated_stream_global_id =
  3154. ENTRY_TO_CONN(conn)->global_identifier;
  3155. circ->dest_port = conn->socks_request->port;
  3156. circ->dest_address = tor_strdup(conn->original_dest_address);
  3157. circ->client_proto_type = conn->socks_request->listener_type;
  3158. circ->client_proto_socksver = conn->socks_request->socks_version;
  3159. tor_addr_copy(&circ->client_addr, &ENTRY_TO_CONN(conn)->addr);
  3160. circ->session_group = conn->session_group;
  3161. circ->nym_epoch = conn->nym_epoch;
  3162. circ->socks_username = sr->username ?
  3163. tor_memdup(sr->username, sr->usernamelen) : NULL;
  3164. circ->socks_password = sr->password ?
  3165. tor_memdup(sr->password, sr->passwordlen) : NULL;
  3166. circ->socks_username_len = sr->usernamelen;
  3167. circ->socks_password_len = sr->passwordlen;
  3168. circ->isolation_values_set = 1;
  3169. return 0;
  3170. } else {
  3171. uint8_t mixed = 0;
  3172. if (conn->socks_request->port != circ->dest_port)
  3173. mixed |= ISO_DESTPORT;
  3174. if (strcasecmp(conn->original_dest_address, circ->dest_address))
  3175. mixed |= ISO_DESTADDR;
  3176. if (!memeq_opt(sr->username, sr->usernamelen,
  3177. circ->socks_username, circ->socks_username_len) ||
  3178. !memeq_opt(sr->password, sr->passwordlen,
  3179. circ->socks_password, circ->socks_password_len))
  3180. mixed |= ISO_SOCKSAUTH;
  3181. if ((conn->socks_request->listener_type != circ->client_proto_type ||
  3182. conn->socks_request->socks_version != circ->client_proto_socksver))
  3183. mixed |= ISO_CLIENTPROTO;
  3184. if (!tor_addr_eq(&ENTRY_TO_CONN(conn)->addr, &circ->client_addr))
  3185. mixed |= ISO_CLIENTADDR;
  3186. if (conn->session_group != circ->session_group)
  3187. mixed |= ISO_SESSIONGRP;
  3188. if (conn->nym_epoch != circ->nym_epoch)
  3189. mixed |= ISO_NYM_EPOCH;
  3190. if (dry_run)
  3191. return mixed;
  3192. if ((mixed & conn->isolation_flags) != 0) {
  3193. log_warn(LD_BUG, "Updating a circuit with seemingly incompatible "
  3194. "isolation flags.");
  3195. }
  3196. circ->isolation_flags_mixed |= mixed;
  3197. return 0;
  3198. }
  3199. }
  3200. /**
  3201. * Clear the isolation settings on <b>circ</b>.
  3202. *
  3203. * This only works on an open circuit that has never had a stream attached to
  3204. * it, and whose isolation settings are hypothetical. (We set hypothetical
  3205. * isolation settings on circuits as we're launching them, so that we
  3206. * know whether they can handle more streams or whether we need to launch
  3207. * even more circuits. Once the circuit is open, if it turns out that
  3208. * we no longer have any streams to attach to it, we clear the isolation flags
  3209. * and data so that other streams can have a chance.)
  3210. */
  3211. void
  3212. circuit_clear_isolation(origin_circuit_t *circ)
  3213. {
  3214. if (circ->isolation_any_streams_attached) {
  3215. log_warn(LD_BUG, "Tried to clear the isolation status of a dirty circuit");
  3216. return;
  3217. }
  3218. if (TO_CIRCUIT(circ)->state != CIRCUIT_STATE_OPEN) {
  3219. log_warn(LD_BUG, "Tried to clear the isolation status of a non-open "
  3220. "circuit");
  3221. return;
  3222. }
  3223. circ->isolation_values_set = 0;
  3224. circ->isolation_flags_mixed = 0;
  3225. circ->associated_isolated_stream_global_id = 0;
  3226. circ->client_proto_type = 0;
  3227. circ->client_proto_socksver = 0;
  3228. circ->dest_port = 0;
  3229. tor_addr_make_unspec(&circ->client_addr);
  3230. tor_free(circ->dest_address);
  3231. circ->session_group = -1;
  3232. circ->nym_epoch = 0;
  3233. if (circ->socks_username) {
  3234. memset(circ->socks_username, 0x11, circ->socks_username_len);
  3235. tor_free(circ->socks_username);
  3236. }
  3237. if (circ->socks_password) {
  3238. memset(circ->socks_password, 0x05, circ->socks_password_len);
  3239. tor_free(circ->socks_password);
  3240. }
  3241. circ->socks_username_len = circ->socks_password_len = 0;
  3242. }