Moved source code of Veency to more obvious location.
[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/UIModalView.h>
54 #import <UIKit/UIModalView-Private.h>
55
56 #import <SpringBoard/SBAlertItemsController.h>
57 #import <SpringBoard/SBDismissOnlyAlertItem.h>
58 #import <SpringBoard/SBStatusBarController.h>
59
60 #define IOMobileFramebuffer "/System/Library/PrivateFrameworks/IOMobileFramebuffer.framework/IOMobileFramebuffer"
61
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;
66
67 static const size_t Stride = Width * BytesPerPixel;
68 static const size_t Size32 = Width * Height;
69 static const size_t Size8 = Size32 * BytesPerPixel;
70
71 static pthread_t thread_;
72 static rfbScreenInfoPtr screen_;
73 static bool running_;
74 static int buttons_;
75 static int x_, y_;
76
77 static unsigned clients_;
78
79 static Class $VNCAlertItem;
80 static Class $SBAlertItemsController;
81 static Class $SBStatusBarController;
82
83 static rfbNewClientAction action_ = RFB_CLIENT_ON_HOLD;
84 static NSCondition *condition_;
85
86 static rfbClientPtr client_;
87
88 void VNCAlertItem$alertSheet$buttonClicked$(id self, SEL sel, id sheet, int button) {
89 [condition_ lock];
90
91 switch (button) {
92 case 1:
93 action_ = RFB_CLIENT_ACCEPT;
94 ++clients_;
95 [[$SBStatusBarController sharedStatusBarController] addStatusBarItem:@"Veency"];
96 break;
97
98 case 2:
99 action_ = RFB_CLIENT_REFUSE;
100 break;
101 }
102
103 [condition_ signal];
104 [condition_ unlock];
105 [self dismiss];
106 }
107
108 void VNCAlertItem$configure$requirePasscodeForActions$(id self, SEL sel, BOOL configure, BOOL require) {
109 UIModalView *sheet([self alertSheet]);
110 [sheet setDelegate:self];
111 [sheet setTitle:@"Remote Access Request"];
112 [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]];
113 [sheet addButtonWithTitle:@"Accept"];
114 [sheet addButtonWithTitle:@"Reject"];
115 }
116
117 void VNCAlertItem$performUnlockAction(id self, SEL sel) {
118 [[$SBAlertItemsController sharedInstance] activateAlertItem:self];
119 }
120
121 @interface VNCBridge : NSObject {
122 }
123
124 + (void) askForConnection;
125 + (void) removeStatusBarItem;
126
127 @end
128
129 @implementation VNCBridge
130
131 + (void) askForConnection {
132 id item = [[[$VNCAlertItem alloc] init] autorelease];
133 [[$SBAlertItemsController sharedInstance] activateAlertItem:item];
134 }
135
136 + (void) removeStatusBarItem {
137 [[$SBStatusBarController sharedStatusBarController] removeStatusBarItem:@"Veency"];
138 }
139
140 @end
141
142 static void VNCPointer(int buttons, int x, int y, rfbClientPtr client) {
143 x_ = x; y_ = y;
144 int diff = buttons_ ^ buttons;
145 bool twas((buttons_ & 0x1) != 0);
146 bool tis((buttons & 0x1) != 0);
147 buttons_ = buttons;
148
149 rfbDefaultPtrAddEvent(buttons, x, y, client);
150
151 mach_port_t purple(0);
152
153 if ((diff & 0x10) != 0) {
154 struct GSEventRecord record;
155
156 memset(&record, 0, sizeof(record));
157
158 record.type = (buttons & 0x4) != 0 ?
159 GSEventTypeHeadsetButtonDown :
160 GSEventTypeHeadsetButtonUp;
161
162 record.timestamp = GSCurrentEventTimestamp();
163
164 GSSendSystemEvent(&record);
165 }
166
167 if ((diff & 0x04) != 0) {
168 struct GSEventRecord record;
169
170 memset(&record, 0, sizeof(record));
171
172 record.type = (buttons & 0x4) != 0 ?
173 GSEventTypeMenuButtonDown :
174 GSEventTypeMenuButtonUp;
175
176 record.timestamp = GSCurrentEventTimestamp();
177
178 GSSendSystemEvent(&record);
179 }
180
181 if ((diff & 0x02) != 0) {
182 struct GSEventRecord record;
183
184 memset(&record, 0, sizeof(record));
185
186 record.type = (buttons & 0x2) != 0 ?
187 GSEventTypeLockButtonDown :
188 GSEventTypeLockButtonUp;
189
190 record.timestamp = GSCurrentEventTimestamp();
191
192 GSSendSystemEvent(&record);
193 }
194
195 if (twas != tis || tis) {
196 struct {
197 struct GSEventRecord record;
198 struct {
199 struct GSEventRecordInfo info;
200 struct GSPathInfo path;
201 } data;
202 } event;
203
204 memset(&event, 0, sizeof(event));
205
206 event.record.type = GSEventTypeMouse;
207 event.record.locationInWindow.x = x;
208 event.record.locationInWindow.y = y;
209 event.record.timestamp = GSCurrentEventTimestamp();
210 event.record.size = sizeof(event.data);
211
212 event.data.info.handInfo.type = twas == tis ?
213 GSMouseEventTypeDragged :
214 tis ?
215 GSMouseEventTypeDown :
216 GSMouseEventTypeUp;
217
218 event.data.info.handInfo.x34 = 0x1;
219 event.data.info.handInfo.x38 = tis ? 0x1 : 0x0;
220
221 event.data.info.pathPositions = 1;
222
223 event.data.path.x00 = 0x01;
224 event.data.path.x01 = 0x02;
225 event.data.path.x02 = tis ? 0x03 : 0x00;
226 event.data.path.position = event.record.locationInWindow;
227
228 mach_port_t port(0);
229
230 if (CAWindowServer *server = [CAWindowServer serverIfRunning]) {
231 NSArray *displays([server displays]);
232 if (displays != nil && [displays count] != 0)
233 if (CAWindowServerDisplay *display = [displays objectAtIndex:0])
234 port = [display clientPortAtPosition:event.record.locationInWindow];
235 }
236
237 if (port == 0) {
238 if (purple == 0)
239 purple = GSCopyPurpleSystemEventPort();
240 port = purple;
241 }
242
243 GSSendEvent(&event.record, port);
244 }
245
246 if (purple != 0)
247 mach_port_deallocate(mach_task_self(), purple);
248 }
249
250 static void VNCKeyboard(rfbBool down, rfbKeySym key, rfbClientPtr client) {
251 if (!down)
252 return;
253
254 switch (key) {
255 case XK_Return: key = '\r'; break;
256 case XK_BackSpace: key = 0x7f; break;
257 }
258
259 if (key > 0xfff)
260 return;
261
262 struct {
263 struct GSEventRecord record;
264 struct GSEventKeyInfo data;
265 } event;
266
267 memset(&event, 0, sizeof(event));
268
269 event.record.type = GSEventTypeKeyDown;
270 event.record.timestamp = GSCurrentEventTimestamp();
271 event.record.size = sizeof(event.data);
272
273 event.data.character = key;
274
275 mach_port_t port(0);
276
277 if (CAWindowServer *server = [CAWindowServer serverIfRunning]) {
278 NSArray *displays([server displays]);
279 if (displays != nil && [displays count] != 0)
280 if (CAWindowServerDisplay *display = [displays objectAtIndex:0])
281 port = [display clientPortAtPosition:CGPointMake(x_, y_)];
282 }
283
284 if (port != 0)
285 GSSendEvent(&event.record, port);
286 }
287
288 static void VNCDisconnect(rfbClientPtr client) {
289 if (--clients_ == 0)
290 [VNCBridge performSelectorOnMainThread:@selector(removeStatusBarItem) withObject:nil waitUntilDone:NO];
291 }
292
293 static rfbNewClientAction VNCClient(rfbClientPtr client) {
294 [condition_ lock];
295 client_ = client;
296 [VNCBridge performSelectorOnMainThread:@selector(askForConnection) withObject:nil waitUntilDone:NO];
297 while (action_ == RFB_CLIENT_ON_HOLD)
298 [condition_ wait];
299 rfbNewClientAction action(action_);
300 action_ = RFB_CLIENT_ON_HOLD;
301 [condition_ unlock];
302 if (action == RFB_CLIENT_ACCEPT)
303 client->clientGoneHook = &VNCDisconnect;
304 return action;
305 }
306
307 static rfbPixel black_[320][480];
308
309 static void *VNCServer(IOMobileFramebufferRef fb) {
310 CGRect rect(CGRectMake(0, 0, Width, Height));
311
312 /*CoreSurfaceBufferRef surface(NULL);
313 kern_return_t value(IOMobileFramebufferGetLayerDefaultSurface(fb, 0, &surface));
314 if (value != 0)
315 return NULL;*/
316
317 condition_ = [[NSCondition alloc] init];
318
319 int argc(1);
320 char *arg0(strdup("VNCServer"));
321 char *argv[] = {arg0, NULL};
322
323 screen_ = rfbGetScreen(&argc, argv, Width, Height, BitsPerSample, 3, BytesPerPixel);
324 screen_->desktopName = "iPhone";
325 screen_->alwaysShared = TRUE;
326 screen_->handleEventsEagerly = TRUE;
327 screen_->deferUpdateTime = 5;
328
329 screen_->serverFormat.redShift = BitsPerSample * 2;
330 screen_->serverFormat.greenShift = BitsPerSample * 1;
331 screen_->serverFormat.blueShift = BitsPerSample * 0;
332
333 /*io_service_t service(IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("IOCoreSurfaceRoot")));
334 CFMutableDictionaryRef properties(NULL);
335 IORegistryEntryCreateCFProperties(service, &properties, kCFAllocatorDefault, kNilOptions);
336
337 CoreSurfaceBufferLock(surface, kCoreSurfaceLockTypeGimmeVRAM);
338 screen_->frameBuffer = reinterpret_cast<char *>(CoreSurfaceBufferGetBaseAddress(surface));
339 CoreSurfaceBufferUnlock(surface);
340 CFRelease(surface);*/
341
342 screen_->frameBuffer = reinterpret_cast<char *>(black_);
343
344 screen_->kbdAddEvent = &VNCKeyboard;
345 screen_->ptrAddEvent = &VNCPointer;
346
347 screen_->newClientHook = &VNCClient;
348
349 /*char data[0], mask[0];
350 rfbCursorPtr cursor = rfbMakeXCursor(0, 0, data, mask);
351 rfbSetCursor(screen_, cursor);*/
352
353 rfbInitServer(screen_);
354 running_ = true;
355
356 rfbRunEventLoop(screen_, -1, true);
357 return NULL;
358
359 running_ = false;
360 rfbScreenCleanup(screen_);
361
362 free(arg0);
363 return NULL;
364 }
365
366 MSHook(kern_return_t, IOMobileFramebufferSwapSetLayer,
367 IOMobileFramebufferRef fb,
368 int layer,
369 CoreSurfaceBufferRef buffer,
370 CGRect bounds,
371 CGRect frame,
372 int flags
373 ) {
374 /*if (
375 bounds.origin.x != 0 || bounds.origin.y != 0 || bounds.size.width != 320 || bounds.size.height != 480 ||
376 frame.origin.x != 0 || frame.origin.y != 0 || frame.size.width != 320 || frame.size.height != 480
377 ) NSLog(@"VNC:%f,%f:%f,%f:%f,%f:%f,%f",
378 bounds.origin.x, bounds.origin.y, bounds.size.width, bounds.size.height,
379 frame.origin.x, frame.origin.y, frame.size.width, frame.size.height
380 );*/
381
382 if (running_) {
383 if (buffer == NULL)
384 screen_->frameBuffer = reinterpret_cast<char *>(black_);
385 else {
386 CoreSurfaceBufferLock(buffer, 2);
387 rfbPixel (*data)[480] = reinterpret_cast<rfbPixel (*)[480]>(CoreSurfaceBufferGetBaseAddress(buffer));
388 screen_->frameBuffer = const_cast<char *>(reinterpret_cast<volatile char *>(data));
389 CoreSurfaceBufferUnlock(buffer);
390 }
391 }
392
393 kern_return_t value(_IOMobileFramebufferSwapSetLayer(fb, layer, buffer, bounds, frame, flags));
394
395 if (thread_ == NULL)
396 pthread_create(&thread_, NULL, &VNCServer, fb);
397 else if (running_)
398 rfbMarkRectAsModified(screen_, 0, 0, Width, Height);
399
400 return value;
401 }
402
403 extern "C" void TweakInitialize() {
404 MSHookFunction(&IOMobileFramebufferSwapSetLayer, &$IOMobileFramebufferSwapSetLayer, &_IOMobileFramebufferSwapSetLayer);
405
406 $SBAlertItemsController = objc_getClass("SBAlertItemsController");
407 $SBStatusBarController = objc_getClass("SBStatusBarController");
408
409 $VNCAlertItem = objc_allocateClassPair(objc_getClass("SBAlertItem"), "VNCAlertItem", 0);
410 class_addMethod($VNCAlertItem, @selector(alertSheet:buttonClicked:), (IMP) &VNCAlertItem$alertSheet$buttonClicked$, "v@:@i");
411 class_addMethod($VNCAlertItem, @selector(configure:requirePasscodeForActions:), (IMP) &VNCAlertItem$configure$requirePasscodeForActions$, "v@:cc");
412 class_addMethod($VNCAlertItem, @selector(performUnlockAction), (IMP) VNCAlertItem$performUnlockAction, "v@:");
413 objc_registerClassPair($VNCAlertItem);
414 }