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
use POP3StreamTypes::{Basic, Ssl};
use POP3Command::{Greet, User, Pass, Stat, UidlAll, UidlOne, ListAll, ListOne, Retr, Dele, Noop, Rset, Quit};
use std::string::String;
use async_std::net::{ToSocketAddrs,TcpStream};
use async_native_tls::{TlsStream, TlsConnector};
use std::str::FromStr;
use regex::Regex;
use lazy_static::lazy_static;
use async_std::io::{Error, ErrorKind, Result};
use async_std::prelude::*;

lazy_static! {
    static ref ENDING_REGEX: Regex = Regex::new(r"^\.\r\n$").unwrap();
    static ref OK_REGEX: Regex = Regex::new(r"\+OK(.*)").unwrap();
    static ref ERR_REGEX: Regex = Regex::new(r"-ERR(.*)").unwrap();
    static ref STAT_REGEX: Regex = Regex::new(r"\+OK (\d+) (\d+)\r\n").unwrap();
    static ref MESSAGE_DATA_UIDL_ALL_REGEX: Regex = Regex::new(r"(\d+) ([\x21-\x7e]+)\r\n").unwrap();
    static ref MESSAGE_DATA_UIDL_ONE_REGEX: Regex = Regex::new(r"\+OK (\d+) ([\x21-\x7e]+)\r\n").unwrap();
    static ref MESSAGE_DATA_LIST_ALL_REGEX: Regex = Regex::new(r"(\d+) (\d+)\r\n").unwrap();
}

/// Wrapper for a regular TcpStream or a SslStream.
#[derive(Debug)]
enum POP3StreamTypes {
	Basic(TcpStream),
	Ssl(TlsStream<TcpStream>)
}

/// The stream to use for interfacing with the POP3 Server.
#[derive(Debug)]
pub struct POP3Stream {
	stream: POP3StreamTypes,
	pub is_authenticated: bool
}

/// List of POP3 Commands
#[derive(Clone)]
enum POP3Command {
	Greet,
	User,
	Pass,
	Stat,
    UidlAll,
    UidlOne,
	ListAll,
	ListOne,
	Retr,
	Dele,
	Noop,
	Rset,
	Quit
}

impl POP3Stream {

	/// Creates a new POP3Stream.
	pub async fn connect<A:ToSocketAddrs>(addr: A,ssl_context: Option<TlsConnector>,domain: &str) -> Result<POP3Stream> {
		let tcp_stream = TcpStream::connect(addr).await?;
		let mut socket = match ssl_context {
			Some(context) => POP3Stream {
                stream: Ssl(TlsConnector::connect(&context, domain,tcp_stream).await.unwrap()),
                is_authenticated: false},
			None => POP3Stream {
                stream: Basic(tcp_stream),
                is_authenticated: false},
		};
		match socket.read_response(Greet).await {
			Ok(_) => (),
			Err(_) => return Err(Error::new(ErrorKind::Other, "Failed to read greet response"))
		}
		Ok(socket)
	}

	async fn write_str(&mut self, s: &str) -> Result<()> {
		match self.stream {
			Ssl(ref mut stream) => stream.write_fmt(format_args!("{}", s)).await,
			Basic(ref mut stream) => stream.write_fmt(format_args!("{}", s)).await,
		}
	}

