]> git.saurik.com Git - veency.git/blob - Tweak.mm
de862ab98764ee126aa064d95164e572a6b7b73c
[veency.git] / Tweak.mm
1 /* Veency - VNC Remote Access Server for iPhoneOS
2 * Copyright (C) 2008-2010 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 #define _unlikely(expr) \
41 __builtin_expect(expr, 0)
42
43 #include <substrate.h>
44
45 #include <rfb/rfb.h>
46 #include <rfb/keysym.h>
47
48 #include <mach/mach_port.h>
49 #include <sys/mman.h>
50
51 #import <QuartzCore/CAWindowServer.h>
52 #import <QuartzCore/CAWindowServerDisplay.h>
53
54 #import <CoreGraphics/CGGeometry.h>
55 #import <GraphicsServices/GraphicsServices.h>
56 #import <Foundation/Foundation.h>
57 #import <IOMobileFramebuffer/IOMobileFramebuffer.h>
58 #import <IOKit/IOKitLib.h>
59 #import <UIKit/UIKit.h>
60
61 #import <SpringBoard/SBAlertItemsController.h>
62 #import <SpringBoard/SBDismissOnlyAlertItem.h>
63 #import <SpringBoard/SBStatusBarController.h>
64
65 static size_t width_;
66 static size_t height_;
67
68 static const size_t BytesPerPixel = 4;
69 static const size_t BitsPerSample = 8;
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 static CFMessagePortRef ashikase_;
80 static bool cursor_;
81
82 static bool Ashikase(bool always) {
83 if (ashikase_ == NULL)
84 ashikase_ = CFMessagePortCreateRemote(kCFAllocatorDefault, CFSTR("jp.ashikase.mousesupport"));
85 return ashikase_ != NULL && (always || cursor_);
86 }
87
88 static CFDataRef cfTrue_;
89 static CFDataRef cfFalse_;
90
91 typedef struct {
92 float x, y;
93 int buttons;
94 BOOL absolute;
95 } MouseEvent;
96
97 static MouseEvent event_;
98 static CFDataRef cfEvent_;
99
100 typedef enum {
101 MouseMessageTypeEvent,
102 MouseMessageTypeSetEnabled
103 } MouseMessageType;
104
105 static void AshikaseSendEvent(float x, float y, int buttons = 0) {
106 event_.x = x;
107 event_.y = y;
108 event_.buttons = buttons;
109 event_.absolute = true;
110
111 CFMessagePortSendRequest(ashikase_, MouseMessageTypeEvent, cfEvent_, 0, 0, NULL, NULL);
112 }
113
114 static void AshikaseSetEnabled(bool enabled, bool always) {
115 if (!Ashikase(always))
116 return;
117
118 CFMessagePortSendRequest(ashikase_, MouseMessageTypeSetEnabled, enabled ? cfTrue_ : cfFalse_, 0, 0, NULL, NULL);
119
120 if (enabled)
121 AshikaseSendEvent(x_, y_);
122 }
123
124 MSClassHook(SBAlertItemsController)
125 MSClassHook(SBStatusBarController)
126
127 @class VNCAlertItem;
128 static Class $VNCAlertItem;
129
130 static rfbNewClientAction action_ = RFB_CLIENT_ON_HOLD;
131 static NSCondition *condition_;
132 static NSLock *lock_;
133
134 static rfbClientPtr client_;
135
136 @interface VNCBridge : NSObject {
137 }
138
139 + (void) askForConnection;
140 + (void) removeStatusBarItem;
141 + (void) registerClient;
142
143 @end
144
145 @implementation VNCBridge
146
147 + (void) askForConnection {
148 [[$SBAlertItemsController sharedInstance] activateAlertItem:[[[$VNCAlertItem alloc] init] autorelease]];
149 }
150
151 + (void) removeStatusBarItem {
152 AshikaseSetEnabled(false, false);
153 [[$SBStatusBarController sharedStatusBarController] removeStatusBarItem:@"Veency"];
154 }
155
156 + (void) registerClient {
157 ++clients_;
158 AshikaseSetEnabled(true, false);
159 [[$SBStatusBarController sharedStatusBarController] addStatusBarItem:@"Veency"];
160 }
161
162 @end
163
164 MSInstanceMessage2(void, VNCAlertItem, alertSheet,buttonClicked, id, sheet, int, button) {
165 [condition_ lock];
166
167 switch (button) {
168 case 1:
169 action_ = RFB_CLIENT_ACCEPT;
170
171 @synchronized (condition_) {
172 [VNCBridge registerClient];
173 }
174 break;
175
176 case 2:
177 action_ = RFB_CLIENT_REFUSE;
178 break;
179 }
180
181 [condition_ signal];
182 [condition_ unlock];
183 [self dismiss];
184 }
185
186 MSInstanceMessage2(void, VNCAlertItem, configure,requirePasscodeForActions, BOOL, configure, BOOL, require) {
187 UIModalView *sheet([self alertSheet]);
188 [sheet setDelegate:self];
189 [sheet setTitle:@"Remote Access Request"];
190 [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]];
191 [sheet addButtonWithTitle:@"Accept"];
192 [sheet addButtonWithTitle:@"Reject"];
193 }
194
195 MSInstanceMessage0(void, VNCAlertItem, performUnlockAction) {
196 [[$SBAlertItemsController sharedInstance] activateAlertItem:self];
197 }
198
199 static mach_port_t (*GSTakePurpleSystemEventPort)(void);
200 static bool PurpleAllocated;
201 static bool Two_;
202
203 static void FixRecord(GSEventRecord *record) {
204 if (Two_)
205 memmove(&record->windowContextId, &record->windowContextId + 1, sizeof(*record) - (reinterpret_cast<uint8_t *>(&record->windowContextId + 1) - reinterpret_cast<uint8_t *>(record)) + record->size);
206 }
207
208 static void VNCSettings() {
209 NSDictionary *settings([NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/Library/Preferences/com.saurik.Veency.plist", NSHomeDirectory()]]);
210
211 @synchronized (lock_) {
212 for (NSValue *handler in handlers_)
213 rfbUnregisterSecurityHandler(reinterpret_cast<rfbSecurityHandler *>([handler pointerValue]));
214 [handlers_ removeAllObjects];
215 }
216
217 @synchronized (condition_) {
218 if (screen_ == NULL)
219 return;
220
221 [reinterpret_cast<NSString *>(screen_->authPasswdData) release];
222 screen_->authPasswdData = NULL;
223
224 if (settings != nil)
225 if (NSString *password = [settings objectForKey:@"Password"])
226 if ([password length] != 0)
227 screen_->authPasswdData = [password retain];
228
229 NSNumber *cursor = [settings objectForKey:@"ShowCursor"];
230 cursor_ = cursor == nil ? true : [cursor boolValue];
231
232 if (clients_ != 0)
233 AshikaseSetEnabled(cursor_, true);
234 }
235 }
236
237 static void VNCNotifySettings(
238 CFNotificationCenterRef center,
239 void *observer,
240 CFStringRef name,
241 const void *object,
242 CFDictionaryRef info
243 ) {
244 VNCSettings();
245 }
246
247 static rfbBool VNCCheck(rfbClientPtr client, const char *data, int size) {
248 @synchronized (condition_) {
249 if (NSString *password = reinterpret_cast<NSString *>(screen_->authPasswdData)) {
250 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
251 rfbEncryptBytes(client->authChallenge, const_cast<char *>([password UTF8String]));
252 bool good(memcmp(client->authChallenge, data, size) == 0);
253 [pool release];
254 return good;
255 } return TRUE;
256 }
257 }
258
259 static void VNCPointer(int buttons, int x, int y, rfbClientPtr client) {
260 x_ = x; y_ = y;
261 int diff = buttons_ ^ buttons;
262 bool twas((buttons_ & 0x1) != 0);
263 bool tis((buttons & 0x1) != 0);
264 buttons_ = buttons;
265
266 rfbDefaultPtrAddEvent(buttons, x, y, client);
267
268 if (Ashikase(false)) {
269 AshikaseSendEvent(x, y, buttons);
270 return;
271 }
272
273 mach_port_t purple(0);
274
275 if ((diff & 0x10) != 0) {
276 struct GSEventRecord record;
277
278 memset(&record, 0, sizeof(record));
279
280 record.type = (buttons & 0x4) != 0 ?
281 GSEventTypeHeadsetButtonDown :
282 GSEventTypeHeadsetButtonUp;
283
284 record.timestamp = GSCurrentEventTimestamp();
285
286 FixRecord(&record);
287 GSSendSystemEvent(&record);
288 }
289
290 if ((diff & 0x04) != 0) {
291 struct GSEventRecord record;
292
293 memset(&record, 0, sizeof(record));
294
295 record.type = (buttons & 0x4) != 0 ?
296 GSEventTypeMenuButtonDown :
297 GSEventTypeMenuButtonUp;
298
299 record.timestamp = GSCurrentEventTimestamp();
300
301 FixRecord(&record);
302 GSSendSystemEvent(&record);
303 }
304
305 if ((diff & 0x02) != 0) {
306 struct GSEventRecord record;
307
308 memset(&record, 0, sizeof(record));
309
310 record.type = (buttons & 0x2) != 0 ?
311 GSEventTypeLockButtonDown :
312 GSEventTypeLockButtonUp;
313
314 record.timestamp = GSCurrentEventTimestamp();
315
316 FixRecord(&record);
317 GSSendSystemEvent(&record);
318 }
319
320 if (twas != tis || tis) {
321 struct {
322 struct GSEventRecord record;
323 struct {
324 struct GSEventRecordInfo info;
325 struct GSPathInfo path;
326 } data;
327 } event;
328
329 memset(&event, 0, sizeof(event));
330
331 event.record.type = GSEventTypeMouse;
332 event.record.locationInWindow.x = x;
333 event.record.locationInWindow.y = y;
334 event.record.timestamp = GSCurrentEventTimestamp();
335 event.record.size = sizeof(event.data);
336
337 event.data.info.handInfo.type = twas == tis ?
338 GSMouseEventTypeDragged :
339 tis ?
340 GSMouseEventTypeDown :
341 GSMouseEventTypeUp;
342
343 event.data.info.handInfo.x34 = 0x1;
344 event.data.info.handInfo.x38 = tis ? 0x1 : 0x0;
345
346 event.data.info.pathPositions = 1;
347
348 event.data.path.x00 = 0x01;
349 event.data.path.x01 = 0x02;
350 event.data.path.x02 = tis ? 0x03 : 0x00;
351 event.data.path.position = event.record.locationInWindow;
352
353 mach_port_t port(0);
354
355 if (CAWindowServer *server = [CAWindowServer serverIfRunning]) {
356 NSArray *displays([server displays]);
357 if (displays != nil && [displays count] != 0)
358 if (CAWindowServerDisplay *display = [displays objectAtIndex:0])
359 port = [display clientPortAtPosition:event.record.locationInWindow];
360 }
361
362 if (port == 0) {
363 if (purple == 0)
364 purple = (*GSTakePurpleSystemEventPort)();
365 port = purple;
366 }
367
368 FixRecord(&event.record);
369 GSSendEvent(&event.record, port);
370 }
371
372 if (purple != 0 && PurpleAllocated)
373 mach_port_deallocate(mach_task_self(), purple);
374 }
375
376 static void VNCKeyboard(rfbBool down, rfbKeySym key, rfbClientPtr client) {
377 if (!down)
378 return;
379
380 switch (key) {
381 case XK_Return: key = '\r'; break;
382 case XK_BackSpace: key = 0x7f; break;
383 }
384
385 if (key > 0xfff)
386 return;
387
388 GSEventRef event(_GSCreateSyntheticKeyEvent(key, YES, YES));
389 GSEventRecord *record(_GSEventGetGSEventRecord(event));
390 record->type = GSEventTypeKeyDown;
391
392 mach_port_t port(0);
393
394 if (CAWindowServer *server = [CAWindowServer serverIfRunning]) {
395 NSArray *displays([server displays]);
396 if (displays != nil && [displays count] != 0)
397 if (CAWindowServerDisplay *display = [displays objectAtIndex:0])
398 port = [display clientPortAtPosition:CGPointMake(x_, y_)];
399 }
400
401 mach_port_t purple(0);
402
403 if (port == 0) {
404 if (purple == 0)
405 purple = (*GSTakePurpleSystemEventPort)();
406 port = purple;
407 }
408
409 if (port != 0)
410 GSSendEvent(record, port);
411
412 if (purple != 0 && PurpleAllocated)
413 mach_port_deallocate(mach_task_self(), purple);
414
415 CFRelease(event);
416 }
417
418 static void VNCDisconnect(rfbClientPtr client) {
419 @synchronized (condition_) {
420 if (--clients_ == 0)
421 [VNCBridge performSelectorOnMainThread:@selector(removeStatusBarItem) withObject:nil waitUntilDone:YES];
422 }
423 }
424
425 static rfbNewClientAction VNCClient(rfbClientPtr client) {
426 @synchronized (condition_) {
427 if (screen_->authPasswdData != NULL) {
428 [VNCBridge performSelectorOnMainThread:@selector(registerClient) withObject:nil waitUntilDone:YES];
429 client->clientGoneHook = &VNCDisconnect;
430 return RFB_CLIENT_ACCEPT;
431 }
432 }
433
434 [condition_ lock];
435 client_ = client;
436 [VNCBridge performSelectorOnMainThread:@selector(askForConnection) withObject:nil waitUntilDone:NO];
437 while (action_ == RFB_CLIENT_ON_HOLD)
438 [condition_ wait];
439 rfbNewClientAction action(action_);
440 action_ = RFB_CLIENT_ON_HOLD;
441 [condition_ unlock];
442
443 if (action == RFB_CLIENT_ACCEPT)
444 client->clientGoneHook = &VNCDisconnect;
445 return action;
446 }
447
448 static rfbPixel *black_;
449
450 static void VNCBlack() {
451 if (_unlikely(black_ == NULL))
452 black_ = reinterpret_cast<rfbPixel *>(mmap(NULL, sizeof(rfbPixel) * width_ * height_, PROT_READ, MAP_ANON | MAP_PRIVATE | MAP_NOCACHE, VM_FLAGS_PURGABLE, 0));
453 screen_->frameBuffer = reinterpret_cast<char *>(black_);
454 }
455
456 static void VNCSetup() {
457 rfbLogEnable(false);
458
459 @synchronized (condition_) {
460 int argc(1);
461 char *arg0(strdup("VNCServer"));
462 char *argv[] = {arg0, NULL};
463 screen_ = rfbGetScreen(&argc, argv, width_, height_, BitsPerSample, 3, BytesPerPixel);
464 free(arg0);
465
466 VNCSettings();
467 }
468
469 screen_->desktopName = strdup([[[NSProcessInfo processInfo] hostName] UTF8String]);
470
471 screen_->alwaysShared = TRUE;
472 screen_->handleEventsEagerly = TRUE;
473 screen_->deferUpdateTime = 5;
474
475 screen_->serverFormat.redShift = BitsPerSample * 2;
476 screen_->serverFormat.greenShift = BitsPerSample * 1;
477 screen_->serverFormat.blueShift = BitsPerSample * 0;
478
479 VNCBlack();
480
481 screen_->kbdAddEvent = &VNCKeyboard;
482 screen_->ptrAddEvent = &VNCPointer;
483
484 screen_->newClientHook = &VNCClient;
485 screen_->passwordCheck = &VNCCheck;
486
487 char data[0], mask[0];
488 rfbCursorPtr cursor = rfbMakeXCursor(0, 0, data, mask);
489 rfbSetCursor(screen_, cursor);
490 }
491
492 static void VNCEnabled() {
493 [lock_ lock];
494
495 bool enabled(true);
496 if (NSDictionary *settings = [NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/Library/Preferences/com.saurik.Veency.plist", NSHomeDirectory()]])
497 if (NSNumber *number = [settings objectForKey:@"Enabled"])
498 enabled = [number boolValue];
499
500 if (enabled != running_)
501 if (enabled) {
502 running_ = true;
503 screen_->socketState = RFB_SOCKET_INIT;
504 rfbInitServer(screen_);
505 rfbRunEventLoop(screen_, -1, true);
506 } else {
507 rfbShutdownServer(screen_, true);
508 running_ = false;
509 }
510
511 [lock_ unlock];
512 }
513
514 static void VNCNotifyEnabled(
515 CFNotificationCenterRef center,
516 void *observer,
517 CFStringRef name,
518 const void *object,
519 CFDictionaryRef info
520 ) {
521 VNCEnabled();
522 }
523
524 MSHook(kern_return_t, IOMobileFramebufferSwapSetLayer,
525 IOMobileFramebufferRef fb,
526 int layer,
527 CoreSurfaceBufferRef buffer,
528 CGRect bounds,
529 CGRect frame,
530 int flags
531 ) {
532 if (_unlikely(screen_ == NULL)) {
533 CGSize size;
534 IOMobileFramebufferGetDisplaySize(fb, &size);
535
536 width_ = size.width;
537 height_ = size.height;
538
539 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
540 VNCSetup();
541 VNCEnabled();
542 [pool release];
543 } else if (_unlikely(clients_ != 0)) {
544 if (buffer == NULL)
545 VNCBlack();
546 else {
547 CoreSurfaceBufferLock(buffer, 2);
548 rfbPixel *data(reinterpret_cast<rfbPixel *>(CoreSurfaceBufferGetBaseAddress(buffer)));
549 screen_->frameBuffer = const_cast<char *>(reinterpret_cast<volatile char *>(data));
550 CoreSurfaceBufferUnlock(buffer);
551 }
552
553 rfbMarkRectAsModified(screen_, 0, 0, width_, height_);
554 }
555
556 return _IOMobileFramebufferSwapSetLayer(fb, layer, buffer, bounds, frame, flags);
557 }
558
559 MSHook(void, rfbRegisterSecurityHandler, rfbSecurityHandler *handler) {
560 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
561
562 @synchronized (lock_) {
563 [handlers_ addObject:[NSValue valueWithPointer:handler]];
564 _rfbRegisterSecurityHandler(handler);
565 }
566
567 [pool release];
568 }
569
570 MSInitialize {
571 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
572
573 MSHookSymbol(GSTakePurpleSystemEventPort, "GSGetPurpleSystemEventPort");
574 if (GSTakePurpleSystemEventPort == NULL) {
575 MSHookSymbol(GSTakePurpleSystemEventPort, "GSCopyPurpleSystemEventPort");
576 PurpleAllocated = true;
577 }
578
579 Two_ = dlsym(RTLD_DEFAULT, "GSEventGetWindowContextId") == NULL;
580
581 MSHookFunction(&IOMobileFramebufferSwapSetLayer, MSHake(IOMobileFramebufferSwapSetLayer));
582 MSHookFunction(&rfbRegisterSecurityHandler, MSHake(rfbRegisterSecurityHandler));
583
584 $VNCAlertItem = objc_allocateClassPair(objc_getClass("SBAlertItem"), "VNCAlertItem", 0);
585 MSAddMessage2(VNCAlertItem, "v@:@i", alertSheet,buttonClicked);
586 MSAddMessage2(VNCAlertItem, "v@:cc", configure,requirePasscodeForActions);
587 MSAddMessage0(VNCAlertItem, "v@:", performUnlockAction);
588 objc_registerClassPair($VNCAlertItem);
589
590 CFNotificationCenterAddObserver(
591 CFNotificationCenterGetDarwinNotifyCenter(),
592 NULL, &VNCNotifyEnabled, CFSTR("com.saurik.Veency-Enabled"), NULL, 0
593 );
594
595 CFNotificationCenterAddObserver(
596 CFNotificationCenterGetDarwinNotifyCenter(),
597 NULL, &VNCNotifySettings, CFSTR("com.saurik.Veency-Settings"), NULL, 0
598 );
599
600 condition_ = [[NSCondition alloc] init];
601 lock_ = [[NSLock alloc] init];
602 handlers_ = [[NSMutableSet alloc] init];
603
604 [pool release];
605
606 bool value;
607
608 value = true;
609 cfTrue_ = CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&value), sizeof(value));
610
611 value = false;
612 cfFalse_ = CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&value), sizeof(value));
613
614 cfEvent_ = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&event_), sizeof(event_), kCFAllocatorNull);
615 }