1 /* Veency - VNC Remote Access Server for iPhoneOS
2 * Copyright (C) 2008-2009 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__)
41 #include <substrate.h>
44 #include <rfb/keysym.h>
46 #include <mach/mach_port.h>
48 #import <QuartzCore/CAWindowServer.h>
49 #import <QuartzCore/CAWindowServerDisplay.h>
51 #import <CoreGraphics/CGGeometry.h>
52 #import <GraphicsServices/GraphicsServices.h>
53 #import <Foundation/Foundation.h>
54 #import <IOMobileFramebuffer/IOMobileFramebuffer.h>
55 #import <IOKit/IOKitLib.h>
56 #import <UIKit/UIKit.h>
58 #import <SpringBoard/SBAlertItemsController.h>
59 #import <SpringBoard/SBDismissOnlyAlertItem.h>
60 #import <SpringBoard/SBStatusBarController.h>
62 static const size_t Width = 320;
63 static const size_t Height = 480;
64 static const size_t BytesPerPixel = 4;
65 static const size_t BitsPerSample = 8;
67 static const size_t Stride = Width * BytesPerPixel;
68 static const size_t Size32 = Width * Height;
69 static const size_t Size8 = Size32 * BytesPerPixel;
71 static NSMutableSet *handlers_;
72 static rfbScreenInfoPtr screen_;
77 static unsigned clients_;
79 MSClassHook(SBAlertItemsController)
80 MSClassHook(SBStatusBarController)
83 static Class $VNCAlertItem;
85 static rfbNewClientAction action_ = RFB_CLIENT_ON_HOLD;
86 static NSCondition *condition_;
89 static rfbClientPtr client_;
91 static void VNCAccept() {
92 action_ = RFB_CLIENT_ACCEPT;
94 [[$SBStatusBarController sharedStatusBarController] addStatusBarItem:@"Veency"];
97 MSInstanceMessage2(void, VNCAlertItem, alertSheet,buttonClicked, id, sheet, int, button) {
106 action_ = RFB_CLIENT_REFUSE;
115 MSInstanceMessage2(void, VNCAlertItem, configure,requirePasscodeForActions, BOOL, configure, BOOL, require) {
116 UIModalView *sheet([self alertSheet]);
117 [sheet setDelegate:self];
118 [sheet setTitle:@"Remote Access Request"];
119 [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]];
120 [sheet addButtonWithTitle:@"Accept"];
121 [sheet addButtonWithTitle:@"Reject"];
124 MSInstanceMessage0(void, VNCAlertItem, performUnlockAction) {
125 [[$SBAlertItemsController sharedInstance] activateAlertItem:self];
128 @interface VNCBridge : NSObject {
131 + (void) askForConnection;
132 + (void) removeStatusBarItem;
136 @implementation VNCBridge
138 + (void) askForConnection {
139 [[$SBAlertItemsController sharedInstance] activateAlertItem:[[[$VNCAlertItem alloc] init] autorelease]];
142 + (void) removeStatusBarItem {
143 [[$SBStatusBarController sharedStatusBarController] removeStatusBarItem:@"Veency"];
148 static mach_port_t (*GSTakePurpleSystemEventPort)(void);
149 static bool PurpleAllocated;
152 static void FixRecord(GSEventRecord *record) {
154 memmove(&record->windowContextId, &record->windowContextId + 1, sizeof(*record) - (reinterpret_cast<uint8_t *>(&record->windowContextId + 1) - reinterpret_cast<uint8_t *>(record)) + record->size);
157 static void VNCSettings() {
158 NSDictionary *settings([NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/Library/Preferences/com.saurik.Veency.plist", NSHomeDirectory()]]);
160 @synchronized (lock_) {
161 for (NSValue *handler in handlers_)
162 rfbUnregisterSecurityHandler(reinterpret_cast<rfbSecurityHandler *>([handler pointerValue]));
163 [handlers_ removeAllObjects];
166 @synchronized (condition_) {
170 [reinterpret_cast<NSString *>(screen_->authPasswdData) release];
171 screen_->authPasswdData = NULL;
173 if (NSString *password = [settings objectForKey:@"Password"])
174 if ([password length] != 0)
175 screen_->authPasswdData = [password retain];
179 static void VNCNotifySettings(
180 CFNotificationCenterRef center,
189 static rfbBool VNCCheck(rfbClientPtr client, const char *data, int size) {
190 @synchronized (condition_) {
191 if (NSString *password = reinterpret_cast<NSString *>(screen_->authPasswdData)) {
192 rfbEncryptBytes(client->authChallenge, const_cast<char *>([password UTF8String]));
193 return memcmp(client->authChallenge, data, size) == 0;
198 static void VNCPointer(int buttons, int x, int y, rfbClientPtr client) {
200 int diff = buttons_ ^ buttons;
201 bool twas((buttons_ & 0x1) != 0);
202 bool tis((buttons & 0x1) != 0);
205 rfbDefaultPtrAddEvent(buttons, x, y, client);
207 mach_port_t purple(0);
209 if ((diff & 0x10) != 0) {
210 struct GSEventRecord record;
212 memset(&record, 0, sizeof(record));
214 record.type = (buttons & 0x4) != 0 ?
215 GSEventTypeHeadsetButtonDown :
216 GSEventTypeHeadsetButtonUp;
218 record.timestamp = GSCurrentEventTimestamp();
221 GSSendSystemEvent(&record);
224 if ((diff & 0x04) != 0) {
225 struct GSEventRecord record;
227 memset(&record, 0, sizeof(record));
229 record.type = (buttons & 0x4) != 0 ?
230 GSEventTypeMenuButtonDown :
231 GSEventTypeMenuButtonUp;
233 record.timestamp = GSCurrentEventTimestamp();
236 GSSendSystemEvent(&record);
239 if ((diff & 0x02) != 0) {
240 struct GSEventRecord record;
242 memset(&record, 0, sizeof(record));
244 record.type = (buttons & 0x2) != 0 ?
245 GSEventTypeLockButtonDown :
246 GSEventTypeLockButtonUp;
248 record.timestamp = GSCurrentEventTimestamp();
251 GSSendSystemEvent(&record);
254 if (twas != tis || tis) {
256 struct GSEventRecord record;
258 struct GSEventRecordInfo info;
259 struct GSPathInfo path;
263 memset(&event, 0, sizeof(event));
265 event.record.type = GSEventTypeMouse;
266 event.record.locationInWindow.x = x;
267 event.record.locationInWindow.y = y;
268 event.record.timestamp = GSCurrentEventTimestamp();
269 event.record.size = sizeof(event.data);
271 event.data.info.handInfo.type = twas == tis ?
272 GSMouseEventTypeDragged :
274 GSMouseEventTypeDown :
277 event.data.info.handInfo.x34 = 0x1;
278 event.data.info.handInfo.x38 = tis ? 0x1 : 0x0;
280 event.data.info.pathPositions = 1;
282 event.data.path.x00 = 0x01;
283 event.data.path.x01 = 0x02;
284 event.data.path.x02 = tis ? 0x03 : 0x00;
285 event.data.path.position = event.record.locationInWindow;
289 if (CAWindowServer *server = [CAWindowServer serverIfRunning]) {
290 NSArray *displays([server displays]);
291 if (displays != nil && [displays count] != 0)
292 if (CAWindowServerDisplay *display = [displays objectAtIndex:0])
293 port = [display clientPortAtPosition:event.record.locationInWindow];
298 purple = (*GSTakePurpleSystemEventPort)();
302 FixRecord(&event.record);
303 GSSendEvent(&event.record, port);
306 if (purple != 0 && PurpleAllocated)
307 mach_port_deallocate(mach_task_self(), purple);
310 static void VNCKeyboard(rfbBool down, rfbKeySym key, rfbClientPtr client) {
315 case XK_Return: key = '\r'; break;
316 case XK_BackSpace: key = 0x7f; break;
322 GSEventRef event(_GSCreateSyntheticKeyEvent(key, YES, YES));
323 GSEventRecord *record(_GSEventGetGSEventRecord(event));
324 record->type = GSEventTypeKeyDown;
328 if (CAWindowServer *server = [CAWindowServer serverIfRunning]) {
329 NSArray *displays([server displays]);
330 if (displays != nil && [displays count] != 0)
331 if (CAWindowServerDisplay *display = [displays objectAtIndex:0])
332 port = [display clientPortAtPosition:CGPointMake(x_, y_)];
335 mach_port_t purple(0);
339 purple = (*GSTakePurpleSystemEventPort)();
344 GSSendEvent(record, port);
346 if (purple != 0 && PurpleAllocated)
347 mach_port_deallocate(mach_task_self(), purple);
352 static void VNCDisconnect(rfbClientPtr client) {
354 [VNCBridge performSelectorOnMainThread:@selector(removeStatusBarItem) withObject:nil waitUntilDone:NO];
357 static rfbNewClientAction VNCClient(rfbClientPtr client) {
358 @synchronized (condition_) {
359 if (screen_->authPasswdData != NULL)
360 return RFB_CLIENT_ACCEPT;
365 [VNCBridge performSelectorOnMainThread:@selector(askForConnection) withObject:nil waitUntilDone:NO];
366 while (action_ == RFB_CLIENT_ON_HOLD)
368 rfbNewClientAction action(action_);
369 action_ = RFB_CLIENT_ON_HOLD;
371 if (action == RFB_CLIENT_ACCEPT)
372 client->clientGoneHook = &VNCDisconnect;
376 static rfbPixel black_[320][480];
378 static void VNCSetup() {
379 @synchronized (condition_) {
381 char *arg0(strdup("VNCServer"));
382 char *argv[] = {arg0, NULL};
383 screen_ = rfbGetScreen(&argc, argv, Width, Height, BitsPerSample, 3, BytesPerPixel);
389 screen_->desktopName = strdup([[[NSProcessInfo processInfo] hostName] UTF8String]);
391 screen_->alwaysShared = TRUE;
392 screen_->handleEventsEagerly = TRUE;
393 screen_->deferUpdateTime = 5;
395 screen_->serverFormat.redShift = BitsPerSample * 2;
396 screen_->serverFormat.greenShift = BitsPerSample * 1;
397 screen_->serverFormat.blueShift = BitsPerSample * 0;
399 screen_->frameBuffer = reinterpret_cast<char *>(black_);
401 screen_->kbdAddEvent = &VNCKeyboard;
402 screen_->ptrAddEvent = &VNCPointer;
404 screen_->newClientHook = &VNCClient;
405 screen_->passwordCheck = &VNCCheck;
407 /*char data[0], mask[0];
408 rfbCursorPtr cursor = rfbMakeXCursor(0, 0, data, mask);
409 rfbSetCursor(screen_, cursor);*/
412 static void VNCEnabled() {
416 if (NSDictionary *settings = [NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/Library/Preferences/com.saurik.Veency.plist", NSHomeDirectory()]])
417 if (NSNumber *number = [settings objectForKey:@"Enabled"])
418 enabled = [number boolValue];
419 if (enabled != running_)
422 screen_->socketState = RFB_SOCKET_INIT;
423 rfbInitServer(screen_);
424 rfbRunEventLoop(screen_, -1, true);
426 rfbShutdownServer(screen_, true);
433 static void VNCNotifyEnabled(
434 CFNotificationCenterRef center,
443 MSHook(kern_return_t, IOMobileFramebufferSwapSetLayer,
444 IOMobileFramebufferRef fb,
446 CoreSurfaceBufferRef buffer,
453 screen_->frameBuffer = reinterpret_cast<char *>(black_);
455 CoreSurfaceBufferLock(buffer, 2);
456 rfbPixel (*data)[480] = reinterpret_cast<rfbPixel (*)[480]>(CoreSurfaceBufferGetBaseAddress(buffer));
457 screen_->frameBuffer = const_cast<char *>(reinterpret_cast<volatile char *>(data));
458 CoreSurfaceBufferUnlock(buffer);
461 rfbMarkRectAsModified(screen_, 0, 0, Width, Height);
464 return _IOMobileFramebufferSwapSetLayer(fb, layer, buffer, bounds, frame, flags);
467 MSHook(void, rfbRegisterSecurityHandler, rfbSecurityHandler *handler) {
468 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
470 @synchronized (lock_) {
471 [handlers_ addObject:[NSValue valueWithPointer:handler]];
472 _rfbRegisterSecurityHandler(handler);
479 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
481 MSHookSymbol(GSTakePurpleSystemEventPort, "GSGetPurpleSystemEventPort");
482 if (GSTakePurpleSystemEventPort == NULL) {
483 MSHookSymbol(GSTakePurpleSystemEventPort, "GSCopyPurpleSystemEventPort");
484 PurpleAllocated = true;
487 Two_ = dlsym(RTLD_DEFAULT, "GSEventGetWindowContextId") == NULL;
489 MSHookFunction(&IOMobileFramebufferSwapSetLayer, MSHake(IOMobileFramebufferSwapSetLayer));
490 MSHookFunction(&rfbRegisterSecurityHandler, MSHake(rfbRegisterSecurityHandler));
492 $VNCAlertItem = objc_allocateClassPair(objc_getClass("SBAlertItem"), "VNCAlertItem", 0);
493 MSAddMessage2(VNCAlertItem, "v@:@i", alertSheet,buttonClicked);
494 MSAddMessage2(VNCAlertItem, "v@:cc", configure,requirePasscodeForActions);
495 MSAddMessage0(VNCAlertItem, "v@:", performUnlockAction);
496 objc_registerClassPair($VNCAlertItem);
498 CFNotificationCenterAddObserver(
499 CFNotificationCenterGetDarwinNotifyCenter(),
500 NULL, &VNCNotifyEnabled, CFSTR("com.saurik.Veency-Enabled"), NULL, 0
503 CFNotificationCenterAddObserver(
504 CFNotificationCenterGetDarwinNotifyCenter(),
505 NULL, &VNCNotifySettings, CFSTR("com.saurik.Veency-Settings"), NULL, 0
508 condition_ = [[NSCondition alloc] init];
509 lock_ = [[NSLock alloc] init];
510 handlers_ = [[NSMutableSet alloc] init];