connection_edge.c 112 KB

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