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 NSMutableSet *handlers_;
74 static rfbScreenInfoPtr screen_;
79 static unsigned clients_;
81 static CFMessagePortRef ashikase_;
84 static bool Ashikase(bool always) {
85 if (!always && !cursor_)
88 if (ashikase_ == NULL)
89 ashikase_ = CFMessagePortCreateRemote(kCFAllocatorDefault, CFSTR("jp.ashikase.mousesupport"));
90 if (ashikase_ != NULL)
97 static CFDataRef cfTrue_;
98 static CFDataRef cfFalse_;
106 static MouseEvent event_;
107 static CFDataRef cfEvent_;
110 MouseMessageTypeEvent,
111 MouseMessageTypeSetEnabled
114 static void AshikaseSendEvent(float x, float y, int buttons = 0) {
117 event_.buttons = buttons;
118 event_.absolute = true;
120 CFMessagePortSendRequest(ashikase_, MouseMessageTypeEvent, cfEvent_, 0, 0, NULL, NULL);
123 static void AshikaseSetEnabled(bool enabled, bool always) {
124 if (!Ashikase(always))
127 CFMessagePortSendRequest(ashikase_, MouseMessageTypeSetEnabled, enabled ? cfTrue_ : cfFalse_, 0, 0, NULL, NULL);
130 AshikaseSendEvent(x_, y_);
133 MSClassHook(SBAlertItemsController)
134 MSClassHook(SBStatusBarController)
137 static Class $VNCAlertItem;
139 static rfbNewClientAction action_ = RFB_CLIENT_ON_HOLD;
140 static NSCondition *condition_;
141 static NSLock *lock_;
143 static rfbClientPtr client_;
145 @interface VNCBridge : NSObject {
148 + (void) askForConnection;
149 + (void) removeStatusBarItem;
150 + (void) registerClient;
154 @implementation VNCBridge
156 + (void) askForConnection {
157 [[$SBAlertItemsController sharedInstance] activateAlertItem:[[[$VNCAlertItem alloc] init] autorelease]];
160 + (void) removeStatusBarItem {
161 AshikaseSetEnabled(false, false);
162 [[$SBStatusBarController sharedStatusBarController] removeStatusBarItem:@"Veency"];
165 + (void) registerClient {
167 AshikaseSetEnabled(true, false);
168 [[$SBStatusBarController sharedStatusBarController] addStatusBarItem:@"Veency"];
173 MSInstanceMessage2(void, VNCAlertItem, alertSheet,buttonClicked, id, sheet, int, button) {
178 action_ = RFB_CLIENT_ACCEPT;
180 @synchronized (condition_) {
181 [VNCBridge registerClient];
186 action_ = RFB_CLIENT_REFUSE;
195 MSInstanceMessage2(void, VNCAlertItem, configure,requirePasscodeForActions, BOOL, configure, BOOL, require) {
196 UIModalView *sheet([self alertSheet]);
197 [sheet setDelegate:self];
198 [sheet setTitle:@"Remote Access Request"];
199 [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]];
200 [sheet addButtonWithTitle:@"Accept"];
201 [sheet addButtonWithTitle:@"Reject"];
204 MSInstanceMessage0(void, VNCAlertItem, performUnlockAction) {
205 [[$SBAlertItemsController sharedInstance] activateAlertItem:self];
208 static mach_port_t (*GSTakePurpleSystemEventPort)(void);
209 static bool PurpleAllocated;
212 static void FixRecord(GSEventRecord *record) {
214 memmove(&record->windowContextId, &record->windowContextId + 1, sizeof(*record) - (reinterpret_cast<uint8_t *>(&record->windowContextId + 1) - reinterpret_cast<uint8_t *>(record)) + record->size);
217 static void VNCSettings() {
218 NSDictionary *settings([NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/Library/Preferences/com.saurik.Veency.plist", NSHomeDirectory()]]);
220 @synchronized (lock_) {
221 for (NSValue *handler in handlers_)
222 rfbUnregisterSecurityHandler(reinterpret_cast<rfbSecurityHandler *>([handler pointerValue]));
223 [handlers_ removeAllObjects];
226 @synchronized (condition_) {
230 [reinterpret_cast<NSString *>(screen_->authPasswdData) release];
231 screen_->authPasswdData = NULL;
234 if (NSString *password = [settings objectForKey:@"Password"])
235 if ([password length] != 0)
236 screen_->authPasswdData = [password retain];
238 NSNumber *cursor = [settings objectForKey:@"ShowCursor"];
239 cursor_ = cursor == nil ? true : [cursor boolValue];
242 AshikaseSetEnabled(cursor_, true);
246 static void VNCNotifySettings(
247 CFNotificationCenterRef center,
256 static rfbBool VNCCheck(rfbClientPtr client, const char *data, int size) {
257 @synchronized (condition_) {
258 if (NSString *password = reinterpret_cast<NSString *>(screen_->authPasswdData)) {
259 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
260 rfbEncryptBytes(client->authChallenge, const_cast<char *>([password UTF8String]));
261 bool good(memcmp(client->authChallenge, data, size) == 0);
268 static void VNCPointer(int buttons, int x, int y, rfbClientPtr client) {
270 int diff = buttons_ ^ buttons;
271 bool twas((buttons_ & 0x1) != 0);
272 bool tis((buttons & 0x1) != 0);
275 rfbDefaultPtrAddEvent(buttons, x, y, client);
277 if (Ashikase(false)) {
278 AshikaseSendEvent(x, y, buttons);
282 mach_port_t purple(0);
284 if ((diff & 0x10) != 0) {
285 struct GSEventRecord record;
287 memset(&record, 0, sizeof(record));
289 record.type = (buttons & 0x4) != 0 ?
290 GSEventTypeHeadsetButtonDown :
291 GSEventTypeHeadsetButtonUp;
293 record.timestamp = GSCurrentEventTimestamp();
296 GSSendSystemEvent(&record);
299 if ((diff & 0x04) != 0) {
300 struct GSEventRecord record;
302 memset(&record, 0, sizeof(record));
304 record.type = (buttons & 0x4) != 0 ?
305 GSEventTypeMenuButtonDown :
306 GSEventTypeMenuButtonUp;
308 record.timestamp = GSCurrentEventTimestamp();
311 GSSendSystemEvent(&record);
314 if ((diff & 0x02) != 0) {
315 struct GSEventRecord record;
317 memset(&record, 0, sizeof(record));
319 record.type = (buttons & 0x2) != 0 ?
320 GSEventTypeLockButtonDown :
321 GSEventTypeLockButtonUp;
323 record.timestamp = GSCurrentEventTimestamp();
326 GSSendSystemEvent(&record);
329 if (twas != tis || tis) {
331 struct GSEventRecord record;
333 struct GSEventRecordInfo info;
334 struct GSPathInfo path;
338 memset(&event, 0, sizeof(event));
340 event.record.type = GSEventTypeMouse;
341 event.record.locationInWindow.x = x;
342 event.record.locationInWindow.y = y;
343 event.record.timestamp = GSCurrentEventTimestamp();
344 event.record.size = sizeof(event.data);
346 event.data.info.handInfo.type = twas == tis ?
347 GSMouseEventTypeDragged :
349 GSMouseEventTypeDown :
352 event.data.info.handInfo.x34 = 0x1;
353 event.data.info.handInfo.x38 = tis ? 0x1 : 0x0;
355 event.data.info.pathPositions = 1;
357 event.data.path.x00 = 0x01;
358 event.data.path.x01 = 0x02;
359 event.data.path.x02 = tis ? 0x03 : 0x00;
360 event.data.path.position = event.record.locationInWindow;
364 if (CAWindowServer *server = [CAWindowServer serverIfRunning]) {
365 NSArray *displays([server displays]);
366 if (displays != nil && [displays count] != 0)
367 if (CAWindowServerDisplay *display = [displays objectAtIndex:0])
368 port = [display clientPortAtPosition:event.record.locationInWindow];
373 purple = (*GSTakePurpleSystemEventPort)();
377 FixRecord(&event.record);
378 GSSendEvent(&event.record, port);
381 if (purple != 0 && PurpleAllocated)
382 mach_port_deallocate(mach_task_self(), purple);
385 static void VNCKeyboard(rfbBool down, rfbKeySym key, rfbClientPtr client) {
390 case XK_Return: key = '\r'; break;
391 case XK_BackSpace: key = 0x7f; break;
397 GSEventRef event(_GSCreateSyntheticKeyEvent(key, YES, YES));
398 GSEventRecord *record(_GSEventGetGSEventRecord(event));
399 record->type = GSEventTypeKeyDown;
403 if (CAWindowServer *server = [CAWindowServer serverIfRunning]) {
404 NSArray *displays([server displays]);
405 if (displays != nil && [displays count] != 0)
406 if (CAWindowServerDisplay *display = [displays objectAtIndex:0])
407 port = [display clientPortAtPosition:CGPointMake(x_, y_)];
410 mach_port_t purple(0);
414 purple = (*GSTakePurpleSystemEventPort)();
419 GSSendEvent(record, port);
421 if (purple != 0 && PurpleAllocated)
422 mach_port_deallocate(mach_task_self(), purple);
427 static void VNCDisconnect(rfbClientPtr client) {
428 @synchronized (condition_) {
430 [VNCBridge performSelectorOnMainThread:@selector(removeStatusBarItem) withObject:nil waitUntilDone:YES];
434 static rfbNewClientAction VNCClient(rfbClientPtr client) {
435 @synchronized (condition_) {
436 if (screen_->authPasswdData != NULL) {
437 [VNCBridge performSelectorOnMainThread:@selector(registerClient) withObject:nil waitUntilDone:YES];
438 client->clientGoneHook = &VNCDisconnect;
439 return RFB_CLIENT_ACCEPT;
445 [VNCBridge performSelectorOnMainThread:@selector(askForConnection) withObject:nil waitUntilDone:NO];
446 while (action_ == RFB_CLIENT_ON_HOLD)
448 rfbNewClientAction action(action_);
449 action_ = RFB_CLIENT_ON_HOLD;
452 if (action == RFB_CLIENT_ACCEPT)
453 client->clientGoneHook = &VNCDisconnect;
457 static rfbPixel *black_;
459 static void VNCBlack() {
460 if (_unlikely(black_ == NULL))
461 black_ = reinterpret_cast<rfbPixel *>(mmap(NULL, sizeof(rfbPixel) * width_ * height_, PROT_READ, MAP_ANON | MAP_PRIVATE | MAP_NOCACHE, VM_FLAGS_PURGABLE, 0));
462 screen_->frameBuffer = reinterpret_cast<char *>(black_);
465 static void VNCSetup() {
468 @synchronized (condition_) {
470 char *arg0(strdup("VNCServer"));
471 char *argv[] = {arg0, NULL};
472 screen_ = rfbGetScreen(&argc, argv, width_, height_, BitsPerSample, 3, BytesPerPixel);
478 screen_->desktopName = strdup([[[NSProcessInfo processInfo] hostName] UTF8String]);
480 screen_->alwaysShared = TRUE;
481 screen_->handleEventsEagerly = TRUE;
482 screen_->deferUpdateTime = 5;
484 screen_->serverFormat.redShift = BitsPerSample * 2;
485 screen_->serverFormat.greenShift = BitsPerSample * 1;
486 screen_->serverFormat.blueShift = BitsPerSample * 0;
490 screen_->kbdAddEvent = &VNCKeyboard;
491 screen_->ptrAddEvent = &VNCPointer;
493 screen_->newClientHook = &VNCClient;
494 screen_->passwordCheck = &VNCCheck;
496 screen_->cursor = NULL;
499 static void VNCEnabled() {
503 if (NSDictionary *settings = [NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/Library/Preferences/com.saurik.Veency.plist", NSHomeDirectory()]])
504 if (NSNumber *number = [settings objectForKey:@"Enabled"])
505 enabled = [number boolValue];
507 if (enabled != running_)
510 screen_->socketState = RFB_SOCKET_INIT;
511 rfbInitServer(screen_);
512 rfbRunEventLoop(screen_, -1, true);
514 rfbShutdownServer(screen_, true);
521 static void VNCNotifyEnabled(
522 CFNotificationCenterRef center,
531 MSHook(kern_return_t, IOMobileFramebufferSwapSetLayer,
532 IOMobileFramebufferRef fb,
534 CoreSurfaceBufferRef buffer,
539 if (_unlikely(screen_ == NULL)) {
541 IOMobileFramebufferGetDisplaySize(fb, &size);
544 height_ = size.height;
546 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
550 } else if (_unlikely(clients_ != 0)) {
554 CoreSurfaceBufferLock(buffer, 2);
555 volatile rfbPixel *data(reinterpret_cast<volatile rfbPixel *>(CoreSurfaceBufferGetBaseAddress(buffer)));
557 rfbPixel corner(data[0]);
561 screen_->frameBuffer = const_cast<char *>(reinterpret_cast<volatile char *>(data));
562 CoreSurfaceBufferUnlock(buffer);
565 //CoreSurfaceBufferFlushProcessorCaches(buffer);
566 rfbMarkRectAsModified(screen_, 0, 0, width_, height_);
569 return _IOMobileFramebufferSwapSetLayer(fb, layer, buffer, bounds, frame, flags);
572 MSHook(void, rfbRegisterSecurityHandler, rfbSecurityHandler *handler) {
573 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
575 @synchronized (lock_) {
576 [handlers_ addObject:[NSValue valueWithPointer:handler]];
577 _rfbRegisterSecurityHandler(handler);
584 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
586 MSHookSymbol(GSTakePurpleSystemEventPort, "GSGetPurpleSystemEventPort");
587 if (GSTakePurpleSystemEventPort == NULL) {
588 MSHookSymbol(GSTakePurpleSystemEventPort, "GSCopyPurpleSystemEventPort");
589 PurpleAllocated = true;
592 Two_ = dlsym(RTLD_DEFAULT, "GSEventGetWindowContextId") == NULL;
594 MSHookFunction(&IOMobileFramebufferSwapSetLayer, MSHake(IOMobileFramebufferSwapSetLayer));
595 MSHookFunction(&rfbRegisterSecurityHandler, MSHake(rfbRegisterSecurityHandler));
597 $VNCAlertItem = objc_allocateClassPair(objc_getClass("SBAlertItem"), "VNCAlertItem", 0);
598 MSAddMessage2(VNCAlertItem, "v@:@i", alertSheet,buttonClicked);
599 MSAddMessage2(VNCAlertItem, "v@:cc", configure,requirePasscodeForActions);
600 MSAddMessage0(VNCAlertItem, "v@:", performUnlockAction);
601 objc_registerClassPair($VNCAlertItem);
603 CFNotificationCenterAddObserver(
604 CFNotificationCenterGetDarwinNotifyCenter(),
605 NULL, &VNCNotifyEnabled, CFSTR("com.saurik.Veency-Enabled"), NULL, 0
608 CFNotificationCenterAddObserver(
609 CFNotificationCenterGetDarwinNotifyCenter(),
610 NULL, &VNCNotifySettings, CFSTR("com.saurik.Veency-Settings"), NULL, 0
613 condition_ = [[NSCondition alloc] init];
614 lock_ = [[NSLock alloc] init];
615 handlers_ = [[NSMutableSet alloc] init];
622 cfTrue_ = CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&value), sizeof(value));
625 cfFalse_ = CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&value), sizeof(value));
627 cfEvent_ = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&event_), sizeof(event_), kCFAllocatorNull);