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 _unlikely(expr) \
41 __builtin_expect(expr, 0)
43 #include <substrate.h>
46 #include <rfb/keysym.h>
48 #include <mach/mach_port.h>
51 #import <QuartzCore/CAWindowServer.h>
52 #import <QuartzCore/CAWindowServerDisplay.h>
54 #import <CoreGraphics/CGGeometry.h>
55 #import <GraphicsServices/GraphicsServices.h>
56 #import <Foundation/Foundation.h>
57 #import <IOMobileFramebuffer/IOMobileFramebuffer.h>
58 #import <IOKit/IOKitLib.h>
59 #import <UIKit/UIKit.h>
61 #import <SpringBoard/SBAlertItemsController.h>
62 #import <SpringBoard/SBDismissOnlyAlertItem.h>
63 #import <SpringBoard/SBStatusBarController.h>
65 extern "C" void CoreSurfaceBufferFlushProcessorCaches(CoreSurfaceBufferRef buffer);
68 static size_t height_;
70 static const size_t BytesPerPixel = 4;
71 static const size_t BitsPerSample = 8;
73 static CoreSurfaceAcceleratorRef accelerator_;
74 static CoreSurfaceBufferRef buffer_;
75 static CFDictionaryRef options_;
77 static NSMutableSet *handlers_;
78 static rfbScreenInfoPtr screen_;
83 static unsigned clients_;
85 static CFMessagePortRef ashikase_;
88 static bool Ashikase(bool always) {
89 if (!always && !cursor_)
92 if (ashikase_ == NULL)
93 ashikase_ = CFMessagePortCreateRemote(kCFAllocatorDefault, CFSTR("jp.ashikase.mousesupport"));
94 if (ashikase_ != NULL)
101 static CFDataRef cfTrue_;
102 static CFDataRef cfFalse_;
110 static MouseEvent event_;
111 static CFDataRef cfEvent_;
114 MouseMessageTypeEvent,
115 MouseMessageTypeSetEnabled
118 static void AshikaseSendEvent(float x, float y, int buttons = 0) {
121 event_.buttons = buttons;
122 event_.absolute = true;
124 CFMessagePortSendRequest(ashikase_, MouseMessageTypeEvent, cfEvent_, 0, 0, NULL, NULL);
127 static void AshikaseSetEnabled(bool enabled, bool always) {
128 if (!Ashikase(always))
131 CFMessagePortSendRequest(ashikase_, MouseMessageTypeSetEnabled, enabled ? cfTrue_ : cfFalse_, 0, 0, NULL, NULL);
134 AshikaseSendEvent(x_, y_);
137 MSClassHook(SBAlertItemsController)
138 MSClassHook(SBStatusBarController)
141 static Class $VNCAlertItem;
143 static rfbNewClientAction action_ = RFB_CLIENT_ON_HOLD;
144 static NSCondition *condition_;
145 static NSLock *lock_;
147 static rfbClientPtr client_;
149 static void VNCSetup();
150 static void VNCEnabled();
152 @interface VNCBridge : NSObject {
155 + (void) askForConnection;
156 + (void) removeStatusBarItem;
157 + (void) registerClient;
161 @implementation VNCBridge
163 + (void) askForConnection {
164 [[$SBAlertItemsController sharedInstance] activateAlertItem:[[[$VNCAlertItem alloc] init] autorelease]];
167 + (void) removeStatusBarItem {
168 AshikaseSetEnabled(false, false);
169 [[$SBStatusBarController sharedStatusBarController] removeStatusBarItem:@"Veency"];
172 + (void) registerClient {
174 AshikaseSetEnabled(true, false);
175 [[$SBStatusBarController sharedStatusBarController] addStatusBarItem:@"Veency"];
178 + (void) performSetup {
179 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
187 MSInstanceMessage2(void, VNCAlertItem, alertSheet,buttonClicked, id, sheet, int, button) {
192 action_ = RFB_CLIENT_ACCEPT;
194 @synchronized (condition_) {
195 [VNCBridge registerClient];
200 action_ = RFB_CLIENT_REFUSE;
209 MSInstanceMessage2(void, VNCAlertItem, configure,requirePasscodeForActions, BOOL, configure, BOOL, require) {
210 UIModalView *sheet([self alertSheet]);
211 [sheet setDelegate:self];
212 [sheet setTitle:@"Remote Access Request"];
213 [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]];
214 [sheet addButtonWithTitle:@"Accept"];
215 [sheet addButtonWithTitle:@"Reject"];
218 MSInstanceMessage0(void, VNCAlertItem, performUnlockAction) {
219 [[$SBAlertItemsController sharedInstance] activateAlertItem:self];
222 static mach_port_t (*GSTakePurpleSystemEventPort)(void);
223 static bool PurpleAllocated;
226 static void FixRecord(GSEventRecord *record) {
228 memmove(&record->windowContextId, &record->windowContextId + 1, sizeof(*record) - (reinterpret_cast<uint8_t *>(&record->windowContextId + 1) - reinterpret_cast<uint8_t *>(record)) + record->size);
231 static void VNCSettings() {
232 NSDictionary *settings([NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/Library/Preferences/com.saurik.Veency.plist", NSHomeDirectory()]]);
234 @synchronized (lock_) {
235 for (NSValue *handler in handlers_)
236 rfbUnregisterSecurityHandler(reinterpret_cast<rfbSecurityHandler *>([handler pointerValue]));
237 [handlers_ removeAllObjects];
240 @synchronized (condition_) {
244 [reinterpret_cast<NSString *>(screen_->authPasswdData) release];
245 screen_->authPasswdData = NULL;
248 if (NSString *password = [settings objectForKey:@"Password"])
249 if ([password length] != 0)
250 screen_->authPasswdData = [password retain];
252 NSNumber *cursor = [settings objectForKey:@"ShowCursor"];
253 cursor_ = cursor == nil ? true : [cursor boolValue];
256 AshikaseSetEnabled(cursor_, true);
260 static void VNCNotifySettings(
261 CFNotificationCenterRef center,
270 static rfbBool VNCCheck(rfbClientPtr client, const char *data, int size) {
271 @synchronized (condition_) {
272 if (NSString *password = reinterpret_cast<NSString *>(screen_->authPasswdData)) {
273 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
274 rfbEncryptBytes(client->authChallenge, const_cast<char *>([password UTF8String]));
275 bool good(memcmp(client->authChallenge, data, size) == 0);
282 static void VNCPointer(int buttons, int x, int y, rfbClientPtr client) {
283 CGPoint location = {x, y};
292 int diff = buttons_ ^ buttons;
293 bool twas((buttons_ & 0x1) != 0);
294 bool tis((buttons & 0x1) != 0);
297 rfbDefaultPtrAddEvent(buttons, x, y, client);
299 if (Ashikase(false)) {
300 AshikaseSendEvent(x, y, buttons);
304 mach_port_t purple(0);
306 if ((diff & 0x10) != 0) {
307 struct GSEventRecord record;
309 memset(&record, 0, sizeof(record));
311 record.type = (buttons & 0x4) != 0 ?
312 GSEventTypeHeadsetButtonDown :
313 GSEventTypeHeadsetButtonUp;
315 record.timestamp = GSCurrentEventTimestamp();
318 GSSendSystemEvent(&record);
321 if ((diff & 0x04) != 0) {
322 struct GSEventRecord record;
324 memset(&record, 0, sizeof(record));
326 record.type = (buttons & 0x4) != 0 ?
327 GSEventTypeMenuButtonDown :
328 GSEventTypeMenuButtonUp;
330 record.timestamp = GSCurrentEventTimestamp();
333 GSSendSystemEvent(&record);
336 if ((diff & 0x02) != 0) {
337 struct GSEventRecord record;
339 memset(&record, 0, sizeof(record));
341 record.type = (buttons & 0x2) != 0 ?
342 GSEventTypeLockButtonDown :
343 GSEventTypeLockButtonUp;
345 record.timestamp = GSCurrentEventTimestamp();
348 GSSendSystemEvent(&record);
351 if (twas != tis || tis) {
353 struct GSEventRecord record;
355 struct GSEventRecordInfo info;
356 struct GSPathInfo path;
360 memset(&event, 0, sizeof(event));
362 event.record.type = GSEventTypeMouse;
363 event.record.locationInWindow.x = x;
364 event.record.locationInWindow.y = y;
365 event.record.timestamp = GSCurrentEventTimestamp();
366 event.record.size = sizeof(event.data);
368 event.data.info.handInfo.type = twas == tis ?
369 GSMouseEventTypeDragged :
371 GSMouseEventTypeDown :
374 event.data.info.handInfo.x34 = 0x1;
375 event.data.info.handInfo.x38 = tis ? 0x1 : 0x0;
377 event.data.info.pathPositions = 1;
379 event.data.path.x00 = 0x01;
380 event.data.path.x01 = 0x02;
381 event.data.path.x02 = tis ? 0x03 : 0x00;
382 event.data.path.position = event.record.locationInWindow;
386 if (CAWindowServer *server = [CAWindowServer serverIfRunning]) {
387 NSArray *displays([server displays]);
388 if (displays != nil && [displays count] != 0)
389 if (CAWindowServerDisplay *display = [displays objectAtIndex:0])
390 port = [display clientPortAtPosition:location];
395 purple = (*GSTakePurpleSystemEventPort)();
399 FixRecord(&event.record);
400 GSSendEvent(&event.record, port);
403 if (purple != 0 && PurpleAllocated)
404 mach_port_deallocate(mach_task_self(), purple);
407 GSEventRef (*$GSEventCreateKeyEvent)(int, CGPoint, CFStringRef, CFStringRef, id, UniChar, short, short);
408 GSEventRef (*$GSCreateSyntheticKeyEvent)(UniChar, BOOL, BOOL);
410 static void VNCKeyboard(rfbBool down, rfbKeySym key, rfbClientPtr client) {
415 case XK_Return: key = '\r'; break;
416 case XK_BackSpace: key = 0x7f; break;
422 CGPoint point(CGPointMake(x_, y_));
424 UniChar unicode(key);
425 CFStringRef string(NULL);
427 GSEventRef event0, event1(NULL);
428 if ($GSEventCreateKeyEvent != NULL) {
429 string = CFStringCreateWithCharacters(kCFAllocatorDefault, &unicode, 1);
430 event0 = (*$GSEventCreateKeyEvent)(10, point, string, string, nil, 0, 0, 1);
431 event1 = (*$GSEventCreateKeyEvent)(11, point, string, string, nil, 0, 0, 1);
432 } else if ($GSCreateSyntheticKeyEvent != NULL) {
433 event0 = (*$GSCreateSyntheticKeyEvent)(unicode, YES, YES);
434 GSEventRecord *record(_GSEventGetGSEventRecord(event0));
435 record->type = GSEventTypeKeyDown;
440 if (CAWindowServer *server = [CAWindowServer serverIfRunning]) {
441 NSArray *displays([server displays]);
442 if (displays != nil && [displays count] != 0)
443 if (CAWindowServerDisplay *display = [displays objectAtIndex:0])
444 port = [display clientPortAtPosition:point];
447 mach_port_t purple(0);
451 purple = (*GSTakePurpleSystemEventPort)();
456 GSSendEvent(_GSEventGetGSEventRecord(event0), port);
458 GSSendEvent(_GSEventGetGSEventRecord(event1), port);
461 if (purple != 0 && PurpleAllocated)
462 mach_port_deallocate(mach_task_self(), purple);
471 static void VNCDisconnect(rfbClientPtr client) {
472 @synchronized (condition_) {
474 [VNCBridge performSelectorOnMainThread:@selector(removeStatusBarItem) withObject:nil waitUntilDone:YES];
478 static rfbNewClientAction VNCClient(rfbClientPtr client) {
479 @synchronized (condition_) {
480 if (screen_->authPasswdData != NULL) {
481 [VNCBridge performSelectorOnMainThread:@selector(registerClient) withObject:nil waitUntilDone:YES];
482 client->clientGoneHook = &VNCDisconnect;
483 return RFB_CLIENT_ACCEPT;
489 [VNCBridge performSelectorOnMainThread:@selector(askForConnection) withObject:nil waitUntilDone:NO];
490 while (action_ == RFB_CLIENT_ON_HOLD)
492 rfbNewClientAction action(action_);
493 action_ = RFB_CLIENT_ON_HOLD;
496 if (action == RFB_CLIENT_ACCEPT)
497 client->clientGoneHook = &VNCDisconnect;
501 static void VNCSetup() {
504 @synchronized (condition_) {
506 char *arg0(strdup("VNCServer"));
507 char *argv[] = {arg0, NULL};
508 screen_ = rfbGetScreen(&argc, argv, width_, height_, BitsPerSample, 3, BytesPerPixel);
514 screen_->desktopName = strdup([[[NSProcessInfo processInfo] hostName] UTF8String]);
516 screen_->alwaysShared = TRUE;
517 screen_->handleEventsEagerly = TRUE;
518 screen_->deferUpdateTime = 1000 / 25;
520 screen_->serverFormat.redShift = BitsPerSample * 2;
521 screen_->serverFormat.greenShift = BitsPerSample * 1;
522 screen_->serverFormat.blueShift = BitsPerSample * 0;
524 buffer_ = CoreSurfaceBufferCreate((CFDictionaryRef) [NSDictionary dictionaryWithObjectsAndKeys:
525 @"PurpleEDRAM", kCoreSurfaceBufferMemoryRegion,
526 [NSNumber numberWithBool:YES], kCoreSurfaceBufferGlobal,
527 [NSNumber numberWithInt:(width_ * BytesPerPixel)], kCoreSurfaceBufferPitch,
528 [NSNumber numberWithInt:width_], kCoreSurfaceBufferWidth,
529 [NSNumber numberWithInt:height_], kCoreSurfaceBufferHeight,
530 [NSNumber numberWithInt:'BGRA'], kCoreSurfaceBufferPixelFormat,
531 [NSNumber numberWithInt:(width_ * height_ * BytesPerPixel)], kCoreSurfaceBufferAllocSize,
534 //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));
536 CoreSurfaceBufferLock(buffer_, 3);
537 screen_->frameBuffer = reinterpret_cast<char *>(CoreSurfaceBufferGetBaseAddress(buffer_));
538 CoreSurfaceBufferUnlock(buffer_);
540 screen_->kbdAddEvent = &VNCKeyboard;
541 screen_->ptrAddEvent = &VNCPointer;
543 screen_->newClientHook = &VNCClient;
544 screen_->passwordCheck = &VNCCheck;
546 screen_->cursor = NULL;
549 static void VNCEnabled() {
553 if (NSDictionary *settings = [NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/Library/Preferences/com.saurik.Veency.plist", NSHomeDirectory()]])
554 if (NSNumber *number = [settings objectForKey:@"Enabled"])
555 enabled = [number boolValue];
557 if (enabled != running_)
560 screen_->socketState = RFB_SOCKET_INIT;
561 rfbInitServer(screen_);
562 rfbRunEventLoop(screen_, -1, true);
564 rfbShutdownServer(screen_, true);
571 static void VNCNotifyEnabled(
572 CFNotificationCenterRef center,
581 MSHook(kern_return_t, IOMobileFramebufferSwapSetLayer,
582 IOMobileFramebufferRef fb,
584 CoreSurfaceBufferRef buffer,
589 if (_unlikely(width_ == 0 || height_ == 0)) {
591 IOMobileFramebufferGetDisplaySize(fb, &size);
594 height_ = size.height;
596 NSThread *thread([[[NSThread alloc]
597 initWithTarget:[VNCBridge class]
598 selector:@selector(performSetup)
603 } else if (_unlikely(clients_ != 0)) {
604 if (buffer == NULL) {
605 //CoreSurfaceBufferLock(buffer_, 3);
606 memset(screen_->frameBuffer, 0, sizeof(rfbPixel) * width_ * height_);
607 //CoreSurfaceBufferUnlock(buffer_);
609 //CoreSurfaceBufferLock(buffer_, 3);
610 //CoreSurfaceBufferLock(buffer, 2);
612 //rfbPixel *data(reinterpret_cast<rfbPixel *>(CoreSurfaceBufferGetBaseAddress(buffer)));
614 /*rfbPixel corner(data[0]);
618 CoreSurfaceAcceleratorTransferSurface(accelerator_, buffer, buffer_, options_);
620 //CoreSurfaceBufferUnlock(buffer);
621 //CoreSurfaceBufferUnlock(buffer_);
624 //CoreSurfaceBufferFlushProcessorCaches(buffer);
625 rfbMarkRectAsModified(screen_, 0, 0, width_, height_);
628 return _IOMobileFramebufferSwapSetLayer(fb, layer, buffer, bounds, frame, flags);
631 MSHook(void, rfbRegisterSecurityHandler, rfbSecurityHandler *handler) {
632 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
634 @synchronized (lock_) {
635 [handlers_ addObject:[NSValue valueWithPointer:handler]];
636 _rfbRegisterSecurityHandler(handler);
642 template <typename Type_>
643 static void dlset(Type_ &function, const char *name) {
644 function = reinterpret_cast<Type_>(dlsym(RTLD_DEFAULT, name));
648 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
650 MSHookSymbol(GSTakePurpleSystemEventPort, "GSGetPurpleSystemEventPort");
651 if (GSTakePurpleSystemEventPort == NULL) {
652 MSHookSymbol(GSTakePurpleSystemEventPort, "GSCopyPurpleSystemEventPort");
653 PurpleAllocated = true;
656 if (dlsym(RTLD_DEFAULT, "GSKeyboardCreate") != NULL)
658 else if (dlsym(RTLD_DEFAULT, "GSEventGetWindowContextId") != NULL)
663 dlset($GSEventCreateKeyEvent, "GSEventCreateKeyEvent");
664 dlset($GSCreateSyntheticKeyEvent, "_GSCreateSyntheticKeyEvent");
666 MSHookFunction(&IOMobileFramebufferSwapSetLayer, MSHake(IOMobileFramebufferSwapSetLayer));
667 MSHookFunction(&rfbRegisterSecurityHandler, MSHake(rfbRegisterSecurityHandler));
669 $VNCAlertItem = objc_allocateClassPair(objc_getClass("SBAlertItem"), "VNCAlertItem", 0);
670 MSAddMessage2(VNCAlertItem, "v@:@i", alertSheet,buttonClicked);
671 MSAddMessage2(VNCAlertItem, "v@:cc", configure,requirePasscodeForActions);
672 MSAddMessage0(VNCAlertItem, "v@:", performUnlockAction);
673 objc_registerClassPair($VNCAlertItem);
675 CFNotificationCenterAddObserver(
676 CFNotificationCenterGetDarwinNotifyCenter(),
677 NULL, &VNCNotifyEnabled, CFSTR("com.saurik.Veency-Enabled"), NULL, 0
680 CFNotificationCenterAddObserver(
681 CFNotificationCenterGetDarwinNotifyCenter(),
682 NULL, &VNCNotifySettings, CFSTR("com.saurik.Veency-Settings"), NULL, 0
685 condition_ = [[NSCondition alloc] init];
686 lock_ = [[NSLock alloc] init];
687 handlers_ = [[NSMutableSet alloc] init];
692 cfTrue_ = CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&value), sizeof(value));
695 cfFalse_ = CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&value), sizeof(value));
697 cfEvent_ = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&event_), sizeof(event_), kCFAllocatorNull);
699 CoreSurfaceAcceleratorCreate(NULL, NULL, &accelerator_);
701 options_ = (CFDictionaryRef) [[NSDictionary dictionaryWithObjectsAndKeys: