connection_edge.c 40 KB

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