connection_edge.c 78 KB

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