1 /* Veency - VNC Remote Access Server for iPhoneOS
2 * Copyright (C) 2008-2012 Jay Freeman (saurik)
5 /* GNU Affero General Public License, Version 3 {{{ */
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
23 fprintf(stderr, "_trace()@%s:%u[%s]\n", __FILE__, __LINE__, __FUNCTION__)
24 #define _likely(expr) \
25 __builtin_expect(expr, 1)
26 #define _unlikely(expr) \
27 __builtin_expect(expr, 0)
29 #include <substrate.h>
32 #include <rfb/keysym.h>
34 #include <mach/mach.h>
35 #include <mach/mach_time.h>
38 #include <sys/sysctl.h>
42 #include <CoreFoundation/CFUserNotification.h>
43 #import <CoreGraphics/CGGeometry.h>
44 #import <GraphicsServices/GraphicsServices.h>
45 #import <Foundation/Foundation.h>
46 #import <UIKit/UIKit.h>
48 #include <IOKit/hid/IOHIDEventTypes.h>
49 #include <IOKit/hidsystem/IOHIDUsageTables.h>
52 #include "SpringBoardAccess.h"
55 MSClassHook(UIApplication)
57 @interface UIApplication (Apple)
58 - (void) addStatusBarImageNamed:(NSString *)name;
59 - (void) removeStatusBarImageNamed:(NSString *)name;
62 @interface CAWindowServerDisplay : NSObject
63 - (mach_port_t) clientPortAtPosition:(CGPoint)position;
66 @interface CAWindowServer : NSObject
67 + (CAWindowServer *) serverIfRunning;
68 - (NSArray *) displays;
71 @interface UIModalView : UIView
72 - (id) addButtonWithTitle:(NSString *)title;
73 - (void) setBodyText:(NSString *)text;
74 - (void) setDelegate:(id)delegate;
75 - (void) setTitle:(NSString *)title;
78 @interface SBAlertItem : NSObject
80 - (UIModalView *) alertSheet;
83 @interface SBAlertItemsController : NSObject
84 + (SBAlertItemsController *) sharedInstance;
85 - (void) activateAlertItem:(SBAlertItem *)item;
88 @interface SBStatusBarController : NSObject
89 + (SBStatusBarController *) sharedStatusBarController;
90 - (void) addStatusBarItem:(NSString *)item;
91 - (void) removeStatusBarItem:(NSString *)item;
94 typedef void *CoreSurfaceBufferRef;
96 extern CFStringRef kCoreSurfaceBufferGlobal;
97 extern CFStringRef kCoreSurfaceBufferMemoryRegion;
98 extern CFStringRef kCoreSurfaceBufferPitch;
99 extern CFStringRef kCoreSurfaceBufferWidth;
100 extern CFStringRef kCoreSurfaceBufferHeight;
101 extern CFStringRef kCoreSurfaceBufferPixelFormat;
102 extern CFStringRef kCoreSurfaceBufferAllocSize;
104 extern "C" CoreSurfaceBufferRef CoreSurfaceBufferCreate(CFDictionaryRef dict);
105 extern "C" int CoreSurfaceBufferLock(CoreSurfaceBufferRef surface, unsigned int lockType);
106 extern "C" int CoreSurfaceBufferUnlock(CoreSurfaceBufferRef surface);
107 extern "C" void *CoreSurfaceBufferGetBaseAddress(CoreSurfaceBufferRef surface);
109 extern "C" void CoreSurfaceBufferFlushProcessorCaches(CoreSurfaceBufferRef buffer);
111 typedef void *CoreSurfaceAcceleratorRef;
113 extern "C" int CoreSurfaceAcceleratorCreate(CFAllocatorRef allocator, void *type, CoreSurfaceAcceleratorRef *accel);
114 extern "C" unsigned int CoreSurfaceAcceleratorTransferSurface(CoreSurfaceAcceleratorRef accelerator, CoreSurfaceBufferRef dest, CoreSurfaceBufferRef src, CFDictionaryRef options/*, void *, void *, void **/);
116 typedef void *IOMobileFramebufferRef;
118 extern "C" kern_return_t IOMobileFramebufferSwapSetLayer(
119 IOMobileFramebufferRef fb,
121 CoreSurfaceBufferRef buffer,
127 extern "C" void IOMobileFramebufferGetDisplaySize(IOMobileFramebufferRef connect, CGSize *size);
128 extern "C" void IOMobileFramebufferIsMainDisplay(IOMobileFramebufferRef connect, int *main);
130 typedef CFTypeRef IOHIDEventRef;
131 typedef CFTypeRef IOHIDEventSystemClientRef;
134 IOHIDEventRef IOHIDEventCreateKeyboardEvent(CFAllocatorRef allocator, uint64_t time, uint16_t page, uint16_t usage, Boolean down, IOHIDEventOptionBits flags);
135 IOHIDEventSystemClientRef IOHIDEventSystemClientCreate(CFAllocatorRef allocator);
136 void IOHIDEventSetSenderID(IOHIDEventRef event, uint64_t sender);
137 void IOHIDEventSystemClientDispatchEvent(IOHIDEventSystemClientRef client, IOHIDEventRef event);
140 static size_t width_;
141 static size_t height_;
142 static NSUInteger ratio_ = 0;
144 static const size_t BytesPerPixel = 4;
145 static const size_t BitsPerSample = 8;
147 static CoreSurfaceAcceleratorRef accelerator_;
148 static CoreSurfaceBufferRef buffer_;
149 static CFDictionaryRef options_;
151 static NSMutableSet *handlers_;
152 static rfbScreenInfoPtr screen_;
153 static bool running_;
157 static unsigned clients_;
159 static CFMessagePortRef ashikase_;
162 static rfbPixel *black_;
164 static void VNCBlack() {
165 if (_unlikely(black_ == NULL))
166 black_ = reinterpret_cast<rfbPixel *>(mmap(NULL, sizeof(rfbPixel) * width_ * height_, PROT_READ, MAP_ANON | MAP_PRIVATE | MAP_NOCACHE, VM_FLAGS_PURGABLE, 0));
167 screen_->frameBuffer = reinterpret_cast<char *>(black_);
170 static bool Ashikase(bool always) {
171 if (!always && !cursor_)
174 if (ashikase_ == NULL)
175 ashikase_ = CFMessagePortCreateRemote(kCFAllocatorDefault, CFSTR("jp.ashikase.mousesupport"));
176 if (ashikase_ != NULL)
183 static CFDataRef cfTrue_;
184 static CFDataRef cfFalse_;
192 static MouseEvent event_;
193 static CFDataRef cfEvent_;
196 MouseMessageTypeEvent,
197 MouseMessageTypeSetEnabled
200 static void AshikaseSendEvent(float x, float y, int buttons = 0) {
203 event_.buttons = buttons;
204 event_.absolute = true;
206 CFMessagePortSendRequest(ashikase_, MouseMessageTypeEvent, cfEvent_, 0, 0, NULL, NULL);
209 static void AshikaseSetEnabled(bool enabled, bool always) {
210 if (!Ashikase(always))
213 CFMessagePortSendRequest(ashikase_, MouseMessageTypeSetEnabled, enabled ? cfTrue_ : cfFalse_, 0, 0, NULL, NULL);
216 AshikaseSendEvent(x_, y_);
219 MSClassHook(SBAlertItem)
220 MSClassHook(SBAlertItemsController)
221 MSClassHook(SBStatusBarController)
223 @interface VNCAlertItem : SBAlertItem
226 static Class $VNCAlertItem;
228 static NSString *DialogTitle(@"Remote Access Request");
229 static NSString *DialogFormat(@"Accept connection from\n%s?\n\nVeency VNC Server\nby Jay Freeman (saurik)\nsaurik@saurik.com\nhttp://www.saurik.com/\n\nSet a VNC password in Settings!");
230 static NSString *DialogAccept(@"Accept");
231 static NSString *DialogReject(@"Reject");
233 static volatile rfbNewClientAction action_ = RFB_CLIENT_ON_HOLD;
234 static NSCondition *condition_;
235 static NSLock *lock_;
237 static rfbClientPtr client_;
239 static void VNCSetup();
240 static void VNCEnabled();
242 float (*$GSMainScreenScaleFactor)();
244 static void OnUserNotification(CFUserNotificationRef notification, CFOptionFlags flags) {
247 if ((flags & 0x3) == 1)
248 action_ = RFB_CLIENT_ACCEPT;
250 action_ = RFB_CLIENT_REFUSE;
255 CFRelease(notification);
258 @interface VNCBridge : NSObject {
261 + (void) askForConnection;
262 + (void) removeStatusBarItem;
263 + (void) registerClient;
267 @implementation VNCBridge
269 + (void) askForConnection {
270 if ($VNCAlertItem != nil) {
271 [[$SBAlertItemsController sharedInstance] activateAlertItem:[[[$VNCAlertItem alloc] init] autorelease]];
276 CFUserNotificationRef notification(CFUserNotificationCreate(kCFAllocatorDefault, 0, kCFUserNotificationPlainAlertLevel, &error, (CFDictionaryRef) [NSDictionary dictionaryWithObjectsAndKeys:
277 DialogTitle, kCFUserNotificationAlertHeaderKey,
278 [NSString stringWithFormat:DialogFormat, client_->host], kCFUserNotificationAlertMessageKey,
279 DialogAccept, kCFUserNotificationAlternateButtonTitleKey,
280 DialogReject, kCFUserNotificationDefaultButtonTitleKey,
284 CFRelease(notification);
288 if (notification == NULL) {
290 action_ = RFB_CLIENT_REFUSE;
296 CFRunLoopSourceRef source(CFUserNotificationCreateRunLoopSource(kCFAllocatorDefault, notification, &OnUserNotification, 0));
297 CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode);
300 + (void) removeStatusBarItem {
301 AshikaseSetEnabled(false, false);
304 SBA_removeStatusBarImage(const_cast<char *>("Veency"));
305 else if ($SBStatusBarController != nil)
306 [[$SBStatusBarController sharedStatusBarController] removeStatusBarItem:@"Veency"];
307 else if (UIApplication *app = [$UIApplication sharedApplication])
308 [app removeStatusBarImageNamed:@"Veency"];
311 + (void) registerClient {
312 // XXX: this could find a better home
314 if ($GSMainScreenScaleFactor == NULL)
317 ratio_ = $GSMainScreenScaleFactor();
321 AshikaseSetEnabled(true, false);
324 SBA_addStatusBarImage(const_cast<char *>("Veency"));
325 else if ($SBStatusBarController != nil)
326 [[$SBStatusBarController sharedStatusBarController] addStatusBarItem:@"Veency"];
327 else if (UIApplication *app = [$UIApplication sharedApplication])
328 [app addStatusBarImageNamed:@"Veency"];
331 + (void) performSetup:(NSThread *)thread {
332 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
333 [thread autorelease];
341 MSInstanceMessage2(void, VNCAlertItem, alertSheet,buttonClicked, id, sheet, int, button) {
346 action_ = RFB_CLIENT_ACCEPT;
348 @synchronized (condition_) {
349 [VNCBridge registerClient];
354 action_ = RFB_CLIENT_REFUSE;
363 MSInstanceMessage2(void, VNCAlertItem, configure,requirePasscodeForActions, BOOL, configure, BOOL, require) {
364 UIModalView *sheet([self alertSheet]);
365 [sheet setDelegate:self];
366 [sheet setTitle:DialogTitle];
367 [sheet setBodyText:[NSString stringWithFormat:DialogFormat, client_->host]];
368 [sheet addButtonWithTitle:DialogAccept];
369 [sheet addButtonWithTitle:DialogReject];
372 MSInstanceMessage0(void, VNCAlertItem, performUnlockAction) {
373 [[$SBAlertItemsController sharedInstance] activateAlertItem:self];
376 static mach_port_t (*GSTakePurpleSystemEventPort)(void);
377 static bool PurpleAllocated;
380 static void FixRecord(GSEventRecord *record) {
382 memmove(&record->windowContextId, &record->windowContextId + 1, sizeof(*record) - (reinterpret_cast<uint8_t *>(&record->windowContextId + 1) - reinterpret_cast<uint8_t *>(record)) + record->size);
385 static void VNCSettings() {
386 NSDictionary *settings([NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/Library/Preferences/com.saurik.Veency.plist", NSHomeDirectory()]]);
388 @synchronized (lock_) {
389 for (NSValue *handler in handlers_)
390 rfbUnregisterSecurityHandler(reinterpret_cast<rfbSecurityHandler *>([handler pointerValue]));
391 [handlers_ removeAllObjects];
394 @synchronized (condition_) {
398 [reinterpret_cast<NSString *>(screen_->authPasswdData) release];
399 screen_->authPasswdData = NULL;
402 if (NSString *password = [settings objectForKey:@"Password"])
403 if ([password length] != 0)
404 screen_->authPasswdData = [password retain];
406 NSNumber *cursor = [settings objectForKey:@"ShowCursor"];
407 cursor_ = cursor == nil ? true : [cursor boolValue];
410 AshikaseSetEnabled(cursor_, true);
414 static void VNCNotifySettings(
415 CFNotificationCenterRef center,
424 static rfbBool VNCCheck(rfbClientPtr client, const char *data, int size) {
425 @synchronized (condition_) {
426 if (NSString *password = reinterpret_cast<NSString *>(screen_->authPasswdData)) {
427 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
428 rfbEncryptBytes(client->authChallenge, const_cast<char *>([password UTF8String]));
429 bool good(memcmp(client->authChallenge, data, size) == 0);
439 struct GSEventRecord record;
441 struct GSEventRecordInfo info;
442 struct GSPathInfo path;
446 static void VNCPointerOld(int buttons, int x, int y, CGPoint location, int diff, bool twas, bool tis);
447 static void VNCPointerNew(int buttons, int x, int y, CGPoint location, int diff, bool twas, bool tis);
449 static void VNCPointer(int buttons, int x, int y, rfbClientPtr client) {
453 CGPoint location = {x, y};
455 if (width_ > height_) {
470 int diff = buttons_ ^ buttons;
471 bool twas((buttons_ & 0x1) != 0);
472 bool tis((buttons & 0x1) != 0);
475 rfbDefaultPtrAddEvent(buttons, x, y, client);
477 if (Ashikase(false)) {
478 AshikaseSendEvent(x, y, buttons);
482 if (kCFCoreFoundationVersionNumber >= 800)
483 return VNCPointerNew(buttons, x, y, location, diff, twas, tis);
485 return VNCPointerOld(buttons, x, y, location, diff, twas, tis);
488 static void VNCPointerOld(int buttons, int x, int y, CGPoint location, int diff, bool twas, bool tis) {
489 mach_port_t purple(0);
491 if ((diff & 0x10) != 0) {
492 struct GSEventRecord record;
494 memset(&record, 0, sizeof(record));
496 record.type = (buttons & 0x10) != 0 ?
497 GSEventTypeHeadsetButtonDown :
498 GSEventTypeHeadsetButtonUp;
500 record.timestamp = GSCurrentEventTimestamp();
503 GSSendSystemEvent(&record);
506 if ((diff & 0x04) != 0) {
507 struct GSEventRecord record;
509 memset(&record, 0, sizeof(record));
511 record.type = (buttons & 0x04) != 0 ?
512 GSEventTypeMenuButtonDown :
513 GSEventTypeMenuButtonUp;
515 record.timestamp = GSCurrentEventTimestamp();
518 GSSendSystemEvent(&record);
521 if ((diff & 0x02) != 0) {
522 struct GSEventRecord record;
524 memset(&record, 0, sizeof(record));
526 record.type = (buttons & 0x02) != 0 ?
527 GSEventTypeLockButtonDown :
528 GSEventTypeLockButtonUp;
530 record.timestamp = GSCurrentEventTimestamp();
533 GSSendSystemEvent(&record);
536 if (twas != tis || tis) {
537 struct VeencyEvent event;
539 memset(&event, 0, sizeof(event));
541 event.record.type = GSEventTypeMouse;
542 event.record.locationInWindow.x = x;
543 event.record.locationInWindow.y = y;
544 event.record.timestamp = GSCurrentEventTimestamp();
545 event.record.size = sizeof(event.data);
547 event.data.info.handInfo.type = twas == tis ?
548 GSMouseEventTypeDragged :
550 GSMouseEventTypeDown :
553 event.data.info.handInfo.x34 = 0x1;
554 event.data.info.handInfo.x38 = tis ? 0x1 : 0x0;
557 event.data.info.pathPositions = 1;
559 event.data.info.x52 = 1;
561 event.data.path.x00 = 0x01;
562 event.data.path.x01 = 0x02;
563 event.data.path.x02 = tis ? 0x03 : 0x00;
564 event.data.path.position = event.record.locationInWindow;
568 if (CAWindowServer *server = [CAWindowServer serverIfRunning]) {
569 NSArray *displays([server displays]);
570 if (displays != nil && [displays count] != 0)
571 if (CAWindowServerDisplay *display = [displays objectAtIndex:0])
572 port = [display clientPortAtPosition:location];
577 purple = (*GSTakePurpleSystemEventPort)();
581 FixRecord(&event.record);
582 GSSendEvent(&event.record, port);
585 if (purple != 0 && PurpleAllocated)
586 mach_port_deallocate(mach_task_self(), purple);
589 static void VNCSendHIDEvent(IOHIDEventRef event) {
590 static IOHIDEventSystemClientRef client_(NULL);
592 client_ = IOHIDEventSystemClientCreate(kCFAllocatorDefault);
593 IOHIDEventSetSenderID(event, 0xDEFACEDBEEFFECE5);
595 IOHIDEventSystemClientDispatchEvent(client_, event);
599 static void VNCPointerNew(int buttons, int x, int y, CGPoint location, int diff, bool twas, bool tis) {
600 if ((diff & 0x10) != 0)
601 VNCSendHIDEvent(IOHIDEventCreateKeyboardEvent(kCFAllocatorDefault, mach_absolute_time(), kHIDPage_Telephony, kHIDUsage_Tfon_Flash, (buttons & 0x10) != 0, 0));
602 if ((diff & 0x04) != 0)
603 VNCSendHIDEvent(IOHIDEventCreateKeyboardEvent(kCFAllocatorDefault, mach_absolute_time(), kHIDPage_Consumer, kHIDUsage_Csmr_Menu, (buttons & 0x04) != 0, 0));
604 if ((diff & 0x02) != 0)
605 VNCSendHIDEvent(IOHIDEventCreateKeyboardEvent(kCFAllocatorDefault, mach_absolute_time(), kHIDPage_Consumer, kHIDUsage_Csmr_Power, (buttons & 0x02) != 0, 0));
607 if (twas != tis || tis) {
611 GSEventRef (*$GSEventCreateKeyEvent)(int, CGPoint, CFStringRef, CFStringRef, id, UniChar, short, short);
612 GSEventRef (*$GSCreateSyntheticKeyEvent)(UniChar, BOOL, BOOL);
614 static void VNCKeyboardNew(rfbBool down, rfbKeySym key, rfbClientPtr client) {
615 //NSLog(@"VNC d:%u k:%04x", down, key);
620 case XK_A: case XK_a: usage = kHIDUsage_KeyboardA; break;
621 case XK_B: case XK_b: usage = kHIDUsage_KeyboardB; break;
622 case XK_C: case XK_c: usage = kHIDUsage_KeyboardC; break;
623 case XK_D: case XK_d: usage = kHIDUsage_KeyboardD; break;
624 case XK_E: case XK_e: usage = kHIDUsage_KeyboardE; break;
625 case XK_F: case XK_f: usage = kHIDUsage_KeyboardF; break;
626 case XK_G: case XK_g: usage = kHIDUsage_KeyboardG; break;
627 case XK_H: case XK_h: usage = kHIDUsage_KeyboardH; break;
628 case XK_I: case XK_i: usage = kHIDUsage_KeyboardI; break;
629 case XK_J: case XK_j: usage = kHIDUsage_KeyboardJ; break;
630 case XK_K: case XK_k: usage = kHIDUsage_KeyboardK; break;
631 case XK_L: case XK_l: usage = kHIDUsage_KeyboardL; break;
632 case XK_M: case XK_m: usage = kHIDUsage_KeyboardM; break;
633 case XK_N: case XK_n: usage = kHIDUsage_KeyboardN; break;
634 case XK_O: case XK_o: usage = kHIDUsage_KeyboardO; break;
635 case XK_P: case XK_p: usage = kHIDUsage_KeyboardP; break;
636 case XK_Q: case XK_q: usage = kHIDUsage_KeyboardQ; break;
637 case XK_R: case XK_r: usage = kHIDUsage_KeyboardR; break;
638 case XK_S: case XK_s: usage = kHIDUsage_KeyboardS; break;
639 case XK_T: case XK_t: usage = kHIDUsage_KeyboardT; break;
640 case XK_U: case XK_u: usage = kHIDUsage_KeyboardU; break;
641 case XK_V: case XK_v: usage = kHIDUsage_KeyboardV; break;
642 case XK_W: case XK_w: usage = kHIDUsage_KeyboardW; break;
643 case XK_X: case XK_x: usage = kHIDUsage_KeyboardX; break;
644 case XK_Y: case XK_y: usage = kHIDUsage_KeyboardY; break;
645 case XK_Z: case XK_z: usage = kHIDUsage_KeyboardZ; break;
647 case XK_underscore: case XK_minus: usage = kHIDUsage_KeyboardHyphen; break;
648 case XK_plus: case XK_equal: usage = kHIDUsage_KeyboardEqualSign; break;
649 case XK_braceleft: case XK_bracketleft: usage = kHIDUsage_KeyboardOpenBracket; break;
650 case XK_braceright: case XK_bracketright: usage = kHIDUsage_KeyboardCloseBracket; break;
651 case XK_bar: case XK_backslash: usage = kHIDUsage_KeyboardBackslash; break;
652 case XK_colon: case XK_semicolon: usage = kHIDUsage_KeyboardSemicolon; break;
653 case XK_quotedbl: case XK_apostrophe: usage = kHIDUsage_KeyboardQuote; break;
654 case XK_asciitilde: case XK_grave: usage = kHIDUsage_KeyboardGraveAccentAndTilde; break;
655 case XK_less: case XK_comma: usage = kHIDUsage_KeyboardComma; break;
656 case XK_greater: case XK_period: usage = kHIDUsage_KeyboardPeriod; break;
657 case XK_question: case XK_slash: usage = kHIDUsage_KeyboardSlash; break;
659 case XK_Return: usage = kHIDUsage_KeyboardReturnOrEnter; break;
660 case XK_BackSpace: usage = kHIDUsage_KeyboardDeleteOrBackspace; break;
661 case XK_Tab: usage = kHIDUsage_KeyboardTab; break;
662 case XK_space: usage = kHIDUsage_KeyboardSpacebar; break;
664 case XK_Shift_L: usage = kHIDUsage_KeyboardLeftShift; break;
665 case XK_Shift_R: usage = kHIDUsage_KeyboardRightShift; break;
666 case XK_Control_L: usage = kHIDUsage_KeyboardLeftControl; break;
667 case XK_Control_R: usage = kHIDUsage_KeyboardRightControl; break;
668 case XK_Meta_L: usage = kHIDUsage_KeyboardLeftAlt; break;
669 case XK_Meta_R: usage = kHIDUsage_KeyboardRightAlt; break;
670 case XK_Alt_L: usage = kHIDUsage_KeyboardLeftGUI; break;
671 case XK_Alt_R: usage = kHIDUsage_KeyboardRightGUI; break;
673 case XK_Up: usage = kHIDUsage_KeyboardUpArrow; break;
674 case XK_Down: usage = kHIDUsage_KeyboardDownArrow; break;
675 case XK_Left: usage = kHIDUsage_KeyboardLeftArrow; break;
676 case XK_Right: usage = kHIDUsage_KeyboardRightArrow; break;
678 case XK_Home: case XK_Begin: usage = kHIDUsage_KeyboardHome; break;
679 case XK_End: usage = kHIDUsage_KeyboardEnd; break;
680 case XK_Page_Up: usage = kHIDUsage_KeyboardPageUp; break;
681 case XK_Page_Down: usage = kHIDUsage_KeyboardPageDown; break;
686 VNCSendHIDEvent(IOHIDEventCreateKeyboardEvent(kCFAllocatorDefault, mach_absolute_time(), kHIDPage_KeyboardOrKeypad, usage, down, 0));
689 static void VNCKeyboard(rfbBool down, rfbKeySym key, rfbClientPtr client) {
690 if (kCFCoreFoundationVersionNumber >= 800)
691 return VNCKeyboardNew(down, key, client);
697 case XK_Return: key = '\r'; break;
698 case XK_BackSpace: key = 0x7f; break;
704 CGPoint point(CGPointMake(x_, y_));
706 UniChar unicode(key);
707 CFStringRef string(NULL);
709 GSEventRef event0, event1(NULL);
710 if ($GSEventCreateKeyEvent != NULL) {
711 string = CFStringCreateWithCharacters(kCFAllocatorDefault, &unicode, 1);
712 event0 = (*$GSEventCreateKeyEvent)(10, point, string, string, nil, 0, 0, 1);
713 event1 = (*$GSEventCreateKeyEvent)(11, point, string, string, nil, 0, 0, 1);
714 } else if ($GSCreateSyntheticKeyEvent != NULL) {
715 event0 = (*$GSCreateSyntheticKeyEvent)(unicode, YES, YES);
716 GSEventRecord *record(_GSEventGetGSEventRecord(event0));
717 record->type = GSEventTypeKeyDown;
722 if (CAWindowServer *server = [CAWindowServer serverIfRunning]) {
723 NSArray *displays([server displays]);
724 if (displays != nil && [displays count] != 0)
725 if (CAWindowServerDisplay *display = [displays objectAtIndex:0])
726 port = [display clientPortAtPosition:point];
729 mach_port_t purple(0);
733 purple = (*GSTakePurpleSystemEventPort)();
738 GSSendEvent(_GSEventGetGSEventRecord(event0), port);
740 GSSendEvent(_GSEventGetGSEventRecord(event1), port);
743 if (purple != 0 && PurpleAllocated)
744 mach_port_deallocate(mach_task_self(), purple);
753 static void VNCDisconnect(rfbClientPtr client) {
754 @synchronized (condition_) {
756 [VNCBridge performSelectorOnMainThread:@selector(removeStatusBarItem) withObject:nil waitUntilDone:YES];
760 static rfbNewClientAction VNCClient(rfbClientPtr client) {
761 @synchronized (condition_) {
762 if (screen_->authPasswdData != NULL) {
763 [VNCBridge performSelectorOnMainThread:@selector(registerClient) withObject:nil waitUntilDone:YES];
764 client->clientGoneHook = &VNCDisconnect;
765 return RFB_CLIENT_ACCEPT;
771 [VNCBridge performSelectorOnMainThread:@selector(askForConnection) withObject:nil waitUntilDone:NO];
772 while (action_ == RFB_CLIENT_ON_HOLD)
774 rfbNewClientAction action(action_);
775 action_ = RFB_CLIENT_ON_HOLD;
778 if (action == RFB_CLIENT_ACCEPT)
779 client->clientGoneHook = &VNCDisconnect;
783 extern "C" bool GSSystemHasCapability(NSString *);
785 static CFTypeRef (*$GSSystemCopyCapability)(CFStringRef);
786 static CFTypeRef (*$GSSystemGetCapability)(CFStringRef);
787 static BOOL (*$MGGetBoolAnswer)(CFStringRef);
789 static void VNCSetup() {
792 @synchronized (condition_) {
794 char *arg0(strdup("VNCServer"));
795 char *argv[] = {arg0, NULL};
796 screen_ = rfbGetScreen(&argc, argv, width_, height_, BitsPerSample, 3, BytesPerPixel);
802 screen_->desktopName = strdup([[[NSProcessInfo processInfo] hostName] UTF8String]);
804 screen_->alwaysShared = TRUE;
805 screen_->handleEventsEagerly = TRUE;
806 screen_->deferUpdateTime = 1000 / 25;
808 screen_->serverFormat.redShift = BitsPerSample * 2;
809 screen_->serverFormat.greenShift = BitsPerSample * 1;
810 screen_->serverFormat.blueShift = BitsPerSample * 0;
812 $GSSystemCopyCapability = reinterpret_cast<CFTypeRef (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, "GSSystemCopyCapability"));
813 $GSSystemGetCapability = reinterpret_cast<CFTypeRef (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, "GSSystemGetCapability"));
814 $MGGetBoolAnswer = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, "MGGetBoolAnswer"));
818 if ($GSSystemCopyCapability != NULL) {
819 opengles2 = (*$GSSystemCopyCapability)(CFSTR("opengles-2"));
820 } else if ($GSSystemGetCapability != NULL) {
821 opengles2 = (*$GSSystemGetCapability)(CFSTR("opengles-2"));
822 if (opengles2 != NULL)
824 } else if ($MGGetBoolAnswer != NULL) {
825 opengles2 = $MGGetBoolAnswer(CFSTR("opengles-2")) ? kCFBooleanTrue : kCFBooleanFalse;
830 bool accelerated(opengles2 != NULL && [(NSNumber *)opengles2 boolValue]);
833 CoreSurfaceAcceleratorCreate(NULL, NULL, &accelerator_);
835 if (opengles2 != NULL)
836 CFRelease(opengles2);
838 if (accelerator_ != NULL)
839 buffer_ = CoreSurfaceBufferCreate((CFDictionaryRef) [NSDictionary dictionaryWithObjectsAndKeys:
840 @"PurpleEDRAM", kCoreSurfaceBufferMemoryRegion,
841 [NSNumber numberWithBool:YES], kCoreSurfaceBufferGlobal,
842 [NSNumber numberWithInt:(width_ * BytesPerPixel)], kCoreSurfaceBufferPitch,
843 [NSNumber numberWithInt:width_], kCoreSurfaceBufferWidth,
844 [NSNumber numberWithInt:height_], kCoreSurfaceBufferHeight,
845 [NSNumber numberWithInt:'BGRA'], kCoreSurfaceBufferPixelFormat,
846 [NSNumber numberWithInt:(width_ * height_ * BytesPerPixel)], kCoreSurfaceBufferAllocSize,
851 //screen_->frameBuffer = reinterpret_cast<char *>(mmap(NULL, sizeof(rfbPixel) * width_ * height_, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE | MAP_NOCACHE, VM_FLAGS_PURGABLE, 0));
853 CoreSurfaceBufferLock(buffer_, 3);
854 screen_->frameBuffer = reinterpret_cast<char *>(CoreSurfaceBufferGetBaseAddress(buffer_));
855 CoreSurfaceBufferUnlock(buffer_);
857 screen_->kbdAddEvent = &VNCKeyboard;
858 screen_->ptrAddEvent = &VNCPointer;
860 screen_->newClientHook = &VNCClient;
861 screen_->passwordCheck = &VNCCheck;
863 screen_->cursor = NULL;
866 static void VNCEnabled() {
873 if (NSDictionary *settings = [NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/Library/Preferences/com.saurik.Veency.plist", NSHomeDirectory()]])
874 if (NSNumber *number = [settings objectForKey:@"Enabled"])
875 enabled = [number boolValue];
877 if (enabled != running_)
880 screen_->socketState = RFB_SOCKET_INIT;
881 rfbInitServer(screen_);
882 rfbRunEventLoop(screen_, -1, true);
884 rfbShutdownServer(screen_, true);
891 static void VNCNotifyEnabled(
892 CFNotificationCenterRef center,
901 void (*$IOMobileFramebufferIsMainDisplay)(IOMobileFramebufferRef, int *);
903 static IOMobileFramebufferRef main_;
904 static CoreSurfaceBufferRef layer_;
906 static void OnLayer(IOMobileFramebufferRef fb, CoreSurfaceBufferRef layer) {
907 if (_unlikely(width_ == 0 || height_ == 0)) {
909 IOMobileFramebufferGetDisplaySize(fb, &size);
912 height_ = size.height;
914 if (width_ == 0 || height_ == 0)
917 NSThread *thread([NSThread alloc]);
920 initWithTarget:[VNCBridge class]
921 selector:@selector(performSetup:)
926 } else if (_unlikely(clients_ != 0)) {
928 if (accelerator_ != NULL)
929 memset(screen_->frameBuffer, 0, sizeof(rfbPixel) * width_ * height_);
933 if (accelerator_ != NULL)
934 CoreSurfaceAcceleratorTransferSurface(accelerator_, layer, buffer_, options_);
936 CoreSurfaceBufferLock(layer, 2);
937 rfbPixel *data(reinterpret_cast<rfbPixel *>(CoreSurfaceBufferGetBaseAddress(layer)));
939 CoreSurfaceBufferFlushProcessorCaches(layer);
941 /*rfbPixel corner(data[0]);
945 screen_->frameBuffer = const_cast<char *>(reinterpret_cast<volatile char *>(data));
946 CoreSurfaceBufferUnlock(layer);
950 rfbMarkRectAsModified(screen_, 0, 0, width_, height_);
954 static bool wait_ = false;
956 MSHook(kern_return_t, IOMobileFramebufferSwapSetLayer,
957 IOMobileFramebufferRef fb,
959 CoreSurfaceBufferRef buffer,
966 if (_unlikely(buffer == NULL))
968 else if (_unlikely(fb == NULL))
970 else if ($IOMobileFramebufferIsMainDisplay == NULL)
973 (*$IOMobileFramebufferIsMainDisplay)(fb, &main);
983 return _IOMobileFramebufferSwapSetLayer(fb, layer, buffer, bounds, frame, flags);
986 // XXX: beg rpetrich for the type of this function
987 extern "C" void *IOMobileFramebufferSwapWait(IOMobileFramebufferRef, void *, unsigned);
989 MSHook(void *, IOMobileFramebufferSwapWait, IOMobileFramebufferRef fb, void *arg1, unsigned flags) {
990 void *value(_IOMobileFramebufferSwapWait(fb, arg1, flags));
996 MSHook(void, rfbRegisterSecurityHandler, rfbSecurityHandler *handler) {
997 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
999 @synchronized (lock_) {
1000 [handlers_ addObject:[NSValue valueWithPointer:handler]];
1001 _rfbRegisterSecurityHandler(handler);
1007 template <typename Type_>
1008 static void dlset(Type_ &function, const char *name) {
1009 function = reinterpret_cast<Type_>(dlsym(RTLD_DEFAULT, name));
1013 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
1015 MSHookSymbol(GSTakePurpleSystemEventPort, "_GSGetPurpleSystemEventPort");
1016 if (GSTakePurpleSystemEventPort == NULL) {
1017 MSHookSymbol(GSTakePurpleSystemEventPort, "_GSCopyPurpleSystemEventPort");
1018 PurpleAllocated = true;
1021 if (dlsym(RTLD_DEFAULT, "GSLibraryCopyGenerationInfoValueForKey") != NULL)
1023 else if (dlsym(RTLD_DEFAULT, "GSKeyboardCreate") != NULL)
1025 else if (dlsym(RTLD_DEFAULT, "GSEventGetWindowContextId") != NULL)
1031 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
1033 sysctlbyname("hw.machine", machine, &size, NULL, 0);
1034 iPad1_ = strcmp(machine, "iPad1,1") == 0;
1036 dlset($GSMainScreenScaleFactor, "GSMainScreenScaleFactor");
1037 dlset($GSEventCreateKeyEvent, "GSEventCreateKeyEvent");
1038 dlset($GSCreateSyntheticKeyEvent, "_GSCreateSyntheticKeyEvent");
1039 dlset($IOMobileFramebufferIsMainDisplay, "IOMobileFramebufferIsMainDisplay");
1041 MSHookFunction(&IOMobileFramebufferSwapSetLayer, MSHake(IOMobileFramebufferSwapSetLayer));
1042 MSHookFunction(&rfbRegisterSecurityHandler, MSHake(rfbRegisterSecurityHandler));
1045 MSHookFunction(&IOMobileFramebufferSwapWait, MSHake(IOMobileFramebufferSwapWait));
1047 if ($SBAlertItem != nil) {
1048 $VNCAlertItem = objc_allocateClassPair($SBAlertItem, "VNCAlertItem", 0);
1049 MSAddMessage2(VNCAlertItem, "v@:@i", alertSheet,buttonClicked);
1050 MSAddMessage2(VNCAlertItem, "v@:cc", configure,requirePasscodeForActions);
1051 MSAddMessage0(VNCAlertItem, "v@:", performUnlockAction);
1052 objc_registerClassPair($VNCAlertItem);
1055 CFNotificationCenterAddObserver(
1056 CFNotificationCenterGetDarwinNotifyCenter(),
1057 NULL, &VNCNotifyEnabled, CFSTR("com.saurik.Veency-Enabled"), NULL, 0
1060 CFNotificationCenterAddObserver(
1061 CFNotificationCenterGetDarwinNotifyCenter(),
1062 NULL, &VNCNotifySettings, CFSTR("com.saurik.Veency-Settings"), NULL, 0
1065 condition_ = [[NSCondition alloc] init];
1066 lock_ = [[NSLock alloc] init];
1067 handlers_ = [[NSMutableSet alloc] init];
1072 cfTrue_ = CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&value), sizeof(value));
1075 cfFalse_ = CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&value), sizeof(value));
1077 cfEvent_ = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&event_), sizeof(event_), kCFAllocatorNull);
1079 options_ = (CFDictionaryRef) [[NSDictionary dictionaryWithObjectsAndKeys: