Skip to main content

lb_rs/service/
import_export.rs

1//! Import plans what bringing folders and files in would do, then writes exactly that plan.
2//! Export copies Lockbook files out to disk.
3use crate::io::docs::LocalDocuments;
4
5use crate::Lb;
6use crate::io::server::Server;
7use crate::model::ValidationFailure;
8use crate::model::api::METADATA_FEE;
9use crate::model::crypto::AESKey;
10use crate::model::errors::{LbErr, LbErrKind, LbResult};
11use crate::model::file::File;
12use crate::model::file_like::FileLike;
13use crate::model::file_metadata::FileType;
14use crate::model::symkey;
15use crate::model::tree_like::TreeLike;
16use crate::service::documents::{compress_encrypt_document, document_hmac};
17use crate::service::events::Actor;
18use futures::StreamExt;
19use futures::stream::FuturesUnordered;
20use std::collections::hash_map::Entry as Slot;
21use std::collections::{HashMap, HashSet};
22use std::fs::{self, Metadata, OpenOptions};
23use std::io::Write;
24use std::path::{Path, PathBuf};
25use tokio::sync::Semaphore;
26use uuid::Uuid;
27
28// File descriptors are process-wide. Share the limit across nested folders and
29// simultaneous exports, and only acquire permits for documents (never parents).
30static EXPORT_DOCUMENTS: Semaphore = Semaphore::const_new(16);
31
32pub enum ImportStatus {
33    CalculatedTotal(usize),
34    StartingItem(String),
35    FinishedItem(File),
36}
37
38/// What an import does with a file or folder already under the destination by the same name.
39#[derive(Clone, Copy, Debug, PartialEq, Eq)]
40pub enum Existing {
41    /// Leave it alone and bring the import in beside it, named `name-1`.
42    Copy,
43    /// Merge into it: replace documents whose contents differ and keep the rest. Only for an
44    /// import whose plan someone saw and went ahead with.
45    Update,
46}
47
48/// What importing some folders and files would do, decided before anything is written.
49#[derive(Clone, Debug)]
50pub struct ImportPlan {
51    pub dest: Uuid,
52    /// Depth-first: every folder comes before what's inside it.
53    pub entries: Vec<Entry>,
54}
55
56#[derive(Clone, Debug)]
57pub struct Entry {
58    pub disk_path: PathBuf,
59    pub file_type: EntryType,
60    pub action: Action,
61    /// Skipped by the user's choice. `action` stays as the walk found it, so changing the
62    /// choice doesn't re-scan files.
63    pub skip: bool,
64}
65
66#[derive(Clone, Copy, Debug, PartialEq, Eq)]
67pub enum EntryType {
68    Folder,
69    /// Its size on disk, its size once compressed and encrypted, and how much writing it grows
70    /// the account's usage: a new document's stored bytes and file fee, or what a replaced one
71    /// grows by.
72    Document {
73        disk_bytes: u64,
74        stored_bytes: u64,
75        added_bytes: u64,
76    },
77}
78
79#[derive(Clone, Copy, Debug, PartialEq, Eq)]
80pub enum Action {
81    Create,
82    Replace(Uuid),
83    /// Already in Lockbook: a document with the same contents, or a folder that exists.
84    Noop(Uuid),
85    Ignore(IgnoreReason),
86}
87
88#[derive(Clone, Copy, Debug, PartialEq, Eq)]
89pub enum IgnoreReason {
90    /// What a file browser hides: a name starting with a dot, or the system's hidden mark.
91    Hidden,
92    Unreadable,
93    /// A symbolic link, pipe, socket or device.
94    NotAFile,
95}
96
97/// A count of documents and how much they grow the account's usage.
98#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
99pub struct DocTotals {
100    pub files: usize,
101    pub added_bytes: u64,
102}
103
104impl DocTotals {
105    fn add(&mut self, added_bytes: u64) {
106        self.files += 1;
107        self.added_bytes += added_bytes;
108    }
109}
110
111/// An import plan's totals.
112#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
113pub struct ImportSummary {
114    pub new: usize,
115    pub changed: usize,
116    /// Documents already here with the same contents.
117    pub same: usize,
118    /// The written documents' size on disk.
119    pub disk_bytes: u64,
120    /// What the writes take up once stored, file fees included: a replaced document counts whole.
121    pub stored_bytes: u64,
122    /// How much the writes grow the account's usage.
123    pub added_bytes: u64,
124    pub skipped: DocTotals,
125    pub hidden: usize,
126    pub unreadable: usize,
127    pub not_a_file: usize,
128}
129
130impl Entry {
131    pub fn name(&self) -> String {
132        self.disk_path
133            .file_name()
134            .map(|n| n.to_string_lossy().into_owned())
135            .unwrap_or_default()
136    }
137
138    /// The import creates this folder, or creates or replaces this document.
139    pub fn writes(&self) -> bool {
140        matches!(self.action, Action::Create | Action::Replace(_)) && !self.skip
141    }
142}
143
144impl<S: Server, D: LocalDocuments> Lb<S, D> {
145    /// Creates a folder, or a document holding `content` from the transaction that creates it.
146    /// When `name` is taken, it becomes `name-1`, `name-2` and so on until one is free.
147    /// It never writes over anything; replacing a document is [`Action::Replace`]'s job.
148    async fn create_imported(
149        &self, name: &str, parent: Uuid, content: Option<&[u8]>,
150    ) -> LbResult<File> {
151        let id = self.entropy.id();
152        let key = self.entropy.key();
153        let document = match content {
154            Some(content) => {
155                let (hmac, encrypted) = compress_encrypt_document(&key, content)?;
156                let pending = self.docs.insert_pending(id, hmac, &encrypted).await?;
157                Some((pending, hmac, encrypted.value.len()))
158            }
159            None => None,
160        };
161        let file_type = if document.is_some() { FileType::Document } else { FileType::Folder };
162
163        let mut tx = self.begin_tx().await;
164        let db = tx.db();
165        let mut tree = (&db.base_metadata)
166            .to_staged(&mut db.local_metadata)
167            .to_lazy();
168        let content = match document {
169            Some((pending, hmac, size)) => {
170                pending.promote().await?;
171                Some((hmac, size))
172            }
173            None => None,
174        };
175        let mut free_name = name.to_string();
176        for tries in 1.. {
177            match tree.create(id, key, &parent, &free_name, file_type, &self.keychain) {
178                Err(err)
179                    if matches!(
180                        err.kind,
181                        LbErrKind::Validation(ValidationFailure::PathConflict(_))
182                    ) =>
183                {
184                    free_name = format!("{name}-{tries}");
185                }
186                result => {
187                    result?;
188                    break;
189                }
190            }
191        }
192        if let Some((hmac, size)) = content {
193            tree.overwrite_document_hmac(&id, Some(hmac), Some(size), &self.keychain)?;
194        }
195        let file = tree.decrypt(&self.keychain, &id, &db.pub_key_lookup)?;
196        tx.end();
197
198        self.events.meta_changed(Actor::User(None));
199        if content.is_some() {
200            self.events.doc_written(id, Actor::User(None));
201        }
202        Ok(file)
203    }
204
205    /// Whether document `id` holds `content`, judged from its metadata so nothing is fetched.
206    async fn holds(&self, id: Uuid, content: &[u8]) -> LbResult<bool> {
207        let (hmac, key) = {
208            let tx = self.ro_tx().await;
209            let db = tx.db();
210            let mut tree = (&db.base_metadata).to_staged(&db.local_metadata).to_lazy();
211            let hmac = tree.find(&id)?.document_hmac().copied();
212            (hmac, tree.decrypt_key(&id, &self.keychain)?)
213        };
214        Ok(match hmac {
215            Some(hmac) => document_hmac(&key, content)? == hmac,
216            None => content.is_empty(),
217        })
218    }
219}
220
221/// What the server counts for a document holding `data`: compressed, then encrypted. Exact for
222/// any key, since compression comes first and the nonce and tag have fixed lengths.
223fn stored_size(key: &AESKey, data: &[u8]) -> LbResult<u64> {
224    Ok(compress_encrypt_document(key, data)?.1.value.len() as u64)
225}
226
227/// What a file browser hides: a name starting with a dot, or the system's hidden mark.
228fn hidden(name: &str, meta: &Metadata) -> bool {
229    if name.starts_with('.') {
230        return true;
231    }
232    #[cfg(target_os = "macos")]
233    {
234        use std::os::macos::fs::MetadataExt;
235        const UF_HIDDEN: u32 = 0x8000;
236        meta.st_flags() & UF_HIDDEN != 0
237    }
238    #[cfg(target_os = "ios")]
239    {
240        use std::os::ios::fs::MetadataExt;
241        const UF_HIDDEN: u32 = 0x8000;
242        meta.st_flags() & UF_HIDDEN != 0
243    }
244    #[cfg(windows)]
245    {
246        use std::os::windows::fs::MetadataExt;
247        const FILE_ATTRIBUTE_HIDDEN: u32 = 0x2;
248        meta.file_attributes() & FILE_ATTRIBUTE_HIDDEN != 0
249    }
250    #[cfg(not(any(target_os = "macos", target_os = "ios", windows)))]
251    {
252        let _ = meta;
253        false
254    }
255}
256
257impl<S: Server, D: LocalDocuments> Lb<S, D> {
258    /// `parent` is the Lockbook folder `disk_path` would land in, when that folder exists.
259    async fn plan_entry(
260        &self, disk_path: &Path, parent: Option<Uuid>, top: bool, key: &AESKey,
261        children: &mut HashMap<Uuid, Vec<File>>,
262    ) -> LbResult<(EntryType, Action)> {
263        let unread = EntryType::Document { disk_bytes: 0, stored_bytes: 0, added_bytes: 0 };
264
265        // 1. Look at the entry itself. Links are never followed, so the walk stays inside what
266        //    was picked.
267        let Ok(meta) = fs::symlink_metadata(disk_path) else {
268            return Ok((unread, Action::Ignore(IgnoreReason::Unreadable)));
269        };
270        let file_type = if meta.is_dir() { EntryType::Folder } else { unread };
271        let Some(name) = disk_path.file_name().and_then(|n| n.to_str()) else {
272            return Ok((file_type, Action::Ignore(IgnoreReason::Unreadable)));
273        };
274
275        // 2. Leave out what a file browser hides, unless it was picked by name.
276        if !top && hidden(name, &meta) {
277            return Ok((file_type, Action::Ignore(IgnoreReason::Hidden)));
278        }
279
280        // 3. Find what's already in Lockbook by this name, listing each folder only once.
281        let existing = match parent {
282            Some(parent) => {
283                let listed = match children.entry(parent) {
284                    Slot::Occupied(listed) => listed.into_mut(),
285                    Slot::Vacant(slot) => slot.insert(self.all_children(&parent).await?),
286                };
287                listed.iter().find(|f| f.name == name).cloned()
288            }
289            None => None,
290        };
291
292        // 4. A folder merges into the folder already there, or is created.
293        if meta.is_dir() {
294            let action = match existing.filter(|f| f.is_folder()) {
295                Some(f) => Action::Noop(f.id),
296                None => Action::Create,
297            };
298            return Ok((file_type, action));
299        }
300
301        // 5. Of everything else, only regular files that can be read come in.
302        if !meta.is_file() {
303            return Ok((file_type, Action::Ignore(IgnoreReason::NotAFile)));
304        }
305        let Ok(data) = fs::read(disk_path) else {
306            return Ok((file_type, Action::Ignore(IgnoreReason::Unreadable)));
307        };
308        let disk_bytes = data.len() as u64;
309        let existing = existing.filter(|f| f.is_document());
310        // `size_bytes` counts the file fee on top of the stored document.
311        let held = |f: &File| f.size_bytes.saturating_sub(METADATA_FEE);
312
313        // 6. A document with the same contents is already here and costs nothing.
314        if let Some(f) = &existing {
315            if self.holds(f.id, &data).await? {
316                let (stored_bytes, added_bytes) = (held(f), 0);
317                return Ok((
318                    EntryType::Document { disk_bytes, stored_bytes, added_bytes },
319                    Action::Noop(f.id),
320                ));
321            }
322        }
323
324        // 7. Otherwise a replacement grows usage by the difference, and a new document by its
325        //    whole stored size plus the file fee.
326        let stored_bytes = stored_size(key, &data)?;
327        Ok(match existing {
328            Some(f) => {
329                let added_bytes = stored_bytes.saturating_sub(held(&f));
330                (
331                    EntryType::Document { disk_bytes, stored_bytes, added_bytes },
332                    Action::Replace(f.id),
333                )
334            }
335            None => {
336                let added_bytes = stored_bytes + METADATA_FEE;
337                (EntryType::Document { disk_bytes, stored_bytes, added_bytes }, Action::Create)
338            }
339        })
340    }
341
342    /// Walks `sources` and, for [`Existing::Update`], compares each file with what's already
343    /// under `dest`, writing nothing.
344    #[instrument(level = "debug", skip(self), err(Debug))]
345    pub async fn plan_import(
346        &self, sources: &[PathBuf], dest: Uuid, existing: Existing,
347    ) -> LbResult<ImportPlan> {
348        // 1. The destination must be a folder.
349        let parent = self.get_file_by_id(dest).await?;
350        if !parent.is_folder() {
351            Err(LbErrKind::Validation(ValidationFailure::NonFolderWithChildren(dest)))?;
352        }
353
354        // 2. One throwaway key measures every document.
355        let key = symkey::generate_key();
356        let mut children = HashMap::new();
357        let mut entries = Vec::new();
358
359        // 3. Start from the picked sources, dropping any inside another, since it's already part
360        //    of it. Only an update compares against `dest`; a copy matches nothing and creates
361        //    everything.
362        let mut stack: Vec<(PathBuf, Option<Uuid>, bool)> = sources
363            .iter()
364            .rev()
365            .filter(|s| !sources.iter().any(|o| o != *s && s.starts_with(o)))
366            .map(|s| (s.clone(), (existing == Existing::Update).then_some(dest), true))
367            .collect();
368
369        // 4. Plan each entry, then queue a folder's contents to come right after it, in name
370        //    order. They're compared against the Lockbook folder only when it already exists.
371        while let Some((disk_path, parent, top)) = stack.pop() {
372            let (file_type, mut action) = self
373                .plan_entry(&disk_path, parent, top, &key, &mut children)
374                .await?;
375            if file_type == EntryType::Folder && !matches!(action, Action::Ignore(_)) {
376                let listed: std::io::Result<Vec<PathBuf>> = fs::read_dir(&disk_path)
377                    .and_then(|dir| dir.map(|child| Ok(child?.path())).collect());
378                match listed {
379                    Ok(mut inside) => {
380                        let here = match action {
381                            Action::Noop(id) => Some(id),
382                            _ => None,
383                        };
384                        inside.sort();
385                        stack.extend(inside.into_iter().rev().map(|c| (c, here, false)));
386                    }
387                    // A folder that can't be listed can't be imported.
388                    Err(_) => action = Action::Ignore(IgnoreReason::Unreadable),
389                }
390            }
391            entries.push(Entry { disk_path, file_type, action, skip: false });
392        }
393        Ok(ImportPlan { dest, entries })
394    }
395}
396
397impl ImportPlan {
398    /// The plan's totals, counted from its entries.
399    pub fn summary(&self) -> ImportSummary {
400        let mut s = ImportSummary::default();
401        for e in &self.entries {
402            match (e.action, e.file_type) {
403                (Action::Ignore(IgnoreReason::Hidden), _) => s.hidden += 1,
404                (Action::Ignore(IgnoreReason::Unreadable), _) => s.unreadable += 1,
405                (Action::Ignore(IgnoreReason::NotAFile), _) => s.not_a_file += 1,
406                (Action::Noop(_), EntryType::Document { .. }) => s.same += 1,
407                (Action::Noop(_), EntryType::Folder) => {}
408                (_, EntryType::Folder) => {
409                    s.stored_bytes += METADATA_FEE;
410                    s.added_bytes += METADATA_FEE;
411                }
412                (_, EntryType::Document { added_bytes, .. }) if e.skip => {
413                    s.skipped.add(added_bytes)
414                }
415                (action, EntryType::Document { disk_bytes, stored_bytes, added_bytes, .. }) => {
416                    if action == Action::Create {
417                        s.new += 1;
418                        s.stored_bytes += stored_bytes + METADATA_FEE;
419                    } else {
420                        s.changed += 1;
421                        s.stored_bytes += stored_bytes;
422                    }
423                    s.disk_bytes += disk_bytes;
424                    s.added_bytes += added_bytes;
425                }
426            }
427        }
428        s
429    }
430}
431
432impl<S: Server, D: LocalDocuments> Lb<S, D> {
433    /// Writes one planned entry under `parent`, reading its file only now.
434    async fn import_entry(&self, e: &Entry, parent: Uuid) -> LbResult<File> {
435        let name = e
436            .disk_path
437            .file_name()
438            .and_then(|n| n.to_str())
439            .ok_or(LbErrKind::DiskPathInvalid)?;
440        if e.file_type == EntryType::Folder {
441            return self.create_imported(name, parent, None).await;
442        }
443        let content = fs::read(&e.disk_path).map_err(LbErr::from)?;
444        match e.action {
445            Action::Replace(id) => {
446                self.write_document(id, &content).await?;
447                self.get_file_by_id(id).await
448            }
449            _ => self.create_imported(name, parent, Some(&content)).await,
450        }
451    }
452
453    /// Writes what `plan` says, one file at a time, then fails naming every entry it couldn't
454    /// write. An entry inside a folder that wasn't created fails with it.
455    #[instrument(level = "debug", skip(self, plan, update_status), err(Debug))]
456    pub async fn import_planned<F: Fn(ImportStatus)>(
457        &self, plan: &ImportPlan, update_status: &F,
458    ) -> LbResult<()> {
459        let total = plan.entries.iter().filter(|e| e.writes()).count();
460        update_status(ImportStatus::CalculatedTotal(total));
461
462        let folders: HashSet<&Path> = plan
463            .entries
464            .iter()
465            .filter(|e| e.file_type == EntryType::Folder)
466            .map(|e| e.disk_path.as_path())
467            .collect();
468        let mut ids: HashMap<&Path, Uuid> = HashMap::new();
469        let mut failed = Vec::new();
470        for e in &plan.entries {
471            if let (Action::Noop(id), EntryType::Folder) = (e.action, e.file_type) {
472                ids.insert(&e.disk_path, id);
473            }
474            if !e.writes() {
475                continue;
476            }
477            let parent = match e.disk_path.parent().filter(|p| folders.contains(p)) {
478                Some(folder) => ids.get(folder).copied(),
479                None => Some(plan.dest),
480            };
481            update_status(ImportStatus::StartingItem(e.disk_path.display().to_string()));
482            let result = match parent {
483                Some(parent) => self.import_entry(e, parent).await,
484                None => Err(LbErrKind::FileParentNonexistent.into()),
485            };
486            match result {
487                Ok(file) => {
488                    if e.file_type == EntryType::Folder {
489                        ids.insert(&e.disk_path, file.id);
490                    }
491                    update_status(ImportStatus::FinishedItem(file));
492                }
493                Err(err) => {
494                    error!(?err, path = %e.disk_path.display(), "import failed");
495                    failed.push(e.disk_path.clone());
496                }
497            }
498        }
499        if failed.is_empty() {
500            Ok(())
501        } else {
502            Err(LbErrKind::ImportFailed { paths: failed, total }.into())
503        }
504    }
505
506    /// Imports `sources` into `dest`, beside anything already there by the same name. Files that
507    /// can't be read, and sources that are links or otherwise not files, fail by name in
508    /// [`LbErrKind::ImportFailed`] along with any that can't be written.
509    #[instrument(level = "debug", skip(self, update_status), err(Debug))]
510    pub async fn import_files<F: Fn(ImportStatus)>(
511        &self, sources: &[PathBuf], dest: Uuid, update_status: &F,
512    ) -> LbResult<()> {
513        let plan = self.plan_import(sources, dest, Existing::Copy).await?;
514        let mut failed: Vec<PathBuf> = plan
515            .entries
516            .iter()
517            .filter(|e| match e.action {
518                Action::Ignore(IgnoreReason::Unreadable) => true,
519                Action::Ignore(IgnoreReason::NotAFile) => sources.contains(&e.disk_path),
520                _ => false,
521            })
522            .map(|e| e.disk_path.clone())
523            .collect();
524        let total = failed.len() + plan.entries.iter().filter(|e| e.writes()).count();
525        if let Err(err) = self.import_planned(&plan, update_status).await {
526            let LbErrKind::ImportFailed { paths, .. } = &err.kind else {
527                return Err(err);
528            };
529            failed.extend(paths.iter().cloned());
530        }
531        if failed.is_empty() {
532            Ok(())
533        } else {
534            Err(LbErrKind::ImportFailed { paths: failed, total }.into())
535        }
536    }
537}
538
539impl<S: Server, D: LocalDocuments> Lb<S, D> {
540    #[instrument(level = "debug", skip(self, update_status), err(Debug))]
541    pub async fn export_file<F: Fn(ExportFileInfo)>(
542        &self, id: Uuid, dest: PathBuf, edit: bool, update_status: &Option<F>,
543    ) -> LbResult<()> {
544        if dest.is_file() {
545            return Err(LbErrKind::DiskPathInvalid.into());
546        }
547
548        self.export_file_recursively(id, &dest, edit, update_status)
549            .await
550    }
551
552    pub async fn export_file_recursively<F: Fn(ExportFileInfo)>(
553        &self, id: Uuid, disk_path: &Path, edit: bool, update_status: &Option<F>,
554    ) -> LbResult<()> {
555        let file = self.get_file_by_id(id).await?;
556
557        let new_dest = disk_path.join(&file.name);
558
559        if let Some(update_status) = update_status {
560            update_status(ExportFileInfo {
561                disk_path: disk_path.to_path_buf(),
562                lockbook_path: self.get_path_by_id(file.id).await?,
563            });
564        }
565
566        match file.file_type {
567            FileType::Document => {
568                let _permit = EXPORT_DOCUMENTS
569                    .acquire()
570                    .await
571                    .expect("export semaphore is never closed");
572                let content = self.read_document(file.id, true).await?;
573
574                // Do not hold an output file open while awaiting document I/O.
575                let mut disk_file = if edit {
576                    OpenOptions::new()
577                        .write(true)
578                        .create(true)
579                        .truncate(true)
580                        .open(new_dest)
581                } else {
582                    OpenOptions::new()
583                        .write(true)
584                        .create_new(true)
585                        .open(new_dest)
586                }
587                .map_err(LbErr::from)?;
588
589                disk_file.write_all(&content).map_err(LbErr::from)?;
590
591                // a note reached by a link has its attachments folder nowhere in this tree, so
592                // no folder's children include it and it has no path to report
593                if let Some(folder) = self.get_attachments_folder(&file.id).await? {
594                    if folder.parent != file.parent {
595                        Box::pin(
596                            self.export_file_recursively(folder.id, disk_path, edit, &None::<F>),
597                        )
598                        .await?;
599                    }
600                }
601            }
602            FileType::Folder => {
603                fs::create_dir(new_dest.clone()).map_err(LbErr::from)?;
604                let export_file_futures = FuturesUnordered::new();
605
606                for child in self.all_children(&file.id).await? {
607                    let lb = self.clone();
608                    let new_dest = &new_dest;
609
610                    export_file_futures.push(async move {
611                        lb.export_file_recursively(child.id, new_dest, edit, update_status)
612                            .await
613                    });
614                }
615
616                export_file_futures
617                    .collect::<Vec<LbResult<()>>>()
618                    .await
619                    .into_iter()
620                    .collect::<LbResult<()>>()?;
621            }
622            FileType::Link { target } => {
623                let export_file_futures = FuturesUnordered::new();
624                let lb = self.clone();
625
626                export_file_futures.push(async move {
627                    lb.export_file_recursively(target, disk_path, edit, update_status)
628                        .await
629                });
630
631                export_file_futures
632                    .collect::<Vec<LbResult<()>>>()
633                    .await
634                    .into_iter()
635                    .collect::<LbResult<()>>()?;
636            }
637        }
638
639        Ok(())
640    }
641}
642
643#[derive(Debug, Clone)]
644pub struct ExportFileInfo {
645    pub disk_path: PathBuf,
646    pub lockbook_path: String,
647}