2 * Copyright (c) 2012-2014 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@
24 #include <AssertMacros.h>
26 #import <Foundation/Foundation.h>
27 #import <Security/Security.h>
28 #import <utilities/SecCFRelease.h>
30 #import <xpc/private.h>
31 #import <CoreFoundation/CFXPCBridge.h>
34 #import <CommonCrypto/CommonDigest.h>
35 #include <utilities/SecXPCError.h>
36 #include <TargetConditionals.h>
37 #include "SOSCloudKeychainConstants.h"
38 #import <Security/SecureObjectSync/SOSInternal.h>
39 #import "KeychainSyncingOverIDSProxy+SendMessage.h"
41 int idsproxymain(int argc, const char *argv[]);
43 #define PROXYXPCSCOPE "idsproxy"
45 static void describeXPCObject(char *prefix, xpc_object_t object)
47 // This is useful for debugging.
50 char *desc = xpc_copy_description(object);
51 secdebug(PROXYXPCSCOPE, "%s%s\n", prefix, desc);
55 secdebug(PROXYXPCSCOPE, "%s<NULL>\n", prefix);
59 static void idskeychainsyncingproxy_peer_dictionary_handler(const xpc_connection_t peer, xpc_object_t event)
64 require_action_string(xpc_get_type(event) == XPC_TYPE_DICTIONARY, xit, err = -51, "expected XPC_TYPE_DICTIONARY");
66 const char *operation = xpc_dictionary_get_string(event, kMessageKeyOperation);
67 require_action(operation, xit, result = false);
69 // Check protocol version
70 uint64_t version = xpc_dictionary_get_uint64(event, kMessageKeyVersion);
71 secdebug(PROXYXPCSCOPE, "Reply version: %lld\n", version);
72 require_action(version == kCKDXPCVersion, xit, result = false);
75 secdebug(PROXYXPCSCOPE, "Handling %s operation", operation);
78 if(operation && !strcmp(operation, kOperationGetDeviceID)){
79 [[KeychainSyncingOverIDSProxy idsProxy] doSetIDSDeviceID];
80 xpc_object_t replyMessage = xpc_dictionary_create_reply(event);
81 xpc_dictionary_set_bool(replyMessage, kMessageKeyValue, true);
82 xpc_connection_send_message(peer, replyMessage);
83 secdebug(PROXYXPCSCOPE, "Set our IDS Device ID message sent");
86 else if(operation && !strcmp(operation, kOperationGetIDSPerfCounters)){
87 NSDictionary *counters = [[KeychainSyncingOverIDSProxy idsProxy] collectStats];
88 xpc_object_t xMessages = _CFXPCCreateXPCObjectFromCFObject((__bridge CFDictionaryRef)(counters));
90 xpc_object_t replyMessage = xpc_dictionary_create_reply(event);
91 xpc_dictionary_set_value(replyMessage, kMessageKeyValue, xMessages);
92 xpc_connection_send_message(peer, replyMessage);
93 secdebug(PROXYXPCSCOPE, "Retrieved counters");
95 else if (operation && !strcmp(operation, kOperationGetPendingMesages))
97 NSDictionary* messages = [[KeychainSyncingOverIDSProxy idsProxy] retrievePendingMessages];
98 xpc_object_t xMessages = _CFXPCCreateXPCObjectFromCFObject((__bridge CFDictionaryRef)(messages));
100 xpc_object_t replyMessage = xpc_dictionary_create_reply(event);
101 xpc_dictionary_set_value(replyMessage, kMessageKeyValue, xMessages);
103 xpc_connection_send_message(peer, replyMessage);
104 secdebug(PROXYXPCSCOPE, "retrieved pending messages");
107 else if(operation && !strcmp(operation, kOperationSendDeviceList)) //IDS device availability check
109 xpc_object_t xidsDeviceList = xpc_dictionary_get_value(event, kMessageKeyValue);
110 xpc_object_t xPeerID = xpc_dictionary_get_value(event, kMessageKeyPeerID);
112 NSArray *idsList = (__bridge_transfer NSArray*)(_CFXPCCreateCFObjectFromXPCObject(xidsDeviceList));
113 NSString *peerID = (__bridge_transfer NSString*)(_CFXPCCreateCFObjectFromXPCObject(xPeerID));
115 bool isMessageArray = (CFGetTypeID((__bridge CFTypeRef)(idsList)) == CFArrayGetTypeID());
116 bool isPeerIDString = (CFGetTypeID((__bridge CFTypeRef)(peerID)) == CFStringGetTypeID());
118 require_quiet(isMessageArray, xit);
119 require_quiet(isPeerIDString, xit);
121 [[KeychainSyncingOverIDSProxy idsProxy] pingDevices:idsList peerID:peerID];
123 xpc_object_t replyMessage = xpc_dictionary_create_reply(event);
124 xpc_dictionary_set_bool(replyMessage, kMessageKeyValue, true);
126 xpc_connection_send_message(peer, replyMessage);
127 secdebug(PROXYXPCSCOPE, "IDS device list sent");
129 else if (operation && !strcmp(operation, kOperationSendFragmentedIDSMessage))
131 xpc_object_t xidsMessageData = xpc_dictionary_get_value(event, kMessageKeyValue);
132 xpc_object_t xDeviceName = xpc_dictionary_get_value(event, kMessageKeyDeviceName);
133 xpc_object_t xPeerID = xpc_dictionary_get_value(event, kMessageKeyPeerID);
136 NSString *deviceName = (__bridge_transfer NSString*)(_CFXPCCreateCFObjectFromXPCObject(xDeviceName));
137 NSString *peerID = (__bridge_transfer NSString*)(_CFXPCCreateCFObjectFromXPCObject(xPeerID));
138 NSDictionary *messageDictionary = (__bridge_transfer NSDictionary*)(_CFXPCCreateCFObjectFromXPCObject(xidsMessageData));
139 NSError *error = NULL;
140 bool isNameString = (CFGetTypeID((__bridge CFTypeRef)(deviceName)) == CFStringGetTypeID());
141 bool isPeerIDString = (CFGetTypeID((__bridge CFTypeRef)(peerID)) == CFStringGetTypeID());
142 bool isMessageDictionary = (CFGetTypeID((__bridge CFTypeRef)(messageDictionary)) == CFDictionaryGetTypeID());
144 require_quiet(isNameString, xit);
145 require_quiet(isPeerIDString, xit);
146 require_quiet(isMessageDictionary, xit);
148 object = [[KeychainSyncingOverIDSProxy idsProxy] sendFragmentedIDSMessages:messageDictionary name:deviceName peer:peerID error:&error];
150 xpc_object_t replyMessage = xpc_dictionary_create_reply(event);
151 xpc_dictionary_set_bool(replyMessage, kMessageKeyValue, object);
154 xpc_object_t xerrobj = SecCreateXPCObjectWithCFError((__bridge CFErrorRef)(error));
155 xpc_dictionary_set_value(replyMessage, kMessageKeyError, xerrobj);
157 xpc_connection_send_message(peer, replyMessage);
158 secdebug(PROXYXPCSCOPE, "IDS message sent");
160 else if (operation && !strcmp(operation, kOperationSendIDSMessage)) //for IDS tests
162 xpc_object_t xidsMessageData = xpc_dictionary_get_value(event, kMessageKeyValue);
163 xpc_object_t xDeviceName = xpc_dictionary_get_value(event, kMessageKeyDeviceName);
164 xpc_object_t xPeerID = xpc_dictionary_get_value(event, kMessageKeyPeerID);
167 NSString *deviceName = (__bridge_transfer NSString*)(_CFXPCCreateCFObjectFromXPCObject(xDeviceName));
168 NSString *peerID = (__bridge_transfer NSString*)(_CFXPCCreateCFObjectFromXPCObject(xPeerID));
169 NSDictionary *messageDictionary = (__bridge_transfer NSDictionary*)(_CFXPCCreateCFObjectFromXPCObject(xidsMessageData));
170 CFErrorRef error = NULL;
171 bool isNameString = (CFGetTypeID((__bridge CFTypeRef)(deviceName)) == CFStringGetTypeID());
172 bool isPeerIDString = (CFGetTypeID((__bridge CFTypeRef)(peerID)) == CFStringGetTypeID());
173 bool isMessageDictionary = (CFGetTypeID((__bridge CFTypeRef)(messageDictionary)) == CFDictionaryGetTypeID());
175 require_quiet(isNameString, xit);
176 require_quiet(isPeerIDString, xit);
177 require_quiet(isMessageDictionary, xit);
179 NSString *localMessageIdentifier = [[NSUUID UUID] UUIDString];
180 NSMutableDictionary* messageDictionaryCopy = [NSMutableDictionary dictionaryWithDictionary:messageDictionary];
182 [messageDictionaryCopy setObject:localMessageIdentifier forKey:(__bridge NSString*)(kIDSMessageUniqueID)];
184 if([[KeychainSyncingOverIDSProxy idsProxy] sendIDSMessage:messageDictionaryCopy name:deviceName peer:peerID])
187 NSString *useAckModel = [messageDictionaryCopy objectForKey:(__bridge NSString*)(kIDSMessageUsesAckModel)];
188 if(object && [useAckModel compare:@"YES"] == NSOrderedSame){
189 secnotice("IDS Transport", "setting timer!");
190 [[KeychainSyncingOverIDSProxy idsProxy] setMessageTimer:localMessageIdentifier deviceID:deviceName message:messageDictionaryCopy];
194 SOSErrorCreate(kSecIDSErrorFailedToSend, &error, NULL, CFSTR("Failed to send keychain data message over IDS"));
195 secerror("Could not send message");
198 xpc_object_t replyMessage = xpc_dictionary_create_reply(event);
199 xpc_dictionary_set_bool(replyMessage, kMessageKeyValue, object);
202 xpc_object_t xerrobj = SecCreateXPCObjectWithCFError(error);
203 xpc_dictionary_set_value(replyMessage, kMessageKeyError, xerrobj);
205 CFReleaseNull(error);
206 xpc_connection_send_message(peer, replyMessage);
207 secdebug(PROXYXPCSCOPE, "IDS message sent");
212 char *description = xpc_copy_description(event);
213 secdebug(PROXYXPCSCOPE, "Unknown op=%s request from pid %d: %s", operation, xpc_connection_get_pid(peer), description);
219 describeXPCObject("handle_operation fail: ", event);
222 static void idskeychainsyncingproxy_peer_event_handler(xpc_connection_t peer, xpc_object_t event)
224 describeXPCObject("peer: ", peer);
225 xpc_type_t type = xpc_get_type(event);
226 if (type == XPC_TYPE_ERROR) {
227 if (event == XPC_ERROR_CONNECTION_INVALID) {
228 // The client process on the other end of the connection has either
229 // crashed or canceled the connection. After receiving this error,
230 // the connection is in an invalid state, and you do not need to
231 // call xpc_connection_cancel(). Just tear down any associated state
233 } else if (event == XPC_ERROR_TERMINATION_IMMINENT) {
234 // Handle per-connection termination cleanup.
237 assert(type == XPC_TYPE_DICTIONARY);
238 // Handle the message.
239 // describeXPCObject("dictionary:", event);
240 dispatch_async(dispatch_get_main_queue(), ^{
241 idskeychainsyncingproxy_peer_dictionary_handler(peer, event);
246 static void idskeychainsyncingproxy_event_handler(xpc_connection_t peer)
248 // By defaults, new connections will target the default dispatch
251 if (xpc_get_type(peer) != XPC_TYPE_CONNECTION)
253 secdebug(PROXYXPCSCOPE, "expected XPC_TYPE_CONNECTION");
257 xpc_connection_set_event_handler(peer, ^(xpc_object_t event)
259 idskeychainsyncingproxy_peer_event_handler(peer, event);
262 // This will tell the connection to begin listening for events. If you
263 // have some other initialization that must be done asynchronously, then
264 // you can defer this call until after that initialization is done.
265 xpc_connection_resume(peer);
268 int idsproxymain(int argc, const char *argv[])
270 secdebug(PROXYXPCSCOPE, "Starting IDSProxy");
271 char *wait4debugger = getenv("WAIT4DEBUGGER");
273 if (wait4debugger && !strcasecmp("YES", wait4debugger))
275 syslog(LOG_ERR, "Waiting for debugger");
276 kill(getpid(), SIGTSTP);
279 // DISPATCH_TARGET_QUEUE_DEFAULT
280 xpc_connection_t listener = xpc_connection_create_mach_service(xpcIDSServiceName, NULL, XPC_CONNECTION_MACH_SERVICE_LISTENER);
281 xpc_connection_set_event_handler(listener, ^(xpc_object_t object){ idskeychainsyncingproxy_event_handler(object); });
283 [KeychainSyncingOverIDSProxy idsProxy];
285 if([[KeychainSyncingOverIDSProxy idsProxy] haveMessagesInFlight] &&
286 [KeychainSyncingOverIDSProxy idsProxy].isIDSInitDone &&
287 [KeychainSyncingOverIDSProxy idsProxy].sendRestoredMessages) {
288 [[KeychainSyncingOverIDSProxy idsProxy] sendPersistedMessagesAgain];
289 [KeychainSyncingOverIDSProxy idsProxy].sendRestoredMessages = false;
292 // It looks to me like there is insufficient locking to allow a request to come in on the XPC connection while doing the initial all items.
293 // Therefore I'm leaving the XPC connection suspended until that has time to process.
294 xpc_connection_resume(listener);
298 secdebug(PROXYXPCSCOPE, "Starting mainRunLoop");
299 NSRunLoop *runLoop = [NSRunLoop mainRunLoop];
303 secdebug(PROXYXPCSCOPE, "Exiting KeychainSyncingOverIDSProxy");
308 int main(int argc, const char *argv[])
310 return idsproxymain(argc, argv);