1 /* Cydget - open-source AwayView plugin multiplexer
2 * Copyright (C) 2009-2011 Jay Freeman (saurik)
6 * Redistribution and use in source and binary
7 * forms, with or without modification, are permitted
8 * provided that the following conditions are met:
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
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.
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.
38 #include <substrate.h>
39 #include <sys/sysctl.h>
41 #import <GraphicsServices/GraphicsServices.h>
42 #import <UIKit/UIKit.h>
43 #import <AddressBook/AddressBook.h>
45 #import <SpringBoard/SBStatusBarController.h>
46 #import <SpringBoardUI/SBAwayViewPluginController.h>
47 #import <TelephonyUI/TPBottomLockBar.h>
49 #import <QuartzCore/CALayer.h>
50 // XXX: fix the minimum requirement
51 extern NSString * const kCAFilterNearest;
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>
60 #include <WebKit/WebFrame.h>
61 #include <WebKit/WebPolicyDelegate.h>
62 #include <WebKit/WebPreferences.h>
63 #include <WebKit/WebScriptObject.h>
65 #import <WebKit/WebView.h>
66 #import <WebKit/WebView-WebPrivate.h>
68 #include <WebCore/Page.h>
69 #include <WebCore/Settings.h>
71 #include <WebCore/WebCoreThread.h>
72 #include <WebKit/WebPreferences-WebPrivate.h>
74 #include "JSGlobalData.h"
76 #include "SourceCode.h"
78 #include <apr-1/apr_pools.h>
82 #define _forever for (;;)
84 _disused static unsigned trace_;
86 #define _trace() do { \
87 NSLog(@"_trace(%u)@%s:%u[%s](%p)\n", \
88 trace_++, __FILE__, __LINE__, __FUNCTION__, pthread_self() \
92 #define _assert(test) do \
94 fprintf(stderr, "_assert(%d:%s)@%s:%u[%s]\n", errno, #test, __FILE__, __LINE__, __FUNCTION__); \
99 #define _syscall(expr) \
100 do if ((long) (expr) != -1) \
102 else switch (errno) { \
109 @protocol CydgetController
110 - (NSDictionary *) currentConfiguration;
113 static Class $CydgetController(objc_getClass("CydgetController"));
115 MSClassHook(UIWebBrowserView)
116 MSClassHook(SBAwayView)
118 static bool Wildcat_, iOS4;
120 @interface NSString (UIKit)
121 - (NSString *) stringByAddingPercentEscapes;
124 @implementation UIWebDocumentView (WebCycript)
126 - (void) _setScrollerOffset:(CGPoint)offset {
127 UIScroller *scroller([self _scroller]);
129 CGSize size([scroller contentSize]);
130 CGSize bounds([scroller bounds].size);
133 max.x = size.width - bounds.width;
134 max.y = size.height - bounds.height;
142 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
143 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
145 [scroller setOffset:offset];
150 /* Perl-Compatible RegEx {{{ */
160 Pcre(const char *regex, int options = 0) :
165 code_ = pcre_compile(regex, options, &error, &offset, NULL);
168 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"*** Pcre(,): [%u] %s", offset, error] userInfo:nil];
170 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
171 matches_ = new int[(capture_ + 1) * 3];
179 NSString *operator [](size_t match) {
180 return [[[NSString alloc] initWithBytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2]) encoding:NSUTF8StringEncoding] autorelease];
183 bool operator ()(NSString *data) {
184 // XXX: length is for characters, not for bytes
185 return operator ()([data UTF8String], [data length]);
188 bool operator ()(const char *data, size_t size) {
190 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
195 static float CYScrollViewDecelerationRateNormal;
197 @interface UIScrollView (Apple)
198 - (void) setDecelerationRate:(float)value;
199 - (void) setScrollingEnabled:(BOOL)enabled;
202 @interface UIWebView (Apple)
203 - (void) setDataDetectorTypes:(int)types;
204 - (UIScrollView *) _scrollView;
205 - (UIScroller *) _scroller;
206 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame;
209 @interface WebView (Apple)
210 - (void) _setLayoutInterval:(float)interval;
211 - (void) _setAllowsMessaging:(BOOL)allows;
212 - (void) setShouldUpdateWhileOffscreen:(BOOL)update;
215 @protocol CydgetWebViewDelegate //<UIWebViewDelegate>
216 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame;
219 @class UIWebViewWebViewDelegate;
221 @interface CydgetWebView : UIWebView {
226 @implementation CydgetWebView
228 - (void) webView:(WebView *)view decidePolicyForNavigationAction:(NSDictionary *)action request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
232 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
233 NSObject<CydgetWebViewDelegate> *delegate([self delegate]);
234 if ([delegate respondsToSelector:@selector(webView:didClearWindowObject:forFrame:)])
235 [delegate webView:view didClearWindowObject:window forFrame:frame];
236 if ([UIWebView instancesRespondToSelector:@selector(webView:didClearWindowObject:forFrame:)])
237 [super webView:view didClearWindowObject:window forFrame:frame];
242 MSInstanceMessageHook0(UIView *, SBAwayView, inputView) {
243 return [[[UIView alloc] init] autorelease];
246 @interface WebCydgetLockScreenView : UIView {
247 CydgetWebView *webview_;
248 UIScrollView *scroller_;
254 @implementation WebCydgetLockScreenView
256 //#include "UICaboodle/UCInternal.h"
259 [webview_ setDelegate:nil];
264 - (void) loadRequest:(NSURLRequest *)request {
265 [webview_ loadRequest:request];
268 - (void) loadURL:(NSURL *)url cachePolicy:(NSURLRequestCachePolicy)policy {
269 [self loadRequest:[NSURLRequest
276 - (void) loadURL:(NSURL *)url {
277 [self loadURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy];
281 CGRect frame = {{0, 0}, {320, 480}};
282 frame.size.height -= 20; //[[[$SBStatusBarController sharedStatusBarController] statusBarView] frame].size.height;
284 if ((self = [super initWithFrame:frame]) != nil) {
285 CGRect bounds([self bounds]);
286 bounds.size.height -= [TPBottomLockBar defaultHeight];
288 webview_ = [[CydgetWebView alloc] initWithFrame:bounds];
289 [webview_ setDelegate:self];
290 [self addSubview:webview_];
292 if ([webview_ respondsToSelector:@selector(setDataDetectorTypes:)])
293 [webview_ setDataDetectorTypes:0x80000000];
295 [webview_ setDetectsPhoneNumbers:NO];
297 [webview_ setScalesPageToFit:YES];
299 UIWebDocumentView *document([webview_ _documentView]);
300 WebView *webview([document webView]);
301 WebPreferences *preferences([webview preferences]);
303 [document setTileSize:CGSizeMake(bounds.size.width, 500)];
305 [document setBackgroundColor:[UIColor blackColor]];
306 [document setDrawsBackground:NO];
308 [webview setPreferencesIdentifier:@"WebCycript"];
310 if ([webview respondsToSelector:@selector(_setLayoutInterval:)])
311 [webview _setLayoutInterval:0];
313 [preferences _setLayoutInterval:0];
315 [preferences setCacheModel:WebCacheModelDocumentViewer];
316 [preferences setJavaScriptCanOpenWindowsAutomatically:YES];
317 [preferences setOfflineWebApplicationCacheEnabled:YES];
319 if ([webview respondsToSelector:@selector(setShouldUpdateWhileOffscreen:)])
320 [webview setShouldUpdateWhileOffscreen:NO];
322 if ([document respondsToSelector:@selector(setAllowsMessaging:)])
323 [document setAllowsMessaging:YES];
324 if ([webview respondsToSelector:@selector(_setAllowsMessaging:)])
325 [webview _setAllowsMessaging:YES];
327 if ([webview_ respondsToSelector:@selector(_scrollView)]) {
328 scroller_ = [webview_ _scrollView];
330 [scroller_ setDirectionalLockEnabled:YES];
331 [scroller_ setDecelerationRate:CYScrollViewDecelerationRateNormal];
332 [scroller_ setDelaysContentTouches:NO];
334 [scroller_ setCanCancelContentTouches:YES];
335 } else if ([webview_ respondsToSelector:@selector(_scroller)]) {
336 UIScroller *scroller([webview_ _scroller]);
337 scroller_ = (UIScrollView *) scroller;
339 [scroller setDirectionalScrolling:YES];
340 [scroller setScrollDecelerationFactor:CYScrollViewDecelerationRateNormal]; /* 0.989324 */
341 [scroller setScrollHysteresis:0]; /* 8 */
343 [scroller setThumbDetectionEnabled:NO];
346 [scroller_ setFixedBackgroundPattern:YES];
347 [scroller_ setBackgroundColor:[UIColor blackColor]];
348 [scroller_ setClipsSubviews:NO];
350 [scroller_ setBounces:YES];
351 [scroller_ setShowBackgroundShadow:NO]; /* YES */
353 [self setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
354 [webview_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
356 NSDictionary *configuration([$CydgetController currentConfiguration]);
358 cycript_ = [configuration objectForKey:@"CycriptURLs"];
360 [scroller_ setScrollingEnabled:[[configuration objectForKey:@"Scrollable"] boolValue]];
362 NSString *homepage([configuration objectForKey:@"Homepage"]);
363 [self loadURL:[NSURL URLWithString:homepage]];
367 - (void) webView:(WebView *)webview didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
369 if (NSString *href = [[[[frame dataSource] request] URL] absoluteString])
370 if (Pcre([cycript_ UTF8String], 0 /*XXX:PCRE_UTF8*/)(href))
371 if (void *handle = dlopen("/usr/lib/libcycript.dylib", RTLD_LAZY | RTLD_GLOBAL))
372 if (void (*CYSetupContext)(JSGlobalContextRef) = reinterpret_cast<void (*)(JSGlobalContextRef)>(dlsym(handle, "CydgetSetupContext"))) {
373 WebFrame *frame([webview mainFrame]);
374 JSGlobalContextRef context([frame globalContext]);
375 CYSetupContext(context);
381 @interface WebCycriptLockScreenController : SBAwayViewPluginController {
392 // String Helpers {{{
393 static const UChar *(*_ZNK7WebCore6String10charactersEv)(const WebCore::String *);
394 static const UChar *(*_ZN7WebCore6String29charactersWithNullTerminationEv)(const WebCore::String *);
395 static unsigned (*_ZNK7WebCore6String6lengthEv)(const WebCore::String *);
397 static bool StringGet(const WebCore::String &string, const UChar *&data, size_t &length) {
400 if (_ZNK7WebCore6String10charactersEv != NULL) {
401 data = (*_ZNK7WebCore6String10charactersEv)(&string);
403 } else if (_ZN7WebCore6String29charactersWithNullTerminationEv != NULL) {
404 data = (*_ZN7WebCore6String29charactersWithNullTerminationEv)(&string);
408 if (_ZNK7WebCore6String6lengthEv != NULL)
409 length = (*_ZNK7WebCore6String6lengthEv)(&string);
411 for (length = 0; data[length] != 0; ++length);
417 static bool StringEquals(const WebCore::String &string, const char *value) {
420 if (!StringGet(string, data, size))
423 size_t length(strlen(value));
427 for (size_t index(0); index != length; ++index)
428 if (data[index] != value[index])
435 static bool cycript_;
437 MSHook(bool, _ZN7WebCore16MIMETypeRegistry29isSupportedJavaScriptMIMETypeERKNS_6StringE, const WebCore::String &mime) {
439 if (!StringEquals(mime, "text/cycript")) {
441 return __ZN7WebCore16MIMETypeRegistry29isSupportedJavaScriptMIMETypeERKNS_6StringE(mime);
445 static void *handle(dlopen("/usr/lib/libcycript.dylib", RTLD_LAZY | RTLD_GLOBAL));
453 // Script Compiler {{{
454 static void Log(const WebCore::String &string) {
458 if (!StringGet(string, data, length))
461 UChar terminated[length + 1];
462 terminated[length] = 0;
463 memcpy(terminated, data, length * 2);
464 NSLog(@"wtf %p:%zu:%S:", &string, length, terminated);
468 static void Cycriptify(apr_pool_t *pool, const uint16_t *&data, size_t &size) {
471 if (void *handle = dlopen("/usr/lib/libcycript.dylib", RTLD_LAZY | RTLD_GLOBAL))
472 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")))
473 CydgetPoolParse(pool, &data, &size);
476 static void (*_ZN7WebCore6String6appendEPKtj)(WebCore::String *, const UChar *, unsigned);
477 static void (*_ZN7WebCore6String8truncateEj)(WebCore::String *, unsigned);
479 static void Cycriptify(const WebCore::String &source, int *psize = NULL) {
486 if (!StringGet(source, data, length)) {
494 apr_pool_create(&pool, NULL);
496 Cycriptify(pool, data, size);
498 WebCore::String &script(const_cast<WebCore::String &>(source));
500 _ZN7WebCore6String8truncateEj(&script, 0);
501 _ZN7WebCore6String6appendEPKtj(&script, data, size);
506 apr_pool_destroy(pool);
512 extern "C" void *_ZN3JSC7UString3Rep14nullBaseStringE __attribute__((__weak_import__));
513 extern "C" void *_ZN3JSC7UString3Rep7destroyEv __attribute__((__weak_import__));
514 extern "C" void *_ZN3JSC7UStringC1EPKti __attribute__((__weak_import__));
515 extern "C" void *_ZN3JSC7UStringC1EPKc __attribute__((__weak_import__));
516 extern "C" void *_ZNK3JSC7UString6substrEii __attribute__((__weak_import__));
517 extern "C" void *_ZN3WTF10fastMallocEm __attribute__((__weak_import__));
518 extern "C" void WTFReportAssertionFailure(const char *, int, const char *, const char *) __attribute__((__weak_import__));
519 extern "C" void *_ZN3WTF8fastFreeEPv __attribute__((__weak_import__));
523 &_ZN3JSC7UString3Rep14nullBaseStringE == NULL ||
524 &_ZN3JSC7UString3Rep7destroyEv == NULL ||
525 &_ZN3JSC7UStringC1EPKti == NULL ||
526 &_ZN3JSC7UStringC1EPKc == NULL ||
527 &_ZNK3JSC7UString6substrEii == NULL ||
528 &_ZN3WTF10fastMallocEm == NULL ||
529 &WTFReportAssertionFailure == NULL ||
530 &_ZN3WTF8fastFreeEPv == NULL ||
534 static WebCore::String *string;
537 MSHook(State, _ZN7WebCore13HTMLTokenizer15scriptExecutionERKNS_6StringENS0_5StateES3_i, void *_this, const WebCore::String &string, State state, const WebCore::String &url, int line) {
540 return __ZN7WebCore13HTMLTokenizer15scriptExecutionERKNS_6StringENS0_5StateES3_i(_this, string, state, url, line);
544 MSHook(void, _ZN3JSC6Parser5parseEPNS_12JSGlobalDataEPiPNS_7UStringE, JSC::SourceCode **_this, JSC::JSGlobalData *global, int *line, JSC::UString *message) {
546 JSC::SourceCode *source(*_this);
547 const uint16_t *data(source->data());
548 size_t size(source->length());
551 apr_pool_create(&pool, NULL);
553 Cycriptify(pool, data, size);
554 source->~SourceCode();
555 // XXX: I actually don't have the original URL here: pants
556 new (source) JSC::SourceCode(JSC::UStringSourceProvider::create(JSC::UString(data, size), "cycript://"), 1);
558 apr_pool_destroy(pool);
562 return __ZN3JSC6Parser5parseEPNS_12JSGlobalDataEPiPNS_7UStringE(_this, global, line, message);
566 MSHook(void, _ZN7WebCore16ScriptSourceCodeC2ERKNS_6StringERKNS_4KURLEi, void *_this, const WebCore::String &source, const WebCore::KURL &url, int line) {
569 return __ZN7WebCore16ScriptSourceCodeC2ERKNS_6StringERKNS_4KURLEi(_this, source, url, line);
573 MSHook(const WebCore::String &, _ZN7WebCore12CachedScript6scriptEv, void *_this) {
575 const WebCore::String &script(__ZN7WebCore12CachedScript6scriptEv(_this));
576 string = const_cast<WebCore::String *>(&script);
582 MSHook(State, _ZN7WebCore13HTMLTokenizer15scriptExecutionERKNS_16ScriptSourceCodeENS0_5StateE, void *_this, void *source, State state) {
584 if (string != NULL) {
586 Cycriptify(*string, reinterpret_cast<int *>(source) + 3);
591 return __ZN7WebCore13HTMLTokenizer15scriptExecutionERKNS_16ScriptSourceCodeENS0_5StateE(_this, source, state);
594 /* Cydget:// Protocol {{{ */
595 @interface CydgetURLProtocol : NSURLProtocol {
600 @implementation CydgetURLProtocol
602 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
603 NSURL *url([request URL]);
606 NSString *scheme([[url scheme] lowercaseString]);
607 if (scheme == nil || ![scheme isEqualToString:@"cydget"])
612 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
616 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
617 id<NSURLProtocolClient> client([self client]);
619 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
621 NSData *data(UIImagePNGRepresentation(icon));
623 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
624 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
625 [client URLProtocol:self didLoadData:data];
626 [client URLProtocolDidFinishLoading:self];
630 - (void) startLoading {
631 id<NSURLProtocolClient> client([self client]);
632 NSURLRequest *request([self request]);
634 NSURL *url([request URL]);
635 NSString *href([url absoluteString]);
637 NSString *path([href substringFromIndex:9]);
638 NSRange slash([path rangeOfString:@"/"]);
641 if (slash.location == NSNotFound) {
645 command = [path substringToIndex:slash.location];
646 path = [path substringFromIndex:(slash.location + 1)];
649 if ([command isEqualToString:@"_UIImageWithName"]) {
652 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
653 UIImage *icon(_UIImageWithName(path));
654 [self _returnPNGWithImage:icon forRequest:request];
656 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
660 - (void) stopLoading {
665 /* Cydget-CGI:// Protocol {{{ */
666 @interface CydgetCGIURLProtocol : NSURLProtocol {
668 CFHTTPMessageRef http_;
669 NSFileHandle *handle_;
674 @implementation CydgetCGIURLProtocol
676 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
677 NSURL *url([request URL]);
680 NSString *scheme([[url scheme] lowercaseString]);
681 if (scheme == nil || ![scheme isEqualToString:@"cydget-cgi"])
686 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
690 - (id) initWithRequest:(NSURLRequest *)request cachedResponse:(NSCachedURLResponse *)response client:(id<NSURLProtocolClient>)client {
691 if ((self = [super initWithRequest:request cachedResponse:response client:client]) != nil) {
696 - (void) startLoading {
697 id<NSURLProtocolClient> client([self client]);
698 NSURLRequest *request([self request]);
699 NSURL *url([request URL]);
701 NSString *path([url path]);
703 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
707 NSFileManager *manager([NSFileManager defaultManager]);
708 if (![manager fileExistsAtPath:path]) {
709 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
714 _assert(pipe(fds) != -1);
719 _assert(close(fds[0]) != -1);
720 _assert(close(fds[1]) != -1);
721 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
726 const char *script([path UTF8String]);
728 setenv("GATEWAY_INTERFACE", "CGI/1.1", true);
729 setenv("SCRIPT_FILENAME", script, true);
730 NSString *query([url query]);
732 setenv("QUERY_STRING", [query UTF8String], true);
734 _assert(dup2(fds[1], 1) != -1);
735 _assert(close(fds[0]) != -1);
736 _assert(close(fds[1]) != -1);
738 execl(script, script, NULL);
743 _assert(close(fds[1]) != -1);
745 _assert(http_ == NULL);
746 http_ = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, FALSE);
747 CFHTTPMessageAppendBytes(http_, (const uint8_t *) "HTTP/1.1 200 OK\r\n", 17);
749 _assert(handle_ == nil);
750 handle_ = [[NSFileHandle alloc] initWithFileDescriptor:fds[0] closeOnDealloc:YES];
752 [[NSNotificationCenter defaultCenter]
754 selector:@selector(onRead:)
755 name:@"NSFileHandleReadCompletionNotification"
759 [handle_ readInBackgroundAndNotify];
762 - (void) onRead:(NSNotification *)notification {
763 NSFileHandle *handle([notification object]);
765 NSData *data([[notification userInfo] objectForKey:NSFileHandleNotificationDataItem]);
767 if (size_t length = [data length]) {
768 CFHTTPMessageAppendBytes(http_, reinterpret_cast<const UInt8 *>([data bytes]), length);
769 [handle readInBackgroundAndNotify];
771 id<NSURLProtocolClient> client([self client]);
773 CFStringRef mime(CFHTTPMessageCopyHeaderFieldValue(http_, CFSTR("Content-type")));
775 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorBadServerResponse userInfo:nil]];
777 NSURLRequest *request([self request]);
779 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:(NSString *)mime expectedContentLength:-1 textEncodingName:nil] autorelease]);
782 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
784 CFDataRef body(CFHTTPMessageCopyBody(http_));
785 [client URLProtocol:self didLoadData:(NSData *)body];
788 [client URLProtocolDidFinishLoading:self];
796 //[client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorNetworkConnectionLost userInfo:nil]];
798 - (void) stopLoading_ {
799 [[NSNotificationCenter defaultCenter] removeObserver:self];
801 if (handle_ != nil) {
809 _syscall(waitpid(pid_, &status, 0));
814 - (void) stopLoading {
816 performSelectorOnMainThread:@selector(stopLoading_)
825 template <typename Type_>
826 static void nlset(Type_ &function, struct nlist *nl, size_t index) {
827 struct nlist &name(nl[index]);
828 uintptr_t value(name.n_value);
829 if ((name.n_desc & N_ARM_THUMB_DEF) != 0)
831 function = reinterpret_cast<Type_>(value);
834 template <typename Type_>
835 static void dlset(Type_ &function, const char *name) {
836 function = reinterpret_cast<Type_>(dlsym(RTLD_DEFAULT, name));
839 template <typename Type_>
840 static void msset_(Type_ &function, const char *name, MSImageRef handle) {
841 function = reinterpret_cast<Type_>(MSFindSymbol(handle, name));
844 #define msset(function, handle) \
845 msset_(function, "_" #function, handle)
847 @implementation WebCycriptLockScreenController
849 static void $UIWebViewWebViewDelegate$webView$didClearWindowObject$forFrame$(UIWebViewWebViewDelegate *self, SEL sel, WebView *view, WebScriptObject *window, WebFrame *frame) {
850 UIWebView *uiWebView(MSHookIvar<UIWebView *>(self, "uiWebView"));
851 if ([uiWebView respondsToSelector:@selector(webView:didClearWindowObject:forFrame:)])
852 [uiWebView webView:view didClearWindowObject:window forFrame:frame];
855 + (void) initialize {
856 if (Class $UIWebViewWebViewDelegate = objc_getClass("UIWebViewWebViewDelegate"))
857 class_addMethod($UIWebViewWebViewDelegate, @selector(webView:didClearWindowObject:forFrame:), (IMP) &$UIWebViewWebViewDelegate$webView$didClearWindowObject$forFrame$, "v20@0:4@8@12@16");
859 if (float *_UIScrollViewDecelerationRateNormal = reinterpret_cast<float *>(dlsym(RTLD_DEFAULT, "UIScrollViewDecelerationRateNormal")))
860 CYScrollViewDecelerationRateNormal = *_UIScrollViewDecelerationRateNormal;
861 else // XXX: this actually might be fast on some older systems: we should look into this
862 CYScrollViewDecelerationRateNormal = 0.998;
864 iOS4 = kCFCoreFoundationVersionNumber >= 550.32;
866 if ($UIWebBrowserView == nil) {
868 $UIWebBrowserView = objc_getClass("UIWebDocumentView");
874 size_t size(sizeof(maxproc));
875 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
876 NSLog(@"sysctlbyname(\"kern.maxproc\", ?)");
877 else if (maxproc < 72) {
879 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
880 NSLog(@"sysctlbyname(\"kern.maxproc\", #)");
885 [NSURLProtocol registerClass:[CydgetURLProtocol class]];
886 [NSURLProtocol registerClass:[CydgetCGIURLProtocol class]];
889 void (*_ZN3JSC6Parser5parseEPNS_12JSGlobalDataEPiPNS_7UStringE)(JSC::SourceCode **, JSC::JSGlobalData *, int *, JSC::UString *);
890 dlset(_ZN3JSC6Parser5parseEPNS_12JSGlobalDataEPiPNS_7UStringE, "_ZN3JSC6Parser5parseEPNS_12JSGlobalDataEPiPNS_7UStringE");
891 if (_ZN3JSC6Parser5parseEPNS_12JSGlobalDataEPiPNS_7UStringE != NULL)
892 MSHookFunction(_ZN3JSC6Parser5parseEPNS_12JSGlobalDataEPiPNS_7UStringE, MSHake(_ZN3JSC6Parser5parseEPNS_12JSGlobalDataEPiPNS_7UStringE));
896 memset(nl, 0, sizeof(nl));
898 nl[0].n_un.n_name = (char *) "__ZN7WebCore16MIMETypeRegistry29isSupportedJavaScriptMIMETypeERKNS_6StringE";
900 nl[1].n_un.n_name = (char *) "__ZN7WebCore16ScriptSourceCodeC2ERKNS_6StringERKNS_4KURLEi";
902 nl[2].n_un.n_name = (char *) "__ZN7WebCore12CachedScript6scriptEv";
903 nl[3].n_un.n_name = (char *) "__ZNK7WebCore20StringSourceProvider6sourceEv";
905 nl[4].n_un.n_name = (char *) "__ZN7WebCore13HTMLTokenizer15scriptExecutionERKNS_6StringENS0_5StateES3_i";
906 nl[5].n_un.n_name = (char *) "__ZN7WebCore13HTMLTokenizer15scriptExecutionERKNS_16ScriptSourceCodeENS0_5StateE";
908 nl[6].n_un.n_name = (char *) "__ZN7WebCore6String6appendEPKtj";
909 nl[7].n_un.n_name = (char *) "__ZN7WebCore6String8truncateEj";
911 nlist("/System/Library/PrivateFrameworks/WebCore.framework/WebCore", nl);
913 bool (*_ZN7WebCore16MIMETypeRegistry29isSupportedJavaScriptMIMETypeERKNS_6StringE)(const WebCore::String &);
914 nlset(_ZN7WebCore16MIMETypeRegistry29isSupportedJavaScriptMIMETypeERKNS_6StringE, nl, 0);
915 if (_ZN7WebCore16MIMETypeRegistry29isSupportedJavaScriptMIMETypeERKNS_6StringE != NULL)
916 MSHookFunction(_ZN7WebCore16MIMETypeRegistry29isSupportedJavaScriptMIMETypeERKNS_6StringE, MSHake(_ZN7WebCore16MIMETypeRegistry29isSupportedJavaScriptMIMETypeERKNS_6StringE));
918 void (*_ZN7WebCore16ScriptSourceCodeC2ERKNS_6StringERKNS_4KURLEi)(void *, const WebCore::String &, const WebCore::KURL &, int);
919 nlset(_ZN7WebCore16ScriptSourceCodeC2ERKNS_6StringERKNS_4KURLEi, nl, 1);
920 if (_ZN7WebCore16ScriptSourceCodeC2ERKNS_6StringERKNS_4KURLEi != NULL)
921 MSHookFunction(_ZN7WebCore16ScriptSourceCodeC2ERKNS_6StringERKNS_4KURLEi, MSHake(_ZN7WebCore16ScriptSourceCodeC2ERKNS_6StringERKNS_4KURLEi));
924 const WebCore::String &(*_ZN7WebCore12CachedScript6scriptEv)(void *);
925 nlset(_ZN7WebCore12CachedScript6scriptEv, nl, 2);
926 if (_ZN7WebCore12CachedScript6scriptEv != NULL)
927 MSHookFunction(_ZN7WebCore12CachedScript6scriptEv, MSHake(_ZN7WebCore12CachedScript6scriptEv));
930 State (*_ZN7WebCore13HTMLTokenizer15scriptExecutionERKNS_6StringENS0_5StateES3_i)(void *, const WebCore::String &, State, const WebCore::String &, int);
931 nlset(_ZN7WebCore13HTMLTokenizer15scriptExecutionERKNS_6StringENS0_5StateES3_i, nl, 4);
932 if (_ZN7WebCore13HTMLTokenizer15scriptExecutionERKNS_6StringENS0_5StateES3_i != NULL)
933 MSHookFunction(_ZN7WebCore13HTMLTokenizer15scriptExecutionERKNS_6StringENS0_5StateES3_i, MSHake(_ZN7WebCore13HTMLTokenizer15scriptExecutionERKNS_6StringENS0_5StateES3_i));
936 State (*_ZN7WebCore13HTMLTokenizer15scriptExecutionERKNS_16ScriptSourceCodeENS0_5StateE)(void *, void *, State);
937 nlset(_ZN7WebCore13HTMLTokenizer15scriptExecutionERKNS_16ScriptSourceCodeENS0_5StateE, nl, 5);
938 if (_ZN7WebCore13HTMLTokenizer15scriptExecutionERKNS_16ScriptSourceCodeENS0_5StateE != NULL)
939 MSHookFunction(_ZN7WebCore13HTMLTokenizer15scriptExecutionERKNS_16ScriptSourceCodeENS0_5StateE, MSHake(_ZN7WebCore13HTMLTokenizer15scriptExecutionERKNS_16ScriptSourceCodeENS0_5StateE));
942 nlset(_ZN7WebCore6String6appendEPKtj, nl, 6);
943 nlset(_ZN7WebCore6String8truncateEj, nl, 7);
945 MSImageRef JavaScriptCore(MSGetImageByName("/System/Library/PrivateFrameworks/JavaScriptCore.framework/JavaScriptCore"));
946 MSImageRef WebCore(MSGetImageByName("/System/Library/PrivateFrameworks/WebCore.framework/WebCore"));
948 if (_ZN7WebCore6String6appendEPKtj == NULL)
949 msset(_ZN7WebCore6String6appendEPKtj, JavaScriptCore);
951 if (_ZN7WebCore6String8truncateEj == NULL)
952 msset(_ZN7WebCore6String8truncateEj, JavaScriptCore);
954 msset(_ZNK7WebCore6String10charactersEv, WebCore);
955 msset(_ZN7WebCore6String29charactersWithNullTerminationEv, JavaScriptCore);
956 msset(_ZNK7WebCore6String6lengthEv, WebCore);
959 + (id) rootViewController {
960 return [[[self alloc] init] autorelease];
964 [self setView:[[[WebCydgetLockScreenView alloc] init] autorelease]];