-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcopyfile.c
5062 lines (4566 loc) · 134 KB
/
copyfile.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
/*
* Copyright (c) 2004-2022 Apple, Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
#include <err.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/acl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <syslog.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/errno.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/xattr.h>
#include <sys/attr.h>
#include <sys/syscall.h>
#include <sys/param.h>
#include <sys/mount.h>
#include <sys/acl.h>
#include <libkern/OSByteOrder.h>
#include <membership.h>
#include <fts.h>
#include <libgen.h>
#include <sys/clonefile.h>
#include <System/sys/fsctl.h>
#include <System/sys/content_protection.h>
#ifdef VOL_CAP_FMT_DECMPFS_COMPRESSION
# include <Kernel/sys/decmpfs.h>
#endif
#include <TargetConditionals.h>
#if !TARGET_OS_IPHONE
#include <quarantine.h>
#define XATTR_QUARANTINE_NAME qtn_xattr_name
#else /* TARGET_OS_IPHONE */
#define qtn_file_t void *
#define QTN_SERIALIZED_DATA_MAX 0
static void * qtn_file_alloc(void) { return NULL; }
static int qtn_file_init_with_fd(__unused void *x, __unused int y) { return -1; }
static int qtn_file_init_with_path(__unused void *x, __unused const char *path) { return -1; }
static int qtn_file_init_with_data(__unused void *x, __unused const void *data, __unused size_t len) { return -1; }
static void qtn_file_free(__unused void *x) { return; }
static int qtn_file_apply_to_fd(__unused void *x, __unused int y) { return 0; }
static char *qtn_error(__unused int x) { return NULL; }
static int qtn_file_to_data(__unused void *x, __unused char *y, __unused size_t *z) { return -1; }
static void *qtn_file_clone(__unused void *x) { return NULL; }
static uint32_t qtn_file_get_flags(__unused void *x) { return 0; }
static int qtn_file_set_flags(__unused void *x, __unused uint32_t flags) { return 0; }
#define XATTR_QUARANTINE_NAME "figgledidiggledy"
#define QTN_FLAG_DO_NOT_TRANSLOCATE 0
#endif /* TARGET_OS_IPHONE */
#include "copyfile.h"
#include "copyfile_private.h"
#include "xattr_flags.h"
#define XATTR_ROOT_INSTALLED_NAME "com.apple.root.installed"
enum cfInternalFlags {
cfDelayAce = 1 << 0, /* set if ACE shouldn't be set until post-order traversal */
cfMakeFileInvisible = 1 << 1, /* set if kFinderInvisibleMask is on src */
cfSawDecmpEA = 1 << 2, /* set if we've seen a com.apple.decmpfs xattr */
cfSrcProtSupportValid = 1 << 3, /* set if cfSrcSupportsCProtect is valid */
cfSrcSupportsCProtect = 1 << 4, /* set if src supports MNT_CPROTECT */
cfDstProtSupportValid = 1 << 5, /* set if cfDstSupportsCProtect is valid */
cfDstSupportsCProtect = 1 << 6, /* set if dst supports MNT_CPROTECT */
};
#define COPYFILE_MNT_CPROTECT_MASK (cfSrcProtSupportValid | cfSrcSupportsCProtect | cfDstProtSupportValid | cfDstSupportsCProtect)
/*
* The state structure keeps track of
* the source filename, the destination filename, their
* associated file-descriptors, the stat information for the
* source file, the security information for the source file,
* the flags passed in for the copy, a pointer to place statistics
* (not currently implemented), debug flags, buffer sizes (if specified),
* and other helpful state information.
*/
struct _copyfile_state
{
char *src;
char *dst;
int src_fd;
int dst_fd;
struct stat sb;
filesec_t fsec;
copyfile_flags_t flags;
unsigned int internal_flags;
void *stats;
uint32_t debug;
copyfile_callback_t statuscb;
void *ctx;
qtn_file_t qinfo; /* Quarantine information -- probably NULL */
filesec_t original_fsec;
filesec_t permissive_fsec;
off_t totalCopied;
int err;
char *xattr_name;
xattr_operation_intent_t copyIntent;
bool was_cloned;
bool set_dst_perms;
uint32_t src_bsize;
uint32_t dst_bsize;
};
#define GET_PROT_CLASS(fd) fcntl((fd), F_GETPROTECTIONCLASS)
#define SET_PROT_CLASS(fd, prot_class) fcntl((fd), F_SETPROTECTIONCLASS, (prot_class))
struct acl_entry {
u_int32_t ae_magic;
#define _ACL_ENTRY_MAGIC 0xac1ac101
u_int32_t ae_tag;
guid_t ae_applicable;
u_int32_t ae_flags;
u_int32_t ae_perms;
};
#define PACE(ace) \
do { \
struct acl_entry *__t = (struct acl_entry*)(ace); \
fprintf(stderr, "%s(%d): " #ace " = { flags = %#x, perms = %#x }\n", __FUNCTION__, __LINE__, __t->ae_flags, __t->ae_perms); \
} while (0)
#define PACL(ace) \
do { \
ssize_t __l; char *__cp = acl_to_text(ace, &__l); \
fprintf(stderr, "%s(%d): " #ace " = %s\n", __FUNCTION__, __LINE__, __cp ? __cp : "(null)"); \
} while (0)
static int
acl_compare_permset_np(acl_permset_t p1, acl_permset_t p2)
{
struct pm { u_int32_t ap_perms; } *ps1, *ps2;
ps1 = (struct pm*) p1;
ps2 = (struct pm*) p2;
return ((ps1->ap_perms == ps2->ap_perms) ? 1 : 0);
}
static int
doesdecmpfs(int fd) {
#ifdef DECMPFS_XATTR_NAME
int rv;
struct attrlist attrs;
char volroot[MAXPATHLEN + 1];
struct statfs sfs;
struct {
uint32_t length;
vol_capabilities_attr_t volAttrs;
} volattrs;
rv = fstatfs(fd, &sfs);
if (rv != 0) {
return 0;
}
strlcpy(volroot, sfs.f_mntonname, sizeof(volroot));
memset(&attrs, 0, sizeof(attrs));
attrs.bitmapcount = ATTR_BIT_MAP_COUNT;
attrs.volattr = ATTR_VOL_CAPABILITIES;
rv = getattrlist(volroot, &attrs, &volattrs, sizeof(volattrs), 0);
if (rv != -1 &&
(volattrs.volAttrs.capabilities[VOL_CAPABILITIES_FORMAT] & VOL_CAP_FMT_DECMPFS_COMPRESSION) &&
(volattrs.volAttrs.valid[VOL_CAPABILITIES_FORMAT] & VOL_CAP_FMT_DECMPFS_COMPRESSION)) {
return 1;
}
#endif
return 0;
}
static int
does_copy_protection(int fd)
{
struct statfs sfs;
if (fstatfs(fd, &sfs) == -1)
return -1;
return ((sfs.f_flags & MNT_CPROTECT) == MNT_CPROTECT);
}
static bool
path_does_copy_protection(const char *path)
{
struct statfs sfs;
if (statfs(path, &sfs) == -1) {
char parent_path[MAXPATHLEN];
if (errno != ENOENT)
return false;
// If the path doesn't exist,
// try to get its parent path and re-attempt the statfs().
if (dirname_r(path, parent_path) == NULL)
return false;
if (statfs(parent_path, &sfs) == -1)
return false;
}
return ((sfs.f_flags & MNT_CPROTECT) == MNT_CPROTECT);
}
static int
do_copy_protected_open(const char *path, int flags, int class, int dpflags, int mode)
{
// The passed-in protection class is meaningful, so use open_dprotected_np().
if (path_does_copy_protection(path)) {
return open_dprotected_np(path, flags, class, dpflags, mode);
}
// Fall-back to regular open().
return open(path, flags, mode);
}
static void
sort_xattrname_list(void *start, size_t length)
{
char **ptrs = NULL;
int nel;
char *tmp;
int indx = 0;
/* If it's not a proper C string at the end, don't do anything */
if (((char*)start)[length] != 0)
return;
/*
* In order to sort the list of names, we need to
* make a list of pointers to strings. To do that,
* we need to run through the buffer, and find the
* beginnings of strings.
*/
nel = 10; // Most files don't have many EAs
ptrs = (char**)calloc(nel, sizeof(char*));
if (ptrs == NULL)
goto done;
#ifdef DEBUG
{
char *curPtr = start;
while (curPtr < (char*)start + length) {
printf("%s\n", curPtr);
curPtr += strlen(curPtr) + 1;
}
}
#endif
tmp = ptrs[indx++] = (char*)start;
while ((tmp = memchr(tmp, 0, ((char*)start + length) - tmp))) {
if (indx == nel) {
nel += 10;
ptrs = realloc(ptrs, sizeof(char**) * nel);
if (ptrs == NULL)
goto done;
}
ptrs[indx++] = ++tmp;
}
#ifdef DEBUG
printf("Unsorted:\n");
for (nel = 0; nel < indx-1; nel++) {
printf("\tEA %d = `%s'\n", nel, ptrs[nel]);
}
#endif
qsort_b(ptrs, indx-1, sizeof(char*), ^(const void *left, const void *right) {
int rv;
char *lstr = *(char**)left, *rstr = *(char**)right;
rv = strcmp(lstr, rstr);
return rv;
});
#ifdef DEBUG
printf("Sorted:\n");
for (nel = 0; nel < indx-1; nel++) {
printf("\tEA %d = `%s'\n", nel, ptrs[nel]);
}
#endif
/*
* Now that it's sorted, we need to make a copy, so we can
* move the strings around into the new order. Then we
* copy that on top of the old buffer, and we're done.
*/
char *copy = malloc(length);
if (copy) {
int i;
char *curPtr = copy;
for (i = 0; i < indx-1; i++) {
size_t len = strlen(ptrs[i]);
memcpy(curPtr, ptrs[i], len+1);
curPtr += len+1;
}
memcpy(start, copy, length);
free(copy);
}
done:
if (ptrs)
free(ptrs);
return;
}
/*
* Internally, the process is broken into a series of
* private functions.
*/
static int copyfile_open (copyfile_state_t);
static int copyfile_close (copyfile_state_t);
static int copyfile_data (copyfile_state_t);
static int copyfile_stat (copyfile_state_t);
static int copyfile_security (copyfile_state_t);
static int copyfile_xattr (copyfile_state_t);
static int copyfile_pack (copyfile_state_t);
static int copyfile_unpack (copyfile_state_t);
static copyfile_flags_t copyfile_check (copyfile_state_t);
static filesec_t copyfile_fix_perms(copyfile_state_t, filesec_t *);
static int copyfile_preamble(copyfile_state_t *s, copyfile_flags_t flags);
static int copyfile_internal(copyfile_state_t state, copyfile_flags_t flags);
static int copyfile_unset_posix_fsec(filesec_t);
static int copyfile_quarantine(copyfile_state_t);
#define COPYFILE_DEBUG (1<<31)
#define COPYFILE_DEBUG_VAR "COPYFILE_DEBUG"
// These macros preserve the value of errno.
#ifndef _COPYFILE_TEST
# define copyfile_warn(str, ...) \
do { \
errno_t _errsv = errno; \
syslog(LOG_WARNING, str ": %m", ## __VA_ARGS__); \
errno = _errsv; \
} while (0)
# define copyfile_debug(d, str, ...) \
do { \
if (s && (d <= s->debug)) {\
errno_t _errsv = errno; \
syslog(LOG_DEBUG, "%s:%d:%s() " str "\n", __FILE__, __LINE__ , __FUNCTION__, ## __VA_ARGS__); \
errno = _errsv; \
} \
} while (0)
#else
#define copyfile_warn(str, ...) \
do { \
errno_t _errsv = errno; \
fprintf(stderr, "%s:%d:%s() " str ": %s\n", __FILE__, __LINE__ , __FUNCTION__, ## __VA_ARGS__, (errno) ? strerror(errno) : ""); \
errno = _errsv; \
} while (0)
# define copyfile_debug(d, str, ...) \
do { \
if (s && (d <= s->debug)) {\
errno_t _errsv = errno; \
fprintf(stderr, "%s:%d:%s() " str "\n", __FILE__, __LINE__ , __FUNCTION__, ## __VA_ARGS__); \
errno = _errsv; \
} \
} while(0)
#endif
static int copyfile_quarantine(copyfile_state_t s)
{
int rv = 0;
if (s->qinfo == NULL)
{
int error;
s->qinfo = qtn_file_alloc();
if (s->qinfo == NULL)
{
rv = -1;
goto done;
}
if ((error = qtn_file_init_with_fd(s->qinfo, s->src_fd)) != 0)
{
qtn_file_free(s->qinfo);
s->qinfo = NULL;
rv = -1;
goto done;
}
}
done:
return rv;
}
static int
add_uberace(acl_t *acl)
{
acl_entry_t entry;
acl_permset_t permset;
uuid_t qual;
if (mbr_uid_to_uuid(getuid(), qual) != 0)
goto error_exit;
/*
* First, we create an entry, and give it the special name
* of ACL_FIRST_ENTRY, thus guaranteeing it will be first.
* After that, we clear out all the permissions in it, and
* add three permissions: WRITE_DATA, WRITE_ATTRIBUTES, and
* WRITE_EXTATTRIBUTES. We put these into an ACE that allows
* the functionality, and put this into the ACL.
*/
if (acl_create_entry_np(acl, &entry, ACL_FIRST_ENTRY) == -1)
goto error_exit;
if (acl_get_permset(entry, &permset) == -1) {
copyfile_warn("acl_get_permset");
goto error_exit;
}
if (acl_clear_perms(permset) == -1) {
copyfile_warn("acl_clear_permset");
goto error_exit;
}
if (acl_add_perm(permset, ACL_WRITE_DATA) == -1) {
copyfile_warn("add ACL_WRITE_DATA");
goto error_exit;
}
if (acl_add_perm(permset, ACL_WRITE_ATTRIBUTES) == -1) {
copyfile_warn("add ACL_WRITE_ATTRIBUTES");
goto error_exit;
}
if (acl_add_perm(permset, ACL_WRITE_EXTATTRIBUTES) == -1) {
copyfile_warn("add ACL_WRITE_EXTATTRIBUTES");
goto error_exit;
}
if (acl_add_perm(permset, ACL_APPEND_DATA) == -1) {
copyfile_warn("add ACL_APPEND_DATA");
goto error_exit;
}
if (acl_add_perm(permset, ACL_WRITE_SECURITY) == -1) {
copyfile_warn("add ACL_WRITE_SECURITY");
goto error_exit;
}
if (acl_set_tag_type(entry, ACL_EXTENDED_ALLOW) == -1) {
copyfile_warn("set ACL_EXTENDED_ALLOW");
goto error_exit;
}
if(acl_set_permset(entry, permset) == -1) {
copyfile_warn("acl_set_permset");
goto error_exit;
}
if(acl_set_qualifier(entry, qual) == -1) {
copyfile_warn("acl_set_qualifier");
goto error_exit;
}
return 0;
error_exit:
return -1;
}
static int
is_uberace(acl_entry_t ace)
{
int retval = 0;
acl_permset_t perms, tperms;
acl_t tacl;
acl_entry_t tentry;
acl_tag_t tag;
guid_t *qual = NULL;
uuid_t myuuid;
// Who am I, and who is the ACE for?
mbr_uid_to_uuid(geteuid(), myuuid);
qual = (guid_t*)acl_get_qualifier(ace);
// Need to create a temporary acl, so I can get the uberace template.
tacl = acl_init(1);
if (tacl == NULL) {
goto done;
}
add_uberace(&tacl);
if (acl_get_entry(tacl, ACL_FIRST_ENTRY, &tentry) != 0) {
goto done;
}
acl_get_permset(tentry, &tperms);
// Now I need to get
acl_get_tag_type(ace, &tag);
acl_get_permset(ace, &perms);
if (tag == ACL_EXTENDED_ALLOW &&
(memcmp(qual, myuuid, sizeof(myuuid)) == 0) &&
acl_compare_permset_np(tperms, perms))
retval = 1;
done:
if (qual)
acl_free(qual);
if (tacl)
acl_free(tacl);
return retval;
}
static void
remove_uberace(int fd, struct stat *sbuf)
{
filesec_t fsec = NULL;
acl_t acl = NULL;
acl_entry_t entry;
struct stat sb;
fsec = filesec_init();
if (fsec == NULL) {
goto noacl;
}
if (fstatx_np(fd, &sb, fsec) != 0) {
if (errno == ENOTSUP)
goto noacl;
goto done;
}
if (filesec_get_property(fsec, FILESEC_ACL, &acl) != 0) {
goto done;
}
if (acl_get_entry(acl, ACL_FIRST_ENTRY, &entry) == 0) {
if (is_uberace(entry))
{
mode_t m = sbuf->st_mode & ~S_IFMT;
if (acl_delete_entry(acl, entry) != 0 ||
filesec_set_property(fsec, FILESEC_ACL, &acl) != 0 ||
filesec_set_property(fsec, FILESEC_MODE, &m) != 0 ||
fchmodx_np(fd, fsec) != 0)
goto noacl;
}
}
done:
if (acl)
acl_free(acl);
if (fsec)
filesec_free(fsec);
return;
noacl:
fchmod(fd, sbuf->st_mode & ~S_IFMT);
goto done;
}
static void
reset_security(copyfile_state_t s)
{
/* If we haven't reset the file security information
* (COPYFILE_SECURITY is not set in flags)
* restore back the permissions the file had originally
*
* One of the reasons this seems so complicated is that
* it is partially at odds with copyfile_security().
*
* Simplisticly, we are simply trying to make sure we
* only copy what was requested, and that we don't stomp
* on what wasn't requested.
*/
if (s->dst_fd > -1) {
struct stat sbuf;
if (s->src_fd > -1 && (s->flags & COPYFILE_STAT))
fstat(s->src_fd, &sbuf);
else
fstat(s->dst_fd, &sbuf);
if (!(s->internal_flags & cfDelayAce))
remove_uberace(s->dst_fd, &sbuf);
}
}
/*
* copytree -- recursively copy a hierarchy.
*
* Unlike normal copyfile(), copytree() can copy an entire hierarchy.
* Care is taken to keep the ACLs set up correctly, in addition to the
* normal copying that is done. (When copying a hierarchy, we can't
* get rid of the "allow-all-writes" ACE on a directory until we're done
* copying the *contents* of the directory.)
*
* The other big difference from copyfile (for the moment) is that copytree()
* will use a call-back function to pass along information about what is
* about to be copied, and whether or not it succeeded.
*
* copytree() is called from copyfile() -- but copytree() itself then calls
* copyfile() to copy each individual object.
*
* If COPYFILE_CLONE is passed, copytree() will clone (instead of copy)
* regular files and symbolic links found in each directory.
* Directories will still be copied normally.
*
* XXX - no effort is made to handle overlapping hierarchies at the moment.
*
*/
static int
copytree(copyfile_state_t s)
{
char *slash;
int retval = 0;
int (*sfunc)(const char *, struct stat *);
copyfile_callback_t status = NULL;
char srcisdir = 0, dstisdir = 0, dstexists = 0;
struct stat sbuf;
char *src, *dst;
const char *dstpathsep = "";
char *srcroot;
FTS *fts = NULL;
FTSENT *ftsent;
ssize_t offset = 0;
const char *paths[2] = { 0 };
unsigned int flags = 0;
int fts_flags = FTS_NOCHDIR;
dev_t last_dev = s->sb.st_dev;
if (s == NULL) {
errno = EINVAL;
retval = -1;
goto done;
}
if (s->flags & (COPYFILE_MOVE | COPYFILE_UNLINK | COPYFILE_CHECK | COPYFILE_PACK | COPYFILE_UNPACK | COPYFILE_CLONE_FORCE)) {
errno = EINVAL;
retval = -1;
goto done;
}
flags = s->flags & (COPYFILE_ALL | COPYFILE_NOFOLLOW | COPYFILE_VERBOSE | COPYFILE_EXCL | COPYFILE_CLONE | COPYFILE_DATA_SPARSE);
paths[0] = src = s->src;
dst = s->dst;
if (src == NULL || dst == NULL) {
errno = EINVAL;
retval = -1;
goto done;
}
sfunc = (flags & COPYFILE_NOFOLLOW_SRC) ? lstat : stat;
if ((sfunc)(src, &sbuf) == -1) {
retval = -1;
goto done;
}
if ((sbuf.st_mode & S_IFMT) == S_IFDIR) {
srcisdir = 1;
}
sfunc = (flags & COPYFILE_NOFOLLOW_DST) ? lstat : stat;
if ((sfunc)(dst, &sbuf) == -1) {
if (errno != ENOENT) {
retval = -1;
goto done;
}
} else {
dstexists = 1;
if ((sbuf.st_mode & S_IFMT) == S_IFDIR) {
dstisdir = 1;
}
}
srcroot = basename((char*)src);
if (srcroot == NULL) {
retval = -1;
goto done;
}
/*
* To work on as well:
* We have a few cases when copying a hierarchy:
* 1) src is a non-directory, dst is a directory;
* 2) src is a non-directory, dst is a non-directory;
* 3) src is a non-directory, dst does not exist;
* 4) src is a directory, dst is a directory;
* 5) src is a directory, dst is a non-directory;
* 6) src is a directory, dst does not exist
*
* (1) copies src to dst/basename(src).
* (2) fails if COPYFILE_EXCL is set, otherwise copies src to dst.
* (3) and (6) copy src to the name dst.
* (4) copies the contents of src to the contents of dst.
* (5) is an error.
*/
if (dstisdir) {
// copy /path/to/src to /path/to/dst/src
// Append "/" and (fts_path - strlen(basename(src))) to dst?
dstpathsep = "/";
slash = strrchr(src, '/');
if (slash == NULL)
offset = 0;
else
offset = slash - src + 1;
} else {
// copy /path/to/src to /path/to/dst
// append (fts_path + strlen(src)) to dst?
dstpathsep = "";
offset = strlen(src);
}
// COPYFILE_RECURSIVE is always done physically: see 11717978.
fts_flags |= FTS_PHYSICAL;
if (!(s->flags & (COPYFILE_NOFOLLOW_SRC|COPYFILE_CLONE))) {
// Follow 'src', even if it's a symlink, unless instructed not to
// or we're cloning, where we never follow symlinks.
fts_flags |= FTS_COMFOLLOW;
}
fts = fts_open((char * const *)paths, fts_flags, NULL);
status = s->statuscb;
while ((ftsent = fts_read(fts)) != NULL) {
int rv = 0;
char *dstfile = NULL;
int cmd = 0;
copyfile_state_t tstate = copyfile_state_alloc();
if (tstate == NULL) {
errno = ENOMEM;
retval = -1;
break;
}
tstate->statuscb = s->statuscb;
tstate->ctx = s->ctx;
if (last_dev == ftsent->fts_dev) {
tstate->internal_flags |= (s->internal_flags & COPYFILE_MNT_CPROTECT_MASK);
} else {
last_dev = ftsent->fts_dev;
}
asprintf(&dstfile, "%s%s%s", dst, dstpathsep, ftsent->fts_path + offset);
if (dstfile == NULL) {
copyfile_state_free(tstate);
errno = ENOMEM;
retval = -1;
break;
}
switch (ftsent->fts_info) {
case FTS_D:
tstate->internal_flags |= cfDelayAce;
cmd = COPYFILE_RECURSE_DIR;
break;
case FTS_SL:
case FTS_SLNONE:
case FTS_DEFAULT:
case FTS_F:
cmd = COPYFILE_RECURSE_FILE;
break;
case FTS_DP:
cmd = COPYFILE_RECURSE_DIR_CLEANUP;
break;
case FTS_DNR:
case FTS_ERR:
case FTS_NS:
case FTS_NSOK:
default:
errno = ftsent->fts_errno;
if (status) {
rv = (*status)(COPYFILE_RECURSE_ERROR, COPYFILE_ERR, tstate, ftsent->fts_path, dstfile, s->ctx);
if (rv == COPYFILE_SKIP || rv == COPYFILE_CONTINUE) {
errno = 0;
goto skipit;
}
if (rv == COPYFILE_QUIT) {
retval = -1;
goto stopit;
}
} else {
retval = -1;
goto stopit;
}
case FTS_DOT:
goto skipit;
}
if (cmd == COPYFILE_RECURSE_DIR || cmd == COPYFILE_RECURSE_FILE) {
if (status) {
rv = (*status)(cmd, COPYFILE_START, tstate, ftsent->fts_path, dstfile, s->ctx);
if (rv == COPYFILE_SKIP) {
if (cmd == COPYFILE_RECURSE_DIR) {
rv = fts_set(fts, ftsent, FTS_SKIP);
if (rv == -1) {
rv = (*status)(0, COPYFILE_ERR, tstate, ftsent->fts_path, dstfile, s->ctx);
if (rv == COPYFILE_QUIT)
retval = -1;
}
}
goto skipit;
}
if (rv == COPYFILE_QUIT) {
retval = -1; errno = 0;
goto stopit;
}
}
// Since we don't support cloning directories this code depends on copyfile()
// falling back to a regular directory copy.
int tmp_flags = (cmd == COPYFILE_RECURSE_DIR) ? (flags & ~COPYFILE_STAT) : flags;
rv = copyfile(ftsent->fts_path, dstfile, tstate, tmp_flags);
if (rv < 0) {
if (status) {
rv = (*status)(cmd, COPYFILE_ERR, tstate, ftsent->fts_path, dstfile, s->ctx);
if (rv == COPYFILE_QUIT) {
retval = -1;
goto stopit;
} else
rv = 0;
goto skipit;
} else {
retval = -1;
goto stopit;
}
}
if (status) {
rv = (*status)(cmd, COPYFILE_FINISH, tstate, ftsent->fts_path, dstfile, s->ctx);
if (rv == COPYFILE_QUIT) {
retval = -1; errno = 0;
goto stopit;
}
}
} else if (cmd == COPYFILE_RECURSE_DIR_CLEANUP) {
if (status) {
rv = (*status)(cmd, COPYFILE_START, tstate, ftsent->fts_path, dstfile, s->ctx);
if (rv == COPYFILE_QUIT) {
retval = -1; errno = 0;
goto stopit;
} else if (rv == COPYFILE_SKIP) {
rv = 0;
goto skipit;
}
}
rv = copyfile(ftsent->fts_path, dstfile, tstate, (flags & COPYFILE_NOFOLLOW) | COPYFILE_STAT);
if (rv < 0) {
if (status) {
rv = (*status)(COPYFILE_RECURSE_DIR_CLEANUP, COPYFILE_ERR, tstate, ftsent->fts_path, dstfile, s->ctx);
if (rv == COPYFILE_QUIT) {
retval = -1;
goto stopit;
} else if (rv == COPYFILE_SKIP || rv == COPYFILE_CONTINUE) {
if (rv == COPYFILE_CONTINUE)
errno = 0;
retval = 0;
goto skipit;
}
} else {
retval = -1;
goto stopit;
}
} else {
if (status) {
rv = (*status)(COPYFILE_RECURSE_DIR_CLEANUP, COPYFILE_FINISH, tstate, ftsent->fts_path, dstfile, s->ctx);
if (rv == COPYFILE_QUIT) {
retval = -1; errno = 0;
goto stopit;
}
}
}
rv = 0;
}
skipit:
stopit:
s->internal_flags &= ~COPYFILE_MNT_CPROTECT_MASK;
s->internal_flags |= (tstate->internal_flags & COPYFILE_MNT_CPROTECT_MASK);
copyfile_state_free(tstate);
free(dstfile);
if (retval == -1)
break;
}
done:
if (fts)
fts_close(fts);
copyfile_debug(1, "returning: %d errno %d\n", retval, errno);
return retval;
}
/*
* fcopyfile() is used to copy a source file descriptor to a destination file
* descriptor. This allows an application to figure out how it wants to open
* the files (doing various security checks, perhaps), and then just pass in
* the file descriptors.
*/
int fcopyfile(int src_fd, int dst_fd, copyfile_state_t state, copyfile_flags_t flags)
{
int ret = 0;
copyfile_state_t s = state;
struct stat dst_sb;
bool dst_stat_ok = true;
if (src_fd < 0 || dst_fd < 0)
{
errno = EINVAL;
return -1;
}
if (copyfile_preamble(&s, flags) < 0)
return -1;
copyfile_debug(2, "set src_fd <- %d", src_fd);
if (s->src_fd == -2 && src_fd > -1)
{
s->src_fd = src_fd;
if (fstatx_np(s->src_fd, &s->sb, s->fsec) != 0)
{
if (errno == ENOTSUP || errno == EPERM)
fstat(s->src_fd, &s->sb);
else
{
copyfile_warn("fstatx_np on src fd %d", s->src_fd);
return -1;
}
}
}
/* prevent copying on unsupported types */
switch (s->sb.st_mode & S_IFMT)
{
case S_IFLNK:
case S_IFDIR:
case S_IFREG:
break;
default:
errno = ENOTSUP;
return -1;
}
copyfile_debug(2, "set dst_fd <- %d", dst_fd);
if (s->dst_fd == -2 && dst_fd > -1)
s->dst_fd = dst_fd;
if (fstat(s->dst_fd, &dst_sb) < 0)
dst_stat_ok = false;
(void)fchmod(s->dst_fd, (dst_sb.st_mode & ~S_IFMT) | (S_IRUSR | S_IWUSR));
(void)copyfile_quarantine(s);
ret = copyfile_internal(s, flags);
if (dst_stat_ok && !(s->flags & COPYFILE_STAT))
{
// Our work here can reset errno, so save its result in advance.
errno_t _errsv = errno;
(void)fchmod(s->dst_fd, dst_sb.st_mode & ~S_IFMT);
errno = _errsv;
}
if (s->err) {
errno = s->err;
s->err = 0;
}
if (state == NULL) {
int t = errno;
copyfile_state_free(s);
errno = t;
}
if (ret >= 0) {
errno = 0;
}
return ret;
}
/*
* This routine implements the clonefileat functionality
* for copyfile. There are 2 kinds of clone flags, namely
* 1. COPYFILE_CLONE_FORCE which is a 'force' clone flag.
* 2. COPYFILE_CLONE which is a 'best try' flag.
* In both cases, we inherit the flags provided
* to copyfile call and clone the file.
* Both these flags are equivalent to