]> git.saurik.com Git - veency.git/blob - Tweak.mm
9c84689935830cd3b1b7fbf8041d8ad1af0dd260
[veency.git] / Tweak.mm
1 /* Veency - VNC Remote Access Server for iPhoneOS
2 * Copyright (C) 2008-2009 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 #define _trace() \
39 fprintf(stderr, "_trace()@%s:%u[%s]\n", __FILE__, __LINE__, __FUNCTION__)
40
41 #include <substrate.h>
42
43 #include <rfb/rfb.h>
44 #include <rfb/keysym.h>
45
46 #include <mach/mach_port.h>
47
48 #import <QuartzCore/CAWindowServer.h>
49 #import <QuartzCore/CAWindowServerDisplay.h>
50
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>
57
58 #import <SpringBoard/SBAlertItemsController.h>
59 #import <SpringBoard/SBDismissOnlyAlertItem.h>
60 #import <SpringBoard/SBStatusBarController.h>
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 NSMutableSet *handlers_;
72 static rfbScreenInfoPtr screen_;
73 static bool running_;
74 static int buttons_;
75 static int x_, y_;
76
77 static unsigned clients_;
78
79 MSClassHook(SBAlertItemsController)
80 MSClassHook(SBStatusBarController)
81
82 @class VNCAlertItem;
83 static Class $VNCAlertItem;
84
85 static rfbNewClientAction action_ = RFB_CLIENT_ON_HOLD;
86 static NSCondition *condition_;
87 static NSLock *lock_;
88
89 static rfbClientPtr client_;
90
91 static void VNCAccept() {
92 action_ = RFB_CLIENT_ACCEPT;
93 ++clients_;
94 [[$SBStatusBarController sharedStatusBarController] addStatusBarItem:@"Veency"];
95 }
96
97 MSInstanceMessage2(void, VNCAlertItem, alertSheet,buttonClicked, id, sheet, int, button) {
98 [condition_ lock];
99
100 switch (button) {
101 case 1:
102 VNCAccept();
103 break;
104
105 case 2:
106 action_ = RFB_CLIENT_REFUSE;
107 break;
108 }
109
110 [condition_ signal];
111 [condition_ unlock];
112 [self dismiss];
113 }
114
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"];
122 }
123
124 MSInstanceMessage0(void, VNCAlertItem, performUnlockAction) {
125 [[$SBAlertItemsController sharedInstance] activateAlertItem:self];
126 }
127
128 @interface VNCBridge : NSObject {
129 }
130
131 + (void) askForConnection;
132 + (void) removeStatusBarItem;
133
134 @end
135
136 @implementation VNCBridge
137
138 + (void) askForConnection {
139 [[$SBAlertItemsController sharedInstance] activateAlertItem:[[[$VNCAlertItem alloc] init] autorelease]];
140 }
141
142 + (void) removeStatusBarItem {
143 [[$SBStatusBarController sharedStatusBarController] removeStatusBarItem:@"Veency"];
144 }
145
146 @end
147
148 static mach_port_t (*GSTakePurpleSystemEventPort)(void);
149 static bool PurpleAllocated;
150 static bool Two_;
151
152 static void FixRecord(GSEventRecord *record) {
153 if (Two_)
154 memmove(&record->windowContextId, &record->windowContextId + 1, sizeof(*record) - (reinterpret_cast<uint8_t *>(&record->windowContextId + 1) - reinterpret_cast<uint8_t *>(record)) + record->size);
155 }
156
157 static void VNCSettings() {
158 NSDictionary *settings([NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/Library/Preferences/com.saurik.Veency.plist", NSHomeDirectory()]]);
159
160 @synchronized (lock_) {
161 for (NSValue *handler in handlers_)
162 rfbUnregisterSecurityHandler(reinterpret_cast<rfbSecurityHandler *>([handler pointerValue]));
163 [handlers_ removeAllObjects];
164 }
165
166 @synchronized (condition_) {
167 if (screen_ == NULL)
168 return;
169
170 [reinterpret_cast<NSString *>(screen_->authPasswdData) release];
171 screen_->authPasswdData = NULL;
172
173 if (NSString *password = [settings objectForKey:@"Password"])
174 if ([password length] != 0)
175 screen_->authPasswdData = [password retain];
176 }
177 }
178
179 static void VNCNotifySettings(
180 CFNotificationCenterRef center,
181 void *observer,
182 CFStringRef name,
183 const void *object,
184 CFDictionaryRef info
185 ) {
186 VNCSettings();
187 }
188
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;
194 } return TRUE;
195 }
196 }
197
198 static void VNCPointer(int buttons, int x, int y, rfbClientPtr client) {
199 x_ = x; y_ = y;
200 int diff = buttons_ ^ buttons;
201 bool twas((buttons_ & 0x1) != 0);
202 bool tis((buttons & 0x1) != 0);
203 buttons_ = buttons;
204
205 rfbDefaultPtrAddEvent(buttons, x, y, client);
206
207 mach_port_t purple(0);
208
209 if ((diff & 0x10) != 0) {
210 struct GSEventRecord record;
211
212 memset(&record, 0, sizeof(record));
213
214 record.type = (buttons & 0x4) != 0 ?
215 GSEventTypeHeadsetButtonDown :
216 GSEventTypeHeadsetButtonUp;
217
218 record.timestamp = GSCurrentEventTimestamp();
219
220 FixRecord(&record);
221 GSSendSystemEvent(&record);
222 }
223
224 if ((diff & 0x04) != 0) {
225 struct GSEventRecord record;
226
227 memset(&record, 0, sizeof(record));
228
229 record.type = (buttons & 0x4) != 0 ?
230 GSEventTypeMenuButtonDown :
231 GSEventTypeMenuButtonUp;
232
233 record.timestamp = GSCurrentEventTimestamp();
234
235 FixRecord(&record);
236 GSSendSystemEvent(&record);
237 }
238
239 if ((diff & 0x02) != 0) {
240 struct GSEventRecord record;
241
242 memset(&record, 0, sizeof(record));
243
244 record.type = (buttons & 0x2) != 0 ?
245 GSEventTypeLockButtonDown :
246 GSEventTypeLockButtonUp;
247
248 record.timestamp = GSCurrentEventTimestamp();
249
250 FixRecord(&record);
251 GSSendSystemEvent(&record);
252 }
253
254 if (twas != tis || tis) {
255 struct {
256 struct GSEventRecord record;
257 struct {
258 struct GSEventRecordInfo info;
259 struct GSPathInfo path;
260 } data;
261 } event;
262
263 memset(&event, 0, sizeof(event));
264
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);
270
271 event.data.info.handInfo.type = twas == tis ?
272 GSMouseEventTypeDragged :
273 tis ?
274 GSMouseEventTypeDown :
275 GSMouseEventTypeUp;
276
277 event.data.info.handInfo.x34 = 0x1;
278 event.data.info.handInfo.x38 = tis ? 0x1 : 0x0;
279
280 event.data.info.pathPositions = 1;
281
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;
286
287 mach_port_t port(0);
288
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];
294 }
295
296 if (port == 0) {
297 if (purple == 0)
298 purple = (*GSTakePurpleSystemEventPort)();
299 port = purple;
300 }
301
302 FixRecord(&event.record);
303 GSSendEvent(&event.record, port);
304 }
305
306 if (purple != 0 && PurpleAllocated)
307 mach_port_deallocate(mach_task_self(), purple);
308 }
309
310 static void VNCKeyboard(rfbBool down, rfbKeySym key, rfbClientPtr client) {
311 if (!down)
312 return;
313
314 switch (key) {
315 case XK_Return: key = '\r'; break;
316 case XK_BackSpace: key = 0x7f; break;
317 }
318
319 if (key > 0xfff)
320 return;
321
322 GSEventRef event(_GSCreateSyntheticKeyEvent(key, YES, YES));
323 GSEventRecord *record(_GSEventGetGSEventRecord(event));
324 record->type = GSEventTypeKeyDown;
325
326 mach_port_t port(0);
327
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_)];
333 }
334
335 mach_port_t purple(0);
336
337 if (port == 0) {
338 if (purple == 0)
339 purple = (*GSTakePurpleSystemEventPort)();
340 port = purple;
341 }
342
343 if (port != 0)
344 GSSendEvent(record, port);
345
346 if (purple != 0 && PurpleAllocated)
347 mach_port_deallocate(mach_task_self(), purple);
348
349 CFRelease(event);
350 }
351
352 static void VNCDisconnect(rfbClientPtr client) {
353 if (--clients_ == 0)
354 [VNCBridge performSelectorOnMainThread:@selector(removeStatusBarItem) withObject:nil waitUntilDone:NO];
355 }
356
357 static rfbNewClientAction VNCClient(rfbClientPtr client) {
358 @synchronized (condition_) {
359 if (screen_->authPasswdData != NULL)
360 return RFB_CLIENT_ACCEPT;
361 }
362
363 [condition_ lock];
364 client_ = client;
365 [VNCBridge performSelectorOnMainThread:@selector(askForConnection) withObject:nil waitUntilDone:NO];
366 while (action_ == RFB_CLIENT_ON_HOLD)
367 [condition_ wait];
368 rfbNewClientAction action(action_);
369 action_ = RFB_CLIENT_ON_HOLD;
370 [condition_ unlock];
371 if (action == RFB_CLIENT_ACCEPT)
372 client->clientGoneHook = &VNCDisconnect;
373 return action;
374 }
375
376 static rfbPixel black_[320][480];
377
378 static void VNCSetup() {
379 @synchronized (condition_) {
380 int argc(1);
381 char *arg0(strdup("VNCServer"));
382 char *argv[] = {arg0, NULL};
383 screen_ = rfbGetScreen(&argc, argv, Width, Height, BitsPerSample, 3, BytesPerPixel);
384 free(arg0);
385
386 VNCSettings();
387 }
388
389 screen_->desktopName = strdup([[[NSProcessInfo processInfo] hostName] UTF8String]);
390
391 screen_->alwaysShared = TRUE;
392 screen_->handleEventsEagerly = TRUE;
393 screen_->deferUpdateTime = 5;
394
395 screen_->serverFormat.redShift = BitsPerSample * 2;
396 screen_->serverFormat.greenShift = BitsPerSample * 1;
397 screen_->serverFormat.blueShift = BitsPerSample * 0;
398
399 screen_->frameBuffer = reinterpret_cast<char *>(black_);
400
401 screen_->kbdAddEvent = &VNCKeyboard;
402 screen_->ptrAddEvent = &VNCPointer;
403
404 screen_->newClientHook = &VNCClient;
405 screen_->passwordCheck = &VNCCheck;
406
407 /*char data[0], mask[0];
408 rfbCursorPtr cursor = rfbMakeXCursor(0, 0, data, mask);
409 rfbSetCursor(screen_, cursor);*/
410 }
411
412 static void VNCEnabled() {
413 [lock_ lock];
414
415 bool enabled(true);
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_)
420 if (enabled) {
421 running_ = true;
422 screen_->socketState = RFB_SOCKET_INIT;
423 rfbInitServer(screen_);
424 rfbRunEventLoop(screen_, -1, true);
425 } else {
426 rfbShutdownServer(screen_, true);
427 running_ = false;
428 }
429
430 [lock_ unlock];
431 }
432
433 static void VNCNotifyEnabled(
434 CFNotificationCenterRef center,
435 void *observer,
436 CFStringRef name,
437 const void *object,
438 CFDictionaryRef info
439 ) {
440 VNCEnabled();
441 }
442
443 MSHook(kern_return_t, IOMobileFramebufferSwapSetLayer,
444 IOMobileFramebufferRef fb,
445 int layer,
446 CoreSurfaceBufferRef buffer,
447 CGRect bounds,
448 CGRect frame,
449 int flags
450 ) {
451 if (running_) {
452 if (buffer == NULL)
453 screen_->frameBuffer = reinterpret_cast<char *>(black_);
454 else {
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);
459 }
460
461 rfbMarkRectAsModified(screen_, 0, 0, Width, Height);
462 }
463
464 return _IOMobileFramebufferSwapSetLayer(fb, layer, buffer, bounds, frame, flags);
465 }
466
467 MSHook(void, rfbRegisterSecurityHandler, rfbSecurityHandler *handler) {
468 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
469
470 @synchronized (lock_) {
471 [handlers_ addObject:[NSValue valueWithPointer:handler]];
472 _rfbRegisterSecurityHandler(handler);
473 }
474
475 [pool release];
476 }
477
478 MSInitialize {
479 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
480
481 MSHookSymbol(GSTakePurpleSystemEventPort, "GSGetPurpleSystemEventPort");
482 if (GSTakePurpleSystemEventPort == NULL) {
483 MSHookSymbol(GSTakePurpleSystemEventPort, "GSCopyPurpleSystemEventPort");
484 PurpleAllocated = true;
485 }
486
487 Two_ = dlsym(RTLD_DEFAULT, "GSEventGetWindowContextId") == NULL;
488
489 MSHookFunction(&IOMobileFramebufferSwapSetLayer, MSHake(IOMobileFramebufferSwapSetLayer));
490 MSHookFunction(&rfbRegisterSecurityHandler, MSHake(rfbRegisterSecurityHandler));
491
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);
497
498 CFNotificationCenterAddObserver(
499 CFNotificationCenterGetDarwinNotifyCenter(),
500 NULL, &VNCNotifyEnabled, CFSTR("com.saurik.Veency-Enabled"), NULL, 0
501 );
502
503 CFNotificationCenterAddObserver(
504 CFNotificationCenterGetDarwinNotifyCenter(),
505 NULL, &VNCNotifySettings, CFSTR("com.saurik.Veency-Settings"), NULL, 0
506 );
507
508 condition_ = [[NSCondition alloc] init];
509 lock_ = [[NSLock alloc] init];
510 handlers_ = [[NSMutableSet alloc] init];
511
512 [pool release];
513
514 VNCSetup();
515 VNCEnabled();
516 }