49a924891855a31d380bc841c3d0f3a054723a99
[WebKit-https.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 <pal/spi/cf/CFNetworkSPI.h>
39 #include <wtf/SoftLinking.h>
40 #include <wtf/cf/TypeCastsCF.h>
41 #include <wtf/text/WTFString.h>
42
43 #if PLATFORM(WIN)
44 #include <WebKitSystemInterface/WebKitSystemInterface.h>
45 #include <windows.h>
46 #endif
47
48 #if PLATFORM(WIN)
49 enum {
50     CFHTTPCookieStorageAcceptPolicyExclusivelyFromMainDocumentDomain = 3
51 };
52 #endif
53
54 namespace WTF {
55
56 #define DECLARE_CF_TYPE_TRAIT(ClassName) \
57 template <> \
58 struct CFTypeTrait<ClassName##Ref> { \
59 static inline CFTypeID typeID() { return ClassName##GetTypeID(); } \
60 };
61
62 #if COMPILER(CLANG)
63 #pragma clang diagnostic push
64 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
65 #endif
66 DECLARE_CF_TYPE_TRAIT(CFHTTPCookie);
67 #if COMPILER(CLANG)
68 #pragma clang diagnostic pop
69 #endif
70
71 #undef DECLARE_CF_TYPE_TRAIT
72 } // namespace WTF
73
74 namespace WebCore {
75
76 static const CFStringRef s_setCookieKeyCF = CFSTR("Set-Cookie");
77 static const CFStringRef s_cookieCF = CFSTR("Cookie");
78
79 static inline RetainPtr<CFStringRef> cookieDomain(CFHTTPCookieRef cookie)
80 {
81     return adoptCF(CFHTTPCookieCopyDomain(cookie));
82 }
83
84 static inline CFAbsoluteTime cookieExpirationTime(CFHTTPCookieRef cookie)
85 {
86     return CFHTTPCookieGetExpirationTime(cookie);
87 }
88
89 static inline RetainPtr<CFStringRef> cookieName(CFHTTPCookieRef cookie)
90 {
91     return adoptCF(CFHTTPCookieCopyName(cookie));
92 }
93
94 static inline RetainPtr<CFStringRef> cookiePath(CFHTTPCookieRef cookie)
95 {
96     return adoptCF(CFHTTPCookieCopyPath(cookie));
97 }
98
99 static inline RetainPtr<CFStringRef> cookieValue(CFHTTPCookieRef cookie)
100 {
101     return adoptCF(CFHTTPCookieCopyValue(cookie));
102 }
103
104 static RetainPtr<CFArrayRef> filterCookies(CFArrayRef unfilteredCookies)
105 {
106     ASSERT(unfilteredCookies);
107     CFIndex count = CFArrayGetCount(unfilteredCookies);
108     RetainPtr<CFMutableArrayRef> filteredCookies = adoptCF(CFArrayCreateMutable(0, count, &kCFTypeArrayCallBacks));
109     for (CFIndex i = 0; i < count; ++i) {
110         CFHTTPCookieRef cookie = (CFHTTPCookieRef)CFArrayGetValueAtIndex(unfilteredCookies, i);
111
112         // <rdar://problem/5632883> CFHTTPCookieStorage would store an empty cookie,
113         // which would be sent as "Cookie: =". We have a workaround in setCookies() to prevent
114         // that, but we also need to avoid sending cookies that were previously stored, and
115         // there's no harm to doing this check because such a cookie is never valid.
116         if (!CFStringGetLength(cookieName(cookie).get()))
117             continue;
118
119         if (CFHTTPCookieIsHTTPOnly(cookie))
120             continue;
121
122         CFArrayAppendValue(filteredCookies.get(), cookie);
123     }
124     return filteredCookies;
125 }
126
127 static RetainPtr<CFArrayRef> copyCookiesForURLWithFirstPartyURL(const NetworkStorageSession& session, const URL& firstParty, const URL& url, IncludeSecureCookies includeSecureCookies)
128 {
129     bool secure = includeSecureCookies == IncludeSecureCookies::Yes;
130
131     ASSERT(!secure || (secure && url.protocolIs("https")));
132
133 #if PLATFORM(COCOA)
134     return adoptCF(_CFHTTPCookieStorageCopyCookiesForURLWithMainDocumentURL(session.cookieStorage().get(), url.createCFURL().get(), firstParty.createCFURL().get(), secure));
135 #else
136     // _CFHTTPCookieStorageCopyCookiesForURLWithMainDocumentURL is not available on other platforms.
137     UNUSED_PARAM(firstParty);
138     return adoptCF(CFHTTPCookieStorageCopyCookiesForURL(session.cookieStorage().get(), url.createCFURL().get(), secure));
139 #endif
140 }
141
142 static CFArrayRef createCookies(CFDictionaryRef headerFields, CFURLRef url)
143 {
144 #if PLATFORM(IOS)
145     CFArrayRef parsedCookies = _CFHTTPParsedCookiesWithResponseHeaderFields(kCFAllocatorDefault, headerFields, url);
146 #else
147     CFArrayRef parsedCookies = CFHTTPCookieCreateWithResponseHeaderFields(kCFAllocatorDefault, headerFields, url);
148 #endif
149     if (!parsedCookies)
150         parsedCookies = CFArrayCreate(kCFAllocatorDefault, 0, 0, &kCFTypeArrayCallBacks);
151
152     return parsedCookies;
153 }
154
155 void setCookiesFromDOM(const NetworkStorageSession& session, const URL& firstParty, const URL& url, const String& value)
156 {
157     // <rdar://problem/5632883> CFHTTPCookieStorage stores an empty cookie, which would be sent as "Cookie: =".
158     if (value.isEmpty())
159         return;
160
161     RetainPtr<CFURLRef> urlCF = url.createCFURL();
162     RetainPtr<CFURLRef> firstPartyForCookiesCF = firstParty.createCFURL();
163
164     // <http://bugs.webkit.org/show_bug.cgi?id=6531>, <rdar://4409034>
165     // cookiesWithResponseHeaderFields doesn't parse cookies without a value
166     String cookieString = value.contains('=') ? value : value + "=";
167
168     RetainPtr<CFStringRef> cookieStringCF = cookieString.createCFString();
169     auto cookieStringCFPtr = cookieStringCF.get();
170     RetainPtr<CFDictionaryRef> headerFieldsCF = adoptCF(CFDictionaryCreate(kCFAllocatorDefault,
171         (const void**)&s_setCookieKeyCF, (const void**)&cookieStringCFPtr, 1,
172         &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
173
174     RetainPtr<CFArrayRef> unfilteredCookies = adoptCF(createCookies(headerFieldsCF.get(), urlCF.get()));
175     CFHTTPCookieStorageSetCookies(session.cookieStorage().get(), filterCookies(unfilteredCookies.get()).get(), urlCF.get(), firstPartyForCookiesCF.get());
176 }
177
178 static bool containsSecureCookies(CFArrayRef cookies)
179 {
180     CFIndex cookieCount = CFArrayGetCount(cookies);
181     while (cookieCount--) {
182         if (CFHTTPCookieIsSecure(checked_cf_cast<CFHTTPCookieRef>(CFArrayGetValueAtIndex(cookies, cookieCount))))
183             return true;
184     }
185
186     return false;
187 }
188
189 std::pair<String, bool> cookiesForDOM(const NetworkStorageSession& session, const URL& firstParty, const URL& url, IncludeSecureCookies includeSecureCookies)
190 {
191     RetainPtr<CFArrayRef> cookiesCF = copyCookiesForURLWithFirstPartyURL(session, firstParty, url, includeSecureCookies);
192
193     auto filteredCookies = filterCookies(cookiesCF.get());
194
195     bool didAccessSecureCookies = containsSecureCookies(filteredCookies.get());
196
197     RetainPtr<CFDictionaryRef> headerCF = adoptCF(CFHTTPCookieCopyRequestHeaderFields(kCFAllocatorDefault, filteredCookies.get()));
198     String cookieString = checked_cf_cast<CFStringRef>(CFDictionaryGetValue(headerCF.get(), s_cookieCF));
199     return { cookieString, didAccessSecureCookies };
200 }
201
202 std::pair<String, bool> cookieRequestHeaderFieldValue(const NetworkStorageSession& session, const URL& firstParty, const URL& url, IncludeSecureCookies includeSecureCookies)
203 {
204     RetainPtr<CFArrayRef> cookiesCF = copyCookiesForURLWithFirstPartyURL(session, firstParty, url, includeSecureCookies);
205
206     bool didAccessSecureCookies = containsSecureCookies(cookiesCF.get());
207
208     RetainPtr<CFDictionaryRef> headerCF = adoptCF(CFHTTPCookieCopyRequestHeaderFields(kCFAllocatorDefault, cookiesCF.get()));
209     String cookieString = checked_cf_cast<CFStringRef>(CFDictionaryGetValue(headerCF.get(), s_cookieCF));
210     return { cookieString, didAccessSecureCookies };
211 }
212
213 bool cookiesEnabled(const NetworkStorageSession& session)
214 {
215     CFHTTPCookieStorageAcceptPolicy policy = CFHTTPCookieStorageGetCookieAcceptPolicy(session.cookieStorage().get());
216     return policy == CFHTTPCookieStorageAcceptPolicyOnlyFromMainDocumentDomain || policy == CFHTTPCookieStorageAcceptPolicyExclusivelyFromMainDocumentDomain || policy == CFHTTPCookieStorageAcceptPolicyAlways;
217 }
218
219 bool getRawCookies(const NetworkStorageSession& session, const URL& firstParty, const URL& url, Vector<Cookie>& rawCookies)
220 {
221     rawCookies.clear();
222
223     auto includeSecureCookies = url.protocolIs("https") ? IncludeSecureCookies::Yes : IncludeSecureCookies::No;
224
225     RetainPtr<CFArrayRef> cookiesCF = copyCookiesForURLWithFirstPartyURL(session, firstParty, url, includeSecureCookies);
226
227     CFIndex count = CFArrayGetCount(cookiesCF.get());
228     rawCookies.reserveCapacity(count);
229
230     for (CFIndex i = 0; i < count; i++) {
231         CFHTTPCookieRef cookie = checked_cf_cast<CFHTTPCookieRef>(CFArrayGetValueAtIndex(cookiesCF.get(), i));
232         String name = cookieName(cookie).get();
233         String value = cookieValue(cookie).get();
234         String domain = cookieDomain(cookie).get();
235         String path = cookiePath(cookie).get();
236
237         double expires = (cookieExpirationTime(cookie) + kCFAbsoluteTimeIntervalSince1970) * 1000;
238
239         bool httpOnly = CFHTTPCookieIsHTTPOnly(cookie);
240         bool secure = CFHTTPCookieIsSecure(cookie);
241         bool session = false; // FIXME: Need API for if a cookie is a session cookie.
242
243         String comment;
244         URL commentURL;
245         Vector<uint16_t> ports;
246
247         rawCookies.uncheckedAppend(Cookie(name, value, domain, path, expires, httpOnly, secure, session, comment, commentURL, ports));
248     }
249
250     return true;
251 }
252
253 void deleteCookie(const NetworkStorageSession& session, const URL& url, const String& name)
254 {
255     RetainPtr<CFHTTPCookieStorageRef> cookieStorage = session.cookieStorage();
256
257     RetainPtr<CFURLRef> urlCF = url.createCFURL();
258
259     bool sendSecureCookies = url.protocolIs("https");
260     RetainPtr<CFArrayRef> cookiesCF = adoptCF(CFHTTPCookieStorageCopyCookiesForURL(cookieStorage.get(), urlCF.get(), sendSecureCookies));
261
262     CFIndex count = CFArrayGetCount(cookiesCF.get());
263     for (CFIndex i = 0; i < count; i++) {
264         CFHTTPCookieRef cookie = checked_cf_cast<CFHTTPCookieRef>(CFArrayGetValueAtIndex(cookiesCF.get(), i));
265         if (String(cookieName(cookie).get()) == name) {
266             CFHTTPCookieStorageDeleteCookie(cookieStorage.get(), cookie);
267             break;
268         }
269     }
270 }
271
272 void getHostnamesWithCookies(const NetworkStorageSession& session, HashSet<String>& hostnames)
273 {
274     RetainPtr<CFArrayRef> cookiesCF = adoptCF(CFHTTPCookieStorageCopyCookies(session.cookieStorage().get()));
275     if (!cookiesCF)
276         return;
277
278     CFIndex count = CFArrayGetCount(cookiesCF.get());
279     for (CFIndex i = 0; i < count; ++i) {
280         CFHTTPCookieRef cookie = checked_cf_cast<CFHTTPCookieRef>(CFArrayGetValueAtIndex(cookiesCF.get(), i));
281         RetainPtr<CFStringRef> domain = cookieDomain(cookie);
282         hostnames.add(domain.get());
283     }
284 }
285
286 void deleteAllCookies(const NetworkStorageSession& session)
287 {
288     CFHTTPCookieStorageDeleteAllCookies(session.cookieStorage().get());
289 }
290
291 #if PLATFORM(WIN)
292 void deleteCookiesForHostnames(const NetworkStorageSession& session, const Vector<String>& hostnames)
293 {
294 }
295
296 void deleteAllCookiesModifiedSince(const NetworkStorageSession&, std::chrono::system_clock::time_point)
297 {
298 }
299 #endif
300
301 } // namespace WebCore
302
303 #endif // USE(CFURLCONNECTION)