connection_edge.c 90 KB

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