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

use std::fmt;
use std::io::Read;
use std::ops::Drop;
use std::ffi::CString;
use std::convert::{From, TryFrom};
use std::mem::MaybeUninit;
use std::os::raw::{c_int, c_void};
use chrono::NaiveDateTime;
use crate::mapi::MAPIProperty;
use crate::utils::*;

#[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum TNEFError {
	CannotInitData   = -1,
	NotTnefStream    = -2,
	ErrorReadingData = -3,
	NoKey            = -4,
	BadChecksum      = -5,
	ErrorInHandler   = -6,
	UnknownProperty  = -7,
	IncorrectSetup   = -8,
	UnknownError     = -9
}

/// Used for conveniently converting return values from ytnef_sys into an error type
impl From<i32> for TNEFError {
	fn from(other: i32) -> Self {
		match other {
			-1 => TNEFError::CannotInitData,
			-2 => TNEFError::NotTnefStream,
			-3 => TNEFError::ErrorReadingData,
			-4 => TNEFError::NoKey,
			-5 => TNEFError::BadChecksum,
			-6 => TNEFError::ErrorInHandler,
			-7 => TNEFError::UnknownProperty,
			-8 => TNEFError::IncorrectSetup,
			_  => TNEFError::UnknownError
		}
	}
}

impl fmt::Display for TNEFError {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		let msg = match self {
			TNEFError::CannotInitData   => "Cannot initialize data",
			TNEFError::NotTnefStream    => "Not a TNEF stream",
			TNEFError::ErrorReadingData => "Error reading data",
			TNEFError::NoKey            => "No key",
			TNEFError::BadChecksum      => "Bad checksum",
			TNEFError::ErrorInHandler   => "Error in I/O handler",
			TNEFError::UnknownProperty  => "Unkown property",
			TNEFError::IncorrectSetup   => "Incorrect setup",
			_ => "Unkown error"
		};
		write!(f, "{} ({})", msg, *self as u8)
	}
}

pub type TNEFResult<T> = Result<T, TNEFError>;

pub struct TNEFAttachmentRenderData {
	pub attach_type: u16,
	pub position: u32,
	pub width: u16,
	pub height: u16,
	pub flags: u32
}

// I wasn't sure what to do with the linked-list pointers used in this structure.
// I tried the Box<T> method and realized that wouldn't work because you can't
// drop the value since drop() borrows self and you can't mutably borrow the inner
// value from the box. Just decided to copy the structures instead.
pub struct TNEFAttachment {
	inner: ytnef_sys::Attachment
}

impl Default for TNEFAttachment {
	fn default() -> Self {
		Self::new()
	}
}

impl TNEFAttachment {
	pub fn new() -> Self {
		unsafe {
			let mut inner = MaybeUninit::<ytnef_sys::Attachment>::zeroed();
			ytnef_sys::TNEFInitAttachment(inner.as_mut_ptr());
			Self { inner: inner.assume_init() }
		}
	}

	/// # Safety
	///
	/// 'raw' must be a non-NULL initialized Attachment object. Only pass pointers returned by the
	/// ytnef_sys API to this function.
	pub unsafe fn from_raw(raw: *mut ytnef_sys::Attachment) -> Self {
		Self { inner: raw.read() }
	}

	/// Returns None if date is invalid.
	pub fn date(&self) -> Option<NaiveDateTime> {
		datetime_from_dtr(self.inner.Date)
	}

	pub fn title(&self) -> Option<String> {
		string_from_varlen(self.inner.Title)
	}

	/// Returns None if date is invalid.
	pub fn create_date(&self) -> Option<NaiveDateTime> {
		datetime_from_dtr(self.inner.CreateDate)
	}

	/// Returns None if date is invalid.
	pub fn modify_date(&self) -> Option<NaiveDateTime> {
		datetime_from_dtr(self.inner.ModifyDate)
	}

	pub fn transport_filename(&self) -> Option<String> {
		string_from_varlen(self.inner.TransportFilename)
	}

	pub fn render_data(&self) -> TNEFAttachmentRenderData {
		TNEFAttachmentRenderData {
			attach_type: self.inner.RenderData.atyp,
			position: self.inner.RenderData.ulPosition,
			width:    self.inner.RenderData.dxWidth,
			height:   self.inner.RenderData.dyHeight,
			flags:    self.inner.RenderData.dwFlags
		}
	}

