connection_edge.c 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783
  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;
  598. ent = strmap_get(addressmap,address);
  599. if (!ent) {
  600. ent = tor_malloc_zero(sizeof(addressmap_entry_t));
  601. ent->expires = time(NULL)+MAX_DNS_ENTRY_AGE;
  602. strmap_set(addressmap,address,ent);
  603. }
  604. ++ent->num_resolve_failures;
  605. log_fn(LOG_INFO,"Address %s now has %d resolve failures.",
  606. safe_str(address), ent->num_resolve_failures);
  607. return ent->num_resolve_failures;
  608. }
  609. /** Record the fact that <b>address</b> resolved to <b>val</b>.
  610. * We can now use this in subsequent streams via addressmap_rewrite()
  611. * so we can more correctly choose an exit that will allow <b>address</b>.
  612. *
  613. * If <b>exitname</b> is defined, then append the addresses with
  614. * ".exitname.exit" before registering the mapping.
  615. */
  616. void
  617. client_dns_set_addressmap(const char *address, uint32_t val, const char *exitname)
  618. {
  619. struct in_addr in;
  620. char extendedaddress[MAX_SOCKS_ADDR_LEN+MAX_HEX_NICKNAME_LEN+10];
  621. char valbuf[INET_NTOA_BUF_LEN];
  622. char extendedval[INET_NTOA_BUF_LEN+MAX_HEX_NICKNAME_LEN+10];
  623. tor_assert(address); tor_assert(val);
  624. if (tor_inet_aton(address, &in))
  625. return; /* If address was an IP address already, don't add a mapping. */
  626. in.s_addr = htonl(val);
  627. tor_inet_ntoa(&in,valbuf,sizeof(valbuf));
  628. if (exitname) {
  629. tor_snprintf(extendedaddress, sizeof(extendedaddress),
  630. "%s.%s.exit", address, exitname);
  631. tor_snprintf(extendedval, sizeof(extendedval),
  632. "%s.%s.exit", valbuf, exitname);
  633. } else {
  634. tor_snprintf(extendedaddress, sizeof(extendedaddress),
  635. "%s", address);
  636. tor_snprintf(extendedval, sizeof(extendedval),
  637. "%s", valbuf);
  638. }
  639. addressmap_register(extendedaddress, tor_strdup(extendedval),
  640. time(NULL) + MAX_DNS_ENTRY_AGE);
  641. }
  642. /* Currently, we hand out 127.192.0.1 through 127.254.254.254.
  643. * These addresses should map to localhost, so even if the
  644. * application accidentally tried to connect to them directly (not
  645. * via Tor), it wouldn't get too far astray.
  646. *
  647. * Eventually, we should probably make this configurable.
  648. */
  649. #define MIN_UNUSED_IPV4 0x7fc00001u
  650. #define MAX_UNUSED_IPV4 0x7ffefefeu
  651. /**
  652. * Return true iff <b>addr</b> is likely to have been returned by
  653. * client_dns_get_unused_address.
  654. **/
  655. static int
  656. address_is_in_virtual_range(const char *addr)
  657. {
  658. struct in_addr in;
  659. tor_assert(addr);
  660. if (!strcasecmpend(addr, ".virtual")) {
  661. return 1;
  662. } else if (tor_inet_aton(addr, &in)) {
  663. uint32_t a = ntohl(in.s_addr);
  664. if (a >= MIN_UNUSED_IPV4 && a <= MAX_UNUSED_IPV4)
  665. return 1;
  666. }
  667. return 0;
  668. }
  669. /** Return a newly allocated string holding an address of <b>type</b>
  670. * (one of RESOLVED_TYPE_{IPV4|HOSTNAME}) that has not yet been mapped,
  671. * and that is very unlikely to be the address of any real host.
  672. */
  673. static char *
  674. addressmap_get_virtual_address(int type)
  675. {
  676. char buf[64];
  677. static uint32_t next_ipv4 = MIN_UNUSED_IPV4;
  678. struct in_addr in;
  679. if (type == RESOLVED_TYPE_HOSTNAME) {
  680. char rand[10];
  681. do {
  682. crypto_rand(rand, sizeof(rand));
  683. base32_encode(buf,sizeof(buf),rand,sizeof(rand));
  684. strlcat(buf, ".virtual", sizeof(buf));
  685. } while (strmap_get(addressmap, buf));
  686. return tor_strdup(buf);
  687. } else if (type == RESOLVED_TYPE_IPV4) {
  688. while (1) {
  689. /* Don't hand out any .0 or .255 address. */
  690. while ((next_ipv4 & 0xff) == 0 ||
  691. (next_ipv4 & 0xff) == 0xff)
  692. ++next_ipv4;
  693. in.s_addr = htonl(next_ipv4);
  694. tor_inet_ntoa(&in, buf, sizeof(buf));
  695. if (!strmap_get(addressmap, buf))
  696. break;
  697. ++next_ipv4;
  698. if (next_ipv4 > MAX_UNUSED_IPV4)
  699. next_ipv4 = MIN_UNUSED_IPV4;
  700. }
  701. return tor_strdup(buf);
  702. } else {
  703. log_fn(LOG_WARN, "Called with unsupported address type (%d)",
  704. type);
  705. return NULL;
  706. }
  707. }
  708. /** A controller has requested that we map some address of type
  709. * <b>type</b> to the address <b>new_address</b>. Choose an address
  710. * that is unlikely to be used, and map it, and return it in a newly
  711. * allocated string. If another address of the same type is already
  712. * mapped to <b>new_address</b>, try to return a copy of that address.
  713. *
  714. * The string in <b>new_address</b> may be freed, or inserted into a map
  715. * as appropriate.
  716. **/
  717. const char *
  718. addressmap_register_virtual_address(int type, char *new_address)
  719. {
  720. char **addrp;
  721. virtaddress_entry_t *vent;
  722. tor_assert(new_address);
  723. tor_assert(addressmap);
  724. tor_assert(virtaddress_reversemap);
  725. vent = strmap_get(virtaddress_reversemap, new_address);
  726. if (!vent) {
  727. vent = tor_malloc_zero(sizeof(virtaddress_entry_t));
  728. strmap_set(virtaddress_reversemap, new_address, vent);
  729. }
  730. addrp = (type == RESOLVED_TYPE_IPV4) ?
  731. &vent->ipv4_address : &vent->hostname_address;
  732. if (*addrp) {
  733. addressmap_entry_t *ent = strmap_get(addressmap, *addrp);
  734. if (ent && ent->new_address && !strcasecmp(new_address, ent->new_address)) {
  735. tor_free(new_address);
  736. return tor_strdup(*addrp);
  737. } else
  738. 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.",
  739. safe_str(new_address), safe_str(*addrp), safe_str(*addrp),
  740. ent?safe_str(ent->new_address):"(nothing)");
  741. }
  742. tor_free(*addrp);
  743. *addrp = addressmap_get_virtual_address(type);
  744. addressmap_register(*addrp, new_address, 2);
  745. #if 0
  746. {
  747. /* Try to catch possible bugs */
  748. addressmap_entry_t *ent;
  749. ent = strmap_get(addressmap, *addrp);
  750. tor_assert(ent);
  751. tor_assert(!strcasecmp(ent->new_address,new_address));
  752. vent = strmap_get(virtaddress_reversemap, new_address);
  753. tor_assert(vent);
  754. tor_assert(!strcasecmp(*addrp,
  755. (type == RESOLVED_TYPE_IPV4) ?
  756. vent->ipv4_address : vent->hostname_address));
  757. log_fn(LOG_INFO, "Map from %s to %s okay.",
  758. safe_str(*addrp),safe_str(new_address));
  759. }
  760. #endif
  761. return *addrp;
  762. }
  763. /** Return 1 if <b>address</b> has funny characters in it like
  764. * colons. Return 0 if it's fine.
  765. */
  766. static int
  767. address_is_invalid_destination(const char *address)
  768. {
  769. /* FFFF should flesh this out */
  770. if (strchr(address,':'))
  771. return 1;
  772. return 0;
  773. }
  774. /** Iterate over all address mapings which have expiry times between
  775. * min_expires and max_expires, inclusive. If sl is provided, add an
  776. * "old-addr new-addr" string to sl for each mapping. If sl is NULL,
  777. * remove the mappings.
  778. */
  779. void
  780. addressmap_get_mappings(smartlist_t *sl, time_t min_expires, time_t max_expires)
  781. {
  782. strmap_iter_t *iter;
  783. const char *key;
  784. void *_val;
  785. addressmap_entry_t *val;
  786. for (iter = strmap_iter_init(addressmap); !strmap_iter_done(iter); ) {
  787. strmap_iter_get(iter, &key, &_val);
  788. val = _val;
  789. if (val->expires >= min_expires && val->expires <= max_expires) {
  790. if (!sl) {
  791. addressmap_ent_remove(key, val);
  792. iter = strmap_iter_next_rmv(addressmap,iter);
  793. continue;
  794. } else if (val->new_address) {
  795. size_t len = strlen(key)+strlen(val->new_address)+2;
  796. char *line = tor_malloc(len);
  797. tor_snprintf(line, len, "%s %s", key, val->new_address);
  798. smartlist_add(sl, line);
  799. }
  800. }
  801. iter = strmap_iter_next(addressmap,iter);
  802. }
  803. }
  804. /** connection_edge_process_inbuf() found a conn in state
  805. * socks_wait. See if conn->inbuf has the right bytes to proceed with
  806. * the socks handshake.
  807. *
  808. * If the handshake is complete, and it's for a general circuit, then
  809. * try to attach it to a circuit (or launch one as needed). If it's for
  810. * a rendezvous circuit, then fetch a rendezvous descriptor first (or
  811. * attach/launch a circuit if the rendezvous descriptor is already here
  812. * and fresh enough).
  813. *
  814. * Return -1 if an unexpected error with conn (and it should be marked
  815. * for close), else return 0.
  816. */
  817. static int
  818. connection_ap_handshake_process_socks(connection_t *conn)
  819. {
  820. socks_request_t *socks;
  821. int sockshere;
  822. hostname_type_t addresstype;
  823. tor_assert(conn);
  824. tor_assert(conn->type == CONN_TYPE_AP);
  825. tor_assert(conn->state == AP_CONN_STATE_SOCKS_WAIT);
  826. tor_assert(conn->socks_request);
  827. socks = conn->socks_request;
  828. log_fn(LOG_DEBUG,"entered.");
  829. sockshere = fetch_from_buf_socks(conn->inbuf, socks);
  830. if (sockshere == 0) {
  831. if (socks->replylen) {
  832. connection_write_to_buf(socks->reply, socks->replylen, conn);
  833. socks->replylen = 0; /* zero it out so we can do another round of negotiation */
  834. } else {
  835. log_fn(LOG_DEBUG,"socks handshake not all here yet.");
  836. }
  837. return 0;
  838. } else if (sockshere == -1) {
  839. if (socks->replylen) { /* we should send reply back */
  840. log_fn(LOG_DEBUG,"reply is already set for us. Using it.");
  841. connection_ap_handshake_socks_reply(conn, socks->reply, socks->replylen,
  842. SOCKS5_GENERAL_ERROR);
  843. } else {
  844. log_fn(LOG_WARN,"Fetching socks handshake failed. Closing.");
  845. connection_ap_handshake_socks_reply(conn, NULL, 0, SOCKS5_GENERAL_ERROR);
  846. }
  847. connection_mark_unattached_ap(conn, END_STREAM_REASON_ALREADY_SOCKS_REPLIED);
  848. return -1;
  849. } /* else socks handshake is done, continue processing */
  850. tor_strlower(socks->address); /* normalize it */
  851. /* For address map controls, remap the address */
  852. addressmap_rewrite(socks->address, sizeof(socks->address));
  853. if (address_is_in_virtual_range(socks->address)) {
  854. /* This address was probably handed out by client_dns_get_unmapped_address,
  855. * but the mapping was discarded for some reason. We *don't* want to send
  856. * the address through tor; that's likely to fail, and may leak
  857. * information.
  858. */
  859. log_fn(LOG_WARN,"Missing mapping for virtual address '%s'. Refusing.",
  860. socks->address); /* don't safe_str() this yet. */
  861. connection_mark_unattached_ap(conn, END_STREAM_REASON_INTERNAL);
  862. return -1;
  863. }
  864. /* Parse the address provided by SOCKS. Modify it in-place if it
  865. * specifies a hidden-service (.onion) or particular exit node (.exit).
  866. */
  867. addresstype = parse_extended_hostname(socks->address);
  868. if (addresstype == BAD_HOSTNAME) {
  869. log_fn(LOG_WARN, "Invalid hostname %s; rejecting", socks->address);
  870. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  871. return -1;
  872. }
  873. if (addresstype == EXIT_HOSTNAME) {
  874. /* foo.exit -- modify conn->chosen_exit_node to specify the exit
  875. * node, and conn->address to hold only the address portion.*/
  876. char *s = strrchr(socks->address,'.');
  877. if (s) {
  878. if (s[1] != '\0') {
  879. conn->chosen_exit_name = tor_strdup(s+1);
  880. *s = 0;
  881. } else {
  882. log_fn(LOG_WARN,"Malformed exit address '%s.exit'. Refusing.",
  883. safe_str(socks->address));
  884. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  885. return -1;
  886. }
  887. } else {
  888. struct in_addr in;
  889. routerinfo_t *r = router_get_by_nickname(socks->address);
  890. if (r) {
  891. conn->chosen_exit_name = tor_strdup(socks->address);
  892. /* XXXX Should this use server->address instead? */
  893. in.s_addr = htonl(r->addr);
  894. strlcpy(socks->address, inet_ntoa(in), sizeof(socks->address));
  895. } else {
  896. log_fn(LOG_WARN,
  897. "Unrecognized server in exit address '%s.exit'. Refusing.",
  898. safe_str(socks->address));
  899. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  900. return -1;
  901. }
  902. }
  903. }
  904. if (addresstype != ONION_HOSTNAME) {
  905. /* not a hidden-service request (i.e. normal or .exit) */
  906. if (address_is_invalid_destination(socks->address)) {
  907. log_fn(LOG_WARN,"Destination '%s' seems to be an invalid hostname. Failing.",
  908. safe_str(socks->address));
  909. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  910. return -1;
  911. }
  912. if (socks->command == SOCKS_COMMAND_RESOLVE) {
  913. uint32_t answer;
  914. struct in_addr in;
  915. /* Reply to resolves immediately if we can. */
  916. if (strlen(socks->address) > RELAY_PAYLOAD_SIZE) {
  917. log_fn(LOG_WARN,"Address to be resolved is too large. Failing.");
  918. connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_ERROR,0,NULL);
  919. connection_mark_unattached_ap(conn, END_STREAM_REASON_ALREADY_SOCKS_REPLIED);
  920. return -1;
  921. }
  922. if (tor_inet_aton(socks->address, &in)) { /* see if it's an IP already */
  923. answer = in.s_addr;
  924. connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_IPV4,4,
  925. (char*)&answer);
  926. connection_mark_unattached_ap(conn, END_STREAM_REASON_ALREADY_SOCKS_REPLIED);
  927. return 0;
  928. }
  929. rep_hist_note_used_resolve(time(NULL)); /* help predict this next time */
  930. control_event_stream_status(conn, STREAM_EVENT_NEW_RESOLVE);
  931. } else { /* socks->command == SOCKS_COMMAND_CONNECT */
  932. if (socks->port == 0) {
  933. log_fn(LOG_NOTICE,"Application asked to connect to port 0. Refusing.");
  934. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  935. return -1;
  936. }
  937. rep_hist_note_used_port(socks->port, time(NULL)); /* help predict this next time */
  938. control_event_stream_status(conn, STREAM_EVENT_NEW);
  939. }
  940. if (! get_options()->LeaveStreamsUnattached) {
  941. conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  942. if (connection_ap_handshake_attach_circuit(conn) < 0) {
  943. connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
  944. return -1;
  945. }
  946. return 0;
  947. } else {
  948. conn->state = AP_CONN_STATE_CONTROLLER_WAIT;
  949. return 0;
  950. }
  951. } else {
  952. /* it's a hidden-service request */
  953. rend_cache_entry_t *entry;
  954. int r;
  955. if (socks->command == SOCKS_COMMAND_RESOLVE) {
  956. /* if it's a resolve request, fail it right now, rather than
  957. * building all the circuits and then realizing it won't work. */
  958. log_fn(LOG_WARN,"Resolve requests to hidden services not allowed. Failing.");
  959. connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_ERROR,0,NULL);
  960. connection_mark_unattached_ap(conn, END_STREAM_REASON_ALREADY_SOCKS_REPLIED);
  961. return -1;
  962. }
  963. strlcpy(conn->rend_query, socks->address, sizeof(conn->rend_query));
  964. log_fn(LOG_INFO,"Got a hidden service request for ID '%s'",
  965. safe_str(conn->rend_query));
  966. /* see if we already have it cached */
  967. r = rend_cache_lookup_entry(conn->rend_query, -1, &entry);
  968. if (r<0) {
  969. log_fn(LOG_WARN,"Invalid service descriptor %s",
  970. safe_str(conn->rend_query));
  971. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  972. return -1;
  973. }
  974. if (r==0) {
  975. conn->state = AP_CONN_STATE_RENDDESC_WAIT;
  976. log_fn(LOG_INFO, "Unknown descriptor %s. Fetching.",
  977. safe_str(conn->rend_query));
  978. rend_client_refetch_renddesc(conn->rend_query);
  979. return 0;
  980. }
  981. if (r>0) {
  982. #define NUM_SECONDS_BEFORE_REFETCH (60*15)
  983. if (time(NULL) - entry->received < NUM_SECONDS_BEFORE_REFETCH) {
  984. conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  985. log_fn(LOG_INFO, "Descriptor is here and fresh enough. Great.");
  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. return 0;
  991. } else {
  992. conn->state = AP_CONN_STATE_RENDDESC_WAIT;
  993. log_fn(LOG_INFO, "Stale descriptor %s. Refetching.",
  994. safe_str(conn->rend_query));
  995. rend_client_refetch_renddesc(conn->rend_query);
  996. return 0;
  997. }
  998. }
  999. }
  1000. return 0; /* unreached but keeps the compiler happy */
  1001. }
  1002. /** Iterate over the two bytes of stream_id until we get one that is not
  1003. * already in use; return it. Return 0 if can't get a unique stream_id.
  1004. */
  1005. static uint16_t
  1006. get_unique_stream_id_by_circ(circuit_t *circ)
  1007. {
  1008. connection_t *tmpconn;
  1009. uint16_t test_stream_id;
  1010. uint32_t attempts=0;
  1011. again:
  1012. test_stream_id = circ->next_stream_id++;
  1013. if (++attempts > 1<<16) {
  1014. /* Make sure we don't loop forever if all stream_id's are used. */
  1015. log_fn(LOG_WARN,"No unused stream IDs. Failing.");
  1016. return 0;
  1017. }
  1018. if (test_stream_id == 0)
  1019. goto again;
  1020. for (tmpconn = circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream)
  1021. if (tmpconn->stream_id == test_stream_id)
  1022. goto again;
  1023. return test_stream_id;
  1024. }
  1025. /** Write a relay begin cell, using destaddr and destport from ap_conn's
  1026. * socks_request field, and send it down circ.
  1027. *
  1028. * If ap_conn is broken, mark it for close and return -1. Else return 0.
  1029. */
  1030. int
  1031. connection_ap_handshake_send_begin(connection_t *ap_conn, circuit_t *circ)
  1032. {
  1033. char payload[CELL_PAYLOAD_SIZE];
  1034. int payload_len;
  1035. tor_assert(ap_conn->type == CONN_TYPE_AP);
  1036. tor_assert(ap_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
  1037. tor_assert(ap_conn->socks_request);
  1038. ap_conn->stream_id = get_unique_stream_id_by_circ(circ);
  1039. if (ap_conn->stream_id==0) {
  1040. connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
  1041. circuit_mark_for_close(circ);
  1042. return -1;
  1043. }
  1044. tor_snprintf(payload,RELAY_PAYLOAD_SIZE, "%s:%d",
  1045. (circ->purpose == CIRCUIT_PURPOSE_C_GENERAL) ?
  1046. ap_conn->socks_request->address : "",
  1047. ap_conn->socks_request->port);
  1048. payload_len = strlen(payload)+1;
  1049. log_fn(LOG_DEBUG,"Sending relay cell to begin stream %d.",ap_conn->stream_id);
  1050. if (connection_edge_send_command(ap_conn, circ, RELAY_COMMAND_BEGIN,
  1051. payload, payload_len, ap_conn->cpath_layer) < 0)
  1052. return -1; /* circuit is closed, don't continue */
  1053. ap_conn->package_window = STREAMWINDOW_START;
  1054. ap_conn->deliver_window = STREAMWINDOW_START;
  1055. ap_conn->state = AP_CONN_STATE_CONNECT_WAIT;
  1056. log_fn(LOG_INFO,"Address/port sent, ap socket %d, n_circ_id %d",
  1057. ap_conn->s, circ->n_circ_id);
  1058. control_event_stream_status(ap_conn, STREAM_EVENT_SENT_CONNECT);
  1059. return 0;
  1060. }
  1061. /** Write a relay resolve cell, using destaddr and destport from ap_conn's
  1062. * socks_request field, and send it down circ.
  1063. *
  1064. * If ap_conn is broken, mark it for close and return -1. Else return 0.
  1065. */
  1066. int
  1067. connection_ap_handshake_send_resolve(connection_t *ap_conn, circuit_t *circ)
  1068. {
  1069. int payload_len;
  1070. const char *string_addr;
  1071. tor_assert(ap_conn->type == CONN_TYPE_AP);
  1072. tor_assert(ap_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
  1073. tor_assert(ap_conn->socks_request);
  1074. tor_assert(ap_conn->socks_request->command == SOCKS_COMMAND_RESOLVE);
  1075. tor_assert(circ->purpose == CIRCUIT_PURPOSE_C_GENERAL);
  1076. ap_conn->stream_id = get_unique_stream_id_by_circ(circ);
  1077. if (ap_conn->stream_id==0) {
  1078. connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
  1079. circuit_mark_for_close(circ);
  1080. return -1;
  1081. }
  1082. string_addr = ap_conn->socks_request->address;
  1083. payload_len = strlen(string_addr)+1;
  1084. tor_assert(payload_len <= RELAY_PAYLOAD_SIZE);
  1085. log_fn(LOG_DEBUG,"Sending relay cell to begin stream %d.",ap_conn->stream_id);
  1086. if (connection_edge_send_command(ap_conn, circ, RELAY_COMMAND_RESOLVE,
  1087. string_addr, payload_len, ap_conn->cpath_layer) < 0)
  1088. return -1; /* circuit is closed, don't continue */
  1089. ap_conn->state = AP_CONN_STATE_RESOLVE_WAIT;
  1090. log_fn(LOG_INFO,"Address sent for resolve, ap socket %d, n_circ_id %d",
  1091. ap_conn->s, circ->n_circ_id);
  1092. control_event_stream_status(ap_conn, STREAM_EVENT_SENT_RESOLVE);
  1093. return 0;
  1094. }
  1095. /** Make an AP connection_t, do a socketpair and attach one side
  1096. * to the conn, connection_add it, initialize it to circuit_wait,
  1097. * and call connection_ap_handshake_attach_circuit(conn) on it.
  1098. *
  1099. * Return the other end of the socketpair, or -1 if error.
  1100. */
  1101. int
  1102. connection_ap_make_bridge(char *address, uint16_t port)
  1103. {
  1104. int fd[2];
  1105. connection_t *conn;
  1106. int err;
  1107. log_fn(LOG_INFO,"Making AP bridge to %s:%d ...",safe_str(address),port);
  1108. if ((err = tor_socketpair(AF_UNIX, SOCK_STREAM, 0, fd)) < 0) {
  1109. log(LOG_WARN,"Couldn't construct socketpair (%s). Network down? Delaying.",
  1110. tor_socket_strerror(-err));
  1111. return -1;
  1112. }
  1113. set_socket_nonblocking(fd[0]);
  1114. set_socket_nonblocking(fd[1]);
  1115. conn = connection_new(CONN_TYPE_AP);
  1116. conn->s = fd[0];
  1117. /* populate conn->socks_request */
  1118. /* leave version at zero, so the socks_reply is empty */
  1119. conn->socks_request->socks_version = 0;
  1120. conn->socks_request->has_finished = 0; /* waiting for 'connected' */
  1121. strlcpy(conn->socks_request->address, address,
  1122. sizeof(conn->socks_request->address));
  1123. conn->socks_request->port = port;
  1124. conn->socks_request->command = SOCKS_COMMAND_CONNECT;
  1125. conn->address = tor_strdup("(local bridge)");
  1126. conn->addr = 0;
  1127. conn->port = 0;
  1128. if (connection_add(conn) < 0) { /* no space, forget it */
  1129. connection_free(conn); /* this closes fd[0] */
  1130. tor_close_socket(fd[1]);
  1131. return -1;
  1132. }
  1133. conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  1134. connection_start_reading(conn);
  1135. /* attaching to a dirty circuit is fine */
  1136. if (connection_ap_handshake_attach_circuit(conn) < 0) {
  1137. connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
  1138. tor_close_socket(fd[1]);
  1139. return -1;
  1140. }
  1141. log_fn(LOG_INFO,"... AP bridge created and connected.");
  1142. return fd[1];
  1143. }
  1144. /** Send an answer to an AP connection that has requested a DNS lookup
  1145. * via SOCKS. The type should be one of RESOLVED_TYPE_(IPV4|IPV6) or
  1146. * -1 for unreachable; the answer should be in the format specified
  1147. * in the socks extensions document.
  1148. **/
  1149. void
  1150. connection_ap_handshake_socks_resolved(connection_t *conn,
  1151. int answer_type,
  1152. size_t answer_len,
  1153. const char *answer)
  1154. {
  1155. char buf[256];
  1156. size_t replylen;
  1157. if (answer_type == RESOLVED_TYPE_IPV4) {
  1158. uint32_t a = get_uint32(answer);
  1159. if (a)
  1160. client_dns_set_addressmap(conn->socks_request->address, ntohl(a),
  1161. conn->chosen_exit_name);
  1162. }
  1163. if (conn->socks_request->socks_version == 4) {
  1164. buf[0] = 0x00; /* version */
  1165. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
  1166. buf[1] = 90; /* "Granted" */
  1167. set_uint16(buf+2, 0);
  1168. memcpy(buf+4, answer, 4); /* address */
  1169. replylen = SOCKS4_NETWORK_LEN;
  1170. } else {
  1171. buf[1] = 91; /* "error" */
  1172. memset(buf+2, 0, 6);
  1173. replylen = SOCKS4_NETWORK_LEN;
  1174. }
  1175. } else {
  1176. /* SOCKS5 */
  1177. buf[0] = 0x05; /* version */
  1178. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
  1179. buf[1] = SOCKS5_SUCCEEDED;
  1180. buf[2] = 0; /* reserved */
  1181. buf[3] = 0x01; /* IPv4 address type */
  1182. memcpy(buf+4, answer, 4); /* address */
  1183. set_uint16(buf+8, 0); /* port == 0. */
  1184. replylen = 10;
  1185. } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
  1186. buf[1] = SOCKS5_SUCCEEDED;
  1187. buf[2] = 0; /* reserved */
  1188. buf[3] = 0x04; /* IPv6 address type */
  1189. memcpy(buf+4, answer, 16); /* address */
  1190. set_uint16(buf+20, 0); /* port == 0. */
  1191. replylen = 22;
  1192. } else {
  1193. buf[1] = SOCKS5_HOST_UNREACHABLE;
  1194. memset(buf+2, 0, 8);
  1195. replylen = 10;
  1196. }
  1197. }
  1198. connection_ap_handshake_socks_reply(conn, buf, replylen,
  1199. (answer_type == RESOLVED_TYPE_IPV4 ||
  1200. answer_type == RESOLVED_TYPE_IPV6) ?
  1201. SOCKS5_SUCCEEDED : SOCKS5_HOST_UNREACHABLE);
  1202. }
  1203. /** Send a socks reply to stream <b>conn</b>, using the appropriate
  1204. * socks version, etc, and mark <b>conn</b> as completed with SOCKS
  1205. * handshaking.
  1206. *
  1207. * If <b>reply</b> is defined, then write <b>replylen</b> bytes of it
  1208. * to conn and return, else reply based on <b>status</b>.
  1209. *
  1210. * If <b>reply</b> is undefined, <b>status</b> can't be 0.
  1211. */
  1212. void
  1213. connection_ap_handshake_socks_reply(connection_t *conn, char *reply,
  1214. size_t replylen,
  1215. socks5_reply_status_t status) {
  1216. char buf[256];
  1217. tor_assert(conn->socks_request); /* make sure it's an AP stream */
  1218. control_event_stream_status(conn,
  1219. status==SOCKS5_SUCCEEDED ? STREAM_EVENT_SUCCEEDED : STREAM_EVENT_FAILED);
  1220. if (conn->socks_request->has_finished) {
  1221. log_fn(LOG_WARN, "Harmless bug: duplicate calls to connection_ap_handshake_socks_reply.");
  1222. return;
  1223. }
  1224. if (replylen) { /* we already have a reply in mind */
  1225. connection_write_to_buf(reply, replylen, conn);
  1226. conn->socks_request->has_finished = 1;
  1227. return;
  1228. }
  1229. if (conn->socks_request->socks_version == 4) {
  1230. memset(buf,0,SOCKS4_NETWORK_LEN);
  1231. #define SOCKS4_GRANTED 90
  1232. #define SOCKS4_REJECT 91
  1233. buf[1] = (status==SOCKS5_SUCCEEDED ? SOCKS4_GRANTED : SOCKS4_REJECT);
  1234. /* leave version, destport, destip zero */
  1235. connection_write_to_buf(buf, SOCKS4_NETWORK_LEN, conn);
  1236. } else if (conn->socks_request->socks_version == 5) {
  1237. buf[0] = 5; /* version 5 */
  1238. buf[1] = (char)status;
  1239. buf[2] = 0;
  1240. buf[3] = 1; /* ipv4 addr */
  1241. memset(buf+4,0,6); /* Set external addr/port to 0.
  1242. The spec doesn't seem to say what to do here. -RD */
  1243. connection_write_to_buf(buf,10,conn);
  1244. }
  1245. /* If socks_version isn't 4 or 5, don't send anything.
  1246. * This can happen in the case of AP bridges. */
  1247. conn->socks_request->has_finished = 1;
  1248. return;
  1249. }
  1250. /** A relay 'begin' cell has arrived, and either we are an exit hop
  1251. * for the circuit, or we are the origin and it is a rendezvous begin.
  1252. *
  1253. * Launch a new exit connection and initialize things appropriately.
  1254. *
  1255. * If it's a rendezvous stream, call connection_exit_connect() on
  1256. * it.
  1257. *
  1258. * For general streams, call dns_resolve() on it first, and only call
  1259. * connection_exit_connect() if the dns answer is already known.
  1260. *
  1261. * Note that we don't call connection_add() on the new stream! We wait
  1262. * for connection_exit_connect() to do that.
  1263. *
  1264. * Return -1 if we want to tear down <b>circ</b>. Else return 0.
  1265. */
  1266. int
  1267. connection_exit_begin_conn(cell_t *cell, circuit_t *circ)
  1268. {
  1269. connection_t *n_stream;
  1270. relay_header_t rh;
  1271. char *address=NULL;
  1272. uint16_t port;
  1273. assert_circuit_ok(circ);
  1274. relay_header_unpack(&rh, cell->payload);
  1275. /* XXX currently we don't send an end cell back if we drop the
  1276. * begin because it's malformed.
  1277. */
  1278. if (!memchr(cell->payload+RELAY_HEADER_SIZE, 0, rh.length)) {
  1279. log_fn(LOG_WARN,"relay begin cell has no \\0. Dropping.");
  1280. return 0;
  1281. }
  1282. if (parse_addr_port(cell->payload+RELAY_HEADER_SIZE,&address,NULL,&port)<0) {
  1283. log_fn(LOG_WARN,"Unable to parse addr:port in relay begin cell. Dropping.");
  1284. return 0;
  1285. }
  1286. if (port==0) {
  1287. log_fn(LOG_WARN,"Missing port in relay begin cell. Dropping.");
  1288. tor_free(address);
  1289. return 0;
  1290. }
  1291. log_fn(LOG_DEBUG,"Creating new exit connection.");
  1292. n_stream = connection_new(CONN_TYPE_EXIT);
  1293. n_stream->purpose = EXIT_PURPOSE_CONNECT;
  1294. n_stream->stream_id = rh.stream_id;
  1295. n_stream->port = port;
  1296. /* leave n_stream->s at -1, because it's not yet valid */
  1297. n_stream->package_window = STREAMWINDOW_START;
  1298. n_stream->deliver_window = STREAMWINDOW_START;
  1299. if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED) {
  1300. log_fn(LOG_DEBUG,"begin is for rendezvous. configuring stream.");
  1301. n_stream->address = tor_strdup("(rendezvous)");
  1302. n_stream->state = EXIT_CONN_STATE_CONNECTING;
  1303. strlcpy(n_stream->rend_query, circ->rend_query,
  1304. sizeof(n_stream->rend_query));
  1305. tor_assert(connection_edge_is_rendezvous_stream(n_stream));
  1306. assert_circuit_ok(circ);
  1307. if (rend_service_set_connection_addr_port(n_stream, circ) < 0) {
  1308. log_fn(LOG_INFO,"Didn't find rendezvous service (port %d)",n_stream->port);
  1309. connection_edge_end(n_stream, END_STREAM_REASON_EXITPOLICY, n_stream->cpath_layer);
  1310. connection_free(n_stream);
  1311. circuit_mark_for_close(circ); /* knock the whole thing down, somebody screwed up */
  1312. tor_free(address);
  1313. return 0;
  1314. }
  1315. assert_circuit_ok(circ);
  1316. log_fn(LOG_DEBUG,"Finished assigning addr/port");
  1317. n_stream->cpath_layer = circ->cpath->prev; /* link it */
  1318. /* add it into the linked list of n_streams on this circuit */
  1319. n_stream->next_stream = circ->n_streams;
  1320. n_stream->on_circuit = circ;
  1321. circ->n_streams = n_stream;
  1322. assert_circuit_ok(circ);
  1323. connection_exit_connect(n_stream);
  1324. tor_free(address);
  1325. return 0;
  1326. }
  1327. tor_strlower(address);
  1328. n_stream->address = address;
  1329. n_stream->state = EXIT_CONN_STATE_RESOLVEFAILED;
  1330. /* default to failed, change in dns_resolve if it turns out not to fail */
  1331. if (we_are_hibernating()) {
  1332. connection_edge_end(n_stream, END_STREAM_REASON_HIBERNATING, n_stream->cpath_layer);
  1333. connection_free(n_stream);
  1334. return 0;
  1335. }
  1336. /* send it off to the gethostbyname farm */
  1337. switch (dns_resolve(n_stream)) {
  1338. case 1: /* resolve worked */
  1339. /* add it into the linked list of n_streams on this circuit */
  1340. n_stream->next_stream = circ->n_streams;
  1341. n_stream->on_circuit = circ;
  1342. circ->n_streams = n_stream;
  1343. assert_circuit_ok(circ);
  1344. connection_exit_connect(n_stream);
  1345. return 0;
  1346. case -1: /* resolve failed */
  1347. /* n_stream got freed. don't touch it. */
  1348. break;
  1349. case 0: /* resolve added to pending list */
  1350. /* add it into the linked list of resolving_streams on this circuit */
  1351. n_stream->next_stream = circ->resolving_streams;
  1352. n_stream->on_circuit = circ;
  1353. circ->resolving_streams = n_stream;
  1354. assert_circuit_ok(circ);
  1355. ;
  1356. }
  1357. return 0;
  1358. }
  1359. /**
  1360. * Called when we receive a RELAY_RESOLVE cell 'cell' along the circuit 'circ';
  1361. * begin resolving the hostname, and (eventually) reply with a RESOLVED cell.
  1362. */
  1363. int
  1364. connection_exit_begin_resolve(cell_t *cell, circuit_t *circ)
  1365. {
  1366. connection_t *dummy_conn;
  1367. relay_header_t rh;
  1368. assert_circuit_ok(circ);
  1369. relay_header_unpack(&rh, cell->payload);
  1370. /* This 'dummy_conn' only exists to remember the stream ID
  1371. * associated with the resolve request; and to make the
  1372. * implementation of dns.c more uniform. (We really only need to
  1373. * remember the circuit, the stream ID, and the hostname to be
  1374. * resolved; but if we didn't store them in a connection like this,
  1375. * the housekeeping in dns.c would get way more complicated.)
  1376. */
  1377. dummy_conn = connection_new(CONN_TYPE_EXIT);
  1378. dummy_conn->stream_id = rh.stream_id;
  1379. dummy_conn->address = tor_strndup(cell->payload+RELAY_HEADER_SIZE,
  1380. rh.length);
  1381. dummy_conn->port = 0;
  1382. dummy_conn->state = EXIT_CONN_STATE_RESOLVEFAILED;
  1383. dummy_conn->purpose = EXIT_PURPOSE_RESOLVE;
  1384. /* send it off to the gethostbyname farm */
  1385. switch (dns_resolve(dummy_conn)) {
  1386. case -1: /* Impossible to resolve; a resolved cell was sent. */
  1387. /* Connection freed; don't touch it. */
  1388. return 0;
  1389. case 1: /* The result was cached; a resolved cell was sent. */
  1390. if (!dummy_conn->marked_for_close)
  1391. connection_free(dummy_conn);
  1392. return 0;
  1393. case 0: /* resolve added to pending list */
  1394. dummy_conn->next_stream = circ->resolving_streams;
  1395. dummy_conn->on_circuit = circ;
  1396. circ->resolving_streams = dummy_conn;
  1397. assert_circuit_ok(circ);
  1398. break;
  1399. }
  1400. return 0;
  1401. }
  1402. /** Connect to conn's specified addr and port. If it worked, conn
  1403. * has now been added to the connection_array.
  1404. *
  1405. * Send back a connected cell. Include the resolved IP of the destination
  1406. * address, but <em>only</em> if it's a general exit stream. (Rendezvous
  1407. * streams must not reveal what IP they connected to.)
  1408. */
  1409. void
  1410. connection_exit_connect(connection_t *conn)
  1411. {
  1412. char connected_payload[4];
  1413. uint32_t addr;
  1414. uint16_t port;
  1415. if (!connection_edge_is_rendezvous_stream(conn) &&
  1416. router_compare_to_my_exit_policy(conn)) {
  1417. log_fn(LOG_INFO,"%s:%d failed exit policy. Closing.",
  1418. safe_str(conn->address), conn->port);
  1419. connection_edge_end(conn, END_STREAM_REASON_EXITPOLICY, conn->cpath_layer);
  1420. circuit_detach_stream(circuit_get_by_edge_conn(conn), conn);
  1421. connection_free(conn);
  1422. return;
  1423. }
  1424. addr = conn->addr;
  1425. port = conn->port;
  1426. if (redirect_exit_list) {
  1427. SMARTLIST_FOREACH(redirect_exit_list, exit_redirect_t *, r,
  1428. {
  1429. if ((addr&r->mask)==(r->addr&r->mask) &&
  1430. (r->port_min <= port) && (port <= r->port_max)) {
  1431. struct in_addr in;
  1432. if (r->is_redirect) {
  1433. char tmpbuf[INET_NTOA_BUF_LEN];
  1434. addr = r->addr_dest;
  1435. port = r->port_dest;
  1436. in.s_addr = htonl(addr);
  1437. tor_inet_ntoa(&in, tmpbuf, sizeof(tmpbuf));
  1438. log_fn(LOG_DEBUG, "Redirecting connection from %s:%d to %s:%d",
  1439. safe_str(conn->address), conn->port, safe_str(tmpbuf), port);
  1440. }
  1441. break;
  1442. }
  1443. });
  1444. }
  1445. log_fn(LOG_DEBUG,"about to try connecting");
  1446. switch (connection_connect(conn, conn->address, addr, port)) {
  1447. case -1:
  1448. connection_edge_end_errno(conn, conn->cpath_layer);
  1449. circuit_detach_stream(circuit_get_by_edge_conn(conn), conn);
  1450. connection_free(conn);
  1451. return;
  1452. case 0:
  1453. conn->state = EXIT_CONN_STATE_CONNECTING;
  1454. connection_watch_events(conn, EV_WRITE | EV_READ);
  1455. /* writable indicates finish;
  1456. * readable/error indicates broken link in windowsland. */
  1457. return;
  1458. /* case 1: fall through */
  1459. }
  1460. conn->state = EXIT_CONN_STATE_OPEN;
  1461. if (connection_wants_to_flush(conn)) { /* in case there are any queued data cells */
  1462. log_fn(LOG_WARN,"Bug: newly connected conn had data waiting!");
  1463. // connection_start_writing(conn);
  1464. }
  1465. connection_watch_events(conn, EV_READ);
  1466. /* also, deliver a 'connected' cell back through the circuit. */
  1467. if (connection_edge_is_rendezvous_stream(conn)) { /* rendezvous stream */
  1468. /* don't send an address back! */
  1469. connection_edge_send_command(conn, circuit_get_by_edge_conn(conn),
  1470. RELAY_COMMAND_CONNECTED,
  1471. NULL, 0, conn->cpath_layer);
  1472. } else { /* normal stream */
  1473. /* This must be the original address, not the redirected address. */
  1474. *(uint32_t*)connected_payload = htonl(conn->addr);
  1475. connection_edge_send_command(conn, circuit_get_by_edge_conn(conn),
  1476. RELAY_COMMAND_CONNECTED,
  1477. connected_payload, 4, conn->cpath_layer);
  1478. }
  1479. }
  1480. /** Return 1 if <b>conn</b> is a rendezvous stream, or 0 if
  1481. * it is a general stream.
  1482. */
  1483. int
  1484. connection_edge_is_rendezvous_stream(connection_t *conn)
  1485. {
  1486. tor_assert(conn);
  1487. if (*conn->rend_query) /* XXX */
  1488. return 1;
  1489. return 0;
  1490. }
  1491. /** Return 1 if router <b>exit</b> is likely to allow stream <b>conn</b>
  1492. * to exit from it, or 0 if it probably will not allow it.
  1493. * (We might be uncertain if conn's destination address has not yet been
  1494. * resolved.)
  1495. */
  1496. int
  1497. connection_ap_can_use_exit(connection_t *conn, routerinfo_t *exit)
  1498. {
  1499. tor_assert(conn);
  1500. tor_assert(conn->type == CONN_TYPE_AP);
  1501. tor_assert(conn->socks_request);
  1502. tor_assert(exit);
  1503. log_fn(LOG_DEBUG,"considering nickname %s, for address %s / port %d:",
  1504. exit->nickname, safe_str(conn->socks_request->address),
  1505. conn->socks_request->port);
  1506. /* If a particular exit node has been requested for the new connection,
  1507. * make sure the exit node of the existing circuit matches exactly.
  1508. */
  1509. if (conn->chosen_exit_name) {
  1510. if (router_get_by_nickname(conn->chosen_exit_name) != exit) {
  1511. /* doesn't match */
  1512. log_fn(LOG_DEBUG,"Requested node '%s', considering node '%s'. No.",
  1513. conn->chosen_exit_name, exit->nickname);
  1514. return 0;
  1515. }
  1516. }
  1517. if (conn->socks_request->command != SOCKS_COMMAND_RESOLVE) {
  1518. struct in_addr in;
  1519. uint32_t addr = 0;
  1520. addr_policy_result_t r;
  1521. if (tor_inet_aton(conn->socks_request->address, &in))
  1522. addr = ntohl(in.s_addr);
  1523. r = router_compare_addr_to_addr_policy(addr, conn->socks_request->port,
  1524. exit->exit_policy);
  1525. if (r == ADDR_POLICY_REJECTED || r == ADDR_POLICY_PROBABLY_REJECTED)
  1526. return 0;
  1527. }
  1528. return 1;
  1529. }
  1530. /** A helper function for socks_policy_permits_address() below.
  1531. *
  1532. * Parse options->SocksPolicy in the same way that the exit policy
  1533. * is parsed, and put the processed version in &socks_policy.
  1534. * Ignore port specifiers.
  1535. */
  1536. void
  1537. parse_socks_policy(void)
  1538. {
  1539. addr_policy_t *n;
  1540. if (socks_policy) {
  1541. addr_policy_free(socks_policy);
  1542. socks_policy = NULL;
  1543. }
  1544. config_parse_addr_policy(get_options()->SocksPolicy, &socks_policy);
  1545. /* ports aren't used. */
  1546. for (n=socks_policy; n; n = n->next) {
  1547. n->prt_min = 1;
  1548. n->prt_max = 65535;
  1549. }
  1550. }
  1551. /** Free all storage held by our SOCKS allow policy
  1552. */
  1553. void
  1554. free_socks_policy(void)
  1555. {
  1556. addr_policy_free(socks_policy);
  1557. socks_policy = NULL;
  1558. }
  1559. /** Return 1 if <b>addr</b> is permitted to connect to our socks port,
  1560. * based on <b>socks_policy</b>. Else return 0.
  1561. */
  1562. int
  1563. socks_policy_permits_address(uint32_t addr)
  1564. {
  1565. int a;
  1566. if (!socks_policy) /* 'no socks policy' means 'accept' */
  1567. return 1;
  1568. a = router_compare_addr_to_addr_policy(addr, 1, socks_policy);
  1569. if (a==ADDR_POLICY_REJECTED)
  1570. return 0;
  1571. else if (a==ADDR_POLICY_ACCEPTED)
  1572. return 1;
  1573. log_fn(LOG_WARN, "Bug: Got unexpected 'maybe' answer from socks policy");
  1574. return 0;
  1575. }
  1576. /** Make connection redirection follow the provided list of
  1577. * exit_redirect_t */
  1578. void
  1579. set_exit_redirects(smartlist_t *lst)
  1580. {
  1581. if (redirect_exit_list) {
  1582. SMARTLIST_FOREACH(redirect_exit_list, exit_redirect_t *, p, tor_free(p));
  1583. smartlist_free(redirect_exit_list);
  1584. }
  1585. redirect_exit_list = lst;
  1586. }
  1587. /** If address is of the form "y.onion" with a well-formed handle y:
  1588. * Put a \code{'\0'} after y, lower-case it, and return ONION_HOSTNAME.
  1589. *
  1590. * If address is of the form "y.exit":
  1591. * Put a \code{'\0'} after y and return EXIT_HOSTNAME.
  1592. *
  1593. * Otherwise:
  1594. * Return NORMAL_HOSTNAME and change nothing.
  1595. */
  1596. hostname_type_t
  1597. parse_extended_hostname(char *address)
  1598. {
  1599. char *s;
  1600. char query[REND_SERVICE_ID_LEN+1];
  1601. s = strrchr(address,'.');
  1602. if (!s) return 0; /* no dot, thus normal */
  1603. if (!strcmp(s+1,"exit")) {
  1604. *s = 0; /* null-terminate it */
  1605. return EXIT_HOSTNAME; /* .exit */
  1606. }
  1607. if (strcmp(s+1,"onion"))
  1608. return NORMAL_HOSTNAME; /* neither .exit nor .onion, thus normal */
  1609. /* so it is .onion */
  1610. *s = 0; /* null-terminate it */
  1611. if (strlcpy(query, address, REND_SERVICE_ID_LEN+1) >= REND_SERVICE_ID_LEN+1)
  1612. goto failed;
  1613. if (rend_valid_service_id(query)) {
  1614. return ONION_HOSTNAME; /* success */
  1615. }
  1616. failed:
  1617. /* otherwise, return to previous state and return 0 */
  1618. *s = '.';
  1619. return BAD_HOSTNAME;
  1620. }