connection_edge.c 113 KB

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