Unreviewed, rolling out r223889.
[WebKit-https.git] / Source / WebKit / Shared / mac / WebCoreArgumentCodersMac.mm
1 /*
2  * Copyright (C) 2010 Apple Inc. All rights reserved.
3  * Copyright (C) 2013 Company 100 Inc. All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
15  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
16  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
18  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
19  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
20  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
21  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
22  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
23  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
24  * THE POSSIBILITY OF SUCH DAMAGE.
25  */
26
27 #import "config.h"
28 #import "WebCoreArgumentCoders.h"
29
30 #import "ArgumentCodersCF.h"
31 #import "DataReference.h"
32 #import <WebCore/CertificateInfo.h>
33 #import <WebCore/ContentFilterUnblockHandler.h>
34 #import <WebCore/Credential.h>
35 #import <WebCore/KeyboardEvent.h>
36 #import <WebCore/MachSendRight.h>
37 #import <WebCore/ProtectionSpace.h>
38 #import <WebCore/ResourceError.h>
39 #import <WebCore/ResourceRequest.h>
40 #import <pal/spi/cf/CFNetworkSPI.h>
41
42 #if USE(CFURLCONNECTION)
43 #import <CFNetwork/CFURLRequest.h>
44 #endif
45
46 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
47 #import <WebCore/MediaPlaybackTargetContext.h>
48 #import <objc/runtime.h>
49 #import <pal/spi/mac/AVFoundationSPI.h>
50 #import <wtf/SoftLinking.h>
51
52 SOFT_LINK_FRAMEWORK_OPTIONAL(AVFoundation)
53 SOFT_LINK_CLASS(AVFoundation, AVOutputContext)
54 #endif
55
56 using namespace WebCore;
57
58 namespace IPC {
59
60 static RetainPtr<CFMutableDictionaryRef> createSerializableRepresentation(CFIndex version, CFTypeRef* objects, CFIndex objectCount, CFDictionaryRef protocolProperties, CFNumberRef expectedContentLength, CFStringRef mimeType, CFTypeRef tokenNull)
61 {
62     auto archiveListArray = adoptCF(CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks));
63
64     for (CFIndex i = 0; i < objectCount; ++i) {
65         CFTypeRef object = objects[i];
66         if (object) {
67             CFArrayAppendValue(archiveListArray.get(), object);
68             CFRelease(object);
69         } else {
70             // Append our token null representation.
71             CFArrayAppendValue(archiveListArray.get(), tokenNull);
72         }
73     }
74
75     auto dictionary = adoptCF(CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
76
77     auto versionNumber = adoptCF(CFNumberCreate(kCFAllocatorDefault, kCFNumberCFIndexType, &version));
78     CFDictionarySetValue(dictionary.get(), CFSTR("version"), versionNumber.get());
79     CFDictionarySetValue(dictionary.get(), CFSTR("archiveList"), archiveListArray.get());
80
81     if (protocolProperties) {
82         CFDictionarySetValue(dictionary.get(), CFSTR("protocolProperties"), protocolProperties);
83         CFRelease(protocolProperties);
84     }
85
86     if (expectedContentLength) {
87         CFDictionarySetValue(dictionary.get(), CFSTR("expectedContentLength"), expectedContentLength);
88         CFRelease(expectedContentLength);
89     }
90
91     if (mimeType) {
92         CFDictionarySetValue(dictionary.get(), CFSTR("mimeType"), mimeType);
93         CFRelease(mimeType);
94     }
95
96     CFAllocatorDeallocate(kCFAllocatorDefault, objects);
97
98     return dictionary;
99 }
100
101 static CFTypeRef dictionaryValueOfType(CFDictionaryRef dictionary, CFStringRef key, CFTypeID type)
102 {
103     CFTypeRef value = CFDictionaryGetValue(dictionary, key);
104     if (value && CFGetTypeID(value) == type)
105         return value;
106     return nullptr;
107 }
108
109 static bool createArchiveList(CFDictionaryRef representation, CFTypeRef tokenNull, CFIndex* version, CFTypeRef** objects, CFIndex* objectCount, CFDictionaryRef* protocolProperties, CFNumberRef* expectedContentLength, CFStringRef* mimeType)
110 {
111     CFNumberRef versionNumber = (CFNumberRef)dictionaryValueOfType(representation, CFSTR("version"), CFNumberGetTypeID());
112     if (!versionNumber)
113         return false;
114
115     if (!CFNumberGetValue(versionNumber, kCFNumberCFIndexType, version))
116         return false;
117
118     CFArrayRef archiveListArray = (CFArrayRef)dictionaryValueOfType(representation, CFSTR("archiveList"), CFArrayGetTypeID());
119     if (!archiveListArray)
120         return false;
121
122     *objectCount = CFArrayGetCount(archiveListArray);
123     *objects = (CFTypeRef*)malloc(sizeof(CFTypeRef) * *objectCount);
124     for (CFIndex i = 0; i < *objectCount; ++i) {
125         CFTypeRef object = CFArrayGetValueAtIndex(archiveListArray, i);
126         if (object == tokenNull)
127             (*objects)[i] = nullptr;
128         else
129             (*objects)[i] = object;
130     }
131
132     if (protocolProperties)
133         *protocolProperties = (CFDictionaryRef)dictionaryValueOfType(representation, CFSTR("protocolProperties"), CFDictionaryGetTypeID());
134
135     if (expectedContentLength)
136         *expectedContentLength = (CFNumberRef)dictionaryValueOfType(representation, CFSTR("expectedContentLength"), CFNumberGetTypeID());
137
138     if (mimeType)
139         *mimeType = (CFStringRef)dictionaryValueOfType(representation, CFSTR("mimeType"), CFStringGetTypeID());
140
141     return true;
142 }
143
144 static RetainPtr<CFDictionaryRef> createSerializableRepresentation(CFURLRequestRef cfRequest, CFTypeRef tokenNull)
145 {
146     CFIndex version;
147     CFTypeRef* objects;
148     CFIndex objectCount;
149     CFDictionaryRef protocolProperties;
150
151     // FIXME (12889518): Do not serialize HTTP message body.
152     // 1. It can be large and thus costly to send across.
153     // 2. It is misleading to provide a body with some requests, while others use body streams, which cannot be serialized at all.
154
155     _CFURLRequestCreateArchiveList(kCFAllocatorDefault, cfRequest, &version, &objects, &objectCount, &protocolProperties);
156
157     // This will deallocate the passed in arguments.
158     return createSerializableRepresentation(version, objects, objectCount, protocolProperties, nullptr, nullptr, tokenNull);
159 }
160
161 static RetainPtr<CFURLRequestRef> createCFURLRequestFromSerializableRepresentation(CFDictionaryRef representation, CFTypeRef tokenNull)
162 {
163     CFIndex version;
164     CFTypeRef* objects;
165     CFIndex objectCount;
166     CFDictionaryRef protocolProperties;
167
168     if (!createArchiveList(representation, tokenNull, &version, &objects, &objectCount, &protocolProperties, nullptr, nullptr))
169         return nullptr;
170
171     auto cfRequest = adoptCF(_CFURLRequestCreateFromArchiveList(kCFAllocatorDefault, version, objects, objectCount, protocolProperties));
172     free(objects);
173     return WTFMove(cfRequest);
174 }
175
176 static RetainPtr<CFDictionaryRef> createSerializableRepresentation(NSURLRequest *request, CFTypeRef tokenNull)
177 {
178     return createSerializableRepresentation([request _CFURLRequest], tokenNull);
179 }
180
181 static RetainPtr<NSURLRequest> createNSURLRequestFromSerializableRepresentation(CFDictionaryRef representation, CFTypeRef tokenNull)
182 {
183     auto cfRequest = createCFURLRequestFromSerializableRepresentation(representation, tokenNull);
184     if (!cfRequest)
185         return nullptr;
186
187     return adoptNS([[NSURLRequest alloc] _initWithCFURLRequest:cfRequest.get()]);
188 }
189
190 #if USE(CFURLCONNECTION)
191 void ArgumentCoder<ResourceRequest>::encodePlatformData(Encoder& encoder, const ResourceRequest& resourceRequest)
192 {
193     RetainPtr<CFURLRequestRef> requestToSerialize = resourceRequest.cfURLRequest(DoNotUpdateHTTPBody);
194
195     bool requestIsPresent = requestToSerialize;
196     encoder << requestIsPresent;
197
198     if (!requestIsPresent)
199         return;
200
201     // We don't send HTTP body over IPC for better performance.
202     // Also, it's not always possible to do, as streams can only be created in process that does networking.
203     RetainPtr<CFDataRef> requestHTTPBody = adoptCF(CFURLRequestCopyHTTPRequestBody(requestToSerialize.get()));
204     RetainPtr<CFReadStreamRef> requestHTTPBodyStream = adoptCF(CFURLRequestCopyHTTPRequestBodyStream(requestToSerialize.get()));
205     if (requestHTTPBody || requestHTTPBodyStream) {
206         CFMutableURLRequestRef mutableRequest = CFURLRequestCreateMutableCopy(0, requestToSerialize.get());
207         requestToSerialize = adoptCF(mutableRequest);
208         CFURLRequestSetHTTPRequestBody(mutableRequest, nil);
209         CFURLRequestSetHTTPRequestBodyStream(mutableRequest, nil);
210     }
211
212     RetainPtr<CFDictionaryRef> dictionary = createSerializableRepresentation(requestToSerialize.get(), IPC::tokenNullTypeRef());
213     IPC::encode(encoder, dictionary.get());
214
215     // The fallback array is part of CFURLRequest, but it is not encoded by WKCFURLRequestCreateSerializableRepresentation.
216     encoder << resourceRequest.responseContentDispositionEncodingFallbackArray();
217     encoder.encodeEnum(resourceRequest.requester());
218     encoder.encodeEnum(resourceRequest.cachePolicy());
219 }
220 #else
221 void ArgumentCoder<ResourceRequest>::encodePlatformData(Encoder& encoder, const ResourceRequest& resourceRequest)
222 {
223     RetainPtr<NSURLRequest> requestToSerialize = resourceRequest.nsURLRequest(DoNotUpdateHTTPBody);
224
225     bool requestIsPresent = requestToSerialize;
226     encoder << requestIsPresent;
227
228     if (!requestIsPresent)
229         return;
230
231     // We don't send HTTP body over IPC for better performance.
232     // Also, it's not always possible to do, as streams can only be created in process that does networking.
233     if ([requestToSerialize HTTPBody] || [requestToSerialize HTTPBodyStream]) {
234         requestToSerialize = adoptNS([requestToSerialize mutableCopy]);
235         [(NSMutableURLRequest *)requestToSerialize setHTTPBody:nil];
236         [(NSMutableURLRequest *)requestToSerialize setHTTPBodyStream:nil];
237     }
238
239     RetainPtr<CFDictionaryRef> dictionary = createSerializableRepresentation(requestToSerialize.get(), IPC::tokenNullTypeRef());
240     IPC::encode(encoder, dictionary.get());
241
242     // The fallback array is part of NSURLRequest, but it is not encoded by WKNSURLRequestCreateSerializableRepresentation.
243     encoder << resourceRequest.responseContentDispositionEncodingFallbackArray();
244     encoder.encodeEnum(resourceRequest.requester());
245     encoder.encodeEnum(resourceRequest.cachePolicy());
246 }
247 #endif
248
249 bool ArgumentCoder<ResourceRequest>::decodePlatformData(Decoder& decoder, ResourceRequest& resourceRequest)
250 {
251     bool requestIsPresent;
252     if (!decoder.decode(requestIsPresent))
253         return false;
254
255     if (!requestIsPresent) {
256         resourceRequest = ResourceRequest();
257         return true;
258     }
259
260     RetainPtr<CFDictionaryRef> dictionary;
261     if (!IPC::decode(decoder, dictionary))
262         return false;
263
264 #if USE(CFURLCONNECTION)
265     RetainPtr<CFURLRequestRef> cfURLRequest = createCFURLRequestFromSerializableRepresentation(dictionary.get(), IPC::tokenNullTypeRef());
266     if (!cfURLRequest)
267         return false;
268
269     resourceRequest = ResourceRequest(cfURLRequest.get());
270 #else
271     RetainPtr<NSURLRequest> nsURLRequest = createNSURLRequestFromSerializableRepresentation(dictionary.get(), IPC::tokenNullTypeRef());
272     if (!nsURLRequest)
273         return false;
274
275     resourceRequest = ResourceRequest(nsURLRequest.get());
276 #endif
277     
278     Vector<String> responseContentDispositionEncodingFallbackArray;
279     if (!decoder.decode(responseContentDispositionEncodingFallbackArray))
280         return false;
281
282     resourceRequest.setResponseContentDispositionEncodingFallbackArray(
283         responseContentDispositionEncodingFallbackArray.size() > 0 ? responseContentDispositionEncodingFallbackArray[0] : String(),
284         responseContentDispositionEncodingFallbackArray.size() > 1 ? responseContentDispositionEncodingFallbackArray[1] : String(),
285         responseContentDispositionEncodingFallbackArray.size() > 2 ? responseContentDispositionEncodingFallbackArray[2] : String()
286     );
287
288     ResourceRequest::Requester requester;
289     if (!decoder.decodeEnum(requester))
290         return false;
291     resourceRequest.setRequester(requester);
292
293     ResourceRequestCachePolicy cachePolicy;
294     if (!decoder.decodeEnum(cachePolicy))
295         return false;
296     resourceRequest.setCachePolicy(cachePolicy);
297
298     return true;
299 }
300
301 void ArgumentCoder<CertificateInfo>::encode(Encoder& encoder, const CertificateInfo& certificateInfo)
302 {
303     encoder.encodeEnum(certificateInfo.type());
304
305     switch (certificateInfo.type()) {
306 #if HAVE(SEC_TRUST_SERIALIZATION)
307     case CertificateInfo::Type::Trust:
308         IPC::encode(encoder, certificateInfo.trust());
309         break;
310 #endif
311     case CertificateInfo::Type::CertificateChain:
312         IPC::encode(encoder, certificateInfo.certificateChain());
313         break;
314     case CertificateInfo::Type::None:
315         // Do nothing.
316         break;
317     }
318 }
319
320 bool ArgumentCoder<CertificateInfo>::decode(Decoder& decoder, CertificateInfo& certificateInfo)
321 {
322     CertificateInfo::Type certificateInfoType;
323     if (!decoder.decodeEnum(certificateInfoType))
324         return false;
325
326     switch (certificateInfoType) {
327 #if HAVE(SEC_TRUST_SERIALIZATION)
328     case CertificateInfo::Type::Trust: {
329         RetainPtr<SecTrustRef> trust;
330         if (!IPC::decode(decoder, trust))
331             return false;
332
333         certificateInfo = CertificateInfo(WTFMove(trust));
334         return true;
335     }
336 #endif
337     case CertificateInfo::Type::CertificateChain: {
338         RetainPtr<CFArrayRef> certificateChain;
339         if (!IPC::decode(decoder, certificateChain))
340             return false;
341
342         certificateInfo = CertificateInfo(WTFMove(certificateChain));
343         return true;
344     }    
345     case CertificateInfo::Type::None:
346         // Do nothing.
347         break;
348     }
349
350     return true;
351 }
352
353 static void encodeNSError(Encoder& encoder, NSError *nsError)
354 {
355     String domain = [nsError domain];
356     encoder << domain;
357
358     int64_t code = [nsError code];
359     encoder << code;
360
361     NSDictionary *userInfo = [nsError userInfo];
362
363     RetainPtr<CFMutableDictionaryRef> filteredUserInfo = adoptCF(CFDictionaryCreateMutable(kCFAllocatorDefault, userInfo.count, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
364
365     [userInfo enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL*) {
366         if ([value isKindOfClass:[NSString class]] || [value isKindOfClass:[NSURL class]] || [value isKindOfClass:[NSNumber class]])
367             CFDictionarySetValue(filteredUserInfo.get(), key, value);
368     }];
369
370     if (NSArray *clientIdentityAndCertificates = [userInfo objectForKey:@"NSErrorClientCertificateChainKey"]) {
371         ASSERT([clientIdentityAndCertificates isKindOfClass:[NSArray class]]);
372         ASSERT(^{
373             for (id object in clientIdentityAndCertificates) {
374                 if (CFGetTypeID(object) != SecIdentityGetTypeID() && CFGetTypeID(object) != SecCertificateGetTypeID())
375                     return false;
376             }
377             return true;
378         }());
379
380         CFDictionarySetValue(filteredUserInfo.get(), @"NSErrorClientCertificateChainKey", clientIdentityAndCertificates);
381     }
382
383     id peerCertificateChain = [userInfo objectForKey:@"NSErrorPeerCertificateChainKey"];
384     if (!peerCertificateChain) {
385         if (SecTrustRef peerTrust = (SecTrustRef)[userInfo objectForKey:NSURLErrorFailingURLPeerTrustErrorKey]) {
386             CFIndex count = SecTrustGetCertificateCount(peerTrust);
387             peerCertificateChain = [NSMutableArray arrayWithCapacity:count];
388             for (CFIndex i = 0; i < count; ++i)
389                 [peerCertificateChain addObject:(id)SecTrustGetCertificateAtIndex(peerTrust, i)];
390         }
391     }
392     ASSERT(!peerCertificateChain || [peerCertificateChain isKindOfClass:[NSArray class]]);
393     if (peerCertificateChain)
394         CFDictionarySetValue(filteredUserInfo.get(), @"NSErrorPeerCertificateChainKey", peerCertificateChain);
395
396 #if HAVE(SEC_TRUST_SERIALIZATION)
397     if (SecTrustRef peerTrust = (SecTrustRef)[userInfo objectForKey:NSURLErrorFailingURLPeerTrustErrorKey])
398         CFDictionarySetValue(filteredUserInfo.get(), NSURLErrorFailingURLPeerTrustErrorKey, peerTrust);
399 #endif
400
401     IPC::encode(encoder, filteredUserInfo.get());
402
403     if (id underlyingError = [userInfo objectForKey:NSUnderlyingErrorKey]) {
404         ASSERT([underlyingError isKindOfClass:[NSError class]]);
405         encoder << true;
406         encodeNSError(encoder, underlyingError);
407     } else
408         encoder << false;
409 }
410
411 void ArgumentCoder<ResourceError>::encodePlatformData(Encoder& encoder, const ResourceError& resourceError)
412 {
413     bool errorIsNull = resourceError.isNull();
414     encoder << errorIsNull;
415
416     if (errorIsNull)
417         return;
418
419     NSError *nsError = resourceError.nsError();
420     encodeNSError(encoder, nsError);
421 }
422
423 static bool decodeNSError(Decoder& decoder, RetainPtr<NSError>& nsError)
424 {
425     String domain;
426     if (!decoder.decode(domain))
427         return false;
428
429     int64_t code;
430     if (!decoder.decode(code))
431         return false;
432
433     RetainPtr<CFDictionaryRef> userInfo;
434     if (!IPC::decode(decoder, userInfo))
435         return false;
436
437     bool hasUnderlyingError = false;
438     if (!decoder.decode(hasUnderlyingError))
439         return false;
440
441     if (hasUnderlyingError) {
442         RetainPtr<NSError> underlyingNSError;
443         if (!decodeNSError(decoder, underlyingNSError))
444             return false;
445
446         userInfo = adoptCF(CFDictionaryCreateMutableCopy(kCFAllocatorDefault, CFDictionaryGetCount(userInfo.get()) + 1, userInfo.get()));
447         CFDictionarySetValue((CFMutableDictionaryRef)userInfo.get(), NSUnderlyingErrorKey, underlyingNSError.get());
448     }
449
450     nsError = adoptNS([[NSError alloc] initWithDomain:domain code:code userInfo:(NSDictionary *)userInfo.get()]);
451     return true;
452 }
453
454 bool ArgumentCoder<ResourceError>::decodePlatformData(Decoder& decoder, ResourceError& resourceError)
455 {
456     bool errorIsNull;
457     if (!decoder.decode(errorIsNull))
458         return false;
459     
460     if (errorIsNull) {
461         resourceError = ResourceError();
462         return true;
463     }
464     
465     RetainPtr<NSError> nsError;
466     if (!decodeNSError(decoder, nsError))
467         return false;
468
469     resourceError = ResourceError(nsError.get());
470     return true;
471 }
472
473 void ArgumentCoder<ProtectionSpace>::encodePlatformData(Encoder& encoder, const ProtectionSpace& space)
474 {
475     RetainPtr<NSMutableData> data = adoptNS([[NSMutableData alloc] init]);
476     RetainPtr<NSKeyedArchiver> archiver = adoptNS([[NSKeyedArchiver alloc] initForWritingWithMutableData:data.get()]);
477     [archiver setRequiresSecureCoding:YES];
478     [archiver encodeObject:space.nsSpace() forKey:@"protectionSpace"];
479     [archiver finishEncoding];
480     IPC::encode(encoder, reinterpret_cast<CFDataRef>(data.get()));
481 }
482
483 bool ArgumentCoder<ProtectionSpace>::decodePlatformData(Decoder& decoder, ProtectionSpace& space)
484 {
485     RetainPtr<CFDataRef> data;
486     if (!IPC::decode(decoder, data))
487         return false;
488
489     RetainPtr<NSKeyedUnarchiver> unarchiver = adoptNS([[NSKeyedUnarchiver alloc] initForReadingWithData:(NSData *)data.get()]);
490     [unarchiver setRequiresSecureCoding:YES];
491     @try {
492         if (RetainPtr<NSURLProtectionSpace> nsSpace = [unarchiver decodeObjectOfClass:[NSURLProtectionSpace class] forKey:@"protectionSpace"])
493             space = ProtectionSpace(nsSpace.get());
494     } @catch (NSException *exception) {
495         LOG_ERROR("Failed to decode NSURLProtectionSpace: %@", exception);
496     }
497
498     [unarchiver finishDecoding];
499     return true;
500 }
501
502 void ArgumentCoder<Credential>::encodePlatformData(Encoder& encoder, const Credential& credential)
503 {
504     NSURLCredential *nsCredential = credential.nsCredential();
505     // NSURLCredential doesn't serialize identities correctly, so we encode the pieces individually
506     // in the identity case. See <rdar://problem/18802434>.
507     if (SecIdentityRef identity = nsCredential.identity) {
508         encoder << true;
509         IPC::encode(encoder, identity);
510
511         if (NSArray *certificates = nsCredential.certificates) {
512             encoder << true;
513             IPC::encode(encoder, reinterpret_cast<CFArrayRef>(certificates));
514         } else
515             encoder << false;
516
517         encoder << static_cast<uint64_t>(nsCredential.persistence);
518         return;
519     }
520
521     encoder << false;
522     RetainPtr<NSMutableData> data = adoptNS([[NSMutableData alloc] init]);
523     RetainPtr<NSKeyedArchiver> archiver = adoptNS([[NSKeyedArchiver alloc] initForWritingWithMutableData:data.get()]);
524     [archiver setRequiresSecureCoding:YES];
525     [archiver encodeObject:nsCredential forKey:@"credential"];
526     [archiver finishEncoding];
527     IPC::encode(encoder, reinterpret_cast<CFDataRef>(data.get()));
528 }
529
530 bool ArgumentCoder<Credential>::decodePlatformData(Decoder& decoder, Credential& credential)
531 {
532     bool hasIdentity;
533     if (!decoder.decode(hasIdentity))
534         return false;
535
536     if (hasIdentity) {
537         RetainPtr<SecIdentityRef> identity;
538         if (!IPC::decode(decoder, identity))
539             return false;
540
541         RetainPtr<CFArrayRef> certificates;
542         bool hasCertificates;
543         if (!decoder.decode(hasCertificates))
544             return false;
545
546         if (hasCertificates) {
547             if (!IPC::decode(decoder, certificates))
548                 return false;
549         }
550
551         uint64_t persistence;
552         if (!decoder.decode(persistence))
553             return false;
554
555         credential = Credential(adoptNS([[NSURLCredential alloc] initWithIdentity:identity.get() certificates:(NSArray *)certificates.get() persistence:(NSURLCredentialPersistence)persistence]).get());
556         return true;
557     }
558
559     RetainPtr<CFDataRef> data;
560     if (!IPC::decode(decoder, data))
561         return false;
562
563     RetainPtr<NSKeyedUnarchiver> unarchiver = adoptNS([[NSKeyedUnarchiver alloc] initForReadingWithData:(NSData *)data.get()]);
564     [unarchiver setRequiresSecureCoding:YES];
565     @try {
566         if (RetainPtr<NSURLCredential> nsCredential = [unarchiver decodeObjectOfClass:[NSURLCredential class] forKey:@"credential"])
567             credential = Credential(nsCredential.get());
568     } @catch (NSException *exception) {
569         LOG_ERROR("Failed to decode NSURLCredential: %@", exception);
570     }
571
572     [unarchiver finishDecoding];
573     return true;
574 }
575
576 void ArgumentCoder<MachSendRight>::encode(Encoder& encoder, const MachSendRight& sendRight)
577 {
578     encoder << Attachment(sendRight.copySendRight().leakSendRight(), MACH_MSG_TYPE_MOVE_SEND);
579 }
580
581 void ArgumentCoder<MachSendRight>::encode(Encoder& encoder, MachSendRight&& sendRight)
582 {
583     encoder << Attachment(sendRight.leakSendRight(), MACH_MSG_TYPE_MOVE_SEND);
584 }
585
586 bool ArgumentCoder<MachSendRight>::decode(Decoder& decoder, MachSendRight& sendRight)
587 {
588     Attachment attachment;
589     if (!decoder.decode(attachment))
590         return false;
591
592     if (attachment.disposition() != MACH_MSG_TYPE_MOVE_SEND)
593         return false;
594
595     sendRight = MachSendRight::adopt(attachment.port());
596     return true;
597 }
598
599 void ArgumentCoder<KeypressCommand>::encode(Encoder& encoder, const KeypressCommand& keypressCommand)
600 {
601     encoder << keypressCommand.commandName << keypressCommand.text;
602 }
603     
604 std::optional<KeypressCommand> ArgumentCoder<KeypressCommand>::decode(Decoder& decoder)
605 {
606     std::optional<String> commandName;
607     decoder >> commandName;
608     if (!commandName)
609         return std::nullopt;
610     
611     std::optional<String> text;
612     decoder >> text;
613     if (!text)
614         return std::nullopt;
615     
616     KeypressCommand command;
617     command.commandName = WTFMove(*commandName);
618     command.text = WTFMove(*text);
619     return WTFMove(command);
620 }
621
622 #if ENABLE(CONTENT_FILTERING)
623 void ArgumentCoder<ContentFilterUnblockHandler>::encode(Encoder& encoder, const ContentFilterUnblockHandler& contentFilterUnblockHandler)
624 {
625     RetainPtr<NSMutableData> data = adoptNS([[NSMutableData alloc] init]);
626     RetainPtr<NSKeyedArchiver> archiver = adoptNS([[NSKeyedArchiver alloc] initForWritingWithMutableData:data.get()]);
627     [archiver setRequiresSecureCoding:YES];
628     contentFilterUnblockHandler.encode(archiver.get());
629     [archiver finishEncoding];
630     IPC::encode(encoder, reinterpret_cast<CFDataRef>(data.get()));
631 }
632
633 bool ArgumentCoder<ContentFilterUnblockHandler>::decode(Decoder& decoder, ContentFilterUnblockHandler& contentFilterUnblockHandler)
634 {
635     RetainPtr<CFDataRef> data;
636     if (!IPC::decode(decoder, data))
637         return false;
638
639     RetainPtr<NSKeyedUnarchiver> unarchiver = adoptNS([[NSKeyedUnarchiver alloc] initForReadingWithData:(NSData *)data.get()]);
640     [unarchiver setRequiresSecureCoding:YES];
641     if (!ContentFilterUnblockHandler::decode(unarchiver.get(), contentFilterUnblockHandler))
642         return false;
643
644     [unarchiver finishDecoding];
645     return true;
646 }
647 #endif
648
649 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
650
651 static NSString *deviceContextKey()
652 {
653     static NSString * const key = @"deviceContext";
654     return key;
655 }
656
657 void ArgumentCoder<MediaPlaybackTargetContext>::encodePlatformData(Encoder& encoder, const MediaPlaybackTargetContext& target)
658 {
659     RetainPtr<NSMutableData> data = adoptNS([[NSMutableData alloc] init]);
660     RetainPtr<NSKeyedArchiver> archiver = adoptNS([[NSKeyedArchiver alloc] initForWritingWithMutableData:data.get()]);
661     [archiver setRequiresSecureCoding:YES];
662
663     if ([getAVOutputContextClass() conformsToProtocol:@protocol(NSSecureCoding)])
664         [archiver encodeObject:target.avOutputContext() forKey:deviceContextKey()];
665
666     [archiver finishEncoding];
667     IPC::encode(encoder, reinterpret_cast<CFDataRef>(data.get()));
668
669 }
670
671 bool ArgumentCoder<MediaPlaybackTargetContext>::decodePlatformData(Decoder& decoder, MediaPlaybackTargetContext& target)
672 {
673     if (![getAVOutputContextClass() conformsToProtocol:@protocol(NSSecureCoding)])
674         return false;
675
676     RetainPtr<CFDataRef> data;
677     if (!IPC::decode(decoder, data))
678         return false;
679
680     RetainPtr<NSKeyedUnarchiver> unarchiver = adoptNS([[NSKeyedUnarchiver alloc] initForReadingWithData:(NSData *)data.get()]);
681     [unarchiver setRequiresSecureCoding:YES];
682
683     AVOutputContext *context = nil;
684     @try {
685         context = [unarchiver decodeObjectOfClass:getAVOutputContextClass() forKey:deviceContextKey()];
686     } @catch (NSException *exception) {
687         LOG_ERROR("The target picker being decoded is not an AVOutputContext.");
688         return false;
689     }
690
691     target = MediaPlaybackTargetContext(context);
692     
693     [unarchiver finishDecoding];
694     return true;
695 }
696 #endif
697
698 } // namespace IPC