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 @interface VNCBridge : NSObject {
152 + (void) askForConnection;
153 + (void) removeStatusBarItem;
154 + (void) registerClient;
158 @implementation VNCBridge
160 + (void) askForConnection {
161 [[$SBAlertItemsController sharedInstance] activateAlertItem:[[[$VNCAlertItem alloc] init] autorelease]];
164 + (void) removeStatusBarItem {
165 AshikaseSetEnabled(false, false);
166 [[$SBStatusBarController sharedStatusBarController] removeStatusBarItem:@"Veency"];
169 + (void) registerClient {
171 AshikaseSetEnabled(true, false);
172 [[$SBStatusBarController sharedStatusBarController] addStatusBarItem:@"Veency"];
177 MSInstanceMessage2(void, VNCAlertItem, alertSheet,buttonClicked, id, sheet, int, button) {
182 action_ = RFB_CLIENT_ACCEPT;
184 @synchronized (condition_) {
185 [VNCBridge registerClient];
190 action_ = RFB_CLIENT_REFUSE;
199 MSInstanceMessage2(void, VNCAlertItem, configure,requirePasscodeForActions, BOOL, configure, BOOL, require) {
200 UIModalView *sheet([self alertSheet]);
201 [sheet setDelegate:self];
202 [sheet setTitle:@"Remote Access Request"];
203 [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]];
204 [sheet addButtonWithTitle:@"Accept"];
205 [sheet addButtonWithTitle:@"Reject"];
208 MSInstanceMessage0(void, VNCAlertItem, performUnlockAction) {
209 [[$SBAlertItemsController sharedInstance] activateAlertItem:self];
212 static mach_port_t (*GSTakePurpleSystemEventPort)(void);
213 static bool PurpleAllocated;
216 static void FixRecord(GSEventRecord *record) {
218 memmove(&record->windowContextId, &record->windowContextId + 1, sizeof(*record) - (reinterpret_cast<uint8_t *>(&record->windowContextId + 1) - reinterpret_cast<uint8_t *>(record)) + record->size);
221 static void VNCSettings() {
222 NSDictionary *settings([NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/Library/Preferences/com.saurik.Veency.plist", NSHomeDirectory()]]);
224 @synchronized (lock_) {
225 for (NSValue *handler in handlers_)
226 rfbUnregisterSecurityHandler(reinterpret_cast<rfbSecurityHandler *>([handler pointerValue]));
227 [handlers_ removeAllObjects];
230 @synchronized (condition_) {
234 [reinterpret_cast<NSString *>(screen_->authPasswdData) release];
235 screen_->authPasswdData = NULL;
238 if (NSString *password = [settings objectForKey:@"Password"])
239 if ([password length] != 0)
240 screen_->authPasswdData = [password retain];
242 NSNumber *cursor = [settings objectForKey:@"ShowCursor"];
243 cursor_ = cursor == nil ? true : [cursor boolValue];
246 AshikaseSetEnabled(cursor_, true);
250 static void VNCNotifySettings(
251 CFNotificationCenterRef center,
260 static rfbBool VNCCheck(rfbClientPtr client, const char *data, int size) {
261 @synchronized (condition_) {
262 if (NSString *password = reinterpret_cast<NSString *>(screen_->authPasswdData)) {
263 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
264 rfbEncryptBytes(client->authChallenge, const_cast<char *>([password UTF8String]));
265 bool good(memcmp(client->authChallenge, data, size) == 0);
272 static void VNCPointer(int buttons, int x, int y, rfbClientPtr client) {
273 CGPoint location = {x, y};
282 int diff = buttons_ ^ buttons;
283 bool twas((buttons_ & 0x1) != 0);
284 bool tis((buttons & 0x1) != 0);
287 rfbDefaultPtrAddEvent(buttons, x, y, client);
289 if (Ashikase(false)) {
290 AshikaseSendEvent(x, y, buttons);
294 mach_port_t purple(0);
296 if ((diff & 0x10) != 0) {
297 struct GSEventRecord record;
299 memset(&record, 0, sizeof(record));
301 record.type = (buttons & 0x4) != 0 ?
302 GSEventTypeHeadsetButtonDown :
303 GSEventTypeHeadsetButtonUp;
305 record.timestamp = GSCurrentEventTimestamp();
308 GSSendSystemEvent(&record);
311 if ((diff & 0x04) != 0) {
312 struct GSEventRecord record;
314 memset(&record, 0, sizeof(record));
316 record.type = (buttons & 0x4) != 0 ?
317 GSEventTypeMenuButtonDown :
318 GSEventTypeMenuButtonUp;
320 record.timestamp = GSCurrentEventTimestamp();
323 GSSendSystemEvent(&record);
326 if ((diff & 0x02) != 0) {
327 struct GSEventRecord record;
329 memset(&record, 0, sizeof(record));
331 record.type = (buttons & 0x2) != 0 ?
332 GSEventTypeLockButtonDown :
333 GSEventTypeLockButtonUp;
335 record.timestamp = GSCurrentEventTimestamp();
338 GSSendSystemEvent(&record);
341 if (twas != tis || tis) {
343 struct GSEventRecord record;
345 struct GSEventRecordInfo info;
346 struct GSPathInfo path;
350 memset(&event, 0, sizeof(event));
352 event.record.type = GSEventTypeMouse;
353 event.record.locationInWindow.x = x;
354 event.record.locationInWindow.y = y;
355 event.record.timestamp = GSCurrentEventTimestamp();
356 event.record.size = sizeof(event.data);
358 event.data.info.handInfo.type = twas == tis ?
359 GSMouseEventTypeDragged :
361 GSMouseEventTypeDown :
364 event.data.info.handInfo.x34 = 0x1;
365 event.data.info.handInfo.x38 = tis ? 0x1 : 0x0;
367 event.data.info.pathPositions = 1;
369 event.data.path.x00 = 0x01;
370 event.data.path.x01 = 0x02;
371 event.data.path.x02 = tis ? 0x03 : 0x00;
372 event.data.path.position = event.record.locationInWindow;
376 if (CAWindowServer *server = [CAWindowServer serverIfRunning]) {
377 NSArray *displays([server displays]);
378 if (displays != nil && [displays count] != 0)
379 if (CAWindowServerDisplay *display = [displays objectAtIndex:0])
380 port = [display clientPortAtPosition:location];
385 purple = (*GSTakePurpleSystemEventPort)();
389 FixRecord(&event.record);
390 GSSendEvent(&event.record, port);
393 if (purple != 0 && PurpleAllocated)
394 mach_port_deallocate(mach_task_self(), purple);
397 GSEventRef (*$GSEventCreateKeyEvent)(int, CGPoint, CFStringRef, CFStringRef, id, UniChar, short, short);
398 GSEventRef (*$GSCreateSyntheticKeyEvent)(UniChar, BOOL, BOOL);
400 static void VNCKeyboard(rfbBool down, rfbKeySym key, rfbClientPtr client) {
405 case XK_Return: key = '\r'; break;
406 case XK_BackSpace: key = 0x7f; break;
412 CGPoint point(CGPointMake(x_, y_));
414 UniChar unicode(key);
415 CFStringRef string(NULL);
417 GSEventRef event0, event1(NULL);
418 if ($GSEventCreateKeyEvent != NULL) {
419 string = CFStringCreateWithCharacters(kCFAllocatorDefault, &unicode, 1);
420 event0 = (*$GSEventCreateKeyEvent)(10, point, string, string, nil, 0, 0, 1);
421 event1 = (*$GSEventCreateKeyEvent)(11, point, string, string, nil, 0, 0, 1);
422 } else if ($GSCreateSyntheticKeyEvent != NULL) {
423 event0 = (*$GSCreateSyntheticKeyEvent)(unicode, YES, YES);
424 GSEventRecord *record(_GSEventGetGSEventRecord(event0));
425 record->type = GSEventTypeKeyDown;
430 if (CAWindowServer *server = [CAWindowServer serverIfRunning]) {
431 NSArray *displays([server displays]);
432 if (displays != nil && [displays count] != 0)
433 if (CAWindowServerDisplay *display = [displays objectAtIndex:0])
434 port = [display clientPortAtPosition:point];
437 mach_port_t purple(0);
441 purple = (*GSTakePurpleSystemEventPort)();
446 GSSendEvent(_GSEventGetGSEventRecord(event0), port);
448 GSSendEvent(_GSEventGetGSEventRecord(event1), port);
451 if (purple != 0 && PurpleAllocated)
452 mach_port_deallocate(mach_task_self(), purple);
461 static void VNCDisconnect(rfbClientPtr client) {
462 @synchronized (condition_) {
464 [VNCBridge performSelectorOnMainThread:@selector(removeStatusBarItem) withObject:nil waitUntilDone:YES];
468 static rfbNewClientAction VNCClient(rfbClientPtr client) {
469 @synchronized (condition_) {
470 if (screen_->authPasswdData != NULL) {
471 [VNCBridge performSelectorOnMainThread:@selector(registerClient) withObject:nil waitUntilDone:YES];
472 client->clientGoneHook = &VNCDisconnect;
473 return RFB_CLIENT_ACCEPT;
479 [VNCBridge performSelectorOnMainThread:@selector(askForConnection) withObject:nil waitUntilDone:NO];
480 while (action_ == RFB_CLIENT_ON_HOLD)
482 rfbNewClientAction action(action_);
483 action_ = RFB_CLIENT_ON_HOLD;
486 if (action == RFB_CLIENT_ACCEPT)
487 client->clientGoneHook = &VNCDisconnect;
491 static void VNCSetup() {
494 @synchronized (condition_) {
496 char *arg0(strdup("VNCServer"));
497 char *argv[] = {arg0, NULL};
498 screen_ = rfbGetScreen(&argc, argv, width_, height_, BitsPerSample, 3, BytesPerPixel);
504 screen_->desktopName = strdup([[[NSProcessInfo processInfo] hostName] UTF8String]);
506 screen_->alwaysShared = TRUE;
507 screen_->handleEventsEagerly = TRUE;
508 screen_->deferUpdateTime = 1000 / 25;
510 screen_->serverFormat.redShift = BitsPerSample * 2;
511 screen_->serverFormat.greenShift = BitsPerSample * 1;
512 screen_->serverFormat.blueShift = BitsPerSample * 0;
514 buffer_ = CoreSurfaceBufferCreate((CFDictionaryRef) [NSDictionary dictionaryWithObjectsAndKeys:
515 @"PurpleEDRAM", kCoreSurfaceBufferMemoryRegion,
516 [NSNumber numberWithBool:YES], kCoreSurfaceBufferGlobal,
517 [NSNumber numberWithInt:(width_ * BytesPerPixel)], kCoreSurfaceBufferPitch,
518 [NSNumber numberWithInt:width_], kCoreSurfaceBufferWidth,
519 [NSNumber numberWithInt:height_], kCoreSurfaceBufferHeight,
520 [NSNumber numberWithInt:'BGRA'], kCoreSurfaceBufferPixelFormat,
521 [NSNumber numberWithInt:(width_ * height_ * BytesPerPixel)], kCoreSurfaceBufferAllocSize,
524 //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));
526 CoreSurfaceBufferLock(buffer_, 3);
527 screen_->frameBuffer = reinterpret_cast<char *>(CoreSurfaceBufferGetBaseAddress(buffer_));
528 CoreSurfaceBufferUnlock(buffer_);
530 screen_->kbdAddEvent = &VNCKeyboard;
531 screen_->ptrAddEvent = &VNCPointer;
533 screen_->newClientHook = &VNCClient;
534 screen_->passwordCheck = &VNCCheck;
536 screen_->cursor = NULL;
539 static void VNCEnabled() {
543 if (NSDictionary *settings = [NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/Library/Preferences/com.saurik.Veency.plist", NSHomeDirectory()]])
544 if (NSNumber *number = [settings objectForKey:@"Enabled"])
545 enabled = [number boolValue];
547 if (enabled != running_)
550 screen_->socketState = RFB_SOCKET_INIT;
551 rfbInitServer(screen_);
552 rfbRunEventLoop(screen_, -1, true);
554 rfbShutdownServer(screen_, true);
561 static void VNCNotifyEnabled(
562 CFNotificationCenterRef center,
571 MSHook(kern_return_t, IOMobileFramebufferSwapSetLayer,
572 IOMobileFramebufferRef fb,
574 CoreSurfaceBufferRef buffer,
579 if (_unlikely(screen_ == NULL)) {
581 IOMobileFramebufferGetDisplaySize(fb, &size);
584 height_ = size.height;
586 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
590 } else if (_unlikely(clients_ != 0)) {
591 if (buffer == NULL) {
592 //CoreSurfaceBufferLock(buffer_, 3);
593 memset(screen_->frameBuffer, 0, sizeof(rfbPixel) * width_ * height_);
594 //CoreSurfaceBufferUnlock(buffer_);
596 //CoreSurfaceBufferLock(buffer_, 3);
597 //CoreSurfaceBufferLock(buffer, 2);
599 //rfbPixel *data(reinterpret_cast<rfbPixel *>(CoreSurfaceBufferGetBaseAddress(buffer)));
601 /*rfbPixel corner(data[0]);
605 CoreSurfaceAcceleratorTransferSurface(accelerator_, buffer, buffer_, options_);
607 //CoreSurfaceBufferUnlock(buffer);
608 //CoreSurfaceBufferUnlock(buffer_);
611 //CoreSurfaceBufferFlushProcessorCaches(buffer);
612 rfbMarkRectAsModified(screen_, 0, 0, width_, height_);
615 return _IOMobileFramebufferSwapSetLayer(fb, layer, buffer, bounds, frame, flags);
618 MSHook(void, rfbRegisterSecurityHandler, rfbSecurityHandler *handler) {
619 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
621 @synchronized (lock_) {
622 [handlers_ addObject:[NSValue valueWithPointer:handler]];
623 _rfbRegisterSecurityHandler(handler);
629 template <typename Type_>
630 static void dlset(Type_ &function, const char *name) {
631 function = reinterpret_cast<Type_>(dlsym(RTLD_DEFAULT, name));
635 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
637 MSHookSymbol(GSTakePurpleSystemEventPort, "GSGetPurpleSystemEventPort");
638 if (GSTakePurpleSystemEventPort == NULL) {
639 MSHookSymbol(GSTakePurpleSystemEventPort, "GSCopyPurpleSystemEventPort");
640 PurpleAllocated = true;
643 if (dlsym(RTLD_DEFAULT, "GSKeyboardCreate") != NULL)
645 else if (dlsym(RTLD_DEFAULT, "GSEventGetWindowContextId") != NULL)
650 dlset($GSEventCreateKeyEvent, "GSEventCreateKeyEvent");
651 dlset($GSCreateSyntheticKeyEvent, "_GSCreateSyntheticKeyEvent");
653 MSHookFunction(&IOMobileFramebufferSwapSetLayer, MSHake(IOMobileFramebufferSwapSetLayer));
654 MSHookFunction(&rfbRegisterSecurityHandler, MSHake(rfbRegisterSecurityHandler));
656 $VNCAlertItem = objc_allocateClassPair(objc_getClass("SBAlertItem"), "VNCAlertItem", 0);
657 MSAddMessage2(VNCAlertItem, "v@:@i", alertSheet,buttonClicked);
658 MSAddMessage2(VNCAlertItem, "v@:cc", configure,requirePasscodeForActions);
659 MSAddMessage0(VNCAlertItem, "v@:", performUnlockAction);
660 objc_registerClassPair($VNCAlertItem);
662 CFNotificationCenterAddObserver(
663 CFNotificationCenterGetDarwinNotifyCenter(),
664 NULL, &VNCNotifyEnabled, CFSTR("com.saurik.Veency-Enabled"), NULL, 0
667 CFNotificationCenterAddObserver(
668 CFNotificationCenterGetDarwinNotifyCenter(),
669 NULL, &VNCNotifySettings, CFSTR("com.saurik.Veency-Settings"), NULL, 0
672 condition_ = [[NSCondition alloc] init];
673 lock_ = [[NSLock alloc] init];
674 handlers_ = [[NSMutableSet alloc] init];
679 cfTrue_ = CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&value), sizeof(value));
682 cfFalse_ = CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&value), sizeof(value));
684 cfEvent_ = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&event_), sizeof(event_), kCFAllocatorNull);
686 CoreSurfaceAcceleratorCreate(NULL, NULL, &accelerator_);
688 options_ = (CFDictionaryRef) [[NSDictionary dictionaryWithObjectsAndKeys: