Skip to main content

servo/
geoclue.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5//! A [`GeolocationDelegate`](crate::GeolocationDelegate) backend built on GeoClue.
6//!
7//! Details about the design:
8//! - This runs as a task on the shared async runtime instead of using a dedicated thread.
9//! - `Manager.GetClient()` returns one client per D-Bus connection, so every page using
10//!   geolocation in this Servo instance shares a single client. The task multiplexes and
11//!   keeps one client alive for as long as anything wants a position, requests the highest
12//!   accuracy asked for, and dispatches each update to all delegate requests.
13//! - GeoClue has no one-shot request. `getCurrentPosition()` is served by joining the shared
14//!   client and taking the first position emitted by the stream.
15
16use std::collections::HashMap;
17
18use embedder_traits::{GeolocationError, GeolocationPositionData, GeolocationWatchId};
19use futures::channel::mpsc::{UnboundedReceiver, UnboundedSender, unbounded};
20use futures::{FutureExt, StreamExt, select};
21use log::{debug, error};
22use net::async_runtime;
23use servo_config::pref;
24use zbus::proxy::CacheProperties;
25use zbus::zvariant::OwnedObjectPath;
26use zbus::{Connection, proxy};
27
28use crate::geolocation_delegate::{PositionRequest, PositionWatch};
29
30/// <https://www.freedesktop.org/software/geoclue/docs/geoclue-gclue-enums.html>
31#[derive(Clone, Copy, PartialEq)]
32#[repr(u32)]
33enum AccuracyLevel {
34    City = 4,
35    Exact = 8,
36}
37
38/// GeoClue reports "no altitude" as a very large negative number rather than an absent value.
39/// Firefox uses the same cutoff.
40const MINIMUM_PLAUSIBLE_ALTITUDE: f64 = -500.0;
41
42#[proxy(
43    interface = "org.freedesktop.GeoClue2.Manager",
44    default_service = "org.freedesktop.GeoClue2",
45    default_path = "/org/freedesktop/GeoClue2/Manager"
46)]
47trait Manager {
48    fn get_client(&self) -> zbus::Result<OwnedObjectPath>;
49}
50
51#[proxy(
52    interface = "org.freedesktop.GeoClue2.Client",
53    default_service = "org.freedesktop.GeoClue2",
54    assume_defaults = false
55)]
56trait Client {
57    fn start(&self) -> zbus::Result<()>;
58    fn stop(&self) -> zbus::Result<()>;
59
60    /// The name of the application's desktop file, which GeoClue uses to grant some access.
61    #[zbus(property)]
62    fn set_desktop_id(&self, id: &str) -> zbus::Result<()>;
63
64    #[zbus(property)]
65    fn set_requested_accuracy_level(&self, level: u32) -> zbus::Result<()>;
66
67    /// The most recent location, or `/` before there has been one.
68    #[zbus(property)]
69    fn location(&self) -> zbus::Result<OwnedObjectPath>;
70
71    #[zbus(signal)]
72    fn location_updated(
73        &self,
74        previous: OwnedObjectPath,
75        current: OwnedObjectPath,
76    ) -> zbus::Result<()>;
77}
78
79#[proxy(
80    interface = "org.freedesktop.GeoClue2.Location",
81    default_service = "org.freedesktop.GeoClue2",
82    assume_defaults = false
83)]
84trait Location {
85    #[zbus(property)]
86    fn latitude(&self) -> zbus::Result<f64>;
87    #[zbus(property)]
88    fn longitude(&self) -> zbus::Result<f64>;
89    /// Horizontal accuracy in metres.
90    #[zbus(property)]
91    fn accuracy(&self) -> zbus::Result<f64>;
92    #[zbus(property)]
93    fn altitude(&self) -> zbus::Result<f64>;
94    /// Metres per second, or negative if unknown.
95    #[zbus(property)]
96    fn speed(&self) -> zbus::Result<f64>;
97    /// Degrees clockwise from true north, or negative if unknown.
98    #[zbus(property)]
99    fn heading(&self) -> zbus::Result<f64>;
100}
101
102/// Translate a D-Bus failure into the closest `GeolocationPositionError` code, matching the
103/// mapping Firefox uses in `GeoclueLocationProvider::DBusProxyError`.
104fn convert_error(error: zbus::Error) -> GeolocationError {
105    let zbus::Error::MethodError(ref name, _, _) = error else {
106        return GeolocationError::position_unavailable(error.to_string());
107    };
108    match name.as_str() {
109        "org.freedesktop.DBus.Error.Timeout" | "org.freedesktop.DBus.Error.TimedOut" => {
110            GeolocationError::timeout(error.to_string())
111        },
112        "org.freedesktop.DBus.Error.AccessDenied" |
113        "org.freedesktop.DBus.Error.AuthFailed" |
114        "org.freedesktop.DBus.Error.LimitsExceeded" => {
115            GeolocationError::permission_denied(error.to_string())
116        },
117        _ => GeolocationError::position_unavailable(error.to_string()),
118    }
119}
120
121async fn read_position(
122    connection: &Connection,
123    path: OwnedObjectPath,
124) -> zbus::Result<GeolocationPositionData> {
125    // A Location object is an immutable snapshot that GeoClue discards again, so caching its
126    // properties would only add a PropertiesChanged subscription with nothing to report.
127    let location = LocationProxy::builder(connection)
128        .path(path)?
129        .cache_properties(CacheProperties::No)
130        .build()
131        .await?;
132
133    let altitude = location.altitude().await?;
134    let speed = location.speed().await?;
135    let heading = location.heading().await?;
136
137    Ok(GeolocationPositionData {
138        accuracy: location.accuracy().await?,
139        latitude: location.latitude().await?,
140        longitude: location.longitude().await?,
141        altitude: (altitude >= MINIMUM_PLAUSIBLE_ALTITUDE).then_some(altitude),
142        // GeoClue does not report a vertical accuracy.
143        altitude_accuracy: None,
144        heading: (heading >= 0.).then_some(heading),
145        speed: (speed >= 0.).then_some(speed),
146    })
147}
148
149/// Work handed to the GeoClue task by the delegate.
150enum Request {
151    /// A one-shot `getCurrentPosition()`, answered by the next position to arrive.
152    Acquire(PositionRequest),
153    StartWatch(PositionWatch),
154    StopWatch(GeolocationWatchId),
155}
156
157/// A handle to the task that owns Servo's connection to GeoClue.
158pub(crate) struct Geoclue(UnboundedSender<Request>);
159
160static GEOCLUE: std::sync::OnceLock<Option<Geoclue>> = std::sync::OnceLock::new();
161
162impl Geoclue {
163    /// Get the singleton instance of the Geoclue client.
164    pub(crate) fn singleton() -> Option<&'static Self> {
165        GEOCLUE.get_or_init(Geoclue::spawn).as_ref()
166    }
167
168    /// Start the GeoClue task on Servo's shared runtime. The connection is created lazily, so a session
169    /// that never uses geolocation pays nothing.
170    pub(crate) fn spawn() -> Option<Self> {
171        debug!("Spawning Geoclue DBus client");
172        if !async_runtime::async_runtime_initialized() {
173            error!("No async runtime yet; geolocation is unavailable.");
174            return None;
175        }
176        let (sender, receiver) = unbounded();
177        async_runtime::spawn_task(GeoclueTaskState::default().run(receiver));
178        Some(Self(sender))
179    }
180
181    pub(crate) fn request_position(&self, request: PositionRequest) {
182        let _ = self.0.unbounded_send(Request::Acquire(request));
183    }
184
185    pub(crate) fn start_watch(&self, watch: PositionWatch) {
186        if self.0.unbounded_send(Request::StartWatch(watch)).is_err() {
187            error!("The GeoClue task is gone; no positions will be delivered.");
188        }
189    }
190
191    pub(crate) fn stop_watch(&self, id: &GeolocationWatchId) {
192        let _ = self.0.unbounded_send(Request::StopWatch(id.clone()));
193    }
194}
195
196/// The live connection to GeoClue, held only while something wants a position.
197struct Session {
198    connection: Connection,
199    client: ClientProxy<'static>,
200    accuracy: AccuracyLevel,
201}
202
203/// The state of the GeoClue task.
204#[derive(Default)]
205struct GeoclueTaskState {
206    session: Option<Session>,
207    /// Bumped whenever a new `session` is created, so that the run loop knows when its
208    /// subscription belongs to a client that no longer exists.
209    generation: u64,
210    /// `getCurrentPosition()` calls waiting for the next position.
211    pending: Vec<PositionRequest>,
212    /// `watchPosition()` calls, for as long as script wants them.
213    watches: HashMap<GeolocationWatchId, PositionWatch>,
214}
215
216impl GeoclueTaskState {
217    async fn run(mut self, mut requests: UnboundedReceiver<Request>) {
218        let mut updates_stream: Option<LocationUpdatedStream> = None;
219        let mut subscribed_to = None;
220
221        loop {
222            if subscribed_to != Some(self.generation) {
223                // Drop any subscription belonging to the previous dbus client before taking a new one.
224                updates_stream = None;
225                let client = self.session.as_ref().map(|session| session.client.clone());
226                if let Some(client) = client {
227                    match client.receive_location_updated().await {
228                        Ok(stream) => updates_stream = Some(stream),
229                        Err(error) => {
230                            self.handle_failure(error);
231                            continue;
232                        },
233                    }
234                }
235                subscribed_to = Some(self.generation);
236
237                // Now that updates are being listened for, pick up a fix that may have landed
238                // between starting the client and subscribing. Without this a device that never
239                // moves again would never produce a new position.
240                if updates_stream.is_some() && !self.is_idle() {
241                    self.report_current_position().await;
242                }
243            }
244
245            let next_update = async {
246                match updates_stream.as_mut() {
247                    Some(stream) => stream.next().await,
248                    // Without a session there is no update to wait for, only requests.
249                    None => futures::future::pending::<Option<LocationUpdated>>().await,
250                }
251            };
252
253            select! {
254                request = requests.next() => {
255                    let Some(request) = request else {
256                        // The delegate, and with it `Servo`, is gone.
257                        break;
258                    };
259                    self.handle_request(request).await;
260                },
261                update = next_update.fuse() => match update {
262                    Some(update) => self.handle_update(update).await,
263                    // GeoClue went away.
264                    None => self.close_session().await,
265                },
266            }
267        }
268        self.close_session().await;
269    }
270
271    async fn handle_request(&mut self, request: Request) {
272        match request {
273            Request::Acquire(request) => {
274                let wants_high_accuracy = request.options().high_accuracy;
275                self.pending.push(request);
276                if let Err(error) = self.open_or_update_session(wants_high_accuracy).await {
277                    self.handle_failure(error);
278                    return;
279                }
280                // A position may already be available, in which case there is no reason to
281                // wait for the device to move.
282                self.report_current_position().await;
283            },
284            Request::StartWatch(watch) => {
285                let wants_high_accuracy = watch.options().high_accuracy;
286                self.watches.insert(watch.id(), watch);
287                if let Err(error) = self.open_or_update_session(wants_high_accuracy).await {
288                    self.handle_failure(error);
289                    return;
290                }
291                self.report_current_position().await;
292            },
293            Request::StopWatch(id) => {
294                self.watches.remove(&id);
295                if self.is_idle() {
296                    self.close_session().await;
297                }
298            },
299        }
300    }
301
302    async fn handle_update(&mut self, update: LocationUpdated) {
303        let Ok(args) = update.args() else {
304            return;
305        };
306        let Some(connection) = self
307            .session
308            .as_ref()
309            .map(|session| session.connection.clone())
310        else {
311            return;
312        };
313        match read_position(&connection, args.current().clone()).await {
314            Ok(position) => self.report(Ok(position)).await,
315            Err(error) => self.handle_failure(error),
316        }
317    }
318
319    /// Deliver the position the client is already holding, if it has one. GeoClue points the
320    /// client's `Location` property at `/` until the first fix.
321    async fn report_current_position(&mut self) {
322        let Some((connection, client)) = self
323            .session
324            .as_ref()
325            .map(|session| (session.connection.clone(), session.client.clone()))
326        else {
327            error!("No client!");
328            return;
329        };
330        let path = match client.location().await {
331            Ok(path) if path.as_str() != "/" => path,
332            Ok(_) => return,
333            Err(error) => return self.handle_failure(error),
334        };
335        match read_position(&connection, path).await {
336            Ok(position) => self.report(Ok(position)).await,
337            Err(error) => self.handle_failure(error),
338        }
339    }
340
341    /// Hand a result to everyone waiting for a position.
342    ///
343    /// A consumer joining a client that already has a fix makes every watch see that position
344    /// again. Firefox re-delivers its last position to new watchers for the same reason.
345    async fn report(&mut self, result: Result<GeolocationPositionData, GeolocationError>) {
346        for request in self.pending.drain(..) {
347            match result.clone() {
348                Ok(position) => request.success(position),
349                Err(error) => request.failure(error),
350            }
351        }
352        for watch in self.watches.values() {
353            match result.clone() {
354                Ok(position) => watch.update(position),
355                Err(error) => watch.error(error),
356            }
357        }
358        if self.is_idle() {
359            self.close_session().await;
360        }
361    }
362
363    /// Report a D-Bus failure to script and tear the session down.
364    ///
365    /// If GeoClue denied us because its agent had not connected yet, `GetClient()` keeps
366    /// returning the same rejected client, so the connection itself has to go for a later attempt
367    /// to have any chance. Firefox carries the same workaround for
368    /// <https://gitlab.freedesktop.org/geoclue/geoclue/-/issues/143>.
369    fn handle_failure(&mut self, error: zbus::Error) {
370        let error = convert_error(error);
371        error!("GeoClue request failed: {}", error.message);
372
373        // Dropped our session object since it's already unusable and can't be properly
374        // closed anymore.
375        self.session = None;
376
377        for request in self.pending.drain(..) {
378            request.failure(error.clone());
379        }
380        // Tell the watches too, rather than leaving them waiting on a session that no longer
381        // exists. They stay registered, and the next request from script rebuilds the session and
382        // starts feeding them again.
383        for watch in self.watches.values() {
384            watch.error(error.clone());
385        }
386    }
387
388    fn is_idle(&self) -> bool {
389        self.pending.is_empty() && self.watches.is_empty()
390    }
391
392    /// The accuracy to request: the most any current consumer asked for.
393    fn wanted_accuracy(&self, wants_high_accuracy: bool) -> AccuracyLevel {
394        let high = wants_high_accuracy ||
395            self.pending
396                .iter()
397                .any(|request| request.options().high_accuracy) ||
398            self.watches
399                .values()
400                .any(|watch| watch.options().high_accuracy);
401        if high {
402            AccuracyLevel::Exact
403        } else {
404            AccuracyLevel::City
405        }
406    }
407
408    /// Make sure a started client exists, restarting it if the accuracy it was started with is no
409    /// longer the one we want since GeoClue only honours `RequestedAccuracyLevel` at `Start()`.
410    async fn open_or_update_session(&mut self, wants_high_accuracy: bool) -> zbus::Result<()> {
411        let accuracy = self.wanted_accuracy(wants_high_accuracy);
412
413        let existing = self
414            .session
415            .as_ref()
416            .map(|session| (session.client.clone(), session.accuracy));
417        if let Some((client, started_with)) = existing {
418            if started_with == accuracy {
419                return Ok(());
420            }
421            client.stop().await?;
422            client.set_requested_accuracy_level(accuracy as u32).await?;
423            client.start().await?;
424            if let Some(session) = self.session.as_mut() {
425                session.accuracy = accuracy;
426            }
427            return Ok(());
428        }
429
430        let connection = Connection::system().await?;
431        let manager = ManagerProxy::new(&connection).await?;
432        let client = ClientProxy::builder(&connection)
433            .path(manager.get_client().await?)?
434            .cache_properties(CacheProperties::No)
435            .build()
436            .await?;
437
438        // This is supposed to match the name of a .desktop file to bypass
439        // the need for interactive agent authorization.
440        let desktop_id = pref!(embedder_name);
441        client.set_desktop_id(&desktop_id).await?;
442
443        client.set_requested_accuracy_level(accuracy as u32).await?;
444        client.start().await?;
445
446        self.session = Some(Session {
447            connection,
448            client,
449            accuracy,
450        });
451        self.generation += 1;
452        Ok(())
453    }
454
455    async fn close_session(&mut self) {
456        let Some(session) = self.session.take() else {
457            return;
458        };
459        if let Err(error) = session.client.stop().await {
460            error!("Could not stop the GeoClue client ({error}).");
461        }
462    }
463}