forked from danielpaulus/go-ios
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
1453 lines (1302 loc) · 47.1 KB
/
main.go
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
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"github.com/danielpaulus/go-ios/ios/afc"
"io/ioutil"
"path"
"path/filepath"
"runtime/debug"
"sort"
"strings"
"syscall"
"github.com/danielpaulus/go-ios/ios/crashreport"
"github.com/danielpaulus/go-ios/ios/testmanagerd"
"github.com/danielpaulus/go-ios/ios/debugserver"
"github.com/danielpaulus/go-ios/ios/imagemounter"
"github.com/danielpaulus/go-ios/ios/zipconduit"
"os"
"os/signal"
"time"
"github.com/danielpaulus/go-ios/ios/simlocation"
"github.com/danielpaulus/go-ios/ios"
"github.com/danielpaulus/go-ios/ios/accessibility"
"github.com/danielpaulus/go-ios/ios/debugproxy"
"github.com/danielpaulus/go-ios/ios/diagnostics"
"github.com/danielpaulus/go-ios/ios/forward"
"github.com/danielpaulus/go-ios/ios/installationproxy"
"github.com/danielpaulus/go-ios/ios/instruments"
"github.com/danielpaulus/go-ios/ios/mcinstall"
"github.com/danielpaulus/go-ios/ios/notificationproxy"
"github.com/danielpaulus/go-ios/ios/pcap"
"github.com/danielpaulus/go-ios/ios/screenshotr"
syslog "github.com/danielpaulus/go-ios/ios/syslog"
"github.com/docopt/docopt-go"
log "github.com/sirupsen/logrus"
)
//JSONdisabled enables or disables output in JSON format
var JSONdisabled = false
var prettyJSON = false
func main() {
Main()
}
const version = "local-build"
// Main Exports main for testing
func Main() {
usage := fmt.Sprintf(`go-ios %s
Usage:
ios listen [options]
ios list [options] [--details]
ios info [options]
ios image list [options]
ios image mount [--path=<imagepath>] [options]
ios image auto [--basedir=<where_dev_images_are_stored>] [options]
ios syslog [options]
ios screenshot [options] [--output=<outfile>]
ios instruments notifications [options]
ios crash ls [<pattern>] [options]
ios crash cp <srcpattern> <target> [options]
ios crash rm <cwd> <pattern> [options]
ios devicename [options]
ios date [options]
ios devicestate list [options]
ios devicestate enable <profileTypeId> <profileId> [options]
ios lang [--setlocale=<locale>] [--setlang=<newlang>] [options]
ios mobilegestalt <key>... [--plist] [options]
ios diagnostics list [options]
ios profile list [options]
ios profile remove <profileName> [options]
ios profile add <profileFile> [--p12file=<orgid>] [--password=<p12password>] [options]
ios httpproxy <host> <port> [<user>] [<pass>] --p12file=<orgid> --password=<p12password> [options]
ios httpproxy remove [options]
ios pair [--p12file=<orgid>] [--password=<p12password>] [options]
ios ps [--apps] [options]
ios ip [options]
ios forward [options] <hostPort> <targetPort>
ios dproxy [--binary]
ios readpair [options]
ios pcap [options] [--pid=<processID>] [--process=<processName>]
ios install --path=<ipaOrAppFolder> [options]
ios uninstall <bundleID> [options]
ios apps [--system] [--all] [options]
ios launch <bundleID> [options]
ios kill (<bundleID> | --pid=<processID> | --process=<processName>) [options]
ios runtest <bundleID> [options]
ios runwda [--bundleid=<bundleid>] [--testrunnerbundleid=<testbundleid>] [--xctestconfig=<xctestconfig>] [--arg=<a>]... [--env=<e>]... [options]
ios ax [options]
ios debug [options] [--stop-at-entry] <app_path>
ios fsync (rm | tree | mkdir) --path=<targetPath>
ios fsync (pull | push) --srcPath=<srcPath> --dstPath=<dstPath>
ios reboot [options]
ios -h | --help
ios --version | version [options]
ios setlocation [options] [--lat=<lat>] [--lon=<lon>]
ios setlocationgpx [options] [--gpxfilepath=<gpxfilepath>]
ios resetlocation [options]
ios assistivetouch (enable | disable | toggle | get) [--force] [options]
Options:
-v --verbose Enable Debug Logging.
-t --trace Enable Trace Logging (dump every message).
--nojson Disable JSON output
--pretty Pretty-print JSON command output
-h --help Show this screen.
--udid=<udid> UDID of the device.
The commands work as following:
The default output of all commands is JSON. Should you prefer human readable outout, specify the --nojson option with your command.
By default, the first device found will be used for a command unless you specify a --udid=some_udid switch.
Specify -v for debug logging and -t for dumping every message.
ios listen [options] Keeps a persistent connection open and notifies about newly connected or disconnected devices.
ios list [options] [--details] Prints a list of all connected device's udids. If --details is specified, it includes version, name and model of each device.
ios info [options] Prints a dump of Lockdown getValues.
ios image list [options] List currently mounted developers images' signatures
ios image mount [--path=<imagepath>] [options] Mount a image from <imagepath>
ios image auto [--basedir=<where_dev_images_are_stored>] [options] Automatically download correct dev image from the internets and mount it.
> You can specify a dir where images should be cached.
> The default is the current dir.
ios syslog [options] Prints a device's log output
ios screenshot [options] [--output=<outfile>] Takes a screenshot and writes it to the current dir or to <outfile>
ios instruments notifications [options] Listen to application state notifications
ios crash ls [<pattern>] [options] run "ios crash ls" to get all crashreports in a list,
> or use a pattern like 'ios crash ls "*ips*"' to filter
ios crash cp <srcpattern> <target> [options] copy "file pattern" to the target dir. Ex.: 'ios crash cp "*" "./crashes"'
ios crash rm <cwd> <pattern> [options] remove file pattern from dir. Ex.: 'ios crash rm "." "*"' to delete everything
ios devicename [options] Prints the devicename
ios date [options] Prints the device date
ios devicestate list [options] Prints a list of all supported device conditions, like slow network, gpu etc.
ios devicestate enable <profileTypeId> <profileId> [options] Enables a profile with ids (use the list command to see options). It will only stay active until the process is terminated.
> Ex. "ios devicestate enable SlowNetworkCondition SlowNetwork3GGood"
ios lang [--setlocale=<locale>] [--setlang=<newlang>] [options] Sets or gets the Device language
ios mobilegestalt <key>... [--plist] [options] Lets you query mobilegestalt keys. Standard output is json but if desired you can get
> it in plist format by adding the --plist param.
> Ex.: "ios mobilegestalt MainScreenCanvasSizes ArtworkTraits --plist"
ios diagnostics list [options] List diagnostic infos
ios pair [--p12file=<orgid>] [--password=<p12password>] [options] Pairs the device. If the device is supervised, specify the path to the p12 file
> to pair without a trust dialog. Specify the password either with the argument or
> by setting the environment variable 'P12_PASSWORD'
ios profile list List the profiles on the device
ios profile remove <profileName> Remove the profileName from the device
ios profile add <profileFile> [--p12file=<orgid>] [--password=<p12password>] Install profile file on the device. If supervised set p12file and password or the environment variable 'P12_PASSWORD'
ios httpproxy <host> <port> [<user>] [<pass>] --p12file=<orgid> [--password=<p12password>] set global http proxy on supervised device. Use the password argument or set the environment variable 'P12_PASSWORD'
> Specify proxy password either as argument or using the environment var: PROXY_PASSWORD
> Use p12 file and password for silent installation on supervised devices.
ios httpproxy remove [options] Removes the global http proxy config. Only works with http proxies set by go-ios!
ios ps [--apps] [options] Dumps a list of running processes on the device.
> Use --nojson for a human-readable listing including BundleID when available. (not included with JSON output)
> --apps limits output to processes flagged by iOS as "isApplication". This greatly-filtered list
> should at least include user-installed software. Additional packages will also be displayed depending on the version of iOS.
ios ip [options] Uses the live pcap iOS packet capture to wait until it finds one that contains the IP address of the device.
> It relies on the MAC address of the WiFi adapter to know which is the right IP.
> You have to disable the "automatic wifi address"-privacy feature of the device for this to work.
> If you wanna speed it up, open apple maps or similar to force network traffic.
> f.ex. "ios launch com.apple.Maps"
ios forward [options] <hostPort> <targetPort> Similar to iproxy, forward a TCP connection to the device.
ios dproxy [--binary] Starts the reverse engineering proxy server.
> It dumps every communication in plain text so it can be implemented easily.
> Use "sudo launchctl unload -w /Library/Apple/System/Library/LaunchDaemons/com.apple.usbmuxd.plist"
> to stop usbmuxd and load to start it again should the proxy mess up things.
> The --binary flag will dump everything in raw binary without any decoding.
ios readpair Dump detailed information about the pairrecord for a device.
ios install --path=<ipaOrAppFolder> [options] Specify a .app folder or an installable ipa file that will be installed.
ios pcap [options] [--pid=<processID>] [--process=<processName>] Starts a pcap dump of network traffic, use --pid or --process to filter specific processes.
ios apps [--system] [--all] Retrieves a list of installed applications. --system prints out preinstalled system apps. --all prints all apps, including system, user, and hidden apps.
ios launch <bundleID> Launch app with the bundleID on the device. Get your bundle ID from the apps command.
ios kill (<bundleID> | --pid=<processID> | --process=<processName>) [options] Kill app with the specified bundleID, process id, or process name on the device.
ios runtest <bundleID> Run a XCUITest.
ios runwda [--bundleid=<bundleid>] [--testrunnerbundleid=<testbundleid>] [--xctestconfig=<xctestconfig>] [--arg=<a>]... [--env=<e>]...[options] runs WebDriverAgents
> specify runtime args and env vars like --env ENV_1=something --env ENV_2=else and --arg ARG1 --arg ARG2
ios ax [options] Access accessibility inspector features.
ios debug [--stop-at-entry] <app_path> Start debug with lldb
ios fsync (rm | tree | mkdir) --path=<targetPath> Remove | treeview | mkdir in target path.
ios fsync (pull | push) --srcPath=<srcPath> --dstPath=<dstPath> Pull or Push file from srcPath to dstPath.
ios reboot [options] Reboot the given device
ios -h | --help Prints this screen.
ios --version | version [options] Prints the version
ios setlocation [options] [--lat=<lat>] [--lon=<lon>] Updates the location of the device to the provided by latitude and longitude coordinates. Example: setlocation --lat=40.730610 --lon=-73.935242
ios setlocationgpx [options] [--gpxfilepath=<gpxfilepath>] Updates the location of the device based on the data in a GPX file. Example: setlocationgpx --gpxfilepath=/home/username/location.gpx
ios resetlocation [options] Resets the location of the device to the actual one
ios assistivetouch (enable | disable | toggle | get) [--force] [options] Enables, disables, toggles, or returns the state of the "AssistiveTouch" software home-screen button. iOS 11+ only (Use --force to try on older versions).
`, version)
arguments, err := docopt.ParseDoc(usage)
exitIfError("failed parsing args", err)
disableJSON, _ := arguments.Bool("--nojson")
if disableJSON {
JSONdisabled = true
} else {
log.SetFormatter(&log.JSONFormatter{})
}
pretty, _ := arguments.Bool("--pretty")
if pretty {
prettyJSON = true
}
traceLevelEnabled, _ := arguments.Bool("--trace")
if traceLevelEnabled {
log.Info("Set Trace mode")
log.SetLevel(log.TraceLevel)
} else {
verboseLoggingEnabledLong, _ := arguments.Bool("--verbose")
if verboseLoggingEnabledLong {
log.Info("Set Debug mode")
log.SetLevel(log.DebugLevel)
}
}
//log.SetReportCaller(true)
log.Debug(arguments)
shouldPrintVersionNoDashes, _ := arguments.Bool("version")
shouldPrintVersion, _ := arguments.Bool("--version")
if shouldPrintVersionNoDashes || shouldPrintVersion {
printVersion()
return
}
b, _ := arguments.Bool("listen")
if b {
startListening()
return
}
listCommand, _ := arguments.Bool("list")
diagnosticsCommand, _ := arguments.Bool("diagnostics")
imageCommand, _ := arguments.Bool("image")
deviceStateCommand, _ := arguments.Bool("devicestate")
profileCommand, _ := arguments.Bool("profile")
if listCommand && !diagnosticsCommand && !imageCommand && !deviceStateCommand && !profileCommand {
b, _ = arguments.Bool("--details")
printDeviceList(b)
return
}
udid, _ := arguments.String("--udid")
device, err := ios.GetDevice(udid)
exitIfError("error getting devicelist", err)
if mobileGestaltCommand(device, arguments) {
return
}
if deviceStateCommand {
if listCommand {
deviceState(device, true, false, "", "")
return
}
enable, _ := arguments.Bool("enable")
profileTypeId, _ := arguments.String("<profileTypeId>")
profileId, _ := arguments.String("<profileId>")
deviceState(device, false, enable, profileTypeId, profileId)
}
b, _ = arguments.Bool("ip")
if b {
ip, err := pcap.FindIp(device)
exitIfError("failed", err)
println(convertToJSONString(ip))
return
}
if crashCommand(device, arguments) {
return
}
if instrumentsCommand(device, arguments) {
return
}
b, _ = arguments.Bool("pcap")
if b {
p, _ := arguments.String("--process")
i, _ := arguments.Int("--pid")
pcap.Pid = int32(i)
pcap.ProcName = p
err := pcap.Start(device)
if err != nil {
exitIfError("pcap failed", err)
}
return
}
b, _ = arguments.Bool("ps")
if b {
applicationsOnly, _ := arguments.Bool("--apps")
processList(device, applicationsOnly)
return
}
b, _ = arguments.Bool("install")
if b {
path, _ := arguments.String("--path")
installApp(device, path)
return
}
b, _ = arguments.Bool("uninstall")
if b {
bundleID, _ := arguments.String("<bundleID>")
uninstallApp(device, bundleID)
return
}
if imageCommand1(device, arguments) {
return
}
b, _ = arguments.Bool("lang")
if b {
locale, _ := arguments.String("--setlocale")
newlang, _ := arguments.String("--setlang")
log.Debugf("lang --setlocale:%s --setlang:%s", locale, newlang)
language(device, locale, newlang)
return
}
b, _ = arguments.Bool("assistivetouch")
if b {
force, _ := arguments.Bool("--force")
b, _ = arguments.Bool("enable")
if b {
assistiveTouch(device, "enable", force)
}
b, _ = arguments.Bool("disable")
if b {
assistiveTouch(device, "disable", force)
}
b, _ = arguments.Bool("toggle")
if b {
assistiveTouch(device, "toggle", force)
}
b, _ = arguments.Bool("get")
if b {
assistiveTouch(device, "get", force)
}
}
b, _ = arguments.Bool("dproxy")
if b {
log.SetFormatter(&log.TextFormatter{})
//log.SetLevel(log.DebugLevel)
binaryMode, _ := arguments.Bool("--binary")
startDebugProxy(device, binaryMode)
return
}
b, _ = arguments.Bool("info")
if b {
printDeviceInfo(device)
return
}
b, _ = arguments.Bool("syslog")
if b {
runSyslog(device)
return
}
b, _ = arguments.Bool("screenshot")
if b {
path, _ := arguments.String("--output")
saveScreenshot(device, path)
return
}
b, _ = arguments.Bool("setlocation")
if b {
lat, _ := arguments.String("--lat")
lon, _ := arguments.String("--lon")
setLocation(device, lat, lon)
return
}
b, _ = arguments.Bool("setlocationgpx")
if b {
gpxFilePath, _ := arguments.String("--gpxfilepath")
setLocationGPX(device, gpxFilePath)
return
}
b, _ = arguments.Bool("resetlocation")
if b {
resetLocation(device)
return
}
b, _ = arguments.Bool("devicename")
if b {
printDeviceName(device)
return
}
b, _ = arguments.Bool("apps")
if b {
system, _ := arguments.Bool("--system")
all, _ := arguments.Bool("--all")
printInstalledApps(device, system, all)
return
}
b, _ = arguments.Bool("date")
if b {
printDeviceDate(device)
return
}
b, _ = arguments.Bool("diagnostics")
if b {
printDiagnostics(device)
return
}
b, _ = arguments.Bool("pair")
if b {
org, _ := arguments.String("--p12file")
pwd, _ := arguments.String("--password")
if pwd == "" {
pwd = os.Getenv("P12_PASSWORD")
}
pairDevice(device, org, pwd)
return
}
b, _ = arguments.Bool("readpair")
if b {
readPair(device)
return
}
b, _ = arguments.Bool("httpproxy")
if b {
removeCommand, _ := arguments.Bool("remove")
if removeCommand {
mcinstall.RemoveProxy(device)
exitIfError("failed removing proxy", err)
log.Info("success")
return
}
host, _ := arguments.String("<host>")
port, _ := arguments.String("<port>")
user, _ := arguments.String("<user>")
pass, _ := arguments.String("<pass>")
if pass == "" {
pass = os.Getenv("PROXY_PASSWORD")
}
p12file, _ := arguments.String("--p12file")
p12password, _ := arguments.String("--password")
if p12password == "" {
p12password = os.Getenv("P12_PASSWORD")
}
p12bytes, err := ioutil.ReadFile(p12file)
exitIfError("could not read p12-file", err)
err = mcinstall.SetHttpProxy(device, host, port, user, pass, p12bytes, p12password)
exitIfError("failed", err)
log.Info("success")
return
}
b, _ = arguments.Bool("profile")
if b {
if listCommand {
handleProfileList(device)
}
b, _ = arguments.Bool("add")
if b {
name, _ := arguments.String("<profileFile>")
p12file, _ := arguments.String("--p12file")
p12password, _ := arguments.String("--password")
if p12password == "" {
p12password = os.Getenv("P12_PASSWORD")
}
if p12file != "" {
handleProfileAddSupervised(device, name, p12file, p12password)
return
}
handleProfileAdd(device, name)
}
b, _ = arguments.Bool("remove")
if b {
name, _ := arguments.String("<profileName>")
handleProfileRemove(device, name)
}
return
}
b, _ = arguments.Bool("forward")
if b {
hostPort, _ := arguments.Int("<hostPort>")
targetPort, _ := arguments.Int("<targetPort>")
startForwarding(device, hostPort, targetPort)
return
}
b, _ = arguments.Bool("launch")
if b {
bundleID, _ := arguments.String("<bundleID>")
if bundleID == "" {
log.Fatal("please provide a bundleID")
}
pControl, err := instruments.NewProcessControl(device)
exitIfError("processcontrol failed", err)
pid, err := pControl.LaunchApp(bundleID)
exitIfError("launch app command failed", err)
log.WithFields(log.Fields{"pid": pid}).Info("Process launched")
}
b, _ = arguments.Bool("kill")
if b {
var response []installationproxy.AppInfo
bundleID, _ := arguments.String("<bundleID>")
processIDint, _ := arguments.Int("--pid")
processName, _ := arguments.String("--process")
processID := uint64(processIDint)
// Technically "Mach Kernel" is process 0, I suppose we provide no way to attempt to kill that.
if bundleID == "" && processID == 0 && processName == "" {
log.Fatal("please provide a bundleID")
}
pControl, err := instruments.NewProcessControl(device)
exitIfError("processcontrol failed", err)
svc, _ := installationproxy.New(device)
// Look for correct process exe name for this bundleID. By default, searches only user-installed apps.
if bundleID != "" {
response, err = svc.BrowseAllApps()
exitIfError("browsing apps failed", err)
for _, app := range response {
if app.CFBundleIdentifier == bundleID {
processName = app.CFBundleExecutable
break
}
}
if processName == "" {
log.Errorf(bundleID, " not installed")
os.Exit(1)
return
}
}
service, err := instruments.NewDeviceInfoService(device)
defer service.Close()
exitIfError("failed opening deviceInfoService for getting process list", err)
processList, _ := service.ProcessList()
// ps
for _, p := range processList {
if (processID > 0 && p.Pid == processID) || (processName != "" && p.Name == processName) {
err = pControl.KillProcess(p.Pid)
exitIfError("kill process failed ", err)
if bundleID != "" {
log.Info(bundleID, " killed, Pid: ", p.Pid)
} else {
log.Info(p.Name, " killed, Pid: ", p.Pid)
}
return
}
}
if bundleID != "" {
log.Error("process of ", bundleID, " not found")
} else if processName != "" {
log.Error("process named ", processName, " not found")
} else {
log.Error("process with pid ", processID, " not found")
}
os.Exit(1)
return
}
b, _ = arguments.Bool("runtest")
if b {
bundleID, _ := arguments.String("<bundleID>")
err := testmanagerd.RunXCUITest(bundleID, device)
if err != nil {
log.WithFields(log.Fields{"error": err}).Info("Failed running Xcuitest")
}
return
}
if runWdaCommand(device, arguments) {
return
}
b, _ = arguments.Bool("ax")
if b {
startAx(device)
return
}
b, _ = arguments.Bool("debug")
if b {
appPath, _ := arguments.String("<app_path>")
if appPath == "" {
log.Fatal("parameter bundleid and app_path must be specified")
}
stopAtEntry, _ := arguments.Bool("--stop-at-entry")
err = debugserver.Start(device, appPath, stopAtEntry)
if err != nil {
log.Error(err.Error())
}
}
b, _ = arguments.Bool("reboot")
if b {
err := diagnostics.Reboot(device)
if err != nil {
log.Error(err)
} else {
log.Info("ok")
}
return
}
b, _ = arguments.Bool("fsync")
if b {
afcService, err := afc.New(device)
exitIfError("fsync: connect afc service failed", err)
b, _ = arguments.Bool("rm")
if b {
path, _ := arguments.String("--path")
err = afcService.Remove(path)
exitIfError("fsync: remove failed", err)
}
b, _ = arguments.Bool("tree")
if b {
path, _ := arguments.String("--path")
err = afcService.TreeView(path, "", true)
exitIfError("fsync: tree view failed", err)
}
b, _ = arguments.Bool("mkdir")
if b {
path, _ := arguments.String("--path")
err = afcService.MkDir(path)
exitIfError("fsync: mkdir failed", err)
}
b, _ = arguments.Bool("pull")
if b {
sp, _ := arguments.String("--srcPath")
dp, _ := arguments.String("--dstPath")
if dp != "" {
ret, _ := ios.PathExists(dp)
if !ret {
err = os.MkdirAll(dp, os.ModePerm)
exitIfError("mkdir failed", err)
}
}
dp = path.Join(dp, filepath.Base(sp))
err = afcService.Pull(sp, dp)
exitIfError("fsync: pull failed", err)
}
b, _ = arguments.Bool("push")
if b {
sp, _ := arguments.String("--srcPath")
dp, _ := arguments.String("--dstPath")
err = afcService.Push(sp, dp)
exitIfError("fsync: push failed", err)
}
afcService.Close()
return
}
}
func mobileGestaltCommand(device ios.DeviceEntry, arguments docopt.Opts) bool {
b, _ := arguments.Bool("mobilegestalt")
if b {
conn, _ := diagnostics.New(device)
keys := arguments["<key>"].([]string)
plist, _ := arguments.Bool("--plist")
resp, _ := conn.MobileGestaltQuery(keys)
if plist {
fmt.Printf("%s\n", ios.ToPlist(resp))
return true
}
jb, _ := marshalJSON(resp)
fmt.Printf("%s\n", jb)
return true
}
return b
}
func imageCommand1(device ios.DeviceEntry, arguments docopt.Opts) bool {
b, _ := arguments.Bool("image")
if b {
list, _ := arguments.Bool("list")
if list {
listMountedImages(device)
}
mount, _ := arguments.Bool("mount")
if mount {
path, _ := arguments.String("--path")
err := imagemounter.MountImage(device, path)
if err != nil {
log.WithFields(log.Fields{"image": path, "udid": device.Properties.SerialNumber, "err": err}).
Error("error mounting image")
return true
}
log.WithFields(log.Fields{"image": path, "udid": device.Properties.SerialNumber}).Info("success mounting image")
}
auto, _ := arguments.Bool("auto")
if auto {
basedir, _ := arguments.String("--basedir")
if basedir == "" {
basedir = "."
}
err := imagemounter.FixDevImage(device, basedir)
if err != nil {
log.WithFields(log.Fields{"basedir": basedir, "udid": device.Properties.SerialNumber, "err": err}).
Error("error mounting image")
return true
}
log.WithFields(log.Fields{"basedir": basedir, "udid": device.Properties.SerialNumber}).Info("success mounting image")
}
}
return b
}
func runWdaCommand(device ios.DeviceEntry, arguments docopt.Opts) bool {
b, _ := arguments.Bool("runwda")
if b {
bundleID, _ := arguments.String("--bundleid")
testbundleID, _ := arguments.String("--testrunnerbundleid")
xctestconfig, _ := arguments.String("--xctestconfig")
wdaargs := arguments["--arg"].([]string)
wdaenv := arguments["--env"].([]string)
if bundleID == "" && testbundleID == "" && xctestconfig == "" {
log.Info("no bundle ids specified, falling back to defaults")
bundleID, testbundleID, xctestconfig = "com.facebook.WebDriverAgentRunner.xctrunner", "com.facebook.WebDriverAgentRunner.xctrunner", "WebDriverAgentRunner.xctest"
}
if bundleID == "" || testbundleID == "" || xctestconfig == "" {
log.WithFields(log.Fields{"bundleid": bundleID, "testbundleid": testbundleID, "xctestconfig": xctestconfig}).Error("please specify either NONE of bundleid, testbundleid and xctestconfig or ALL of them. At least one was empty.")
return true
}
log.WithFields(log.Fields{"bundleid": bundleID, "testbundleid": testbundleID, "xctestconfig": xctestconfig}).Info("Running wda")
go func() {
err := testmanagerd.RunXCUIWithBundleIdsCtx(context.Background(), bundleID, testbundleID, xctestconfig, device, wdaargs, wdaenv)
if err != nil {
log.WithFields(log.Fields{"error": err}).Fatal("Failed running WDA")
}
}()
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
signal := <-c
log.Infof("os signal:%d received, closing..", signal)
err := testmanagerd.CloseXCUITestRunner()
if err != nil {
log.Error("Failed closing wda-testrunner")
os.Exit(1)
}
log.Info("Done Closing")
}
return b
}
func instrumentsCommand(device ios.DeviceEntry, arguments docopt.Opts) bool {
b, _ := arguments.Bool("instruments")
if b {
listenerFunc, closeFunc, err := instruments.ListenAppStateNotifications(device)
if err != nil {
log.Fatal(err)
}
go func() {
for {
notification, err := listenerFunc()
if err != nil {
log.Error(err)
return
}
s, _ := json.Marshal(notification)
println(string(s))
}
}()
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
<-c
err = closeFunc()
if err != nil {
log.Warnf("timeout during close %v", err)
}
}
return b
}
func crashCommand(device ios.DeviceEntry, arguments docopt.Opts) bool {
b, _ := arguments.Bool("crash")
if b {
ls, _ := arguments.Bool("ls")
if ls {
pattern, err := arguments.String("<pattern>")
if err != nil || pattern == "" {
pattern = "*"
}
files, err := crashreport.ListReports(device, pattern)
exitIfError("failed listing crashreports", err)
println(
convertToJSONString(
map[string]interface{}{"files": files, "length": len(files)},
),
)
}
cp, _ := arguments.Bool("cp")
if cp {
pattern, _ := arguments.String("<srcpattern>")
target, _ := arguments.String("<target>")
log.Debugf("cp %s %s", pattern, target)
err := crashreport.DownloadReports(device, pattern, target)
exitIfError("failed downloading crashreports", err)
}
rm, _ := arguments.Bool("rm")
if rm {
cwd, _ := arguments.String("<cwd>")
pattern, _ := arguments.String("<pattern>")
log.Debugf("rm %s %s", cwd, pattern)
err := crashreport.RemoveReports(device, cwd, pattern)
exitIfError("failed deleting crashreports", err)
}
}
return b
}
func deviceState(device ios.DeviceEntry, list bool, enable bool, profileTypeId string, profileId string) {
control, err := instruments.NewDeviceStateControl(device)
exitIfError("failed to connect to deviceStateControl", err)
profileTypes, err := control.List()
if list {
if JSONdisabled {
outputPrettyStateList(profileTypes)
} else {
b, err := marshalJSON(profileTypes)
exitIfError("failed json conversion", err)
println(string(b))
}
return
}
exitIfError("failed listing device states", err)
if enable {
pType, profile, err := instruments.VerifyProfileAndType(profileTypes, profileTypeId, profileId)
exitIfError("invalid arguments", err)
log.Info("Enabling profile.. (this can take a while for ThermalConditions)")
err = control.Enable(pType, profile)
exitIfError("could not enable profile", err)
log.Infof("Profile %s - %s is active! waiting for SIGTERM..", profileTypeId, profileId)
c := make(chan os.Signal, syscall.SIGTERM)
signal.Notify(c, os.Interrupt)
<-c
log.Infof("Disabling profiletype %s", profileTypeId)
err = control.Disable(pType)
exitIfError("could not disable profile", err)
log.Info("ok")
}
}
func outputPrettyStateList(types []instruments.ProfileType) {
var buffer bytes.Buffer
for i, ptype := range types {
buffer.WriteString(
fmt.Sprintf("ProfileType %d\nName:%s\nisActive:%v\nIdentifier:%s\n\n",
i, ptype.Name, ptype.IsActive, ptype.Identifier,
),
)
for i, profile := range ptype.Profiles {
buffer.WriteString(fmt.Sprintf("\tProfile %d:%s\n\tIdentifier:%s\n\t%s",
i, profile.Name, profile.Identifier, profile.Description),
)
buffer.WriteString("\n\t------\n")
}
buffer.WriteString("\n\n")
}
println(buffer.String())
}
func listMountedImages(device ios.DeviceEntry) {
conn, err := imagemounter.New(device)
exitIfError("failed connecting to image mounter", err)
signatures, err := conn.ListImages()
exitIfError("failed getting image list", err)
if len(signatures) == 0 {
log.Infof("none")
return
}
for _, sig := range signatures {
log.Infof("%x", sig)
}
}
func installApp(device ios.DeviceEntry, path string) {
log.WithFields(
log.Fields{"appPath": path, "device": device.Properties.SerialNumber}).Info("installing")
conn, err := zipconduit.New(device)
exitIfError("failed connecting to zipconduit, dev image installed?", err)
err = conn.SendFile(path)
exitIfError("failed writing", err)
}
func uninstallApp(device ios.DeviceEntry, bundleId string) {
log.WithFields(
log.Fields{"appPath": bundleId, "device": device.Properties.SerialNumber}).Info("uninstalling")
svc, err := installationproxy.New(device)
exitIfError("failed connecting to installationproxy", err)
err = svc.Uninstall(bundleId)
exitIfError("failed uninstalling", err)
}
func language(device ios.DeviceEntry, locale string, language string) {
lang, err := ios.GetLanguage(device)
exitIfError("failed getting language", err)
err = ios.SetLanguage(device, ios.LanguageConfiguration{Language: language, Locale: locale})
exitIfError("failed setting language", err)
if lang.Language != language && language != "" {
log.Debugf("Language should be changed from %s to %s waiting for Springboard to reboot", lang.Language, language)
notificationproxy.WaitUntilSpringboardStarted(device)
}
lang, err = ios.GetLanguage(device)
exitIfError("failed getting language", err)
fmt.Println(convertToJSONString(lang))
}
func assistiveTouch(device ios.DeviceEntry, operation string, force bool) {
var enable bool
if !force {
version, err := ios.GetProductVersion(device)
exitIfError("failed getting device product version", err)
if version.LessThan(ios.IOS11()) {
log.Errorf("iOS Version 11.0+ required to manipulate AssistiveTouch. iOS version: %s detected. Use --force to override.", version)
os.Exit(1)
}
}
wasEnabled, err := ios.GetAssistiveTouch(device)
if err != nil {
if force && (operation == "enable" || operation == "disable") {
log.WithFields(log.Fields{"error": err}).Warn("Failed getting current AssistiveTouch status. Continuing anyway.")
} else {
exitIfError("failed getting current AssistiveTouch status", err)
}
}
switch {
case operation == "enable":
enable = true
case operation == "disable":
enable = false
case operation == "toggle":
enable = !wasEnabled
default: // get
enable = wasEnabled
}
if operation != "get" && (force || wasEnabled != enable) {
err = ios.SetAssistiveTouch(device, enable)
exitIfError("failed setting AssistiveTouch", err)
}
if operation == "get" {
if JSONdisabled {
fmt.Printf("%t\n", enable)
} else {
fmt.Println(convertToJSONString(map[string]bool{"AssistiveTouchEnabled": enable}))
}
}
}
func startAx(device ios.DeviceEntry) {
go func() {
deviceList, err := ios.ListDevices()
exitIfError("failed converting to json", err)
device := deviceList.DeviceList[0]
conn, err := accessibility.New(device)
exitIfError("failed starting ax", err)