[io-layer] add URLs for some ximian bug numbers in sockets.cs
[mono.git] / mcs / class / System / System.Net / HttpUtility.cs
1 // 
2 // Copied from System.Web.HttpUtility and marked internal
3 //
4 // Authors:
5 //   Patrik Torstensson (Patrik.Torstensson@labs2.com)
6 //   Wictor WilĂ©n (decode/encode functions) (wictor@ibizkit.se)
7 //   Tim Coleman (tim@timcoleman.com)
8 //   Gonzalo Paniagua Javier (gonzalo@ximian.com)
9 //
10 // Copyright (C) 2005-2009 Novell, Inc (http://www.novell.com)
11 //
12 // Permission is hereby granted, free of charge, to any person obtaining
13 // a copy of this software and associated documentation files (the
14 // "Software"), to deal in the Software without restriction, including
15 // without limitation the rights to use, copy, modify, merge, publish,
16 // distribute, sublicense, and/or sell copies of the Software, and to
17 // permit persons to whom the Software is furnished to do so, subject to
18 // the following conditions:
19 // 
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
22 // 
23 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
27 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
28 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30 //
31
32 using System.Collections;
33 using System.Collections.Generic;
34 using System.Collections.Specialized;
35 using System.Globalization;
36 using System.IO;
37 using System.Security.Permissions;
38 using System.Text;
39
40 namespace System.Net {
41
42         internal sealed class HttpUtility
43         {
44                 sealed class HttpQSCollection : NameValueCollection
45                 {
46                         public override string ToString ()
47                         {
48                                 int count = Count;
49                                 if (count == 0)
50                                         return "";
51                                 StringBuilder sb = new StringBuilder ();
52                                 string [] keys = AllKeys;
53                                 for (int i = 0; i < count; i++) {
54                                         sb.AppendFormat ("{0}={1}&", keys [i], this [keys [i]]);
55                                 }
56                                 if (sb.Length > 0)
57                                         sb.Length--;
58                                 return sb.ToString ();
59                         }
60                 }
61                 #region Fields
62         
63                 static Hashtable entities;
64                 static object lock_ = new object ();
65         
66                 #endregion // Fields
67         
68                 static Hashtable Entities {
69                         get {
70                                 lock (lock_) {
71                                         if (entities == null)
72                                                 InitEntities ();
73
74                                         return entities;
75                                 }
76                         }
77                 }
78                 
79                 #region Constructors
80
81                 static void InitEntities ()
82                 {
83                         // Build the hash table of HTML entity references.  This list comes
84                         // from the HTML 4.01 W3C recommendation.
85                         entities = new Hashtable ();
86                         entities.Add ("nbsp", '\u00A0');
87                         entities.Add ("iexcl", '\u00A1');
88                         entities.Add ("cent", '\u00A2');
89                         entities.Add ("pound", '\u00A3');
90                         entities.Add ("curren", '\u00A4');
91                         entities.Add ("yen", '\u00A5');
92                         entities.Add ("brvbar", '\u00A6');
93                         entities.Add ("sect", '\u00A7');
94                         entities.Add ("uml", '\u00A8');
95                         entities.Add ("copy", '\u00A9');
96                         entities.Add ("ordf", '\u00AA');
97                         entities.Add ("laquo", '\u00AB');
98                         entities.Add ("not", '\u00AC');
99                         entities.Add ("shy", '\u00AD');
100                         entities.Add ("reg", '\u00AE');
101                         entities.Add ("macr", '\u00AF');
102                         entities.Add ("deg", '\u00B0');
103                         entities.Add ("plusmn", '\u00B1');
104                         entities.Add ("sup2", '\u00B2');
105                         entities.Add ("sup3", '\u00B3');
106                         entities.Add ("acute", '\u00B4');
107                         entities.Add ("micro", '\u00B5');
108                         entities.Add ("para", '\u00B6');
109                         entities.Add ("middot", '\u00B7');
110                         entities.Add ("cedil", '\u00B8');
111                         entities.Add ("sup1", '\u00B9');
112                         entities.Add ("ordm", '\u00BA');
113                         entities.Add ("raquo", '\u00BB');
114                         entities.Add ("frac14", '\u00BC');
115                         entities.Add ("frac12", '\u00BD');
116                         entities.Add ("frac34", '\u00BE');
117                         entities.Add ("iquest", '\u00BF');
118                         entities.Add ("Agrave", '\u00C0');
119                         entities.Add ("Aacute", '\u00C1');
120                         entities.Add ("Acirc", '\u00C2');
121                         entities.Add ("Atilde", '\u00C3');
122                         entities.Add ("Auml", '\u00C4');
123                         entities.Add ("Aring", '\u00C5');
124                         entities.Add ("AElig", '\u00C6');
125                         entities.Add ("Ccedil", '\u00C7');
126                         entities.Add ("Egrave", '\u00C8');
127                         entities.Add ("Eacute", '\u00C9');
128                         entities.Add ("Ecirc", '\u00CA');
129                         entities.Add ("Euml", '\u00CB');
130                         entities.Add ("Igrave", '\u00CC');
131                         entities.Add ("Iacute", '\u00CD');
132                         entities.Add ("Icirc", '\u00CE');
133                         entities.Add ("Iuml", '\u00CF');
134                         entities.Add ("ETH", '\u00D0');
135                         entities.Add ("Ntilde", '\u00D1');
136                         entities.Add ("Ograve", '\u00D2');
137                         entities.Add ("Oacute", '\u00D3');
138                         entities.Add ("Ocirc", '\u00D4');
139                         entities.Add ("Otilde", '\u00D5');
140                         entities.Add ("Ouml", '\u00D6');
141                         entities.Add ("times", '\u00D7');
142                         entities.Add ("Oslash", '\u00D8');
143                         entities.Add ("Ugrave", '\u00D9');
144                         entities.Add ("Uacute", '\u00DA');
145                         entities.Add ("Ucirc", '\u00DB');
146                         entities.Add ("Uuml", '\u00DC');
147                         entities.Add ("Yacute", '\u00DD');
148                         entities.Add ("THORN", '\u00DE');
149                         entities.Add ("szlig", '\u00DF');
150                         entities.Add ("agrave", '\u00E0');
151                         entities.Add ("aacute", '\u00E1');
152                         entities.Add ("acirc", '\u00E2');
153                         entities.Add ("atilde", '\u00E3');
154                         entities.Add ("auml", '\u00E4');
155                         entities.Add ("aring", '\u00E5');
156                         entities.Add ("aelig", '\u00E6');
157                         entities.Add ("ccedil", '\u00E7');
158                         entities.Add ("egrave", '\u00E8');
159                         entities.Add ("eacute", '\u00E9');
160                         entities.Add ("ecirc", '\u00EA');
161                         entities.Add ("euml", '\u00EB');
162                         entities.Add ("igrave", '\u00EC');
163                         entities.Add ("iacute", '\u00ED');
164                         entities.Add ("icirc", '\u00EE');
165                         entities.Add ("iuml", '\u00EF');
166                         entities.Add ("eth", '\u00F0');
167                         entities.Add ("ntilde", '\u00F1');
168                         entities.Add ("ograve", '\u00F2');
169                         entities.Add ("oacute", '\u00F3');
170                         entities.Add ("ocirc", '\u00F4');
171                         entities.Add ("otilde", '\u00F5');
172                         entities.Add ("ouml", '\u00F6');
173                         entities.Add ("divide", '\u00F7');
174                         entities.Add ("oslash", '\u00F8');
175                         entities.Add ("ugrave", '\u00F9');
176                         entities.Add ("uacute", '\u00FA');
177                         entities.Add ("ucirc", '\u00FB');
178                         entities.Add ("uuml", '\u00FC');
179                         entities.Add ("yacute", '\u00FD');
180                         entities.Add ("thorn", '\u00FE');
181                         entities.Add ("yuml", '\u00FF');
182                         entities.Add ("fnof", '\u0192');
183                         entities.Add ("Alpha", '\u0391');
184                         entities.Add ("Beta", '\u0392');
185                         entities.Add ("Gamma", '\u0393');
186                         entities.Add ("Delta", '\u0394');
187                         entities.Add ("Epsilon", '\u0395');
188                         entities.Add ("Zeta", '\u0396');
189                         entities.Add ("Eta", '\u0397');
190                         entities.Add ("Theta", '\u0398');
191                         entities.Add ("Iota", '\u0399');
192                         entities.Add ("Kappa", '\u039A');
193                         entities.Add ("Lambda", '\u039B');
194                         entities.Add ("Mu", '\u039C');
195                         entities.Add ("Nu", '\u039D');
196                         entities.Add ("Xi", '\u039E');
197                         entities.Add ("Omicron", '\u039F');
198                         entities.Add ("Pi", '\u03A0');
199                         entities.Add ("Rho", '\u03A1');
200                         entities.Add ("Sigma", '\u03A3');
201                         entities.Add ("Tau", '\u03A4');
202                         entities.Add ("Upsilon", '\u03A5');
203                         entities.Add ("Phi", '\u03A6');
204                         entities.Add ("Chi", '\u03A7');
205                         entities.Add ("Psi", '\u03A8');
206                         entities.Add ("Omega", '\u03A9');
207                         entities.Add ("alpha", '\u03B1');
208                         entities.Add ("beta", '\u03B2');
209                         entities.Add ("gamma", '\u03B3');
210                         entities.Add ("delta", '\u03B4');
211                         entities.Add ("epsilon", '\u03B5');
212                         entities.Add ("zeta", '\u03B6');
213                         entities.Add ("eta", '\u03B7');
214                         entities.Add ("theta", '\u03B8');
215                         entities.Add ("iota", '\u03B9');
216                         entities.Add ("kappa", '\u03BA');
217                         entities.Add ("lambda", '\u03BB');
218                         entities.Add ("mu", '\u03BC');
219                         entities.Add ("nu", '\u03BD');
220                         entities.Add ("xi", '\u03BE');
221                         entities.Add ("omicron", '\u03BF');
222                         entities.Add ("pi", '\u03C0');
223                         entities.Add ("rho", '\u03C1');
224                         entities.Add ("sigmaf", '\u03C2');
225                         entities.Add ("sigma", '\u03C3');
226                         entities.Add ("tau", '\u03C4');
227                         entities.Add ("upsilon", '\u03C5');
228                         entities.Add ("phi", '\u03C6');
229                         entities.Add ("chi", '\u03C7');
230                         entities.Add ("psi", '\u03C8');
231                         entities.Add ("omega", '\u03C9');
232                         entities.Add ("thetasym", '\u03D1');
233                         entities.Add ("upsih", '\u03D2');
234                         entities.Add ("piv", '\u03D6');
235                         entities.Add ("bull", '\u2022');
236                         entities.Add ("hellip", '\u2026');
237                         entities.Add ("prime", '\u2032');
238                         entities.Add ("Prime", '\u2033');
239                         entities.Add ("oline", '\u203E');
240                         entities.Add ("frasl", '\u2044');
241                         entities.Add ("weierp", '\u2118');
242                         entities.Add ("image", '\u2111');
243                         entities.Add ("real", '\u211C');
244                         entities.Add ("trade", '\u2122');
245                         entities.Add ("alefsym", '\u2135');
246                         entities.Add ("larr", '\u2190');
247                         entities.Add ("uarr", '\u2191');
248                         entities.Add ("rarr", '\u2192');
249                         entities.Add ("darr", '\u2193');
250                         entities.Add ("harr", '\u2194');
251                         entities.Add ("crarr", '\u21B5');
252                         entities.Add ("lArr", '\u21D0');
253                         entities.Add ("uArr", '\u21D1');
254                         entities.Add ("rArr", '\u21D2');
255                         entities.Add ("dArr", '\u21D3');
256                         entities.Add ("hArr", '\u21D4');
257                         entities.Add ("forall", '\u2200');
258                         entities.Add ("part", '\u2202');
259                         entities.Add ("exist", '\u2203');
260                         entities.Add ("empty", '\u2205');
261                         entities.Add ("nabla", '\u2207');
262                         entities.Add ("isin", '\u2208');
263                         entities.Add ("notin", '\u2209');
264                         entities.Add ("ni", '\u220B');
265                         entities.Add ("prod", '\u220F');
266                         entities.Add ("sum", '\u2211');
267                         entities.Add ("minus", '\u2212');
268                         entities.Add ("lowast", '\u2217');
269                         entities.Add ("radic", '\u221A');
270                         entities.Add ("prop", '\u221D');
271                         entities.Add ("infin", '\u221E');
272                         entities.Add ("ang", '\u2220');
273                         entities.Add ("and", '\u2227');
274                         entities.Add ("or", '\u2228');
275                         entities.Add ("cap", '\u2229');
276                         entities.Add ("cup", '\u222A');
277                         entities.Add ("int", '\u222B');
278                         entities.Add ("there4", '\u2234');
279                         entities.Add ("sim", '\u223C');
280                         entities.Add ("cong", '\u2245');
281                         entities.Add ("asymp", '\u2248');
282                         entities.Add ("ne", '\u2260');
283                         entities.Add ("equiv", '\u2261');
284                         entities.Add ("le", '\u2264');
285                         entities.Add ("ge", '\u2265');
286                         entities.Add ("sub", '\u2282');
287                         entities.Add ("sup", '\u2283');
288                         entities.Add ("nsub", '\u2284');
289                         entities.Add ("sube", '\u2286');
290                         entities.Add ("supe", '\u2287');
291                         entities.Add ("oplus", '\u2295');
292                         entities.Add ("otimes", '\u2297');
293                         entities.Add ("perp", '\u22A5');
294                         entities.Add ("sdot", '\u22C5');
295                         entities.Add ("lceil", '\u2308');
296                         entities.Add ("rceil", '\u2309');
297                         entities.Add ("lfloor", '\u230A');
298                         entities.Add ("rfloor", '\u230B');
299                         entities.Add ("lang", '\u2329');
300                         entities.Add ("rang", '\u232A');
301                         entities.Add ("loz", '\u25CA');
302                         entities.Add ("spades", '\u2660');
303                         entities.Add ("clubs", '\u2663');
304                         entities.Add ("hearts", '\u2665');
305                         entities.Add ("diams", '\u2666');
306                         entities.Add ("quot", '\u0022');
307                         entities.Add ("amp", '\u0026');
308                         entities.Add ("lt", '\u003C');
309                         entities.Add ("gt", '\u003E');
310                         entities.Add ("OElig", '\u0152');
311                         entities.Add ("oelig", '\u0153');
312                         entities.Add ("Scaron", '\u0160');
313                         entities.Add ("scaron", '\u0161');
314                         entities.Add ("Yuml", '\u0178');
315                         entities.Add ("circ", '\u02C6');
316                         entities.Add ("tilde", '\u02DC');
317                         entities.Add ("ensp", '\u2002');
318                         entities.Add ("emsp", '\u2003');
319                         entities.Add ("thinsp", '\u2009');
320                         entities.Add ("zwnj", '\u200C');
321                         entities.Add ("zwj", '\u200D');
322                         entities.Add ("lrm", '\u200E');
323                         entities.Add ("rlm", '\u200F');
324                         entities.Add ("ndash", '\u2013');
325                         entities.Add ("mdash", '\u2014');
326                         entities.Add ("lsquo", '\u2018');
327                         entities.Add ("rsquo", '\u2019');
328                         entities.Add ("sbquo", '\u201A');
329                         entities.Add ("ldquo", '\u201C');
330                         entities.Add ("rdquo", '\u201D');
331                         entities.Add ("bdquo", '\u201E');
332                         entities.Add ("dagger", '\u2020');
333                         entities.Add ("Dagger", '\u2021');
334                         entities.Add ("permil", '\u2030');
335                         entities.Add ("lsaquo", '\u2039');
336                         entities.Add ("rsaquo", '\u203A');
337                         entities.Add ("euro", '\u20AC');
338                 }
339
340                 public HttpUtility () 
341                 {
342                 }
343         
344                 #endregion // Constructors
345         
346                 #region Methods
347         
348                 public static void HtmlAttributeEncode (string s, TextWriter output) 
349                 {
350                         output.Write(HtmlAttributeEncode(s));
351                 }
352         
353                 public static string HtmlAttributeEncode (string s) 
354                 {
355                         if (null == s) 
356                                 return null;
357         
358                         bool needEncode = false;
359                         for (int i = 0; i < s.Length; i++) {
360                                 if (s [i] == '&' || s [i] == '"' || s [i] == '<') {
361                                         needEncode = true;
362                                         break;
363                                 }
364                         }
365
366                         if (!needEncode)
367                                 return s;
368
369                         StringBuilder output = new StringBuilder ();
370                         int len = s.Length;
371                         for (int i = 0; i < len; i++)
372                                 switch (s [i]) {
373                                 case '&' : 
374                                         output.Append ("&amp;");
375                                         break;
376                                 case '"' :
377                                         output.Append ("&quot;");
378                                         break;
379                                 case '<':
380                                         output.Append ("&lt;");
381                                         break;
382                                 default:
383                                         output.Append (s [i]);
384                                         break;
385                                 }
386         
387                         return output.ToString();
388                 }
389         
390                 public static string UrlDecode (string str) 
391                 {
392                         return UrlDecode(str, Encoding.UTF8);
393                 }
394         
395                 static char [] GetChars (MemoryStream b, Encoding e)
396                 {
397                         return e.GetChars (b.GetBuffer (), 0, (int) b.Length);
398                 }
399
400                 static void WriteCharBytes (IList buf, char ch, Encoding e)
401                 {
402                         if (ch > 255) {
403                                 foreach (byte b in e.GetBytes (new char[] { ch }))
404                                         buf.Add (b);
405                         } else
406                                 buf.Add ((byte)ch);
407                 }
408                 
409                 public static string UrlDecode (string s, Encoding e)
410                 {
411                         if (null == s) 
412                                 return null;
413
414                         if (s.IndexOf ('%') == -1 && s.IndexOf ('+') == -1)
415                                 return s;
416                         
417                         if (e == null)
418                                 e = Encoding.UTF8;
419
420                         long len = s.Length;
421                         var bytes = new List <byte> ();
422                         int xchar;
423                         char ch;
424                         
425                         for (int i = 0; i < len; i++) {
426                                 ch = s [i];
427                                 if (ch == '%' && i + 2 < len && s [i + 1] != '%') {
428                                         if (s [i + 1] == 'u' && i + 5 < len) {
429                                                 // unicode hex sequence
430                                                 xchar = GetChar (s, i + 2, 4);
431                                                 if (xchar != -1) {
432                                                         WriteCharBytes (bytes, (char)xchar, e);
433                                                         i += 5;
434                                                 } else
435                                                         WriteCharBytes (bytes, '%', e);
436                                         } else if ((xchar = GetChar (s, i + 1, 2)) != -1) {
437                                                 WriteCharBytes (bytes, (char)xchar, e);
438                                                 i += 2;
439                                         } else {
440                                                 WriteCharBytes (bytes, '%', e);
441                                         }
442                                         continue;
443                                 }
444
445                                 if (ch == '+')
446                                         WriteCharBytes (bytes, ' ', e);
447                                 else
448                                         WriteCharBytes (bytes, ch, e);
449                         }
450                         
451                         byte[] buf = bytes.ToArray ();
452                         bytes = null;
453                         return e.GetString (buf);
454                         
455                 }
456         
457                 public static string UrlDecode (byte [] bytes, Encoding e)
458                 {
459                         if (bytes == null)
460                                 return null;
461
462                         return UrlDecode (bytes, 0, bytes.Length, e);
463                 }
464
465                 static int GetInt (byte b)
466                 {
467                         char c = (char) b;
468                         if (c >= '0' && c <= '9')
469                                 return c - '0';
470
471                         if (c >= 'a' && c <= 'f')
472                                 return c - 'a' + 10;
473
474                         if (c >= 'A' && c <= 'F')
475                                 return c - 'A' + 10;
476
477                         return -1;
478                 }
479
480                 static int GetChar (byte [] bytes, int offset, int length)
481                 {
482                         int value = 0;
483                         int end = length + offset;
484                         for (int i = offset; i < end; i++) {
485                                 int current = GetInt (bytes [i]);
486                                 if (current == -1)
487                                         return -1;
488                                 value = (value << 4) + current;
489                         }
490
491                         return value;
492                 }
493
494                 static int GetChar (string str, int offset, int length)
495                 {
496                         int val = 0;
497                         int end = length + offset;
498                         for (int i = offset; i < end; i++) {
499                                 char c = str [i];
500                                 if (c > 127)
501                                         return -1;
502
503                                 int current = GetInt ((byte) c);
504                                 if (current == -1)
505                                         return -1;
506                                 val = (val << 4) + current;
507                         }
508
509                         return val;
510                 }
511                 
512                 public static string UrlDecode (byte [] bytes, int offset, int count, Encoding e)
513                 {
514                         if (bytes == null)
515                                 return null;
516                         if (count == 0)
517                                 return String.Empty;
518
519                         if (bytes == null)
520                                 throw new ArgumentNullException ("bytes");
521
522                         if (offset < 0 || offset > bytes.Length)
523                                 throw new ArgumentOutOfRangeException ("offset");
524
525                         if (count < 0 || offset + count > bytes.Length)
526                                 throw new ArgumentOutOfRangeException ("count");
527
528                         StringBuilder output = new StringBuilder ();
529                         MemoryStream acc = new MemoryStream ();
530
531                         int end = count + offset;
532                         int xchar;
533                         for (int i = offset; i < end; i++) {
534                                 if (bytes [i] == '%' && i + 2 < count && bytes [i + 1] != '%') {
535                                         if (bytes [i + 1] == (byte) 'u' && i + 5 < end) {
536                                                 if (acc.Length > 0) {
537                                                         output.Append (GetChars (acc, e));
538                                                         acc.SetLength (0);
539                                                 }
540                                                 xchar = GetChar (bytes, i + 2, 4);
541                                                 if (xchar != -1) {
542                                                         output.Append ((char) xchar);
543                                                         i += 5;
544                                                         continue;
545                                                 }
546                                         } else if ((xchar = GetChar (bytes, i + 1, 2)) != -1) {
547                                                 acc.WriteByte ((byte) xchar);
548                                                 i += 2;
549                                                 continue;
550                                         }
551                                 }
552
553                                 if (acc.Length > 0) {
554                                         output.Append (GetChars (acc, e));
555                                         acc.SetLength (0);
556                                 }
557
558                                 if (bytes [i] == '+') {
559                                         output.Append (' ');
560                                 } else {
561                                         output.Append ((char) bytes [i]);
562                                 }
563                         }
564
565                         if (acc.Length > 0) {
566                                 output.Append (GetChars (acc, e));
567                         }
568                         
569                         acc = null;
570                         return output.ToString ();
571                 }
572         
573                 public static byte [] UrlDecodeToBytes (byte [] bytes)
574                 {
575                         if (bytes == null)
576                                 return null;
577
578                         return UrlDecodeToBytes (bytes, 0, bytes.Length);
579                 }
580
581                 public static byte [] UrlDecodeToBytes (string str)
582                 {
583                         return UrlDecodeToBytes (str, Encoding.UTF8);
584                 }
585
586                 public static byte [] UrlDecodeToBytes (string str, Encoding e)
587                 {
588                         if (str == null)
589                                 return null;
590
591                         if (e == null)
592                                 throw new ArgumentNullException ("e");
593
594                         return UrlDecodeToBytes (e.GetBytes (str));
595                 }
596
597                 public static byte [] UrlDecodeToBytes (byte [] bytes, int offset, int count)
598                 {
599                         if (bytes == null)
600                                 return null;
601                         if (count == 0)
602                                 return new byte [0];
603
604                         int len = bytes.Length;
605                         if (offset < 0 || offset >= len)
606                                 throw new ArgumentOutOfRangeException("offset");
607
608                         if (count < 0 || offset > len - count)
609                                 throw new ArgumentOutOfRangeException("count");
610
611                         MemoryStream result = new MemoryStream ();
612                         int end = offset + count;
613                         for (int i = offset; i < end; i++){
614                                 char c = (char) bytes [i];
615                                 if (c == '+') {
616                                         c = ' ';
617                                 } else if (c == '%' && i < end - 2) {
618                                         int xchar = GetChar (bytes, i + 1, 2);
619                                         if (xchar != -1) {
620                                                 c = (char) xchar;
621                                                 i += 2;
622                                         }
623                                 }
624                                 result.WriteByte ((byte) c);
625                         }
626
627                         return result.ToArray ();
628                 }
629
630                 public static string UrlEncode(string str) 
631                 {
632                         return UrlEncode(str, Encoding.UTF8);
633                 }
634         
635                 public static string UrlEncode (string s, Encoding Enc) 
636                 {
637                         if (s == null)
638                                 return null;
639
640                         if (s == "")
641                                 return "";
642
643                         bool needEncode = false;
644                         int len = s.Length;
645                         for (int i = 0; i < len; i++) {
646                                 char c = s [i];
647                                 if ((c < '0') || (c < 'A' && c > '9') || (c > 'Z' && c < 'a') || (c > 'z')) {
648                                         if (NotEncoded (c))
649                                                 continue;
650
651                                         needEncode = true;
652                                         break;
653                                 }
654                         }
655
656                         if (!needEncode)
657                                 return s;
658
659                         // avoided GetByteCount call
660                         byte [] bytes = new byte[Enc.GetMaxByteCount(s.Length)];
661                         int realLen = Enc.GetBytes (s, 0, s.Length, bytes, 0);
662                         return Encoding.ASCII.GetString (UrlEncodeToBytes (bytes, 0, realLen));
663                 }
664           
665                 public static string UrlEncode (byte [] bytes)
666                 {
667                         if (bytes == null)
668                                 return null;
669
670                         if (bytes.Length == 0)
671                                 return "";
672
673                         return Encoding.ASCII.GetString (UrlEncodeToBytes (bytes, 0, bytes.Length));
674                 }
675
676                 public static string UrlEncode (byte [] bytes, int offset, int count)
677                 {
678                         if (bytes == null)
679                                 return null;
680
681                         if (bytes.Length == 0)
682                                 return "";
683
684                         return Encoding.ASCII.GetString (UrlEncodeToBytes (bytes, offset, count));
685                 }
686
687                 public static byte [] UrlEncodeToBytes (string str)
688                 {
689                         return UrlEncodeToBytes (str, Encoding.UTF8);
690                 }
691
692                 public static byte [] UrlEncodeToBytes (string str, Encoding e)
693                 {
694                         if (str == null)
695                                 return null;
696
697                         if (str == "")
698                                 return new byte [0];
699
700                         byte [] bytes = e.GetBytes (str);
701                         return UrlEncodeToBytes (bytes, 0, bytes.Length);
702                 }
703
704                 public static byte [] UrlEncodeToBytes (byte [] bytes)
705                 {
706                         if (bytes == null)
707                                 return null;
708
709                         if (bytes.Length == 0)
710                                 return new byte [0];
711
712                         return UrlEncodeToBytes (bytes, 0, bytes.Length);
713                 }
714
715                 static char [] hexChars = "0123456789abcdef".ToCharArray ();
716
717                 static bool NotEncoded (char c)
718                 {
719                         return (c == '!' || c == '\'' || c == '(' || c == ')' || c == '*' || c == '-' || c == '.' || c == '_');
720                 }
721
722                 static void UrlEncodeChar (char c, Stream result, bool isUnicode) {
723                         if (c > 255) {
724                                 //FIXME: what happens when there is an internal error?
725                                 //if (!isUnicode)
726                                 //      throw new ArgumentOutOfRangeException ("c", c, "c must be less than 256");
727                                 int idx;
728                                 int i = (int) c;
729
730                                 result.WriteByte ((byte)'%');
731                                 result.WriteByte ((byte)'u');
732                                 idx = i >> 12;
733                                 result.WriteByte ((byte)hexChars [idx]);
734                                 idx = (i >> 8) & 0x0F;
735                                 result.WriteByte ((byte)hexChars [idx]);
736                                 idx = (i >> 4) & 0x0F;
737                                 result.WriteByte ((byte)hexChars [idx]);
738                                 idx = i & 0x0F;
739                                 result.WriteByte ((byte)hexChars [idx]);
740                                 return;
741                         }
742                         
743                         if (c > ' ' && NotEncoded (c)) {
744                                 result.WriteByte ((byte)c);
745                                 return;
746                         }
747                         if (c==' ') {
748                                 result.WriteByte ((byte)'+');
749                                 return;
750                         }
751                         if (    (c < '0') ||
752                                 (c < 'A' && c > '9') ||
753                                 (c > 'Z' && c < 'a') ||
754                                 (c > 'z')) {
755                                 if (isUnicode && c > 127) {
756                                         result.WriteByte ((byte)'%');
757                                         result.WriteByte ((byte)'u');
758                                         result.WriteByte ((byte)'0');
759                                         result.WriteByte ((byte)'0');
760                                 }
761                                 else
762                                         result.WriteByte ((byte)'%');
763                                 
764                                 int idx = ((int) c) >> 4;
765                                 result.WriteByte ((byte)hexChars [idx]);
766                                 idx = ((int) c) & 0x0F;
767                                 result.WriteByte ((byte)hexChars [idx]);
768                         }
769                         else
770                                 result.WriteByte ((byte)c);
771                 }
772
773                 public static byte [] UrlEncodeToBytes (byte [] bytes, int offset, int count)
774                 {
775                         if (bytes == null)
776                                 return null;
777
778                         int len = bytes.Length;
779                         if (len == 0)
780                                 return new byte [0];
781
782                         if (offset < 0 || offset >= len)
783                                 throw new ArgumentOutOfRangeException("offset");
784
785                         if (count < 0 || count > len - offset)
786                                 throw new ArgumentOutOfRangeException("count");
787
788                         MemoryStream result = new MemoryStream (count);
789                         int end = offset + count;
790                         for (int i = offset; i < end; i++)
791                                 UrlEncodeChar ((char)bytes [i], result, false);
792
793                         return result.ToArray();
794                 }
795
796                 public static string UrlEncodeUnicode (string str)
797                 {
798                         if (str == null)
799                                 return null;
800
801                         return Encoding.ASCII.GetString (UrlEncodeUnicodeToBytes (str));
802                 }
803
804                 public static byte [] UrlEncodeUnicodeToBytes (string str)
805                 {
806                         if (str == null)
807                                 return null;
808
809                         if (str == "")
810                                 return new byte [0];
811
812                         MemoryStream result = new MemoryStream (str.Length);
813                         foreach (char c in str){
814                                 UrlEncodeChar (c, result, true);
815                         }
816                         return result.ToArray ();
817                 }
818
819                 /// <summary>
820                 /// Decodes an HTML-encoded string and returns the decoded string.
821                 /// </summary>
822                 /// <param name="s">The HTML string to decode. </param>
823                 /// <returns>The decoded text.</returns>
824                 public static string HtmlDecode (string s) 
825                 {
826                         if (s == null)
827                                 throw new ArgumentNullException ("s");
828
829                         if (s.IndexOf ('&') == -1)
830                                 return s;
831
832                         StringBuilder entity = new StringBuilder ();
833                         StringBuilder output = new StringBuilder ();
834                         int len = s.Length;
835                         // 0 -> nothing,
836                         // 1 -> right after '&'
837                         // 2 -> between '&' and ';' but no '#'
838                         // 3 -> '#' found after '&' and getting numbers
839                         int state = 0;
840                         int number = 0;
841                         bool have_trailing_digits = false;
842         
843                         for (int i = 0; i < len; i++) {
844                                 char c = s [i];
845                                 if (state == 0) {
846                                         if (c == '&') {
847                                                 entity.Append (c);
848                                                 state = 1;
849                                         } else {
850                                                 output.Append (c);
851                                         }
852                                         continue;
853                                 }
854
855                                 if (c == '&') {
856                                         state = 1;
857                                         if (have_trailing_digits) {
858                                                 entity.Append (number.ToString (CultureInfo.InvariantCulture));
859                                                 have_trailing_digits = false;
860                                         }
861
862                                         output.Append (entity.ToString ());
863                                         entity.Length = 0;
864                                         entity.Append ('&');
865                                         continue;
866                                 }
867
868                                 if (state == 1) {
869                                         if (c == ';') {
870                                                 state = 0;
871                                                 output.Append (entity.ToString ());
872                                                 output.Append (c);
873                                                 entity.Length = 0;
874                                         } else {
875                                                 number = 0;
876                                                 if (c != '#') {
877                                                         state = 2;
878                                                 } else {
879                                                         state = 3;
880                                                 }
881                                                 entity.Append (c);
882                                         }
883                                 } else if (state == 2) {
884                                         entity.Append (c);
885                                         if (c == ';') {
886                                                 string key = entity.ToString ();
887                                                 if (key.Length > 1 && Entities.ContainsKey (key.Substring (1, key.Length - 2)))
888                                                         key = Entities [key.Substring (1, key.Length - 2)].ToString ();
889
890                                                 output.Append (key);
891                                                 state = 0;
892                                                 entity.Length = 0;
893                                         }
894                                 } else if (state == 3) {
895                                         if (c == ';') {
896                                                 if (number > 65535) {
897                                                         output.Append ("&#");
898                                                         output.Append (number.ToString (CultureInfo.InvariantCulture));
899                                                         output.Append (";");
900                                                 } else {
901                                                         output.Append ((char) number);
902                                                 }
903                                                 state = 0;
904                                                 entity.Length = 0;
905                                                 have_trailing_digits = false;
906                                         } else if (Char.IsDigit (c)) {
907                                                 number = number * 10 + ((int) c - '0');
908                                                 have_trailing_digits = true;
909                                         } else {
910                                                 state = 2;
911                                                 if (have_trailing_digits) {
912                                                         entity.Append (number.ToString (CultureInfo.InvariantCulture));
913                                                         have_trailing_digits = false;
914                                                 }
915                                                 entity.Append (c);
916                                         }
917                                 }
918                         }
919
920                         if (entity.Length > 0) {
921                                 output.Append (entity.ToString ());
922                         } else if (have_trailing_digits) {
923                                 output.Append (number.ToString (CultureInfo.InvariantCulture));
924                         }
925                         return output.ToString ();
926                 }
927         
928                 /// <summary>
929                 /// Decodes an HTML-encoded string and sends the resulting output to a TextWriter output stream.
930                 /// </summary>
931                 /// <param name="s">The HTML string to decode</param>
932                 /// <param name="output">The TextWriter output stream containing the decoded string. </param>
933                 public static void HtmlDecode(string s, TextWriter output) 
934                 {
935                         if (s != null)
936                                 output.Write (HtmlDecode (s));
937                 }
938         
939                 /// <summary>
940                 /// HTML-encodes a string and returns the encoded string.
941                 /// </summary>
942                 /// <param name="s">The text string to encode. </param>
943                 /// <returns>The HTML-encoded text.</returns>
944                 public static string HtmlEncode (string s) 
945                 {
946                         if (s == null)
947                                 return null;
948
949                         bool needEncode = false;
950                         for (int i = 0; i < s.Length; i++) {
951                                 char c = s [i];
952                                 if (c == '&' || c == '"' || c == '<' || c == '>' || c > 159) {
953                                         needEncode = true;
954                                         break;
955                                 }
956                         }
957
958                         if (!needEncode)
959                                 return s;
960
961                         StringBuilder output = new StringBuilder ();
962                         
963                         int len = s.Length;
964                         for (int i = 0; i < len; i++) 
965                                 switch (s [i]) {
966                                 case '&' :
967                                         output.Append ("&amp;");
968                                         break;
969                                 case '>' : 
970                                         output.Append ("&gt;");
971                                         break;
972                                 case '<' :
973                                         output.Append ("&lt;");
974                                         break;
975                                 case '"' :
976                                         output.Append ("&quot;");
977                                         break;
978                                 default:
979                                         // MS starts encoding with &# from 160 and stops at 255.
980                                         // We don't do that. One reason is the 65308/65310 unicode
981                                         // characters that look like '<' and '>'.
982 #if TARGET_JVM
983                                         if (s [i] > 159 && s [i] < 256) {
984 #else
985                                         if (s [i] > 159) {
986 #endif
987                                                 output.Append ("&#");
988                                                 output.Append (((int) s [i]).ToString (CultureInfo.InvariantCulture));
989                                                 output.Append (";");
990                                         } else {
991                                                 output.Append (s [i]);
992                                         }
993                                         break;
994                                 }
995                         return output.ToString ();
996                 }
997         
998                 /// <summary>
999                 /// HTML-encodes a string and sends the resulting output to a TextWriter output stream.
1000                 /// </summary>
1001                 /// <param name="s">The string to encode. </param>
1002                 /// <param name="output">The TextWriter output stream containing the encoded string. </param>
1003                 public static void HtmlEncode(string s, TextWriter output) 
1004                 {
1005                         if (s != null)
1006                                 output.Write (HtmlEncode (s));
1007                 }
1008
1009                 public static string UrlPathEncode (string s)
1010                 {
1011                         if (s == null || s.Length == 0)
1012                                 return s;
1013
1014                         MemoryStream result = new MemoryStream ();
1015                         int length = s.Length;
1016                         for (int i = 0; i < length; i++) {
1017                                 UrlPathEncodeChar (s [i], result);
1018                         }
1019                         return Encoding.ASCII.GetString (result.ToArray ());
1020                 }
1021                 
1022                 static void UrlPathEncodeChar (char c, Stream result)
1023                 {
1024                         if (c < 33 || c > 126) {
1025                                 byte [] bIn = Encoding.UTF8.GetBytes (c.ToString ());
1026                                 for (int i = 0; i < bIn.Length; i++) {
1027                                         result.WriteByte ((byte) '%');
1028                                         int idx = ((int) bIn [i]) >> 4;
1029                                         result.WriteByte ((byte) hexChars [idx]);
1030                                         idx = ((int) bIn [i]) & 0x0F;
1031                                         result.WriteByte ((byte) hexChars [idx]);
1032                                 }
1033                         }
1034                         else if (c == ' ') {
1035                                 result.WriteByte ((byte) '%');
1036                                 result.WriteByte ((byte) '2');
1037                                 result.WriteByte ((byte) '0');
1038                         }
1039                         else
1040                                 result.WriteByte ((byte) c);
1041                 }
1042
1043                 public static NameValueCollection ParseQueryString (string query)
1044                 {
1045                         return ParseQueryString (query, Encoding.UTF8);
1046                 }
1047
1048                 public static NameValueCollection ParseQueryString (string query, Encoding encoding)
1049                 {
1050                         if (query == null)
1051                                 throw new ArgumentNullException ("query");
1052                         if (encoding == null)
1053                                 throw new ArgumentNullException ("encoding");
1054                         if (query.Length == 0 || (query.Length == 1 && query[0] == '?'))
1055                                 return new NameValueCollection ();
1056                         if (query[0] == '?')
1057                                 query = query.Substring (1);
1058                                 
1059                         NameValueCollection result = new HttpQSCollection ();
1060                         ParseQueryString (query, encoding, result);
1061                         return result;
1062                 }
1063
1064                 internal static void ParseQueryString (string query, Encoding encoding, NameValueCollection result)
1065                 {
1066                         if (query.Length == 0)
1067                                 return;
1068
1069                         string decoded = HtmlDecode (query);
1070                         int decodedLength = decoded.Length;
1071                         int namePos = 0;
1072                         bool first = true;
1073                         while (namePos <= decodedLength) {
1074                                 int valuePos = -1, valueEnd = -1;
1075                                 for (int q = namePos; q < decodedLength; q++) {
1076                                         if (valuePos == -1 && decoded [q] == '=') {
1077                                                 valuePos = q + 1;
1078                                         } else if (decoded [q] == '&') {
1079                                                 valueEnd = q;
1080                                                 break;
1081                                         }
1082                                 }
1083
1084                                 if (first) {
1085                                         first = false;
1086                                         if (decoded [namePos] == '?')
1087                                                 namePos++;
1088                                 }
1089                                 
1090                                 string name, value;
1091                                 if (valuePos == -1) {
1092                                         name = null;
1093                                         valuePos = namePos;
1094                                 } else {
1095                                         name = UrlDecode (decoded.Substring (namePos, valuePos - namePos - 1), encoding);
1096                                 }
1097                                 if (valueEnd < 0) {
1098                                         namePos = -1;
1099                                         valueEnd = decoded.Length;
1100                                 } else {
1101                                         namePos = valueEnd + 1;
1102                                 }
1103                                 value = UrlDecode (decoded.Substring (valuePos, valueEnd - valuePos), encoding);
1104
1105                                 result.Add (name, value);
1106                                 if (namePos == -1)
1107                                         break;
1108                         }
1109                 }
1110                 #endregion // Methods
1111         }
1112 }
1113