forked from aspnet/AspNetWebStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMimeMultipartParser.cs
More file actions
807 lines (695 loc) · 31.2 KB
/
Copy pathMimeMultipartParser.cs
File metadata and controls
807 lines (695 loc) · 31.2 KB
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
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Text;
using System.Web.Http;
namespace System.Net.Http.Formatting.Parsers
{
/// <summary>
/// Buffer-oriented MIME multipart parser.
/// </summary>
internal class MimeMultipartParser
{
internal const int MinMessageSize = 10;
private const int MaxBoundarySize = 256;
private const byte HTAB = 0x09;
private const byte SP = 0x20;
private const byte CR = 0x0D;
private const byte LF = 0x0A;
private const byte Dash = 0x2D;
private static readonly ArraySegment<byte> _emptyBodyPart = new ArraySegment<byte>(new byte[0]);
private long _totalBytesConsumed;
private long _maxMessageSize;
private BodyPartState _bodyPartState;
private string _boundary;
private CurrentBodyPartStore _currentBoundary;
/// <summary>
/// Initializes a new instance of the <see cref="MimeMultipartParser"/> class.
/// </summary>
/// <param name="boundary">Message boundary</param>
/// <param name="maxMessageSize">Maximum length of entire MIME multipart message.</param>
public MimeMultipartParser(string boundary, long maxMessageSize)
{
// The minimum length which would be an empty message terminated by CRLF
if (maxMessageSize < MimeMultipartParser.MinMessageSize)
{
throw Error.ArgumentMustBeGreaterThanOrEqualTo("maxMessageSize", maxMessageSize, MinMessageSize);
}
if (String.IsNullOrWhiteSpace(boundary))
{
throw Error.ArgumentNull("boundary");
}
if (boundary.Length > MaxBoundarySize - 10)
{
throw Error.ArgumentMustBeLessThanOrEqualTo("boundary", boundary.Length, MaxBoundarySize - 10);
}
if (boundary.EndsWith(" ", StringComparison.Ordinal))
{
throw Error.Argument("boundary", Properties.Resources.MimeMultipartParserBadBoundary);
}
_maxMessageSize = maxMessageSize;
_boundary = boundary;
_currentBoundary = new CurrentBodyPartStore(_boundary);
_bodyPartState = BodyPartState.AfterFirstLineFeed;
}
public bool IsWaitingForEndOfMessage
{
get
{
return
_bodyPartState == BodyPartState.AfterBoundary &&
_currentBoundary != null &&
_currentBoundary.IsFinal;
}
}
private enum BodyPartState
{
BodyPart = 0,
AfterFirstCarriageReturn,
AfterFirstLineFeed,
AfterFirstDash,
Boundary,
AfterBoundary,
AfterSecondDash,
AfterSecondCarriageReturn
}
private enum MessageState
{
Boundary = 0, // about to parse boundary
BodyPart, // about to parse body-part
CloseDelimiter // about to read close-delimiter
}
/// <summary>
/// Represents the overall state of the <see cref="MimeMultipartParser"/>.
/// </summary>
public enum State
{
/// <summary>
/// Need more data
/// </summary>
NeedMoreData = 0,
/// <summary>
/// Parsing of a complete body part succeeded.
/// </summary>
BodyPartCompleted,
/// <summary>
/// Bad data format
/// </summary>
Invalid,
/// <summary>
/// Data exceeds the allowed size
/// </summary>
DataTooBig,
}
public bool CanParseMore(int bytesRead, int bytesConsumed)
{
if (bytesConsumed < bytesRead)
{
// If there's more bytes we haven't parsed, then we can parse more
return true;
}
if (bytesRead == 0 && IsWaitingForEndOfMessage)
{
// If we're waiting for the end of the message and we've arrived there, we want parse to be called
// again so we can mark the parse as complete.
//
// This can happen when the last boundary segment doesn't have a trailing CRLF. We need to wait until
// the end of the message to complete the parse because we need to consume any trailing whitespace that's
//present.
return true;
}
return false;
}
/// <summary>
/// Parse a MIME multipart message. Bytes are parsed in a consuming
/// manner from the beginning of the request buffer meaning that the same bytes can not be
/// present in the request buffer.
/// </summary>
/// <param name="buffer">Request buffer from where request is read</param>
/// <param name="bytesReady">Size of request buffer</param>
/// <param name="bytesConsumed">Offset into request buffer</param>
/// <param name="remainingBodyPart">Any body part that was considered as a potential MIME multipart boundary but which was in fact part of the body.</param>
/// <param name="bodyPart">The bulk of the body part.</param>
/// <param name="isFinalBodyPart">Indicates whether the final body part has been found.</param>
/// <remarks>In order to get the complete body part, the caller is responsible for concatenating the contents of the
/// <paramref name="remainingBodyPart"/> and <paramref name="bodyPart"/> out parameters.</remarks>
/// <returns>State of the parser.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Exception is translated to parse state.")]
public State ParseBuffer(
byte[] buffer,
int bytesReady,
ref int bytesConsumed,
out ArraySegment<byte> remainingBodyPart,
out ArraySegment<byte> bodyPart,
out bool isFinalBodyPart)
{
if (buffer == null)
{
throw Error.ArgumentNull("buffer");
}
State parseStatus = State.NeedMoreData;
remainingBodyPart = MimeMultipartParser._emptyBodyPart;
bodyPart = MimeMultipartParser._emptyBodyPart;
isFinalBodyPart = false;
try
{
parseStatus = MimeMultipartParser.ParseBodyPart(
buffer,
bytesReady,
ref bytesConsumed,
ref _bodyPartState,
_maxMessageSize,
ref _totalBytesConsumed,
_currentBoundary);
}
catch (Exception)
{
parseStatus = State.Invalid;
}
remainingBodyPart = _currentBoundary.GetDiscardedBoundary();
bodyPart = _currentBoundary.BodyPart;
if (parseStatus == State.BodyPartCompleted)
{
isFinalBodyPart = _currentBoundary.IsFinal;
_currentBoundary.ClearAll();
}
else
{
_currentBoundary.ClearBodyPart();
}
return parseStatus;
}
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "This is a parser which cannot be split up for performance reasons.")]
private static State ParseBodyPart(
byte[] buffer,
int bytesReady,
ref int bytesConsumed,
ref BodyPartState bodyPartState,
long maximumMessageLength,
ref long totalBytesConsumed,
CurrentBodyPartStore currentBodyPart)
{
Contract.Assert((bytesReady - bytesConsumed) >= 0, "ParseBodyPart()|(bytesReady - bytesConsumed) < 0");
Contract.Assert(maximumMessageLength <= 0 || totalBytesConsumed <= maximumMessageLength, "ParseBodyPart()|Message already read exceeds limit.");
// Remember where we started.
int segmentStart;
int initialBytesParsed = bytesConsumed;
if (bytesReady == 0 && bodyPartState == BodyPartState.AfterBoundary && currentBodyPart.IsFinal)
{
// We've seen the end of the stream - the final body part has no trailing CRLF
return State.BodyPartCompleted;
}
// Set up parsing status with what will happen if we exceed the buffer.
State parseStatus = State.DataTooBig;
long effectiveMax = maximumMessageLength <= 0 ? Int64.MaxValue : (maximumMessageLength - totalBytesConsumed + bytesConsumed);
if (effectiveMax == 0)
{
// effectiveMax is based on our max message size - if we've arrrived at the max size, then we need
// to stop parsing.
return State.DataTooBig;
}
if (bytesReady <= effectiveMax)
{
parseStatus = State.NeedMoreData;
effectiveMax = bytesReady;
}
currentBodyPart.ResetBoundaryOffset();
Contract.Assert(bytesConsumed < effectiveMax, "We have already consumed more than the max header length.");
switch (bodyPartState)
{
case BodyPartState.BodyPart:
while (buffer[bytesConsumed] != MimeMultipartParser.CR)
{
if (++bytesConsumed == effectiveMax)
{
goto quit;
}
}
// Remember potential boundary
currentBodyPart.AppendBoundary(MimeMultipartParser.CR);
// Move past the CR
bodyPartState = BodyPartState.AfterFirstCarriageReturn;
if (++bytesConsumed == effectiveMax)
{
goto quit;
}
goto case BodyPartState.AfterFirstCarriageReturn;
case BodyPartState.AfterFirstCarriageReturn:
if (buffer[bytesConsumed] != MimeMultipartParser.LF)
{
currentBodyPart.ResetBoundary();
bodyPartState = BodyPartState.BodyPart;
goto case BodyPartState.BodyPart;
}
// Remember potential boundary
currentBodyPart.AppendBoundary(MimeMultipartParser.LF);
// Move past the CR
bodyPartState = BodyPartState.AfterFirstLineFeed;
if (++bytesConsumed == effectiveMax)
{
goto quit;
}
goto case BodyPartState.AfterFirstLineFeed;
case BodyPartState.AfterFirstLineFeed:
if (buffer[bytesConsumed] == MimeMultipartParser.CR)
{
// Remember potential boundary
currentBodyPart.ResetBoundary();
currentBodyPart.AppendBoundary(MimeMultipartParser.CR);
// Move past the CR
bodyPartState = BodyPartState.AfterFirstCarriageReturn;
if (++bytesConsumed == effectiveMax)
{
goto quit;
}
goto case BodyPartState.AfterFirstCarriageReturn;
}
if (buffer[bytesConsumed] != MimeMultipartParser.Dash)
{
currentBodyPart.ResetBoundary();
bodyPartState = BodyPartState.BodyPart;
goto case BodyPartState.BodyPart;
}
// Remember potential boundary
currentBodyPart.AppendBoundary(MimeMultipartParser.Dash);
// Move past the Dash
bodyPartState = BodyPartState.AfterFirstDash;
if (++bytesConsumed == effectiveMax)
{
goto quit;
}
goto case BodyPartState.AfterFirstDash;
case BodyPartState.AfterFirstDash:
if (buffer[bytesConsumed] != MimeMultipartParser.Dash)
{
currentBodyPart.ResetBoundary();
bodyPartState = BodyPartState.BodyPart;
goto case BodyPartState.BodyPart;
}
// Remember potential boundary
currentBodyPart.AppendBoundary(MimeMultipartParser.Dash);
// Move past the Dash
bodyPartState = BodyPartState.Boundary;
if (++bytesConsumed == effectiveMax)
{
goto quit;
}
goto case BodyPartState.Boundary;
case BodyPartState.Boundary:
segmentStart = bytesConsumed;
while (buffer[bytesConsumed] != MimeMultipartParser.CR)
{
if (++bytesConsumed == effectiveMax)
{
if (currentBodyPart.AppendBoundary(buffer, segmentStart, bytesConsumed - segmentStart))
{
if (currentBodyPart.IsBoundaryComplete())
{
// At this point we've seen the end of a boundary segment that is aligned at the end
// of the buffer - this might be because we have another segment coming or it might
// truly be the end of the message.
bodyPartState = BodyPartState.AfterBoundary;
}
}
else
{
currentBodyPart.ResetBoundary();
bodyPartState = BodyPartState.BodyPart;
}
goto quit;
}
}
if (bytesConsumed > segmentStart)
{
if (!currentBodyPart.AppendBoundary(buffer, segmentStart, bytesConsumed - segmentStart))
{
currentBodyPart.ResetBoundary();
bodyPartState = BodyPartState.BodyPart;
goto case BodyPartState.BodyPart;
}
}
goto case BodyPartState.AfterBoundary;
case BodyPartState.AfterBoundary:
// This state means that we just saw the end of a boundary. It might by a 'normal' boundary, in which
// case it's followed by optional whitespace and a CRLF. Or it might be the 'final' boundary and will
// be followed by '--', optional whitespace and an optional CRLF.
if (buffer[bytesConsumed] == MimeMultipartParser.Dash && !currentBodyPart.IsFinal)
{
currentBodyPart.AppendBoundary(MimeMultipartParser.Dash);
if (++bytesConsumed == effectiveMax)
{
bodyPartState = BodyPartState.AfterSecondDash;
goto quit;
}
goto case BodyPartState.AfterSecondDash;
}
// Capture optional whitespace
segmentStart = bytesConsumed;
while (buffer[bytesConsumed] != MimeMultipartParser.CR)
{
if (++bytesConsumed == effectiveMax)
{
if (!currentBodyPart.AppendBoundary(buffer, segmentStart, bytesConsumed - segmentStart))
{
// It's an unexpected character
currentBodyPart.ResetBoundary();
bodyPartState = BodyPartState.BodyPart;
}
goto quit;
}
}
if (bytesConsumed > segmentStart)
{
if (!currentBodyPart.AppendBoundary(buffer, segmentStart, bytesConsumed - segmentStart))
{
currentBodyPart.ResetBoundary();
bodyPartState = BodyPartState.BodyPart;
goto case BodyPartState.BodyPart;
}
}
if (buffer[bytesConsumed] == MimeMultipartParser.CR)
{
currentBodyPart.AppendBoundary(MimeMultipartParser.CR);
if (++bytesConsumed == effectiveMax)
{
bodyPartState = BodyPartState.AfterSecondCarriageReturn;
goto quit;
}
goto case BodyPartState.AfterSecondCarriageReturn;
}
else
{
// It's an unexpected character
currentBodyPart.ResetBoundary();
bodyPartState = BodyPartState.BodyPart;
goto case BodyPartState.BodyPart;
}
case BodyPartState.AfterSecondDash:
if (buffer[bytesConsumed] == MimeMultipartParser.Dash)
{
currentBodyPart.AppendBoundary(MimeMultipartParser.Dash);
bytesConsumed++;
if (currentBodyPart.IsBoundaryComplete())
{
Debug.Assert(currentBodyPart.IsFinal);
// If we get in here, it means we've see the trailing '--' of the last boundary - in order to consume all of the
// remaining bytes, we don't mark the parse as complete again - wait until this method is called again with the
// empty buffer to do that.
bodyPartState = BodyPartState.AfterBoundary;
parseStatus = State.NeedMoreData;
goto quit;
}
else
{
currentBodyPart.ResetBoundary();
if (bytesConsumed == effectiveMax)
{
goto quit;
}
goto case BodyPartState.BodyPart;
}
}
else
{
currentBodyPart.ResetBoundary();
bodyPartState = BodyPartState.BodyPart;
goto case BodyPartState.BodyPart;
}
case BodyPartState.AfterSecondCarriageReturn:
if (buffer[bytesConsumed] != MimeMultipartParser.LF)
{
currentBodyPart.ResetBoundary();
bodyPartState = BodyPartState.BodyPart;
goto case BodyPartState.BodyPart;
}
currentBodyPart.AppendBoundary(MimeMultipartParser.LF);
bytesConsumed++;
bodyPartState = BodyPartState.BodyPart;
if (currentBodyPart.IsBoundaryComplete())
{
parseStatus = State.BodyPartCompleted;
goto quit;
}
else
{
currentBodyPart.ResetBoundary();
if (bytesConsumed == effectiveMax)
{
goto quit;
}
goto case BodyPartState.BodyPart;
}
}
quit:
if (initialBytesParsed < bytesConsumed)
{
int boundaryLength = currentBodyPart.BoundaryDelta;
if (boundaryLength > 0 && parseStatus != State.BodyPartCompleted)
{
currentBodyPart.HasPotentialBoundaryLeftOver = true;
}
int bodyPartEnd = bytesConsumed - initialBytesParsed - boundaryLength;
currentBodyPart.BodyPart = new ArraySegment<byte>(buffer, initialBytesParsed, bodyPartEnd);
}
totalBytesConsumed += bytesConsumed - initialBytesParsed;
return parseStatus;
}
/// <summary>
/// Maintains information about the current body part being parsed.
/// </summary>
[DebuggerDisplay("{DebuggerToString()}")]
private class CurrentBodyPartStore
{
private const int InitialOffset = 2;
private byte[] _boundaryStore = new byte[MaxBoundarySize];
private int _boundaryStoreLength;
private byte[] _referenceBoundary = new byte[MaxBoundarySize];
private int _referenceBoundaryLength;
private byte[] _boundary = new byte[MaxBoundarySize];
private int _boundaryLength = 0;
private ArraySegment<byte> _bodyPart = MimeMultipartParser._emptyBodyPart;
private bool _isFinal;
private bool _isFirst = true;
private bool _releaseDiscardedBoundary;
private int _boundaryOffset;
/// <summary>
/// Initializes a new instance of the <see cref="CurrentBodyPartStore"/> class.
/// </summary>
/// <param name="referenceBoundary">The reference boundary.</param>
public CurrentBodyPartStore(string referenceBoundary)
{
Contract.Assert(referenceBoundary != null);
_referenceBoundary[0] = MimeMultipartParser.CR;
_referenceBoundary[1] = MimeMultipartParser.LF;
_referenceBoundary[2] = MimeMultipartParser.Dash;
_referenceBoundary[3] = MimeMultipartParser.Dash;
_referenceBoundaryLength = 4 + Encoding.UTF8.GetBytes(referenceBoundary, 0, referenceBoundary.Length, _referenceBoundary, 4);
_boundary[0] = MimeMultipartParser.CR;
_boundary[1] = MimeMultipartParser.LF;
_boundaryLength = CurrentBodyPartStore.InitialOffset;
}
/// <summary>
/// Gets or sets a value indicating whether this instance has potential boundary left over.
/// </summary>
/// <value>
/// <c>true</c> if this instance has potential boundary left over; otherwise, <c>false</c>.
/// </value>
public bool HasPotentialBoundaryLeftOver { get; set; }
/// <summary>
/// Gets the boundary delta.
/// </summary>
public int BoundaryDelta
{
get { return (_boundaryLength - _boundaryOffset > 0) ? _boundaryLength - _boundaryOffset : _boundaryLength; }
}
/// <summary>
/// Gets or sets the body part.
/// </summary>
/// <value>
/// The body part.
/// </value>
public ArraySegment<byte> BodyPart
{
get { return _bodyPart; }
set { _bodyPart = value; }
}
/// <summary>
/// Gets a value indicating whether this body part instance is final.
/// </summary>
/// <value>
/// <c>true</c> if this body part instance is final; otherwise, <c>false</c>.
/// </value>
public bool IsFinal
{
get { return _isFinal; }
}
/// <summary>
/// Resets the boundary offset.
/// </summary>
public void ResetBoundaryOffset()
{
_boundaryOffset = _boundaryLength;
}
/// <summary>
/// Resets the boundary.
/// </summary>
public void ResetBoundary()
{
// If we had a potential boundary left over then store it so that we don't loose it
if (HasPotentialBoundaryLeftOver)
{
Buffer.BlockCopy(_boundary, 0, _boundaryStore, 0, _boundaryOffset);
_boundaryStoreLength = _boundaryOffset;
HasPotentialBoundaryLeftOver = false;
_releaseDiscardedBoundary = true;
}
_boundaryLength = 0;
_boundaryOffset = 0;
}
/// <summary>
/// Appends byte to the current boundary.
/// </summary>
/// <param name="data">The data to append to the boundary.</param>
public void AppendBoundary(byte data)
{
_boundary[_boundaryLength++] = data;
}
/// <summary>
/// Appends array of bytes to the current boundary.
/// </summary>
/// <param name="data">The data to append to the boundary.</param>
/// <param name="offset">The offset into the data.</param>
/// <param name="count">The number of bytes to append.</param>
public bool AppendBoundary(byte[] data, int offset, int count)
{
// Check that potential boundary is not bigger than our reference boundary.
// Allow for 2 extra characters to include the final boundary which ends with
// an additional "--" sequence + plus up to 4 LWS characters (which are allowed).
if (_boundaryLength + count > _referenceBoundaryLength + 6)
{
return false;
}
int cnt = _boundaryLength;
Buffer.BlockCopy(data, offset, _boundary, _boundaryLength, count);
_boundaryLength += count;
// Verify that boundary matches so far
int maxCount = Math.Min(_boundaryLength, _referenceBoundaryLength);
for (; cnt < maxCount; cnt++)
{
if (_boundary[cnt] != _referenceBoundary[cnt])
{
return false;
}
}
return true;
}
/// <summary>
/// Gets the discarded boundary.
/// </summary>
/// <returns>An <see cref="ArraySegment{T}"/> containing the discarded boundary.</returns>
public ArraySegment<byte> GetDiscardedBoundary()
{
if (_boundaryStoreLength > 0 && _releaseDiscardedBoundary)
{
ArraySegment<byte> discarded = new ArraySegment<byte>(_boundaryStore, 0, _boundaryStoreLength);
_boundaryStoreLength = 0;
return discarded;
}
return MimeMultipartParser._emptyBodyPart;
}
/// <summary>
/// Determines whether current boundary is valid.
/// </summary>
/// <returns>
/// <c>true</c> if curent boundary is valid; otherwise, <c>false</c>.
/// </returns>
public bool IsBoundaryValid()
{
int offset = 0;
if (_isFirst)
{
offset = CurrentBodyPartStore.InitialOffset;
}
int count = offset;
for (; count < _referenceBoundaryLength; count++)
{
if (_boundary[count] != _referenceBoundary[count])
{
return false;
}
}
// Check for final
bool boundaryIsFinal = false;
if (_boundary[count] == MimeMultipartParser.Dash &&
_boundary[count + 1] == MimeMultipartParser.Dash)
{
boundaryIsFinal = true;
count += 2;
}
// Rest of boundary must be ignorable whitespace in order for it to match
for (; count < _boundaryLength - 2; count++)
{
if (_boundary[count] != MimeMultipartParser.SP && _boundary[count] != MimeMultipartParser.HTAB)
{
return false;
}
}
// We have a valid boundary so whatever we stored in the boundary story is no longer needed
_isFinal = boundaryIsFinal;
_isFirst = false;
return true;
}
public bool IsBoundaryComplete()
{
if (!IsBoundaryValid())
{
return false;
}
if (_boundaryLength < _referenceBoundaryLength)
{
return false;
}
if (_boundaryLength == _referenceBoundaryLength + 1 &&
_boundary[_referenceBoundaryLength] == MimeMultipartParser.Dash)
{
return false;
}
return true;
}
/// <summary>
/// Clears the body part.
/// </summary>
public void ClearBodyPart()
{
BodyPart = MimeMultipartParser._emptyBodyPart;
}
/// <summary>
/// Clears all.
/// </summary>
public void ClearAll()
{
_releaseDiscardedBoundary = false;
HasPotentialBoundaryLeftOver = false;
_boundaryLength = 0;
_boundaryOffset = 0;
_boundaryStoreLength = 0;
_isFinal = false;
ClearBodyPart();
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Used for Debugger Display.")]
private string DebuggerToString()
{
var referenceBoundary = Encoding.UTF8.GetString(_referenceBoundary, 0, _referenceBoundaryLength);
var boundary = Encoding.UTF8.GetString(_boundary, 0, _boundaryLength);
return String.Format(
CultureInfo.InvariantCulture,
"Expected: {0} *** Current: {1}",
referenceBoundary,
boundary);
}
}
}
}