cowboy_http.erl 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081
  1. %% Copyright (c) 2011-2012, Loïc Hoguin <essen@ninenines.eu>
  2. %% Copyright (c) 2011, Anthony Ramine <nox@dev-extend.eu>
  3. %%
  4. %% Permission to use, copy, modify, and/or distribute this software for any
  5. %% purpose with or without fee is hereby granted, provided that the above
  6. %% copyright notice and this permission notice appear in all copies.
  7. %%
  8. %% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  9. %% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  10. %% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  11. %% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  12. %% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  13. %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  14. %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. %% @doc Core HTTP parsing API.
  16. -module(cowboy_http).
  17. %% Parsing.
  18. -export([list/2]).
  19. -export([nonempty_list/2]).
  20. -export([content_type/1]).
  21. -export([media_range/2]).
  22. -export([conneg/2]).
  23. -export([language_range/2]).
  24. -export([entity_tag_match/1]).
  25. -export([expectation/2]).
  26. -export([params/2]).
  27. -export([http_date/1]).
  28. -export([rfc1123_date/1]).
  29. -export([rfc850_date/1]).
  30. -export([asctime_date/1]).
  31. -export([whitespace/2]).
  32. -export([digits/1]).
  33. -export([token/2]).
  34. -export([token_ci/2]).
  35. -export([quoted_string/2]).
  36. %% Decoding.
  37. -export([te_chunked/2]).
  38. -export([te_identity/2]).
  39. -export([ce_identity/1]).
  40. %% Interpretation.
  41. -export([version_to_binary/1]).
  42. -export([urldecode/1]).
  43. -export([urldecode/2]).
  44. -export([urlencode/1]).
  45. -export([urlencode/2]).
  46. -export([x_www_form_urlencoded/1]).
  47. -type version() :: {Major::non_neg_integer(), Minor::non_neg_integer()}.
  48. -type headers() :: [{binary(), iodata()}].
  49. -type status() :: non_neg_integer() | binary().
  50. -export_type([version/0]).
  51. -export_type([headers/0]).
  52. -export_type([status/0]).
  53. -ifdef(TEST).
  54. -include_lib("eunit/include/eunit.hrl").
  55. -endif.
  56. %% Parsing.
  57. %% @doc Parse a non-empty list of the given type.
  58. -spec nonempty_list(binary(), fun()) -> [any(), ...] | {error, badarg}.
  59. nonempty_list(Data, Fun) ->
  60. case list(Data, Fun, []) of
  61. {error, badarg} -> {error, badarg};
  62. [] -> {error, badarg};
  63. L -> lists:reverse(L)
  64. end.
  65. %% @doc Parse a list of the given type.
  66. -spec list(binary(), fun()) -> list() | {error, badarg}.
  67. list(Data, Fun) ->
  68. case list(Data, Fun, []) of
  69. {error, badarg} -> {error, badarg};
  70. L -> lists:reverse(L)
  71. end.
  72. -spec list(binary(), fun(), [binary()]) -> [any()] | {error, badarg}.
  73. %% From the RFC:
  74. %% <blockquote>Wherever this construct is used, null elements are allowed,
  75. %% but do not contribute to the count of elements present.
  76. %% That is, "(element), , (element) " is permitted, but counts
  77. %% as only two elements. Therefore, where at least one element is required,
  78. %% at least one non-null element MUST be present.</blockquote>
  79. list(Data, Fun, Acc) ->
  80. whitespace(Data,
  81. fun (<<>>) -> Acc;
  82. (<< $,, Rest/binary >>) -> list(Rest, Fun, Acc);
  83. (Rest) -> Fun(Rest,
  84. fun (D, I) -> whitespace(D,
  85. fun (<<>>) -> [I|Acc];
  86. (<< $,, R/binary >>) -> list(R, Fun, [I|Acc]);
  87. (_Any) -> {error, badarg}
  88. end)
  89. end)
  90. end).
  91. %% @doc Parse a content type.
  92. -spec content_type(binary()) -> any().
  93. content_type(Data) ->
  94. media_type(Data,
  95. fun (Rest, Type, SubType) ->
  96. params(Rest,
  97. fun (<<>>, Params) -> {Type, SubType, Params};
  98. (_Rest2, _) -> {error, badarg}
  99. end)
  100. end).
  101. %% @doc Parse a media range.
  102. -spec media_range(binary(), fun()) -> any().
  103. media_range(Data, Fun) ->
  104. media_type(Data,
  105. fun (Rest, Type, SubType) ->
  106. media_range_params(Rest, Fun, Type, SubType, [])
  107. end).
  108. -spec media_range_params(binary(), fun(), binary(), binary(),
  109. [{binary(), binary()}]) -> any().
  110. media_range_params(Data, Fun, Type, SubType, Acc) ->
  111. whitespace(Data,
  112. fun (<< $;, Rest/binary >>) ->
  113. whitespace(Rest,
  114. fun (Rest2) ->
  115. media_range_param_attr(Rest2, Fun, Type, SubType, Acc)
  116. end);
  117. (Rest) -> Fun(Rest, {{Type, SubType, lists:reverse(Acc)}, 1000, []})
  118. end).
  119. -spec media_range_param_attr(binary(), fun(), binary(), binary(),
  120. [{binary(), binary()}]) -> any().
  121. media_range_param_attr(Data, Fun, Type, SubType, Acc) ->
  122. token_ci(Data,
  123. fun (_Rest, <<>>) -> {error, badarg};
  124. (<< $=, Rest/binary >>, Attr) ->
  125. media_range_param_value(Rest, Fun, Type, SubType, Acc, Attr)
  126. end).
  127. -spec media_range_param_value(binary(), fun(), binary(), binary(),
  128. [{binary(), binary()}], binary()) -> any().
  129. media_range_param_value(Data, Fun, Type, SubType, Acc, <<"q">>) ->
  130. qvalue(Data,
  131. fun (Rest, Quality) ->
  132. accept_ext(Rest, Fun, Type, SubType, Acc, Quality, [])
  133. end);
  134. media_range_param_value(Data, Fun, Type, SubType, Acc, Attr) ->
  135. word(Data,
  136. fun (Rest, Value) ->
  137. media_range_params(Rest, Fun,
  138. Type, SubType, [{Attr, Value}|Acc])
  139. end).
  140. %% @doc Parse a media type.
  141. -spec media_type(binary(), fun()) -> any().
  142. media_type(Data, Fun) ->
  143. token_ci(Data,
  144. fun (_Rest, <<>>) -> {error, badarg};
  145. (<< $/, Rest/binary >>, Type) ->
  146. token_ci(Rest,
  147. fun (_Rest2, <<>>) -> {error, badarg};
  148. (Rest2, SubType) -> Fun(Rest2, Type, SubType)
  149. end);
  150. %% This is a non-strict parsing clause required by some user agents
  151. %% that use * instead of */* in the list of media types.
  152. (Rest, <<"*">> = Type) ->
  153. token_ci(<<"*", Rest/binary>>,
  154. fun (_Rest2, <<>>) -> {error, badarg};
  155. (Rest2, SubType) -> Fun(Rest2, Type, SubType)
  156. end);
  157. (_Rest, _Type) -> {error, badarg}
  158. end).
  159. -spec accept_ext(binary(), fun(), binary(), binary(),
  160. [{binary(), binary()}], 0..1000,
  161. [{binary(), binary()} | binary()]) -> any().
  162. accept_ext(Data, Fun, Type, SubType, Params, Quality, Acc) ->
  163. whitespace(Data,
  164. fun (<< $;, Rest/binary >>) ->
  165. whitespace(Rest,
  166. fun (Rest2) ->
  167. accept_ext_attr(Rest2, Fun,
  168. Type, SubType, Params, Quality, Acc)
  169. end);
  170. (Rest) ->
  171. Fun(Rest, {{Type, SubType, lists:reverse(Params)},
  172. Quality, lists:reverse(Acc)})
  173. end).
  174. -spec accept_ext_attr(binary(), fun(), binary(), binary(),
  175. [{binary(), binary()}], 0..1000,
  176. [{binary(), binary()} | binary()]) -> any().
  177. accept_ext_attr(Data, Fun, Type, SubType, Params, Quality, Acc) ->
  178. token_ci(Data,
  179. fun (_Rest, <<>>) -> {error, badarg};
  180. (<< $=, Rest/binary >>, Attr) ->
  181. accept_ext_value(Rest, Fun, Type, SubType, Params,
  182. Quality, Acc, Attr);
  183. (Rest, Attr) ->
  184. accept_ext(Rest, Fun, Type, SubType, Params,
  185. Quality, [Attr|Acc])
  186. end).
  187. -spec accept_ext_value(binary(), fun(), binary(), binary(),
  188. [{binary(), binary()}], 0..1000,
  189. [{binary(), binary()} | binary()], binary()) -> any().
  190. accept_ext_value(Data, Fun, Type, SubType, Params, Quality, Acc, Attr) ->
  191. word(Data,
  192. fun (Rest, Value) ->
  193. accept_ext(Rest, Fun,
  194. Type, SubType, Params, Quality, [{Attr, Value}|Acc])
  195. end).
  196. %% @doc Parse a conneg header (Accept-Charset, Accept-Encoding),
  197. %% followed by an optional quality value.
  198. -spec conneg(binary(), fun()) -> any().
  199. conneg(Data, Fun) ->
  200. token_ci(Data,
  201. fun (_Rest, <<>>) -> {error, badarg};
  202. (Rest, Conneg) ->
  203. maybe_qparam(Rest,
  204. fun (Rest2, Quality) ->
  205. Fun(Rest2, {Conneg, Quality})
  206. end)
  207. end).
  208. %% @doc Parse a language range, followed by an optional quality value.
  209. -spec language_range(binary(), fun()) -> any().
  210. language_range(<< $*, Rest/binary >>, Fun) ->
  211. language_range_ret(Rest, Fun, '*');
  212. language_range(Data, Fun) ->
  213. language_tag(Data,
  214. fun (Rest, LanguageTag) ->
  215. language_range_ret(Rest, Fun, LanguageTag)
  216. end).
  217. -spec language_range_ret(binary(), fun(), '*' | {binary(), [binary()]}) -> any().
  218. language_range_ret(Data, Fun, LanguageTag) ->
  219. maybe_qparam(Data,
  220. fun (Rest, Quality) ->
  221. Fun(Rest, {LanguageTag, Quality})
  222. end).
  223. -spec language_tag(binary(), fun()) -> any().
  224. language_tag(Data, Fun) ->
  225. alpha(Data,
  226. fun (_Rest, Tag) when byte_size(Tag) =:= 0; byte_size(Tag) > 8 ->
  227. {error, badarg};
  228. (<< $-, Rest/binary >>, Tag) ->
  229. language_subtag(Rest, Fun, Tag, []);
  230. (Rest, Tag) ->
  231. Fun(Rest, Tag)
  232. end).
  233. -spec language_subtag(binary(), fun(), binary(), [binary()]) -> any().
  234. language_subtag(Data, Fun, Tag, Acc) ->
  235. alpha(Data,
  236. fun (_Rest, SubTag) when byte_size(SubTag) =:= 0;
  237. byte_size(SubTag) > 8 -> {error, badarg};
  238. (<< $-, Rest/binary >>, SubTag) ->
  239. language_subtag(Rest, Fun, Tag, [SubTag|Acc]);
  240. (Rest, SubTag) ->
  241. %% Rebuild the full tag now that we know it's correct
  242. Sub = << << $-, S/binary >> || S <- lists:reverse([SubTag|Acc]) >>,
  243. Fun(Rest, << Tag/binary, Sub/binary >>)
  244. end).
  245. -spec maybe_qparam(binary(), fun()) -> any().
  246. maybe_qparam(Data, Fun) ->
  247. whitespace(Data,
  248. fun (<< $;, Rest/binary >>) ->
  249. whitespace(Rest,
  250. fun (Rest2) ->
  251. %% This is a non-strict parsing clause required by some user agents
  252. %% that use the wrong delimiter putting a charset where a qparam is
  253. %% expected.
  254. try qparam(Rest2, Fun) of
  255. Result -> Result
  256. catch
  257. error:function_clause ->
  258. Fun(<<",", Rest2/binary>>, 1000)
  259. end
  260. end);
  261. (Rest) ->
  262. Fun(Rest, 1000)
  263. end).
  264. %% @doc Parse a quality parameter string (for example q=0.500).
  265. -spec qparam(binary(), fun()) -> any().
  266. qparam(<< Q, $=, Data/binary >>, Fun) when Q =:= $q; Q =:= $Q ->
  267. qvalue(Data, Fun).
  268. %% @doc Parse either a list of entity tags or a "*".
  269. -spec entity_tag_match(binary()) -> any().
  270. entity_tag_match(<< $*, Rest/binary >>) ->
  271. whitespace(Rest,
  272. fun (<<>>) -> '*';
  273. (_Any) -> {error, badarg}
  274. end);
  275. entity_tag_match(Data) ->
  276. nonempty_list(Data, fun entity_tag/2).
  277. %% @doc Parse an entity-tag.
  278. -spec entity_tag(binary(), fun()) -> any().
  279. entity_tag(<< "W/", Rest/binary >>, Fun) ->
  280. opaque_tag(Rest, Fun, weak);
  281. entity_tag(Data, Fun) ->
  282. opaque_tag(Data, Fun, strong).
  283. -spec opaque_tag(binary(), fun(), weak | strong) -> any().
  284. opaque_tag(Data, Fun, Strength) ->
  285. quoted_string(Data,
  286. fun (_Rest, <<>>) -> {error, badarg};
  287. (Rest, OpaqueTag) -> Fun(Rest, {Strength, OpaqueTag})
  288. end).
  289. %% @doc Parse an expectation.
  290. -spec expectation(binary(), fun()) -> any().
  291. expectation(Data, Fun) ->
  292. token_ci(Data,
  293. fun (_Rest, <<>>) -> {error, badarg};
  294. (<< $=, Rest/binary >>, Expectation) ->
  295. word(Rest,
  296. fun (Rest2, ExtValue) ->
  297. params(Rest2, fun (Rest3, ExtParams) ->
  298. Fun(Rest3, {Expectation, ExtValue, ExtParams})
  299. end)
  300. end);
  301. (Rest, Expectation) ->
  302. Fun(Rest, Expectation)
  303. end).
  304. %% @doc Parse a list of parameters (a=b;c=d).
  305. -spec params(binary(), fun()) -> any().
  306. params(Data, Fun) ->
  307. params(Data, Fun, []).
  308. -spec params(binary(), fun(), [{binary(), binary()}]) -> any().
  309. params(Data, Fun, Acc) ->
  310. whitespace(Data,
  311. fun (<< $;, Rest/binary >>) -> param(Rest, Fun, Acc);
  312. (Rest) -> Fun(Rest, lists:reverse(Acc))
  313. end).
  314. -spec param(binary(), fun(), [{binary(), binary()}]) -> any().
  315. param(Data, Fun, Acc) ->
  316. whitespace(Data,
  317. fun (Rest) ->
  318. token_ci(Rest,
  319. fun (_Rest2, <<>>) -> {error, badarg};
  320. (<< $=, Rest2/binary >>, Attr) ->
  321. word(Rest2,
  322. fun (Rest3, Value) ->
  323. params(Rest3, Fun,
  324. [{Attr, Value}|Acc])
  325. end);
  326. (_Rest2, _Attr) -> {error, badarg}
  327. end)
  328. end).
  329. %% @doc Parse an HTTP date (RFC1123, RFC850 or asctime date).
  330. %% @end
  331. %%
  332. %% While this may not be the most efficient date parsing we can do,
  333. %% it should work fine for our purposes because all HTTP dates should
  334. %% be sent as RFC1123 dates in HTTP/1.1.
  335. -spec http_date(binary()) -> any().
  336. http_date(Data) ->
  337. case rfc1123_date(Data) of
  338. {error, badarg} ->
  339. case rfc850_date(Data) of
  340. {error, badarg} ->
  341. case asctime_date(Data) of
  342. {error, badarg} ->
  343. {error, badarg};
  344. HTTPDate ->
  345. HTTPDate
  346. end;
  347. HTTPDate ->
  348. HTTPDate
  349. end;
  350. HTTPDate ->
  351. HTTPDate
  352. end.
  353. %% @doc Parse an RFC1123 date.
  354. -spec rfc1123_date(binary()) -> any().
  355. rfc1123_date(Data) ->
  356. wkday(Data,
  357. fun (<< ", ", Rest/binary >>, _WkDay) ->
  358. date1(Rest,
  359. fun (<< " ", Rest2/binary >>, Date) ->
  360. time(Rest2,
  361. fun (<< " GMT", Rest3/binary >>, Time) ->
  362. http_date_ret(Rest3, {Date, Time});
  363. (_Any, _Time) ->
  364. {error, badarg}
  365. end);
  366. (_Any, _Date) ->
  367. {error, badarg}
  368. end);
  369. (_Any, _WkDay) ->
  370. {error, badarg}
  371. end).
  372. %% @doc Parse an RFC850 date.
  373. -spec rfc850_date(binary()) -> any().
  374. %% From the RFC:
  375. %% HTTP/1.1 clients and caches SHOULD assume that an RFC-850 date
  376. %% which appears to be more than 50 years in the future is in fact
  377. %% in the past (this helps solve the "year 2000" problem).
  378. rfc850_date(Data) ->
  379. weekday(Data,
  380. fun (<< ", ", Rest/binary >>, _WeekDay) ->
  381. date2(Rest,
  382. fun (<< " ", Rest2/binary >>, Date) ->
  383. time(Rest2,
  384. fun (<< " GMT", Rest3/binary >>, Time) ->
  385. http_date_ret(Rest3, {Date, Time});
  386. (_Any, _Time) ->
  387. {error, badarg}
  388. end);
  389. (_Any, _Date) ->
  390. {error, badarg}
  391. end);
  392. (_Any, _WeekDay) ->
  393. {error, badarg}
  394. end).
  395. %% @doc Parse an asctime date.
  396. -spec asctime_date(binary()) -> any().
  397. asctime_date(Data) ->
  398. wkday(Data,
  399. fun (<< " ", Rest/binary >>, _WkDay) ->
  400. date3(Rest,
  401. fun (<< " ", Rest2/binary >>, PartialDate) ->
  402. time(Rest2,
  403. fun (<< " ", Rest3/binary >>, Time) ->
  404. asctime_year(Rest3,
  405. PartialDate, Time);
  406. (_Any, _Time) ->
  407. {error, badarg}
  408. end);
  409. (_Any, _PartialDate) ->
  410. {error, badarg}
  411. end);
  412. (_Any, _WkDay) ->
  413. {error, badarg1}
  414. end).
  415. -spec asctime_year(binary(), tuple(), tuple()) -> any().
  416. asctime_year(<< Y1, Y2, Y3, Y4, Rest/binary >>, {Month, Day}, Time)
  417. when Y1 >= $0, Y1 =< $9, Y2 >= $0, Y2 =< $9,
  418. Y3 >= $0, Y3 =< $9, Y4 >= $0, Y4 =< $9 ->
  419. Year = (Y1 - $0) * 1000 + (Y2 - $0) * 100 + (Y3 - $0) * 10 + (Y4 - $0),
  420. http_date_ret(Rest, {{Year, Month, Day}, Time}).
  421. -spec http_date_ret(binary(), tuple()) -> any().
  422. http_date_ret(Data, DateTime = {Date, _Time}) ->
  423. whitespace(Data,
  424. fun (<<>>) ->
  425. case calendar:valid_date(Date) of
  426. true -> DateTime;
  427. false -> {error, badarg}
  428. end;
  429. (_Any) ->
  430. {error, badarg}
  431. end).
  432. %% We never use it, pretty much just checks the wkday is right.
  433. -spec wkday(binary(), fun()) -> any().
  434. wkday(<< WkDay:3/binary, Rest/binary >>, Fun)
  435. when WkDay =:= <<"Mon">>; WkDay =:= <<"Tue">>; WkDay =:= <<"Wed">>;
  436. WkDay =:= <<"Thu">>; WkDay =:= <<"Fri">>; WkDay =:= <<"Sat">>;
  437. WkDay =:= <<"Sun">> ->
  438. Fun(Rest, WkDay);
  439. wkday(_Any, _Fun) ->
  440. {error, badarg}.
  441. %% We never use it, pretty much just checks the weekday is right.
  442. -spec weekday(binary(), fun()) -> any().
  443. weekday(<< "Monday", Rest/binary >>, Fun) ->
  444. Fun(Rest, <<"Monday">>);
  445. weekday(<< "Tuesday", Rest/binary >>, Fun) ->
  446. Fun(Rest, <<"Tuesday">>);
  447. weekday(<< "Wednesday", Rest/binary >>, Fun) ->
  448. Fun(Rest, <<"Wednesday">>);
  449. weekday(<< "Thursday", Rest/binary >>, Fun) ->
  450. Fun(Rest, <<"Thursday">>);
  451. weekday(<< "Friday", Rest/binary >>, Fun) ->
  452. Fun(Rest, <<"Friday">>);
  453. weekday(<< "Saturday", Rest/binary >>, Fun) ->
  454. Fun(Rest, <<"Saturday">>);
  455. weekday(<< "Sunday", Rest/binary >>, Fun) ->
  456. Fun(Rest, <<"Sunday">>);
  457. weekday(_Any, _Fun) ->
  458. {error, badarg}.
  459. -spec date1(binary(), fun()) -> any().
  460. date1(<< D1, D2, " ", M:3/binary, " ", Y1, Y2, Y3, Y4, Rest/binary >>, Fun)
  461. when D1 >= $0, D1 =< $9, D2 >= $0, D2 =< $9,
  462. Y1 >= $0, Y1 =< $9, Y2 >= $0, Y2 =< $9,
  463. Y3 >= $0, Y3 =< $9, Y4 >= $0, Y4 =< $9 ->
  464. case month(M) of
  465. {error, badarg} ->
  466. {error, badarg};
  467. Month ->
  468. Fun(Rest, {
  469. (Y1 - $0) * 1000 + (Y2 - $0) * 100 + (Y3 - $0) * 10 + (Y4 - $0),
  470. Month,
  471. (D1 - $0) * 10 + (D2 - $0)
  472. })
  473. end;
  474. date1(_Data, _Fun) ->
  475. {error, badarg}.
  476. -spec date2(binary(), fun()) -> any().
  477. date2(<< D1, D2, "-", M:3/binary, "-", Y1, Y2, Rest/binary >>, Fun)
  478. when D1 >= $0, D1 =< $9, D2 >= $0, D2 =< $9,
  479. Y1 >= $0, Y1 =< $9, Y2 >= $0, Y2 =< $9 ->
  480. case month(M) of
  481. {error, badarg} ->
  482. {error, badarg};
  483. Month ->
  484. Year = (Y1 - $0) * 10 + (Y2 - $0),
  485. Year2 = case Year > 50 of
  486. true -> Year + 1900;
  487. false -> Year + 2000
  488. end,
  489. Fun(Rest, {
  490. Year2,
  491. Month,
  492. (D1 - $0) * 10 + (D2 - $0)
  493. })
  494. end;
  495. date2(_Data, _Fun) ->
  496. {error, badarg}.
  497. -spec date3(binary(), fun()) -> any().
  498. date3(<< M:3/binary, " ", D1, D2, Rest/binary >>, Fun)
  499. when (D1 >= $0 andalso D1 =< $3) orelse D1 =:= $\s,
  500. D2 >= $0, D2 =< $9 ->
  501. case month(M) of
  502. {error, badarg} ->
  503. {error, badarg};
  504. Month ->
  505. Day = case D1 of
  506. $\s -> D2 - $0;
  507. D1 -> (D1 - $0) * 10 + (D2 - $0)
  508. end,
  509. Fun(Rest, {Month, Day})
  510. end;
  511. date3(_Data, _Fun) ->
  512. {error, badarg}.
  513. -spec month(<< _:24 >>) -> 1..12 | {error, badarg}.
  514. month(<<"Jan">>) -> 1;
  515. month(<<"Feb">>) -> 2;
  516. month(<<"Mar">>) -> 3;
  517. month(<<"Apr">>) -> 4;
  518. month(<<"May">>) -> 5;
  519. month(<<"Jun">>) -> 6;
  520. month(<<"Jul">>) -> 7;
  521. month(<<"Aug">>) -> 8;
  522. month(<<"Sep">>) -> 9;
  523. month(<<"Oct">>) -> 10;
  524. month(<<"Nov">>) -> 11;
  525. month(<<"Dec">>) -> 12;
  526. month(_Any) -> {error, badarg}.
  527. -spec time(binary(), fun()) -> any().
  528. time(<< H1, H2, ":", M1, M2, ":", S1, S2, Rest/binary >>, Fun)
  529. when H1 >= $0, H1 =< $2, H2 >= $0, H2 =< $9,
  530. M1 >= $0, M1 =< $5, M2 >= $0, M2 =< $9,
  531. S1 >= $0, S1 =< $5, S2 >= $0, S2 =< $9 ->
  532. Hour = (H1 - $0) * 10 + (H2 - $0),
  533. case Hour < 24 of
  534. true ->
  535. Time = {
  536. Hour,
  537. (M1 - $0) * 10 + (M2 - $0),
  538. (S1 - $0) * 10 + (S2 - $0)
  539. },
  540. Fun(Rest, Time);
  541. false ->
  542. {error, badarg}
  543. end.
  544. %% @doc Skip whitespace.
  545. -spec whitespace(binary(), fun()) -> any().
  546. whitespace(<< C, Rest/binary >>, Fun)
  547. when C =:= $\s; C =:= $\t ->
  548. whitespace(Rest, Fun);
  549. whitespace(Data, Fun) ->
  550. Fun(Data).
  551. %% @doc Parse a list of digits as a non negative integer.
  552. -spec digits(binary()) -> non_neg_integer() | {error, badarg}.
  553. digits(Data) ->
  554. digits(Data,
  555. fun (Rest, I) ->
  556. whitespace(Rest,
  557. fun (<<>>) ->
  558. I;
  559. (_Rest2) ->
  560. {error, badarg}
  561. end)
  562. end).
  563. -spec digits(binary(), fun()) -> any().
  564. digits(<< C, Rest/binary >>, Fun)
  565. when C >= $0, C =< $9 ->
  566. digits(Rest, Fun, C - $0);
  567. digits(_Data, _Fun) ->
  568. {error, badarg}.
  569. -spec digits(binary(), fun(), non_neg_integer()) -> any().
  570. digits(<< C, Rest/binary >>, Fun, Acc)
  571. when C >= $0, C =< $9 ->
  572. digits(Rest, Fun, Acc * 10 + (C - $0));
  573. digits(Data, Fun, Acc) ->
  574. Fun(Data, Acc).
  575. %% @doc Parse a list of case-insensitive alpha characters.
  576. %%
  577. %% Changes all characters to lowercase.
  578. -spec alpha(binary(), fun()) -> any().
  579. alpha(Data, Fun) ->
  580. alpha(Data, Fun, <<>>).
  581. -spec alpha(binary(), fun(), binary()) -> any().
  582. alpha(<<>>, Fun, Acc) ->
  583. Fun(<<>>, Acc);
  584. alpha(<< C, Rest/binary >>, Fun, Acc)
  585. when C >= $a andalso C =< $z;
  586. C >= $A andalso C =< $Z ->
  587. C2 = cowboy_bstr:char_to_lower(C),
  588. alpha(Rest, Fun, << Acc/binary, C2 >>);
  589. alpha(Data, Fun, Acc) ->
  590. Fun(Data, Acc).
  591. %% @doc Parse either a token or a quoted string.
  592. -spec word(binary(), fun()) -> any().
  593. word(Data = << $", _/binary >>, Fun) ->
  594. quoted_string(Data, Fun);
  595. word(Data, Fun) ->
  596. token(Data,
  597. fun (_Rest, <<>>) -> {error, badarg};
  598. (Rest, Token) -> Fun(Rest, Token)
  599. end).
  600. %% @doc Parse a case-insensitive token.
  601. %%
  602. %% Changes all characters to lowercase.
  603. -spec token_ci(binary(), fun()) -> any().
  604. token_ci(Data, Fun) ->
  605. token(Data, Fun, ci, <<>>).
  606. %% @doc Parse a token.
  607. -spec token(binary(), fun()) -> any().
  608. token(Data, Fun) ->
  609. token(Data, Fun, cs, <<>>).
  610. -spec token(binary(), fun(), ci | cs, binary()) -> any().
  611. token(<<>>, Fun, _Case, Acc) ->
  612. Fun(<<>>, Acc);
  613. token(Data = << C, _Rest/binary >>, Fun, _Case, Acc)
  614. when C =:= $(; C =:= $); C =:= $<; C =:= $>; C =:= $@;
  615. C =:= $,; C =:= $;; C =:= $:; C =:= $\\; C =:= $";
  616. C =:= $/; C =:= $[; C =:= $]; C =:= $?; C =:= $=;
  617. C =:= ${; C =:= $}; C =:= $\s; C =:= $\t;
  618. C < 32; C =:= 127 ->
  619. Fun(Data, Acc);
  620. token(<< C, Rest/binary >>, Fun, Case = ci, Acc) ->
  621. C2 = cowboy_bstr:char_to_lower(C),
  622. token(Rest, Fun, Case, << Acc/binary, C2 >>);
  623. token(<< C, Rest/binary >>, Fun, Case, Acc) ->
  624. token(Rest, Fun, Case, << Acc/binary, C >>).
  625. %% @doc Parse a quoted string.
  626. -spec quoted_string(binary(), fun()) -> any().
  627. quoted_string(<< $", Rest/binary >>, Fun) ->
  628. quoted_string(Rest, Fun, <<>>).
  629. -spec quoted_string(binary(), fun(), binary()) -> any().
  630. quoted_string(<<>>, _Fun, _Acc) ->
  631. {error, badarg};
  632. quoted_string(<< $", Rest/binary >>, Fun, Acc) ->
  633. Fun(Rest, Acc);
  634. quoted_string(<< $\\, C, Rest/binary >>, Fun, Acc) ->
  635. quoted_string(Rest, Fun, << Acc/binary, C >>);
  636. quoted_string(<< C, Rest/binary >>, Fun, Acc) ->
  637. quoted_string(Rest, Fun, << Acc/binary, C >>).
  638. %% @doc Parse a quality value.
  639. -spec qvalue(binary(), fun()) -> any().
  640. qvalue(<< $0, $., Rest/binary >>, Fun) ->
  641. qvalue(Rest, Fun, 0, 100);
  642. %% Some user agents use q=.x instead of q=0.x
  643. qvalue(<< $., Rest/binary >>, Fun) ->
  644. qvalue(Rest, Fun, 0, 100);
  645. qvalue(<< $0, Rest/binary >>, Fun) ->
  646. Fun(Rest, 0);
  647. qvalue(<< $1, $., $0, $0, $0, Rest/binary >>, Fun) ->
  648. Fun(Rest, 1000);
  649. qvalue(<< $1, $., $0, $0, Rest/binary >>, Fun) ->
  650. Fun(Rest, 1000);
  651. qvalue(<< $1, $., $0, Rest/binary >>, Fun) ->
  652. Fun(Rest, 1000);
  653. qvalue(<< $1, Rest/binary >>, Fun) ->
  654. Fun(Rest, 1000);
  655. qvalue(_Data, _Fun) ->
  656. {error, badarg}.
  657. -spec qvalue(binary(), fun(), integer(), 1 | 10 | 100) -> any().
  658. qvalue(Data, Fun, Q, 0) ->
  659. Fun(Data, Q);
  660. qvalue(<< C, Rest/binary >>, Fun, Q, M)
  661. when C >= $0, C =< $9 ->
  662. qvalue(Rest, Fun, Q + (C - $0) * M, M div 10);
  663. qvalue(Data, Fun, Q, _M) ->
  664. Fun(Data, Q).
  665. %% Decoding.
  666. %% @doc Decode a stream of chunks.
  667. -spec te_chunked(binary(), {non_neg_integer(), non_neg_integer()})
  668. -> more | {ok, binary(), {non_neg_integer(), non_neg_integer()}}
  669. | {ok, binary(), binary(), {non_neg_integer(), non_neg_integer()}}
  670. | {done, non_neg_integer(), binary()} | {error, badarg}.
  671. te_chunked(<<>>, _) ->
  672. more;
  673. te_chunked(<< "0\r\n\r\n", Rest/binary >>, {0, Streamed}) ->
  674. {done, Streamed, Rest};
  675. te_chunked(Data, {0, Streamed}) ->
  676. %% @todo We are expecting an hex size, not a general token.
  677. token(Data,
  678. fun (Rest, _) when byte_size(Rest) < 4 ->
  679. more;
  680. (<< "\r\n", Rest/binary >>, BinLen) ->
  681. Len = list_to_integer(binary_to_list(BinLen), 16),
  682. te_chunked(Rest, {Len, Streamed});
  683. (_, _) ->
  684. {error, badarg}
  685. end);
  686. te_chunked(Data, {ChunkRem, Streamed}) when byte_size(Data) >= ChunkRem + 2 ->
  687. << Chunk:ChunkRem/binary, "\r\n", Rest/binary >> = Data,
  688. {ok, Chunk, Rest, {0, Streamed + byte_size(Chunk)}};
  689. te_chunked(Data, {ChunkRem, Streamed}) ->
  690. Size = byte_size(Data),
  691. {ok, Data, {ChunkRem - Size, Streamed + Size}}.
  692. %% @doc Decode an identity stream.
  693. -spec te_identity(binary(), {non_neg_integer(), non_neg_integer()})
  694. -> {ok, binary(), {non_neg_integer(), non_neg_integer()}}
  695. | {done, binary(), non_neg_integer(), binary()}.
  696. te_identity(Data, {Streamed, Total})
  697. when Streamed + byte_size(Data) < Total ->
  698. {ok, Data, {Streamed + byte_size(Data), Total}};
  699. te_identity(Data, {Streamed, Total}) ->
  700. Size = Total - Streamed,
  701. << Data2:Size/binary, Rest/binary >> = Data,
  702. {done, Data2, Total, Rest}.
  703. %% @doc Decode an identity content.
  704. -spec ce_identity(binary()) -> {ok, binary()}.
  705. ce_identity(Data) ->
  706. {ok, Data}.
  707. %% Interpretation.
  708. %% @doc Convert an HTTP version tuple to its binary form.
  709. -spec version_to_binary(version()) -> binary().
  710. version_to_binary({1, 1}) -> <<"HTTP/1.1">>;
  711. version_to_binary({1, 0}) -> <<"HTTP/1.0">>.
  712. %% @doc Decode a URL encoded binary.
  713. %% @equiv urldecode(Bin, crash)
  714. -spec urldecode(binary()) -> binary().
  715. urldecode(Bin) when is_binary(Bin) ->
  716. urldecode(Bin, <<>>, crash).
  717. %% @doc Decode a URL encoded binary.
  718. %% The second argument specifies how to handle percent characters that are not
  719. %% followed by two valid hex characters. Use `skip' to ignore such errors,
  720. %% if `crash' is used the function will fail with the reason `badarg'.
  721. -spec urldecode(binary(), crash | skip) -> binary().
  722. urldecode(Bin, OnError) when is_binary(Bin) ->
  723. urldecode(Bin, <<>>, OnError).
  724. -spec urldecode(binary(), binary(), crash | skip) -> binary().
  725. urldecode(<<$%, H, L, Rest/binary>>, Acc, OnError) ->
  726. G = unhex(H),
  727. M = unhex(L),
  728. if G =:= error; M =:= error ->
  729. case OnError of skip -> ok; crash -> erlang:error(badarg) end,
  730. urldecode(<<H, L, Rest/binary>>, <<Acc/binary, $%>>, OnError);
  731. true ->
  732. urldecode(Rest, <<Acc/binary, (G bsl 4 bor M)>>, OnError)
  733. end;
  734. urldecode(<<$%, Rest/binary>>, Acc, OnError) ->
  735. case OnError of skip -> ok; crash -> erlang:error(badarg) end,
  736. urldecode(Rest, <<Acc/binary, $%>>, OnError);
  737. urldecode(<<$+, Rest/binary>>, Acc, OnError) ->
  738. urldecode(Rest, <<Acc/binary, $ >>, OnError);
  739. urldecode(<<C, Rest/binary>>, Acc, OnError) ->
  740. urldecode(Rest, <<Acc/binary, C>>, OnError);
  741. urldecode(<<>>, Acc, _OnError) ->
  742. Acc.
  743. -spec unhex(byte()) -> byte() | error.
  744. unhex(C) when C >= $0, C =< $9 -> C - $0;
  745. unhex(C) when C >= $A, C =< $F -> C - $A + 10;
  746. unhex(C) when C >= $a, C =< $f -> C - $a + 10;
  747. unhex(_) -> error.
  748. %% @doc URL encode a string binary.
  749. %% @equiv urlencode(Bin, [])
  750. -spec urlencode(binary()) -> binary().
  751. urlencode(Bin) ->
  752. urlencode(Bin, []).
  753. %% @doc URL encode a string binary.
  754. %% The `noplus' option disables the default behaviour of quoting space
  755. %% characters, `\s', as `+'. The `upper' option overrides the default behaviour
  756. %% of writing hex numbers using lowecase letters to using uppercase letters
  757. %% instead.
  758. -spec urlencode(binary(), [noplus|upper]) -> binary().
  759. urlencode(Bin, Opts) ->
  760. Plus = not lists:member(noplus, Opts),
  761. Upper = lists:member(upper, Opts),
  762. urlencode(Bin, <<>>, Plus, Upper).
  763. -spec urlencode(binary(), binary(), boolean(), boolean()) -> binary().
  764. urlencode(<<C, Rest/binary>>, Acc, P=Plus, U=Upper) ->
  765. if C >= $0, C =< $9 -> urlencode(Rest, <<Acc/binary, C>>, P, U);
  766. C >= $A, C =< $Z -> urlencode(Rest, <<Acc/binary, C>>, P, U);
  767. C >= $a, C =< $z -> urlencode(Rest, <<Acc/binary, C>>, P, U);
  768. C =:= $.; C =:= $-; C =:= $~; C =:= $_ ->
  769. urlencode(Rest, <<Acc/binary, C>>, P, U);
  770. C =:= $ , Plus ->
  771. urlencode(Rest, <<Acc/binary, $+>>, P, U);
  772. true ->
  773. H = C band 16#F0 bsr 4, L = C band 16#0F,
  774. H1 = if Upper -> tohexu(H); true -> tohexl(H) end,
  775. L1 = if Upper -> tohexu(L); true -> tohexl(L) end,
  776. urlencode(Rest, <<Acc/binary, $%, H1, L1>>, P, U)
  777. end;
  778. urlencode(<<>>, Acc, _Plus, _Upper) ->
  779. Acc.
  780. -spec tohexu(byte()) -> byte().
  781. tohexu(C) when C < 10 -> $0 + C;
  782. tohexu(C) when C < 17 -> $A + C - 10.
  783. -spec tohexl(byte()) -> byte().
  784. tohexl(C) when C < 10 -> $0 + C;
  785. tohexl(C) when C < 17 -> $a + C - 10.
  786. -spec x_www_form_urlencoded(binary()) -> list({binary(), binary() | true}).
  787. x_www_form_urlencoded(<<>>) ->
  788. [];
  789. x_www_form_urlencoded(Qs) ->
  790. Tokens = binary:split(Qs, <<"&">>, [global, trim]),
  791. [case binary:split(Token, <<"=">>) of
  792. [Token] -> {urldecode(Token), true};
  793. [Name, Value] -> {urldecode(Name), urldecode(Value)}
  794. end || Token <- Tokens].
  795. %% Tests.
  796. -ifdef(TEST).
  797. nonempty_charset_list_test_() ->
  798. %% {Value, Result}
  799. Tests = [
  800. {<<>>, {error, badarg}},
  801. {<<"iso-8859-5, unicode-1-1;q=0.8">>, [
  802. {<<"iso-8859-5">>, 1000},
  803. {<<"unicode-1-1">>, 800}
  804. ]},
  805. %% Some user agents send this invalid value for the Accept-Charset header
  806. {<<"ISO-8859-1;utf-8;q=0.7,*;q=0.7">>, [
  807. {<<"iso-8859-1">>, 1000},
  808. {<<"utf-8">>, 700},
  809. {<<"*">>, 700}
  810. ]}
  811. ],
  812. [{V, fun() -> R = nonempty_list(V, fun conneg/2) end} || {V, R} <- Tests].
  813. nonempty_language_range_list_test_() ->
  814. %% {Value, Result}
  815. Tests = [
  816. {<<"da, en-gb;q=0.8, en;q=0.7">>, [
  817. {<<"da">>, 1000},
  818. {<<"en-gb">>, 800},
  819. {<<"en">>, 700}
  820. ]},
  821. {<<"en, en-US, en-cockney, i-cherokee, x-pig-latin">>, [
  822. {<<"en">>, 1000},
  823. {<<"en-us">>, 1000},
  824. {<<"en-cockney">>, 1000},
  825. {<<"i-cherokee">>, 1000},
  826. {<<"x-pig-latin">>, 1000}
  827. ]}
  828. ],
  829. [{V, fun() -> R = nonempty_list(V, fun language_range/2) end}
  830. || {V, R} <- Tests].
  831. nonempty_token_list_test_() ->
  832. %% {Value, Result}
  833. Tests = [
  834. {<<>>, {error, badarg}},
  835. {<<" ">>, {error, badarg}},
  836. {<<" , ">>, {error, badarg}},
  837. {<<",,,">>, {error, badarg}},
  838. {<<"a b">>, {error, badarg}},
  839. {<<"a , , , ">>, [<<"a">>]},
  840. {<<" , , , a">>, [<<"a">>]},
  841. {<<"a, , b">>, [<<"a">>, <<"b">>]},
  842. {<<"close">>, [<<"close">>]},
  843. {<<"keep-alive, upgrade">>, [<<"keep-alive">>, <<"upgrade">>]}
  844. ],
  845. [{V, fun() -> R = nonempty_list(V, fun token/2) end} || {V, R} <- Tests].
  846. media_range_list_test_() ->
  847. %% {Tokens, Result}
  848. Tests = [
  849. {<<"audio/*; q=0.2, audio/basic">>, [
  850. {{<<"audio">>, <<"*">>, []}, 200, []},
  851. {{<<"audio">>, <<"basic">>, []}, 1000, []}
  852. ]},
  853. {<<"text/plain; q=0.5, text/html, "
  854. "text/x-dvi; q=0.8, text/x-c">>, [
  855. {{<<"text">>, <<"plain">>, []}, 500, []},
  856. {{<<"text">>, <<"html">>, []}, 1000, []},
  857. {{<<"text">>, <<"x-dvi">>, []}, 800, []},
  858. {{<<"text">>, <<"x-c">>, []}, 1000, []}
  859. ]},
  860. {<<"text/*, text/html, text/html;level=1, */*">>, [
  861. {{<<"text">>, <<"*">>, []}, 1000, []},
  862. {{<<"text">>, <<"html">>, []}, 1000, []},
  863. {{<<"text">>, <<"html">>, [{<<"level">>, <<"1">>}]}, 1000, []},
  864. {{<<"*">>, <<"*">>, []}, 1000, []}
  865. ]},
  866. {<<"text/*;q=0.3, text/html;q=0.7, text/html;level=1, "
  867. "text/html;level=2;q=0.4, */*;q=0.5">>, [
  868. {{<<"text">>, <<"*">>, []}, 300, []},
  869. {{<<"text">>, <<"html">>, []}, 700, []},
  870. {{<<"text">>, <<"html">>, [{<<"level">>, <<"1">>}]}, 1000, []},
  871. {{<<"text">>, <<"html">>, [{<<"level">>, <<"2">>}]}, 400, []},
  872. {{<<"*">>, <<"*">>, []}, 500, []}
  873. ]},
  874. {<<"text/html;level=1;quoted=\"hi hi hi\";"
  875. "q=0.123;standalone;complex=gits, text/plain">>, [
  876. {{<<"text">>, <<"html">>,
  877. [{<<"level">>, <<"1">>}, {<<"quoted">>, <<"hi hi hi">>}]}, 123,
  878. [<<"standalone">>, {<<"complex">>, <<"gits">>}]},
  879. {{<<"text">>, <<"plain">>, []}, 1000, []}
  880. ]},
  881. {<<"text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2">>, [
  882. {{<<"text">>, <<"html">>, []}, 1000, []},
  883. {{<<"image">>, <<"gif">>, []}, 1000, []},
  884. {{<<"image">>, <<"jpeg">>, []}, 1000, []},
  885. {{<<"*">>, <<"*">>, []}, 200, []},
  886. {{<<"*">>, <<"*">>, []}, 200, []}
  887. ]}
  888. ],
  889. [{V, fun() -> R = list(V, fun media_range/2) end} || {V, R} <- Tests].
  890. entity_tag_match_test_() ->
  891. %% {Tokens, Result}
  892. Tests = [
  893. {<<"\"xyzzy\"">>, [{strong, <<"xyzzy">>}]},
  894. {<<"\"xyzzy\", W/\"r2d2xxxx\", \"c3piozzzz\"">>,
  895. [{strong, <<"xyzzy">>},
  896. {weak, <<"r2d2xxxx">>},
  897. {strong, <<"c3piozzzz">>}]},
  898. {<<"*">>, '*'}
  899. ],
  900. [{V, fun() -> R = entity_tag_match(V) end} || {V, R} <- Tests].
  901. http_date_test_() ->
  902. %% {Tokens, Result}
  903. Tests = [
  904. {<<"Sun, 06 Nov 1994 08:49:37 GMT">>, {{1994, 11, 6}, {8, 49, 37}}},
  905. {<<"Sunday, 06-Nov-94 08:49:37 GMT">>, {{1994, 11, 6}, {8, 49, 37}}},
  906. {<<"Sun Nov 6 08:49:37 1994">>, {{1994, 11, 6}, {8, 49, 37}}}
  907. ],
  908. [{V, fun() -> R = http_date(V) end} || {V, R} <- Tests].
  909. rfc1123_date_test_() ->
  910. %% {Tokens, Result}
  911. Tests = [
  912. {<<"Sun, 06 Nov 1994 08:49:37 GMT">>, {{1994, 11, 6}, {8, 49, 37}}}
  913. ],
  914. [{V, fun() -> R = rfc1123_date(V) end} || {V, R} <- Tests].
  915. rfc850_date_test_() ->
  916. %% {Tokens, Result}
  917. Tests = [
  918. {<<"Sunday, 06-Nov-94 08:49:37 GMT">>, {{1994, 11, 6}, {8, 49, 37}}}
  919. ],
  920. [{V, fun() -> R = rfc850_date(V) end} || {V, R} <- Tests].
  921. asctime_date_test_() ->
  922. %% {Tokens, Result}
  923. Tests = [
  924. {<<"Sun Nov 6 08:49:37 1994">>, {{1994, 11, 6}, {8, 49, 37}}}
  925. ],
  926. [{V, fun() -> R = asctime_date(V) end} || {V, R} <- Tests].
  927. content_type_test_() ->
  928. %% {ContentType, Result}
  929. Tests = [
  930. {<<"text/plain; charset=iso-8859-4">>,
  931. {<<"text">>, <<"plain">>, [{<<"charset">>, <<"iso-8859-4">>}]}},
  932. {<<"multipart/form-data \t;Boundary=\"MultipartIsUgly\"">>,
  933. {<<"multipart">>, <<"form-data">>, [
  934. {<<"boundary">>, <<"MultipartIsUgly">>}
  935. ]}},
  936. {<<"foo/bar; one=FirstParam; two=SecondParam">>,
  937. {<<"foo">>, <<"bar">>, [
  938. {<<"one">>, <<"FirstParam">>},
  939. {<<"two">>, <<"SecondParam">>}
  940. ]}}
  941. ],
  942. [{V, fun () -> R = content_type(V) end} || {V, R} <- Tests].
  943. digits_test_() ->
  944. %% {Digits, Result}
  945. Tests = [
  946. {<<"42 ">>, 42},
  947. {<<"69\t">>, 69},
  948. {<<"1337">>, 1337}
  949. ],
  950. [{V, fun() -> R = digits(V) end} || {V, R} <- Tests].
  951. x_www_form_urlencoded_test_() ->
  952. %% {Qs, Result}
  953. Tests = [
  954. {<<"">>, []},
  955. {<<"a=b">>, [{<<"a">>, <<"b">>}]},
  956. {<<"aaa=bbb">>, [{<<"aaa">>, <<"bbb">>}]},
  957. {<<"a&b">>, [{<<"a">>, true}, {<<"b">>, true}]},
  958. {<<"a=b&c&d=e">>, [{<<"a">>, <<"b">>},
  959. {<<"c">>, true}, {<<"d">>, <<"e">>}]},
  960. {<<"a=b=c=d=e&f=g">>, [{<<"a">>, <<"b=c=d=e">>}, {<<"f">>, <<"g">>}]},
  961. {<<"a+b=c+d">>, [{<<"a b">>, <<"c d">>}]}
  962. ],
  963. [{Qs, fun() -> R = x_www_form_urlencoded(Qs) end} || {Qs, R} <- Tests].
  964. urldecode_test_() ->
  965. U = fun urldecode/2,
  966. [?_assertEqual(<<" ">>, U(<<"%20">>, crash)),
  967. ?_assertEqual(<<" ">>, U(<<"+">>, crash)),
  968. ?_assertEqual(<<0>>, U(<<"%00">>, crash)),
  969. ?_assertEqual(<<255>>, U(<<"%fF">>, crash)),
  970. ?_assertEqual(<<"123">>, U(<<"123">>, crash)),
  971. ?_assertEqual(<<"%i5">>, U(<<"%i5">>, skip)),
  972. ?_assertEqual(<<"%5">>, U(<<"%5">>, skip)),
  973. ?_assertError(badarg, U(<<"%i5">>, crash)),
  974. ?_assertError(badarg, U(<<"%5">>, crash))
  975. ].
  976. urlencode_test_() ->
  977. U = fun urlencode/2,
  978. [?_assertEqual(<<"%ff%00">>, U(<<255,0>>, [])),
  979. ?_assertEqual(<<"%FF%00">>, U(<<255,0>>, [upper])),
  980. ?_assertEqual(<<"+">>, U(<<" ">>, [])),
  981. ?_assertEqual(<<"%20">>, U(<<" ">>, [noplus])),
  982. ?_assertEqual(<<"aBc">>, U(<<"aBc">>, [])),
  983. ?_assertEqual(<<".-~_">>, U(<<".-~_">>, [])),
  984. ?_assertEqual(<<"%ff+">>, urlencode(<<255, " ">>))
  985. ].
  986. -endif.