1
// org.freedesktop.Secret.Collection
2

            
3
use std::{
4
    collections::HashMap,
5
    sync::Arc,
6
    time::{Duration, SystemTime},
7
};
8

            
9
use oo7::{
10
    Secret,
11
    dbus::{
12
        ServiceError,
13
        api::{DBusSecretInner, Properties},
14
    },
15
    file::Keyring,
16
};
17
use tokio::sync::{Mutex, RwLock};
18
use wire::{ObjectPath, OwnedObjectPath};
19
use zbus::{interface, object_server::SignalEmitter, proxy::Defaults, wire};
20

            
21
use crate::{
22
    Service,
23
    error::{Error, custom_service_error},
24
    item,
25
};
26

            
27
#[derive(Clone)]
28
pub struct Collection {
29
    // Properties
30
    items: Arc<Mutex<Vec<item::Item>>>,
31
    label: Arc<Mutex<String>>,
32
    created: Duration,
33
    modified: Arc<Mutex<Duration>>,
34
    // Other attributes
35
    name: String,
36
    alias: Arc<Mutex<String>>,
37
    pub(crate) keyring: Arc<RwLock<Option<Keyring>>>,
38
    service: Service,
39
    item_index: Arc<RwLock<u32>>,
40
    path: OwnedObjectPath,
41
}
42

            
43
#[interface(name = "org.freedesktop.Secret.Collection")]
44
impl Collection {
45
    #[zbus(out_args("prompt"))]
46
8
    pub async fn delete(
47
        &self,
48
        #[zbus(header)] header: zbus::message::Header<'_>,
49
    ) -> Result<OwnedObjectPath, ServiceError> {
50
17
        let caller = if let Some(sender) = header.sender() {
51
            self.service.peer_display_name(sender).await
52
        } else {
53
17
            "unknown".to_string()
54
        };
55
        // Deleting the placeholder of a pending migration would migrate
56
        // the legacy keyring and throw the result away
57
26
        if self.service.has_pending_migration(self.name()).await {
58
8
            return Err(ServiceError::IsLocked(format!(
59
                "Collection `{}` holds a keyring awaiting migration, unlock it first.",
60
                self.path
61
            )));
62
        }
63
        // Check if collection is locked
64
31
        if self.is_locked().await {
65
            // Create a prompt to unlock and delete the collection
66
            let prompt = crate::prompt::Prompt::new(
67
14
                self.service.clone(),
68
7
                crate::prompt::PromptRole::Unlock,
69
13
                self.label().await,
70
12
                Some(self.clone()),
71
            )
72
18
            .await;
73
12
            let prompt_path = OwnedObjectPath::from(prompt.path().clone());
74

            
75
12
            let collection = self.clone();
76
6
            let service = self.service.clone();
77
6
            let caller_owned = caller;
78
22
            let action =
79
                crate::prompt::PromptAction::new(move |unlock_secret: Option<Secret>| async move {
80
                    // Unlock the collection, completing a pending migration
81
16
                    service
82
4
                        .unlock_collection(&collection, unlock_secret)
83
12
                        .await?;
84

            
85
4
                    collection.delete_unlocked(&caller_owned).await?;
86

            
87
8
                    Ok(wire::Variant::new(OwnedObjectPath::default())
88
4
                        .try_into_owned()
89
4
                        .unwrap())
90
                });
91

            
92
6
            prompt.set_action(action).await;
93

            
94
21
            self.service
95
14
                .register_prompt(prompt_path.clone(), prompt.clone())
96
13
                .await;
97

            
98
31
            self.service
99
                .object_server()
100
6
                .at(&prompt_path, prompt)
101
19
                .await?;
102

            
103
7
            tracing::debug!(
104
                "Delete prompt created at `{}` for locked collection `{}`",
105
                prompt_path,
106
                self.path
107
            );
108

            
109
7
            return Ok(prompt_path);
110
        }
111

            
112
36
        self.delete_unlocked(&caller).await?;
113
10
        Ok(OwnedObjectPath::default())
114
    }
115

            
116
50
    async fn delete_unlocked(&self, caller: &str) -> Result<(), ServiceError> {
117
        let keyring_path = {
118
20
            let keyring_guard = self.keyring.read().await;
119
20
            let keyring = match keyring_guard.as_ref() {
120
20
                Some(k) if !k.is_locked() => k.as_unlocked(),
121
                _ => return Err(ServiceError::IsLocked("Collection is locked".to_owned())),
122
            };
123
30
            keyring.path().map(|p| p.to_path_buf())
124
        };
125

            
126
20
        let object_server = self.service.object_server();
127

            
128
        // Remove all items from the object server
129
26
        let items = self.items.lock().await;
130
24
        for item in items.iter() {
131
12
            object_server.remove::<item::Item, _>(item.path()).await?;
132
        }
133
10
        drop(items);
134

            
135
        // Delete the keyring file if it's persistent
136
10
        if let Some(path) = keyring_path {
137
30
            tokio::fs::remove_file(&path).await.map_err(|err| {
138
                custom_service_error(&format!("Failed to delete keyring file: {err}"))
139
            })?;
140
10
            tracing::debug!("Deleted keyring file: {}", path.display());
141
        }
142

            
143
        // Emit CollectionDeleted signal before removing from object server
144
20
        let service_path = oo7::dbus::api::Service::PATH.as_ref().unwrap();
145
10
        let signal_emitter = self.service.signal_emitter(service_path)?;
146
26
        Service::collection_deleted(&signal_emitter, &self.path).await?;
147

            
148
        // Remove collection from object server
149
15
        object_server.remove::<Collection, _>(&self.path).await?;
150
21
        self.remove_alias_path(&self.alias().await).await;
151

            
152
        // Notify service to remove from collections list
153
14
        self.service.remove_collection(&self.path).await;
154

            
155
10
        tracing::info!("Collection `{}` deleted by {caller}.", self.path);
156

            
157
9
        Ok(())
158
    }
159

            
160
    #[zbus(out_args("results"))]
161
12
    pub async fn search_items(
162
        &self,
163
        attributes: HashMap<String, String>,
164
    ) -> Result<Vec<OwnedObjectPath>, ServiceError> {
165
51
        let results = self
166
12
            .search_inner_items(&attributes)
167
45
            .await?
168
            .iter()
169
40
            .map(|item| item.path().clone().into())
170
            .collect::<Vec<OwnedObjectPath>>();
171

            
172
14
        if results.is_empty() {
173
18
            tracing::debug!(
174
                "Items with attributes {:?} does not exist in collection: {}.",
175
                attributes,
176
                self.path
177
            );
178
        } else {
179
26
            tracing::debug!(
180
                "Items with attributes {:?} found in collection: {}.",
181
                attributes,
182
                self.path
183
            );
184
        }
185

            
186
14
        Ok(results)
187
    }
188

            
189
    #[zbus(out_args("item", "prompt"))]
190
15
    pub async fn create_item(
191
        &self,
192
        properties: Properties,
193
        secret: DBusSecretInner,
194
        replace: bool,
195
        #[zbus(header)] header: zbus::message::Header<'_>,
196
    ) -> Result<(OwnedObjectPath, OwnedObjectPath), ServiceError> {
197
30
        let caller = if let Some(sender) = header.sender() {
198
            self.service.peer_display_name(sender).await
199
        } else {
200
30
            "unknown".to_string()
201
        };
202
30
        tracing::debug!("CreateItem called by {caller} with session {}", secret.0);
203
43
        if self.is_locked().await {
204
            // Create a prompt to unlock the collection and create the item
205
            let prompt = crate::prompt::Prompt::new(
206
8
                self.service.clone(),
207
4
                crate::prompt::PromptRole::Unlock,
208
8
                self.label().await,
209
8
                Some(self.clone()),
210
            )
211
12
            .await;
212
8
            let prompt_path = OwnedObjectPath::from(prompt.path().clone());
213

            
214
8
            let collection = self.clone();
215
4
            let service = self.service.clone();
216
24
            let action =
217
                crate::prompt::PromptAction::new(move |unlock_secret: Option<Secret>| async move {
218
                    // Unlock the collection, completing a pending migration
219
16
                    service
220
4
                        .unlock_collection(&collection, unlock_secret)
221
16
                        .await?;
222

            
223
15
                    let item_path = collection
224
5
                        .create_item_unlocked(properties, secret, replace)
225
22
                        .await?;
226

            
227
11
                    Ok(wire::Variant::new(item_path).try_into_owned().unwrap())
228
                });
229

            
230
4
            prompt.set_action(action).await;
231

            
232
12
            self.service
233
9
                .register_prompt(prompt_path.clone(), prompt.clone())
234
10
                .await;
235

            
236
25
            self.service
237
                .object_server()
238
5
                .at(&prompt_path, prompt)
239
15
                .await?;
240

            
241
5
            tracing::debug!(
242
                "CreateItem prompt created at `{}` for locked collection `{}`",
243
                prompt_path,
244
                self.path
245
            );
246

            
247
12
            return Ok((OwnedObjectPath::default(), prompt_path));
248
        }
249

            
250
66
        let item_path = self
251
17
            .create_item_unlocked(properties, secret, replace)
252
74
            .await?;
253

            
254
21
        Ok((item_path, OwnedObjectPath::default()))
255
    }
256

            
257
15
    async fn create_item_unlocked(
258
        &self,
259
        properties: Properties,
260
        secret: DBusSecretInner,
261
        replace: bool,
262
    ) -> Result<OwnedObjectPath, ServiceError> {
263
32
        let keyring_guard = self.keyring.read().await;
264
32
        let keyring = match keyring_guard.as_ref() {
265
32
            Some(k) if !k.is_locked() => k.as_unlocked(),
266
            _ => return Err(ServiceError::IsLocked("Collection is locked".to_owned())),
267
        };
268

            
269
16
        let DBusSecretInner(ref session_path, ref iv, ref secret_bytes, ref content_type) = secret;
270
16
        let label = properties.label();
271
        // Safe to unwrap as an item always has attributes
272
20
        let mut attributes = properties.attributes().unwrap().to_owned();
273

            
274
43
        let Some(session) = self.service.session(session_path).await else {
275
8
            tracing::error!(
276
                "The session `{}` does not exist, referenced while creating item in collection `{}`.",
277
                session_path,
278
                self.path
279
            );
280
8
            return Err(ServiceError::NoSession(format!(
281
                "The session `{session_path}` does not exist."
282
            )));
283
        };
284

            
285
32
        let secret = match session.aes_key() {
286
39
            Some(key) => oo7::crypto::decrypt(secret_bytes, &key, iv)
287
26
                .map_err(|err| custom_service_error(&format!("Failed to decrypt secret {err}.")))?,
288
11
            None => zeroize::Zeroizing::new(secret_bytes.clone()),
289
        };
290

            
291
        // Ensure content-type attribute is stored
292
32
        if !attributes.contains_key(oo7::CONTENT_TYPE_ATTRIBUTE) {
293
31
            attributes.insert(
294
31
                oo7::CONTENT_TYPE_ATTRIBUTE.to_owned(),
295
33
                content_type.as_str().to_owned(),
296
            );
297
        }
298

            
299
80
        let key = keyring
300
            .key()
301
61
            .await
302
16
            .map_err(|err| custom_service_error(&format!("Failed to derive key: {err}")))?;
303

            
304
        // When replacing, find existing items that match so we can update the
305
        // first one in place, keeping its D-Bus object path valid for any
306
        // concurrent GetSecret callers.
307
39
        let existing_items = if replace {
308
57
            let items = self
309
30
                .search_items_with_key(&attributes, key.as_deref(), true)
310
60
                .await?;
311
31
            if items.is_empty() { None } else { Some(items) }
312
        } else {
313
9
            None
314
        };
315

            
316
97
        let new_file_item = keyring
317
37
            .create_item(label, &attributes, secret, existing_items.is_some())
318
69
            .await
319
17
            .map_err(|err| custom_service_error(&format!("Failed to create a new item {err}.")))?;
320
17
        drop(keyring_guard);
321

            
322
18
        let signal_emitter = self.service.signal_emitter(&self.path)?;
323
35
        let object_server = self.service.object_server();
324

            
325
34
        let item_path = if let Some(existing_items) = existing_items {
326
12
            let kept = &existing_items[0];
327
6
            let kept_path: OwnedObjectPath = kept.path().to_owned().into();
328
8
            *kept.inner.lock().await = Some(new_file_item.into());
329

            
330
            // Remove any duplicate matches beyond the first.
331
6
            if existing_items.len() > 1 {
332
4
                let mut items = self.items.lock().await;
333
12
                for dup in &existing_items[1..] {
334
8
                    let dup_path = dup.path();
335
12
                    items.retain(|i| i.path() != dup_path);
336
8
                    object_server.remove::<item::Item, _>(dup_path).await?;
337
8
                    Self::item_deleted(&signal_emitter, dup_path).await?;
338
                }
339
            }
340

            
341
14
            Self::item_changed(&signal_emitter, &kept_path).await?;
342
6
            kept_path
343
        } else {
344
50
            let n_items = *self.item_index.read().await;
345
18
            let new_path = OwnedObjectPath::try_from(format!("{}/{n_items}", self.path)).unwrap();
346

            
347
            let item = item::Item::new(
348
34
                new_file_item.into(),
349
34
                self.service.clone(),
350
34
                self.path.clone(),
351
17
                new_path.clone(),
352
            );
353
48
            *self.item_index.write().await = n_items + 1;
354

            
355
32
            self.items.lock().await.push(item.clone());
356
32
            object_server.at(&new_path, item).await?;
357

            
358
30
            Self::item_created(&signal_emitter, &new_path).await?;
359
18
            new_path
360
        };
361

            
362
48
        self.update_modified().await?;
363
30
        self.items_changed(&signal_emitter).await?;
364

            
365
20
        match session.peer_info() {
366
34
            Some(info) => tracing::info!(
367
                "Item `{item_path}` created by {} ({info}).",
368
                session.sender()
369
            ),
370
            None => tracing::info!("Item `{item_path}` created by {}.", session.sender()),
371
        }
372

            
373
21
        Ok(item_path)
374
    }
375

            
376
    #[zbus(property, name = "Items")]
377
104
    pub async fn items(&self) -> Vec<OwnedObjectPath> {
378
128
        self.items
379
            .lock()
380
96
            .await
381
            .iter()
382
65
            .map(|i| i.path().to_owned().into())
383
            .collect()
384
    }
385

            
386
    #[zbus(property, name = "Label")]
387
40
    pub async fn label(&self) -> String {
388
26
        self.label.lock().await.clone()
389
    }
390

            
391
    #[zbus(property, name = "Label")]
392
40
    pub async fn set_label(&self, label: &str) -> Result<(), ServiceError> {
393
20
        if self.is_locked().await {
394
8
            return Err(ServiceError::IsLocked(format!(
395
                "Collection `{}` is locked.",
396
                self.path
397
            )));
398
        }
399

            
400
        let old_label = {
401
20
            let mut guard = self.label.lock().await;
402
16
            let old = guard.clone();
403
8
            *guard = label.to_owned();
404
8
            old
405
        };
406
16
        tracing::info!(
407
            "Collection `{}` label changed from \"{}\" to \"{}\".",
408
            self.path,
409
            old_label,
410
            label
411
        );
412

            
413
20
        self.update_modified().await?;
414

            
415
12
        let service_path = oo7::dbus::api::Service::PATH.as_ref().unwrap();
416
8
        let signal_emitter = self.service.signal_emitter(service_path)?;
417
20
        Service::collection_changed(&signal_emitter, &self.path).await?;
418

            
419
8
        let signal_emitter = self.service.signal_emitter(&self.path)?;
420
20
        self.label_changed(&signal_emitter).await?;
421

            
422
8
        Ok(())
423
    }
424

            
425
    #[zbus(property, name = "Locked")]
426
72
    pub async fn is_locked(&self) -> bool {
427
69
        self.keyring
428
            .read()
429
57
            .await
430
            .as_ref()
431
58
            .map(|k| k.is_locked())
432
            .unwrap_or(true)
433
    }
434

            
435
    #[zbus(property, name = "Created")]
436
11
    pub fn created_at(&self) -> u64 {
437
11
        self.created.as_secs()
438
    }
439

            
440
    #[zbus(property, name = "Modified")]
441
80
    pub async fn modified_at(&self) -> u64 {
442
59
        self.modified.lock().await.as_secs()
443
    }
444

            
445
    #[zbus(signal, name = "ItemCreated")]
446
    async fn item_created(
447
17
        signal_emitter: &SignalEmitter<'_>,
448
17
        item: &ObjectPath<'_>,
449
    ) -> zbus::Result<()>;
450

            
451
    #[zbus(signal, name = "ItemDeleted")]
452
    pub async fn item_deleted(
453
13
        signal_emitter: &SignalEmitter<'_>,
454
14
        item: &ObjectPath<'_>,
455
    ) -> zbus::Result<()>;
456

            
457
    #[zbus(signal, name = "ItemChanged")]
458
    pub async fn item_changed(
459
11
        signal_emitter: &SignalEmitter<'_>,
460
11
        item: &ObjectPath<'_>,
461
    ) -> zbus::Result<()>;
462
}
463

            
464
30
pub(crate) fn alias_path(alias: &str) -> Option<OwnedObjectPath> {
465
24
    OwnedObjectPath::try_from(format!("/org/freedesktop/secrets/aliases/{alias}")).ok()
466
}
467

            
468
37
pub(crate) fn collection_path(label: &str) -> Result<OwnedObjectPath, wire::Error> {
469
37
    let mut sanitized_label = label
470
        .to_lowercase()
471
74
        .replace(|c: char| !c.is_ascii_alphanumeric() && c != '_', "_");
472
41
    if sanitized_label.is_empty() {
473
        // An empty label would produce a path with a trailing slash
474
4
        sanitized_label = "_".to_owned();
475
    }
476

            
477
74
    OwnedObjectPath::try_from(format!(
478
        "/org/freedesktop/secrets/collection/{sanitized_label}"
479
    ))
480
}
481

            
482
impl Collection {
483
35
    pub async fn new(
484
        name: &str,
485
        label: &str,
486
        alias: &str,
487
        service: Service,
488
        keyring: Keyring,
489
    ) -> Self {
490
95
        let modified = keyring.modified_time().await;
491
69
        let created = keyring.created_time().await.unwrap_or(modified);
492

            
493
        Self {
494
31
            items: Default::default(),
495
62
            label: Arc::new(Mutex::new(label.to_owned())),
496
66
            modified: Arc::new(Mutex::new(modified)),
497
33
            name: name.to_owned(),
498
66
            alias: Arc::new(Mutex::new(alias.to_owned())),
499
65
            item_index: Arc::new(RwLock::new(0)),
500
34
            path: collection_path(label)
501
                .expect("Label should already be sanitized and produce valid object path"),
502
            created,
503
            service,
504
66
            keyring: Arc::new(RwLock::new(Some(keyring))),
505
        }
506
    }
507

            
508
32
    pub fn path(&self) -> &ObjectPath<'_> {
509
30
        &self.path
510
    }
