connection_edge.c 61 KB

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