connection_edge.c 85 KB

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