	pub fn file_data(&self) -> Option<Vec<u8>> {
		vec_from_varlen(self.inner.FileData)
	}

	pub fn icon_data(&self) -> Option<Vec<u8>> {
		vec_from_varlen(self.inner.IconData)
	}
}

#[derive(Debug)]
pub enum TNEFMessageClass {
	/// E-Mail with a note.
	EmailNote,
	/// E-Mail with a read receipt.
	EmailReadReceipt,
	/// E-Mail with a non-delivery notification.
	EmailNonDelivery,
	/// E-Mail with a positive meeting response.
	MeetingResponsePositive,
	/// E-Mail with a negative meeting response.
	MeetingResponseNegative,
	/// E-Mail with a tentative meeting response.
	MeetingResponseTentative,
	/// E-Mail with a meeting request.
	MeetingRequest,
	/// E-Mail with a meeting cancellation.
	MeetingCancelled,
	/// Any other non-standard value for the message class.
	Other(String)
}

impl From<&str> for TNEFMessageClass {
	fn from(other: &str) -> Self {
		match other {
			"IPM.Microsoft Mail.Note"         => TNEFMessageClass::EmailNote,
			"IPM.Microsoft Mail.Read Receipt" => TNEFMessageClass::EmailReadReceipt,
			"IPM.Microsoft Mail.Non-Delivery" => TNEFMessageClass::EmailNonDelivery,
			"IPM.Microsoft Schedule.MtgRespP" => TNEFMessageClass::MeetingResponsePositive,
			"IPM.Microsoft Schedule.MtgRespN" => TNEFMessageClass::MeetingResponseNegative,
			"IPM.Microsoft Schedule.MtgRespA" => TNEFMessageClass::MeetingResponseTentative,
			"IPM.Microsoft Schedule.MtgReq"   => TNEFMessageClass::MeetingRequest,
			"IPM.Microsoft Schedule.MtgCncl"  => TNEFMessageClass::MeetingCancelled,
			_ => TNEFMessageClass::Other(other.into())
		}
	}
}

#[derive(Debug)]
pub enum TNEFMessageStatus {
	/// E-Mail read.
	Read,
	/// E-Mail modified.
	Modified,
	/// E-Mail submitted.
	Submitted,
	/// Unsent E-Mail.
	Unsent,
	/// E-Mail with an attachement.
	HasAttachments
}

impl TryFrom<&str> for TNEFMessageStatus {
	type Error = TNEFError;

	fn try_from(other: &str) -> Result<Self, Self::Error> {
		match other {
			"fmsRead"      => Ok(TNEFMessageStatus::Read),
			"fmsModified"  => Ok(TNEFMessageStatus::Modified),
			"fmsSubmitted" => Ok(TNEFMessageStatus::Submitted),
			"fmsLocal"     => Ok(TNEFMessageStatus::Unsent),
			"fmsHasAttach" => Ok(TNEFMessageStatus::HasAttachments),
			_ => Err(TNEFError::UnknownProperty)
		}
	}
}

#[derive(Debug)]
pub enum TNEFPriority {
	Low,
	Normal,
	High
}

impl TryFrom<&str> for TNEFPriority {
	type Error = TNEFError;

	fn try_from(other: &str) -> Result<Self, Self::Error> {
		match other {
			"low"    => Ok(TNEFPriority::Low),
			"normal" => Ok(TNEFPriority::Normal),
			"high"   => Ok(TNEFPriority::High),
			_        => Err(TNEFError::UnknownProperty)
		}
	}
}

#[derive(Debug)]
pub struct TNEFFile {
	inner: ytnef_sys::TNEFStruct
}

struct ReaderWrapper {
	inner: Box<dyn Read>
}

unsafe extern "C" fn tnef_io_open(_io: *mut ytnef_sys::_TNEFIOStruct) -> c_int {
	0
}

