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