cowboy_http.erl 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292
  1. %% Copyright (c) 2011-2013, 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. -export([authorization/2]).
  37. -export([range/1]).
  38. -export([parameterized_tokens/1]).
  39. %% Decoding.
  40. -export([te_chunked/2]).
  41. -export([te_identity/2]).
  42. -export([ce_identity/1]).
  43. %% Interpretation.
  44. -export([urldecode/1]).
  45. -export([urldecode/2]).
  46. -export([urlencode/1]).
  47. -export([urlencode/2]).
  48. %% Parsing.
  49. %% @doc Parse a non-empty list of the given type.
  50. -spec nonempty_list(binary(), fun()) -> [any(), ...] | {error, badarg}.
  51. nonempty_list(Data, Fun) ->
  52. case list(Data, Fun, []) of
  53. {error, badarg} -> {error, badarg};
  54. [] -> {error, badarg};
  55. L -> lists:reverse(L)
  56. end.
  57. %% @doc Parse a list of the given type.
  58. -spec list(binary(), fun()) -> list() | {error, badarg}.
  59. list(Data, Fun) ->
  60. case list(Data, Fun, []) of
  61. {error, badarg} -> {error, badarg};
  62. L -> lists:reverse(L)
  63. end.
  64. -spec list(binary(), fun(), [binary()]) -> [any()] | {error, badarg}.
  65. %% From the RFC:
  66. %% <blockquote>Wherever this construct is used, null elements are allowed,
  67. %% but do not contribute to the count of elements present.
  68. %% That is, "(element), , (element) " is permitted, but counts
  69. %% as only two elements. Therefore, where at least one element is required,
  70. %% at least one non-null element MUST be present.</blockquote>
  71. list(Data, Fun, Acc) ->
  72. whitespace(Data,
  73. fun (<<>>) -> Acc;
  74. (<< $,, Rest/binary >>) -> list(Rest, Fun, Acc);
  75. (Rest) -> Fun(Rest,
  76. fun (D, I) -> whitespace(D,
  77. fun (<<>>) -> [I|Acc];
  78. (<< $,, R/binary >>) -> list(R, Fun, [I|Acc]);
  79. (_Any) -> {error, badarg}
  80. end)
  81. end)
  82. end).
  83. %% @doc Parse a content type.
  84. %%
  85. %% We lowercase the charset header as we know it's case insensitive.
  86. -spec content_type(binary()) -> any().
  87. content_type(Data) ->
  88. media_type(Data,
  89. fun (Rest, Type, SubType) ->
  90. params(Rest,
  91. fun (<<>>, Params) ->
  92. case lists:keyfind(<<"charset">>, 1, Params) of
  93. false ->
  94. {Type, SubType, Params};
  95. {_, Charset} ->
  96. Charset2 = cowboy_bstr:to_lower(Charset),
  97. Params2 = lists:keyreplace(<<"charset">>,
  98. 1, Params, {<<"charset">>, Charset2}),
  99. {Type, SubType, Params2}
  100. end;
  101. (_Rest2, _) ->
  102. {error, badarg}
  103. end)
  104. end).
  105. %% @doc Parse a media range.
  106. -spec media_range(binary(), fun()) -> any().
  107. media_range(Data, Fun) ->
  108. media_type(Data,
  109. fun (Rest, Type, SubType) ->
  110. media_range_params(Rest, Fun, Type, SubType, [])
  111. end).
  112. -spec media_range_params(binary(), fun(), binary(), binary(),
  113. [{binary(), binary()}]) -> any().
  114. media_range_params(Data, Fun, Type, SubType, Acc) ->
  115. whitespace(Data,
  116. fun (<< $;, Rest/binary >>) ->
  117. whitespace(Rest,
  118. fun (Rest2) ->
  119. media_range_param_attr(Rest2, Fun, Type, SubType, Acc)
  120. end);
  121. (Rest) -> Fun(Rest, {{Type, SubType, lists:reverse(Acc)}, 1000, []})
  122. end).
  123. -spec media_range_param_attr(binary(), fun(), binary(), binary(),
  124. [{binary(), binary()}]) -> any().
  125. media_range_param_attr(Data, Fun, Type, SubType, Acc) ->
  126. token_ci(Data,
  127. fun (_Rest, <<>>) -> {error, badarg};
  128. (<< $=, Rest/binary >>, Attr) ->
  129. media_range_param_value(Rest, Fun, Type, SubType, Acc, Attr)
  130. end).
  131. -spec media_range_param_value(binary(), fun(), binary(), binary(),
  132. [{binary(), binary()}], binary()) -> any().
  133. media_range_param_value(Data, Fun, Type, SubType, Acc, <<"q">>) ->
  134. qvalue(Data,
  135. fun (Rest, Quality) ->
  136. accept_ext(Rest, Fun, Type, SubType, Acc, Quality, [])
  137. end);
  138. media_range_param_value(Data, Fun, Type, SubType, Acc, Attr) ->
  139. word(Data,
  140. fun (Rest, Value) ->
  141. media_range_params(Rest, Fun,
  142. Type, SubType, [{Attr, Value}|Acc])
  143. end).
  144. %% @doc Parse a media type.
  145. -spec media_type(binary(), fun()) -> any().
  146. media_type(Data, Fun) ->
  147. token_ci(Data,
  148. fun (_Rest, <<>>) -> {error, badarg};
  149. (<< $/, Rest/binary >>, Type) ->
  150. token_ci(Rest,
  151. fun (_Rest2, <<>>) -> {error, badarg};
  152. (Rest2, SubType) -> Fun(Rest2, Type, SubType)
  153. end);
  154. %% This is a non-strict parsing clause required by some user agents
  155. %% that use * instead of */* in the list of media types.
  156. (Rest, <<"*">> = Type) ->
  157. token_ci(<<"*", Rest/binary>>,
  158. fun (_Rest2, <<>>) -> {error, badarg};
  159. (Rest2, SubType) -> Fun(Rest2, Type, SubType)
  160. end);
  161. (_Rest, _Type) -> {error, badarg}
  162. end).
  163. -spec accept_ext(binary(), fun(), binary(), binary(),
  164. [{binary(), binary()}], 0..1000,
  165. [{binary(), binary()} | binary()]) -> any().
  166. accept_ext(Data, Fun, Type, SubType, Params, Quality, Acc) ->
  167. whitespace(Data,
  168. fun (<< $;, Rest/binary >>) ->
  169. whitespace(Rest,
  170. fun (Rest2) ->
  171. accept_ext_attr(Rest2, Fun,
  172. Type, SubType, Params, Quality, Acc)
  173. end);
  174. (Rest) ->
  175. Fun(Rest, {{Type, SubType, lists:reverse(Params)},
  176. Quality, lists:reverse(Acc)})
  177. end).
  178. -spec accept_ext_attr(binary(), fun(), binary(), binary(),
  179. [{binary(), binary()}], 0..1000,
  180. [{binary(), binary()} | binary()]) -> any().
  181. accept_ext_attr(Data, Fun, Type, SubType, Params, Quality, Acc) ->
  182. token_ci(Data,
  183. fun (_Rest, <<>>) -> {error, badarg};
  184. (<< $=, Rest/binary >>, Attr) ->
  185. accept_ext_value(Rest, Fun, Type, SubType, Params,
  186. Quality, Acc, Attr);
  187. (Rest, Attr) ->
  188. accept_ext(Rest, Fun, Type, SubType, Params,
  189. Quality, [Attr|Acc])
  190. end).
  191. -spec accept_ext_value(binary(), fun(), binary(), binary(),
  192. [{binary(), binary()}], 0..1000,
  193. [{binary(), binary()} | binary()], binary()) -> any().
  194. accept_ext_value(Data, Fun, Type, SubType, Params, Quality, Acc, Attr) ->
  195. word(Data,
  196. fun (Rest, Value) ->
  197. accept_ext(Rest, Fun,
  198. Type, SubType, Params, Quality, [{Attr, Value}|Acc])
  199. end).
  200. %% @doc Parse a conneg header (Accept-Charset, Accept-Encoding),
  201. %% followed by an optional quality value.
  202. -spec conneg(binary(), fun()) -> any().
  203. conneg(Data, Fun) ->
  204. token_ci(Data,
  205. fun (_Rest, <<>>) -> {error, badarg};
  206. (Rest, Conneg) ->
  207. maybe_qparam(Rest,
  208. fun (Rest2, Quality) ->
  209. Fun(Rest2, {Conneg, Quality})
  210. end)
  211. end).
  212. %% @doc Parse a language range, followed by an optional quality value.
  213. -spec language_range(binary(), fun()) -> any().
  214. language_range(<< $*, Rest/binary >>, Fun) ->
  215. language_range_ret(Rest, Fun, '*');
  216. language_range(Data, Fun) ->
  217. language_tag(Data,
  218. fun (Rest, LanguageTag) ->
  219. language_range_ret(Rest, Fun, LanguageTag)
  220. end).
  221. -spec language_range_ret(binary(), fun(), '*' | {binary(), [binary()]}) -> any().
  222. language_range_ret(Data, Fun, LanguageTag) ->
  223. maybe_qparam(Data,
  224. fun (Rest, Quality) ->
  225. Fun(Rest, {LanguageTag, Quality})
  226. end).
  227. -spec language_tag(binary(), fun()) -> any().
  228. language_tag(Data, Fun) ->
  229. alpha(Data,
  230. fun (_Rest, Tag) when byte_size(Tag) =:= 0; byte_size(Tag) > 8 ->
  231. {error, badarg};
  232. (<< $-, Rest/binary >>, Tag) ->
  233. language_subtag(Rest, Fun, Tag, []);
  234. (Rest, Tag) ->
  235. Fun(Rest, Tag)
  236. end).
  237. -spec language_subtag(binary(), fun(), binary(), [binary()]) -> any().
  238. language_subtag(Data, Fun, Tag, Acc) ->
  239. alpha(Data,
  240. fun (_Rest, SubTag) when byte_size(SubTag) =:= 0;
  241. byte_size(SubTag) > 8 -> {error, badarg};
  242. (<< $-, Rest/binary >>, SubTag) ->
  243. language_subtag(Rest, Fun, Tag, [SubTag|Acc]);
  244. (Rest, SubTag) ->
  245. %% Rebuild the full tag now that we know it's correct
  246. Sub = << << $-, S/binary >> || S <- lists:reverse([SubTag|Acc]) >>,
  247. Fun(Rest, << Tag/binary, Sub/binary >>)
  248. end).
  249. -spec maybe_qparam(binary(), fun()) -> any().
  250. maybe_qparam(Data, Fun) ->
  251. whitespace(Data,
  252. fun (<< $;, Rest/binary >>) ->
  253. whitespace(Rest,
  254. fun (Rest2) ->
  255. %% This is a non-strict parsing clause required by some user agents
  256. %% that use the wrong delimiter putting a charset where a qparam is
  257. %% expected.
  258. try qparam(Rest2, Fun) of
  259. Result -> Result
  260. catch
  261. error:function_clause ->
  262. Fun(<<",", Rest2/binary>>, 1000)
  263. end
  264. end);
  265. (Rest) ->
  266. Fun(Rest, 1000)
  267. end).
  268. %% @doc Parse a quality parameter string (for example q=0.500).
  269. -spec qparam(binary(), fun()) -> any().
  270. qparam(<< Q, $=, Data/binary >>, Fun) when Q =:= $q; Q =:= $Q ->
  271. qvalue(Data, Fun).
  272. %% @doc Parse either a list of entity tags or a "*".
  273. -spec entity_tag_match(binary()) -> any().
  274. entity_tag_match(<< $*, Rest/binary >>) ->
  275. whitespace(Rest,
  276. fun (<<>>) -> '*';
  277. (_Any) -> {error, badarg}
  278. end);
  279. entity_tag_match(Data) ->
  280. nonempty_list(Data, fun entity_tag/2).
  281. %% @doc Parse an entity-tag.
  282. -spec entity_tag(binary(), fun()) -> any().
  283. entity_tag(<< "W/", Rest/binary >>, Fun) ->
  284. opaque_tag(Rest, Fun, weak);
  285. entity_tag(Data, Fun) ->
  286. opaque_tag(Data, Fun, strong).
  287. -spec opaque_tag(binary(), fun(), weak | strong) -> any().
  288. opaque_tag(Data, Fun, Strength) ->
  289. quoted_string(Data,
  290. fun (_Rest, <<>>) -> {error, badarg};
  291. (Rest, OpaqueTag) -> Fun(Rest, {Strength, OpaqueTag})
  292. end).
  293. %% @doc Parse an expectation.
  294. -spec expectation(binary(), fun()) -> any().
  295. expectation(Data, Fun) ->
  296. token_ci(Data,
  297. fun (_Rest, <<>>) -> {error, badarg};
  298. (<< $=, Rest/binary >>, Expectation) ->
  299. word(Rest,
  300. fun (Rest2, ExtValue) ->
  301. params(Rest2, fun (Rest3, ExtParams) ->
  302. Fun(Rest3, {Expectation, ExtValue, ExtParams})
  303. end)
  304. end);
  305. (Rest, Expectation) ->
  306. Fun(Rest, Expectation)
  307. end).
  308. %% @doc Parse a list of parameters (a=b;c=d).
  309. -spec params(binary(), fun()) -> any().
  310. params(Data, Fun) ->
  311. params(Data, Fun, []).
  312. -spec params(binary(), fun(), [{binary(), binary()}]) -> any().
  313. params(Data, Fun, Acc) ->
  314. whitespace(Data,
  315. fun (<< $;, Rest/binary >>) ->
  316. param(Rest,
  317. fun (Rest2, Attr, Value) ->
  318. params(Rest2, Fun, [{Attr, Value}|Acc])
  319. end);
  320. (Rest) ->
  321. Fun(Rest, lists:reverse(Acc))
  322. end).
  323. -spec param(binary(), fun()) -> any().
  324. param(Data, Fun) ->
  325. whitespace(Data,
  326. fun (Rest) ->
  327. token_ci(Rest,
  328. fun (_Rest2, <<>>) -> {error, badarg};
  329. (<< $=, Rest2/binary >>, Attr) ->
  330. word(Rest2,
  331. fun (Rest3, Value) ->
  332. Fun(Rest3, Attr, Value)
  333. end);
  334. (_Rest2, _Attr) -> {error, badarg}
  335. end)
  336. end).
  337. %% @doc Parse an HTTP date (RFC1123, RFC850 or asctime date).
  338. %% @end
  339. %%
  340. %% While this may not be the most efficient date parsing we can do,
  341. %% it should work fine for our purposes because all HTTP dates should
  342. %% be sent as RFC1123 dates in HTTP/1.1.
  343. -spec http_date(binary()) -> any().
  344. http_date(Data) ->
  345. case rfc1123_date(Data) of
  346. {error, badarg} ->
  347. case rfc850_date(Data) of
  348. {error, badarg} ->
  349. case asctime_date(Data) of
  350. {error, badarg} ->
  351. {error, badarg};
  352. HTTPDate ->
  353. HTTPDate
  354. end;
  355. HTTPDate ->
  356. HTTPDate
  357. end;
  358. HTTPDate ->
  359. HTTPDate
  360. end.
  361. %% @doc Parse an RFC1123 date.
  362. -spec rfc1123_date(binary()) -> any().
  363. rfc1123_date(Data) ->
  364. wkday(Data,
  365. fun (<< ", ", Rest/binary >>, _WkDay) ->
  366. date1(Rest,
  367. fun (<< " ", Rest2/binary >>, Date) ->
  368. time(Rest2,
  369. fun (<< " GMT", Rest3/binary >>, Time) ->
  370. http_date_ret(Rest3, {Date, Time});
  371. (_Any, _Time) ->
  372. {error, badarg}
  373. end);
  374. (_Any, _Date) ->
  375. {error, badarg}
  376. end);
  377. (_Any, _WkDay) ->
  378. {error, badarg}
  379. end).
  380. %% @doc Parse an RFC850 date.
  381. -spec rfc850_date(binary()) -> any().
  382. %% From the RFC:
  383. %% HTTP/1.1 clients and caches SHOULD assume that an RFC-850 date
  384. %% which appears to be more than 50 years in the future is in fact
  385. %% in the past (this helps solve the "year 2000" problem).
  386. rfc850_date(Data) ->
  387. weekday(Data,
  388. fun (<< ", ", Rest/binary >>, _WeekDay) ->
  389. date2(Rest,
  390. fun (<< " ", Rest2/binary >>, Date) ->
  391. time(Rest2,
  392. fun (<< " GMT", Rest3/binary >>, Time) ->
  393. http_date_ret(Rest3, {Date, Time});
  394. (_Any, _Time) ->
  395. {error, badarg}
  396. end);
  397. (_Any, _Date) ->
  398. {error, badarg}
  399. end);
  400. (_Any, _WeekDay) ->
  401. {error, badarg}
  402. end).
  403. %% @doc Parse an asctime date.
  404. -spec asctime_date(binary()) -> any().
  405. asctime_date(Data) ->
  406. wkday(Data,
  407. fun (<< " ", Rest/binary >>, _WkDay) ->
  408. date3(Rest,
  409. fun (<< " ", Rest2/binary >>, PartialDate) ->
  410. time(Rest2,
  411. fun (<< " ", Rest3/binary >>, Time) ->
  412. asctime_year(Rest3,
  413. PartialDate, Time);
  414. (_Any, _Time) ->
  415. {error, badarg}
  416. end);
  417. (_Any, _PartialDate) ->
  418. {error, badarg}
  419. end);
  420. (_Any, _WkDay) ->
  421. {error, badarg1}
  422. end).
  423. -spec asctime_year(binary(), tuple(), tuple()) -> any().
  424. asctime_year(<< Y1, Y2, Y3, Y4, Rest/binary >>, {Month, Day}, Time)
  425. when Y1 >= $0, Y1 =< $9, Y2 >= $0, Y2 =< $9,
  426. Y3 >= $0, Y3 =< $9, Y4 >= $0, Y4 =< $9 ->
  427. Year = (Y1 - $0) * 1000 + (Y2 - $0) * 100 + (Y3 - $0) * 10 + (Y4 - $0),
  428. http_date_ret(Rest, {{Year, Month, Day}, Time}).
  429. -spec http_date_ret(binary(), tuple()) -> any().
  430. http_date_ret(Data, DateTime = {Date, _Time}) ->
  431. whitespace(Data,
  432. fun (<<>>) ->
  433. case calendar:valid_date(Date) of
  434. true -> DateTime;
  435. false -> {error, badarg}
  436. end;
  437. (_Any) ->
  438. {error, badarg}
  439. end).
  440. %% We never use it, pretty much just checks the wkday is right.
  441. -spec wkday(binary(), fun()) -> any().
  442. wkday(<< WkDay:3/binary, Rest/binary >>, Fun)
  443. when WkDay =:= <<"Mon">>; WkDay =:= <<"Tue">>; WkDay =:= <<"Wed">>;
  444. WkDay =:= <<"Thu">>; WkDay =:= <<"Fri">>; WkDay =:= <<"Sat">>;
  445. WkDay =:= <<"Sun">> ->
  446. Fun(Rest, WkDay);
  447. wkday(_Any, _Fun) ->
  448. {error, badarg}.
  449. %% We never use it, pretty much just checks the weekday is right.
  450. -spec weekday(binary(), fun()) -> any().
  451. weekday(<< "Monday", Rest/binary >>, Fun) ->
  452. Fun(Rest, <<"Monday">>);
  453. weekday(<< "Tuesday", Rest/binary >>, Fun) ->
  454. Fun(Rest, <<"Tuesday">>);
  455. weekday(<< "Wednesday", Rest/binary >>, Fun) ->
  456. Fun(Rest, <<"Wednesday">>);
  457. weekday(<< "Thursday", Rest/binary >>, Fun) ->
  458. Fun(Rest, <<"Thursday">>);
  459. weekday(<< "Friday", Rest/binary >>, Fun) ->
  460. Fun(Rest, <<"Friday">>);
  461. weekday(<< "Saturday", Rest/binary >>, Fun) ->
  462. Fun(Rest, <<"Saturday">>);
  463. weekday(<< "Sunday", Rest/binary >>, Fun) ->
  464. Fun(Rest, <<"Sunday">>);
  465. weekday(_Any, _Fun) ->
  466. {error, badarg}.
  467. -spec date1(binary(), fun()) -> any().
  468. date1(<< D1, D2, " ", M:3/binary, " ", Y1, Y2, Y3, Y4, Rest/binary >>, Fun)
  469. when D1 >= $0, D1 =< $9, D2 >= $0, D2 =< $9,
  470. Y1 >= $0, Y1 =< $9, Y2 >= $0, Y2 =< $9,
  471. Y3 >= $0, Y3 =< $9, Y4 >= $0, Y4 =< $9 ->
  472. case month(M) of
  473. {error, badarg} ->
  474. {error, badarg};
  475. Month ->
  476. Fun(Rest, {
  477. (Y1 - $0) * 1000 + (Y2 - $0) * 100 + (Y3 - $0) * 10 + (Y4 - $0),
  478. Month,
  479. (D1 - $0) * 10 + (D2 - $0)
  480. })
  481. end;
  482. date1(_Data, _Fun) ->
  483. {error, badarg}.
  484. -spec date2(binary(), fun()) -> any().
  485. date2(<< D1, D2, "-", M:3/binary, "-", Y1, Y2, Rest/binary >>, Fun)
  486. when D1 >= $0, D1 =< $9, D2 >= $0, D2 =< $9,
  487. Y1 >= $0, Y1 =< $9, Y2 >= $0, Y2 =< $9 ->
  488. case month(M) of
  489. {error, badarg} ->
  490. {error, badarg};
  491. Month ->
  492. Year = (Y1 - $0) * 10 + (Y2 - $0),
  493. Year2 = case Year > 50 of
  494. true -> Year + 1900;
  495. false -> Year + 2000
  496. end,
  497. Fun(Rest, {
  498. Year2,
  499. Month,
  500. (D1 - $0) * 10 + (D2 - $0)
  501. })
  502. end;
  503. date2(_Data, _Fun) ->
  504. {error, badarg}.
  505. -spec date3(binary(), fun()) -> any().
  506. date3(<< M:3/binary, " ", D1, D2, Rest/binary >>, Fun)
  507. when (D1 >= $0 andalso D1 =< $3) orelse D1 =:= $\s,
  508. D2 >= $0, D2 =< $9 ->
  509. case month(M) of
  510. {error, badarg} ->
  511. {error, badarg};
  512. Month ->
  513. Day = case D1 of
  514. $\s -> D2 - $0;
  515. D1 -> (D1 - $0) * 10 + (D2 - $0)
  516. end,
  517. Fun(Rest, {Month, Day})
  518. end;
  519. date3(_Data, _Fun) ->
  520. {error, badarg}.
  521. -spec month(<< _:24 >>) -> 1..12 | {error, badarg}.
  522. month(<<"Jan">>) -> 1;
  523. month(<<"Feb">>) -> 2;
  524. month(<<"Mar">>) -> 3;
  525. month(<<"Apr">>) -> 4;
  526. month(<<"May">>) -> 5;
  527. month(<<"Jun">>) -> 6;
  528. month(<<"Jul">>) -> 7;
  529. month(<<"Aug">>) -> 8;
  530. month(<<"Sep">>) -> 9;
  531. month(<<"Oct">>) -> 10;
  532. month(<<"Nov">>) -> 11;
  533. month(<<"Dec">>) -> 12;
  534. month(_Any) -> {error, badarg}.
  535. -spec time(binary(), fun()) -> any().
  536. time(<< H1, H2, ":", M1, M2, ":", S1, S2, Rest/binary >>, Fun)
  537. when H1 >= $0, H1 =< $2, H2 >= $0, H2 =< $9,
  538. M1 >= $0, M1 =< $5, M2 >= $0, M2 =< $9,
  539. S1 >= $0, S1 =< $5, S2 >= $0, S2 =< $9 ->
  540. Hour = (H1 - $0) * 10 + (H2 - $0),
  541. case Hour < 24 of
  542. true ->
  543. Time = {
  544. Hour,
  545. (M1 - $0) * 10 + (M2 - $0),
  546. (S1 - $0) * 10 + (S2 - $0)
  547. },
  548. Fun(Rest, Time);
  549. false ->
  550. {error, badarg}
  551. end.
  552. %% @doc Skip whitespace.
  553. -spec whitespace(binary(), fun()) -> any().
  554. whitespace(<< C, Rest/binary >>, Fun)
  555. when C =:= $\s; C =:= $\t ->
  556. whitespace(Rest, Fun);
  557. whitespace(Data, Fun) ->
  558. Fun(Data).
  559. %% @doc Parse a list of digits as a non negative integer.
  560. -spec digits(binary()) -> non_neg_integer() | {error, badarg}.
  561. digits(Data) ->
  562. digits(Data,
  563. fun (Rest, I) ->
  564. whitespace(Rest,
  565. fun (<<>>) ->
  566. I;
  567. (_Rest2) ->
  568. {error, badarg}
  569. end)
  570. end).
  571. -spec digits(binary(), fun()) -> any().
  572. digits(<< C, Rest/binary >>, Fun)
  573. when C >= $0, C =< $9 ->
  574. digits(Rest, Fun, C - $0);
  575. digits(_Data, _Fun) ->
  576. {error, badarg}.
  577. -spec digits(binary(), fun(), non_neg_integer()) -> any().
  578. digits(<< C, Rest/binary >>, Fun, Acc)
  579. when C >= $0, C =< $9 ->
  580. digits(Rest, Fun, Acc * 10 + (C - $0));
  581. digits(Data, Fun, Acc) ->
  582. Fun(Data, Acc).
  583. %% @doc Parse a list of case-insensitive alpha characters.
  584. %%
  585. %% Changes all characters to lowercase.
  586. -spec alpha(binary(), fun()) -> any().
  587. alpha(Data, Fun) ->
  588. alpha(Data, Fun, <<>>).
  589. -spec alpha(binary(), fun(), binary()) -> any().
  590. alpha(<<>>, Fun, Acc) ->
  591. Fun(<<>>, Acc);
  592. alpha(<< C, Rest/binary >>, Fun, Acc)
  593. when C >= $a andalso C =< $z;
  594. C >= $A andalso C =< $Z ->
  595. C2 = cowboy_bstr:char_to_lower(C),
  596. alpha(Rest, Fun, << Acc/binary, C2 >>);
  597. alpha(Data, Fun, Acc) ->
  598. Fun(Data, Acc).
  599. %% @doc Parse either a token or a quoted string.
  600. -spec word(binary(), fun()) -> any().
  601. word(Data = << $", _/binary >>, Fun) ->
  602. quoted_string(Data, Fun);
  603. word(Data, Fun) ->
  604. token(Data,
  605. fun (_Rest, <<>>) -> {error, badarg};
  606. (Rest, Token) -> Fun(Rest, Token)
  607. end).
  608. %% @doc Parse a case-insensitive token.
  609. %%
  610. %% Changes all characters to lowercase.
  611. -spec token_ci(binary(), fun()) -> any().
  612. token_ci(Data, Fun) ->
  613. token(Data, Fun, ci, <<>>).
  614. %% @doc Parse a token.
  615. -spec token(binary(), fun()) -> any().
  616. token(Data, Fun) ->
  617. token(Data, Fun, cs, <<>>).
  618. -spec token(binary(), fun(), ci | cs, binary()) -> any().
  619. token(<<>>, Fun, _Case, Acc) ->
  620. Fun(<<>>, Acc);
  621. token(Data = << C, _Rest/binary >>, Fun, _Case, Acc)
  622. when C =:= $(; C =:= $); C =:= $<; C =:= $>; C =:= $@;
  623. C =:= $,; C =:= $;; C =:= $:; C =:= $\\; C =:= $";
  624. C =:= $/; C =:= $[; C =:= $]; C =:= $?; C =:= $=;
  625. C =:= ${; C =:= $}; C =:= $\s; C =:= $\t;
  626. C < 32; C =:= 127 ->
  627. Fun(Data, Acc);
  628. token(<< C, Rest/binary >>, Fun, Case = ci, Acc) ->
  629. C2 = cowboy_bstr:char_to_lower(C),
  630. token(Rest, Fun, Case, << Acc/binary, C2 >>);
  631. token(<< C, Rest/binary >>, Fun, Case, Acc) ->
  632. token(Rest, Fun, Case, << Acc/binary, C >>).
  633. %% @doc Parse a quoted string.
  634. -spec quoted_string(binary(), fun()) -> any().
  635. quoted_string(<< $", Rest/binary >>, Fun) ->
  636. quoted_string(Rest, Fun, <<>>).
  637. -spec quoted_string(binary(), fun(), binary()) -> any().
  638. quoted_string(<<>>, _Fun, _Acc) ->
  639. {error, badarg};
  640. quoted_string(<< $", Rest/binary >>, Fun, Acc) ->
  641. Fun(Rest, Acc);
  642. quoted_string(<< $\\, C, Rest/binary >>, Fun, Acc) ->
  643. quoted_string(Rest, Fun, << Acc/binary, C >>);
  644. quoted_string(<< C, Rest/binary >>, Fun, Acc) ->
  645. quoted_string(Rest, Fun, << Acc/binary, C >>).
  646. %% @doc Parse a quality value.
  647. -spec qvalue(binary(), fun()) -> any().
  648. qvalue(<< $0, $., Rest/binary >>, Fun) ->
  649. qvalue(Rest, Fun, 0, 100);
  650. %% Some user agents use q=.x instead of q=0.x
  651. qvalue(<< $., Rest/binary >>, Fun) ->
  652. qvalue(Rest, Fun, 0, 100);
  653. qvalue(<< $0, Rest/binary >>, Fun) ->
  654. Fun(Rest, 0);
  655. qvalue(<< $1, $., $0, $0, $0, Rest/binary >>, Fun) ->
  656. Fun(Rest, 1000);
  657. qvalue(<< $1, $., $0, $0, Rest/binary >>, Fun) ->
  658. Fun(Rest, 1000);
  659. qvalue(<< $1, $., $0, Rest/binary >>, Fun) ->
  660. Fun(Rest, 1000);
  661. qvalue(<< $1, Rest/binary >>, Fun) ->
  662. Fun(Rest, 1000);
  663. qvalue(_Data, _Fun) ->
  664. {error, badarg}.
  665. -spec qvalue(binary(), fun(), integer(), 1 | 10 | 100) -> any().
  666. qvalue(Data, Fun, Q, 0) ->
  667. Fun(Data, Q);
  668. qvalue(<< C, Rest/binary >>, Fun, Q, M)
  669. when C >= $0, C =< $9 ->
  670. qvalue(Rest, Fun, Q + (C - $0) * M, M div 10);
  671. qvalue(Data, Fun, Q, _M) ->
  672. Fun(Data, Q).
  673. %% @doc Parse authorization value according rfc 2617.
  674. %% Only Basic authorization is supported so far.
  675. -spec authorization(binary(), binary()) -> {binary(), any()} | {error, badarg}.
  676. authorization(UserPass, Type = <<"basic">>) ->
  677. whitespace(UserPass,
  678. fun(D) ->
  679. authorization_basic_userid(base64:mime_decode(D),
  680. fun(Rest, Userid) ->
  681. authorization_basic_password(Rest,
  682. fun(Password) ->
  683. {Type, {Userid, Password}}
  684. end)
  685. end)
  686. end);
  687. authorization(String, Type) ->
  688. whitespace(String, fun(Rest) -> {Type, Rest} end).
  689. %% @doc Parse user credentials.
  690. -spec authorization_basic_userid(binary(), fun()) -> any().
  691. authorization_basic_userid(Data, Fun) ->
  692. authorization_basic_userid(Data, Fun, <<>>).
  693. authorization_basic_userid(<<>>, _Fun, _Acc) ->
  694. {error, badarg};
  695. authorization_basic_userid(<<C, _Rest/binary>>, _Fun, Acc)
  696. when C < 32; C =:= 127; (C =:=$: andalso Acc =:= <<>>) ->
  697. {error, badarg};
  698. authorization_basic_userid(<<$:, Rest/binary>>, Fun, Acc) ->
  699. Fun(Rest, Acc);
  700. authorization_basic_userid(<<C, Rest/binary>>, Fun, Acc) ->
  701. authorization_basic_userid(Rest, Fun, <<Acc/binary, C>>).
  702. -spec authorization_basic_password(binary(), fun()) -> any().
  703. authorization_basic_password(Data, Fun) ->
  704. authorization_basic_password(Data, Fun, <<>>).
  705. authorization_basic_password(<<>>, _Fun, <<>>) ->
  706. {error, badarg};
  707. authorization_basic_password(<<C, _Rest/binary>>, _Fun, _Acc)
  708. when C < 32; C=:= 127 ->
  709. {error, badarg};
  710. authorization_basic_password(<<>>, Fun, Acc) ->
  711. Fun(Acc);
  712. authorization_basic_password(<<C, Rest/binary>>, Fun, Acc) ->
  713. authorization_basic_password(Rest, Fun, <<Acc/binary, C>>).
  714. %% @doc Parse range header according rfc 2616.
  715. -spec range(binary()) -> {Unit, [Range]} | {error, badarg} when
  716. Unit :: binary(),
  717. Range :: {non_neg_integer(), non_neg_integer() | infinity} | neg_integer().
  718. range(Data) ->
  719. token_ci(Data, fun range/2).
  720. range(Data, Token) ->
  721. whitespace(Data,
  722. fun(<<"=", Rest/binary>>) ->
  723. case list(Rest, fun range_beginning/2) of
  724. {error, badarg} ->
  725. {error, badarg};
  726. Ranges ->
  727. {Token, Ranges}
  728. end;
  729. (_) ->
  730. {error, badarg}
  731. end).
  732. range_beginning(Data, Fun) ->
  733. range_digits(Data, suffix,
  734. fun(D, RangeBeginning) ->
  735. range_ending(D, Fun, RangeBeginning)
  736. end).
  737. range_ending(Data, Fun, RangeBeginning) ->
  738. whitespace(Data,
  739. fun(<<"-", R/binary>>) ->
  740. case RangeBeginning of
  741. suffix ->
  742. range_digits(R, fun(D, RangeEnding) -> Fun(D, -RangeEnding) end);
  743. _ ->
  744. range_digits(R, infinity,
  745. fun(D, RangeEnding) ->
  746. Fun(D, {RangeBeginning, RangeEnding})
  747. end)
  748. end;
  749. (_) ->
  750. {error, badarg}
  751. end).
  752. -spec range_digits(binary(), fun()) -> any().
  753. range_digits(Data, Fun) ->
  754. whitespace(Data,
  755. fun(D) ->
  756. digits(D, Fun)
  757. end).
  758. -spec range_digits(binary(), any(), fun()) -> any().
  759. range_digits(Data, Default, Fun) ->
  760. whitespace(Data,
  761. fun(<< C, Rest/binary >>) when C >= $0, C =< $9 ->
  762. digits(Rest, Fun, C - $0);
  763. (_) ->
  764. Fun(Data, Default)
  765. end).
  766. %% @doc Parse a non empty list of tokens followed with optional parameters.
  767. -spec parameterized_tokens(binary()) -> any().
  768. parameterized_tokens(Data) ->
  769. nonempty_list(Data,
  770. fun (D, Fun) ->
  771. token(D,
  772. fun (_Rest, <<>>) -> {error, badarg};
  773. (Rest, Token) ->
  774. parameterized_tokens_params(Rest,
  775. fun (Rest2, Params) ->
  776. Fun(Rest2, {Token, Params})
  777. end, [])
  778. end)
  779. end).
  780. -spec parameterized_tokens_params(binary(), fun(), [binary() | {binary(), binary()}]) -> any().
  781. parameterized_tokens_params(Data, Fun, Acc) ->
  782. whitespace(Data,
  783. fun (<< $;, Rest/binary >>) ->
  784. parameterized_tokens_param(Rest,
  785. fun (Rest2, Param) ->
  786. parameterized_tokens_params(Rest2, Fun, [Param|Acc])
  787. end);
  788. (Rest) ->
  789. Fun(Rest, lists:reverse(Acc))
  790. end).
  791. -spec parameterized_tokens_param(binary(), fun()) -> any().
  792. parameterized_tokens_param(Data, Fun) ->
  793. whitespace(Data,
  794. fun (Rest) ->
  795. token(Rest,
  796. fun (_Rest2, <<>>) -> {error, badarg};
  797. (<< $=, Rest2/binary >>, Attr) ->
  798. word(Rest2,
  799. fun (Rest3, Value) ->
  800. Fun(Rest3, {Attr, Value})
  801. end);
  802. (Rest2, Attr) ->
  803. Fun(Rest2, Attr)
  804. end)
  805. end).
  806. %% Decoding.
  807. %% @doc Decode a stream of chunks.
  808. -spec te_chunked(Bin, TransferState)
  809. -> more | {more, non_neg_integer(), Bin, TransferState}
  810. | {ok, Bin, Bin, TransferState}
  811. | {done, non_neg_integer(), Bin} | {error, badarg}
  812. when Bin::binary(), TransferState::{non_neg_integer(), non_neg_integer()}.
  813. te_chunked(<< "0\r\n\r\n", Rest/binary >>, {0, Streamed}) ->
  814. {done, Streamed, Rest};
  815. te_chunked(Data, {0, Streamed}) ->
  816. %% @todo We are expecting an hex size, not a general token.
  817. token(Data,
  818. fun (<< "\r\n", Rest/binary >>, BinLen) ->
  819. case list_to_integer(binary_to_list(BinLen), 16) of
  820. %% Final chunk is parsed in one go above. Rest would be
  821. %% <<\r\n">> if complete.
  822. 0 when byte_size(Rest) < 2 ->
  823. more;
  824. %% Normal chunk. Add 2 to Len for trailing <<"\r\n">>. Note
  825. %% that repeated <<"-2\r\n">> would be streamed, and
  826. %% accumulated, until out of memory if Len could be -2.
  827. Len when Len > 0 ->
  828. te_chunked(Rest, {Len + 2, Streamed})
  829. end;
  830. %% Chunk size shouldn't take too many bytes,
  831. %% don't try to stream forever.
  832. (Rest, _) when byte_size(Rest) < 16 ->
  833. more;
  834. (_, _) ->
  835. {error, badarg}
  836. end);
  837. %% <<"\n">> from trailing <<"\r\n">>.
  838. te_chunked(<< "\n", Rest/binary>>, {1, Streamed}) ->
  839. {ok, <<>>, Rest, {0, Streamed}};
  840. te_chunked(<<>>, State={1, _Streamed}) ->
  841. {more, 1, <<>>, State};
  842. %% Remainder of chunk (if any) and as much of trailing <<"\r\n">> as possible.
  843. te_chunked(Data, {ChunkRem, Streamed}) when byte_size(Data) >= ChunkRem - 2 ->
  844. ChunkSize = ChunkRem - 2,
  845. Streamed2 = Streamed + ChunkSize,
  846. case Data of
  847. << Chunk:ChunkSize/binary, "\r\n", Rest/binary >> ->
  848. {ok, Chunk, Rest, {0, Streamed2}};
  849. << Chunk:ChunkSize/binary, "\r" >> ->
  850. {more, 1, Chunk, {1, Streamed2}};
  851. << Chunk:ChunkSize/binary >> ->
  852. {more, 2, Chunk, {2, Streamed2}}
  853. end;
  854. %% Incomplete chunk.
  855. te_chunked(Data, {ChunkRem, Streamed}) ->
  856. ChunkRem2 = ChunkRem - byte_size(Data),
  857. Streamed2 = Streamed + byte_size(Data),
  858. {more, ChunkRem2, Data, {ChunkRem2, Streamed2}}.
  859. %% @doc Decode an identity stream.
  860. -spec te_identity(Bin, TransferState)
  861. -> {more, non_neg_integer(), Bin, TransferState}
  862. | {done, Bin, non_neg_integer(), Bin}
  863. when Bin::binary(), TransferState::{non_neg_integer(), non_neg_integer()}.
  864. te_identity(Data, {Streamed, Total})
  865. when Streamed + byte_size(Data) < Total ->
  866. Streamed2 = Streamed + byte_size(Data),
  867. {more, Total - Streamed2, Data, {Streamed2, Total}};
  868. te_identity(Data, {Streamed, Total}) ->
  869. Size = Total - Streamed,
  870. << Data2:Size/binary, Rest/binary >> = Data,
  871. {done, Data2, Total, Rest}.
  872. %% @doc Decode an identity content.
  873. -spec ce_identity(binary()) -> {ok, binary()}.
  874. ce_identity(Data) ->
  875. {ok, Data}.
  876. %% Interpretation.
  877. %% @doc Decode a URL encoded binary.
  878. %% @equiv urldecode(Bin, crash)
  879. -spec urldecode(binary()) -> binary().
  880. urldecode(Bin) when is_binary(Bin) ->
  881. urldecode(Bin, <<>>, crash).
  882. %% @doc Decode a URL encoded binary.
  883. %% The second argument specifies how to handle percent characters that are not
  884. %% followed by two valid hex characters. Use `skip' to ignore such errors,
  885. %% if `crash' is used the function will fail with the reason `badarg'.
  886. -spec urldecode(binary(), crash | skip) -> binary().
  887. urldecode(Bin, OnError) when is_binary(Bin) ->
  888. urldecode(Bin, <<>>, OnError).
  889. -spec urldecode(binary(), binary(), crash | skip) -> binary().
  890. urldecode(<<$%, H, L, Rest/binary>>, Acc, OnError) ->
  891. G = unhex(H),
  892. M = unhex(L),
  893. if G =:= error; M =:= error ->
  894. case OnError of skip -> ok; crash -> erlang:error(badarg) end,
  895. urldecode(<<H, L, Rest/binary>>, <<Acc/binary, $%>>, OnError);
  896. true ->
  897. urldecode(Rest, <<Acc/binary, (G bsl 4 bor M)>>, OnError)
  898. end;
  899. urldecode(<<$%, Rest/binary>>, Acc, OnError) ->
  900. case OnError of skip -> ok; crash -> erlang:error(badarg) end,
  901. urldecode(Rest, <<Acc/binary, $%>>, OnError);
  902. urldecode(<<$+, Rest/binary>>, Acc, OnError) ->
  903. urldecode(Rest, <<Acc/binary, $ >>, OnError);
  904. urldecode(<<C, Rest/binary>>, Acc, OnError) ->
  905. urldecode(Rest, <<Acc/binary, C>>, OnError);
  906. urldecode(<<>>, Acc, _OnError) ->
  907. Acc.
  908. -spec unhex(byte()) -> byte() | error.
  909. unhex(C) when C >= $0, C =< $9 -> C - $0;
  910. unhex(C) when C >= $A, C =< $F -> C - $A + 10;
  911. unhex(C) when C >= $a, C =< $f -> C - $a + 10;
  912. unhex(_) -> error.
  913. %% @doc URL encode a string binary.
  914. %% @equiv urlencode(Bin, [])
  915. -spec urlencode(binary()) -> binary().
  916. urlencode(Bin) ->
  917. urlencode(Bin, []).
  918. %% @doc URL encode a string binary.
  919. %% The `noplus' option disables the default behaviour of quoting space
  920. %% characters, `\s', as `+'. The `upper' option overrides the default behaviour
  921. %% of writing hex numbers using lowecase letters to using uppercase letters
  922. %% instead.
  923. -spec urlencode(binary(), [noplus|upper]) -> binary().
  924. urlencode(Bin, Opts) ->
  925. Plus = not lists:member(noplus, Opts),
  926. Upper = lists:member(upper, Opts),
  927. urlencode(Bin, <<>>, Plus, Upper).
  928. -spec urlencode(binary(), binary(), boolean(), boolean()) -> binary().
  929. urlencode(<<C, Rest/binary>>, Acc, P=Plus, U=Upper) ->
  930. if C >= $0, C =< $9 -> urlencode(Rest, <<Acc/binary, C>>, P, U);
  931. C >= $A, C =< $Z -> urlencode(Rest, <<Acc/binary, C>>, P, U);
  932. C >= $a, C =< $z -> urlencode(Rest, <<Acc/binary, C>>, P, U);
  933. C =:= $.; C =:= $-; C =:= $~; C =:= $_ ->
  934. urlencode(Rest, <<Acc/binary, C>>, P, U);
  935. C =:= $ , Plus ->
  936. urlencode(Rest, <<Acc/binary, $+>>, P, U);
  937. true ->
  938. H = C band 16#F0 bsr 4, L = C band 16#0F,
  939. H1 = if Upper -> tohexu(H); true -> tohexl(H) end,
  940. L1 = if Upper -> tohexu(L); true -> tohexl(L) end,
  941. urlencode(Rest, <<Acc/binary, $%, H1, L1>>, P, U)
  942. end;
  943. urlencode(<<>>, Acc, _Plus, _Upper) ->
  944. Acc.
  945. -spec tohexu(byte()) -> byte().
  946. tohexu(C) when C < 10 -> $0 + C;
  947. tohexu(C) when C < 17 -> $A + C - 10.
  948. -spec tohexl(byte()) -> byte().
  949. tohexl(C) when C < 10 -> $0 + C;
  950. tohexl(C) when C < 17 -> $a + C - 10.
  951. %% Tests.
  952. -ifdef(TEST).
  953. nonempty_charset_list_test_() ->
  954. %% {Value, Result}
  955. Tests = [
  956. {<<>>, {error, badarg}},
  957. {<<"iso-8859-5, unicode-1-1;q=0.8">>, [
  958. {<<"iso-8859-5">>, 1000},
  959. {<<"unicode-1-1">>, 800}
  960. ]},
  961. %% Some user agents send this invalid value for the Accept-Charset header
  962. {<<"ISO-8859-1;utf-8;q=0.7,*;q=0.7">>, [
  963. {<<"iso-8859-1">>, 1000},
  964. {<<"utf-8">>, 700},
  965. {<<"*">>, 700}
  966. ]}
  967. ],
  968. [{V, fun() -> R = nonempty_list(V, fun conneg/2) end} || {V, R} <- Tests].
  969. nonempty_language_range_list_test_() ->
  970. %% {Value, Result}
  971. Tests = [
  972. {<<"da, en-gb;q=0.8, en;q=0.7">>, [
  973. {<<"da">>, 1000},
  974. {<<"en-gb">>, 800},
  975. {<<"en">>, 700}
  976. ]},
  977. {<<"en, en-US, en-cockney, i-cherokee, x-pig-latin">>, [
  978. {<<"en">>, 1000},
  979. {<<"en-us">>, 1000},
  980. {<<"en-cockney">>, 1000},
  981. {<<"i-cherokee">>, 1000},
  982. {<<"x-pig-latin">>, 1000}
  983. ]}
  984. ],
  985. [{V, fun() -> R = nonempty_list(V, fun language_range/2) end}
  986. || {V, R} <- Tests].
  987. nonempty_token_list_test_() ->
  988. %% {Value, Result}
  989. Tests = [
  990. {<<>>, {error, badarg}},
  991. {<<" ">>, {error, badarg}},
  992. {<<" , ">>, {error, badarg}},
  993. {<<",,,">>, {error, badarg}},
  994. {<<"a b">>, {error, badarg}},
  995. {<<"a , , , ">>, [<<"a">>]},
  996. {<<" , , , a">>, [<<"a">>]},
  997. {<<"a, , b">>, [<<"a">>, <<"b">>]},
  998. {<<"close">>, [<<"close">>]},
  999. {<<"keep-alive, upgrade">>, [<<"keep-alive">>, <<"upgrade">>]}
  1000. ],
  1001. [{V, fun() -> R = nonempty_list(V, fun token/2) end} || {V, R} <- Tests].
  1002. media_range_list_test_() ->
  1003. %% {Tokens, Result}
  1004. Tests = [
  1005. {<<"audio/*; q=0.2, audio/basic">>, [
  1006. {{<<"audio">>, <<"*">>, []}, 200, []},
  1007. {{<<"audio">>, <<"basic">>, []}, 1000, []}
  1008. ]},
  1009. {<<"text/plain; q=0.5, text/html, "
  1010. "text/x-dvi; q=0.8, text/x-c">>, [
  1011. {{<<"text">>, <<"plain">>, []}, 500, []},
  1012. {{<<"text">>, <<"html">>, []}, 1000, []},
  1013. {{<<"text">>, <<"x-dvi">>, []}, 800, []},
  1014. {{<<"text">>, <<"x-c">>, []}, 1000, []}
  1015. ]},
  1016. {<<"text/*, text/html, text/html;level=1, */*">>, [
  1017. {{<<"text">>, <<"*">>, []}, 1000, []},
  1018. {{<<"text">>, <<"html">>, []}, 1000, []},
  1019. {{<<"text">>, <<"html">>, [{<<"level">>, <<"1">>}]}, 1000, []},
  1020. {{<<"*">>, <<"*">>, []}, 1000, []}
  1021. ]},
  1022. {<<"text/*;q=0.3, text/html;q=0.7, text/html;level=1, "
  1023. "text/html;level=2;q=0.4, */*;q=0.5">>, [
  1024. {{<<"text">>, <<"*">>, []}, 300, []},
  1025. {{<<"text">>, <<"html">>, []}, 700, []},
  1026. {{<<"text">>, <<"html">>, [{<<"level">>, <<"1">>}]}, 1000, []},
  1027. {{<<"text">>, <<"html">>, [{<<"level">>, <<"2">>}]}, 400, []},
  1028. {{<<"*">>, <<"*">>, []}, 500, []}
  1029. ]},
  1030. {<<"text/html;level=1;quoted=\"hi hi hi\";"
  1031. "q=0.123;standalone;complex=gits, text/plain">>, [
  1032. {{<<"text">>, <<"html">>,
  1033. [{<<"level">>, <<"1">>}, {<<"quoted">>, <<"hi hi hi">>}]}, 123,
  1034. [<<"standalone">>, {<<"complex">>, <<"gits">>}]},
  1035. {{<<"text">>, <<"plain">>, []}, 1000, []}
  1036. ]},
  1037. {<<"text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2">>, [
  1038. {{<<"text">>, <<"html">>, []}, 1000, []},
  1039. {{<<"image">>, <<"gif">>, []}, 1000, []},
  1040. {{<<"image">>, <<"jpeg">>, []}, 1000, []},
  1041. {{<<"*">>, <<"*">>, []}, 200, []},
  1042. {{<<"*">>, <<"*">>, []}, 200, []}
  1043. ]}
  1044. ],
  1045. [{V, fun() -> R = list(V, fun media_range/2) end} || {V, R} <- Tests].
  1046. entity_tag_match_test_() ->
  1047. %% {Tokens, Result}
  1048. Tests = [
  1049. {<<"\"xyzzy\"">>, [{strong, <<"xyzzy">>}]},
  1050. {<<"\"xyzzy\", W/\"r2d2xxxx\", \"c3piozzzz\"">>,
  1051. [{strong, <<"xyzzy">>},
  1052. {weak, <<"r2d2xxxx">>},
  1053. {strong, <<"c3piozzzz">>}]},
  1054. {<<"*">>, '*'}
  1055. ],
  1056. [{V, fun() -> R = entity_tag_match(V) end} || {V, R} <- Tests].
  1057. http_date_test_() ->
  1058. %% {Tokens, Result}
  1059. Tests = [
  1060. {<<"Sun, 06 Nov 1994 08:49:37 GMT">>, {{1994, 11, 6}, {8, 49, 37}}},
  1061. {<<"Sunday, 06-Nov-94 08:49:37 GMT">>, {{1994, 11, 6}, {8, 49, 37}}},
  1062. {<<"Sun Nov 6 08:49:37 1994">>, {{1994, 11, 6}, {8, 49, 37}}}
  1063. ],
  1064. [{V, fun() -> R = http_date(V) end} || {V, R} <- Tests].
  1065. rfc1123_date_test_() ->
  1066. %% {Tokens, Result}
  1067. Tests = [
  1068. {<<"Sun, 06 Nov 1994 08:49:37 GMT">>, {{1994, 11, 6}, {8, 49, 37}}}
  1069. ],
  1070. [{V, fun() -> R = rfc1123_date(V) end} || {V, R} <- Tests].
  1071. rfc850_date_test_() ->
  1072. %% {Tokens, Result}
  1073. Tests = [
  1074. {<<"Sunday, 06-Nov-94 08:49:37 GMT">>, {{1994, 11, 6}, {8, 49, 37}}}
  1075. ],
  1076. [{V, fun() -> R = rfc850_date(V) end} || {V, R} <- Tests].
  1077. asctime_date_test_() ->
  1078. %% {Tokens, Result}
  1079. Tests = [
  1080. {<<"Sun Nov 6 08:49:37 1994">>, {{1994, 11, 6}, {8, 49, 37}}}
  1081. ],
  1082. [{V, fun() -> R = asctime_date(V) end} || {V, R} <- Tests].
  1083. content_type_test_() ->
  1084. %% {ContentType, Result}
  1085. Tests = [
  1086. {<<"text/plain; charset=iso-8859-4">>,
  1087. {<<"text">>, <<"plain">>, [{<<"charset">>, <<"iso-8859-4">>}]}},
  1088. {<<"multipart/form-data \t;Boundary=\"MultipartIsUgly\"">>,
  1089. {<<"multipart">>, <<"form-data">>, [
  1090. {<<"boundary">>, <<"MultipartIsUgly">>}
  1091. ]}},
  1092. {<<"foo/bar; one=FirstParam; two=SecondParam">>,
  1093. {<<"foo">>, <<"bar">>, [
  1094. {<<"one">>, <<"FirstParam">>},
  1095. {<<"two">>, <<"SecondParam">>}
  1096. ]}}
  1097. ],
  1098. [{V, fun () -> R = content_type(V) end} || {V, R} <- Tests].
  1099. parameterized_tokens_test_() ->
  1100. %% {ParameterizedTokens, Result}
  1101. Tests = [
  1102. {<<"foo">>, [{<<"foo">>, []}]},
  1103. {<<"bar; baz=2">>, [{<<"bar">>, [{<<"baz">>, <<"2">>}]}]},
  1104. {<<"bar; baz=2;bat">>, [{<<"bar">>, [{<<"baz">>, <<"2">>}, <<"bat">>]}]},
  1105. {<<"bar; baz=2;bat=\"z=1,2;3\"">>, [{<<"bar">>, [{<<"baz">>, <<"2">>}, {<<"bat">>, <<"z=1,2;3">>}]}]},
  1106. {<<"foo, bar; baz=2">>, [{<<"foo">>, []}, {<<"bar">>, [{<<"baz">>, <<"2">>}]}]}
  1107. ],
  1108. [{V, fun () -> R = parameterized_tokens(V) end} || {V, R} <- Tests].
  1109. digits_test_() ->
  1110. %% {Digits, Result}
  1111. Tests = [
  1112. {<<"42 ">>, 42},
  1113. {<<"69\t">>, 69},
  1114. {<<"1337">>, 1337}
  1115. ],
  1116. [{V, fun() -> R = digits(V) end} || {V, R} <- Tests].
  1117. urldecode_test_() ->
  1118. F = fun(Qs, O) ->
  1119. try urldecode(Qs, O) of
  1120. R ->
  1121. {ok, R}
  1122. catch _:E ->
  1123. {error, E}
  1124. end
  1125. end,
  1126. Tests = [
  1127. {<<"%20">>, crash, {ok, <<" ">>}},
  1128. {<<"+">>, crash, {ok, <<" ">>}},
  1129. {<<"%00">>, crash, {ok, <<0>>}},
  1130. {<<"%fF">>, crash, {ok, <<255>>}},
  1131. {<<"123">>, crash, {ok, <<"123">>}},
  1132. {<<"%i5">>, skip, {ok, <<"%i5">>}},
  1133. {<<"%5">>, skip, {ok, <<"%5">>}},
  1134. {<<"%i5">>, crash, {error, badarg}},
  1135. {<<"%5">>, crash, {error, badarg}}
  1136. ],
  1137. [{Qs, fun() -> R = F(Qs,O) end} || {Qs, O, R} <- Tests].
  1138. urlencode_test_() ->
  1139. Tests = [
  1140. {<<255,0>>, [], <<"%ff%00">>},
  1141. {<<255,0>>, [upper], <<"%FF%00">>},
  1142. {<<" ">>, [], <<"+">>},
  1143. {<<" ">>, [noplus], <<"%20">>},
  1144. {<<"aBc">>, [], <<"aBc">>},
  1145. {<<".-~_">>, [], <<".-~_">>}
  1146. ],
  1147. Tests2 = [{<<255, " ">>,<<"%ff+">>}],
  1148. [{V, fun() -> R = urlencode(V, O) end} || {V, O, R} <- Tests] ++
  1149. [{V, fun() -> R = urlencode(V) end} || {V, R} <- Tests2].
  1150. http_authorization_test_() ->
  1151. Tests = [
  1152. {<<"basic">>, <<"QWxsYWRpbjpvcGVuIHNlc2FtZQ==">>,
  1153. {<<"basic">>, {<<"Alladin">>, <<"open sesame">>}}},
  1154. {<<"basic">>, <<"dXNlcm5hbWUK">>,
  1155. {error, badarg}},
  1156. {<<"basic">>, <<"_[]@#$%^&*()-AA==">>,
  1157. {error, badarg}},
  1158. {<<"basic">>, <<"dXNlcjpwYXNzCA==">>,
  1159. {error, badarg}},
  1160. {<<"bearer">>, <<" some_secret_key">>,
  1161. {<<"bearer">>,<<"some_secret_key">>}}
  1162. ],
  1163. [{V, fun() -> R = authorization(V,T) end} || {T, V, R} <- Tests].
  1164. http_range_test_() ->
  1165. Tests = [
  1166. {<<"bytes=1-20">>,
  1167. {<<"bytes">>, [{1, 20}]}},
  1168. {<<"bytes=-100">>,
  1169. {<<"bytes">>, [-100]}},
  1170. {<<"bytes=1-">>,
  1171. {<<"bytes">>, [{1, infinity}]}},
  1172. {<<"bytes=1-20,30-40,50-">>,
  1173. {<<"bytes">>, [{1, 20}, {30, 40}, {50, infinity}]}},
  1174. {<<"bytes = 1 - 20 , 50 - , - 300 ">>,
  1175. {<<"bytes">>, [{1, 20}, {50, infinity}, -300]}},
  1176. {<<"bytes=1-20,-500,30-40">>,
  1177. {<<"bytes">>, [{1, 20}, -500, {30, 40}]}},
  1178. {<<"test=1-20,-500,30-40">>,
  1179. {<<"test">>, [{1, 20}, -500, {30, 40}]}},
  1180. {<<"bytes=-">>,
  1181. {error, badarg}},
  1182. {<<"bytes=-30,-">>,
  1183. {error, badarg}}
  1184. ],
  1185. [fun() -> R = range(V) end ||{V, R} <- Tests].
  1186. -endif.