Skip to main content

tor_geoip/
rpc.rs

1//! RPC APIs for geoip functionality.
2
3use std::{collections::HashMap, sync::Arc};
4
5use tor_rpcbase as rpc;
6use tor_rpcbase::derive_deftly::Deftly;
7
8use crate::{CountryCode, GeoipDb};
9
10/// Look up the country codes for a list of IP addresses.
11///
12/// The caller passes a list of addresses in the `address` field;
13/// the method returns a map from addresses to country code.
14///
15/// If a country code is not known for some address,
16/// then it is omitted from the map.
17#[derive(Debug, serde::Deserialize, serde::Serialize, Deftly)]
18#[derive_deftly(rpc::DynMethod)]
19#[deftly(rpc(method_name = "arti:geoip_lookup_countries"))]
20#[non_exhaustive]
21struct GeoipLookupCountries {
22    /// The addresses to look countries for.
23    ///
24    /// It is an error to include an entry here that is not an IP address.
25    //
26    // Note: we take these arguments as strings so that we can preserve
27    // them exactly as keys in the output map.  Otherwise, it would get
28    // confusing for any clients that provided non-normalized IPs.
29    #[serde(default)]
30    addresses: Vec<String>,
31}
32
33impl rpc::RpcMethod for GeoipLookupCountries {
34    type Output = GeoipLookupResult;
35
36    type Update = rpc::NoUpdates;
37}
38
39/// Result returned by the `arti:geoip_lookup_countries` method.
40#[derive(Debug, serde::Serialize)]
41#[non_exhaustive]
42struct GeoipLookupResult {
43    /// A map from addresses to country codes.
44    ///
45    /// Countries without known addresses are omitted.
46    countries: HashMap<String, CountryCode>,
47}
48
49impl GeoipDb {
50    /// Actually perform the geoip lookup for a given [`GeoipLookupCountries`] request.
51    fn rpc_lookup_countries(
52        &self,
53        request: GeoipLookupCountries,
54    ) -> Result<GeoipLookupResult, std::net::AddrParseError> {
55        let countries: Result<HashMap<_, _>, _> = request
56            .addresses
57            .into_iter()
58            .filter_map(|s| {
59                s.parse()
60                    .map(|ip| Some((s, *self.lookup_country_code(ip)?)))
61                    .transpose()
62            })
63            .collect();
64
65        Ok(GeoipLookupResult {
66            countries: countries?,
67        })
68    }
69}
70
71/// Implementation for [`GeoipLookupCountries`] on [`GeoipDb`].
72async fn geoip_lookup_on_geoipdb(
73    db: Arc<GeoipDb>,
74    method: Box<GeoipLookupCountries>,
75    _ctx: Arc<dyn rpc::Context>,
76) -> Result<GeoipLookupResult, rpc::RpcError> {
77    db.rpc_lookup_countries(*method)
78        .map_err(|e| rpc::RpcError::new(e.to_string(), rpc::RpcErrorKind::RequestError))
79}
80
81rpc::static_rpc_invoke_fn! {
82    geoip_lookup_on_geoipdb;
83}