8e36965230576868d495ddb96b86006972ae4c66
[WebKit-https.git] / Source / WebKit / Shared / mac / WebCoreArgumentCodersMac.mm
1 /*
2  * Copyright (C) 2010-2018 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/ProtectionSpace.h>
37 #import <WebCore/ResourceError.h>
38 #import <WebCore/ResourceRequest.h>
39 #import <pal/spi/cf/CFNetworkSPI.h>
40 #import <pal/spi/cocoa/NSKeyedArchiverSPI.h>
41 #import <wtf/MachSendRight.h>
42
43 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
44 #import <WebCore/MediaPlaybackTargetContext.h>
45 #import <objc/runtime.h>
46 #import <pal/spi/mac/AVFoundationSPI.h>
47 #import <wtf/SoftLinking.h>
48
49 SOFT_LINK_FRAMEWORK_OPTIONAL(AVFoundation)
50 SOFT_LINK_CLASS(AVFoundation, AVOutputContext)
51 #endif
52
53 namespace IPC {
54
55 static RetainPtr<CFMutableDictionaryRef> createSerializableRepresentation(CFIndex version, CFTypeRef* objects, CFIndex objectCount, CFDictionaryRef protocolProperties, CFNumberRef expectedContentLength, CFStringRef mimeType, CFTypeRef tokenNull)
56 {
57     auto archiveListArray = adoptCF(CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks));
58
59     for (CFIndex i = 0; i < objectCount; ++i) {
60         CFTypeRef object = objects[i];
61         if (object) {
62             CFArrayAppendValue(archiveListArray.get(), object);
63             CFRelease(object);
64         } else {
65             // Append our token null representation.
66             CFArrayAppendValue(archiveListArray.get(), tokenNull);
67         }
68     }
69
70     auto dictionary = adoptCF(CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
71
72     auto versionNumber = adoptCF(CFNumberCreate(kCFAllocatorDefault, kCFNumberCFIndexType, &version));
73     CFDictionarySetValue(dictionary.get(), CFSTR("version"), versionNumber.get());
74     CFDictionarySetValue(dictionary.get(), CFSTR("archiveList"), archiveListArray.get());
75
76     if (protocolProperties) {
77         CFDictionarySetValue(dictionary.get(), CFSTR("protocolProperties"), protocolProperties);
78         CFRelease(protocolProperties);
79     }
80
81     if (expectedContentLength) {
82         CFDictionarySetValue(dictionary.get(), CFSTR("expectedContentLength"), expectedContentLength);
83         CFRelease(expectedContentLength);
84     }
85
86     if (mimeType) {
87         CFDictionarySetValue(dictionary.get(), CFSTR("mimeType"), mimeType);
88         CFRelease(mimeType);
89     }
90
91     CFAllocatorDeallocate(kCFAllocatorDefault, objects);
92
93     return dictionary;
94 }
95
96 static CFTypeRef dictionaryValueOfType(CFDictionaryRef dictionary, CFStringRef key, CFTypeID type)
97 {
98     CFTypeRef value = CFDictionaryGetValue(dictionary, key);
99     if (value && CFGetTypeID(value) == type)
100         return value;
101     return nullptr;
102 }
103
104 static bool createArchiveList(CFDictionaryRef representation, CFTypeRef tokenNull, CFIndex* version, CFTypeRef** objects, CFIndex* objectCount, CFDictionaryRef* protocolProperties, CFNumberRef* expectedContentLength, CFStringRef* mimeType)
105 {
106     CFNumberRef versionNumber = (CFNumberRef)dictionaryValueOfType(representation, CFSTR("version"), CFNumberGetTypeID());
107     if (!versionNumber)
108         return false;
109
110     if (!CFNumberGetValue(versionNumber, kCFNumberCFIndexType, version))
111         return false;
112
113     CFArrayRef archiveListArray = (CFArrayRef)dictionaryValueOfType(representation, CFSTR("archiveList"), CFArrayGetTypeID());
114     if (!archiveListArray)
115         return false;
116
117     *objectCount = CFArrayGetCount(archiveListArray);
118     *objects = (CFTypeRef*)malloc(sizeof(CFTypeRef) * *objectCount);
119     for (CFIndex i = 0; i < *objectCount; ++i) {
120         CFTypeRef object = CFArrayGetValueAtIndex(archiveListArray, i);
121         if (object == tokenNull)
122             (*objects)[i] = nullptr;
123         else
124             (*objects)[i] = object;
125     }
126
127     if (protocolProperties)
128         *protocolProperties = (CFDictionaryRef)dictionaryValueOfType(representation, CFSTR("protocolProperties"), CFDictionaryGetTypeID());
129
130     if (expectedContentLength)
131         *expectedContentLength = (CFNumberRef)dictionaryValueOfType(representation, CFSTR("expectedContentLength"), CFNumberGetTypeID());
132
133     if (mimeType)
134         *mimeType = (CFStringRef)dictionaryValueOfType(representation, CFSTR("mimeType"), CFStringGetTypeID());
135
136     return true;
137 }
138
139 static RetainPtr<CFDictionaryRef> createSerializableRepresentation(CFURLRequestRef cfRequest, CFTypeRef tokenNull)
140 {
141     CFIndex version;
142     CFTypeRef* objects;
143     CFIndex objectCount;
144     CFDictionaryRef protocolProperties;
145
146     // FIXME (12889518): Do not serialize HTTP message body.
147     // 1. It can be large and thus costly to send across.
148     // 2. It is misleading to provide a body with some requests, while others use body streams, which cannot be serialized at all.
149
150     _CFURLRequestCreateArchiveList(kCFAllocatorDefault, cfRequest, &version, &objects, &objectCount, &protocolProperties);
151
152     // This will deallocate the passed in arguments.
153     return createSerializableRepresentation(version, objects, objectCount, protocolProperties, nullptr, nullptr, tokenNull);
154 }
155
156 static RetainPtr<CFURLRequestRef> createCFURLRequestFromSerializableRepresentation(CFDictionaryRef representation, CFTypeRef tokenNull)
157 {
158     CFIndex version;
159     CFTypeRef* objects;
160     CFIndex objectCount;
161     CFDictionaryRef protocolProperties;
162
163     if (!createArchiveList(representation, tokenNull, &version, &objects, &objectCount, &protocolProperties, nullptr, nullptr))
164         return nullptr;
165
166     auto cfRequest = adoptCF(_CFURLRequestCreateFromArchiveList(kCFAllocatorDefault, version, objects, objectCount, protocolProperties));
167     free(objects);
168     return WTFMove(cfRequest);
169 }
170
171 static RetainPtr<CFDictionaryRef> createSerializableRepresentation(NSURLRequest *request, CFTypeRef tokenNull)
172 {
173     return createSerializableRepresentation([request _CFURLRequest], tokenNull);
174 }
175
176 static RetainPtr<NSURLRequest> createNSURLRequestFromSerializableRepresentation(CFDictionaryRef representation, CFTypeRef tokenNull)
177 {
178     auto cfRequest = createCFURLRequestFromSerializableRepresentation(representation, tokenNull);
179     if (!cfRequest)
180         return nullptr;
181     
182     return adoptNS([[NSURLRequest alloc] _initWithCFURLRequest:cfRequest.get()]);
183 }
184     
185 void ArgumentCoder<WebCore::ResourceRequest>::encodePlatformData(Encoder& encoder, const WebCore::ResourceRequest& resourceRequest)
186 {
187     RetainPtr<NSURLRequest> requestToSerialize = resourceRequest.nsURLRequest(WebCore::HTTPBodyUpdatePolicy::DoNotUpdateHTTPBody);
188
189     bool requestIsPresent = requestToSerialize;
190     encoder << requestIsPresent;
191
192     if (!requestIsPresent)
193         return;
194
195     // We don't send HTTP body over IPC for better performance.
196     // Also, it's not always possible to do, as streams can only be created in process that does networking.
197     if ([requestToSerialize HTTPBody] || [requestToSerialize HTTPBodyStream]) {
198         requestToSerialize = adoptNS([requestToSerialize mutableCopy]);
199         [(NSMutableURLRequest *)requestToSerialize setHTTPBody:nil];
200         [(NSMutableURLRequest *)requestToSerialize setHTTPBodyStream:nil];
201     }
202
203     RetainPtr<CFDictionaryRef> dictionary = createSerializableRepresentation(requestToSerialize.get(), IPC::tokenNullTypeRef());
204     IPC::encode(encoder, dictionary.get());
205
206     // The fallback array is part of NSURLRequest, but it is not encoded by WKNSURLRequestCreateSerializableRepresentation.
207     encoder << resourceRequest.responseContentDispositionEncodingFallbackArray();
208     encoder.encodeEnum(resourceRequest.requester());
209     encoder.encodeEnum(resourceRequest.cachePolicy());
210 }
211
212 bool ArgumentCoder<WebCore::ResourceRequest>::decodePlatformData(Decoder& decoder, WebCore::ResourceRequest& resourceRequest)
213 {
214     bool requestIsPresent;
215     if (!decoder.decode(requestIsPresent))
216         return false;
217
218     if (!requestIsPresent) {
219         resourceRequest = WebCore::ResourceRequest();
220         return true;
221     }
222
223     RetainPtr<CFDictionaryRef> dictionary;
224     if (!IPC::decode(decoder, dictionary))
225         return false;
226
227     RetainPtr<NSURLRequest> nsURLRequest = createNSURLRequestFromSerializableRepresentation(dictionary.get(), IPC::tokenNullTypeRef());
228     if (!nsURLRequest)
229         return false;
230
231     resourceRequest = WebCore::ResourceRequest(nsURLRequest.get());
232     
233     Vector<String> responseContentDispositionEncodingFallbackArray;
234     if (!decoder.decode(responseContentDispositionEncodingFallbackArray))
235         return false;
236
237     resourceRequest.setResponseContentDispositionEncodingFallbackArray(
238         responseContentDispositionEncodingFallbackArray.size() > 0 ? responseContentDispositionEncodingFallbackArray[0] : String(),
239         responseContentDispositionEncodingFallbackArray.size() > 1 ? responseContentDispositionEncodingFallbackArray[1] : String(),
240         responseContentDispositionEncodingFallbackArray.size() > 2 ? responseContentDispositionEncodingFallbackArray[2] : String()
241     );
242
243     WebCore::ResourceRequest::Requester requester;
244     if (!decoder.decodeEnum(requester))
245         return false;
246     resourceRequest.setRequester(requester);
247
248     WebCore::ResourceRequestCachePolicy cachePolicy;
249     if (!decoder.decodeEnum(cachePolicy))
250         return false;
251     resourceRequest.setCachePolicy(cachePolicy);
252
253     return true;
254 }
255
256 void ArgumentCoder<WebCore::CertificateInfo>::encode(Encoder& encoder, const WebCore::CertificateInfo& certificateInfo)
257 {
258     encoder.encodeEnum(certificateInfo.type());
259
260     switch (certificateInfo.type()) {
261 #if HAVE(SEC_TRUST_SERIALIZATION)
262     case WebCore::CertificateInfo::Type::Trust:
263         IPC::encode(encoder, certificateInfo.trust());
264         break;
265 #endif
266     case WebCore::CertificateInfo::Type::CertificateChain:
267         IPC::encode(encoder, certificateInfo.certificateChain());
268         break;
269     case WebCore::CertificateInfo::Type::None:
270         // Do nothing.
271         break;
272     }
273 }
274
275 bool ArgumentCoder<WebCore::CertificateInfo>::decode(Decoder& decoder, WebCore::CertificateInfo& certificateInfo)
276 {
277     WebCore::CertificateInfo::Type certificateInfoType;
278     if (!decoder.decodeEnum(certificateInfoType))
279         return false;
280
281     switch (certificateInfoType) {
282 #if HAVE(SEC_TRUST_SERIALIZATION)
283     case WebCore::CertificateInfo::Type::Trust: {
284         RetainPtr<SecTrustRef> trust;
285         if (!IPC::decode(decoder, trust))
286             return false;
287
288         certificateInfo = WebCore::CertificateInfo(WTFMove(trust));
289         return true;
290     }
291 #endif
292     case WebCore::CertificateInfo::Type::CertificateChain: {
293         RetainPtr<CFArrayRef> certificateChain;
294         if (!IPC::decode(decoder, certificateChain))
295             return false;
296
297         certificateInfo = WebCore::CertificateInfo(WTFMove(certificateChain));
298         return true;
299     }    
300     case WebCore::CertificateInfo::Type::None:
301         // Do nothing.
302         break;
303     }
304
305     return true;
306 }
307
308 static void encodeNSError(Encoder& encoder, NSError *nsError)
309 {
310     String domain = [nsError domain];
311     encoder << domain;
312
313     int64_t code = [nsError code];
314     encoder << code;
315
316     NSDictionary *userInfo = [nsError userInfo];
317
318     RetainPtr<CFMutableDictionaryRef> filteredUserInfo = adoptCF(CFDictionaryCreateMutable(kCFAllocatorDefault, userInfo.count, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
319
320     [userInfo enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL*) {
321         if ([value isKindOfClass:[NSString class]] || [value isKindOfClass:[NSURL class]] || [value isKindOfClass:[NSNumber class]])
322             CFDictionarySetValue(filteredUserInfo.get(), (__bridge CFTypeRef)key, (__bridge CFTypeRef)value);
323     }];
324
325     if (NSArray *clientIdentityAndCertificates = [userInfo objectForKey:@"NSErrorClientCertificateChainKey"]) {
326         ASSERT([clientIdentityAndCertificates isKindOfClass:[NSArray class]]);
327         ASSERT(^{
328             for (id object in clientIdentityAndCertificates) {
329                 if (CFGetTypeID((__bridge CFTypeRef)object) != SecIdentityGetTypeID() && CFGetTypeID((__bridge CFTypeRef)object) != SecCertificateGetTypeID())
330                     return false;
331             }
332             return true;
333         }());
334
335         // Turn SecIdentity members into SecCertificate to strip out private key information.
336         id clientCertificates = [NSMutableArray arrayWithCapacity:clientIdentityAndCertificates.count];
337         for (id object in clientIdentityAndCertificates) {
338             if (CFGetTypeID((__bridge CFTypeRef)object) != SecIdentityGetTypeID()) {
339                 [clientCertificates addObject:object];
340                 continue;
341             }
342             SecCertificateRef certificate = nil;
343             OSStatus status = SecIdentityCopyCertificate((SecIdentityRef)object, &certificate);
344             RetainPtr<SecCertificateRef> retainCertificate = adoptCF(certificate);
345             // The SecIdentity member is the key information of this attribute. Without it, we should nil
346             // the attribute.
347             if (status != errSecSuccess) {
348                 LOG_ERROR("Failed to encode nsError.userInfo[NSErrorClientCertificateChainKey]: %d", status);
349                 clientCertificates = nil;
350                 break;
351             }
352             [clientCertificates addObject:(__bridge id)certificate];
353         }
354         CFDictionarySetValue(filteredUserInfo.get(), CFSTR("NSErrorClientCertificateChainKey"), (__bridge CFTypeRef)clientCertificates);
355     }
356
357     id peerCertificateChain = [userInfo objectForKey:@"NSErrorPeerCertificateChainKey"];
358     if (!peerCertificateChain) {
359         if (SecTrustRef peerTrust = (__bridge SecTrustRef)[userInfo objectForKey:NSURLErrorFailingURLPeerTrustErrorKey]) {
360             CFIndex count = SecTrustGetCertificateCount(peerTrust);
361             peerCertificateChain = [NSMutableArray arrayWithCapacity:count];
362             for (CFIndex i = 0; i < count; ++i)
363                 [peerCertificateChain addObject:(__bridge id)SecTrustGetCertificateAtIndex(peerTrust, i)];
364         }
365     }
366     ASSERT(!peerCertificateChain || [peerCertificateChain isKindOfClass:[NSArray class]]);
367     if (peerCertificateChain)
368         CFDictionarySetValue(filteredUserInfo.get(), CFSTR("NSErrorPeerCertificateChainKey"), (__bridge CFTypeRef)peerCertificateChain);
369
370 #if HAVE(SEC_TRUST_SERIALIZATION)
371     if (SecTrustRef peerTrust = (__bridge SecTrustRef)[userInfo objectForKey:NSURLErrorFailingURLPeerTrustErrorKey])
372         CFDictionarySetValue(filteredUserInfo.get(), (__bridge CFStringRef)NSURLErrorFailingURLPeerTrustErrorKey, peerTrust);
373 #endif
374
375     IPC::encode(encoder, filteredUserInfo.get());
376
377     if (id underlyingError = [userInfo objectForKey:NSUnderlyingErrorKey]) {
378         ASSERT([underlyingError isKindOfClass:[NSError class]]);
379         encoder << true;
380         encodeNSError(encoder, underlyingError);
381     } else
382         encoder << false;
383 }
384
385 void ArgumentCoder<WebCore::ResourceError>::encodePlatformData(Encoder& encoder, const WebCore::ResourceError& resourceError)
386 {
387     encodeNSError(encoder, resourceError.nsError());
388 }
389
390 static bool decodeNSError(Decoder& decoder, RetainPtr<NSError>& nsError)
391 {
392     String domain;
393     if (!decoder.decode(domain))
394         return false;
395
396     int64_t code;
397     if (!decoder.decode(code))
398         return false;
399
400     RetainPtr<CFDictionaryRef> userInfo;
401     if (!IPC::decode(decoder, userInfo))
402         return false;
403
404     bool hasUnderlyingError = false;
405     if (!decoder.decode(hasUnderlyingError))
406         return false;
407
408     if (hasUnderlyingError) {
409         RetainPtr<NSError> underlyingNSError;
410         if (!decodeNSError(decoder, underlyingNSError))
411             return false;
412
413         auto mutableUserInfo = adoptCF(CFDictionaryCreateMutableCopy(kCFAllocatorDefault, CFDictionaryGetCount(userInfo.get()) + 1, userInfo.get()));
414         CFDictionarySetValue(mutableUserInfo.get(), (__bridge CFStringRef)NSUnderlyingErrorKey, (__bridge CFTypeRef)underlyingNSError.get());
415         userInfo = WTFMove(mutableUserInfo);
416     }
417
418     nsError = adoptNS([[NSError alloc] initWithDomain:domain code:code userInfo:(__bridge NSDictionary *)userInfo.get()]);
419     return true;
420 }
421
422 bool ArgumentCoder<WebCore::ResourceError>::decodePlatformData(Decoder& decoder, WebCore::ResourceError& resourceError)
423 {
424     RetainPtr<NSError> nsError;
425     if (!decodeNSError(decoder, nsError))
426         return false;
427
428     resourceError = WebCore::ResourceError(nsError.get());
429     return true;
430 }
431
432 void ArgumentCoder<WebCore::ProtectionSpace>::encodePlatformData(Encoder& encoder, const WebCore::ProtectionSpace& space)
433 {
434     auto archiver = secureArchiver();
435     [archiver encodeObject:space.nsSpace() forKey:@"protectionSpace"];
436     IPC::encode(encoder, (__bridge CFDataRef)archiver.get().encodedData);
437 }
438
439 bool ArgumentCoder<WebCore::ProtectionSpace>::decodePlatformData(Decoder& decoder, WebCore::ProtectionSpace& space)
440 {
441     RetainPtr<CFDataRef> data;
442     if (!IPC::decode(decoder, data))
443         return false;
444
445     auto unarchiver = secureUnarchiverFromData((__bridge NSData *)data.get());
446     @try {
447         if (RetainPtr<NSURLProtectionSpace> nsSpace = [unarchiver decodeObjectOfClass:[NSURLProtectionSpace class] forKey:@"protectionSpace"])
448             space = WebCore::ProtectionSpace(nsSpace.get());
449     } @catch (NSException *exception) {
450         LOG_ERROR("Failed to decode NSURLProtectionSpace: %@", exception);
451     }
452
453     [unarchiver finishDecoding];
454     return true;
455 }
456
457 void ArgumentCoder<WebCore::Credential>::encodePlatformData(Encoder& encoder, const WebCore::Credential& credential)
458 {
459     NSURLCredential *nsCredential = credential.nsCredential();
460     // NSURLCredential doesn't serialize identities correctly, so we encode the pieces individually
461     // in the identity case. See <rdar://problem/18802434>.
462     if (SecIdentityRef identity = nsCredential.identity) {
463         encoder << true;
464         IPC::encode(encoder, identity);
465
466         if (NSArray *certificates = nsCredential.certificates) {
467             encoder << true;
468             IPC::encode(encoder, (__bridge CFArrayRef)certificates);
469         } else
470             encoder << false;
471
472         encoder << static_cast<uint64_t>(nsCredential.persistence);
473         return;
474     }
475
476     encoder << false;
477
478     auto archiver = secureArchiver();
479     [archiver encodeObject:nsCredential forKey:@"credential"];
480     IPC::encode(encoder, (__bridge CFDataRef)archiver.get().encodedData);
481 }
482
483 bool ArgumentCoder<WebCore::Credential>::decodePlatformData(Decoder& decoder, WebCore::Credential& credential)
484 {
485     bool hasIdentity;
486     if (!decoder.decode(hasIdentity))
487         return false;
488
489     if (hasIdentity) {
490         RetainPtr<SecIdentityRef> identity;
491         if (!IPC::decode(decoder, identity))
492             return false;
493
494         RetainPtr<CFArrayRef> certificates;
495         bool hasCertificates;
496         if (!decoder.decode(hasCertificates))
497             return false;
498
499         if (hasCertificates) {
500             if (!IPC::decode(decoder, certificates))
501                 return false;
502         }
503
504         uint64_t persistence;
505         if (!decoder.decode(persistence))
506             return false;
507
508         credential = WebCore::Credential(adoptNS([[NSURLCredential alloc] initWithIdentity:identity.get() certificates:(__bridge NSArray *)certificates.get() persistence:(NSURLCredentialPersistence)persistence]).get());
509         return true;
510     }
511
512     RetainPtr<CFDataRef> data;
513     if (!IPC::decode(decoder, data))
514         return false;
515
516     auto unarchiver = secureUnarchiverFromData((__bridge NSData *)data.get());
517     @try {
518         if (RetainPtr<NSURLCredential> nsCredential = [unarchiver decodeObjectOfClass:[NSURLCredential class] forKey:@"credential"])
519             credential = WebCore::Credential(nsCredential.get());
520     } @catch (NSException *exception) {
521         LOG_ERROR("Failed to decode NSURLCredential: %@", exception);
522     }
523
524     [unarchiver finishDecoding];
525     return true;
526 }
527
528 void ArgumentCoder<MachSendRight>::encode(Encoder& encoder, const MachSendRight& sendRight)
529 {
530     encoder << Attachment(sendRight.copySendRight().leakSendRight(), MACH_MSG_TYPE_MOVE_SEND);
531 }
532
533 void ArgumentCoder<MachSendRight>::encode(Encoder& encoder, MachSendRight&& sendRight)
534 {
535     encoder << Attachment(sendRight.leakSendRight(), MACH_MSG_TYPE_MOVE_SEND);
536 }
537
538 bool ArgumentCoder<MachSendRight>::decode(Decoder& decoder, MachSendRight& sendRight)
539 {
540     Attachment attachment;
541     if (!decoder.decode(attachment))
542         return false;
543
544     if (attachment.disposition() != MACH_MSG_TYPE_MOVE_SEND)
545         return false;
546
547     sendRight = MachSendRight::adopt(attachment.port());
548     return true;
549 }
550
551 void ArgumentCoder<WebCore::KeypressCommand>::encode(Encoder& encoder, const WebCore::KeypressCommand& keypressCommand)
552 {
553     encoder << keypressCommand.commandName << keypressCommand.text;
554 }
555     
556 std::optional<WebCore::KeypressCommand> ArgumentCoder<WebCore::KeypressCommand>::decode(Decoder& decoder)
557 {
558     std::optional<String> commandName;
559     decoder >> commandName;
560     if (!commandName)
561         return std::nullopt;
562     
563     std::optional<String> text;
564     decoder >> text;
565     if (!text)
566         return std::nullopt;
567     
568     WebCore::KeypressCommand command;
569     command.commandName = WTFMove(*commandName);
570     command.text = WTFMove(*text);
571     return WTFMove(command);
572 }
573
574 #if ENABLE(CONTENT_FILTERING)
575
576 void ArgumentCoder<WebCore::ContentFilterUnblockHandler>::encode(Encoder& encoder, const WebCore::ContentFilterUnblockHandler& contentFilterUnblockHandler)
577 {
578     auto archiver = secureArchiver();
579     contentFilterUnblockHandler.encode(archiver.get());
580     IPC::encode(encoder, (__bridge CFDataRef)archiver.get().encodedData);
581 }
582
583 bool ArgumentCoder<WebCore::ContentFilterUnblockHandler>::decode(Decoder& decoder, WebCore::ContentFilterUnblockHandler& contentFilterUnblockHandler)
584 {
585     RetainPtr<CFDataRef> data;
586     if (!IPC::decode(decoder, data))
587         return false;
588
589     auto unarchiver = secureUnarchiverFromData((__bridge NSData *)data.get());
590     if (!WebCore::ContentFilterUnblockHandler::decode(unarchiver.get(), contentFilterUnblockHandler))
591         return false;
592
593     [unarchiver finishDecoding];
594     return true;
595 }
596
597 #endif
598
599 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
600
601 static NSString *deviceContextKey()
602 {
603     static NSString * const key = @"deviceContext";
604     return key;
605 }
606
607 void ArgumentCoder<WebCore::MediaPlaybackTargetContext>::encodePlatformData(Encoder& encoder, const WebCore::MediaPlaybackTargetContext& target)
608 {
609     auto archiver = secureArchiver();
610
611     if ([getAVOutputContextClass() conformsToProtocol:@protocol(NSSecureCoding)])
612         [archiver encodeObject:target.avOutputContext() forKey:deviceContextKey()];
613
614     IPC::encode(encoder, (__bridge CFDataRef)archiver.get().encodedData);
615 }
616
617 bool ArgumentCoder<WebCore::MediaPlaybackTargetContext>::decodePlatformData(Decoder& decoder, WebCore::MediaPlaybackTargetContext& target)
618 {
619     if (![getAVOutputContextClass() conformsToProtocol:@protocol(NSSecureCoding)])
620         return false;
621
622     RetainPtr<CFDataRef> data;
623     if (!IPC::decode(decoder, data))
624         return false;
625
626     auto unarchiver = secureUnarchiverFromData((__bridge NSData *)data.get());
627
628     AVOutputContext *context = nil;
629     @try {
630         context = [unarchiver decodeObjectOfClass:getAVOutputContextClass() forKey:deviceContextKey()];
631     } @catch (NSException *exception) {
632         LOG_ERROR("The target picker being decoded is not an AVOutputContext.");
633         return false;
634     }
635
636     target = WebCore::MediaPlaybackTargetContext(context);
637     
638     [unarchiver finishDecoding];
639     return true;
640 }
641
642 #endif
643
644 } // namespace IPC