511

            
512
32
    pub fn name(&self) -> &str {
513
30
        &self.name
514
    }
515

            
516
16
    pub async fn set_alias(&self, alias: &str) {
517
8
        let old_alias = std::mem::replace(&mut *self.alias.lock().await, alias.to_owned());
518
4
        self.remove_alias_path(&old_alias).await;
519
4
        self.serve_alias_path(alias).await;
520
    }
521

            
522
    /// Serve this collection at the path of `alias`, in place of the
523
    /// collection served there before
524
108
    pub async fn serve_alias_path(&self, alias: &str) {
525
54
        let Some(path) = alias_path(alias) else {
526
            return;
527
        };
528
54
        let object_server = self.service.object_server();
529
70
        let _ = object_server.remove::<Collection, _>(&path).await;
530
74
        if let Err(err) = object_server.at(&path, self.clone()).await {
531
            tracing::warn!(
532
                "Failed to serve collection `{}` at `{path}`: {err}",
533
                self.path
534
            );
535
        }
536
    }
537

            
538
    /// Stop serving this collection at the path of `alias`
539
36
    async fn remove_alias_path(&self, alias: &str) {
540
18
        let Some(path) = alias_path(alias) else {
541
            return;
542
        };
543
8
        let object_server = self.service.object_server();
544
8
        let serves_self = match object_server.interface::<_, Collection>(&path).await {
545
4
            Ok(collection) => collection.get().await.path == self.path,
546
            Err(_) => false,
547
        };
548
8
        if serves_self {
549
8
            let _ = object_server.remove::<Collection, _>(&path).await;
550
        }
551
    }
