-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
erl_tar.erl
2320 lines (2094 loc) · 87.2 KB
/
erl_tar.erl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
%%
%% %CopyrightBegin%
%%
%% Copyright Ericsson AB 1997-2024. All Rights Reserved.
%%
%% Licensed under the Apache License, Version 2.0 (the "License");
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing, software
%% distributed under the License is distributed on an "AS IS" BASIS,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% %CopyrightEnd%
%%
%% This module implements extraction/creation of tar archives.
%% It supports reading most common tar formats, namely V7, STAR,
%% USTAR, GNU, BSD/libarchive, and PAX. It produces archives in USTAR
%% format, unless it must use PAX headers, in which case it produces PAX
%% format.
%%
%% The following references where used:
%% http://www.freebsd.org/cgi/man.cgi?query=tar&sektion=5
%% http://www.gnu.org/software/tar/manual/html_node/Standard.html
%% http://pubs.opengroup.org/onlinepubs/9699919799/utilities/pax.html
-module(erl_tar).
-moduledoc """
Unix 'tar' utility for reading and writing tar archives.
This module archives and extract files to and from a tar file. This module
supports reading most common tar formats, namely v7, STAR, USTAR, and PAX, as
well as some of GNU tar's extensions to the USTAR format (sparse files most
notably). It produces tar archives in USTAR format, unless the files being
archived require PAX format due to restrictions in USTAR (such as unicode
metadata, filename length, and more). As such, `erl_tar` supports tar archives
produced by most all modern tar utilities, and produces tarballs which should be
similarly portable.
By convention, the name of a tar file is to end in "`.tar`". To abide to the
convention, add "`.tar`" to the name.
Tar files can be created in one operation using function `create/2` or
`create/3`.
Alternatively, for more control, use functions `open/2`, [`add/3,4`](`add/3`),
and `close/1`.
To extract all files from a tar file, use function `extract/1`. To extract only
some files or to be able to specify some more options, use function `extract/2`.
To return a list of the files in a tar file, use function `table/1` or
`table/2`. To print a list of files to the Erlang shell, use function `t/1` or
`tt/1`.
To convert an error term returned from one of the functions above to a readable
message, use function `format_error/1`.
## Unicode Support
If `file:native_name_encoding/0` returns `utf8`, path names are encoded in UTF-8
when creating tar files, and path names are assumed to be encoded in UTF-8 when
extracting tar files.
If `file:native_name_encoding/0` returns `latin1`, no translation of path names
is done.
Unicode metadata stored in PAX headers is preserved
## Other Storage Media
The `m:ftp` module normally accesses the tar file on disk using the `m:file`
module. When other needs arise, you can define your own low-level Erlang
functions to perform the writing and reading on the storage media; use function
`init/3`.
An example of this is the SFTP support in `ssh_sftp:open_tar/3`. This function
opens a tar file on a remote machine using an SFTP channel.
## Limitations
- If you must remain compatible with the USTAR tar format, you must ensure file
paths being stored are less than 255 bytes in total, with a maximum filename
component length of 100 bytes. USTAR uses a header field (prefix) in addition
to the name field, and splits file paths longer than 100 bytes into two parts.
This split is done on a directory boundary, and is done in such a way to make
the best use of the space available in those two fields, but in practice this
will often mean that you have less than 255 bytes for a path. `erl_tar` will
automatically upgrade the format to PAX to handle longer filenames, so this is
only an issue if you need to extract the archive with an older implementation
of `erl_tar` or `tar` which does not support PAX. In this case, the PAX
headers will be extracted as regular files, and you will need to apply them
manually.
- Like the above, if you must remain USTAR compatible, you must also ensure than
paths for symbolic/hard links are no more than 100 bytes, otherwise PAX
headers will be used.
""".
-export([init/3,
create/2, create/3,
extract/1, extract/2,
table/1, table/2, t/1, tt/1,
open/2, close/1,
add/3, add/4,
format_error/1]).
-include_lib("kernel/include/file.hrl").
-include_lib("erl_tar.hrl").
%% Converts the short error reason to a descriptive string.
-doc "Converts an error reason term to a human-readable error message string.".
-spec format_error(term()) -> string().
format_error(invalid_tar_checksum) ->
"Checksum failed";
format_error(bad_header) ->
"Unrecognized tar header format";
format_error({bad_header, Reason}) ->
lists:flatten(io_lib:format("Unrecognized tar header format: ~p", [Reason]));
format_error({invalid_header, negative_size}) ->
"Invalid header: negative size";
format_error(invalid_sparse_header_size) ->
"Invalid sparse header: negative size";
format_error(invalid_sparse_map_entry) ->
"Invalid sparse map entry";
format_error({invalid_sparse_map_entry, Reason}) ->
lists:flatten(io_lib:format("Invalid sparse map entry: ~p", [Reason]));
format_error(invalid_end_of_archive) ->
"Invalid end of archive";
format_error(eof) ->
"Unexpected end of file";
format_error(integer_overflow) ->
"Failed to parse numeric: integer overflow";
format_error({misaligned_read, Pos}) ->
lists:flatten(io_lib:format("Read a block which was misaligned: block_size=~p pos=~p",
[?BLOCK_SIZE, Pos]));
format_error(invalid_gnu_1_0_sparsemap) ->
"Invalid GNU sparse map (version 1.0)";
format_error({invalid_gnu_0_1_sparsemap, Format}) ->
lists:flatten(io_lib:format("Invalid GNU sparse map (version ~s)", [Format]));
format_error(unsafe_path) ->
"The path points above the current working directory";
format_error({Name,Reason}) ->
lists:flatten(io_lib:format("~ts: ~ts", [Name,format_error(Reason)]));
format_error(Atom) when is_atom(Atom) ->
file:format_error(Atom);
format_error(Term) ->
lists:flatten(io_lib:format("~tp", [Term])).
%% Initializes a new reader given a custom file handle and I/O wrappers
-doc """
The `Fun` is the definition of what to do when the different storage operations
functions are to be called from the higher tar handling functions (such as
[`add/3`](`add/3`), [`add/4`](`add/4`), and [`close/1`](`close/1`)).
The `Fun` is called when the tar function wants to do a low-level operation,
like writing a block to a file. The `Fun` is called as
`Fun(Op, {UserData,Parameters...})`, where `Op` is the operation name,
`UserData` is the term passed as the first argument to `init/1` and
`Parameters...` are the data added by the tar function to be passed down to the
storage handling function.
Parameter `UserData` is typically the result of opening a low-level structure
like a file descriptor or an SFTP channel id. The different `Fun` clauses
operate on that very term.
The following are the fun clauses parameter lists:
- **`(write, {UserData,DataToWrite})`** - Writes term `DataToWrite` using
`UserData`.
- **`(close, UserData)`** - Closes the access.
- **`(read2, {UserData,Size})`** - Reads using `UserData` but only `Size` bytes.
Notice that there is only an arity-2 read function, not an arity-1 function.
- **`(position,{UserData,Position})`** - Sets the position of `UserData` as
defined for files in `file:position/2`
_Example:_
The following is a complete `Fun` parameter for reading and writing on files
using the `m:file` module:
```erlang
ExampleFun =
fun(write, {Fd,Data}) -> file:write(Fd, Data);
(position, {Fd,Pos}) -> file:position(Fd, Pos);
(read2, {Fd,Size}) -> file:read(Fd, Size);
(close, Fd) -> file:close(Fd)
end
```
Here `Fd` was specified to function [`init/3`](`init/3`) as:
```erlang
{ok,Fd} = file:open(Name, ...).
{ok,TarDesc} = erl_tar:init(Fd, [write], ExampleFun),
```
`TarDesc` is then used:
```erlang
erl_tar:add(TarDesc, SomeValueIwantToAdd, FileNameInTarFile),
...,
erl_tar:close(TarDesc)
```
When the `erl_tar` core wants to, for example, write a piece of `Data`, it would
call `ExampleFun(write, {UserData,Data})`.
> #### Note {: .info }
>
> This example with the `file` module operations is not necessary to use
> directly, as that is what function `open/2` in principle does.
> #### Warning {: .warning }
>
> The `TarDescriptor` term is not a file descriptor. You are advised not to rely
> on the specific contents of this term, as it can change in future Erlang/OTP
> releases when more features are added to this module.
""".
-doc(#{since => <<"OTP 17.4">>}).
-spec init(UserData :: user_data(), write | read, file_op()) ->
{ok, tar_descriptor()} | {error, badarg}.
init(UserData, AccessMode, Fun) when is_function(Fun, 2) ->
Reader = #reader{handle=UserData,access=AccessMode,func=Fun},
{ok, Pos, Reader2} = do_position(Reader, {cur, 0}),
{ok, Reader2#reader{pos=Pos}};
init(_UserData, _AccessMode, _Fun) ->
{error, badarg}.
%%%================================================================
%% Extracts all files from the tar file Name.
-doc """
Extracts all files from a tar archive.
If argument `Name` is specified as `{binary,Binary}`, the contents of the binary
is assumed to be a tar archive.
If argument `Name` is specified as `{file,Fd}`, `Fd` is assumed to be a file
descriptor returned from function `file:open/2`.
Otherwise, `Name` is to be a filename.
> #### Note {: .info }
>
> Leading slashes in tar member names will be removed before writing the file.
> That is, absolute paths will be turned into relative paths. There will be an
> info message written to the error logger when paths are changed in this way.
> #### Warning {: .warning }
>
> The `compressed` and `cooked` flags are invalid when passing a file descriptor
> with `{file,Fd}`. The file is assumed to have been opened with the appropriate
> flags.
""".
-spec extract(Open :: open_type()) -> ok | {error, term()}.
extract(Name) ->
extract(Name, []).
%% Extracts (all) files from the tar file Name.
%% Options accepted:
%% - cooked: Opens the tar file without mode `raw`
%% - compressed: Uncompresses the tar file when reading
%% - memory: Returns the tar contents as a list of tuples {Name, Bin}
%% - keep_old_files: Extracted files will not overwrite the destination
%% - {files, ListOfFilesToExtract}: Only extract ListOfFilesToExtract
%% - verbose: Prints verbose information about the extraction,
%% - {cwd, AbsoluteDir}: Sets the current working directory for the extraction
-doc """
Extracts files from a tar archive.
If argument `Name` is specified as `{binary,Binary}`, the contents of the binary
is assumed to be a tar archive.
If argument `Name` is specified as `{file,Fd}`, `Fd` is assumed to be a file
descriptor returned from function `file:open/2`.
Otherwise, `Name` is to be a filename.
The following options modify the defaults for the extraction as follows:
- **`{cwd,Cwd}`** - Files with relative filenames are by default extracted to
the current working directory. With this option, files are instead extracted
into directory `Cwd`.
- **`{files,FileList}`** - By default, all files are extracted from the tar
file. With this option, only those files are extracted whose names are
included in `FileList`.
- **`compressed`** - With this option, the file is uncompressed while
extracting. If the tar file is not compressed, this option is ignored.
- **`cooked`** - By default, function [`open/2`](`open/2`) function opens the
tar file in `raw` mode, which is faster but does not allow a remote (Erlang)
file server to be used. Adding `cooked` to the mode list overrides the default
and opens the tar file without option `raw`.
- **`memory`** - Instead of extracting to a directory, this option gives the
result as a list of tuples `{Filename, Binary}`, where `Binary` is a binary
containing the extracted data of the file named `Filename` in the tar file.
- **`keep_old_files`** - By default, all existing files with the same name as
files in the tar file are overwritten. With this option, existing files are
not overwriten.
- **`verbose`** - Prints an informational message for each extracted file.
> #### Warning {: .warning }
>
> The `compressed` and `cooked` flags are invalid when passing a file descriptor
> with `{file,Fd}`. The file is assumed to have been opened with the appropriate
> flags.
""".
-spec extract(Open :: open_type(), [extract_opt()]) ->
{ok, [{string(), binary()}]} |
{error, term()} |
ok.
extract({binary, Bin}, Opts) when is_list(Opts) ->
do_extract({binary, Bin}, Opts);
extract({file, Fd}, Opts) when is_list(Opts) ->
do_extract({file, Fd}, Opts);
extract(#reader{}=Reader, Opts) when is_list(Opts) ->
do_extract(Reader, Opts);
extract(Name, Opts) when is_list(Name); is_binary(Name), is_list(Opts) ->
do_extract(Name, Opts).
do_extract(Handle, Opts) when is_list(Opts) ->
Opts2 = extract_opts(Opts),
Acc = if Opts2#read_opts.output =:= memory -> []; true -> ok end,
foldl_read(Handle, fun extract1/4, Acc, Opts2).
extract1(eof, Reader, _, Acc) when is_list(Acc) ->
{ok, {ok, lists:reverse(Acc)}, Reader};
extract1(eof, Reader, _, leading_slash) ->
error_logger:info_msg("erl_tar: removed leading '/' from member names\n"),
{ok, ok, Reader};
extract1(eof, Reader, _, Acc) ->
{ok, Acc, Reader};
extract1(#tar_header{name=Name,size=Size}=Header, Reader0, Opts, Acc0) ->
case check_extract(Name, Opts) of
true ->
case do_read(Reader0, Size) of
{ok, Bin, Reader1} ->
Acc = extract2(Header, Bin, Opts, Acc0),
{ok, Acc, Reader1};
{error, _} = Err ->
throw(Err)
end;
false ->
{ok, Acc0, skip_file(Reader0)}
end.
extract2(Header, Bin, Opts, Acc) ->
case write_extracted_element(Header, Bin, Opts) of
ok ->
case Header of
#tar_header{name="/"++_} ->
leading_slash;
#tar_header{} ->
Acc
end;
{ok, NameBin} when is_list(Acc) ->
[NameBin | Acc];
{error, _} = Err ->
throw(Err)
end.
%% Checks if the file Name should be extracted.
check_extract(_, #read_opts{files=all}) ->
true;
check_extract(Name, #read_opts{files=Files}) ->
ordsets:is_element(Name, Files).
%%%================================================================
%% The following table functions produce a list of information about
%% the files contained in the archive.
-type typeflag() :: regular | link | symlink |
char | block | directory |
fifo | reserved | unknown.
-type mode() :: non_neg_integer().
-type uid() :: non_neg_integer().
-type gid() :: non_neg_integer().
-type tar_entry() :: {Name :: name_in_archive(),
Type :: typeflag(),
Size :: non_neg_integer(),
MTime :: tar_time(),
Mode :: mode(),
Uid :: uid(),
Gid :: gid()}.
%% Returns a list of names of the files in the tar file Name.
-doc(#{equiv => table(Open, [])}).
-spec table(Open :: open_type()) -> {ok, [name_in_archive()]} | {error, term()}.
table(Name) ->
table(Name, []).
%% Returns a list of names of the files in the tar file Name.
%% Options accepted: compressed, verbose, cooked.
-doc "Retrieves the names of all files in the tar file `Name`.".
-spec table(Open :: open_type(), [compressed | verbose | cooked]) ->
{ok, [name_in_archive() | tar_entry()]} | {error, term()}.
table(Name, Opts) when is_list(Opts) ->
foldl_read(Name, fun table1/4, [], table_opts(Opts)).
table1(eof, Reader, _, Result) ->
{ok, {ok, lists:reverse(Result)}, Reader};
table1(#tar_header{}=Header, Reader, #read_opts{verbose=Verbose}, Result) ->
Attrs = table1_attrs(Header, Verbose),
Reader2 = skip_file(Reader),
{ok, [Attrs|Result], Reader2}.
%% Extracts attributes relevant to table1's output
table1_attrs(#tar_header{typeflag=Typeflag,mode=Mode}=Header, true) ->
Type = typeflag(Typeflag),
Name = Header#tar_header.name,
Mtime = Header#tar_header.mtime,
Uid = Header#tar_header.uid,
Gid = Header#tar_header.gid,
Size = Header#tar_header.size,
{Name, Type, Size, Mtime, Mode, Uid, Gid};
table1_attrs(#tar_header{name=Name}, _Verbose) ->
Name.
typeflag(?TYPE_REGULAR) -> regular;
typeflag(?TYPE_REGULAR_A) -> regular;
typeflag(?TYPE_GNU_SPARSE) -> regular;
typeflag(?TYPE_CONT) -> regular;
typeflag(?TYPE_LINK) -> link;
typeflag(?TYPE_SYMLINK) -> symlink;
typeflag(?TYPE_CHAR) -> char;
typeflag(?TYPE_BLOCK) -> block;
typeflag(?TYPE_DIR) -> directory;
typeflag(?TYPE_FIFO) -> fifo;
typeflag(_) -> unknown.
%%%================================================================
%% Comments for printing the contents of a tape archive,
%% meant to be invoked from the shell.
%% Prints each filename in the archive
-doc """
Prints the names of all files in the tar file `Name` to the Erlang shell
(similar to "`tar t`").
""".
-spec t(file:filename()) -> ok | {error, term()}.
t(Name) when is_list(Name); is_binary(Name) ->
case table(Name) of
{ok, List} ->
lists:foreach(fun(N) -> ok = io:format("~ts\n", [N]) end, List);
Error ->
Error
end.
%% Prints verbose information about each file in the archive
-doc """
Prints names and information about all files in the tar file `Name` to the
Erlang shell (similar to "`tar tv`").
""".
-spec tt(open_type()) -> ok | {error, term()}.
tt(Name) ->
case table(Name, [verbose]) of
{ok, List} ->
lists:foreach(fun print_header/1, List);
Error ->
Error
end.
%% Used by tt/1 to print a tar_entry tuple
-spec print_header(tar_entry()) -> ok.
print_header({Name, Type, Size, Mtime, Mode, Uid, Gid}) ->
io:format("~s~s ~4w/~-4w ~7w ~s ~s\n",
[type_to_string(Type), mode_to_string(Mode),
Uid, Gid, Size, time_to_string(Mtime), Name]).
type_to_string(regular) -> "-";
type_to_string(directory) -> "d";
type_to_string(link) -> "l";
type_to_string(symlink) -> "s";
type_to_string(char) -> "c";
type_to_string(block) -> "b";
type_to_string(fifo) -> "f";
type_to_string(unknown) -> "?".
%% Converts a numeric mode to its human-readable representation
mode_to_string(Mode) ->
mode_to_string(Mode, "xwrxwrxwr", []).
mode_to_string(Mode, [C|T], Acc) when Mode band 1 =:= 1 ->
mode_to_string(Mode bsr 1, T, [C|Acc]);
mode_to_string(Mode, [_|T], Acc) ->
mode_to_string(Mode bsr 1, T, [$-|Acc]);
mode_to_string(_, [], Acc) ->
Acc.
%% Converts a tar_time() (POSIX time) to a readable string
time_to_string(Secs0) ->
Epoch = calendar:datetime_to_gregorian_seconds(?EPOCH),
Secs = Epoch + Secs0,
DateTime0 = calendar:gregorian_seconds_to_datetime(Secs),
DateTime = calendar:universal_time_to_local_time(DateTime0),
{{Y, Mon, Day}, {H, Min, _}} = DateTime,
io_lib:format("~s ~2w ~s:~s ~w", [month(Mon), Day, two_d(H), two_d(Min), Y]).
two_d(N) ->
tl(integer_to_list(N + 100)).
month(1) -> "Jan";
month(2) -> "Feb";
month(3) -> "Mar";
month(4) -> "Apr";
month(5) -> "May";
month(6) -> "Jun";
month(7) -> "Jul";
month(8) -> "Aug";
month(9) -> "Sep";
month(10) -> "Oct";
month(11) -> "Nov";
month(12) -> "Dec".
%%%================================================================
%% The open function with friends is to keep the file and binary api of this module
-type open_type() :: file:filename_all()
| {binary, binary()}
| {file, file:io_device()}.
-doc """
Creates a tar file for writing (any existing file with the same name is
truncated).
By convention, the name of a tar file is to end in "`.tar`". To abide to the
convention, add "`.tar`" to the name.
Except for the `write` atom, the following atoms can be added to `OpenModeList`:
- **`compressed`** - The entire tar file is compressed, as if it has been run
through the `gzip` program. To abide to the convention that a compressed tar
file is to end in "`.tar.gz`" or "`.tgz`", add the appropriate extension.
- **`cooked`** - By default, the tar file is opened in `raw` mode, which is
faster but does not allow a remote (Erlang) file server to be used. Adding
`cooked` to the mode list overrides the default and opens the tar file without
option `raw`.
To add one file at the time into an opened tar file, use function
[`add/3,4`](`add/3`). When you are finished adding files, use function `close/1`
to close the tar file.
> #### Warning {: .warning }
>
> The `compressed` and `cooked` flags are invalid when passing a file descriptor
> with `{file,Fd}`. The file must already be opened with the appropriate flags.
> #### Warning {: .warning }
>
> The `TarDescriptor` term is not a file descriptor. You are advised not to rely
> on the specific contents of this term, as it can change in future Erlang/OTP
> releases when more features are added to this module.
""".
-spec open(Open :: open_type(), [write | compressed | cooked]) ->
{ok, tar_descriptor()} | {error, term()}.
open({binary, Bin}, Mode) when is_binary(Bin) ->
do_open({binary, Bin}, Mode);
open({file, Fd}, Mode) ->
do_open({file, Fd}, Mode);
open(Name, Mode) when is_list(Name); is_binary(Name) ->
do_open(Name, Mode).
do_open(Name, Mode) when is_list(Mode) ->
case open_mode(Mode) of
{ok, Access, Raw, Opts} ->
open1(Name, Access, Raw, Opts);
{error, Reason} ->
{error, {Name, Reason}}
end.
open1({binary,Bin0}=Handle, read, _Raw, Opts) when is_binary(Bin0) ->
Bin = case lists:member(compressed, Opts) of
true ->
%% emulate file:open with Modes = [compressed_one ...]
Z = zlib:open(),
zlib:inflateInit(Z, 31, cut),
try
IoList = zlib:inflate(Z, Bin0),
zlib:inflateEnd(Z),
iolist_to_binary(IoList)
catch
_:_ -> Bin0
after
zlib:close(Z)
end;
false ->
Bin0
end,
case file:open(Bin, [ram,binary,read]) of
{ok,File} ->
{ok, #reader{handle=File,access=read,func=fun file_op/2}};
{error, Reason} ->
{error, {Handle, Reason}}
end;
open1({file, Fd}=Handle, read, [raw], Opts) ->
case not lists:member(compressed, Opts) of
true ->
Reader = #reader{handle=Fd,access=read,func=fun file_op/2},
case do_position(Reader, {cur, 0}) of
{ok, Pos, Reader2} ->
{ok, Reader2#reader{pos=Pos}};
{error, Reason} ->
{error, {Handle, Reason}}
end;
false ->
{error, {Handle, {incompatible_option, compressed}}}
end;
open1({file, _Fd}=Handle, read, [], _Opts) ->
{error, {Handle, {incompatible_option, cooked}}};
open1(Name, Access, Raw, Opts0) when is_list(Name); is_binary(Name) ->
Opts = case lists:member(compressed, Opts0) andalso Access == read of
true ->
[compressed_one | (Opts0 -- [compressed])];
false ->
Opts0
end,
case file:open(Name, Raw ++ [binary, Access|Opts]) of
{ok, File} ->
{ok, #reader{handle=File,access=Access,func=fun file_op/2}};
{error, Reason} ->
{error, {Name, Reason}}
end.
open_mode(Mode) ->
open_mode(Mode, false, [raw], []).
open_mode(read, _, Raw, _) ->
{ok, read, Raw, []};
open_mode(write, _, Raw, _) ->
{ok, write, Raw, []};
open_mode([read|Rest], false, Raw, Opts) ->
open_mode(Rest, read, Raw, Opts);
open_mode([write|Rest], false, Raw, Opts) ->
open_mode(Rest, write, Raw, Opts);
open_mode([compressed|Rest], Access, Raw, Opts) ->
open_mode(Rest, Access, Raw, [compressed,read_ahead|Opts]);
open_mode([cooked|Rest], Access, _Raw, Opts) ->
open_mode(Rest, Access, [], Opts);
open_mode([], Access, Raw, Opts) ->
{ok, Access, Raw, Opts};
open_mode(_, _, _, _) ->
{error, einval}.
file_op(write, {Fd, Data}) ->
file:write(Fd, Data);
file_op(position, {Fd, Pos}) ->
file:position(Fd, Pos);
file_op(read2, {Fd, Size}) ->
file:read(Fd, Size);
file_op(close, Fd) ->
file:close(Fd).
%% Closes a tar archive.
-doc "Closes a tar file opened by `open/2`.".
-spec close(TarDescriptor :: tar_descriptor()) -> ok | {error, term()}.
close(#reader{access=read}=Reader) ->
ok = do_close(Reader);
close(#reader{access=write}=Reader) ->
{ok, Reader2} = pad_file(Reader),
ok = do_close(Reader2),
ok;
close(_) ->
{error, einval}.
pad_file(#reader{pos=Pos}=Reader) ->
%% There must be at least two zero blocks at the end.
PadCurrent = skip_padding(Pos+?BLOCK_SIZE),
Padding = <<0:PadCurrent/unit:8>>,
do_write(Reader, [Padding, ?ZERO_BLOCK, ?ZERO_BLOCK]).
%%%================================================================
%% Creation/modification of tar archives
%% Creates a tar file Name containing the given files.
-doc """
Creates a tar file and archives the files whose names are specified in
`FileList` into it. The files can either be read from disk or be specified as
binaries.
""".
-spec create(file:filename_all(), filelist()) -> ok | {error, {string(), term()}}.
create(Name, FileList) when is_list(Name); is_binary(Name) ->
create(Name, FileList, []).
%% Creates a tar archive Name containing the given files.
%% Accepted options: verbose, compressed, cooked
-doc """
Creates a tar file and archives the files whose names are specified in
`FileList` into it. The files can either be read from disk or be specified as
binaries.
The options in `OptionList` modify the defaults as follows:
- **`compressed`** - The entire tar file is compressed, as if it has been run
through the `gzip` program. To abide to the convention that a compressed tar
file is to end in "`.tar.gz`" or "`.tgz`", add the appropriate extension.
- **`cooked`** - By default, function [`open/2`](`open/2`) opens the tar file in
`raw` mode, which is faster but does not allow a remote (Erlang) file server
to be used. Adding `cooked` to the mode list overrides the default and opens
the tar file without option `raw`.
- **`dereference`** - By default, symbolic links are stored as symbolic links in
the tar file. To override the default and store the file that the symbolic
link points to into the tar file, use option `dereference`.
- **`verbose`** - Prints an informational message about each added file.
""".
-spec create(file:filename_all(), filelist(), [create_opt()]) ->
ok | {error, term()} | {error, {string(), term()}}.
create(Name, FileList, Options) when is_list(Name); is_binary(Name) ->
Mode = lists:filter(fun(X) -> (X=:=compressed) or (X=:=cooked)
end, Options),
case open(Name, [write|Mode]) of
{ok, TarFile} ->
do_create(TarFile, FileList, Options);
{error, _} = Err ->
Err
end.
do_create(TarFile, [], _Opts) ->
close(TarFile);
do_create(TarFile, [{NameInArchive, NameOrBin}|Rest], Opts) ->
case add(TarFile, NameOrBin, NameInArchive, Opts) of
ok ->
do_create(TarFile, Rest, Opts);
{error, _} = Err ->
_ = close(TarFile),
Err
end;
do_create(TarFile, [Name|Rest], Opts) ->
case add(TarFile, Name, Name, Opts) of
ok ->
do_create(TarFile, Rest, Opts);
{error, _} = Err ->
_ = close(TarFile),
Err
end.
%% Adds a file to a tape archive.
-doc """
Equivalent to `add/4`.
If `Name` is `t:name_in_archive/0`, then [`add(TarDescriptor, Name, Name, Options)`](`add/4`) is called.
If `Name` is a two tuple then [`add(TarDescriptor, NameInArchive, Name, Options)`](`add/4`) is called.
""".
-spec add(TarDescriptor, Name, Options) -> ok | {error, term()} when
TarDescriptor :: tar_descriptor(),
Name :: name_in_archive() | {name_in_archive(), file:filename_all()},
Options :: [add_opt()].
add(Reader, {NameInArchive, Name}, Opts)
when is_list(NameInArchive), is_list(Name) ->
do_add(Reader, Name, NameInArchive, Opts);
add(Reader, {NameInArchive, Bin}, Opts)
when is_list(NameInArchive), is_binary(Bin) ->
do_add(Reader, Bin, NameInArchive, Opts);
add(Reader, Name, Opts) when is_list(Name) ->
do_add(Reader, Name, Name, Opts).
-doc """
Adds a file to a tar file that has been opened for writing by
[`open/1`](`open/2`).
`NameInArchive` is the name under which the file becomes stored in the tar file.
The file gets this name when it is extracted from the tar file.
Options:
- **`dereference`** - By default, symbolic links are stored as symbolic links in
the tar file. To override the default and store the file that the symbolic
link points to into the tar file, use option `dereference`.
- **`verbose`** - Prints an informational message about the added file.
- **`{chunks,ChunkSize}`** - Reads data in parts from the file. This is intended
for memory-limited machines that, for example, builds a tar file on a remote
machine over SFTP, see `ssh_sftp:open_tar/3`.
- **`{atime,non_neg_integer()}`** - Sets the last time, as
[POSIX time](`e:erts:time_correction.md#posix-time`), when the file was read.
See also `file:read_file_info/1`.
- **`{mtime,non_neg_integer()}`** - Sets the last time, as
[POSIX time](`e:erts:time_correction.md#posix-time`), when the file was
written. See also `file:read_file_info/1`.
- **`{ctime,non_neg_integer()}`** - Sets the time, as
[POSIX time](`e:erts:time_correction.md#posix-time`), when the file was
created. See also `file:read_file_info/1`.
- **`{uid,non_neg_integer()}`** - Sets the file owner. `file:read_file_info/1`.
- **`{gid,non_neg_integer()}`** - Sets the group that the file owner belongs to.
`file:read_file_info/1`.
""".
-spec add(TarDescriptor, Filename, NameInArchive, Options) ->
ok | {error, term()} when
TarDescriptor :: tar_descriptor(),
Filename :: file:filename_all(),
NameInArchive :: name_in_archive(),
Options :: [add_opt()].
add(Reader, NameOrBin, NameInArchive, Options)
when is_list(NameOrBin); is_binary(NameOrBin),
is_list(NameInArchive), is_list(Options) ->
do_add(Reader, NameOrBin, NameInArchive, Options).
do_add(#reader{access=write}=Reader, Name, NameInArchive, Options)
when is_list(NameInArchive), is_list(Options) ->
RF = apply_file_info_opts_fun(Options, read_link_info),
Opts = #add_opts{read_info=RF},
add1(Reader, Name, NameInArchive, add_opts(Options, Options, Opts));
do_add(#reader{access=read},_,_,_) ->
{error, eacces};
do_add(Reader,_,_,_) ->
{error, {badarg, Reader}}.
add_opts([dereference|T], AllOptions, Opts) ->
RF = apply_file_info_opts_fun(AllOptions, read_file_info),
add_opts(T, AllOptions, Opts#add_opts{read_info=RF});
add_opts([verbose|T], AllOptions, Opts) ->
add_opts(T, AllOptions, Opts#add_opts{verbose=true});
add_opts([{chunks,N}|T], AllOptions, Opts) ->
add_opts(T, AllOptions, Opts#add_opts{chunk_size=N});
add_opts([{atime,Value}|T], AllOptions, Opts) ->
add_opts(T, AllOptions, Opts#add_opts{atime=Value});
add_opts([{mtime,Value}|T], AllOptions, Opts) ->
add_opts(T, AllOptions, Opts#add_opts{mtime=Value});
add_opts([{ctime,Value}|T], AllOptions, Opts) ->
add_opts(T, AllOptions, Opts#add_opts{ctime=Value});
add_opts([{uid,Value}|T], AllOptions, Opts) ->
add_opts(T, AllOptions, Opts#add_opts{uid=Value});
add_opts([{gid,Value}|T], AllOptions, Opts) ->
add_opts(T, AllOptions, Opts#add_opts{gid=Value});
add_opts([_|T], AllOptions, Opts) ->
add_opts(T, AllOptions, Opts);
add_opts([], _AllOptions, Opts) ->
Opts.
apply_file_info_opts(Opts, {ok, FileInfo}) ->
{ok, do_apply_file_info_opts(Opts, FileInfo)};
apply_file_info_opts(_Opts, Other) ->
Other.
do_apply_file_info_opts([{atime,Value}|T], FileInfo) ->
do_apply_file_info_opts(T, FileInfo#file_info{atime=Value});
do_apply_file_info_opts([{mtime,Value}|T], FileInfo) ->
do_apply_file_info_opts(T, FileInfo#file_info{mtime=Value});
do_apply_file_info_opts([{ctime,Value}|T], FileInfo) ->
do_apply_file_info_opts(T, FileInfo#file_info{ctime=Value});
do_apply_file_info_opts([{uid,Value}|T], FileInfo) ->
do_apply_file_info_opts(T, FileInfo#file_info{uid=Value});
do_apply_file_info_opts([{gid,Value}|T], FileInfo) ->
do_apply_file_info_opts(T, FileInfo#file_info{gid=Value});
do_apply_file_info_opts([_|T], FileInfo) ->
do_apply_file_info_opts(T, FileInfo);
do_apply_file_info_opts([], FileInfo) ->
FileInfo.
apply_file_info_opts_fun(Options, InfoFunction) ->
fun(F) ->
apply_file_info_opts(Options, file:InfoFunction(F, [{time, posix}]))
end.
add1(#reader{}=Reader, Name, NameInArchive, #add_opts{read_info=ReadInfo}=Opts)
when is_list(Name) ->
Res = case ReadInfo(Name) of
{error, Reason0} ->
{error, {Name, Reason0}};
{ok, #file_info{type=symlink}=Fi} ->
add_verbose(Opts, "a ~ts~n", [NameInArchive]),
{ok, Linkname} = file:read_link(Name),
Header = fileinfo_to_header(NameInArchive, Fi, Linkname),
add_header(Reader, Header, Opts);
{ok, #file_info{type=regular}=Fi} ->
add_verbose(Opts, "a ~ts~n", [NameInArchive]),
Header = fileinfo_to_header(NameInArchive, Fi, false),
{ok, Reader2} = add_header(Reader, Header, Opts),
FileSize = Header#tar_header.size,
{ok, FileSize, Reader3} = do_copy(Reader2, Name, Opts),
Padding = skip_padding(FileSize),
Pad = <<0:Padding/unit:8>>,
do_write(Reader3, Pad);
{ok, #file_info{type=directory}=Fi} ->
add_directory(Reader, Name, NameInArchive, Fi, Opts);
{ok, #file_info{}=Fi} ->
add_verbose(Opts, "a ~ts~n", [NameInArchive]),
Header = fileinfo_to_header(NameInArchive, Fi, false),
add_header(Reader, Header, Opts)
end,
case Res of
ok -> ok;
{ok, _Reader} -> ok;
{error, _Reason} = Err -> Err
end;
add1(Reader, Bin, NameInArchive, Opts) when is_binary(Bin) ->
add_verbose(Opts, "a ~ts~n", [NameInArchive]),
Now = os:system_time(seconds),
Header = #tar_header{
name = NameInArchive,
size = byte_size(Bin),
typeflag = ?TYPE_REGULAR,
atime = add_opts_time(Opts#add_opts.atime, Now),
mtime = add_opts_time(Opts#add_opts.mtime, Now),
ctime = add_opts_time(Opts#add_opts.ctime, Now),
uid = Opts#add_opts.uid,
gid = Opts#add_opts.gid,
mode = 8#100644},
{ok, Reader2} = add_header(Reader, Header, Opts),
Padding = skip_padding(byte_size(Bin)),
Data = [Bin, <<0:Padding/unit:8>>],
case do_write(Reader2, Data) of
{ok, _Reader3} -> ok;
{error, Reason} -> {error, {NameInArchive, Reason}}
end.
add_opts_time(undefined, Now) -> Now;
add_opts_time(Time, _Now) -> Time.
add_directory(Reader, DirName, NameInArchive, Info, Opts) ->
case file:list_dir(DirName) of
{ok, []} ->
add_verbose(Opts, "a ~ts~n", [NameInArchive]),
Header = fileinfo_to_header(NameInArchive, Info, false),
add_header(Reader, Header, Opts);
{ok, Files} ->
add_verbose(Opts, "a ~ts~n", [NameInArchive]),
try add_files(Reader, Files, DirName, NameInArchive, Opts) of
ok -> ok;
{error, _} = Err -> Err
catch
throw:{error, {_Name, _Reason}} = Err -> Err;
throw:{error, Reason} -> {error, {DirName, Reason}}
end;
{error, Reason} ->
{error, {DirName, Reason}}
end.
add_files(_Reader, [], _Dir, _DirInArchive, _Opts) ->
ok;
add_files(Reader, [Name|Rest], Dir, DirInArchive, #add_opts{read_info=Info}=Opts) ->
FullName = filename:join(Dir, Name),
NameInArchive = filename:join(DirInArchive, Name),
Res = case Info(FullName) of
{error, Reason} ->
{error, {FullName, Reason}};
{ok, #file_info{type=directory}=Fi} ->
add_directory(Reader, FullName, NameInArchive, Fi, Opts);
{ok, #file_info{type=symlink}=Fi} ->
add_verbose(Opts, "a ~ts~n", [NameInArchive]),
{ok, Linkname} = file:read_link(FullName),
Header = fileinfo_to_header(NameInArchive, Fi, Linkname),
add_header(Reader, Header, Opts);
{ok, #file_info{type=regular}=Fi} ->
add_verbose(Opts, "a ~ts~n", [NameInArchive]),
Header = fileinfo_to_header(NameInArchive, Fi, false),
{ok, Reader2} = add_header(Reader, Header, Opts),
FileSize = Header#tar_header.size,
{ok, FileSize, Reader3} = do_copy(Reader2, FullName, Opts),
Padding = skip_padding(FileSize),
Pad = <<0:Padding/unit:8>>,
do_write(Reader3, Pad);
{ok, #file_info{}=Fi} ->
add_verbose(Opts, "a ~ts~n", [NameInArchive]),
Header = fileinfo_to_header(NameInArchive, Fi, false),
add_header(Reader, Header, Opts)
end,
case Res of
ok -> add_files(Reader, Rest, Dir, DirInArchive, Opts);
{ok, ReaderNext} -> add_files(ReaderNext, Rest, Dir, DirInArchive, Opts);
{error, _} = Err -> Err
end.
format_string(String, Size) when length(String) > Size ->
throw({error, {write_string, field_too_long}});
format_string(String, Size) ->
Ascii = to_ascii(String),
if byte_size(Ascii) < Size ->
[Ascii, 0];
true ->
Ascii
end.
format_octal(Octal) ->
iolist_to_binary(io_lib:fwrite("~.8B", [Octal])).
add_header(#reader{}=Reader, #tar_header{}=Header, Opts) ->
{ok, Iodata} = build_header(Header, Opts),
do_write(Reader, Iodata).
write_to_block(Block, IoData, Start) when is_list(IoData) ->