1 /* Veency - VNC Remote Access Server for iPhoneOS
2 * Copyright (C) 2008 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.
38 #include <substrate.h>
41 #include <rfb/keysym.h>
43 #include <mach/mach_port.h>
45 #import <QuartzCore/CAWindowServer.h>
46 #import <QuartzCore/CAWindowServerDisplay.h>
48 #import <CoreGraphics/CGGeometry.h>
49 #import <GraphicsServices/GraphicsServices.h>
50 #import <Foundation/Foundation.h>
51 #import <IOMobileFramebuffer/IOMobileFramebuffer.h>
52 #import <IOKit/IOKitLib.h>
53 #import <UIKit/UIKit.h>
55 #import <SpringBoard/SBAlertItemsController.h>
56 #import <SpringBoard/SBDismissOnlyAlertItem.h>
57 #import <SpringBoard/SBStatusBarController.h>
59 #define IOMobileFramebuffer "/System/Library/PrivateFrameworks/IOMobileFramebuffer.framework/IOMobileFramebuffer"
61 static const size_t Width = 320;
62 static const size_t Height = 480;
63 static const size_t BytesPerPixel = 4;
64 static const size_t BitsPerSample = 8;
66 static const size_t Stride = Width * BytesPerPixel;
67 static const size_t Size32 = Width * Height;
68 static const size_t Size8 = Size32 * BytesPerPixel;
70 static pthread_t thread_;
71 static rfbScreenInfoPtr screen_;
76 static unsigned clients_;
78 static Class $VNCAlertItem;
79 static Class $SBAlertItemsController;
80 static Class $SBStatusBarController;
82 static rfbNewClientAction action_ = RFB_CLIENT_ON_HOLD;
83 static NSCondition *condition_;
85 static rfbClientPtr client_;
87 static void VNCAccept() {
88 action_ = RFB_CLIENT_ACCEPT;
90 [[$SBStatusBarController sharedStatusBarController] addStatusBarItem:@"Veency"];
93 void VNCAlertItem$alertSheet$buttonClicked$(id self, SEL sel, id sheet, int button) {
102 action_ = RFB_CLIENT_REFUSE;
111 void VNCAlertItem$configure$requirePasscodeForActions$(id self, SEL sel, BOOL configure, BOOL require) {
112 UIModalView *sheet([self alertSheet]);
113 [sheet setDelegate:self];
114 [sheet setTitle:@"Remote Access Request"];
115 [sheet setBodyText:[NSString stringWithFormat:@"Accept connection from\n%s?\n\nVeency VNC Server\nby Jay Freeman (saurik)\nsaurik@saurik.com\nhttp://www.saurik.com/", client_->host]];
116 [sheet addButtonWithTitle:@"Accept"];
117 [sheet addButtonWithTitle:@"Reject"];
120 void VNCAlertItem$performUnlockAction(id self, SEL sel) {
121 [[$SBAlertItemsController sharedInstance] activateAlertItem:self];
124 @interface VNCBridge : NSObject {
127 + (void) askForConnection;
128 + (void) removeStatusBarItem;
132 @implementation VNCBridge
134 + (void) askForConnection {
141 id item = [[[$VNCAlertItem alloc] init] autorelease];
142 [[$SBAlertItemsController sharedInstance] activateAlertItem:item];
146 + (void) removeStatusBarItem {
147 [[$SBStatusBarController sharedStatusBarController] removeStatusBarItem:@"Veency"];
152 static mach_port_t (*GSTakePurpleSystemEventPort)(void);
153 static bool PurpleAllocated;
155 static void VNCPointer(int buttons, int x, int y, rfbClientPtr client) {
157 int diff = buttons_ ^ buttons;
158 bool twas((buttons_ & 0x1) != 0);
159 bool tis((buttons & 0x1) != 0);
162 rfbDefaultPtrAddEvent(buttons, x, y, client);
164 mach_port_t purple(0);
166 if ((diff & 0x10) != 0) {
167 struct GSEventRecord record;
169 memset(&record, 0, sizeof(record));
171 record.type = (buttons & 0x4) != 0 ?
172 GSEventTypeHeadsetButtonDown :
173 GSEventTypeHeadsetButtonUp;
175 record.timestamp = GSCurrentEventTimestamp();
177 GSSendSystemEvent(&record);
180 if ((diff & 0x04) != 0) {
181 struct GSEventRecord record;
183 memset(&record, 0, sizeof(record));
185 record.type = (buttons & 0x4) != 0 ?
186 GSEventTypeMenuButtonDown :
187 GSEventTypeMenuButtonUp;
189 record.timestamp = GSCurrentEventTimestamp();
191 GSSendSystemEvent(&record);
194 if ((diff & 0x02) != 0) {
195 struct GSEventRecord record;
197 memset(&record, 0, sizeof(record));
199 record.type = (buttons & 0x2) != 0 ?
200 GSEventTypeLockButtonDown :
201 GSEventTypeLockButtonUp;
203 record.timestamp = GSCurrentEventTimestamp();
205 GSSendSystemEvent(&record);
208 if (twas != tis || tis) {
210 struct GSEventRecord record;
212 struct GSEventRecordInfo info;
213 struct GSPathInfo path;
217 memset(&event, 0, sizeof(event));
219 event.record.type = GSEventTypeMouse;
220 event.record.locationInWindow.x = x;
221 event.record.locationInWindow.y = y;
222 event.record.timestamp = GSCurrentEventTimestamp();
223 event.record.size = sizeof(event.data);
225 event.data.info.handInfo.type = twas == tis ?
226 GSMouseEventTypeDragged :
228 GSMouseEventTypeDown :
231 event.data.info.handInfo.x34 = 0x1;
232 event.data.info.handInfo.x38 = tis ? 0x1 : 0x0;
234 event.data.info.pathPositions = 1;
236 event.data.path.x00 = 0x01;
237 event.data.path.x01 = 0x02;
238 event.data.path.x02 = tis ? 0x03 : 0x00;
239 event.data.path.position = event.record.locationInWindow;
243 if (CAWindowServer *server = [CAWindowServer serverIfRunning]) {
244 NSArray *displays([server displays]);
245 if (displays != nil && [displays count] != 0)
246 if (CAWindowServerDisplay *display = [displays objectAtIndex:0])
247 port = [display clientPortAtPosition:event.record.locationInWindow];
252 purple = (*GSTakePurpleSystemEventPort)();
256 GSSendEvent(&event.record, port);
259 if (purple != 0 && PurpleAllocated)
260 mach_port_deallocate(mach_task_self(), purple);
263 static void VNCKeyboard(rfbBool down, rfbKeySym key, rfbClientPtr client) {
268 case XK_Return: key = '\r'; break;
269 case XK_BackSpace: key = 0x7f; break;
275 GSEventRef event(_GSCreateSyntheticKeyEvent(key, YES, YES));
276 GSEventRecord *record(_GSEventGetGSEventRecord(event));
277 record->type = GSEventTypeKeyDown;
281 if (CAWindowServer *server = [CAWindowServer serverIfRunning]) {
282 NSArray *displays([server displays]);
283 if (displays != nil && [displays count] != 0)
284 if (CAWindowServerDisplay *display = [displays objectAtIndex:0])
285 port = [display clientPortAtPosition:CGPointMake(x_, y_)];
288 mach_port_t purple(0);
292 purple = (*GSTakePurpleSystemEventPort)();
297 GSSendEvent(record, port);
299 if (purple != 0 && PurpleAllocated)
300 mach_port_deallocate(mach_task_self(), purple);
305 static void VNCDisconnect(rfbClientPtr client) {
307 [VNCBridge performSelectorOnMainThread:@selector(removeStatusBarItem) withObject:nil waitUntilDone:NO];
310 static rfbNewClientAction VNCClient(rfbClientPtr client) {
313 [VNCBridge performSelectorOnMainThread:@selector(askForConnection) withObject:nil waitUntilDone:NO];
314 while (action_ == RFB_CLIENT_ON_HOLD)
316 rfbNewClientAction action(action_);
317 action_ = RFB_CLIENT_ON_HOLD;
319 if (action == RFB_CLIENT_ACCEPT)
320 client->clientGoneHook = &VNCDisconnect;
324 static rfbPixel black_[320][480];
326 static void *VNCServer(IOMobileFramebufferRef fb) {
327 CGRect rect(CGRectMake(0, 0, Width, Height));
329 /*CoreSurfaceBufferRef surface(NULL);
330 kern_return_t value(IOMobileFramebufferGetLayerDefaultSurface(fb, 0, &surface));
334 condition_ = [[NSCondition alloc] init];
337 char *arg0(strdup("VNCServer"));
338 char *argv[] = {arg0, NULL};
340 screen_ = rfbGetScreen(&argc, argv, Width, Height, BitsPerSample, 3, BytesPerPixel);
341 screen_->desktopName = "iPhone";
342 screen_->alwaysShared = TRUE;
343 screen_->handleEventsEagerly = TRUE;
344 screen_->deferUpdateTime = 5;
346 screen_->serverFormat.redShift = BitsPerSample * 2;
347 screen_->serverFormat.greenShift = BitsPerSample * 1;
348 screen_->serverFormat.blueShift = BitsPerSample * 0;
350 /*io_service_t service(IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("IOCoreSurfaceRoot")));
351 CFMutableDictionaryRef properties(NULL);
352 IORegistryEntryCreateCFProperties(service, &properties, kCFAllocatorDefault, kNilOptions);
354 CoreSurfaceBufferLock(surface, kCoreSurfaceLockTypeGimmeVRAM);
355 screen_->frameBuffer = reinterpret_cast<char *>(CoreSurfaceBufferGetBaseAddress(surface));
356 CoreSurfaceBufferUnlock(surface);
357 CFRelease(surface);*/
359 screen_->frameBuffer = reinterpret_cast<char *>(black_);
361 screen_->kbdAddEvent = &VNCKeyboard;
362 screen_->ptrAddEvent = &VNCPointer;
364 screen_->newClientHook = &VNCClient;
366 /*char data[0], mask[0];
367 rfbCursorPtr cursor = rfbMakeXCursor(0, 0, data, mask);
368 rfbSetCursor(screen_, cursor);*/
370 rfbInitServer(screen_);
373 rfbRunEventLoop(screen_, -1, true);
374 NSLog(@"rfbRunEventLoop().");
378 rfbScreenCleanup(screen_);
384 MSHook(kern_return_t, IOMobileFramebufferSwapSetLayer,
385 IOMobileFramebufferRef fb,
387 CoreSurfaceBufferRef buffer,
393 bounds.origin.x != 0 || bounds.origin.y != 0 || bounds.size.width != 320 || bounds.size.height != 480 ||
394 frame.origin.x != 0 || frame.origin.y != 0 || frame.size.width != 320 || frame.size.height != 480
395 ) NSLog(@"VNC:%f,%f:%f,%f:%f,%f:%f,%f",
396 bounds.origin.x, bounds.origin.y, bounds.size.width, bounds.size.height,
397 frame.origin.x, frame.origin.y, frame.size.width, frame.size.height
402 screen_->frameBuffer = reinterpret_cast<char *>(black_);
404 CoreSurfaceBufferLock(buffer, 2);
405 rfbPixel (*data)[480] = reinterpret_cast<rfbPixel (*)[480]>(CoreSurfaceBufferGetBaseAddress(buffer));
406 screen_->frameBuffer = const_cast<char *>(reinterpret_cast<volatile char *>(data));
407 CoreSurfaceBufferUnlock(buffer);
411 kern_return_t value(_IOMobileFramebufferSwapSetLayer(fb, layer, buffer, bounds, frame, flags));
414 pthread_create(&thread_, NULL, &VNCServer, fb);
416 rfbMarkRectAsModified(screen_, 0, 0, Width, Height);
421 extern "C" void TweakInitialize() {
422 GSTakePurpleSystemEventPort = reinterpret_cast<mach_port_t (*)()>(dlsym(RTLD_DEFAULT, "GSGetPurpleSystemEventPort"));
423 if (GSTakePurpleSystemEventPort == NULL) {
424 GSTakePurpleSystemEventPort = reinterpret_cast<mach_port_t (*)()>(dlsym(RTLD_DEFAULT, "GSCopyPurpleSystemEventPort"));
425 PurpleAllocated = true;
428 MSHookFunction(&IOMobileFramebufferSwapSetLayer, &$IOMobileFramebufferSwapSetLayer, &_IOMobileFramebufferSwapSetLayer);
430 $SBAlertItemsController = objc_getClass("SBAlertItemsController");
431 $SBStatusBarController = objc_getClass("SBStatusBarController");
433 $VNCAlertItem = objc_allocateClassPair(objc_getClass("SBAlertItem"), "VNCAlertItem", 0);
434 class_addMethod($VNCAlertItem, @selector(alertSheet:buttonClicked:), (IMP) &VNCAlertItem$alertSheet$buttonClicked$, "v@:@i");
435 class_addMethod($VNCAlertItem, @selector(configure:requirePasscodeForActions:), (IMP) &VNCAlertItem$configure$requirePasscodeForActions$, "v@:cc");
436 class_addMethod($VNCAlertItem, @selector(performUnlockAction), (IMP) VNCAlertItem$performUnlockAction, "v@:");
437 objc_registerClassPair($VNCAlertItem);