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
//! # Mail Extractor
//!
//! `Mail_extractor` is a Rust library to extract files
//!  from MIME type files and returns you a hashmap
//!  which will contain filename and it corresponding file content as bytes.
//!
//! # Example
//!
//! ```
//! use std::collections::HashMap;
//! use mail_extractor;
//! fn get_files(file_stream: Vec<u8>) -> HashMap<String, Vec<u8>> {
//!     let extracted_file: HashMap<String, Vec<u8>> = mail_extractor::rewrite(file_stream);    
//! 	extracted_file
//! }
//! ```

use lol_html::{element, HtmlRewriter, Settings};
use mailparse::body::Body;
use mailparse::parse_mail;
use regex::{Captures, Regex};
use htmlescape::decode_html;
use std::collections::HashMap;
use std::hash::Hash;
use uuid::Uuid;

#[macro_use]
extern crate lazy_static;
extern crate base64;

fn proxify_css<'a>(
	body: &str,
	link_to_hash_old: &mut HashMap<String, String>,
) -> (String, HashMap<String, String>) {
	let mut link_to_hash: HashMap<String, String> = HashMap::new();
	lazy_static! {
		static ref RE: Regex =
			Regex::new(r#"(?i)(?m)url\s*\(\s*([$&+,:;=?@#'"<>*%!/.-a-zA-Z_]+)\s*\)"#).unwrap();
	}
	(
		RE.replace_all(body, |caps: &Captures| {
			let match_url = &caps[0][5..caps[0].len() - 2];
			// let len = match_url.len();
			if match_url.starts_with("data:") | match_url.ends_with(".css") != true {
				if !link_to_hash_old.contains_key(match_url) {
					let hash: &str = &Uuid::new_v4().to_string();
					// let mut filename = match_url.split('/');
					let decoded_url = match decode_html(&match_url.to_string()) {
						Ok(new_name) => new_name,
						Err(_) => match_url.to_string(),
					};
					link_to_hash.insert(decoded_url, hash.to_string());
					format!("url(\"{}\")", hash)
				} else {
					format!("url(\"{}\")", link_to_hash_old.get(match_url).unwrap())
				}
			} else {
				format!("{}", &caps[0])
			}
		})
		.into_owned(),
		link_to_hash,
	)
}

fn rewrite_html(body: Vec<u8>) -> (Vec<u8>, HashMap<String, String>) {
	let mut html_out: Vec<u8> = vec![];
	let mut link_to_hash: HashMap<String, String> = HashMap::new();
	let mut rewriter = HtmlRewriter::try_new(
		Settings {
			element_content_handlers: vec![element!(
				"base, img[src], link[rel=stylesheet][href], iframe[src]",
				|el| {
					if el.get_attribute("rel") == Some("stylesheet".to_string()) {
						let src = el.get_attribute("href").unwrap();
						let length = src
							.split("/")
							.collect::<Vec<&str>>()
							.pop()
							.unwrap()
							.split('?')
							.next()
							.unwrap()
							.split('.')
							.collect::<Vec<&str>>()
							.len();
						let (src1, mut newname) = set_filename(src, ".css".to_string());
						let hash = Uuid::new_v4();
						if length == 1 {
							newname = hash.to_string() + &newname;
							link_to_hash.insert(el.get_attribute("href").unwrap(), newname.clone());
							el.set_attribute("href", &newname).unwrap();
						} else {
							link_to_hash.insert(el.get_attribute("href").unwrap(), newname);
							el.set_attribute(
								"href",
								&(src1.replace("#", "") + &String::from(".css")),
							)
							.unwrap();
						}
					} else if el.tag_name() == "iframe" {
						let src = el.get_attribute("src").unwrap();
						let (src1, newname) = set_filename(src, ".html".to_string());
						println!("{}", newname.clone());
						link_to_hash.insert(
							el.get_attribute("src")
								.unwrap()
								.replace("cid:", "<")
								.to_string() + ">",
							newname,
						);

						el.set_attribute("src", &(src1.replace("#", "") + &String::from(".html")))
							.unwrap();
					} else if el.tag_name() == "base" {
						el.set_attribute("href", "").unwrap();
					} else {
						let decoded_url = decode_html(&el.get_attribute("src").unwrap());
						let hash: &str = &Uuid::new_v4().to_string();
						// println!("{:?} {:?}", el.get_attribute("src").unwrap(), hash.to_string());
						link_to_hash.insert(decoded_url.unwrap(), hash.to_string());
						// link_to_hash.insert(el.get_attribute("src").unwrap(), hash.to_string());
						el.set_attribute("src", &hash.to_string()).unwrap();
					}
					Ok(())
				}
			)],
			..Settings::default()
		},
		|c: &[u8]| html_out.extend_from_slice(c),
	)
	.unwrap();

	rewriter.write(&body).unwrap();
	rewriter.end().unwrap();
	drop(rewriter);
	(html_out, link_to_hash)
}

fn merge<K: Hash + Eq + Clone, V: Clone>(
	first_context: &mut std::collections::HashMap<K, V>,
	second_context: &HashMap<K, V>,
) {
	for (key, value) in second_context.iter() {
		&first_context.insert(key.clone(), value.clone());
	}
}

fn set_filename(filename: String, file_format: String) -> (String, String) {
	let mut filename2 = filename.split('/');
	let name = filename2.next_back();
	let src1 = name.unwrap();
	let filename1 = src1.split('?').next().unwrap();

	let mut filename = filename1.split(':');
	let name = filename.next_back().unwrap();
	let mut name1 = name.split('.');
	let src1 = name1.next();

	(
		src1.unwrap().to_string(),
		String::from(src1.unwrap().to_string().replace("#", "")) + &String::from(file_format),
	)
}

pub fn rewrite(mht_file: Vec<u8>) -> HashMap<String, Vec<u8>> {
	/*!
	 * Rewrites file and returns it's corresponding file content as bytes.
	*/

	let mut extracted_file: HashMap<String, Vec<u8>> = HashMap::new();
	let parsed = parse_mail(&mht_file).unwrap();
	let (index_out, mut link_to_hash) = rewrite_html(parsed.subparts[0].get_body_raw().unwrap());
	extracted_file.insert("index.html".to_string(), index_out);
	for sub in parsed.subparts {
		// println!("{:?} {:?}", sub.headers[2].get_value(), sub.headers[1].get_value());
		let name = match decode_html(&sub.headers[2].get_value().unwrap()) {
			Ok(new_name) => new_name,
			Err(_) => sub.headers[2].get_value().unwrap(),
		};
		let ctype = sub.headers[0].get_value().unwrap();
		let mut cid = match decode_html(&sub.headers[1].get_value().unwrap()) {
			Ok(new_name) => new_name,
			Err(_) => sub.headers[1].get_value().unwrap(),
		};
		// println!("{} {:?}",name,  cid);
		let creation;
		if link_to_hash.contains_key(&name) {
			creation = link_to_hash.get(&name);
		} else {
			creation = link_to_hash.get(&cid);
		}
		match creation {
			Some(name1) => {
				let mut filename = name1.split(':');
				let name = filename.next_back();
				let src1 = name.unwrap().replace("#", "");
				match sub.get_body_encoded().unwrap() {
					Body::Base64(body) | Body::QuotedPrintable(body) => {
						if ctype == "text/css" {
							let css_content: &str = &*body.get_decoded_as_string().unwrap();
							let (after, link_to_hash_new) =
								proxify_css(css_content, &mut link_to_hash);
							merge(&mut link_to_hash, &link_to_hash_new);
							extracted_file.insert(src1.clone(), after.as_bytes().to_vec());
						} else if ctype == "text/html" {
							cid = cid[1..cid.len() - 1]
								.to_string()
								.split('.')
								.next()
								.unwrap()
								.to_string();
							let frame = cid + &String::from(".html");
							let frame_content = body.get_decoded_as_string().unwrap();
							let (after, link_to_hash_new) =
								rewrite_html(frame_content.as_bytes().to_vec());
							merge(&mut link_to_hash, &link_to_hash_new);
							extracted_file.insert(frame, after);
						} else {
							extracted_file.insert(src1.clone(), body.get_decoded().unwrap());
						}
					}
					Body::SevenBit(body) | Body::EightBit(body) => {
						println!("mail body: {:?}", body.get_raw());
					}
					Body::Binary(body) => {
						println!("mail body binary: {:?}", body.get_raw());
					}
				}
			}
			None => {
				let hash: &str = &Uuid::new_v4().to_string();
				let filename = match decode_html(&name) {
					Ok(new_name) => new_name,
					Err(_) => name,
				};
				link_to_hash.insert(filename, hash.to_string());
				match sub.get_body_encoded().unwrap() {
					Body::Base64(body) | Body::QuotedPrintable(body) => {
						extracted_file.insert(hash.to_string(), body.get_decoded().unwrap());
					}
					Body::SevenBit(body) | Body::EightBit(body) => {
						println!("mail body: {:?}", body.get_raw());
					}
					Body::Binary(body) => {
						println!("mail body binary: {:?}", body.get_raw());
					}
				}
			}
		}
	}
	extracted_file
}