]> git.saurik.com Git - apple/security.git/blob - keychain/otpaird/OTPairingClient.m
Security-59306.11.20.tar.gz
[apple/security.git] / keychain / otpaird / OTPairingClient.m
1 #import <TargetConditionals.h>
2
3 #if TARGET_OS_WATCH
4
5 #import <Foundation/Foundation.h>
6 #import <xpc/xpc.h>
7 #import <os/log.h>
8 #import <Security/SecXPCHelper.h>
9
10 #import "keychain/categories/NSError+UsefulConstructors.h"
11
12 #import "OTPairingClient.h"
13 #import "OTPairingConstants.h"
14
15 void
16 OTPairingInitiateWithCompletion(dispatch_queue_t queue, void (^completion)(bool success, NSError *))
17 {
18 xpc_connection_t connection;
19 xpc_object_t message;
20
21 connection = xpc_connection_create_mach_service(OTPairingMachServiceName, NULL, XPC_CONNECTION_MACH_SERVICE_PRIVILEGED);
22 xpc_connection_set_event_handler(connection, ^(__unused xpc_object_t event) {
23 });
24 xpc_connection_activate(connection);
25
26 message = xpc_dictionary_create(NULL, NULL, 0);
27 xpc_dictionary_set_uint64(message, OTPairingXPCKeyOperation, OTPairingOperationInitiate);
28
29 xpc_connection_send_message_with_reply(connection, message, queue, ^(xpc_object_t reply) {
30 if (xpc_get_type(reply) == XPC_TYPE_DICTIONARY) {
31 bool success = xpc_dictionary_get_bool(reply, OTPairingXPCKeySuccess);
32 size_t errlen = 0;
33 const void *errptr = xpc_dictionary_get_data(reply, OTPairingXPCKeyError, &errlen);
34 NSData *errordata;
35 NSError *nserr = nil;
36
37 if (errptr != NULL) {
38 errordata = [NSData dataWithBytesNoCopy:(void *)errptr length:errlen freeWhenDone:NO];
39 nserr = [SecXPCHelper errorFromEncodedData:errordata];
40 }
41
42 completion(success, nserr);
43 } else if (reply == XPC_ERROR_CONNECTION_INVALID) {
44 // This error is expected; otpaird is a NanoLaunchDaemon, only loaded when companion is paired.
45 os_log(OS_LOG_DEFAULT, "otpaird connection invalid (daemon unloaded?)");
46 completion(true, nil);
47 } else {
48 char *desc = NULL;
49 NSDictionary *userInfo = nil;
50
51 desc = xpc_copy_description(reply);
52 userInfo = @{ NSLocalizedDescriptionKey : [NSString stringWithUTF8String:desc] };
53 free(desc);
54
55 completion(false, [NSError errorWithDomain:OTPairingErrorDomain code:OTPairingErrorTypeXPC userInfo:userInfo]);
56 }
57 });
58 }
59
60 #endif /* TARGET_OS_WATCH */