3ffc12b6d36eada72a9df26d6b34bff3d4d24b06
[WebKit-https.git] / Source / WebCore / 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 "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
58 namespace WebCore {
59
60 const unsigned long long EventSource::defaultReconnectDelay = 3000;
61
62 inline EventSource::EventSource(ScriptExecutionContext& context, const URL& 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
76 PassRefPtr<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     URL 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
110 EventSource::~EventSource()
111 {
112     ASSERT(m_state == CLOSED);
113     ASSERT(!m_requestInFlight);
114 }
115
116 void 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
145 void 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
158 void EventSource::scheduleInitialConnect()
159 {
160     ASSERT(m_state == CONNECTING);
161     ASSERT(!m_requestInFlight);
162
163     m_connectTimer.startOneShot(0);
164 }
165
166 void 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
173 void EventSource::connectTimerFired(Timer<EventSource>*)
174 {
175     connect();
176 }
177
178 String EventSource::url() const
179 {
180     return m_url.string();
181 }
182
183 bool EventSource::withCredentials() const
184 {
185     return m_withCredentials;
186 }
187
188 EventSource::State EventSource::readyState() const
189 {
190     return m_state;
191 }
192
193 void 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
212 void EventSource::didReceiveResponse(unsigned long, const ResourceResponse& response)
213 {
214     ASSERT(m_state == CONNECTING);
215     ASSERT(m_requestInFlight);
216
217     m_eventStreamOrigin = SecurityOrigin::create(response.url())->toString();
218     int statusCode = response.httpStatusCode();
219     bool mimeTypeIsValid = response.mimeType() == "text/event-stream";
220     bool responseIsValid = statusCode == 200 && mimeTypeIsValid;
221     if (responseIsValid) {
222         const String& charset = response.textEncodingName();
223         // If we have a charset, the only allowed value is UTF-8 (case-insensitive).
224         responseIsValid = charset.isEmpty() || equalIgnoringCase(charset, "UTF-8");
225         if (!responseIsValid) {
226             StringBuilder message;
227             message.appendLiteral("EventSource's response has a charset (\"");
228             message.append(charset);
229             message.appendLiteral("\") that is not UTF-8. Aborting the connection.");
230             // FIXME: We are missing the source line.
231             scriptExecutionContext()->addConsoleMessage(JSMessageSource, ErrorMessageLevel, message.toString());
232         }
233     } else {
234         // To keep the signal-to-noise ratio low, we only log 200-response with an invalid MIME type.
235         if (statusCode == 200 && !mimeTypeIsValid) {
236             StringBuilder message;
237             message.appendLiteral("EventSource's response has a MIME type (\"");
238             message.append(response.mimeType());
239             message.appendLiteral("\") that is not \"text/event-stream\". Aborting the connection.");
240             // FIXME: We are missing the source line.
241             scriptExecutionContext()->addConsoleMessage(JSMessageSource, ErrorMessageLevel, message.toString());
242         }
243     }
244
245     if (responseIsValid) {
246         m_state = OPEN;
247         dispatchEvent(Event::create(eventNames().openEvent, false, false));
248     } else {
249         m_loader->cancel();
250         dispatchEvent(Event::create(eventNames().errorEvent, false, false));
251     }
252 }
253
254 void EventSource::didReceiveData(const char* data, int length)
255 {
256     ASSERT(m_state == OPEN);
257     ASSERT(m_requestInFlight);
258
259     append(m_receiveBuf, m_decoder->decode(data, length));
260     parseEventStream();
261 }
262
263 void EventSource::didFinishLoading(unsigned long, double)
264 {
265     ASSERT(m_state == OPEN);
266     ASSERT(m_requestInFlight);
267
268     if (m_receiveBuf.size() > 0 || m_data.size() > 0) {
269         parseEventStream();
270
271         // Discard everything that has not been dispatched by now.
272         m_receiveBuf.clear();
273         m_data.clear();
274         m_eventName = "";
275         m_currentlyParsedEventId = String();
276     }
277     networkRequestEnded();
278 }
279
280 void EventSource::didFail(const ResourceError& error)
281 {
282     ASSERT(m_state != CLOSED);
283     ASSERT(m_requestInFlight);
284
285     if (error.isCancellation())
286         m_state = CLOSED;
287     networkRequestEnded();
288 }
289
290 void EventSource::didFailAccessControlCheck(const ResourceError& error)
291 {
292     String message = makeString("EventSource cannot load ", error.failingURL(), ". ", error.localizedDescription());
293     scriptExecutionContext()->addConsoleMessage(JSMessageSource, ErrorMessageLevel, message);
294
295     abortConnectionAttempt();
296 }
297
298 void EventSource::didFailRedirectCheck()
299 {
300     abortConnectionAttempt();
301 }
302
303 void EventSource::abortConnectionAttempt()
304 {
305     ASSERT(m_state == CONNECTING);
306
307     if (m_requestInFlight)
308         m_loader->cancel();
309     else {
310         m_state = CLOSED;
311         unsetPendingActivity(this);
312     }
313
314     ASSERT(m_state == CLOSED);
315     dispatchEvent(Event::create(eventNames().errorEvent, false, false));
316 }
317
318 void EventSource::parseEventStream()
319 {
320     unsigned int bufPos = 0;
321     unsigned int bufSize = m_receiveBuf.size();
322     while (bufPos < bufSize) {
323         if (m_discardTrailingNewline) {
324             if (m_receiveBuf[bufPos] == '\n')
325                 bufPos++;
326             m_discardTrailingNewline = false;
327         }
328
329         int lineLength = -1;
330         int fieldLength = -1;
331         for (unsigned int i = bufPos; lineLength < 0 && i < bufSize; i++) {
332             switch (m_receiveBuf[i]) {
333             case ':':
334                 if (fieldLength < 0)
335                     fieldLength = i - bufPos;
336                 break;
337             case '\r':
338                 m_discardTrailingNewline = true;
339             case '\n':
340                 lineLength = i - bufPos;
341                 break;
342             }
343         }
344
345         if (lineLength < 0)
346             break;
347
348         parseEventStreamLine(bufPos, fieldLength, lineLength);
349         bufPos += lineLength + 1;
350
351         // EventSource.close() might've been called by one of the message event handlers.
352         // Per spec, no further messages should be fired after that.
353         if (m_state == CLOSED)
354             break;
355     }
356
357     if (bufPos == bufSize)
358         m_receiveBuf.clear();
359     else if (bufPos)
360         m_receiveBuf.remove(0, bufPos);
361 }
362
363 void EventSource::parseEventStreamLine(unsigned bufPos, int fieldLength, int lineLength)
364 {
365     if (!lineLength) {
366         if (!m_data.isEmpty()) {
367             m_data.removeLast();
368             if (!m_currentlyParsedEventId.isNull()) {
369                 m_lastEventId.swap(m_currentlyParsedEventId);
370                 m_currentlyParsedEventId = String();
371             }
372             dispatchEvent(createMessageEvent());
373         }
374         if (!m_eventName.isEmpty())
375             m_eventName = "";
376     } else if (fieldLength) {
377         bool noValue = fieldLength < 0;
378
379         String field(&m_receiveBuf[bufPos], noValue ? lineLength : fieldLength);
380         int step;
381         if (noValue)
382             step = lineLength;
383         else if (m_receiveBuf[bufPos + fieldLength + 1] != ' ')
384             step = fieldLength + 1;
385         else
386             step = fieldLength + 2;
387         bufPos += step;
388         int valueLength = lineLength - step;
389
390         if (field == "data") {
391             if (valueLength)
392                 m_data.append(&m_receiveBuf[bufPos], valueLength);
393             m_data.append('\n');
394         } else if (field == "event")
395             m_eventName = valueLength ? String(&m_receiveBuf[bufPos], valueLength) : "";
396         else if (field == "id")
397             m_currentlyParsedEventId = valueLength ? String(&m_receiveBuf[bufPos], valueLength) : "";
398         else if (field == "retry") {
399             if (!valueLength)
400                 m_reconnectDelay = defaultReconnectDelay;
401             else {
402                 String value(&m_receiveBuf[bufPos], valueLength);
403                 bool ok;
404                 unsigned long long retry = value.toUInt64(&ok);
405                 if (ok)
406                     m_reconnectDelay = retry;
407             }
408         }
409     }
410 }
411
412 void EventSource::stop()
413 {
414     close();
415 }
416
417 PassRefPtr<MessageEvent> EventSource::createMessageEvent()
418 {
419     RefPtr<MessageEvent> event = MessageEvent::create();
420     event->initMessageEvent(m_eventName.isEmpty() ? eventNames().messageEvent : AtomicString(m_eventName), false, false, SerializedScriptValue::create(String::adopt(m_data)), m_eventStreamOrigin, m_lastEventId, 0, 0);
421     return event.release();
422 }
423
424 } // namespace WebCore