]> git.saurik.com Git - cydget.git/blob - LockScreen.mm
Port Cydget to UIWebView.
[cydget.git] / LockScreen.mm
1 /* Cydget - open-source AwayView plugin multiplexer
2 * Copyright (C) 2009-2011 Jay Freeman (saurik)
3 */
4
5 /*
6 * Redistribution and use in source and binary
7 * forms, with or without modification, are permitted
8 * provided that the following conditions are met:
9 *
10 * 1. Redistributions of source code must retain the
11 * above copyright notice, this list of conditions
12 * and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the
14 * above copyright notice, this list of conditions
15 * and the following disclaimer in the documentation
16 * and/or other materials provided with the
17 * distribution.
18 * 3. The name of the author may not be used to endorse
19 * or promote products derived from this software
20 * without specific prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
23 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
24 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
25 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
27 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
28 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
29 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
30 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
31 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
32 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
33 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
34 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
35 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 */
37
38 #include <substrate.h>
39 #include <sys/sysctl.h>
40
41 #import <GraphicsServices/GraphicsServices.h>
42 #import <UIKit/UIKit.h>
43 #import <AddressBook/AddressBook.h>
44
45 #import <SpringBoard/SBStatusBarController.h>
46 #import <SpringBoardUI/SBAwayViewPluginController.h>
47 #import <TelephonyUI/TPBottomLockBar.h>
48
49 #import <QuartzCore/CALayer.h>
50 // XXX: fix the minimum requirement
51 extern NSString * const kCAFilterNearest;
52
53 #include <WebKit/DOMCSSPrimitiveValue.h>
54 #include <WebKit/DOMCSSStyleDeclaration.h>
55 #include <WebKit/DOMDocument.h>
56 #include <WebKit/DOMHTMLBodyElement.h>
57 #include <WebKit/DOMNodeList.h>
58 #include <WebKit/DOMRGBColor.h>
59
60 #include <WebKit/WebFrame.h>
61 #include <WebKit/WebPolicyDelegate.h>
62 #include <WebKit/WebPreferences.h>
63 #include <WebKit/WebScriptObject.h>
64
65 #import <WebKit/WebView.h>
66 #import <WebKit/WebView-WebPrivate.h>
67
68 #include <WebCore/Page.h>
69 #include <WebCore/Settings.h>
70
71 #include <WebCore/WebCoreThread.h>
72 #include <WebKit/WebPreferences-WebPrivate.h>
73
74 #include "JSGlobalData.h"
75
76 #include "SourceCode.h"
77
78 #include <apr-1/apr_pools.h>
79 #include <pcre.h>
80
81 #define _transient
82 #define _forever for (;;)
83
84 _disused static unsigned trace_;
85
86 #define _trace() do { \
87 NSLog(@"_trace(%u)@%s:%u[%s](%p)\n", \
88 trace_++, __FILE__, __LINE__, __FUNCTION__, pthread_self() \
89 ); \
90 } while (false)
91
92 #define _assert(test) do \
93 if (!(test)) { \
94 fprintf(stderr, "_assert(%d:%s)@%s:%u[%s]\n", errno, #test, __FILE__, __LINE__, __FUNCTION__); \
95 exit(-1); \
96 } \
97 while (false)
98
99 #define _syscall(expr) \
100 do if ((long) (expr) != -1) \
101 break; \
102 else switch (errno) { \
103 case EINTR: \
104 continue; \
105 default: \
106 _assert(false); \
107 } while (true)
108
109 @protocol CydgetController
110 - (NSDictionary *) currentConfiguration;
111 @end
112
113 static Class $CydgetController(objc_getClass("CydgetController"));
114
115 static Class $UIWebBrowserView;
116 static bool Wildcat_, iOS4;
117
118 @interface NSString (UIKit)
119 - (NSString *) stringByAddingPercentEscapes;
120 @end
121
122 @implementation UIWebDocumentView (WebCycript)
123
124 - (void) _setScrollerOffset:(CGPoint)offset {
125 UIScroller *scroller([self _scroller]);
126
127 CGSize size([scroller contentSize]);
128 CGSize bounds([scroller bounds].size);
129
130 CGPoint max;
131 max.x = size.width - bounds.width;
132 max.y = size.height - bounds.height;
133
134 // wtf Apple?!
135 if (max.x < 0)
136 max.x = 0;
137 if (max.y < 0)
138 max.y = 0;
139
140 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
141 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
142
143 [scroller setOffset:offset];
144 }
145
146 @end
147
148 /* Perl-Compatible RegEx {{{ */
149 class Pcre {
150 private:
151 pcre *code_;
152 pcre_extra *study_;
153 int capture_;
154 int *matches_;
155 const char *data_;
156
157 public:
158 Pcre(const char *regex, int options = 0) :
159 study_(NULL)
160 {
161 const char *error;
162 int offset;
163 code_ = pcre_compile(regex, options, &error, &offset, NULL);
164
165 if (code_ == NULL)
166 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"*** Pcre(,): [%u] %s", offset, error] userInfo:nil];
167
168 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
169 matches_ = new int[(capture_ + 1) * 3];
170 }
171
172 ~Pcre() {
173 pcre_free(code_);
174 delete matches_;
175 }
176
177 NSString *operator [](size_t match) {
178 return [[[NSString alloc] initWithBytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2]) encoding:NSUTF8StringEncoding] autorelease];
179 }
180
181 bool operator ()(NSString *data) {
182 // XXX: length is for characters, not for bytes
183 return operator ()([data UTF8String], [data length]);
184 }
185
186 bool operator ()(const char *data, size_t size) {
187 data_ = data;
188 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
189 }
190 };
191 /* }}} */
192
193 static float CYScrollViewDecelerationRateNormal;
194
195 @interface UIScrollView (Apple)
196 - (void) setDecelerationRate:(float)value;
197 - (void) setScrollingEnabled:(BOOL)enabled;
198 @end
199
200 @interface UIWebView (Apple)
201 - (void) setDataDetectorTypes:(int)types;
202 - (UIScrollView *) _scrollView;
203 - (UIScroller *) _scroller;
204 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame;
205 @end
206
207 @interface WebView (Apple)
208 - (void) _setLayoutInterval:(float)interval;
209 - (void) _setAllowsMessaging:(BOOL)allows;
210 - (void) setShouldUpdateWhileOffscreen:(BOOL)update;
211 @end
212
213 @protocol CydgetWebViewDelegate //<UIWebViewDelegate>
214 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame;
215 @end
216
217 @class UIWebViewWebViewDelegate;
218
219 @interface CydgetWebView : UIWebView {
220 }
221
222 @end
223
224 @implementation CydgetWebView
225
226 - (void) webView:(WebView *)view decidePolicyForNavigationAction:(NSDictionary *)action request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
227 [listener use];
228 }
229
230 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
231 NSObject<CydgetWebViewDelegate> *delegate([self delegate]);
232 if ([delegate respondsToSelector:@selector(webView:didClearWindowObject:forFrame:)])
233 [delegate webView:view didClearWindowObject:window forFrame:frame];
234 if ([UIWebView instancesRespondToSelector:@selector(webView:didClearWindowObject:forFrame:)])
235 [super webView:view didClearWindowObject:window forFrame:frame];
236 }
237
238 @end
239
240 @interface WebCydgetLockScreenView : UIView {
241 CydgetWebView *webview_;
242 UIScrollView *scroller_;
243 NSString *cycript_;
244 }
245
246 @end
247
248 @implementation WebCydgetLockScreenView
249
250 //#include "UICaboodle/UCInternal.h"
251
252 - (void) dealloc {
253 [webview_ setDelegate:nil];
254 [webview_ release];
255 [super dealloc];
256 }
257
258 - (void) loadRequest:(NSURLRequest *)request {
259 [webview_ loadRequest:request];
260 }
261
262 - (void) loadURL:(NSURL *)url cachePolicy:(NSURLRequestCachePolicy)policy {
263 [self loadRequest:[NSURLRequest
264 requestWithURL:url
265 cachePolicy:policy
266 timeoutInterval:30.0
267 ]];
268 }
269
270 - (void) loadURL:(NSURL *)url {
271 [self loadURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy];
272 }
273
274 - (id) init {
275 CGRect frame = {{0, 0}, {320, 480}};
276 frame.size.height -= 20; //[[[$SBStatusBarController sharedStatusBarController] statusBarView] frame].size.height;
277
278 if ((self = [super initWithFrame:frame]) != nil) {
279 CGRect bounds([self bounds]);
280 bounds.size.height -= [TPBottomLockBar defaultHeight];
281
282 webview_ = [[CydgetWebView alloc] initWithFrame:bounds];
283 [webview_ setDelegate:self];
284 [self addSubview:webview_];
285
286 if ([webview_ respondsToSelector:@selector(setDataDetectorTypes:)])
287 [webview_ setDataDetectorTypes:0x80000000];
288 else
289 [webview_ setDetectsPhoneNumbers:NO];
290
291 [webview_ setScalesPageToFit:YES];
292
293 UIWebDocumentView *document([webview_ _documentView]);
294 WebView *webview([document webView]);
295 WebPreferences *preferences([webview preferences]);
296
297 [document setTileSize:CGSizeMake(bounds.size.width, 500)];
298
299 [document setBackgroundColor:[UIColor blackColor]];
300 [document setDrawsBackground:NO];
301
302 [webview setPreferencesIdentifier:@"WebCycript"];
303
304 if ([webview respondsToSelector:@selector(_setLayoutInterval:)])
305 [webview _setLayoutInterval:0];
306 else
307 [preferences _setLayoutInterval:0];
308
309 [preferences setCacheModel:WebCacheModelDocumentViewer];
310 [preferences setJavaScriptCanOpenWindowsAutomatically:YES];
311 [preferences setOfflineWebApplicationCacheEnabled:YES];
312
313 if ([webview respondsToSelector:@selector(setShouldUpdateWhileOffscreen:)])
314 [webview setShouldUpdateWhileOffscreen:NO];
315
316 if ([document respondsToSelector:@selector(setAllowsMessaging:)])
317 [document setAllowsMessaging:YES];
318 if ([webview respondsToSelector:@selector(_setAllowsMessaging:)])
319 [webview _setAllowsMessaging:YES];
320
321 if ([webview_ respondsToSelector:@selector(_scrollView)]) {
322 scroller_ = [webview_ _scrollView];
323
324 [scroller_ setDirectionalLockEnabled:YES];
325 [scroller_ setDecelerationRate:CYScrollViewDecelerationRateNormal];
326 [scroller_ setDelaysContentTouches:NO];
327
328 [scroller_ setCanCancelContentTouches:YES];
329 } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
330 UIScroller *scroller([webview_ _scroller]);
331 scroller_ = (UIScrollView *) scroller;
332
333 [scroller setDirectionalScrolling:YES];
334 [scroller setScrollDecelerationFactor:CYScrollViewDecelerationRateNormal]; /* 0.989324 */
335 [scroller setScrollHysteresis:0]; /* 8 */
336
337 [scroller setThumbDetectionEnabled:NO];
338 }
339
340 [scroller_ setFixedBackgroundPattern:YES];
341 [scroller_ setBackgroundColor:[UIColor blackColor]];
342 [scroller_ setClipsSubviews:NO];
343
344 [scroller_ setBounces:YES];
345 [scroller_ setShowBackgroundShadow:NO]; /* YES */
346
347 [self setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
348 [webview_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
349
350 NSDictionary *configuration([$CydgetController currentConfiguration]);
351
352 cycript_ = [configuration objectForKey:@"CycriptURLs"];
353
354 [scroller_ setScrollingEnabled:[[configuration objectForKey:@"Scrollable"] boolValue]];
355
356 NSString *homepage([configuration objectForKey:@"Homepage"]);
357 [self loadURL:[NSURL URLWithString:homepage]];
358 } return self;
359 }
360
361 - (void) webView:(WebView *)webview didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
362 if (cycript_ != nil)
363 if (NSString *href = [[[[frame dataSource] request] URL] absoluteString])
364 if (Pcre([cycript_ UTF8String], 0 /*XXX:PCRE_UTF8*/)(href))
365 if (void *handle = dlopen("/usr/lib/libcycript.dylib", RTLD_LAZY | RTLD_GLOBAL))
366 if (void (*CYSetupContext)(JSGlobalContextRef) = reinterpret_cast<void (*)(JSGlobalContextRef)>(dlsym(handle, "CydgetSetupContext"))) {
367 WebFrame *frame([webview mainFrame]);
368 JSGlobalContextRef context([frame globalContext]);
369 CYSetupContext(context);
370 }
371 }
372
373 @end
374
375 @interface WebCycriptLockScreenController : SBAwayViewPluginController {
376 }
377
378 @end
379
380 #include <string>
381
382 struct State {
383 unsigned state;
384 };
385
386 // String Helpers {{{
387 static const UChar *(*_ZNK7WebCore6String10charactersEv)(const WebCore::String *);
388 static const UChar *(*_ZN7WebCore6String29charactersWithNullTerminationEv)(const WebCore::String *);
389 static unsigned (*_ZNK7WebCore6String6lengthEv)(const WebCore::String *);
390
391 static bool StringGet(const WebCore::String &string, const UChar *&data, size_t &length) {
392 bool terminated;
393
394 if (_ZNK7WebCore6String10charactersEv != NULL) {
395 data = (*_ZNK7WebCore6String10charactersEv)(&string);
396 terminated = false;
397 } else if (_ZN7WebCore6String29charactersWithNullTerminationEv != NULL) {
398 data = (*_ZN7WebCore6String29charactersWithNullTerminationEv)(&string);
399 terminated = true;
400 } else return false;
401
402 if (_ZNK7WebCore6String6lengthEv != NULL)
403 length = (*_ZNK7WebCore6String6lengthEv)(&string);
404 else if (terminated)
405 for (length = 0; data[length] != 0; ++length);
406 else return false;
407
408 return true;
409 }
410
411 static bool StringEquals(const WebCore::String &string, const char *value) {
412 const UChar *data;
413 size_t size;
414 if (!StringGet(string, data, size))
415 return false;
416
417 size_t length(strlen(value));
418 if (size != length)
419 return false;
420
421 for (size_t index(0); index != length; ++index)
422 if (data[index] != value[index])
423 return false;
424
425 return true;
426 }
427 // }}}
428 // State Machine {{{
429 static bool cycript_;
430
431 MSHook(bool, _ZN7WebCore16MIMETypeRegistry29isSupportedJavaScriptMIMETypeERKNS_6StringE, const WebCore::String &mime) {
432 _trace();
433 if (!StringEquals(mime, "text/cycript")) {
434 cycript_ = false;
435 return __ZN7WebCore16MIMETypeRegistry29isSupportedJavaScriptMIMETypeERKNS_6StringE(mime);
436 }
437 _trace();
438
439 static void *handle(dlopen("/usr/lib/libcycript.dylib", RTLD_LAZY | RTLD_GLOBAL));
440 if (handle == NULL)
441 return false;
442
443 cycript_ = true;
444 return true;
445 }
446 // }}}
447 // Script Compiler {{{
448 static void Log(const WebCore::String &string) {
449 #if 0
450 const UChar *data;
451 size_t length;
452 if (!StringGet(string, data, length))
453 return;
454
455 UChar terminated[length + 1];
456 terminated[length] = 0;
457 memcpy(terminated, data, length * 2);
458 NSLog(@"wtf %p:%zu:%S:", &string, length, terminated);
459 #endif
460 }
461
462 static void Cycriptify(apr_pool_t *pool, const uint16_t *&data, size_t &size) {
463 cycript_ = false;
464
465 if (void *handle = dlopen("/usr/lib/libcycript.dylib", RTLD_LAZY | RTLD_GLOBAL))
466 if (void (*CydgetPoolParse)(apr_pool_t *, const uint16_t **, size_t *) = reinterpret_cast<void (*)(apr_pool_t *, const uint16_t **, size_t *)>(dlsym(handle, "CydgetPoolParse")))
467 CydgetPoolParse(pool, &data, &size);
468 }
469
470 static void (*_ZN7WebCore6String6appendEPKtj)(WebCore::String *, const UChar *, unsigned);
471 static void (*_ZN7WebCore6String8truncateEj)(WebCore::String *, unsigned);
472
473 static void Cycriptify(const WebCore::String &source, int *psize = NULL) {
474 if (!cycript_)
475 return;
476
477 const UChar *data;
478 size_t length;
479
480 if (!StringGet(source, data, length)) {
481 _trace();
482 return;
483 }
484
485 size_t size(length);
486
487 apr_pool_t *pool;
488 apr_pool_create(&pool, NULL);
489
490 Cycriptify(pool, data, size);
491
492 WebCore::String &script(const_cast<WebCore::String &>(source));
493
494 _ZN7WebCore6String8truncateEj(&script, 0);
495 _ZN7WebCore6String6appendEPKtj(&script, data, size);
496
497 if (psize != NULL)
498 *psize = size;
499
500 apr_pool_destroy(pool);
501
502 Log(source);
503 }
504 // }}}
505
506 extern "C" void *_ZN3JSC7UString3Rep14nullBaseStringE __attribute__((__weak_import__));
507 extern "C" void *_ZN3JSC7UString3Rep7destroyEv __attribute__((__weak_import__));
508 extern "C" void *_ZN3JSC7UStringC1EPKti __attribute__((__weak_import__));
509 extern "C" void *_ZN3JSC7UStringC1EPKc __attribute__((__weak_import__));
510 extern "C" void *_ZNK3JSC7UString6substrEii __attribute__((__weak_import__));
511 extern "C" void *_ZN3WTF10fastMallocEm __attribute__((__weak_import__));
512 extern "C" void WTFReportAssertionFailure(const char *, int, const char *, const char *) __attribute__((__weak_import__));
513 extern "C" void *_ZN3WTF8fastFreeEPv __attribute__((__weak_import__));
514
515 bool CYWeakHell() {
516 return
517 &_ZN3JSC7UString3Rep14nullBaseStringE == NULL ||
518 &_ZN3JSC7UString3Rep7destroyEv == NULL ||
519 &_ZN3JSC7UStringC1EPKti == NULL ||
520 &_ZN3JSC7UStringC1EPKc == NULL ||
521 &_ZNK3JSC7UString6substrEii == NULL ||
522 &_ZN3WTF10fastMallocEm == NULL ||
523 &WTFReportAssertionFailure == NULL ||
524 &_ZN3WTF8fastFreeEPv == NULL ||
525 false;
526 }
527
528 static WebCore::String *string;
529
530 // iOS 2.x
531 MSHook(State, _ZN7WebCore13HTMLTokenizer15scriptExecutionERKNS_6StringENS0_5StateES3_i, void *_this, const WebCore::String &string, State state, const WebCore::String &url, int line) {
532 _trace();
533 Cycriptify(string);
534 return __ZN7WebCore13HTMLTokenizer15scriptExecutionERKNS_6StringENS0_5StateES3_i(_this, string, state, url, line);
535 }
536
537 // iOS 3.x
538 MSHook(void, _ZN3JSC6Parser5parseEPNS_12JSGlobalDataEPiPNS_7UStringE, JSC::SourceCode **_this, JSC::JSGlobalData *global, int *line, JSC::UString *message) {
539 if (cycript_) {
540 JSC::SourceCode *source(*_this);
541 const uint16_t *data(source->data());
542 size_t size(source->length());
543
544 apr_pool_t *pool;
545 apr_pool_create(&pool, NULL);
546
547 Cycriptify(pool, data, size);
548 source->~SourceCode();
549 // XXX: I actually don't have the original URL here: pants
550 new (source) JSC::SourceCode(JSC::UStringSourceProvider::create(JSC::UString(data, size), "cycript://"), 1);
551
552 apr_pool_destroy(pool);
553
554 }
555
556 return __ZN3JSC6Parser5parseEPNS_12JSGlobalDataEPiPNS_7UStringE(_this, global, line, message);
557 }
558
559 // iOS 4.x cdata
560 MSHook(void, _ZN7WebCore16ScriptSourceCodeC2ERKNS_6StringERKNS_4KURLEi, void *_this, const WebCore::String &source, const WebCore::KURL &url, int line) {
561 _trace();
562 Cycriptify(source);
563 return __ZN7WebCore16ScriptSourceCodeC2ERKNS_6StringERKNS_4KURLEi(_this, source, url, line);
564 }
565
566 // iOS 4.x @src=
567 MSHook(const WebCore::String &, _ZN7WebCore12CachedScript6scriptEv, void *_this) {
568 _trace();
569 const WebCore::String &script(__ZN7WebCore12CachedScript6scriptEv(_this));
570 string = const_cast<WebCore::String *>(&script);
571 Log(script);
572 return script;
573 }
574
575 // iOS 4.x @src=
576 MSHook(State, _ZN7WebCore13HTMLTokenizer15scriptExecutionERKNS_16ScriptSourceCodeENS0_5StateE, void *_this, void *source, State state) {
577 _trace();
578 if (string != NULL) {
579 if (iOS4)
580 Cycriptify(*string, reinterpret_cast<int *>(source) + 3);
581 else
582 Cycriptify(*string);
583 }
584 string = NULL;
585 return __ZN7WebCore13HTMLTokenizer15scriptExecutionERKNS_16ScriptSourceCodeENS0_5StateE(_this, source, state);
586 }
587
588 /* Cydget:// Protocol {{{ */
589 @interface CydgetURLProtocol : NSURLProtocol {
590 }
591
592 @end
593
594 @implementation CydgetURLProtocol
595
596 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
597 NSURL *url([request URL]);
598 if (url == nil)
599 return NO;
600 NSString *scheme([[url scheme] lowercaseString]);
601 if (scheme == nil || ![scheme isEqualToString:@"cydget"])
602 return NO;
603 return YES;
604 }
605
606 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
607 return request;
608 }
609
610 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
611 id<NSURLProtocolClient> client([self client]);
612 if (icon == nil)
613 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
614 else {
615 NSData *data(UIImagePNGRepresentation(icon));
616
617 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
618 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
619 [client URLProtocol:self didLoadData:data];
620 [client URLProtocolDidFinishLoading:self];
621 }
622 }
623
624 - (void) startLoading {
625 id<NSURLProtocolClient> client([self client]);
626 NSURLRequest *request([self request]);
627
628 NSURL *url([request URL]);
629 NSString *href([url absoluteString]);
630
631 NSString *path([href substringFromIndex:9]);
632 NSRange slash([path rangeOfString:@"/"]);
633
634 NSString *command;
635 if (slash.location == NSNotFound) {
636 command = path;
637 path = nil;
638 } else {
639 command = [path substringToIndex:slash.location];
640 path = [path substringFromIndex:(slash.location + 1)];
641 }
642
643 if ([command isEqualToString:@"_UIImageWithName"]) {
644 if (path == nil)
645 goto fail;
646 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
647 UIImage *icon(_UIImageWithName(path));
648 [self _returnPNGWithImage:icon forRequest:request];
649 } else fail: {
650 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
651 }
652 }
653
654 - (void) stopLoading {
655 }
656
657 @end
658 /* }}} */
659 /* Cydget-CGI:// Protocol {{{ */
660 @interface CydgetCGIURLProtocol : NSURLProtocol {
661 pid_t pid_;
662 CFHTTPMessageRef http_;
663 NSFileHandle *handle_;
664 }
665
666 @end
667
668 @implementation CydgetCGIURLProtocol
669
670 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
671 NSURL *url([request URL]);
672 if (url == nil)
673 return NO;
674 NSString *scheme([[url scheme] lowercaseString]);
675 if (scheme == nil || ![scheme isEqualToString:@"cydget-cgi"])
676 return NO;
677 return YES;
678 }
679
680 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
681 return request;
682 }
683
684 - (id) initWithRequest:(NSURLRequest *)request cachedResponse:(NSCachedURLResponse *)response client:(id<NSURLProtocolClient>)client {
685 if ((self = [super initWithRequest:request cachedResponse:response client:client]) != nil) {
686 pid_ = -1;
687 } return self;
688 }
689
690 - (void) startLoading {
691 id<NSURLProtocolClient> client([self client]);
692 NSURLRequest *request([self request]);
693 NSURL *url([request URL]);
694
695 NSString *path([url path]);
696 if (path == nil) {
697 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
698 return;
699 }
700
701 NSFileManager *manager([NSFileManager defaultManager]);
702 if (![manager fileExistsAtPath:path]) {
703 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
704 return;
705 }
706
707 int fds[2];
708 _assert(pipe(fds) != -1);
709
710 _assert(pid_ == -1);
711 pid_ = fork();
712 if (pid_ == -1) {
713 _assert(close(fds[0]) != -1);
714 _assert(close(fds[1]) != -1);
715 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
716 return;
717 }
718
719 if (pid_ == 0) {
720 const char *script([path UTF8String]);
721
722 setenv("GATEWAY_INTERFACE", "CGI/1.1", true);
723 setenv("SCRIPT_FILENAME", script, true);
724 NSString *query([url query]);
725 if (query != nil)
726 setenv("QUERY_STRING", [query UTF8String], true);
727
728 _assert(dup2(fds[1], 1) != -1);
729 _assert(close(fds[0]) != -1);
730 _assert(close(fds[1]) != -1);
731
732 execl(script, script, NULL);
733 exit(1);
734 _assert(false);
735 }
736
737 _assert(close(fds[1]) != -1);
738
739 _assert(http_ == NULL);
740 http_ = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, FALSE);
741 CFHTTPMessageAppendBytes(http_, (const uint8_t *) "HTTP/1.1 200 OK\r\n", 17);
742
743 _assert(handle_ == nil);
744 handle_ = [[NSFileHandle alloc] initWithFileDescriptor:fds[0] closeOnDealloc:YES];
745
746 [[NSNotificationCenter defaultCenter]
747 addObserver:self
748 selector:@selector(onRead:)
749 name:@"NSFileHandleReadCompletionNotification"
750 object:handle_
751 ];
752
753 [handle_ readInBackgroundAndNotify];
754 }
755
756 - (void) onRead:(NSNotification *)notification {
757 NSFileHandle *handle([notification object]);
758
759 NSData *data([[notification userInfo] objectForKey:NSFileHandleNotificationDataItem]);
760
761 if (size_t length = [data length]) {
762 CFHTTPMessageAppendBytes(http_, reinterpret_cast<const UInt8 *>([data bytes]), length);
763 [handle readInBackgroundAndNotify];
764 } else {
765 id<NSURLProtocolClient> client([self client]);
766
767 CFStringRef mime(CFHTTPMessageCopyHeaderFieldValue(http_, CFSTR("Content-type")));
768 if (mime == NULL)
769 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorBadServerResponse userInfo:nil]];
770 else {
771 NSURLRequest *request([self request]);
772
773 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:(NSString *)mime expectedContentLength:-1 textEncodingName:nil] autorelease]);
774 CFRelease(mime);
775
776 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
777
778 CFDataRef body(CFHTTPMessageCopyBody(http_));
779 [client URLProtocol:self didLoadData:(NSData *)body];
780 CFRelease(body);
781
782 [client URLProtocolDidFinishLoading:self];
783 }
784
785 CFRelease(http_);
786 http_ = NULL;
787 }
788 }
789
790 //[client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorNetworkConnectionLost userInfo:nil]];
791
792 - (void) stopLoading_ {
793 [[NSNotificationCenter defaultCenter] removeObserver:self];
794
795 if (handle_ != nil) {
796 [handle_ release];
797 handle_ = nil;
798 }
799
800 if (pid_ != -1) {
801 kill(pid_, SIGTERM);
802 int status;
803 _syscall(waitpid(pid_, &status, 0));
804 pid_ = -1;
805 }
806 }
807
808 - (void) stopLoading {
809 [self
810 performSelectorOnMainThread:@selector(stopLoading_)
811 withObject:nil
812 waitUntilDone:NO
813 ];
814 }
815
816 @end
817 /* }}} */
818
819 template <typename Type_>
820 static void nlset(Type_ &function, struct nlist *nl, size_t index) {
821 struct nlist &name(nl[index]);
822 uintptr_t value(name.n_value);
823 if ((name.n_desc & N_ARM_THUMB_DEF) != 0)
824 value |= 0x00000001;
825 function = reinterpret_cast<Type_>(value);
826 }
827
828 template <typename Type_>
829 static void dlset(Type_ &function, const char *name) {
830 function = reinterpret_cast<Type_>(dlsym(RTLD_DEFAULT, name));
831 }
832
833 template <typename Type_>
834 static void msset_(Type_ &function, const char *name, MSImageRef handle) {
835 function = reinterpret_cast<Type_>(MSFindSymbol(handle, name));
836 }
837
838 #define msset(function, handle) \
839 msset_(function, "_" #function, handle)
840
841 @implementation WebCycriptLockScreenController
842
843 static void $UIWebViewWebViewDelegate$webView$didClearWindowObject$forFrame$(UIWebViewWebViewDelegate *self, SEL sel, WebView *view, WebScriptObject *window, WebFrame *frame) {
844 UIWebView *uiWebView(MSHookIvar<UIWebView *>(self, "uiWebView"));
845 if ([uiWebView respondsToSelector:@selector(webView:didClearWindowObject:forFrame:)])
846 [uiWebView webView:view didClearWindowObject:window forFrame:frame];
847 }
848
849 + (void) initialize {
850 if (Class $UIWebViewWebViewDelegate = objc_getClass("UIWebViewWebViewDelegate"))
851 class_addMethod($UIWebViewWebViewDelegate, @selector(webView:didClearWindowObject:forFrame:), (IMP) &$UIWebViewWebViewDelegate$webView$didClearWindowObject$forFrame$, "v20@0:4@8@12@16");
852
853 if (float *_UIScrollViewDecelerationRateNormal = reinterpret_cast<float *>(dlsym(RTLD_DEFAULT, "UIScrollViewDecelerationRateNormal")))
854 CYScrollViewDecelerationRateNormal = *_UIScrollViewDecelerationRateNormal;
855 else // XXX: this actually might be fast on some older systems: we should look into this
856 CYScrollViewDecelerationRateNormal = 0.998;
857
858 iOS4 = kCFCoreFoundationVersionNumber >= 550.32;
859
860 $UIWebBrowserView = objc_getClass("UIWebBrowserView");
861 if ($UIWebBrowserView == nil) {
862 Wildcat_ = false;
863 $UIWebBrowserView = objc_getClass("UIWebDocumentView");
864 } else {
865 Wildcat_ = true;
866 }
867
868 int maxproc;
869 size_t size(sizeof(maxproc));
870 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
871 NSLog(@"sysctlbyname(\"kern.maxproc\", ?)");
872 else if (maxproc < 72) {
873 maxproc = 72;
874 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
875 NSLog(@"sysctlbyname(\"kern.maxproc\", #)");
876 }
877
878 apr_initialize();
879
880 [NSURLProtocol registerClass:[CydgetURLProtocol class]];
881 [NSURLProtocol registerClass:[CydgetCGIURLProtocol class]];
882
883 if (!iOS4) {
884 void (*_ZN3JSC6Parser5parseEPNS_12JSGlobalDataEPiPNS_7UStringE)(JSC::SourceCode **, JSC::JSGlobalData *, int *, JSC::UString *);
885 dlset(_ZN3JSC6Parser5parseEPNS_12JSGlobalDataEPiPNS_7UStringE, "_ZN3JSC6Parser5parseEPNS_12JSGlobalDataEPiPNS_7UStringE");
886 if (_ZN3JSC6Parser5parseEPNS_12JSGlobalDataEPiPNS_7UStringE != NULL)
887 MSHookFunction(_ZN3JSC6Parser5parseEPNS_12JSGlobalDataEPiPNS_7UStringE, MSHake(_ZN3JSC6Parser5parseEPNS_12JSGlobalDataEPiPNS_7UStringE));
888 }
889
890 struct nlist nl[9];
891 memset(nl, 0, sizeof(nl));
892
893 nl[0].n_un.n_name = (char *) "__ZN7WebCore16MIMETypeRegistry29isSupportedJavaScriptMIMETypeERKNS_6StringE";
894
895 nl[1].n_un.n_name = (char *) "__ZN7WebCore16ScriptSourceCodeC2ERKNS_6StringERKNS_4KURLEi";
896
897 nl[2].n_un.n_name = (char *) "__ZN7WebCore12CachedScript6scriptEv";
898 nl[3].n_un.n_name = (char *) "__ZNK7WebCore20StringSourceProvider6sourceEv";
899
900 nl[4].n_un.n_name = (char *) "__ZN7WebCore13HTMLTokenizer15scriptExecutionERKNS_6StringENS0_5StateES3_i";
901 nl[5].n_un.n_name = (char *) "__ZN7WebCore13HTMLTokenizer15scriptExecutionERKNS_16ScriptSourceCodeENS0_5StateE";
902
903 nl[6].n_un.n_name = (char *) "__ZN7WebCore6String6appendEPKtj";
904 nl[7].n_un.n_name = (char *) "__ZN7WebCore6String8truncateEj";
905
906 nlist("/System/Library/PrivateFrameworks/WebCore.framework/WebCore", nl);
907
908 bool (*_ZN7WebCore16MIMETypeRegistry29isSupportedJavaScriptMIMETypeERKNS_6StringE)(const WebCore::String &);
909 nlset(_ZN7WebCore16MIMETypeRegistry29isSupportedJavaScriptMIMETypeERKNS_6StringE, nl, 0);
910 if (_ZN7WebCore16MIMETypeRegistry29isSupportedJavaScriptMIMETypeERKNS_6StringE != NULL)
911 MSHookFunction(_ZN7WebCore16MIMETypeRegistry29isSupportedJavaScriptMIMETypeERKNS_6StringE, MSHake(_ZN7WebCore16MIMETypeRegistry29isSupportedJavaScriptMIMETypeERKNS_6StringE));
912
913 void (*_ZN7WebCore16ScriptSourceCodeC2ERKNS_6StringERKNS_4KURLEi)(void *, const WebCore::String &, const WebCore::KURL &, int);
914 nlset(_ZN7WebCore16ScriptSourceCodeC2ERKNS_6StringERKNS_4KURLEi, nl, 1);
915 if (_ZN7WebCore16ScriptSourceCodeC2ERKNS_6StringERKNS_4KURLEi != NULL)
916 MSHookFunction(_ZN7WebCore16ScriptSourceCodeC2ERKNS_6StringERKNS_4KURLEi, MSHake(_ZN7WebCore16ScriptSourceCodeC2ERKNS_6StringERKNS_4KURLEi));
917
918 if (iOS4) {
919 const WebCore::String &(*_ZN7WebCore12CachedScript6scriptEv)(void *);
920 nlset(_ZN7WebCore12CachedScript6scriptEv, nl, 2);
921 if (_ZN7WebCore12CachedScript6scriptEv != NULL)
922 MSHookFunction(_ZN7WebCore12CachedScript6scriptEv, MSHake(_ZN7WebCore12CachedScript6scriptEv));
923 }
924
925 State (*_ZN7WebCore13HTMLTokenizer15scriptExecutionERKNS_6StringENS0_5StateES3_i)(void *, const WebCore::String &, State, const WebCore::String &, int);
926 nlset(_ZN7WebCore13HTMLTokenizer15scriptExecutionERKNS_6StringENS0_5StateES3_i, nl, 4);
927 if (_ZN7WebCore13HTMLTokenizer15scriptExecutionERKNS_6StringENS0_5StateES3_i != NULL)
928 MSHookFunction(_ZN7WebCore13HTMLTokenizer15scriptExecutionERKNS_6StringENS0_5StateES3_i, MSHake(_ZN7WebCore13HTMLTokenizer15scriptExecutionERKNS_6StringENS0_5StateES3_i));
929
930 if (iOS4) {
931 State (*_ZN7WebCore13HTMLTokenizer15scriptExecutionERKNS_16ScriptSourceCodeENS0_5StateE)(void *, void *, State);
932 nlset(_ZN7WebCore13HTMLTokenizer15scriptExecutionERKNS_16ScriptSourceCodeENS0_5StateE, nl, 5);
933 if (_ZN7WebCore13HTMLTokenizer15scriptExecutionERKNS_16ScriptSourceCodeENS0_5StateE != NULL)
934 MSHookFunction(_ZN7WebCore13HTMLTokenizer15scriptExecutionERKNS_16ScriptSourceCodeENS0_5StateE, MSHake(_ZN7WebCore13HTMLTokenizer15scriptExecutionERKNS_16ScriptSourceCodeENS0_5StateE));
935 }
936
937 nlset(_ZN7WebCore6String6appendEPKtj, nl, 6);
938 nlset(_ZN7WebCore6String8truncateEj, nl, 7);
939
940 MSImageRef JavaScriptCore(MSGetImageByName("/System/Library/PrivateFrameworks/JavaScriptCore.framework/JavaScriptCore"));
941 MSImageRef WebCore(MSGetImageByName("/System/Library/PrivateFrameworks/WebCore.framework/WebCore"));
942
943 if (_ZN7WebCore6String6appendEPKtj == NULL)
944 msset(_ZN7WebCore6String6appendEPKtj, JavaScriptCore);
945
946 if (_ZN7WebCore6String8truncateEj == NULL)
947 msset(_ZN7WebCore6String8truncateEj, JavaScriptCore);
948
949 msset(_ZNK7WebCore6String10charactersEv, WebCore);
950 msset(_ZN7WebCore6String29charactersWithNullTerminationEv, JavaScriptCore);
951 msset(_ZNK7WebCore6String6lengthEv, WebCore);
952 }
953
954 + (id) rootViewController {
955 return [[[self alloc] init] autorelease];
956 }
957
958 - (void) loadView {
959 [self setView:[[[WebCydgetLockScreenView alloc] init] autorelease]];
960 }
961
962 @end