HttpUtility.cs 29 KB

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