connection_edge.c 105 KB

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