connection_edge.c 96 KB

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