UrlEncoded.d 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. module http.UrlEncoded;
  2. import hunt.collection.List;
  3. import hunt.collection.MultiMap;
  4. import hunt.collection.StringBuffer;
  5. import hunt.Exceptions;
  6. import hunt.logging;
  7. import hunt.text.Charset;
  8. import hunt.text.Common;
  9. import hunt.text.StringBuilder;
  10. import hunt.util.TypeUtils;
  11. import std.conv;
  12. import std.array;
  13. /**
  14. * Handles coding of MIME "x-www-form-urlencoded".
  15. * <p>
  16. * This class handles the encoding and decoding for either the query string of a
  17. * URL or the _content of a POST HTTP request.
  18. * </p>
  19. * <b>Notes</b>
  20. * <p>
  21. * The UTF-8 charset is assumed, unless otherwise defined by either passing a
  22. * parameter or setting the "org.hunt.utils.UrlEncoding.charset" System
  23. * property.
  24. * </p>
  25. * <p>
  26. * The hashtable either contains string single values, vectors of string or
  27. * arrays of Strings.
  28. * </p>
  29. * <p>
  30. * This class is only partially synchronised. In particular, simple get
  31. * operations are not protected from concurrent updates.
  32. * </p>
  33. *
  34. * @see java.net.URLEncoder
  35. */
  36. class UrlEncoded : MultiMap!string {
  37. enum string ENCODING = StandardCharsets.UTF_8;
  38. this() {
  39. }
  40. this(string query) {
  41. decodeTo(query, this, ENCODING);
  42. }
  43. void decode(string query) {
  44. decodeTo(query, this, ENCODING);
  45. }
  46. void decode(string query, string charset) {
  47. decodeTo(query, this, charset);
  48. }
  49. /**
  50. * Encode MultiMap with % encoding for UTF8 sequences.
  51. *
  52. * @return the MultiMap as a string with % encoding
  53. */
  54. string encode() {
  55. return encode(ENCODING, false);
  56. }
  57. /**
  58. * Encode MultiMap with % encoding for arbitrary string sequences.
  59. *
  60. * @param charset the charset to use for encoding
  61. * @return the MultiMap as a string encoded with % encodings
  62. */
  63. string encode(string charset) {
  64. return encode(charset, false);
  65. }
  66. /**
  67. * Encode MultiMap with % encoding.
  68. *
  69. * @param charset the charset to encode with
  70. * @param equalsForNullValue if True, then an '=' is always used, even
  71. * for parameters without a value. e.g. <code>"blah?a=&amp;b=&amp;c="</code>.
  72. * @return the MultiMap as a string encoded with % encodings
  73. */
  74. string encode(string charset, bool equalsForNullValue) {
  75. return encode(this, charset, equalsForNullValue);
  76. }
  77. /**
  78. * Encode MultiMap with % encoding.
  79. *
  80. * @param map the map to encode
  81. * @param charset the charset to use for encoding (uses default encoding if null)
  82. * @param equalsForNullValue if True, then an '=' is always used, even
  83. * for parameters without a value. e.g. <code>"blah?a=&amp;b=&amp;c="</code>.
  84. * @return the MultiMap as a string encoded with % encodings.
  85. */
  86. static string encode(MultiMap!string map, string charset, bool equalsForNullValue) {
  87. if (charset is null)
  88. charset = ENCODING;
  89. StringBuilder result = new StringBuilder(128);
  90. bool delim = false;
  91. foreach(string key, List!string list; map)
  92. {
  93. int s = list.size();
  94. if (delim) {
  95. result.append('&');
  96. }
  97. if (s == 0) {
  98. result.append(encodeString(key, charset));
  99. if (equalsForNullValue)
  100. result.append('=');
  101. } else {
  102. for (int i = 0; i < s; i++) {
  103. if (i > 0)
  104. result.append('&');
  105. string val = list.get(i);
  106. result.append(encodeString(key, charset));
  107. if (val != null) {
  108. if (val.length > 0) {
  109. result.append('=');
  110. result.append(encodeString(val, charset));
  111. } else if (equalsForNullValue)
  112. result.append('=');
  113. } else if (equalsForNullValue)
  114. result.append('=');
  115. }
  116. }
  117. delim = true;
  118. }
  119. return result.toString();
  120. }
  121. /**
  122. * Decoded parameters to Map.
  123. *
  124. * @param content the string containing the encoded parameters
  125. * @param map the MultiMap to put parsed query parameters into
  126. * @param charset the charset to use for decoding
  127. */
  128. static void decodeTo(string content, MultiMap!string map, string charset = ENCODING) {
  129. if (charset.empty)
  130. charset = ENCODING;
  131. synchronized (map) {
  132. string key = null;
  133. string value = null;
  134. int mark = -1;
  135. bool encoded = false;
  136. for (int i = 0; i < content.length; i++) {
  137. char c = content[i];
  138. switch (c) {
  139. case '&':
  140. int l = i - mark - 1;
  141. value = l == 0 ? "" :
  142. (encoded ? decodeString(content, mark + 1, l) : content.substring(mark + 1, i));
  143. mark = i;
  144. encoded = false;
  145. if (key != null) {
  146. map.add(key, value);
  147. } else if (value != null && value.length > 0) {
  148. map.add(value, "");
  149. }
  150. key = null;
  151. value = null;
  152. break;
  153. case '=':
  154. if (key != null)
  155. break;
  156. key = encoded ? decodeString(content, mark + 1, i - mark - 1) : content.substring(mark + 1, i);
  157. mark = i;
  158. encoded = false;
  159. break;
  160. case '+':
  161. encoded = true;
  162. break;
  163. case '%':
  164. encoded = true;
  165. break;
  166. default: break;
  167. }
  168. }
  169. int contentLen = cast(int)content.length;
  170. if (key != null) {
  171. int l = contentLen - mark - 1;
  172. value = l == 0 ? "" : (encoded ? decodeString(content, mark + 1, l) : content.substring(mark + 1));
  173. version(HUNT_DEBUG) tracef("key=%s, value=%s", key, value);
  174. map.add(key, value);
  175. } else if (mark < contentLen) {
  176. version(HUNT_DEBUG) tracef("empty value: content=%s, key=%s", content, key);
  177. key = encoded
  178. ? decodeString(content, mark + 1, contentLen - mark - 1, charset)
  179. : content.substring(mark + 1);
  180. if (!key.empty) {
  181. map.add(key, "");
  182. }
  183. } else {
  184. warningf("No key found.");
  185. }
  186. }
  187. }
  188. /**
  189. * Decode string with % encoding.
  190. * This method makes the assumption that the majority of calls
  191. * will need no decoding.
  192. *
  193. * @param encoded the encoded string to decode
  194. * @return the decoded string
  195. */
  196. static string decodeString(string encoded) {
  197. return decodeString(encoded, 0, cast(int)encoded.length);
  198. }
  199. /**
  200. * Decode string with % encoding.
  201. * This method makes the assumption that the majority of calls
  202. * will need no decoding.
  203. *
  204. * @param encoded the encoded string to decode
  205. * @param offset the offset in the encoded string to decode from
  206. * @param length the length of characters in the encoded string to decode
  207. * @param charset the charset to use for decoding
  208. * @return the decoded string
  209. */
  210. static string decodeString(string encoded, int offset, int length, string charset = ENCODING) {
  211. StringBuffer buffer = null;
  212. for (int i = 0; i < length; i++) {
  213. char c = encoded.charAt(offset + i);
  214. if (c < 0 || c > 0xff) {
  215. if (buffer is null) {
  216. buffer = new StringBuffer(length);
  217. buffer.append(encoded, offset, offset + i + 1);
  218. } else
  219. buffer.append(c);
  220. } else if (c == '+') {
  221. if (buffer is null) {
  222. buffer = new StringBuffer(length);
  223. buffer.append(encoded, offset, offset + i);
  224. }
  225. buffer.append(' ');
  226. } else if (c == '%') {
  227. if (buffer is null) {
  228. buffer = new StringBuffer(length);
  229. buffer.append(encoded, offset, offset + i);
  230. }
  231. byte[] ba = new byte[length];
  232. int n = 0;
  233. while (c >= 0 && c <= 0xff) {
  234. if (c == '%') {
  235. if (i + 2 < length) {
  236. int o = offset + i + 1;
  237. i += 3;
  238. ba[n] = cast(byte) TypeUtils.parseInt(encoded, o, 2, 16);
  239. n++;
  240. } else {
  241. ba[n++] = cast(byte) '?';
  242. i = length;
  243. }
  244. } else if (c == '+') {
  245. ba[n++] = cast(byte) ' ';
  246. i++;
  247. } else {
  248. ba[n++] = cast(byte) c;
  249. i++;
  250. }
  251. if (i >= length)
  252. break;
  253. c = encoded.charAt(offset + i);
  254. }
  255. i--;
  256. buffer.append(cast(string)(ba[0 .. n]));
  257. } else if (buffer !is null)
  258. buffer.append(c);
  259. }
  260. if (buffer is null) {
  261. if (offset == 0 && encoded.length == length)
  262. return encoded;
  263. return encoded.substring(offset, offset + length);
  264. }
  265. return buffer.toString();
  266. }
  267. /**
  268. * Perform URL encoding.
  269. *
  270. * @param string the string to encode
  271. * @return encoded string.
  272. */
  273. static string encodeString(string string) {
  274. return encodeString(string, ENCODING);
  275. }
  276. /**
  277. * Perform URL encoding.
  278. *
  279. * @param string the string to encode
  280. * @param charset the charset to use for encoding
  281. * @return encoded string.
  282. */
  283. static string encodeString(string str, string charset) {
  284. if (charset is null)
  285. charset = ENCODING;
  286. byte[] bytes = cast(byte[])str;
  287. // bytes = string.getBytes(charset);
  288. int len = cast(int)bytes.length;
  289. byte[] encoded = new byte[bytes.length * 3];
  290. int n = 0;
  291. bool noEncode = true;
  292. for (int i = 0; i < len; i++) {
  293. byte b = bytes[i];
  294. if (b == ' ') {
  295. noEncode = false;
  296. encoded[n++] = cast(byte) '+';
  297. } else if (b >= 'a' && b <= 'z' ||
  298. b >= 'A' && b <= 'Z' ||
  299. b >= '0' && b <= '9') {
  300. encoded[n++] = b;
  301. } else {
  302. noEncode = false;
  303. encoded[n++] = cast(byte) '%';
  304. byte nibble = cast(byte) ((b & 0xf0) >> 4);
  305. if (nibble >= 10)
  306. encoded[n++] = cast(byte) ('A' + nibble - 10);
  307. else
  308. encoded[n++] = cast(byte) ('0' + nibble);
  309. nibble = cast(byte) (b & 0xf);
  310. if (nibble >= 10)
  311. encoded[n++] = cast(byte) ('A' + nibble - 10);
  312. else
  313. encoded[n++] = cast(byte) ('0' + nibble);
  314. }
  315. }
  316. if (noEncode)
  317. return str;
  318. return cast(string)(encoded[0 .. n]);
  319. }
  320. }