/
copy.c
2361 lines (2112 loc) · 80.7 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-1991, 1995-2010 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 <http://www.gnu.org/licenses/>. */
/* Extracted from cp.c and librarified by Jim Meyering. */
#include <config.h>
#include <stdio.h>
#include <assert.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 "backupfile.h"
#include "buffer-lcm.h"
#include "copy.h"
#include "cp-hash.h"
#include "error.h"
#include "fcntl--.h"
#include "file-set.h"
#include "filemode.h"
#include "filenamecat.h"
#include "full-write.h"
#include "hash.h"
#include "hash-triple.h"
#include "ignore-value.h"
#include "quote.h"
#include "same.h"
#include "savedir.h"
#include "stat-time.h"
#include "utimecmp.h"
#include "utimens.h"
#include "write-any-file.h"
#include "areadlink.h"
#include "yesno.h"
#if USE_XATTR
# include <attr/error_context.h>
# include <attr/libattr.h>
# include <stdarg.h>
# include "verror.h"
#endif
#if HAVE_SYS_IOCTL_H
# include <sys/ioctl.h>
#endif
#ifndef HAVE_FCHOWN
# define HAVE_FCHOWN false
# define fchown(fd, uid, gid) (-1)
#endif
#ifndef HAVE_LCHOWN
# define HAVE_LCHOWN false
# define lchown(name, uid, gid) chown (name, uid, gid)
#endif
#ifndef HAVE_MKFIFO
static int
rpl_mkfifo (char const *file, mode_t mode)
{
errno = ENOTSUP;
return -1;
}
# define mkfifo rpl_mkfifo
#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))
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,
bool new_dst, dev_t device,
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;
/* Set the timestamp of symlink, FILE, to TIMESPEC.
If this system lacks support for that, simply return 0. */
static inline int
utimens_symlink (char const *file, struct timespec const *timespec)
{
int err = lutimens (file, timespec);
/* When configuring on a system with new headers and libraries, and
running on one with a kernel that is old enough to lack the syscall,
utimensat fails with ENOSYS. Ignore that. */
if (err && errno == ENOSYS)
err = 0;
return err;
}
/* 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 __linux__
# undef BTRFS_IOCTL_MAGIC
# define BTRFS_IOCTL_MAGIC 0x94
# undef BTRFS_IOC_CLONE
# define BTRFS_IOC_CLONE _IOW (BTRFS_IOCTL_MAGIC, 9, int)
return ioctl (dest_fd, BTRFS_IOC_CLONE, src_fd);
#else
(void) dest_fd;
(void) src_fd;
errno = ENOTSUP;
return -1;
#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 */
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
static void
copy_attr_error (struct error_context *ctx ATTRIBUTE_UNUSED,
char const *fmt, ...)
{
int err = errno;
va_list ap;
if (!errno_unsupported (errno))
{
/* use verror module to print error message */
va_start (ap, fmt);
verror (0, err, fmt, ap);
va_end (ap);
}
}
static void
copy_attr_allerror (struct error_context *ctx ATTRIBUTE_UNUSED,
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 (struct error_context *ctx ATTRIBUTE_UNUSED, char const *str)
{
return quote (str);
}
static void
copy_attr_free (struct error_context *ctx ATTRIBUTE_UNUSED,
char const *str ATTRIBUTE_UNUSED)
{
}
static bool
copy_attr_by_fd (char const *src_path, int src_fd,
char const *dst_path, int dst_fd, const struct cp_options *x)
{
struct error_context ctx =
{
.error = x->require_preserve_xattr ? copy_attr_allerror : copy_attr_error,
.quote = copy_attr_quote,
.quote_free = copy_attr_free
};
return 0 == attr_copy_fd (src_path, src_fd, dst_path, dst_fd, 0,
(x->reduce_diagnostics
&& !x->require_preserve_xattr)? NULL : &ctx);
}
static bool
copy_attr_by_name (char const *src_path, char const *dst_path,
const struct cp_options *x)
{
struct error_context ctx =
{
.error = x->require_preserve_xattr ? copy_attr_allerror : copy_attr_error,
.quote = copy_attr_quote,
.quote_free = copy_attr_free
};
return 0 == attr_copy_file (src_path, dst_path, 0,
(x-> reduce_diagnostics
&& !x->require_preserve_xattr) ? NULL : &ctx);
}
#else /* USE_XATTR */
static bool
copy_attr_by_fd (char const *src_path ATTRIBUTE_UNUSED,
int src_fd ATTRIBUTE_UNUSED,
char const *dst_path ATTRIBUTE_UNUSED,
int dst_fd ATTRIBUTE_UNUSED,
const struct cp_options *x ATTRIBUTE_UNUSED)
{
return true;
}
static bool
copy_attr_by_name (char const *src_path ATTRIBUTE_UNUSED,
char const *dst_path ATTRIBUTE_UNUSED,
const struct cp_options *x ATTRIBUTE_UNUSED)
{
return true;
}
#endif /* USE_XATTR */
/* Read the contents of the directory SRC_NAME_IN, and recursively
copy the contents to DST_NAME_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
FIRST_DIR_CREATED_PER_COMMAND_LINE_ARG FIXME
(or the same as) DST_NAME_IN; otherwise, clear it.
Return true if successful. */
static bool
copy_dir (char const *src_name_in, char const *dst_name_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);
if (name_space == NULL)
{
/* This diagnostic is a bit vague because savedir can fail in
several different ways. */
error (0, errno, _("cannot access %s"), quote (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;
namep = name_space;
while (*namep != '\0')
{
bool local_copy_into_self;
char *src_name = file_name_concat (src_name_in, namep, NULL);
char *dst_name = file_name_concat (dst_name_in, namep, NULL);
ok &= copy_internal (src_name, dst_name, new_dst, src_sb->st_dev,
ancestors, &non_command_line_options, false,
first_dir_created_per_command_line_arg,
&local_copy_into_self, NULL);
*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;
namep += strlen (namep) + 1;
}
free (name_space);
return ok;
}
/* 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 instead; for
safety prefer lchown if the system supports it since no
symbolic links should be involved. DEST_DESC must
refer to the same file as DEST_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 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"), quote (dst_name));
return -x->require_preserve;
}
}
if (HAVE_FCHOWN && dest_desc != -1)
{
if (fchown (dest_desc, uid, gid) == 0)
return 1;
if (errno == EPERM || errno == EINVAL)
{
/* We've failed to set *both*. Now, try to set just the group
ID, but ignore any failure here, and don't change errno. */
int saved_errno = errno;
ignore_value (fchown (dest_desc, -1, gid));
errno = saved_errno;
}
}
else
{
if (lchown (dst_name, uid, gid) == 0)
return 1;
if (errno == EPERM || errno == EINVAL)
{
/* We've failed to set *both*. Now, try to set just the group
ID, but ignore any failure here, and don't change errno. */
int saved_errno = errno;
ignore_value (lchown (dst_name, -1, gid));
errno = saved_errno;
}
}
if (! chown_failure_ok (x))
{
error (0, errno, _("failed to preserve ownership for %s"),
quote (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
DEST_NAME if defined. */
static void
set_author (const char *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"), quote (dst_name));
else
{
error_t err = file_chauthor (file, src_sb->st_author);
if (err)
error (0, err, _("failed to preserve authorship for %s"),
quote (dst_name));
mach_port_deallocate (mach_task_self (), file);
}
#else
(void) dst_name;
(void) dest_desc;
(void) src_sb;
#endif
}
/* Change the file mode bits of the file identified by DESC or NAME to MODE.
Use DESC if DESC is valid and fchmod is available, NAME otherwise. */
static int
fchmod_or_lchmod (int desc, char const *name, mode_t mode)
{
#if HAVE_FCHMOD
if (0 <= desc)
return fchmod (desc, mode);
#endif
return lchmod (name, mode);
}
/* Copy a regular file from SRC_NAME to DST_NAME.
If the source file contains holes, copies holes and blocks of zeros
in the source file as holes in the destination file.
(Holes are read as zeroes by the `read' system call.)
When creating the destination, use DST_MODE & ~OMITTED_PERMISSIONS
as the third argument in the call to open, adding
OMITTED_PERMISSIONS after copying as needed.
X provides many option settings.
Return true if successful.
*NEW_DST is as in copy_internal.
SRC_SB is the result of calling XSTAT (aka stat) on SRC_NAME. */
static bool
copy_reg (char const *src_name, char const *dst_name,
const struct cp_options *x,
mode_t dst_mode, mode_t omitted_permissions, bool *new_dst,
struct stat const *src_sb)
{
char *buf;
char *buf_alloc = NULL;
char *name_alloc = NULL;
int dest_desc;
int dest_errno;
int source_desc;
mode_t src_mode = src_sb->st_mode;
struct stat sb;
struct stat src_open_sb;
bool return_val = true;
bool data_copy_required = true;
source_desc = open (src_name,
(O_RDONLY | O_BINARY
| (x->dereference == DEREF_NEVER ? O_NOFOLLOW : 0)));
if (source_desc < 0)
{
error (0, errno, _("cannot open %s for reading"), quote (src_name));
return false;
}
if (fstat (source_desc, &src_open_sb) != 0)
{
error (0, errno, _("cannot fstat %s"), quote (src_name));
return_val = false;
goto close_src_desc;
}
/* Compare the source dev/ino from the open file to the incoming,
saved ones obtained via a previous call to stat. */
if (! SAME_INODE (*src_sb, src_open_sb))
{
error (0, 0,
_("skipping file %s, as it was replaced while being copied"),
quote (src_name));
return_val = false;
goto close_src_desc;
}
/* The semantics of the following open calls are mandated
by the specs for both cp and mv. */
if (! *new_dst)
{
dest_desc = open (dst_name, O_WRONLY | O_TRUNC | O_BINARY);
dest_errno = errno;
/* When using cp --preserve=context to copy to an existing destination,
use the default context rather than that of the source. Why?
1) the src context may prohibit writing, and
2) because it's more consistent to use the same context
that is used when the destination file doesn't already exist. */
if (x->preserve_security_context && 0 <= dest_desc)
{
security_context_t con = NULL;
if (getfscreatecon (&con) < 0)
{
if (x->require_preserve_context ||
(!x->reduce_diagnostics && !errno_unsupported (errno)))
error (0, errno, _("failed to get file system create context"));
if (x->require_preserve_context)
{
return_val = false;
goto close_src_and_dst_desc;
}
}
if (con)
{
if (fsetfilecon (dest_desc, con) < 0)
{
if (x->require_preserve_context ||
(!x->reduce_diagnostics && !errno_unsupported (errno)))
error (0, errno,
_("failed to set the security context of %s to %s"),
quote_n (0, dst_name), quote_n (1, con));
if (x->require_preserve_context)
{
return_val = false;
freecon (con);
goto close_src_and_dst_desc;
}
}
freecon (con);
}
}
if (dest_desc < 0 && x->unlink_dest_after_failed_open)
{
if (unlink (dst_name) != 0)
{
error (0, errno, _("cannot remove %s"), quote (dst_name));
return_val = false;
goto close_src_desc;
}
if (x->verbose)
printf (_("removed %s\n"), quote (dst_name));
/* Tell caller that the destination file was unlinked. */
*new_dst = true;
}
}
if (*new_dst)
{
int open_flags = O_WRONLY | O_CREAT | O_BINARY;
dest_desc = open (dst_name, open_flags | O_EXCL,
dst_mode & ~omitted_permissions);
dest_errno = errno;
/* When trying to copy through a dangling destination symlink,
the above open fails with EEXIST. If that happens, and
lstat'ing the DST_NAME shows that it is a symlink, then we
have a problem: trying to resolve this dangling symlink to
a directory/destination-entry pair is fundamentally racy,
so punt. If x->open_dangling_dest_symlink is set (cp sets
that when POSIXLY_CORRECT is set in the environment), simply
call open again, but without O_EXCL (potentially dangerous).
If not, fail with a diagnostic. These shenanigans are necessary
only when copying, i.e., not in move_mode. */
if (dest_desc < 0 && dest_errno == EEXIST && ! x->move_mode)
{
struct stat dangling_link_sb;
if (lstat (dst_name, &dangling_link_sb) == 0
&& S_ISLNK (dangling_link_sb.st_mode))
{
if (x->open_dangling_dest_symlink)
{
dest_desc = open (dst_name, open_flags,
dst_mode & ~omitted_permissions);
dest_errno = errno;
}
else
{
error (0, 0, _("not writing through dangling symlink %s"),
quote (dst_name));
return_val = false;
goto close_src_desc;
}
}
}
}
else
omitted_permissions = 0;
if (dest_desc < 0)
{
error (0, dest_errno, _("cannot create regular file %s"),
quote (dst_name));
return_val = false;
goto close_src_desc;
}
if (fstat (dest_desc, &sb) != 0)
{
error (0, errno, _("cannot fstat %s"), quote (dst_name));
return_val = false;
goto close_src_and_dst_desc;
}
if (x->reflink_mode)
{
bool clone_ok = clone_file (dest_desc, source_desc) == 0;
if (clone_ok || x->reflink_mode == REFLINK_ALWAYS)
{
if (!clone_ok)
{
error (0, errno, _("failed to clone %s"), quote (dst_name));
return_val = false;
goto close_src_and_dst_desc;
}
data_copy_required = false;
}
}
if (data_copy_required)
{
typedef uintptr_t word;
off_t n_read_total = 0;
/* Choose a suitable buffer size; it may be adjusted later. */
size_t buf_alignment = lcm (getpagesize (), sizeof (word));
size_t buf_alignment_slop = sizeof (word) + buf_alignment - 1;
size_t buf_size = io_blksize (sb);
/* Deal with sparse files. */
bool last_write_made_hole = false;
bool make_holes = false;
if (S_ISREG (sb.st_mode))
{
/* Even with --sparse=always, try to create holes only
if the destination is a regular file. */
if (x->sparse_mode == SPARSE_ALWAYS)
make_holes = true;
#if HAVE_STRUCT_STAT_ST_BLOCKS
/* Use a heuristic to determine whether SRC_NAME contains any sparse
blocks. If the file has fewer blocks than would normally be
needed for a file of its size, then at least one of the blocks in
the file is a hole. */
if (x->sparse_mode == SPARSE_AUTO && S_ISREG (src_open_sb.st_mode)
&& ST_NBLOCKS (src_open_sb) < src_open_sb.st_size / ST_NBLOCKSIZE)
make_holes = true;
#endif
}
/* If not making a sparse file, try to use a more-efficient
buffer size. */
if (! make_holes)
{
/* Compute the least common multiple of the input and output
buffer sizes, adjusting for outlandish values. */
size_t blcm_max = MIN (SIZE_MAX, SSIZE_MAX) - buf_alignment_slop;
size_t blcm = buffer_lcm (io_blksize (src_open_sb), buf_size,
blcm_max);
/* Do not bother with a buffer larger than the input file, plus one
byte to make sure the file has not grown while reading it. */
if (S_ISREG (src_open_sb.st_mode) && src_open_sb.st_size < buf_size)
buf_size = src_open_sb.st_size + 1;
/* However, stick with a block size that is a positive multiple of
blcm, overriding the above adjustments. Watch out for
overflow. */
buf_size += blcm - 1;
buf_size -= buf_size % blcm;
if (buf_size == 0 || blcm_max < buf_size)
buf_size = blcm;
}
/* Make a buffer with space for a sentinel at the end. */
buf_alloc = xmalloc (buf_size + buf_alignment_slop);
buf = ptr_align (buf_alloc, buf_alignment);
for (;;)
{
word *wp = NULL;
ssize_t n_read = read (source_desc, buf, buf_size);
if (n_read < 0)
{
#ifdef EINTR
if (errno == EINTR)
continue;
#endif
error (0, errno, _("reading %s"), quote (src_name));
return_val = false;
goto close_src_and_dst_desc;
}
if (n_read == 0)
break;
n_read_total += n_read;
if (make_holes)
{
char *cp;
/* Sentinel to stop loop. */
buf[n_read] = '\1';
#ifdef lint
/* Usually, buf[n_read] is not the byte just before a "word"
(aka uintptr_t) boundary. In that case, the word-oriented
test below (*wp++ == 0) would read some uninitialized bytes
after the sentinel. To avoid false-positive reports about
this condition (e.g., from a tool like valgrind), set the
remaining bytes -- to any value. */
memset (buf + n_read + 1, 0, sizeof (word) - 1);
#endif
/* Find first nonzero *word*, or the word with the sentinel. */
wp = (word *) buf;
while (*wp++ == 0)
continue;
/* Find the first nonzero *byte*, or the sentinel. */
cp = (char *) (wp - 1);
while (*cp++ == 0)
continue;
if (cp <= buf + n_read)
/* Clear to indicate that a normal write is needed. */
wp = NULL;
else
{
/* We found the sentinel, so the whole input block was zero.
Make a hole. */
if (lseek (dest_desc, n_read, SEEK_CUR) < 0)
{
error (0, errno, _("cannot lseek %s"), quote (dst_name));
return_val = false;
goto close_src_and_dst_desc;
}
last_write_made_hole = true;
}
}
if (!wp)
{
size_t n = n_read;
if (full_write (dest_desc, buf, n) != n)
{
error (0, errno, _("writing %s"), quote (dst_name));
return_val = false;
goto close_src_and_dst_desc;
}
last_write_made_hole = false;
/* It is tempting to return 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 with linux kernels from at least 2.6.9 .. 2.6.29. */
}
}
/* If the file ends with a `hole', we need to do something to record
the length of the file. On modern systems, calling ftruncate does
the job. On systems without native ftruncate support, we have to
write a byte at the ending position. Otherwise the kernel would
truncate the file at the end of the last write operation. */
if (last_write_made_hole)
{
if (ftruncate (dest_desc, n_read_total) < 0)
{
error (0, errno, _("truncating %s"), quote (dst_name));
return_val = false;
goto close_src_and_dst_desc;
}
}
}
if (x->preserve_timestamps)
{
struct timespec timespec[2];
timespec[0] = get_stat_atime (src_sb);
timespec[1] = get_stat_mtime (src_sb);
if (gl_futimens (dest_desc, dst_name, timespec) != 0)
{
error (0, errno, _("preserving times for %s"), quote (dst_name));
if (x->require_preserve)
{
return_val = false;
goto close_src_and_dst_desc;
}
}
}
/* Set ownership before xattrs as changing owners will
clear capabilities. */
if (x->preserve_ownership && ! SAME_OWNER_AND_GROUP (*src_sb, sb))
{
switch (set_owner (x, dst_name, dest_desc, src_sb, *new_dst, &sb))
{
case -1:
return_val = false;
goto close_src_and_dst_desc;
case 0:
src_mode &= ~ (S_ISUID | S_ISGID | S_ISVTX);
break;
}
}
/* To allow copying xattrs on read-only files, temporarily chmod u+rw.
This workaround is required as an inode permission check is done
by xattr_permission() in fs/xattr.c of the GNU/Linux kernel tree. */
if (x->preserve_xattr)
{
bool access_changed = false;
if (!(sb.st_mode & S_IWUSR) && geteuid () != 0)
access_changed = fchmod_or_lchmod (dest_desc, dst_name, 0600) == 0;
if (!copy_attr_by_fd (src_name, source_desc, dst_name, dest_desc, x)
&& x->require_preserve_xattr)
return_val = false;
if (access_changed)
fchmod_or_lchmod (dest_desc, dst_name, dst_mode & ~omitted_permissions);
}
set_author (dst_name, dest_desc, src_sb);
if (x->preserve_mode || x->move_mode)
{
if (copy_acl (src_name, source_desc, dst_name, dest_desc, src_mode) != 0
&& x->require_preserve)
return_val = false;
}
else if (x->set_mode)
{
if (set_acl (dst_name, dest_desc, x->mode) != 0)
return_val = false;
}
else if (omitted_permissions)
{
omitted_permissions &= ~ cached_umask ();
if (omitted_permissions
&& fchmod_or_lchmod (dest_desc, dst_name, dst_mode) != 0)
{
error (0, errno, _("preserving permissions for %s"),
quote (dst_name));
if (x->require_preserve)
return_val = false;
}
}
close_src_and_dst_desc:
if (close (dest_desc) < 0)
{
error (0, errno, _("closing %s"), quote (dst_name));
return_val = false;
}
close_src_desc:
if (close (source_desc) < 0)
{
error (0, errno, _("closing %s"), quote (src_name));
return_val = false;
}
free (buf_alloc);
free (name_alloc);
return return_val;
}
/* Return true if it's ok that the source and destination
files are the `same' by some measure. The goal is to avoid
making the `copy' operation remove both copies of the file
in that case, while still allowing the user to e.g., move or
copy a regular file onto a symlink that points to it.
Try to minimize the cost of this function in the common case.
Set *RETURN_NOW if we've determined that the caller has no more
work to do and should return successfully, right away.
Set *UNLINK_SRC if we've determined that the caller wants to do
`rename (a, b)' where `a' and `b' are distinct hard links to the same
file. In that case, the caller should try to unlink `a' and then return
successfully. Ideally, we wouldn't have to do that, and we'd be
able to rely on rename to remove the source file. However, POSIX
mistakenly requires that such a rename call do *nothing* and return
successfully. */
static bool
same_file_ok (char const *src_name, struct stat const *src_sb,
char const *dst_name, struct stat const *dst_sb,
const struct cp_options *x, bool *return_now, bool *unlink_src)
{
const struct stat *src_sb_link;
const struct stat *dst_sb_link;
struct stat tmp_dst_sb;
struct stat tmp_src_sb;
bool same_link;
bool same = SAME_INODE (*src_sb, *dst_sb);
*return_now = false;
*unlink_src = false;
/* FIXME: this should (at the very least) be moved into the following
if-block. More likely, it should be removed, because it inhibits
making backups. But removing it will result in a change in behavior
that will probably have to be documented -- and tests will have to
be updated. */
if (same && x->hard_link)
{
*return_now = true;
return true;
}
if (x->dereference == DEREF_NEVER)
{
same_link = same;
/* If both the source and destination files are symlinks (and we'll
know this here IFF preserving symlinks), then it's ok -- as long
as they are distinct. */
if (S_ISLNK (src_sb->st_mode) && S_ISLNK (dst_sb->st_mode))
return ! same_name (src_name, dst_name);
src_sb_link = src_sb;
dst_sb_link = dst_sb;
}
else
{
if (!same)
return true;
if (lstat (dst_name, &tmp_dst_sb) != 0
|| lstat (src_name, &tmp_src_sb) != 0)
return true;
src_sb_link = &tmp_src_sb;
dst_sb_link = &tmp_dst_sb;
same_link = SAME_INODE (*src_sb_link, *dst_sb_link);
/* If both are symlinks, then it's ok, but only if the destination
will be unlinked before being opened. This is like the test
above, but with the addition of the unlink_dest_before_opening
conjunct because otherwise, with two symlinks to the same target,
we'd end up truncating the source file. */
if (S_ISLNK (src_sb_link->st_mode) && S_ISLNK (dst_sb_link->st_mode)
&& x->unlink_dest_before_opening)
return true;
}
/* The backup code ensures there's a copy, so it's usually ok to
remove any destination file. One exception is when both
source and destination are the same directory entry. In that
case, moving the destination file aside (in making the backup)
would also rename the source file and result in an error. */
if (x->backup_type != no_backups)
{
if (!same_link)
{
/* In copy mode when dereferencing symlinks, if the source is a
symlink and the dest is not, then backing up the destination
(moving it aside) would make it a dangling symlink, and the
subsequent attempt to open it in copy_reg would fail with