connection_edge.c 94 KB

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