552

            
553
95
    pub async fn alias(&self) -> String {
554
64
        self.alias.lock().await.clone()
555
    }
556

            
557
12
    pub async fn search_inner_items(
558
        &self,
559
        attributes: &HashMap<String, String>,
560
    ) -> Result<Vec<item::Item>, ServiceError> {
561
24
        let keyring_guard = self.keyring.read().await;
562
24
        let Some(keyring) = keyring_guard.as_ref() else {
563
            return Ok(Vec::new());
564
        };
565
24
        if keyring.is_locked() {
566
4
            drop(keyring_guard);
567

            
568
            // The placeholder items of a pending migration store their
569
            // attribute values as MD5 digests; hash the searched values
570
            // to match them. The generic schema fallback is compared
571
            // as-is.
572
8
            let hashed: HashMap<String, String> = attributes
573
                .iter()
574
12
                .map(|(key, value)| {
575
4
                    if key.as_str() == oo7::XDG_SCHEMA_ATTRIBUTE
576
4
                        && value.as_str() == oo7::GENERIC_SCHEMA
577
                    {
578
                        (key.clone(), value.clone())
579
                    } else {
580
4
                        (key.clone(), oo7::crypto::md5_hex(value))
581
                    }
582
                })
583
                .collect();
584
8
            return self.search_items_with_key(&hashed, None, false).await;
585
        }
586
50
        let key = keyring
587
            .as_unlocked()
588
            .key()
589
49
            .await
590
12
            .map_err(|err| custom_service_error(&format!("Failed to derive key: {err}")))?;
591
12
        drop(keyring_guard);
592

            
593
38
        self.search_items_with_key(attributes, key.as_deref(), false)
594
46
            .await
595
    }
