Welcome to mirror list, hosted at ThFree Co, Russian Federation.

SystemIOWindows.cs « IO « Common « Library « Duplicati - github.com/duplicati/duplicati.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 52f3165763f3c541b6efc0f89b2db787827d180a (plain)
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
//  Copyright (C) 2015, The Duplicati Team

//  http://www.duplicati.com, info@duplicati.com
//
//  This library is free software; you can redistribute it and/or modify
//  it under the terms of the GNU Lesser General Public License as
//  published by the Free Software Foundation; either version 2.1 of the
//  License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful, but
//  WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using System.Collections.Generic;
using System.Security.AccessControl;
using System.IO;
using System.Linq;

using AlphaFS = Alphaleonis.Win32.Filesystem;
using Duplicati.Library.Interface;
using Newtonsoft.Json;

namespace Duplicati.Library.Common.IO
{
    public struct SystemIOWindows : ISystemIO
    {
        private const string UNCPREFIX = PathInternalWindows.ExtendedDevicePathPrefix;
        private const string UNCPREFIX_SERVER = PathInternalWindows.UncExtendedPathPrefix;
        private const string PATHPREFIX_SERVER = PathInternalWindows.UncPathPrefix;
        private const string PATHPREFIX_SERVER_ALT = @"//";
        private static readonly string DIRSEP = Util.DirectorySeparatorString;

        /// <summary>
        /// Prefix path with one of the UNC prefixes, but only if it's a fully
        /// qualified path with no relative components (i.e., with no "." or
        /// ".." as part of the path).
        /// </summary>
        public static string PrefixWithUNC(string path)
        {
            if (IsPrefixedWithUNC(path))
            {
                // For example: \\?\C:\Temp\foo.txt or \\?\UNC\example.com\share\foo.txt
                return path;
            }
            else
            {
                var hasRelativePathComponents = HasRelativePathComponents(path);
                if (IsPrefixedWithBasicUNC(path) && !hasRelativePathComponents)
                {
                    // For example: \\example.com\share\foo.txt or //example.com/share/foo.txt
                    return UNCPREFIX_SERVER + ConvertSlashes(path.Substring(PATHPREFIX_SERVER.Length));
                }
                else if (DotNetRuntimePathWindows.IsPathFullyQualified(path) && !hasRelativePathComponents)
                {
                    // For example: C:\Temp\foo.txt or C:/Temp/foo.txt
                    return UNCPREFIX + ConvertSlashes(path);
                }
                else
                {
                    // A relative path or a fully qualified path with relative
                    // path components so the UNC prefix cannot be applied.
                    // For example: foo.txt or C:\Temp\..\foo.txt
                    return path;
                }
            }
        }

        private static bool IsPrefixedWithBasicUNC(string path)
        {
            return path.StartsWith(PATHPREFIX_SERVER, StringComparison.Ordinal) ||
                path.StartsWith(PATHPREFIX_SERVER_ALT, StringComparison.Ordinal);
        }

        private static bool IsPrefixedWithUNC(string path)
        {
            return path.StartsWith(UNCPREFIX_SERVER, StringComparison.Ordinal) ||
                path.StartsWith(UNCPREFIX, StringComparison.Ordinal);
        }

        private static string[] relativePathComponents = new[] { ".", ".." };

        /// <summary>
        /// Returns true if <paramref name="path"/> contains relative path components; i.e., "." or "..".
        /// </summary>
        private static bool HasRelativePathComponents(string path)
        {
            return GetPathComponents(path).Any(pathComponent => relativePathComponents.Contains(pathComponent));
        }

        /// <summary>
        /// Returns a sequence representing the files and directories in <paramref name="path"/>.
        /// </summary>
        private static IEnumerable<string> GetPathComponents(string path)
        {
            while (!String.IsNullOrEmpty(path))
            {
                var pathComponent = Path.GetFileName(path);
                if (!String.IsNullOrEmpty(pathComponent))
                {
                    yield return pathComponent;
                }
                path = Path.GetDirectoryName(path);
            }
        }

