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