connection_edge.c 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186
  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. strcpy(conn->rend_query, socks->address); /* this strcpy is safe -RD */
  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. 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. 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. strcpy(conn->socks_request->address, address);
  536. conn->socks_request->port = port;
  537. conn->socks_request->command = SOCKS_COMMAND_CONNECT;
  538. conn->address = tor_strdup("(local bridge)");
  539. conn->addr = 0;
  540. conn->port = 0;
  541. if(connection_add(conn) < 0) { /* no space, forget it */
  542. connection_free(conn); /* this closes fd[0] */
  543. tor_close_socket(fd[1]);
  544. return -1;
  545. }
  546. conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  547. connection_start_reading(conn);
  548. /* attaching to a dirty circuit is fine */
  549. if (connection_ap_handshake_attach_circuit(conn) < 0) {
  550. conn->has_sent_end = 1; /* no circ to send to */
  551. connection_mark_for_close(conn);
  552. tor_close_socket(fd[1]);
  553. return -1;
  554. }
  555. log_fn(LOG_INFO,"... AP bridge created and connected.");
  556. return fd[1];
  557. }
  558. void connection_ap_handshake_socks_resolved(connection_t *conn,
  559. int answer_type,
  560. size_t answer_len,
  561. const char *answer)
  562. {
  563. char buf[256];
  564. size_t replylen;
  565. if (answer_type == RESOLVED_TYPE_IPV4) {
  566. uint32_t a = get_uint32(answer);
  567. if(a)
  568. client_dns_set_entry(conn->socks_request->address, ntohl(a));
  569. }
  570. if (conn->socks_request->socks_version == 4) {
  571. buf[0] = 0x00; /* version */
  572. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
  573. buf[1] = 90; /* "Granted" */
  574. set_uint16(buf+2, 0);
  575. memcpy(buf+4, answer, 4); /* address */
  576. replylen = SOCKS4_NETWORK_LEN;
  577. } else {
  578. buf[1] = 91; /* "error" */
  579. memset(buf+2, 0, 6);
  580. replylen = SOCKS4_NETWORK_LEN;
  581. }
  582. } else {
  583. /* SOCKS5 */
  584. buf[0] = 0x05; /* version */
  585. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
  586. buf[1] = 0; /* succeeded */
  587. buf[2] = 0; /* reserved */
  588. buf[3] = 0x01; /* IPv4 address type */
  589. memcpy(buf+4, answer, 4); /* address */
  590. set_uint16(buf+8, 0); /* port == 0. */
  591. replylen = 10;
  592. } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
  593. buf[1] = 0; /* succeeded */
  594. buf[2] = 0; /* reserved */
  595. buf[3] = 0x04; /* IPv6 address type */
  596. memcpy(buf+4, answer, 16); /* address */
  597. set_uint16(buf+20, 0); /* port == 0. */
  598. replylen = 22;
  599. } else {
  600. buf[1] = 0x04; /* host unreachable */
  601. memset(buf+2, 0, 8);
  602. replylen = 10;
  603. }
  604. }
  605. connection_ap_handshake_socks_reply(conn, buf, replylen,
  606. answer_type == RESOLVED_TYPE_IPV4 ||
  607. answer_type == RESOLVED_TYPE_IPV6);
  608. }
  609. /** Send a socks reply to stream <b>conn</b>, using the appropriate
  610. * socks version, etc.
  611. *
  612. * If <b>reply</b> is defined, then write <b>replylen</b> bytes of it
  613. * to conn and return.
  614. *
  615. * Otherwise, send back a reply based on whether <b>success</b> is 1 or 0.
  616. */
  617. void connection_ap_handshake_socks_reply(connection_t *conn, char *reply,
  618. size_t replylen, int success) {
  619. char buf[256];
  620. if(replylen) { /* we already have a reply in mind */
  621. connection_write_to_buf(reply, replylen, conn);
  622. return;
  623. }
  624. tor_assert(conn->socks_request);
  625. if(conn->socks_request->socks_version == 4) {
  626. memset(buf,0,SOCKS4_NETWORK_LEN);
  627. #define SOCKS4_GRANTED 90
  628. #define SOCKS4_REJECT 91
  629. buf[1] = (success ? SOCKS4_GRANTED : SOCKS4_REJECT);
  630. /* leave version, destport, destip zero */
  631. connection_write_to_buf(buf, SOCKS4_NETWORK_LEN, conn);
  632. }
  633. if(conn->socks_request->socks_version == 5) {
  634. buf[0] = 5; /* version 5 */
  635. #define SOCKS5_SUCCESS 0
  636. #define SOCKS5_GENERIC_ERROR 1
  637. buf[1] = success ? SOCKS5_SUCCESS : SOCKS5_GENERIC_ERROR;
  638. buf[2] = 0;
  639. buf[3] = 1; /* ipv4 addr */
  640. memset(buf+4,0,6); /* Set external addr/port to 0.
  641. The spec doesn't seem to say what to do here. -RD */
  642. connection_write_to_buf(buf,10,conn);
  643. }
  644. /* If socks_version isn't 4 or 5, don't send anything.
  645. * This can happen in the case of AP bridges. */
  646. return;
  647. }
  648. /** A relay 'begin' cell has arrived, and either we are an exit hop
  649. * for the circuit, or we are the origin and it is a rendezvous begin.
  650. *
  651. * Launch a new exit connection and initialize things appropriately.
  652. *
  653. * If it's a rendezvous stream, call connection_exit_connect() on
  654. * it.
  655. *
  656. * For general streams, call dns_resolve() on it first, and only call
  657. * connection_exit_connect() if the dns answer is already known.
  658. *
  659. * Note that we don't call connection_add() on the new stream! We wait
  660. * for connection_exit_connect() to do that.
  661. *
  662. * Return -1 if we want to tear down <b>circ</b>. Else return 0.
  663. */
  664. int connection_exit_begin_conn(cell_t *cell, circuit_t *circ) {
  665. connection_t *n_stream;
  666. relay_header_t rh;
  667. char *address=NULL;
  668. uint16_t port;
  669. assert_circuit_ok(circ);
  670. relay_header_unpack(&rh, cell->payload);
  671. /* XXX currently we don't send an end cell back if we drop the
  672. * begin because it's malformed.
  673. */
  674. if(!memchr(cell->payload+RELAY_HEADER_SIZE, 0, rh.length)) {
  675. log_fn(LOG_WARN,"relay begin cell has no \\0. Dropping.");
  676. return 0;
  677. }
  678. if (parse_addr_port(cell->payload+RELAY_HEADER_SIZE, &address, NULL,&port)<0){
  679. log_fn(LOG_WARN,"Unable to parse addr:port in relay begin cell. Dropping.");
  680. return 0;
  681. }
  682. if (port==0) {
  683. log_fn(LOG_WARN,"Missing port in relay begin cell. Dropping.");
  684. tor_free(address);
  685. return 0;
  686. }
  687. log_fn(LOG_DEBUG,"Creating new exit connection.");
  688. n_stream = connection_new(CONN_TYPE_EXIT);
  689. n_stream->purpose = EXIT_PURPOSE_CONNECT;
  690. n_stream->stream_id = rh.stream_id;
  691. n_stream->port = port;
  692. /* leave n_stream->s at -1, because it's not yet valid */
  693. n_stream->package_window = STREAMWINDOW_START;
  694. n_stream->deliver_window = STREAMWINDOW_START;
  695. if(circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED) {
  696. log_fn(LOG_DEBUG,"begin is for rendezvous. configuring stream.");
  697. n_stream->address = tor_strdup("(rendezvous)");
  698. n_stream->state = EXIT_CONN_STATE_CONNECTING;
  699. strcpy(n_stream->rend_query, circ->rend_query);
  700. tor_assert(n_stream->rend_query[0]);
  701. assert_circuit_ok(circ);
  702. if(rend_service_set_connection_addr_port(n_stream, circ) < 0) {
  703. log_fn(LOG_INFO,"Didn't find rendezvous service (port %d)",n_stream->port);
  704. connection_edge_end(n_stream, END_STREAM_REASON_EXITPOLICY, n_stream->cpath_layer);
  705. connection_free(n_stream);
  706. circuit_mark_for_close(circ); /* knock the whole thing down, somebody screwed up */
  707. tor_free(address);
  708. return 0;
  709. }
  710. assert_circuit_ok(circ);
  711. log_fn(LOG_DEBUG,"Finished assigning addr/port");
  712. n_stream->cpath_layer = circ->cpath->prev; /* link it */
  713. /* add it into the linked list of n_streams on this circuit */
  714. n_stream->next_stream = circ->n_streams;
  715. circ->n_streams = n_stream;
  716. assert_circuit_ok(circ);
  717. connection_exit_connect(n_stream);
  718. tor_free(address);
  719. return 0;
  720. }
  721. n_stream->address = address;
  722. n_stream->state = EXIT_CONN_STATE_RESOLVEFAILED;
  723. /* default to failed, change in dns_resolve if it turns out not to fail */
  724. /* send it off to the gethostbyname farm */
  725. switch(dns_resolve(n_stream)) {
  726. case 1: /* resolve worked */
  727. /* add it into the linked list of n_streams on this circuit */
  728. n_stream->next_stream = circ->n_streams;
  729. circ->n_streams = n_stream;
  730. assert_circuit_ok(circ);
  731. connection_exit_connect(n_stream);
  732. return 0;
  733. case -1: /* resolve failed */
  734. log_fn(LOG_INFO,"Resolve failed (%s).", n_stream->address);
  735. connection_edge_end(n_stream, END_STREAM_REASON_RESOLVEFAILED, n_stream->cpath_layer);
  736. connection_free(n_stream);
  737. break;
  738. case 0: /* resolve added to pending list */
  739. /* add it into the linked list of resolving_streams on this circuit */
  740. n_stream->next_stream = circ->resolving_streams;
  741. circ->resolving_streams = n_stream;
  742. assert_circuit_ok(circ);
  743. ;
  744. }
  745. return 0;
  746. }
  747. /**
  748. * Called when we receive a RELAY_RESOLVE cell 'cell' along the circuit 'circ';
  749. * begin resolving the hostname, and (eventually) reply with a RESOLVED cell.
  750. */
  751. int connection_exit_begin_resolve(cell_t *cell, circuit_t *circ) {
  752. connection_t *dummy_conn;
  753. relay_header_t rh;
  754. assert_circuit_ok(circ);
  755. relay_header_unpack(&rh, cell->payload);
  756. /* This 'dummy_conn' only exists to remember the stream ID
  757. * associated with the resolve request; and to make the
  758. * implementation of dns.c more uniform. (We really only need to
  759. * remember the circuit, the stream ID, and the hostname to be
  760. * resolved; but if we didn't store them in a connection like this,
  761. * the housekeeping in dns.c would get way more complicated.)
  762. */
  763. dummy_conn = connection_new(CONN_TYPE_EXIT);
  764. dummy_conn->stream_id = rh.stream_id;
  765. dummy_conn->address = tor_strndup(cell->payload+RELAY_HEADER_SIZE,
  766. rh.length);
  767. dummy_conn->port = 0;
  768. dummy_conn->state = EXIT_CONN_STATE_RESOLVEFAILED;
  769. dummy_conn->purpose = EXIT_PURPOSE_RESOLVE;
  770. dummy_conn->next_stream = circ->resolving_streams;
  771. circ->resolving_streams = dummy_conn;
  772. /* send it off to the gethostbyname farm */
  773. switch(dns_resolve(dummy_conn)) {
  774. case 1: /* The result was cached; a resolved cell was sent. */
  775. case -1:
  776. circuit_detach_stream(circuit_get_by_conn(dummy_conn), dummy_conn);
  777. connection_free(dummy_conn);
  778. return 0;
  779. case 0: /* resolve added to pending list */
  780. assert_circuit_ok(circ);
  781. ;
  782. }
  783. return 0;
  784. }
  785. /** Connect to conn's specified addr and port. If it worked, conn
  786. * has now been added to the connection_array.
  787. *
  788. * Send back a connected cell. Include the resolved IP of the destination
  789. * address, but <em>only</em> if it's a general exit stream. (Rendezvous
  790. * streams must not reveal what IP they connected to.)
  791. */
  792. void connection_exit_connect(connection_t *conn) {
  793. unsigned char connected_payload[4];
  794. uint32_t addr;
  795. uint16_t port;
  796. if (!connection_edge_is_rendezvous_stream(conn) &&
  797. router_compare_to_my_exit_policy(conn) == ADDR_POLICY_REJECTED) {
  798. log_fn(LOG_INFO,"%s:%d failed exit policy. Closing.", conn->address, conn->port);
  799. connection_edge_end(conn, END_STREAM_REASON_EXITPOLICY, conn->cpath_layer);
  800. circuit_detach_stream(circuit_get_by_conn(conn), conn);
  801. connection_free(conn);
  802. return;
  803. }
  804. addr = conn->addr;
  805. port = conn->port;
  806. SMARTLIST_FOREACH(options.RedirectExitList, exit_redirect_t *, r,
  807. {
  808. if ((addr&r->mask)==(r->addr&r->mask) &&
  809. (r->port_min <= port) && (port <= r->port_max)) {
  810. struct in_addr in;
  811. addr = r->addr_dest;
  812. port = r->port_dest;
  813. in.s_addr = htonl(addr);
  814. log_fn(LOG_DEBUG, "Redirecting connection from %s:%d to %s:%d",
  815. conn->address, conn->port, inet_ntoa(in), port);
  816. break;
  817. }
  818. });
  819. log_fn(LOG_DEBUG,"about to try connecting");
  820. switch(connection_connect(conn, conn->address, addr, port)) {
  821. case -1:
  822. connection_edge_end(conn, END_STREAM_REASON_CONNECTFAILED, conn->cpath_layer);
  823. circuit_detach_stream(circuit_get_by_conn(conn), conn);
  824. connection_free(conn);
  825. return;
  826. case 0:
  827. conn->state = EXIT_CONN_STATE_CONNECTING;
  828. connection_watch_events(conn, POLLOUT | POLLIN | POLLERR);
  829. /* writable indicates finish, readable indicates broken link,
  830. error indicates broken link in windowsland. */
  831. return;
  832. /* case 1: fall through */
  833. }
  834. conn->state = EXIT_CONN_STATE_OPEN;
  835. if(connection_wants_to_flush(conn)) { /* in case there are any queued data cells */
  836. log_fn(LOG_WARN,"tell roger: newly connected conn had data waiting!");
  837. // connection_start_writing(conn);
  838. }
  839. connection_watch_events(conn, POLLIN);
  840. /* also, deliver a 'connected' cell back through the circuit. */
  841. if(connection_edge_is_rendezvous_stream(conn)) { /* rendezvous stream */
  842. /* don't send an address back! */
  843. connection_edge_send_command(conn, circuit_get_by_conn(conn), RELAY_COMMAND_CONNECTED,
  844. NULL, 0, conn->cpath_layer);
  845. } else { /* normal stream */
  846. /* This must be the original address, not the redirected address. */
  847. *(uint32_t*)connected_payload = htonl(conn->addr);
  848. connection_edge_send_command(conn, circuit_get_by_conn(conn), RELAY_COMMAND_CONNECTED,
  849. connected_payload, 4, conn->cpath_layer);
  850. }
  851. }
  852. /** Return 1 if <b>conn</b> is a rendezvous stream, or 0 if
  853. * it is a general stream.
  854. */
  855. int connection_edge_is_rendezvous_stream(connection_t *conn) {
  856. tor_assert(conn);
  857. if(*conn->rend_query) /* XXX */
  858. return 1;
  859. return 0;
  860. }
  861. /** Return 1 if router <b>exit</b> might allow stream <b>conn</b>
  862. * to exit from it, or 0 if it definitely will not allow it.
  863. * (We might be uncertain if conn's destination address has not yet been
  864. * resolved.)
  865. */
  866. int connection_ap_can_use_exit(connection_t *conn, routerinfo_t *exit)
  867. {
  868. uint32_t addr;
  869. tor_assert(conn);
  870. tor_assert(conn->type == CONN_TYPE_AP);
  871. tor_assert(conn->socks_request);
  872. log_fn(LOG_DEBUG,"considering nickname %s, for address %s / port %d:",
  873. exit->nickname, conn->socks_request->address,
  874. conn->socks_request->port);
  875. if (conn->socks_request->command == SOCKS_COMMAND_RESOLVE) {
  876. return tor_version_as_new_as(exit->platform, "0.0.9pre1");
  877. }
  878. addr = client_dns_lookup_entry(conn->socks_request->address);
  879. if(router_compare_addr_to_exit_policy(addr,
  880. conn->socks_request->port, exit->exit_policy) < 0)
  881. return 0;
  882. return 1;
  883. }
  884. /** A helper function for socks_policy_permits_address() below.
  885. *
  886. * Parse options.SocksPolicy in the same way that the exit policy
  887. * is parsed, and put the processed version in &socks_policy.
  888. * Ignore port specifiers.
  889. */
  890. static void parse_socks_policy(void)
  891. {
  892. struct exit_policy_t *n;
  893. if (socks_policy) {
  894. exit_policy_free(socks_policy);
  895. socks_policy = NULL;
  896. }
  897. config_parse_exit_policy(options.SocksPolicy, &socks_policy);
  898. /* ports aren't used. */
  899. for (n=socks_policy; n; n = n->next) {
  900. n->prt_min = 1;
  901. n->prt_max = 65535;
  902. }
  903. }
  904. /** Return 1 if <b>addr</b> is permitted to connect to our socks port,
  905. * based on <b>socks_policy</b>. Else return 0.
  906. */
  907. int socks_policy_permits_address(uint32_t addr)
  908. {
  909. int a;
  910. if (options.SocksPolicy && !socks_policy)
  911. parse_socks_policy();
  912. if(!socks_policy) /* 'no socks policy' means 'accept' */
  913. return 1;
  914. a = router_compare_addr_to_exit_policy(addr, 1, socks_policy);
  915. if (a==-1)
  916. return 0;
  917. else if (a==0)
  918. return 1;
  919. tor_assert(a==1);
  920. log_fn(LOG_WARN, "Got unexpected 'maybe' answer from socks policy");
  921. return 0;
  922. }
  923. /* ***** Client DNS code ***** */
  924. /* XXX Perhaps this should get merged with the dns.c code somehow. */
  925. /* XXX But we can't just merge them, because then nodes that act as
  926. * both OR and OP could be attacked: people could rig the dns cache
  927. * by answering funny things to stream begin requests, and later
  928. * other clients would reuse those funny addr's. Hm.
  929. */
  930. /** A client-side struct to remember the resolved IP (addr) for
  931. * a given address. These structs make up a tree, with client_dns_map
  932. * below as its root.
  933. */
  934. struct client_dns_entry {
  935. uint32_t addr; /**< The resolved IP of this entry. */
  936. time_t expires; /**< At what second does addr expire? */
  937. int n_failures; /**< How many times has this entry failed to resolve so far? */
  938. };
  939. /** How many elements are in the client dns cache currently? */
  940. static int client_dns_size = 0;
  941. /** The tree of client-side cached DNS resolves. */
  942. static strmap_t *client_dns_map = NULL;
  943. /** Initialize client_dns_map and client_dns_size. */
  944. void client_dns_init(void) {
  945. client_dns_map = strmap_new();
  946. client_dns_size = 0;
  947. }
  948. /** Return the client_dns_entry that corresponds to <b>address</b>.
  949. * If it's not there, allocate and return a new entry for <b>address</b>.
  950. */
  951. static struct client_dns_entry *
  952. _get_or_create_ent(const char *address)
  953. {
  954. struct client_dns_entry *ent;
  955. ent = strmap_get_lc(client_dns_map,address);
  956. if (!ent) {
  957. ent = tor_malloc_zero(sizeof(struct client_dns_entry));
  958. ent->expires = time(NULL)+MAX_DNS_ENTRY_AGE;
  959. strmap_set_lc(client_dns_map,address,ent);
  960. ++client_dns_size;
  961. }
  962. return ent;
  963. }
  964. /** Return the IP associated with <b>address</b>, if we know it
  965. * and it's still fresh enough. Otherwise return 0.
  966. */
  967. uint32_t client_dns_lookup_entry(const char *address)
  968. {
  969. struct client_dns_entry *ent;
  970. struct in_addr in;
  971. time_t now;
  972. tor_assert(address);
  973. if (tor_inet_aton(address, &in)) {
  974. log_fn(LOG_DEBUG, "Using static address %s (%08lX)", address,
  975. (unsigned long)ntohl(in.s_addr));
  976. return ntohl(in.s_addr);
  977. }
  978. ent = strmap_get_lc(client_dns_map,address);
  979. if (!ent || !ent->addr) {
  980. log_fn(LOG_DEBUG, "No entry found for address %s", address);
  981. return 0;
  982. } else {
  983. now = time(NULL);
  984. if (ent->expires < now) {
  985. log_fn(LOG_DEBUG, "Expired entry found for address %s", address);
  986. strmap_remove_lc(client_dns_map,address);
  987. tor_free(ent);
  988. --client_dns_size;
  989. return 0;
  990. }
  991. in.s_addr = htonl(ent->addr);
  992. log_fn(LOG_DEBUG, "Found cached entry for address %s: %s", address,
  993. inet_ntoa(in));
  994. return ent->addr;
  995. }
  996. }
  997. /** An attempt to resolve <b>address</b> failed at some OR.
  998. * Increment the number of resolve failures we have on record
  999. * for it, and then return that number.
  1000. */
  1001. int client_dns_incr_failures(const char *address)
  1002. {
  1003. struct client_dns_entry *ent;
  1004. ent = _get_or_create_ent(address);
  1005. ++ent->n_failures;
  1006. log_fn(LOG_DEBUG,"Address %s now has %d resolve failures.",
  1007. address, ent->n_failures);
  1008. return ent->n_failures;
  1009. }
  1010. /** Record the fact that <b>address</b> resolved to <b>val</b>.
  1011. * We can now use this in subsequent streams in client_dns_lookup_entry(),
  1012. * so we can more correctly choose a router that will allow <b>address</b>
  1013. * to exit from him.
  1014. */
  1015. void client_dns_set_entry(const char *address, uint32_t val)
  1016. {
  1017. struct client_dns_entry *ent;
  1018. struct in_addr in;
  1019. time_t now;
  1020. tor_assert(address);
  1021. tor_assert(val);
  1022. if (tor_inet_aton(address, &in))
  1023. return;
  1024. now = time(NULL);
  1025. ent = _get_or_create_ent(address);
  1026. in.s_addr = htonl(val);
  1027. log_fn(LOG_DEBUG, "Updating entry for address %s: %s", address,
  1028. inet_ntoa(in));
  1029. ent->addr = val;
  1030. ent->expires = now+MAX_DNS_ENTRY_AGE;
  1031. ent->n_failures = 0;
  1032. }
  1033. /** A helper function for client_dns_clean() below. If ent is too old,
  1034. * then remove it from the tree and return NULL, else return ent.
  1035. */
  1036. static void* _remove_if_expired(const char *addr,
  1037. struct client_dns_entry *ent,
  1038. time_t *nowp)
  1039. {
  1040. if (ent->expires < *nowp) {
  1041. --client_dns_size;
  1042. tor_free(ent);
  1043. return NULL;
  1044. } else {
  1045. return ent;
  1046. }
  1047. }
  1048. /** Clean out entries from the client-side DNS cache that were
  1049. * resolved long enough ago that they are no longer valid.
  1050. */
  1051. void client_dns_clean(void)
  1052. {
  1053. time_t now;
  1054. if(!client_dns_size)
  1055. return;
  1056. now = time(NULL);
  1057. strmap_foreach(client_dns_map, (strmap_foreach_fn)_remove_if_expired, &now);
  1058. }
  1059. /*
  1060. Local Variables:
  1061. mode:c
  1062. indent-tabs-mode:nil
  1063. c-basic-offset:2
  1064. End:
  1065. */