        public static string StripUNCPrefix(string path)
        {
            if (path.StartsWith(UNCPREFIX_SERVER, StringComparison.Ordinal))
            {
                // @"\\?\UNC\example.com\share\file.txt" to @"\\example.com\share\file.txt"
                return PATHPREFIX_SERVER + path.Substring(UNCPREFIX_SERVER.Length);
            }
            else if (path.StartsWith(UNCPREFIX, StringComparison.Ordinal))
            {
                // @"\\?\C:\file.txt" to @"C:\file.txt"
                return path.Substring(UNCPREFIX.Length);
            }
            else
            {
                return path;
            }
        }

        /// <summary>
        /// Convert forward slashes to backslashes.
        /// </summary>
        /// <returns>Path with forward slashes replaced by backslashes.</returns>
        private static string ConvertSlashes(string path)
        {
            return path.Replace("/", Util.DirectorySeparatorString);
        }

        private class FileSystemAccess
        {
            // Use JsonProperty Attribute to allow readonly fields to be set by deserializer
            // https://github.com/duplicati/duplicati/issues/4028
            [JsonProperty]
            public readonly FileSystemRights Rights;
            [JsonProperty]
            public readonly AccessControlType ControlType;
            [JsonProperty]
            public readonly string SID;
            [JsonProperty]
            public readonly bool Inherited;
            [JsonProperty]
            public readonly InheritanceFlags Inheritance;
            [JsonProperty]
            public readonly PropagationFlags Propagation;

            public FileSystemAccess()
            {
            }

            public FileSystemAccess(FileSystemAccessRule rule)
            {
                Rights = rule.FileSystemRights;
                ControlType = rule.AccessControlType;
                SID = rule.IdentityReference.Value;
                Inherited = rule.IsInherited;
                Inheritance = rule.InheritanceFlags;
                Propagation = rule.PropagationFlags;
            }

            public FileSystemAccessRule Create(System.Security.AccessControl.FileSystemSecurity owner)
            {
                return (FileSystemAccessRule)owner.AccessRuleFactory(
                    new System.Security.Principal.SecurityIdentifier(SID),
                    (int)Rights,
                    Inherited,
                    Inheritance,
                    Propagation,
                    ControlType);
            }
        }

        private static Newtonsoft.Json.JsonSerializer _cachedSerializer;

        private Newtonsoft.Json.JsonSerializer Serializer
        {
            get
            {
                if (_cachedSerializer != null)
                {
                    return _cachedSerializer;
                }

                _cachedSerializer = Newtonsoft.Json.JsonSerializer.Create(
                    new Newtonsoft.Json.JsonSerializerSettings { Culture = System.Globalization.CultureInfo.InvariantCulture });

                return _cachedSerializer;
            }
        }

        private string SerializeObject<T>(T o)
        {
            using (var tw = new System.IO.StringWriter())
            {
                Serializer.Serialize(tw, o);
                tw.Flush();
                return tw.ToString();
            }
        }

        private T DeserializeObject<T>(string data)
        {
            using (var tr = new System.IO.StringReader(data))
            {
                return (T)Serializer.Deserialize(tr, typeof(T));
            }
        }

        private System.Security.AccessControl.FileSystemSecurity GetAccessControlDir(string path)
        {
            return System.IO.Directory.GetAccessControl(PrefixWithUNC(path));
        }

        private System.Security.AccessControl.FileSystemSecurity GetAccessControlFile(string path)
        {
            return System.IO.File.GetAccessControl(PrefixWithUNC(path));
        }

        private void SetAccessControlFile(string path, FileSecurity rules)
        {
            System.IO.File.SetAccessControl(PrefixWithUNC(path), rules);
        }

        private void SetAccessControlDir(string path, DirectorySecurity rules)
        {
            System.IO.Directory.SetAccessControl(PrefixWithUNC(path), rules);
        }

        #region ISystemIO implementation
        public void DirectoryCreate(string path)
        {
            System.IO.Directory.CreateDirectory(PrefixWithUNC(path));
        }

