connection_edge.c 113 KB

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