Repository navigation
Expand file tree
/
Copy pathUtility.cs
More file actions
891 lines (737 loc) · 31.7 KB
/
Copy pathUtility.cs
File metadata and controls
891 lines (737 loc) · 31.7 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
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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.Contracts;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Security.Cryptography;
using System.Security.Principal;
using System.Threading;
using Splat;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Net;
using NuGet;
namespace Squirrel
{
static class Utility
{
public static string RemoveByteOrderMarkerIfPresent(string content)
{
return string.IsNullOrEmpty(content) ?
string.Empty : RemoveByteOrderMarkerIfPresent(Encoding.UTF8.GetBytes(content));
}
public static string RemoveByteOrderMarkerIfPresent(byte[] content)
{
byte[] output = { };
if (content == null) {
goto done;
}
Func<byte[], byte[], bool> matches = (bom, src) => {
if (src.Length < bom.Length) return false;
return !bom.Where((chr, index) => src[index] != chr).Any();
};
var utf32Be = new byte[] { 0x00, 0x00, 0xFE, 0xFF };
var utf32Le = new byte[] { 0xFF, 0xFE, 0x00, 0x00 };
var utf16Be = new byte[] { 0xFE, 0xFF };
var utf16Le = new byte[] { 0xFF, 0xFE };
var utf8 = new byte[] { 0xEF, 0xBB, 0xBF };
if (matches(utf32Be, content)) {
output = new byte[content.Length - utf32Be.Length];
} else if (matches(utf32Le, content)) {
output = new byte[content.Length - utf32Le.Length];
} else if (matches(utf16Be, content)) {
output = new byte[content.Length - utf16Be.Length];
} else if (matches(utf16Le, content)) {
output = new byte[content.Length - utf16Le.Length];
} else if (matches(utf8, content)) {
output = new byte[content.Length - utf8.Length];
} else {
output = content;
}
done:
if (output.Length > 0) {
Buffer.BlockCopy(content, content.Length - output.Length, output, 0, output.Length);
}
return Encoding.UTF8.GetString(output);
}
public static IEnumerable<FileInfo> GetAllFilesRecursively(this DirectoryInfo rootPath)
{
Contract.Requires(rootPath != null);
return rootPath.EnumerateFiles("*", SearchOption.AllDirectories);
}
public static IEnumerable<string> GetAllFilePathsRecursively(string rootPath)
{
Contract.Requires(rootPath != null);
return Directory.EnumerateFiles(rootPath, "*", SearchOption.AllDirectories);
}
public static string CalculateFileSHA1(string filePath)
{
Contract.Requires(filePath != null);
using (var stream = File.OpenRead(filePath)) {
return CalculateStreamSHA1(stream);
}
}
public static string CalculateStreamSHA1(Stream file)
{
Contract.Requires(file != null && file.CanRead);
using (var sha1 = SHA1.Create()) {
return BitConverter.ToString(sha1.ComputeHash(file)).Replace("-", String.Empty);
}
}
public static WebClient CreateWebClient()
{
// WHY DOESNT IT JUST DO THISSSSSSSS
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
var ret = new WebClient();
var wp = WebRequest.DefaultWebProxy;
if (wp != null) {
wp.Credentials = CredentialCache.DefaultCredentials;
ret.Proxy = wp;
}
return ret;
}
public static async Task CopyToAsync(string from, string to)
{
Contract.Requires(!String.IsNullOrEmpty(from) && File.Exists(from));
Contract.Requires(!String.IsNullOrEmpty(to));
if (!File.Exists(from)) {
Log().Warn("The file {0} does not exist", from);
// TODO: should we fail this operation?
return;
}
// XXX: SafeCopy
await Task.Run(() => File.Copy(from, to, true));
}
public static void Retry(this Action block, int retries = 2)
{
Contract.Requires(retries > 0);
Func<object> thunk = () => {
block();
return null;
};
thunk.Retry(retries);
}
public static T Retry<T>(this Func<T> block, int retries = 2)
{
Contract.Requires(retries > 0);
while (true) {
try {
T ret = block();
return ret;
} catch (Exception) {
if (retries == 0) {
throw;
}
retries--;
Thread.Sleep(250);
}
}
}
public static Task<Tuple<int, string>> InvokeProcessAsync(string fileName, string arguments, CancellationToken ct, string workingDirectory = "")
{
var psi = new ProcessStartInfo(fileName, arguments);
if (Environment.OSVersion.Platform != PlatformID.Win32NT && fileName.EndsWith (".exe", StringComparison.OrdinalIgnoreCase)) {
psi = new ProcessStartInfo("wine", fileName + " " + arguments);
}
psi.UseShellExecute = false;
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.ErrorDialog = false;
psi.CreateNoWindow = true;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
psi.WorkingDirectory = workingDirectory;
return InvokeProcessAsync(psi, ct);
}
public static async Task<Tuple<int, string>> InvokeProcessAsync(ProcessStartInfo psi, CancellationToken ct)
{
var pi = Process.Start(psi);
await Task.Run(() => {
while (!ct.IsCancellationRequested) {
if (pi.WaitForExit(2000)) return;
}
if (ct.IsCancellationRequested) {
pi.Kill();
ct.ThrowIfCancellationRequested();
}
});
string textResult = await pi.StandardOutput.ReadToEndAsync();
if (String.IsNullOrWhiteSpace(textResult) || pi.ExitCode != 0) {
textResult = (textResult ?? "") + "\n" + await pi.StandardError.ReadToEndAsync();
if (String.IsNullOrWhiteSpace(textResult)) {
textResult = String.Empty;
}
}
return Tuple.Create(pi.ExitCode, textResult.Trim());
}
public static Task ForEachAsync<T>(this IEnumerable<T> source, Action<T> body, int degreeOfParallelism = 4)
{
return ForEachAsync(source, x => Task.Run(() => body(x)), degreeOfParallelism);
}
public static Task ForEachAsync<T>(this IEnumerable<T> source, Func<T, Task> body, int degreeOfParallelism = 4)
{
return Task.WhenAll(
from partition in Partitioner.Create(source).GetPartitions(degreeOfParallelism)
select Task.Run(async () => {
using (partition)
while (partition.MoveNext())
await body(partition.Current);
}));
}
static Lazy<string> directoryChars = new Lazy<string>(() => {
return "abcdefghijklmnopqrstuvwxyz" +
Enumerable.Range(0x03B0, 0x03FF - 0x03B0) // Greek and Coptic
.Concat(Enumerable.Range(0x0400, 0x04FF - 0x0400)) // Cyrillic
.Aggregate(new StringBuilder(), (acc, x) => { acc.Append(Char.ConvertFromUtf32(x)); return acc; })
.ToString();
});
internal static string tempNameForIndex(int index, string prefix)
{
if (index < directoryChars.Value.Length) {
return prefix + directoryChars.Value[index];
}
return prefix + directoryChars.Value[index % directoryChars.Value.Length] + tempNameForIndex(index / directoryChars.Value.Length, "");
}
public static DirectoryInfo GetTempDirectory(string localAppDirectory)
{
var tempDir = Environment.GetEnvironmentVariable("SQUIRREL_TEMP");
tempDir = tempDir ?? Path.Combine(localAppDirectory ?? Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "SquirrelTemp");
var di = new DirectoryInfo(tempDir);
if (!di.Exists) di.Create();
return di;
}
public static IDisposable WithTempDirectory(out string path, string localAppDirectory = null)
{
var di = GetTempDirectory(localAppDirectory);
var tempDir = default(DirectoryInfo);
var names = Enumerable.Range(0, 1<<20).Select(x => tempNameForIndex(x, "temp"));
foreach (var name in names) {
var target = Path.Combine(di.FullName, name);
if (!File.Exists(target) && !Directory.Exists(target)) {
Directory.CreateDirectory(target);
tempDir = new DirectoryInfo(target);
break;
}
}
path = tempDir.FullName;
return Disposable.Create(() => Task.Run(async () => await DeleteDirectory(tempDir.FullName)).Wait());
}
public static IDisposable WithTempFile(out string path, string localAppDirectory = null)
{
var di = GetTempDirectory(localAppDirectory);
var names = Enumerable.Range(0, 1<<20).Select(x => tempNameForIndex(x, "temp"));
path = "";
foreach (var name in names) {
path = Path.Combine(di.FullName, name);
if (!File.Exists(path) && !Directory.Exists(path)) {
break;
}
}
var thePath = path;
return Disposable.Create(() => File.Delete(thePath));
}
public static async Task DeleteDirectory(string directoryPath)
{
Contract.Requires(!String.IsNullOrEmpty(directoryPath));
Log().Debug("Starting to delete folder: {0}", directoryPath);
if (!Directory.Exists(directoryPath)) {
Log().Warn("DeleteDirectory: does not exist - {0}", directoryPath);
return;
}
// From http://stackoverflow.com/questions/329355/cannot-delete-directory-with-directory-deletepath-true/329502#329502
var files = new string[0];
try {
files = Directory.GetFiles(directoryPath);
} catch (UnauthorizedAccessException ex) {
var message = String.Format("The files inside {0} could not be read", directoryPath);
Log().Warn(message, ex);
}
var dirs = new string[0];
try {
dirs = Directory.GetDirectories(directoryPath);
} catch (UnauthorizedAccessException ex) {
var message = String.Format("The directories inside {0} could not be read", directoryPath);
Log().Warn(message, ex);
}
var fileOperations = files.ForEachAsync(file => {
File.SetAttributes(file, FileAttributes.Normal);
File.Delete(file);
});
var directoryOperations =
dirs.ForEachAsync(async dir => await DeleteDirectory(dir));
await Task.WhenAll(fileOperations, directoryOperations);
Log().Debug("Now deleting folder: {0}", directoryPath);
File.SetAttributes(directoryPath, FileAttributes.Normal);
try {
Directory.Delete(directoryPath, false);
} catch (Exception ex) {
var message = String.Format("DeleteDirectory: could not delete - {0}", directoryPath);
Log().ErrorException(message, ex);
}
}
public static string FindHelperExecutable(string toFind, IEnumerable<string> additionalDirs = null)
{
additionalDirs = additionalDirs ?? Enumerable.Empty<string>();
var dirs = (new[] { Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) })
.Concat(additionalDirs ?? Enumerable.Empty<string>());
var exe = @".\" + toFind;
return dirs
.Select(x => Path.Combine(x, toFind))
.FirstOrDefault(x => File.Exists(x)) ?? exe;
}
static string find7Zip()
{
if (ModeDetector.InUnitTestRunner()) {
var vendorDir = Path.Combine(
Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase.Replace("file:///", "")),
"..", "..", "..", "..",
"vendor", "7zip"
);
return FindHelperExecutable("7z.exe", new[] { vendorDir });
} else {
return FindHelperExecutable("7z.exe");
}
}
public static async Task ExtractZipToDirectory(string zipFilePath, string outFolder)
{
var sevenZip = find7Zip();
var result = default(Tuple<int, string>);
try {
var cmd = sevenZip;
var args = String.Format("x \"{0}\" -tzip -mmt on -aoa -y -o\"{1}\" *", zipFilePath, outFolder);
if (Environment.OSVersion.Platform != PlatformID.Win32NT) {
cmd = "wine";
args = sevenZip + " " + args;
}
result = await Utility.InvokeProcessAsync(cmd, args, CancellationToken.None);
if (result.Item1 != 0) throw new Exception(result.Item2);
} catch (Exception ex) {
Log().Error($"Failed to extract file {zipFilePath} to {outFolder}\n{ex.Message}");
throw;
}
}
public static async Task CreateZipFromDirectory(string zipFilePath, string inFolder)
{
var sevenZip = find7Zip();
var result = default(Tuple<int, string>);
try {
var cmd = sevenZip;
var args = String.Format("a \"{0}\" -tzip -aoa -y -mmt on *", zipFilePath);
if (Environment.OSVersion.Platform != PlatformID.Win32NT) {
cmd = "wine";
args = sevenZip + " " + args;
}
result = await Utility.InvokeProcessAsync(cmd, args, CancellationToken.None, inFolder);
if (result.Item1 != 0) throw new Exception(result.Item2);
} catch (Exception ex) {
Log().Error($"Failed to extract file {zipFilePath} to {inFolder}\n{ex.Message}");
throw;
}
}
public static string AppDirForRelease(string rootAppDirectory, ReleaseEntry entry)
{
return Path.Combine(rootAppDirectory, "app-" + entry.Version.ToString());
}
public static string AppDirForVersion(string rootAppDirectory, SemanticVersion version)
{
return Path.Combine(rootAppDirectory, "app-" + version.ToString());
}
public static string PackageDirectoryForAppDir(string rootAppDirectory)
{
return Path.Combine(rootAppDirectory, "packages");
}
public static string LocalReleaseFileForAppDir(string rootAppDirectory)
{
return Path.Combine(PackageDirectoryForAppDir(rootAppDirectory), "RELEASES");
}
public static IEnumerable<ReleaseEntry> LoadLocalReleases(string localReleaseFile)
{
var file = File.OpenRead(localReleaseFile);
// NB: sr disposes file
using (var sr = new StreamReader(file, Encoding.UTF8)) {
return ReleaseEntry.ParseReleaseFile(sr.ReadToEnd());
}
}
public static ReleaseEntry FindCurrentVersion(IEnumerable<ReleaseEntry> localReleases)
{
if (!localReleases.Any()) {
return null;
}
return localReleases.OrderByDescending(x => x.Version).FirstOrDefault(x => !x.IsDelta);
}
static TAcc scan<T, TAcc>(this IEnumerable<T> This, TAcc initialValue, Func<TAcc, T, TAcc> accFunc)
{
TAcc acc = initialValue;
foreach (var x in This)
{
acc = accFunc(acc, x);
}
return acc;
}
public static bool IsHttpUrl(string urlOrPath)
{
var uri = default(Uri);
if (!Uri.TryCreate(urlOrPath, UriKind.Absolute, out uri)) {
return false;
}
return uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps;
}
public static Uri AppendPathToUri(Uri uri, string path)
{
var builder = new UriBuilder(uri);
if (!builder.Path.EndsWith("/")) {
builder.Path += "/";
}
builder.Path += path;
return builder.Uri;
}
public static Uri EnsureTrailingSlash(Uri uri)
{
return AppendPathToUri(uri, "");
}
public static Uri AddQueryParamsToUri(Uri uri, IEnumerable<KeyValuePair<string, string>> newQuery)
{
var query = System.Web.HttpUtility.ParseQueryString(uri.Query);
foreach (var entry in newQuery) {
query[entry.Key] = entry.Value;
}
var builder = new UriBuilder(uri);
builder.Query = query.ToString();
return builder.Uri;
}
public static void DeleteFileHarder(string path, bool ignoreIfFails = false)
{
try {
Retry(() => File.Delete(path), 2);
} catch (Exception ex) {
if (ignoreIfFails) return;
LogHost.Default.ErrorException("Really couldn't delete file: " + path, ex);
throw;
}
}
public static async Task DeleteDirectoryOrJustGiveUp(string dir)
{
try {
await Utility.DeleteDirectory(dir);
} catch {
var message = String.Format("Uninstall failed to delete dir '{0}'", dir);
}
}
// http://stackoverflow.com/questions/3111669/how-can-i-determine-the-subsystem-used-by-a-given-net-assembly
public static bool ExecutableUsesWin32Subsystem(string peImage)
{
using (var s = new FileStream(peImage, FileMode.Open, FileAccess.Read)) {
var rawPeSignatureOffset = new byte[4];
s.Seek(0x3c, SeekOrigin.Begin);
s.Read(rawPeSignatureOffset, 0, 4);
int peSignatureOffset = rawPeSignatureOffset[0];
peSignatureOffset |= rawPeSignatureOffset[1] << 8;
peSignatureOffset |= rawPeSignatureOffset[2] << 16;
peSignatureOffset |= rawPeSignatureOffset[3] << 24;
var coffHeader = new byte[24];
s.Seek(peSignatureOffset, SeekOrigin.Begin);
s.Read(coffHeader, 0, 24);
byte[] signature = { (byte)'P', (byte)'E', (byte)'\0', (byte)'\0' };
for (int index = 0; index < 4; index++) {
if (coffHeader[index] != signature[index]) throw new Exception("File is not a PE image");
}
var subsystemBytes = new byte[2];
s.Seek(68, SeekOrigin.Current);
s.Read(subsystemBytes, 0, 2);
int subSystem = subsystemBytes[0] | subsystemBytes[1] << 8;
return subSystem == 2; /*IMAGE_SUBSYSTEM_WINDOWS_GUI*/
}
}
readonly static string[] peExtensions = new[] { ".exe", ".dll", ".node" };
public static bool FileIsLikelyPEImage(string name)
{
var ext = Path.GetExtension(name);
return peExtensions.Any(x => ext.Equals(x, StringComparison.OrdinalIgnoreCase));
}
public static bool IsFileTopLevelInPackage(string fullName, string pkgPath)
{
var fn = fullName.ToLowerInvariant();
var pkg = pkgPath.ToLowerInvariant();
var relativePath = fn.Replace(pkg, "");
// NB: We want to match things like `/lib/net45/foo.exe` but not `/lib/net45/bar/foo.exe`
return relativePath.Split(Path.DirectorySeparatorChar).Length == 4;
}
public static void LogIfThrows(this IFullLogger This, LogLevel level, string message, Action block)
{
try {
block();
} catch (Exception ex) {
switch (level) {
case LogLevel.Debug:
This.DebugException(message ?? "", ex);
break;
case LogLevel.Info:
This.InfoException(message ?? "", ex);
break;
case LogLevel.Warn:
This.WarnException(message ?? "", ex);
break;
case LogLevel.Error:
This.ErrorException(message ?? "", ex);
break;
}
throw;
}
}
public static async Task LogIfThrows(this IFullLogger This, LogLevel level, string message, Func<Task> block)
{
try {
await block();
} catch (Exception ex) {
switch (level) {
case LogLevel.Debug:
This.DebugException(message ?? "", ex);
break;
case LogLevel.Info:
This.InfoException(message ?? "", ex);
break;
case LogLevel.Warn:
This.WarnException(message ?? "", ex);
break;
case LogLevel.Error:
This.ErrorException(message ?? "", ex);
break;
}
throw;
}
}
public static async Task<T> LogIfThrows<T>(this IFullLogger This, LogLevel level, string message, Func<Task<T>> block)
{
try {
return await block();
} catch (Exception ex) {
switch (level) {
case LogLevel.Debug:
This.DebugException(message ?? "", ex);
break;
case LogLevel.Info:
This.InfoException(message ?? "", ex);
break;
case LogLevel.Warn:
This.WarnException(message ?? "", ex);
break;
case LogLevel.Error:
This.ErrorException(message ?? "", ex);
break;
}
throw;
}
}
public static void WarnIfThrows(this IEnableLogger This, Action block, string message = null)
{
This.Log().LogIfThrows(LogLevel.Warn, message, block);
}
public static Task WarnIfThrows(this IEnableLogger This, Func<Task> block, string message = null)
{
return This.Log().LogIfThrows(LogLevel.Warn, message, block);
}
public static Task<T> WarnIfThrows<T>(this IEnableLogger This, Func<Task<T>> block, string message = null)
{
return This.Log().LogIfThrows(LogLevel.Warn, message, block);
}
public static void ErrorIfThrows(this IEnableLogger This, Action block, string message = null)
{
This.Log().LogIfThrows(LogLevel.Error, message, block);
}
public static Task ErrorIfThrows(this IEnableLogger This, Func<Task> block, string message = null)
{
return This.Log().LogIfThrows(LogLevel.Error, message, block);
}
public static Task<T> ErrorIfThrows<T>(this IEnableLogger This, Func<Task<T>> block, string message = null)
{
return This.Log().LogIfThrows(LogLevel.Error, message, block);
}
static IFullLogger logger;
static IFullLogger Log()
{
return logger ??
(logger = Locator.CurrentMutable.GetService<ILogManager>().GetLogger(typeof(Utility)));
}
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
static extern bool MoveFileEx(string lpExistingFileName, string lpNewFileName, MoveFileFlags dwFlags);
[Flags]
enum MoveFileFlags
{
MOVEFILE_REPLACE_EXISTING = 0x00000001,
MOVEFILE_COPY_ALLOWED = 0x00000002,
MOVEFILE_DELAY_UNTIL_REBOOT = 0x00000004,
MOVEFILE_WRITE_THROUGH = 0x00000008,
MOVEFILE_CREATE_HARDLINK = 0x00000010,
MOVEFILE_FAIL_IF_NOT_TRACKABLE = 0x00000020
}
public static Guid CreateGuidFromHash(string text)
{
return CreateGuidFromHash(text, Utility.IsoOidNamespace);
}
public static Guid CreateGuidFromHash(byte[] data)
{
return CreateGuidFromHash(data, Utility.IsoOidNamespace);
}
public static Guid CreateGuidFromHash(string text, Guid namespaceId)
{
return CreateGuidFromHash(Encoding.UTF8.GetBytes(text), namespaceId);
}
public static Guid CreateGuidFromHash(byte[] nameBytes, Guid namespaceId)
{
// convert the namespace UUID to network order (step 3)
byte[] namespaceBytes = namespaceId.ToByteArray();
SwapByteOrder(namespaceBytes);
// comput the hash of the name space ID concatenated with the
// name (step 4)
byte[] hash;
using (var algorithm = SHA1.Create()) {
algorithm.TransformBlock(namespaceBytes, 0, namespaceBytes.Length, null, 0);
algorithm.TransformFinalBlock(nameBytes, 0, nameBytes.Length);
hash = algorithm.Hash;
}
// most bytes from the hash are copied straight to the bytes of
// the new GUID (steps 5-7, 9, 11-12)
var newGuid = new byte[16];
Array.Copy(hash, 0, newGuid, 0, 16);
// set the four most significant bits (bits 12 through 15) of
// the time_hi_and_version field to the appropriate 4-bit
// version number from Section 4.1.3 (step 8)
newGuid[6] = (byte)((newGuid[6] & 0x0F) | (5 << 4));
// set the two most significant bits (bits 6 and 7) of the
// clock_seq_hi_and_reserved to zero and one, respectively
// (step 10)
newGuid[8] = (byte)((newGuid[8] & 0x3F) | 0x80);
// convert the resulting UUID to local byte order (step 13)
SwapByteOrder(newGuid);
return new Guid(newGuid);
}
/// <summary>
/// The namespace for fully-qualified domain names (from RFC 4122, Appendix C).
/// </summary>
public static readonly Guid DnsNamespace = new Guid("6ba7b810-9dad-11d1-80b4-00c04fd430c8");
/// <summary>
/// The namespace for URLs (from RFC 4122, Appendix C).
/// </summary>
public static readonly Guid UrlNamespace = new Guid("6ba7b811-9dad-11d1-80b4-00c04fd430c8");
/// <summary>
/// The namespace for ISO OIDs (from RFC 4122, Appendix C).
/// </summary>
public static readonly Guid IsoOidNamespace = new Guid("6ba7b812-9dad-11d1-80b4-00c04fd430c8");
// Converts a GUID (expressed as a byte array) to/from network order (MSB-first).
static void SwapByteOrder(byte[] guid)
{
SwapBytes(guid, 0, 3);
SwapBytes(guid, 1, 2);
SwapBytes(guid, 4, 5);
SwapBytes(guid, 6, 7);
}
static void SwapBytes(byte[] guid, int left, int right)
{
byte temp = guid[left];
guid[left] = guid[right];
guid[right] = temp;
}
}
static unsafe class UnsafeUtility
{
public static List<Tuple<string, int>> EnumerateProcesses()
{
int bytesReturned = 0;
var pids = new int[2048];
fixed(int* p = pids) {
if (!NativeMethods.EnumProcesses((IntPtr)p, sizeof(int) * pids.Length, out bytesReturned)) {
throw new Win32Exception("Failed to enumerate processes");
}
if (bytesReturned < 1) throw new Exception("Failed to enumerate processes");
}
return Enumerable.Range(0, bytesReturned / sizeof(int))
.Where(i => pids[i] > 0)
.Select(i => {
try {
var hProcess = NativeMethods.OpenProcess(ProcessAccess.QueryLimitedInformation, false, pids[i]);
if (hProcess == IntPtr.Zero) throw new Win32Exception();
var sb = new StringBuilder(256);
var capacity = sb.Capacity;
if (!NativeMethods.QueryFullProcessImageName(hProcess, 0, sb, ref capacity)) {
throw new Win32Exception();
}
NativeMethods.CloseHandle(hProcess);
return Tuple.Create(sb.ToString(), pids[i]);
} catch (Exception) {
return Tuple.Create(default(string), pids[i]);
}
})
.ToList();
}
}
sealed class SingleGlobalInstance : IDisposable, IEnableLogger
{
IDisposable handle = null;
public SingleGlobalInstance(string key, TimeSpan timeOut)
{
if (ModeDetector.InUnitTestRunner()) {
return;
}
var path = Path.Combine(Path.GetTempPath(), ".squirrel-lock-" + key);
var st = new Stopwatch();
st.Start();
var fh = default(FileStream);
while (st.Elapsed < timeOut) {
try {
fh = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Delete);
fh.Write(new byte[] { 0xba, 0xad, 0xf0, 0x0d, }, 0, 4);
break;
} catch (Exception ex) {
this.Log().WarnException("Failed to grab lockfile, will retry: " + path, ex);
Thread.Sleep(250);
}
}
st.Stop();
if (fh == null) {
throw new Exception("Couldn't acquire lock, is another instance running");
}
handle = Disposable.Create(() => {
fh.Dispose();
File.Delete(path);
});
}
public void Dispose()
{
if (ModeDetector.InUnitTestRunner()) {
return;
}
var disp = Interlocked.Exchange(ref handle, null);
if (disp != null) disp.Dispose();
}
~SingleGlobalInstance()
{
if (handle == null) return;
throw new AbandonedMutexException("Leaked a Mutex!");
}
}
static class Disposable
{
public static IDisposable Create(Action action)
{
return new AnonDisposable(action);
}
class AnonDisposable : IDisposable
{
static readonly Action dummyBlock = (() => { });
Action block;
public AnonDisposable(Action b)
{
block = b;
}
public void Dispose()
{
Interlocked.Exchange(ref block, dummyBlock)();
}
}
}
}