-
Notifications
You must be signed in to change notification settings - Fork 351
/
Copy pathadb.js
477 lines (388 loc) · 12.8 KB
/
adb.js
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
/* @flow */
import ADBKit from '@devicefarmer/adbkit';
import { isErrorWithCode, UsageError, WebExtError } from '../errors.js';
import { createLogger } from '../util/logger.js';
import packageIdentifiers, {
defaultApkComponents,
} from '../firefox/package-identifiers.js';
export const DEVICE_DIR_BASE = '/data/local/tmp/';
export const ARTIFACTS_DIR_PREFIX = 'web-ext-artifacts-';
const defaultADB = ADBKit.default;
const log = createLogger(import.meta.url);
export type ADBUtilsParams = {|
adb?: typeof defaultADB,
// ADB configs.
adbBin?: string,
adbHost?: string,
adbPort?: string,
adbDevice?: string,
|};
export type DiscoveryParams = {
maxDiscoveryTime: number,
retryInterval: number,
};
// Helper function used to raise an UsageError when the adb binary has not been found.
async function wrapADBCall(asyncFn: (...any) => Promise<any>): Promise<any> {
try {
return await asyncFn();
} catch (error) {
if (
isErrorWithCode('ENOENT', error) &&
error.message.includes('spawn adb')
) {
throw new UsageError(
'No adb executable has been found. ' +
'You can Use --adb-bin, --adb-host/--adb-port ' +
'to configure it manually if needed.'
);
}
throw error;
}
}
export default class ADBUtils {
params: ADBUtilsParams;
adb: typeof defaultADB;
adbClient: any; // TODO: better flow typing here.
// Map<deviceId -> artifactsDir>
artifactsDirMap: Map<string, string>;
// Toggled when the user wants to abort the RDP Unix Socket discovery loop
// while it is still executing.
userAbortDiscovery: boolean;
// Toggled when the user wants to abort the Start Activity loop
// while it is still executing.
userAbortStartActivity: boolean;
constructor(params: ADBUtilsParams) {
this.params = params;
const { adb, adbBin, adbHost, adbPort } = params;
this.adb = adb || defaultADB;
this.adbClient = this.adb.createClient({
bin: adbBin,
host: adbHost,
port: adbPort,
});
this.artifactsDirMap = new Map();
this.userAbortDiscovery = false;
this.userAbortStartActivity = false;
}
runShellCommand(
deviceId: string,
cmd: string | Array<string>
): Promise<string> {
const { adb, adbClient } = this;
log.debug(`Run adb shell command on ${deviceId}: ${JSON.stringify(cmd)}`);
return wrapADBCall(async () => {
return await adbClient
.getDevice(deviceId)
.shell(cmd)
.then(adb.util.readAll);
}).then((res) => res.toString());
}
async discoverDevices(): Promise<Array<string>> {
const { adbClient } = this;
let devices = [];
log.debug('Listing android devices');
devices = await wrapADBCall(async () => adbClient.listDevices());
return devices.map((dev) => dev.id);
}
async discoverInstalledFirefoxAPKs(
deviceId: string,
firefoxApk?: string
): Promise<Array<string>> {
log.debug(`Listing installed Firefox APKs on ${deviceId}`);
const pmList = await this.runShellCommand(deviceId, [
'pm',
'list',
'packages',
]);
return pmList
.split('\n')
.map((line) => line.replace('package:', '').trim())
.filter((line) => {
// Look for an exact match if firefoxApk is defined.
if (firefoxApk) {
return line === firefoxApk;
}
// Match any package name that starts with the package name of a Firefox for Android browser.
for (const browser of packageIdentifiers) {
if (line.startsWith(browser)) {
return true;
}
}
return false;
});
}
async getAndroidVersionNumber(deviceId: string): Promise<number> {
const androidVersion = (
await this.runShellCommand(deviceId, ['getprop', 'ro.build.version.sdk'])
).trim();
const androidVersionNumber = parseInt(androidVersion);
// No need to check the granted runtime permissions on Android versions < Lollypop.
if (isNaN(androidVersionNumber)) {
throw new WebExtError(
'Unable to discovery android version on ' +
`${deviceId}: ${androidVersion}`
);
}
return androidVersionNumber;
}
// Raise an UsageError when the given APK does not have the required runtime permissions.
async ensureRequiredAPKRuntimePermissions(
deviceId: string,
apk: string,
permissions: Array<string>
): Promise<void> {
const permissionsMap = {};
// Initialize every permission to false in the permissions map.
for (const perm of permissions) {
permissionsMap[perm] = false;
}
// Retrieve the permissions information for the given apk.
const pmDumpLogs = (
await this.runShellCommand(deviceId, ['pm', 'dump', apk])
).split('\n');
// Set to true the required permissions that have been granted.
for (const line of pmDumpLogs) {
for (const perm of permissions) {
if (
line.includes(`${perm}: granted=true`) ||
line.includes(`${perm}, granted=true`)
) {
permissionsMap[perm] = true;
}
}
}
for (const perm of permissions) {
if (!permissionsMap[perm]) {
throw new UsageError(
`Required ${perm} has not be granted for ${apk}. ` +
'Please grant them using the Android Settings ' +
'or using the following adb command:\n' +
`\t adb shell pm grant ${apk} ${perm}\n`
);
}
}
}
async amForceStopAPK(deviceId: string, apk: string): Promise<void> {
await this.runShellCommand(deviceId, ['am', 'force-stop', apk]);
}
async getOrCreateArtifactsDir(deviceId: string): Promise<string> {
let artifactsDir = this.artifactsDirMap.get(deviceId);
if (artifactsDir) {
return artifactsDir;
}
artifactsDir = `${DEVICE_DIR_BASE}${ARTIFACTS_DIR_PREFIX}${Date.now()}`;
const testDirOut = (
await this.runShellCommand(deviceId, `test -d ${artifactsDir} ; echo $?`)
).trim();
if (testDirOut !== '1') {
throw new WebExtError(
`Cannot create artifacts directory ${artifactsDir} ` +
`because it exists on ${deviceId}.`
);
}
await this.runShellCommand(deviceId, ['mkdir', '-p', artifactsDir]);
this.artifactsDirMap.set(deviceId, artifactsDir);
return artifactsDir;
}
async detectOrRemoveOldArtifacts(
deviceId: string,
removeArtifactDirs?: boolean = false
): Promise<boolean> {
const { adbClient } = this;
log.debug('Checking adb device for existing web-ext artifacts dirs');
return wrapADBCall(async () => {
const files = await adbClient
.getDevice(deviceId)
.readdir(DEVICE_DIR_BASE);
let found = false;
for (const file of files) {
if (
!file.isDirectory() ||
!file.name.startsWith(ARTIFACTS_DIR_PREFIX)
) {
continue;
}
// Return earlier if we only need to warn the user that some
// existing artifacts dirs have been found on the adb device.
if (!removeArtifactDirs) {
return true;
}
found = true;
const artifactsDir = `${DEVICE_DIR_BASE}${file.name}`;
log.debug(
`Removing artifacts directory ${artifactsDir} from device ${deviceId}`
);
await this.runShellCommand(deviceId, ['rm', '-rf', artifactsDir]);
}
return found;
});
}
async clearArtifactsDir(deviceId: string): Promise<void> {
const artifactsDir = this.artifactsDirMap.get(deviceId);
if (!artifactsDir) {
// nothing to do here.
return;
}
this.artifactsDirMap.delete(deviceId);
log.debug(
`Removing ${artifactsDir} artifacts directory on ${deviceId} device`
);
await this.runShellCommand(deviceId, ['rm', '-rf', artifactsDir]);
}
async pushFile(
deviceId: string,
localPath: string,
devicePath: string
): Promise<void> {
const { adbClient } = this;
log.debug(`Pushing ${localPath} to ${devicePath} on ${deviceId}`);
await wrapADBCall(async () => {
await adbClient
.getDevice(deviceId)
.push(localPath, devicePath)
.then(function (transfer) {
return new Promise((resolve) => {
transfer.on('end', resolve);
});
});
});
}
async startFirefoxAPK(
deviceId: string,
apk: string,
apkComponent: ?string,
deviceProfileDir: string
): Promise<void> {
const { adbClient } = this;
log.debug(`Starting ${apk} on ${deviceId}`);
// Fenix does ignore the -profile parameter, on the contrary Fennec
// would run using the given path as the profile to be used during
// this execution.
const extras = [
{
key: 'args',
value: `-profile ${deviceProfileDir}`,
},
];
if (!apkComponent) {
apkComponent = '.App';
if (defaultApkComponents[apk]) {
apkComponent = defaultApkComponents[apk];
}
} else if (!apkComponent.includes('.')) {
apkComponent = `.${apkComponent}`;
}
// if `apk` is a browser package or the `apk` has a
// browser package prefix: prepend the package identifier
// before `apkComponent`
if (apkComponent.startsWith('.')) {
for (const browser of packageIdentifiers) {
if (apk === browser || apk.startsWith(`${browser}.`)) {
apkComponent = browser + apkComponent;
}
}
}
// if `apkComponent` starts with a '.', then adb will expand
// the following to: `${apk}/${apk}.${apkComponent}`
const component = `${apk}/${apkComponent}`;
let exception;
wrapADBCall(async () => {
await adbClient.getDevice(deviceId).startActivity({
wait: true,
action: 'android.activity.MAIN',
component,
extras,
});
})
.then(() => {
exception = null;
})
.catch((err) => {
exception = err;
});
// Wait for the activity to be started.
while (exception === undefined) {
if (this.userAbortStartActivity) {
throw new UsageError('Exiting Firefox Start Activity on user request');
}
await new Promise((resolve) => setTimeout(resolve, 1000));
}
if (exception) {
throw exception;
}
}
setUserAbortDiscovery(value: boolean) {
this.userAbortDiscovery = value;
}
setUserAbortStartActivity(value: boolean) {
this.userAbortStartActivity = value;
}
async discoverRDPUnixSocket(
deviceId: string,
apk: string,
{ maxDiscoveryTime, retryInterval }: DiscoveryParams = {}
): Promise<string> {
let rdpUnixSockets = [];
const discoveryStartedAt = Date.now();
const msg =
`Waiting for ${apk} Remote Debugging Server...` +
'\nMake sure to enable "Remote Debugging via USB" ' +
'from Settings -> Developer Tools if it is not yet enabled.';
while (rdpUnixSockets.length === 0) {
log.info(msg);
if (this.userAbortDiscovery) {
throw new UsageError(
'Exiting Firefox Remote Debugging socket discovery on user request'
);
}
if (Date.now() - discoveryStartedAt > maxDiscoveryTime) {
throw new WebExtError(
'Timeout while waiting for the Android Firefox Debugger Socket'
);
}
rdpUnixSockets = (
await this.runShellCommand(deviceId, ['cat', '/proc/net/unix'])
)
.split('\n')
.filter((line) => {
// The RDP unix socket is expected to be a path in the form:
// /data/data/org.mozilla.fennec_rpl/firefox-debugger-socket
return line.trim().endsWith(`${apk}/firefox-debugger-socket`);
});
if (rdpUnixSockets.length === 0) {
await new Promise((resolve) => setTimeout(resolve, retryInterval));
}
}
// Convert into an array of unix socket filenames.
rdpUnixSockets = rdpUnixSockets.map((line) => {
return line.trim().split(/\s/).pop();
});
if (rdpUnixSockets.length > 1) {
throw new WebExtError(
'Unexpected multiple RDP sockets: ' +
`${JSON.stringify(rdpUnixSockets)}`
);
}
return rdpUnixSockets[0];
}
async setupForward(deviceId: string, remote: string, local: string) {
const { adbClient } = this;
// TODO(rpl): we should use adb.listForwards and reuse the existing one if any (especially
// because adbkit doesn't seem to support `adb forward --remote` yet).
log.debug(`Configuring ADB forward for ${deviceId}: ${remote} -> ${local}`);
await wrapADBCall(async () => {
await adbClient.getDevice(deviceId).forward(local, remote);
});
}
}
export async function listADBDevices(adbBin?: string): Promise<Array<string>> {
const adbUtils = new ADBUtils({ adbBin });
return adbUtils.discoverDevices();
}
export async function listADBFirefoxAPKs(
deviceId: string,
adbBin?: string
): Promise<Array<string>> {
const adbUtils = new ADBUtils({ adbBin });
return adbUtils.discoverInstalledFirefoxAPKs(deviceId);
}