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