596

            
597
16
    async fn search_items_with_key(
598
        &self,
599
        attributes: &HashMap<String, String>,
600
        key: Option<&oo7::Key>,
601
        exact: bool,
602
    ) -> Result<Vec<item::Item>, ServiceError> {
603
18
        let mut matching_items = Vec::new();
604
46
        let items = self.items.lock().await;
605

            
606
68
        for item_wrapper in items.iter() {
607
36
            let inner = item_wrapper.inner.lock().await;
608
20
            let Some(file_item) = inner.as_ref() else {
609
                continue;
610
            };
611

            
612
10
            let matches = if exact {
613
16
                file_item.matches_attributes_exact(attributes, key)
614
            } else {
615
25
                file_item.matches_attributes(attributes, key)
616
            };
617
10
            if matches {
618
13
                matching_items.push(item_wrapper.clone());
619
            }
620
        }
621

            
622
18
        Ok(matching_items)
623
    }
624

            
625
60
    pub async fn item_from_path(&self, path: &ObjectPath<'_>) -> Option<item::Item> {
626
41
        let items = self.items.lock().await;
627

            
628
60
        items.iter().find(|i| i.path() == path).cloned()
629
    }
630

            
631
10
    pub async fn set_locked(
632
        &self,
633
        locked: bool,
634
        secret: Option<Secret>,
635
    ) -> Result<(), ServiceError> {
636
20
        let mut keyring_guard = self.keyring.write().await;
637

            
638
29
        if let Some(keyring) = keyring_guard.as_ref()
639
18
            && keyring.is_locked() != locked
640
        {
641
9
            let unlocked = match keyring {
642
                Keyring::Locked(keyring) => Some(
643
24
                    if let Some(secret) = secret {
644
16
                        keyring.try_unlock(secret).await
645
                    } else {
646
8
                        keyring.try_unlock_unencrypted().await
647
                    }
648
12
                    .map_err(|err| {
649
8
                        custom_service_error(&format!("Failed to unlock keyring: {err}"))
650
                    })?,
651
                ),
652
9
                Keyring::Unlocked(_) => None,
653
            };
654
37
            let item_keyring = unlocked.as_ref().unwrap_or_else(|| keyring.as_unlocked());
655
15
            let items = self.items.lock().await;
656
22
            let mut changes = Vec::with_capacity(items.len());
657
44
            for item in items.iter() {
658
20
                if let Some(change) = item.prepare_lock_state(locked, item_keyring).await? {
659
6
                    changes.push(change);
660
                }
661
            }
662

            
663
            // All conversions succeeded. Commit the keyring and cached items
664
            // before emitting any lock-state notifications.
665
11
            if let Some(unlocked) = unlocked {
666
8
                *keyring_guard = Some(Keyring::Unlocked(unlocked));
667
44
            } else if let Some(Keyring::Unlocked(keyring)) = keyring_guard.take() {
668
22
                *keyring_guard = Some(Keyring::Locked(keyring.lock()));
669
            }
670
33
            for (mut current, next) in changes {
671
6
                *current = Some(next);
672
            }
673
17
            for item in items.iter() {
674
20
                item.notify_lock_state(locked).await?;
675
            }
676
        }
677

            
678
11
        drop(keyring_guard);
679

            
680
        // Emit signals
681
11
        let signal_emitter = self.service.signal_emitter(&self.path)?;
682
25
        self.locked_changed(&signal_emitter).await?;
683

            
684
16
        let service_path = oo7::dbus::api::Service::PATH.as_ref().unwrap();
685
10
        let signal_emitter = self.service.signal_emitter(service_path)?;
686
24
        Service::collection_changed(&signal_emitter, &self.path).await?;
687

            
688
5
        tracing::debug!(
689
            "Collection: {} is {}.",
690
            self.path,
691
            if locked { "locked" } else { "unlocked" }
692
        );
693

            
694
11
        Ok(())
695
    }
