2 * Copyright (c) 2016 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 * March 1, 2016 Allan Nathanson <ajn@apple.com>
32 #include <mach/mach.h>
33 #include <mach-o/fat.h>
34 #include <mach-o/loader.h>
36 #include <net/if_types.h>
38 #include <sys/ioctl.h>
39 #include <sys/kern_control.h>
40 #include <sys/socket.h>
41 #include <sys/sockio.h>
42 #include <sys/sys_domain.h>
44 #define SC_LOG_HANDLE __log_QoSMarking()
45 #include <SystemConfiguration/SystemConfiguration.h>
46 #include <SystemConfiguration/SCPrivate.h>
47 #include <SystemConfiguration/SCValidation.h>
49 #import <Foundation/Foundation.h>
50 #import <NetworkExtension/NEPolicySession.h>
51 #import <NEHelperClient.h>
53 // define the QoSMarking.bundle Info.plist key containing [application] bundleIDs to be white-listed
54 #define kQoSMarkingBundleIdentifiersAppleAudioVideoCallsKey CFSTR("QoSMarking_AppleAudioVideoCalls_BundleIDs")
56 // define the QoSMarking.bundle Info.plist key containing paths to be white-listed
57 #define kQoSMarkingExecutablePathsAppleAudioVideoCallsKey CFSTR("QoSMarking_AppleAudioVideoCalls_ExecutablePaths")
59 // define the starting "order" value for any QoS Marking NEPolicy rules
60 #define QOS_MARKING_PRIORITY_BLOCK_AV_APPS 1000
61 #define QOS_MARKING_PRIORITY_BLOCK_AV_PATHS 1500
62 #define QOS_MARKING_PRIORITY_BLOCK_APPS 2000
65 static CFStringRef interfacesKey = NULL;
66 static NSArray * qosMarkingAudioVideoCalls_bundleIDs = nil;
67 static NSArray * qosMarkingAudioVideoCalls_executablePaths = nil;
74 __private_extern__ os_log_t
77 static os_log_t log = NULL;
80 log = os_log_create("com.apple.SystemConfiguration", "QoSMarking");
88 #pragma mark QoSMarking support (system)
92 qosMarkingSetPolicyRestriction(const char *ctl, BOOL yn)
94 int restricted = yn ? 1 : 0;
97 ret = sysctlbyname(ctl, NULL, 0, &restricted, sizeof(restricted));
99 SC_log(LOG_NOTICE, "QoS marking policy: sysctl %s=%d", ctl, restricted);
101 if (errno != ENOENT) {
102 SC_log(LOG_ERR, "sysctlbyname() failed: %s", strerror(errno));
111 qosMarkingSetHavePolicies(BOOL havePolicies)
113 qosMarkingSetPolicyRestriction("net.qos.policy.restricted", havePolicies);
119 qosMarkingSetRestrictAVApps(BOOL restrictApps)
121 qosMarkingSetPolicyRestriction("net.qos.policy.restrict_avapps", restrictApps);
127 #pragma mark QoSMarking support (per-interface)
131 supportsQoSMarking(int s, const char *ifname)
135 bzero(&ifr, sizeof(ifr));
136 strlcpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
137 if (ioctl(s, SIOCGIFTYPE, (caddr_t)&ifr) == -1) {
138 SC_log(LOG_NOTICE, "%s: ioctl(SIOCGIFTYPE) failed: %m", ifname);
139 ifr.ifr_type.ift_type = 0;
140 ifr.ifr_type.ift_family = IFRTYPE_FAMILY_ANY;
141 ifr.ifr_type.ift_subfamily = IFRTYPE_SUBFAMILY_ANY;
144 if ((ifr.ifr_type.ift_family == IFRTYPE_FAMILY_ETHERNET) &&
145 (ifr.ifr_type.ift_subfamily == IFRTYPE_SUBFAMILY_WIFI)) {
154 qosMarkingSetEnabled(int s, const char *ifname, BOOL enabled)
159 bzero(&ifr, sizeof(ifr));
160 strlcpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
161 ifr.ifr_qosmarking_enabled = enabled ? 1 : 0;
162 ret = ioctl(s, SIOCSQOSMARKINGENABLED, &ifr);
164 SC_log(LOG_ERR, "%s: ioctl(SIOCSQOSMARKINGENABLED) failed: %s",
174 #pragma mark QoSMarking Policy support
177 @interface QoSMarkingController : NSObject
179 + (QoSMarkingController *)sharedController;
180 - (void)setInterfaces:(NSArray *)interfaces;
181 - (void)setPolicy:(NSDictionary *)policy forInterface:(NSString *)interface;
186 @interface QoSMarkingController()
190 * An array of network interface names on the system/device
192 @property (nonatomic) NSArray * interfaces;
196 * A dictionary for the maintaining the QoS marking policies.
198 * Key : interface [name]
199 * Value : the NEPolicySession* for the interface
201 @property (nonatomic) NSMutableDictionary * policySessions;
205 * A dictionary for the tracking the QoS marking policies.
207 * Key : interface [name]
208 * Value : the [requested] NSDictionary* "policy" for the interface
210 @property (nonatomic) NSMutableDictionary * requested;
214 * Dictionaries for tracking the "enabled" interfaces with QoS [AV]
217 * Key : interface [name]
218 * Value : the enabled NSDictionary* "policy" for the interface
220 @property (nonatomic) NSMutableDictionary * enabled;
221 @property (nonatomic) NSMutableDictionary * enabledAV;
226 @implementation QoSMarkingController
228 - (NEPolicySession *)createPolicySession
230 NEPolicySession *session = nil;
231 #if !TARGET_OS_IPHONE
233 * Note: we cannot have entitlements on OSX so we open a kernel
234 * control socket and use it to create a policy session
237 struct sockaddr_ctl kernctl_addr;
238 struct ctl_info kernctl_info;
241 // Create kernel control socket
242 sock = socket(PF_SYSTEM, SOCK_DGRAM, SYSPROTO_CONTROL);
244 SC_log(LOG_ERR, "socket() failed: %s", strerror(errno));
248 bzero(&kernctl_info, sizeof(kernctl_info));
249 strlcpy(kernctl_info.ctl_name, NECP_CONTROL_NAME, sizeof(kernctl_info.ctl_name));
250 if (ioctl(sock, CTLIOCGINFO, &kernctl_info)) {
251 SC_log(LOG_ERR, "ioctl() failed: %s", strerror(errno));
256 bzero(&kernctl_addr, sizeof(kernctl_addr));
257 kernctl_addr.sc_len = sizeof(kernctl_addr);
258 kernctl_addr.sc_family = AF_SYSTEM;
259 kernctl_addr.ss_sysaddr = AF_SYS_CONTROL;
260 kernctl_addr.sc_id = kernctl_info.ctl_id;
261 kernctl_addr.sc_unit = 0;
262 if (connect(sock, (struct sockaddr *)&kernctl_addr, sizeof(kernctl_addr))) {
263 SC_log(LOG_ERR, "connect() failed: %s", strerror(errno));
268 /* Create policy session */
269 session = [[NEPolicySession alloc] initWithSocket:sock];
270 if (session == nil) {
274 #else // !TARGET_OS_IPHONE
275 session = [[NEPolicySession alloc] init];
276 #endif // !TARGET_OS_IPHONE
285 - (BOOL)qosMarkingPolicyEnabled:(NSDictionary *)policy forKey:(NSString *)key
289 enabled = policy[key];
290 if (enabled != nil) {
291 if (![enabled isKindOfClass:[NSNumber class]]) {
292 SC_log(LOG_ERR, "%@ not valid", key);
296 // assume "enabled" if no key
300 return enabled.boolValue;
304 - (BOOL)qosMarkingIsEnabled:(NSDictionary *)policy
306 return [self qosMarkingPolicyEnabled:policy
307 forKey:(NSString *)kSCPropNetQoSMarkingEnabled];
311 - (BOOL)qosMarkingIsAppleAudioVideoCallsEnabled:(NSDictionary *)policy
313 return [self qosMarkingPolicyEnabled:policy
314 forKey:(NSString *)kSCPropNetQoSMarkingAppleAudioVideoCalls];
318 - (NSArray *)qosMarkingWhitelistedAppIdentifiers:(NSDictionary *)policy
322 appIDs = policy[(NSString *)kSCPropNetQoSMarkingWhitelistedAppIdentifiers];
323 if ((appIDs != nil) && ![appIDs isKindOfClass:[NSArray class]]) {
324 SC_log(LOG_ERR, "QoSMarkingWhitelistedAppIdentifier list not valid");
328 for (NSString *appID in appIDs) {
329 if ((appID != nil) &&
330 (![appID isKindOfClass:[NSString class]] || (appID.length == 0))) {
331 SC_log(LOG_ERR, "QoSMarkingWhitelistedAppIdentifier not valid");
343 - (NSUUID *)copyUUIDForSingleArch:(int)fd
345 struct mach_header header;
348 if (read(fd, &header, sizeof(header)) != sizeof(header)) {
352 // Go past the 64 bit header if we have a 64 arch
353 if (header.magic == MH_MAGIC_64) {
354 if (lseek(fd, sizeof(uint32_t), SEEK_CUR) == -1) {
355 SC_log(LOG_ERR, "could not lseek() past 64 bit header");
360 // Find LC_UUID in the load commands
361 for (size_t i = 0; i < header.ncmds; i++) {
362 struct load_command lcmd;
364 if (read(fd, &lcmd, sizeof(lcmd)) != sizeof(lcmd)) {
365 SC_log(LOG_ERR, "could not read() load_command");
369 if (lcmd.cmd == LC_UUID) {
370 struct uuid_command uuid_cmd;
372 if (read(fd, uuid_cmd.uuid, sizeof(uuid_t)) != sizeof(uuid_t)) {
373 SC_log(LOG_ERR, "could not read() uuid_command");
377 uuid = [[NSUUID alloc] initWithUUIDBytes:uuid_cmd.uuid];
380 if (lseek(fd, lcmd.cmdsize - sizeof(lcmd), SEEK_CUR) == -1) {
381 SC_log(LOG_ERR, "could not lseek() past load command");
390 #define MAX_NFAT_ARCH 32
392 - (NSArray *)copyUUIDsForFatBinary:(int)fd
394 struct fat_arch * arches = NULL;
395 mach_msg_type_number_t count;
396 struct fat_header hdr;
397 struct host_basic_info hostinfo;
399 NSMutableArray * uuids = nil;
401 // For a fat architecture, we need find the section that is closet to the host cpu
402 bzero(&hostinfo, sizeof(hostinfo));
403 count = HOST_BASIC_INFO_COUNT;
404 kr = host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostinfo, &count);
405 if (kr != KERN_SUCCESS) {
406 SC_log(LOG_ERR, "host_info() failed: %d", kr);
410 if (read(fd, &hdr, sizeof(hdr)) != sizeof(hdr)) {
411 SC_log(LOG_ERR, "could not read() fat_header");
415 // Fat header info are always big-endian
416 hdr.nfat_arch = OSSwapInt32(hdr.nfat_arch);
417 if (hdr.nfat_arch > MAX_NFAT_ARCH) {
418 SC_log(LOG_ERR, "fat_header.nfat_arch (%d) > %d", hdr.nfat_arch, MAX_NFAT_ARCH);
422 arches = (struct fat_arch *)malloc(hdr.nfat_arch * sizeof(struct fat_arch));
423 if (arches == NULL) {
424 // if we could not allocate space for architectures
428 uuids = [[NSMutableArray alloc] init];
430 for (size_t i = 0; i < hdr.nfat_arch; ++i) {
431 struct fat_arch arch;
433 if (read(fd, &arch, sizeof(arch)) != sizeof(arch)) {
434 SC_log(LOG_ERR, "could not read() fat_arch");
437 arch.cputype = (int)OSSwapInt32(arch.cputype);
438 arch.offset = OSSwapInt32(arch.offset);
439 memcpy(&arches[i], &arch, sizeof(arch));
442 for (size_t i = 0; i < hdr.nfat_arch; ++i) {
443 struct fat_arch arch;
446 memcpy(&arch, &arches[i], sizeof(arch));
448 if (arch.offset == 0) {
449 SC_log(LOG_ERR, "invalid offset for arch %d", arch.cputype);
453 if (lseek(fd, arch.offset, SEEK_SET) == -1) {
454 SC_log(LOG_ERR, "could not lseek() to arch %d", arch.cputype);
458 uuid = [self copyUUIDForSingleArch:fd];
460 SC_log(LOG_ERR, "could not get uuid for arch %d", arch.cputype);
464 if (arch.cputype == hostinfo.cpu_type) {
465 [uuids insertObject:uuid atIndex:0];
467 [uuids addObject:uuid];
473 if (arches != NULL) {
476 if (uuids.count == 0) {
482 - (NSArray *)copyUUIDsForExecutable:(const char *)executablePath
486 NSArray * uuids = nil;
488 if (executablePath == NULL) {
492 fd = open(executablePath, O_RDONLY);
494 if (errno != ENOENT) {
495 SC_log(LOG_ERR, "open(\"%s\", O_RDONLY) failed: %s", executablePath, strerror(errno));
501 // Read the magic format to decide which path to take
502 if (read(fd, &magic, sizeof(magic)) != sizeof(magic)) {
503 SC_log(LOG_ERR, "read() no magic format: %s", executablePath);
507 // Rewind to the beginning
508 lseek(fd, 0, SEEK_SET);
511 uuids = [self copyUUIDsForFatBinary:fd];
519 uuid = [self copyUUIDForSingleArch:fd];
521 SC_log(LOG_ERR, "%s: failed to get UUID for single arch", __FUNCTION__);
541 - (void)addWhitelistedPathPolicy:(NSString *)interface forPath:(NSString *)path order:(uint32_t)order
543 NEPolicyCondition * allInterfacesCondition;
544 NEPolicyResult * result;
545 NEPolicyRouteRule * routeRule;
546 NEPolicySession * session;
549 session = _policySessions[interface];
550 if (session == nil) {
551 SC_log(LOG_ERR, "QoS marking policy: %@: no session", interface);
555 // create QoS route rule
556 routeRule = [NEPolicyRouteRule routeRuleWithAction:NEPolicyRouteRuleActionQoSMarking
557 forInterfaceName:interface];
558 result = [NEPolicyResult routeRules:@[ routeRule ]];
560 // create "all interfaces" condition
561 allInterfacesCondition = [NEPolicyCondition allInterfaces];
563 uuids = [self copyUUIDsForExecutable:[path UTF8String]];
564 if ((uuids == nil) || (uuids.count == 0)) {
565 SC_log(LOG_ERR, "QoS marking policy: %@: could not add path \"%@\"",
571 for (NSUUID *uuid in uuids) {
574 NEPolicyCondition * uuidCondition;
576 // create per-app bundleID-->UUID condition
577 uuidCondition = [NEPolicyCondition effectiveApplication:uuid];
579 // create and add policy
580 policy = [[NEPolicy alloc] initWithOrder:order
582 conditions:@[ uuidCondition, allInterfacesCondition ]];
583 policyID = [session addPolicy:policy];
585 SC_log(LOG_NOTICE, "QoS marking policy: %@: %u: whitelist path \"%@\" (%@)",
592 SC_log(LOG_ERR, "QoS marking policy: %@: could not add whitelist policy for path \"%@\" (%@)",
607 - (NSArray *)copyUUIDsForUUIDMapping:(xpc_object_t)mapping
609 NSMutableArray * uuids = nil;
611 if ((mapping != NULL) &&
612 (xpc_get_type(mapping) == XPC_TYPE_ARRAY)) {
613 uuids = [NSMutableArray array];
615 xpc_array_apply(mapping, ^bool(size_t index, xpc_object_t value) {
616 if ((value != NULL) &&
617 (xpc_get_type(value) == XPC_TYPE_UUID)) {
620 uuid = [[NSUUID alloc] initWithUUIDBytes:xpc_uuid_get_bytes(value)];
621 [uuids addObject:uuid];
626 if (uuids.count == 0) {
635 - (NSArray *)copyUUIDsForBundleID:(NSString *)bundleID
638 xpc_object_t uuidsFromHelper;
640 uuidsFromHelper = NEHelperCacheCopyAppUUIDMapping([bundleID UTF8String], NULL);
642 uuids = [self copyUUIDsForUUIDMapping:uuidsFromHelper];
647 - (void)addWhitelistedAppIdentifierPolicy:(NSString *)interface forApp:(NSString *)appBundleID order:(uint32_t)order
649 NEPolicyCondition * allInterfacesCondition;
650 NEPolicyResult * result;
651 NEPolicyRouteRule * routeRule;
652 NEPolicySession * session;
655 if ([appBundleID hasPrefix:@"/"]) {
656 if (_SC_isAppleInternal()) {
657 // special case executable path handling (if internal)
658 [self addWhitelistedPathPolicy:interface forPath:appBundleID order:order];
664 session = _policySessions[interface];
665 if (session == nil) {
666 SC_log(LOG_ERR, "QoS marking policy: %@: no session", interface);
670 // create QoS route rule
671 routeRule = [NEPolicyRouteRule routeRuleWithAction:NEPolicyRouteRuleActionQoSMarking
672 forInterfaceName:interface];
673 result = [NEPolicyResult routeRules:@[ routeRule ]];
675 // create "all interfaces" condition
676 allInterfacesCondition = [NEPolicyCondition allInterfaces];
678 uuids = [self copyUUIDsForBundleID:appBundleID];
679 if ((uuids == nil) || (uuids.count == 0)) {
680 SC_log(LOG_ERR, "QoS marking policy: %@: could not add bundleID \"%@\"",
686 for (NSUUID *uuid in uuids) {
689 NEPolicyCondition * uuidCondition;
691 // create per-app bundleID-->UUID condition
692 uuidCondition = [NEPolicyCondition effectiveApplication:uuid];
694 // create and add policy
695 policy = [[NEPolicy alloc] initWithOrder:order
697 conditions:@[ uuidCondition, allInterfacesCondition ]];
698 policyID = [session addPolicy:policy];
700 SC_log(LOG_NOTICE, "QoS marking policy: %@: %u: whitelist bundleID \"%@\" (%@)",
707 SC_log(LOG_ERR, "QoS marking policy: %@: could not add whitelist policy for bundleID \"%@\" (%@)",
726 _policySessions = [NSMutableDictionary dictionary];
727 _requested = [NSMutableDictionary dictionary];
728 _enabled = [NSMutableDictionary dictionary];
729 _enabledAV = [NSMutableDictionary dictionary];
738 Have QoS Whitelist AppleAVCalls | net.qos.policy. | Interface Interface Interface
739 Profile Enabled Apps(#) Enabled | restricted restrict_avapps | QoS Enabled NECP rules NECP AV rules
740 ======= ======= ========= ============ + ========== =============== + =========== ========== =============
741 1 [N] | 0 0 | [Y] [N] [N]
743 2 [Y] [N] [0] [N] | 0 0 | [N] [N] [N]
744 3 [Y] [N] [0] [Y] | 0 0 | [N] [N] [N]
746 4 [Y] [N] [> 0] [N] | 0 0 | [N] [N] [N]
747 5 [Y] [N] [> 0] [Y] | 0 0 | [N] [N] [N]
749 6 [Y] [Y] [0] [N] | 1 1 | [Y] [N] [N]
750 7 [Y] [Y] [0] [Y] | 1 0 | [Y] [N] [Y]
752 8 [Y] [Y] [> 0] [N] | 1 1 | [Y] [Y] [N]
753 9 [Y] [Y] [> 0] [Y] | 1 0 | [Y] [Y] [Y]
755 Notes (QoSMarking policy) :
756 * If "QoSEnabled" is not present, assume "Y"
757 * If "QoSMarkingAppleAudioVideoCalls" is not present, assume "Y"
758 * If "QoSMarkingWhitelistedAppIdentifiers" is not present (or empty), assume no whitelisted applications
761 * net.qos.policy.restricted should be "1" when NECP policies are present
762 * net.qos.policy.restrict_avapps should be "1" when "QoSMarkingAppleAudioVideoCalls" is "N"
766 - (void)updatePolicy:(NSDictionary *)reqPolicy forInterface:(NSString *)interface
768 // currently enabled settings
769 NSDictionary * nowPolicy = _enabled[interface];
770 BOOL nowDisabled = false;
771 BOOL nowEnabled = false;
772 BOOL nowAppleAV = false;
774 // requested settings
775 BOOL reqDefault = false;
776 BOOL reqDisabled = false;
777 BOOL reqEnabled = false;
778 BOOL reqAppleAV = false;
780 if (nowPolicy != nil) {
781 if ([self qosMarkingIsEnabled:nowPolicy]) {
782 // if we have an enabled QoS marking policy
785 // if we have a disabled QoS marking policy
789 nowAppleAV = [self qosMarkingIsAppleAudioVideoCallsEnabled:nowPolicy];
792 if (reqPolicy != nil) {
793 if ([self qosMarkingIsEnabled:reqPolicy]) {
794 // if QoS marking policy requested
797 // if QoS marking policy present (but disabled)
801 reqAppleAV = [self qosMarkingIsAppleAudioVideoCallsEnabled:reqPolicy];
806 if ((!nowEnabled && reqDefault ) ||
807 ( nowEnabled != reqEnabled ) ||
808 ( nowDisabled != reqDisabled) ||
809 ( nowEnabled && reqEnabled && ![nowPolicy isEqual:reqPolicy])) {
813 // if we are transitioning to enabled or we have a policy
814 // change, ensure that we rebuild policies
817 if ((nowPolicy != nil) && (reqPolicy == nil)) {
818 SC_log(LOG_NOTICE, "QoS marking policy: %@: remove", interface);
821 // if QoS marking was enabled (for this interface), close session
822 [_policySessions removeObjectForKey:interface];
824 // QoS marking policy for this interface is no longer enabled
825 [_enabled removeObjectForKey:interface];
826 [_enabledAV removeObjectForKey:interface];
829 // update QoSMarking enabled (per-interface)
830 s = socket(AF_INET, SOCK_DGRAM, 0);
832 BOOL enable = reqEnabled || reqDefault;
834 SC_log(LOG_NOTICE, "QoS marking policy: %@: %s%s",
836 enable ? "enable" : "disable",
837 reqDefault ? " (default)" : "");
838 qosMarkingSetEnabled(s, interface.UTF8String, enable);
841 SC_log(LOG_ERR, "socket() failed: %s", strerror(errno));
850 if (nowAppleAV != reqAppleAV) {
854 curAppIDs = [self qosMarkingWhitelistedAppIdentifiers:nowPolicy];
855 reqAppIDs = [self qosMarkingWhitelistedAppIdentifiers:reqPolicy];
856 if (![curAppIDs isEqual:reqAppIDs]) {
863 NEPolicySession * session;
865 // QoS marking being (or still) enabled for this interface
866 if (_enabled.count == 0) {
867 // if we now have a profile requiring us to check NECP policies
868 qosMarkingSetHavePolicies(true);
871 // the QoS marking policy for this interface is now enabled
872 _enabled[interface] = reqPolicy;
874 SC_log(LOG_NOTICE, "QoS marking policy: %@: %s",
876 nowEnabled ? "update" : "add");
878 // prepare [new] per-interface NECP session
880 session = _policySessions[interface];
881 if ((session == nil) && ((reqAppIDs.count > 0) || reqAppleAV)) {
882 // if we need to add NECP policies
883 session = [self createPolicySession];
884 if (session != nil) {
885 _policySessions[interface] = session;
887 SC_log(LOG_ERR, "%@: failed to create policy session", interface);
891 // zap any previously stored policies
892 if (session != nil) {
893 ok = [session removeAllPolicies];
895 SC_log(LOG_ERR, "%@: could not remove policies", interface);
899 // if needed, add policies for any whitelisted applications
900 if ((session != nil) && (reqAppIDs.count > 0)) {
901 order = QOS_MARKING_PRIORITY_BLOCK_APPS;
902 for (NSString *app in reqAppIDs) {
903 [self addWhitelistedAppIdentifierPolicy:interface forApp:app order:order++];
908 if (_enabledAV.count == 0) {
909 // if we are enabling the marking of Apple AV application
910 // then we do not want to restrict handling of traffic that
911 // cannot be handled by NECP
912 qosMarkingSetRestrictAVApps(false);
915 // the QoS [AV] marking policy for this interface is now enabled
916 _enabledAV[interface] = reqPolicy;
918 if (session != nil) {
919 // if needed, add Apple audio/video application policies
921 order = QOS_MARKING_PRIORITY_BLOCK_AV_APPS;
922 for (NSString *app in qosMarkingAudioVideoCalls_bundleIDs) {
923 [self addWhitelistedAppIdentifierPolicy:interface forApp:app order:order++];
926 order = QOS_MARKING_PRIORITY_BLOCK_AV_PATHS;
927 for (NSString *path in qosMarkingAudioVideoCalls_executablePaths) {
928 [self addWhitelistedPathPolicy:interface forPath:path order:order++];
932 // the QoS [AV] marking policy for this interface is no longer enabled
933 [_enabledAV removeObjectForKey:interface];
935 if (_enabledAV.count == 0) {
936 // if we do not (no longer want to) be marking AV then restrict
937 // handling traffic that cannot be handled by NECP
938 qosMarkingSetRestrictAVApps(true);
942 if (session != nil) {
943 ok = [session apply];
945 SC_log(LOG_ERR, "%@: could not apply new policies", interface);
951 // Restore "default" state if no policies
952 if (_enabled.count == 0) {
953 qosMarkingSetRestrictAVApps(false);
954 qosMarkingSetHavePolicies(false);
960 #pragma mark Update QoSMarking Policy Configuration per [SC] changes
963 + (QoSMarkingController *)sharedController
965 static QoSMarkingController * controller;
966 static dispatch_once_t once;
968 dispatch_once(&once, ^{
969 controller = [[QoSMarkingController alloc] init];
976 - (void)setInterfaces:(NSArray *)newInterfaces
978 NSArray * curInterfaces;
981 s = socket(AF_INET, SOCK_DGRAM, 0);
983 SC_log(LOG_ERR, "socket() failed: %s", strerror(errno));
987 curInterfaces = _interfaces;
988 _interfaces = newInterfaces;
990 for (NSString *interface in newInterfaces) {
991 if (!supportsQoSMarking(s, interface.UTF8String)) {
992 // skip interfaces that do not support QoS marking
996 if (![curInterfaces containsObject:interface]) {
997 NSDictionary * policy;
1000 policy = _requested[interface];
1001 [_requested removeObjectForKey:interface]; // make this look like a fresh "add"
1002 [self setPolicy:policy forInterface:interface]; // and "set" the new policy
1011 - (void)setPolicy:(NSDictionary *)policy forInterface:(NSString *)interface
1013 if (policy != nil) {
1014 if ([_interfaces containsObject:interface]) {
1015 // set (update) per-interface policy
1016 [self updatePolicy:policy forInterface:interface];
1019 // track policy for future changes
1020 [_requested setObject:policy forKey:interface];
1022 // remove (update) per-interface policy
1023 [self updatePolicy:policy forInterface:interface];
1025 // track policy for future changes
1026 [_requested removeObjectForKey:interface];
1036 #pragma mark Update QoS Marking Policy Plugin
1040 * Function: parse_component
1042 * Given a string 'key' and a string prefix 'prefix',
1043 * return the next component in the slash '/' separated
1047 * 1. key = "a/b/c" prefix = "a/"
1049 * 2. key = "a/b/c" prefix = "a/b/"
1052 static CF_RETURNS_RETAINED CFStringRef
1053 parse_component(CFStringRef key, CFStringRef prefix)
1055 CFMutableStringRef comp;
1058 if (!CFStringHasPrefix(key, prefix)) {
1061 comp = CFStringCreateMutableCopy(NULL, 0, key);
1062 CFStringDelete(comp, CFRangeMake(0, CFStringGetLength(prefix)));
1063 range = CFStringFind(comp, CFSTR("/"), 0);
1064 if (range.location == kCFNotFound) {
1067 range.length = CFStringGetLength(comp) - range.location;
1068 CFStringDelete(comp, range);
1075 qosMarkingConfigChangedCallback(SCDynamicStoreRef store, CFArrayRef changedKeys, void *arg)
1077 os_activity_t activity;
1078 CFDictionaryRef changes;
1080 static CFStringRef prefix = NULL;
1082 activity = os_activity_create("processing QoS marking configuration changes",
1083 OS_ACTIVITY_CURRENT,
1084 OS_ACTIVITY_FLAG_DEFAULT);
1085 os_activity_scope(activity);
1087 if (prefix == NULL) {
1088 prefix = SCDynamicStoreKeyCreate(NULL,
1090 kSCDynamicStoreDomainSetup,
1095 changes = SCDynamicStoreCopyMultiple(store, changedKeys, NULL);
1097 n = CFArrayGetCount(changedKeys);
1098 for (CFIndex i = 0; i < n; i++) {
1101 key = CFArrayGetValueAtIndex(changedKeys, i);
1103 if (CFEqual(key, interfacesKey)) {
1104 CFDictionaryRef info;
1106 info = (changes != NULL) ? CFDictionaryGetValue(changes, key) : NULL;
1107 if (isA_CFDictionary(info) != NULL) {
1108 CFArrayRef interfaces;
1110 interfaces = CFDictionaryGetValue(info, kSCPropNetInterfaces);
1111 if (isA_CFArray(interfaces)) {
1113 QoSMarkingController * controller;
1115 controller = [QoSMarkingController sharedController];
1116 [controller setInterfaces:(__bridge NSArray *)interfaces];
1121 CFStringRef interface;
1123 interface = parse_component(key, prefix);
1124 if (interface != NULL) {
1125 CFDictionaryRef policy;
1127 policy = (changes != NULL) ? CFDictionaryGetValue(changes, key) : NULL;
1129 QoSMarkingController * controller;
1131 controller = [QoSMarkingController sharedController];
1132 [controller setPolicy:(__bridge NSDictionary *)policy
1133 forInterface:(__bridge NSString *)interface];
1135 CFRelease(interface);
1140 if (changes != NULL) {
1150 load_QoSMarking(CFBundleRef bundle, Boolean bundleVerbose)
1152 CFDictionaryRef dict;
1154 CFMutableArrayRef keys;
1156 CFMutableArrayRef patterns;
1157 CFRunLoopSourceRef rls;
1158 SCDynamicStoreRef store;
1160 SC_log(LOG_DEBUG, "load() called");
1161 SC_log(LOG_DEBUG, " bundle ID = %@", CFBundleGetIdentifier(bundle));
1163 // initialize a few globals
1164 interfacesKey = SCDynamicStoreKeyCreateNetworkInterface(NULL,
1165 kSCDynamicStoreDomainState);
1167 dict = CFBundleGetInfoDictionary(bundle);
1168 if (isA_CFDictionary(dict)) {
1169 CFArrayRef bundleIDs;
1172 bundleIDs = CFDictionaryGetValue(dict, kQoSMarkingBundleIdentifiersAppleAudioVideoCallsKey);
1173 bundleIDs = isA_CFArray(bundleIDs);
1174 qosMarkingAudioVideoCalls_bundleIDs = (__bridge NSArray *)bundleIDs;
1176 paths = CFDictionaryGetValue(dict, kQoSMarkingExecutablePathsAppleAudioVideoCallsKey);
1177 paths = isA_CFArray(paths);
1178 qosMarkingAudioVideoCalls_executablePaths = (__bridge NSArray *)paths;
1181 // open a "configd" store to allow cache updates
1182 store = SCDynamicStoreCreate(NULL,
1183 CFSTR("QoS Marking Configuraton plug-in"),
1184 qosMarkingConfigChangedCallback,
1186 if (store == NULL) {
1187 SC_log(LOG_ERR, "SCDynamicStoreCreate() failed: %s", SCErrorString(SCError()));
1191 // establish notification keys and patterns
1192 keys = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
1193 patterns = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
1195 // ...watch for a change in the list of network interfaces
1196 CFArrayAppendValue(keys, interfacesKey);
1198 // ...watch for (per-interface) QoS marking policy changes
1199 key = SCDynamicStoreKeyCreateNetworkInterfaceEntity(NULL,
1200 kSCDynamicStoreDomainSetup,
1202 kSCEntNetQoSMarkingPolicy);
1203 CFArrayAppendValue(patterns, key);
1206 // register the keys/patterns
1207 ok = SCDynamicStoreSetNotificationKeys(store, keys, patterns);
1209 CFRelease(patterns);
1211 SC_log(LOG_NOTICE, "SCDynamicStoreSetNotificationKeys() failed: %s",
1212 SCErrorString(SCError()));
1216 rls = SCDynamicStoreCreateRunLoopSource(NULL, store, 0);
1218 SC_log(LOG_NOTICE, "SCDynamicStoreCreateRunLoopSource() failed: %s",
1219 SCErrorString(SCError()));
1223 CFRunLoopAddSource(CFRunLoopGetCurrent(), rls, kCFRunLoopDefaultMode);
1228 if (store != NULL) CFRelease(store);
1237 #pragma mark Standalone test code
1241 main(int argc, char **argv)
1244 _sc_verbose = (argc > 1) ? TRUE : FALSE;
1246 load_QoSMarking(CFBundleGetMainBundle(), (argc > 1) ? TRUE : FALSE);