-
-
Notifications
You must be signed in to change notification settings - Fork 167
/
adb.js
1700 lines (1544 loc) · 52.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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use strict";
var spawn = require('child_process').spawn
, path = require('path')
, fs = require('fs')
, net = require('net')
, mkdirp = require('mkdirp')
, logger = require('./logger')
, async = require('async')
, ncp = require('ncp')
, _ = require('underscore')
, helpers = require('./helpers')
, unzipFile = helpers.unzipFile
, testZipArchive = helpers.testZipArchive
, AdmZip = require('adm-zip')
, rimraf = require('rimraf')
, Logcat = require('./logcat')
, isWindows = helpers.isWindows()
, tempDir = require('appium-support').tempDir
, mv = require('mv')
, helperJarPath = path.resolve(__dirname, '../jars')
, logger = require('./logger')
, getDirectories = helpers.getDirectories
, prettyExec = helpers.prettyExec;
var ADB = function (opts) {
if (!opts) {
opts = {};
}
if (typeof opts.sdkRoot === "undefined") {
opts.sdkRoot = process.env.ANDROID_HOME || '';
}
this.sdkRoot = opts.sdkRoot;
this.udid = opts.udid;
this.appDeviceReadyTimeout = opts.appDeviceReadyTimeout;
this.useKeystore = opts.useKeystore;
this.keystorePath = opts.keystorePath;
this.keystorePassword = opts.keystorePassword;
this.keyAlias = opts.keyAlias;
this.keyPassword = opts.keyPassword;
this.adb = {path: "adb", defaultArgs:[]};
this.tmpDir = opts.tmpDir;
if (opts.remoteAdbHost) {
this.adb.defaultArgs.push("-H", opts.remoteAdbHost);
}
if (opts.remoteAdbPort) {
this.adb.defaultArgs.push("-P", opts.remoteAdbPort);
}
this.curDeviceId = null;
this.emulatorPort = null;
this.logcat = null;
this.binaries = {};
this.instrumentProc = null;
this.javaVersion = opts.javaVersion;
this.suppressKillServer = opts.suppressAdbKillServer;
this.jars = {};
_(['move_manifest.jar', 'sign.jar', 'appium_apk_tools.jar', 'unsign.jar',
'verify.jar']).each(function (jarName) {
this.jars[jarName] = path.resolve(__dirname, '../jars', jarName);
}.bind(this));
if (!this.javaVersion || parseFloat(this.javaVersion) < 1.7) {
this.jars["appium_apk_tools.jar"] = path.resolve(__dirname, '../jars', "appium_apk_tools_1.6.jar");
}
};
// exposing logger
ADB.logger = logger;
ADB.createADB = function (opts, cb) {
var adb = new ADB(opts);
adb.checkAdbPresent(function (err) {
cb(err, adb);
});
};
ADB.prototype.checkSdkBinaryPresent = function (binary, cb) {
logger.debug("Checking whether " + binary + " is present");
var binaryLoc = null;
var binaryName = binary;
var cmd = "which";
if (isWindows) {
if (binaryName === "android") {
binaryName += ".bat";
} else {
if (binaryName.indexOf(".exe", binaryName.length - 4) === -1) {
binaryName += ".exe";
}
}
cmd = "where";
}
if (this.sdkRoot) {
var binaryLocs = [path.resolve(this.sdkRoot, "platform-tools", binaryName)
, path.resolve(this.sdkRoot, "tools", binaryName)];
// get subpaths for currently installed build tool directories
var buildToolDirs = getDirectories(path.resolve(this.sdkRoot, "build-tools"));
_.each(buildToolDirs, function (versionDir) {
binaryLocs.push(path.resolve(this.sdkRoot, "build-tools", versionDir, binaryName));
}.bind(this));
_.each(binaryLocs, function (loc) {
if (fs.existsSync(loc)) binaryLoc = loc;
});
if (binaryLoc === null) {
cb(new Error("Could not find " + binary + " in tools, platform-tools, " +
"or supported build-tools under \"" + this.sdkRoot + "\"; " +
"do you have the Android SDK installed at this location?"));
return;
}
binaryLoc = binaryLoc.trim();
logger.debug("Using " + binary + " from " + binaryLoc);
this.binaries[binary] = binaryLoc;
cb(null, binaryLoc);
} else {
logger.warn("The ANDROID_HOME environment variable is not set to the Android SDK root directory path. " +
"ANDROID_HOME is required for compatibility with SDK 23+. Checking along PATH for " + binary + ".");
prettyExec(cmd, [binary], { maxBuffer: 524288 }, function (err, stdout) {
if (stdout) {
logger.debug("Using " + binary + " from " + stdout);
this.binaries[binary] = '"' + stdout.trim() + '"';
cb(null, this.binaries[binary]);
} else {
cb(new Error("Could not find " + binary + ". Please set the ANDROID_HOME " +
"environment variable with the Android SDK root directory path."));
}
}.bind(this));
}
};
ADB.prototype.checkAdbPresent = function (cb) {
this.checkSdkBinaryPresent("adb", function (err, binaryLoc) {
if (err) return cb(err);
this.adb.path = binaryLoc;
cb(null, this.adb);
}.bind(this));
};
ADB.prototype.checkAaptPresent = function (cb) {
this.checkSdkBinaryPresent("aapt", cb);
};
ADB.prototype.checkZipAlignPresent = function (cb) {
this.checkSdkBinaryPresent("zipalign", cb);
};
ADB.prototype.exec = function (cmd, opts, cb) {
if (!cb && typeof opts === 'function') {
cb = opts;
opts = {};
}
if (!cmd) {
return cb(new Error("You need to pass in a command to exec()"));
}
opts = _.defaults(opts, {maxBuffer: 524288, wrapArgs: false});
var retryNum = 2;
async.retry(retryNum, function (_cb) {
prettyExec(this.adb.path, this.adb.defaultArgs.concat([cmd]),
opts, function (err, stdout, stderr) {
var linkerWarningRe = /^WARNING: linker.+$/m;
// sometimes ADB prints out stupid stdout warnings that we don't want
// to include in any of the response data, so let's strip it out
stdout = stdout.replace(linkerWarningRe, '').trim();
if (err) {
var protocolFaultError = new RegExp("protocol fault \\(no status\\)", "i").test(stderr);
var deviceNotFoundError = new RegExp("error: device not found", "i").test(stderr);
if (protocolFaultError || deviceNotFoundError) {
logger.info("error sending command, reconnecting device and retrying: " + cmd);
return setTimeout(function () {
this.getDevicesWithRetry(function (err, devices) {
if (err) return _cb(new Error("Reconnect failed, devices are: " + devices));
_cb(new Error(stderr)); // we've reconnected, so get back into the retry loop
});
}.bind(this), 1000);
}
return cb(err); // shortcut retry and fall out since we have a non-recoverable error
} else {
cb(null, stdout, stderr); // shortcut retry and respond with success
}
}.bind(this));
}.bind(this), function (err) {
if (err) return cb(err); // if we retry too many times, we'll get the error here, the success case is handled in the retry loop
});
};
ADB.prototype.shell = function (cmd, cb) {
if (cmd.indexOf('"') === -1) {
cmd = '"' + cmd + '"';
}
var execCmd = 'shell ' + cmd;
this.exec(execCmd, cb);
};
ADB.prototype.spawn = function (args) {
logger.debug("spawning: " + [this.adb.path].concat(this.adb.defaultArgs, args).join(" "));
return spawn(this.adb.path, this.adb.defaultArgs.concat(args));
};
// android:process= may be defined in AndroidManifest.xml
// http://developer.android.com/reference/android/R.attr.html#process
// note that the process name when used with ps must be truncated to the last 15 chars
// ps -c com.example.android.apis becomes ps -c le.android.apis
ADB.prototype.processFromManifest = function (localApk, cb) {
this.checkAaptPresent(function (err) {
if (err) return cb(err);
logger.debug("Retrieving process from manifest.");
prettyExec(this.binaries.aapt, ['dump', 'xmltree', localApk, 'AndroidManifest.xml'],
{ maxBuffer: 524288 }, function (err, stdout, stderr) {
if (err || stderr) {
logger.warn(stderr);
return cb(new Error("processFromManifest failed. " + err));
}
var result = null;
var lines = stdout.split("\n");
var applicationRegex = new RegExp(/\s+E: application \(line=\d+\).*/);
var applicationFound = false;
var attributeRegex = new RegExp(/\s+A: .+/);
var processRegex = new RegExp(/\s+A: android:process\(0x01010011\)="([^"]+).*"/);
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
if (!applicationFound) {
if (applicationRegex.test(line)) {
applicationFound = true;
}
} else {
var notAttribute = !attributeRegex.test(line);
// process must be an attribute after application.
if (notAttribute) {
break;
}
var process = processRegex.exec(line);
// this is an application attribute process.
if (process && process.length > 1) {
result = process[1];
// must trim to last 15 for android's ps binary
if (result.length > 15) result = result.substr(result.length - 15);
break;
}
}
}
cb(null, result);
});
}.bind(this));
};
ADB.prototype.packageAndLaunchActivityFromManifest = function (localApk, cb) {
this.checkAaptPresent(function (err) {
if (err) return cb(err);
logger.debug("Extracting package and launch activity from manifest.");
prettyExec(this.binaries.aapt, ['dump', 'badging', localApk], { maxBuffer: 524288 }, function (err, stdout, stderr) {
if (err || stderr) {
logger.warn(stderr);
return cb(new Error("packageAndLaunchActivityFromManifest failed. " + err));
}
var apkPackage = new RegExp(/package: name='([^']+)'/g).exec(stdout);
if (apkPackage && apkPackage.length >= 2) {
apkPackage = apkPackage[1];
} else {
apkPackage = null;
}
var apkActivity = new RegExp(/launchable-activity: name='([^']+)'/g).exec(stdout);
if (apkActivity && apkActivity.length >= 2) {
apkActivity = apkActivity[1];
} else {
apkActivity = null;
}
logger.debug("badging package: " + apkPackage);
logger.debug("badging act: " + apkActivity);
cb(null, apkPackage, apkActivity);
});
}.bind(this));
};
ADB.prototype.processExists = function (processName, cb) {
if (!this.isValidClass(processName)) return cb(new Error("Invalid process name: " + processName));
this.shell("ps", function (err, out) {
if (err) return cb(err);
var exists = _.find(out.split(/\r?\n/), function (line) {
line = line.trim().split(/\s+/);
var pkgColumn = line[line.length - 1];
if (pkgColumn && pkgColumn.indexOf(processName) !== -1) {
return pkgColumn;
}
});
exists = exists ? true : false;
logger.debug("process: " + processName + " exists:" + exists);
cb(null, exists);
});
};
ADB.prototype.compileManifest = function (manifest, manifestPackage,
targetPackage, cb) {
logger.debug("Compiling manifest " + manifest);
var platform = helpers.getAndroidPlatform();
if (!platform || !platform[1]) {
return cb(new Error("Required platform doesn't exist (API level >= 17)"));
}
logger.debug('Compiling manifest.');
prettyExec(this.binaries.aapt,
['package', '-M', manifest, '--rename-manifest-package', manifestPackage,
'--rename-instrumentation-target-package', targetPackage, '-I',
path.resolve(platform[1], 'android.jar'), '-F', manifest + '.apk', '-f'],
{ maxBuffer: 524288 }, function (err, stdout, stderr) {
if (err) {
logger.debug(stderr);
return cb("error compiling manifest");
}
logger.debug("Compiled manifest");
cb();
});
};
ADB.prototype.insertManifest = function (manifest, srcApk, dstApk, cb) {
logger.debug("Inserting manifest, src: " + srcApk + ", dst: " + dstApk);
var extractManifest = function (cb) {
logger.debug("Extracting manifest");
// Extract compiled manifest from manifest.xml.apk
unzipFile(manifest + '.apk', function (err, stderr) {
if (err) {
logger.debug("Error unzipping manifest apk, here's stderr:");
logger.debug(stderr);
return cb(err);
}
cb();
});
};
var createTmpApk = function (cb) {
logger.debug("Writing tmp apk. " + srcApk + ' to ' + dstApk);
ncp(srcApk, dstApk, cb);
};
var testDstApk = function (cb) {
logger.debug("Testing new tmp apk.");
testZipArchive(dstApk, cb);
};
var moveManifest = function (cb) {
if (isWindows) {
var java = path.resolve(process.env.JAVA_HOME, 'bin', 'java');
if (isWindows) java = java + '.exe';
logger.debug("Moving manifest.");
prettyExec(java,
['-jar', path.resolve(helperJarPath, 'move_manifest.jar'),
dstApk, manifest],
{ maxBuffer: 524288 }, function (err) {
if (err) {
logger.debug("Got error moving manifest: " + err);
return cb(err);
}
logger.debug("Inserted manifest.");
cb(null);
});
} else {
// Insert compiled manifest into /tmp/appPackage.clean.apk
// -j = keep only the file, not the dirs
// -m = move manifest into target apk.
logger.debug("Moving manifest.");
prettyExec('zip', ['-j', '-m', dstApk, manifest], { maxBuffer: 524288 }, function (err) {
if (err) {
logger.debug("Got error moving manifest: " + err);
return cb(err);
}
logger.debug("Inserted manifest.");
cb();
});
}
};
async.series([
function (cb) { extractManifest(cb); },
function (cb) { createTmpApk(cb); },
function (cb) { testDstApk(cb); },
function (cb) { moveManifest(cb); }
], cb);
};
ADB.prototype.signWithDefaultCert = function (apk, cb) {
var signPath = path.resolve(helperJarPath, 'sign.jar');
logger.debug("Resigning apk.");
prettyExec('java', ['-jar', signPath, apk, '--override'],
{ maxBuffer: 524288 }, function (err, stdout, stderr) {
if (stderr.indexOf("Input is not an existing file") !== -1) {
logger.warn("Could not resign apk, got non-existing file error");
return cb(new Error("Could not sign apk. Are you sure " +
"the file path is correct: " +
JSON.stringify(apk)));
}
cb(err);
});
};
ADB.prototype.signWithCustomCert = function (apk, cb) {
var jarsigner = path.resolve(process.env.JAVA_HOME, 'bin', 'jarsigner');
if (isWindows) jarsigner = jarsigner + '.exe';
var java = path.resolve(process.env.JAVA_HOME, 'bin', 'java');
if (isWindows) java = java + '.exe';
if (!fs.existsSync(this.keystorePath)) {
return cb(new Error("Keystore doesn't exist. " + this.keystorePath));
}
logger.debug("Unsigning apk.");
prettyExec(java,
['-jar', path.resolve(helperJarPath, 'unsign.jar'), apk],
{ maxBuffer: 524288 }, function (err, stdout, stderr) {
if (err || stderr) {
logger.warn(stderr);
return cb(new Error("Could not unsign apk. Are you sure " +
"the file path is correct: " +
JSON.stringify(apk)));
}
logger.debug("Signing apk.");
prettyExec(
jarsigner,
['-sigalg', 'MD5withRSA', '-digestalg', 'SHA1', '-keystore', this.keystorePath,
'-storepass', this.keystorePassword, '-keypass', this.keyPassword, apk,
this.keyAlias],
{ maxBuffer: 524288 }, function (err, stdout, stderr) {
if (err || stderr) {
logger.warn(stderr);
return cb(new Error("Could not sign apk. Are you sure " +
"the file path is correct: " +
JSON.stringify(apk)));
}
cb(err);
}.bind(this));
}.bind(this));
};
ADB.prototype.sign = function (apk, cb) {
async.series([
function (cb) {
if (this.useKeystore) {
this.signWithCustomCert(apk, cb);
} else {
this.signWithDefaultCert(apk, cb);
}
}.bind(this),
function (cb) { this.zipAlignApk(apk, cb); }.bind(this),
], cb);
};
ADB.prototype.zipAlignApk = function (apk, cb) {
logger.debug("Zip-aligning " + apk);
this.checkZipAlignPresent(function (err) {
if (err) return cb(err);
var alignedApk = tempDir.path({prefix: 'appium', suffix: '.tmp'});
mkdirp.sync(path.dirname(alignedApk));
logger.debug("Zip-aligning apk.");
prettyExec(this.binaries.zipalign,
['-f', '4', apk, alignedApk], { maxBuffer: 524288 }, function (err, stdout, stderr) {
if (err || stderr) {
logger.warn(stderr);
return cb(new Error("zipAlignApk failed. " + err));
}
mv(alignedApk, apk, { mkdirp: true }, cb);
});
}.bind(this));
};
// returns true when already signed, false otherwise.
ADB.prototype.checkApkCert = function (apk, pkg, cb) {
if (!fs.existsSync(apk)) {
logger.debug("APK doesn't exist. " + apk);
return cb(null, false);
}
if (this.useKeystore) {
return this.checkCustomApkCert(apk, pkg, cb);
}
logger.debug("Checking app cert for " + apk + ".");
prettyExec('java',
['-jar', path.resolve(helperJarPath, 'verify.jar'), apk],
{ maxBuffer: 524288 }, function (err) {
if (err) {
logger.debug("App not signed with debug cert.");
return cb(null, false);
}
logger.debug("App already signed.");
this.zipAlignApk(apk, function (err) {
if (err) return cb(err);
cb(null, true);
});
}.bind(this));
};
ADB.prototype.checkCustomApkCert = function (apk, pkg, cb) {
var h = "a-fA-F0-9";
var md5Str = ['.*MD5.*((?:[', h, ']{2}:){15}[', h, ']{2})'].join('');
var md5 = new RegExp(md5Str, 'mi');
if (!process.env.JAVA_HOME) return cb(new Error("JAVA_HOME is not set"));
fs.exists(process.env.JAVA_HOME, function (exists) {
if (!exists) return cb(new Error("JAVA_HOME is not set or the directory does not exist: " + process.env.JAVA_HOME));
var keytool = path.resolve(process.env.JAVA_HOME, 'bin', 'keytool');
keytool = isWindows ? '"' + keytool + '.exe"' : '"' + keytool + '"';
this.getKeystoreMd5(keytool, md5, function (err, keystoreHash) {
if (err) return cb(err);
this.checkApkKeystoreMatch(keytool, md5, keystoreHash, pkg, apk, cb);
}.bind(this));
}.bind(this));
};
ADB.prototype.getKeystoreMd5 = function (keytool, md5re, cb) {
var keystoreHash;
logger.debug("Printing keystore md5.");
prettyExec(keytool,
['-v', '-list', '-alias', this.keyAlias,
'-keystore', this.keystorePath, '-storepass',
this.keystorePassword],
{ maxBuffer: 524288 }, function (err, stdout) {
if (err) return cb(err);
keystoreHash = md5re.exec(stdout);
keystoreHash = keystoreHash ? keystoreHash[1] : null;
logger.debug('Keystore MD5: ' + keystoreHash);
cb(null, keystoreHash);
});
};
ADB.prototype.checkApkKeystoreMatch = function (keytool, md5re, keystoreHash,
pkg, apk, cb) {
var entryHash = null;
var zip = new AdmZip(apk);
var rsa = /^META-INF\/.*\.[rR][sS][aA]$/;
var entries = zip.getEntries();
var numEntries = entries.length;
var responded = false;
var examined = 0;
var onExamine = function (err, matched) {
examined++;
if (!responded) {
if (err) {
responded = true;
return cb(err);
} else if (matched) {
responded = true;
return cb(null, true);
} else if (examined === numEntries) {
responded = true;
return cb(null, false);
}
}
};
var checkMd5 = function (err, stdout) {
if (responded) return;
entryHash = md5re.exec(stdout);
entryHash = entryHash ? entryHash[1] : null;
logger.debug('entryHash MD5: ' + entryHash);
logger.debug(' keystore MD5: ' + keystoreHash);
var matchesKeystore = entryHash && entryHash === keystoreHash;
logger.debug('Matches keystore? ' + matchesKeystore);
onExamine(null, matchesKeystore);
};
while (entries.length > 0) {
if (responded) break;
var entry = entries.pop(); // meta-inf tends to be at the end
entry = entry.entryName;
if (!rsa.test(entry)) {
onExamine(null, false);
continue;
}
logger.debug("Entry: " + entry);
var entryPath = path.join(this.tmpDir, pkg, 'cert');
logger.debug("entryPath: " + entryPath);
var entryFile = path.join(entryPath, entry);
logger.debug("entryFile: " + entryFile);
// ensure /tmp/pkg/cert/ doesn't exist or extract will fail.
rimraf.sync(entryPath);
// META-INF/CERT.RSA
zip.extractEntryTo(entry, entryPath, true); // overwrite = true
logger.debug("extracted!");
// check for match
logger.debug("Printing apk md5.");
prettyExec(keytool,
['-v', '-printcert', '-file', entryFile],
{ maxBuffer: 524288 }, checkMd5);
}
};
ADB.prototype.getDevicesWithRetry = function (timeoutMs, cb) {
if (typeof timeoutMs === "function") {
cb = timeoutMs;
timeoutMs = 20000;
}
var start = Date.now();
logger.debug("Trying to find a connected android device");
var error = new Error("Could not find a connected Android device.");
var getDevices = function () {
this.getConnectedDevices(function (err, devices) {
if (err || devices.length < 1) {
if ((Date.now() - start) > timeoutMs) {
cb(error);
} else {
logger.debug("Could not find devices, restarting adb server...");
setTimeout(function () {
this.restartAdb(function () {
getDevices();
}.bind(this));
}.bind(this), 1000);
}
} else {
cb(null, devices);
}
}.bind(this));
}.bind(this);
getDevices();
};
ADB.prototype.getApiLevel = function (cb) {
logger.debug("Getting device API level");
this.shell("getprop ro.build.version.sdk", function (err, stdout) {
if (err) {
logger.warn(err);
cb(err);
} else {
logger.debug("Device is at API Level " + stdout.trim());
cb(null, stdout);
}
});
};
ADB.prototype.getEmulatorPort = function (cb) {
logger.debug("Getting running emulator port");
if (this.emulatorPort !== null) {
return cb(null, this.emulatorPort);
}
this.getConnectedDevices(function (err, devices) {
if (err || devices.length < 1) {
cb(new Error("No devices connected"));
} else {
// pick first device
var port = this.getPortFromEmulatorString(devices[0].udid);
if (port) {
cb(null, port);
} else {
cb(new Error("Emulator port not found"));
}
}
}.bind(this));
};
ADB.prototype.rimraf = function (path, cb) {
this.shell('rm -rf ' + path, cb);
};
ADB.prototype.push = function (localPath, remotePath, cb) {
try {
localPath = JSON.parse(localPath);
} catch (e) { }
localPath = JSON.stringify(localPath);
this.exec('push ' + localPath + ' ' + remotePath, cb);
};
ADB.prototype.pull = function (remotePath, localPath, cb) {
try {
localPath = JSON.parse(localPath);
} catch (e) { }
localPath = JSON.stringify(localPath);
this.exec('pull ' + remotePath + ' ' + localPath, cb);
};
ADB.prototype.getPortFromEmulatorString = function (emStr) {
var portPattern = /emulator-(\d+)/;
if (portPattern.test(emStr)) {
return parseInt(portPattern.exec(emStr)[1], 10);
}
return false;
};
ADB.prototype.getRunningAVD = function (avdName, cb) {
logger.debug("Trying to find " + avdName + " emulator");
this.getConnectedEmulators(function (err, emulators) {
if (err || emulators.length < 1) {
return cb(new Error("No emulators connected"), null);
} else {
async.forEach(emulators, function (emulator, asyncCb) {
this.setEmulatorPort(emulator.port);
this.sendTelnetCommand("avd name", function (err, runningAVDName) {
if (avdName === runningAVDName) {
logger.debug("Found emulator " + avdName + " in port " + emulator.port);
this.setDeviceId(emulator.udid);
return cb(null, emulator);
}
asyncCb();
}.bind(this));
}.bind(this), function (err) {
logger.debug("Emulator " + avdName + " not running");
cb(err, null);
});
}
}.bind(this));
};
ADB.prototype.getRunningAVDWithRetry = function (avdName, timeoutMs, cb) {
var start = Date.now();
var error = new Error("Could not find " + avdName + " emulator.");
var getAVD = function () {
this.getRunningAVD(avdName.replace('@', ''), function (err, runningAVD) {
if (err || runningAVD === null) {
if ((Date.now() - start) > timeoutMs) {
cb(error);
} else {
setTimeout(function () {
getAVD();
}.bind(this), 2000);
}
} else {
cb();
}
}.bind(this));
}.bind(this);
getAVD();
};
ADB.prototype.killAllEmulators = function (cb) {
var cmd, args;
if (isWindows) {
cmd = 'TASKKILL';
args = ['TASKKILL' ,'/IM', 'emulator.exe'];
} else {
cmd = '/usr/bin/killall';
args = ['-m', 'emulator*'];
}
prettyExec(cmd, args, { maxBuffer: 524288 }, function (err) {
if (err) {
logger.debug("Could not kill emulator. It was probably not running.: " +
err.message);
}
cb();
});
};
ADB.prototype.launchAVD = function (avdName, avdArgs, language, locale, avdLaunchTimeout,
avdReadyTimeout, cb, retry) {
if (typeof retry === "undefined") {
retry = 0;
}
logger.debug("Launching Emulator with AVD " + avdName + ", launchTimeout " +
avdLaunchTimeout + "ms and readyTimeout " + avdReadyTimeout +
"ms");
this.checkSdkBinaryPresent("emulator", function (err, emulatorBinaryPath) {
if (err) return cb(err);
if (avdName[0] === "@") {
avdName = avdName.substr(1);
}
var launchArgs = ["-avd", avdName];
if (typeof language === "string") {
logger.debug("Setting Android Device Language to " + language);
launchArgs.push("-prop", "persist.sys.language=" + language.toLowerCase());
}
if (typeof locale === "string") {
logger.debug("Setting Android Device Country to " + locale);
launchArgs.push("-prop", "persist.sys.country=" + locale.toUpperCase());
}
if (typeof avdArgs === "string") {
avdArgs = avdArgs.split(" ");
launchArgs = launchArgs.concat(avdArgs);
}
var proc = spawn(emulatorBinaryPath,
launchArgs);
proc.on("error", function (err) {
logger.error("Unable to start Emulator: " + err.message);
// actual error will get caught by getRunningAVDWithRetry
});
proc.stderr.on('data', function (data) {
logger.error("Unable to start Emulator: " + data);
});
proc.stdout.on('data', function (data) {
if (data.toString().indexOf('ERROR') > -1) {
logger.error("Unable to start Emulator: " + data);
}
});
this.getRunningAVDWithRetry(avdName.replace('@', ''), avdLaunchTimeout,
function (err) {
if (err) {
if (retry < 1) {
logger.warn("Emulator never became active. Going to retry once");
proc.kill();
return this.launchAVD(avdName, avdArgs, language, locale, avdLaunchTimeout,
avdReadyTimeout, cb, retry + 1);
} else {
return cb(err);
}
}
this.waitForEmulatorReady(avdReadyTimeout, cb);
}.bind(this));
}.bind(this));
};
ADB.prototype.waitForEmulatorReady = function (timeoutMs, cb) {
var start = Date.now();
var error = new Error("Emulator is not ready.");
logger.debug("Waiting until emulator is ready");
var getBootAnimStatus = function () {
this.shell("getprop init.svc.bootanim", function (err, stdout) {
if (err || stdout === null || stdout.indexOf('stopped') !== 0) {
if ((Date.now() - start) > timeoutMs) {
cb(error);
} else {
setTimeout(function () {
getBootAnimStatus();
}.bind(this), 3000);
}
} else {
cb();
}
}.bind(this));
}.bind(this);
getBootAnimStatus();
};
ADB.prototype.getConnectedDevices = function (cb) {
logger.debug("Getting connected devices...");
this.exec("devices", function (err, stdout) {
if (err) return cb(err);
if (stdout.toLowerCase().indexOf("error") !== -1) {
logger.error(stdout);
cb(new Error(stdout));
} else {
var devices = [];
_.each(stdout.split("\n"), function (line) {
if (line.trim() !== "" &&
line.indexOf("List of devices") === -1 &&
line.indexOf("* daemon") === -1 &&
line.indexOf("offline") === -1) {
var lineInfo = line.split("\t");
// state is either "device" or "offline", afaict
devices.push({udid: lineInfo[0], state: lineInfo[1]});
}
});
logger.debug(devices.length + " device(s) connected");
cb(null, devices);
}
}.bind(this));
};
ADB.prototype.getConnectedEmulators = function (cb) {
logger.debug("Getting connected emulators");
this.getConnectedDevices(function (err, devices) {
if (err) return cb(err);
var emulators = [];
_.each(devices, function (device) {
var port = this.getPortFromEmulatorString(device.udid);
if (port) {
device.port = port;
emulators.push(device);
}
}.bind(this));
logger.debug(emulators.length + " emulator(s) connected");
cb(null, emulators);
}.bind(this));
};
ADB.prototype.forwardPort = function (systemPort, devicePort, cb) {
logger.debug("Forwarding system:" + systemPort + " to device:" + devicePort);
this.exec("forward tcp:" + systemPort + " tcp:" + devicePort, cb);
};
ADB.prototype.forwardAbstractPort = function (systemPort, devicePort, cb) {
logger.debug("Forwarding system:" + systemPort + " to abstract device:" + devicePort);
this.exec("forward tcp:" + systemPort + " localabstract:" + devicePort, cb);
};
ADB.prototype.isDeviceConnected = function (cb) {
this.getConnectedDevices(function (err, devices) {
if (err) {
cb(err);
} else {
cb(null, devices.length > 0);
}
});
};
/*
* Check whether the ADB connection is up
*/
ADB.prototype.ping = function (cb) {
this.shell("echo 'ping'", function (err, stdout) {
if (!err && stdout.indexOf("ping") === 0) {
cb(null, true);
} else if (err) {
cb(err);
} else {
cb(new Error("ADB ping failed, returned: " + stdout));
}
});
};
ADB.prototype.setDeviceId = function (deviceId) {
logger.debug("Setting device id to " + deviceId);
this.curDeviceId = deviceId;
this.adb.defaultArgs.push("-s", deviceId);
};
ADB.prototype.setEmulatorPort = function (emPort) {
this.emulatorPort = emPort;
};
ADB.prototype.waitForDevice = function (cb) {
var doWait = function (innerCb) {
logger.debug("Waiting for device to be ready and to respond to shell " +
"commands (timeout = " + this.appDeviceReadyTimeout + ")");
var movedOn = false
, timeoutSecs = parseInt(this.appDeviceReadyTimeout, 10);
setTimeout(function () {
if (!movedOn) {
movedOn = true;
innerCb("Device did not become ready in " + timeoutSecs + " secs; " +
"are you sure it's powered on?");
}
}.bind(this), timeoutSecs * 1000);
this.exec("wait-for-device", function (err) {
if (!movedOn) {
if (err) {
logger.error("Error running wait-for-device");
movedOn = true;
innerCb(err);
} else {
this.shell("echo 'ready'", function (err) {
if (!movedOn) {
movedOn = true;
if (err) {
logger.error("Error running shell echo: " + err);
innerCb(err);
} else {
innerCb();
}
}
}.bind(this));
}
}
}.bind(this));
}.bind(this);
var tries = 0;
var waitCb = function (err) {
if (err) {
var lastCb = cb;
if (tries < 3) {
tries++;
logger.debug("Retrying restartAdb");
lastCb = waitCb.bind(this);
}
this.restartAdb(function () {
this.getConnectedDevices(function () {
doWait(lastCb);
});
}.bind(this));
} else {
cb(null);
}
};
doWait(waitCb.bind(this));
};
ADB.prototype.restartAdb = function (cb) {
if (!this.suppressKillServer) {
this.exec("kill-server", function (err) {
if (err) {
logger.error("Error killing ADB server, going to see if it's online " +
"anyway");
}
cb();
});
} else {
logger.debug("'adb kill-server' suppressed. Ignoring command.");
cb();
}
};
ADB.prototype.restart = function (cb) {
async.series([
this.stopLogcat.bind(this)
, this.restartAdb.bind(this)
, this.waitForDevice.bind(this)
, this.startLogcat.bind(this)