2 * Copyright (c) 2007-2018 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 * October 24, 2007 Allan Nathanson <ajn@apple.com>
34 #include <CoreFoundation/CoreFoundation.h>
36 #define SC_LOG_HANDLE __log_SCMonitor()
37 #define SC_LOG_HANDLE_TYPE static
38 #include <SystemConfiguration/SystemConfiguration.h>
39 #include <SystemConfiguration/SCPrivate.h>
41 #include <IOKit/IOKitLib.h>
42 #include <IOKit/IOKitKeysPrivate.h>
43 #include <IOKit/IOMessage.h>
44 #include <ApplicationServices/ApplicationServices.h>
45 #include "UserEventAgentInterface.h"
47 #define MY_BUNDLE_ID "com.apple.SystemConfiguration.SCMonitor"
48 #define MY_ICON_PATH "/System/Library/PreferencePanes/Network.prefPane/Contents/Resources/Network.icns"
50 #define NETWORK_PREF_APP "/System/Library/PreferencePanes/Network.prefPane"
51 #define NETWORK_PREF_CMD "New Interface"
54 * The following keys/values control the actions taken when a new interface
55 * has been detected and whether we interact with the user.
57 * The keys/values can be provided globally (in SCMonitor.plugin's Info.plist
58 * file) or per-inteface in the IORegistry.
60 * For the "New Interface Detected Action" key we define the following [CFString]
63 * "None" No action, ignore this interface.
64 * "Prompt" Post a "new interface detected" notification to the user.
65 * "Configure" Automatically configure this interface without any
68 * Note: automatic configuration may not be possible if the logged in user
69 * is NOT "root" (eUID==0) or if the authorization right that governs
70 * SCHelper write operations (kSCPreferencesAuthorizationRight_write)
71 * is not currently available.
73 * An [older] "User Intervention" key is also supported. That CFBoolean
74 * key, if present and TRUE, implies "Configure" configuration of the
75 * interface without intervention.
79 UserEventAgentInterfaceStruct
*_UserEventAgentInterface
;
85 CFStringRef configuration_action
;
87 CFRunLoopSourceRef monitorRls
;
89 IONotificationPortRef notifyPort
;
90 io_iterator_t notifyIterator
;
91 CFMutableArrayRef notifyNodes
;
93 // interfaces that we already know about
94 CFMutableSetRef interfaces_known
;
96 // interfaces that should be auto-configured (no user notification)
97 CFMutableArrayRef interfaces_configure
;
99 // interfaces that require user notification
100 CFMutableArrayRef interfaces_prompt
;
102 CFUserNotificationRef userNotification
;
103 CFRunLoopSourceRef userRls
;
105 AuthorizationRef authorization
;
108 static CFMutableDictionaryRef notify_to_instance
= NULL
;
119 __log_SCMonitor(void)
121 static os_log_t log
= NULL
;
124 log
= os_log_create("com.apple.SystemConfiguration", "SCMonitor");
132 #pragma mark Authorization
135 static AuthorizationRef
136 getAuthorization(MyType
*myInstance
)
138 if (myInstance
->authorization
== NULL
) {
139 AuthorizationFlags flags
= kAuthorizationFlagDefaults
;
142 status
= AuthorizationCreate(NULL
,
143 kAuthorizationEmptyEnvironment
,
145 &myInstance
->authorization
);
146 if (status
!= errAuthorizationSuccess
) {
147 SC_log(LOG_ERR
, "AuthorizationCreate() failed: status = %d", (int)status
);
151 return myInstance
->authorization
;
156 hasAuthorization(MyType
*myInstance
)
158 AuthorizationRef authorization
;
159 Boolean isAdmin
= FALSE
;
161 authorization
= getAuthorization(myInstance
);
162 if (authorization
!= NULL
) {
163 AuthorizationFlags flags
= kAuthorizationFlagDefaults
;
164 AuthorizationItem items
[1];
165 AuthorizationRights rights
;
168 items
[0].name
= kSCPreferencesAuthorizationRight_write
;
169 items
[0].value
= NULL
;
170 items
[0].valueLength
= 0;
173 rights
.count
= sizeof(items
) / sizeof(items
[0]);
174 rights
.items
= items
;
176 status
= AuthorizationCopyRights(authorization
,
178 kAuthorizationEmptyEnvironment
,
181 isAdmin
= (status
== errAuthorizationSuccess
);
189 freeAuthorization(MyType
*myInstance
)
191 if (myInstance
->authorization
!= NULL
) {
192 AuthorizationFree(myInstance
->authorization
, kAuthorizationFlagDefaults
);
193 // AuthorizationFree(myInstance->authorization, kAuthorizationFlagDestroyRights);
194 myInstance
->authorization
= NULL
;
202 #pragma mark New interface notification / configuration
206 open_NetworkPrefPane(MyType
*myInstance
)
208 #pragma unused(myInstance)
209 AEDesc aeDesc
= { typeNull
, NULL
};
210 CFArrayRef prefArray
;
212 LSLaunchURLSpec prefSpec
;
215 prefURL
= CFURLCreateWithFileSystemPath(kCFAllocatorDefault
,
216 CFSTR(NETWORK_PREF_APP
),
217 kCFURLPOSIXPathStyle
,
219 prefArray
= CFArrayCreate(NULL
, (const void **)&prefURL
, 1, &kCFTypeArrayCallBacks
);
222 status
= AECreateDesc('ptru',
223 (const void *)NETWORK_PREF_CMD
,
224 strlen(NETWORK_PREF_CMD
),
226 if (status
!= noErr
) {
227 SC_log(LOG_ERR
, "AECreateDesc() failed: %d", (int)status
);
230 prefSpec
.appURL
= NULL
;
231 prefSpec
.itemURLs
= prefArray
;
232 prefSpec
.passThruParams
= &aeDesc
;
233 prefSpec
.launchFlags
= kLSLaunchAsync
| kLSLaunchDontAddToRecents
;
234 prefSpec
.asyncRefCon
= NULL
;
236 status
= LSOpenFromURLSpec(&prefSpec
, NULL
);
237 if (status
!= noErr
) {
238 SC_log(LOG_ERR
, "LSOpenFromURLSpec() failed: %d", (int)status
);
241 CFRelease(prefArray
);
242 if (aeDesc
.descriptorType
!= typeNull
) AEDisposeDesc(&aeDesc
);
248 notify_remove(MyType
*myInstance
, Boolean cancel
)
250 if (myInstance
->interfaces_configure
!= NULL
) {
251 CFRelease(myInstance
->interfaces_configure
);
252 myInstance
->interfaces_configure
= NULL
;
255 if (myInstance
->interfaces_prompt
!= NULL
) {
256 CFRelease(myInstance
->interfaces_prompt
);
257 myInstance
->interfaces_prompt
= NULL
;
260 if (myInstance
->userRls
!= NULL
) {
261 CFRunLoopSourceInvalidate(myInstance
->userRls
);
262 CFRelease(myInstance
->userRls
);
263 myInstance
->userRls
= NULL
;
266 if (myInstance
->userNotification
!= NULL
) {
270 status
= CFUserNotificationCancel(myInstance
->userNotification
);
273 "CFUserNotificationCancel() failed, status=%d",
277 CFRelease(myInstance
->userNotification
);
278 myInstance
->userNotification
= NULL
;
286 notify_reply(CFUserNotificationRef userNotification
, CFOptionFlags response_flags
)
288 MyType
*myInstance
= NULL
;
290 // get instance for notification
291 if (notify_to_instance
!= NULL
) {
292 myInstance
= (MyType
*)CFDictionaryGetValue(notify_to_instance
, userNotification
);
293 if (myInstance
!= NULL
) {
294 CFDictionaryRemoveValue(notify_to_instance
, userNotification
);
295 if (CFDictionaryGetCount(notify_to_instance
) == 0) {
296 CFRelease(notify_to_instance
);
297 notify_to_instance
= NULL
;
301 if (myInstance
== NULL
) {
302 SC_log(LOG_ERR
, "can't find user notification");
307 switch (response_flags
& 0x3) {
308 case kCFUserNotificationDefaultResponse
:
309 // user asked to configure interface
310 open_NetworkPrefPane(myInstance
);
317 notify_remove(myInstance
, FALSE
);
323 notify_add(MyType
*myInstance
)
326 CFMutableDictionaryRef dict
= NULL
;
329 CFIndex n
= CFArrayGetCount(myInstance
->interfaces_prompt
);
332 if (myInstance
->userNotification
!= NULL
) {
333 CFMutableArrayRef save
= NULL
;
336 CFRetain(myInstance
->interfaces_prompt
);
337 save
= myInstance
->interfaces_prompt
;
339 notify_remove(myInstance
, TRUE
);
340 myInstance
->interfaces_prompt
= save
;
346 dict
= CFDictionaryCreateMutable(NULL
,
348 &kCFTypeDictionaryKeyCallBacks
,
349 &kCFTypeDictionaryValueCallBacks
);
351 // set localization URL
352 bundle
= CFBundleGetBundleWithIdentifier(CFSTR(MY_BUNDLE_ID
));
353 if (bundle
!= NULL
) {
354 url
= CFBundleCopyBundleURL(bundle
);
358 url
= CFURLCreateFromFileSystemRepresentation(NULL
,
359 (const UInt8
*)"/System/Library/UserEventPlugins/SCMonitor.plugin",
360 strlen("/System/Library/UserEventPlugins/SCMonitor.plugin"),
362 if (bundle
== NULL
) {
363 bundle
= CFBundleCreate(NULL
, url
);
369 CFDictionarySetValue(dict
, kCFUserNotificationLocalizationURLKey
, url
);
372 SC_log(LOG_ERR
, "can't find bundle");
377 url
= CFURLCreateFromFileSystemRepresentation(NULL
,
378 (const UInt8
*)MY_ICON_PATH
,
379 strlen(MY_ICON_PATH
),
382 CFDictionarySetValue(dict
, kCFUserNotificationIconURLKey
, url
);
387 CFDictionarySetValue(dict
,
388 kCFUserNotificationAlertHeaderKey
,
389 (n
== 1) ? CFSTR("HEADER_1") : CFSTR("HEADER_N"));
394 SCNetworkInterfaceRef interface
;
398 #define MESSAGE_1 "The “%@” network interface has not been set up. To set up this interface, use Network Preferences."
400 format
= CFBundleCopyLocalizedString(bundle
,
404 interface
= CFArrayGetValueAtIndex(myInstance
->interfaces_prompt
, 0);
405 name
= SCNetworkInterfaceGetLocalizedDisplayName(interface
);
406 message
= CFStringCreateWithFormat(NULL
, NULL
, format
, name
);
407 CFDictionarySetValue(dict
, kCFUserNotificationAlertMessageKey
, message
);
411 CFMutableArrayRef message
;
413 message
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
414 CFArrayAppendValue(message
, CFSTR("MESSAGE_SN"));
415 for (i
= 0; i
< n
; i
++) {
416 SCNetworkInterfaceRef interface
;
420 interface
= CFArrayGetValueAtIndex(myInstance
->interfaces_prompt
, i
);
421 name
= SCNetworkInterfaceGetLocalizedDisplayName(interface
);
422 str
= CFStringCreateWithFormat(NULL
, NULL
, CFSTR("\r\t%@"), name
);
423 CFArrayAppendValue(message
, str
);
426 CFArrayAppendValue(message
, CFSTR("MESSAGE_EN"));
427 CFDictionarySetValue(dict
, kCFUserNotificationAlertMessageKey
, message
);
432 CFDictionaryAddValue(dict
, kCFUserNotificationDefaultButtonTitleKey
, CFSTR("OPEN_NP"));
433 CFDictionaryAddValue(dict
, kCFUserNotificationAlternateButtonTitleKey
, CFSTR("CANCEL"));
435 // create and post notification
436 myInstance
->userNotification
= CFUserNotificationCreate(NULL
,
438 kCFUserNotificationNoteAlertLevel
,
441 if (myInstance
->userNotification
== NULL
) {
442 SC_log(LOG_ERR
, "CFUserNotificationCreate() failed: %d", (int)error
);
446 // establish callback
447 myInstance
->userRls
= CFUserNotificationCreateRunLoopSource(NULL
,
448 myInstance
->userNotification
,
451 if (myInstance
->userRls
== NULL
) {
452 SC_log(LOG_ERR
, "CFUserNotificationCreateRunLoopSource() failed");
453 CFRelease(myInstance
->userNotification
);
454 myInstance
->userNotification
= NULL
;
457 CFRunLoopAddSource(CFRunLoopGetCurrent(), myInstance
->userRls
, kCFRunLoopDefaultMode
);
459 // add instance for notification
460 if (notify_to_instance
== NULL
) {
461 notify_to_instance
= CFDictionaryCreateMutable(NULL
,
463 &kCFTypeDictionaryKeyCallBacks
,
464 NULL
); // no retain/release/... for values
466 CFDictionarySetValue(notify_to_instance
, myInstance
->userNotification
, myInstance
);
470 if (dict
!= NULL
) CFRelease(dict
);
476 notify_configure(MyType
*myInstance
)
479 CFIndex n
= CFArrayGetCount(myInstance
->interfaces_configure
);
481 SCPreferencesRef prefs
= NULL
;
482 SCNetworkSetRef set
= NULL
;
484 if (geteuid() == 0) {
485 prefs
= SCPreferencesCreate(NULL
, CFSTR("SCMonitor"), NULL
);
487 AuthorizationRef authorization
;
489 authorization
= getAuthorization(myInstance
);
490 if (authorization
== NULL
) {
494 prefs
= SCPreferencesCreateWithAuthorization(NULL
, CFSTR("SCMonitor"), NULL
, authorization
);
497 set
= SCNetworkSetCopyCurrent(prefs
);
499 // if no "current" set, create new/default ("Automatic") set
500 set
= _SCNetworkSetCreateDefault(prefs
);
504 SC_log(LOG_DEBUG
, "added new \"default\" set");
507 for (i
= 0; i
< n
; i
++) {
508 SCNetworkInterfaceRef interface
;
510 interface
= CFArrayGetValueAtIndex(myInstance
->interfaces_configure
, i
);
511 ok
= SCNetworkSetEstablishDefaultInterfaceConfiguration(set
, interface
);
515 name
= SCNetworkInterfaceGetLocalizedDisplayName(interface
);
516 SC_log(LOG_NOTICE
, "add/update service for %@", name
);
520 ok
= SCPreferencesCommitChanges(prefs
);
523 "SCPreferencesCommitChanges() failed: %s",
524 SCErrorString(SCError()));
528 ok
= SCPreferencesApplyChanges(prefs
);
531 "SCPreferencesApplyChanges() failed: %s",
532 SCErrorString(SCError()));
548 CFRelease(myInstance
->interfaces_configure
);
549 myInstance
->interfaces_configure
= NULL
;
560 CFArrayRef console_sessions
;
562 io_registry_entry_t root
;
563 uid_t uid
= geteuid();
565 root
= IORegistryGetRootEntry(kIOMasterPortDefault
);
566 console_sessions
= IORegistryEntryCreateCFProperty(root
,
567 CFSTR(kIOConsoleUsersKey
),
570 if (console_sessions
!= NULL
) {
573 n
= isA_CFArray(console_sessions
) ? CFArrayGetCount(console_sessions
) : 0;
574 for (CFIndex i
= 0; i
< n
; i
++) {
576 CFDictionaryRef session
;
580 session
= CFArrayGetValueAtIndex(console_sessions
, i
);
581 if (!isA_CFDictionary(session
)) {
586 if (!CFDictionaryGetValueIfPresent(session
,
587 CFSTR(kIOConsoleSessionUIDKey
),
588 (const void **)&val
) ||
589 !isA_CFNumber(val
) ||
590 !CFNumberGetValue(val
, kCFNumberSInt64Type
, (void *)&sessionUID
) ||
591 (uid
!= sessionUID
)) {
596 if (CFDictionaryGetValueIfPresent(session
,
597 CFSTR(kIOConsoleSessionOnConsoleKey
),
598 (const void **)&bVal
) &&
599 isA_CFBoolean(bVal
) &&
600 CFBooleanGetValue(bVal
)) {
601 // if "on console" session
608 CFRelease(console_sessions
);
610 IOObjectRelease(root
);
619 // configure ONLY IF authorized
620 #define kSCNetworkInterfaceConfigurationActionValueConfigureAuthorized CFSTR("Configure-Authorized")
624 updateInterfaceList(MyType
*myInstance
)
626 Boolean changed
= FALSE
;
628 CFArrayRef interfaces
;
629 CFMutableSetRef interfaces_old
= NULL
;
631 SCPreferencesRef prefs
;
632 SCNetworkSetRef set
= NULL
;
638 prefs
= SCPreferencesCreate(NULL
, CFSTR("SCMonitor"), NULL
);
643 set
= SCNetworkSetCopyCurrent(prefs
);
645 // if no "current" set, create new/default ("Automatic") set
646 set
= _SCNetworkSetCreateDefault(prefs
);
652 interfaces_old
= CFSetCreateMutableCopy(NULL
, 0, myInstance
->interfaces_known
);
654 interfaces
= _SCNetworkInterfaceCopyAllWithPreferences(prefs
);
655 if (interfaces
!= NULL
) {
656 n
= CFArrayGetCount(interfaces
);
657 for (i
= 0; i
< n
; i
++) {
658 SCNetworkInterfaceRef interface
;
661 interface
= CFArrayGetValueAtIndex(interfaces
, i
);
663 // track new vs. old (removed) interfaces
664 CFSetRemoveValue(interfaces_old
, interface
);
665 if (CFSetContainsValue(myInstance
->interfaces_known
, interface
)) {
666 // if we already know about this interface
669 CFSetAddValue(myInstance
->interfaces_known
, interface
);
672 ok
= SCNetworkSetEstablishDefaultInterfaceConfiguration(set
, interface
);
676 // this is a *new* interface
678 action
= _SCNetworkInterfaceGetConfigurationAction(interface
);
679 if (action
== NULL
) {
680 // if no per-interface action, use [global] default
681 action
= myInstance
->configuration_action
;
683 if ((action
== NULL
) ||
684 (!CFEqual(action
, kSCNetworkInterfaceConfigurationActionValueNone
) &&
685 !CFEqual(action
, kSCNetworkInterfaceConfigurationActionValueConfigure
))) {
686 if (_SCNetworkInterfaceIsBuiltin(interface
)) {
687 // if built-in interface
688 action
= kSCNetworkInterfaceConfigurationActionValueConfigureAuthorized
;
690 action
= kSCNetworkInterfaceConfigurationActionValuePrompt
;
694 if (CFEqual(action
, kSCNetworkInterfaceConfigurationActionValueNone
)) {
696 } else if (CFEqual(action
, kSCNetworkInterfaceConfigurationActionValueConfigure
)) {
697 // configure automatically (without user intervention)
698 if (myInstance
->interfaces_configure
== NULL
) {
699 myInstance
->interfaces_configure
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
701 CFArrayAppendValue(myInstance
->interfaces_configure
, interface
);
702 } else if (hasAuthorization(myInstance
)) {
703 // if we already have the "admin" (kSCPreferencesAuthorizationRight_write)
704 // right, configure automatically (without user intervention)
705 if (myInstance
->interfaces_configure
== NULL
) {
706 myInstance
->interfaces_configure
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
708 CFArrayAppendValue(myInstance
->interfaces_configure
, interface
);
709 } else if (!CFEqual(action
, kSCNetworkInterfaceConfigurationActionValueConfigureAuthorized
)) {
711 if (myInstance
->interfaces_prompt
== NULL
) {
712 myInstance
->interfaces_prompt
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
714 CFArrayAppendValue(myInstance
->interfaces_prompt
, interface
);
719 CFRelease(interfaces
);
722 // remove any posted notifications for network interfaces that have been removed
723 n
= CFSetGetCount(interfaces_old
);
725 const void * paths_q
[32];
726 const void ** paths
= paths_q
;
728 if (n
> (CFIndex
)(sizeof(paths_q
) / sizeof(CFTypeRef
)))
729 paths
= CFAllocatorAllocate(NULL
, n
* sizeof(CFTypeRef
), 0);
730 CFSetGetValues(interfaces_old
, paths
);
731 for (i
= 0; i
< n
; i
++) {
732 if (myInstance
->interfaces_prompt
!= NULL
) {
735 j
= CFArrayGetCount(myInstance
->interfaces_prompt
);
737 SCNetworkInterfaceRef interface
;
740 interface
= CFArrayGetValueAtIndex(myInstance
->interfaces_prompt
, j
);
741 if (CFEqual(interface
, paths
[i
])) {
742 // if we have previously posted a notification
743 // for this no-longer-present interface
744 CFArrayRemoveValueAtIndex(myInstance
->interfaces_prompt
, j
);
750 CFSetRemoveValue(myInstance
->interfaces_known
, paths
[i
]);
752 if (paths
!= paths_q
) CFAllocatorDeallocate(NULL
, paths
);
758 if (myInstance
->interfaces_configure
!= NULL
) {
759 // if we have network services to configure automatically
760 notify_configure(myInstance
);
763 if (myInstance
->interfaces_prompt
!= NULL
) {
764 // if we have network services that require user intervention
765 // post notification for new interfaces
766 notify_add(myInstance
);
770 if (interfaces_old
!= NULL
) CFRelease(interfaces_old
);
771 if (set
!= NULL
) CFRelease(set
);
778 #pragma mark Watch for new [network] interfaces
782 update_lan(SCDynamicStoreRef store
, CFArrayRef changes
, void * arg
)
784 #pragma unused(store)
785 #pragma unused(changes)
786 MyType
*myInstance
= (MyType
*)arg
;
788 updateInterfaceList(myInstance
);
794 watcher_add_lan(MyType
*myInstance
)
796 SCDynamicStoreContext context
= { 0, (void *)myInstance
, NULL
, NULL
, NULL
};
799 SCDynamicStoreRef store
;
801 store
= SCDynamicStoreCreate(NULL
, CFSTR("SCMonitor"), update_lan
, &context
);
804 "SCDynamicStoreCreate() failed: %s",
805 SCErrorString(SCError()));
809 key
= SCDynamicStoreKeyCreateNetworkInterface(NULL
, kSCDynamicStoreDomainState
);
811 // watch for changes to the list of network interfaces
812 keys
= CFArrayCreate(NULL
, (const void **)&key
, 1, &kCFTypeArrayCallBacks
);
813 SCDynamicStoreSetNotificationKeys(store
, keys
, NULL
);
815 myInstance
->monitorRls
= SCDynamicStoreCreateRunLoopSource(NULL
, store
, 0);
816 CFRunLoopAddSource(CFRunLoopGetCurrent(),
817 myInstance
->monitorRls
,
818 kCFRunLoopDefaultMode
);
820 // check if we already have the "admin" (kSCPreferencesAuthorizationRight_write)
821 // right. If so, we can automatically configure (without user intervention) any
822 // "new" network interfaces that are present at login (e.g. a USB ethernet
823 // dongle that was plugged in before login).
824 if (!hasAuthorization(myInstance
)) {
825 CFDictionaryRef dict
;
827 // ... and if we don't have the right then we populate the list of
828 // known interfaces with those already named so that we avoid any
829 // login prompts (that the user might have no choice but to dismiss)
830 dict
= SCDynamicStoreCopyValue(store
, key
);
832 if (isA_CFDictionary(dict
)) {
834 CFArrayRef interfaces
;
837 interfaces
= CFDictionaryGetValue(dict
, kSCPropNetInterfaces
);
838 n
= isA_CFArray(interfaces
) ? CFArrayGetCount(interfaces
) : 0;
839 for (i
= 0; i
< n
; i
++) {
842 bsdName
= CFArrayGetValueAtIndex(interfaces
, i
);
843 if (isA_CFString(bsdName
)) {
844 SCNetworkInterfaceRef interface
;
846 interface
= _SCNetworkInterfaceCreateWithBSDName(NULL
, bsdName
, kIncludeNoVirtualInterfaces
);
847 if (interface
!= NULL
) {
848 CFSetAddValue(myInstance
->interfaces_known
, interface
);
849 CFRelease(interface
);
866 watcher_remove_lan(MyType
*myInstance
)
868 if (myInstance
->monitorRls
!= NULL
) {
869 CFRunLoopSourceInvalidate(myInstance
->monitorRls
);
870 CFRelease(myInstance
->monitorRls
);
871 myInstance
->monitorRls
= NULL
;
882 io_registry_entry_t interface
;
883 io_registry_entry_t interface_node
;
885 io_object_t notification
;
890 add_node_watcher(MyType
*myInstance
, io_registry_entry_t node
, io_registry_entry_t interface
);
894 update_node(void *refCon
, io_service_t service
, natural_t messageType
, void *messageArgument
)
896 #pragma unused(messageArgument)
898 CFDataRef myData
= (CFDataRef
)refCon
;
902 /* ALIGN: CF aligns to at least >8 bytes */
903 myNode
= (MyNode
*)(void *)CFDataGetBytePtr(myData
);
904 myInstance
= myNode
->myInstance
;
906 switch (messageType
) {
907 case kIOMessageServicePropertyChange
: {
908 Boolean initializing
= FALSE
;
909 SCNetworkInterfaceRef interface
;
912 if (myNode
->interface
== MACH_PORT_NULL
) {
913 // if we are not watching the "Initializing" property
917 val
= IORegistryEntryCreateCFProperty(service
, kSCNetworkInterfaceInitializingKey
, NULL
, 0);
919 initializing
= (isA_CFBoolean(val
) && CFBooleanGetValue(val
));
922 // if initialization not complete, keep watching
928 interface
= _SCNetworkInterfaceCreateWithIONetworkInterfaceObject(myNode
->interface
);
929 if (interface
!= NULL
) {
930 CFRelease(interface
);
932 // watch interface (to see when/if it's removed)
933 add_node_watcher(myInstance
, myNode
->interface
, MACH_PORT_NULL
);
938 case kIOMessageServiceIsTerminated
:
945 // remove no-longer-needed notification
946 if (myNode
->interface
!= myNode
->interface_node
) {
947 IOObjectRelease(myNode
->interface_node
);
949 if (myNode
->interface
!= MACH_PORT_NULL
) {
950 IOObjectRelease(myNode
->interface
);
952 IOObjectRelease(myNode
->notification
);
953 i
= CFArrayGetFirstIndexOfValue(myInstance
->notifyNodes
,
954 CFRangeMake(0, CFArrayGetCount(myInstance
->notifyNodes
)),
956 if (i
!= kCFNotFound
) {
957 CFArrayRemoveValueAtIndex(myInstance
->notifyNodes
, i
);
958 if (CFArrayGetCount(myInstance
->notifyNodes
) == 0) {
959 CFRelease(myInstance
->notifyNodes
);
960 myInstance
->notifyNodes
= NULL
;
964 updateInterfaceList(myInstance
);
970 add_node_watcher(MyType
*myInstance
, io_registry_entry_t node
, io_registry_entry_t interface
)
973 CFMutableDataRef myData
;
976 // wait for initialization to complete
977 myData
= CFDataCreateMutable(NULL
, sizeof(MyNode
));
978 CFDataSetLength(myData
, sizeof(MyNode
));
980 /* ALIGN: CF aligns to at least >8 bytes */
981 myNode
= (MyNode
*)(void *)CFDataGetBytePtr(myData
);
983 bzero(myNode
, sizeof(MyNode
));
984 myNode
->interface
= interface
;
985 if (myNode
->interface
!= MACH_PORT_NULL
) {
986 IOObjectRetain(myNode
->interface
);
988 myNode
->interface_node
= (interface
== MACH_PORT_NULL
) ? node
: interface
;
989 if (myNode
->interface
!= myNode
->interface_node
) {
990 IOObjectRetain(myNode
->interface_node
);
992 myNode
->myInstance
= myInstance
;
993 myNode
->notification
= MACH_PORT_NULL
;
995 kr
= IOServiceAddInterestNotification(myInstance
->notifyPort
, // IONotificationPortRef
996 node
, // io_service_t
997 kIOGeneralInterest
, // interestType
998 update_node
, // IOServiceInterestCallback
999 (void *)myData
, // refCon
1000 &myNode
->notification
); // notification
1001 if (kr
== KERN_SUCCESS
) {
1002 if (myInstance
->notifyNodes
== NULL
) {
1003 myInstance
->notifyNodes
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
1005 CFArrayAppendValue(myInstance
->notifyNodes
, myData
);
1008 "add_init_watcher IOServiceAddInterestNotification() failed, kr = 0x%x",
1016 add_init_watcher(MyType
*myInstance
, io_registry_entry_t interface
)
1019 io_registry_entry_t node
= interface
;
1020 CFTypeRef val
= NULL
;
1022 while (node
!= MACH_PORT_NULL
) {
1023 io_registry_entry_t parent
;
1025 val
= IORegistryEntryCreateCFProperty(node
, kSCNetworkInterfaceHiddenPortKey
, NULL
, 0);
1032 val
= IORegistryEntryCreateCFProperty(node
, kSCNetworkInterfaceInitializingKey
, NULL
, 0);
1037 parent
= MACH_PORT_NULL
;
1038 kr
= IORegistryEntryGetParentEntry(node
, kIOServicePlane
, &parent
);
1040 case kIOReturnSuccess
: // if we have a parent node
1041 case kIOReturnNoDevice
: // if we have hit the root node
1044 SC_log(LOG_ERR
, "add_init_watcher IORegistryEntryGetParentEntry() failed, kr = 0x%x", kr
);
1047 if (node
!= interface
) {
1048 IOObjectRelease(node
);
1054 if (isA_CFBoolean(val
) && CFBooleanGetValue(val
)) {
1055 // watch the "Initializing" node
1056 add_node_watcher(myInstance
, node
, interface
);
1062 if ((node
!= MACH_PORT_NULL
) && (node
!= interface
)) {
1063 IOObjectRelease(node
);
1071 update_serial(void *refcon
, io_iterator_t iter
)
1073 MyType
*myInstance
= (MyType
*)refcon
;
1074 io_registry_entry_t obj
;
1076 while ((obj
= IOIteratorNext(iter
)) != MACH_PORT_NULL
) {
1077 SCNetworkInterfaceRef interface
;
1079 interface
= _SCNetworkInterfaceCreateWithIONetworkInterfaceObject(obj
);
1080 if (interface
!= NULL
) {
1081 CFRelease(interface
);
1083 // watch interface (to see when/if it's removed)
1084 add_node_watcher(myInstance
, obj
, MACH_PORT_NULL
);
1086 // check interface, watch if initializing
1087 add_init_watcher(myInstance
, obj
);
1090 IOObjectRelease(obj
);
1098 update_serial_nodes(void *refcon
, io_iterator_t iter
)
1100 MyType
*myInstance
= (MyType
*)refcon
;
1102 update_serial(refcon
, iter
);
1103 updateInterfaceList(myInstance
);
1108 watcher_add_serial(MyType
*myInstance
)
1112 myInstance
->notifyPort
= IONotificationPortCreate(kIOMasterPortDefault
);
1113 if (myInstance
->notifyPort
== NULL
) {
1114 SC_log(LOG_ERR
, "IONotificationPortCreate failed");
1118 // watch for the introduction of new network serial devices
1119 kr
= IOServiceAddMatchingNotification(myInstance
->notifyPort
,
1120 kIOFirstMatchNotification
,
1121 IOServiceMatching("IOSerialBSDClient"),
1122 &update_serial_nodes
,
1123 (void *)myInstance
, // refCon
1124 &myInstance
->notifyIterator
); // notification
1125 if (kr
!= KERN_SUCCESS
) {
1126 SC_log(LOG_ERR
, "SCMonitor : IOServiceAddMatchingNotification returned 0x%x", kr
);
1130 myInstance
->notifyNodes
= NULL
;
1132 // Get the current list of matches and arm the notification for
1133 // future interface arrivals.
1134 update_serial((void *)myInstance
, myInstance
->notifyIterator
);
1136 if (myInstance
->notifyNodes
!= NULL
) {
1137 // if we have any serial nodes, check if we already have the
1138 // "admin" (kSCPreferencesAuthorizationRight_write) right. If
1139 // so, we can automatically configure (without user intervention)
1140 // any "new" network interfaces that are present at login (e.g. a
1141 // USB modem that was plugged in before login).
1143 if (!hasAuthorization(myInstance
)) {
1145 CFIndex n
= CFArrayGetCount(myInstance
->notifyNodes
);
1147 // ... and if we don't have the right then we populate the list of
1148 // known interfaces with those already named so that we avoid any
1149 // login prompts (that the user might have no choice but to dismiss)
1151 for (i
= 0; i
< n
; i
++) {
1152 SCNetworkInterfaceRef interface
;
1156 myData
= CFArrayGetValueAtIndex(myInstance
->notifyNodes
, i
);
1158 /* ALIGN: CF aligns to at least >8 bytes */
1159 myNode
= (MyNode
*)(void *)CFDataGetBytePtr(myData
);
1161 interface
= _SCNetworkInterfaceCreateWithIONetworkInterfaceObject(myNode
->interface_node
);
1162 if (interface
!= NULL
) {
1163 CFSetAddValue(myInstance
->interfaces_known
, interface
);
1164 CFRelease(interface
);
1170 // and keep watching
1171 CFRunLoopAddSource(CFRunLoopGetCurrent(),
1172 IONotificationPortGetRunLoopSource(myInstance
->notifyPort
),
1173 kCFRunLoopDefaultMode
);
1179 watcher_remove_serial(MyType
*myInstance
)
1181 if (myInstance
->notifyNodes
!= NULL
) {
1183 CFIndex n
= CFArrayGetCount(myInstance
->notifyNodes
);
1185 for (i
= 0; i
< n
; i
++) {
1189 myData
= CFArrayGetValueAtIndex(myInstance
->notifyNodes
, i
);
1191 /* ALIGN: CF aligns to at least >8 bytes */
1192 myNode
= (MyNode
*)(void *)CFDataGetBytePtr(myData
);
1194 if (myNode
->interface
!= myNode
->interface_node
) {
1195 IOObjectRelease(myNode
->interface_node
);
1197 if (myNode
->interface
!= MACH_PORT_NULL
) {
1198 IOObjectRelease(myNode
->interface
);
1200 IOObjectRelease(myNode
->notification
);
1203 CFRelease(myInstance
->notifyNodes
);
1204 myInstance
->notifyNodes
= NULL
;
1207 if (myInstance
->notifyIterator
!= MACH_PORT_NULL
) {
1208 IOObjectRelease(myInstance
->notifyIterator
);
1209 myInstance
->notifyIterator
= MACH_PORT_NULL
;
1212 if (myInstance
->notifyPort
!= MACH_PORT_NULL
) {
1213 IONotificationPortDestroy(myInstance
->notifyPort
);
1214 myInstance
->notifyPort
= NULL
;
1225 watcher_add(MyType
*myInstance
)
1229 bundle
= CFBundleGetBundleWithIdentifier(CFSTR(MY_BUNDLE_ID
));
1230 if (bundle
!= NULL
) {
1233 CFDictionaryRef info
;
1235 info
= CFBundleGetInfoDictionary(bundle
);
1237 bVal
= CFDictionaryGetValue(info
, CFSTR("Debug"));
1238 bVal
= isA_CFBoolean(bVal
);
1240 myInstance
->debug
= CFBooleanGetValue(bVal
);
1243 action
= CFDictionaryGetValue(info
, kSCNetworkInterfaceConfigurationActionKey
);
1244 action
= isA_CFString(action
);
1245 if (action
!= NULL
) {
1246 myInstance
->configuration_action
= action
;
1248 CFBooleanRef user_intervention
;
1250 user_intervention
= CFDictionaryGetValue(info
, CFSTR("User Intervention"));
1251 if (isA_CFBoolean(user_intervention
) && !CFBooleanGetValue(user_intervention
)) {
1252 myInstance
->configuration_action
= kSCNetworkInterfaceConfigurationActionValueConfigure
;
1257 // initialize the list of known interfaces
1258 myInstance
->interfaces_known
= CFSetCreateMutable(NULL
, 0, &kCFTypeSetCallBacks
);
1260 // add LAN interfaces
1261 watcher_add_lan(myInstance
);
1263 // add SERIAL interfaces
1264 watcher_add_serial(myInstance
);
1266 // auto-configure (as needed)
1267 updateInterfaceList(myInstance
);
1274 watcher_remove(MyType
*myInstance
)
1276 watcher_remove_lan(myInstance
);
1277 watcher_remove_serial(myInstance
);
1279 if (myInstance
->interfaces_known
!= NULL
) {
1280 CFRelease(myInstance
->interfaces_known
);
1281 myInstance
->interfaces_known
= NULL
;
1289 #pragma mark UserEventAgent stubs
1293 myQueryInterface(void *myInstance
, REFIID iid
, LPVOID
*ppv
)
1295 CFUUIDRef interfaceID
= CFUUIDCreateFromUUIDBytes(NULL
, iid
);
1297 // Test the requested ID against the valid interfaces.
1298 if (CFEqual(interfaceID
, kUserEventAgentInterfaceID
)) {
1299 ((MyType
*) myInstance
)->_UserEventAgentInterface
->AddRef(myInstance
);
1301 CFRelease(interfaceID
);
1305 if (CFEqual(interfaceID
, IUnknownUUID
)) {
1306 ((MyType
*) myInstance
)->_UserEventAgentInterface
->AddRef(myInstance
);
1308 CFRelease(interfaceID
);
1312 // Requested interface unknown, bail with error.
1314 CFRelease(interfaceID
);
1315 return E_NOINTERFACE
;
1320 myAddRef(void *myInstance
)
1322 ((MyType
*) myInstance
)->_refCount
++;
1323 return ((MyType
*) myInstance
)->_refCount
;
1328 myRelease(void *myInstance
)
1330 ((MyType
*) myInstance
)->_refCount
--;
1331 if (((MyType
*) myInstance
)->_refCount
== 0) {
1332 CFUUIDRef factoryID
= ((MyType
*) myInstance
)->_factoryID
;
1334 if (factoryID
!= NULL
) {
1335 CFPlugInRemoveInstanceForFactory(factoryID
);
1336 CFRelease(factoryID
);
1338 watcher_remove((MyType
*)myInstance
);
1339 notify_remove((MyType
*)myInstance
, TRUE
);
1340 freeAuthorization((MyType
*)myInstance
);
1346 return ((MyType
*) myInstance
)->_refCount
;
1351 myInstall(void *myInstance
)
1353 watcher_add((MyType
*)myInstance
);
1358 static UserEventAgentInterfaceStruct UserEventAgentInterfaceFtbl
= {
1359 NULL
, // Required padding for COM
1360 myQueryInterface
, // These three are the required COM functions
1363 myInstall
// Interface implementation
1368 UserEventAgentFactory(CFAllocatorRef allocator
, CFUUIDRef typeID
)
1370 #pragma unused(allocator)
1371 MyType
*newOne
= NULL
;
1373 if (CFEqual(typeID
, kUserEventAgentTypeID
)) {
1374 newOne
= (MyType
*)malloc(sizeof(MyType
));
1375 bzero(newOne
, sizeof(*newOne
));
1376 newOne
->_UserEventAgentInterface
= &UserEventAgentInterfaceFtbl
;
1377 newOne
->_factoryID
= (CFUUIDRef
)CFRetain(kUserEventAgentFactoryID
);
1378 CFPlugInAddInstanceForFactory(kUserEventAgentFactoryID
);
1379 newOne
->_refCount
= 1;
1388 main(int argc
, char **argv
)
1390 MyType
*newOne
= (MyType
*)malloc(sizeof(MyType
));
1393 _sc_verbose
= (argc
> 1) ? TRUE
: FALSE
;
1395 bzero(newOne
, sizeof(*newOne
));