	async fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
		match self.stream {
			Ssl(ref mut stream) => stream.read(buf).await,
			Basic(ref mut stream) => stream.read(buf).await,
		}
	}

	/// Login to the POP3 server.
	pub async fn login(&mut self, username: &str, password: &str) -> POP3Result {
		let user_command = format!("USER {}\r\n", username);
		let pass_command = format!("PASS {}\r\n", password);
		//Send user command
		match self.write_str(&user_command).await {
			Ok(_) => {},
			Err(_) => panic!("Error writing"),
		}
		match self.read_response(User).await {
			Ok(_) => {
				match self.write_str(&pass_command).await {
					Ok(_) => self.is_authenticated = true,
					Err(_) => panic!("Error writing"),
				}
				match self.read_response(Pass).await {
					Ok(_) => {
						POP3Result::POP3Ok
					},
					Err(_) => panic!("Failure to use PASS")
				}
			},
			Err(_) => panic!("Failure to use USER")
		}
	}

	/// Gives the current number of messages in the mailbox and the total size in bytes of the mailbox.
	pub async fn stat(&mut self) -> POP3Result {
		if !self.is_authenticated {
			panic!("login");
		}

		let stat_command = "STAT\r\n";
		match self.write_str(&stat_command).await {
			Ok(_) => {},
			Err(_) => panic!("Error writing"),
		}
		match self.read_response(Stat).await {
			Ok(res) => {
				match res.result {
					Some(s) => s,
					None => POP3Result::POP3Err
				}
			},
			Err(_) => POP3Result::POP3Err
		}
	}

    pub async fn uidl(&mut self, message_number: Option<i32>) -> POP3Result {
        if !self.is_authenticated {
            panic!("login");
        }

        let uidl_command = match message_number {
            Some(i) => format!("UIDL {}\r\n", i),
            None => format!("UIDL\r\n"),
        };
        let command_type = match message_number {
            Some(_) => UidlOne,
            None => UidlAll,
        };

        match self.write_str(&uidl_command).await {
            Ok(_) => {},
            Err(_) => panic!("Error writing"),
        }

        match self.read_response(command_type).await {
            Ok(res) => {
                match res.result {
                    Some(s) => s,
                    None => POP3Result::POP3Err
                }
            },
            Err(_) => POP3Result::POP3Err
        }
    }

	/// List displays a summary of messages where each message number is shown and the size of the message in bytes.
	pub async fn list(&mut self, message_number: Option<i32>) -> POP3Result {
		if !self.is_authenticated {
			panic!("login");
		}

		let list_command = match message_number {
							Some(i) => format!("LIST {}\r\n", i),
							None => format!("LIST\r\n"),
						};
		let command_type = match message_number {
							Some(_) => ListOne,
							None => ListAll,
						};

		match self.write_str(&list_command).await {
			Ok(_) => {},
			Err(_) => panic!("Error writing"),
		}

		match self.read_response(command_type).await {
			Ok(res) => {
				match res.result {
					Some(s) => s,
					None => POP3Result::POP3Err
				}
			},
			Err(_) => POP3Result::POP3Err
		}
	}

	/// retrieves the message of the message id given.
	pub async fn retr(&mut self, message_id: i32) -> POP3Result {
		if !self.is_authenticated {
			panic!("login");
		}

		let retr_command = format!("RETR {}\r\n", message_id);

		match self.write_str(&retr_command).await {
			Ok(_) => {},
			Err(_) => panic!("Error writing"),
		}

		match self.read_response(Retr).await {
			Ok(res) => {
				match res.result {
					Some(s) => s,
					None => POP3Result::POP3Err
				}
			},
			Err(_) => POP3Result::POP3Err
		}
	}

	/// Delete the message with the given message id.
	pub async fn dele(&mut self, message_id: i32) -> POP3Result {
		if !self.is_authenticated {
			panic!("login");
		}

		let dele_command = format!("DELE {}\r\n", message_id);

		match self.write_str(&dele_command).await {
			Ok(_) => {},
			Err(_) => panic!("Error writing"),
		}

		match self.read_response(Dele).await {
			Ok(res) => {
				match res.result {
					Some(s) => s,
					None => POP3Result::POP3Err
				}
			},
			Err(_) => POP3Result::POP3Err
		}
	}

	/// This resets the session to its original state.
	pub async fn rset(&mut self) -> POP3Result {
		if !self.is_authenticated {
			panic!("Not Logged In");
		}

		let retr_command = format!("RETR\r\n");

		match self.write_str(&retr_command).await {
			Ok(_) => {},
			Err(_) => panic!("Error writing"),
		}

		match self.read_response(Rset).await {
			Ok(res) => {
				match res.result {
					Some(s) => s,
					None => POP3Result::POP3Err
				}
			},
			Err(_) => POP3Result::POP3Err
		}
	}

	/// Quits the current session.
	pub async fn quit(&mut self) -> POP3Result {
		let quit_command = "QUIT\r\n";

		match self.write_str(&quit_command).await {
			Ok(_) => {},
			Err(_) => panic!("Error writing"),
		}

		match self.read_response(Quit).await {
			Ok(res) => {
				match res.result {
					Some(s) => s,
					None => POP3Result::POP3Err
				}
			},
			Err(_) => POP3Result::POP3Err
		}
	}

	/// Doesn't do anything. This is usually just used to keep the connection open.
	pub async fn noop(&mut self) -> POP3Result {
		if !self.is_authenticated {
			panic!("Not Logged In");
		}

		let noop_command = "noop\r\n";

		match self.write_str(noop_command).await {
			Ok(_) => {},
			Err(_) => panic!("Error writing"),
		}

		match self.read_response(Noop).await {
			Ok(res) => {
				match res.result {
					Some(s) => s,
					None => POP3Result::POP3Err
				}
			},
			Err(_) => panic!("Error noop")
		}
	}

	async fn read_response(&mut self, command: POP3Command) -> Result<Box<POP3Response>> {
		let mut response = Box::new(POP3Response::new());
		//Carriage return
		let cr = 0x0d;
		//Line Feed
		let lf = 0x0a;
		let mut line_buffer: Vec<u8> = Vec::new();

		while !response.complete {
			while line_buffer.len() < 2 || (line_buffer[line_buffer.len()-1] != lf && line_buffer[line_buffer.len()-2] != cr) {
				let byte_buffer: &mut [u8] = &mut [0];
				match self.read(byte_buffer).await {
					Ok(_) => {},
					Err(_) => println!("Error Reading!"),
				}
				line_buffer.push(byte_buffer[0]);
			}

			match String::from_utf8(line_buffer.clone()) {
        		Ok(res) => {
          			response.add_line(res, command.clone());
            		line_buffer = Vec::new();
        		},
        		Err(_) => return Err(Error::new(ErrorKind::Other, "Failed to read the response"))
      		}
		}
		Ok(response)
	}
}

