connection_edge.c 39 KB

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