nntp 0.0.5

NNTP client for Rust
Documentation
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
#![crate_name = "nntp"]
#![crate_type = "lib"]

//#![feature(collections)]

use std::string::String;
use std::io::{Read, Result, Error, ErrorKind, Write};
use std::net::TcpStream;
use std::net::ToSocketAddrs;
use std::vec::Vec;
use std::collections::HashMap;
use std::str::FromStr;

/// Stream to be used for interfacing with a NNTP server.
pub struct NNTPStream {
	stream: TcpStream,
}

pub struct Article {
	pub headers: HashMap<String, String>,
	pub body: Vec<String>
}

impl Article {
	pub fn new_article(lines: Vec<String>) -> Article {
		let mut headers = HashMap::new();
		let mut body = Vec::new();
		let mut parsing_headers = true;

		for i in lines.iter() {
			if i == &format!("\r\n") {
				parsing_headers = false;
				continue;
			}
			if parsing_headers {
				let mut header = i.splitn(2, ':');
				let chars_to_trim: &[char] = &['\r', '\n'];
				let key = format!("{}", header.nth(0).unwrap().trim_matches(chars_to_trim));
				let value = format!("{}", header.nth(0).unwrap().trim_matches(chars_to_trim));
				headers.insert(key, value);
			} else {
				body.push(i.clone());
			}

		}
		Article {headers: headers, body: body}
	}
}

pub struct NewsGroup {
	pub name: String ,
	pub high: isize,
	pub low: isize,
	pub status: String
}

impl NewsGroup {
	pub fn new_news_group(group: &str) -> NewsGroup {
		let chars_to_trim: &[char] = &['\r', '\n', ' '];
		let trimmed_group = group.trim_matches(chars_to_trim);
		let split_group: Vec<&str> = trimmed_group.split(' ').collect();
		NewsGroup{name: format!("{}", split_group[0]), high: FromStr::from_str(split_group[1]).unwrap(), low: FromStr::from_str(split_group[2]).unwrap(), status: format!("{}", split_group[3])}
	}
}

impl NNTPStream {

	/// Creates an NNTP Stream.
	pub fn connect<A: ToSocketAddrs>(addr: A) -> Result<NNTPStream> {
		let tcp_stream = TcpStream::connect(addr)?;
		let mut socket = NNTPStream { stream: tcp_stream };

		match socket.read_response(200) {
			Ok(_) => (),
			Err(_) => return Err(Error::new(ErrorKind::Other, "Failed to read greeting response"))
		}

		Ok(socket)
	}

	/// The article indicated by the current article number in the currently selected newsgroup is selected.
	pub fn article(&mut self) -> Result<Article> {
		self.retrieve_article(&format!("ARTICLE\r\n"))
	}

	/// The article indicated by the article id is selected.
	pub fn article_by_id(&mut self, article_id: &str) -> Result<Article> {
		self.retrieve_article(&format!("ARTICLE {}\r\n", article_id))
	}

	/// The article indicated by the article number in the currently selected newsgroup is selected.
	pub fn article_by_number(&mut self, article_number: isize) -> Result<Article> {
		self.retrieve_article(&format!("ARTICLE {}\r\n", article_number))
	}

	fn retrieve_article(&mut self, article_command: &str) -> Result<Article> {
		match self.stream.write_fmt(format_args!("{}", article_command)) {
			Ok(_) => (),
			Err(_) => return Err(Error::new(ErrorKind::Other, "Failed to retreive atricle"))
		}

		match self.read_response(220) {
			Ok(_) => (),
			Err(e) => return Err(e)
		}

		match self.read_multiline_response() {
			Ok(lines) => {
				Ok(Article::new_article(lines))
			}
			Err(e) => Err(e)
		}
	}

	/// Retrieves the body of the current article number in the currently selected newsgroup.
	pub fn body(&mut self) -> Result<Vec<String>> {
		self.retrieve_body(&format!("BODY\r\n"))
	}

	/// Retrieves the body of the article id.
	pub fn body_by_id(&mut self, article_id: &str) -> Result<Vec<String>> {
		self.retrieve_body(&format!("BODY {}\r\n", article_id))
	}

	/// Retrieves the body of the article number in the currently selected newsgroup.
	pub fn body_by_number(&mut self, article_number: isize) -> Result<Vec<String>> {
		self.retrieve_body(&format!("BODY {}\r\n", article_number))
	}

	fn retrieve_body(&mut self, body_command: &str) -> Result<Vec<String>> {
		match self.stream.write_fmt(format_args!("{}", body_command)) {
			Ok(_) => (),
			Err(e) => return Err(e)
		}

		match self.read_response(222) {
			Ok(_) => (),
			Err(e) => return Err(e)
		}

		self.read_multiline_response()
	}

	/// Gives the list of capabilities that the server has.
	pub fn capabilities(&mut self) -> Result<Vec<String>> {
		let capabilities_command = format!("CAPABILITIES\r\n");

		match self.stream.write_fmt(format_args!("{}", capabilities_command)) {
			Ok(_) => (),
			Err(e) => return Err(e)
		}

		match self.read_response(101) {
			Ok(_) => (),
			Err(e) => return Err(e)
		}

		self.read_multiline_response()
	}

