Apply ContentExtension actions after redirects.
[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 "DFABytecodeInterpreter.h"
34 #include "Document.h"
35 #include "DocumentLoader.h"
36 #include "Frame.h"
37 #include "MainFrame.h"
38 #include "ResourceLoadInfo.h"
39 #include "URL.h"
40 #include "UserContentController.h"
41 #include <wtf/NeverDestroyed.h>
42 #include <wtf/text/CString.h>
43
44 namespace WebCore {
45
46 namespace ContentExtensions {
47     
48 void ContentExtensionsBackend::addContentExtension(const String& identifier, RefPtr<CompiledContentExtension> compiledContentExtension)
49 {
50     ASSERT(!identifier.isEmpty());
51     if (identifier.isEmpty())
52         return;
53
54     if (!compiledContentExtension) {
55         removeContentExtension(identifier);
56         return;
57     }
58
59     RefPtr<ContentExtension> extension = ContentExtension::create(identifier, adoptRef(*compiledContentExtension.leakRef()));
60     m_contentExtensions.set(identifier, WTF::move(extension));
61 }
62
63 void ContentExtensionsBackend::removeContentExtension(const String& identifier)
64 {
65     m_contentExtensions.remove(identifier);
66 }
67
68 void ContentExtensionsBackend::removeAllContentExtensions()
69 {
70     m_contentExtensions.clear();
71 }
72
73 Vector<Action> ContentExtensionsBackend::actionsForResourceLoad(const ResourceLoadInfo& resourceLoadInfo) const
74 {
75     const String& urlString = resourceLoadInfo.resourceURL.string();
76     ASSERT_WITH_MESSAGE(urlString.containsOnlyASCII(), "A decoded URL should only contain ASCII characters. The matching algorithm assumes the input is ASCII.");
77     const CString& urlCString = urlString.utf8();
78
79     Vector<Action> finalActions;
80     ResourceFlags flags = resourceLoadInfo.getResourceFlags();
81     for (auto& contentExtension : m_contentExtensions.values()) {
82         const CompiledContentExtension& compiledExtension = contentExtension->compiledExtension();
83         DFABytecodeInterpreter interpreter(compiledExtension.bytecode(), compiledExtension.bytecodeLength());
84         DFABytecodeInterpreter::Actions triggeredActions = interpreter.interpret(urlCString, flags);
85         
86         const SerializedActionByte* actions = compiledExtension.actions();
87         const unsigned actionsLength = compiledExtension.actionsLength();
88         
89         bool sawIgnorePreviousRules = false;
90         if (!triggeredActions.isEmpty()) {
91             Vector<unsigned> actionLocations;
92             actionLocations.reserveInitialCapacity(triggeredActions.size());
93             for (auto actionLocation : triggeredActions)
94                 actionLocations.append(static_cast<unsigned>(actionLocation));
95             std::sort(actionLocations.begin(), actionLocations.end());
96
97             // Add actions in reverse order to properly deal with IgnorePreviousRules.
98             for (unsigned i = actionLocations.size(); i; i--) {
99                 Action action = Action::deserialize(actions, actionsLength, actionLocations[i - 1]);
100                 if (action.type() == ActionType::IgnorePreviousRules) {
101                     sawIgnorePreviousRules = true;
102                     break;
103                 }
104                 finalActions.append(action);
105             }
106         }
107         if (!sawIgnorePreviousRules)
108             finalActions.append(Action(ActionType::CSSDisplayNoneStyleSheet, contentExtension->identifier()));
109     }
110     return finalActions;
111 }
112
113 StyleSheetContents* ContentExtensionsBackend::globalDisplayNoneStyleSheet(const String& identifier) const
114 {
115     const auto& contentExtension = m_contentExtensions.get(identifier);
116     return contentExtension ? contentExtension->globalDisplayNoneStyleSheet() : nullptr;
117 }
118
119 void ContentExtensionsBackend::processContentExtensionRulesForLoad(ResourceRequest& request, ResourceType resourceType, DocumentLoader& initiatingDocumentLoader)
120 {
121     Document* currentDocument = nullptr;
122     URL mainDocumentURL;
123
124     if (initiatingDocumentLoader.frame()) {
125         currentDocument = initiatingDocumentLoader.frame()->document();
126
127         if (Document* mainDocument = initiatingDocumentLoader.frame()->mainFrame().document())
128             mainDocumentURL = mainDocument->url();
129     }
130
131     ResourceLoadInfo resourceLoadInfo = { request.url(), mainDocumentURL, resourceType };
132     Vector<ContentExtensions::Action> actions = actionsForResourceLoad(resourceLoadInfo);
133
134     StringBuilder css;
135     bool willBlockLoad = false;
136     for (const auto& action : actions) {
137         switch (action.type()) {
138         case ContentExtensions::ActionType::BlockLoad:
139             willBlockLoad = true;
140             break;
141         case ContentExtensions::ActionType::BlockCookies:
142             request.setAllowCookies(false);
143             break;
144         case ContentExtensions::ActionType::CSSDisplayNoneSelector:
145             css.append(action.stringArgument());
146             css.append(displayNoneCSSRule());
147             break;
148         case ContentExtensions::ActionType::CSSDisplayNoneStyleSheet: {
149             StyleSheetContents* styleSheetContents = globalDisplayNoneStyleSheet(action.stringArgument());
150             if (styleSheetContents) {
151                 if (resourceType == ResourceType::Document)
152                     initiatingDocumentLoader.addPendingContentExtensionSheet(action.stringArgument(), *styleSheetContents);
153                 else if (currentDocument)
154                     currentDocument->styleSheetCollection().maybeAddContentExtensionSheet(action.stringArgument(), *styleSheetContents);
155             }
156             break;
157         }
158         case ContentExtensions::ActionType::IgnorePreviousRules:
159         case ContentExtensions::ActionType::InvalidAction:
160             RELEASE_ASSERT_NOT_REACHED();
161         }
162     }
163
164     if (css.length()) {
165         Ref<StyleSheetContents> styleSheet = StyleSheetContents::create();
166         styleSheet->setIsUserStyleSheet(true);
167
168         if (styleSheet->parseString(css.toString())) {
169             if (resourceType == ResourceType::Document)
170                 initiatingDocumentLoader.addPendingContentExtensionSheet(styleSheet);
171             else if (currentDocument)
172                 currentDocument->styleSheetCollection().addUserSheet(WTF::move(styleSheet));
173         }
174     }
175
176     if (willBlockLoad)
177         request = ResourceRequest();
178 }
179
180 const String& ContentExtensionsBackend::displayNoneCSSRule()
181 {
182     static NeverDestroyed<const String> rule(ASCIILiteral("{display:none !important;}\n"));
183     return rule;
184 }
185
186 } // namespace ContentExtensions
187
188 } // namespace WebCore
189
190 #endif // ENABLE(CONTENT_EXTENSIONS)