-
Notifications
You must be signed in to change notification settings - Fork 13
/
Utilities.m
1381 lines (1085 loc) · 31.5 KB
/
Utilities.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
//
// Utilities.m
// DHS
//
// Created by Patrick Wardle on 2/7/15.
// Copyright (c) 2015 Objective-See. All rights reserved.
//
@import Sentry;
#import "Consts.h"
#import "Utilities.h"
#import <dlfcn.h>
#import <signal.h>
#import <unistd.h>
#import <syslog.h>
#import <libproc.h>
#import <sys/sysctl.h>
#import <Security/Security.h>
#import <Foundation/Foundation.h>
#import <CommonCrypto/CommonDigest.h>
#import <CoreServices/CoreServices.h>
#import <Collaboration/Collaboration.h>
#import <SystemConfiguration/SystemConfiguration.h>
//disable std err
void disableSTDERR()
{
//file handle
int devNull = -1;
//open /dev/null
devNull = open("/dev/null", O_RDWR);
//dup
dup2(devNull, STDERR_FILENO);
//close
close(devNull);
return;
}
//init crash reporting
void initCrashReporting()
{
//sentry
NSBundle *sentry = nil;
//error
NSError* error = nil;
//class
Class SentryClient = nil;
//load senty
sentry = loadFramework(@"Sentry.framework");
if(nil == sentry)
{
//bail
goto bail;
}
//get client class
SentryClient = NSClassFromString(@"SentryClient");
if(nil == SentryClient)
{
//bail
goto bail;
}
//set shared client
[SentryClient setSharedClient:[[SentryClient alloc] initWithDsn:CRASH_REPORTING_URL didFailWithError:&error]];
if(nil != error)
{
//bail
goto bail;
}
//start crash handler
[[SentryClient sharedClient] startCrashHandlerWithError:&error];
if(nil != error)
{
//bail
goto bail;
}
bail:
return;
}
//loads a framework
// note: assumes it is in 'Framework' dir
NSBundle* loadFramework(NSString* name)
{
//handle
NSBundle* framework = nil;
//framework path
NSString* path = nil;
//init path
path = [NSString stringWithFormat:@"%@/../Frameworks/%@", [NSProcessInfo.processInfo.arguments[0] stringByDeletingLastPathComponent], name];
//standardize path
path = [path stringByStandardizingPath];
//init framework (bundle)
framework = [NSBundle bundleWithPath:path];
if(NULL == framework)
{
//bail
goto bail;
}
//load framework
if(YES != [framework loadAndReturnError:nil])
{
//bail
goto bail;
}
bail:
return framework;
}
//check if OS is supported
// ->Lion and newer
BOOL isSupportedOS()
{
//return
BOOL isSupported = NO;
//major version
SInt32 versionMajor = 0;
//minor version
SInt32 versionMinor = 0;
//get major version
versionMajor = getVersion(gestaltSystemVersionMajor);
//get minor version
versionMinor = getVersion(gestaltSystemVersionMinor);
//sanity check
if( (-1 == versionMajor) ||
(-1 == versionMinor) )
{
//err
goto bail;
}
//check that OS is supported
// ->10.8+ ?
if( (versionMajor == OS_MAJOR_VERSION_X) &&
(versionMinor >= OS_MINOR_VERSION_LION) )
{
//set flag
isSupported = YES;
}
//bail
bail:
return isSupported;
}
//get OS's major or minor version
SInt32 getVersion(OSType selector)
{
//version
// ->major or minor
SInt32 version = -1;
//get version info
if(noErr != Gestalt(selector, &version))
{
//reset version
version = -1;
//err
goto bail;
}
//bail
bail:
return version;
}
/*
//get the signing info of a file
NSDictionary* extractSigningInfo(NSString* path)
{
//info dictionary
NSMutableDictionary* signingStatus = nil;
//code
SecStaticCodeRef staticCode = NULL;
//status
OSStatus status = !STATUS_SUCCESS;
//signing information
CFDictionaryRef signingInformation = NULL;
//cert chain
NSArray* certificateChain = nil;
//index
NSUInteger index = 0;
//cert
SecCertificateRef certificate = NULL;
//common name on chert
CFStringRef commonName = NULL;
//init signing status
signingStatus = [NSMutableDictionary dictionary];
//create static code
status = SecStaticCodeCreateWithPath((__bridge CFURLRef)([NSURL fileURLWithPath:path]), kSecCSDefaultFlags, &staticCode);
//save signature status
signingStatus[KEY_SIGNATURE_STATUS] = [NSNumber numberWithInt:status];
//sanity check
if(STATUS_SUCCESS != status)
{
//err msg
//syslog(LOG_ERR, "OBJECTIVE-SEE ERROR: SecStaticCodeCreateWithPath() failed on %s with %d", [path UTF8String], status);
//bail
goto bail;
}
//check signature
status = SecStaticCodeCheckValidityWithErrors(staticCode, kSecCSDoNotValidateResources, NULL, NULL);
//(re)save signature status
signingStatus[KEY_SIGNATURE_STATUS] = [NSNumber numberWithInt:status];
//if file is signed
// ->grab signing authorities
if(STATUS_SUCCESS == status)
{
//grab signing authorities
status = SecCodeCopySigningInformation(staticCode, kSecCSSigningInformation, &signingInformation);
//sanity check
if(STATUS_SUCCESS != status)
{
//err msg
//syslog(LOG_ERR, "OBJECTIVE-SEE ERROR: SecCodeCopySigningInformation() failed on %s with %d", [path UTF8String], status);
//bail
goto bail;
}
//determine if binary is signed by Apple
signingStatus[KEY_SIGNING_IS_APPLE] = [NSNumber numberWithBool:isApple(path)];
}
//error
// ->not signed, or something else, so no need to check cert's names
else
{
//bail
goto bail;
}
//init array for certificate names
signingStatus[KEY_SIGNING_AUTHORITIES] = [NSMutableArray array];
//get cert chain
certificateChain = [(__bridge NSDictionary*)signingInformation objectForKey:(__bridge NSString*)kSecCodeInfoCertificates];
//handle case there is no cert chain
// ->adhoc? (/Library/Frameworks/OpenVPN.framework/Versions/Current/bin/openvpn-service)
if(0 == certificateChain.count)
{
//set
[signingStatus[KEY_SIGNING_AUTHORITIES] addObject:@"signed, but no signing authorities (adhoc?)"];
}
//got cert chain
// ->add each to list
else
{
//get name of all certs
for(index = 0; index < certificateChain.count; index++)
{
//extract cert
certificate = (__bridge SecCertificateRef)([certificateChain objectAtIndex:index]);
//get common name
status = SecCertificateCopyCommonName(certificate, &commonName);
//skip ones that error out
if( (STATUS_SUCCESS != status) ||
(NULL == commonName))
{
//skip
continue;
}
//save
[signingStatus[KEY_SIGNING_AUTHORITIES] addObject:(__bridge NSString*)commonName];
//release name
CFRelease(commonName);
}
}
//bail
bail:
//free signing info
if(NULL != signingInformation)
{
//free
CFRelease(signingInformation);
}
//free static code
if(NULL != staticCode)
{
//free
CFRelease(staticCode);
}
return signingStatus;
}
//determine if a file is signed by Apple proper
BOOL isApple(NSString* path)
{
//flag
BOOL isApple = NO;
//code
SecStaticCodeRef staticCode = NULL;
//signing reqs
SecRequirementRef requirementRef = NULL;
//status
OSStatus status = -1;
//create static code
status = SecStaticCodeCreateWithPath((__bridge CFURLRef)([NSURL fileURLWithPath:path]), kSecCSDefaultFlags, &staticCode);
if(STATUS_SUCCESS != status)
{
//err msg
syslog(LOG_ERR, "OBJECTIVE-SEE ERROR: SecStaticCodeCreateWithPath() failed on %s with %d", [path UTF8String], status);
//bail
goto bail;
}
//create req string w/ 'anchor apple'
// (3rd party: 'anchor apple generic')
status = SecRequirementCreateWithString(CFSTR("anchor apple"), kSecCSDefaultFlags, &requirementRef);
if( (STATUS_SUCCESS != status) ||
(requirementRef == NULL) )
{
//err msg
syslog(LOG_ERR, "OBJECTIVE-SEE ERROR: SecRequirementCreateWithString() failed on %s with %d", [path UTF8String], status);
//bail
goto bail;
}
//check if file is signed by apple by checking if it conforms to req string
// note: ignore 'errSecCSBadResource' as lots of signed apple files return this issue :/
status = SecStaticCodeCheckValidity(staticCode, kSecCSDefaultFlags, requirementRef);
if( (STATUS_SUCCESS != status) &&
(errSecCSBadResource != status) )
{
//bail
// ->just means app isn't signed by apple
goto bail;
}
//ok, happy (SecStaticCodeCheckValidity() didn't fail)
// ->file is signed by Apple
isApple = YES;
//bail
bail:
//free req reference
if(NULL != requirementRef)
{
//free
CFRelease(requirementRef);
}
//free static code
if(NULL != staticCode)
{
//free
CFRelease(staticCode);
}
return isApple;
}
*/
//given a directory and a filter predicate
// ->return all matches
NSArray* directoryContents(NSString* directory, NSString* predicate)
{
//(unfiltered) directory contents
NSArray* directoryContents = nil;
//matches
NSArray* matches = nil;
//get (unfiltered) directory contents
directoryContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:directory error:nil];
//filter out matches
if(nil != predicate)
{
//filter
matches = [directoryContents filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:predicate]];
}
//no need to filter
else
{
//no filter
matches = directoryContents;
}
return matches;
}
//given a path to binary
// parse it back up to find app's bundle
NSBundle* findAppBundle(NSString* binaryPath)
{
//app's bundle
NSBundle* appBundle = nil;
//app's path
NSString* appPath = nil;
//first just try full path
appPath = binaryPath;
//try to find the app's bundle/info dictionary
do
{
//try to load app's bundle
appBundle = [NSBundle bundleWithPath:appPath];
//check for match
// ->binary path's match
if( (nil != appBundle) &&
(YES == [appBundle.executablePath isEqualToString:binaryPath]))
{
//all done
break;
}
//always unset bundle var since it's being returned
// ->and at this point, its not a match
appBundle = nil;
//remove last part
// ->will try this next
appPath = [appPath stringByDeletingLastPathComponent];
//scan until we get to root
// ->of course, loop will be exited if app info dictionary is found/loaded
} while( (nil != appPath) &&
(YES != [appPath isEqualToString:@"/"]) &&
(YES != [appPath isEqualToString:@""]) );
return appBundle;
}
//hash a file
// ->md5 and sha1
NSDictionary* hashFile(NSString* filePath)
{
//file hashes
NSDictionary* hashes = nil;
//file's contents
NSData* fileContents = nil;
//hash digest (md5)
uint8_t digestMD5[CC_MD5_DIGEST_LENGTH] = {0};
//md5 hash as string
NSMutableString* md5 = nil;
//hash digest (sha1)
uint8_t digestSHA1[CC_SHA1_DIGEST_LENGTH] = {0};
//sha1 hash as string
NSMutableString* sha1 = nil;
//index var
NSUInteger index = 0;
//init md5 hash string
md5 = [NSMutableString string];
//init sha1 hash string
sha1 = [NSMutableString string];
//load file
if(nil == (fileContents = [NSData dataWithContentsOfFile:filePath]))
{
//err msg
//syslog(LOG_ERR, "OBJECTIVE-SEE ERROR: couldn't load %s to hash", [filePath UTF8String]);
//bail
goto bail;
}
//md5 it
CC_MD5(fileContents.bytes, (unsigned int)fileContents.length, digestMD5);
//convert to NSString
// ->iterate over each bytes in computed digest and format
for(index=0; index < CC_MD5_DIGEST_LENGTH; index++)
{
//format/append
[md5 appendFormat:@"%02lX", (unsigned long)digestMD5[index]];
}
//sha1 it
CC_SHA1(fileContents.bytes, (unsigned int)fileContents.length, digestSHA1);
//convert to NSString
// ->iterate over each bytes in computed digest and format
for(index=0; index < CC_SHA1_DIGEST_LENGTH; index++)
{
//format/append
[sha1 appendFormat:@"%02lX", (unsigned long)digestSHA1[index]];
}
//init hash dictionary
hashes = @{KEY_HASH_MD5: md5, KEY_HASH_SHA1: sha1};
//bail
bail:
return hashes;
}
//get app's version
// ->extracted from Info.plist
NSString* getAppVersion()
{
//read and return 'CFBundleVersion' from bundle
return [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
}
//convert a textview to a clickable hyperlink
void makeTextViewHyperlink(NSTextField* textField, NSURL* url)
{
//hyperlink
NSMutableAttributedString *hyperlinkString = nil;
//range
NSRange range = {0};
//init hyper link
hyperlinkString = [[NSMutableAttributedString alloc] initWithString:textField.stringValue];
//init range
range = NSMakeRange(0, [hyperlinkString length]);
//start editing
[hyperlinkString beginEditing];
//add url
[hyperlinkString addAttribute:NSLinkAttributeName value:url range:range];
//make it blue
[hyperlinkString addAttribute:NSForegroundColorAttributeName value:[NSColor blueColor] range:NSMakeRange(0, [hyperlinkString length])];
//underline
[hyperlinkString addAttribute:
NSUnderlineStyleAttributeName value:[NSNumber numberWithInt:NSSingleUnderlineStyle] range:NSMakeRange(0, [hyperlinkString length])];
//done editing
[hyperlinkString endEditing];
//set text
[textField setAttributedStringValue:hyperlinkString];
return;
}
//set the color of an attributed string
NSMutableAttributedString* setStringColor(NSAttributedString* string, NSColor* color)
{
//colored string
NSMutableAttributedString *coloredString = nil;
//alloc/init colored string from existing one
coloredString = [[NSMutableAttributedString alloc] initWithAttributedString:string];
//set color
[coloredString addAttribute:NSForegroundColorAttributeName value:color range:NSMakeRange(0, [coloredString length])];
return coloredString;
}
//exec a process with args
// if 'shouldWait' is set, wait and return stdout/in and termination status
NSMutableDictionary* execTask(NSString* binaryPath, NSArray* arguments, BOOL shouldWait)
{
//task
NSTask* task = nil;
//output pipe for stdout
NSPipe* stdOutPipe = nil;
//output pipe for stderr
NSPipe* stdErrPipe = nil;
//read handle for stdout
NSFileHandle* stdOutReadHandle = nil;
//read handle for stderr
NSFileHandle* stdErrReadHandle = nil;
//results dictionary
NSMutableDictionary* results = nil;
//output for stdout
NSMutableData *stdOutData = nil;
//output for stderr
NSMutableData *stdErrData = nil;
//init dictionary for results
results = [NSMutableDictionary dictionary];
//init task
task = [NSTask new];
//only setup pipes if wait flag is set
if(YES == shouldWait)
{
//init stdout pipe
stdOutPipe = [NSPipe pipe];
//init stderr pipe
stdErrPipe = [NSPipe pipe];
//init stdout read handle
stdOutReadHandle = [stdOutPipe fileHandleForReading];
//init stderr read handle
stdErrReadHandle = [stdErrPipe fileHandleForReading];
//init stdout output buffer
stdOutData = [NSMutableData data];
//init stderr output buffer
stdErrData = [NSMutableData data];
//set task's stdout
task.standardOutput = stdOutPipe;
//set task's stderr
task.standardError = stdErrPipe;
}
//set task's path
task.launchPath = binaryPath;
//set task's args
if(nil != arguments)
{
//set
task.arguments = arguments;
}
//wrap task launch
@try
{
//launch
[task launch];
}
@catch(NSException *exception)
{
//bail
goto bail;
}
//no need to wait
// can just bail w/ no output
if(YES != shouldWait)
{
//bail
goto bail;
}
//read in stdout/stderr
while(YES == [task isRunning])
{
//accumulate stdout
[stdOutData appendData:[stdOutReadHandle readDataToEndOfFile]];
//accumulate stderr
[stdErrData appendData:[stdErrReadHandle readDataToEndOfFile]];
}
//grab any leftover stdout
[stdOutData appendData:[stdOutReadHandle readDataToEndOfFile]];
//grab any leftover stderr
[stdErrData appendData:[stdErrReadHandle readDataToEndOfFile]];
//add stdout
if(0 != stdOutData.length)
{
//add
results[STDOUT] = stdOutData;
}
//add stderr
if(0 != stdErrData.length)
{
//add
results[STDERR] = stdErrData;
}
//add exit code
results[EXIT_CODE] = [NSNumber numberWithInteger:task.terminationStatus];
bail:
return results;
}
//wait until a window is non nil
// ->then make it modal
void makeModal(NSWindowController* windowController)
{
//wait up to 1 second window to be non-nil
// ->then make modal
for(int i=0; i<20; i++)
{
//can make it modal once we have a window
if(nil != windowController.window)
{
//make modal on main thread
dispatch_sync(dispatch_get_main_queue(), ^{
//make app front
[NSApp activateIgnoringOtherApps:YES];
//modal
[[NSApplication sharedApplication] runModalForWindow:windowController.window];
});
//all done
break;
}
//nap
[NSThread sleepForTimeInterval:0.05f];
}//until 1 second
return;
}
//given a pid, get its parent (ppid)
pid_t getParentID(int pid)
{
//parent id
pid_t parentID = -1;
//kinfo_proc struct
struct kinfo_proc processStruct = {0};
//size
size_t procBufferSize = sizeof(processStruct);
//syscall result
int sysctlResult = -1;
//init mib
int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, pid};
//make syscall
sysctlResult = sysctl(mib, sizeof(mib)/sizeof(*mib), &processStruct, &procBufferSize, NULL, 0);
//check if got ppid
if( (STATUS_SUCCESS == sysctlResult) &&
(0 != procBufferSize) )
{
//save ppid
parentID = processStruct.kp_eproc.e_ppid;
}
return parentID;
}
//get path to XPC service
NSString* getPath2XPC()
{
//path to XPC service
NSString* xpcService = nil;
//build path
xpcService = [NSString stringWithFormat:@"%@/Contents/XPCServices/%@", [[NSBundle mainBundle] bundlePath], XPC_SERVICE];
//make sure its there
if(YES != [[NSFileManager defaultManager] fileExistsAtPath:xpcService])
{
//nope
// ->nil out
xpcService = nil;
}
return xpcService;
}
//get path to kernel
NSString* path2Kernel()
{
//kernel path
NSString* kernel;
//check Yosemite's location first
if(YES == [[NSFileManager defaultManager] fileExistsAtPath:KERNEL_YOSEMITE])
{
//set
kernel = KERNEL_YOSEMITE;
}
//go w/ older location
else
{
//set
kernel = KERNEL_PRE_YOSEMITE;
}
return kernel;
}
//determine if process is (still) alive
BOOL isAlive(pid_t targetPID)
{
//flag
BOOL isAlive = YES;
//reset errno
errno = 0;
//'management info base' array
int mib[4] = {0};
//kinfo proc
struct kinfo_proc procInfo = {0};
//try 'kill' with 0
// ->no harm done, but will fail with 'ESRCH' if process is dead
kill(targetPID, 0);
//dead proc -> 'ESRCH'
// ->'No such process'
if(ESRCH == errno)
{
//dead
isAlive = NO;
//bail
goto bail;
}
//size
size_t size = 0;
//init mib
mib[0] = CTL_KERN;
mib[1] = KERN_PROC;
mib[2] = KERN_PROC_PID;
mib[3] = targetPID;
//init size
size = sizeof(procInfo);
//get task's flags
// ->allows to check for zombies
if(0 == sysctl(mib, sizeof(mib)/sizeof(*mib), &procInfo, &size, NULL, 0))
{
//check for zombies
if(((procInfo.kp_proc.p_stat) & SZOMB) == SZOMB)
{
//dead
isAlive = NO;
//bail
goto bail;
}
}
//bail
bail:
return isAlive;
}
//check if computer has network connection
BOOL isNetworkConnected()
{
//flag
BOOL isConnected = NO;
//sock addr stuct
struct sockaddr zeroAddress = {0};
//reachability ref
SCNetworkReachabilityRef reachabilityRef = NULL;
//reachability flags
SCNetworkReachabilityFlags flags = 0;
//reachable flag
BOOL isReachable = NO;
//connection required flag
BOOL connectionRequired = NO;
//ensure its cleared out
bzero(&zeroAddress, sizeof(zeroAddress));
//set size
zeroAddress.sa_len = sizeof(zeroAddress);
//set family
zeroAddress.sa_family = AF_INET;
//create reachability ref
reachabilityRef = SCNetworkReachabilityCreateWithAddress(NULL, (const struct sockaddr*)&zeroAddress);
//sanity check
if(NULL == reachabilityRef)
{
//bail
goto bail;
}
//get flags
if(TRUE != SCNetworkReachabilityGetFlags(reachabilityRef, &flags))
{
//bail
goto bail;
}
//set reachable flag
isReachable = ((flags & kSCNetworkFlagsReachable) != 0);
//set connection required flag
connectionRequired = ((flags & kSCNetworkFlagsConnectionRequired) != 0);
//finally
// ->determine if network is available
isConnected = (isReachable && !connectionRequired) ? YES : NO;
//bail
bail:
//cleanup
if(NULL != reachabilityRef)
{
//release
CFRelease(reachabilityRef);
}
return isConnected;
}
//set or unset button's highlight
void buttonAppearance(NSTableView* table, NSEvent* event, BOOL shouldReset)
{
//mouse point
NSPoint mousePoint = {0};
//row index