opendal/services/sftp/
backend.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use std::fmt::Debug;
19use std::fmt::Formatter;
20use std::io::SeekFrom;
21use std::path::Path;
22use std::path::PathBuf;
23use std::sync::Arc;
24
25use log::debug;
26use openssh::KnownHosts;
27use tokio::io::AsyncSeekExt;
28use tokio::sync::OnceCell;
29
30use super::core::SftpCore;
31use super::delete::SftpDeleter;
32use super::error::is_not_found;
33use super::error::is_sftp_protocol_error;
34use super::error::parse_sftp_error;
35use super::lister::SftpLister;
36use super::reader::SftpReader;
37use super::writer::SftpWriter;
38use super::DEFAULT_SCHEME;
39use crate::raw::*;
40use crate::services::SftpConfig;
41use crate::*;
42impl Configurator for SftpConfig {
43    type Builder = SftpBuilder;
44    fn into_builder(self) -> Self::Builder {
45        SftpBuilder { config: self }
46    }
47}
48
49/// SFTP services support. (only works on unix)
50///
51/// If you are interested in working on windows, please refer to [this](https://github.com/apache/opendal/issues/2963) issue.
52/// Welcome to leave your comments or make contributions.
53///
54/// Warning: Maximum number of file holdings is depending on the remote system configuration.
55///
56/// For example, the default value is 255 in macOS, and 1024 in linux. If you want to open
57/// lots of files, you should pay attention to close the file after using it.
58#[doc = include_str!("docs.md")]
59#[derive(Default)]
60pub struct SftpBuilder {
61    config: SftpConfig,
62}
63
64impl Debug for SftpBuilder {
65    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
66        f.debug_struct("SftpBuilder")
67            .field("config", &self.config)
68            .finish()
69    }
70}
71
72impl SftpBuilder {
73    /// set endpoint for sftp backend.
74    /// The format is same as `openssh`, using either `[user@]hostname` or `ssh://[user@]hostname[:port]`. A username or port that is specified in the endpoint overrides the one set in the builder (but does not change the builder).
75    pub fn endpoint(mut self, endpoint: &str) -> Self {
76        self.config.endpoint = if endpoint.is_empty() {
77            None
78        } else {
79            Some(endpoint.to_string())
80        };
81
82        self
83    }
84
85    /// set root path for sftp backend.
86    /// It uses the default directory set by the remote `sftp-server` as default.
87    pub fn root(mut self, root: &str) -> Self {
88        self.config.root = if root.is_empty() {
89            None
90        } else {
91            Some(root.to_string())
92        };
93
94        self
95    }
96
97    /// set user for sftp backend.
98    pub fn user(mut self, user: &str) -> Self {
99        self.config.user = if user.is_empty() {
100            None
101        } else {
102            Some(user.to_string())
103        };
104
105        self
106    }
107
108    /// set key path for sftp backend.
109    pub fn key(mut self, key: &str) -> Self {
110        self.config.key = if key.is_empty() {
111            None
112        } else {
113            Some(key.to_string())
114        };
115
116        self
117    }
118
119    /// set known_hosts strategy for sftp backend.
120    /// available values:
121    /// - Strict (default)
122    /// - Accept
123    /// - Add
124    pub fn known_hosts_strategy(mut self, strategy: &str) -> Self {
125        self.config.known_hosts_strategy = if strategy.is_empty() {
126            None
127        } else {
128            Some(strategy.to_string())
129        };
130
131        self
132    }
133
134    /// set enable_copy for sftp backend.
135    /// It requires the server supports copy-file extension.
136    pub fn enable_copy(mut self, enable_copy: bool) -> Self {
137        self.config.enable_copy = enable_copy;
138
139        self
140    }
141}
142
143impl Builder for SftpBuilder {
144    type Config = SftpConfig;
145
146    fn build(self) -> Result<impl Access> {
147        debug!("sftp backend build started: {:?}", &self);
148        let endpoint = match self.config.endpoint.clone() {
149            Some(v) => v,
150            None => return Err(Error::new(ErrorKind::ConfigInvalid, "endpoint is empty")),
151        };
152
153        let user = self.config.user.clone();
154
155        let root = self
156            .config
157            .root
158            .clone()
159            .map(|r| normalize_root(r.as_str()))
160            .unwrap_or_default();
161
162        let known_hosts_strategy = match &self.config.known_hosts_strategy {
163            Some(v) => {
164                let v = v.to_lowercase();
165                if v == "strict" {
166                    KnownHosts::Strict
167                } else if v == "accept" {
168                    KnownHosts::Accept
169                } else if v == "add" {
170                    KnownHosts::Add
171                } else {
172                    return Err(Error::new(
173                        ErrorKind::ConfigInvalid,
174                        format!("unknown known_hosts strategy: {v}").as_str(),
175                    ));
176                }
177            }
178            None => KnownHosts::Strict,
179        };
180
181        let info = AccessorInfo::default();
182        info.set_root(root.as_str())
183            .set_scheme(DEFAULT_SCHEME)
184            .set_native_capability(Capability {
185                stat: true,
186
187                read: true,
188
189                write: true,
190                write_can_multi: true,
191
192                create_dir: true,
193                delete: true,
194
195                list: true,
196                list_with_limit: true,
197
198                copy: self.config.enable_copy,
199                rename: true,
200
201                shared: true,
202
203                ..Default::default()
204            });
205
206        let accessor_info = Arc::new(info);
207        let core = Arc::new(SftpCore {
208            info: accessor_info,
209            endpoint,
210            root,
211            user,
212            key: self.config.key.clone(),
213            known_hosts_strategy,
214
215            client: OnceCell::new(),
216        });
217
218        debug!("sftp backend finished: {:?}", &self);
219        Ok(SftpBackend { core })
220    }
221}
222
223/// Backend is used to serve `Accessor` support for sftp.
224#[derive(Clone)]
225pub struct SftpBackend {
226    pub core: Arc<SftpCore>,
227}
228
229impl Debug for SftpBackend {
230    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
231        f.debug_struct("SftpBackend")
232            .field("core", &self.core)
233            .finish()
234    }
235}
236
237impl Access for SftpBackend {
238    type Reader = SftpReader;
239    type Writer = SftpWriter;
240    type Lister = Option<SftpLister>;
241    type Deleter = oio::OneShotDeleter<SftpDeleter>;
242
243    fn info(&self) -> Arc<AccessorInfo> {
244        self.core.info.clone()
245    }
246
247    async fn create_dir(&self, path: &str, _: OpCreateDir) -> Result<RpCreateDir> {
248        let client = self.core.connect().await?;
249        let mut fs = client.fs();
250        fs.set_cwd(&self.core.root);
251
252        let paths = Path::new(&path).components();
253        let mut current = PathBuf::from(&self.core.root);
254        for p in paths {
255            current = current.join(p);
256            let res = fs.create_dir(p).await;
257
258            if let Err(e) = res {
259                // ignore error if dir already exists
260                if !is_sftp_protocol_error(&e) {
261                    return Err(parse_sftp_error(e));
262                }
263            }
264            fs.set_cwd(&current);
265        }
266
267        Ok(RpCreateDir::default())
268    }
269
270    async fn stat(&self, path: &str, _: OpStat) -> Result<RpStat> {
271        let client = self.core.connect().await?;
272        let mut fs = client.fs();
273        fs.set_cwd(&self.core.root);
274
275        let meta: Metadata = fs.metadata(path).await.map_err(parse_sftp_error)?.into();
276
277        Ok(RpStat::new(meta))
278    }
279
280    async fn read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::Reader)> {
281        let client = self.core.connect().await?;
282
283        let mut fs = client.fs();
284        fs.set_cwd(&self.core.root);
285
286        let path = fs.canonicalize(path).await.map_err(parse_sftp_error)?;
287
288        let mut f = client
289            .open(path.as_path())
290            .await
291            .map_err(parse_sftp_error)?;
292
293        if args.range().offset() != 0 {
294            f.seek(SeekFrom::Start(args.range().offset()))
295                .await
296                .map_err(new_std_io_error)?;
297        }
298
299        Ok((
300            RpRead::default(),
301            SftpReader::new(client, f, args.range().size()),
302        ))
303    }
304
305    async fn write(&self, path: &str, op: OpWrite) -> Result<(RpWrite, Self::Writer)> {
306        if let Some((dir, _)) = path.rsplit_once('/') {
307            self.create_dir(dir, OpCreateDir::default()).await?;
308        }
309
310        let client = self.core.connect().await?;
311
312        let mut fs = client.fs();
313        fs.set_cwd(&self.core.root);
314        let path = fs.canonicalize(path).await.map_err(parse_sftp_error)?;
315
316        let mut option = client.options();
317        option.create(true);
318        if op.append() {
319            option.append(true);
320        } else {
321            option.write(true).truncate(true);
322        }
323
324        let file = option.open(path).await.map_err(parse_sftp_error)?;
325
326        Ok((RpWrite::new(), SftpWriter::new(file)))
327    }
328
329    async fn delete(&self) -> Result<(RpDelete, Self::Deleter)> {
330        Ok((
331            RpDelete::default(),
332            oio::OneShotDeleter::new(SftpDeleter::new(self.core.clone())),
333        ))
334    }
335
336    async fn list(&self, path: &str, _: OpList) -> Result<(RpList, Self::Lister)> {
337        let client = self.core.connect().await?;
338        let mut fs = client.fs();
339        fs.set_cwd(&self.core.root);
340
341        let file_path = format!("./{path}");
342
343        let dir = match fs.open_dir(&file_path).await {
344            Ok(dir) => dir,
345            Err(e) => {
346                if is_not_found(&e) {
347                    return Ok((RpList::default(), None));
348                } else {
349                    return Err(parse_sftp_error(e));
350                }
351            }
352        }
353        .read_dir();
354
355        Ok((
356            RpList::default(),
357            Some(SftpLister::new(dir, path.to_owned())),
358        ))
359    }
360
361    async fn copy(&self, from: &str, to: &str, _: OpCopy) -> Result<RpCopy> {
362        let client = self.core.connect().await?;
363
364        let mut fs = client.fs();
365        fs.set_cwd(&self.core.root);
366
367        if let Some((dir, _)) = to.rsplit_once('/') {
368            self.create_dir(dir, OpCreateDir::default()).await?;
369        }
370
371        let src = fs.canonicalize(from).await.map_err(parse_sftp_error)?;
372        let dst = fs.canonicalize(to).await.map_err(parse_sftp_error)?;
373        let mut src_file = client.open(&src).await.map_err(parse_sftp_error)?;
374        let mut dst_file = client.create(dst).await.map_err(parse_sftp_error)?;
375
376        src_file
377            .copy_all_to(&mut dst_file)
378            .await
379            .map_err(parse_sftp_error)?;
380
381        Ok(RpCopy::default())
382    }
383
384    async fn rename(&self, from: &str, to: &str, _: OpRename) -> Result<RpRename> {
385        let client = self.core.connect().await?;
386
387        let mut fs = client.fs();
388        fs.set_cwd(&self.core.root);
389
390        if let Some((dir, _)) = to.rsplit_once('/') {
391            self.create_dir(dir, OpCreateDir::default()).await?;
392        }
393        fs.rename(from, to).await.map_err(parse_sftp_error)?;
394
395        Ok(RpRename::default())
396    }
397}