]> git.saurik.com Git - apple/configd.git/blob - Plugins/QoSMarking/qos-marking.m
configd-1061.141.1.tar.gz
[apple/configd.git] / Plugins / QoSMarking / qos-marking.m
1 /*
2 * Copyright (c) 2016-2019 Apple Inc. All rights reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
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
11 * file.
12 *
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.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23
24 /*
25 * Modification History
26 *
27 * March 1, 2016 Allan Nathanson <ajn@apple.com>
28 * - initial revision
29 */
30
31
32 #include <mach/mach.h>
33 #include <mach-o/fat.h>
34 #include <mach-o/loader.h>
35 #include <net/if.h>
36 #include <net/if_types.h>
37 #include <net/necp.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>
44
45 #define SC_LOG_HANDLE __log_QoSMarking
46 #include <SystemConfiguration/SystemConfiguration.h>
47 #include <SystemConfiguration/SCPrivate.h>
48 #include <SystemConfiguration/SCValidation.h>
49
50 #import <Foundation/Foundation.h>
51 #import <NetworkExtension/NEPolicySession.h>
52 #import <NEHelperClient.h>
53
54 // define the QoSMarking.bundle Info.plist key containing [application] bundleIDs to be white-listed
55 #define kQoSMarkingBundleIdentifiersAppleAudioVideoCallsKey CFSTR("QoSMarking_AppleAudioVideoCalls_BundleIDs")
56
57 // define the QoSMarking.bundle Info.plist key containing paths to be white-listed
58 #define kQoSMarkingExecutablePathsAppleAudioVideoCallsKey CFSTR("QoSMarking_AppleAudioVideoCalls_ExecutablePaths")
59
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
64
65
66 static CFStringRef interfacesKey = NULL;
67 static NSArray * qosMarkingAudioVideoCalls_bundleIDs = nil;
68 static NSArray * qosMarkingAudioVideoCalls_executablePaths = nil;
69
70
71 #pragma mark -
72 #pragma mark Logging
73
74
75 __private_extern__ os_log_t
76 __log_QoSMarking(void)
77 {
78 static os_log_t log = NULL;
79
80 if (log == NULL) {
81 log = os_log_create("com.apple.SystemConfiguration", "QoSMarking");
82 }
83
84 return log;
85 }
86
87
88 #pragma mark -
89 #pragma mark QoSMarking support (system)
90
91
92 static void
93 qosMarkingSetPolicyRestriction(const char *ctl, BOOL yn)
94 {
95 int restricted = yn ? 1 : 0;
96 int ret;
97
98 ret = sysctlbyname(ctl, NULL, 0, &restricted, sizeof(restricted));
99 if (ret != -1) {
100 SC_log(LOG_NOTICE, "QoS marking policy: sysctl %s=%d", ctl, restricted);
101 } else {
102 if (errno != ENOENT) {
103 SC_log(LOG_ERR, "sysctlbyname() failed: %s", strerror(errno));
104 }
105 }
106
107 return;
108 }
109
110
111 static void
112 qosMarkingSetHavePolicies(BOOL havePolicies)
113 {
114 qosMarkingSetPolicyRestriction("net.qos.policy.restricted", havePolicies);
115 return;
116 }
117
118
119 static void
120 qosMarkingSetRestrictAVApps(BOOL restrictApps)
121 {
122 qosMarkingSetPolicyRestriction("net.qos.policy.restrict_avapps", restrictApps);
123 return;
124 }
125
126
127 #pragma mark -
128 #pragma mark QoSMarking support (per-interface)
129
130
131 static BOOL
132 supportsQoSMarking(int s, const char *ifname)
133 {
134 struct ifreq ifr;
135
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",
140 ifname,
141 strerror(errno));
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;
145 }
146
147 #if !TARGET_OS_IPHONE
148 if (ifr.ifr_type.ift_family == IFRTYPE_FAMILY_ETHERNET) {
149 return true;
150 }
151 #else // !TARGET_OS_IPHONE
152 if ((ifr.ifr_type.ift_family == IFRTYPE_FAMILY_ETHERNET) &&
153 (ifr.ifr_type.ift_subfamily == IFRTYPE_SUBFAMILY_WIFI)) {
154 return true;
155 }
156 #endif // !TARGET_OS_IPHONE
157
158 return false;
159 }
160
161
162 static void
163 qosMarkingSetEnabled(int s, const char *ifname, BOOL enabled)
164 {
165 struct ifreq ifr;
166 int ret;
167
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);
172 if (ret == -1) {
173 SC_log(LOG_ERR, "%s: ioctl(SIOCSQOSMARKINGENABLED) failed: %s",
174 ifname,
175 strerror(errno));
176 }
177
178 return;
179 }
180
181
182 #pragma mark -
183 #pragma mark QoSMarking Policy support
184
185
186 @interface QoSMarkingController : NSObject
187
188 + (QoSMarkingController *)sharedController;
189 - (void)setInterfaces:(NSArray *)interfaces;
190 - (void)setPolicy:(NSDictionary *)policy forInterface:(NSString *)interface;
191
192 @end
193
194
195 @interface QoSMarkingController()
196
197 /*
198 * interfaces
199 * An array of network interface names on the system/device
200 */
201 @property (nonatomic) NSArray * interfaces;
202
203 /*
204 * policySessions
205 * A dictionary for the maintaining the QoS marking policies.
206 *
207 * Key : interface [name]
208 * Value : the NEPolicySession* for the interface
209 */
210 @property (nonatomic) NSMutableDictionary * policySessions;
211
212 /*
213 * requested
214 * A dictionary for the tracking the QoS marking policies.
215 *
216 * Key : interface [name]
217 * Value : the [requested] NSDictionary* "policy" for the interface
218 */
219 @property (nonatomic) NSMutableDictionary * requested;
220
221 /*
222 * enabled, enabledAV
223 * Dictionaries for tracking the "enabled" interfaces with QoS [AV]
224 * marking policies.
225 *
226 * Key : interface [name]
227 * Value : the enabled NSDictionary* "policy" for the interface
228 */
229 @property (nonatomic) NSMutableDictionary * enabled;
230 @property (nonatomic) NSMutableDictionary * enabledAV;
231
232 @end
233
234
235 @implementation QoSMarkingController
236
237 - (NEPolicySession *)createPolicySession
238 {
239 return [[NEPolicySession alloc] init];
240 }
241
242
243 #pragma mark -
244
245
246 - (BOOL)qosMarkingPolicyEnabled:(NSDictionary *)policy forKey:(NSString *)key
247 {
248 NSNumber * enabled;
249
250 enabled = policy[key];
251 if (enabled != nil) {
252 if (![enabled isKindOfClass:[NSNumber class]]) {
253 SC_log(LOG_ERR, "%@ not valid", key);
254 return false;
255 }
256 } else {
257 // assume "enabled" if no key
258 return true;
259 }
260
261 return enabled.boolValue;
262 }
263
264
265 - (BOOL)qosMarkingIsEnabled:(NSDictionary *)policy
266 {
267 return [self qosMarkingPolicyEnabled:policy
268 forKey:(NSString *)kSCPropNetQoSMarkingEnabled];
269 }
270
271
272 - (BOOL)qosMarkingIsAppleAudioVideoCallsEnabled:(NSDictionary *)policy
273 {
274 return [self qosMarkingPolicyEnabled:policy
275 forKey:(NSString *)kSCPropNetQoSMarkingAppleAudioVideoCalls];
276 }
277
278
279 - (NSArray *)qosMarkingWhitelistedAppIdentifiers:(NSDictionary *)policy
280 {
281 NSArray * appIDs;
282
283 appIDs = policy[(NSString *)kSCPropNetQoSMarkingWhitelistedAppIdentifiers];
284 if ((appIDs != nil) && ![appIDs isKindOfClass:[NSArray class]]) {
285 SC_log(LOG_ERR, "QoSMarkingWhitelistedAppIdentifier list not valid");
286 return nil;
287 }
288
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");
293 return nil;
294 }
295 }
296
297 return appIDs;
298 }
299
300
301 #pragma mark -
302
303
304 - (NSUUID *)copyUUIDForSingleArch:(int)fd
305 {
306 uint64_t bytes = 0;
307 struct mach_header header;
308 NSUUID * uuid = nil;
309
310 if (read(fd, &header, sizeof(header)) != sizeof(header)) {
311 return nil;
312 }
313
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");
318 return nil;
319 }
320 }
321
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);
327 return nil;
328 }
329
330 // Find LC_UUID in the load commands
331 for (size_t i = 0; i < header.ncmds; i++) {
332 struct load_command lcmd;
333
334 if (read(fd, &lcmd, sizeof(lcmd)) != sizeof(lcmd)) {
335 SC_log(LOG_ERR, "could not read() load_command");
336 break;
337 }
338
339 if (lcmd.cmd == LC_UUID) {
340 struct uuid_command uuid_cmd;
341
342 if (read(fd, uuid_cmd.uuid, sizeof(uuid_t)) != sizeof(uuid_t)) {
343 SC_log(LOG_ERR, "could not read() uuid_command");
344 break;
345 }
346
347 uuid = [[NSUUID alloc] initWithUUIDBytes:uuid_cmd.uuid];
348 break;
349 } else {
350 if (lseek(fd, lcmd.cmdsize - sizeof(lcmd), SEEK_CUR) == -1) {
351 SC_log(LOG_ERR, "could not lseek() past load command");
352 return nil;
353 }
354 }
355 }
356
357 return uuid;
358 }
359
360 #define MAX_NFAT_ARCH 32
361
362 - (NSArray *)copyUUIDsForFatBinary:(int)fd
363 {
364 struct fat_arch * arches = NULL;
365 mach_msg_type_number_t count;
366 struct fat_header hdr;
367 struct host_basic_info hostinfo;
368 kern_return_t kr;
369 NSMutableArray * uuids = nil;
370
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);
377 return nil;
378 }
379
380 if (read(fd, &hdr, sizeof(hdr)) != sizeof(hdr)) {
381 SC_log(LOG_ERR, "could not read() fat_header");
382 return nil;
383 }
384
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);
389 return nil;
390 }
391
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
395 return nil;
396 }
397
398 uuids = [[NSMutableArray alloc] init];
399
400 for (size_t i = 0; i < hdr.nfat_arch; ++i) {
401 struct fat_arch arch;
402
403 if (read(fd, &arch, sizeof(arch)) != sizeof(arch)) {
404 SC_log(LOG_ERR, "could not read() fat_arch");
405 goto done;
406 }
407 arch.cputype = (int)OSSwapInt32(arch.cputype);
408 arch.offset = OSSwapInt32(arch.offset);
409 memcpy(&arches[i], &arch, sizeof(arch));
410 }
411
412 for (size_t i = 0; i < hdr.nfat_arch; ++i) {
413 struct fat_arch arch;
414 NSUUID * uuid;
415
416 memcpy(&arch, &arches[i], sizeof(arch));
417
418 if (arch.offset == 0) {
419 SC_log(LOG_ERR, "invalid offset for arch %d", arch.cputype);
420 goto done;
421 }
422
423 if (lseek(fd, arch.offset, SEEK_SET) == -1) {
424 SC_log(LOG_ERR, "could not lseek() to arch %d", arch.cputype);
425 goto done;
426 }
427
428 uuid = [self copyUUIDForSingleArch:fd];
429 if (uuid == nil) {
430 SC_log(LOG_ERR, "could not get uuid for arch %d", arch.cputype);
431 goto done;
432 }
433
434 if (arch.cputype == hostinfo.cpu_type) {
435 [uuids insertObject:uuid atIndex:0];
436 } else {
437 [uuids addObject:uuid];
438 }
439 }
440
441 done:
442
443 if (arches != NULL) {
444 free(arches);
445 }
446 if (uuids.count == 0) {
447 uuids = nil;
448 }
449 return uuids;
450 }
451
452 - (NSArray *)copyUUIDsForExecutable:(const char *)executablePath
453 {
454 int fd;
455 uint32_t magic;
456 NSArray * uuids = nil;
457
458 if (executablePath == NULL) {
459 return nil;
460 }
461
462 fd = open(executablePath, O_RDONLY);
463 if (fd == -1) {
464 if (errno != ENOENT) {
465 SC_log(LOG_ERR, "open(\"%s\", O_RDONLY) failed: %s", executablePath, strerror(errno));
466 }
467
468 return nil;
469 }
470
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);
474 goto done;
475 }
476
477 // Rewind to the beginning
478 lseek(fd, 0, SEEK_SET);
479 switch (magic) {
480 case FAT_CIGAM: {
481 uuids = [self copyUUIDsForFatBinary:fd];
482 break;
483 }
484
485 case MH_MAGIC:
486 case MH_MAGIC_64: {
487 NSUUID * uuid;
488
489 uuid = [self copyUUIDForSingleArch:fd];
490 if (uuid == nil) {
491 SC_log(LOG_ERR, "%s: failed to get UUID for single arch", __FUNCTION__);
492 goto done;
493 }
494
495 uuids = @[ uuid ];
496 break;
497 }
498
499 default: {
500 break;
501 }
502 }
503
504 done:
505
506 close(fd);
507 return uuids;
508 }
509
510
511 - (void)addWhitelistedPathPolicy:(NSString *)interface forPath:(NSString *)path order:(uint32_t)order
512 {
513 NEPolicyCondition * allInterfacesCondition;
514 NEPolicyResult * result;
515 NEPolicyRouteRule * routeRule;
516 NEPolicySession * session;
517 NSArray * uuids;
518
519 session = _policySessions[interface];
520 if (session == nil) {
521 SC_log(LOG_ERR, "QoS marking policy: %@: no session", interface);
522 return;
523 }
524
525 // create QoS route rule
526 routeRule = [NEPolicyRouteRule routeRuleWithAction:NEPolicyRouteRuleActionQoSMarking
527 forInterfaceName:interface];
528 result = [NEPolicyResult routeRules:@[ routeRule ]];
529
530 // create "all interfaces" condition
531 allInterfacesCondition = [NEPolicyCondition allInterfaces];
532
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 \"%@\"",
536 interface,
537 path);
538 return;
539 }
540
541 for (NSUUID *uuid in uuids) {
542 NEPolicy * policy;
543 NSUInteger policyID;
544 NEPolicyCondition * uuidCondition;
545
546 // create per-app bundleID-->UUID condition
547 uuidCondition = [NEPolicyCondition effectiveApplication:uuid];
548
549 // create and add policy
550 policy = [[NEPolicy alloc] initWithOrder:order
551 result:result
552 conditions:@[ uuidCondition, allInterfacesCondition ]];
553 policyID = [session addPolicy:policy];
554 if (policyID != 0) {
555 SC_log(LOG_NOTICE, "QoS marking policy: %@: %u: whitelist path \"%@\" (%@)",
556 interface,
557 order,
558 path,
559 uuid.UUIDString);
560
561 } else {
562 SC_log(LOG_ERR, "QoS marking policy: %@: could not add whitelist policy for path \"%@\" (%@)",
563 interface,
564 path,
565 uuid.UUIDString);
566 }
567 }
568
569
570 return;
571 }
572
573
574 #pragma mark -
575
576
577 - (NSArray *)copyUUIDsForUUIDMapping:(xpc_object_t)mapping
578 {
579 NSMutableArray * uuids = nil;
580
581 if ((mapping != NULL) &&
582 (xpc_get_type(mapping) == XPC_TYPE_ARRAY)) {
583 uuids = [NSMutableArray array];
584
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)) {
589 NSUUID * uuid;
590
591 uuid = [[NSUUID alloc] initWithUUIDBytes:xpc_uuid_get_bytes(value)];
592 [uuids addObject:uuid];
593 }
594 return YES;
595 });
596
597 if (uuids.count == 0) {
598 uuids = nil;
599 }
600 }
601
602 return uuids;
603 }
604
605
606 - (NSArray *)copyUUIDsForBundleID:(NSString *)bundleID
607 {
608 NSArray * uuids;
609 xpc_object_t uuidsFromHelper;
610
611 uuidsFromHelper = NEHelperCacheCopyAppUUIDMapping([bundleID UTF8String], NULL);
612
613 uuids = [self copyUUIDsForUUIDMapping:uuidsFromHelper];
614 return uuids;
615 }
616
617
618 - (void)addWhitelistedAppIdentifierPolicy:(NSString *)interface forApp:(NSString *)appBundleID order:(uint32_t)order
619 {
620 NEPolicyCondition * allInterfacesCondition;
621 NEPolicyResult * result;
622 NEPolicyRouteRule * routeRule;
623 NEPolicySession * session;
624 NSArray * uuids;
625
626 if ([appBundleID hasPrefix:@"/"]) {
627 if (_SC_isAppleInternal()) {
628 // special case executable path handling (if internal)
629 [self addWhitelistedPathPolicy:interface forPath:appBundleID order:order];
630 }
631
632 return;
633 }
634
635 session = _policySessions[interface];
636 if (session == nil) {
637 SC_log(LOG_ERR, "QoS marking policy: %@: no session", interface);
638 return;
639 }
640
641 // create QoS route rule
642 routeRule = [NEPolicyRouteRule routeRuleWithAction:NEPolicyRouteRuleActionQoSMarking
643 forInterfaceName:interface];
644 result = [NEPolicyResult routeRules:@[ routeRule ]];
645
646 // create "all interfaces" condition
647 allInterfacesCondition = [NEPolicyCondition allInterfaces];
648
649 uuids = [self copyUUIDsForBundleID:appBundleID];
650 if ((uuids == nil) || (uuids.count == 0)) {
651 SC_log(LOG_ERR, "QoS marking policy: %@: could not add bundleID \"%@\"",
652 interface,
653 appBundleID);
654 return;
655 }
656
657 for (NSUUID *uuid in uuids) {
658 NEPolicy * policy;
659 NSUInteger policyID;
660 NEPolicyCondition * uuidCondition;
661
662 // create per-app bundleID-->UUID condition
663 uuidCondition = [NEPolicyCondition effectiveApplication:uuid];
664
665 // create and add policy
666 policy = [[NEPolicy alloc] initWithOrder:order
667 result:result
668 conditions:@[ uuidCondition, allInterfacesCondition ]];
669 policyID = [session addPolicy:policy];
670 if (policyID != 0) {
671 SC_log(LOG_NOTICE, "QoS marking policy: %@: %u: whitelist bundleID \"%@\" (%@)",
672 interface,
673 order,
674 appBundleID,
675 uuid.UUIDString);
676
677 } else {
678 SC_log(LOG_ERR, "QoS marking policy: %@: could not add whitelist policy for bundleID \"%@\" (%@)",
679 interface,
680 appBundleID,
681 uuid.UUIDString);
682 }
683 }
684
685 return;
686 }
687
688
689 #pragma mark -
690
691
692 - (instancetype)init
693 {
694 self = [super init];
695 if (self != nil) {
696 _interfaces = nil;
697 _policySessions = [NSMutableDictionary dictionary];
698 _requested = [NSMutableDictionary dictionary];
699 _enabled = [NSMutableDictionary dictionary];
700 _enabledAV = [NSMutableDictionary dictionary];
701 }
702
703 return self;
704 }
705
706
707 /*
708
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]
713 | |
714 2 [Y] [N] [0] [N] | 0 0 | [N] [N] [N]
715 3 [Y] [N] [0] [Y] | 0 0 | [N] [N] [N]
716 | |
717 4 [Y] [N] [> 0] [N] | 0 0 | [N] [N] [N]
718 5 [Y] [N] [> 0] [Y] | 0 0 | [N] [N] [N]
719 | |
720 6 [Y] [Y] [0] [N] | 1 1 | [Y] [N] [N]
721 7 [Y] [Y] [0] [Y] | 1 0 | [Y] [N] [Y]
722 | |
723 8 [Y] [Y] [> 0] [N] | 1 1 | [Y] [Y] [N]
724 9 [Y] [Y] [> 0] [Y] | 1 0 | [Y] [Y] [Y]
725
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
730
731 Notes (sysctl) :
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"
734
735 */
736
737 - (void)updatePolicy:(NSDictionary *)reqPolicy forInterface:(NSString *)interface
738 {
739 // currently enabled settings
740 NSDictionary * nowPolicy = _enabled[interface];
741 BOOL nowDisabled = false;
742 BOOL nowEnabled = false;
743 BOOL nowAppleAV = false;
744
745 // requested settings
746 BOOL reqDefault = false;
747 BOOL reqDisabled = false;
748 BOOL reqEnabled = false;
749 BOOL reqAppleAV = false;
750
751 if (nowPolicy != nil) {
752 if ([self qosMarkingIsEnabled:nowPolicy]) {
753 // if we have an enabled QoS marking policy
754 nowEnabled = true;
755 } else {
756 // if we have a disabled QoS marking policy
757 nowDisabled = true;
758 }
759
760 nowAppleAV = [self qosMarkingIsAppleAudioVideoCallsEnabled:nowPolicy];
761 }
762
763 if (reqPolicy != nil) {
764 if ([self qosMarkingIsEnabled:reqPolicy]) {
765 // if QoS marking policy requested
766 reqEnabled = true;
767 } else {
768 // if QoS marking policy present (but disabled)
769 reqDisabled = true;
770 }
771
772 reqAppleAV = [self qosMarkingIsAppleAudioVideoCallsEnabled:reqPolicy];
773 } else {
774 reqDefault = true;
775 }
776
777 if ((!nowEnabled && reqDefault ) ||
778 ( nowEnabled != reqEnabled ) ||
779 ( nowDisabled != reqDisabled) ||
780 ( nowEnabled && reqEnabled && ![nowPolicy isEqual:reqPolicy])) {
781 int s;
782
783 if (reqEnabled) {
784 // if we are transitioning to enabled or we have a policy
785 // change, ensure that we rebuild policies
786 nowPolicy = nil;
787 } else {
788 if ((nowPolicy != nil) && (reqPolicy == nil)) {
789 SC_log(LOG_NOTICE, "QoS marking policy: %@: remove", interface);
790 }
791
792 // if QoS marking was enabled (for this interface), close session
793 [_policySessions removeObjectForKey:interface];
794
795 // QoS marking policy for this interface is no longer enabled
796 [_enabled removeObjectForKey:interface];
797 [_enabledAV removeObjectForKey:interface];
798 }
799
800 // update QoSMarking enabled (per-interface)
801 s = socket(AF_INET, SOCK_DGRAM, 0);
802 if (s != -1) {
803 BOOL enable = reqEnabled || reqDefault;
804
805 SC_log(LOG_NOTICE, "QoS marking policy: %@: %s%s",
806 interface,
807 enable ? "enable" : "disable",
808 reqDefault ? " (default)" : "");
809 qosMarkingSetEnabled(s, interface.UTF8String, enable);
810 close(s);
811 } else {
812 SC_log(LOG_ERR, "socket() failed: %s", strerror(errno));
813 }
814 }
815
816 if (reqEnabled) {
817 NSArray * curAppIDs;
818 NSArray * reqAppIDs;
819 BOOL update = FALSE;
820
821 if (nowAppleAV != reqAppleAV) {
822 update = true;
823 }
824
825 curAppIDs = [self qosMarkingWhitelistedAppIdentifiers:nowPolicy];
826 reqAppIDs = [self qosMarkingWhitelistedAppIdentifiers:reqPolicy];
827 if (![curAppIDs isEqual:reqAppIDs]) {
828 update = true;
829 }
830
831 if (update) {
832 BOOL ok;
833 uint32_t order;
834 NEPolicySession * session;
835
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);
840 }
841
842 // the QoS marking policy for this interface is now enabled
843 _enabled[interface] = reqPolicy;
844
845 SC_log(LOG_NOTICE, "QoS marking policy: %@: %s",
846 interface,
847 nowEnabled ? "update" : "add");
848
849 // prepare [new] per-interface NECP session
850
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;
857 } else {
858 SC_log(LOG_ERR, "%@: failed to create policy session", interface);
859 }
860 }
861
862 // zap any previously stored policies
863 if (session != nil) {
864 ok = [session removeAllPolicies];
865 if (!ok) {
866 SC_log(LOG_ERR, "%@: could not remove policies", interface);
867 }
868 }
869
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++];
875 }
876 }
877
878 if (reqAppleAV) {
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);
884 }
885
886 // the QoS [AV] marking policy for this interface is now enabled
887 _enabledAV[interface] = reqPolicy;
888
889 if (session != nil) {
890 // if needed, add Apple audio/video application policies
891
892 order = QOS_MARKING_PRIORITY_BLOCK_AV_APPS;
893 for (NSString *app in qosMarkingAudioVideoCalls_bundleIDs) {
894 [self addWhitelistedAppIdentifierPolicy:interface forApp:app order:order++];
895 }
896
897 order = QOS_MARKING_PRIORITY_BLOCK_AV_PATHS;
898 for (NSString *path in qosMarkingAudioVideoCalls_executablePaths) {
899 [self addWhitelistedPathPolicy:interface forPath:path order:order++];
900 }
901 }
902 } else {
903 // the QoS [AV] marking policy for this interface is no longer enabled
904 [_enabledAV removeObjectForKey:interface];
905
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);
910 }
911 }
912
913 if (session != nil) {
914 ok = [session apply];
915 if (!ok) {
916 SC_log(LOG_ERR, "%@: could not apply new policies", interface);
917 }
918 }
919 }
920 }
921
922 // Restore "default" state if no policies
923 if (_enabled.count == 0) {
924 qosMarkingSetRestrictAVApps(false);
925 qosMarkingSetHavePolicies(false);
926 }
927 }
928
929
930 #pragma mark -
931 #pragma mark Update QoSMarking Policy Configuration per [SC] changes
932
933
934 + (QoSMarkingController *)sharedController
935 {
936 static QoSMarkingController * controller;
937 static dispatch_once_t once;
938
939 dispatch_once(&once, ^{
940 controller = [[QoSMarkingController alloc] init];
941 });
942
943 return controller;
944 }
945
946
947 - (void)setInterfaces:(NSArray *)newInterfaces
948 {
949 NSArray * curInterfaces;
950 int s;
951
952 s = socket(AF_INET, SOCK_DGRAM, 0);
953 if (s == -1) {
954 SC_log(LOG_ERR, "socket() failed: %s", strerror(errno));
955 return;
956 }
957
958 curInterfaces = _interfaces;
959 _interfaces = newInterfaces;
960
961 for (NSString *interface in newInterfaces) {
962 if (!supportsQoSMarking(s, interface.UTF8String)) {
963 // skip interfaces that do not support QoS marking
964 continue;
965 }
966
967 if (![curInterfaces containsObject:interface]) {
968 NSDictionary * policy;
969
970 // if new interface
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
974 }
975 }
976
977 close(s);
978 return;
979 }
980
981
982 - (void)setPolicy:(NSDictionary *)policy forInterface:(NSString *)interface
983 {
984 if (policy != nil) {
985 if ([_interfaces containsObject:interface]) {
986 // set (update) per-interface policy
987 [self updatePolicy:policy forInterface:interface];
988 }
989
990 // track policy for future changes
991 [_requested setObject:policy forKey:interface];
992 } else {
993 // remove (update) per-interface policy
994 [self updatePolicy:policy forInterface:interface];
995
996 // track policy for future changes
997 [_requested removeObjectForKey:interface];
998 }
999
1000 return;
1001 }
1002
1003 @end
1004
1005
1006 #pragma mark -
1007 #pragma mark Update QoS Marking Policy Plugin
1008
1009
1010 /*
1011 * Function: parse_component
1012 * Purpose:
1013 * Given a string 'key' and a string prefix 'prefix',
1014 * return the next component in the slash '/' separated
1015 * key.
1016 *
1017 * Examples:
1018 * 1. key = "a/b/c" prefix = "a/"
1019 * returns "b"
1020 * 2. key = "a/b/c" prefix = "a/b/"
1021 * returns "c"
1022 */
1023 static CF_RETURNS_RETAINED CFStringRef
1024 parse_component(CFStringRef key, CFStringRef prefix)
1025 {
1026 CFMutableStringRef comp;
1027 CFRange range;
1028
1029 if (!CFStringHasPrefix(key, prefix)) {
1030 return NULL;
1031 }
1032 comp = CFStringCreateMutableCopy(NULL, 0, key);
1033 CFStringDelete(comp, CFRangeMake(0, CFStringGetLength(prefix)));
1034 range = CFStringFind(comp, CFSTR("/"), 0);
1035 if (range.location == kCFNotFound) {
1036 return comp;
1037 }
1038 range.length = CFStringGetLength(comp) - range.location;
1039 CFStringDelete(comp, range);
1040 return comp;
1041 }
1042
1043
1044
1045 static void
1046 qosMarkingConfigChangedCallback(SCDynamicStoreRef store, CFArrayRef changedKeys, void *arg)
1047 {
1048 #pragma unused(arg)
1049 CFDictionaryRef changes;
1050 CFIndex n;
1051 static CFStringRef prefix = NULL;
1052
1053 if (prefix == NULL) {
1054 prefix = SCDynamicStoreKeyCreate(NULL,
1055 CFSTR("%@/%@/%@/"),
1056 kSCDynamicStoreDomainSetup,
1057 kSCCompNetwork,
1058 kSCCompInterface);
1059 }
1060
1061 changes = SCDynamicStoreCopyMultiple(store, changedKeys, NULL);
1062
1063 n = CFArrayGetCount(changedKeys);
1064 for (CFIndex i = 0; i < n; i++) {
1065 CFStringRef key;
1066
1067 key = CFArrayGetValueAtIndex(changedKeys, i);
1068
1069 if (CFEqual(key, interfacesKey)) {
1070 CFDictionaryRef info;
1071
1072 info = (changes != NULL) ? CFDictionaryGetValue(changes, key) : NULL;
1073 if (isA_CFDictionary(info) != NULL) {
1074 CFArrayRef interfaces;
1075
1076 interfaces = CFDictionaryGetValue(info, kSCPropNetInterfaces);
1077 if (isA_CFArray(interfaces)) {
1078 @autoreleasepool {
1079 QoSMarkingController * controller;
1080
1081 controller = [QoSMarkingController sharedController];
1082 [controller setInterfaces:(__bridge NSArray *)interfaces];
1083 }
1084 }
1085 }
1086 } else {
1087 CFStringRef interface;
1088
1089 interface = parse_component(key, prefix);
1090 if (interface != NULL) {
1091 CFDictionaryRef policy;
1092
1093 policy = (changes != NULL) ? CFDictionaryGetValue(changes, key) : NULL;
1094 @autoreleasepool {
1095 QoSMarkingController * controller;
1096
1097 controller = [QoSMarkingController sharedController];
1098 [controller setPolicy:(__bridge NSDictionary *)policy
1099 forInterface:(__bridge NSString *)interface];
1100 }
1101 CFRelease(interface);
1102 }
1103 }
1104 }
1105
1106 if (changes != NULL) {
1107 CFRelease(changes);
1108 }
1109
1110 return;
1111 }
1112
1113
1114 static Boolean
1115 haveNetworkExtensionFramework()
1116 {
1117 Boolean haveFramework;
1118
1119 haveFramework = ([NEPolicy class] != nil);
1120 return haveFramework;
1121 }
1122
1123
1124 __private_extern__
1125 void
1126 load_QoSMarking(CFBundleRef bundle, Boolean bundleVerbose)
1127 {
1128 #pragma unused(bundleVerbose)
1129 CFDictionaryRef dict;
1130 CFStringRef key;
1131 CFMutableArrayRef keys;
1132 Boolean ok;
1133 CFMutableArrayRef patterns;
1134 CFRunLoopSourceRef rls;
1135 SCDynamicStoreRef store;
1136
1137 SC_log(LOG_DEBUG, "load() called");
1138 SC_log(LOG_DEBUG, " bundle ID = %@", CFBundleGetIdentifier(bundle));
1139
1140 if (!haveNetworkExtensionFramework()) {
1141 return;
1142 }
1143
1144 // initialize a few globals
1145 interfacesKey = SCDynamicStoreKeyCreateNetworkInterface(NULL,
1146 kSCDynamicStoreDomainState);
1147
1148 dict = CFBundleGetInfoDictionary(bundle);
1149 if (isA_CFDictionary(dict)) {
1150 CFArrayRef bundleIDs;
1151 CFArrayRef paths;
1152
1153 bundleIDs = CFDictionaryGetValue(dict, kQoSMarkingBundleIdentifiersAppleAudioVideoCallsKey);
1154 bundleIDs = isA_CFArray(bundleIDs);
1155 qosMarkingAudioVideoCalls_bundleIDs = (__bridge NSArray *)bundleIDs;
1156
1157 paths = CFDictionaryGetValue(dict, kQoSMarkingExecutablePathsAppleAudioVideoCallsKey);
1158 paths = isA_CFArray(paths);
1159 qosMarkingAudioVideoCalls_executablePaths = (__bridge NSArray *)paths;
1160 }
1161
1162 // open a "configd" store to allow cache updates
1163 store = SCDynamicStoreCreate(NULL,
1164 CFSTR("QoS Marking Configuraton plug-in"),
1165 qosMarkingConfigChangedCallback,
1166 NULL);
1167 if (store == NULL) {
1168 SC_log(LOG_ERR, "SCDynamicStoreCreate() failed: %s", SCErrorString(SCError()));
1169 goto error;
1170 }
1171
1172 // establish notification keys and patterns
1173 keys = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
1174 patterns = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
1175
1176 // ...watch for a change in the list of network interfaces
1177 CFArrayAppendValue(keys, interfacesKey);
1178
1179 // ...watch for (per-interface) QoS marking policy changes
1180 key = SCDynamicStoreKeyCreateNetworkInterfaceEntity(NULL,
1181 kSCDynamicStoreDomainSetup,
1182 kSCCompAnyRegex,
1183 kSCEntNetQoSMarkingPolicy);
1184 CFArrayAppendValue(patterns, key);
1185 CFRelease(key);
1186
1187 // register the keys/patterns
1188 ok = SCDynamicStoreSetNotificationKeys(store, keys, patterns);
1189 CFRelease(keys);
1190 CFRelease(patterns);
1191 if (!ok) {
1192 SC_log(LOG_NOTICE, "SCDynamicStoreSetNotificationKeys() failed: %s",
1193 SCErrorString(SCError()));
1194 goto error;
1195 }
1196
1197 rls = SCDynamicStoreCreateRunLoopSource(NULL, store, 0);
1198 if (rls == NULL) {
1199 SC_log(LOG_NOTICE, "SCDynamicStoreCreateRunLoopSource() failed: %s",
1200 SCErrorString(SCError()));
1201 goto error;
1202 }
1203
1204 CFRunLoopAddSource(CFRunLoopGetCurrent(), rls, kCFRunLoopDefaultMode);
1205 CFRelease(rls);
1206
1207 error :
1208
1209 if (store != NULL) CFRelease(store);
1210 return;
1211 }
1212
1213
1214 #ifdef MAIN
1215
1216
1217 #pragma mark -
1218 #pragma mark Standalone test code
1219
1220
1221 int
1222 main(int argc, char **argv)
1223 {
1224 _sc_log = kSCLogDestinationFile;
1225 _sc_verbose = (argc > 1) ? TRUE : FALSE;
1226
1227 load_QoSMarking(CFBundleGetMainBundle(), (argc > 1) ? TRUE : FALSE);
1228 CFRunLoopRun();
1229 // not reached
1230 exit(0);
1231 return 0;
1232 }
1233 #endif