[WPE][GTK] Bump minimum versions of GLib, GTK, libsoup, ATK, GStreamer, and Cairo
[WebKit-https.git] / Source / WebCore / platform / network / soup / SoupNetworkSession.cpp
1 /*
2  * Copyright (C) 2014 Igalia S.L.
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
28 #if USE(SOUP)
29
30 #include "SoupNetworkSession.h"
31
32 #include "AuthenticationChallenge.h"
33 #include "GUniquePtrSoup.h"
34 #include "Logging.h"
35 #include "SoupNetworkProxySettings.h"
36 #include <glib/gstdio.h>
37 #include <libsoup/soup.h>
38 #include <pal/crypto/CryptoDigest.h>
39 #include <wtf/FileSystem.h>
40 #include <wtf/HashSet.h>
41 #include <wtf/NeverDestroyed.h>
42 #include <wtf/text/Base64.h>
43 #include <wtf/text/CString.h>
44
45 namespace WebCore {
46
47 static bool gIgnoreTLSErrors;
48 static GType gCustomProtocolRequestType;
49
50 static CString& initialAcceptLanguages()
51 {
52     static NeverDestroyed<CString> storage;
53     return storage.get();
54 }
55
56 static SoupNetworkProxySettings& proxySettings()
57 {
58     static NeverDestroyed<SoupNetworkProxySettings> settings;
59     return settings.get();
60 }
61
62 #if !LOG_DISABLED
63 inline static void soupLogPrinter(SoupLogger*, SoupLoggerLogLevel, char direction, const char* data, gpointer)
64 {
65     LOG(Network, "%c %s", direction, data);
66 }
67 #endif
68
69 class HostTLSCertificateSet {
70 public:
71     void add(GTlsCertificate* certificate)
72     {
73         String certificateHash = computeCertificateHash(certificate);
74         if (!certificateHash.isEmpty())
75             m_certificates.add(certificateHash);
76     }
77
78     bool contains(GTlsCertificate* certificate) const
79     {
80         return m_certificates.contains(computeCertificateHash(certificate));
81     }
82
83 private:
84     static String computeCertificateHash(GTlsCertificate* certificate)
85     {
86         GRefPtr<GByteArray> certificateData;
87         g_object_get(G_OBJECT(certificate), "certificate", &certificateData.outPtr(), nullptr);
88         if (!certificateData)
89             return String();
90
91         auto digest = PAL::CryptoDigest::create(PAL::CryptoDigest::Algorithm::SHA_256);
92         digest->addBytes(certificateData->data, certificateData->len);
93
94         auto hash = digest->computeHash();
95         return base64Encode(reinterpret_cast<const char*>(hash.data()), hash.size());
96     }
97
98     HashSet<String> m_certificates;
99 };
100
101 using AllowedCertificatesMap = HashMap<String, HostTLSCertificateSet, ASCIICaseInsensitiveHash>;
102
103 static AllowedCertificatesMap& allowedCertificates()
104 {
105     static NeverDestroyed<AllowedCertificatesMap> certificates;
106     return certificates;
107 }
108
109 SoupNetworkSession::SoupNetworkSession(PAL::SessionID sessionID, SoupCookieJar* cookieJar)
110     : m_soupSession(adoptGRef(soup_session_new()))
111 {
112     // Values taken from http://www.browserscope.org/ following
113     // the rule "Do What Every Other Modern Browser Is Doing". They seem
114     // to significantly improve page loading time compared to soup's
115     // default values.
116     static const int maxConnections = 17;
117     static const int maxConnectionsPerHost = 6;
118
119     GRefPtr<SoupCookieJar> jar = cookieJar;
120     if (!jar) {
121         jar = adoptGRef(soup_cookie_jar_new());
122         soup_cookie_jar_set_accept_policy(jar.get(), SOUP_COOKIE_JAR_ACCEPT_NO_THIRD_PARTY);
123     }
124
125     g_object_set(m_soupSession.get(),
126         SOUP_SESSION_MAX_CONNS, maxConnections,
127         SOUP_SESSION_MAX_CONNS_PER_HOST, maxConnectionsPerHost,
128         SOUP_SESSION_TIMEOUT, 0,
129         SOUP_SESSION_IDLE_TIMEOUT, 0,
130         SOUP_SESSION_ADD_FEATURE_BY_TYPE, SOUP_TYPE_CONTENT_SNIFFER,
131         SOUP_SESSION_ADD_FEATURE, jar.get(),
132         nullptr);
133
134     setupCustomProtocols();
135
136     if (!initialAcceptLanguages().isNull())
137         setAcceptLanguages(initialAcceptLanguages());
138
139     if (soup_auth_negotiate_supported() && !sessionID.isEphemeral()) {
140         g_object_set(m_soupSession.get(),
141             SOUP_SESSION_ADD_FEATURE_BY_TYPE, SOUP_TYPE_AUTH_NEGOTIATE,
142             nullptr);
143     }
144
145     if (proxySettings().mode != SoupNetworkProxySettings::Mode::Default)
146         setupProxy();
147     setupLogger();
148 }
149
150 SoupNetworkSession::~SoupNetworkSession() = default;
151
152 void SoupNetworkSession::setupLogger()
153 {
154 #if !LOG_DISABLED
155     if (LogNetwork.state != WTFLogChannelState::On || soup_session_get_feature(m_soupSession.get(), SOUP_TYPE_LOGGER))
156         return;
157
158     GRefPtr<SoupLogger> logger = adoptGRef(soup_logger_new(SOUP_LOGGER_LOG_BODY, -1));
159     soup_session_add_feature(m_soupSession.get(), SOUP_SESSION_FEATURE(logger.get()));
160     soup_logger_set_printer(logger.get(), soupLogPrinter, nullptr, nullptr);
161 #endif
162 }
163
164 void SoupNetworkSession::setCookieJar(SoupCookieJar* jar)
165 {
166     if (SoupCookieJar* currentJar = cookieJar())
167         soup_session_remove_feature(m_soupSession.get(), SOUP_SESSION_FEATURE(currentJar));
168     soup_session_add_feature(m_soupSession.get(), SOUP_SESSION_FEATURE(jar));
169 }
170
171 SoupCookieJar* SoupNetworkSession::cookieJar() const
172 {
173     return SOUP_COOKIE_JAR(soup_session_get_feature(m_soupSession.get(), SOUP_TYPE_COOKIE_JAR));
174 }
175
176 static inline bool stringIsNumeric(const char* str)
177 {
178     while (*str) {
179         if (!g_ascii_isdigit(*str))
180             return false;
181         str++;
182     }
183     return true;
184 }
185
186 // Old versions of WebKit created this cache.
187 void SoupNetworkSession::clearOldSoupCache(const String& cacheDirectory)
188 {
189     CString cachePath = FileSystem::fileSystemRepresentation(cacheDirectory);
190     GUniquePtr<char> cacheFile(g_build_filename(cachePath.data(), "soup.cache2", nullptr));
191     if (!g_file_test(cacheFile.get(), G_FILE_TEST_IS_REGULAR))
192         return;
193
194     GUniquePtr<GDir> dir(g_dir_open(cachePath.data(), 0, nullptr));
195     if (!dir)
196         return;
197
198     while (const char* name = g_dir_read_name(dir.get())) {
199         if (!g_str_has_prefix(name, "soup.cache") && !stringIsNumeric(name))
200             continue;
201
202         GUniquePtr<gchar> filename(g_build_filename(cachePath.data(), name, nullptr));
203         if (g_file_test(filename.get(), G_FILE_TEST_IS_REGULAR))
204             g_unlink(filename.get());
205     }
206 }
207
208 void SoupNetworkSession::setupProxy()
209 {
210     GRefPtr<GProxyResolver> resolver;
211     switch (proxySettings().mode) {
212     case SoupNetworkProxySettings::Mode::Default: {
213         GRefPtr<GProxyResolver> currentResolver;
214         g_object_get(m_soupSession.get(), SOUP_SESSION_PROXY_RESOLVER, &currentResolver.outPtr(), nullptr);
215         GProxyResolver* defaultResolver = g_proxy_resolver_get_default();
216         if (currentResolver.get() == defaultResolver)
217             return;
218         resolver = defaultResolver;
219         break;
220     }
221     case SoupNetworkProxySettings::Mode::NoProxy:
222         // Do nothing in this case, resolver is nullptr so that when set it will disable proxies.
223         break;
224     case SoupNetworkProxySettings::Mode::Custom:
225         resolver = adoptGRef(g_simple_proxy_resolver_new(nullptr, nullptr));
226         if (!proxySettings().defaultProxyURL.isNull())
227             g_simple_proxy_resolver_set_default_proxy(G_SIMPLE_PROXY_RESOLVER(resolver.get()), proxySettings().defaultProxyURL.data());
228         if (proxySettings().ignoreHosts)
229             g_simple_proxy_resolver_set_ignore_hosts(G_SIMPLE_PROXY_RESOLVER(resolver.get()), proxySettings().ignoreHosts.get());
230         for (const auto& iter : proxySettings().proxyMap)
231             g_simple_proxy_resolver_set_uri_proxy(G_SIMPLE_PROXY_RESOLVER(resolver.get()), iter.key.data(), iter.value.data());
232         break;
233     }
234
235     g_object_set(m_soupSession.get(), SOUP_SESSION_PROXY_RESOLVER, resolver.get(), nullptr);
236     soup_session_abort(m_soupSession.get());
237 }
238
239 void SoupNetworkSession::setProxySettings(const SoupNetworkProxySettings& settings)
240 {
241     proxySettings() = settings;
242 }
243
244 void SoupNetworkSession::setInitialAcceptLanguages(const CString& languages)
245 {
246     initialAcceptLanguages() = languages;
247 }
248
249 void SoupNetworkSession::setAcceptLanguages(const CString& languages)
250 {
251     g_object_set(m_soupSession.get(), "accept-language", languages.data(), nullptr);
252 }
253
254 void SoupNetworkSession::setCustomProtocolRequestType(GType requestType)
255 {
256     ASSERT(g_type_is_a(requestType, SOUP_TYPE_REQUEST));
257     gCustomProtocolRequestType = requestType;
258 }
259
260 void SoupNetworkSession::setupCustomProtocols()
261 {
262     if (!g_type_is_a(gCustomProtocolRequestType, SOUP_TYPE_REQUEST))
263         return;
264
265     auto* requestClass = static_cast<SoupRequestClass*>(g_type_class_peek(gCustomProtocolRequestType));
266     if (!requestClass || !requestClass->schemes)
267         return;
268
269     soup_session_add_feature_by_type(m_soupSession.get(), gCustomProtocolRequestType);
270 }
271
272 void SoupNetworkSession::setShouldIgnoreTLSErrors(bool ignoreTLSErrors)
273 {
274     gIgnoreTLSErrors = ignoreTLSErrors;
275 }
276
277 Optional<ResourceError> SoupNetworkSession::checkTLSErrors(const URL& requestURL, GTlsCertificate* certificate, GTlsCertificateFlags tlsErrors)
278 {
279     if (gIgnoreTLSErrors)
280         return WTF::nullopt;
281
282     if (!tlsErrors)
283         return WTF::nullopt;
284
285     auto it = allowedCertificates().find(requestURL.host().toStringWithoutCopying());
286     if (it != allowedCertificates().end() && it->value.contains(certificate))
287         return WTF::nullopt;
288
289     return ResourceError::tlsError(requestURL, tlsErrors, certificate);
290 }
291
292 void SoupNetworkSession::allowSpecificHTTPSCertificateForHost(const CertificateInfo& certificateInfo, const String& host)
293 {
294     allowedCertificates().add(host, HostTLSCertificateSet()).iterator->value.add(certificateInfo.certificate());
295 }
296
297 } // namespace WebCore
298
299 #endif