-
Notifications
You must be signed in to change notification settings - Fork 2
/
CopyModule.cs
672 lines (628 loc) · 27.4 KB
/
CopyModule.cs
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Text.RegularExpressions;
using System.Runtime.InteropServices;
using System.Data.Common;
namespace yahb
{
struct DestinationFile
{
public string destDrive;
public string timestamp;
public string fileName;
public string driveTimeFilename;
}
class CopyModule
{
const int ERROR_SHARING_VIOLATION = 32;
const int ERROR_LOCK_VIOLATION = 33;
private Config cfg;
private string now;
List<String> sourceFileList;
List<String> sourceDirList;
List<DestinationFile> destFileList;
List<String> destDirList;
public CopyModule(Config cfg)
{
this.cfg = cfg;
this.now = DateTime.Now.ToString("yyyyMMddHHmm");
this.sourceFileList = new List<String>();
this.sourceDirList = new List<String>();
this.destFileList = new List<DestinationFile>();
this.destDirList = new List<String>();
}
public List<String> createDirectoryList() {
cfg.addToLog("creating list of directories ... ");
List<String> dirs = new List<String>();
// first check provided source directory and all subdirectories, if required
if (cfg.copySubDirectories)
{
Stack<string> dir_stack = new Stack<string>(20);
if (!String.IsNullOrEmpty(cfg.sourceDirectory))
{
dir_stack.Push(cfg.sourceDirectory);
}
// add directories from file here to stack
// /s is used, in order to get all
// subdirs
if(cfg.copySubDirectories)
{
foreach( string dir_i in cfg.inputDirectories)
{
dir_stack.Push(dir_i);
}
}
List<string> subdirs;
while (dir_stack.Count > 0)
{
string currentDir = dir_stack.Pop();
try
{
subdirs = new List<string>(Directory.EnumerateDirectories(currentDir));
string currentDirName = new DirectoryInfo(currentDir).Name;
bool addDir = true;
if (!cfg.copyAll)
{
foreach (string commonDir in cfg.commonDirsToIgnore)
{
// like ".Contains" but case insensitive
if (currentDir.IndexOf(commonDir, StringComparison.OrdinalIgnoreCase) >= 0)
{
addDir = false;
break;
}
}
}
if (addDir)
{
dirs.Add(currentDir);
} else
{
if(cfg.verboseMode)
{
cfg.addToLog(currentDir + ": skipping");
}
}
}
catch (UnauthorizedAccessException e)
{
cfg.addToLog("ERR:" + currentDir + ":" + e.Message);
continue;
}
catch (DirectoryNotFoundException e)
{
cfg.addToLog("ERR:" + currentDir + ":" + e.Message);
continue;
}
catch (PathTooLongException e)
{
cfg.addToLog("ERR:" + currentDir + ":" + e.Message);
continue;
}
foreach (string str in subdirs)
{
dir_stack.Push(str);
}
}
} else
{
dirs.Add(cfg.sourceDirectory);
}
// get directories from provided input file
// but only if /s was not provided (otherwise)
// above stack operation added them incl. subdirs
if (!cfg.copySubDirectories)
{
dirs.AddRange(cfg.inputDirectories);
}
// filter directories according to input given
List<String> dirs_filtered = new List<String>();
foreach (string dir_i in dirs)
{
bool addDir = true;
foreach (string pattern_i in cfg.directoriesToIgnore)
{
if (dir_i.IndexOf(pattern_i, StringComparison.OrdinalIgnoreCase) >= 0)
//if (dir_i.Contains(pattern_i))
{
addDir = false;
break;
}
}
if (addDir)
{
dirs_filtered.Add(dir_i);
} else
{
if (cfg.verboseMode)
{
cfg.addToLog(dir_i + ": skipping");
}
}
}
cfg.addToLog("creating list of directories ... DONE");
return dirs_filtered;
}
public void createFileList(List<String> inputDirList) {
cfg.addToLog("creating list of files ... ");
foreach (string dir_i in inputDirList)
{
try
{
this.destDirList.Add(this.createDirDestPath(dir_i, cfg.destinationDirectory));
sourceDirList.Add(dir_i);
}
catch (System.IO.PathTooLongException e)
{
this.cfg.addToLog("ERR:" + dir_i + ": " + e.Message);
continue;
}
string[] files_dir_i = System.IO.Directory.GetFiles(dir_i);
foreach (string file_i in files_dir_i)
{
bool addFile = false;
string file_i_pure = System.IO.Path.GetFileName(file_i);
// only add those files that are in our extension list
if (cfg.fileEndings.Count() > 0)
{
foreach (string pattern_i in cfg.fileEndings)
{
if (this.Like(file_i_pure, pattern_i))
{
addFile = true;
break;
}
}
} else // otherwise take file
{
addFile = true;
}
if (cfg.filePatternsToIgnore.Count > 0 && addFile == true)
{
foreach (string pattern_i in cfg.filePatternsToIgnore)
{
if (this.Like(file_i_pure, pattern_i))
{
addFile = false;
break;
}
}
}
if(!cfg.copyAll)
{
foreach (string pattern_i in cfg.commonFilePatternsToIgnore)
{
// in our common File patterns, we also have full file names like "hiberfil.sys"
// hence we must also check equality
if (this.Like(file_i_pure, pattern_i) || string.Equals(file_i_pure, pattern_i))
{
addFile = false;
break;
}
}
}
if (addFile)
{
try
{
this.destFileList.Add(this.createFileDestPath(file_i, cfg.destinationDirectory));
this.sourceFileList.Add(file_i);
} catch (System.IO.PathTooLongException e)
{
this.cfg.addToLog("ERR:" + file_i + ": " + e.Message);
}
} else
{
if (cfg.verboseMode)
{
cfg.addToLog(file_i + ": skipping");
}
}
}
}
/*
Console.WriteLine("input directories: ");
Console.WriteLine(String.Join("\n", sourceDirList));
Console.WriteLine("destination directories: ");
Console.WriteLine(String.Join("\n", destDirList));
Console.WriteLine("input file list: ");
Console.WriteLine(String.Join("\n", sourceFileList));
Console.WriteLine("destination file list: ");
foreach(DestinationFile df in destFileList)
{
Console.WriteLine(df.driveTimeFilename);
}*/
cfg.addToLog("creating list of files ... DONE");
}
public Tuple<string, string> getLastDir(string destDirectory)
{
try
{
string[] dirs = System.IO.Directory.GetDirectories(destDirectory);
List<Tuple<string,string>> numberDirs = new List<Tuple<string,string>>();
foreach (string dir_i in dirs)
{
DirectoryInfo f = new DirectoryInfo(dir_i);
string src_drive = Path.GetPathRoot(f.FullName);
//string dir_i_wo_drive = dir_i.Substring(src_drive.Length-1, dir_i.Length - src_drive.Length+1);
string dir_i_wo_drive = f.Name;
//Console.WriteLine("checking dir_i " + dir_i_wo_drive);
if(this.IsDigitsOnly(dir_i_wo_drive))
{
//Console.WriteLine("dir_i_wo_drive: " + dir_i_wo_drive);
numberDirs.Add(new Tuple<string,string>(dir_i, dir_i_wo_drive));
}
}
numberDirs.Sort();
numberDirs.Reverse();
if(numberDirs.Count > 0)
{
return numberDirs[0];
} else
{
throw new ArgumentException();
}
}
catch (UnauthorizedAccessException e)
{
this.cfg.addToLog("ERR:" + destDirectory + ": " + e.Message);
throw new ArgumentException();
}
catch (DirectoryNotFoundException e)
{
this.cfg.addToLog("ERR:" + destDirectory + ": " + e.Message);
throw new ArgumentException();
}
catch (PathTooLongException e)
{
this.cfg.addToLog("ERR:" + destDirectory + ": " + e.Message);
throw new ArgumentException();
}
}
public void doCopy()
{
List<Tuple<String, DestinationFile>> tryWithVSS = new List<Tuple<String, DestinationFile>>();
this.cfg.addToLog("-----------------------------------------------------------------");
bool foundLastDir = false;
string lastBackupDirectory = "";
string lastTimestamp = "";
try
{
Tuple<string,string> tpl = this.getLastDir(cfg.destinationDirectory);
lastBackupDirectory = tpl.Item1;
lastTimestamp = tpl.Item2;
this.cfg.addToLog("identified last backup directory: " + lastBackupDirectory);
foundLastDir = true;
} catch (ArgumentException e)
{
this.cfg.addToLog("unable to identify a previous backup location, copying all");
}
// first create all target directories
foreach (string destDir in this.destDirList)
{
try
{
if (!cfg.dryRun)
{
System.IO.Directory.CreateDirectory(destDir);
}
if (cfg.verboseMode)
{
cfg.addToLog(destDir + ": created");
}
}
catch (DirectoryNotFoundException ex)
{
this.cfg.addToLog("ERR:" + destDir + ": " + ex.Message);
continue;
}
catch (NotSupportedException ex)
{
this.cfg.addToLog("ERR:" + destDir + ": " + ex.Message);
continue;
}
catch (PathTooLongException ex)
{
this.cfg.addToLog("ERR:" + destDir + ": " + ex.Message);
continue;
}
catch (UnauthorizedAccessException ex)
{
this.cfg.addToLog("ERR:" + destDir + ": " + ex.Message);
continue;
}
catch (ArgumentException ex)
{
this.cfg.addToLog("ERR:" + destDir + ": " + ex.Message);
continue;
}
catch (IOException ex)
{
this.cfg.addToLog("ERR:" + destDir + ": " + ex.Message);
continue;
}
}
//Console.WriteLine("now " + this.now);
//Console.WriteLine("now eq backup: " + (this.now == lastTimestamp));
if (this.now == lastTimestamp)
{
this.cfg.addToLog("ERR: Backup folder " + this.now + " already exists. Aborting.");
this.cfg.addToLog("-----------------------------------------------------------------");
return;
}
// copy all files
var sourceDestFiles = this.sourceFileList.Zip(this.destFileList, (a, b) => new { sourceFile = a, destFile = b });
int counter = 0;
int cntAll = sourceDestFiles.Count();
if(cntAll == 0)
{
cntAll = 1;
}
int onePercent = (int) ((float) cntAll / 100.0);
var watch = System.Diagnostics.Stopwatch.StartNew();
cfg.WriteProgressBar("copying files: ", "", 0);
foreach (var x in sourceDestFiles)
{
try
{
FileInfo fi_source = new FileInfo(x.sourceFile);
bool makeCopy = true;
if (foundLastDir) {
// first check if file exists in old backup
string oldFn = Path.Combine(x.destFile.destDrive, lastBackupDirectory, x.destFile.fileName);
//Console.WriteLine("old file name: " + oldFn);
//Console.WriteLine("backup name: " + fi_source.FullName);
//Console.WriteLine("checking if: " + oldFn + " exists...");
FileInfo fi_backup = new FileInfo(oldFn);
if (fi_backup.Exists)
{
//Console.WriteLine("found file " + x.sourceFile + " in backup folder, checking similarity");
if (fi_source.CreationTimeUtc == fi_backup.CreationTimeUtc &&
fi_source.LastWriteTimeUtc == fi_backup.LastWriteTimeUtc &&
fi_source.Length == fi_backup.Length)
{
if (!cfg.dryRun)
{
//Console.WriteLine("no need to copy " + x.sourceFile + ", already exists in backup");
if (CreateHardLink(x.destFile.driveTimeFilename, oldFn, IntPtr.Zero))
{
makeCopy = false;
if (cfg.verboseMode)
{
cfg.addToLog(x.sourceFile + ": creating hardlink to " + oldFn);
}
}
else
{
cfg.addToLog("ERR:" + x.sourceFile + ": unable to create hardlink, copying instead");
}
} else
{
if (cfg.verboseMode)
{
cfg.addToLog(x.sourceFile + ": creating hardlink to " + oldFn);
}
}
}
}
}
if (!cfg.dryRun)
{
if (makeCopy)
{
try
{
//Console.WriteLine("source filename: " + x.sourceFile);
//Console.WriteLine("copying to: " + x.destFile.driveTimeFilename);
File.Copy(x.sourceFile, x.destFile.driveTimeFilename);
FileInfo fi_dest = new FileInfo(x.destFile.driveTimeFilename);
bool wasReadOnly = false;
if (fi_dest.IsReadOnly)
{
fi_dest.IsReadOnly = false;
wasReadOnly = true;
}
fi_dest.CreationTime = fi_source.CreationTime;
fi_dest.LastWriteTime = fi_source.LastWriteTime;
fi_dest.LastAccessTime = fi_source.LastAccessTime;
if (wasReadOnly)
{
fi_dest.IsReadOnly = true;
}
if (cfg.verboseMode)
{
cfg.addToLog(x.sourceFile + ": file copied");
}
}
catch (UnauthorizedAccessException unauthEx)
{
cfg.addToLog("ERR: " + x.sourceFile + ": couldn't access file and/or set creation time of destination file");
}
catch (ArgumentException e)
{
cfg.addToLog("ERR: " + x.sourceFile + ": argument exception");
}
catch (PathTooLongException e)
{
cfg.addToLog("ERR: " + x.sourceFile + ": path too long exception");
}
catch (DirectoryNotFoundException e)
{
cfg.addToLog("ERR: " + x.sourceFile + ": directory not found exception");
}
catch (FileNotFoundException e)
{
cfg.addToLog("ERR: " + x.sourceFile + ": file not found exception");
}
}
} else
{
if (cfg.verboseMode)
{
cfg.addToLog(x.sourceFile + ": file copied");
}
}
}
catch (IOException copyError)
{
if (cfg.useVss)
{
int errorCode = Marshal.GetHRForException(copyError) & ((1 << 16) - 1);
if (errorCode == ERROR_SHARING_VIOLATION || errorCode == ERROR_LOCK_VIOLATION)
{
cfg.addToLog("ERR:" + x.sourceFile + ": sharing or lock violation, trying later w/ shadow copy");
Tuple<String, DestinationFile> tpl = new Tuple<String, DestinationFile>(x.sourceFile, x.destFile);
tryWithVSS.Add(tpl);
} else
{
cfg.addToLog("ERR:" + x.sourceFile + ": " + copyError.Message);
}
} else
{
cfg.addToLog("ERR:" + x.sourceFile + ": " + copyError.Message);
}
}
catch(PlatformNotSupportedException e)
{
cfg.addToLog("ERR:" + x.sourceFile + ": " + e.Message);
}
catch (ArgumentOutOfRangeException e)
{
cfg.addToLog("ERR:" + x.sourceFile + ": " + e.Message);
}
counter += 1;
if (!cfg.verboseMode)
{
if(onePercent == 0)
{
onePercent += 1;
}
if (counter % onePercent == 0)
{
int percent = (int)((((double)counter / (double)cntAll)) * 100.0);
watch.Stop();
long passedSecs = watch.ElapsedMilliseconds / 1000;
double ratio = ((double) cntAll - (double)(counter + 1)) / (double) (counter + 1);
long remSecsTotal = (long)(passedSecs * ratio);
if (remSecsTotal > 10)
{
int remSeconds = (int) (remSecsTotal % 60);
int remMinutes = ((int) (remSecsTotal / 60)) % 60;
int remHours = (int) (remSecsTotal / (60 * 60));
string strETR = String.Format(" ETR: {0:00}:{1:00}:{2:00}", remHours, remMinutes, remSeconds);
cfg.WriteProgressBar("copying files:", strETR, percent, true);
} else
{
cfg.WriteProgressBar("copying files:", "", percent, true);
}
watch.Start();
}
}
}
if(!cfg.verboseMode)
{
cfg.WriteProgressBar("copying files:", " ", 100, true);
cfg.addToLog("");
}
cfg.addToLog("copying files: finished.");
watch.Stop();
TimeSpan ts = watch.Elapsed;
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
Console.WriteLine("Time Required: " + elapsedTime);
if (this.cfg.useVss && tryWithVSS.Count > 0)
{
using (VssBackup vss = new VssBackup())
{
vss.Setup(Path.GetPathRoot(tryWithVSS[0].Item1));
foreach(Tuple<String, DestinationFile> x in tryWithVSS)
{
//Console.WriteLine("using vss");
string snap_path = vss.GetSnapshotPath(x.Item1);
try
{
Alphaleonis.Win32.Filesystem.File.Copy(snap_path, x.Item2.driveTimeFilename);
cfg.addToLog(x.Item1 + ": copied snapshot via VSS");
} catch (ArgumentException e)
{
cfg.addToLog("ERR: " + x.Item1 + ": "+e.Message);
}
catch (DirectoryNotFoundException e)
{
cfg.addToLog("ERR: " + x.Item1 + ": " + e.Message);
} catch (FileNotFoundException e)
{
cfg.addToLog("ERR: " + x.Item1 + ": " + e.Message);
} catch (IOException e)
{
cfg.addToLog("ERR: " + x.Item1 + ": " + e.Message);
} catch (NotSupportedException e)
{
cfg.addToLog("ERR: " + x.Item1 + ": " + e.Message);
} catch (UnauthorizedAccessException e)
{
cfg.addToLog("ERR: " + x.Item1 + ": " + e.Message);
}
}
}
}
this.cfg.addToLog("-----------------------------------------------------------------");
}
public DestinationFile createFileDestPath(string fileSourcePath, string destDrive)
{
if(destDrive.EndsWith(":"))
{
destDrive += "\\";
}
FileInfo f = new FileInfo(fileSourcePath);
string src_drive = Path.GetPathRoot(f.FullName);
string dest_file = fileSourcePath.Substring(src_drive.Length, fileSourcePath.Length - src_drive.Length);
string src_drive_clean = src_drive.Replace(':', '_').Replace('\\', '_');
DestinationFile df = new DestinationFile();
df.destDrive = destDrive;
df.timestamp = now;
df.fileName = Path.Combine(src_drive_clean, dest_file);
df.driveTimeFilename = Path.Combine(destDrive, now, src_drive_clean, dest_file);
return df;
}
public string createDirDestPath(string dirSourcePath, string destDrive)
{
if (destDrive.EndsWith(":"))
{
destDrive += "\\";
}
DirectoryInfo f = new DirectoryInfo(dirSourcePath);
string src_drive = Path.GetPathRoot(f.FullName);
string des_dir = dirSourcePath.Substring(src_drive.Length, dirSourcePath.Length - src_drive.Length);
string src_drive_clean = src_drive.Replace(':', '_').Replace('\\', '_');
return Path.Combine(destDrive, now, src_drive_clean, des_dir);
}
public bool Like(string str, string pattern)
{
return new Regex(
"^" + Regex.Escape(pattern).Replace(@"\*", ".*").Replace(@"\?", ".") + "$",
RegexOptions.IgnoreCase | RegexOptions.Singleline
).IsMatch(str);
}
bool IsDigitsOnly(string str)
{
foreach (char c in str)
{
if (c < '0' || c > '9')
return false;
}
return true;
}
[DllImport("Kernel32.dll", CharSet = CharSet.Unicode)]
static extern bool CreateHardLink(
string lpFileName,
string lpExistingFileName,
IntPtr lpSecurityAttributes
);
}
}