-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMimeReader.cs
398 lines (356 loc) · 13.5 KB
/
MimeReader.cs
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
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Mime;
namespace CSharpHelper
{
/// <summary>
/// This class is responsible for parsing a string array of lines
/// containing a MIME message.
/// </summary>
public class MimeReader
{
private static readonly char[] HeaderWhitespaceChars = new char[] { ' ', '\t' };
private Queue<string> _lines;
/// <summary>
/// Gets the lines.
/// </summary>
/// <value>The lines.</value>
public Queue<string> Lines
{
get
{
return _lines;
}
}
private MimeEntity _entity;
/// <summary>
/// Initializes a new instance of the <see cref="MimeReader"/> class.
/// </summary>
private MimeReader()
{
_entity = new MimeEntity();
}
/// <summary>
/// Initializes a new instance of the <see cref="MimeReader"/> class.
/// </summary>
/// <param name="entity">The entity.</param>
/// <param name="lines">The lines.</param>
private MimeReader(MimeEntity entity, Queue<string> lines)
: this()
{
if (entity == null)
{
throw new ArgumentNullException("entity");
}
if (lines == null)
{
throw new ArgumentNullException("lines");
}
_lines = lines;
_entity = new MimeEntity(entity);
}
/// <summary>
/// Initializes a new instance of the <see cref="MimeReader"/> class.
/// </summary>
/// <param name="lines">The lines.</param>
public MimeReader(string[] lines)
: this()
{
if (lines == null)
{
throw new ArgumentNullException("lines");
}
_lines = new Queue<string>(lines);
}
/// <summary>
/// Parse headers into _entity.Headers NameValueCollection.
/// </summary>
private int ParseHeaders()
{
string lastHeader = string.Empty;
string line = string.Empty;
// the first empty line is the end of the headers.
while (_lines.Count > 0 && !string.IsNullOrEmpty(_lines.Peek()))
{
line = _lines.Dequeue();
//if a header line starts with a space or tab then it is a continuation of the
//previous line.
if (line.StartsWith(" ") || line.StartsWith(Convert.ToString('\t')))
{
_entity.Headers[lastHeader] = string.Concat(_entity.Headers[lastHeader], line);
continue;
}
int separatorIndex = line.IndexOf(':');
if (separatorIndex < 0)
{
System.Diagnostics.Debug.WriteLine("Invalid header:{0}", line);
continue;
} //This is an invalid header field. Ignore this line.
string headerName = line.Substring(0, separatorIndex);
string headerValue = line.Substring(separatorIndex + 1).Trim(HeaderWhitespaceChars);
_entity.Headers.Add(headerName.ToLower(), headerValue);
lastHeader = headerName;
}
if (_lines.Count > 0)
{
_lines.Dequeue();
} //remove closing header CRLF.
return _entity.Headers.Count;
}
/// <summary>
/// Processes mime specific headers.
/// </summary>
/// <returns>A mime entity with mime specific headers parsed.</returns>
private void ProcessHeaders()
{
foreach (string key in _entity.Headers.AllKeys)
{
switch (key)
{
case "content-description":
_entity.ContentDescription = _entity.Headers[key];
break;
case "content-disposition":
_entity.ContentDisposition = new ContentDisposition(_entity.Headers[key]);
break;
case "content-id":
_entity.ContentId = _entity.Headers[key];
break;
case "content-transfer-encoding":
_entity.TransferEncoding = _entity.Headers[key];
_entity.ContentTransferEncoding = MimeReader.GetTransferEncoding(_entity.Headers[key]);
break;
case "content-type":
_entity.SetContentType(MimeReader.GetContentType(_entity.Headers[key]));
break;
case "mime-version":
_entity.MimeVersion = _entity.Headers[key];
break;
}
}
}
/// <summary>
/// Creates the MIME entity.
/// </summary>
/// <returns>A mime entity containing 0 or more children representing the mime message.</returns>
public MimeEntity CreateMimeEntity()
{
try
{
ParseHeaders();
ProcessHeaders();
ParseBody();
SetDecodedContentStream();
return _entity;
}
catch
{
return null;
}
}
/// <summary>
/// Sets the decoded content stream by decoding the EncodedMessage
/// and writing it to the entity content stream.
/// </summary>
/// <param name="entity">The entity containing the encoded message.</param>
private void SetDecodedContentStream()
{
switch (_entity.ContentTransferEncoding)
{
case System.Net.Mime.TransferEncoding.Base64:
_entity.Content = new MemoryStream(Convert.FromBase64String(_entity.EncodedMessage.ToString()), false);
break;
case System.Net.Mime.TransferEncoding.QuotedPrintable:
_entity.Content = new MemoryStream(GetBytes(QuotedPrintableEncoding.Decode(_entity.EncodedMessage.ToString())), false);
break;
case System.Net.Mime.TransferEncoding.SevenBit:
default:
_entity.Content = new MemoryStream(GetBytes(_entity.EncodedMessage.ToString()), false);
break;
}
}
/// <summary>
/// Gets a byte[] of content for the provided string.
/// </summary>
/// <param name="decodedContent">Content.</param>
/// <returns>A byte[] containing content.</returns>
private byte[] GetBytes(string content)
{
using (MemoryStream stream = new MemoryStream())
{
using (StreamWriter writer = new StreamWriter(stream))
{
writer.Write(content);
}
return stream.ToArray();
}
}
/// <summary>
/// Parses the body.
/// </summary>
private void ParseBody()
{
if (_entity.HasBoundary)
{
while (_lines.Count > 0
&& !string.Equals(_lines.Peek(), _entity.EndBoundary))
{
/*Check to verify the current line is not the same as the parent starting boundary.
If it is the same as the parent starting boundary this indicates existence of a
new child entity. Return and process the next child.*/
if (_entity.Parent != null
&& string.Equals(_entity.Parent.StartBoundary, _lines.Peek()))
{
return;
}
if (string.Equals(_lines.Peek(), _entity.StartBoundary))
{
AddChildEntity(_entity, _lines);
} //Parse a new child mime part.
else if (string.Equals(_entity.ContentType.MediaType, MediaTypes.MessageRfc822, StringComparison.InvariantCultureIgnoreCase)
&& string.Equals(_entity.ContentDisposition.DispositionType, DispositionTypeNames.Attachment, StringComparison.InvariantCultureIgnoreCase))
{
/*If the content type is message/rfc822 the stop condition to parse headers has already been encountered.
But, a content type of message/rfc822 would have the message headers immediately following the mime
headers so we need to parse the headers for the attached message now. This is done by creating
a new child entity.*/
AddChildEntity(_entity, _lines);
break;
}
else
{
_entity.EncodedMessage.Append(string.Concat(_lines.Dequeue(), Pop3Commands.Crlf));
} //Append the message content.
}
} //Parse a multipart message.
else
{
while (_lines.Count > 0)
{
_entity.EncodedMessage.Append(string.Concat(_lines.Dequeue(), Pop3Commands.Crlf));
}
} //Parse a single part message.
}
/// <summary>
/// Adds the child entity.
/// </summary>
/// <param name="entity">The entity.</param>
private void AddChildEntity(MimeEntity entity, Queue<string> lines)
{
/*if (entity == null)
{
return;
}
if (lines == null)
{
return;
}*/
MimeReader reader = new MimeReader(entity, lines);
entity.Children.Add(reader.CreateMimeEntity());
}
/// <summary>
/// Gets the type of the content.
/// </summary>
/// <param name="contentType">Type of the content.</param>
/// <returns></returns>
public static ContentType GetContentType(string contentType)
{
if (string.IsNullOrEmpty(contentType))
{
contentType = "text/plain; charset=us-ascii";
}
return new ContentType(contentType);
}
/// <summary>
/// Gets the type of the media.
/// </summary>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
public static string GetMediaType(string mediaType)
{
if (string.IsNullOrEmpty(mediaType))
{
return "text/plain";
}
return mediaType.Trim();
}
/// <summary>
/// Gets the type of the media main.
/// </summary>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
public static string GetMediaMainType(string mediaType)
{
int separatorIndex = mediaType.IndexOf('/');
if (separatorIndex < 0)
{
return mediaType;
}
else
{
return mediaType.Substring(0, separatorIndex);
}
}
/// <summary>
/// Gets the type of the media sub.
/// </summary>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
public static string GetMediaSubType(string mediaType)
{
int separatorIndex = mediaType.IndexOf('/');
if (separatorIndex < 0)
{
if (mediaType.Equals("text"))
{
return "plain";
}
return string.Empty;
}
else
{
if (mediaType.Length > separatorIndex)
{
return mediaType.Substring(separatorIndex + 1);
}
else
{
string mainType = GetMediaMainType(mediaType);
if (mainType.Equals("text"))
{
return "plain";
}
return string.Empty;
}
}
}
/// <summary>
/// Gets the transfer encoding.
/// </summary>
/// <param name="transferEncoding">The transfer encoding.</param>
/// <returns></returns>
/// <remarks>
/// The transfer encoding determination follows the same rules as
/// Peter Huber's article w/ the exception of not throwing exceptions
/// when binary is provided as a transferEncoding. Instead it is left
/// to the calling code to check for binary.
/// </remarks>
public static TransferEncoding GetTransferEncoding(string transferEncoding)
{
switch (transferEncoding.Trim().ToLowerInvariant())
{
case "7bit":
case "8bit":
return System.Net.Mime.TransferEncoding.SevenBit;
case "quoted-printable":
return System.Net.Mime.TransferEncoding.QuotedPrintable;
case "base64":
return System.Net.Mime.TransferEncoding.Base64;
case "binary":
default:
return System.Net.Mime.TransferEncoding.Unknown;
}
}
}
}