        public void DirectoryDelete(string path, bool recursive)
        {
            System.IO.Directory.Delete(PrefixWithUNC(path), recursive);
        }

        public bool DirectoryExists(string path)
        {
            return System.IO.Directory.Exists(PrefixWithUNC(path));
        }

        public void DirectoryMove(string sourceDirName, string destDirName)
        {
            System.IO.Directory.Move(PrefixWithUNC(sourceDirName), PrefixWithUNC(destDirName));
        }

        public void FileDelete(string path)
        {
            System.IO.File.Delete(PrefixWithUNC(path));
        }

        public void FileSetLastWriteTimeUtc(string path, DateTime time)
        {
            System.IO.File.SetLastWriteTimeUtc(PrefixWithUNC(path), time);
        }

        public void FileSetCreationTimeUtc(string path, DateTime time)
        {
            System.IO.File.SetCreationTimeUtc(PrefixWithUNC(path), time);
        }

        public DateTime FileGetLastWriteTimeUtc(string path)
        {
            return System.IO.File.GetLastWriteTimeUtc(PrefixWithUNC(path));
        }

        public DateTime FileGetCreationTimeUtc(string path)
        {
            return System.IO.File.GetCreationTimeUtc(PrefixWithUNC(path));
        }

        public bool FileExists(string path)
        {
            return System.IO.File.Exists(PrefixWithUNC(path));
        }