unsafe extern "C" fn tnef_io_read(
	io: *mut ytnef_sys::_TNEFIOStruct,
	size: c_int,
	count: c_int,
	dest: *mut c_void
) -> c_int {
	// extract our reader from the `data' field in our I/O struct
	let mut reader = Box::from_raw((*io).data as *mut ReaderWrapper);

	// allocate a buffer sufficient for the amount of data we will read
	let buffer_size: usize = (size * count) as usize;
	let mut buffer: Vec<u8> = vec![0; buffer_size];

	// read data from our reader and write data to the `dest' buffer
	let bytes_read: i32 = match reader.inner.read(&mut buffer) {
		Ok(bytes_read) => bytes_read as i32,
		Err(_) => -1
	};
	buffer.as_ptr().copy_to(dest as *mut u8, buffer_size);

	// turn our box back into a raw pointer to avoid double free then
	// return our result
	(*io).data = Box::into_raw(reader) as *mut c_void;
	bytes_read
}

unsafe extern "C" fn tnef_io_close(_io: *mut ytnef_sys::_TNEFIOStruct) -> c_int {
	0
}

impl TNEFFile {
	// impl with Read trait instead
	pub fn new<R: 'static + Read>(reader: R) -> TNEFResult<Self> {
		let reader_wrapper = Box::new(ReaderWrapper {
			inner: Box::new(reader)
		});

		// configure IO struct
		let io = ytnef_sys::_TNEFIOStruct {
			InitProc: Some(tnef_io_open),
			ReadProc: Some(tnef_io_read),
			CloseProc: Some(tnef_io_close),
			data: Box::into_raw(reader_wrapper) as *mut c_void
		};
		
		// initialize TNEF struct
		let mut inner = MaybeUninit::<ytnef_sys::TNEFStruct>::zeroed();

		let result: i32 = unsafe {
			let inner_ptr = inner.as_mut_ptr();
			ytnef_sys::TNEFInitialize(inner_ptr);
			(*inner_ptr).IO = io; // insert our custom I/O interface before parsing
			(*inner_ptr).Debug = 0;
			ytnef_sys::TNEFParse(inner_ptr)
		};

