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 "EventSource.h" 35 36#include "ContentSecurityPolicy.h" 37#include "DOMWindow.h" 38#include "Dictionary.h" 39#include "Document.h" 40#include "Event.h" 41#include "EventException.h" 42#include "ExceptionCode.h" 43#include "Frame.h" 44#include "MemoryCache.h" 45#include "MessageEvent.h" 46#include "ResourceError.h" 47#include "ResourceRequest.h" 48#include "ResourceResponse.h" 49#include "ScriptCallStack.h" 50#include "ScriptController.h" 51#include "ScriptExecutionContext.h" 52#include "SecurityOrigin.h" 53#include "SerializedScriptValue.h" 54#include "TextResourceDecoder.h" 55#include "ThreadableLoader.h" 56#include <wtf/text/StringBuilder.h> 57 58namespace WebCore { 59 60const unsigned long long EventSource::defaultReconnectDelay = 3000; 61 62inline EventSource::EventSource(ScriptExecutionContext* 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 eventSourceInit.get("withCredentials", m_withCredentials); 74} 75 76PassRefPtr<EventSource> EventSource::create(ScriptExecutionContext* context, const String& url, const Dictionary& eventSourceInit, ExceptionCode& ec) 77{ 78 if (url.isEmpty()) { 79 ec = SYNTAX_ERR; 80 return 0; 81 } 82 83 KURL fullURL = context->completeURL(url); 84 if (!fullURL.isValid()) { 85 ec = SYNTAX_ERR; 86 return 0; 87 } 88 89 // FIXME: Convert this to check the isolated world's Content Security Policy once webkit.org/b/104520 is solved. 90 bool shouldBypassMainWorldContentSecurityPolicy = false; 91 if (context->isDocument()) { 92 Document* document = toDocument(context); 93 shouldBypassMainWorldContentSecurityPolicy = document->frame()->script()->shouldBypassMainWorldContentSecurityPolicy(); 94 } 95 if (!shouldBypassMainWorldContentSecurityPolicy && !context->contentSecurityPolicy()->allowConnectToSource(fullURL)) { 96 // FIXME: Should this be throwing an exception? 97 ec = SECURITY_ERR; 98 return 0; 99 } 100 101 RefPtr<EventSource> source = adoptRef(new EventSource(context, fullURL, eventSourceInit)); 102 103 source->setPendingActivity(source.get()); 104 source->scheduleInitialConnect(); 105 source->suspendIfNeeded(); 106 107 return source.release(); 108} 109 110EventSource::~EventSource() 111{ 112 ASSERT(m_state == CLOSED); 113 ASSERT(!m_requestInFlight); 114} 115 116void EventSource::connect() 117{ 118 ASSERT(m_state == CONNECTING); 119 ASSERT(!m_requestInFlight); 120 121 ResourceRequest request(m_url); 122 request.setHTTPMethod("GET"); 123 request.setHTTPHeaderField("Accept", "text/event-stream"); 124 request.setHTTPHeaderField("Cache-Control", "no-cache"); 125 if (!m_lastEventId.isEmpty()) 126 request.setHTTPHeaderField("Last-Event-ID", m_lastEventId); 127 128 SecurityOrigin* origin = scriptExecutionContext()->securityOrigin(); 129 130 ThreadableLoaderOptions options; 131 options.sendLoadCallbacks = SendCallbacks; 132 options.sniffContent = DoNotSniffContent; 133 options.allowCredentials = (origin->canRequest(m_url) || m_withCredentials) ? AllowStoredCredentials : DoNotAllowStoredCredentials; 134 options.preflightPolicy = PreventPreflight; 135 options.crossOriginRequestPolicy = UseAccessControl; 136 options.dataBufferingPolicy = DoNotBufferData; 137 options.securityOrigin = origin; 138 139 m_loader = ThreadableLoader::create(scriptExecutionContext(), this, request, options); 140 141 if (m_loader) 142 m_requestInFlight = true; 143} 144 145void EventSource::networkRequestEnded() 146{ 147 if (!m_requestInFlight) 148 return; 149 150 m_requestInFlight = false; 151 152 if (m_state != CLOSED) 153 scheduleReconnect(); 154 else 155 unsetPendingActivity(this); 156} 157 158void EventSource::scheduleInitialConnect() 159{ 160 ASSERT(m_state == CONNECTING); 161 ASSERT(!m_requestInFlight); 162 163 m_connectTimer.startOneShot(0); 164} 165 166void EventSource::scheduleReconnect() 167{ 168 m_state = CONNECTING; 169 m_connectTimer.startOneShot(m_reconnectDelay / 1000.0); 170 dispatchEvent(Event::create(eventNames().errorEvent, false, false)); 171} 172 173void EventSource::connectTimerFired(Timer<EventSource>*) 174{ 175 connect(); 176} 177 178String EventSource::url() const 179{ 180 return m_url.string(); 181} 182 183bool EventSource::withCredentials() const 184{ 185 return m_withCredentials; 186} 187 188EventSource::State EventSource::readyState() const 189{ 190 return m_state; 191} 192 193void EventSource::close() 194{ 195 if (m_state == CLOSED) { 196 ASSERT(!m_requestInFlight); 197 return; 198 } 199 200 // Stop trying to connect/reconnect if EventSource was explicitly closed or if ActiveDOMObject::stop() was called. 201 if (m_connectTimer.isActive()) 202 m_connectTimer.stop(); 203 204 if (m_requestInFlight) 205 m_loader->cancel(); 206 else { 207 m_state = CLOSED; 208 unsetPendingActivity(this); 209 } 210} 211 212const AtomicString& EventSource::interfaceName() const 213{ 214 return eventNames().interfaceForEventSource; 215} 216 217ScriptExecutionContext* EventSource::scriptExecutionContext() const 218{ 219 return ActiveDOMObject::scriptExecutionContext(); 220} 221 222void EventSource::didReceiveResponse(unsigned long, const ResourceResponse& response) 223{ 224 ASSERT(m_state == CONNECTING); 225 ASSERT(m_requestInFlight); 226 227 m_eventStreamOrigin = SecurityOrigin::create(response.url())->toString(); 228 int statusCode = response.httpStatusCode(); 229 bool mimeTypeIsValid = response.mimeType() == "text/event-stream"; 230 bool responseIsValid = statusCode == 200 && mimeTypeIsValid; 231 if (responseIsValid) { 232 const String& charset = response.textEncodingName(); 233 // If we have a charset, the only allowed value is UTF-8 (case-insensitive). 234 responseIsValid = charset.isEmpty() || equalIgnoringCase(charset, "UTF-8"); 235 if (!responseIsValid) { 236 StringBuilder message; 237 message.appendLiteral("EventSource's response has a charset (\""); 238 message.append(charset); 239 message.appendLiteral("\") that is not UTF-8. Aborting the connection."); 240 // FIXME: We are missing the source line. 241 scriptExecutionContext()->addConsoleMessage(JSMessageSource, ErrorMessageLevel, message.toString()); 242 } 243 } else { 244 // To keep the signal-to-noise ratio low, we only log 200-response with an invalid MIME type. 245 if (statusCode == 200 && !mimeTypeIsValid) { 246 StringBuilder message; 247 message.appendLiteral("EventSource's response has a MIME type (\""); 248 message.append(response.mimeType()); 249 message.appendLiteral("\") that is not \"text/event-stream\". Aborting the connection."); 250 // FIXME: We are missing the source line. 251 scriptExecutionContext()->addConsoleMessage(JSMessageSource, ErrorMessageLevel, message.toString()); 252 } 253 } 254 255 if (responseIsValid) { 256 m_state = OPEN; 257 dispatchEvent(Event::create(eventNames().openEvent, false, false)); 258 } else { 259 m_loader->cancel(); 260 dispatchEvent(Event::create(eventNames().errorEvent, false, false)); 261 } 262} 263 264void EventSource::didReceiveData(const char* data, int length) 265{ 266 ASSERT(m_state == OPEN); 267 ASSERT(m_requestInFlight); 268 269 append(m_receiveBuf, m_decoder->decode(data, length)); 270 parseEventStream(); 271} 272 273void EventSource::didFinishLoading(unsigned long, double) 274{ 275 ASSERT(m_state == OPEN); 276 ASSERT(m_requestInFlight); 277 278 if (m_receiveBuf.size() > 0 || m_data.size() > 0) { 279 parseEventStream(); 280 281 // Discard everything that has not been dispatched by now. 282 m_receiveBuf.clear(); 283 m_data.clear(); 284 m_eventName = ""; 285 m_currentlyParsedEventId = String(); 286 } 287 networkRequestEnded(); 288} 289 290void EventSource::didFail(const ResourceError& error) 291{ 292 ASSERT(m_state != CLOSED); 293 ASSERT(m_requestInFlight); 294 295 if (error.isCancellation()) 296 m_state = CLOSED; 297 networkRequestEnded(); 298} 299 300void EventSource::didFailAccessControlCheck(const ResourceError& error) 301{ 302 String message = makeString("EventSource cannot load ", error.failingURL(), ". ", error.localizedDescription()); 303 scriptExecutionContext()->addConsoleMessage(JSMessageSource, ErrorMessageLevel, message); 304 305 abortConnectionAttempt(); 306} 307 308void EventSource::didFailRedirectCheck() 309{ 310 abortConnectionAttempt(); 311} 312 313void EventSource::abortConnectionAttempt() 314{ 315 ASSERT(m_state == CONNECTING); 316 317 if (m_requestInFlight) 318 m_loader->cancel(); 319 else { 320 m_state = CLOSED; 321 unsetPendingActivity(this); 322 } 323 324 ASSERT(m_state == CLOSED); 325 dispatchEvent(Event::create(eventNames().errorEvent, false, false)); 326} 327 328void EventSource::parseEventStream() 329{ 330 unsigned int bufPos = 0; 331 unsigned int bufSize = m_receiveBuf.size(); 332 while (bufPos < bufSize) { 333 if (m_discardTrailingNewline) { 334 if (m_receiveBuf[bufPos] == '\n') 335 bufPos++; 336 m_discardTrailingNewline = false; 337 } 338 339 int lineLength = -1; 340 int fieldLength = -1; 341 for (unsigned int i = bufPos; lineLength < 0 && i < bufSize; i++) { 342 switch (m_receiveBuf[i]) { 343 case ':': 344 if (fieldLength < 0) 345 fieldLength = i - bufPos; 346 break; 347 case '\r': 348 m_discardTrailingNewline = true; 349 case '\n': 350 lineLength = i - bufPos; 351 break; 352 } 353 } 354 355 if (lineLength < 0) 356 break; 357 358 parseEventStreamLine(bufPos, fieldLength, lineLength); 359 bufPos += lineLength + 1; 360 361 // EventSource.close() might've been called by one of the message event handlers. 362 // Per spec, no further messages should be fired after that. 363 if (m_state == CLOSED) 364 break; 365 } 366 367 if (bufPos == bufSize) 368 m_receiveBuf.clear(); 369 else if (bufPos) 370 m_receiveBuf.remove(0, bufPos); 371} 372 373void EventSource::parseEventStreamLine(unsigned bufPos, int fieldLength, int lineLength) 374{ 375 if (!lineLength) { 376 if (!m_data.isEmpty()) { 377 m_data.removeLast(); 378 if (!m_currentlyParsedEventId.isNull()) { 379 m_lastEventId.swap(m_currentlyParsedEventId); 380 m_currentlyParsedEventId = String(); 381 } 382 dispatchEvent(createMessageEvent()); 383 } 384 if (!m_eventName.isEmpty()) 385 m_eventName = ""; 386 } else if (fieldLength) { 387 bool noValue = fieldLength < 0; 388 389 String field(&m_receiveBuf[bufPos], noValue ? lineLength : fieldLength); 390 int step; 391 if (noValue) 392 step = lineLength; 393 else if (m_receiveBuf[bufPos + fieldLength + 1] != ' ') 394 step = fieldLength + 1; 395 else 396 step = fieldLength + 2; 397 bufPos += step; 398 int valueLength = lineLength - step; 399 400 if (field == "data") { 401 if (valueLength) 402 m_data.append(&m_receiveBuf[bufPos], valueLength); 403 m_data.append('\n'); 404 } else if (field == "event") 405 m_eventName = valueLength ? String(&m_receiveBuf[bufPos], valueLength) : ""; 406 else if (field == "id") 407 m_currentlyParsedEventId = valueLength ? String(&m_receiveBuf[bufPos], valueLength) : ""; 408 else if (field == "retry") { 409 if (!valueLength) 410 m_reconnectDelay = defaultReconnectDelay; 411 else { 412 String value(&m_receiveBuf[bufPos], valueLength); 413 bool ok; 414 unsigned long long retry = value.toUInt64(&ok); 415 if (ok) 416 m_reconnectDelay = retry; 417 } 418 } 419 } 420} 421 422void EventSource::stop() 423{ 424 close(); 425} 426 427PassRefPtr<MessageEvent> EventSource::createMessageEvent() 428{ 429 RefPtr<MessageEvent> event = MessageEvent::create(); 430 event->initMessageEvent(m_eventName.isEmpty() ? eventNames().messageEvent : AtomicString(m_eventName), false, false, SerializedScriptValue::create(String::adopt(m_data)), m_eventStreamOrigin, m_lastEventId, 0, 0); 431 return event.release(); 432} 433 434EventTargetData* EventSource::eventTargetData() 435{ 436 return &m_eventTargetData; 437} 438 439EventTargetData* EventSource::ensureEventTargetData() 440{ 441 return &m_eventTargetData; 442} 443 444} // namespace WebCore 445