mirrored from git://git.sv.gnu.org/coreutils.git
-
Notifications
You must be signed in to change notification settings - Fork 897
/
copy.c
3469 lines (3108 loc) · 123 KB
/
copy.c
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
/* copy.c -- core functions for copying files and directories
Copyright (C) 1989-2024 Free Software Foundation, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>. */
/* Extracted from cp.c and librarified by Jim Meyering. */
#include <config.h>
#include <stdio.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <selinux/selinux.h>
#if HAVE_HURD_H
# include <hurd.h>
#endif
#if HAVE_PRIV_H
# include <priv.h>
#endif
#include "system.h"
#include "acl.h"
#include "alignalloc.h"
#include "assure.h"
#include "backupfile.h"
#include "buffer-lcm.h"
#include "canonicalize.h"
#include "copy.h"
#include "cp-hash.h"
#include "fadvise.h"
#include "fcntl--.h"
#include "file-set.h"
#include "filemode.h"
#include "filenamecat.h"
#include "force-link.h"
#include "full-write.h"
#include "hash.h"
#include "hash-triple.h"
#include "ignore-value.h"
#include "ioblksize.h"
#include "quote.h"
#include "renameatu.h"
#include "root-uid.h"
#include "same.h"
#include "savedir.h"
#include "stat-size.h"
#include "stat-time.h"
#include "utimecmp.h"
#include "utimens.h"
#include "write-any-file.h"
#include "areadlink.h"
#include "yesno.h"
#include "selinux.h"
#ifndef USE_XATTR
# define USE_XATTR false
#endif
#if USE_XATTR
# include <attr/error_context.h>
# include <attr/libattr.h>
# include <stdarg.h>
# include "verror.h"
#endif
#if HAVE_LINUX_FALLOC_H
# include <linux/falloc.h>
#endif
/* See HAVE_FALLOCATE workaround when including this file. */
#ifdef HAVE_LINUX_FS_H
# include <linux/fs.h>
#endif
#if !defined FICLONE && defined __linux__
# define FICLONE _IOW (0x94, 9, int)
#endif
#if HAVE_FCLONEFILEAT && !USE_XATTR
# include <sys/clonefile.h>
#endif
#ifndef USE_ACL
# define USE_ACL 0
#endif
#define SAME_OWNER(A, B) ((A).st_uid == (B).st_uid)
#define SAME_GROUP(A, B) ((A).st_gid == (B).st_gid)
#define SAME_OWNER_AND_GROUP(A, B) (SAME_OWNER (A, B) && SAME_GROUP (A, B))
/* LINK_FOLLOWS_SYMLINKS is tri-state; if it is -1, we don't know
how link() behaves, so assume we can't hardlink symlinks in that case. */
#if (defined HAVE_LINKAT && ! LINKAT_SYMLINK_NOTSUP) || ! LINK_FOLLOWS_SYMLINKS
# define CAN_HARDLINK_SYMLINKS 1
#else
# define CAN_HARDLINK_SYMLINKS 0
#endif
struct dir_list
{
struct dir_list *parent;
ino_t ino;
dev_t dev;
};
/* Initial size of the cp.dest_info hash table. */
#define DEST_INFO_INITIAL_CAPACITY 61
static bool copy_internal (char const *src_name, char const *dst_name,
int dst_dirfd, char const *dst_relname,
int nonexistent_dst, struct stat const *parent,
struct dir_list *ancestors,
const struct cp_options *x,
bool command_line_arg,
bool *first_dir_created_per_command_line_arg,
bool *copy_into_self,
bool *rename_succeeded);
static bool owner_failure_ok (struct cp_options const *x);
/* Pointers to the file names: they're used in the diagnostic that is issued
when we detect the user is trying to copy a directory into itself. */
static char const *top_level_src_name;
static char const *top_level_dst_name;
enum copy_debug_val
{
COPY_DEBUG_UNKNOWN,
COPY_DEBUG_NO,
COPY_DEBUG_YES,
COPY_DEBUG_EXTERNAL,
COPY_DEBUG_EXTERNAL_INTERNAL,
COPY_DEBUG_AVOIDED,
COPY_DEBUG_UNSUPPORTED,
};
/* debug info about the last file copy. */
static struct copy_debug
{
enum copy_debug_val offload;
enum copy_debug_val reflink;
enum copy_debug_val sparse_detection;
} copy_debug;
static const char*
copy_debug_string (enum copy_debug_val debug_val)
{
switch (debug_val)
{
case COPY_DEBUG_NO: return "no";
case COPY_DEBUG_YES: return "yes";
case COPY_DEBUG_AVOIDED: return "avoided";
case COPY_DEBUG_UNSUPPORTED: return "unsupported";
default: return "unknown";
}
}
static const char*
copy_debug_sparse_string (enum copy_debug_val debug_val)
{
switch (debug_val)
{
case COPY_DEBUG_NO: return "no";
case COPY_DEBUG_YES: return "zeros";
case COPY_DEBUG_EXTERNAL: return "SEEK_HOLE";
case COPY_DEBUG_EXTERNAL_INTERNAL: return "SEEK_HOLE + zeros";
default: return "unknown";
}
}
/* Print --debug output on standard output. */
static void
emit_debug (const struct cp_options *x)
{
if (! x->hard_link && ! x->symbolic_link && x->data_copy_required)
printf ("copy offload: %s, reflink: %s, sparse detection: %s\n",
copy_debug_string (copy_debug.offload),
copy_debug_string (copy_debug.reflink),
copy_debug_sparse_string (copy_debug.sparse_detection));
}
#ifndef DEV_FD_MIGHT_BE_CHR
# define DEV_FD_MIGHT_BE_CHR false
#endif
/* Act like fstat (DIRFD, FILENAME, ST, FLAGS), except when following
symbolic links on Solaris-like systems, treat any character-special
device like /dev/fd/0 as if it were the file it is open on. */
static int
follow_fstatat (int dirfd, char const *filename, struct stat *st, int flags)
{
int result = fstatat (dirfd, filename, st, flags);
if (DEV_FD_MIGHT_BE_CHR && result == 0 && !(flags & AT_SYMLINK_NOFOLLOW)
&& S_ISCHR (st->st_mode))
{
static dev_t stdin_rdev;
static signed char stdin_rdev_status;
if (stdin_rdev_status == 0)
{
struct stat stdin_st;
if (stat ("/dev/stdin", &stdin_st) == 0 && S_ISCHR (stdin_st.st_mode)
&& minor (stdin_st.st_rdev) == STDIN_FILENO)
{
stdin_rdev = stdin_st.st_rdev;
stdin_rdev_status = 1;
}
else
stdin_rdev_status = -1;
}
if (0 < stdin_rdev_status && major (stdin_rdev) == major (st->st_rdev))
result = fstat (minor (st->st_rdev), st);
}
return result;
}
/* Attempt to punch a hole to avoid any permanent
speculative preallocation on file systems such as XFS.
Return values as per fallocate(2) except ENOSYS etc. are ignored. */
static int
punch_hole (int fd, off_t offset, off_t length)
{
int ret = 0;
/* +0 is to work around older <linux/fs.h> defining HAVE_FALLOCATE to empty. */
#if HAVE_FALLOCATE + 0
# if defined FALLOC_FL_PUNCH_HOLE && defined FALLOC_FL_KEEP_SIZE
ret = fallocate (fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
offset, length);
if (ret < 0 && (is_ENOTSUP (errno) || errno == ENOSYS))
ret = 0;
# endif
#endif
return ret;
}
/* Create a hole at the end of a file,
avoiding preallocation if requested. */
static bool
create_hole (int fd, char const *name, bool punch_holes, off_t size)
{
off_t file_end = lseek (fd, size, SEEK_CUR);
if (file_end < 0)
{
error (0, errno, _("cannot lseek %s"), quoteaf (name));
return false;
}
/* Some file systems (like XFS) preallocate when write extending a file.
I.e., a previous write() may have preallocated extra space
that the seek above will not discard. A subsequent write() could
then make this allocation permanent. */
if (punch_holes && punch_hole (fd, file_end - size, size) < 0)
{
error (0, errno, _("error deallocating %s"), quoteaf (name));
return false;
}
return true;
}
/* Whether an errno value ERR, set by FICLONE or copy_file_range,
indicates that the copying operation has terminally failed, even
though it was invoked correctly (so that, e.g, EBADF cannot occur)
and even though !is_CLONENOTSUP (ERR). */
static bool
is_terminal_error (int err)
{
return err == EIO || err == ENOMEM || err == ENOSPC || err == EDQUOT;
}
/* Similarly, whether ERR indicates that the copying operation is not
supported or allowed for this file or process, even though the
operation was invoked correctly. */
static bool
is_CLONENOTSUP (int err)
{
return err == ENOSYS || err == ENOTTY || is_ENOTSUP (err)
|| err == EINVAL || err == EBADF
|| err == EXDEV || err == ETXTBSY
|| err == EPERM || err == EACCES;
}
/* Copy the regular file open on SRC_FD/SRC_NAME to DST_FD/DST_NAME,
honoring the MAKE_HOLES setting and using the BUF_SIZE-byte buffer
*ABUF for temporary storage, allocating it lazily if *ABUF is null.
Copy no more than MAX_N_READ bytes.
Return true upon successful completion;
print a diagnostic and return false upon error.
Note that for best results, BUF should be "well"-aligned.
Set *LAST_WRITE_MADE_HOLE to true if the final operation on
DEST_FD introduced a hole. Set *TOTAL_N_READ to the number of
bytes read. */
static bool
sparse_copy (int src_fd, int dest_fd, char **abuf, size_t buf_size,
size_t hole_size, bool punch_holes, bool allow_reflink,
char const *src_name, char const *dst_name,
uintmax_t max_n_read, off_t *total_n_read,
bool *last_write_made_hole)
{
*last_write_made_hole = false;
*total_n_read = 0;
if (copy_debug.sparse_detection == COPY_DEBUG_UNKNOWN)
copy_debug.sparse_detection = hole_size ? COPY_DEBUG_YES : COPY_DEBUG_NO;
else if (hole_size && copy_debug.sparse_detection == COPY_DEBUG_EXTERNAL)
copy_debug.sparse_detection = COPY_DEBUG_EXTERNAL_INTERNAL;
/* If not looking for holes, use copy_file_range if functional,
but don't use if reflink disallowed as that may be implicit. */
if (!hole_size && allow_reflink)
while (max_n_read)
{
/* Copy at most COPY_MAX bytes at a time; this is min
(SSIZE_MAX, SIZE_MAX) truncated to a value that is
surely aligned well. */
ssize_t copy_max = MIN (SSIZE_MAX, SIZE_MAX) >> 30 << 30;
ssize_t n_copied = copy_file_range (src_fd, nullptr, dest_fd, nullptr,
MIN (max_n_read, copy_max), 0);
if (n_copied == 0)
{
/* copy_file_range incorrectly returns 0 when reading from
the proc file system on the Linux kernel through at
least 5.6.19 (2020), so fall back on 'read' if the
input file seems empty. */
if (*total_n_read == 0)
break;
copy_debug.offload = COPY_DEBUG_YES;
return true;
}
if (n_copied < 0)
{
copy_debug.offload = COPY_DEBUG_UNSUPPORTED;
/* Consider operation unsupported only if no data copied.
For example, EPERM could occur if copy_file_range not enabled
in seccomp filters, so retry with a standard copy. EPERM can
also occur for immutable files, but that would only be in the
edge case where the file is made immutable after creating,
in which case the (more accurate) error is still shown. */
if (*total_n_read == 0 && is_CLONENOTSUP (errno))
break;
/* ENOENT was seen sometimes across CIFS shares, resulting in
no data being copied, but subsequent standard copies succeed. */
if (*total_n_read == 0 && errno == ENOENT)
break;
if (errno == EINTR)
n_copied = 0;
else
{
error (0, errno, _("error copying %s to %s"),
quoteaf_n (0, src_name), quoteaf_n (1, dst_name));
return false;
}
}
copy_debug.offload = COPY_DEBUG_YES;
max_n_read -= n_copied;
*total_n_read += n_copied;
}
else
copy_debug.offload = COPY_DEBUG_AVOIDED;
bool make_hole = false;
off_t psize = 0;
while (max_n_read)
{
if (!*abuf)
*abuf = xalignalloc (getpagesize (), buf_size);
char *buf = *abuf;
ssize_t n_read = read (src_fd, buf, MIN (max_n_read, buf_size));
if (n_read < 0)
{
if (errno == EINTR)
continue;
error (0, errno, _("error reading %s"), quoteaf (src_name));
return false;
}
if (n_read == 0)
break;
max_n_read -= n_read;
*total_n_read += n_read;
/* Loop over the input buffer in chunks of hole_size. */
size_t csize = hole_size ? hole_size : buf_size;
char *cbuf = buf;
char *pbuf = buf;
while (n_read)
{
bool prev_hole = make_hole;
csize = MIN (csize, n_read);
if (hole_size && csize)
make_hole = is_nul (cbuf, csize);
bool transition = (make_hole != prev_hole) && psize;
bool last_chunk = (n_read == csize && ! make_hole) || ! csize;
if (transition || last_chunk)
{
if (! transition)
psize += csize;
if (! prev_hole)
{
if (full_write (dest_fd, pbuf, psize) != psize)
{
error (0, errno, _("error writing %s"),
quoteaf (dst_name));
return false;
}
}
else
{
if (! create_hole (dest_fd, dst_name, punch_holes, psize))
return false;
}
pbuf = cbuf;
psize = csize;
if (last_chunk)
{
if (! csize)
n_read = 0; /* Finished processing buffer. */
if (transition)
csize = 0; /* Loop again to deal with last chunk. */
else
psize = 0; /* Reset for next read loop. */
}
}
else /* Coalesce writes/seeks. */
{
if (ckd_add (&psize, psize, csize))
{
error (0, 0, _("overflow reading %s"), quoteaf (src_name));
return false;
}
}
n_read -= csize;
cbuf += csize;
}
*last_write_made_hole = make_hole;
/* It's tempting to break early here upon a short read from
a regular file. That would save the final read syscall
for each file. Unfortunately that doesn't work for
certain files in /proc or /sys with linux kernels. */
}
/* Ensure a trailing hole is created, so that subsequent
calls of sparse_copy() start at the correct offset. */
if (make_hole && ! create_hole (dest_fd, dst_name, punch_holes, psize))
return false;
else
return true;
}
/* Perform the O(1) btrfs clone operation, if possible.
Upon success, return 0. Otherwise, return -1 and set errno. */
static inline int
clone_file (int dest_fd, int src_fd)
{
#ifdef FICLONE
return ioctl (dest_fd, FICLONE, src_fd);
#else
(void) dest_fd;
(void) src_fd;
errno = ENOTSUP;
return -1;
#endif
}
/* Write N_BYTES zero bytes to file descriptor FD. Return true if successful.
Upon write failure, set errno and return false. */
static bool
write_zeros (int fd, off_t n_bytes)
{
static char *zeros;
static size_t nz = IO_BUFSIZE;
/* Attempt to use a relatively large calloc'd source buffer for
efficiency, but if that allocation fails, resort to a smaller
statically allocated one. */
if (zeros == nullptr)
{
static char fallback[1024];
zeros = calloc (nz, 1);
if (zeros == nullptr)
{
zeros = fallback;
nz = sizeof fallback;
}
}
while (n_bytes)
{
size_t n = MIN (nz, n_bytes);
if ((full_write (fd, zeros, n)) != n)
return false;
n_bytes -= n;
}
return true;
}
#ifdef SEEK_HOLE
/* Perform an efficient extent copy, if possible. This avoids
the overhead of detecting holes in hole-introducing/preserving
copy, and thus makes copying sparse files much more efficient.
Copy from SRC_FD to DEST_FD, using *ABUF (of size BUF_SIZE) for a buffer.
Allocate *ABUF lazily if *ABUF is null.
Look for holes of size HOLE_SIZE in the input.
The input file is of size SRC_TOTAL_SIZE.
Use SPARSE_MODE to determine whether to create holes in the output.
SRC_NAME and DST_NAME are the input and output file names.
Return true if successful, false (with a diagnostic) otherwise. */
static bool
lseek_copy (int src_fd, int dest_fd, char **abuf, size_t buf_size,
size_t hole_size, off_t ext_start, off_t src_total_size,
enum Sparse_type sparse_mode,
bool allow_reflink,
char const *src_name, char const *dst_name)
{
off_t last_ext_start = 0;
off_t last_ext_len = 0;
off_t dest_pos = 0;
bool wrote_hole_at_eof = true;
copy_debug.sparse_detection = COPY_DEBUG_EXTERNAL;
while (0 <= ext_start)
{
off_t ext_end = lseek (src_fd, ext_start, SEEK_HOLE);
if (ext_end < 0)
{
if (errno != ENXIO)
goto cannot_lseek;
ext_end = src_total_size;
if (ext_end <= ext_start)
{
/* The input file grew; get its current size. */
src_total_size = lseek (src_fd, 0, SEEK_END);
if (src_total_size < 0)
goto cannot_lseek;
/* If the input file shrank after growing, stop copying. */
if (src_total_size <= ext_start)
break;
ext_end = src_total_size;
}
}
/* If the input file must have grown, increase its measured size. */
if (src_total_size < ext_end)
src_total_size = ext_end;
if (lseek (src_fd, ext_start, SEEK_SET) < 0)
goto cannot_lseek;
wrote_hole_at_eof = false;
off_t ext_hole_size = ext_start - last_ext_start - last_ext_len;
if (ext_hole_size)
{
if (sparse_mode != SPARSE_NEVER)
{
if (! create_hole (dest_fd, dst_name,
sparse_mode == SPARSE_ALWAYS,
ext_hole_size))
return false;
wrote_hole_at_eof = true;
}
else
{
/* When not inducing holes and when there is a hole between
the end of the previous extent and the beginning of the
current one, write zeros to the destination file. */
if (! write_zeros (dest_fd, ext_hole_size))
{
error (0, errno, _("%s: write failed"),
quotef (dst_name));
return false;
}
}
}
off_t ext_len = ext_end - ext_start;
last_ext_start = ext_start;
last_ext_len = ext_len;
/* Copy this extent, looking for further opportunities to not
bother to write zeros if --sparse=always, since SEEK_HOLE
is conservative and may miss some holes. */
off_t n_read;
bool read_hole;
if ( ! sparse_copy (src_fd, dest_fd, abuf, buf_size,
sparse_mode != SPARSE_ALWAYS ? 0 : hole_size,
true, allow_reflink, src_name, dst_name,
ext_len, &n_read, &read_hole))
return false;
dest_pos = ext_start + n_read;
if (n_read)
wrote_hole_at_eof = read_hole;
if (n_read < ext_len)
{
/* The input file shrank. */
src_total_size = dest_pos;
break;
}
ext_start = lseek (src_fd, dest_pos, SEEK_DATA);
if (ext_start < 0 && errno != ENXIO)
goto cannot_lseek;
}
/* When the source file ends with a hole, we have to do a little more work,
since the above copied only up to and including the final extent.
In order to complete the copy, we may have to insert a hole or write
zeros in the destination corresponding to the source file's hole-at-EOF.
In addition, if the final extent was a block of zeros at EOF and we've
just converted them to a hole in the destination, we must call ftruncate
here in order to record the proper length in the destination. */
if ((dest_pos < src_total_size || wrote_hole_at_eof)
&& ! (sparse_mode == SPARSE_NEVER
? write_zeros (dest_fd, src_total_size - dest_pos)
: ftruncate (dest_fd, src_total_size) == 0))
{
error (0, errno, _("failed to extend %s"), quoteaf (dst_name));
return false;
}
if (sparse_mode == SPARSE_ALWAYS && dest_pos < src_total_size
&& punch_hole (dest_fd, dest_pos, src_total_size - dest_pos) < 0)
{
error (0, errno, _("error deallocating %s"), quoteaf (dst_name));
return false;
}
return true;
cannot_lseek:
error (0, errno, _("cannot lseek %s"), quoteaf (src_name));
return false;
}
#endif
/* FIXME: describe */
/* FIXME: rewrite this to use a hash table so we avoid the quadratic
performance hit that's probably noticeable only on trees deeper
than a few hundred levels. See use of active_dir_map in remove.c */
ATTRIBUTE_PURE
static bool
is_ancestor (const struct stat *sb, const struct dir_list *ancestors)
{
while (ancestors != 0)
{
if (ancestors->ino == sb->st_ino && ancestors->dev == sb->st_dev)
return true;
ancestors = ancestors->parent;
}
return false;
}
static bool
errno_unsupported (int err)
{
return err == ENOTSUP || err == ENODATA;
}
#if USE_XATTR
ATTRIBUTE_FORMAT ((printf, 2, 3))
static void
copy_attr_error (MAYBE_UNUSED struct error_context *ctx,
char const *fmt, ...)
{
if (!errno_unsupported (errno))
{
int err = errno;
va_list ap;
/* use verror module to print error message */
va_start (ap, fmt);
verror (0, err, fmt, ap);
va_end (ap);
}
}
ATTRIBUTE_FORMAT ((printf, 2, 3))
static void
copy_attr_allerror (MAYBE_UNUSED struct error_context *ctx,
char const *fmt, ...)
{
int err = errno;
va_list ap;
/* use verror module to print error message */
va_start (ap, fmt);
verror (0, err, fmt, ap);
va_end (ap);
}
static char const *
copy_attr_quote (MAYBE_UNUSED struct error_context *ctx, char const *str)
{
return quoteaf (str);
}
static void
copy_attr_free (MAYBE_UNUSED struct error_context *ctx,
MAYBE_UNUSED char const *str)
{
}
/* Exclude SELinux extended attributes that are otherwise handled,
and are problematic to copy again. Also honor attributes
configured for exclusion in /etc/xattr.conf.
FIXME: Should we handle POSIX ACLs similarly?
Return zero to skip. */
static int
check_selinux_attr (char const *name, struct error_context *ctx)
{
return STRNCMP_LIT (name, "security.selinux")
&& attr_copy_check_permissions (name, ctx);
}
/* If positive SRC_FD and DST_FD descriptors are passed,
then copy by fd, otherwise copy by name. */
static bool
copy_attr (char const *src_path, int src_fd,
char const *dst_path, int dst_fd, struct cp_options const *x)
{
bool all_errors = (!x->data_copy_required || x->require_preserve_xattr);
bool some_errors = (!all_errors && !x->reduce_diagnostics);
int (*check) (char const *, struct error_context *)
= (x->preserve_security_context || x->set_security_context
? check_selinux_attr : nullptr);
# if 4 < __GNUC__ + (8 <= __GNUC_MINOR__)
/* Pacify gcc -Wsuggest-attribute=format through at least GCC 13.2.1. */
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wsuggest-attribute=format"
# endif
struct error_context *ctx
= (all_errors || some_errors
? (&(struct error_context) {
.error = all_errors ? copy_attr_allerror : copy_attr_error,
.quote = copy_attr_quote,
.quote_free = copy_attr_free
})
: nullptr);
# if 4 < __GNUC__ + (8 <= __GNUC_MINOR__)
# pragma GCC diagnostic pop
# endif
return ! (0 <= src_fd && 0 <= dst_fd
? attr_copy_fd (src_path, src_fd, dst_path, dst_fd, check, ctx)
: attr_copy_file (src_path, dst_path, check, ctx));
}
#else /* USE_XATTR */
static bool
copy_attr (MAYBE_UNUSED char const *src_path,
MAYBE_UNUSED int src_fd,
MAYBE_UNUSED char const *dst_path,
MAYBE_UNUSED int dst_fd,
MAYBE_UNUSED struct cp_options const *x)
{
return true;
}
#endif /* USE_XATTR */
/* Read the contents of the directory SRC_NAME_IN, and recursively
copy the contents to DST_NAME_IN aka DST_DIRFD+DST_RELNAME_IN.
NEW_DST is true if DST_NAME_IN is a directory
that was created previously in the recursion.
SRC_SB and ANCESTORS describe SRC_NAME_IN.
Set *COPY_INTO_SELF if SRC_NAME_IN is a parent of
(or the same as) DST_NAME_IN; otherwise, clear it.
Propagate *FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG from
caller to each invocation of copy_internal. Be careful to
pass the address of a temporary, and to update
*FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG only upon completion.
Return true if successful. */
static bool
copy_dir (char const *src_name_in, char const *dst_name_in,
int dst_dirfd, char const *dst_relname_in, bool new_dst,
const struct stat *src_sb, struct dir_list *ancestors,
const struct cp_options *x,
bool *first_dir_created_per_command_line_arg,
bool *copy_into_self)
{
char *name_space;
char *namep;
struct cp_options non_command_line_options = *x;
bool ok = true;
name_space = savedir (src_name_in, SAVEDIR_SORT_FASTREAD);
if (name_space == nullptr)
{
/* This diagnostic is a bit vague because savedir can fail in
several different ways. */
error (0, errno, _("cannot access %s"), quoteaf (src_name_in));
return false;
}
/* For cp's -H option, dereference command line arguments, but do not
dereference symlinks that are found via recursive traversal. */
if (x->dereference == DEREF_COMMAND_LINE_ARGUMENTS)
non_command_line_options.dereference = DEREF_NEVER;
bool new_first_dir_created = false;
namep = name_space;
while (*namep != '\0')
{
bool local_copy_into_self;
char *src_name = file_name_concat (src_name_in, namep, nullptr);
char *dst_name = file_name_concat (dst_name_in, namep, nullptr);
bool first_dir_created = *first_dir_created_per_command_line_arg;
bool rename_succeeded;
ok &= copy_internal (src_name, dst_name, dst_dirfd,
dst_name + (dst_relname_in - dst_name_in),
new_dst, src_sb,
ancestors, &non_command_line_options, false,
&first_dir_created,
&local_copy_into_self, &rename_succeeded);
*copy_into_self |= local_copy_into_self;
free (dst_name);
free (src_name);
/* If we're copying into self, there's no point in continuing,
and in fact, that would even infloop, now that we record only
the first created directory per command line argument. */
if (local_copy_into_self)
break;
new_first_dir_created |= first_dir_created;
namep += strlen (namep) + 1;
}
free (name_space);
*first_dir_created_per_command_line_arg = new_first_dir_created;
return ok;
}
/* Change the file mode bits of the file identified by DESC or
DIRFD+NAME to MODE. Use DESC if DESC is valid and fchmod is
available, DIRFD+NAME otherwise. */
static int
fchmod_or_lchmod (int desc, int dirfd, char const *name, mode_t mode)
{
#if HAVE_FCHMOD
if (0 <= desc)
return fchmod (desc, mode);
#endif
return lchmodat (dirfd, name, mode);
}
/* Change the ownership of the file identified by DESC or
DIRFD+NAME to UID+GID. Use DESC if DESC is valid and fchown is
available, DIRFD+NAME otherwise. */
static int
fchown_or_lchown (int desc, int dirfd, char const *name, uid_t uid, gid_t gid)
{
#if HAVE_FCHOWN
if (0 <= desc)
return fchown (desc, uid, gid);
#endif
return lchownat (dirfd, name, uid, gid);
}
/* Set the owner and owning group of DEST_DESC to the st_uid and
st_gid fields of SRC_SB. If DEST_DESC is undefined (-1), set
the owner and owning group of DST_NAME aka DST_DIRFD+DST_RELNAME
instead; for safety prefer lchownat since no
symbolic links should be involved. DEST_DESC must
refer to the same file as DST_NAME if defined.
Upon failure to set both UID and GID, try to set only the GID.
NEW_DST is true if the file was newly created; otherwise,
DST_SB is the status of the destination.
Return 1 if the initial syscall succeeds, 0 if it fails but it's OK
not to preserve ownership, -1 otherwise. */
static int
set_owner (const struct cp_options *x, char const *dst_name,
int dst_dirfd, char const *dst_relname, int dest_desc,
struct stat const *src_sb, bool new_dst,
struct stat const *dst_sb)
{
uid_t uid = src_sb->st_uid;
gid_t gid = src_sb->st_gid;
/* Naively changing the ownership of an already-existing file before
changing its permissions would create a window of vulnerability if
the file's old permissions are too generous for the new owner and
group. Avoid the window by first changing to a restrictive
temporary mode if necessary. */
if (!new_dst && (x->preserve_mode || x->move_mode || x->set_mode))
{
mode_t old_mode = dst_sb->st_mode;
mode_t new_mode =
(x->preserve_mode || x->move_mode ? src_sb->st_mode : x->mode);
mode_t restrictive_temp_mode = old_mode & new_mode & S_IRWXU;
if ((USE_ACL
|| (old_mode & CHMOD_MODE_BITS
& (~new_mode | S_ISUID | S_ISGID | S_ISVTX)))
&& qset_acl (dst_name, dest_desc, restrictive_temp_mode) != 0)
{
if (! owner_failure_ok (x))
error (0, errno, _("clearing permissions for %s"),
quoteaf (dst_name));
return -x->require_preserve;
}
}
if (fchown_or_lchown (dest_desc, dst_dirfd, dst_relname, uid, gid) == 0)
return 1;
/* The ownership change failed. If the failure merely means we lack
privileges to change owner+group, try to change just the group
and ignore any failure of this. Otherwise, report an error. */
if (chown_failure_ok (x))
ignore_value (fchown_or_lchown (dest_desc, dst_dirfd, dst_relname,
-1, gid));
else
{
error (0, errno, _("failed to preserve ownership for %s"),
quoteaf (dst_name));
if (x->require_preserve)
return -1;
}
return 0;
}
/* Set the st_author field of DEST_DESC to the st_author field of
SRC_SB. If DEST_DESC is undefined (-1), set the st_author field
of DST_NAME instead. DEST_DESC must refer to the same file as
DST_NAME if defined. */
static void
set_author (char const *dst_name, int dest_desc, const struct stat *src_sb)
{
#if HAVE_STRUCT_STAT_ST_AUTHOR
/* FIXME: Modify the following code so that it does not
follow symbolic links. */
/* Preserve the st_author field. */
file_t file = (dest_desc < 0
? file_name_lookup (dst_name, 0, 0)
: getdport (dest_desc));
if (file == MACH_PORT_NULL)
error (0, errno, _("failed to lookup file %s"), quoteaf (dst_name));
else
{
error_t err = file_chauthor (file, src_sb->st_author);
if (err)
error (0, err, _("failed to preserve authorship for %s"),
quoteaf (dst_name));
mach_port_deallocate (mach_task_self (), file);
}
#else
(void) dst_name;
(void) dest_desc;