        public System.IO.FileStream FileOpenRead(string path)
        {
            return System.IO.File.Open(PrefixWithUNC(path), System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
        }

        public System.IO.FileStream FileOpenWrite(string path)
        {
            return !FileExists(path)
                ? FileCreate(path)
                : System.IO.File.OpenWrite(PrefixWithUNC(path));
        }

        public System.IO.FileStream FileCreate(string path)
        {
            return System.IO.File.Create(PrefixWithUNC(path));
        }

        public System.IO.FileAttributes GetFileAttributes(string path)
        {
            return System.IO.File.GetAttributes(PrefixWithUNC(path));
        }

        public void SetFileAttributes(string path, System.IO.FileAttributes attributes)
        {
            System.IO.File.SetAttributes(PrefixWithUNC(path), attributes);
        }

        /// <summary>
        /// Returns the symlink target if the entry is a symlink, and null otherwise
        /// </summary>
        /// <param name="file">The file or folder to examine</param>
        /// <returns>The symlink target</returns>
        public string GetSymlinkTarget(string file)
        {
            try
            {
                return AlphaFS.File.GetLinkTargetInfo(PrefixWithUNC(file)).PrintName;
            }
            catch (AlphaFS.NotAReparsePointException) { }
            catch (AlphaFS.UnrecognizedReparsePointException) { }

            // This path looks like it isn't actually a symlink
            // (Note that some reparse points aren't actually symlinks -
            // things like the OneDrive folder in the Windows 10 Fall Creator's Update for example)
            return null;
        }

        public IEnumerable<string> EnumerateFileSystemEntries(string path)
        {
            return System.IO.Directory.EnumerateFileSystemEntries(PrefixWithUNC(path)).Select(StripUNCPrefix);
        }

        public IEnumerable<string> EnumerateFiles(string path)
        {
            return System.IO.Directory.EnumerateFiles(PrefixWithUNC(path)).Select(StripUNCPrefix);
        }

        public IEnumerable<string> EnumerateFiles(string path, string searchPattern, SearchOption searchOption)
        {
            return System.IO.Directory.EnumerateFiles(PrefixWithUNC(path), searchPattern,  searchOption).Select(StripUNCPrefix);
        }

        public string PathGetFileName(string path)
        {
            return StripUNCPrefix(System.IO.Path.GetFileName(PrefixWithUNC(path)));
        }

        public string PathGetDirectoryName(string path)
        {
            return StripUNCPrefix(System.IO.Path.GetDirectoryName(PrefixWithUNC(path)));
        }

        public string PathGetExtension(string path)
        {
            return StripUNCPrefix(System.IO.Path.GetExtension(PrefixWithUNC(path)));
        }

        public string PathChangeExtension(string path, string extension)
        {
            return StripUNCPrefix(System.IO.Path.ChangeExtension(PrefixWithUNC(path), extension));
        }

        public void DirectorySetLastWriteTimeUtc(string path, DateTime time)
        {
            System.IO.Directory.SetLastWriteTimeUtc(PrefixWithUNC(path), time);
        }

        public void DirectorySetCreationTimeUtc(string path, DateTime time)
        {
            System.IO.Directory.SetCreationTimeUtc(PrefixWithUNC(path), time);
        }

        public void FileMove(string source, string target)
        {
            System.IO.File.Move(PrefixWithUNC(source), PrefixWithUNC(target));
        }

        public long FileLength(string path)
        {
            return new System.IO.FileInfo(PrefixWithUNC(path)).Length;
        }

        public string GetPathRoot(string path)
        {
            if (IsPrefixedWithUNC(path))
            {
                return Path.GetPathRoot(path);
            }
            else
            {
                return StripUNCPrefix(Path.GetPathRoot(PrefixWithUNC(path)));
            }
        }

        public string[] GetDirectories(string path)
        {
            if (IsPrefixedWithUNC(path))
            {
                return Directory.GetDirectories(path);
            }
            else
            {
                return Directory.GetDirectories(PrefixWithUNC(path)).Select(StripUNCPrefix).ToArray();
            }
        }

        public string[] GetFiles(string path)
        {
            if (IsPrefixedWithUNC(path))
            {
                return Directory.GetFiles(path);
            }
            else
            {
                return Directory.GetFiles(PrefixWithUNC(path)).Select(StripUNCPrefix).ToArray();
            }
        }

        public string[] GetFiles(string path, string searchPattern)
        {
            if (IsPrefixedWithUNC(path))
            {
                return Directory.GetFiles(path, searchPattern);
            }
            else
            {
                return Directory.GetFiles(PrefixWithUNC(path), searchPattern).Select(StripUNCPrefix).ToArray();
            }
        }

        public DateTime GetCreationTimeUtc(string path)
        {
            return Directory.GetCreationTimeUtc(PrefixWithUNC(path));
        }

        public DateTime GetLastWriteTimeUtc(string path)
        {
            return Directory.GetLastWriteTimeUtc(PrefixWithUNC(path));
        }

        public IEnumerable<string> EnumerateDirectories(string path)
        {
            if (IsPrefixedWithUNC(path))
            {
                return Directory.EnumerateDirectories(path);
            }
            else
            {
                return Directory.EnumerateDirectories(PrefixWithUNC(path)).Select(StripUNCPrefix);
            }
        }

        public void FileCopy(string source, string target, bool overwrite)
        {
            File.Copy(PrefixWithUNC(source), PrefixWithUNC(target), overwrite);
        }

        public string PathGetFullPath(string path)
        {
            // Desired behavior:
            // 1. If path is already prefixed with \\?\, it should be left untouched
            // 2. If path is not already prefixed with \\?\, the return value should also not be prefixed
            // 3. If path is relative or has relative components, that should be resolved by calling Path.GetFullPath()
            // 4. If path is not relative and has no relative components, prefix with \\?\ to prevent normalization from munging "problematic Windows paths"
            if (IsPrefixedWithUNC(path))
            {
                return path;
            }
            else
            {
                return StripUNCPrefix(Path.GetFullPath(PrefixWithUNC(path)));
            }
        }

        public IFileEntry DirectoryEntry(string path)
        {
            var dInfo = new DirectoryInfo(PrefixWithUNC(path));
            return new FileEntry(dInfo.Name, 0, dInfo.LastAccessTime, dInfo.LastWriteTime)
            {
                IsFolder = true
            };
        }

        public IFileEntry FileEntry(string path)
        {
            var fileInfo = new FileInfo(PrefixWithUNC(path));
            return new FileEntry(fileInfo.Name, fileInfo.Length, fileInfo.LastAccessTime, fileInfo.LastWriteTime);
        }

        public Dictionary<string, string> GetMetadata(string path, bool isSymlink, bool followSymlink)
        {
            var isDirTarget = path.EndsWith(DIRSEP, StringComparison.Ordinal);
            var targetpath = isDirTarget ? path.Substring(0, path.Length - 1) : path;
            var dict = new Dictionary<string, string>();

            FileSystemSecurity rules = isDirTarget ? GetAccessControlDir(targetpath) : GetAccessControlFile(targetpath);
            var objs = new List<FileSystemAccess>();
            foreach (var f in rules.GetAccessRules(true, false, typeof(System.Security.Principal.SecurityIdentifier)))
                objs.Add(new FileSystemAccess((FileSystemAccessRule)f));

            dict["win-ext:accessrules"] = SerializeObject(objs);

            // Only include the following key when its value is True.
            // This prevents unnecessary 'metadata change' detections when upgrading from
            // older versions (pre-2.0.5.101) that didn't store this value at all.
            // When key is not present, its value is presumed False by the restore code.
            if (rules.AreAccessRulesProtected)
            {
                dict["win-ext:accessrulesprotected"] = "True";
            }

            return dict;
        }

        public void SetMetadata(string path, Dictionary<string, string> data, bool restorePermissions)
        {
            var isDirTarget = path.EndsWith(DIRSEP, StringComparison.Ordinal);
            var targetpath = isDirTarget ? path.Substring(0, path.Length - 1) : path;

            if (restorePermissions)
            {
                FileSystemSecurity rules = isDirTarget ? GetAccessControlDir(targetpath) : GetAccessControlFile(targetpath);

                if (data.ContainsKey("win-ext:accessrulesprotected"))
                {
                    bool isProtected = bool.Parse(data["win-ext:accessrulesprotected"]);
                    if (rules.AreAccessRulesProtected != isProtected)
                    {
                        rules.SetAccessRuleProtection(isProtected, false);
                    }
                }

                if (data.ContainsKey("win-ext:accessrules"))
                {
                    var content = DeserializeObject<FileSystemAccess[]>(data["win-ext:accessrules"]);
                    var c = rules.GetAccessRules(true, false, typeof(System.Security.Principal.SecurityIdentifier));
                    for (var i = c.Count - 1; i >= 0; i--)
                        rules.RemoveAccessRule((System.Security.AccessControl.FileSystemAccessRule)c[i]);

                    Exception ex = null;

                    foreach (var r in content)
                    {
                        // Attempt to apply as many rules as we can
                        try
                        {
                            rules.AddAccessRule(r.Create(rules));
                        }
                        catch (Exception e)
                        {
                            ex = e;
                        }
                    }

                    if (ex != null)
                        throw ex;
                }

                if (isDirTarget)
                    SetAccessControlDir(targetpath, (DirectorySecurity)rules);
                else
                    SetAccessControlFile(targetpath, (FileSecurity)rules);
            }
        }

        public string PathCombine(params string[] paths)
        {
            return Path.Combine(paths);
        }

        public void CreateSymlink(string symlinkfile, string target, bool asDir)
        {
            if (FileExists(symlinkfile) || DirectoryExists(symlinkfile))
                throw new System.IO.IOException(string.Format("File already exists: {0}", symlinkfile));

            if (asDir)
            {
                Alphaleonis.Win32.Filesystem.Directory.CreateSymbolicLink(PrefixWithUNC(symlinkfile), target, AlphaFS.PathFormat.LongFullPath);
            }
            else
            {
                Alphaleonis.Win32.Filesystem.File.CreateSymbolicLink(PrefixWithUNC(symlinkfile), target, AlphaFS.PathFormat.LongFullPath);
            }

            //Sadly we do not get a notification if the creation fails :(
            System.IO.FileAttributes attr = 0;
            if ((!asDir && FileExists(symlinkfile)) || (asDir && DirectoryExists(symlinkfile)))
                try { attr = GetFileAttributes(symlinkfile); }
                catch { }

            if ((attr & System.IO.FileAttributes.ReparsePoint) == 0)
                throw new System.IO.IOException(string.Format("Unable to create symlink, check account permissions: {0}", symlinkfile));
        }
        #endregion
    }
}