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