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>
50 #import <QuartzCore/CAWindowServer.h>
51 #import <QuartzCore/CAWindowServerDisplay.h>
53 #import <CoreGraphics/CGGeometry.h>
54 #import <GraphicsServices/GraphicsServices.h>
55 #import <Foundation/Foundation.h>
56 #import <IOMobileFramebuffer/IOMobileFramebuffer.h>
57 #import <IOKit/IOKitLib.h>
58 #import <UIKit/UIKit.h>
60 #import <SpringBoard/SBAlertItemsController.h>
61 #import <SpringBoard/SBDismissOnlyAlertItem.h>
62 #import <SpringBoard/SBStatusBarController.h>
64 static size_t Width = 320;
65 static size_t Height = 480;
67 static const size_t BytesPerPixel = 4;
68 static const size_t BitsPerSample = 8;
70 static NSMutableSet *handlers_;
71 static rfbScreenInfoPtr screen_;
76 static unsigned clients_;
78 static CFMessagePortRef ashikase_;
81 static bool Ashikase(bool always) {
82 if (ashikase_ == NULL)
83 ashikase_ = CFMessagePortCreateRemote(kCFAllocatorDefault, CFSTR("jp.ashikase.mousesupport"));
84 return ashikase_ != NULL && (always || cursor_);
87 static CFDataRef cfTrue_;
88 static CFDataRef cfFalse_;
96 static MouseEvent event_;
97 static CFDataRef cfEvent_;
100 MouseMessageTypeEvent,
101 MouseMessageTypeSetEnabled
104 static void AshikaseSendEvent(float x, float y, int buttons = 0) {
107 event_.buttons = buttons;
108 event_.absolute = true;
110 CFMessagePortSendRequest(ashikase_, MouseMessageTypeEvent, cfEvent_, 0, 0, NULL, NULL);
113 static void AshikaseSetEnabled(bool enabled, bool always) {
114 if (!Ashikase(always))
117 CFMessagePortSendRequest(ashikase_, MouseMessageTypeSetEnabled, enabled ? cfTrue_ : cfFalse_, 0, 0, NULL, NULL);
120 AshikaseSendEvent(x_, y_);
123 MSClassHook(SBAlertItemsController)
124 MSClassHook(SBStatusBarController)
127 static Class $VNCAlertItem;
129 static rfbNewClientAction action_ = RFB_CLIENT_ON_HOLD;
130 static NSCondition *condition_;
131 static NSLock *lock_;
133 static rfbClientPtr client_;
135 @interface VNCBridge : NSObject {
138 + (void) askForConnection;
139 + (void) removeStatusBarItem;
140 + (void) registerClient;
144 @implementation VNCBridge
146 + (void) askForConnection {
147 [[$SBAlertItemsController sharedInstance] activateAlertItem:[[[$VNCAlertItem alloc] init] autorelease]];
150 + (void) removeStatusBarItem {
151 AshikaseSetEnabled(false, false);
152 [[$SBStatusBarController sharedStatusBarController] removeStatusBarItem:@"Veency"];
155 + (void) registerClient {
157 AshikaseSetEnabled(true, false);
158 [[$SBStatusBarController sharedStatusBarController] addStatusBarItem:@"Veency"];
163 MSInstanceMessage2(void, VNCAlertItem, alertSheet,buttonClicked, id, sheet, int, button) {
168 action_ = RFB_CLIENT_ACCEPT;
170 @synchronized (condition_) {
171 [VNCBridge registerClient];
176 action_ = RFB_CLIENT_REFUSE;
185 MSInstanceMessage2(void, VNCAlertItem, configure,requirePasscodeForActions, BOOL, configure, BOOL, require) {
186 UIModalView *sheet([self alertSheet]);
187 [sheet setDelegate:self];
188 [sheet setTitle:@"Remote Access Request"];
189 [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]];
190 [sheet addButtonWithTitle:@"Accept"];
191 [sheet addButtonWithTitle:@"Reject"];
194 MSInstanceMessage0(void, VNCAlertItem, performUnlockAction) {
195 [[$SBAlertItemsController sharedInstance] activateAlertItem:self];
198 static mach_port_t (*GSTakePurpleSystemEventPort)(void);
199 static bool PurpleAllocated;
202 static void FixRecord(GSEventRecord *record) {
204 memmove(&record->windowContextId, &record->windowContextId + 1, sizeof(*record) - (reinterpret_cast<uint8_t *>(&record->windowContextId + 1) - reinterpret_cast<uint8_t *>(record)) + record->size);
207 static void VNCSettings() {
208 NSDictionary *settings([NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/Library/Preferences/com.saurik.Veency.plist", NSHomeDirectory()]]);
210 @synchronized (lock_) {
211 for (NSValue *handler in handlers_)
212 rfbUnregisterSecurityHandler(reinterpret_cast<rfbSecurityHandler *>([handler pointerValue]));
213 [handlers_ removeAllObjects];
216 @synchronized (condition_) {
220 [reinterpret_cast<NSString *>(screen_->authPasswdData) release];
221 screen_->authPasswdData = NULL;
224 if (NSString *password = [settings objectForKey:@"Password"])
225 if ([password length] != 0)
226 screen_->authPasswdData = [password retain];
228 NSNumber *cursor = [settings objectForKey:@"ShowCursor"];
229 cursor_ = cursor == nil ? true : [cursor boolValue];
232 AshikaseSetEnabled(cursor_, true);
236 static void VNCNotifySettings(
237 CFNotificationCenterRef center,
246 static rfbBool VNCCheck(rfbClientPtr client, const char *data, int size) {
247 @synchronized (condition_) {
248 if (NSString *password = reinterpret_cast<NSString *>(screen_->authPasswdData)) {
249 rfbEncryptBytes(client->authChallenge, const_cast<char *>([password UTF8String]));
250 return memcmp(client->authChallenge, data, size) == 0;
255 static void VNCPointer(int buttons, int x, int y, rfbClientPtr client) {
257 int diff = buttons_ ^ buttons;
258 bool twas((buttons_ & 0x1) != 0);
259 bool tis((buttons & 0x1) != 0);
262 rfbDefaultPtrAddEvent(buttons, x, y, client);
264 if (Ashikase(false)) {
265 AshikaseSendEvent(x, y, buttons);
269 mach_port_t purple(0);
271 if ((diff & 0x10) != 0) {
272 struct GSEventRecord record;
274 memset(&record, 0, sizeof(record));
276 record.type = (buttons & 0x4) != 0 ?
277 GSEventTypeHeadsetButtonDown :
278 GSEventTypeHeadsetButtonUp;
280 record.timestamp = GSCurrentEventTimestamp();
283 GSSendSystemEvent(&record);
286 if ((diff & 0x04) != 0) {
287 struct GSEventRecord record;
289 memset(&record, 0, sizeof(record));
291 record.type = (buttons & 0x4) != 0 ?
292 GSEventTypeMenuButtonDown :
293 GSEventTypeMenuButtonUp;
295 record.timestamp = GSCurrentEventTimestamp();
298 GSSendSystemEvent(&record);
301 if ((diff & 0x02) != 0) {
302 struct GSEventRecord record;
304 memset(&record, 0, sizeof(record));
306 record.type = (buttons & 0x2) != 0 ?
307 GSEventTypeLockButtonDown :
308 GSEventTypeLockButtonUp;
310 record.timestamp = GSCurrentEventTimestamp();
313 GSSendSystemEvent(&record);
316 if (twas != tis || tis) {
318 struct GSEventRecord record;
320 struct GSEventRecordInfo info;
321 struct GSPathInfo path;
325 memset(&event, 0, sizeof(event));
327 event.record.type = GSEventTypeMouse;
328 event.record.locationInWindow.x = x;
329 event.record.locationInWindow.y = y;
330 event.record.timestamp = GSCurrentEventTimestamp();
331 event.record.size = sizeof(event.data);
333 event.data.info.handInfo.type = twas == tis ?
334 GSMouseEventTypeDragged :
336 GSMouseEventTypeDown :
339 event.data.info.handInfo.x34 = 0x1;
340 event.data.info.handInfo.x38 = tis ? 0x1 : 0x0;
342 event.data.info.pathPositions = 1;
344 event.data.path.x00 = 0x01;
345 event.data.path.x01 = 0x02;
346 event.data.path.x02 = tis ? 0x03 : 0x00;
347 event.data.path.position = event.record.locationInWindow;
351 if (CAWindowServer *server = [CAWindowServer serverIfRunning]) {
352 NSArray *displays([server displays]);
353 if (displays != nil && [displays count] != 0)
354 if (CAWindowServerDisplay *display = [displays objectAtIndex:0])
355 port = [display clientPortAtPosition:event.record.locationInWindow];
360 purple = (*GSTakePurpleSystemEventPort)();
364 FixRecord(&event.record);
365 GSSendEvent(&event.record, port);
368 if (purple != 0 && PurpleAllocated)
369 mach_port_deallocate(mach_task_self(), purple);
372 static void VNCKeyboard(rfbBool down, rfbKeySym key, rfbClientPtr client) {
377 case XK_Return: key = '\r'; break;
378 case XK_BackSpace: key = 0x7f; break;
384 GSEventRef event(_GSCreateSyntheticKeyEvent(key, YES, YES));
385 GSEventRecord *record(_GSEventGetGSEventRecord(event));
386 record->type = GSEventTypeKeyDown;
390 if (CAWindowServer *server = [CAWindowServer serverIfRunning]) {
391 NSArray *displays([server displays]);
392 if (displays != nil && [displays count] != 0)
393 if (CAWindowServerDisplay *display = [displays objectAtIndex:0])
394 port = [display clientPortAtPosition:CGPointMake(x_, y_)];
397 mach_port_t purple(0);
401 purple = (*GSTakePurpleSystemEventPort)();
406 GSSendEvent(record, port);
408 if (purple != 0 && PurpleAllocated)
409 mach_port_deallocate(mach_task_self(), purple);
414 static void VNCDisconnect(rfbClientPtr client) {
415 @synchronized (condition_) {
417 [VNCBridge performSelectorOnMainThread:@selector(removeStatusBarItem) withObject:nil waitUntilDone:YES];
421 static rfbNewClientAction VNCClient(rfbClientPtr client) {
422 @synchronized (condition_) {
423 if (screen_->authPasswdData != NULL) {
424 [VNCBridge performSelectorOnMainThread:@selector(registerClient) withObject:nil waitUntilDone:YES];
425 client->clientGoneHook = &VNCDisconnect;
426 return RFB_CLIENT_ACCEPT;
432 [VNCBridge performSelectorOnMainThread:@selector(askForConnection) withObject:nil waitUntilDone:NO];
433 while (action_ == RFB_CLIENT_ON_HOLD)
435 rfbNewClientAction action(action_);
436 action_ = RFB_CLIENT_ON_HOLD;
439 if (action == RFB_CLIENT_ACCEPT)
440 client->clientGoneHook = &VNCDisconnect;
444 static rfbPixel black_[320][480];
446 static void VNCSetup() {
447 @synchronized (condition_) {
449 char *arg0(strdup("VNCServer"));
450 char *argv[] = {arg0, NULL};
451 screen_ = rfbGetScreen(&argc, argv, Width, Height, BitsPerSample, 3, BytesPerPixel);
457 screen_->desktopName = strdup([[[NSProcessInfo processInfo] hostName] UTF8String]);
459 screen_->alwaysShared = TRUE;
460 screen_->handleEventsEagerly = TRUE;
461 screen_->deferUpdateTime = 5;
463 screen_->serverFormat.redShift = BitsPerSample * 2;
464 screen_->serverFormat.greenShift = BitsPerSample * 1;
465 screen_->serverFormat.blueShift = BitsPerSample * 0;
467 screen_->frameBuffer = reinterpret_cast<char *>(black_);
469 screen_->kbdAddEvent = &VNCKeyboard;
470 screen_->ptrAddEvent = &VNCPointer;
472 screen_->newClientHook = &VNCClient;
473 screen_->passwordCheck = &VNCCheck;
475 char data[0], mask[0];
476 rfbCursorPtr cursor = rfbMakeXCursor(0, 0, data, mask);
477 rfbSetCursor(screen_, cursor);
480 static void VNCEnabled() {
484 if (NSDictionary *settings = [NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/Library/Preferences/com.saurik.Veency.plist", NSHomeDirectory()]])
485 if (NSNumber *number = [settings objectForKey:@"Enabled"])
486 enabled = [number boolValue];
488 if (enabled != running_)
491 screen_->socketState = RFB_SOCKET_INIT;
492 rfbInitServer(screen_);
493 rfbRunEventLoop(screen_, -1, true);
495 rfbShutdownServer(screen_, true);
502 static void VNCNotifyEnabled(
503 CFNotificationCenterRef center,
512 MSHook(kern_return_t, IOMobileFramebufferSwapSetLayer,
513 IOMobileFramebufferRef fb,
515 CoreSurfaceBufferRef buffer,
520 if (_unlikely(screen_ == NULL)) {
523 } else if (_unlikely(clients_ != 0)) {
525 screen_->frameBuffer = reinterpret_cast<char *>(black_);
527 CoreSurfaceBufferLock(buffer, 2);
528 rfbPixel (*data)[480] = reinterpret_cast<rfbPixel (*)[480]>(CoreSurfaceBufferGetBaseAddress(buffer));
529 screen_->frameBuffer = const_cast<char *>(reinterpret_cast<volatile char *>(data));
530 CoreSurfaceBufferUnlock(buffer);
533 rfbMarkRectAsModified(screen_, 0, 0, Width, Height);
536 return _IOMobileFramebufferSwapSetLayer(fb, layer, buffer, bounds, frame, flags);
539 MSHook(void, rfbRegisterSecurityHandler, rfbSecurityHandler *handler) {
540 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
542 @synchronized (lock_) {
543 [handlers_ addObject:[NSValue valueWithPointer:handler]];
544 _rfbRegisterSecurityHandler(handler);
551 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
553 MSHookSymbol(GSTakePurpleSystemEventPort, "GSGetPurpleSystemEventPort");
554 if (GSTakePurpleSystemEventPort == NULL) {
555 MSHookSymbol(GSTakePurpleSystemEventPort, "GSCopyPurpleSystemEventPort");
556 PurpleAllocated = true;
559 Two_ = dlsym(RTLD_DEFAULT, "GSEventGetWindowContextId") == NULL;
561 MSHookFunction(&IOMobileFramebufferSwapSetLayer, MSHake(IOMobileFramebufferSwapSetLayer));
562 MSHookFunction(&rfbRegisterSecurityHandler, MSHake(rfbRegisterSecurityHandler));
564 $VNCAlertItem = objc_allocateClassPair(objc_getClass("SBAlertItem"), "VNCAlertItem", 0);
565 MSAddMessage2(VNCAlertItem, "v@:@i", alertSheet,buttonClicked);
566 MSAddMessage2(VNCAlertItem, "v@:cc", configure,requirePasscodeForActions);
567 MSAddMessage0(VNCAlertItem, "v@:", performUnlockAction);
568 objc_registerClassPair($VNCAlertItem);
570 CFNotificationCenterAddObserver(
571 CFNotificationCenterGetDarwinNotifyCenter(),
572 NULL, &VNCNotifyEnabled, CFSTR("com.saurik.Veency-Enabled"), NULL, 0
575 CFNotificationCenterAddObserver(
576 CFNotificationCenterGetDarwinNotifyCenter(),
577 NULL, &VNCNotifySettings, CFSTR("com.saurik.Veency-Settings"), NULL, 0
580 condition_ = [[NSCondition alloc] init];
581 lock_ = [[NSLock alloc] init];
582 handlers_ = [[NSMutableSet alloc] init];
589 cfTrue_ = CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&value), sizeof(value));
592 cfFalse_ = CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&value), sizeof(value));
594 cfEvent_ = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&event_), sizeof(event_), kCFAllocatorNull);