connection_edge.c 94 KB

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