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 crate::raw::*;
39use crate::services::SftpConfig;
40use crate::*;
41
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    const SCHEME: Scheme = Scheme::Sftp;
145    type Config = SftpConfig;
146
147    fn build(self) -> Result<impl Access> {
148        debug!("sftp backend build started: {:?}", &self);
149        let endpoint = match self.config.endpoint.clone() {
150            Some(v) => v,
151            None => return Err(Error::new(ErrorKind::ConfigInvalid, "endpoint is empty")),
152        };
153
154        let user = self.config.user.clone();
155
156        let root = self
157            .config
158            .root
159            .clone()
160            .map(|r| normalize_root(r.as_str()))
161            .unwrap_or_default();
162
163        let known_hosts_strategy = match &self.config.known_hosts_strategy {
164            Some(v) => {
165                let v = v.to_lowercase();
166                if v == "strict" {
167                    KnownHosts::Strict
168                } else if v == "accept" {
169                    KnownHosts::Accept
170                } else if v == "add" {
171                    KnownHosts::Add
172                } else {
173                    return Err(Error::new(
174                        ErrorKind::ConfigInvalid,
175                        format!("unknown known_hosts strategy: {}", v).as_str(),
176                    ));
177                }
178            }
179            None => KnownHosts::Strict,
180        };
181
182        let info = AccessorInfo::default();
183        info.set_root(root.as_str())
184            .set_scheme(Scheme::Sftp)
185            .set_native_capability(Capability {
186                stat: true,
187                stat_has_content_length: true,
188                stat_has_last_modified: true,
189
190                read: true,
191
192                write: true,
193                write_can_multi: true,
194
195                create_dir: true,
196                delete: true,
197
198                list: true,
199                list_with_limit: true,
200                list_has_content_length: true,
201                list_has_last_modified: true,
202
203                copy: self.config.enable_copy,
204                rename: true,
205
206                shared: true,
207
208                ..Default::default()
209            });
210
211        let accessor_info = Arc::new(info);
212        let core = Arc::new(SftpCore {
213            info: accessor_info,
214            endpoint,
215            root,
216            user,
217            key: self.config.key.clone(),
218            known_hosts_strategy,
219
220            client: OnceCell::new(),
221        });
222
223        debug!("sftp backend finished: {:?}", &self);
224        Ok(SftpBackend { core })
225    }
226}
227
228/// Backend is used to serve `Accessor` support for sftp.
229#[derive(Clone)]
230pub struct SftpBackend {
231    pub core: Arc<SftpCore>,
232}
233
234impl Debug for SftpBackend {
235    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
236        f.debug_struct("SftpBackend")
237            .field("core", &self.core)
238            .finish()
239    }
240}
241
242impl Access for SftpBackend {
243    type Reader = SftpReader;
244    type Writer = SftpWriter;
245    type Lister = Option<SftpLister>;
246    type Deleter = oio::OneShotDeleter<SftpDeleter>;
247
248    fn info(&self) -> Arc<AccessorInfo> {
249        self.core.info.clone()
250    }
251
252    async fn create_dir(&self, path: &str, _: OpCreateDir) -> Result<RpCreateDir> {
253        let client = self.core.connect().await?;
254        let mut fs = client.fs();
255        fs.set_cwd(&self.core.root);
256
257        let paths = Path::new(&path).components();
258        let mut current = PathBuf::from(&self.core.root);
259        for p in paths {
260            current = current.join(p);
261            let res = fs.create_dir(p).await;
262
263            if let Err(e) = res {
264                // ignore error if dir already exists
265                if !is_sftp_protocol_error(&e) {
266                    return Err(parse_sftp_error(e));
267                }
268            }
269            fs.set_cwd(&current);
270        }
271
272        Ok(RpCreateDir::default())
273    }
274
275    async fn stat(&self, path: &str, _: OpStat) -> Result<RpStat> {
276        let client = self.core.connect().await?;
277        let mut fs = client.fs();
278        fs.set_cwd(&self.core.root);
279
280        let meta: Metadata = fs.metadata(path).await.map_err(parse_sftp_error)?.into();
281
282        Ok(RpStat::new(meta))
283    }
284
285    async fn read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::Reader)> {
286        let client = self.core.connect().await?;
287
288        let mut fs = client.fs();
289        fs.set_cwd(&self.core.root);
290
291        let path = fs.canonicalize(path).await.map_err(parse_sftp_error)?;
292
293        let mut f = client
294            .open(path.as_path())
295            .await
296            .map_err(parse_sftp_error)?;
297
298        if args.range().offset() != 0 {
299            f.seek(SeekFrom::Start(args.range().offset()))
300                .await
301                .map_err(new_std_io_error)?;
302        }
303
304        Ok((
305            RpRead::default(),
306            SftpReader::new(client, f, args.range().size()),
307        ))
308    }
309
310    async fn write(&self, path: &str, op: OpWrite) -> Result<(RpWrite, Self::Writer)> {
311        if let Some((dir, _)) = path.rsplit_once('/') {
312            self.create_dir(dir, OpCreateDir::default()).await?;
313        }
314
315        let client = self.core.connect().await?;
316
317        let mut fs = client.fs();
318        fs.set_cwd(&self.core.root);
319        let path = fs.canonicalize(path).await.map_err(parse_sftp_error)?;
320
321        let mut option = client.options();
322        option.create(true);
323        if op.append() {
324            option.append(true);
325        } else {
326            option.write(true).truncate(true);
327        }
328
329        let file = option.open(path).await.map_err(parse_sftp_error)?;
330
331        Ok((RpWrite::new(), SftpWriter::new(file)))
332    }
333
334    async fn delete(&self) -> Result<(RpDelete, Self::Deleter)> {
335        Ok((
336            RpDelete::default(),
337            oio::OneShotDeleter::new(SftpDeleter::new(self.core.clone())),
338        ))
339    }
340
341    async fn list(&self, path: &str, _: OpList) -> Result<(RpList, Self::Lister)> {
342        let client = self.core.connect().await?;
343        let mut fs = client.fs();
344        fs.set_cwd(&self.core.root);
345
346        let file_path = format!("./{}", path);
347
348        let dir = match fs.open_dir(&file_path).await {
349            Ok(dir) => dir,
350            Err(e) => {
351                if is_not_found(&e) {
352                    return Ok((RpList::default(), None));
353                } else {
354                    return Err(parse_sftp_error(e));
355                }
356            }
357        }
358        .read_dir();
359
360        Ok((
361            RpList::default(),
362            Some(SftpLister::new(dir, path.to_owned())),
363        ))
364    }
365
366    async fn copy(&self, from: &str, to: &str, _: OpCopy) -> Result<RpCopy> {
367        let client = self.core.connect().await?;
368
369        let mut fs = client.fs();
370        fs.set_cwd(&self.core.root);
371
372        if let Some((dir, _)) = to.rsplit_once('/') {
373            self.create_dir(dir, OpCreateDir::default()).await?;
374        }
375
376        let src = fs.canonicalize(from).await.map_err(parse_sftp_error)?;
377        let dst = fs.canonicalize(to).await.map_err(parse_sftp_error)?;
378        let mut src_file = client.open(&src).await.map_err(parse_sftp_error)?;
379        let mut dst_file = client.create(dst).await.map_err(parse_sftp_error)?;
380
381        src_file
382            .copy_all_to(&mut dst_file)
383            .await
384            .map_err(parse_sftp_error)?;
385
386        Ok(RpCopy::default())
387    }
388
389    async fn rename(&self, from: &str, to: &str, _: OpRename) -> Result<RpRename> {
390        let client = self.core.connect().await?;
391
392        let mut fs = client.fs();
393        fs.set_cwd(&self.core.root);
394
395        if let Some((dir, _)) = to.rsplit_once('/') {
396            self.create_dir(dir, OpCreateDir::default()).await?;
397        }
398        fs.rename(from, to).await.map_err(parse_sftp_error)?;
399
400        Ok(RpRename::default())
401    }
402}