connection_edge.c 106 KB

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