connection_edge.c 96 KB

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