connection_edge.c 94 KB

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