293ed14ef4852fc878b4d1133d293e0ef0b47cdc
[platform/framework/web/crosswalk-tizen.git] /
1 /*
2  * Copyright (C) 2009, 2012 Google Inc. All rights reserved.
3  * Copyright (C) 2013, Intel Corporation
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are
7  * met:
8  *
9  *     * Redistributions of source code must retain the above copyright
10  * notice, this list of conditions and the following disclaimer.
11  *     * Redistributions in binary form must reproduce the above
12  * copyright notice, this list of conditions and the following disclaimer
13  * in the documentation and/or other materials provided with the
14  * distribution.
15  *     * Neither the name of Google Inc. nor the names of its
16  * contributors may be used to endorse or promote products derived from
17  * this software without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  */
31
32 #ifndef DocumentThreadableLoader_h
33 #define DocumentThreadableLoader_h
34
35 #include "core/CoreExport.h"
36 #include "core/fetch/RawResource.h"
37 #include "core/fetch/ResourceOwner.h"
38 #include "core/loader/ThreadableLoader.h"
39 #include "platform/Timer.h"
40 #include "platform/heap/Handle.h"
41 #include "platform/network/HTTPHeaderMap.h"
42 #include "platform/network/ResourceError.h"
43 #include "platform/weborigin/Referrer.h"
44 #include "wtf/Forward.h"
45 #include "wtf/text/WTFString.h"
46 #include <memory>
47
48 namespace blink {
49
50 class Document;
51 class KURL;
52 class ResourceRequest;
53 class SecurityOrigin;
54 class ThreadableLoaderClient;
55
56 class CORE_EXPORT DocumentThreadableLoader final : public ThreadableLoader,
57                                                    private RawResourceClient {
58   USING_GARBAGE_COLLECTED_MIXIN(DocumentThreadableLoader);
59
60  public:
61   static void loadResourceSynchronously(Document&,
62                                         const ResourceRequest&,
63                                         ThreadableLoaderClient&,
64                                         const ThreadableLoaderOptions&,
65                                         const ResourceLoaderOptions&);
66   static DocumentThreadableLoader* create(Document&,
67                                           ThreadableLoaderClient*,
68                                           const ThreadableLoaderOptions&,
69                                           const ResourceLoaderOptions&);
70   ~DocumentThreadableLoader() override;
71
72   void start(const ResourceRequest&) override;
73
74   void overrideTimeout(unsigned long timeout) override;
75
76   void cancel() override;
77   void setDefersLoading(bool);
78
79   DECLARE_TRACE();
80
81  private:
82   enum BlockingBehavior { LoadSynchronously, LoadAsynchronously };
83
84   DocumentThreadableLoader(Document&,
85                            ThreadableLoaderClient*,
86                            BlockingBehavior,
87                            const ThreadableLoaderOptions&,
88                            const ResourceLoaderOptions&);
89
90   void clear();
91
92   // ResourceClient
93   void notifyFinished(Resource*) override;
94
95   String debugName() const override { return "DocumentThreadableLoader"; }
96
97   // RawResourceClient
98   void dataSent(Resource*,
99                 unsigned long long bytesSent,
100                 unsigned long long totalBytesToBeSent) override;
101   void responseReceived(Resource*,
102                         const ResourceResponse&,
103                         std::unique_ptr<WebDataConsumerHandle>) override;
104   void setSerializedCachedMetadata(Resource*, const char*, size_t) override;
105   void dataReceived(Resource*, const char* data, size_t dataLength) override;
106   bool redirectReceived(Resource*,
107                         const ResourceRequest&,
108                         const ResourceResponse&) override;
109   void redirectBlocked() override;
110   void dataDownloaded(Resource*, int) override;
111   void didReceiveResourceTiming(Resource*, const ResourceTimingInfo&) override;
112
113   void cancelWithError(const ResourceError&);
114
115   // Notify Inspector and log to console about resource response. Use this
116   // method if response is not going to be finished normally.
117   void reportResponseReceived(unsigned long identifier,
118                               const ResourceResponse&);
119
120   // Methods containing code to handle resource fetch results which are common
121   // to both sync and async mode.
122   void handleResponse(unsigned long identifier,
123                       const ResourceResponse&,
124                       std::unique_ptr<WebDataConsumerHandle>);
125   void handleReceivedData(const char* data, size_t dataLength);
126   void handleSuccessfulFinish(unsigned long identifier, double finishTime);
127
128   void didTimeout(TimerBase*);
129   // Calls the appropriate loading method according to policy and data about
130   // origin. Only for handling the initial load (including fallback after
131   // consulting ServiceWorker).
132   void dispatchInitialRequest(const ResourceRequest&);
133   void makeCrossOriginAccessRequest(const ResourceRequest&);
134   // Loads m_fallbackRequestForServiceWorker.
135   void loadFallbackRequestForServiceWorker();
136   // Loads m_actualRequest.
137   void loadActualRequest();
138   // Clears m_actualRequest and reports access control check failure to
139   // m_client.
140   void handlePreflightFailure(const String& url,
141                               const String& errorDescription);
142   // Investigates the response for the preflight request. If successful,
143   // the actual request will be made later in handleSuccessfulFinish().
144   void handlePreflightResponse(const ResourceResponse&);
145   void handleError(const ResourceError&);
146
147   void loadRequestAsync(const ResourceRequest&, ResourceLoaderOptions);
148   void loadRequestSync(const ResourceRequest&, ResourceLoaderOptions);
149
150   void prepareCrossOriginRequest(ResourceRequest&);
151   void loadRequest(const ResourceRequest&, ResourceLoaderOptions);
152   bool isAllowedRedirect(const KURL&) const;
153   // Returns DoNotAllowStoredCredentials if m_forceDoNotAllowStoredCredentials
154   // is set. Otherwise, just returns allowCredentials value of
155   // m_resourceLoaderOptions.
156   StoredCredentials effectiveAllowCredentials() const;
157
158   // TODO(hiroshige): After crbug.com/633696 is fixed,
159   // - Remove RawResourceClientStateChecker logic,
160   // - Make DocumentThreadableLoader to be a ResourceOwner and remove this
161   //   re-implementation of ResourceOwner, and
162   // - Consider re-applying RawResourceClientStateChecker in a more
163   //   general fashion (crbug.com/640291).
164   RawResource* resource() const { return m_resource.get(); }
165   void clearResource() { setResource(nullptr); }
166   void setResource(RawResource* newResource) {
167     if (newResource == m_resource)
168       return;
169
170     if (RawResource* oldResource = m_resource.release()) {
171       m_checker.willRemoveClient();
172       oldResource->removeClient(this);
173     }
174
175     if (newResource) {
176       m_resource = newResource;
177       m_checker.willAddClient();
178       m_resource->addClient(this);
179     }
180   }
181   Member<RawResource> m_resource;
182   // End of ResourceOwner re-implementation, see above.
183
184   const SecurityOrigin* getSecurityOrigin() const;
185   Document& document() const;
186
187   ThreadableLoaderClient* m_client;
188   Member<Document> m_document;
189
190   const ThreadableLoaderOptions m_options;
191   // Some items may be overridden by m_forceDoNotAllowStoredCredentials and
192   // m_securityOrigin. In such a case, build a ResourceLoaderOptions with
193   // up-to-date values from them and this variable, and use it.
194   const ResourceLoaderOptions m_resourceLoaderOptions;
195
196   bool m_forceDoNotAllowStoredCredentials;
197   RefPtr<SecurityOrigin> m_securityOrigin;
198
199   // True while the initial URL and all the URLs of the redirects this object
200   // has followed, if any, are same-origin to getSecurityOrigin().
201   bool m_sameOriginRequest;
202   // Set to true if the current request is cross-origin and not simple.
203   bool m_crossOriginNonSimpleRequest;
204
205   // Set to true when the response data is given to a data consumer handle.
206   bool m_isUsingDataConsumerHandle;
207
208   const bool m_async;
209
210   // Holds the original request context (used for sanity checks).
211   WebURLRequest::RequestContext m_requestContext;
212
213   // Holds the original request for fallback in case the Service Worker
214   // does not respond.
215   ResourceRequest m_fallbackRequestForServiceWorker;
216
217   // Holds the original request and options for it during preflight request
218   // handling phase.
219   ResourceRequest m_actualRequest;
220   ResourceLoaderOptions m_actualOptions;
221
222   // stores simple request headers in case of a cross-origin redirect.
223   HTTPHeaderMap m_simpleRequestHeaders;
224
225   Timer<DocumentThreadableLoader> m_timeoutTimer;
226   double
227       m_requestStartedSeconds;  // Time an asynchronous fetch request is started
228
229   // Max number of times that this DocumentThreadableLoader can follow
230   // cross-origin redirects. This is used to limit the number of redirects. But
231   // this value is not the max number of total redirects allowed, because
232   // same-origin redirects are not counted here.
233   int m_corsRedirectLimit;
234
235   WebURLRequest::FetchRedirectMode m_redirectMode;
236
237   // Holds the referrer after a redirect response was received. This referrer is
238   // used to populate the HTTP Referer header when following the redirect.
239   bool m_overrideReferrer;
240   Referrer m_referrerAfterRedirect;
241
242   RawResourceClientStateChecker m_checker;
243 };
244
245 }  // namespace blink
246
247 #endif  // DocumentThreadableLoader_h