cf34d0595f9b5570eb0edd25c4e1387bdfa44abe
[WebKit.git] / Source / WebCore / platform / network / cf / CookieJarCFNet.cpp
1 /*
2  * Copyright (C) 2006-2017 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
17  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
24  */
25
26 #include "config.h"
27 #include "PlatformCookieJar.h"
28
29 #if USE(CFURLCONNECTION)
30
31 #include "Cookie.h"
32 #include "CookiesStrategy.h"
33 #include "NetworkStorageSession.h"
34 #include "NotImplemented.h"
35 #include "URL.h"
36 #include <CFNetwork/CFHTTPCookiesPriv.h>
37 #include <CoreFoundation/CoreFoundation.h>
38 #include <WebKitSystemInterface/WebKitSystemInterface.h>
39 #include <pal/spi/cf/CFNetworkSPI.h>
40 #include <windows.h>
41 #include <wtf/SoftLinking.h>
42 #include <wtf/cf/TypeCastsCF.h>
43 #include <wtf/text/WTFString.h>
44
45 enum {
46     CFHTTPCookieStorageAcceptPolicyExclusivelyFromMainDocumentDomain = 3
47 };
48
49 namespace WTF {
50
51 #define DECLARE_CF_TYPE_TRAIT(ClassName) \
52 template <> \
53 struct CFTypeTrait<ClassName##Ref> { \
54 static inline CFTypeID typeID() { return ClassName##GetTypeID(); } \
55 };
56
57 #if COMPILER(CLANG)
58 #pragma clang diagnostic push
59 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
60 #endif
61 DECLARE_CF_TYPE_TRAIT(CFHTTPCookie);
62 #if COMPILER(CLANG)
63 #pragma clang diagnostic pop
64 #endif
65
66 #undef DECLARE_CF_TYPE_TRAIT
67 } // namespace WTF
68
69 namespace WebCore {
70
71 static const CFStringRef s_setCookieKeyCF = CFSTR("Set-Cookie");
72 static const CFStringRef s_cookieCF = CFSTR("Cookie");
73 static const CFStringRef s_createdCF = CFSTR("Created");
74
75 static inline RetainPtr<CFStringRef> cookieDomain(CFHTTPCookieRef cookie)
76 {
77     return adoptCF(CFHTTPCookieCopyDomain(cookie));
78 }
79
80 static double canonicalCookieTime(double time)
81 {
82     if (!time)
83         return time;
84
85     return (time + kCFAbsoluteTimeIntervalSince1970) * 1000;
86 }
87
88 static double cookieCreatedTime(CFHTTPCookieRef cookie)
89 {
90     RetainPtr<CFDictionaryRef> props = adoptCF(CFHTTPCookieCopyProperties(cookie));
91     auto value = CFDictionaryGetValue(props.get(), s_createdCF);
92
93     auto asNumber = dynamic_cf_cast<CFNumberRef>(value);
94     if (asNumber) {
95         double asDouble;
96         if (CFNumberGetValue(asNumber, kCFNumberFloat64Type, &asDouble))
97             return canonicalCookieTime(asDouble);
98         return 0.0;
99     }
100
101     auto asString = dynamic_cf_cast<CFStringRef>(value);
102     if (asString)
103         return canonicalCookieTime(CFStringGetDoubleValue(asString));
104
105     return 0.0;
106 }
107
108 static inline CFAbsoluteTime cookieExpirationTime(CFHTTPCookieRef cookie)
109 {
110     return canonicalCookieTime(CFHTTPCookieGetExpirationTime(cookie));
111 }
112
113 static inline RetainPtr<CFStringRef> cookieName(CFHTTPCookieRef cookie)
114 {
115     return adoptCF(CFHTTPCookieCopyName(cookie));
116 }
117
118 static inline RetainPtr<CFStringRef> cookiePath(CFHTTPCookieRef cookie)
119 {
120     return adoptCF(CFHTTPCookieCopyPath(cookie));
121 }
122
123 static inline RetainPtr<CFStringRef> cookieValue(CFHTTPCookieRef cookie)
124 {
125     return adoptCF(CFHTTPCookieCopyValue(cookie));
126 }
127
128 static RetainPtr<CFArrayRef> filterCookies(CFArrayRef unfilteredCookies)
129 {
130     ASSERT(unfilteredCookies);
131     CFIndex count = CFArrayGetCount(unfilteredCookies);
132     RetainPtr<CFMutableArrayRef> filteredCookies = adoptCF(CFArrayCreateMutable(0, count, &kCFTypeArrayCallBacks));
133     for (CFIndex i = 0; i < count; ++i) {
134         CFHTTPCookieRef cookie = (CFHTTPCookieRef)CFArrayGetValueAtIndex(unfilteredCookies, i);
135
136         // <rdar://problem/5632883> CFHTTPCookieStorage would store an empty cookie,
137         // which would be sent as "Cookie: =". We have a workaround in setCookies() to prevent
138         // that, but we also need to avoid sending cookies that were previously stored, and
139         // there's no harm to doing this check because such a cookie is never valid.
140         if (!CFStringGetLength(cookieName(cookie).get()))
141             continue;
142
143         if (CFHTTPCookieIsHTTPOnly(cookie))
144             continue;
145
146         CFArrayAppendValue(filteredCookies.get(), cookie);
147     }
148     return filteredCookies;
149 }
150
151 static RetainPtr<CFArrayRef> copyCookiesForURLWithFirstPartyURL(const NetworkStorageSession& session, const URL& firstParty, const URL& url, IncludeSecureCookies includeSecureCookies)
152 {
153     bool secure = includeSecureCookies == IncludeSecureCookies::Yes;
154
155     ASSERT(!secure || (secure && url.protocolIs("https")));
156
157     UNUSED_PARAM(firstParty);
158     return adoptCF(CFHTTPCookieStorageCopyCookiesForURL(session.cookieStorage().get(), url.createCFURL().get(), secure));
159 }
160
161 static CFArrayRef createCookies(CFDictionaryRef headerFields, CFURLRef url)
162 {
163     CFArrayRef parsedCookies = CFHTTPCookieCreateWithResponseHeaderFields(kCFAllocatorDefault, headerFields, url);
164     if (!parsedCookies)
165         parsedCookies = CFArrayCreate(kCFAllocatorDefault, 0, 0, &kCFTypeArrayCallBacks);
166
167     return parsedCookies;
168 }
169
170 void setCookiesFromDOM(const NetworkStorageSession& session, const URL& firstParty, const URL& url, std::optional<uint64_t> frameID, std::optional<uint64_t> pageID, const String& value)
171 {
172     UNUSED_PARAM(frameID);
173     UNUSED_PARAM(pageID);
174     // <rdar://problem/5632883> CFHTTPCookieStorage stores an empty cookie, which would be sent as "Cookie: =".
175     if (value.isEmpty())
176         return;
177
178     RetainPtr<CFURLRef> urlCF = url.createCFURL();
179     RetainPtr<CFURLRef> firstPartyForCookiesCF = firstParty.createCFURL();
180
181     // <http://bugs.webkit.org/show_bug.cgi?id=6531>, <rdar://4409034>
182     // cookiesWithResponseHeaderFields doesn't parse cookies without a value
183     String cookieString = value.contains('=') ? value : value + "=";
184
185     RetainPtr<CFStringRef> cookieStringCF = cookieString.createCFString();
186     auto cookieStringCFPtr = cookieStringCF.get();
187     RetainPtr<CFDictionaryRef> headerFieldsCF = adoptCF(CFDictionaryCreate(kCFAllocatorDefault,
188         (const void**)&s_setCookieKeyCF, (const void**)&cookieStringCFPtr, 1,
189         &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
190
191     RetainPtr<CFArrayRef> unfilteredCookies = adoptCF(createCookies(headerFieldsCF.get(), urlCF.get()));
192     CFHTTPCookieStorageSetCookies(session.cookieStorage().get(), filterCookies(unfilteredCookies.get()).get(), urlCF.get(), firstPartyForCookiesCF.get());
193 }
194
195 static bool containsSecureCookies(CFArrayRef cookies)
196 {
197     CFIndex cookieCount = CFArrayGetCount(cookies);
198     while (cookieCount--) {
199         if (CFHTTPCookieIsSecure(checked_cf_cast<CFHTTPCookieRef>(CFArrayGetValueAtIndex(cookies, cookieCount))))
200             return true;
201     }
202
203     return false;
204 }
205
206 std::pair<String, bool> cookiesForDOM(const NetworkStorageSession& session, const URL& firstParty, const URL& url, std::optional<uint64_t> frameID, std::optional<uint64_t> pageID, IncludeSecureCookies includeSecureCookies)
207 {
208     UNUSED_PARAM(frameID);
209     UNUSED_PARAM(pageID);
210     RetainPtr<CFArrayRef> cookiesCF = copyCookiesForURLWithFirstPartyURL(session, firstParty, url, includeSecureCookies);
211
212     auto filteredCookies = filterCookies(cookiesCF.get());
213
214     bool didAccessSecureCookies = containsSecureCookies(filteredCookies.get());
215
216     RetainPtr<CFDictionaryRef> headerCF = adoptCF(CFHTTPCookieCopyRequestHeaderFields(kCFAllocatorDefault, filteredCookies.get()));
217     String cookieString = checked_cf_cast<CFStringRef>(CFDictionaryGetValue(headerCF.get(), s_cookieCF));
218     return { cookieString, didAccessSecureCookies };
219 }
220
221 std::pair<String, bool> cookieRequestHeaderFieldValue(const NetworkStorageSession& session, const URL& firstParty, const URL& url, std::optional<uint64_t> frameID, std::optional<uint64_t> pageID, IncludeSecureCookies includeSecureCookies)
222 {
223     UNUSED_PARAM(frameID);
224     UNUSED_PARAM(pageID);
225     RetainPtr<CFArrayRef> cookiesCF = copyCookiesForURLWithFirstPartyURL(session, firstParty, url, includeSecureCookies);
226
227     bool didAccessSecureCookies = containsSecureCookies(cookiesCF.get());
228
229     RetainPtr<CFDictionaryRef> headerCF = adoptCF(CFHTTPCookieCopyRequestHeaderFields(kCFAllocatorDefault, cookiesCF.get()));
230     String cookieString = checked_cf_cast<CFStringRef>(CFDictionaryGetValue(headerCF.get(), s_cookieCF));
231     return { cookieString, didAccessSecureCookies };
232 }
233
234 bool cookiesEnabled(const NetworkStorageSession& session)
235 {
236     CFHTTPCookieStorageAcceptPolicy policy = CFHTTPCookieStorageGetCookieAcceptPolicy(session.cookieStorage().get());
237     return policy == CFHTTPCookieStorageAcceptPolicyOnlyFromMainDocumentDomain || policy == CFHTTPCookieStorageAcceptPolicyExclusivelyFromMainDocumentDomain || policy == CFHTTPCookieStorageAcceptPolicyAlways;
238 }
239
240 bool getRawCookies(const NetworkStorageSession& session, const URL& firstParty, const URL& url, std::optional<uint64_t> frameID, std::optional<uint64_t> pageID, Vector<Cookie>& rawCookies)
241 {
242     UNUSED_PARAM(frameID);
243     UNUSED_PARAM(pageID);
244     rawCookies.clear();
245
246     auto includeSecureCookies = url.protocolIs("https") ? IncludeSecureCookies::Yes : IncludeSecureCookies::No;
247
248     RetainPtr<CFArrayRef> cookiesCF = copyCookiesForURLWithFirstPartyURL(session, firstParty, url, includeSecureCookies);
249
250     CFIndex count = CFArrayGetCount(cookiesCF.get());
251     rawCookies.reserveCapacity(count);
252
253     for (CFIndex i = 0; i < count; i++) {
254         CFHTTPCookieRef cookie = checked_cf_cast<CFHTTPCookieRef>(CFArrayGetValueAtIndex(cookiesCF.get(), i));
255         String name = cookieName(cookie).get();
256         String value = cookieValue(cookie).get();
257         String domain = cookieDomain(cookie).get();
258         String path = cookiePath(cookie).get();
259
260         double created = cookieCreatedTime(cookie);
261         double expires = cookieExpirationTime(cookie);
262
263         bool httpOnly = CFHTTPCookieIsHTTPOnly(cookie);
264         bool secure = CFHTTPCookieIsSecure(cookie);
265         bool session = false; // FIXME: Need API for if a cookie is a session cookie.
266
267         String comment;
268         URL commentURL;
269         Vector<uint16_t> ports;
270
271         rawCookies.uncheckedAppend(Cookie(name, value, domain, path, created, expires, httpOnly, secure, session, comment, commentURL, ports));
272     }
273
274     return true;
275 }
276
277 void deleteCookie(const NetworkStorageSession& session, const URL& url, const String& name)
278 {
279     RetainPtr<CFHTTPCookieStorageRef> cookieStorage = session.cookieStorage();
280
281     RetainPtr<CFURLRef> urlCF = url.createCFURL();
282
283     bool sendSecureCookies = url.protocolIs("https");
284     RetainPtr<CFArrayRef> cookiesCF = adoptCF(CFHTTPCookieStorageCopyCookiesForURL(cookieStorage.get(), urlCF.get(), sendSecureCookies));
285
286     CFIndex count = CFArrayGetCount(cookiesCF.get());
287     for (CFIndex i = 0; i < count; i++) {
288         CFHTTPCookieRef cookie = checked_cf_cast<CFHTTPCookieRef>(CFArrayGetValueAtIndex(cookiesCF.get(), i));
289         if (String(cookieName(cookie).get()) == name) {
290             CFHTTPCookieStorageDeleteCookie(cookieStorage.get(), cookie);
291             break;
292         }
293     }
294 }
295
296 void getHostnamesWithCookies(const NetworkStorageSession& session, HashSet<String>& hostnames)
297 {
298     RetainPtr<CFArrayRef> cookiesCF = adoptCF(CFHTTPCookieStorageCopyCookies(session.cookieStorage().get()));
299     if (!cookiesCF)
300         return;
301
302     CFIndex count = CFArrayGetCount(cookiesCF.get());
303     for (CFIndex i = 0; i < count; ++i) {
304         CFHTTPCookieRef cookie = checked_cf_cast<CFHTTPCookieRef>(CFArrayGetValueAtIndex(cookiesCF.get(), i));
305         RetainPtr<CFStringRef> domain = cookieDomain(cookie);
306         hostnames.add(domain.get());
307     }
308 }
309
310 void deleteAllCookies(const NetworkStorageSession& session)
311 {
312     CFHTTPCookieStorageDeleteAllCookies(session.cookieStorage().get());
313 }
314
315 void deleteCookiesForHostnames(const NetworkStorageSession& session, const Vector<String>& hostnames)
316 {
317 }
318
319 void deleteAllCookiesModifiedSince(const NetworkStorageSession&, std::chrono::system_clock::time_point)
320 {
321 }
322
323 } // namespace WebCore
324
325 #endif // USE(CFURLCONNECTION)