1 /* Veency - VNC Remote Access Server for iPhoneOS
2 * Copyright (C) 2008-2010 Jay Freeman (saurik)
6 * Redistribution and use in source and binary
7 * forms, with or without modification, are permitted
8 * provided that the following conditions are met:
10 * 1. Redistributions of source code must retain the
11 * above copyright notice, this list of conditions
12 * and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the
14 * above copyright notice, this list of conditions
15 * and the following disclaimer in the documentation
16 * and/or other materials provided with the
18 * 3. The name of the author may not be used to endorse
19 * or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
23 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
24 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
25 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
27 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
28 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
29 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
30 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
31 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
32 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
33 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
34 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
35 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39 fprintf(stderr, "_trace()@%s:%u[%s]\n", __FILE__, __LINE__, __FUNCTION__)
40 #define _likely(expr) \
41 __builtin_expect(expr, 1)
42 #define _unlikely(expr) \
43 __builtin_expect(expr, 0)
45 #include <CydiaSubstrate.h>
48 #include <rfb/keysym.h>
50 #include <mach/mach_port.h>
53 #import <QuartzCore/CAWindowServer.h>
54 #import <QuartzCore/CAWindowServerDisplay.h>
56 #import <CoreGraphics/CGGeometry.h>
57 #import <GraphicsServices/GraphicsServices.h>
58 #import <Foundation/Foundation.h>
59 #import <IOMobileFramebuffer/IOMobileFramebuffer.h>
60 #import <IOKit/IOKitLib.h>
61 #import <UIKit/UIKit.h>
63 #import <SpringBoard/SBAlertItemsController.h>
64 #import <SpringBoard/SBDismissOnlyAlertItem.h>
65 #import <SpringBoard/SBStatusBarController.h>
67 extern "C" void CoreSurfaceBufferFlushProcessorCaches(CoreSurfaceBufferRef buffer);
70 static size_t height_;
71 static NSUInteger ratio_ = 0;
73 static const size_t BytesPerPixel = 4;
74 static const size_t BitsPerSample = 8;
76 static CoreSurfaceAcceleratorRef accelerator_;
77 static CoreSurfaceBufferRef buffer_;
78 static CFDictionaryRef options_;
80 static NSMutableSet *handlers_;
81 static rfbScreenInfoPtr screen_;
86 static unsigned clients_;
88 static CFMessagePortRef ashikase_;
91 static bool Ashikase(bool always) {
92 if (!always && !cursor_)
95 if (ashikase_ == NULL)
96 ashikase_ = CFMessagePortCreateRemote(kCFAllocatorDefault, CFSTR("jp.ashikase.mousesupport"));
97 if (ashikase_ != NULL)
104 static CFDataRef cfTrue_;
105 static CFDataRef cfFalse_;
113 static MouseEvent event_;
114 static CFDataRef cfEvent_;
117 MouseMessageTypeEvent,
118 MouseMessageTypeSetEnabled
121 static void AshikaseSendEvent(float x, float y, int buttons = 0) {
124 event_.buttons = buttons;
125 event_.absolute = true;
127 CFMessagePortSendRequest(ashikase_, MouseMessageTypeEvent, cfEvent_, 0, 0, NULL, NULL);
130 static void AshikaseSetEnabled(bool enabled, bool always) {
131 if (!Ashikase(always))
134 CFMessagePortSendRequest(ashikase_, MouseMessageTypeSetEnabled, enabled ? cfTrue_ : cfFalse_, 0, 0, NULL, NULL);
137 AshikaseSendEvent(x_, y_);
140 MSClassHook(SBAlertItemsController)
141 MSClassHook(SBStatusBarController)
144 static Class $VNCAlertItem;
146 static rfbNewClientAction action_ = RFB_CLIENT_ON_HOLD;
147 static NSCondition *condition_;
148 static NSLock *lock_;
150 static rfbClientPtr client_;
152 static void VNCSetup();
153 static void VNCEnabled();
155 @interface VNCBridge : NSObject {
158 + (void) askForConnection;
159 + (void) removeStatusBarItem;
160 + (void) registerClient;
164 @implementation VNCBridge
166 + (void) askForConnection {
167 [[$SBAlertItemsController sharedInstance] activateAlertItem:[[[$VNCAlertItem alloc] init] autorelease]];
170 + (void) removeStatusBarItem {
171 AshikaseSetEnabled(false, false);
172 [[$SBStatusBarController sharedStatusBarController] removeStatusBarItem:@"Veency"];
175 + (void) registerClient {
176 // XXX: this could find a better home
178 UIScreen *screen([UIScreen mainScreen]);
179 if ([screen respondsToSelector:@selector(scale)])
180 ratio_ = [screen scale];
186 AshikaseSetEnabled(true, false);
187 [[$SBStatusBarController sharedStatusBarController] addStatusBarItem:@"Veency"];
190 + (void) performSetup:(NSThread *)thread {
191 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
192 [thread autorelease];
200 MSInstanceMessage2(void, VNCAlertItem, alertSheet,buttonClicked, id, sheet, int, button) {
205 action_ = RFB_CLIENT_ACCEPT;
207 @synchronized (condition_) {
208 [VNCBridge registerClient];
213 action_ = RFB_CLIENT_REFUSE;
222 MSInstanceMessage2(void, VNCAlertItem, configure,requirePasscodeForActions, BOOL, configure, BOOL, require) {
223 UIModalView *sheet([self alertSheet]);
224 [sheet setDelegate:self];
225 [sheet setTitle:@"Remote Access Request"];
226 [sheet setBodyText:[NSString stringWithFormat:@"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!", client_->host]];
227 [sheet addButtonWithTitle:@"Accept"];
228 [sheet addButtonWithTitle:@"Reject"];
231 MSInstanceMessage0(void, VNCAlertItem, performUnlockAction) {
232 [[$SBAlertItemsController sharedInstance] activateAlertItem:self];
235 static mach_port_t (*GSTakePurpleSystemEventPort)(void);
236 static bool PurpleAllocated;
239 static void FixRecord(GSEventRecord *record) {
241 memmove(&record->windowContextId, &record->windowContextId + 1, sizeof(*record) - (reinterpret_cast<uint8_t *>(&record->windowContextId + 1) - reinterpret_cast<uint8_t *>(record)) + record->size);
244 static void VNCSettings() {
245 NSDictionary *settings([NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/Library/Preferences/com.saurik.Veency.plist", NSHomeDirectory()]]);
247 @synchronized (lock_) {
248 for (NSValue *handler in handlers_)
249 rfbUnregisterSecurityHandler(reinterpret_cast<rfbSecurityHandler *>([handler pointerValue]));
250 [handlers_ removeAllObjects];
253 @synchronized (condition_) {
257 [reinterpret_cast<NSString *>(screen_->authPasswdData) release];
258 screen_->authPasswdData = NULL;
261 if (NSString *password = [settings objectForKey:@"Password"])
262 if ([password length] != 0)
263 screen_->authPasswdData = [password retain];
265 NSNumber *cursor = [settings objectForKey:@"ShowCursor"];
266 cursor_ = cursor == nil ? true : [cursor boolValue];
269 AshikaseSetEnabled(cursor_, true);
273 static void VNCNotifySettings(
274 CFNotificationCenterRef center,
283 static rfbBool VNCCheck(rfbClientPtr client, const char *data, int size) {
284 @synchronized (condition_) {
285 if (NSString *password = reinterpret_cast<NSString *>(screen_->authPasswdData)) {
286 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
287 rfbEncryptBytes(client->authChallenge, const_cast<char *>([password UTF8String]));
288 bool good(memcmp(client->authChallenge, data, size) == 0);
295 static void VNCPointer(int buttons, int x, int y, rfbClientPtr client) {
301 CGPoint location = {x, y};
303 if (width_ > height_) {
305 x = height_ / ratio_ - 1 - y;
310 int diff = buttons_ ^ buttons;
311 bool twas((buttons_ & 0x1) != 0);
312 bool tis((buttons & 0x1) != 0);
315 rfbDefaultPtrAddEvent(buttons, x, y, client);
317 if (Ashikase(false)) {
318 AshikaseSendEvent(x, y, buttons);
322 mach_port_t purple(0);
324 if ((diff & 0x10) != 0) {
325 struct GSEventRecord record;
327 memset(&record, 0, sizeof(record));
329 record.type = (buttons & 0x4) != 0 ?
330 GSEventTypeHeadsetButtonDown :
331 GSEventTypeHeadsetButtonUp;
333 record.timestamp = GSCurrentEventTimestamp();
336 GSSendSystemEvent(&record);
339 if ((diff & 0x04) != 0) {
340 struct GSEventRecord record;
342 memset(&record, 0, sizeof(record));
344 record.type = (buttons & 0x4) != 0 ?
345 GSEventTypeMenuButtonDown :
346 GSEventTypeMenuButtonUp;
348 record.timestamp = GSCurrentEventTimestamp();
351 GSSendSystemEvent(&record);
354 if ((diff & 0x02) != 0) {
355 struct GSEventRecord record;
357 memset(&record, 0, sizeof(record));
359 record.type = (buttons & 0x2) != 0 ?
360 GSEventTypeLockButtonDown :
361 GSEventTypeLockButtonUp;
363 record.timestamp = GSCurrentEventTimestamp();
366 GSSendSystemEvent(&record);
369 if (twas != tis || tis) {
371 struct GSEventRecord record;
373 struct GSEventRecordInfo info;
374 struct GSPathInfo path;
378 memset(&event, 0, sizeof(event));
380 event.record.type = GSEventTypeMouse;
381 event.record.locationInWindow.x = x;
382 event.record.locationInWindow.y = y;
383 event.record.timestamp = GSCurrentEventTimestamp();
384 event.record.size = sizeof(event.data);
386 event.data.info.handInfo.type = twas == tis ?
387 GSMouseEventTypeDragged :
389 GSMouseEventTypeDown :
392 event.data.info.handInfo.x34 = 0x1;
393 event.data.info.handInfo.x38 = tis ? 0x1 : 0x0;
395 event.data.info.pathPositions = 1;
397 event.data.path.x00 = 0x01;
398 event.data.path.x01 = 0x02;
399 event.data.path.x02 = tis ? 0x03 : 0x00;
400 event.data.path.position = event.record.locationInWindow;
404 if (CAWindowServer *server = [CAWindowServer serverIfRunning]) {
405 NSArray *displays([server displays]);
406 if (displays != nil && [displays count] != 0)
407 if (CAWindowServerDisplay *display = [displays objectAtIndex:0])
408 port = [display clientPortAtPosition:location];
413 purple = (*GSTakePurpleSystemEventPort)();
417 FixRecord(&event.record);
418 GSSendEvent(&event.record, port);
421 if (purple != 0 && PurpleAllocated)
422 mach_port_deallocate(mach_task_self(), purple);
425 GSEventRef (*$GSEventCreateKeyEvent)(int, CGPoint, CFStringRef, CFStringRef, id, UniChar, short, short);
426 GSEventRef (*$GSCreateSyntheticKeyEvent)(UniChar, BOOL, BOOL);
428 static void VNCKeyboard(rfbBool down, rfbKeySym key, rfbClientPtr client) {
433 case XK_Return: key = '\r'; break;
434 case XK_BackSpace: key = 0x7f; break;
440 CGPoint point(CGPointMake(x_, y_));
442 UniChar unicode(key);
443 CFStringRef string(NULL);
445 GSEventRef event0, event1(NULL);
446 if ($GSEventCreateKeyEvent != NULL) {
447 string = CFStringCreateWithCharacters(kCFAllocatorDefault, &unicode, 1);
448 event0 = (*$GSEventCreateKeyEvent)(10, point, string, string, nil, 0, 0, 1);
449 event1 = (*$GSEventCreateKeyEvent)(11, point, string, string, nil, 0, 0, 1);
450 } else if ($GSCreateSyntheticKeyEvent != NULL) {
451 event0 = (*$GSCreateSyntheticKeyEvent)(unicode, YES, YES);
452 GSEventRecord *record(_GSEventGetGSEventRecord(event0));
453 record->type = GSEventTypeKeyDown;
458 if (CAWindowServer *server = [CAWindowServer serverIfRunning]) {
459 NSArray *displays([server displays]);
460 if (displays != nil && [displays count] != 0)
461 if (CAWindowServerDisplay *display = [displays objectAtIndex:0])
462 port = [display clientPortAtPosition:point];
465 mach_port_t purple(0);
469 purple = (*GSTakePurpleSystemEventPort)();
474 GSSendEvent(_GSEventGetGSEventRecord(event0), port);
476 GSSendEvent(_GSEventGetGSEventRecord(event1), port);
479 if (purple != 0 && PurpleAllocated)
480 mach_port_deallocate(mach_task_self(), purple);
489 static void VNCDisconnect(rfbClientPtr client) {
490 @synchronized (condition_) {
492 [VNCBridge performSelectorOnMainThread:@selector(removeStatusBarItem) withObject:nil waitUntilDone:YES];
496 static rfbNewClientAction VNCClient(rfbClientPtr client) {
497 @synchronized (condition_) {
498 if (screen_->authPasswdData != NULL) {
499 [VNCBridge performSelectorOnMainThread:@selector(registerClient) withObject:nil waitUntilDone:YES];
500 client->clientGoneHook = &VNCDisconnect;
501 return RFB_CLIENT_ACCEPT;
507 [VNCBridge performSelectorOnMainThread:@selector(askForConnection) withObject:nil waitUntilDone:NO];
508 while (action_ == RFB_CLIENT_ON_HOLD)
510 rfbNewClientAction action(action_);
511 action_ = RFB_CLIENT_ON_HOLD;
514 if (action == RFB_CLIENT_ACCEPT)
515 client->clientGoneHook = &VNCDisconnect;
519 static void VNCSetup() {
522 @synchronized (condition_) {
524 char *arg0(strdup("VNCServer"));
525 char *argv[] = {arg0, NULL};
526 screen_ = rfbGetScreen(&argc, argv, width_, height_, BitsPerSample, 3, BytesPerPixel);
532 screen_->desktopName = strdup([[[NSProcessInfo processInfo] hostName] UTF8String]);
534 screen_->alwaysShared = TRUE;
535 screen_->handleEventsEagerly = TRUE;
536 screen_->deferUpdateTime = 1000 / 25;
538 screen_->serverFormat.redShift = BitsPerSample * 2;
539 screen_->serverFormat.greenShift = BitsPerSample * 1;
540 screen_->serverFormat.blueShift = BitsPerSample * 0;
542 buffer_ = CoreSurfaceBufferCreate((CFDictionaryRef) [NSDictionary dictionaryWithObjectsAndKeys:
543 @"PurpleEDRAM", kCoreSurfaceBufferMemoryRegion,
544 [NSNumber numberWithBool:YES], kCoreSurfaceBufferGlobal,
545 [NSNumber numberWithInt:(width_ * BytesPerPixel)], kCoreSurfaceBufferPitch,
546 [NSNumber numberWithInt:width_], kCoreSurfaceBufferWidth,
547 [NSNumber numberWithInt:height_], kCoreSurfaceBufferHeight,
548 [NSNumber numberWithInt:'BGRA'], kCoreSurfaceBufferPixelFormat,
549 [NSNumber numberWithInt:(width_ * height_ * BytesPerPixel)], kCoreSurfaceBufferAllocSize,
552 //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));
554 CoreSurfaceBufferLock(buffer_, 3);
555 screen_->frameBuffer = reinterpret_cast<char *>(CoreSurfaceBufferGetBaseAddress(buffer_));
556 CoreSurfaceBufferUnlock(buffer_);
558 screen_->kbdAddEvent = &VNCKeyboard;
559 screen_->ptrAddEvent = &VNCPointer;
561 screen_->newClientHook = &VNCClient;
562 screen_->passwordCheck = &VNCCheck;
564 screen_->cursor = NULL;
567 static void VNCEnabled() {
571 if (NSDictionary *settings = [NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/Library/Preferences/com.saurik.Veency.plist", NSHomeDirectory()]])
572 if (NSNumber *number = [settings objectForKey:@"Enabled"])
573 enabled = [number boolValue];
575 if (enabled != running_)
578 screen_->socketState = RFB_SOCKET_INIT;
579 rfbInitServer(screen_);
580 rfbRunEventLoop(screen_, -1, true);
582 rfbShutdownServer(screen_, true);
589 static void VNCNotifyEnabled(
590 CFNotificationCenterRef center,
599 void (*$IOMobileFramebufferIsMainDisplay)(IOMobileFramebufferRef, bool *);
601 static IOMobileFramebufferRef main_;
603 MSHook(kern_return_t, IOMobileFramebufferSwapSetLayer,
604 IOMobileFramebufferRef fb,
606 CoreSurfaceBufferRef buffer,
613 if (_unlikely(buffer == NULL))
615 else if (_unlikely(fb == NULL))
617 else if ($IOMobileFramebufferIsMainDisplay == NULL)
620 (*$IOMobileFramebufferIsMainDisplay)(fb, &main);
626 if (_unlikely(width_ == 0 || height_ == 0)) {
628 IOMobileFramebufferGetDisplaySize(fb, &size);
631 height_ = size.height;
633 if (width_ == 0 || height_ == 0)
636 NSThread *thread([NSThread alloc]);
639 initWithTarget:[VNCBridge class]
640 selector:@selector(performSetup:)
645 } else if (_unlikely(clients_ != 0)) {
646 if (buffer == NULL) {
647 //CoreSurfaceBufferLock(buffer_, 3);
648 memset(screen_->frameBuffer, 0, sizeof(rfbPixel) * width_ * height_);
649 //CoreSurfaceBufferUnlock(buffer_);
651 //CoreSurfaceBufferLock(buffer_, 3);
652 //CoreSurfaceBufferLock(buffer, 2);
654 //rfbPixel *data(reinterpret_cast<rfbPixel *>(CoreSurfaceBufferGetBaseAddress(buffer)));
656 /*rfbPixel corner(data[0]);
660 CoreSurfaceAcceleratorTransferSurface(accelerator_, buffer, buffer_, options_);
662 //CoreSurfaceBufferUnlock(buffer);
663 //CoreSurfaceBufferUnlock(buffer_);
666 //CoreSurfaceBufferFlushProcessorCaches(buffer);
667 rfbMarkRectAsModified(screen_, 0, 0, width_, height_);
671 return _IOMobileFramebufferSwapSetLayer(fb, layer, buffer, bounds, frame, flags);
674 MSHook(void, rfbRegisterSecurityHandler, rfbSecurityHandler *handler) {
675 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
677 @synchronized (lock_) {
678 [handlers_ addObject:[NSValue valueWithPointer:handler]];
679 _rfbRegisterSecurityHandler(handler);
685 template <typename Type_>
686 static void dlset(Type_ &function, const char *name) {
687 function = reinterpret_cast<Type_>(dlsym(RTLD_DEFAULT, name));
691 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
693 MSHookSymbol(GSTakePurpleSystemEventPort, "GSGetPurpleSystemEventPort");
694 if (GSTakePurpleSystemEventPort == NULL) {
695 MSHookSymbol(GSTakePurpleSystemEventPort, "GSCopyPurpleSystemEventPort");
696 PurpleAllocated = true;
699 if (dlsym(RTLD_DEFAULT, "GSKeyboardCreate") != NULL)
701 else if (dlsym(RTLD_DEFAULT, "GSEventGetWindowContextId") != NULL)
706 dlset($GSEventCreateKeyEvent, "GSEventCreateKeyEvent");
707 dlset($GSCreateSyntheticKeyEvent, "_GSCreateSyntheticKeyEvent");
708 dlset($IOMobileFramebufferIsMainDisplay, "IOMobileFramebufferIsMainDisplay");
710 MSHookFunction(&IOMobileFramebufferSwapSetLayer, MSHake(IOMobileFramebufferSwapSetLayer));
711 MSHookFunction(&rfbRegisterSecurityHandler, MSHake(rfbRegisterSecurityHandler));
713 $VNCAlertItem = objc_allocateClassPair(objc_getClass("SBAlertItem"), "VNCAlertItem", 0);
714 MSAddMessage2(VNCAlertItem, "v@:@i", alertSheet,buttonClicked);
715 MSAddMessage2(VNCAlertItem, "v@:cc", configure,requirePasscodeForActions);
716 MSAddMessage0(VNCAlertItem, "v@:", performUnlockAction);
717 objc_registerClassPair($VNCAlertItem);
719 CFNotificationCenterAddObserver(
720 CFNotificationCenterGetDarwinNotifyCenter(),
721 NULL, &VNCNotifyEnabled, CFSTR("com.saurik.Veency-Enabled"), NULL, 0
724 CFNotificationCenterAddObserver(
725 CFNotificationCenterGetDarwinNotifyCenter(),
726 NULL, &VNCNotifySettings, CFSTR("com.saurik.Veency-Settings"), NULL, 0
729 condition_ = [[NSCondition alloc] init];
730 lock_ = [[NSLock alloc] init];
731 handlers_ = [[NSMutableSet alloc] init];
736 cfTrue_ = CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&value), sizeof(value));
739 cfFalse_ = CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&value), sizeof(value));
741 cfEvent_ = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&event_), sizeof(event_), kCFAllocatorNull);
743 CoreSurfaceAcceleratorCreate(NULL, NULL, &accelerator_);
745 options_ = (CFDictionaryRef) [[NSDictionary dictionaryWithObjectsAndKeys: