connection_edge.c 33 KB

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