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>
66 static size_t height_;
68 static const size_t BytesPerPixel = 4;
69 static const size_t BitsPerSample = 8;
71 static NSMutableSet *handlers_;
72 static rfbScreenInfoPtr screen_;
77 static unsigned clients_;
79 static CFMessagePortRef ashikase_;
82 static bool Ashikase(bool always) {
83 if (ashikase_ == NULL)
84 ashikase_ = CFMessagePortCreateRemote(kCFAllocatorDefault, CFSTR("jp.ashikase.mousesupport"));
85 return ashikase_ != NULL && (always || cursor_);
88 static CFDataRef cfTrue_;
89 static CFDataRef cfFalse_;
97 static MouseEvent event_;
98 static CFDataRef cfEvent_;
101 MouseMessageTypeEvent,
102 MouseMessageTypeSetEnabled
105 static void AshikaseSendEvent(float x, float y, int buttons = 0) {
108 event_.buttons = buttons;
109 event_.absolute = true;
111 CFMessagePortSendRequest(ashikase_, MouseMessageTypeEvent, cfEvent_, 0, 0, NULL, NULL);
114 static void AshikaseSetEnabled(bool enabled, bool always) {
115 if (!Ashikase(always))
118 CFMessagePortSendRequest(ashikase_, MouseMessageTypeSetEnabled, enabled ? cfTrue_ : cfFalse_, 0, 0, NULL, NULL);
121 AshikaseSendEvent(x_, y_);
124 MSClassHook(SBAlertItemsController)
125 MSClassHook(SBStatusBarController)
128 static Class $VNCAlertItem;
130 static rfbNewClientAction action_ = RFB_CLIENT_ON_HOLD;
131 static NSCondition *condition_;
132 static NSLock *lock_;
134 static rfbClientPtr client_;
136 @interface VNCBridge : NSObject {
139 + (void) askForConnection;
140 + (void) removeStatusBarItem;
141 + (void) registerClient;
145 @implementation VNCBridge
147 + (void) askForConnection {
148 [[$SBAlertItemsController sharedInstance] activateAlertItem:[[[$VNCAlertItem alloc] init] autorelease]];
151 + (void) removeStatusBarItem {
152 AshikaseSetEnabled(false, false);
153 [[$SBStatusBarController sharedStatusBarController] removeStatusBarItem:@"Veency"];
156 + (void) registerClient {
158 AshikaseSetEnabled(true, false);
159 [[$SBStatusBarController sharedStatusBarController] addStatusBarItem:@"Veency"];
164 MSInstanceMessage2(void, VNCAlertItem, alertSheet,buttonClicked, id, sheet, int, button) {
169 action_ = RFB_CLIENT_ACCEPT;
171 @synchronized (condition_) {
172 [VNCBridge registerClient];
177 action_ = RFB_CLIENT_REFUSE;
186 MSInstanceMessage2(void, VNCAlertItem, configure,requirePasscodeForActions, BOOL, configure, BOOL, require) {
187 UIModalView *sheet([self alertSheet]);
188 [sheet setDelegate:self];
189 [sheet setTitle:@"Remote Access Request"];
190 [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]];
191 [sheet addButtonWithTitle:@"Accept"];
192 [sheet addButtonWithTitle:@"Reject"];
195 MSInstanceMessage0(void, VNCAlertItem, performUnlockAction) {
196 [[$SBAlertItemsController sharedInstance] activateAlertItem:self];
199 static mach_port_t (*GSTakePurpleSystemEventPort)(void);
200 static bool PurpleAllocated;
203 static void FixRecord(GSEventRecord *record) {
205 memmove(&record->windowContextId, &record->windowContextId + 1, sizeof(*record) - (reinterpret_cast<uint8_t *>(&record->windowContextId + 1) - reinterpret_cast<uint8_t *>(record)) + record->size);
208 static void VNCSettings() {
209 NSDictionary *settings([NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/Library/Preferences/com.saurik.Veency.plist", NSHomeDirectory()]]);
211 @synchronized (lock_) {
212 for (NSValue *handler in handlers_)
213 rfbUnregisterSecurityHandler(reinterpret_cast<rfbSecurityHandler *>([handler pointerValue]));
214 [handlers_ removeAllObjects];
217 @synchronized (condition_) {
221 [reinterpret_cast<NSString *>(screen_->authPasswdData) release];
222 screen_->authPasswdData = NULL;
225 if (NSString *password = [settings objectForKey:@"Password"])
226 if ([password length] != 0)
227 screen_->authPasswdData = [password retain];
229 NSNumber *cursor = [settings objectForKey:@"ShowCursor"];
230 cursor_ = cursor == nil ? true : [cursor boolValue];
233 AshikaseSetEnabled(cursor_, true);
237 static void VNCNotifySettings(
238 CFNotificationCenterRef center,
247 static rfbBool VNCCheck(rfbClientPtr client, const char *data, int size) {
248 @synchronized (condition_) {
249 if (NSString *password = reinterpret_cast<NSString *>(screen_->authPasswdData)) {
250 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
251 rfbEncryptBytes(client->authChallenge, const_cast<char *>([password UTF8String]));
252 bool good(memcmp(client->authChallenge, data, size) == 0);
259 static void VNCPointer(int buttons, int x, int y, rfbClientPtr client) {
261 int diff = buttons_ ^ buttons;
262 bool twas((buttons_ & 0x1) != 0);
263 bool tis((buttons & 0x1) != 0);
266 rfbDefaultPtrAddEvent(buttons, x, y, client);
268 if (Ashikase(false)) {
269 AshikaseSendEvent(x, y, buttons);
273 mach_port_t purple(0);
275 if ((diff & 0x10) != 0) {
276 struct GSEventRecord record;
278 memset(&record, 0, sizeof(record));
280 record.type = (buttons & 0x4) != 0 ?
281 GSEventTypeHeadsetButtonDown :
282 GSEventTypeHeadsetButtonUp;
284 record.timestamp = GSCurrentEventTimestamp();
287 GSSendSystemEvent(&record);
290 if ((diff & 0x04) != 0) {
291 struct GSEventRecord record;
293 memset(&record, 0, sizeof(record));
295 record.type = (buttons & 0x4) != 0 ?
296 GSEventTypeMenuButtonDown :
297 GSEventTypeMenuButtonUp;
299 record.timestamp = GSCurrentEventTimestamp();
302 GSSendSystemEvent(&record);
305 if ((diff & 0x02) != 0) {
306 struct GSEventRecord record;
308 memset(&record, 0, sizeof(record));
310 record.type = (buttons & 0x2) != 0 ?
311 GSEventTypeLockButtonDown :
312 GSEventTypeLockButtonUp;
314 record.timestamp = GSCurrentEventTimestamp();
317 GSSendSystemEvent(&record);
320 if (twas != tis || tis) {
322 struct GSEventRecord record;
324 struct GSEventRecordInfo info;
325 struct GSPathInfo path;
329 memset(&event, 0, sizeof(event));
331 event.record.type = GSEventTypeMouse;
332 event.record.locationInWindow.x = x;
333 event.record.locationInWindow.y = y;
334 event.record.timestamp = GSCurrentEventTimestamp();
335 event.record.size = sizeof(event.data);
337 event.data.info.handInfo.type = twas == tis ?
338 GSMouseEventTypeDragged :
340 GSMouseEventTypeDown :
343 event.data.info.handInfo.x34 = 0x1;
344 event.data.info.handInfo.x38 = tis ? 0x1 : 0x0;
346 event.data.info.pathPositions = 1;
348 event.data.path.x00 = 0x01;
349 event.data.path.x01 = 0x02;
350 event.data.path.x02 = tis ? 0x03 : 0x00;
351 event.data.path.position = event.record.locationInWindow;
355 if (CAWindowServer *server = [CAWindowServer serverIfRunning]) {
356 NSArray *displays([server displays]);
357 if (displays != nil && [displays count] != 0)
358 if (CAWindowServerDisplay *display = [displays objectAtIndex:0])
359 port = [display clientPortAtPosition:event.record.locationInWindow];
364 purple = (*GSTakePurpleSystemEventPort)();
368 FixRecord(&event.record);
369 GSSendEvent(&event.record, port);
372 if (purple != 0 && PurpleAllocated)
373 mach_port_deallocate(mach_task_self(), purple);
376 static void VNCKeyboard(rfbBool down, rfbKeySym key, rfbClientPtr client) {
381 case XK_Return: key = '\r'; break;
382 case XK_BackSpace: key = 0x7f; break;
388 GSEventRef event(_GSCreateSyntheticKeyEvent(key, YES, YES));
389 GSEventRecord *record(_GSEventGetGSEventRecord(event));
390 record->type = GSEventTypeKeyDown;
394 if (CAWindowServer *server = [CAWindowServer serverIfRunning]) {
395 NSArray *displays([server displays]);
396 if (displays != nil && [displays count] != 0)
397 if (CAWindowServerDisplay *display = [displays objectAtIndex:0])
398 port = [display clientPortAtPosition:CGPointMake(x_, y_)];
401 mach_port_t purple(0);
405 purple = (*GSTakePurpleSystemEventPort)();
410 GSSendEvent(record, port);
412 if (purple != 0 && PurpleAllocated)
413 mach_port_deallocate(mach_task_self(), purple);
418 static void VNCDisconnect(rfbClientPtr client) {
419 @synchronized (condition_) {
421 [VNCBridge performSelectorOnMainThread:@selector(removeStatusBarItem) withObject:nil waitUntilDone:YES];
425 static rfbNewClientAction VNCClient(rfbClientPtr client) {
426 @synchronized (condition_) {
427 if (screen_->authPasswdData != NULL) {
428 [VNCBridge performSelectorOnMainThread:@selector(registerClient) withObject:nil waitUntilDone:YES];
429 client->clientGoneHook = &VNCDisconnect;
430 return RFB_CLIENT_ACCEPT;
436 [VNCBridge performSelectorOnMainThread:@selector(askForConnection) withObject:nil waitUntilDone:NO];
437 while (action_ == RFB_CLIENT_ON_HOLD)
439 rfbNewClientAction action(action_);
440 action_ = RFB_CLIENT_ON_HOLD;
443 if (action == RFB_CLIENT_ACCEPT)
444 client->clientGoneHook = &VNCDisconnect;
448 static rfbPixel *black_;
450 static void VNCBlack() {
451 if (_unlikely(black_ == NULL))
452 black_ = reinterpret_cast<rfbPixel *>(mmap(NULL, sizeof(rfbPixel) * width_ * height_, PROT_READ, MAP_ANON | MAP_PRIVATE | MAP_NOCACHE, VM_FLAGS_PURGABLE, 0));
453 screen_->frameBuffer = reinterpret_cast<char *>(black_);
456 static void VNCSetup() {
459 @synchronized (condition_) {
461 char *arg0(strdup("VNCServer"));
462 char *argv[] = {arg0, NULL};
463 screen_ = rfbGetScreen(&argc, argv, width_, height_, BitsPerSample, 3, BytesPerPixel);
469 screen_->desktopName = strdup([[[NSProcessInfo processInfo] hostName] UTF8String]);
471 screen_->alwaysShared = TRUE;
472 screen_->handleEventsEagerly = TRUE;
473 screen_->deferUpdateTime = 5;
475 screen_->serverFormat.redShift = BitsPerSample * 2;
476 screen_->serverFormat.greenShift = BitsPerSample * 1;
477 screen_->serverFormat.blueShift = BitsPerSample * 0;
481 screen_->kbdAddEvent = &VNCKeyboard;
482 screen_->ptrAddEvent = &VNCPointer;
484 screen_->newClientHook = &VNCClient;
485 screen_->passwordCheck = &VNCCheck;
487 char data[0], mask[0];
488 rfbCursorPtr cursor = rfbMakeXCursor(0, 0, data, mask);
489 rfbSetCursor(screen_, cursor);
492 static void VNCEnabled() {
496 if (NSDictionary *settings = [NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/Library/Preferences/com.saurik.Veency.plist", NSHomeDirectory()]])
497 if (NSNumber *number = [settings objectForKey:@"Enabled"])
498 enabled = [number boolValue];
500 if (enabled != running_)
503 screen_->socketState = RFB_SOCKET_INIT;
504 rfbInitServer(screen_);
505 rfbRunEventLoop(screen_, -1, true);
507 rfbShutdownServer(screen_, true);
514 static void VNCNotifyEnabled(
515 CFNotificationCenterRef center,
524 MSHook(kern_return_t, IOMobileFramebufferSwapSetLayer,
525 IOMobileFramebufferRef fb,
527 CoreSurfaceBufferRef buffer,
532 if (_unlikely(screen_ == NULL)) {
534 IOMobileFramebufferGetDisplaySize(fb, &size);
537 height_ = size.height;
539 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
543 } else if (_unlikely(clients_ != 0)) {
547 CoreSurfaceBufferLock(buffer, 2);
548 rfbPixel *data(reinterpret_cast<rfbPixel *>(CoreSurfaceBufferGetBaseAddress(buffer)));
549 screen_->frameBuffer = const_cast<char *>(reinterpret_cast<volatile char *>(data));
550 CoreSurfaceBufferUnlock(buffer);
553 rfbMarkRectAsModified(screen_, 0, 0, width_, height_);
556 return _IOMobileFramebufferSwapSetLayer(fb, layer, buffer, bounds, frame, flags);
559 MSHook(void, rfbRegisterSecurityHandler, rfbSecurityHandler *handler) {
560 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
562 @synchronized (lock_) {
563 [handlers_ addObject:[NSValue valueWithPointer:handler]];
564 _rfbRegisterSecurityHandler(handler);
571 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
573 MSHookSymbol(GSTakePurpleSystemEventPort, "GSGetPurpleSystemEventPort");
574 if (GSTakePurpleSystemEventPort == NULL) {
575 MSHookSymbol(GSTakePurpleSystemEventPort, "GSCopyPurpleSystemEventPort");
576 PurpleAllocated = true;
579 Two_ = dlsym(RTLD_DEFAULT, "GSEventGetWindowContextId") == NULL;
581 MSHookFunction(&IOMobileFramebufferSwapSetLayer, MSHake(IOMobileFramebufferSwapSetLayer));
582 MSHookFunction(&rfbRegisterSecurityHandler, MSHake(rfbRegisterSecurityHandler));
584 $VNCAlertItem = objc_allocateClassPair(objc_getClass("SBAlertItem"), "VNCAlertItem", 0);
585 MSAddMessage2(VNCAlertItem, "v@:@i", alertSheet,buttonClicked);
586 MSAddMessage2(VNCAlertItem, "v@:cc", configure,requirePasscodeForActions);
587 MSAddMessage0(VNCAlertItem, "v@:", performUnlockAction);
588 objc_registerClassPair($VNCAlertItem);
590 CFNotificationCenterAddObserver(
591 CFNotificationCenterGetDarwinNotifyCenter(),
592 NULL, &VNCNotifyEnabled, CFSTR("com.saurik.Veency-Enabled"), NULL, 0
595 CFNotificationCenterAddObserver(
596 CFNotificationCenterGetDarwinNotifyCenter(),
597 NULL, &VNCNotifySettings, CFSTR("com.saurik.Veency-Settings"), NULL, 0
600 condition_ = [[NSCondition alloc] init];
601 lock_ = [[NSLock alloc] init];
602 handlers_ = [[NSMutableSet alloc] init];
609 cfTrue_ = CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&value), sizeof(value));
612 cfFalse_ = CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&value), sizeof(value));
614 cfEvent_ = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&event_), sizeof(event_), kCFAllocatorNull);