forked from jstedfast/MimeKit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInternetAddress.cs
1361 lines (1116 loc) · 49.1 KB
/
InternetAddress.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
863
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
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// InternetAddress.cs
//
// Author: Jeffrey Stedfast <[email protected]>
//
// Copyright (c) 2013-2024 .NET Foundation and Contributors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System;
using System.Text;
using System.Globalization;
using MimeKit.Utils;
namespace MimeKit {
/// <summary>
/// An abstract internet address, as specified by rfc0822.
/// </summary>
/// <remarks>
/// <para>An <see cref="InternetAddress"/> can be any type of address defined by the
/// original Internet Message specification.</para>
/// <para>There are effectively two (2) types of addresses: mailboxes and groups.</para>
/// <para>Mailbox addresses are what are most commonly known as email addresses and are
/// represented by the <see cref="MailboxAddress"/> class.</para>
/// <para>Group addresses are themselves lists of addresses and are represented by the
/// <see cref="GroupAddress"/> class. While rare, it is still important to handle these
/// types of addresses. They typically only contain mailbox addresses, but may also
/// contain other group addresses.</para>
/// </remarks>
public abstract class InternetAddress : IComparable<InternetAddress>, IEquatable<InternetAddress>
{
const string AtomSpecials = "()<>@,;:\\\".[]";
Encoding encoding;
string name;
/// <summary>
/// Initialize a new instance of the <see cref="InternetAddress"/> class.
/// </summary>
/// <remarks>
/// Initializes the <see cref="Encoding"/> and <see cref="Name"/> properties of the internet address.
/// </remarks>
/// <param name="encoding">The character encoding to be used for encoding the name.</param>
/// <param name="name">The name of the mailbox or group.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="encoding"/> is <c>null</c>.
/// </exception>
protected InternetAddress (Encoding encoding, string name)
{
if (encoding is null)
throw new ArgumentNullException (nameof (encoding));
Encoding = encoding;
Name = name;
}
/// <summary>
/// Get or set the character encoding to use when encoding the name of the address.
/// </summary>
/// <remarks>
/// The character encoding is used to convert the <see cref="Name"/> property, if it is set,
/// to a stream of bytes when encoding the internet address for transport.
/// </remarks>
/// <value>The character encoding.</value>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="value"/> is <c>null</c>.
/// </exception>
public Encoding Encoding {
get { return encoding; }
set {
if (value is null)
throw new ArgumentNullException (nameof (value));
if (value == encoding)
return;
encoding = value;
OnChanged ();
}
}
/// <summary>
/// Get or set the display name of the address.
/// </summary>
/// <remarks>
/// <para>A name is optional and is typically set to the name of the person
/// or group that own the internet address.</para>
/// <para>For example, the <see cref="Name"/> property of the following <see cref="MailboxAddress"/> would be <c>"John Smith"</c>.</para>
/// <para><c>John Smith <[email protected]></c></para>
/// <para>Likewise, the <see cref="Name"/> property of the following <see cref="GroupAddress"/> would be <c>"undisclosed-recipients"</c>.</para>
/// <para><c>undisclosed-recipients: Alice <[email protected]>, Bob <[email protected]>;</c></para>
/// </remarks>
/// <value>The name of the address.</value>
public string Name {
get { return name; }
set {
if (value == name)
return;
name = value;
OnChanged ();
}
}
/// <summary>
/// Clone the address.
/// </summary>
/// <remarks>
/// Clones the address.
/// </remarks>
/// <returns>The cloned address.</returns>
public abstract InternetAddress Clone ();
#region IComparable implementation
/// <summary>
/// Compares two internet addresses.
/// </summary>
/// <remarks>
/// Compares two internet addresses for the purpose of sorting.
/// </remarks>
/// <returns>The sort order of the current internet address compared to the other internet address.</returns>
/// <param name="other">The internet address to compare to.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="other"/> is <c>null</c>.
/// </exception>
public int CompareTo (InternetAddress other)
{
int rv;
if (other is null)
throw new ArgumentNullException (nameof (other));
if ((rv = string.Compare (Name, other.Name, StringComparison.OrdinalIgnoreCase)) != 0)
return rv;
var otherMailbox = other as MailboxAddress;
var mailbox = this as MailboxAddress;
if (mailbox != null && otherMailbox != null) {
string otherAddress = otherMailbox.Address;
int otherAt = otherAddress.IndexOf ('@');
string address = mailbox.Address;
int at = address.IndexOf ('@');
if (at != -1 && otherAt != -1) {
int length = Math.Min (address.Length - (at 1), otherAddress.Length - (otherAt 1));
rv = string.Compare (address, at 1, otherAddress, otherAt 1, length, StringComparison.OrdinalIgnoreCase);
}
if (rv == 0) {
int otherLength = otherAt == -1 ? otherAddress.Length : otherAt;
int length = at == -1 ? address.Length : at;
int n = Math.Min (length, otherLength);
if ((rv = string.Compare (address, 0, otherAddress, 0, n, StringComparison.OrdinalIgnoreCase)) == 0) {
// The local-part's of the addresses are identical for the first `n` characters. The address
// with the longer local-part should sort as > the address with the shorter local-part.
rv = length - otherLength;
}
}
return rv;
}
// sort mailbox addresses before group addresses
if (mailbox != null && otherMailbox is null)
return -1;
if (mailbox is null && otherMailbox != null)
return 1;
return 0;
}
#endregion
#region IEquatable implementation
/// <summary>
/// Determine whether the specified <see cref="InternetAddress"/> is equal to the current <see cref="InternetAddress"/>.
/// </summary>
/// <remarks>
/// Compares two internet addresses to determine if they are identical or not.
/// </remarks>
/// <param name="other">The <see cref="InternetAddress"/> to compare with the current <see cref="InternetAddress"/>.</param>
/// <returns><c>true</c> if the specified <see cref="InternetAddress"/> is equal to the current
/// <see cref="InternetAddress"/>; otherwise, <c>false</c>.</returns>
public abstract bool Equals (InternetAddress other);
#endregion
/// <summary>
/// Determine whether the specified object is equal to the current object.
/// </summary>
/// <remarks>
/// The type of comparison between the current instance and the <paramref name="obj"/> parameter depends on whether
/// the current instance is a reference type or a value type.
/// </remarks>
/// <param name="obj">The object to compare with the current object.</param>
/// <returns><c>true</c> if the specified object is equal to the current object; otherwise, <c>false</c>.</returns>
public override bool Equals (object obj)
{
return Equals (obj as InternetAddress);
}
/// <summary>
/// Return the hash code for this instance.
/// </summary>
/// <remarks>
/// Returns the hash code for this instance.
/// </remarks>
/// <returns>A hash code for the current object.</returns>
public override int GetHashCode ()
{
return ToString ().GetHashCode ();
}
internal static string EncodeInternationalizedPhrase (string phrase)
{
for (int i = 0; i < phrase.Length; i ) {
if (AtomSpecials.IndexOf (phrase[i]) != -1)
return MimeUtils.Quote (phrase);
}
return phrase;
}
internal abstract void Encode (FormatOptions options, StringBuilder builder, bool firstToken, ref int lineLength);
/// <summary>
/// Serialize an <see cref="InternetAddress"/> to a string, optionally encoding it for transport.
/// </summary>
/// <remarks>
/// <para>If the <paramref name="encode"/> parameter is <c>true</c>, then this method will return
/// an encoded version of the internet address according to the rules described in rfc2047.</para>
/// <para>However, if the <paramref name="encode"/> parameter is <c>false</c>, then this method will
/// return a string suitable only for display purposes.</para>
/// </remarks>
/// <returns>A string representing the <see cref="InternetAddress"/>.</returns>
/// <param name="options">The formatting options.</param>
/// <param name="encode">If set to <c>true</c>, the <see cref="InternetAddress"/> will be encoded.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="options"/> is <c>null</c>.
/// </exception>
public abstract string ToString (FormatOptions options, bool encode);
/// <summary>
/// Serialize an <see cref="InternetAddress"/> to a string, optionally encoding it for transport.
/// </summary>
/// <remarks>
/// <para>If the <paramref name="encode"/> parameter is <c>true</c>, then this method will return
/// an encoded version of the internet address according to the rules described in rfc2047.</para>
/// <para>However, if the <paramref name="encode"/> parameter is <c>false</c>, then this method will
/// return a string suitable only for display purposes.</para>
/// </remarks>
/// <returns>A string representing the <see cref="InternetAddress"/>.</returns>
/// <param name="encode">If set to <c>true</c>, the <see cref="InternetAddress"/> will be encoded.</param>
public string ToString (bool encode)
{
return ToString (FormatOptions.Default, encode);
}
/// <summary>
/// Serialize an <see cref="InternetAddress"/> to a string suitable for display.
/// </summary>
/// <remarks>
/// The string returned by this method is suitable only for display purposes.
/// </remarks>
/// <returns>A string representing the <see cref="InternetAddress"/>.</returns>
public override string ToString ()
{
return ToString (FormatOptions.Default, false);
}
internal event EventHandler Changed;
/// <summary>
/// Raise the internal changed event used by <see cref="MimeMessage"/> to keep headers in sync.
/// </summary>
/// <remarks>
/// This method is called whenever a property of the internet address is changed.
/// </remarks>
protected virtual void OnChanged ()
{
Changed?.Invoke (this, EventArgs.Empty);
}
internal static bool TryParseLocalPart (byte[] text, ref int index, int endIndex, RfcComplianceMode compliance, bool skipTrailingCfws, bool throwOnError, out string localpart)
{
using var token = new ValueStringBuilder (128);
int startIndex = index;
localpart = null;
do {
bool escapedAt = false;
int start = index;
if (text[index] == (byte) '"') {
if (!ParseUtils.SkipQuoted (text, ref index, endIndex, throwOnError))
return false;
} else if (text[index].IsAtom ()) {
if (!ParseUtils.SkipAtom (text, ref index, endIndex))
return false;
if (compliance == RfcComplianceMode.Looser) {
// Allow local-parts that include escaped '@' symbols.
// See https://github.com/jstedfast/MimeKit/issues/1043 for details.
while (index 1 < endIndex && text[index] == (byte) '\\' && text[index 1] == (byte) '@') {
// track that we've encountered an escaped @ symbol
escapedAt = true;
// skip over the '\\' and '@' characters
index = 2;
if (!ParseUtils.SkipAtom (text, ref index, endIndex))
break;
}
}
} else {
if (throwOnError)
throw new ParseException (string.Format (CultureInfo.InvariantCulture, "Invalid local-part at offset {0}", startIndex), startIndex, index);
return false;
}
string word;
try {
word = CharsetUtils.UTF8.GetString (text, start, index - start);
} catch (DecoderFallbackException ex) {
if (compliance == RfcComplianceMode.Strict) {
if (throwOnError)
throw new ParseException ("Internationalized local-part tokens may only contain UTF-8 characters.", start, start, ex);
return false;
}
word = CharsetUtils.Latin1.GetString (text, start, index - start);
}
if (escapedAt)
word = word.Replace ("\\@", "@");
token.Append (word);
int cfws = index;
if (!ParseUtils.SkipCommentsAndWhiteSpace (text, ref index, endIndex, throwOnError))
return false;
if (index >= endIndex || text[index] != (byte) '.') {
if (!skipTrailingCfws)
index = cfws;
break;
}
do {
token.Append ('.');
index ;
if (!ParseUtils.SkipCommentsAndWhiteSpace (text, ref index, endIndex, throwOnError))
return false;
if (index >= endIndex) {
if (throwOnError)
throw new ParseException (string.Format (CultureInfo.InvariantCulture, "Incomplete local-part at offset {0}", startIndex), startIndex, index);
return false;
}
} while (compliance == RfcComplianceMode.Looser && text[index] == (byte) '.');
if (compliance == RfcComplianceMode.Looser && (index >= endIndex || text[index] == (byte) '@'))
break;
} while (true);
localpart = token.ToString ();
return true;
}
static ReadOnlySpan<byte> CommaGreaterThanOrSemiColon => ",>;"u8;
internal static bool TryParseAddrspec (byte[] text, ref int index, int endIndex, ReadOnlySpan<byte> sentinels, RfcComplianceMode compliance, bool throwOnError, out string addrspec, out int at)
{
int startIndex = index;
addrspec = null;
at = -1;
if (!TryParseLocalPart (text, ref index, endIndex, compliance, true, throwOnError, out var localpart))
return false;
if (index >= endIndex || ParseUtils.IsSentinel (text[index], sentinels)) {
addrspec = localpart;
return true;
}
if (text[index] != (byte) '@') {
if (throwOnError)
throw new ParseException (string.Format (CultureInfo.InvariantCulture, "Invalid addr-spec token at offset {0}", startIndex), startIndex, index);
return false;
}
index ;
if (index >= endIndex) {
if (throwOnError)
throw new ParseException (string.Format (CultureInfo.InvariantCulture, "Incomplete addr-spec token at offset {0}", startIndex), startIndex, index);
return false;
}
if (!ParseUtils.SkipCommentsAndWhiteSpace (text, ref index, endIndex, throwOnError))
return false;
if (index >= endIndex) {
if (throwOnError)
throw new ParseException (string.Format (CultureInfo.InvariantCulture, "Incomplete addr-spec token at offset {0}", startIndex), startIndex, index);
return false;
}
if (!ParseUtils.TryParseDomain (text, ref index, endIndex, sentinels, throwOnError, out var domain))
return false;
if (ParseUtils.IsIdnEncoded (domain))
domain = MailboxAddress.IdnMapping.Decode (domain);
addrspec = localpart "@" domain;
at = localpart.Length;
return true;
}
internal static bool TryParseMailbox (ParserOptions options, byte[] text, int startIndex, ref int index, int endIndex, string name, int codepage, bool throwOnError, out InternetAddress address)
{
var encoding = CharsetUtils.GetEncodingOrDefault (codepage, Encoding.UTF8);
DomainList route = null;
address = null;
// skip over the '<'
index ;
// Note: check for excessive angle brackets like the example described in section 7.1.2 of rfc7103...
if (index < endIndex && text[index] == (byte) '<') {
if (options.AddressParserComplianceMode == RfcComplianceMode.Strict) {
if (throwOnError)
throw new ParseException (string.Format (CultureInfo.InvariantCulture, "Excessive angle brackets at offset {0}", index), startIndex, index);
return false;
}
do {
index ;
} while (index < endIndex && text[index] == '<');
}
if (!ParseUtils.SkipCommentsAndWhiteSpace (text, ref index, endIndex, throwOnError))
return false;
if (index >= endIndex) {
if (throwOnError)
throw new ParseException (string.Format (CultureInfo.InvariantCulture, "Incomplete mailbox at offset {0}", startIndex), startIndex, index);
return false;
}
if (text[index] == (byte) '@') {
// Note: we always pass 'false' as the throwOnError argument here so that we can throw a more informative exception on error
if (!DomainList.TryParse (text, ref index, endIndex, false, out route)) {
if (throwOnError)
throw new ParseException (string.Format (CultureInfo.InvariantCulture, "Invalid route in mailbox at offset {0}", startIndex), startIndex, index);
return false;
}
if (index >= endIndex || text[index] != (byte) ':') {
if (throwOnError)
throw new ParseException (string.Format (CultureInfo.InvariantCulture, "Incomplete route in mailbox at offset {0}", startIndex), startIndex, index);
return false;
}
// skip over ':'
index ;
if (!ParseUtils.SkipCommentsAndWhiteSpace (text, ref index, endIndex, throwOnError))
return false;
if (index >= endIndex) {
if (throwOnError)
throw new ParseException (string.Format (CultureInfo.InvariantCulture, "Incomplete mailbox at offset {0}", startIndex), startIndex, index);
return false;
}
}
// Note: The only syntactically correct sentinel token here is the '>', but alas... to deal with the first example
// in section 7.1.5 of rfc7103, we need to at least handle ',' as a sentinel and might as well handle ';' as well
// in case the mailbox is within a group address.
//
// Example: <[email protected], [email protected]>
if (!TryParseAddrspec (text, ref index, endIndex, CommaGreaterThanOrSemiColon, options.AddressParserComplianceMode, throwOnError, out string addrspec, out int at))
return false;
if (!ParseUtils.SkipCommentsAndWhiteSpace (text, ref index, endIndex, throwOnError))
return false;
if (index >= endIndex || text[index] != (byte) '>') {
if (options.AddressParserComplianceMode == RfcComplianceMode.Strict) {
if (throwOnError)
throw new ParseException (string.Format (CultureInfo.InvariantCulture, "Unexpected end of mailbox at offset {0}", startIndex), startIndex, index);
return false;
}
} else {
// skip over the '>'
index ;
// Note: check for excessive angle brackets like the example described in section 7.1.2 of rfc7103...
if (index < endIndex && text[index] == (byte) '>') {
if (options.AddressParserComplianceMode == RfcComplianceMode.Strict) {
if (throwOnError)
throw new ParseException (string.Format (CultureInfo.InvariantCulture, "Excessive angle brackets at offset {0}", index), startIndex, index);
return false;
}
do {
index ;
} while (index < endIndex && text[index] == '>');
}
}
if (route != null)
address = new MailboxAddress (encoding, name, route, addrspec, at);
else
address = new MailboxAddress (encoding, name, addrspec, at);
return true;
}
static bool TryParseGroup (AddressParserFlags flags, ParserOptions options, byte[] text, int startIndex, ref int index, int endIndex, int groupDepth, string name, int codepage, out InternetAddress address)
{
var encoding = CharsetUtils.GetEncodingOrDefault (codepage, Encoding.UTF8);
bool throwOnError = (flags & AddressParserFlags.ThrowOnError) != 0;
// skip over the ':'
index ;
while (index < endIndex && (text[index] == ':' || text[index].IsBlank ()))
index ;
if (InternetAddressList.TryParse (flags | AddressParserFlags.AllowMailboxAddress, options, text, ref index, endIndex, true, groupDepth, out var members))
address = new GroupAddress (encoding, name, members);
else
address = new GroupAddress (encoding, name);
if (index >= endIndex || text[index] != (byte) ';') {
if (throwOnError && options.AddressParserComplianceMode == RfcComplianceMode.Strict)
throw new ParseException (string.Format (CultureInfo.InvariantCulture, "Expected to find ';' at offset {0}", index), startIndex, index);
while (index < endIndex && text[index] != (byte) ';')
index ;
} else {
index ;
}
return true;
}
internal static bool TryParse (AddressParserFlags flags, ParserOptions options, byte[] text, ref int index, int endIndex, int groupDepth, out InternetAddress address)
{
bool throwOnError = (flags & AddressParserFlags.ThrowOnError) != 0;
int minWordCount = options.AllowUnquotedCommasInAddresses ? 0 : 1;
address = null;
if (!ParseUtils.SkipCommentsAndWhiteSpace (text, ref index, endIndex, throwOnError))
return false;
if (index == endIndex) {
if (throwOnError)
throw new ParseException ("No address found.", index, index);
return false;
}
// keep track of the start & length of the phrase
bool trimLeadingQuote = false;
int startIndex = index;
int length = 0;
int words = 0;
while (index < endIndex) {
if (options.AddressParserComplianceMode == RfcComplianceMode.Strict) {
if (!ParseUtils.SkipWord (text, ref index, endIndex, throwOnError))
break;
} else if (text[index] == (byte) '"') {
int qstringIndex = index;
if (!ParseUtils.SkipQuoted (text, ref index, endIndex, false)) {
index = qstringIndex 1;
ParseUtils.SkipWhiteSpace (text, ref index, endIndex);
if (!ParseUtils.SkipPhraseAtom (text, ref index, endIndex)) {
if (throwOnError)
throw new ParseException (string.Format (CultureInfo.InvariantCulture, "Incomplete quoted-string token at offset {0}", qstringIndex), qstringIndex, endIndex);
break;
}
if (startIndex == qstringIndex)
trimLeadingQuote = true;
}
} else {
if (!ParseUtils.SkipPhraseAtom (text, ref index, endIndex))
break;
}
length = index - startIndex;
do {
if (!ParseUtils.SkipCommentsAndWhiteSpace (text, ref index, endIndex, throwOnError))
return false;
// Note: some clients don't quote dots in the name
if (index >= endIndex || text[index] != (byte) '.')
break;
index ;
length = index - startIndex;
} while (true);
words ;
// Note: some clients don't quote commas in the name
if (index < endIndex && text[index] == ',' && words > minWordCount) {
index ;
length = index - startIndex;
if (!ParseUtils.SkipCommentsAndWhiteSpace (text, ref index, endIndex, throwOnError))
return false;
}
}
if (!ParseUtils.SkipCommentsAndWhiteSpace (text, ref index, endIndex, throwOnError))
return false;
// specials = "(" / ")" / "<" / ">" / "@" ; Must be in quoted-
// / "," / ";" / ":" / "\" / <"> ; string, to use
// / "." / "[" / "]" ; within a word.
if (index >= endIndex || text[index] == (byte) ',' || text[index] == (byte) '>' || text[index] == ';') {
// we've completely gobbled up an addr-spec w/o a domain
byte sentinel = index < endIndex ? text[index] : (byte) ',';
string name;
if ((flags & AddressParserFlags.AllowMailboxAddress) == 0) {
if (throwOnError)
throw new ParseException (string.Format (CultureInfo.InvariantCulture, "Addr-spec token at offset {0}", startIndex), startIndex, index);
return false;
}
if (!options.AllowAddressesWithoutDomain) {
if (throwOnError)
throw new ParseException (string.Format (CultureInfo.InvariantCulture, "Incomplete addr-spec token at offset {0}", startIndex), startIndex, index);
return false;
}
// rewind back to the beginning of the local-part
index = startIndex;
if (!TryParseLocalPart (text, ref index, endIndex, options.AddressParserComplianceMode, false, throwOnError, out var addrspec))
return false;
ParseUtils.SkipWhiteSpace (text, ref index, endIndex);
if (index < endIndex && text[index] == '(') {
int comment = index 1;
// Note: this can't fail because it has already been skipped in TryParseLocalPart() above.
ParseUtils.SkipComment (text, ref index, endIndex);
name = Rfc2047.DecodePhrase (options, text, comment, (index - 1) - comment).Trim ();
ParseUtils.SkipCommentsAndWhiteSpace (text, ref index, endIndex, throwOnError);
} else {
name = string.Empty;
}
if (index < endIndex && text[index] == (byte) '>') {
if (options.AddressParserComplianceMode == RfcComplianceMode.Strict) {
if (throwOnError)
throw new ParseException (string.Format (CultureInfo.InvariantCulture, "Unexpected '>' token at offset {0}", index), startIndex, index);
return false;
}
index ;
}
if (index < endIndex && text[index] != sentinel) {
if (throwOnError)
throw new ParseException (string.Format (CultureInfo.InvariantCulture, "Unexpected '{0}' token at offset {1}", (char) text[index], index), startIndex, index);
return false;
}
address = new MailboxAddress (Encoding.UTF8, name, addrspec, -1);
return true;
}
if (text[index] == (byte) ':') {
// rfc2822 group address
int nameIndex = startIndex;
int codepage = -1;
string name;
if ((flags & AddressParserFlags.AllowGroupAddress) == 0) {
if (throwOnError)
throw new ParseException (string.Format (CultureInfo.InvariantCulture, "Group address token at offset {0}", startIndex), startIndex, index);
return false;
}
if (groupDepth >= options.MaxAddressGroupDepth) {
if (throwOnError)
throw new ParseException (string.Format (CultureInfo.InvariantCulture, "Exceeded maximum rfc822 group depth at offset {0}", startIndex), startIndex, index);
return false;
}
if (trimLeadingQuote) {
nameIndex ;
length--;
}
if (length > 0) {
name = Rfc2047.DecodePhrase (options, text, nameIndex, length, out codepage);
} else {
name = string.Empty;
}
if (codepage == -1)
codepage = 65001;
return TryParseGroup (flags, options, text, startIndex, ref index, endIndex, groupDepth 1, MimeUtils.Unquote (name, true), codepage, out address);
}
if ((flags & AddressParserFlags.AllowMailboxAddress) == 0) {
if (throwOnError)
throw new ParseException (string.Format (CultureInfo.InvariantCulture, "Mailbox address token at offset {0}", startIndex), startIndex, index);
return false;
}
if (text[index] == (byte) '@') {
// we're either in the middle of an addr-spec token or we completely gobbled up an addr-spec w/o a domain
string name;
// rewind back to the beginning of the local-part
index = startIndex;
if (!TryParseAddrspec (text, ref index, endIndex, CommaGreaterThanOrSemiColon, options.AddressParserComplianceMode, throwOnError, out var addrspec, out int at))
return false;
ParseUtils.SkipWhiteSpace (text, ref index, endIndex);
if (index < endIndex && text[index] == '(') {
int comment = index;
if (!ParseUtils.SkipComment (text, ref index, endIndex)) {
if (throwOnError)
throw new ParseException (string.Format (CultureInfo.InvariantCulture, "Incomplete comment token at offset {0}", comment), comment, index);
return false;
}
comment ;
name = Rfc2047.DecodePhrase (options, text, comment, (index - 1) - comment).Trim ();
} else {
name = string.Empty;
}
if (!ParseUtils.SkipCommentsAndWhiteSpace (text, ref index, endIndex, throwOnError))
return false;
if (index >= endIndex) {
address = new MailboxAddress (Encoding.UTF8, name, addrspec, at);
return true;
}
if (text[index] == (byte) '<') {
// We have an address like "[email protected] <[email protected]>"; i.e. the name is an unquoted string with an '@'.
if (options.AddressParserComplianceMode == RfcComplianceMode.Strict) {
if (throwOnError)
throw new ParseException (string.Format (CultureInfo.InvariantCulture, "Unexpected '<' token at offset {0}", index), startIndex, index);
return false;
}
int nameEndIndex = index;
while (nameEndIndex > startIndex && text[nameEndIndex - 1].IsWhitespace ())
nameEndIndex--;
length = nameEndIndex - startIndex;
// fall through to the rfc822 angle-addr token case...
} else {
// Note: since there was no '<', there should not be a '>'... but we handle it anyway in order to
// deal with the second Unbalanced Angle Brackets example in section 7.1.3: [email protected]>
if (text[index] == (byte) '>') {
if (options.AddressParserComplianceMode == RfcComplianceMode.Strict) {
if (throwOnError)
throw new ParseException (string.Format (CultureInfo.InvariantCulture, "Unexpected '>' token at offset {0}", index), startIndex, index);
return false;
}
index ;
}
address = new MailboxAddress (Encoding.UTF8, name, addrspec, at);
return true;
}
}
if (text[index] == (byte) '<') {
// rfc2822 angle-addr token
int nameIndex = startIndex;
int codepage = -1;
string name;
if (trimLeadingQuote) {
nameIndex ;
length--;
}
if (length > 0) {
var unquoted = MimeUtils.Unquote (text, nameIndex, length, true);
name = Rfc2047.DecodePhrase (options, unquoted, 0, unquoted.Length, out codepage);
} else {
name = string.Empty;
}
if (codepage == -1)
codepage = 65001;
return TryParseMailbox (options, text, startIndex, ref index, endIndex, name, codepage, throwOnError, out address);
}
if (throwOnError)
throw new ParseException (string.Format (CultureInfo.InvariantCulture, "Invalid address token at offset {0}", startIndex), startIndex, index);
return false;
}
/// <summary>
/// Try to parse the given input buffer into a new <see cref="InternetAddress"/> instance.
/// </summary>
/// <remarks>
/// Parses a single <see cref="MailboxAddress"/> or <see cref="GroupAddress"/>. If the buffer contains
/// more data, then parsing will fail.
/// </remarks>
/// <returns><c>true</c>, if the address was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="options">The parser options to use.</param>
/// <param name="buffer">The input buffer.</param>
/// <param name="startIndex">The starting index of the input buffer.</param>
/// <param name="length">The number of bytes in the input buffer to parse.</param>
/// <param name="address">The parsed address.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="options"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="buffer"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> and <paramref name="length"/> do not specify
/// a valid range in the byte array.
/// </exception>
public static bool TryParse (ParserOptions options, byte[] buffer, int startIndex, int length, out InternetAddress address)
{
ParseUtils.ValidateArguments (options, buffer, startIndex, length);
int endIndex = startIndex length;
int index = startIndex;
if (!TryParse (AddressParserFlags.TryParse, options, buffer, ref index, endIndex, 0, out address))
return false;
if (!ParseUtils.SkipCommentsAndWhiteSpace (buffer, ref index, endIndex, false)) {
address = null;
return false;
}
if (index != endIndex) {
address = null;
return false;
}
return true;
}
/// <summary>
/// Try to parse the given input buffer into a new <see cref="InternetAddress"/> instance.
/// </summary>
/// <remarks>
/// Parses a single <see cref="MailboxAddress"/> or <see cref="GroupAddress"/>. If the buffer contains
/// more data, then parsing will fail.
/// </remarks>
/// <returns><c>true</c>, if the address was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="buffer">The input buffer.</param>
/// <param name="startIndex">The starting index of the input buffer.</param>
/// <param name="length">The number of bytes in the input buffer to parse.</param>
/// <param name="address">The parsed address.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="buffer"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> and <paramref name="length"/> do not specify
/// a valid range in the byte array.
/// </exception>
public static bool TryParse (byte[] buffer, int startIndex, int length, out InternetAddress address)
{
return TryParse (ParserOptions.Default, buffer, startIndex, length, out address);
}
/// <summary>
/// Try to parse the given input buffer into a new <see cref="InternetAddress"/> instance.
/// </summary>
/// <remarks>
/// Parses a single <see cref="MailboxAddress"/> or <see cref="GroupAddress"/>. If the buffer contains
/// more data, then parsing will fail.
/// </remarks>
/// <returns><c>true</c>, if the address was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="options">The parser options to use.</param>
/// <param name="buffer">The input buffer.</param>
/// <param name="startIndex">The starting index of the input buffer.</param>
/// <param name="address">The parsed address.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="options"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="buffer"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> is out of range.
/// </exception>
public static bool TryParse (ParserOptions options, byte[] buffer, int startIndex, out InternetAddress address)
{
ParseUtils.ValidateArguments (options, buffer, startIndex);
int endIndex = buffer.Length;
int index = startIndex;
if (!TryParse (AddressParserFlags.TryParse, options, buffer, ref index, endIndex, 0, out address))
return false;
if (!ParseUtils.SkipCommentsAndWhiteSpace (buffer, ref index, endIndex, false) || index != endIndex) {
address = null;
return false;
}
return true;
}
/// <summary>
/// Try to parse the given input buffer into a new <see cref="InternetAddress"/> instance.
/// </summary>
/// <remarks>
/// Parses a single <see cref="MailboxAddress"/> or <see cref="GroupAddress"/>. If the buffer contains
/// more data, then parsing will fail.