696

            
697
160
    pub async fn dispatch_items(&self) -> Result<(), Error> {
698
        let keyring_items = {
699
67
            let keyring_guard = self.keyring.read().await;
700
74
            let keyring = keyring_guard.as_ref().unwrap();
701
85
            keyring.items().await?
702
        };
703
40
        self.dispatch_file_items(keyring_items).await
704
    }
705

            
706
    /// Register the given file items on the object server and notify
707
    /// clients.
708
28
    pub async fn dispatch_file_items(
709
        &self,
710
        keyring_items: Vec<oo7::file::Item>,
711
    ) -> Result<(), Error> {
712
19
        tracing::debug!(
713
            "Dispatching {} items for collection `{}`.",
714
            keyring_items.len(),
715
            self.path
716
        );
717

            
718
28
        let mut dispatched_items = Vec::new();
719
        {
720
66
            let mut items = self.items.lock().await;
721
56
            let object_server = self.service.object_server();
722
23
            let mut n_items = 1;
723

            
724
83
            for keyring_item in keyring_items {
725
8
                let item_path =
726
                    OwnedObjectPath::try_from(format!("{}/{n_items}", self.path)).unwrap();
727
                let item = item::Item::new(
728
4
                    keyring_item,
729
8
                    self.service.clone(),
730
8
                    self.path.clone(),
731
4
                    item_path.clone(),
732
                );
733
4
                n_items += 1;
734

            
735
8
                items.push(item.clone());
736
4
                dispatched_items.push(item.clone());
737
12
                object_server.at(item_path, item).await?;
738
            }
739

            
740
44
            *self.item_index.write().await = n_items;
741
        }
742

            
743
        // Notify clients about the newly dispatched items.
744
24
        let signal_emitter = self.service.signal_emitter(&self.path)?;
745
56
        for item in &dispatched_items {
746
12
            Self::item_created(&signal_emitter, item.path()).await?;
747
        }
748
44
        self.items_changed(&signal_emitter).await?;
749

            
750
24
        Ok(())
751
    }
