connection_edge.c 60 KB

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