forked from danielpaulus/go-ios
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
2173 lines (1953 loc) · 73.7 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 (
"bufio"
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"os"
"os/signal"
"path"
"path/filepath"
"runtime/debug"
"sort"
"strconv"
"strings"
"syscall"
"time"
"github.com/danielpaulus/go-ios/ios/debugproxy"
"github.com/danielpaulus/go-ios/ios/deviceinfo"
"github.com/danielpaulus/go-ios/ios/remoted"
"github.com/danielpaulus/go-ios/ios/tunnel"
"github.com/danielpaulus/go-ios/ios/amfi"
"github.com/danielpaulus/go-ios/ios/mobileactivation"
"github.com/danielpaulus/go-ios/ios/afc"
"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"
"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/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"
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
prettyJSON = false
)
func main() {
Main()
}
const version = "local-build"
// Main Exports main for testing
func Main() {
usage := fmt.Sprintf(`go-ios %s
Usage:
ios activate [options]
ios listen [options]
ios list [options] [--details]
ios info [display | lockdown] [options]
ios image list [options]
ios image mount [--path=<imagepath>] [options]
ios image unmount [options]
ios image auto [--basedir=<where_dev_images_are_stored>] [options]
ios syslog [options]
ios screenshot [options] [--output=<outfile>] [--stream] [--port=<port>]
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 timeformat (24h | 12h | toggle | get) [--force] [options]
ios devicestate list [options]
ios devicestate enable <profileTypeId> <profileId> [options]
ios erase [--force] [options]
ios lang [--setlocale=<locale>] [--setlang=<newlang>] [options]
ios mobilegestalt <key>... [--plist] [options]
ios diagnostics list [options]
ios profile list [options]
ios prepare [--skip-all] [--skip=<option>]... [--certfile=<cert_file_path>] [--orgname=<org_name>] [--locale] [--lang] [options]
ios prepare create-cert
ios prepare printskip
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] [--mode=<all(default)|usbmuxd|utun>] [--iface=<iface>] [options]
ios readpair [options]
ios pcap [options] [--pid=<processID>] [--process=<processName>]
ios install --path=<ipaOrAppFolder> [options]
ios uninstall <bundleID> [options]
ios apps [--system] [--all] [--list] [--filesharing] [options]
ios launch <bundleID> [--wait] [--kill-existing] [options]
ios kill (<bundleID> | --pid=<processID> | --process=<processName>) [options]
ios runtest [--bundle-id=<bundleid>] [--test-runner-bundle-id=<testrunnerbundleid>] [--xctest-config=<xctestconfig>] [--log-output=<file>] [--xctest] [--test-to-run=<tests>]... [--test-to-skip=<tests>]... [--env=<e>]... [options]
ios runwda [--bundleid=<bundleid>] [--testrunnerbundleid=<testbundleid>] [--xctestconfig=<xctestconfig>] [--log-output=<file>] [--arg=<a>]... [--env=<e>]... [options]
ios ax [--font=<fontSize>] [options]
ios debug [options] [--stop-at-entry] <app_path>
ios fsync (rm [--r] | 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]
ios voiceover (enable | disable | toggle | get) [--force] [options]
ios zoomtouch (enable | disable | toggle | get) [--force] [options]
ios diskspace [options]
ios batterycheck [options]
ios tunnel start [options] [--pair-record-path=<pairrecordpath>] [--userspace]
ios tunnel ls [options]
ios tunnel stopagent
ios devmode (enable | get) [--enable-post-restart] [options]
ios rsd ls [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.
--tunnel-info-port=<port> When go-ios is used to manage tunnels for iOS 17+ it exposes them on an HTTP-API for localhost (default port: 28100)
--address=<ipv6addrr> Address of the device on the interface. This parameter is optional and can be set if a tunnel created by MacOS needs to be used.
> To get this value run "log stream --debug --info --predicate 'eventMessage LIKE "*Tunnel established*" OR eventMessage LIKE "*for server port*"'",
> connect a device and open Xcode
--rsd-port=<port> Port of remote service discovery on the device through the tunnel
> This parameter is similar to '--address' and can be obtained by the same log filter
--proxyurl=<url> Set this if you want go-ios to use a http proxy for outgoing requests, like for downloading images or contacting Apple during device activation.
> A simple format like: "http://PROXY_LOGIN:PROXY_PASS@proxyIp:proxyPort" works. Otherwise use the HTTP_PROXY system env var.
--userspace-port=<port> Optional. Set this if you run a command supplying rsd-port and address and your device is using userspace tunnel
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 activate [options] Activate a device
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 [display | lockdown] [options] Prints a dump of device information from the given source.
ios image list [options] List currently mounted developers images' signatures
ios image mount [--path=<imagepath>] [options] Mount a image from <imagepath>
> For iOS 17+ (personalized developer disk images) <imagepath> must point to the "Restore" directory inside the developer disk
ios image unmount [options] Unmount developer disk image
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>] [--stream] [--port=<port>] Takes a screenshot and writes it to the current dir or to <outfile> If --stream is supplied it
> starts an mjpeg server at 0.0.0.0:3333. Use --port to set another port.
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 erase [--force] [options] Erase the device. It will prompt you to input y+Enter unless --force is specified.
ios lang [--setlocale=<locale>] [--setlang=<newlang>] [options] Sets or gets the Device language. ios lang will print the current language and locale, as well as a list of all supported langs and locales.
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 prepare [--skip-all] [--skip=<option>]... [--certfile=<cert_file_path>] [--orgname=<org_name>] [--locale] [--lang] [options] prepare a device. Use skip-all to skip everything multiple --skip args to skip only a subset.
> You can use 'ios prepare printskip' to get a list of all options to skip. Use certfile and orgname if you want to supervise the device. If you need certificates
> to supervise, run 'ios prepare create-cert' and go-ios will generate one you can use. locale and lang are optional, the default is en_US and en.
> Run 'ios lang' to see a list of all supported locales and languages.
ios prepare create-cert A nice util to generate a certificate you can use for supervising devices. Make sure you rename and store it in a safe place.
ios prepare printskip Print all options you can skip.
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] [--mode=<all(default)|usbmuxd|utun>] [--iface=<iface>] [options] 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] [--list] [--filesharing] Retrieves a list of installed applications. --system prints out preinstalled system apps. --all prints all apps, including system, user, and hidden apps. --list only prints bundle ID, bundle name and version number. --filesharing only prints apps which enable documents sharing.
ios launch <bundleID> [--wait] [--kill-existing] [options] Launch app with the bundleID on the device. Get your bundle ID from the apps command. --wait keeps the connection open if you want logs.
ios kill (<bundleID> | --pid=<processID> | --process=<processName>) [options] Kill app with the specified bundleID, process id, or process name on the device.
ios runtest [--bundle-id=<bundleid>] [--test-runner-bundle-id=<testbundleid>] [--xctest-config=<xctestconfig>] [--log-output=<file>] [--xctest] [--test-to-run=<tests>]... [--test-to-skip=<tests>]... [--env=<e>]... [options] Run a XCUITest. If you provide only bundle-id go-ios will try to dynamically create test-runner-bundle-id and xctest-config.
> If you provide '-' as log output, it prints resuts to stdout.
> To be able to filter for tests to run or skip, use one argument per test selector. Example: runtest --test-to-run=(TestTarget.)TestClass/testMethod --test-to-run=(TestTarget.)TestClass/testMethod (the value for 'TestTarget' is optional)
> The method name can also be omitted and in this case all tests of the specified class are run
ios runwda [--bundleid=<bundleid>] [--testrunnerbundleid=<testbundleid>] [--xctestconfig=<xctestconfig>] [--log-output=<file>] [--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 [--font=<fontSize>] [options] Access accessibility inspector features.
ios debug [--stop-at-entry] <app_path> Start debug with lldb
ios fsync (rm [--r] | tree | mkdir) --path=<targetPath> Remove | treeview | mkdir in target path. --r used alongside rm will recursively remove all files and directories from 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).
ios voiceover (enable | disable | toggle | get) [--force] [options] Enables, disables, toggles, or returns the state of the "VoiceOver" software home-screen button. iOS 11+ only (Use --force to try on older versions).
ios zoom (enable | disable | toggle | get) [--force] [options] Enables, disables, toggles, or returns the state of the "ZoomTouch" software home-screen button. iOS 11+ only (Use --force to try on older versions).
ios timeformat (24h | 12h | toggle | get) [--force] [options] Sets, or returns the state of the "time format". iOS 11+ only (Use --force to try on older versions).
ios diskspace [options] Prints disk space info.
ios batterycheck [options] Prints battery info.
ios tunnel start [options] [--pair-record-path=<pairrecordpath>] [--enabletun] Creates a tunnel connection to the device. If the device was not paired with the host yet, device pairing will also be executed.
> On systems with System Integrity Protection enabled the argument '--pair-record-path=default' can be used to point to /var/db/lockdown/RemotePairing/user_501.
> If nothing is specified, the current dir is used for the pair record.
> This command needs to be executed with admin privileges.
> (On MacOS the process 'remoted' must be paused before starting a tunnel is possible 'sudo pkill -SIGSTOP remoted', and 'sudo pkill -SIGCONT remoted' to resume)
ios tunnel ls List currently started tunnels. Use --enabletun to activate using TUN devices rather than user space network. Requires sudo/admin shells.
ios devmode (enable | get) [--enable-post-restart] [options] Enable developer mode on the device or check if it is enabled. Can also completely finalize developer mode setup after device is restarted.
ios rsd ls [options] List RSD services and their port.
`, 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)
skipAgent, _ := os.LookupEnv("ENABLE_GO_IOS_AGENT")
if skipAgent == "yes" {
tunnel.RunAgent()
}
if !tunnel.IsAgentRunning() {
log.Warn("go-ios agent is not running. You might need to start it with 'ios tunnel start' for ios17+. Use ENABLE_GO_IOS_AGENT=yes for experimental daemon mode.")
}
shouldPrintVersionNoDashes, _ := arguments.Bool("version")
shouldPrintVersion, _ := arguments.Bool("--version")
if shouldPrintVersionNoDashes || shouldPrintVersion {
printVersion()
return
}
proxyUrl, _ := arguments.String("--proxyurl")
exitIfError("could not parse proxy url", ios.UseHttpProxy(proxyUrl))
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
}
tunnelInfoPort, err := arguments.Int("--tunnel-info-port")
if err != nil {
tunnelInfoPort = ios.HttpApiPort()
}
tunnelCommand, _ := arguments.Bool("tunnel")
udid, _ := arguments.String("--udid")
address, addressErr := arguments.String("--address")
rsdPort, rsdErr := arguments.Int("--rsd-port")
userspaceTunnelPort, userspaceTunnelErr := arguments.Int("--userspace-port")
device, err := ios.GetDevice(udid)
// device address and rsd port are only available after the tunnel started
if !tunnelCommand {
exitIfError("Device not found: "+udid, err)
if addressErr == nil && rsdErr == nil {
if userspaceTunnelErr == nil {
device.UserspaceTUN = true
device.UserspaceTUNPort = userspaceTunnelPort
}
device = deviceWithRsdProvider(device, udid, address, rsdPort)
} else {
info, err := tunnel.TunnelInfoForDevice(device.Properties.SerialNumber, tunnelInfoPort)
if err == nil {
device.UserspaceTUNPort = info.UserspaceTUNPort
device.UserspaceTUN = info.UserspaceTUN
device = deviceWithRsdProvider(device, udid, info.Address, info.RsdPort)
} else {
log.WithField("udid", device.Properties.SerialNumber).Warn("failed to get tunnel info")
}
}
}
b, _ = arguments.Bool("erase")
if b {
force, _ := arguments.Bool("--force")
if !force {
log.Warnf("are you sure you want to erase device %s? (y/n)", device.Properties.SerialNumber)
reader := bufio.NewReader(os.Stdin)
// ReadString will block until the delimiter is entered
input, err := reader.ReadString('\n')
exitIfError("An error occured while reading input", err)
if !strings.HasPrefix(input, "y") {
log.Errorf("abort")
return
}
}
exitIfError("failed erasing", mcinstall.Erase(device))
print(convertToJSONString("ok"))
return
}
rsdCommand, _ := arguments.Bool("rsd")
if rsdCommand {
listCommand, _ := arguments.Bool("ls")
if listCommand {
services := device.Rsd.GetServices()
if JSONdisabled {
fmt.Println(services)
} else {
b, err := marshalJSON(services)
exitIfError("failed json conversion", err)
println(string(b))
}
return
}
}
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("prepare")
if b {
b, _ = arguments.Bool("create-cert")
if b {
cert, err := ios.CreateDERFormattedSupervisionCert()
exitIfError("failed creating cert", err)
err = os.WriteFile("supervision-cert.der", cert.CertDER, 0o777)
log.Info("supervision-cert.der")
exitIfError("failed writing cert", err)
err = os.WriteFile("supervision-cert.pem", cert.CertPEM, 0o777)
log.Info("supervision-cert.pem")
exitIfError("failed writing cert", err)
err = os.WriteFile("supervision-private-key.key", cert.PrivateKeyDER, 0o777)
log.Info("supervision-private-key.key")
exitIfError("failed writing cert", err)
err = os.WriteFile("supervision-private-key.pem", cert.PrivateKeyPEM, 0o777)
log.Info("supervision-private-key.pem")
exitIfError("failed writing key", err)
err = os.WriteFile("supervision-csr.csr", []byte(cert.Csr), 0o777)
log.Info("supervision-csr.csr")
exitIfError("failed writing cert", err)
log.Info("Golang does not have good PKCS12 format sadly. If you need a p12 file run this: " +
"'openssl pkcs12 -export -inkey supervision-private-key.pem -in supervision-cert.pem -out certificate.p12 -password pass:a'")
return
}
b, _ = arguments.Bool("printskip")
if b {
println(convertToJSONString(mcinstall.GetAllSetupSkipOptions()))
return
}
skip := mcinstall.GetAllSetupSkipOptions()
skip1 := arguments["--skip"].([]string)
if len(skip1) > 0 {
skip = skip1
}
certfile, _ := arguments.String("--certfile")
orgname, _ := arguments.String("--orgname")
locale, _ := arguments.String("--locale")
lang, _ := arguments.String("--lang")
var certBytes []byte
if certfile != "" {
certBytes, err = os.ReadFile(certfile)
exitIfError("failed opening cert file", err)
if orgname == "" {
log.Fatal("--orgname must be specified if certfile for supervision is provided")
}
}
exitIfError("failed erasing", mcinstall.Prepare(device, skip, certBytes, orgname, locale, lang))
print(convertToJSONString("ok"))
return
}
b, _ = arguments.Bool("activate")
if b {
exitIfError("failed activation", mobileactivation.Activate(device))
return
}
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("voiceover")
if b {
force, _ := arguments.Bool("--force")
b, _ = arguments.Bool("enable")
if b {
voiceOver(device, "enable", force)
}
b, _ = arguments.Bool("disable")
if b {
voiceOver(device, "disable", force)
}
b, _ = arguments.Bool("toggle")
if b {
voiceOver(device, "toggle", force)
}
b, _ = arguments.Bool("get")
if b {
voiceOver(device, "get", force)
}
}
b, _ = arguments.Bool("zoom")
if b {
force, _ := arguments.Bool("--force")
b, _ = arguments.Bool("enable")
if b {
zoomTouch(device, "enable", force)
}
b, _ = arguments.Bool("disable")
if b {
zoomTouch(device, "disable", force)
}
b, _ = arguments.Bool("toggle")
if b {
zoomTouch(device, "toggle", force)
}
b, _ = arguments.Bool("get")
if b {
zoomTouch(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 {
if display, _ := arguments.Bool("display"); display {
deviceInfo, err := deviceinfo.NewDeviceInfo(device)
exitIfError("Can't connect to deviceinfo service", err)
defer deviceInfo.Close()
info, err := deviceInfo.GetDisplayInfo()
exitIfError("Can't fetch dispaly info", err)
fmt.Println(convertToJSONString(info))
} else if lockdown, _ := arguments.Bool("lockdown"); lockdown {
printDeviceInfo(device)
} else {
// When subcommand is missing, it defaults to lockdown.
// Unknown subcommands don't reach this line and quit early.
printDeviceInfo(device)
}
return
}
b, _ = arguments.Bool("syslog")
if b {
runSyslog(device)
return
}
b, _ = arguments.Bool("screenshot")
if b {
stream, _ := arguments.Bool("--stream")
port, _ := arguments.String("--port")
path, _ := arguments.String("--output")
if stream {
if port == "" {
port = "3333"
}
err := instruments.StartMJPEGStreamingServer(device, port)
exitIfError("failed starting mjpeg", err)
return
}
saveScreenshot(device, path)
return
}
b, _ = arguments.Bool("setlocation")
if b {
lat, _ := arguments.String("--lat")
lon, _ := arguments.String("--lon")
if device.SupportsRsd() {
server, err := instruments.NewLocationSimulationService(device)
exitIfError("failed to create location simulation service:", err)
startLocationSimulation(server, lat, lon)
return
}
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 {
list, _ := arguments.Bool("--list")
system, _ := arguments.Bool("--system")
all, _ := arguments.Bool("--all")
filesharing, _ := arguments.Bool("--filesharing")
printInstalledApps(device, system, all, list, filesharing)
return
}
b, _ = arguments.Bool("date")
if b {
printDeviceDate(device)
return
}
b, _ = arguments.Bool("diagnostics")
if b {
printDiagnostics(device)
return
}
b, _ = arguments.Bool("timeformat")
if b {
force, _ := arguments.Bool("--force")
b, _ = arguments.Bool("24h")
if b {
timeFormat(device, "24h", force)
}
b, _ = arguments.Bool("12h")
if b {
timeFormat(device, "12h", force)
}
b, _ = arguments.Bool("toggle")
if b {
timeFormat(device, "toggle", force)
}
b, _ = arguments.Bool("get")
if b {
timeFormat(device, "get", force)
}
}
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 := os.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 {
wait, _ := arguments.Bool("--wait")
bKillExisting, _ := arguments.Bool("--kill-existing")
bundleID, _ := arguments.String("<bundleID>")
if bundleID == "" {
log.Fatal("please provide a bundleID")
}
pControl, err := instruments.NewProcessControl(device)
exitIfError("processcontrol failed", err)
opts := map[string]any{}
if bKillExisting {
opts["KillExisting"] = 1
} // end if
pid, err := pControl.LaunchApp(bundleID, opts)
exitIfError("launch app command failed", err)
log.WithFields(log.Fields{"pid": pid}).Info("Process launched")
if wait {
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
<-c
log.WithFields(log.Fields{"pid": pid}).Info("stop listening to logs")
}
}
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("%s not installed", bundleID)
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("--bundle-id")
testRunnerBundleId, _ := arguments.String("--test-runner-bundle-id")
xctestConfig, _ := arguments.String("--xctest-config")
testsToRunArg := arguments["--test-to-run"]
var testsToRun []string
if testsToRunArg != nil && len(testsToRunArg.([]string)) > 0 {
testsToRun = testsToRunArg.([]string)
}
testsToSkipArg := arguments["--test-to-skip"]
var testsToSkip []string
testsToSkip = nil
if testsToSkipArg != nil && len(testsToSkipArg.([]string)) > 0 {
testsToSkip = testsToSkipArg.([]string)
}
rawTestlog, rawTestlogErr := arguments.String("--log-output")
env := arguments["--env"].([]string)
isXCTest, _ := arguments.Bool("--xctest")
if rawTestlogErr == nil {
var writer *os.File = os.Stdout
if rawTestlog != "-" {
file, err := os.Create(rawTestlog)
exitIfError("Cannot open file "+rawTestlog, err)
writer = file
}
defer writer.Close()
testResults, err := testmanagerd.RunXCUITest(bundleID, testRunnerBundleId, xctestConfig, device, env, testsToRun, testsToSkip, testmanagerd.NewTestListener(writer, writer, os.TempDir()), isXCTest)
if err != nil {
log.WithFields(log.Fields{"error": err}).Info("Failed running Xcuitest")
}
log.Info(fmt.Printf("%+v", testResults))
} else {
_, err := testmanagerd.RunXCUITest(bundleID, testRunnerBundleId, xctestConfig, device, env, testsToRun, testsToSkip, testmanagerd.NewTestListener(io.Discard, io.Discard, os.TempDir()), isXCTest)
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, arguments)
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")
isRecursive, _ := arguments.Bool("--r")
if isRecursive {
err = afcService.RemoveAll(path)
} else {
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")