connection_edge.c 71 KB

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