-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstrarc.cpp
More file actions
668 lines (548 loc) · 16.4 KB
/
strarc.cpp
File metadata and controls
668 lines (548 loc) · 16.4 KB
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
/* Stream Archive I/O utility, Copyright (C) Olof Lagerkvist 2004-2022
*
* strarc.cpp
* Definitions for some common outline members of StrArc class.
*/
#ifndef _UNICODE
#define _UNICODE
#endif
#ifndef _DLL
#define _DLL
#endif
#ifndef UNICODE
#define UNICODE
#endif
#ifndef _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#endif
#ifndef _CRT_NON_CONFORMING_WCSTOK
#define _CRT_NON_CONFORMING_WCSTOK
#endif
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
// Use the WinStructured library classes and functions.
#define WIN32_NO_STATUS
#include <windows.h>
#include <intsafe.h>
#include <shellapi.h>
#undef WIN32_NO_STATUS
#include <ntdll.h>
#include <winstrct.h>
#include <wio.h>
#include <wntsecur.h>
#include <wprocess.h>
#include <wsync.h>
#include <stdlib.h>
#include "strarc.hpp"
#include "version.h"
#define BOOL_FROM_FLAG(flags, flag) (((flags) & (flag)) != 0)
DWORDLONG
StrArc::GetLibraryVersion()
{
union
{
WORD fields[4];
DWORDLONG dwl;
} record = { { STRARC_VERSION_INFO } };
return record.dwl;
}
void
StrArc::Initialize()
{
LPBYTE dataptr = (LPBYTE)&FirstMember;
SSIZE_T datasize = sizeof(*this) - (dataptr - (LPBYTE)this);
memset(dataptr, 0, datasize);
FileCounter = 0;
FullPath.Length = 0;
FullPath.MaximumLength = USHORT_MAX;
FullPath.Buffer = wczFullPathBuffer;
hArchive = INVALID_HANDLE_VALUE;
bCancel = false;
bVerbose = false;
bLocal = false;
bTestMode = false;
bListOnly = false;
bListFiles = false;
bProcessSecurity = TRUE;
bProcessFileTimes = true;
bProcessFileAttribs = true;
bHardLinkSupport = true;
bRestoreCompression = true;
bSkipShortNames = false;
bNoShortNameWarnings = false;
bOverwriteOlder = false;
bOverwriteArchived = false;
bFreshenExisting = false;
dwExtractCreation = FILE_CREATE;
dwCreateOption = FILE_OPEN_FOR_BACKUP_INTENT;
bRestoreShortNamesOnly = false;
bBackupRegistrySnapshots = false;
BackupMethod = BACKUP_METHOD_COPY;
dwExcludeStrings = 0;
szExcludeStrings = NULL;
dwIncludeStrings = 0;
szIncludeStrings = NULL;
dwBufferSize = DEFAULT_STREAM_BUFFER_SIZE;
Buffer = NULL;
}
StrArc::~StrArc()
{
if (szIncludeStrings != NULL)
free(szIncludeStrings);
if (szExcludeStrings != NULL)
free(szExcludeStrings);
for (int i = 0; i < 256; i++)
for (LinkTrackerItem *item = LinkTrackerItems[i];
item != NULL;
item = item->DeleteAndGetNext());
if (Buffer != NULL)
LocalFree(Buffer);
if (RootDirectory != NULL)
NtClose(RootDirectory);
if (hArchive != NULL)
CloseHandle(hArchive);
if (piFilter.dwProcessId != 0)
{
if (bVerbose)
fputs("Waiting for filter utility to exit...\r\n", stderr);
WaitForSingleObject(piFilter.hProcess, INFINITE);
if (bVerbose)
{
DWORD dwExitCode;
if (GetExitCodeProcess(piFilter.hProcess, &dwExitCode))
fprintf(stderr, "Filter return value: %i\n", dwExitCode);
else
win_perrorA("Error getting filter return value");
}
}
}
// This function is called on various kinds of non-recoverable errors. It
// prepares an error message and some exception information and calls
// RaiseException().
void
__declspec(noreturn)
StrArc::Exception(XError XE, LPCWSTR Name)
{
DWORD syscode = GetLastError();
WErrMsgW syserrmsg;
bool bDisplaySysErrMsg = false;
LPCWSTR errmsg = L"";
NTSTATUS status = (NTSTATUS)XE;
switch (XE)
{
case XE_CANCELLED:
errmsg = L"\r\nstrarc aborted: Operation cancelled.\r\n";
status = STATUS_CANCELLED;
break;
case XE_CREATE_DIR:
errmsg = L"\r\nstrarc aborted: Cannot create directory.\r\n";
bDisplaySysErrMsg = true;
status = STATUS_IO_DEVICE_ERROR;
break;
case XE_CHANGE_DIR:
errmsg = L"\r\nstrarc aborted: Cannot change to directory.\r\n";
bDisplaySysErrMsg = true;
status = STATUS_IO_DEVICE_ERROR;
break;
case XE_CREATE_FILE:
errmsg = L"\r\nstrarc aborted: Cannot create file.\r\n";
bDisplaySysErrMsg = true;
status = STATUS_IO_DEVICE_ERROR;
break;
case XE_FILE_IO:
errmsg = L"\r\nstrarc aborted: File I/O error.\r\n";
bDisplaySysErrMsg = true;
status = STATUS_IO_DEVICE_ERROR;
break;
case XE_ARCHIVE_IO:
errmsg = L"\r\nstrarc aborted: Archive I/O error.\r\n";
bDisplaySysErrMsg = true;
status = STATUS_IO_DEVICE_ERROR;
break;
case XE_ARCHIVE_OPEN:
errmsg = L"\r\nstrarc: Archive open error.\r\n";
bDisplaySysErrMsg = true;
status = STATUS_IO_DEVICE_ERROR;
break;
case XE_CREATE_PIPE:
errmsg = L"\r\nstrarc: Cannot create pipe.\r\n";
bDisplaySysErrMsg = true;
status = STATUS_IO_DEVICE_ERROR;
break;
case XE_FILTER_EXECUTE:
errmsg = L"\r\nstrarc: Cannot execute filter.\r\n";
bDisplaySysErrMsg = true;
status = RPC_NT_CALL_FAILED;
break;
case XE_ARCHIVE_TRUNC:
errmsg = L"\r\nstrarc aborted: Unexpected end of archive.\r\n";
status = STATUS_UNEXPECTED_IO_ERROR;
break;
case XE_ARCHIVE_BAD_HEADER:
errmsg = L"\r\nstrarc aborted: Bad archive format, aborted.\r\n";
status = STATUS_UNEXPECTED_IO_ERROR;
break;
case XE_TOO_LONG_PATH:
errmsg = L"\r\nstrarc aborted: Target path is too long.\r\n";
status = STATUS_NAME_TOO_LONG;
break;
case XE_NOT_ENOUGH_MEMORY:
errmsg = L"\r\nstrarc aborted: Memory allocation failed.\r\n";
bDisplaySysErrMsg = true;
status = STATUS_NO_MEMORY;
break;
case XE_NOT_ENOUGH_MEMORY_FOR_LINK_TRACKER:
errmsg =
L"\r\n"
L"strarc aborted: Memory allocation for hard link tracking failed.\r\n"
L"Free some memory or use the -s:l option\r\n";
bDisplaySysErrMsg = true;
status = STATUS_NO_MEMORY;
break;
case XE_BAD_BUFFER:
errmsg = L"\r\nstrarc aborted: The stream buffer size is too small.\r\n";
status = STATUS_INVALID_PARAMETER;
break;
case XE_NOERROR:
errmsg = Name;
Name = NULL;
status = STATUS_INVALID_PARAMETER;
break;
default:
errmsg = Name;
Name = NULL;
status = XE;
break;
}
ZeroMemory(&ExceptionData, sizeof(ExceptionData));
if (bDisplaySysErrMsg)
{
ExceptionData.SysErrorCode = syscode;
ExceptionData.SysErrorMessage = syserrmsg;
}
ExceptionData.ErrorCode = XE;
ExceptionData.ErrorMessage = errmsg;
ExceptionData.ObjectName = Name;
RaiseException((DWORD)status, EXCEPTION_NONCONTINUABLE, 0, NULL);
ExitThread(XE);
}
StrArc::XError
StrArc::InitializeBuffer()
{
// It needs to be greater than 64 KB.
if (dwBufferSize < 65536)
return XE_BAD_BUFFER;
// Try to allocate the buffer size (possibly specified on command line).
if (!InitializeBuffer(dwBufferSize))
return XE_NOT_ENOUGH_MEMORY;
return XE_NOERROR;
}
bool
StrArc::OpenArchive(LPCWSTR wczFilename,
bool bBackupMode,
DWORD dwArchiveCreation)
{
WSecurityAttributes sa;
sa.bInheritHandle = TRUE;
if (wczFilename == NULL)
hArchive = GetStdHandle(bBackupMode ?
STD_OUTPUT_HANDLE : STD_INPUT_HANDLE);
else
{
hArchive = CreateFile(wczFilename,
bBackupMode ? GENERIC_WRITE : GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_DELETE |
(bBackupMode ? 0 : FILE_SHARE_WRITE),
&sa,
bBackupMode ?
dwArchiveCreation : OPEN_EXISTING,
(bBackupMode ? FILE_ATTRIBUTE_NORMAL : 0) |
FILE_FLAG_SEQUENTIAL_SCAN |
FILE_FLAG_BACKUP_SEMANTICS,
NULL);
if (hArchive == INVALID_HANDLE_VALUE)
return false;
}
if (dwArchiveCreation == OPEN_ALWAYS)
SetFilePointer(hArchive, 0, 0, FILE_END);
else
SetEndOfFile(hArchive);
return true;
}
bool
StrArc::OpenFilterUtility(LPWSTR wczFilterCmd,
bool bBackupMode)
{
HANDLE hPipe[2] = { NULL };
if (!CreatePipe(&hPipe[0], &hPipe[1], NULL, 0))
return false;
// This makes child process only inherit one end of the pipe.
WStartupInfo si;
si.dwFlags = STARTF_USESTDHANDLES;
if (bBackupMode)
{
SetHandleInformation(hPipe[0],
HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT);
si.hStdInput = hPipe[0];
si.hStdOutput = hArchive;
hArchive = hPipe[1];
}
else
{
SetHandleInformation(hPipe[1],
HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT);
si.hStdInput = hArchive;
si.hStdOutput = hPipe[1];
hArchive = hPipe[0];
}
si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
if (!CreateProcess(NULL, wczFilterCmd, NULL, NULL, TRUE, 0, NULL,
NULL, &si, &piFilter))
return false;
CloseHandle(si.hStdInput);
CloseHandle(si.hStdOutput);
return true;
}
bool
StrArc::OpenWorkingDirectory(LPCWSTR wczStartDir, bool bBackupMode)
{
HANDLE root_dir;
UNICODE_STRING start_dir;
if (wczStartDir == NULL)
{
root_dir = NtCurrentDirectoryHandle();
RtlCreateUnicodeString(&start_dir, L"");
}
else
{
root_dir = NULL;
NTSTATUS status =
RtlDosPathNameToNtPathName_U(wczStartDir, &start_dir, NULL, NULL);
if (!NT_SUCCESS(status))
{
SetLastError(RtlNtStatusToDosError(status));
return false;
}
if (bVerbose)
oem_printf(stderr,
"Working directory is '%1!wZ!'%%n",
&start_dir);
}
if (bBackupMode)
{
RootDirectory =
NativeOpenFile(root_dir,
&start_dir,
FILE_LIST_DIRECTORY |
FILE_TRAVERSE,
OBJ_CASE_INSENSITIVE,
FILE_SHARE_READ |
FILE_SHARE_WRITE |
FILE_SHARE_DELETE,
FILE_DIRECTORY_FILE |
FILE_OPEN_FOR_BACKUP_INTENT);
}
else
{
RootDirectory =
NativeCreateDirectory(root_dir,
&start_dir,
FILE_LIST_DIRECTORY |
FILE_TRAVERSE,
OBJ_CASE_INSENSITIVE,
NULL,
FILE_ATTRIBUTE_NORMAL,
FILE_SHARE_READ |
FILE_SHARE_WRITE |
FILE_SHARE_DELETE,
FILE_DIRECTORY_FILE |
FILE_OPEN_FOR_BACKUP_INTENT,
TRUE);
}
DWORD dwLastError = GetLastError();
RtlFreeUnicodeString(&start_dir);
if (RootDirectory == INVALID_HANDLE_VALUE)
{
SetLastError(dwLastError);
return false;
}
return true;
}
StrArc::StrArc()
{
Initialize();
}
StrArc::StrArc(STRARC_OPERATION_MODE OperationMode,
STRARC_OPERATIONAL_FLAGS OperationalFlags,
BackupMethods BackupMethod,
LPCWSTR wczArchiveFile,
bool bAppendToArchive,
DWORD dwBufferSize,
LPWSTR wczFilterCmd,
LPCWSTR wczStartDir)
{
Initialize();
bool bBackupMode = false;
switch (OperationMode)
{
case STRARC_BACKUP_MODE:
bBackupMode = true;
break;
case STRARC_RESTORE_MODE:
break;
case STRARC_TEST_MODE:
bTestMode = true;
break;
default:
Exception(XE_NOERROR, L"Invalid operation mode.");
}
DWORD dwArchiveCreation = CREATE_ALWAYS;
if (bAppendToArchive)
dwArchiveCreation = OPEN_ALWAYS;
this->BackupMethod = BackupMethod;
this->dwBufferSize = dwBufferSize;
this->bBackupRegistrySnapshots =
BOOL_FROM_FLAG(OperationalFlags, STRARC_FLAG_BACKUP_REGISTRY_SNAPSHOTS);
this->bVerbose =
BOOL_FROM_FLAG(OperationalFlags, STRARC_FLAG_VERBOSE);
this->bListFiles =
BOOL_FROM_FLAG(OperationalFlags, STRARC_FLAG_LIST_FILES);
this->bListOnly =
BOOL_FROM_FLAG(OperationalFlags, STRARC_FLAG_LIST_ONLY);
this->bLocal =
BOOL_FROM_FLAG(OperationalFlags, STRARC_FLAG_NO_FOLLOW_REPARSE);
this->bProcessSecurity =
!BOOL_FROM_FLAG(OperationalFlags, STRARC_FLAG_NO_PROCESS_SECURITY);
this->bProcessFileTimes =
!BOOL_FROM_FLAG(OperationalFlags, STRARC_FLAG_NO_PROCESS_FILE_TIME);
this->bProcessFileAttribs =
!BOOL_FROM_FLAG(OperationalFlags, STRARC_FLAG_NO_PROCESS_FILE_ATTRIBUTES);
this->bHardLinkSupport =
!BOOL_FROM_FLAG(OperationalFlags, STRARC_FLAG_NO_TRACK_HARD_LINKS);
this->bRestoreCompression =
!BOOL_FROM_FLAG(OperationalFlags, STRARC_FLAG_NO_RESTORE_COMPRESSION);
this->bSkipShortNames =
BOOL_FROM_FLAG(OperationalFlags, STRARC_FLAG_NO_SHORT_NAMES);
this->bNoShortNameWarnings =
BOOL_FROM_FLAG(OperationalFlags, STRARC_FLAG_NO_SHORT_NAME_WARNINGS);
this->bOverwriteOlder =
BOOL_FROM_FLAG(OperationalFlags, STRARC_FLAG_OVERWRITE_OLDER);
this->bOverwriteArchived =
BOOL_FROM_FLAG(OperationalFlags, STRARC_FLAG_OVERWRITE_ARCHIVED);
this->bFreshenExisting =
BOOL_FROM_FLAG(OperationalFlags, STRARC_FLAG_FRESHEN_EXISTING);
this->bRestoreShortNamesOnly =
BOOL_FROM_FLAG(OperationalFlags, STRARC_FLAG_RESTORE_SHORT_NAMES_ONLY);
XError bufferstatus = InitializeBuffer();
if (bufferstatus != XE_NOERROR)
Exception(bufferstatus);
if (bBackupRegistrySnapshots)
if (!bBackupMode)
Exception(XE_NOERROR,
L"Registry snaphot feature only available for "
L"backup operation.");
else
CreateRegistrySnapshots();
if (!bListOnly)
if (!OpenArchive(wczArchiveFile,
bBackupMode,
dwArchiveCreation))
Exception(XE_ARCHIVE_OPEN, wczArchiveFile);
// If we should filter through a compression utility.
if (wczFilterCmd != NULL)
if (!OpenFilterUtility(wczFilterCmd, bBackupMode))
Exception(XE_FILTER_EXECUTE, wczFilterCmd);
if (!OpenWorkingDirectory(wczStartDir, bBackupMode))
Exception(XE_CHANGE_DIR, wczStartDir);
if (bBackupMode && (dwBufferSize < HEADER_SIZE))
Exception(XE_BAD_BUFFER);
}
void
StrArc::BackupFilenamesFromStreamW(HANDLE hInputFile)
{
WOverlappedIOC ol;
if (!ol)
Exception(XE_NOT_ENOUGH_MEMORY);
for (;;)
{
YieldSingleProcessor();
if (bCancel)
break;
FullPath.Length = (USHORT)
ol.LineRecvW(hInputFile,
FullPath.Buffer,
FullPath.MaximumLength >> 1);
if (FullPath.Length == 0)
{
if (GetLastError() == NO_ERROR)
continue;
if (GetLastError() != ERROR_HANDLE_EOF)
win_perrorA("strarc");
break;
}
BackupFile(&FullPath, NULL, false);
}
}
void
StrArc::BackupFilenamesFromStreamA(HANDLE hInputFile)
{
WOverlappedIOC ol;
if (!ol)
(XE_NOT_ENOUGH_MEMORY);
for (;;)
{
YieldSingleProcessor();
if (bCancel)
break;
WHeapMem<char> czFile(32768,
HEAP_GENERATE_EXCEPTIONS | HEAP_ZERO_MEMORY);
size_t iLen =
ol.LineRecv(hInputFile,
czFile,
(DWORD)czFile.Count());
if (iLen == 0)
{
if (GetLastError() == NO_ERROR)
continue;
if (GetLastError() != ERROR_HANDLE_EOF)
win_perrorA("strarc");
break;
}
ANSI_STRING file;
RtlInitAnsiString(&file, czFile);
NTSTATUS status =
RtlAnsiStringToUnicodeString(&FullPath,
&file,
FALSE);
if (!NT_SUCCESS(status))
{
WErrMsgA errmsg(RtlNtStatusToDosError(status));
fprintf(stderr,
"strarc: Too long path: '%s'\n", (LPSTR)czFile);
continue;
}
BackupFile(&FullPath, NULL, false);
}
}
void
StrArc::SetIncludeExcludeStrings(LPDWORD dwStrings,
LPWSTR *szStrings,
LPCWSTR wczNewStrings)
{
if (*szStrings != NULL)
free(*szStrings);
if (wczNewStrings == NULL)
{
*dwStrings = 0;
*szStrings = NULL;
return;
}
LPWSTR str = _wcsdup(wczNewStrings);
if (str == NULL)
Exception(XE_NOT_ENOUGH_MEMORY);
*szStrings = wcstok(str, L",");
*dwStrings = 1;
while (wcstok(NULL, L","))
++ *dwStrings;
}