forked from rileytestut/AltServer-Windows
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathAltServerApp.cpp
More file actions
2222 lines (1843 loc) · 65.1 KB
/
AltServerApp.cpp
File metadata and controls
2222 lines (1843 loc) · 65.1 KB
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
//
// AltServerApp.cpp
// AltServer-Windows
//
// Created by Riley Testut on 8/30/19.
// Copyright (c) 2019 Riley Testut. All rights reserved.
//
#include "AltServerApp.h"
#include <windows.h>
#include <windowsx.h>
#include <strsafe.h>
#include <Guiddef.h>
#include "AppleAPI.hpp"
#include "ConnectionManager.hpp"
#include "InstallError.hpp"
#include "Signer.hpp"
#include "DeviceManager.hpp"
#include "Archiver.hpp"
#include "ServerError.hpp"
#include "AnisetteDataManager.h"
#include <cpprest/http_client.h>
#include <cpprest/filestream.h>
#include <filesystem>
#include <regex>
#include <numeric>
#include <plist/plist.h>
#include <WS2tcpip.h>
#include <ShlObj_core.h>
#pragma comment( lib, "gdiplus.lib" )
#include <gdiplus.h>
#include <strsafe.h>
#include "resource.h"
#include <winsparkle/winsparkle.h>
#define odslog(msg) { std::stringstream ss; ss << msg << std::endl; OutputDebugStringA(ss.str().c_str()); }
using namespace utility; // Common utilities like string conversions
using namespace web; // Common features like URIs.
using namespace web::http; // Common HTTP functionality
using namespace web::http::client; // HTTP client features
using namespace concurrency::streams; // Asynchronous streams
namespace fs = std::filesystem;
extern std::string temporary_directory();
extern std::string make_uuid();
extern std::vector<unsigned char> readFile(const char* filename);
extern std::string StringFromWideString(std::wstring wideString);
extern std::wstring WideStringFromString(std::string string);
const char* REGISTRY_ROOT_KEY = "SOFTWARE\\RileyTestut\\AltServer";
const char* DID_LAUNCH_KEY = "Launched";
const char* LAUNCH_AT_STARTUP_KEY = "LaunchAtStartup";
const char* PRESENTED_RUNNING_NOTIFICATION_KEY = "PresentedRunningNotification";
const char* SERVER_ID_KEY = "ServerID";
const char* REPROVISIONED_DEVICE_KEY = "ReprovisionedDevice";
const char* APPLE_FOLDER_KEY = "AppleFolder";
const char* STARTUP_ITEMS_KEY = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run";
std::wstring altstoreSourceURL = L"https://apps.sidestore.io";
std::wstring altstoreBundleID = L"com.SideStore.SideStore";
std::string _verificationCode;
HKEY OpenRegistryKey()
{
HKEY hKey;
LONG nError = RegOpenKeyExA(HKEY_CURRENT_USER, REGISTRY_ROOT_KEY, NULL, KEY_ALL_ACCESS, &hKey);
if (nError == ERROR_FILE_NOT_FOUND)
{
nError = RegCreateKeyExA(HKEY_CURRENT_USER, REGISTRY_ROOT_KEY, NULL, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKey, NULL);
}
if (nError)
{
odslog("Error finding/creating registry value. " << nError);
}
return hKey;
}
void SetRegistryBoolValue(const char *lpValue, bool data)
{
int32_t value = data ? 1 : 0;
HKEY rootKey = OpenRegistryKey();
LONG nError = RegSetValueExA(rootKey, lpValue, NULL, REG_DWORD, (BYTE *)&value, sizeof(int32_t));
if (nError)
{
odslog("Error setting registry value. " << nError);
}
RegCloseKey(rootKey);
}
void SetRegistryStringValue(const char* lpValue, std::string string)
{
HKEY rootKey = OpenRegistryKey();
LONG nError = RegSetValueExA(rootKey, lpValue, NULL, REG_SZ, (const BYTE *)string.c_str(), string.size() + 1);
if (nError)
{
odslog("Error setting registry value. " << nError);
}
RegCloseKey(rootKey);
}
bool GetRegistryBoolValue(const char *lpValue)
{
HKEY rootKey = OpenRegistryKey();
int32_t data;
DWORD size = sizeof(int32_t);
DWORD type = REG_DWORD;
LONG nError = RegQueryValueExA(rootKey, lpValue, NULL, &type, (BYTE *)& data, &size);
if (nError == ERROR_FILE_NOT_FOUND)
{
data = 0;
}
else if (nError)
{
odslog("Could not get registry value. " << nError);
}
RegCloseKey(rootKey);
return (bool)data;
}
std::string GetRegistryStringValue(const char* lpValue)
{
HKEY rootKey = OpenRegistryKey();
char value[1024];
DWORD length = sizeof(value);
DWORD type = REG_SZ;
LONG nError = RegQueryValueExA(rootKey, lpValue, NULL, &type, (LPBYTE)& value, &length);
if (nError == ERROR_FILE_NOT_FOUND)
{
value[0] = 0;
}
else if (nError)
{
odslog("Could not get registry value. " << nError);
}
RegCloseKey(rootKey);
std::string string(value);
return string;
}
// Observes all exceptions that occurred in all tasks in the given range.
template<class T, class InIt>
void observe_all_exceptions(InIt first, InIt last)
{
std::for_each(first, last, [](concurrency::task<T> t)
{
t.then([](concurrency::task<T> previousTask)
{
try
{
previousTask.get();
}
catch (const std::exception&)
{
// Swallow the exception.
}
});
});
}
INT_PTR CALLBACK InstallDlgProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam)
{
switch (Message)
{
case WM_INITDIALOG:
{
std::map<std::string, std::wstring>* parameters = (std::map<std::string, std::wstring>*)lParam;
std::wstring title = (*parameters)["title"];
std::wstring message = (*parameters)["message"];
SetWindowText(hwnd, title.c_str());
HWND descriptionText = GetDlgItem(hwnd, IDC_DESCRIPTION);
SetWindowText(descriptionText, message.c_str());
HWND downloadButton = GetDlgItem(hwnd, IDOK);
PostMessage(hwnd, WM_NEXTDLGCTL, (WPARAM)downloadButton, TRUE);
return TRUE;
}
case WM_CTLCOLORSTATIC:
{
if (GetDlgCtrlID((HWND)lParam) == IDC_DESCRIPTION)
{
HBRUSH success = (HBRUSH)GetStockObject(HOLLOW_BRUSH);
SetBkMode((HDC)wParam, TRANSPARENT);
return (BOOL)success;
}
return TRUE;
}
case WM_COMMAND:
{
switch (LOWORD(wParam))
{
case IDOK:
case IDCANCEL:
case ID_FOLDER:
EndDialog(hwnd, LOWORD(wParam));
return TRUE;
}
}
default: break;
}
return FALSE;
}
INT_PTR CALLBACK TwoFactorDlgProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam)
{
HWND verificationCodeTextField = GetDlgItem(hwnd, IDC_EDIT1);
HWND submitButton = GetDlgItem(hwnd, IDOK);
switch (Message)
{
case WM_INITDIALOG:
{
Edit_SetCueBannerText(verificationCodeTextField, L"123456");
Button_Enable(submitButton, false);
break;
}
case WM_CTLCOLORSTATIC:
{
if (GetDlgCtrlID((HWND)lParam) == IDC_DESCRIPTION)
{
HBRUSH success = (HBRUSH)GetStockObject(HOLLOW_BRUSH);
SetBkMode((HDC)wParam, TRANSPARENT);
return (BOOL)success;
}
break;
}
case WM_COMMAND:
{
switch (HIWORD(wParam))
{
case EN_CHANGE:
{
/*PostMessage(hWnd, WM_CLOSE, 0, 0);
break;*/
int codeLength = Edit_GetTextLength(verificationCodeTextField);
if (codeLength == 6)
{
Button_Enable(submitButton, true);
}
else
{
Button_Enable(submitButton, false);
}
break;
}
}
switch (LOWORD(wParam))
{
case IDOK:
{
wchar_t verificationCode[512];
Edit_GetText(verificationCodeTextField, verificationCode, 512);
odslog("Verification Code:" << verificationCode);
_verificationCode = StringFromWideString(verificationCode);
EndDialog(hwnd, IDOK);
break;
}
case IDCANCEL:
EndDialog(hwnd, IDCANCEL);
break;
}
break;
}
default:
return FALSE;
}
return FALSE;
}
INT_PTR CALLBACK ChooseTeamDlgProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam)
{
HWND okButton = GetDlgItem(hwnd, IDOK);
HWND hwndList = GetDlgItem(hwnd, IDC_LIST_TEAM);
switch (Message)
{
case WM_INITDIALOG:
{
std::vector<std::shared_ptr<Team>>* teams = (std::vector<std::shared_ptr<Team>>*)lParam;
for (auto& team : *teams)
{
std::wstringstream item;
auto name = team->name();
auto identifier = team->identifier();
switch (team->type()) {
case Team::Type::Organization:
{
item << "Organization: ";
break;
}
case Team::Type::Free:
{
item << "Free: ";
break;
}
case Team::Type::Individual:
{
item << "Individual: ";
break;
}
default:
{
continue;
}
}
item << std::wstring(name.begin(), name.end()) << " - " << std::wstring(identifier.begin(), identifier.end());
int pos = (int)SendMessage(hwndList, LB_ADDSTRING, 0, (LPARAM)item.str().c_str());
// Set the array index of the player as item data.
// This enables us to retrieve the item from the array
// even after the items are sorted by the list box.
SendMessage(hwndList, LB_SETITEMDATA, pos, (LPARAM)&team);
}
SetFocus(hwndList);
PostMessage(hwnd, WM_NEXTDLGCTL, (WPARAM)okButton, TRUE);
return TRUE;
}
case WM_COMMAND:
{
switch (LOWORD(wParam))
{
case IDC_LIST_TEAM:
{
switch (HIWORD(wParam))
{
case LBN_SELCHANGE:
{
Button_Enable(okButton, true);
return TRUE;
}
}
return TRUE;
}
case IDOK:
{
int lbItem = (int)SendMessage(hwndList, LB_GETCURSEL, 0, 0);
auto team = SendMessage(hwndList, LB_GETITEMDATA, lbItem, 0);
EndDialog(hwnd, team);
return TRUE;
}
case IDCANCEL:
EndDialog(hwnd, IDCANCEL);
return TRUE;
}
}
default: break;
}
return FALSE;
}
VOID CALLBACK DetailedErrorMessageBoxCallback(LPHELPINFO lpHelpInfo)
{
auto helpError = AltServerApp::instance()->helpError();
if (helpError == NULL)
{
return;
}
std::string url("https://faq.altstore.io/getting-started/error-codes?q=");
url += helpError->domain() + "+" + std::to_string(helpError->displayCode());
ShellExecute(NULL, L"open", WideStringFromString(url).c_str(), NULL, NULL, SW_SHOWNORMAL);
}
VOID CALLBACK ErrorMessageBoxCallback(LPHELPINFO lpHelpInfo)
{
auto helpError = AltServerApp::instance()->helpError();
if (helpError == NULL)
{
return;
}
std::string localizedErrorCode = helpError->localizedErrorCode();
auto wideTitle = WideStringFromString(localizedErrorCode);
auto wideMessage = WideStringFromString(helpError->formattedDetailedDescription() + "\n\n" + "Press 'Help' to search the AltStore FAQ.");
MSGBOXPARAMSW parameters = {};
parameters.cbSize = sizeof(parameters);
parameters.lpszText = wideMessage.c_str();
parameters.lpszCaption = wideTitle.c_str();
parameters.lpfnMsgBoxCallback = DetailedErrorMessageBoxCallback;
parameters.dwStyle = MB_HELP | MB_ICONINFORMATION;
MessageBoxIndirectW(¶meters);
}
AltServerApp* AltServerApp::_instance = nullptr;
AltServerApp* AltServerApp::instance()
{
if (_instance == 0)
{
_instance = new AltServerApp();
}
return _instance;
}
AltServerApp::AltServerApp() : _appGroupSemaphore(1)
{
CLSIDFromString(L"{A549EEDA-6301-41BA-8323-312A2AF9D380}", &_notificationIconGUID);
}
AltServerApp::~AltServerApp()
{
}
static int CALLBACK BrowseFolderCallback(HWND hwnd, UINT uMsg, LPARAM lParam, LPARAM lpData)
{
if (uMsg == BFFM_INITIALIZED)
{
std::string tmp = (const char*)lpData;
odslog("Browser Path:" << tmp);
SendMessage(hwnd, BFFM_SETSELECTION, TRUE, lpData);
}
return 0;
}
std::string AltServerApp::BrowseForFolder(std::wstring title, std::string folderPath)
{
BROWSEINFO browseInfo = { 0 };
browseInfo.lpszTitle = title.c_str();
browseInfo.ulFlags = BIF_RETURNONLYFSDIRS | BIF_NEWDIALOGSTYLE | BIF_NONEWFOLDERBUTTON;
browseInfo.lpfn = BrowseFolderCallback;
browseInfo.lParam = (LPARAM)folderPath.c_str();
LPITEMIDLIST pidList = SHBrowseForFolder(&browseInfo);
if (pidList == 0)
{
return "";
}
TCHAR path[MAX_PATH];
SHGetPathFromIDList(pidList, path);
IMalloc* imalloc = NULL;
if (SUCCEEDED(SHGetMalloc(&imalloc)))
{
imalloc->Free(pidList);
imalloc->Release();
}
return StringFromWideString(path);
}
void AltServerApp::Start(HWND windowHandle, HINSTANCE instanceHandle)
{
_windowHandle = windowHandle;
_instanceHandle = instanceHandle;
#if STAGING
win_sparkle_set_appcast_url("https://raw.githubusercontent.com/SideStore/SideServer-Windows/develop/sparkle-windows.xml");
#else
win_sparkle_set_appcast_url("https://raw.githubusercontent.com/SideStore/SideServer-Windows/develop/sparkle-windows-staging.xml");
#endif
win_sparkle_init();
bool didLaunch = GetRegistryBoolValue(DID_LAUNCH_KEY);
if (!didLaunch)
{
// First launch.
// Automatically launch at login.
this->setAutomaticallyLaunchAtLogin(true);
auto serverID = make_uuid();
this->setServerID(serverID);
SetRegistryBoolValue(DID_LAUNCH_KEY, true);
}
Gdiplus::GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
Gdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
ConnectionManager::instance()->Start();
try
{
this->CheckDependencies();
AnisetteDataManager::instance()->LoadDependencies();
#if SPOOF_MAC
if (!this->CheckiCloudDependencies())
{
this->ShowAlert("iCloud Not Installed", "iCloud must be installed from Apple's website (not the Microsoft Store) in order to use SideStore.");
}
#endif
}
catch (AnisetteError &error)
{
this->HandleAnisetteError(error);
}
catch (Error& error)
{
this->ShowAlert("Failed to Start SideServer", error.localizedDescription());
}
catch (std::exception& exception)
{
this->ShowAlert("Failed to Start SideServer", exception.what());
}
odslog("SideServer launched?", !this->presentedRunningNotification())
if (!this->presentedRunningNotification())
{
this->ShowNotification("SideServer Running", "SideServer will continue to run in the background listening for SideStore.");
this->setPresentedRunningNotification(true);
}
else
{
// Make AltServer appear in notification area.
this->ShowNotification("", "");
}
DeviceManager::instance()->Start();
}
void AltServerApp::Stop()
{
win_sparkle_cleanup();
}
void AltServerApp::CheckForUpdates()
{
win_sparkle_check_update_with_ui();
}
pplx::task<std::shared_ptr<Application>> AltServerApp::InstallApplication(std::optional<std::string> filepath, std::shared_ptr<Device> installDevice, std::string appleID, std::string password)
{
auto appName = filepath.has_value() ? fs::path(*filepath).filename().string() : "SideStore";
auto localizedFailure = "Could not install " + appName + " to " + installDevice->name() + ".";
return this->_InstallApplication(filepath, installDevice, appleID, password)
.then([=](pplx::task<std::shared_ptr<Application>> task) -> pplx::task<std::shared_ptr<Application>> {
try
{
auto application = task.get();
return pplx::create_task([application]() {
return application;
});
}
catch (APIError& error)
{
if ((APIErrorCode)error.code() == APIErrorCode::InvalidAnisetteData)
{
// Our attempt to re-provision the device as a Mac failed, so reset provisioning and try one more time.
// This appears to happen when iCloud is running simultaneously, and just happens to provision device at same time as AltServer.
AnisetteDataManager::instance()->ResetProvisioning();
this->ShowNotification("Registering PC with Apple...", "This may take a few seconds.");
// Provisioning device can fail if attempted too soon after previous attempt.
// As a hack around this, we wait a bit before trying again.
// 10-11 seconds appears to be too short, so wait for 12 seconds instead.
Sleep(12000);
return this->_InstallApplication(filepath, installDevice, appleID, password);
}
else
{
throw;
}
}
})
.then([=](pplx::task<std::shared_ptr<Application>> task) -> std::shared_ptr<Application> {
try
{
auto application = task.get();
std::stringstream ss;
ss << application->name() << " was successfully installed on " << installDevice->name() << ".";
this->ShowNotification("Installation Succeeded", ss.str());
return application;
}
catch (InstallError& error)
{
if ((InstallErrorCode)error.code() == InstallErrorCode::Cancelled)
{
// Ignore
}
else
{
this->ShowErrorAlert(error, localizedFailure);
throw;
}
}
catch (APIError& error)
{
if ((APIErrorCode)error.code() == APIErrorCode::InvalidAnisetteData)
{
AnisetteDataManager::instance()->ResetProvisioning();
}
this->ShowErrorAlert(error, localizedFailure);
throw;
}
catch (AnisetteError& error)
{
this->HandleAnisetteError(error);
throw;
}
catch (std::exception& exception)
{
this->ShowErrorAlert(exception, localizedFailure);
throw;
}
});
}
pplx::task<std::shared_ptr<Application>> AltServerApp::_InstallApplication(std::optional<std::string> filepath, std::shared_ptr<Device> installDevice, std::string appleID, std::string password)
{
fs::path destinationDirectoryPath(temporary_directory());
destinationDirectoryPath.append(make_uuid());
auto account = std::make_shared<Account>();
auto app = std::make_shared<Application>();
auto team = std::make_shared<Team>();
auto device = std::make_shared<Device>();
auto appID = std::make_shared<AppID>();
auto certificate = std::make_shared<Certificate>();
auto profile = std::make_shared<ProvisioningProfile>();
auto session = std::make_shared<AppleAPISession>();
return pplx::create_task([=]() {
auto anisetteData = AnisetteDataManager::instance()->FetchAnisetteData();
return this->Authenticate(appleID, password, anisetteData);
})
.then([=](std::pair<std::shared_ptr<Account>, std::shared_ptr<AppleAPISession>> pair)
{
*account = *(pair.first);
*session = *(pair.second);
odslog("Fetching team...");
return this->FetchTeam(account, session);
})
.then([=](std::shared_ptr<Team> tempTeam)
{
odslog("Registering device...");
*team = *tempTeam;
return this->RegisterDevice(installDevice, team, session);
})
.then([=](std::shared_ptr<Device> tempDevice)
{
odslog("Fetching certificate...");
tempDevice->setName(installDevice->name()); // Ensure we use real device name.
tempDevice->setOSVersion(installDevice->osVersion());
*device = *tempDevice;
return this->FetchCertificate(team, session);
})
.then([=](std::shared_ptr<Certificate> tempCertificate)
{
*certificate = *tempCertificate;
odslog("Preparing device...");
return this->PrepareDevice(device).then([=](pplx::task<void> task) {
try
{
// Don't rethrow error, and instead continue installing app even if we couldn't install Developer disk image.
task.get();
}
catch (Error& error)
{
odslog("Failed to install DeveloperDiskImage.dmg to " << *device << ". " << error.localizedDescription());
}
catch (std::exception& exception)
{
odslog("Failed to install DeveloperDiskImage.dmg to " << *device << ". " << exception.what());
}
if (filepath.has_value())
{
odslog("Importing app...");
return pplx::create_task([filepath] {
return fs::path(*filepath);
});
}
else
{
odslog("Downloading app...");
// Show alert before downloading AltStore.
this->ShowInstallationNotification("AltStore", device->name());
return this->DownloadApp(device);
}
});
})
.then([=](fs::path downloadedAppPath)
{
odslog("Downloaded app!");
fs::create_directory(destinationDirectoryPath);
auto appBundlePath = UnzipAppBundle(downloadedAppPath.string(), destinationDirectoryPath.string());
auto app = std::make_shared<Application>(appBundlePath);
if (filepath.has_value())
{
// Show alert after "downloading" local .ipa.
this->ShowInstallationNotification(app->name(), device->name());
}
else
{
// Remove downloaded app.
try
{
fs::remove(downloadedAppPath);
}
catch (std::exception& e)
{
odslog("Failed to remove downloaded .ipa." << e.what());
}
}
return app;
})
.then([=](std::shared_ptr<Application> tempApp)
{
*app = *tempApp;
return this->PrepareAllProvisioningProfiles(app, device, team, session);
})
.then([=](std::map<std::string, std::shared_ptr<ProvisioningProfile>> profiles)
{
return this->InstallApp(app, device, team, certificate, profiles);
})
.then([=](pplx::task<std::shared_ptr<Application>> task)
{
if (fs::exists(destinationDirectoryPath))
{
fs::remove_all(destinationDirectoryPath);
}
try
{
auto application = task.get();
return application;
}
catch (LocalizedError& error)
{
if (error.code() == -22421)
{
// Don't know what API call returns this error code, so assume any LocalizedError with -22421 error code
// means invalid anisette data, then throw the correct APIError.
throw APIError(APIErrorCode::InvalidAnisetteData);
}
else if (error.code() == -29004)
{
// Same with -29004, "Environment Mismatch"
throw APIError(APIErrorCode::InvalidAnisetteData);
}
else
{
throw;
}
}
});
}
pplx::task<void> AltServerApp::PrepareDevice(std::shared_ptr<Device> device)
{
return DeviceManager::instance()->IsDeveloperDiskImageMounted(device)
.then([=](bool isMounted) {
if (isMounted)
{
return pplx::create_task([] { return; });
}
else
{
return this->_developerDiskManager.DownloadDeveloperDisk(device)
.then([=](std::pair<std::string, std::string> paths) {
return DeviceManager::instance()->InstallDeveloperDiskImage(paths.first, paths.second, device);
})
.then([=](pplx::task<void> task) {
try
{
task.get();
// No error thrown, so assume disk is compatible.
this->_developerDiskManager.SetDeveloperDiskCompatible(true, device);
}
catch (ServerError& serverError)
{
if (serverError.code() == (int)ServerErrorCode::IncompatibleDeveloperDisk)
{
// Developer disk is not compatible with this device, so mark it as incompatible.
this->_developerDiskManager.SetDeveloperDiskCompatible(false, device);
}
else
{
// Don't mark developer disk as incompatible because it probably failed for a different reason.
}
throw;
}
});
}
});
}
pplx::task<std::string> AltServerApp::FetchAltStoreDownloadURL(std::shared_ptr<Device> device)
{
uri_builder builder(altstoreSourceURL);
http_client client(builder.to_uri());
return client.request(methods::GET).then([=](http_response response)
{
return response.content_ready();
})
.then([=](http_response response)
{
odslog("Received SideStore source response status code: " << response.status_code());
return response.extract_vector();
})
.then([=](std::vector<unsigned char> decompressedData)
{
std::string decompressedJSON = std::string(decompressedData.begin(), decompressedData.end());
if (decompressedJSON.size() == 0)
{
return json::value::object();
}
utility::stringstream_t s;
s << WideStringFromString(decompressedJSON);
auto json = json::value::parse(s);
return json;
})
.then([=](json::value json) {
try
{
auto apps = json[L"apps"].as_array();
std::optional<json::value> altstore = std::nullopt;
for (auto& app : apps)
{
auto bundleID = app[L"bundleIdentifier"].as_string();
if (bundleID == altstoreBundleID)
{
altstore = app;
break;
}
}
auto bundleID = StringFromWideString(altstoreBundleID);
if (!altstore.has_value())
{
auto debugDescription = "App with bundle ID '" + bundleID + "' does not exist in source JSON.";
throw CocoaError(CocoaErrorCode::CoderValueNotFound, { {NSDebugDescriptionErrorKey, debugDescription} });
}
if (!altstore->has_array_field(L"versions"))
{
auto debugDescription = "There is no 'versions' key for " + bundleID + ".";
throw CocoaError(CocoaErrorCode::CoderReadCorrupt, { {NSDebugDescriptionErrorKey, debugDescription} });
}
auto versions = (*altstore)[L"versions"].as_array();
if (versions.size() == 0)
{
auto debugDescription = "The 'versions' array is empty for " + bundleID + ".";
throw CocoaError(CocoaErrorCode::CoderValueNotFound, { {NSDebugDescriptionErrorKey, debugDescription} });
}
auto latestVersion = versions[0];
std::optional<json::value> latestSupportedVersion = std::nullopt;
for (auto& version : versions)
{
if (!version.has_string_field(L"minOSVersion"))
{
// No minOSVersion, so assume it's compatible.
latestSupportedVersion = version;
break;
}
auto minOSVersionString = version[L"minOSVersion"].as_string();
auto minOSVersion = OperatingSystemVersion(StringFromWideString(minOSVersionString));
if (device->osVersion() < minOSVersion)
{
// Device OS version is older than minOSVersion, so ignore.
continue;
}
latestSupportedVersion = version;
break;
}
auto deviceOSName = ALTOperatingSystemNameForDeviceType(device->type());
std::string osName = deviceOSName.has_value() ? *deviceOSName : "iOS";
auto minOSVersionString = latestVersion.has_string_field(L"minOSVersion") ? StringFromWideString(latestVersion[L"minOSVersion"].as_string()) : "12.2";
if (!latestSupportedVersion.has_value())
{
throw ServerError(ServerErrorCode::UnsupportediOSVersion, { {AppNameErrorKey, "AltStore"}, {OperatingSystemNameErrorKey, osName}, {OperatingSystemVersionErrorKey, minOSVersionString} });
}
auto latestVersionNumber = latestVersion[L"version"].as_string();
auto latestSupportedVersionNumber = (*latestSupportedVersion)[L"version"].as_string();
if (latestVersionNumber == latestSupportedVersionNumber)
{
// Latest version is supported, so return downloadURL.
auto downloadURL = latestVersion[L"downloadURL"].as_string();
return StringFromWideString(downloadURL);
}
else
{
auto minOSVersion = StringFromWideString(latestVersion[L"minOSVersion"].as_string());
std::ostringstream oss;
oss << device->name() << " is running " << osName << " " << device->osVersion().stringValue() << ", but AltStore requires " << osName << " " << minOSVersion << " or later.";
oss << "\n\n";
oss << "Would you like to download the last version compatible with this device instead (AltStore " << StringFromWideString(latestSupportedVersionNumber) << ")?";
std::string alertTitle = "Unsupported " + osName + " Version";
auto alertResult = MessageBox(NULL, WideStringFromString(oss.str()).c_str(), WideStringFromString(alertTitle).c_str(), MB_OKCANCEL);
if (alertResult == IDCANCEL)
{
throw InstallError(InstallErrorCode::Cancelled);
}
auto downloadURL = (*latestSupportedVersion)[L"downloadURL"].as_string();
return StringFromWideString(downloadURL);
}
}
catch (Error& error)