-
Notifications
You must be signed in to change notification settings - Fork 3
/
WinMailParser.cs
614 lines (512 loc) · 20.4 KB
/
WinMailParser.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
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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using WinMailParser.Logging;
namespace WinMailParser
{
/// <summary>
/// Used to parse attachments that have the MIME-type Application/MS-TNEF
/// TNEF stands for Transport Neutral Encapsulation Format, and is proprietary Microsoft attachment format.
///
/// Based on tnef.c from Thomas Boll.
/// </summary>
/// <remarks>
/// See http://en.wikipedia.org/wiki/Transport_Neutral_Encapsulation_Format
/// for more details
/// </remarks>
public class WinMailParser : Disposable
{
#region Member Variables
private const int TNEF_SIGNATURE = 0x223e9f78;
private const int LVL_MESSAGE = 0x01;
private const int LVL_ATTACHMENT = 0x02;
private const int _string = 0x00010000;
private const int _BYTE = 0x00060000;
private const int _WORD = 0x00070000;
private const int _DWORD = 0x00080000;
private const int AVERSION = (_DWORD | 0x9006); // Unused?
private const int AMCLASS = (_WORD | 0x8008); // Unused?
private const int ASUBJECT = (_DWORD | 0x8004);
private const int AFILENAME = (_string | 0x8010);
private const int ATTACHDATA = (_BYTE | 0x800f);
private const int ATTACHREND = (_BYTE | 0x9002);
private Stream fsTNEF;
private readonly List<WinMailAttachment> _attachments = new List<WinMailAttachment>();
private WinMailAttachment _attachment;
private long fileLength;
private string subject;
#endregion
#region Properties
/// <summary>
/// The file the parser is associated with
/// </summary>
public string TNEFFile { get; set; }
/// <summary>
/// Specifies whether to turn of verbose logging output
/// </summary>
public bool Verbose { get; set; }
/// <summary>
///
/// </summary>
public int SkipSignature { get; set; }
/// <summary>
/// The logging interface for the object
/// </summary>
private ILogger Log { get; set; }
#endregion
#region Constructors
/// <summary>
/// Used the set up default values
/// </summary>
/// <param name="logger">The logging interface to use</param>
/// <exception cref="ArgumentNullException">If <paramref name="logger"/> is <see langword="null"/></exception>
private WinMailParser( ILogger logger )
{
if ( logger == null )
throw new ArgumentNullException("logger");
Log = logger;
Verbose = false;
TNEFFile = string.Empty;
}
/// <summary>
/// Create a TNEFParser which loads its contents from a file
/// </summary>
/// <param name="file">MS-TNEF file</param>
/// <param name="logger">The logging interface to use</param>
/// <exception cref="ArgumentNullException">If <paramref name="file"/> or <paramref name="logger"/> is <see langword="null"/></exception>
/// <exception cref="ArgumentException">If <paramref name="file"/> could not be opened</exception>
public WinMailParser( FileInfo file, ILogger logger )
: this(logger)
{
if ( file == null )
throw new ArgumentNullException("file");
if ( !OpenTNEFStream(file) )
throw new ArgumentException("Error opening the file", "file");
}
/// <summary>
/// Create a TNEFParser which loads its contents from a byte array
/// </summary>
/// <param name="contents">MS-TNEF bytes</param>
/// <param name="logger">The logging interface to use</param>
/// <exception cref="ArgumentNullException">If <paramref name="contents"/> or <paramref name="logger"/> is <see langword="null"/></exception>
/// <exception cref="ArgumentException">If <paramref name="contents"/> could not be opened as a stream</exception>
public WinMailParser( byte[] contents, ILogger logger )
: this(logger)
{
if ( contents == null )
throw new ArgumentNullException("contents");
if ( !OpenTNEFStream(contents) )
throw new ArgumentException("The contents is invalid", "contents");
}
#endregion
private static int GETINT32( byte[] p )
{
return (p[0] + (p[1] << 8) + (p[2] << 16) + (p[3] << 24));
}
private static short GETINT16( byte[] p )
{
return (short)(p[0] + (p[1] << 8));
}
private int geti32()
{
byte[] buffer = new byte[4];
if ( StreamReadBytes(buffer, 4) != 1 )
{
Log.LogError("geti32():unexpected end of input\n");
return 1;
}
return GETINT32(buffer);
}
private int geti16()
{
byte[] buffer = new byte[2];
if ( StreamReadBytes(buffer, 2) != 1 )
{
Log.LogError("geti16():unexpected end of input\n");
return 1;
}
return GETINT16(buffer);
}
private int geti8()
{
byte[] buffer = new byte[1];
if ( StreamReadBytes(buffer, 1) != 1 )
{
Log.LogError("geti8():unexpected end of input\n");
return 1;
}
return buffer[0];
}
private int StreamReadBytes( byte[] buffer, int size )
{
try
{
if ( fsTNEF.Position + size <= fileLength )
{
fsTNEF.Read(buffer, 0, size);
return 1;
}
return 0;
}
catch ( Exception e )
{
Log.LogError("StreamReadBytes():" + e.Message);
return 0;
}
}
private void CloseTNEFStream()
{
if ( fsTNEF == null )
return;
try
{
Stream stream = fsTNEF;
fsTNEF = null;
stream.Close();
}
catch ( Exception e )
{
Log.LogError("CloseTNEFStream():" + e.Message);
}
}
/// <summary>
/// Open the MS-TNEF stream from file
/// </summary>
/// <param name="file">MS-TNEF file</param>
/// <returns></returns>
private bool OpenTNEFStream( FileInfo file )
{
if ( file == null )
throw new ArgumentNullException("file");
TNEFFile = file.FullName;
try
{
fsTNEF = file.OpenRead();
fileLength = file.Length;
return true;
}
catch ( Exception e )
{
fsTNEF = null;
Log.LogError("OpenTNEFStream(File):" + e.Message);
return false;
}
}
/// <summary>
/// Open the MS-TNEF stream from bytes
/// </summary>
/// <param name="contents">MS-TNEF bytes</param>
/// <returns></returns>
/// <exception cref="ArgumentNullException">If <paramref name="contents"/> is <see langword="null"/></exception>
private bool OpenTNEFStream( byte[] contents )
{
if ( contents == null )
throw new ArgumentNullException("contents");
try
{
fsTNEF = new MemoryStream(contents);
fileLength = contents.Length;
return true;
}
catch ( Exception e )
{
fsTNEF = null;
Log.LogError("OpenTNEFStream(Bytes):" + e.Message);
return false;
}
}
/// <summary>
/// Find the MS-TNEF signature
/// </summary>
/// <returns>true if found, vice versa</returns>
public bool FindSignature()
{
AssertDisposed();
bool returner;
long leftPosition = 0;
try
{
for ( leftPosition = 0; ; leftPosition++ )
{
if ( fsTNEF.Seek(leftPosition, SeekOrigin.Begin) == -1 )
{
PrintResult("No signature found\n");
return false;
}
int d = geti32();
if ( d == TNEF_SIGNATURE )
{
PrintResult("Signature found at {0}\n", leftPosition);
break;
}
}
returner = true;
}
catch ( Exception e )
{
Log.LogError("FindSignature():" + e.Message);
returner = false;
}
fsTNEF.Position = leftPosition;
return returner;
}
private void decode_attribute( int d )
{
byte[] buffer = new byte[4000];
int i;
int length = geti32();
switch ( d & 0xffff0000 )
{
case _BYTE:
PrintResult("Attribute {0} =", d & 0xffff);
for ( i = 0; i < length; i++ )
{
int v = geti8();
if ( i < 10 ) PrintResult(" {0}", v);
else if ( i == 10 ) PrintResult("...");
}
PrintResult("\n");
break;
case _WORD:
PrintResult("Attribute {0} =", d & 0xffff);
for ( i = 0; i < length; i += 2 )
{
int v = geti16();
if ( i < 6 ) PrintResult(" {0}", v);
else if ( i == 6 ) PrintResult("...");
}
PrintResult("\n");
break;
case _DWORD:
PrintResult("Attribute {0} =", d & 0xffff);
for ( i = 0; i < length; i += 4 )
{
int v = geti32();
if ( i < 4 ) PrintResult(" {0}", v);
else if ( i == 4 ) PrintResult("...");
}
PrintResult("\n");
break;
case _string:
StreamReadBytes(buffer, length);
PrintResult("Attribute {0} = {1}\n", d & 0xffff, Encoding.Default.GetString(buffer));
break;
default:
StreamReadBytes(buffer, length);
PrintResult("Attribute {0}\n", d);
break;
}
geti16(); /* checksum */
}
private void decode_message()
{
int d = geti32();
decode_attribute(d);
}
private void decode_attachment()
{
byte[] buffer = new byte[4096];
int length;
int d = geti32();
switch ( d )
{
case ATTACHREND:
_attachment = new WinMailAttachment();
_attachments.Add(_attachment);
length = geti32();
StreamReadBytes(buffer, length);
geti16(); /* checksum */
break;
case ASUBJECT:
length = geti32();
StreamReadBytes(buffer, length);
byte[] _subjectBuffer = new byte[length - 1];
Array.Copy(buffer, _subjectBuffer, (long)length - 1);
subject = Encoding.Default.GetString(_subjectBuffer);
PrintResult("Found subject: {0}", subject);
geti16(); /* checksum */
break;
case AFILENAME:
length = geti32();
StreamReadBytes(buffer, length);
//PrintResult("File-Name: {0}\n", buf);
byte[] _fileNameBuffer = new byte[length - 1];
Array.Copy(buffer, _fileNameBuffer, (long)length - 1);
string strFileName = Encoding.Default.GetString(_fileNameBuffer);
//new attachment found because attachment data goes before attachment name
_attachment.FileName = strFileName;
_attachment.Subject = subject;
geti16(); /* checksum */
break;
case ATTACHDATA:
length = geti32();
PrintResult("ATTACH-DATA: {0} bytes\n", length);
_attachment.Content = new byte[length];
_attachment.Length = length;
for ( int i = 0; i < length; )
{
int chunk = length - i;
if ( chunk > buffer.Length ) chunk = buffer.Length;
StreamReadBytes(buffer, chunk);
Array.Copy(buffer, 0, _attachment.Content, i, chunk);
i += chunk;
}
geti16(); /* checksum */
break;
default:
decode_attribute(d);
break;
}
}
/// <summary>
/// decoded attachments
/// </summary>
/// <returns>attachment array</returns>
public List<WinMailAttachment> Attachments()
{
AssertDisposed();
return _attachments;
}
/// <summary>
/// save all decoded attachments to files
/// </summary>
/// <returns><see langword="true"/> if succeeded, <see langword="false"/> otherwise</returns>
/// <exception cref="ArgumentNullException">If <paramref name="pathToSaveTo"/> is <see langword="null"/></exception>
public bool SaveAttachments( DirectoryInfo pathToSaveTo )
{
AssertDisposed();
if ( pathToSaveTo == null )
throw new ArgumentNullException("pathToSaveTo");
bool result = false;
foreach ( WinMailAttachment tnefAttachment in _attachments )
{
result = SaveAttachment(tnefAttachment, pathToSaveTo, Log);
}
return result;
}
/// <summary>
/// save a decoded attachment to file
/// </summary>
/// <param name="attachment">decoded attachment</param>
/// <param name="pathToSaveTo">Where to save the attachment to</param>
/// <returns><see langword="true"/> if succeeded, <see langword="false"/> otherwise</returns>
/// <exception cref="ArgumentNullException">If <paramref name="attachment"/> or <paramref name="pathToSaveTo"/> is <see langword="null"/></exception>
/// <exception cref="ArgumentException">If <paramref name="pathToSaveTo"/> does not exist</exception>
public static bool SaveAttachment( WinMailAttachment attachment, DirectoryInfo pathToSaveTo )
{
if ( attachment == null )
throw new ArgumentNullException("attachment");
if ( pathToSaveTo == null )
throw new ArgumentNullException("pathToSaveTo");
if ( !pathToSaveTo.Exists )
throw new ArgumentException("The path " + pathToSaveTo.FullName + " does not exist");
return SaveAttachment(attachment, pathToSaveTo, DefaultLogger.Create());
}
/// <summary>
/// save a decoded attachment to file
/// </summary>
/// <param name="attachment">decoded attachment</param>
/// <param name="pathToSaveTo">Where to save the attachment to</param>
/// <param name="logger">The object to use for logging output</param>
/// <returns><see langword="true"/> if succeeded, <see langword="false"/> otherwise</returns>
/// <exception cref="ArgumentNullException">If <paramref name="attachment"/>, <paramref name="pathToSaveTo"/> or <paramref name="logger"/> is <see langword="null"/></exception>
/// <exception cref="ArgumentException">If <paramref name="pathToSaveTo"/> does not exist</exception>
public static bool SaveAttachment( WinMailAttachment attachment, DirectoryInfo pathToSaveTo, ILogger logger )
{
if ( attachment == null )
throw new ArgumentNullException("attachment");
if ( pathToSaveTo == null )
throw new ArgumentNullException("pathToSaveTo");
if ( logger == null )
throw new ArgumentNullException("logger");
if ( !pathToSaveTo.Exists )
throw new ArgumentException("The path " + pathToSaveTo.FullName + " does not exist");
try
{
FileInfo outFile = new FileInfo(Path.Combine(pathToSaveTo.FullName, attachment.FileName));
if ( outFile.Exists )
outFile.Delete();
using ( FileStream fsData = outFile.Create() )
{
fsData.Write(attachment.Content, 0, (int)attachment.Length);
}
return true;
}
catch ( Exception e )
{
logger.LogError("SaveAttachment(): " + e.Message);
return false;
}
}
/// <summary>
/// parse MS-TNEF stream
/// </summary>
/// <returns><see langword="true"/> if succeeded, <see langword="false"/> otherwise</returns>
public bool Parse()
{
AssertDisposed();
byte[] buffer = new byte[4];
if ( FindSignature() )
{
int d;
if ( SkipSignature < 2 )
{
d = geti32();
if ( SkipSignature < 1 )
{
if ( d != TNEF_SIGNATURE )
{
PrintResult("Seems not to be a TNEF file\n");
return false;
}
}
}
d = geti16();
PrintResult("TNEF Key is: {0}\n", d);
for ( ; ; )
{
if ( StreamReadBytes(buffer, 1) == 0 )
break;
d = buffer[0];
switch ( d )
{
case LVL_MESSAGE:
PrintResult("{0}: Decoding Message Attributes\n", fsTNEF.Position);
decode_message();
break;
case LVL_ATTACHMENT:
PrintResult("Decoding Attachment\n");
decode_attachment();
break;
default:
PrintResult("Coding Error in TNEF file\n");
return false;
}
}
return true;
}
return false;
}
private void PrintResult( string result, params object[] content )
{
if ( Verbose )
{
Log.LogDebug(string.Format(result, content));
}
}
/// <summary>
/// Disposes of the managed resources within the object
/// </summary>
/// <param name="disposing">Specifies if managed resources are being disposed of</param>
protected override void Dispose( bool disposing )
{
if ( disposing && !IsDisposed )
{
CloseTNEFStream();
Log = null;
}
base.Dispose(disposing);
}
}
}