-
-
Notifications
You must be signed in to change notification settings - Fork 134
/
TPLocalHost.m
587 lines (461 loc) · 15.1 KB
/
TPLocalHost.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
//
// TPLocalHost.m
// teleport
//
// Created by JuL on Fri Feb 27 2004.
// Copyright (c) 2003-2005 abyssoft. All rights reserved.
//
#import "TPLocalHost.h"
#import "TPPreferencesManager.h"
#include <IOKit/IOKitLib.h>
#include <IOKit/network/IOEthernetInterface.h>
#include <IOKit/network/IONetworkInterface.h>
#include <IOKit/pwr_mgt/IOPMLib.h>
#include <errno.h>
#include <sys/sysctl.h>
#define FAKE_MULTI_SCREEN 0
NSString * TPLocalHostCapabilitiesChangedNotification = @"TPLocalHostCapabilitiesChangedNotification";
static kern_return_t FindEthernetInterfaces(io_iterator_t *matchingServices)
{
kern_return_t kernResult;
CFMutableDictionaryRef matchingDict;
CFMutableDictionaryRef propertyMatchDict;
matchingDict = IOServiceMatching(kIOEthernetInterfaceClass);
if (NULL == matchingDict) {
printf("IOServiceMatching returned a NULL dictionary.\n");
}
else {
propertyMatchDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
&kCFTypeDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks);
if (NULL == propertyMatchDict) {
printf("CFDictionaryCreateMutable returned a NULL dictionary.\n");
}
else {
CFDictionarySetValue(propertyMatchDict, CFSTR(kIOPrimaryInterface), kCFBooleanTrue);
CFDictionarySetValue(matchingDict, CFSTR(kIOPropertyMatchKey), propertyMatchDict);
CFRelease(propertyMatchDict);
}
}
kernResult = IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, matchingServices);
if (KERN_SUCCESS != kernResult) {
printf("IOServiceGetMatchingServices returned 0x%08x\n", kernResult);
}
return kernResult;
}
static kern_return_t GetMACAddress(io_iterator_t intfIterator, UInt8 *MACAddress, UInt8 bufferSize)
{
io_object_t intfService;
io_object_t controllerService;
kern_return_t kernResult = KERN_FAILURE;
if (bufferSize < kIOEthernetAddressSize) {
return kernResult;
}
bzero(MACAddress, bufferSize);
while ((intfService = IOIteratorNext(intfIterator)) != 0)
{
CFTypeRef MACAddressAsCFData;
kernResult = IORegistryEntryGetParentEntry(intfService,
kIOServicePlane,
&controllerService);
if (KERN_SUCCESS != kernResult) {
printf("IORegistryEntryGetParentEntry returned 0x%08x\n", kernResult);
}
else {
MACAddressAsCFData = IORegistryEntryCreateCFProperty(controllerService,
CFSTR(kIOMACAddress),
kCFAllocatorDefault,
0);
if (MACAddressAsCFData) {
CFDataGetBytes(MACAddressAsCFData, CFRangeMake(0, kIOEthernetAddressSize), MACAddress);
CFRelease(MACAddressAsCFData);
}
(void) IOObjectRelease(controllerService);
}
(void) IOObjectRelease(intfService);
}
return kernResult;
}
static TPLocalHost * _localHost = nil;
@interface TPLocalHost (Internal)
- (void)_generateBackgroundImages;
- (NSString*)_desktopPicturePathForScreen:(NSScreen*)screen;
- (NSImage*)_desktopPictureForScreen:(NSScreen*)screen;
@end
@implementation TPLocalHost
+ (TPLocalHost*)localHost
{
if(_localHost == nil)
_localHost = [[TPLocalHost alloc] init];
return _localHost;
}
- (instancetype) init
{
self = [super init];
[[NSDistributedNotificationCenter defaultCenter] addObserver:self selector:@selector(_generateBackgroundImages) name:@"com.apple.desktop" object:@"BackgroundChanged"];
[[NSDistributedNotificationCenter defaultCenter] addObserver:self selector:@selector(_accessibilityAPIChanged:) name:@"com.apple.accessibility.api" object:nil];
return self;
}
- (NSString*)identifier
{
return [[NSWorkspace sharedWorkspace] computerIdentifier];
}
- (SInt32)osVersion
{
SInt32 MacVersion = 0;
size_t size = 256;
char str[size];
int ret = sysctlbyname("kern.osrelease", str, &size, NULL, 0);
if (ret == noErr) {
MacVersion = atoi(str);
}
return MacVersion;
}
- (NSString*)address
{
return @"127.0.0.1";
}
- (NSString*)computerName
{
if(_computerName == nil)
_computerName = (NSString *)CFBridgingRelease(CSCopyMachineName());
return [super computerName];
}
- (IOEthernetAddress)MACAddress
{
if(![self hasValidMACAddress]) {
kern_return_t kernResult = KERN_SUCCESS;
io_iterator_t intfIterator;
kernResult = FindEthernetInterfaces(&intfIterator);
if(KERN_SUCCESS != kernResult) {
printf("FindEthernetInterfaces returned 0x%08x\n", kernResult);
}
else {
kernResult = GetMACAddress(intfIterator, _macAddress.bytes, kIOEthernetAddressSize);
if(KERN_SUCCESS != kernResult) {
printf("GetMACAddress returned 0x%08x\n", kernResult);
}
}
(void)IOObjectRelease(intfIterator); // Release the iterator.
}
return [super MACAddress];
}
- (NSArray*)screens
{
#if FAKE_MULTI_SCREEN
NSMutableArray * screens = [[NSScreen screens] mutableCopy];
TPScreen * otherScreen = [[TPScreen alloc] init];
NSRect frame = [[screens objectAtIndex:0] frame];
frame.origin.x += NSWidth(frame);
frame.size.width *= 1.5;
frame.size.height *= 1.5;
otherScreen.frame = frame;
[screens addObject:otherScreen];
[otherScreen release];
return [screens autorelease];
#else
return [NSScreen screens];
#endif
}
#pragma mark -
#pragma mark Background image
- (void)_generateBackgroundImages
{
NSArray * screens = [[TPLocalHost localHost] screens];
_backgroundImages = [[NSMutableArray alloc] initWithCapacity:[screens count]];
NSEnumerator * screenEnum = [screens objectEnumerator];
NSScreen * screen;
while((screen = [screenEnum nextObject]) != nil) {
NSImage * backgroundImage = nil;
NSImage * desktopPicture = [self _desktopPictureForScreen:screen];
if(desktopPicture != nil) {
backgroundImage = [TPHost backgroundImageFromDesktopPicture:desktopPicture];
}
else {
backgroundImage = [self defaultBackgroundImage];
}
if(backgroundImage != nil)
[_backgroundImages addObject:backgroundImage];
}
[self notifyChange];
}
- (NSImage*)backgroundImageForScreen:(NSScreen*)screen
{
if(_backgroundImages == nil)
[self _generateBackgroundImages];
int index = [[[TPLocalHost localHost] screens] indexOfObject:screen];
if(index >= 0 && index < [_backgroundImages count])
return _backgroundImages[index];
else
return nil;
}
- (NSImage*)backgroundImage
{
return [self backgroundImageForScreen:[self mainScreen]];
}
- (BOOL)hasCustomBackgroundImage
{
return ([self _desktopPicturePathForScreen:[self mainScreen]] != nil);
}
- (NSString*)_desktopPicturePathForScreen:(NSScreen*)screen
{
if([[NSWorkspace sharedWorkspace] respondsToSelector:@selector(desktopImageURLForScreen:)]) {
NSURL * desktopPictureURL = [[NSWorkspace sharedWorkspace] desktopImageURLForScreen:screen];
// Addresses issue https://github.com/abyssoft/teleport/issues/15
if(![[NSFileManager defaultManager] fileExistsAtPath:[desktopPictureURL absoluteString]]){
return nil;
} else
return [desktopPictureURL path];
}
else {
NSUserDefaults * userDefaults = [[NSUserDefaults alloc] init];
[userDefaults addSuiteNamed:@"com.apple.desktop"];
[userDefaults synchronize];
NSDictionary * prefDict = [userDefaults dictionaryRepresentation];
NSNumber * screenNum = [screen deviceDescription][@"NSScreenNumber"];
NSDictionary * backgroundDict = prefDict[@"Background"];
NSDictionary * screenDict = backgroundDict[[screenNum stringValue]];
if(screenDict == nil)
screenDict = backgroundDict[@"default"];
NSString * imagePath = nil;
NSString * change = screenDict[@"Change"];
if(change != nil && ![change isEqualToString:@"Never"]) {
imagePath = screenDict[@"ChangePath"];
imagePath = [imagePath stringByAppendingPathComponent:screenDict[@"LastName"]];
}
if(imagePath == nil)
imagePath = screenDict[@"ImageFilePath"];
if(imagePath == nil)
return nil;
if(![[NSFileManager defaultManager] fileExistsAtPath:imagePath])
return nil;
return imagePath;
}
}
- (NSImage*)_desktopPictureForScreen:(NSScreen*)screen
{
NSString * path = [self _desktopPicturePathForScreen:screen];
if(path == nil)
return nil;
NSImage * desktopPicture = [[NSImage alloc] initByReferencingFile:path];
return desktopPicture;
}
#pragma mark -
#pragma mark Capabilities
- (TPHostCapability)capabilities
{
TPHostCapability capabilities = TPHostNoCapability;
int c;
for(c=0; c<=MAX_CAPABILITIES; c++) {
TPHostCapability capability = (1 << c);
if([self hasCapability:capability])
capabilities |= capability;
}
return capabilities;
}
- (BOOL)isAccessibilityAPIEnabled
{
return AXAPIEnabled();
}
- (BOOL)checkAccessibility
{
return AXIsProcessTrustedWithOptions((__bridge CFDictionaryRef)@{(__bridge NSString*)kAXTrustedCheckOptionPrompt: @YES});
}
- (BOOL)hasCapability:(TPHostCapability)capability
{
switch(capability) {
case TPHostEncryptionCapability:
return [self hasIdentity] && [[TPPreferencesManager sharedPreferencesManager] boolForPref:ENABLED_ENCRYPTION];
case TPHostEventTapsCapability:
return ([self osVersion] >= TPHostOSVersion(4)) && [self isAccessibilityAPIEnabled];
case TPHostDirectEventTapsCapability:
return ([self osVersion] >= TPHostOSVersion(5)) && [self isAccessibilityAPIEnabled] && ![[TPPreferencesManager sharedPreferencesManager] boolForPref:TIGER_BEHAVIOR];
default:
return NO;
}
return NO;
}
- (void)checkCapabilities
{
[self willChangeValueForKey:@"supportDragNDrop"];
[self didChangeValueForKey:@"supportDragNDrop"];
}
- (void)_accessibilityAPIChanged:(NSNotification*)notification
{
[self notifyChange];
}
#pragma mark -
#pragma mark Identity
- (SecKeychainRef)_keychainRef
{
static SecKeychainRef keychainRef = NULL;
if(keychainRef == NULL) {
OSErr err;
NSString * keychainName = nil;
if(keychainName != nil) {
NSString * keychainsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Keychains"];
NSString * fullPath = [keychainsDirectory stringByAppendingPathComponent:keychainName];
if((err = SecKeychainOpen([fullPath UTF8String], &keychainRef)) != noErr) {
NSLog(@"Unable to open keychain: %d", err);
}
}
else if((err = SecKeychainCopyDefault(&keychainRef)) != noErr) {
NSLog(@"Unable to copy default keychain: %d", err);
}
}
return keychainRef;
}
- (id)_identifierForIdentity:(SecIdentityRef)identity
{
UInt32 tags[] = { kSecPublicKeyHashItemAttr };
UInt32 formats[] = { CSSM_DB_ATTRIBUTE_FORMAT_BLOB };
SecKeychainAttributeInfo info = { 1, tags, formats };
SecKeychainAttributeList * attrList = NULL;
OSStatus err;
SecCertificateRef certRef;
if((err = SecIdentityCopyCertificate(identity, &certRef)) != noErr) {
NSLog(@"Unable to copy certificate: %d", err);
return nil;
}
if((err = SecKeychainItemCopyAttributesAndData((SecKeychainItemRef)certRef, &info, NULL, &attrList, NULL, NULL)) != noErr) {
NSLog(@"Unable to copy identifier: %d", err);
CFRelease(certRef);
return nil;
}
CFRelease(certRef);
if(attrList->count != 1) {
NSLog(@"unexpected number of serial number: %d", attrList->count);
SecKeychainItemFreeAttributesAndData(attrList, NULL);
return nil;
}
SecKeychainAttribute identifierAttribute = attrList->attr[0];
NSData * identifierData = [[NSData alloc] initWithBytes:identifierAttribute.data length:identifierAttribute.length];
SecKeychainItemFreeAttributesAndData(attrList, NULL);
return identifierData;
}
- (NSArray*)potentialIdentities
{
if(_potentialIdentities == nil) {
OSErr err;
SecKeychainRef keychainRef = [self _keychainRef];
SecIdentitySearchRef searchRef = NULL;
if((err = SecIdentitySearchCreate(keychainRef, CSSM_KEYUSE_ENCRYPT|CSSM_KEYUSE_DECRYPT|CSSM_KEYUSE_SIGN|CSSM_KEYUSE_VERIFY, &searchRef)) != noErr) {
NSLog(@"Unable to create keychain search: %d", err);
CFRelease(keychainRef);
return nil;
}
id identifier = [[TPPreferencesManager sharedPreferencesManager] valueForPref:CERTIFICATE_IDENTIFIER];
NSMutableArray * potentialIdentities = [[NSMutableArray alloc] init];
SecIdentityRef identityRef;
while((err = SecIdentitySearchCopyNext(searchRef, &identityRef)) == noErr) {
id identityIdentifier = [self _identifierForIdentity:identityRef];
if((identifier != nil) && [identifier isEqual:identityIdentifier]) {
[potentialIdentities insertObject:(id)CFBridgingRelease(identityRef) atIndex:0]; // put current identity first in the potential identities
}
else {
[potentialIdentities addObject:(id)CFBridgingRelease(identityRef)];
}
}
CFRelease(searchRef);
if(err != errSecItemNotFound) {
DebugLog(@"Unable to get next search result: %d", err);
}
else {
_potentialIdentities = potentialIdentities;
}
}
return _potentialIdentities;
}
- (SecIdentityRef)identity
{
NSArray * potentialIdentities = [self potentialIdentities];
if(potentialIdentities == nil || ([potentialIdentities count] == 0)) {
return NULL;
}
else {
return (__bridge SecIdentityRef)potentialIdentities[0];
}
}
- (void)setIdentity:(SecIdentityRef)identity
{
if(identity != NULL) {
id identifier = [self _identifierForIdentity:identity];
[[TPPreferencesManager sharedPreferencesManager] setValue:identifier forKey:CERTIFICATE_IDENTIFIER];
}
[self reloadIdentity];
}
- (BOOL)hasIdentity
{
return ([self identity] != NULL);
}
- (void)resetIdentity
{
[self setIdentity:NULL];
}
- (void)reloadIdentity
{
_potentialIdentities = nil;
}
- (NSString*)bonjourName
{
return [NSString stringWithFormat:@"%@@%@", NSUserName(), [self computerName]];
}
#pragma mark -
#pragma mark Screen
- (NSScreen*)mainScreen
{
return [self screenAtIndex:0];
}
- (NSScreen*)sharedScreen
{
NSScreen * sharedScreen = [self screenAtIndex:[self sharedScreenIndex]];
if(sharedScreen == nil) {
sharedScreen = [self mainScreen];
}
return sharedScreen;
}
- (void)setSharedScreenIndex:(unsigned)screenIndex
{
[[TPPreferencesManager sharedPreferencesManager] setValue:@(screenIndex) forKey:SHARED_SCREEN_INDEX];
[self notifyChange];
}
- (unsigned)sharedScreenIndex
{
return [[[TPPreferencesManager sharedPreferencesManager] valueForKey:SHARED_SCREEN_INDEX] unsignedIntValue];
}
- (void)wakeUpScreen
{
IOPMAssertionID assertionID;
IOReturn success = IOPMAssertionCreate(kIOPMAssertionTypeNoDisplaySleep, kIOPMAssertionLevelOn, &assertionID);
if(success == kIOReturnSuccess) {
IOPMAssertionRelease(assertionID);
}
io_registry_entry_t entry = IORegistryEntryFromPath(kIOMasterPortDefault,
"IOService:/IOResources/IODisplayWrangler");
if (entry != MACH_PORT_NULL) {
IORegistryEntrySetCFProperty(entry, CFSTR("IORequestIdle"), kCFBooleanFalse);
IOObjectRelease(entry);
}
/* The previous code doesn't appear to work on Big Sur with an M1 mac, but explicitly declaring user activity does. This should be cleaned up. */
success = IOPMAssertionDeclareUserActivity(CFSTR("teleport waking screen"), kIOPMUserActiveLocal, &assertionID);
if(success == kIOReturnSuccess) {
IOPMAssertionRelease(assertionID);
}
}
- (void)sleepScreen {
/* This doesn't work on Big Sur with an M1 mac */
io_registry_entry_t entry = IORegistryEntryFromPath(kIOMasterPortDefault,
"IOService:/IOResources/IODisplayWrangler");
if (entry != MACH_PORT_NULL) {
IORegistryEntrySetCFProperty(entry, CFSTR("IORequestIdle"), kCFBooleanTrue);
IOObjectRelease(entry);
}
}
- (id)valueForUndefinedKey:(NSString*)key
{
if([key isEqualToString:@"supportDragNDrop"])
return @([self hasCapability:TPHostDragNDropCapability]);
else
return [super valueForUndefinedKey:key];
}
@end