connection_edge.c 93 KB

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