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