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 "ResourceError.h"
45
#include "ResourceRequest.h"
46
#include "ResourceResponse.h"
47
#include "ScriptCallStack.h"
48
#include "ScriptExecutionContext.h"
49
#include "SecurityOrigin.h"
50
#include "SerializedScriptValue.h"
51
#include "TextResourceDecoder.h"
52
#include "ThreadableLoader.h"
53
#include <wtf/text/StringBuilder.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
StringBuilder message;
214
message.appendLiteral("EventSource's response has a charset (\"");
215
message.append(charset);
216
message.appendLiteral("\") that is not UTF-8. Aborting the connection.");
217
// FIXME: We are missing the source line.
218
scriptExecutionContext()->addConsoleMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, message.toString());
221
// To keep the signal-to-noise ratio low, we only log 200-response with an invalid MIME type.
222
if (statusCode == 200 && !mimeTypeIsValid) {
223
StringBuilder message;
224
message.appendLiteral("EventSource's response has a MIME type (\"");
225
message.append(response.mimeType());
226
message.appendLiteral("\") that is not \"text/event-stream\". Aborting the connection.");
227
// FIXME: We are missing the source line.
228
scriptExecutionContext()->addConsoleMessage(JSMessageSource, LogMessageType, ErrorMessageLevel, message.toString());
232
if (responseIsValid) {
234
dispatchEvent(Event::create(eventNames().openEvent, false, false));
237
dispatchEvent(Event::create(eventNames().errorEvent, false, false));
241
void EventSource::didReceiveData(const char* data, int length)
243
ASSERT(m_state == OPEN);
244
ASSERT(m_requestInFlight);
246
append(m_receiveBuf, m_decoder->decode(data, length));
250
void EventSource::didFinishLoading(unsigned long, double)
252
ASSERT(m_state == OPEN);
253
ASSERT(m_requestInFlight);
255
if (m_receiveBuf.size() > 0 || m_data.size() > 0) {
258
// Discard everything that has not been dispatched by now.
259
m_receiveBuf.clear();
262
m_currentlyParsedEventId = String();
264
networkRequestEnded();
267
void EventSource::didFail(const ResourceError& error)
269
ASSERT(m_state != CLOSED);
270
ASSERT(m_requestInFlight);
272
if (error.isCancellation())
274
networkRequestEnded();
277
void EventSource::didFailRedirectCheck()
279
ASSERT(m_state == CONNECTING);
280
ASSERT(m_requestInFlight);
284
ASSERT(m_state == CLOSED);
285
dispatchEvent(Event::create(eventNames().errorEvent, false, false));
288
void EventSource::parseEventStream()
290
unsigned int bufPos = 0;
291
unsigned int bufSize = m_receiveBuf.size();
292
while (bufPos < bufSize) {
293
if (m_discardTrailingNewline) {
294
if (m_receiveBuf[bufPos] == '\n')
296
m_discardTrailingNewline = false;
300
int fieldLength = -1;
301
for (unsigned int i = bufPos; lineLength < 0 && i < bufSize; i++) {
302
switch (m_receiveBuf[i]) {
305
fieldLength = i - bufPos;
308
m_discardTrailingNewline = true;
310
lineLength = i - bufPos;
318
parseEventStreamLine(bufPos, fieldLength, lineLength);
319
bufPos += lineLength + 1;
321
// EventSource.close() might've been called by one of the message event handlers.
322
// Per spec, no further messages should be fired after that.
323
if (m_state == CLOSED)
327
if (bufPos == bufSize)
328
m_receiveBuf.clear();
330
m_receiveBuf.remove(0, bufPos);
333
void EventSource::parseEventStreamLine(unsigned int bufPos, int fieldLength, int lineLength)
336
if (!m_data.isEmpty()) {
338
if (!m_currentlyParsedEventId.isNull()) {
339
m_lastEventId.swap(m_currentlyParsedEventId);
340
m_currentlyParsedEventId = String();
342
dispatchEvent(createMessageEvent());
344
if (!m_eventName.isEmpty())
346
} else if (fieldLength) {
347
bool noValue = fieldLength < 0;
349
String field(&m_receiveBuf[bufPos], noValue ? lineLength : fieldLength);
353
else if (m_receiveBuf[bufPos + fieldLength + 1] != ' ')
354
step = fieldLength + 1;
356
step = fieldLength + 2;
358
int valueLength = lineLength - step;
360
if (field == "data") {
362
m_data.append(&m_receiveBuf[bufPos], valueLength);
364
} else if (field == "event")
365
m_eventName = valueLength ? String(&m_receiveBuf[bufPos], valueLength) : "";
366
else if (field == "id")
367
m_currentlyParsedEventId = valueLength ? String(&m_receiveBuf[bufPos], valueLength) : "";
368
else if (field == "retry") {
370
m_reconnectDelay = defaultReconnectDelay;
372
String value(&m_receiveBuf[bufPos], valueLength);
374
unsigned long long retry = value.toUInt64(&ok);
376
m_reconnectDelay = retry;
382
void EventSource::stop()
387
PassRefPtr<MessageEvent> EventSource::createMessageEvent()
389
RefPtr<MessageEvent> event = MessageEvent::create();
390
event->initMessageEvent(m_eventName.isEmpty() ? eventNames().messageEvent : AtomicString(m_eventName), false, false, SerializedScriptValue::create(String::adopt(m_data)), m_origin, m_lastEventId, 0, 0);
391
return event.release();
394
EventTargetData* EventSource::eventTargetData()
396
return &m_eventTargetData;
399
EventTargetData* EventSource::ensureEventTargetData()
401
return &m_eventTargetData;
404
} // namespace WebCore