connection_edge.c 99 KB

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