1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim:set ts=2 sw=2 sts=2 et cindent: */
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 "mozilla/dom/ContentParent.h"
8 #include "mozilla/dom/HTMLIFrameElementBinding.h"
9 #include "mozilla/dom/TabParent.h"
10 #include "mozilla/Function.h"
11 #include "mozilla/Logging.h"
12 #include "mozilla/Move.h"
13 #include "mozilla/Preferences.h"
14 #include "mozilla/Services.h"
15 #include "nsContentUtils.h"
16 #include "nsGlobalWindow.h"
17 #include "nsIDocShell.h"
18 #include "nsFrameLoader.h"
19 #include "nsIMutableArray.h"
20 #include "nsINetAddr.h"
21 #include "nsISocketTransport.h"
22 #include "nsISupportsPrimitives.h"
23 #include "nsNetCID.h"
24 #include "nsServiceManagerUtils.h"
25 #include "nsThreadUtils.h"
26 #include "PresentationLog.h"
27 #include "PresentationService.h"
28 #include "PresentationSessionInfo.h"
29 
30 #ifdef MOZ_WIDGET_ANDROID
31 #include "nsIPresentationNetworkHelper.h"
32 #endif // MOZ_WIDGET_ANDROID
33 
34 #ifdef MOZ_WIDGET_GONK
35 #include "nsINetworkInterface.h"
36 #include "nsINetworkManager.h"
37 #endif
38 
39 using namespace mozilla;
40 using namespace mozilla::dom;
41 using namespace mozilla::services;
42 
43 /*
44  * Implementation of PresentationChannelDescription
45  */
46 
47 namespace mozilla {
48 namespace dom {
49 
50 #ifdef MOZ_WIDGET_ANDROID
51 
52 namespace {
53 
54 class PresentationNetworkHelper final : public nsIPresentationNetworkHelperListener
55 {
56 public:
57   NS_DECL_ISUPPORTS
58   NS_DECL_NSIPRESENTATIONNETWORKHELPERLISTENER
59 
60   using Function = nsresult(PresentationControllingInfo::*)(const nsACString&);
61 
62   explicit PresentationNetworkHelper(PresentationControllingInfo* aInfo,
63                                      const Function& aFunc);
64 
65   nsresult GetWifiIPAddress();
66 
67 private:
68   ~PresentationNetworkHelper() = default;
69 
70   RefPtr<PresentationControllingInfo> mInfo;
71   Function mFunc;
72 };
73 
NS_IMPL_ISUPPORTS(PresentationNetworkHelper,nsIPresentationNetworkHelperListener)74 NS_IMPL_ISUPPORTS(PresentationNetworkHelper,
75                   nsIPresentationNetworkHelperListener)
76 
77 PresentationNetworkHelper::PresentationNetworkHelper(PresentationControllingInfo* aInfo,
78                                                      const Function& aFunc)
79   : mInfo(aInfo)
80   , mFunc(aFunc)
81 {
82   MOZ_ASSERT(aInfo);
83   MOZ_ASSERT(aFunc);
84 }
85 
86 nsresult
GetWifiIPAddress()87 PresentationNetworkHelper::GetWifiIPAddress()
88 {
89   nsresult rv;
90 
91   nsCOMPtr<nsIPresentationNetworkHelper> networkHelper =
92     do_GetService(PRESENTATION_NETWORK_HELPER_CONTRACTID, &rv);
93   if (NS_WARN_IF(NS_FAILED(rv))) {
94     return rv;
95   }
96 
97   return networkHelper->GetWifiIPAddress(this);
98 }
99 
100 NS_IMETHODIMP
OnError(const nsACString & aReason)101 PresentationNetworkHelper::OnError(const nsACString & aReason)
102 {
103   PRES_ERROR("PresentationNetworkHelper::OnError: %s",
104     nsPromiseFlatCString(aReason).get());
105   return NS_OK;
106 }
107 
108 NS_IMETHODIMP
OnGetWifiIPAddress(const nsACString & aIPAddress)109 PresentationNetworkHelper::OnGetWifiIPAddress(const nsACString& aIPAddress)
110 {
111   MOZ_ASSERT(mInfo);
112   MOZ_ASSERT(mFunc);
113 
114   NS_DispatchToMainThread(
115     NewRunnableMethod<nsCString>(mInfo,
116                                  mFunc,
117                                  aIPAddress));
118   return NS_OK;
119 }
120 
121 } // anonymous namespace
122 
123 #endif // MOZ_WIDGET_ANDROID
124 
125 class TCPPresentationChannelDescription final : public nsIPresentationChannelDescription
126 {
127 public:
128   NS_DECL_ISUPPORTS
129   NS_DECL_NSIPRESENTATIONCHANNELDESCRIPTION
130 
TCPPresentationChannelDescription(const nsACString & aAddress,uint16_t aPort)131   TCPPresentationChannelDescription(const nsACString& aAddress,
132                                     uint16_t aPort)
133     : mAddress(aAddress)
134     , mPort(aPort)
135   {
136   }
137 
138 private:
~TCPPresentationChannelDescription()139   ~TCPPresentationChannelDescription() {}
140 
141   nsCString mAddress;
142   uint16_t mPort;
143 };
144 
145 } // namespace dom
146 } // namespace mozilla
147 
NS_IMPL_ISUPPORTS(TCPPresentationChannelDescription,nsIPresentationChannelDescription)148 NS_IMPL_ISUPPORTS(TCPPresentationChannelDescription, nsIPresentationChannelDescription)
149 
150 NS_IMETHODIMP
151 TCPPresentationChannelDescription::GetType(uint8_t* aRetVal)
152 {
153   if (NS_WARN_IF(!aRetVal)) {
154     return NS_ERROR_INVALID_POINTER;
155   }
156 
157   *aRetVal = nsIPresentationChannelDescription::TYPE_TCP;
158   return NS_OK;
159 }
160 
161 NS_IMETHODIMP
GetTcpAddress(nsIArray ** aRetVal)162 TCPPresentationChannelDescription::GetTcpAddress(nsIArray** aRetVal)
163 {
164   if (NS_WARN_IF(!aRetVal)) {
165     return NS_ERROR_INVALID_POINTER;
166   }
167 
168   nsCOMPtr<nsIMutableArray> array = do_CreateInstance(NS_ARRAY_CONTRACTID);
169   if (NS_WARN_IF(!array)) {
170     return NS_ERROR_OUT_OF_MEMORY;
171   }
172 
173   // TODO bug 1228504 Take all IP addresses in PresentationChannelDescription
174   // into account. And at the first stage Presentation API is only exposed on
175   // Firefox OS where the first IP appears enough for most scenarios.
176   nsCOMPtr<nsISupportsCString> address = do_CreateInstance(NS_SUPPORTS_CSTRING_CONTRACTID);
177   if (NS_WARN_IF(!address)) {
178     return NS_ERROR_OUT_OF_MEMORY;
179   }
180   address->SetData(mAddress);
181 
182   array->AppendElement(address, false);
183   array.forget(aRetVal);
184 
185   return NS_OK;
186 }
187 
188 NS_IMETHODIMP
GetTcpPort(uint16_t * aRetVal)189 TCPPresentationChannelDescription::GetTcpPort(uint16_t* aRetVal)
190 {
191   if (NS_WARN_IF(!aRetVal)) {
192     return NS_ERROR_INVALID_POINTER;
193   }
194 
195   *aRetVal = mPort;
196   return NS_OK;
197 }
198 
199 NS_IMETHODIMP
GetDataChannelSDP(nsAString & aDataChannelSDP)200 TCPPresentationChannelDescription::GetDataChannelSDP(nsAString& aDataChannelSDP)
201 {
202   aDataChannelSDP.Truncate();
203   return NS_OK;
204 }
205 
206 /*
207  * Implementation of PresentationSessionInfo
208  */
209 
210 NS_IMPL_ISUPPORTS(PresentationSessionInfo,
211                   nsIPresentationSessionTransportCallback,
212                   nsIPresentationControlChannelListener,
213                   nsIPresentationSessionTransportBuilderListener);
214 
215 /* virtual */ nsresult
Init(nsIPresentationControlChannel * aControlChannel)216 PresentationSessionInfo::Init(nsIPresentationControlChannel* aControlChannel)
217 {
218   SetControlChannel(aControlChannel);
219   return NS_OK;
220 }
221 
222 /* virtual */ void
Shutdown(nsresult aReason)223 PresentationSessionInfo::Shutdown(nsresult aReason)
224 {
225   PRES_DEBUG("%s:id[%s], reason[%x], role[%d]\n", __func__,
226              NS_ConvertUTF16toUTF8(mSessionId).get(), aReason, mRole);
227 
228   NS_WARNING_ASSERTION(NS_SUCCEEDED(aReason), "bad reason");
229 
230   // Close the control channel if any.
231   if (mControlChannel) {
232     Unused << NS_WARN_IF(NS_FAILED(mControlChannel->Disconnect(aReason)));
233   }
234 
235   // Close the data transport channel if any.
236   if (mTransport) {
237     // |mIsTransportReady| will be unset once |NotifyTransportClosed| is called.
238     Unused << NS_WARN_IF(NS_FAILED(mTransport->Close(aReason)));
239   }
240 
241   mIsResponderReady = false;
242   mIsOnTerminating = false;
243 
244   ResetBuilder();
245 }
246 
247 nsresult
SetListener(nsIPresentationSessionListener * aListener)248 PresentationSessionInfo::SetListener(nsIPresentationSessionListener* aListener)
249 {
250   mListener = aListener;
251 
252   if (mListener) {
253     // Enable data notification for the transport channel if it's available.
254     if (mTransport) {
255       nsresult rv = mTransport->EnableDataNotification();
256       if (NS_WARN_IF(NS_FAILED(rv))) {
257         return rv;
258       }
259     }
260 
261     // The transport might become ready, or might become un-ready again, before
262     // the listener has registered. So notify the listener of the state change.
263     return mListener->NotifyStateChange(mSessionId, mState, mReason);
264   }
265 
266   return NS_OK;
267 }
268 
269 nsresult
Send(const nsAString & aData)270 PresentationSessionInfo::Send(const nsAString& aData)
271 {
272   if (NS_WARN_IF(!IsSessionReady())) {
273     return NS_ERROR_DOM_INVALID_STATE_ERR;
274   }
275 
276   if (NS_WARN_IF(!mTransport)) {
277     return NS_ERROR_NOT_AVAILABLE;
278   }
279 
280   return mTransport->Send(aData);
281 }
282 
283 nsresult
SendBinaryMsg(const nsACString & aData)284 PresentationSessionInfo::SendBinaryMsg(const nsACString& aData)
285 {
286   if (NS_WARN_IF(!IsSessionReady())) {
287     return NS_ERROR_DOM_INVALID_STATE_ERR;
288   }
289 
290   if (NS_WARN_IF(!mTransport)) {
291     return NS_ERROR_NOT_AVAILABLE;
292   }
293 
294   return mTransport->SendBinaryMsg(aData);
295 }
296 
297 nsresult
SendBlob(nsIDOMBlob * aBlob)298 PresentationSessionInfo::SendBlob(nsIDOMBlob* aBlob)
299 {
300   if (NS_WARN_IF(!IsSessionReady())) {
301     return NS_ERROR_DOM_INVALID_STATE_ERR;
302   }
303 
304   if (NS_WARN_IF(!mTransport)) {
305     return NS_ERROR_NOT_AVAILABLE;
306   }
307 
308   return mTransport->SendBlob(aBlob);
309 }
310 
311 nsresult
Close(nsresult aReason,uint32_t aState)312 PresentationSessionInfo::Close(nsresult aReason,
313                                uint32_t aState)
314 {
315   // Do nothing if session is already terminated.
316   if (nsIPresentationSessionListener::STATE_TERMINATED == mState) {
317     return NS_OK;
318   }
319 
320   SetStateWithReason(aState, aReason);
321 
322   switch (aState) {
323     case nsIPresentationSessionListener::STATE_CLOSED: {
324       Shutdown(aReason);
325       break;
326     }
327     case nsIPresentationSessionListener::STATE_TERMINATED: {
328       if (!mControlChannel) {
329         nsCOMPtr<nsIPresentationControlChannel> ctrlChannel;
330         nsresult rv = mDevice->EstablishControlChannel(getter_AddRefs(ctrlChannel));
331         if (NS_FAILED(rv)) {
332           Shutdown(rv);
333           return rv;
334         }
335 
336         SetControlChannel(ctrlChannel);
337         return rv;
338       }
339 
340       ContinueTermination();
341       return NS_OK;
342     }
343   }
344 
345   return NS_OK;
346 }
347 
348 nsresult
OnTerminate(nsIPresentationControlChannel * aControlChannel)349 PresentationSessionInfo::OnTerminate(nsIPresentationControlChannel* aControlChannel)
350 {
351   mIsOnTerminating = true; // Mark for terminating transport channel
352   SetStateWithReason(nsIPresentationSessionListener::STATE_TERMINATED, NS_OK);
353   SetControlChannel(aControlChannel);
354 
355   return NS_OK;
356 }
357 
358 nsresult
ReplySuccess()359 PresentationSessionInfo::ReplySuccess()
360 {
361   SetStateWithReason(nsIPresentationSessionListener::STATE_CONNECTED, NS_OK);
362   return NS_OK;
363 }
364 
365 nsresult
ReplyError(nsresult aError)366 PresentationSessionInfo::ReplyError(nsresult aError)
367 {
368   Shutdown(aError);
369 
370   // Remove itself since it never succeeds.
371   return UntrackFromService();
372 }
373 
374 /* virtual */ nsresult
UntrackFromService()375 PresentationSessionInfo::UntrackFromService()
376 {
377   nsCOMPtr<nsIPresentationService> service =
378     do_GetService(PRESENTATION_SERVICE_CONTRACTID);
379   if (NS_WARN_IF(!service)) {
380     return NS_ERROR_NOT_AVAILABLE;
381   }
382   static_cast<PresentationService*>(service.get())->UntrackSessionInfo(mSessionId, mRole);
383 
384   return NS_OK;
385 }
386 
387 nsPIDOMWindowInner*
GetWindow()388 PresentationSessionInfo::GetWindow()
389 {
390   nsCOMPtr<nsIPresentationService> service =
391   do_GetService(PRESENTATION_SERVICE_CONTRACTID);
392   if (NS_WARN_IF(!service)) {
393     return nullptr;
394   }
395   uint64_t windowId = 0;
396   if (NS_WARN_IF(NS_FAILED(service->GetWindowIdBySessionId(mSessionId,
397                                                            mRole,
398                                                            &windowId)))) {
399     return nullptr;
400   }
401 
402   auto window = nsGlobalWindow::GetInnerWindowWithId(windowId);
403   if (!window) {
404     return nullptr;
405   }
406 
407   return window->AsInner();
408 }
409 
410 /* virtual */ bool
IsAccessible(base::ProcessId aProcessId)411 PresentationSessionInfo::IsAccessible(base::ProcessId aProcessId)
412 {
413   // No restriction by default.
414   return true;
415 }
416 
417 void
ContinueTermination()418 PresentationSessionInfo::ContinueTermination()
419 {
420   MOZ_ASSERT(NS_IsMainThread());
421   MOZ_ASSERT(mControlChannel);
422 
423   if (NS_WARN_IF(NS_FAILED(mControlChannel->Terminate(mSessionId)))
424       || mIsOnTerminating) {
425     Shutdown(NS_OK);
426   }
427 }
428 
429 // nsIPresentationSessionTransportCallback
430 NS_IMETHODIMP
NotifyTransportReady()431 PresentationSessionInfo::NotifyTransportReady()
432 {
433   PRES_DEBUG("%s:id[%s], role[%d], state[%d]\n", __func__,
434              NS_ConvertUTF16toUTF8(mSessionId).get(), mRole, mState);
435 
436   MOZ_ASSERT(NS_IsMainThread());
437 
438   if (mState != nsIPresentationSessionListener::STATE_CONNECTING &&
439       mState != nsIPresentationSessionListener::STATE_CONNECTED) {
440     return NS_OK;
441   }
442 
443   mIsTransportReady = true;
444 
445   // Established RTCDataChannel implies responder is ready.
446   if (mTransportType == nsIPresentationChannelDescription::TYPE_DATACHANNEL) {
447     mIsResponderReady = true;
448   }
449 
450   // At sender side, session might not be ready at this point (waiting for
451   // receiver's answer). Yet at receiver side, session must be ready at this
452   // point since the data transport channel is created after the receiver page
453   // is ready for presentation use.
454   if (IsSessionReady()) {
455     return ReplySuccess();
456   }
457 
458   return NS_OK;
459 }
460 
461 NS_IMETHODIMP
NotifyTransportClosed(nsresult aReason)462 PresentationSessionInfo::NotifyTransportClosed(nsresult aReason)
463 {
464   PRES_DEBUG("%s:id[%s], reason[%x], role[%d]\n", __func__,
465              NS_ConvertUTF16toUTF8(mSessionId).get(), aReason, mRole);
466 
467   MOZ_ASSERT(NS_IsMainThread());
468 
469   // Nullify |mTransport| here so it won't try to re-close |mTransport| in
470   // potential subsequent |Shutdown| calls.
471   mTransport = nullptr;
472 
473   if (NS_WARN_IF(!IsSessionReady() &&
474                  mState == nsIPresentationSessionListener::STATE_CONNECTING)) {
475     // It happens before the session is ready. Reply the callback.
476     return ReplyError(NS_ERROR_DOM_OPERATION_ERR);
477   }
478 
479   // Unset |mIsTransportReady| here so it won't affect |IsSessionReady()| above.
480   mIsTransportReady = false;
481 
482   if (mState == nsIPresentationSessionListener::STATE_CONNECTED) {
483     // The transport channel is closed unexpectedly (not caused by a |Close| call).
484     SetStateWithReason(nsIPresentationSessionListener::STATE_CLOSED, aReason);
485   }
486 
487   Shutdown(aReason);
488 
489   if (mState == nsIPresentationSessionListener::STATE_TERMINATED) {
490     // Directly untrack the session info from the service.
491     return UntrackFromService();
492   }
493 
494   return NS_OK;
495 }
496 
497 NS_IMETHODIMP
NotifyData(const nsACString & aData,bool aIsBinary)498 PresentationSessionInfo::NotifyData(const nsACString& aData, bool aIsBinary)
499 {
500   MOZ_ASSERT(NS_IsMainThread());
501 
502   if (NS_WARN_IF(!IsSessionReady())) {
503     return NS_ERROR_DOM_INVALID_STATE_ERR;
504   }
505 
506   if (NS_WARN_IF(!mListener)) {
507     return NS_ERROR_NOT_AVAILABLE;
508   }
509 
510   return mListener->NotifyMessage(mSessionId, aData, aIsBinary);
511 }
512 
513 // nsIPresentationSessionTransportBuilderListener
514 NS_IMETHODIMP
OnSessionTransport(nsIPresentationSessionTransport * aTransport)515 PresentationSessionInfo::OnSessionTransport(nsIPresentationSessionTransport* aTransport)
516 {
517   PRES_DEBUG("%s:id[%s], role[%d], state[%d]\n", __func__,
518              NS_ConvertUTF16toUTF8(mSessionId).get(), mRole, mState);
519 
520   ResetBuilder();
521 
522   if (mState != nsIPresentationSessionListener::STATE_CONNECTING) {
523     return NS_ERROR_FAILURE;
524   }
525 
526   if (NS_WARN_IF(!aTransport)) {
527     return NS_ERROR_INVALID_ARG;
528   }
529 
530   mTransport = aTransport;
531 
532   nsresult rv = mTransport->SetCallback(this);
533   if (NS_WARN_IF(NS_FAILED(rv))) {
534     return rv;
535   }
536 
537   if (mListener) {
538     mTransport->EnableDataNotification();
539   }
540 
541   return NS_OK;
542 }
543 
544 NS_IMETHODIMP
OnError(nsresult aReason)545 PresentationSessionInfo::OnError(nsresult aReason)
546 {
547   PRES_DEBUG("%s:id[%s], reason[%x], role[%d]\n", __func__,
548              NS_ConvertUTF16toUTF8(mSessionId).get(), aReason, mRole);
549 
550   ResetBuilder();
551   return ReplyError(aReason);
552 }
553 
554 NS_IMETHODIMP
SendOffer(nsIPresentationChannelDescription * aOffer)555 PresentationSessionInfo::SendOffer(nsIPresentationChannelDescription* aOffer)
556 {
557   return mControlChannel->SendOffer(aOffer);
558 }
559 
560 NS_IMETHODIMP
SendAnswer(nsIPresentationChannelDescription * aAnswer)561 PresentationSessionInfo::SendAnswer(nsIPresentationChannelDescription* aAnswer)
562 {
563   return mControlChannel->SendAnswer(aAnswer);
564 }
565 
566 NS_IMETHODIMP
SendIceCandidate(const nsAString & candidate)567 PresentationSessionInfo::SendIceCandidate(const nsAString& candidate)
568 {
569   return mControlChannel->SendIceCandidate(candidate);
570 }
571 
572 NS_IMETHODIMP
Close(nsresult reason)573 PresentationSessionInfo::Close(nsresult reason)
574 {
575   return mControlChannel->Disconnect(reason);
576 }
577 
578 /**
579  * Implementation of PresentationControllingInfo
580  *
581  * During presentation session establishment, the sender expects the following
582  * after trying to establish the control channel: (The order between step 3 and
583  * 4 is not guaranteed.)
584  * 1. |Init| is called to open a socket |mServerSocket| for data transport
585  *    channel.
586  * 2. |NotifyConnected| of |nsIPresentationControlChannelListener| is called to
587  *    indicate the control channel is ready to use. Then send the offer to the
588  *    receiver via the control channel.
589  * 3.1 |OnSocketAccepted| of |nsIServerSocketListener| is called to indicate the
590  *     data transport channel is connected. Then initialize |mTransport|.
591  * 3.2 |NotifyTransportReady| of |nsIPresentationSessionTransportCallback| is
592  *     called.
593  * 4. |OnAnswer| of |nsIPresentationControlChannelListener| is called to
594  *    indicate the receiver is ready. Close the control channel since it's no
595  *    longer needed.
596  * 5. Once both step 3 and 4 are done, the presentation session is ready to use.
597  *    So notify the listener of CONNECTED state.
598  */
599 
NS_IMPL_ISUPPORTS_INHERITED(PresentationControllingInfo,PresentationSessionInfo,nsIServerSocketListener)600 NS_IMPL_ISUPPORTS_INHERITED(PresentationControllingInfo,
601                             PresentationSessionInfo,
602                             nsIServerSocketListener)
603 
604 nsresult
605 PresentationControllingInfo::Init(nsIPresentationControlChannel* aControlChannel)
606 {
607   PresentationSessionInfo::Init(aControlChannel);
608 
609   // Initialize |mServerSocket| for bootstrapping the data transport channel and
610   // use |this| as the listener.
611   mServerSocket = do_CreateInstance(NS_SERVERSOCKET_CONTRACTID);
612   if (NS_WARN_IF(!mServerSocket)) {
613     return ReplyError(NS_ERROR_DOM_OPERATION_ERR);
614   }
615 
616   nsresult rv = mServerSocket->Init(-1, false, -1);
617   if (NS_WARN_IF(NS_FAILED(rv))) {
618     return rv;
619   }
620 
621   rv = mServerSocket->AsyncListen(this);
622   if (NS_WARN_IF(NS_FAILED(rv))) {
623     return rv;
624   }
625 
626   int32_t port;
627   rv = mServerSocket->GetPort(&port);
628   if (!NS_WARN_IF(NS_FAILED(rv))) {
629     PRES_DEBUG("%s:ServerSocket created.port[%d]\n",__func__, port);
630   }
631 
632   return NS_OK;
633 }
634 
635 void
Shutdown(nsresult aReason)636 PresentationControllingInfo::Shutdown(nsresult aReason)
637 {
638   PresentationSessionInfo::Shutdown(aReason);
639 
640   // Close the server socket if any.
641   if (mServerSocket) {
642     Unused << NS_WARN_IF(NS_FAILED(mServerSocket->Close()));
643     mServerSocket = nullptr;
644   }
645 }
646 
647 nsresult
GetAddress()648 PresentationControllingInfo::GetAddress()
649 {
650 #if defined(MOZ_WIDGET_GONK)
651   nsCOMPtr<nsINetworkManager> networkManager =
652     do_GetService("@mozilla.org/network/manager;1");
653   if (NS_WARN_IF(!networkManager)) {
654     return NS_ERROR_NOT_AVAILABLE;
655   }
656 
657   nsCOMPtr<nsINetworkInfo> activeNetworkInfo;
658   networkManager->GetActiveNetworkInfo(getter_AddRefs(activeNetworkInfo));
659   if (NS_WARN_IF(!activeNetworkInfo)) {
660     return NS_ERROR_FAILURE;
661   }
662 
663   char16_t** ips = nullptr;
664   uint32_t* prefixes = nullptr;
665   uint32_t count = 0;
666   activeNetworkInfo->GetAddresses(&ips, &prefixes, &count);
667   if (NS_WARN_IF(!count)) {
668     NS_Free(prefixes);
669     NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(count, ips);
670     return NS_ERROR_FAILURE;
671   }
672 
673   // TODO bug 1228504 Take all IP addresses in PresentationChannelDescription
674   // into account. And at the first stage Presentation API is only exposed on
675   // Firefox OS where the first IP appears enough for most scenarios.
676 
677   nsAutoString ip;
678   ip.Assign(ips[0]);
679 
680   // On Android platform, the IP address is retrieved from a callback function.
681   // To make consistent code sequence, following function call is dispatched
682   // into main thread instead of calling it directly.
683   NS_DispatchToMainThread(
684     NewRunnableMethod<nsCString>(
685       this,
686       &PresentationControllingInfo::OnGetAddress,
687       NS_ConvertUTF16toUTF8(ip)));
688 
689   NS_Free(prefixes);
690   NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(count, ips);
691 
692 #elif defined(MOZ_WIDGET_ANDROID)
693   RefPtr<PresentationNetworkHelper> networkHelper =
694     new PresentationNetworkHelper(this,
695                                   &PresentationControllingInfo::OnGetAddress);
696   nsresult rv = networkHelper->GetWifiIPAddress();
697   if (NS_WARN_IF(NS_FAILED(rv))) {
698     return rv;
699   }
700 
701 #else
702   nsCOMPtr<nsINetworkInfoService> networkInfo = do_GetService(NETWORKINFOSERVICE_CONTRACT_ID);
703   MOZ_ASSERT(networkInfo);
704 
705   nsresult rv = networkInfo->ListNetworkAddresses(this);
706 
707   if (NS_WARN_IF(NS_FAILED(rv))) {
708     return rv;
709   }
710 #endif
711 
712   return NS_OK;
713 }
714 
715 nsresult
OnGetAddress(const nsACString & aAddress)716 PresentationControllingInfo::OnGetAddress(const nsACString& aAddress)
717 {
718   MOZ_ASSERT(NS_IsMainThread());
719 
720   if (NS_WARN_IF(!mServerSocket)) {
721     return NS_ERROR_FAILURE;
722   }
723   if (NS_WARN_IF(!mControlChannel)) {
724     return NS_ERROR_FAILURE;
725   }
726 
727   // Prepare and send the offer.
728   int32_t port;
729   nsresult rv = mServerSocket->GetPort(&port);
730   if (NS_WARN_IF(NS_FAILED(rv))) {
731     return rv;
732   }
733 
734   RefPtr<TCPPresentationChannelDescription> description =
735     new TCPPresentationChannelDescription(aAddress, static_cast<uint16_t>(port));
736   return mControlChannel->SendOffer(description);
737 }
738 
739 // nsIPresentationControlChannelListener
740 NS_IMETHODIMP
OnIceCandidate(const nsAString & aCandidate)741 PresentationControllingInfo::OnIceCandidate(const nsAString& aCandidate)
742 {
743   if (mTransportType != nsIPresentationChannelDescription::TYPE_DATACHANNEL) {
744     return NS_ERROR_FAILURE;
745   }
746 
747   nsCOMPtr<nsIPresentationDataChannelSessionTransportBuilder>
748     builder = do_QueryInterface(mBuilder);
749 
750   if (NS_WARN_IF(!builder)) {
751     return NS_ERROR_FAILURE;
752   }
753 
754   return builder->OnIceCandidate(aCandidate);
755 }
756 
757 NS_IMETHODIMP
OnOffer(nsIPresentationChannelDescription * aDescription)758 PresentationControllingInfo::OnOffer(nsIPresentationChannelDescription* aDescription)
759 {
760   MOZ_ASSERT(false, "Sender side should not receive offer.");
761   return NS_ERROR_FAILURE;
762 }
763 
764 NS_IMETHODIMP
OnAnswer(nsIPresentationChannelDescription * aDescription)765 PresentationControllingInfo::OnAnswer(nsIPresentationChannelDescription* aDescription)
766 {
767   if (mTransportType == nsIPresentationChannelDescription::TYPE_DATACHANNEL) {
768     nsCOMPtr<nsIPresentationDataChannelSessionTransportBuilder>
769       builder = do_QueryInterface(mBuilder);
770 
771     if (NS_WARN_IF(!builder)) {
772       return NS_ERROR_FAILURE;
773     }
774 
775     return builder->OnAnswer(aDescription);
776   }
777 
778   mIsResponderReady = true;
779 
780   // Close the control channel since it's no longer needed.
781   nsresult rv = mControlChannel->Disconnect(NS_OK);
782   if (NS_WARN_IF(NS_FAILED(rv))) {
783     return ReplyError(NS_ERROR_DOM_OPERATION_ERR);
784   }
785 
786   // Session might not be ready at this moment (waiting for the establishment of
787   // the data transport channel).
788   if (IsSessionReady()){
789     return ReplySuccess();
790   }
791 
792   return NS_OK;
793 }
794 
795 NS_IMETHODIMP
NotifyConnected()796 PresentationControllingInfo::NotifyConnected()
797 {
798   PRES_DEBUG("%s:id[%s], role[%d]\n", __func__,
799              NS_ConvertUTF16toUTF8(mSessionId).get(), mRole);
800 
801   MOZ_ASSERT(NS_IsMainThread());
802 
803   switch (mState) {
804     case nsIPresentationSessionListener::STATE_CONNECTING: {
805       if (mIsReconnecting) {
806         return ContinueReconnect();
807       }
808 
809       nsresult rv = mControlChannel->Launch(GetSessionId(), GetUrl());
810       if (NS_WARN_IF(NS_FAILED(rv))) {
811         return rv;
812       }
813       Unused << NS_WARN_IF(NS_FAILED(BuildTransport()));
814       break;
815     }
816     case nsIPresentationSessionListener::STATE_TERMINATED: {
817       ContinueTermination();
818       break;
819     }
820     default:
821       break;
822   }
823 
824   return NS_OK;
825 }
826 
827 NS_IMETHODIMP
NotifyReconnected()828 PresentationControllingInfo::NotifyReconnected()
829 {
830   PRES_DEBUG("%s:id[%s], role[%d]\n", __func__,
831              NS_ConvertUTF16toUTF8(mSessionId).get(), mRole);
832 
833   MOZ_ASSERT(NS_IsMainThread());
834 
835   if (NS_WARN_IF(mState != nsIPresentationSessionListener::STATE_CONNECTING)) {
836     return NS_ERROR_FAILURE;
837   }
838 
839   return NotifyReconnectResult(NS_OK);
840 }
841 
842 nsresult
BuildTransport()843 PresentationControllingInfo::BuildTransport()
844 {
845   MOZ_ASSERT(NS_IsMainThread());
846 
847   if (mState != nsIPresentationSessionListener::STATE_CONNECTING) {
848     return NS_OK;
849   }
850 
851   if (NS_WARN_IF(!mBuilderConstructor)) {
852     return NS_ERROR_NOT_AVAILABLE;
853   }
854 
855   if (!Preferences::GetBool("dom.presentation.session_transport.data_channel.enable")) {
856     // Build TCP session transport
857     return GetAddress();
858   }
859   /**
860    * Generally transport is maintained by the chrome process. However, data
861    * channel should be live with the DOM , which implies RTCDataChannel in an OOP
862    * page should be establish in the content process.
863    *
864    * |mBuilderConstructor| is responsible for creating a builder, which is for
865    * building a data channel transport.
866    *
867    * In the OOP case, |mBuilderConstructor| would create a builder which is
868    * an object of |PresentationBuilderParent|. So, |BuildDataChannelTransport|
869    * triggers an IPC call to make content process establish a RTCDataChannel
870    * transport.
871    */
872 
873   mTransportType = nsIPresentationChannelDescription::TYPE_DATACHANNEL;
874   if (NS_WARN_IF(NS_FAILED(
875     mBuilderConstructor->CreateTransportBuilder(mTransportType,
876                                                 getter_AddRefs(mBuilder))))) {
877     return NS_ERROR_NOT_AVAILABLE;
878   }
879 
880   nsCOMPtr<nsIPresentationDataChannelSessionTransportBuilder>
881     dataChannelBuilder(do_QueryInterface(mBuilder));
882   if (NS_WARN_IF(!dataChannelBuilder)) {
883     return NS_ERROR_NOT_AVAILABLE;
884   }
885 
886   // OOP window would be set from content process
887   nsPIDOMWindowInner* window = GetWindow();
888 
889   nsresult rv = dataChannelBuilder->
890          BuildDataChannelTransport(nsIPresentationService::ROLE_CONTROLLER,
891                                    window,
892                                    this);
893   if (NS_WARN_IF(NS_FAILED(rv))) {
894     return rv;
895   }
896 
897   return NS_OK;
898 }
899 
900 NS_IMETHODIMP
NotifyDisconnected(nsresult aReason)901 PresentationControllingInfo::NotifyDisconnected(nsresult aReason)
902 {
903   PRES_DEBUG("%s:id[%s], reason[%x], role[%d]\n", __func__,
904              NS_ConvertUTF16toUTF8(mSessionId).get(), aReason, mRole);
905 
906   MOZ_ASSERT(NS_IsMainThread());
907 
908   if (mTransportType == nsIPresentationChannelDescription::TYPE_DATACHANNEL) {
909     nsCOMPtr<nsIPresentationDataChannelSessionTransportBuilder>
910       builder = do_QueryInterface(mBuilder);
911     if (builder) {
912       Unused << NS_WARN_IF(NS_FAILED(builder->NotifyDisconnected(aReason)));
913     }
914   }
915 
916   // Unset control channel here so it won't try to re-close it in potential
917   // subsequent |Shutdown| calls.
918   SetControlChannel(nullptr);
919 
920   if (NS_WARN_IF(NS_FAILED(aReason) || !mIsResponderReady)) {
921     // The presentation session instance may already exist.
922     // Change the state to CLOSED if it is not terminated.
923     if (nsIPresentationSessionListener::STATE_TERMINATED != mState) {
924       SetStateWithReason(nsIPresentationSessionListener::STATE_CLOSED, aReason);
925     }
926 
927     // If |aReason| is NS_OK, it implies that the user closes the connection
928     // before becomming connected. No need to call |ReplyError| in this case.
929     if (NS_FAILED(aReason)) {
930       if (mIsReconnecting) {
931         NotifyReconnectResult(NS_ERROR_DOM_OPERATION_ERR);
932       }
933       // Reply error for an abnormal close.
934       return ReplyError(NS_ERROR_DOM_OPERATION_ERR);
935     }
936     Shutdown(aReason);
937   }
938 
939   // This is the case for reconnecting a connection which is in
940   // connecting state and |mTransport| is not ready.
941   if (mDoReconnectAfterClose && !mTransport) {
942     mDoReconnectAfterClose = false;
943     return Reconnect(mReconnectCallback);
944   }
945 
946   return NS_OK;
947 }
948 
949 // nsIServerSocketListener
950 NS_IMETHODIMP
OnSocketAccepted(nsIServerSocket * aServerSocket,nsISocketTransport * aTransport)951 PresentationControllingInfo::OnSocketAccepted(nsIServerSocket* aServerSocket,
952                                             nsISocketTransport* aTransport)
953 {
954   int32_t port;
955   nsresult rv = aTransport->GetPort(&port);
956   if (!NS_WARN_IF(NS_FAILED(rv))) {
957     PRES_DEBUG("%s:receive from port[%d]\n",__func__, port);
958   }
959 
960   MOZ_ASSERT(NS_IsMainThread());
961 
962   if (NS_WARN_IF(!mBuilderConstructor)) {
963     return ReplyError(NS_ERROR_DOM_OPERATION_ERR);
964   }
965 
966   // Initialize session transport builder and use |this| as the callback.
967   nsCOMPtr<nsIPresentationTCPSessionTransportBuilder> builder;
968   if (NS_SUCCEEDED(mBuilderConstructor->CreateTransportBuilder(
969                      nsIPresentationChannelDescription::TYPE_TCP,
970                      getter_AddRefs(mBuilder)))) {
971     builder = do_QueryInterface(mBuilder);
972   }
973 
974   if (NS_WARN_IF(!builder)) {
975     return ReplyError(NS_ERROR_DOM_OPERATION_ERR);
976   }
977 
978   mTransportType = nsIPresentationChannelDescription::TYPE_TCP;
979   return builder->BuildTCPSenderTransport(aTransport, this);
980 }
981 
982 NS_IMETHODIMP
OnStopListening(nsIServerSocket * aServerSocket,nsresult aStatus)983 PresentationControllingInfo::OnStopListening(nsIServerSocket* aServerSocket,
984                                            nsresult aStatus)
985 {
986   PRES_DEBUG("controller %s:status[%x]\n",__func__, aStatus);
987 
988   MOZ_ASSERT(NS_IsMainThread());
989 
990   if (aStatus == NS_BINDING_ABORTED) { // The server socket was manually closed.
991     return NS_OK;
992   }
993 
994   Shutdown(aStatus);
995 
996   if (NS_WARN_IF(!IsSessionReady())) {
997     // It happens before the session is ready. Reply the callback.
998     return ReplyError(NS_ERROR_DOM_OPERATION_ERR);
999   }
1000 
1001   // It happens after the session is ready. Change the state to CLOSED.
1002   SetStateWithReason(nsIPresentationSessionListener::STATE_CLOSED, aStatus);
1003 
1004   return NS_OK;
1005 }
1006 
1007 /**
1008  * The steps to reconnect a session are summarized below:
1009  * 1. Change |mState| to CONNECTING.
1010  * 2. Check whether |mControlChannel| is existed or not. Usually we have to
1011  *    create a new control cahnnel.
1012  * 3.1 |mControlChannel| is null, which means we have to create a new one.
1013  *     |EstablishControlChannel| is called to create a new control channel.
1014  *     At this point, |mControlChannel| is not able to use yet. Set
1015  *     |mIsReconnecting| to true and wait until |NotifyConnected|.
1016  * 3.2 |mControlChannel| is not null and is avaliable.
1017  *     We can just call |ContinueReconnect| to send reconnect command.
1018  * 4. |NotifyReconnected| of |nsIPresentationControlChannelListener| is called
1019  *    to indicate the receiver is ready for reconnecting.
1020  * 5. Once both step 3 and 4 are done, the rest is to build a new data
1021  *    transport channel by following the same steps as starting a
1022  *    new session.
1023  */
1024 
1025 nsresult
Reconnect(nsIPresentationServiceCallback * aCallback)1026 PresentationControllingInfo::Reconnect(nsIPresentationServiceCallback* aCallback)
1027 {
1028   PRES_DEBUG("%s:id[%s], role[%d], state[%d]\n", __func__,
1029              NS_ConvertUTF16toUTF8(mSessionId).get(), mRole, mState);
1030 
1031   if (!aCallback) {
1032     return NS_ERROR_INVALID_ARG;
1033   }
1034 
1035   mReconnectCallback = aCallback;
1036 
1037   if (NS_WARN_IF(mState == nsIPresentationSessionListener::STATE_TERMINATED)) {
1038     return NotifyReconnectResult(NS_ERROR_DOM_INVALID_STATE_ERR);
1039   }
1040 
1041   // If |mState| is not CLOSED, we have to close the connection before
1042   // reconnecting. The process to reconnect will be continued after
1043   // |NotifyDisconnected| or |NotifyTransportClosed| is invoked.
1044   if (mState == nsIPresentationSessionListener::STATE_CONNECTING ||
1045       mState == nsIPresentationSessionListener::STATE_CONNECTED) {
1046     mDoReconnectAfterClose = true;
1047     return Close(NS_OK, nsIPresentationSessionListener::STATE_CLOSED);
1048   }
1049 
1050   // Make sure |mState| is closed at this point.
1051   MOZ_ASSERT(mState == nsIPresentationSessionListener::STATE_CLOSED);
1052 
1053   mState = nsIPresentationSessionListener::STATE_CONNECTING;
1054   mIsReconnecting = true;
1055 
1056   nsresult rv = NS_OK;
1057   if (!mControlChannel) {
1058     nsCOMPtr<nsIPresentationControlChannel> ctrlChannel;
1059     rv = mDevice->EstablishControlChannel(getter_AddRefs(ctrlChannel));
1060     if (NS_WARN_IF(NS_FAILED(rv))) {
1061       return NotifyReconnectResult(NS_ERROR_DOM_OPERATION_ERR);
1062     }
1063 
1064     rv = Init(ctrlChannel);
1065     if (NS_WARN_IF(NS_FAILED(rv))) {
1066       return NotifyReconnectResult(NS_ERROR_DOM_OPERATION_ERR);
1067     }
1068   } else {
1069     return ContinueReconnect();
1070   }
1071 
1072   return NS_OK;
1073 }
1074 
1075 nsresult
ContinueReconnect()1076 PresentationControllingInfo::ContinueReconnect()
1077 {
1078   MOZ_ASSERT(NS_IsMainThread());
1079   MOZ_ASSERT(mControlChannel);
1080 
1081   mIsReconnecting = false;
1082   if (NS_WARN_IF(NS_FAILED(mControlChannel->Reconnect(mSessionId, GetUrl())))) {
1083     return NotifyReconnectResult(NS_ERROR_DOM_OPERATION_ERR);
1084   }
1085 
1086   return NS_OK;
1087 }
1088 
1089 // nsIListNetworkAddressesListener
1090 NS_IMETHODIMP
OnListedNetworkAddresses(const char ** aAddressArray,uint32_t aAddressArraySize)1091 PresentationControllingInfo::OnListedNetworkAddresses(const char** aAddressArray,
1092                                                       uint32_t aAddressArraySize)
1093 {
1094   if (!aAddressArraySize) {
1095     return OnListNetworkAddressesFailed();
1096   }
1097 
1098   // TODO bug 1228504 Take all IP addresses in PresentationChannelDescription
1099   // into account. And at the first stage Presentation API is only exposed on
1100   // Firefox OS where the first IP appears enough for most scenarios.
1101 
1102   nsAutoCString ip;
1103   ip.Assign(aAddressArray[0]);
1104 
1105   // On Firefox desktop, the IP address is retrieved from a callback function.
1106   // To make consistent code sequence, following function call is dispatched
1107   // into main thread instead of calling it directly.
1108   NS_DispatchToMainThread(
1109     NewRunnableMethod<nsCString>(
1110       this,
1111       &PresentationControllingInfo::OnGetAddress,
1112       ip));
1113 
1114   return NS_OK;
1115 }
1116 
1117 NS_IMETHODIMP
OnListNetworkAddressesFailed()1118 PresentationControllingInfo::OnListNetworkAddressesFailed()
1119 {
1120   PRES_ERROR("PresentationControllingInfo:OnListNetworkAddressesFailed");
1121 
1122   // In 1-UA case, transport channel can still be established
1123   // on loopback interface even if no network address available.
1124   NS_DispatchToMainThread(
1125     NewRunnableMethod<nsCString>(
1126       this,
1127       &PresentationControllingInfo::OnGetAddress,
1128       "127.0.0.1"));
1129 
1130   return NS_OK;
1131 }
1132 
1133 nsresult
NotifyReconnectResult(nsresult aStatus)1134 PresentationControllingInfo::NotifyReconnectResult(nsresult aStatus)
1135 {
1136   if (!mReconnectCallback) {
1137     MOZ_ASSERT(false, "mReconnectCallback can not be null here.");
1138     return NS_ERROR_FAILURE;
1139   }
1140 
1141   mIsReconnecting = false;
1142   nsCOMPtr<nsIPresentationServiceCallback> callback =
1143     mReconnectCallback.forget();
1144   if (NS_FAILED(aStatus)) {
1145     return callback->NotifyError(aStatus);
1146   }
1147 
1148   return callback->NotifySuccess(GetUrl());
1149 }
1150 
1151 // nsIPresentationSessionTransportCallback
1152 NS_IMETHODIMP
NotifyTransportReady()1153 PresentationControllingInfo::NotifyTransportReady()
1154 {
1155   return PresentationSessionInfo::NotifyTransportReady();
1156 }
1157 
1158 NS_IMETHODIMP
NotifyTransportClosed(nsresult aReason)1159 PresentationControllingInfo::NotifyTransportClosed(nsresult aReason)
1160 {
1161   if (!mDoReconnectAfterClose) {
1162     return PresentationSessionInfo::NotifyTransportClosed(aReason);;
1163   }
1164 
1165   MOZ_ASSERT(mState == nsIPresentationSessionListener::STATE_CLOSED);
1166 
1167   mTransport = nullptr;
1168   mIsTransportReady = false;
1169   mDoReconnectAfterClose = false;
1170   return Reconnect(mReconnectCallback);
1171 }
1172 
1173 NS_IMETHODIMP
NotifyData(const nsACString & aData,bool aIsBinary)1174 PresentationControllingInfo::NotifyData(const nsACString& aData, bool aIsBinary)
1175 {
1176   return PresentationSessionInfo::NotifyData(aData, aIsBinary);
1177 }
1178 
1179 /**
1180  * Implementation of PresentationPresentingInfo
1181  *
1182  * During presentation session establishment, the receiver expects the following
1183  * after trying to launch the app by notifying "presentation-launch-receiver":
1184  * (The order between step 2 and 3 is not guaranteed.)
1185  * 1. |Observe| of |nsIObserver| is called with "presentation-receiver-launched".
1186  *    Then start listen to document |STATE_TRANSFERRING| event.
1187  * 2. |NotifyResponderReady| is called to indicate the receiver page is ready
1188  *    for presentation use.
1189  * 3. |OnOffer| of |nsIPresentationControlChannelListener| is called.
1190  * 4. Once both step 2 and 3 are done, establish the data transport channel and
1191  *    send the answer. (The control channel will be closed by the sender once it
1192  *    receives the answer.)
1193  * 5. |NotifyTransportReady| of |nsIPresentationSessionTransportCallback| is
1194  *    called. The presentation session is ready to use, so notify the listener
1195  *    of CONNECTED state.
1196  */
1197 
NS_IMPL_ISUPPORTS_INHERITED(PresentationPresentingInfo,PresentationSessionInfo,nsITimerCallback)1198 NS_IMPL_ISUPPORTS_INHERITED(PresentationPresentingInfo,
1199                             PresentationSessionInfo,
1200                             nsITimerCallback)
1201 
1202 nsresult
1203 PresentationPresentingInfo::Init(nsIPresentationControlChannel* aControlChannel)
1204 {
1205   PresentationSessionInfo::Init(aControlChannel);
1206 
1207   // Add a timer to prevent waiting indefinitely in case the receiver page fails
1208   // to become ready.
1209   nsresult rv;
1210   int32_t timeout =
1211     Preferences::GetInt("presentation.receiver.loading.timeout", 10000);
1212   mTimer = do_CreateInstance(NS_TIMER_CONTRACTID, &rv);
1213   if (NS_WARN_IF(NS_FAILED(rv))) {
1214     return rv;
1215   }
1216   rv = mTimer->InitWithCallback(this, timeout, nsITimer::TYPE_ONE_SHOT);
1217   if (NS_WARN_IF(NS_FAILED(rv))) {
1218     return rv;
1219   }
1220 
1221   return NS_OK;
1222 }
1223 
1224 void
Shutdown(nsresult aReason)1225 PresentationPresentingInfo::Shutdown(nsresult aReason)
1226 {
1227   PresentationSessionInfo::Shutdown(aReason);
1228 
1229   if (mTimer) {
1230     mTimer->Cancel();
1231   }
1232 
1233   mLoadingCallback = nullptr;
1234   mRequesterDescription = nullptr;
1235   mPendingCandidates.Clear();
1236   mPromise = nullptr;
1237   mHasFlushPendingEvents = false;
1238 }
1239 
1240 // nsIPresentationSessionTransportBuilderListener
1241 NS_IMETHODIMP
OnSessionTransport(nsIPresentationSessionTransport * aTransport)1242 PresentationPresentingInfo::OnSessionTransport(nsIPresentationSessionTransport* aTransport)
1243 {
1244   nsresult rv = PresentationSessionInfo::OnSessionTransport(aTransport);
1245 
1246   if (NS_WARN_IF(NS_FAILED(rv))) {
1247     return rv;
1248   }
1249 
1250   // The session transport is managed by content process
1251   if (NS_WARN_IF(!aTransport)) {
1252     return NS_ERROR_INVALID_ARG;
1253   }
1254 
1255   // send answer for TCP session transport
1256   if (mTransportType == nsIPresentationChannelDescription::TYPE_TCP) {
1257     // Prepare and send the answer.
1258     // In the current implementation of |PresentationSessionTransport|,
1259     // |GetSelfAddress| cannot return the real info when it's initialized via
1260     // |buildTCPReceiverTransport|. Yet this deficiency only affects the channel
1261     // description for the answer, which is not actually checked at requester side.
1262     nsCOMPtr<nsINetAddr> selfAddr;
1263     rv = mTransport->GetSelfAddress(getter_AddRefs(selfAddr));
1264     NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "GetSelfAddress failed");
1265 
1266     nsCString address;
1267     uint16_t port = 0;
1268     if (NS_SUCCEEDED(rv)) {
1269       selfAddr->GetAddress(address);
1270       selfAddr->GetPort(&port);
1271     }
1272     nsCOMPtr<nsIPresentationChannelDescription> description =
1273       new TCPPresentationChannelDescription(address, port);
1274 
1275     return mControlChannel->SendAnswer(description);
1276   }
1277 
1278   return NS_OK;
1279 }
1280 
1281 // Delegate the pending offer and ICE candidates to builder.
1282 NS_IMETHODIMP
FlushPendingEvents(nsIPresentationDataChannelSessionTransportBuilder * builder)1283 PresentationPresentingInfo::FlushPendingEvents(nsIPresentationDataChannelSessionTransportBuilder* builder)
1284 {
1285   if (NS_WARN_IF(!builder)) {
1286     return NS_ERROR_FAILURE;
1287   }
1288 
1289   mHasFlushPendingEvents = true;
1290 
1291   if (mRequesterDescription) {
1292     builder->OnOffer(mRequesterDescription);
1293   }
1294   mRequesterDescription = nullptr;
1295 
1296   for (size_t i = 0; i < mPendingCandidates.Length(); ++i) {
1297     builder->OnIceCandidate(mPendingCandidates[i]);
1298   }
1299   mPendingCandidates.Clear();
1300   return NS_OK;
1301 }
1302 
1303 nsresult
InitTransportAndSendAnswer()1304 PresentationPresentingInfo::InitTransportAndSendAnswer()
1305 {
1306   MOZ_ASSERT(NS_IsMainThread());
1307   MOZ_ASSERT(mState == nsIPresentationSessionListener::STATE_CONNECTING);
1308 
1309   uint8_t type = 0;
1310   nsresult rv = mRequesterDescription->GetType(&type);
1311   if (NS_WARN_IF(NS_FAILED(rv))) {
1312     return rv;
1313   }
1314 
1315   if (NS_WARN_IF(!mBuilderConstructor)) {
1316     return ReplyError(NS_ERROR_DOM_OPERATION_ERR);
1317   }
1318 
1319   if (NS_WARN_IF(NS_FAILED(
1320     mBuilderConstructor->CreateTransportBuilder(type,
1321                                                 getter_AddRefs(mBuilder))))) {
1322     return NS_ERROR_NOT_AVAILABLE;
1323   }
1324 
1325   if (type == nsIPresentationChannelDescription::TYPE_TCP) {
1326     // Establish a data transport channel |mTransport| to the sender and use
1327     // |this| as the callback.
1328     nsCOMPtr<nsIPresentationTCPSessionTransportBuilder> builder =
1329       do_QueryInterface(mBuilder);
1330     if (NS_WARN_IF(!builder)) {
1331       return NS_ERROR_NOT_AVAILABLE;
1332     }
1333 
1334     mTransportType = nsIPresentationChannelDescription::TYPE_TCP;
1335     return builder->BuildTCPReceiverTransport(mRequesterDescription, this);
1336   }
1337 
1338   if (type == nsIPresentationChannelDescription::TYPE_DATACHANNEL) {
1339     if (!Preferences::GetBool("dom.presentation.session_transport.data_channel.enable")) {
1340       return NS_ERROR_NOT_IMPLEMENTED;
1341     }
1342     /**
1343      * Generally transport is maintained by the chrome process. However, data
1344      * channel should be live with the DOM , which implies RTCDataChannel in an OOP
1345      * page should be establish in the content process.
1346      *
1347      * |mBuilderConstructor| is responsible for creating a builder, which is for
1348      * building a data channel transport.
1349      *
1350      * In the OOP case, |mBuilderConstructor| would create a builder which is
1351      * an object of |PresentationBuilderParent|. So, |BuildDataChannelTransport|
1352      * triggers an IPC call to make content process establish a RTCDataChannel
1353      * transport.
1354      */
1355 
1356     mTransportType = nsIPresentationChannelDescription::TYPE_DATACHANNEL;
1357 
1358     nsCOMPtr<nsIPresentationDataChannelSessionTransportBuilder> dataChannelBuilder =
1359       do_QueryInterface(mBuilder);
1360     if (NS_WARN_IF(!dataChannelBuilder)) {
1361       return NS_ERROR_NOT_AVAILABLE;
1362     }
1363 
1364     nsPIDOMWindowInner* window = GetWindow();
1365 
1366     rv = dataChannelBuilder->
1367            BuildDataChannelTransport(nsIPresentationService::ROLE_RECEIVER,
1368                                      window,
1369                                      this);
1370     if (NS_WARN_IF(NS_FAILED(rv))) {
1371       return rv;
1372     }
1373 
1374     rv = FlushPendingEvents(dataChannelBuilder);
1375     if (NS_WARN_IF(NS_FAILED(rv))) {
1376       return rv;
1377     }
1378 
1379     return NS_OK;
1380   }
1381 
1382   MOZ_ASSERT(false, "Unknown nsIPresentationChannelDescription type!");
1383   return NS_ERROR_UNEXPECTED;
1384 }
1385 
1386 nsresult
UntrackFromService()1387 PresentationPresentingInfo::UntrackFromService()
1388 {
1389   // Remove the OOP responding info (if it has never been used).
1390   if (mContentParent) {
1391     Unused << NS_WARN_IF(!static_cast<ContentParent*>(mContentParent.get())->SendNotifyPresentationReceiverCleanUp(mSessionId));
1392   }
1393 
1394   // Receiver device might need clean up after session termination.
1395   if (mDevice) {
1396     mDevice->Disconnect();
1397   }
1398   mDevice = nullptr;
1399 
1400   // Remove the session info (and the in-process responding info if there's any).
1401   nsCOMPtr<nsIPresentationService> service =
1402     do_GetService(PRESENTATION_SERVICE_CONTRACTID);
1403   if (NS_WARN_IF(!service)) {
1404     return NS_ERROR_NOT_AVAILABLE;
1405   }
1406   static_cast<PresentationService*>(service.get())->UntrackSessionInfo(mSessionId, mRole);
1407 
1408   return NS_OK;
1409 }
1410 
1411 bool
IsAccessible(base::ProcessId aProcessId)1412 PresentationPresentingInfo::IsAccessible(base::ProcessId aProcessId)
1413 {
1414   // Only the specific content process should access the responder info.
1415   return (mContentParent) ?
1416           aProcessId == static_cast<ContentParent*>(mContentParent.get())->OtherPid() :
1417           false;
1418 }
1419 
1420 nsresult
NotifyResponderReady()1421 PresentationPresentingInfo::NotifyResponderReady()
1422 {
1423   PRES_DEBUG("%s:id[%s], role[%d], state[%d]\n", __func__,
1424              NS_ConvertUTF16toUTF8(mSessionId).get(), mRole, mState);
1425 
1426   if (mTimer) {
1427     mTimer->Cancel();
1428     mTimer = nullptr;
1429   }
1430 
1431   mIsResponderReady = true;
1432 
1433   // Initialize |mTransport| and send the answer to the sender if sender's
1434   // description is already offered.
1435   if (mRequesterDescription) {
1436     nsresult rv = InitTransportAndSendAnswer();
1437     if (NS_WARN_IF(NS_FAILED(rv))) {
1438       return ReplyError(NS_ERROR_DOM_OPERATION_ERR);
1439     }
1440   }
1441 
1442   return NS_OK;
1443 }
1444 
1445 nsresult
NotifyResponderFailure()1446 PresentationPresentingInfo::NotifyResponderFailure()
1447 {
1448   PRES_DEBUG("%s:id[%s], role[%d]\n", __func__,
1449              NS_ConvertUTF16toUTF8(mSessionId).get(), mRole);
1450 
1451   if (mTimer) {
1452     mTimer->Cancel();
1453     mTimer = nullptr;
1454   }
1455 
1456   return ReplyError(NS_ERROR_DOM_OPERATION_ERR);
1457 }
1458 
1459 nsresult
DoReconnect()1460 PresentationPresentingInfo::DoReconnect()
1461 {
1462   PRES_DEBUG("%s:id[%s], role[%d]\n", __func__,
1463              NS_ConvertUTF16toUTF8(mSessionId).get(), mRole);
1464 
1465   MOZ_ASSERT(mState == nsIPresentationSessionListener::STATE_CLOSED);
1466 
1467   SetStateWithReason(nsIPresentationSessionListener::STATE_CONNECTING, NS_OK);
1468 
1469   return NotifyResponderReady();
1470 }
1471 
1472 // nsIPresentationControlChannelListener
1473 NS_IMETHODIMP
OnOffer(nsIPresentationChannelDescription * aDescription)1474 PresentationPresentingInfo::OnOffer(nsIPresentationChannelDescription* aDescription)
1475 {
1476   if (NS_WARN_IF(mHasFlushPendingEvents)) {
1477     return ReplyError(NS_ERROR_DOM_OPERATION_ERR);
1478   }
1479 
1480   if (NS_WARN_IF(!aDescription)) {
1481     return ReplyError(NS_ERROR_DOM_OPERATION_ERR);
1482   }
1483 
1484   mRequesterDescription = aDescription;
1485 
1486   // Initialize |mTransport| and send the answer to the sender if the receiver
1487   // page is ready for presentation use.
1488   if (mIsResponderReady) {
1489     nsresult rv = InitTransportAndSendAnswer();
1490     if (NS_WARN_IF(NS_FAILED(rv))) {
1491       return ReplyError(NS_ERROR_DOM_OPERATION_ERR);
1492     }
1493   }
1494 
1495   return NS_OK;
1496 }
1497 
1498 NS_IMETHODIMP
OnAnswer(nsIPresentationChannelDescription * aDescription)1499 PresentationPresentingInfo::OnAnswer(nsIPresentationChannelDescription* aDescription)
1500 {
1501   MOZ_ASSERT(false, "Receiver side should not receive answer.");
1502   return NS_ERROR_FAILURE;
1503 }
1504 
1505 NS_IMETHODIMP
OnIceCandidate(const nsAString & aCandidate)1506 PresentationPresentingInfo::OnIceCandidate(const nsAString& aCandidate)
1507 {
1508   if (!mBuilder && !mHasFlushPendingEvents) {
1509     mPendingCandidates.AppendElement(nsString(aCandidate));
1510     return NS_OK;
1511   }
1512 
1513   if (NS_WARN_IF(!mBuilder && mHasFlushPendingEvents)) {
1514     return NS_ERROR_FAILURE;
1515   }
1516 
1517   nsCOMPtr<nsIPresentationDataChannelSessionTransportBuilder>
1518     builder = do_QueryInterface(mBuilder);
1519 
1520   return builder->OnIceCandidate(aCandidate);
1521 }
1522 
1523 NS_IMETHODIMP
NotifyConnected()1524 PresentationPresentingInfo::NotifyConnected()
1525 {
1526   PRES_DEBUG("%s:id[%s], role[%d]\n", __func__,
1527              NS_ConvertUTF16toUTF8(mSessionId).get(), mRole);
1528 
1529   if (nsIPresentationSessionListener::STATE_TERMINATED == mState) {
1530     ContinueTermination();
1531   }
1532 
1533   return NS_OK;
1534 }
1535 
1536 NS_IMETHODIMP
NotifyReconnected()1537 PresentationPresentingInfo::NotifyReconnected()
1538 {
1539   MOZ_ASSERT(false, "NotifyReconnected should not be called at receiver side.");
1540   return NS_OK;
1541 }
1542 
1543 NS_IMETHODIMP
NotifyDisconnected(nsresult aReason)1544 PresentationPresentingInfo::NotifyDisconnected(nsresult aReason)
1545 {
1546   PRES_DEBUG("%s:id[%s], reason[%x], role[%d]\n", __func__,
1547              NS_ConvertUTF16toUTF8(mSessionId).get(), aReason, mRole);
1548 
1549   MOZ_ASSERT(NS_IsMainThread());
1550 
1551   if (mTransportType == nsIPresentationChannelDescription::TYPE_DATACHANNEL) {
1552     nsCOMPtr<nsIPresentationDataChannelSessionTransportBuilder>
1553       builder = do_QueryInterface(mBuilder);
1554     if (builder) {
1555       Unused << NS_WARN_IF(NS_FAILED(builder->NotifyDisconnected(aReason)));
1556     }
1557   }
1558 
1559   // Unset control channel here so it won't try to re-close it in potential
1560   // subsequent |Shutdown| calls.
1561   SetControlChannel(nullptr);
1562 
1563   if (NS_WARN_IF(NS_FAILED(aReason))) {
1564     // The presentation session instance may already exist.
1565     // Change the state to TERMINATED since it never succeeds.
1566     SetStateWithReason(nsIPresentationSessionListener::STATE_TERMINATED, aReason);
1567 
1568     // Reply error for an abnormal close.
1569     return ReplyError(NS_ERROR_DOM_OPERATION_ERR);
1570   }
1571 
1572   return NS_OK;
1573 }
1574 
1575 // nsITimerCallback
1576 NS_IMETHODIMP
Notify(nsITimer * aTimer)1577 PresentationPresentingInfo::Notify(nsITimer* aTimer)
1578 {
1579   MOZ_ASSERT(NS_IsMainThread());
1580   NS_WARNING("The receiver page fails to become ready before timeout.");
1581 
1582   mTimer = nullptr;
1583   return ReplyError(NS_ERROR_DOM_TIMEOUT_ERR);
1584 }
1585 
1586 // PromiseNativeHandler
1587 void
ResolvedCallback(JSContext * aCx,JS::Handle<JS::Value> aValue)1588 PresentationPresentingInfo::ResolvedCallback(JSContext* aCx,
1589                                              JS::Handle<JS::Value> aValue)
1590 {
1591   MOZ_ASSERT(NS_IsMainThread());
1592 
1593   if (NS_WARN_IF(!aValue.isObject())) {
1594     ReplyError(NS_ERROR_DOM_OPERATION_ERR);
1595     return;
1596   }
1597 
1598   JS::Rooted<JSObject*> obj(aCx, &aValue.toObject());
1599   if (NS_WARN_IF(!obj)) {
1600     ReplyError(NS_ERROR_DOM_OPERATION_ERR);
1601     return;
1602   }
1603 
1604   // Start to listen to document state change event |STATE_TRANSFERRING|.
1605   // Use Element to support both HTMLIFrameElement and nsXULElement.
1606   Element* frame = nullptr;
1607   nsresult rv = UNWRAP_OBJECT(Element, &obj, frame);
1608   if (NS_WARN_IF(!frame)) {
1609     ReplyError(NS_ERROR_DOM_OPERATION_ERR);
1610     return;
1611   }
1612 
1613   nsCOMPtr<nsIFrameLoaderOwner> owner = do_QueryInterface((nsIFrameLoaderOwner*) frame);
1614   if (NS_WARN_IF(!owner)) {
1615     ReplyError(NS_ERROR_DOM_OPERATION_ERR);
1616     return;
1617   }
1618 
1619   nsCOMPtr<nsIFrameLoader> frameLoader = owner->GetFrameLoader();
1620   if (NS_WARN_IF(!frameLoader)) {
1621     ReplyError(NS_ERROR_DOM_OPERATION_ERR);
1622     return;
1623   }
1624 
1625   RefPtr<TabParent> tabParent = TabParent::GetFrom(frameLoader);
1626   if (tabParent) {
1627     // OOP frame
1628     // Notify the content process that a receiver page has launched, so it can
1629     // start monitoring the loading progress.
1630     mContentParent = tabParent->Manager();
1631     Unused << NS_WARN_IF(!static_cast<ContentParent*>(mContentParent.get())->SendNotifyPresentationReceiverLaunched(tabParent, mSessionId));
1632   } else {
1633     // In-process frame
1634     nsCOMPtr<nsIDocShell> docShell;
1635     rv = frameLoader->GetDocShell(getter_AddRefs(docShell));
1636     if (NS_WARN_IF(NS_FAILED(rv))) {
1637       ReplyError(NS_ERROR_DOM_OPERATION_ERR);
1638       return;
1639     }
1640 
1641     // Keep an eye on the loading progress of the receiver page.
1642     mLoadingCallback = new PresentationResponderLoadingCallback(mSessionId);
1643     rv = mLoadingCallback->Init(docShell);
1644     if (NS_WARN_IF(NS_FAILED(rv))) {
1645       ReplyError(NS_ERROR_DOM_OPERATION_ERR);
1646       return;
1647     }
1648   }
1649 }
1650 
1651 void
RejectedCallback(JSContext * aCx,JS::Handle<JS::Value> aValue)1652 PresentationPresentingInfo::RejectedCallback(JSContext* aCx,
1653                                              JS::Handle<JS::Value> aValue)
1654 {
1655   MOZ_ASSERT(NS_IsMainThread());
1656   NS_WARNING("Launching the receiver page has been rejected.");
1657 
1658   if (mTimer) {
1659     mTimer->Cancel();
1660     mTimer = nullptr;
1661   }
1662 
1663   ReplyError(NS_ERROR_DOM_OPERATION_ERR);
1664 }
1665