]> git.saurik.com Git - veency.git/blob - Tweak.mm
7eaaea9c5f0e064379e37ccb0b797d3b4b0dc97f
[veency.git] / Tweak.mm
1 /* Veency - VNC Remote Access Server for iPhoneOS
2 * Copyright (C) 2008-2012 Jay Freeman (saurik)
3 */
4
5 /* GNU Affero General Public License, Version 3 {{{ */
6 /*
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
16
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 **/
20 /* }}} */
21
22 #define _trace() \
23 fprintf(stderr, "_trace()@%s:%u[%s]\n", __FILE__, __LINE__, __FUNCTION__)
24 #define _likely(expr) \
25 __builtin_expect(expr, 1)
26 #define _unlikely(expr) \
27 __builtin_expect(expr, 0)
28
29 #include <substrate.h>
30
31 #include <rfb/rfb.h>
32 #include <rfb/keysym.h>
33
34 #include <mach/mach.h>
35 #include <mach/mach_time.h>
36
37 #include <sys/mman.h>
38 #include <sys/sysctl.h>
39
40 #undef assert
41
42 #include <CoreFoundation/CFUserNotification.h>
43 #import <CoreGraphics/CGGeometry.h>
44 #import <GraphicsServices/GraphicsServices.h>
45 #import <Foundation/Foundation.h>
46 #import <UIKit/UIKit.h>
47
48 #include <IOKit/hid/IOHIDEventTypes.h>
49 #include <IOKit/hidsystem/IOHIDUsageTables.h>
50
51 extern "C" {
52 #include "SpringBoardAccess.h"
53 }
54
55 MSClassHook(UIApplication)
56
57 @interface UIApplication (Apple)
58 - (void) addStatusBarImageNamed:(NSString *)name;
59 - (void) removeStatusBarImageNamed:(NSString *)name;
60 @end
61
62 @interface CAWindowServerDisplay : NSObject
63 - (mach_port_t) clientPortAtPosition:(CGPoint)position;
64 @end
65
66 @interface CAWindowServer : NSObject
67 + (CAWindowServer *) serverIfRunning;
68 - (NSArray *) displays;
69 @end
70
71 @interface UIModalView : UIView
72 - (id) addButtonWithTitle:(NSString *)title;
73 - (void) setBodyText:(NSString *)text;
74 - (void) setDelegate:(id)delegate;
75 - (void) setTitle:(NSString *)title;
76 @end
77
78 @interface SBAlertItem : NSObject
79 - (void) dismiss;
80 - (UIModalView *) alertSheet;
81 @end
82
83 @interface SBAlertItemsController : NSObject
84 + (SBAlertItemsController *) sharedInstance;
85 - (void) activateAlertItem:(SBAlertItem *)item;
86 @end
87
88 @interface SBStatusBarController : NSObject
89 + (SBStatusBarController *) sharedStatusBarController;
90 - (void) addStatusBarItem:(NSString *)item;
91 - (void) removeStatusBarItem:(NSString *)item;
92 @end
93
94 typedef void *CoreSurfaceBufferRef;
95
96 extern CFStringRef kCoreSurfaceBufferGlobal;
97 extern CFStringRef kCoreSurfaceBufferMemoryRegion;
98 extern CFStringRef kCoreSurfaceBufferPitch;
99 extern CFStringRef kCoreSurfaceBufferWidth;
100 extern CFStringRef kCoreSurfaceBufferHeight;
101 extern CFStringRef kCoreSurfaceBufferPixelFormat;
102 extern CFStringRef kCoreSurfaceBufferAllocSize;
103
104 extern "C" CoreSurfaceBufferRef CoreSurfaceBufferCreate(CFDictionaryRef dict);
105 extern "C" int CoreSurfaceBufferLock(CoreSurfaceBufferRef surface, unsigned int lockType);
106 extern "C" int CoreSurfaceBufferUnlock(CoreSurfaceBufferRef surface);
107 extern "C" void *CoreSurfaceBufferGetBaseAddress(CoreSurfaceBufferRef surface);
108
109 extern "C" void CoreSurfaceBufferFlushProcessorCaches(CoreSurfaceBufferRef buffer);
110
111 typedef void *CoreSurfaceAcceleratorRef;
112
113 extern "C" int CoreSurfaceAcceleratorCreate(CFAllocatorRef allocator, void *type, CoreSurfaceAcceleratorRef *accel);
114 extern "C" unsigned int CoreSurfaceAcceleratorTransferSurface(CoreSurfaceAcceleratorRef accelerator, CoreSurfaceBufferRef dest, CoreSurfaceBufferRef src, CFDictionaryRef options/*, void *, void *, void **/);
115
116 typedef void *IOMobileFramebufferRef;
117
118 extern "C" kern_return_t IOMobileFramebufferSwapSetLayer(
119 IOMobileFramebufferRef fb,
120 int layer,
121 CoreSurfaceBufferRef buffer,
122 CGRect bounds,
123 CGRect frame,
124 int flags
125 );
126
127 extern "C" void IOMobileFramebufferGetDisplaySize(IOMobileFramebufferRef connect, CGSize *size);
128 extern "C" void IOMobileFramebufferIsMainDisplay(IOMobileFramebufferRef connect, int *main);
129
130 typedef CFTypeRef IOHIDEventRef;
131 typedef CFTypeRef IOHIDEventSystemClientRef;
132
133 extern "C" {
134 IOHIDEventRef IOHIDEventCreateKeyboardEvent(CFAllocatorRef allocator, uint64_t time, uint16_t page, uint16_t usage, Boolean down, IOHIDEventOptionBits flags);
135 IOHIDEventSystemClientRef IOHIDEventSystemClientCreate(CFAllocatorRef allocator);
136 void IOHIDEventSetSenderID(IOHIDEventRef event, uint64_t sender);
137 void IOHIDEventSystemClientDispatchEvent(IOHIDEventSystemClientRef client, IOHIDEventRef event);
138 }
139
140 static size_t width_;
141 static size_t height_;
142 static NSUInteger ratio_ = 0;
143
144 static const size_t BytesPerPixel = 4;
145 static const size_t BitsPerSample = 8;
146
147 static CoreSurfaceAcceleratorRef accelerator_;
148 static CoreSurfaceBufferRef buffer_;
149 static CFDictionaryRef options_;
150
151 static NSMutableSet *handlers_;
152 static rfbScreenInfoPtr screen_;
153 static bool running_;
154 static int buttons_;
155 static int x_, y_;
156
157 static unsigned clients_;
158
159 static CFMessagePortRef ashikase_;
160 static bool cursor_;
161
162 static rfbPixel *black_;
163
164 static void VNCBlack() {
165 if (_unlikely(black_ == NULL))
166 black_ = reinterpret_cast<rfbPixel *>(mmap(NULL, sizeof(rfbPixel) * width_ * height_, PROT_READ, MAP_ANON | MAP_PRIVATE | MAP_NOCACHE, VM_FLAGS_PURGABLE, 0));
167 screen_->frameBuffer = reinterpret_cast<char *>(black_);
168 }
169
170 static bool Ashikase(bool always) {
171 if (!always && !cursor_)
172 return false;
173
174 if (ashikase_ == NULL)
175 ashikase_ = CFMessagePortCreateRemote(kCFAllocatorDefault, CFSTR("jp.ashikase.mousesupport"));
176 if (ashikase_ != NULL)
177 return true;
178
179 cursor_ = false;
180 return false;
181 }
182
183 static CFDataRef cfTrue_;
184 static CFDataRef cfFalse_;
185
186 typedef struct {
187 float x, y;
188 int buttons;
189 BOOL absolute;
190 } MouseEvent;
191
192 static MouseEvent event_;
193 static CFDataRef cfEvent_;
194
195 typedef enum {
196 MouseMessageTypeEvent,
197 MouseMessageTypeSetEnabled
198 } MouseMessageType;
199
200 static void AshikaseSendEvent(float x, float y, int buttons = 0) {
201 event_.x = x;
202 event_.y = y;
203 event_.buttons = buttons;
204 event_.absolute = true;
205
206 CFMessagePortSendRequest(ashikase_, MouseMessageTypeEvent, cfEvent_, 0, 0, NULL, NULL);
207 }
208
209 static void AshikaseSetEnabled(bool enabled, bool always) {
210 if (!Ashikase(always))
211 return;
212
213 CFMessagePortSendRequest(ashikase_, MouseMessageTypeSetEnabled, enabled ? cfTrue_ : cfFalse_, 0, 0, NULL, NULL);
214
215 if (enabled)
216 AshikaseSendEvent(x_, y_);
217 }
218
219 MSClassHook(SBAlertItem)
220 MSClassHook(SBAlertItemsController)
221 MSClassHook(SBStatusBarController)
222
223 @interface VNCAlertItem : SBAlertItem
224 @end
225
226 static Class $VNCAlertItem;
227
228 static NSString *DialogTitle(@"Remote Access Request");
229 static NSString *DialogFormat(@"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!");
230 static NSString *DialogAccept(@"Accept");
231 static NSString *DialogReject(@"Reject");
232
233 static volatile rfbNewClientAction action_ = RFB_CLIENT_ON_HOLD;
234 static NSCondition *condition_;
235 static NSLock *lock_;
236
237 static rfbClientPtr client_;
238
239 static void VNCSetup();
240 static void VNCEnabled();
241
242 float (*$GSMainScreenScaleFactor)();
243
244 static void OnUserNotification(CFUserNotificationRef notification, CFOptionFlags flags) {
245 [condition_ lock];
246
247 if ((flags & 0x3) == 1)
248 action_ = RFB_CLIENT_ACCEPT;
249 else
250 action_ = RFB_CLIENT_REFUSE;
251
252 [condition_ signal];
253 [condition_ unlock];
254
255 CFRelease(notification);
256 }
257
258 @interface VNCBridge : NSObject {
259 }
260
261 + (void) askForConnection;
262 + (void) removeStatusBarItem;
263 + (void) registerClient;
264
265 @end
266
267 @implementation VNCBridge
268
269 + (void) askForConnection {
270 if ($VNCAlertItem != nil) {
271 [[$SBAlertItemsController sharedInstance] activateAlertItem:[[[$VNCAlertItem alloc] init] autorelease]];
272 return;
273 }
274
275 SInt32 error;
276 CFUserNotificationRef notification(CFUserNotificationCreate(kCFAllocatorDefault, 0, kCFUserNotificationPlainAlertLevel, &error, (CFDictionaryRef) [NSDictionary dictionaryWithObjectsAndKeys:
277 DialogTitle, kCFUserNotificationAlertHeaderKey,
278 [NSString stringWithFormat:DialogFormat, client_->host], kCFUserNotificationAlertMessageKey,
279 DialogAccept, kCFUserNotificationAlternateButtonTitleKey,
280 DialogReject, kCFUserNotificationDefaultButtonTitleKey,
281 nil]));
282
283 if (error != 0) {
284 CFRelease(notification);
285 notification = NULL;
286 }
287
288 if (notification == NULL) {
289 [condition_ lock];
290 action_ = RFB_CLIENT_REFUSE;
291 [condition_ signal];
292 [condition_ unlock];
293 return;
294 }
295
296 CFRunLoopSourceRef source(CFUserNotificationCreateRunLoopSource(kCFAllocatorDefault, notification, &OnUserNotification, 0));
297 CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode);
298 }
299
300 + (void) removeStatusBarItem {
301 AshikaseSetEnabled(false, false);
302
303 if (SBA_available())
304 SBA_removeStatusBarImage(const_cast<char *>("Veency"));
305 else if ($SBStatusBarController != nil)
306 [[$SBStatusBarController sharedStatusBarController] removeStatusBarItem:@"Veency"];
307 else if (UIApplication *app = [$UIApplication sharedApplication])
308 [app removeStatusBarImageNamed:@"Veency"];
309 }
310
311 + (void) registerClient {
312 // XXX: this could find a better home
313 if (ratio_ == 0) {
314 if ($GSMainScreenScaleFactor == NULL)
315 ratio_ = 1.0f;
316 else
317 ratio_ = $GSMainScreenScaleFactor();
318 }
319
320 ++clients_;
321 AshikaseSetEnabled(true, false);
322
323 if (SBA_available())
324 SBA_addStatusBarImage(const_cast<char *>("Veency"));
325 else if ($SBStatusBarController != nil)
326 [[$SBStatusBarController sharedStatusBarController] addStatusBarItem:@"Veency"];
327 else if (UIApplication *app = [$UIApplication sharedApplication])
328 [app addStatusBarImageNamed:@"Veency"];
329 }
330
331 + (void) performSetup:(NSThread *)thread {
332 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
333 [thread autorelease];
334 VNCSetup();
335 VNCEnabled();
336 [pool release];
337 }
338
339 @end
340
341 MSInstanceMessage2(void, VNCAlertItem, alertSheet,buttonClicked, id, sheet, int, button) {
342 [condition_ lock];
343
344 switch (button) {
345 case 1:
346 action_ = RFB_CLIENT_ACCEPT;
347
348 @synchronized (condition_) {
349 [VNCBridge registerClient];
350 }
351 break;
352
353 case 2:
354 action_ = RFB_CLIENT_REFUSE;
355 break;
356 }
357
358 [condition_ signal];
359 [condition_ unlock];
360 [self dismiss];
361 }
362
363 MSInstanceMessage2(void, VNCAlertItem, configure,requirePasscodeForActions, BOOL, configure, BOOL, require) {
364 UIModalView *sheet([self alertSheet]);
365 [sheet setDelegate:self];
366 [sheet setTitle:DialogTitle];
367 [sheet setBodyText:[NSString stringWithFormat:DialogFormat, client_->host]];
368 [sheet addButtonWithTitle:DialogAccept];
369 [sheet addButtonWithTitle:DialogReject];
370 }
371
372 MSInstanceMessage0(void, VNCAlertItem, performUnlockAction) {
373 [[$SBAlertItemsController sharedInstance] activateAlertItem:self];
374 }
375
376 static mach_port_t (*GSTakePurpleSystemEventPort)(void);
377 static bool PurpleAllocated;
378 static int Level_;
379
380 static void FixRecord(GSEventRecord *record) {
381 if (Level_ < 1)
382 memmove(&record->windowContextId, &record->windowContextId + 1, sizeof(*record) - (reinterpret_cast<uint8_t *>(&record->windowContextId + 1) - reinterpret_cast<uint8_t *>(record)) + record->size);
383 }
384
385 static void VNCSettings() {
386 NSDictionary *settings([NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/Library/Preferences/com.saurik.Veency.plist", NSHomeDirectory()]]);
387
388 @synchronized (lock_) {
389 for (NSValue *handler in handlers_)
390 rfbUnregisterSecurityHandler(reinterpret_cast<rfbSecurityHandler *>([handler pointerValue]));
391 [handlers_ removeAllObjects];
392 }
393
394 @synchronized (condition_) {
395 if (screen_ == NULL)
396 return;
397
398 [reinterpret_cast<NSString *>(screen_->authPasswdData) release];
399 screen_->authPasswdData = NULL;
400
401 if (settings != nil)
402 if (NSString *password = [settings objectForKey:@"Password"])
403 if ([password length] != 0)
404 screen_->authPasswdData = [password retain];
405
406 NSNumber *cursor = [settings objectForKey:@"ShowCursor"];
407 cursor_ = cursor == nil ? true : [cursor boolValue];
408
409 if (clients_ != 0)
410 AshikaseSetEnabled(cursor_, true);
411 }
412 }
413
414 static void VNCNotifySettings(
415 CFNotificationCenterRef center,
416 void *observer,
417 CFStringRef name,
418 const void *object,
419 CFDictionaryRef info
420 ) {
421 VNCSettings();
422 }
423
424 static rfbBool VNCCheck(rfbClientPtr client, const char *data, int size) {
425 @synchronized (condition_) {
426 if (NSString *password = reinterpret_cast<NSString *>(screen_->authPasswdData)) {
427 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
428 rfbEncryptBytes(client->authChallenge, const_cast<char *>([password UTF8String]));
429 bool good(memcmp(client->authChallenge, data, size) == 0);
430 [pool release];
431 return good;
432 } return TRUE;
433 }
434 }
435
436 static bool iPad1_;
437
438 struct VeencyEvent {
439 struct GSEventRecord record;
440 struct {
441 struct GSEventRecordInfo info;
442 struct GSPathInfo path;
443 } data;
444 };
445
446 static void VNCPointerOld(int buttons, int x, int y, CGPoint location, int diff, bool twas, bool tis);
447 static void VNCPointerNew(int buttons, int x, int y, CGPoint location, int diff, bool twas, bool tis);
448
449 static void VNCPointer(int buttons, int x, int y, rfbClientPtr client) {
450 if (ratio_ == 0)
451 return;
452
453 CGPoint location = {x, y};
454
455 if (width_ > height_) {
456 int t(x);
457 x = height_ - 1 - y;
458 y = t;
459
460 if (!iPad1_) {
461 x = height_ - 1 - x;
462 y = width_ - 1 - y;
463 }
464 }
465
466 x /= ratio_;
467 y /= ratio_;
468
469 x_ = x; y_ = y;
470 int diff = buttons_ ^ buttons;
471 bool twas((buttons_ & 0x1) != 0);
472 bool tis((buttons & 0x1) != 0);
473 buttons_ = buttons;
474
475 rfbDefaultPtrAddEvent(buttons, x, y, client);
476
477 if (Ashikase(false)) {
478 AshikaseSendEvent(x, y, buttons);
479 return;
480 }
481
482 if (kCFCoreFoundationVersionNumber >= 800)
483 return VNCPointerNew(buttons, x, y, location, diff, twas, tis);
484 else
485 return VNCPointerOld(buttons, x, y, location, diff, twas, tis);
486 }
487
488 static void VNCPointerOld(int buttons, int x, int y, CGPoint location, int diff, bool twas, bool tis) {
489 mach_port_t purple(0);
490
491 if ((diff & 0x10) != 0) {
492 struct GSEventRecord record;
493
494 memset(&record, 0, sizeof(record));
495
496 record.type = (buttons & 0x10) != 0 ?
497 GSEventTypeHeadsetButtonDown :
498 GSEventTypeHeadsetButtonUp;
499
500 record.timestamp = GSCurrentEventTimestamp();
501
502 FixRecord(&record);
503 GSSendSystemEvent(&record);
504 }
505
506 if ((diff & 0x04) != 0) {
507 struct GSEventRecord record;
508
509 memset(&record, 0, sizeof(record));
510
511 record.type = (buttons & 0x04) != 0 ?
512 GSEventTypeMenuButtonDown :
513 GSEventTypeMenuButtonUp;
514
515 record.timestamp = GSCurrentEventTimestamp();
516
517 FixRecord(&record);
518 GSSendSystemEvent(&record);
519 }
520
521 if ((diff & 0x02) != 0) {
522 struct GSEventRecord record;
523
524 memset(&record, 0, sizeof(record));
525
526 record.type = (buttons & 0x02) != 0 ?
527 GSEventTypeLockButtonDown :
528 GSEventTypeLockButtonUp;
529
530 record.timestamp = GSCurrentEventTimestamp();
531
532 FixRecord(&record);
533 GSSendSystemEvent(&record);
534 }
535
536 if (twas != tis || tis) {
537 struct VeencyEvent event;
538
539 memset(&event, 0, sizeof(event));
540
541 event.record.type = GSEventTypeMouse;
542 event.record.locationInWindow.x = x;
543 event.record.locationInWindow.y = y;
544 event.record.timestamp = GSCurrentEventTimestamp();
545 event.record.size = sizeof(event.data);
546
547 event.data.info.handInfo.type = twas == tis ?
548 GSMouseEventTypeDragged :
549 tis ?
550 GSMouseEventTypeDown :
551 GSMouseEventTypeUp;
552
553 event.data.info.handInfo.x34 = 0x1;
554 event.data.info.handInfo.x38 = tis ? 0x1 : 0x0;
555
556 if (Level_ < 3)
557 event.data.info.pathPositions = 1;
558 else
559 event.data.info.x52 = 1;
560
561 event.data.path.x00 = 0x01;
562 event.data.path.x01 = 0x02;
563 event.data.path.x02 = tis ? 0x03 : 0x00;
564 event.data.path.position = event.record.locationInWindow;
565
566 mach_port_t port(0);
567
568 if (CAWindowServer *server = [CAWindowServer serverIfRunning]) {
569 NSArray *displays([server displays]);
570 if (displays != nil && [displays count] != 0)
571 if (CAWindowServerDisplay *display = [displays objectAtIndex:0])
572 port = [display clientPortAtPosition:location];
573 }
574
575 if (port == 0) {
576 if (purple == 0)
577 purple = (*GSTakePurpleSystemEventPort)();
578 port = purple;
579 }
580
581 FixRecord(&event.record);
582 GSSendEvent(&event.record, port);
583 }
584
585 if (purple != 0 && PurpleAllocated)
586 mach_port_deallocate(mach_task_self(), purple);
587 }
588
589 static void VNCSendHIDEvent(IOHIDEventRef event) {
590 static IOHIDEventSystemClientRef client_(NULL);
591 if (client_ == NULL)
592 client_ = IOHIDEventSystemClientCreate(kCFAllocatorDefault);
593 IOHIDEventSetSenderID(event, 0xDEFACEDBEEFFECE5);
594
595 IOHIDEventSystemClientDispatchEvent(client_, event);
596 CFRelease(event);
597 }
598
599 static void VNCPointerNew(int buttons, int x, int y, CGPoint location, int diff, bool twas, bool tis) {
600 if ((diff & 0x10) != 0)
601 VNCSendHIDEvent(IOHIDEventCreateKeyboardEvent(kCFAllocatorDefault, mach_absolute_time(), kHIDPage_Telephony, kHIDUsage_Tfon_Flash, (buttons & 0x10) != 0, 0));
602 if ((diff & 0x04) != 0)
603 VNCSendHIDEvent(IOHIDEventCreateKeyboardEvent(kCFAllocatorDefault, mach_absolute_time(), kHIDPage_Consumer, kHIDUsage_Csmr_Menu, (buttons & 0x04) != 0, 0));
604 if ((diff & 0x02) != 0)
605 VNCSendHIDEvent(IOHIDEventCreateKeyboardEvent(kCFAllocatorDefault, mach_absolute_time(), kHIDPage_Consumer, kHIDUsage_Csmr_Power, (buttons & 0x02) != 0, 0));
606
607 if (twas != tis || tis) {
608 }
609 }
610
611 GSEventRef (*$GSEventCreateKeyEvent)(int, CGPoint, CFStringRef, CFStringRef, id, UniChar, short, short);
612 GSEventRef (*$GSCreateSyntheticKeyEvent)(UniChar, BOOL, BOOL);
613
614 static void VNCKeyboardNew(rfbBool down, rfbKeySym key, rfbClientPtr client) {
615 //NSLog(@"VNC d:%u k:%04x", down, key);
616
617 uint16_t usage;
618
619 switch (key) {
620 case XK_A: case XK_a: usage = kHIDUsage_KeyboardA; break;
621 case XK_B: case XK_b: usage = kHIDUsage_KeyboardB; break;
622 case XK_C: case XK_c: usage = kHIDUsage_KeyboardC; break;
623 case XK_D: case XK_d: usage = kHIDUsage_KeyboardD; break;
624 case XK_E: case XK_e: usage = kHIDUsage_KeyboardE; break;
625 case XK_F: case XK_f: usage = kHIDUsage_KeyboardF; break;
626 case XK_G: case XK_g: usage = kHIDUsage_KeyboardG; break;
627 case XK_H: case XK_h: usage = kHIDUsage_KeyboardH; break;
628 case XK_I: case XK_i: usage = kHIDUsage_KeyboardI; break;
629 case XK_J: case XK_j: usage = kHIDUsage_KeyboardJ; break;
630 case XK_K: case XK_k: usage = kHIDUsage_KeyboardK; break;
631 case XK_L: case XK_l: usage = kHIDUsage_KeyboardL; break;
632 case XK_M: case XK_m: usage = kHIDUsage_KeyboardM; break;
633 case XK_N: case XK_n: usage = kHIDUsage_KeyboardN; break;
634 case XK_O: case XK_o: usage = kHIDUsage_KeyboardO; break;
635 case XK_P: case XK_p: usage = kHIDUsage_KeyboardP; break;
636 case XK_Q: case XK_q: usage = kHIDUsage_KeyboardQ; break;
637 case XK_R: case XK_r: usage = kHIDUsage_KeyboardR; break;
638 case XK_S: case XK_s: usage = kHIDUsage_KeyboardS; break;
639 case XK_T: case XK_t: usage = kHIDUsage_KeyboardT; break;
640 case XK_U: case XK_u: usage = kHIDUsage_KeyboardU; break;
641 case XK_V: case XK_v: usage = kHIDUsage_KeyboardV; break;
642 case XK_W: case XK_w: usage = kHIDUsage_KeyboardW; break;
643 case XK_X: case XK_x: usage = kHIDUsage_KeyboardX; break;
644 case XK_Y: case XK_y: usage = kHIDUsage_KeyboardY; break;
645 case XK_Z: case XK_z: usage = kHIDUsage_KeyboardZ; break;
646
647 case XK_underscore: case XK_minus: usage = kHIDUsage_KeyboardHyphen; break;
648 case XK_plus: case XK_equal: usage = kHIDUsage_KeyboardEqualSign; break;
649 case XK_braceleft: case XK_bracketleft: usage = kHIDUsage_KeyboardOpenBracket; break;
650 case XK_braceright: case XK_bracketright: usage = kHIDUsage_KeyboardCloseBracket; break;
651 case XK_bar: case XK_backslash: usage = kHIDUsage_KeyboardBackslash; break;
652 case XK_colon: case XK_semicolon: usage = kHIDUsage_KeyboardSemicolon; break;
653 case XK_quotedbl: case XK_apostrophe: usage = kHIDUsage_KeyboardQuote; break;
654 case XK_asciitilde: case XK_grave: usage = kHIDUsage_KeyboardGraveAccentAndTilde; break;
655 case XK_less: case XK_comma: usage = kHIDUsage_KeyboardComma; break;
656 case XK_greater: case XK_period: usage = kHIDUsage_KeyboardPeriod; break;
657 case XK_question: case XK_slash: usage = kHIDUsage_KeyboardSlash; break;
658
659 case XK_Return: usage = kHIDUsage_KeyboardReturnOrEnter; break;
660 case XK_BackSpace: usage = kHIDUsage_KeyboardDeleteOrBackspace; break;
661 case XK_Tab: usage = kHIDUsage_KeyboardTab; break;
662 case XK_space: usage = kHIDUsage_KeyboardSpacebar; break;
663
664 case XK_Shift_L: usage = kHIDUsage_KeyboardLeftShift; break;
665 case XK_Shift_R: usage = kHIDUsage_KeyboardRightShift; break;
666 case XK_Control_L: usage = kHIDUsage_KeyboardLeftControl; break;
667 case XK_Control_R: usage = kHIDUsage_KeyboardRightControl; break;
668 case XK_Meta_L: usage = kHIDUsage_KeyboardLeftAlt; break;
669 case XK_Meta_R: usage = kHIDUsage_KeyboardRightAlt; break;
670 case XK_Alt_L: usage = kHIDUsage_KeyboardLeftGUI; break;
671 case XK_Alt_R: usage = kHIDUsage_KeyboardRightGUI; break;
672
673 case XK_Up: usage = kHIDUsage_KeyboardUpArrow; break;
674 case XK_Down: usage = kHIDUsage_KeyboardDownArrow; break;
675 case XK_Left: usage = kHIDUsage_KeyboardLeftArrow; break;
676 case XK_Right: usage = kHIDUsage_KeyboardRightArrow; break;
677
678 case XK_Home: case XK_Begin: usage = kHIDUsage_KeyboardHome; break;
679 case XK_End: usage = kHIDUsage_KeyboardEnd; break;
680 case XK_Page_Up: usage = kHIDUsage_KeyboardPageUp; break;
681 case XK_Page_Down: usage = kHIDUsage_KeyboardPageDown; break;
682
683 default: return;
684 }
685
686 VNCSendHIDEvent(IOHIDEventCreateKeyboardEvent(kCFAllocatorDefault, mach_absolute_time(), kHIDPage_KeyboardOrKeypad, usage, down, 0));
687 }
688
689 static void VNCKeyboard(rfbBool down, rfbKeySym key, rfbClientPtr client) {
690 if (kCFCoreFoundationVersionNumber >= 800)
691 return VNCKeyboardNew(down, key, client);
692
693 if (!down)
694 return;
695
696 switch (key) {
697 case XK_Return: key = '\r'; break;
698 case XK_BackSpace: key = 0x7f; break;
699 }
700
701 if (key > 0xfff)
702 return;
703
704 CGPoint point(CGPointMake(x_, y_));
705
706 UniChar unicode(key);
707 CFStringRef string(NULL);
708
709 GSEventRef event0, event1(NULL);
710 if ($GSEventCreateKeyEvent != NULL) {
711 string = CFStringCreateWithCharacters(kCFAllocatorDefault, &unicode, 1);
712 event0 = (*$GSEventCreateKeyEvent)(10, point, string, string, nil, 0, 0, 1);
713 event1 = (*$GSEventCreateKeyEvent)(11, point, string, string, nil, 0, 0, 1);
714 } else if ($GSCreateSyntheticKeyEvent != NULL) {
715 event0 = (*$GSCreateSyntheticKeyEvent)(unicode, YES, YES);
716 GSEventRecord *record(_GSEventGetGSEventRecord(event0));
717 record->type = GSEventTypeKeyDown;
718 } else return;
719
720 mach_port_t port(0);
721
722 if (CAWindowServer *server = [CAWindowServer serverIfRunning]) {
723 NSArray *displays([server displays]);
724 if (displays != nil && [displays count] != 0)
725 if (CAWindowServerDisplay *display = [displays objectAtIndex:0])
726 port = [display clientPortAtPosition:point];
727 }
728
729 mach_port_t purple(0);
730
731 if (port == 0) {
732 if (purple == 0)
733 purple = (*GSTakePurpleSystemEventPort)();
734 port = purple;
735 }
736
737 if (port != 0) {
738 GSSendEvent(_GSEventGetGSEventRecord(event0), port);
739 if (event1 != NULL)
740 GSSendEvent(_GSEventGetGSEventRecord(event1), port);
741 }
742
743 if (purple != 0 && PurpleAllocated)
744 mach_port_deallocate(mach_task_self(), purple);
745
746 CFRelease(event0);
747 if (event1 != NULL)
748 CFRelease(event1);
749 if (string != NULL)
750 CFRelease(string);
751 }
752
753 static void VNCDisconnect(rfbClientPtr client) {
754 @synchronized (condition_) {
755 if (--clients_ == 0)
756 [VNCBridge performSelectorOnMainThread:@selector(removeStatusBarItem) withObject:nil waitUntilDone:YES];
757 }
758 }
759
760 static rfbNewClientAction VNCClient(rfbClientPtr client) {
761 @synchronized (condition_) {
762 if (screen_->authPasswdData != NULL) {
763 [VNCBridge performSelectorOnMainThread:@selector(registerClient) withObject:nil waitUntilDone:YES];
764 client->clientGoneHook = &VNCDisconnect;
765 return RFB_CLIENT_ACCEPT;
766 }
767 }
768
769 [condition_ lock];
770 client_ = client;
771 [VNCBridge performSelectorOnMainThread:@selector(askForConnection) withObject:nil waitUntilDone:NO];
772 while (action_ == RFB_CLIENT_ON_HOLD)
773 [condition_ wait];
774 rfbNewClientAction action(action_);
775 action_ = RFB_CLIENT_ON_HOLD;
776 [condition_ unlock];
777
778 if (action == RFB_CLIENT_ACCEPT)
779 client->clientGoneHook = &VNCDisconnect;
780 return action;
781 }
782
783 extern "C" bool GSSystemHasCapability(NSString *);
784
785 static CFTypeRef (*$GSSystemCopyCapability)(CFStringRef);
786 static CFTypeRef (*$GSSystemGetCapability)(CFStringRef);
787 static BOOL (*$MGGetBoolAnswer)(CFStringRef);
788
789 static void VNCSetup() {
790 rfbLogEnable(false);
791
792 @synchronized (condition_) {
793 int argc(1);
794 char *arg0(strdup("VNCServer"));
795 char *argv[] = {arg0, NULL};
796 screen_ = rfbGetScreen(&argc, argv, width_, height_, BitsPerSample, 3, BytesPerPixel);
797 free(arg0);
798
799 VNCSettings();
800 }
801
802 screen_->desktopName = strdup([[[NSProcessInfo processInfo] hostName] UTF8String]);
803
804 screen_->alwaysShared = TRUE;
805 screen_->handleEventsEagerly = TRUE;
806 screen_->deferUpdateTime = 1000 / 25;
807
808 screen_->serverFormat.redShift = BitsPerSample * 2;
809 screen_->serverFormat.greenShift = BitsPerSample * 1;
810 screen_->serverFormat.blueShift = BitsPerSample * 0;
811
812 $GSSystemCopyCapability = reinterpret_cast<CFTypeRef (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, "GSSystemCopyCapability"));
813 $GSSystemGetCapability = reinterpret_cast<CFTypeRef (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, "GSSystemGetCapability"));
814 $MGGetBoolAnswer = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, "MGGetBoolAnswer"));
815
816 CFTypeRef opengles2;
817
818 if ($GSSystemCopyCapability != NULL) {
819 opengles2 = (*$GSSystemCopyCapability)(CFSTR("opengles-2"));
820 } else if ($GSSystemGetCapability != NULL) {
821 opengles2 = (*$GSSystemGetCapability)(CFSTR("opengles-2"));
822 if (opengles2 != NULL)
823 CFRetain(opengles2);
824 } else if ($MGGetBoolAnswer != NULL) {
825 opengles2 = $MGGetBoolAnswer(CFSTR("opengles-2")) ? kCFBooleanTrue : kCFBooleanFalse;
826 CFRetain(opengles2);
827 } else
828 opengles2 = NULL;
829
830 bool accelerated(opengles2 != NULL && [(NSNumber *)opengles2 boolValue]);
831
832 if (accelerated)
833 CoreSurfaceAcceleratorCreate(NULL, NULL, &accelerator_);
834
835 if (opengles2 != NULL)
836 CFRelease(opengles2);
837
838 if (accelerator_ != NULL)
839 buffer_ = CoreSurfaceBufferCreate((CFDictionaryRef) [NSDictionary dictionaryWithObjectsAndKeys:
840 @"PurpleEDRAM", kCoreSurfaceBufferMemoryRegion,
841 [NSNumber numberWithBool:YES], kCoreSurfaceBufferGlobal,
842 [NSNumber numberWithInt:(width_ * BytesPerPixel)], kCoreSurfaceBufferPitch,
843 [NSNumber numberWithInt:width_], kCoreSurfaceBufferWidth,
844 [NSNumber numberWithInt:height_], kCoreSurfaceBufferHeight,
845 [NSNumber numberWithInt:'BGRA'], kCoreSurfaceBufferPixelFormat,
846 [NSNumber numberWithInt:(width_ * height_ * BytesPerPixel)], kCoreSurfaceBufferAllocSize,
847 nil]);
848 else
849 VNCBlack();
850
851 //screen_->frameBuffer = reinterpret_cast<char *>(mmap(NULL, sizeof(rfbPixel) * width_ * height_, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE | MAP_NOCACHE, VM_FLAGS_PURGABLE, 0));
852
853 CoreSurfaceBufferLock(buffer_, 3);
854 screen_->frameBuffer = reinterpret_cast<char *>(CoreSurfaceBufferGetBaseAddress(buffer_));
855 CoreSurfaceBufferUnlock(buffer_);
856
857 screen_->kbdAddEvent = &VNCKeyboard;
858 screen_->ptrAddEvent = &VNCPointer;
859
860 screen_->newClientHook = &VNCClient;
861 screen_->passwordCheck = &VNCCheck;
862
863 screen_->cursor = NULL;
864 }
865
866 static void VNCEnabled() {
867 if (screen_ == NULL)
868 return;
869
870 [lock_ lock];
871
872 bool enabled(true);
873 if (NSDictionary *settings = [NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/Library/Preferences/com.saurik.Veency.plist", NSHomeDirectory()]])
874 if (NSNumber *number = [settings objectForKey:@"Enabled"])
875 enabled = [number boolValue];
876
877 if (enabled != running_)
878 if (enabled) {
879 running_ = true;
880 screen_->socketState = RFB_SOCKET_INIT;
881 rfbInitServer(screen_);
882 rfbRunEventLoop(screen_, -1, true);
883 } else {
884 rfbShutdownServer(screen_, true);
885 running_ = false;
886 }
887
888 [lock_ unlock];
889 }
890
891 static void VNCNotifyEnabled(
892 CFNotificationCenterRef center,
893 void *observer,
894 CFStringRef name,
895 const void *object,
896 CFDictionaryRef info
897 ) {
898 VNCEnabled();
899 }
900
901 void (*$IOMobileFramebufferIsMainDisplay)(IOMobileFramebufferRef, int *);
902
903 static IOMobileFramebufferRef main_;
904 static CoreSurfaceBufferRef layer_;
905
906 static void OnLayer(IOMobileFramebufferRef fb, CoreSurfaceBufferRef layer) {
907 if (_unlikely(width_ == 0 || height_ == 0)) {
908 CGSize size;
909 IOMobileFramebufferGetDisplaySize(fb, &size);
910
911 width_ = size.width;
912 height_ = size.height;
913
914 if (width_ == 0 || height_ == 0)
915 return;
916
917 NSThread *thread([NSThread alloc]);
918
919 [thread
920 initWithTarget:[VNCBridge class]
921 selector:@selector(performSetup:)
922 object:thread
923 ];
924
925 [thread start];
926 } else if (_unlikely(clients_ != 0)) {
927 if (layer == NULL) {
928 if (accelerator_ != NULL)
929 memset(screen_->frameBuffer, 0, sizeof(rfbPixel) * width_ * height_);
930 else
931 VNCBlack();
932 } else {
933 if (accelerator_ != NULL)
934 CoreSurfaceAcceleratorTransferSurface(accelerator_, layer, buffer_, options_);
935 else {
936 CoreSurfaceBufferLock(layer, 2);
937 rfbPixel *data(reinterpret_cast<rfbPixel *>(CoreSurfaceBufferGetBaseAddress(layer)));
938
939 CoreSurfaceBufferFlushProcessorCaches(layer);
940
941 /*rfbPixel corner(data[0]);
942 data[0] = 0;
943 data[0] = corner;*/
944
945 screen_->frameBuffer = const_cast<char *>(reinterpret_cast<volatile char *>(data));
946 CoreSurfaceBufferUnlock(layer);
947 }
948 }
949
950 rfbMarkRectAsModified(screen_, 0, 0, width_, height_);
951 }
952 }
953
954 static bool wait_ = false;
955
956 MSHook(kern_return_t, IOMobileFramebufferSwapSetLayer,
957 IOMobileFramebufferRef fb,
958 int layer,
959 CoreSurfaceBufferRef buffer,
960 CGRect bounds,
961 CGRect frame,
962 int flags
963 ) {
964 int main(false);
965
966 if (_unlikely(buffer == NULL))
967 main = fb == main_;
968 else if (_unlikely(fb == NULL))
969 main = false;
970 else if ($IOMobileFramebufferIsMainDisplay == NULL)
971 main = true;
972 else
973 (*$IOMobileFramebufferIsMainDisplay)(fb, &main);
974
975 if (_likely(main)) {
976 main_ = fb;
977 if (wait_)
978 layer_ = buffer;
979 else
980 OnLayer(fb, buffer);
981 }
982
983 return _IOMobileFramebufferSwapSetLayer(fb, layer, buffer, bounds, frame, flags);
984 }
985
986 // XXX: beg rpetrich for the type of this function
987 extern "C" void *IOMobileFramebufferSwapWait(IOMobileFramebufferRef, void *, unsigned);
988
989 MSHook(void *, IOMobileFramebufferSwapWait, IOMobileFramebufferRef fb, void *arg1, unsigned flags) {
990 void *value(_IOMobileFramebufferSwapWait(fb, arg1, flags));
991 if (fb == main_)
992 OnLayer(fb, layer_);
993 return value;
994 }
995
996 MSHook(void, rfbRegisterSecurityHandler, rfbSecurityHandler *handler) {
997 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
998
999 @synchronized (lock_) {
1000 [handlers_ addObject:[NSValue valueWithPointer:handler]];
1001 _rfbRegisterSecurityHandler(handler);
1002 }
1003
1004 [pool release];
1005 }
1006
1007 template <typename Type_>
1008 static void dlset(Type_ &function, const char *name) {
1009 function = reinterpret_cast<Type_>(dlsym(RTLD_DEFAULT, name));
1010 }
1011
1012 MSInitialize {
1013 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
1014
1015 MSHookSymbol(GSTakePurpleSystemEventPort, "_GSGetPurpleSystemEventPort");
1016 if (GSTakePurpleSystemEventPort == NULL) {
1017 MSHookSymbol(GSTakePurpleSystemEventPort, "_GSCopyPurpleSystemEventPort");
1018 PurpleAllocated = true;
1019 }
1020
1021 if (dlsym(RTLD_DEFAULT, "GSLibraryCopyGenerationInfoValueForKey") != NULL)
1022 Level_ = 3;
1023 else if (dlsym(RTLD_DEFAULT, "GSKeyboardCreate") != NULL)
1024 Level_ = 2;
1025 else if (dlsym(RTLD_DEFAULT, "GSEventGetWindowContextId") != NULL)
1026 Level_ = 1;
1027 else
1028 Level_ = 0;
1029
1030 size_t size;
1031 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
1032 char machine[size];
1033 sysctlbyname("hw.machine", machine, &size, NULL, 0);
1034 iPad1_ = strcmp(machine, "iPad1,1") == 0;
1035
1036 dlset($GSMainScreenScaleFactor, "GSMainScreenScaleFactor");
1037 dlset($GSEventCreateKeyEvent, "GSEventCreateKeyEvent");
1038 dlset($GSCreateSyntheticKeyEvent, "_GSCreateSyntheticKeyEvent");
1039 dlset($IOMobileFramebufferIsMainDisplay, "IOMobileFramebufferIsMainDisplay");
1040
1041 MSHookFunction(&IOMobileFramebufferSwapSetLayer, MSHake(IOMobileFramebufferSwapSetLayer));
1042 MSHookFunction(&rfbRegisterSecurityHandler, MSHake(rfbRegisterSecurityHandler));
1043
1044 if (wait_)
1045 MSHookFunction(&IOMobileFramebufferSwapWait, MSHake(IOMobileFramebufferSwapWait));
1046
1047 if ($SBAlertItem != nil) {
1048 $VNCAlertItem = objc_allocateClassPair($SBAlertItem, "VNCAlertItem", 0);
1049 MSAddMessage2(VNCAlertItem, "v@:@i", alertSheet,buttonClicked);
1050 MSAddMessage2(VNCAlertItem, "v@:cc", configure,requirePasscodeForActions);
1051 MSAddMessage0(VNCAlertItem, "v@:", performUnlockAction);
1052 objc_registerClassPair($VNCAlertItem);
1053 }
1054
1055 CFNotificationCenterAddObserver(
1056 CFNotificationCenterGetDarwinNotifyCenter(),
1057 NULL, &VNCNotifyEnabled, CFSTR("com.saurik.Veency-Enabled"), NULL, 0
1058 );
1059
1060 CFNotificationCenterAddObserver(
1061 CFNotificationCenterGetDarwinNotifyCenter(),
1062 NULL, &VNCNotifySettings, CFSTR("com.saurik.Veency-Settings"), NULL, 0
1063 );
1064
1065 condition_ = [[NSCondition alloc] init];
1066 lock_ = [[NSLock alloc] init];
1067 handlers_ = [[NSMutableSet alloc] init];
1068
1069 bool value;
1070
1071 value = true;
1072 cfTrue_ = CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&value), sizeof(value));
1073
1074 value = false;
1075 cfFalse_ = CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&value), sizeof(value));
1076
1077 cfEvent_ = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&event_), sizeof(event_), kCFAllocatorNull);
1078
1079 options_ = (CFDictionaryRef) [[NSDictionary dictionaryWithObjectsAndKeys:
1080 nil] retain];
1081
1082 [pool release];
1083 }