Move WebCore into Source
[WebKit-https.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  *
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
35 #if ENABLE(EVENTSOURCE)
36
37 #include "EventSource.h"
38
39 #include "MemoryCache.h"
40 #include "DOMWindow.h"
41 #include "Event.h"
42 #include "EventException.h"
43 #include "PlatformString.h"
44 #include "MessageEvent.h"
45 #include "ResourceError.h"
46 #include "ResourceRequest.h"
47 #include "ResourceResponse.h"
48 #include "ScriptExecutionContext.h"
49 #include "SerializedScriptValue.h"
50 #include "TextResourceDecoder.h"
51 #include "ThreadableLoader.h"
52
53 namespace WebCore {
54
55 const unsigned long long EventSource::defaultReconnectDelay = 3000;
56
57 inline EventSource::EventSource(const KURL& url, ScriptExecutionContext* context)
58     : ActiveDOMObject(context, this)
59     , m_url(url)
60     , m_state(CONNECTING)
61     , m_decoder(TextResourceDecoder::create("text/plain", "UTF-8"))
62     , m_reconnectTimer(this, &EventSource::reconnectTimerFired)
63     , m_discardTrailingNewline(false)
64     , m_failSilently(false)
65     , m_requestInFlight(false)
66     , m_reconnectDelay(defaultReconnectDelay)
67     , m_origin(context->securityOrigin()->toString())
68 {
69 }
70
71 PassRefPtr<EventSource> EventSource::create(const String& url, ScriptExecutionContext* context, ExceptionCode& ec)
72 {
73     if (url.isEmpty()) {
74         ec = SYNTAX_ERR;
75         return 0;
76     }
77
78     KURL fullURL = context->completeURL(url);
79     if (!fullURL.isValid()) {
80         ec = SYNTAX_ERR;
81         return 0;
82     }
83
84     // FIXME: Should support at least some cross-origin requests.
85     if (!context->securityOrigin()->canRequest(fullURL)) {
86         ec = SECURITY_ERR;
87         return 0;
88     }
89
90     RefPtr<EventSource> source = adoptRef(new EventSource(fullURL, context));
91
92     source->setPendingActivity(source.get());
93     source->connect();
94
95     return source.release();
96 }
97
98 EventSource::~EventSource()
99 {
100 }
101
102 void EventSource::connect()
103 {
104     ResourceRequest request(m_url);
105     request.setHTTPMethod("GET");
106     request.setHTTPHeaderField("Accept", "text/event-stream");
107     request.setHTTPHeaderField("Cache-Control", "no-cache");
108     if (!m_lastEventId.isEmpty())
109         request.setHTTPHeaderField("Last-Event-ID", m_lastEventId);
110
111     ThreadableLoaderOptions options;
112     options.sendLoadCallbacks = true;
113     options.sniffContent = false;
114     options.allowCredentials = true;
115
116     m_loader = ThreadableLoader::create(scriptExecutionContext(), this, request, options);
117
118     m_requestInFlight = true;
119 }
120
121 void EventSource::endRequest()
122 {
123     if (!m_requestInFlight)
124         return;
125
126     m_requestInFlight = false;
127
128     if (!m_failSilently)
129         dispatchEvent(Event::create(eventNames().errorEvent, false, false));
130
131     if (m_state != CLOSED)
132         scheduleReconnect();
133     else
134         unsetPendingActivity(this);
135 }
136
137 void EventSource::scheduleReconnect()
138 {
139     m_state = CONNECTING;
140     m_reconnectTimer.startOneShot(m_reconnectDelay / 1000);
141 }
142
143 void EventSource::reconnectTimerFired(Timer<EventSource>*)
144 {
145     connect();
146 }
147
148 String EventSource::url() const
149 {
150     return m_url.string();
151 }
152
153 EventSource::State EventSource::readyState() const
154 {
155     return m_state;
156 }
157
158 void EventSource::close()
159 {
160     if (m_state == CLOSED)
161         return;
162
163     if (m_reconnectTimer.isActive()) {
164         m_reconnectTimer.stop();
165         unsetPendingActivity(this);
166     }
167
168     m_state = CLOSED;
169     m_failSilently = true;
170
171     if (m_requestInFlight)
172         m_loader->cancel();
173 }
174
175 ScriptExecutionContext* EventSource::scriptExecutionContext() const
176 {
177     return ActiveDOMObject::scriptExecutionContext();
178 }
179
180 void EventSource::didReceiveResponse(const ResourceResponse& response)
181 {
182     int statusCode = response.httpStatusCode();
183     if (statusCode == 200 && response.mimeType() == "text/event-stream") {
184         m_state = OPEN;
185         dispatchEvent(Event::create(eventNames().openEvent, false, false));
186     } else {
187         if (statusCode <= 200 || statusCode > 299)
188             m_state = CLOSED;
189         m_loader->cancel();
190     }
191 }
192
193 void EventSource::didReceiveData(const char* data, int length)
194 {
195     append(m_receiveBuf, m_decoder->decode(data, length));
196     parseEventStream();
197 }
198
199 void EventSource::didFinishLoading(unsigned long)
200 {
201     if (m_receiveBuf.size() > 0 || m_data.size() > 0) {
202         append(m_receiveBuf, "\n\n");
203         parseEventStream();
204     }
205     m_state = CONNECTING;
206     endRequest();
207 }
208
209 void EventSource::didFail(const ResourceError& error)
210 {
211     int canceled = error.isCancellation();
212     if (((m_state == CONNECTING) && !canceled) || ((m_state == OPEN) && canceled))
213         m_state = CLOSED;
214     endRequest();
215 }
216
217 void EventSource::didFailRedirectCheck()
218 {
219     m_state = CLOSED;
220     m_loader->cancel();
221 }
222
223 void EventSource::parseEventStream()
224 {
225     unsigned int bufPos = 0;
226     unsigned int bufSize = m_receiveBuf.size();
227     while (bufPos < bufSize) {
228         if (m_discardTrailingNewline) {
229             if (m_receiveBuf[bufPos] == '\n')
230                 bufPos++;
231             m_discardTrailingNewline = false;
232         }
233
234         int lineLength = -1;
235         int fieldLength = -1;
236         for (unsigned int i = bufPos; lineLength < 0 && i < bufSize; i++) {
237             switch (m_receiveBuf[i]) {
238             case ':':
239                 if (fieldLength < 0)
240                     fieldLength = i - bufPos;
241                 break;
242             case '\r':
243                 m_discardTrailingNewline = true;
244             case '\n':
245                 lineLength = i - bufPos;
246                 break;
247             }
248         }
249
250         if (lineLength < 0)
251             break;
252
253         parseEventStreamLine(bufPos, fieldLength, lineLength);
254         bufPos += lineLength + 1;
255     }
256
257     if (bufPos == bufSize)
258         m_receiveBuf.clear();
259     else if (bufPos)
260         m_receiveBuf.remove(0, bufPos);
261 }
262
263 void EventSource::parseEventStreamLine(unsigned int bufPos, int fieldLength, int lineLength)
264 {
265     if (!lineLength) {
266         if (!m_data.isEmpty()) {
267             m_data.removeLast();
268             dispatchEvent(createMessageEvent());
269         }
270         if (!m_eventName.isEmpty())
271             m_eventName = "";
272     } else if (fieldLength) {
273         bool noValue = fieldLength < 0;
274
275         String field(&m_receiveBuf[bufPos], noValue ? lineLength : fieldLength);
276         int step;
277         if (noValue)
278             step = lineLength;
279         else if (m_receiveBuf[bufPos + fieldLength + 1] != ' ')
280             step = fieldLength + 1;
281         else
282             step = fieldLength + 2;
283         bufPos += step;
284         int valueLength = lineLength - step;
285
286         if (field == "data") {
287             if (valueLength)
288                 m_data.append(&m_receiveBuf[bufPos], valueLength);
289             m_data.append('\n');
290         } else if (field == "event")
291             m_eventName = valueLength ? String(&m_receiveBuf[bufPos], valueLength) : "";
292         else if (field == "id")
293             m_lastEventId = valueLength ? String(&m_receiveBuf[bufPos], valueLength) : "";
294         else if (field == "retry") {
295             if (!valueLength)
296                 m_reconnectDelay = defaultReconnectDelay;
297             else {
298                 String value(&m_receiveBuf[bufPos], valueLength);
299                 bool ok;
300                 unsigned long long retry = value.toUInt64(&ok);
301                 if (ok)
302                     m_reconnectDelay = retry;
303             }
304         }
305     }
306 }
307
308 void EventSource::stop()
309 {
310     close();
311 }
312
313 PassRefPtr<MessageEvent> EventSource::createMessageEvent()
314 {
315     RefPtr<MessageEvent> event = MessageEvent::create();
316     event->initMessageEvent(m_eventName.isEmpty() ? eventNames().messageEvent : AtomicString(m_eventName), false, false, SerializedScriptValue::create(String::adopt(m_data)), m_origin, m_lastEventId, 0, 0);
317     return event.release();
318 }
319
320 EventTargetData* EventSource::eventTargetData()
321 {
322     return &m_eventTargetData;
323 }
324
325 EventTargetData* EventSource::ensureEventTargetData()
326 {
327     return &m_eventTargetData;
328 }
329
330 } // namespace WebCore
331
332 #endif // ENABLE(EVENTSOURCE)