connection_edge.c 71 KB

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