		if result < 0 {
			Err(result.into())
		} else {
			Ok(Self { inner: unsafe { inner.assume_init() }})
		}
	}

	pub fn from_file(path: String) -> TNEFResult<Self> {
		let mut inner = MaybeUninit::<ytnef_sys::TNEFStruct>::zeroed();

		let result: i32 = unsafe {
			let path_cstr = match CString::new(path) {
				Ok(path) => path.into_raw(),
				Err(_) => {
					return Err(TNEFError::CannotInitData);
				}
			};
			
			let inner_ptr = inner.as_mut_ptr();
			ytnef_sys::TNEFInitialize(inner_ptr);
			let result = ytnef_sys::TNEFParseFile(path_cstr, inner_ptr);
			let _ = CString::from_raw(path_cstr);
			
			result
		};

		if result < 0 {
			Err(result.into())
		} else {
			Ok(Self { inner: unsafe { inner.assume_init() } })
		}
	}

	// FIXME: it sucks that we need this mutable borrow
	pub fn from_buffer(buffer: &mut [u8]) -> TNEFResult<Self> {
		let mut inner = MaybeUninit::<ytnef_sys::TNEFStruct>::zeroed();

		let result: i32 = unsafe {
			let inner_ptr = inner.as_mut_ptr();

			#[cfg(target_pointer_width = "32")]
			let buffer_len = buffer.len() as i32;
			#[cfg(target_pointer_width = "64")]
			let buffer_len = buffer.len() as i64;

			ytnef_sys::TNEFInitialize(inner_ptr);
			ytnef_sys::TNEFParseMemory(
				buffer.as_mut_ptr(),
				buffer_len,
				inner_ptr
			)
		};

		if result < 0 {
			Err(result.into())
		} else {
			Ok(Self { inner: unsafe { inner.assume_init() } })
		}
	}

	pub fn version(&self) -> String {
		make_safe_string(self.inner.version.as_ptr())
	}

	pub fn from(&self) -> Option<String> {
		string_from_varlen(self.inner.from)
	}

	pub fn subject(&self) -> Option<String> {
		string_from_varlen(self.inner.subject)
	}

	/// Returns None if date is invalid.
	pub fn date_sent(&self) -> Option<NaiveDateTime> {
		datetime_from_dtr(self.inner.dateSent)
	}

	/// Returns None if date is invalid.
	pub fn date_received(&self) -> Option<NaiveDateTime> {
		datetime_from_dtr(self.inner.dateReceived)
	}

	/// Returns None if date is invalid.
	pub fn date_modified(&self) -> Option<NaiveDateTime> {
		datetime_from_dtr(self.inner.dateModified)
	}

	/// Returns None if date is invalid.
	pub fn date_start(&self) -> Option<NaiveDateTime> {
		datetime_from_dtr(self.inner.DateStart)
	}

	/// Returns None if date is invalid.
	pub fn date_end(&self) -> Option<NaiveDateTime> {
		datetime_from_dtr(self.inner.DateEnd)
	}

	pub fn message_status(&self) -> Option<TNEFResult<TNEFMessageStatus>> {
		Some(make_safe_string(self.inner.messageStatus.as_ptr()))
			.filter(|status| !status.is_empty())
			.map(|status| status.as_str().try_into())
	}

	pub fn message_class(&self) -> TNEFMessageClass {
		make_safe_string(self.inner.messageClass.as_ptr())
			.as_str()
			.into()
	}

	pub fn message_id(&self) -> String {
		make_safe_string(self.inner.messageID.as_ptr())
	}

	pub fn parent_id(&self) -> String {
		make_safe_string(self.inner.parentID.as_ptr())
	}

	pub fn conversation_id(&self) -> String {
		make_safe_string(self.inner.conversationID.as_ptr())
	}

	pub fn body(&self) -> Option<String> {
		string_from_varlen(self.inner.body)
	}

	pub fn priority(&self) -> TNEFResult<TNEFPriority> {
		let mut priority_str = make_safe_string(self.inner.priority.as_ptr());
		priority_str.make_ascii_lowercase();
		priority_str.as_str().try_into()
	}

	pub fn attachments(&self) -> Vec<TNEFAttachment> {
		let mut output: Vec<TNEFAttachment> = vec![];
		let mut curr_attach = self.inner.starting_attach.next;

		// push starting attachment itself onto output
		output.push(TNEFAttachment { inner: self.inner.starting_attach });

		while !curr_attach.is_null() {
			let attach = unsafe { TNEFAttachment::from_raw(curr_attach) };
			curr_attach = attach.inner.next;
			output.push(attach);
		}

		output
	}

	pub fn mapi_properties(&self) -> Vec<MAPIProperty> {
		let mut output: Vec<MAPIProperty> = vec![];
		let props_list = self.inner.MapiProperties;

		for i in 0..props_list.count {
			let property = unsafe {
				MAPIProperty::from_raw(
					props_list.properties.offset(i as isize)
				)
			};
			output.push(property);
		}

		output
	}

	pub fn code_page(&self) -> Option<Vec<u8>> {
		vec_from_varlen(self.inner.CodePage)
	}

	pub fn original_message_class(&self) -> Option<String> {
		string_from_varlen(self.inner.OriginalMessageClass)
			.map(|msg_class_str| msg_class_str.as_str().into())
	}

	pub fn owner(&self) -> Option<String> {
		string_from_varlen(self.inner.Owner)
	}

	pub fn sent_for(&self) -> Option<String> {
		string_from_varlen(self.inner.SentFor)
	}

	pub fn delegate(&self) -> Option<String> {
		string_from_varlen(self.inner.Delegate)
	}

	pub fn aid_owner(&self) -> Option<String> {
		string_from_varlen(self.inner.AidOwner)
	}
}

impl Drop for TNEFFile {
	fn drop(&mut self) {
		unsafe { ytnef_sys::TNEFFree(&mut self.inner); }
	}
}

#[cfg(test)]
mod test {
	use super::*;
	use std::fs::{read, File};

	#[test]
	fn new_from_file() {
		let file = File::open("test_data/winmail.dat").unwrap();
		let _ = TNEFFile::new(file).unwrap();
	}

	#[test]
	fn new_from_path() {
		let _ = TNEFFile::from_file("test_data/winmail.dat".to_string()).unwrap();
	}

	#[test]
	fn new_from_buffer() {
		let mut buffer: Vec<u8> = read("test_data/winmail.dat").unwrap();
		let _ = TNEFFile::from_buffer(&mut buffer).unwrap();
	}
}