-
Notifications
You must be signed in to change notification settings - Fork 69
/
VNCController.m
1672 lines (1396 loc) · 69.2 KB
/
VNCController.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
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* VNCController.m
* OSXvnc
*
* Created by Jonathan Gillaspie on Fri Aug 02 2002. osxvnc@redstonesoftware.com
* Copyright (c) 2002-2005 Redstone Software Inc. All rights reserved.
*
* All Rights Reserved.
*
* This is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this software; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
* USA.
*/
#import "VNCController.h"
#import "OSXvnc-server/vncauth.h"
#import <signal.h>
#import <unistd.h>
#import <sys/socket.h>
#import <netinet/in.h>
#import <fcntl.h>
#import <sys/types.h>
#import <ifaddrs.h>
#import <netdb.h>
#define PasswordProxy @"********"
#define LocalizedString(X) [[NSBundle mainBundle] localizedStringForKey:(X) value:nil table:nil]
@interface NSString (VNCExtensions)
@property (NS_NONATOMIC_IOSONLY, readonly, copy) NSString *string;
@end
@implementation NSString (VNCExtensions)
- (NSString *) string {
return self;
}
@end
@interface NSTextView (VNCExtensions)
- (void) setStringValue: (NSString *) newString;
@end
@implementation NSTextView (VNCExtensions)
- (void) setStringValue: (NSString *) newString {
self.string = newString;
}
@end
@interface NSFileManager (VNCExtensions)
- (BOOL) directoryExistsAtPath: (NSString *) path;
- (BOOL) createFullDirectoryAtPath:(NSString *)path attributes:(NSDictionary *)attributes;
- (BOOL) canWriteToFile: (NSString *) path;
@end
@implementation NSFileManager (VNCExtensions)
- (BOOL) directoryExistsAtPath: (NSString *) path {
BOOL isDirectory = NO;
return ([self fileExistsAtPath:path isDirectory: &isDirectory] && isDirectory);
}
- (BOOL) createFullDirectoryAtPath:(NSString *)path attributes:(NSDictionary *)attributes {
return [self createDirectoryAtPath:path withIntermediateDirectories:YES attributes:attributes error:NULL];
}
- (BOOL) canWriteToFile: (NSString *) path {
if ([[NSFileManager defaultManager] fileExistsAtPath:path])
return [[NSFileManager defaultManager] isWritableFileAtPath:path];
else {
[[NSFileManager defaultManager] createFullDirectoryAtPath:path.stringByDeletingLastPathComponent attributes:nil];
return [[NSFileManager defaultManager] isWritableFileAtPath:path.stringByDeletingLastPathComponent];
}
}
@end
@implementation VNCController
static int shutdownSignal = 0;
static NSColor *successColor;
static NSColor *failureColor;
static void terminateOnSignal(int signal) {
shutdownSignal = signal;
NSLog(@"Trapped Signal %d -- Terminating", shutdownSignal);
[NSApp terminate:NSApp];
}
static NSMutableString *hostNameString(void) {
char hostName[256];
gethostname(hostName, 256);
NSMutableString *hostNameString = [NSMutableString stringWithUTF8String:hostName];
if ([hostNameString hasSuffix:@".local"])
[hostNameString deleteCharactersInRange:NSMakeRange(hostNameString.length - 6, 6)];
return hostNameString;
}
static NSMutableArray *localIPAddresses(void) {
NSMutableArray *returnArray = [NSMutableArray array];
struct ifaddrs *ifa = NULL, *ifp = NULL;
if (getifaddrs (&ifp) < 0) {
return nil;
}
for (ifa = ifp; ifa; ifa = ifa->ifa_next) {
char ipString[256];
socklen_t salen;
if (ifa->ifa_addr->sa_family == AF_INET)
salen = sizeof (struct sockaddr_in);
else if (ifa->ifa_addr->sa_family == AF_INET6)
salen = sizeof (struct sockaddr_in6);
else
continue;
if (getnameinfo (ifa->ifa_addr, salen, ipString, sizeof (ipString), NULL, 0, NI_NUMERICHOST) == 0) {
[returnArray addObject:@(ipString)];
}
}
freeifaddrs (ifp);
return returnArray;
}
- (instancetype) init {
self = [super init];
// Transform the GUI into a "ForegroundApp" with Dock Icon and Menu
// This is so the server can run without a UI
// 10.3+ only
// ProcessSerialNumber psn = { 0, kCurrentProcess };
// OSStatus returnCode = TransformProcessType(& psn, kProcessTransformToForegroundApplication);
// if (returnCode != 0) {
// NSLog(@"Could not transform process type. Error %d", returnCode);
// }
//
// if (![[NSUserDefaults standardUserDefaults] boolForKey:@"autolaunch"])
// SetFrontProcess(& psn );
hostName = [hostNameString() retain];
successColor = [[NSColor colorWithDeviceRed:0.0 green:0.4 blue:0.0 alpha:1.0] retain];
failureColor = [[NSColor colorWithDeviceRed:0.6 green:0.0 blue:0.0 alpha:1.0] retain];
[[NSUserDefaults standardUserDefaults] registerDefaults: @{
@"PasswordFile": @"",
@"LogFile": @"",
@"desktopName": [NSString stringWithFormat:@"%@ (%@)", hostName, NSUserName()],
@"portNumberSystemServer": @"5900",
@"desktopNameSystemServer": hostName,
@"allowSleep": @"NO",
@"allowDimming": @"YES",
@"allowScreenSaver": @"YES",
@"swapButtons": @"YES",
@"keyboardLayout": @0,
@"keyboardEvents": @3,
@"eventSource": @2,
@"disableRemoteEvents": @"NO",
@"disableRichClipboard": @"NO",
@"allowRendezvous": @"YES",
@"dontDisconnectClients": @"NO",
@"startServerOnLaunch": @"NO",
@"terminateOnFastUserSwitch": @"NO",
@"serverKeepAlive": @"YES",
@"protocolVersion": @"Default",
@"otherArguments": @"",
@"localhostOnly": @"NO",
@"localhostOnlySystemServer": @"NO",
#if defined(WITH_EXTERNAL_IP)
@"externalIPURL": @"http://automation.whatismyip.com/n09230945.asp",
#endif
@"startupItemLocation": @"/Library/StartupItems/OSXvnc",
@"launchdItemLocation": @"/Library/LaunchAgents/com.redstonesoftware.VineServer.plist"
}];
alwaysShared = FALSE;
neverShared = FALSE;
userStopped = FALSE;
automaticReverseHost = [[NSBundle mainBundle].infoDictionary[@"ReverseHost"] copy];
automaticReversePort = [[NSBundle mainBundle].infoDictionary[@"ReversePort"] copy];
signal(SIGHUP, SIG_IGN);
signal(SIGABRT, terminateOnSignal);
signal(SIGINT, terminateOnSignal);
signal(SIGQUIT, terminateOnSignal);
signal(SIGBUS, terminateOnSignal);
signal(SIGSEGV, terminateOnSignal);
signal(SIGTERM, terminateOnSignal);
signal(SIGTSTP, terminateOnSignal);
return self;
}
- (IBAction) terminateRequest: sender {
if (clientList.count && !shutdownSignal)
NSBeginAlertSheet(LocalizedString(@"Quit Vine Server"),
LocalizedString(@"Cancel"),
LocalizedString(@"Quit"),
nil, statusWindow, self, @selector(terminateSheetDidEnd:returnCode:contextInfo:), NULL, NULL,
LocalizedString(@"Disconnect %lu clients and quit Vine Server?"), (unsigned long)clientList.count);
else
[NSApp terminate: self];
}
- (void) terminateSheetDidEnd:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo {
if (returnCode == NSAlertAlternateReturn) {
[sheet orderOut:self];
[NSApp terminate: self];
}
}
- (BOOL) authenticationIsValid {
return (automaticReverseHost.length || [[NSUserDefaults standardUserDefaults] dataForKey:@"vncauth"].length || [[NSUserDefaults standardUserDefaults] integerForKey:@"AuthenticationType"] > 1);
}
- (void) updateHostInfo {
// These commands can sometimes take a little while, so we have a dedicated thread for them
if (!waitingForHostInfo) {
waitingForHostInfo = TRUE;
[NSThread detachNewThreadSelector:@selector(dedicatedUpdateHostInfoThread) toTarget:self withObject:nil];
}
}
// Since this can block for a long time in certain DNS situations we will put this in a separate thread
- (void) dedicatedUpdateHostInfoThread {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NS_DURING {
// flushHostCache is no longer needed since OS X 10.6.
#if 0
[NSHost flushHostCache];
#endif
NSHost *currentHost = [NSHost currentHost];
NSMutableArray *commonHostNames = [currentHost.names mutableCopy];
NSMutableArray *commonIPAddresses = [currentHost.addresses mutableCopy];
NSMutableArray *displayIPAddresses = [NSMutableArray array];
#if defined(WITH_EXTERNAL_IP)
NSURL *externalIP = [NSURL URLWithString:[[NSUserDefaults standardUserDefaults] stringForKey:@"externalIPURL"]];
NSData *externalIPData = [NSData dataWithContentsOfURL:externalIP];
NSString *externalIPString = (externalIPData.length ? [NSString stringWithUTF8String: externalIPData.bytes] : @"" );
#endif
NSEnumerator *ipEnum = nil;
NSString *anIP = nil;
BOOL anyConnections = TRUE; // Sadly it looks like the local IP's bypass the firewall anyhow
#if defined(WITH_EXTERNAL_IP)
if (externalIPString.length && [commonIPAddresses indexOfObject:externalIPString] == NSNotFound)
[commonIPAddresses insertObject:externalIPString atIndex:0];
#endif
ipEnum = [commonIPAddresses objectEnumerator];
while (anIP = [ipEnum nextObject]) {
#if defined(WITH_EXTERNAL_IP)
BOOL isExternal = [externalIPString isEqualToString:anIP];
#else
bool isExternal = false;
#endif
NSMutableAttributedString *ipString = [[[NSMutableAttributedString alloc] initWithString: anIP] autorelease];
if ([anIP hasPrefix:@"127.0.0.1"] || // localhost entries
[anIP rangeOfString:@"::"].location != NSNotFound) {
continue;
}
if (isExternal) {
[ipString replaceCharactersInRange:NSMakeRange(ipString.length,0) withString:@"\tExternal"];
} else {
[ipString replaceCharactersInRange:NSMakeRange(ipString.length,0) withString:@"\tInternal"];
}
if (controller && !limitToLocalConnections.state) { // Colorize and add tooltip
NSURL *testURL = [NSURL URLWithString:[NSString stringWithFormat:@"http://%@:%d",
anIP, self.runningPortNum]];
NSData *testData = [NSData dataWithContentsOfURL:testURL];
NSString *testString = (testData.length
? [NSString stringWithUTF8String: testData.bytes] : @"");
if ([testString hasPrefix:@"RFB"]) {
[ipString replaceCharactersInRange:NSMakeRange(ipString.length,0) withString:@"\tNetwork is configured to allow connections to this IP"];
[ipString addAttribute:NSForegroundColorAttributeName value:successColor range:NSMakeRange(0,ipString.length)];
anyConnections = TRUE;
}
else {
[ipString replaceCharactersInRange:NSMakeRange(ipString.length,0) withString:@"\tNetwork is NOT configured to allow connections to this IP"];
[ipString addAttribute:NSForegroundColorAttributeName value:failureColor range:NSMakeRange(0,ipString.length)];
}
}
else // We don't want to warn about the firewall if we don't actually do the detection
anyConnections = TRUE;
[displayIPAddresses addObject: ipString];
}
if (!anyConnections)
[self performSelectorOnMainThread:@selector(addStatusMessage:) withObject: @"\n(It appears that your firewall is not permitting VNC connections)" waitUntilDone:NO];
[self performSelectorOnMainThread:@selector(updateHostNames:) withObject: commonHostNames waitUntilDone:NO];
[self performSelectorOnMainThread:@selector(updateIPAddresses:) withObject: displayIPAddresses waitUntilDone:NO];
waitingForHostInfo = FALSE;
}
NS_HANDLER
NSLog(@"Exception in updateHostInfo: %@", localException);
NS_ENDHANDLER
[pool release];
}
// Display Host Names
- (void) updateHostNames: (NSArray *) newHostNames {
NSMutableArray *commonHostNames = [[newHostNames mutableCopy] autorelease];
[commonHostNames removeObject:@"localhost"];
if (commonHostNames.count > 1) {
[hostNamesBox setTitle:LocalizedString(@"Host Names")];
hostNamesField.stringValue = [commonHostNames componentsJoinedByString:@"\n"];
}
else if (commonHostNames.count == 1) {
[hostNamesBox setTitle:LocalizedString(@"Host Name")];
hostNamesField.stringValue = [commonHostNames componentsJoinedByString:@"\n"];
}
else {
[hostNamesBox setTitle:LocalizedString(@"Host Name")];
hostNamesField.stringValue = @"";
}
}
// Display IP Info
- (void) updateIPAddresses: (NSArray *) commonIPAddresses {
[ipAddressesView renewRows:0 columns:2];
id ipAddressEnum = [commonIPAddresses objectEnumerator];
id ipAddress = nil;
int i = 0;
while (ipAddress = [ipAddressEnum nextObject]) {
NSString *anIP = [ipAddress string];
if ([anIP hasPrefix:@"127.0.0.1"] || // localhost entries
[anIP rangeOfString:@"::"].location != NSNotFound) {
;//[commonIPAddresses removeObject:anIP];
} else {
NSRange endOfIP = [anIP rangeOfString:@"\t"];
NSAttributedString *ipString = ipAddress;
NSAttributedString *noteString = nil;
NSString *tooltipString = @"";
if (endOfIP.location != NSNotFound && [ipAddress isKindOfClass:[NSAttributedString class]]) {
ipString = [ipAddress attributedSubstringFromRange: NSMakeRange(0,endOfIP.location)];
noteString = [ipAddress attributedSubstringFromRange: NSMakeRange(endOfIP.location+1,[ipAddress length]-(endOfIP.location+1))];
endOfIP = [noteString.string rangeOfString:@"\t"];
if (endOfIP.location != NSNotFound) {
tooltipString = [noteString.string substringFromIndex:endOfIP.location+1];
noteString = [noteString attributedSubstringFromRange: NSMakeRange(0,endOfIP.location)];
}
}
[ipAddressesView addRow];
[ipAddressesView cellAtRow:i column:0].attributedStringValue = ipString;
[ipAddressesView setToolTip:tooltipString forCell:[ipAddressesView cellAtRow:i column:0]];
[ipAddressesView cellAtRow:i column:1].attributedStringValue = noteString;
[ipAddressesView setToolTip:tooltipString forCell:[ipAddressesView cellAtRow:i column:1]];
i++;
}
}
[ipAddressesView sizeToCells];
if (commonIPAddresses.count > 1) {
[ipAddressesBox setTitle:LocalizedString(@"IP Addresses")];
//[ipAddressesField setStringValue:[commonIPAddresses componentsJoinedByString:@"\n"]];
}
else {
[ipAddressesBox setTitle:LocalizedString(@"IP Address")];
//[ipAddressesField setStringValue:@""];
}
}
- (void) addStatusMessage: message {
if ([message isKindOfClass:[NSAttributedString class]])
[statusMessageField.textStorage appendAttributedString:message];
else if ([message isKindOfClass:[NSString class]])
[statusMessageField.textStorage appendAttributedString:[[[NSAttributedString alloc] initWithString:message] autorelease]];
}
- (NSWindow *) window {
return preferenceWindow;
}
- (void) determinePasswordLocation {
NSArray *passwordFiles = @[[[NSUserDefaults standardUserDefaults] stringForKey:@"PasswordFile"],
@"~/.vinevncauth",
[[NSBundle mainBundle].bundlePath stringByAppendingPathComponent:@".vinevncauth"],
@"/tmp/.vinevncauth"];
NSEnumerator *passwordEnumerators = [passwordFiles objectEnumerator];
[passwordFile release];
passwordFile = nil;
// Find first writable location for the password file
while (passwordFile = [passwordEnumerators nextObject]) {
passwordFile = passwordFile.stringByStandardizingPath;
if (passwordFile.length && [[NSFileManager defaultManager] canWriteToFile:passwordFile]) {
[passwordFile retain];
break;
}
}
}
- (void) determineLogLocation {
NSArray *logFiles = @[[[NSUserDefaults standardUserDefaults] stringForKey:@"LogFile"],
@"~/Library/Logs/VineServer.log",
@"/var/log/VineServer.log",
@"/tmp/VineServer.log",
[[NSBundle mainBundle].bundlePath stringByAppendingPathComponent:@"VineServer.log"]];
NSEnumerator *logEnumerators = [logFiles objectEnumerator];
[logFile release];
logFile = nil;
// Find first writable location for the log file
while (logFile = [logEnumerators nextObject]) {
logFile = logFile.stringByStandardizingPath;
if (logFile.length && [[NSFileManager defaultManager] canWriteToFile:logFile]) {
[logFile retain];
break;
}
}
}
- (void) awakeFromNib {
id infoDictionary = [NSBundle mainBundle].infoDictionary;
[self determinePasswordLocation];
[self determineLogLocation];
connectPort.stringValue = @"";
[connectPort.cell performSelector:@selector(setPlaceholderString:) withObject:@"5500"];
// Copy over old preferences found in OSXvnc
NSDictionary *oldPrefs = [[NSUserDefaults standardUserDefaults] persistentDomainForName:@"OSXvnc"];
if (!oldPrefs[@"Converted"]) {
[[NSUserDefaults standardUserDefaults] registerDefaults:oldPrefs];
[self loadUserDefaults: self];
[self saveUserDefaults: self];
oldPrefs = [oldPrefs mutableCopy];
((NSMutableDictionary *)oldPrefs)[@"Converted"] = [NSNumber numberWithBool:TRUE]; // Record that we've converted
[[NSUserDefaults standardUserDefaults] setPersistentDomain:oldPrefs
forName:@"OSXvnc"]; // write it back
}
else
[self loadUserDefaults: self];
statusWindow.title = [NSString stringWithFormat:@"%@: %@",
infoDictionary[@"CFBundleName"],
displayNameField.stringValue];
[optionsTabView selectTabViewItemAtIndex:0];
systemServerIsConfigured = ([[NSFileManager defaultManager] fileExistsAtPath:[[NSUserDefaults standardUserDefaults] stringForKey:@"startupItemLocation"]] ||
[[NSFileManager defaultManager] fileExistsAtPath:[[NSUserDefaults standardUserDefaults] stringForKey:@"launchdItemLocation"]]);
[self loadUIForSystemServer];
stopServerButton.keyEquivalent = @"";
startServerButton.keyEquivalent = @"\r";
preferencesMessageTestField.stringValue = @"";
// First we'll update with the quick-lookup information that doesn't hang
[self updateHostNames:@[hostName]];
[self updateIPAddresses: localIPAddresses()];
[self updateHostInfo];
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
if (startServerOnLaunchCheckbox.state)// && [self authenticationIsValid])
[self startServer: self];
if (!NSApp.hidden)
[statusWindow makeMainWindow];
}
- (void)applicationDidBecomeActive:(NSNotification *)aNotification {
if (!statusWindow.visible)
[statusWindow makeKeyAndOrderFront:self];
[self updateHostInfo];
}
// This is sent when the server's screen params change,
// the server can't handle this right now so we'll restart.
- (void)applicationDidChangeScreenParameters:(NSNotification *)aNotification {
[self addStatusMessage:@"\n"];
[self addStatusMessage:LocalizedString(@"Screen Resolution changed - Server Reinitialized")];
}
- (void) updateUIForConnectionList: (NSArray *) connectionList {
NSMutableString *statusMessage = [NSMutableString string];
[clientList autorelease];
clientList = [connectionList copy];
NSUInteger activeConnectionsCount = clientList.count;
if (!passwordField.stringValue.length)
[statusMessage appendFormat:@"%@(%@)", LocalizedString(@"Server Running"),
LocalizedString(@"No Authentication")];
else
[statusMessage appendString: LocalizedString(@"Server Running")];
[statusMessage appendString:@"\n"];
if (activeConnectionsCount == 0)
[statusMessage appendString: LocalizedString(@"No Clients Connected")];
else if (activeConnectionsCount == 1) {
[statusMessage appendFormat: @"%d ", 1];
[statusMessage appendString: LocalizedString(@"Client Connected: ")];
[statusMessage appendString: [clientList[0] valueForKey:@"clientIP"]];
}
else if (activeConnectionsCount > 1) {
[statusMessage appendFormat: @"%lu ", (unsigned long)activeConnectionsCount];
[statusMessage appendString: LocalizedString(@"Clients Connected: ")];
[statusMessage appendString:
[[clientList valueForKey:@"clientIP"] componentsJoinedByString:@", "]];
}
[statusMessageField setStringValue: statusMessage];
if (activeConnectionsCount == 0) {
[[NSApp performSelector:@selector(dockTile)]
performSelector:@selector(setBadgeLabel:) withObject:@""];
} else {
[[NSApp performSelector:@selector(dockTile)]
performSelector:@selector(setBadgeLabel:) withObject:[NSString stringWithFormat:@"%lu",
(unsigned long)activeConnectionsCount]];
}
}
- (void)activeConnections: (NSNotification *) aNotification {
[self updateUIForConnectionList: aNotification.userInfo[@"clientList"]];
}
- (int) scanForOpenPort: (int) tryPort {
int listen_fd4=0;
int value=1;
struct sockaddr_in sin4;
bzero(&sin4, sizeof(sin4));
sin4.sin_len = sizeof(sin4);
sin4.sin_family = AF_INET;
sin4.sin_addr.s_addr = htonl(INADDR_ANY);
// I'm going to only scan on IPv4 since our OSXvnc is going to register in both spaces
// struct sockaddr_in6 sin6;
// int listen_fd6=0;
// bzero(&sin6, sizeof(sin6));
// sin6.sin6_len = sizeof(sin6);
// sin6.sin6_family = AF_INET6;
// sin6.sin6_addr = in6addr_any;
while (tryPort < 5910) {
sin4.sin_port = htons(tryPort);
//sin6.sin6_port = htons(tryPort);
if ((listen_fd4 = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
//NSLog(@"Socket init failed %d", tryPort);
}
else if (fcntl(listen_fd4, F_SETFL, O_NONBLOCK) < 0) {
//rfbLogPerror("fcntl O_NONBLOCK failed");
}
else if (setsockopt(listen_fd4, SOL_SOCKET, SO_REUSEADDR, &value, sizeof(value)) < 0) {
//NSLog(@"setsockopt SO_REUSEADDR failed %d", tryPort);
}
else if (bind(listen_fd4, (struct sockaddr *) &sin4, sizeof(sin4)) < 0) {
//NSLog(@"Failed to bind socket: port %d may be in use by another VNC", tryPort);
}
else if (listen(listen_fd4, 5) < 0) {
//NSLog(@"Listen failed %d", tryPort);
}
/*
else if ((listen_fd6 = socket(PF_INET6, SOCK_STREAM, 0)) < 0) {
// NSLog(@"Socket init 6 failed %d", tryPort);
}
else if (fcntl(listen_fd6, F_SETFL, O_NONBLOCK) < 0) {
// rfbLogPerror("IPv6: fcntl O_NONBLOCK failed");
}
else if (setsockopt(listen_fd6, SOL_SOCKET, SO_REUSEADDR, &value, sizeof(value)) < 0) {
//NSLog(@"setsockopt 6 SO_REUSEADDR failed %d", tryPort);
}
else if (bind(listen_fd6, (struct sockaddr *) &sin6, sizeof(sin6)) < 0) {
//NSLog(@"Failed to bind socket: port %d may be in use by another VNC", tryPort);
}
else if (listen(listen_fd6, 5) < 0) {
//NSLog(@"Listen failed %d", tryPort);
}
*/
else {
close(listen_fd4);
//close(listen_fd6);
return tryPort;
}
close(listen_fd4);
//close(listen_fd6);
tryPort++;
}
[statusMessageField setStringValue:LocalizedString(@"Unable to find open port 5900-5909")];
return 0;
}
- (int) runningPortNum {
return portNumText.intValue;
}
- (void) loadUIForSystemServer {
if (systemServerIsConfigured) {
startupItemStatusMessageField.textColor = successColor;
[startupItemStatusMessageField setStringValue:LocalizedString(@"Startup Item Configured (Started)")];
}
else {
startupItemStatusMessageField.textColor = failureColor;
[startupItemStatusMessageField setStringValue:LocalizedString(@"Startup Item Disabled (Stopped)")];
}
disableStartupButton.enabled = systemServerIsConfigured;
systemServerMenu.state = (systemServerIsConfigured ? NSOnState : NSOffState);
setStartupButton.title = (systemServerIsConfigured ? LocalizedString(@"Restart System Server") : LocalizedString(@"Start System Server"));
}
- (void) loadAuthenticationUI {
NSUInteger authType = [[NSUserDefaults standardUserDefaults] integerForKey:@"AuthenticationType"];
if ([[NSUserDefaults standardUserDefaults] dataForKey:@"vncauth"].length) {
[passwordField setStringValue:PasswordProxy];
[authenticationType selectCellWithTag:1];
}
else if (authType == 2) {
[authenticationType selectCellWithTag: 2];
}
limitToLocalConnections.state = [[NSUserDefaults standardUserDefaults] boolForKey:@"localhostOnly"];
}
- (void) loadSystemServerAuthenticationUI {
if ([[NSUserDefaults standardUserDefaults] dataForKey:@"vncauthSystemServer"].length) {
[systemServerPasswordField setStringValue:PasswordProxy];
[systemServerAuthenticationType selectCellWithTag:1];
}
else { // if (authType == 2) {
[systemServerAuthenticationType selectCellWithTag: 2];
}
systemServerLimitToLocalConnections.state = [[NSUserDefaults standardUserDefaults] boolForKey:@"localhostOnlySystemServer"];
}
- (void) loadUIForPort: (NSInteger) port {
if (port) {
if (port < 5900 || port > 5909)
[displayNumberField selectItemWithTitle:@"--"];
else
[displayNumberField selectItemWithTitle:[NSString stringWithFormat:@"%d", (int)(port - 5900)]];
portField.stringValue = [NSString stringWithFormat:@"%u", (unsigned)port];
displayNumText.stringValue = displayNumberField.title;
portNumText.stringValue = [NSString stringWithFormat:@"%u", (unsigned)port];
} else {
[displayNumberField selectItemWithTitle:@"Auto"];
port = [self scanForOpenPort:5900];
if (port) {
portField.stringValue = @"";
[portField.cell performSelector:@selector(setPlaceholderString:)
withObject:[NSString stringWithFormat:@"%u", (unsigned)port]];
displayNumText.intValue = (int)(port - 5900);
portNumText.stringValue = [NSString stringWithFormat:@"%u", (unsigned)port];
}
}
}
- (void) loadUIForSystemServerPort: (NSInteger) port {
if (port) {
if (port < 5900 || port > 5909)
[systemServerDisplayNumberField selectItemWithTitle:@"--"];
else
[systemServerDisplayNumberField selectItemWithTitle:[NSString stringWithFormat:@"%d",
(int)(port - 5900)]];
systemServerPortField.stringValue = [NSString stringWithFormat:@"%u", (unsigned)port];
}
else {
[systemServerDisplayNumberField selectItemWithTitle:@"Auto"];
port = [self scanForOpenPort:5900];
if (port) {
systemServerPortField.stringValue = @"";
[systemServerPortField.cell performSelector:@selector(setPlaceholderString:)
withObject:[NSString stringWithFormat:@"%u",
(unsigned)port]];
}
}
}
- (void) loadUserDefaults: sender {
[self loadAuthenticationUI];
[self loadSystemServerAuthenticationUI];
[self loadUIForPort: [[NSUserDefaults standardUserDefaults] integerForKey:@"portNumber"]];
[self loadUIForSystemServerPort: [[NSUserDefaults standardUserDefaults] integerForKey:@"portNumberSystemServer"]];
displayNameField.stringValue = [[NSUserDefaults standardUserDefaults] stringForKey:@"desktopName"];
systemServerDisplayNameField.stringValue = [[NSUserDefaults standardUserDefaults] stringForKey:@"desktopNameSystemServer"];
allowSleepCheckbox.state = [[NSUserDefaults standardUserDefaults] boolForKey:@"allowSleep"];
allowDimmingCheckbox.state = [[NSUserDefaults standardUserDefaults] boolForKey:@"allowDimming"];
allowScreenSaverCheckbox.state = [[NSUserDefaults standardUserDefaults] boolForKey:@"allowScreenSaver"];
swapMouseButtonsCheckbox.state = [[NSUserDefaults standardUserDefaults] boolForKey:@"swapButtons"];
[keyboardLayout selectItemAtIndex:[keyboardLayout indexOfItemWithTag:[[NSUserDefaults standardUserDefaults] integerForKey:@"keyboardLayout"]]];
[keyboardEvents selectItemAtIndex:[keyboardEvents indexOfItemWithTag:[[NSUserDefaults standardUserDefaults] integerForKey:@"keyboardEvents"]]];
[eventSourcePopup selectItemAtIndex:[eventSourcePopup indexOfItemWithTag:[[NSUserDefaults standardUserDefaults] integerForKey:@"eventSource"]]];
disableRemoteEventsCheckbox.state = [[NSUserDefaults standardUserDefaults] boolForKey:@"disableRemoteEvents"];
disableRichClipboardCheckbox.state = [[NSUserDefaults standardUserDefaults] boolForKey:@"disableRichClipboard"];
allowRendezvousCheckbox.state = [[NSUserDefaults standardUserDefaults] boolForKey:@"allowRendezvous"];
[sharingMatrix selectCellWithTag: [[NSUserDefaults standardUserDefaults] integerForKey:@"sharingMode"]];
dontDisconnectCheckbox.state = [[NSUserDefaults standardUserDefaults] boolForKey:@"dontDisconnectClients"];
[self changeSharing:self];
if ([[NSUserDefaults standardUserDefaults] floatForKey:@"protocolVersion"] > 0.0)
[protocolVersion selectItemWithTitle:[[NSUserDefaults standardUserDefaults] stringForKey:@"protocolVersion"]];
otherArguments.stringValue = [[NSUserDefaults standardUserDefaults] stringForKey:@"otherArguments"];
startServerOnLaunchCheckbox.state = [[NSUserDefaults standardUserDefaults] boolForKey:@"startServerOnLaunch"];
terminateOnFastUserSwitch.state = [[NSUserDefaults standardUserDefaults] boolForKey:@"terminateOnFastUserSwitch"];
serverKeepAliveCheckbox.state = [[NSUserDefaults standardUserDefaults] boolForKey:@"serverKeepAlive"];
}
- (void) saveUserDefaults: sender {
if (displayNameField.stringValue.length)
[[NSUserDefaults standardUserDefaults] setObject:displayNameField.stringValue forKey:@"desktopName"];
if (displayNumberField.selectedItem.tag == 0)
[[NSUserDefaults standardUserDefaults] setInteger:0 forKey:@"portNumber"];
else
[[NSUserDefaults standardUserDefaults] setInteger:portField.intValue forKey:@"portNumber"];
[[NSUserDefaults standardUserDefaults] setInteger:(authenticationType.selectedCell).tag forKey:@"AuthenticationType"];
// System Server
{
if (systemServerDisplayNameField.stringValue.length)
[[NSUserDefaults standardUserDefaults] setObject:systemServerDisplayNameField.stringValue forKey:@"desktopNameSystemServer"];
if (systemServerDisplayNumberField.selectedItem.tag == 0)
[[NSUserDefaults standardUserDefaults] setInteger:0 forKey:@"portNumberSystemServer"];
else
[[NSUserDefaults standardUserDefaults] setInteger:systemServerPortField.intValue forKey:@"portNumberSystemServer"];
[[NSUserDefaults standardUserDefaults] setInteger:(systemServerAuthenticationType.selectedCell).tag forKey:@"AuthenticationTypeSystemServer"];
[[NSUserDefaults standardUserDefaults] setBool:systemServerLimitToLocalConnections.state forKey:@"localhostOnlySystemServer"];
}
[[NSUserDefaults standardUserDefaults] setBool:swapMouseButtonsCheckbox.state forKey:@"swapButtons"];
[[NSUserDefaults standardUserDefaults] setInteger:(sharingMatrix.selectedCell).tag forKey:@"sharingMode"];
[[NSUserDefaults standardUserDefaults] setBool:dontDisconnectCheckbox.state forKey:@"dontDisconnectClients"];
[[NSUserDefaults standardUserDefaults] setBool:disableRemoteEventsCheckbox.state forKey:@"disableRemoteEvents"];
[[NSUserDefaults standardUserDefaults] setBool:disableRichClipboardCheckbox.state forKey:@"disableRichClipboard"];
[[NSUserDefaults standardUserDefaults] setBool:limitToLocalConnections.state forKey:@"localhostOnly"];
[[NSUserDefaults standardUserDefaults] setBool:allowRendezvousCheckbox.state forKey:@"allowRendezvous"];
[[NSUserDefaults standardUserDefaults] setBool:startServerOnLaunchCheckbox.state forKey:@"startServerOnLaunch"];
[[NSUserDefaults standardUserDefaults] setBool:terminateOnFastUserSwitch.state forKey:@"terminateOnFastUserSwitch"];
[[NSUserDefaults standardUserDefaults] setBool:serverKeepAliveCheckbox.state forKey:@"serverKeepAlive"];
[[NSUserDefaults standardUserDefaults] setBool:allowSleepCheckbox.state forKey:@"allowSleep"];
[[NSUserDefaults standardUserDefaults] setBool:allowDimmingCheckbox.state forKey:@"allowDimming"];
[[NSUserDefaults standardUserDefaults] setBool:allowScreenSaverCheckbox.state forKey:@"allowScreenSaver"];
[[NSUserDefaults standardUserDefaults] setInteger:keyboardLayout.selectedItem.tag forKey:@"keyboardLayout"];
[[NSUserDefaults standardUserDefaults] setInteger:keyboardEvents.selectedItem.tag forKey:@"keyboardEvents"];
[[NSUserDefaults standardUserDefaults] setInteger:eventSourcePopup.selectedItem.tag forKey:@"eventSource"];
if (protocolVersion.titleOfSelectedItem.floatValue > 0.0)
[[NSUserDefaults standardUserDefaults] setFloat:protocolVersion.titleOfSelectedItem.floatValue forKey:@"protocolVersion"];
else
[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"protocolVersion"];
[[NSUserDefaults standardUserDefaults] setObject:otherArguments.stringValue
forKey:@"otherArguments"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
- (void) startServer: sender {
NSArray *argv;
if (controller) {
// Set to relaunch and then try to shut-down
relaunchServer = TRUE;
[self stopServer: self];
return;
}
if (![preferenceWindow makeFirstResponder:preferenceWindow]) {
[preferenceWindow endEditingFor:nil];
}
if (![statusWindow makeFirstResponder:statusWindow]) {
[statusWindow endEditingFor:nil];
}
if (displayNumberField.selectedItem.tag == 0) {
[self loadUIForPort:0]; // To update the UI on the likely port that we will get
}
if (![self authenticationIsValid]) {
[NSApp beginSheet: initialWindow modalForWindow:statusWindow modalDelegate:nil didEndSelector: NULL contextInfo: NULL];
return;
}
if ([[NSUserDefaults standardUserDefaults] dataForKey:@"vncauth"] && ![[[NSUserDefaults standardUserDefaults] dataForKey:@"vncauth"] writeToFile: passwordFile atomically:NO]) {
[self addStatusMessage:@"Unable to start - problem writing vnc password file"];
return;
}
if ((argv = [self formCommandLineForSystemServer: NO])) {
NSDictionary *infoDictionary = [NSBundle mainBundle].infoDictionary;
NSString *executionPath = [[NSBundle mainBundle].bundlePath
stringByAppendingPathComponent: @"Contents/MacOS/OSXvnc-server"];
NSString *noteStartup = [NSString stringWithFormat:@"%@\tStarting %@ %@(%@)\n",
[NSDate date], [NSProcessInfo processInfo].processName,
[infoDictionary valueForKey:@"CFBundleShortVersion"],
[infoDictionary valueForKey:@"CFBundleVersion"]];
[self determineLogLocation];
if (![[NSFileManager defaultManager] fileExistsAtPath:logFile]) {
[[NSFileManager defaultManager] createFileAtPath:logFile contents:nil attributes:nil];
}
else { // Clear it
serverOutput = [NSFileHandle fileHandleForUpdatingAtPath:logFile];
[serverOutput truncateFileAtOffset:0];
[serverOutput closeFile];
}
serverOutput = [[NSFileHandle fileHandleForUpdatingAtPath:logFile] retain];
[serverOutput writeData:[noteStartup dataUsingEncoding: NSUTF8StringEncoding]];
[serverOutput writeData:[[argv componentsJoinedByString:@" "] dataUsingEncoding: NSUTF8StringEncoding]];
[serverOutput writeData:[@"\n\n" dataUsingEncoding: NSUTF8StringEncoding]];
controller = [[NSTask alloc] init];
controller.launchPath = executionPath;
controller.arguments = argv;
controller.standardOutput = serverOutput;
controller.standardError = serverOutput;
[[NSDistributedNotificationCenter defaultCenter] addObserver:self
selector:@selector(activeConnections:)
name:@"VNCConnections"
object:[NSString stringWithFormat:@"OSXvnc%d", self.runningPortNum]
suspensionBehavior:NSNotificationSuspensionBehaviorDeliverImmediately];
[controller launch];
[lastLaunchTime release];
lastLaunchTime = [[NSDate date] retain];
[[NSNotificationCenter defaultCenter] addObserver: self
selector: NSSelectorFromString(@"serverStopped:")
name: NSTaskDidTerminateNotification
object: controller];
if (!passwordField.stringValue.length)
[statusMessageField setStringValue:[NSString stringWithFormat:@"%@ - %@", LocalizedString(@"Server Running"), LocalizedString(@"No Authentication")]];
else
[statusMessageField setStringValue:LocalizedString(@"Server Running")];
//[startServerButton setEnabled:FALSE];
[startServerButton setTitle:LocalizedString(@"Restart Server")];
[startServerMenuItem setTitle:LocalizedString(@"Restart Server")];
[stopServerButton setEnabled:TRUE];
serverMenuItem.state = NSOnState;
// We really don't want people to accidentally stop the server
//[startServerButton setKeyEquivalent:@""];
//[stopServerButton setKeyEquivalent:@"\r"];
userStopped = FALSE;
/* Only auto-connect the very first time ??; */
if (automaticReverseHost.length) {
[self addStatusMessage:[NSString stringWithFormat:@"\n%@: %@", LocalizedString(@"Initiating Reverse Connection To Host"), automaticReverseHost]];
// [automaticReverseHost release];
// automaticReverseHost = nil;
// [automaticReversePort release];
// automaticReversePort = nil;
}
// Give the server a second to launch
[self performSelector:@selector(updateHostInfo) withObject:nil afterDelay:1.0];
}
}
- (void) stopServer: sender {
[self updateHostInfo];
if (controller != nil) {
userStopped = TRUE;
[controller terminate];
}
else {
[statusMessageField setStringValue:LocalizedString(@"The server is stopped.")];
}
}
- (void) serverStopped: (NSNotification *) aNotification {
// If we don't get the notification soon enough, we may have already restarted
if (controller.running) {
return;
}
[[NSDistributedNotificationCenter defaultCenter] removeObserver:self
name:@"VNCConnections"
object:[NSString stringWithFormat:@"OSXvnc%d", self.runningPortNum]];
[[NSNotificationCenter defaultCenter] removeObserver: self
name: NSTaskDidTerminateNotification
object: controller];
[self updateUIForConnectionList:[NSArray array]];
preferencesMessageTestField.stringValue = @"";
[startServerButton setTitle:LocalizedString(@"Start Server")];
[startServerMenuItem setTitle:LocalizedString(@"Start Server")];
//[startServerButton setEnabled:TRUE];
[stopServerButton setEnabled:FALSE];
serverMenuItem.state = NSOffState;
//[stopServerButton setKeyEquivalent:@""];
//[startServerButton setKeyEquivalent:@"\r"];
if (userStopped)
[statusMessageField setStringValue:LocalizedString(@"The server is stopped.")];
else if (controller.terminationStatus==250) {
NSMutableString *messageString = [NSMutableString stringWithFormat: LocalizedString(@"Vine Server can't listen on the specified port (%d)."), self.runningPortNum];
[messageString appendString:@"\n"];
if (systemServerIsConfigured)
[messageString appendString:LocalizedString(@"Probably because the VNC server is already running as a Startup Item.")];
else
[messageString appendString:LocalizedString(@"Probably because another VNC is already using this port.")];
[statusMessageField setStringValue:messageString];
}
else if (controller.terminationStatus) {
[statusMessageField setStringValue:[NSString stringWithFormat:LocalizedString(@"The server has stopped running. See Log (%d)\n"), controller.terminationStatus]];
}
else
[statusMessageField setStringValue:LocalizedString(@"The server has stopped running")];
if (!userStopped &&
serverKeepAliveCheckbox.state &&
controller.terminationStatus >= 0 &&
controller.terminationStatus <= 64 &&
-lastLaunchTime.timeIntervalSinceNow > 1.0)
relaunchServer = YES;
[controller release];
controller = nil;
[serverOutput closeFile];
[serverOutput release];
serverOutput = nil;
// If it crashes in less than a second it probably can't launch
if (relaunchServer) {
relaunchServer = NO;
[self startServer:self];
}
}
- (NSMutableArray *) formCommandLineForSystemServer: (BOOL) isSystemServer {
NSMutableArray *argv = [NSMutableArray array];
if (isSystemServer) {
[argv addObject:@"-rfbport"];
if (systemServerDisplayNumberField.selectedItem.tag == 0)
[argv addObject:@"0"];