connection_edge.c 43 KB

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