Repository navigation
Expand file tree
/
Copy pathLocalBinary.js
More file actions
486 lines (431 loc) · 18.1 KB
/
Copy pathLocalBinary.js
File metadata and controls
486 lines (431 loc) · 18.1 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
/* global Atomics, SharedArrayBuffer -- ES2017, used for the blocking wait in
waitWhileBinaryBusySync; declared here rather than widening the lint env. */
var https = require('https'),
fs = require('fs'),
path = require('path'),
os = require('os'),
url = require('url'),
util = require('util'),
childProcess = require('child_process'),
zlib = require('zlib'),
{ buildProxyAgent } = require('./util'),
version = require('../package.json').version,
LocalError = require('./LocalError'),
fetchDownloadSourceUrlAsync = require('./fetchDownloadSourceUrlAsync');
const packageName = 'browserstack-local-nodejs';
function LocalBinary(){
this.hostOS = process.platform;
/* Set here, not only in getBinaryFilename(): binaryPath() reads it before any download. */
this.windows = /mswin|msys|mingw|cygwin|bccwin|wince|emc|win32/i.test(this.hostOS);
this.is64bits = process.arch == 'x64';
this.isArm64 = process.arch == 'arm64';
this.baseRetries = 9;
this.sourceURL = null;
this.downloadErrorMessage = null;
/*
* Per-instance binary-download signalling. Historically these three fields were
* carried on process.env (BINARY_DOWNLOAD_FALLBACK_ENABLED / _ERROR_MESSAGE /
* _SOURCE_URL), which is a process-global mutable store: a failure on one Local
* instance bled into every other instance in the same process, and an attacker
* who could set the env before boot could force this instance to download from
* an arbitrary host. Keep the state on the instance instead. The owning Local
* object shares ONE downloadState object across the LocalBinary instances it
* recreates during a retry loop, so the fallback URL is still cached within a
* single Local instance without leaking across sibling instances.
*/
this.downloadState = { fallbackEnabled: false, errorMessage: null, sourceURL: null };
/* Proxy credentials reach the spawned download scripts through their environment,
never argv — same reason as the auth token. A copy already sitting in process.env
is dropped first so only this instance's settings are used. */
this.addProxyCredentialsToEnv = function(env, conf) {
delete env.BROWSERSTACK_LOCAL_PROXY_USER;
delete env.BROWSERSTACK_LOCAL_PROXY_PASS;
if(conf.proxyHost && conf.proxyPort && conf.proxyUser) {
env.BROWSERSTACK_LOCAL_PROXY_USER = String(conf.proxyUser);
if(conf.proxyPass !== undefined && conf.proxyPass !== null) {
env.BROWSERSTACK_LOCAL_PROXY_PASS = String(conf.proxyPass);
}
}
return env;
};
this.getSourceUrlSync = function(conf, retries) {
/* Request for an endpoint to download the local binary from Rails no more than twice with 5 retries each */
if (![4, 9].includes(retries) && this.sourceURL != null) {
return this.sourceURL;
}
if (this.downloadState.sourceURL != null && this.downloadState.fallbackEnabled && this.parentRetries != 4) {
/* This is triggered from Local.js if there's an error executing the downloaded binary */
return this.downloadState.sourceURL;
}
let cmd, opts;
cmd = 'node';
/* The auth token is handed to the child through its environment, not argv —
argv is readable by any local user via `ps` / /proc/<pid>/cmdline. */
opts = [path.join(__dirname, 'fetchDownloadSourceUrl.js'), this.bsHost];
if (retries == 4 || (this.downloadState.fallbackEnabled && this.parentRetries == 4)) {
opts.push(true, this.downloadErrorMessage || this.downloadState.errorMessage);
} else {
opts.push(false, null);
}
if(conf.proxyHost && conf.proxyPort) {
opts.push(conf.proxyHost, conf.proxyPort);
if (conf.useCaCertificate) {
opts.push(conf.useCaCertificate);
}
} else if (conf.useCaCertificate) {
opts.push(undefined, undefined, conf.useCaCertificate);
}
const userAgent = [packageName, version].join('/');
const env = Object.assign({ 'USER_AGENT': userAgent }, process.env);
if (this.key) {
env.BROWSERSTACK_LOCAL_AUTH_TOKEN = this.key;
}
this.addProxyCredentialsToEnv(env, conf);
const obj = childProcess.spawnSync(cmd, opts, { env: env });
/* stdout is null on a spawn failure; reading .length masked the real cause. */
if(obj.error) {
throw(util.format(obj.error));
}
if(obj.stdout.length > 0) {
this.sourceURL = obj.stdout.toString().replace(/\n+$/, '');
this.downloadState.sourceURL = this.sourceURL;
return this.sourceURL;
} else if(obj.stderr.length > 0) {
let output = Buffer.from(JSON.parse(JSON.stringify(obj.stderr)).data).toString();
throw(output);
}
};
this.getSourceUrl = function(conf, retries, callback) {
/* Request for an endpoint to download the local binary from Rails no more than twice with 5 retries each */
if (![4, 9].includes(retries) && this.sourceURL != null) {
return callback(null, this.sourceURL);
}
if (this.downloadState.sourceURL != null && this.downloadState.fallbackEnabled && this.parentRetries != 4) {
/* This is triggered from Local.js if there's an error executing the downloaded binary */
return callback(null, this.downloadState.sourceURL);
}
let downloadFallback = false;
let downloadErrorMessage = null;
if (retries == 4 || (this.downloadState.fallbackEnabled && this.parentRetries == 4)) {
downloadFallback = true;
downloadErrorMessage = this.downloadErrorMessage || this.downloadState.errorMessage;
}
fetchDownloadSourceUrlAsync(this.key, this.bsHost, downloadFallback, downloadErrorMessage, conf.proxyHost, conf.proxyPort, conf.proxyUser, conf.proxyPass, conf.useCaCertificate, (err, sourceURL) => {
if (err) return callback(err);
this.sourceURL = sourceURL;
this.downloadState.sourceURL = sourceURL;
callback(null, sourceURL);
});
};
this.getBinaryFilename = function() {
if(this.hostOS.match(/darwin|mac os/i)){
return 'BrowserStackLocal-darwin-x64';
} else if(this.hostOS.match(/mswin|msys|mingw|cygwin|bccwin|wince|emc|win32/i)) {
this.windows = true;
return 'BrowserStackLocal.exe';
} else {
if(this.isArm64) {
return 'BrowserStackLocal-linux-arm64';
} else if(this.is64bits) {
if(this.isAlpine())
return 'BrowserStackLocal-alpine';
else
return 'BrowserStackLocal-linux-x64';
} else {
return 'BrowserStackLocal-linux-ia32';
}
}
};
this.getDownloadPath = function (conf, retries, callback) {
this.getSourceUrl(conf, retries, (err, sourceURL) => {
if (err) return callback(err);
callback(null, sourceURL + '/' + this.getBinaryFilename());
});
};
this.isAlpine = function() {
try {
return childProcess.execSync('grep -w "NAME" /etc/os-release').includes('Alpine');
} catch(e) {
return false;
}
};
this.binaryDownloadError = function(errorMessagePrefix, errorMessage) {
console.error(errorMessagePrefix, errorMessage);
this.downloadErrorMessage = errorMessagePrefix + ' : ' + errorMessage;
};
/* A locked binary is transient on Windows (AV scan, a tunnel still releasing
its handle), not a corrupt one. Mirrors the CLI binary's existing probe. */
this.BUSY_ERROR_CODES = ['EBUSY', 'EPERM', 'ETXTBSY', 'EACCES'];
this.BUSY_MAX_WAITS = 3;
this.BUSY_WAIT_MS = 1000;
this.isBinaryBusy = function(binaryPath) {
try {
fs.closeSync(fs.openSync(binaryPath, 'r+'));
return false;
} catch(err) {
return this.BUSY_ERROR_CODES.indexOf(err.code) !== -1;
}
};
/* Blocking by design: the sync path has no event loop to come back to. */
this.waitWhileBinaryBusySync = function(binaryPath) {
for(var i = 0; i < this.BUSY_MAX_WAITS; i++) {
if(!fs.existsSync(binaryPath) || !this.isBinaryBusy(binaryPath)) return;
console.log('Binary is in use, waiting before retrying.');
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, this.BUSY_WAIT_MS);
}
};
this.retryBinaryDownload = function(conf, destParentDir, callback, retries, binaryPath) {
var that = this;
if(retries <= 0) {
console.error('Number of retries to download exceeded.');
/* The async contract has to be completed or Local.start() waits forever.
An empty path is the signal; the caller reports it. */
if(callback) callback();
return;
}
console.log('Retrying Download. Retries left', retries);
/* Must stay synchronous: this return value is what downloadSync ->
binaryPath() -> Local.getBinaryPath hands back. Retrying inside a callback
returned undefined before the retry had done anything. */
if(!callback) {
that.waitWhileBinaryBusySync(binaryPath);
try { fs.unlinkSync(binaryPath); } catch(err) { /* missing or locked */ }
return that.downloadSync(conf, destParentDir, retries - 1);
}
var attemptAsync = function(waitsLeft) {
if(waitsLeft > 0 && fs.existsSync(binaryPath) && that.isBinaryBusy(binaryPath)) {
console.log('Binary is in use, waiting before retrying.');
return setTimeout(function() { attemptAsync(waitsLeft - 1); }, that.BUSY_WAIT_MS);
}
fs.unlink(binaryPath, function() {
that.download(conf, destParentDir, callback, retries - 1);
});
};
attemptAsync(that.BUSY_MAX_WAITS);
};
this.downloadSync = function(conf, destParentDir, retries) {
try {
this.httpPath = this.getSourceUrlSync(conf, retries) + '/' + this.getBinaryFilename();
} catch (e) {
return console.error(`Unable to fetch the source url to download the binary with error: ${e}`);
}
console.log('Downloading in sync');
var that = this;
if(!this.checkPath(destParentDir))
fs.mkdirSync(destParentDir);
var destBinaryName = (this.windows) ? 'BrowserStackLocal.exe' : 'BrowserStackLocal';
var binaryPath = path.join(destParentDir, destBinaryName);
let cmd, opts;
cmd = 'node';
opts = [path.join(__dirname, 'download.js'), binaryPath, this.httpPath];
if(conf.proxyHost && conf.proxyPort) {
opts.push(conf.proxyHost, conf.proxyPort);
if (conf.useCaCertificate) {
opts.push(conf.useCaCertificate);
}
} else if (conf.useCaCertificate) {
opts.push(undefined, undefined, conf.useCaCertificate);
}
try{
const userAgent = [packageName, version].join('/');
const env = Object.assign({ 'USER_AGENT': userAgent }, process.env);
this.addProxyCredentialsToEnv(env, conf);
const obj = childProcess.spawnSync(cmd, opts, { env: env });
if(obj.status !== 0) {
that.binaryDownloadError('Download failed with status', String(obj.status));
return that.retryBinaryDownload(conf, destParentDir, null, retries, binaryPath);
}
if(obj.error) {
that.binaryDownloadError('Download failed with error', util.format(obj.error));
return that.retryBinaryDownload(conf, destParentDir, null, retries, binaryPath);
}
let output;
if(obj.stdout.length > 0) {
if(fs.existsSync(binaryPath)){
fs.chmodSync(binaryPath, '0755');
return binaryPath;
}else{
that.binaryDownloadError('failed to download');
return that.retryBinaryDownload(conf, destParentDir, null, retries, binaryPath);
}
} else if(obj.stderr.length > 0) {
output = Buffer.from(JSON.parse(JSON.stringify(obj.stderr)).data).toString();
that.binaryDownloadError(output);
return that.retryBinaryDownload(conf, destParentDir, null, retries, binaryPath);
}
} catch(err) {
that.binaryDownloadError('Download failed with error', util.format(err));
return that.retryBinaryDownload(conf, destParentDir, null, retries, binaryPath);
}
};
this.download = function(conf, destParentDir, callback, retries){
this.getDownloadPath(conf, retries, (err, downloadUrl) => {
if(err) {
console.error('Unable to fetch the source url to download the binary with error: ', err);
return callback();
}
this.httpPath = downloadUrl;
var that = this;
if(!this.checkPath(destParentDir))
fs.mkdirSync(destParentDir);
var destBinaryName = (this.windows) ? 'BrowserStackLocal.exe' : 'BrowserStackLocal';
var binaryPath = path.join(destParentDir, destBinaryName);
var fileStream = fs.createWriteStream(binaryPath);
/* A failed open and the in-flight request can both report on the same
attempt; one attempt must trigger at most one retry. */
var retried = false;
var retryOnce = function(prefix, err) {
that.binaryDownloadError(prefix, util.format(err));
if(retried) return;
retried = true;
that.retryBinaryDownload(conf, destParentDir, callback, retries, binaryPath);
};
/* Same as lib/download.js: the open() failure lands first. */
fileStream.on('error', function (err) {
retryOnce('Got Error while downloading binary file', err);
});
var options = url.parse(this.httpPath);
var agent = buildProxyAgent(conf.proxyHost, conf.proxyPort, conf.proxyUser, conf.proxyPass);
if(agent) {
options.agent = agent;
}
if (conf.useCaCertificate) {
try {
options.ca = fs.readFileSync(conf.useCaCertificate);
} catch(err) {
console.log('failed to read cert file', err);
}
}
options.headers = Object.assign({}, options.headers, {
'accept-encoding': 'gzip, *',
'user-agent': [packageName, version].join('/'),
});
https.get(options, function (response) {
const contentEncoding = response.headers['content-encoding'];
if (typeof contentEncoding === 'string' && contentEncoding.match(/gzip/i)) {
if (process.env.BROWSERSTACK_LOCAL_DEBUG_GZIP) {
console.info('Using gzip in ' + options.headers['user-agent']);
}
response.pipe(zlib.createGunzip()).pipe(fileStream);
} else {
response.pipe(fileStream);
}
response.on('error', function(err) {
retryOnce('Got Error in binary download response', err);
});
fileStream.on('close', function () {
/* node emits 'close' after 'error' too, so without this a failed
attempt reports success alongside the retry it just started. */
if(retried) return;
fs.chmod(binaryPath, '0755', function() {
callback(binaryPath);
});
});
}).on('error', function(err) {
retryOnce('Got Error in binary downloading request', err);
});
});
};
this.binaryPath = function(conf, bsHost, key, parentRetries, callback){
this.key = key;
this.bsHost = bsHost;
this.parentRetries = parentRetries;
var destParentDir = this.getAvailableDirs();
var destBinaryName = (this.windows) ? 'BrowserStackLocal.exe' : 'BrowserStackLocal';
var binaryPath = path.join(destParentDir, destBinaryName);
if(this.checkPath(binaryPath, fs.X_OK)){
if(!callback) {
return binaryPath;
}
callback(binaryPath);
} else {
let retries = this.baseRetries;
if(!callback) {
return this.downloadSync(conf, destParentDir, retries);
}
this.download(conf, destParentDir, callback, retries);
}
};
this.checkPath = function(path, mode){
mode = mode || (fs.R_OK | fs.W_OK);
try {
fs.accessSync(path, mode);
return true;
} catch(e){
if(typeof fs.accessSync !== 'undefined') return false;
// node v0.10
try {
fs.statSync(path);
return true;
} catch (e){
return false;
}
}
};
this.getAvailableDirs = function(){
for(var i=0; i < this.orderedPaths.length; i++){
var path = this.orderedPaths[i];
// the last entry lives under the shared temp dir — it must be ours alone
var requirePrivate = (i === this.orderedPaths.length - 1);
if(this.makePath(path, requirePrivate))
return path;
}
throw new LocalError('Error trying to download BrowserStack Local binary');
};
this.makePath = function(path, requirePrivate){
try {
if(!this.checkPath(path)){
fs.mkdirSync(path, { mode: 0o700 });
}
return requirePrivate ? this.isUserPrivateDir(path) : true;
} catch(e){
return false;
}
};
/* Only applied to the shared-temp fallback. The binary is written there and
then executed, so that directory must not be writable by anyone but us —
otherwise another local user can swap the binary between the download and
the exec, or pre-create the path as a symlink. Windows has no POSIX mode
bits; there this is a no-op. */
this.isUserPrivateDir = function(dirPath){
if(process.platform === 'win32' || typeof process.getuid !== 'function') return true;
try {
var stats = fs.lstatSync(dirPath);
if(!stats.isDirectory()) return false;
if(stats.uid !== process.getuid()) return false;
// reject group- or world-writable
return (stats.mode & 0o022) === 0;
} catch(e){
return false;
}
};
this.homedir = function() {
if(typeof os.homedir === 'function') return os.homedir();
var env = process.env;
var home = env.HOME;
var user = env.LOGNAME || env.USER || env.LNAME || env.USERNAME;
if (process.platform === 'win32') {
return env.USERPROFILE || env.HOMEDRIVE + env.HOMEPATH || home || null;
}
if (process.platform === 'darwin') {
return home || (user ? '/Users/' + user : null);
}
if (process.platform === 'linux') {
return home || (process.getuid() === 0 ? '/root' : (user ? '/home/' + user : null));
}
return home || null;
};
/* The last entry is a per-user subdirectory of the temp dir rather than the
temp dir itself: os.tmpdir() is /tmp on Linux, which is world-writable, and
the binary name below it is fixed and predictable. */
this.tmpDirPath = function(){
var suffix = (typeof process.getuid === 'function') ? String(process.getuid()) : 'user';
return path.join(os.tmpdir(), 'browserstack-local-' + suffix);
};
this.orderedPaths = [
path.join(this.homedir(), '.browserstack'),
process.cwd(),
this.tmpDirPath()
];
}
module.exports = LocalBinary;