connection_edge.c 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191
  1. /* Copyright 2001 Matej Pfajfar, 2001-2004 Roger Dingledine. */
  2. /* See LICENSE for licensing information */
  3. /* $Id$ */
  4. /**
  5. * \file connection_edge.c
  6. * \brief Handle edge streams.
  7. **/
  8. #include "or.h"
  9. #include "tree.h"
  10. extern or_options_t options; /* command-line and config-file options */
  11. extern char *conn_state_to_string[][_CONN_TYPE_MAX+1]; /* from connection.c */
  12. static struct exit_policy_t *socks_policy = NULL;
  13. static int connection_ap_handshake_process_socks(connection_t *conn);
  14. static void parse_socks_policy(void);
  15. /** Handle new bytes on conn->inbuf, or notification of eof.
  16. *
  17. * If there was an EOF, then send an end and mark the connection
  18. * for close.
  19. *
  20. * Otherwise handle it based on state:
  21. * - If it's waiting for socks info, try to read another step of the
  22. * socks handshake out of conn->inbuf.
  23. * - If it's open, then package more relay cells from the stream.
  24. * - Else, leave the bytes on inbuf alone for now.
  25. *
  26. * Mark and return -1 if there was an unexpected error with the conn,
  27. * else return 0.
  28. */
  29. int connection_edge_process_inbuf(connection_t *conn) {
  30. tor_assert(conn);
  31. tor_assert(conn->type == CONN_TYPE_AP || conn->type == CONN_TYPE_EXIT);
  32. if(conn->inbuf_reached_eof) {
  33. #ifdef HALF_OPEN
  34. /* eof reached; we're done reading, but we might want to write more. */
  35. conn->done_receiving = 1;
  36. shutdown(conn->s, 0); /* XXX check return, refactor NM */
  37. if (conn->done_sending) {
  38. connection_edge_end(conn, END_STREAM_REASON_DONE, conn->cpath_layer);
  39. connection_mark_for_close(conn);
  40. } else {
  41. connection_edge_send_command(conn, circuit_get_by_conn(conn), RELAY_COMMAND_END,
  42. NULL, 0, conn->cpath_layer);
  43. }
  44. return 0;
  45. #else
  46. /* eof reached, kill it. */
  47. log_fn(LOG_INFO,"conn (fd %d) reached eof. Closing.", conn->s);
  48. connection_edge_end(conn, END_STREAM_REASON_DONE, conn->cpath_layer);
  49. if(!conn->marked_for_close) {
  50. /* only mark it if not already marked. it's possible to
  51. * get the 'end' right around when the client hangs up on us. */
  52. connection_mark_for_close(conn);
  53. }
  54. conn->hold_open_until_flushed = 1; /* just because we shouldn't read
  55. doesn't mean we shouldn't write */
  56. return 0;
  57. #endif
  58. }
  59. switch(conn->state) {
  60. case AP_CONN_STATE_SOCKS_WAIT:
  61. if(connection_ap_handshake_process_socks(conn) < 0) {
  62. conn->has_sent_end = 1; /* no circ yet */
  63. connection_mark_for_close(conn);
  64. conn->hold_open_until_flushed = 1;
  65. return -1;
  66. }
  67. return 0;
  68. case AP_CONN_STATE_OPEN:
  69. case EXIT_CONN_STATE_OPEN:
  70. if(conn->package_window <= 0) {
  71. /* XXX this is still getting called rarely :( */
  72. log_fn(LOG_WARN,"called with package_window %d. Tell Roger.", conn->package_window);
  73. return 0;
  74. }
  75. if(connection_edge_package_raw_inbuf(conn) < 0) {
  76. connection_edge_end(conn, END_STREAM_REASON_MISC, conn->cpath_layer);
  77. connection_mark_for_close(conn);
  78. return -1;
  79. }
  80. return 0;
  81. case EXIT_CONN_STATE_CONNECTING:
  82. case AP_CONN_STATE_RENDDESC_WAIT:
  83. case AP_CONN_STATE_CIRCUIT_WAIT:
  84. case AP_CONN_STATE_CONNECT_WAIT:
  85. log_fn(LOG_INFO,"data from edge while in '%s' state. Leaving it on buffer.",
  86. conn_state_to_string[conn->type][conn->state]);
  87. return 0;
  88. }
  89. log_fn(LOG_WARN,"Got unexpected state %d. Closing.",conn->state);
  90. connection_edge_end(conn, END_STREAM_REASON_MISC, conn->cpath_layer);
  91. connection_mark_for_close(conn);
  92. return -1;
  93. }
  94. /** This edge needs to be closed, because its circuit has closed.
  95. * Mark it for close and return 0.
  96. */
  97. int connection_edge_destroy(uint16_t circ_id, connection_t *conn) {
  98. tor_assert(conn->type == CONN_TYPE_AP || conn->type == CONN_TYPE_EXIT);
  99. if(conn->marked_for_close)
  100. return 0; /* already marked; probably got an 'end' */
  101. log_fn(LOG_INFO,"CircID %d: At an edge. Marking connection for close.",
  102. circ_id);
  103. conn->has_sent_end = 1; /* we're closing the circuit, nothing to send to */
  104. connection_mark_for_close(conn);
  105. conn->hold_open_until_flushed = 1;
  106. return 0;
  107. }
  108. /** Send a relay end cell from stream <b>conn</b> to conn's circuit,
  109. * with a destination of cpath_layer. (If cpath_layer is NULL, the
  110. * destination is the circuit's origin.) Mark the relay end cell as
  111. * closing because of <b>reason</b>.
  112. *
  113. * Return -1 if this function has already been called on this conn,
  114. * else return 0.
  115. */
  116. int
  117. connection_edge_end(connection_t *conn, char reason, crypt_path_t *cpath_layer)
  118. {
  119. char payload[5];
  120. size_t payload_len=1;
  121. circuit_t *circ;
  122. if(conn->has_sent_end) {
  123. log_fn(LOG_WARN,"It appears I've already sent the end. Are you calling me twice?");
  124. return -1;
  125. }
  126. payload[0] = reason;
  127. if(reason == END_STREAM_REASON_EXITPOLICY) {
  128. /* this is safe even for rend circs, because they never fail
  129. * because of exitpolicy */
  130. set_uint32(payload+1, htonl(conn->addr));
  131. payload_len += 4;
  132. }
  133. circ = circuit_get_by_conn(conn);
  134. if(circ && !circ->marked_for_close) {
  135. log_fn(LOG_DEBUG,"Marking conn (fd %d) and sending end.",conn->s);
  136. connection_edge_send_command(conn, circ, RELAY_COMMAND_END,
  137. payload, payload_len, cpath_layer);
  138. } else {
  139. log_fn(LOG_DEBUG,"Marking conn (fd %d); no circ to send end.",conn->s);
  140. }
  141. conn->has_sent_end = 1;
  142. return 0;
  143. }
  144. /** Connection <b>conn</b> has finished writing and has no bytes left on
  145. * its outbuf.
  146. *
  147. * If it's in state 'open', stop writing, consider responding with a
  148. * sendme, and return.
  149. * Otherwise, stop writing and return.
  150. *
  151. * If <b>conn</b> is broken, mark it for close and return -1, else
  152. * return 0.
  153. */
  154. int connection_edge_finished_flushing(connection_t *conn) {
  155. tor_assert(conn);
  156. tor_assert(conn->type == CONN_TYPE_AP || conn->type == CONN_TYPE_EXIT);
  157. switch(conn->state) {
  158. case AP_CONN_STATE_OPEN:
  159. case EXIT_CONN_STATE_OPEN:
  160. connection_stop_writing(conn);
  161. connection_edge_consider_sending_sendme(conn);
  162. return 0;
  163. case AP_CONN_STATE_SOCKS_WAIT:
  164. case AP_CONN_STATE_RENDDESC_WAIT:
  165. case AP_CONN_STATE_CIRCUIT_WAIT:
  166. case AP_CONN_STATE_CONNECT_WAIT:
  167. connection_stop_writing(conn);
  168. return 0;
  169. default:
  170. log_fn(LOG_WARN,"BUG: called in unexpected state %d.", conn->state);
  171. return -1;
  172. }
  173. return 0;
  174. }
  175. /** Connected handler for exit connections: start writing pending
  176. * data, deliver 'CONNECTED' relay cells as appropriate, and check
  177. * any pending data that may have been received. */
  178. int connection_edge_finished_connecting(connection_t *conn)
  179. {
  180. unsigned char connected_payload[4];
  181. tor_assert(conn);
  182. tor_assert(conn->type == CONN_TYPE_EXIT);
  183. tor_assert(conn->state == EXIT_CONN_STATE_CONNECTING);
  184. log_fn(LOG_INFO,"Exit connection to %s:%u established.",
  185. conn->address,conn->port);
  186. conn->state = EXIT_CONN_STATE_OPEN;
  187. connection_watch_events(conn, POLLIN); /* stop writing, continue reading */
  188. if(connection_wants_to_flush(conn)) /* in case there are any queued relay cells */
  189. connection_start_writing(conn);
  190. /* deliver a 'connected' relay cell back through the circuit. */
  191. if(connection_edge_is_rendezvous_stream(conn)) {
  192. if(connection_edge_send_command(conn, circuit_get_by_conn(conn),
  193. RELAY_COMMAND_CONNECTED, NULL, 0, conn->cpath_layer) < 0)
  194. return 0; /* circuit is closed, don't continue */
  195. } else {
  196. *(uint32_t*)connected_payload = htonl(conn->addr);
  197. if(connection_edge_send_command(conn, circuit_get_by_conn(conn),
  198. RELAY_COMMAND_CONNECTED, connected_payload, 4, conn->cpath_layer) < 0)
  199. return 0; /* circuit is closed, don't continue */
  200. }
  201. tor_assert(conn->package_window > 0);
  202. return connection_edge_process_inbuf(conn); /* in case the server has written anything */
  203. }
  204. /** How many times do we retry a general-purpose stream (detach it from
  205. * one circuit and try another, after we wait a while with no 'connected'
  206. * cell) before giving up?
  207. */
  208. #define MAX_STREAM_RETRIES 4
  209. /** Find all general-purpose AP streams in state connect_wait that sent
  210. * their begin cell >=15 seconds ago. Detach from their current circuit,
  211. * and mark their current circuit as unsuitable for new streams. Then call
  212. * connection_ap_handshake_attach_circuit() to attach to a new circuit (if
  213. * available) or launch a new one.
  214. *
  215. * For rendezvous streams, simply give up after 45 seconds (with no
  216. * retry attempt).
  217. */
  218. void connection_ap_expire_beginning(void) {
  219. connection_t **carray;
  220. connection_t *conn;
  221. circuit_t *circ;
  222. int n, i;
  223. time_t now = time(NULL);
  224. get_connection_array(&carray, &n);
  225. for (i = 0; i < n; ++i) {
  226. conn = carray[i];
  227. if (conn->type != CONN_TYPE_AP ||
  228. conn->state != AP_CONN_STATE_CONNECT_WAIT)
  229. continue;
  230. if (now - conn->timestamp_lastread < 15)
  231. continue;
  232. conn->num_retries++;
  233. circ = circuit_get_by_conn(conn);
  234. if(!circ) { /* it's vanished? */
  235. log_fn(LOG_INFO,"Conn is in connect-wait, but lost its circ.");
  236. connection_mark_for_close(conn);
  237. continue;
  238. }
  239. if(circ->purpose == CIRCUIT_PURPOSE_C_REND_JOINED) {
  240. if (now - conn->timestamp_lastread > 45) {
  241. log_fn(LOG_WARN,"Rend stream is %d seconds late. Giving up.",
  242. (int)(now - conn->timestamp_lastread));
  243. connection_edge_end(conn, END_STREAM_REASON_TIMEOUT, conn->cpath_layer);
  244. connection_mark_for_close(conn);
  245. }
  246. continue;
  247. }
  248. tor_assert(circ->purpose == CIRCUIT_PURPOSE_C_GENERAL);
  249. if(conn->num_retries >= MAX_STREAM_RETRIES) {
  250. log_fn(LOG_WARN,"Stream is %d seconds late. Giving up.",
  251. 15*conn->num_retries);
  252. circuit_log_path(LOG_WARN, circ);
  253. connection_edge_end(conn, END_STREAM_REASON_TIMEOUT, conn->cpath_layer);
  254. connection_mark_for_close(conn);
  255. } else {
  256. log_fn(LOG_WARN,"Stream is %d seconds late. Retrying.",
  257. (int)(now - conn->timestamp_lastread));
  258. circuit_log_path(LOG_WARN, circ);
  259. /* send an end down the circuit */
  260. connection_edge_end(conn, END_STREAM_REASON_TIMEOUT, conn->cpath_layer);
  261. /* un-mark it as ending, since we're going to reuse it */
  262. conn->has_sent_end = 0;
  263. /* move it back into 'pending' state. */
  264. conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  265. circuit_detach_stream(circ, conn);
  266. /* kludge to make us not try this circuit again, yet to allow
  267. * current streams on it to survive if they can: make it
  268. * unattractive to use for new streams */
  269. tor_assert(circ->timestamp_dirty);
  270. circ->timestamp_dirty -= options.NewCircuitPeriod;
  271. /* give our stream another 15 seconds to try */
  272. conn->timestamp_lastread += 15;
  273. /* attaching to a dirty circuit is fine */
  274. if(connection_ap_handshake_attach_circuit(conn)<0) {
  275. /* it will never work */
  276. /* Don't need to send end -- we're not connected */
  277. conn->has_sent_end = 1;
  278. connection_mark_for_close(conn);
  279. }
  280. } /* end if max_retries */
  281. } /* end for */
  282. }
  283. /** Tell any AP streamss that are waiting for a new circuit that one is
  284. * available.
  285. */
  286. void connection_ap_attach_pending(void)
  287. {
  288. connection_t **carray;
  289. connection_t *conn;
  290. int n, i;
  291. get_connection_array(&carray, &n);
  292. for (i = 0; i < n; ++i) {
  293. conn = carray[i];
  294. if (conn->marked_for_close ||
  295. conn->type != CONN_TYPE_AP ||
  296. conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
  297. continue;
  298. if(connection_ap_handshake_attach_circuit(conn) < 0) {
  299. /* -1 means it will never work */
  300. /* Don't send end; there is no 'other side' yet */
  301. conn->has_sent_end = 1;
  302. connection_mark_for_close(conn);
  303. }
  304. }
  305. }
  306. /** connection_edge_process_inbuf() found a conn in state
  307. * socks_wait. See if conn->inbuf has the right bytes to proceed with
  308. * the socks handshake.
  309. *
  310. * If the handshake is complete, and it's for a general circuit, then
  311. * try to attach it to a circuit (or launch one as needed). If it's for
  312. * a rendezvous circuit, then fetch a rendezvous descriptor first (or
  313. * attach/launch a circuit if the rendezvous descriptor is already here
  314. * and fresh enough).
  315. *
  316. * Return -1 if an unexpected error with conn (and it should be marked
  317. * for close), else return 0.
  318. */
  319. static int connection_ap_handshake_process_socks(connection_t *conn) {
  320. socks_request_t *socks;
  321. int sockshere;
  322. tor_assert(conn);
  323. tor_assert(conn->type == CONN_TYPE_AP);
  324. tor_assert(conn->state == AP_CONN_STATE_SOCKS_WAIT);
  325. tor_assert(conn->socks_request);
  326. socks = conn->socks_request;
  327. log_fn(LOG_DEBUG,"entered.");
  328. sockshere = fetch_from_buf_socks(conn->inbuf, socks);
  329. if(sockshere == -1 || sockshere == 0) {
  330. if(socks->replylen) { /* we should send reply back */
  331. log_fn(LOG_DEBUG,"reply is already set for us. Using it.");
  332. connection_ap_handshake_socks_reply(conn, socks->reply, socks->replylen, 0);
  333. } else if(sockshere == -1) { /* send normal reject */
  334. log_fn(LOG_WARN,"Fetching socks handshake failed. Closing.");
  335. connection_ap_handshake_socks_reply(conn, NULL, 0, 0);
  336. } else {
  337. log_fn(LOG_DEBUG,"socks handshake not all here yet.");
  338. }
  339. if (sockshere == -1)
  340. socks->has_finished = 1;
  341. return sockshere;
  342. } /* else socks handshake is done, continue processing */
  343. if (socks->command == SOCKS_COMMAND_RESOLVE) {
  344. uint32_t answer;
  345. /* Reply to resolves immediately if we can. */
  346. if (strlen(socks->address) > RELAY_PAYLOAD_SIZE) {
  347. connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_ERROR,0,NULL);
  348. conn->socks_request->has_finished = 1;
  349. conn->has_sent_end = 1;
  350. connection_mark_for_close(conn);
  351. conn->hold_open_until_flushed = 1;
  352. return 0;
  353. }
  354. answer = htonl(client_dns_lookup_entry(socks->address));
  355. if (answer) {
  356. connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_IPV4,4,
  357. (char*)&answer);
  358. conn->socks_request->has_finished = 1;
  359. conn->has_sent_end = 1;
  360. connection_mark_for_close(conn);
  361. conn->hold_open_until_flushed = 1;
  362. return 0;
  363. }
  364. }
  365. /* this call _modifies_ socks->address iff it's a hidden-service request */
  366. if (rend_parse_rendezvous_address(socks->address) < 0) {
  367. /* normal request */
  368. conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  369. return connection_ap_handshake_attach_circuit(conn);
  370. } else {
  371. /* it's a hidden-service request */
  372. rend_cache_entry_t *entry;
  373. int r;
  374. if (socks->command == SOCKS_COMMAND_RESOLVE) {
  375. /* if it's a resolve request, fail it right now, rather than
  376. * building all the circuits and then realizing it won't work. */
  377. connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_ERROR,0,NULL);
  378. conn->socks_request->has_finished = 1;
  379. conn->has_sent_end = 1;
  380. connection_mark_for_close(conn);
  381. conn->hold_open_until_flushed = 1;
  382. return 0;
  383. }
  384. strlcpy(conn->rend_query, socks->address, sizeof(conn->rend_query));
  385. log_fn(LOG_INFO,"Got a hidden service request for ID '%s'", conn->rend_query);
  386. /* see if we already have it cached */
  387. r = rend_cache_lookup_entry(conn->rend_query, &entry);
  388. if(r<0) {
  389. log_fn(LOG_WARN,"Invalid service descriptor %s", conn->rend_query);
  390. return -1;
  391. }
  392. if(r==0) {
  393. conn->state = AP_CONN_STATE_RENDDESC_WAIT;
  394. log_fn(LOG_INFO, "Unknown descriptor %s. Fetching.", conn->rend_query);
  395. rend_client_refetch_renddesc(conn->rend_query);
  396. return 0;
  397. }
  398. if(r>0) {
  399. #define NUM_SECONDS_BEFORE_REFETCH (60*15)
  400. if(time(NULL) - entry->received < NUM_SECONDS_BEFORE_REFETCH) {
  401. conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  402. log_fn(LOG_INFO, "Descriptor is here and fresh enough. Great.");
  403. return connection_ap_handshake_attach_circuit(conn);
  404. } else {
  405. conn->state = AP_CONN_STATE_RENDDESC_WAIT;
  406. log_fn(LOG_INFO, "Stale descriptor %s. Refetching.", conn->rend_query);
  407. rend_client_refetch_renddesc(conn->rend_query);
  408. return 0;
  409. }
  410. }
  411. }
  412. return 0;
  413. }
  414. /** Iterate over the two bytes of stream_id until we get one that is not
  415. * already in use; return it. Return 0 if can't get a unique stream_id.
  416. */
  417. static uint16_t get_unique_stream_id_by_circ(circuit_t *circ) {
  418. connection_t *tmpconn;
  419. uint16_t test_stream_id;
  420. uint32_t attempts=0;
  421. again:
  422. test_stream_id = circ->next_stream_id++;
  423. if(++attempts > 1<<16) {
  424. /* Make sure we don't loop forever if all stream_id's are used. */
  425. log_fn(LOG_WARN,"No unused stream IDs. Failing.");
  426. return 0;
  427. }
  428. if (test_stream_id == 0)
  429. goto again;
  430. for(tmpconn = circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream)
  431. if(tmpconn->stream_id == test_stream_id)
  432. goto again;
  433. return test_stream_id;
  434. }
  435. /** Write a relay begin cell, using destaddr and destport from ap_conn's
  436. * socks_request field, and send it down circ.
  437. *
  438. * If ap_conn is broken, mark it for close and return -1. Else return 0.
  439. */
  440. int connection_ap_handshake_send_begin(connection_t *ap_conn, circuit_t *circ)
  441. {
  442. char payload[CELL_PAYLOAD_SIZE];
  443. int payload_len;
  444. struct in_addr in;
  445. const char *string_addr;
  446. tor_assert(ap_conn->type == CONN_TYPE_AP);
  447. tor_assert(ap_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
  448. tor_assert(ap_conn->socks_request);
  449. ap_conn->stream_id = get_unique_stream_id_by_circ(circ);
  450. if (ap_conn->stream_id==0) {
  451. /* Don't send end: there is no 'other side' yet */
  452. ap_conn->has_sent_end = 1;
  453. connection_mark_for_close(ap_conn);
  454. circuit_mark_for_close(circ);
  455. return -1;
  456. }
  457. if(circ->purpose == CIRCUIT_PURPOSE_C_GENERAL) {
  458. in.s_addr = htonl(client_dns_lookup_entry(ap_conn->socks_request->address));
  459. string_addr = in.s_addr ? inet_ntoa(in) : NULL;
  460. tor_snprintf(payload,RELAY_PAYLOAD_SIZE,
  461. "%s:%d",
  462. string_addr ? string_addr : ap_conn->socks_request->address,
  463. ap_conn->socks_request->port);
  464. } else {
  465. tor_snprintf(payload,RELAY_PAYLOAD_SIZE,
  466. ":%d", ap_conn->socks_request->port);
  467. }
  468. payload_len = strlen(payload)+1;
  469. log_fn(LOG_DEBUG,"Sending relay cell to begin stream %d.",ap_conn->stream_id);
  470. if(connection_edge_send_command(ap_conn, circ, RELAY_COMMAND_BEGIN,
  471. payload, payload_len, ap_conn->cpath_layer) < 0)
  472. return -1; /* circuit is closed, don't continue */
  473. ap_conn->package_window = STREAMWINDOW_START;
  474. ap_conn->deliver_window = STREAMWINDOW_START;
  475. ap_conn->state = AP_CONN_STATE_CONNECT_WAIT;
  476. log_fn(LOG_INFO,"Address/port sent, ap socket %d, n_circ_id %d",ap_conn->s,circ->n_circ_id);
  477. return 0;
  478. }
  479. /** Write a relay resolve cell, using destaddr and destport from ap_conn's
  480. * socks_request field, and send it down circ.
  481. *
  482. * If ap_conn is broken, mark it for close and return -1. Else return 0.
  483. */
  484. int connection_ap_handshake_send_resolve(connection_t *ap_conn, circuit_t *circ)
  485. {
  486. int payload_len;
  487. const char *string_addr;
  488. tor_assert(ap_conn->type == CONN_TYPE_AP);
  489. tor_assert(ap_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
  490. tor_assert(ap_conn->socks_request);
  491. tor_assert(ap_conn->socks_request->command == SOCKS_COMMAND_RESOLVE);
  492. tor_assert(circ->purpose == CIRCUIT_PURPOSE_C_GENERAL);
  493. ap_conn->stream_id = get_unique_stream_id_by_circ(circ);
  494. if (ap_conn->stream_id==0) {
  495. /* Don't send end: there is no 'other side' yet */
  496. ap_conn->has_sent_end = 1;
  497. connection_mark_for_close(ap_conn);
  498. circuit_mark_for_close(circ);
  499. return -1;
  500. }
  501. string_addr = ap_conn->socks_request->address;
  502. payload_len = strlen(string_addr);
  503. tor_assert(strlen(string_addr) <= RELAY_PAYLOAD_SIZE);
  504. log_fn(LOG_DEBUG,"Sending relay cell to begin stream %d.",ap_conn->stream_id);
  505. if(connection_edge_send_command(ap_conn, circ, RELAY_COMMAND_RESOLVE,
  506. string_addr, payload_len, ap_conn->cpath_layer) < 0)
  507. return -1; /* circuit is closed, don't continue */
  508. ap_conn->state = AP_CONN_STATE_RESOLVE_WAIT;
  509. log_fn(LOG_INFO,"Address sent for resolve, ap socket %d, n_circ_id %d",ap_conn->s,circ->n_circ_id);
  510. return 0;
  511. }
  512. /** Make an AP connection_t, do a socketpair and attach one side
  513. * to the conn, connection_add it, initialize it to circuit_wait,
  514. * and call connection_ap_handshake_attach_circuit(conn) on it.
  515. *
  516. * Return the other end of the socketpair, or -1 if error.
  517. */
  518. int connection_ap_make_bridge(char *address, uint16_t port) {
  519. int fd[2];
  520. connection_t *conn;
  521. log_fn(LOG_INFO,"Making AP bridge to %s:%d ...",address,port);
  522. if(tor_socketpair(AF_UNIX, SOCK_STREAM, 0, fd) < 0) {
  523. log(LOG_WARN,"Couldn't construct socketpair (%s). Network down? Delaying.",
  524. tor_socket_strerror(tor_socket_errno(-1)));
  525. return -1;
  526. }
  527. set_socket_nonblocking(fd[0]);
  528. set_socket_nonblocking(fd[1]);
  529. conn = connection_new(CONN_TYPE_AP);
  530. conn->s = fd[0];
  531. /* populate conn->socks_request */
  532. /* leave version at zero, so the socks_reply is empty */
  533. conn->socks_request->socks_version = 0;
  534. conn->socks_request->has_finished = 0; /* waiting for 'connected' */
  535. strlcpy(conn->socks_request->address, address,
  536. sizeof(conn->socks_request->address));
  537. conn->socks_request->port = port;
  538. conn->socks_request->command = SOCKS_COMMAND_CONNECT;
  539. conn->address = tor_strdup("(local bridge)");
  540. conn->addr = 0;
  541. conn->port = 0;
  542. if(connection_add(conn) < 0) { /* no space, forget it */
  543. connection_free(conn); /* this closes fd[0] */
  544. tor_close_socket(fd[1]);
  545. return -1;
  546. }
  547. conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  548. connection_start_reading(conn);
  549. /* attaching to a dirty circuit is fine */
  550. if (connection_ap_handshake_attach_circuit(conn) < 0) {
  551. conn->has_sent_end = 1; /* no circ to send to */
  552. connection_mark_for_close(conn);
  553. tor_close_socket(fd[1]);
  554. return -1;
  555. }
  556. log_fn(LOG_INFO,"... AP bridge created and connected.");
  557. return fd[1];
  558. }
  559. void connection_ap_handshake_socks_resolved(connection_t *conn,
  560. int answer_type,
  561. size_t answer_len,
  562. const char *answer)
  563. {
  564. char buf[256];
  565. size_t replylen;
  566. if (answer_type == RESOLVED_TYPE_IPV4) {
  567. uint32_t a = get_uint32(answer);
  568. if(a)
  569. client_dns_set_entry(conn->socks_request->address, ntohl(a));
  570. }
  571. if (conn->socks_request->socks_version == 4) {
  572. buf[0] = 0x00; /* version */
  573. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
  574. buf[1] = 90; /* "Granted" */
  575. set_uint16(buf+2, 0);
  576. memcpy(buf+4, answer, 4); /* address */
  577. replylen = SOCKS4_NETWORK_LEN;
  578. } else {
  579. buf[1] = 91; /* "error" */
  580. memset(buf+2, 0, 6);
  581. replylen = SOCKS4_NETWORK_LEN;
  582. }
  583. } else {
  584. /* SOCKS5 */
  585. buf[0] = 0x05; /* version */
  586. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
  587. buf[1] = 0; /* succeeded */
  588. buf[2] = 0; /* reserved */
  589. buf[3] = 0x01; /* IPv4 address type */
  590. memcpy(buf+4, answer, 4); /* address */
  591. set_uint16(buf+8, 0); /* port == 0. */
  592. replylen = 10;
  593. } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
  594. buf[1] = 0; /* succeeded */
  595. buf[2] = 0; /* reserved */
  596. buf[3] = 0x04; /* IPv6 address type */
  597. memcpy(buf+4, answer, 16); /* address */
  598. set_uint16(buf+20, 0); /* port == 0. */
  599. replylen = 22;
  600. } else {
  601. buf[1] = 0x04; /* host unreachable */
  602. memset(buf+2, 0, 8);
  603. replylen = 10;
  604. }
  605. }
  606. connection_ap_handshake_socks_reply(conn, buf, replylen,
  607. answer_type == RESOLVED_TYPE_IPV4 ||
  608. answer_type == RESOLVED_TYPE_IPV6);
  609. }
  610. /** Send a socks reply to stream <b>conn</b>, using the appropriate
  611. * socks version, etc.
  612. *
  613. * If <b>reply</b> is defined, then write <b>replylen</b> bytes of it
  614. * to conn and return.
  615. *
  616. * Otherwise, send back a reply based on whether <b>success</b> is 1 or 0.
  617. */
  618. void connection_ap_handshake_socks_reply(connection_t *conn, char *reply,
  619. size_t replylen, int success) {
  620. char buf[256];
  621. if(replylen) { /* we already have a reply in mind */
  622. connection_write_to_buf(reply, replylen, conn);
  623. return;
  624. }
  625. tor_assert(conn->socks_request);
  626. if(conn->socks_request->socks_version == 4) {
  627. memset(buf,0,SOCKS4_NETWORK_LEN);
  628. #define SOCKS4_GRANTED 90
  629. #define SOCKS4_REJECT 91
  630. buf[1] = (success ? SOCKS4_GRANTED : SOCKS4_REJECT);
  631. /* leave version, destport, destip zero */
  632. connection_write_to_buf(buf, SOCKS4_NETWORK_LEN, conn);
  633. }
  634. if(conn->socks_request->socks_version == 5) {
  635. buf[0] = 5; /* version 5 */
  636. #define SOCKS5_SUCCESS 0
  637. #define SOCKS5_GENERIC_ERROR 1
  638. buf[1] = success ? SOCKS5_SUCCESS : SOCKS5_GENERIC_ERROR;
  639. buf[2] = 0;
  640. buf[3] = 1; /* ipv4 addr */
  641. memset(buf+4,0,6); /* Set external addr/port to 0.
  642. The spec doesn't seem to say what to do here. -RD */
  643. connection_write_to_buf(buf,10,conn);
  644. }
  645. /* If socks_version isn't 4 or 5, don't send anything.
  646. * This can happen in the case of AP bridges. */
  647. return;
  648. }
  649. /** A relay 'begin' cell has arrived, and either we are an exit hop
  650. * for the circuit, or we are the origin and it is a rendezvous begin.
  651. *
  652. * Launch a new exit connection and initialize things appropriately.
  653. *
  654. * If it's a rendezvous stream, call connection_exit_connect() on
  655. * it.
  656. *
  657. * For general streams, call dns_resolve() on it first, and only call
  658. * connection_exit_connect() if the dns answer is already known.
  659. *
  660. * Note that we don't call connection_add() on the new stream! We wait
  661. * for connection_exit_connect() to do that.
  662. *
  663. * Return -1 if we want to tear down <b>circ</b>. Else return 0.
  664. */
  665. int connection_exit_begin_conn(cell_t *cell, circuit_t *circ) {
  666. connection_t *n_stream;
  667. relay_header_t rh;
  668. char *address=NULL;
  669. uint16_t port;
  670. assert_circuit_ok(circ);
  671. relay_header_unpack(&rh, cell->payload);
  672. /* XXX currently we don't send an end cell back if we drop the
  673. * begin because it's malformed.
  674. */
  675. if(!memchr(cell->payload+RELAY_HEADER_SIZE, 0, rh.length)) {
  676. log_fn(LOG_WARN,"relay begin cell has no \\0. Dropping.");
  677. return 0;
  678. }
  679. if (parse_addr_port(cell->payload+RELAY_HEADER_SIZE, &address, NULL,&port)<0){
  680. log_fn(LOG_WARN,"Unable to parse addr:port in relay begin cell. Dropping.");
  681. return 0;
  682. }
  683. if (port==0) {
  684. log_fn(LOG_WARN,"Missing port in relay begin cell. Dropping.");
  685. tor_free(address);
  686. return 0;
  687. }
  688. log_fn(LOG_DEBUG,"Creating new exit connection.");
  689. n_stream = connection_new(CONN_TYPE_EXIT);
  690. n_stream->purpose = EXIT_PURPOSE_CONNECT;
  691. n_stream->stream_id = rh.stream_id;
  692. n_stream->port = port;
  693. /* leave n_stream->s at -1, because it's not yet valid */
  694. n_stream->package_window = STREAMWINDOW_START;
  695. n_stream->deliver_window = STREAMWINDOW_START;
  696. if(circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED) {
  697. log_fn(LOG_DEBUG,"begin is for rendezvous. configuring stream.");
  698. n_stream->address = tor_strdup("(rendezvous)");
  699. n_stream->state = EXIT_CONN_STATE_CONNECTING;
  700. strlcpy(n_stream->rend_query, circ->rend_query,
  701. sizeof(n_stream->rend_query));
  702. tor_assert(connection_edge_is_rendezvous_stream(n_stream));
  703. assert_circuit_ok(circ);
  704. if(rend_service_set_connection_addr_port(n_stream, circ) < 0) {
  705. log_fn(LOG_INFO,"Didn't find rendezvous service (port %d)",n_stream->port);
  706. connection_edge_end(n_stream, END_STREAM_REASON_EXITPOLICY, n_stream->cpath_layer);
  707. connection_free(n_stream);
  708. circuit_mark_for_close(circ); /* knock the whole thing down, somebody screwed up */
  709. tor_free(address);
  710. return 0;
  711. }
  712. assert_circuit_ok(circ);
  713. log_fn(LOG_DEBUG,"Finished assigning addr/port");
  714. n_stream->cpath_layer = circ->cpath->prev; /* link it */
  715. /* add it into the linked list of n_streams on this circuit */
  716. n_stream->next_stream = circ->n_streams;
  717. circ->n_streams = n_stream;
  718. assert_circuit_ok(circ);
  719. connection_exit_connect(n_stream);
  720. tor_free(address);
  721. return 0;
  722. }
  723. n_stream->address = address;
  724. n_stream->state = EXIT_CONN_STATE_RESOLVEFAILED;
  725. /* default to failed, change in dns_resolve if it turns out not to fail */
  726. /* send it off to the gethostbyname farm */
  727. switch(dns_resolve(n_stream)) {
  728. case 1: /* resolve worked */
  729. /* add it into the linked list of n_streams on this circuit */
  730. n_stream->next_stream = circ->n_streams;
  731. circ->n_streams = n_stream;
  732. assert_circuit_ok(circ);
  733. connection_exit_connect(n_stream);
  734. return 0;
  735. case -1: /* resolve failed */
  736. log_fn(LOG_INFO,"Resolve failed (%s).", n_stream->address);
  737. connection_edge_end(n_stream, END_STREAM_REASON_RESOLVEFAILED, n_stream->cpath_layer);
  738. connection_free(n_stream);
  739. break;
  740. case 0: /* resolve added to pending list */
  741. /* add it into the linked list of resolving_streams on this circuit */
  742. n_stream->next_stream = circ->resolving_streams;
  743. circ->resolving_streams = n_stream;
  744. assert_circuit_ok(circ);
  745. ;
  746. }
  747. return 0;
  748. }
  749. /**
  750. * Called when we receive a RELAY_RESOLVE cell 'cell' along the circuit 'circ';
  751. * begin resolving the hostname, and (eventually) reply with a RESOLVED cell.
  752. */
  753. int connection_exit_begin_resolve(cell_t *cell, circuit_t *circ) {
  754. connection_t *dummy_conn;
  755. relay_header_t rh;
  756. assert_circuit_ok(circ);
  757. relay_header_unpack(&rh, cell->payload);
  758. /* This 'dummy_conn' only exists to remember the stream ID
  759. * associated with the resolve request; and to make the
  760. * implementation of dns.c more uniform. (We really only need to
  761. * remember the circuit, the stream ID, and the hostname to be
  762. * resolved; but if we didn't store them in a connection like this,
  763. * the housekeeping in dns.c would get way more complicated.)
  764. */
  765. dummy_conn = connection_new(CONN_TYPE_EXIT);
  766. dummy_conn->stream_id = rh.stream_id;
  767. dummy_conn->address = tor_strndup(cell->payload+RELAY_HEADER_SIZE,
  768. rh.length);
  769. dummy_conn->port = 0;
  770. dummy_conn->state = EXIT_CONN_STATE_RESOLVEFAILED;
  771. dummy_conn->purpose = EXIT_PURPOSE_RESOLVE;
  772. dummy_conn->next_stream = circ->resolving_streams;
  773. circ->resolving_streams = dummy_conn;
  774. /* send it off to the gethostbyname farm */
  775. switch(dns_resolve(dummy_conn)) {
  776. case 1: /* The result was cached; a resolved cell was sent. */
  777. case -1:
  778. circuit_detach_stream(circuit_get_by_conn(dummy_conn), dummy_conn);
  779. connection_free(dummy_conn);
  780. return 0;
  781. case 0: /* resolve added to pending list */
  782. assert_circuit_ok(circ);
  783. ;
  784. }
  785. return 0;
  786. }
  787. /** Connect to conn's specified addr and port. If it worked, conn
  788. * has now been added to the connection_array.
  789. *
  790. * Send back a connected cell. Include the resolved IP of the destination
  791. * address, but <em>only</em> if it's a general exit stream. (Rendezvous
  792. * streams must not reveal what IP they connected to.)
  793. */
  794. void connection_exit_connect(connection_t *conn) {
  795. unsigned char connected_payload[4];
  796. uint32_t addr;
  797. uint16_t port;
  798. if (!connection_edge_is_rendezvous_stream(conn) &&
  799. router_compare_to_my_exit_policy(conn) == ADDR_POLICY_REJECTED) {
  800. log_fn(LOG_INFO,"%s:%d failed exit policy. Closing.", conn->address, conn->port);
  801. connection_edge_end(conn, END_STREAM_REASON_EXITPOLICY, conn->cpath_layer);
  802. circuit_detach_stream(circuit_get_by_conn(conn), conn);
  803. connection_free(conn);
  804. return;
  805. }
  806. addr = conn->addr;
  807. port = conn->port;
  808. SMARTLIST_FOREACH(options.RedirectExitList, exit_redirect_t *, r,
  809. {
  810. if ((addr&r->mask)==(r->addr&r->mask) &&
  811. (r->port_min <= port) && (port <= r->port_max)) {
  812. struct in_addr in;
  813. if (r->is_redirect) {
  814. addr = r->addr_dest;
  815. port = r->port_dest;
  816. in.s_addr = htonl(addr);
  817. log_fn(LOG_DEBUG, "Redirecting connection from %s:%d to %s:%d",
  818. conn->address, conn->port, inet_ntoa(in), port);
  819. }
  820. break;
  821. }
  822. });
  823. log_fn(LOG_DEBUG,"about to try connecting");
  824. switch(connection_connect(conn, conn->address, addr, port)) {
  825. case -1:
  826. connection_edge_end(conn, END_STREAM_REASON_CONNECTFAILED, conn->cpath_layer);
  827. circuit_detach_stream(circuit_get_by_conn(conn), conn);
  828. connection_free(conn);
  829. return;
  830. case 0:
  831. conn->state = EXIT_CONN_STATE_CONNECTING;
  832. connection_watch_events(conn, POLLOUT | POLLIN | POLLERR);
  833. /* writable indicates finish, readable indicates broken link,
  834. error indicates broken link in windowsland. */
  835. return;
  836. /* case 1: fall through */
  837. }
  838. conn->state = EXIT_CONN_STATE_OPEN;
  839. if(connection_wants_to_flush(conn)) { /* in case there are any queued data cells */
  840. log_fn(LOG_WARN,"tell roger: newly connected conn had data waiting!");
  841. // connection_start_writing(conn);
  842. }
  843. connection_watch_events(conn, POLLIN);
  844. /* also, deliver a 'connected' cell back through the circuit. */
  845. if(connection_edge_is_rendezvous_stream(conn)) { /* rendezvous stream */
  846. /* don't send an address back! */
  847. connection_edge_send_command(conn, circuit_get_by_conn(conn), RELAY_COMMAND_CONNECTED,
  848. NULL, 0, conn->cpath_layer);
  849. } else { /* normal stream */
  850. /* This must be the original address, not the redirected address. */
  851. *(uint32_t*)connected_payload = htonl(conn->addr);
  852. connection_edge_send_command(conn, circuit_get_by_conn(conn), RELAY_COMMAND_CONNECTED,
  853. connected_payload, 4, conn->cpath_layer);
  854. }
  855. }
  856. /** Return 1 if <b>conn</b> is a rendezvous stream, or 0 if
  857. * it is a general stream.
  858. */
  859. int connection_edge_is_rendezvous_stream(connection_t *conn) {
  860. tor_assert(conn);
  861. if(*conn->rend_query) /* XXX */
  862. return 1;
  863. return 0;
  864. }
  865. /** Return 1 if router <b>exit</b> might allow stream <b>conn</b>
  866. * to exit from it, or 0 if it definitely will not allow it.
  867. * (We might be uncertain if conn's destination address has not yet been
  868. * resolved.)
  869. */
  870. int connection_ap_can_use_exit(connection_t *conn, routerinfo_t *exit)
  871. {
  872. uint32_t addr;
  873. tor_assert(conn);
  874. tor_assert(conn->type == CONN_TYPE_AP);
  875. tor_assert(conn->socks_request);
  876. log_fn(LOG_DEBUG,"considering nickname %s, for address %s / port %d:",
  877. exit->nickname, conn->socks_request->address,
  878. conn->socks_request->port);
  879. if (conn->socks_request->command == SOCKS_COMMAND_RESOLVE) {
  880. /* 0.0.8 servers have buggy resolve support. */
  881. return tor_version_as_new_as(exit->platform, "0.0.9pre1");
  882. }
  883. addr = client_dns_lookup_entry(conn->socks_request->address);
  884. if(router_compare_addr_to_exit_policy(addr,
  885. conn->socks_request->port, exit->exit_policy) < 0)
  886. return 0;
  887. return 1;
  888. }
  889. /** A helper function for socks_policy_permits_address() below.
  890. *
  891. * Parse options.SocksPolicy in the same way that the exit policy
  892. * is parsed, and put the processed version in &socks_policy.
  893. * Ignore port specifiers.
  894. */
  895. static void parse_socks_policy(void)
  896. {
  897. struct exit_policy_t *n;
  898. if (socks_policy) {
  899. exit_policy_free(socks_policy);
  900. socks_policy = NULL;
  901. }
  902. config_parse_exit_policy(options.SocksPolicy, &socks_policy);
  903. /* ports aren't used. */
  904. for (n=socks_policy; n; n = n->next) {
  905. n->prt_min = 1;
  906. n->prt_max = 65535;
  907. }
  908. }
  909. /** Return 1 if <b>addr</b> is permitted to connect to our socks port,
  910. * based on <b>socks_policy</b>. Else return 0.
  911. */
  912. int socks_policy_permits_address(uint32_t addr)
  913. {
  914. int a;
  915. if (options.SocksPolicy && !socks_policy)
  916. parse_socks_policy();
  917. if(!socks_policy) /* 'no socks policy' means 'accept' */
  918. return 1;
  919. a = router_compare_addr_to_exit_policy(addr, 1, socks_policy);
  920. if (a==-1)
  921. return 0;
  922. else if (a==0)
  923. return 1;
  924. tor_assert(a==1);
  925. log_fn(LOG_WARN, "Got unexpected 'maybe' answer from socks policy");
  926. return 0;
  927. }
  928. /* ***** Client DNS code ***** */
  929. /* XXX Perhaps this should get merged with the dns.c code somehow. */
  930. /* XXX But we can't just merge them, because then nodes that act as
  931. * both OR and OP could be attacked: people could rig the dns cache
  932. * by answering funny things to stream begin requests, and later
  933. * other clients would reuse those funny addr's. Hm.
  934. */
  935. /** A client-side struct to remember the resolved IP (addr) for
  936. * a given address. These structs make up a tree, with client_dns_map
  937. * below as its root.
  938. */
  939. struct client_dns_entry {
  940. uint32_t addr; /**< The resolved IP of this entry. */
  941. time_t expires; /**< At what second does addr expire? */
  942. int n_failures; /**< How many times has this entry failed to resolve so far? */
  943. };
  944. /** How many elements are in the client dns cache currently? */
  945. static int client_dns_size = 0;
  946. /** The tree of client-side cached DNS resolves. */
  947. static strmap_t *client_dns_map = NULL;
  948. /** Initialize client_dns_map and client_dns_size. */
  949. void client_dns_init(void) {
  950. client_dns_map = strmap_new();
  951. client_dns_size = 0;
  952. }
  953. /** Return the client_dns_entry that corresponds to <b>address</b>.
  954. * If it's not there, allocate and return a new entry for <b>address</b>.
  955. */
  956. static struct client_dns_entry *
  957. _get_or_create_ent(const char *address)
  958. {
  959. struct client_dns_entry *ent;
  960. ent = strmap_get_lc(client_dns_map,address);
  961. if (!ent) {
  962. ent = tor_malloc_zero(sizeof(struct client_dns_entry));
  963. ent->expires = time(NULL)+MAX_DNS_ENTRY_AGE;
  964. strmap_set_lc(client_dns_map,address,ent);
  965. ++client_dns_size;
  966. }
  967. return ent;
  968. }
  969. /** Return the IP associated with <b>address</b>, if we know it
  970. * and it's still fresh enough. Otherwise return 0.
  971. */
  972. uint32_t client_dns_lookup_entry(const char *address)
  973. {
  974. struct client_dns_entry *ent;
  975. struct in_addr in;
  976. time_t now;
  977. tor_assert(address);
  978. if (tor_inet_aton(address, &in)) {
  979. log_fn(LOG_DEBUG, "Using static address %s (%08lX)", address,
  980. (unsigned long)ntohl(in.s_addr));
  981. return ntohl(in.s_addr);
  982. }
  983. ent = strmap_get_lc(client_dns_map,address);
  984. if (!ent || !ent->addr) {
  985. log_fn(LOG_DEBUG, "No entry found for address %s", address);
  986. return 0;
  987. } else {
  988. now = time(NULL);
  989. if (ent->expires < now) {
  990. log_fn(LOG_DEBUG, "Expired entry found for address %s", address);
  991. strmap_remove_lc(client_dns_map,address);
  992. tor_free(ent);
  993. --client_dns_size;
  994. return 0;
  995. }
  996. in.s_addr = htonl(ent->addr);
  997. log_fn(LOG_DEBUG, "Found cached entry for address %s: %s", address,
  998. inet_ntoa(in));
  999. return ent->addr;
  1000. }
  1001. }
  1002. /** An attempt to resolve <b>address</b> failed at some OR.
  1003. * Increment the number of resolve failures we have on record
  1004. * for it, and then return that number.
  1005. */
  1006. int client_dns_incr_failures(const char *address)
  1007. {
  1008. struct client_dns_entry *ent;
  1009. ent = _get_or_create_ent(address);
  1010. ++ent->n_failures;
  1011. log_fn(LOG_DEBUG,"Address %s now has %d resolve failures.",
  1012. address, ent->n_failures);
  1013. return ent->n_failures;
  1014. }
  1015. /** Record the fact that <b>address</b> resolved to <b>val</b>.
  1016. * We can now use this in subsequent streams in client_dns_lookup_entry(),
  1017. * so we can more correctly choose a router that will allow <b>address</b>
  1018. * to exit from him.
  1019. */
  1020. void client_dns_set_entry(const char *address, uint32_t val)
  1021. {
  1022. struct client_dns_entry *ent;
  1023. struct in_addr in;
  1024. time_t now;
  1025. tor_assert(address);
  1026. tor_assert(val);
  1027. if (tor_inet_aton(address, &in))
  1028. return;
  1029. now = time(NULL);
  1030. ent = _get_or_create_ent(address);
  1031. in.s_addr = htonl(val);
  1032. log_fn(LOG_DEBUG, "Updating entry for address %s: %s", address,
  1033. inet_ntoa(in));
  1034. ent->addr = val;
  1035. ent->expires = now+MAX_DNS_ENTRY_AGE;
  1036. ent->n_failures = 0;
  1037. }
  1038. /** A helper function for client_dns_clean() below. If ent is too old,
  1039. * then remove it from the tree and return NULL, else return ent.
  1040. */
  1041. static void* _remove_if_expired(const char *addr,
  1042. struct client_dns_entry *ent,
  1043. time_t *nowp)
  1044. {
  1045. if (ent->expires < *nowp) {
  1046. --client_dns_size;
  1047. tor_free(ent);
  1048. return NULL;
  1049. } else {
  1050. return ent;
  1051. }
  1052. }
  1053. /** Clean out entries from the client-side DNS cache that were
  1054. * resolved long enough ago that they are no longer valid.
  1055. */
  1056. void client_dns_clean(void)
  1057. {
  1058. time_t now;
  1059. if(!client_dns_size)
  1060. return;
  1061. now = time(NULL);
  1062. strmap_foreach(client_dns_map, (strmap_foreach_fn)_remove_if_expired, &now);
  1063. }
  1064. /*
  1065. Local Variables:
  1066. mode:c
  1067. indent-tabs-mode:nil
  1068. c-basic-offset:2
  1069. End:
  1070. */