Ported Veency to 3.x.
[veency.git] / Tweak.mm
1 /* Veency - VNC Remote Access Server for iPhoneOS
2 * Copyright (C) 2008 Jay Freeman (saurik)
3 */
4
5 /*
6 * Redistribution and use in source and binary
7 * forms, with or without modification, are permitted
8 * provided that the following conditions are met:
9 *
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
17 * distribution.
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.
21 *
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.
36 */
37
38 #include <substrate.h>
39
40 #include <rfb/rfb.h>
41 #include <rfb/keysym.h>
42
43 #include <mach/mach_port.h>
44
45 #import <QuartzCore/CAWindowServer.h>
46 #import <QuartzCore/CAWindowServerDisplay.h>
47
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>
54
55 #import <SpringBoard/SBAlertItemsController.h>
56 #import <SpringBoard/SBDismissOnlyAlertItem.h>
57 #import <SpringBoard/SBStatusBarController.h>
58
59 #define IOMobileFramebuffer "/System/Library/PrivateFrameworks/IOMobileFramebuffer.framework/IOMobileFramebuffer"
60
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;
65
66 static const size_t Stride = Width * BytesPerPixel;
67 static const size_t Size32 = Width * Height;
68 static const size_t Size8 = Size32 * BytesPerPixel;
69
70 static pthread_t thread_;
71 static rfbScreenInfoPtr screen_;
72 static bool running_;
73 static int buttons_;
74 static int x_, y_;
75
76 static unsigned clients_;
77
78 static Class $VNCAlertItem;
79 static Class $SBAlertItemsController;
80 static Class $SBStatusBarController;
81
82 static rfbNewClientAction action_ = RFB_CLIENT_ON_HOLD;
83 static NSCondition *condition_;
84
85 static rfbClientPtr client_;
86
87 static void VNCAccept() {
88 action_ = RFB_CLIENT_ACCEPT;
89 ++clients_;
90 [[$SBStatusBarController sharedStatusBarController] addStatusBarItem:@"Veency"];
91 }
92
93 void VNCAlertItem$alertSheet$buttonClicked$(id self, SEL sel, id sheet, int button) {
94 [condition_ lock];
95
96 switch (button) {
97 case 1:
98 VNCAccept();
99 break;
100
101 case 2:
102 action_ = RFB_CLIENT_REFUSE;
103 break;
104 }
105
106 [condition_ signal];
107 [condition_ unlock];
108 [self dismiss];
109 }
110
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"];
118 }
119
120 void VNCAlertItem$performUnlockAction(id self, SEL sel) {
121 [[$SBAlertItemsController sharedInstance] activateAlertItem:self];
122 }
123
124 @interface VNCBridge : NSObject {
125 }
126
127 + (void) askForConnection;
128 + (void) removeStatusBarItem;
129
130 @end
131
132 @implementation VNCBridge
133
134 + (void) askForConnection {
135 if (false) {
136 [condition_ lock];
137 VNCAccept();
138 [condition_ signal];
139 [condition_ unlock];
140 } else {
141 id item = [[[$VNCAlertItem alloc] init] autorelease];
142 [[$SBAlertItemsController sharedInstance] activateAlertItem:item];
143 }
144 }
145
146 + (void) removeStatusBarItem {
147 [[$SBStatusBarController sharedStatusBarController] removeStatusBarItem:@"Veency"];
148 }
149
150 @end
151
152 static mach_port_t (*GSTakePurpleSystemEventPort)(void);
153 static bool PurpleAllocated;
154
155 static void VNCPointer(int buttons, int x, int y, rfbClientPtr client) {
156 x_ = x; y_ = y;
157 int diff = buttons_ ^ buttons;
158 bool twas((buttons_ & 0x1) != 0);
159 bool tis((buttons & 0x1) != 0);
160 buttons_ = buttons;
161
162 rfbDefaultPtrAddEvent(buttons, x, y, client);
163
164 mach_port_t purple(0);
165
166 if ((diff & 0x10) != 0) {
167 struct GSEventRecord record;
168
169 memset(&record, 0, sizeof(record));
170
171 record.type = (buttons & 0x4) != 0 ?
172 GSEventTypeHeadsetButtonDown :
173 GSEventTypeHeadsetButtonUp;
174
175 record.timestamp = GSCurrentEventTimestamp();
176
177 GSSendSystemEvent(&record);
178 }
179
180 if ((diff & 0x04) != 0) {
181 struct GSEventRecord record;
182
183 memset(&record, 0, sizeof(record));
184
185 record.type = (buttons & 0x4) != 0 ?
186 GSEventTypeMenuButtonDown :
187 GSEventTypeMenuButtonUp;
188
189 record.timestamp = GSCurrentEventTimestamp();
190
191 GSSendSystemEvent(&record);
192 }
193
194 if ((diff & 0x02) != 0) {
195 struct GSEventRecord record;
196
197 memset(&record, 0, sizeof(record));
198
199 record.type = (buttons & 0x2) != 0 ?
200 GSEventTypeLockButtonDown :
201 GSEventTypeLockButtonUp;
202
203 record.timestamp = GSCurrentEventTimestamp();
204
205 GSSendSystemEvent(&record);
206 }
207
208 if (twas != tis || tis) {
209 struct {
210 struct GSEventRecord record;
211 struct {
212 struct GSEventRecordInfo info;
213 struct GSPathInfo path;
214 } data;
215 } event;
216
217 memset(&event, 0, sizeof(event));
218
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);
224
225 event.data.info.handInfo.type = twas == tis ?
226 GSMouseEventTypeDragged :
227 tis ?
228 GSMouseEventTypeDown :
229 GSMouseEventTypeUp;
230
231 event.data.info.handInfo.x34 = 0x1;
232 event.data.info.handInfo.x38 = tis ? 0x1 : 0x0;
233
234 event.data.info.pathPositions = 1;
235
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;
240
241 mach_port_t port(0);
242
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];
248 }
249
250 if (port == 0) {
251 if (purple == 0)
252 purple = (*GSTakePurpleSystemEventPort)();
253 port = purple;
254 }
255
256 GSSendEvent(&event.record, port);
257 }
258
259 if (purple != 0 && PurpleAllocated)
260 mach_port_deallocate(mach_task_self(), purple);
261 }
262
263 static void VNCKeyboard(rfbBool down, rfbKeySym key, rfbClientPtr client) {
264 if (!down)
265 return;
266
267 switch (key) {
268 case XK_Return: key = '\r'; break;
269 case XK_BackSpace: key = 0x7f; break;
270 }
271
272 if (key > 0xfff)
273 return;
274
275 GSEventRef event(_GSCreateSyntheticKeyEvent(key, YES, YES));
276 GSEventRecord *record(_GSEventGetGSEventRecord(event));
277 record->type = GSEventTypeKeyDown;
278
279 mach_port_t port(0);
280
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_)];
286 }
287
288 mach_port_t purple(0);
289
290 if (port == 0) {
291 if (purple == 0)
292 purple = (*GSTakePurpleSystemEventPort)();
293 port = purple;
294 }
295
296 if (port != 0)
297 GSSendEvent(record, port);
298
299 if (purple != 0 && PurpleAllocated)
300 mach_port_deallocate(mach_task_self(), purple);
301
302 CFRelease(event);
303 }
304
305 static void VNCDisconnect(rfbClientPtr client) {
306 if (--clients_ == 0)
307 [VNCBridge performSelectorOnMainThread:@selector(removeStatusBarItem) withObject:nil waitUntilDone:NO];
308 }
309
310 static rfbNewClientAction VNCClient(rfbClientPtr client) {
311 [condition_ lock];
312 client_ = client;
313 [VNCBridge performSelectorOnMainThread:@selector(askForConnection) withObject:nil waitUntilDone:NO];
314 while (action_ == RFB_CLIENT_ON_HOLD)
315 [condition_ wait];
316 rfbNewClientAction action(action_);
317 action_ = RFB_CLIENT_ON_HOLD;
318 [condition_ unlock];
319 if (action == RFB_CLIENT_ACCEPT)
320 client->clientGoneHook = &VNCDisconnect;
321 return action;
322 }
323
324 static rfbPixel black_[320][480];
325
326 static void *VNCServer(IOMobileFramebufferRef fb) {
327 CGRect rect(CGRectMake(0, 0, Width, Height));
328
329 /*CoreSurfaceBufferRef surface(NULL);
330 kern_return_t value(IOMobileFramebufferGetLayerDefaultSurface(fb, 0, &surface));
331 if (value != 0)
332 return NULL;*/
333
334 condition_ = [[NSCondition alloc] init];
335
336 int argc(1);
337 char *arg0(strdup("VNCServer"));
338 char *argv[] = {arg0, NULL};
339
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;
345
346 screen_->serverFormat.redShift = BitsPerSample * 2;
347 screen_->serverFormat.greenShift = BitsPerSample * 1;
348 screen_->serverFormat.blueShift = BitsPerSample * 0;
349
350 /*io_service_t service(IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("IOCoreSurfaceRoot")));
351 CFMutableDictionaryRef properties(NULL);
352 IORegistryEntryCreateCFProperties(service, &properties, kCFAllocatorDefault, kNilOptions);
353
354 CoreSurfaceBufferLock(surface, kCoreSurfaceLockTypeGimmeVRAM);
355 screen_->frameBuffer = reinterpret_cast<char *>(CoreSurfaceBufferGetBaseAddress(surface));
356 CoreSurfaceBufferUnlock(surface);
357 CFRelease(surface);*/
358
359 screen_->frameBuffer = reinterpret_cast<char *>(black_);
360
361 screen_->kbdAddEvent = &VNCKeyboard;
362 screen_->ptrAddEvent = &VNCPointer;
363
364 screen_->newClientHook = &VNCClient;
365
366 /*char data[0], mask[0];
367 rfbCursorPtr cursor = rfbMakeXCursor(0, 0, data, mask);
368 rfbSetCursor(screen_, cursor);*/
369
370 rfbInitServer(screen_);
371 running_ = true;
372
373 rfbRunEventLoop(screen_, -1, true);
374 NSLog(@"rfbRunEventLoop().");
375 return NULL;
376
377 running_ = false;
378 rfbScreenCleanup(screen_);
379
380 free(arg0);
381 return NULL;
382 }
383
384 MSHook(kern_return_t, IOMobileFramebufferSwapSetLayer,
385 IOMobileFramebufferRef fb,
386 int layer,
387 CoreSurfaceBufferRef buffer,
388 CGRect bounds,
389 CGRect frame,
390 int flags
391 ) {
392 /*if (
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
398 );*/
399
400 if (running_) {
401 if (buffer == NULL)
402 screen_->frameBuffer = reinterpret_cast<char *>(black_);
403 else {
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);
408 }
409 }
410
411 kern_return_t value(_IOMobileFramebufferSwapSetLayer(fb, layer, buffer, bounds, frame, flags));
412
413 if (thread_ == NULL)
414 pthread_create(&thread_, NULL, &VNCServer, fb);
415 else if (running_)
416 rfbMarkRectAsModified(screen_, 0, 0, Width, Height);
417
418 return value;
419 }
420
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;
426 }
427
428 MSHookFunction(&IOMobileFramebufferSwapSetLayer, &$IOMobileFramebufferSwapSetLayer, &_IOMobileFramebufferSwapSetLayer);
429
430 $SBAlertItemsController = objc_getClass("SBAlertItemsController");
431 $SBStatusBarController = objc_getClass("SBStatusBarController");
432
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);
438 }