connection_edge.c 104 KB

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