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