[runtime] Overwrite stacktrace for exception on re-throw. Fixes #1856.
[mono.git] / mcs / class / System / System / Uri.cs
1 //
2 // System.Uri
3 //
4 // Authors:
5 //    Lawrence Pit (loz@cable.a2000.nl)
6 //    Garrett Rooney (rooneg@electricjellyfish.net)
7 //    Ian MacLean (ianm@activestate.com)
8 //    Ben Maurer (bmaurer@users.sourceforge.net)
9 //    Atsushi Enomoto (atsushi@ximian.com)
10 //    Sebastien Pouliot  <sebastien@ximian.com>
11 //    Stephane Delcroix  <stephane@delcroix.org>
12 //
13 // (C) 2001 Garrett Rooney
14 // (C) 2003 Ian MacLean
15 // (C) 2003 Ben Maurer
16 // Copyright (C) 2003,2009 Novell, Inc (http://www.novell.com)
17 // Copyright (c) 2009 Stephane Delcroix
18 //
19 // Permission is hereby granted, free of charge, to any person obtaining
20 // a copy of this software and associated documentation files (the
21 // "Software"), to deal in the Software without restriction, including
22 // without limitation the rights to use, copy, modify, merge, publish,
23 // distribute, sublicense, and/or sell copies of the Software, and to
24 // permit persons to whom the Software is furnished to do so, subject to
25 // the following conditions:
26 // 
27 // The above copyright notice and this permission notice shall be
28 // included in all copies or substantial portions of the Software.
29 // 
30 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
31 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
32 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
33 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
34 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
35 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
36 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
37 //
38 // See RFC 2396 for more info on URI's.
39 //
40 // TODO: optimize by parsing host string only once
41 //
42 using System.ComponentModel;
43 using System.IO;
44 using System.Net;
45 using System.Runtime.Serialization;
46 using System.Text;
47 using System.Collections;
48 using System.Collections.Generic;
49 using System.Globalization;
50
51 //
52 // Disable warnings on Obsolete methods being used
53 //
54 #pragma warning disable 612
55
56 namespace System {
57
58         [Serializable]
59         [TypeConverter (typeof (UriTypeConverter))]
60         public class Uri : ISerializable {
61                 // NOTES:
62                 // o  scheme excludes the scheme delimiter
63                 // o  port is -1 to indicate no port is defined
64                 // o  path is empty or starts with / when scheme delimiter == "://"
65                 // o  query is empty or starts with ? char, escaped.
66                 // o  fragment is empty or starts with # char, unescaped.
67                 // o  all class variables are in escaped format when they are escapable,
68                 //    except cachedToString.
69                 // o  UNC is supported, as starts with "\\" for windows,
70                 //    or "//" with unix.
71
72                 private string source;
73                 private string scheme = String.Empty;
74                 private string host = String.Empty;
75                 private int port = -1;
76                 private string path = String.Empty;
77                 private string query = String.Empty;
78                 private string fragment = String.Empty;
79                 private string userinfo;
80                 private bool isUnc;
81                 private bool isAbsoluteUri = true;
82                 private long scope_id;
83
84                 private List<string> segments;
85                 
86                 private bool userEscaped;
87                 private string cachedAbsoluteUri;
88                 private string cachedToString;
89                 private string cachedLocalPath;
90                 private int cachedHashCode;
91                 
92                 private static bool s_IriParsing;
93
94                 internal static bool IriParsing {
95                         get { return s_IriParsing; }
96                         set { s_IriParsing = value; }
97                 }
98
99 #if BOOTSTRAP_BASIC
100                 private static readonly string hexUpperChars = "0123456789ABCDEF";
101                 private static readonly string [] Empty = new string [0];
102                 private static bool isWin32 = (Path.DirectorySeparatorChar == '\\');
103 #else
104                 static readonly char[] hexUpperChars = new [] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
105 #endif
106         
107                 // Fields
108                 
109                 public static readonly string SchemeDelimiter = "://";
110                 public static readonly string UriSchemeFile = "file";
111                 public static readonly string UriSchemeFtp = "ftp";
112                 public static readonly string UriSchemeGopher = "gopher";
113                 public static readonly string UriSchemeHttp = "http";
114                 public static readonly string UriSchemeHttps = "https";
115                 public static readonly string UriSchemeMailto = "mailto";
116                 public static readonly string UriSchemeNews = "news";
117                 public static readonly string UriSchemeNntp = "nntp";
118                 public static readonly string UriSchemeNetPipe = "net.pipe";
119                 public static readonly string UriSchemeNetTcp = "net.tcp";
120
121                 internal static readonly string UriSchemeTelnet = "telnet";
122                 internal static readonly string UriSchemeLdap = "ldap";
123                 internal static readonly string UriSchemeUuid = "uuid";
124
125                 private static readonly string [] knownUriSchemes =
126                 {
127                         UriSchemeFile,
128                         UriSchemeFtp,
129                         UriSchemeGopher,
130                         UriSchemeHttp,
131                         UriSchemeHttps,
132                         UriSchemeMailto,
133                         UriSchemeNews,
134                         UriSchemeNntp,
135                         UriSchemeNetPipe,
136                         UriSchemeNetTcp
137                 };
138
139                 // Constructors
140
141                 static Uri ()
142                 {
143                         IriParsing = true;
144
145                         var iriparsingVar = Environment.GetEnvironmentVariable ("MONO_URI_IRIPARSING");
146                         if (iriparsingVar == "true")
147                                 IriParsing = true;
148                         else if (iriparsingVar == "false")
149                                 IriParsing = false;
150                 }
151
152                 public Uri (string uriString) : this (uriString, false) 
153                 {
154                 }
155
156                 protected Uri (SerializationInfo serializationInfo, StreamingContext streamingContext)
157                 {
158                         string uri = serializationInfo.GetString ("AbsoluteUri");
159                         if (uri.Length > 0) {
160                                 source = uri;
161                                 ParseUri (UriKind.Absolute);
162                         } else {
163                                 uri = serializationInfo.GetString ("RelativeUri");
164                                 if (uri.Length > 0) {
165                                         source = uri;
166                                         ParseUri (UriKind.Relative);
167                                 } else {
168                                         throw new ArgumentException ("Uri string was null or empty.");
169                                 }
170                         }
171                 }
172
173                 public Uri (string uriString, UriKind uriKind)
174                 {
175                         source = uriString;
176                         ParseUri (uriKind);
177
178                         switch (uriKind) {
179                         case UriKind.Absolute:
180                                 if (!IsAbsoluteUri)
181                                         throw new UriFormatException ("Invalid URI: The format of the URI could not be "
182                                                 + "determined.");
183                                 break;
184                         case UriKind.Relative:
185                                 if (IsAbsoluteUri)
186                                         throw new UriFormatException ("Invalid URI: The format of the URI could not be "
187                                                 + "determined because the parameter 'uriString' represents an absolute URI.");
188                                 break;
189                         case UriKind.RelativeOrAbsolute:
190                                 break;
191                         default:
192                                 string msg = Locale.GetText ("Invalid UriKind value '{0}'.", uriKind);
193                                 throw new ArgumentException (msg);
194                         }
195                 }
196
197                 //
198                 // An exception-less constructor, returns success
199                 // condition on the out parameter `success'.
200                 //
201                 Uri (string uriString, UriKind uriKind, out bool success)
202                 {
203                         if (uriString == null) {
204                                 success = false;
205                                 return;
206                         }
207
208                         if (uriKind != UriKind.RelativeOrAbsolute &&
209                                 uriKind != UriKind.Absolute &&
210                                 uriKind != UriKind.Relative) {
211                                 string msg = Locale.GetText ("Invalid UriKind value '{0}'.", uriKind);
212                                 throw new ArgumentException (msg);
213                         }
214
215                         source = uriString;
216                         if (ParseNoExceptions (uriKind, uriString) != null)
217                                 success = false;
218                         else {
219                                 success = true;
220                                 
221                                 switch (uriKind) {
222                                 case UriKind.Absolute:
223                                         if (!IsAbsoluteUri)
224                                                 success = false;
225                                         break;
226                                 case UriKind.Relative:
227                                         if (IsAbsoluteUri)
228                                                 success = false;
229                                         break;
230                                 case UriKind.RelativeOrAbsolute:
231                                         break;
232                                 default:
233                                         success = false;
234                                         break;
235                                 }
236                         }
237                 }
238
239                 public Uri (Uri baseUri, Uri relativeUri)
240                 {
241                         Merge (baseUri, relativeUri == null ? String.Empty : relativeUri.OriginalString);
242                         // FIXME: this should call UriParser.Resolve
243                 }
244
245                 // note: doc says that dontEscape is always false but tests show otherwise
246                 [Obsolete]
247                 public Uri (string uriString, bool dontEscape) 
248                 {
249                         userEscaped = dontEscape;
250                         source = uriString;
251                         ParseUri (UriKind.Absolute);
252                         if (!isAbsoluteUri)
253                                 throw new UriFormatException ("Invalid URI: The format of the URI could not be "
254                                         + "determined: " + uriString);
255                 }
256
257                 public Uri (Uri baseUri, string relativeUri) 
258                 {
259                         Merge (baseUri, relativeUri);
260                         // FIXME: this should call UriParser.Resolve
261                 }
262
263                 [Obsolete ("dontEscape is always false")]
264                 public Uri (Uri baseUri, string relativeUri, bool dontEscape) 
265                 {
266                         userEscaped = dontEscape;
267                         Merge (baseUri, relativeUri);
268                 }
269
270                 private void Merge (Uri baseUri, string relativeUri)
271                 {
272                         if (baseUri == null)
273                                 throw new ArgumentNullException ("baseUri");
274                         if (!baseUri.IsAbsoluteUri)
275                                 throw new ArgumentOutOfRangeException ("baseUri");
276                         if (string.IsNullOrEmpty (relativeUri)) {
277                                 source = baseUri.OriginalString;
278                                 ParseUri (UriKind.Absolute);
279                                 return;
280                         }
281
282                         string error;
283                         bool startsWithSlash = false;
284
285                         UriElements baseEl;
286                         if (!UriParseComponents.TryParseComponents (baseUri.OriginalString, UriKind.Absolute, out baseEl, out error))
287                                 throw new UriFormatException (error);
288
289                         if (relativeUri.StartsWith (baseEl.scheme + ":", StringComparison.Ordinal))
290                                 relativeUri = relativeUri.Substring (baseEl.scheme.Length + 1);
291
292                         if (relativeUri.Length >= 1 && relativeUri [0] == '/') {
293                                 if (relativeUri.Length >= 2 && relativeUri [1] == '/') {
294                                         source = baseEl.scheme + ":" + relativeUri;
295                                         ParseUri (UriKind.Absolute);
296                                         return;
297                                 }
298
299                                 relativeUri = relativeUri.Substring (1);
300                                 startsWithSlash = true;
301                         }
302
303                         UriElements relativeEl;
304                         if (!UriParseComponents.TryParseComponents (relativeUri, UriKind.RelativeOrAbsolute, out relativeEl, out error))
305                                 throw new UriFormatException (error);
306
307                         if (relativeEl.isAbsoluteUri) {
308                                 source = relativeUri;
309                                 ParseUri (UriKind.Absolute);
310                                 return;
311                         }
312
313                         source = baseEl.scheme + baseEl.delimiter;
314
315                         if (baseEl.user != null)
316                                 source += baseEl.user + "@";
317
318                         source += baseEl.host;
319
320                         if (baseEl.port >= 0)
321                                 source += ":" + baseEl.port.ToString (CultureInfo.InvariantCulture);
322
323                         var canUseBase = true;
324
325                         string path;
326                         if (!string.IsNullOrEmpty (relativeEl.path) || startsWithSlash) {
327                                 canUseBase = false;
328                                 path = relativeEl.path;
329                                 if (startsWithSlash)
330                                         path = relativeEl.path;
331                                 else {
332                                         var pathEnd = baseEl.path.LastIndexOf ('/');
333                                         path = (pathEnd > 0)? baseEl.path.Substring (0, pathEnd+1) : "";
334                                         path += relativeEl.path;
335                                 }
336                         } else {
337                                 path = baseEl.path;
338                         }
339
340                         if ((path.Length == 0 || path [0] != '/') && baseEl.delimiter == SchemeDelimiter)
341                                 path = "/" + path;
342
343                         source += UriHelper.Reduce (path, true);
344
345                         if (relativeEl.query != null) {
346                                 canUseBase = false;
347                                 source += "?" + relativeEl.query;
348                         } else if (canUseBase && baseEl.query != null)
349                                 source += "?" + baseEl.query;
350
351                         if (relativeEl.fragment != null)
352                                 source += "#" + relativeEl.fragment;
353                         else if (canUseBase && baseEl.fragment != null)
354                                 source += "#" + baseEl.fragment;
355
356                         ParseUri (UriKind.Absolute);
357
358                         return;
359                 }
360                 
361                 // Properties
362                 
363                 public string AbsolutePath { 
364                         get {
365                                 EnsureAbsoluteUri ();
366                                 if (scheme == "mailto" || scheme == "file")
367                                         // faster (mailto) and special (file) cases
368                                         return path;
369                                 
370                                 if (path.Length == 0) {
371                                         string start = scheme + SchemeDelimiter;
372                                         if (path.StartsWith (start, StringComparison.Ordinal))
373                                                 return "/";
374                                         else
375                                                 return String.Empty;
376                                 }
377                                 return path;
378                         }
379                 }
380
381                 public string AbsoluteUri { 
382                         get { 
383                                 EnsureAbsoluteUri ();
384
385                                 if (cachedAbsoluteUri == null)
386                                         cachedAbsoluteUri = GetComponents (UriComponents.AbsoluteUri, UriFormat.UriEscaped);
387
388                                 return cachedAbsoluteUri;
389                         } 
390                 }
391
392                 public string Authority { 
393                         get { 
394                                 EnsureAbsoluteUri ();
395                                 return (GetDefaultPort (Scheme) == port)
396                                      ? host : host + ":" + port;
397                         } 
398                 }
399
400                 public string Fragment { 
401                         get { 
402                                 EnsureAbsoluteUri ();
403                                 return fragment; 
404                         } 
405                 }
406
407                 public string Host { 
408                         get { 
409                                 EnsureAbsoluteUri ();
410                                 return host; 
411                         } 
412                 }
413
414                 public UriHostNameType HostNameType { 
415                         get {
416                                 EnsureAbsoluteUri ();
417                                 UriHostNameType ret = CheckHostName (Host);
418                                 if (ret != UriHostNameType.Unknown)
419                                         return ret;
420
421                                 if (scheme == "mailto")
422                                         return UriHostNameType.Basic;
423                                 return (IsFile) ? UriHostNameType.Basic : ret;
424                         } 
425                 }
426
427                 public bool IsDefaultPort { 
428                         get {
429                                 EnsureAbsoluteUri ();
430                                 return GetDefaultPort (Scheme) == port;
431                         }
432                 }
433
434                 public bool IsFile { 
435                         get {
436                                 EnsureAbsoluteUri ();
437                                 return (Scheme == UriSchemeFile);
438                         }
439                 }
440
441                 public bool IsLoopback { 
442                         get {
443                                 EnsureAbsoluteUri ();
444                                 
445                                 if (Host.Length == 0) {
446                                         return IsFile;
447                                 }
448
449                                 if (host == "loopback" || host == "localhost") 
450                                         return true;
451
452                                 IPAddress result;
453                                 if (IPAddress.TryParse (host, out result))
454                                         if (IPAddress.Loopback.Equals (result))
455                                                 return true;
456
457                                 IPv6Address result6;
458                                 if (IPv6Address.TryParse (host, out result6)){
459                                         if (IPv6Address.IsLoopback (result6))
460                                                 return true;
461                                 }
462
463                                 return false;
464                         } 
465                 }
466
467                 public bool IsUnc {
468                         // rule: This should be true only if
469                         //   - uri string starts from "\\", or
470                         //   - uri string starts from "//" (Samba way)
471                         get { 
472                                 EnsureAbsoluteUri ();
473                                 return isUnc; 
474                         } 
475                 }
476
477                 private bool IsLocalIdenticalToAbsolutePath ()
478                 {
479                         if (IsFile)
480                                 return false;
481
482                         if ((scheme == Uri.UriSchemeNews) || (scheme == Uri.UriSchemeNntp) || (scheme == Uri.UriSchemeFtp))
483                                 return false;
484
485                         return IsWellFormedOriginalString ();
486                 }
487
488                 public string LocalPath { 
489                         get {
490                                 EnsureAbsoluteUri ();
491                                 if (cachedLocalPath != null)
492                                         return cachedLocalPath;
493
494                                 var formatFlags = UriHelper.FormatFlags.NoSlashReplace;
495
496                                 if (userEscaped)
497                                         formatFlags |= UriHelper.FormatFlags.UserEscaped;
498
499                                 string unescapedPath = UriHelper.FormatAbsolute (path, scheme,
500                                         UriComponents.Path, UriFormat.Unescaped, formatFlags);
501
502                                 if (path.StartsWith ("/", StringComparison.Ordinal) &&
503                                         !unescapedPath.StartsWith ("/", StringComparison.Ordinal))
504                                         unescapedPath = "/" + unescapedPath;
505
506                                 if (IsLocalIdenticalToAbsolutePath ()) {
507                                         cachedLocalPath = unescapedPath;
508                                         return cachedLocalPath;
509                                 }
510
511                                 if (!IsUnc) {
512                                         bool windows = (path.Length > 3 && path [1] == ':' &&
513                                                 (path [2] == '\\' || path [2] == '/'));
514
515                                         if (windows)
516                                                 cachedLocalPath = unescapedPath.Replace ('/', '\\');
517                                         else
518                                                 cachedLocalPath = unescapedPath;
519                                 } else {
520                                         // support *nix and W32 styles
521                                         if (path.Length > 1 && path [1] == ':')
522                                                 cachedLocalPath = unescapedPath.Replace (Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
523
524                                         // LAMESPEC: ok, now we cannot determine
525                                         // if such URI like "file://foo/bar" is
526                                         // Windows UNC or unix file path, so
527                                         // they should be handled differently.
528                                         else if (System.IO.Path.DirectorySeparatorChar == '\\') {
529                                                 string h = host;
530                                                 if (path.Length > 0) {
531                                                         if ((path.Length > 1) || (path[0] != '/')) {
532                                                                 h += unescapedPath.Replace ('/', '\\');
533                                                         }
534                                                 }
535                                                 cachedLocalPath = "\\\\" + h;
536                                         }  else
537                                                 cachedLocalPath = unescapedPath;
538                                 }
539                                 if (cachedLocalPath.Length == 0)
540                                         cachedLocalPath = Path.DirectorySeparatorChar.ToString ();
541                                 return cachedLocalPath;
542                         } 
543                 }
544
545                 public string PathAndQuery { 
546                         get {
547                                 EnsureAbsoluteUri ();
548                                 return path + Query;
549                         } 
550                 }
551
552                 public int Port { 
553                         get { 
554                                 EnsureAbsoluteUri ();
555                                 return port; 
556                         } 
557                 }
558
559                 public string Query { 
560                         get { 
561                                 EnsureAbsoluteUri ();
562                                 return query; 
563                         }
564                 }
565
566                 public string Scheme { 
567                         get { 
568                                 EnsureAbsoluteUri ();
569                                 return scheme; 
570                         } 
571                 }
572
573                 public string [] Segments { 
574                         get { 
575                                 EnsureAbsoluteUri ();
576
577                                 // return a (pre-allocated) empty array
578                                 if (path.Length == 0)
579 #if BOOTSTRAP_BASIC
580                                         return Empty;
581 #else
582                                         return EmptyArray<string>.Value;
583 #endif
584                                 // do not return the original array (since items can be changed)
585                                 if (segments != null)
586                                         return segments.ToArray ();
587
588                                 List<string> list = new List<string> ();
589                                 StringBuilder current = new StringBuilder ();
590                                 for (int i = 0; i < path.Length; i++) {
591                                         switch (path [i]) {
592                                         case '/':
593                                         case '\\':
594                                                 current.Append (path [i]);
595                                                 list.Add (current.ToString ());
596                                                 current.Length = 0;
597                                                 break;
598                                         case '%':
599                                                 if ((i < path.Length - 2) && (path [i + 1] == '5' && path [i + 2] == 'C')) {
600                                                         current.Append ("%5C");
601                                                         list.Add (current.ToString ());
602                                                         current.Length = 0;
603                                                         i += 2;
604                                                 } else {
605                                                         current.Append ('%');
606                                                 }
607                                                 break;
608                                         default:
609                                                 current.Append (path [i]);
610                                                 break;
611                                         }
612                                 }
613
614                                 if (current.Length > 0)
615                                         list.Add (current.ToString ());
616
617                                 if (IsFile && (list.Count > 0)) {
618                                         string first = list [0];
619                                         if ((first.Length > 1) && (first [1] == ':')) {
620                                                 list.Insert (0, "/");
621                                         }
622                                 }
623                                 segments = list;
624                                 return segments.ToArray ();
625                         } 
626                 }
627
628                 public bool UserEscaped { 
629                         get { return userEscaped; } 
630                 }
631
632                 public string UserInfo { 
633                         get { 
634                                 EnsureAbsoluteUri ();
635                                 return userinfo == null ? String.Empty : userinfo;
636                         }
637                 }
638                 
639                 public string DnsSafeHost {
640                         get {
641                                 EnsureAbsoluteUri ();
642                                 string host = Host;
643                                 if (HostNameType == UriHostNameType.IPv6) {
644                                         host = Host.Substring (1, Host.Length - 2);
645                                         if (scope_id != 0)
646                                                 host += "%" + scope_id.ToString ();
647                                 }
648                                 return Unescape (host);
649                         }
650                 }
651
652                 public bool IsAbsoluteUri {
653                         get { return isAbsoluteUri; }
654                 }
655
656                 public string OriginalString {
657                         get { return source; }
658                 }
659
660                 // Methods              
661
662                 public static UriHostNameType CheckHostName (string name) 
663                 {
664                         if (name == null || name.Length == 0)
665                                 return UriHostNameType.Unknown;
666
667                         if (IsIPv4Address (name)) 
668                                 return UriHostNameType.IPv4;
669                                 
670                         if (IsDomainAddress (name))
671                                 return UriHostNameType.Dns;                             
672                                 
673                         IPv6Address addr;
674                         if (IPv6Address.TryParse (name, out addr))
675                                 return UriHostNameType.IPv6;
676                         
677                         return UriHostNameType.Unknown;
678                 }
679                 
680                 internal static bool IsIPv4Address (string name)
681                 {
682                         string [] captures = name.Split (new char [] {'.'});
683                         if (captures.Length != 4)
684                                 return false;
685
686                         for (int i = 0; i < 4; i++) {
687                                 int length;
688
689                                 length = captures [i].Length;
690                                 if (length == 0)
691                                         return false;
692                                 uint number;
693                                 if (!UInt32.TryParse (captures [i], out number))
694                                         return false;
695                                 if (number > 255)
696                                         return false;
697                         }
698                         return true;
699                 }                       
700                                 
701                 internal static bool IsDomainAddress (string name)
702                 {
703                         int len = name.Length;
704                         
705                         int count = 0;
706                         for (int i = 0; i < len; i++) {
707                                 char c = name [i];
708                                 if (count == 0) {
709                                         if (!Char.IsLetterOrDigit (c))
710                                                 return false;
711                                 } else if (c == '.') {
712                                         // www..host.com is bad
713                                         if (i + 1 < len && name [i + 1] == '.')
714                                                 return false;
715                                         count = 0;
716                                         continue;
717                                 } else if (!Char.IsLetterOrDigit (c) && c != '-' && c != '_') {
718                                         return false;
719                                 }
720                                 if (++count == 64)
721                                         return false;
722                         }
723                         
724                         return true;
725                 }
726 #if !NET_2_1
727
728                 [Obsolete ("This method does nothing, it has been obsoleted")]
729                 protected virtual void Canonicalize ()
730                 {
731                         //
732                         // This is flagged in the Microsoft documentation as used
733                         // internally, no longer in use, and Obsolete.
734                         //
735                 }
736
737                 [MonoTODO ("Find out what this should do")]
738                 [Obsolete]
739                 protected virtual void CheckSecurity ()
740                 {
741                 }
742
743 #endif // NET_2_1
744
745                 // defined in RFC3986 as = ALPHA *( ALPHA / DIGIT / "+" / "-" / ".")
746                 public static bool CheckSchemeName (string schemeName) 
747                 {
748                         if (schemeName == null || schemeName.Length == 0)
749                                 return false;
750                         
751                         if (!IsAlpha (schemeName [0]))
752                                 return false;
753
754                         int len = schemeName.Length;
755                         for (int i = 1; i < len; i++) {
756                                 char c = schemeName [i];
757                                 if (!Char.IsDigit (c) && !IsAlpha (c) && c != '.' && c != '+' && c != '-')
758                                         return false;
759                         }
760                         
761                         return true;
762                 }
763
764                 private static bool IsAlpha (char c)
765                 {
766                         // as defined in rfc2234
767                         // %x41-5A / %x61-7A (A-Z / a-z)
768                         int i = (int) c;
769                         return (((i >= 0x41) && (i <= 0x5A)) || ((i >= 0x61) && (i <= 0x7A)));
770                 }
771
772                 public override bool Equals (object comparand) 
773                 {
774                         if (comparand == null) 
775                                 return false;
776
777                         Uri uri = comparand as Uri;
778                         if ((object) uri == null) {
779                                 string s = comparand as String;
780                                 if (s == null)
781                                         return false;
782
783                                 if (!TryCreate (s, UriKind.RelativeOrAbsolute, out uri))
784                                         return false;
785                         }
786
787                         return InternalEquals (uri);
788                 }
789
790                 // Assumes: uri != null
791                 bool InternalEquals (Uri uri)
792                 {
793                         if (this.isAbsoluteUri != uri.isAbsoluteUri)
794                                 return false;
795                         if (!this.isAbsoluteUri)
796                                 return this.source == uri.source;
797
798                         CultureInfo inv = CultureInfo.InvariantCulture;
799                         return this.scheme.ToLower (inv) == uri.scheme.ToLower (inv)
800                                 && this.host.ToLower (inv) == uri.host.ToLower (inv)
801                                 && this.port == uri.port
802                                 && this.query == uri.query
803                                 && this.path == uri.path;
804                 }
805
806                 public static bool operator == (Uri uri1, Uri uri2)
807                 {
808                         return object.Equals (uri1, uri2);
809                 }
810
811                 public static bool operator != (Uri uri1, Uri uri2)
812                 {
813                         return !(uri1 == uri2);
814                 }
815
816                 public override int GetHashCode () 
817                 {
818                         if (cachedHashCode == 0) {
819                                 CultureInfo inv = CultureInfo.InvariantCulture;
820                                 if (isAbsoluteUri) {
821                                         cachedHashCode = scheme.ToLower (inv).GetHashCode ()
822                                                 ^ host.ToLower (inv).GetHashCode ()
823                                                 ^ port
824                                                 ^ query.GetHashCode ()
825                                                 ^ path.GetHashCode ();
826                                 }
827                                 else {
828                                         cachedHashCode = source.GetHashCode ();
829                                 }
830                         }
831                         return cachedHashCode;
832                 }
833                 
834                 public string GetLeftPart (UriPartial part) 
835                 {
836                         EnsureAbsoluteUri ();
837                         int defaultPort;
838                         switch (part) {                         
839                         case UriPartial.Scheme : 
840                                 return scheme + GetOpaqueWiseSchemeDelimiter ();
841                         case UriPartial.Authority :
842                                 if ((scheme == Uri.UriSchemeMailto) || (scheme == Uri.UriSchemeNews))
843                                         return String.Empty;
844                                         
845                                 StringBuilder s = new StringBuilder ();
846                                 s.Append (scheme);
847                                 s.Append (GetOpaqueWiseSchemeDelimiter ());
848                                 if (path.Length > 1 && path [1] == ':' && (Uri.UriSchemeFile == scheme)) 
849                                         s.Append ('/');  // win32 file
850                                 if (userinfo != null) 
851                                         s.Append (userinfo).Append ('@');
852                                 s.Append (host);
853                                 defaultPort = GetDefaultPort (scheme);
854                                 if ((port != -1) && (port != defaultPort))
855                                         s.Append (':').Append (port);                    
856                                 return s.ToString ();                           
857                         case UriPartial.Path :
858                                 StringBuilder sb = new StringBuilder ();
859                                 sb.Append (scheme);
860                                 sb.Append (GetOpaqueWiseSchemeDelimiter ());
861                                 if (path.Length > 1 && path [1] == ':' && (Uri.UriSchemeFile == scheme)) 
862                                         sb.Append ('/');  // win32 file
863                                 if (userinfo != null) 
864                                         sb.Append (userinfo).Append ('@');
865                                 sb.Append (host);
866                                 defaultPort = GetDefaultPort (scheme);
867                                 if ((port != -1) && (port != defaultPort))
868                                         sb.Append (':').Append (port);
869
870                                 if (path.Length > 0) {
871                                         if (scheme == "mailto" || scheme == "news")
872                                                 sb.Append (path);
873                                         else 
874                                                 sb.Append (Reduce (path, CompactEscaped (scheme)));
875                                 }
876                                 return sb.ToString ();
877                         }
878                         return null;
879                 }
880
881                 public static int FromHex (char digit) 
882                 {
883                         if ('0' <= digit && digit <= '9') {
884                                 return (int) (digit - '0');
885                         }
886                                 
887                         if ('a' <= digit && digit <= 'f')
888                                 return (int) (digit - 'a' + 10);
889
890                         if ('A' <= digit && digit <= 'F')
891                                 return (int) (digit - 'A' + 10);
892                                 
893                         throw new ArgumentException ("digit");
894                 }
895
896                 public static string HexEscape (char character) 
897                 {
898                         if (character > 255) {
899                                 throw new ArgumentOutOfRangeException ("character");
900                         }
901                         
902                         return "%" + hexUpperChars [((character & 0xf0) >> 4)] 
903                                    + hexUpperChars [((character & 0x0f))];
904                 }
905
906                 public static char HexUnescape (string pattern, ref int index) 
907                 {
908                         if (pattern == null) 
909                                 throw new ArgumentException ("pattern");
910                                 
911                         if (index < 0 || index >= pattern.Length)
912                                 throw new ArgumentOutOfRangeException ("index");
913
914                         if (!IsHexEncoding (pattern, index))
915                                 return pattern [index++];
916
917                         index++;
918                         int msb = FromHex (pattern [index++]);
919                         int lsb = FromHex (pattern [index++]);
920                         return (char) ((msb << 4) | lsb);
921                 }
922
923                 public static bool IsHexDigit (char character) 
924                 {
925                         return (('0' <= character && character <= '9') ||
926                                 ('a' <= character && character <= 'f') ||
927                                 ('A' <= character && character <= 'F'));
928                 }
929
930                 public static bool IsHexEncoding (string pattern, int index) 
931                 {
932                         if ((index + 3) > pattern.Length)
933                                 return false;
934
935                         return ((pattern [index++] == '%') &&
936                                 IsHexDigit (pattern [index++]) &&
937                                 IsHexDigit (pattern [index]));
938                 }
939
940                 //
941                 // Implemented by copying most of the MakeRelative code
942                 //
943                 public Uri MakeRelativeUri (Uri uri)
944                 {
945                         if (uri == null)
946                                 throw new ArgumentNullException ("uri");
947                         if (Host != uri.Host || Scheme != uri.Scheme)
948                                 return uri;
949
950                         string result = String.Empty;
951                         if (this.path != uri.path){
952                                 string [] segments = this.Segments;
953                                 string [] segments2 = uri.Segments;
954                                 
955                                 int k = 0;
956                                 int max = Math.Min (segments.Length, segments2.Length);
957                                 for (; k < max; k++)
958                                         if (segments [k] != segments2 [k]) 
959                                                 break;
960                                 
961                                 for (int i = k; i < segments.Length && segments [i].EndsWith ("/", StringComparison.Ordinal); i++)
962                                         result += "../";
963                                 for (int i = k; i < segments2.Length; i++)
964                                         result += segments2 [i];
965                                 
966                                 if (result == string.Empty)
967                                         result = "./";
968                         }
969                         uri.AppendQueryAndFragment (ref result);
970
971                         return new Uri (result, UriKind.Relative);
972                 }
973
974                 [Obsolete ("Use MakeRelativeUri(Uri uri) instead.")]
975                 public string MakeRelative (Uri toUri) 
976                 {
977                         if ((this.Scheme != toUri.Scheme) ||
978                             (this.Authority != toUri.Authority))
979                                 return toUri.ToString ();
980
981                         string result = String.Empty;
982                         if (this.path != toUri.path){
983                                 string [] segments = this.Segments;
984                                 string [] segments2 = toUri.Segments;
985                                 int k = 0;
986                                 int max = Math.Min (segments.Length, segments2.Length);
987                                 for (; k < max; k++)
988                                         if (segments [k] != segments2 [k]) 
989                                                 break;
990                                 
991                                 for (int i = k + 1; i < segments.Length; i++)
992                                         result += "../";
993                                 for (int i = k; i < segments2.Length; i++)
994                                         result += segments2 [i];
995                         }
996
997                         // Important: MakeRelative does not append fragment or query.
998
999                         return result;
1000                 }
1001
1002                 void AppendQueryAndFragment (ref string result)
1003                 {
1004                         if (query.Length > 0) {
1005                                 string q = query [0] == '?' ? '?' + Unescape (query.Substring (1), true, false) : Unescape (query, false);
1006                                 result += q;
1007                         }
1008                         if (fragment.Length > 0)
1009                                 result += Unescape (fragment, true, false);
1010                 }
1011                 
1012                 public override string ToString () 
1013                 {
1014                         if (cachedToString != null) 
1015                                 return cachedToString;
1016
1017                         if (isAbsoluteUri) {
1018                                 if (Parser is DefaultUriParser)
1019                                         cachedToString = Parser.GetComponentsHelper (this, UriComponents.AbsoluteUri, UriHelper.ToStringUnescape);
1020                                 else
1021                                         cachedToString = Parser.GetComponents (this, UriComponents.AbsoluteUri, UriFormat.SafeUnescaped);
1022                         } else
1023                                 cachedToString = UriHelper.FormatRelative (source, scheme, UriHelper.ToStringUnescape);
1024
1025                         return cachedToString;
1026                 }
1027
1028                 protected void GetObjectData (SerializationInfo serializationInfo, StreamingContext streamingContext)
1029                 {
1030                         if (this.isAbsoluteUri) {
1031                                 serializationInfo.AddValue ("AbsoluteUri", this.AbsoluteUri);
1032                         } else {
1033                                 serializationInfo.AddValue ("AbsoluteUri", String.Empty);
1034                                 serializationInfo.AddValue ("RelativeUri", this.OriginalString);
1035                         }
1036                 }
1037
1038                 void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context)
1039                 {
1040                         GetObjectData (info, context);
1041                 }
1042
1043
1044                 // Internal Methods             
1045
1046                 [Obsolete]
1047                 protected virtual void Escape ()
1048                 {
1049                         path = EscapeString (path);
1050                 }
1051
1052                 [Obsolete]
1053                 protected static string EscapeString (string str) 
1054                 {
1055                         return EscapeString (str, Uri.EscapeCommonHexBrackets);
1056                 }
1057
1058                 private const string EscapeCommon = "<>%\"{}|\\^`";
1059                 private const string EscapeReserved = ";/?:@&=+$,";
1060                 private const string EscapeFragment = "#";
1061                 private const string EscapeBrackets = "[]";
1062
1063                 private const string EscapeNews = EscapeCommon + EscapeBrackets + "?";
1064                 private const string EscapeCommonHex = EscapeCommon + EscapeFragment;
1065                 private const string EscapeCommonBrackets = EscapeCommon + EscapeBrackets;
1066                 internal const string EscapeCommonHexBrackets = EscapeCommon + EscapeFragment + EscapeBrackets;
1067                 internal const string EscapeCommonHexBracketsQuery = EscapeCommonHexBrackets + "?";
1068
1069                 internal static string EscapeString (string str, string escape)
1070                 {
1071                         return EscapeString (str, escape, true);
1072                 }
1073
1074                 internal static string EscapeString (string str, string escape, bool nonAsciiEscape) 
1075                 {
1076                         if (String.IsNullOrEmpty (str))
1077                                 return String.Empty;
1078                         
1079                         StringBuilder s = new StringBuilder ();
1080                         int len = str.Length;   
1081                         for (int i = 0; i < len; i++) {
1082                                 // reserved    = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | "$" | ","
1083                                 // mark        = "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")"
1084                                 // control     = <US-ASCII coded characters 00-1F and 7F hexadecimal>
1085                                 // space       = <US-ASCII coded character 20 hexadecimal>
1086                                 // delims      = "<" | ">" | "#" | "%" | <">
1087                                 // unwise      = "{" | "}" | "|" | "\" | "^" | "[" | "]" | "`"
1088
1089                                 // check for escape code already placed in str, 
1090                                 // i.e. for encoding that follows the pattern 
1091                                 // "%hexhex" in a string, where "hex" is a digit from 0-9 
1092                                 // or a letter from A-F (case-insensitive).
1093                                 if (IsHexEncoding (str,i)) {
1094                                         // if ,yes , copy it as is
1095                                         s.Append (str.Substring (i, 3));
1096                                         i += 2;
1097                                         continue;
1098                                 }
1099
1100                                 char c = str [i];
1101                                 bool outside_limited_ascii = ((c <= 0x20) || (c >= 0x7f));
1102                                 bool needs_escape = (escape.IndexOf (c) != -1);
1103                                 if (nonAsciiEscape && outside_limited_ascii) {
1104                                         byte [] data = Encoding.UTF8.GetBytes (new char [] { c });
1105                                         int length = data.Length;
1106                                         for (int j = 0; j < length; j++) {
1107                                                 c = (char) data [j];
1108                                                 if (needs_escape || nonAsciiEscape)
1109                                                         s.Append (HexEscape (c));
1110                                                 else
1111                                                         s.Append (c);
1112                                         }
1113                                 } else if (needs_escape) {
1114                                         s.Append (HexEscape (c));
1115                                 } else {
1116                                         s.Append (c);
1117                                 }
1118                         }
1119                         
1120                         return s.ToString ();
1121                 }
1122
1123                 // On .NET 1.x, this method is called from .ctor(). When overriden, we 
1124                 // can avoid the "absolute uri" constraints of the .ctor() by
1125                 // overriding with custom code.
1126                 [Obsolete("The method has been deprecated. It is not used by the system.")]
1127                 protected virtual void Parse ()
1128                 {
1129                 }
1130
1131                 private void ParseUri (UriKind kind)
1132                 {
1133                         Parse (kind, source);
1134
1135                         if (userEscaped)
1136                                 return;
1137
1138                         if (host.Length > 1 && host [0] != '[' && host [host.Length - 1] != ']') {
1139                                 // host name present (but not an IPv6 address)
1140                                 host = host.ToLower (CultureInfo.InvariantCulture);
1141                         }
1142                 }
1143
1144                 [Obsolete]
1145                 protected virtual string Unescape (string path)
1146                 {
1147                         var formatFlags = UriHelper.FormatFlags.NoSlashReplace | UriHelper.FormatFlags.NoReduce;
1148                         return UriHelper.FormatAbsolute (path, scheme, UriComponents.Path, UriFormat.Unescaped, formatFlags);
1149                 }
1150
1151                 internal static string Unescape (string str, bool excludeSpecial)
1152                 {
1153                         return Unescape (str, excludeSpecial, excludeSpecial);
1154                 }
1155                 
1156                 internal static string Unescape (string str, bool excludeSpecial, bool excludeBackslash) 
1157                 {
1158                         if (String.IsNullOrEmpty (str))
1159                                 return String.Empty;
1160
1161                         StringBuilder s = new StringBuilder ();
1162                         int len = str.Length;
1163                         for (int i = 0; i < len; i++) {
1164                                 char c = str [i];
1165                                 if (c == '%') {
1166                                         char surrogate;
1167                                         char x = HexUnescapeMultiByte (str, ref i, out surrogate);
1168                                         if (excludeSpecial && x == '#')
1169                                                 s.Append ("%23");
1170                                         else if (excludeSpecial && x == '%')
1171                                                 s.Append ("%25");
1172                                         else if (excludeSpecial && x == '?')
1173                                                 s.Append ("%3F");
1174                                         else if (excludeBackslash && x == '\\')
1175                                                 s.Append ("%5C");
1176                                         else {
1177                                                 s.Append (x);
1178                                                 if (surrogate != char.MinValue)
1179                                                         s.Append (surrogate);
1180                                         }
1181                                         i--;
1182                                 } else
1183                                         s.Append (c);
1184                         }
1185                         return s.ToString ();
1186                 }
1187
1188                 
1189                 // Private Methods
1190                 
1191                 private void ParseAsWindowsUNC (string uriString)
1192                 {
1193                         scheme = UriSchemeFile;
1194                         port = -1;
1195                         fragment = String.Empty;
1196                         query = String.Empty;
1197                         isUnc = true;
1198
1199                         uriString = uriString.TrimStart (new char [] {'\\'});
1200                         int pos = uriString.IndexOf ('\\');
1201                         if (pos > 0) {
1202                                 path = uriString.Substring (pos);
1203                                 host = uriString.Substring (0, pos);
1204                         } else { // "\\\\server"
1205                                 host = uriString;
1206                                 path = String.Empty;
1207                         }
1208                         path = path.Replace ("\\", "/");
1209                 }
1210
1211                 //
1212                 // Returns null on success, string with error on failure
1213                 //
1214                 private string ParseAsWindowsAbsoluteFilePath (string uriString)
1215                 {
1216                         if (uriString.Length > 2 && uriString [2] != '\\' && uriString [2] != '/')
1217                                 return "Relative file path is not allowed.";
1218                         scheme = UriSchemeFile;
1219                         host = String.Empty;
1220                         port = -1;
1221                         path = uriString.Replace ("\\", "/");
1222                         fragment = String.Empty;
1223                         query = String.Empty;
1224
1225                         return null;
1226                 }
1227
1228                 private void ParseAsUnixAbsoluteFilePath (string uriString)
1229                 {
1230                         scheme = UriSchemeFile;
1231                         port = -1;
1232                         fragment = String.Empty;
1233                         query = String.Empty;
1234                         host = String.Empty;
1235                         path = null;
1236
1237                         if (uriString.Length >= 2 && uriString [0] == '/' && uriString [1] == '/') {
1238                                 uriString = uriString.TrimStart (new char [] {'/'});
1239                                 // Now we don't regard //foo/bar as "foo" host.
1240                                 /* 
1241                                 int pos = uriString.IndexOf ('/');
1242                                 if (pos > 0) {
1243                                         path = '/' + uriString.Substring (pos + 1);
1244                                         host = uriString.Substring (0, pos);
1245                                 } else { // "///server"
1246                                         host = uriString;
1247                                         path = String.Empty;
1248                                 }
1249                                 */
1250                                 path = '/' + uriString;
1251                         }
1252                         if (path == null)
1253                                 path = uriString;
1254                 }
1255
1256                 //
1257                 // This parse method will throw exceptions on failure
1258                 //  
1259                 private void Parse (UriKind kind, string uriString)
1260                 {                       
1261                         if (uriString == null)
1262                                 throw new ArgumentNullException ("uriString");
1263
1264                         string s = ParseNoExceptions (kind, uriString);
1265                         if (s != null)
1266                                 throw new UriFormatException (s);
1267                 }
1268
1269                 private bool SupportsQuery ()
1270                 {
1271                         return UriHelper.SupportsQuery (scheme);
1272                 }
1273
1274
1275                 private string ParseNoExceptions (UriKind kind, string uriString)
1276                 {
1277                         UriElements elements;
1278                         string error;
1279                         if (!UriParseComponents.TryParseComponents (source, kind, out elements, out error))
1280                                 return error;
1281
1282                         scheme = elements.scheme;
1283                         var parser = UriParser.GetParser (scheme);
1284                         if (parser != null && !(parser is DefaultUriParser)) {
1285                                 userinfo = Parser.GetComponents (this, UriComponents.UserInfo, UriFormat.UriEscaped);
1286                                 host = Parser.GetComponents (this, UriComponents.Host, UriFormat.UriEscaped);
1287
1288                                 var portStr = Parser.GetComponents (this, UriComponents.StrongPort, UriFormat.UriEscaped);
1289                                 if (!string.IsNullOrEmpty (portStr))
1290                                         port = int.Parse (portStr);
1291
1292                                 path = Parser.GetComponents (this, UriComponents.Path | UriComponents.KeepDelimiter, UriFormat.UriEscaped);
1293                                 query = Parser.GetComponents (this, UriComponents.Query, UriFormat.UriEscaped);
1294                                 fragment = Parser.GetComponents (this, UriComponents.StrongPort, UriFormat.UriEscaped);
1295
1296                                 return null;
1297                         }
1298
1299                         var formatFlags = UriHelper.FormatFlags.None;
1300                         if (UriHelper.HasCharactersToNormalize (uriString))
1301                                 formatFlags |= UriHelper.FormatFlags.HasUriCharactersToNormalize;
1302
1303                         if (userEscaped)
1304                                 formatFlags |= UriHelper.FormatFlags.UserEscaped;
1305
1306                         if (elements.host != null)
1307                                 formatFlags |= UriHelper.FormatFlags.HasHost;
1308
1309                         userinfo = elements.user;
1310
1311                         if (elements.host != null) {
1312                                 host = UriHelper.FormatAbsolute (elements.host, scheme,
1313                                         UriComponents.Host, UriFormat.UriEscaped, formatFlags);
1314                         }
1315
1316                         port = elements.port;
1317
1318                         if (port == -1)
1319                                 port = GetDefaultPort (scheme);
1320
1321                         if (elements.path != null) {
1322                                 path = UriHelper.FormatAbsolute (elements.path, scheme,
1323                                         UriComponents.Path, UriFormat.UriEscaped, formatFlags);
1324                                 if (elements.delimiter == SchemeDelimiter && string.IsNullOrEmpty (path))
1325                                         path = "/";
1326                         }
1327
1328                         if (elements.query != null) {
1329                                 query = "?" + UriHelper.FormatAbsolute (elements.query, scheme,
1330                                         UriComponents.Query, UriFormat.UriEscaped, formatFlags);
1331                         }
1332
1333                         if (elements.fragment != null) {
1334                                 fragment = "#" + UriHelper.FormatAbsolute (elements.fragment, scheme,
1335                                         UriComponents.Fragment, UriFormat.UriEscaped, formatFlags);
1336                         }
1337
1338                         isAbsoluteUri = elements.isAbsoluteUri;
1339                         isUnc = elements.isUnc;
1340                         scope_id = elements.scopeId;
1341
1342                         return null;
1343                 }
1344                 
1345                 private static string TryGetKnownUriSchemeInstance (string scheme)
1346                 {
1347                         foreach (string knownScheme in knownUriSchemes) {
1348                                 if (knownScheme == scheme)
1349                                         return knownScheme;
1350                         }
1351                         
1352                         return scheme;
1353                 }
1354         
1355                 private static bool CompactEscaped (string scheme)
1356                 {
1357                         if (scheme == null || scheme.Length < 4)
1358                                 return false;
1359
1360                         char first = scheme [0];
1361                         if (first == 'h'){
1362                                 return scheme == "http" || scheme == "https";
1363                         } else if (first == 'f' && scheme == "file"){
1364                                 return true;
1365                         } else if (first == 'n')
1366                                 return scheme == "net.pipe" || scheme == "net.tcp";
1367
1368                         return false;
1369                 }
1370
1371                 // replace '\', %5C ('\') and %2f ('/') into '/'
1372                 // replace %2e ('.') into '.'
1373                 private static string NormalizePath (string path)
1374                 {
1375                         StringBuilder res = new StringBuilder ();
1376                         for (int i = 0; i < path.Length; i++) {
1377                                 char c = path [i];
1378                                 switch (c) {
1379                                 case '\\':
1380                                         c = '/';
1381                                         break;
1382                                 case '%':
1383                                         if (i < path.Length - 2) {
1384                                                 char c1 = path [i + 1];
1385                                                 char c2 = Char.ToUpper (path [i + 2]);
1386                                                 if ((c1 == '2') && (c2 == 'E')) {
1387                                                         c = '.';
1388                                                         i += 2;
1389                                                 } else if (((c1 == '2') && (c2 == 'F')) || ((c1 == '5') && (c2 == 'C'))) {
1390                                                         c = '/';
1391                                                         i += 2;
1392                                                 }
1393                                         }
1394                                         break;
1395                                 }
1396                                 res.Append (c);
1397                         }
1398                         return res.ToString ();
1399                 }
1400
1401                 // This is called "compacting" in the MSDN documentation
1402                 private static string Reduce (string path, bool compact_escaped)
1403                 {
1404                         // quick out, allocation-free, for a common case
1405                         if (path == "/")
1406                                 return path;
1407
1408                         if (compact_escaped && (path.IndexOf ('%') != -1)) {
1409                                 // replace '\', %2f, %5c with '/' and replace %2e with '.'
1410                                 // other escaped values seems to survive this step
1411                                 path = NormalizePath (path);
1412                         } else {
1413                                 // (always) replace '\' with '/'
1414                                 path = path.Replace ('\\', '/');
1415                         }
1416
1417                         List<string> result = new List<string> ();
1418
1419                         bool begin = true;
1420                         for (int startpos = 0; startpos < path.Length; ) {
1421                                 int endpos = path.IndexOf ('/', startpos);
1422                                 if (endpos == -1)
1423                                         endpos = path.Length;
1424                                 string current = path.Substring (startpos, endpos-startpos);
1425                                 startpos = endpos + 1;
1426                                 if ((begin && current.Length == 0) || current == "." ) {
1427                                         begin = false;
1428                                         continue;
1429                                 }
1430
1431                                 begin = false;
1432                                 if (current == "..") {
1433                                         int resultCount = result.Count;
1434                                         // in 2.0 profile, skip leading ".." parts
1435                                         if (resultCount == 0) {
1436                                                 continue;
1437                                         }
1438
1439                                         result.RemoveAt (resultCount - 1);
1440                                         continue;
1441                                 }
1442
1443                                 result.Add (current);
1444                         }
1445
1446                         if (result.Count == 0)
1447                                 return "/";
1448
1449                         StringBuilder res = new StringBuilder ();
1450
1451                         if (path [0] == '/')
1452                                 res.Append ('/');
1453
1454                         bool first = true;
1455                         foreach (string part in result) {
1456                                 if (first) {
1457                                         first = false;
1458                                 } else {
1459                                         res.Append ('/');
1460                                 }
1461                                 res.Append (part);
1462                         }
1463
1464                         if (path [path.Length - 1] == '/')
1465                                 res.Append ('/');
1466                                 
1467                         return res.ToString ();
1468                 }
1469
1470                 // A variant of HexUnescape() which can decode multi-byte escaped
1471                 // sequences such as (e.g.) %E3%81%8B into a single character
1472                 internal static char HexUnescapeMultiByte (string pattern, ref int index, out char surrogate) 
1473                 {
1474                         bool invalidEscape;
1475                         return HexUnescapeMultiByte (pattern, ref index, out surrogate, out invalidEscape);
1476                 }
1477
1478                 internal static char HexUnescapeMultiByte (string pattern, ref int index, out char surrogate, out bool invalidEscape)
1479                 {
1480                         surrogate = char.MinValue;
1481                         invalidEscape = false;
1482
1483                         if (pattern == null) 
1484                                 throw new ArgumentException ("pattern");
1485                                 
1486                         if (index < 0 || index >= pattern.Length)
1487                                 throw new ArgumentOutOfRangeException ("index");
1488
1489                         if (!IsHexEncoding (pattern, index))
1490                                 return pattern [index++];
1491
1492                         int orig_index = index++;
1493                         int msb = FromHex (pattern [index++]);
1494                         int lsb = FromHex (pattern [index++]);
1495
1496                         // We might be dealing with a multi-byte character:
1497                         // The number of ones at the top-end of the first byte will tell us
1498                         // how many bytes will make up this character.
1499                         int msb_copy = msb;
1500                         int num_bytes = 0;
1501                         while ((msb_copy & 0x8) == 0x8) {
1502                                 num_bytes++;
1503                                 msb_copy <<= 1;
1504                         }
1505
1506                         // We might be dealing with a single-byte character:
1507                         // If there was only 0 or 1 leading ones then we're not dealing
1508                         // with a multi-byte character.
1509                         if (num_bytes <= 1) {
1510                                 var c = (char) ((msb << 4) | lsb);
1511                                 invalidEscape = c > 0x7F;
1512                                 return c;
1513                         }
1514
1515                         // Now that we know how many bytes *should* follow, we'll check them
1516                         // to ensure we are dealing with a valid multi-byte character.
1517                         byte [] chars = new byte [num_bytes];
1518                         bool all_invalid = false;
1519                         chars[0] = (byte) ((msb << 4) | lsb);
1520
1521                         for (int i = 1; i < num_bytes; i++) {
1522                                 if (!IsHexEncoding (pattern, index++)) {
1523                                         all_invalid = true;
1524                                         break;
1525                                 }
1526
1527                                 // All following bytes must be in the form 10xxxxxx
1528                                 int cur_msb = FromHex (pattern [index++]);
1529                                 if ((cur_msb & 0xc) != 0x8) {
1530                                         all_invalid = true;
1531                                         break;
1532                                 }
1533
1534                                 int cur_lsb = FromHex (pattern [index++]);
1535                                 chars[i] = (byte) ((cur_msb << 4) | cur_lsb);
1536                         }
1537
1538                         // If what looked like a multi-byte character is invalid, then we'll
1539                         // just return the first byte as a single byte character.
1540                         if (all_invalid) {
1541                                 invalidEscape = true;
1542                                 index = orig_index + 3;
1543                                 return (char) chars[0];
1544                         }
1545
1546                         // Otherwise, we're dealing with a valid multi-byte character.
1547                         // We need to ignore the leading ones from the first byte:
1548                         byte mask = (byte) 0xFF;
1549                         mask >>= (num_bytes + 1);
1550                         int result = chars[0] & mask;
1551
1552                         // The result will now be built up from the following bytes.
1553                         for (int i = 1; i < num_bytes; i++) {
1554                                 // Ignore upper two bits
1555                                 result <<= 6;
1556                                 result |= (chars[i] & 0x3F);
1557                         }
1558
1559                         if (result <= 0xFFFF) {
1560                                 return (char) result;
1561                         } else {
1562                                 // We need to handle this as a UTF16 surrogate (i.e. return
1563                                 // two characters)
1564                                 result -= 0x10000;
1565                                 surrogate = (char) ((result & 0x3FF) | 0xDC00);
1566                                 return (char) ((result >> 10) | 0xD800);
1567                         }
1568                 }
1569
1570                 private struct UriScheme 
1571                 {
1572                         public string scheme;
1573                         public string delimiter;
1574                         public int defaultPort;
1575
1576                         public UriScheme (string s, string d, int p) 
1577                         {
1578                                 scheme = s;
1579                                 delimiter = d;
1580                                 defaultPort = p;
1581                         }
1582                 };
1583
1584                 static UriScheme [] schemes = new UriScheme [] {
1585                         new UriScheme (UriSchemeHttp, SchemeDelimiter, 80),
1586                         new UriScheme (UriSchemeHttps, SchemeDelimiter, 443),
1587                         new UriScheme (UriSchemeFtp, SchemeDelimiter, 21),
1588                         new UriScheme (UriSchemeFile, SchemeDelimiter, -1),
1589                         new UriScheme (UriSchemeMailto, ":", 25),
1590                         new UriScheme (UriSchemeNews, ":", 119),
1591                         new UriScheme (UriSchemeUuid, ":", -1),
1592                         new UriScheme (UriSchemeNntp, SchemeDelimiter, 119),
1593                         new UriScheme (UriSchemeGopher, SchemeDelimiter, 70),
1594                 };
1595                                 
1596                 internal static string GetSchemeDelimiter (string scheme) 
1597                 {
1598                         for (int i = 0; i < schemes.Length; i++) 
1599                                 if (schemes [i].scheme == scheme)
1600                                         return schemes [i].delimiter;
1601                         return Uri.SchemeDelimiter;
1602                 }
1603                 
1604                 internal static int GetDefaultPort (string scheme)
1605                 {
1606                         UriParser parser = UriParser.GetParser (scheme);
1607                         if (parser == null)
1608                                 return -1;
1609                         return parser.DefaultPort;
1610                 }
1611
1612                 private string GetOpaqueWiseSchemeDelimiter ()
1613                 {
1614                         return GetSchemeDelimiter (scheme);
1615                 }
1616
1617                 [Obsolete]
1618                 protected virtual bool IsBadFileSystemCharacter (char character)
1619                 {
1620                         // It does not always overlap with InvalidPathChars.
1621                         int chInt = (int) character;
1622                         if (chInt < 32 || (chInt < 64 && chInt > 57))
1623                                 return true;
1624                         switch (chInt) {
1625                         case 0:
1626                         case 34: // "
1627                         case 38: // &
1628                         case 42: // *
1629                         case 44: // ,
1630                         case 47: // /
1631                         case 92: // \
1632                         case 94: // ^
1633                         case 124: // |
1634                                 return true;
1635                         }
1636
1637                         return false;
1638                 }
1639
1640                 [Obsolete]
1641                 protected static bool IsExcludedCharacter (char character)
1642                 {
1643                         if (character <= 32 || character >= 127)
1644                                 return true;
1645                         
1646                         if (character == '"' || character == '#' || character == '%' || character == '<' ||
1647                             character == '>' || character == '[' || character == '\\' || character == ']' ||
1648                             character == '^' || character == '`' || character == '{' || character == '|' ||
1649                             character == '}')
1650                                 return true;
1651                         return false;
1652                 }
1653
1654                 internal static bool MaybeUri (string s)
1655                 {
1656                         int p = s.IndexOf (':');
1657                         if (p == -1)
1658                                 return false;
1659
1660                         if (p >= 10)
1661                                 return false;
1662
1663                         return IsPredefinedScheme (s.Substring (0, p));
1664                 }
1665                 
1666                 //
1667                 // Using a simple block of if's is twice as slow as the compiler generated
1668                 // switch statement.   But using this tuned code is faster than the
1669                 // compiler generated code, with a million loops on x86-64:
1670                 //
1671                 // With "http": .10 vs .51 (first check)
1672                 // with "https": .16 vs .51 (second check)
1673                 // with "foo": .22 vs .31 (never found)
1674                 // with "mailto": .12 vs .51  (last check)
1675                 //
1676                 //
1677                 private static bool IsPredefinedScheme (string scheme)
1678                 {
1679                         if (scheme == null || scheme.Length < 3)
1680                                 return false;
1681                         
1682                         char c = scheme [0];
1683                         if (c == 'h')
1684                                 return (scheme == "http" || scheme == "https");
1685                         if (c == 'f')
1686                                 return (scheme == "file" || scheme == "ftp");
1687                                 
1688                         if (c == 'n'){
1689                                 c = scheme [1];
1690                                 if (c == 'e')
1691                                         return (scheme == "news" || scheme == "net.pipe" || scheme == "net.tcp");
1692                                 if (scheme == "nntp")
1693                                         return true;
1694                                 return false;
1695                         }
1696                         if ((c == 'g' && scheme == "gopher") || (c == 'm' && scheme == "mailto"))
1697                                 return true;
1698
1699                         return false;
1700                 }
1701
1702                 [Obsolete]
1703                 protected virtual bool IsReservedCharacter (char character)
1704                 {
1705                         if (character == '$' || character == '&' || character == '+' || character == ',' ||
1706                             character == '/' || character == ':' || character == ';' || character == '=' ||
1707                             character == '@')
1708                                 return true;
1709                         return false;
1710                 }
1711
1712                 [NonSerialized]
1713                 private UriParser parser;
1714
1715                 private UriParser Parser {
1716                         get {
1717                                 if (parser == null) {
1718                                         parser = UriParser.GetParser (scheme);
1719                                         // no specific parser ? then use a default one
1720                                         if (parser == null)
1721                                                 parser = new DefaultUriParser ("*");
1722                                 }
1723                                 return parser;
1724                         }
1725                         set { parser = value; }
1726                 }
1727
1728                 public string GetComponents (UriComponents components, UriFormat format)
1729                 {
1730                         if ((components & UriComponents.SerializationInfoString) == 0)
1731                                 EnsureAbsoluteUri ();
1732
1733                         return Parser.GetComponents (this, components, format);
1734                 }
1735
1736                 public bool IsBaseOf (Uri uri)
1737                 {
1738                         if (uri == null)
1739                                 throw new ArgumentNullException ("uri");
1740                         return Parser.IsBaseOf (this, uri);
1741                 }
1742
1743                 public bool IsWellFormedOriginalString ()
1744                 {
1745                         // funny, but it does not use the Parser's IsWellFormedOriginalString().
1746                         // Also, it seems we need to *not* escape hex.
1747                         return EscapeString (OriginalString, EscapeCommonBrackets) == OriginalString;
1748                 }
1749
1750                 // static methods
1751
1752                 private const int MaxUriLength = 32766;
1753
1754                 public static int Compare (Uri uri1, Uri uri2, UriComponents partsToCompare, UriFormat compareFormat, StringComparison comparisonType)
1755                 {
1756                         if ((comparisonType < StringComparison.CurrentCulture) || (comparisonType > StringComparison.OrdinalIgnoreCase)) {
1757                                 string msg = Locale.GetText ("Invalid StringComparison value '{0}'", comparisonType);
1758                                 throw new ArgumentException ("comparisonType", msg);
1759                         }
1760
1761                         if ((uri1 == null) && (uri2 == null))
1762                                 return 0;
1763                         if (uri1 == null)
1764                                 return -1;
1765                         if (uri2 == null)
1766                                 return 1;
1767
1768                         string s1 = uri1.GetComponents (partsToCompare, compareFormat);
1769                         string s2 = uri2.GetComponents (partsToCompare, compareFormat);
1770                         return String.Compare (s1, s2, comparisonType);
1771                 }
1772
1773                 //
1774                 // The rules for EscapeDataString
1775                 //
1776                 static bool NeedToEscapeDataChar (char b)
1777                 {
1778                         if ((b >= 'A' && b <= 'Z') ||
1779                                 (b >= 'a' && b <= 'z') ||
1780                                 (b >= '0' && b <= '9'))
1781                                 return false;
1782
1783                         switch (b) {
1784                         case '-':
1785                         case '.':
1786                         case '_':
1787                         case '~':
1788                                 return false;
1789                         }
1790
1791
1792                         return true;
1793                 }
1794                 
1795                 public static string EscapeDataString (string stringToEscape)
1796                 {
1797                         if (stringToEscape == null)
1798                                 throw new ArgumentNullException ("stringToEscape");
1799
1800                         if (stringToEscape.Length > MaxUriLength) {
1801                                 throw new UriFormatException (string.Format ("Uri is longer than the maximum {0} characters.", MaxUriLength));
1802                         }
1803
1804                         bool escape = false;
1805                         foreach (char c in stringToEscape){
1806                                 if (NeedToEscapeDataChar (c)){
1807                                         escape = true;
1808                                         break;
1809                                 }
1810                         }
1811                         if (!escape){
1812                                 return stringToEscape;
1813                         }
1814                         
1815                         StringBuilder sb = new StringBuilder ();
1816                         byte [] bytes = Encoding.UTF8.GetBytes (stringToEscape);
1817                         foreach (byte b in bytes){
1818                                 if (NeedToEscapeDataChar ((char) b))
1819                                         sb.Append (HexEscape ((char) b));
1820                                 else
1821                                         sb.Append ((char) b);
1822                         }
1823                         return sb.ToString ();
1824                 }
1825
1826                 //
1827                 // The rules for EscapeUriString
1828                 //
1829                 static bool NeedToEscapeUriChar (char b)
1830                 {
1831                         if ((b >= 'A' && b <= 'Z') || (b >= 'a' && b <= 'z') || (b >= '&' && b <= ';'))
1832                                 return false;
1833
1834                         switch (b) {
1835                         case '!':
1836                         case '#':
1837                         case '$':
1838                         case '=':
1839                         case '?':
1840                         case '@':
1841                         case '_':
1842                         case '~':
1843                                 return false;
1844                         case '[':
1845                         case ']':
1846                                 return false;
1847                         }
1848
1849                         return true;
1850                 }
1851                 
1852                 public static string EscapeUriString (string stringToEscape)
1853                 {
1854                         if (stringToEscape == null)
1855                                 throw new ArgumentNullException ("stringToEscape");
1856
1857                         if (stringToEscape.Length > MaxUriLength) {
1858                                 throw new UriFormatException (string.Format ("Uri is longer than the maximum {0} characters.", MaxUriLength));
1859                         }
1860
1861                         bool escape = false;
1862                         foreach (char c in stringToEscape){
1863                                 if (NeedToEscapeUriChar (c)){
1864                                         escape = true;
1865                                         break;
1866                                 }
1867                         }
1868                         if (!escape)
1869                                 return stringToEscape;
1870
1871                         StringBuilder sb = new StringBuilder ();
1872                         byte [] bytes = Encoding.UTF8.GetBytes (stringToEscape);
1873                         foreach (byte b in bytes){
1874                                 if (NeedToEscapeUriChar ((char) b))
1875                                         sb.Append (HexEscape ((char) b));
1876                                 else
1877                                         sb.Append ((char) b);
1878                         }
1879                         return sb.ToString ();
1880                 }
1881
1882                 public static bool IsWellFormedUriString (string uriString, UriKind uriKind)
1883                 {
1884                         if (uriString == null)
1885                                 return false;
1886
1887                         Uri uri;
1888                         if (Uri.TryCreate (uriString, uriKind, out uri))
1889                                 return uri.IsWellFormedOriginalString ();
1890                         return false;
1891                 }
1892
1893                 public static bool TryCreate (string uriString, UriKind uriKind, out Uri result)
1894                 {
1895                         bool success;
1896
1897                         Uri r = new Uri (uriString, uriKind, out success);
1898                         if (success) {
1899                                 result = r;
1900                                 return true;
1901                         }
1902                         result = null;
1903                         return false;
1904                 }
1905
1906                 // [MonoTODO ("rework code to avoid exception catching")]
1907                 public static bool TryCreate (Uri baseUri, string relativeUri, out Uri result)
1908                 {
1909                         result = null;
1910                         if (relativeUri == null)
1911                                 return false;
1912
1913                         try {
1914                                 Uri relative = new Uri (relativeUri, UriKind.RelativeOrAbsolute);
1915                                 if ((baseUri != null) && baseUri.IsAbsoluteUri) {
1916                                         // FIXME: this should call UriParser.Resolve
1917                                         result = new Uri (baseUri, relative);
1918                                 } else if (relative.IsAbsoluteUri) {
1919                                         // special case - see unit tests
1920                                         result = relative;
1921                                 }
1922                                 return (result != null);
1923                         } catch (UriFormatException) {
1924                                 return false;
1925                         }
1926                 }
1927
1928                 //[MonoTODO ("rework code to avoid exception catching")]
1929                 public static bool TryCreate (Uri baseUri, Uri relativeUri, out Uri result)
1930                 {
1931                         result = null;
1932                         if ((baseUri == null) || !baseUri.IsAbsoluteUri)
1933                                 return false;
1934                         if (relativeUri == null)
1935                                 return false;
1936                         try {
1937                                 // FIXME: this should call UriParser.Resolve
1938                                 result = new Uri (baseUri, relativeUri.OriginalString);
1939                                 return true;
1940                         } catch (UriFormatException) {
1941                                 return false;
1942                         }
1943                 }
1944
1945                 public static string UnescapeDataString (string stringToUnescape)
1946                 {
1947                         return UnescapeDataString (stringToUnescape, false);
1948                 }
1949
1950                 internal static string UnescapeDataString (string stringToUnescape, bool safe)
1951                 {
1952                         if (stringToUnescape == null)
1953                                 throw new ArgumentNullException ("stringToUnescape");
1954
1955                         if (stringToUnescape.IndexOf ('%') == -1 && stringToUnescape.IndexOf ('+') == -1)
1956                                 return stringToUnescape;
1957
1958                         StringBuilder output = new StringBuilder ();
1959                         long len = stringToUnescape.Length;
1960                         MemoryStream bytes = new MemoryStream ();
1961                         int xchar;
1962
1963                         for (int i = 0; i < len; i++) {
1964                                 if (stringToUnescape [i] == '%' && i + 2 < len && stringToUnescape [i + 1] != '%') {
1965                                         if (stringToUnescape [i + 1] == 'u' && i + 5 < len) {
1966                                                 if (bytes.Length > 0) {
1967                                                         output.Append (GetChars (bytes, Encoding.UTF8));
1968                                                         bytes.SetLength (0);
1969                                                 }
1970
1971                                                 xchar = GetChar (stringToUnescape, i + 2, 4, safe);
1972                                                 if (xchar != -1) {
1973                                                         output.Append ((char) xchar);
1974                                                         i += 5;
1975                                                 }
1976                                                 else {
1977                                                         output.Append ('%');
1978                                                 }
1979                                         }
1980                                         else if ((xchar = GetChar (stringToUnescape, i + 1, 2, safe)) != -1) {
1981                                                 bytes.WriteByte ((byte) xchar);
1982                                                 i += 2;
1983                                         }
1984                                         else {
1985                                                 output.Append ('%');
1986                                         }
1987                                         continue;
1988                                 }
1989
1990                                 if (bytes.Length > 0) {
1991                                         output.Append (GetChars (bytes, Encoding.UTF8));
1992                                         bytes.SetLength (0);
1993                                 }
1994
1995                                 output.Append (stringToUnescape [i]);
1996                         }
1997
1998                         if (bytes.Length > 0) {
1999                                 output.Append (GetChars (bytes, Encoding.UTF8));
2000                         }
2001
2002                         bytes = null;
2003                         return output.ToString ();
2004                 }
2005
2006                 private static int GetInt (byte b)
2007                 {
2008                         char c = (char) b;
2009                         if (c >= '0' && c <= '9')
2010                                 return c - '0';
2011
2012                         if (c >= 'a' && c <= 'f')
2013                                 return c - 'a' + 10;
2014
2015                         if (c >= 'A' && c <= 'F')
2016                                 return c - 'A' + 10;
2017
2018                         return -1;
2019                 }
2020
2021                 private static int GetChar (string str, int offset, int length, bool safe)
2022                 {
2023                         int val = 0;
2024                         int end = length + offset;
2025                         for (int i = offset; i < end; i++) {
2026                                 char c = str [i];
2027                                 if (c > 127)
2028                                         return -1;
2029
2030                                 int current = GetInt ((byte) c);
2031                                 if (current == -1)
2032                                         return -1;
2033                                 val = (val << 4) + current;
2034                         }
2035
2036                         if (!safe)
2037                                 return val;
2038
2039                         switch ((char) val) {
2040                         case '%':
2041                         case '#':
2042                         case '?':
2043                         case '/':
2044                         case '\\':
2045                         case '@':
2046                         case '&': // not documented
2047                                 return -1;
2048                         default:
2049                                 return val;
2050                         }
2051                 }
2052
2053                 private static char [] GetChars (MemoryStream b, Encoding e)
2054                 {
2055                         return e.GetChars (b.GetBuffer (), 0, (int) b.Length);
2056                 }
2057                 
2058
2059                 private void EnsureAbsoluteUri ()
2060                 {
2061                         if (!IsAbsoluteUri)
2062                                 throw new InvalidOperationException ("This operation is not supported for a relative URI.");
2063                 }
2064         }
2065 }