connection_edge.c 132 KB

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