connection_edge.c 114 KB

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