connection_edge.c 117 KB

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