Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / core / page / EventSource.cpp
1 /*
2  * Copyright (C) 2009, 2012 Ericsson AB. All rights reserved.
3  * Copyright (C) 2010 Apple Inc. All rights reserved.
4  * Copyright (C) 2011, Code Aurora Forum. All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer
14  *    in the documentation and/or other materials provided with the
15  *    distribution.
16  * 3. Neither the name of Ericsson nor the names of its contributors
17  *    may be used to endorse or promote products derived from this
18  *    software without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31  */
32
33 #include "config.h"
34 #include "core/page/EventSource.h"
35
36 #include "bindings/core/v8/Dictionary.h"
37 #include "bindings/core/v8/ExceptionState.h"
38 #include "bindings/core/v8/ScriptController.h"
39 #include "bindings/core/v8/SerializedScriptValue.h"
40 #include "core/dom/Document.h"
41 #include "core/dom/ExceptionCode.h"
42 #include "core/dom/ExecutionContext.h"
43 #include "core/events/Event.h"
44 #include "core/events/MessageEvent.h"
45 #include "core/frame/LocalDOMWindow.h"
46 #include "core/frame/LocalFrame.h"
47 #include "core/frame/csp/ContentSecurityPolicy.h"
48 #include "core/html/parser/TextResourceDecoder.h"
49 #include "core/inspector/ConsoleMessage.h"
50 #include "core/loader/ThreadableLoader.h"
51 #include "platform/network/ResourceError.h"
52 #include "platform/network/ResourceRequest.h"
53 #include "platform/network/ResourceResponse.h"
54 #include "platform/weborigin/SecurityOrigin.h"
55 #include "public/platform/WebURLRequest.h"
56 #include "wtf/text/StringBuilder.h"
57
58 namespace blink {
59
60 const unsigned long long EventSource::defaultReconnectDelay = 3000;
61
62 inline EventSource::EventSource(ExecutionContext* context, const KURL& url, const Dictionary& eventSourceInit)
63     : ActiveDOMObject(context)
64     , m_url(url)
65     , m_withCredentials(false)
66     , m_state(CONNECTING)
67     , m_decoder(TextResourceDecoder::create("text/plain", "UTF-8"))
68     , m_connectTimer(this, &EventSource::connectTimerFired)
69     , m_discardTrailingNewline(false)
70     , m_requestInFlight(false)
71     , m_reconnectDelay(defaultReconnectDelay)
72 {
73     ScriptWrappable::init(this);
74     DictionaryHelper::get(eventSourceInit, "withCredentials", m_withCredentials);
75 }
76
77 PassRefPtrWillBeRawPtr<EventSource> EventSource::create(ExecutionContext* context, const String& url, const Dictionary& eventSourceInit, ExceptionState& exceptionState)
78 {
79     if (url.isEmpty()) {
80         exceptionState.throwDOMException(SyntaxError, "Cannot open an EventSource to an empty URL.");
81         return nullptr;
82     }
83
84     KURL fullURL = context->completeURL(url);
85     if (!fullURL.isValid()) {
86         exceptionState.throwDOMException(SyntaxError, "Cannot open an EventSource to '" + url + "'. The URL is invalid.");
87         return nullptr;
88     }
89
90     // FIXME: Convert this to check the isolated world's Content Security Policy once webkit.org/b/104520 is solved.
91     bool shouldBypassMainWorldCSP = false;
92     if (context->isDocument()) {
93         Document* document = toDocument(context);
94         shouldBypassMainWorldCSP = document->frame()->script().shouldBypassMainWorldCSP();
95     }
96     if (!shouldBypassMainWorldCSP && !context->contentSecurityPolicy()->allowConnectToSource(fullURL)) {
97         // We can safely expose the URL to JavaScript, as this exception is generate synchronously before any redirects take place.
98         exceptionState.throwSecurityError("Refused to connect to '" + fullURL.elidedString() + "' because it violates the document's Content Security Policy.");
99         return nullptr;
100     }
101
102     RefPtrWillBeRawPtr<EventSource> source = adoptRefWillBeRefCountedGarbageCollected(new EventSource(context, fullURL, eventSourceInit));
103
104     source->scheduleInitialConnect();
105     source->suspendIfNeeded();
106
107     return source.release();
108 }
109
110 EventSource::~EventSource()
111 {
112     ASSERT(m_state == CLOSED);
113     ASSERT(!m_requestInFlight);
114 }
115
116 void EventSource::scheduleInitialConnect()
117 {
118     ASSERT(m_state == CONNECTING);
119     ASSERT(!m_requestInFlight);
120
121     m_connectTimer.startOneShot(0, FROM_HERE);
122 }
123
124 void EventSource::connect()
125 {
126     ASSERT(m_state == CONNECTING);
127     ASSERT(!m_requestInFlight);
128     ASSERT(executionContext());
129
130     ExecutionContext& executionContext = *this->executionContext();
131     ResourceRequest request(m_url);
132     request.setHTTPMethod("GET");
133     request.setHTTPHeaderField("Accept", "text/event-stream");
134     request.setHTTPHeaderField("Cache-Control", "no-cache");
135     request.setRequestContext(blink::WebURLRequest::RequestContextEventSource);
136     if (!m_lastEventId.isEmpty())
137         request.setHTTPHeaderField("Last-Event-ID", m_lastEventId);
138
139     SecurityOrigin* origin = executionContext.securityOrigin();
140
141     ThreadableLoaderOptions options;
142     options.preflightPolicy = PreventPreflight;
143     options.crossOriginRequestPolicy = UseAccessControl;
144     options.contentSecurityPolicyEnforcement = ContentSecurityPolicy::shouldBypassMainWorld(&executionContext) ? DoNotEnforceContentSecurityPolicy : EnforceConnectSrcDirective;
145
146     ResourceLoaderOptions resourceLoaderOptions;
147     resourceLoaderOptions.allowCredentials = (origin->canRequest(m_url) || m_withCredentials) ? AllowStoredCredentials : DoNotAllowStoredCredentials;
148     resourceLoaderOptions.credentialsRequested = m_withCredentials ? ClientRequestedCredentials : ClientDidNotRequestCredentials;
149     resourceLoaderOptions.dataBufferingPolicy = DoNotBufferData;
150     resourceLoaderOptions.securityOrigin = origin;
151     resourceLoaderOptions.mixedContentBlockingTreatment = TreatAsActiveContent;
152
153     m_loader = ThreadableLoader::create(executionContext, this, request, options, resourceLoaderOptions);
154
155     if (m_loader)
156         m_requestInFlight = true;
157 }
158
159 void EventSource::networkRequestEnded()
160 {
161     if (!m_requestInFlight)
162         return;
163
164     m_requestInFlight = false;
165
166     if (m_state != CLOSED)
167         scheduleReconnect();
168 }
169
170 void EventSource::scheduleReconnect()
171 {
172     m_state = CONNECTING;
173     m_connectTimer.startOneShot(m_reconnectDelay / 1000.0, FROM_HERE);
174     dispatchEvent(Event::create(EventTypeNames::error));
175 }
176
177 void EventSource::connectTimerFired(Timer<EventSource>*)
178 {
179     connect();
180 }
181
182 String EventSource::url() const
183 {
184     return m_url.string();
185 }
186
187 bool EventSource::withCredentials() const
188 {
189     return m_withCredentials;
190 }
191
192 EventSource::State EventSource::readyState() const
193 {
194     return m_state;
195 }
196
197 void EventSource::close()
198 {
199     if (m_state == CLOSED) {
200         ASSERT(!m_requestInFlight);
201         return;
202     }
203
204     // Stop trying to reconnect if EventSource was explicitly closed or if ActiveDOMObject::stop() was called.
205     if (m_connectTimer.isActive()) {
206         m_connectTimer.stop();
207     }
208
209     if (m_requestInFlight)
210         m_loader->cancel();
211
212     m_state = CLOSED;
213 }
214
215 const AtomicString& EventSource::interfaceName() const
216 {
217     return EventTargetNames::EventSource;
218 }
219
220 ExecutionContext* EventSource::executionContext() const
221 {
222     return ActiveDOMObject::executionContext();
223 }
224
225 void EventSource::didReceiveResponse(unsigned long, const ResourceResponse& response)
226 {
227     ASSERT(m_state == CONNECTING);
228     ASSERT(m_requestInFlight);
229
230     m_eventStreamOrigin = SecurityOrigin::create(response.url())->toString();
231     int statusCode = response.httpStatusCode();
232     bool mimeTypeIsValid = response.mimeType() == "text/event-stream";
233     bool responseIsValid = statusCode == 200 && mimeTypeIsValid;
234     if (responseIsValid) {
235         const String& charset = response.textEncodingName();
236         // If we have a charset, the only allowed value is UTF-8 (case-insensitive).
237         responseIsValid = charset.isEmpty() || equalIgnoringCase(charset, "UTF-8");
238         if (!responseIsValid) {
239             StringBuilder message;
240             message.appendLiteral("EventSource's response has a charset (\"");
241             message.append(charset);
242             message.appendLiteral("\") that is not UTF-8. Aborting the connection.");
243             // FIXME: We are missing the source line.
244             executionContext()->addConsoleMessage(ConsoleMessage::create(JSMessageSource, ErrorMessageLevel, message.toString()));
245         }
246     } else {
247         // To keep the signal-to-noise ratio low, we only log 200-response with an invalid MIME type.
248         if (statusCode == 200 && !mimeTypeIsValid) {
249             StringBuilder message;
250             message.appendLiteral("EventSource's response has a MIME type (\"");
251             message.append(response.mimeType());
252             message.appendLiteral("\") that is not \"text/event-stream\". Aborting the connection.");
253             // FIXME: We are missing the source line.
254             executionContext()->addConsoleMessage(ConsoleMessage::create(JSMessageSource, ErrorMessageLevel, message.toString()));
255         }
256     }
257
258     if (responseIsValid) {
259         m_state = OPEN;
260         dispatchEvent(Event::create(EventTypeNames::open));
261     } else {
262         m_loader->cancel();
263         dispatchEvent(Event::create(EventTypeNames::error));
264     }
265 }
266
267 void EventSource::didReceiveData(const char* data, int length)
268 {
269     ASSERT(m_state == OPEN);
270     ASSERT(m_requestInFlight);
271
272     append(m_receiveBuf, m_decoder->decode(data, length));
273     parseEventStream();
274 }
275
276 void EventSource::didFinishLoading(unsigned long, double)
277 {
278     ASSERT(m_state == OPEN);
279     ASSERT(m_requestInFlight);
280
281     if (m_receiveBuf.size() > 0 || m_data.size() > 0) {
282         parseEventStream();
283
284         // Discard everything that has not been dispatched by now.
285         m_receiveBuf.clear();
286         m_data.clear();
287         m_eventName = emptyAtom;
288         m_currentlyParsedEventId = nullAtom;
289     }
290     networkRequestEnded();
291 }
292
293 void EventSource::didFail(const ResourceError& error)
294 {
295     ASSERT(m_state != CLOSED);
296     ASSERT(m_requestInFlight);
297
298     if (error.isCancellation())
299         m_state = CLOSED;
300     networkRequestEnded();
301 }
302
303 void EventSource::didFailAccessControlCheck(const ResourceError& error)
304 {
305     String message = "EventSource cannot load " + error.failingURL() + ". " + error.localizedDescription();
306     executionContext()->addConsoleMessage(ConsoleMessage::create(JSMessageSource, ErrorMessageLevel, message));
307
308     abortConnectionAttempt();
309 }
310
311 void EventSource::didFailRedirectCheck()
312 {
313     abortConnectionAttempt();
314 }
315
316 void EventSource::abortConnectionAttempt()
317 {
318     ASSERT(m_state == CONNECTING);
319
320     if (m_requestInFlight) {
321         m_loader->cancel();
322     } else {
323         m_state = CLOSED;
324     }
325
326     ASSERT(m_state == CLOSED);
327     dispatchEvent(Event::create(EventTypeNames::error));
328 }
329
330 void EventSource::parseEventStream()
331 {
332     unsigned bufPos = 0;
333     unsigned bufSize = m_receiveBuf.size();
334     while (bufPos < bufSize) {
335         if (m_discardTrailingNewline) {
336             if (m_receiveBuf[bufPos] == '\n')
337                 bufPos++;
338             m_discardTrailingNewline = false;
339         }
340
341         int lineLength = -1;
342         int fieldLength = -1;
343         for (unsigned i = bufPos; lineLength < 0 && i < bufSize; i++) {
344             switch (m_receiveBuf[i]) {
345             case ':':
346                 if (fieldLength < 0)
347                     fieldLength = i - bufPos;
348                 break;
349             case '\r':
350                 m_discardTrailingNewline = true;
351             case '\n':
352                 lineLength = i - bufPos;
353                 break;
354             }
355         }
356
357         if (lineLength < 0)
358             break;
359
360         parseEventStreamLine(bufPos, fieldLength, lineLength);
361         bufPos += lineLength + 1;
362
363         // EventSource.close() might've been called by one of the message event handlers.
364         // Per spec, no further messages should be fired after that.
365         if (m_state == CLOSED)
366             break;
367     }
368
369     if (bufPos == bufSize)
370         m_receiveBuf.clear();
371     else if (bufPos)
372         m_receiveBuf.remove(0, bufPos);
373 }
374
375 void EventSource::parseEventStreamLine(unsigned bufPos, int fieldLength, int lineLength)
376 {
377     if (!lineLength) {
378         if (!m_data.isEmpty()) {
379             m_data.removeLast();
380             if (!m_currentlyParsedEventId.isNull()) {
381                 m_lastEventId = m_currentlyParsedEventId;
382                 m_currentlyParsedEventId = nullAtom;
383             }
384             dispatchEvent(createMessageEvent());
385         }
386         if (!m_eventName.isEmpty())
387             m_eventName = emptyAtom;
388     } else if (fieldLength) {
389         bool noValue = fieldLength < 0;
390
391         String field(&m_receiveBuf[bufPos], noValue ? lineLength : fieldLength);
392         int step;
393         if (noValue)
394             step = lineLength;
395         else if (m_receiveBuf[bufPos + fieldLength + 1] != ' ')
396             step = fieldLength + 1;
397         else
398             step = fieldLength + 2;
399         bufPos += step;
400         int valueLength = lineLength - step;
401
402         if (field == "data") {
403             if (valueLength)
404                 m_data.append(&m_receiveBuf[bufPos], valueLength);
405             m_data.append('\n');
406         } else if (field == "event") {
407             m_eventName = valueLength ? AtomicString(&m_receiveBuf[bufPos], valueLength) : "";
408         } else if (field == "id") {
409             m_currentlyParsedEventId = valueLength ? AtomicString(&m_receiveBuf[bufPos], valueLength) : "";
410         } else if (field == "retry") {
411             if (!valueLength)
412                 m_reconnectDelay = defaultReconnectDelay;
413             else {
414                 String value(&m_receiveBuf[bufPos], valueLength);
415                 bool ok;
416                 unsigned long long retry = value.toUInt64(&ok);
417                 if (ok)
418                     m_reconnectDelay = retry;
419             }
420         }
421     }
422 }
423
424 void EventSource::stop()
425 {
426     close();
427 }
428
429 bool EventSource::hasPendingActivity() const
430 {
431     return m_state != CLOSED;
432 }
433
434 PassRefPtrWillBeRawPtr<MessageEvent> EventSource::createMessageEvent()
435 {
436     RefPtrWillBeRawPtr<MessageEvent> event = MessageEvent::create();
437     event->initMessageEvent(m_eventName.isEmpty() ? EventTypeNames::message : m_eventName, false, false, SerializedScriptValue::create(String(m_data)), m_eventStreamOrigin, m_lastEventId, 0, nullptr);
438     m_data.clear();
439     return event.release();
440 }
441
442 } // namespace blink