connection_edge.c 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274
  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. if (!conn->marked_for_close) {
  39. /* only mark it if not already marked. it's possible to
  40. * get the 'end' right around when the client hangs up on us. */
  41. connection_edge_end(conn, END_STREAM_REASON_DONE, conn->cpath_layer);
  42. connection_mark_for_close(conn);
  43. conn->hold_open_until_flushed = 1; /* just because we shouldn't read
  44. doesn't mean we shouldn't write */
  45. }
  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,"Bug: 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,"Bug: Calling connection_edge_end on an already ended stream?");
  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, EV_READ); /* 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_INFO,"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_NOTICE,"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_NOTICE, 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->MaxCircuitDirtiness;
  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. /* Parse the address provided by SOCKS. Modify it in-place if it
  335. * specifies a hidden-service (.onion) or particular exit node (.exit).
  336. */
  337. addresstype = parse_extended_hostname(socks->address);
  338. if (addresstype == EXIT_HOSTNAME) {
  339. /* .exit -- modify conn to specify the exit node. */
  340. char *s = strrchr(socks->address,'.');
  341. if (!s || s[1] == '\0') {
  342. log_fn(LOG_WARN,"Malformed address '%s.exit'. Refusing.", socks->address);
  343. return -1;
  344. }
  345. conn->chosen_exit_name = tor_strdup(s+1);
  346. *s = 0;
  347. }
  348. if (addresstype != ONION_HOSTNAME) {
  349. /* not a hidden-service request (i.e. normal or .exit) */
  350. if (socks->command == SOCKS_COMMAND_RESOLVE) {
  351. uint32_t answer = 0;
  352. struct in_addr in;
  353. /* Reply to resolves immediately if we can. */
  354. if (strlen(socks->address) > RELAY_PAYLOAD_SIZE) {
  355. log_fn(LOG_WARN,"Address to be resolved is too large. Failing.");
  356. connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_ERROR,0,NULL);
  357. return -1;
  358. }
  359. if (tor_inet_aton(socks->address, &in)) /* see if it's an IP already */
  360. answer = in.s_addr;
  361. if (!answer && !conn->chosen_exit_name) /* if it's not .exit, check cache */
  362. answer = htonl(client_dns_lookup_entry(socks->address));
  363. if (answer) {
  364. connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_IPV4,4,
  365. (char*)&answer);
  366. conn->has_sent_end = 1;
  367. connection_mark_for_close(conn);
  368. conn->hold_open_until_flushed = 1;
  369. return 0;
  370. }
  371. rep_hist_note_used_resolve(time(NULL)); /* help predict this next time */
  372. } else { /* socks->command == SOCKS_COMMAND_CONNECT */
  373. if (socks->port == 0) {
  374. log_fn(LOG_NOTICE,"Application asked to connect to port 0. Refusing.");
  375. return -1;
  376. }
  377. rep_hist_note_used_port(socks->port, time(NULL)); /* help predict this next time */
  378. }
  379. conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  380. return connection_ap_handshake_attach_circuit(conn);
  381. } else {
  382. /* it's a hidden-service request */
  383. rend_cache_entry_t *entry;
  384. int r;
  385. if (socks->command == SOCKS_COMMAND_RESOLVE) {
  386. /* if it's a resolve request, fail it right now, rather than
  387. * building all the circuits and then realizing it won't work. */
  388. log_fn(LOG_WARN,"Resolve requests to hidden services not allowed. Failing.");
  389. connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_ERROR,0,NULL);
  390. return -1;
  391. }
  392. strlcpy(conn->rend_query, socks->address, sizeof(conn->rend_query));
  393. log_fn(LOG_INFO,"Got a hidden service request for ID '%s'", conn->rend_query);
  394. /* see if we already have it cached */
  395. r = rend_cache_lookup_entry(conn->rend_query, &entry);
  396. if (r<0) {
  397. log_fn(LOG_WARN,"Invalid service descriptor %s", conn->rend_query);
  398. return -1;
  399. }
  400. if (r==0) {
  401. conn->state = AP_CONN_STATE_RENDDESC_WAIT;
  402. log_fn(LOG_INFO, "Unknown descriptor %s. Fetching.", conn->rend_query);
  403. rend_client_refetch_renddesc(conn->rend_query);
  404. return 0;
  405. }
  406. if (r>0) {
  407. #define NUM_SECONDS_BEFORE_REFETCH (60*15)
  408. if (time(NULL) - entry->received < NUM_SECONDS_BEFORE_REFETCH) {
  409. conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  410. log_fn(LOG_INFO, "Descriptor is here and fresh enough. Great.");
  411. return connection_ap_handshake_attach_circuit(conn);
  412. } else {
  413. conn->state = AP_CONN_STATE_RENDDESC_WAIT;
  414. log_fn(LOG_INFO, "Stale descriptor %s. Refetching.", conn->rend_query);
  415. rend_client_refetch_renddesc(conn->rend_query);
  416. return 0;
  417. }
  418. }
  419. }
  420. return 0; /* unreached but keeps the compiler happy */
  421. }
  422. /** Iterate over the two bytes of stream_id until we get one that is not
  423. * already in use; return it. Return 0 if can't get a unique stream_id.
  424. */
  425. static uint16_t get_unique_stream_id_by_circ(circuit_t *circ) {
  426. connection_t *tmpconn;
  427. uint16_t test_stream_id;
  428. uint32_t attempts=0;
  429. again:
  430. test_stream_id = circ->next_stream_id++;
  431. if (++attempts > 1<<16) {
  432. /* Make sure we don't loop forever if all stream_id's are used. */
  433. log_fn(LOG_WARN,"No unused stream IDs. Failing.");
  434. return 0;
  435. }
  436. if (test_stream_id == 0)
  437. goto again;
  438. for (tmpconn = circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream)
  439. if (tmpconn->stream_id == test_stream_id)
  440. goto again;
  441. return test_stream_id;
  442. }
  443. /** Write a relay begin cell, using destaddr and destport from ap_conn's
  444. * socks_request field, and send it down circ.
  445. *
  446. * If ap_conn is broken, mark it for close and return -1. Else return 0.
  447. */
  448. int connection_ap_handshake_send_begin(connection_t *ap_conn, circuit_t *circ)
  449. {
  450. char payload[CELL_PAYLOAD_SIZE];
  451. int payload_len;
  452. struct in_addr in;
  453. const char *string_addr;
  454. tor_assert(ap_conn->type == CONN_TYPE_AP);
  455. tor_assert(ap_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
  456. tor_assert(ap_conn->socks_request);
  457. ap_conn->stream_id = get_unique_stream_id_by_circ(circ);
  458. if (ap_conn->stream_id==0) {
  459. /* Don't send end: there is no 'other side' yet */
  460. ap_conn->has_sent_end = 1;
  461. connection_mark_for_close(ap_conn);
  462. circuit_mark_for_close(circ);
  463. return -1;
  464. }
  465. if (circ->purpose == CIRCUIT_PURPOSE_C_GENERAL) {
  466. in.s_addr = htonl(client_dns_lookup_entry(ap_conn->socks_request->address));
  467. string_addr = in.s_addr ? inet_ntoa(in) : NULL;
  468. tor_snprintf(payload,RELAY_PAYLOAD_SIZE,
  469. "%s:%d",
  470. string_addr ? string_addr : ap_conn->socks_request->address,
  471. ap_conn->socks_request->port);
  472. } else {
  473. tor_snprintf(payload,RELAY_PAYLOAD_SIZE,
  474. ":%d", ap_conn->socks_request->port);
  475. }
  476. payload_len = strlen(payload)+1;
  477. log_fn(LOG_DEBUG,"Sending relay cell to begin stream %d.",ap_conn->stream_id);
  478. if (connection_edge_send_command(ap_conn, circ, RELAY_COMMAND_BEGIN,
  479. payload, payload_len, ap_conn->cpath_layer) < 0)
  480. return -1; /* circuit is closed, don't continue */
  481. ap_conn->package_window = STREAMWINDOW_START;
  482. ap_conn->deliver_window = STREAMWINDOW_START;
  483. ap_conn->state = AP_CONN_STATE_CONNECT_WAIT;
  484. log_fn(LOG_INFO,"Address/port sent, ap socket %d, n_circ_id %d",ap_conn->s,circ->n_circ_id);
  485. control_event_stream_status(ap_conn, STREAM_EVENT_SENT_CONNECT);
  486. return 0;
  487. }
  488. /** Write a relay resolve cell, using destaddr and destport from ap_conn's
  489. * socks_request field, and send it down circ.
  490. *
  491. * If ap_conn is broken, mark it for close and return -1. Else return 0.
  492. */
  493. int connection_ap_handshake_send_resolve(connection_t *ap_conn, circuit_t *circ)
  494. {
  495. int payload_len;
  496. const char *string_addr;
  497. tor_assert(ap_conn->type == CONN_TYPE_AP);
  498. tor_assert(ap_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
  499. tor_assert(ap_conn->socks_request);
  500. tor_assert(ap_conn->socks_request->command == SOCKS_COMMAND_RESOLVE);
  501. tor_assert(circ->purpose == CIRCUIT_PURPOSE_C_GENERAL);
  502. ap_conn->stream_id = get_unique_stream_id_by_circ(circ);
  503. if (ap_conn->stream_id==0) {
  504. /* Don't send end: there is no 'other side' yet */
  505. ap_conn->has_sent_end = 1;
  506. connection_mark_for_close(ap_conn);
  507. circuit_mark_for_close(circ);
  508. return -1;
  509. }
  510. string_addr = ap_conn->socks_request->address;
  511. payload_len = strlen(string_addr);
  512. tor_assert(strlen(string_addr) <= RELAY_PAYLOAD_SIZE);
  513. log_fn(LOG_DEBUG,"Sending relay cell to begin stream %d.",ap_conn->stream_id);
  514. if (connection_edge_send_command(ap_conn, circ, RELAY_COMMAND_RESOLVE,
  515. string_addr, payload_len, ap_conn->cpath_layer) < 0)
  516. return -1; /* circuit is closed, don't continue */
  517. ap_conn->state = AP_CONN_STATE_RESOLVE_WAIT;
  518. log_fn(LOG_INFO,"Address sent for resolve, ap socket %d, n_circ_id %d",ap_conn->s,circ->n_circ_id);
  519. control_event_stream_status(ap_conn, STREAM_EVENT_SENT_RESOLVE);
  520. return 0;
  521. }
  522. /** Make an AP connection_t, do a socketpair and attach one side
  523. * to the conn, connection_add it, initialize it to circuit_wait,
  524. * and call connection_ap_handshake_attach_circuit(conn) on it.
  525. *
  526. * Return the other end of the socketpair, or -1 if error.
  527. */
  528. int connection_ap_make_bridge(char *address, uint16_t port) {
  529. int fd[2];
  530. connection_t *conn;
  531. log_fn(LOG_INFO,"Making AP bridge to %s:%d ...",address,port);
  532. if (tor_socketpair(AF_UNIX, SOCK_STREAM, 0, fd) < 0) {
  533. log(LOG_WARN,"Couldn't construct socketpair (%s). Network down? Delaying.",
  534. tor_socket_strerror(tor_socket_errno(-1)));
  535. return -1;
  536. }
  537. set_socket_nonblocking(fd[0]);
  538. set_socket_nonblocking(fd[1]);
  539. conn = connection_new(CONN_TYPE_AP);
  540. conn->s = fd[0];
  541. /* populate conn->socks_request */
  542. /* leave version at zero, so the socks_reply is empty */
  543. conn->socks_request->socks_version = 0;
  544. conn->socks_request->has_finished = 0; /* waiting for 'connected' */
  545. strlcpy(conn->socks_request->address, address,
  546. sizeof(conn->socks_request->address));
  547. conn->socks_request->port = port;
  548. conn->socks_request->command = SOCKS_COMMAND_CONNECT;
  549. conn->address = tor_strdup("(local bridge)");
  550. conn->addr = 0;
  551. conn->port = 0;
  552. if (connection_add(conn) < 0) { /* no space, forget it */
  553. connection_free(conn); /* this closes fd[0] */
  554. tor_close_socket(fd[1]);
  555. return -1;
  556. }
  557. conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  558. connection_start_reading(conn);
  559. /* attaching to a dirty circuit is fine */
  560. if (connection_ap_handshake_attach_circuit(conn) < 0) {
  561. conn->has_sent_end = 1; /* no circ to send to */
  562. connection_mark_for_close(conn);
  563. tor_close_socket(fd[1]);
  564. return -1;
  565. }
  566. log_fn(LOG_INFO,"... AP bridge created and connected.");
  567. return fd[1];
  568. }
  569. /* DOCDOC */
  570. void connection_ap_handshake_socks_resolved(connection_t *conn,
  571. int answer_type,
  572. size_t answer_len,
  573. const char *answer)
  574. {
  575. char buf[256];
  576. size_t replylen;
  577. if (answer_type == RESOLVED_TYPE_IPV4) {
  578. uint32_t a = get_uint32(answer);
  579. if (a)
  580. client_dns_set_entry(conn->socks_request->address, ntohl(a));
  581. }
  582. if (conn->socks_request->socks_version == 4) {
  583. buf[0] = 0x00; /* version */
  584. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
  585. buf[1] = 90; /* "Granted" */
  586. set_uint16(buf+2, 0);
  587. memcpy(buf+4, answer, 4); /* address */
  588. replylen = SOCKS4_NETWORK_LEN;
  589. } else {
  590. buf[1] = 91; /* "error" */
  591. memset(buf+2, 0, 6);
  592. replylen = SOCKS4_NETWORK_LEN;
  593. }
  594. } else {
  595. /* SOCKS5 */
  596. buf[0] = 0x05; /* version */
  597. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
  598. buf[1] = 0; /* succeeded */
  599. buf[2] = 0; /* reserved */
  600. buf[3] = 0x01; /* IPv4 address type */
  601. memcpy(buf+4, answer, 4); /* address */
  602. set_uint16(buf+8, 0); /* port == 0. */
  603. replylen = 10;
  604. } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
  605. buf[1] = 0; /* succeeded */
  606. buf[2] = 0; /* reserved */
  607. buf[3] = 0x04; /* IPv6 address type */
  608. memcpy(buf+4, answer, 16); /* address */
  609. set_uint16(buf+20, 0); /* port == 0. */
  610. replylen = 22;
  611. } else {
  612. buf[1] = 0x04; /* host unreachable */
  613. memset(buf+2, 0, 8);
  614. replylen = 10;
  615. }
  616. }
  617. connection_ap_handshake_socks_reply(conn, buf, replylen,
  618. (answer_type == RESOLVED_TYPE_IPV4 ||
  619. answer_type == RESOLVED_TYPE_IPV6) ? 1 : -1);
  620. conn->socks_request->has_finished = 1;
  621. }
  622. /** Send a socks reply to stream <b>conn</b>, using the appropriate
  623. * socks version, etc.
  624. *
  625. * Status can be 1 (succeeded), -1 (failed), or 0 (not sure yet).
  626. *
  627. * If <b>reply</b> is defined, then write <b>replylen</b> bytes of it
  628. * to conn and return, else reply based on <b>status</b>.
  629. *
  630. * If <b>reply</b> is undefined, <b>status</b> can't be 0.
  631. */
  632. void connection_ap_handshake_socks_reply(connection_t *conn, char *reply,
  633. size_t replylen, int status) {
  634. char buf[256];
  635. if (status) /* it's either 1 or -1 */
  636. control_event_stream_status(conn,
  637. status==1 ? STREAM_EVENT_SUCCEEDED : STREAM_EVENT_FAILED);
  638. if (replylen) { /* we already have a reply in mind */
  639. connection_write_to_buf(reply, replylen, conn);
  640. return;
  641. }
  642. tor_assert(conn->socks_request);
  643. tor_assert(status == 1 || status == -1);
  644. if (conn->socks_request->socks_version == 4) {
  645. memset(buf,0,SOCKS4_NETWORK_LEN);
  646. #define SOCKS4_GRANTED 90
  647. #define SOCKS4_REJECT 91
  648. buf[1] = (status==1 ? SOCKS4_GRANTED : SOCKS4_REJECT);
  649. /* leave version, destport, destip zero */
  650. connection_write_to_buf(buf, SOCKS4_NETWORK_LEN, conn);
  651. }
  652. if (conn->socks_request->socks_version == 5) {
  653. buf[0] = 5; /* version 5 */
  654. #define SOCKS5_SUCCESS 0
  655. #define SOCKS5_GENERIC_ERROR 1
  656. buf[1] = status==1 ? SOCKS5_SUCCESS : SOCKS5_GENERIC_ERROR;
  657. buf[2] = 0;
  658. buf[3] = 1; /* ipv4 addr */
  659. memset(buf+4,0,6); /* Set external addr/port to 0.
  660. The spec doesn't seem to say what to do here. -RD */
  661. connection_write_to_buf(buf,10,conn);
  662. }
  663. /* If socks_version isn't 4 or 5, don't send anything.
  664. * This can happen in the case of AP bridges. */
  665. return;
  666. }
  667. /** A relay 'begin' cell has arrived, and either we are an exit hop
  668. * for the circuit, or we are the origin and it is a rendezvous begin.
  669. *
  670. * Launch a new exit connection and initialize things appropriately.
  671. *
  672. * If it's a rendezvous stream, call connection_exit_connect() on
  673. * it.
  674. *
  675. * For general streams, call dns_resolve() on it first, and only call
  676. * connection_exit_connect() if the dns answer is already known.
  677. *
  678. * Note that we don't call connection_add() on the new stream! We wait
  679. * for connection_exit_connect() to do that.
  680. *
  681. * Return -1 if we want to tear down <b>circ</b>. Else return 0.
  682. */
  683. int connection_exit_begin_conn(cell_t *cell, circuit_t *circ) {
  684. connection_t *n_stream;
  685. relay_header_t rh;
  686. char *address=NULL;
  687. uint16_t port;
  688. assert_circuit_ok(circ);
  689. relay_header_unpack(&rh, cell->payload);
  690. /* XXX currently we don't send an end cell back if we drop the
  691. * begin because it's malformed.
  692. */
  693. if (!memchr(cell->payload+RELAY_HEADER_SIZE, 0, rh.length)) {
  694. log_fn(LOG_WARN,"relay begin cell has no \\0. Dropping.");
  695. return 0;
  696. }
  697. if (parse_addr_port(cell->payload+RELAY_HEADER_SIZE,&address,NULL,&port)<0) {
  698. log_fn(LOG_WARN,"Unable to parse addr:port in relay begin cell. Dropping.");
  699. return 0;
  700. }
  701. if (port==0) {
  702. log_fn(LOG_WARN,"Missing port in relay begin cell. Dropping.");
  703. tor_free(address);
  704. return 0;
  705. }
  706. log_fn(LOG_DEBUG,"Creating new exit connection.");
  707. n_stream = connection_new(CONN_TYPE_EXIT);
  708. n_stream->purpose = EXIT_PURPOSE_CONNECT;
  709. n_stream->stream_id = rh.stream_id;
  710. n_stream->port = port;
  711. /* leave n_stream->s at -1, because it's not yet valid */
  712. n_stream->package_window = STREAMWINDOW_START;
  713. n_stream->deliver_window = STREAMWINDOW_START;
  714. if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED) {
  715. log_fn(LOG_DEBUG,"begin is for rendezvous. configuring stream.");
  716. n_stream->address = tor_strdup("(rendezvous)");
  717. n_stream->state = EXIT_CONN_STATE_CONNECTING;
  718. strlcpy(n_stream->rend_query, circ->rend_query,
  719. sizeof(n_stream->rend_query));
  720. tor_assert(connection_edge_is_rendezvous_stream(n_stream));
  721. assert_circuit_ok(circ);
  722. if (rend_service_set_connection_addr_port(n_stream, circ) < 0) {
  723. log_fn(LOG_INFO,"Didn't find rendezvous service (port %d)",n_stream->port);
  724. connection_edge_end(n_stream, END_STREAM_REASON_EXITPOLICY, n_stream->cpath_layer);
  725. connection_free(n_stream);
  726. circuit_mark_for_close(circ); /* knock the whole thing down, somebody screwed up */
  727. tor_free(address);
  728. return 0;
  729. }
  730. assert_circuit_ok(circ);
  731. log_fn(LOG_DEBUG,"Finished assigning addr/port");
  732. n_stream->cpath_layer = circ->cpath->prev; /* link it */
  733. /* add it into the linked list of n_streams on this circuit */
  734. n_stream->next_stream = circ->n_streams;
  735. circ->n_streams = n_stream;
  736. assert_circuit_ok(circ);
  737. connection_exit_connect(n_stream);
  738. tor_free(address);
  739. return 0;
  740. }
  741. n_stream->address = address;
  742. n_stream->state = EXIT_CONN_STATE_RESOLVEFAILED;
  743. /* default to failed, change in dns_resolve if it turns out not to fail */
  744. if (we_are_hibernating()) {
  745. connection_edge_end(n_stream, END_STREAM_REASON_EXITPOLICY, n_stream->cpath_layer);
  746. connection_free(n_stream);
  747. return 0;
  748. }
  749. /* send it off to the gethostbyname farm */
  750. switch (dns_resolve(n_stream)) {
  751. case 1: /* resolve worked */
  752. /* add it into the linked list of n_streams on this circuit */
  753. n_stream->next_stream = circ->n_streams;
  754. circ->n_streams = n_stream;
  755. assert_circuit_ok(circ);
  756. connection_exit_connect(n_stream);
  757. return 0;
  758. case -1: /* resolve failed */
  759. log_fn(LOG_INFO,"Resolve failed (%s).", n_stream->address);
  760. if (!n_stream->marked_for_close) {
  761. connection_edge_end(n_stream, END_STREAM_REASON_RESOLVEFAILED,
  762. n_stream->cpath_layer);
  763. }
  764. connection_free(n_stream);
  765. break;
  766. case 0: /* resolve added to pending list */
  767. /* add it into the linked list of resolving_streams on this circuit */
  768. n_stream->next_stream = circ->resolving_streams;
  769. circ->resolving_streams = n_stream;
  770. assert_circuit_ok(circ);
  771. ;
  772. }
  773. return 0;
  774. }
  775. /**
  776. * Called when we receive a RELAY_RESOLVE cell 'cell' along the circuit 'circ';
  777. * begin resolving the hostname, and (eventually) reply with a RESOLVED cell.
  778. */
  779. int connection_exit_begin_resolve(cell_t *cell, circuit_t *circ) {
  780. connection_t *dummy_conn;
  781. relay_header_t rh;
  782. assert_circuit_ok(circ);
  783. relay_header_unpack(&rh, cell->payload);
  784. /* This 'dummy_conn' only exists to remember the stream ID
  785. * associated with the resolve request; and to make the
  786. * implementation of dns.c more uniform. (We really only need to
  787. * remember the circuit, the stream ID, and the hostname to be
  788. * resolved; but if we didn't store them in a connection like this,
  789. * the housekeeping in dns.c would get way more complicated.)
  790. */
  791. dummy_conn = connection_new(CONN_TYPE_EXIT);
  792. dummy_conn->stream_id = rh.stream_id;
  793. dummy_conn->address = tor_strndup(cell->payload+RELAY_HEADER_SIZE,
  794. rh.length);
  795. dummy_conn->port = 0;
  796. dummy_conn->state = EXIT_CONN_STATE_RESOLVEFAILED;
  797. dummy_conn->purpose = EXIT_PURPOSE_RESOLVE;
  798. dummy_conn->next_stream = circ->resolving_streams;
  799. circ->resolving_streams = dummy_conn;
  800. /* send it off to the gethostbyname farm */
  801. switch (dns_resolve(dummy_conn)) {
  802. case 1: /* The result was cached; a resolved cell was sent. */
  803. case -1:
  804. circuit_detach_stream(circuit_get_by_conn(dummy_conn), dummy_conn);
  805. connection_free(dummy_conn);
  806. return 0;
  807. case 0: /* resolve added to pending list */
  808. assert_circuit_ok(circ);
  809. ;
  810. }
  811. return 0;
  812. }
  813. /** Connect to conn's specified addr and port. If it worked, conn
  814. * has now been added to the connection_array.
  815. *
  816. * Send back a connected cell. Include the resolved IP of the destination
  817. * address, but <em>only</em> if it's a general exit stream. (Rendezvous
  818. * streams must not reveal what IP they connected to.)
  819. */
  820. void
  821. connection_exit_connect(connection_t *conn) {
  822. unsigned char connected_payload[4];
  823. uint32_t addr;
  824. uint16_t port;
  825. if (!connection_edge_is_rendezvous_stream(conn) &&
  826. router_compare_to_my_exit_policy(conn) == ADDR_POLICY_REJECTED) {
  827. log_fn(LOG_INFO,"%s:%d failed exit policy. Closing.", conn->address, conn->port);
  828. connection_edge_end(conn, END_STREAM_REASON_EXITPOLICY, conn->cpath_layer);
  829. circuit_detach_stream(circuit_get_by_conn(conn), conn);
  830. connection_free(conn);
  831. return;
  832. }
  833. addr = conn->addr;
  834. port = conn->port;
  835. if (redirect_exit_list) {
  836. SMARTLIST_FOREACH(redirect_exit_list, exit_redirect_t *, r,
  837. {
  838. if ((addr&r->mask)==(r->addr&r->mask) &&
  839. (r->port_min <= port) && (port <= r->port_max)) {
  840. struct in_addr in;
  841. if (r->is_redirect) {
  842. addr = r->addr_dest;
  843. port = r->port_dest;
  844. in.s_addr = htonl(addr);
  845. log_fn(LOG_DEBUG, "Redirecting connection from %s:%d to %s:%d",
  846. conn->address, conn->port, inet_ntoa(in), port);
  847. }
  848. break;
  849. }
  850. });
  851. }
  852. log_fn(LOG_DEBUG,"about to try connecting");
  853. switch (connection_connect(conn, conn->address, addr, port)) {
  854. case -1:
  855. connection_edge_end(conn, END_STREAM_REASON_CONNECTFAILED, conn->cpath_layer);
  856. circuit_detach_stream(circuit_get_by_conn(conn), conn);
  857. connection_free(conn);
  858. return;
  859. case 0:
  860. conn->state = EXIT_CONN_STATE_CONNECTING;
  861. connection_watch_events(conn, EV_WRITE | EV_READ);
  862. /* writable indicates finish, readable indicates broken link,
  863. error indicates broken link in windowsland. */
  864. return;
  865. /* case 1: fall through */
  866. }
  867. conn->state = EXIT_CONN_STATE_OPEN;
  868. if (connection_wants_to_flush(conn)) { /* in case there are any queued data cells */
  869. log_fn(LOG_WARN,"Bug: newly connected conn had data waiting!");
  870. // connection_start_writing(conn);
  871. }
  872. connection_watch_events(conn, EV_READ);
  873. /* also, deliver a 'connected' cell back through the circuit. */
  874. if (connection_edge_is_rendezvous_stream(conn)) { /* rendezvous stream */
  875. /* don't send an address back! */
  876. connection_edge_send_command(conn, circuit_get_by_conn(conn), RELAY_COMMAND_CONNECTED,
  877. NULL, 0, conn->cpath_layer);
  878. } else { /* normal stream */
  879. /* This must be the original address, not the redirected address. */
  880. *(uint32_t*)connected_payload = htonl(conn->addr);
  881. connection_edge_send_command(conn, circuit_get_by_conn(conn), RELAY_COMMAND_CONNECTED,
  882. connected_payload, 4, conn->cpath_layer);
  883. }
  884. }
  885. /** Return 1 if <b>conn</b> is a rendezvous stream, or 0 if
  886. * it is a general stream.
  887. */
  888. int connection_edge_is_rendezvous_stream(connection_t *conn) {
  889. tor_assert(conn);
  890. if (*conn->rend_query) /* XXX */
  891. return 1;
  892. return 0;
  893. }
  894. /** Return 1 if router <b>exit</b> might allow stream <b>conn</b>
  895. * to exit from it, or 0 if it definitely will not allow it.
  896. * (We might be uncertain if conn's destination address has not yet been
  897. * resolved.)
  898. */
  899. int connection_ap_can_use_exit(connection_t *conn, routerinfo_t *exit)
  900. {
  901. uint32_t addr;
  902. tor_assert(conn);
  903. tor_assert(conn->type == CONN_TYPE_AP);
  904. tor_assert(conn->socks_request);
  905. tor_assert(exit);
  906. log_fn(LOG_DEBUG,"considering nickname %s, for address %s / port %d:",
  907. exit->nickname, conn->socks_request->address,
  908. conn->socks_request->port);
  909. /* If a particular exit node has been requested for the new connection,
  910. * make sure the exit node of the existing circuit matches exactly.
  911. */
  912. if (conn->chosen_exit_name) {
  913. if (router_get_by_nickname(conn->chosen_exit_name) != exit) {
  914. /* doesn't match */
  915. log_fn(LOG_DEBUG,"Requested node '%s', considering node '%s'. No.",
  916. conn->chosen_exit_name, exit->nickname);
  917. return 0;
  918. }
  919. }
  920. if (conn->socks_request->command != SOCKS_COMMAND_RESOLVE) {
  921. addr = client_dns_lookup_entry(conn->socks_request->address);
  922. if (router_compare_addr_to_addr_policy(addr, conn->socks_request->port,
  923. exit->exit_policy) == ADDR_POLICY_REJECTED)
  924. return 0;
  925. }
  926. return 1;
  927. }
  928. /** A helper function for socks_policy_permits_address() below.
  929. *
  930. * Parse options->SocksPolicy in the same way that the exit policy
  931. * is parsed, and put the processed version in &socks_policy.
  932. * Ignore port specifiers.
  933. */
  934. void
  935. parse_socks_policy(void)
  936. {
  937. addr_policy_t *n;
  938. if (socks_policy) {
  939. addr_policy_free(socks_policy);
  940. socks_policy = NULL;
  941. }
  942. config_parse_addr_policy(get_options()->SocksPolicy, &socks_policy);
  943. /* ports aren't used. */
  944. for (n=socks_policy; n; n = n->next) {
  945. n->prt_min = 1;
  946. n->prt_max = 65535;
  947. }
  948. }
  949. /** Return 1 if <b>addr</b> is permitted to connect to our socks port,
  950. * based on <b>socks_policy</b>. Else return 0.
  951. */
  952. int socks_policy_permits_address(uint32_t addr)
  953. {
  954. int a;
  955. if (!socks_policy) /* 'no socks policy' means 'accept' */
  956. return 1;
  957. a = router_compare_addr_to_addr_policy(addr, 1, socks_policy);
  958. if (a==-1)
  959. return 0;
  960. else if (a==0)
  961. return 1;
  962. tor_assert(a==1);
  963. log_fn(LOG_WARN, "Bug: Got unexpected 'maybe' answer from socks policy");
  964. return 0;
  965. }
  966. /* ***** Client DNS code ***** */
  967. /* XXX Perhaps this should get merged with the dns.c code somehow. */
  968. /* XXX But we can't just merge them, because then nodes that act as
  969. * both OR and OP could be attacked: people could rig the dns cache
  970. * by answering funny things to stream begin requests, and later
  971. * other clients would reuse those funny addr's. Hm.
  972. */
  973. /** A client-side struct to remember the resolved IP (addr) for
  974. * a given address. These structs make up a tree, with client_dns_map
  975. * below as its root.
  976. */
  977. struct client_dns_entry {
  978. uint32_t addr; /**< The resolved IP of this entry. */
  979. time_t expires; /**< At what second does addr expire? */
  980. int n_failures; /**< How many times has this entry failed to resolve so far? */
  981. };
  982. /** How many elements are in the client dns cache currently? */
  983. static int client_dns_size = 0;
  984. /** The tree of client-side cached DNS resolves. */
  985. static strmap_t *client_dns_map = NULL;
  986. /** Initialize client_dns_map and client_dns_size. */
  987. void client_dns_init(void) {
  988. client_dns_map = strmap_new();
  989. client_dns_size = 0;
  990. }
  991. /** Return the client_dns_entry that corresponds to <b>address</b>.
  992. * If it's not there, allocate and return a new entry for <b>address</b>.
  993. */
  994. static struct client_dns_entry *
  995. _get_or_create_ent(const char *address)
  996. {
  997. struct client_dns_entry *ent;
  998. ent = strmap_get_lc(client_dns_map,address);
  999. if (!ent) {
  1000. ent = tor_malloc_zero(sizeof(struct client_dns_entry));
  1001. ent->expires = time(NULL)+MAX_DNS_ENTRY_AGE;
  1002. strmap_set_lc(client_dns_map,address,ent);
  1003. ++client_dns_size;
  1004. }
  1005. return ent;
  1006. }
  1007. /** Return the IP associated with <b>address</b>, if we know it
  1008. * and it's still fresh enough. Otherwise return 0.
  1009. */
  1010. uint32_t client_dns_lookup_entry(const char *address)
  1011. {
  1012. struct client_dns_entry *ent;
  1013. struct in_addr in;
  1014. time_t now;
  1015. tor_assert(address);
  1016. if (tor_inet_aton(address, &in)) {
  1017. log_fn(LOG_DEBUG, "Using static address %s (%08lX)", address,
  1018. (unsigned long)ntohl(in.s_addr));
  1019. return ntohl(in.s_addr);
  1020. }
  1021. ent = strmap_get_lc(client_dns_map,address);
  1022. if (!ent || !ent->addr) {
  1023. log_fn(LOG_DEBUG, "No entry found for address %s", address);
  1024. return 0;
  1025. } else {
  1026. now = time(NULL);
  1027. if (ent->expires < now) {
  1028. log_fn(LOG_DEBUG, "Expired entry found for address %s", address);
  1029. strmap_remove_lc(client_dns_map,address);
  1030. tor_free(ent);
  1031. --client_dns_size;
  1032. return 0;
  1033. }
  1034. in.s_addr = htonl(ent->addr);
  1035. log_fn(LOG_DEBUG, "Found cached entry for address %s: %s", address,
  1036. inet_ntoa(in));
  1037. return ent->addr;
  1038. }
  1039. }
  1040. /** An attempt to resolve <b>address</b> failed at some OR.
  1041. * Increment the number of resolve failures we have on record
  1042. * for it, and then return that number.
  1043. */
  1044. int client_dns_incr_failures(const char *address)
  1045. {
  1046. struct client_dns_entry *ent;
  1047. ent = _get_or_create_ent(address);
  1048. ++ent->n_failures;
  1049. log_fn(LOG_DEBUG,"Address %s now has %d resolve failures.",
  1050. address, ent->n_failures);
  1051. return ent->n_failures;
  1052. }
  1053. /** Record the fact that <b>address</b> resolved to <b>val</b>.
  1054. * We can now use this in subsequent streams in client_dns_lookup_entry(),
  1055. * so we can more correctly choose a router that will allow <b>address</b>
  1056. * to exit from him.
  1057. */
  1058. void client_dns_set_entry(const char *address, uint32_t val)
  1059. {
  1060. struct client_dns_entry *ent;
  1061. struct in_addr in;
  1062. time_t now;
  1063. tor_assert(address);
  1064. tor_assert(val);
  1065. if (tor_inet_aton(address, &in))
  1066. return;
  1067. now = time(NULL);
  1068. ent = _get_or_create_ent(address);
  1069. in.s_addr = htonl(val);
  1070. log_fn(LOG_DEBUG, "Updating entry for address %s: %s", address,
  1071. inet_ntoa(in));
  1072. ent->addr = val;
  1073. ent->expires = now+MAX_DNS_ENTRY_AGE;
  1074. ent->n_failures = 0;
  1075. }
  1076. /** A helper function for client_dns_clean() below. If ent is too old,
  1077. * then remove it from the tree and return NULL, else return ent.
  1078. */
  1079. static void* _remove_if_expired(const char *addr,
  1080. struct client_dns_entry *ent,
  1081. time_t *nowp)
  1082. {
  1083. if (ent->expires < *nowp) {
  1084. --client_dns_size;
  1085. tor_free(ent);
  1086. return NULL;
  1087. } else {
  1088. return ent;
  1089. }
  1090. }
  1091. /** Clean out entries from the client-side DNS cache that were
  1092. * resolved long enough ago that they are no longer valid.
  1093. */
  1094. void client_dns_clean(void)
  1095. {
  1096. time_t now;
  1097. if (!client_dns_size)
  1098. return;
  1099. now = time(NULL);
  1100. strmap_foreach(client_dns_map, (strmap_foreach_fn)_remove_if_expired, &now);
  1101. }
  1102. /** Make connection redirection follow the provided list of
  1103. * exit_redirect_t */
  1104. void
  1105. set_exit_redirects(smartlist_t *lst)
  1106. {
  1107. if (redirect_exit_list) {
  1108. SMARTLIST_FOREACH(redirect_exit_list, exit_redirect_t *, p, tor_free(p));
  1109. smartlist_free(redirect_exit_list);
  1110. }
  1111. redirect_exit_list = lst;
  1112. }
  1113. /** If address is of the form "y.onion" with a well-formed handle y:
  1114. * Put a '\0' after y, lower-case it, and return ONION_HOSTNAME.
  1115. *
  1116. * If address is of the form "y.exit":
  1117. * Put a '\0' after y and return EXIT_HOSTNAME.
  1118. *
  1119. * Otherwise:
  1120. * Return NORMAL_HOSTNAME and change nothing.
  1121. */
  1122. hostname_type_t
  1123. parse_extended_hostname(char *address) {
  1124. char *s;
  1125. char query[REND_SERVICE_ID_LEN+1];
  1126. s = strrchr(address,'.');
  1127. if (!s) return 0; /* no dot, thus normal */
  1128. if (!strcasecmp(s+1,"exit")) {
  1129. *s = 0; /* null-terminate it */
  1130. return EXIT_HOSTNAME; /* .exit */
  1131. }
  1132. if (strcasecmp(s+1,"onion"))
  1133. return NORMAL_HOSTNAME; /* neither .exit nor .onion, thus normal */
  1134. /* so it is .onion */
  1135. *s = 0; /* null-terminate it */
  1136. if (strlcpy(query, address, REND_SERVICE_ID_LEN+1) >= REND_SERVICE_ID_LEN+1)
  1137. goto failed;
  1138. tor_strlower(query);
  1139. if (rend_valid_service_id(query)) {
  1140. tor_strlower(address);
  1141. return ONION_HOSTNAME; /* success */
  1142. }
  1143. failed:
  1144. /* otherwise, return to previous state and return 0 */
  1145. *s = '.';
  1146. return NORMAL_HOSTNAME;
  1147. }