connection_edge.c 61 KB

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