forked from jonhoo/rust-imap
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.rs
More file actions
3116 lines (2910 loc) · 122 KB
/
client.rs
File metadata and controls
3116 lines (2910 loc) · 122 KB
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
use base64::{engine::general_purpose, Engine as _};
use bufstream::BufStream;
use chrono::{DateTime, FixedOffset};
use imap_proto::Response;
use std::collections::HashSet;
use std::collections::VecDeque;
use std::io::{Read, Write};
use std::ops::{Deref, DerefMut};
use std::str;
use super::authenticator::Authenticator;
use super::error::{Bad, Bye, Error, No, ParseError, Result, TagMismatch, ValidateError};
use super::extensions;
use super::parse::*;
use super::types::*;
use super::utils::*;
#[cfg(doc)]
use imap_proto::NameAttribute;
static TAG_PREFIX: &str = "a";
const INITIAL_TAG: u32 = 0;
const CR: u8 = 0x0d;
const LF: u8 = 0x0a;
macro_rules! quote {
($x:expr) => {
format!("\"{}\"", $x.replace(r"\", r"\\").replace("\"", "\\\""))
};
}
trait OptionExt<E> {
fn err(self) -> std::result::Result<(), E>;
}
impl<E> OptionExt<E> for Option<E> {
fn err(self) -> std::result::Result<(), E> {
match self {
Some(e) => Err(e),
None => Ok(()),
}
}
}
/// Convert the input into what [the IMAP
/// grammar](https://tools.ietf.org/html/rfc3501#section-9)
/// calls "quoted", which is reachable from "string" et al.
/// Also ensure it doesn't contain a colliding command-delimiter (newline).
///
/// The arguments `synopsis` and `arg_name` are used to construct the error message of
/// [ValidateError] in case validation fails.
pub(crate) fn validate_str(
synopsis: impl Into<String>,
arg_name: impl Into<String>,
value: &str,
) -> Result<String> {
validate_str_noquote(synopsis, arg_name, value)?;
Ok(quote!(value))
}
/// Ensure the input doesn't contain a command-terminator (newline), but don't quote it like
/// `validate_str`.
/// This is helpful for things like the FETCH attributes, which,
/// per [the IMAP grammar](https://tools.ietf.org/html/rfc3501#section-9) may not be quoted:
///
/// > fetch = "FETCH" SP sequence-set SP ("ALL" / "FULL" / "FAST" /
/// > fetch-att / "(" fetch-att *(SP fetch-att) ")")
/// >
/// > fetch-att = "ENVELOPE" / "FLAGS" / "INTERNALDATE" /
/// > "RFC822" [".HEADER" / ".SIZE" / ".TEXT"] /
/// > "BODY" ["STRUCTURE"] / "UID" /
/// > "BODY" section ["<" number "." nz-number ">"] /
/// > "BODY.PEEK" section ["<" number "." nz-number ">"]
///
/// Note the lack of reference to any of the string-like rules or the quote characters themselves.
///
/// The arguments `synopsis` and `arg_name` are used to construct the error message of
/// [ValidateError] in case validation fails.
fn validate_str_noquote(
synopsis: impl Into<String>,
arg_name: impl Into<String>,
value: &str,
) -> Result<&str> {
value
.matches(|c| c == '\n' || c == '\r')
.next()
.and_then(|s| s.chars().next())
.err()
.map_err(|c| {
Error::Validate(ValidateError {
command_synopsis: synopsis.into(),
argument: arg_name.into(),
offending_char: c,
})
})?;
Ok(value)
}
/// This ensures the input doesn't contain a command-terminator or any other whitespace
/// while leaving it not-quoted.
/// This is needed because, per [the formal grammar given in RFC
/// 3501](https://tools.ietf.org/html/rfc3501#section-9), a sequence set consists of the following:
///
/// > sequence-set = (seq-number / seq-range) *("," sequence-set)
/// > seq-range = seq-number ":" seq-number
/// > seq-number = nz-number / "*"
/// > nz-number = digit-nz *DIGIT
/// > digit-nz = %x31-39
///
/// Note the lack of reference to SP or any other such whitespace terminals.
/// Per this grammar, in theory we ought to be even more restrictive than "no whitespace".
fn validate_sequence_set(
synopsis: impl Into<String>,
arg_name: impl Into<String>,
value: &str,
) -> Result<&str> {
value
.matches(|c: char| c.is_ascii_whitespace())
.next()
.and_then(|s| s.chars().next())
.err()
.map_err(|c| {
Error::Validate(ValidateError {
command_synopsis: synopsis.into(),
argument: arg_name.into(),
offending_char: c,
})
})?;
Ok(value)
}
/// An authenticated IMAP session providing the usual IMAP commands. This type is what you get from
/// a successful login attempt.
///
/// Note that the server *is* allowed to unilaterally send things to the client for messages in
/// a selected mailbox whose status has changed. See the note on [unilateral server responses
/// in RFC 3501](https://tools.ietf.org/html/rfc3501#section-7). Any such messages are parsed out
/// and sent on `Session::unsolicited_responses`.
// Both `Client` and `Session` deref to [`Connection`](struct.Connection.html), the underlying
// primitives type.
#[derive(Debug)]
pub struct Session<T: Read + Write> {
conn: Connection<T>,
/// Server responses that are not related to the current command. See also the note on
/// [unilateral server responses in RFC 3501](https://tools.ietf.org/html/rfc3501#section-7).
pub(crate) unsolicited_responses: VecDeque<UnsolicitedResponse>,
}
/// An (unauthenticated) handle to talk to an IMAP server. This is what you get when first
/// connecting. A successful call to [`Client::login`] or [`Client::authenticate`] will return a
/// [`Session`] instance that provides the usual IMAP methods.
// Both `Client` and `Session` deref to [`Connection`](struct.Connection.html), the underlying
// primitives type.
#[derive(Debug)]
pub struct Client<T: Read + Write> {
conn: Connection<T>,
}
/// The underlying primitives type. Both `Client`(unauthenticated) and `Session`(after successful
/// login) use a `Connection` internally for the TCP stream primitives.
#[derive(Debug)]
#[doc(hidden)]
pub struct Connection<T: Read + Write> {
pub(crate) stream: BufStream<T>,
tag: u32,
/// Enable debug mode for this connection so that all client-server interactions are printed to
/// `STDERR`.
pub debug: bool,
/// Tracks if we have read a greeting.
pub greeting_read: bool,
}
impl<T: Read + Write> Connection<T> {
/// Manually increment the current tag.
///
/// If writing a command to the server fails, [`Client`] assumes that the command did not reach
/// the server, and thus that the next tag that should be sent is still the one used for the
/// failed command. However, it could be the case that the command _did_ reach the server
/// before failing, and thus a fresh tag needs to be issued instead.
///
/// This function can be used to attempt to manually re-synchronize the client's tag tracker in
/// such cases. It forcibly increments the client's tag counter such that the next command
/// sent to the server will have a tag that is one greater than it otherwise would.
pub fn skip_tag(&mut self) {
self.tag += 1;
}
}
/// A builder for the append command
#[must_use]
pub struct AppendCmd<'a, T: Read + Write> {
session: &'a mut Session<T>,
content: &'a [u8],
mailbox: &'a str,
flags: Vec<Flag<'a>>,
date: Option<DateTime<FixedOffset>>,
}
impl<'a, T: Read + Write> AppendCmd<'a, T> {
/// The [`APPEND` command](https://tools.ietf.org/html/rfc3501#section-6.3.11) can take
/// an optional FLAGS parameter to set the flags on the new message.
///
/// > If a flag parenthesized list is specified, the flags SHOULD be set
/// > in the resulting message; otherwise, the flag list of the
/// > resulting message is set to empty by default. In either case, the
/// > Recent flag is also set.
///
/// The [`\Recent` flag](https://tools.ietf.org/html/rfc3501#section-2.3.2) is not
/// allowed as an argument to `APPEND` and will be filtered out if present in `flags`.
pub fn flag(&mut self, flag: Flag<'a>) -> &mut Self {
self.flags.push(flag);
self
}
/// Set multiple flags at once.
pub fn flags(&mut self, flags: impl IntoIterator<Item = Flag<'a>>) -> &mut Self {
self.flags.extend(flags);
self
}
/// Pass a date in order to set the date that the message was originally sent.
///
/// > If a date-time is specified, the internal date SHOULD be set in
/// > the resulting message; otherwise, the internal date of the
/// > resulting message is set to the current date and time by default.
pub fn internal_date(&mut self, date: DateTime<FixedOffset>) -> &mut Self {
self.date = Some(date);
self
}
/// Finishes up the command and executes it.
///
/// Note: be sure to set flags and optional date before you
/// finish the command.
pub fn finish(&mut self) -> Result<Appended> {
let flagstr = iter_join(self.flags.iter().filter(|f| **f != Flag::Recent), " ");
let datestr = if let Some(date) = self.date {
format!(" \"{}\"", date.format("%d-%h-%Y %T %z"))
} else {
"".to_string()
};
self.session.run_command(&format!(
"APPEND \"{}\" ({}){} {{{}}}",
self.mailbox,
flagstr,
datestr,
self.content.len()
))?;
let mut v = Vec::new();
self.session.readline(&mut v)?;
if !v.starts_with(b"+") {
return Err(Error::Append);
}
self.session.stream.write_all(self.content)?;
self.session.stream.write_all(b"\r\n")?;
self.session.stream.flush()?;
self.session
.read_response()
.and_then(|(lines, _)| parse_append(&lines, &mut self.session.unsolicited_responses))
}
}
// `Deref` instances are so we can make use of the same underlying primitives in `Client` and
// `Session`
impl<T: Read + Write> Deref for Client<T> {
type Target = Connection<T>;
fn deref(&self) -> &Connection<T> {
&self.conn
}
}
impl<T: Read + Write> DerefMut for Client<T> {
fn deref_mut(&mut self) -> &mut Connection<T> {
&mut self.conn
}
}
impl<T: Read + Write> Deref for Session<T> {
type Target = Connection<T>;
fn deref(&self) -> &Connection<T> {
&self.conn
}
}
impl<T: Read + Write> DerefMut for Session<T> {
fn deref_mut(&mut self) -> &mut Connection<T> {
&mut self.conn
}
}
// As the pattern of returning the unauthenticated `Client` (a.k.a. `self`) back with a login error
// is relatively common, it's abstracted away into a macro here.
//
// Note: 1) using `.map_err(|e| (e, self))` or similar here makes the closure own self, so we can't
// do that.
// 2) in theory we wouldn't need the second parameter, and could just use the identifier
// `self` from the surrounding function, but being explicit here seems a lot cleaner.
macro_rules! ok_or_unauth_client_err {
($r:expr, $self:expr) => {
match $r {
Ok(o) => o,
Err(e) => return Err((e, $self)),
}
};
}
impl<T: Read + Write> Client<T> {
/// Creates a new client over the given stream.
///
/// This method primarily exists for writing tests that mock the underlying transport,
/// but can also be used to support IMAP over custom tunnels. If you do not need to do
/// that, then it is simpler to use the [`ClientBuilder`](crate::ClientBuilder) to get
/// a new client.
///
/// For an example, see `examples/timeout.rs` which uses a custom timeout on the
/// tcp stream.
///
/// **Note:** In case you do need to use `Client::new` instead of the `ClientBuilder`
/// you will need to listen for the IMAP protocol server greeting before authenticating:
///
/// ```rust,no_run
/// # use imap::Client;
/// # use std::io;
/// # use std::net::TcpStream;
/// # {} #[cfg(feature = "native-tls")]
/// # fn main() {
/// # let server = "imap.example.com";
/// # let username = "";
/// # let password = "";
/// # let tcp = TcpStream::connect((server, 993)).unwrap();
/// # use native_tls::TlsConnector;
/// # let ssl_connector = TlsConnector::builder().build().unwrap();
/// # let tls = TlsConnector::connect(&ssl_connector, server.as_ref(), tcp).unwrap();
/// let mut client = Client::new(tls);
/// client.read_greeting().unwrap();
/// let session = client.login(username, password).unwrap();
/// # }
/// ```
pub fn new(stream: T) -> Client<T> {
Client {
conn: Connection {
stream: BufStream::new(stream),
tag: INITIAL_TAG,
debug: false,
greeting_read: false,
},
}
}
/// Yield the underlying connection for this Client.
///
/// This consumes `self` since the Client is not much use without
/// an underlying transport.
pub fn into_inner(self) -> Result<T> {
let res = self.conn.stream.into_inner()?;
Ok(res)
}
/// The [`CAPABILITY` command](https://tools.ietf.org/html/rfc3501#section-6.1.1) requests a
/// listing of capabilities that the server supports. The server will include "IMAP4rev1" as
/// one of the listed capabilities. See [`Capabilities`] for further details.
///
/// This allows reading capabilities before authentication.
pub fn capabilities(&mut self) -> Result<Capabilities> {
// Create a temporary vec deque as we do not care about out of band responses before login
let mut unsolicited_responses = VecDeque::new();
self.run_command_and_read_response("CAPABILITY")
.and_then(|lines| Capabilities::parse(lines, &mut unsolicited_responses))
}
/// Log in to the IMAP server. Upon success a [`Session`](struct.Session.html) instance is
/// returned; on error the original `Client` instance is returned in addition to the error.
/// This is because `login` takes ownership of `self`, so in order to try again (e.g. after
/// prompting the user for credentials), ownership of the original `Client` needs to be
/// transferred back to the caller.
///
/// ```rust,no_run
/// # {} #[cfg(feature = "native-tls")]
/// # fn main() {
/// let client = imap::ClientBuilder::new("imap.example.org", 993)
/// .connect().unwrap();
///
/// match client.login("user", "pass") {
/// Ok(s) => {
/// // you are successfully authenticated!
/// },
/// Err((e, orig_client)) => {
/// eprintln!("error logging in: {}", e);
/// // prompt user and try again with orig_client here
/// return;
/// }
/// }
/// # }
/// ```
pub fn login(
mut self,
username: impl AsRef<str>,
password: impl AsRef<str>,
) -> ::std::result::Result<Session<T>, (Error, Client<T>)> {
let synopsis = "LOGIN";
let u =
ok_or_unauth_client_err!(validate_str(synopsis, "username", username.as_ref()), self);
let p =
ok_or_unauth_client_err!(validate_str(synopsis, "password", password.as_ref()), self);
ok_or_unauth_client_err!(
self.run_command_and_check_ok(&format!("LOGIN {} {}", u, p)),
self
);
Ok(Session::new(self.conn))
}
/// Authenticate with the server using the given custom `authenticator` to handle the server's
/// challenge.
///
/// ```no_run
/// struct OAuth2 {
/// user: String,
/// access_token: String,
/// }
///
/// impl imap::Authenticator for OAuth2 {
/// type Response = String;
/// fn process(&self, _: &[u8]) -> Self::Response {
/// format!(
/// "user={}\x01auth=Bearer {}\x01\x01",
/// self.user, self.access_token
/// )
/// }
/// }
///
/// # {} #[cfg(feature = "native-tls")]
/// fn main() {
/// let auth = OAuth2 {
/// user: String::from("me@example.com"),
/// access_token: String::from("<access_token>"),
/// };
/// let client = imap::ClientBuilder::new("imap.example.com", 993).connect()
/// .expect("Could not connect to server");
///
/// match client.authenticate("XOAUTH2", &auth) {
/// Ok(session) => {
/// // you are successfully authenticated!
/// },
/// Err((e, orig_client)) => {
/// eprintln!("error authenticating: {}", e);
/// // prompt user and try again with orig_client here
/// return;
/// }
/// };
/// }
/// ```
pub fn authenticate<A: Authenticator>(
mut self,
auth_type: impl AsRef<str>,
authenticator: &A,
) -> ::std::result::Result<Session<T>, (Error, Client<T>)> {
ok_or_unauth_client_err!(
self.run_command(&format!("AUTHENTICATE {}", auth_type.as_ref())),
self
);
self.do_auth_handshake(authenticator)
}
/// This func does the handshake process once the authenticate command is made.
fn do_auth_handshake<A: Authenticator>(
mut self,
authenticator: &A,
) -> ::std::result::Result<Session<T>, (Error, Client<T>)> {
// TODO Clean up this code
loop {
let mut line = Vec::new();
// explicit match blocks necessary to convert error to tuple and not bind self too
// early (see also comment on `login`)
ok_or_unauth_client_err!(self.readline(&mut line), self);
// ignore server comments
if line.starts_with(b"* ") {
continue;
}
// Some servers will only send `+\r\n`.
if line.starts_with(b"+ ") || &line == b"+\r\n" {
let challenge = if &line == b"+\r\n" {
Vec::new()
} else {
let line_str = ok_or_unauth_client_err!(
match str::from_utf8(line.as_slice()) {
Ok(line_str) => Ok(line_str),
Err(e) => Err(Error::Parse(ParseError::DataNotUtf8(line, e))),
},
self
);
let data =
ok_or_unauth_client_err!(parse_authenticate_response(line_str), self);
ok_or_unauth_client_err!(
general_purpose::STANDARD_NO_PAD
.decode(data)
.map_err(|e| Error::Parse(ParseError::Authentication(
data.to_string(),
Some(e)
))),
self
)
};
let raw_response = &authenticator.process(&challenge);
let auth_response = general_purpose::STANDARD_NO_PAD.encode(raw_response);
ok_or_unauth_client_err!(
self.write_line(auth_response.into_bytes().as_slice()),
self
);
} else {
ok_or_unauth_client_err!(self.read_response_onto(&mut line), self);
return Ok(Session::new(self.conn));
}
}
}
}
impl<T: Read + Write> Session<T> {
// not public, just to avoid duplicating the channel creation code
fn new(conn: Connection<T>) -> Self {
Session {
conn,
unsolicited_responses: VecDeque::new(),
}
}
/// Takes all the unsolicited responses received thus far.
pub fn take_all_unsolicited(&mut self) -> impl ExactSizeIterator<Item = UnsolicitedResponse> {
std::mem::take(&mut self.unsolicited_responses).into_iter()
}
/// Selects a mailbox
///
/// The `SELECT` command selects a mailbox so that messages in the mailbox can be accessed.
/// Note that earlier versions of this protocol only required the FLAGS, EXISTS, and RECENT
/// untagged data; consequently, client implementations SHOULD implement default behavior for
/// missing data as discussed with the individual item.
///
/// Only one mailbox can be selected at a time in a connection; simultaneous access to multiple
/// mailboxes requires multiple connections. The `SELECT` command automatically deselects any
/// currently selected mailbox before attempting the new selection. Consequently, if a mailbox
/// is selected and a `SELECT` command that fails is attempted, no mailbox is selected.
///
/// Note that the server *is* allowed to unilaterally send things to the client for messages in
/// a selected mailbox whose status has changed. See the note on [unilateral server responses
/// in RFC 3501](https://tools.ietf.org/html/rfc3501#section-7). This means that if you use
/// [`Connection::run_command_and_read_response`], you *may* see additional untagged `RECENT`,
/// `EXISTS`, `FETCH`, and `EXPUNGE` responses. You can get them from the
/// `unsolicited_responses` channel of the [`Session`](struct.Session.html).
pub fn select(&mut self, mailbox_name: impl AsRef<str>) -> Result<Mailbox> {
self.run(&format!(
"SELECT {}",
validate_str("SELECT", "mailbox", mailbox_name.as_ref())?
))
.and_then(|(lines, _)| parse_mailbox(&lines[..], &mut self.unsolicited_responses))
}
/// The `EXAMINE` command is identical to [`Session::select`] and returns the same output;
/// however, the selected mailbox is identified as read-only. No changes to the permanent state
/// of the mailbox, including per-user state, will happen in a mailbox opened with `examine`;
/// in particular, messagess cannot lose [`Flag::Recent`] in an examined mailbox.
pub fn examine(&mut self, mailbox_name: impl AsRef<str>) -> Result<Mailbox> {
self.run(&format!(
"EXAMINE {}",
validate_str("EXAMINE", "mailbox", mailbox_name.as_ref())?
))
.and_then(|(lines, _)| parse_mailbox(&lines[..], &mut self.unsolicited_responses))
}
/// Fetch retrieves data associated with a set of messages in the mailbox.
///
/// Note that the server *is* allowed to unilaterally include `FETCH` responses for other
/// messages in the selected mailbox whose status has changed. See the note on [unilateral
/// server responses in RFC 3501](https://tools.ietf.org/html/rfc3501#section-7).
///
/// `query` is a list of "data items" (space-separated in parentheses if `>1`). There are three
/// "macro items" which specify commonly-used sets of data items, and can be used instead of
/// data items. A macro must be used by itself, and not in conjunction with other macros or
/// data items. They are:
///
/// - `ALL`: equivalent to: `(FLAGS INTERNALDATE RFC822.SIZE ENVELOPE)`
/// - `FAST`: equivalent to: `(FLAGS INTERNALDATE RFC822.SIZE)`
///
/// The currently defined data items that can be fetched are listed [in the
/// RFC](https://tools.ietf.org/html/rfc3501#section-6.4.5), but here are some common ones:
///
/// - `FLAGS`: The flags that are set for this message.
/// - `INTERNALDATE`: The internal date of the message.
/// - `BODY[<section>]`:
///
/// The text of a particular body section. The section specification is a set of zero or
/// more part specifiers delimited by periods. A part specifier is either a part number
/// (see RFC) or one of the following: `HEADER`, `HEADER.FIELDS`, `HEADER.FIELDS.NOT`,
/// `MIME`, and `TEXT`. An empty section specification (i.e., `BODY[]`) refers to the
/// entire message, including the header.
///
/// The `HEADER`, `HEADER.FIELDS`, and `HEADER.FIELDS.NOT` part specifiers refer to the
/// [RFC-2822](https://tools.ietf.org/html/rfc2822) header of the message or of an
/// encapsulated [MIME-IMT](https://tools.ietf.org/html/rfc2046)
/// MESSAGE/[RFC822](https://tools.ietf.org/html/rfc822) message. `HEADER.FIELDS` and
/// `HEADER.FIELDS.NOT` are followed by a list of field-name (as defined in
/// [RFC-2822](https://tools.ietf.org/html/rfc2822)) names, and return a subset of the
/// header. The subset returned by `HEADER.FIELDS` contains only those header fields with
/// a field-name that matches one of the names in the list; similarly, the subset returned
/// by `HEADER.FIELDS.NOT` contains only the header fields with a non-matching field-name.
/// The field-matching is case-insensitive but otherwise exact. Subsetting does not
/// exclude the [RFC-2822](https://tools.ietf.org/html/rfc2822) delimiting blank line
/// between the header and the body; the blank line is included in all header fetches,
/// except in the case of a message which has no body and no blank line.
///
/// The `MIME` part specifier refers to the [MIME-IMB](https://tools.ietf.org/html/rfc2045)
/// header for this part.
///
/// The `TEXT` part specifier refers to the text body of the message,
/// omitting the [RFC-2822](https://tools.ietf.org/html/rfc2822) header.
///
/// [`Flag::Seen`] is implicitly set when `BODY` is fetched; if this causes the flags to
/// change, they will generally be included as part of the `FETCH` responses.
/// - `BODY.PEEK[<section>]`: An alternate form of `BODY[<section>]` that does not implicitly
/// set [`Flag::Seen`].
/// - `ENVELOPE`: The envelope structure of the message. This is computed by the server by
/// parsing the [RFC-2822](https://tools.ietf.org/html/rfc2822) header into the component
/// parts, defaulting various fields as necessary.
/// - `RFC822`: Functionally equivalent to `BODY[]`.
/// - `RFC822.HEADER`: Functionally equivalent to `BODY.PEEK[HEADER]`.
/// - `RFC822.SIZE`: The [RFC-2822](https://tools.ietf.org/html/rfc2822) size of the message.
/// - `UID`: The unique identifier for the message.
pub fn fetch(
&mut self,
sequence_set: impl AsRef<str>,
query: impl AsRef<str>,
) -> Result<Fetches> {
if sequence_set.as_ref().is_empty() {
Fetches::parse(vec![], &mut self.unsolicited_responses)
} else {
let synopsis = "FETCH";
self.run_command_and_read_response(&format!(
"FETCH {} {}",
validate_sequence_set(synopsis, "seq", sequence_set.as_ref())?,
validate_str_noquote(synopsis, "query", query.as_ref())?
))
.and_then(|lines| Fetches::parse(lines, &mut self.unsolicited_responses))
}
}
/// Equivalent to [`Session::fetch`], except that all identifiers in `uid_set` are
/// [`Uid`]s. See also the [`UID` command](https://tools.ietf.org/html/rfc3501#section-6.4.8).
pub fn uid_fetch(
&mut self,
uid_set: impl AsRef<str>,
query: impl AsRef<str>,
) -> Result<Fetches> {
if uid_set.as_ref().is_empty() {
Fetches::parse(vec![], &mut self.unsolicited_responses)
} else {
let synopsis = "UID FETCH";
self.run_command_and_read_response(&format!(
"UID FETCH {} {}",
validate_sequence_set(synopsis, "seq", uid_set.as_ref())?,
validate_str_noquote(synopsis, "query", query.as_ref())?
))
.and_then(|lines| Fetches::parse(lines, &mut self.unsolicited_responses))
}
}
/// Noop always succeeds, and it does nothing.
pub fn noop(&mut self) -> Result<()> {
self.run_command_and_read_response("NOOP")
.and_then(|lines| parse_noop(lines, &mut self.unsolicited_responses))
}
/// Logout informs the server that the client is done with the connection.
pub fn logout(&mut self) -> Result<()> {
// Check for OK or BYE.
// According to the RFC:
// https://datatracker.ietf.org/doc/html/rfc3501#section-6.1.3
// We should get an untagged BYE and a tagged OK.
// Apparently some servers send a tagged BYE (imap.wp.pl #210)
// instead, so we just treat it like OK since we are logging out
// anyway and this avoids returning an error on logout.
match self.run_command_and_check_ok("LOGOUT") {
Ok(_) => Ok(()),
Err(Error::Bye(_)) => Ok(()),
resp => resp,
}
}
/// The [`CREATE` command](https://tools.ietf.org/html/rfc3501#section-6.3.3) creates a mailbox
/// with the given name. `Ok` is returned only if a new mailbox with that name has been
/// created. It is an error to attempt to create `INBOX` or a mailbox with a name that
/// refers to an extant mailbox. Any error in creation will return [`Error::No`].
///
/// If the mailbox name is suffixed with the server's hierarchy separator character (as
/// returned from the server by [`Session::list`]), this is a declaration that the client
/// intends to create mailbox names under this name in the hierarchy. Servers that do not
/// require this declaration will ignore the declaration. In any case, the name created is
/// without the trailing hierarchy delimiter.
///
/// If the server's hierarchy separator character appears elsewhere in the name, the server
/// will generally create any superior hierarchical names that are needed for the `CREATE`
/// command to be successfully completed. In other words, an attempt to create `foo/bar/zap`
/// on a server in which `/` is the hierarchy separator character will usually create `foo/`
/// and `foo/bar/` if they do not already exist.
///
/// If a new mailbox is created with the same name as a mailbox which was deleted, its unique
/// identifiers will be greater than any unique identifiers used in the previous incarnation of
/// the mailbox UNLESS the new incarnation has a different unique identifier validity value.
/// See the description of the [`UID`
/// command](https://tools.ietf.org/html/rfc3501#section-6.4.8) for more detail.
pub fn create(&mut self, mailbox_name: impl AsRef<str>) -> Result<()> {
self.run_command_and_check_ok(&format!(
"CREATE {}",
validate_str("CREATE", "mailbox", mailbox_name.as_ref())?
))
}
/// The [`DELETE` command](https://tools.ietf.org/html/rfc3501#section-6.3.4) permanently
/// removes the mailbox with the given name. `Ok` is returned only if the mailbox has been
/// deleted. It is an error to attempt to delete `INBOX` or a mailbox name that does not
/// exist.
///
/// The `DELETE` command will not remove inferior hierarchical names. For example, if a mailbox
/// `foo` has an inferior `foo.bar` (assuming `.` is the hierarchy delimiter character),
/// removing `foo` will not remove `foo.bar`. It is an error to attempt to delete a name that
/// has inferior hierarchical names and also has [`NameAttribute::NoSelect`].
///
/// It is permitted to delete a name that has inferior hierarchical names and does not have
/// [`NameAttribute::NoSelect`]. In this case, all messages in that mailbox are removed, and
/// the name will acquire [`NameAttribute::NoSelect`].
///
/// The value of the highest-used unique identifier of the deleted mailbox will be preserved so
/// that a new mailbox created with the same name will not reuse the identifiers of the former
/// incarnation, UNLESS the new incarnation has a different unique identifier validity value.
/// See the description of the [`UID`
/// command](https://tools.ietf.org/html/rfc3501#section-6.4.8) for more detail.
pub fn delete(&mut self, mailbox_name: impl AsRef<str>) -> Result<()> {
self.run_command_and_check_ok(&format!(
"DELETE {}",
validate_str("DELETE", "mailbox", mailbox_name.as_ref())?
))
}
/// The [`RENAME` command](https://tools.ietf.org/html/rfc3501#section-6.3.5) changes the name
/// of a mailbox. `Ok` is returned only if the mailbox has been renamed. It is an error to
/// attempt to rename from a mailbox name that does not exist or to a mailbox name that already
/// exists. Any error in renaming will return [`Error::No`].
///
/// If the name has inferior hierarchical names, then the inferior hierarchical names will also
/// be renamed. For example, a rename of `foo` to `zap` will rename `foo/bar` (assuming `/` is
/// the hierarchy delimiter character) to `zap/bar`.
///
/// If the server's hierarchy separator character appears in the name, the server will
/// generally create any superior hierarchical names that are needed for the `RENAME` command
/// to complete successfully. In other words, an attempt to rename `foo/bar/zap` to
/// `baz/rag/zowie` on a server in which `/` is the hierarchy separator character will
/// generally create `baz/` and `baz/rag/` if they do not already exist.
///
/// The value of the highest-used unique identifier of the old mailbox name will be preserved
/// so that a new mailbox created with the same name will not reuse the identifiers of the
/// former incarnation, UNLESS the new incarnation has a different unique identifier validity
/// value. See the description of the [`UID`
/// command](https://tools.ietf.org/html/rfc3501#section-6.4.8) for more detail.
///
/// Renaming `INBOX` is permitted, and has special behavior. It moves all messages in `INBOX`
/// to a new mailbox with the given name, leaving `INBOX` empty. If the server implementation
/// supports inferior hierarchical names of `INBOX`, these are unaffected by a rename of
/// `INBOX`.
pub fn rename(&mut self, from: impl AsRef<str>, to: impl AsRef<str>) -> Result<()> {
self.run_command_and_check_ok(&format!(
"RENAME {} {}",
quote!(from.as_ref()),
quote!(to.as_ref())
))
}
/// The [`SUBSCRIBE` command](https://tools.ietf.org/html/rfc3501#section-6.3.6) adds the
/// specified mailbox name to the server's set of "active" or "subscribed" mailboxes as
/// returned by [`Session::lsub`]. This command returns `Ok` only if the subscription is
/// successful.
///
/// The server may validate the mailbox argument to `SUBSCRIBE` to verify that it exists.
/// However, it will not unilaterally remove an existing mailbox name from the subscription
/// list even if a mailbox by that name no longer exists.
pub fn subscribe(&mut self, mailbox: impl AsRef<str>) -> Result<()> {
self.run_command_and_check_ok(&format!("SUBSCRIBE {}", quote!(mailbox.as_ref())))
}
/// The [`UNSUBSCRIBE` command](https://tools.ietf.org/html/rfc3501#section-6.3.7) removes the
/// specified mailbox name from the server's set of "active" or "subscribed" mailboxes as
/// returned by [`Session::lsub`]. This command returns `Ok` only if the unsubscription is
/// successful.
pub fn unsubscribe(&mut self, mailbox: impl AsRef<str>) -> Result<()> {
self.run_command_and_check_ok(&format!("UNSUBSCRIBE {}", quote!(mailbox.as_ref())))
}
/// The [`CAPABILITY` command](https://tools.ietf.org/html/rfc3501#section-6.1.1) requests a
/// listing of capabilities that the server supports. The server will include "IMAP4rev1" as
/// one of the listed capabilities. See [`Capabilities`] for further details.
pub fn capabilities(&mut self) -> Result<Capabilities> {
self.run_command_and_read_response("CAPABILITY")
.and_then(|lines| Capabilities::parse(lines, &mut self.unsolicited_responses))
}
/// The [`EXPUNGE` command](https://tools.ietf.org/html/rfc3501#section-6.4.3) permanently
/// removes all messages that have [`Flag::Deleted`] set from the currently selected mailbox.
/// The message sequence number of each message that is removed is returned.
pub fn expunge(&mut self) -> Result<Deleted> {
self.run_command("EXPUNGE")?;
self.read_response()
.and_then(|(lines, _)| parse_expunge(lines, &mut self.unsolicited_responses))
}
/// The [`UID EXPUNGE` command](https://tools.ietf.org/html/rfc4315#section-2.1) permanently
/// removes all messages that both have [`Flag::Deleted`] set and have a [`Uid`] that is
/// included in the specified sequence set from the currently selected mailbox. If a message
/// either does not have [`Flag::Deleted`] set or has a [`Uid`] that is not included in the
/// specified sequence set, it is not affected.
///
/// This command is particularly useful for disconnected use clients. By using `uid_expunge`
/// instead of [`expunge`](Session::expunge) when resynchronizing with the server, the client
/// can ensure that it does not inadvertently remove any messages that have been marked as
/// [`Flag::Deleted`] by other clients between the time that the client was last connected and
/// the time the client resynchronizes.
///
/// This command requires that the server supports [RFC
/// 4315](https://tools.ietf.org/html/rfc4315) as indicated by the `UIDPLUS` capability (see
/// [`Session::capabilities`]). If the server does not support the `UIDPLUS` capability, the
/// client should fall back to using [`Session::store`] to temporarily remove [`Flag::Deleted`]
/// from messages it does not want to remove, then invoking [`Session::expunge`]. Finally, the
/// client should use [`Session::store`] to restore [`Flag::Deleted`] on the messages in which
/// it was temporarily removed.
///
/// Alternatively, the client may fall back to using just [`Session::expunge`], risking the
/// unintended removal of some messages.
pub fn uid_expunge(&mut self, uid_set: impl AsRef<str>) -> Result<Deleted> {
self.run_command(&format!("UID EXPUNGE {}", uid_set.as_ref()))?;
self.read_response()
.and_then(|(lines, _)| parse_expunge(lines, &mut self.unsolicited_responses))
}
/// The [`CHECK` command](https://tools.ietf.org/html/rfc3501#section-6.4.1) requests a
/// checkpoint of the currently selected mailbox. A checkpoint refers to any
/// implementation-dependent housekeeping associated with the mailbox (e.g., resolving the
/// server's in-memory state of the mailbox with the state on its disk) that is not normally
/// executed as part of each command. A checkpoint MAY take a non-instantaneous amount of real
/// time to complete. If a server implementation has no such housekeeping considerations,
/// [`Session::check`] is equivalent to [`Session::noop`].
///
/// There is no guarantee that an `EXISTS` untagged response will happen as a result of
/// `CHECK`. [`Session::noop`] SHOULD be used for new message polling.
pub fn check(&mut self) -> Result<()> {
self.run_command_and_check_ok("CHECK")
}
/// The [`CLOSE` command](https://tools.ietf.org/html/rfc3501#section-6.4.2) permanently
/// removes all messages that have [`Flag::Deleted`] set from the currently selected mailbox,
/// and returns to the authenticated state from the selected state. No `EXPUNGE` responses are
/// sent.
///
/// No messages are removed, and no error is given, if the mailbox is selected by
/// [`Session::examine`] or is otherwise selected read-only.
///
/// Even if a mailbox is selected, [`Session::select`], [`Session::examine`], or
/// [`Session::logout`] command MAY be issued without previously invoking [`Session::close`].
/// [`Session::select`], [`Session::examine`], and [`Session::logout`] implicitly close the
/// currently selected mailbox without doing an expunge. However, when many messages are
/// deleted, a `CLOSE-LOGOUT` or `CLOSE-SELECT` sequence is considerably faster than an
/// `EXPUNGE-LOGOUT` or `EXPUNGE-SELECT` because no `EXPUNGE` responses (which the client would
/// probably ignore) are sent.
pub fn close(&mut self) -> Result<()> {
self.run_command_and_check_ok("CLOSE")
}
/// The [`STORE` command](https://tools.ietf.org/html/rfc3501#section-6.4.6) alters data
/// associated with a message in the mailbox. Normally, `STORE` will return the updated value
/// of the data with an untagged FETCH response. A suffix of `.SILENT` in `query` prevents the
/// untagged `FETCH`, and the server assumes that the client has determined the updated value
/// itself or does not care about the updated value.
///
/// The currently defined data items that can be stored are:
///
/// - `FLAGS <flag list>`:
///
/// Replace the flags for the message (other than [`Flag::Recent`]) with the argument. The
/// new value of the flags is returned as if a `FETCH` of those flags was done.
///
/// - `FLAGS.SILENT <flag list>`: Equivalent to `FLAGS`, but without returning a new value.
///
/// - `+FLAGS <flag list>`
///
/// Add the argument to the flags for the message. The new value of the flags is returned
/// as if a `FETCH` of those flags was done.
/// - `+FLAGS.SILENT <flag list>`: Equivalent to `+FLAGS`, but without returning a new value.
///
/// - `-FLAGS <flag list>`
///
/// Remove the argument from the flags for the message. The new value of the flags is
/// returned as if a `FETCH` of those flags was done.
///
/// - `-FLAGS.SILENT <flag list>`: Equivalent to `-FLAGS`, but without returning a new value.
///
/// In all cases, `<flag list>` is a space-separated list enclosed in parentheses.
///
/// # Examples
///
/// Delete a message:
///
/// ```rust,no_run
/// # extern crate imap;
/// # use imap::{self, Session};
/// # use std::net::TcpStream;
/// fn delete(seq: imap::types::Seq, s: &mut Session<TcpStream>) -> imap::error::Result<()> {
/// s.store(format!("{}", seq), "+FLAGS (\\Deleted)")?;
/// s.expunge()?;
/// Ok(())
/// }
/// ```
pub fn store(
&mut self,
sequence_set: impl AsRef<str>,
query: impl AsRef<str>,
) -> Result<Fetches> {
self.run_command_and_read_response(&format!(
"STORE {} {}",
sequence_set.as_ref(),
query.as_ref()
))
.and_then(|lines| Fetches::parse(lines, &mut self.unsolicited_responses))
}
/// Equivalent to [`Session::store`], except that all identifiers in `sequence_set` are
/// [`Uid`]s. See also the [`UID` command](https://tools.ietf.org/html/rfc3501#section-6.4.8).
pub fn uid_store(
&mut self,
uid_set: impl AsRef<str>,
query: impl AsRef<str>,
) -> Result<Fetches> {
self.run_command_and_read_response(&format!(
"UID STORE {} {}",
uid_set.as_ref(),
query.as_ref()
))
.and_then(|lines| Fetches::parse(lines, &mut self.unsolicited_responses))
}
/// The [`COPY` command](https://tools.ietf.org/html/rfc3501#section-6.4.7) copies the
/// specified message(s) to the end of the specified destination mailbox. The flags and
/// internal date of the message(s) will generally be preserved, and [`Flag::Recent`] will
/// generally be set, in the copy.
///
/// If the `COPY` command is unsuccessful for any reason, the server restores the destination
/// mailbox to its state before the `COPY` attempt.
pub fn copy(
&mut self,
sequence_set: impl AsRef<str>,
mailbox_name: impl AsRef<str>,
) -> Result<()> {
self.run_command_and_check_ok(&format!(
"COPY {} {}",
sequence_set.as_ref(),
mailbox_name.as_ref()
))
}
/// Equivalent to [`Session::copy`], except that all identifiers in `sequence_set` are
/// [`Uid`]s. See also the [`UID` command](https://tools.ietf.org/html/rfc3501#section-6.4.8).
pub fn uid_copy(
&mut self,
uid_set: impl AsRef<str>,
mailbox_name: impl AsRef<str>,
) -> Result<()> {
self.run_command_and_check_ok(&format!(
"UID COPY {} {}",
uid_set.as_ref(),
mailbox_name.as_ref()
))
}
/// The [`MOVE` command](https://tools.ietf.org/html/rfc6851#section-3.1) takes two
/// arguments: a sequence set and a named mailbox. Each message included in the set is moved,
/// rather than copied, from the selected (source) mailbox to the named (target) mailbox.
///
/// This means that a new message is created in the target mailbox with a
/// new [`Uid`], the original message is removed from the source mailbox, and
/// it appears to the client as a single action. This has the same
/// effect for each message as this sequence:
///
/// 1. COPY
/// 2. STORE +FLAGS.SILENT \DELETED
/// 3. EXPUNGE