Skip to main content

libupdated/
directory_source.rs

1// SPDX-License-Identifier: MIT
2// SPDX-FileCopyrightText: <text>
3// Copyright(c) 2026 Liebherr-Digital Development Center GmbH
4// Written by Thomas Witte <thomas.witte@liebherr.com>
5// </text>
6
7use std::{
8    collections::HashMap,
9    os::unix::fs::MetadataExt,
10    path::{Path, PathBuf},
11};
12
13use bytes::Bytes;
14use serde::{Deserialize, Serialize};
15use tokio::io::AsyncReadExt;
16use tokio::{fs::File, io::BufReader};
17
18use crate::{
19    update_source::{
20        StreamSender, Update, UpdateFile, UpdateInfo, UpdateSource, UpdateSourceError,
21    },
22    update_workflow::UpdateError,
23};
24
25/// The expected file name of the manifest file that describes the update.
26/// The source's check_for_updates will return an UpdateInfo if this file is
27/// found in the configured update directory.
28const UPDATE_MANIFEST: &str = "update.json";
29
30pub struct DirectorySource {
31    source_dir: PathBuf,
32}
33
34impl DirectorySource {
35    pub fn new(source_dir: &Path) -> Self {
36        DirectorySource {
37            source_dir: source_dir.to_path_buf(),
38        }
39    }
40}
41
42impl UpdateSource for DirectorySource {
43    #[allow(refining_impl_trait)]
44    async fn check_for_updates(&mut self) -> Result<DirectoryUpdateInfo, UpdateError> {
45        match tokio::fs::try_exists(self.source_dir.join(UPDATE_MANIFEST).as_path()).await {
46            Ok(true) => {
47                let filename = self.source_dir.join(UPDATE_MANIFEST);
48                let content = &tokio::fs::read_to_string(filename.as_path()).await?;
49                let mut info =
50                    serde_json::from_str::<DirectoryUpdateInfo>(content).map_err(|e| {
51                        UpdateSourceError::FetchError(format!("could not parse {filename:?}: {e}"))
52                    })?;
53
54                // prepend the source directory to all files in the update
55                for file in &mut info.files {
56                    let mut buf = PathBuf::new();
57                    buf.push(&self.source_dir);
58                    #[allow(clippy::needless_borrows_for_generic_args)]
59                    // clippy gives a false positive
60                    buf.push(&file);
61                    *file = buf.to_string_lossy().into_owned();
62                }
63
64                Ok(info)
65            }
66            Ok(false) => Err(UpdateError::NoPendingUpdates),
67            Err(err) => Err(UpdateError::UpdateSourceError(
68                UpdateSourceError::ConnectionError(format!("{err}")),
69            )),
70        }
71    }
72}
73
74#[derive(Deserialize, Serialize)]
75pub struct DirectoryUpdateInfo {
76    pub update_id: String,
77    pub metadata: HashMap<String, String>,
78    pub files: Vec<String>,
79}
80
81impl UpdateInfo for DirectoryUpdateInfo {
82    fn needs_consent(&self) -> bool {
83        false
84    }
85
86    fn metadata(&self) -> HashMap<String, String> {
87        self.metadata.clone()
88    }
89
90    fn version(&self) -> String {
91        self.update_id.clone()
92    }
93
94    async fn give_consent(&mut self) -> Result<(), UpdateError> {
95        Ok(())
96    }
97
98    #[allow(refining_impl_trait)]
99    fn update(&self) -> Result<DirectoryUpdate, UpdateError> {
100        Ok(DirectoryUpdate::new(
101            &self.update_id,
102            self.files.iter().map(|s| s.into()).collect(),
103        ))
104    }
105}
106
107#[derive(Clone)]
108pub struct DirectoryUpdate {
109    update_id: String,
110    files: Vec<PathBuf>,
111    size: u64,
112}
113
114impl DirectoryUpdate {
115    fn new(update_id: &str, files: Vec<PathBuf>) -> DirectoryUpdate {
116        // calculate the size of the update by adding the file sizes
117        let size = files.iter().fold(0u64, |v, path| {
118            std::fs::metadata(path).map(|m| m.size()).unwrap_or(0) + v
119        });
120
121        DirectoryUpdate {
122            update_id: update_id.to_string(),
123            files,
124            size,
125        }
126    }
127}
128
129impl Update for DirectoryUpdate {
130    fn as_any(&self) -> &dyn std::any::Any {
131        self
132    }
133
134    fn version(&self) -> &str {
135        &self.update_id
136    }
137
138    fn size(&self) -> u64 {
139        self.size
140    }
141
142    async fn save_to_disk_by_name(
143        &self,
144        artifact: String,
145        save_dir: Option<PathBuf>,
146    ) -> Result<UpdateFile<impl Update>, UpdateError> {
147        // for a DirectoryUpdate, the artifact is the absolute path of the source file;
148        // extract the target file name from it
149        let filename = Path::new(&artifact).file_name();
150
151        if let Some(filename) = filename {
152            // create the target file name from the save_dir and the artifact name
153            // if no save_dir is given, choose the directory in which the file
154            // already exists to skip copying it.
155            let target_file = if let Some(save_dir) = save_dir {
156                let mut target_file = save_dir;
157                target_file.push(filename);
158
159                tokio::fs::copy(artifact, &target_file).await?;
160
161                target_file
162            } else {
163                PathBuf::from(&artifact)
164            };
165
166            Ok(UpdateFile::new(&target_file, self).await?)
167        } else {
168            Err(UpdateSourceError::FetchError(format!("{artifact} is not a filename")).into())
169        }
170    }
171
172    async fn stream_by_name(&self, artifact: String, tx: &StreamSender) {
173        match File::open(artifact).await {
174            Ok(file) => {
175                let mut reader = BufReader::new(file);
176                let mut buf = Vec::new();
177
178                loop {
179                    buf.clear();
180
181                    match reader.read_buf(&mut buf).await {
182                        Ok(bytes_read) => {
183                            if bytes_read == 0 {
184                                break;
185                            }
186
187                            tx.send(Ok(Bytes::from(buf.clone())))
188                                .await
189                                .map_err(|err| tx.try_send(Err(err.into())))
190                                .ok();
191                        }
192                        Err(e) => {
193                            tx.try_send(Err(e.into())).ok();
194                            return;
195                        }
196                    }
197                }
198            }
199            Err(err) => {
200                tx.try_send(Err(err.into())).ok();
201            }
202        }
203    }
204
205    fn files(&self) -> Vec<String> {
206        self.files
207            .iter()
208            .map(|path| path.to_string_lossy().into_owned())
209            .collect()
210    }
211}