connection_edge.c 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267
  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. const char connection_edge_c_id[] = "$Id$";
  7. /**
  8. * \file connection_edge.c
  9. * \brief Handle edge streams.
  10. **/
  11. #include "or.h"
  12. #include "tree.h"
  13. static addr_policy_t *socks_policy = NULL;
  14. /* List of exit_redirect_t */
  15. static smartlist_t *redirect_exit_list = NULL;
  16. static int connection_ap_handshake_process_socks(connection_t *conn);
  17. /** There was an EOF. Send an end and mark the connection for close.
  18. */
  19. int connection_edge_reached_eof(connection_t *conn) {
  20. #ifdef HALF_OPEN
  21. /* eof reached; we're done reading, but we might want to write more. */
  22. conn->done_receiving = 1;
  23. shutdown(conn->s, 0); /* XXX check return, refactor NM */
  24. if (conn->done_sending) {
  25. connection_edge_end(conn, END_STREAM_REASON_DONE, conn->cpath_layer);
  26. connection_mark_for_close(conn);
  27. } else {
  28. connection_edge_send_command(conn, circuit_get_by_conn(conn), RELAY_COMMAND_END,
  29. NULL, 0, conn->cpath_layer);
  30. }
  31. return 0;
  32. #else
  33. if (buf_datalen(conn->inbuf) && connection_state_is_open(conn)) {
  34. /* it still has stuff to process. don't let it die yet. */
  35. return 0;
  36. }
  37. log_fn(LOG_INFO,"conn (fd %d) reached eof (stream size %d). Closing.", conn->s, (int)conn->stream_size);
  38. connection_edge_end(conn, END_STREAM_REASON_DONE, conn->cpath_layer);
  39. if (!conn->marked_for_close) {
  40. /* only mark it if not already marked. it's possible to
  41. * get the 'end' right around when the client hangs up on us. */
  42. connection_mark_for_close(conn);
  43. }
  44. conn->hold_open_until_flushed = 1; /* just because we shouldn't read
  45. doesn't mean we shouldn't write */
  46. return 0;
  47. #endif
  48. }
  49. /** Handle new bytes on conn->inbuf based on state:
  50. * - If it's waiting for socks info, try to read another step of the
  51. * socks handshake out of conn->inbuf.
  52. * - If it's open, then package more relay cells from the stream.
  53. * - Else, leave the bytes on inbuf alone for now.
  54. *
  55. * Mark and return -1 if there was an unexpected error with the conn,
  56. * else return 0.
  57. */
  58. int connection_edge_process_inbuf(connection_t *conn, int package_partial) {
  59. tor_assert(conn);
  60. tor_assert(conn->type == CONN_TYPE_AP || conn->type == CONN_TYPE_EXIT);
  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; /* redundant but shouldn't hurt */
  67. return -1;
  68. }
  69. return 0;
  70. case AP_CONN_STATE_OPEN:
  71. case EXIT_CONN_STATE_OPEN:
  72. if (connection_edge_package_raw_inbuf(conn, package_partial) < 0) {
  73. connection_edge_end(conn, END_STREAM_REASON_MISC, conn->cpath_layer);
  74. connection_mark_for_close(conn);
  75. return -1;
  76. }
  77. return 0;
  78. case EXIT_CONN_STATE_CONNECTING:
  79. case AP_CONN_STATE_RENDDESC_WAIT:
  80. case AP_CONN_STATE_CIRCUIT_WAIT:
  81. case AP_CONN_STATE_CONNECT_WAIT:
  82. case AP_CONN_STATE_RESOLVE_WAIT:
  83. log_fn(LOG_INFO,"data from edge while in '%s' state. Leaving it on buffer.",
  84. conn_state_to_string[conn->type][conn->state]);
  85. return 0;
  86. }
  87. log_fn(LOG_WARN,"Got unexpected state %d. Closing.",conn->state);
  88. connection_edge_end(conn, END_STREAM_REASON_MISC, conn->cpath_layer);
  89. connection_mark_for_close(conn);
  90. return -1;
  91. }
  92. /** This edge needs to be closed, because its circuit has closed.
  93. * Mark it for close and return 0.
  94. */
  95. int connection_edge_destroy(uint16_t circ_id, connection_t *conn) {
  96. tor_assert(conn->type == CONN_TYPE_AP || conn->type == CONN_TYPE_EXIT);
  97. if (conn->marked_for_close)
  98. return 0; /* already marked; probably got an 'end' */
  99. log_fn(LOG_INFO,"CircID %d: At an edge. Marking connection for close.",
  100. circ_id);
  101. conn->has_sent_end = 1; /* we're closing the circuit, nothing to send to */
  102. connection_mark_for_close(conn);
  103. conn->hold_open_until_flushed = 1;
  104. return 0;
  105. }
  106. /** Send a relay end cell from stream <b>conn</b> to conn's circuit,
  107. * with a destination of cpath_layer. (If cpath_layer is NULL, the
  108. * destination is the circuit's origin.) Mark the relay end cell as
  109. * closing because of <b>reason</b>.
  110. *
  111. * Return -1 if this function has already been called on this conn,
  112. * else return 0.
  113. */
  114. int
  115. connection_edge_end(connection_t *conn, char reason, crypt_path_t *cpath_layer)
  116. {
  117. char payload[5];
  118. size_t payload_len=1;
  119. circuit_t *circ;
  120. if (conn->has_sent_end) {
  121. log_fn(LOG_WARN,"It appears I've already sent the end. Are you calling me twice?");
  122. return -1;
  123. }
  124. payload[0] = reason;
  125. if (reason == END_STREAM_REASON_EXITPOLICY) {
  126. /* this is safe even for rend circs, because they never fail
  127. * because of exitpolicy */
  128. set_uint32(payload+1, htonl(conn->addr));
  129. payload_len += 4;
  130. }
  131. circ = circuit_get_by_conn(conn);
  132. if (circ && !circ->marked_for_close) {
  133. log_fn(LOG_DEBUG,"Marking conn (fd %d) and sending end.",conn->s);
  134. connection_edge_send_command(conn, circ, RELAY_COMMAND_END,
  135. payload, payload_len, cpath_layer);
  136. } else {
  137. log_fn(LOG_DEBUG,"Marking conn (fd %d); no circ to send end.",conn->s);
  138. }
  139. conn->has_sent_end = 1;
  140. return 0;
  141. }
  142. /** Connection <b>conn</b> has finished writing and has no bytes left on
  143. * its outbuf.
  144. *
  145. * If it's in state 'open', stop writing, consider responding with a
  146. * sendme, and return.
  147. * Otherwise, stop writing and return.
  148. *
  149. * If <b>conn</b> is broken, mark it for close and return -1, else
  150. * return 0.
  151. */
  152. int connection_edge_finished_flushing(connection_t *conn) {
  153. tor_assert(conn);
  154. tor_assert(conn->type == CONN_TYPE_AP || conn->type == CONN_TYPE_EXIT);
  155. switch (conn->state) {
  156. case AP_CONN_STATE_OPEN:
  157. case EXIT_CONN_STATE_OPEN:
  158. connection_stop_writing(conn);
  159. connection_edge_consider_sending_sendme(conn);
  160. return 0;
  161. case AP_CONN_STATE_SOCKS_WAIT:
  162. case AP_CONN_STATE_RENDDESC_WAIT:
  163. case AP_CONN_STATE_CIRCUIT_WAIT:
  164. case AP_CONN_STATE_CONNECT_WAIT:
  165. connection_stop_writing(conn);
  166. return 0;
  167. default:
  168. log_fn(LOG_WARN,"BUG: called in unexpected state %d.", conn->state);
  169. return -1;
  170. }
  171. return 0;
  172. }
  173. /** Connected handler for exit connections: start writing pending
  174. * data, deliver 'CONNECTED' relay cells as appropriate, and check
  175. * any pending data that may have been received. */
  176. int connection_edge_finished_connecting(connection_t *conn)
  177. {
  178. unsigned char connected_payload[4];
  179. tor_assert(conn);
  180. tor_assert(conn->type == CONN_TYPE_EXIT);
  181. tor_assert(conn->state == EXIT_CONN_STATE_CONNECTING);
  182. log_fn(LOG_INFO,"Exit connection to %s:%u established.",
  183. conn->address,conn->port);
  184. conn->state = EXIT_CONN_STATE_OPEN;
  185. connection_watch_events(conn, POLLIN); /* stop writing, continue reading */
  186. if (connection_wants_to_flush(conn)) /* in case there are any queued relay cells */
  187. connection_start_writing(conn);
  188. /* deliver a 'connected' relay cell back through the circuit. */
  189. if (connection_edge_is_rendezvous_stream(conn)) {
  190. if (connection_edge_send_command(conn, circuit_get_by_conn(conn),
  191. RELAY_COMMAND_CONNECTED, NULL, 0, conn->cpath_layer) < 0)
  192. return 0; /* circuit is closed, don't continue */
  193. } else {
  194. *(uint32_t*)connected_payload = htonl(conn->addr);
  195. if (connection_edge_send_command(conn, circuit_get_by_conn(conn),
  196. RELAY_COMMAND_CONNECTED, connected_payload, 4, conn->cpath_layer) < 0)
  197. return 0; /* circuit is closed, don't continue */
  198. }
  199. tor_assert(conn->package_window > 0);
  200. /* in case the server has written anything */
  201. return connection_edge_process_inbuf(conn, 1);
  202. }
  203. /** Find all general-purpose AP streams waiting for a response that sent
  204. * their begin/resolve cell >=15 seconds ago. Detach from their current circuit,
  205. * and mark their current circuit as unsuitable for new streams. Then call
  206. * connection_ap_handshake_attach_circuit() to attach to a new circuit (if
  207. * available) or launch a new one.
  208. *
  209. * For rendezvous streams, simply give up after 45 seconds (with no
  210. * retry attempt).
  211. */
  212. void connection_ap_expire_beginning(void) {
  213. connection_t **carray;
  214. connection_t *conn;
  215. circuit_t *circ;
  216. int n, i;
  217. time_t now = time(NULL);
  218. or_options_t *options = get_options();
  219. get_connection_array(&carray, &n);
  220. for (i = 0; i < n; ++i) {
  221. conn = carray[i];
  222. if (conn->type != CONN_TYPE_AP)
  223. continue;
  224. if (conn->state != AP_CONN_STATE_RESOLVE_WAIT &&
  225. conn->state != AP_CONN_STATE_CONNECT_WAIT)
  226. continue;
  227. if (now - conn->timestamp_lastread < 15)
  228. continue;
  229. circ = circuit_get_by_conn(conn);
  230. if (!circ) { /* it's vanished? */
  231. log_fn(LOG_WARN,"Conn is waiting (address %s), but lost its circ.",
  232. conn->socks_request->address);
  233. connection_mark_for_close(conn);
  234. continue;
  235. }
  236. if (circ->purpose == CIRCUIT_PURPOSE_C_REND_JOINED) {
  237. if (now - conn->timestamp_lastread > 45) {
  238. log_fn(LOG_WARN,"Rend stream is %d seconds late. Giving up on address '%s'.",
  239. (int)(now - conn->timestamp_lastread), conn->socks_request->address);
  240. connection_edge_end(conn, END_STREAM_REASON_TIMEOUT, conn->cpath_layer);
  241. connection_mark_for_close(conn);
  242. }
  243. continue;
  244. }
  245. tor_assert(circ->purpose == CIRCUIT_PURPOSE_C_GENERAL);
  246. log_fn(LOG_NOTICE,"Stream is %d seconds late on address '%s'. Retrying.",
  247. (int)(now - conn->timestamp_lastread), conn->socks_request->address);
  248. circuit_log_path(LOG_WARN, circ);
  249. /* send an end down the circuit */
  250. connection_edge_end(conn, END_STREAM_REASON_TIMEOUT, conn->cpath_layer);
  251. /* un-mark it as ending, since we're going to reuse it */
  252. conn->has_sent_end = 0;
  253. /* move it back into 'pending' state. */
  254. conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  255. circuit_detach_stream(circ, conn);
  256. /* kludge to make us not try this circuit again, yet to allow
  257. * current streams on it to survive if they can: make it
  258. * unattractive to use for new streams */
  259. tor_assert(circ->timestamp_dirty);
  260. circ->timestamp_dirty -= options->NewCircuitPeriod;
  261. /* give our stream another 15 seconds to try */
  262. conn->timestamp_lastread += 15;
  263. /* attaching to a dirty circuit is fine */
  264. if (connection_ap_handshake_attach_circuit(conn)<0) {
  265. /* it will never work */
  266. /* Don't need to send end -- we're not connected */
  267. conn->has_sent_end = 1;
  268. connection_mark_for_close(conn);
  269. }
  270. } /* end for */
  271. }
  272. /** Tell any AP streams that are waiting for a new circuit that one is
  273. * available.
  274. */
  275. void connection_ap_attach_pending(void)
  276. {
  277. connection_t **carray;
  278. connection_t *conn;
  279. int n, i;
  280. get_connection_array(&carray, &n);
  281. for (i = 0; i < n; ++i) {
  282. conn = carray[i];
  283. if (conn->marked_for_close ||
  284. conn->type != CONN_TYPE_AP ||
  285. conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
  286. continue;
  287. if (connection_ap_handshake_attach_circuit(conn) < 0) {
  288. /* -1 means it will never work */
  289. /* Don't send end; there is no 'other side' yet */
  290. conn->has_sent_end = 1;
  291. connection_mark_for_close(conn);
  292. }
  293. }
  294. }
  295. /** connection_edge_process_inbuf() found a conn in state
  296. * socks_wait. See if conn->inbuf has the right bytes to proceed with
  297. * the socks handshake.
  298. *
  299. * If the handshake is complete, and it's for a general circuit, then
  300. * try to attach it to a circuit (or launch one as needed). If it's for
  301. * a rendezvous circuit, then fetch a rendezvous descriptor first (or
  302. * attach/launch a circuit if the rendezvous descriptor is already here
  303. * and fresh enough).
  304. *
  305. * Return -1 if an unexpected error with conn (and it should be marked
  306. * for close), else return 0.
  307. */
  308. static int connection_ap_handshake_process_socks(connection_t *conn) {
  309. socks_request_t *socks;
  310. int sockshere;
  311. hostname_type_t addresstype;
  312. tor_assert(conn);
  313. tor_assert(conn->type == CONN_TYPE_AP);
  314. tor_assert(conn->state == AP_CONN_STATE_SOCKS_WAIT);
  315. tor_assert(conn->socks_request);
  316. socks = conn->socks_request;
  317. log_fn(LOG_DEBUG,"entered.");
  318. sockshere = fetch_from_buf_socks(conn->inbuf, socks);
  319. if (sockshere == -1 || sockshere == 0) {
  320. if (socks->replylen) { /* we should send reply back */
  321. log_fn(LOG_DEBUG,"reply is already set for us. Using it.");
  322. connection_ap_handshake_socks_reply(conn, socks->reply, socks->replylen, 0);
  323. socks->replylen = 0; /* zero it out so we can do another round of negotiation */
  324. } else if (sockshere == -1) { /* send normal reject */
  325. log_fn(LOG_WARN,"Fetching socks handshake failed. Closing.");
  326. connection_ap_handshake_socks_reply(conn, NULL, 0, -1);
  327. } else {
  328. log_fn(LOG_DEBUG,"socks handshake not all here yet.");
  329. }
  330. if (sockshere == -1)
  331. socks->has_finished = 1;
  332. return sockshere;
  333. } /* else socks handshake is done, continue processing */
  334. if (socks->command == SOCKS_COMMAND_RESOLVE) {
  335. uint32_t answer;
  336. /* Reply to resolves immediately if we can. */
  337. if (strlen(socks->address) > RELAY_PAYLOAD_SIZE) {
  338. log_fn(LOG_WARN,"Address to be resolved is too large. Failing.");
  339. connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_ERROR,0,NULL);
  340. return -1;
  341. }
  342. answer = htonl(client_dns_lookup_entry(socks->address));
  343. if (answer) {
  344. connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_IPV4,4,
  345. (char*)&answer);
  346. conn->has_sent_end = 1;
  347. connection_mark_for_close(conn);
  348. conn->hold_open_until_flushed = 1;
  349. return 0;
  350. }
  351. }
  352. /* Parse the address provided by SOCKS. Modify it in-place if it
  353. * specifies a hidden-service (.onion) or particular exit node (.exit).
  354. */
  355. addresstype = parse_extended_hostname(socks->address);
  356. if (addresstype == EXIT_HOSTNAME) {
  357. /* .exit -- modify conn to specify the exit node. */
  358. char *s = strrchr(socks->address,'.');
  359. if (!s || s[1] == '\0') {
  360. log_fn(LOG_WARN,"Malformed address '%s.exit'. Refusing.", socks->address);
  361. return -1;
  362. }
  363. conn->chosen_exit_name = tor_strdup(s+1);
  364. *s = 0;
  365. }
  366. if (addresstype != ONION_HOSTNAME) {
  367. /* not a hidden-service request (i.e. normal or .exit) */
  368. if (socks->command == SOCKS_COMMAND_CONNECT && socks->port == 0) {
  369. log_fn(LOG_WARN,"Application asked to connect to port 0. Refusing.");
  370. return -1;
  371. }
  372. conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  373. return connection_ap_handshake_attach_circuit(conn);
  374. } else {
  375. /* it's a hidden-service request */
  376. rend_cache_entry_t *entry;
  377. int r;
  378. if (socks->command == SOCKS_COMMAND_RESOLVE) {
  379. /* if it's a resolve request, fail it right now, rather than
  380. * building all the circuits and then realizing it won't work. */
  381. log_fn(LOG_WARN,"Resolve requests to hidden services not allowed. Failing.");
  382. connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_ERROR,0,NULL);
  383. return -1;
  384. }
  385. strlcpy(conn->rend_query, socks->address, sizeof(conn->rend_query));
  386. log_fn(LOG_INFO,"Got a hidden service request for ID '%s'", conn->rend_query);
  387. /* see if we already have it cached */
  388. r = rend_cache_lookup_entry(conn->rend_query, &entry);
  389. if (r<0) {
  390. log_fn(LOG_WARN,"Invalid service descriptor %s", conn->rend_query);
  391. return -1;
  392. }
  393. if (r==0) {
  394. conn->state = AP_CONN_STATE_RENDDESC_WAIT;
  395. log_fn(LOG_INFO, "Unknown descriptor %s. Fetching.", conn->rend_query);
  396. rend_client_refetch_renddesc(conn->rend_query);
  397. return 0;
  398. }
  399. if (r>0) {
  400. #define NUM_SECONDS_BEFORE_REFETCH (60*15)
  401. if (time(NULL) - entry->received < NUM_SECONDS_BEFORE_REFETCH) {
  402. conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  403. log_fn(LOG_INFO, "Descriptor is here and fresh enough. Great.");
  404. return connection_ap_handshake_attach_circuit(conn);
  405. } else {
  406. conn->state = AP_CONN_STATE_RENDDESC_WAIT;
  407. log_fn(LOG_INFO, "Stale descriptor %s. Refetching.", conn->rend_query);
  408. rend_client_refetch_renddesc(conn->rend_query);
  409. return 0;
  410. }
  411. }
  412. }
  413. return 0; /* unreached but keeps the compiler happy */
  414. }
  415. /** Iterate over the two bytes of stream_id until we get one that is not
  416. * already in use; return it. Return 0 if can't get a unique stream_id.
  417. */
  418. static uint16_t get_unique_stream_id_by_circ(circuit_t *circ) {
  419. connection_t *tmpconn;
  420. uint16_t test_stream_id;
  421. uint32_t attempts=0;
  422. again:
  423. test_stream_id = circ->next_stream_id++;
  424. if (++attempts > 1<<16) {
  425. /* Make sure we don't loop forever if all stream_id's are used. */
  426. log_fn(LOG_WARN,"No unused stream IDs. Failing.");
  427. return 0;
  428. }
  429. if (test_stream_id == 0)
  430. goto again;
  431. for (tmpconn = circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream)
  432. if (tmpconn->stream_id == test_stream_id)
  433. goto again;
  434. return test_stream_id;
  435. }
  436. /** Write a relay begin cell, using destaddr and destport from ap_conn's
  437. * socks_request field, and send it down circ.
  438. *
  439. * If ap_conn is broken, mark it for close and return -1. Else return 0.
  440. */
  441. int connection_ap_handshake_send_begin(connection_t *ap_conn, circuit_t *circ)
  442. {
  443. char payload[CELL_PAYLOAD_SIZE];
  444. int payload_len;
  445. struct in_addr in;
  446. const char *string_addr;
  447. tor_assert(ap_conn->type == CONN_TYPE_AP);
  448. tor_assert(ap_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
  449. tor_assert(ap_conn->socks_request);
  450. ap_conn->stream_id = get_unique_stream_id_by_circ(circ);
  451. if (ap_conn->stream_id==0) {
  452. /* Don't send end: there is no 'other side' yet */
  453. ap_conn->has_sent_end = 1;
  454. connection_mark_for_close(ap_conn);
  455. circuit_mark_for_close(circ);
  456. return -1;
  457. }
  458. if (circ->purpose == CIRCUIT_PURPOSE_C_GENERAL) {
  459. in.s_addr = htonl(client_dns_lookup_entry(ap_conn->socks_request->address));
  460. string_addr = in.s_addr ? inet_ntoa(in) : NULL;
  461. tor_snprintf(payload,RELAY_PAYLOAD_SIZE,
  462. "%s:%d",
  463. string_addr ? string_addr : ap_conn->socks_request->address,
  464. ap_conn->socks_request->port);
  465. } else {
  466. tor_snprintf(payload,RELAY_PAYLOAD_SIZE,
  467. ":%d", ap_conn->socks_request->port);
  468. }
  469. payload_len = strlen(payload)+1;
  470. log_fn(LOG_DEBUG,"Sending relay cell to begin stream %d.",ap_conn->stream_id);
  471. if (connection_edge_send_command(ap_conn, circ, RELAY_COMMAND_BEGIN,
  472. payload, payload_len, ap_conn->cpath_layer) < 0)
  473. return -1; /* circuit is closed, don't continue */
  474. ap_conn->package_window = STREAMWINDOW_START;
  475. ap_conn->deliver_window = STREAMWINDOW_START;
  476. ap_conn->state = AP_CONN_STATE_CONNECT_WAIT;
  477. log_fn(LOG_INFO,"Address/port sent, ap socket %d, n_circ_id %d",ap_conn->s,circ->n_circ_id);
  478. control_event_stream_status(ap_conn, STREAM_EVENT_SENT_CONNECT);
  479. return 0;
  480. }
  481. /** Write a relay resolve cell, using destaddr and destport from ap_conn's
  482. * socks_request field, and send it down circ.
  483. *
  484. * If ap_conn is broken, mark it for close and return -1. Else return 0.
  485. */
  486. int connection_ap_handshake_send_resolve(connection_t *ap_conn, circuit_t *circ)
  487. {
  488. int payload_len;
  489. const char *string_addr;
  490. tor_assert(ap_conn->type == CONN_TYPE_AP);
  491. tor_assert(ap_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
  492. tor_assert(ap_conn->socks_request);
  493. tor_assert(ap_conn->socks_request->command == SOCKS_COMMAND_RESOLVE);
  494. tor_assert(circ->purpose == CIRCUIT_PURPOSE_C_GENERAL);
  495. ap_conn->stream_id = get_unique_stream_id_by_circ(circ);
  496. if (ap_conn->stream_id==0) {
  497. /* Don't send end: there is no 'other side' yet */
  498. ap_conn->has_sent_end = 1;
  499. connection_mark_for_close(ap_conn);
  500. circuit_mark_for_close(circ);
  501. return -1;
  502. }
  503. string_addr = ap_conn->socks_request->address;
  504. payload_len = strlen(string_addr);
  505. tor_assert(strlen(string_addr) <= RELAY_PAYLOAD_SIZE);
  506. log_fn(LOG_DEBUG,"Sending relay cell to begin stream %d.",ap_conn->stream_id);
  507. if (connection_edge_send_command(ap_conn, circ, RELAY_COMMAND_RESOLVE,
  508. string_addr, payload_len, ap_conn->cpath_layer) < 0)
  509. return -1; /* circuit is closed, don't continue */
  510. ap_conn->state = AP_CONN_STATE_RESOLVE_WAIT;
  511. log_fn(LOG_INFO,"Address sent for resolve, ap socket %d, n_circ_id %d",ap_conn->s,circ->n_circ_id);
  512. control_event_stream_status(ap_conn, STREAM_EVENT_SENT_RESOLVE);
  513. return 0;
  514. }
  515. /** Make an AP connection_t, do a socketpair and attach one side
  516. * to the conn, connection_add it, initialize it to circuit_wait,
  517. * and call connection_ap_handshake_attach_circuit(conn) on it.
  518. *
  519. * Return the other end of the socketpair, or -1 if error.
  520. */
  521. int connection_ap_make_bridge(char *address, uint16_t port) {
  522. int fd[2];
  523. connection_t *conn;
  524. log_fn(LOG_INFO,"Making AP bridge to %s:%d ...",address,port);
  525. if (tor_socketpair(AF_UNIX, SOCK_STREAM, 0, fd) < 0) {
  526. log(LOG_WARN,"Couldn't construct socketpair (%s). Network down? Delaying.",
  527. tor_socket_strerror(tor_socket_errno(-1)));
  528. return -1;
  529. }
  530. set_socket_nonblocking(fd[0]);
  531. set_socket_nonblocking(fd[1]);
  532. conn = connection_new(CONN_TYPE_AP);
  533. conn->s = fd[0];
  534. /* populate conn->socks_request */
  535. /* leave version at zero, so the socks_reply is empty */
  536. conn->socks_request->socks_version = 0;
  537. conn->socks_request->has_finished = 0; /* waiting for 'connected' */
  538. strlcpy(conn->socks_request->address, address,
  539. sizeof(conn->socks_request->address));
  540. conn->socks_request->port = port;
  541. conn->socks_request->command = SOCKS_COMMAND_CONNECT;
  542. conn->address = tor_strdup("(local bridge)");
  543. conn->addr = 0;
  544. conn->port = 0;
  545. if (connection_add(conn) < 0) { /* no space, forget it */
  546. connection_free(conn); /* this closes fd[0] */
  547. tor_close_socket(fd[1]);
  548. return -1;
  549. }
  550. conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  551. connection_start_reading(conn);
  552. /* attaching to a dirty circuit is fine */
  553. if (connection_ap_handshake_attach_circuit(conn) < 0) {
  554. conn->has_sent_end = 1; /* no circ to send to */
  555. connection_mark_for_close(conn);
  556. tor_close_socket(fd[1]);
  557. return -1;
  558. }
  559. log_fn(LOG_INFO,"... AP bridge created and connected.");
  560. return fd[1];
  561. }
  562. /* DOCDOC */
  563. void connection_ap_handshake_socks_resolved(connection_t *conn,
  564. int answer_type,
  565. size_t answer_len,
  566. const char *answer)
  567. {
  568. char buf[256];
  569. size_t replylen;
  570. if (answer_type == RESOLVED_TYPE_IPV4) {
  571. uint32_t a = get_uint32(answer);
  572. if (a)
  573. client_dns_set_entry(conn->socks_request->address, ntohl(a));
  574. }
  575. if (conn->socks_request->socks_version == 4) {
  576. buf[0] = 0x00; /* version */
  577. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
  578. buf[1] = 90; /* "Granted" */
  579. set_uint16(buf+2, 0);
  580. memcpy(buf+4, answer, 4); /* address */
  581. replylen = SOCKS4_NETWORK_LEN;
  582. } else {
  583. buf[1] = 91; /* "error" */
  584. memset(buf+2, 0, 6);
  585. replylen = SOCKS4_NETWORK_LEN;
  586. }
  587. } else {
  588. /* SOCKS5 */
  589. buf[0] = 0x05; /* version */
  590. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
  591. buf[1] = 0; /* succeeded */
  592. buf[2] = 0; /* reserved */
  593. buf[3] = 0x01; /* IPv4 address type */
  594. memcpy(buf+4, answer, 4); /* address */
  595. set_uint16(buf+8, 0); /* port == 0. */
  596. replylen = 10;
  597. } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
  598. buf[1] = 0; /* succeeded */
  599. buf[2] = 0; /* reserved */
  600. buf[3] = 0x04; /* IPv6 address type */
  601. memcpy(buf+4, answer, 16); /* address */
  602. set_uint16(buf+20, 0); /* port == 0. */
  603. replylen = 22;
  604. } else {
  605. buf[1] = 0x04; /* host unreachable */
  606. memset(buf+2, 0, 8);
  607. replylen = 10;
  608. }
  609. }
  610. connection_ap_handshake_socks_reply(conn, buf, replylen,
  611. (answer_type == RESOLVED_TYPE_IPV4 ||
  612. answer_type == RESOLVED_TYPE_IPV6) ? 1 : -1);
  613. conn->socks_request->has_finished = 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. if (!connection_edge_is_rendezvous_stream(conn) &&
  815. router_compare_to_my_exit_policy(conn) == ADDR_POLICY_REJECTED) {
  816. log_fn(LOG_INFO,"%s:%d failed exit policy. Closing.", conn->address, conn->port);
  817. connection_edge_end(conn, END_STREAM_REASON_EXITPOLICY, conn->cpath_layer);
  818. circuit_detach_stream(circuit_get_by_conn(conn), conn);
  819. connection_free(conn);
  820. return;
  821. }
  822. addr = conn->addr;
  823. port = conn->port;
  824. if (redirect_exit_list) {
  825. SMARTLIST_FOREACH(redirect_exit_list, exit_redirect_t *, r,
  826. {
  827. if ((addr&r->mask)==(r->addr&r->mask) &&
  828. (r->port_min <= port) && (port <= r->port_max)) {
  829. struct in_addr in;
  830. if (r->is_redirect) {
  831. addr = r->addr_dest;
  832. port = r->port_dest;
  833. in.s_addr = htonl(addr);
  834. log_fn(LOG_DEBUG, "Redirecting connection from %s:%d to %s:%d",
  835. conn->address, conn->port, inet_ntoa(in), port);
  836. }
  837. break;
  838. }
  839. });
  840. }
  841. log_fn(LOG_DEBUG,"about to try connecting");
  842. switch (connection_connect(conn, conn->address, addr, port)) {
  843. case -1:
  844. connection_edge_end(conn, END_STREAM_REASON_CONNECTFAILED, conn->cpath_layer);
  845. circuit_detach_stream(circuit_get_by_conn(conn), conn);
  846. connection_free(conn);
  847. return;
  848. case 0:
  849. conn->state = EXIT_CONN_STATE_CONNECTING;
  850. connection_watch_events(conn, POLLOUT | POLLIN | POLLERR);
  851. /* writable indicates finish, readable indicates broken link,
  852. error indicates broken link in windowsland. */
  853. return;
  854. /* case 1: fall through */
  855. }
  856. conn->state = EXIT_CONN_STATE_OPEN;
  857. if (connection_wants_to_flush(conn)) { /* in case there are any queued data cells */
  858. log_fn(LOG_WARN,"tell roger: newly connected conn had data waiting!");
  859. // connection_start_writing(conn);
  860. }
  861. connection_watch_events(conn, POLLIN);
  862. /* also, deliver a 'connected' cell back through the circuit. */
  863. if (connection_edge_is_rendezvous_stream(conn)) { /* rendezvous stream */
  864. /* don't send an address back! */
  865. connection_edge_send_command(conn, circuit_get_by_conn(conn), RELAY_COMMAND_CONNECTED,
  866. NULL, 0, conn->cpath_layer);
  867. } else { /* normal stream */
  868. /* This must be the original address, not the redirected address. */
  869. *(uint32_t*)connected_payload = htonl(conn->addr);
  870. connection_edge_send_command(conn, circuit_get_by_conn(conn), RELAY_COMMAND_CONNECTED,
  871. connected_payload, 4, conn->cpath_layer);
  872. }
  873. }
  874. /** Return 1 if <b>conn</b> is a rendezvous stream, or 0 if
  875. * it is a general stream.
  876. */
  877. int connection_edge_is_rendezvous_stream(connection_t *conn) {
  878. tor_assert(conn);
  879. if (*conn->rend_query) /* XXX */
  880. return 1;
  881. return 0;
  882. }
  883. /** Return 1 if router <b>exit</b> might allow stream <b>conn</b>
  884. * to exit from it, or 0 if it definitely will not allow it.
  885. * (We might be uncertain if conn's destination address has not yet been
  886. * resolved.)
  887. */
  888. int connection_ap_can_use_exit(connection_t *conn, routerinfo_t *exit)
  889. {
  890. uint32_t addr;
  891. tor_assert(conn);
  892. tor_assert(conn->type == CONN_TYPE_AP);
  893. tor_assert(conn->socks_request);
  894. tor_assert(exit);
  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 a particular exit node has been requested for the new connection,
  899. * make sure the exit node of the existing circuit matches exactly.
  900. */
  901. if (conn->chosen_exit_name) {
  902. if (router_get_by_nickname(conn->chosen_exit_name) != exit) {
  903. /* doesn't match */
  904. log_fn(LOG_DEBUG,"Requested node '%s', considering node '%s'. No.",
  905. conn->chosen_exit_name, exit->nickname);
  906. return 0;
  907. }
  908. }
  909. if (conn->socks_request->command == SOCKS_COMMAND_RESOLVE) {
  910. /* 0.0.8 servers have buggy resolve support. */
  911. if (!tor_version_as_new_as(exit->platform, "0.0.9pre1"))
  912. return 0;
  913. } else {
  914. addr = client_dns_lookup_entry(conn->socks_request->address);
  915. if (router_compare_addr_to_addr_policy(addr, conn->socks_request->port,
  916. exit->exit_policy) < 0)
  917. return 0;
  918. }
  919. return 1;
  920. }
  921. /** A helper function for socks_policy_permits_address() below.
  922. *
  923. * Parse options->SocksPolicy in the same way that the exit policy
  924. * is parsed, and put the processed version in &socks_policy.
  925. * Ignore port specifiers.
  926. */
  927. void
  928. parse_socks_policy(void)
  929. {
  930. addr_policy_t *n;
  931. if (socks_policy) {
  932. addr_policy_free(socks_policy);
  933. socks_policy = NULL;
  934. }
  935. config_parse_addr_policy(get_options()->SocksPolicy, &socks_policy);
  936. /* ports aren't used. */
  937. for (n=socks_policy; n; n = n->next) {
  938. n->prt_min = 1;
  939. n->prt_max = 65535;
  940. }
  941. }
  942. /** Return 1 if <b>addr</b> is permitted to connect to our socks port,
  943. * based on <b>socks_policy</b>. Else return 0.
  944. */
  945. int socks_policy_permits_address(uint32_t addr)
  946. {
  947. int a;
  948. if (!socks_policy) /* 'no socks policy' means 'accept' */
  949. return 1;
  950. a = router_compare_addr_to_addr_policy(addr, 1, socks_policy);
  951. if (a==-1)
  952. return 0;
  953. else if (a==0)
  954. return 1;
  955. tor_assert(a==1);
  956. log_fn(LOG_WARN, "Got unexpected 'maybe' answer from socks policy");
  957. return 0;
  958. }
  959. /* ***** Client DNS code ***** */
  960. /* XXX Perhaps this should get merged with the dns.c code somehow. */
  961. /* XXX But we can't just merge them, because then nodes that act as
  962. * both OR and OP could be attacked: people could rig the dns cache
  963. * by answering funny things to stream begin requests, and later
  964. * other clients would reuse those funny addr's. Hm.
  965. */
  966. /** A client-side struct to remember the resolved IP (addr) for
  967. * a given address. These structs make up a tree, with client_dns_map
  968. * below as its root.
  969. */
  970. struct client_dns_entry {
  971. uint32_t addr; /**< The resolved IP of this entry. */
  972. time_t expires; /**< At what second does addr expire? */
  973. int n_failures; /**< How many times has this entry failed to resolve so far? */
  974. };
  975. /** How many elements are in the client dns cache currently? */
  976. static int client_dns_size = 0;
  977. /** The tree of client-side cached DNS resolves. */
  978. static strmap_t *client_dns_map = NULL;
  979. /** Initialize client_dns_map and client_dns_size. */
  980. void client_dns_init(void) {
  981. client_dns_map = strmap_new();
  982. client_dns_size = 0;
  983. }
  984. /** Return the client_dns_entry that corresponds to <b>address</b>.
  985. * If it's not there, allocate and return a new entry for <b>address</b>.
  986. */
  987. static struct client_dns_entry *
  988. _get_or_create_ent(const char *address)
  989. {
  990. struct client_dns_entry *ent;
  991. ent = strmap_get_lc(client_dns_map,address);
  992. if (!ent) {
  993. ent = tor_malloc_zero(sizeof(struct client_dns_entry));
  994. ent->expires = time(NULL)+MAX_DNS_ENTRY_AGE;
  995. strmap_set_lc(client_dns_map,address,ent);
  996. ++client_dns_size;
  997. }
  998. return ent;
  999. }
  1000. /** Return the IP associated with <b>address</b>, if we know it
  1001. * and it's still fresh enough. Otherwise return 0.
  1002. */
  1003. uint32_t client_dns_lookup_entry(const char *address)
  1004. {
  1005. struct client_dns_entry *ent;
  1006. struct in_addr in;
  1007. time_t now;
  1008. tor_assert(address);
  1009. if (tor_inet_aton(address, &in)) {
  1010. log_fn(LOG_DEBUG, "Using static address %s (%08lX)", address,
  1011. (unsigned long)ntohl(in.s_addr));
  1012. return ntohl(in.s_addr);
  1013. }
  1014. ent = strmap_get_lc(client_dns_map,address);
  1015. if (!ent || !ent->addr) {
  1016. log_fn(LOG_DEBUG, "No entry found for address %s", address);
  1017. return 0;
  1018. } else {
  1019. now = time(NULL);
  1020. if (ent->expires < now) {
  1021. log_fn(LOG_DEBUG, "Expired entry found for address %s", address);
  1022. strmap_remove_lc(client_dns_map,address);
  1023. tor_free(ent);
  1024. --client_dns_size;
  1025. return 0;
  1026. }
  1027. in.s_addr = htonl(ent->addr);
  1028. log_fn(LOG_DEBUG, "Found cached entry for address %s: %s", address,
  1029. inet_ntoa(in));
  1030. return ent->addr;
  1031. }
  1032. }
  1033. /** An attempt to resolve <b>address</b> failed at some OR.
  1034. * Increment the number of resolve failures we have on record
  1035. * for it, and then return that number.
  1036. */
  1037. int client_dns_incr_failures(const char *address)
  1038. {
  1039. struct client_dns_entry *ent;
  1040. ent = _get_or_create_ent(address);
  1041. ++ent->n_failures;
  1042. log_fn(LOG_DEBUG,"Address %s now has %d resolve failures.",
  1043. address, ent->n_failures);
  1044. return ent->n_failures;
  1045. }
  1046. /** Record the fact that <b>address</b> resolved to <b>val</b>.
  1047. * We can now use this in subsequent streams in client_dns_lookup_entry(),
  1048. * so we can more correctly choose a router that will allow <b>address</b>
  1049. * to exit from him.
  1050. */
  1051. void client_dns_set_entry(const char *address, uint32_t val)
  1052. {
  1053. struct client_dns_entry *ent;
  1054. struct in_addr in;
  1055. time_t now;
  1056. tor_assert(address);
  1057. tor_assert(val);
  1058. if (tor_inet_aton(address, &in))
  1059. return;
  1060. now = time(NULL);
  1061. ent = _get_or_create_ent(address);
  1062. in.s_addr = htonl(val);
  1063. log_fn(LOG_DEBUG, "Updating entry for address %s: %s", address,
  1064. inet_ntoa(in));
  1065. ent->addr = val;
  1066. ent->expires = now+MAX_DNS_ENTRY_AGE;
  1067. ent->n_failures = 0;
  1068. }
  1069. /** A helper function for client_dns_clean() below. If ent is too old,
  1070. * then remove it from the tree and return NULL, else return ent.
  1071. */
  1072. static void* _remove_if_expired(const char *addr,
  1073. struct client_dns_entry *ent,
  1074. time_t *nowp)
  1075. {
  1076. if (ent->expires < *nowp) {
  1077. --client_dns_size;
  1078. tor_free(ent);
  1079. return NULL;
  1080. } else {
  1081. return ent;
  1082. }
  1083. }
  1084. /** Clean out entries from the client-side DNS cache that were
  1085. * resolved long enough ago that they are no longer valid.
  1086. */
  1087. void client_dns_clean(void)
  1088. {
  1089. time_t now;
  1090. if (!client_dns_size)
  1091. return;
  1092. now = time(NULL);
  1093. strmap_foreach(client_dns_map, (strmap_foreach_fn)_remove_if_expired, &now);
  1094. }
  1095. /** Make connection redirection follow the provided list of
  1096. * exit_redirect_t */
  1097. void
  1098. set_exit_redirects(smartlist_t *lst)
  1099. {
  1100. if (redirect_exit_list) {
  1101. SMARTLIST_FOREACH(redirect_exit_list, exit_redirect_t *, p, tor_free(p));
  1102. smartlist_free(redirect_exit_list);
  1103. }
  1104. redirect_exit_list = lst;
  1105. }
  1106. /** If address is of the form "y.onion" with a well-formed handle y:
  1107. * Put a '\0' after y, lower-case it, and return ONION_HOSTNAME.
  1108. *
  1109. * If address is of the form "y.exit":
  1110. * Put a '\0' after y and return EXIT_HOSTNAME.
  1111. *
  1112. * Otherwise:
  1113. * Return NORMAL_HOSTNAME and change nothing.
  1114. */
  1115. hostname_type_t
  1116. parse_extended_hostname(char *address) {
  1117. char *s;
  1118. char query[REND_SERVICE_ID_LEN+1];
  1119. s = strrchr(address,'.');
  1120. if (!s) return 0; /* no dot, thus normal */
  1121. if (!strcasecmp(s+1,"exit")) {
  1122. *s = 0; /* null-terminate it */
  1123. return EXIT_HOSTNAME; /* .exit */
  1124. }
  1125. if (strcasecmp(s+1,"onion"))
  1126. return NORMAL_HOSTNAME; /* neither .exit nor .onion, thus normal */
  1127. /* so it is .onion */
  1128. *s = 0; /* null-terminate it */
  1129. if (strlcpy(query, address, REND_SERVICE_ID_LEN+1) >= REND_SERVICE_ID_LEN+1)
  1130. goto failed;
  1131. tor_strlower(query);
  1132. if (rend_valid_service_id(query)) {
  1133. tor_strlower(address);
  1134. return ONION_HOSTNAME; /* success */
  1135. }
  1136. failed:
  1137. /* otherwise, return to previous state and return 0 */
  1138. *s = '.';
  1139. return NORMAL_HOSTNAME;
  1140. }