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