-
-
Notifications
You must be signed in to change notification settings - Fork 345
/
Copy pathNetFileCache.cs
296 lines (246 loc) · 9.73 KB
/
NetFileCache.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
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using ChinhDo.Transactions;
using ICSharpCode.SharpZipLib.Zip;
using log4net;
using System.Text.RegularExpressions;
using System.Diagnostics;
using System.Security.Permissions;
namespace CKAN
{
/// <summary>
/// A local cache dedicated to storing and retrieving files based upon their
/// URL.
/// </summary>
// We require fancy permissions to use the FileSystemWatcher
[PermissionSet(SecurityAction.Demand, Name="FullTrust")]
public class NetFileCache : IDisposable
{
private FileSystemWatcher watcher;
private string[] cachedFiles;
private string cachePath;
private static readonly TxFileManager tx_file = new TxFileManager();
private static readonly ILog log = LogManager.GetLogger(typeof (NetFileCache));
public NetFileCache(string _cachePath)
{
// Basic validation, our cache has to exist.
if (!Directory.Exists(_cachePath))
{
throw new DirectoryNotFoundKraken(_cachePath, "Cannot find cache directory");
}
cachePath = _cachePath;
// Establish a watch on our cache. This means we can cache the directory contents,
// and discard that cache if we spot changes.
watcher = new FileSystemWatcher(cachePath, "");
// While we should only care about files appearing and disappearing, I've over-asked
// for permissions to get things to work on Mono.
watcher.NotifyFilter =
NotifyFilters.LastWrite | NotifyFilters.LastAccess | NotifyFilters.DirectoryName | NotifyFilters.FileName;
// If we spot any changes, we fire our event handler.
watcher.Changed += new FileSystemEventHandler(OnCacheChanged);
watcher.Created += new FileSystemEventHandler(OnCacheChanged);
watcher.Deleted += new FileSystemEventHandler(OnCacheChanged);
watcher.Renamed += new RenamedEventHandler(OnCacheChanged);
// Enable events!
watcher.EnableRaisingEvents = true;
}
/// <summary>
/// Releases all resource used by the <see cref="CKAN.NetFileCache"/> object.
/// </summary>
/// <remarks>Call <see cref="Dispose"/> when you are finished using the <see cref="CKAN.NetFileCache"/>. The
/// <see cref="Dispose"/> method leaves the <see cref="CKAN.NetFileCache"/> in an unusable state. After calling
/// <see cref="Dispose"/>, you must release all references to the <see cref="CKAN.NetFileCache"/> so the garbage
/// collector can reclaim the memory that the <see cref="CKAN.NetFileCache"/> was occupying.</remarks>
public void Dispose()
{
// All we really need to do is clear our FileSystemWatcher.
// We disable its event raising capabilities first for good measure.
watcher.EnableRaisingEvents = false;
watcher.Dispose();
}
/// <summary>
/// Called from our FileSystemWatcher. Use OnCacheChanged()
/// without arguments to signal manually.
/// </summary>
private void OnCacheChanged(object source, FileSystemEventArgs e)
{
OnCacheChanged();
}
/// <summary>
/// When our cache dirctory changes, we just clear the list of
/// files we know about.
/// </summary>
public void OnCacheChanged()
{
cachedFiles = null;
}
public string GetCachePath()
{
return cachePath;
}
// returns true if a url is already in the cache
public bool IsCached(Uri url)
{
return GetCachedFilename(url) != null;
}
// returns true if a url is already in the cache
// returns the filename in the outFilename parameter
public bool IsCached(Uri url, out string outFilename)
{
outFilename = GetCachedFilename(url);
return outFilename != null;
}
/// <summary>
/// Returns true if our given URL is cached, *and* it passes zip
/// validation tests. Prefer this over IsCached when working with
/// zip files.
/// </summary>
public bool IsCachedZip(Uri url)
{
return GetCachedZip(url) != null;
}
/// <summary>
/// Returns true if a file matching the given URL is cached, but makes no
/// attempts to check if it's even valid. This is very fast.
///
/// Use IsCachedZip() for a slower but more reliable method.
/// </summary>
public bool IsMaybeCachedZip(Uri url)
{
return GetCachedFilename(url) != null;
}
/// <summary>>
/// Returns the filename of an already cached url or null otherwise
/// </summary>
public string GetCachedFilename(Uri url)
{
log.DebugFormat("Checking cache for {0}", url);
if (url == null)
{
return null;
}
string hash = CreateURLHash(url);
// Use our existing list of files, or retrieve and
// store the list of files in our cache. Note that
// we copy cachedFiles into our own variable as it
// *may* get cleared by OnCacheChanged while we're
// using it.
string[] files = cachedFiles;
if (files == null)
{
log.Debug("Rebuilding cache index");
cachedFiles = files = Directory.GetFiles(cachePath);
}
// Now that we have a list of files one way or another,
// check them to see if we can find the one we're looking
// for.
foreach (string file in files)
{
string filename = Path.GetFileName(file);
if (filename.StartsWith(hash))
{
return file;
}
}
return null;
}
/// <summary>
/// Returns the filename for a cached URL, if and only if it
/// passes zipfile validation tests. Prefer this to GetCachedFilename
/// when working with zip files. Returns null if not available, or
/// validation failed.
///
/// Test data toggles if low level crc checks should be done. This can
/// take time on order of seconds for larger zip files.
/// </summary>
public string GetCachedZip(Uri url, bool test_data = false)
{
string filename = GetCachedFilename(url);
if (filename == null)
{
return null;
}
try
{
using (ZipFile zip = new ZipFile (filename))
{
// Perform CRC check.
if (zip.TestArchive(test_data))
{
return filename;
}
}
}
catch (ZipException)
{
// We ignore these; it just means the file is borked,
// same as failing validation.
}
return null;
}
/// <summary>
/// Stores the results of a given URL in the cache.
/// Description is adjusted to be filesystem-safe and then appended to the file hash when saving.
/// If not present, the filename will be used.
/// If `move` is true, then the file will be moved; otherwise, it will be copied.
///
/// Returns a path to the newly cached file.
///
/// This method is filesystem transaction aware.
/// </summary>
public string Store(Uri url, string path, string description = null, bool move = false)
{
log.DebugFormat("Storing {0}", url);
// Make sure we clear our cache entry first.
Remove(url);
string hash = CreateURLHash(url);
description = description ?? Path.GetFileName(path);
Debug.Assert(
Regex.IsMatch(description, "^[A-Za-z0-9_.-]*$"),
"description isn't as filesystem safe as we thought... (#1266)"
);
string fullName = String.Format("{0}-{1}", hash, Path.GetFileName(description));
string targetPath = Path.Combine(cachePath, fullName);
log.DebugFormat("Storing {0} in {1}", path, targetPath);
if (move)
{
tx_file.Move(path, targetPath);
}
else
{
tx_file.Copy(path, targetPath, true);
}
// We've changed our cache, so signal that immediately.
OnCacheChanged();
return targetPath;
}
/// <summary>
/// Removes the given URL from the cache.
/// Returns true if any work was done, false otherwise.
/// This method is filesystem transaction aware.
/// </summary>
public bool Remove(Uri url)
{
string file = GetCachedFilename(url);
if (file != null)
{
tx_file.Delete(file);
// We've changed our cache, so signal that immediately.
OnCacheChanged();
return true;
}
return false;
}
// returns the 8-byte hash for a given url
public static string CreateURLHash(Uri url)
{
using (var sha1 = new SHA1Cng())
{
byte[] hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(url.ToString()));
return BitConverter.ToString(hash).Replace("-", "").Substring(0, 8);
}
}
}
}