1/*
2 * Copyright (c) 2013-2014 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#import "KDSecCircle.h"
26#import "KDCirclePeer.h"
27#include <notify.h>
28#include <dispatch/dispatch.h>
29#import "SecureObjectSync/SOSCloudCircle.h"
30#include "SecureObjectSync/SOSPeerInfo.h"
31
32@interface KDSecCircle ()
33@property (retain) NSMutableArray *callbacks;
34
35@property (readwrite) unsigned long long changeCount;
36
37@property (readwrite) SOSCCStatus rawStatus;
38
39@property (readwrite) NSString *status;
40@property (readwrite) NSError *error;
41
42@property (readwrite) NSArray *peers;
43@property (readwrite) NSArray *applicants;
44
45@property (readwrite) dispatch_queue_t queue_;
46
47@end
48
49@implementation KDSecCircle
50
51-(void)updateCheck
52{
53	// XXX: assert not on main_queue
54	CFErrorRef err = NULL;
55	SOSCCStatus newRawStatus = SOSCCThisDeviceIsInCircle(&err);
56
57    NSArray *peerInfos = (__bridge NSArray *)(SOSCCCopyApplicantPeerInfo(&err));
58    NSMutableArray *newApplicants = [[NSMutableArray alloc] initWithCapacity:peerInfos.count];
59	[peerInfos enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
60        [newApplicants addObject:[[KDCirclePeer alloc] initWithPeerObject:obj]];
61    }];
62
63	peerInfos = (__bridge NSArray *)(SOSCCCopyPeerPeerInfo(&err));
64    NSMutableArray *newPeers = [[NSMutableArray alloc] initWithCapacity:peerInfos.count];
65	[peerInfos enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
66        [newPeers addObject:[[KDCirclePeer alloc] initWithPeerObject:obj]];
67    }];
68
69    NSLog(@"rawStatus %d, #applicants %lu, #peers %lu, err=%@", newRawStatus, (unsigned long)[newApplicants count], (unsigned long)[newPeers count], err);
70
71	dispatch_async(dispatch_get_main_queue(), ^{
72        self.rawStatus = newRawStatus;
73
74		switch (newRawStatus) {
75			case kSOSCCInCircle:
76				self.status = @"In Circle";
77				break;
78
79			case kSOSCCNotInCircle:
80				self.status = @"Not In Circle";
81				break;
82
83			case kSOSCCRequestPending:
84				self.status = @"Request Pending";
85				break;
86
87			case kSOSCCCircleAbsent:
88				self.status = @"Circle Absent";
89				break;
90
91			case kSOSCCError:
92				self.status = [NSString stringWithFormat:@"Error: %@", err];
93				break;
94
95			default:
96				self.status = [NSString stringWithFormat:@"Unknown status code %d", self.rawStatus];
97				break;
98		}
99
100        self.applicants = [newApplicants copy];
101        self.peers = [newPeers copy];
102        self.error = (__bridge NSError *)(err);
103
104        self.changeCount++;
105        for (dispatch_block_t callback in self.callbacks) {
106            callback();
107        }
108	});
109}
110
111// XXX It's a botch to use the "name" and not applicant, but
112// it is hard to get anythign else to survive a serialastion
113// trip thoguth NSUserNotificationCenter.
114//
115// Er, now that I look more closely maybe SOSPeerInfoGetPeerID...
116
117typedef void (^applicantBlock)(id applicant);
118
119-(void)forApplicantId:(NSString*)applicantId run:(applicantBlock)applicantBlock
120{
121    dispatch_async(self.queue_, ^{
122		for (KDCirclePeer *applicant in self.applicants) {
123			if ([applicantId isEqualToString:applicantId]) {
124				applicantBlock(applicant.peerObject);
125				break;
126			}
127		}
128    });
129}
130
131-(void)acceptApplicantId:(NSString*)applicantId
132{
133    [self forApplicantId:applicantId run:^void(id applicant) {
134        CFErrorRef err = NULL;
135        bool ok = SOSCCAcceptApplicants((__bridge CFArrayRef)(@[applicant]), &err);
136        NSAssert(ok, @"Error %@ while accepting %@ (%@)", err, applicantId, applicant);
137    }];
138}
139
140-(void)rejectApplicantId:(NSString*)applicantId
141{
142    [self forApplicantId:applicantId run:^void(id applicant) {
143        CFErrorRef err = NULL;
144        bool ok = SOSCCRejectApplicants((__bridge CFArrayRef)(@[applicant]), &err);
145        NSAssert(ok, @"Error %@ while rejecting %@ (%@)", err, applicantId, applicant);
146    }];
147}
148
149-(id)init
150{
151	self = [super init];
152	int token;
153
154    self->_queue_ = dispatch_queue_create([[NSString stringWithFormat:@"KDSecCircle@%p", self] UTF8String], NULL);
155    self->_callbacks = [NSMutableArray new];
156    // Replace "com.apple.security.secureobjectsync.circlechanged" with kSOSCCCircleChangedNotification once it is exported
157	notify_register_dispatch("com.apple.security.secureobjectsync.circlechanged", &token, self.queue_, ^(int token){
158		[self updateCheck];
159	});
160
161    return self;
162}
163
164-(void)addChangeCallback:(dispatch_block_t)callback
165{
166	[self.callbacks addObject:callback];
167    if (self.changeCount) {
168        dispatch_async(dispatch_get_main_queue(), callback);
169    } else if (self.callbacks.count == 1) {
170        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
171            [self updateCheck];
172        });
173    }
174}
175
176-(BOOL)isInCircle
177{
178    return (self.rawStatus == kSOSCCInCircle) ? YES : NO;
179}
180
181-(BOOL)isOutOfCircle
182{
183    return (self.rawStatus == kSOSCCNotInCircle || self.rawStatus == kSOSCCCircleAbsent);
184}
185
186-(void)enableSync
187{
188    CFErrorRef err = NULL;
189	if (self.rawStatus == kSOSCCCircleAbsent) {
190		SOSCCResetToOffering(&err);
191	} else {
192		SOSCCRequestToJoinCircle(&err);
193	}
194}
195
196-(void)disableSync
197{
198    CFErrorRef err = NULL;
199    SOSCCRemoveThisDeviceFromCircle(&err);
200}
201
202@end
203