connection_edge.c 116 KB

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