2 * Copyright (C) 2009 Ericsson AB
4 * Copyright (C) 2010 Apple Inc. All rights reserved.
5 * Copyright (C) 2011, Code Aurora Forum. All rights reserved.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer
15 * in the documentation and/or other materials provided with the
17 * 3. Neither the name of Ericsson nor the names of its contributors
18 * may be used to endorse or promote products derived from this
19 * software without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35 #include "EventSource.h"
37 #include "ContentSecurityPolicy.h"
38 #include "DOMWindow.h"
40 #include "EventException.h"
41 #include "ExceptionCode.h"
42 #include "MemoryCache.h"
43 #include "MessageEvent.h"
44 #include "PlatformString.h"
45 #include "ResourceError.h"
46 #include "ResourceRequest.h"
47 #include "ResourceResponse.h"
48 #include "ScriptCallStack.h"
49 #include "ScriptExecutionContext.h"
50 #include "SecurityOrigin.h"
51 #include "SerializedScriptValue.h"
52 #include "TextResourceDecoder.h"
53 #include "ThreadableLoader.h"
57 const unsigned long long EventSource::defaultReconnectDelay = 3000;
59 inline EventSource::EventSource(const KURL& url, ScriptExecutionContext* context)
60 : ActiveDOMObject(context, this)
63 , m_decoder(TextResourceDecoder::create("text/plain", "UTF-8"))
64 , m_reconnectTimer(this, &EventSource::reconnectTimerFired)
65 , m_discardTrailingNewline(false)
66 , m_requestInFlight(false)
67 , m_reconnectDelay(defaultReconnectDelay)
68 , m_origin(context->securityOrigin()->toString())
72 PassRefPtr<EventSource> EventSource::create(ScriptExecutionContext* context, const String& url, ExceptionCode& ec)
79 KURL fullURL = context->completeURL(url);
80 if (!fullURL.isValid()) {
85 // FIXME: Should support at least some cross-origin requests.
86 if (!context->securityOrigin()->canRequest(fullURL)) {
91 if (!context->contentSecurityPolicy()->allowConnectToSource(fullURL)) {
92 // FIXME: Should this be throwing an exception?
97 RefPtr<EventSource> source = adoptRef(new EventSource(fullURL, context));
99 source->setPendingActivity(source.get());
101 source->suspendIfNeeded();
103 return source.release();
106 EventSource::~EventSource()
108 ASSERT(m_state == CLOSED);
109 ASSERT(!m_requestInFlight);
112 void EventSource::connect()
114 ASSERT(m_state == CONNECTING);
115 ASSERT(!m_requestInFlight);
117 ResourceRequest request(m_url);
118 request.setHTTPMethod("GET");
119 request.setHTTPHeaderField("Accept", "text/event-stream");
120 request.setHTTPHeaderField("Cache-Control", "no-cache");
121 if (!m_lastEventId.isEmpty())
122 request.setHTTPHeaderField("Last-Event-ID", m_lastEventId);
124 ThreadableLoaderOptions options;
125 options.sendLoadCallbacks = SendCallbacks;
126 options.sniffContent = DoNotSniffContent;
127 options.allowCredentials = AllowStoredCredentials;
128 options.shouldBufferData = DoNotBufferData;
130 m_loader = ThreadableLoader::create(scriptExecutionContext(), this, request, options);
133 m_requestInFlight = true;
136 void EventSource::networkRequestEnded()
138 if (!m_requestInFlight)
141 m_requestInFlight = false;
143 if (m_state != CLOSED)
146 unsetPendingActivity(this);
149 void EventSource::scheduleReconnect()
151 m_state = CONNECTING;
152 m_reconnectTimer.startOneShot(m_reconnectDelay / 1000);
153 dispatchEvent(Event::create(eventNames().errorEvent, false, false));
156 void EventSource::reconnectTimerFired(Timer<EventSource>*)
161 String EventSource::url() const
163 return m_url.string();
166 EventSource::State EventSource::readyState() const
171 void EventSource::close()
173 if (m_state == CLOSED) {
174 ASSERT(!m_requestInFlight);
178 // Stop trying to reconnect if EventSource was explicitly closed or if ActiveDOMObject::stop() was called.
179 if (m_reconnectTimer.isActive()) {
180 m_reconnectTimer.stop();
181 unsetPendingActivity(this);
184 if (m_requestInFlight)
190 const AtomicString& EventSource::interfaceName() const
192 return eventNames().interfaceForEventSource;
195 ScriptExecutionContext* EventSource::scriptExecutionContext() const
197 return ActiveDOMObject::scriptExecutionContext();
200 void EventSource::didReceiveResponse(unsigned long, const ResourceResponse& response)
202 ASSERT(m_state == CONNECTING);
203 ASSERT(m_requestInFlight);
205 int statusCode = response.httpStatusCode();
206 bool mimeTypeIsValid = response.mimeType() == "text/event-stream";
207 bool responseIsValid = statusCode == 200 && mimeTypeIsValid;
208 if (responseIsValid) {
209 const String& charset = response.textEncodingName();
210 // If we have a charset, the only allowed value is UTF-8 (case-insensitive).
211 responseIsValid = charset.isEmpty() || equalIgnoringCase(charset, "UTF-8");
212 if (!responseIsValid) {
213 String message = "EventSource's response has a charset (\"";
215 message += "\") that is not UTF-8. Aborting the connection.";
216 // FIXME: We are missing the source line.
217 scriptExecutionContext()->addConsoleMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, message);
220 // To keep the signal-to-noise ratio low, we only log 200-response with an invalid MIME type.
221 if (statusCode == 200 && !mimeTypeIsValid) {
222 String message = "EventSource's response has a MIME type (\"";
223 message += response.mimeType();
224 message += "\") that is not \"text/event-stream\". Aborting the connection.";
225 // FIXME: We are missing the source line.
226 scriptExecutionContext()->addConsoleMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, message);
230 if (responseIsValid) {
232 dispatchEvent(Event::create(eventNames().openEvent, false, false));
235 dispatchEvent(Event::create(eventNames().errorEvent, false, false));
239 void EventSource::didReceiveData(const char* data, int length)
241 ASSERT(m_state == OPEN);
242 ASSERT(m_requestInFlight);
244 append(m_receiveBuf, m_decoder->decode(data, length));
248 void EventSource::didFinishLoading(unsigned long, double)
250 ASSERT(m_state == OPEN);
251 ASSERT(m_requestInFlight);
253 if (m_receiveBuf.size() > 0 || m_data.size() > 0) {
256 // Discard everything that has not been dispatched by now.
257 m_receiveBuf.clear();
260 m_currentlyParsedEventId = String();
262 networkRequestEnded();
265 void EventSource::didFail(const ResourceError& error)
267 ASSERT(m_state != CLOSED);
268 ASSERT(m_requestInFlight);
270 if (error.isCancellation())
272 networkRequestEnded();
275 void EventSource::didFailRedirectCheck()
277 ASSERT(m_state == CONNECTING);
278 ASSERT(m_requestInFlight);
282 ASSERT(m_state == CLOSED);
283 dispatchEvent(Event::create(eventNames().errorEvent, false, false));
286 void EventSource::parseEventStream()
288 unsigned int bufPos = 0;
289 unsigned int bufSize = m_receiveBuf.size();
290 while (bufPos < bufSize) {
291 if (m_discardTrailingNewline) {
292 if (m_receiveBuf[bufPos] == '\n')
294 m_discardTrailingNewline = false;
298 int fieldLength = -1;
299 for (unsigned int i = bufPos; lineLength < 0 && i < bufSize; i++) {
300 switch (m_receiveBuf[i]) {
303 fieldLength = i - bufPos;
306 m_discardTrailingNewline = true;
308 lineLength = i - bufPos;
316 parseEventStreamLine(bufPos, fieldLength, lineLength);
317 bufPos += lineLength + 1;
319 // EventSource.close() might've been called by one of the message event handlers.
320 // Per spec, no further messages should be fired after that.
321 if (m_state == CLOSED)
325 if (bufPos == bufSize)
326 m_receiveBuf.clear();
328 m_receiveBuf.remove(0, bufPos);
331 void EventSource::parseEventStreamLine(unsigned int bufPos, int fieldLength, int lineLength)
334 if (!m_data.isEmpty()) {
336 if (!m_currentlyParsedEventId.isNull()) {
337 m_lastEventId.swap(m_currentlyParsedEventId);
338 m_currentlyParsedEventId = String();
340 dispatchEvent(createMessageEvent());
342 if (!m_eventName.isEmpty())
344 } else if (fieldLength) {
345 bool noValue = fieldLength < 0;
347 String field(&m_receiveBuf[bufPos], noValue ? lineLength : fieldLength);
351 else if (m_receiveBuf[bufPos + fieldLength + 1] != ' ')
352 step = fieldLength + 1;
354 step = fieldLength + 2;
356 int valueLength = lineLength - step;
358 if (field == "data") {
360 m_data.append(&m_receiveBuf[bufPos], valueLength);
362 } else if (field == "event")
363 m_eventName = valueLength ? String(&m_receiveBuf[bufPos], valueLength) : "";
364 else if (field == "id")
365 m_currentlyParsedEventId = valueLength ? String(&m_receiveBuf[bufPos], valueLength) : "";
366 else if (field == "retry") {
368 m_reconnectDelay = defaultReconnectDelay;
370 String value(&m_receiveBuf[bufPos], valueLength);
372 unsigned long long retry = value.toUInt64(&ok);
374 m_reconnectDelay = retry;
380 void EventSource::stop()
385 PassRefPtr<MessageEvent> EventSource::createMessageEvent()
387 RefPtr<MessageEvent> event = MessageEvent::create();
388 event->initMessageEvent(m_eventName.isEmpty() ? eventNames().messageEvent : AtomicString(m_eventName), false, false, SerializedScriptValue::create(String::adopt(m_data)), m_origin, m_lastEventId, 0, 0);
389 return event.release();
392 EventTargetData* EventSource::eventTargetData()
394 return &m_eventTargetData;
397 EventTargetData* EventSource::ensureEventTargetData()
399 return &m_eventTargetData;
402 } // namespace WebCore