/
mod.rs
1464 lines (1340 loc) · 54.1 KB
/
mod.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! # Sync
//!
//! This module contains the definition for all Sync implementation of suppaftp
mod data_stream;
mod tls;
use std::fmt::Debug;
use std::io::{copy, BufRead, BufReader, Cursor, Read, Write};
#[cfg(not(feature = "secure"))]
use std::marker::PhantomData;
use std::net::{Ipv4Addr, SocketAddr, TcpListener, TcpStream, ToSocketAddrs};
use std::time::{Duration, Instant};
use chrono::{NaiveDate, NaiveDateTime, NaiveTime};
// export
pub use data_stream::DataStream;
pub use tls::NoTlsStream;
#[cfg(feature = "secure")]
pub use tls::TlsConnector;
use tls::TlsStream;
#[cfg(feature = "native-tls")]
pub use tls::{NativeTlsConnector, NativeTlsStream};
#[cfg(feature = "rustls")]
pub use tls::{RustlsConnector, RustlsStream};
use super::regex::{EPSV_PORT_RE, MDTM_RE, PASV_PORT_RE, SIZE_RE};
use super::types::{FileType, FtpError, FtpResult, Mode, Response};
use super::Status;
use crate::command::Command;
#[cfg(feature = "secure")]
use crate::command::ProtectionLevel;
use crate::types::Features;
/// Stream to interface with the FTP server. This interface is only for the command stream.
#[derive(Debug)]
pub struct ImplFtpStream<T>
where
T: TlsStream,
{
reader: BufReader<DataStream<T>>,
mode: Mode,
nat_workaround: bool,
welcome_msg: Option<String>,
active_timeout: Duration,
#[cfg(not(feature = "secure"))]
marker: PhantomData<T>,
#[cfg(feature = "secure")]
tls_ctx: Option<Box<dyn TlsConnector<Stream = T> + Send + Sync + 'static>>,
#[cfg(feature = "secure")]
domain: Option<String>,
}
impl<T> ImplFtpStream<T>
where
T: TlsStream,
{
/// Try to connect to the remote server
pub fn connect<A: ToSocketAddrs>(addr: A) -> FtpResult<Self> {
debug!("Connecting to server");
TcpStream::connect(addr)
.map_err(FtpError::ConnectionError)
.and_then(|stream| Self::connect_with_stream(stream))
}
/// Try to connect to the remote server but with the specified timeout
pub fn connect_timeout(addr: std::net::SocketAddr, timeout: Duration) -> FtpResult<Self> {
debug!("Connecting to server {addr}");
TcpStream::connect_timeout(&addr, timeout)
.map_err(FtpError::ConnectionError)
.and_then(|stream| Self::connect_with_stream(stream))
}
/// Connect using provided configured tcp stream
pub fn connect_with_stream(stream: TcpStream) -> FtpResult<Self> {
debug!("Established connection with server");
let mut ftp_stream = Self {
reader: BufReader::new(DataStream::Tcp(stream)),
mode: Mode::Passive,
nat_workaround: false,
welcome_msg: None,
active_timeout: Duration::from_secs(60),
#[cfg(feature = "secure")]
tls_ctx: None,
#[cfg(feature = "secure")]
domain: None,
#[cfg(not(feature = "secure"))]
marker: PhantomData {},
};
debug!("Reading server response...");
match ftp_stream.read_response(Status::Ready) {
Ok(response) => {
let welcome_msg = response.as_string().ok();
debug!("Server READY; response: {:?}", welcome_msg);
ftp_stream.welcome_msg = welcome_msg;
Ok(ftp_stream)
}
Err(err) => Err(err),
}
}
/// Enable active mode for data channel
pub fn active_mode(mut self, accept_timeout: Duration) -> Self {
self.mode = Mode::Active;
self.active_timeout = accept_timeout;
self
}
/// Set the data channel transfer mode
pub fn set_mode(&mut self, mode: Mode) {
debug!("Changed mode to {:?}", mode);
self.mode = mode;
}
/// Set NAT workaround for passive mode
pub fn set_passive_nat_workaround(&mut self, nat_workaround: bool) {
self.nat_workaround = nat_workaround;
}
/// Switch to explicit secure mode if possible (FTPS), using a provided SSL configuration.
/// This method does nothing if the connect is already secured.
///
/// ## Example
///
/// ```rust,no_run
/// use suppaftp::{NativeTlsFtpStream, NativeTlsConnector};
/// use suppaftp::native_tls::{TlsConnector, TlsStream};
/// use std::path::Path;
///
/// // Create a TlsConnector
/// // NOTE: For custom options see <https://docs.rs/native-tls/0.2.6/native_tls/struct.TlsConnectorBuilder.html>
/// let mut ctx = NativeTlsConnector::from(TlsConnector::new().unwrap());
/// let mut ftp_stream = NativeTlsFtpStream::connect("127.0.0.1:21").unwrap();
/// let mut ftp_stream = ftp_stream.into_secure(ctx, "localhost").unwrap();
/// ```
#[cfg(feature = "secure")]
#[cfg_attr(docsrs, doc(cfg(feature = "secure")))]
pub fn into_secure(
mut self,
tls_connector: impl TlsConnector<Stream = T> + Send + Sync + 'static,
domain: &str,
) -> FtpResult<Self> {
// Ask the server to start securing data.
debug!("Initializing TLS auth");
self.perform(Command::Auth)?;
self.read_response(Status::AuthOk)?;
debug!("TLS OK; initializing ssl stream");
let stream = tls_connector
.connect(domain, self.reader.into_inner().into_tcp_stream())
.map_err(|e| FtpError::SecureError(format!("{e}")))?;
debug!("TLS Steam OK");
let mut secured_ftp_tream = Self {
reader: BufReader::new(DataStream::Ssl(Box::new(stream))),
mode: self.mode,
nat_workaround: self.nat_workaround,
tls_ctx: Some(Box::new(tls_connector)),
domain: Some(String::from(domain)),
welcome_msg: self.welcome_msg,
active_timeout: self.active_timeout,
};
// Set protection buffer size
secured_ftp_tream.perform(Command::Pbsz(0))?;
secured_ftp_tream.read_response(Status::CommandOk)?;
// Change the level of data protectio to Private
secured_ftp_tream.perform(Command::Prot(ProtectionLevel::Private))?;
secured_ftp_tream.read_response(Status::CommandOk)?;
Ok(secured_ftp_tream)
}
/// Connect to remote ftps server using IMPLICIT secure connection.
///
/// > Warning: mind that implicit ftps should be considered deprecated, if you can use explicit mode with `into_secure()`
///
///
/// ## Example
///
/// ```rust,no_run
/// use suppaftp::FtpStream;
/// use suppaftp::native_tls::{TlsConnector, TlsStream};
/// use std::path::Path;
///
/// // Create a TlsConnector
/// // NOTE: For custom options see <https://docs.rs/native-tls/0.2.6/native_tls/struct.TlsConnectorBuilder.html>
/// let mut ctx = TlsConnector::new().unwrap();
/// let mut ftp_stream = FtpStream::connect_secure_implicit("127.0.0.1:990", ctx, "localhost").unwrap();
/// ```
#[cfg(all(feature = "secure", feature = "deprecated"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "secure", feature = "deprecated"))))]
pub fn connect_secure_implicit<A: ToSocketAddrs>(
addr: A,
tls_connector: impl TlsConnector<Stream = T> + Send + Sync + 'static,
domain: &str,
) -> FtpResult<Self> {
debug!("Connecting to server (secure)");
let stream = TcpStream::connect(addr)
.map_err(FtpError::ConnectionError)
.map(|stream| {
debug!("Established connection with server");
Self {
reader: BufReader::new(DataStream::Tcp(stream)),
mode: Mode::Passive,
nat_workaround: false,
welcome_msg: None,
tls_ctx: None,
domain: None,
active_timeout: Duration::from_secs(60),
}
})?;
debug!("Established connection with server");
debug!("TLS OK; initializing ssl stream");
let stream = tls_connector
.connect(domain, stream.reader.into_inner().into_tcp_stream())
.map_err(|e| FtpError::SecureError(format!("{e}")))?;
debug!("TLS Steam OK");
let mut stream = Self {
reader: BufReader::new(DataStream::Ssl(Box::new(stream))),
mode: Mode::Passive,
nat_workaround: false,
tls_ctx: Some(Box::new(tls_connector)),
domain: Some(String::from(domain)),
welcome_msg: None,
active_timeout: Duration::from_secs(60),
};
debug!("Reading server response...");
match stream.read_response(Status::Ready) {
Ok(response) => {
let welcome_msg = response.as_string().ok();
debug!("Server READY; response: {:?}", welcome_msg);
stream.welcome_msg = welcome_msg;
}
Err(err) => return Err(err),
}
Ok(stream)
}
/// Returns welcome message retrieved from server (if available)
pub fn get_welcome_msg(&self) -> Option<&str> {
self.welcome_msg.as_deref()
}
/// Returns a reference to the underlying TcpStream.
///
/// Example:
/// ```no_run
/// use suppaftp::FtpStream;
/// use std::net::TcpStream;
/// use std::time::Duration;
///
/// let stream = FtpStream::connect("127.0.0.1:21")
/// .expect("Couldn't connect to the server...");
/// stream.get_ref().set_read_timeout(Some(Duration::from_secs(10)))
/// .expect("set_read_timeout call failed");
/// ```
pub fn get_ref(&self) -> &TcpStream {
self.reader.get_ref().get_ref()
}
/// Log in to the FTP server.
pub fn login<S: AsRef<str>>(&mut self, user: S, password: S) -> FtpResult<()> {
debug!("Signin in with user '{}'", user.as_ref());
self.perform(Command::User(user.as_ref().to_string()))?;
self.read_response_in(&[Status::LoggedIn, Status::NeedPassword])
.and_then(|Response { status, body: _ }| {
if status == Status::NeedPassword {
debug!("Password is required");
self.perform(Command::Pass(password.as_ref().to_string()))?;
self.read_response(Status::LoggedIn)?;
}
debug!("Login OK");
Ok(())
})
}
/// Perform clear command channel (CCC).
/// Once the command is performed, the command channel will be encrypted no more.
/// The data stream will still be secure.
#[cfg(feature = "secure")]
#[cfg_attr(docsrs, doc(cfg(feature = "secure")))]
pub fn clear_command_channel(mut self) -> FtpResult<Self> {
// Ask the server to stop securing data
debug!("performing clear command channel");
self.perform(Command::ClearCommandChannel)?;
self.read_response(Status::CommandOk)?;
trace!("CCC OK");
self.reader = BufReader::new(DataStream::Tcp(self.reader.into_inner().into_tcp_stream()));
Ok(self)
}
/// Change the current directory to the path specified.
pub fn cwd<S: AsRef<str>>(&mut self, path: S) -> FtpResult<()> {
debug!("Changing working directory to {}", path.as_ref());
self.perform(Command::Cwd(path.as_ref().to_string()))?;
self.read_response(Status::RequestedFileActionOk)
.map(|_| ())
}
/// Move the current directory to the parent directory.
pub fn cdup(&mut self) -> FtpResult<()> {
debug!("Going to parent directory");
self.perform(Command::Cdup)?;
self.read_response_in(&[Status::CommandOk, Status::RequestedFileActionOk])
.map(|_| ())
}
/// Gets the current directory
pub fn pwd(&mut self) -> FtpResult<String> {
debug!("Getting working directory");
self.perform(Command::Pwd)?;
self.read_response(Status::PathCreated)
.and_then(|response| {
let body = response.as_string().map_err(|_| FtpError::BadResponse)?;
let status = response.status;
match (body.find('"'), body.rfind('"')) {
(Some(begin), Some(end)) if begin < end => Ok(body[begin + 1..end].to_string()),
_ => Err(FtpError::UnexpectedResponse(Response::new(
status,
response.body,
))),
}
})
}
/// This does nothing. This is usually just used to keep the connection open.
pub fn noop(&mut self) -> FtpResult<()> {
debug!("Pinging server");
self.perform(Command::Noop)?;
self.read_response(Status::CommandOk).map(|_| ())
}
/// The EPRT command allows for the specification of an extended address
/// for the data connection. The extended address MUST consist of the
/// network protocol as well as the network and transport addresses
pub fn eprt(&mut self, address: SocketAddr) -> FtpResult<()> {
debug!("EPRT with address {address}");
self.perform(Command::Eprt(address))?;
self.read_response(Status::CommandOk).map(|_| ())
}
/// This creates a new directory on the server.
pub fn mkdir<S: AsRef<str>>(&mut self, pathname: S) -> FtpResult<()> {
debug!("Creating directory at {}", pathname.as_ref());
self.perform(Command::Mkd(pathname.as_ref().to_string()))?;
self.read_response(Status::PathCreated).map(|_| ())
}
/// Sets the type of file to be transferred. That is the implementation
/// of `TYPE` command.
pub fn transfer_type(&mut self, file_type: FileType) -> FtpResult<()> {
debug!("Setting transfer type {}", file_type.to_string());
self.perform(Command::Type(file_type))?;
self.read_response(Status::CommandOk).map(|_| ())
}
/// Quits the current FTP session.
pub fn quit(&mut self) -> FtpResult<()> {
debug!("Quitting stream");
self.perform(Command::Quit)?;
self.read_response(Status::Closing).map(|_| ())
}
/// Renames the file from_name to to_name
pub fn rename<S: AsRef<str>>(&mut self, from_name: S, to_name: S) -> FtpResult<()> {
debug!(
"Renaming '{}' to '{}'",
from_name.as_ref(),
to_name.as_ref()
);
self.perform(Command::RenameFrom(from_name.as_ref().to_string()))?;
self.read_response(Status::RequestFilePending)
.and_then(|_| {
self.perform(Command::RenameTo(to_name.as_ref().to_string()))?;
self.read_response(Status::RequestedFileActionOk)
.map(|_| ())
})
}
/// The implementation of `RETR` command where `filename` is the name of the file
/// to download from FTP and `reader` is the function which operates with the
/// data stream opened.
///
/// ```
/// # use suppaftp::{FtpStream, FtpError};
/// # use std::io::Cursor;
/// # let mut conn = FtpStream::connect("127.0.0.1:10021").unwrap();
/// # conn.login("test", "test").and_then(|_| {
/// # let mut reader = Cursor::new("hello, world!".as_bytes());
/// # conn.put_file("retr.txt", &mut reader)
/// # }).unwrap();
/// assert!(conn.retr("retr.txt", |stream| {
/// let mut buf = Vec::new();
/// stream.read_to_end(&mut buf).map(|_|
/// assert_eq!(buf, "hello, world!".as_bytes())
/// ).map_err(|e| FtpError::ConnectionError(e))
/// }).is_ok());
/// # assert!(conn.rm("retr.txt").is_ok());
/// ```
pub fn retr<F, D>(&mut self, file_name: &str, mut reader: F) -> FtpResult<D>
where
F: FnMut(&mut dyn Read) -> FtpResult<D>,
{
match self.retr_as_stream(file_name) {
Ok(mut stream) => {
let result = reader(&mut stream)?;
self.finalize_retr_stream(stream)?;
Ok(result)
}
Err(err) => Err(err),
}
}
/// Simple way to retr a file from the server. This stores the file in a buffer in memory.
///
/// ```
/// # use suppaftp::{FtpStream, FtpError};
/// # use std::io::Cursor;
/// # let mut conn = FtpStream::connect("127.0.0.1:10021").unwrap();
/// # conn.login("test", "test").and_then(|_| {
/// # let mut reader = Cursor::new("hello, world!".as_bytes());
/// # conn.put_file("simple_retr.txt", &mut reader)
/// # }).unwrap();
/// let cursor = conn.retr_as_buffer("simple_retr.txt").unwrap();
/// // do something with bytes
/// assert_eq!(cursor.into_inner(), "hello, world!".as_bytes());
/// # assert!(conn.rm("simple_retr.txt").is_ok());
/// ```
pub fn retr_as_buffer(&mut self, file_name: &str) -> FtpResult<Cursor<Vec<u8>>> {
self.retr(file_name, |reader| {
let mut buffer = Vec::new();
reader
.read_to_end(&mut buffer)
.map(|_| buffer)
.map_err(FtpError::ConnectionError)
})
.map(Cursor::new)
}
/// Retrieves the file name specified from the server as a readable stream.
/// This method is a more complicated way to retrieve a file.
/// The reader returned should be dropped.
/// Also you will have to read the response to make sure it has the correct value.
/// Once file has been read, call `finalize_retr_stream()`
pub fn retr_as_stream<S: AsRef<str>>(&mut self, file_name: S) -> FtpResult<DataStream<T>> {
debug!("Retrieving '{}'", file_name.as_ref());
let data_stream = self.data_command(Command::Retr(file_name.as_ref().to_string()))?;
self.read_response_in(&[Status::AboutToSend, Status::AlreadyOpen])?;
Ok(data_stream)
}
/// Finalize retr stream; must be called once the requested file, got previously with `retr_as_stream()` has been read
pub fn finalize_retr_stream(&mut self, stream: impl Read) -> FtpResult<()> {
debug!("Finalizing retr stream");
// Drop stream NOTE: must be done first, otherwise server won't return any response
drop(stream);
trace!("dropped stream");
// Then read response
self.read_response_in(&[Status::ClosingDataConnection, Status::RequestedFileActionOk])
.map(|_| ())
}
/// Removes the remote pathname from the server.
pub fn rmdir<S: AsRef<str>>(&mut self, pathname: S) -> FtpResult<()> {
debug!("Removing directory {}", pathname.as_ref());
self.perform(Command::Rmd(pathname.as_ref().to_string()))?;
self.read_response(Status::RequestedFileActionOk)
.map(|_| ())
}
/// Remove the remote file from the server.
pub fn rm<S: AsRef<str>>(&mut self, filename: S) -> FtpResult<()> {
debug!("Removing file {}", filename.as_ref());
self.perform(Command::Dele(filename.as_ref().to_string()))?;
self.read_response(Status::RequestedFileActionOk)
.map(|_| ())
}
/// This stores a file on the server.
/// r argument must be any struct which implemenents the Read trait.
/// Returns amount of written bytes
pub fn put_file<S: AsRef<str>, R: Read>(&mut self, filename: S, r: &mut R) -> FtpResult<u64> {
// Get stream
let mut data_stream = self.put_with_stream(filename.as_ref())?;
let bytes = copy(r, &mut data_stream).map_err(FtpError::ConnectionError)?;
self.finalize_put_stream(data_stream)?;
Ok(bytes)
}
/// Send PUT command and returns a BufWriter, which references the file created on the server
/// The returned stream must be then correctly manipulated to write the content of the source file to the remote destination
/// The stream must be then correctly dropped.
/// Once you've finished the write, YOU MUST CALL THIS METHOD: `finalize_put_stream`
pub fn put_with_stream<S: AsRef<str>>(&mut self, filename: S) -> FtpResult<DataStream<T>> {
debug!("Put file {}", filename.as_ref());
let stream = self.data_command(Command::Store(filename.as_ref().to_string()))?;
self.read_response_in(&[Status::AlreadyOpen, Status::AboutToSend])?;
Ok(stream)
}
/// Finalize put when using stream
/// This method must be called once the file has been written and
/// `put_with_stream` has been used to write the file
pub fn finalize_put_stream(&mut self, stream: impl Write) -> FtpResult<()> {
debug!("Finalizing put stream");
// Drop stream NOTE: must be done first, otherwise server won't return any response
drop(stream);
trace!("Stream dropped");
// Read response
self.read_response_in(&[Status::ClosingDataConnection, Status::RequestedFileActionOk])
.map(|_| ())
}
/// Open specified file for appending data. Returns the stream to append data to specified file.
/// Once you've finished the write, YOU MUST CALL THIS METHOD: `finalize_put_stream`
pub fn append_with_stream<S: AsRef<str>>(&mut self, filename: S) -> FtpResult<DataStream<T>> {
debug!("Appending to file {}", filename.as_ref());
let stream = self.data_command(Command::Appe(filename.as_ref().to_string()))?;
self.read_response_in(&[Status::AlreadyOpen, Status::AboutToSend])?;
Ok(stream)
}
/// Append data from reader to file at `filename`
pub fn append_file<R: Read>(&mut self, filename: &str, r: &mut R) -> FtpResult<u64> {
// Get stream
let mut data_stream = self.append_with_stream(filename)?;
let bytes = copy(r, &mut data_stream).map_err(FtpError::ConnectionError)?;
self.finalize_put_stream(Box::new(data_stream))?;
Ok(bytes)
}
/// abort the previous FTP service command
pub fn abort(&mut self, data_stream: impl Read + 'static) -> FtpResult<()> {
debug!("Aborting active file transfer");
self.perform(Command::Abor)?;
// Drop stream NOTE: must be done first, otherwise server won't return any response
drop(data_stream);
trace!("dropped stream");
self.read_response_in(&[Status::ClosingDataConnection, Status::TransferAborted])?;
self.read_response(Status::ClosingDataConnection)?;
debug!("Transfer aborted");
Ok(())
}
/// Tell the server to resume the transfer from a certain offset. The offset indicates the amount of bytes to skip
/// from the beginning of the file.
/// the REST command does not actually initiate the transfer.
/// After issuing a REST command, the client must send the appropriate FTP command to transfer the file
///
/// It is possible to cancel the REST command, sending a REST command with offset 0
pub fn resume_transfer(&mut self, offset: usize) -> FtpResult<()> {
debug!("Requesting to resume transfer at offset {}", offset);
self.perform(Command::Rest(offset))?;
self.read_response(Status::RequestFilePending)?;
debug!("Resume transfer accepted");
Ok(())
}
/// Execute `LIST` command which returns the detailed file listing in human readable format.
/// If `pathname` is omited then the list of files in the current directory will be
/// returned otherwise it will the list of files on `pathname`.
///
/// ### Parse result
///
/// You can parse the output of this command with
///
/// ```rust
///
/// use std::str::FromStr;
/// use suppaftp::list::File;
///
/// let file: File = File::from_str("-rw-rw-r-- 1 0 1 8192 Nov 5 2018 omar.txt")
///
/// .unwrap();
/// ```
pub fn list(&mut self, pathname: Option<&str>) -> FtpResult<Vec<String>> {
debug!(
"Reading {} directory content",
pathname.unwrap_or("working")
);
self.stream_lines(
Command::List(pathname.map(|x| x.to_string())),
Status::AboutToSend,
)
}
/// Execute `NLST` command which returns the list of file names only.
/// If `pathname` is omited then the list of files in the current directory will be
/// returned otherwise it will the list of files on `pathname`.
pub fn nlst(&mut self, pathname: Option<&str>) -> FtpResult<Vec<String>> {
debug!(
"Getting file names for {} directory",
pathname.unwrap_or("working")
);
self.stream_lines(
Command::Nlst(pathname.map(|x| x.to_string())),
Status::AboutToSend,
)
}
/// Execute `MLSD` command which returns the machine-processable listing of a directory.
/// If `pathname` is omited then the list of files in the current directory will be
pub fn mlsd(&mut self, pathname: Option<&str>) -> FtpResult<Vec<String>> {
debug!(
"Reading {} directory content",
pathname.unwrap_or("working")
);
self.stream_lines(
Command::Mlsd(pathname.map(|x| x.to_string())),
Status::AboutToSend,
)
}
/// Execute `MLST` command which returns the machine-processable listing of a file.
/// If `pathname` is omited then the list of files in the current directory will be
pub fn mlst(&mut self, pathname: Option<&str>) -> FtpResult<String> {
debug!("Reading {} path information", pathname.unwrap_or("working"));
self.perform(Command::Mlst(pathname.map(|x| x.to_string())))?;
let response = self.read_response_in(&[Status::RequestedFileActionOk])?;
// read body at line 1
let response_str = String::from_utf8_lossy(&response.body).to_string();
match response_str.lines().nth(1) {
Some("") => Err(FtpError::BadResponse),
Some(line) => Ok(line.trim().to_string()),
None => Err(FtpError::BadResponse),
}
}
/// Retrieves the modification time of the file at `pathname` if it exists.
pub fn mdtm<S: AsRef<str>>(&mut self, pathname: S) -> FtpResult<NaiveDateTime> {
debug!("Getting modification time for {}", pathname.as_ref());
self.perform(Command::Mdtm(pathname.as_ref().to_string()))?;
let response: Response = self.read_response(Status::File)?;
let body = response.as_string().map_err(|_| FtpError::BadResponse)?;
match MDTM_RE.captures(&body) {
Some(caps) => {
let (year, month, day) = (
caps[1].parse::<i32>().unwrap(),
caps[2].parse::<u32>().unwrap(),
caps[3].parse::<u32>().unwrap(),
);
let (hour, minute, second) = (
caps[4].parse::<u32>().unwrap(),
caps[5].parse::<u32>().unwrap(),
caps[6].parse::<u32>().unwrap(),
);
let date = match NaiveDate::from_ymd_opt(year, month, day) {
Some(d) => d,
None => return Err(FtpError::BadResponse),
};
let time = match NaiveTime::from_hms_opt(hour, minute, second) {
Some(t) => t,
None => return Err(FtpError::BadResponse),
};
Ok(NaiveDateTime::new(date, time))
}
None => Err(FtpError::BadResponse),
}
}
/// Retrieves the size of the file in bytes at `pathname` if it exists.
pub fn size<S: AsRef<str>>(&mut self, pathname: S) -> FtpResult<usize> {
debug!("Getting file size for {}", pathname.as_ref());
self.perform(Command::Size(pathname.as_ref().to_string()))?;
let response: Response = self.read_response(Status::File)?;
let body = response.as_string().map_err(|_| FtpError::BadResponse)?;
match SIZE_RE.captures(&body) {
Some(caps) => Ok(caps[1].parse().unwrap()),
None => Err(FtpError::BadResponse),
}
}
/// Retrieves the features supported by the server, through the FEAT command.
pub fn feat(&mut self) -> FtpResult<Features> {
debug!("Getting server supported features");
self.perform(Command::Feat)?;
self.read_response(Status::System)?;
let mut supported_features = Features::default();
loop {
let mut line = Vec::new();
self.read_line(&mut line)?;
let line = String::from_utf8_lossy(&line);
if line.starts_with(' ') {
let mut feature_line = line.trim().split(' ');
let feature_name = feature_line.next();
let feature_values = match feature_line.collect::<Vec<&str>>().join(" ") {
values if values.is_empty() => None,
values => Some(values),
};
if let Some(feature_name) = feature_name {
debug!("found supported feature: {feature_name}: {feature_values:?}");
supported_features.insert(feature_name.to_string(), feature_values);
}
} else {
break;
}
}
Ok(supported_features)
}
/// Set option `option` with an optional value
pub fn opts(&mut self, option: impl ToString, value: Option<impl ToString>) -> FtpResult<()> {
debug!("Getting server supported features");
self.perform(Command::Opts(
option.to_string(),
value.map(|x| x.to_string()),
))?;
self.read_response(Status::CommandOk)?;
Ok(())
}
/// Execute a command on the server and return the response
pub fn site(&mut self, command: impl ToString) -> FtpResult<Response> {
debug!("Sending SITE command: {}", command.to_string());
self.perform(Command::Site(command.to_string()))?;
self.read_response(Status::CommandOk)
}
/// Perform custom command
pub fn custom_command(
&mut self,
command: impl ToString,
expected_code: &[Status],
) -> FtpResult<Response> {
let command = command.to_string();
debug!("Sending custom command: {}", command);
self.perform(Command::Custom(command))?;
self.read_response_in(expected_code)
}
// -- private
/// Retrieve stream "message"
fn get_lines_from_stream(data_stream: &mut BufReader<DataStream<T>>) -> FtpResult<Vec<String>> {
let mut lines: Vec<String> = Vec::new();
loop {
let mut line = String::new();
match data_stream.read_line(&mut line) {
Ok(0) => break,
Ok(_) => {
if line.ends_with('\n') {
line.pop();
if line.ends_with('\r') {
line.pop();
}
}
if line.is_empty() {
continue;
}
lines.push(line);
}
Err(_) => return Err(FtpError::BadResponse),
}
}
trace!("Lines from stream {:?}", lines);
Ok(lines)
}
/// Read response from stream
fn read_response(&mut self, expected_code: Status) -> FtpResult<Response> {
self.read_response_in(&[expected_code])
}
/// Retrieve single line response
fn read_response_in(&mut self, expected_code: &[Status]) -> FtpResult<Response> {
let mut line = Vec::new();
let mut body: Vec<u8> = Vec::new();
self.read_line(&mut line)?;
body.extend(line.iter());
trace!("CC IN: {:?}", line);
if line.len() < 5 {
return Err(FtpError::BadResponse);
}
let code_word: u32 = self.code_from_buffer(&line, 3)?;
let code = Status::from(code_word);
trace!("Code parsed from response: {} ({})", code, code_word);
// multiple line reply
// loop while the line does not begin with the code and a space (or dash)
let expected = [line[0], line[1], line[2], 0x20];
let alt_expected = if expected_code.contains(&Status::System) {
[line[0], line[1], line[2], b'-']
} else {
expected
};
trace!("CC IN: {:?}", line);
while line.len() < 5 || (line[0..4] != expected && line[0..4] != alt_expected) {
line.clear();
self.read_line(&mut line)?;
body.extend(line.iter());
trace!("CC IN: {:?}", line);
}
let response: Response = Response::new(code, body);
// Return Ok or error with response
if expected_code.iter().any(|ec| code == *ec) {
Ok(response)
} else {
Err(FtpError::UnexpectedResponse(response))
}
}
/// Read bytes from reader until 0x0A or EOF is found
fn read_line(&mut self, line: &mut Vec<u8>) -> FtpResult<usize> {
self.reader
.read_until(0x0A, line.as_mut())
.map_err(FtpError::ConnectionError)?;
Ok(line.len())
}
/// Get code from buffer
fn code_from_buffer(&self, buf: &[u8], len: usize) -> Result<u32, FtpError> {
if buf.len() < len {
return Err(FtpError::BadResponse);
}
let buffer = buf[0..len].to_vec();
let as_string = String::from_utf8(buffer).map_err(|_| FtpError::BadResponse)?;
as_string.parse::<u32>().map_err(|_| FtpError::BadResponse)
}
/// Write data to stream with command to perform
fn perform(&mut self, command: Command) -> FtpResult<()> {
let command = command.to_string();
trace!("CC OUT: {}", command.trim_end_matches("\r\n"));
let stream = self.reader.get_mut();
stream
.write_all(command.as_bytes())
.map_err(FtpError::ConnectionError)
}
/// Execute command which send data back in a separate stream
fn data_command(&mut self, cmd: Command) -> FtpResult<DataStream<T>> {
let stream = match self.mode {
Mode::Active => self
.active()
.and_then(|listener| self.perform(cmd).map(|_| listener))
.and_then(|listener| {
let start = Instant::now();
loop {
match listener.accept() {
Ok((stream, _)) => break Ok(stream),
Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => {
if start.elapsed() > self.active_timeout {
break Err(FtpError::ConnectionError(
std::io::ErrorKind::WouldBlock.into(),
));
}
std::thread::sleep(Duration::from_millis(100));
}
Err(e) => break Err(FtpError::ConnectionError(e)),
}
}
})?,
Mode::ExtendedPassive => self
.epsv()
.and_then(|addr| self.perform(cmd).map(|_| addr))
.and_then(|addr| TcpStream::connect(addr).map_err(FtpError::ConnectionError))?,
Mode::Passive => self
.pasv()
.and_then(|addr| self.perform(cmd).map(|_| addr))
.and_then(|addr| TcpStream::connect(addr).map_err(FtpError::ConnectionError))?,
};
#[cfg(not(feature = "secure"))]
{
Ok(DataStream::Tcp(stream))
}
#[cfg(feature = "secure")]
match self.tls_ctx {
Some(ref tls_ctx) => tls_ctx
.connect(self.domain.as_ref().unwrap(), stream)
.map(|x| DataStream::Ssl(Box::new(x)))
.map_err(|e| FtpError::SecureError(format!("{e}"))),
None => Ok(DataStream::Tcp(stream)),
}
}
/// Create a new tcp listener and send a PORT command for it
fn active(&mut self) -> FtpResult<TcpListener> {
debug!("Starting local tcp listener...");
let conn = TcpListener::bind("0.0.0.0:0").map_err(FtpError::ConnectionError)?;
conn.set_nonblocking(true)
.map_err(FtpError::ConnectionError)?;
let addr = conn.local_addr().map_err(FtpError::ConnectionError)?;
trace!("Local address is {}", addr);
let ip = match self.reader.get_mut() {
DataStream::Tcp(stream) => stream.local_addr().unwrap().ip(),
DataStream::Ssl(stream) => stream.get_ref().local_addr().unwrap().ip(),
};
let msb = addr.port() / 256;
let lsb = addr.port() % 256;
let ip_port = format!("{},{},{}", ip.to_string().replace('.', ","), msb, lsb);
debug!("Active mode, listening on {}:{}", ip, addr.port());
debug!("Running PORT command");
self.perform(Command::Port(ip_port))?;
self.read_response(Status::CommandOk)?;
Ok(conn)
}
/// Runs the EPSV to enter Extended passive mode.
fn epsv(&mut self) -> FtpResult<SocketAddr> {
debug!("EPSV command");
self.perform(Command::Epsv)?;
// PASV response format : 229 Entering Extended Passive Mode (|||PORT|)
let response: Response = self.read_response(Status::ExtendedPassiveMode)?;
let response_str = response.as_string().map_err(|_| FtpError::BadResponse)?;
let caps = EPSV_PORT_RE
.captures(&response_str)
.ok_or_else(|| FtpError::UnexpectedResponse(response.clone()))?;
let new_port = caps[1].parse::<u16>().unwrap();
trace!("Got port number from EPSV: {}", new_port);
let mut remote = self
.reader
.get_ref()
.get_ref()
.peer_addr()
.map_err(FtpError::ConnectionError)?;
remote.set_port(new_port);
trace!("Remote address for extended passive mode is {}", remote);
Ok(remote)
}
/// Runs the PASV command to enter passive mode.
fn pasv(&mut self) -> FtpResult<SocketAddr> {
debug!("PASV command");
self.perform(Command::Pasv)?;
// PASV response format : 227 Entering Passive Mode (h1,h2,h3,h4,p1,p2).
let response: Response = self.read_response(Status::PassiveMode)?;
let response_str = response.as_string().map_err(|_| FtpError::BadResponse)?;
let caps = PASV_PORT_RE
.captures(&response_str)
.ok_or_else(|| FtpError::UnexpectedResponse(response.clone()))?;
// If the regex matches we can be sure groups contains numbers
let (oct1, oct2, oct3, oct4) = (
caps[1].parse::<u8>().unwrap(),
caps[2].parse::<u8>().unwrap(),
caps[3].parse::<u8>().unwrap(),
caps[4].parse::<u8>().unwrap(),
);
let (msb, lsb) = (
caps[5].parse::<u8>().unwrap(),
caps[6].parse::<u8>().unwrap(),
);
let ip = Ipv4Addr::new(oct1, oct2, oct3, oct4);
let port = (u16::from(msb) << 8) | u16::from(lsb);
let addr = SocketAddr::new(ip.into(), port);
trace!("Passive address: {}", addr);
if self.nat_workaround && ip.is_private() {
let mut remote = self
.reader
.get_ref()
.get_ref()
.peer_addr()
.map_err(FtpError::ConnectionError)?;
remote.set_port(port);
trace!("Replacing site local address {} with {}", addr, remote);
Ok(remote)
} else {
Ok(addr)
}
}
/// Execute a command which returns list of strings in a separate stream
fn stream_lines(&mut self, cmd: Command, open_code: Status) -> FtpResult<Vec<String>> {
let mut data_stream = BufReader::new(self.data_command(cmd)?);
self.read_response_in(&[open_code, Status::AlreadyOpen])?;
let lines = Self::get_lines_from_stream(&mut data_stream);
self.finalize_retr_stream(data_stream)?;
lines
}
}
#[cfg(test)]
mod test {
#[cfg(any(feature = "with-containers", feature = "secure"))]