You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2006 lines
75 KiB

  1. %% Vendored from hex_core v0.6.8, do not edit manually
  2. %% @private
  3. %% Copied from https://github.com/erlang/otp/blob/OTP-20.0.1/lib/stdlib/src/erl_tar.erl
  4. %% with modifications:
  5. %% - Change module name to `r3_hex_erl_tar`
  6. %% - Set tar mtimes to 0 and remove dependency on :os.system_time/1
  7. %% - Preserve modes when building tarball
  8. %% - Do not crash if failing to write tar
  9. %% - Allow setting file_info opts on :r3_hex_erl_tar.add
  10. %% - Add safe_relative_path_links/2 to check directory traversal vulnerability when extracting files,
  11. %% it differs from OTP's current fix (2020-02-04) in that it checks regular files instead of
  12. %% symlink targets. This allows creating symlinks with relative path targets such as `../tmp/log`
  13. %%
  14. %% %CopyrightBegin%
  15. %%
  16. %% Copyright Ericsson AB 1997-2017. All Rights Reserved.
  17. %%
  18. %% Licensed under the Apache License, Version 2.0 (the "License");
  19. %% you may not use this file except in compliance with the License.
  20. %% You may obtain a copy of the License at
  21. %%
  22. %% http://www.apache.org/licenses/LICENSE-2.0
  23. %%
  24. %% Unless required by applicable law or agreed to in writing, software
  25. %% distributed under the License is distributed on an "AS IS" BASIS,
  26. %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  27. %% See the License for the specific language governing permissions and
  28. %% limitations under the License.
  29. %%
  30. %% %CopyrightEnd%
  31. %%
  32. %% This module implements extraction/creation of tar archives.
  33. %% It supports reading most common tar formats, namely V7, STAR,
  34. %% USTAR, GNU, BSD/libarchive, and PAX. It produces archives in USTAR
  35. %% format, unless it must use PAX headers, in which case it produces PAX
  36. %% format.
  37. %%
  38. %% The following references where used:
  39. %% http://www.freebsd.org/cgi/man.cgi?query=tar&sektion=5
  40. %% http://www.gnu.org/software/tar/manual/html_node/Standard.html
  41. %% http://pubs.opengroup.org/onlinepubs/9699919799/utilities/pax.html
  42. -module(r3_hex_erl_tar).
  43. -export([init/3,
  44. create/2, create/3,
  45. extract/1, extract/2,
  46. table/1, table/2, t/1, tt/1,
  47. open/2, close/1,
  48. add/3, add/4, add/5,
  49. format_error/1]).
  50. -include_lib("kernel/include/file.hrl").
  51. -include_lib("r3_hex_erl_tar.hrl").
  52. %% Converts the short error reason to a descriptive string.
  53. -spec format_error(term()) -> string().
  54. format_error(invalid_tar_checksum) ->
  55. "Checksum failed";
  56. format_error(bad_header) ->
  57. "Unrecognized tar header format";
  58. format_error({bad_header, Reason}) ->
  59. lists:flatten(io_lib:format("Unrecognized tar header format: ~p", [Reason]));
  60. format_error({invalid_header, negative_size}) ->
  61. "Invalid header: negative size";
  62. format_error(invalid_sparse_header_size) ->
  63. "Invalid sparse header: negative size";
  64. format_error(invalid_sparse_map_entry) ->
  65. "Invalid sparse map entry";
  66. format_error({invalid_sparse_map_entry, Reason}) ->
  67. lists:flatten(io_lib:format("Invalid sparse map entry: ~p", [Reason]));
  68. format_error(invalid_end_of_archive) ->
  69. "Invalid end of archive";
  70. format_error(eof) ->
  71. "Unexpected end of file";
  72. format_error(integer_overflow) ->
  73. "Failed to parse numeric: integer overflow";
  74. format_error({misaligned_read, Pos}) ->
  75. lists:flatten(io_lib:format("Read a block which was misaligned: block_size=~p pos=~p",
  76. [?BLOCK_SIZE, Pos]));
  77. format_error(invalid_gnu_1_0_sparsemap) ->
  78. "Invalid GNU sparse map (version 1.0)";
  79. format_error({invalid_gnu_0_1_sparsemap, Format}) ->
  80. lists:flatten(io_lib:format("Invalid GNU sparse map (version ~s)", [Format]));
  81. format_error(unsafe_path) ->
  82. "The path points above the current working directory";
  83. format_error({Name,Reason}) ->
  84. lists:flatten(io_lib:format("~ts: ~ts", [Name,format_error(Reason)]));
  85. format_error(Atom) when is_atom(Atom) ->
  86. file:format_error(Atom);
  87. format_error(Term) ->
  88. lists:flatten(io_lib:format("~tp", [Term])).
  89. %% Initializes a new reader given a custom file handle and I/O wrappers
  90. -spec init(handle(), write | read, file_op()) -> {ok, reader()} | {error, badarg}.
  91. init(Handle, AccessMode, Fun) when is_function(Fun, 2) ->
  92. Reader = #reader{handle=Handle,access=AccessMode,func=Fun},
  93. {ok, Pos, Reader2} = do_position(Reader, {cur, 0}),
  94. {ok, Reader2#reader{pos=Pos}};
  95. init(_Handle, _AccessMode, _Fun) ->
  96. {error, badarg}.
  97. %%%================================================================
  98. %% Extracts all files from the tar file Name.
  99. -spec extract(open_handle()) -> ok | {error, term()}.
  100. extract(Name) ->
  101. extract(Name, []).
  102. %% Extracts (all) files from the tar file Name.
  103. %% Options accepted:
  104. %% - cooked: Opens the tar file without mode `raw`
  105. %% - compressed: Uncompresses the tar file when reading
  106. %% - memory: Returns the tar contents as a list of tuples {Name, Bin}
  107. %% - keep_old_files: Extracted files will not overwrite the destination
  108. %% - {files, ListOfFilesToExtract}: Only extract ListOfFilesToExtract
  109. %% - verbose: Prints verbose information about the extraction,
  110. %% - {cwd, AbsoluteDir}: Sets the current working directory for the extraction
  111. -spec extract(open_handle(), [extract_opt()]) ->
  112. ok
  113. | {ok, [{string(), binary()}]}
  114. | {error, term()}.
  115. extract({binary, Bin}, Opts) when is_list(Opts) ->
  116. do_extract({binary, Bin}, Opts);
  117. extract({file, Fd}, Opts) when is_list(Opts) ->
  118. do_extract({file, Fd}, Opts);
  119. extract(#reader{}=Reader, Opts) when is_list(Opts) ->
  120. do_extract(Reader, Opts);
  121. extract(Name, Opts) when is_list(Name); is_binary(Name), is_list(Opts) ->
  122. do_extract(Name, Opts).
  123. do_extract(Handle, Opts) when is_list(Opts) ->
  124. Opts2 = extract_opts(Opts),
  125. Acc = if Opts2#read_opts.output =:= memory -> []; true -> ok end,
  126. foldl_read(Handle, fun extract1/4, Acc, Opts2).
  127. extract1(eof, Reader, _, Acc) when is_list(Acc) ->
  128. {ok, {ok, lists:reverse(Acc)}, Reader};
  129. extract1(eof, Reader, _, leading_slash) ->
  130. error_logger:info_msg("erl_tar: removed leading '/' from member names\n"),
  131. {ok, ok, Reader};
  132. extract1(eof, Reader, _, Acc) ->
  133. {ok, Acc, Reader};
  134. extract1(#tar_header{name=Name,size=Size}=Header, Reader0, Opts, Acc0) ->
  135. case check_extract(Name, Opts) of
  136. true ->
  137. case do_read(Reader0, Size) of
  138. {ok, Bin, Reader1} ->
  139. Acc = extract2(Header, Bin, Opts, Acc0),
  140. {ok, Acc, Reader1};
  141. {error, _} = Err ->
  142. throw(Err)
  143. end;
  144. false ->
  145. {ok, Acc0, skip_file(Reader0)}
  146. end.
  147. extract2(Header, Bin, Opts, Acc) ->
  148. case write_extracted_element(Header, Bin, Opts) of
  149. ok ->
  150. case Header of
  151. #tar_header{name="/"++_} ->
  152. leading_slash;
  153. #tar_header{} ->
  154. Acc
  155. end;
  156. {ok, NameBin} when is_list(Acc) ->
  157. [NameBin | Acc];
  158. {error, _} = Err ->
  159. throw(Err)
  160. end.
  161. %% Checks if the file Name should be extracted.
  162. check_extract(_, #read_opts{files=all}) ->
  163. true;
  164. check_extract(Name, #read_opts{files=Files}) ->
  165. ordsets:is_element(Name, Files).
  166. %%%================================================================
  167. %% The following table functions produce a list of information about
  168. %% the files contained in the archive.
  169. -type filename() :: string().
  170. -type typeflag() :: regular | link | symlink |
  171. char | block | directory |
  172. fifo | reserved | unknown.
  173. -type mode() :: non_neg_integer().
  174. -type uid() :: non_neg_integer().
  175. -type gid() :: non_neg_integer().
  176. -type tar_entry() :: {filename(),
  177. typeflag(),
  178. non_neg_integer(),
  179. tar_time(),
  180. mode(),
  181. uid(),
  182. gid()}.
  183. %% Returns a list of names of the files in the tar file Name.
  184. -spec table(open_handle()) -> {ok, [string()]} | {error, term()}.
  185. table(Name) ->
  186. table(Name, []).
  187. %% Returns a list of names of the files in the tar file Name.
  188. %% Options accepted: compressed, verbose, cooked.
  189. -spec table(open_handle(), [compressed | verbose | cooked]) ->
  190. {ok, [tar_entry()]} | {error, term()}.
  191. table(Name, Opts) when is_list(Opts) ->
  192. foldl_read(Name, fun table1/4, [], table_opts(Opts)).
  193. table1(eof, Reader, _, Result) ->
  194. {ok, {ok, lists:reverse(Result)}, Reader};
  195. table1(#tar_header{}=Header, Reader, #read_opts{verbose=Verbose}, Result) ->
  196. Attrs = table1_attrs(Header, Verbose),
  197. Reader2 = skip_file(Reader),
  198. {ok, [Attrs|Result], Reader2}.
  199. %% Extracts attributes relevant to table1's output
  200. table1_attrs(#tar_header{typeflag=Typeflag,mode=Mode}=Header, true) ->
  201. Type = typeflag(Typeflag),
  202. Name = Header#tar_header.name,
  203. Mtime = Header#tar_header.mtime,
  204. Uid = Header#tar_header.uid,
  205. Gid = Header#tar_header.gid,
  206. Size = Header#tar_header.size,
  207. {Name, Type, Size, Mtime, Mode, Uid, Gid};
  208. table1_attrs(#tar_header{name=Name}, _Verbose) ->
  209. Name.
  210. typeflag(?TYPE_REGULAR) -> regular;
  211. typeflag(?TYPE_REGULAR_A) -> regular;
  212. typeflag(?TYPE_GNU_SPARSE) -> regular;
  213. typeflag(?TYPE_CONT) -> regular;
  214. typeflag(?TYPE_LINK) -> link;
  215. typeflag(?TYPE_SYMLINK) -> symlink;
  216. typeflag(?TYPE_CHAR) -> char;
  217. typeflag(?TYPE_BLOCK) -> block;
  218. typeflag(?TYPE_DIR) -> directory;
  219. typeflag(?TYPE_FIFO) -> fifo;
  220. typeflag(_) -> unknown.
  221. %%%================================================================
  222. %% Comments for printing the contents of a tape archive,
  223. %% meant to be invoked from the shell.
  224. %% Prints each filename in the archive
  225. -spec t(file:filename()) -> ok | {error, term()}.
  226. t(Name) when is_list(Name); is_binary(Name) ->
  227. case table(Name) of
  228. {ok, List} ->
  229. lists:foreach(fun(N) -> ok = io:format("~ts\n", [N]) end, List);
  230. Error ->
  231. Error
  232. end.
  233. %% Prints verbose information about each file in the archive
  234. -spec tt(open_handle()) -> ok | {error, term()}.
  235. tt(Name) ->
  236. case table(Name, [verbose]) of
  237. {ok, List} ->
  238. lists:foreach(fun print_header/1, List);
  239. Error ->
  240. Error
  241. end.
  242. %% Used by tt/1 to print a tar_entry tuple
  243. -spec print_header(tar_entry()) -> ok.
  244. print_header({Name, Type, Size, Mtime, Mode, Uid, Gid}) ->
  245. io:format("~s~s ~4w/~-4w ~7w ~s ~s\n",
  246. [type_to_string(Type), mode_to_string(Mode),
  247. Uid, Gid, Size, time_to_string(Mtime), Name]).
  248. type_to_string(regular) -> "-";
  249. type_to_string(directory) -> "d";
  250. type_to_string(link) -> "l";
  251. type_to_string(symlink) -> "s";
  252. type_to_string(char) -> "c";
  253. type_to_string(block) -> "b";
  254. type_to_string(fifo) -> "f";
  255. type_to_string(unknown) -> "?".
  256. %% Converts a numeric mode to its human-readable representation
  257. mode_to_string(Mode) ->
  258. mode_to_string(Mode, "xwrxwrxwr", []).
  259. mode_to_string(Mode, [C|T], Acc) when Mode band 1 =:= 1 ->
  260. mode_to_string(Mode bsr 1, T, [C|Acc]);
  261. mode_to_string(Mode, [_|T], Acc) ->
  262. mode_to_string(Mode bsr 1, T, [$-|Acc]);
  263. mode_to_string(_, [], Acc) ->
  264. Acc.
  265. %% Converts a tar_time() (POSIX time) to a readable string
  266. time_to_string(Secs0) ->
  267. Epoch = calendar:datetime_to_gregorian_seconds(?EPOCH),
  268. Secs = Epoch + Secs0,
  269. DateTime0 = calendar:gregorian_seconds_to_datetime(Secs),
  270. DateTime = calendar:universal_time_to_local_time(DateTime0),
  271. {{Y, Mon, Day}, {H, Min, _}} = DateTime,
  272. io_lib:format("~s ~2w ~s:~s ~w", [month(Mon), Day, two_d(H), two_d(Min), Y]).
  273. two_d(N) ->
  274. tl(integer_to_list(N + 100)).
  275. month(1) -> "Jan";
  276. month(2) -> "Feb";
  277. month(3) -> "Mar";
  278. month(4) -> "Apr";
  279. month(5) -> "May";
  280. month(6) -> "Jun";
  281. month(7) -> "Jul";
  282. month(8) -> "Aug";
  283. month(9) -> "Sep";
  284. month(10) -> "Oct";
  285. month(11) -> "Nov";
  286. month(12) -> "Dec".
  287. %%%================================================================
  288. %% The open function with friends is to keep the file and binary api of this module
  289. -type open_handle() :: file:filename()
  290. | {binary, binary()}
  291. | {file, term()}.
  292. -spec open(open_handle(), [write | compressed | cooked]) ->
  293. {ok, reader()} | {error, term()}.
  294. open({binary, Bin}, Mode) when is_binary(Bin) ->
  295. do_open({binary, Bin}, Mode);
  296. open({file, Fd}, Mode) ->
  297. do_open({file, Fd}, Mode);
  298. open(Name, Mode) when is_list(Name); is_binary(Name) ->
  299. do_open(Name, Mode).
  300. do_open(Name, Mode) when is_list(Mode) ->
  301. case open_mode(Mode) of
  302. {ok, Access, Raw, Opts} ->
  303. open1(Name, Access, Raw, Opts);
  304. {error, Reason} ->
  305. {error, {Name, Reason}}
  306. end.
  307. open1({binary,Bin}, read, _Raw, Opts) when is_binary(Bin) ->
  308. case file:open(Bin, [ram,binary,read]) of
  309. {ok,File} ->
  310. _ = [ram_file:uncompress(File) || Opts =:= [compressed]],
  311. {ok, #reader{handle=File,access=read,func=fun file_op/2}};
  312. Error ->
  313. Error
  314. end;
  315. open1({file, Fd}, read, _Raw, _Opts) ->
  316. Reader = #reader{handle=Fd,access=read,func=fun file_op/2},
  317. case do_position(Reader, {cur, 0}) of
  318. {ok, Pos, Reader2} ->
  319. {ok, Reader2#reader{pos=Pos}};
  320. {error, _} = Err ->
  321. Err
  322. end;
  323. open1(Name, Access, Raw, Opts) when is_list(Name) or is_binary(Name) ->
  324. case file:open(Name, Raw ++ [binary, Access|Opts]) of
  325. {ok, File} ->
  326. {ok, #reader{handle=File,access=Access,func=fun file_op/2}};
  327. {error, Reason} ->
  328. {error, {Name, Reason}}
  329. end.
  330. open_mode(Mode) ->
  331. open_mode(Mode, false, [raw], []).
  332. open_mode(read, _, Raw, _) ->
  333. {ok, read, Raw, []};
  334. open_mode(write, _, Raw, _) ->
  335. {ok, write, Raw, []};
  336. open_mode([read|Rest], false, Raw, Opts) ->
  337. open_mode(Rest, read, Raw, Opts);
  338. open_mode([write|Rest], false, Raw, Opts) ->
  339. open_mode(Rest, write, Raw, Opts);
  340. open_mode([compressed|Rest], Access, Raw, Opts) ->
  341. open_mode(Rest, Access, Raw, [compressed|Opts]);
  342. open_mode([cooked|Rest], Access, _Raw, Opts) ->
  343. open_mode(Rest, Access, [], Opts);
  344. open_mode([], Access, Raw, Opts) ->
  345. {ok, Access, Raw, Opts};
  346. open_mode(_, _, _, _) ->
  347. {error, einval}.
  348. file_op(write, {Fd, Data}) ->
  349. file:write(Fd, Data);
  350. file_op(position, {Fd, Pos}) ->
  351. file:position(Fd, Pos);
  352. file_op(read2, {Fd, Size}) ->
  353. file:read(Fd, Size);
  354. file_op(close, Fd) ->
  355. file:close(Fd).
  356. %% Closes a tar archive.
  357. -spec close(reader()) -> ok | {error, term()}.
  358. close(#reader{access=read}=Reader) ->
  359. ok = do_close(Reader);
  360. close(#reader{access=write}=Reader) ->
  361. {ok, Reader2} = pad_file(Reader),
  362. ok = do_close(Reader2),
  363. ok;
  364. close(_) ->
  365. {error, einval}.
  366. pad_file(#reader{pos=Pos}=Reader) ->
  367. %% There must be at least two zero blocks at the end.
  368. PadCurrent = skip_padding(Pos+?BLOCK_SIZE),
  369. Padding = <<0:PadCurrent/unit:8>>,
  370. do_write(Reader, [Padding, ?ZERO_BLOCK, ?ZERO_BLOCK]).
  371. %%%================================================================
  372. %% Creation/modification of tar archives
  373. %% Creates a tar file Name containing the given files.
  374. -spec create(file:filename(), filelist()) -> ok | {error, {string(), term()}}.
  375. create(Name, FileList) when is_list(Name); is_binary(Name) ->
  376. create(Name, FileList, []).
  377. %% Creates a tar archive Name containing the given files.
  378. %% Accepted options: verbose, compressed, cooked
  379. -spec create(file:filename(), filelist(), [create_opt()]) ->
  380. ok | {error, term()} | {error, {string(), term()}}.
  381. create(Name, FileList, Options) when is_list(Name); is_binary(Name) ->
  382. Mode = lists:filter(fun(X) -> (X=:=compressed) or (X=:=cooked)
  383. end, Options),
  384. case open(Name, [write|Mode]) of
  385. {ok, TarFile} ->
  386. do_create(TarFile, FileList, Options);
  387. {error, _} = Err ->
  388. Err
  389. end.
  390. do_create(TarFile, [], _Opts) ->
  391. close(TarFile);
  392. do_create(TarFile, [{NameInArchive, NameOrBin}|Rest], Opts) ->
  393. case add(TarFile, NameOrBin, NameInArchive, Opts) of
  394. ok ->
  395. do_create(TarFile, Rest, Opts);
  396. {error, _} = Err ->
  397. _ = close(TarFile),
  398. Err
  399. end;
  400. do_create(TarFile, [Name|Rest], Opts) ->
  401. case add(TarFile, Name, Name, Opts) of
  402. ok ->
  403. do_create(TarFile, Rest, Opts);
  404. {error, _} = Err ->
  405. _ = close(TarFile),
  406. Err
  407. end.
  408. %% Adds a file to a tape archive.
  409. -type add_type() :: string()
  410. | {string(), string()}
  411. | {string(), binary()}.
  412. -spec add(reader(), add_type(), [add_opt()]) -> ok | {error, term()}.
  413. add(Reader, {NameInArchive, Name}, Opts)
  414. when is_list(NameInArchive), is_list(Name) ->
  415. do_add(Reader, Name, NameInArchive, undefined, Opts);
  416. add(Reader, {NameInArchive, Bin}, Opts)
  417. when is_list(NameInArchive), is_binary(Bin) ->
  418. do_add(Reader, Bin, NameInArchive, undefined, Opts);
  419. add(Reader, {NameInArchive, Bin, Mode}, Opts)
  420. when is_list(NameInArchive), is_binary(Bin), is_integer(Mode) ->
  421. do_add(Reader, Bin, NameInArchive, Mode, Opts);
  422. add(Reader, Name, Opts) when is_list(Name) ->
  423. do_add(Reader, Name, Name, undefined, Opts).
  424. -spec add(reader(), string() | binary(), string(), [add_opt()]) ->
  425. ok | {error, term()}.
  426. add(Reader, NameOrBin, NameInArchive, Options)
  427. when is_list(NameOrBin); is_binary(NameOrBin),
  428. is_list(NameInArchive), is_list(Options) ->
  429. do_add(Reader, NameOrBin, NameInArchive, undefined, Options).
  430. -spec add(reader(), string() | binary(), string(), integer(), [add_opt()]) ->
  431. ok | {error, term()}.
  432. add(Reader, NameOrBin, NameInArchive, Mode, Options)
  433. when is_list(NameOrBin); is_binary(NameOrBin),
  434. is_list(NameInArchive), is_integer(Mode), is_list(Options) ->
  435. do_add(Reader, NameOrBin, NameInArchive, Mode, Options).
  436. do_add(#reader{access=write}=Reader, Name, NameInArchive, Mode, Options)
  437. when is_list(NameInArchive), is_list(Options) ->
  438. RF = fun(F) -> apply_file_info_opts(Options, file:read_link_info(F, [{time, posix}])) end,
  439. Opts = #add_opts{read_info=RF},
  440. add1(Reader, Name, NameInArchive, Mode, add_opts(Options, Options, Opts));
  441. do_add(#reader{access=read},_,_,_,_) ->
  442. {error, eacces};
  443. do_add(Reader,_,_,_,_) ->
  444. {error, {badarg, Reader}}.
  445. add_opts([dereference|T], AllOptions, Opts) ->
  446. RF = fun(F) -> apply_file_info_opts(AllOptions, file:read_file_info(F, [{time, posix}])) end,
  447. add_opts(T, AllOptions, Opts#add_opts{read_info=RF});
  448. add_opts([verbose|T], AllOptions, Opts) ->
  449. add_opts(T, AllOptions, Opts#add_opts{verbose=true});
  450. add_opts([{chunks,N}|T], AllOptions, Opts) ->
  451. add_opts(T, AllOptions, Opts#add_opts{chunk_size=N});
  452. add_opts([{atime,Value}|T], AllOptions, Opts) ->
  453. add_opts(T, AllOptions, Opts#add_opts{atime=Value});
  454. add_opts([{mtime,Value}|T], AllOptions, Opts) ->
  455. add_opts(T, AllOptions, Opts#add_opts{mtime=Value});
  456. add_opts([{ctime,Value}|T], AllOptions, Opts) ->
  457. add_opts(T, AllOptions, Opts#add_opts{ctime=Value});
  458. add_opts([{uid,Value}|T], AllOptions, Opts) ->
  459. add_opts(T, AllOptions, Opts#add_opts{uid=Value});
  460. add_opts([{gid,Value}|T], AllOptions, Opts) ->
  461. add_opts(T, AllOptions, Opts#add_opts{gid=Value});
  462. add_opts([_|T], AllOptions, Opts) ->
  463. add_opts(T, AllOptions, Opts);
  464. add_opts([], _AllOptions, Opts) ->
  465. Opts.
  466. apply_file_info_opts(Opts, {ok, FileInfo}) ->
  467. {ok, do_apply_file_info_opts(Opts, FileInfo)};
  468. apply_file_info_opts(_Opts, Other) ->
  469. Other.
  470. do_apply_file_info_opts([{atime,Value}|T], FileInfo) ->
  471. do_apply_file_info_opts(T, FileInfo#file_info{atime=Value});
  472. do_apply_file_info_opts([{mtime,Value}|T], FileInfo) ->
  473. do_apply_file_info_opts(T, FileInfo#file_info{mtime=Value});
  474. do_apply_file_info_opts([{ctime,Value}|T], FileInfo) ->
  475. do_apply_file_info_opts(T, FileInfo#file_info{ctime=Value});
  476. do_apply_file_info_opts([{uid,Value}|T], FileInfo) ->
  477. do_apply_file_info_opts(T, FileInfo#file_info{uid=Value});
  478. do_apply_file_info_opts([{gid,Value}|T], FileInfo) ->
  479. do_apply_file_info_opts(T, FileInfo#file_info{gid=Value});
  480. do_apply_file_info_opts([_|T], FileInfo) ->
  481. do_apply_file_info_opts(T, FileInfo);
  482. do_apply_file_info_opts([], FileInfo) ->
  483. FileInfo.
  484. add1(#reader{}=Reader, Name, NameInArchive, undefined, #add_opts{read_info=ReadInfo}=Opts)
  485. when is_list(Name) ->
  486. Res = case ReadInfo(Name) of
  487. {error, Reason0} ->
  488. {error, {Name, Reason0}};
  489. {ok, #file_info{type=symlink}=Fi} ->
  490. add_verbose(Opts, "a ~ts~n", [NameInArchive]),
  491. {ok, Linkname} = file:read_link(Name),
  492. Header = fileinfo_to_header(NameInArchive, Fi, Linkname),
  493. add_header(Reader, Header, Opts);
  494. {ok, #file_info{type=regular}=Fi} ->
  495. add_verbose(Opts, "a ~ts~n", [NameInArchive]),
  496. Header = fileinfo_to_header(NameInArchive, Fi, false),
  497. {ok, Reader2} = add_header(Reader, Header, Opts),
  498. FileSize = Header#tar_header.size,
  499. {ok, FileSize, Reader3} = do_copy(Reader2, Name, Opts),
  500. Padding = skip_padding(FileSize),
  501. Pad = <<0:Padding/unit:8>>,
  502. do_write(Reader3, Pad);
  503. {ok, #file_info{type=directory}=Fi} ->
  504. add_directory(Reader, Name, NameInArchive, Fi, Opts);
  505. {ok, #file_info{}=Fi} ->
  506. add_verbose(Opts, "a ~ts~n", [NameInArchive]),
  507. Header = fileinfo_to_header(NameInArchive, Fi, false),
  508. add_header(Reader, Header, Opts)
  509. end,
  510. case Res of
  511. ok -> ok;
  512. {ok, _Reader} -> ok;
  513. {error, _Reason} = Err -> Err
  514. end;
  515. add1(Reader, Bin, NameInArchive, Mode, Opts) when is_binary(Bin) ->
  516. add_verbose(Opts, "a ~ts~n", [NameInArchive]),
  517. Now = 0,
  518. Header = #tar_header{
  519. name = NameInArchive,
  520. size = byte_size(Bin),
  521. typeflag = ?TYPE_REGULAR,
  522. atime = add_opts_time(Opts#add_opts.atime, Now),
  523. mtime = add_opts_time(Opts#add_opts.mtime, Now),
  524. ctime = add_opts_time(Opts#add_opts.ctime, Now),
  525. uid = Opts#add_opts.uid,
  526. gid = Opts#add_opts.gid,
  527. mode = default_mode(Mode, 8#100644)},
  528. {ok, Reader2} = add_header(Reader, Header, Opts),
  529. Padding = skip_padding(byte_size(Bin)),
  530. Data = [Bin, <<0:Padding/unit:8>>],
  531. case do_write(Reader2, Data) of
  532. {ok, _Reader3} -> ok;
  533. {error, Reason} -> {error, {NameInArchive, Reason}}
  534. end.
  535. add_opts_time(undefined, _Now) -> 0;
  536. add_opts_time(Time, _Now) -> Time.
  537. default_mode(undefined, Mode) -> Mode;
  538. default_mode(Mode, _) -> Mode.
  539. add_directory(Reader, DirName, NameInArchive, Info, Opts) ->
  540. case file:list_dir(DirName) of
  541. {ok, []} ->
  542. add_verbose(Opts, "a ~ts~n", [NameInArchive]),
  543. Header = fileinfo_to_header(NameInArchive, Info, false),
  544. add_header(Reader, Header, Opts);
  545. {ok, Files} ->
  546. add_verbose(Opts, "a ~ts~n", [NameInArchive]),
  547. try add_files(Reader, Files, DirName, NameInArchive, Opts) of
  548. ok -> ok;
  549. {error, _} = Err -> Err
  550. catch
  551. throw:{error, {_Name, _Reason}} = Err -> Err;
  552. throw:{error, Reason} -> {error, {DirName, Reason}}
  553. end;
  554. {error, Reason} ->
  555. {error, {DirName, Reason}}
  556. end.
  557. add_files(_Reader, [], _Dir, _DirInArchive, _Opts) ->
  558. ok;
  559. add_files(Reader, [Name|Rest], Dir, DirInArchive, #add_opts{read_info=Info}=Opts) ->
  560. FullName = filename:join(Dir, Name),
  561. NameInArchive = filename:join(DirInArchive, Name),
  562. Res = case Info(FullName) of
  563. {error, Reason} ->
  564. {error, {FullName, Reason}};
  565. {ok, #file_info{type=directory}=Fi} ->
  566. add_directory(Reader, FullName, NameInArchive, Fi, Opts);
  567. {ok, #file_info{type=symlink}=Fi} ->
  568. add_verbose(Opts, "a ~ts~n", [NameInArchive]),
  569. {ok, Linkname} = file:read_link(FullName),
  570. Header = fileinfo_to_header(NameInArchive, Fi, Linkname),
  571. add_header(Reader, Header, Opts);
  572. {ok, #file_info{type=regular}=Fi} ->
  573. add_verbose(Opts, "a ~ts~n", [NameInArchive]),
  574. Header = fileinfo_to_header(NameInArchive, Fi, false),
  575. {ok, Reader2} = add_header(Reader, Header, Opts),
  576. FileSize = Header#tar_header.size,
  577. {ok, FileSize, Reader3} = do_copy(Reader2, FullName, Opts),
  578. Padding = skip_padding(FileSize),
  579. Pad = <<0:Padding/unit:8>>,
  580. do_write(Reader3, Pad);
  581. {ok, #file_info{}=Fi} ->
  582. add_verbose(Opts, "a ~ts~n", [NameInArchive]),
  583. Header = fileinfo_to_header(NameInArchive, Fi, false),
  584. add_header(Reader, Header, Opts)
  585. end,
  586. case Res of
  587. ok -> add_files(Reader, Rest, Dir, DirInArchive, Opts);
  588. {ok, ReaderNext} -> add_files(ReaderNext, Rest, Dir, DirInArchive, Opts);
  589. {error, _} = Err -> Err
  590. end.
  591. format_string(String, Size) when length(String) > Size ->
  592. throw({error, {write_string, field_too_long}});
  593. format_string(String, Size) ->
  594. Ascii = to_ascii(String),
  595. if byte_size(Ascii) < Size ->
  596. [Ascii, 0];
  597. true ->
  598. Ascii
  599. end.
  600. format_octal(Octal) ->
  601. iolist_to_binary(io_lib:fwrite("~.8B", [Octal])).
  602. add_header(#reader{}=Reader, #tar_header{}=Header, Opts) ->
  603. {ok, Iodata} = build_header(Header, Opts),
  604. do_write(Reader, Iodata).
  605. write_to_block(Block, IoData, Start) when is_list(IoData) ->
  606. write_to_block(Block, iolist_to_binary(IoData), Start);
  607. write_to_block(Block, Bin, Start) when is_binary(Bin) ->
  608. Size = byte_size(Bin),
  609. <<Head:Start/unit:8, _:Size/unit:8, Rest/binary>> = Block,
  610. <<Head:Start/unit:8, Bin/binary, Rest/binary>>.
  611. build_header(#tar_header{}=Header, Opts) ->
  612. #tar_header{
  613. name=Name,
  614. mode=Mode,
  615. uid=Uid,
  616. gid=Gid,
  617. size=Size,
  618. typeflag=Type,
  619. linkname=Linkname,
  620. uname=Uname,
  621. gname=Gname,
  622. devmajor=Devmaj,
  623. devminor=Devmin
  624. } = Header,
  625. Mtime = Header#tar_header.mtime,
  626. Block0 = ?ZERO_BLOCK,
  627. {Block1, Pax0} = write_string(Block0, ?V7_NAME, ?V7_NAME_LEN, Name, ?PAX_PATH, #{}),
  628. Block2 = write_octal(Block1, ?V7_MODE, ?V7_MODE_LEN, Mode),
  629. {Block3, Pax1} = write_numeric(Block2, ?V7_UID, ?V7_UID_LEN, Uid, ?PAX_UID, Pax0),
  630. {Block4, Pax2} = write_numeric(Block3, ?V7_GID, ?V7_GID_LEN, Gid, ?PAX_GID, Pax1),
  631. {Block5, Pax3} = write_numeric(Block4, ?V7_SIZE, ?V7_SIZE_LEN, Size, ?PAX_SIZE, Pax2),
  632. {Block6, Pax4} = write_numeric(Block5, ?V7_MTIME, ?V7_MTIME_LEN, Mtime, ?PAX_NONE, Pax3),
  633. {Block7, Pax5} = write_string(Block6, ?V7_TYPE, ?V7_TYPE_LEN, <<Type>>, ?PAX_NONE, Pax4),
  634. {Block8, Pax6} = write_string(Block7, ?V7_LINKNAME, ?V7_LINKNAME_LEN,
  635. Linkname, ?PAX_LINKPATH, Pax5),
  636. {Block9, Pax7} = write_string(Block8, ?USTAR_UNAME, ?USTAR_UNAME_LEN,
  637. Uname, ?PAX_UNAME, Pax6),
  638. {Block10, Pax8} = write_string(Block9, ?USTAR_GNAME, ?USTAR_GNAME_LEN,
  639. Gname, ?PAX_GNAME, Pax7),
  640. {Block11, Pax9} = write_numeric(Block10, ?USTAR_DEVMAJ, ?USTAR_DEVMAJ_LEN,
  641. Devmaj, ?PAX_NONE, Pax8),
  642. {Block12, Pax10} = write_numeric(Block11, ?USTAR_DEVMIN, ?USTAR_DEVMIN_LEN,
  643. Devmin, ?PAX_NONE, Pax9),
  644. {Block13, Pax11} = set_path(Block12, Pax10),
  645. PaxEntry = case maps:size(Pax11) of
  646. 0 -> [];
  647. _ -> build_pax_entry(Header, Pax11, Opts)
  648. end,
  649. Block14 = set_format(Block13, ?FORMAT_USTAR),
  650. Block15 = set_checksum(Block14),
  651. {ok, [PaxEntry, Block15]}.
  652. set_path(Block0, Pax) ->
  653. %% only use ustar header when name is too long
  654. case maps:get(?PAX_PATH, Pax, nil) of
  655. nil ->
  656. {Block0, Pax};
  657. PaxPath ->
  658. case split_ustar_path(PaxPath) of
  659. {ok, UstarName, UstarPrefix} ->
  660. {Block1, _} = write_string(Block0, ?V7_NAME, ?V7_NAME_LEN,
  661. UstarName, ?PAX_NONE, #{}),
  662. {Block2, _} = write_string(Block1, ?USTAR_PREFIX, ?USTAR_PREFIX_LEN,
  663. UstarPrefix, ?PAX_NONE, #{}),
  664. {Block2, maps:remove(?PAX_PATH, Pax)};
  665. false ->
  666. {Block0, Pax}
  667. end
  668. end.
  669. set_format(Block0, Format)
  670. when Format =:= ?FORMAT_USTAR; Format =:= ?FORMAT_PAX ->
  671. Block1 = write_to_block(Block0, ?MAGIC_USTAR, ?USTAR_MAGIC),
  672. write_to_block(Block1, ?VERSION_USTAR, ?USTAR_VERSION);
  673. set_format(_Block, Format) ->
  674. throw({error, {invalid_format, Format}}).
  675. set_checksum(Block) ->
  676. Checksum = compute_checksum(Block),
  677. write_octal(Block, ?V7_CHKSUM, ?V7_CHKSUM_LEN, Checksum).
  678. build_pax_entry(Header, PaxAttrs, Opts) ->
  679. Path = Header#tar_header.name,
  680. Filename = filename:basename(Path),
  681. Dir = filename:dirname(Path),
  682. Path2 = filename:join([Dir, "PaxHeaders.0", Filename]),
  683. AsciiPath = to_ascii(Path2),
  684. Path3 = if byte_size(AsciiPath) > ?V7_NAME_LEN ->
  685. binary_part(AsciiPath, 0, ?V7_NAME_LEN - 1);
  686. true ->
  687. AsciiPath
  688. end,
  689. Keys = maps:keys(PaxAttrs),
  690. SortedKeys = lists:sort(Keys),
  691. PaxFile = build_pax_file(SortedKeys, PaxAttrs),
  692. Size = byte_size(PaxFile),
  693. Padding = (?BLOCK_SIZE -
  694. (byte_size(PaxFile) rem ?BLOCK_SIZE)) rem ?BLOCK_SIZE,
  695. Pad = <<0:Padding/unit:8>>,
  696. PaxHeader = #tar_header{
  697. name=unicode:characters_to_list(Path3),
  698. size=Size,
  699. mtime=Header#tar_header.mtime,
  700. atime=Header#tar_header.atime,
  701. ctime=Header#tar_header.ctime,
  702. typeflag=?TYPE_X_HEADER
  703. },
  704. {ok, PaxHeaderData} = build_header(PaxHeader, Opts),
  705. [PaxHeaderData, PaxFile, Pad].
  706. build_pax_file(Keys, PaxAttrs) ->
  707. build_pax_file(Keys, PaxAttrs, []).
  708. build_pax_file([], _, Acc) ->
  709. unicode:characters_to_binary(Acc);
  710. build_pax_file([K|Rest], Attrs, Acc) ->
  711. V = maps:get(K, Attrs),
  712. Size = sizeof(K) + sizeof(V) + 3,
  713. Size2 = sizeof(Size) + Size,
  714. Key = to_string(K),
  715. Value = to_string(V),
  716. Record = unicode:characters_to_binary(io_lib:format("~B ~ts=~ts\n", [Size2, Key, Value])),
  717. if byte_size(Record) =/= Size2 ->
  718. Size3 = byte_size(Record),
  719. Record2 = io_lib:format("~B ~ts=~ts\n", [Size3, Key, Value]),
  720. build_pax_file(Rest, Attrs, [Acc, Record2]);
  721. true ->
  722. build_pax_file(Rest, Attrs, [Acc, Record])
  723. end.
  724. sizeof(Bin) when is_binary(Bin) ->
  725. byte_size(Bin);
  726. sizeof(List) when is_list(List) ->
  727. length(List);
  728. sizeof(N) when is_integer(N) ->
  729. byte_size(integer_to_binary(N));
  730. sizeof(N) when is_float(N) ->
  731. byte_size(float_to_binary(N)).
  732. to_string(Bin) when is_binary(Bin) ->
  733. unicode:characters_to_list(Bin);
  734. to_string(List) when is_list(List) ->
  735. List;
  736. to_string(N) when is_integer(N) ->
  737. integer_to_list(N);
  738. to_string(N) when is_float(N) ->
  739. float_to_list(N).
  740. split_ustar_path(Path) ->
  741. Len = length(Path),
  742. NotAscii = not is_ascii(Path),
  743. if Len =< ?V7_NAME_LEN; NotAscii ->
  744. false;
  745. true ->
  746. PathBin = binary:list_to_bin(Path),
  747. case binary:split(PathBin, [<<$/>>], [global, trim_all]) of
  748. [Part] when byte_size(Part) >= ?V7_NAME_LEN ->
  749. false;
  750. Parts ->
  751. case lists:last(Parts) of
  752. Name when byte_size(Name) >= ?V7_NAME_LEN ->
  753. false;
  754. Name ->
  755. Parts2 = lists:sublist(Parts, length(Parts) - 1),
  756. join_split_ustar_path(Parts2, {ok, Name, nil})
  757. end
  758. end
  759. end.
  760. join_split_ustar_path([], Acc) ->
  761. Acc;
  762. join_split_ustar_path([Part|_], {ok, _, nil})
  763. when byte_size(Part) > ?USTAR_PREFIX_LEN ->
  764. false;
  765. join_split_ustar_path([Part|_], {ok, _Name, Acc})
  766. when (byte_size(Part)+byte_size(Acc)) > ?USTAR_PREFIX_LEN ->
  767. false;
  768. join_split_ustar_path([Part|Rest], {ok, Name, nil}) ->
  769. join_split_ustar_path(Rest, {ok, Name, Part});
  770. join_split_ustar_path([Part|Rest], {ok, Name, Acc}) ->
  771. join_split_ustar_path(Rest, {ok, Name, <<Acc/binary,$/,Part/binary>>}).
  772. write_octal(Block, Pos, Size, X) ->
  773. Octal = zero_pad(format_octal(X), Size-1),
  774. if byte_size(Octal) < Size ->
  775. write_to_block(Block, Octal, Pos);
  776. true ->
  777. throw({error, {write_failed, octal_field_too_long}})
  778. end.
  779. write_string(Block, Pos, Size, Str, PaxAttr, Pax0) ->
  780. NotAscii = not is_ascii(Str),
  781. if PaxAttr =/= ?PAX_NONE andalso (length(Str) > Size orelse NotAscii) ->
  782. Pax1 = maps:put(PaxAttr, Str, Pax0),
  783. {Block, Pax1};
  784. true ->
  785. Formatted = format_string(Str, Size),
  786. {write_to_block(Block, Formatted, Pos), Pax0}
  787. end.
  788. write_numeric(Block, Pos, Size, X, PaxAttr, Pax0) ->
  789. %% attempt octal
  790. Octal = zero_pad(format_octal(X), Size-1),
  791. if byte_size(Octal) < Size ->
  792. {write_to_block(Block, [Octal, 0], Pos), Pax0};
  793. PaxAttr =/= ?PAX_NONE ->
  794. Pax1 = maps:put(PaxAttr, X, Pax0),
  795. {Block, Pax1};
  796. true ->
  797. throw({error, {write_failed, numeric_field_too_long}})
  798. end.
  799. zero_pad(Str, Size) when byte_size(Str) >= Size ->
  800. Str;
  801. zero_pad(Str, Size) ->
  802. Padding = Size - byte_size(Str),
  803. Pad = binary:copy(<<$0>>, Padding),
  804. <<Pad/binary, Str/binary>>.
  805. %%%================================================================
  806. %% Functions for creating or modifying tar archives
  807. read_block(Reader) ->
  808. case do_read(Reader, ?BLOCK_SIZE) of
  809. eof ->
  810. throw({error, eof});
  811. %% Two zero blocks mark the end of the archive
  812. {ok, ?ZERO_BLOCK, Reader1} ->
  813. case do_read(Reader1, ?BLOCK_SIZE) of
  814. eof ->
  815. % This is technically a malformed end-of-archive marker,
  816. % as two ZERO_BLOCKs are expected as the marker,
  817. % but if we've already made it this far, we should just ignore it
  818. eof;
  819. {ok, ?ZERO_BLOCK, _Reader2} ->
  820. eof;
  821. {ok, _Block, _Reader2} ->
  822. throw({error, invalid_end_of_archive});
  823. {error,_} = Err ->
  824. throw(Err)
  825. end;
  826. {ok, Block, Reader1} when is_binary(Block) ->
  827. {ok, Block, Reader1};
  828. {error, _} = Err ->
  829. throw(Err)
  830. end.
  831. get_header(#reader{}=Reader) ->
  832. case read_block(Reader) of
  833. eof ->
  834. eof;
  835. {ok, Block, Reader1} ->
  836. convert_header(Block, Reader1)
  837. end.
  838. %% Converts the tar header to a record.
  839. to_v7(Bin) when is_binary(Bin), byte_size(Bin) =:= ?BLOCK_SIZE ->
  840. #header_v7{
  841. name=binary_part(Bin, ?V7_NAME, ?V7_NAME_LEN),
  842. mode=binary_part(Bin, ?V7_MODE, ?V7_MODE_LEN),
  843. uid=binary_part(Bin, ?V7_UID, ?V7_UID_LEN),
  844. gid=binary_part(Bin, ?V7_GID, ?V7_GID_LEN),
  845. size=binary_part(Bin, ?V7_SIZE, ?V7_SIZE_LEN),
  846. mtime=binary_part(Bin, ?V7_MTIME, ?V7_MTIME_LEN),
  847. checksum=binary_part(Bin, ?V7_CHKSUM, ?V7_CHKSUM_LEN),
  848. typeflag=binary:at(Bin, ?V7_TYPE),
  849. linkname=binary_part(Bin, ?V7_LINKNAME, ?V7_LINKNAME_LEN)
  850. };
  851. to_v7(_) ->
  852. {error, header_block_too_small}.
  853. to_gnu(#header_v7{}=V7, Bin)
  854. when is_binary(Bin), byte_size(Bin) =:= ?BLOCK_SIZE ->
  855. #header_gnu{
  856. header_v7=V7,
  857. magic=binary_part(Bin, ?GNU_MAGIC, ?GNU_MAGIC_LEN),
  858. version=binary_part(Bin, ?GNU_VERSION, ?GNU_VERSION_LEN),
  859. uname=binary_part(Bin, 265, 32),
  860. gname=binary_part(Bin, 297, 32),
  861. devmajor=binary_part(Bin, 329, 8),
  862. devminor=binary_part(Bin, 337, 8),
  863. atime=binary_part(Bin, 345, 12),
  864. ctime=binary_part(Bin, 357, 12),
  865. sparse=to_sparse_array(binary_part(Bin, 386, 24*4+1)),
  866. real_size=binary_part(Bin, 483, 12)
  867. }.
  868. to_star(#header_v7{}=V7, Bin)
  869. when is_binary(Bin), byte_size(Bin) =:= ?BLOCK_SIZE ->
  870. #header_star{
  871. header_v7=V7,
  872. magic=binary_part(Bin, ?USTAR_MAGIC, ?USTAR_MAGIC_LEN),
  873. version=binary_part(Bin, ?USTAR_VERSION, ?USTAR_VERSION_LEN),
  874. uname=binary_part(Bin, ?USTAR_UNAME, ?USTAR_UNAME_LEN),
  875. gname=binary_part(Bin, ?USTAR_GNAME, ?USTAR_GNAME_LEN),
  876. devmajor=binary_part(Bin, ?USTAR_DEVMAJ, ?USTAR_DEVMAJ_LEN),
  877. devminor=binary_part(Bin, ?USTAR_DEVMIN, ?USTAR_DEVMIN_LEN),
  878. prefix=binary_part(Bin, 345, 131),
  879. atime=binary_part(Bin, 476, 12),
  880. ctime=binary_part(Bin, 488, 12),
  881. trailer=binary_part(Bin, ?STAR_TRAILER, ?STAR_TRAILER_LEN)
  882. }.
  883. to_ustar(#header_v7{}=V7, Bin)
  884. when is_binary(Bin), byte_size(Bin) =:= ?BLOCK_SIZE ->
  885. #header_ustar{
  886. header_v7=V7,
  887. magic=binary_part(Bin, ?USTAR_MAGIC, ?USTAR_MAGIC_LEN),
  888. version=binary_part(Bin, ?USTAR_VERSION, ?USTAR_VERSION_LEN),
  889. uname=binary_part(Bin, ?USTAR_UNAME, ?USTAR_UNAME_LEN),
  890. gname=binary_part(Bin, ?USTAR_GNAME, ?USTAR_GNAME_LEN),
  891. devmajor=binary_part(Bin, ?USTAR_DEVMAJ, ?USTAR_DEVMAJ_LEN),
  892. devminor=binary_part(Bin, ?USTAR_DEVMIN, ?USTAR_DEVMIN_LEN),
  893. prefix=binary_part(Bin, 345, 155)
  894. }.
  895. to_sparse_array(Bin) when is_binary(Bin) ->
  896. MaxEntries = byte_size(Bin) div 24,
  897. IsExtended = 1 =:= binary:at(Bin, 24*MaxEntries),
  898. Entries = parse_sparse_entries(Bin, MaxEntries-1, []),
  899. #sparse_array{
  900. entries=Entries,
  901. max_entries=MaxEntries,
  902. is_extended=IsExtended
  903. }.
  904. parse_sparse_entries(<<>>, _, Acc) ->
  905. Acc;
  906. parse_sparse_entries(_, -1, Acc) ->
  907. Acc;
  908. parse_sparse_entries(Bin, N, Acc) ->
  909. case to_sparse_entry(binary_part(Bin, N*24, 24)) of
  910. nil ->
  911. parse_sparse_entries(Bin, N-1, Acc);
  912. Entry = #sparse_entry{} ->
  913. parse_sparse_entries(Bin, N-1, [Entry|Acc])
  914. end.
  915. -define(EMPTY_ENTRY, <<0,0,0,0,0,0,0,0,0,0,0,0>>).
  916. to_sparse_entry(Bin) when is_binary(Bin), byte_size(Bin) =:= 24 ->
  917. OffsetBin = binary_part(Bin, 0, 12),
  918. NumBytesBin = binary_part(Bin, 12, 12),
  919. case {OffsetBin, NumBytesBin} of
  920. {?EMPTY_ENTRY, ?EMPTY_ENTRY} ->
  921. nil;
  922. _ ->
  923. #sparse_entry{
  924. offset=parse_numeric(OffsetBin),
  925. num_bytes=parse_numeric(NumBytesBin)}
  926. end.
  927. -spec get_format(binary()) -> {ok, pos_integer(), header_v7()}
  928. | ?FORMAT_UNKNOWN
  929. | {error, term()}.
  930. get_format(Bin) when is_binary(Bin), byte_size(Bin) =:= ?BLOCK_SIZE ->
  931. do_get_format(to_v7(Bin), Bin).
  932. do_get_format({error, _} = Err, _Bin) ->
  933. Err;
  934. do_get_format(#header_v7{}=V7, Bin)
  935. when is_binary(Bin), byte_size(Bin) =:= ?BLOCK_SIZE ->
  936. Checksum = parse_octal(V7#header_v7.checksum),
  937. Chk1 = compute_checksum(Bin),
  938. Chk2 = compute_signed_checksum(Bin),
  939. if Checksum =/= Chk1 andalso Checksum =/= Chk2 ->
  940. ?FORMAT_UNKNOWN;
  941. true ->
  942. %% guess magic
  943. Ustar = to_ustar(V7, Bin),
  944. Star = to_star(V7, Bin),
  945. Magic = Ustar#header_ustar.magic,
  946. Version = Ustar#header_ustar.version,
  947. Trailer = Star#header_star.trailer,
  948. Format = if
  949. Magic =:= ?MAGIC_USTAR, Trailer =:= ?TRAILER_STAR ->
  950. ?FORMAT_STAR;
  951. Magic =:= ?MAGIC_USTAR ->
  952. ?FORMAT_USTAR;
  953. Magic =:= ?MAGIC_GNU, Version =:= ?VERSION_GNU ->
  954. ?FORMAT_GNU;
  955. true ->
  956. ?FORMAT_V7
  957. end,
  958. {ok, Format, V7}
  959. end.
  960. unpack_format(Format, #header_v7{}=V7, Bin, Reader)
  961. when is_binary(Bin), byte_size(Bin) =:= ?BLOCK_SIZE ->
  962. Mtime = parse_numeric(V7#header_v7.mtime),
  963. Header0 = #tar_header{
  964. name=parse_string(V7#header_v7.name),
  965. mode=parse_numeric(V7#header_v7.mode),
  966. uid=parse_numeric(V7#header_v7.uid),
  967. gid=parse_numeric(V7#header_v7.gid),
  968. size=parse_numeric(V7#header_v7.size),
  969. mtime=Mtime,
  970. atime=Mtime,
  971. ctime=Mtime,
  972. typeflag=V7#header_v7.typeflag,
  973. linkname=parse_string(V7#header_v7.linkname)
  974. },
  975. Typeflag = Header0#tar_header.typeflag,
  976. Header1 = if Format > ?FORMAT_V7 ->
  977. unpack_modern(Format, V7, Bin, Header0);
  978. true ->
  979. Name = Header0#tar_header.name,
  980. Header0#tar_header{name=safe_join_path("", Name)}
  981. end,
  982. HeaderOnly = is_header_only_type(Typeflag),
  983. Header2 = if HeaderOnly ->
  984. Header1#tar_header{size=0};
  985. true ->
  986. Header1
  987. end,
  988. if Typeflag =:= ?TYPE_GNU_SPARSE ->
  989. Gnu = to_gnu(V7, Bin),
  990. RealSize = parse_numeric(Gnu#header_gnu.real_size),
  991. {Sparsemap, Reader2} = parse_sparse_map(Gnu, Reader),
  992. Header3 = Header2#tar_header{size=RealSize},
  993. {Header3, new_sparse_file_reader(Reader2, Sparsemap, RealSize)};
  994. true ->
  995. FileReader = #reg_file_reader{
  996. handle=Reader,
  997. num_bytes=Header2#tar_header.size,
  998. size=Header2#tar_header.size,
  999. pos = 0
  1000. },
  1001. {Header2, FileReader}
  1002. end.
  1003. unpack_modern(Format, #header_v7{}=V7, Bin, #tar_header{}=Header0)
  1004. when is_binary(Bin) ->
  1005. Typeflag = Header0#tar_header.typeflag,
  1006. Ustar = to_ustar(V7, Bin),
  1007. H0 = Header0#tar_header{
  1008. uname=parse_string(Ustar#header_ustar.uname),
  1009. gname=parse_string(Ustar#header_ustar.gname)},
  1010. H1 = if Typeflag =:= ?TYPE_CHAR
  1011. orelse Typeflag =:= ?TYPE_BLOCK ->
  1012. Ma = parse_numeric(Ustar#header_ustar.devmajor),
  1013. Mi = parse_numeric(Ustar#header_ustar.devminor),
  1014. H0#tar_header{
  1015. devmajor=Ma,
  1016. devminor=Mi
  1017. };
  1018. true ->
  1019. H0
  1020. end,
  1021. {Prefix, H2} = case Format of
  1022. ?FORMAT_USTAR ->
  1023. {parse_string(Ustar#header_ustar.prefix), H1};
  1024. ?FORMAT_STAR ->
  1025. Star = to_star(V7, Bin),
  1026. Prefix0 = parse_string(Star#header_star.prefix),
  1027. Atime0 = Star#header_star.atime,
  1028. Atime = parse_numeric(Atime0),
  1029. Ctime0 = Star#header_star.ctime,
  1030. Ctime = parse_numeric(Ctime0),
  1031. {Prefix0, H1#tar_header{
  1032. atime=Atime,
  1033. ctime=Ctime
  1034. }};
  1035. _ ->
  1036. {"", H1}
  1037. end,
  1038. Name = H2#tar_header.name,
  1039. H2#tar_header{name=safe_join_path(Prefix, Name)}.
  1040. safe_join_path([], Name) ->
  1041. filename:join([Name]);
  1042. safe_join_path(Prefix, []) ->
  1043. filename:join([Prefix]);
  1044. safe_join_path(Prefix, Name) ->
  1045. filename:join(Prefix, Name).
  1046. new_sparse_file_reader(Reader, Sparsemap, RealSize) ->
  1047. true = validate_sparse_entries(Sparsemap, RealSize),
  1048. #sparse_file_reader{
  1049. handle = Reader,
  1050. num_bytes = RealSize,
  1051. pos = 0,
  1052. size = RealSize,
  1053. sparse_map = Sparsemap}.
  1054. validate_sparse_entries(Entries, RealSize) ->
  1055. validate_sparse_entries(Entries, RealSize, 0, 0).
  1056. validate_sparse_entries([], _RealSize, _I, _LastOffset) ->
  1057. true;
  1058. validate_sparse_entries([#sparse_entry{}=Entry|Rest], RealSize, I, LastOffset) ->
  1059. Offset = Entry#sparse_entry.offset,
  1060. NumBytes = Entry#sparse_entry.num_bytes,
  1061. if
  1062. Offset > ?MAX_INT64-NumBytes ->
  1063. throw({error, {invalid_sparse_map_entry, offset_too_large}});
  1064. Offset+NumBytes > RealSize ->
  1065. throw({error, {invalid_sparse_map_entry, offset_too_large}});
  1066. I > 0 andalso LastOffset > Offset ->
  1067. throw({error, {invalid_sparse_map_entry, overlapping_offsets}});
  1068. true ->
  1069. ok
  1070. end,
  1071. validate_sparse_entries(Rest, RealSize, I+1, Offset+NumBytes).
  1072. -spec parse_sparse_map(header_gnu(), reader_type()) ->
  1073. {[sparse_entry()], reader_type()}.
  1074. parse_sparse_map(#header_gnu{sparse=Sparse}, Reader)
  1075. when Sparse#sparse_array.is_extended ->
  1076. parse_sparse_map(Sparse, Reader, []);
  1077. parse_sparse_map(#header_gnu{sparse=Sparse}, Reader) ->
  1078. {Sparse#sparse_array.entries, Reader}.
  1079. parse_sparse_map(#sparse_array{is_extended=true,entries=Entries}, Reader, Acc) ->
  1080. case read_block(Reader) of
  1081. eof ->
  1082. throw({error, eof});
  1083. {ok, Block, Reader2} ->
  1084. Sparse2 = to_sparse_array(Block),
  1085. parse_sparse_map(Sparse2, Reader2, Entries++Acc)
  1086. end;
  1087. parse_sparse_map(#sparse_array{entries=Entries}, Reader, Acc) ->
  1088. Sorted = lists:sort(fun (#sparse_entry{offset=A},#sparse_entry{offset=B}) ->
  1089. A =< B
  1090. end, Entries++Acc),
  1091. {Sorted, Reader}.
  1092. %% Defined by taking the sum of the unsigned byte values of the
  1093. %% entire header record, treating the checksum bytes to as ASCII spaces
  1094. compute_checksum(<<H1:?V7_CHKSUM/binary,
  1095. H2:?V7_CHKSUM_LEN/binary,
  1096. Rest:(?BLOCK_SIZE - ?V7_CHKSUM - ?V7_CHKSUM_LEN)/binary,
  1097. _/binary>>) ->
  1098. C0 = checksum(H1) + (byte_size(H2) * $\s),
  1099. C1 = checksum(Rest),
  1100. C0 + C1.
  1101. compute_signed_checksum(<<H1:?V7_CHKSUM/binary,
  1102. H2:?V7_CHKSUM_LEN/binary,
  1103. Rest:(?BLOCK_SIZE - ?V7_CHKSUM - ?V7_CHKSUM_LEN)/binary,
  1104. _/binary>>) ->
  1105. C0 = signed_checksum(H1) + (byte_size(H2) * $\s),
  1106. C1 = signed_checksum(Rest),
  1107. C0 + C1.
  1108. %% Returns the checksum of a binary.
  1109. checksum(Bin) -> checksum(Bin, 0).
  1110. checksum(<<A/unsigned,Rest/binary>>, Sum) ->
  1111. checksum(Rest, Sum+A);
  1112. checksum(<<>>, Sum) -> Sum.
  1113. signed_checksum(Bin) -> signed_checksum(Bin, 0).
  1114. signed_checksum(<<A/signed,Rest/binary>>, Sum) ->
  1115. signed_checksum(Rest, Sum+A);
  1116. signed_checksum(<<>>, Sum) -> Sum.
  1117. -spec parse_numeric(binary()) -> non_neg_integer().
  1118. parse_numeric(<<>>) ->
  1119. 0;
  1120. parse_numeric(<<First, _/binary>> = Bin) ->
  1121. %% check for base-256 format first
  1122. %% if the bit is set, then all following bits constitute a two's
  1123. %% complement encoded number in big-endian byte order
  1124. if
  1125. First band 16#80 =/= 0 ->
  1126. %% Handling negative numbers relies on the following identity:
  1127. %% -a-1 == ^a
  1128. %% If the number is negative, we use an inversion mask to invert
  1129. %% the data bytes and treat the value as an unsigned number
  1130. Inv = if First band 16#40 =/= 0 -> 16#00; true -> 16#FF end,
  1131. Bytes = binary:bin_to_list(Bin),
  1132. Reducer = fun (C, {I, X}) ->
  1133. C1 = C bxor Inv,
  1134. C2 = if I =:= 0 -> C1 band 16#7F; true -> C1 end,
  1135. if (X bsr 56) > 0 ->
  1136. throw({error,integer_overflow});
  1137. true ->
  1138. {I+1, (X bsl 8) bor C2}
  1139. end
  1140. end,
  1141. {_, N} = lists:foldl(Reducer, {0,0}, Bytes),
  1142. if (N bsr 63) > 0 ->
  1143. throw({error, integer_overflow});
  1144. true ->
  1145. if Inv =:= 16#FF ->
  1146. -1 bxor N;
  1147. true ->
  1148. N
  1149. end
  1150. end;
  1151. true ->
  1152. %% normal case is an octal number
  1153. parse_octal(Bin)
  1154. end.
  1155. parse_octal(Bin) when is_binary(Bin) ->
  1156. %% skip leading/trailing zero bytes and spaces
  1157. do_parse_octal(Bin, <<>>).
  1158. do_parse_octal(<<>>, <<>>) ->
  1159. 0;
  1160. do_parse_octal(<<>>, Acc) ->
  1161. case io_lib:fread("~8u", binary:bin_to_list(Acc)) of
  1162. {error, _} -> throw({error, invalid_tar_checksum});
  1163. {ok, [Octal], []} -> Octal;
  1164. {ok, _, _} -> throw({error, invalid_tar_checksum})
  1165. end;
  1166. do_parse_octal(<<$\s,Rest/binary>>, Acc) ->
  1167. do_parse_octal(Rest, Acc);
  1168. do_parse_octal(<<0, Rest/binary>>, Acc) ->
  1169. do_parse_octal(Rest, Acc);
  1170. do_parse_octal(<<C, Rest/binary>>, Acc) ->
  1171. do_parse_octal(Rest, <<Acc/binary, C>>).
  1172. parse_string(Bin) when is_binary(Bin) ->
  1173. do_parse_string(Bin, <<>>).
  1174. do_parse_string(<<>>, Acc) ->
  1175. case unicode:characters_to_list(Acc) of
  1176. Str when is_list(Str) ->
  1177. Str;
  1178. {incomplete, _Str, _Rest} ->
  1179. binary:bin_to_list(Acc);
  1180. {error, _Str, _Rest} ->
  1181. throw({error, {bad_header, invalid_string}})
  1182. end;
  1183. do_parse_string(<<0, _/binary>>, Acc) ->
  1184. do_parse_string(<<>>, Acc);
  1185. do_parse_string(<<C, Rest/binary>>, Acc) ->
  1186. do_parse_string(Rest, <<Acc/binary, C>>).
  1187. convert_header(Bin, #reader{pos=Pos}=Reader)
  1188. when byte_size(Bin) =:= ?BLOCK_SIZE, (Pos rem ?BLOCK_SIZE) =:= 0 ->
  1189. case get_format(Bin) of
  1190. ?FORMAT_UNKNOWN ->
  1191. throw({error, bad_header});
  1192. {ok, Format, V7} ->
  1193. unpack_format(Format, V7, Bin, Reader);
  1194. {error, Reason} ->
  1195. throw({error, {bad_header, Reason}})
  1196. end;
  1197. convert_header(Bin, #reader{pos=Pos}) when byte_size(Bin) =:= ?BLOCK_SIZE ->
  1198. throw({error, misaligned_read, Pos});
  1199. convert_header(Bin, _Reader) when byte_size(Bin) =:= 0 ->
  1200. eof;
  1201. convert_header(_Bin, _Reader) ->
  1202. throw({error, eof}).
  1203. %% Creates a partially-populated header record based
  1204. %% on the provided file_info record. If the file is
  1205. %% a symlink, then `link` is used as the link target.
  1206. %% If the file is a directory, a slash is appended to the name.
  1207. fileinfo_to_header(Name, #file_info{}=Fi, Link) when is_list(Name) ->
  1208. BaseHeader = #tar_header{name=Name,
  1209. mtime=0,
  1210. atime=0,
  1211. ctime=0,
  1212. mode=Fi#file_info.mode,
  1213. typeflag=?TYPE_REGULAR},
  1214. do_fileinfo_to_header(BaseHeader, Fi, Link).
  1215. do_fileinfo_to_header(Header, #file_info{size=Size,type=regular}, _Link) ->
  1216. Header#tar_header{size=Size,typeflag=?TYPE_REGULAR};
  1217. do_fileinfo_to_header(#tar_header{name=Name}=Header,
  1218. #file_info{type=directory}, _Link) ->
  1219. Header#tar_header{name=Name++"/",typeflag=?TYPE_DIR};
  1220. do_fileinfo_to_header(Header, #file_info{type=symlink}, Link) ->
  1221. Header#tar_header{typeflag=?TYPE_SYMLINK,linkname=Link};
  1222. do_fileinfo_to_header(Header, #file_info{type=device,mode=Mode}=Fi, _Link)
  1223. when (Mode band ?S_IFMT) =:= ?S_IFCHR ->
  1224. Header#tar_header{typeflag=?TYPE_CHAR,
  1225. devmajor=Fi#file_info.major_device,
  1226. devminor=Fi#file_info.minor_device};
  1227. do_fileinfo_to_header(Header, #file_info{type=device,mode=Mode}=Fi, _Link)
  1228. when (Mode band ?S_IFMT) =:= ?S_IFBLK ->
  1229. Header#tar_header{typeflag=?TYPE_BLOCK,
  1230. devmajor=Fi#file_info.major_device,
  1231. devminor=Fi#file_info.minor_device};
  1232. do_fileinfo_to_header(Header, #file_info{type=other,mode=Mode}, _Link)
  1233. when (Mode band ?S_IFMT) =:= ?S_FIFO ->
  1234. Header#tar_header{typeflag=?TYPE_FIFO};
  1235. do_fileinfo_to_header(Header, Fi, _Link) ->
  1236. {error, {invalid_file_type, Header#tar_header.name, Fi}}.
  1237. is_ascii(Str) when is_list(Str) ->
  1238. not lists:any(fun (Char) -> Char >= 16#80 end, Str);
  1239. is_ascii(Bin) when is_binary(Bin) ->
  1240. is_ascii1(Bin).
  1241. is_ascii1(<<>>) ->
  1242. true;
  1243. is_ascii1(<<C,_Rest/binary>>) when C >= 16#80 ->
  1244. false;
  1245. is_ascii1(<<_, Rest/binary>>) ->
  1246. is_ascii1(Rest).
  1247. to_ascii(Str) when is_list(Str) ->
  1248. case is_ascii(Str) of
  1249. true ->
  1250. unicode:characters_to_binary(Str);
  1251. false ->
  1252. Chars = lists:filter(fun (Char) -> Char < 16#80 end, Str),
  1253. unicode:characters_to_binary(Chars)
  1254. end;
  1255. to_ascii(Bin) when is_binary(Bin) ->
  1256. to_ascii(Bin, <<>>).
  1257. to_ascii(<<>>, Acc) ->
  1258. Acc;
  1259. to_ascii(<<C, Rest/binary>>, Acc) when C < 16#80 ->
  1260. to_ascii(Rest, <<Acc/binary,C>>);
  1261. to_ascii(<<_, Rest/binary>>, Acc) ->
  1262. to_ascii(Rest, Acc).
  1263. is_header_only_type(?TYPE_SYMLINK) -> true;
  1264. is_header_only_type(?TYPE_LINK) -> true;
  1265. is_header_only_type(?TYPE_DIR) -> true;
  1266. is_header_only_type(_) -> false.
  1267. foldl_read(#reader{access=read}=Reader, Fun, Accu, #read_opts{}=Opts)
  1268. when is_function(Fun,4) ->
  1269. case foldl_read0(Reader, Fun, Accu, Opts) of
  1270. {ok, Result, _Reader2} ->
  1271. Result;
  1272. {error, _} = Err ->
  1273. Err
  1274. end;
  1275. foldl_read(#reader{access=Access}, _Fun, _Accu, _Opts) ->
  1276. {error, {read_mode_expected, Access}};
  1277. foldl_read(TarName, Fun, Accu, #read_opts{}=Opts)
  1278. when is_function(Fun,4) ->
  1279. try open(TarName, [read|Opts#read_opts.open_mode]) of
  1280. {ok, #reader{access=read}=Reader} ->
  1281. try
  1282. foldl_read(Reader, Fun, Accu, Opts)
  1283. after
  1284. _ = close(Reader)
  1285. end;
  1286. {error, _} = Err ->
  1287. Err
  1288. catch
  1289. throw:Err ->
  1290. Err
  1291. end.
  1292. foldl_read0(Reader, Fun, Accu, Opts) ->
  1293. try foldl_read1(Fun, Accu, Reader, Opts, #{}) of
  1294. {ok,_,_} = Ok ->
  1295. Ok
  1296. catch
  1297. throw:{error, {Reason, Format, Args}} ->
  1298. read_verbose(Opts, Format, Args),
  1299. {error, Reason};
  1300. throw:Err ->
  1301. Err
  1302. end.
  1303. foldl_read1(Fun, Accu0, Reader0, Opts, ExtraHeaders) ->
  1304. {ok, Reader1} = skip_unread(Reader0),
  1305. case get_header(Reader1) of
  1306. eof ->
  1307. Fun(eof, Reader1, Opts, Accu0);
  1308. {Header, Reader2} ->
  1309. case Header#tar_header.typeflag of
  1310. ?TYPE_X_HEADER ->
  1311. {ExtraHeaders2, Reader3} = parse_pax(Reader2),
  1312. ExtraHeaders3 = maps:merge(ExtraHeaders, ExtraHeaders2),
  1313. foldl_read1(Fun, Accu0, Reader3, Opts, ExtraHeaders3);
  1314. ?TYPE_GNU_LONGNAME ->
  1315. {RealName, Reader3} = get_real_name(Reader2),
  1316. ExtraHeaders2 = maps:put(?PAX_PATH,
  1317. parse_string(RealName), ExtraHeaders),
  1318. foldl_read1(Fun, Accu0, Reader3, Opts, ExtraHeaders2);
  1319. ?TYPE_GNU_LONGLINK ->
  1320. {RealName, Reader3} = get_real_name(Reader2),
  1321. ExtraHeaders2 = maps:put(?PAX_LINKPATH,
  1322. parse_string(RealName), ExtraHeaders),
  1323. foldl_read1(Fun, Accu0, Reader3, Opts, ExtraHeaders2);
  1324. _ ->
  1325. Header1 = merge_pax(Header, ExtraHeaders),
  1326. {ok, NewAccu, Reader3} = Fun(Header1, Reader2, Opts, Accu0),
  1327. foldl_read1(Fun, NewAccu, Reader3, Opts, #{})
  1328. end
  1329. end.
  1330. %% Applies all known PAX attributes to the current tar header
  1331. -spec merge_pax(tar_header(), #{binary() => binary()}) -> tar_header().
  1332. merge_pax(Header, ExtraHeaders) when is_map(ExtraHeaders) ->
  1333. do_merge_pax(Header, maps:to_list(ExtraHeaders)).
  1334. do_merge_pax(Header, []) ->
  1335. Header;
  1336. do_merge_pax(Header, [{?PAX_PATH, Path}|Rest]) ->
  1337. do_merge_pax(Header#tar_header{name=unicode:characters_to_list(Path)}, Rest);
  1338. do_merge_pax(Header, [{?PAX_LINKPATH, LinkPath}|Rest]) ->
  1339. do_merge_pax(Header#tar_header{linkname=unicode:characters_to_list(LinkPath)}, Rest);
  1340. do_merge_pax(Header, [{?PAX_GNAME, Gname}|Rest]) ->
  1341. do_merge_pax(Header#tar_header{gname=unicode:characters_to_list(Gname)}, Rest);
  1342. do_merge_pax(Header, [{?PAX_UNAME, Uname}|Rest]) ->
  1343. do_merge_pax(Header#tar_header{uname=unicode:characters_to_list(Uname)}, Rest);
  1344. do_merge_pax(Header, [{?PAX_UID, Uid}|Rest]) ->
  1345. Uid2 = binary_to_integer(Uid),
  1346. do_merge_pax(Header#tar_header{uid=Uid2}, Rest);
  1347. do_merge_pax(Header, [{?PAX_GID, Gid}|Rest]) ->
  1348. Gid2 = binary_to_integer(Gid),
  1349. do_merge_pax(Header#tar_header{gid=Gid2}, Rest);
  1350. do_merge_pax(Header, [{?PAX_ATIME, Atime}|Rest]) ->
  1351. Atime2 = parse_pax_time(Atime),
  1352. do_merge_pax(Header#tar_header{atime=Atime2}, Rest);
  1353. do_merge_pax(Header, [{?PAX_MTIME, Mtime}|Rest]) ->
  1354. Mtime2 = parse_pax_time(Mtime),
  1355. do_merge_pax(Header#tar_header{mtime=Mtime2}, Rest);
  1356. do_merge_pax(Header, [{?PAX_CTIME, Ctime}|Rest]) ->
  1357. Ctime2 = parse_pax_time(Ctime),
  1358. do_merge_pax(Header#tar_header{ctime=Ctime2}, Rest);
  1359. do_merge_pax(Header, [{?PAX_SIZE, Size}|Rest]) ->
  1360. Size2 = binary_to_integer(Size),
  1361. do_merge_pax(Header#tar_header{size=Size2}, Rest);
  1362. do_merge_pax(Header, [{<<?PAX_XATTR_STR, _Key/binary>>, _Value}|Rest]) ->
  1363. do_merge_pax(Header, Rest);
  1364. do_merge_pax(Header, [_Ignore|Rest]) ->
  1365. do_merge_pax(Header, Rest).
  1366. %% Returns the time since UNIX epoch as a datetime
  1367. -spec parse_pax_time(binary()) -> tar_time().
  1368. parse_pax_time(Bin) when is_binary(Bin) ->
  1369. TotalNano = case binary:split(Bin, [<<$.>>]) of
  1370. [SecondsStr, NanoStr0] ->
  1371. Seconds = binary_to_integer(SecondsStr),
  1372. if byte_size(NanoStr0) < ?MAX_NANO_INT_SIZE ->
  1373. %% right pad
  1374. PaddingN = ?MAX_NANO_INT_SIZE-byte_size(NanoStr0),
  1375. Padding = binary:copy(<<$0>>, PaddingN),
  1376. NanoStr1 = <<NanoStr0/binary,Padding/binary>>,
  1377. Nano = binary_to_integer(NanoStr1),
  1378. (Seconds*?BILLION)+Nano;
  1379. byte_size(NanoStr0) > ?MAX_NANO_INT_SIZE ->
  1380. %% right truncate
  1381. NanoStr1 = binary_part(NanoStr0, 0, ?MAX_NANO_INT_SIZE),
  1382. Nano = binary_to_integer(NanoStr1),
  1383. (Seconds*?BILLION)+Nano;
  1384. true ->
  1385. (Seconds*?BILLION)+binary_to_integer(NanoStr0)
  1386. end;
  1387. [SecondsStr] ->
  1388. binary_to_integer(SecondsStr)*?BILLION
  1389. end,
  1390. %% truncate to microseconds
  1391. Micro = TotalNano div 1000,
  1392. Mega = Micro div 1000000000000,
  1393. Secs = Micro div 1000000 - (Mega*1000000),
  1394. Secs.
  1395. %% Given a regular file reader, reads the whole file and
  1396. %% parses all extended attributes it contains.
  1397. parse_pax(#reg_file_reader{handle=Handle,num_bytes=0}) ->
  1398. {#{}, Handle};
  1399. parse_pax(#reg_file_reader{handle=Handle0,num_bytes=NumBytes}) ->
  1400. case do_read(Handle0, NumBytes) of
  1401. {ok, Bytes, Handle1} ->
  1402. do_parse_pax(Handle1, Bytes, #{});
  1403. {error, _} = Err ->
  1404. throw(Err)
  1405. end.
  1406. do_parse_pax(Reader, <<>>, Headers) ->
  1407. {Headers, Reader};
  1408. do_parse_pax(Reader, Bin, Headers) ->
  1409. {Key, Value, Residual} = parse_pax_record(Bin),
  1410. NewHeaders = maps:put(Key, Value, Headers),
  1411. do_parse_pax(Reader, Residual, NewHeaders).
  1412. %% Parse an extended attribute
  1413. parse_pax_record(Bin) when is_binary(Bin) ->
  1414. case binary:split(Bin, [<<$\n>>]) of
  1415. [Record, Residual] ->
  1416. case [X || X <- binary:split(Record, [<<$\s>>], [global]), X =/= <<>>] of
  1417. [_Len, Record1] ->
  1418. case [X || X <- binary:split(Record1, [<<$=>>], [global]), X =/= <<>>] of
  1419. [AttrName, AttrValue] ->
  1420. {AttrName, AttrValue, Residual};
  1421. _Other ->
  1422. throw({error, malformed_pax_record})
  1423. end;
  1424. _Other ->
  1425. throw({error, malformed_pax_record})
  1426. end;
  1427. _Other ->
  1428. throw({error, malformed_pax_record})
  1429. end.
  1430. get_real_name(#reg_file_reader{handle=Handle,num_bytes=0}) ->
  1431. {"", Handle};
  1432. get_real_name(#reg_file_reader{handle=Handle0,num_bytes=NumBytes}) ->
  1433. case do_read(Handle0, NumBytes) of
  1434. {ok, RealName, Handle1} ->
  1435. {RealName, Handle1};
  1436. {error, _} = Err ->
  1437. throw(Err)
  1438. end;
  1439. get_real_name(#sparse_file_reader{num_bytes=NumBytes}=Reader0) ->
  1440. case do_read(Reader0, NumBytes) of
  1441. {ok, RealName, Reader1} ->
  1442. {RealName, Reader1};
  1443. {error, _} = Err ->
  1444. throw(Err)
  1445. end.
  1446. %% Skip the remaining bytes for the current file entry
  1447. skip_file(#reg_file_reader{handle=Handle0,pos=Pos,size=Size}=Reader) ->
  1448. Padding = skip_padding(Size),
  1449. AbsPos = Handle0#reader.pos + (Size-Pos) + Padding,
  1450. case do_position(Handle0, AbsPos) of
  1451. {ok, _, Handle1} ->
  1452. Reader#reg_file_reader{handle=Handle1,num_bytes=0,pos=Size};
  1453. Err ->
  1454. throw(Err)
  1455. end;
  1456. skip_file(#sparse_file_reader{pos=Pos,size=Size}=Reader) ->
  1457. case do_read(Reader, Size-Pos) of
  1458. {ok, _, Reader2} ->
  1459. Reader2;
  1460. Err ->
  1461. throw(Err)
  1462. end.
  1463. skip_padding(0) ->
  1464. 0;
  1465. skip_padding(Size) when (Size rem ?BLOCK_SIZE) =:= 0 ->
  1466. 0;
  1467. skip_padding(Size) when Size =< ?BLOCK_SIZE ->
  1468. ?BLOCK_SIZE - Size;
  1469. skip_padding(Size) ->
  1470. ?BLOCK_SIZE - (Size rem ?BLOCK_SIZE).
  1471. skip_unread(#reader{pos=Pos}=Reader0) when (Pos rem ?BLOCK_SIZE) > 0 ->
  1472. Padding = skip_padding(Pos + ?BLOCK_SIZE),
  1473. AbsPos = Pos + Padding,
  1474. case do_position(Reader0, AbsPos) of
  1475. {ok, _, Reader1} ->
  1476. {ok, Reader1};
  1477. Err ->
  1478. throw(Err)
  1479. end;
  1480. skip_unread(#reader{}=Reader) ->
  1481. {ok, Reader};
  1482. skip_unread(#reg_file_reader{handle=Handle,num_bytes=0}) ->
  1483. skip_unread(Handle);
  1484. skip_unread(#reg_file_reader{}=Reader) ->
  1485. #reg_file_reader{handle=Handle} = skip_file(Reader),
  1486. {ok, Handle};
  1487. skip_unread(#sparse_file_reader{handle=Handle,num_bytes=0}) ->
  1488. skip_unread(Handle);
  1489. skip_unread(#sparse_file_reader{}=Reader) ->
  1490. #sparse_file_reader{handle=Handle} = skip_file(Reader),
  1491. {ok, Handle}.
  1492. write_extracted_element(#tar_header{name=Name,typeflag=Type},
  1493. Bin,
  1494. #read_opts{output=memory}=Opts) ->
  1495. case typeflag(Type) of
  1496. regular ->
  1497. read_verbose(Opts, "x ~ts~n", [Name]),
  1498. {ok, {Name, Bin}};
  1499. _ ->
  1500. ok
  1501. end;
  1502. write_extracted_element(#tar_header{name=Name0}=Header, Bin, Opts) ->
  1503. Name1 = make_safe_path(Name0, Opts),
  1504. Created =
  1505. case typeflag(Header#tar_header.typeflag) of
  1506. regular ->
  1507. create_regular(Name1, Name0, Bin, Opts);
  1508. directory ->
  1509. read_verbose(Opts, "x ~ts~n", [Name0]),
  1510. create_extracted_dir(Name1, Opts);
  1511. symlink ->
  1512. read_verbose(Opts, "x ~ts~n", [Name0]),
  1513. create_symlink(Name1, Header#tar_header.linkname, Opts);
  1514. Device when Device =:= char orelse Device =:= block ->
  1515. %% char/block devices will be created as empty files
  1516. %% and then have their major/minor device set later
  1517. create_regular(Name1, Name0, <<>>, Opts);
  1518. fifo ->
  1519. %% fifo devices will be created as empty files
  1520. create_regular(Name1, Name0, <<>>, Opts);
  1521. Other -> % Ignore.
  1522. read_verbose(Opts, "x ~ts - unsupported type ~p~n",
  1523. [Name0, Other]),
  1524. not_written
  1525. end,
  1526. case Created of
  1527. ok -> set_extracted_file_info(Name1, Header);
  1528. not_written -> ok
  1529. end.
  1530. make_safe_path([$/|Path], Opts) ->
  1531. make_safe_path(Path, Opts);
  1532. make_safe_path(Path, #read_opts{cwd=Cwd}) ->
  1533. case safe_relative_path_links(Path, Cwd) of
  1534. unsafe ->
  1535. throw({error,{Path,unsafe_path}});
  1536. SafePath ->
  1537. filename:absname(SafePath, Cwd)
  1538. end.
  1539. safe_relative_path_links(Path, Cwd) ->
  1540. case filename:pathtype(Path) of
  1541. relative -> safe_relative_path_links(filename:split(Path), Cwd, [], "");
  1542. _ -> unsafe
  1543. end.
  1544. safe_relative_path_links([], _Cwd, _PrevLinks, Acc) ->
  1545. Acc;
  1546. safe_relative_path_links([Segment | Segments], Cwd, PrevLinks, Acc) ->
  1547. AccSegment = join(Acc, Segment),
  1548. case r3_hex_filename:safe_relative_path(AccSegment) of
  1549. unsafe ->
  1550. unsafe;
  1551. SafeAccSegment ->
  1552. case file:read_link(join(Cwd, SafeAccSegment)) of
  1553. {ok, LinkPath} ->
  1554. case lists:member(LinkPath, PrevLinks) of
  1555. true ->
  1556. unsafe;
  1557. false ->
  1558. case safe_relative_path_links(filename:split(LinkPath), Cwd, [LinkPath | PrevLinks], Acc) of
  1559. unsafe -> unsafe;
  1560. NewAcc -> safe_relative_path_links(Segments, Cwd, [], NewAcc)
  1561. end
  1562. end;
  1563. {error, _} ->
  1564. safe_relative_path_links(Segments, Cwd, PrevLinks, SafeAccSegment)
  1565. end
  1566. end.
  1567. join([], Path) -> Path;
  1568. join(Left, Right) -> filename:join(Left, Right).
  1569. create_regular(Name, NameInArchive, Bin, Opts) ->
  1570. case write_extracted_file(Name, Bin, Opts) of
  1571. not_written ->
  1572. read_verbose(Opts, "x ~ts - exists, not created~n", [NameInArchive]),
  1573. not_written;
  1574. Ok ->
  1575. read_verbose(Opts, "x ~ts~n", [NameInArchive]),
  1576. Ok
  1577. end.
  1578. create_extracted_dir(Name, _Opts) ->
  1579. case file:make_dir(Name) of
  1580. ok -> ok;
  1581. {error,enotsup} -> not_written;
  1582. {error,eexist} -> not_written;
  1583. {error,enoent} -> make_dirs(Name, dir);
  1584. {error,Reason} -> throw({error, Reason})
  1585. end.
  1586. create_symlink(Name, Linkname, Opts) ->
  1587. case file:make_symlink(Linkname, Name) of
  1588. ok -> ok;
  1589. {error,enoent} ->
  1590. ok = make_dirs(Name, file),
  1591. create_symlink(Name, Linkname, Opts);
  1592. {error,eexist} -> not_written;
  1593. {error,enotsup} ->
  1594. read_verbose(Opts, "x ~ts - symbolic links not supported~n", [Name]),
  1595. not_written;
  1596. {error,Reason} -> throw({error, Reason})
  1597. end.
  1598. write_extracted_file(Name, Bin, Opts) ->
  1599. Write =
  1600. case Opts#read_opts.keep_old_files of
  1601. true ->
  1602. case file:read_file_info(Name) of
  1603. {ok, _} -> false;
  1604. _ -> true
  1605. end;
  1606. false -> true
  1607. end,
  1608. case Write of
  1609. true -> write_file(Name, Bin);
  1610. false -> not_written
  1611. end.
  1612. write_file(Name, Bin) ->
  1613. case file:write_file(Name, Bin) of
  1614. ok -> ok;
  1615. {error,enoent} ->
  1616. case make_dirs(Name, file) of
  1617. ok ->
  1618. write_file(Name, Bin);
  1619. {error,Reason} ->
  1620. throw({error, Reason})
  1621. end;
  1622. {error,Reason} ->
  1623. throw({error, Reason})
  1624. end.
  1625. set_extracted_file_info(_, #tar_header{typeflag = ?TYPE_SYMLINK}) -> ok;
  1626. set_extracted_file_info(_, #tar_header{typeflag = ?TYPE_LINK}) -> ok;
  1627. set_extracted_file_info(Name, #tar_header{typeflag = ?TYPE_CHAR}=Header) ->
  1628. set_device_info(Name, Header);
  1629. set_extracted_file_info(Name, #tar_header{typeflag = ?TYPE_BLOCK}=Header) ->
  1630. set_device_info(Name, Header);
  1631. set_extracted_file_info(Name, #tar_header{mtime=Mtime,mode=Mode}) ->
  1632. Info = #file_info{mode=Mode, mtime=Mtime},
  1633. file:write_file_info(Name, Info, [{time, posix}]).
  1634. set_device_info(Name, #tar_header{}=Header) ->
  1635. Mtime = Header#tar_header.mtime,
  1636. Mode = Header#tar_header.mode,
  1637. Devmajor = Header#tar_header.devmajor,
  1638. Devminor = Header#tar_header.devminor,
  1639. Info = #file_info{
  1640. mode=Mode,
  1641. mtime=Mtime,
  1642. major_device=Devmajor,
  1643. minor_device=Devminor
  1644. },
  1645. file:write_file_info(Name, Info).
  1646. %% Makes all directories leading up to the file.
  1647. make_dirs(Name, file) ->
  1648. filelib:ensure_dir(Name);
  1649. make_dirs(Name, dir) ->
  1650. filelib:ensure_dir(filename:join(Name,"*")).
  1651. %% Prints the message on if the verbose option is given (for reading).
  1652. read_verbose(#read_opts{verbose=true}, Format, Args) ->
  1653. io:format(Format, Args);
  1654. read_verbose(_, _, _) ->
  1655. ok.
  1656. %% Prints the message on if the verbose option is given.
  1657. add_verbose(#add_opts{verbose=true}, Format, Args) ->
  1658. io:format(Format, Args);
  1659. add_verbose(_, _, _) ->
  1660. ok.
  1661. %%%%%%%%%%%%%%%%%%
  1662. %% I/O primitives
  1663. %%%%%%%%%%%%%%%%%%
  1664. do_write(#reader{handle=Handle,func=Fun}=Reader0, Data)
  1665. when is_function(Fun,2) ->
  1666. case Fun(write,{Handle,Data}) of
  1667. ok ->
  1668. {ok, Pos, Reader1} = do_position(Reader0, {cur,0}),
  1669. {ok, Reader1#reader{pos=Pos}};
  1670. {error, _} = Err ->
  1671. Err
  1672. end.
  1673. do_copy(#reader{func=Fun}=Reader, Source, #add_opts{chunk_size=0}=Opts)
  1674. when is_function(Fun, 2) ->
  1675. do_copy(Reader, Source, Opts#add_opts{chunk_size=65536});
  1676. do_copy(#reader{func=Fun}=Reader, Source, #add_opts{chunk_size=ChunkSize})
  1677. when is_function(Fun, 2) ->
  1678. case file:open(Source, [read, binary]) of
  1679. {ok, SourceFd} ->
  1680. case copy_chunked(Reader, SourceFd, ChunkSize, 0) of
  1681. {ok, _Copied, _Reader2} = Ok->
  1682. _ = file:close(SourceFd),
  1683. Ok;
  1684. Err ->
  1685. _ = file:close(SourceFd),
  1686. throw(Err)
  1687. end;
  1688. Err ->
  1689. throw(Err)
  1690. end.
  1691. copy_chunked(#reader{}=Reader, Source, ChunkSize, Copied) ->
  1692. case file:read(Source, ChunkSize) of
  1693. {ok, Bin} ->
  1694. {ok, Reader2} = do_write(Reader, Bin),
  1695. copy_chunked(Reader2, Source, ChunkSize, Copied+byte_size(Bin));
  1696. eof ->
  1697. {ok, Copied, Reader};
  1698. Other ->
  1699. Other
  1700. end.
  1701. do_position(#reader{handle=Handle,func=Fun}=Reader, Pos)
  1702. when is_function(Fun,2)->
  1703. case Fun(position, {Handle,Pos}) of
  1704. {ok, NewPos} ->
  1705. %% since Pos may not always be an absolute seek,
  1706. %% make sure we update the reader with the new absolute position
  1707. {ok, AbsPos} = Fun(position, {Handle, {cur, 0}}),
  1708. {ok, NewPos, Reader#reader{pos=AbsPos}};
  1709. Other ->
  1710. Other
  1711. end.
  1712. do_read(#reg_file_reader{handle=Handle,pos=Pos,size=Size}=Reader, Len) ->
  1713. NumBytes = Size - Pos,
  1714. ActualLen = if NumBytes - Len < 0 -> NumBytes; true -> Len end,
  1715. case do_read(Handle, ActualLen) of
  1716. {ok, Bin, Handle2} ->
  1717. NewPos = Pos + ActualLen,
  1718. NumBytes2 = Size - NewPos,
  1719. Reader1 = Reader#reg_file_reader{
  1720. handle=Handle2,
  1721. pos=NewPos,
  1722. num_bytes=NumBytes2},
  1723. {ok, Bin, Reader1};
  1724. Other ->
  1725. Other
  1726. end;
  1727. do_read(#sparse_file_reader{}=Reader, Len) ->
  1728. do_sparse_read(Reader, Len);
  1729. do_read(#reader{pos=Pos,handle=Handle,func=Fun}=Reader, Len)
  1730. when is_function(Fun,2)->
  1731. %% Always convert to binary internally
  1732. case Fun(read2,{Handle,Len}) of
  1733. {ok, List} when is_list(List) ->
  1734. Bin = list_to_binary(List),
  1735. NewPos = Pos+byte_size(Bin),
  1736. {ok, Bin, Reader#reader{pos=NewPos}};
  1737. {ok, Bin} when is_binary(Bin) ->
  1738. NewPos = Pos+byte_size(Bin),
  1739. {ok, Bin, Reader#reader{pos=NewPos}};
  1740. Other ->
  1741. Other
  1742. end.
  1743. do_sparse_read(Reader, Len) ->
  1744. do_sparse_read(Reader, Len, <<>>).
  1745. do_sparse_read(#sparse_file_reader{sparse_map=[#sparse_entry{num_bytes=0}|Entries]
  1746. }=Reader0, Len, Acc) ->
  1747. %% skip all empty fragments
  1748. Reader1 = Reader0#sparse_file_reader{sparse_map=Entries},
  1749. do_sparse_read(Reader1, Len, Acc);
  1750. do_sparse_read(#sparse_file_reader{sparse_map=[],
  1751. pos=Pos,size=Size}=Reader0, Len, Acc)
  1752. when Pos < Size ->
  1753. %% if there are no more fragments, it is possible that there is one last sparse hole
  1754. %% this behaviour matches the BSD tar utility
  1755. %% however, GNU tar stops returning data even if we haven't reached the end
  1756. {ok, Bin, Reader1} = read_sparse_hole(Reader0, Size, Len),
  1757. do_sparse_read(Reader1, Len-byte_size(Bin), <<Acc/binary,Bin/binary>>);
  1758. do_sparse_read(#sparse_file_reader{sparse_map=[]}=Reader, _Len, Acc) ->
  1759. {ok, Acc, Reader};
  1760. do_sparse_read(#sparse_file_reader{}=Reader, 0, Acc) ->
  1761. {ok, Acc, Reader};
  1762. do_sparse_read(#sparse_file_reader{sparse_map=[#sparse_entry{offset=Offset}|_],
  1763. pos=Pos}=Reader0, Len, Acc)
  1764. when Pos < Offset ->
  1765. {ok, Bin, Reader1} = read_sparse_hole(Reader0, Offset, Offset-Pos),
  1766. do_sparse_read(Reader1, Len-byte_size(Bin), <<Acc/binary,Bin/binary>>);
  1767. do_sparse_read(#sparse_file_reader{sparse_map=[Entry|Entries],
  1768. pos=Pos}=Reader0, Len, Acc) ->
  1769. %% we're in a data fragment, so read from it
  1770. %% end offset of fragment
  1771. EndPos = Entry#sparse_entry.offset + Entry#sparse_entry.num_bytes,
  1772. %% bytes left in fragment
  1773. NumBytes = EndPos - Pos,
  1774. ActualLen = if Len > NumBytes -> NumBytes; true -> Len end,
  1775. case do_read(Reader0#sparse_file_reader.handle, ActualLen) of
  1776. {ok, Bin, Handle} ->
  1777. BytesRead = byte_size(Bin),
  1778. ActualEndPos = Pos+BytesRead,
  1779. Reader1 = if ActualEndPos =:= EndPos ->
  1780. Reader0#sparse_file_reader{sparse_map=Entries};
  1781. true ->
  1782. Reader0
  1783. end,
  1784. Size = Reader1#sparse_file_reader.size,
  1785. NumBytes2 = Size - ActualEndPos,
  1786. Reader2 = Reader1#sparse_file_reader{
  1787. handle=Handle,
  1788. pos=ActualEndPos,
  1789. num_bytes=NumBytes2},
  1790. do_sparse_read(Reader2, Len-byte_size(Bin), <<Acc/binary,Bin/binary>>);
  1791. Other ->
  1792. Other
  1793. end.
  1794. %% Reads a sparse hole ending at Offset
  1795. read_sparse_hole(#sparse_file_reader{pos=Pos}=Reader, Offset, Len) ->
  1796. N = Offset - Pos,
  1797. N2 = if N > Len ->
  1798. Len;
  1799. true ->
  1800. N
  1801. end,
  1802. Bin = <<0:N2/unit:8>>,
  1803. NumBytes = Reader#sparse_file_reader.size - (Pos+N2),
  1804. {ok, Bin, Reader#sparse_file_reader{
  1805. num_bytes=NumBytes,
  1806. pos=Pos+N2}}.
  1807. -spec do_close(reader()) -> ok | {error, term()}.
  1808. do_close(#reader{handle=Handle,func=Fun}) when is_function(Fun,2) ->
  1809. Fun(close,Handle).
  1810. %%%%%%%%%%%%%%%%%%
  1811. %% Option parsing
  1812. %%%%%%%%%%%%%%%%%%
  1813. extract_opts(List) ->
  1814. extract_opts(List, default_options()).
  1815. table_opts(List) ->
  1816. read_opts(List, default_options()).
  1817. default_options() ->
  1818. {ok, Cwd} = file:get_cwd(),
  1819. #read_opts{cwd=Cwd}.
  1820. extract_opts([keep_old_files|Rest], Opts) ->
  1821. extract_opts(Rest, Opts#read_opts{keep_old_files=true});
  1822. extract_opts([{cwd, Cwd}|Rest], Opts) ->
  1823. extract_opts(Rest, Opts#read_opts{cwd=Cwd});
  1824. extract_opts([{files, Files}|Rest], Opts) ->
  1825. Set = ordsets:from_list(Files),
  1826. extract_opts(Rest, Opts#read_opts{files=Set});
  1827. extract_opts([memory|Rest], Opts) ->
  1828. extract_opts(Rest, Opts#read_opts{output=memory});
  1829. extract_opts([compressed|Rest], Opts=#read_opts{open_mode=OpenMode}) ->
  1830. extract_opts(Rest, Opts#read_opts{open_mode=[compressed|OpenMode]});
  1831. extract_opts([cooked|Rest], Opts=#read_opts{open_mode=OpenMode}) ->
  1832. extract_opts(Rest, Opts#read_opts{open_mode=[cooked|OpenMode]});
  1833. extract_opts([verbose|Rest], Opts) ->
  1834. extract_opts(Rest, Opts#read_opts{verbose=true});
  1835. extract_opts([Other|Rest], Opts) ->
  1836. extract_opts(Rest, read_opts([Other], Opts));
  1837. extract_opts([], Opts) ->
  1838. Opts.
  1839. read_opts([compressed|Rest], Opts=#read_opts{open_mode=OpenMode}) ->
  1840. read_opts(Rest, Opts#read_opts{open_mode=[compressed|OpenMode]});
  1841. read_opts([cooked|Rest], Opts=#read_opts{open_mode=OpenMode}) ->
  1842. read_opts(Rest, Opts#read_opts{open_mode=[cooked|OpenMode]});
  1843. read_opts([verbose|Rest], Opts) ->
  1844. read_opts(Rest, Opts#read_opts{verbose=true});
  1845. read_opts([_|Rest], Opts) ->
  1846. read_opts(Rest, Opts);
  1847. read_opts([], Opts) ->
  1848. Opts.