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 "third_party/blink/renderer/modules/eventsource/event_source.h"
34 
35 #include <memory>
36 
37 #include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom-blink.h"
38 #include "third_party/blink/public/platform/task_type.h"
39 #include "third_party/blink/public/platform/web_url_request.h"
40 #include "third_party/blink/renderer/bindings/core/v8/script_controller.h"
41 #include "third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value.h"
42 #include "third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value_factory.h"
43 #include "third_party/blink/renderer/bindings/modules/v8/v8_event_source_init.h"
44 #include "third_party/blink/renderer/core/dom/events/event.h"
45 #include "third_party/blink/renderer/core/events/message_event.h"
46 #include "third_party/blink/renderer/core/execution_context/execution_context.h"
47 #include "third_party/blink/renderer/core/frame/csp/content_security_policy.h"
48 #include "third_party/blink/renderer/core/frame/local_dom_window.h"
49 #include "third_party/blink/renderer/core/frame/local_frame.h"
50 #include "third_party/blink/renderer/core/inspector/console_message.h"
51 #include "third_party/blink/renderer/core/loader/threadable_loader.h"
52 #include "third_party/blink/renderer/core/probe/core_probes.h"
53 #include "third_party/blink/renderer/platform/bindings/exception_state.h"
54 #include "third_party/blink/renderer/platform/heap/heap.h"
55 #include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
56 #include "third_party/blink/renderer/platform/loader/fetch/resource_error.h"
57 #include "third_party/blink/renderer/platform/loader/fetch/resource_loader_options.h"
58 #include "third_party/blink/renderer/platform/loader/fetch/resource_request.h"
59 #include "third_party/blink/renderer/platform/loader/fetch/resource_response.h"
60 #include "third_party/blink/renderer/platform/network/http_names.h"
61 #include "third_party/blink/renderer/platform/weborigin/security_origin.h"
62 #include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
63 
64 namespace blink {
65 
66 const uint64_t EventSource::kDefaultReconnectDelay = 3000;
67 
EventSource(ExecutionContext * context,const KURL & url,const EventSourceInit * event_source_init)68 inline EventSource::EventSource(ExecutionContext* context,
69                                 const KURL& url,
70                                 const EventSourceInit* event_source_init)
71     : ExecutionContextLifecycleObserver(context),
72       url_(url),
73       current_url_(url),
74       with_credentials_(event_source_init->withCredentials()),
75       state_(kConnecting),
76       connect_timer_(context->GetTaskRunner(TaskType::kRemoteEvent),
77                      this,
78                      &EventSource::ConnectTimerFired),
79       reconnect_delay_(kDefaultReconnectDelay),
80       world_(context->GetCurrentWorld()) {}
81 
Create(ExecutionContext * context,const String & url,const EventSourceInit * event_source_init,ExceptionState & exception_state)82 EventSource* EventSource::Create(ExecutionContext* context,
83                                  const String& url,
84                                  const EventSourceInit* event_source_init,
85                                  ExceptionState& exception_state) {
86   UseCounter::Count(context, context->IsWindow()
87                                  ? WebFeature::kEventSourceDocument
88                                  : WebFeature::kEventSourceWorker);
89 
90   if (url.IsEmpty()) {
91     exception_state.ThrowDOMException(
92         DOMExceptionCode::kSyntaxError,
93         "Cannot open an EventSource to an empty URL.");
94     return nullptr;
95   }
96 
97   KURL full_url = context->CompleteURL(url);
98   if (!full_url.IsValid()) {
99     exception_state.ThrowDOMException(
100         DOMExceptionCode::kSyntaxError,
101         "Cannot open an EventSource to '" + url + "'. The URL is invalid.");
102     return nullptr;
103   }
104 
105   EventSource* source =
106       MakeGarbageCollected<EventSource>(context, full_url, event_source_init);
107 
108   source->ScheduleInitialConnect();
109   return source;
110 }
111 
~EventSource()112 EventSource::~EventSource() {
113   DCHECK_EQ(kClosed, state_);
114   DCHECK(!loader_);
115 }
116 
ScheduleInitialConnect()117 void EventSource::ScheduleInitialConnect() {
118   DCHECK_EQ(kConnecting, state_);
119   DCHECK(!loader_);
120 
121   connect_timer_.StartOneShot(base::TimeDelta(), FROM_HERE);
122 }
123 
Connect()124 void EventSource::Connect() {
125   DCHECK_EQ(kConnecting, state_);
126   DCHECK(!loader_);
127   DCHECK(GetExecutionContext());
128 
129   ExecutionContext& execution_context = *this->GetExecutionContext();
130   ResourceRequest request(current_url_);
131   request.SetHttpMethod(http_names::kGET);
132   request.SetHttpHeaderField(http_names::kAccept, "text/event-stream");
133   request.SetHttpHeaderField(http_names::kCacheControl, "no-cache");
134   request.SetRequestContext(mojom::blink::RequestContextType::EVENT_SOURCE);
135   request.SetFetchLikeAPI(true);
136   request.SetMode(network::mojom::RequestMode::kCors);
137   request.SetCredentialsMode(
138       with_credentials_ ? network::mojom::CredentialsMode::kInclude
139                         : network::mojom::CredentialsMode::kSameOrigin);
140   request.SetCacheMode(blink::mojom::FetchCacheMode::kNoStore);
141   request.SetExternalRequestStateFromRequestorAddressSpace(
142       execution_context.AddressSpace());
143   request.SetCorsPreflightPolicy(
144       network::mojom::CorsPreflightPolicy::kPreventPreflight);
145   if (parser_ && !parser_->LastEventId().IsEmpty()) {
146     // HTTP headers are Latin-1 byte strings, but the Last-Event-ID header is
147     // encoded as UTF-8.
148     // TODO(davidben): This should be captured in the type of
149     // setHTTPHeaderField's arguments.
150     std::string last_event_id_utf8 = parser_->LastEventId().Utf8();
151     request.SetHttpHeaderField(
152         http_names::kLastEventID,
153         AtomicString(reinterpret_cast<const LChar*>(last_event_id_utf8.c_str()),
154                      last_event_id_utf8.length()));
155   }
156 
157   ResourceLoaderOptions resource_loader_options(world_);
158   resource_loader_options.data_buffering_policy = kDoNotBufferData;
159 
160   probe::WillSendEventSourceRequest(&execution_context);
161   loader_ = MakeGarbageCollected<ThreadableLoader>(execution_context, this,
162                                                    resource_loader_options);
163   loader_->Start(std::move(request));
164 }
165 
NetworkRequestEnded()166 void EventSource::NetworkRequestEnded() {
167   loader_ = nullptr;
168 
169   if (state_ != kClosed)
170     ScheduleReconnect();
171 }
172 
ScheduleReconnect()173 void EventSource::ScheduleReconnect() {
174   state_ = kConnecting;
175   connect_timer_.StartOneShot(
176       base::TimeDelta::FromMilliseconds(reconnect_delay_), FROM_HERE);
177   DispatchEvent(*Event::Create(event_type_names::kError));
178 }
179 
ConnectTimerFired(TimerBase *)180 void EventSource::ConnectTimerFired(TimerBase*) {
181   Connect();
182 }
183 
url() const184 String EventSource::url() const {
185   return url_.GetString();
186 }
187 
withCredentials() const188 bool EventSource::withCredentials() const {
189   return with_credentials_;
190 }
191 
readyState() const192 EventSource::State EventSource::readyState() const {
193   return state_;
194 }
195 
close()196 void EventSource::close() {
197   if (state_ == kClosed) {
198     DCHECK(!loader_);
199     return;
200   }
201   if (parser_)
202     parser_->Stop();
203 
204   // Stop trying to reconnect if EventSource was explicitly closed or if
205   // contextDestroyed() was called.
206   if (connect_timer_.IsActive()) {
207     connect_timer_.Stop();
208   }
209 
210   state_ = kClosed;
211 
212   if (loader_) {
213     loader_->Cancel();
214     loader_ = nullptr;
215   }
216 
217 }
218 
InterfaceName() const219 const AtomicString& EventSource::InterfaceName() const {
220   return event_target_names::kEventSource;
221 }
222 
GetExecutionContext() const223 ExecutionContext* EventSource::GetExecutionContext() const {
224   return ExecutionContextLifecycleObserver::GetExecutionContext();
225 }
226 
DidReceiveResponse(uint64_t identifier,const ResourceResponse & response)227 void EventSource::DidReceiveResponse(uint64_t identifier,
228                                      const ResourceResponse& response) {
229   DCHECK_EQ(kConnecting, state_);
230   DCHECK(loader_);
231 
232   resource_identifier_ = identifier;
233   current_url_ = response.CurrentRequestUrl();
234   event_stream_origin_ =
235       SecurityOrigin::Create(response.CurrentRequestUrl())->ToString();
236   int status_code = response.HttpStatusCode();
237   bool mime_type_is_valid = response.MimeType() == "text/event-stream";
238   bool response_is_valid = status_code == 200 && mime_type_is_valid;
239   if (response_is_valid) {
240     const String& charset = response.TextEncodingName();
241     // If we have a charset, the only allowed value is UTF-8 (case-insensitive).
242     response_is_valid =
243         charset.IsEmpty() || EqualIgnoringASCIICase(charset, "UTF-8");
244     if (!response_is_valid) {
245       StringBuilder message;
246       message.Append("EventSource's response has a charset (\"");
247       message.Append(charset);
248       message.Append("\") that is not UTF-8. Aborting the connection.");
249       // FIXME: We are missing the source line.
250       GetExecutionContext()->AddConsoleMessage(
251           MakeGarbageCollected<ConsoleMessage>(
252               mojom::ConsoleMessageSource::kJavaScript,
253               mojom::ConsoleMessageLevel::kError, message.ToString()));
254     }
255   } else {
256     // To keep the signal-to-noise ratio low, we only log 200-response with an
257     // invalid MIME type.
258     if (status_code == 200 && !mime_type_is_valid) {
259       StringBuilder message;
260       message.Append("EventSource's response has a MIME type (\"");
261       message.Append(response.MimeType());
262       message.Append(
263           "\") that is not \"text/event-stream\". Aborting the connection.");
264       // FIXME: We are missing the source line.
265       GetExecutionContext()->AddConsoleMessage(
266           MakeGarbageCollected<ConsoleMessage>(
267               mojom::ConsoleMessageSource::kJavaScript,
268               mojom::ConsoleMessageLevel::kError, message.ToString()));
269     }
270   }
271 
272   if (response_is_valid) {
273     state_ = kOpen;
274     AtomicString last_event_id;
275     if (parser_) {
276       // The new parser takes over the event ID.
277       last_event_id = parser_->LastEventId();
278     }
279     parser_ = MakeGarbageCollected<EventSourceParser>(last_event_id, this);
280     DispatchEvent(*Event::Create(event_type_names::kOpen));
281   } else {
282     loader_->Cancel();
283   }
284 }
285 
DidReceiveData(const char * data,unsigned length)286 void EventSource::DidReceiveData(const char* data, unsigned length) {
287   DCHECK_EQ(kOpen, state_);
288   DCHECK(loader_);
289   DCHECK(parser_);
290 
291   parser_->AddBytes(data, length);
292 }
293 
DidFinishLoading(uint64_t)294 void EventSource::DidFinishLoading(uint64_t) {
295   DCHECK_EQ(kOpen, state_);
296   DCHECK(loader_);
297 
298   NetworkRequestEnded();
299 }
300 
DidFail(const ResourceError & error)301 void EventSource::DidFail(const ResourceError& error) {
302   DCHECK(loader_);
303   if (error.IsCancellation() && state_ == kClosed) {
304     NetworkRequestEnded();
305     return;
306   }
307 
308   DCHECK_NE(kClosed, state_);
309 
310   if (error.IsAccessCheck()) {
311     AbortConnectionAttempt();
312     return;
313   }
314 
315   if (error.IsCancellation()) {
316     // When the loading is cancelled for an external reason (e.g.,
317     // window.stop()), dispatch an error event and do not reconnect.
318     AbortConnectionAttempt();
319     return;
320   }
321   NetworkRequestEnded();
322 }
323 
DidFailRedirectCheck()324 void EventSource::DidFailRedirectCheck() {
325   DCHECK(loader_);
326 
327   AbortConnectionAttempt();
328 }
329 
OnMessageEvent(const AtomicString & event_type,const String & data,const AtomicString & last_event_id)330 void EventSource::OnMessageEvent(const AtomicString& event_type,
331                                  const String& data,
332                                  const AtomicString& last_event_id) {
333   MessageEvent* e = MessageEvent::Create();
334   e->initMessageEvent(event_type, false, false, data, event_stream_origin_,
335                       last_event_id, nullptr, nullptr);
336 
337   probe::WillDispatchEventSourceEvent(GetExecutionContext(),
338                                       resource_identifier_, event_type,
339                                       last_event_id, data);
340   DispatchEvent(*e);
341 }
342 
OnReconnectionTimeSet(uint64_t reconnection_time)343 void EventSource::OnReconnectionTimeSet(uint64_t reconnection_time) {
344   reconnect_delay_ = reconnection_time;
345 }
346 
AbortConnectionAttempt()347 void EventSource::AbortConnectionAttempt() {
348   DCHECK_NE(kClosed, state_);
349 
350   loader_ = nullptr;
351   state_ = kClosed;
352   NetworkRequestEnded();
353 
354   DispatchEvent(*Event::Create(event_type_names::kError));
355 }
356 
ContextDestroyed()357 void EventSource::ContextDestroyed() {
358   close();
359 }
360 
HasPendingActivity() const361 bool EventSource::HasPendingActivity() const {
362   return state_ != kClosed;
363 }
364 
Trace(Visitor * visitor) const365 void EventSource::Trace(Visitor* visitor) const {
366   visitor->Trace(parser_);
367   visitor->Trace(loader_);
368   EventTargetWithInlineData::Trace(visitor);
369   ThreadableLoaderClient::Trace(visitor);
370   ExecutionContextLifecycleObserver::Trace(visitor);
371   EventSourceParser::Client::Trace(visitor);
372 }
373 
374 }  // namespace blink
375