cow_multipart.erl 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775
  1. %% Copyright (c) 2014-2018, Loïc Hoguin <essen@ninenines.eu>
  2. %%
  3. %% Permission to use, copy, modify, and/or distribute this software for any
  4. %% purpose with or without fee is hereby granted, provided that the above
  5. %% copyright notice and this permission notice appear in all copies.
  6. %%
  7. %% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  8. %% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  9. %% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  10. %% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  11. %% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  12. %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  13. %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  14. -module(cow_multipart).
  15. %% Parsing.
  16. -export([parse_headers/2]).
  17. -export([parse_body/2]).
  18. %% Building.
  19. -export([boundary/0]).
  20. -export([first_part/2]).
  21. -export([part/2]).
  22. -export([close/1]).
  23. %% Headers.
  24. -export([form_data/1]).
  25. -export([parse_content_disposition/1]).
  26. -export([parse_content_transfer_encoding/1]).
  27. -export([parse_content_type/1]).
  28. -type headers() :: [{iodata(), iodata()}].
  29. -export_type([headers/0]).
  30. -include("cow_inline.hrl").
  31. -define(TEST1_MIME, <<
  32. "This is a message with multiple parts in MIME format.\r\n"
  33. "--frontier\r\n"
  34. "Content-Type: text/plain\r\n"
  35. "\r\n"
  36. "This is the body of the message.\r\n"
  37. "--frontier\r\n"
  38. "Content-Type: application/octet-stream\r\n"
  39. "Content-Transfer-Encoding: base64\r\n"
  40. "\r\n"
  41. "PGh0bWw+CiAgPGhlYWQ+CiAgPC9oZWFkPgogIDxib2R5PgogICAgPHA+VGhpcyBpcyB0aGUg\r\n"
  42. "Ym9keSBvZiB0aGUgbWVzc2FnZS48L3A+CiAgPC9ib2R5Pgo8L2h0bWw+Cg==\r\n"
  43. "--frontier--"
  44. >>).
  45. -define(TEST1_BOUNDARY, <<"frontier">>).
  46. -define(TEST2_MIME, <<
  47. "--AaB03x\r\n"
  48. "Content-Disposition: form-data; name=\"submit-name\"\r\n"
  49. "\r\n"
  50. "Larry\r\n"
  51. "--AaB03x\r\n"
  52. "Content-Disposition: form-data; name=\"files\"\r\n"
  53. "Content-Type: multipart/mixed; boundary=BbC04y\r\n"
  54. "\r\n"
  55. "--BbC04y\r\n"
  56. "Content-Disposition: file; filename=\"file1.txt\"\r\n"
  57. "Content-Type: text/plain\r\n"
  58. "\r\n"
  59. "... contents of file1.txt ...\r\n"
  60. "--BbC04y\r\n"
  61. "Content-Disposition: file; filename=\"file2.gif\"\r\n"
  62. "Content-Type: image/gif\r\n"
  63. "Content-Transfer-Encoding: binary\r\n"
  64. "\r\n"
  65. "...contents of file2.gif...\r\n"
  66. "--BbC04y--\r\n"
  67. "--AaB03x--"
  68. >>).
  69. -define(TEST2_BOUNDARY, <<"AaB03x">>).
  70. -define(TEST3_MIME, <<
  71. "This is the preamble.\r\n"
  72. "--boundary\r\n"
  73. "Content-Type: text/plain\r\n"
  74. "\r\n"
  75. "This is the body of the message.\r\n"
  76. "--boundary--"
  77. "\r\nThis is the epilogue. Here it includes leading CRLF"
  78. >>).
  79. -define(TEST3_BOUNDARY, <<"boundary">>).
  80. -define(TEST4_MIME, <<
  81. "This is the preamble.\r\n"
  82. "--boundary\r\n"
  83. "Content-Type: text/plain\r\n"
  84. "\r\n"
  85. "This is the body of the message.\r\n"
  86. "--boundary--"
  87. "\r\n"
  88. >>).
  89. -define(TEST4_BOUNDARY, <<"boundary">>).
  90. %% RFC 2046, Section 5.1.1
  91. -define(TEST5_MIME, <<
  92. "This is the preamble. It is to be ignored, though it\r\n"
  93. "is a handy place for composition agents to include an\r\n"
  94. "explanatory note to non-MIME conformant readers.\r\n"
  95. "\r\n"
  96. "--simple boundary\r\n",
  97. "\r\n"
  98. "This is implicitly typed plain US-ASCII text.\r\n"
  99. "It does NOT end with a linebreak."
  100. "\r\n"
  101. "--simple boundary\r\n",
  102. "Content-type: text/plain; charset=us-ascii\r\n"
  103. "\r\n"
  104. "This is explicitly typed plain US-ASCII text.\r\n"
  105. "It DOES end with a linebreak.\r\n"
  106. "\r\n"
  107. "--simple boundary--\r\n"
  108. "\r\n"
  109. "This is the epilogue. It is also to be ignored."
  110. >>).
  111. -define(TEST5_BOUNDARY, <<"simple boundary">>).
  112. %% Parsing.
  113. %%
  114. %% The multipart format is defined in RFC 2045.
  115. %% @doc Parse the headers for the next multipart part.
  116. %%
  117. %% This function skips any preamble before the boundary.
  118. %% The preamble may be retrieved using parse_body/2.
  119. %%
  120. %% This function will accept input of any size, it is
  121. %% up to the caller to limit it if needed.
  122. -spec parse_headers(binary(), binary())
  123. -> more | {more, binary()}
  124. | {ok, headers(), binary()}
  125. | {done, binary()}.
  126. %% If the stream starts with the boundary we can make a few assumptions
  127. %% and quickly figure out if we got the complete list of headers.
  128. parse_headers(<< "--", Stream/bits >>, Boundary) ->
  129. BoundarySize = byte_size(Boundary),
  130. case Stream of
  131. %% Last boundary. Return the epilogue.
  132. << Boundary:BoundarySize/binary, "--", Stream2/bits >> ->
  133. {done, Stream2};
  134. << Boundary:BoundarySize/binary, Stream2/bits >> ->
  135. %% We have all the headers only if there is a \r\n\r\n
  136. %% somewhere in the data after the boundary.
  137. case binary:match(Stream2, <<"\r\n\r\n">>) of
  138. nomatch ->
  139. more;
  140. _ ->
  141. before_parse_headers(Stream2)
  142. end;
  143. %% If there isn't enough to represent Boundary \r\n\r\n
  144. %% then we definitely don't have all the headers.
  145. _ when byte_size(Stream) < byte_size(Boundary) + 4 ->
  146. more;
  147. %% Otherwise we have preamble data to skip.
  148. %% We still got rid of the first two misleading bytes.
  149. _ ->
  150. skip_preamble(Stream, Boundary)
  151. end;
  152. %% Otherwise we have preamble data to skip.
  153. parse_headers(Stream, Boundary) ->
  154. skip_preamble(Stream, Boundary).
  155. %% We need to find the boundary and a \r\n\r\n after that.
  156. %% Since the boundary isn't at the start, it must be right
  157. %% after a \r\n too.
  158. skip_preamble(Stream, Boundary) ->
  159. case binary:match(Stream, <<"\r\n--", Boundary/bits >>) of
  160. %% No boundary, need more data.
  161. nomatch ->
  162. %% We can safely skip the size of the stream
  163. %% minus the last 3 bytes which may be a partial boundary.
  164. SkipSize = byte_size(Stream) - 3,
  165. case SkipSize > 0 of
  166. false ->
  167. more;
  168. true ->
  169. << _:SkipSize/binary, Stream2/bits >> = Stream,
  170. {more, Stream2}
  171. end;
  172. {Start, Length} ->
  173. Start2 = Start + Length,
  174. << _:Start2/binary, Stream2/bits >> = Stream,
  175. case Stream2 of
  176. %% Last boundary. Return the epilogue.
  177. << "--", Stream3/bits >> ->
  178. {done, Stream3};
  179. _ ->
  180. case binary:match(Stream, <<"\r\n\r\n">>) of
  181. %% We don't have the full headers.
  182. nomatch ->
  183. {more, Stream2};
  184. _ ->
  185. before_parse_headers(Stream2)
  186. end
  187. end
  188. end.
  189. before_parse_headers(<< "\r\n\r\n", Stream/bits >>) ->
  190. %% This indicates that there are no headers, so we can abort immediately.
  191. {ok, [], Stream};
  192. before_parse_headers(<< "\r\n", Stream/bits >>) ->
  193. %% There is a line break right after the boundary, skip it.
  194. parse_hd_name(Stream, [], <<>>).
  195. parse_hd_name(<< C, Rest/bits >>, H, SoFar) ->
  196. case C of
  197. $: -> parse_hd_before_value(Rest, H, SoFar);
  198. $\s -> parse_hd_name_ws(Rest, H, SoFar);
  199. $\t -> parse_hd_name_ws(Rest, H, SoFar);
  200. _ -> ?LOWER(parse_hd_name, Rest, H, SoFar)
  201. end.
  202. parse_hd_name_ws(<< C, Rest/bits >>, H, Name) ->
  203. case C of
  204. $\s -> parse_hd_name_ws(Rest, H, Name);
  205. $\t -> parse_hd_name_ws(Rest, H, Name);
  206. $: -> parse_hd_before_value(Rest, H, Name)
  207. end.
  208. parse_hd_before_value(<< $\s, Rest/bits >>, H, N) ->
  209. parse_hd_before_value(Rest, H, N);
  210. parse_hd_before_value(<< $\t, Rest/bits >>, H, N) ->
  211. parse_hd_before_value(Rest, H, N);
  212. parse_hd_before_value(Buffer, H, N) ->
  213. parse_hd_value(Buffer, H, N, <<>>).
  214. parse_hd_value(<< $\r, Rest/bits >>, Headers, Name, SoFar) ->
  215. case Rest of
  216. << "\n\r\n", Rest2/bits >> ->
  217. {ok, [{Name, SoFar}|Headers], Rest2};
  218. << $\n, C, Rest2/bits >> when C =:= $\s; C =:= $\t ->
  219. parse_hd_value(Rest2, Headers, Name, SoFar);
  220. << $\n, Rest2/bits >> ->
  221. parse_hd_name(Rest2, [{Name, SoFar}|Headers], <<>>)
  222. end;
  223. parse_hd_value(<< C, Rest/bits >>, H, N, SoFar) ->
  224. parse_hd_value(Rest, H, N, << SoFar/binary, C >>).
  225. %% @doc Parse the body of the current multipart part.
  226. %%
  227. %% The body is everything until the next boundary.
  228. -spec parse_body(binary(), binary())
  229. -> {ok, binary()} | {ok, binary(), binary()}
  230. | done | {done, binary()} | {done, binary(), binary()}.
  231. parse_body(Stream, Boundary) ->
  232. BoundarySize = byte_size(Boundary),
  233. case Stream of
  234. << "--", Boundary:BoundarySize/binary, _/bits >> ->
  235. done;
  236. _ ->
  237. case binary:match(Stream, << "\r\n--", Boundary/bits >>) of
  238. %% No boundary, check for a possible partial at the end.
  239. %% Return more or less of the body depending on the result.
  240. nomatch ->
  241. StreamSize = byte_size(Stream),
  242. From = StreamSize - BoundarySize - 3,
  243. MatchOpts = if
  244. %% Binary too small to contain boundary, check it fully.
  245. From < 0 -> [];
  246. %% Optimize, only check the end of the binary.
  247. true -> [{scope, {From, StreamSize - From}}]
  248. end,
  249. case binary:match(Stream, <<"\r">>, MatchOpts) of
  250. nomatch ->
  251. {ok, Stream};
  252. {Pos, _} ->
  253. case Stream of
  254. << Body:Pos/binary >> ->
  255. {ok, Body};
  256. << Body:Pos/binary, Rest/bits >> ->
  257. {ok, Body, Rest}
  258. end
  259. end;
  260. %% Boundary found, this is the last chunk of the body.
  261. {Pos, _} ->
  262. case Stream of
  263. << Body:Pos/binary, "\r\n" >> ->
  264. {done, Body};
  265. << Body:Pos/binary, "\r\n", Rest/bits >> ->
  266. {done, Body, Rest};
  267. << Body:Pos/binary, Rest/bits >> ->
  268. {done, Body, Rest}
  269. end
  270. end
  271. end.
  272. -ifdef(TEST).
  273. parse_test() ->
  274. H1 = [{<<"content-type">>, <<"text/plain">>}],
  275. Body1 = <<"This is the body of the message.">>,
  276. H2 = lists:sort([{<<"content-type">>, <<"application/octet-stream">>},
  277. {<<"content-transfer-encoding">>, <<"base64">>}]),
  278. Body2 = <<"PGh0bWw+CiAgPGhlYWQ+CiAgPC9oZWFkPgogIDxib2R5PgogICAgPHA+VGhpcyBpcyB0aGUg\r\n"
  279. "Ym9keSBvZiB0aGUgbWVzc2FnZS48L3A+CiAgPC9ib2R5Pgo8L2h0bWw+Cg==">>,
  280. {ok, H1, Rest} = parse_headers(?TEST1_MIME, ?TEST1_BOUNDARY),
  281. {done, Body1, Rest2} = parse_body(Rest, ?TEST1_BOUNDARY),
  282. done = parse_body(Rest2, ?TEST1_BOUNDARY),
  283. {ok, H2Unsorted, Rest3} = parse_headers(Rest2, ?TEST1_BOUNDARY),
  284. H2 = lists:sort(H2Unsorted),
  285. {done, Body2, Rest4} = parse_body(Rest3, ?TEST1_BOUNDARY),
  286. done = parse_body(Rest4, ?TEST1_BOUNDARY),
  287. {done, <<>>} = parse_headers(Rest4, ?TEST1_BOUNDARY),
  288. ok.
  289. parse_interleaved_test() ->
  290. H1 = [{<<"content-disposition">>, <<"form-data; name=\"submit-name\"">>}],
  291. Body1 = <<"Larry">>,
  292. H2 = lists:sort([{<<"content-disposition">>, <<"form-data; name=\"files\"">>},
  293. {<<"content-type">>, <<"multipart/mixed; boundary=BbC04y">>}]),
  294. InH1 = lists:sort([{<<"content-disposition">>, <<"file; filename=\"file1.txt\"">>},
  295. {<<"content-type">>, <<"text/plain">>}]),
  296. InBody1 = <<"... contents of file1.txt ...">>,
  297. InH2 = lists:sort([{<<"content-disposition">>, <<"file; filename=\"file2.gif\"">>},
  298. {<<"content-type">>, <<"image/gif">>},
  299. {<<"content-transfer-encoding">>, <<"binary">>}]),
  300. InBody2 = <<"...contents of file2.gif...">>,
  301. {ok, H1, Rest} = parse_headers(?TEST2_MIME, ?TEST2_BOUNDARY),
  302. {done, Body1, Rest2} = parse_body(Rest, ?TEST2_BOUNDARY),
  303. done = parse_body(Rest2, ?TEST2_BOUNDARY),
  304. {ok, H2Unsorted, Rest3} = parse_headers(Rest2, ?TEST2_BOUNDARY),
  305. H2 = lists:sort(H2Unsorted),
  306. {_, ContentType} = lists:keyfind(<<"content-type">>, 1, H2),
  307. {<<"multipart">>, <<"mixed">>, [{<<"boundary">>, InBoundary}]}
  308. = parse_content_type(ContentType),
  309. {ok, InH1Unsorted, InRest} = parse_headers(Rest3, InBoundary),
  310. InH1 = lists:sort(InH1Unsorted),
  311. {done, InBody1, InRest2} = parse_body(InRest, InBoundary),
  312. done = parse_body(InRest2, InBoundary),
  313. {ok, InH2Unsorted, InRest3} = parse_headers(InRest2, InBoundary),
  314. InH2 = lists:sort(InH2Unsorted),
  315. {done, InBody2, InRest4} = parse_body(InRest3, InBoundary),
  316. done = parse_body(InRest4, InBoundary),
  317. {done, Rest4} = parse_headers(InRest4, InBoundary),
  318. {done, <<>>} = parse_headers(Rest4, ?TEST2_BOUNDARY),
  319. ok.
  320. parse_epilogue_test() ->
  321. H1 = [{<<"content-type">>, <<"text/plain">>}],
  322. Body1 = <<"This is the body of the message.">>,
  323. Epilogue = <<"\r\nThis is the epilogue. Here it includes leading CRLF">>,
  324. {ok, H1, Rest} = parse_headers(?TEST3_MIME, ?TEST3_BOUNDARY),
  325. {done, Body1, Rest2} = parse_body(Rest, ?TEST3_BOUNDARY),
  326. done = parse_body(Rest2, ?TEST3_BOUNDARY),
  327. {done, Epilogue} = parse_headers(Rest2, ?TEST3_BOUNDARY),
  328. ok.
  329. parse_epilogue_crlf_test() ->
  330. H1 = [{<<"content-type">>, <<"text/plain">>}],
  331. Body1 = <<"This is the body of the message.">>,
  332. Epilogue = <<"\r\n">>,
  333. {ok, H1, Rest} = parse_headers(?TEST4_MIME, ?TEST4_BOUNDARY),
  334. {done, Body1, Rest2} = parse_body(Rest, ?TEST4_BOUNDARY),
  335. done = parse_body(Rest2, ?TEST4_BOUNDARY),
  336. {done, Epilogue} = parse_headers(Rest2, ?TEST4_BOUNDARY),
  337. ok.
  338. parse_rfc2046_test() ->
  339. %% The following is an example included in RFC 2046, Section 5.1.1.
  340. Body1 = <<"This is implicitly typed plain US-ASCII text.\r\n"
  341. "It does NOT end with a linebreak.">>,
  342. Body2 = <<"This is explicitly typed plain US-ASCII text.\r\n"
  343. "It DOES end with a linebreak.\r\n">>,
  344. H2 = [{<<"content-type">>, <<"text/plain; charset=us-ascii">>}],
  345. Epilogue = <<"\r\n\r\nThis is the epilogue. It is also to be ignored.">>,
  346. {ok, [], Rest} = parse_headers(?TEST5_MIME, ?TEST5_BOUNDARY),
  347. {done, Body1, Rest2} = parse_body(Rest, ?TEST5_BOUNDARY),
  348. {ok, H2, Rest3} = parse_headers(Rest2, ?TEST5_BOUNDARY),
  349. {done, Body2, Rest4} = parse_body(Rest3, ?TEST5_BOUNDARY),
  350. {done, Epilogue} = parse_headers(Rest4, ?TEST5_BOUNDARY),
  351. ok.
  352. parse_partial_test() ->
  353. {ok, <<0:8000, "abcdef">>, <<"\rghij">>}
  354. = parse_body(<<0:8000, "abcdef\rghij">>, <<"boundary">>),
  355. {ok, <<"abcdef">>, <<"\rghij">>}
  356. = parse_body(<<"abcdef\rghij">>, <<"boundary">>),
  357. {ok, <<"abc">>, <<"\rdef">>}
  358. = parse_body(<<"abc\rdef">>, <<"boundaryboundary">>),
  359. {ok, <<0:8000, "abcdef">>, <<"\r\nghij">>}
  360. = parse_body(<<0:8000, "abcdef\r\nghij">>, <<"boundary">>),
  361. {ok, <<"abcdef">>, <<"\r\nghij">>}
  362. = parse_body(<<"abcdef\r\nghij">>, <<"boundary">>),
  363. {ok, <<"abc">>, <<"\r\ndef">>}
  364. = parse_body(<<"abc\r\ndef">>, <<"boundaryboundary">>),
  365. {ok, <<"boundary">>, <<"\r">>}
  366. = parse_body(<<"boundary\r">>, <<"boundary">>),
  367. {ok, <<"boundary">>, <<"\r\n">>}
  368. = parse_body(<<"boundary\r\n">>, <<"boundary">>),
  369. {ok, <<"boundary">>, <<"\r\n-">>}
  370. = parse_body(<<"boundary\r\n-">>, <<"boundary">>),
  371. {ok, <<"boundary">>, <<"\r\n--">>}
  372. = parse_body(<<"boundary\r\n--">>, <<"boundary">>),
  373. ok.
  374. perf_parse_multipart(Stream, Boundary) ->
  375. case parse_headers(Stream, Boundary) of
  376. {ok, _, Rest} ->
  377. {_, _, Rest2} = parse_body(Rest, Boundary),
  378. perf_parse_multipart(Rest2, Boundary);
  379. {done, _} ->
  380. ok
  381. end.
  382. horse_parse() ->
  383. horse:repeat(50000,
  384. perf_parse_multipart(?TEST1_MIME, ?TEST1_BOUNDARY)
  385. ).
  386. -endif.
  387. %% Building.
  388. %% @doc Generate a new random boundary.
  389. %%
  390. %% The boundary generated has a low probability of ever appearing
  391. %% in the data.
  392. -spec boundary() -> binary().
  393. boundary() ->
  394. cow_base64url:encode(crypto:strong_rand_bytes(48), #{padding => false}).
  395. %% @doc Return the first part's head.
  396. %%
  397. %% This works exactly like the part/2 function except there is
  398. %% no leading \r\n. It's not required to use this function,
  399. %% just makes the output a little smaller and prettier.
  400. -spec first_part(binary(), headers()) -> iodata().
  401. first_part(Boundary, Headers) ->
  402. [<<"--">>, Boundary, <<"\r\n">>, headers_to_iolist(Headers, [])].
  403. %% @doc Return a part's head.
  404. -spec part(binary(), headers()) -> iodata().
  405. part(Boundary, Headers) ->
  406. [<<"\r\n--">>, Boundary, <<"\r\n">>, headers_to_iolist(Headers, [])].
  407. headers_to_iolist([], Acc) ->
  408. lists:reverse([<<"\r\n">>|Acc]);
  409. headers_to_iolist([{N, V}|Tail], Acc) ->
  410. %% We don't want to create a sublist so we list the
  411. %% values in reverse order so that it gets reversed properly.
  412. headers_to_iolist(Tail, [<<"\r\n">>, V, <<": ">>, N|Acc]).
  413. %% @doc Return the closing delimiter of the multipart message.
  414. -spec close(binary()) -> iodata().
  415. close(Boundary) ->
  416. [<<"\r\n--">>, Boundary, <<"--">>].
  417. -ifdef(TEST).
  418. build_test() ->
  419. Result = string:to_lower(binary_to_list(?TEST1_MIME)),
  420. Result = string:to_lower(binary_to_list(iolist_to_binary([
  421. <<"This is a message with multiple parts in MIME format.\r\n">>,
  422. first_part(?TEST1_BOUNDARY, [{<<"content-type">>, <<"text/plain">>}]),
  423. <<"This is the body of the message.">>,
  424. part(?TEST1_BOUNDARY, [
  425. {<<"content-type">>, <<"application/octet-stream">>},
  426. {<<"content-transfer-encoding">>, <<"base64">>}]),
  427. <<"PGh0bWw+CiAgPGhlYWQ+CiAgPC9oZWFkPgogIDxib2R5PgogICAgPHA+VGhpcyBpcyB0aGUg\r\n"
  428. "Ym9keSBvZiB0aGUgbWVzc2FnZS48L3A+CiAgPC9ib2R5Pgo8L2h0bWw+Cg==">>,
  429. close(?TEST1_BOUNDARY)
  430. ]))),
  431. ok.
  432. identity_test() ->
  433. B = boundary(),
  434. Preamble = <<"This is a message with multiple parts in MIME format.">>,
  435. H1 = [{<<"content-type">>, <<"text/plain">>}],
  436. Body1 = <<"This is the body of the message.">>,
  437. H2 = lists:sort([{<<"content-type">>, <<"application/octet-stream">>},
  438. {<<"content-transfer-encoding">>, <<"base64">>}]),
  439. Body2 = <<"PGh0bWw+CiAgPGhlYWQ+CiAgPC9oZWFkPgogIDxib2R5PgogICAgPHA+VGhpcyBpcyB0aGUg\r\n"
  440. "Ym9keSBvZiB0aGUgbWVzc2FnZS48L3A+CiAgPC9ib2R5Pgo8L2h0bWw+Cg==">>,
  441. Epilogue = <<"Gotta go fast!">>,
  442. M = iolist_to_binary([
  443. Preamble,
  444. part(B, H1), Body1,
  445. part(B, H2), Body2,
  446. close(B),
  447. Epilogue
  448. ]),
  449. {done, Preamble, M2} = parse_body(M, B),
  450. {ok, H1, M3} = parse_headers(M2, B),
  451. {done, Body1, M4} = parse_body(M3, B),
  452. {ok, H2Unsorted, M5} = parse_headers(M4, B),
  453. H2 = lists:sort(H2Unsorted),
  454. {done, Body2, M6} = parse_body(M5, B),
  455. {done, Epilogue} = parse_headers(M6, B),
  456. ok.
  457. perf_build_multipart() ->
  458. B = boundary(),
  459. [
  460. <<"preamble\r\n">>,
  461. first_part(B, [{<<"content-type">>, <<"text/plain">>}]),
  462. <<"This is the body of the message.">>,
  463. part(B, [
  464. {<<"content-type">>, <<"application/octet-stream">>},
  465. {<<"content-transfer-encoding">>, <<"base64">>}]),
  466. <<"PGh0bWw+CiAgPGhlYWQ+CiAgPC9oZWFkPgogIDxib2R5PgogICAgPHA+VGhpcyBpcyB0aGUg\r\n"
  467. "Ym9keSBvZiB0aGUgbWVzc2FnZS48L3A+CiAgPC9ib2R5Pgo8L2h0bWw+Cg==">>,
  468. close(B),
  469. <<"epilogue">>
  470. ].
  471. horse_build() ->
  472. horse:repeat(50000,
  473. perf_build_multipart()
  474. ).
  475. -endif.
  476. %% Headers.
  477. %% @doc Convenience function for extracting information from headers
  478. %% when parsing a multipart/form-data stream.
  479. -spec form_data(headers() | #{binary() => binary()})
  480. -> {data, binary()}
  481. | {file, binary(), binary(), binary()}.
  482. form_data(Headers) when is_map(Headers) ->
  483. form_data(maps:to_list(Headers));
  484. form_data(Headers) ->
  485. {_, DispositionBin} = lists:keyfind(<<"content-disposition">>, 1, Headers),
  486. {<<"form-data">>, Params} = parse_content_disposition(DispositionBin),
  487. {_, FieldName} = lists:keyfind(<<"name">>, 1, Params),
  488. case lists:keyfind(<<"filename">>, 1, Params) of
  489. false ->
  490. {data, FieldName};
  491. {_, Filename} ->
  492. Type = case lists:keyfind(<<"content-type">>, 1, Headers) of
  493. false -> <<"text/plain">>;
  494. {_, T} -> T
  495. end,
  496. {file, FieldName, Filename, Type}
  497. end.
  498. -ifdef(TEST).
  499. form_data_test_() ->
  500. Tests = [
  501. {[{<<"content-disposition">>, <<"form-data; name=\"submit-name\"">>}],
  502. {data, <<"submit-name">>}},
  503. {[{<<"content-disposition">>,
  504. <<"form-data; name=\"files\"; filename=\"file1.txt\"">>},
  505. {<<"content-type">>, <<"text/x-plain">>}],
  506. {file, <<"files">>, <<"file1.txt">>, <<"text/x-plain">>}}
  507. ],
  508. [{lists:flatten(io_lib:format("~p", [V])),
  509. fun() -> R = form_data(V) end} || {V, R} <- Tests].
  510. -endif.
  511. %% @todo parse_content_description
  512. %% @todo parse_content_id
  513. %% @doc Parse an RFC 2183 content-disposition value.
  514. %% @todo Support RFC 2231.
  515. -spec parse_content_disposition(binary())
  516. -> {binary(), [{binary(), binary()}]}.
  517. parse_content_disposition(Bin) ->
  518. parse_cd_type(Bin, <<>>).
  519. parse_cd_type(<<>>, Acc) ->
  520. {Acc, []};
  521. parse_cd_type(<< C, Rest/bits >>, Acc) ->
  522. case C of
  523. $; -> {Acc, parse_before_param(Rest, [])};
  524. $\s -> {Acc, parse_before_param(Rest, [])};
  525. $\t -> {Acc, parse_before_param(Rest, [])};
  526. _ -> ?LOWER(parse_cd_type, Rest, Acc)
  527. end.
  528. -ifdef(TEST).
  529. parse_content_disposition_test_() ->
  530. Tests = [
  531. {<<"inline">>, {<<"inline">>, []}},
  532. {<<"attachment">>, {<<"attachment">>, []}},
  533. {<<"attachment; filename=genome.jpeg;"
  534. " modification-date=\"Wed, 12 Feb 1997 16:29:51 -0500\";">>,
  535. {<<"attachment">>, [
  536. {<<"filename">>, <<"genome.jpeg">>},
  537. {<<"modification-date">>, <<"Wed, 12 Feb 1997 16:29:51 -0500">>}
  538. ]}},
  539. {<<"form-data; name=\"user\"">>,
  540. {<<"form-data">>, [{<<"name">>, <<"user">>}]}},
  541. {<<"form-data; NAME=\"submit-name\"">>,
  542. {<<"form-data">>, [{<<"name">>, <<"submit-name">>}]}},
  543. {<<"form-data; name=\"files\"; filename=\"file1.txt\"">>,
  544. {<<"form-data">>, [
  545. {<<"name">>, <<"files">>},
  546. {<<"filename">>, <<"file1.txt">>}
  547. ]}},
  548. {<<"file; filename=\"file1.txt\"">>,
  549. {<<"file">>, [{<<"filename">>, <<"file1.txt">>}]}},
  550. {<<"file; filename=\"file2.gif\"">>,
  551. {<<"file">>, [{<<"filename">>, <<"file2.gif">>}]}}
  552. ],
  553. [{V, fun() -> R = parse_content_disposition(V) end} || {V, R} <- Tests].
  554. horse_parse_content_disposition_attachment() ->
  555. horse:repeat(100000,
  556. parse_content_disposition(<<"attachment; filename=genome.jpeg;"
  557. " modification-date=\"Wed, 12 Feb 1997 16:29:51 -0500\";">>)
  558. ).
  559. horse_parse_content_disposition_form_data() ->
  560. horse:repeat(100000,
  561. parse_content_disposition(
  562. <<"form-data; name=\"files\"; filename=\"file1.txt\"">>)
  563. ).
  564. horse_parse_content_disposition_inline() ->
  565. horse:repeat(100000,
  566. parse_content_disposition(<<"inline">>)
  567. ).
  568. -endif.
  569. %% @doc Parse an RFC 2045 content-transfer-encoding header.
  570. -spec parse_content_transfer_encoding(binary()) -> binary().
  571. parse_content_transfer_encoding(Bin) ->
  572. ?LOWER(Bin).
  573. -ifdef(TEST).
  574. parse_content_transfer_encoding_test_() ->
  575. Tests = [
  576. {<<"7bit">>, <<"7bit">>},
  577. {<<"7BIT">>, <<"7bit">>},
  578. {<<"8bit">>, <<"8bit">>},
  579. {<<"binary">>, <<"binary">>},
  580. {<<"quoted-printable">>, <<"quoted-printable">>},
  581. {<<"base64">>, <<"base64">>},
  582. {<<"Base64">>, <<"base64">>},
  583. {<<"BASE64">>, <<"base64">>},
  584. {<<"bAsE64">>, <<"base64">>}
  585. ],
  586. [{V, fun() -> R = parse_content_transfer_encoding(V) end}
  587. || {V, R} <- Tests].
  588. horse_parse_content_transfer_encoding() ->
  589. horse:repeat(100000,
  590. parse_content_transfer_encoding(<<"QUOTED-PRINTABLE">>)
  591. ).
  592. -endif.
  593. %% @doc Parse an RFC 2045 content-type header.
  594. -spec parse_content_type(binary())
  595. -> {binary(), binary(), [{binary(), binary()}]}.
  596. parse_content_type(Bin) ->
  597. parse_ct_type(Bin, <<>>).
  598. parse_ct_type(<< C, Rest/bits >>, Acc) ->
  599. case C of
  600. $/ -> parse_ct_subtype(Rest, Acc, <<>>);
  601. _ -> ?LOWER(parse_ct_type, Rest, Acc)
  602. end.
  603. parse_ct_subtype(<<>>, Type, Subtype) when Subtype =/= <<>> ->
  604. {Type, Subtype, []};
  605. parse_ct_subtype(<< C, Rest/bits >>, Type, Acc) ->
  606. case C of
  607. $; -> {Type, Acc, parse_before_param(Rest, [])};
  608. $\s -> {Type, Acc, parse_before_param(Rest, [])};
  609. $\t -> {Type, Acc, parse_before_param(Rest, [])};
  610. _ -> ?LOWER(parse_ct_subtype, Rest, Type, Acc)
  611. end.
  612. -ifdef(TEST).
  613. parse_content_type_test_() ->
  614. Tests = [
  615. {<<"image/gif">>,
  616. {<<"image">>, <<"gif">>, []}},
  617. {<<"text/plain">>,
  618. {<<"text">>, <<"plain">>, []}},
  619. {<<"text/plain; charset=us-ascii">>,
  620. {<<"text">>, <<"plain">>, [{<<"charset">>, <<"us-ascii">>}]}},
  621. {<<"text/plain; charset=\"us-ascii\"">>,
  622. {<<"text">>, <<"plain">>, [{<<"charset">>, <<"us-ascii">>}]}},
  623. {<<"multipart/form-data; boundary=AaB03x">>,
  624. {<<"multipart">>, <<"form-data">>,
  625. [{<<"boundary">>, <<"AaB03x">>}]}},
  626. {<<"multipart/mixed; boundary=BbC04y">>,
  627. {<<"multipart">>, <<"mixed">>, [{<<"boundary">>, <<"BbC04y">>}]}},
  628. {<<"multipart/mixed; boundary=--------">>,
  629. {<<"multipart">>, <<"mixed">>, [{<<"boundary">>, <<"--------">>}]}},
  630. {<<"application/x-horse; filename=genome.jpeg;"
  631. " some-date=\"Wed, 12 Feb 1997 16:29:51 -0500\";"
  632. " charset=us-ascii; empty=; number=12345">>,
  633. {<<"application">>, <<"x-horse">>, [
  634. {<<"filename">>, <<"genome.jpeg">>},
  635. {<<"some-date">>, <<"Wed, 12 Feb 1997 16:29:51 -0500">>},
  636. {<<"charset">>, <<"us-ascii">>},
  637. {<<"empty">>, <<>>},
  638. {<<"number">>, <<"12345">>}
  639. ]}}
  640. ],
  641. [{V, fun() -> R = parse_content_type(V) end}
  642. || {V, R} <- Tests].
  643. horse_parse_content_type_zero() ->
  644. horse:repeat(100000,
  645. parse_content_type(<<"text/plain">>)
  646. ).
  647. horse_parse_content_type_one() ->
  648. horse:repeat(100000,
  649. parse_content_type(<<"text/plain; charset=\"us-ascii\"">>)
  650. ).
  651. horse_parse_content_type_five() ->
  652. horse:repeat(100000,
  653. parse_content_type(<<"application/x-horse; filename=genome.jpeg;"
  654. " some-date=\"Wed, 12 Feb 1997 16:29:51 -0500\";"
  655. " charset=us-ascii; empty=; number=12345">>)
  656. ).
  657. -endif.
  658. %% @doc Parse RFC 2045 parameters.
  659. parse_before_param(<<>>, Params) ->
  660. lists:reverse(Params);
  661. parse_before_param(<< C, Rest/bits >>, Params) ->
  662. case C of
  663. $; -> parse_before_param(Rest, Params);
  664. $\s -> parse_before_param(Rest, Params);
  665. $\t -> parse_before_param(Rest, Params);
  666. _ -> ?LOWER(parse_param_name, Rest, Params, <<>>)
  667. end.
  668. parse_param_name(<<>>, Params, Acc) ->
  669. lists:reverse([{Acc, <<>>}|Params]);
  670. parse_param_name(<< C, Rest/bits >>, Params, Acc) ->
  671. case C of
  672. $= -> parse_param_value(Rest, Params, Acc);
  673. _ -> ?LOWER(parse_param_name, Rest, Params, Acc)
  674. end.
  675. parse_param_value(<<>>, Params, Name) ->
  676. lists:reverse([{Name, <<>>}|Params]);
  677. parse_param_value(<< C, Rest/bits >>, Params, Name) ->
  678. case C of
  679. $" -> parse_param_quoted_value(Rest, Params, Name, <<>>);
  680. $; -> parse_before_param(Rest, [{Name, <<>>}|Params]);
  681. $\s -> parse_before_param(Rest, [{Name, <<>>}|Params]);
  682. $\t -> parse_before_param(Rest, [{Name, <<>>}|Params]);
  683. C -> parse_param_value(Rest, Params, Name, << C >>)
  684. end.
  685. parse_param_value(<<>>, Params, Name, Acc) ->
  686. lists:reverse([{Name, Acc}|Params]);
  687. parse_param_value(<< C, Rest/bits >>, Params, Name, Acc) ->
  688. case C of
  689. $; -> parse_before_param(Rest, [{Name, Acc}|Params]);
  690. $\s -> parse_before_param(Rest, [{Name, Acc}|Params]);
  691. $\t -> parse_before_param(Rest, [{Name, Acc}|Params]);
  692. C -> parse_param_value(Rest, Params, Name, << Acc/binary, C >>)
  693. end.
  694. %% We expect a final $" so no need to test for <<>>.
  695. parse_param_quoted_value(<< $\\, C, Rest/bits >>, Params, Name, Acc) ->
  696. parse_param_quoted_value(Rest, Params, Name, << Acc/binary, C >>);
  697. parse_param_quoted_value(<< $", Rest/bits >>, Params, Name, Acc) ->
  698. parse_before_param(Rest, [{Name, Acc}|Params]);
  699. parse_param_quoted_value(<< C, Rest/bits >>, Params, Name, Acc)
  700. when C =/= $\r ->
  701. parse_param_quoted_value(Rest, Params, Name, << Acc/binary, C >>).