connection_edge.c 57 KB

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