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 typedef CFTypeRef IOHIDEventRef;
56 typedef CFTypeRef IOHIDEventSystemClientRef;
57 typedef CFTypeRef IOHIDEventSystemConnectionRef;
59 MSClassHook(BKAccessibility)
60 MSClassHook(UIApplication)
62 @interface UIApplication (Apple)
63 - (void) addStatusBarImageNamed:(NSString *)name;
64 - (void) removeStatusBarImageNamed:(NSString *)name;
67 @interface CAWindowServerDisplay : NSObject
68 - (mach_port_t) clientPortAtPosition:(CGPoint)position;
69 - (unsigned) contextIdAtPosition:(CGPoint)position;
70 - (mach_port_t) taskPortOfContextId:(unsigned)context;
73 @interface CAWindowServer : NSObject
74 + (CAWindowServer *) serverIfRunning;
75 - (NSArray *) displays;
78 @interface UIModalView : UIView
79 - (id) addButtonWithTitle:(NSString *)title;
80 - (void) setBodyText:(NSString *)text;
81 - (void) setDelegate:(id)delegate;
82 - (void) setTitle:(NSString *)title;
85 @interface SBAlertItem : NSObject
87 - (UIModalView *) alertSheet;
90 @interface SBAlertItemsController : NSObject
91 + (SBAlertItemsController *) sharedInstance;
92 - (void) activateAlertItem:(SBAlertItem *)item;
95 @interface SBStatusBarController : NSObject
96 + (SBStatusBarController *) sharedStatusBarController;
97 - (void) addStatusBarItem:(NSString *)item;
98 - (void) removeStatusBarItem:(NSString *)item;
101 @interface BKHIDClientConnectionManager : NSObject
102 - (IOHIDEventSystemConnectionRef) clientForTaskPort:(mach_port_t)port;
105 @interface BKAccessibility : NSObject
106 + (BKHIDClientConnectionManager *) _eventRoutingClientConnectionManager;
109 typedef void *CoreSurfaceBufferRef;
111 extern CFStringRef kCoreSurfaceBufferGlobal;
112 extern CFStringRef kCoreSurfaceBufferMemoryRegion;
113 extern CFStringRef kCoreSurfaceBufferPitch;
114 extern CFStringRef kCoreSurfaceBufferWidth;
115 extern CFStringRef kCoreSurfaceBufferHeight;
116 extern CFStringRef kCoreSurfaceBufferPixelFormat;
117 extern CFStringRef kCoreSurfaceBufferAllocSize;
119 extern "C" CoreSurfaceBufferRef CoreSurfaceBufferCreate(CFDictionaryRef dict);
120 extern "C" int CoreSurfaceBufferLock(CoreSurfaceBufferRef surface, unsigned int lockType);
121 extern "C" int CoreSurfaceBufferUnlock(CoreSurfaceBufferRef surface);
122 extern "C" void *CoreSurfaceBufferGetBaseAddress(CoreSurfaceBufferRef surface);
124 extern "C" void CoreSurfaceBufferFlushProcessorCaches(CoreSurfaceBufferRef buffer);
126 typedef void *CoreSurfaceAcceleratorRef;
128 extern "C" int CoreSurfaceAcceleratorCreate(CFAllocatorRef allocator, void *type, CoreSurfaceAcceleratorRef *accel);
129 extern "C" unsigned int CoreSurfaceAcceleratorTransferSurface(CoreSurfaceAcceleratorRef accelerator, CoreSurfaceBufferRef dest, CoreSurfaceBufferRef src, CFDictionaryRef options/*, void *, void *, void **/);
131 typedef void *IOMobileFramebufferRef;
133 extern "C" kern_return_t IOMobileFramebufferSwapSetLayer(
134 IOMobileFramebufferRef fb,
136 CoreSurfaceBufferRef buffer,
142 extern "C" void IOMobileFramebufferGetDisplaySize(IOMobileFramebufferRef connect, CGSize *size);
143 extern "C" void IOMobileFramebufferIsMainDisplay(IOMobileFramebufferRef connect, int *main);
146 IOHIDEventRef IOHIDEventCreateKeyboardEvent(CFAllocatorRef allocator, uint64_t time, uint16_t page, uint16_t usage, Boolean down, IOHIDEventOptionBits flags);
148 IOHIDEventRef IOHIDEventCreateDigitizerEvent(CFAllocatorRef allocator, uint64_t timeStamp, IOHIDDigitizerTransducerType type, uint32_t index, uint32_t identity, uint32_t eventMask, uint32_t buttonMask, IOHIDFloat x, IOHIDFloat y, IOHIDFloat z, IOHIDFloat tipPressure, IOHIDFloat barrelPressure, Boolean range, Boolean touch, IOOptionBits options);
149 IOHIDEventRef IOHIDEventCreateDigitizerFingerEvent(CFAllocatorRef allocator, uint64_t timeStamp, uint32_t index, uint32_t identity, uint32_t eventMask, IOHIDFloat x, IOHIDFloat y, IOHIDFloat z, IOHIDFloat tipPressure, IOHIDFloat twist, Boolean range, Boolean touch, IOOptionBits options);
151 IOHIDEventSystemClientRef IOHIDEventSystemClientCreate(CFAllocatorRef allocator);
153 void IOHIDEventAppendEvent(IOHIDEventRef parent, IOHIDEventRef child);
154 void IOHIDEventSetIntegerValue(IOHIDEventRef event, IOHIDEventField field, int value);
155 void IOHIDEventSetSenderID(IOHIDEventRef event, uint64_t sender);
157 void IOHIDEventSystemClientDispatchEvent(IOHIDEventSystemClientRef client, IOHIDEventRef event);
158 void IOHIDEventSystemConnectionDispatchEvent(IOHIDEventSystemConnectionRef connection, IOHIDEventRef event);
161 static size_t width_;
162 static size_t height_;
163 static NSUInteger ratio_ = 0;
165 static const size_t BytesPerPixel = 4;
166 static const size_t BitsPerSample = 8;
168 static CoreSurfaceAcceleratorRef accelerator_;
169 static CoreSurfaceBufferRef buffer_;
170 static CFDictionaryRef options_;
172 static NSMutableSet *handlers_;
173 static rfbScreenInfoPtr screen_;
174 static bool running_;
178 static unsigned clients_;
180 static CFMessagePortRef ashikase_;
183 static rfbPixel *black_;
185 static void VNCBlack() {
186 if (_unlikely(black_ == NULL))
187 black_ = reinterpret_cast<rfbPixel *>(mmap(NULL, sizeof(rfbPixel) * width_ * height_, PROT_READ, MAP_ANON | MAP_PRIVATE | MAP_NOCACHE, VM_FLAGS_PURGABLE, 0));
188 screen_->frameBuffer = reinterpret_cast<char *>(black_);
191 static bool Ashikase(bool always) {
192 if (kCFCoreFoundationVersionNumber >= 800)
195 if (!always && !cursor_)
198 if (ashikase_ == NULL)
199 ashikase_ = CFMessagePortCreateRemote(kCFAllocatorDefault, CFSTR("jp.ashikase.mousesupport"));
200 if (ashikase_ != NULL)
207 static CFDataRef cfTrue_;
208 static CFDataRef cfFalse_;
216 static MouseEvent event_;
217 static CFDataRef cfEvent_;
220 MouseMessageTypeEvent,
221 MouseMessageTypeSetEnabled
224 static void AshikaseSendEvent(float x, float y, int buttons = 0) {
227 event_.buttons = buttons;
228 event_.absolute = true;
230 CFMessagePortSendRequest(ashikase_, MouseMessageTypeEvent, cfEvent_, 0, 0, NULL, NULL);
233 static void AshikaseSetEnabled(bool enabled, bool always) {
234 if (!Ashikase(always))
237 CFMessagePortSendRequest(ashikase_, MouseMessageTypeSetEnabled, enabled ? cfTrue_ : cfFalse_, 0, 0, NULL, NULL);
240 AshikaseSendEvent(x_, y_);
243 MSClassHook(SBAlertItem)
244 MSClassHook(SBAlertItemsController)
245 MSClassHook(SBStatusBarController)
247 @interface VNCAlertItem : SBAlertItem
250 static Class $VNCAlertItem;
252 static NSString *DialogTitle(@"Remote Access Request");
253 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!");
254 static NSString *DialogAccept(@"Accept");
255 static NSString *DialogReject(@"Reject");
257 static volatile rfbNewClientAction action_ = RFB_CLIENT_ON_HOLD;
258 static NSCondition *condition_;
259 static NSLock *lock_;
261 static rfbClientPtr client_;
263 static void VNCSetup();
264 static void VNCEnabled();
266 float (*$GSMainScreenScaleFactor)();
268 static void OnUserNotification(CFUserNotificationRef notification, CFOptionFlags flags) {
271 if ((flags & 0x3) == 1)
272 action_ = RFB_CLIENT_ACCEPT;
274 action_ = RFB_CLIENT_REFUSE;
279 CFRelease(notification);
282 @interface VNCBridge : NSObject {
285 + (void) askForConnection;
286 + (void) removeStatusBarItem;
287 + (void) registerClient;
291 @implementation VNCBridge
293 + (void) askForConnection {
294 if ($VNCAlertItem != nil) {
295 [[$SBAlertItemsController sharedInstance] activateAlertItem:[[[$VNCAlertItem alloc] init] autorelease]];
300 CFUserNotificationRef notification(CFUserNotificationCreate(kCFAllocatorDefault, 0, kCFUserNotificationPlainAlertLevel, &error, (CFDictionaryRef) [NSDictionary dictionaryWithObjectsAndKeys:
301 DialogTitle, kCFUserNotificationAlertHeaderKey,
302 [NSString stringWithFormat:DialogFormat, client_->host], kCFUserNotificationAlertMessageKey,
303 DialogAccept, kCFUserNotificationAlternateButtonTitleKey,
304 DialogReject, kCFUserNotificationDefaultButtonTitleKey,
308 CFRelease(notification);
312 if (notification == NULL) {
314 action_ = RFB_CLIENT_REFUSE;
320 CFRunLoopSourceRef source(CFUserNotificationCreateRunLoopSource(kCFAllocatorDefault, notification, &OnUserNotification, 0));
321 CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode);
324 + (void) removeStatusBarItem {
325 AshikaseSetEnabled(false, false);
328 SBA_removeStatusBarImage(const_cast<char *>("Veency"));
329 else if ($SBStatusBarController != nil)
330 [[$SBStatusBarController sharedStatusBarController] removeStatusBarItem:@"Veency"];
331 else if (UIApplication *app = [$UIApplication sharedApplication])
332 [app removeStatusBarImageNamed:@"Veency"];
335 + (void) registerClient {
336 // XXX: this could find a better home
338 if ($GSMainScreenScaleFactor == NULL)
341 ratio_ = $GSMainScreenScaleFactor();
345 AshikaseSetEnabled(true, false);
348 SBA_addStatusBarImage(const_cast<char *>("Veency"));
349 else if ($SBStatusBarController != nil)
350 [[$SBStatusBarController sharedStatusBarController] addStatusBarItem:@"Veency"];
351 else if (UIApplication *app = [$UIApplication sharedApplication])
352 [app addStatusBarImageNamed:@"Veency"];
355 + (void) performSetup:(NSThread *)thread {
356 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
357 [thread autorelease];
365 MSInstanceMessage2(void, VNCAlertItem, alertSheet,buttonClicked, id, sheet, int, button) {
370 action_ = RFB_CLIENT_ACCEPT;
372 @synchronized (condition_) {
373 [VNCBridge registerClient];
378 action_ = RFB_CLIENT_REFUSE;
387 MSInstanceMessage2(void, VNCAlertItem, configure,requirePasscodeForActions, BOOL, configure, BOOL, require) {
388 UIModalView *sheet([self alertSheet]);
389 [sheet setDelegate:self];
390 [sheet setTitle:DialogTitle];
391 [sheet setBodyText:[NSString stringWithFormat:DialogFormat, client_->host]];
392 [sheet addButtonWithTitle:DialogAccept];
393 [sheet addButtonWithTitle:DialogReject];
396 MSInstanceMessage0(void, VNCAlertItem, performUnlockAction) {
397 [[$SBAlertItemsController sharedInstance] activateAlertItem:self];
400 static mach_port_t (*GSTakePurpleSystemEventPort)(void);
401 static bool PurpleAllocated;
404 static void FixRecord(GSEventRecord *record) {
406 memmove(&record->windowContextId, &record->windowContextId + 1, sizeof(*record) - (reinterpret_cast<uint8_t *>(&record->windowContextId + 1) - reinterpret_cast<uint8_t *>(record)) + record->size);
409 static void VNCSettings() {
410 NSDictionary *settings([NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/Library/Preferences/com.saurik.Veency.plist", NSHomeDirectory()]]);
412 @synchronized (lock_) {
413 for (NSValue *handler in handlers_)
414 rfbUnregisterSecurityHandler(reinterpret_cast<rfbSecurityHandler *>([handler pointerValue]));
415 [handlers_ removeAllObjects];
418 @synchronized (condition_) {
422 [reinterpret_cast<NSString *>(screen_->authPasswdData) release];
423 screen_->authPasswdData = NULL;
426 if (NSString *password = [settings objectForKey:@"Password"])
427 if ([password length] != 0)
428 screen_->authPasswdData = [password retain];
430 NSNumber *cursor = [settings objectForKey:@"ShowCursor"];
431 cursor_ = cursor == nil ? true : [cursor boolValue];
434 AshikaseSetEnabled(cursor_, true);
438 static void VNCNotifySettings(
439 CFNotificationCenterRef center,
448 static rfbBool VNCCheck(rfbClientPtr client, const char *data, int size) {
449 @synchronized (condition_) {
450 if (NSString *password = reinterpret_cast<NSString *>(screen_->authPasswdData)) {
451 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
452 rfbEncryptBytes(client->authChallenge, const_cast<char *>([password UTF8String]));
453 bool good(memcmp(client->authChallenge, data, size) == 0);
463 struct GSEventRecord record;
465 struct GSEventRecordInfo info;
466 struct GSPathInfo path;
470 static void VNCPointerOld(int buttons, int x, int y, CGPoint location, int diff, bool twas, bool tis);
471 static void VNCPointerNew(int buttons, int x, int y, CGPoint location, int diff, bool twas, bool tis);
473 static void VNCPointer(int buttons, int x, int y, rfbClientPtr client) {
477 CGPoint location = {x, y};
479 if (width_ > height_) {
494 int diff = buttons_ ^ buttons;
495 bool twas((buttons_ & 0x1) != 0);
496 bool tis((buttons & 0x1) != 0);
499 rfbDefaultPtrAddEvent(buttons, x, y, client);
501 if (Ashikase(false)) {
502 AshikaseSendEvent(x, y, buttons);
506 if (kCFCoreFoundationVersionNumber >= 800)
507 return VNCPointerNew(buttons, x, y, location, diff, twas, tis);
509 return VNCPointerOld(buttons, x, y, location, diff, twas, tis);
512 static void VNCPointerOld(int buttons, int x, int y, CGPoint location, int diff, bool twas, bool tis) {
513 mach_port_t purple(0);
515 if ((diff & 0x10) != 0) {
516 struct GSEventRecord record;
518 memset(&record, 0, sizeof(record));
520 record.type = (buttons & 0x10) != 0 ?
521 GSEventTypeHeadsetButtonDown :
522 GSEventTypeHeadsetButtonUp;
524 record.timestamp = GSCurrentEventTimestamp();
527 GSSendSystemEvent(&record);
530 if ((diff & 0x04) != 0) {
531 struct GSEventRecord record;
533 memset(&record, 0, sizeof(record));
535 record.type = (buttons & 0x04) != 0 ?
536 GSEventTypeMenuButtonDown :
537 GSEventTypeMenuButtonUp;
539 record.timestamp = GSCurrentEventTimestamp();
542 GSSendSystemEvent(&record);
545 if ((diff & 0x02) != 0) {
546 struct GSEventRecord record;
548 memset(&record, 0, sizeof(record));
550 record.type = (buttons & 0x02) != 0 ?
551 GSEventTypeLockButtonDown :
552 GSEventTypeLockButtonUp;
554 record.timestamp = GSCurrentEventTimestamp();
557 GSSendSystemEvent(&record);
560 if (twas != tis || tis) {
561 struct VeencyEvent event;
563 memset(&event, 0, sizeof(event));
565 event.record.type = GSEventTypeMouse;
566 event.record.locationInWindow.x = x;
567 event.record.locationInWindow.y = y;
568 event.record.timestamp = GSCurrentEventTimestamp();
569 event.record.size = sizeof(event.data);
571 event.data.info.handInfo.type = twas == tis ?
572 GSMouseEventTypeDragged :
574 GSMouseEventTypeDown :
577 event.data.info.handInfo.x34 = 0x1;
578 event.data.info.handInfo.x38 = tis ? 0x1 : 0x0;
581 event.data.info.pathPositions = 1;
583 event.data.info.x52 = 1;
585 event.data.path.x00 = 0x01;
586 event.data.path.x01 = 0x02;
587 event.data.path.x02 = tis ? 0x03 : 0x00;
588 event.data.path.position = event.record.locationInWindow;
592 if (CAWindowServer *server = [CAWindowServer serverIfRunning]) {
593 NSArray *displays([server displays]);
594 if (displays != nil && [displays count] != 0)
595 if (CAWindowServerDisplay *display = [displays objectAtIndex:0])
596 port = [display clientPortAtPosition:location];
601 purple = (*GSTakePurpleSystemEventPort)();
605 FixRecord(&event.record);
606 GSSendEvent(&event.record, port);
609 if (purple != 0 && PurpleAllocated)
610 mach_port_deallocate(mach_task_self(), purple);
613 static void VNCSetSender(IOHIDEventRef event) {
614 IOHIDEventSetSenderID(event, 0xDEFACEDBEEFFECE5);
617 static void VNCSendHIDEvent(IOHIDEventRef event) {
618 static IOHIDEventSystemClientRef client_(NULL);
620 client_ = IOHIDEventSystemClientCreate(kCFAllocatorDefault);
623 IOHIDEventSystemClientDispatchEvent(client_, event);
627 static void VNCPointerNew(int buttons, int x, int y, CGPoint location, int diff, bool twas, bool tis) {
628 if ((diff & 0x10) != 0)
629 VNCSendHIDEvent(IOHIDEventCreateKeyboardEvent(kCFAllocatorDefault, mach_absolute_time(), kHIDPage_Telephony, kHIDUsage_Tfon_Flash, (buttons & 0x10) != 0, 0));
630 if ((diff & 0x04) != 0)
631 VNCSendHIDEvent(IOHIDEventCreateKeyboardEvent(kCFAllocatorDefault, mach_absolute_time(), kHIDPage_Consumer, kHIDUsage_Csmr_Menu, (buttons & 0x04) != 0, 0));
632 if ((diff & 0x02) != 0)
633 VNCSendHIDEvent(IOHIDEventCreateKeyboardEvent(kCFAllocatorDefault, mach_absolute_time(), kHIDPage_Consumer, kHIDUsage_Csmr_Power, (buttons & 0x02) != 0, 0));
638 if (twas == 0 && tis == 1) {
639 handm = kIOHIDDigitizerEventRange | kIOHIDDigitizerEventTouch | kIOHIDDigitizerEventIdentity;
640 fingerm = kIOHIDDigitizerEventRange | kIOHIDDigitizerEventTouch;
641 } else if (twas == 1 && tis == 1) {
642 handm = kIOHIDDigitizerEventPosition;
643 fingerm = kIOHIDDigitizerEventPosition;
644 } else if (twas == 1 && tis == 0) {
645 handm = kIOHIDDigitizerEventRange | kIOHIDDigitizerEventTouch | kIOHIDDigitizerEventIdentity | kIOHIDDigitizerEventPosition;
646 fingerm = kIOHIDDigitizerEventRange | kIOHIDDigitizerEventTouch;
649 CAWindowServer *server([CAWindowServer serverIfRunning]);
653 CAWindowServerDisplay *display([[server displays] objectAtIndex:0]);
657 unsigned context([display contextIdAtPosition:CGPointMake(x, y)]);
658 mach_port_t port([display taskPortOfContextId:context]);
659 if (port == MACH_PORT_NULL)
662 IOHIDEventSystemConnectionRef connection([[$BKAccessibility _eventRoutingClientConnectionManager] clientForTaskPort:port]);
663 if (connection == NULL)
666 // XXX: I guess this isn't ambiguous, and it works
670 IOHIDEventRef hand(IOHIDEventCreateDigitizerEvent(kCFAllocatorDefault, mach_absolute_time(), kIOHIDDigitizerTransducerTypeHand, 1<<22, 1, handm, 0, xf, yf, 0, 0, 0, 0, 0, 0));
671 IOHIDEventSetIntegerValue(hand, kIOHIDEventFieldIsBuiltIn, true);
672 IOHIDEventSetIntegerValue(hand, kIOHIDEventFieldDigitizerIsDisplayIntegrated, true);
674 IOHIDEventRef finger(IOHIDEventCreateDigitizerFingerEvent(kCFAllocatorDefault, mach_absolute_time(), 3, 2, fingerm, xf, yf, 0, 0, 0, tis, tis, 0));
675 IOHIDEventAppendEvent(hand, finger);
679 IOHIDEventSystemConnectionDispatchEvent(connection, hand);
683 GSEventRef (*$GSEventCreateKeyEvent)(int, CGPoint, CFStringRef, CFStringRef, id, UniChar, short, short);
684 GSEventRef (*$GSCreateSyntheticKeyEvent)(UniChar, BOOL, BOOL);
686 static void VNCKeyboardNew(rfbBool down, rfbKeySym key, rfbClientPtr client) {
687 //NSLog(@"VNC d:%u k:%04x", down, key);
692 case XK_exclam: case XK_1: usage = kHIDUsage_Keyboard1; break;
693 case XK_at: case XK_2: usage = kHIDUsage_Keyboard2; break;
694 case XK_numbersign: case XK_3: usage = kHIDUsage_Keyboard3; break;
695 case XK_dollar: case XK_4: usage = kHIDUsage_Keyboard4; break;
696 case XK_percent: case XK_5: usage = kHIDUsage_Keyboard5; break;
697 case XK_asciicircum: case XK_6: usage = kHIDUsage_Keyboard6; break;
698 case XK_ampersand: case XK_7: usage = kHIDUsage_Keyboard7; break;
699 case XK_asterisk: case XK_8: usage = kHIDUsage_Keyboard8; break;
700 case XK_parenleft: case XK_9: usage = kHIDUsage_Keyboard9; break;
701 case XK_parenright: case XK_0: usage = kHIDUsage_Keyboard0; break;
703 case XK_A: case XK_a: usage = kHIDUsage_KeyboardA; break;
704 case XK_B: case XK_b: usage = kHIDUsage_KeyboardB; break;
705 case XK_C: case XK_c: usage = kHIDUsage_KeyboardC; break;
706 case XK_D: case XK_d: usage = kHIDUsage_KeyboardD; break;
707 case XK_E: case XK_e: usage = kHIDUsage_KeyboardE; break;
708 case XK_F: case XK_f: usage = kHIDUsage_KeyboardF; break;
709 case XK_G: case XK_g: usage = kHIDUsage_KeyboardG; break;
710 case XK_H: case XK_h: usage = kHIDUsage_KeyboardH; break;
711 case XK_I: case XK_i: usage = kHIDUsage_KeyboardI; break;
712 case XK_J: case XK_j: usage = kHIDUsage_KeyboardJ; break;
713 case XK_K: case XK_k: usage = kHIDUsage_KeyboardK; break;
714 case XK_L: case XK_l: usage = kHIDUsage_KeyboardL; break;
715 case XK_M: case XK_m: usage = kHIDUsage_KeyboardM; break;
716 case XK_N: case XK_n: usage = kHIDUsage_KeyboardN; break;
717 case XK_O: case XK_o: usage = kHIDUsage_KeyboardO; break;
718 case XK_P: case XK_p: usage = kHIDUsage_KeyboardP; break;
719 case XK_Q: case XK_q: usage = kHIDUsage_KeyboardQ; break;
720 case XK_R: case XK_r: usage = kHIDUsage_KeyboardR; break;
721 case XK_S: case XK_s: usage = kHIDUsage_KeyboardS; break;
722 case XK_T: case XK_t: usage = kHIDUsage_KeyboardT; break;
723 case XK_U: case XK_u: usage = kHIDUsage_KeyboardU; break;
724 case XK_V: case XK_v: usage = kHIDUsage_KeyboardV; break;
725 case XK_W: case XK_w: usage = kHIDUsage_KeyboardW; break;
726 case XK_X: case XK_x: usage = kHIDUsage_KeyboardX; break;
727 case XK_Y: case XK_y: usage = kHIDUsage_KeyboardY; break;
728 case XK_Z: case XK_z: usage = kHIDUsage_KeyboardZ; break;
730 case XK_underscore: case XK_minus: usage = kHIDUsage_KeyboardHyphen; break;
731 case XK_plus: case XK_equal: usage = kHIDUsage_KeyboardEqualSign; break;
732 case XK_braceleft: case XK_bracketleft: usage = kHIDUsage_KeyboardOpenBracket; break;
733 case XK_braceright: case XK_bracketright: usage = kHIDUsage_KeyboardCloseBracket; break;
734 case XK_bar: case XK_backslash: usage = kHIDUsage_KeyboardBackslash; break;
735 case XK_colon: case XK_semicolon: usage = kHIDUsage_KeyboardSemicolon; break;
736 case XK_quotedbl: case XK_apostrophe: usage = kHIDUsage_KeyboardQuote; break;
737 case XK_asciitilde: case XK_grave: usage = kHIDUsage_KeyboardGraveAccentAndTilde; break;
738 case XK_less: case XK_comma: usage = kHIDUsage_KeyboardComma; break;
739 case XK_greater: case XK_period: usage = kHIDUsage_KeyboardPeriod; break;
740 case XK_question: case XK_slash: usage = kHIDUsage_KeyboardSlash; break;
742 case XK_Return: usage = kHIDUsage_KeyboardReturnOrEnter; break;
743 case XK_BackSpace: usage = kHIDUsage_KeyboardDeleteOrBackspace; break;
744 case XK_Tab: usage = kHIDUsage_KeyboardTab; break;
745 case XK_space: usage = kHIDUsage_KeyboardSpacebar; break;
747 case XK_Shift_L: usage = kHIDUsage_KeyboardLeftShift; break;
748 case XK_Shift_R: usage = kHIDUsage_KeyboardRightShift; break;
749 case XK_Control_L: usage = kHIDUsage_KeyboardLeftControl; break;
750 case XK_Control_R: usage = kHIDUsage_KeyboardRightControl; break;
751 case XK_Meta_L: usage = kHIDUsage_KeyboardLeftAlt; break;
752 case XK_Meta_R: usage = kHIDUsage_KeyboardRightAlt; break;
753 case XK_Alt_L: usage = kHIDUsage_KeyboardLeftGUI; break;
754 case XK_Alt_R: usage = kHIDUsage_KeyboardRightGUI; break;
756 case XK_Up: usage = kHIDUsage_KeyboardUpArrow; break;
757 case XK_Down: usage = kHIDUsage_KeyboardDownArrow; break;
758 case XK_Left: usage = kHIDUsage_KeyboardLeftArrow; break;
759 case XK_Right: usage = kHIDUsage_KeyboardRightArrow; break;
761 case XK_Home: case XK_Begin: usage = kHIDUsage_KeyboardHome; break;
762 case XK_End: usage = kHIDUsage_KeyboardEnd; break;
763 case XK_Page_Up: usage = kHIDUsage_KeyboardPageUp; break;
764 case XK_Page_Down: usage = kHIDUsage_KeyboardPageDown; break;
769 VNCSendHIDEvent(IOHIDEventCreateKeyboardEvent(kCFAllocatorDefault, mach_absolute_time(), kHIDPage_KeyboardOrKeypad, usage, down, 0));
772 static void VNCKeyboard(rfbBool down, rfbKeySym key, rfbClientPtr client) {
773 if (kCFCoreFoundationVersionNumber >= 800)
774 return VNCKeyboardNew(down, key, client);
780 case XK_Return: key = '\r'; break;
781 case XK_BackSpace: key = 0x7f; break;
787 CGPoint point(CGPointMake(x_, y_));
789 UniChar unicode(key);
790 CFStringRef string(NULL);
792 GSEventRef event0, event1(NULL);
793 if ($GSEventCreateKeyEvent != NULL) {
794 string = CFStringCreateWithCharacters(kCFAllocatorDefault, &unicode, 1);
795 event0 = (*$GSEventCreateKeyEvent)(10, point, string, string, nil, 0, 0, 1);
796 event1 = (*$GSEventCreateKeyEvent)(11, point, string, string, nil, 0, 0, 1);
797 } else if ($GSCreateSyntheticKeyEvent != NULL) {
798 event0 = (*$GSCreateSyntheticKeyEvent)(unicode, YES, YES);
799 GSEventRecord *record(_GSEventGetGSEventRecord(event0));
800 record->type = GSEventTypeKeyDown;
805 if (CAWindowServer *server = [CAWindowServer serverIfRunning]) {
806 NSArray *displays([server displays]);
807 if (displays != nil && [displays count] != 0)
808 if (CAWindowServerDisplay *display = [displays objectAtIndex:0])
809 port = [display clientPortAtPosition:point];
812 mach_port_t purple(0);
816 purple = (*GSTakePurpleSystemEventPort)();
821 GSSendEvent(_GSEventGetGSEventRecord(event0), port);
823 GSSendEvent(_GSEventGetGSEventRecord(event1), port);
826 if (purple != 0 && PurpleAllocated)
827 mach_port_deallocate(mach_task_self(), purple);
836 static void VNCDisconnect(rfbClientPtr client) {
837 @synchronized (condition_) {
839 [VNCBridge performSelectorOnMainThread:@selector(removeStatusBarItem) withObject:nil waitUntilDone:YES];
843 static rfbNewClientAction VNCClient(rfbClientPtr client) {
844 @synchronized (condition_) {
845 if (screen_->authPasswdData != NULL) {
846 [VNCBridge performSelectorOnMainThread:@selector(registerClient) withObject:nil waitUntilDone:YES];
847 client->clientGoneHook = &VNCDisconnect;
848 return RFB_CLIENT_ACCEPT;
854 [VNCBridge performSelectorOnMainThread:@selector(askForConnection) withObject:nil waitUntilDone:NO];
855 while (action_ == RFB_CLIENT_ON_HOLD)
857 rfbNewClientAction action(action_);
858 action_ = RFB_CLIENT_ON_HOLD;
861 if (action == RFB_CLIENT_ACCEPT)
862 client->clientGoneHook = &VNCDisconnect;
866 extern "C" bool GSSystemHasCapability(NSString *);
868 static CFTypeRef (*$GSSystemCopyCapability)(CFStringRef);
869 static CFTypeRef (*$GSSystemGetCapability)(CFStringRef);
870 static BOOL (*$MGGetBoolAnswer)(CFStringRef);
872 static void VNCSetup() {
875 @synchronized (condition_) {
877 char *arg0(strdup("VNCServer"));
878 char *argv[] = {arg0, NULL};
879 screen_ = rfbGetScreen(&argc, argv, width_, height_, BitsPerSample, 3, BytesPerPixel);
885 screen_->desktopName = strdup([[[NSProcessInfo processInfo] hostName] UTF8String]);
887 screen_->alwaysShared = TRUE;
888 screen_->handleEventsEagerly = TRUE;
889 screen_->deferUpdateTime = 1000 / 25;
891 screen_->serverFormat.redShift = BitsPerSample * 2;
892 screen_->serverFormat.greenShift = BitsPerSample * 1;
893 screen_->serverFormat.blueShift = BitsPerSample * 0;
895 $GSSystemCopyCapability = reinterpret_cast<CFTypeRef (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, "GSSystemCopyCapability"));
896 $GSSystemGetCapability = reinterpret_cast<CFTypeRef (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, "GSSystemGetCapability"));
897 $MGGetBoolAnswer = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, "MGGetBoolAnswer"));
901 if ($GSSystemCopyCapability != NULL) {
902 opengles2 = (*$GSSystemCopyCapability)(CFSTR("opengles-2"));
903 } else if ($GSSystemGetCapability != NULL) {
904 opengles2 = (*$GSSystemGetCapability)(CFSTR("opengles-2"));
905 if (opengles2 != NULL)
907 } else if ($MGGetBoolAnswer != NULL) {
908 opengles2 = $MGGetBoolAnswer(CFSTR("opengles-2")) ? kCFBooleanTrue : kCFBooleanFalse;
913 bool accelerated(opengles2 != NULL && [(NSNumber *)opengles2 boolValue]);
916 CoreSurfaceAcceleratorCreate(NULL, NULL, &accelerator_);
918 if (opengles2 != NULL)
919 CFRelease(opengles2);
921 if (accelerator_ != NULL)
922 buffer_ = CoreSurfaceBufferCreate((CFDictionaryRef) [NSDictionary dictionaryWithObjectsAndKeys:
923 @"PurpleEDRAM", kCoreSurfaceBufferMemoryRegion,
924 [NSNumber numberWithBool:YES], kCoreSurfaceBufferGlobal,
925 [NSNumber numberWithInt:(width_ * BytesPerPixel)], kCoreSurfaceBufferPitch,
926 [NSNumber numberWithInt:width_], kCoreSurfaceBufferWidth,
927 [NSNumber numberWithInt:height_], kCoreSurfaceBufferHeight,
928 [NSNumber numberWithInt:'BGRA'], kCoreSurfaceBufferPixelFormat,
929 [NSNumber numberWithInt:(width_ * height_ * BytesPerPixel)], kCoreSurfaceBufferAllocSize,
934 //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));
936 CoreSurfaceBufferLock(buffer_, 3);
937 screen_->frameBuffer = reinterpret_cast<char *>(CoreSurfaceBufferGetBaseAddress(buffer_));
938 CoreSurfaceBufferUnlock(buffer_);
940 screen_->kbdAddEvent = &VNCKeyboard;
941 screen_->ptrAddEvent = &VNCPointer;
943 screen_->newClientHook = &VNCClient;
944 screen_->passwordCheck = &VNCCheck;
946 screen_->cursor = NULL;
949 static void VNCEnabled() {
956 if (NSDictionary *settings = [NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/Library/Preferences/com.saurik.Veency.plist", NSHomeDirectory()]])
957 if (NSNumber *number = [settings objectForKey:@"Enabled"])
958 enabled = [number boolValue];
960 if (enabled != running_)
963 screen_->socketState = RFB_SOCKET_INIT;
964 rfbInitServer(screen_);
965 rfbRunEventLoop(screen_, -1, true);
967 rfbShutdownServer(screen_, true);
974 static void VNCNotifyEnabled(
975 CFNotificationCenterRef center,
984 void (*$IOMobileFramebufferIsMainDisplay)(IOMobileFramebufferRef, int *);
986 static IOMobileFramebufferRef main_;
987 static CoreSurfaceBufferRef layer_;
989 static void OnLayer(IOMobileFramebufferRef fb, CoreSurfaceBufferRef layer) {
990 if (_unlikely(width_ == 0 || height_ == 0)) {
992 IOMobileFramebufferGetDisplaySize(fb, &size);
995 height_ = size.height;
997 if (width_ == 0 || height_ == 0)
1000 NSThread *thread([NSThread alloc]);
1003 initWithTarget:[VNCBridge class]
1004 selector:@selector(performSetup:)
1009 } else if (_unlikely(clients_ != 0)) {
1010 if (layer == NULL) {
1011 if (accelerator_ != NULL)
1012 memset(screen_->frameBuffer, 0, sizeof(rfbPixel) * width_ * height_);
1016 if (accelerator_ != NULL)
1017 CoreSurfaceAcceleratorTransferSurface(accelerator_, layer, buffer_, options_);
1019 CoreSurfaceBufferLock(layer, 2);
1020 rfbPixel *data(reinterpret_cast<rfbPixel *>(CoreSurfaceBufferGetBaseAddress(layer)));
1022 CoreSurfaceBufferFlushProcessorCaches(layer);
1024 /*rfbPixel corner(data[0]);
1028 screen_->frameBuffer = const_cast<char *>(reinterpret_cast<volatile char *>(data));
1029 CoreSurfaceBufferUnlock(layer);
1033 rfbMarkRectAsModified(screen_, 0, 0, width_, height_);
1037 static bool wait_ = false;
1039 MSHook(kern_return_t, IOMobileFramebufferSwapSetLayer,
1040 IOMobileFramebufferRef fb,
1042 CoreSurfaceBufferRef buffer,
1049 if (_unlikely(buffer == NULL))
1051 else if (_unlikely(fb == NULL))
1053 else if ($IOMobileFramebufferIsMainDisplay == NULL)
1056 (*$IOMobileFramebufferIsMainDisplay)(fb, &main);
1058 if (_likely(main)) {
1063 OnLayer(fb, buffer);
1066 return _IOMobileFramebufferSwapSetLayer(fb, layer, buffer, bounds, frame, flags);
1069 // XXX: beg rpetrich for the type of this function
1070 extern "C" void *IOMobileFramebufferSwapWait(IOMobileFramebufferRef, void *, unsigned);
1072 MSHook(void *, IOMobileFramebufferSwapWait, IOMobileFramebufferRef fb, void *arg1, unsigned flags) {
1073 void *value(_IOMobileFramebufferSwapWait(fb, arg1, flags));
1075 OnLayer(fb, layer_);
1079 MSHook(void, rfbRegisterSecurityHandler, rfbSecurityHandler *handler) {
1080 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
1082 @synchronized (lock_) {
1083 [handlers_ addObject:[NSValue valueWithPointer:handler]];
1084 _rfbRegisterSecurityHandler(handler);
1090 template <typename Type_>
1091 static void dlset(Type_ &function, const char *name) {
1092 function = reinterpret_cast<Type_>(dlsym(RTLD_DEFAULT, name));
1096 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
1098 MSHookSymbol(GSTakePurpleSystemEventPort, "_GSGetPurpleSystemEventPort");
1099 if (GSTakePurpleSystemEventPort == NULL) {
1100 MSHookSymbol(GSTakePurpleSystemEventPort, "_GSCopyPurpleSystemEventPort");
1101 PurpleAllocated = true;
1104 if (dlsym(RTLD_DEFAULT, "GSLibraryCopyGenerationInfoValueForKey") != NULL)
1106 else if (dlsym(RTLD_DEFAULT, "GSKeyboardCreate") != NULL)
1108 else if (dlsym(RTLD_DEFAULT, "GSEventGetWindowContextId") != NULL)
1114 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
1116 sysctlbyname("hw.machine", machine, &size, NULL, 0);
1117 iPad1_ = strcmp(machine, "iPad1,1") == 0;
1119 dlset($GSMainScreenScaleFactor, "GSMainScreenScaleFactor");
1120 dlset($GSEventCreateKeyEvent, "GSEventCreateKeyEvent");
1121 dlset($GSCreateSyntheticKeyEvent, "_GSCreateSyntheticKeyEvent");
1122 dlset($IOMobileFramebufferIsMainDisplay, "IOMobileFramebufferIsMainDisplay");
1124 MSHookFunction(&IOMobileFramebufferSwapSetLayer, MSHake(IOMobileFramebufferSwapSetLayer));
1125 MSHookFunction(&rfbRegisterSecurityHandler, MSHake(rfbRegisterSecurityHandler));
1128 MSHookFunction(&IOMobileFramebufferSwapWait, MSHake(IOMobileFramebufferSwapWait));
1130 if ($SBAlertItem != nil) {
1131 $VNCAlertItem = objc_allocateClassPair($SBAlertItem, "VNCAlertItem", 0);
1132 MSAddMessage2(VNCAlertItem, "v@:@i", alertSheet,buttonClicked);
1133 MSAddMessage2(VNCAlertItem, "v@:cc", configure,requirePasscodeForActions);
1134 MSAddMessage0(VNCAlertItem, "v@:", performUnlockAction);
1135 objc_registerClassPair($VNCAlertItem);
1138 CFNotificationCenterAddObserver(
1139 CFNotificationCenterGetDarwinNotifyCenter(),
1140 NULL, &VNCNotifyEnabled, CFSTR("com.saurik.Veency-Enabled"), NULL, 0
1143 CFNotificationCenterAddObserver(
1144 CFNotificationCenterGetDarwinNotifyCenter(),
1145 NULL, &VNCNotifySettings, CFSTR("com.saurik.Veency-Settings"), NULL, 0
1148 condition_ = [[NSCondition alloc] init];
1149 lock_ = [[NSLock alloc] init];
1150 handlers_ = [[NSMutableSet alloc] init];
1155 cfTrue_ = CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&value), sizeof(value));
1158 cfFalse_ = CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&value), sizeof(value));
1160 cfEvent_ = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&event_), sizeof(event_), kCFAllocatorNull);
1162 options_ = (CFDictionaryRef) [[NSDictionary dictionaryWithObjectsAndKeys: