Split author style code out from DocumentStyleSheetCollection
[WebKit-https.git] / Source / WebCore / contentextensions / ContentExtensionsBackend.cpp
1 /*
2  * Copyright (C) 2014 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. AND ITS CONTRIBUTORS ``AS IS''
14  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23  * THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #include "config.h"
27 #include "ContentExtensionsBackend.h"
28
29 #if ENABLE(CONTENT_EXTENSIONS)
30
31 #include "CompiledContentExtension.h"
32 #include "ContentExtension.h"
33 #include "ContentExtensionsDebugging.h"
34 #include "DFABytecodeInterpreter.h"
35 #include "Document.h"
36 #include "DocumentLoader.h"
37 #include "ExtensionStyleSheets.h"
38 #include "Frame.h"
39 #include "MainFrame.h"
40 #include "ResourceLoadInfo.h"
41 #include "URL.h"
42 #include "UserContentController.h"
43 #include <wtf/NeverDestroyed.h>
44 #include <wtf/text/CString.h>
45
46 namespace WebCore {
47
48 namespace ContentExtensions {
49     
50 void ContentExtensionsBackend::addContentExtension(const String& identifier, RefPtr<CompiledContentExtension> compiledContentExtension)
51 {
52     ASSERT(!identifier.isEmpty());
53     if (identifier.isEmpty())
54         return;
55
56     if (!compiledContentExtension) {
57         removeContentExtension(identifier);
58         return;
59     }
60
61     RefPtr<ContentExtension> extension = ContentExtension::create(identifier, adoptRef(*compiledContentExtension.leakRef()));
62     m_contentExtensions.set(identifier, WTF::move(extension));
63 }
64
65 void ContentExtensionsBackend::removeContentExtension(const String& identifier)
66 {
67     m_contentExtensions.remove(identifier);
68 }
69
70 void ContentExtensionsBackend::removeAllContentExtensions()
71 {
72     m_contentExtensions.clear();
73 }
74
75 Vector<Action> ContentExtensionsBackend::actionsForResourceLoad(const ResourceLoadInfo& resourceLoadInfo) const
76 {
77 #if CONTENT_EXTENSIONS_PERFORMANCE_REPORTING
78     double addedTimeStart = monotonicallyIncreasingTime();
79 #endif
80     if (resourceLoadInfo.resourceURL.protocolIsData())
81         return Vector<Action>();
82
83     const String& urlString = resourceLoadInfo.resourceURL.string();
84     ASSERT_WITH_MESSAGE(urlString.containsOnlyASCII(), "A decoded URL should only contain ASCII characters. The matching algorithm assumes the input is ASCII.");
85     const CString& urlCString = urlString.utf8();
86
87     Vector<Action> finalActions;
88     ResourceFlags flags = resourceLoadInfo.getResourceFlags();
89     for (auto& contentExtension : m_contentExtensions.values()) {
90         RELEASE_ASSERT(contentExtension);
91         const CompiledContentExtension& compiledExtension = contentExtension->compiledExtension();
92         
93         DFABytecodeInterpreter withoutDomainsInterpreter(compiledExtension.filtersWithoutDomainsBytecode(), compiledExtension.filtersWithoutDomainsBytecodeLength());
94         DFABytecodeInterpreter::Actions withoutDomainsActions = withoutDomainsInterpreter.interpret(urlCString, flags);
95         
96         String domain = resourceLoadInfo.mainDocumentURL.host();
97         DFABytecodeInterpreter withDomainsInterpreter(compiledExtension.filtersWithDomainsBytecode(), compiledExtension.filtersWithDomainsBytecodeLength());
98         DFABytecodeInterpreter::Actions withDomainsActions = withDomainsInterpreter.interpretWithDomains(urlCString, flags, contentExtension->cachedDomainActions(domain));
99         
100         const SerializedActionByte* actions = compiledExtension.actions();
101         const unsigned actionsLength = compiledExtension.actionsLength();
102         
103         bool sawIgnorePreviousRules = false;
104         const Vector<uint32_t>& universalWithDomains = contentExtension->universalActionsWithDomains(domain);
105         const Vector<uint32_t>& universalWithoutDomains = contentExtension->universalActionsWithoutDomains();
106         if (!withoutDomainsActions.isEmpty() || !withDomainsActions.isEmpty() || !universalWithDomains.isEmpty() || !universalWithoutDomains.isEmpty()) {
107             Vector<uint32_t> actionLocations;
108             actionLocations.reserveInitialCapacity(withoutDomainsActions.size() + withDomainsActions.size() + universalWithoutDomains.size() + universalWithDomains.size());
109             for (uint64_t actionLocation : withoutDomainsActions)
110                 actionLocations.uncheckedAppend(static_cast<uint32_t>(actionLocation));
111             for (uint64_t actionLocation : withDomainsActions)
112                 actionLocations.uncheckedAppend(static_cast<uint32_t>(actionLocation));
113             for (uint32_t actionLocation : universalWithoutDomains)
114                 actionLocations.uncheckedAppend(actionLocation);
115             for (uint32_t actionLocation : universalWithDomains)
116                 actionLocations.uncheckedAppend(actionLocation);
117             std::sort(actionLocations.begin(), actionLocations.end());
118
119             // Add actions in reverse order to properly deal with IgnorePreviousRules.
120             for (unsigned i = actionLocations.size(); i; i--) {
121                 Action action = Action::deserialize(actions, actionsLength, actionLocations[i - 1]);
122                 action.setExtensionIdentifier(contentExtension->identifier());
123                 if (action.type() == ActionType::IgnorePreviousRules) {
124                     sawIgnorePreviousRules = true;
125                     break;
126                 }
127                 finalActions.append(action);
128             }
129         }
130         if (!sawIgnorePreviousRules) {
131             finalActions.append(Action(ActionType::CSSDisplayNoneStyleSheet, contentExtension->identifier()));
132             finalActions.last().setExtensionIdentifier(contentExtension->identifier());
133         }
134     }
135 #if CONTENT_EXTENSIONS_PERFORMANCE_REPORTING
136     double addedTimeEnd = monotonicallyIncreasingTime();
137     dataLogF("Time added: %f microseconds %s \n", (addedTimeEnd - addedTimeStart) * 1.0e6, resourceLoadInfo.resourceURL.string().utf8().data());
138 #endif
139     return finalActions;
140 }
141
142 StyleSheetContents* ContentExtensionsBackend::globalDisplayNoneStyleSheet(const String& identifier) const
143 {
144     const auto& contentExtension = m_contentExtensions.get(identifier);
145     return contentExtension ? contentExtension->globalDisplayNoneStyleSheet() : nullptr;
146 }
147
148 void ContentExtensionsBackend::processContentExtensionRulesForLoad(ResourceRequest& request, ResourceType resourceType, DocumentLoader& initiatingDocumentLoader)
149 {
150     Document* currentDocument = nullptr;
151     URL mainDocumentURL;
152
153     if (Frame* frame = initiatingDocumentLoader.frame()) {
154         currentDocument = frame->document();
155
156         if (initiatingDocumentLoader.isLoadingMainResource()
157             && frame->isMainFrame()
158             && resourceType == ResourceType::Document)
159             mainDocumentURL = request.url();
160         else if (Document* mainDocument = frame->mainFrame().document())
161             mainDocumentURL = mainDocument->url();
162     }
163
164     ResourceLoadInfo resourceLoadInfo = { request.url(), mainDocumentURL, resourceType };
165     Vector<ContentExtensions::Action> actions = actionsForResourceLoad(resourceLoadInfo);
166
167     bool willBlockLoad = false;
168     for (const auto& action : actions) {
169         switch (action.type()) {
170         case ContentExtensions::ActionType::BlockLoad:
171             willBlockLoad = true;
172             break;
173         case ContentExtensions::ActionType::BlockCookies:
174             request.setAllowCookies(false);
175             break;
176         case ContentExtensions::ActionType::CSSDisplayNoneSelector:
177             if (resourceType == ResourceType::Document)
178                 initiatingDocumentLoader.addPendingContentExtensionDisplayNoneSelector(action.extensionIdentifier(), action.stringArgument(), action.actionID());
179             else if (currentDocument)
180                 currentDocument->extensionStyleSheets().addDisplayNoneSelector(action.extensionIdentifier(), action.stringArgument(), action.actionID());
181             break;
182         case ContentExtensions::ActionType::CSSDisplayNoneStyleSheet: {
183             StyleSheetContents* styleSheetContents = globalDisplayNoneStyleSheet(action.stringArgument());
184             if (styleSheetContents) {
185                 if (resourceType == ResourceType::Document)
186                     initiatingDocumentLoader.addPendingContentExtensionSheet(action.stringArgument(), *styleSheetContents);
187                 else if (currentDocument)
188                     currentDocument->extensionStyleSheets().maybeAddContentExtensionSheet(action.stringArgument(), *styleSheetContents);
189             }
190             break;
191         }
192         case ContentExtensions::ActionType::IgnorePreviousRules:
193         case ContentExtensions::ActionType::InvalidAction:
194             RELEASE_ASSERT_NOT_REACHED();
195         }
196     }
197
198     if (willBlockLoad) {
199         if (currentDocument)
200             currentDocument->addConsoleMessage(MessageSource::ContentBlocker, MessageLevel::Info, makeString("Content blocker prevented frame displaying ", mainDocumentURL.string(), " from loading a resource from ", request.url().string()));
201         request = ResourceRequest();
202     }
203 }
204
205 const String& ContentExtensionsBackend::displayNoneCSSRule()
206 {
207     static NeverDestroyed<const String> rule(ASCIILiteral("display:none !important;"));
208     return rule;
209 }
210
211 } // namespace ContentExtensions
212
213 } // namespace WebCore
214
215 #endif // ENABLE(CONTENT_EXTENSIONS)