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.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
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
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.
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.
34 #include "core/page/EventSource.h"
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"
58 const unsigned long long EventSource::defaultReconnectDelay = 3000;
60 inline EventSource::EventSource(ExecutionContext* context, const KURL& url, const Dictionary& eventSourceInit)
61 : ActiveDOMObject(context)
63 , m_withCredentials(false)
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)
71 ScriptWrappable::init(this);
72 eventSourceInit.get("withCredentials", m_withCredentials);
75 PassRefPtrWillBeRawPtr<EventSource> EventSource::create(ExecutionContext* context, const String& url, const Dictionary& eventSourceInit, ExceptionState& exceptionState)
78 exceptionState.throwDOMException(SyntaxError, "Cannot open an EventSource to an empty URL.");
82 KURL fullURL = context->completeURL(url);
83 if (!fullURL.isValid()) {
84 exceptionState.throwDOMException(SyntaxError, "Cannot open an EventSource to '" + url + "'. The URL is invalid.");
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();
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.");
100 RefPtrWillBeRawPtr<EventSource> source = adoptRefWillBeRefCountedGarbageCollected(new EventSource(context, fullURL, eventSourceInit));
102 source->setPendingActivity(source.get());
103 source->scheduleInitialConnect();
104 source->suspendIfNeeded();
106 return source.release();
109 EventSource::~EventSource()
111 ASSERT(m_state == CLOSED);
112 ASSERT(!m_requestInFlight);
115 void EventSource::scheduleInitialConnect()
117 ASSERT(m_state == CONNECTING);
118 ASSERT(!m_requestInFlight);
120 m_connectTimer.startOneShot(0, FROM_HERE);
123 void EventSource::connect()
125 ASSERT(m_state == CONNECTING);
126 ASSERT(!m_requestInFlight);
127 ASSERT(executionContext());
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);
137 SecurityOrigin* origin = executionContext.securityOrigin();
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;
149 m_loader = ThreadableLoader::create(executionContext, this, request, options);
152 m_requestInFlight = true;
155 void EventSource::networkRequestEnded()
157 if (!m_requestInFlight)
160 m_requestInFlight = false;
162 if (m_state != CLOSED)
165 unsetPendingActivity(this);
168 void EventSource::scheduleReconnect()
170 m_state = CONNECTING;
171 m_connectTimer.startOneShot(m_reconnectDelay / 1000.0, FROM_HERE);
172 dispatchEvent(Event::create(EventTypeNames::error));
175 void EventSource::connectTimerFired(Timer<EventSource>*)
180 String EventSource::url() const
182 return m_url.string();
185 bool EventSource::withCredentials() const
187 return m_withCredentials;
190 EventSource::State EventSource::readyState() const
195 void EventSource::close()
197 if (m_state == CLOSED) {
198 ASSERT(!m_requestInFlight);
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);
208 if (m_requestInFlight)
214 const AtomicString& EventSource::interfaceName() const
216 return EventTargetNames::EventSource;
219 ExecutionContext* EventSource::executionContext() const
221 return ActiveDOMObject::executionContext();
224 void EventSource::didReceiveResponse(unsigned long, const ResourceResponse& response)
226 ASSERT(m_state == CONNECTING);
227 ASSERT(m_requestInFlight);
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());
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());
257 if (responseIsValid) {
259 dispatchEvent(Event::create(EventTypeNames::open));
262 dispatchEvent(Event::create(EventTypeNames::error));
266 void EventSource::didReceiveData(const char* data, int length)
268 ASSERT(m_state == OPEN);
269 ASSERT(m_requestInFlight);
271 append(m_receiveBuf, m_decoder->decode(data, length));
275 void EventSource::didFinishLoading(unsigned long, double)
277 ASSERT(m_state == OPEN);
278 ASSERT(m_requestInFlight);
280 if (m_receiveBuf.size() > 0 || m_data.size() > 0) {
283 // Discard everything that has not been dispatched by now.
284 m_receiveBuf.clear();
286 m_eventName = emptyAtom;
287 m_currentlyParsedEventId = nullAtom;
289 networkRequestEnded();
292 void EventSource::didFail(const ResourceError& error)
294 ASSERT(m_state != CLOSED);
295 ASSERT(m_requestInFlight);
297 if (error.isCancellation())
299 networkRequestEnded();
302 void EventSource::didFailAccessControlCheck(const ResourceError& error)
304 String message = "EventSource cannot load " + error.failingURL() + ". " + error.localizedDescription();
305 executionContext()->addConsoleMessage(JSMessageSource, ErrorMessageLevel, message);
307 abortConnectionAttempt();
310 void EventSource::didFailRedirectCheck()
312 abortConnectionAttempt();
315 void EventSource::abortConnectionAttempt()
317 ASSERT(m_state == CONNECTING);
319 if (m_requestInFlight) {
323 unsetPendingActivity(this);
326 ASSERT(m_state == CLOSED);
327 dispatchEvent(Event::create(EventTypeNames::error));
330 void EventSource::parseEventStream()
333 unsigned bufSize = m_receiveBuf.size();
334 while (bufPos < bufSize) {
335 if (m_discardTrailingNewline) {
336 if (m_receiveBuf[bufPos] == '\n')
338 m_discardTrailingNewline = false;
342 int fieldLength = -1;
343 for (unsigned i = bufPos; lineLength < 0 && i < bufSize; i++) {
344 switch (m_receiveBuf[i]) {
347 fieldLength = i - bufPos;
350 m_discardTrailingNewline = true;
352 lineLength = i - bufPos;
360 parseEventStreamLine(bufPos, fieldLength, lineLength);
361 bufPos += lineLength + 1;
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)
369 if (bufPos == bufSize)
370 m_receiveBuf.clear();
372 m_receiveBuf.remove(0, bufPos);
375 void EventSource::parseEventStreamLine(unsigned bufPos, int fieldLength, int lineLength)
378 if (!m_data.isEmpty()) {
380 if (!m_currentlyParsedEventId.isNull()) {
381 m_lastEventId = m_currentlyParsedEventId;
382 m_currentlyParsedEventId = nullAtom;
384 dispatchEvent(createMessageEvent());
386 if (!m_eventName.isEmpty())
387 m_eventName = emptyAtom;
388 } else if (fieldLength) {
389 bool noValue = fieldLength < 0;
391 String field(&m_receiveBuf[bufPos], noValue ? lineLength : fieldLength);
395 else if (m_receiveBuf[bufPos + fieldLength + 1] != ' ')
396 step = fieldLength + 1;
398 step = fieldLength + 2;
400 int valueLength = lineLength - step;
402 if (field == "data") {
404 m_data.append(&m_receiveBuf[bufPos], valueLength);
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") {
412 m_reconnectDelay = defaultReconnectDelay;
414 String value(&m_receiveBuf[bufPos], valueLength);
416 unsigned long long retry = value.toUInt64(&ok);
418 m_reconnectDelay = retry;
424 void EventSource::stop()
429 PassRefPtrWillBeRawPtr<MessageEvent> EventSource::createMessageEvent()
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);
434 return event.release();
437 } // namespace WebCore