2 * Copyright (c) 2016-2019 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 <os/overflow.h>
39 #include <sys/ioctl.h>
40 #include <sys/kern_control.h>
41 #include <sys/socket.h>
42 #include <sys/sockio.h>
43 #include <sys/sys_domain.h>
45 #define SC_LOG_HANDLE __log_QoSMarking
46 #include <SystemConfiguration/SystemConfiguration.h>
47 #include <SystemConfiguration/SCPrivate.h>
48 #include <SystemConfiguration/SCValidation.h>
50 #import <Foundation/Foundation.h>
51 #import <NetworkExtension/NEPolicySession.h>
52 #import <NEHelperClient.h>
54 // define the QoSMarking.bundle Info.plist key containing [application] bundleIDs to be white-listed
55 #define kQoSMarkingBundleIdentifiersAppleAudioVideoCallsKey CFSTR("QoSMarking_AppleAudioVideoCalls_BundleIDs")
57 // define the QoSMarking.bundle Info.plist key containing paths to be white-listed
58 #define kQoSMarkingExecutablePathsAppleAudioVideoCallsKey CFSTR("QoSMarking_AppleAudioVideoCalls_ExecutablePaths")
60 // define the starting "order" value for any QoS Marking NEPolicy rules
61 #define QOS_MARKING_PRIORITY_BLOCK_AV_APPS 1000
62 #define QOS_MARKING_PRIORITY_BLOCK_AV_PATHS 1500
63 #define QOS_MARKING_PRIORITY_BLOCK_APPS 2000
66 static CFStringRef interfacesKey = NULL;
67 static NSArray * qosMarkingAudioVideoCalls_bundleIDs = nil;
68 static NSArray * qosMarkingAudioVideoCalls_executablePaths = nil;
75 __private_extern__ os_log_t
76 __log_QoSMarking(void)
78 static os_log_t log = NULL;
81 log = os_log_create("com.apple.SystemConfiguration", "QoSMarking");
89 #pragma mark QoSMarking support (system)
93 qosMarkingSetPolicyRestriction(const char *ctl, BOOL yn)
95 int restricted = yn ? 1 : 0;
98 ret = sysctlbyname(ctl, NULL, 0, &restricted, sizeof(restricted));
100 SC_log(LOG_NOTICE, "QoS marking policy: sysctl %s=%d", ctl, restricted);
102 if (errno != ENOENT) {
103 SC_log(LOG_ERR, "sysctlbyname() failed: %s", strerror(errno));
112 qosMarkingSetHavePolicies(BOOL havePolicies)
114 qosMarkingSetPolicyRestriction("net.qos.policy.restricted", havePolicies);
120 qosMarkingSetRestrictAVApps(BOOL restrictApps)
122 qosMarkingSetPolicyRestriction("net.qos.policy.restrict_avapps", restrictApps);
128 #pragma mark QoSMarking support (per-interface)
132 supportsQoSMarking(int s, const char *ifname)
136 memset(&ifr, 0, sizeof(ifr));
137 strlcpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
138 if (ioctl(s, SIOCGIFTYPE, (caddr_t)&ifr) == -1) {
139 SC_log(LOG_NOTICE, "%s: ioctl(SIOCGIFTYPE) failed: %s",
142 ifr.ifr_type.ift_type = 0;
143 ifr.ifr_type.ift_family = IFRTYPE_FAMILY_ANY;
144 ifr.ifr_type.ift_subfamily = IFRTYPE_SUBFAMILY_ANY;
147 #if !TARGET_OS_IPHONE
148 if (ifr.ifr_type.ift_family == IFRTYPE_FAMILY_ETHERNET) {
151 #else // !TARGET_OS_IPHONE
152 if ((ifr.ifr_type.ift_family == IFRTYPE_FAMILY_ETHERNET) &&
153 (ifr.ifr_type.ift_subfamily == IFRTYPE_SUBFAMILY_WIFI)) {
156 #endif // !TARGET_OS_IPHONE
163 qosMarkingSetEnabled(int s, const char *ifname, BOOL enabled)
168 memset(&ifr, 0, sizeof(ifr));
169 strlcpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
170 ifr.ifr_qosmarking_enabled = enabled ? 1 : 0;
171 ret = ioctl(s, SIOCSQOSMARKINGENABLED, &ifr);
173 SC_log(LOG_ERR, "%s: ioctl(SIOCSQOSMARKINGENABLED) failed: %s",
183 #pragma mark QoSMarking Policy support
186 @interface QoSMarkingController : NSObject
188 + (QoSMarkingController *)sharedController;
189 - (void)setInterfaces:(NSArray *)interfaces;
190 - (void)setPolicy:(NSDictionary *)policy forInterface:(NSString *)interface;
195 @interface QoSMarkingController()
199 * An array of network interface names on the system/device
201 @property (nonatomic) NSArray * interfaces;
205 * A dictionary for the maintaining the QoS marking policies.
207 * Key : interface [name]
208 * Value : the NEPolicySession* for the interface
210 @property (nonatomic) NSMutableDictionary * policySessions;
214 * A dictionary for the tracking the QoS marking policies.
216 * Key : interface [name]
217 * Value : the [requested] NSDictionary* "policy" for the interface
219 @property (nonatomic) NSMutableDictionary * requested;
223 * Dictionaries for tracking the "enabled" interfaces with QoS [AV]
226 * Key : interface [name]
227 * Value : the enabled NSDictionary* "policy" for the interface
229 @property (nonatomic) NSMutableDictionary * enabled;
230 @property (nonatomic) NSMutableDictionary * enabledAV;
235 @implementation QoSMarkingController
237 - (NEPolicySession *)createPolicySession
239 return [[NEPolicySession alloc] init];
246 - (BOOL)qosMarkingPolicyEnabled:(NSDictionary *)policy forKey:(NSString *)key
250 enabled = policy[key];
251 if (enabled != nil) {
252 if (![enabled isKindOfClass:[NSNumber class]]) {
253 SC_log(LOG_ERR, "%@ not valid", key);
257 // assume "enabled" if no key
261 return enabled.boolValue;
265 - (BOOL)qosMarkingIsEnabled:(NSDictionary *)policy
267 return [self qosMarkingPolicyEnabled:policy
268 forKey:(NSString *)kSCPropNetQoSMarkingEnabled];
272 - (BOOL)qosMarkingIsAppleAudioVideoCallsEnabled:(NSDictionary *)policy
274 return [self qosMarkingPolicyEnabled:policy
275 forKey:(NSString *)kSCPropNetQoSMarkingAppleAudioVideoCalls];
279 - (NSArray *)qosMarkingWhitelistedAppIdentifiers:(NSDictionary *)policy
283 appIDs = policy[(NSString *)kSCPropNetQoSMarkingWhitelistedAppIdentifiers];
284 if ((appIDs != nil) && ![appIDs isKindOfClass:[NSArray class]]) {
285 SC_log(LOG_ERR, "QoSMarkingWhitelistedAppIdentifier list not valid");
289 for (NSString *appID in appIDs) {
290 if ((appID != nil) &&
291 (![appID isKindOfClass:[NSString class]] || (appID.length == 0))) {
292 SC_log(LOG_ERR, "QoSMarkingWhitelistedAppIdentifier not valid");
304 - (NSUUID *)copyUUIDForSingleArch:(int)fd
307 struct mach_header header;
310 if (read(fd, &header, sizeof(header)) != sizeof(header)) {
314 // Go past the 64 bit header if we have a 64 arch
315 if (header.magic == MH_MAGIC_64) {
316 if (lseek(fd, sizeof(uint32_t), SEEK_CUR) == -1) {
317 SC_log(LOG_ERR, "could not lseek() past 64 bit header");
322 if(os_mul_overflow((uint64_t)header.ncmds, sizeof(struct load_command), &bytes) ||
323 (bytes > header.sizeofcmds)) {
324 SC_log(LOG_ERR, "mach_header error with \".ncmds\" (%llu), \".sizeofcmds\" (%llu)",
325 (uint64_t)header.ncmds,
326 (uint64_t)header.sizeofcmds);
330 // Find LC_UUID in the load commands
331 for (size_t i = 0; i < header.ncmds; i++) {
332 struct load_command lcmd;
334 if (read(fd, &lcmd, sizeof(lcmd)) != sizeof(lcmd)) {
335 SC_log(LOG_ERR, "could not read() load_command");
339 if (lcmd.cmd == LC_UUID) {
340 struct uuid_command uuid_cmd;
342 if (read(fd, uuid_cmd.uuid, sizeof(uuid_t)) != sizeof(uuid_t)) {
343 SC_log(LOG_ERR, "could not read() uuid_command");
347 uuid = [[NSUUID alloc] initWithUUIDBytes:uuid_cmd.uuid];
350 if (lseek(fd, lcmd.cmdsize - sizeof(lcmd), SEEK_CUR) == -1) {
351 SC_log(LOG_ERR, "could not lseek() past load command");
360 #define MAX_NFAT_ARCH 32
362 - (NSArray *)copyUUIDsForFatBinary:(int)fd
364 struct fat_arch * arches = NULL;
365 mach_msg_type_number_t count;
366 struct fat_header hdr;
367 struct host_basic_info hostinfo;
369 NSMutableArray * uuids = nil;
371 // For a fat architecture, we need find the section that is closet to the host cpu
372 memset(&hostinfo, 0, sizeof(hostinfo));
373 count = HOST_BASIC_INFO_COUNT;
374 kr = host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostinfo, &count);
375 if (kr != KERN_SUCCESS) {
376 SC_log(LOG_ERR, "host_info() failed: %d", kr);
380 if (read(fd, &hdr, sizeof(hdr)) != sizeof(hdr)) {
381 SC_log(LOG_ERR, "could not read() fat_header");
385 // Fat header info are always big-endian
386 hdr.nfat_arch = OSSwapInt32(hdr.nfat_arch);
387 if (hdr.nfat_arch > MAX_NFAT_ARCH) {
388 SC_log(LOG_ERR, "fat_header.nfat_arch (%d) > %d", hdr.nfat_arch, MAX_NFAT_ARCH);
392 arches = (struct fat_arch *)malloc(hdr.nfat_arch * sizeof(struct fat_arch));
393 if (arches == NULL) {
394 // if we could not allocate space for architectures
398 uuids = [[NSMutableArray alloc] init];
400 for (size_t i = 0; i < hdr.nfat_arch; ++i) {
401 struct fat_arch arch;
403 if (read(fd, &arch, sizeof(arch)) != sizeof(arch)) {
404 SC_log(LOG_ERR, "could not read() fat_arch");
407 arch.cputype = (int)OSSwapInt32(arch.cputype);
408 arch.offset = OSSwapInt32(arch.offset);
409 memcpy(&arches[i], &arch, sizeof(arch));
412 for (size_t i = 0; i < hdr.nfat_arch; ++i) {
413 struct fat_arch arch;
416 memcpy(&arch, &arches[i], sizeof(arch));
418 if (arch.offset == 0) {
419 SC_log(LOG_ERR, "invalid offset for arch %d", arch.cputype);
423 if (lseek(fd, arch.offset, SEEK_SET) == -1) {
424 SC_log(LOG_ERR, "could not lseek() to arch %d", arch.cputype);
428 uuid = [self copyUUIDForSingleArch:fd];
430 SC_log(LOG_ERR, "could not get uuid for arch %d", arch.cputype);
434 if (arch.cputype == hostinfo.cpu_type) {
435 [uuids insertObject:uuid atIndex:0];
437 [uuids addObject:uuid];
443 if (arches != NULL) {
446 if (uuids.count == 0) {
452 - (NSArray *)copyUUIDsForExecutable:(const char *)executablePath
456 NSArray * uuids = nil;
458 if (executablePath == NULL) {
462 fd = open(executablePath, O_RDONLY);
464 if (errno != ENOENT) {
465 SC_log(LOG_ERR, "open(\"%s\", O_RDONLY) failed: %s", executablePath, strerror(errno));
471 // Read the magic format to decide which path to take
472 if (read(fd, &magic, sizeof(magic)) != sizeof(magic)) {
473 SC_log(LOG_ERR, "read() no magic format: %s", executablePath);
477 // Rewind to the beginning
478 lseek(fd, 0, SEEK_SET);
481 uuids = [self copyUUIDsForFatBinary:fd];
489 uuid = [self copyUUIDForSingleArch:fd];
491 SC_log(LOG_ERR, "%s: failed to get UUID for single arch", __FUNCTION__);
511 - (void)addWhitelistedPathPolicy:(NSString *)interface forPath:(NSString *)path order:(uint32_t)order
513 NEPolicyCondition * allInterfacesCondition;
514 NEPolicyResult * result;
515 NEPolicyRouteRule * routeRule;
516 NEPolicySession * session;
519 session = _policySessions[interface];
520 if (session == nil) {
521 SC_log(LOG_ERR, "QoS marking policy: %@: no session", interface);
525 // create QoS route rule
526 routeRule = [NEPolicyRouteRule routeRuleWithAction:NEPolicyRouteRuleActionQoSMarking
527 forInterfaceName:interface];
528 result = [NEPolicyResult routeRules:@[ routeRule ]];
530 // create "all interfaces" condition
531 allInterfacesCondition = [NEPolicyCondition allInterfaces];
533 uuids = [self copyUUIDsForExecutable:[path UTF8String]];
534 if ((uuids == nil) || (uuids.count == 0)) {
535 SC_log(LOG_ERR, "QoS marking policy: %@: could not add path \"%@\"",
541 for (NSUUID *uuid in uuids) {
544 NEPolicyCondition * uuidCondition;
546 // create per-app bundleID-->UUID condition
547 uuidCondition = [NEPolicyCondition effectiveApplication:uuid];
549 // create and add policy
550 policy = [[NEPolicy alloc] initWithOrder:order
552 conditions:@[ uuidCondition, allInterfacesCondition ]];
553 policyID = [session addPolicy:policy];
555 SC_log(LOG_NOTICE, "QoS marking policy: %@: %u: whitelist path \"%@\" (%@)",
562 SC_log(LOG_ERR, "QoS marking policy: %@: could not add whitelist policy for path \"%@\" (%@)",
577 - (NSArray *)copyUUIDsForUUIDMapping:(xpc_object_t)mapping
579 NSMutableArray * uuids = nil;
581 if ((mapping != NULL) &&
582 (xpc_get_type(mapping) == XPC_TYPE_ARRAY)) {
583 uuids = [NSMutableArray array];
585 xpc_array_apply(mapping, ^bool(size_t index, xpc_object_t value) {
586 #pragma unused(index)
587 if ((value != NULL) &&
588 (xpc_get_type(value) == XPC_TYPE_UUID)) {
591 uuid = [[NSUUID alloc] initWithUUIDBytes:xpc_uuid_get_bytes(value)];
592 [uuids addObject:uuid];
597 if (uuids.count == 0) {
606 - (NSArray *)copyUUIDsForBundleID:(NSString *)bundleID
609 xpc_object_t uuidsFromHelper;
611 uuidsFromHelper = NEHelperCacheCopyAppUUIDMapping([bundleID UTF8String], NULL);
613 uuids = [self copyUUIDsForUUIDMapping:uuidsFromHelper];
618 - (void)addWhitelistedAppIdentifierPolicy:(NSString *)interface forApp:(NSString *)appBundleID order:(uint32_t)order
620 NEPolicyCondition * allInterfacesCondition;
621 NEPolicyResult * result;
622 NEPolicyRouteRule * routeRule;
623 NEPolicySession * session;
626 if ([appBundleID hasPrefix:@"/"]) {
627 if (_SC_isAppleInternal()) {
628 // special case executable path handling (if internal)
629 [self addWhitelistedPathPolicy:interface forPath:appBundleID order:order];
635 session = _policySessions[interface];
636 if (session == nil) {
637 SC_log(LOG_ERR, "QoS marking policy: %@: no session", interface);
641 // create QoS route rule
642 routeRule = [NEPolicyRouteRule routeRuleWithAction:NEPolicyRouteRuleActionQoSMarking
643 forInterfaceName:interface];
644 result = [NEPolicyResult routeRules:@[ routeRule ]];
646 // create "all interfaces" condition
647 allInterfacesCondition = [NEPolicyCondition allInterfaces];
649 uuids = [self copyUUIDsForBundleID:appBundleID];
650 if ((uuids == nil) || (uuids.count == 0)) {
651 SC_log(LOG_ERR, "QoS marking policy: %@: could not add bundleID \"%@\"",
657 for (NSUUID *uuid in uuids) {
660 NEPolicyCondition * uuidCondition;
662 // create per-app bundleID-->UUID condition
663 uuidCondition = [NEPolicyCondition effectiveApplication:uuid];
665 // create and add policy
666 policy = [[NEPolicy alloc] initWithOrder:order
668 conditions:@[ uuidCondition, allInterfacesCondition ]];
669 policyID = [session addPolicy:policy];
671 SC_log(LOG_NOTICE, "QoS marking policy: %@: %u: whitelist bundleID \"%@\" (%@)",
678 SC_log(LOG_ERR, "QoS marking policy: %@: could not add whitelist policy for bundleID \"%@\" (%@)",
697 _policySessions = [NSMutableDictionary dictionary];
698 _requested = [NSMutableDictionary dictionary];
699 _enabled = [NSMutableDictionary dictionary];
700 _enabledAV = [NSMutableDictionary dictionary];
709 Have QoS Whitelist AppleAVCalls | net.qos.policy. | Interface Interface Interface
710 Profile Enabled Apps(#) Enabled | restricted restrict_avapps | QoS Enabled NECP rules NECP AV rules
711 ======= ======= ========= ============ + ========== =============== + =========== ========== =============
712 1 [N] | 0 0 | [Y] [N] [N]
714 2 [Y] [N] [0] [N] | 0 0 | [N] [N] [N]
715 3 [Y] [N] [0] [Y] | 0 0 | [N] [N] [N]
717 4 [Y] [N] [> 0] [N] | 0 0 | [N] [N] [N]
718 5 [Y] [N] [> 0] [Y] | 0 0 | [N] [N] [N]
720 6 [Y] [Y] [0] [N] | 1 1 | [Y] [N] [N]
721 7 [Y] [Y] [0] [Y] | 1 0 | [Y] [N] [Y]
723 8 [Y] [Y] [> 0] [N] | 1 1 | [Y] [Y] [N]
724 9 [Y] [Y] [> 0] [Y] | 1 0 | [Y] [Y] [Y]
726 Notes (QoSMarking policy) :
727 * If "QoSEnabled" is not present, assume "Y"
728 * If "QoSMarkingAppleAudioVideoCalls" is not present, assume "Y"
729 * If "QoSMarkingWhitelistedAppIdentifiers" is not present (or empty), assume no whitelisted applications
732 * net.qos.policy.restricted should be "1" when NECP policies are present
733 * net.qos.policy.restrict_avapps should be "1" when "QoSMarkingAppleAudioVideoCalls" is "N"
737 - (void)updatePolicy:(NSDictionary *)reqPolicy forInterface:(NSString *)interface
739 // currently enabled settings
740 NSDictionary * nowPolicy = _enabled[interface];
741 BOOL nowDisabled = false;
742 BOOL nowEnabled = false;
743 BOOL nowAppleAV = false;
745 // requested settings
746 BOOL reqDefault = false;
747 BOOL reqDisabled = false;
748 BOOL reqEnabled = false;
749 BOOL reqAppleAV = false;
751 if (nowPolicy != nil) {
752 if ([self qosMarkingIsEnabled:nowPolicy]) {
753 // if we have an enabled QoS marking policy
756 // if we have a disabled QoS marking policy
760 nowAppleAV = [self qosMarkingIsAppleAudioVideoCallsEnabled:nowPolicy];
763 if (reqPolicy != nil) {
764 if ([self qosMarkingIsEnabled:reqPolicy]) {
765 // if QoS marking policy requested
768 // if QoS marking policy present (but disabled)
772 reqAppleAV = [self qosMarkingIsAppleAudioVideoCallsEnabled:reqPolicy];
777 if ((!nowEnabled && reqDefault ) ||
778 ( nowEnabled != reqEnabled ) ||
779 ( nowDisabled != reqDisabled) ||
780 ( nowEnabled && reqEnabled && ![nowPolicy isEqual:reqPolicy])) {
784 // if we are transitioning to enabled or we have a policy
785 // change, ensure that we rebuild policies
788 if ((nowPolicy != nil) && (reqPolicy == nil)) {
789 SC_log(LOG_NOTICE, "QoS marking policy: %@: remove", interface);
792 // if QoS marking was enabled (for this interface), close session
793 [_policySessions removeObjectForKey:interface];
795 // QoS marking policy for this interface is no longer enabled
796 [_enabled removeObjectForKey:interface];
797 [_enabledAV removeObjectForKey:interface];
800 // update QoSMarking enabled (per-interface)
801 s = socket(AF_INET, SOCK_DGRAM, 0);
803 BOOL enable = reqEnabled || reqDefault;
805 SC_log(LOG_NOTICE, "QoS marking policy: %@: %s%s",
807 enable ? "enable" : "disable",
808 reqDefault ? " (default)" : "");
809 qosMarkingSetEnabled(s, interface.UTF8String, enable);
812 SC_log(LOG_ERR, "socket() failed: %s", strerror(errno));
821 if (nowAppleAV != reqAppleAV) {
825 curAppIDs = [self qosMarkingWhitelistedAppIdentifiers:nowPolicy];
826 reqAppIDs = [self qosMarkingWhitelistedAppIdentifiers:reqPolicy];
827 if (![curAppIDs isEqual:reqAppIDs]) {
834 NEPolicySession * session;
836 // QoS marking being (or still) enabled for this interface
837 if (_enabled.count == 0) {
838 // if we now have a profile requiring us to check NECP policies
839 qosMarkingSetHavePolicies(true);
842 // the QoS marking policy for this interface is now enabled
843 _enabled[interface] = reqPolicy;
845 SC_log(LOG_NOTICE, "QoS marking policy: %@: %s",
847 nowEnabled ? "update" : "add");
849 // prepare [new] per-interface NECP session
851 session = _policySessions[interface];
852 if ((session == nil) && ((reqAppIDs.count > 0) || reqAppleAV)) {
853 // if we need to add NECP policies
854 session = [self createPolicySession];
855 if (session != nil) {
856 _policySessions[interface] = session;
858 SC_log(LOG_ERR, "%@: failed to create policy session", interface);
862 // zap any previously stored policies
863 if (session != nil) {
864 ok = [session removeAllPolicies];
866 SC_log(LOG_ERR, "%@: could not remove policies", interface);
870 // if needed, add policies for any whitelisted applications
871 if ((session != nil) && (reqAppIDs.count > 0)) {
872 order = QOS_MARKING_PRIORITY_BLOCK_APPS;
873 for (NSString *app in reqAppIDs) {
874 [self addWhitelistedAppIdentifierPolicy:interface forApp:app order:order++];
879 if (_enabledAV.count == 0) {
880 // if we are enabling the marking of Apple AV application
881 // then we do not want to restrict handling of traffic that
882 // cannot be handled by NECP
883 qosMarkingSetRestrictAVApps(false);
886 // the QoS [AV] marking policy for this interface is now enabled
887 _enabledAV[interface] = reqPolicy;
889 if (session != nil) {
890 // if needed, add Apple audio/video application policies
892 order = QOS_MARKING_PRIORITY_BLOCK_AV_APPS;
893 for (NSString *app in qosMarkingAudioVideoCalls_bundleIDs) {
894 [self addWhitelistedAppIdentifierPolicy:interface forApp:app order:order++];
897 order = QOS_MARKING_PRIORITY_BLOCK_AV_PATHS;
898 for (NSString *path in qosMarkingAudioVideoCalls_executablePaths) {
899 [self addWhitelistedPathPolicy:interface forPath:path order:order++];
903 // the QoS [AV] marking policy for this interface is no longer enabled
904 [_enabledAV removeObjectForKey:interface];
906 if (_enabledAV.count == 0) {
907 // if we do not (no longer want to) be marking AV then restrict
908 // handling traffic that cannot be handled by NECP
909 qosMarkingSetRestrictAVApps(true);
913 if (session != nil) {
914 ok = [session apply];
916 SC_log(LOG_ERR, "%@: could not apply new policies", interface);
922 // Restore "default" state if no policies
923 if (_enabled.count == 0) {
924 qosMarkingSetRestrictAVApps(false);
925 qosMarkingSetHavePolicies(false);
931 #pragma mark Update QoSMarking Policy Configuration per [SC] changes
934 + (QoSMarkingController *)sharedController
936 static QoSMarkingController * controller;
937 static dispatch_once_t once;
939 dispatch_once(&once, ^{
940 controller = [[QoSMarkingController alloc] init];
947 - (void)setInterfaces:(NSArray *)newInterfaces
949 NSArray * curInterfaces;
952 s = socket(AF_INET, SOCK_DGRAM, 0);
954 SC_log(LOG_ERR, "socket() failed: %s", strerror(errno));
958 curInterfaces = _interfaces;
959 _interfaces = newInterfaces;
961 for (NSString *interface in newInterfaces) {
962 if (!supportsQoSMarking(s, interface.UTF8String)) {
963 // skip interfaces that do not support QoS marking
967 if (![curInterfaces containsObject:interface]) {
968 NSDictionary * policy;
971 policy = _requested[interface];
972 [_requested removeObjectForKey:interface]; // make this look like a fresh "add"
973 [self setPolicy:policy forInterface:interface]; // and "set" the new policy
982 - (void)setPolicy:(NSDictionary *)policy forInterface:(NSString *)interface
985 if ([_interfaces containsObject:interface]) {
986 // set (update) per-interface policy
987 [self updatePolicy:policy forInterface:interface];
990 // track policy for future changes
991 [_requested setObject:policy forKey:interface];
993 // remove (update) per-interface policy
994 [self updatePolicy:policy forInterface:interface];
996 // track policy for future changes
997 [_requested removeObjectForKey:interface];
1007 #pragma mark Update QoS Marking Policy Plugin
1011 * Function: parse_component
1013 * Given a string 'key' and a string prefix 'prefix',
1014 * return the next component in the slash '/' separated
1018 * 1. key = "a/b/c" prefix = "a/"
1020 * 2. key = "a/b/c" prefix = "a/b/"
1023 static CF_RETURNS_RETAINED CFStringRef
1024 parse_component(CFStringRef key, CFStringRef prefix)
1026 CFMutableStringRef comp;
1029 if (!CFStringHasPrefix(key, prefix)) {
1032 comp = CFStringCreateMutableCopy(NULL, 0, key);
1033 CFStringDelete(comp, CFRangeMake(0, CFStringGetLength(prefix)));
1034 range = CFStringFind(comp, CFSTR("/"), 0);
1035 if (range.location == kCFNotFound) {
1038 range.length = CFStringGetLength(comp) - range.location;
1039 CFStringDelete(comp, range);
1046 qosMarkingConfigChangedCallback(SCDynamicStoreRef store, CFArrayRef changedKeys, void *arg)
1049 CFDictionaryRef changes;
1051 static CFStringRef prefix = NULL;
1053 if (prefix == NULL) {
1054 prefix = SCDynamicStoreKeyCreate(NULL,
1056 kSCDynamicStoreDomainSetup,
1061 changes = SCDynamicStoreCopyMultiple(store, changedKeys, NULL);
1063 n = CFArrayGetCount(changedKeys);
1064 for (CFIndex i = 0; i < n; i++) {
1067 key = CFArrayGetValueAtIndex(changedKeys, i);
1069 if (CFEqual(key, interfacesKey)) {
1070 CFDictionaryRef info;
1072 info = (changes != NULL) ? CFDictionaryGetValue(changes, key) : NULL;
1073 if (isA_CFDictionary(info) != NULL) {
1074 CFArrayRef interfaces;
1076 interfaces = CFDictionaryGetValue(info, kSCPropNetInterfaces);
1077 if (isA_CFArray(interfaces)) {
1079 QoSMarkingController * controller;
1081 controller = [QoSMarkingController sharedController];
1082 [controller setInterfaces:(__bridge NSArray *)interfaces];
1087 CFStringRef interface;
1089 interface = parse_component(key, prefix);
1090 if (interface != NULL) {
1091 CFDictionaryRef policy;
1093 policy = (changes != NULL) ? CFDictionaryGetValue(changes, key) : NULL;
1095 QoSMarkingController * controller;
1097 controller = [QoSMarkingController sharedController];
1098 [controller setPolicy:(__bridge NSDictionary *)policy
1099 forInterface:(__bridge NSString *)interface];
1101 CFRelease(interface);
1106 if (changes != NULL) {
1115 haveNetworkExtensionFramework()
1117 Boolean haveFramework;
1119 haveFramework = ([NEPolicy class] != nil);
1120 return haveFramework;
1126 load_QoSMarking(CFBundleRef bundle, Boolean bundleVerbose)
1128 #pragma unused(bundleVerbose)
1129 CFDictionaryRef dict;
1131 CFMutableArrayRef keys;
1133 CFMutableArrayRef patterns;
1134 CFRunLoopSourceRef rls;
1135 SCDynamicStoreRef store;
1137 SC_log(LOG_DEBUG, "load() called");
1138 SC_log(LOG_DEBUG, " bundle ID = %@", CFBundleGetIdentifier(bundle));
1140 if (!haveNetworkExtensionFramework()) {
1144 // initialize a few globals
1145 interfacesKey = SCDynamicStoreKeyCreateNetworkInterface(NULL,
1146 kSCDynamicStoreDomainState);
1148 dict = CFBundleGetInfoDictionary(bundle);
1149 if (isA_CFDictionary(dict)) {
1150 CFArrayRef bundleIDs;
1153 bundleIDs = CFDictionaryGetValue(dict, kQoSMarkingBundleIdentifiersAppleAudioVideoCallsKey);
1154 bundleIDs = isA_CFArray(bundleIDs);
1155 qosMarkingAudioVideoCalls_bundleIDs = (__bridge NSArray *)bundleIDs;
1157 paths = CFDictionaryGetValue(dict, kQoSMarkingExecutablePathsAppleAudioVideoCallsKey);
1158 paths = isA_CFArray(paths);
1159 qosMarkingAudioVideoCalls_executablePaths = (__bridge NSArray *)paths;
1162 // open a "configd" store to allow cache updates
1163 store = SCDynamicStoreCreate(NULL,
1164 CFSTR("QoS Marking Configuraton plug-in"),
1165 qosMarkingConfigChangedCallback,
1167 if (store == NULL) {
1168 SC_log(LOG_ERR, "SCDynamicStoreCreate() failed: %s", SCErrorString(SCError()));
1172 // establish notification keys and patterns
1173 keys = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
1174 patterns = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
1176 // ...watch for a change in the list of network interfaces
1177 CFArrayAppendValue(keys, interfacesKey);
1179 // ...watch for (per-interface) QoS marking policy changes
1180 key = SCDynamicStoreKeyCreateNetworkInterfaceEntity(NULL,
1181 kSCDynamicStoreDomainSetup,
1183 kSCEntNetQoSMarkingPolicy);
1184 CFArrayAppendValue(patterns, key);
1187 // register the keys/patterns
1188 ok = SCDynamicStoreSetNotificationKeys(store, keys, patterns);
1190 CFRelease(patterns);
1192 SC_log(LOG_NOTICE, "SCDynamicStoreSetNotificationKeys() failed: %s",
1193 SCErrorString(SCError()));
1197 rls = SCDynamicStoreCreateRunLoopSource(NULL, store, 0);
1199 SC_log(LOG_NOTICE, "SCDynamicStoreCreateRunLoopSource() failed: %s",
1200 SCErrorString(SCError()));
1204 CFRunLoopAddSource(CFRunLoopGetCurrent(), rls, kCFRunLoopDefaultMode);
1209 if (store != NULL) CFRelease(store);
1218 #pragma mark Standalone test code
1222 main(int argc, char **argv)
1225 _sc_verbose = (argc > 1) ? TRUE : FALSE;
1227 load_QoSMarking(CFBundleGetMainBundle(), (argc > 1) ? TRUE : FALSE);