Remove the Timer parameters from timer callbacks
[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 "HTTPHeaderNames.h"
45 #include "MemoryCache.h"
46 #include "MessageEvent.h"
47 #include "ResourceError.h"
48 #include "ResourceRequest.h"
49 #include "ResourceResponse.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 nullptr;
81     }
82
83     URL fullURL = context.completeURL(url);
84     if (!fullURL.isValid()) {
85         ec = SYNTAX_ERR;
86         return nullptr;
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 (is<Document>(context)) {
92         Document& document = downcast<Document>(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 nullptr;
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(HTTPHeaderName::Accept, "text/event-stream");
124     request.setHTTPHeaderField(HTTPHeaderName::CacheControl, "no-cache");
125     if (!m_lastEventId.isEmpty())
126         request.setHTTPHeaderField(HTTPHeaderName::LastEventID, m_lastEventId);
127
128     SecurityOrigin* origin = scriptExecutionContext()->securityOrigin();
129
130     ThreadableLoaderOptions options;
131     options.setSendLoadCallbacks(SendCallbacks);
132     options.setSniffContent(DoNotSniffContent);
133     options.setAllowCredentials((origin->canRequest(m_url) || m_withCredentials) ? AllowStoredCredentials : DoNotAllowStoredCredentials);
134     options.preflightPolicy = PreventPreflight;
135     options.crossOriginRequestPolicy = UseAccessControl;
136     options.setDataBufferingPolicy(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()
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(MessageSource::JS, MessageLevel::Error, 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(MessageSource::JS, MessageLevel::Error, 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     // FIXME: Need to call flush at some point.
260     append(m_receiveBuf, StringView(m_decoder->decode(data, length)));
261     parseEventStream();
262 }
263
264 void EventSource::didFinishLoading(unsigned long, double)
265 {
266     ASSERT(m_state == OPEN);
267     ASSERT(m_requestInFlight);
268
269     if (m_receiveBuf.size() > 0 || m_data.size() > 0) {
270         parseEventStream();
271
272         // Discard everything that has not been dispatched by now.
273         m_receiveBuf.clear();
274         m_data.clear();
275         m_eventName = "";
276         m_currentlyParsedEventId = String();
277     }
278     networkRequestEnded();
279 }
280
281 void EventSource::didFail(const ResourceError& error)
282 {
283     ASSERT(m_state != CLOSED);
284     ASSERT(m_requestInFlight);
285
286     if (error.isCancellation())
287         m_state = CLOSED;
288     networkRequestEnded();
289 }
290
291 void EventSource::didFailAccessControlCheck(const ResourceError& error)
292 {
293     String message = makeString("EventSource cannot load ", error.failingURL(), ". ", error.localizedDescription());
294     scriptExecutionContext()->addConsoleMessage(MessageSource::JS, MessageLevel::Error, message);
295
296     abortConnectionAttempt();
297 }
298
299 void EventSource::didFailRedirectCheck()
300 {
301     abortConnectionAttempt();
302 }
303
304 void EventSource::abortConnectionAttempt()
305 {
306     ASSERT(m_state == CONNECTING);
307
308     if (m_requestInFlight)
309         m_loader->cancel();
310     else {
311         m_state = CLOSED;
312         unsetPendingActivity(this);
313     }
314
315     ASSERT(m_state == CLOSED);
316     dispatchEvent(Event::create(eventNames().errorEvent, false, false));
317 }
318
319 void EventSource::parseEventStream()
320 {
321     unsigned int bufPos = 0;
322     unsigned int bufSize = m_receiveBuf.size();
323     while (bufPos < bufSize) {
324         if (m_discardTrailingNewline) {
325             if (m_receiveBuf[bufPos] == '\n')
326                 bufPos++;
327             m_discardTrailingNewline = false;
328         }
329
330         int lineLength = -1;
331         int fieldLength = -1;
332         for (unsigned int i = bufPos; lineLength < 0 && i < bufSize; i++) {
333             switch (m_receiveBuf[i]) {
334             case ':':
335                 if (fieldLength < 0)
336                     fieldLength = i - bufPos;
337                 break;
338             case '\r':
339                 m_discardTrailingNewline = true;
340                 FALLTHROUGH;
341             case '\n':
342                 lineLength = i - bufPos;
343                 break;
344             }
345         }
346
347         if (lineLength < 0)
348             break;
349
350         parseEventStreamLine(bufPos, fieldLength, lineLength);
351         bufPos += lineLength + 1;
352
353         // EventSource.close() might've been called by one of the message event handlers.
354         // Per spec, no further messages should be fired after that.
355         if (m_state == CLOSED)
356             break;
357     }
358
359     if (bufPos == bufSize)
360         m_receiveBuf.clear();
361     else if (bufPos)
362         m_receiveBuf.remove(0, bufPos);
363 }
364
365 void EventSource::parseEventStreamLine(unsigned bufPos, int fieldLength, int lineLength)
366 {
367     if (!lineLength) {
368         if (!m_data.isEmpty()) {
369             m_data.removeLast();
370             if (!m_currentlyParsedEventId.isNull()) {
371                 m_lastEventId.swap(m_currentlyParsedEventId);
372                 m_currentlyParsedEventId = String();
373             }
374             dispatchEvent(createMessageEvent());
375         }
376         if (!m_eventName.isEmpty())
377             m_eventName = "";
378     } else if (fieldLength) {
379         bool noValue = fieldLength < 0;
380
381         String field(&m_receiveBuf[bufPos], noValue ? lineLength : fieldLength);
382         int step;
383         if (noValue)
384             step = lineLength;
385         else if (m_receiveBuf[bufPos + fieldLength + 1] != ' ')
386             step = fieldLength + 1;
387         else
388             step = fieldLength + 2;
389         bufPos += step;
390         int valueLength = lineLength - step;
391
392         if (field == "data") {
393             if (valueLength)
394                 m_data.append(&m_receiveBuf[bufPos], valueLength);
395             m_data.append('\n');
396         } else if (field == "event")
397             m_eventName = valueLength ? String(&m_receiveBuf[bufPos], valueLength) : "";
398         else if (field == "id")
399             m_currentlyParsedEventId = valueLength ? String(&m_receiveBuf[bufPos], valueLength) : "";
400         else if (field == "retry") {
401             if (!valueLength)
402                 m_reconnectDelay = defaultReconnectDelay;
403             else {
404                 String value(&m_receiveBuf[bufPos], valueLength);
405                 bool ok;
406                 unsigned long long retry = value.toUInt64(&ok);
407                 if (ok)
408                     m_reconnectDelay = retry;
409             }
410         }
411     }
412 }
413
414 void EventSource::stop()
415 {
416     close();
417 }
418
419 PassRefPtr<MessageEvent> EventSource::createMessageEvent()
420 {
421     RefPtr<MessageEvent> event = MessageEvent::create();
422     event->initMessageEvent(m_eventName.isEmpty() ? eventNames().messageEvent : AtomicString(m_eventName), false, false, SerializedScriptValue::create(String::adopt(m_data)), m_eventStreamOrigin, m_lastEventId, 0, 0);
423     return event.release();
424 }
425
426 } // namespace WebCore