Repository navigation
Expand file tree
/
Copy pathLocalBinary.js
More file actions
416 lines (369 loc) · 15.2 KB
/
Copy pathLocalBinary.js
File metadata and controls
416 lines (369 loc) · 15.2 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
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'),
HttpsProxyAgent = require('https-proxy-agent'),
version = require('../package.json').version,
LocalError = require('./LocalError'),
fetchDownloadSourceUrlAsync = require('./fetchDownloadSourceUrlAsync');
const packageName = 'browserstack-local-nodejs';
function LocalBinary(){
this.hostOS = process.platform;
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 };
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;
}
/* Same reasoning as the auth token above: proxy credentials go through the
environment, not argv. */
if (conf.proxyUser && conf.proxyPass) {
env.BROWSERSTACK_LOCAL_PROXY_USER = conf.proxyUser;
env.BROWSERSTACK_LOCAL_PROXY_PASS = conf.proxyPass;
}
const obj = childProcess.spawnSync(cmd, opts, { env: env });
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.useCaCertificate, conf.proxyUser, conf.proxyPass, (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;
};
this.retryBinaryDownload = function(conf, destParentDir, callback, retries, binaryPath) {
var that = this;
if(retries > 0) {
console.log('Retrying Download. Retries left', retries);
/* Single unlink instead of stat-then-unlinkSync: the gap between the two
let a concurrent writer swap the file, and a failing unlinkSync threw
out of the stat callback where it could not be caught. A missing file
is the expected case here, so any error is ignored. */
fs.unlink(binaryPath, function() {
if(!callback) {
return that.downloadSync(conf, destParentDir, retries - 1);
}
that.download(conf, destParentDir, callback, retries - 1);
});
} else {
console.error('Number of retries to download exceeded.');
}
};
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);
if (conf.proxyUser && conf.proxyPass) {
env.BROWSERSTACK_LOCAL_PROXY_USER = conf.proxyUser;
env.BROWSERSTACK_LOCAL_PROXY_PASS = conf.proxyPass;
}
const obj = childProcess.spawnSync(cmd, opts, { env: env });
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) {
return console.error('Unable to fetch the source url to download the binary with error: ', err);
}
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);
var options = url.parse(this.httpPath);
if(conf.proxyHost && conf.proxyPort) {
var proxyOpts = { host: conf.proxyHost, port: conf.proxyPort };
if (conf.proxyUser && conf.proxyPass) {
proxyOpts.auth = `${conf.proxyUser}:${conf.proxyPass}`;
}
options.agent = new HttpsProxyAgent(proxyOpts);
}
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) {
that.binaryDownloadError('Got Error in binary download response', util.format(err));
that.retryBinaryDownload(conf, destParentDir, callback, retries, binaryPath);
});
fileStream.on('error', function (err) {
that.binaryDownloadError('Got Error while downloading binary file', util.format(err));
that.retryBinaryDownload(conf, destParentDir, callback, retries, binaryPath);
});
fileStream.on('close', function () {
fs.chmod(binaryPath, '0755', function() {
callback(binaryPath);
});
});
}).on('error', function(err) {
that.binaryDownloadError('Got Error in binary downloading request', util.format(err));
that.retryBinaryDownload(conf, destParentDir, callback, retries, binaryPath);
});
});
};
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;