752

            
753
    /// Remove all items from the object server and the collection.
754
16
    async fn clear_items(&self) -> Result<(), Error> {
755
8
        let mut items = self.items.lock().await;
756
8
        let object_server = self.service.object_server();
757
12
        for item in items.iter() {
758
12
            object_server.remove::<item::Item, _>(item.path()).await?;
759
        }
760
4
        items.clear();
761
4
        Ok(())
762
    }
763

            
764
    /// Replace the keyring with a just-migrated one, dispatch its items
765
    /// and emit the corresponding change signals.
766
20
    pub async fn apply_migrated_keyring(&self, keyring: Keyring) -> Result<(), Error> {
767
4
        *self.keyring.write().await = Some(keyring);
768

            
769
        // Drop the placeholder items, the migrated items take their paths
770
4
        self.clear_items().await?;
771
8
        self.dispatch_items().await?;
772

            
773
        // The keyring swap bypasses set_locked, so emit Locked here.
774
4
        let signal_emitter = self.service.signal_emitter(&self.path)?;
775
8
        self.locked_changed(&signal_emitter).await?;
776

            
777
8
        let service_path = oo7::dbus::api::Service::PATH.as_ref().unwrap();
778
4
        let signal_emitter = self.service.signal_emitter(service_path)?;
779
8
        Service::collection_changed(&signal_emitter, &self.path).await?;
780

            
781
4
        Ok(())
782
    }
