1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4  * License, v. 2.0. If a copy of the MPL was not distributed with this
5  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 
7 #include "EventSourceEventService.h"
8 #include "mozilla/StaticPtr.h"
9 #include "nsISupportsPrimitives.h"
10 #include "nsIObserverService.h"
11 #include "nsXULAppAPI.h"
12 #include "nsSocketTransportService2.h"
13 #include "nsThreadUtils.h"
14 #include "mozilla/Services.h"
15 
16 namespace mozilla::dom {
17 
18 namespace {
19 
20 StaticRefPtr<EventSourceEventService> gEventSourceEventService;
21 
22 }  // anonymous namespace
23 
24 class EventSourceBaseRunnable : public Runnable {
25  public:
EventSourceBaseRunnable(uint64_t aHttpChannelId,uint64_t aInnerWindowID)26   EventSourceBaseRunnable(uint64_t aHttpChannelId, uint64_t aInnerWindowID)
27       : Runnable("dom::EventSourceBaseRunnable"),
28         mHttpChannelId(aHttpChannelId),
29         mInnerWindowID(aInnerWindowID) {}
30 
Run()31   NS_IMETHOD Run() override {
32     MOZ_ASSERT(NS_IsMainThread());
33     RefPtr<EventSourceEventService> service =
34         EventSourceEventService::GetOrCreate();
35     MOZ_ASSERT(service);
36 
37     EventSourceEventService::EventSourceListeners listeners;
38 
39     service->GetListeners(mInnerWindowID, listeners);
40 
41     for (uint32_t i = 0; i < listeners.Length(); ++i) {
42       DoWork(listeners[i]);
43     }
44 
45     return NS_OK;
46   }
47 
48  protected:
49   ~EventSourceBaseRunnable() = default;
50 
51   virtual void DoWork(nsIEventSourceEventListener* aListener) = 0;
52 
53   uint64_t mHttpChannelId;
54   uint64_t mInnerWindowID;
55 };
56 
57 class EventSourceConnectionOpenedRunnable final
58     : public EventSourceBaseRunnable {
59  public:
EventSourceConnectionOpenedRunnable(uint64_t aHttpChannelId,uint64_t aInnerWindowID)60   EventSourceConnectionOpenedRunnable(uint64_t aHttpChannelId,
61                                       uint64_t aInnerWindowID)
62       : EventSourceBaseRunnable(aHttpChannelId, aInnerWindowID) {}
63 
64  private:
DoWork(nsIEventSourceEventListener * aListener)65   virtual void DoWork(nsIEventSourceEventListener* aListener) override {
66     DebugOnly<nsresult> rv =
67         aListener->EventSourceConnectionOpened(mHttpChannelId);
68     NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
69                          "EventSourceConnectionOpened failed");
70   }
71 };
72 
73 class EventSourceConnectionClosedRunnable final
74     : public EventSourceBaseRunnable {
75  public:
EventSourceConnectionClosedRunnable(uint64_t aHttpChannelId,uint64_t aInnerWindowID)76   EventSourceConnectionClosedRunnable(uint64_t aHttpChannelId,
77                                       uint64_t aInnerWindowID)
78       : EventSourceBaseRunnable(aHttpChannelId, aInnerWindowID) {}
79 
80  private:
DoWork(nsIEventSourceEventListener * aListener)81   virtual void DoWork(nsIEventSourceEventListener* aListener) override {
82     DebugOnly<nsresult> rv =
83         aListener->EventSourceConnectionClosed(mHttpChannelId);
84     NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
85                          "EventSourceConnectionClosed failed");
86   }
87 };
88 
89 class EventSourceEventRunnable final : public EventSourceBaseRunnable {
90  public:
EventSourceEventRunnable(uint64_t aHttpChannelId,uint64_t aInnerWindowID,const nsAString & aEventName,const nsAString & aLastEventID,const nsAString & aData,uint32_t aRetry,DOMHighResTimeStamp aTimeStamp)91   EventSourceEventRunnable(uint64_t aHttpChannelId, uint64_t aInnerWindowID,
92                            const nsAString& aEventName,
93                            const nsAString& aLastEventID,
94                            const nsAString& aData, uint32_t aRetry,
95                            DOMHighResTimeStamp aTimeStamp)
96       : EventSourceBaseRunnable(aHttpChannelId, aInnerWindowID),
97         mEventName(aEventName),
98         mLastEventID(aLastEventID),
99         mData(aData),
100         mRetry(aRetry),
101         mTimeStamp(aTimeStamp) {}
102 
103  private:
DoWork(nsIEventSourceEventListener * aListener)104   virtual void DoWork(nsIEventSourceEventListener* aListener) override {
105     DebugOnly<nsresult> rv = aListener->EventReceived(
106         mHttpChannelId, mEventName, mLastEventID, mData, mRetry, mTimeStamp);
107 
108     NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "Event op failed");
109   }
110 
111   nsString mEventName;
112   nsString mLastEventID;
113   nsString mData;
114   uint32_t mRetry;
115   DOMHighResTimeStamp mTimeStamp;
116 };
117 
118 /* static */
119 already_AddRefed<EventSourceEventService>
GetOrCreate()120 EventSourceEventService::GetOrCreate() {
121   MOZ_ASSERT(NS_IsMainThread());
122 
123   if (!gEventSourceEventService) {
124     gEventSourceEventService = new EventSourceEventService();
125   }
126 
127   RefPtr<EventSourceEventService> service = gEventSourceEventService.get();
128   return service.forget();
129 }
130 
131 NS_INTERFACE_MAP_BEGIN(EventSourceEventService)
NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports,nsIEventSourceEventService)132   NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIEventSourceEventService)
133   NS_INTERFACE_MAP_ENTRY(nsIObserver)
134   NS_INTERFACE_MAP_ENTRY(nsIEventSourceEventService)
135 NS_INTERFACE_MAP_END
136 
137 NS_IMPL_ADDREF(EventSourceEventService)
138 NS_IMPL_RELEASE(EventSourceEventService)
139 
140 EventSourceEventService::EventSourceEventService() : mCountListeners(0) {
141   MOZ_ASSERT(NS_IsMainThread());
142 
143   nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
144   if (obs) {
145     obs->AddObserver(this, "xpcom-shutdown", false);
146     obs->AddObserver(this, "inner-window-destroyed", false);
147   }
148 }
149 
~EventSourceEventService()150 EventSourceEventService::~EventSourceEventService() {
151   MOZ_ASSERT(NS_IsMainThread());
152 }
153 
EventSourceConnectionOpened(uint64_t aHttpChannelId,uint64_t aInnerWindowID)154 void EventSourceEventService::EventSourceConnectionOpened(
155     uint64_t aHttpChannelId, uint64_t aInnerWindowID) {
156   // Let's continue only if we have some listeners.
157   if (!HasListeners()) {
158     return;
159   }
160 
161   RefPtr<EventSourceConnectionOpenedRunnable> runnable =
162       new EventSourceConnectionOpenedRunnable(aHttpChannelId, aInnerWindowID);
163   DebugOnly<nsresult> rv = NS_DispatchToMainThread(runnable);
164   NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "NS_DispatchToMainThread failed");
165 }
166 
EventSourceConnectionClosed(uint64_t aHttpChannelId,uint64_t aInnerWindowID)167 void EventSourceEventService::EventSourceConnectionClosed(
168     uint64_t aHttpChannelId, uint64_t aInnerWindowID) {
169   // Let's continue only if we have some listeners.
170   if (!HasListeners()) {
171     return;
172   }
173   RefPtr<EventSourceConnectionClosedRunnable> runnable =
174       new EventSourceConnectionClosedRunnable(aHttpChannelId, aInnerWindowID);
175   DebugOnly<nsresult> rv = NS_DispatchToMainThread(runnable);
176   NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "NS_DispatchToMainThread failed");
177 }
178 
EventReceived(uint64_t aHttpChannelId,uint64_t aInnerWindowID,const nsAString & aEventName,const nsAString & aLastEventID,const nsAString & aData,uint32_t aRetry,DOMHighResTimeStamp aTimeStamp)179 void EventSourceEventService::EventReceived(
180     uint64_t aHttpChannelId, uint64_t aInnerWindowID,
181     const nsAString& aEventName, const nsAString& aLastEventID,
182     const nsAString& aData, uint32_t aRetry, DOMHighResTimeStamp aTimeStamp) {
183   // Let's continue only if we have some listeners.
184   if (!HasListeners()) {
185     return;
186   }
187 
188   RefPtr<EventSourceEventRunnable> runnable =
189       new EventSourceEventRunnable(aHttpChannelId, aInnerWindowID, aEventName,
190                                    aLastEventID, aData, aRetry, aTimeStamp);
191   DebugOnly<nsresult> rv = NS_DispatchToMainThread(runnable);
192   NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "NS_DispatchToMainThread failed");
193 }
194 
195 NS_IMETHODIMP
AddListener(uint64_t aInnerWindowID,nsIEventSourceEventListener * aListener)196 EventSourceEventService::AddListener(uint64_t aInnerWindowID,
197                                      nsIEventSourceEventListener* aListener) {
198   MOZ_ASSERT(NS_IsMainThread());
199   if (!aListener) {
200     return NS_ERROR_FAILURE;
201   }
202   ++mCountListeners;
203 
204   WindowListener* listener = mWindows.GetOrInsertNew(aInnerWindowID);
205 
206   listener->mListeners.AppendElement(aListener);
207 
208   return NS_OK;
209 }
210 
211 NS_IMETHODIMP
RemoveListener(uint64_t aInnerWindowID,nsIEventSourceEventListener * aListener)212 EventSourceEventService::RemoveListener(
213     uint64_t aInnerWindowID, nsIEventSourceEventListener* aListener) {
214   MOZ_ASSERT(NS_IsMainThread());
215 
216   if (!aListener) {
217     return NS_ERROR_FAILURE;
218   }
219 
220   WindowListener* listener = mWindows.Get(aInnerWindowID);
221   if (!listener) {
222     return NS_ERROR_FAILURE;
223   }
224 
225   if (!listener->mListeners.RemoveElement(aListener)) {
226     return NS_ERROR_FAILURE;
227   }
228 
229   // The last listener for this window.
230   if (listener->mListeners.IsEmpty()) {
231     mWindows.Remove(aInnerWindowID);
232   }
233 
234   MOZ_ASSERT(mCountListeners);
235   --mCountListeners;
236 
237   return NS_OK;
238 }
239 
240 NS_IMETHODIMP
HasListenerFor(uint64_t aInnerWindowID,bool * aResult)241 EventSourceEventService::HasListenerFor(uint64_t aInnerWindowID,
242                                         bool* aResult) {
243   MOZ_ASSERT(NS_IsMainThread());
244 
245   *aResult = mWindows.Get(aInnerWindowID);
246 
247   return NS_OK;
248 }
249 
250 NS_IMETHODIMP
Observe(nsISupports * aSubject,const char * aTopic,const char16_t * aData)251 EventSourceEventService::Observe(nsISupports* aSubject, const char* aTopic,
252                                  const char16_t* aData) {
253   MOZ_ASSERT(NS_IsMainThread());
254 
255   if (!strcmp(aTopic, "xpcom-shutdown")) {
256     Shutdown();
257     return NS_OK;
258   }
259 
260   if (!strcmp(aTopic, "inner-window-destroyed") && HasListeners()) {
261     nsCOMPtr<nsISupportsPRUint64> wrapper = do_QueryInterface(aSubject);
262     NS_ENSURE_TRUE(wrapper, NS_ERROR_FAILURE);
263 
264     uint64_t innerID;
265     nsresult rv = wrapper->GetData(&innerID);
266     NS_ENSURE_SUCCESS(rv, rv);
267 
268     WindowListener* listener = mWindows.Get(innerID);
269     if (!listener) {
270       return NS_OK;
271     }
272 
273     MOZ_ASSERT(mCountListeners >= listener->mListeners.Length());
274     mCountListeners -= listener->mListeners.Length();
275     mWindows.Remove(innerID);
276   }
277 
278   // This should not happen.
279   return NS_ERROR_FAILURE;
280 }
281 
Shutdown()282 void EventSourceEventService::Shutdown() {
283   MOZ_ASSERT(NS_IsMainThread());
284 
285   if (gEventSourceEventService) {
286     nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
287     if (obs) {
288       obs->RemoveObserver(gEventSourceEventService, "xpcom-shutdown");
289       obs->RemoveObserver(gEventSourceEventService, "inner-window-destroyed");
290     }
291 
292     mWindows.Clear();
293     gEventSourceEventService = nullptr;
294   }
295 }
296 
HasListeners() const297 bool EventSourceEventService::HasListeners() const { return !!mCountListeners; }
298 
GetListeners(uint64_t aInnerWindowID,EventSourceEventService::EventSourceListeners & aListeners) const299 void EventSourceEventService::GetListeners(
300     uint64_t aInnerWindowID,
301     EventSourceEventService::EventSourceListeners& aListeners) const {
302   aListeners.Clear();
303 
304   WindowListener* listener = mWindows.Get(aInnerWindowID);
305   if (!listener) {
306     return;
307   }
308 
309   aListeners.AppendElements(listener->mListeners);
310 }
311 
312 }  // namespace mozilla::dom
313