Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
382 lines (351 loc) · 11.3 KB
/
Copy pathindex.js
File metadata and controls
382 lines (351 loc) · 11.3 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
const crypto = require('crypto');
const fs = require('fs');
const net = require('net');
const os = require('os');
const path = require('path');
const { StringDecoder } = require('string_decoder');
const { Loot, IsCompatible, SetLogLevel } = require('./build/Release/node-loot');
const LogLevel = {
trace: 0,
debug: 1,
info: 2,
warning: 3,
error: 4,
};
// where the worker's socket goes: the user's runtime directory, which the desktop spec keeps
// private, when there is a usable one, otherwise the temp directory
function socketDir() {
const runtimeDir = process.env.XDG_RUNTIME_DIR;
if (runtimeDir !== undefined) {
try {
fs.accessSync(runtimeDir, fs.constants.W_OK);
return runtimeDir;
} catch (err) {
// inherited from another user, or from a session that no longer exists
}
}
return os.tmpdir();
}
// the endpoint the worker connects to: a named pipe on Windows, a unix socket elsewhere
function ipcPath() {
const id = crypto.randomUUID();
return process.platform === 'win32'
? `\\\\?\\pipe\\loot-ipc-${id}`
: path.join(socketDir(), `loot-ipc-${id}.sock`);
}
// interface IPluginsNotLoadedArgs {
// name: string;
// plugin: string;
// func: string;
// currentlyLoaded: string[];
// }
class PluginNotLoaded extends Error {
constructor(args) {
const currentlyLoaded = args.currentlyLoaded ?? [];
super(`Plugin not loaded: "${args.plugin}"; currently loaded: ${currentlyLoaded.join(', ')}`);
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
this.plugin = args.plugin;
this.func = args.func;
this.currentlyLoaded = currentlyLoaded;
}
}
class AlreadyClosed extends Error {
constructor() {
super('Already closed');
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
}
}
class RemoteDied extends Error {
constructor(call, code) {
super('LOOT process died');
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
this.call = call;
// the socket error that ended it, where one was reported before it closed
this.code = code;
}
}
// the worker answered with something that is not a message
class InvalidResponse extends Error {
constructor(call, frameBytes, detail) {
super(`Invalid response to "${call}": ${detail}`);
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
this.call = call;
this.frameBytes = frameBytes;
}
}
class LootAsync {
static create(gameId, gamePath, gameLocalPath, language, logCallback, onFork) {
return new Promise((resolve, reject) => {
const res = new LootAsync(gameId, gamePath, gameLocalPath, language, logCallback, onFork,
(err) => (err ? reject(err) : resolve(res)));
});
}
constructor(gameId, gamePath, gameLocalPath, language, logCallback, onFork, callback) {
this.queue = [];
this.logCallback = logCallback;
this.didClose = false;
this.dataBuffer = '';
// the call the worker is answering, named on the errors that end it
this.currentCall = undefined;
// the code of the socket error that closed the pipe, if one was reported
this.socketErrorCode = undefined;
// how many connections to the pipe were not the worker's
this.strayConnections = 0;
// a read can end mid-character; the decoder holds the incomplete sequence back until the
// rest arrives
this.decoder = new StringDecoder('utf8');
if (onFork !== undefined) {
this.onFork = onFork;
} else {
const cp = require('child_process');
this.onFork = (script, args) => {
cp.spawn(process.execPath, [
script,
...args,
]);
}
}
this.initArgs = [
gameId,
gamePath,
gameLocalPath,
language,
];
let initCallback = (err) => {
// ensure the init callback isn't called twice.
initCallback = (err) => {
if (err) {
logCallback(4, err.message);
}
}
callback(err);
}
// every native method runs in the worker, which also answers setLogLevel itself
for (const name of Object.getOwnPropertyNames(Loot.prototype)) {
if (name !== 'constructor') {
this.makeProxy(name);
}
}
this.makeProxy('setLogLevel');
this.ipcPath = ipcPath();
this.ipc = new net.Server();
try {
// this seems to fail for some users with EINVAL. why?
// May be a wine-only problem but that's not confirmed
this.ipc.listen(this.ipcPath, () => {
this.ipc.on('connection', socket => {
// other software, security products in particular, can open the pipe too. The worker is
// the connection that speaks first, and no other connection may take its place
if (this.socket !== undefined) {
this.strayConnection(socket);
return;
}
socket
.on('data', data => {
this.socket ??= socket;
if (socket !== this.socket) {
return;
}
try {
this.dataBuffer += this.decoder.write(data);
const messages = this.dataBuffer.split('\uFFFF');
// Keep incomplete chunk (last element after split if no trailing delimiter)
if (!this.dataBuffer.endsWith('\uFFFF')) {
this.dataBuffer = messages.pop();
} else {
this.dataBuffer = '';
}
// the call a frame in this read may still answer, and the first frame that was no
// answer at all
const answering = this.currentCallback;
let unreadable;
for (const msg of messages) {
if (msg.length === 0) {
continue;
}
let response;
try {
response = JSON.parse(msg);
} catch (err) {
unreadable ??= new InvalidResponse(this.currentCall, msg.length, err.message);
continue;
}
this.handleResponse(response);
}
// a log frame can be the unreadable one, so the call only fails if nothing in the
// read answered it
if (unreadable !== undefined && this.currentCallback === answering) {
this.failCurrent(unreadable);
}
} catch (err) {
this.logCallback(4, err.message);
}
})
.on('error', err => {
if (socket !== this.socket) {
return;
}
// a socket error closes the socket, so the calls waiting on it are failed by the
// close handler; this keeps the reason to tell them why
this.socketErrorCode = err.code;
this.logCallback(4, err.message);
})
.on('close', () => {
if (socket !== this.socket) {
this.strayConnection(socket);
return;
}
// nothing more is coming from the child, so every call waiting on it fails here
const pending = [
{ call: this.currentCall, callback: this.currentCallback },
...this.queue.map((entry) => ({ call: entry.message.type, callback: entry.callback })),
];
this.queue = [];
this.currentCallback = undefined;
this.currentCall = undefined;
for (const { call, callback } of pending) {
if (callback !== undefined) {
callback(new RemoteDied(call, this.socketErrorCode));
}
}
});
})
this.restart().then(() => initCallback(null), initCallback);
})
.on('error', (err) => {
initCallback(err);
});
} catch (err) {
initCallback(new Error('failed to establish IPC endpoint'));
}
}
// another process opened the pipe; counted so the host can tell telemetry how often that happens
strayConnection(socket) {
++this.strayConnections;
this.logCallback(3, 'another process opened the LOOT pipe');
socket.destroy();
}
restart() {
return new Promise((resolve) => {
// a worker started over a live one takes its place on the pipe
if (this.socket !== undefined) {
this.socket.removeAllListeners('close').destroy();
this.socket = undefined;
}
this.worker = this.onFork(`${__dirname}${path.sep}async.js`, [this.ipcPath]);
this.currentCallback = () => resolve(this.request({ type: 'init', args: this.initArgs }));
});
}
close() {
if (this.didClose) {
return;
}
this.enqueue({ type: 'terminate' }, () => {
this.worker = undefined;
// closing the server removes a unix socket's file
this.ipc.close();
});
this.didClose = true;
}
isClosed() {
return this.didClose;
}
makeProxy(name) {
this[name] = (...args) => this.request({ type: name, args });
}
request(message) {
return new Promise((resolve, reject) => {
this.enqueue(message, (err, result) => (err ? reject(err) : resolve(result)));
});
}
enqueue(message, callback) {
if (this.didClose) {
return callback(new AlreadyClosed());
}
if (!this.currentCallback) {
this.deliver(message, callback);
} else {
this.queue.push({ message, callback });
}
}
// fail the call being answered and move on to the next one
failCurrent(err) {
const callback = this.currentCallback;
this.currentCallback = undefined;
this.currentCall = undefined;
this.processQueue();
if (callback !== undefined) {
callback(err);
}
}
deliver(message, callback) {
this.currentCallback = callback;
this.currentCall = message.type;
const handleError = err => {
if (!!err) {
this.failCurrent(err.code === 'EPIPE' ? new RemoteDied(this.currentCall) : err);
}
};
try {
this.socket.write(JSON.stringify(message) + '\uFFFF', handleError);
} catch (err) {
handleError(err);
}
}
processQueue() {
if (this.queue.length > 0) {
const next = this.queue.shift();
this.deliver(next.message, next.callback);
} else {
this.currentCallback = undefined;
}
}
handleResponse(msg) {
// don't touch the queue when relaying logs
if (msg.log) {
this.logCallback(msg.log.level, msg.log.message);
return;
}
// relay result, then process next request in the queue, if any
try {
if (!!this.currentCallback) {
if (msg.error) {
const extraArgs = JSON.parse(msg.extraArgs);
let err;
if (extraArgs.name === 'AlreadyClosed') {
err = new AlreadyClosed();
} else if (extraArgs.name === 'PluginNotLoaded') {
err = new PluginNotLoaded(extraArgs);
} else {
err = new Error(msg.error);
}
Object.assign(err, extraArgs);
this.currentCallback(err);
} else {
this.currentCallback(null, msg.result);
}
}
this.processQueue();
} catch (err) {
// don't want to suppress an error but
// if we don't trigger the queue here, this proxy is dead
this.processQueue();
throw err;
}
}
}
module.exports = {
AlreadyClosed,
InvalidResponse,
LogLevel,
Loot,
LootAsync,
IsCompatible,
PluginNotLoaded,
RemoteDied,
SetLogLevel,
};