#[derive(Clone,Copy,Debug)]
pub struct POP3EmailMetadata {
	pub message_id: i32,
	pub message_size: i32
}

#[derive(Clone,Debug)]
pub struct POP3EmailUidldata {
    pub message_id: i32,
    pub message_uid: String
}

#[derive(Debug)]
pub enum POP3Result {
	POP3Ok,
	POP3Err,
	POP3Stat {
		num_email: i32,
		mailbox_size: i32
	},
    POP3Uidl {
        emails_metadata: Vec<POP3EmailUidldata>,
    },
	POP3List {
		emails_metadata: Vec<POP3EmailMetadata>,
	},
	POP3Message {
		raw: Vec<String>,
	},
}

#[derive(Default)]
struct POP3Response {
	complete: bool,
	lines: Vec<String>,
	result: Option<POP3Result>
}

impl POP3Response {
	fn new() -> POP3Response {
		POP3Response {
			complete: false,
			lines: Vec::new(),
			result: None
		}
	}

	fn add_line(&mut self, line: String, command: POP3Command) {
		//We are retreiving status line
		if self.lines.len() == 0 {
			if OK_REGEX.is_match(&line) {
				self.lines.push(line);
				match command {
					Greet|User|Pass|Quit|Dele|Rset => {
						self.result = Some(POP3Result::POP3Ok);
						self.complete = true;
					},
					Stat => {
						self.complete = true;
						self.parse_stat()
					},
                                    UidlAll => {

                                    },
                                    UidlOne => {
                                        self.complete = true;
                                        self.parse_uidl_one();
                                    },
					ListAll => {

					},
					ListOne => {
						self.complete = true;
						self.parse_list_one();
					},
					Retr => {

					},
					_ => self.complete = true,
				}
			} else if ERR_REGEX.is_match(&line) {
				self.lines.push(line);
				self.result = Some(POP3Result::POP3Err);
				self.complete = true;
			}
		} else {
			if ENDING_REGEX.is_match(&line) {
				self.lines.push(line);
				match command {
                                    UidlAll => {
                                        self.complete = true;
                                        self.parse_uidl_all();
                                    },
					ListAll => {
						self.complete = true;
						self.parse_list_all();
					},
					Retr => {
						self.complete = true;
						self.parse_message();
					},
					_ => self.complete = true,
				}
			} else {
				self.lines.push(line);
			}
		}
	}

