connection_edge.c 41 KB

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