-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathcopy.c
1237 lines (1060 loc) · 44.8 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
/**
* @file copy/copy.c
*
* Yori shell copy files
*
* Copyright (c) 2017-2022 Malcolm J. Smith
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, COPYESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <yoripch.h>
#include <yorilib.h>
/**
Help text to display to the user.
*/
const
CHAR strCopyHelpText[] =
"\n"
"Copies one or more files.\n"
"\n"
"COPY [-license] [-b] [-c:algorithm] [-ds size] [-l] [-n|-nt|-p] [-s] [-t] [-v]\n"
" [-x exclude] <src>\n"
"COPY [-license] [-b] [-c:algorithm] [-ds size] [-l] [-n|-nt|-p] [-s] [-t] [-v]\n"
" [-x exclude] <src> [<src> ...] <dest>\n"
"\n"
" -b Use basic search criteria for files only\n"
" -c Compress targets with specified algorithm. Options are:\n"
" lzx, ntfs, xp4k, xp8k, xp16k\n"
" -ds The size of the device, ignored for files\n"
" -l Copy links as links rather than contents\n"
" -n Copy new or files whose size have changed only\n"
" -nt Copy new or files whose size or timestamps have changed only\n"
" -p Preserve existing files, no overwriting\n"
" -s Copy subdirectories as well as files\n"
" -t Copy timestamps only, no data\n"
" -v Verbose output\n"
" -x Exclude files matching specified pattern\n";
/**
Display usage text to the user.
*/
BOOL
CopyHelp(VOID)
{
YoriLibOutput(YORI_LIB_OUTPUT_STDOUT, _T("Copy %i.%02i\n"), YORI_VER_MAJOR, YORI_VER_MINOR);
#if YORI_BUILD_ID
YoriLibOutput(YORI_LIB_OUTPUT_STDOUT, _T(" Build %i\n"), YORI_BUILD_ID);
#endif
YoriLibOutput(YORI_LIB_OUTPUT_STDOUT, _T("%hs"), strCopyHelpText);
return TRUE;
}
/**
A single item to exclude. Note this can refer to multiple files.
*/
typedef struct _COPY_EXCLUDE_ITEM {
/**
List of items to exclude.
*/
YORI_LIST_ENTRY ExcludeList;
/**
A string describing the object to exclude, which may include
wildcards.
*/
YORI_STRING ExcludeCriteria;
} COPY_EXCLUDE_ITEM, *PCOPY_EXCLUDE_ITEM;
/**
A context passed between each source file match when copying multiple
files.
*/
typedef struct _COPY_CONTEXT {
/**
Path to the destination for the copy operation.
*/
YORI_STRING Dest;
/**
Files matching any of the exclude rules will not be copied.
*/
YORI_LIST_ENTRY ExcludeList;
/**
State related to background compression of files after copy.
*/
YORILIB_COMPRESS_CONTEXT CompressContext;
/**
The number of bytes to copy when copying to or from a device. Zero
means copy until the end of the device.
*/
LARGE_INTEGER DeviceSize;
/**
The file system attributes of the destination. Used to determine if
the destination exists and is a directory.
*/
DWORD DestAttributes;
/**
The number of files that have been previously copied to this
destination. This can be used to determine if we're about to copy
a second object over the top of an earlier copied file.
*/
DWORD FilesCopied;
/**
The number of files that have been enumerated while expanding a
particular command argument. If this is zero, the argument hasn't
resolved to any existing files.
*/
DWORD FilesFoundThisArg;
/**
If TRUE, targets should be compressed.
*/
BOOLEAN CompressDest;
/**
If TRUE, links are copied as links rather than having their contents
copied.
*/
BOOLEAN CopyAsLinks;
/**
If TRUE, files are copied if they are not on the target, or if the size
on the source is different to the target. Depending on the value of
CopyChangedTimestamps, a file may be copied if its size is identical
on the source and target but the timestamp has changed.
*/
BOOLEAN CopyNewOnly;
/**
If TRUE, files are copied if the timestamp has changed despite other
attributes being the same. If FALSE, the timestamp is ignored, and
files will not be copied unless other attributes have changed. This
field is only meaningful if CopyNewOnly is TRUE.
*/
BOOLEAN CopyChangedTimestamps;
/**
If TRUE, files are copied if they do not already exists. Any existing
file will be skipped.
*/
BOOLEAN PreserveExisting;
/**
If TRUE, times from the source are explicitly copied to the target. If
FALSE, this task is left to CopyFile's defaults.
*/
BOOLEAN CopyTimestamps;
/**
If TRUE, data copies are skipped. This is done when timestamps are
being copied on existing files without moving any data.
*/
BOOLEAN SkipDataCopy;
/**
If TRUE, the destination is a device rather than a file, and CopyFile
should not be used since setting file metadata on the device is
expected to fail.
*/
BOOLEAN DestinationIsDevice;
/**
If TRUE, output is generated for each object copied.
*/
BOOLEAN Verbose;
} COPY_CONTEXT, *PCOPY_CONTEXT;
/**
Add a new exclude criteria to the list.
@param CopyContext Pointer to the copy context to populate with a new
exclude criteria.
@param NewCriteria Pointer to the new criteria to add, which may include
wildcards.
@return TRUE to indicate success, FALSE to indicate failure.
*/
BOOL
CopyAddExclude(
__in PCOPY_CONTEXT CopyContext,
__in PYORI_STRING NewCriteria
)
{
PCOPY_EXCLUDE_ITEM ExcludeItem;
ExcludeItem = YoriLibReferencedMalloc(sizeof(COPY_EXCLUDE_ITEM) + (NewCriteria->LengthInChars + 1) * sizeof(TCHAR));
if (ExcludeItem == NULL) {
return FALSE;
}
ZeroMemory(ExcludeItem, sizeof(COPY_EXCLUDE_ITEM));
ExcludeItem->ExcludeCriteria.StartOfString = (LPTSTR)(ExcludeItem + 1);
ExcludeItem->ExcludeCriteria.LengthInChars = NewCriteria->LengthInChars;
ExcludeItem->ExcludeCriteria.LengthAllocated = NewCriteria->LengthInChars + 1;
memcpy(ExcludeItem->ExcludeCriteria.StartOfString, NewCriteria->StartOfString, ExcludeItem->ExcludeCriteria.LengthInChars * sizeof(TCHAR));
ExcludeItem->ExcludeCriteria.StartOfString[ExcludeItem->ExcludeCriteria.LengthInChars] = '\0';
YoriLibAppendList(&CopyContext->ExcludeList, &ExcludeItem->ExcludeList);
return TRUE;
}
/**
Free all previously added exclude criteria.
@param CopyContext Pointer to the copy context to free all exclude criteria
from.
*/
VOID
CopyFreeExcludes(
__in PCOPY_CONTEXT CopyContext
)
{
PCOPY_EXCLUDE_ITEM ExcludeItem;
PYORI_LIST_ENTRY ListEntry;
ListEntry = YoriLibGetNextListEntry(&CopyContext->ExcludeList, NULL);
while (ListEntry != NULL) {
ExcludeItem = CONTAINING_RECORD(ListEntry, COPY_EXCLUDE_ITEM, ExcludeList);
YoriLibRemoveListItem(&ExcludeItem->ExcludeList);
YoriLibDereference(ExcludeItem);
ListEntry = YoriLibGetNextListEntry(&CopyContext->ExcludeList, NULL);
}
}
/**
Construct a full path to the destination from a CopyContext which specifies
the destination location, and the relative path from the source.
@param CopyContext Pointer to a copy context specifying the destination.
@param RelativePathFromSource Pointer to the file name relative to the source
root.
@param FullDest On successful completion, updated to point to a fully
qualified name to the destination.
@return TRUE to indicate success, FALSE to indicate failure. Note this
function can display errors to the console.
*/
__success(return)
BOOL
CopyBuildDestinationPath(
__in PCOPY_CONTEXT CopyContext,
__in PYORI_STRING RelativePathFromSource,
__inout PYORI_STRING FullDest
)
{
//
// If the target is a directory, construct a full path to the object
// within the target's directory tree. Otherwise, the target is just
// a regular file with no path.
//
if (CopyContext->DestAttributes & FILE_ATTRIBUTE_DIRECTORY) {
YORI_STRING DestWithFile;
if (!YoriLibAllocateString(&DestWithFile, CopyContext->Dest.LengthInChars + 1 + RelativePathFromSource->LengthInChars + 1)) {
return FALSE;
}
DestWithFile.LengthInChars = YoriLibSPrintf(DestWithFile.StartOfString, _T("%y\\%y"), &CopyContext->Dest, RelativePathFromSource);
if (!YoriLibGetFullPathNameReturnAllocation(&DestWithFile, TRUE, FullDest, NULL)) {
return FALSE;
}
YoriLibFreeStringContents(&DestWithFile);
} else {
if (CopyContext->FilesCopied > 0) {
YoriLibOutput(YORI_LIB_OUTPUT_STDERR, _T("Attempting to copy multiple files over a single file (%y)\n"), &CopyContext->Dest);
return FALSE;
}
YoriLibCloneString(FullDest, &CopyContext->Dest);
}
return TRUE;
}
/**
Returns TRUE to indicate that an object should be excluded based on the
exclude criteria, or FALSE if it should be included.
@param CopyContext Pointer to the copy context to check the new object
against.
@param RelativeSourcePath Pointer to a string describing the file relative
to the root of the source of the copy operation.
@param SourceFindData Pointer to information about the source as returned
from directory enumeration. This can be NULL if the source was not
found from directory enumeration.
@return TRUE to exclude the file, FALSE to include it.
*/
BOOL
CopyShouldExclude(
__in PCOPY_CONTEXT CopyContext,
__in PYORI_STRING RelativeSourcePath,
__in_opt PWIN32_FIND_DATA SourceFindData
)
{
PCOPY_EXCLUDE_ITEM ExcludeItem;
PYORI_LIST_ENTRY ListEntry;
ListEntry = YoriLibGetNextListEntry(&CopyContext->ExcludeList, NULL);
while (ListEntry != NULL) {
ExcludeItem = CONTAINING_RECORD(ListEntry, COPY_EXCLUDE_ITEM, ExcludeList);
if (YoriLibDoesFileMatchExpression(RelativeSourcePath, &ExcludeItem->ExcludeCriteria)) {
return TRUE;
}
ListEntry = YoriLibGetNextListEntry(&CopyContext->ExcludeList, ListEntry);
}
if (CopyContext->CopyNewOnly || CopyContext->PreserveExisting) {
YORI_STRING FullDest;
BY_HANDLE_FILE_INFORMATION DestFileInfo;
LARGE_INTEGER DestWriteTime;
LARGE_INTEGER SourceWriteTime;
HANDLE DestFileHandle;
YoriLibInitEmptyString(&FullDest);
if (!CopyBuildDestinationPath(CopyContext, RelativeSourcePath, &FullDest)) {
return FALSE;
}
DestFileHandle = CreateFile(FullDest.StartOfString,
FILE_READ_ATTRIBUTES,
FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
NULL,
OPEN_EXISTING,
FILE_FLAG_OPEN_REPARSE_POINT|FILE_FLAG_OPEN_NO_RECALL|FILE_FLAG_BACKUP_SEMANTICS,
NULL);
YoriLibFreeStringContents(&FullDest);
if (DestFileHandle == INVALID_HANDLE_VALUE) {
return FALSE;
}
if (CopyContext->PreserveExisting) {
CloseHandle(DestFileHandle);
return TRUE;
}
if (!GetFileInformationByHandle(DestFileHandle, &DestFileInfo)) {
CloseHandle(DestFileHandle);
return FALSE;
}
if (SourceFindData == NULL) {
CloseHandle(DestFileHandle);
return TRUE;
}
if (DestFileInfo.nFileSizeHigh != SourceFindData->nFileSizeHigh ||
DestFileInfo.nFileSizeLow != SourceFindData->nFileSizeLow) {
CloseHandle(DestFileHandle);
return FALSE;
}
if (CopyContext->CopyChangedTimestamps) {
DestWriteTime.HighPart = DestFileInfo.ftLastWriteTime.dwHighDateTime;
DestWriteTime.LowPart = DestFileInfo.ftLastWriteTime.dwLowDateTime;
SourceWriteTime.HighPart = SourceFindData->ftLastWriteTime.dwHighDateTime;
SourceWriteTime.LowPart = SourceFindData->ftLastWriteTime.dwLowDateTime;
//
// Due to file system timing granularity, if the source was written
// to more than 5 seconds before or after the target, consider it
// a timestamp change.
//
if (SourceWriteTime.QuadPart < DestWriteTime.QuadPart - 10 * 1000 * 1000 * 5 ||
SourceWriteTime.QuadPart > DestWriteTime.QuadPart + 10 * 1000 * 1000 * 5) {
CloseHandle(DestFileHandle);
return FALSE;
}
}
CloseHandle(DestFileHandle);
return TRUE;
}
return FALSE;
}
/**
Copy a single file from the source to the target by preserving its link
contents.
@param SourceFileName A NULL terminated string specifying the source file.
@param DestFileName A NULL terminated string specifying the destination file.
@param IsDirectory TRUE if the object being copied is a directory, FALSE if
it is not.
@return TRUE to indicate success, FALSE to indicate failure.
*/
BOOL
CopyAsLink(
__in LPTSTR SourceFileName,
__in LPTSTR DestFileName,
__in BOOL IsDirectory
)
{
PVOID ReparseData;
HANDLE SourceFileHandle;
HANDLE DestFileHandle;
DWORD LastError;
DWORD BytesReturned;
DWORD BytesToAllocate;
LPTSTR ErrText;
SourceFileHandle = CreateFile(SourceFileName,
GENERIC_READ,
FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
NULL,
OPEN_EXISTING,
FILE_FLAG_OPEN_REPARSE_POINT|FILE_FLAG_OPEN_NO_RECALL|FILE_FLAG_BACKUP_SEMANTICS,
NULL);
if (SourceFileHandle == INVALID_HANDLE_VALUE) {
LastError = GetLastError();
ErrText = YoriLibGetWinErrorText(LastError);
YoriLibOutput(YORI_LIB_OUTPUT_STDERR, _T("Open of source failed: %s: %s"), SourceFileName, ErrText);
YoriLibFreeWinErrorText(ErrText);
return FALSE;
}
if (IsDirectory) {
if (!CreateDirectory(DestFileName, NULL)) {
LastError = GetLastError();
if (LastError != ERROR_ALREADY_EXISTS) {
ErrText = YoriLibGetWinErrorText(LastError);
YoriLibOutput(YORI_LIB_OUTPUT_STDERR, _T("Create of destination failed: %s: %s"), DestFileName, ErrText);
YoriLibFreeWinErrorText(ErrText);
CloseHandle(SourceFileHandle);
return FALSE;
}
}
DestFileHandle = CreateFile(DestFileName,
GENERIC_WRITE,
FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
NULL,
OPEN_EXISTING,
FILE_FLAG_OPEN_REPARSE_POINT|FILE_FLAG_OPEN_NO_RECALL|FILE_FLAG_BACKUP_SEMANTICS,
NULL);
if (DestFileHandle == INVALID_HANDLE_VALUE) {
LastError = GetLastError();
ErrText = YoriLibGetWinErrorText(LastError);
YoriLibOutput(YORI_LIB_OUTPUT_STDERR, _T("Open of destination failed: %s: %s"), DestFileName, ErrText);
YoriLibFreeWinErrorText(ErrText);
CloseHandle(SourceFileHandle);
RemoveDirectory(DestFileName);
return FALSE;
}
} else {
DestFileHandle = CreateFile(DestFileName,
GENERIC_WRITE,
FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
NULL,
CREATE_ALWAYS,
FILE_FLAG_OPEN_REPARSE_POINT|FILE_FLAG_OPEN_NO_RECALL|FILE_FLAG_BACKUP_SEMANTICS,
NULL);
if (DestFileHandle == INVALID_HANDLE_VALUE) {
LastError = GetLastError();
ErrText = YoriLibGetWinErrorText(LastError);
YoriLibOutput(YORI_LIB_OUTPUT_STDERR, _T("Open of destination failed: %s: %s"), DestFileName, ErrText);
YoriLibFreeWinErrorText(ErrText);
CloseHandle(SourceFileHandle);
return FALSE;
}
}
BytesToAllocate = 64 * 1024;
if (!YoriLibIsSizeAllocatable(BytesToAllocate)) {
BytesToAllocate = 32 * 1024;
}
ReparseData = YoriLibMalloc((YORI_ALLOC_SIZE_T)BytesToAllocate);
if (ReparseData == NULL) {
CloseHandle(DestFileHandle);
CloseHandle(SourceFileHandle);
if (IsDirectory) {
RemoveDirectory(DestFileName);
} else {
DeleteFile(DestFileName);
}
return FALSE;
}
if (!DeviceIoControl(SourceFileHandle, FSCTL_GET_REPARSE_POINT, NULL, 0, ReparseData, 64 * 1024, &BytesReturned, NULL)) {
LastError = GetLastError();
ErrText = YoriLibGetWinErrorText(LastError);
YoriLibOutput(YORI_LIB_OUTPUT_STDERR, _T("Querying reparse data of source failed: %s: %s"), SourceFileName, ErrText);
YoriLibFreeWinErrorText(ErrText);
CloseHandle(SourceFileHandle);
CloseHandle(DestFileHandle);
YoriLibFree(ReparseData);
if (IsDirectory) {
RemoveDirectory(DestFileName);
} else {
DeleteFile(DestFileName);
}
return FALSE;
}
if (!DeviceIoControl(DestFileHandle, FSCTL_SET_REPARSE_POINT, ReparseData, BytesReturned, NULL, 0, &BytesReturned, NULL)) {
LastError = GetLastError();
ErrText = YoriLibGetWinErrorText(LastError);
YoriLibOutput(YORI_LIB_OUTPUT_STDERR, _T("Setting reparse data on dest failed: %s: %s"), DestFileName, ErrText);
YoriLibFreeWinErrorText(ErrText);
CloseHandle(SourceFileHandle);
CloseHandle(DestFileHandle);
YoriLibFree(ReparseData);
if (IsDirectory) {
RemoveDirectory(DestFileName);
} else {
DeleteFile(DestFileName);
}
return FALSE;
}
CloseHandle(SourceFileHandle);
CloseHandle(DestFileHandle);
YoriLibFree(ReparseData);
return TRUE;
}
/**
For objects that are not really files, copy can't use CopyFile, and instead
falls back to this stupid thing of reading and writing. Note this path
should not be used for files since it makes no attempt to preserve any kind
of file metadata, but for devices file metadata is meaningless anyway.
@param CopyContext Pointer to the copy context, specifying device size.
@param SourceFile Pointer to the source file/device name.
@param DestFile Pointer to the destination file/device name.
@return TRUE to indicate success, FALSE to indicate failure.
*/
BOOL
CopyAsDumbDataMove(
__in PCOPY_CONTEXT CopyContext,
__in PYORI_STRING SourceFile,
__in PYORI_STRING DestFile
)
{
PVOID Buffer;
DWORD BytesCopied;
DWORD BufferSize;
DWORD SectorSize;
HANDLE SourceHandle;
HANDLE DestHandle;
DWORD LastError;
LPTSTR ErrText;
LONGLONG TotalBytesCopied;
SourceHandle = CreateFile(SourceFile->StartOfString,
GENERIC_READ,
FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
NULL,
OPEN_EXISTING,
FILE_FLAG_OPEN_NO_RECALL|FILE_FLAG_BACKUP_SEMANTICS,
NULL);
if (SourceHandle == INVALID_HANDLE_VALUE) {
LastError = GetLastError();
ErrText = YoriLibGetWinErrorText(LastError);
YoriLibOutput(YORI_LIB_OUTPUT_STDERR, _T("Open of source failed: %y: %s"), SourceFile, ErrText);
YoriLibFreeWinErrorText(ErrText);
return FALSE;
}
DestHandle = CreateFile(DestFile->StartOfString,
GENERIC_WRITE,
FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
NULL,
CREATE_ALWAYS,
FILE_FLAG_BACKUP_SEMANTICS,
NULL);
LastError = GetLastError();
if (LastError == ERROR_INVALID_PARAMETER) {
DestHandle = CreateFile(DestFile->StartOfString,
GENERIC_WRITE,
FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
NULL,
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS,
NULL);
}
if (DestHandle == INVALID_HANDLE_VALUE) {
ErrText = YoriLibGetWinErrorText(LastError);
YoriLibOutput(YORI_LIB_OUTPUT_STDERR, _T("Open of destination failed: %y: %s"), DestFile, ErrText);
YoriLibFreeWinErrorText(ErrText);
CloseHandle(SourceHandle);
return FALSE;
}
SectorSize = YoriLibGetHandleSectorSize(DestHandle);
BufferSize = 64 * 1024;
if (!YoriLibIsSizeAllocatable(BufferSize)) {
BufferSize = 32 * 1024;
}
Buffer = YoriLibMalloc((YORI_ALLOC_SIZE_T)BufferSize);
if (Buffer == NULL) {
CloseHandle(SourceHandle);
CloseHandle(DestHandle);
return FALSE;
}
if (SectorSize > BufferSize) {
SectorSize = BufferSize;
}
TotalBytesCopied = 0;
while (ReadFile(SourceHandle, Buffer, BufferSize, &BytesCopied, NULL)) {
if (BytesCopied == 0) {
break;
}
if (CopyContext->DeviceSize.QuadPart != 0 &&
(TotalBytesCopied + BytesCopied) > CopyContext->DeviceSize.QuadPart) {
BytesCopied = (DWORD)(CopyContext->DeviceSize.QuadPart - TotalBytesCopied);
}
//
// If the destination has a sector size requirement, round up to the
// next whole sector
//
if (SectorSize != 0 &&
(BytesCopied % SectorSize) != 0) {
DWORD SectorOffset;
DWORD SectorRemaining;
DWORD BufferOffset;
SectorOffset = BytesCopied % SectorSize;
SectorRemaining = SectorSize - SectorOffset;
BufferOffset = (BytesCopied / SectorSize) * SectorSize + SectorOffset;
ZeroMemory(YoriLibAddToPointer(Buffer, BufferOffset), SectorRemaining);
BytesCopied = BytesCopied + SectorRemaining;
}
if (!WriteFile(DestHandle, Buffer, BytesCopied, &BytesCopied, NULL)) {
LastError = GetLastError();
ErrText = YoriLibGetWinErrorText(LastError);
YoriLibOutput(YORI_LIB_OUTPUT_STDERR, _T("Write to destination failed: %y: %s"), DestFile, ErrText);
YoriLibFreeWinErrorText(ErrText);
YoriLibFree(Buffer);
CloseHandle(SourceHandle);
CloseHandle(DestHandle);
return FALSE;
}
TotalBytesCopied = TotalBytesCopied + BytesCopied;
if (CopyContext->DeviceSize.QuadPart != 0 &&
TotalBytesCopied >= CopyContext->DeviceSize.QuadPart) {
break;
}
}
YoriLibFree(Buffer);
CloseHandle(SourceHandle);
CloseHandle(DestHandle);
return TRUE;
}
/**
Apply the timestamps from the source enumeration to the target file. This
can be done as a standalone operation or as part of updating files to
newer contents, where it is important that the timestamps of the target are
updated.
@param SourceFindData Pointer to the enumeration from the source specifying
file times to apply.
@param DestFile Points to the fully qualified pathname to the target to
apply timestamps to.
@return TRUE to indicate success, FALSE to indicate failure.
*/
BOOL
CopyTimestamps(
__in PWIN32_FIND_DATA SourceFindData,
__in PYORI_STRING DestFile
)
{
HANDLE DestFileHandle;
DestFileHandle = CreateFile(DestFile->StartOfString,
FILE_WRITE_ATTRIBUTES,
FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
NULL,
OPEN_EXISTING,
FILE_FLAG_OPEN_REPARSE_POINT|FILE_FLAG_OPEN_NO_RECALL|FILE_FLAG_BACKUP_SEMANTICS,
NULL);
if (DestFileHandle == INVALID_HANDLE_VALUE) {
return FALSE;
}
if (!SetFileTime(DestFileHandle, &SourceFindData->ftCreationTime, &SourceFindData->ftLastAccessTime, &SourceFindData->ftLastWriteTime)) {
CloseHandle(DestFileHandle);
return FALSE;
}
CloseHandle(DestFileHandle);
return TRUE;
}
/**
A callback that is invoked when a file is found that matches a search criteria
specified in the set of strings to enumerate.
@param FilePath Pointer to the file path that was found.
@param FileInfo Information about the file. This can be NULL if the file was
not found from enumeration, since the file may not be a file system
object (ie., it may be a device.)
@param Depth Indicates the recursion depth. Used by copy to check if it
needs to create new directories in the destination path.
@param Context Pointer to a context block specifying the destination of the
copy, indicating parameters to the copy operation, and tracking how
many objects have been copied.
@return TRUE to continute enumerating, FALSE to abort.
*/
BOOL
CopyFileFoundCallback(
__in PYORI_STRING FilePath,
__in_opt PWIN32_FIND_DATA FileInfo,
__in DWORD Depth,
__in PVOID Context
)
{
PCOPY_CONTEXT CopyContext = (PCOPY_CONTEXT)Context;
YORI_STRING RelativePathFromSource;
YORI_STRING FullDest;
YORI_STRING HumanSourcePath;
YORI_STRING HumanDestPath;
PYORI_STRING SourceNameToDisplay;
PYORI_STRING DestNameToDisplay;
YORI_ALLOC_SIZE_T SlashesFound;
YORI_ALLOC_SIZE_T Index;
DWORD LastError;
CopyContext->FilesFoundThisArg++;
ASSERT(YoriLibIsStringNullTerminated(FilePath));
YoriLibInitEmptyString(&FullDest);
YoriLibInitEmptyString(&RelativePathFromSource);
YoriLibInitEmptyString(&HumanSourcePath);
YoriLibInitEmptyString(&HumanDestPath);
SourceNameToDisplay = FilePath;
SlashesFound = 0;
for (Index = FilePath->LengthInChars; Index > 0; Index--) {
if (FilePath->StartOfString[Index - 1] == '\\') {
SlashesFound++;
if (SlashesFound == Depth + 1) {
break;
}
}
}
ASSERT(Index > 0);
ASSERT(SlashesFound == Depth + 1);
RelativePathFromSource.StartOfString = &FilePath->StartOfString[Index];
RelativePathFromSource.LengthInChars = FilePath->LengthInChars - Index;
//
// Check if the user wanted to exclude this file
//
if (CopyShouldExclude(CopyContext, &RelativePathFromSource, FileInfo)) {
if (CopyContext->Verbose) {
if (YoriLibUnescapePath(FilePath, &HumanSourcePath)) {
SourceNameToDisplay = &HumanSourcePath;
}
YoriLibOutput(YORI_LIB_OUTPUT_STDOUT, _T("Skipping %y\n"), SourceNameToDisplay);
YoriLibFreeStringContents(&HumanSourcePath);
}
return TRUE;
}
if (!CopyBuildDestinationPath(CopyContext, &RelativePathFromSource, &FullDest)) {
return FALSE;
}
//
// This cannot detect all cases where two paths might refer to the same
// file, but it can improve the experience if a user fails to specify
// a destination (implying a relative path to a file in the current
// directory should be copied to the current directory.) It can't even
// check for case insensitivity given NTFS can support case sensitive
// paths.
//
if (YoriLibCompareString(&FullDest, FilePath) == 0) {
YoriLibFreeStringContents(&FullDest);
YoriLibOutput(YORI_LIB_OUTPUT_STDERR, _T("Cannot copy file over itself: %y\n"), FilePath);
return TRUE;
}
DestNameToDisplay = &FullDest;
if (CopyContext->Verbose) {
if (YoriLibUnescapePath(FilePath, &HumanSourcePath)) {
SourceNameToDisplay = &HumanSourcePath;
}
if (YoriLibUnescapePath(&FullDest, &HumanDestPath)) {
DestNameToDisplay = &HumanDestPath;
}
YoriLibOutput(YORI_LIB_OUTPUT_STDOUT, _T("Copying %y to %y\n"), SourceNameToDisplay, DestNameToDisplay);
}
if (!CopyContext->SkipDataCopy) {
if (FileInfo != NULL &&
FileInfo->dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT &&
CopyContext->CopyAsLinks &&
(FileInfo->dwReserved0 == IO_REPARSE_TAG_MOUNT_POINT || FileInfo->dwReserved0 == IO_REPARSE_TAG_SYMLINK)) {
CopyAsLink(FilePath->StartOfString, FullDest.StartOfString, (FileInfo->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY));
} else if (FileInfo != NULL &&
FileInfo->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
if (!CreateDirectory(FullDest.StartOfString, NULL)) {
LastError = GetLastError();
if (LastError != ERROR_ALREADY_EXISTS) {
LPTSTR ErrText = YoriLibGetWinErrorText(LastError);
YoriLibOutput(YORI_LIB_OUTPUT_STDERR, _T("CreateDirectory failed: %s: %s"), FullDest.StartOfString, ErrText);
YoriLibFreeWinErrorText(ErrText);
}
}
} else if (CopyContext->DestinationIsDevice || YoriLibIsFileNameDeviceName(FilePath)) {
CopyAsDumbDataMove(CopyContext, FilePath, &FullDest);
} else {
LastError = YoriLibCopyFile(FilePath, &FullDest);
if (LastError != ERROR_SUCCESS) {
//
// If it failed with an error indicating CopyFile couldn't
// handle it, fall back to dumb data copy. Note that this
// function will output its own errors, so from this point,
// error handling is over.
//
if (LastError == ERROR_INVALID_PARAMETER) {
CopyAsDumbDataMove(CopyContext, FilePath, &FullDest);
} else {
LPTSTR ErrText = YoriLibGetWinErrorText(LastError);
if (SourceNameToDisplay != &HumanSourcePath) {
if (YoriLibUnescapePath(FilePath, &HumanSourcePath)) {
SourceNameToDisplay = &HumanSourcePath;
}
}
if (DestNameToDisplay != &HumanDestPath) {
if (YoriLibUnescapePath(&FullDest, &HumanDestPath)) {
DestNameToDisplay = &HumanDestPath;
}
}
YoriLibOutput(YORI_LIB_OUTPUT_STDERR, _T("CopyFile failed: %y to %y: %s"), SourceNameToDisplay, DestNameToDisplay, ErrText);
YoriLibFreeWinErrorText(ErrText);
}
}
if (CopyContext->CompressDest) {
YoriLibCompressFileInBackground(&CopyContext->CompressContext, &FullDest);
}
}
}
if (CopyContext->CopyTimestamps && FileInfo != NULL) {
CopyTimestamps(FileInfo, &FullDest);
}
CopyContext->FilesCopied++;
YoriLibFreeStringContents(&FullDest);
YoriLibFreeStringContents(&HumanSourcePath);
YoriLibFreeStringContents(&HumanDestPath);
return TRUE;
}
/**
Free the structures allocated within a copy context. The structure itself
is on the stack and is not freed. This will wait for any outstanding
compression work to complete.
@param CopyContext Pointer to the context to free.
*/
VOID
CopyFreeCopyContext(
__in PCOPY_CONTEXT CopyContext
)
{
YoriLibFreeCompressContext(&CopyContext->CompressContext);
YoriLibFreeStringContents(&CopyContext->Dest);
CopyFreeExcludes(CopyContext);
}
#ifdef YORI_BUILTIN
/**
The main entrypoint for the copy builtin command.
*/
#define ENTRYPOINT YoriCmd_YCOPY
#else
/**
The main entrypoint for the copy standalone application.
*/
#define ENTRYPOINT ymain
#endif
/**
The main entrypoint for the copy cmdlet.
@param ArgC The number of arguments.
@param ArgV An array of arguments.
@return Exit code of the child process on success, or failure if the child
could not be launched.
*/
DWORD
ENTRYPOINT(
__in YORI_ALLOC_SIZE_T ArgC,
__in YORI_STRING ArgV[]
)
{
BOOLEAN ArgumentUnderstood;
DWORD FilesProcessed;
DWORD FileCount;
YORI_ALLOC_SIZE_T LastFileArg = 0;
YORI_ALLOC_SIZE_T FirstFileArg = 0;
WORD MatchFlags;
BOOLEAN BasicEnumeration;
BOOLEAN Recursive;
YORI_ALLOC_SIZE_T i;
DWORD Result;
COPY_CONTEXT CopyContext;
YORILIB_COMPRESS_ALGORITHM CompressionAlgorithm;
YORI_STRING Arg;
FileCount = 0;
Recursive = FALSE;
BasicEnumeration = FALSE;
ZeroMemory(&CopyContext, sizeof(CopyContext));
CompressionAlgorithm.EntireAlgorithm = 0;
YoriLibInitializeListHead(&CopyContext.ExcludeList);
for (i = 1; i < ArgC; i++) {