	fn parse_stat(&mut self) {
		let caps = STAT_REGEX.captures(&self.lines[0]).unwrap();
		let num_emails = FromStr::from_str(caps.get(1).unwrap().as_str());
		let total_email_size = FromStr::from_str(caps.get(2).unwrap().as_str());
		self.result = Some(POP3Result::POP3Stat {
			num_email: num_emails.unwrap(),
			mailbox_size: total_email_size.unwrap()
		})
	}


    fn parse_uidl_all(&mut self) {
        let mut metadata = Vec::new();

        for i in 1..self.lines.len() - 1 {
            let caps = MESSAGE_DATA_UIDL_ALL_REGEX.captures(&self.lines[i]).unwrap();
            let message_id = FromStr::from_str(caps.get(1).unwrap().as_str());
            let message_uid = caps.get(2).unwrap().as_str();

            metadata.push(POP3EmailUidldata {
                message_id: message_id.unwrap(),
                message_uid: message_uid.to_owned()
            });
        }

        self.result = Some(POP3Result::POP3Uidl {
            emails_metadata: metadata
        });
    }

    fn parse_uidl_one(&mut self) {
        let caps = MESSAGE_DATA_UIDL_ONE_REGEX.captures(&self.lines[0]).unwrap();
        let message_id = FromStr::from_str(caps.get(1).unwrap().as_str());
        let message_uid = caps.get(2).unwrap().as_str();

        self.result = Some(POP3Result::POP3Uidl {
            emails_metadata: vec![POP3EmailUidldata{
                    message_id: message_id.unwrap(),
                    message_uid: message_uid.to_owned()
            }]
        });
    }

	fn parse_list_all(&mut self) {
		let mut metadata = Vec::new();

		for i in 1 .. self.lines.len()-1 {
			let caps = MESSAGE_DATA_LIST_ALL_REGEX.captures(&self.lines[i]).unwrap();
			let message_id = FromStr::from_str(caps.get(1).unwrap().as_str());
			let message_size = FromStr::from_str(caps.get(2).unwrap().as_str());
			metadata.push(POP3EmailMetadata{ message_id: message_id.unwrap(), message_size: message_size.unwrap()});
		}
		self.result = Some(POP3Result::POP3List {
			emails_metadata: metadata
		});
	}

	fn parse_list_one(&mut self) {
		let caps = STAT_REGEX.captures(&self.lines[0]).unwrap();
		let message_id = FromStr::from_str(caps.get(1).unwrap().as_str());
		let message_size = FromStr::from_str(caps.get(2).unwrap().as_str());
		self.result = Some(POP3Result::POP3List {
			emails_metadata: vec![POP3EmailMetadata{ message_id: message_id.unwrap(), message_size: message_size.unwrap()}]
		});
	}

	fn parse_message(&mut self) {
		let mut raw = Vec::new();
		for i in 1 .. self.lines.len()-1 {
			raw.push(self.lines[i].clone());
		}
		self.result = Some(POP3Result::POP3Message{
			raw: raw
		});
	}
}