[Content Extensions] Remove memory page reporting
[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 "Frame.h"
38 #include "MainFrame.h"
39 #include "ResourceLoadInfo.h"
40 #include "URL.h"
41 #include "UserContentController.h"
42 #include <wtf/NeverDestroyed.h>
43 #include <wtf/text/CString.h>
44
45 namespace WebCore {
46
47 namespace ContentExtensions {
48     
49 void ContentExtensionsBackend::addContentExtension(const String& identifier, RefPtr<CompiledContentExtension> compiledContentExtension)
50 {
51     ASSERT(!identifier.isEmpty());
52     if (identifier.isEmpty())
53         return;
54
55     if (!compiledContentExtension) {
56         removeContentExtension(identifier);
57         return;
58     }
59
60     RefPtr<ContentExtension> extension = ContentExtension::create(identifier, adoptRef(*compiledContentExtension.leakRef()));
61     m_contentExtensions.set(identifier, WTF::move(extension));
62 }
63
64 void ContentExtensionsBackend::removeContentExtension(const String& identifier)
65 {
66     m_contentExtensions.remove(identifier);
67 }
68
69 void ContentExtensionsBackend::removeAllContentExtensions()
70 {
71     m_contentExtensions.clear();
72 }
73
74 Vector<Action> ContentExtensionsBackend::actionsForResourceLoad(const ResourceLoadInfo& resourceLoadInfo) const
75 {
76 #if CONTENT_EXTENSIONS_PERFORMANCE_REPORTING
77     double addedTimeStart = monotonicallyIncreasingTime();
78 #endif
79     if (resourceLoadInfo.resourceURL.protocolIsData())
80         return Vector<Action>();
81
82     const String& urlString = resourceLoadInfo.resourceURL.string();
83     ASSERT_WITH_MESSAGE(urlString.containsOnlyASCII(), "A decoded URL should only contain ASCII characters. The matching algorithm assumes the input is ASCII.");
84     const CString& urlCString = urlString.utf8();
85
86     Vector<Action> finalActions;
87     ResourceFlags flags = resourceLoadInfo.getResourceFlags();
88     for (auto& contentExtension : m_contentExtensions.values()) {
89         RELEASE_ASSERT(contentExtension);
90         const CompiledContentExtension& compiledExtension = contentExtension->compiledExtension();
91         
92         DFABytecodeInterpreter withoutDomainsInterpreter(compiledExtension.filtersWithoutDomainsBytecode(), compiledExtension.filtersWithoutDomainsBytecodeLength());
93         DFABytecodeInterpreter::Actions triggeredActions = withoutDomainsInterpreter.interpret(urlCString, flags);
94         
95         // Check to see if there are any actions triggered with if- or unless-domain and check the domain if there are.
96         DFABytecodeInterpreter withDomainsInterpreter(compiledExtension.filtersWithDomainsBytecode(), compiledExtension.filtersWithDomainsBytecodeLength());
97         
98         DFABytecodeInterpreter::Actions withDomainsPossibleActions = withDomainsInterpreter.interpret(urlCString, flags);
99         if (!withDomainsPossibleActions.isEmpty()) {
100             DFABytecodeInterpreter domainsInterpreter(compiledExtension.domainFiltersBytecode(), compiledExtension.domainFiltersBytecodeLength());
101             DFABytecodeInterpreter::Actions domainsActions = domainsInterpreter.interpret(resourceLoadInfo.mainDocumentURL.host().utf8(), flags);
102             
103             DFABytecodeInterpreter::Actions ifDomainActions;
104             DFABytecodeInterpreter::Actions unlessDomainActions;
105             for (uint64_t action : domainsActions) {
106                 if (action & IfDomainFlag)
107                     ifDomainActions.add(action);
108                 else
109                     unlessDomainActions.add(action);
110             }
111             
112             for (uint64_t action : withDomainsPossibleActions) {
113                 if (ifDomainActions.contains(action)) {
114                     // If an if-domain trigger matches, add the action.
115                     ASSERT(action & IfDomainFlag);
116                     triggeredActions.add(action & ~IfDomainFlag);
117                 } else if (!(action & IfDomainFlag) && !unlessDomainActions.contains(action)) {
118                     // If this action did not need an if-domain, it must have been an unless-domain rule.
119                     // Add the action unless it matched an unless-domain trigger.
120                     triggeredActions.add(action);
121                 }
122             }
123         }
124         
125         const SerializedActionByte* actions = compiledExtension.actions();
126         const unsigned actionsLength = compiledExtension.actionsLength();
127         
128         bool sawIgnorePreviousRules = false;
129         if (!triggeredActions.isEmpty()) {
130             Vector<unsigned> actionLocations;
131             actionLocations.reserveInitialCapacity(triggeredActions.size());
132             for (auto actionLocation : triggeredActions)
133                 actionLocations.append(static_cast<unsigned>(actionLocation));
134             std::sort(actionLocations.begin(), actionLocations.end());
135
136             // Add actions in reverse order to properly deal with IgnorePreviousRules.
137             for (unsigned i = actionLocations.size(); i; i--) {
138                 Action action = Action::deserialize(actions, actionsLength, actionLocations[i - 1]);
139                 action.setExtensionIdentifier(contentExtension->identifier());
140                 if (action.type() == ActionType::IgnorePreviousRules) {
141                     sawIgnorePreviousRules = true;
142                     break;
143                 }
144                 finalActions.append(action);
145             }
146         }
147         if (!sawIgnorePreviousRules) {
148             finalActions.append(Action(ActionType::CSSDisplayNoneStyleSheet, contentExtension->identifier()));
149             finalActions.last().setExtensionIdentifier(contentExtension->identifier());
150         }
151     }
152 #if CONTENT_EXTENSIONS_PERFORMANCE_REPORTING
153     double addedTimeEnd = monotonicallyIncreasingTime();
154     WTFLogAlways("Time added: %f microseconds %s", (addedTimeEnd - addedTimeStart) * 1.0e6, resourceLoadInfo.resourceURL.string().utf8().data());
155 #endif
156     return finalActions;
157 }
158
159 StyleSheetContents* ContentExtensionsBackend::globalDisplayNoneStyleSheet(const String& identifier) const
160 {
161     const auto& contentExtension = m_contentExtensions.get(identifier);
162     return contentExtension ? contentExtension->globalDisplayNoneStyleSheet() : nullptr;
163 }
164
165 void ContentExtensionsBackend::processContentExtensionRulesForLoad(ResourceRequest& request, ResourceType resourceType, DocumentLoader& initiatingDocumentLoader)
166 {
167     Document* currentDocument = nullptr;
168     URL mainDocumentURL;
169
170     if (initiatingDocumentLoader.frame()) {
171         currentDocument = initiatingDocumentLoader.frame()->document();
172
173         if (Document* mainDocument = initiatingDocumentLoader.frame()->mainFrame().document())
174             mainDocumentURL = mainDocument->url();
175     }
176
177     ResourceLoadInfo resourceLoadInfo = { request.url(), mainDocumentURL, resourceType };
178     Vector<ContentExtensions::Action> actions = actionsForResourceLoad(resourceLoadInfo);
179
180     StringBuilder css;
181     bool willBlockLoad = false;
182     for (const auto& action : actions) {
183         switch (action.type()) {
184         case ContentExtensions::ActionType::BlockLoad:
185             willBlockLoad = true;
186             break;
187         case ContentExtensions::ActionType::BlockCookies:
188             request.setAllowCookies(false);
189             break;
190         case ContentExtensions::ActionType::CSSDisplayNoneSelector:
191             if (resourceType == ResourceType::Document)
192                 initiatingDocumentLoader.addPendingContentExtensionDisplayNoneSelector(action.extensionIdentifier(), action.stringArgument(), action.actionID());
193             else if (currentDocument)
194                 currentDocument->styleSheetCollection().addDisplayNoneSelector(action.extensionIdentifier(), action.stringArgument(), action.actionID());
195             break;
196         case ContentExtensions::ActionType::CSSDisplayNoneStyleSheet: {
197             StyleSheetContents* styleSheetContents = globalDisplayNoneStyleSheet(action.stringArgument());
198             if (styleSheetContents) {
199                 if (resourceType == ResourceType::Document)
200                     initiatingDocumentLoader.addPendingContentExtensionSheet(action.stringArgument(), *styleSheetContents);
201                 else if (currentDocument)
202                     currentDocument->styleSheetCollection().maybeAddContentExtensionSheet(action.stringArgument(), *styleSheetContents);
203             }
204             break;
205         }
206         case ContentExtensions::ActionType::IgnorePreviousRules:
207         case ContentExtensions::ActionType::InvalidAction:
208             RELEASE_ASSERT_NOT_REACHED();
209         }
210     }
211
212     if (willBlockLoad) {
213         if (currentDocument)
214             currentDocument->addConsoleMessage(MessageSource::ContentBlocker, MessageLevel::Info, makeString("Content blocker prevented frame displaying ", mainDocumentURL.string(), " from loading a resource from ", request.url().string()));
215         request = ResourceRequest();
216     }
217 }
218
219 const String& ContentExtensionsBackend::displayNoneCSSRule()
220 {
221     static NeverDestroyed<const String> rule(ASCIILiteral("display:none !important;"));
222     return rule;
223 }
224
225 } // namespace ContentExtensions
226
227 } // namespace WebCore
228
229 #endif // ENABLE(CONTENT_EXTENSIONS)