connection_edge.c 114 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118
  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-2013, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file connection_edge.c
  8. * \brief Handle edge streams.
  9. **/
  10. #define CONNECTION_EDGE_PRIVATE
  11. #include "or.h"
  12. #include "addressmap.h"
  13. #include "buffers.h"
  14. #include "channel.h"
  15. #include "circuitlist.h"
  16. #include "circuituse.h"
  17. #include "config.h"
  18. #include "connection.h"
  19. #include "connection_edge.h"
  20. #include "connection_or.h"
  21. #include "control.h"
  22. #include "dns.h"
  23. #include "dnsserv.h"
  24. #include "dirserv.h"
  25. #include "hibernate.h"
  26. #include "main.h"
  27. #include "nodelist.h"
  28. #include "policies.h"
  29. #include "reasons.h"
  30. #include "relay.h"
  31. #include "rendclient.h"
  32. #include "rendcommon.h"
  33. #include "rendservice.h"
  34. #include "rephist.h"
  35. #include "router.h"
  36. #include "routerlist.h"
  37. #include "routerset.h"
  38. #include "circuitbuild.h"
  39. #ifdef HAVE_LINUX_TYPES_H
  40. #include <linux/types.h>
  41. #endif
  42. #ifdef HAVE_LINUX_NETFILTER_IPV4_H
  43. #include <linux/netfilter_ipv4.h>
  44. #define TRANS_NETFILTER
  45. #endif
  46. #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
  47. #include <net/if.h>
  48. #include <net/pfvar.h>
  49. #define TRANS_PF
  50. #endif
  51. #define SOCKS4_GRANTED 90
  52. #define SOCKS4_REJECT 91
  53. static int connection_ap_handshake_process_socks(entry_connection_t *conn);
  54. static int connection_ap_process_natd(entry_connection_t *conn);
  55. static int connection_exit_connect_dir(edge_connection_t *exitconn);
  56. static int consider_plaintext_ports(entry_connection_t *conn, uint16_t port);
  57. static int connection_ap_supports_optimistic_data(const entry_connection_t *);
  58. static void connection_ap_handshake_socks_resolved_addr(
  59. entry_connection_t *conn,
  60. const tor_addr_t *answer,
  61. int ttl,
  62. time_t expires);
  63. /** An AP stream has failed/finished. If it hasn't already sent back
  64. * a socks reply, send one now (based on endreason). Also set
  65. * has_sent_end to 1, and mark the conn.
  66. */
  67. void
  68. connection_mark_unattached_ap_(entry_connection_t *conn, int endreason,
  69. int line, const char *file)
  70. {
  71. connection_t *base_conn = ENTRY_TO_CONN(conn);
  72. edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
  73. tor_assert(base_conn->type == CONN_TYPE_AP);
  74. ENTRY_TO_EDGE_CONN(conn)->edge_has_sent_end = 1; /* no circ yet */
  75. /* If this is a rendezvous stream and it is failing without ever
  76. * being attached to a circuit, assume that an attempt to connect to
  77. * the destination hidden service has just ended.
  78. *
  79. * XXXX This condition doesn't limit to only streams failing
  80. * without ever being attached. That sloppiness should be harmless,
  81. * but we should fix it someday anyway. */
  82. if ((edge_conn->on_circuit != NULL || edge_conn->edge_has_sent_end) &&
  83. connection_edge_is_rendezvous_stream(edge_conn)) {
  84. rend_client_note_connection_attempt_ended(
  85. edge_conn->rend_data->onion_address);
  86. }
  87. if (base_conn->marked_for_close) {
  88. /* This call will warn as appropriate. */
  89. connection_mark_for_close_(base_conn, line, file);
  90. return;
  91. }
  92. if (!conn->socks_request->has_finished) {
  93. if (endreason & END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED)
  94. log_warn(LD_BUG,
  95. "stream (marked at %s:%d) sending two socks replies?",
  96. file, line);
  97. if (SOCKS_COMMAND_IS_CONNECT(conn->socks_request->command))
  98. connection_ap_handshake_socks_reply(conn, NULL, 0, endreason);
  99. else if (SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command))
  100. connection_ap_handshake_socks_resolved(conn,
  101. RESOLVED_TYPE_ERROR_TRANSIENT,
  102. 0, NULL, -1, -1);
  103. else /* unknown or no handshake at all. send no response. */
  104. conn->socks_request->has_finished = 1;
  105. }
  106. connection_mark_and_flush_(base_conn, line, file);
  107. ENTRY_TO_EDGE_CONN(conn)->end_reason = endreason;
  108. }
  109. /** There was an EOF. Send an end and mark the connection for close.
  110. */
  111. int
  112. connection_edge_reached_eof(edge_connection_t *conn)
  113. {
  114. if (connection_get_inbuf_len(TO_CONN(conn)) &&
  115. connection_state_is_open(TO_CONN(conn))) {
  116. /* it still has stuff to process. don't let it die yet. */
  117. return 0;
  118. }
  119. log_info(LD_EDGE,"conn (fd "TOR_SOCKET_T_FORMAT") reached eof. Closing.",
  120. conn->base_.s);
  121. if (!conn->base_.marked_for_close) {
  122. /* only mark it if not already marked. it's possible to
  123. * get the 'end' right around when the client hangs up on us. */
  124. connection_edge_end(conn, END_STREAM_REASON_DONE);
  125. if (conn->base_.type == CONN_TYPE_AP) {
  126. /* eof, so don't send a socks reply back */
  127. if (EDGE_TO_ENTRY_CONN(conn)->socks_request)
  128. EDGE_TO_ENTRY_CONN(conn)->socks_request->has_finished = 1;
  129. }
  130. connection_mark_for_close(TO_CONN(conn));
  131. }
  132. return 0;
  133. }
  134. /** Handle new bytes on conn->inbuf based on state:
  135. * - If it's waiting for socks info, try to read another step of the
  136. * socks handshake out of conn->inbuf.
  137. * - If it's waiting for the original destination, fetch it.
  138. * - If it's open, then package more relay cells from the stream.
  139. * - Else, leave the bytes on inbuf alone for now.
  140. *
  141. * Mark and return -1 if there was an unexpected error with the conn,
  142. * else return 0.
  143. */
  144. int
  145. connection_edge_process_inbuf(edge_connection_t *conn, int package_partial)
  146. {
  147. tor_assert(conn);
  148. switch (conn->base_.state) {
  149. case AP_CONN_STATE_SOCKS_WAIT:
  150. if (connection_ap_handshake_process_socks(EDGE_TO_ENTRY_CONN(conn)) <0) {
  151. /* already marked */
  152. return -1;
  153. }
  154. return 0;
  155. case AP_CONN_STATE_NATD_WAIT:
  156. if (connection_ap_process_natd(EDGE_TO_ENTRY_CONN(conn)) < 0) {
  157. /* already marked */
  158. return -1;
  159. }
  160. return 0;
  161. case AP_CONN_STATE_OPEN:
  162. case EXIT_CONN_STATE_OPEN:
  163. if (connection_edge_package_raw_inbuf(conn, package_partial, NULL) < 0) {
  164. /* (We already sent an end cell if possible) */
  165. connection_mark_for_close(TO_CONN(conn));
  166. return -1;
  167. }
  168. return 0;
  169. case AP_CONN_STATE_CONNECT_WAIT:
  170. if (connection_ap_supports_optimistic_data(EDGE_TO_ENTRY_CONN(conn))) {
  171. log_info(LD_EDGE,
  172. "data from edge while in '%s' state. Sending it anyway. "
  173. "package_partial=%d, buflen=%ld",
  174. conn_state_to_string(conn->base_.type, conn->base_.state),
  175. package_partial,
  176. (long)connection_get_inbuf_len(TO_CONN(conn)));
  177. if (connection_edge_package_raw_inbuf(conn, package_partial, NULL)<0) {
  178. /* (We already sent an end cell if possible) */
  179. connection_mark_for_close(TO_CONN(conn));
  180. return -1;
  181. }
  182. return 0;
  183. }
  184. /* Fall through if the connection is on a circuit without optimistic
  185. * data support. */
  186. case EXIT_CONN_STATE_CONNECTING:
  187. case AP_CONN_STATE_RENDDESC_WAIT:
  188. case AP_CONN_STATE_CIRCUIT_WAIT:
  189. case AP_CONN_STATE_RESOLVE_WAIT:
  190. case AP_CONN_STATE_CONTROLLER_WAIT:
  191. log_info(LD_EDGE,
  192. "data from edge while in '%s' state. Leaving it on buffer.",
  193. conn_state_to_string(conn->base_.type, conn->base_.state));
  194. return 0;
  195. }
  196. log_warn(LD_BUG,"Got unexpected state %d. Closing.",conn->base_.state);
  197. tor_fragile_assert();
  198. connection_edge_end(conn, END_STREAM_REASON_INTERNAL);
  199. connection_mark_for_close(TO_CONN(conn));
  200. return -1;
  201. }
  202. /** This edge needs to be closed, because its circuit has closed.
  203. * Mark it for close and return 0.
  204. */
  205. int
  206. connection_edge_destroy(circid_t circ_id, edge_connection_t *conn)
  207. {
  208. if (!conn->base_.marked_for_close) {
  209. log_info(LD_EDGE, "CircID %u: At an edge. Marking connection for close.",
  210. (unsigned) circ_id);
  211. if (conn->base_.type == CONN_TYPE_AP) {
  212. entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
  213. connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_DESTROY);
  214. control_event_stream_bandwidth(conn);
  215. control_event_stream_status(entry_conn, STREAM_EVENT_CLOSED,
  216. END_STREAM_REASON_DESTROY);
  217. conn->end_reason |= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED;
  218. } else {
  219. /* closing the circuit, nothing to send an END to */
  220. conn->edge_has_sent_end = 1;
  221. conn->end_reason = END_STREAM_REASON_DESTROY;
  222. conn->end_reason |= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED;
  223. connection_mark_and_flush(TO_CONN(conn));
  224. }
  225. }
  226. conn->cpath_layer = NULL;
  227. conn->on_circuit = NULL;
  228. return 0;
  229. }
  230. /** Send a raw end cell to the stream with ID <b>stream_id</b> out over the
  231. * <b>circ</b> towards the hop identified with <b>cpath_layer</b>. If this
  232. * is not a client connection, set the relay end cell's reason for closing
  233. * as <b>reason</b> */
  234. static int
  235. relay_send_end_cell_from_edge(streamid_t stream_id, circuit_t *circ,
  236. uint8_t reason, crypt_path_t *cpath_layer)
  237. {
  238. char payload[1];
  239. if (CIRCUIT_PURPOSE_IS_CLIENT(circ->purpose)) {
  240. /* Never send the server an informative reason code; it doesn't need to
  241. * know why the client stream is failing. */
  242. reason = END_STREAM_REASON_MISC;
  243. }
  244. payload[0] = (char) reason;
  245. return relay_send_command_from_edge(stream_id, circ, RELAY_COMMAND_END,
  246. payload, 1, cpath_layer);
  247. }
  248. /** Send a relay end cell from stream <b>conn</b> down conn's circuit, and
  249. * remember that we've done so. If this is not a client connection, set the
  250. * relay end cell's reason for closing as <b>reason</b>.
  251. *
  252. * Return -1 if this function has already been called on this conn,
  253. * else return 0.
  254. */
  255. int
  256. connection_edge_end(edge_connection_t *conn, uint8_t reason)
  257. {
  258. char payload[RELAY_PAYLOAD_SIZE];
  259. size_t payload_len=1;
  260. circuit_t *circ;
  261. uint8_t control_reason = reason;
  262. if (conn->edge_has_sent_end) {
  263. log_warn(LD_BUG,"(Harmless.) Calling connection_edge_end (reason %d) "
  264. "on an already ended stream?", reason);
  265. tor_fragile_assert();
  266. return -1;
  267. }
  268. if (conn->base_.marked_for_close) {
  269. log_warn(LD_BUG,
  270. "called on conn that's already marked for close at %s:%d.",
  271. conn->base_.marked_for_close_file, conn->base_.marked_for_close);
  272. return 0;
  273. }
  274. circ = circuit_get_by_edge_conn(conn);
  275. if (circ && CIRCUIT_PURPOSE_IS_CLIENT(circ->purpose)) {
  276. /* If this is a client circuit, don't send the server an informative
  277. * reason code; it doesn't need to know why the client stream is
  278. * failing. */
  279. reason = END_STREAM_REASON_MISC;
  280. }
  281. payload[0] = (char)reason;
  282. if (reason == END_STREAM_REASON_EXITPOLICY &&
  283. !connection_edge_is_rendezvous_stream(conn)) {
  284. int addrlen;
  285. if (tor_addr_family(&conn->base_.addr) == AF_INET) {
  286. set_uint32(payload+1, tor_addr_to_ipv4n(&conn->base_.addr));
  287. addrlen = 4;
  288. } else {
  289. memcpy(payload+1, tor_addr_to_in6_addr8(&conn->base_.addr), 16);
  290. addrlen = 16;
  291. }
  292. set_uint32(payload+1+addrlen, htonl(dns_clip_ttl(conn->address_ttl)));
  293. payload_len += 4+addrlen;
  294. }
  295. if (circ && !circ->marked_for_close) {
  296. log_debug(LD_EDGE,"Sending end on conn (fd "TOR_SOCKET_T_FORMAT").",
  297. conn->base_.s);
  298. connection_edge_send_command(conn, RELAY_COMMAND_END,
  299. payload, payload_len);
  300. } else {
  301. log_debug(LD_EDGE,"No circ to send end on conn "
  302. "(fd "TOR_SOCKET_T_FORMAT").",
  303. conn->base_.s);
  304. }
  305. conn->edge_has_sent_end = 1;
  306. conn->end_reason = control_reason;
  307. return 0;
  308. }
  309. /** An error has just occurred on an operation on an edge connection
  310. * <b>conn</b>. Extract the errno; convert it to an end reason, and send an
  311. * appropriate relay end cell to the other end of the connection's circuit.
  312. **/
  313. int
  314. connection_edge_end_errno(edge_connection_t *conn)
  315. {
  316. uint8_t reason;
  317. tor_assert(conn);
  318. reason = errno_to_stream_end_reason(tor_socket_errno(conn->base_.s));
  319. return connection_edge_end(conn, reason);
  320. }
  321. /** We just wrote some data to <b>conn</b>; act appropriately.
  322. *
  323. * (That is, if it's open, consider sending a stream-level sendme cell if we
  324. * have just flushed enough.)
  325. */
  326. int
  327. connection_edge_flushed_some(edge_connection_t *conn)
  328. {
  329. switch (conn->base_.state) {
  330. case AP_CONN_STATE_OPEN:
  331. case EXIT_CONN_STATE_OPEN:
  332. connection_edge_consider_sending_sendme(conn);
  333. break;
  334. }
  335. return 0;
  336. }
  337. /** Connection <b>conn</b> has finished writing and has no bytes left on
  338. * its outbuf.
  339. *
  340. * If it's in state 'open', stop writing, consider responding with a
  341. * sendme, and return.
  342. * Otherwise, stop writing and return.
  343. *
  344. * If <b>conn</b> is broken, mark it for close and return -1, else
  345. * return 0.
  346. */
  347. int
  348. connection_edge_finished_flushing(edge_connection_t *conn)
  349. {
  350. tor_assert(conn);
  351. switch (conn->base_.state) {
  352. case AP_CONN_STATE_OPEN:
  353. case EXIT_CONN_STATE_OPEN:
  354. connection_edge_consider_sending_sendme(conn);
  355. return 0;
  356. case AP_CONN_STATE_SOCKS_WAIT:
  357. case AP_CONN_STATE_NATD_WAIT:
  358. case AP_CONN_STATE_RENDDESC_WAIT:
  359. case AP_CONN_STATE_CIRCUIT_WAIT:
  360. case AP_CONN_STATE_CONNECT_WAIT:
  361. case AP_CONN_STATE_CONTROLLER_WAIT:
  362. case AP_CONN_STATE_RESOLVE_WAIT:
  363. return 0;
  364. default:
  365. log_warn(LD_BUG, "Called in unexpected state %d.",conn->base_.state);
  366. tor_fragile_assert();
  367. return -1;
  368. }
  369. return 0;
  370. }
  371. /** Longest size for the relay payload of a RELAY_CONNECTED cell that we're
  372. * able to generate. */
  373. /* 4 zero bytes; 1 type byte; 16 byte IPv6 address; 4 byte TTL. */
  374. #define MAX_CONNECTED_CELL_PAYLOAD_LEN 25
  375. /** Set the buffer at <b>payload_out</b> -- which must have at least
  376. * MAX_CONNECTED_CELL_PAYLOAD_LEN bytes available -- to the body of a
  377. * RELAY_CONNECTED cell indicating that we have connected to <b>addr</b>, and
  378. * that the name resolution that led us to <b>addr</b> will be valid for
  379. * <b>ttl</b> seconds. Return -1 on error, or the number of bytes used on
  380. * success. */
  381. /* private */int
  382. connected_cell_format_payload(uint8_t *payload_out,
  383. const tor_addr_t *addr,
  384. uint32_t ttl)
  385. {
  386. const sa_family_t family = tor_addr_family(addr);
  387. int connected_payload_len;
  388. /* should be needless */
  389. memset(payload_out, 0, MAX_CONNECTED_CELL_PAYLOAD_LEN);
  390. if (family == AF_INET) {
  391. set_uint32(payload_out, tor_addr_to_ipv4n(addr));
  392. connected_payload_len = 4;
  393. } else if (family == AF_INET6) {
  394. set_uint32(payload_out, 0);
  395. set_uint8(payload_out + 4, 6);
  396. memcpy(payload_out + 5, tor_addr_to_in6_addr8(addr), 16);
  397. connected_payload_len = 21;
  398. } else {
  399. return -1;
  400. }
  401. set_uint32(payload_out + connected_payload_len, htonl(dns_clip_ttl(ttl)));
  402. connected_payload_len += 4;
  403. tor_assert(connected_payload_len <= MAX_CONNECTED_CELL_PAYLOAD_LEN);
  404. return connected_payload_len;
  405. }
  406. /** Connected handler for exit connections: start writing pending
  407. * data, deliver 'CONNECTED' relay cells as appropriate, and check
  408. * any pending data that may have been received. */
  409. int
  410. connection_edge_finished_connecting(edge_connection_t *edge_conn)
  411. {
  412. connection_t *conn;
  413. tor_assert(edge_conn);
  414. tor_assert(edge_conn->base_.type == CONN_TYPE_EXIT);
  415. conn = TO_CONN(edge_conn);
  416. tor_assert(conn->state == EXIT_CONN_STATE_CONNECTING);
  417. log_info(LD_EXIT,"Exit connection to %s:%u (%s) established.",
  418. escaped_safe_str(conn->address), conn->port,
  419. safe_str(fmt_and_decorate_addr(&conn->addr)));
  420. rep_hist_note_exit_stream_opened(conn->port);
  421. conn->state = EXIT_CONN_STATE_OPEN;
  422. IF_HAS_NO_BUFFEREVENT(conn)
  423. connection_watch_events(conn, READ_EVENT); /* stop writing, keep reading */
  424. if (connection_get_outbuf_len(conn)) /* in case there are any queued relay
  425. * cells */
  426. connection_start_writing(conn);
  427. /* deliver a 'connected' relay cell back through the circuit. */
  428. if (connection_edge_is_rendezvous_stream(edge_conn)) {
  429. if (connection_edge_send_command(edge_conn,
  430. RELAY_COMMAND_CONNECTED, NULL, 0) < 0)
  431. return 0; /* circuit is closed, don't continue */
  432. } else {
  433. uint8_t connected_payload[MAX_CONNECTED_CELL_PAYLOAD_LEN];
  434. int connected_payload_len =
  435. connected_cell_format_payload(connected_payload, &conn->addr,
  436. edge_conn->address_ttl);
  437. if (connected_payload_len < 0)
  438. return -1;
  439. if (connection_edge_send_command(edge_conn,
  440. RELAY_COMMAND_CONNECTED,
  441. (char*)connected_payload, connected_payload_len) < 0)
  442. return 0; /* circuit is closed, don't continue */
  443. }
  444. tor_assert(edge_conn->package_window > 0);
  445. /* in case the server has written anything */
  446. return connection_edge_process_inbuf(edge_conn, 1);
  447. }
  448. /** Common code to connection_(ap|exit)_about_to_close. */
  449. static void
  450. connection_edge_about_to_close(edge_connection_t *edge_conn)
  451. {
  452. if (!edge_conn->edge_has_sent_end) {
  453. connection_t *conn = TO_CONN(edge_conn);
  454. log_warn(LD_BUG, "(Harmless.) Edge connection (marked at %s:%d) "
  455. "hasn't sent end yet?",
  456. conn->marked_for_close_file, conn->marked_for_close);
  457. tor_fragile_assert();
  458. }
  459. }
  460. /** Called when we're about to finally unlink and free an AP (client)
  461. * connection: perform necessary accounting and cleanup */
  462. void
  463. connection_ap_about_to_close(entry_connection_t *entry_conn)
  464. {
  465. circuit_t *circ;
  466. edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(entry_conn);
  467. connection_t *conn = ENTRY_TO_CONN(entry_conn);
  468. if (entry_conn->socks_request->has_finished == 0) {
  469. /* since conn gets removed right after this function finishes,
  470. * there's no point trying to send back a reply at this point. */
  471. log_warn(LD_BUG,"Closing stream (marked at %s:%d) without sending"
  472. " back a socks reply.",
  473. conn->marked_for_close_file, conn->marked_for_close);
  474. }
  475. if (!edge_conn->end_reason) {
  476. log_warn(LD_BUG,"Closing stream (marked at %s:%d) without having"
  477. " set end_reason.",
  478. conn->marked_for_close_file, conn->marked_for_close);
  479. }
  480. if (entry_conn->dns_server_request) {
  481. log_warn(LD_BUG,"Closing stream (marked at %s:%d) without having"
  482. " replied to DNS request.",
  483. conn->marked_for_close_file, conn->marked_for_close);
  484. dnsserv_reject_request(entry_conn);
  485. }
  486. control_event_stream_bandwidth(edge_conn);
  487. control_event_stream_status(entry_conn, STREAM_EVENT_CLOSED,
  488. edge_conn->end_reason);
  489. circ = circuit_get_by_edge_conn(edge_conn);
  490. if (circ)
  491. circuit_detach_stream(circ, edge_conn);
  492. }
  493. /** Called when we're about to finally unlink and free an exit
  494. * connection: perform necessary accounting and cleanup */
  495. void
  496. connection_exit_about_to_close(edge_connection_t *edge_conn)
  497. {
  498. circuit_t *circ;
  499. connection_t *conn = TO_CONN(edge_conn);
  500. connection_edge_about_to_close(edge_conn);
  501. circ = circuit_get_by_edge_conn(edge_conn);
  502. if (circ)
  503. circuit_detach_stream(circ, edge_conn);
  504. if (conn->state == EXIT_CONN_STATE_RESOLVING) {
  505. connection_dns_remove(edge_conn);
  506. }
  507. }
  508. /** Define a schedule for how long to wait between retrying
  509. * application connections. Rather than waiting a fixed amount of
  510. * time between each retry, we wait 10 seconds each for the first
  511. * two tries, and 15 seconds for each retry after
  512. * that. Hopefully this will improve the expected user experience. */
  513. static int
  514. compute_retry_timeout(entry_connection_t *conn)
  515. {
  516. int timeout = get_options()->CircuitStreamTimeout;
  517. if (timeout) /* if our config options override the default, use them */
  518. return timeout;
  519. if (conn->num_socks_retries < 2) /* try 0 and try 1 */
  520. return 10;
  521. return 15;
  522. }
  523. /** Find all general-purpose AP streams waiting for a response that sent their
  524. * begin/resolve cell too long ago. Detach from their current circuit, and
  525. * mark their current circuit as unsuitable for new streams. Then call
  526. * connection_ap_handshake_attach_circuit() to attach to a new circuit (if
  527. * available) or launch a new one.
  528. *
  529. * For rendezvous streams, simply give up after SocksTimeout seconds (with no
  530. * retry attempt).
  531. */
  532. void
  533. connection_ap_expire_beginning(void)
  534. {
  535. edge_connection_t *conn;
  536. entry_connection_t *entry_conn;
  537. circuit_t *circ;
  538. time_t now = time(NULL);
  539. const or_options_t *options = get_options();
  540. int severity;
  541. int cutoff;
  542. int seconds_idle, seconds_since_born;
  543. smartlist_t *conns = get_connection_array();
  544. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
  545. if (base_conn->type != CONN_TYPE_AP || base_conn->marked_for_close)
  546. continue;
  547. entry_conn = TO_ENTRY_CONN(base_conn);
  548. conn = ENTRY_TO_EDGE_CONN(entry_conn);
  549. /* if it's an internal linked connection, don't yell its status. */
  550. severity = (tor_addr_is_null(&base_conn->addr) && !base_conn->port)
  551. ? LOG_INFO : LOG_NOTICE;
  552. seconds_idle = (int)( now - base_conn->timestamp_lastread );
  553. seconds_since_born = (int)( now - base_conn->timestamp_created );
  554. if (base_conn->state == AP_CONN_STATE_OPEN)
  555. continue;
  556. /* We already consider SocksTimeout in
  557. * connection_ap_handshake_attach_circuit(), but we need to consider
  558. * it here too because controllers that put streams in controller_wait
  559. * state never ask Tor to attach the circuit. */
  560. if (AP_CONN_STATE_IS_UNATTACHED(base_conn->state)) {
  561. if (seconds_since_born >= options->SocksTimeout) {
  562. log_fn(severity, LD_APP,
  563. "Tried for %d seconds to get a connection to %s:%d. "
  564. "Giving up. (%s)",
  565. seconds_since_born,
  566. safe_str_client(entry_conn->socks_request->address),
  567. entry_conn->socks_request->port,
  568. conn_state_to_string(CONN_TYPE_AP, base_conn->state));
  569. connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TIMEOUT);
  570. }
  571. continue;
  572. }
  573. /* We're in state connect_wait or resolve_wait now -- waiting for a
  574. * reply to our relay cell. See if we want to retry/give up. */
  575. cutoff = compute_retry_timeout(entry_conn);
  576. if (seconds_idle < cutoff)
  577. continue;
  578. circ = circuit_get_by_edge_conn(conn);
  579. if (!circ) { /* it's vanished? */
  580. log_info(LD_APP,"Conn is waiting (address %s), but lost its circ.",
  581. safe_str_client(entry_conn->socks_request->address));
  582. connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TIMEOUT);
  583. continue;
  584. }
  585. if (circ->purpose == CIRCUIT_PURPOSE_C_REND_JOINED) {
  586. if (seconds_idle >= options->SocksTimeout) {
  587. log_fn(severity, LD_REND,
  588. "Rend stream is %d seconds late. Giving up on address"
  589. " '%s.onion'.",
  590. seconds_idle,
  591. safe_str_client(entry_conn->socks_request->address));
  592. /* Roll back path bias use state so that we probe the circuit
  593. * if nothing else succeeds on it */
  594. pathbias_mark_use_rollback(TO_ORIGIN_CIRCUIT(circ));
  595. connection_edge_end(conn, END_STREAM_REASON_TIMEOUT);
  596. connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TIMEOUT);
  597. }
  598. continue;
  599. }
  600. if (circ->purpose != CIRCUIT_PURPOSE_C_GENERAL &&
  601. circ->purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT &&
  602. circ->purpose != CIRCUIT_PURPOSE_PATH_BIAS_TESTING) {
  603. log_warn(LD_BUG, "circuit->purpose == CIRCUIT_PURPOSE_C_GENERAL failed. "
  604. "The purpose on the circuit was %s; it was in state %s, "
  605. "path_state %s.",
  606. circuit_purpose_to_string(circ->purpose),
  607. circuit_state_to_string(circ->state),
  608. CIRCUIT_IS_ORIGIN(circ) ?
  609. pathbias_state_to_string(TO_ORIGIN_CIRCUIT(circ)->path_state) :
  610. "none");
  611. }
  612. log_fn(cutoff < 15 ? LOG_INFO : severity, LD_APP,
  613. "We tried for %d seconds to connect to '%s' using exit %s."
  614. " Retrying on a new circuit.",
  615. seconds_idle,
  616. safe_str_client(entry_conn->socks_request->address),
  617. conn->cpath_layer ?
  618. extend_info_describe(conn->cpath_layer->extend_info):
  619. "*unnamed*");
  620. /* send an end down the circuit */
  621. connection_edge_end(conn, END_STREAM_REASON_TIMEOUT);
  622. /* un-mark it as ending, since we're going to reuse it */
  623. conn->edge_has_sent_end = 0;
  624. conn->end_reason = 0;
  625. /* make us not try this circuit again, but allow
  626. * current streams on it to survive if they can */
  627. mark_circuit_unusable_for_new_conns(TO_ORIGIN_CIRCUIT(circ));
  628. /* give our stream another 'cutoff' seconds to try */
  629. conn->base_.timestamp_lastread += cutoff;
  630. if (entry_conn->num_socks_retries < 250) /* avoid overflow */
  631. entry_conn->num_socks_retries++;
  632. /* move it back into 'pending' state, and try to attach. */
  633. if (connection_ap_detach_retriable(entry_conn, TO_ORIGIN_CIRCUIT(circ),
  634. END_STREAM_REASON_TIMEOUT)<0) {
  635. if (!base_conn->marked_for_close)
  636. connection_mark_unattached_ap(entry_conn,
  637. END_STREAM_REASON_CANT_ATTACH);
  638. }
  639. } SMARTLIST_FOREACH_END(base_conn);
  640. }
  641. /** Tell any AP streams that are waiting for a new circuit to try again,
  642. * either attaching to an available circ or launching a new one.
  643. */
  644. void
  645. connection_ap_attach_pending(void)
  646. {
  647. entry_connection_t *entry_conn;
  648. smartlist_t *conns = get_connection_array();
  649. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
  650. if (conn->marked_for_close ||
  651. conn->type != CONN_TYPE_AP ||
  652. conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
  653. continue;
  654. entry_conn = TO_ENTRY_CONN(conn);
  655. if (connection_ap_handshake_attach_circuit(entry_conn) < 0) {
  656. if (!conn->marked_for_close)
  657. connection_mark_unattached_ap(entry_conn,
  658. END_STREAM_REASON_CANT_ATTACH);
  659. }
  660. } SMARTLIST_FOREACH_END(conn);
  661. }
  662. /** Tell any AP streams that are waiting for a one-hop tunnel to
  663. * <b>failed_digest</b> that they are going to fail. */
  664. /* XXX024 We should get rid of this function, and instead attach
  665. * one-hop streams to circ->p_streams so they get marked in
  666. * circuit_mark_for_close like normal p_streams. */
  667. void
  668. connection_ap_fail_onehop(const char *failed_digest,
  669. cpath_build_state_t *build_state)
  670. {
  671. entry_connection_t *entry_conn;
  672. char digest[DIGEST_LEN];
  673. smartlist_t *conns = get_connection_array();
  674. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
  675. if (conn->marked_for_close ||
  676. conn->type != CONN_TYPE_AP ||
  677. conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
  678. continue;
  679. entry_conn = TO_ENTRY_CONN(conn);
  680. if (!entry_conn->want_onehop)
  681. continue;
  682. if (hexdigest_to_digest(entry_conn->chosen_exit_name, digest) < 0 ||
  683. tor_memneq(digest, failed_digest, DIGEST_LEN))
  684. continue;
  685. if (tor_digest_is_zero(digest)) {
  686. /* we don't know the digest; have to compare addr:port */
  687. tor_addr_t addr;
  688. if (!build_state || !build_state->chosen_exit ||
  689. !entry_conn->socks_request)
  690. continue;
  691. if (tor_addr_parse(&addr, entry_conn->socks_request->address)<0 ||
  692. !tor_addr_eq(&build_state->chosen_exit->addr, &addr) ||
  693. build_state->chosen_exit->port != entry_conn->socks_request->port)
  694. continue;
  695. }
  696. log_info(LD_APP, "Closing one-hop stream to '%s/%s' because the OR conn "
  697. "just failed.", entry_conn->chosen_exit_name,
  698. entry_conn->socks_request->address);
  699. connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TIMEOUT);
  700. } SMARTLIST_FOREACH_END(conn);
  701. }
  702. /** A circuit failed to finish on its last hop <b>info</b>. If there
  703. * are any streams waiting with this exit node in mind, but they
  704. * don't absolutely require it, make them give up on it.
  705. */
  706. void
  707. circuit_discard_optional_exit_enclaves(extend_info_t *info)
  708. {
  709. entry_connection_t *entry_conn;
  710. const node_t *r1, *r2;
  711. smartlist_t *conns = get_connection_array();
  712. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
  713. if (conn->marked_for_close ||
  714. conn->type != CONN_TYPE_AP ||
  715. conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
  716. continue;
  717. entry_conn = TO_ENTRY_CONN(conn);
  718. if (!entry_conn->chosen_exit_optional &&
  719. !entry_conn->chosen_exit_retries)
  720. continue;
  721. r1 = node_get_by_nickname(entry_conn->chosen_exit_name, 0);
  722. r2 = node_get_by_id(info->identity_digest);
  723. if (!r1 || !r2 || r1 != r2)
  724. continue;
  725. tor_assert(entry_conn->socks_request);
  726. if (entry_conn->chosen_exit_optional) {
  727. log_info(LD_APP, "Giving up on enclave exit '%s' for destination %s.",
  728. safe_str_client(entry_conn->chosen_exit_name),
  729. escaped_safe_str_client(entry_conn->socks_request->address));
  730. entry_conn->chosen_exit_optional = 0;
  731. tor_free(entry_conn->chosen_exit_name); /* clears it */
  732. /* if this port is dangerous, warn or reject it now that we don't
  733. * think it'll be using an enclave. */
  734. consider_plaintext_ports(entry_conn, entry_conn->socks_request->port);
  735. }
  736. if (entry_conn->chosen_exit_retries) {
  737. if (--entry_conn->chosen_exit_retries == 0) { /* give up! */
  738. clear_trackexithost_mappings(entry_conn->chosen_exit_name);
  739. tor_free(entry_conn->chosen_exit_name); /* clears it */
  740. /* if this port is dangerous, warn or reject it now that we don't
  741. * think it'll be using an enclave. */
  742. consider_plaintext_ports(entry_conn, entry_conn->socks_request->port);
  743. }
  744. }
  745. } SMARTLIST_FOREACH_END(conn);
  746. }
  747. /** The AP connection <b>conn</b> has just failed while attaching or
  748. * sending a BEGIN or resolving on <b>circ</b>, but another circuit
  749. * might work. Detach the circuit, and either reattach it, launch a
  750. * new circuit, tell the controller, or give up as appropriate.
  751. *
  752. * Returns -1 on err, 1 on success, 0 on not-yet-sure.
  753. */
  754. int
  755. connection_ap_detach_retriable(entry_connection_t *conn,
  756. origin_circuit_t *circ,
  757. int reason)
  758. {
  759. control_event_stream_status(conn, STREAM_EVENT_FAILED_RETRIABLE, reason);
  760. ENTRY_TO_CONN(conn)->timestamp_lastread = time(NULL);
  761. /* Roll back path bias use state so that we probe the circuit
  762. * if nothing else succeeds on it */
  763. pathbias_mark_use_rollback(circ);
  764. if (conn->pending_optimistic_data) {
  765. generic_buffer_set_to_copy(&conn->sending_optimistic_data,
  766. conn->pending_optimistic_data);
  767. }
  768. if (!get_options()->LeaveStreamsUnattached || conn->use_begindir) {
  769. /* If we're attaching streams ourself, or if this connection is
  770. * a tunneled directory connection, then just attach it. */
  771. ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_CIRCUIT_WAIT;
  772. circuit_detach_stream(TO_CIRCUIT(circ),ENTRY_TO_EDGE_CONN(conn));
  773. return connection_ap_handshake_attach_circuit(conn);
  774. } else {
  775. ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_CONTROLLER_WAIT;
  776. circuit_detach_stream(TO_CIRCUIT(circ),ENTRY_TO_EDGE_CONN(conn));
  777. return 0;
  778. }
  779. }
  780. /** Check if <b>conn</b> is using a dangerous port. Then warn and/or
  781. * reject depending on our config options. */
  782. static int
  783. consider_plaintext_ports(entry_connection_t *conn, uint16_t port)
  784. {
  785. const or_options_t *options = get_options();
  786. int reject = smartlist_contains_int_as_string(
  787. options->RejectPlaintextPorts, port);
  788. if (smartlist_contains_int_as_string(options->WarnPlaintextPorts, port)) {
  789. log_warn(LD_APP, "Application request to port %d: this port is "
  790. "commonly used for unencrypted protocols. Please make sure "
  791. "you don't send anything you would mind the rest of the "
  792. "Internet reading!%s", port, reject ? " Closing." : "");
  793. control_event_client_status(LOG_WARN, "DANGEROUS_PORT PORT=%d RESULT=%s",
  794. port, reject ? "REJECT" : "WARN");
  795. }
  796. if (reject) {
  797. log_info(LD_APP, "Port %d listed in RejectPlaintextPorts. Closing.", port);
  798. connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
  799. return -1;
  800. }
  801. return 0;
  802. }
  803. /** How many times do we try connecting with an exit configured via
  804. * TrackHostExits before concluding that it won't work any more and trying a
  805. * different one? */
  806. #define TRACKHOSTEXITS_RETRIES 5
  807. /** Call connection_ap_handshake_rewrite_and_attach() unless a controller
  808. * asked us to leave streams unattached. Return 0 in that case.
  809. *
  810. * See connection_ap_handshake_rewrite_and_attach()'s
  811. * documentation for arguments and return value.
  812. */
  813. int
  814. connection_ap_rewrite_and_attach_if_allowed(entry_connection_t *conn,
  815. origin_circuit_t *circ,
  816. crypt_path_t *cpath)
  817. {
  818. const or_options_t *options = get_options();
  819. if (options->LeaveStreamsUnattached) {
  820. ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_CONTROLLER_WAIT;
  821. return 0;
  822. }
  823. return connection_ap_handshake_rewrite_and_attach(conn, circ, cpath);
  824. }
  825. /** Connection <b>conn</b> just finished its socks handshake, or the
  826. * controller asked us to take care of it. If <b>circ</b> is defined,
  827. * then that's where we'll want to attach it. Otherwise we have to
  828. * figure it out ourselves.
  829. *
  830. * First, parse whether it's a .exit address, remap it, and so on. Then
  831. * if it's for a general circuit, try to attach it to a circuit (or launch
  832. * one as needed), else if it's for a rendezvous circuit, fetch a
  833. * rendezvous descriptor first (or attach/launch a circuit if the
  834. * rendezvous descriptor is already here and fresh enough).
  835. *
  836. * The stream will exit from the hop
  837. * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
  838. * <b>cpath</b> is NULL.
  839. */
  840. int
  841. connection_ap_handshake_rewrite_and_attach(entry_connection_t *conn,
  842. origin_circuit_t *circ,
  843. crypt_path_t *cpath)
  844. {
  845. socks_request_t *socks = conn->socks_request;
  846. hostname_type_t addresstype;
  847. const or_options_t *options = get_options();
  848. tor_addr_t addr_tmp;
  849. /* We set this to true if this is an address we should automatically
  850. * remap to a local address in VirtualAddrNetwork */
  851. int automap = 0;
  852. char orig_address[MAX_SOCKS_ADDR_LEN];
  853. time_t map_expires = TIME_MAX;
  854. time_t now = time(NULL);
  855. connection_t *base_conn = ENTRY_TO_CONN(conn);
  856. addressmap_entry_source_t exit_source = ADDRMAPSRC_NONE;
  857. tor_strlower(socks->address); /* normalize it */
  858. strlcpy(orig_address, socks->address, sizeof(orig_address));
  859. log_debug(LD_APP,"Client asked for %s:%d",
  860. safe_str_client(socks->address),
  861. socks->port);
  862. if (!strcmpend(socks->address, ".exit") && !options->AllowDotExit) {
  863. log_warn(LD_APP, "The \".exit\" notation is disabled in Tor due to "
  864. "security risks. Set AllowDotExit in your torrc to enable "
  865. "it (at your own risk).");
  866. control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
  867. escaped(socks->address));
  868. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  869. return -1;
  870. }
  871. if (! conn->original_dest_address)
  872. conn->original_dest_address = tor_strdup(conn->socks_request->address);
  873. if (socks->command == SOCKS_COMMAND_RESOLVE &&
  874. tor_addr_parse(&addr_tmp, socks->address)<0 &&
  875. options->AutomapHostsOnResolve) {
  876. automap = addressmap_address_should_automap(socks->address, options);
  877. if (automap) {
  878. const char *new_addr;
  879. int addr_type = RESOLVED_TYPE_IPV4;
  880. if (conn->socks_request->socks_version != 4) {
  881. if (!conn->ipv4_traffic_ok ||
  882. (conn->ipv6_traffic_ok && conn->prefer_ipv6_traffic) ||
  883. conn->prefer_ipv6_virtaddr)
  884. addr_type = RESOLVED_TYPE_IPV6;
  885. }
  886. new_addr = addressmap_register_virtual_address(
  887. addr_type, tor_strdup(socks->address));
  888. if (! new_addr) {
  889. log_warn(LD_APP, "Unable to automap address %s",
  890. escaped_safe_str(socks->address));
  891. connection_mark_unattached_ap(conn, END_STREAM_REASON_INTERNAL);
  892. return -1;
  893. }
  894. log_info(LD_APP, "Automapping %s to %s",
  895. escaped_safe_str_client(socks->address),
  896. safe_str_client(new_addr));
  897. strlcpy(socks->address, new_addr, sizeof(socks->address));
  898. }
  899. }
  900. if (socks->command == SOCKS_COMMAND_RESOLVE_PTR) {
  901. unsigned rewrite_flags = 0;
  902. if (conn->use_cached_ipv4_answers)
  903. rewrite_flags |= AMR_FLAG_USE_IPV4_DNS;
  904. if (conn->use_cached_ipv6_answers)
  905. rewrite_flags |= AMR_FLAG_USE_IPV6_DNS;
  906. if (addressmap_rewrite_reverse(socks->address, sizeof(socks->address),
  907. rewrite_flags, &map_expires)) {
  908. char *result = tor_strdup(socks->address);
  909. /* remember _what_ is supposed to have been resolved. */
  910. tor_snprintf(socks->address, sizeof(socks->address), "REVERSE[%s]",
  911. orig_address);
  912. connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_HOSTNAME,
  913. strlen(result), (uint8_t*)result,
  914. -1,
  915. map_expires);
  916. connection_mark_unattached_ap(conn,
  917. END_STREAM_REASON_DONE |
  918. END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
  919. return 0;
  920. }
  921. if (options->ClientDNSRejectInternalAddresses) {
  922. /* Don't let people try to do a reverse lookup on 10.0.0.1. */
  923. tor_addr_t addr;
  924. int ok;
  925. ok = tor_addr_parse_PTR_name(
  926. &addr, socks->address, AF_UNSPEC, 1);
  927. if (ok == 1 && tor_addr_is_internal(&addr, 0)) {
  928. connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_ERROR,
  929. 0, NULL, -1, TIME_MAX);
  930. connection_mark_unattached_ap(conn,
  931. END_STREAM_REASON_SOCKSPROTOCOL |
  932. END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
  933. return -1;
  934. }
  935. }
  936. } else if (!automap) {
  937. /* For address map controls, remap the address. */
  938. unsigned rewrite_flags = 0;
  939. if (conn->use_cached_ipv4_answers)
  940. rewrite_flags |= AMR_FLAG_USE_IPV4_DNS;
  941. if (conn->use_cached_ipv6_answers)
  942. rewrite_flags |= AMR_FLAG_USE_IPV6_DNS;
  943. if (addressmap_rewrite(socks->address, sizeof(socks->address),
  944. rewrite_flags, &map_expires, &exit_source)) {
  945. control_event_stream_status(conn, STREAM_EVENT_REMAP,
  946. REMAP_STREAM_SOURCE_CACHE);
  947. }
  948. }
  949. if (!automap && address_is_in_virtual_range(socks->address)) {
  950. /* This address was probably handed out by client_dns_get_unmapped_address,
  951. * but the mapping was discarded for some reason. We *don't* want to send
  952. * the address through Tor; that's likely to fail, and may leak
  953. * information.
  954. */
  955. log_warn(LD_APP,"Missing mapping for virtual address '%s'. Refusing.",
  956. safe_str_client(socks->address));
  957. connection_mark_unattached_ap(conn, END_STREAM_REASON_INTERNAL);
  958. return -1;
  959. }
  960. /* Parse the address provided by SOCKS. Modify it in-place if it
  961. * specifies a hidden-service (.onion) or particular exit node (.exit).
  962. */
  963. addresstype = parse_extended_hostname(socks->address);
  964. if (addresstype == BAD_HOSTNAME) {
  965. control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
  966. escaped(socks->address));
  967. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  968. return -1;
  969. }
  970. if (addresstype == EXIT_HOSTNAME) {
  971. /* foo.exit -- modify conn->chosen_exit_node to specify the exit
  972. * node, and conn->address to hold only the address portion. */
  973. char *s = strrchr(socks->address,'.');
  974. /* If StrictNodes is not set, then .exit overrides ExcludeNodes. */
  975. routerset_t *excludeset = options->StrictNodes ?
  976. options->ExcludeExitNodesUnion_ : options->ExcludeExitNodes;
  977. const node_t *node;
  978. if (exit_source == ADDRMAPSRC_AUTOMAP && !options->AllowDotExit) {
  979. /* Whoops; this one is stale. It must have gotten added earlier,
  980. * when AllowDotExit was on. */
  981. log_warn(LD_APP,"Stale automapped address for '%s.exit', with "
  982. "AllowDotExit disabled. Refusing.",
  983. safe_str_client(socks->address));
  984. control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
  985. escaped(socks->address));
  986. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  987. return -1;
  988. }
  989. if (exit_source == ADDRMAPSRC_DNS ||
  990. (exit_source == ADDRMAPSRC_NONE && !options->AllowDotExit)) {
  991. /* It shouldn't be possible to get a .exit address from any of these
  992. * sources. */
  993. log_warn(LD_BUG,"Address '%s.exit', with impossible source for the "
  994. ".exit part. Refusing.",
  995. safe_str_client(socks->address));
  996. control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
  997. escaped(socks->address));
  998. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  999. return -1;
  1000. }
  1001. tor_assert(!automap);
  1002. if (s) {
  1003. /* The address was of the form "(stuff).(name).exit */
  1004. if (s[1] != '\0') {
  1005. conn->chosen_exit_name = tor_strdup(s+1);
  1006. node = node_get_by_nickname(conn->chosen_exit_name, 1);
  1007. if (exit_source == ADDRMAPSRC_TRACKEXIT) {
  1008. /* We 5 tries before it expires the addressmap */
  1009. conn->chosen_exit_retries = TRACKHOSTEXITS_RETRIES;
  1010. }
  1011. *s = 0;
  1012. } else {
  1013. /* Oops, the address was (stuff)..exit. That's not okay. */
  1014. log_warn(LD_APP,"Malformed exit address '%s.exit'. Refusing.",
  1015. safe_str_client(socks->address));
  1016. control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
  1017. escaped(socks->address));
  1018. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1019. return -1;
  1020. }
  1021. } else {
  1022. /* It looks like they just asked for "foo.exit". */
  1023. conn->chosen_exit_name = tor_strdup(socks->address);
  1024. node = node_get_by_nickname(conn->chosen_exit_name, 1);
  1025. if (node) {
  1026. *socks->address = 0;
  1027. node_get_address_string(node, socks->address, sizeof(socks->address));
  1028. }
  1029. }
  1030. /* Now make sure that the chosen exit exists... */
  1031. if (!node) {
  1032. log_warn(LD_APP,
  1033. "Unrecognized relay in exit address '%s.exit'. Refusing.",
  1034. safe_str_client(socks->address));
  1035. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1036. return -1;
  1037. }
  1038. /* ...and make sure that it isn't excluded. */
  1039. if (routerset_contains_node(excludeset, node)) {
  1040. log_warn(LD_APP,
  1041. "Excluded relay in exit address '%s.exit'. Refusing.",
  1042. safe_str_client(socks->address));
  1043. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1044. return -1;
  1045. }
  1046. /* XXXX024-1090 Should we also allow foo.bar.exit if ExitNodes is set and
  1047. Bar is not listed in it? I say yes, but our revised manpage branch
  1048. implies no. */
  1049. }
  1050. if (addresstype != ONION_HOSTNAME) {
  1051. /* not a hidden-service request (i.e. normal or .exit) */
  1052. if (address_is_invalid_destination(socks->address, 1)) {
  1053. control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
  1054. escaped(socks->address));
  1055. log_warn(LD_APP,
  1056. "Destination '%s' seems to be an invalid hostname. Failing.",
  1057. safe_str_client(socks->address));
  1058. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1059. return -1;
  1060. }
  1061. if (options->Tor2webMode) {
  1062. log_warn(LD_APP, "Refusing to connect to non-hidden-service hostname %s "
  1063. "because tor2web mode is enabled.",
  1064. safe_str_client(socks->address));
  1065. connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
  1066. return -1;
  1067. }
  1068. if (socks->command == SOCKS_COMMAND_RESOLVE) {
  1069. tor_addr_t answer;
  1070. /* Reply to resolves immediately if we can. */
  1071. if (tor_addr_parse(&answer, socks->address) >= 0) {/* is it an IP? */
  1072. /* remember _what_ is supposed to have been resolved. */
  1073. strlcpy(socks->address, orig_address, sizeof(socks->address));
  1074. connection_ap_handshake_socks_resolved_addr(conn, &answer, -1,
  1075. map_expires);
  1076. connection_mark_unattached_ap(conn,
  1077. END_STREAM_REASON_DONE |
  1078. END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
  1079. return 0;
  1080. }
  1081. tor_assert(!automap);
  1082. rep_hist_note_used_resolve(now); /* help predict this next time */
  1083. } else if (socks->command == SOCKS_COMMAND_CONNECT) {
  1084. tor_assert(!automap);
  1085. if (socks->port == 0) {
  1086. log_notice(LD_APP,"Application asked to connect to port 0. Refusing.");
  1087. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1088. return -1;
  1089. }
  1090. if (options->ClientRejectInternalAddresses &&
  1091. !conn->use_begindir && !conn->chosen_exit_name && !circ) {
  1092. tor_addr_t addr;
  1093. if (tor_addr_hostname_is_local(socks->address) ||
  1094. (tor_addr_parse(&addr, socks->address) >= 0 &&
  1095. tor_addr_is_internal(&addr, 0))) {
  1096. /* If this is an explicit private address with no chosen exit node,
  1097. * then we really don't want to try to connect to it. That's
  1098. * probably an error. */
  1099. if (conn->is_transparent_ap) {
  1100. #define WARN_INTRVL_LOOP 300
  1101. static ratelim_t loop_warn_limit = RATELIM_INIT(WARN_INTRVL_LOOP);
  1102. char *m;
  1103. if ((m = rate_limit_log(&loop_warn_limit, approx_time()))) {
  1104. log_warn(LD_NET,
  1105. "Rejecting request for anonymous connection to private "
  1106. "address %s on a TransPort or NATDPort. Possible loop "
  1107. "in your NAT rules?%s", safe_str_client(socks->address),
  1108. m);
  1109. tor_free(m);
  1110. }
  1111. } else {
  1112. #define WARN_INTRVL_PRIV 300
  1113. static ratelim_t priv_warn_limit = RATELIM_INIT(WARN_INTRVL_PRIV);
  1114. char *m;
  1115. if ((m = rate_limit_log(&priv_warn_limit, approx_time()))) {
  1116. log_warn(LD_NET,
  1117. "Rejecting SOCKS request for anonymous connection to "
  1118. "private address %s.%s",
  1119. safe_str_client(socks->address),m);
  1120. tor_free(m);
  1121. }
  1122. }
  1123. connection_mark_unattached_ap(conn, END_STREAM_REASON_PRIVATE_ADDR);
  1124. return -1;
  1125. }
  1126. }
  1127. {
  1128. tor_addr_t addr;
  1129. /* XXX Duplicate call to tor_addr_parse. */
  1130. if (tor_addr_parse(&addr, socks->address) >= 0) {
  1131. sa_family_t family = tor_addr_family(&addr);
  1132. if ((family == AF_INET && ! conn->ipv4_traffic_ok) ||
  1133. (family == AF_INET6 && ! conn->ipv4_traffic_ok)) {
  1134. log_warn(LD_NET, "Rejecting SOCKS request for an IP address "
  1135. "family that this listener does not support.");
  1136. connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
  1137. return -1;
  1138. } else if (family == AF_INET6 && socks->socks_version == 4) {
  1139. log_warn(LD_NET, "Rejecting SOCKS4 request for an IPv6 address.");
  1140. connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
  1141. return -1;
  1142. } else if (socks->socks_version == 4 && !conn->ipv4_traffic_ok) {
  1143. log_warn(LD_NET, "Rejecting SOCKS4 request on a listener with "
  1144. "no IPv4 traffic supported.");
  1145. connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
  1146. return -1;
  1147. } else if (family == AF_INET6) {
  1148. conn->ipv4_traffic_ok = 0;
  1149. } else if (family == AF_INET) {
  1150. conn->ipv6_traffic_ok = 0;
  1151. }
  1152. }
  1153. }
  1154. if (socks->socks_version == 4)
  1155. conn->ipv6_traffic_ok = 0;
  1156. if (!conn->use_begindir && !conn->chosen_exit_name && !circ) {
  1157. /* see if we can find a suitable enclave exit */
  1158. const node_t *r =
  1159. router_find_exact_exit_enclave(socks->address, socks->port);
  1160. if (r) {
  1161. log_info(LD_APP,
  1162. "Redirecting address %s to exit at enclave router %s",
  1163. safe_str_client(socks->address), node_describe(r));
  1164. /* use the hex digest, not nickname, in case there are two
  1165. routers with this nickname */
  1166. conn->chosen_exit_name =
  1167. tor_strdup(hex_str(r->identity, DIGEST_LEN));
  1168. conn->chosen_exit_optional = 1;
  1169. }
  1170. }
  1171. /* warn or reject if it's using a dangerous port */
  1172. if (!conn->use_begindir && !conn->chosen_exit_name && !circ)
  1173. if (consider_plaintext_ports(conn, socks->port) < 0)
  1174. return -1;
  1175. if (!conn->use_begindir) {
  1176. /* help predict this next time */
  1177. rep_hist_note_used_port(now, socks->port);
  1178. }
  1179. } else if (socks->command == SOCKS_COMMAND_RESOLVE_PTR) {
  1180. rep_hist_note_used_resolve(now); /* help predict this next time */
  1181. /* no extra processing needed */
  1182. } else {
  1183. tor_fragile_assert();
  1184. }
  1185. base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  1186. if ((circ && connection_ap_handshake_attach_chosen_circuit(
  1187. conn, circ, cpath) < 0) ||
  1188. (!circ &&
  1189. connection_ap_handshake_attach_circuit(conn) < 0)) {
  1190. if (!base_conn->marked_for_close)
  1191. connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
  1192. return -1;
  1193. }
  1194. return 0;
  1195. } else {
  1196. /* it's a hidden-service request */
  1197. rend_cache_entry_t *entry;
  1198. int r;
  1199. rend_service_authorization_t *client_auth;
  1200. rend_data_t *rend_data;
  1201. tor_assert(!automap);
  1202. if (SOCKS_COMMAND_IS_RESOLVE(socks->command)) {
  1203. /* if it's a resolve request, fail it right now, rather than
  1204. * building all the circuits and then realizing it won't work. */
  1205. log_warn(LD_APP,
  1206. "Resolve requests to hidden services not allowed. Failing.");
  1207. connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_ERROR,
  1208. 0,NULL,-1,TIME_MAX);
  1209. connection_mark_unattached_ap(conn,
  1210. END_STREAM_REASON_SOCKSPROTOCOL |
  1211. END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
  1212. return -1;
  1213. }
  1214. if (circ) {
  1215. log_warn(LD_CONTROL, "Attachstream to a circuit is not "
  1216. "supported for .onion addresses currently. Failing.");
  1217. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1218. return -1;
  1219. }
  1220. ENTRY_TO_EDGE_CONN(conn)->rend_data = rend_data =
  1221. tor_malloc_zero(sizeof(rend_data_t));
  1222. strlcpy(rend_data->onion_address, socks->address,
  1223. sizeof(rend_data->onion_address));
  1224. log_info(LD_REND,"Got a hidden service request for ID '%s'",
  1225. safe_str_client(rend_data->onion_address));
  1226. /* see if we already have it cached */
  1227. r = rend_cache_lookup_entry(rend_data->onion_address, -1, &entry);
  1228. if (r<0) {
  1229. log_warn(LD_BUG,"Invalid service name '%s'",
  1230. safe_str_client(rend_data->onion_address));
  1231. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  1232. return -1;
  1233. }
  1234. /* Help predict this next time. We're not sure if it will need
  1235. * a stable circuit yet, but we know we'll need *something*. */
  1236. rep_hist_note_used_internal(now, 0, 1);
  1237. /* Look up if we have client authorization for it. */
  1238. client_auth = rend_client_lookup_service_authorization(
  1239. rend_data->onion_address);
  1240. if (client_auth) {
  1241. log_info(LD_REND, "Using previously configured client authorization "
  1242. "for hidden service request.");
  1243. memcpy(rend_data->descriptor_cookie,
  1244. client_auth->descriptor_cookie, REND_DESC_COOKIE_LEN);
  1245. rend_data->auth_type = client_auth->auth_type;
  1246. }
  1247. if (r==0) {
  1248. base_conn->state = AP_CONN_STATE_RENDDESC_WAIT;
  1249. log_info(LD_REND, "Unknown descriptor %s. Fetching.",
  1250. safe_str_client(rend_data->onion_address));
  1251. rend_client_refetch_v2_renddesc(rend_data);
  1252. } else { /* r > 0 */
  1253. base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  1254. log_info(LD_REND, "Descriptor is here. Great.");
  1255. if (connection_ap_handshake_attach_circuit(conn) < 0) {
  1256. if (!base_conn->marked_for_close)
  1257. connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
  1258. return -1;
  1259. }
  1260. }
  1261. return 0;
  1262. }
  1263. return 0; /* unreached but keeps the compiler happy */
  1264. }
  1265. #ifdef TRANS_PF
  1266. static int pf_socket = -1;
  1267. int
  1268. get_pf_socket(void)
  1269. {
  1270. int pf;
  1271. /* This should be opened before dropping privileges. */
  1272. if (pf_socket >= 0)
  1273. return pf_socket;
  1274. #ifdef OPENBSD
  1275. /* only works on OpenBSD */
  1276. pf = tor_open_cloexec("/dev/pf", O_RDONLY, 0);
  1277. #else
  1278. /* works on NetBSD and FreeBSD */
  1279. pf = tor_open_cloexec("/dev/pf", O_RDWR, 0);
  1280. #endif
  1281. if (pf < 0) {
  1282. log_warn(LD_NET, "open(\"/dev/pf\") failed: %s", strerror(errno));
  1283. return -1;
  1284. }
  1285. pf_socket = pf;
  1286. return pf_socket;
  1287. }
  1288. #endif
  1289. /** Fetch the original destination address and port from a
  1290. * system-specific interface and put them into a
  1291. * socks_request_t as if they came from a socks request.
  1292. *
  1293. * Return -1 if an error prevents fetching the destination,
  1294. * else return 0.
  1295. */
  1296. static int
  1297. connection_ap_get_original_destination(entry_connection_t *conn,
  1298. socks_request_t *req)
  1299. {
  1300. #ifdef TRANS_NETFILTER
  1301. /* Linux 2.4+ */
  1302. struct sockaddr_storage orig_dst;
  1303. socklen_t orig_dst_len = sizeof(orig_dst);
  1304. tor_addr_t addr;
  1305. if (getsockopt(ENTRY_TO_CONN(conn)->s, SOL_IP, SO_ORIGINAL_DST,
  1306. (struct sockaddr*)&orig_dst, &orig_dst_len) < 0) {
  1307. int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
  1308. log_warn(LD_NET, "getsockopt() failed: %s", tor_socket_strerror(e));
  1309. return -1;
  1310. }
  1311. tor_addr_from_sockaddr(&addr, (struct sockaddr*)&orig_dst, &req->port);
  1312. tor_addr_to_str(req->address, &addr, sizeof(req->address), 1);
  1313. return 0;
  1314. #elif defined(TRANS_PF)
  1315. struct sockaddr_storage proxy_addr;
  1316. socklen_t proxy_addr_len = sizeof(proxy_addr);
  1317. struct sockaddr *proxy_sa = (struct sockaddr*) &proxy_addr;
  1318. struct pfioc_natlook pnl;
  1319. tor_addr_t addr;
  1320. int pf = -1;
  1321. if (getsockname(ENTRY_TO_CONN(conn)->s, (struct sockaddr*)&proxy_addr,
  1322. &proxy_addr_len) < 0) {
  1323. int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
  1324. log_warn(LD_NET, "getsockname() to determine transocks destination "
  1325. "failed: %s", tor_socket_strerror(e));
  1326. return -1;
  1327. }
  1328. memset(&pnl, 0, sizeof(pnl));
  1329. pnl.proto = IPPROTO_TCP;
  1330. pnl.direction = PF_OUT;
  1331. if (proxy_sa->sa_family == AF_INET) {
  1332. struct sockaddr_in *sin = (struct sockaddr_in *)proxy_sa;
  1333. pnl.af = AF_INET;
  1334. pnl.saddr.v4.s_addr = tor_addr_to_ipv4n(&ENTRY_TO_CONN(conn)->addr);
  1335. pnl.sport = htons(ENTRY_TO_CONN(conn)->port);
  1336. pnl.daddr.v4.s_addr = sin->sin_addr.s_addr;
  1337. pnl.dport = sin->sin_port;
  1338. } else if (proxy_sa->sa_family == AF_INET6) {
  1339. struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)proxy_sa;
  1340. pnl.af = AF_INET6;
  1341. memcpy(&pnl.saddr.v6, tor_addr_to_in6(&ENTRY_TO_CONN(conn)->addr),
  1342. sizeof(struct in6_addr));
  1343. pnl.sport = htons(ENTRY_TO_CONN(conn)->port);
  1344. memcpy(&pnl.daddr.v6, &sin6->sin6_addr, sizeof(struct in6_addr));
  1345. pnl.dport = sin6->sin6_port;
  1346. } else {
  1347. log_warn(LD_NET, "getsockname() gave an unexpected address family (%d)",
  1348. (int)proxy_sa->sa_family);
  1349. return -1;
  1350. }
  1351. pf = get_pf_socket();
  1352. if (pf<0)
  1353. return -1;
  1354. if (ioctl(pf, DIOCNATLOOK, &pnl) < 0) {
  1355. log_warn(LD_NET, "ioctl(DIOCNATLOOK) failed: %s", strerror(errno));
  1356. return -1;
  1357. }
  1358. if (pnl.af == AF_INET) {
  1359. tor_addr_from_ipv4n(&addr, pnl.rdaddr.v4.s_addr);
  1360. } else if (pnl.af == AF_INET6) {
  1361. tor_addr_from_in6(&addr, &pnl.rdaddr.v6);
  1362. } else {
  1363. tor_fragile_assert();
  1364. return -1;
  1365. }
  1366. tor_addr_to_str(req->address, &addr, sizeof(req->address), 1);
  1367. req->port = ntohs(pnl.rdport);
  1368. return 0;
  1369. #else
  1370. (void)conn;
  1371. (void)req;
  1372. log_warn(LD_BUG, "Called connection_ap_get_original_destination, but no "
  1373. "transparent proxy method was configured.");
  1374. return -1;
  1375. #endif
  1376. }
  1377. /** connection_edge_process_inbuf() found a conn in state
  1378. * socks_wait. See if conn->inbuf has the right bytes to proceed with
  1379. * the socks handshake.
  1380. *
  1381. * If the handshake is complete, send it to
  1382. * connection_ap_handshake_rewrite_and_attach().
  1383. *
  1384. * Return -1 if an unexpected error with conn occurs (and mark it for close),
  1385. * else return 0.
  1386. */
  1387. static int
  1388. connection_ap_handshake_process_socks(entry_connection_t *conn)
  1389. {
  1390. socks_request_t *socks;
  1391. int sockshere;
  1392. const or_options_t *options = get_options();
  1393. int had_reply = 0;
  1394. connection_t *base_conn = ENTRY_TO_CONN(conn);
  1395. tor_assert(conn);
  1396. tor_assert(base_conn->type == CONN_TYPE_AP);
  1397. tor_assert(base_conn->state == AP_CONN_STATE_SOCKS_WAIT);
  1398. tor_assert(conn->socks_request);
  1399. socks = conn->socks_request;
  1400. log_debug(LD_APP,"entered.");
  1401. IF_HAS_BUFFEREVENT(base_conn, {
  1402. struct evbuffer *input = bufferevent_get_input(base_conn->bufev);
  1403. sockshere = fetch_from_evbuffer_socks(input, socks,
  1404. options->TestSocks, options->SafeSocks);
  1405. }) ELSE_IF_NO_BUFFEREVENT {
  1406. sockshere = fetch_from_buf_socks(base_conn->inbuf, socks,
  1407. options->TestSocks, options->SafeSocks);
  1408. };
  1409. if (socks->replylen) {
  1410. had_reply = 1;
  1411. connection_write_to_buf((const char*)socks->reply, socks->replylen,
  1412. base_conn);
  1413. socks->replylen = 0;
  1414. if (sockshere == -1) {
  1415. /* An invalid request just got a reply, no additional
  1416. * one is necessary. */
  1417. socks->has_finished = 1;
  1418. }
  1419. }
  1420. if (sockshere == 0) {
  1421. log_debug(LD_APP,"socks handshake not all here yet.");
  1422. return 0;
  1423. } else if (sockshere == -1) {
  1424. if (!had_reply) {
  1425. log_warn(LD_APP,"Fetching socks handshake failed. Closing.");
  1426. connection_ap_handshake_socks_reply(conn, NULL, 0,
  1427. END_STREAM_REASON_SOCKSPROTOCOL);
  1428. }
  1429. connection_mark_unattached_ap(conn,
  1430. END_STREAM_REASON_SOCKSPROTOCOL |
  1431. END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
  1432. return -1;
  1433. } /* else socks handshake is done, continue processing */
  1434. if (SOCKS_COMMAND_IS_CONNECT(socks->command))
  1435. control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
  1436. else
  1437. control_event_stream_status(conn, STREAM_EVENT_NEW_RESOLVE, 0);
  1438. return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
  1439. }
  1440. /** connection_init_accepted_conn() found a new trans AP conn.
  1441. * Get the original destination and send it to
  1442. * connection_ap_handshake_rewrite_and_attach().
  1443. *
  1444. * Return -1 if an unexpected error with conn (and it should be marked
  1445. * for close), else return 0.
  1446. */
  1447. int
  1448. connection_ap_process_transparent(entry_connection_t *conn)
  1449. {
  1450. socks_request_t *socks;
  1451. tor_assert(conn);
  1452. tor_assert(conn->socks_request);
  1453. socks = conn->socks_request;
  1454. /* pretend that a socks handshake completed so we don't try to
  1455. * send a socks reply down a transparent conn */
  1456. socks->command = SOCKS_COMMAND_CONNECT;
  1457. socks->has_finished = 1;
  1458. log_debug(LD_APP,"entered.");
  1459. if (connection_ap_get_original_destination(conn, socks) < 0) {
  1460. log_warn(LD_APP,"Fetching original destination failed. Closing.");
  1461. connection_mark_unattached_ap(conn,
  1462. END_STREAM_REASON_CANT_FETCH_ORIG_DEST);
  1463. return -1;
  1464. }
  1465. /* we have the original destination */
  1466. control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
  1467. return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
  1468. }
  1469. /** connection_edge_process_inbuf() found a conn in state natd_wait. See if
  1470. * conn-\>inbuf has the right bytes to proceed. See FreeBSD's libalias(3) and
  1471. * ProxyEncodeTcpStream() in src/lib/libalias/alias_proxy.c for the encoding
  1472. * form of the original destination.
  1473. *
  1474. * If the original destination is complete, send it to
  1475. * connection_ap_handshake_rewrite_and_attach().
  1476. *
  1477. * Return -1 if an unexpected error with conn (and it should be marked
  1478. * for close), else return 0.
  1479. */
  1480. static int
  1481. connection_ap_process_natd(entry_connection_t *conn)
  1482. {
  1483. char tmp_buf[36], *tbuf, *daddr;
  1484. size_t tlen = 30;
  1485. int err, port_ok;
  1486. socks_request_t *socks;
  1487. tor_assert(conn);
  1488. tor_assert(ENTRY_TO_CONN(conn)->state == AP_CONN_STATE_NATD_WAIT);
  1489. tor_assert(conn->socks_request);
  1490. socks = conn->socks_request;
  1491. log_debug(LD_APP,"entered.");
  1492. /* look for LF-terminated "[DEST ip_addr port]"
  1493. * where ip_addr is a dotted-quad and port is in string form */
  1494. err = connection_fetch_from_buf_line(ENTRY_TO_CONN(conn), tmp_buf, &tlen);
  1495. if (err == 0)
  1496. return 0;
  1497. if (err < 0) {
  1498. log_warn(LD_APP,"NATD handshake failed (DEST too long). Closing");
  1499. connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
  1500. return -1;
  1501. }
  1502. if (strcmpstart(tmp_buf, "[DEST ")) {
  1503. log_warn(LD_APP,"NATD handshake was ill-formed; closing. The client "
  1504. "said: %s",
  1505. escaped(tmp_buf));
  1506. connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
  1507. return -1;
  1508. }
  1509. daddr = tbuf = &tmp_buf[0] + 6; /* after end of "[DEST " */
  1510. if (!(tbuf = strchr(tbuf, ' '))) {
  1511. log_warn(LD_APP,"NATD handshake was ill-formed; closing. The client "
  1512. "said: %s",
  1513. escaped(tmp_buf));
  1514. connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
  1515. return -1;
  1516. }
  1517. *tbuf++ = '\0';
  1518. /* pretend that a socks handshake completed so we don't try to
  1519. * send a socks reply down a natd conn */
  1520. strlcpy(socks->address, daddr, sizeof(socks->address));
  1521. socks->port = (uint16_t)
  1522. tor_parse_long(tbuf, 10, 1, 65535, &port_ok, &daddr);
  1523. if (!port_ok) {
  1524. log_warn(LD_APP,"NATD handshake failed; port %s is ill-formed or out "
  1525. "of range.", escaped(tbuf));
  1526. connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
  1527. return -1;
  1528. }
  1529. socks->command = SOCKS_COMMAND_CONNECT;
  1530. socks->has_finished = 1;
  1531. control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
  1532. ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_CIRCUIT_WAIT;
  1533. return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
  1534. }
  1535. /** Iterate over the two bytes of stream_id until we get one that is not
  1536. * already in use; return it. Return 0 if can't get a unique stream_id.
  1537. */
  1538. streamid_t
  1539. get_unique_stream_id_by_circ(origin_circuit_t *circ)
  1540. {
  1541. edge_connection_t *tmpconn;
  1542. streamid_t test_stream_id;
  1543. uint32_t attempts=0;
  1544. again:
  1545. test_stream_id = circ->next_stream_id++;
  1546. if (++attempts > 1<<16) {
  1547. /* Make sure we don't loop forever if all stream_id's are used. */
  1548. log_warn(LD_APP,"No unused stream IDs. Failing.");
  1549. return 0;
  1550. }
  1551. if (test_stream_id == 0)
  1552. goto again;
  1553. for (tmpconn = circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream)
  1554. if (tmpconn->stream_id == test_stream_id)
  1555. goto again;
  1556. return test_stream_id;
  1557. }
  1558. /** Return true iff <b>conn</b> is linked to a circuit and configured to use
  1559. * an exit that supports optimistic data. */
  1560. static int
  1561. connection_ap_supports_optimistic_data(const entry_connection_t *conn)
  1562. {
  1563. const edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
  1564. /* We can only send optimistic data if we're connected to an open
  1565. general circuit. */
  1566. if (edge_conn->on_circuit == NULL ||
  1567. edge_conn->on_circuit->state != CIRCUIT_STATE_OPEN ||
  1568. edge_conn->on_circuit->purpose != CIRCUIT_PURPOSE_C_GENERAL)
  1569. return 0;
  1570. return conn->may_use_optimistic_data;
  1571. }
  1572. /** Return a bitmask of BEGIN_FLAG_* flags that we should transmit in the
  1573. * RELAY_BEGIN cell for <b>ap_conn</b>. */
  1574. static uint32_t
  1575. connection_ap_get_begincell_flags(entry_connection_t *ap_conn)
  1576. {
  1577. edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
  1578. const node_t *exitnode = NULL;
  1579. const crypt_path_t *cpath_layer = edge_conn->cpath_layer;
  1580. uint32_t flags = 0;
  1581. /* No flags for begindir */
  1582. if (ap_conn->use_begindir)
  1583. return 0;
  1584. /* No flags for hidden services. */
  1585. if (edge_conn->on_circuit->purpose != CIRCUIT_PURPOSE_C_GENERAL)
  1586. return 0;
  1587. /* If only IPv4 is supported, no flags */
  1588. if (ap_conn->ipv4_traffic_ok && !ap_conn->ipv6_traffic_ok)
  1589. return 0;
  1590. if (! cpath_layer ||
  1591. ! cpath_layer->extend_info)
  1592. return 0;
  1593. if (!ap_conn->ipv4_traffic_ok)
  1594. flags |= BEGIN_FLAG_IPV4_NOT_OK;
  1595. exitnode = node_get_by_id(cpath_layer->extend_info->identity_digest);
  1596. if (ap_conn->ipv6_traffic_ok && exitnode) {
  1597. tor_addr_t a;
  1598. tor_addr_make_null(&a, AF_INET6);
  1599. if (compare_tor_addr_to_node_policy(&a, ap_conn->socks_request->port,
  1600. exitnode)
  1601. != ADDR_POLICY_REJECTED) {
  1602. /* Only say "IPv6 OK" if the exit node supports IPv6. Otherwise there's
  1603. * no point. */
  1604. flags |= BEGIN_FLAG_IPV6_OK;
  1605. }
  1606. }
  1607. if (flags == BEGIN_FLAG_IPV6_OK) {
  1608. /* When IPv4 and IPv6 are both allowed, consider whether to say we
  1609. * prefer IPv6. Otherwise there's no point in declaring a preference */
  1610. if (ap_conn->prefer_ipv6_traffic)
  1611. flags |= BEGIN_FLAG_IPV6_PREFERRED;
  1612. }
  1613. if (flags == BEGIN_FLAG_IPV4_NOT_OK) {
  1614. log_warn(LD_EDGE, "I'm about to ask a node for a connection that I "
  1615. "am telling it to fulfil with neither IPv4 nor IPv6. That's "
  1616. "not going to work. Did you perhaps ask for an IPv6 address "
  1617. "on an IPv4Only port, or vice versa?");
  1618. }
  1619. return flags;
  1620. }
  1621. /** Write a relay begin cell, using destaddr and destport from ap_conn's
  1622. * socks_request field, and send it down circ.
  1623. *
  1624. * If ap_conn is broken, mark it for close and return -1. Else return 0.
  1625. */
  1626. int
  1627. connection_ap_handshake_send_begin(entry_connection_t *ap_conn)
  1628. {
  1629. char payload[CELL_PAYLOAD_SIZE];
  1630. int payload_len;
  1631. int begin_type;
  1632. origin_circuit_t *circ;
  1633. edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
  1634. connection_t *base_conn = TO_CONN(edge_conn);
  1635. tor_assert(edge_conn->on_circuit);
  1636. circ = TO_ORIGIN_CIRCUIT(edge_conn->on_circuit);
  1637. tor_assert(base_conn->type == CONN_TYPE_AP);
  1638. tor_assert(base_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
  1639. tor_assert(ap_conn->socks_request);
  1640. tor_assert(SOCKS_COMMAND_IS_CONNECT(ap_conn->socks_request->command));
  1641. edge_conn->stream_id = get_unique_stream_id_by_circ(circ);
  1642. if (edge_conn->stream_id==0) {
  1643. /* XXXX024 Instead of closing this stream, we should make it get
  1644. * retried on another circuit. */
  1645. connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
  1646. /* Mark this circuit "unusable for new streams". */
  1647. mark_circuit_unusable_for_new_conns(circ);
  1648. return -1;
  1649. }
  1650. /* Set up begin cell flags. */
  1651. edge_conn->begincell_flags = connection_ap_get_begincell_flags(ap_conn);
  1652. tor_snprintf(payload,RELAY_PAYLOAD_SIZE, "%s:%d",
  1653. (circ->base_.purpose == CIRCUIT_PURPOSE_C_GENERAL) ?
  1654. ap_conn->socks_request->address : "",
  1655. ap_conn->socks_request->port);
  1656. payload_len = (int)strlen(payload)+1;
  1657. if (payload_len <= RELAY_PAYLOAD_SIZE - 4 && edge_conn->begincell_flags) {
  1658. set_uint32(payload + payload_len, htonl(edge_conn->begincell_flags));
  1659. payload_len += 4;
  1660. }
  1661. log_info(LD_APP,
  1662. "Sending relay cell %d to begin stream %d.",
  1663. (int)ap_conn->use_begindir,
  1664. edge_conn->stream_id);
  1665. begin_type = ap_conn->use_begindir ?
  1666. RELAY_COMMAND_BEGIN_DIR : RELAY_COMMAND_BEGIN;
  1667. if (begin_type == RELAY_COMMAND_BEGIN) {
  1668. #ifndef NON_ANONYMOUS_MODE_ENABLED
  1669. tor_assert(circ->build_state->onehop_tunnel == 0);
  1670. #endif
  1671. }
  1672. if (connection_edge_send_command(edge_conn, begin_type,
  1673. begin_type == RELAY_COMMAND_BEGIN ? payload : NULL,
  1674. begin_type == RELAY_COMMAND_BEGIN ? payload_len : 0) < 0)
  1675. return -1; /* circuit is closed, don't continue */
  1676. edge_conn->package_window = STREAMWINDOW_START;
  1677. edge_conn->deliver_window = STREAMWINDOW_START;
  1678. base_conn->state = AP_CONN_STATE_CONNECT_WAIT;
  1679. log_info(LD_APP,"Address/port sent, ap socket "TOR_SOCKET_T_FORMAT
  1680. ", n_circ_id %u",
  1681. base_conn->s, (unsigned)circ->base_.n_circ_id);
  1682. control_event_stream_status(ap_conn, STREAM_EVENT_SENT_CONNECT, 0);
  1683. /* If there's queued-up data, send it now */
  1684. if ((connection_get_inbuf_len(base_conn) ||
  1685. ap_conn->sending_optimistic_data) &&
  1686. connection_ap_supports_optimistic_data(ap_conn)) {
  1687. log_info(LD_APP, "Sending up to %ld + %ld bytes of queued-up data",
  1688. (long)connection_get_inbuf_len(base_conn),
  1689. ap_conn->sending_optimistic_data ?
  1690. (long)generic_buffer_len(ap_conn->sending_optimistic_data) : 0);
  1691. if (connection_edge_package_raw_inbuf(edge_conn, 1, NULL) < 0) {
  1692. connection_mark_for_close(base_conn);
  1693. }
  1694. }
  1695. return 0;
  1696. }
  1697. /** Write a relay resolve cell, using destaddr and destport from ap_conn's
  1698. * socks_request field, and send it down circ.
  1699. *
  1700. * If ap_conn is broken, mark it for close and return -1. Else return 0.
  1701. */
  1702. int
  1703. connection_ap_handshake_send_resolve(entry_connection_t *ap_conn)
  1704. {
  1705. int payload_len, command;
  1706. const char *string_addr;
  1707. char inaddr_buf[REVERSE_LOOKUP_NAME_BUF_LEN];
  1708. origin_circuit_t *circ;
  1709. edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
  1710. connection_t *base_conn = TO_CONN(edge_conn);
  1711. tor_assert(edge_conn->on_circuit);
  1712. circ = TO_ORIGIN_CIRCUIT(edge_conn->on_circuit);
  1713. tor_assert(base_conn->type == CONN_TYPE_AP);
  1714. tor_assert(base_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
  1715. tor_assert(ap_conn->socks_request);
  1716. tor_assert(circ->base_.purpose == CIRCUIT_PURPOSE_C_GENERAL);
  1717. command = ap_conn->socks_request->command;
  1718. tor_assert(SOCKS_COMMAND_IS_RESOLVE(command));
  1719. edge_conn->stream_id = get_unique_stream_id_by_circ(circ);
  1720. if (edge_conn->stream_id==0) {
  1721. /* XXXX024 Instead of closing this stream, we should make it get
  1722. * retried on another circuit. */
  1723. connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
  1724. /* Mark this circuit "unusable for new streams". */
  1725. mark_circuit_unusable_for_new_conns(circ);
  1726. return -1;
  1727. }
  1728. if (command == SOCKS_COMMAND_RESOLVE) {
  1729. string_addr = ap_conn->socks_request->address;
  1730. payload_len = (int)strlen(string_addr)+1;
  1731. } else {
  1732. /* command == SOCKS_COMMAND_RESOLVE_PTR */
  1733. const char *a = ap_conn->socks_request->address;
  1734. tor_addr_t addr;
  1735. int r;
  1736. /* We're doing a reverse lookup. The input could be an IP address, or
  1737. * could be an .in-addr.arpa or .ip6.arpa address */
  1738. r = tor_addr_parse_PTR_name(&addr, a, AF_UNSPEC, 1);
  1739. if (r <= 0) {
  1740. log_warn(LD_APP, "Rejecting ill-formed reverse lookup of %s",
  1741. safe_str_client(a));
  1742. connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
  1743. return -1;
  1744. }
  1745. r = tor_addr_to_PTR_name(inaddr_buf, sizeof(inaddr_buf), &addr);
  1746. if (r < 0) {
  1747. log_warn(LD_BUG, "Couldn't generate reverse lookup hostname of %s",
  1748. safe_str_client(a));
  1749. connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
  1750. return -1;
  1751. }
  1752. string_addr = inaddr_buf;
  1753. payload_len = (int)strlen(inaddr_buf)+1;
  1754. tor_assert(payload_len <= (int)sizeof(inaddr_buf));
  1755. }
  1756. log_debug(LD_APP,
  1757. "Sending relay cell to begin stream %d.", edge_conn->stream_id);
  1758. if (connection_edge_send_command(edge_conn,
  1759. RELAY_COMMAND_RESOLVE,
  1760. string_addr, payload_len) < 0)
  1761. return -1; /* circuit is closed, don't continue */
  1762. if (!base_conn->address) {
  1763. /* This might be unnecessary. XXXX */
  1764. base_conn->address = tor_dup_addr(&base_conn->addr);
  1765. }
  1766. base_conn->state = AP_CONN_STATE_RESOLVE_WAIT;
  1767. log_info(LD_APP,"Address sent for resolve, ap socket "TOR_SOCKET_T_FORMAT
  1768. ", n_circ_id %u",
  1769. base_conn->s, (unsigned)circ->base_.n_circ_id);
  1770. control_event_stream_status(ap_conn, STREAM_EVENT_SENT_RESOLVE, 0);
  1771. return 0;
  1772. }
  1773. /** Make an AP connection_t linked to the connection_t <b>partner</b>. make a
  1774. * new linked connection pair, and attach one side to the conn, connection_add
  1775. * it, initialize it to circuit_wait, and call
  1776. * connection_ap_handshake_attach_circuit(conn) on it.
  1777. *
  1778. * Return the newly created end of the linked connection pair, or -1 if error.
  1779. */
  1780. entry_connection_t *
  1781. connection_ap_make_link(connection_t *partner,
  1782. char *address, uint16_t port,
  1783. const char *digest,
  1784. int session_group, int isolation_flags,
  1785. int use_begindir, int want_onehop)
  1786. {
  1787. entry_connection_t *conn;
  1788. connection_t *base_conn;
  1789. log_info(LD_APP,"Making internal %s tunnel to %s:%d ...",
  1790. want_onehop ? "direct" : "anonymized",
  1791. safe_str_client(address), port);
  1792. conn = entry_connection_new(CONN_TYPE_AP, tor_addr_family(&partner->addr));
  1793. base_conn = ENTRY_TO_CONN(conn);
  1794. base_conn->linked = 1; /* so that we can add it safely below. */
  1795. /* populate conn->socks_request */
  1796. /* leave version at zero, so the socks_reply is empty */
  1797. conn->socks_request->socks_version = 0;
  1798. conn->socks_request->has_finished = 0; /* waiting for 'connected' */
  1799. strlcpy(conn->socks_request->address, address,
  1800. sizeof(conn->socks_request->address));
  1801. conn->socks_request->port = port;
  1802. conn->socks_request->command = SOCKS_COMMAND_CONNECT;
  1803. conn->want_onehop = want_onehop;
  1804. conn->use_begindir = use_begindir;
  1805. if (use_begindir) {
  1806. conn->chosen_exit_name = tor_malloc(HEX_DIGEST_LEN+2);
  1807. conn->chosen_exit_name[0] = '$';
  1808. tor_assert(digest);
  1809. base16_encode(conn->chosen_exit_name+1,HEX_DIGEST_LEN+1,
  1810. digest, DIGEST_LEN);
  1811. }
  1812. /* Populate isolation fields. */
  1813. conn->socks_request->listener_type = CONN_TYPE_DIR_LISTENER;
  1814. conn->original_dest_address = tor_strdup(address);
  1815. conn->session_group = session_group;
  1816. conn->isolation_flags = isolation_flags;
  1817. base_conn->address = tor_strdup("(Tor_internal)");
  1818. tor_addr_make_unspec(&base_conn->addr);
  1819. base_conn->port = 0;
  1820. connection_link_connections(partner, base_conn);
  1821. if (connection_add(base_conn) < 0) { /* no space, forget it */
  1822. connection_free(base_conn);
  1823. return NULL;
  1824. }
  1825. base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  1826. control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
  1827. /* attaching to a dirty circuit is fine */
  1828. if (connection_ap_handshake_attach_circuit(conn) < 0) {
  1829. if (!base_conn->marked_for_close)
  1830. connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
  1831. return NULL;
  1832. }
  1833. log_info(LD_APP,"... application connection created and linked.");
  1834. return conn;
  1835. }
  1836. /** Notify any interested controller connections about a new hostname resolve
  1837. * or resolve error. Takes the same arguments as does
  1838. * connection_ap_handshake_socks_resolved(). */
  1839. static void
  1840. tell_controller_about_resolved_result(entry_connection_t *conn,
  1841. int answer_type,
  1842. size_t answer_len,
  1843. const char *answer,
  1844. int ttl,
  1845. time_t expires)
  1846. {
  1847. expires = time(NULL) + ttl;
  1848. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len >= 4) {
  1849. char *cp = tor_dup_ip(ntohl(get_uint32(answer)));
  1850. control_event_address_mapped(conn->socks_request->address,
  1851. cp, expires, NULL, 0);
  1852. tor_free(cp);
  1853. } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
  1854. char *cp = tor_strndup(answer, answer_len);
  1855. control_event_address_mapped(conn->socks_request->address,
  1856. cp, expires, NULL, 0);
  1857. tor_free(cp);
  1858. } else {
  1859. control_event_address_mapped(conn->socks_request->address,
  1860. "<error>", time(NULL)+ttl,
  1861. "error=yes", 0);
  1862. }
  1863. }
  1864. /**
  1865. * As connection_ap_handshake_socks_resolved, but take a tor_addr_t to send
  1866. * as the answer.
  1867. */
  1868. static void
  1869. connection_ap_handshake_socks_resolved_addr(entry_connection_t *conn,
  1870. const tor_addr_t *answer,
  1871. int ttl,
  1872. time_t expires)
  1873. {
  1874. if (tor_addr_family(answer) == AF_INET) {
  1875. uint32_t a = tor_addr_to_ipv4n(answer); /* network order */
  1876. connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_IPV4,4,
  1877. (uint8_t*)&a,
  1878. ttl, expires);
  1879. } else if (tor_addr_family(answer) == AF_INET6) {
  1880. const uint8_t *a = tor_addr_to_in6_addr8(answer);
  1881. connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_IPV6,16,
  1882. a,
  1883. ttl, expires);
  1884. } else {
  1885. log_warn(LD_BUG, "Got called with address of unexpected family %d",
  1886. tor_addr_family(answer));
  1887. connection_ap_handshake_socks_resolved(conn,
  1888. RESOLVED_TYPE_ERROR,0,NULL,-1,-1);
  1889. }
  1890. }
  1891. /** Send an answer to an AP connection that has requested a DNS lookup via
  1892. * SOCKS. The type should be one of RESOLVED_TYPE_(IPV4|IPV6|HOSTNAME) or -1
  1893. * for unreachable; the answer should be in the format specified in the socks
  1894. * extensions document. <b>ttl</b> is the ttl for the answer, or -1 on
  1895. * certain errors or for values that didn't come via DNS. <b>expires</b> is
  1896. * a time when the answer expires, or -1 or TIME_MAX if there's a good TTL.
  1897. **/
  1898. /* XXXX the use of the ttl and expires fields is nutty. Let's make this
  1899. * interface and those that use it less ugly. */
  1900. void
  1901. connection_ap_handshake_socks_resolved(entry_connection_t *conn,
  1902. int answer_type,
  1903. size_t answer_len,
  1904. const uint8_t *answer,
  1905. int ttl,
  1906. time_t expires)
  1907. {
  1908. char buf[384];
  1909. size_t replylen;
  1910. if (ttl >= 0) {
  1911. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
  1912. tor_addr_t a;
  1913. tor_addr_from_ipv4n(&a, get_uint32(answer));
  1914. if (! tor_addr_is_null(&a)) {
  1915. client_dns_set_addressmap(conn,
  1916. conn->socks_request->address, &a,
  1917. conn->chosen_exit_name, ttl);
  1918. }
  1919. } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
  1920. tor_addr_t a;
  1921. tor_addr_from_ipv6_bytes(&a, (char*)answer);
  1922. if (! tor_addr_is_null(&a)) {
  1923. client_dns_set_addressmap(conn,
  1924. conn->socks_request->address, &a,
  1925. conn->chosen_exit_name, ttl);
  1926. }
  1927. } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
  1928. char *cp = tor_strndup((char*)answer, answer_len);
  1929. client_dns_set_reverse_addressmap(conn,
  1930. conn->socks_request->address,
  1931. cp,
  1932. conn->chosen_exit_name, ttl);
  1933. tor_free(cp);
  1934. }
  1935. }
  1936. if (ENTRY_TO_EDGE_CONN(conn)->is_dns_request) {
  1937. if (conn->dns_server_request) {
  1938. /* We had a request on our DNS port: answer it. */
  1939. dnsserv_resolved(conn, answer_type, answer_len, (char*)answer, ttl);
  1940. conn->socks_request->has_finished = 1;
  1941. return;
  1942. } else {
  1943. /* This must be a request from the controller. Since answers to those
  1944. * requests are not cached, they do not generate an ADDRMAP event on
  1945. * their own. */
  1946. tell_controller_about_resolved_result(conn, answer_type, answer_len,
  1947. (char*)answer, ttl, expires);
  1948. conn->socks_request->has_finished = 1;
  1949. return;
  1950. }
  1951. /* We shouldn't need to free conn here; it gets marked by the caller. */
  1952. }
  1953. if (conn->socks_request->socks_version == 4) {
  1954. buf[0] = 0x00; /* version */
  1955. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
  1956. buf[1] = SOCKS4_GRANTED;
  1957. set_uint16(buf+2, 0);
  1958. memcpy(buf+4, answer, 4); /* address */
  1959. replylen = SOCKS4_NETWORK_LEN;
  1960. } else { /* "error" */
  1961. buf[1] = SOCKS4_REJECT;
  1962. memset(buf+2, 0, 6);
  1963. replylen = SOCKS4_NETWORK_LEN;
  1964. }
  1965. } else if (conn->socks_request->socks_version == 5) {
  1966. /* SOCKS5 */
  1967. buf[0] = 0x05; /* version */
  1968. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
  1969. buf[1] = SOCKS5_SUCCEEDED;
  1970. buf[2] = 0; /* reserved */
  1971. buf[3] = 0x01; /* IPv4 address type */
  1972. memcpy(buf+4, answer, 4); /* address */
  1973. set_uint16(buf+8, 0); /* port == 0. */
  1974. replylen = 10;
  1975. } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
  1976. buf[1] = SOCKS5_SUCCEEDED;
  1977. buf[2] = 0; /* reserved */
  1978. buf[3] = 0x04; /* IPv6 address type */
  1979. memcpy(buf+4, answer, 16); /* address */
  1980. set_uint16(buf+20, 0); /* port == 0. */
  1981. replylen = 22;
  1982. } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
  1983. buf[1] = SOCKS5_SUCCEEDED;
  1984. buf[2] = 0; /* reserved */
  1985. buf[3] = 0x03; /* Domainname address type */
  1986. buf[4] = (char)answer_len;
  1987. memcpy(buf+5, answer, answer_len); /* address */
  1988. set_uint16(buf+5+answer_len, 0); /* port == 0. */
  1989. replylen = 5+answer_len+2;
  1990. } else {
  1991. buf[1] = SOCKS5_HOST_UNREACHABLE;
  1992. memset(buf+2, 0, 8);
  1993. replylen = 10;
  1994. }
  1995. } else {
  1996. /* no socks version info; don't send anything back */
  1997. return;
  1998. }
  1999. connection_ap_handshake_socks_reply(conn, buf, replylen,
  2000. (answer_type == RESOLVED_TYPE_IPV4 ||
  2001. answer_type == RESOLVED_TYPE_IPV6 ||
  2002. answer_type == RESOLVED_TYPE_HOSTNAME) ?
  2003. 0 : END_STREAM_REASON_RESOLVEFAILED);
  2004. }
  2005. /** Send a socks reply to stream <b>conn</b>, using the appropriate
  2006. * socks version, etc, and mark <b>conn</b> as completed with SOCKS
  2007. * handshaking.
  2008. *
  2009. * If <b>reply</b> is defined, then write <b>replylen</b> bytes of it to conn
  2010. * and return, else reply based on <b>endreason</b> (one of
  2011. * END_STREAM_REASON_*). If <b>reply</b> is undefined, <b>endreason</b> can't
  2012. * be 0 or REASON_DONE. Send endreason to the controller, if appropriate.
  2013. */
  2014. void
  2015. connection_ap_handshake_socks_reply(entry_connection_t *conn, char *reply,
  2016. size_t replylen, int endreason)
  2017. {
  2018. char buf[256];
  2019. socks5_reply_status_t status =
  2020. stream_end_reason_to_socks5_response(endreason);
  2021. tor_assert(conn->socks_request); /* make sure it's an AP stream */
  2022. if (!SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command)) {
  2023. control_event_stream_status(conn, status==SOCKS5_SUCCEEDED ?
  2024. STREAM_EVENT_SUCCEEDED : STREAM_EVENT_FAILED,
  2025. endreason);
  2026. }
  2027. /* Flag this stream's circuit as having completed a stream successfully
  2028. * (for path bias) */
  2029. if (status == SOCKS5_SUCCEEDED ||
  2030. endreason == END_STREAM_REASON_RESOLVEFAILED ||
  2031. endreason == END_STREAM_REASON_CONNECTREFUSED ||
  2032. endreason == END_STREAM_REASON_CONNRESET ||
  2033. endreason == END_STREAM_REASON_NOROUTE ||
  2034. endreason == END_STREAM_REASON_RESOURCELIMIT) {
  2035. if (!conn->edge_.on_circuit ||
  2036. !CIRCUIT_IS_ORIGIN(conn->edge_.on_circuit)) {
  2037. // DNS remaps can trigger this. So can failed hidden service
  2038. // lookups.
  2039. log_info(LD_BUG,
  2040. "No origin circuit for successful SOCKS stream "U64_FORMAT
  2041. ". Reason: %d",
  2042. U64_PRINTF_ARG(ENTRY_TO_CONN(conn)->global_identifier),
  2043. endreason);
  2044. } else {
  2045. // XXX: Hrmm. It looks like optimistic data can't go through this
  2046. // codepath, but someone should probably test it and make sure.
  2047. // We don't want to mark optimistically opened streams as successful.
  2048. pathbias_mark_use_success(TO_ORIGIN_CIRCUIT(conn->edge_.on_circuit));
  2049. }
  2050. }
  2051. if (conn->socks_request->has_finished) {
  2052. log_warn(LD_BUG, "(Harmless.) duplicate calls to "
  2053. "connection_ap_handshake_socks_reply.");
  2054. return;
  2055. }
  2056. if (replylen) { /* we already have a reply in mind */
  2057. connection_write_to_buf(reply, replylen, ENTRY_TO_CONN(conn));
  2058. conn->socks_request->has_finished = 1;
  2059. return;
  2060. }
  2061. if (conn->socks_request->socks_version == 4) {
  2062. memset(buf,0,SOCKS4_NETWORK_LEN);
  2063. buf[1] = (status==SOCKS5_SUCCEEDED ? SOCKS4_GRANTED : SOCKS4_REJECT);
  2064. /* leave version, destport, destip zero */
  2065. connection_write_to_buf(buf, SOCKS4_NETWORK_LEN, ENTRY_TO_CONN(conn));
  2066. } else if (conn->socks_request->socks_version == 5) {
  2067. buf[0] = 5; /* version 5 */
  2068. buf[1] = (char)status;
  2069. buf[2] = 0;
  2070. buf[3] = 1; /* ipv4 addr */
  2071. memset(buf+4,0,6); /* Set external addr/port to 0.
  2072. The spec doesn't seem to say what to do here. -RD */
  2073. connection_write_to_buf(buf,10,ENTRY_TO_CONN(conn));
  2074. }
  2075. /* If socks_version isn't 4 or 5, don't send anything.
  2076. * This can happen in the case of AP bridges. */
  2077. conn->socks_request->has_finished = 1;
  2078. return;
  2079. }
  2080. /** Read a RELAY_BEGIN or RELAY_BEGINDIR cell from <b>cell</b>, decode it, and
  2081. * place the result in <b>bcell</b>. On success return 0; on failure return
  2082. * <0 and set *<b>end_reason_out</b> to the end reason we should send back to
  2083. * the client.
  2084. *
  2085. * Return -1 in the case where want to send a RELAY_END cell, and < -1 when
  2086. * we don't.
  2087. **/
  2088. /* static */ int
  2089. begin_cell_parse(const cell_t *cell, begin_cell_t *bcell,
  2090. uint8_t *end_reason_out)
  2091. {
  2092. relay_header_t rh;
  2093. const uint8_t *body, *nul;
  2094. memset(bcell, 0, sizeof(*bcell));
  2095. *end_reason_out = END_STREAM_REASON_MISC;
  2096. relay_header_unpack(&rh, cell->payload);
  2097. if (rh.length > RELAY_PAYLOAD_SIZE) {
  2098. return -2; /*XXXX why not TORPROTOCOL? */
  2099. }
  2100. bcell->stream_id = rh.stream_id;
  2101. if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
  2102. bcell->is_begindir = 1;
  2103. return 0;
  2104. } else if (rh.command != RELAY_COMMAND_BEGIN) {
  2105. log_warn(LD_BUG, "Got an unexpected command %d", (int)rh.command);
  2106. *end_reason_out = END_STREAM_REASON_INTERNAL;
  2107. return -1;
  2108. }
  2109. body = cell->payload + RELAY_HEADER_SIZE;
  2110. nul = memchr(body, 0, rh.length);
  2111. if (! nul) {
  2112. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  2113. "Relay begin cell has no \\0. Closing.");
  2114. *end_reason_out = END_STREAM_REASON_TORPROTOCOL;
  2115. return -1;
  2116. }
  2117. if (tor_addr_port_split(LOG_PROTOCOL_WARN,
  2118. (char*)(body),
  2119. &bcell->address,&bcell->port)<0) {
  2120. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  2121. "Unable to parse addr:port in relay begin cell. Closing.");
  2122. *end_reason_out = END_STREAM_REASON_TORPROTOCOL;
  2123. return -1;
  2124. }
  2125. if (bcell->port == 0) {
  2126. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  2127. "Missing port in relay begin cell. Closing.");
  2128. tor_free(bcell->address);
  2129. *end_reason_out = END_STREAM_REASON_TORPROTOCOL;
  2130. return -1;
  2131. }
  2132. if (body + rh.length >= nul + 4)
  2133. bcell->flags = ntohl(get_uint32(nul+1));
  2134. return 0;
  2135. }
  2136. /** A relay 'begin' or 'begin_dir' cell has arrived, and either we are
  2137. * an exit hop for the circuit, or we are the origin and it is a
  2138. * rendezvous begin.
  2139. *
  2140. * Launch a new exit connection and initialize things appropriately.
  2141. *
  2142. * If it's a rendezvous stream, call connection_exit_connect() on
  2143. * it.
  2144. *
  2145. * For general streams, call dns_resolve() on it first, and only call
  2146. * connection_exit_connect() if the dns answer is already known.
  2147. *
  2148. * Note that we don't call connection_add() on the new stream! We wait
  2149. * for connection_exit_connect() to do that.
  2150. *
  2151. * Return -(some circuit end reason) if we want to tear down <b>circ</b>.
  2152. * Else return 0.
  2153. */
  2154. int
  2155. connection_exit_begin_conn(cell_t *cell, circuit_t *circ)
  2156. {
  2157. edge_connection_t *n_stream;
  2158. relay_header_t rh;
  2159. char *address = NULL;
  2160. uint16_t port = 0;
  2161. or_circuit_t *or_circ = NULL;
  2162. const or_options_t *options = get_options();
  2163. begin_cell_t bcell;
  2164. int r;
  2165. uint8_t end_reason=0;
  2166. assert_circuit_ok(circ);
  2167. if (!CIRCUIT_IS_ORIGIN(circ))
  2168. or_circ = TO_OR_CIRCUIT(circ);
  2169. relay_header_unpack(&rh, cell->payload);
  2170. if (rh.length > RELAY_PAYLOAD_SIZE)
  2171. return -1;
  2172. /* Note: we have to use relay_send_command_from_edge here, not
  2173. * connection_edge_end or connection_edge_send_command, since those require
  2174. * that we have a stream connected to a circuit, and we don't connect to a
  2175. * circuit until we have a pending/successful resolve. */
  2176. if (!server_mode(options) &&
  2177. circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
  2178. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  2179. "Relay begin cell at non-server. Closing.");
  2180. relay_send_end_cell_from_edge(rh.stream_id, circ,
  2181. END_STREAM_REASON_EXITPOLICY, NULL);
  2182. return 0;
  2183. }
  2184. r = begin_cell_parse(cell, &bcell, &end_reason);
  2185. if (r < -1) {
  2186. return -1;
  2187. } else if (r == -1) {
  2188. tor_free(bcell.address);
  2189. relay_send_end_cell_from_edge(rh.stream_id, circ, end_reason, NULL);
  2190. return 0;
  2191. }
  2192. if (! bcell.is_begindir) {
  2193. /* Steal reference */
  2194. address = bcell.address;
  2195. port = bcell.port;
  2196. if (or_circ && or_circ->p_chan) {
  2197. if (!options->AllowSingleHopExits &&
  2198. (or_circ->is_first_hop ||
  2199. (!connection_or_digest_is_known_relay(
  2200. or_circ->p_chan->identity_digest) &&
  2201. should_refuse_unknown_exits(options)))) {
  2202. /* Don't let clients use us as a single-hop proxy, unless the user
  2203. * has explicitly allowed that in the config. It attracts attackers
  2204. * and users who'd be better off with, well, single-hop proxies.
  2205. */
  2206. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  2207. "Attempt by %s to open a stream %s. Closing.",
  2208. safe_str(channel_get_canonical_remote_descr(or_circ->p_chan)),
  2209. or_circ->is_first_hop ? "on first hop of circuit" :
  2210. "from unknown relay");
  2211. relay_send_end_cell_from_edge(rh.stream_id, circ,
  2212. or_circ->is_first_hop ?
  2213. END_STREAM_REASON_TORPROTOCOL :
  2214. END_STREAM_REASON_MISC,
  2215. NULL);
  2216. tor_free(address);
  2217. return 0;
  2218. }
  2219. }
  2220. } else if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
  2221. if (!directory_permits_begindir_requests(options) ||
  2222. circ->purpose != CIRCUIT_PURPOSE_OR) {
  2223. relay_send_end_cell_from_edge(rh.stream_id, circ,
  2224. END_STREAM_REASON_NOTDIRECTORY, NULL);
  2225. return 0;
  2226. }
  2227. /* Make sure to get the 'real' address of the previous hop: the
  2228. * caller might want to know whether his IP address has changed, and
  2229. * we might already have corrected base_.addr[ess] for the relay's
  2230. * canonical IP address. */
  2231. if (or_circ && or_circ->p_chan)
  2232. address = tor_strdup(channel_get_actual_remote_address(or_circ->p_chan));
  2233. else
  2234. address = tor_strdup("127.0.0.1");
  2235. port = 1; /* XXXX This value is never actually used anywhere, and there
  2236. * isn't "really" a connection here. But we
  2237. * need to set it to something nonzero. */
  2238. } else {
  2239. log_warn(LD_BUG, "Got an unexpected command %d", (int)rh.command);
  2240. relay_send_end_cell_from_edge(rh.stream_id, circ,
  2241. END_STREAM_REASON_INTERNAL, NULL);
  2242. return 0;
  2243. }
  2244. if (! options->IPv6Exit) {
  2245. /* I don't care if you prefer IPv6; I can't give you any. */
  2246. bcell.flags &= ~BEGIN_FLAG_IPV6_PREFERRED;
  2247. /* If you don't want IPv4, I can't help. */
  2248. if (bcell.flags & BEGIN_FLAG_IPV4_NOT_OK) {
  2249. tor_free(address);
  2250. relay_send_end_cell_from_edge(rh.stream_id, circ,
  2251. END_STREAM_REASON_EXITPOLICY, NULL);
  2252. return 0;
  2253. }
  2254. }
  2255. log_debug(LD_EXIT,"Creating new exit connection.");
  2256. /* The 'AF_INET' here is temporary; we might need to change it later in
  2257. * connection_exit_connect(). */
  2258. n_stream = edge_connection_new(CONN_TYPE_EXIT, AF_INET);
  2259. /* Remember the tunneled request ID in the new edge connection, so that
  2260. * we can measure download times. */
  2261. n_stream->dirreq_id = circ->dirreq_id;
  2262. n_stream->base_.purpose = EXIT_PURPOSE_CONNECT;
  2263. n_stream->begincell_flags = bcell.flags;
  2264. n_stream->stream_id = rh.stream_id;
  2265. n_stream->base_.port = port;
  2266. /* leave n_stream->s at -1, because it's not yet valid */
  2267. n_stream->package_window = STREAMWINDOW_START;
  2268. n_stream->deliver_window = STREAMWINDOW_START;
  2269. if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED) {
  2270. origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
  2271. log_info(LD_REND,"begin is for rendezvous. configuring stream.");
  2272. n_stream->base_.address = tor_strdup("(rendezvous)");
  2273. n_stream->base_.state = EXIT_CONN_STATE_CONNECTING;
  2274. n_stream->rend_data = rend_data_dup(origin_circ->rend_data);
  2275. tor_assert(connection_edge_is_rendezvous_stream(n_stream));
  2276. assert_circuit_ok(circ);
  2277. if (rend_service_set_connection_addr_port(n_stream, origin_circ) < 0) {
  2278. log_info(LD_REND,"Didn't find rendezvous service (port %d)",
  2279. n_stream->base_.port);
  2280. relay_send_end_cell_from_edge(rh.stream_id, circ,
  2281. END_STREAM_REASON_EXITPOLICY,
  2282. origin_circ->cpath->prev);
  2283. connection_free(TO_CONN(n_stream));
  2284. tor_free(address);
  2285. return 0;
  2286. }
  2287. assert_circuit_ok(circ);
  2288. log_debug(LD_REND,"Finished assigning addr/port");
  2289. n_stream->cpath_layer = origin_circ->cpath->prev; /* link it */
  2290. /* add it into the linked list of p_streams on this circuit */
  2291. n_stream->next_stream = origin_circ->p_streams;
  2292. n_stream->on_circuit = circ;
  2293. origin_circ->p_streams = n_stream;
  2294. assert_circuit_ok(circ);
  2295. connection_exit_connect(n_stream);
  2296. /* For path bias: This circuit was used successfully */
  2297. pathbias_mark_use_success(origin_circ);
  2298. tor_free(address);
  2299. return 0;
  2300. }
  2301. tor_strlower(address);
  2302. n_stream->base_.address = address;
  2303. n_stream->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
  2304. /* default to failed, change in dns_resolve if it turns out not to fail */
  2305. if (we_are_hibernating()) {
  2306. relay_send_end_cell_from_edge(rh.stream_id, circ,
  2307. END_STREAM_REASON_HIBERNATING, NULL);
  2308. connection_free(TO_CONN(n_stream));
  2309. return 0;
  2310. }
  2311. n_stream->on_circuit = circ;
  2312. if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
  2313. tor_addr_t tmp_addr;
  2314. tor_assert(or_circ);
  2315. if (or_circ->p_chan &&
  2316. channel_get_addr_if_possible(or_circ->p_chan, &tmp_addr)) {
  2317. tor_addr_copy(&n_stream->base_.addr, &tmp_addr);
  2318. }
  2319. return connection_exit_connect_dir(n_stream);
  2320. }
  2321. log_debug(LD_EXIT,"about to start the dns_resolve().");
  2322. /* send it off to the gethostbyname farm */
  2323. switch (dns_resolve(n_stream)) {
  2324. case 1: /* resolve worked; now n_stream is attached to circ. */
  2325. assert_circuit_ok(circ);
  2326. log_debug(LD_EXIT,"about to call connection_exit_connect().");
  2327. connection_exit_connect(n_stream);
  2328. return 0;
  2329. case -1: /* resolve failed */
  2330. relay_send_end_cell_from_edge(rh.stream_id, circ,
  2331. END_STREAM_REASON_RESOLVEFAILED, NULL);
  2332. /* n_stream got freed. don't touch it. */
  2333. break;
  2334. case 0: /* resolve added to pending list */
  2335. assert_circuit_ok(circ);
  2336. break;
  2337. }
  2338. return 0;
  2339. }
  2340. /**
  2341. * Called when we receive a RELAY_COMMAND_RESOLVE cell 'cell' along the
  2342. * circuit <b>circ</b>;
  2343. * begin resolving the hostname, and (eventually) reply with a RESOLVED cell.
  2344. */
  2345. int
  2346. connection_exit_begin_resolve(cell_t *cell, or_circuit_t *circ)
  2347. {
  2348. edge_connection_t *dummy_conn;
  2349. relay_header_t rh;
  2350. assert_circuit_ok(TO_CIRCUIT(circ));
  2351. relay_header_unpack(&rh, cell->payload);
  2352. if (rh.length > RELAY_PAYLOAD_SIZE)
  2353. return -1;
  2354. /* This 'dummy_conn' only exists to remember the stream ID
  2355. * associated with the resolve request; and to make the
  2356. * implementation of dns.c more uniform. (We really only need to
  2357. * remember the circuit, the stream ID, and the hostname to be
  2358. * resolved; but if we didn't store them in a connection like this,
  2359. * the housekeeping in dns.c would get way more complicated.)
  2360. */
  2361. dummy_conn = edge_connection_new(CONN_TYPE_EXIT, AF_INET);
  2362. dummy_conn->stream_id = rh.stream_id;
  2363. dummy_conn->base_.address = tor_strndup(
  2364. (char*)cell->payload+RELAY_HEADER_SIZE,
  2365. rh.length);
  2366. dummy_conn->base_.port = 0;
  2367. dummy_conn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
  2368. dummy_conn->base_.purpose = EXIT_PURPOSE_RESOLVE;
  2369. dummy_conn->on_circuit = TO_CIRCUIT(circ);
  2370. /* send it off to the gethostbyname farm */
  2371. switch (dns_resolve(dummy_conn)) {
  2372. case -1: /* Impossible to resolve; a resolved cell was sent. */
  2373. /* Connection freed; don't touch it. */
  2374. return 0;
  2375. case 1: /* The result was cached; a resolved cell was sent. */
  2376. if (!dummy_conn->base_.marked_for_close)
  2377. connection_free(TO_CONN(dummy_conn));
  2378. return 0;
  2379. case 0: /* resolve added to pending list */
  2380. assert_circuit_ok(TO_CIRCUIT(circ));
  2381. break;
  2382. }
  2383. return 0;
  2384. }
  2385. /** Connect to conn's specified addr and port. If it worked, conn
  2386. * has now been added to the connection_array.
  2387. *
  2388. * Send back a connected cell. Include the resolved IP of the destination
  2389. * address, but <em>only</em> if it's a general exit stream. (Rendezvous
  2390. * streams must not reveal what IP they connected to.)
  2391. */
  2392. void
  2393. connection_exit_connect(edge_connection_t *edge_conn)
  2394. {
  2395. const tor_addr_t *addr;
  2396. uint16_t port;
  2397. connection_t *conn = TO_CONN(edge_conn);
  2398. int socket_error = 0;
  2399. if ( (!connection_edge_is_rendezvous_stream(edge_conn) &&
  2400. router_compare_to_my_exit_policy(&edge_conn->base_.addr,
  2401. edge_conn->base_.port)) ||
  2402. (tor_addr_family(&conn->addr) == AF_INET6 &&
  2403. ! get_options()->IPv6Exit)) {
  2404. log_info(LD_EXIT,"%s:%d failed exit policy. Closing.",
  2405. escaped_safe_str_client(conn->address), conn->port);
  2406. connection_edge_end(edge_conn, END_STREAM_REASON_EXITPOLICY);
  2407. circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
  2408. connection_free(conn);
  2409. return;
  2410. }
  2411. addr = &conn->addr;
  2412. port = conn->port;
  2413. if (tor_addr_family(addr) == AF_INET6)
  2414. conn->socket_family = AF_INET6;
  2415. log_debug(LD_EXIT,"about to try connecting");
  2416. switch (connection_connect(conn, conn->address, addr, port, &socket_error)) {
  2417. case -1: {
  2418. int reason = errno_to_stream_end_reason(socket_error);
  2419. connection_edge_end(edge_conn, reason);
  2420. circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
  2421. connection_free(conn);
  2422. return;
  2423. }
  2424. case 0:
  2425. conn->state = EXIT_CONN_STATE_CONNECTING;
  2426. connection_watch_events(conn, READ_EVENT | WRITE_EVENT);
  2427. /* writable indicates finish;
  2428. * readable/error indicates broken link in windows-land. */
  2429. return;
  2430. /* case 1: fall through */
  2431. }
  2432. conn->state = EXIT_CONN_STATE_OPEN;
  2433. if (connection_get_outbuf_len(conn)) {
  2434. /* in case there are any queued data cells, from e.g. optimistic data */
  2435. IF_HAS_NO_BUFFEREVENT(conn)
  2436. connection_watch_events(conn, READ_EVENT|WRITE_EVENT);
  2437. } else {
  2438. IF_HAS_NO_BUFFEREVENT(conn)
  2439. connection_watch_events(conn, READ_EVENT);
  2440. }
  2441. /* also, deliver a 'connected' cell back through the circuit. */
  2442. if (connection_edge_is_rendezvous_stream(edge_conn)) {
  2443. /* rendezvous stream */
  2444. /* don't send an address back! */
  2445. connection_edge_send_command(edge_conn,
  2446. RELAY_COMMAND_CONNECTED,
  2447. NULL, 0);
  2448. } else { /* normal stream */
  2449. uint8_t connected_payload[MAX_CONNECTED_CELL_PAYLOAD_LEN];
  2450. int connected_payload_len =
  2451. connected_cell_format_payload(connected_payload, &conn->addr,
  2452. edge_conn->address_ttl);
  2453. if (connected_payload_len < 0) {
  2454. connection_edge_end(edge_conn, END_STREAM_REASON_INTERNAL);
  2455. circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
  2456. connection_free(conn);
  2457. return;
  2458. }
  2459. connection_edge_send_command(edge_conn,
  2460. RELAY_COMMAND_CONNECTED,
  2461. (char*)connected_payload,
  2462. connected_payload_len);
  2463. }
  2464. }
  2465. /** Given an exit conn that should attach to us as a directory server, open a
  2466. * bridge connection with a linked connection pair, create a new directory
  2467. * conn, and join them together. Return 0 on success (or if there was an
  2468. * error we could send back an end cell for). Return -(some circuit end
  2469. * reason) if the circuit needs to be torn down. Either connects
  2470. * <b>exitconn</b>, frees it, or marks it, as appropriate.
  2471. */
  2472. static int
  2473. connection_exit_connect_dir(edge_connection_t *exitconn)
  2474. {
  2475. dir_connection_t *dirconn = NULL;
  2476. or_circuit_t *circ = TO_OR_CIRCUIT(exitconn->on_circuit);
  2477. log_info(LD_EXIT, "Opening local connection for anonymized directory exit");
  2478. exitconn->base_.state = EXIT_CONN_STATE_OPEN;
  2479. dirconn = dir_connection_new(tor_addr_family(&exitconn->base_.addr));
  2480. tor_addr_copy(&dirconn->base_.addr, &exitconn->base_.addr);
  2481. dirconn->base_.port = 0;
  2482. dirconn->base_.address = tor_strdup(exitconn->base_.address);
  2483. dirconn->base_.type = CONN_TYPE_DIR;
  2484. dirconn->base_.purpose = DIR_PURPOSE_SERVER;
  2485. dirconn->base_.state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
  2486. /* Note that the new dir conn belongs to the same tunneled request as
  2487. * the edge conn, so that we can measure download times. */
  2488. dirconn->dirreq_id = exitconn->dirreq_id;
  2489. connection_link_connections(TO_CONN(dirconn), TO_CONN(exitconn));
  2490. if (connection_add(TO_CONN(exitconn))<0) {
  2491. connection_edge_end(exitconn, END_STREAM_REASON_RESOURCELIMIT);
  2492. connection_free(TO_CONN(exitconn));
  2493. connection_free(TO_CONN(dirconn));
  2494. return 0;
  2495. }
  2496. /* link exitconn to circ, now that we know we can use it. */
  2497. exitconn->next_stream = circ->n_streams;
  2498. circ->n_streams = exitconn;
  2499. if (connection_add(TO_CONN(dirconn))<0) {
  2500. connection_edge_end(exitconn, END_STREAM_REASON_RESOURCELIMIT);
  2501. connection_close_immediate(TO_CONN(exitconn));
  2502. connection_mark_for_close(TO_CONN(exitconn));
  2503. connection_free(TO_CONN(dirconn));
  2504. return 0;
  2505. }
  2506. connection_start_reading(TO_CONN(dirconn));
  2507. connection_start_reading(TO_CONN(exitconn));
  2508. if (connection_edge_send_command(exitconn,
  2509. RELAY_COMMAND_CONNECTED, NULL, 0) < 0) {
  2510. connection_mark_for_close(TO_CONN(exitconn));
  2511. connection_mark_for_close(TO_CONN(dirconn));
  2512. return 0;
  2513. }
  2514. return 0;
  2515. }
  2516. /** Return 1 if <b>conn</b> is a rendezvous stream, or 0 if
  2517. * it is a general stream.
  2518. */
  2519. int
  2520. connection_edge_is_rendezvous_stream(edge_connection_t *conn)
  2521. {
  2522. tor_assert(conn);
  2523. if (conn->rend_data)
  2524. return 1;
  2525. return 0;
  2526. }
  2527. /** Return 1 if router <b>exit</b> is likely to allow stream <b>conn</b>
  2528. * to exit from it, or 0 if it probably will not allow it.
  2529. * (We might be uncertain if conn's destination address has not yet been
  2530. * resolved.)
  2531. */
  2532. int
  2533. connection_ap_can_use_exit(const entry_connection_t *conn, const node_t *exit)
  2534. {
  2535. const or_options_t *options = get_options();
  2536. tor_assert(conn);
  2537. tor_assert(conn->socks_request);
  2538. tor_assert(exit);
  2539. /* If a particular exit node has been requested for the new connection,
  2540. * make sure the exit node of the existing circuit matches exactly.
  2541. */
  2542. if (conn->chosen_exit_name) {
  2543. const node_t *chosen_exit =
  2544. node_get_by_nickname(conn->chosen_exit_name, 1);
  2545. if (!chosen_exit || tor_memneq(chosen_exit->identity,
  2546. exit->identity, DIGEST_LEN)) {
  2547. /* doesn't match */
  2548. // log_debug(LD_APP,"Requested node '%s', considering node '%s'. No.",
  2549. // conn->chosen_exit_name, exit->nickname);
  2550. return 0;
  2551. }
  2552. }
  2553. if (conn->use_begindir) {
  2554. /* Internal directory fetches do not count as exiting. */
  2555. return 1;
  2556. }
  2557. if (conn->socks_request->command == SOCKS_COMMAND_CONNECT) {
  2558. tor_addr_t addr, *addrp = NULL;
  2559. addr_policy_result_t r;
  2560. if (0 == tor_addr_parse(&addr, conn->socks_request->address)) {
  2561. addrp = &addr;
  2562. } else if (!conn->ipv4_traffic_ok && conn->ipv6_traffic_ok) {
  2563. tor_addr_make_null(&addr, AF_INET6);
  2564. addrp = &addr;
  2565. } else if (conn->ipv4_traffic_ok && !conn->ipv6_traffic_ok) {
  2566. tor_addr_make_null(&addr, AF_INET);
  2567. addrp = &addr;
  2568. }
  2569. r = compare_tor_addr_to_node_policy(addrp, conn->socks_request->port,exit);
  2570. if (r == ADDR_POLICY_REJECTED)
  2571. return 0; /* We know the address, and the exit policy rejects it. */
  2572. if (r == ADDR_POLICY_PROBABLY_REJECTED && !conn->chosen_exit_name)
  2573. return 0; /* We don't know the addr, but the exit policy rejects most
  2574. * addresses with this port. Since the user didn't ask for
  2575. * this node, err on the side of caution. */
  2576. } else if (SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command)) {
  2577. /* Don't send DNS requests to non-exit servers by default. */
  2578. if (!conn->chosen_exit_name && node_exit_policy_rejects_all(exit))
  2579. return 0;
  2580. }
  2581. if (routerset_contains_node(options->ExcludeExitNodesUnion_, exit)) {
  2582. /* Not a suitable exit. Refuse it. */
  2583. return 0;
  2584. }
  2585. return 1;
  2586. }
  2587. /** If address is of the form "y.onion" with a well-formed handle y:
  2588. * Put a NUL after y, lower-case it, and return ONION_HOSTNAME.
  2589. *
  2590. * If address is of the form "x.y.onion" with a well-formed handle x:
  2591. * Drop "x.", put a NUL after y, lower-case it, and return ONION_HOSTNAME.
  2592. *
  2593. * If address is of the form "y.onion" with a badly-formed handle y:
  2594. * Return BAD_HOSTNAME and log a message.
  2595. *
  2596. * If address is of the form "y.exit":
  2597. * Put a NUL after y and return EXIT_HOSTNAME.
  2598. *
  2599. * Otherwise:
  2600. * Return NORMAL_HOSTNAME and change nothing.
  2601. */
  2602. hostname_type_t
  2603. parse_extended_hostname(char *address)
  2604. {
  2605. char *s;
  2606. char *q;
  2607. char query[REND_SERVICE_ID_LEN_BASE32+1];
  2608. s = strrchr(address,'.');
  2609. if (!s)
  2610. return NORMAL_HOSTNAME; /* no dot, thus normal */
  2611. if (!strcmp(s+1,"exit")) {
  2612. *s = 0; /* NUL-terminate it */
  2613. return EXIT_HOSTNAME; /* .exit */
  2614. }
  2615. if (strcmp(s+1,"onion"))
  2616. return NORMAL_HOSTNAME; /* neither .exit nor .onion, thus normal */
  2617. /* so it is .onion */
  2618. *s = 0; /* NUL-terminate it */
  2619. /* locate a 'sub-domain' component, in order to remove it */
  2620. q = strrchr(address, '.');
  2621. if (q == address) {
  2622. goto failed; /* reject sub-domain, as DNS does */
  2623. }
  2624. q = (NULL == q) ? address : q + 1;
  2625. if (strlcpy(query, q, REND_SERVICE_ID_LEN_BASE32+1) >=
  2626. REND_SERVICE_ID_LEN_BASE32+1)
  2627. goto failed;
  2628. if (q != address) {
  2629. memmove(address, q, strlen(q) + 1 /* also get \0 */);
  2630. }
  2631. if (rend_valid_service_id(query)) {
  2632. return ONION_HOSTNAME; /* success */
  2633. }
  2634. failed:
  2635. /* otherwise, return to previous state and return 0 */
  2636. *s = '.';
  2637. log_warn(LD_APP, "Invalid onion hostname %s; rejecting",
  2638. safe_str_client(address));
  2639. return BAD_HOSTNAME;
  2640. }
  2641. /** Return true iff the (possibly NULL) <b>alen</b>-byte chunk of memory at
  2642. * <b>a</b> is equal to the (possibly NULL) <b>blen</b>-byte chunk of memory
  2643. * at <b>b</b>. */
  2644. static int
  2645. memeq_opt(const char *a, size_t alen, const char *b, size_t blen)
  2646. {
  2647. if (a == NULL) {
  2648. return (b == NULL);
  2649. } else if (b == NULL) {
  2650. return 0;
  2651. } else if (alen != blen) {
  2652. return 0;
  2653. } else {
  2654. return tor_memeq(a, b, alen);
  2655. }
  2656. }
  2657. /**
  2658. * Return true iff none of the isolation flags and fields in <b>conn</b>
  2659. * should prevent it from being attached to <b>circ</b>.
  2660. */
  2661. int
  2662. connection_edge_compatible_with_circuit(const entry_connection_t *conn,
  2663. const origin_circuit_t *circ)
  2664. {
  2665. const uint8_t iso = conn->isolation_flags;
  2666. const socks_request_t *sr = conn->socks_request;
  2667. /* If circ has never been used for an isolated connection, we can
  2668. * totally use it for this one. */
  2669. if (!circ->isolation_values_set)
  2670. return 1;
  2671. /* If circ has been used for connections having more than one value
  2672. * for some field f, it will have the corresponding bit set in
  2673. * isolation_flags_mixed. If isolation_flags_mixed has any bits
  2674. * in common with iso, then conn must be isolated from at least
  2675. * one stream that has been attached to circ. */
  2676. if ((iso & circ->isolation_flags_mixed) != 0) {
  2677. /* For at least one field where conn is isolated, the circuit
  2678. * already has mixed streams. */
  2679. return 0;
  2680. }
  2681. if (! conn->original_dest_address) {
  2682. log_warn(LD_BUG, "Reached connection_edge_compatible_with_circuit without "
  2683. "having set conn->original_dest_address");
  2684. ((entry_connection_t*)conn)->original_dest_address =
  2685. tor_strdup(conn->socks_request->address);
  2686. }
  2687. if ((iso & ISO_STREAM) &&
  2688. (circ->associated_isolated_stream_global_id !=
  2689. ENTRY_TO_CONN(conn)->global_identifier))
  2690. return 0;
  2691. if ((iso & ISO_DESTPORT) && conn->socks_request->port != circ->dest_port)
  2692. return 0;
  2693. if ((iso & ISO_DESTADDR) &&
  2694. strcasecmp(conn->original_dest_address, circ->dest_address))
  2695. return 0;
  2696. if ((iso & ISO_SOCKSAUTH) &&
  2697. (! memeq_opt(sr->username, sr->usernamelen,
  2698. circ->socks_username, circ->socks_username_len) ||
  2699. ! memeq_opt(sr->password, sr->passwordlen,
  2700. circ->socks_password, circ->socks_password_len)))
  2701. return 0;
  2702. if ((iso & ISO_CLIENTPROTO) &&
  2703. (conn->socks_request->listener_type != circ->client_proto_type ||
  2704. conn->socks_request->socks_version != circ->client_proto_socksver))
  2705. return 0;
  2706. if ((iso & ISO_CLIENTADDR) &&
  2707. !tor_addr_eq(&ENTRY_TO_CONN(conn)->addr, &circ->client_addr))
  2708. return 0;
  2709. if ((iso & ISO_SESSIONGRP) && conn->session_group != circ->session_group)
  2710. return 0;
  2711. if ((iso & ISO_NYM_EPOCH) && conn->nym_epoch != circ->nym_epoch)
  2712. return 0;
  2713. return 1;
  2714. }
  2715. /**
  2716. * If <b>dry_run</b> is false, update <b>circ</b>'s isolation flags and fields
  2717. * to reflect having had <b>conn</b> attached to it, and return 0. Otherwise,
  2718. * if <b>dry_run</b> is true, then make no changes to <b>circ</b>, and return
  2719. * a bitfield of isolation flags that we would have to set in
  2720. * isolation_flags_mixed to add <b>conn</b> to <b>circ</b>, or -1 if
  2721. * <b>circ</b> has had no streams attached to it.
  2722. */
  2723. int
  2724. connection_edge_update_circuit_isolation(const entry_connection_t *conn,
  2725. origin_circuit_t *circ,
  2726. int dry_run)
  2727. {
  2728. const socks_request_t *sr = conn->socks_request;
  2729. if (! conn->original_dest_address) {
  2730. log_warn(LD_BUG, "Reached connection_update_circuit_isolation without "
  2731. "having set conn->original_dest_address");
  2732. ((entry_connection_t*)conn)->original_dest_address =
  2733. tor_strdup(conn->socks_request->address);
  2734. }
  2735. if (!circ->isolation_values_set) {
  2736. if (dry_run)
  2737. return -1;
  2738. circ->associated_isolated_stream_global_id =
  2739. ENTRY_TO_CONN(conn)->global_identifier;
  2740. circ->dest_port = conn->socks_request->port;
  2741. circ->dest_address = tor_strdup(conn->original_dest_address);
  2742. circ->client_proto_type = conn->socks_request->listener_type;
  2743. circ->client_proto_socksver = conn->socks_request->socks_version;
  2744. tor_addr_copy(&circ->client_addr, &ENTRY_TO_CONN(conn)->addr);
  2745. circ->session_group = conn->session_group;
  2746. circ->nym_epoch = conn->nym_epoch;
  2747. circ->socks_username = sr->username ?
  2748. tor_memdup(sr->username, sr->usernamelen) : NULL;
  2749. circ->socks_password = sr->password ?
  2750. tor_memdup(sr->password, sr->passwordlen) : NULL;
  2751. circ->socks_username_len = sr->usernamelen;
  2752. circ->socks_password_len = sr->passwordlen;
  2753. circ->isolation_values_set = 1;
  2754. return 0;
  2755. } else {
  2756. uint8_t mixed = 0;
  2757. if (conn->socks_request->port != circ->dest_port)
  2758. mixed |= ISO_DESTPORT;
  2759. if (strcasecmp(conn->original_dest_address, circ->dest_address))
  2760. mixed |= ISO_DESTADDR;
  2761. if (!memeq_opt(sr->username, sr->usernamelen,
  2762. circ->socks_username, circ->socks_username_len) ||
  2763. !memeq_opt(sr->password, sr->passwordlen,
  2764. circ->socks_password, circ->socks_password_len))
  2765. mixed |= ISO_SOCKSAUTH;
  2766. if ((conn->socks_request->listener_type != circ->client_proto_type ||
  2767. conn->socks_request->socks_version != circ->client_proto_socksver))
  2768. mixed |= ISO_CLIENTPROTO;
  2769. if (!tor_addr_eq(&ENTRY_TO_CONN(conn)->addr, &circ->client_addr))
  2770. mixed |= ISO_CLIENTADDR;
  2771. if (conn->session_group != circ->session_group)
  2772. mixed |= ISO_SESSIONGRP;
  2773. if (conn->nym_epoch != circ->nym_epoch)
  2774. mixed |= ISO_NYM_EPOCH;
  2775. if (dry_run)
  2776. return mixed;
  2777. if ((mixed & conn->isolation_flags) != 0) {
  2778. log_warn(LD_BUG, "Updating a circuit with seemingly incompatible "
  2779. "isolation flags.");
  2780. }
  2781. circ->isolation_flags_mixed |= mixed;
  2782. return 0;
  2783. }
  2784. }
  2785. /**
  2786. * Clear the isolation settings on <b>circ</b>.
  2787. *
  2788. * This only works on an open circuit that has never had a stream attached to
  2789. * it, and whose isolation settings are hypothetical. (We set hypothetical
  2790. * isolation settings on circuits as we're launching them, so that we
  2791. * know whether they can handle more streams or whether we need to launch
  2792. * even more circuits. Once the circuit is open, if it turns out that
  2793. * we no longer have any streams to attach to it, we clear the isolation flags
  2794. * and data so that other streams can have a chance.)
  2795. */
  2796. void
  2797. circuit_clear_isolation(origin_circuit_t *circ)
  2798. {
  2799. if (circ->isolation_any_streams_attached) {
  2800. log_warn(LD_BUG, "Tried to clear the isolation status of a dirty circuit");
  2801. return;
  2802. }
  2803. if (TO_CIRCUIT(circ)->state != CIRCUIT_STATE_OPEN) {
  2804. log_warn(LD_BUG, "Tried to clear the isolation status of a non-open "
  2805. "circuit");
  2806. return;
  2807. }
  2808. circ->isolation_values_set = 0;
  2809. circ->isolation_flags_mixed = 0;
  2810. circ->associated_isolated_stream_global_id = 0;
  2811. circ->client_proto_type = 0;
  2812. circ->client_proto_socksver = 0;
  2813. circ->dest_port = 0;
  2814. tor_addr_make_unspec(&circ->client_addr);
  2815. tor_free(circ->dest_address);
  2816. circ->session_group = -1;
  2817. circ->nym_epoch = 0;
  2818. if (circ->socks_username) {
  2819. memwipe(circ->socks_username, 0x11, circ->socks_username_len);
  2820. tor_free(circ->socks_username);
  2821. }
  2822. if (circ->socks_password) {
  2823. memwipe(circ->socks_password, 0x05, circ->socks_password_len);
  2824. tor_free(circ->socks_password);
  2825. }
  2826. circ->socks_username_len = circ->socks_password_len = 0;
  2827. }