-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathIOSDeviceLib.cpp
1576 lines (1360 loc) · 53 KB
/
IOSDeviceLib.cpp
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
#include <bitset>
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <mutex>
#include <thread>
#include <memory>
#include <algorithm>
#include <sys/stat.h>
#include "json.hpp"
#include "PlistCpp/Plist.hpp"
#include "PlistCpp/PlistDate.hpp"
#include "PlistCpp/include/boost/any.hpp"
#include "FileHelper.h"
#include "StringHelper.h"
#include "Declarations.h"
#include "GDBHelper.h"
#include "Constants.h"
#include "Printing.h"
#include "CommonFunctions.h"
#include "ServerHelper.h"
#ifdef _WIN32
#pragma region Dll_Variable_Definitions
CFPropertyListFormat kCFPropertyListXMLFormat_v1_0 = (CFPropertyListFormat)100;
device_notification_subscribe_ptr __AMDeviceNotificationSubscribe;
HINSTANCE mobile_device_dll;
HINSTANCE core_foundation_dll;
device_copy_device_identifier __AMDeviceCopyDeviceIdentifier;
device_copy_value __AMDeviceCopyValue;
device_start_service __AMDeviceStartService;
device_uninstall_application __AMDeviceUninstallApplication;
device_secure_operation_with_bundle_id __AMDeviceSecureUninstallApplication;
device_secure_start_service_ptr __AMDeviceSecureStartService;
service_connection_get_socket_ptr __AMDServiceConnectionGetSocket;
service_connection_receive_ptr __AMDServiceConnectionReceive;
service_connection_send_message_ptr __AMDServiceConnectionSendMessage;
device_create_house_arrest_service_ptr __AMDeviceCreateHouseArrestService;
device_connection_operation __AMDeviceStartSession;
device_connection_operation __AMDeviceStopSession;
device_connection_operation __AMDeviceConnect;
device_connection_operation __AMDeviceDisconnect;
device_connection_operation __AMDeviceIsPaired;
device_connection_operation __AMDevicePair;
device_connection_operation __AMDeviceValidatePairing;
device_secure_operation_with_path __AMDeviceSecureTransferPath;
device_secure_operation_with_path __AMDeviceSecureInstallApplication;
device_start_house_arrest __AMDeviceStartHouseArrestService;
device_lookup_applications __AMDeviceLookupApplications;
usb_mux_connect_by_port __USBMuxConnectByPort;
device_connection_operation __AMDeviceGetConnectionID;
device_connection_operation __AMDeviceGetInterfaceType;
cfstring_get_c_string_ptr __CFStringGetCStringPtr;
cfstring_get_c_string __CFStringGetCString;
cf_get_type_id __CFGetTypeID;
cf_get_concrete_type_id __CFStringGetTypeID;
cf_get_concrete_type_id __CFDictionaryGetTypeID;
cfdictionary_get_count __CFDictionaryGetCount;
cfdictionary_get_keys_and_values __CFDictionaryGetKeysAndValues;
cfstring_create_with_cstring __CFStringCreateWithCString;
cfarray_create __CFArrayCreate;
cfurl_create_with_string __CFURLCreateWithString;
cfdictionary_create __CFDictionaryCreate;
cfrelease __CFRelease;
afc_connection_open __AFCConnectionOpen;
afc_connection_close __AFCConnectionClose;
afc_file_info_open __AFCFileInfoOpen;
afc_directory_read __AFCDirectoryRead;
afc_directory_open __AFCDirectoryOpen;
afc_directory_close __AFCDirectoryClose;
afc_directory_create __AFCDirectoryCreate;
afc_remove_path __AFCRemovePath;
afc_fileref_open __AFCFileRefOpen;
afc_fileref_read __AFCFileRefRead;
afc_get_device_info_key __AFCGetDeviceInfoKey;
afc_fileref_write __AFCFileRefWrite;
afc_fileref_close __AFCFileRefClose;
#pragma endregion Dll_Variable_Definitions
#endif // _WIN32
using json = nlohmann::json;
int __result;
int nextServiceConnectionId = 1;
std::map<std::string, DeviceData> devices;
std::map<int, ServiceConnRef> serviceConnections;
std::string get_dirname(std::string& path)
{
size_t found;
found = path.find_last_of(kPathSeparators);
return path.substr(0, found);
}
template<typename T> std::string windows_path_to_unix(T& path)
{
std::string path_str(path);
replace_all(path_str, "\\", "/");
return path_str;
}
std::string get_cstring_from_cfstring(CFStringRef cfstring)
{
const char * result_attempt = CFStringGetCStringPtr(cfstring, kCFStringEncodingUTF8);
char cfstring_buffer[2000];
if (result_attempt == NULL)
{
if (CFStringGetCString(cfstring, cfstring_buffer, 2000, kCFStringEncodingUTF8))
{
return std::string(cfstring_buffer);
}
}
return std::string(result_attempt);
}
CFStringRef create_CFString(const char* str)
{
return CFStringCreateWithCString(NULL, str, kCFStringEncodingUTF8);
}
std::mutex start_session_mutex;
int start_session(std::string& device_identifier)
{
start_session_mutex.lock();
if (devices[device_identifier].sessions < 1)
{
const DeviceInfo* device_info = devices[device_identifier].device_info;
UNLOCK_MUTEX_AND_RETURN_IF_FAILED_RESULT(AMDeviceConnect(device_info), start_session_mutex);
assert(AMDeviceIsPaired(device_info));
UNLOCK_MUTEX_AND_RETURN_IF_FAILED_RESULT(AMDeviceValidatePairing(device_info), start_session_mutex);
UNLOCK_MUTEX_AND_RETURN_IF_FAILED_RESULT(AMDeviceStartSession(device_info), start_session_mutex);
}
++devices[device_identifier].sessions;
start_session_mutex.unlock();
return 0;
}
std::mutex stop_session_mutex;
void stop_session(std::string& device_identifier)
{
stop_session_mutex.lock();
if (--devices[device_identifier].sessions < 1)
{
const DeviceInfo *device_info = devices[device_identifier].device_info;
AMDeviceStopSession(device_info);
AMDeviceDisconnect(device_info);
}
stop_session_mutex.unlock();
}
std::string get_device_property_value(std::string& device_identifier, const char* property_name)
{
const DeviceInfo* device_info = devices[device_identifier].device_info;
std::string result;
if (!start_session(device_identifier))
{
CFStringRef cfstring = create_CFString(property_name);
result = get_cstring_from_cfstring(AMDeviceCopyValue(device_info, NULL, cfstring));
CFRelease(cfstring);
}
stop_session(device_identifier);
return result;
}
const char *get_device_status(std::string device_identifier)
{
const char *result;
if (start_session(device_identifier))
{
result = kUnreachableStatus;
}
else
{
result = kConnectedStatus;
}
stop_session(device_identifier);
return result;
}
void erase_safe(std::map<const char*, HANDLE>& m, const char* key)
{
if (m.count(key))
{
m.erase(key);
}
}
void cleanup_file_resources(const std::string& device_identifier, const std::string& application_identifier)
{
if (!devices.count(device_identifier))
{
return;
}
if (devices[device_identifier].apps_cache[application_identifier].afc_connection)
{
AFCConnectionRef afc_connection_to_close = devices[device_identifier].apps_cache[application_identifier].afc_connection;
AFCConnectionClose(afc_connection_to_close);
devices[device_identifier].apps_cache.erase(application_identifier);
}
}
void cleanup_file_resources(const std::string& device_identifier)
{
if (!devices.count(device_identifier))
{
return;
}
if (devices[device_identifier].apps_cache.size())
{
std::map<std::string, ApplicationCache> apps_cache_clone = devices[device_identifier].apps_cache;
for (auto const& key_value_pair : apps_cache_clone)
{
cleanup_file_resources(device_identifier, key_value_pair.first);
}
devices[device_identifier].apps_cache.clear();
}
}
void get_device_properties(std::string device_identifier, json &result)
{
result["status"] = get_device_status(device_identifier);
result["productType"] = get_device_property_value(device_identifier, "ProductType");
result["deviceName"] = get_device_property_value(device_identifier, "DeviceName");
result["productVersion"] = get_device_property_value(device_identifier, kProductVersion);
result["deviceColor"] = get_device_property_value(device_identifier, "DeviceColor");
// available values:
// "BluetoothAddress","BoardId","CPUArchitecture","ChipID","DeviceClass",
// "DeviceColor","DeviceName","FirmwareVersion","HardwareModel",
// "ModelNumber","ProductType","ProductVersion","UniqueDeviceID","WiFiAddress"
}
inline bool has_complete_status(std::map<std::string, boost::any>& dict)
{
return boost::any_cast<std::string>(dict[kStatusKey]) == kComplete;
}
void update_device_result(std::string device_identifier, json &result)
{
result[kIsUSBConnected] = devices[device_identifier].isUSBConnected;
result[kIsWiFiConnected] = devices[device_identifier].isWiFiConnected;
get_device_properties(device_identifier, result);
}
void on_device_found(const DevicePointer* device_ptr, std::string device_identifier, json &result)
{
/*
Interface type can be one of the followings:
-1 - invalid interface type
0 - unknown interface type
1 - usb interface type
2 - wifi interface type
*/
int interface_type = AMDeviceGetInterfaceType(device_ptr->device_info);
if (interface_type == kUSBInterfaceType || interface_type == kWIFIInterfaceType) {
if (devices.count(device_identifier)) {
devices[device_identifier].device_info = device_ptr->device_info;
result[kEventString] = kDeviceUpdated;
} else {
devices[device_identifier] = { device_ptr->device_info, nullptr };
result[kEventString] = kDeviceFound;
}
if (interface_type == kUSBInterfaceType) {
devices[device_identifier].isUSBConnected = 1;
} else {
devices[device_identifier].isWiFiConnected = 1;
}
update_device_result(device_identifier, result);
}
}
void device_notification_callback(const DevicePointer* device_ptr)
{
std::string device_identifier = get_cstring_from_cfstring(AMDeviceCopyDeviceIdentifier(device_ptr->device_info));
json result;
result[kDeviceId] = device_identifier;
switch (device_ptr->msg)
{
case kADNCIMessageConnected:
{
on_device_found(device_ptr, device_identifier, result);
break;
}
case kADNCIMessageDisconnected:
{
if (devices.count(device_identifier)) {
int interface_type = AMDeviceGetInterfaceType(device_ptr->device_info);
if (interface_type == kUSBInterfaceType) {
devices[device_identifier].isUSBConnected = 0;
} else if (interface_type == kWIFIInterfaceType) {
devices[device_identifier].isWiFiConnected = 0;
}
if (!devices[device_identifier].isUSBConnected && !devices[device_identifier].isWiFiConnected) {
if (devices[device_identifier].apps_cache.size())
{
cleanup_file_resources(device_identifier);
}
devices.erase(device_identifier);
result[kEventString] = kDeviceLost;
} else {
result[kEventString] = kDeviceUpdated;
update_device_result(device_identifier, result);
}
}
break;
}
case kADNCIMessageUnknown:
{
result[kEventString] = kDeviceUnknown;
break;
}
case kADNCIMessageTrusted:
{
on_device_found(device_ptr, device_identifier, result);
break;
}
}
print(result);
}
#ifdef _WIN32
void add_dll_paths_to_environment()
{
std::string str(std::getenv(kPathUpperCase));
str = str.append(";C:\\Program Files\\Common Files\\Apple\\Apple Application Support;C:\\Program Files\\Common Files\\Apple\\Mobile Device Support;");
str = str.append(";C:\\Program Files (x86)\\Common Files\\Apple\\Apple Application Support;C:\\Program Files (x86)\\Common Files\\Apple\\Mobile Device Support;");
SetEnvironmentVariable(kPathUpperCase, str.c_str());
}
int load_dlls()
{
add_dll_paths_to_environment();
mobile_device_dll = LoadLibrary("MobileDevice.dll");
if (!mobile_device_dll)
{
print_error("Could not load MobileDevice.dll", kNullMessageId, kNullMessageId);
return 1;
}
core_foundation_dll = LoadLibrary("CoreFoundation.dll");
if (!core_foundation_dll)
{
print_error("Could not load CoreFoundation.dll", kNullMessageId, kNullMessageId);
return 1;
}
return 0;
}
#endif // _WIN32
int subscribe_for_notifications()
{
HANDLE notify_function = nullptr;
int result = AMDeviceNotificationSubscribe(device_notification_callback, 0, 0, 0, ¬ify_function);
if (result)
{
print_error("Could not attach notification callback", kNullMessageId, kNullMessageId);
}
return result;
}
void start_run_loop()
{
int subscribe_for_notifications_result = subscribe_for_notifications();
if (subscribe_for_notifications_result)
{
return;
}
#ifdef _WIN32
run_loop_ptr CFRunLoopRun = (run_loop_ptr)GetProcAddress(core_foundation_dll, "CFRunLoopRun");
#endif
CFRunLoopRun();
}
std::mutex start_service_mutex;
ServiceInfo start_secure_service(std::string device_identifier, const char* service_name, std::string method_id, bool should_log_error, bool skip_cache)
{
start_service_mutex.lock();
ServiceInfo serviceInfoResult = {};
if (!devices.count(device_identifier))
{
if (should_log_error)
print_error("Device not found", device_identifier, method_id, kAMDNotFoundError);
start_service_mutex.unlock();
return serviceInfoResult;
}
if (!skip_cache && devices[device_identifier].services.count(service_name))
{
start_service_mutex.unlock();
return devices[device_identifier].services[service_name];
}
PRINT_ERROR_AND_RETURN_VALUE_IF_FAILED_RESULT(start_session(device_identifier), "Could not start device session", device_identifier, method_id, serviceInfoResult);
CFStringRef cf_service_name = create_CFString(service_name);
ServiceConnRef connection;
unsigned result = AMDeviceSecureStartService(devices[device_identifier].device_info, cf_service_name, NULL, &connection);
service_conn_t socket = (void*)AMDServiceConnectionGetSocket(connection);
stop_session(device_identifier);
CFRelease(cf_service_name);
if (result)
{
std::string message("Could not start service ");
message += service_name;
if (should_log_error)
print_error(message.c_str(), device_identifier, method_id, result);
start_service_mutex.unlock();
return serviceInfoResult;
}
serviceInfoResult.socket = socket;
serviceInfoResult.connection = connection;
serviceInfoResult.connection_id = nextServiceConnectionId;
serviceConnections[nextServiceConnectionId] = connection;
nextServiceConnectionId++;
if (!skip_cache) {
devices[device_identifier].services[service_name] = serviceInfoResult;
}
start_service_mutex.unlock();
return serviceInfoResult;
}
AFCConnectionRef start_house_arrest(std::string device_identifier, const char* application_identifier, std::string method_id)
{
if (!devices.count(device_identifier))
{
print_error("Device not found", device_identifier, method_id, kAMDNotFoundError);
return NULL;
}
AFCConnectionRef persistedHouseArrestService = devices[device_identifier].apps_cache[application_identifier].afc_connection;
if (persistedHouseArrestService)
{
return persistedHouseArrestService;
}
AFCConnectionRef conn = NULL;
start_session(device_identifier);
CFStringRef cf_application_identifier = create_CFString(application_identifier);
unsigned result = AMDeviceCreateHouseArrestService(devices[device_identifier].device_info, cf_application_identifier, 0, &conn);
stop_session(device_identifier);
CFRelease(cf_application_identifier);
if (result)
{
std::string message("Could not start house arrest for application ");
message += application_identifier;
print_error(message.c_str(), device_identifier, method_id, result);
return NULL;
}
devices[device_identifier].apps_cache[application_identifier].afc_connection = conn;
return conn;
}
HANDLE start_debug_server(std::string device_identifier, std::string ddi, std::string method_id)
{
ServiceInfo info = start_secure_service(device_identifier, kDebugServer, method_id, false, false);
// mount_image is not available on Windows
#ifndef _WIN32
if (!info.socket && mount_image(device_identifier, ddi, method_id))
{
info = start_secure_service(device_identifier, kDebugServer, method_id, true, false);
}
#endif
return info.socket;
}
AFCConnectionRef get_afc_connection(std::string& device_identifier, const char* application_identifier, std::string& root_path, std::string& method_id)
{
if (devices.count(device_identifier) && devices[device_identifier].apps_cache[application_identifier].afc_connection)
{
return devices[device_identifier].apps_cache[application_identifier].afc_connection;
}
AFCConnectionRef con_ref = start_house_arrest(device_identifier, application_identifier, method_id);
if (!con_ref)
{
return NULL;
}
devices[device_identifier].apps_cache[application_identifier].afc_connection = con_ref;
return con_ref;
}
void uninstall_application(std::string application_identifier, std::string device_identifier, std::string method_id)
{
if (!devices.count(device_identifier))
{
print_error("Device not found", device_identifier, method_id, kAMDNotFoundError);
return;
}
ServiceInfo serviceInfo = start_secure_service(device_identifier, kInstallationProxy, method_id, true, false);
if (!serviceInfo.socket)
{
return;
}
CFStringRef appid_cfstring = create_CFString(application_identifier.c_str());
DeviceInfo* deviceInfo = devices[device_identifier].device_info;
CFDictionaryRef params = CFDictionaryCreate(NULL, {}, {}, 0, NULL, NULL);
unsigned result = AMDeviceSecureUninstallApplication(serviceInfo.connection, deviceInfo, appid_cfstring, params, NULL);
CFRelease(appid_cfstring);
if (result)
{
print_error("Could not uninstall application", device_identifier, method_id, result);
}
else
{
print(json({{ kResponse, "Successfully uninstalled application" }, { kId, method_id }, { kDeviceId, device_identifier }}));
// AppleFileConnection and HouseArrest deal with the files on an application so they have to be removed when uninstalling the application
cleanup_file_resources(device_identifier, application_identifier);
}
}
void install_application(std::string install_path, std::string device_identifier, std::string method_id)
{
if (!devices.count(device_identifier))
{
print_error("Device not found", device_identifier, method_id, kAMDNotFoundError);
return;
}
#ifdef _WIN32
if (install_path.compare(0, kFilePrefix.size(), kFilePrefix))
{
install_path = kFilePrefix + install_path;
}
install_path = windows_path_to_unix(install_path);
install_path = url_encode_without_forward_slash_and_colon(install_path);
#endif
int session_result = start_session(device_identifier);
if (session_result) {
print_error("Could not start device session", device_identifier, method_id, session_result);
return;
}
CFStringRef path = create_CFString(install_path.c_str());
CFURLRef local_app_url =
#ifdef _WIN32
CFURLCreateWithString(NULL, path, NULL);
#else
CFURLCreateWithFileSystemPath(NULL, path, kCFURLPOSIXPathStyle, true);
#endif
CFRelease(path);
if (!local_app_url)
{
stop_session(device_identifier);
print_error("Could not parse application path", device_identifier, method_id, kAMDAPIInternalError);
return;
}
CFStringRef cf_package_type = create_CFString("PackageType");
CFStringRef cf_developer = create_CFString("Developer");
const void *keys_arr[] = { cf_package_type };
const void *values_arr[] = { cf_developer };
CFDictionaryRef options = CFDictionaryCreate(NULL, keys_arr, values_arr, 1, NULL, NULL);
unsigned transfer_result = AMDeviceSecureTransferPath(0, devices[device_identifier].device_info, local_app_url, options, NULL, 0);
stop_session(device_identifier);
if (transfer_result)
{
print_error("Could not transfer application", device_identifier, method_id, transfer_result);
return;
}
session_result = start_session(device_identifier);
if (session_result) {
print_error("Could not start device session", device_identifier, method_id, session_result);
return;
}
unsigned install_result = AMDeviceSecureInstallApplication(0, devices[device_identifier].device_info, local_app_url, options, NULL, 0);
CFRelease(cf_package_type);
CFRelease(cf_developer);
stop_session(device_identifier);
if (install_result)
{
print_error("Could not install application", device_identifier, method_id, install_result);
return;
}
print(json({ { kResponse, "Successfully installed application" }, { kId, method_id }, {kDeviceId, device_identifier}}));
// In case this is a REinstall we need to invalidate cached file resources
cleanup_file_resources(device_identifier);
}
void perform_detached_operation(void(*operation)(std::string, std::string), std::string arg, std::string method_id)
{
std::thread([operation, arg, method_id]() { operation(arg, method_id); }).detach();
}
void perform_detached_operation(void(*operation)(std::string, std::string, std::string), json method_args, std::string method_id)
{
std::string first_arg = method_args[0].get<std::string>();
std::vector<std::string> device_identifiers = method_args[1].get<std::vector<std::string>>();
for (std::string &device_identifier : device_identifiers)
std::thread([operation, first_arg, device_identifier, method_id]() { operation(first_arg, device_identifier, method_id); }).detach();
}
void read_dir(AFCConnectionRef afc_conn_p, const char* dir, json &files, std::stringstream &errors, std::string method_id, std::string device_identifier)
{
char *dir_ent;
files.push_back(dir);
afc_dictionary afc_dict;
afc_dictionary* afc_dict_p = &afc_dict;
unsigned afc_file_info_open_result = AFCFileInfoOpen(afc_conn_p, dir, &afc_dict_p);
if (afc_file_info_open_result)
{
errors << "Could not open file info for file: ";
errors << dir;
errors << '\n';
return;
}
afc_directory afc_dir;
afc_directory* afc_dir_p = &afc_dir;
unsigned err = AFCDirectoryOpen(afc_conn_p, dir, &afc_dir_p);
if (err != 0)
{
// Couldn't open dir - was probably a file
return;
}
while (true)
{
err = AFCDirectoryRead(afc_conn_p, afc_dir_p, &dir_ent);
if (!dir_ent)
break;
if (strcmp(dir_ent, ".") == 0 || strcmp(dir_ent, "..") == 0)
continue;
char* dir_joined = (char*)malloc(strlen(dir) + strlen(dir_ent) + 2);
strcpy(dir_joined, dir);
if (dir_joined[strlen(dir) - 1] != '/')
strcat(dir_joined, "/");
strcat(dir_joined, dir_ent);
read_dir(afc_conn_p, dir_joined, files, errors, method_id, device_identifier);
free(dir_joined);
}
unsigned afc_directory_close_result = AFCDirectoryClose(afc_conn_p, afc_dir_p);
if (afc_directory_close_result)
{
errors << "Could not close directory: ";
errors << dir_ent;
errors << '\n';
}
}
std::mutex list_files_mutex;
void list_files(std::string device_identifier, const char *application_identifier, const char *device_path, std::string method_id)
{
list_files_mutex.lock();
std::string device_root(device_path);
AFCConnectionRef afc_conn_p = get_afc_connection(device_identifier, application_identifier, device_root, method_id);
if (!afc_conn_p)
{
print_error("Could not establish AFC Connection", device_identifier, method_id);
list_files_mutex.unlock();
return;
}
json files;
std::stringstream errors;
std::string device_path_str = windows_path_to_unix(device_path);
read_dir(afc_conn_p, device_path_str.c_str(), files, errors, method_id, device_identifier);
if (!files.empty())
{
print(json({{ kResponse, files }, { kId, method_id }, { kDeviceId, device_identifier }}));
}
if (errors.rdbuf()->in_avail() != 0)
{
print_error(errors.str().c_str(), device_identifier, method_id, kAFCCustomError);
}
cleanup_file_resources(device_identifier, application_identifier);
list_files_mutex.unlock();
}
bool ensure_device_path_exists(std::string &device_path, AFCConnectionRef connection)
{
std::vector<std::string> directories = split(device_path, kUnixPathSeparator);
std::string curent_device_path("");
for (std::string &directory_path : directories)
{
if (!directory_path.empty())
{
curent_device_path += kUnixPathSeparator;
curent_device_path += directory_path;
if (AFCDirectoryCreate(connection, curent_device_path.c_str()))
return false;
}
}
return true;
}
std::mutex upload_file_mutex;
void upload_file(std::string device_identifier, const char *application_identifier, const std::vector<FileUploadData>& files, std::string method_id) {
json success_json = json({ { kResponse, "Successfully uploaded files" },{ kId, method_id },{ kDeviceId, device_identifier } });
if (!files.size())
{
print(success_json);
return;
}
upload_file_mutex.lock();
std::string afc_destination_str = windows_path_to_unix(files[0].destination);
AFCConnectionRef afc_conn_p = get_afc_connection(device_identifier, application_identifier, afc_destination_str, method_id);
if (!afc_conn_p)
{
upload_file_mutex.unlock();
// If there is no opened afc connection the get_afc_connection will print the error for the operation.
return;
}
// We need to set the size of errors here because we need to access the elements by index.
// If we don't access them by index and use push_back from multiple threads, some of them will try to push at the same memory.
// The result of this will be an exception.
std::vector<std::string> errors(files.size());
std::vector<std::thread> file_upload_threads;
// We're only ever going to insert kDeviceUploadFilesBatchSize elements
file_upload_threads.reserve(kDeviceUploadFilesBatchSize);
// Launching a separate thread for each file puts a strain on the OS' memory
// That's why we launch batches of threads - kDeviceUploadFilesBatchSize each
size_t batch_end = files.size() / kDeviceUploadFilesBatchSize + 1;
for (size_t batch_index = 0; batch_index < batch_end; ++batch_index)
{
size_t start = batch_index * kDeviceUploadFilesBatchSize;
size_t end = (std::min)((batch_index + 1 ) * kDeviceUploadFilesBatchSize, files.size());
for (size_t i = start; i < end; ++i)
{
FileUploadData current_file_data = files[i];
file_upload_threads.emplace_back([=, &errors]() -> void
{
afc_file_ref file_ref;
std::string source = current_file_data.source;
std::string destination = current_file_data.destination;
FileInfo file_info = get_file_info(source, true);
if (file_info.size >= 0)
{
std::string dir_name = get_dirname(destination);
if (ensure_device_path_exists(dir_name, afc_conn_p))
{
std::stringstream error_message;
AFCRemovePath(afc_conn_p, destination.c_str());
error_message << "Could not open file " << destination << " for writing";
if (AFCFileRefOpen(afc_conn_p, destination.c_str(), kAFCFileModeWrite, &file_ref))
{
errors[i] = error_message.str();
return;
}
error_message.str("");
error_message << "Could not write to file: " << destination;
if (AFCFileRefWrite(afc_conn_p, file_ref, &file_info.contents[0], file_info.size))
{
errors[i] = error_message.str();
return;
}
error_message.str("");
error_message << "Could not close file reference: " << destination;
if (AFCFileRefClose(afc_conn_p, file_ref))
{
errors[i] = error_message.str();
return;
}
}
else
{
std::string message("Could not create device path for file: ");
message += source;
errors.push_back(message);
}
}
else
{
std::string message("Could not open file: ");
message += source;
errors.push_back(message);
}
});
}
for (std::thread& file_upload_thread : file_upload_threads)
{
file_upload_thread.join();
}
// After a batch is completed we need to empty file_upload_threads so that the new batch may take the old one's place
file_upload_threads.clear();
cleanup_file_resources(device_identifier, application_identifier);
upload_file_mutex.unlock();
}
std::vector<std::string> filtered_errors;
std::copy_if(std::begin(errors), std::end(errors), std::back_inserter(filtered_errors), [](std::string e) { return e.size() != 0; });
if (!filtered_errors.size())
{
print(success_json);
}
else
{
print_errors(filtered_errors, device_identifier, method_id, kAMDAPIInternalError);
}
}
std::mutex delete_file_mutex;
void delete_file(std::string device_identifier, const char *application_identifier, const char *destination, std::string method_id) {
delete_file_mutex.lock();
std::string destination_str = windows_path_to_unix(destination);
AFCConnectionRef afc_conn_p = get_afc_connection(device_identifier, application_identifier, destination_str, method_id);
if (!afc_conn_p)
{
delete_file_mutex.unlock();
return;
}
destination = destination_str.c_str();
std::stringstream error_message;
error_message << "Could not remove file " << destination;
unsigned afcRemovePathResult = AFCRemovePath(afc_conn_p, destination);
cleanup_file_resources(device_identifier, application_identifier);
delete_file_mutex.unlock();
PRINT_ERROR_AND_RETURN_IF_FAILED_RESULT(afcRemovePathResult, error_message.str().c_str(), device_identifier, method_id);
print(json({{ kResponse, "Successfully removed file" },{ kId, method_id },{ kDeviceId, device_identifier } }));
}
std::unique_ptr<afc_file> get_afc_file(std::string device_identifier, const char *application_identifier, const char *destination, std::string method_id){
afc_file_ref file_ref;
std::string destination_str = windows_path_to_unix(destination);
AFCConnectionRef afc_conn_p = get_afc_connection(device_identifier, application_identifier, destination_str, method_id);
if (!afc_conn_p)
{
return NULL;
}
destination = destination_str.c_str();
std::stringstream error_message;
error_message << "Could not open file " << destination << " for reading";
PRINT_ERROR_AND_RETURN_VALUE_IF_FAILED_RESULT(AFCFileRefOpen(afc_conn_p, destination, kAFCFileModeRead, &file_ref), error_message.str().c_str(), device_identifier, method_id, NULL);
std::unique_ptr<afc_file> result(new afc_file{ file_ref, afc_conn_p });
return result;
}
std::mutex read_file_mutex;
void read_file(std::string device_identifier, const char *application_identifier, const char *path, std::string method_id, const char *destination = nullptr) {
read_file_mutex.lock();
std::unique_ptr<afc_file> file = get_afc_file(device_identifier, application_identifier, path, method_id);
if (!file)
{
read_file_mutex.unlock();
return;
}
size_t read_size = kDeviceFileBytesToRead;
std::string result;
char *buf;
if (destination)
{
// Write the contents of the source file to the destination
std::ofstream ostream;
ostream.open(destination);
do
{
buf = new char[kDeviceFileBytesToRead];
AFCFileRefRead(file->afc_conn_p, file->file_ref, buf, &read_size);
ostream.write(buf, read_size);
free(buf);
} while (read_size == kDeviceFileBytesToRead);
ostream.close();
result = std::string("File written successfully!");
}
else
{
// Pipe the contents of the file to the stdout
std::vector<char> file_contents;
do
{
buf = new char[kDeviceFileBytesToRead];
AFCFileRefRead(file->afc_conn_p, file->file_ref, buf, &read_size);
file_contents.insert(file_contents.end(), buf, buf + read_size);
free(buf);
} while (read_size == kDeviceFileBytesToRead);
result = std::string(file_contents.begin(), file_contents.end());
}
unsigned afcFileRefCloseResult = AFCFileRefClose(file->afc_conn_p, file->file_ref);
cleanup_file_resources(device_identifier, application_identifier);
read_file_mutex.unlock();
PRINT_ERROR_AND_RETURN_IF_FAILED_RESULT(afcFileRefCloseResult, "Could not close file reference", device_identifier, method_id);
print(json({{ kResponse, result },{ kId, method_id },{ kDeviceId, device_identifier } }));
}
void get_application_infos(std::string device_identifier, std::string method_id)
{
ServiceInfo serviceInfo = start_secure_service(device_identifier, kInstallationProxy, method_id, true, false);
if (!serviceInfo.socket)
{
return;
}
CFStringRef cf_bundle_id_key = create_CFString("CFBundleIdentifier");
CFStringRef cf_config_key = create_CFString("configuration");
const void* cf_return_attributes[] = { cf_bundle_id_key, cf_config_key };
const CFArrayRef cf_return_attributes_array = CFArrayCreate(NULL, cf_return_attributes, 2, NULL);
CFStringRef cf_app_type_key = create_CFString("ApplicationType");
CFStringRef cf_return_attrs_key = create_CFString("ReturnAttributes");
const void *client_opts_keys_arr[] = { cf_app_type_key, cf_return_attrs_key };
CFStringRef cf_app_type_value = create_CFString("User");
const void *client_opts_values_arr[] = { cf_app_type_value, cf_return_attributes_array };
CFDictionaryRef client_opts_dict = CFDictionaryCreate(NULL, client_opts_keys_arr, client_opts_values_arr, 2, NULL, NULL);
CFStringRef cf_command_key = create_CFString("Command");
CFStringRef cf_client_options_key = create_CFString("ClientOptions");
const void *keys_arr[] = { cf_command_key, cf_client_options_key };
CFStringRef cf_command_value = create_CFString("Browse");
const void *values_arr[] = { cf_command_value, client_opts_dict };
CFDictionaryRef dict_command = CFDictionaryCreate(NULL, keys_arr, values_arr, 2, NULL, NULL);
send_con_message(serviceInfo.connection, dict_command);
CFRelease(cf_bundle_id_key);
CFRelease(cf_config_key);
CFRelease(cf_return_attributes_array);
CFRelease(cf_app_type_key);
CFRelease(cf_return_attrs_key);
CFRelease(cf_app_type_value);
CFRelease(client_opts_dict);
CFRelease(cf_command_key);
CFRelease(cf_client_options_key);
CFRelease(cf_command_value);
CFRelease(dict_command);