1
use oo7::{
2
    Secret,
3
    file::{Keyring, LockedKeyring, UnlockedKeyring},
4
};
5
use tokio_stream::StreamExt;
6
use zbus::{
7
    fdo::{RequestNameFlags, RequestNameReply},
8
    names::UniqueName,
9
    proxy::Defaults,
10
    wire::Optional,
11
};
12

            
13
use super::{Service, discovery, naming};
14
#[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))]
15
use crate::gnome::internal::InternalInterface;
16
use crate::{collection::Collection, error::Error, prompt::Prompt};
17

            
18
impl Service {
19
    pub async fn run(
20
        secret: Option<Secret>,
21
        request_replacement: bool,
22
    ) -> Result<zbus::Connection, Error> {
23
        // Compute data directory from environment variables
24
        let data_dir = std::env::var_os("XDG_DATA_HOME")
25
            .filter(|h| !h.is_empty())
26
            .map(std::path::PathBuf::from)
27
            .filter(|p| p.is_absolute())
28
            .or_else(|| {
29
                std::env::var_os("HOME")
30
                    .filter(|h| !h.is_empty())
31
                    .map(std::path::PathBuf::from)
32
                    .map(|p| p.join(".local/share"))
33
            })
34
            .ok_or_else(|| {
35
                Error::IO(std::io::Error::new(
36
                    std::io::ErrorKind::NotFound,
37
                    "No data directory found (XDG_DATA_HOME or HOME)",
38
                ))
39
            })?;
40

            
41
        // Compute PAM socket path from environment variable
42
        let pam_socket = std::env::var_os("OO7_PAM_SOCKET").map(std::path::PathBuf::from);
43

            
44
        let service = Self::new(data_dir, pam_socket, true);
45

            
46
        // Start PAM listener early so it can buffer secrets arriving before
47
        // D-Bus is ready (e.g. during PAM-initiated login startup).
48
        tracing::info!("Starting PAM listener");
49
        let pam_listener = crate::pam_listener::PamListener::new(service.clone());
50
        let pam_listener_replay = pam_listener.clone();
51
        tokio::spawn(async move {
52
            if let Err(e) = pam_listener.start().await {
53
                tracing::error!("PAM listener error: {}", e);
54
            }
55
        });
56

            
57
        // The name is requested only once the service is initialized
58
        let connection = zbus::connection::Builder::session()
59
            .serve_at(
60
                oo7::dbus::api::Service::PATH.as_deref().unwrap(),
61
                service.clone(),
62
            )
63
            .build()
64
            .await?;
65

            
66
        #[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))]
67
        connection
68
            .object_server()
69
            .at(
70
                oo7::dbus::api::Service::PATH.as_deref().unwrap(),
71
                InternalInterface::new(service.clone()),
72
            )
73
            .await?;
74

            
75
        // Discover existing keyrings
76
        let discovered_keyrings = service.discover_keyrings(secret.clone()).await?;
77

            
78
        let connection_clone = connection.clone();
79
        service
80
            .initialize(connection, discovered_keyrings, secret, true)
81
            .await?;
82

            
83
        let mut flags = RequestNameFlags::ALLOW_REPLACEMENT | RequestNameFlags::DO_NOT_QUEUE;
84
        if request_replacement {
85
            flags |= RequestNameFlags::REPLACE_EXISTING;
86
        }
87
        match connection_clone
88
            .request_name_with_flags(
89
                oo7::dbus::api::Service::DESTINATION.as_deref().unwrap(),
90
                flags,
91
            )
92
            .await?
93
        {
94
            RequestNameReply::PrimaryOwner | RequestNameReply::AlreadyOwner => {}
95
            RequestNameReply::Exists | RequestNameReply::InQueue => {
96
                return Err(Error::Zbus(zbus::Error::NameTaken));
97
            }
98
        }
99

            
100
        // Replay any secrets that the PAM listener buffered during startup
101
        pam_listener_replay.replay_buffered_secrets().await;
102

            
103
        Ok(connection_clone)
104
    }
105

            
106
    #[cfg(any(test, feature = "test-util"))]
107
    #[allow(dead_code)]
108
38
    pub async fn run_with_connection(
109
        connection: zbus::Connection,
110
        data_dir: std::path::PathBuf,
111
        pam_socket: Option<std::path::PathBuf>,
112
        secret: Option<Secret>,
113
        encrypted_supported: bool,
114
    ) -> Result<Self, Error> {
115
36
        let service = Self::new(data_dir, pam_socket, encrypted_supported);
116

            
117
        // Serve the service at the standard path
118
141
        connection
119
            .object_server()
120
            .at(
121
40
                oo7::dbus::api::Service::PATH.as_deref().unwrap(),
122
34
                service.clone(),
123
            )
124
153
            .await?;
125

            
126
        #[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))]
127
137
        connection
128
            .object_server()
129
            .at(
130
39
                oo7::dbus::api::Service::PATH.as_deref().unwrap(),
131
35
                InternalInterface::new(service.clone()),
132
            )
133
158
            .await?;
134

            
135
70
        let default_keyring = if let Some(secret) = secret.clone() {
136
113
            vec![discovery::LoadedKeyring {
137
39
                name: "default".to_owned(),
138
35
                label: "Login".to_owned(),
139
39
                alias: oo7::dbus::Service::DEFAULT_COLLECTION.to_owned(),
140
113
                keyring: Keyring::Unlocked(UnlockedKeyring::temporary(secret).await?),
141
35
                pending_migration: None,
142
            }]
143
        } else {
144
12
            vec![]
145
        };
146

            
147
139
        service
148
35
            .initialize(connection, default_keyring, secret, false)
149
128
            .await?;
150
26
        Ok(service)
151
    }
152

            
153
4
    pub(crate) async fn discover_keyrings(
154
        &self,
155
        secret: Option<Secret>,
156
    ) -> Result<Vec<discovery::LoadedKeyring>, Error> {
157
12
        let mut loaded = discovery::discover_keyrings(&self.data_dir, secret).await?;
158
8
        let mut pending = self.pending_migrations.lock().await;
159
8
        for item in &mut loaded {
160
12
            if let Some(migration) = item.pending_migration.take() {
161
8
                pending.insert(item.name.clone(), migration);
162
            }
163
        }
164
4
        Ok(loaded)
165
    }
166

            
167
38
    pub(crate) async fn initialize(
168
        &self,
169
        connection: zbus::Connection,
170
        mut discovered_keyrings: Vec<discovery::LoadedKeyring>,
171
        secret: Option<Secret>,
172
        auto_create_default: bool,
173
    ) -> Result<(), Error> {
174
74
        *self.connection.write().unwrap() = Some(connection.clone());
175

            
176
38
        let object_server = connection.object_server();
177
74
        let mut collections = self.collections.lock().await;
178

            
179
        // Check if we have a default collection
180
110
        let has_default = discovered_keyrings.iter().any(|dk| {
181
38
            dk.alias == oo7::dbus::Service::DEFAULT_COLLECTION || dk.alias == Self::LOGIN_ALIAS
182
        });
183

            
184
36
        if !has_default && auto_create_default {
185
            tracing::info!("No default collection found, creating 'Login' keyring");
186

            
187
            let keyring = if let Some(secret) = secret {
188
                UnlockedKeyring::open_at(&self.data_dir, Self::LOGIN_ALIAS, Some(secret))
189
                    .await
190
                    .map(Keyring::Unlocked)
191
            } else {
192
                LockedKeyring::open_at(&self.data_dir, Self::LOGIN_ALIAS)
193
                    .await
194
                    .map(Keyring::Locked)
195
            };
196

            
197
            let keyring = keyring.inspect_err(|e| {
198
                tracing::error!("Failed to create default Login keyring: {}", e);
199
            })?;
200

            
201
            let is_locked = if keyring.is_locked() {
202
                "locked"
203
            } else {
204
                "unlocked"
205
            };
206
            discovered_keyrings.push(discovery::LoadedKeyring {
207
                name: Self::LOGIN_ALIAS.to_owned(),
208
                label: "Login".to_owned(),
209
                alias: oo7::dbus::Service::DEFAULT_COLLECTION.to_owned(),
210
                keyring,
211
                pending_migration: None,
212
            });
213

            
214
            tracing::info!("Created default 'Login' collection ({})", is_locked);
215
        }
216

            
217
        // Sort so the login keyring is processed first
218
78
        discovered_keyrings.sort_by(|a, b| {
219
4
            let a_is_login = a.name.eq_ignore_ascii_case(Self::LOGIN_ALIAS);
220
4
            let b_is_login = b.name.eq_ignore_ascii_case(Self::LOGIN_ALIAS);
221
4
            b_is_login.cmp(&a_is_login)
222
        });
223

            
224
        // Build all collections under the lock, then register on D-Bus after
225
        // releasing it to avoid deadlocks with incoming calls.
226
38
        let mut built_collections: Vec<(Collection, String)> = Vec::new();
227

            
228
138
        for dk in discovered_keyrings {
229
74
            tracing::info!("Setting up collection '{}' (alias: {}).", dk.name, dk.alias);
230
79
            let (unique_label, unique_alias) =
231
                naming::make_unique_label_and_alias(&collections, &dk.label, &dk.alias).await;
232
            let collection = Collection::new(
233
35
                &dk.name,
234
35
                &unique_label,
235
35
                &unique_alias,
236
35
                self.clone(),
237
35
                dk.keyring,
238
            )
239
140
            .await;
240
65
            collections.insert(collection.path().to_owned().into(), collection.clone());
241
35
            built_collections.push((collection, unique_alias));
242
        }
243

            
244
        // Always create session collection (always temporary)
245
        let session_collection = Collection::new(
246
            "session",
247
            "session",
248
34
            oo7::dbus::Service::SESSION_COLLECTION,
249
66
            self.clone(),
250
96
            Keyring::Unlocked(UnlockedKeyring::temporary(Secret::random().unwrap()).await?),
251
        )
252
91
        .await;
253
61
        collections.insert(
254
59
            session_collection.path().to_owned().into(),
255
28
            session_collection.clone(),
256
        );
257

            
258
28
        drop(collections);
259

            
260
        // Now register on D-Bus and dispatch items without holding the lock
261
94
        for (collection, alias) in &built_collections {
262
            // A pending migration dispatches the placeholder items of the
263
            // legacy keyring, so they can be searched while locked
264
            let migration = {
265
94
                let pending = self.pending_migrations.lock().await;
266
63
                pending.get(collection.name()).cloned()
267
            };
268
33
            match migration {
269
4
                Some(migration) => {
270
16
                    let items = migration.items().await.unwrap_or_else(|e| {
271
                        tracing::warn!(
272
                            "Failed to read the items of the pending migration of '{}': {e}",
273
                            collection.name()
274
                        );
275
                        Vec::new()
276
                    });
277
8
                    collection.dispatch_file_items(items).await?;
278
                }
279
94
                None => collection.dispatch_items().await?,
280
            }
281
106
            object_server
282
54
                .at(collection.path(), collection.clone())
283
138
                .await?;
284
54
            collection.serve_alias_path(alias).await;
285
        }
286

            
287
24
        let session_path = session_collection.path().to_owned();
288
120
        object_server
289
54
            .at(&session_path, session_collection.clone())
290
94
            .await?;
291
52
        session_collection
292
22
            .serve_alias_path(oo7::dbus::Service::SESSION_COLLECTION)
293
60
            .await;
294

            
295
        // Spawn client disconnect handler
296
22
        let service = self.clone();
297
80
        tokio::spawn(async move { service.on_client_disconnect().await });
298

            
299
        // Spawn stale session cleanup task
300
22
        let service = self.clone();
301
80
        tokio::spawn(async move { service.cleanup_stale_sessions().await });
302

            
303
22
        Ok(())
304
    }
305

            
306
100
    pub(crate) async fn on_client_disconnect(&self) -> zbus::Result<()> {
307
56
        let rule = zbus::MatchRule::builder()
308
22
            .msg_type(zbus::message::Type::Signal)
309
            .sender("org.freedesktop.DBus")
310
            .interface("org.freedesktop.DBus")
311
            .member("NameOwnerChanged")
312
            .arg(2, "")
313
            .build()?;
314
22
        let mut stream =
315
            zbus::MessageStream::for_match_rule(rule, &self.connection(), None).await?;
316
78
        while let Some(message) = stream.try_next().await? {
317
            let body = message.body();
318
            let Ok((name, old_owner, new_owner)) =
319
                body.deserialize::<(&str, Optional<UniqueName<'_>>, Optional<UniqueName<'_>>)>()
320
            else {
321
                continue;
322
            };
323
            debug_assert!(new_owner.is_none()); // We enforce that in the matching rule
324
            let old_owner = old_owner
325
                .as_ref()
326
                .expect("A disconnected client requires an old_owner");
327
            self.handle_owner_lost(name, old_owner).await;
328
        }
329
        Ok(())
330
    }
331

            
332
16
    pub(crate) async fn handle_owner_lost(&self, name: &str, old_owner: &UniqueName<'_>) {
333
8
        if name != old_owner.as_str() {
334
8
            self.dismiss_orphaned_prompts(name).await;
335
            return;
336
        }
337
12
        if let Some(session) = self.session_from_sender(old_owner).await {
338
8
            let client_name = match session.peer_info() {
339
8
                Some(info) => format!("{old_owner} ({info})"),
340
                None => old_owner.to_string(),
341
            };
342
8
            session.mark_stale().await;
343
2
            tracing::info!(
344
                "Client {} disconnected. Session: {} marked for cleanup.",
345
                client_name,
346
                session.path()
347
            );
348
        }
349
    }
350

            
351
    /// Dismiss the prompts waiting on a prompter that left the bus.
352
16
    async fn dismiss_orphaned_prompts(&self, name: &str) {
353
        #[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))]
354
4
        let is_gnome = name
355
4
            == crate::gnome::prompter::GNOMEPrompterProxy::DESTINATION
356
4
                .as_ref()
357
4
                .map(zbus::names::BusName::as_str)
358
4
                .unwrap_or_default();
359
        #[cfg(not(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto")))]
360
        let is_gnome = false;
361
        #[cfg(any(feature = "plasma_native_crypto", feature = "plasma_openssl_crypto"))]
362
8
        let is_plasma = name
363
4
            == crate::plasma::prompter::PlasmaPrompterProxy::DESTINATION
364
4
                .as_ref()
365
4
                .map(zbus::names::BusName::as_str)
366
4
                .unwrap_or_default();
367
        #[cfg(not(any(feature = "plasma_native_crypto", feature = "plasma_openssl_crypto")))]
368
        let is_plasma = false;
369

            
370
4
        if !is_gnome && !is_plasma {
371
            return;
372
        }
373

            
374
        let orphaned: Vec<Prompt> = {
375
8
            let prompts = self.prompts.lock().await;
376
8
            prompts.values().cloned().collect()
377
        };
378

            
379
12
        for prompt in orphaned {
380
4
            tracing::warn!(
381
                "Prompter `{name}` disappeared, dismissing prompt `{}`",
382
                prompt.path()
383
            );
384
20
            if let Err(e) = self
385
                .object_server()
386
8
                .remove::<Prompt, _>(prompt.path())
387
16
                .await
388
            {
389
                tracing::debug!("Failed to remove prompt from object server: {e}");
390
            }
391
8
            self.remove_prompt(prompt.path()).await;
392
12
            if let Err(e) = prompt.emit_orphaned_completed().await {
393
                tracing::debug!("Failed to emit Completed on orphaned prompt: {e}");
394
            }
395
        }
396
    }
397

            
398
104
    pub(crate) async fn cleanup_stale_sessions(&self) {
399
52
        let mut interval = tokio::time::interval(std::time::Duration::from_secs(30));
400
        loop {
401
114
            interval.tick().await;
402
48
            self.cleanup_stale_sessions_tick().await;
403
        }
404
    }
405

            
406
    /// Close the sessions whose client has been gone for longer than the
407
    /// stale timeout.
408
90
    pub(crate) async fn cleanup_stale_sessions_tick(&self) {
409
        let stale_paths: Vec<_> = {
410
43
            let sessions = self.sessions.lock().await;
411
23
            let mut paths = Vec::new();
412
87
            for (path, session) in sessions.iter() {
413
12
                if session.is_stale().await {
414
4
                    paths.push(path.clone());
415
                }
416
            }
417
20
            paths
418
        };
419
71
        for path in stale_paths {
420
12
            if let Some(session) = self.session(&path).await {
421
12
                match session.close().await {
422
4
                    Ok(_) => tracing::info!("Stale session {} cleaned up.", path),
423
                    Err(err) => {
424
                        tracing::error!("Failed to clean up stale session {}: {}", path, err)
425
                    }
426
                }
427
            }
428
        }
429
    }
430
}