connection_edge.c 113 KB

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