Upstream version 7.36.149.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/v8/Dictionary.h"
37 #include "bindings/v8/ExceptionState.h"
38 #include "bindings/v8/ScriptController.h"
39 #include "bindings/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/DOMWindow.h"
46 #include "core/frame/LocalFrame.h"
47 #include "core/frame/csp/ContentSecurityPolicy.h"
48 #include "core/html/parser/TextResourceDecoder.h"
49 #include "core/loader/ThreadableLoader.h"
50 #include "platform/network/ResourceError.h"
51 #include "platform/network/ResourceRequest.h"
52 #include "platform/network/ResourceResponse.h"
53 #include "platform/weborigin/SecurityOrigin.h"
54 #include "wtf/text/StringBuilder.h"
55
56 namespace WebCore {
57
58 const unsigned long long EventSource::defaultReconnectDelay = 3000;
59
60 inline EventSource::EventSource(ExecutionContext* context, const KURL& url, const Dictionary& eventSourceInit)
61     : ActiveDOMObject(context)
62     , m_url(url)
63     , m_withCredentials(false)
64     , m_state(CONNECTING)
65     , m_decoder(TextResourceDecoder::create("text/plain", "UTF-8"))
66     , m_connectTimer(this, &EventSource::connectTimerFired)
67     , m_discardTrailingNewline(false)
68     , m_requestInFlight(false)
69     , m_reconnectDelay(defaultReconnectDelay)
70 {
71     ScriptWrappable::init(this);
72     eventSourceInit.get("withCredentials", m_withCredentials);
73 }
74
75 PassRefPtrWillBeRawPtr<EventSource> EventSource::create(ExecutionContext* context, const String& url, const Dictionary& eventSourceInit, ExceptionState& exceptionState)
76 {
77     if (url.isEmpty()) {
78         exceptionState.throwDOMException(SyntaxError, "Cannot open an EventSource to an empty URL.");
79         return nullptr;
80     }
81
82     KURL fullURL = context->completeURL(url);
83     if (!fullURL.isValid()) {
84         exceptionState.throwDOMException(SyntaxError, "Cannot open an EventSource to '" + url + "'. The URL is invalid.");
85         return nullptr;
86     }
87
88     // FIXME: Convert this to check the isolated world's Content Security Policy once webkit.org/b/104520 is solved.
89     bool shouldBypassMainWorldContentSecurityPolicy = false;
90     if (context->isDocument()) {
91         Document* document = toDocument(context);
92         shouldBypassMainWorldContentSecurityPolicy = document->frame()->script().shouldBypassMainWorldContentSecurityPolicy();
93     }
94     if (!shouldBypassMainWorldContentSecurityPolicy && !context->contentSecurityPolicy()->allowConnectToSource(fullURL)) {
95         // We can safely expose the URL to JavaScript, as this exception is generate synchronously before any redirects take place.
96         exceptionState.throwSecurityError("Refused to connect to '" + fullURL.elidedString() + "' because it violates the document's Content Security Policy.");
97         return nullptr;
98     }
99
100     RefPtrWillBeRawPtr<EventSource> source = adoptRefWillBeRefCountedGarbageCollected(new EventSource(context, fullURL, eventSourceInit));
101
102     source->setPendingActivity(source.get());
103     source->scheduleInitialConnect();
104     source->suspendIfNeeded();
105
106     return source.release();
107 }
108
109 EventSource::~EventSource()
110 {
111     ASSERT(m_state == CLOSED);
112     ASSERT(!m_requestInFlight);
113 }
114
115 void EventSource::scheduleInitialConnect()
116 {
117     ASSERT(m_state == CONNECTING);
118     ASSERT(!m_requestInFlight);
119
120     m_connectTimer.startOneShot(0, FROM_HERE);
121 }
122
123 void EventSource::connect()
124 {
125     ASSERT(m_state == CONNECTING);
126     ASSERT(!m_requestInFlight);
127     ASSERT(executionContext());
128
129     ExecutionContext& executionContext = *this->executionContext();
130     ResourceRequest request(m_url);
131     request.setHTTPMethod("GET");
132     request.setHTTPHeaderField("Accept", "text/event-stream");
133     request.setHTTPHeaderField("Cache-Control", "no-cache");
134     if (!m_lastEventId.isEmpty())
135         request.setHTTPHeaderField("Last-Event-ID", m_lastEventId);
136
137     SecurityOrigin* origin = executionContext.securityOrigin();
138
139     ThreadableLoaderOptions options;
140     options.sniffContent = DoNotSniffContent;
141     options.allowCredentials = (origin->canRequest(m_url) || m_withCredentials) ? AllowStoredCredentials : DoNotAllowStoredCredentials;
142     options.credentialsRequested = m_withCredentials ? ClientRequestedCredentials : ClientDidNotRequestCredentials;
143     options.preflightPolicy = PreventPreflight;
144     options.crossOriginRequestPolicy = UseAccessControl;
145     options.dataBufferingPolicy = DoNotBufferData;
146     options.securityOrigin = origin;
147     options.contentSecurityPolicyEnforcement = ContentSecurityPolicy::shouldBypassMainWorld(&executionContext) ? DoNotEnforceContentSecurityPolicy : EnforceConnectSrcDirective;
148
149     m_loader = ThreadableLoader::create(executionContext, this, request, options);
150
151     if (m_loader)
152         m_requestInFlight = true;
153 }
154
155 void EventSource::networkRequestEnded()
156 {
157     if (!m_requestInFlight)
158         return;
159
160     m_requestInFlight = false;
161
162     if (m_state != CLOSED)
163         scheduleReconnect();
164     else
165         unsetPendingActivity(this);
166 }
167
168 void EventSource::scheduleReconnect()
169 {
170     m_state = CONNECTING;
171     m_connectTimer.startOneShot(m_reconnectDelay / 1000.0, FROM_HERE);
172     dispatchEvent(Event::create(EventTypeNames::error));
173 }
174
175 void EventSource::connectTimerFired(Timer<EventSource>*)
176 {
177     connect();
178 }
179
180 String EventSource::url() const
181 {
182     return m_url.string();
183 }
184
185 bool EventSource::withCredentials() const
186 {
187     return m_withCredentials;
188 }
189
190 EventSource::State EventSource::readyState() const
191 {
192     return m_state;
193 }
194
195 void EventSource::close()
196 {
197     if (m_state == CLOSED) {
198         ASSERT(!m_requestInFlight);
199         return;
200     }
201
202     // Stop trying to reconnect if EventSource was explicitly closed or if ActiveDOMObject::stop() was called.
203     if (m_connectTimer.isActive()) {
204         m_connectTimer.stop();
205         unsetPendingActivity(this);
206     }
207
208     if (m_requestInFlight)
209         m_loader->cancel();
210
211     m_state = CLOSED;
212 }
213
214 const AtomicString& EventSource::interfaceName() const
215 {
216     return EventTargetNames::EventSource;
217 }
218
219 ExecutionContext* EventSource::executionContext() const
220 {
221     return ActiveDOMObject::executionContext();
222 }
223
224 void EventSource::didReceiveResponse(unsigned long, const ResourceResponse& response)
225 {
226     ASSERT(m_state == CONNECTING);
227     ASSERT(m_requestInFlight);
228
229     m_eventStreamOrigin = SecurityOrigin::create(response.url())->toString();
230     int statusCode = response.httpStatusCode();
231     bool mimeTypeIsValid = response.mimeType() == "text/event-stream";
232     bool responseIsValid = statusCode == 200 && mimeTypeIsValid;
233     if (responseIsValid) {
234         const String& charset = response.textEncodingName();
235         // If we have a charset, the only allowed value is UTF-8 (case-insensitive).
236         responseIsValid = charset.isEmpty() || equalIgnoringCase(charset, "UTF-8");
237         if (!responseIsValid) {
238             StringBuilder message;
239             message.appendLiteral("EventSource's response has a charset (\"");
240             message.append(charset);
241             message.appendLiteral("\") that is not UTF-8. Aborting the connection.");
242             // FIXME: We are missing the source line.
243             executionContext()->addConsoleMessage(JSMessageSource, ErrorMessageLevel, message.toString());
244         }
245     } else {
246         // To keep the signal-to-noise ratio low, we only log 200-response with an invalid MIME type.
247         if (statusCode == 200 && !mimeTypeIsValid) {
248             StringBuilder message;
249             message.appendLiteral("EventSource's response has a MIME type (\"");
250             message.append(response.mimeType());
251             message.appendLiteral("\") that is not \"text/event-stream\". Aborting the connection.");
252             // FIXME: We are missing the source line.
253             executionContext()->addConsoleMessage(JSMessageSource, ErrorMessageLevel, message.toString());
254         }
255     }
256
257     if (responseIsValid) {
258         m_state = OPEN;
259         dispatchEvent(Event::create(EventTypeNames::open));
260     } else {
261         m_loader->cancel();
262         dispatchEvent(Event::create(EventTypeNames::error));
263     }
264 }
265
266 void EventSource::didReceiveData(const char* data, int length)
267 {
268     ASSERT(m_state == OPEN);
269     ASSERT(m_requestInFlight);
270
271     append(m_receiveBuf, m_decoder->decode(data, length));
272     parseEventStream();
273 }
274
275 void EventSource::didFinishLoading(unsigned long, double)
276 {
277     ASSERT(m_state == OPEN);
278     ASSERT(m_requestInFlight);
279
280     if (m_receiveBuf.size() > 0 || m_data.size() > 0) {
281         parseEventStream();
282
283         // Discard everything that has not been dispatched by now.
284         m_receiveBuf.clear();
285         m_data.clear();
286         m_eventName = emptyAtom;
287         m_currentlyParsedEventId = nullAtom;
288     }
289     networkRequestEnded();
290 }
291
292 void EventSource::didFail(const ResourceError& error)
293 {
294     ASSERT(m_state != CLOSED);
295     ASSERT(m_requestInFlight);
296
297     if (error.isCancellation())
298         m_state = CLOSED;
299     networkRequestEnded();
300 }
301
302 void EventSource::didFailAccessControlCheck(const ResourceError& error)
303 {
304     String message = "EventSource cannot load " + error.failingURL() + ". " + error.localizedDescription();
305     executionContext()->addConsoleMessage(JSMessageSource, ErrorMessageLevel, message);
306
307     abortConnectionAttempt();
308 }
309
310 void EventSource::didFailRedirectCheck()
311 {
312     abortConnectionAttempt();
313 }
314
315 void EventSource::abortConnectionAttempt()
316 {
317     ASSERT(m_state == CONNECTING);
318
319     if (m_requestInFlight) {
320         m_loader->cancel();
321     } else {
322         m_state = CLOSED;
323         unsetPendingActivity(this);
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 PassRefPtrWillBeRawPtr<MessageEvent> EventSource::createMessageEvent()
430 {
431     RefPtrWillBeRawPtr<MessageEvent> event = MessageEvent::create();
432     event->initMessageEvent(m_eventName.isEmpty() ? EventTypeNames::message : m_eventName, false, false, SerializedScriptValue::create(String(m_data)), m_eventStreamOrigin, m_lastEventId, 0, nullptr);
433     m_data.clear();
434     return event.release();
435 }
436
437 } // namespace WebCore