/
Uri.cs
5299 lines (4666 loc) · 204 KB
/
Uri.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
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Text;
using System.Threading;
namespace System
{
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public partial class Uri : ISerializable
{
public static readonly string UriSchemeFile = UriParser.FileUri.SchemeName;
public static readonly string UriSchemeFtp = UriParser.FtpUri.SchemeName;
public static readonly string UriSchemeSftp = "sftp";
public static readonly string UriSchemeFtps = "ftps";
public static readonly string UriSchemeGopher = UriParser.GopherUri.SchemeName;
public static readonly string UriSchemeHttp = UriParser.HttpUri.SchemeName;
public static readonly string UriSchemeHttps = UriParser.HttpsUri.SchemeName;
public static readonly string UriSchemeWs = UriParser.WsUri.SchemeName;
public static readonly string UriSchemeWss = UriParser.WssUri.SchemeName;
public static readonly string UriSchemeMailto = UriParser.MailToUri.SchemeName;
public static readonly string UriSchemeNews = UriParser.NewsUri.SchemeName;
public static readonly string UriSchemeNntp = UriParser.NntpUri.SchemeName;
public static readonly string UriSchemeSsh = "ssh";
public static readonly string UriSchemeTelnet = UriParser.TelnetUri.SchemeName;
public static readonly string UriSchemeNetTcp = UriParser.NetTcpUri.SchemeName;
public static readonly string UriSchemeNetPipe = UriParser.NetPipeUri.SchemeName;
public static readonly string SchemeDelimiter = "://";
internal const int StackallocThreshold = 512;
internal const int c_MaxUriBufferSize = 0xFFF0;
private const int c_MaxUriSchemeName = 1024;
// untouched user string unless string has unicode chars and iriparsing is enabled
// or idn is on and we have unicode host or idn host
// In that case, this string is normalized, stripped of bidi chars, and validated
// with char limits
private string _string = null!; // initialized early in ctor via a helper
// untouched user string if string has unicode with iri on or unicode/idn host with idn on
private string _originalUnicodeString = null!; // initialized in ctor via helper
internal UriParser _syntax = null!; // Initialized in ctor via helper. This is a whole Uri syntax, not only the scheme name
internal Flags _flags;
private UriInfo _info = null!;
[Flags]
internal enum Flags : ulong
{
Zero = 0x00000000,
SchemeNotCanonical = 0x1,
UserNotCanonical = 0x2,
HostNotCanonical = 0x4,
PortNotCanonical = 0x8,
PathNotCanonical = 0x10,
QueryNotCanonical = 0x20,
FragmentNotCanonical = 0x40,
CannotDisplayCanonical = 0x7F,
E_UserNotCanonical = 0x80,
E_HostNotCanonical = 0x100,
E_PortNotCanonical = 0x200,
E_PathNotCanonical = 0x400,
E_QueryNotCanonical = 0x800,
E_FragmentNotCanonical = 0x1000,
E_CannotDisplayCanonical = 0x1F80,
ShouldBeCompressed = 0x2000,
FirstSlashAbsent = 0x4000,
BackslashInPath = 0x8000,
IndexMask = 0x0000FFFF,
HostTypeMask = 0x00070000,
HostNotParsed = 0x00000000,
IPv6HostType = 0x00010000,
IPv4HostType = 0x00020000,
DnsHostType = 0x00030000,
UncHostType = 0x00040000,
BasicHostType = 0x00050000,
UnusedHostType = 0x00060000,
UnknownHostType = 0x00070000,
UserEscaped = 0x00080000,
AuthorityFound = 0x00100000,
HasUserInfo = 0x00200000,
LoopbackHost = 0x00400000,
NotDefaultPort = 0x00800000,
UserDrivenParsing = 0x01000000,
CanonicalDnsHost = 0x02000000,
ErrorOrParsingRecursion = 0x04000000, // Used to signal a default parser error and also to confirm Port
// and Host values in case of a custom user Parser
DosPath = 0x08000000,
UncPath = 0x10000000,
ImplicitFile = 0x20000000,
MinimalUriInfoSet = 0x40000000,
AllUriInfoSet = unchecked(0x80000000),
IdnHost = 0x100000000,
HasUnicode = 0x200000000,
HostUnicodeNormalized = 0x400000000,
RestUnicodeNormalized = 0x800000000,
UnicodeHost = 0x1000000000,
IntranetUri = 0x2000000000,
// Is this component Iri canonical
UserIriCanonical = 0x8000000000,
PathIriCanonical = 0x10000000000,
QueryIriCanonical = 0x20000000000,
FragmentIriCanonical = 0x40000000000,
IriCanonical = 0x78000000000,
UnixPath = 0x100000000000,
/// <summary>
/// Disables any validation/normalization past the authority. Fragments will always be empty. GetComponents will throw for Path/Query.
/// </summary>
DisablePathAndQueryCanonicalization = 0x200000000000,
/// <summary>
/// Used to ensure that InitializeAndValidate is only called once per Uri instance and only from an override of InitializeAndValidate
/// </summary>
CustomParser_ParseMinimalAlreadyCalled = 0x4000000000000000,
/// <summary>
/// Used for asserting that certain methods are only called from the constructor to validate thread-safety assumptions
/// </summary>
Debug_LeftConstructor = 0x8000000000000000
}
[Conditional("DEBUG")]
private void DebugSetLeftCtor()
{
_flags |= Flags.Debug_LeftConstructor;
}
[Conditional("DEBUG")]
internal void DebugAssertInCtor()
{
Debug.Assert((_flags & Flags.Debug_LeftConstructor) == 0);
}
private sealed class UriInfo
{
public Offset Offset;
public string? String;
public string? Host;
public string? IdnHost;
public string? PathAndQuery;
/// <summary>
/// Only IP v6 may need this
/// </summary>
public string? ScopeId;
private MoreInfo? _moreInfo;
public MoreInfo MoreInfo
{
get
{
if (_moreInfo is null)
{
Interlocked.CompareExchange(ref _moreInfo, new MoreInfo(), null);
}
return _moreInfo;
}
}
};
[StructLayout(LayoutKind.Sequential, Pack = 1)]
private struct Offset
{
public ushort Scheme;
public ushort User;
public ushort Host;
public ushort PortValue;
public ushort Path;
public ushort Query;
public ushort Fragment;
public ushort End;
};
private sealed class MoreInfo
{
public string? Path;
public string? Query;
public string? Fragment;
public string? AbsoluteUri;
public string? RemoteUrl;
};
private void InterlockedSetFlags(Flags flags)
{
Debug.Assert(_syntax != null);
if (_syntax.IsSimple)
{
// For built-in (simple) parsers, it is safe to do an Interlocked update here
Debug.Assert(sizeof(Flags) == sizeof(ulong));
Interlocked.Or(ref Unsafe.As<Flags, ulong>(ref _flags), (ulong)flags);
}
else
{
// Custom parsers still use a lock in CreateHostString and perform non-atomic flags updates
// We have to take the lock to ensure flags access synchronization if CreateHostString and ParseRemaining are called concurrently
lock (_info)
{
_flags |= flags;
}
}
}
private bool IsImplicitFile
{
get { return (_flags & Flags.ImplicitFile) != 0; }
}
private bool IsUncOrDosPath
{
get { return (_flags & (Flags.UncPath | Flags.DosPath)) != 0; }
}
private bool IsDosPath
{
get { return (_flags & Flags.DosPath) != 0; }
}
private bool IsUncPath
{
get { return (_flags & Flags.UncPath) != 0; }
}
private bool IsUnixPath
{
get { return (_flags & Flags.UnixPath) != 0; }
}
private Flags HostType
{
get { return _flags & Flags.HostTypeMask; }
}
private UriParser Syntax
{
get
{
return _syntax;
}
}
private bool IsNotAbsoluteUri
{
get { return _syntax is null; }
}
//
// Checks if Iri parsing is allowed by the syntax & by config
//
private bool IriParsing => IriParsingStatic(_syntax);
internal static bool IriParsingStatic(UriParser? syntax)
{
return syntax is null || syntax.InFact(UriSyntaxFlags.AllowIriParsing);
}
internal bool DisablePathAndQueryCanonicalization => (_flags & Flags.DisablePathAndQueryCanonicalization) != 0;
internal bool UserDrivenParsing
{
get
{
return (_flags & Flags.UserDrivenParsing) != 0;
}
}
private int SecuredPathIndex
{
get
{
// This is one more trouble with a Dos Path.
// This property gets "safe" first path slash that is not the first if path = c:\
if (IsDosPath)
{
char ch = _string[_info.Offset.Path];
return (ch == '/' || ch == '\\') ? 3 : 2;
}
return 0;
}
}
private bool NotAny(Flags flags)
{
return (_flags & flags) == 0;
}
private bool InFact(Flags flags)
{
return (_flags & flags) != 0;
}
private static bool StaticNotAny(Flags allFlags, Flags checkFlags)
{
return (allFlags & checkFlags) == 0;
}
private static bool StaticInFact(Flags allFlags, Flags checkFlags)
{
return (allFlags & checkFlags) != 0;
}
private UriInfo EnsureUriInfo()
{
Flags cF = _flags;
if ((cF & Flags.MinimalUriInfoSet) == 0)
{
CreateUriInfo(cF);
}
Debug.Assert(_info != null && (_flags & Flags.MinimalUriInfoSet) != 0);
return _info;
}
private void EnsureParseRemaining()
{
if ((_flags & Flags.AllUriInfoSet) == 0)
{
ParseRemaining();
}
}
private void EnsureHostString(bool allowDnsOptimization)
{
UriInfo info = EnsureUriInfo();
if (info.Host is null)
{
if (allowDnsOptimization && InFact(Flags.CanonicalDnsHost))
{
/* Optimization for a canonical DNS name
* ATTN: the host string won't be created,
* Hence ALL _info.Host callers first call EnsureHostString(false)
* For example IsLoopBack property is one of such callers.
*/
return;
}
CreateHostString();
}
}
//
// Uri(string)
//
// We expect to create a Uri from a display name - e.g. that was typed by
// a user, or that was copied & pasted from a document. That is, we do not
// expect already encoded URI to be supplied.
//
public Uri([StringSyntax(StringSyntaxAttribute.Uri)] string uriString)
{
ArgumentNullException.ThrowIfNull(uriString);
CreateThis(uriString, false, UriKind.Absolute);
DebugSetLeftCtor();
}
//
// Uri(string, bool)
//
// Uri constructor. Assumes that input string is canonically escaped
//
[Obsolete("This constructor has been deprecated; the dontEscape parameter is always false. Use Uri(string) instead.")]
public Uri([StringSyntax(StringSyntaxAttribute.Uri)] string uriString, bool dontEscape)
{
ArgumentNullException.ThrowIfNull(uriString);
CreateThis(uriString, dontEscape, UriKind.Absolute);
DebugSetLeftCtor();
}
//
// Uri(Uri, string, bool)
//
// Uri combinatorial constructor. Do not perform character escaping if
// DontEscape is true
//
[Obsolete("This constructor has been deprecated; the dontEscape parameter is always false. Use Uri(Uri, string) instead.")]
public Uri(Uri baseUri, string? relativeUri, bool dontEscape)
{
ArgumentNullException.ThrowIfNull(baseUri);
if (!baseUri.IsAbsoluteUri)
throw new ArgumentOutOfRangeException(nameof(baseUri));
CreateUri(baseUri, relativeUri, dontEscape);
DebugSetLeftCtor();
}
//
// Uri(string, UriKind);
//
public Uri([StringSyntax(StringSyntaxAttribute.Uri, nameof(uriKind))] string uriString, UriKind uriKind)
{
ArgumentNullException.ThrowIfNull(uriString);
CreateThis(uriString, false, uriKind);
DebugSetLeftCtor();
}
/// <summary>
/// Initializes a new instance of the <see cref="Uri"/> class with the specified URI and additional <see cref="UriCreationOptions"/>.
/// </summary>
/// <param name="uriString">A string that identifies the resource to be represented by the <see cref="Uri"/> instance.</param>
/// <param name="creationOptions">Options that control how the <seealso cref="Uri"/> is created and behaves.</param>
public Uri([StringSyntax(StringSyntaxAttribute.Uri)] string uriString, in UriCreationOptions creationOptions)
{
ArgumentNullException.ThrowIfNull(uriString);
CreateThis(uriString, false, UriKind.Absolute, in creationOptions);
DebugSetLeftCtor();
}
//
// Uri(Uri, string)
//
// Construct a new Uri from a base and relative URI. The relative URI may
// also be an absolute URI, in which case the resultant URI is constructed
// entirely from it
//
public Uri(Uri baseUri, string? relativeUri)
{
ArgumentNullException.ThrowIfNull(baseUri);
if (!baseUri.IsAbsoluteUri)
throw new ArgumentOutOfRangeException(nameof(baseUri));
CreateUri(baseUri, relativeUri, false);
DebugSetLeftCtor();
}
//
// Uri(SerializationInfo, StreamingContext)
//
// ISerializable constructor
//
protected Uri(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
string? uriString = serializationInfo.GetString("AbsoluteUri"); // Do not rename (binary serialization)
if (uriString!.Length != 0)
{
CreateThis(uriString, false, UriKind.Absolute);
DebugSetLeftCtor();
return;
}
uriString = serializationInfo.GetString("RelativeUri"); // Do not rename (binary serialization)
if (uriString is null)
throw new ArgumentException(SR.Format(SR.InvalidNullArgument, "RelativeUri"), nameof(serializationInfo));
CreateThis(uriString, false, UriKind.Relative);
DebugSetLeftCtor();
}
//
// ISerializable method
//
/// <internalonly/>
void ISerializable.GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
GetObjectData(serializationInfo, streamingContext);
}
//
// FxCop: provide some way for derived classes to access GetObjectData even if the derived class
// explicitly re-inherits ISerializable.
//
protected void GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
if (IsAbsoluteUri)
serializationInfo.AddValue("AbsoluteUri", GetParts(UriComponents.SerializationInfoString, UriFormat.UriEscaped)); // Do not rename (binary serialization)
else
{
serializationInfo.AddValue("AbsoluteUri", string.Empty); // Do not rename (binary serialization)
serializationInfo.AddValue("RelativeUri", GetParts(UriComponents.SerializationInfoString, UriFormat.UriEscaped)); // Do not rename (binary serialization)
}
}
private void CreateUri(Uri baseUri, string? relativeUri, bool dontEscape)
{
DebugAssertInCtor();
// Parse relativeUri and populate Uri internal data.
CreateThis(relativeUri, dontEscape, UriKind.RelativeOrAbsolute);
if (baseUri.Syntax!.IsSimple)
{
// Resolve Uris if possible OR get merged Uri String to re-parse below
Uri? uriResult = ResolveHelper(baseUri, this, ref relativeUri, ref dontEscape);
// If resolved into a Uri then we build from that Uri
if (uriResult != null)
{
if (!ReferenceEquals(this, uriResult))
CreateThisFromUri(uriResult);
return;
}
}
else
{
dontEscape = false;
relativeUri = baseUri.Syntax.InternalResolve(baseUri, this, out UriFormatException? e);
if (e != null)
throw e;
}
_flags = Flags.Zero;
_info = null!;
_syntax = null!;
_originalUnicodeString = null!;
// If not resolved, we reparse modified Uri string and populate Uri internal data.
CreateThis(relativeUri, dontEscape, UriKind.Absolute);
}
//
// Uri(Uri , Uri )
// Note: a static Create() method should be used by users, not this .ctor
//
public Uri(Uri baseUri, Uri relativeUri)
{
ArgumentNullException.ThrowIfNull(baseUri);
if (!baseUri.IsAbsoluteUri)
throw new ArgumentOutOfRangeException(nameof(baseUri));
CreateThisFromUri(relativeUri);
string? newUriString = null;
bool dontEscape;
if (baseUri.Syntax!.IsSimple)
{
dontEscape = InFact(Flags.UserEscaped);
Uri? resolvedRelativeUri = ResolveHelper(baseUri, this, ref newUriString, ref dontEscape);
if (resolvedRelativeUri != null)
{
if (!ReferenceEquals(this, resolvedRelativeUri))
CreateThisFromUri(resolvedRelativeUri);
DebugSetLeftCtor();
return;
}
}
else
{
dontEscape = false;
newUriString = baseUri.Syntax.InternalResolve(baseUri, this, out UriFormatException? e);
if (e != null)
throw e;
}
_flags = Flags.Zero;
_info = null!;
_syntax = null!;
_originalUnicodeString = null!;
CreateThis(newUriString, dontEscape, UriKind.Absolute);
DebugSetLeftCtor();
}
//
// This method is shared by base+relative Uris constructors and is only called from them.
// The assumptions:
// - baseUri is a valid absolute Uri
// - relative part is not null and not empty
private static unsafe void GetCombinedString(Uri baseUri, string relativeStr,
bool dontEscape, ref string? result)
{
// NB: This is not RFC2396 compliant although it is inline with w3c.org recommendations
// This parser will allow the relativeStr to be an absolute Uri with the different scheme
// In fact this is strict violation of RFC2396
//
for (int i = 0; i < relativeStr.Length; ++i)
{
if (relativeStr[i] == '/' || relativeStr[i] == '\\' || relativeStr[i] == '?' || relativeStr[i] == '#')
{
break;
}
else if (relativeStr[i] == ':')
{
if (i < 2)
{
// Note we don't support one-letter Uri schemes.
// Hence anything like x:sdsd is a relative path and be added to the baseUri Path
break;
}
UriParser? syntax = null;
if (CheckSchemeSyntax(relativeStr.AsSpan(0, i), ref syntax) == ParsingError.None)
{
if (baseUri.Syntax == syntax)
{
//Remove the scheme for backward Uri parsers compatibility
if (i + 1 < relativeStr.Length)
{
relativeStr = relativeStr.Substring(i + 1);
}
else
{
relativeStr = string.Empty;
}
}
else
{
// This is the place where we switch the scheme.
// Return relative part as the result Uri.
result = relativeStr;
return;
}
}
break;
}
}
if (relativeStr.Length == 0)
{
result = baseUri.OriginalString;
}
else
{
result = CombineUri(baseUri, relativeStr, dontEscape ? UriFormat.UriEscaped : UriFormat.SafeUnescaped);
}
}
private static UriFormatException? GetException(ParsingError err)
{
switch (err)
{
case ParsingError.None:
return null;
// Could be OK for Relative Uri
case ParsingError.BadFormat:
return new UriFormatException(SR.net_uri_BadFormat);
case ParsingError.BadScheme:
return new UriFormatException(SR.net_uri_BadScheme);
case ParsingError.BadAuthority:
return new UriFormatException(SR.net_uri_BadAuthority);
case ParsingError.EmptyUriString:
return new UriFormatException(SR.net_uri_EmptyUri);
// Fatal
case ParsingError.SchemeLimit:
return new UriFormatException(SR.net_uri_SchemeLimit);
case ParsingError.SizeLimit:
return new UriFormatException(SR.net_uri_SizeLimit);
case ParsingError.MustRootedPath:
return new UriFormatException(SR.net_uri_MustRootedPath);
// Derived class controllable
case ParsingError.BadHostName:
return new UriFormatException(SR.net_uri_BadHostName);
case ParsingError.NonEmptyHost: //unix-only
return new UriFormatException(SR.net_uri_BadFormat);
case ParsingError.BadPort:
return new UriFormatException(SR.net_uri_BadPort);
case ParsingError.BadAuthorityTerminator:
return new UriFormatException(SR.net_uri_BadAuthorityTerminator);
case ParsingError.CannotCreateRelative:
return new UriFormatException(SR.net_uri_CannotCreateRelative);
default:
break;
}
return new UriFormatException(SR.net_uri_BadFormat);
}
public string AbsolutePath
{
get
{
if (IsNotAbsoluteUri)
{
throw new InvalidOperationException(SR.net_uri_NotAbsolute);
}
string path = PrivateAbsolutePath;
//
// For Compat:
// Remove the first slash from a Dos Path if it's present
//
if (IsDosPath && path[0] == '/')
{
path = path.Substring(1);
}
return path;
}
}
private string PrivateAbsolutePath
{
get
{
Debug.Assert(IsAbsoluteUri);
MoreInfo info = EnsureUriInfo().MoreInfo;
return info.Path ??= GetParts(UriComponents.Path | UriComponents.KeepDelimiter, UriFormat.UriEscaped);
}
}
public string AbsoluteUri
{
get
{
if (_syntax == null)
{
throw new InvalidOperationException(SR.net_uri_NotAbsolute);
}
MoreInfo info = EnsureUriInfo().MoreInfo;
return info.AbsoluteUri ??= GetParts(UriComponents.AbsoluteUri, UriFormat.UriEscaped);
}
}
//
// LocalPath
//
// Returns a 'local' version of the path. This is mainly for file: URI
// such that DOS and UNC paths are returned with '/' converted back to
// '\', and any escape sequences converted
//
// The form of the returned path is in NOT Escaped
//
public string LocalPath
{
get
{
if (IsNotAbsoluteUri)
{
throw new InvalidOperationException(SR.net_uri_NotAbsolute);
}
return GetLocalPath();
}
}
//
// The result is of the form "hostname[:port]" Port is omitted if default
//
public string Authority
{
get
{
if (IsNotAbsoluteUri)
{
throw new InvalidOperationException(SR.net_uri_NotAbsolute);
}
// Note: Compatibility with V1 that does not report user info
return GetParts(UriComponents.Host | UriComponents.Port, UriFormat.UriEscaped);
}
}
public UriHostNameType HostNameType
{
get
{
if (IsNotAbsoluteUri)
{
throw new InvalidOperationException(SR.net_uri_NotAbsolute);
}
if (_syntax.IsSimple)
EnsureUriInfo();
else
{
// For a custom parser we request HostString creation to confirm HostType
EnsureHostString(false);
}
switch (HostType)
{
case Flags.DnsHostType: return UriHostNameType.Dns;
case Flags.IPv4HostType: return UriHostNameType.IPv4;
case Flags.IPv6HostType: return UriHostNameType.IPv6;
case Flags.BasicHostType: return UriHostNameType.Basic;
case Flags.UncHostType: return UriHostNameType.Basic;
case Flags.UnknownHostType: return UriHostNameType.Unknown;
default:
break;
}
return UriHostNameType.Unknown;
}
}
public bool IsDefaultPort
{
get
{
if (IsNotAbsoluteUri)
{
throw new InvalidOperationException(SR.net_uri_NotAbsolute);
}
if (_syntax.IsSimple)
EnsureUriInfo();
else
{
// For a custom parser we request HostString creation that will also set the port
EnsureHostString(false);
}
return NotAny(Flags.NotDefaultPort);
}
}
public bool IsFile
{
get
{
if (IsNotAbsoluteUri)
{
throw new InvalidOperationException(SR.net_uri_NotAbsolute);
}
return (object)_syntax.SchemeName == (object)UriSchemeFile;
}
}
public bool IsLoopback
{
get
{
if (IsNotAbsoluteUri)
{
throw new InvalidOperationException(SR.net_uri_NotAbsolute);
}
EnsureHostString(false);
return InFact(Flags.LoopbackHost);
}
}
//
// Gets the escaped Uri.AbsolutePath and Uri.Query
// properties separated by a "?" character.
public string PathAndQuery
{
get
{
if (IsNotAbsoluteUri)
{
throw new InvalidOperationException(SR.net_uri_NotAbsolute);
}
UriInfo info = EnsureUriInfo();
if (info.PathAndQuery is null)
{
string result = GetParts(UriComponents.PathAndQuery, UriFormat.UriEscaped);
// Compatibility:
// Remove the first slash from a Dos Path if it's present
if (IsDosPath && result[0] == '/')
{
result = result.Substring(1);
}
info.PathAndQuery = result;
}
return info.PathAndQuery;
}
}
//
// Gets an array of the segments that make up a URI.
public string[] Segments
{
get
{
if (IsNotAbsoluteUri)
{
throw new InvalidOperationException(SR.net_uri_NotAbsolute);
}
string[] segments;
string path = PrivateAbsolutePath;
if (path.Length == 0)
{
segments = Array.Empty<string>();
}
else
{
ArrayBuilder<string> pathSegments = default;
int current = 0;
while (current < path.Length)
{
int next = path.IndexOf('/', current);
if (next == -1)
{
next = path.Length - 1;
}
pathSegments.Add(path.Substring(current, (next - current) + 1));
current = next + 1;
}
segments = pathSegments.ToArray();
}
return segments;
}
}
public bool IsUnc
{
get
{
if (IsNotAbsoluteUri)
{
throw new InvalidOperationException(SR.net_uri_NotAbsolute);
}
return IsUncPath;
}
}
//
// Gets a hostname part (special formatting for IPv6 form)
public string Host
{
get
{
if (IsNotAbsoluteUri)
{
throw new InvalidOperationException(SR.net_uri_NotAbsolute);
}
return GetParts(UriComponents.Host, UriFormat.UriEscaped);
}
}
private static bool StaticIsFile(UriParser syntax)
{
return syntax.InFact(UriSyntaxFlags.FileLikeUri);
}
private string GetLocalPath()
{
EnsureParseRemaining();
//Other cases will get a Unix-style path
if (IsUncOrDosPath)
{
EnsureHostString(false);
Debug.Assert(_info != null);
Debug.Assert(_info.Host != null);
int start;
// Do we have a valid local path right in _string?
if (NotAny(Flags.HostNotCanonical | Flags.PathNotCanonical | Flags.ShouldBeCompressed))
{
start = IsUncPath ? _info.Offset.Host - 2 : _info.Offset.Path;
string str = (IsImplicitFile && _info.Offset.Host == (IsDosPath ? 0 : 2) &&
_info.Offset.Query == _info.Offset.End)
? _string
: (IsDosPath && (_string[start] == '/' || _string[start] == '\\'))
? _string.Substring(start + 1, _info.Offset.Query - start - 1)
: _string.Substring(start, _info.Offset.Query - start);
// Should be a rare case, convert c|\ into c:\
if (IsDosPath && str[1] == '|')
{
// Sadly, today there is no method for replacing just one occurrence
str = str.Remove(1, 1);
str = str.Insert(1, ":");
}
// check for all back slashes
str = str.Replace('/', '\\');
return str;
}
char[] result;
int count = 0;
start = _info.Offset.Path;
string host = _info.Host;
result = new char[host.Length + 3 + _info.Offset.Fragment - _info.Offset.Path];
if (IsUncPath)
{
result[0] = '\\';
result[1] = '\\';
count = 2;