/
HttpUtility.cs
717 lines (603 loc) · 16.4 KB
/
HttpUtility.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
//
// System.Web.HttpUtility
//
// Authors:
// Patrik Torstensson (Patrik.Torstensson@labs2.com)
// Wictor Wilén (decode/encode functions) (wictor@ibizkit.se)
// Tim Coleman (tim@timcoleman.com)
// Gonzalo Paniagua Javier (gonzalo@ximian.com)
//
// Copyright (C) 2005-2010 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.IO;
using System.Security.Permissions;
using System.Text;
using System.Web.Util;
namespace System.Web {
#if !MOBILE
// CAS - no InheritanceDemand here as the class is sealed
[AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
#endif
public sealed class HttpUtility
{
sealed class HttpQSCollection : NameValueCollection
{
public override string ToString ()
{
int count = Count;
if (count == 0)
return "";
StringBuilder sb = new StringBuilder ();
string [] keys = AllKeys;
for (int i = 0; i < count; i++) {
sb.AppendFormat ("{0}={1}&", keys [i], this [keys [i]]);
}
if (sb.Length > 0)
sb.Length--;
return sb.ToString ();
}
}
#region Constructors
public HttpUtility ()
{
}
#endregion // Constructors
#region Methods
public static void HtmlAttributeEncode (string s, TextWriter output)
{
if (output == null) {
#if NET_4_0
throw new ArgumentNullException ("output");
#else
throw new NullReferenceException (".NET emulation");
#endif
}
#if NET_4_0
HttpEncoder.Current.HtmlAttributeEncode (s, output);
#else
output.Write (HttpEncoder.HtmlAttributeEncode (s));
#endif
}
public static string HtmlAttributeEncode (string s)
{
#if NET_4_0
if (s == null)
return null;
using (var sw = new StringWriter ()) {
HttpEncoder.Current.HtmlAttributeEncode (s, sw);
return sw.ToString ();
}
#else
return HttpEncoder.HtmlAttributeEncode (s);
#endif
}
public static string UrlDecode (string str)
{
return UrlDecode(str, Encoding.UTF8);
}
static char [] GetChars (MemoryStream b, Encoding e)
{
return e.GetChars (b.GetBuffer (), 0, (int) b.Length);
}
static void WriteCharBytes (IList buf, char ch, Encoding e)
{
if (ch > 255) {
foreach (byte b in e.GetBytes (new char[] { ch }))
buf.Add (b);
} else
buf.Add ((byte)ch);
}
public static string UrlDecode (string s, Encoding e)
{
if (null == s)
return null;
if (s.IndexOf ('%') == -1 && s.IndexOf ('+') == -1)
return s;
if (e == null)
e = Encoding.UTF8;
long len = s.Length;
var bytes = new List <byte> ();
int xchar;
char ch;
for (int i = 0; i < len; i++) {
ch = s [i];
if (ch == '%' && i + 2 < len && s [i + 1] != '%') {
if (s [i + 1] == 'u' && i + 5 < len) {
// unicode hex sequence
xchar = GetChar (s, i + 2, 4);
if (xchar != -1) {
WriteCharBytes (bytes, (char)xchar, e);
i += 5;
} else
WriteCharBytes (bytes, '%', e);
} else if ((xchar = GetChar (s, i + 1, 2)) != -1) {
WriteCharBytes (bytes, (char)xchar, e);
i += 2;
} else {
WriteCharBytes (bytes, '%', e);
}
continue;
}
if (ch == '+')
WriteCharBytes (bytes, ' ', e);
else
WriteCharBytes (bytes, ch, e);
}
byte[] buf = bytes.ToArray ();
bytes = null;
return e.GetString (buf);
}
public static string UrlDecode (byte [] bytes, Encoding e)
{
if (bytes == null)
return null;
return UrlDecode (bytes, 0, bytes.Length, e);
}
static int GetInt (byte b)
{
char c = (char) b;
if (c >= '0' && c <= '9')
return c - '0';
if (c >= 'a' && c <= 'f')
return c - 'a' + 10;
if (c >= 'A' && c <= 'F')
return c - 'A' + 10;
return -1;
}
static int GetChar (byte [] bytes, int offset, int length)
{
int value = 0;
int end = length + offset;
for (int i = offset; i < end; i++) {
int current = GetInt (bytes [i]);
if (current == -1)
return -1;
value = (value << 4) + current;
}
return value;
}
static int GetChar (string str, int offset, int length)
{
int val = 0;
int end = length + offset;
for (int i = offset; i < end; i++) {
char c = str [i];
if (c > 127)
return -1;
int current = GetInt ((byte) c);
if (current == -1)
return -1;
val = (val << 4) + current;
}
return val;
}
public static string UrlDecode (byte [] bytes, int offset, int count, Encoding e)
{
if (bytes == null)
return null;
if (count == 0)
return String.Empty;
if (bytes == null)
throw new ArgumentNullException ("bytes");
if (offset < 0 || offset > bytes.Length)
throw new ArgumentOutOfRangeException ("offset");
if (count < 0 || offset + count > bytes.Length)
throw new ArgumentOutOfRangeException ("count");
StringBuilder output = new StringBuilder ();
MemoryStream acc = new MemoryStream ();
int end = count + offset;
int xchar;
for (int i = offset; i < end; i++) {
if (bytes [i] == '%' && i + 2 < count && bytes [i + 1] != '%') {
if (bytes [i + 1] == (byte) 'u' && i + 5 < end) {
if (acc.Length > 0) {
output.Append (GetChars (acc, e));
acc.SetLength (0);
}
xchar = GetChar (bytes, i + 2, 4);
if (xchar != -1) {
output.Append ((char) xchar);
i += 5;
continue;
}
} else if ((xchar = GetChar (bytes, i + 1, 2)) != -1) {
acc.WriteByte ((byte) xchar);
i += 2;
continue;
}
}
if (acc.Length > 0) {
output.Append (GetChars (acc, e));
acc.SetLength (0);
}
if (bytes [i] == '+') {
output.Append (' ');
} else {
output.Append ((char) bytes [i]);
}
}
if (acc.Length > 0) {
output.Append (GetChars (acc, e));
}
acc = null;
return output.ToString ();
}
public static byte [] UrlDecodeToBytes (byte [] bytes)
{
if (bytes == null)
return null;
return UrlDecodeToBytes (bytes, 0, bytes.Length);
}
public static byte [] UrlDecodeToBytes (string str)
{
return UrlDecodeToBytes (str, Encoding.UTF8);
}
public static byte [] UrlDecodeToBytes (string str, Encoding e)
{
if (str == null)
return null;
if (e == null)
throw new ArgumentNullException ("e");
return UrlDecodeToBytes (e.GetBytes (str));
}
public static byte [] UrlDecodeToBytes (byte [] bytes, int offset, int count)
{
if (bytes == null)
return null;
if (count == 0)
return new byte [0];
int len = bytes.Length;
if (offset < 0 || offset >= len)
throw new ArgumentOutOfRangeException("offset");
if (count < 0 || offset > len - count)
throw new ArgumentOutOfRangeException("count");
MemoryStream result = new MemoryStream ();
int end = offset + count;
for (int i = offset; i < end; i++){
char c = (char) bytes [i];
if (c == '+') {
c = ' ';
} else if (c == '%' && i < end - 2) {
int xchar = GetChar (bytes, i + 1, 2);
if (xchar != -1) {
c = (char) xchar;
i += 2;
}
}
result.WriteByte ((byte) c);
}
return result.ToArray ();
}
public static string UrlEncode(string str)
{
return UrlEncode(str, Encoding.UTF8);
}
public static string UrlEncode (string s, Encoding Enc)
{
if (s == null)
return null;
if (s == String.Empty)
return String.Empty;
bool needEncode = false;
int len = s.Length;
for (int i = 0; i < len; i++) {
char c = s [i];
if ((c < '0') || (c < 'A' && c > '9') || (c > 'Z' && c < 'a') || (c > 'z')) {
if (HttpEncoder.NotEncoded (c))
continue;
needEncode = true;
break;
}
}
if (!needEncode)
return s;
// avoided GetByteCount call
byte [] bytes = new byte[Enc.GetMaxByteCount(s.Length)];
int realLen = Enc.GetBytes (s, 0, s.Length, bytes, 0);
return Encoding.ASCII.GetString (UrlEncodeToBytes (bytes, 0, realLen));
}
public static string UrlEncode (byte [] bytes)
{
if (bytes == null)
return null;
if (bytes.Length == 0)
return String.Empty;
return Encoding.ASCII.GetString (UrlEncodeToBytes (bytes, 0, bytes.Length));
}
public static string UrlEncode (byte [] bytes, int offset, int count)
{
if (bytes == null)
return null;
if (bytes.Length == 0)
return String.Empty;
return Encoding.ASCII.GetString (UrlEncodeToBytes (bytes, offset, count));
}
public static byte [] UrlEncodeToBytes (string str)
{
return UrlEncodeToBytes (str, Encoding.UTF8);
}
public static byte [] UrlEncodeToBytes (string str, Encoding e)
{
if (str == null)
return null;
if (str.Length == 0)
return new byte [0];
byte [] bytes = e.GetBytes (str);
return UrlEncodeToBytes (bytes, 0, bytes.Length);
}
public static byte [] UrlEncodeToBytes (byte [] bytes)
{
if (bytes == null)
return null;
if (bytes.Length == 0)
return new byte [0];
return UrlEncodeToBytes (bytes, 0, bytes.Length);
}
public static byte [] UrlEncodeToBytes (byte [] bytes, int offset, int count)
{
if (bytes == null)
return null;
#if NET_4_0
return HttpEncoder.Current.UrlEncode (bytes, offset, count);
#else
return HttpEncoder.UrlEncodeToBytes (bytes, offset, count);
#endif
}
public static string UrlEncodeUnicode (string str)
{
if (str == null)
return null;
return Encoding.ASCII.GetString (UrlEncodeUnicodeToBytes (str));
}
public static byte [] UrlEncodeUnicodeToBytes (string str)
{
if (str == null)
return null;
if (str.Length == 0)
return new byte [0];
MemoryStream result = new MemoryStream (str.Length);
foreach (char c in str){
HttpEncoder.UrlEncodeChar (c, result, true);
}
return result.ToArray ();
}
/// <summary>
/// Decodes an HTML-encoded string and returns the decoded string.
/// </summary>
/// <param name="s">The HTML string to decode. </param>
/// <returns>The decoded text.</returns>
public static string HtmlDecode (string s)
{
#if NET_4_0
if (s == null)
return null;
using (var sw = new StringWriter ()) {
HttpEncoder.Current.HtmlDecode (s, sw);
return sw.ToString ();
}
#else
return HttpEncoder.HtmlDecode (s);
#endif
}
/// <summary>
/// Decodes an HTML-encoded string and sends the resulting output to a TextWriter output stream.
/// </summary>
/// <param name="s">The HTML string to decode</param>
/// <param name="output">The TextWriter output stream containing the decoded string. </param>
public static void HtmlDecode(string s, TextWriter output)
{
if (output == null) {
#if NET_4_0
throw new ArgumentNullException ("output");
#else
throw new NullReferenceException (".NET emulation");
#endif
}
if (!String.IsNullOrEmpty (s)) {
#if NET_4_0
HttpEncoder.Current.HtmlDecode (s, output);
#else
output.Write (HttpEncoder.HtmlDecode (s));
#endif
}
}
public static string HtmlEncode (string s)
{
#if NET_4_0
if (s == null)
return null;
using (var sw = new StringWriter ()) {
HttpEncoder.Current.HtmlEncode (s, sw);
return sw.ToString ();
}
#else
return HttpEncoder.HtmlEncode (s);
#endif
}
/// <summary>
/// HTML-encodes a string and sends the resulting output to a TextWriter output stream.
/// </summary>
/// <param name="s">The string to encode. </param>
/// <param name="output">The TextWriter output stream containing the encoded string. </param>
public static void HtmlEncode(string s, TextWriter output)
{
if (output == null) {
#if NET_4_0
throw new ArgumentNullException ("output");
#else
throw new NullReferenceException (".NET emulation");
#endif
}
if (!String.IsNullOrEmpty (s)) {
#if NET_4_0
HttpEncoder.Current.HtmlEncode (s, output);
#else
output.Write (HttpEncoder.HtmlEncode (s));
#endif
}
}
#if NET_4_0
public static string HtmlEncode (object value)
{
if (value == null)
return null;
#if !MOBILE
IHtmlString htmlString = value as IHtmlString;
if (htmlString != null)
return htmlString.ToHtmlString ();
#endif
return HtmlEncode (value.ToString ());
}
public static string JavaScriptStringEncode (string value)
{
return JavaScriptStringEncode (value, false);
}
public static string JavaScriptStringEncode (string value, bool addDoubleQuotes)
{
if (String.IsNullOrEmpty (value))
return addDoubleQuotes ? "\"\"" : String.Empty;
int len = value.Length;
bool needEncode = false;
char c;
for (int i = 0; i < len; i++) {
c = value [i];
if (c >= 0 && c <= 31 || c == 34 || c == 39 || c == 60 || c == 62 || c == 92) {
needEncode = true;
break;
}
}
if (!needEncode)
return addDoubleQuotes ? "\"" + value + "\"" : value;
var sb = new StringBuilder ();
if (addDoubleQuotes)
sb.Append ('"');
for (int i = 0; i < len; i++) {
c = value [i];
if (c >= 0 && c <= 7 || c == 11 || c >= 14 && c <= 31 || c == 39 || c == 60 || c == 62)
sb.AppendFormat ("\\u{0:x4}", (int)c);
else switch ((int)c) {
case 8:
sb.Append ("\\b");
break;
case 9:
sb.Append ("\\t");
break;
case 10:
sb.Append ("\\n");
break;
case 12:
sb.Append ("\\f");
break;
case 13:
sb.Append ("\\r");
break;
case 34:
sb.Append ("\\\"");
break;
case 92:
sb.Append ("\\\\");
break;
default:
sb.Append (c);
break;
}
}
if (addDoubleQuotes)
sb.Append ('"');
return sb.ToString ();
}
#endif
public static string UrlPathEncode (string s)
{
#if NET_4_0
return HttpEncoder.Current.UrlPathEncode (s);
#else
return HttpEncoder.UrlPathEncode (s);
#endif
}
public static NameValueCollection ParseQueryString (string query)
{
return ParseQueryString (query, Encoding.UTF8);
}
public static NameValueCollection ParseQueryString (string query, Encoding encoding)
{
if (query == null)
throw new ArgumentNullException ("query");
if (encoding == null)
throw new ArgumentNullException ("encoding");
if (query.Length == 0 || (query.Length == 1 && query[0] == '?'))
return new HttpQSCollection ();
if (query[0] == '?')
query = query.Substring (1);
NameValueCollection result = new HttpQSCollection ();
ParseQueryString (query, encoding, result);
return result;
}
internal static void ParseQueryString (string query, Encoding encoding, NameValueCollection result)
{
if (query.Length == 0)
return;
string decoded = HtmlDecode (query);
int decodedLength = decoded.Length;
int namePos = 0;
bool first = true;
while (namePos <= decodedLength) {
int valuePos = -1, valueEnd = -1;
for (int q = namePos; q < decodedLength; q++) {
if (valuePos == -1 && decoded [q] == '=') {
valuePos = q + 1;
} else if (decoded [q] == '&') {
valueEnd = q;
break;
}
}
if (first) {
first = false;
if (decoded [namePos] == '?')
namePos++;
}
string name, value;
if (valuePos == -1) {
name = null;
valuePos = namePos;
} else {
name = UrlDecode (decoded.Substring (namePos, valuePos - namePos - 1), encoding);
}
if (valueEnd < 0) {
namePos = -1;
valueEnd = decoded.Length;
} else {
namePos = valueEnd + 1;
}
value = UrlDecode (decoded.Substring (valuePos, valueEnd - valuePos), encoding);
result.Add (name, value);
if (namePos == -1)
break;
}
}
#endregion // Methods
}
}