connection_edge.c 65 KB

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