connection_edge.c 106 KB

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