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;
71 @interface CAWindowServer : NSObject
72 + (CAWindowServer *) serverIfRunning;
73 - (NSArray *) displays;
76 @interface UIModalView : UIView
77 - (id) addButtonWithTitle:(NSString *)title;
78 - (void) setBodyText:(NSString *)text;
79 - (void) setDelegate:(id)delegate;
80 - (void) setTitle:(NSString *)title;
83 @interface SBAlertItem : NSObject
85 - (UIModalView *) alertSheet;
88 @interface SBAlertItemsController : NSObject
89 + (SBAlertItemsController *) sharedInstance;
90 - (void) activateAlertItem:(SBAlertItem *)item;
93 @interface SBStatusBarController : NSObject
94 + (SBStatusBarController *) sharedStatusBarController;
95 - (void) addStatusBarItem:(NSString *)item;
96 - (void) removeStatusBarItem:(NSString *)item;
99 #if defined(_ARM_ARCH_6) && !defined(_ARM_ARCH_7)
101 #define kIOSurfaceAllocSize kCoreSurfaceBufferAllocSize
102 #define kIOSurfaceBytesPerRow kCoreSurfaceBufferPitch
103 #define kIOSurfaceHeight kCoreSurfaceBufferHeight
104 #define kIOSurfaceIsGlobal kCoreSurfaceBufferGlobal
105 #define kIOSurfaceMemoryRegion kCoreSurfaceBufferMemoryRegion
106 #define kIOSurfacePixelFormat kCoreSurfaceBufferPixelFormat
107 #define kIOSurfaceWidth kCoreSurfaceBufferWidth
109 #define IOSurfaceRef CoreSurfaceBufferRef
110 #define IOSurfaceAcceleratorRef CoreSurfaceAcceleratorRef
112 #define IOSurfaceCreate CoreSurfaceBufferCreate
113 #define IOSurfaceFlushProcessorCaches CoreSurfaceBufferFlushProcessorCaches
114 #define IOSurfaceGetBaseAddress CoreSurfaceBufferGetBaseAddress
115 #define IOSurfaceLock CoreSurfaceBufferLock
116 #define IOSurfaceUnlock CoreSurfaceBufferUnlock
118 #define IOSurfaceAcceleratorCreate CoreSurfaceAcceleratorCreate
119 #define IOSurfaceAcceleratorTransferSurface CoreSurfaceAcceleratorTransferSurface
123 typedef void *IOSurfaceRef;
125 extern CFStringRef kIOSurfaceIsGlobal;
126 extern CFStringRef kIOSurfaceMemoryRegion;
127 extern CFStringRef kIOSurfaceBytesPerRow;
128 extern CFStringRef kIOSurfaceWidth;
129 extern CFStringRef kIOSurfaceHeight;
130 extern CFStringRef kIOSurfacePixelFormat;
131 extern CFStringRef kIOSurfaceAllocSize;
133 extern "C" IOSurfaceRef IOSurfaceCreate(CFDictionaryRef dict);
134 extern "C" int IOSurfaceLock(IOSurfaceRef surface, unsigned int lockType);
135 extern "C" int IOSurfaceUnlock(IOSurfaceRef surface);
136 extern "C" void *IOSurfaceGetBaseAddress(IOSurfaceRef surface);
138 extern "C" void IOSurfaceFlushProcessorCaches(IOSurfaceRef buffer);
140 typedef void *IOSurfaceAcceleratorRef;
142 extern "C" int IOSurfaceAcceleratorCreate(CFAllocatorRef allocator, void *type, IOSurfaceAcceleratorRef *accel);
143 extern "C" unsigned int IOSurfaceAcceleratorTransferSurface(IOSurfaceAcceleratorRef accelerator, IOSurfaceRef dest, IOSurfaceRef src, void *, void *, void *, void *);
145 typedef void *IOMobileFramebufferRef;
147 extern "C" kern_return_t IOMobileFramebufferSwapSetLayer(
148 IOMobileFramebufferRef fb,
156 extern "C" void IOMobileFramebufferGetDisplaySize(IOMobileFramebufferRef connect, CGSize *size);
157 extern "C" void IOMobileFramebufferIsMainDisplay(IOMobileFramebufferRef connect, int *main);
160 IOHIDEventRef IOHIDEventCreateKeyboardEvent(CFAllocatorRef allocator, uint64_t time, uint16_t page, uint16_t usage, Boolean down, IOHIDEventOptionBits flags);
162 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);
163 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);
165 IOHIDEventSystemClientRef IOHIDEventSystemClientCreate(CFAllocatorRef allocator);
167 void IOHIDEventAppendEvent(IOHIDEventRef parent, IOHIDEventRef child);
168 void IOHIDEventSetIntegerValue(IOHIDEventRef event, IOHIDEventField field, int value);
169 void IOHIDEventSetSenderID(IOHIDEventRef event, uint64_t sender);
171 void IOHIDEventSystemClientDispatchEvent(IOHIDEventSystemClientRef client, IOHIDEventRef event);
172 void IOHIDEventSystemConnectionDispatchEvent(IOHIDEventSystemConnectionRef connection, IOHIDEventRef event);
175 static size_t width_;
176 static size_t height_;
177 static NSUInteger ratio_ = 0;
179 static const size_t BytesPerPixel = 4;
180 static const size_t BitsPerSample = 8;
182 static IOSurfaceAcceleratorRef accelerator_;
183 static IOSurfaceRef buffer_;
185 static NSMutableSet *handlers_;
186 static rfbScreenInfoPtr screen_;
187 static bool running_;
191 static unsigned clients_;
193 static CFMessagePortRef ashikase_;
196 static rfbPixel *black_;
198 static void VNCBlack() {
199 if (_unlikely(black_ == NULL))
200 black_ = reinterpret_cast<rfbPixel *>(mmap(NULL, sizeof(rfbPixel) * width_ * height_, PROT_READ, MAP_ANON | MAP_PRIVATE | MAP_NOCACHE, VM_FLAGS_PURGABLE, 0));
201 screen_->frameBuffer = reinterpret_cast<char *>(black_);
204 static bool Ashikase(bool always) {
205 if (!always && !cursor_)
208 if (ashikase_ == NULL)
209 ashikase_ = CFMessagePortCreateRemote(kCFAllocatorDefault, CFSTR("jp.ashikase.mousesupport"));
210 if (ashikase_ != NULL)
217 static CFDataRef cfTrue_;
218 static CFDataRef cfFalse_;
226 static MouseEvent event_;
227 static CFDataRef cfEvent_;
230 MouseMessageTypeEvent,
231 MouseMessageTypeSetEnabled
234 static void AshikaseSendEvent(float x, float y, int buttons = 0) {
237 event_.buttons = buttons;
238 event_.absolute = true;
240 CFMessagePortSendRequest(ashikase_, MouseMessageTypeEvent, cfEvent_, 0, 0, NULL, NULL);
243 static void AshikaseSetEnabled(bool enabled, bool always) {
244 if (!Ashikase(always))
247 CFMessagePortSendRequest(ashikase_, MouseMessageTypeSetEnabled, enabled ? cfTrue_ : cfFalse_, 0, 0, NULL, NULL);
250 AshikaseSendEvent(x_, y_);
253 MSClassHook(SBAlertItem)
254 MSClassHook(SBAlertItemsController)
255 MSClassHook(SBStatusBarController)
257 @interface VNCAlertItem : SBAlertItem
260 static Class $VNCAlertItem;
262 static NSString *DialogTitle(@"Remote Access Request");
263 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!");
264 static NSString *DialogAccept(@"Accept");
265 static NSString *DialogReject(@"Reject");
267 static volatile rfbNewClientAction action_ = RFB_CLIENT_ON_HOLD;
268 static NSCondition *condition_;
269 static NSLock *lock_;
271 static rfbClientPtr client_;
273 static void VNCSetup();
274 static void VNCEnabled();
276 float (*$GSMainScreenScaleFactor)();
278 static void VNCAction(rfbNewClientAction action) {
285 static void OnUserNotification(CFUserNotificationRef notification, CFOptionFlags flags) {
286 if ((flags & 0x3) == 1)
287 VNCAction(RFB_CLIENT_ACCEPT);
289 VNCAction(RFB_CLIENT_REFUSE);
291 CFRelease(notification);
294 @interface VNCBridge : NSObject {
297 + (void) askForConnection;
298 + (void) removeStatusBarItem;
299 + (void) registerClient;
303 @implementation VNCBridge
305 + (void) askForConnection {
306 if ($VNCAlertItem != nil) {
307 [[$SBAlertItemsController sharedInstance] activateAlertItem:[[[$VNCAlertItem alloc] init] autorelease]];
312 CFUserNotificationRef notification(CFUserNotificationCreate(kCFAllocatorDefault, 0, kCFUserNotificationPlainAlertLevel, &error, (CFDictionaryRef) [NSDictionary dictionaryWithObjectsAndKeys:
313 DialogTitle, kCFUserNotificationAlertHeaderKey,
314 [NSString stringWithFormat:DialogFormat, client_->host], kCFUserNotificationAlertMessageKey,
315 DialogAccept, kCFUserNotificationAlternateButtonTitleKey,
316 DialogReject, kCFUserNotificationDefaultButtonTitleKey,
320 CFRelease(notification);
324 if (notification == NULL) {
325 VNCAction(RFB_CLIENT_REFUSE);
329 CFRunLoopSourceRef source(CFUserNotificationCreateRunLoopSource(kCFAllocatorDefault, notification, &OnUserNotification, 0));
330 CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode);
333 + (void) removeStatusBarItem {
334 AshikaseSetEnabled(false, false);
337 SBA_removeStatusBarImage(const_cast<char *>("Veency"));
338 else if ($SBStatusBarController != nil)
339 [[$SBStatusBarController sharedStatusBarController] removeStatusBarItem:@"Veency"];
340 else if (UIApplication *app = [$UIApplication sharedApplication])
341 [app removeStatusBarImageNamed:@"Veency"];
344 + (void) registerClient {
345 // XXX: this could find a better home
347 if ($GSMainScreenScaleFactor == NULL)
350 ratio_ = $GSMainScreenScaleFactor();
354 AshikaseSetEnabled(true, false);
357 SBA_addStatusBarImage(const_cast<char *>("Veency"));
358 else if ($SBStatusBarController != nil)
359 [[$SBStatusBarController sharedStatusBarController] addStatusBarItem:@"Veency"];
360 else if (UIApplication *app = [$UIApplication sharedApplication])
361 [app addStatusBarImageNamed:@"Veency"];
364 + (void) performSetup:(NSThread *)thread {
365 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
366 [thread autorelease];
374 MSInstanceMessage2(void, VNCAlertItem, alertSheet,buttonClicked, id, sheet, int, button) {
377 VNCAction(RFB_CLIENT_ACCEPT);
381 VNCAction(RFB_CLIENT_REFUSE);
388 MSInstanceMessage2(void, VNCAlertItem, configure,requirePasscodeForActions, BOOL, configure, BOOL, require) {
389 UIModalView *sheet([self alertSheet]);
390 [sheet setDelegate:self];
391 [sheet setTitle:DialogTitle];
392 [sheet setBodyText:[NSString stringWithFormat:DialogFormat, client_->host]];
393 [sheet addButtonWithTitle:DialogAccept];
394 [sheet addButtonWithTitle:DialogReject];
397 MSInstanceMessage0(void, VNCAlertItem, performUnlockAction) {
398 [[$SBAlertItemsController sharedInstance] activateAlertItem:self];
401 static mach_port_t (*GSTakePurpleSystemEventPort)(void);
402 static bool PurpleAllocated;
405 static void FixRecord(GSEventRecord *record) {
407 memmove(&record->windowContextId, &record->windowContextId + 1, sizeof(*record) - (reinterpret_cast<uint8_t *>(&record->windowContextId + 1) - reinterpret_cast<uint8_t *>(record)) + record->size);
410 static void VNCSettings() {
411 @synchronized (lock_) {
412 for (NSValue *handler in handlers_)
413 rfbUnregisterSecurityHandler(reinterpret_cast<rfbSecurityHandler *>([handler pointerValue]));
414 [handlers_ removeAllObjects];
417 @synchronized (condition_) {
421 [(NSString *) screen_->authPasswdData release];
422 screen_->authPasswdData = NULL;
424 if (CFStringRef password = (CFStringRef) CFPreferencesCopyAppValue(CFSTR("Password"), CFSTR("com.saurik.Veency")))
425 if (CFStringGetLength(password) == 0)
428 screen_->authPasswdData = (void *) password;
431 cursor_ = CFPreferencesGetAppBooleanValue(CFSTR("ShowCursor"), CFSTR("com.saurik.Veency"), &valid);
436 AshikaseSetEnabled(cursor_, true);
440 static void VNCNotifySettings(
441 CFNotificationCenterRef center,
447 CFPreferencesAppSynchronize(CFSTR("com.saurik.Veency"));
451 static rfbBool VNCCheck(rfbClientPtr client, const char *data, int size) {
452 @synchronized (condition_) {
453 if (NSString *password = reinterpret_cast<NSString *>(screen_->authPasswdData)) {
454 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
455 rfbEncryptBytes(client->authChallenge, const_cast<char *>([password UTF8String]));
456 bool good(memcmp(client->authChallenge, data, size) == 0);
466 struct GSEventRecord record;
468 struct GSEventRecordInfo info;
469 struct GSPathInfo path;
473 static void VNCPointerOld(int buttons, int x, int y, CGPoint location, int diff, bool twas, bool tis);
474 static void VNCPointerNew(int buttons, int x, int y, CGPoint location, int diff, bool twas, bool tis);
476 static void VNCPointer(int buttons, int x, int y, rfbClientPtr client) {
480 CGPoint location = {x, y};
482 if (width_ > height_) {
497 int diff = buttons_ ^ buttons;
498 bool twas((buttons_ & 0x1) != 0);
499 bool tis((buttons & 0x1) != 0);
502 rfbDefaultPtrAddEvent(buttons, x, y, client);
504 if (Ashikase(false)) {
505 AshikaseSendEvent(x, y, buttons);
509 if (kCFCoreFoundationVersionNumber >= 800)
510 return VNCPointerNew(buttons, x, y, location, diff, twas, tis);
512 return VNCPointerOld(buttons, x, y, location, diff, twas, tis);
515 static void VNCPointerOld(int buttons, int x, int y, CGPoint location, int diff, bool twas, bool tis) {
516 mach_port_t purple(0);
518 if ((diff & 0x10) != 0) {
519 struct GSEventRecord record;
521 memset(&record, 0, sizeof(record));
523 record.type = (buttons & 0x10) != 0 ?
524 GSEventTypeHeadsetButtonDown :
525 GSEventTypeHeadsetButtonUp;
527 record.timestamp = GSCurrentEventTimestamp();
530 GSSendSystemEvent(&record);
533 if ((diff & 0x04) != 0) {
534 struct GSEventRecord record;
536 memset(&record, 0, sizeof(record));
538 record.type = (buttons & 0x04) != 0 ?
539 GSEventTypeMenuButtonDown :
540 GSEventTypeMenuButtonUp;
542 record.timestamp = GSCurrentEventTimestamp();
545 GSSendSystemEvent(&record);
548 if ((diff & 0x02) != 0) {
549 struct GSEventRecord record;
551 memset(&record, 0, sizeof(record));
553 record.type = (buttons & 0x02) != 0 ?
554 GSEventTypeLockButtonDown :
555 GSEventTypeLockButtonUp;
557 record.timestamp = GSCurrentEventTimestamp();
560 GSSendSystemEvent(&record);
563 if (twas != tis || tis) {
564 struct VeencyEvent event;
566 memset(&event, 0, sizeof(event));
568 event.record.type = GSEventTypeMouse;
569 event.record.locationInWindow.x = x;
570 event.record.locationInWindow.y = y;
571 event.record.timestamp = GSCurrentEventTimestamp();
572 event.record.size = sizeof(event.data);
574 event.data.info.handInfo.type = twas == tis ?
575 GSMouseEventTypeDragged :
577 GSMouseEventTypeDown :
580 event.data.info.handInfo.x34 = 0x1;
581 event.data.info.handInfo.x38 = tis ? 0x1 : 0x0;
584 event.data.info.pathPositions = 1;
586 event.data.info.x52 = 1;
588 event.data.path.x00 = 0x01;
589 event.data.path.x01 = 0x02;
590 event.data.path.x02 = tis ? 0x03 : 0x00;
591 event.data.path.position = event.record.locationInWindow;
595 if (CAWindowServer *server = [CAWindowServer serverIfRunning]) {
596 NSArray *displays([server displays]);
597 if (displays != nil && [displays count] != 0)
598 if (CAWindowServerDisplay *display = [displays objectAtIndex:0])
599 port = [display clientPortAtPosition:location];
604 purple = (*GSTakePurpleSystemEventPort)();
608 FixRecord(&event.record);
609 GSSendEvent(&event.record, port);
612 if (purple != 0 && PurpleAllocated)
613 mach_port_deallocate(mach_task_self(), purple);
616 static void VNCSendHIDEvent(IOHIDEventRef event) {
617 static IOHIDEventSystemClientRef client_(NULL);
619 client_ = IOHIDEventSystemClientCreate(kCFAllocatorDefault);
621 IOHIDEventSetSenderID(event, 0xDEFACEDBEEFFECE5);
622 IOHIDEventSystemClientDispatchEvent(client_, event);
626 static void VNCPointerNew(int buttons, int x, int y, CGPoint location, int diff, bool twas, bool tis) {
627 if ((diff & 0x10) != 0)
628 VNCSendHIDEvent(IOHIDEventCreateKeyboardEvent(kCFAllocatorDefault, mach_absolute_time(), kHIDPage_Telephony, kHIDUsage_Tfon_Flash, (buttons & 0x10) != 0, 0));
629 if ((diff & 0x04) != 0)
630 VNCSendHIDEvent(IOHIDEventCreateKeyboardEvent(kCFAllocatorDefault, mach_absolute_time(), kHIDPage_Consumer, kHIDUsage_Csmr_Menu, (buttons & 0x04) != 0, 0));
631 if ((diff & 0x02) != 0)
632 VNCSendHIDEvent(IOHIDEventCreateKeyboardEvent(kCFAllocatorDefault, mach_absolute_time(), kHIDPage_Consumer, kHIDUsage_Csmr_Power, (buttons & 0x02) != 0, 0));
637 if (twas == 0 && tis == 1) {
638 handm = kIOHIDDigitizerEventRange | kIOHIDDigitizerEventTouch | kIOHIDDigitizerEventIdentity;
639 fingerm = kIOHIDDigitizerEventRange | kIOHIDDigitizerEventTouch;
640 } else if (twas == 1 && tis == 1) {
641 handm = kIOHIDDigitizerEventPosition;
642 fingerm = kIOHIDDigitizerEventPosition;
643 } else if (twas == 1 && tis == 0) {
644 handm = kIOHIDDigitizerEventRange | kIOHIDDigitizerEventTouch | kIOHIDDigitizerEventIdentity | kIOHIDDigitizerEventPosition;
645 fingerm = kIOHIDDigitizerEventRange | kIOHIDDigitizerEventTouch;
648 // XXX: avoid division in VNCPointer()
658 IOHIDEventRef hand(IOHIDEventCreateDigitizerEvent(kCFAllocatorDefault, mach_absolute_time(), kIOHIDDigitizerTransducerTypeHand, 1<<22, 1, handm, 0, xf, yf, 0, 0, 0, 0, 0, 0));
659 IOHIDEventSetIntegerValue(hand, kIOHIDEventFieldIsBuiltIn, true);
660 IOHIDEventSetIntegerValue(hand, kIOHIDEventFieldDigitizerIsDisplayIntegrated, true);
662 IOHIDEventRef finger(IOHIDEventCreateDigitizerFingerEvent(kCFAllocatorDefault, mach_absolute_time(), 3, 2, fingerm, xf, yf, 0, 0, 0, tis, tis, 0));
663 IOHIDEventAppendEvent(hand, finger);
666 VNCSendHIDEvent(hand);
669 GSEventRef (*$GSEventCreateKeyEvent)(int, CGPoint, CFStringRef, CFStringRef, id, UniChar, short, short);
670 GSEventRef (*$GSCreateSyntheticKeyEvent)(UniChar, BOOL, BOOL);
672 static void VNCKeyboardNew(rfbBool down, rfbKeySym key, rfbClientPtr client) {
673 //NSLog(@"VNC d:%u k:%04x", down, key);
678 case XK_exclam: case XK_1: usage = kHIDUsage_Keyboard1; break;
679 case XK_at: case XK_2: usage = kHIDUsage_Keyboard2; break;
680 case XK_numbersign: case XK_3: usage = kHIDUsage_Keyboard3; break;
681 case XK_dollar: case XK_4: usage = kHIDUsage_Keyboard4; break;
682 case XK_percent: case XK_5: usage = kHIDUsage_Keyboard5; break;
683 case XK_asciicircum: case XK_6: usage = kHIDUsage_Keyboard6; break;
684 case XK_ampersand: case XK_7: usage = kHIDUsage_Keyboard7; break;
685 case XK_asterisk: case XK_8: usage = kHIDUsage_Keyboard8; break;
686 case XK_parenleft: case XK_9: usage = kHIDUsage_Keyboard9; break;
687 case XK_parenright: case XK_0: usage = kHIDUsage_Keyboard0; break;
689 case XK_A: case XK_a: usage = kHIDUsage_KeyboardA; break;
690 case XK_B: case XK_b: usage = kHIDUsage_KeyboardB; break;
691 case XK_C: case XK_c: usage = kHIDUsage_KeyboardC; break;
692 case XK_D: case XK_d: usage = kHIDUsage_KeyboardD; break;
693 case XK_E: case XK_e: usage = kHIDUsage_KeyboardE; break;
694 case XK_F: case XK_f: usage = kHIDUsage_KeyboardF; break;
695 case XK_G: case XK_g: usage = kHIDUsage_KeyboardG; break;
696 case XK_H: case XK_h: usage = kHIDUsage_KeyboardH; break;
697 case XK_I: case XK_i: usage = kHIDUsage_KeyboardI; break;
698 case XK_J: case XK_j: usage = kHIDUsage_KeyboardJ; break;
699 case XK_K: case XK_k: usage = kHIDUsage_KeyboardK; break;
700 case XK_L: case XK_l: usage = kHIDUsage_KeyboardL; break;
701 case XK_M: case XK_m: usage = kHIDUsage_KeyboardM; break;
702 case XK_N: case XK_n: usage = kHIDUsage_KeyboardN; break;
703 case XK_O: case XK_o: usage = kHIDUsage_KeyboardO; break;
704 case XK_P: case XK_p: usage = kHIDUsage_KeyboardP; break;
705 case XK_Q: case XK_q: usage = kHIDUsage_KeyboardQ; break;
706 case XK_R: case XK_r: usage = kHIDUsage_KeyboardR; break;
707 case XK_S: case XK_s: usage = kHIDUsage_KeyboardS; break;
708 case XK_T: case XK_t: usage = kHIDUsage_KeyboardT; break;
709 case XK_U: case XK_u: usage = kHIDUsage_KeyboardU; break;
710 case XK_V: case XK_v: usage = kHIDUsage_KeyboardV; break;
711 case XK_W: case XK_w: usage = kHIDUsage_KeyboardW; break;
712 case XK_X: case XK_x: usage = kHIDUsage_KeyboardX; break;
713 case XK_Y: case XK_y: usage = kHIDUsage_KeyboardY; break;
714 case XK_Z: case XK_z: usage = kHIDUsage_KeyboardZ; break;
716 case XK_underscore: case XK_minus: usage = kHIDUsage_KeyboardHyphen; break;
717 case XK_plus: case XK_equal: usage = kHIDUsage_KeyboardEqualSign; break;
718 case XK_braceleft: case XK_bracketleft: usage = kHIDUsage_KeyboardOpenBracket; break;
719 case XK_braceright: case XK_bracketright: usage = kHIDUsage_KeyboardCloseBracket; break;
720 case XK_bar: case XK_backslash: usage = kHIDUsage_KeyboardBackslash; break;
721 case XK_colon: case XK_semicolon: usage = kHIDUsage_KeyboardSemicolon; break;
722 case XK_quotedbl: case XK_apostrophe: usage = kHIDUsage_KeyboardQuote; break;
723 case XK_asciitilde: case XK_grave: usage = kHIDUsage_KeyboardGraveAccentAndTilde; break;
724 case XK_less: case XK_comma: usage = kHIDUsage_KeyboardComma; break;
725 case XK_greater: case XK_period: usage = kHIDUsage_KeyboardPeriod; break;
726 case XK_question: case XK_slash: usage = kHIDUsage_KeyboardSlash; break;
728 case XK_Return: usage = kHIDUsage_KeyboardReturnOrEnter; break;
729 case XK_BackSpace: usage = kHIDUsage_KeyboardDeleteOrBackspace; break;
730 case XK_Tab: usage = kHIDUsage_KeyboardTab; break;
731 case XK_space: usage = kHIDUsage_KeyboardSpacebar; break;
733 case XK_Shift_L: usage = kHIDUsage_KeyboardLeftShift; break;
734 case XK_Shift_R: usage = kHIDUsage_KeyboardRightShift; break;
735 case XK_Control_L: usage = kHIDUsage_KeyboardLeftControl; break;
736 case XK_Control_R: usage = kHIDUsage_KeyboardRightControl; break;
737 case XK_Meta_L: usage = kHIDUsage_KeyboardLeftAlt; break;
738 case XK_Meta_R: usage = kHIDUsage_KeyboardRightAlt; break;
739 case XK_Alt_L: usage = kHIDUsage_KeyboardLeftGUI; break;
740 case XK_Alt_R: usage = kHIDUsage_KeyboardRightGUI; break;
742 case XK_Up: usage = kHIDUsage_KeyboardUpArrow; break;
743 case XK_Down: usage = kHIDUsage_KeyboardDownArrow; break;
744 case XK_Left: usage = kHIDUsage_KeyboardLeftArrow; break;
745 case XK_Right: usage = kHIDUsage_KeyboardRightArrow; break;
747 case XK_Home: case XK_Begin: usage = kHIDUsage_KeyboardHome; break;
748 case XK_End: usage = kHIDUsage_KeyboardEnd; break;
749 case XK_Page_Up: usage = kHIDUsage_KeyboardPageUp; break;
750 case XK_Page_Down: usage = kHIDUsage_KeyboardPageDown; break;
755 VNCSendHIDEvent(IOHIDEventCreateKeyboardEvent(kCFAllocatorDefault, mach_absolute_time(), kHIDPage_KeyboardOrKeypad, usage, down, 0));
758 static void VNCKeyboard(rfbBool down, rfbKeySym key, rfbClientPtr client) {
759 if (kCFCoreFoundationVersionNumber >= 800)
760 return VNCKeyboardNew(down, key, client);
766 case XK_Return: key = '\r'; break;
767 case XK_BackSpace: key = 0x7f; break;
773 CGPoint point(CGPointMake(x_, y_));
775 UniChar unicode(key);
776 CFStringRef string(NULL);
778 GSEventRef event0, event1(NULL);
779 if ($GSEventCreateKeyEvent != NULL) {
780 string = CFStringCreateWithCharacters(kCFAllocatorDefault, &unicode, 1);
781 event0 = (*$GSEventCreateKeyEvent)(10, point, string, string, nil, 0, 0, 1);
782 event1 = (*$GSEventCreateKeyEvent)(11, point, string, string, nil, 0, 0, 1);
783 } else if ($GSCreateSyntheticKeyEvent != NULL) {
784 event0 = (*$GSCreateSyntheticKeyEvent)(unicode, YES, YES);
785 GSEventRecord *record(_GSEventGetGSEventRecord(event0));
786 record->type = GSEventTypeKeyDown;
791 if (CAWindowServer *server = [CAWindowServer serverIfRunning]) {
792 NSArray *displays([server displays]);
793 if (displays != nil && [displays count] != 0)
794 if (CAWindowServerDisplay *display = [displays objectAtIndex:0])
795 port = [display clientPortAtPosition:point];
798 mach_port_t purple(0);
802 purple = (*GSTakePurpleSystemEventPort)();
807 GSSendEvent(_GSEventGetGSEventRecord(event0), port);
809 GSSendEvent(_GSEventGetGSEventRecord(event1), port);
812 if (purple != 0 && PurpleAllocated)
813 mach_port_deallocate(mach_task_self(), purple);
822 static void VNCDisconnect(rfbClientPtr client) {
823 @synchronized (condition_) {
825 [VNCBridge performSelectorOnMainThread:@selector(removeStatusBarItem) withObject:nil waitUntilDone:YES];
829 static rfbNewClientAction VNCClient(rfbClientPtr client) {
832 rfbNewClientAction action;
833 if (screen_->authPasswdData != NULL)
834 action = RFB_CLIENT_ACCEPT;
837 [VNCBridge performSelectorOnMainThread:@selector(askForConnection) withObject:nil waitUntilDone:NO];
838 while (action_ == RFB_CLIENT_ON_HOLD)
841 action_ = RFB_CLIENT_ON_HOLD;
844 if (action == RFB_CLIENT_ACCEPT) {
845 [VNCBridge performSelectorOnMainThread:@selector(registerClient) withObject:nil waitUntilDone:YES];
846 client->clientGoneHook = &VNCDisconnect;
853 extern "C" bool GSSystemHasCapability(NSString *);
855 static CFTypeRef (*$GSSystemCopyCapability)(CFStringRef);
856 static CFTypeRef (*$GSSystemGetCapability)(CFStringRef);
857 static BOOL (*$MGGetBoolAnswer)(CFStringRef);
859 static void VNCSetup() {
862 @synchronized (condition_) {
864 char *arg0(strdup("VNCServer"));
865 char *argv[] = {arg0, NULL};
866 screen_ = rfbGetScreen(&argc, argv, width_, height_, BitsPerSample, 3, BytesPerPixel);
872 screen_->desktopName = strdup([[[NSProcessInfo processInfo] hostName] UTF8String]);
874 screen_->alwaysShared = TRUE;
875 screen_->handleEventsEagerly = TRUE;
876 screen_->deferUpdateTime = 1000 / 25;
878 screen_->serverFormat.redShift = BitsPerSample * 2;
879 screen_->serverFormat.greenShift = BitsPerSample * 1;
880 screen_->serverFormat.blueShift = BitsPerSample * 0;
882 $GSSystemCopyCapability = reinterpret_cast<CFTypeRef (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, "GSSystemCopyCapability"));
883 $GSSystemGetCapability = reinterpret_cast<CFTypeRef (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, "GSSystemGetCapability"));
884 $MGGetBoolAnswer = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, "MGGetBoolAnswer"));
888 if ($GSSystemCopyCapability != NULL) {
889 opengles2 = (*$GSSystemCopyCapability)(CFSTR("opengles-2"));
890 } else if ($GSSystemGetCapability != NULL) {
891 opengles2 = (*$GSSystemGetCapability)(CFSTR("opengles-2"));
892 if (opengles2 != NULL)
894 } else if ($MGGetBoolAnswer != NULL) {
895 opengles2 = $MGGetBoolAnswer(CFSTR("opengles-2")) ? kCFBooleanTrue : kCFBooleanFalse;
900 bool accelerated(opengles2 != NULL && [(NSNumber *)opengles2 boolValue]);
903 IOSurfaceAcceleratorCreate(NULL, NULL, &accelerator_);
905 if (opengles2 != NULL)
906 CFRelease(opengles2);
908 if (accelerator_ == NULL)
911 buffer_ = IOSurfaceCreate((CFDictionaryRef) [NSDictionary dictionaryWithObjectsAndKeys:
912 @"PurpleEDRAM", kIOSurfaceMemoryRegion,
913 [NSNumber numberWithBool:YES], kIOSurfaceIsGlobal,
914 [NSNumber numberWithInt:(width_ * BytesPerPixel)], kIOSurfaceBytesPerRow,
915 [NSNumber numberWithInt:width_], kIOSurfaceWidth,
916 [NSNumber numberWithInt:height_], kIOSurfaceHeight,
917 [NSNumber numberWithInt:'BGRA'], kIOSurfacePixelFormat,
918 [NSNumber numberWithInt:(width_ * height_ * BytesPerPixel)], kIOSurfaceAllocSize,
921 IOSurfaceLock(buffer_, 3);
922 screen_->frameBuffer = reinterpret_cast<char *>(IOSurfaceGetBaseAddress(buffer_));
923 IOSurfaceUnlock(buffer_);
926 screen_->kbdAddEvent = &VNCKeyboard;
927 screen_->ptrAddEvent = &VNCPointer;
929 screen_->newClientHook = &VNCClient;
930 screen_->passwordCheck = &VNCCheck;
932 screen_->cursor = NULL;
935 static void VNCEnabled() {
939 @synchronized (lock_) {
942 bool enabled(CFPreferencesGetAppBooleanValue(CFSTR("Enabled"), CFSTR("com.saurik.Veency"), &valid));
946 if (enabled != running_)
949 screen_->socketState = RFB_SOCKET_INIT;
950 rfbInitServer(screen_);
951 rfbRunEventLoop(screen_, -1, true);
953 rfbShutdownServer(screen_, true);
960 static void VNCNotifyEnabled(
961 CFNotificationCenterRef center,
967 CFPreferencesAppSynchronize(CFSTR("com.saurik.Veency"));
971 void (*$IOMobileFramebufferIsMainDisplay)(IOMobileFramebufferRef, int *);
973 static IOMobileFramebufferRef main_;
974 static IOSurfaceRef layer_;
976 static void OnLayer(IOMobileFramebufferRef fb, IOSurfaceRef layer) {
977 if (_unlikely(width_ == 0 || height_ == 0)) {
979 IOMobileFramebufferGetDisplaySize(fb, &size);
982 height_ = size.height;
984 if (width_ == 0 || height_ == 0)
987 NSThread *thread([NSThread alloc]);
990 initWithTarget:[VNCBridge class]
991 selector:@selector(performSetup:)
996 } else if (_unlikely(clients_ != 0)) {
998 if (accelerator_ != NULL)
999 memset(screen_->frameBuffer, 0, sizeof(rfbPixel) * width_ * height_);
1003 if (accelerator_ != NULL)
1004 IOSurfaceAcceleratorTransferSurface(accelerator_, layer, buffer_, NULL, NULL, NULL, NULL);
1006 IOSurfaceLock(layer, 2);
1007 rfbPixel *data(reinterpret_cast<rfbPixel *>(IOSurfaceGetBaseAddress(layer)));
1009 IOSurfaceFlushProcessorCaches(layer);
1011 /*rfbPixel corner(data[0]);
1015 screen_->frameBuffer = const_cast<char *>(reinterpret_cast<volatile char *>(data));
1016 IOSurfaceUnlock(layer);
1020 rfbMarkRectAsModified(screen_, 0, 0, width_, height_);
1024 static bool wait_ = false;
1026 MSHook(kern_return_t, IOMobileFramebufferSwapSetLayer,
1027 IOMobileFramebufferRef fb,
1029 IOSurfaceRef buffer,
1036 if (_unlikely(buffer == NULL))
1038 else if (_unlikely(fb == NULL))
1040 else if ($IOMobileFramebufferIsMainDisplay == NULL)
1043 (*$IOMobileFramebufferIsMainDisplay)(fb, &main);
1045 if (_likely(main)) {
1050 OnLayer(fb, buffer);
1053 return _IOMobileFramebufferSwapSetLayer(fb, layer, buffer, bounds, frame, flags);
1056 // XXX: beg rpetrich for the type of this function
1057 extern "C" void *IOMobileFramebufferSwapWait(IOMobileFramebufferRef, void *, unsigned);
1059 MSHook(void *, IOMobileFramebufferSwapWait, IOMobileFramebufferRef fb, void *arg1, unsigned flags) {
1060 void *value(_IOMobileFramebufferSwapWait(fb, arg1, flags));
1062 OnLayer(fb, layer_);
1066 MSHook(void, rfbRegisterSecurityHandler, rfbSecurityHandler *handler) {
1067 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
1069 @synchronized (lock_) {
1070 [handlers_ addObject:[NSValue valueWithPointer:handler]];
1071 _rfbRegisterSecurityHandler(handler);
1077 template <typename Type_>
1078 static void dlset(Type_ &function, const char *name) {
1079 function = reinterpret_cast<Type_>(dlsym(RTLD_DEFAULT, name));
1083 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
1085 MSHookSymbol(GSTakePurpleSystemEventPort, "_GSGetPurpleSystemEventPort");
1086 if (GSTakePurpleSystemEventPort == NULL) {
1087 MSHookSymbol(GSTakePurpleSystemEventPort, "_GSCopyPurpleSystemEventPort");
1088 PurpleAllocated = true;
1091 if (dlsym(RTLD_DEFAULT, "GSLibraryCopyGenerationInfoValueForKey") != NULL)
1093 else if (dlsym(RTLD_DEFAULT, "GSKeyboardCreate") != NULL)
1095 else if (dlsym(RTLD_DEFAULT, "GSEventGetWindowContextId") != NULL)
1101 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
1103 sysctlbyname("hw.machine", machine, &size, NULL, 0);
1104 iPad1_ = strcmp(machine, "iPad1,1") == 0;
1106 dlset($GSMainScreenScaleFactor, "GSMainScreenScaleFactor");
1107 dlset($GSEventCreateKeyEvent, "GSEventCreateKeyEvent");
1108 dlset($GSCreateSyntheticKeyEvent, "_GSCreateSyntheticKeyEvent");
1109 dlset($IOMobileFramebufferIsMainDisplay, "IOMobileFramebufferIsMainDisplay");
1111 MSHookFunction(&IOMobileFramebufferSwapSetLayer, MSHake(IOMobileFramebufferSwapSetLayer));
1112 MSHookFunction(&rfbRegisterSecurityHandler, MSHake(rfbRegisterSecurityHandler));
1115 MSHookFunction(&IOMobileFramebufferSwapWait, MSHake(IOMobileFramebufferSwapWait));
1117 if ($SBAlertItem != nil) {
1118 $VNCAlertItem = objc_allocateClassPair($SBAlertItem, "VNCAlertItem", 0);
1119 MSAddMessage2(VNCAlertItem, "v@:@i", alertSheet,buttonClicked);
1120 MSAddMessage2(VNCAlertItem, "v@:cc", configure,requirePasscodeForActions);
1121 MSAddMessage0(VNCAlertItem, "v@:", performUnlockAction);
1122 objc_registerClassPair($VNCAlertItem);
1125 CFNotificationCenterAddObserver(
1126 CFNotificationCenterGetDarwinNotifyCenter(),
1127 NULL, &VNCNotifyEnabled, CFSTR("com.saurik.Veency-Enabled"), NULL, 0
1130 CFNotificationCenterAddObserver(
1131 CFNotificationCenterGetDarwinNotifyCenter(),
1132 NULL, &VNCNotifySettings, CFSTR("com.saurik.Veency-Settings"), NULL, 0
1135 condition_ = [[NSCondition alloc] init];
1136 lock_ = [[NSLock alloc] init];
1137 handlers_ = [[NSMutableSet alloc] init];
1142 cfTrue_ = CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&value), sizeof(value));
1145 cfFalse_ = CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&value), sizeof(value));
1147 cfEvent_ = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&event_), sizeof(event_), kCFAllocatorNull);