	/// Retrieves the date as the server sees the date.
	pub fn date(&mut self) -> Result<String> {
		let date_command = format!("DATE\r\n");

		match self.stream.write_fmt(format_args!("{}", date_command)) {
			Ok(_) => (),
			Err(e) => return Err(e)
		}

		match self.read_response(111) {
			Ok((_, message)) => Ok(message),
			Err(e) => Err(e)
		}
	}

	/// Retrieves the headers of the current article number in the currently selected newsgroup.
	pub fn head(&mut self) -> Result<Vec<String>> {
		self.retrieve_head(&format!("HEAD\r\n"))
	}

	/// Retrieves the headers of the article id.
	pub fn head_by_id(&mut self, article_id: &str) -> Result<Vec<String>> {
		self.retrieve_head(&format!("HEAD {}\r\n", article_id))
	}

	/// Retrieves the headers of the article number in the currently selected newsgroup.
	pub fn head_by_number(&mut self, article_number: isize) -> Result<Vec<String>> {
		self.retrieve_head(&format!("HEAD {}\r\n", article_number))
	}

	fn retrieve_head(&mut self, head_command: &str) -> Result<Vec<String>> {
		match self.stream.write_fmt(format_args!("{}", head_command)) {
			Ok(_) => (),
			Err(e) => return Err(e)
		}

		match self.read_response(221) {
			Ok(_) => (),
			Err(e) => return Err(e)
		}

		self.read_multiline_response()
	}

	/// Moves the currently selected article number back one
	pub fn last(&mut self) -> Result<String> {
		let last_command = format!("LAST\r\n");

		match self.stream.write_fmt(format_args!("{}", last_command)) {
			Ok(_) => (),
			Err(e) => return Err(e)
		}

		match self.read_response(223) {
			Ok((_, message)) => Ok(message),
			Err(e) => Err(e)
		}
	}

	/// Lists all of the newgroups on the server.
	pub fn list(&mut self) -> Result<Vec<NewsGroup>> {
		let list_command = format!("LIST\r\n");

		match self.stream.write_fmt(format_args!("{}", list_command)) {
			Ok(_) => (),
			Err(e) => return Err(e)
		}

		match self.read_response(215) {
			Ok(_) => (),
			Err(e) => return Err(e)
		}

		match self.read_multiline_response() {
			Ok(lines) => {
				let lines: Vec<NewsGroup> = lines.iter().map(|ref mut x| NewsGroup::new_news_group((*x))).collect();
				return Ok(lines)
			},
			Err(e) => Err(e)
		}
	}

	/// Selects a newsgroup
	pub fn group(&mut self, group: &str) -> Result<()> {
		let group_command = format!("GROUP {}\r\n", group);

		match self.stream.write_fmt(format_args!("{}", group_command)) {
			Ok(_) => (),
			Err(e) => return Err(e)
		}

		match self.read_response(211) {
			Ok(_) => Ok(()),
			Err(e) => Err(e)
		}
	}

	/// Show the help command given on the server.
	pub fn help(&mut self) -> Result<Vec<String>> {
		let help_command = format!("HELP\r\n");

		match self.stream.write_fmt(format_args!("{}", help_command)) {
			Ok(_) => (),
			Err(e) => return Err(e)
		}

		match self.read_response(100) {
			Ok(_) => (),
			Err(e) => return Err(e)
		}

		self.read_multiline_response()
	}

	/// Quits the current session.
	pub fn quit(&mut self) -> Result<()> {
		let quit_command = format!("QUIT\r\n");
		match self.stream.write_fmt(format_args!("{}", quit_command)) {
			Ok(_) => (),
			Err(e) => return Err(e)
		}

		match self.read_response(205) {
			Ok(_) => Ok(()),
			Err(e) => Err(e)
		}
	}

	/// Retrieves a list of newsgroups since the date and time given.
	pub fn newgroups(&mut self, date: &str, time: &str, use_gmt: bool) -> Result<Vec<String>> {
		let newgroups_command = match use_gmt {
			true => format!("NEWSGROUP {} {} GMT\r\n", date, time),
			false => format!("NEWSGROUP {} {}\r\n", date, time)
		};

		match self.stream.write_fmt(format_args!("{}", newgroups_command)) {
			Ok(_) => (),
			Err(e) => return Err(e)
		}

		match self.read_response(231) {
			Ok(_) => (),
			Err(e) => return Err(e)
		}

		self.read_multiline_response()
	}

	/// Retrieves a list of new news since the date and time given.
	pub fn newnews(&mut self, wildmat: &str, date: &str, time: &str, use_gmt: bool) -> Result<Vec<String>> {
		let newnews_command = match use_gmt {
			true => format!("NEWNEWS {} {} {} GMT\r\n", wildmat, date, time),
			false => format!("NEWNEWS {} {} {}\r\n", wildmat, date, time)
		};

		match self.stream.write_fmt(format_args!("{}", newnews_command)) {
			Ok(_) => (),
			Err(e) => return Err(e)
		}

		match self.read_response(230) {
			Ok(_) => (),
			Err(e) => return Err(e)
		}

		self.read_multiline_response()
	}

	/// Moves the currently selected article number forward one
	pub fn next(&mut self) -> Result<String> {
		let next_command = format!("NEXT\r\n");
		match self.stream.write_fmt(format_args!("{}", next_command)) {
			Ok(_) => (),
			Err(e) => return Err(e)
		}

		match self.read_response(223) {
			Ok((_, message)) => Ok(message),
			Err(e) => Err(e)
		}
	}

	/// Posts a message to the NNTP server.
	pub fn post(&mut self, message: &str) -> Result<()> {
		if !self.is_valid_message(message) {
			return Err(Error::new(ErrorKind::Other, "Invalid message format. Message must end with \"\r\n.\r\n\""));
		}

		let post_command = format!("POST\r\n");

		match self.stream.write_fmt(format_args!("{}", post_command)) {
			Ok(_) => (),
			Err(e) => return Err(e)
		}

		match self.read_response(340) {
			Ok(_) => (),
			Err(e) => return Err(e)
		};

		match self.stream.write_fmt(format_args!("{}", message)) {
			Ok(_) => (),
			Err(e) => return Err(e)
		}

		match self.read_response(240) {
			Ok(_) => Ok(()),
			Err(e) => Err(e)
		}
	}

	/// Gets information about the current article.
	pub fn stat(&mut self) -> Result<String> {
		self.retrieve_stat(&format!("STAT\r\n"))
	}

	/// Gets the information about the article id.
	pub fn stat_by_id(&mut self, article_id: &str) -> Result<String> {
		self.retrieve_stat(&format!("STAT {}\r\n", article_id))
	}

	/// Gets the information about the article number.
	pub fn stat_by_number(&mut self, article_number: isize) -> Result<String> {
		self.retrieve_stat(&format!("STAT {}\r\n", article_number))
	}

	fn retrieve_stat(&mut self, stat_command: &str) -> Result<String> {
		match self.stream.write_fmt(format_args!("{}", stat_command)) {
			Ok(_) => (),
			Err(_) => return Err(Error::new(ErrorKind::Other, "Write Error"))
		}

		match self.read_response(223) {
			Ok((_, message)) => Ok(message),
			Err(e) => Err(e)
		}
	}

	fn is_valid_message(&mut self, message: &str) -> bool {
		//Carriage return
		let cr = 0x0d;
		//Line Feed
		let lf = 0x0a;
		//Dot
		let dot = 0x2e;
		let message_string = message.to_string();
		let message_bytes = message_string.as_bytes();
		let length = message_string.len();

		return length >= 5 && (message_bytes[length-1] == lf && message_bytes[length-2] == cr &&
			message_bytes[length-3] == dot && message_bytes[length-4] == lf && message_bytes[length-5] == cr)
	}

	//Retrieve single line response
	fn read_response(&mut self, expected_code: isize) -> Result<(isize, String)> {
		//Carriage return
		let cr = 0x0d;
		//Line Feed
		let lf = 0x0a;
		let mut line_buffer: Vec<u8> = Vec::new();

		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.stream.read(byte_buffer) {
					Ok(_) => {},
					Err(_) => return Err(Error::new(ErrorKind::Other, "Error reading response")),
				}
				line_buffer.push(byte_buffer[0]);
		}

		let response = String::from_utf8(line_buffer).unwrap();
		let chars_to_trim: &[char] = &['\r', '\n'];
		let trimmed_response = response.trim_matches(chars_to_trim);
    	let trimmed_response_vec: Vec<char> = trimmed_response.chars().collect();
    	if trimmed_response_vec.len() < 5 || trimmed_response_vec[3] != ' ' {
    		return Err(Error::new(ErrorKind::Other, "Invalid response"));
    	}

    	let v: Vec<&str> = trimmed_response.splitn(2, ' ').collect();
    	let code: isize = FromStr::from_str(v[0]).unwrap();
    	let message = v[1];
    	if code != expected_code {
    		return Err(Error::new(ErrorKind::Other, "Invalid response"))
    	}
    	Ok((code, message.to_string()))
	}

	fn read_multiline_response(&mut self) -> Result<Vec<String>> {
		let mut response: Vec<String> = Vec::new();
		//Carriage return
		let cr = 0x0d;
		//Line Feed
		let lf = 0x0a;
		let mut line_buffer: Vec<u8> = Vec::new();
		let mut complete = false;

		while !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.stream.read(byte_buffer) {
					Ok(_) => {},
					Err(_) => println!("Error Reading!"),
				}
				line_buffer.push(byte_buffer[0]);
			}

			match String::from_utf8(line_buffer.clone()) {
        		Ok(res) => {
        			if res == format!(".\r\n") {
        				complete = true;
        			}
        			else {
          				response.push(res.clone());
            			line_buffer = Vec::new();
            		}
        		},
        		Err(_) => return Err(Error::new(ErrorKind::Other, "Error Reading"))
      		}
		}
		Ok(response)
	}
}