]> git.saurik.com Git - safemode-ios.git/blob - Tweak.xm
7c7c20a047c8983edbc13eded51c1a9a5a104601
[safemode-ios.git] / Tweak.xm
1 /* Cydia Substrate - Powerful Code Insertion Platform
2 * Copyright (C) 2008-2013 Jay Freeman (saurik)
3 */
4
5 /* GNU Lesser General Public License, Version 3 {{{ */
6 /*
7 * Substrate is free software: you can redistribute it and/or modify it under
8 * the terms of the GNU Lesser General Public License as published by the
9 * Free Software Foundation, either version 3 of the License, or (at your
10 * option) any later version.
11 *
12 * Substrate is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
15 * License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public License
18 * along with Substrate. If not, see <http://www.gnu.org/licenses/>.
19 **/
20 /* }}} */
21
22 #import <CoreFoundation/CoreFoundation.h>
23 #import <Foundation/Foundation.h>
24 #import <CoreGraphics/CGGeometry.h>
25 #import <UIKit/UIKit.h>
26
27 #include <dlfcn.h>
28 #include <substrate.h>
29
30 Class $SafeModeAlertItem;
31
32 #define UIAlertActionStyleDefault 0
33
34 @interface UIAlertAction
35 + (UIAlertAction *) actionWithTitle:(NSString *)title style:(NSUInteger)style handler:(void (^)(UIAlertAction *action))handler;
36 @end
37
38 @interface UIAlertController : UIViewController
39 - (void) addAction:(UIAlertAction *)action;
40 - (void) setMessage:(NSString *)message;
41 - (void) setTitle:(NSString *)title;
42 @end
43
44 @interface SBAlertItem : NSObject {
45 }
46 - (UIAlertController *) alertController;
47 - (UIAlertView *) alertSheet;
48 - (void) deactivateForButton;
49 - (void) dismiss;
50 @end
51
52 @interface SBAlertItemsController : NSObject {
53 }
54 + (SBAlertItemsController *) sharedInstance;
55 - (void) activateAlertItem:(SBAlertItem *)item;
56 @end
57
58 @interface SBStatusBarTimeView : UIView {
59 }
60 - (id) textFont;
61 @end
62
63 @interface UIApplication (CydiaSubstrate)
64 - (void) applicationOpenURL:(id)url;
65 @end
66
67 @interface UIAlertView (CydiaSubstrate)
68 - (void) setForceHorizontalButtonsLayout:(BOOL)force;
69 - (void) setBodyText:(NSString *)body;
70 - (void) setNumberOfRows:(NSInteger)rows;
71 @end
72
73 void SafeModeButtonClicked(int button) {
74 switch (button) {
75 case 1:
76 break;
77
78 case 2:
79 if (kCFCoreFoundationVersionNumber >= 700)
80 system("killall backboardd");
81 else
82 // XXX: there are better ways of restarting SpringBoard that would actually save state
83 exit(0);
84 break;
85
86 case 3:
87 [[UIApplication sharedApplication] applicationOpenURL:[NSURL URLWithString:@"http://cydia.saurik.com/safemode/"]];
88 break;
89 }
90 }
91
92 void SafeModeButtonClicked(id self, int button) {
93 SafeModeButtonClicked(button);
94 [self deactivateForButton];
95 }
96
97 void SafeModeAlertItem$alertSheet$buttonClicked$(id self, SEL sel, id sheet, int button) {
98 SafeModeButtonClicked(button);
99 [self dismiss];
100 }
101
102 void SafeModeAlertItem$alertView$clickedButtonAtIndex$(id self, SEL sel, id sheet, NSInteger button) {
103 SafeModeButtonClicked(button + 1);
104 [self dismiss];
105 }
106
107 void SafeModeAlertItem$configure$requirePasscodeForActions$(id self, SEL sel, BOOL configure, BOOL require) {
108 NSString *text(@"We apologize for the inconvenience, but SpringBoard has just crashed.\n\nMobileSubstrate /did not/ cause this problem: it has protected you from it.\n\nSpringBoard is now running in Safe Mode. All extensions that support this safety system are disabled.\n\nReboot (or restart SpringBoard) to return to the normal mode. To return to this dialog touch the status bar.\n\nTap \"Help\" below for more tips.");
109
110 #ifdef __arm64__
111 if ([self respondsToSelector:@selector(alertController)]) {
112 UIAlertController *alert([self alertController]);
113
114 [alert setTitle:@""];
115 [alert setMessage:text];
116
117 [alert addAction:[%c(UIAlertAction) actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) { SafeModeButtonClicked(self, 1); }]];
118 [alert addAction:[%c(UIAlertAction) actionWithTitle:@"Restart" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) { SafeModeButtonClicked(self, 2); }]];
119 [alert addAction:[%c(UIAlertAction) actionWithTitle:@"Help" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) { SafeModeButtonClicked(self, 3); }]];
120
121 return;
122 }
123 #else
124 if (false) %c(UIAlertAction);
125 #endif
126
127 UIAlertView *sheet([self alertSheet]);
128 [sheet setDelegate:self];
129
130 [sheet setTitle:@""];
131 [sheet setBodyText:text];
132
133 [sheet addButtonWithTitle:@"OK"];
134 [sheet addButtonWithTitle:@"Restart"];
135 [sheet addButtonWithTitle:@"Help"];
136
137 [sheet setNumberOfRows:1];
138 if ([sheet respondsToSelector:@selector(setForceHorizontalButtonsLayout:)])
139 [sheet setForceHorizontalButtonsLayout:YES];
140 }
141
142 void SafeModeAlertItem$performUnlockAction(id self, SEL sel) {
143 [[%c(SBAlertItemsController) sharedInstance] activateAlertItem:self];
144 }
145
146 static void MSAlert() {
147 if ($SafeModeAlertItem == nil)
148 $SafeModeAlertItem = objc_lookUpClass("SafeModeAlertItem");
149 if ($SafeModeAlertItem == nil) {
150 $SafeModeAlertItem = objc_allocateClassPair(objc_getClass("SBAlertItem"), "SafeModeAlertItem", 0);
151 if ($SafeModeAlertItem == nil)
152 return;
153
154 class_addMethod($SafeModeAlertItem, @selector(alertSheet:buttonClicked:), (IMP) &SafeModeAlertItem$alertSheet$buttonClicked$, "v@:@i");
155 class_addMethod($SafeModeAlertItem, @selector(alertView:clickedButtonAtIndex:), (IMP) &SafeModeAlertItem$alertView$clickedButtonAtIndex$, "v@:@i");
156 class_addMethod($SafeModeAlertItem, @selector(configure:requirePasscodeForActions:), (IMP) &SafeModeAlertItem$configure$requirePasscodeForActions$, "v@:cc");
157 class_addMethod($SafeModeAlertItem, @selector(performUnlockAction), (IMP) SafeModeAlertItem$performUnlockAction, "v@:");
158 objc_registerClassPair($SafeModeAlertItem);
159 }
160
161 if (%c(SBAlertItemsController) != nil)
162 [[%c(SBAlertItemsController) sharedInstance] activateAlertItem:[[[$SafeModeAlertItem alloc] init] autorelease]];
163 }
164
165
166 // XXX: on iOS 5.0, we really would prefer avoiding
167
168 %hook SBStatusBar
169 - (void) touchesEnded:(id)touches withEvent:(id)event {
170 MSAlert();
171 %orig(touches, event);
172 } %end
173
174 %hook SBStatusBar
175 - (void) mouseDown:(void *)event {
176 MSAlert();
177 %orig(event);
178 } %end
179
180 %hook UIStatusBar
181 - (void) touchesBegan:(void *)touches withEvent:(void *)event {
182 MSAlert();
183 %orig(touches, event);
184 } %end
185
186
187 // this fairly complex code came from Grant, to solve the "it Safe Mode"-in-bar bug
188
189 %hook SBStatusBarDataManager
190 - (void) _updateTimeString {
191 char *_data(&MSHookIvar<char>(self, "_data"));
192 if (_data == NULL)
193 return;
194
195 Ivar _itemIsEnabled(object_getInstanceVariable(self, "_itemIsEnabled", NULL));
196 if (_itemIsEnabled == NULL)
197 return;
198
199 Ivar _itemIsCloaked(object_getInstanceVariable(self, "_itemIsCloaked", NULL));
200 if (_itemIsCloaked == NULL)
201 return;
202
203 size_t enabledOffset(ivar_getOffset(_itemIsEnabled));
204 size_t cloakedOffset(ivar_getOffset(_itemIsCloaked));
205 if (enabledOffset >= cloakedOffset)
206 return;
207
208 size_t offset(cloakedOffset - enabledOffset);
209 char *timeString(_data + offset);
210 strcpy(timeString, "Exit Safe Mode");
211 } %end
212
213
214 // this /insanely/ complex code came from that parrot guy... omg this is getting bad
215
216 @interface SBStatusBarStateAggregator : NSObject
217 - (void) _stopTimeItemTimer;
218 @end
219
220 %hook SBStatusBarStateAggregator
221
222 - (void) _updateTimeItems {
223 if ([self respondsToSelector:@selector(_stopTimeItemTimer)])
224 [self _stopTimeItemTimer];
225 %orig;
226 }
227
228 - (void) _restartTimeItemTimer {
229 }
230
231 - (void) _resetTimeItemFormatter {
232 %orig;
233 if (NSDateFormatter *df = MSHookIvar<NSDateFormatter *>(self, "_timeItemDateFormatter"))
234 [df setDateFormat:@"'Exit' 'Safe' 'Mode'"];
235 }
236
237 %end
238
239
240 static bool alerted_;
241
242 static void AlertIfNeeded() {
243 if (alerted_)
244 return;
245 alerted_ = true;
246 MSAlert();
247 }
248
249 // iOS 7
250 %hook SBLockScreenManager
251 - (void) _finishUIUnlockFromSource:(int)source withOptions:(id)options {
252 %orig;
253 AlertIfNeeded();
254 } %end
255
256 // iOS 6
257 %hook SBAwayController
258 - (void) _finishUnlockWithSound:(BOOL)sound unlockSource:(int)source isAutoUnlock:(BOOL)is {
259 %orig;
260 AlertIfNeeded();
261 } %end
262
263 // iOS 5
264 %hook SBAwayController
265 - (void) _unlockWithSound:(BOOL)sound isAutoUnlock:(BOOL)is unlockSource:(int)source {
266 %orig;
267 AlertIfNeeded();
268 } %end
269
270 // iOS 4.3 XXX: check lower versions
271 %hook SBAwayController
272 - (void) _unlockWithSound:(BOOL)sound isAutoUnlock:(BOOL)is unlockType:(int)type {
273 %orig;
274 AlertIfNeeded();
275 } %end
276
277 // -[SBIconController showInfoAlertIfNeeded] explains how to drag icons around the iPhone home screen
278 // it used to be shown to users when they unlocked their screen for the first time, and happened every unlock
279 // however, as of iOS 4.3, it got relegated to only appearing once the user installed an app or web clip
280
281 %hook SBIconController
282 - (void) showInfoAlertIfNeeded {
283 AlertIfNeeded();
284 } %end
285
286
287 // the icon state, including crazy configurations like Five Icon Dock, is stored in SpringBoard's defaults
288 // unfortunately, SpringBoard on iOS 2.0 and 2.1 (maybe 2.2 as well) buffer overrun with more than 4 icons
289 // there is a third party package called IconSupport that remedies this, but not everyone is using it yet
290
291 %hook SBButtonBar
292 - (int) maxIconColumns {
293 static int max;
294 if (max == 0) {
295 max = %orig();
296 if (NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults])
297 if (NSDictionary *iconState = [defaults objectForKey:@"iconState"])
298 if (NSDictionary *buttonBar = [iconState objectForKey:@"buttonBar"])
299 if (NSArray *iconMatrix = [buttonBar objectForKey:@"iconMatrix"])
300 if ([iconMatrix count] != 0)
301 if (NSArray *row = [iconMatrix objectAtIndex:0]) {
302 int count([row count]);
303 if (max < count)
304 max = count;
305 }
306 } return max;
307 } %end
308
309
310 %hook SBUIController
311 - (id) init {
312 if ((self = %orig()) != nil) {
313 UIView *&_contentLayer(MSHookIvar<UIView *>(self, "_contentLayer"));
314 UIView *&_contentView(MSHookIvar<UIView *>(self, "_contentView"));
315
316 UIView *layer;
317 if (&_contentLayer != NULL)
318 layer = _contentLayer;
319 else if (&_contentView != NULL)
320 layer = _contentView;
321 else
322 layer = nil;
323
324 if (layer != nil)
325 [layer setBackgroundColor:[UIColor darkGrayColor]];
326 } return self;
327 } %end
328
329 #define Paper_ "/Library/MobileSubstrate/MobileSafety.png"
330
331 %hook SBWallpaperImage
332 + (id) alloc {
333 return nil;
334 } %end
335
336 %hook UIImage
337 + (UIImage *) defaultDesktopImage {
338 return [UIImage imageWithContentsOfFile:@Paper_];
339 } %end
340
341 %hook SBStatusBarTimeView
342 - (void) tile {
343 NSString *&_time(MSHookIvar<NSString *>(self, "_time"));
344 CGRect &_textRect(MSHookIvar<CGRect>(self, "_textRect"));
345 if (_time != nil)
346 [_time release];
347 _time = [@"Exit Safe Mode" retain];
348 id font([self textFont]);
349 CGSize size([_time sizeWithFont:font]);
350 CGRect frame([self frame]);
351 _textRect.size = size;
352 _textRect.origin.x = (frame.size.width - size.width) / 2;
353 _textRect.origin.y = (frame.size.height - size.height) / 2;
354 } %end
355
356
357 // on iOS 6.0, Apple split parts of SpringBoard into a daemon called backboardd, including app launches
358 // in order to allow safe mode to propogate into applications, we need to then tell backboardd here
359 // XXX: (all of this should be replaced, however, with per-process launchd-mediated exception handling)
360
361 %hook BKSApplicationLaunchSettings
362 - (void) setEnvironment:(NSDictionary *)original {
363 if (original == nil)
364 return %orig(nil);
365
366 NSMutableDictionary *modified([original mutableCopy]);
367 [modified setObject:@"1" forKey:@"_MSSafeMode"];
368 return %orig(modified);
369 } %end
370
371
372 // this highly-general hook replaces all previous attempts to protect SpringBoard from spurious code
373 // the main purpose is to protect SpringBoard from non-Substrate "away view plug-ins" and "wee apps"
374
375 const char *dylibs_[] = {
376 "/usr/lib",
377 "/System/Library/Frameworks",
378 "/System/Library/PrivateFrameworks",
379 "/System/Library/CoreServices",
380 "/System/Library/AccessibilityBundles",
381 "/System/Library/HIDPlugins",
382 NULL,
383 };
384
385 MSHook(void *, dlopen, const char *path, int mode) {
386 // we probably don't need this whitelist, but it has the nifty benefit of letting Cycript inject
387 // that said, older versions of iOS (before 3.1) will need a special case due to now shared cache
388
389 for (const char **dylib = dylibs_; *dylib != NULL; ++dylib) {
390 size_t length(strlen(*dylib));
391 if (strncmp(path, *dylib, length) != 0)
392 continue;
393 if (path[length] != '/')
394 continue;
395 goto load;
396 }
397
398 // if the file is not on disk, and isn't already loaded (LC_ID_DYLIB), it is in the shared cache
399 // files loaded from the shared cache are "trusted". ones that don't exist are clearly harmless.
400 // this allows us to load most of the dynamic functionality of SpringBoard without going nuts ;P
401
402 if (access(path, F_OK) == 0)
403 mode |= RTLD_NOLOAD;
404
405 load:
406 return _dlopen(path, mode);
407 }
408
409
410 %ctor {
411 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
412
413 MSHookFunction(&dlopen, MSHake(dlopen));
414
415 // on iOS 6, backboardd is in charge of brightness, and freaks out when SpringBoard restarts :(
416 // the result is that the device is super dark until we attempt to update the brightness here.
417
418 if (kCFCoreFoundationVersionNumber >= 700) {
419 if (void (*GSEventSetBacklightLevel)(float) = reinterpret_cast<void (*)(float)>(dlsym(RTLD_DEFAULT, "GSEventSetBacklightLevel")))
420 if (NSMutableDictionary *defaults = [NSMutableDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/Library/Preferences/com.apple.springboard.plist", NSHomeDirectory()]])
421 if (NSNumber *level = [defaults objectForKey:@"SBBacklightLevel2"])
422 GSEventSetBacklightLevel([level floatValue]);
423 }
424
425 [pool release];
426 }