connection_edge.c 45 KB

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