Merge "[CherryPick] Refactoring: Move the content of HTMLInputElement::subtreeHasChan...
[framework/web/webkit-efl.git] / Source / WebCore / page / EventSource.cpp
1 /*
2  * Copyright (C) 2009 Ericsson AB
3  * All rights reserved.
4  * Copyright (C) 2010 Apple Inc. All rights reserved.
5  * Copyright (C) 2011, Code Aurora Forum. All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
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
16  *    distribution.
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.
20  *
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.
32  */
33
34 #include "config.h"
35 #include "EventSource.h"
36
37 #include "ContentSecurityPolicy.h"
38 #include "DOMWindow.h"
39 #include "Event.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"
54
55 namespace WebCore {
56
57 const unsigned long long EventSource::defaultReconnectDelay = 3000;
58
59 inline EventSource::EventSource(const KURL& url, ScriptExecutionContext* context)
60     : ActiveDOMObject(context, this)
61     , m_url(url)
62     , m_state(CONNECTING)
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())
69 {
70 }
71
72 PassRefPtr<EventSource> EventSource::create(ScriptExecutionContext* context, const String& url, ExceptionCode& ec)
73 {
74     if (url.isEmpty()) {
75         ec = SYNTAX_ERR;
76         return 0;
77     }
78
79     KURL fullURL = context->completeURL(url);
80     if (!fullURL.isValid()) {
81         ec = SYNTAX_ERR;
82         return 0;
83     }
84
85     // FIXME: Should support at least some cross-origin requests.
86     if (!context->securityOrigin()->canRequest(fullURL)) {
87         ec = SECURITY_ERR;
88         return 0;
89     }
90
91     if (!context->contentSecurityPolicy()->allowConnectToSource(fullURL)) {
92         // FIXME: Should this be throwing an exception?
93         ec = SECURITY_ERR;
94         return 0;
95     }
96
97     RefPtr<EventSource> source = adoptRef(new EventSource(fullURL, context));
98
99     source->setPendingActivity(source.get());
100     source->connect();
101     source->suspendIfNeeded();
102
103     return source.release();
104 }
105
106 EventSource::~EventSource()
107 {
108     ASSERT(m_state == CLOSED);
109     ASSERT(!m_requestInFlight);
110 }
111
112 void EventSource::connect()
113 {
114     ASSERT(m_state == CONNECTING);
115     ASSERT(!m_requestInFlight);
116
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);
123
124     ThreadableLoaderOptions options;
125     options.sendLoadCallbacks = SendCallbacks;
126     options.sniffContent = DoNotSniffContent;
127     options.allowCredentials = AllowStoredCredentials;
128     options.shouldBufferData = DoNotBufferData;
129
130     m_loader = ThreadableLoader::create(scriptExecutionContext(), this, request, options);
131
132     if (m_loader)
133         m_requestInFlight = true;
134 }
135
136 void EventSource::networkRequestEnded()
137 {
138     if (!m_requestInFlight)
139         return;
140
141     m_requestInFlight = false;
142
143     if (m_state != CLOSED)
144         scheduleReconnect();
145     else
146         unsetPendingActivity(this);
147 }
148
149 void EventSource::scheduleReconnect()
150 {
151     m_state = CONNECTING;
152     m_reconnectTimer.startOneShot(m_reconnectDelay / 1000);
153     dispatchEvent(Event::create(eventNames().errorEvent, false, false));
154 }
155
156 void EventSource::reconnectTimerFired(Timer<EventSource>*)
157 {
158     connect();
159 }
160
161 String EventSource::url() const
162 {
163     return m_url.string();
164 }
165
166 EventSource::State EventSource::readyState() const
167 {
168     return m_state;
169 }
170
171 void EventSource::close()
172 {
173     if (m_state == CLOSED) {
174         ASSERT(!m_requestInFlight);
175         return;
176     }
177
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);
182     }
183
184     if (m_requestInFlight)
185         m_loader->cancel();
186
187     m_state = CLOSED;
188 }
189
190 const AtomicString& EventSource::interfaceName() const
191 {
192     return eventNames().interfaceForEventSource;
193 }
194
195 ScriptExecutionContext* EventSource::scriptExecutionContext() const
196 {
197     return ActiveDOMObject::scriptExecutionContext();
198 }
199
200 void EventSource::didReceiveResponse(unsigned long, const ResourceResponse& response)
201 {
202     ASSERT(m_state == CONNECTING);
203     ASSERT(m_requestInFlight);
204
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 (\"";
214             message += 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);
218         }
219     } else {
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);
227         }
228     }
229
230     if (responseIsValid) {
231         m_state = OPEN;
232         dispatchEvent(Event::create(eventNames().openEvent, false, false));
233     } else {
234         m_loader->cancel();
235         dispatchEvent(Event::create(eventNames().errorEvent, false, false));
236     }
237 }
238
239 void EventSource::didReceiveData(const char* data, int length)
240 {
241     ASSERT(m_state == OPEN);
242     ASSERT(m_requestInFlight);
243
244     append(m_receiveBuf, m_decoder->decode(data, length));
245     parseEventStream();
246 }
247
248 void EventSource::didFinishLoading(unsigned long, double)
249 {
250     ASSERT(m_state == OPEN);
251     ASSERT(m_requestInFlight);
252
253     if (m_receiveBuf.size() > 0 || m_data.size() > 0) {
254         parseEventStream();
255
256         // Discard everything that has not been dispatched by now.
257         m_receiveBuf.clear();
258         m_data.clear();
259         m_eventName = "";
260         m_currentlyParsedEventId = String();
261     }
262     networkRequestEnded();
263 }
264
265 void EventSource::didFail(const ResourceError& error)
266 {
267     ASSERT(m_state != CLOSED);
268     ASSERT(m_requestInFlight);
269
270     if (error.isCancellation())
271         m_state = CLOSED;
272     networkRequestEnded();
273 }
274
275 void EventSource::didFailRedirectCheck()
276 {
277     ASSERT(m_state == CONNECTING);
278     ASSERT(m_requestInFlight);
279
280     m_loader->cancel();
281
282     ASSERT(m_state == CLOSED);
283     dispatchEvent(Event::create(eventNames().errorEvent, false, false));
284 }
285
286 void EventSource::parseEventStream()
287 {
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')
293                 bufPos++;
294             m_discardTrailingNewline = false;
295         }
296
297         int lineLength = -1;
298         int fieldLength = -1;
299         for (unsigned int i = bufPos; lineLength < 0 && i < bufSize; i++) {
300             switch (m_receiveBuf[i]) {
301             case ':':
302                 if (fieldLength < 0)
303                     fieldLength = i - bufPos;
304                 break;
305             case '\r':
306                 m_discardTrailingNewline = true;
307             case '\n':
308                 lineLength = i - bufPos;
309                 break;
310             }
311         }
312
313         if (lineLength < 0)
314             break;
315
316         parseEventStreamLine(bufPos, fieldLength, lineLength);
317         bufPos += lineLength + 1;
318
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)
322             break;
323     }
324
325     if (bufPos == bufSize)
326         m_receiveBuf.clear();
327     else if (bufPos)
328         m_receiveBuf.remove(0, bufPos);
329 }
330
331 void EventSource::parseEventStreamLine(unsigned int bufPos, int fieldLength, int lineLength)
332 {
333     if (!lineLength) {
334         if (!m_data.isEmpty()) {
335             m_data.removeLast();
336             if (!m_currentlyParsedEventId.isNull()) {
337                 m_lastEventId.swap(m_currentlyParsedEventId);
338                 m_currentlyParsedEventId = String();
339             }
340             dispatchEvent(createMessageEvent());
341         }
342         if (!m_eventName.isEmpty())
343             m_eventName = "";
344     } else if (fieldLength) {
345         bool noValue = fieldLength < 0;
346
347         String field(&m_receiveBuf[bufPos], noValue ? lineLength : fieldLength);
348         int step;
349         if (noValue)
350             step = lineLength;
351         else if (m_receiveBuf[bufPos + fieldLength + 1] != ' ')
352             step = fieldLength + 1;
353         else
354             step = fieldLength + 2;
355         bufPos += step;
356         int valueLength = lineLength - step;
357
358         if (field == "data") {
359             if (valueLength)
360                 m_data.append(&m_receiveBuf[bufPos], valueLength);
361             m_data.append('\n');
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") {
367             if (!valueLength)
368                 m_reconnectDelay = defaultReconnectDelay;
369             else {
370                 String value(&m_receiveBuf[bufPos], valueLength);
371                 bool ok;
372                 unsigned long long retry = value.toUInt64(&ok);
373                 if (ok)
374                     m_reconnectDelay = retry;
375             }
376         }
377     }
378 }
379
380 void EventSource::stop()
381 {
382     close();
383 }
384
385 PassRefPtr<MessageEvent> EventSource::createMessageEvent()
386 {
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();
390 }
391
392 EventTargetData* EventSource::eventTargetData()
393 {
394     return &m_eventTargetData;
395 }
396
397 EventTargetData* EventSource::ensureEventTargetData()
398 {
399     return &m_eventTargetData;
400 }
401
402 } // namespace WebCore