opendal/services/ftp/
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::str::FromStr;
20use std::sync::Arc;
21
22use http::Uri;
23use log::debug;
24use services::ftp::core::Manager;
25use suppaftp::FtpError;
26use suppaftp::Status;
27use suppaftp::list::File;
28use suppaftp::types::Response;
29use tokio::sync::OnceCell;
30
31use super::FTP_SCHEME;
32use super::config::FtpConfig;
33use super::core::FtpCore;
34use super::deleter::FtpDeleter;
35use super::err::parse_error;
36use super::lister::FtpLister;
37use super::reader::FtpReader;
38use super::writer::FtpWriter;
39use crate::raw::*;
40use crate::*;
41
42/// FTP and FTPS services support.
43#[doc = include_str!("docs.md")]
44#[derive(Debug, Default)]
45pub struct FtpBuilder {
46    pub(super) config: FtpConfig,
47}
48
49impl FtpBuilder {
50    /// set endpoint for ftp backend.
51    pub fn endpoint(mut self, endpoint: &str) -> Self {
52        self.config.endpoint = if endpoint.is_empty() {
53            None
54        } else {
55            Some(endpoint.to_string())
56        };
57
58        self
59    }
60
61    /// set root path for ftp backend.
62    pub fn root(mut self, root: &str) -> Self {
63        self.config.root = if root.is_empty() {
64            None
65        } else {
66            Some(root.to_string())
67        };
68
69        self
70    }
71
72    /// set user for ftp backend.
73    pub fn user(mut self, user: &str) -> Self {
74        self.config.user = if user.is_empty() {
75            None
76        } else {
77            Some(user.to_string())
78        };
79
80        self
81    }
82
83    /// set password for ftp backend.
84    pub fn password(mut self, password: &str) -> Self {
85        self.config.password = if password.is_empty() {
86            None
87        } else {
88            Some(password.to_string())
89        };
90
91        self
92    }
93}
94
95impl Builder for FtpBuilder {
96    type Config = FtpConfig;
97
98    fn build(self) -> Result<impl Access> {
99        debug!("ftp backend build started: {:?}", &self);
100        let endpoint = match &self.config.endpoint {
101            None => return Err(Error::new(ErrorKind::ConfigInvalid, "endpoint is empty")),
102            Some(v) => v,
103        };
104
105        let endpoint_uri = match endpoint.parse::<Uri>() {
106            Err(e) => {
107                return Err(Error::new(ErrorKind::ConfigInvalid, "endpoint is invalid")
108                    .with_context("endpoint", endpoint)
109                    .set_source(e));
110            }
111            Ok(uri) => uri,
112        };
113
114        let host = endpoint_uri.host().unwrap_or("127.0.0.1");
115        let port = endpoint_uri.port_u16().unwrap_or(21);
116
117        let endpoint = format!("{host}:{port}");
118
119        let enable_secure = match endpoint_uri.scheme_str() {
120            Some("ftp") => false,
121            // if the user forgot to add a scheme prefix
122            // treat it as using secured scheme
123            Some("ftps") | None => true,
124
125            Some(s) => {
126                return Err(Error::new(
127                    ErrorKind::ConfigInvalid,
128                    "endpoint is unsupported or invalid",
129                )
130                .with_context("endpoint", s));
131            }
132        };
133
134        let root = normalize_root(&self.config.root.unwrap_or_default());
135
136        let user = match &self.config.user {
137            None => "".to_string(),
138            Some(v) => v.clone(),
139        };
140
141        let password = match &self.config.password {
142            None => "".to_string(),
143            Some(v) => v.clone(),
144        };
145
146        let accessor_info = AccessorInfo::default();
147        accessor_info
148            .set_scheme(FTP_SCHEME)
149            .set_root(&root)
150            .set_native_capability(Capability {
151                stat: true,
152
153                read: true,
154
155                write: true,
156                write_can_multi: true,
157                write_can_append: true,
158
159                delete: true,
160                create_dir: true,
161
162                list: true,
163
164                shared: true,
165
166                ..Default::default()
167            });
168        let manager = Manager {
169            endpoint: endpoint.clone(),
170            root: root.clone(),
171            user: user.clone(),
172            password: password.clone(),
173            enable_secure,
174        };
175        let core = Arc::new(FtpCore {
176            info: accessor_info.into(),
177            manager,
178            pool: OnceCell::new(),
179        });
180
181        Ok(FtpBackend { core })
182    }
183}
184
185// Backend is used to serve `Accessor` support for ftp.
186#[derive(Clone)]
187pub struct FtpBackend {
188    core: Arc<FtpCore>,
189}
190
191impl Debug for FtpBackend {
192    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
193        f.debug_struct("FtpBackend").finish()
194    }
195}
196
197impl Access for FtpBackend {
198    type Reader = FtpReader;
199    type Writer = FtpWriter;
200    type Lister = FtpLister;
201    type Deleter = oio::OneShotDeleter<FtpDeleter>;
202
203    fn info(&self) -> Arc<AccessorInfo> {
204        self.core.info.clone()
205    }
206
207    async fn create_dir(&self, path: &str, _: OpCreateDir) -> Result<RpCreateDir> {
208        let mut ftp_stream = self.core.ftp_connect(Operation::CreateDir).await?;
209
210        let paths: Vec<&str> = path.split_inclusive('/').collect();
211
212        let mut curr_path = String::new();
213
214        for path in paths {
215            curr_path.push_str(path);
216            match ftp_stream.mkdir(&curr_path).await {
217                // Do nothing if status is FileUnavailable or OK(()) is return.
218                Err(FtpError::UnexpectedResponse(Response {
219                    status: Status::FileUnavailable,
220                    ..
221                }))
222                | Ok(()) => (),
223                Err(e) => {
224                    return Err(parse_error(e));
225                }
226            }
227        }
228
229        Ok(RpCreateDir::default())
230    }
231
232    async fn stat(&self, path: &str, _: OpStat) -> Result<RpStat> {
233        let file = self.ftp_stat(path).await?;
234
235        let mode = if file.is_file() {
236            EntryMode::FILE
237        } else if file.is_directory() {
238            EntryMode::DIR
239        } else {
240            EntryMode::Unknown
241        };
242
243        let mut meta = Metadata::new(mode);
244        meta.set_content_length(file.size() as u64);
245        meta.set_last_modified(Timestamp::try_from(file.modified())?);
246
247        Ok(RpStat::new(meta))
248    }
249
250    async fn read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::Reader)> {
251        let ftp_stream = self.core.ftp_connect(Operation::Read).await?;
252
253        let reader = FtpReader::new(ftp_stream, path.to_string(), args).await?;
254        Ok((RpRead::new(), reader))
255    }
256
257    async fn write(&self, path: &str, op: OpWrite) -> Result<(RpWrite, Self::Writer)> {
258        // Ensure the parent dir exists.
259        let parent = get_parent(path);
260        let paths: Vec<&str> = parent.split('/').collect();
261
262        // TODO: we can optimize this by checking dir existence first.
263        let mut ftp_stream = self.core.ftp_connect(Operation::Write).await?;
264        let mut curr_path = String::new();
265
266        for path in paths {
267            if path.is_empty() {
268                continue;
269            }
270            curr_path.push_str(path);
271            curr_path.push('/');
272            match ftp_stream.mkdir(&curr_path).await {
273                // Do nothing if status is FileUnavailable or OK(()) is return.
274                Err(FtpError::UnexpectedResponse(Response {
275                    status: Status::FileUnavailable,
276                    ..
277                }))
278                | Ok(()) => (),
279                Err(e) => {
280                    return Err(parse_error(e));
281                }
282            }
283        }
284
285        let tmp_path = (!op.append()).then_some(build_tmp_path_of(path));
286        let w = FtpWriter::new(ftp_stream, path.to_string(), tmp_path);
287
288        Ok((RpWrite::new(), w))
289    }
290
291    async fn delete(&self) -> Result<(RpDelete, Self::Deleter)> {
292        Ok((
293            RpDelete::default(),
294            oio::OneShotDeleter::new(FtpDeleter::new(self.core.clone())),
295        ))
296    }
297
298    async fn list(&self, path: &str, _: OpList) -> Result<(RpList, Self::Lister)> {
299        let mut ftp_stream = self.core.ftp_connect(Operation::List).await?;
300
301        let pathname = if path == "/" { None } else { Some(path) };
302        let files = ftp_stream.list(pathname).await.map_err(parse_error)?;
303
304        Ok((
305            RpList::default(),
306            FtpLister::new(if path == "/" { "" } else { path }, files),
307        ))
308    }
309}
310
311impl FtpBackend {
312    pub async fn ftp_stat(&self, path: &str) -> Result<File> {
313        let mut ftp_stream = self.core.ftp_connect(Operation::Stat).await?;
314
315        let (parent, basename) = (get_parent(path), get_basename(path));
316
317        let pathname = if parent == "/" { None } else { Some(parent) };
318
319        let resp = ftp_stream.list(pathname).await.map_err(parse_error)?;
320
321        // Get stat of file.
322        let mut files = resp
323            .into_iter()
324            .filter_map(|file| File::from_str(file.as_str()).ok())
325            .filter(|f| f.name() == basename.trim_end_matches('/'))
326            .collect::<Vec<File>>();
327
328        if files.is_empty() {
329            Err(Error::new(
330                ErrorKind::NotFound,
331                "file is not found during list",
332            ))
333        } else {
334            Ok(files.remove(0))
335        }
336    }
337}
338
339#[cfg(test)]
340mod build_test {
341    use super::FtpBuilder;
342    use crate::services::FtpConfig;
343    use crate::*;
344
345    #[test]
346    fn test_build() {
347        // ftps scheme, should suffix with default port 21
348        let b = FtpBuilder::default()
349            .endpoint("ftps://ftp_server.local")
350            .build();
351        assert!(b.is_ok());
352
353        // ftp scheme
354        let b = FtpBuilder::default()
355            .endpoint("ftp://ftp_server.local:1234")
356            .build();
357        assert!(b.is_ok());
358
359        // no scheme
360        let b = FtpBuilder::default()
361            .endpoint("ftp_server.local:8765")
362            .build();
363        assert!(b.is_ok());
364
365        // invalid scheme
366        let b = FtpBuilder::default()
367            .endpoint("invalidscheme://ftp_server.local:8765")
368            .build();
369        assert!(b.is_err());
370        let e = b.unwrap_err();
371        assert_eq!(e.kind(), ErrorKind::ConfigInvalid);
372    }
373
374    #[test]
375    fn from_uri_sets_endpoint_and_root() {
376        let uri = OperatorUri::new(
377            "ftp://example.com/public/data",
378            Vec::<(String, String)>::new(),
379        )
380        .unwrap();
381
382        let cfg = FtpConfig::from_uri(&uri).unwrap();
383        assert_eq!(cfg.endpoint.as_deref(), Some("ftp://example.com"));
384        assert_eq!(cfg.root.as_deref(), Some("public/data"));
385    }
386
387    #[test]
388    fn from_uri_applies_credentials_from_query() {
389        let uri = OperatorUri::new(
390            "ftp://example.com/data",
391            vec![
392                ("user".to_string(), "alice".to_string()),
393                ("password".to_string(), "secret".to_string()),
394            ],
395        )
396        .unwrap();
397
398        let cfg = FtpConfig::from_uri(&uri).unwrap();
399        assert_eq!(cfg.endpoint.as_deref(), Some("ftp://example.com"));
400        assert_eq!(cfg.user.as_deref(), Some("alice"));
401        assert_eq!(cfg.password.as_deref(), Some("secret"));
402    }
403}