783

            
784
64
    pub async fn delete_item(&self, path: &ObjectPath<'_>) -> Result<(), ServiceError> {
785
30
        tracing::debug!("Deleting item `{}` from collection `{}`.", path, self.path);
786
41
        let Some(item) = self.item_from_path(path).await else {
787
            return Err(ServiceError::NoSuchObject(format!(
788
                "Item `{path}` does not exist."
789
            )));
790
        };
791

            
792
41
        if item.is_locked().await {
793
            return Err(ServiceError::IsLocked(format!(
794
                "Cannot delete a locked item `{path}`"
795
            )));
796
        }
797

            
798
41
        let attributes = item.attributes().await.map_err(|err| {
799
            custom_service_error(&format!("Failed to read item attributes {err}"))
800
        })?;
801

            
802
30
        let keyring_guard = self.keyring.read().await;
803
30
        let keyring = match keyring_guard.as_ref() {
804
32
            Some(k) if !k.is_locked() => k.as_unlocked(),
805
            _ => {
806
                return Err(ServiceError::IsLocked(format!(
807
                    "Cannot delete an item `{path}` in a locked collection"
808
                )));
809
            }
810
        };
811

            
812
64
        keyring
813
16
            .delete(&attributes)
814
68
            .await
815
15
            .map_err(|err| custom_service_error(&format!("Failed to deleted item {err}.")))?;
816

            
817
40
        let mut items = self.items.lock().await;
818
58
        items.retain(|item| item.path() != path);
819
14
        drop(items);
820

            
821
25
        self.update_modified().await?;
822

            
823
15
        let signal_emitter = self.service.signal_emitter(&self.path)?;
824
39
        self.items_changed(&signal_emitter).await?;
825

            
826
15
        Ok(())
827
    }
828

            
829
    /// Update the modified timestamp and emit the PropertiesChanged signal
830
76
    async fn update_modified(&self) -> Result<(), ServiceError> {
831
57
        let now = SystemTime::now()
832
19
            .duration_since(SystemTime::UNIX_EPOCH)
833
            .unwrap();
834
34
        *self.modified.lock().await = now;
835

            
836
19
        let signal_emitter = self.service.signal_emitter(&self.path)?;
837
53
        self.modified_changed(&signal_emitter).await?;
838

            
839
21
        Ok(())
840
    }
841
}
842

            
843
#[cfg(test)]
844
mod tests;