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
|
/*
* This file is part of Adblock Plus <http://adblockplus.org/>,
* Copyright (C) 2006-2014 Eyeo GmbH
*
* Adblock Plus is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* Adblock Plus 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Adblock Plus. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @fileOverview Module containing file I/O helpers.
*/
let {Services} = Cu.import("resource://gre/modules/Services.jsm", null);
let {FileUtils} = Cu.import("resource://gre/modules/FileUtils.jsm", null);
let {OS} = Cu.import("resource://gre/modules/osfile.jsm", null);
let {Task} = Cu.import("resource://gre/modules/Task.jsm", null);
let {TimeLine} = require("timeline");
let {Prefs} = require("prefs");
let {Utils} = require("utils");
let firstRead = true;
const BUFFER_SIZE = 0x8000; // 32kB
let IO = exports.IO =
{
/**
* Retrieves the platform-dependent line break string.
*/
get lineBreak()
{
let lineBreak = (Services.appinfo.OS == "WINNT" ? "\r\n" : "\n");
delete IO.lineBreak;
IO.__defineGetter__("lineBreak", () => lineBreak);
return IO.lineBreak;
},
/**
* Tries to interpret a file path as an absolute path or a path relative to
* user's profile. Returns a file or null on failure.
*/
resolveFilePath: function(/**String*/ path) /**nsIFile*/
{
if (!path)
return null;
try {
// Assume an absolute path first
return new FileUtils.File(path);
} catch (e) {}
try {
// Try relative path now
return FileUtils.getFile("ProfD", path.split("/"));
} catch (e) {}
return null;
},
/**
* Reads strings from a file asynchronously, calls listener.process() with
* each line read and with a null parameter once the read operation is done.
* The callback will be called when the operation is done.
*/
readFromFile: function(/**nsIFile*/ file, /**Object*/ listener, /**Function*/ callback, /**String*/ timeLineID)
{
try
{
let processing = false;
let buffer = "";
let loaded = false;
let error = null;
let onProgress = function(data)
{
if (timeLineID)
{
TimeLine.asyncStart(timeLineID);
}
let index = (processing ? -1 : Math.max(data.lastIndexOf("\n"), data.lastIndexOf("\r")));
if (index >= 0)
{
// Protect against reentrance in case the listener processes events.
processing = true;
try
{
let oldBuffer = buffer;
buffer = data.substr(index + 1);
data = data.substr(0, index + 1);
let lines = data.split(/[\r\n]+/);
lines.pop();
lines[0] = oldBuffer + lines[0];
for (let i = 0; i < lines.length; i++)
listener.process(lines[i]);
}
finally
{
processing = false;
data = buffer;
buffer = "";
onProgress(data);
if (loaded)
{
loaded = false;
onSuccess();
}
if (error)
{
let param = error;
error = null;
onError(param);
}
}
}
else
buffer += data;
if (timeLineID)
{
TimeLine.asyncEnd(timeLineID);
}
};
let onSuccess = function()
{
if (processing)
{
// Still processing data, delay processing this event.
loaded = true;
return;
}
if (timeLineID)
{
TimeLine.asyncStart(timeLineID);
}
if (buffer !== "")
listener.process(buffer);
listener.process(null);
if (timeLineID)
{
TimeLine.asyncEnd(timeLineID);
TimeLine.asyncDone(timeLineID);
}
callback(null);
};
let onError = function(e)
{
if (processing)
{
// Still processing data, delay processing this event.
error = e;
return;
}
callback(e);
if (timeLineID)
{
TimeLine.asyncDone(timeLineID);
}
};
let decoder = new TextDecoder();
let array = new Uint8Array(BUFFER_SIZE);
Task.spawn(function()
{
if (firstRead && Services.vc.compare(Utils.platformVersion, "23.0a1") <= 0)
{
// See https://issues.adblockplus.org/ticket/530 - the first file
// opened cannot be closed due to Gecko bug 858723. Make sure that
// our patterns.ini file doesn't stay locked by opening a dummy file
// first.
try
{
let dummyPath = IO.resolveFilePath(Prefs.data_directory + "/dummy").path;
let dummy = yield OS.File.open(dummyPath, {write: true, truncate: true});
yield dummy.close();
}
catch (e)
{
// Dummy might be locked already, we don't care
}
}
firstRead = false;
let f = yield OS.File.open(file.path, {read: true});
let numBytes;
do
{
numBytes = yield f.readTo(array);
if (numBytes)
{
let data = decoder.decode(numBytes == BUFFER_SIZE ?
array :
array.subarray(0, numBytes), {stream: true});
onProgress(data);
}
} while (numBytes);
yield f.close();
}.bind(this)).then(onSuccess, onError);
}
catch (e)
{
callback(e);
}
},
/**
* Writes string data to a file in UTF-8 format asynchronously. The callback
* will be called when the write operation is done.
*/
writeToFile: function(/**nsIFile*/ file, /**Iterator*/ data, /**Function*/ callback, /**String*/ timeLineID)
{
try
{
let encoder = new TextEncoder();
Task.spawn(function()
{
// This mimics OS.File.writeAtomic() but writes in chunks.
let tmpPath = file.path + ".tmp";
let f = yield OS.File.open(tmpPath, {write: true, truncate: true});
let buf = [];
let bufLen = 0;
let lineBreak = this.lineBreak;
function writeChunk()
{
let array = encoder.encode(buf.join(lineBreak) + lineBreak);
buf = [];
bufLen = 0;
return f.write(array);
}
for (let line in data)
{
buf.push(line);
bufLen += line.length;
if (bufLen >= BUFFER_SIZE)
yield writeChunk();
}
if (bufLen)
yield writeChunk();
// OS.File.flush() isn't exposed prior to Gecko 27, see bug 912457.
if (typeof f.flush == "function")
yield f.flush();
yield f.close();
yield OS.File.move(tmpPath, file.path, {noCopy: true});
}.bind(this)).then(callback.bind(null, null), callback);
}
catch (e)
{
callback(e);
}
},
/**
* Copies a file asynchronously. The callback will be called when the copy
* operation is done.
*/
copyFile: function(/**nsIFile*/ fromFile, /**nsIFile*/ toFile, /**Function*/ callback)
{
try
{
let promise = OS.File.copy(fromFile.path, toFile.path);
promise.then(callback.bind(null, null), callback);
}
catch (e)
{
callback(e);
}
},
/**
* Renames a file within the same directory, will call callback when done.
*/
renameFile: function(/**nsIFile*/ fromFile, /**String*/ newName, /**Function*/ callback)
{
try
{
toFile = fromFile.clone();
toFile.leafName = newName;
let promise = OS.File.move(fromFile.path, toFile.path);
promise.then(callback.bind(null, null), callback);
}
catch(e)
{
callback(e);
}
},
/**
* Removes a file, will call callback when done.
*/
removeFile: function(/**nsIFile*/ file, /**Function*/ callback)
{
try
{
let promise = OS.File.remove(file.path);
promise.then(callback.bind(null, null), callback);
}
catch(e)
{
callback(e);
}
},
/**
* Gets file information such as whether the file exists.
*/
statFile: function(/**nsIFile*/ file, /**Function*/ callback)
{
try
{
let promise = OS.File.stat(file.path);
promise.then(function onSuccess(info)
{
callback(null, {
exists: true,
isDirectory: info.isDir,
isFile: !info.isDir,
lastModified: info.lastModificationDate.getTime()
});
}, function onError(e)
{
if (e.becauseNoSuchFile)
{
callback(null, {
exists: false,
isDirectory: false,
isFile: false,
lastModified: 0
});
}
else
callback(e);
});
}
catch(e)
{
callback(e);
}
}
}
|