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 typedef void *CoreSurfaceBufferRef;
101 extern CFStringRef kCoreSurfaceBufferGlobal;
102 extern CFStringRef kCoreSurfaceBufferMemoryRegion;
103 extern CFStringRef kCoreSurfaceBufferPitch;
104 extern CFStringRef kCoreSurfaceBufferWidth;
105 extern CFStringRef kCoreSurfaceBufferHeight;
106 extern CFStringRef kCoreSurfaceBufferPixelFormat;
107 extern CFStringRef kCoreSurfaceBufferAllocSize;
109 extern "C" CoreSurfaceBufferRef CoreSurfaceBufferCreate(CFDictionaryRef dict);
110 extern "C" int CoreSurfaceBufferLock(CoreSurfaceBufferRef surface, unsigned int lockType);
111 extern "C" int CoreSurfaceBufferUnlock(CoreSurfaceBufferRef surface);
112 extern "C" void *CoreSurfaceBufferGetBaseAddress(CoreSurfaceBufferRef surface);
114 extern "C" void CoreSurfaceBufferFlushProcessorCaches(CoreSurfaceBufferRef buffer);
116 typedef void *CoreSurfaceAcceleratorRef;
118 extern "C" int CoreSurfaceAcceleratorCreate(CFAllocatorRef allocator, void *type, CoreSurfaceAcceleratorRef *accel);
119 extern "C" unsigned int CoreSurfaceAcceleratorTransferSurface(CoreSurfaceAcceleratorRef accelerator, CoreSurfaceBufferRef dest, CoreSurfaceBufferRef src, CFDictionaryRef options/*, void *, void *, void **/);
121 typedef void *IOMobileFramebufferRef;
123 extern "C" kern_return_t IOMobileFramebufferSwapSetLayer(
124 IOMobileFramebufferRef fb,
126 CoreSurfaceBufferRef buffer,
132 extern "C" void IOMobileFramebufferGetDisplaySize(IOMobileFramebufferRef connect, CGSize *size);
133 extern "C" void IOMobileFramebufferIsMainDisplay(IOMobileFramebufferRef connect, int *main);
136 IOHIDEventRef IOHIDEventCreateKeyboardEvent(CFAllocatorRef allocator, uint64_t time, uint16_t page, uint16_t usage, Boolean down, IOHIDEventOptionBits flags);
138 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);
139 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);
141 IOHIDEventSystemClientRef IOHIDEventSystemClientCreate(CFAllocatorRef allocator);
143 void IOHIDEventAppendEvent(IOHIDEventRef parent, IOHIDEventRef child);
144 void IOHIDEventSetIntegerValue(IOHIDEventRef event, IOHIDEventField field, int value);
145 void IOHIDEventSetSenderID(IOHIDEventRef event, uint64_t sender);
147 void IOHIDEventSystemClientDispatchEvent(IOHIDEventSystemClientRef client, IOHIDEventRef event);
148 void IOHIDEventSystemConnectionDispatchEvent(IOHIDEventSystemConnectionRef connection, IOHIDEventRef event);
151 static size_t width_;
152 static size_t height_;
153 static NSUInteger ratio_ = 0;
155 static const size_t BytesPerPixel = 4;
156 static const size_t BitsPerSample = 8;
158 static CoreSurfaceAcceleratorRef accelerator_;
159 static CoreSurfaceBufferRef buffer_;
160 static CFDictionaryRef options_;
162 static NSMutableSet *handlers_;
163 static rfbScreenInfoPtr screen_;
164 static bool running_;
168 static unsigned clients_;
170 static CFMessagePortRef ashikase_;
173 static rfbPixel *black_;
175 static void VNCBlack() {
176 if (_unlikely(black_ == NULL))
177 black_ = reinterpret_cast<rfbPixel *>(mmap(NULL, sizeof(rfbPixel) * width_ * height_, PROT_READ, MAP_ANON | MAP_PRIVATE | MAP_NOCACHE, VM_FLAGS_PURGABLE, 0));
178 screen_->frameBuffer = reinterpret_cast<char *>(black_);
181 static bool Ashikase(bool always) {
182 if (!always && !cursor_)
185 if (ashikase_ == NULL)
186 ashikase_ = CFMessagePortCreateRemote(kCFAllocatorDefault, CFSTR("jp.ashikase.mousesupport"));
187 if (ashikase_ != NULL)
194 static CFDataRef cfTrue_;
195 static CFDataRef cfFalse_;
203 static MouseEvent event_;
204 static CFDataRef cfEvent_;
207 MouseMessageTypeEvent,
208 MouseMessageTypeSetEnabled
211 static void AshikaseSendEvent(float x, float y, int buttons = 0) {
214 event_.buttons = buttons;
215 event_.absolute = true;
217 CFMessagePortSendRequest(ashikase_, MouseMessageTypeEvent, cfEvent_, 0, 0, NULL, NULL);
220 static void AshikaseSetEnabled(bool enabled, bool always) {
221 if (!Ashikase(always))
224 CFMessagePortSendRequest(ashikase_, MouseMessageTypeSetEnabled, enabled ? cfTrue_ : cfFalse_, 0, 0, NULL, NULL);
227 AshikaseSendEvent(x_, y_);
230 MSClassHook(SBAlertItem)
231 MSClassHook(SBAlertItemsController)
232 MSClassHook(SBStatusBarController)
234 @interface VNCAlertItem : SBAlertItem
237 static Class $VNCAlertItem;
239 static NSString *DialogTitle(@"Remote Access Request");
240 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!");
241 static NSString *DialogAccept(@"Accept");
242 static NSString *DialogReject(@"Reject");
244 static volatile rfbNewClientAction action_ = RFB_CLIENT_ON_HOLD;
245 static NSCondition *condition_;
246 static NSLock *lock_;
248 static rfbClientPtr client_;
250 static void VNCSetup();
251 static void VNCEnabled();
253 float (*$GSMainScreenScaleFactor)();
255 static void OnUserNotification(CFUserNotificationRef notification, CFOptionFlags flags) {
258 if ((flags & 0x3) == 1)
259 action_ = RFB_CLIENT_ACCEPT;
261 action_ = RFB_CLIENT_REFUSE;
266 CFRelease(notification);
269 @interface VNCBridge : NSObject {
272 + (void) askForConnection;
273 + (void) removeStatusBarItem;
274 + (void) registerClient;
278 @implementation VNCBridge
280 + (void) askForConnection {
281 if ($VNCAlertItem != nil) {
282 [[$SBAlertItemsController sharedInstance] activateAlertItem:[[[$VNCAlertItem alloc] init] autorelease]];
287 CFUserNotificationRef notification(CFUserNotificationCreate(kCFAllocatorDefault, 0, kCFUserNotificationPlainAlertLevel, &error, (CFDictionaryRef) [NSDictionary dictionaryWithObjectsAndKeys:
288 DialogTitle, kCFUserNotificationAlertHeaderKey,
289 [NSString stringWithFormat:DialogFormat, client_->host], kCFUserNotificationAlertMessageKey,
290 DialogAccept, kCFUserNotificationAlternateButtonTitleKey,
291 DialogReject, kCFUserNotificationDefaultButtonTitleKey,
295 CFRelease(notification);
299 if (notification == NULL) {
301 action_ = RFB_CLIENT_REFUSE;
307 CFRunLoopSourceRef source(CFUserNotificationCreateRunLoopSource(kCFAllocatorDefault, notification, &OnUserNotification, 0));
308 CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode);
311 + (void) removeStatusBarItem {
312 AshikaseSetEnabled(false, false);
315 SBA_removeStatusBarImage(const_cast<char *>("Veency"));
316 else if ($SBStatusBarController != nil)
317 [[$SBStatusBarController sharedStatusBarController] removeStatusBarItem:@"Veency"];
318 else if (UIApplication *app = [$UIApplication sharedApplication])
319 [app removeStatusBarImageNamed:@"Veency"];
322 + (void) registerClient {
323 // XXX: this could find a better home
325 if ($GSMainScreenScaleFactor == NULL)
328 ratio_ = $GSMainScreenScaleFactor();
332 AshikaseSetEnabled(true, false);
335 SBA_addStatusBarImage(const_cast<char *>("Veency"));
336 else if ($SBStatusBarController != nil)
337 [[$SBStatusBarController sharedStatusBarController] addStatusBarItem:@"Veency"];
338 else if (UIApplication *app = [$UIApplication sharedApplication])
339 [app addStatusBarImageNamed:@"Veency"];
342 + (void) performSetup:(NSThread *)thread {
343 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
344 [thread autorelease];
352 MSInstanceMessage2(void, VNCAlertItem, alertSheet,buttonClicked, id, sheet, int, button) {
357 action_ = RFB_CLIENT_ACCEPT;
359 @synchronized (condition_) {
360 [VNCBridge registerClient];
365 action_ = RFB_CLIENT_REFUSE;
374 MSInstanceMessage2(void, VNCAlertItem, configure,requirePasscodeForActions, BOOL, configure, BOOL, require) {
375 UIModalView *sheet([self alertSheet]);
376 [sheet setDelegate:self];
377 [sheet setTitle:DialogTitle];
378 [sheet setBodyText:[NSString stringWithFormat:DialogFormat, client_->host]];
379 [sheet addButtonWithTitle:DialogAccept];
380 [sheet addButtonWithTitle:DialogReject];
383 MSInstanceMessage0(void, VNCAlertItem, performUnlockAction) {
384 [[$SBAlertItemsController sharedInstance] activateAlertItem:self];
387 static mach_port_t (*GSTakePurpleSystemEventPort)(void);
388 static bool PurpleAllocated;
391 static void FixRecord(GSEventRecord *record) {
393 memmove(&record->windowContextId, &record->windowContextId + 1, sizeof(*record) - (reinterpret_cast<uint8_t *>(&record->windowContextId + 1) - reinterpret_cast<uint8_t *>(record)) + record->size);
396 static void VNCSettings() {
397 @synchronized (lock_) {
398 for (NSValue *handler in handlers_)
399 rfbUnregisterSecurityHandler(reinterpret_cast<rfbSecurityHandler *>([handler pointerValue]));
400 [handlers_ removeAllObjects];
403 @synchronized (condition_) {
407 [(NSString *) screen_->authPasswdData release];
408 screen_->authPasswdData = NULL;
410 if (CFStringRef password = (CFStringRef) CFPreferencesCopyAppValue(CFSTR("Password"), CFSTR("com.saurik.Veency")))
411 if (CFStringGetLength(password) == 0)
414 screen_->authPasswdData = (void *) password;
417 cursor_ = CFPreferencesGetAppBooleanValue(CFSTR("ShowCursor"), CFSTR("com.saurik.Veency"), &valid);
422 AshikaseSetEnabled(cursor_, true);
426 static void VNCNotifySettings(
427 CFNotificationCenterRef center,
436 static rfbBool VNCCheck(rfbClientPtr client, const char *data, int size) {
437 @synchronized (condition_) {
438 if (NSString *password = reinterpret_cast<NSString *>(screen_->authPasswdData)) {
439 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
440 rfbEncryptBytes(client->authChallenge, const_cast<char *>([password UTF8String]));
441 bool good(memcmp(client->authChallenge, data, size) == 0);
451 struct GSEventRecord record;
453 struct GSEventRecordInfo info;
454 struct GSPathInfo path;
458 static void VNCPointerOld(int buttons, int x, int y, CGPoint location, int diff, bool twas, bool tis);
459 static void VNCPointerNew(int buttons, int x, int y, CGPoint location, int diff, bool twas, bool tis);
461 static void VNCPointer(int buttons, int x, int y, rfbClientPtr client) {
465 CGPoint location = {x, y};
467 if (width_ > height_) {
482 int diff = buttons_ ^ buttons;
483 bool twas((buttons_ & 0x1) != 0);
484 bool tis((buttons & 0x1) != 0);
487 rfbDefaultPtrAddEvent(buttons, x, y, client);
489 if (Ashikase(false)) {
490 AshikaseSendEvent(x, y, buttons);
494 if (kCFCoreFoundationVersionNumber >= 800)
495 return VNCPointerNew(buttons, x, y, location, diff, twas, tis);
497 return VNCPointerOld(buttons, x, y, location, diff, twas, tis);
500 static void VNCPointerOld(int buttons, int x, int y, CGPoint location, int diff, bool twas, bool tis) {
501 mach_port_t purple(0);
503 if ((diff & 0x10) != 0) {
504 struct GSEventRecord record;
506 memset(&record, 0, sizeof(record));
508 record.type = (buttons & 0x10) != 0 ?
509 GSEventTypeHeadsetButtonDown :
510 GSEventTypeHeadsetButtonUp;
512 record.timestamp = GSCurrentEventTimestamp();
515 GSSendSystemEvent(&record);
518 if ((diff & 0x04) != 0) {
519 struct GSEventRecord record;
521 memset(&record, 0, sizeof(record));
523 record.type = (buttons & 0x04) != 0 ?
524 GSEventTypeMenuButtonDown :
525 GSEventTypeMenuButtonUp;
527 record.timestamp = GSCurrentEventTimestamp();
530 GSSendSystemEvent(&record);
533 if ((diff & 0x02) != 0) {
534 struct GSEventRecord record;
536 memset(&record, 0, sizeof(record));
538 record.type = (buttons & 0x02) != 0 ?
539 GSEventTypeLockButtonDown :
540 GSEventTypeLockButtonUp;
542 record.timestamp = GSCurrentEventTimestamp();
545 GSSendSystemEvent(&record);
548 if (twas != tis || tis) {
549 struct VeencyEvent event;
551 memset(&event, 0, sizeof(event));
553 event.record.type = GSEventTypeMouse;
554 event.record.locationInWindow.x = x;
555 event.record.locationInWindow.y = y;
556 event.record.timestamp = GSCurrentEventTimestamp();
557 event.record.size = sizeof(event.data);
559 event.data.info.handInfo.type = twas == tis ?
560 GSMouseEventTypeDragged :
562 GSMouseEventTypeDown :
565 event.data.info.handInfo.x34 = 0x1;
566 event.data.info.handInfo.x38 = tis ? 0x1 : 0x0;
569 event.data.info.pathPositions = 1;
571 event.data.info.x52 = 1;
573 event.data.path.x00 = 0x01;
574 event.data.path.x01 = 0x02;
575 event.data.path.x02 = tis ? 0x03 : 0x00;
576 event.data.path.position = event.record.locationInWindow;
580 if (CAWindowServer *server = [CAWindowServer serverIfRunning]) {
581 NSArray *displays([server displays]);
582 if (displays != nil && [displays count] != 0)
583 if (CAWindowServerDisplay *display = [displays objectAtIndex:0])
584 port = [display clientPortAtPosition:location];
589 purple = (*GSTakePurpleSystemEventPort)();
593 FixRecord(&event.record);
594 GSSendEvent(&event.record, port);
597 if (purple != 0 && PurpleAllocated)
598 mach_port_deallocate(mach_task_self(), purple);
601 static void VNCSendHIDEvent(IOHIDEventRef event) {
602 static IOHIDEventSystemClientRef client_(NULL);
604 client_ = IOHIDEventSystemClientCreate(kCFAllocatorDefault);
606 IOHIDEventSetSenderID(event, 0xDEFACEDBEEFFECE5);
607 IOHIDEventSystemClientDispatchEvent(client_, event);
611 static void VNCPointerNew(int buttons, int x, int y, CGPoint location, int diff, bool twas, bool tis) {
612 if ((diff & 0x10) != 0)
613 VNCSendHIDEvent(IOHIDEventCreateKeyboardEvent(kCFAllocatorDefault, mach_absolute_time(), kHIDPage_Telephony, kHIDUsage_Tfon_Flash, (buttons & 0x10) != 0, 0));
614 if ((diff & 0x04) != 0)
615 VNCSendHIDEvent(IOHIDEventCreateKeyboardEvent(kCFAllocatorDefault, mach_absolute_time(), kHIDPage_Consumer, kHIDUsage_Csmr_Menu, (buttons & 0x04) != 0, 0));
616 if ((diff & 0x02) != 0)
617 VNCSendHIDEvent(IOHIDEventCreateKeyboardEvent(kCFAllocatorDefault, mach_absolute_time(), kHIDPage_Consumer, kHIDUsage_Csmr_Power, (buttons & 0x02) != 0, 0));
622 if (twas == 0 && tis == 1) {
623 handm = kIOHIDDigitizerEventRange | kIOHIDDigitizerEventTouch | kIOHIDDigitizerEventIdentity;
624 fingerm = kIOHIDDigitizerEventRange | kIOHIDDigitizerEventTouch;
625 } else if (twas == 1 && tis == 1) {
626 handm = kIOHIDDigitizerEventPosition;
627 fingerm = kIOHIDDigitizerEventPosition;
628 } else if (twas == 1 && tis == 0) {
629 handm = kIOHIDDigitizerEventRange | kIOHIDDigitizerEventTouch | kIOHIDDigitizerEventIdentity | kIOHIDDigitizerEventPosition;
630 fingerm = kIOHIDDigitizerEventRange | kIOHIDDigitizerEventTouch;
633 // XXX: avoid division in VNCPointer()
643 IOHIDEventRef hand(IOHIDEventCreateDigitizerEvent(kCFAllocatorDefault, mach_absolute_time(), kIOHIDDigitizerTransducerTypeHand, 1<<22, 1, handm, 0, xf, yf, 0, 0, 0, 0, 0, 0));
644 IOHIDEventSetIntegerValue(hand, kIOHIDEventFieldIsBuiltIn, true);
645 IOHIDEventSetIntegerValue(hand, kIOHIDEventFieldDigitizerIsDisplayIntegrated, true);
647 IOHIDEventRef finger(IOHIDEventCreateDigitizerFingerEvent(kCFAllocatorDefault, mach_absolute_time(), 3, 2, fingerm, xf, yf, 0, 0, 0, tis, tis, 0));
648 IOHIDEventAppendEvent(hand, finger);
651 VNCSendHIDEvent(hand);
654 GSEventRef (*$GSEventCreateKeyEvent)(int, CGPoint, CFStringRef, CFStringRef, id, UniChar, short, short);
655 GSEventRef (*$GSCreateSyntheticKeyEvent)(UniChar, BOOL, BOOL);
657 static void VNCKeyboardNew(rfbBool down, rfbKeySym key, rfbClientPtr client) {
658 //NSLog(@"VNC d:%u k:%04x", down, key);
663 case XK_exclam: case XK_1: usage = kHIDUsage_Keyboard1; break;
664 case XK_at: case XK_2: usage = kHIDUsage_Keyboard2; break;
665 case XK_numbersign: case XK_3: usage = kHIDUsage_Keyboard3; break;
666 case XK_dollar: case XK_4: usage = kHIDUsage_Keyboard4; break;
667 case XK_percent: case XK_5: usage = kHIDUsage_Keyboard5; break;
668 case XK_asciicircum: case XK_6: usage = kHIDUsage_Keyboard6; break;
669 case XK_ampersand: case XK_7: usage = kHIDUsage_Keyboard7; break;
670 case XK_asterisk: case XK_8: usage = kHIDUsage_Keyboard8; break;
671 case XK_parenleft: case XK_9: usage = kHIDUsage_Keyboard9; break;
672 case XK_parenright: case XK_0: usage = kHIDUsage_Keyboard0; break;
674 case XK_A: case XK_a: usage = kHIDUsage_KeyboardA; break;
675 case XK_B: case XK_b: usage = kHIDUsage_KeyboardB; break;
676 case XK_C: case XK_c: usage = kHIDUsage_KeyboardC; break;
677 case XK_D: case XK_d: usage = kHIDUsage_KeyboardD; break;
678 case XK_E: case XK_e: usage = kHIDUsage_KeyboardE; break;
679 case XK_F: case XK_f: usage = kHIDUsage_KeyboardF; break;
680 case XK_G: case XK_g: usage = kHIDUsage_KeyboardG; break;
681 case XK_H: case XK_h: usage = kHIDUsage_KeyboardH; break;
682 case XK_I: case XK_i: usage = kHIDUsage_KeyboardI; break;
683 case XK_J: case XK_j: usage = kHIDUsage_KeyboardJ; break;
684 case XK_K: case XK_k: usage = kHIDUsage_KeyboardK; break;
685 case XK_L: case XK_l: usage = kHIDUsage_KeyboardL; break;
686 case XK_M: case XK_m: usage = kHIDUsage_KeyboardM; break;
687 case XK_N: case XK_n: usage = kHIDUsage_KeyboardN; break;
688 case XK_O: case XK_o: usage = kHIDUsage_KeyboardO; break;
689 case XK_P: case XK_p: usage = kHIDUsage_KeyboardP; break;
690 case XK_Q: case XK_q: usage = kHIDUsage_KeyboardQ; break;
691 case XK_R: case XK_r: usage = kHIDUsage_KeyboardR; break;
692 case XK_S: case XK_s: usage = kHIDUsage_KeyboardS; break;
693 case XK_T: case XK_t: usage = kHIDUsage_KeyboardT; break;
694 case XK_U: case XK_u: usage = kHIDUsage_KeyboardU; break;
695 case XK_V: case XK_v: usage = kHIDUsage_KeyboardV; break;
696 case XK_W: case XK_w: usage = kHIDUsage_KeyboardW; break;
697 case XK_X: case XK_x: usage = kHIDUsage_KeyboardX; break;
698 case XK_Y: case XK_y: usage = kHIDUsage_KeyboardY; break;
699 case XK_Z: case XK_z: usage = kHIDUsage_KeyboardZ; break;
701 case XK_underscore: case XK_minus: usage = kHIDUsage_KeyboardHyphen; break;
702 case XK_plus: case XK_equal: usage = kHIDUsage_KeyboardEqualSign; break;
703 case XK_braceleft: case XK_bracketleft: usage = kHIDUsage_KeyboardOpenBracket; break;
704 case XK_braceright: case XK_bracketright: usage = kHIDUsage_KeyboardCloseBracket; break;
705 case XK_bar: case XK_backslash: usage = kHIDUsage_KeyboardBackslash; break;
706 case XK_colon: case XK_semicolon: usage = kHIDUsage_KeyboardSemicolon; break;
707 case XK_quotedbl: case XK_apostrophe: usage = kHIDUsage_KeyboardQuote; break;
708 case XK_asciitilde: case XK_grave: usage = kHIDUsage_KeyboardGraveAccentAndTilde; break;
709 case XK_less: case XK_comma: usage = kHIDUsage_KeyboardComma; break;
710 case XK_greater: case XK_period: usage = kHIDUsage_KeyboardPeriod; break;
711 case XK_question: case XK_slash: usage = kHIDUsage_KeyboardSlash; break;
713 case XK_Return: usage = kHIDUsage_KeyboardReturnOrEnter; break;
714 case XK_BackSpace: usage = kHIDUsage_KeyboardDeleteOrBackspace; break;
715 case XK_Tab: usage = kHIDUsage_KeyboardTab; break;
716 case XK_space: usage = kHIDUsage_KeyboardSpacebar; break;
718 case XK_Shift_L: usage = kHIDUsage_KeyboardLeftShift; break;
719 case XK_Shift_R: usage = kHIDUsage_KeyboardRightShift; break;
720 case XK_Control_L: usage = kHIDUsage_KeyboardLeftControl; break;
721 case XK_Control_R: usage = kHIDUsage_KeyboardRightControl; break;
722 case XK_Meta_L: usage = kHIDUsage_KeyboardLeftAlt; break;
723 case XK_Meta_R: usage = kHIDUsage_KeyboardRightAlt; break;
724 case XK_Alt_L: usage = kHIDUsage_KeyboardLeftGUI; break;
725 case XK_Alt_R: usage = kHIDUsage_KeyboardRightGUI; break;
727 case XK_Up: usage = kHIDUsage_KeyboardUpArrow; break;
728 case XK_Down: usage = kHIDUsage_KeyboardDownArrow; break;
729 case XK_Left: usage = kHIDUsage_KeyboardLeftArrow; break;
730 case XK_Right: usage = kHIDUsage_KeyboardRightArrow; break;
732 case XK_Home: case XK_Begin: usage = kHIDUsage_KeyboardHome; break;
733 case XK_End: usage = kHIDUsage_KeyboardEnd; break;
734 case XK_Page_Up: usage = kHIDUsage_KeyboardPageUp; break;
735 case XK_Page_Down: usage = kHIDUsage_KeyboardPageDown; break;
740 VNCSendHIDEvent(IOHIDEventCreateKeyboardEvent(kCFAllocatorDefault, mach_absolute_time(), kHIDPage_KeyboardOrKeypad, usage, down, 0));
743 static void VNCKeyboard(rfbBool down, rfbKeySym key, rfbClientPtr client) {
744 if (kCFCoreFoundationVersionNumber >= 800)
745 return VNCKeyboardNew(down, key, client);
751 case XK_Return: key = '\r'; break;
752 case XK_BackSpace: key = 0x7f; break;
758 CGPoint point(CGPointMake(x_, y_));
760 UniChar unicode(key);
761 CFStringRef string(NULL);
763 GSEventRef event0, event1(NULL);
764 if ($GSEventCreateKeyEvent != NULL) {
765 string = CFStringCreateWithCharacters(kCFAllocatorDefault, &unicode, 1);
766 event0 = (*$GSEventCreateKeyEvent)(10, point, string, string, nil, 0, 0, 1);
767 event1 = (*$GSEventCreateKeyEvent)(11, point, string, string, nil, 0, 0, 1);
768 } else if ($GSCreateSyntheticKeyEvent != NULL) {
769 event0 = (*$GSCreateSyntheticKeyEvent)(unicode, YES, YES);
770 GSEventRecord *record(_GSEventGetGSEventRecord(event0));
771 record->type = GSEventTypeKeyDown;
776 if (CAWindowServer *server = [CAWindowServer serverIfRunning]) {
777 NSArray *displays([server displays]);
778 if (displays != nil && [displays count] != 0)
779 if (CAWindowServerDisplay *display = [displays objectAtIndex:0])
780 port = [display clientPortAtPosition:point];
783 mach_port_t purple(0);
787 purple = (*GSTakePurpleSystemEventPort)();
792 GSSendEvent(_GSEventGetGSEventRecord(event0), port);
794 GSSendEvent(_GSEventGetGSEventRecord(event1), port);
797 if (purple != 0 && PurpleAllocated)
798 mach_port_deallocate(mach_task_self(), purple);
807 static void VNCDisconnect(rfbClientPtr client) {
808 @synchronized (condition_) {
810 [VNCBridge performSelectorOnMainThread:@selector(removeStatusBarItem) withObject:nil waitUntilDone:YES];
814 static rfbNewClientAction VNCClient(rfbClientPtr client) {
815 @synchronized (condition_) {
816 if (screen_->authPasswdData != NULL) {
817 [VNCBridge performSelectorOnMainThread:@selector(registerClient) withObject:nil waitUntilDone:YES];
818 client->clientGoneHook = &VNCDisconnect;
819 return RFB_CLIENT_ACCEPT;
825 [VNCBridge performSelectorOnMainThread:@selector(askForConnection) withObject:nil waitUntilDone:NO];
826 while (action_ == RFB_CLIENT_ON_HOLD)
828 rfbNewClientAction action(action_);
829 action_ = RFB_CLIENT_ON_HOLD;
832 if (action == RFB_CLIENT_ACCEPT)
833 client->clientGoneHook = &VNCDisconnect;
837 extern "C" bool GSSystemHasCapability(NSString *);
839 static CFTypeRef (*$GSSystemCopyCapability)(CFStringRef);
840 static CFTypeRef (*$GSSystemGetCapability)(CFStringRef);
841 static BOOL (*$MGGetBoolAnswer)(CFStringRef);
843 static void VNCSetup() {
846 @synchronized (condition_) {
848 char *arg0(strdup("VNCServer"));
849 char *argv[] = {arg0, NULL};
850 screen_ = rfbGetScreen(&argc, argv, width_, height_, BitsPerSample, 3, BytesPerPixel);
856 screen_->desktopName = strdup([[[NSProcessInfo processInfo] hostName] UTF8String]);
858 screen_->alwaysShared = TRUE;
859 screen_->handleEventsEagerly = TRUE;
860 screen_->deferUpdateTime = 1000 / 25;
862 screen_->serverFormat.redShift = BitsPerSample * 2;
863 screen_->serverFormat.greenShift = BitsPerSample * 1;
864 screen_->serverFormat.blueShift = BitsPerSample * 0;
866 $GSSystemCopyCapability = reinterpret_cast<CFTypeRef (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, "GSSystemCopyCapability"));
867 $GSSystemGetCapability = reinterpret_cast<CFTypeRef (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, "GSSystemGetCapability"));
868 $MGGetBoolAnswer = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, "MGGetBoolAnswer"));
872 if ($GSSystemCopyCapability != NULL) {
873 opengles2 = (*$GSSystemCopyCapability)(CFSTR("opengles-2"));
874 } else if ($GSSystemGetCapability != NULL) {
875 opengles2 = (*$GSSystemGetCapability)(CFSTR("opengles-2"));
876 if (opengles2 != NULL)
878 } else if ($MGGetBoolAnswer != NULL) {
879 opengles2 = $MGGetBoolAnswer(CFSTR("opengles-2")) ? kCFBooleanTrue : kCFBooleanFalse;
884 bool accelerated(opengles2 != NULL && [(NSNumber *)opengles2 boolValue]);
887 CoreSurfaceAcceleratorCreate(NULL, NULL, &accelerator_);
889 if (opengles2 != NULL)
890 CFRelease(opengles2);
892 if (accelerator_ != NULL)
893 buffer_ = CoreSurfaceBufferCreate((CFDictionaryRef) [NSDictionary dictionaryWithObjectsAndKeys:
894 @"PurpleEDRAM", kCoreSurfaceBufferMemoryRegion,
895 [NSNumber numberWithBool:YES], kCoreSurfaceBufferGlobal,
896 [NSNumber numberWithInt:(width_ * BytesPerPixel)], kCoreSurfaceBufferPitch,
897 [NSNumber numberWithInt:width_], kCoreSurfaceBufferWidth,
898 [NSNumber numberWithInt:height_], kCoreSurfaceBufferHeight,
899 [NSNumber numberWithInt:'BGRA'], kCoreSurfaceBufferPixelFormat,
900 [NSNumber numberWithInt:(width_ * height_ * BytesPerPixel)], kCoreSurfaceBufferAllocSize,
905 //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));
907 CoreSurfaceBufferLock(buffer_, 3);
908 screen_->frameBuffer = reinterpret_cast<char *>(CoreSurfaceBufferGetBaseAddress(buffer_));
909 CoreSurfaceBufferUnlock(buffer_);
911 screen_->kbdAddEvent = &VNCKeyboard;
912 screen_->ptrAddEvent = &VNCPointer;
914 screen_->newClientHook = &VNCClient;
915 screen_->passwordCheck = &VNCCheck;
917 screen_->cursor = NULL;
920 static void VNCEnabled() {
927 bool enabled(CFPreferencesGetAppBooleanValue(CFSTR("Enabled"), CFSTR("com.saurik.Veency"), &valid));
931 if (enabled != running_)
934 screen_->socketState = RFB_SOCKET_INIT;
935 rfbInitServer(screen_);
936 rfbRunEventLoop(screen_, -1, true);
938 rfbShutdownServer(screen_, true);
945 static void VNCNotifyEnabled(
946 CFNotificationCenterRef center,
955 void (*$IOMobileFramebufferIsMainDisplay)(IOMobileFramebufferRef, int *);
957 static IOMobileFramebufferRef main_;
958 static CoreSurfaceBufferRef layer_;
960 static void OnLayer(IOMobileFramebufferRef fb, CoreSurfaceBufferRef layer) {
961 if (_unlikely(width_ == 0 || height_ == 0)) {
963 IOMobileFramebufferGetDisplaySize(fb, &size);
966 height_ = size.height;
968 if (width_ == 0 || height_ == 0)
971 NSThread *thread([NSThread alloc]);
974 initWithTarget:[VNCBridge class]
975 selector:@selector(performSetup:)
980 } else if (_unlikely(clients_ != 0)) {
982 if (accelerator_ != NULL)
983 memset(screen_->frameBuffer, 0, sizeof(rfbPixel) * width_ * height_);
987 if (accelerator_ != NULL)
988 CoreSurfaceAcceleratorTransferSurface(accelerator_, layer, buffer_, options_);
990 CoreSurfaceBufferLock(layer, 2);
991 rfbPixel *data(reinterpret_cast<rfbPixel *>(CoreSurfaceBufferGetBaseAddress(layer)));
993 CoreSurfaceBufferFlushProcessorCaches(layer);
995 /*rfbPixel corner(data[0]);
999 screen_->frameBuffer = const_cast<char *>(reinterpret_cast<volatile char *>(data));
1000 CoreSurfaceBufferUnlock(layer);
1004 rfbMarkRectAsModified(screen_, 0, 0, width_, height_);
1008 static bool wait_ = false;
1010 MSHook(kern_return_t, IOMobileFramebufferSwapSetLayer,
1011 IOMobileFramebufferRef fb,
1013 CoreSurfaceBufferRef buffer,
1020 if (_unlikely(buffer == NULL))
1022 else if (_unlikely(fb == NULL))
1024 else if ($IOMobileFramebufferIsMainDisplay == NULL)
1027 (*$IOMobileFramebufferIsMainDisplay)(fb, &main);
1029 if (_likely(main)) {
1034 OnLayer(fb, buffer);
1037 return _IOMobileFramebufferSwapSetLayer(fb, layer, buffer, bounds, frame, flags);
1040 // XXX: beg rpetrich for the type of this function
1041 extern "C" void *IOMobileFramebufferSwapWait(IOMobileFramebufferRef, void *, unsigned);
1043 MSHook(void *, IOMobileFramebufferSwapWait, IOMobileFramebufferRef fb, void *arg1, unsigned flags) {
1044 void *value(_IOMobileFramebufferSwapWait(fb, arg1, flags));
1046 OnLayer(fb, layer_);
1050 MSHook(void, rfbRegisterSecurityHandler, rfbSecurityHandler *handler) {
1051 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
1053 @synchronized (lock_) {
1054 [handlers_ addObject:[NSValue valueWithPointer:handler]];
1055 _rfbRegisterSecurityHandler(handler);
1061 template <typename Type_>
1062 static void dlset(Type_ &function, const char *name) {
1063 function = reinterpret_cast<Type_>(dlsym(RTLD_DEFAULT, name));
1067 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
1069 MSHookSymbol(GSTakePurpleSystemEventPort, "_GSGetPurpleSystemEventPort");
1070 if (GSTakePurpleSystemEventPort == NULL) {
1071 MSHookSymbol(GSTakePurpleSystemEventPort, "_GSCopyPurpleSystemEventPort");
1072 PurpleAllocated = true;
1075 if (dlsym(RTLD_DEFAULT, "GSLibraryCopyGenerationInfoValueForKey") != NULL)
1077 else if (dlsym(RTLD_DEFAULT, "GSKeyboardCreate") != NULL)
1079 else if (dlsym(RTLD_DEFAULT, "GSEventGetWindowContextId") != NULL)
1085 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
1087 sysctlbyname("hw.machine", machine, &size, NULL, 0);
1088 iPad1_ = strcmp(machine, "iPad1,1") == 0;
1090 dlset($GSMainScreenScaleFactor, "GSMainScreenScaleFactor");
1091 dlset($GSEventCreateKeyEvent, "GSEventCreateKeyEvent");
1092 dlset($GSCreateSyntheticKeyEvent, "_GSCreateSyntheticKeyEvent");
1093 dlset($IOMobileFramebufferIsMainDisplay, "IOMobileFramebufferIsMainDisplay");
1095 MSHookFunction(&IOMobileFramebufferSwapSetLayer, MSHake(IOMobileFramebufferSwapSetLayer));
1096 MSHookFunction(&rfbRegisterSecurityHandler, MSHake(rfbRegisterSecurityHandler));
1099 MSHookFunction(&IOMobileFramebufferSwapWait, MSHake(IOMobileFramebufferSwapWait));
1101 if ($SBAlertItem != nil) {
1102 $VNCAlertItem = objc_allocateClassPair($SBAlertItem, "VNCAlertItem", 0);
1103 MSAddMessage2(VNCAlertItem, "v@:@i", alertSheet,buttonClicked);
1104 MSAddMessage2(VNCAlertItem, "v@:cc", configure,requirePasscodeForActions);
1105 MSAddMessage0(VNCAlertItem, "v@:", performUnlockAction);
1106 objc_registerClassPair($VNCAlertItem);
1109 CFNotificationCenterAddObserver(
1110 CFNotificationCenterGetDarwinNotifyCenter(),
1111 NULL, &VNCNotifyEnabled, CFSTR("com.saurik.Veency-Enabled"), NULL, 0
1114 CFNotificationCenterAddObserver(
1115 CFNotificationCenterGetDarwinNotifyCenter(),
1116 NULL, &VNCNotifySettings, CFSTR("com.saurik.Veency-Settings"), NULL, 0
1119 condition_ = [[NSCondition alloc] init];
1120 lock_ = [[NSLock alloc] init];
1121 handlers_ = [[NSMutableSet alloc] init];
1126 cfTrue_ = CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&value), sizeof(value));
1129 cfFalse_ = CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&value), sizeof(value));
1131 cfEvent_ = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&event_), sizeof(event_), kCFAllocatorNull);
1133 options_ = (CFDictionaryRef) [[NSDictionary dictionaryWithObjectsAndKeys: