]> git.saurik.com Git - veency.git/blob - Tweak.mm
6ebe403f679340b830b9e8d24ebf5cf4414f56fb
[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 <CydiaSubstrate.h>
30
31 #include <rfb/rfb.h>
32 #include <rfb/keysym.h>
33
34 #include <mach/mach_port.h>
35 #include <sys/mman.h>
36 #include <sys/sysctl.h>
37
38 #import <QuartzCore/CAWindowServer.h>
39 #import <QuartzCore/CAWindowServerDisplay.h>
40
41 #import <CoreGraphics/CGGeometry.h>
42 #import <GraphicsServices/GraphicsServices.h>
43 #import <Foundation/Foundation.h>
44 #import <IOMobileFramebuffer/IOMobileFramebuffer.h>
45 #import <IOKit/IOKitLib.h>
46 #import <UIKit/UIKit.h>
47
48 #import <SpringBoard/SBAlertItemsController.h>
49 #import <SpringBoard/SBDismissOnlyAlertItem.h>
50 #import <SpringBoard/SBStatusBarController.h>
51
52 #include "SpringBoardAccess.h"
53
54 MSClassHook(UIApplication)
55
56 extern "C" void CoreSurfaceBufferFlushProcessorCaches(CoreSurfaceBufferRef buffer);
57
58 static size_t width_;
59 static size_t height_;
60 static NSUInteger ratio_ = 0;
61
62 static const size_t BytesPerPixel = 4;
63 static const size_t BitsPerSample = 8;
64
65 static CoreSurfaceAcceleratorRef accelerator_;
66 static CoreSurfaceBufferRef buffer_;
67 static CFDictionaryRef options_;
68
69 static NSMutableSet *handlers_;
70 static rfbScreenInfoPtr screen_;
71 static bool running_;
72 static int buttons_;
73 static int x_, y_;
74
75 static unsigned clients_;
76
77 static CFMessagePortRef ashikase_;
78 static bool cursor_;
79
80 static rfbPixel *black_;
81
82 static void VNCBlack() {
83 if (_unlikely(black_ == NULL))
84 black_ = reinterpret_cast<rfbPixel *>(mmap(NULL, sizeof(rfbPixel) * width_ * height_, PROT_READ, MAP_ANON | MAP_PRIVATE | MAP_NOCACHE, VM_FLAGS_PURGABLE, 0));
85 screen_->frameBuffer = reinterpret_cast<char *>(black_);
86 }
87
88 static bool Ashikase(bool always) {
89 if (!always && !cursor_)
90 return false;
91
92 if (ashikase_ == NULL)
93 ashikase_ = CFMessagePortCreateRemote(kCFAllocatorDefault, CFSTR("jp.ashikase.mousesupport"));
94 if (ashikase_ != NULL)
95 return true;
96
97 cursor_ = false;
98 return false;
99 }
100
101 static CFDataRef cfTrue_;
102 static CFDataRef cfFalse_;
103
104 typedef struct {
105 float x, y;
106 int buttons;
107 BOOL absolute;
108 } MouseEvent;
109
110 static MouseEvent event_;
111 static CFDataRef cfEvent_;
112
113 typedef enum {
114 MouseMessageTypeEvent,
115 MouseMessageTypeSetEnabled
116 } MouseMessageType;
117
118 static void AshikaseSendEvent(float x, float y, int buttons = 0) {
119 event_.x = x;
120 event_.y = y;
121 event_.buttons = buttons;
122 event_.absolute = true;
123
124 CFMessagePortSendRequest(ashikase_, MouseMessageTypeEvent, cfEvent_, 0, 0, NULL, NULL);
125 }
126
127 static void AshikaseSetEnabled(bool enabled, bool always) {
128 if (!Ashikase(always))
129 return;
130
131 CFMessagePortSendRequest(ashikase_, MouseMessageTypeSetEnabled, enabled ? cfTrue_ : cfFalse_, 0, 0, NULL, NULL);
132
133 if (enabled)
134 AshikaseSendEvent(x_, y_);
135 }
136
137 MSClassHook(SBAlertItem)
138 MSClassHook(SBAlertItemsController)
139 MSClassHook(SBStatusBarController)
140
141 @class VNCAlertItem;
142 static Class $VNCAlertItem;
143
144 static NSString *DialogTitle(@"Remote Access Request");
145 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!");
146 static NSString *DialogAccept(@"Accept");
147 static NSString *DialogReject(@"Reject");
148
149 static volatile rfbNewClientAction action_ = RFB_CLIENT_ON_HOLD;
150 static NSCondition *condition_;
151 static NSLock *lock_;
152
153 static rfbClientPtr client_;
154
155 static void VNCSetup();
156 static void VNCEnabled();
157
158 float (*$GSMainScreenScaleFactor)();
159
160 static void OnUserNotification(CFUserNotificationRef notification, CFOptionFlags flags) {
161 [condition_ lock];
162
163 if ((flags & 0x3) == 1)
164 action_ = RFB_CLIENT_ACCEPT;
165 else
166 action_ = RFB_CLIENT_REFUSE;
167
168 [condition_ signal];
169 [condition_ unlock];
170
171 CFRelease(notification);
172 }
173
174 @interface VNCBridge : NSObject {
175 }
176
177 + (void) askForConnection;
178 + (void) removeStatusBarItem;
179 + (void) registerClient;
180
181 @end
182
183 @implementation VNCBridge
184
185 + (void) askForConnection {
186 if ($VNCAlertItem != nil) {
187 [[$SBAlertItemsController sharedInstance] activateAlertItem:[[[$VNCAlertItem alloc] init] autorelease]];
188 return;
189 }
190
191 SInt32 error;
192 CFUserNotificationRef notification(CFUserNotificationCreate(kCFAllocatorDefault, 0, kCFUserNotificationPlainAlertLevel, &error, (CFDictionaryRef) [NSDictionary dictionaryWithObjectsAndKeys:
193 DialogTitle, kCFUserNotificationAlertHeaderKey,
194 [NSString stringWithFormat:DialogFormat, client_->host], kCFUserNotificationAlertMessageKey,
195 DialogAccept, kCFUserNotificationAlternateButtonTitleKey,
196 DialogReject, kCFUserNotificationDefaultButtonTitleKey,
197 nil]));
198
199 if (error != 0) {
200 CFRelease(notification);
201 notification = NULL;
202 }
203
204 if (notification == NULL) {
205 [condition_ lock];
206 action_ = RFB_CLIENT_REFUSE;
207 [condition_ signal];
208 [condition_ unlock];
209 return;
210 }
211
212 CFRunLoopSourceRef source(CFUserNotificationCreateRunLoopSource(kCFAllocatorDefault, notification, &OnUserNotification, 0));
213 CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode);
214 }
215
216 + (void) removeStatusBarItem {
217 AshikaseSetEnabled(false, false);
218
219 if (SBA_available())
220 SBA_removeStatusBarImage(const_cast<char *>("Veency"));
221 else if ($SBStatusBarController != nil)
222 [[$SBStatusBarController sharedStatusBarController] removeStatusBarItem:@"Veency"];
223 else if (UIApplication *app = [$UIApplication sharedApplication])
224 [app removeStatusBarImageNamed:@"Veency"];
225 }
226
227 + (void) registerClient {
228 // XXX: this could find a better home
229 if (ratio_ == 0) {
230 if ($GSMainScreenScaleFactor == NULL)
231 ratio_ = 1.0f;
232 else
233 ratio_ = $GSMainScreenScaleFactor();
234 }
235
236 ++clients_;
237 AshikaseSetEnabled(true, false);
238
239 if (SBA_available())
240 SBA_addStatusBarImage(const_cast<char *>("Veency"));
241 else if ($SBStatusBarController != nil)
242 [[$SBStatusBarController sharedStatusBarController] addStatusBarItem:@"Veency"];
243 else if (UIApplication *app = [$UIApplication sharedApplication])
244 [app addStatusBarImageNamed:@"Veency"];
245 }
246
247 + (void) performSetup:(NSThread *)thread {
248 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
249 [thread autorelease];
250 VNCSetup();
251 VNCEnabled();
252 [pool release];
253 }
254
255 @end
256
257 MSInstanceMessage2(void, VNCAlertItem, alertSheet,buttonClicked, id, sheet, int, button) {
258 [condition_ lock];
259
260 switch (button) {
261 case 1:
262 action_ = RFB_CLIENT_ACCEPT;
263
264 @synchronized (condition_) {
265 [VNCBridge registerClient];
266 }
267 break;
268
269 case 2:
270 action_ = RFB_CLIENT_REFUSE;
271 break;
272 }
273
274 [condition_ signal];
275 [condition_ unlock];
276 [self dismiss];
277 }
278
279 MSInstanceMessage2(void, VNCAlertItem, configure,requirePasscodeForActions, BOOL, configure, BOOL, require) {
280 UIModalView *sheet([self alertSheet]);
281 [sheet setDelegate:self];
282 [sheet setTitle:DialogTitle];
283 [sheet setBodyText:[NSString stringWithFormat:DialogFormat, client_->host]];
284 [sheet addButtonWithTitle:DialogAccept];
285 [sheet addButtonWithTitle:DialogReject];
286 }
287
288 MSInstanceMessage0(void, VNCAlertItem, performUnlockAction) {
289 [[$SBAlertItemsController sharedInstance] activateAlertItem:self];
290 }
291
292 static mach_port_t (*GSTakePurpleSystemEventPort)(void);
293 static bool PurpleAllocated;
294 static int Level_;
295
296 static void FixRecord(GSEventRecord *record) {
297 if (Level_ < 1)
298 memmove(&record->windowContextId, &record->windowContextId + 1, sizeof(*record) - (reinterpret_cast<uint8_t *>(&record->windowContextId + 1) - reinterpret_cast<uint8_t *>(record)) + record->size);
299 }
300
301 static void VNCSettings() {
302 NSDictionary *settings([NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/Library/Preferences/com.saurik.Veency.plist", NSHomeDirectory()]]);
303
304 @synchronized (lock_) {
305 for (NSValue *handler in handlers_)
306 rfbUnregisterSecurityHandler(reinterpret_cast<rfbSecurityHandler *>([handler pointerValue]));
307 [handlers_ removeAllObjects];
308 }
309
310 @synchronized (condition_) {
311 if (screen_ == NULL)
312 return;
313
314 [reinterpret_cast<NSString *>(screen_->authPasswdData) release];
315 screen_->authPasswdData = NULL;
316
317 if (settings != nil)
318 if (NSString *password = [settings objectForKey:@"Password"])
319 if ([password length] != 0)
320 screen_->authPasswdData = [password retain];
321
322 NSNumber *cursor = [settings objectForKey:@"ShowCursor"];
323 cursor_ = cursor == nil ? true : [cursor boolValue];
324
325 if (clients_ != 0)
326 AshikaseSetEnabled(cursor_, true);
327 }
328 }
329
330 static void VNCNotifySettings(
331 CFNotificationCenterRef center,
332 void *observer,
333 CFStringRef name,
334 const void *object,
335 CFDictionaryRef info
336 ) {
337 VNCSettings();
338 }
339
340 static rfbBool VNCCheck(rfbClientPtr client, const char *data, int size) {
341 @synchronized (condition_) {
342 if (NSString *password = reinterpret_cast<NSString *>(screen_->authPasswdData)) {
343 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
344 rfbEncryptBytes(client->authChallenge, const_cast<char *>([password UTF8String]));
345 bool good(memcmp(client->authChallenge, data, size) == 0);
346 [pool release];
347 return good;
348 } return TRUE;
349 }
350 }
351
352 static bool iPad1_;
353
354 struct VeencyEvent {
355 struct GSEventRecord record;
356 struct {
357 struct GSEventRecordInfo info;
358 struct GSPathInfo path;
359 } data;
360 };
361
362 static void VNCPointer(int buttons, int x, int y, rfbClientPtr client) {
363 if (ratio_ == 0)
364 return;
365
366 CGPoint location = {x, y};
367
368 if (width_ > height_) {
369 int t(x);
370 x = height_ - 1 - y;
371 y = t;
372
373 if (!iPad1_) {
374 x = height_ - 1 - x;
375 y = width_ - 1 - y;
376 }
377 }
378
379 x /= ratio_;
380 y /= ratio_;
381
382 x_ = x; y_ = y;
383 int diff = buttons_ ^ buttons;
384 bool twas((buttons_ & 0x1) != 0);
385 bool tis((buttons & 0x1) != 0);
386 buttons_ = buttons;
387
388 rfbDefaultPtrAddEvent(buttons, x, y, client);
389
390 if (Ashikase(false)) {
391 AshikaseSendEvent(x, y, buttons);
392 return;
393 }
394
395 mach_port_t purple(0);
396
397 if ((diff & 0x10) != 0) {
398 struct GSEventRecord record;
399
400 memset(&record, 0, sizeof(record));
401
402 record.type = (buttons & 0x10) != 0 ?
403 GSEventTypeHeadsetButtonDown :
404 GSEventTypeHeadsetButtonUp;
405
406 record.timestamp = GSCurrentEventTimestamp();
407
408 FixRecord(&record);
409 GSSendSystemEvent(&record);
410 }
411
412 if ((diff & 0x04) != 0) {
413 struct GSEventRecord record;
414
415 memset(&record, 0, sizeof(record));
416
417 record.type = (buttons & 0x04) != 0 ?
418 GSEventTypeMenuButtonDown :
419 GSEventTypeMenuButtonUp;
420
421 record.timestamp = GSCurrentEventTimestamp();
422
423 FixRecord(&record);
424 GSSendSystemEvent(&record);
425 }
426
427 if ((diff & 0x02) != 0) {
428 struct GSEventRecord record;
429
430 memset(&record, 0, sizeof(record));
431
432 record.type = (buttons & 0x02) != 0 ?
433 GSEventTypeLockButtonDown :
434 GSEventTypeLockButtonUp;
435
436 record.timestamp = GSCurrentEventTimestamp();
437
438 FixRecord(&record);
439 GSSendSystemEvent(&record);
440 }
441
442 if (twas != tis || tis) {
443 struct VeencyEvent event;
444
445 memset(&event, 0, sizeof(event));
446
447 event.record.type = GSEventTypeMouse;
448 event.record.locationInWindow.x = x;
449 event.record.locationInWindow.y = y;
450 event.record.timestamp = GSCurrentEventTimestamp();
451 event.record.size = sizeof(event.data);
452
453 event.data.info.handInfo.type = twas == tis ?
454 GSMouseEventTypeDragged :
455 tis ?
456 GSMouseEventTypeDown :
457 GSMouseEventTypeUp;
458
459 event.data.info.handInfo.x34 = 0x1;
460 event.data.info.handInfo.x38 = tis ? 0x1 : 0x0;
461
462 if (Level_ < 3)
463 event.data.info.pathPositions = 1;
464 else
465 event.data.info.x52 = 1;
466
467 event.data.path.x00 = 0x01;
468 event.data.path.x01 = 0x02;
469 event.data.path.x02 = tis ? 0x03 : 0x00;
470 event.data.path.position = event.record.locationInWindow;
471
472 mach_port_t port(0);
473
474 if (CAWindowServer *server = [CAWindowServer serverIfRunning]) {
475 NSArray *displays([server displays]);
476 if (displays != nil && [displays count] != 0)
477 if (CAWindowServerDisplay *display = [displays objectAtIndex:0])
478 port = [display clientPortAtPosition:location];
479 }
480
481 if (port == 0) {
482 if (purple == 0)
483 purple = (*GSTakePurpleSystemEventPort)();
484 port = purple;
485 }
486
487 FixRecord(&event.record);
488 GSSendEvent(&event.record, port);
489 }
490
491 if (purple != 0 && PurpleAllocated)
492 mach_port_deallocate(mach_task_self(), purple);
493 }
494
495 GSEventRef (*$GSEventCreateKeyEvent)(int, CGPoint, CFStringRef, CFStringRef, id, UniChar, short, short);
496 GSEventRef (*$GSCreateSyntheticKeyEvent)(UniChar, BOOL, BOOL);
497
498 static void VNCKeyboard(rfbBool down, rfbKeySym key, rfbClientPtr client) {
499 if (!down)
500 return;
501
502 switch (key) {
503 case XK_Return: key = '\r'; break;
504 case XK_BackSpace: key = 0x7f; break;
505 }
506
507 if (key > 0xfff)
508 return;
509
510 CGPoint point(CGPointMake(x_, y_));
511
512 UniChar unicode(key);
513 CFStringRef string(NULL);
514
515 GSEventRef event0, event1(NULL);
516 if ($GSEventCreateKeyEvent != NULL) {
517 string = CFStringCreateWithCharacters(kCFAllocatorDefault, &unicode, 1);
518 event0 = (*$GSEventCreateKeyEvent)(10, point, string, string, nil, 0, 0, 1);
519 event1 = (*$GSEventCreateKeyEvent)(11, point, string, string, nil, 0, 0, 1);
520 } else if ($GSCreateSyntheticKeyEvent != NULL) {
521 event0 = (*$GSCreateSyntheticKeyEvent)(unicode, YES, YES);
522 GSEventRecord *record(_GSEventGetGSEventRecord(event0));
523 record->type = GSEventTypeKeyDown;
524 } else return;
525
526 mach_port_t port(0);
527
528 if (CAWindowServer *server = [CAWindowServer serverIfRunning]) {
529 NSArray *displays([server displays]);
530 if (displays != nil && [displays count] != 0)
531 if (CAWindowServerDisplay *display = [displays objectAtIndex:0])
532 port = [display clientPortAtPosition:point];
533 }
534
535 mach_port_t purple(0);
536
537 if (port == 0) {
538 if (purple == 0)
539 purple = (*GSTakePurpleSystemEventPort)();
540 port = purple;
541 }
542
543 if (port != 0) {
544 GSSendEvent(_GSEventGetGSEventRecord(event0), port);
545 if (event1 != NULL)
546 GSSendEvent(_GSEventGetGSEventRecord(event1), port);
547 }
548
549 if (purple != 0 && PurpleAllocated)
550 mach_port_deallocate(mach_task_self(), purple);
551
552 CFRelease(event0);
553 if (event1 != NULL)
554 CFRelease(event1);
555 if (string != NULL)
556 CFRelease(string);
557 }
558
559 static void VNCDisconnect(rfbClientPtr client) {
560 @synchronized (condition_) {
561 if (--clients_ == 0)
562 [VNCBridge performSelectorOnMainThread:@selector(removeStatusBarItem) withObject:nil waitUntilDone:YES];
563 }
564 }
565
566 static rfbNewClientAction VNCClient(rfbClientPtr client) {
567 @synchronized (condition_) {
568 if (screen_->authPasswdData != NULL) {
569 [VNCBridge performSelectorOnMainThread:@selector(registerClient) withObject:nil waitUntilDone:YES];
570 client->clientGoneHook = &VNCDisconnect;
571 return RFB_CLIENT_ACCEPT;
572 }
573 }
574
575 [condition_ lock];
576 client_ = client;
577 [VNCBridge performSelectorOnMainThread:@selector(askForConnection) withObject:nil waitUntilDone:NO];
578 while (action_ == RFB_CLIENT_ON_HOLD)
579 [condition_ wait];
580 rfbNewClientAction action(action_);
581 action_ = RFB_CLIENT_ON_HOLD;
582 [condition_ unlock];
583
584 if (action == RFB_CLIENT_ACCEPT)
585 client->clientGoneHook = &VNCDisconnect;
586 return action;
587 }
588
589 extern "C" bool GSSystemHasCapability(NSString *);
590
591 static CFTypeRef (*$GSSystemCopyCapability)(CFStringRef);
592 static CFTypeRef (*$GSSystemGetCapability)(CFStringRef);
593 static BOOL (*$MGGetBoolAnswer)(CFStringRef);
594
595 static void VNCSetup() {
596 rfbLogEnable(false);
597
598 @synchronized (condition_) {
599 int argc(1);
600 char *arg0(strdup("VNCServer"));
601 char *argv[] = {arg0, NULL};
602 screen_ = rfbGetScreen(&argc, argv, width_, height_, BitsPerSample, 3, BytesPerPixel);
603 free(arg0);
604
605 VNCSettings();
606 }
607
608 screen_->desktopName = strdup([[[NSProcessInfo processInfo] hostName] UTF8String]);
609
610 screen_->alwaysShared = TRUE;
611 screen_->handleEventsEagerly = TRUE;
612 screen_->deferUpdateTime = 1000 / 25;
613
614 screen_->serverFormat.redShift = BitsPerSample * 2;
615 screen_->serverFormat.greenShift = BitsPerSample * 1;
616 screen_->serverFormat.blueShift = BitsPerSample * 0;
617
618 $GSSystemCopyCapability = reinterpret_cast<CFTypeRef (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, "GSSystemCopyCapability"));
619 $GSSystemGetCapability = reinterpret_cast<CFTypeRef (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, "GSSystemGetCapability"));
620 $MGGetBoolAnswer = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, "MGGetBoolAnswer"));
621
622 CFTypeRef opengles2;
623
624 if ($GSSystemCopyCapability != NULL) {
625 opengles2 = (*$GSSystemCopyCapability)(CFSTR("opengles-2"));
626 } else if ($GSSystemGetCapability != NULL) {
627 opengles2 = (*$GSSystemGetCapability)(CFSTR("opengles-2"));
628 if (opengles2 != NULL)
629 CFRetain(opengles2);
630 } else if ($MGGetBoolAnswer != NULL) {
631 opengles2 = $MGGetBoolAnswer(CFSTR("opengles-2")) ? kCFBooleanTrue : kCFBooleanFalse;
632 CFRetain(opengles2);
633 } else
634 opengles2 = NULL;
635
636 bool accelerated(opengles2 != NULL && [(NSNumber *)opengles2 boolValue]);
637
638 if (accelerated)
639 CoreSurfaceAcceleratorCreate(NULL, NULL, &accelerator_);
640
641 if (opengles2 != NULL)
642 CFRelease(opengles2);
643
644 if (accelerator_ != NULL)
645 buffer_ = CoreSurfaceBufferCreate((CFDictionaryRef) [NSDictionary dictionaryWithObjectsAndKeys:
646 @"PurpleEDRAM", kCoreSurfaceBufferMemoryRegion,
647 [NSNumber numberWithBool:YES], kCoreSurfaceBufferGlobal,
648 [NSNumber numberWithInt:(width_ * BytesPerPixel)], kCoreSurfaceBufferPitch,
649 [NSNumber numberWithInt:width_], kCoreSurfaceBufferWidth,
650 [NSNumber numberWithInt:height_], kCoreSurfaceBufferHeight,
651 [NSNumber numberWithInt:'BGRA'], kCoreSurfaceBufferPixelFormat,
652 [NSNumber numberWithInt:(width_ * height_ * BytesPerPixel)], kCoreSurfaceBufferAllocSize,
653 nil]);
654 else
655 VNCBlack();
656
657 //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));
658
659 CoreSurfaceBufferLock(buffer_, 3);
660 screen_->frameBuffer = reinterpret_cast<char *>(CoreSurfaceBufferGetBaseAddress(buffer_));
661 CoreSurfaceBufferUnlock(buffer_);
662
663 screen_->kbdAddEvent = &VNCKeyboard;
664 screen_->ptrAddEvent = &VNCPointer;
665
666 screen_->newClientHook = &VNCClient;
667 screen_->passwordCheck = &VNCCheck;
668
669 screen_->cursor = NULL;
670 }
671
672 static void VNCEnabled() {
673 if (screen_ == NULL)
674 return;
675
676 [lock_ lock];
677
678 bool enabled(true);
679 if (NSDictionary *settings = [NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/Library/Preferences/com.saurik.Veency.plist", NSHomeDirectory()]])
680 if (NSNumber *number = [settings objectForKey:@"Enabled"])
681 enabled = [number boolValue];
682
683 if (enabled != running_)
684 if (enabled) {
685 running_ = true;
686 screen_->socketState = RFB_SOCKET_INIT;
687 rfbInitServer(screen_);
688 rfbRunEventLoop(screen_, -1, true);
689 } else {
690 rfbShutdownServer(screen_, true);
691 running_ = false;
692 }
693
694 [lock_ unlock];
695 }
696
697 static void VNCNotifyEnabled(
698 CFNotificationCenterRef center,
699 void *observer,
700 CFStringRef name,
701 const void *object,
702 CFDictionaryRef info
703 ) {
704 VNCEnabled();
705 }
706
707 void (*$IOMobileFramebufferIsMainDisplay)(IOMobileFramebufferRef, int *);
708
709 static IOMobileFramebufferRef main_;
710 static CoreSurfaceBufferRef layer_;
711
712 static void OnLayer(IOMobileFramebufferRef fb, CoreSurfaceBufferRef layer) {
713 if (_unlikely(width_ == 0 || height_ == 0)) {
714 CGSize size;
715 IOMobileFramebufferGetDisplaySize(fb, &size);
716
717 width_ = size.width;
718 height_ = size.height;
719
720 if (width_ == 0 || height_ == 0)
721 return;
722
723 NSThread *thread([NSThread alloc]);
724
725 [thread
726 initWithTarget:[VNCBridge class]
727 selector:@selector(performSetup:)
728 object:thread
729 ];
730
731 [thread start];
732 } else if (_unlikely(clients_ != 0)) {
733 if (layer == NULL) {
734 if (accelerator_ != NULL)
735 memset(screen_->frameBuffer, 0, sizeof(rfbPixel) * width_ * height_);
736 else
737 VNCBlack();
738 } else {
739 if (accelerator_ != NULL)
740 CoreSurfaceAcceleratorTransferSurface(accelerator_, layer, buffer_, options_);
741 else {
742 CoreSurfaceBufferLock(layer, 2);
743 rfbPixel *data(reinterpret_cast<rfbPixel *>(CoreSurfaceBufferGetBaseAddress(layer)));
744
745 CoreSurfaceBufferFlushProcessorCaches(layer);
746
747 /*rfbPixel corner(data[0]);
748 data[0] = 0;
749 data[0] = corner;*/
750
751 screen_->frameBuffer = const_cast<char *>(reinterpret_cast<volatile char *>(data));
752 CoreSurfaceBufferUnlock(layer);
753 }
754 }
755
756 rfbMarkRectAsModified(screen_, 0, 0, width_, height_);
757 }
758 }
759
760 static bool wait_ = false;
761
762 MSHook(kern_return_t, IOMobileFramebufferSwapSetLayer,
763 IOMobileFramebufferRef fb,
764 int layer,
765 CoreSurfaceBufferRef buffer,
766 CGRect bounds,
767 CGRect frame,
768 int flags
769 ) {
770 int main(false);
771
772 if (_unlikely(buffer == NULL))
773 main = fb == main_;
774 else if (_unlikely(fb == NULL))
775 main = false;
776 else if ($IOMobileFramebufferIsMainDisplay == NULL)
777 main = true;
778 else
779 (*$IOMobileFramebufferIsMainDisplay)(fb, &main);
780
781 if (_likely(main)) {
782 main_ = fb;
783 if (wait_)
784 layer_ = buffer;
785 else
786 OnLayer(fb, buffer);
787 }
788
789 return _IOMobileFramebufferSwapSetLayer(fb, layer, buffer, bounds, frame, flags);
790 }
791
792 // XXX: beg rpetrich for the type of this function
793 extern "C" void *IOMobileFramebufferSwapWait(IOMobileFramebufferRef, void *, unsigned);
794
795 MSHook(void *, IOMobileFramebufferSwapWait, IOMobileFramebufferRef fb, void *arg1, unsigned flags) {
796 void *value(_IOMobileFramebufferSwapWait(fb, arg1, flags));
797 if (fb == main_)
798 OnLayer(fb, layer_);
799 return value;
800 }
801
802 MSHook(void, rfbRegisterSecurityHandler, rfbSecurityHandler *handler) {
803 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
804
805 @synchronized (lock_) {
806 [handlers_ addObject:[NSValue valueWithPointer:handler]];
807 _rfbRegisterSecurityHandler(handler);
808 }
809
810 [pool release];
811 }
812
813 template <typename Type_>
814 static void dlset(Type_ &function, const char *name) {
815 function = reinterpret_cast<Type_>(dlsym(RTLD_DEFAULT, name));
816 }
817
818 MSInitialize {
819 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
820
821 MSHookSymbol(GSTakePurpleSystemEventPort, "_GSGetPurpleSystemEventPort");
822 if (GSTakePurpleSystemEventPort == NULL) {
823 MSHookSymbol(GSTakePurpleSystemEventPort, "_GSCopyPurpleSystemEventPort");
824 PurpleAllocated = true;
825 }
826
827 if (dlsym(RTLD_DEFAULT, "GSLibraryCopyGenerationInfoValueForKey") != NULL)
828 Level_ = 3;
829 else if (dlsym(RTLD_DEFAULT, "GSKeyboardCreate") != NULL)
830 Level_ = 2;
831 else if (dlsym(RTLD_DEFAULT, "GSEventGetWindowContextId") != NULL)
832 Level_ = 1;
833 else
834 Level_ = 0;
835
836 size_t size;
837 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
838 char machine[size];
839 sysctlbyname("hw.machine", machine, &size, NULL, 0);
840 iPad1_ = strcmp(machine, "iPad1,1") == 0;
841
842 dlset($GSMainScreenScaleFactor, "GSMainScreenScaleFactor");
843 dlset($GSEventCreateKeyEvent, "GSEventCreateKeyEvent");
844 dlset($GSCreateSyntheticKeyEvent, "_GSCreateSyntheticKeyEvent");
845 dlset($IOMobileFramebufferIsMainDisplay, "IOMobileFramebufferIsMainDisplay");
846
847 MSHookFunction(&IOMobileFramebufferSwapSetLayer, MSHake(IOMobileFramebufferSwapSetLayer));
848 MSHookFunction(&rfbRegisterSecurityHandler, MSHake(rfbRegisterSecurityHandler));
849
850 if (wait_)
851 MSHookFunction(&IOMobileFramebufferSwapWait, MSHake(IOMobileFramebufferSwapWait));
852
853 if ($SBAlertItem != nil) {
854 $VNCAlertItem = objc_allocateClassPair($SBAlertItem, "VNCAlertItem", 0);
855 MSAddMessage2(VNCAlertItem, "v@:@i", alertSheet,buttonClicked);
856 MSAddMessage2(VNCAlertItem, "v@:cc", configure,requirePasscodeForActions);
857 MSAddMessage0(VNCAlertItem, "v@:", performUnlockAction);
858 objc_registerClassPair($VNCAlertItem);
859 }
860
861 CFNotificationCenterAddObserver(
862 CFNotificationCenterGetDarwinNotifyCenter(),
863 NULL, &VNCNotifyEnabled, CFSTR("com.saurik.Veency-Enabled"), NULL, 0
864 );
865
866 CFNotificationCenterAddObserver(
867 CFNotificationCenterGetDarwinNotifyCenter(),
868 NULL, &VNCNotifySettings, CFSTR("com.saurik.Veency-Settings"), NULL, 0
869 );
870
871 condition_ = [[NSCondition alloc] init];
872 lock_ = [[NSLock alloc] init];
873 handlers_ = [[NSMutableSet alloc] init];
874
875 bool value;
876
877 value = true;
878 cfTrue_ = CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&value), sizeof(value));
879
880 value = false;
881 cfFalse_ = CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&value), sizeof(value));
882
883 cfEvent_ = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&event_), sizeof(event_), kCFAllocatorNull);
884
885 options_ = (CFDictionaryRef) [[NSDictionary dictionaryWithObjectsAndKeys:
886 nil] retain];
887
888 [pool release];
889 }