2 * Copyright (c) 2000-2017 Apple Inc. All rights reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
21 * @APPLE_LICENSE_HEADER_END@
25 * Modification History
27 * June 1, 2001 Allan Nathanson <ajn@apple.com>
28 * - public API conversion
30 * November 9, 2000 Allan Nathanson <ajn@apple.com>
34 //#define DO_NOT_CRASH
35 //#define DO_NOT_INFORM
37 #define SC_LOG_HANDLE _SC_LOG_DEFAULT()
38 #include <SystemConfiguration/SystemConfiguration.h>
39 #include <SystemConfiguration/SCValidation.h>
40 #include <SystemConfiguration/SCPrivate.h>
42 #include <sys/param.h>
43 #include <sys/types.h>
44 #include <sys/socket.h>
45 #include <sys/ioctl.h>
47 #include <net/if_dl.h>
48 #include <netinet/in.h>
49 #include <arpa/inet.h>
51 #include <dispatch/dispatch.h>
53 #include <mach/mach.h>
54 #include <mach/notify.h>
55 #include <mach/mach_error.h>
63 #if TARGET_OS_EMBEDDED && !defined(DO_NOT_INFORM)
64 #include <CoreFoundation/CFUserNotification.h>
65 #endif // TARGET_OS_EMBEDDED && !defined(DO_NOT_INFORM)
71 #pragma mark Miscellaneous
74 __private_extern__
char *
75 _SC_cfstring_to_cstring_ext(CFStringRef cfstr
, char *buf
, CFIndex bufLen
, CFStringEncoding encoding
, UInt8 lossByte
, CFIndex
*usedBufLen
)
84 len
= CFStringGetLength(cfstr
);
86 /* how much buffer space will we really need? */
87 converted
= CFStringGetBytes(cfstr
,
95 if (converted
< len
) {
96 /* if full string could not be converted */
104 if (bufLen
< (last
+ 1)) {
105 /* if the size of the provided buffer is too small */
110 /* allocate a buffer */
112 buf
= CFAllocatorAllocate(NULL
, bufLen
, 0);
118 (void)CFStringGetBytes(cfstr
,
128 if (usedBufLen
!= NULL
) {
137 _SC_cfstring_to_cstring(CFStringRef cfstr
, char *buf
, CFIndex bufLen
, CFStringEncoding encoding
)
139 return _SC_cfstring_to_cstring_ext(cfstr
, buf
, bufLen
, encoding
, 0, NULL
);
145 _SC_sockaddr_to_string(const struct sockaddr
*address
, char *buf
, size_t bufLen
)
148 const struct sockaddr
*sa
;
149 const struct sockaddr_in
*sin
;
150 const struct sockaddr_in6
*sin6
;
151 const struct sockaddr_dl
*sdl
;
157 switch (address
->sa_family
) {
159 (void)inet_ntop(addr
.sin
->sin_family
,
165 (void)inet_ntop(addr
.sin6
->sin6_family
,
166 &addr
.sin6
->sin6_addr
,
169 if (addr
.sin6
->sin6_scope_id
!= 0) {
173 if ((n
+IF_NAMESIZE
+1) <= bufLen
) {
175 if_indextoname(addr
.sin6
->sin6_scope_id
, &buf
[n
]);
181 snprintf(buf
, bufLen
, "unexpected address family %d", address
->sa_family
);
190 _SC_string_to_sockaddr(const char *str
, sa_family_t af
, void *buf
, size_t bufLen
)
195 struct sockaddr_in
*sin
;
196 struct sockaddr_in6
*sin6
;
200 bufLen
= sizeof(struct sockaddr_storage
);
201 addr
.buf
= CFAllocatorAllocate(NULL
, bufLen
, 0);
206 bzero(addr
.buf
, bufLen
);
207 if (((af
== AF_UNSPEC
) || (af
== AF_INET
)) &&
208 (bufLen
>= sizeof(struct sockaddr_in
)) &&
209 inet_aton(str
, &addr
.sin
->sin_addr
) == 1) {
211 addr
.sin
->sin_len
= sizeof(struct sockaddr_in
);
212 addr
.sin
->sin_family
= AF_INET
;
213 } else if (((af
== AF_UNSPEC
) || (af
== AF_INET6
)) &&
214 (bufLen
>= sizeof(struct sockaddr_in6
)) &&
215 inet_pton(AF_INET6
, str
, &addr
.sin6
->sin6_addr
) == 1) {
219 addr
.sin6
->sin6_len
= sizeof(struct sockaddr_in6
);
220 addr
.sin6
->sin6_family
= AF_INET6
;
222 p
= strchr(str
, '%');
224 addr
.sin6
->sin6_scope_id
= if_nametoindex(p
+ 1);
227 if (IN6_IS_ADDR_LINKLOCAL(&addr
.sin6
->sin6_addr
) ||
228 IN6_IS_ADDR_MC_LINKLOCAL(&addr
.sin6
->sin6_addr
)) {
231 if_index
= ntohs(addr
.sin6
->sin6_addr
.__u6_addr
.__u6_addr16
[1]);
232 addr
.sin6
->sin6_addr
.__u6_addr
.__u6_addr16
[1] = 0;
233 if (addr
.sin6
->sin6_scope_id
== 0) {
234 // use the scope id that was embedded in the [link local] IPv6 address
235 addr
.sin6
->sin6_scope_id
= if_index
;
239 if (addr
.buf
!= buf
) {
240 CFAllocatorDeallocate(NULL
, addr
.buf
);
250 _SC_sendMachMessage(mach_port_t port
, mach_msg_id_t msg_id
)
252 mach_msg_empty_send_t msg
;
253 mach_msg_option_t options
;
254 kern_return_t status
;
256 msg
.header
.msgh_bits
= MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND
, 0);
257 msg
.header
.msgh_size
= sizeof(msg
);
258 msg
.header
.msgh_remote_port
= port
;
259 msg
.header
.msgh_local_port
= MACH_PORT_NULL
;
260 msg
.header
.msgh_id
= msg_id
;
261 options
= MACH_SEND_TIMEOUT
;
262 status
= mach_msg(&msg
.header
, /* msg */
263 MACH_SEND_MSG
|options
, /* options */
264 msg
.header
.msgh_size
, /* send_size */
266 MACH_PORT_NULL
, /* rcv_name */
268 MACH_PORT_NULL
); /* notify */
269 if (status
!= MACH_MSG_SUCCESS
) {
270 mach_msg_destroy(&msg
.header
);
278 _SC_trimDomain(CFStringRef domain
)
282 if (!isA_CFString(domain
)) {
286 // remove any leading/trailing dots
287 length
= CFStringGetLength(domain
);
289 (CFStringFindWithOptions(domain
,
294 CFStringFindWithOptions(domain
,
296 CFRangeMake(0, length
),
297 kCFCompareAnchored
|kCFCompareBackwards
,
300 CFMutableStringRef trimmed
;
302 trimmed
= CFStringCreateMutableCopy(NULL
, 0, domain
);
303 CFStringTrim(trimmed
, CFSTR("."));
304 domain
= (CFStringRef
)trimmed
;
305 length
= CFStringGetLength(domain
);
320 _SC_hw_model(Boolean trim
)
322 static CFStringRef model
= NULL
;
323 static CFStringRef model_trimmed
= NULL
;
324 static dispatch_once_t once
;
326 dispatch_once(&once
, ^{
329 int mib
[] = { CTL_HW
, HW_MODEL
};
330 size_t n
= sizeof(hwModel
);
334 bzero(&hwModel
, sizeof(hwModel
));
335 ret
= sysctl(mib
, sizeof(mib
) / sizeof(mib
[0]), &hwModel
, &n
, NULL
, 0);
337 SC_log(LOG_NOTICE
, "sysctl() CTL_HW/HW_MODEL failed: %s", strerror(errno
));
340 hwModel
[sizeof(hwModel
) - 1] = '\0';
341 model
= CFStringCreateWithCString(NULL
, hwModel
, kCFStringEncodingASCII
);
343 // and the "trimmed" name
344 // ... remove everything after (and including) a comma
345 // ... and then any trailing digits
346 cp
= index(hwModel
, ',');
350 n
= strlen(hwModel
) - 1;
352 if (!isdigit(hwModel
[n
])) {
357 model_trimmed
= CFStringCreateWithCString(NULL
, hwModel
, kCFStringEncodingASCII
);
360 return trim
? model_trimmed
: model
;
365 #pragma mark Serialization
369 _SCSerialize(CFPropertyListRef obj
, CFDataRef
*xml
, void **dataRef
, CFIndex
*dataLen
)
373 if ((xml
== NULL
) && ((dataRef
== NULL
) || (dataLen
== NULL
))) {
374 /* if not keeping track of allocated space */
378 myXml
= CFPropertyListCreateData(NULL
,
380 kCFPropertyListBinaryFormat_v1_0
,
384 SC_log(LOG_NOTICE
, "CFPropertyListCreateData() failed");
388 if ((dataRef
!= NULL
) && (dataLen
!= NULL
)) {
397 if ((dataRef
!= NULL
) && (dataLen
!= NULL
)) {
398 *dataRef
= (void *)CFDataGetBytePtr(myXml
);
399 *dataLen
= CFDataGetLength(myXml
);
402 mach_msg_type_number_t len
;
403 kern_return_t status
;
405 status
= vm_read(mach_task_self(),
406 (vm_address_t
)CFDataGetBytePtr(myXml
), // address
407 (vm_size_t
) CFDataGetLength(myXml
), // size
410 if (status
!= KERN_SUCCESS
) {
411 SC_log(LOG_NOTICE
, "vm_read() failed: %s", mach_error_string(status
));
427 _SCUnserialize(CFPropertyListRef
*obj
, CFDataRef xml
, void *dataRef
, CFIndex dataLen
)
429 CFErrorRef error
= NULL
;
432 kern_return_t status
;
434 xml
= CFDataCreateWithBytesNoCopy(NULL
, (void *)dataRef
, dataLen
, kCFAllocatorNull
);
435 *obj
= CFPropertyListCreateWithData(NULL
, xml
, kCFPropertyListImmutable
, NULL
, &error
);
438 status
= vm_deallocate(mach_task_self(), (vm_address_t
)dataRef
, dataLen
);
439 if (status
!= KERN_SUCCESS
) {
440 SC_log(LOG_NOTICE
, "vm_deallocate() failed: %s", mach_error_string(status
));
441 /* non-fatal???, proceed */
444 *obj
= CFPropertyListCreateWithData(NULL
, xml
, kCFPropertyListImmutable
, NULL
, &error
);
449 SC_log(LOG_NOTICE
, "CFPropertyListCreateWithData() faled: %@", error
);
452 _SCErrorSet(kSCStatusFailed
);
461 _SCSerializeString(CFStringRef str
, CFDataRef
*data
, void **dataRef
, CFIndex
*dataLen
)
465 if (!isA_CFString(str
)) {
466 /* if not a CFString */
470 if ((data
== NULL
) && ((dataRef
== NULL
) || (dataLen
== NULL
))) {
471 /* if not keeping track of allocated space */
475 myData
= CFStringCreateExternalRepresentation(NULL
, str
, kCFStringEncodingUTF8
, 0);
476 if (myData
== NULL
) {
477 SC_log(LOG_NOTICE
, "CFStringCreateExternalRepresentation() failed");
481 if ((dataRef
!= NULL
) && (dataLen
!= NULL
)) {
490 if ((dataRef
!= NULL
) && (dataLen
!= NULL
)) {
491 *dataRef
= (void *)CFDataGetBytePtr(myData
);
492 *dataLen
= CFDataGetLength(myData
);
495 mach_msg_type_number_t len
;
496 kern_return_t status
;
498 *dataLen
= CFDataGetLength(myData
);
499 status
= vm_read(mach_task_self(),
500 (vm_address_t
)CFDataGetBytePtr(myData
), // address
504 if (status
!= KERN_SUCCESS
) {
505 SC_log(LOG_NOTICE
, "vm_read() failed: %s", mach_error_string(status
));
521 _SCUnserializeString(CFStringRef
*str
, CFDataRef utf8
, void *dataRef
, CFIndex dataLen
)
524 kern_return_t status
;
526 utf8
= CFDataCreateWithBytesNoCopy(NULL
, dataRef
, dataLen
, kCFAllocatorNull
);
527 *str
= CFStringCreateFromExternalRepresentation(NULL
, utf8
, kCFStringEncodingUTF8
);
530 status
= vm_deallocate(mach_task_self(), (vm_address_t
)dataRef
, dataLen
);
531 if (status
!= KERN_SUCCESS
) {
532 SC_log(LOG_NOTICE
, "vm_deallocate() failed: %s", mach_error_string(status
));
533 /* non-fatal???, proceed */
536 *str
= CFStringCreateFromExternalRepresentation(NULL
, utf8
, kCFStringEncodingUTF8
);
540 SC_log(LOG_NOTICE
, "CFStringCreateFromExternalRepresentation() failed");
549 _SCSerializeData(CFDataRef data
, void **dataRef
, CFIndex
*dataLen
)
551 mach_msg_type_number_t len
;
552 kern_return_t status
;
554 if (!isA_CFData(data
)) {
555 /* if not a CFData */
559 *dataLen
= CFDataGetLength(data
);
560 status
= vm_read(mach_task_self(),
561 (vm_address_t
)CFDataGetBytePtr(data
), // address
565 if (status
!= KERN_SUCCESS
) {
566 SC_log(LOG_NOTICE
, "vm_read() failed: %s", mach_error_string(status
));
579 _SCUnserializeData(CFDataRef
*data
, void *dataRef
, CFIndex dataLen
)
581 kern_return_t status
;
583 *data
= CFDataCreate(NULL
, dataRef
, dataLen
);
584 status
= vm_deallocate(mach_task_self(), (vm_address_t
)dataRef
, dataLen
);
585 if (status
!= KERN_SUCCESS
) {
586 SC_log(LOG_NOTICE
, "vm_deallocate() failed: %s", mach_error_string(status
));
587 _SCErrorSet(kSCStatusFailed
);
595 CF_RETURNS_RETAINED CFDictionaryRef
596 _SCSerializeMultiple(CFDictionaryRef dict
)
599 const void * keys_q
[N_QUICK
];
600 const void ** keys
= keys_q
;
602 CFDictionaryRef newDict
= NULL
;
603 const void * pLists_q
[N_QUICK
];
604 const void ** pLists
= pLists_q
;
605 const void * values_q
[N_QUICK
];
606 const void ** values
= values_q
;
608 nElements
= CFDictionaryGetCount(dict
);
610 if (nElements
> (CFIndex
)(sizeof(keys_q
) / sizeof(CFTypeRef
))) {
611 keys
= CFAllocatorAllocate(NULL
, nElements
* sizeof(CFTypeRef
), 0);
612 values
= CFAllocatorAllocate(NULL
, nElements
* sizeof(CFTypeRef
), 0);
613 pLists
= CFAllocatorAllocate(NULL
, nElements
* sizeof(CFDataRef
), 0);
615 bzero(pLists
, nElements
* sizeof(CFDataRef
));
617 CFDictionaryGetKeysAndValues(dict
, keys
, values
);
618 for (i
= 0; i
< nElements
; i
++) {
620 if (!_SCSerialize((CFPropertyListRef
)values
[i
], (CFDataRef
*)&pLists
[i
], NULL
, NULL
)) {
626 newDict
= CFDictionaryCreate(NULL
,
630 &kCFTypeDictionaryKeyCallBacks
,
631 &kCFTypeDictionaryValueCallBacks
);
636 for (i
= 0; i
< nElements
; i
++) {
637 if (pLists
[i
] != NULL
) CFRelease((CFDataRef
)pLists
[i
]);
640 if (keys
!= keys_q
) {
641 CFAllocatorDeallocate(NULL
, keys
);
642 CFAllocatorDeallocate(NULL
, values
);
643 CFAllocatorDeallocate(NULL
, pLists
);
653 _SCUnserializeMultiple(CFDictionaryRef dict
)
655 const void * keys_q
[N_QUICK
];
656 const void ** keys
= keys_q
;
658 CFDictionaryRef newDict
= NULL
;
659 const void * pLists_q
[N_QUICK
];
660 const void ** pLists
= pLists_q
;
661 const void * values_q
[N_QUICK
];
662 const void ** values
= values_q
;
664 nElements
= CFDictionaryGetCount(dict
);
668 if (nElements
> (CFIndex
)(sizeof(keys_q
) / sizeof(CFTypeRef
))) {
669 keys
= CFAllocatorAllocate(NULL
, nElements
* sizeof(CFTypeRef
), 0);
670 values
= CFAllocatorAllocate(NULL
, nElements
* sizeof(CFTypeRef
), 0);
671 pLists
= CFAllocatorAllocate(NULL
, nElements
* sizeof(CFTypeRef
), 0);
673 bzero(pLists
, nElements
* sizeof(CFTypeRef
));
675 CFDictionaryGetKeysAndValues(dict
, keys
, values
);
676 for (i
= 0; i
< nElements
; i
++) {
677 if (!_SCUnserialize((CFPropertyListRef
*)&pLists
[i
], values
[i
], NULL
, 0)) {
683 newDict
= CFDictionaryCreate(NULL
,
687 &kCFTypeDictionaryKeyCallBacks
,
688 &kCFTypeDictionaryValueCallBacks
);
695 for (i
= 0; i
< nElements
; i
++) {
696 if (pLists
[i
]) CFRelease(pLists
[i
]);
699 if (keys
!= keys_q
) {
700 CFAllocatorDeallocate(NULL
, keys
);
701 CFAllocatorDeallocate(NULL
, values
);
702 CFAllocatorDeallocate(NULL
, pLists
);
714 _SCCreatePropertyListFromResource(CFURLRef url
)
716 CFDictionaryRef dict
= NULL
;
719 CFReadStreamRef readStream
;
720 CFNumberRef val
= NULL
;
722 if (!CFURLCopyResourcePropertyForKey(url
, kCFURLFileSizeKey
, &val
, NULL
) ||
724 // if size not available
725 SC_log(LOG_NOTICE
, "CFURLCopyResourcePropertyForKey() size not available: %@", url
);
729 ok
= CFNumberGetValue(val
, kCFNumberSInt64Type
, &fileLen
);
731 if (!ok
|| (fileLen
== 0)) {
732 // if empty or size too large
733 SC_log(LOG_INFO
, "_SCCreatePropertyListFromResource() improper size: %@", url
);
737 readStream
= CFReadStreamCreateWithFile(NULL
, url
);
738 if (readStream
!= NULL
) {
739 if (CFReadStreamOpen(readStream
)) {
743 buffer
= CFAllocatorAllocate(NULL
, (CFIndex
)fileLen
, 0);
744 dataLen
= CFReadStreamRead(readStream
, buffer
, (CFIndex
)fileLen
);
745 if (dataLen
== (CFIndex
)fileLen
) {
748 data
= CFDataCreateWithBytesNoCopy(NULL
, buffer
, (CFIndex
)fileLen
, kCFAllocatorNull
);
750 dict
= CFPropertyListCreateWithData(NULL
,
752 kCFPropertyListImmutable
,
758 CFAllocatorDeallocate(NULL
, buffer
);
759 CFReadStreamClose(readStream
);
761 CFRelease(readStream
);
769 #pragma mark CFRunLoop scheduling
772 __private_extern__
void
773 _SC_signalRunLoop(CFTypeRef obj
, CFRunLoopSourceRef rls
, CFArrayRef rlList
)
775 CFRunLoopRef rl
= NULL
;
776 CFRunLoopRef rl1
= NULL
;
778 CFIndex n
= CFArrayGetCount(rlList
);
784 /* get first runLoop for this object */
785 for (i
= 0; i
< n
; i
+= 3) {
786 if (!CFEqual(obj
, CFArrayGetValueAtIndex(rlList
, i
))) {
790 rl1
= (CFRunLoopRef
)CFArrayGetValueAtIndex(rlList
, i
+1);
795 /* if not scheduled */
799 /* check if we have another runLoop for this object */
801 for (i
= i
+3; i
< n
; i
+= 3) {
804 if (!CFEqual(obj
, CFArrayGetValueAtIndex(rlList
, i
))) {
808 rl2
= (CFRunLoopRef
)CFArrayGetValueAtIndex(rlList
, i
+1);
809 if (!CFEqual(rl1
, rl2
)) {
810 /* we've got more than one runLoop */
817 /* if we only have one runLoop */
822 /* more than one different runLoop, so we must pick one */
823 for (i
= 0; i
< n
; i
+=3) {
826 if (!CFEqual(obj
, CFArrayGetValueAtIndex(rlList
, i
))) {
830 rl
= (CFRunLoopRef
)CFArrayGetValueAtIndex(rlList
, i
+1);
831 rlMode
= CFRunLoopCopyCurrentMode(rl
);
832 if (rlMode
!= NULL
) {
835 waiting
= (CFRunLoopIsWaiting(rl
) && CFRunLoopContainsSource(rl
, rls
, rlMode
));
838 /* we've found a runLoop that's "ready" */
845 /* didn't choose one above, so choose first */
846 CFRunLoopWakeUp(rl1
);
851 __private_extern__ Boolean
852 _SC_isScheduled(CFTypeRef obj
, CFRunLoopRef runLoop
, CFStringRef runLoopMode
, CFMutableArrayRef rlList
)
855 CFIndex n
= CFArrayGetCount(rlList
);
857 for (i
= 0; i
< n
; i
+= 3) {
858 if ((obj
!= NULL
) && !CFEqual(obj
, CFArrayGetValueAtIndex(rlList
, i
))) {
861 if ((runLoop
!= NULL
) && !CFEqual(runLoop
, CFArrayGetValueAtIndex(rlList
, i
+1))) {
864 if ((runLoopMode
!= NULL
) && !CFEqual(runLoopMode
, CFArrayGetValueAtIndex(rlList
, i
+2))) {
874 __private_extern__
void
875 _SC_schedule(CFTypeRef obj
, CFRunLoopRef runLoop
, CFStringRef runLoopMode
, CFMutableArrayRef rlList
)
877 CFArrayAppendValue(rlList
, obj
);
878 CFArrayAppendValue(rlList
, runLoop
);
879 CFArrayAppendValue(rlList
, runLoopMode
);
885 __private_extern__ Boolean
886 _SC_unschedule(CFTypeRef obj
, CFRunLoopRef runLoop
, CFStringRef runLoopMode
, CFMutableArrayRef rlList
, Boolean all
)
889 Boolean found
= FALSE
;
890 CFIndex n
= CFArrayGetCount(rlList
);
893 if ((obj
!= NULL
) && !CFEqual(obj
, CFArrayGetValueAtIndex(rlList
, i
))) {
897 if ((runLoop
!= NULL
) && !CFEqual(runLoop
, CFArrayGetValueAtIndex(rlList
, i
+1))) {
901 if ((runLoopMode
!= NULL
) && !CFEqual(runLoopMode
, CFArrayGetValueAtIndex(rlList
, i
+2))) {
908 CFArrayRemoveValueAtIndex(rlList
, i
+ 2);
909 CFArrayRemoveValueAtIndex(rlList
, i
+ 1);
910 CFArrayRemoveValueAtIndex(rlList
, i
);
927 #define SYSTEMCONFIGURATION_BUNDLE_ID CFSTR("com.apple.SystemConfiguration")
928 #define SYSTEMCONFIGURATION_FRAMEWORK_PATH_LEN (sizeof(SYSTEMCONFIGURATION_FRAMEWORK_PATH) - 1)
930 #define SUFFIX_SYM "~sym"
931 #define SUFFIX_SYM_LEN (sizeof(SUFFIX_SYM) - 1)
933 #define SUFFIX_DST "~dst"
937 _SC_CFBundleGet(void)
939 static CFBundleRef bundle
= NULL
;
944 if (bundle
!= NULL
) {
948 bundle
= CFBundleGetBundleWithIdentifier(SYSTEMCONFIGURATION_BUNDLE_ID
);
949 if (bundle
!= NULL
) {
950 CFRetain(bundle
); // we want to hold a reference to the bundle
953 SC_log(LOG_NOTICE
, "could not get CFBundle for \"%@\". Trying harder...",
954 SYSTEMCONFIGURATION_BUNDLE_ID
);
957 // if appropriate (e.g. when debugging), try a bit harder
959 env
= getenv("DYLD_FRAMEWORK_PATH");
960 len
= (env
!= NULL
) ? strlen(env
) : 0;
962 if (len
> 0) { /* We are debugging */
964 // trim any trailing slashes
966 if (env
[len
- 1] != '/') {
972 // if DYLD_FRAMEWORK_PATH is ".../xxx~sym" than try ".../xxx~dst"
973 if ((len
> SUFFIX_SYM_LEN
) &&
974 (strncmp(&env
[len
- SUFFIX_SYM_LEN
], SUFFIX_SYM
, SUFFIX_SYM_LEN
) == 0) &&
975 ((len
+ SYSTEMCONFIGURATION_FRAMEWORK_PATH_LEN
) < MAXPATHLEN
)) {
976 char path
[MAXPATHLEN
];
978 strlcpy(path
, env
, sizeof(path
));
979 strlcpy(&path
[len
- SUFFIX_SYM_LEN
], SUFFIX_DST
, sizeof(path
) - (len
- SUFFIX_SYM_LEN
));
980 strlcat(&path
[len
], SYSTEMCONFIGURATION_FRAMEWORK_PATH
, sizeof(path
) - len
);
982 url
= CFURLCreateFromFileSystemRepresentation(NULL
,
984 len
+ SYSTEMCONFIGURATION_FRAMEWORK_PATH_LEN
,
986 bundle
= CFBundleCreate(NULL
, url
);
991 if (bundle
== NULL
) { /* Try a more "direct" route to get the bundle */
993 url
= CFURLCreateWithFileSystemPath(NULL
,
994 CFSTR(SYSTEMCONFIGURATION_FRAMEWORK_PATH
),
995 kCFURLPOSIXPathStyle
,
998 bundle
= CFBundleCreate(NULL
, url
);
1002 if (bundle
== NULL
) {
1003 SC_log(LOG_ERR
, "could not get CFBundle for \"%@\"", SYSTEMCONFIGURATION_BUNDLE_ID
);
1014 * <key>bundleID-tableName</key>
1016 * ... property list from non-localized bundle URL
1020 static CFMutableDictionaryRef cachedInfo
= NULL
;
1023 static dispatch_queue_t
1024 _SC_CFBundleCachedInfoQueue()
1026 static dispatch_once_t once
;
1027 static dispatch_queue_t q
;
1029 dispatch_once(&once
, ^{
1030 q
= dispatch_queue_create("_SC_CFBundleCachedInfo", NULL
);
1038 _SC_CFBundleCachedInfoCopyTableKey(CFBundleRef bundle
, CFStringRef tableName
)
1040 CFStringRef bundleID
;
1041 CFStringRef tableKey
;
1043 bundleID
= CFBundleGetIdentifier(bundle
);
1044 tableKey
= CFStringCreateWithFormat(NULL
, NULL
, CFSTR("%@: %@"), bundleID
, tableName
);
1049 static CFDictionaryRef
1050 _SC_CFBundleCachedInfoCopyTable(CFBundleRef bundle
, CFStringRef tableName
)
1052 __block CFDictionaryRef dict
= NULL
;
1054 dispatch_sync(_SC_CFBundleCachedInfoQueue(), ^{
1055 if (cachedInfo
!= NULL
) {
1056 CFStringRef tableKey
;
1058 tableKey
= _SC_CFBundleCachedInfoCopyTableKey(bundle
, tableName
);
1059 dict
= CFDictionaryGetValue(cachedInfo
, tableKey
);
1063 CFRelease(tableKey
);
1072 _SC_CFBundleCachedInfoSaveTable(CFBundleRef bundle
, CFStringRef tableName
, CFDictionaryRef table
)
1075 dispatch_sync(_SC_CFBundleCachedInfoQueue(), ^{
1076 CFStringRef tableKey
;
1078 tableKey
= _SC_CFBundleCachedInfoCopyTableKey(bundle
, tableName
);
1079 SC_log(LOG_DEBUG
, "Caching %@", tableKey
);
1081 if (cachedInfo
== NULL
) {
1082 cachedInfo
= CFDictionaryCreateMutable(NULL
,
1084 &kCFTypeDictionaryKeyCallBacks
,
1085 &kCFTypeDictionaryValueCallBacks
);
1087 CFDictionarySetValue(cachedInfo
, tableKey
, table
);
1088 CFRelease(tableKey
);
1096 _SC_CFBundleCopyNonLocalizedString(CFBundleRef bundle
, CFStringRef key
, CFStringRef value
, CFStringRef tableName
)
1098 CFStringRef str
= NULL
;
1099 CFDictionaryRef table
= NULL
;
1102 if ((tableName
== NULL
) || CFEqual(tableName
, CFSTR(""))) {
1103 tableName
= CFSTR("Localizable");
1106 table
= _SC_CFBundleCachedInfoCopyTable(bundle
, tableName
);
1107 if (table
== NULL
) {
1108 url
= CFBundleCopyResourceURLForLocalization(bundle
,
1114 table
= _SCCreatePropertyListFromResource(url
);
1116 if (table
!= NULL
) {
1117 _SC_CFBundleCachedInfoSaveTable(bundle
, tableName
, table
);
1120 SC_log(LOG_ERR
, "failed to get resource url: {bundle:%@, table: %@}", bundle
, tableName
);
1124 if (table
!= NULL
) {
1125 if (isA_CFDictionary(table
)) {
1126 str
= CFDictionaryGetValue(table
, key
);
1136 str
= CFRetain(value
);
1144 #pragma mark Mach port / CFMachPort management
1148 _SC_CFMachPortCreateWithPort(const char *portDescription
,
1149 mach_port_t portNum
,
1150 CFMachPortCallBack callout
,
1151 CFMachPortContext
*context
)
1154 Boolean shouldFree
= FALSE
;
1156 port
= CFMachPortCreateWithPort(NULL
, portNum
, callout
, context
, &shouldFree
);
1157 if ((port
== NULL
) || shouldFree
) {
1159 char *crash_info
= NULL
;
1161 SC_log(LOG_NOTICE
, "%s: CFMachPortCreateWithPort() failed , port = %p",
1163 (void *)(uintptr_t)portNum
);
1165 err
= CFStringCreateWithFormat(NULL
, NULL
,
1166 CFSTR("%s: CFMachPortCreateWithPort recycled, [old] port = %@"),
1167 portDescription
, port
);
1169 err
= CFStringCreateWithFormat(NULL
, NULL
,
1170 CFSTR("%s: CFMachPortCreateWithPort returned NULL"),
1173 crash_info
= _SC_cfstring_to_cstring(err
, NULL
, 0, kCFStringEncodingASCII
);
1174 if (err
!= NULL
) CFRelease(err
);
1177 err
= CFStringCreateWithFormat(NULL
,
1179 CFSTR("A recycled mach_port has been detected by \"%s\"."),
1181 _SC_crash(crash_info
, CFSTR("CFMachPort error"), err
);
1182 CFAllocatorDeallocate(NULL
, crash_info
);
1183 if (err
!= NULL
) CFRelease(err
);
1191 #pragma mark DOS encoding/codepage
1194 #if !TARGET_OS_IPHONE
1196 _SC_dos_encoding_and_codepage(CFStringEncoding macEncoding
,
1198 CFStringEncoding
*dosEncoding
,
1199 UInt32
*dosCodepage
)
1201 switch (macEncoding
) {
1202 case kCFStringEncodingMacRoman
:
1203 if (macRegion
!= 0) /* anything non-zero is not US */
1204 *dosEncoding
= kCFStringEncodingDOSLatin1
;
1205 else /* US region */
1206 *dosEncoding
= kCFStringEncodingDOSLatinUS
;
1209 case kCFStringEncodingMacJapanese
:
1210 *dosEncoding
= kCFStringEncodingDOSJapanese
;
1213 case kCFStringEncodingMacChineseTrad
:
1214 *dosEncoding
= kCFStringEncodingDOSChineseTrad
;
1217 case kCFStringEncodingMacKorean
:
1218 *dosEncoding
= kCFStringEncodingDOSKorean
;
1221 case kCFStringEncodingMacArabic
:
1222 *dosEncoding
= kCFStringEncodingDOSArabic
;
1225 case kCFStringEncodingMacHebrew
:
1226 *dosEncoding
= kCFStringEncodingDOSHebrew
;
1229 case kCFStringEncodingMacGreek
:
1230 *dosEncoding
= kCFStringEncodingDOSGreek
;
1233 case kCFStringEncodingMacCyrillic
:
1234 *dosEncoding
= kCFStringEncodingDOSCyrillic
;
1237 case kCFStringEncodingMacThai
:
1238 *dosEncoding
= kCFStringEncodingDOSThai
;
1241 case kCFStringEncodingMacChineseSimp
:
1242 *dosEncoding
= kCFStringEncodingDOSChineseSimplif
;
1245 case kCFStringEncodingMacCentralEurRoman
:
1246 *dosEncoding
= kCFStringEncodingDOSLatin2
;
1249 case kCFStringEncodingMacTurkish
:
1250 *dosEncoding
= kCFStringEncodingDOSTurkish
;
1253 case kCFStringEncodingMacCroatian
:
1254 *dosEncoding
= kCFStringEncodingDOSLatin2
;
1257 case kCFStringEncodingMacIcelandic
:
1258 *dosEncoding
= kCFStringEncodingDOSIcelandic
;
1261 case kCFStringEncodingMacRomanian
:
1262 *dosEncoding
= kCFStringEncodingDOSLatin2
;
1265 case kCFStringEncodingMacFarsi
:
1266 *dosEncoding
= kCFStringEncodingDOSArabic
;
1269 case kCFStringEncodingMacUkrainian
:
1270 *dosEncoding
= kCFStringEncodingDOSCyrillic
;
1274 *dosEncoding
= kCFStringEncodingDOSLatin1
;
1278 *dosCodepage
= CFStringConvertEncodingToWindowsCodepage(*dosEncoding
);
1281 #endif // !TARGET_OS_IPHONE
1285 #pragma mark Debugging
1289 * print status of in-use mach ports
1292 _SC_logMachPortStatus(void)
1294 kern_return_t status
;
1295 mach_port_name_array_t ports
;
1296 mach_port_type_array_t types
;
1297 mach_msg_type_number_t pi
, pn
, tn
;
1298 CFMutableStringRef str
;
1300 SC_log(LOG_DEBUG
, "----------");
1302 /* report on ALL mach ports associated with this task */
1303 status
= mach_port_names(mach_task_self(), &ports
, &pn
, &types
, &tn
);
1304 if (status
== MACH_MSG_SUCCESS
) {
1305 str
= CFStringCreateMutable(NULL
, 0);
1306 for (pi
= 0; pi
< pn
; pi
++) {
1307 char rights
[16], *rp
= &rights
[0];
1309 if (types
[pi
] != MACH_PORT_TYPE_NONE
) {
1312 if (types
[pi
] & MACH_PORT_TYPE_SEND
)
1314 if (types
[pi
] & MACH_PORT_TYPE_RECEIVE
)
1316 if (types
[pi
] & MACH_PORT_TYPE_SEND_ONCE
)
1318 if (types
[pi
] & MACH_PORT_TYPE_PORT_SET
)
1320 if (types
[pi
] & MACH_PORT_TYPE_DEAD_NAME
)
1325 CFStringAppendFormat(str
, NULL
, CFSTR(" %d%s"), ports
[pi
], rights
);
1327 SC_log(LOG_DEBUG
, "Task ports (n=%d):%@", pn
, str
);
1337 _SC_getMachPortReferences(mach_port_t port
,
1338 mach_port_type_t
*pt
,
1339 mach_port_urefs_t
*refs_send
,
1340 mach_port_urefs_t
*refs_recv
,
1341 mach_port_status_t
*recv_status
,
1342 mach_port_urefs_t
*refs_once
,
1343 mach_port_urefs_t
*refs_pset
,
1344 mach_port_urefs_t
*refs_dead
,
1345 const char *err_prefix
)
1347 kern_return_t status
;
1349 status
= mach_port_type(mach_task_self(), port
, pt
);
1350 if (status
!= KERN_SUCCESS
) {
1351 SC_log(LOG_DEBUG
, "%smach_port_type(..., 0x%x): %s",
1354 mach_error_string(status
));
1358 if ((refs_send
!= NULL
) && ((*pt
& MACH_PORT_TYPE_SEND
) != 0)) {
1359 status
= mach_port_get_refs(mach_task_self(), port
, MACH_PORT_RIGHT_SEND
, refs_send
);
1360 if (status
!= KERN_SUCCESS
) {
1361 SC_log(LOG_DEBUG
, "%smach_port_get_refs(..., 0x%x, MACH_PORT_RIGHT_SEND): %s",
1364 mach_error_string(status
));
1369 if ((refs_recv
!= NULL
) && (recv_status
!= NULL
) && ((*pt
& MACH_PORT_TYPE_RECEIVE
) != 0)) {
1370 mach_msg_type_number_t count
;
1372 status
= mach_port_get_refs(mach_task_self(), port
, MACH_PORT_RIGHT_RECEIVE
, refs_recv
);
1373 if (status
!= KERN_SUCCESS
) {
1374 SC_log(LOG_DEBUG
, "%smach_port_get_refs(..., 0x%x, MACH_PORT_RIGHT_RECEIVE): %s",
1377 mach_error_string(status
));
1381 count
= MACH_PORT_RECEIVE_STATUS_COUNT
;
1382 status
= mach_port_get_attributes(mach_task_self(),
1384 MACH_PORT_RECEIVE_STATUS
,
1385 (mach_port_info_t
)recv_status
,
1387 if (status
!= KERN_SUCCESS
) {
1388 SC_log(LOG_DEBUG
, "%smach_port_get_attributes(..., 0x%x, MACH_PORT_RECEIVE_STATUS): %s",
1391 mach_error_string(status
));
1396 if ((refs_once
!= NULL
) && ((*pt
& MACH_PORT_TYPE_SEND_ONCE
) != 0)) {
1397 status
= mach_port_get_refs(mach_task_self(), port
, MACH_PORT_RIGHT_SEND_ONCE
, refs_once
);
1398 if (status
!= KERN_SUCCESS
) {
1399 SC_log(LOG_DEBUG
, "%smach_port_get_refs(..., 0x%x, MACH_PORT_RIGHT_SEND_ONCE): %s",
1402 mach_error_string(status
));
1407 if ((refs_pset
!= NULL
) && ((*pt
& MACH_PORT_TYPE_PORT_SET
) != 0)) {
1408 status
= mach_port_get_refs(mach_task_self(), port
, MACH_PORT_RIGHT_PORT_SET
, refs_pset
);
1409 if (status
!= KERN_SUCCESS
) {
1410 SC_log(LOG_DEBUG
, "%smach_port_get_refs(..., 0x%x, MACH_PORT_RIGHT_PORT_SET): %s",
1413 mach_error_string(status
));
1418 if ((refs_dead
!= NULL
) && ((*pt
& MACH_PORT_TYPE_DEAD_NAME
) != 0)) {
1419 status
= mach_port_get_refs(mach_task_self(), port
, MACH_PORT_RIGHT_DEAD_NAME
, refs_dead
);
1420 if (status
!= KERN_SUCCESS
) {
1421 SC_log(LOG_DEBUG
, "%smach_port_get_refs(..., 0x%x, MACH_PORT_RIGHT_DEAD_NAME): %s",
1424 mach_error_string(status
));
1429 return KERN_SUCCESS
;
1434 _SC_logMachPortReferences(const char *str
, mach_port_t port
)
1436 const char *blanks
= " ";
1438 mach_port_type_t pt
;
1439 mach_port_status_t recv_status
= { .mps_nsrequest
= 0, };
1440 mach_port_urefs_t refs_send
= 0;
1441 mach_port_urefs_t refs_recv
= 0;
1442 mach_port_urefs_t refs_once
= 0;
1443 mach_port_urefs_t refs_pset
= 0;
1444 mach_port_urefs_t refs_dead
= 0;
1445 kern_return_t status
;
1449 static int is_configd
= -1;
1451 if (is_configd
== -1) {
1452 is_configd
= (strcmp(getprogname(), _SC_SERVER_PROG
) == 0);
1454 if (is_configd
== 1) {
1455 // if "configd", add indication if this is the M[ain] or [P]lugin thread
1457 (CFRunLoopGetMain() == CFRunLoopGetCurrent()) ? "M " : "P ",
1461 // add provided string
1462 strlcat(buf
, str
, sizeof(buf
));
1465 strlcat(buf
, blanks
, sizeof(buf
));
1466 if (strcmp(&buf
[sizeof(buf
) - 3], " ") == 0) {
1467 buf
[sizeof(buf
) - 3] = ':';
1471 status
= _SC_getMachPortReferences(port
,
1480 if (status
!= KERN_SUCCESS
) {
1484 SC_log(LOG_DEBUG
, "%smach port 0x%x (%d): send=%d, receive=%d, send once=%d, port set=%d, dead name=%d%s%s",
1493 recv_status
.mps_nsrequest
? ", no more senders" : "",
1494 ((pt
& MACH_PORT_TYPE_DEAD_NAME
) != 0) ? ", dead name request" : "");
1506 CFMutableStringRef trace
;
1508 n
= backtrace(stack
, sizeof(stack
)/sizeof(stack
[0]));
1510 SC_log(LOG_NOTICE
, "backtrace() failed: %s", strerror(errno
));
1514 trace
= CFStringCreateMutable(NULL
, 0);
1516 symbols
= backtrace_symbols(stack
, n
);
1517 if (symbols
!= NULL
) {
1520 for (i
= 0; i
< n
; i
++) {
1521 CFStringAppendFormat(trace
, NULL
, CFSTR("%s\n"), symbols
[i
]);
1531 /* CrashReporter info */
1532 #if !TARGET_OS_IPHONE
1533 #include <CrashReporterClient.h>
1534 #else // !TARGET_OS_IPHONE
1535 const char *__crashreporter_info__
= NULL
;
1536 asm(".desc ___crashreporter_info__, 0x10");
1537 #endif // !TARGET_OS_IPHONE
1541 _SC_SimulateCrash(const char *crash_info
, CFStringRef notifyHeader
, CFStringRef notifyMessage
)
1543 #if !TARGET_OS_EMBEDDED || defined(DO_NOT_INFORM)
1544 #pragma unused(notifyHeader)
1545 #pragma unused(notifyMessage)
1546 #endif // !TARGET_OS_EMBEDDED || defined(DO_NOT_INFORM)
1547 #if TARGET_OS_SIMULATOR
1548 #pragma unused(crash_info)
1549 #endif // TARGET_OS_SIMULATOR
1552 #if !TARGET_OS_SIMULATOR
1553 static bool (*dyfunc_SimulateCrash
)(pid_t
, mach_exception_data_type_t
, CFStringRef
) = NULL
;
1554 static void *image
= NULL
;
1555 static dispatch_once_t once
;
1557 dispatch_once(&once
, ^{
1558 image
= _SC_dlopen("/System/Library/PrivateFrameworks/CrashReporterSupport.framework/CrashReporterSupport");
1559 if (image
!= NULL
) {
1560 dyfunc_SimulateCrash
= dlsym(image
, "SimulateCrash");
1564 if (dyfunc_SimulateCrash
!= NULL
) {
1567 str
= CFStringCreateWithCString(NULL
, crash_info
, kCFStringEncodingUTF8
);
1568 ok
= dyfunc_SimulateCrash(getpid(), 0xbad0005cull
, str
);
1572 #if TARGET_OS_EMBEDDED && !defined(DO_NOT_INFORM)
1573 if (ok
&& (notifyHeader
!= NULL
) && (notifyMessage
!= NULL
)) {
1574 static Boolean warned
= FALSE
;
1577 CFStringRef displayMessage
;
1579 displayMessage
= CFStringCreateWithFormat(NULL
,
1581 CFSTR("%@\n\nPlease collect the crash report and file a Radar."),
1583 CFUserNotificationDisplayNotice(0,
1584 kCFUserNotificationStopAlertLevel
,
1591 CFRelease(displayMessage
);
1595 #endif // TARGET_OS_EMBEDDED && !defined(DO_NOT_INFORM)
1596 #endif // !TARGET_OS_SIMULATOR
1603 _SC_crash(const char *crash_info
, CFStringRef notifyHeader
, CFStringRef notifyMessage
)
1607 if (crash_info
!= NULL
) {
1608 #if !TARGET_OS_IPHONE
1609 CRSetCrashLogMessage(crash_info
);
1610 #else // !TARGET_OS_IPHONE
1611 __crashreporter_info__
= crash_info
;
1612 #endif // !TARGET_OS_IPHONE
1614 SC_log(LOG_NOTICE
, "%s", crash_info
);
1617 if (_SC_isAppleInternal()) {
1618 // simulate a crash report
1619 ok
= _SC_SimulateCrash(crash_info
, notifyHeader
, notifyMessage
);
1620 #ifndef DO_NOT_CRASH
1622 // if we could not simulate a crash report, crash for real
1625 #endif // DO_NOT_CRASH
1628 #if !TARGET_OS_IPHONE
1629 CRSetCrashLogMessage(NULL
);
1630 #else // !TARGET_OS_IPHONE
1631 __crashreporter_info__
= NULL
;
1632 #endif // !TARGET_OS_IPHONE
1638 _SC_getconninfo(int socket
, struct sockaddr_storage
*src_addr
, struct sockaddr_storage
*dest_addr
, int *if_index
, uint32_t *flags
)
1640 struct so_cinforeq request
;
1642 memset(&request
, 0, sizeof(request
));
1644 if (src_addr
!= NULL
) {
1645 memset(src_addr
, 0, sizeof(*src_addr
));
1646 request
.scir_src
= (struct sockaddr
*)src_addr
;
1647 request
.scir_src_len
= sizeof(*src_addr
);
1650 if (dest_addr
!= NULL
) {
1651 memset(dest_addr
, 0, sizeof(*dest_addr
));
1652 request
.scir_dst
= (struct sockaddr
*)dest_addr
;
1653 request
.scir_dst_len
= sizeof(*dest_addr
);
1656 if (ioctl(socket
, SIOCGCONNINFO
, &request
) != 0) {
1657 SC_log(LOG_NOTICE
, "SIOCGCONNINFO failed: %s", strerror(errno
));
1661 if (if_index
!= NULL
) {
1663 *if_index
= request
.scir_ifindex
;
1666 if (flags
!= NULL
) {
1668 *flags
= request
.scir_flags
;