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 static void VNCKeyboard(rfbBool down, rfbKeySym key, rfbClientPtr client) {
402 case XK_Return: key = '\r'; break;
403 case XK_BackSpace: key = 0x7f; break;
409 GSEventRef event(_GSCreateSyntheticKeyEvent(key, YES, YES));
410 GSEventRecord *record(_GSEventGetGSEventRecord(event));
411 record->type = GSEventTypeKeyDown;
415 if (CAWindowServer *server = [CAWindowServer serverIfRunning]) {
416 NSArray *displays([server displays]);
417 if (displays != nil && [displays count] != 0)
418 if (CAWindowServerDisplay *display = [displays objectAtIndex:0])
419 port = [display clientPortAtPosition:CGPointMake(x_, y_)];
422 mach_port_t purple(0);
426 purple = (*GSTakePurpleSystemEventPort)();
431 GSSendEvent(record, port);
433 if (purple != 0 && PurpleAllocated)
434 mach_port_deallocate(mach_task_self(), purple);
439 static void VNCDisconnect(rfbClientPtr client) {
440 @synchronized (condition_) {
442 [VNCBridge performSelectorOnMainThread:@selector(removeStatusBarItem) withObject:nil waitUntilDone:YES];
446 static rfbNewClientAction VNCClient(rfbClientPtr client) {
447 @synchronized (condition_) {
448 if (screen_->authPasswdData != NULL) {
449 [VNCBridge performSelectorOnMainThread:@selector(registerClient) withObject:nil waitUntilDone:YES];
450 client->clientGoneHook = &VNCDisconnect;
451 return RFB_CLIENT_ACCEPT;
457 [VNCBridge performSelectorOnMainThread:@selector(askForConnection) withObject:nil waitUntilDone:NO];
458 while (action_ == RFB_CLIENT_ON_HOLD)
460 rfbNewClientAction action(action_);
461 action_ = RFB_CLIENT_ON_HOLD;
464 if (action == RFB_CLIENT_ACCEPT)
465 client->clientGoneHook = &VNCDisconnect;
469 static void VNCSetup() {
472 @synchronized (condition_) {
474 char *arg0(strdup("VNCServer"));
475 char *argv[] = {arg0, NULL};
476 screen_ = rfbGetScreen(&argc, argv, width_, height_, BitsPerSample, 3, BytesPerPixel);
482 screen_->desktopName = strdup([[[NSProcessInfo processInfo] hostName] UTF8String]);
484 screen_->alwaysShared = TRUE;
485 screen_->handleEventsEagerly = TRUE;
486 screen_->deferUpdateTime = 1000 / 25;
488 screen_->serverFormat.redShift = BitsPerSample * 2;
489 screen_->serverFormat.greenShift = BitsPerSample * 1;
490 screen_->serverFormat.blueShift = BitsPerSample * 0;
492 buffer_ = CoreSurfaceBufferCreate((CFDictionaryRef) [NSDictionary dictionaryWithObjectsAndKeys:
493 @"PurpleEDRAM", kCoreSurfaceBufferMemoryRegion,
494 [NSNumber numberWithBool:YES], kCoreSurfaceBufferGlobal,
495 [NSNumber numberWithInt:(width_ * BytesPerPixel)], kCoreSurfaceBufferPitch,
496 [NSNumber numberWithInt:width_], kCoreSurfaceBufferWidth,
497 [NSNumber numberWithInt:height_], kCoreSurfaceBufferHeight,
498 [NSNumber numberWithInt:'BGRA'], kCoreSurfaceBufferPixelFormat,
499 [NSNumber numberWithInt:(width_ * height_ * BytesPerPixel)], kCoreSurfaceBufferAllocSize,
502 //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));
504 CoreSurfaceBufferLock(buffer_, 3);
505 screen_->frameBuffer = reinterpret_cast<char *>(CoreSurfaceBufferGetBaseAddress(buffer_));
506 CoreSurfaceBufferUnlock(buffer_);
508 screen_->kbdAddEvent = &VNCKeyboard;
509 screen_->ptrAddEvent = &VNCPointer;
511 screen_->newClientHook = &VNCClient;
512 screen_->passwordCheck = &VNCCheck;
514 screen_->cursor = NULL;
517 static void VNCEnabled() {
521 if (NSDictionary *settings = [NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/Library/Preferences/com.saurik.Veency.plist", NSHomeDirectory()]])
522 if (NSNumber *number = [settings objectForKey:@"Enabled"])
523 enabled = [number boolValue];
525 if (enabled != running_)
528 screen_->socketState = RFB_SOCKET_INIT;
529 rfbInitServer(screen_);
530 rfbRunEventLoop(screen_, -1, true);
532 rfbShutdownServer(screen_, true);
539 static void VNCNotifyEnabled(
540 CFNotificationCenterRef center,
549 MSHook(kern_return_t, IOMobileFramebufferSwapSetLayer,
550 IOMobileFramebufferRef fb,
552 CoreSurfaceBufferRef buffer,
557 if (_unlikely(screen_ == NULL)) {
559 IOMobileFramebufferGetDisplaySize(fb, &size);
562 height_ = size.height;
564 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
568 } else if (_unlikely(clients_ != 0)) {
569 if (buffer == NULL) {
570 //CoreSurfaceBufferLock(buffer_, 3);
571 memset(screen_->frameBuffer, 0, sizeof(rfbPixel) * width_ * height_);
572 //CoreSurfaceBufferUnlock(buffer_);
574 //CoreSurfaceBufferLock(buffer_, 3);
575 //CoreSurfaceBufferLock(buffer, 2);
577 //rfbPixel *data(reinterpret_cast<rfbPixel *>(CoreSurfaceBufferGetBaseAddress(buffer)));
579 /*rfbPixel corner(data[0]);
583 CoreSurfaceAcceleratorTransferSurface(accelerator_, buffer, buffer_, options_);
585 //CoreSurfaceBufferUnlock(buffer);
586 //CoreSurfaceBufferUnlock(buffer_);
589 //CoreSurfaceBufferFlushProcessorCaches(buffer);
590 rfbMarkRectAsModified(screen_, 0, 0, width_, height_);
593 return _IOMobileFramebufferSwapSetLayer(fb, layer, buffer, bounds, frame, flags);
596 MSHook(void, rfbRegisterSecurityHandler, rfbSecurityHandler *handler) {
597 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
599 @synchronized (lock_) {
600 [handlers_ addObject:[NSValue valueWithPointer:handler]];
601 _rfbRegisterSecurityHandler(handler);
608 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
610 MSHookSymbol(GSTakePurpleSystemEventPort, "GSGetPurpleSystemEventPort");
611 if (GSTakePurpleSystemEventPort == NULL) {
612 MSHookSymbol(GSTakePurpleSystemEventPort, "GSCopyPurpleSystemEventPort");
613 PurpleAllocated = true;
616 if (dlsym(RTLD_DEFAULT, "GSKeyboardCreate") != NULL)
618 else if (dlsym(RTLD_DEFAULT, "GSEventGetWindowContextId") != NULL)
623 MSHookFunction(&IOMobileFramebufferSwapSetLayer, MSHake(IOMobileFramebufferSwapSetLayer));
624 MSHookFunction(&rfbRegisterSecurityHandler, MSHake(rfbRegisterSecurityHandler));
626 $VNCAlertItem = objc_allocateClassPair(objc_getClass("SBAlertItem"), "VNCAlertItem", 0);
627 MSAddMessage2(VNCAlertItem, "v@:@i", alertSheet,buttonClicked);
628 MSAddMessage2(VNCAlertItem, "v@:cc", configure,requirePasscodeForActions);
629 MSAddMessage0(VNCAlertItem, "v@:", performUnlockAction);
630 objc_registerClassPair($VNCAlertItem);
632 CFNotificationCenterAddObserver(
633 CFNotificationCenterGetDarwinNotifyCenter(),
634 NULL, &VNCNotifyEnabled, CFSTR("com.saurik.Veency-Enabled"), NULL, 0
637 CFNotificationCenterAddObserver(
638 CFNotificationCenterGetDarwinNotifyCenter(),
639 NULL, &VNCNotifySettings, CFSTR("com.saurik.Veency-Settings"), NULL, 0
642 condition_ = [[NSCondition alloc] init];
643 lock_ = [[NSLock alloc] init];
644 handlers_ = [[NSMutableSet alloc] init];
649 cfTrue_ = CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&value), sizeof(value));
652 cfFalse_ = CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&value), sizeof(value));
654 cfEvent_ = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&event_), sizeof(event_), kCFAllocatorNull);
656 CoreSurfaceAcceleratorCreate(NULL, NULL, &accelerator_);
658 options_ = (CFDictionaryRef) [[NSDictionary dictionaryWithObjectsAndKeys: