forked from ish-app/ish
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AppDelegate.m
342 lines (294 loc) · 14.3 KB
/
AppDelegate.m
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
//
// AppDelegate.m
// iSH
//
// Created by Theodore Dubois on 10/17/17.
//
#include <resolv.h>
#include <arpa/inet.h>
#include <netdb.h>
#import <SystemConfiguration/SystemConfiguration.h>
#import "AboutViewController.h"
#import "AppDelegate.h"
#import "AppGroup.h"
#import "iOSFS.h"
#import "SceneDelegate.h"
#import "PasteboardDevice.h"
#import "LocationDevice.h"
#import "NSObject+SaneKVO.h"
#import "Roots.h"
#import "TerminalViewController.h"
#import "UserPreferences.h"
#import "UIApplication+OpenURL.h"
#include "kernel/init.h"
#include "kernel/calls.h"
#include "fs/dyndev.h"
#include "fs/devices.h"
#include "fs/path.h"
@interface AppDelegate ()
@property BOOL exiting;
@property NSString *unameVersion;
@property NSString *unameHostname;
@property SCNetworkReachabilityRef reachability;
@end
static void ios_handle_exit(struct task *task, int code) {
// we are interested in init and in children of init
// this is called with pids_lock as an implementation side effect, please do not cite as an example of good API design
if (task->parent != NULL && task->parent->parent != NULL)
return;
// pid should be saved now since task would be freed
pid_t pid = task->pid;
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:ProcessExitedNotification
object:nil
userInfo:@{@"pid": @(pid),
@"code": @(code)}];
});
}
// Put the abort message in the thread name so it gets included in the crash dump
static void ios_handle_die(const char *msg) {
char name[17];
pthread_getname_np(pthread_self(), name, sizeof(name));
NSString *newName = [NSString stringWithFormat:@"%s died: %s", name, msg];
pthread_setname_np(newName.UTF8String);
}
static int bootError;
static int fs_ish_version;
static NSString *const kSkipStartupMessage = @"Skip Startup Message";
@implementation AppDelegate
- (int)boot {
NSURL *root = [[Roots.instance rootUrl:Roots.instance.defaultRoot] URLByAppendingPathComponent:@"data"];
int err = mount_root(&fakefs, root.fileSystemRepresentation);
if (err < 0)
return err;
fs_register(&iosfs);
fs_register(&iosfs_unsafe);
// need to do this first so that we can have a valid current for the generic_mknod calls
err = become_first_process();
if (err < 0)
return err;
// /ish/version is the last ish version that opened this root. Used to migrate the filesystem.
struct fd *ish_version_fd = generic_open("/ish/version", O_RDONLY_, 0);
if (!IS_ERR(ish_version_fd)) {
char buf[100];
ssize_t n = ish_version_fd->ops->read(ish_version_fd, buf, sizeof(buf));
if (n < 0)
return (int) n;
NSString *version = [[NSString alloc] initWithBytesNoCopy:buf length:n encoding:NSUTF8StringEncoding freeWhenDone:NO];
version = [version stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];
fs_ish_version = version.intValue;
fd_close(ish_version_fd);
NSURL *repositories = [NSBundle.mainBundle URLForResource:@"repositories" withExtension:@"txt"];
if (repositories != nil) {
NSData *repositoriesData = [NSData dataWithContentsOfURL:repositories];
struct fd *repositories_fd = generic_open("/etc/apk/repositories", O_WRONLY_|O_TRUNC_, 0);
if (!IS_ERR(repositories_fd)) {
repositories_fd->ops->write(repositories_fd, repositoriesData.bytes, repositoriesData.length);
fd_close(repositories_fd);
}
}
generic_rmdirat(AT_PWD, "/ish/apk");
NSString *currentVersion = NSBundle.mainBundle.infoDictionary[(__bridge NSString *) kCFBundleVersionKey];
if (currentVersion.intValue > fs_ish_version) {
fs_ish_version = currentVersion.intValue;
ish_version_fd = generic_open("/ish/version", O_WRONLY_|O_TRUNC_, 0644);
if (!IS_ERR(ish_version_fd)) {
NSString *file = [NSString stringWithFormat:@"%@\n", currentVersion];
ish_version_fd->ops->write(ish_version_fd, file.UTF8String, [file lengthOfBytesUsingEncoding:NSUTF8StringEncoding]);
fd_close(ish_version_fd);
}
}
}
// create some device nodes
// this will do nothing if they already exist
generic_mknodat(AT_PWD, "/dev/tty1", S_IFCHR|0666, dev_make(TTY_CONSOLE_MAJOR, 1));
generic_mknodat(AT_PWD, "/dev/tty2", S_IFCHR|0666, dev_make(TTY_CONSOLE_MAJOR, 2));
generic_mknodat(AT_PWD, "/dev/tty3", S_IFCHR|0666, dev_make(TTY_CONSOLE_MAJOR, 3));
generic_mknodat(AT_PWD, "/dev/tty4", S_IFCHR|0666, dev_make(TTY_CONSOLE_MAJOR, 4));
generic_mknodat(AT_PWD, "/dev/tty5", S_IFCHR|0666, dev_make(TTY_CONSOLE_MAJOR, 5));
generic_mknodat(AT_PWD, "/dev/tty6", S_IFCHR|0666, dev_make(TTY_CONSOLE_MAJOR, 6));
generic_mknodat(AT_PWD, "/dev/tty7", S_IFCHR|0666, dev_make(TTY_CONSOLE_MAJOR, 7));
generic_mknodat(AT_PWD, "/dev/tty", S_IFCHR|0666, dev_make(TTY_ALTERNATE_MAJOR, DEV_TTY_MINOR));
generic_mknodat(AT_PWD, "/dev/console", S_IFCHR|0666, dev_make(TTY_ALTERNATE_MAJOR, DEV_CONSOLE_MINOR));
generic_mknodat(AT_PWD, "/dev/ptmx", S_IFCHR|0666, dev_make(TTY_ALTERNATE_MAJOR, DEV_PTMX_MINOR));
generic_mknodat(AT_PWD, "/dev/null", S_IFCHR|0666, dev_make(MEM_MAJOR, DEV_NULL_MINOR));
generic_mknodat(AT_PWD, "/dev/zero", S_IFCHR|0666, dev_make(MEM_MAJOR, DEV_ZERO_MINOR));
generic_mknodat(AT_PWD, "/dev/full", S_IFCHR|0666, dev_make(MEM_MAJOR, DEV_FULL_MINOR));
generic_mknodat(AT_PWD, "/dev/random", S_IFCHR|0666, dev_make(MEM_MAJOR, DEV_RANDOM_MINOR));
generic_mknodat(AT_PWD, "/dev/urandom", S_IFCHR|0666, dev_make(MEM_MAJOR, DEV_URANDOM_MINOR));
generic_mkdirat(AT_PWD, "/dev/pts", 0755);
// Permissions on / have been broken for a while, let's fix them
generic_setattrat(AT_PWD, "/", (struct attr) {.type = attr_mode, .mode = 0755}, false);
// Register clipboard device driver and create device node for it
err = dyn_dev_register(&clipboard_dev, DEV_CHAR, DYN_DEV_MAJOR, DEV_CLIPBOARD_MINOR);
if (err != 0) {
return err;
}
generic_mknodat(AT_PWD, "/dev/clipboard", S_IFCHR|0666, dev_make(DYN_DEV_MAJOR, DEV_CLIPBOARD_MINOR));
err = dyn_dev_register(&location_dev, DEV_CHAR, DYN_DEV_MAJOR, DEV_LOCATION_MINOR);
if (err != 0)
return err;
generic_mknodat(AT_PWD, "/dev/location", S_IFCHR|0666, dev_make(DYN_DEV_MAJOR, DEV_LOCATION_MINOR));
do_mount(&procfs, "proc", "/proc", "", 0);
do_mount(&devptsfs, "devpts", "/dev/pts", "", 0);
iosfs_init(); // let it mount any filesystems from user defaults
[self configureDns];
exit_hook = ios_handle_exit;
die_handler = ios_handle_die;
#if !TARGET_OS_SIMULATOR
NSString *sockTmp = [NSTemporaryDirectory() stringByAppendingString:@"ishsock"];
sock_tmp_prefix = strdup(sockTmp.UTF8String);
#endif
tty_drivers[TTY_CONSOLE_MAJOR] = &ios_console_driver;
set_console_device(TTY_CONSOLE_MAJOR, 1);
err = create_stdio("/dev/console", TTY_CONSOLE_MAJOR, 1);
if (err < 0)
return err;
NSArray<NSString *> *command;
command = UserPreferences.shared.bootCommand;
NSLog(@"%@", command);
char argv[4096];
[Terminal convertCommand:command toArgs:argv limitSize:sizeof(argv)];
const char *envp = "TERM=xterm-256color\0";
err = do_execve(command[0].UTF8String, command.count, argv, envp);
if (err < 0)
return err;
task_start(current);
return 0;
}
- (void)configureDns {
struct __res_state res;
if (EXIT_SUCCESS != res_ninit(&res)) {
exit(2);
}
NSMutableString *resolvConf = [NSMutableString new];
if (res.dnsrch[0] != NULL) {
[resolvConf appendString:@"search"];
for (int i = 0; res.dnsrch[i] != NULL; i++) {
[resolvConf appendFormat:@" %s", res.dnsrch[i]];
}
[resolvConf appendString:@"\n"];
}
union res_sockaddr_union servers[NI_MAXSERV];
int serversFound = res_getservers(&res, servers, NI_MAXSERV);
char address[NI_MAXHOST];
for (int i = 0; i < serversFound; i ++) {
union res_sockaddr_union s = servers[i];
if (s.sin.sin_len == 0)
continue;
getnameinfo((struct sockaddr *) &s.sin, s.sin.sin_len,
address, sizeof(address),
NULL, 0, NI_NUMERICHOST);
[resolvConf appendFormat:@"nameserver %s\n", address];
}
current = pid_get_task(1);
struct fd *fd = generic_open("/etc/resolv.conf", O_WRONLY_ | O_CREAT_ | O_TRUNC_, 0666);
if (!IS_ERR(fd)) {
fd->ops->write(fd, resolvConf.UTF8String, [resolvConf lengthOfBytesUsingEncoding:NSUTF8StringEncoding]);
fd_close(fd);
}
}
+ (int)bootError {
return bootError;
}
+ (void)maybePresentStartupMessageOnViewController:(UIViewController *)vc {
if ([NSUserDefaults.standardUserDefaults integerForKey:kSkipStartupMessage] >= 1)
return;
if (fs_ish_version == 0) {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Install iSH’s built-in APK?"
message:@"iSH now includes the APK package manager, but it must be manually activated."
preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"Show me how"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * _Nonnull action) {
[UIApplication openURL:@"https://go.ish.app/get-apk"];
}]];
[alert addAction:[UIAlertAction actionWithTitle:@"Don't show again"
style:UIAlertActionStyleDefault
handler:nil]];
[vc presentViewController:alert animated:YES completion:nil];
}
[NSUserDefaults.standardUserDefaults setInteger:1 forKey:kSkipStartupMessage];
}
- (BOOL)application:(UIApplication *)application willFinishLaunchingWithOptions:(NSDictionary<UIApplicationLaunchOptionsKey,id> *)launchOptions {
NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
if ([defaults boolForKey:@"hail mary"]) {
[defaults removeObjectForKey:kPreferenceBootCommandKey];
[defaults removeObjectForKey:kPreferenceLaunchCommandKey];
[defaults setBool:NO forKey:@"hail mary"];
}
if ([NSUserDefaults.standardUserDefaults boolForKey:@"recovery"])
return YES;
bootError = [self boot];
return YES;
}
void NetworkReachabilityCallback(SCNetworkReachabilityRef target, SCNetworkReachabilityFlags flags, void *info) {
AppDelegate *self = (__bridge AppDelegate *) info;
[self configureDns];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// get the network permissions popup to appear on chinese devices
[[NSURLSession.sharedSession dataTaskWithURL:[NSURL URLWithString:@"http://captive.apple.com"]] resume];
if ([NSUserDefaults.standardUserDefaults boolForKey:@"FASTLANE_SNAPSHOT"])
[UIView setAnimationsEnabled:NO];
self.unameVersion = [NSString stringWithFormat:@"iSH %@ (%@)",
[NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleShortVersionString"],
[NSBundle.mainBundle objectForInfoDictionaryKey:(NSString *) kCFBundleVersionKey]];
extern const char *uname_version;
uname_version = self.unameVersion.UTF8String;
// this defaults key is set when taking app store screenshots
self.unameHostname = [NSUserDefaults.standardUserDefaults stringForKey:@"hostnameOverride"];
extern const char *uname_hostname_override;
uname_hostname_override = self.unameHostname.UTF8String;
[UserPreferences.shared observe:@[@"shouldDisableDimming"] options:NSKeyValueObservingOptionInitial
owner:self usingBlock:^(typeof(self) self) {
UIApplication.sharedApplication.idleTimerDisabled = UserPreferences.shared.shouldDisableDimming;
}];
struct sockaddr_in6 address = {
.sin6_len = sizeof(address),
.sin6_family = AF_INET6,
};
self.reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (struct sockaddr *) &address);
SCNetworkReachabilityContext context = {
.info = (__bridge void *) self,
};
SCNetworkReachabilitySetCallback(self.reachability, NetworkReachabilityCallback, &context);
SCNetworkReachabilityScheduleWithRunLoop(self.reachability, CFRunLoopGetMain(), kCFRunLoopCommonModes);
if (self.window != nil) {
// For iOS <13, where the app delegate owns the window instead of the scene
if ([NSUserDefaults.standardUserDefaults boolForKey:@"recovery"]) {
UINavigationController *vc = [[UIStoryboard storyboardWithName:@"About" bundle:nil] instantiateInitialViewController];
AboutViewController *avc = (AboutViewController *) vc.topViewController;
avc.recoveryMode = YES;
self.window.rootViewController = vc;
return YES;
}
TerminalViewController *vc = (TerminalViewController *) self.window.rootViewController;
currentTerminalViewController = vc;
[vc startNewSession];
}
return YES;
}
- (void)application:(UIApplication *)application didDiscardSceneSessions:(NSSet<UISceneSession *> *)sceneSessions API_AVAILABLE(ios(13.0)) {
for (UISceneSession *sceneSession in sceneSessions) {
NSString *terminalUUID = sceneSession.stateRestorationActivity.userInfo[@"TerminalUUID"];
[[Terminal terminalWithUUID:[[NSUUID alloc] initWithUUIDString:terminalUUID]] destroy];
}
}
- (void)dealloc {
if (self.reachability != NULL) {
SCNetworkReachabilityUnscheduleFromRunLoop(self.reachability, CFRunLoopGetMain(), kCFRunLoopCommonModes);
CFRelease(self.reachability);
}
}
- (void)exitApp {
self.exiting = YES;
id app = [UIApplication sharedApplication];
[app suspend];
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
if (self.exiting)
exit(0);
}
@end
NSString *const ProcessExitedNotification = @"ProcessExitedNotification";