HttpUtility.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  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-2010 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. using System.Collections;
  32. using System.Collections.Generic;
  33. using System.Collections.Specialized;
  34. using System.Globalization;
  35. using System.IO;
  36. using System.Security.Permissions;
  37. using System.Text;
  38. using System.Web.Util;
  39. namespace System.Web {
  40. public sealed class HttpUtility
  41. {
  42. sealed class HttpQSCollection : NameValueCollection
  43. {
  44. public override string ToString ()
  45. {
  46. int count = Count;
  47. if (count == 0)
  48. return "";
  49. StringBuilder sb = new StringBuilder ();
  50. string [] keys = AllKeys;
  51. for (int i = 0; i < count; i++) {
  52. sb.AppendFormat ("{0}={1}&", keys [i], this [keys [i]]);
  53. }
  54. if (sb.Length > 0)
  55. sb.Length--;
  56. return sb.ToString ();
  57. }
  58. }
  59. #region Constructors
  60. public HttpUtility ()
  61. {
  62. }
  63. #endregion // Constructors
  64. #region Methods
  65. public static void HtmlAttributeEncode (string s, TextWriter output)
  66. {
  67. if (output == null) {
  68. #if NET_4_0
  69. throw new ArgumentNullException ("output");
  70. #else
  71. throw new NullReferenceException (".NET emulation");
  72. #endif
  73. }
  74. #if NET_4_0
  75. HttpEncoder.Current.HtmlAttributeEncode (s, output);
  76. #else
  77. output.Write (HttpEncoder.HtmlAttributeEncode (s));
  78. #endif
  79. }
  80. public static string HtmlAttributeEncode (string s)
  81. {
  82. #if NET_4_0
  83. if (s == null)
  84. return null;
  85. using (var sw = new StringWriter ()) {
  86. HttpEncoder.Current.HtmlAttributeEncode (s, sw);
  87. return sw.ToString ();
  88. }
  89. #else
  90. return HttpEncoder.HtmlAttributeEncode (s);
  91. #endif
  92. }
  93. public static string UrlDecode (string str)
  94. {
  95. return UrlDecode(str, Encoding.UTF8);
  96. }
  97. static char [] GetChars (MemoryStream b, Encoding e)
  98. {
  99. return e.GetChars (b.GetBuffer (), 0, (int) b.Length);
  100. }
  101. static void WriteCharBytes (IList buf, char ch, Encoding e)
  102. {
  103. if (ch > 255) {
  104. foreach (byte b in e.GetBytes (new char[] { ch }))
  105. buf.Add (b);
  106. } else
  107. buf.Add ((byte)ch);
  108. }
  109. public static string UrlDecode (string s, Encoding e)
  110. {
  111. if (null == s)
  112. return null;
  113. if (s.IndexOf ('%') == -1 && s.IndexOf ('+') == -1)
  114. return s;
  115. if (e == null)
  116. e = Encoding.UTF8;
  117. long len = s.Length;
  118. var bytes = new List <byte> ();
  119. int xchar;
  120. char ch;
  121. for (int i = 0; i < len; i++) {
  122. ch = s [i];
  123. if (ch == '%' && i + 2 < len && s [i + 1] != '%') {
  124. if (s [i + 1] == 'u' && i + 5 < len) {
  125. // unicode hex sequence
  126. xchar = GetChar (s, i + 2, 4);
  127. if (xchar != -1) {
  128. WriteCharBytes (bytes, (char)xchar, e);
  129. i += 5;
  130. } else
  131. WriteCharBytes (bytes, '%', e);
  132. } else if ((xchar = GetChar (s, i + 1, 2)) != -1) {
  133. WriteCharBytes (bytes, (char)xchar, e);
  134. i += 2;
  135. } else {
  136. WriteCharBytes (bytes, '%', e);
  137. }
  138. continue;
  139. }
  140. if (ch == '+')
  141. WriteCharBytes (bytes, ' ', e);
  142. else
  143. WriteCharBytes (bytes, ch, e);
  144. }
  145. byte[] buf = bytes.ToArray ();
  146. bytes = null;
  147. return e.GetString (buf);
  148. }
  149. public static string UrlDecode (byte [] bytes, Encoding e)
  150. {
  151. if (bytes == null)
  152. return null;
  153. return UrlDecode (bytes, 0, bytes.Length, e);
  154. }
  155. static int GetInt (byte b)
  156. {
  157. char c = (char) b;
  158. if (c >= '0' && c <= '9')
  159. return c - '0';
  160. if (c >= 'a' && c <= 'f')
  161. return c - 'a' + 10;
  162. if (c >= 'A' && c <= 'F')
  163. return c - 'A' + 10;
  164. return -1;
  165. }
  166. static int GetChar (byte [] bytes, int offset, int length)
  167. {
  168. int value = 0;
  169. int end = length + offset;
  170. for (int i = offset; i < end; i++) {
  171. int current = GetInt (bytes [i]);
  172. if (current == -1)
  173. return -1;
  174. value = (value << 4) + current;
  175. }
  176. return value;
  177. }
  178. static int GetChar (string str, int offset, int length)
  179. {
  180. int val = 0;
  181. int end = length + offset;
  182. for (int i = offset; i < end; i++) {
  183. char c = str [i];
  184. if (c > 127)
  185. return -1;
  186. int current = GetInt ((byte) c);
  187. if (current == -1)
  188. return -1;
  189. val = (val << 4) + current;
  190. }
  191. return val;
  192. }
  193. public static string UrlDecode (byte [] bytes, int offset, int count, Encoding e)
  194. {
  195. if (bytes == null)
  196. return null;
  197. if (count == 0)
  198. return String.Empty;
  199. if (bytes == null)
  200. throw new ArgumentNullException ("bytes");
  201. if (offset < 0 || offset > bytes.Length)
  202. throw new ArgumentOutOfRangeException ("offset");
  203. if (count < 0 || offset + count > bytes.Length)
  204. throw new ArgumentOutOfRangeException ("count");
  205. StringBuilder output = new StringBuilder ();
  206. MemoryStream acc = new MemoryStream ();
  207. int end = count + offset;
  208. int xchar;
  209. for (int i = offset; i < end; i++) {
  210. if (bytes [i] == '%' && i + 2 < count && bytes [i + 1] != '%') {
  211. if (bytes [i + 1] == (byte) 'u' && i + 5 < end) {
  212. if (acc.Length > 0) {
  213. output.Append (GetChars (acc, e));
  214. acc.SetLength (0);
  215. }
  216. xchar = GetChar (bytes, i + 2, 4);
  217. if (xchar != -1) {
  218. output.Append ((char) xchar);
  219. i += 5;
  220. continue;
  221. }
  222. } else if ((xchar = GetChar (bytes, i + 1, 2)) != -1) {
  223. acc.WriteByte ((byte) xchar);
  224. i += 2;
  225. continue;
  226. }
  227. }
  228. if (acc.Length > 0) {
  229. output.Append (GetChars (acc, e));
  230. acc.SetLength (0);
  231. }
  232. if (bytes [i] == '+') {
  233. output.Append (' ');
  234. } else {
  235. output.Append ((char) bytes [i]);
  236. }
  237. }
  238. if (acc.Length > 0) {
  239. output.Append (GetChars (acc, e));
  240. }
  241. acc = null;
  242. return output.ToString ();
  243. }
  244. public static byte [] UrlDecodeToBytes (byte [] bytes)
  245. {
  246. if (bytes == null)
  247. return null;
  248. return UrlDecodeToBytes (bytes, 0, bytes.Length);
  249. }
  250. public static byte [] UrlDecodeToBytes (string str)
  251. {
  252. return UrlDecodeToBytes (str, Encoding.UTF8);
  253. }
  254. public static byte [] UrlDecodeToBytes (string str, Encoding e)
  255. {
  256. if (str == null)
  257. return null;
  258. if (e == null)
  259. throw new ArgumentNullException ("e");
  260. return UrlDecodeToBytes (e.GetBytes (str));
  261. }
  262. public static byte [] UrlDecodeToBytes (byte [] bytes, int offset, int count)
  263. {
  264. if (bytes == null)
  265. return null;
  266. if (count == 0)
  267. return new byte [0];
  268. int len = bytes.Length;
  269. if (offset < 0 || offset >= len)
  270. throw new ArgumentOutOfRangeException("offset");
  271. if (count < 0 || offset > len - count)
  272. throw new ArgumentOutOfRangeException("count");
  273. MemoryStream result = new MemoryStream ();
  274. int end = offset + count;
  275. for (int i = offset; i < end; i++){
  276. char c = (char) bytes [i];
  277. if (c == '+') {
  278. c = ' ';
  279. } else if (c == '%' && i < end - 2) {
  280. int xchar = GetChar (bytes, i + 1, 2);
  281. if (xchar != -1) {
  282. c = (char) xchar;
  283. i += 2;
  284. }
  285. }
  286. result.WriteByte ((byte) c);
  287. }
  288. return result.ToArray ();
  289. }
  290. public static string UrlEncode(string str)
  291. {
  292. return UrlEncode(str, Encoding.UTF8);
  293. }
  294. public static string UrlEncode (string s, Encoding Enc)
  295. {
  296. if (s == null)
  297. return null;
  298. if (s == String.Empty)
  299. return String.Empty;
  300. bool needEncode = false;
  301. int len = s.Length;
  302. for (int i = 0; i < len; i++) {
  303. char c = s [i];
  304. if ((c < '0') || (c < 'A' && c > '9') || (c > 'Z' && c < 'a') || (c > 'z')) {
  305. if (HttpEncoder.NotEncoded (c))
  306. continue;
  307. needEncode = true;
  308. break;
  309. }
  310. }
  311. if (!needEncode)
  312. return s;
  313. // avoided GetByteCount call
  314. byte [] bytes = new byte[Enc.GetMaxByteCount(s.Length)];
  315. int realLen = Enc.GetBytes (s, 0, s.Length, bytes, 0);
  316. return Encoding.ASCII.GetString (UrlEncodeToBytes (bytes, 0, realLen));
  317. }
  318. public static string UrlEncode (byte [] bytes)
  319. {
  320. if (bytes == null)
  321. return null;
  322. if (bytes.Length == 0)
  323. return String.Empty;
  324. return Encoding.ASCII.GetString (UrlEncodeToBytes (bytes, 0, bytes.Length));
  325. }
  326. public static string UrlEncode (byte [] bytes, int offset, int count)
  327. {
  328. if (bytes == null)
  329. return null;
  330. if (bytes.Length == 0)
  331. return String.Empty;
  332. return Encoding.ASCII.GetString (UrlEncodeToBytes (bytes, offset, count));
  333. }
  334. public static byte [] UrlEncodeToBytes (string str)
  335. {
  336. return UrlEncodeToBytes (str, Encoding.UTF8);
  337. }
  338. public static byte [] UrlEncodeToBytes (string str, Encoding e)
  339. {
  340. if (str == null)
  341. return null;
  342. if (str.Length == 0)
  343. return new byte [0];
  344. byte [] bytes = e.GetBytes (str);
  345. return UrlEncodeToBytes (bytes, 0, bytes.Length);
  346. }
  347. public static byte [] UrlEncodeToBytes (byte [] bytes)
  348. {
  349. if (bytes == null)
  350. return null;
  351. if (bytes.Length == 0)
  352. return new byte [0];
  353. return UrlEncodeToBytes (bytes, 0, bytes.Length);
  354. }
  355. public static byte [] UrlEncodeToBytes (byte [] bytes, int offset, int count)
  356. {
  357. if (bytes == null)
  358. return null;
  359. #if NET_4_0
  360. return HttpEncoder.Current.UrlEncode (bytes, offset, count);
  361. #else
  362. return HttpEncoder.UrlEncodeToBytes (bytes, offset, count);
  363. #endif
  364. }
  365. public static string UrlEncodeUnicode (string str)
  366. {
  367. if (str == null)
  368. return null;
  369. return Encoding.ASCII.GetString (UrlEncodeUnicodeToBytes (str));
  370. }
  371. public static byte [] UrlEncodeUnicodeToBytes (string str)
  372. {
  373. if (str == null)
  374. return null;
  375. if (str.Length == 0)
  376. return new byte [0];
  377. MemoryStream result = new MemoryStream (str.Length);
  378. foreach (char c in str){
  379. HttpEncoder.UrlEncodeChar (c, result, true);
  380. }
  381. return result.ToArray ();
  382. }
  383. /// <summary>
  384. /// Decodes an HTML-encoded string and returns the decoded string.
  385. /// </summary>
  386. /// <param name="s">The HTML string to decode. </param>
  387. /// <returns>The decoded text.</returns>
  388. public static string HtmlDecode (string s)
  389. {
  390. #if NET_4_0
  391. if (s == null)
  392. return null;
  393. using (var sw = new StringWriter ()) {
  394. HttpEncoder.Current.HtmlDecode (s, sw);
  395. return sw.ToString ();
  396. }
  397. #else
  398. return HttpEncoder.HtmlDecode (s);
  399. #endif
  400. }
  401. /// <summary>
  402. /// Decodes an HTML-encoded string and sends the resulting output to a TextWriter output stream.
  403. /// </summary>
  404. /// <param name="s">The HTML string to decode</param>
  405. /// <param name="output">The TextWriter output stream containing the decoded string. </param>
  406. public static void HtmlDecode(string s, TextWriter output)
  407. {
  408. if (output == null) {
  409. #if NET_4_0
  410. throw new ArgumentNullException ("output");
  411. #else
  412. throw new NullReferenceException (".NET emulation");
  413. #endif
  414. }
  415. if (!String.IsNullOrEmpty (s)) {
  416. #if NET_4_0
  417. HttpEncoder.Current.HtmlDecode (s, output);
  418. #else
  419. output.Write (HttpEncoder.HtmlDecode (s));
  420. #endif
  421. }
  422. }
  423. public static string HtmlEncode (string s)
  424. {
  425. #if NET_4_0
  426. if (s == null)
  427. return null;
  428. using (var sw = new StringWriter ()) {
  429. HttpEncoder.Current.HtmlEncode (s, sw);
  430. return sw.ToString ();
  431. }
  432. #else
  433. return HttpEncoder.HtmlEncode (s);
  434. #endif
  435. }
  436. /// <summary>
  437. /// HTML-encodes a string and sends the resulting output to a TextWriter output stream.
  438. /// </summary>
  439. /// <param name="s">The string to encode. </param>
  440. /// <param name="output">The TextWriter output stream containing the encoded string. </param>
  441. public static void HtmlEncode(string s, TextWriter output)
  442. {
  443. if (output == null) {
  444. #if NET_4_0
  445. throw new ArgumentNullException ("output");
  446. #else
  447. throw new NullReferenceException (".NET emulation");
  448. #endif
  449. }
  450. if (!String.IsNullOrEmpty (s)) {
  451. #if NET_4_0
  452. HttpEncoder.Current.HtmlEncode (s, output);
  453. #else
  454. output.Write (HttpEncoder.HtmlEncode (s));
  455. #endif
  456. }
  457. }
  458. #if NET_4_0
  459. public static string HtmlEncode (object value)
  460. {
  461. if (value == null)
  462. return null;
  463. #if !MOBILE
  464. IHtmlString htmlString = value as IHtmlString;
  465. if (htmlString != null)
  466. return htmlString.ToHtmlString ();
  467. #endif
  468. return HtmlEncode (value.ToString ());
  469. }
  470. public static string JavaScriptStringEncode (string value)
  471. {
  472. return JavaScriptStringEncode (value, false);
  473. }
  474. public static string JavaScriptStringEncode (string value, bool addDoubleQuotes)
  475. {
  476. if (String.IsNullOrEmpty (value))
  477. return addDoubleQuotes ? "\"\"" : String.Empty;
  478. int len = value.Length;
  479. bool needEncode = false;
  480. char c;
  481. for (int i = 0; i < len; i++) {
  482. c = value [i];
  483. if (c >= 0 && c <= 31 || c == 34 || c == 39 || c == 60 || c == 62 || c == 92) {
  484. needEncode = true;
  485. break;
  486. }
  487. }
  488. if (!needEncode)
  489. return addDoubleQuotes ? "\"" + value + "\"" : value;
  490. var sb = new StringBuilder ();
  491. if (addDoubleQuotes)
  492. sb.Append ('"');
  493. for (int i = 0; i < len; i++) {
  494. c = value [i];
  495. if (c >= 0 && c <= 7 || c == 11 || c >= 14 && c <= 31 || c == 39 || c == 60 || c == 62)
  496. sb.AppendFormat ("\\u{0:x4}", (int)c);
  497. else switch ((int)c) {
  498. case 8:
  499. sb.Append ("\\b");
  500. break;
  501. case 9:
  502. sb.Append ("\\t");
  503. break;
  504. case 10:
  505. sb.Append ("\\n");
  506. break;
  507. case 12:
  508. sb.Append ("\\f");
  509. break;
  510. case 13:
  511. sb.Append ("\\r");
  512. break;
  513. case 34:
  514. sb.Append ("\\\"");
  515. break;
  516. case 92:
  517. sb.Append ("\\\\");
  518. break;
  519. default:
  520. sb.Append (c);
  521. break;
  522. }
  523. }
  524. if (addDoubleQuotes)
  525. sb.Append ('"');
  526. return sb.ToString ();
  527. }
  528. #endif
  529. public static string UrlPathEncode (string s)
  530. {
  531. #if NET_4_0
  532. return HttpEncoder.Current.UrlPathEncode (s);
  533. #else
  534. return HttpEncoder.UrlPathEncode (s);
  535. #endif
  536. }
  537. public static NameValueCollection ParseQueryString (string query)
  538. {
  539. return ParseQueryString (query, Encoding.UTF8);
  540. }
  541. public static NameValueCollection ParseQueryString (string query, Encoding encoding)
  542. {
  543. if (query == null)
  544. throw new ArgumentNullException ("query");
  545. if (encoding == null)
  546. throw new ArgumentNullException ("encoding");
  547. if (query.Length == 0 || (query.Length == 1 && query[0] == '?'))
  548. return new HttpQSCollection ();
  549. if (query[0] == '?')
  550. query = query.Substring (1);
  551. NameValueCollection result = new HttpQSCollection ();
  552. ParseQueryString (query, encoding, result);
  553. return result;
  554. }
  555. internal static void ParseQueryString (string query, Encoding encoding, NameValueCollection result)
  556. {
  557. if (query.Length == 0)
  558. return;
  559. string decoded = HtmlDecode (query);
  560. int decodedLength = decoded.Length;
  561. int namePos = 0;
  562. bool first = true;
  563. while (namePos <= decodedLength) {
  564. int valuePos = -1, valueEnd = -1;
  565. for (int q = namePos; q < decodedLength; q++) {
  566. if (valuePos == -1 && decoded [q] == '=') {
  567. valuePos = q + 1;
  568. } else if (decoded [q] == '&') {
  569. valueEnd = q;
  570. break;
  571. }
  572. }
  573. if (first) {
  574. first = false;
  575. if (decoded [namePos] == '?')
  576. namePos++;
  577. }
  578. string name, value;
  579. if (valuePos == -1) {
  580. name = null;
  581. valuePos = namePos;
  582. } else {
  583. name = UrlDecode (decoded.Substring (namePos, valuePos - namePos - 1), encoding);
  584. }
  585. if (valueEnd < 0) {
  586. namePos = -1;
  587. valueEnd = decoded.Length;
  588. } else {
  589. namePos = valueEnd + 1;
  590. }
  591. value = UrlDecode (decoded.Substring (valuePos, valueEnd - valuePos), encoding);
  592. result.Add (name, value);
  593. if (namePos == -1)
  594. break;
  595. }
  596. }
  597. #endregion // Methods
  598. }
  599. }