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