diff --git a/application/palemoon/components/nsBrowserGlue.js b/application/palemoon/components/nsBrowserGlue.js index d8bc5be7e7..df63513dfe 100644 --- a/application/palemoon/components/nsBrowserGlue.js +++ b/application/palemoon/components/nsBrowserGlue.js @@ -1585,18 +1585,29 @@ BrowserGlue.prototype = { const SMART_BOOKMARKS_VERSION = 4; const SMART_BOOKMARKS_ANNO = "Places/SmartBookmark"; const SMART_BOOKMARKS_PREF = "browser.places.smartBookmarksVersion"; + const SMART_BOOKMARKS_MAX_PREF = "browser.places.smartBookmarks.max"; + const SMART_BOOKMARKS_OLDMAX_PREF = "browser.places.smartBookmarks.old-max"; - // TODO bug 399268: should this be a pref? - const MAX_RESULTS = 10; + const MAX_RESULTS = Services.prefs.getIntPref(SMART_BOOKMARKS_MAX_PREF, 10); + let OLD_MAX_RESULTS = Services.prefs.getIntPref(SMART_BOOKMARKS_OLDMAX_PREF, 10); // Get current smart bookmarks version. If not set, create them. let smartBookmarksCurrentVersion = Services.prefs.getIntPref(SMART_BOOKMARKS_PREF, 0); - // If version is current or smart bookmarks are disabled, just bail out. + // If version is current and max hasn't changed or smart bookmarks are disabled, just bail out. if (smartBookmarksCurrentVersion == -1 || - smartBookmarksCurrentVersion >= SMART_BOOKMARKS_VERSION) { + (smartBookmarksCurrentVersion >= SMART_BOOKMARKS_VERSION && + OLD_MAX_RESULTS == MAX_RESULTS)) { return; } + + // We're going to recreate the smart bookmarks and set the current max, so store it. + if (Services.prefs.prefHasUserValue(SMART_BOOKMARKS_MAX_PREF)) { + Services.prefs.setIntPref(SMART_BOOKMARKS_OLDMAX_PREF, MAX_RESULTS); + } else { + // The max value is default, no need to track the temp value. + Services.prefs.clearUserPref(SMART_BOOKMARKS_OLDMAX_PREF); + } let batch = { runBatched: function BG_EPDQI_runBatched() { diff --git a/dom/base/Navigator.cpp b/dom/base/Navigator.cpp index 1433f32571..a544f23c10 100644 --- a/dom/base/Navigator.cpp +++ b/dom/base/Navigator.cpp @@ -37,8 +37,6 @@ #include "mozilla/dom/PowerManager.h" #include "mozilla/dom/WakeLock.h" #include "mozilla/dom/power/PowerManagerService.h" -#include "mozilla/dom/FlyWebPublishedServer.h" -#include "mozilla/dom/FlyWebService.h" #include "mozilla/dom/Permissions.h" #include "mozilla/dom/ServiceWorkerContainer.h" #include "mozilla/dom/StorageManager.h" @@ -1356,41 +1354,6 @@ Navigator::GetBattery(ErrorResult& aRv) return mBatteryPromise; } -already_AddRefed -Navigator::PublishServer(const nsAString& aName, - const FlyWebPublishOptions& aOptions, - ErrorResult& aRv) -{ - RefPtr service = FlyWebService::GetOrCreate(); - if (!service) { - aRv.Throw(NS_ERROR_FAILURE); - return nullptr; - } - - RefPtr mozPromise = - service->PublishServer(aName, aOptions, mWindow); - MOZ_ASSERT(mozPromise); - - nsCOMPtr global = do_QueryInterface(mWindow); - ErrorResult result; - RefPtr domPromise = Promise::Create(global, result); - if (result.Failed()) { - aRv.Throw(NS_ERROR_FAILURE); - return nullptr; - } - - mozPromise->Then(AbstractThread::MainThread(), - __func__, - [domPromise] (FlyWebPublishedServer* aServer) { - domPromise->MaybeResolve(aServer); - }, - [domPromise] (nsresult aStatus) { - domPromise->MaybeReject(aStatus); - }); - - return domPromise.forget(); -} - PowerManager* Navigator::GetMozPower(ErrorResult& aRv) { diff --git a/dom/base/Navigator.h b/dom/base/Navigator.h index c681797fb6..4ddaaabab4 100644 --- a/dom/base/Navigator.h +++ b/dom/base/Navigator.h @@ -39,8 +39,6 @@ class WakeLock; class ArrayBufferViewOrBlobOrStringOrFormData; class ServiceWorkerContainer; class DOMRequest; -struct FlyWebPublishOptions; -struct FlyWebFilter; } // namespace dom } // namespace mozilla @@ -140,9 +138,6 @@ public: Geolocation* GetGeolocation(ErrorResult& aRv); Promise* GetBattery(ErrorResult& aRv); - already_AddRefed PublishServer(const nsAString& aName, - const FlyWebPublishOptions& aOptions, - ErrorResult& aRv); static void AppName(nsAString& aAppName, bool aUsePrefOverriddenValue); static nsresult GetPlatform(nsAString& aPlatform, diff --git a/dom/base/nsDocument.cpp b/dom/base/nsDocument.cpp index 293e48eb0d..b05bf827bf 100644 --- a/dom/base/nsDocument.cpp +++ b/dom/base/nsDocument.cpp @@ -166,7 +166,6 @@ #include "mozilla/dom/HTMLIFrameElement.h" #include "mozilla/dom/HTMLImageElement.h" #include "mozilla/dom/MediaSource.h" -#include "mozilla/dom/FlyWebService.h" #include "mozAutoDocUpdate.h" #include "nsGlobalWindow.h" @@ -8453,13 +8452,6 @@ nsDocument::CanSavePresentation(nsIRequest *aNewRequest) return false; } - // Don't save presentation if there are active FlyWeb connections or FlyWeb - // servers. - FlyWebService* flyWebService = FlyWebService::GetExisting(); - if (flyWebService && flyWebService->HasConnectionOrServer(win->WindowID())) { - return false; - } - if (mSubDocuments) { for (auto iter = mSubDocuments->Iter(); !iter.Done(); iter.Next()) { auto entry = static_cast(iter.Get()); diff --git a/dom/bindings/Bindings.conf b/dom/bindings/Bindings.conf index 9428529f48..56d220194a 100644 --- a/dom/bindings/Bindings.conf +++ b/dom/bindings/Bindings.conf @@ -340,14 +340,6 @@ DOMInterfaces = { 'wrapperCache': False, }, -'FlyWebFetchEvent': { - 'headerFile': 'FlyWebServerEvents.h', -}, - -'FlyWebWebSocketEvent': { - 'headerFile': 'FlyWebServerEvents.h', -}, - 'FontFaceSet': { 'implicitJSContext': [ 'load' ], }, diff --git a/dom/events/test/test_all_synthetic_events.html b/dom/events/test/test_all_synthetic_events.html index 90dbe95ee7..58560fdcef 100644 --- a/dom/events/test/test_all_synthetic_events.html +++ b/dom/events/test/test_all_synthetic_events.html @@ -139,10 +139,6 @@ const kEventConstructors = { return new ErrorEvent(aName, aProps); }, }, - FlyWebFetchEvent: { create: null, // Cannot create untrusted event from JS. - }, - FlyWebWebSocketEvent: { create: null, // Cannot create untrusted event from JS. - }, FocusEvent: { create: function (aName, aProps) { return new FocusEvent(aName, aProps); }, diff --git a/dom/flyweb/FlyWebDiscoveryManager.cpp b/dom/flyweb/FlyWebDiscoveryManager.cpp deleted file mode 100644 index 14ad5aa1f9..0000000000 --- a/dom/flyweb/FlyWebDiscoveryManager.cpp +++ /dev/null @@ -1,126 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "nsString.h" -#include "nsTHashtable.h" -#include "nsClassHashtable.h" -#include "nsIUUIDGenerator.h" -#include "jsapi.h" -#include "mozilla/StaticPtr.h" -#include "mozilla/Logging.h" -#include "nsComponentManagerUtils.h" -#include "nsServiceManagerUtils.h" - -#include "mozilla/dom/FlyWebDiscoveryManager.h" -#include "mozilla/dom/FlyWebDiscoveryManagerBinding.h" -#include "mozilla/dom/Element.h" - -namespace mozilla { -namespace dom { - -static LazyLogModule gFlyWebDiscoveryManagerLog("FlyWebDiscoveryManager"); -#undef LOG_I -#define LOG_I(...) MOZ_LOG(mozilla::dom::gFlyWebDiscoveryManagerLog, mozilla::LogLevel::Debug, (__VA_ARGS__)) -#undef LOG_E -#define LOG_E(...) MOZ_LOG(mozilla::dom::gFlyWebDiscoveryManagerLog, mozilla::LogLevel::Error, (__VA_ARGS__)) - - -NS_IMPL_CYCLE_COLLECTION_WRAPPERCACHE_0(FlyWebDiscoveryManager) - -NS_IMPL_CYCLE_COLLECTING_ADDREF(FlyWebDiscoveryManager) -NS_IMPL_CYCLE_COLLECTING_RELEASE(FlyWebDiscoveryManager) -NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(FlyWebDiscoveryManager) - NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY - NS_INTERFACE_MAP_ENTRY(nsISupports) -NS_INTERFACE_MAP_END - -FlyWebDiscoveryManager::FlyWebDiscoveryManager(nsISupports* aParent, - FlyWebService* aService) - : mParent(aParent) - , mService(aService) - , mNextId(0) -{ -} - -FlyWebDiscoveryManager::~FlyWebDiscoveryManager() -{ - mService->UnregisterDiscoveryManager(this); -} - -JSObject* -FlyWebDiscoveryManager::WrapObject(JSContext* aCx, JS::Handle aGivenProto) -{ - return FlyWebDiscoveryManagerBinding::Wrap(aCx, this, aGivenProto); -} - -nsISupports* -FlyWebDiscoveryManager::GetParentObject() const -{ - return mParent; -} - -/* static */ already_AddRefed -FlyWebDiscoveryManager::Constructor(const GlobalObject& aGlobal, ErrorResult& rv) -{ - RefPtr service = FlyWebService::GetOrCreate(); - if (!service) { - return nullptr; - } - - RefPtr result = new FlyWebDiscoveryManager( - aGlobal.GetAsSupports(), service); - return result.forget(); -} - -void -FlyWebDiscoveryManager::ListServices(nsTArray& aServices) -{ - return mService->ListDiscoveredServices(aServices); -} - -uint32_t -FlyWebDiscoveryManager::StartDiscovery(FlyWebDiscoveryCallback& aCallback) -{ - uint32_t id = GenerateId(); - mCallbackMap.Put(id, &aCallback); - mService->RegisterDiscoveryManager(this); - return id; -} - -void -FlyWebDiscoveryManager::StopDiscovery(uint32_t aId) -{ - mCallbackMap.Remove(aId); - if (mCallbackMap.Count() == 0) { - mService->UnregisterDiscoveryManager(this); - } -} - -void -FlyWebDiscoveryManager::PairWithService(const nsAString& aServiceId, - FlyWebPairingCallback& aCallback) -{ - mService->PairWithService(aServiceId, aCallback); -} - -void -FlyWebDiscoveryManager::NotifyDiscoveredServicesChanged() -{ - nsTArray services; - ListServices(services); - Sequence servicesSeq; - servicesSeq.SwapElements(services); - for (auto iter = mCallbackMap.Iter(); !iter.Done(); iter.Next()) { - FlyWebDiscoveryCallback *callback = iter.UserData(); - ErrorResult err; - callback->OnDiscoveredServicesChanged(servicesSeq, err); - ENSURE_SUCCESS_VOID(err); - } -} - - -} // namespace dom -} // namespace mozilla diff --git a/dom/flyweb/FlyWebDiscoveryManager.h b/dom/flyweb/FlyWebDiscoveryManager.h deleted file mode 100644 index cb5f692f83..0000000000 --- a/dom/flyweb/FlyWebDiscoveryManager.h +++ /dev/null @@ -1,61 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_dom_FlyWebDiscoveryManager_h -#define mozilla_dom_FlyWebDiscoveryManager_h - -#include "nsISupportsImpl.h" -#include "mozilla/ErrorResult.h" -#include "nsRefPtrHashtable.h" -#include "nsWrapperCache.h" -#include "FlyWebDiscoveryManagerBinding.h" -#include "FlyWebService.h" - -namespace mozilla { -namespace dom { - -class FlyWebDiscoveryManager final : public nsISupports - , public nsWrapperCache -{ -public: - NS_DECL_CYCLE_COLLECTING_ISUPPORTS - NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(FlyWebDiscoveryManager) - - virtual JSObject* WrapObject(JSContext* aCx, JS::Handle aGivenProto) override; - nsISupports* GetParentObject() const; - - static already_AddRefed Constructor(const GlobalObject& aGlobal, - ErrorResult& rv); - - void ListServices(nsTArray& aServices); - uint32_t StartDiscovery(FlyWebDiscoveryCallback& aCallback); - void StopDiscovery(uint32_t aId); - - void PairWithService(const nsAString& aServiceId, - FlyWebPairingCallback& callback); - - void NotifyDiscoveredServicesChanged(); - -private: - FlyWebDiscoveryManager(nsISupports* mParent, FlyWebService* aService); - ~FlyWebDiscoveryManager(); - - uint32_t GenerateId() { - return ++mNextId; - } - - nsCOMPtr mParent; - RefPtr mService; - - uint32_t mNextId; - - nsRefPtrHashtable mCallbackMap; -}; - -} // namespace dom -} // namespace mozilla - -#endif // mozilla_dom_FlyWebDiscoveryManager_h diff --git a/dom/flyweb/FlyWebPublishOptionsIPCSerializer.h b/dom/flyweb/FlyWebPublishOptionsIPCSerializer.h deleted file mode 100644 index fa1a441138..0000000000 --- a/dom/flyweb/FlyWebPublishOptionsIPCSerializer.h +++ /dev/null @@ -1,33 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_dom_FlyWebPublishOptionsIPCSerialiser_h -#define mozilla_dom_FlyWebPublishOptionsIPCSerialiser_h - -#include "mozilla/dom/FlyWebPublishBinding.h" - -namespace IPC { - -template <> -struct ParamTraits -{ - typedef mozilla::dom::FlyWebPublishOptions paramType; - - // Function to serialize a FlyWebPublishOptions - static void Write(Message *aMsg, const paramType& aParam) - { - WriteParam(aMsg, aParam.mUiUrl); - } - // Function to de-serialize a FlyWebPublishOptions - static bool Read(const Message* aMsg, PickleIterator* aIter, paramType* aResult) - { - return ReadParam(aMsg, aIter, &(aResult->mUiUrl)); - } -}; - -} - -#endif // mozilla_dom_FlyWebPublishOptionsIPCSerialiser_h diff --git a/dom/flyweb/FlyWebPublishedServer.cpp b/dom/flyweb/FlyWebPublishedServer.cpp deleted file mode 100644 index 375df332f8..0000000000 --- a/dom/flyweb/FlyWebPublishedServer.cpp +++ /dev/null @@ -1,675 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "mozilla/dom/FlyWebPublishedServerIPC.h" -#include "mozilla/dom/FlyWebPublishBinding.h" -#include "mozilla/dom/FlyWebService.h" -#include "mozilla/dom/Request.h" -#include "mozilla/dom/FlyWebServerEvents.h" -#include "mozilla/dom/ContentChild.h" -#include "mozilla/dom/ContentParent.h" -#include "mozilla/dom/InternalResponse.h" -#include "mozilla/ipc/IPCStreamUtils.h" -#include "mozilla/net/NeckoParent.h" -#include "mozilla/net/IPCTransportProvider.h" -#include "mozilla/ErrorResult.h" -#include "mozilla/Preferences.h" -#include "mozilla/Unused.h" -#include "nsCharSeparatedTokenizer.h" -#include "nsGlobalWindow.h" -#include "WebSocketChannel.h" - -namespace mozilla { -namespace dom { - -static LazyLogModule gFlyWebPublishedServerLog("FlyWebPublishedServer"); -#undef LOG_I -#define LOG_I(...) MOZ_LOG(mozilla::dom::gFlyWebPublishedServerLog, mozilla::LogLevel::Debug, (__VA_ARGS__)) -#undef LOG_E -#define LOG_E(...) MOZ_LOG(mozilla::dom::gFlyWebPublishedServerLog, mozilla::LogLevel::Error, (__VA_ARGS__)) - -/******** FlyWebPublishedServer ********/ - -FlyWebPublishedServer::FlyWebPublishedServer(nsPIDOMWindowInner* aOwner, - const nsAString& aName, - const FlyWebPublishOptions& aOptions) - : mozilla::DOMEventTargetHelper(aOwner) - , mOwnerWindowID(aOwner ? aOwner->WindowID() : 0) - , mName(aName) - , mUiUrl(aOptions.mUiUrl) - , mIsRegistered(true) // Registered by the FlyWebService -{ -} - -void -FlyWebPublishedServer::LastRelease() -{ - // Make sure to unregister to avoid dangling pointers. Use the LastRelease - // hook rather than dtor since calling virtual functions during dtor - // wouldn't do what we want. Also, LastRelease is called earlier than dtor - // for CC objects. - Close(); -} - -JSObject* -FlyWebPublishedServer::WrapObject(JSContext* aCx, JS::Handle aGivenProto) -{ - return FlyWebPublishedServerBinding::Wrap(aCx, this, aGivenProto); -} - -void -FlyWebPublishedServer::Close() -{ - LOG_I("FlyWebPublishedServer::Close(%p)", this); - - // Unregister from server. - if (mIsRegistered) { - MOZ_ASSERT(FlyWebService::GetExisting()); - FlyWebService::GetExisting()->UnregisterServer(this); - mIsRegistered = false; - - DispatchTrustedEvent(NS_LITERAL_STRING("close")); - } -} - -void -FlyWebPublishedServer::FireFetchEvent(InternalRequest* aRequest) -{ - nsCOMPtr global = do_QueryInterface(GetOwner()); - RefPtr e = new FlyWebFetchEvent(this, - new Request(global, aRequest), - aRequest); - e->Init(this); - e->InitEvent(NS_LITERAL_STRING("fetch"), false, false); - - DispatchTrustedEvent(e); -} - -void -FlyWebPublishedServer::FireWebsocketEvent(InternalRequest* aConnectRequest) -{ - nsCOMPtr global = do_QueryInterface(GetOwner()); - RefPtr e = new FlyWebWebSocketEvent(this, - new Request(global, aConnectRequest), - aConnectRequest); - e->Init(this); - e->InitEvent(NS_LITERAL_STRING("websocket"), false, false); - - DispatchTrustedEvent(e); -} - -void -FlyWebPublishedServer::PublishedServerStarted(nsresult aStatus) -{ - LOG_I("FlyWebPublishedServer::PublishedServerStarted(%p)", this); - - RefPtr promise = mPublishPromise.Ensure(__func__); - if (NS_SUCCEEDED(aStatus)) { - mPublishPromise.Resolve(this, __func__); - } else { - Close(); - mPublishPromise.Reject(aStatus, __func__); - } -} - -already_AddRefed -FlyWebPublishedServer::OnWebSocketAccept(InternalRequest* aConnectRequest, - const Optional& aProtocol, - ErrorResult& aRv) -{ - MOZ_ASSERT(aConnectRequest); - - LOG_I("FlyWebPublishedServer::OnWebSocketAccept(%p)", this); - - nsCOMPtr provider = - OnWebSocketAcceptInternal(aConnectRequest, - aProtocol, - aRv); - if (aRv.Failed()) { - return nullptr; - } - MOZ_ASSERT(provider); - - nsCOMPtr window = do_QueryInterface(GetOwner()); - AutoJSContext cx; - GlobalObject global(cx, nsGlobalWindow::Cast(window)->FastGetGlobalJSObject()); - - nsAutoCString extensions, negotiatedExtensions; - aConnectRequest->Headers()-> - GetFirst(NS_LITERAL_CSTRING("Sec-WebSocket-Extensions"), extensions, aRv); - mozilla::net::ProcessServerWebSocketExtensions(extensions, - negotiatedExtensions); - - nsCString url; - aConnectRequest->GetURL(url); - Sequence protocols; - if (aProtocol.WasPassed() && - !protocols.AppendElement(aProtocol.Value(), fallible)) { - aRv.Throw(NS_ERROR_OUT_OF_MEMORY); - return nullptr; - } - - return WebSocket::ConstructorCommon(global, - NS_ConvertUTF8toUTF16(url), - protocols, - provider, - negotiatedExtensions, - aRv); -} - -/******** FlyWebPublishedServerImpl ********/ - -NS_IMPL_ISUPPORTS_INHERITED0(FlyWebPublishedServerImpl, mozilla::DOMEventTargetHelper) - -FlyWebPublishedServerImpl::FlyWebPublishedServerImpl(nsPIDOMWindowInner* aOwner, - const nsAString& aName, - const FlyWebPublishOptions& aOptions) - : FlyWebPublishedServer(aOwner, aName, aOptions) - , mHttpServer(new HttpServer()) -{ - LOG_I("FlyWebPublishedServerImpl::FlyWebPublishedServerImpl(%p)", this); -} - -void -FlyWebPublishedServerImpl::PermissionGranted(bool aGranted) -{ - LOG_I("FlyWebPublishedServerImpl::PermissionGranted(%b)", aGranted); - if (!aGranted) { - PublishedServerStarted(NS_ERROR_FAILURE); - return; - } - - mHttpServer->Init(-1, Preferences::GetBool("flyweb.use-tls", false), this); -} - -void -FlyWebPublishedServerImpl::Close() -{ - FlyWebPublishedServer::Close(); - - if (mMDNSCancelRegister) { - mMDNSCancelRegister->Cancel(NS_BINDING_ABORTED); - mMDNSCancelRegister = nullptr; - } - - if (mHttpServer) { - RefPtr server = mHttpServer.forget(); - server->Close(); - } -} - -void -FlyWebPublishedServerImpl::OnServerStarted(nsresult aStatus) -{ - if (NS_SUCCEEDED(aStatus)) { - FlyWebService::GetOrCreate()->StartDiscoveryOf(this); - } else { - PublishedServerStarted(aStatus); - } -} - -void -FlyWebPublishedServerImpl::OnFetchResponse(InternalRequest* aRequest, - InternalResponse* aResponse) -{ - MOZ_ASSERT(aRequest); - MOZ_ASSERT(aResponse); - - LOG_I("FlyWebPublishedServerImpl::OnFetchResponse(%p)", this); - - if (mHttpServer) { - mHttpServer->SendResponse(aRequest, aResponse); - } -} - -void -FlyWebPublishedServerImpl::OnWebSocketResponse(InternalRequest* aConnectRequest, - InternalResponse* aResponse) -{ - MOZ_ASSERT(aConnectRequest); - MOZ_ASSERT(aResponse); - - LOG_I("FlyWebPublishedMDNSServer::OnWebSocketResponse(%p)", this); - - if (mHttpServer) { - mHttpServer->SendWebSocketResponse(aConnectRequest, aResponse); - } -} - -already_AddRefed -FlyWebPublishedServerImpl::OnWebSocketAcceptInternal(InternalRequest* aConnectRequest, - const Optional& aProtocol, - ErrorResult& aRv) -{ - LOG_I("FlyWebPublishedServerImpl::OnWebSocketAcceptInternal(%p)", this); - - if (!mHttpServer) { - aRv.Throw(NS_ERROR_UNEXPECTED); - return nullptr; - } - - return mHttpServer->AcceptWebSocket(aConnectRequest, - aProtocol, - aRv); -} - -/******** FlyWebPublishedServerChild ********/ - -FlyWebPublishedServerChild::FlyWebPublishedServerChild(nsPIDOMWindowInner* aOwner, - const nsAString& aName, - const FlyWebPublishOptions& aOptions) - : FlyWebPublishedServer(aOwner, aName, aOptions) - , mActorExists(false) -{ - LOG_I("FlyWebPublishedServerChild::FlyWebPublishedServerChild(%p)", this); - - // The matching release happens when the actor is destroyed, in - // ContentChild::DeallocPFlyWebPublishedServerChild - NS_ADDREF_THIS(); -} - -void -FlyWebPublishedServerChild::PermissionGranted(bool aGranted) -{ - if (!aGranted) { - PublishedServerStarted(NS_ERROR_FAILURE); - return; - } - - mActorExists = true; - FlyWebPublishOptions options; - options.mUiUrl = mUiUrl; - - // Proceed with initialization. - ContentChild::GetSingleton()-> - SendPFlyWebPublishedServerConstructor(this, mName, options); -} - -bool -FlyWebPublishedServerChild::RecvServerReady(const nsresult& aStatus) -{ - LOG_I("FlyWebPublishedServerChild::RecvServerReady(%p)", this); - MOZ_ASSERT(mActorExists); - - PublishedServerStarted(aStatus); - return true; -} - -bool -FlyWebPublishedServerChild::RecvServerClose() -{ - LOG_I("FlyWebPublishedServerChild::RecvServerClose(%p)", this); - MOZ_ASSERT(mActorExists); - - Close(); - - return true; -} - -bool -FlyWebPublishedServerChild::RecvFetchRequest(const IPCInternalRequest& aRequest, - const uint64_t& aRequestId) -{ - LOG_I("FlyWebPublishedServerChild::RecvFetchRequest(%p)", this); - MOZ_ASSERT(mActorExists); - - RefPtr request = new InternalRequest(aRequest); - mPendingRequests.Put(request, aRequestId); - FireFetchEvent(request); - - return true; -} - -bool -FlyWebPublishedServerChild::RecvWebSocketRequest(const IPCInternalRequest& aRequest, - const uint64_t& aRequestId, - PTransportProviderChild* aProvider) -{ - LOG_I("FlyWebPublishedServerChild::RecvWebSocketRequest(%p)", this); - MOZ_ASSERT(mActorExists); - - RefPtr request = new InternalRequest(aRequest); - mPendingRequests.Put(request, aRequestId); - - // Not addreffing here. The addref was already done when the - // PTransportProvider child constructor original ran. - mPendingTransportProviders.Put(aRequestId, - dont_AddRef(static_cast(aProvider))); - - FireWebsocketEvent(request); - - return true; -} - -void -FlyWebPublishedServerChild::ActorDestroy(ActorDestroyReason aWhy) -{ - LOG_I("FlyWebPublishedServerChild::ActorDestroy(%p)", this); - - mActorExists = false; -} - -void -FlyWebPublishedServerChild::OnFetchResponse(InternalRequest* aRequest, - InternalResponse* aResponse) -{ - LOG_I("FlyWebPublishedServerChild::OnFetchResponse(%p)", this); - - if (!mActorExists) { - LOG_I("FlyWebPublishedServerChild::OnFetchResponse(%p) - No actor!", this); - return; - } - - uint64_t id = mPendingRequests.Get(aRequest); - MOZ_ASSERT(id); - mPendingRequests.Remove(aRequest); - - IPCInternalResponse ipcResp; - UniquePtr autoStream; - nsIContentChild* cc = static_cast(Manager()); - aResponse->ToIPC(&ipcResp, cc, autoStream); - Unused << SendFetchResponse(ipcResp, id); - if (autoStream) { - autoStream->TakeOptionalValue(); - } -} - -already_AddRefed -FlyWebPublishedServerChild::OnWebSocketAcceptInternal(InternalRequest* aRequest, - const Optional& aProtocol, - ErrorResult& aRv) -{ - LOG_I("FlyWebPublishedServerChild::OnWebSocketAcceptInternal(%p)", this); - - if (!mActorExists) { - LOG_I("FlyWebPublishedServerChild::OnWebSocketAcceptInternal(%p) - No actor!", this); - return nullptr; - } - - uint64_t id = mPendingRequests.Get(aRequest); - MOZ_ASSERT(id); - mPendingRequests.Remove(aRequest); - - RefPtr provider; - mPendingTransportProviders.Remove(id, getter_AddRefs(provider)); - - nsString protocol; - if (aProtocol.WasPassed()) { - protocol = aProtocol.Value(); - - nsAutoCString reqProtocols; - aRequest->Headers()-> - GetFirst(NS_LITERAL_CSTRING("Sec-WebSocket-Protocol"), reqProtocols, aRv); - if (!ContainsToken(reqProtocols, NS_ConvertUTF16toUTF8(protocol))) { - // Should throw a better error here - aRv.Throw(NS_ERROR_FAILURE); - return nullptr; - } - } else { - protocol.SetIsVoid(true); - } - - Unused << SendWebSocketAccept(protocol, id); - - return provider.forget(); -} - -void -FlyWebPublishedServerChild::OnWebSocketResponse(InternalRequest* aRequest, - InternalResponse* aResponse) -{ - LOG_I("FlyWebPublishedServerChild::OnFetchResponse(%p)", this); - - if (!mActorExists) { - LOG_I("FlyWebPublishedServerChild::OnFetchResponse(%p) - No actor!", this); - return; - } - - uint64_t id = mPendingRequests.Get(aRequest); - MOZ_ASSERT(id); - mPendingRequests.Remove(aRequest); - - mPendingTransportProviders.Remove(id); - - IPCInternalResponse ipcResp; - UniquePtr autoStream; - nsIContentChild* cc = static_cast(Manager()); - aResponse->ToIPC(&ipcResp, cc, autoStream); - - Unused << SendWebSocketResponse(ipcResp, id); - if (autoStream) { - autoStream->TakeOptionalValue(); - } -} - -void -FlyWebPublishedServerChild::Close() -{ - LOG_I("FlyWebPublishedServerChild::Close(%p)", this); - - FlyWebPublishedServer::Close(); - - if (mActorExists) { - LOG_I("FlyWebPublishedServerChild::Close - sending __delete__ (%p)", this); - - Send__delete__(this); - } -} - -/******** FlyWebPublishedServerParent ********/ - -NS_IMPL_ISUPPORTS(FlyWebPublishedServerParent, nsIDOMEventListener) - -FlyWebPublishedServerParent::FlyWebPublishedServerParent(const nsAString& aName, - const FlyWebPublishOptions& aOptions) - : mActorDestroyed(false) - , mNextRequestId(1) -{ - LOG_I("FlyWebPublishedServerParent::FlyWebPublishedServerParent(%p)", this); - - RefPtr service = FlyWebService::GetOrCreate(); - if (!service) { - Unused << SendServerReady(NS_ERROR_FAILURE); - return; - } - - RefPtr mozPromise = - service->PublishServer(aName, aOptions, nullptr); - if (!mozPromise) { - Unused << SendServerReady(NS_ERROR_FAILURE); - return; - } - - RefPtr self = this; - - mozPromise->Then( - AbstractThread::MainThread(), - __func__, - [this, self] (FlyWebPublishedServer* aServer) { - mPublishedServer = static_cast(aServer); - if (mActorDestroyed) { - mPublishedServer->Close(); - return; - } - - mPublishedServer->AddEventListener(NS_LITERAL_STRING("fetch"), - this, false, false, 2); - mPublishedServer->AddEventListener(NS_LITERAL_STRING("websocket"), - this, false, false, 2); - mPublishedServer->AddEventListener(NS_LITERAL_STRING("close"), - this, false, false, 2); - Unused << SendServerReady(NS_OK); - }, - [this, self] (nsresult aStatus) { - MOZ_ASSERT(NS_FAILED(aStatus)); - if (!mActorDestroyed) { - Unused << SendServerReady(aStatus); - } - }); -} - -NS_IMETHODIMP -FlyWebPublishedServerParent::HandleEvent(nsIDOMEvent* aEvent) -{ - if (mActorDestroyed) { - return NS_OK; - } - - nsAutoString type; - aEvent->GetType(type); - if (type.EqualsLiteral("close")) { - Unused << SendServerClose(); - return NS_OK; - } - - if (type.EqualsLiteral("fetch")) { - RefPtr request = - static_cast(aEvent)->Request()->GetInternalRequest(); - uint64_t id = mNextRequestId++; - mPendingRequests.Put(id, request); - - IPCInternalRequest ipcReq; - request->ToIPC(&ipcReq); - Unused << SendFetchRequest(ipcReq, id); - return NS_OK; - } - - if (type.EqualsLiteral("websocket")) { - RefPtr request = - static_cast(aEvent)->Request()->GetInternalRequest(); - uint64_t id = mNextRequestId++; - mPendingRequests.Put(id, request); - - nsTArray neckoParents; - Manager()->ManagedPNeckoParent(neckoParents); - if (neckoParents.Length() != 1) { - MOZ_CRASH("Expected exactly 1 PNeckoParent instance per PNeckoChild"); - } - - RefPtr provider = - static_cast( - neckoParents[0]->SendPTransportProviderConstructor()); - - IPCInternalRequest ipcReq; - request->ToIPC(&ipcReq); - Unused << SendWebSocketRequest(ipcReq, id, provider); - - mPendingTransportProviders.Put(id, provider.forget()); - return NS_OK; - } - - MOZ_CRASH("Unknown event type"); - - return NS_OK; -} - -bool -FlyWebPublishedServerParent::RecvFetchResponse(const IPCInternalResponse& aResponse, - const uint64_t& aRequestId) -{ - MOZ_ASSERT(!mActorDestroyed); - - RefPtr request; - mPendingRequests.Remove(aRequestId, getter_AddRefs(request)); - if (!request) { - static_cast(Manager())->KillHard("unknown request id"); - return false; - } - - RefPtr response = InternalResponse::FromIPC(aResponse); - - mPublishedServer->OnFetchResponse(request, response); - - return true; -} - -bool -FlyWebPublishedServerParent::RecvWebSocketResponse(const IPCInternalResponse& aResponse, - const uint64_t& aRequestId) -{ - MOZ_ASSERT(!mActorDestroyed); - - mPendingTransportProviders.Remove(aRequestId); - - RefPtr request; - mPendingRequests.Remove(aRequestId, getter_AddRefs(request)); - if (!request) { - static_cast(Manager())->KillHard("unknown websocket request id"); - return false; - } - - RefPtr response = InternalResponse::FromIPC(aResponse); - - mPublishedServer->OnWebSocketResponse(request, response); - - return true; -} - -bool -FlyWebPublishedServerParent::RecvWebSocketAccept(const nsString& aProtocol, - const uint64_t& aRequestId) -{ - MOZ_ASSERT(!mActorDestroyed); - - RefPtr providerIPC; - mPendingTransportProviders.Remove(aRequestId, getter_AddRefs(providerIPC)); - - RefPtr request; - mPendingRequests.Remove(aRequestId, getter_AddRefs(request)); - - if (!request || !providerIPC) { - static_cast(Manager())->KillHard("unknown websocket request id"); - return false; - } - - Optional protocol; - if (!aProtocol.IsVoid()) { - protocol = &aProtocol; - } - - ErrorResult result; - nsCOMPtr providerServer = - mPublishedServer->OnWebSocketAcceptInternal(request, protocol, result); - if (result.Failed()) { - return false; - } - - providerServer->SetListener(providerIPC); - - return true; -} - -void -FlyWebPublishedServerParent::ActorDestroy(ActorDestroyReason aWhy) -{ - LOG_I("FlyWebPublishedServerParent::ActorDestroy(%p)", this); - - mActorDestroyed = true; -} - -bool -FlyWebPublishedServerParent::Recv__delete__() -{ - LOG_I("FlyWebPublishedServerParent::Recv__delete__(%p)", this); - MOZ_ASSERT(!mActorDestroyed); - - if (mPublishedServer) { - mPublishedServer->RemoveEventListener(NS_LITERAL_STRING("fetch"), - this, false); - mPublishedServer->RemoveEventListener(NS_LITERAL_STRING("websocket"), - this, false); - mPublishedServer->RemoveEventListener(NS_LITERAL_STRING("close"), - this, false); - mPublishedServer->Close(); - mPublishedServer = nullptr; - } - return true; -} - -} // namespace dom -} // namespace mozilla - - diff --git a/dom/flyweb/FlyWebPublishedServer.h b/dom/flyweb/FlyWebPublishedServer.h deleted file mode 100644 index ec3a685ec6..0000000000 --- a/dom/flyweb/FlyWebPublishedServer.h +++ /dev/null @@ -1,109 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_dom_FlyWebPublishedServer_h -#define mozilla_dom_FlyWebPublishedServer_h - -#include "mozilla/DOMEventTargetHelper.h" -#include "mozilla/MozPromise.h" - -class nsPIDOMWindowInner; -class nsITransportProvider; - -namespace mozilla { - -class ErrorResult; - -namespace dom { - -class InternalResponse; -class InternalRequest; -class WebSocket; -struct FlyWebPublishOptions; -class FlyWebPublishedServer; - -typedef MozPromise, nsresult, false> - FlyWebPublishPromise; - -class FlyWebPublishedServer : public mozilla::DOMEventTargetHelper -{ -public: - FlyWebPublishedServer(nsPIDOMWindowInner* aOwner, - const nsAString& aName, - const FlyWebPublishOptions& aOptions); - - virtual void LastRelease() override; - - virtual JSObject* WrapObject(JSContext *cx, JS::Handle aGivenProto) override; - - uint64_t OwnerWindowID() const { - return mOwnerWindowID; - } - - void GetName(nsAString& aName) - { - aName = mName; - } - nsAString& Name() - { - return mName; - } - - void GetUiUrl(nsAString& aUiUrl) - { - aUiUrl = mUiUrl; - } - - virtual void PermissionGranted(bool aGranted) = 0; - - virtual void OnFetchResponse(InternalRequest* aRequest, - InternalResponse* aResponse) = 0; - already_AddRefed - OnWebSocketAccept(InternalRequest* aConnectRequest, - const Optional& aProtocol, - ErrorResult& aRv); - virtual void OnWebSocketResponse(InternalRequest* aConnectRequest, - InternalResponse* aResponse) = 0; - virtual already_AddRefed - OnWebSocketAcceptInternal(InternalRequest* aConnectRequest, - const Optional& aProtocol, - ErrorResult& aRv) = 0; - - virtual void Close(); - - void FireFetchEvent(InternalRequest* aRequest); - void FireWebsocketEvent(InternalRequest* aConnectRequest); - void PublishedServerStarted(nsresult aStatus); - - IMPL_EVENT_HANDLER(fetch) - IMPL_EVENT_HANDLER(websocket) - IMPL_EVENT_HANDLER(close) - - already_AddRefed - GetPublishPromise() - { - return mPublishPromise.Ensure(__func__); - } - -protected: - virtual ~FlyWebPublishedServer() - { - MOZ_ASSERT(!mIsRegistered, "Subclass dtor forgot to call Close()"); - } - - uint64_t mOwnerWindowID; - MozPromiseHolder mPublishPromise; - - nsString mName; - nsString mUiUrl; - - bool mIsRegistered; -}; - -} // namespace dom -} // namespace mozilla - -#endif // mozilla_dom_FlyWebPublishedServer_h diff --git a/dom/flyweb/FlyWebPublishedServerIPC.h b/dom/flyweb/FlyWebPublishedServerIPC.h deleted file mode 100644 index 942c7847ee..0000000000 --- a/dom/flyweb/FlyWebPublishedServerIPC.h +++ /dev/null @@ -1,172 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_dom_FlyWebPublishedServerIPC_h -#define mozilla_dom_FlyWebPublishedServerIPC_h - -#include "HttpServer.h" -#include "mozilla/dom/FlyWebPublishedServer.h" -#include "mozilla/dom/PFlyWebPublishedServerParent.h" -#include "mozilla/dom/PFlyWebPublishedServerChild.h" -#include "mozilla/MozPromise.h" -#include "nsICancelable.h" -#include "nsIDOMEventListener.h" -#include "nsISupportsImpl.h" - -class nsPIDOMWindowInner; - -namespace mozilla { -namespace net { -class TransportProviderParent; -class TransportProviderChild; -} - -namespace dom { - -class FlyWebPublishedServerParent; - -class FlyWebPublishedServerImpl final : public FlyWebPublishedServer - , public HttpServerListener -{ -public: - FlyWebPublishedServerImpl(nsPIDOMWindowInner* aOwner, - const nsAString& aName, - const FlyWebPublishOptions& aOptions); - - NS_DECL_ISUPPORTS_INHERITED - - int32_t Port() - { - return mHttpServer ? mHttpServer->GetPort() : 0; - } - void GetCertKey(nsACString& aKey) { - if (mHttpServer) { - mHttpServer->GetCertKey(aKey); - } else { - aKey.Truncate(); - } - } - - virtual void PermissionGranted(bool aGranted) override; - virtual void OnFetchResponse(InternalRequest* aRequest, - InternalResponse* aResponse) override; - virtual void OnWebSocketResponse(InternalRequest* aConnectRequest, - InternalResponse* aResponse) override; - virtual already_AddRefed - OnWebSocketAcceptInternal(InternalRequest* aConnectRequest, - const Optional& aProtocol, - ErrorResult& aRv) override; - - void SetCancelRegister(nsICancelable* aCancelRegister) - { - mMDNSCancelRegister = aCancelRegister; - } - - virtual void Close() override; - - // HttpServerListener - virtual void OnServerStarted(nsresult aStatus) override; - virtual void OnRequest(InternalRequest* aRequest) override - { - FireFetchEvent(aRequest); - } - virtual void OnWebSocket(InternalRequest* aConnectRequest) override - { - FireWebsocketEvent(aConnectRequest); - } - virtual void OnServerClose() override - { - mHttpServer = nullptr; - Close(); - } - -private: - ~FlyWebPublishedServerImpl() {} - - RefPtr mHttpServer; - nsCOMPtr mMDNSCancelRegister; - RefPtr mServerParent; -}; - -class FlyWebPublishedServerChild final : public FlyWebPublishedServer - , public PFlyWebPublishedServerChild -{ -public: - FlyWebPublishedServerChild(nsPIDOMWindowInner* aOwner, - const nsAString& aName, - const FlyWebPublishOptions& aOptions); - - virtual void PermissionGranted(bool aGranted) override; - virtual bool RecvServerReady(const nsresult& aStatus) override; - virtual bool RecvServerClose() override; - virtual bool RecvFetchRequest(const IPCInternalRequest& aRequest, - const uint64_t& aRequestId) override; - virtual bool RecvWebSocketRequest(const IPCInternalRequest& aRequest, - const uint64_t& aRequestId, - PTransportProviderChild* aProvider) override; - - virtual void OnFetchResponse(InternalRequest* aRequest, - InternalResponse* aResponse) override; - virtual void OnWebSocketResponse(InternalRequest* aConnectRequest, - InternalResponse* aResponse) override; - virtual already_AddRefed - OnWebSocketAcceptInternal(InternalRequest* aConnectRequest, - const Optional& aProtocol, - ErrorResult& aRv) override; - - virtual void Close() override; - - virtual void ActorDestroy(ActorDestroyReason aWhy) override; - -private: - ~FlyWebPublishedServerChild() {} - - nsDataHashtable, uint64_t> mPendingRequests; - nsRefPtrHashtable - mPendingTransportProviders; - bool mActorExists; -}; - -class FlyWebPublishedServerParent final : public PFlyWebPublishedServerParent - , public nsIDOMEventListener -{ -public: - FlyWebPublishedServerParent(const nsAString& aName, - const FlyWebPublishOptions& aOptions); - - NS_DECL_ISUPPORTS - NS_DECL_NSIDOMEVENTLISTENER - -private: - virtual void - ActorDestroy(ActorDestroyReason aWhy) override; - - virtual bool - Recv__delete__() override; - virtual bool - RecvFetchResponse(const IPCInternalResponse& aResponse, - const uint64_t& aRequestId) override; - virtual bool - RecvWebSocketResponse(const IPCInternalResponse& aResponse, - const uint64_t& aRequestId) override; - virtual bool - RecvWebSocketAccept(const nsString& aProtocol, - const uint64_t& aRequestId) override; - - ~FlyWebPublishedServerParent() {} - - bool mActorDestroyed; - uint64_t mNextRequestId; - nsRefPtrHashtable mPendingRequests; - nsRefPtrHashtable - mPendingTransportProviders; - RefPtr mPublishedServer; -}; - -} // namespace dom -} // namespace mozilla - -#endif // mozilla_dom_FlyWebPublishedServerIPC_h diff --git a/dom/flyweb/FlyWebServerEvents.cpp b/dom/flyweb/FlyWebServerEvents.cpp deleted file mode 100644 index fe774ffb08..0000000000 --- a/dom/flyweb/FlyWebServerEvents.cpp +++ /dev/null @@ -1,141 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim:set ts=2 sw=2 sts=2 et cindent: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "mozilla/dom/EventBinding.h" -#include "mozilla/dom/FlyWebFetchEventBinding.h" -#include "mozilla/dom/FlyWebPublishedServer.h" -#include "mozilla/dom/FlyWebServerEvents.h" -#include "mozilla/dom/FlyWebWebSocketEventBinding.h" -#include "mozilla/dom/Nullable.h" -#include "mozilla/dom/Promise.h" -#include "mozilla/dom/Response.h" - -#include "js/GCAPI.h" - -namespace mozilla { -namespace dom { - - -NS_IMPL_CYCLE_COLLECTION_CLASS(FlyWebFetchEvent) - -NS_IMPL_ADDREF_INHERITED(FlyWebFetchEvent, Event) -NS_IMPL_RELEASE_INHERITED(FlyWebFetchEvent, Event) - -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(FlyWebFetchEvent, Event) - NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mRequest) -NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END - -NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN_INHERITED(FlyWebFetchEvent, Event) -NS_IMPL_CYCLE_COLLECTION_TRACE_END - -NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(FlyWebFetchEvent, Event) - NS_IMPL_CYCLE_COLLECTION_UNLINK(mRequest) -NS_IMPL_CYCLE_COLLECTION_UNLINK_END - -NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(FlyWebFetchEvent) -NS_INTERFACE_MAP_END_INHERITING(Event) - -FlyWebFetchEvent::FlyWebFetchEvent(FlyWebPublishedServer* aServer, - class Request* aRequest, - InternalRequest* aInternalRequest) - : Event(aServer, nullptr, nullptr) - , mRequest(aRequest) - , mInternalRequest(aInternalRequest) - , mServer(aServer) - , mResponded(false) -{ - MOZ_ASSERT(aServer); - MOZ_ASSERT(aRequest); - MOZ_ASSERT(aInternalRequest); -} - -FlyWebFetchEvent::~FlyWebFetchEvent() -{ -} - -JSObject* -FlyWebFetchEvent::WrapObjectInternal(JSContext* aCx, JS::Handle aGivenProto) -{ - return FlyWebFetchEventBinding::Wrap(aCx, this, aGivenProto); -} - -void -FlyWebFetchEvent::RespondWith(Promise& aArg, ErrorResult& aRv) -{ - if (mResponded) { - aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR); - return; - } - - mResponded = true; - - aArg.AppendNativeHandler(this); -} - -void -FlyWebFetchEvent::ResolvedCallback(JSContext* aCx, JS::Handle aValue) -{ - RefPtr response; - if (aValue.isObject()) { - UNWRAP_OBJECT(Response, &aValue.toObject(), response); - } - - RefPtr intResponse; - if (response && response->Type() != ResponseType::Opaque) { - intResponse = response->GetInternalResponse(); - } - - if (!intResponse) { - intResponse = InternalResponse::NetworkError(); - } - - NotifyServer(intResponse); -} - -void -FlyWebFetchEvent::NotifyServer(InternalResponse* aResponse) -{ - mServer->OnFetchResponse(mInternalRequest, aResponse); -} - -void -FlyWebFetchEvent::RejectedCallback(JSContext* aCx, JS::Handle aValue) -{ - RefPtr err = InternalResponse::NetworkError(); - - NotifyServer(err); -} - -JSObject* -FlyWebWebSocketEvent::WrapObjectInternal(JSContext* aCx, JS::Handle aGivenProto) -{ - return FlyWebWebSocketEventBinding::Wrap(aCx, this, aGivenProto); -} - -already_AddRefed -FlyWebWebSocketEvent::Accept(const Optional& aProtocol, - ErrorResult& aRv) -{ - if (mResponded) { - aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR); - return nullptr; - } - - mResponded = true; - - return mServer->OnWebSocketAccept(mInternalRequest, aProtocol, aRv); -} - - -void -FlyWebWebSocketEvent::NotifyServer(InternalResponse* aResponse) -{ - mServer->OnWebSocketResponse(mInternalRequest, aResponse); -} - - -} // namespace dom -} // namespace mozilla diff --git a/dom/flyweb/FlyWebServerEvents.h b/dom/flyweb/FlyWebServerEvents.h deleted file mode 100644 index f00e860185..0000000000 --- a/dom/flyweb/FlyWebServerEvents.h +++ /dev/null @@ -1,88 +0,0 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim:set ts=2 sw=2 sts=2 et cindent: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_dom_FlyWebFetchEvent_h -#define mozilla_dom_FlyWebFetchEvent_h - -#include "mozilla/Attributes.h" -#include "mozilla/ErrorResult.h" -#include "mozilla/dom/BindingUtils.h" -#include "mozilla/dom/Event.h" -#include "mozilla/dom/FlyWebFetchEventBinding.h" -#include "mozilla/dom/PromiseNativeHandler.h" -#include "mozilla/dom/WebSocket.h" - -struct JSContext; -namespace mozilla { -namespace dom { - -class Request; -class Response; -class FlyWebPublishedServer; -class InternalRequest; -class InternalResponse; - -class FlyWebFetchEvent : public Event - , public PromiseNativeHandler -{ -public: - NS_DECL_ISUPPORTS_INHERITED - NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS_INHERITED(FlyWebFetchEvent, Event) - - virtual JSObject* WrapObjectInternal(JSContext* aCx, JS::Handle aGivenProto) override; - - virtual void - ResolvedCallback(JSContext* aCx, JS::Handle aValue) override; - virtual void - RejectedCallback(JSContext* aCx, JS::Handle aValue) override; - - class Request* Request() const - { - return mRequest; - } - - void RespondWith(Promise& aArg, ErrorResult& aRv); - - FlyWebFetchEvent(FlyWebPublishedServer* aServer, - class Request* aRequest, - InternalRequest* aInternalRequest); - -protected: - virtual ~FlyWebFetchEvent(); - - virtual void NotifyServer(InternalResponse* aResponse); - - RefPtr mRequest; - RefPtr mInternalRequest; - RefPtr mServer; - - bool mResponded; -}; - -class FlyWebWebSocketEvent final : public FlyWebFetchEvent -{ -public: - FlyWebWebSocketEvent(FlyWebPublishedServer* aServer, - class Request* aRequest, - InternalRequest* aInternalRequest) - : FlyWebFetchEvent(aServer, aRequest, aInternalRequest) - {} - - virtual JSObject* WrapObjectInternal(JSContext* aCx, JS::Handle aGivenProto) override; - - already_AddRefed Accept(const Optional& aProtocol, - ErrorResult& aRv); - -private: - ~FlyWebWebSocketEvent() {}; - - virtual void NotifyServer(InternalResponse* aResponse) override; -}; - -} // namespace dom -} // namespace mozilla - -#endif // mozilla_dom_FlyWebFetchEvent_h diff --git a/dom/flyweb/FlyWebService.cpp b/dom/flyweb/FlyWebService.cpp deleted file mode 100644 index 5f3b0d66f1..0000000000 --- a/dom/flyweb/FlyWebService.cpp +++ /dev/null @@ -1,1310 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "mozilla/dom/FlyWebService.h" -#include "mozilla/ClearOnShutdown.h" -#include "mozilla/StaticPtr.h" -#include "mozilla/ScopeExit.h" -#include "mozilla/dom/Promise.h" -#include "mozilla/dom/FlyWebPublishedServerIPC.h" -#include "mozilla/AddonPathService.h" -#include "nsISocketTransportService.h" -#include "mdns/libmdns/nsDNSServiceInfo.h" -#include "nsIUUIDGenerator.h" -#include "nsStandardURL.h" -#include "mozilla/Services.h" -#include "nsISupportsPrimitives.h" -#include "mozilla/dom/FlyWebDiscoveryManagerBinding.h" -#include "prnetdb.h" -#include "DNS.h" -#include "nsContentPermissionHelper.h" -#include "nsSocketTransportService2.h" -#include "nsSocketTransport2.h" -#include "nsHashPropertyBag.h" -#include "nsNetUtil.h" -#include "nsISimpleEnumerator.h" -#include "nsIProperty.h" -#include "nsICertOverrideService.h" - -namespace mozilla { -namespace dom { - -struct FlyWebPublishOptions; - -static LazyLogModule gFlyWebServiceLog("FlyWebService"); -#undef LOG_I -#define LOG_I(...) MOZ_LOG(mozilla::dom::gFlyWebServiceLog, mozilla::LogLevel::Debug, (__VA_ARGS__)) - -#undef LOG_E -#define LOG_E(...) MOZ_LOG(mozilla::dom::gFlyWebServiceLog, mozilla::LogLevel::Error, (__VA_ARGS__)) - -#undef LOG_TEST_I -#define LOG_TEST_I(...) MOZ_LOG_TEST(mozilla::dom::gFlyWebServiceLog, mozilla::LogLevel::Debug) - -class FlyWebPublishServerPermissionCheck final - : public nsIContentPermissionRequest - , public nsIRunnable -{ -public: - NS_DECL_ISUPPORTS - - FlyWebPublishServerPermissionCheck(const nsCString& aServiceName, uint64_t aWindowID, - FlyWebPublishedServer* aServer) - : mServiceName(aServiceName) - , mWindowID(aWindowID) - , mServer(aServer) - {} - - uint64_t WindowID() const - { - return mWindowID; - } - - NS_IMETHOD Run() override - { - MOZ_ASSERT(NS_IsMainThread()); - - nsGlobalWindow* globalWindow = nsGlobalWindow::GetInnerWindowWithId(mWindowID); - if (!globalWindow) { - return Cancel(); - } - mWindow = globalWindow->AsInner(); - if (NS_WARN_IF(!mWindow)) { - return Cancel(); - } - - nsCOMPtr doc = mWindow->GetDoc(); - if (NS_WARN_IF(!doc)) { - return Cancel(); - } - - mPrincipal = doc->NodePrincipal(); - MOZ_ASSERT(mPrincipal); - - mRequester = new nsContentPermissionRequester(mWindow); - return nsContentPermissionUtils::AskPermission(this, mWindow); - } - - NS_IMETHOD Cancel() override - { - Resolve(false); - return NS_OK; - } - - NS_IMETHOD Allow(JS::HandleValue aChoices) override - { - MOZ_ASSERT(aChoices.isUndefined()); - Resolve(true); - return NS_OK; - } - - NS_IMETHOD GetTypes(nsIArray** aTypes) override - { - nsTArray emptyOptions; - return nsContentPermissionUtils::CreatePermissionArray(NS_LITERAL_CSTRING("flyweb-publish-server"), - NS_LITERAL_CSTRING("unused"), emptyOptions, aTypes); - } - - NS_IMETHOD GetRequester(nsIContentPermissionRequester** aRequester) override - { - NS_ENSURE_ARG_POINTER(aRequester); - nsCOMPtr requester = mRequester; - requester.forget(aRequester); - return NS_OK; - } - - NS_IMETHOD GetPrincipal(nsIPrincipal** aRequestingPrincipal) override - { - NS_IF_ADDREF(*aRequestingPrincipal = mPrincipal); - return NS_OK; - } - - NS_IMETHOD GetWindow(mozIDOMWindow** aRequestingWindow) override - { - NS_IF_ADDREF(*aRequestingWindow = mWindow); - return NS_OK; - } - - NS_IMETHOD GetElement(nsIDOMElement** aRequestingElement) override - { - *aRequestingElement = nullptr; - return NS_OK; - } - -private: - void Resolve(bool aResolve) - { - mServer->PermissionGranted(aResolve); - } - - virtual ~FlyWebPublishServerPermissionCheck() = default; - - nsCString mServiceName; - uint64_t mWindowID; - RefPtr mServer; - nsCOMPtr mWindow; - nsCOMPtr mPrincipal; - nsCOMPtr mRequester; -}; - -NS_IMPL_ISUPPORTS(FlyWebPublishServerPermissionCheck, - nsIContentPermissionRequest, - nsIRunnable) - -class FlyWebMDNSService final - : public nsIDNSServiceDiscoveryListener - , public nsIDNSServiceResolveListener - , public nsIDNSRegistrationListener - , public nsITimerCallback -{ - friend class FlyWebService; - -private: - enum DiscoveryState { - DISCOVERY_IDLE, - DISCOVERY_STARTING, - DISCOVERY_RUNNING, - DISCOVERY_STOPPING - }; - -public: - NS_DECL_ISUPPORTS - NS_DECL_NSIDNSSERVICEDISCOVERYLISTENER - NS_DECL_NSIDNSSERVICERESOLVELISTENER - NS_DECL_NSIDNSREGISTRATIONLISTENER - NS_DECL_NSITIMERCALLBACK - - explicit FlyWebMDNSService(FlyWebService* aService, - const nsACString& aServiceType); - -private: - virtual ~FlyWebMDNSService() = default; - - nsresult Init(); - nsresult StartDiscovery(); - nsresult StopDiscovery(); - - void ListDiscoveredServices(nsTArray& aServices); - bool HasService(const nsAString& aServiceId); - nsresult PairWithService(const nsAString& aServiceId, - UniquePtr& aInfo); - - nsresult StartDiscoveryOf(FlyWebPublishedServerImpl* aServer); - - void EnsureDiscoveryStarted(); - void EnsureDiscoveryStopped(); - - // Cycle-breaking link to manager. - FlyWebService* mService; - nsCString mServiceType; - - // Indicates the desired state of the system. If mDiscoveryActive is true, - // it indicates that backend discovery "should be happening", and discovery - // events should be forwarded to listeners. - // If false, the backend discovery "should be idle", and any discovery events - // that show up should not be forwarded to listeners. - bool mDiscoveryActive; - - uint32_t mNumConsecutiveStartDiscoveryFailures; - - // Represents the internal discovery state as it relates to nsDNSServiceDiscovery. - // When mDiscoveryActive is true, this state will periodically loop from - // (IDLE => STARTING => RUNNING => STOPPING => IDLE). - DiscoveryState mDiscoveryState; - - nsCOMPtr mDiscoveryStartTimer; - nsCOMPtr mDiscoveryStopTimer; - nsCOMPtr mDNSServiceDiscovery; - nsCOMPtr mCancelDiscovery; - nsTHashtable mNewServiceSet; - - struct DiscoveredInfo - { - explicit DiscoveredInfo(nsIDNSServiceInfo* aDNSServiceInfo); - FlyWebDiscoveredService mService; - nsCOMPtr mDNSServiceInfo; - }; - nsClassHashtable mServiceMap; -}; - -void -LogDNSInfo(nsIDNSServiceInfo* aServiceInfo, const char* aFunc) -{ - if (!LOG_TEST_I()) { - return; - } - - nsCString tmp; - aServiceInfo->GetServiceName(tmp); - LOG_I("%s: serviceName=%s", aFunc, tmp.get()); - - aServiceInfo->GetHost(tmp); - LOG_I("%s: host=%s", aFunc, tmp.get()); - - aServiceInfo->GetAddress(tmp); - LOG_I("%s: address=%s", aFunc, tmp.get()); - - uint16_t port = -2; - aServiceInfo->GetPort(&port); - LOG_I("%s: port=%d", aFunc, (int)port); - - nsCOMPtr attributes; - aServiceInfo->GetAttributes(getter_AddRefs(attributes)); - if (!attributes) { - LOG_I("%s: no attributes", aFunc); - } else { - nsCOMPtr enumerator; - attributes->GetEnumerator(getter_AddRefs(enumerator)); - MOZ_ASSERT(enumerator); - - LOG_I("%s: attributes start", aFunc); - - bool hasMoreElements; - while (NS_SUCCEEDED(enumerator->HasMoreElements(&hasMoreElements)) && - hasMoreElements) { - nsCOMPtr element; - MOZ_ALWAYS_SUCCEEDS(enumerator->GetNext(getter_AddRefs(element))); - nsCOMPtr property = do_QueryInterface(element); - MOZ_ASSERT(property); - - nsAutoString name; - nsCOMPtr value; - MOZ_ALWAYS_SUCCEEDS(property->GetName(name)); - MOZ_ALWAYS_SUCCEEDS(property->GetValue(getter_AddRefs(value))); - - nsAutoCString str; - nsresult rv = value->GetAsACString(str); - if (NS_SUCCEEDED(rv)) { - LOG_I("%s: attribute name=%s value=%s", aFunc, - NS_ConvertUTF16toUTF8(name).get(), str.get()); - } else { - uint16_t type; - MOZ_ALWAYS_SUCCEEDS(value->GetDataType(&type)); - LOG_I("%s: attribute *unstringifiable* name=%s type=%d", aFunc, - NS_ConvertUTF16toUTF8(name).get(), (int)type); - } - } - - LOG_I("%s: attributes end", aFunc); - } -} - -NS_IMPL_ISUPPORTS(FlyWebMDNSService, - nsIDNSServiceDiscoveryListener, - nsIDNSServiceResolveListener, - nsIDNSRegistrationListener, - nsITimerCallback) - -FlyWebMDNSService::FlyWebMDNSService( - FlyWebService* aService, - const nsACString& aServiceType) - : mService(aService) - , mServiceType(aServiceType) - , mDiscoveryActive(false) - , mNumConsecutiveStartDiscoveryFailures(0) - , mDiscoveryState(DISCOVERY_IDLE) -{} - -nsresult -FlyWebMDNSService::OnDiscoveryStarted(const nsACString& aServiceType) -{ - MOZ_ASSERT(mDiscoveryState == DISCOVERY_STARTING); - mDiscoveryState = DISCOVERY_RUNNING; - // Reset consecutive start discovery failures. - mNumConsecutiveStartDiscoveryFailures = 0; - LOG_I("==========================================="); - LOG_I("MDNSService::OnDiscoveryStarted(%s)", PromiseFlatCString(aServiceType).get()); - LOG_I("==========================================="); - - // Clear the new service array. - mNewServiceSet.Clear(); - - // If service discovery is inactive, then stop network discovery immediately. - if (!mDiscoveryActive) { - // Set the stop timer to fire immediately. - Unused << NS_WARN_IF(NS_FAILED(mDiscoveryStopTimer->InitWithCallback(this, 0, nsITimer::TYPE_ONE_SHOT))); - return NS_OK; - } - - // Otherwise, set the stop timer to fire in 5 seconds. - Unused << NS_WARN_IF(NS_FAILED(mDiscoveryStopTimer->InitWithCallback(this, 5 * 1000, nsITimer::TYPE_ONE_SHOT))); - - return NS_OK; -} - -nsresult -FlyWebMDNSService::OnDiscoveryStopped(const nsACString& aServiceType) -{ - LOG_I("///////////////////////////////////////////"); - LOG_I("MDNSService::OnDiscoveryStopped(%s)", PromiseFlatCString(aServiceType).get()); - LOG_I("///////////////////////////////////////////"); - MOZ_ASSERT(mDiscoveryState == DISCOVERY_STOPPING); - mDiscoveryState = DISCOVERY_IDLE; - - // If service discovery is inactive, then discard all results and do not proceed. - if (!mDiscoveryActive) { - mServiceMap.Clear(); - mNewServiceSet.Clear(); - return NS_OK; - } - - // Process the service map, add to the pair map. - for (auto iter = mServiceMap.Iter(); !iter.Done(); iter.Next()) { - DiscoveredInfo* service = iter.UserData(); - - if (!mNewServiceSet.Contains(service->mService.mServiceId)) { - iter.Remove(); - } - } - - // Notify FlyWebService of changed service list. - mService->NotifyDiscoveredServicesChanged(); - - // Start discovery again immediately. - Unused << NS_WARN_IF(NS_FAILED(mDiscoveryStartTimer->InitWithCallback(this, 0, nsITimer::TYPE_ONE_SHOT))); - - return NS_OK; -} - -nsresult -FlyWebMDNSService::OnServiceFound(nsIDNSServiceInfo* aServiceInfo) -{ - LogDNSInfo(aServiceInfo, "FlyWebMDNSService::OnServiceFound"); - - // If discovery is not active, don't do anything with the result. - // If there is no discovery underway, ignore this. - if (!mDiscoveryActive || mDiscoveryState != DISCOVERY_RUNNING) { - return NS_OK; - } - - // Discovery is underway - resolve the service. - nsresult rv = mDNSServiceDiscovery->ResolveService(aServiceInfo, this); - NS_ENSURE_SUCCESS(rv, rv); - - return NS_OK; -} - -nsresult -FlyWebMDNSService::OnServiceLost(nsIDNSServiceInfo* aServiceInfo) -{ - LogDNSInfo(aServiceInfo, "FlyWebMDNSService::OnServiceLost"); - - return NS_OK; -} - -nsresult -FlyWebMDNSService::OnStartDiscoveryFailed(const nsACString& aServiceType, int32_t aErrorCode) -{ - LOG_E("MDNSService::OnStartDiscoveryFailed(%s): %d", PromiseFlatCString(aServiceType).get(), (int) aErrorCode); - - MOZ_ASSERT(mDiscoveryState == DISCOVERY_STARTING); - mDiscoveryState = DISCOVERY_IDLE; - mNumConsecutiveStartDiscoveryFailures++; - - // If discovery is active, and the number of consecutive failures is < 3, try starting again. - if (mDiscoveryActive && mNumConsecutiveStartDiscoveryFailures < 3) { - Unused << NS_WARN_IF(NS_FAILED(mDiscoveryStartTimer->InitWithCallback(this, 0, nsITimer::TYPE_ONE_SHOT))); - } - - return NS_OK; -} - -nsresult -FlyWebMDNSService::OnStopDiscoveryFailed(const nsACString& aServiceType, int32_t aErrorCode) -{ - LOG_E("MDNSService::OnStopDiscoveryFailed(%s)", PromiseFlatCString(aServiceType).get()); - MOZ_ASSERT(mDiscoveryState == DISCOVERY_STOPPING); - mDiscoveryState = DISCOVERY_IDLE; - - // If discovery is active, start discovery again immediately. - if (mDiscoveryActive) { - Unused << NS_WARN_IF(NS_FAILED(mDiscoveryStartTimer->InitWithCallback(this, 0, nsITimer::TYPE_ONE_SHOT))); - } - - return NS_OK; -} - -static bool -IsAcceptableServiceAddress(const nsCString& addr) -{ - PRNetAddr prNetAddr; - PRStatus status = PR_StringToNetAddr(addr.get(), &prNetAddr); - if (status == PR_FAILURE) { - return false; - } - // Only allow ipv4 addreses for now. - return prNetAddr.raw.family == PR_AF_INET; -} - -nsresult -FlyWebMDNSService::OnServiceResolved(nsIDNSServiceInfo* aServiceInfo) -{ - LogDNSInfo(aServiceInfo, "FlyWebMDNSService::OnServiceResolved"); - - // If discovery is not active, don't do anything with the result. - // If there is no discovery underway, ignore this resolve. - if (!mDiscoveryActive || mDiscoveryState != DISCOVERY_RUNNING) { - return NS_OK; - } - - nsresult rv; - - nsCString address; - rv = aServiceInfo->GetAddress(address); - if (NS_WARN_IF(NS_FAILED(rv))) { - return rv; - } - - if (!IsAcceptableServiceAddress(address)) { - return NS_OK; - } - - // Create a new serviceInfo and stuff it in the new service array. - UniquePtr svc(new DiscoveredInfo(aServiceInfo)); - mNewServiceSet.PutEntry(svc->mService.mServiceId); - - DiscoveredInfo* existingSvc = - mServiceMap.Get(svc->mService.mServiceId); - if (existingSvc) { - // Update the underlying DNS service info, but leave the old object in place. - existingSvc->mDNSServiceInfo = aServiceInfo; - } else { - DiscoveredInfo* info = svc.release(); - mServiceMap.Put(info->mService.mServiceId, info); - } - - // Notify FlyWebService of changed service list. - mService->NotifyDiscoveredServicesChanged(); - - return NS_OK; -} - -FlyWebMDNSService::DiscoveredInfo::DiscoveredInfo(nsIDNSServiceInfo* aDNSServiceInfo) - : mDNSServiceInfo(aDNSServiceInfo) -{ - nsCString tmp; - DebugOnly drv = aDNSServiceInfo->GetServiceName(tmp); - MOZ_ASSERT(NS_SUCCEEDED(drv)); - CopyUTF8toUTF16(tmp, mService.mDisplayName); - - mService.mTransport = NS_LITERAL_STRING("mdns"); - - drv = aDNSServiceInfo->GetServiceType(tmp); - MOZ_ASSERT(NS_SUCCEEDED(drv)); - CopyUTF8toUTF16(tmp, mService.mServiceType); - - nsCOMPtr attrs; - drv = aDNSServiceInfo->GetAttributes(getter_AddRefs(attrs)); - MOZ_ASSERT(NS_SUCCEEDED(drv)); - if (attrs) { - attrs->GetPropertyAsAString(NS_LITERAL_STRING("cert"), mService.mCert); - attrs->GetPropertyAsAString(NS_LITERAL_STRING("path"), mService.mPath); - } - - // Construct a service id from the name, host, address, and port. - nsCString cHost; - drv = aDNSServiceInfo->GetHost(cHost); - MOZ_ASSERT(NS_SUCCEEDED(drv)); - - nsCString cAddress; - drv = aDNSServiceInfo->GetAddress(cAddress); - MOZ_ASSERT(NS_SUCCEEDED(drv)); - - uint16_t port; - drv = aDNSServiceInfo->GetPort(&port); - MOZ_ASSERT(NS_SUCCEEDED(drv)); - nsAutoString portStr; - portStr.AppendInt(port, 10); - - mService.mServiceId = - NS_ConvertUTF8toUTF16(cAddress) + - NS_LITERAL_STRING(":") + - portStr + - NS_LITERAL_STRING("|") + - mService.mServiceType + - NS_LITERAL_STRING("|") + - NS_ConvertUTF8toUTF16(cHost) + - NS_LITERAL_STRING("|") + - mService.mDisplayName; -} - - -nsresult -FlyWebMDNSService::OnResolveFailed(nsIDNSServiceInfo* aServiceInfo, int32_t aErrorCode) -{ - LogDNSInfo(aServiceInfo, "FlyWebMDNSService::OnResolveFailed"); - - return NS_OK; -} - -nsresult -FlyWebMDNSService::OnServiceRegistered(nsIDNSServiceInfo* aServiceInfo) -{ - LogDNSInfo(aServiceInfo, "FlyWebMDNSService::OnServiceRegistered"); - - nsCString cName; - if (NS_WARN_IF(NS_FAILED(aServiceInfo->GetServiceName(cName)))) { - return NS_ERROR_FAILURE; - } - - nsString name = NS_ConvertUTF8toUTF16(cName); - RefPtr existingServer = - FlyWebService::GetOrCreate()->FindPublishedServerByName(name); - if (!existingServer) { - return NS_ERROR_FAILURE; - } - - existingServer->PublishedServerStarted(NS_OK); - - return NS_OK; -} - -nsresult -FlyWebMDNSService::OnServiceUnregistered(nsIDNSServiceInfo* aServiceInfo) -{ - LogDNSInfo(aServiceInfo, "FlyWebMDNSService::OnServiceUnregistered"); - - nsCString cName; - if (NS_WARN_IF(NS_FAILED(aServiceInfo->GetServiceName(cName)))) { - return NS_ERROR_FAILURE; - } - - nsString name = NS_ConvertUTF8toUTF16(cName); - RefPtr existingServer = - FlyWebService::GetOrCreate()->FindPublishedServerByName(name); - if (!existingServer) { - return NS_ERROR_FAILURE; - } - - LOG_I("OnServiceRegistered(MDNS): De-advertised server with name %s.", cName.get()); - - return NS_OK; -} - -nsresult -FlyWebMDNSService::OnRegistrationFailed(nsIDNSServiceInfo* aServiceInfo, int32_t errorCode) -{ - LogDNSInfo(aServiceInfo, "FlyWebMDNSService::OnRegistrationFailed"); - - nsCString cName; - if (NS_WARN_IF(NS_FAILED(aServiceInfo->GetServiceName(cName)))) { - return NS_ERROR_FAILURE; - } - - nsString name = NS_ConvertUTF8toUTF16(cName); - RefPtr existingServer = - FlyWebService::GetOrCreate()->FindPublishedServerByName(name); - if (!existingServer) { - return NS_ERROR_FAILURE; - } - - LOG_I("OnServiceRegistered(MDNS): Registration of server with name %s failed.", cName.get()); - - // Remove the nsICancelable from the published server. - existingServer->PublishedServerStarted(NS_ERROR_FAILURE); - return NS_OK; -} - -nsresult -FlyWebMDNSService::OnUnregistrationFailed(nsIDNSServiceInfo* aServiceInfo, int32_t errorCode) -{ - LogDNSInfo(aServiceInfo, "FlyWebMDNSService::OnUnregistrationFailed"); - - nsCString cName; - if (NS_WARN_IF(NS_FAILED(aServiceInfo->GetServiceName(cName)))) { - return NS_ERROR_FAILURE; - } - - nsString name = NS_ConvertUTF8toUTF16(cName); - RefPtr existingServer = - FlyWebService::GetOrCreate()->FindPublishedServerByName(name); - if (!existingServer) { - return NS_ERROR_FAILURE; - } - - LOG_I("OnServiceRegistered(MDNS): Un-Advertisement of server with name %s failed.", cName.get()); - return NS_OK; -} - -nsresult -FlyWebMDNSService::Notify(nsITimer* timer) -{ - if (timer == mDiscoveryStopTimer.get()) { - LOG_I("MDNSService::Notify() got discovery stop timeout"); - // Internet discovery stop timer has fired. - nsresult rv = StopDiscovery(); - if (NS_WARN_IF(NS_FAILED(rv))) { - return rv; - } - return NS_OK; - } - - if (timer == mDiscoveryStartTimer.get()) { - LOG_I("MDNSService::Notify() got discovery start timeout"); - // Internet discovery start timer has fired. - nsresult rv = StartDiscovery(); - if (NS_WARN_IF(NS_FAILED(rv))) { - return rv; - } - return NS_OK; - } - - LOG_E("MDNSService::Notify got unknown timeout."); - return NS_OK; -} - -nsresult -FlyWebMDNSService::Init() -{ - MOZ_ASSERT(mDiscoveryState == DISCOVERY_IDLE); - - mDiscoveryStartTimer = do_CreateInstance("@mozilla.org/timer;1"); - if (!mDiscoveryStartTimer) { - return NS_ERROR_FAILURE; - } - - mDiscoveryStopTimer = do_CreateInstance("@mozilla.org/timer;1"); - if (!mDiscoveryStopTimer) { - return NS_ERROR_FAILURE; - } - - nsresult rv; - mDNSServiceDiscovery = do_GetService(DNSSERVICEDISCOVERY_CONTRACT_ID, &rv); - if (NS_WARN_IF(NS_FAILED(rv))) { - return rv; - } - - return NS_OK; -} - -nsresult -FlyWebMDNSService::StartDiscovery() -{ - nsresult rv; - - // Always cancel the timer. - rv = mDiscoveryStartTimer->Cancel(); - if (NS_WARN_IF(NS_FAILED(rv))) { - LOG_E("FlyWeb failed to cancel DNS service discovery start timer."); - } - - // If discovery is not idle, don't start it. - if (mDiscoveryState != DISCOVERY_IDLE) { - return NS_OK; - } - - LOG_I("FlyWeb starting dicovery."); - mDiscoveryState = DISCOVERY_STARTING; - - // start the discovery. - rv = mDNSServiceDiscovery->StartDiscovery(mServiceType, this, - getter_AddRefs(mCancelDiscovery)); - if (NS_WARN_IF(NS_FAILED(rv))) { - LOG_E("FlyWeb failed to start DNS service discovery."); - return rv; - } - - return NS_OK; -} - -nsresult -FlyWebMDNSService::StopDiscovery() -{ - nsresult rv; - - // Always cancel the timer. - rv = mDiscoveryStopTimer->Cancel(); - if (NS_WARN_IF(NS_FAILED(rv))) { - LOG_E("FlyWeb failed to cancel DNS service discovery stop timer."); - } - - // If discovery is not running, do nothing. - if (mDiscoveryState != DISCOVERY_RUNNING) { - return NS_OK; - } - - LOG_I("FlyWeb stopping dicovery."); - - // Mark service discovery as stopping. - mDiscoveryState = DISCOVERY_STOPPING; - - if (mCancelDiscovery) { - LOG_I("MDNSService::StopDiscovery() - mCancelDiscovery exists!"); - nsCOMPtr cancelDiscovery = mCancelDiscovery.forget(); - rv = cancelDiscovery->Cancel(NS_ERROR_ABORT); - if (NS_WARN_IF(NS_FAILED(rv))) { - LOG_E("FlyWeb failed to cancel DNS stop service discovery."); - } - } else { - LOG_I("MDNSService::StopDiscovery() - mCancelDiscovery does not exist!"); - mDiscoveryState = DISCOVERY_IDLE; - } - - return NS_OK; -} - -void -FlyWebMDNSService::ListDiscoveredServices(nsTArray& aServices) -{ - for (auto iter = mServiceMap.Iter(); !iter.Done(); iter.Next()) { - aServices.AppendElement(iter.UserData()->mService); - } -} - -bool -FlyWebMDNSService::HasService(const nsAString& aServiceId) -{ - return mServiceMap.Contains(aServiceId); -} - -nsresult -FlyWebMDNSService::PairWithService(const nsAString& aServiceId, - UniquePtr& aInfo) -{ - MOZ_ASSERT(HasService(aServiceId)); - - nsresult rv; - nsCOMPtr uuidgen = - do_GetService("@mozilla.org/uuid-generator;1", &rv); - NS_ENSURE_SUCCESS(rv, rv); - - nsID id; - rv = uuidgen->GenerateUUIDInPlace(&id); - NS_ENSURE_SUCCESS(rv, rv); - - aInfo.reset(new FlyWebService::PairedInfo()); - - char uuidChars[NSID_LENGTH]; - id.ToProvidedString(uuidChars); - CopyUTF8toUTF16(Substring(uuidChars + 1, uuidChars + NSID_LENGTH - 2), - aInfo->mService.mHostname); - - DiscoveredInfo* discInfo = mServiceMap.Get(aServiceId); - - nsAutoString url; - if (discInfo->mService.mCert.IsEmpty()) { - url.AssignLiteral("http://"); - } else { - url.AssignLiteral("https://"); - } - url.Append(aInfo->mService.mHostname + NS_LITERAL_STRING("/")); - nsCOMPtr uiURL; - NS_NewURI(getter_AddRefs(uiURL), url); - MOZ_ASSERT(uiURL); - if (!discInfo->mService.mPath.IsEmpty()) { - nsCOMPtr tmp = uiURL.forget(); - NS_NewURI(getter_AddRefs(uiURL), discInfo->mService.mPath, nullptr, tmp); - } - if (uiURL) { - nsAutoCString spec; - uiURL->GetSpec(spec); - CopyUTF8toUTF16(spec, aInfo->mService.mUiUrl); - } - - aInfo->mService.mDiscoveredService = discInfo->mService; - aInfo->mDNSServiceInfo = discInfo->mDNSServiceInfo; - - return NS_OK; -} - -nsresult -FlyWebMDNSService::StartDiscoveryOf(FlyWebPublishedServerImpl* aServer) -{ - - RefPtr existingServer = - FlyWebService::GetOrCreate()->FindPublishedServerByName(aServer->Name()); - MOZ_ASSERT(existingServer); - - // Advertise the service via mdns. - RefPtr serviceInfo(new net::nsDNSServiceInfo()); - - serviceInfo->SetPort(aServer->Port()); - serviceInfo->SetServiceType(mServiceType); - - nsCString certKey; - aServer->GetCertKey(certKey); - nsString uiURL; - aServer->GetUiUrl(uiURL); - - if (!uiURL.IsEmpty() || !certKey.IsEmpty()) { - RefPtr attrs = new nsHashPropertyBag(); - if (!uiURL.IsEmpty()) { - attrs->SetPropertyAsAString(NS_LITERAL_STRING("path"), uiURL); - } - if (!certKey.IsEmpty()) { - attrs->SetPropertyAsACString(NS_LITERAL_STRING("cert"), certKey); - } - serviceInfo->SetAttributes(attrs); - } - - nsCString cstrName = NS_ConvertUTF16toUTF8(aServer->Name()); - LOG_I("MDNSService::StartDiscoveryOf() advertising service %s", cstrName.get()); - serviceInfo->SetServiceName(cstrName); - - LogDNSInfo(serviceInfo, "FlyWebMDNSService::StartDiscoveryOf"); - - // Advertise the service. - nsCOMPtr cancelRegister; - nsresult rv = mDNSServiceDiscovery-> - RegisterService(serviceInfo, this, getter_AddRefs(cancelRegister)); - NS_ENSURE_SUCCESS(rv, rv); - - // All done. - aServer->SetCancelRegister(cancelRegister); - - return NS_OK; -} - -void -FlyWebMDNSService::EnsureDiscoveryStarted() -{ - mDiscoveryActive = true; - // If state is idle, start discovery immediately. - if (mDiscoveryState == DISCOVERY_IDLE) { - StartDiscovery(); - } -} - -void -FlyWebMDNSService::EnsureDiscoveryStopped() -{ - // All we need to do is set the flag to false. - // If current state is IDLE, it's already the correct state. - // Otherwise, the handlers for the internal state - // transitions will check this flag and drive the state - // towards IDLE. - mDiscoveryActive = false; -} - -static StaticRefPtr gFlyWebService; - -NS_IMPL_ISUPPORTS(FlyWebService, nsIObserver) - -FlyWebService::FlyWebService() - : mMonitor("FlyWebService::mMonitor") -{ - MOZ_ASSERT(NS_IsMainThread()); - nsCOMPtr obs = mozilla::services::GetObserverService(); - if (obs) { - obs->AddObserver(this, "inner-window-destroyed", false); - } -} - -FlyWebService::~FlyWebService() -{ -} - -FlyWebService* -FlyWebService::GetExisting() -{ - return gFlyWebService; -} - -FlyWebService* -FlyWebService::GetOrCreate() -{ - if (!gFlyWebService) { - gFlyWebService = new FlyWebService(); - ClearOnShutdown(&gFlyWebService); - ErrorResult rv = gFlyWebService->Init(); - if (rv.Failed()) { - gFlyWebService = nullptr; - return nullptr; - } - } - return gFlyWebService; -} - -ErrorResult -FlyWebService::Init() -{ - // Most functions of FlyWebService should not be started in the child. - // Instead FlyWebService in the child is mainly responsible for tracking - // publishedServer lifetimes. Other functions are handled by the - // FlyWebService running in the parent. - if (XRE_GetProcessType() == GeckoProcessType_Content) { - return ErrorResult(NS_OK); - } - - MOZ_ASSERT(NS_IsMainThread()); - if (!mMDNSHttpService) { - mMDNSHttpService = new FlyWebMDNSService(this, NS_LITERAL_CSTRING("_http._tcp.")); - ErrorResult rv; - - rv = mMDNSHttpService->Init(); - if (rv.Failed()) { - LOG_E("FlyWebService failed to initialize MDNS _http._tcp."); - mMDNSHttpService = nullptr; - rv.SuppressException(); - } - } - - if (!mMDNSFlywebService) { - mMDNSFlywebService = new FlyWebMDNSService(this, NS_LITERAL_CSTRING("_flyweb._tcp.")); - ErrorResult rv; - - rv = mMDNSFlywebService->Init(); - if (rv.Failed()) { - LOG_E("FlyWebService failed to initialize MDNS _flyweb._tcp."); - mMDNSFlywebService = nullptr; - rv.SuppressException(); - } - } - - return ErrorResult(NS_OK); -} - -static already_AddRefed -MakeRejectionPromise(const char* name) -{ - MozPromiseHolder holder; - RefPtr promise = holder.Ensure(name); - holder.Reject(NS_ERROR_FAILURE, name); - return promise.forget(); -} - -static bool -CheckForFlyWebAddon(const nsACString& uriString) -{ - // Before proceeding, ensure that the FlyWeb system addon exists. - nsresult rv; - nsCOMPtr uri; - rv = NS_NewURI(getter_AddRefs(uri), uriString); - if (NS_FAILED(rv)) { - return false; - } - - JSAddonId *addonId = MapURIToAddonID(uri); - if (!addonId) { - return false; - } - - JSFlatString* flat = JS_ASSERT_STRING_IS_FLAT(JS::StringOfAddonId(addonId)); - nsAutoString addonIdString; - AssignJSFlatString(addonIdString, flat); - if (!addonIdString.EqualsLiteral("flyweb@mozilla.org")) { - nsCString addonIdCString = NS_ConvertUTF16toUTF8(addonIdString); - return false; - } - - return true; -} - -already_AddRefed -FlyWebService::PublishServer(const nsAString& aName, - const FlyWebPublishOptions& aOptions, - nsPIDOMWindowInner* aWindow) -{ - // Scan uiUrl for illegal characters - - RefPtr existingServer = - FlyWebService::GetOrCreate()->FindPublishedServerByName(aName); - if (existingServer) { - LOG_I("PublishServer: Trying to publish server with already-existing name %s.", - NS_ConvertUTF16toUTF8(aName).get()); - return MakeRejectionPromise(__func__); - } - - RefPtr server; - if (XRE_GetProcessType() == GeckoProcessType_Content) { - server = new FlyWebPublishedServerChild(aWindow, aName, aOptions); - } else { - server = new FlyWebPublishedServerImpl(aWindow, aName, aOptions); - - // Before proceeding, ensure that the FlyWeb system addon exists. - if (!CheckForFlyWebAddon(NS_LITERAL_CSTRING("chrome://flyweb/skin/icon-64.png")) && - !CheckForFlyWebAddon(NS_LITERAL_CSTRING("chrome://flyweb/content/icon-64.png"))) - { - LOG_E("PublishServer: Failed to find FlyWeb system addon."); - return MakeRejectionPromise(__func__); - } - } - - if (aWindow) { - nsresult rv; - - MOZ_ASSERT(NS_IsMainThread()); - rv = NS_DispatchToCurrentThread( - MakeAndAddRef( - NS_ConvertUTF16toUTF8(aName), aWindow->WindowID(), server)); - if (NS_WARN_IF(NS_FAILED(rv))) { - LOG_E("PublishServer: Failed to dispatch permission check runnable for %s", - NS_ConvertUTF16toUTF8(aName).get()); - return MakeRejectionPromise(__func__); - } - } else { - // If aWindow is null, we're definitely in the e10s parent process. - // In this case, we know that permission has already been granted - // by the user because of content-process prompt. - MOZ_ASSERT(XRE_GetProcessType() == GeckoProcessType_Default); - server->PermissionGranted(true); - } - - mServers.AppendElement(server); - - return server->GetPublishPromise(); -} - -already_AddRefed -FlyWebService::FindPublishedServerByName( - const nsAString& aName) -{ - MOZ_ASSERT(NS_IsMainThread()); - for (FlyWebPublishedServer* publishedServer : mServers) { - if (publishedServer->Name().Equals(aName)) { - RefPtr server = publishedServer; - return server.forget(); - } - } - return nullptr; -} - -void -FlyWebService::RegisterDiscoveryManager(FlyWebDiscoveryManager* aDiscoveryManager) -{ - MOZ_ASSERT(NS_IsMainThread()); - mDiscoveryManagerTable.PutEntry(aDiscoveryManager); - if (mMDNSHttpService) { - mMDNSHttpService->EnsureDiscoveryStarted(); - } - if (mMDNSFlywebService) { - mMDNSFlywebService->EnsureDiscoveryStarted(); - } -} - -void -FlyWebService::UnregisterDiscoveryManager(FlyWebDiscoveryManager* aDiscoveryManager) -{ - MOZ_ASSERT(NS_IsMainThread()); - mDiscoveryManagerTable.RemoveEntry(aDiscoveryManager); - if (mDiscoveryManagerTable.IsEmpty()) { - if (mMDNSHttpService) { - mMDNSHttpService->EnsureDiscoveryStopped(); - } - if (mMDNSFlywebService) { - mMDNSFlywebService->EnsureDiscoveryStopped(); - } - } -} - -NS_IMETHODIMP -FlyWebService::Observe(nsISupports* aSubject, const char* aTopic, - const char16_t* aData) -{ - MOZ_ASSERT(NS_IsMainThread()); - if (strcmp(aTopic, "inner-window-destroyed")) { - return NS_OK; - } - - nsCOMPtr wrapper = do_QueryInterface(aSubject); - NS_ENSURE_TRUE(wrapper, NS_ERROR_FAILURE); - - uint64_t innerID; - nsresult rv = wrapper->GetData(&innerID); - NS_ENSURE_SUCCESS(rv, rv); - - for (FlyWebPublishedServer* server : mServers) { - if (server->OwnerWindowID() == innerID) { - server->Close(); - } - } - - return NS_OK; -} - -void -FlyWebService::UnregisterServer(FlyWebPublishedServer* aServer) -{ - MOZ_ASSERT(NS_IsMainThread()); - DebugOnly removed = mServers.RemoveElement(aServer); - MOZ_ASSERT(removed); -} - -bool -FlyWebService::HasConnectionOrServer(uint64_t aWindowID) -{ - MOZ_ASSERT(NS_IsMainThread()); - for (FlyWebPublishedServer* server : mServers) { - nsPIDOMWindowInner* win = server->GetOwner(); - if (win && win->WindowID() == aWindowID) { - return true; - } - } - - return false; -} - -void -FlyWebService::NotifyDiscoveredServicesChanged() -{ - // Process the service map, add to the pair map. - for (auto iter = mDiscoveryManagerTable.Iter(); !iter.Done(); iter.Next()) { - iter.Get()->GetKey()->NotifyDiscoveredServicesChanged(); - } -} - -void -FlyWebService::ListDiscoveredServices(nsTArray& aServices) -{ - MOZ_ASSERT(NS_IsMainThread()); - if (mMDNSHttpService) { - mMDNSHttpService->ListDiscoveredServices(aServices); - } - if (mMDNSFlywebService) { - mMDNSFlywebService->ListDiscoveredServices(aServices); - } -} - -void -FlyWebService::PairWithService(const nsAString& aServiceId, - FlyWebPairingCallback& aCallback) -{ - MOZ_ASSERT(NS_IsMainThread()); - // See if we have already paired with this service. If so, re-use the - // FlyWebPairedService for that. - { - ReentrantMonitorAutoEnter pairedMapLock(mMonitor); - for (auto iter = mPairedServiceTable.Iter(); !iter.Done(); iter.Next()) { - PairedInfo* pairInfo = iter.UserData(); - if (pairInfo->mService.mDiscoveredService.mServiceId.Equals(aServiceId)) { - ErrorResult er; - ReentrantMonitorAutoExit pairedMapRelease(mMonitor); - aCallback.PairingSucceeded(pairInfo->mService, er); - ENSURE_SUCCESS_VOID(er); - return; - } - } - } - - UniquePtr pairInfo; - - nsresult rv = NS_OK; - bool notFound = false; - if (mMDNSHttpService && mMDNSHttpService->HasService(aServiceId)) { - rv = mMDNSHttpService->PairWithService(aServiceId, pairInfo); - } else if (mMDNSFlywebService && mMDNSFlywebService->HasService(aServiceId)) { - rv = mMDNSFlywebService->PairWithService(aServiceId, pairInfo); - } else { - notFound = true; - } - - if (NS_FAILED(rv)) { - ErrorResult result; - result.Throw(rv); - const nsAString& reason = NS_LITERAL_STRING("Error pairing."); - aCallback.PairingFailed(reason, result); - ENSURE_SUCCESS_VOID(result); - return; - } - - if (!pairInfo) { - ErrorResult res; - const nsAString& reason = notFound ? - NS_LITERAL_STRING("No such service.") : - NS_LITERAL_STRING("Error pairing."); - aCallback.PairingFailed(reason, res); - ENSURE_SUCCESS_VOID(res); - return; - } - - // Add fingerprint to certificate override database. - if (!pairInfo->mService.mDiscoveredService.mCert.IsEmpty()) { - nsCOMPtr override = - do_GetService("@mozilla.org/security/certoverride;1"); - if (!override || - NS_FAILED(override->RememberTemporaryValidityOverrideUsingFingerprint( - NS_ConvertUTF16toUTF8(pairInfo->mService.mHostname), - -1, - NS_ConvertUTF16toUTF8(pairInfo->mService.mDiscoveredService.mCert), - nsICertOverrideService::ERROR_UNTRUSTED | - nsICertOverrideService::ERROR_MISMATCH))) { - ErrorResult res; - aCallback.PairingFailed(NS_LITERAL_STRING("Error adding certificate override."), res); - ENSURE_SUCCESS_VOID(res); - return; - } - } - - // Grab a weak reference to the PairedInfo so that we can - // use it even after ownership has been transferred to mPairedServiceTable - PairedInfo* pairInfoWeak = pairInfo.release(); - - { - ReentrantMonitorAutoEnter pairedMapLock(mMonitor); - mPairedServiceTable.Put( - NS_ConvertUTF16toUTF8(pairInfoWeak->mService.mHostname), pairInfoWeak); - } - - ErrorResult er; - aCallback.PairingSucceeded(pairInfoWeak->mService, er); - ENSURE_SUCCESS_VOID(er); -} - -nsresult -FlyWebService::CreateTransportForHost(const char **types, - uint32_t typeCount, - const nsACString &host, - int32_t port, - const nsACString &hostRoute, - int32_t portRoute, - nsIProxyInfo *proxyInfo, - nsISocketTransport **result) -{ - // This might be called on background threads - - *result = nullptr; - - nsCString ipAddrString; - uint16_t discPort; - - { - ReentrantMonitorAutoEnter pairedMapLock(mMonitor); - - PairedInfo* info = mPairedServiceTable.Get(host); - - if (!info) { - return NS_OK; - } - - // Get the ip address of the underlying service. - info->mDNSServiceInfo->GetAddress(ipAddrString); - info->mDNSServiceInfo->GetPort(&discPort); - } - - // Parse it into an NetAddr. - PRNetAddr prNetAddr; - PRStatus status = PR_StringToNetAddr(ipAddrString.get(), &prNetAddr); - NS_ENSURE_FALSE(status == PR_FAILURE, NS_ERROR_FAILURE); - - // Convert PRNetAddr to NetAddr. - mozilla::net::NetAddr netAddr; - PRNetAddrToNetAddr(&prNetAddr, &netAddr); - netAddr.inet.port = htons(discPort); - - RefPtr trans = new mozilla::net::nsSocketTransport(); - nsresult rv = trans->InitPreResolved( - types, typeCount, host, port, hostRoute, portRoute, proxyInfo, &netAddr); - NS_ENSURE_SUCCESS(rv, rv); - - trans.forget(result); - return NS_OK; -} - -void -FlyWebService::StartDiscoveryOf(FlyWebPublishedServerImpl* aServer) -{ - MOZ_ASSERT(NS_IsMainThread()); - nsresult rv = mMDNSFlywebService ? - mMDNSFlywebService->StartDiscoveryOf(aServer) : - NS_ERROR_FAILURE; - - if (NS_FAILED(rv)) { - aServer->PublishedServerStarted(rv); - } -} - -} // namespace dom -} // namespace mozilla diff --git a/dom/flyweb/FlyWebService.h b/dom/flyweb/FlyWebService.h deleted file mode 100644 index f7b9834402..0000000000 --- a/dom/flyweb/FlyWebService.h +++ /dev/null @@ -1,113 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_dom_FlyWebService_h -#define mozilla_dom_FlyWebService_h - -#include "nsISupportsImpl.h" -#include "mozilla/ErrorResult.h" -#include "nsIProtocolHandler.h" -#include "nsDataHashtable.h" -#include "nsClassHashtable.h" -#include "nsIObserver.h" -#include "mozilla/MozPromise.h" -#include "mozilla/ReentrantMonitor.h" -#include "mozilla/dom/FlyWebDiscoveryManagerBinding.h" -#include "nsITimer.h" -#include "nsICancelable.h" -#include "nsIDNSServiceDiscovery.h" - -class nsPIDOMWindowInner; -class nsIProxyInfo; -class nsISocketTransport; - -namespace mozilla { -namespace dom { - -struct FlyWebPublishOptions; -struct FlyWebFilter; -class FlyWebPublishedServer; -class FlyWebPublishedServerImpl; -class FlyWebPairingCallback; -class FlyWebDiscoveryManager; -class FlyWebMDNSService; - -typedef MozPromise, nsresult, false> - FlyWebPublishPromise; - -class FlyWebService final : public nsIObserver -{ - friend class FlyWebMDNSService; -public: - NS_DECL_THREADSAFE_ISUPPORTS - NS_DECL_NSIOBSERVER - - static FlyWebService* GetExisting(); - static FlyWebService* GetOrCreate(); - static already_AddRefed GetOrCreateAddRefed() - { - return do_AddRef(GetOrCreate()); - } - - already_AddRefed - PublishServer(const nsAString& aName, - const FlyWebPublishOptions& aOptions, - nsPIDOMWindowInner* aWindow); - - void UnregisterServer(FlyWebPublishedServer* aServer); - - bool HasConnectionOrServer(uint64_t aWindowID); - - void ListDiscoveredServices(nsTArray& aServices); - void PairWithService(const nsAString& aServiceId, FlyWebPairingCallback& aCallback); - nsresult CreateTransportForHost(const char **types, - uint32_t typeCount, - const nsACString &host, - int32_t port, - const nsACString &hostRoute, - int32_t portRoute, - nsIProxyInfo *proxyInfo, - nsISocketTransport **result); - - already_AddRefed FindPublishedServerByName( - const nsAString& aName); - - void RegisterDiscoveryManager(FlyWebDiscoveryManager* aDiscoveryManager); - void UnregisterDiscoveryManager(FlyWebDiscoveryManager* aDiscoveryManager); - - // Should only be called by FlyWebPublishedServerImpl - void StartDiscoveryOf(FlyWebPublishedServerImpl* aServer); - -private: - FlyWebService(); - ~FlyWebService(); - - ErrorResult Init(); - - void NotifyDiscoveredServicesChanged(); - - // Might want to make these hashes for perf - nsTArray mServers; - - RefPtr mMDNSHttpService; - RefPtr mMDNSFlywebService; - - struct PairedInfo - { - FlyWebPairedService mService; - nsCOMPtr mDNSServiceInfo; - }; - nsClassHashtable - mPairedServiceTable; - ReentrantMonitor mMonitor; // Protecting mPairedServiceTable - - nsTHashtable> mDiscoveryManagerTable; -}; - -} // namespace dom -} // namespace mozilla - -#endif // mozilla_dom_FlyWebService_h diff --git a/dom/flyweb/HttpServer.cpp b/dom/flyweb/HttpServer.cpp deleted file mode 100644 index 26e15d9d51..0000000000 --- a/dom/flyweb/HttpServer.cpp +++ /dev/null @@ -1,1319 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "mozilla/dom/HttpServer.h" -#include "nsISocketTransport.h" -#include "nsWhitespaceTokenizer.h" -#include "nsNetUtil.h" -#include "nsIStreamTransportService.h" -#include "nsIAsyncStreamCopier2.h" -#include "nsIPipe.h" -#include "nsIOService.h" -#include "nsIHttpChannelInternal.h" -#include "Base64.h" -#include "WebSocketChannel.h" -#include "nsCharSeparatedTokenizer.h" -#include "nsIX509Cert.h" - -static NS_DEFINE_CID(kStreamTransportServiceCID, NS_STREAMTRANSPORTSERVICE_CID); - -namespace mozilla { -namespace dom { - -static LazyLogModule gHttpServerLog("HttpServer"); -#undef LOG_I -#define LOG_I(...) MOZ_LOG(gHttpServerLog, mozilla::LogLevel::Debug, (__VA_ARGS__)) -#undef LOG_V -#define LOG_V(...) MOZ_LOG(gHttpServerLog, mozilla::LogLevel::Verbose, (__VA_ARGS__)) -#undef LOG_E -#define LOG_E(...) MOZ_LOG(gHttpServerLog, mozilla::LogLevel::Error, (__VA_ARGS__)) - - -NS_IMPL_ISUPPORTS(HttpServer, - nsIServerSocketListener, - nsILocalCertGetCallback) - -HttpServer::HttpServer() - : mPort() - , mHttps() -{ -} - -HttpServer::~HttpServer() -{ -} - -void -HttpServer::Init(int32_t aPort, bool aHttps, HttpServerListener* aListener) -{ - mPort = aPort; - mHttps = aHttps; - mListener = aListener; - - if (mHttps) { - nsCOMPtr lcs = - do_CreateInstance("@mozilla.org/security/local-cert-service;1"); - nsresult rv = lcs->GetOrCreateCert(NS_LITERAL_CSTRING("flyweb"), this); - if (NS_FAILED(rv)) { - NotifyStarted(rv); - } - } else { - // Make sure to always have an async step before notifying callbacks - HandleCert(nullptr, NS_OK); - } -} - -NS_IMETHODIMP -HttpServer::HandleCert(nsIX509Cert* aCert, nsresult aResult) -{ - nsresult rv = aResult; - if (NS_SUCCEEDED(rv)) { - rv = StartServerSocket(aCert); - } - - if (NS_FAILED(rv) && mServerSocket) { - mServerSocket->Close(); - mServerSocket = nullptr; - } - - NotifyStarted(rv); - - return NS_OK; -} - -void -HttpServer::NotifyStarted(nsresult aStatus) -{ - RefPtr listener = mListener; - nsCOMPtr event = NS_NewRunnableFunction([listener, aStatus] () - { - listener->OnServerStarted(aStatus); - }); - NS_DispatchToCurrentThread(event); -} - -nsresult -HttpServer::StartServerSocket(nsIX509Cert* aCert) -{ - nsresult rv; - mServerSocket = - do_CreateInstance(aCert ? "@mozilla.org/network/tls-server-socket;1" - : "@mozilla.org/network/server-socket;1", &rv); - NS_ENSURE_SUCCESS(rv, rv); - - rv = mServerSocket->Init(mPort, false, -1); - NS_ENSURE_SUCCESS(rv, rv); - - if (aCert) { - nsCOMPtr tls = do_QueryInterface(mServerSocket); - rv = tls->SetServerCert(aCert); - NS_ENSURE_SUCCESS(rv, rv); - - rv = tls->SetSessionTickets(false); - NS_ENSURE_SUCCESS(rv, rv); - - mCert = aCert; - } - - rv = mServerSocket->AsyncListen(this); - NS_ENSURE_SUCCESS(rv, rv); - - rv = mServerSocket->GetPort(&mPort); - NS_ENSURE_SUCCESS(rv, rv); - - LOG_I("HttpServer::StartServerSocket(%p)", this); - - return NS_OK; -} - -NS_IMETHODIMP -HttpServer::OnSocketAccepted(nsIServerSocket* aServ, - nsISocketTransport* aTransport) -{ - MOZ_ASSERT(SameCOMIdentity(aServ, mServerSocket)); - - nsresult rv; - RefPtr conn = new Connection(aTransport, this, rv); - NS_ENSURE_SUCCESS(rv, rv); - - LOG_I("HttpServer::OnSocketAccepted(%p) - Socket %p", this, conn.get()); - - mConnections.AppendElement(conn.forget()); - - return NS_OK; -} - -NS_IMETHODIMP -HttpServer::OnStopListening(nsIServerSocket* aServ, - nsresult aStatus) -{ - MOZ_ASSERT(aServ == mServerSocket || !mServerSocket); - - LOG_I("HttpServer::OnStopListening(%p) - status 0x%lx", this, aStatus); - - Close(); - - return NS_OK; -} - -void -HttpServer::SendResponse(InternalRequest* aRequest, InternalResponse* aResponse) -{ - for (Connection* conn : mConnections) { - if (conn->TryHandleResponse(aRequest, aResponse)) { - return; - } - } - - MOZ_ASSERT(false, "Unknown request"); -} - -already_AddRefed -HttpServer::AcceptWebSocket(InternalRequest* aConnectRequest, - const Optional& aProtocol, - ErrorResult& aRv) -{ - for (Connection* conn : mConnections) { - if (!conn->HasPendingWebSocketRequest(aConnectRequest)) { - continue; - } - nsCOMPtr provider = - conn->HandleAcceptWebSocket(aProtocol, aRv); - if (aRv.Failed()) { - conn->Close(); - } - // This connection is now owned by the websocket, or we just closed it - mConnections.RemoveElement(conn); - return provider.forget(); - } - - aRv.Throw(NS_ERROR_UNEXPECTED); - MOZ_ASSERT(false, "Unknown request"); - - return nullptr; -} - -void -HttpServer::SendWebSocketResponse(InternalRequest* aConnectRequest, - InternalResponse* aResponse) -{ - for (Connection* conn : mConnections) { - if (conn->HasPendingWebSocketRequest(aConnectRequest)) { - conn->HandleWebSocketResponse(aResponse); - return; - } - } - - MOZ_ASSERT(false, "Unknown request"); -} - -void -HttpServer::Close() -{ - if (mServerSocket) { - mServerSocket->Close(); - mServerSocket = nullptr; - } - - if (mListener) { - RefPtr listener = mListener.forget(); - listener->OnServerClose(); - } - - for (Connection* conn : mConnections) { - conn->Close(); - } - mConnections.Clear(); -} - -void -HttpServer::GetCertKey(nsACString& aKey) -{ - nsAutoString tmp; - if (mCert) { - mCert->GetSha256Fingerprint(tmp); - } - LossyCopyUTF16toASCII(tmp, aKey); -} - -NS_IMPL_ISUPPORTS(HttpServer::TransportProvider, - nsITransportProvider) - -HttpServer::TransportProvider::~TransportProvider() -{ -} - -NS_IMETHODIMP -HttpServer::TransportProvider::SetListener(nsIHttpUpgradeListener* aListener) -{ - MOZ_ASSERT(!mListener); - MOZ_ASSERT(aListener); - - mListener = aListener; - - MaybeNotify(); - - return NS_OK; -} - -NS_IMETHODIMP -HttpServer::TransportProvider::GetIPCChild(PTransportProviderChild** aChild) -{ - MOZ_CRASH("Don't call this in parent process"); - *aChild = nullptr; - return NS_OK; -} - -void -HttpServer::TransportProvider::SetTransport(nsISocketTransport* aTransport, - nsIAsyncInputStream* aInput, - nsIAsyncOutputStream* aOutput) -{ - MOZ_ASSERT(!mTransport); - MOZ_ASSERT(aTransport && aInput && aOutput); - - mTransport = aTransport; - mInput = aInput; - mOutput = aOutput; - - MaybeNotify(); -} - -void -HttpServer::TransportProvider::MaybeNotify() -{ - if (mTransport && mListener) { - RefPtr self = this; - nsCOMPtr event = NS_NewRunnableFunction([self, this] () - { - mListener->OnTransportAvailable(mTransport, mInput, mOutput); - }); - NS_DispatchToCurrentThread(event); - } -} - -NS_IMPL_ISUPPORTS(HttpServer::Connection, - nsIInputStreamCallback, - nsIOutputStreamCallback) - -HttpServer::Connection::Connection(nsISocketTransport* aTransport, - HttpServer* aServer, - nsresult& rv) - : mServer(aServer) - , mTransport(aTransport) - , mState(eRequestLine) - , mPendingReqVersion() - , mRemainingBodySize() - , mCloseAfterRequest(false) -{ - nsCOMPtr input; - rv = mTransport->OpenInputStream(0, 0, 0, getter_AddRefs(input)); - NS_ENSURE_SUCCESS_VOID(rv); - - mInput = do_QueryInterface(input); - - nsCOMPtr output; - rv = mTransport->OpenOutputStream(0, 0, 0, getter_AddRefs(output)); - NS_ENSURE_SUCCESS_VOID(rv); - - mOutput = do_QueryInterface(output); - - if (mServer->mHttps) { - SetSecurityObserver(true); - } else { - mInput->AsyncWait(this, 0, 0, NS_GetCurrentThread()); - } -} - -NS_IMETHODIMP -HttpServer::Connection::OnHandshakeDone(nsITLSServerSocket* aServer, - nsITLSClientStatus* aStatus) -{ - LOG_I("HttpServer::Connection::OnHandshakeDone(%p)", this); - - // XXX Verify connection security - - SetSecurityObserver(false); - mInput->AsyncWait(this, 0, 0, NS_GetCurrentThread()); - - return NS_OK; -} - -void -HttpServer::Connection::SetSecurityObserver(bool aListen) -{ - LOG_I("HttpServer::Connection::SetSecurityObserver(%p) - %s", this, - aListen ? "On" : "Off"); - - nsCOMPtr secInfo; - mTransport->GetSecurityInfo(getter_AddRefs(secInfo)); - nsCOMPtr tlsConnInfo = - do_QueryInterface(secInfo); - MOZ_ASSERT(tlsConnInfo); - tlsConnInfo->SetSecurityObserver(aListen ? this : nullptr); -} - -HttpServer::Connection::~Connection() -{ -} - -NS_IMETHODIMP -HttpServer::Connection::OnInputStreamReady(nsIAsyncInputStream* aStream) -{ - MOZ_ASSERT(!mInput || aStream == mInput); - - LOG_I("HttpServer::Connection::OnInputStreamReady(%p)", this); - - if (!mInput || mState == ePause) { - return NS_OK; - } - - uint64_t avail; - nsresult rv = mInput->Available(&avail); - if (NS_FAILED(rv)) { - LOG_I("HttpServer::Connection::OnInputStreamReady(%p) - Connection closed", this); - - mServer->mConnections.RemoveElement(this); - // Connection closed. Handle errors here. - return NS_OK; - } - - uint32_t numRead; - rv = mInput->ReadSegments(ReadSegmentsFunc, - this, - UINT32_MAX, - &numRead); - NS_ENSURE_SUCCESS(rv, rv); - - rv = mInput->AsyncWait(this, 0, 0, NS_GetCurrentThread()); - NS_ENSURE_SUCCESS(rv, rv); - - return NS_OK; -} - -nsresult -HttpServer::Connection::ReadSegmentsFunc(nsIInputStream* aIn, - void* aClosure, - const char* aBuffer, - uint32_t aToOffset, - uint32_t aCount, - uint32_t* aWriteCount) -{ - const char* buffer = aBuffer; - nsresult rv = static_cast(aClosure)-> - ConsumeInput(buffer, buffer + aCount); - - *aWriteCount = buffer - aBuffer; - MOZ_ASSERT(*aWriteCount <= aCount); - - return rv; -} - -static const char* -findCRLF(const char* aBuffer, const char* aEnd) -{ - if (aBuffer + 1 >= aEnd) { - return nullptr; - } - - const char* pos; - while ((pos = static_cast(memchr(aBuffer, - '\r', - aEnd - aBuffer - 1)))) { - if (*(pos + 1) == '\n') { - return pos; - } - aBuffer = pos + 1; - } - return nullptr; -} - -nsresult -HttpServer::Connection::ConsumeInput(const char*& aBuffer, - const char* aEnd) -{ - nsresult rv; - while (mState == eRequestLine || - mState == eHeaders) { - // Consume line-by-line - - // Check if buffer boundry ended up right between the CR and LF - if (!mInputBuffer.IsEmpty() && mInputBuffer.Last() == '\r' && - *aBuffer == '\n') { - aBuffer++; - rv = ConsumeLine(mInputBuffer.BeginReading(), mInputBuffer.Length() - 1); - NS_ENSURE_SUCCESS(rv, rv); - - mInputBuffer.Truncate(); - } - - // Look for a CRLF - const char* pos = findCRLF(aBuffer, aEnd); - if (!pos) { - mInputBuffer.Append(aBuffer, aEnd - aBuffer); - aBuffer = aEnd; - return NS_OK; - } - - if (!mInputBuffer.IsEmpty()) { - mInputBuffer.Append(aBuffer, pos - aBuffer); - aBuffer = pos + 2; - rv = ConsumeLine(mInputBuffer.BeginReading(), mInputBuffer.Length() - 1); - NS_ENSURE_SUCCESS(rv, rv); - - mInputBuffer.Truncate(); - } else { - rv = ConsumeLine(aBuffer, pos - aBuffer); - NS_ENSURE_SUCCESS(rv, rv); - - aBuffer = pos + 2; - } - } - - if (mState == eBody) { - uint32_t size = std::min(mRemainingBodySize, - static_cast(aEnd - aBuffer)); - uint32_t written = size; - - if (mCurrentRequestBody) { - rv = mCurrentRequestBody->Write(aBuffer, size, &written); - // Since we've given the pipe unlimited size, we should never - // end up needing to block. - MOZ_ASSERT(rv != NS_BASE_STREAM_WOULD_BLOCK); - if (NS_FAILED(rv)) { - written = size; - mCurrentRequestBody = nullptr; - } - } - - aBuffer += written; - mRemainingBodySize -= written; - if (!mRemainingBodySize) { - mCurrentRequestBody->Close(); - mCurrentRequestBody = nullptr; - mState = eRequestLine; - } - } - - return NS_OK; -} - -bool -ContainsToken(const nsCString& aList, const nsCString& aToken) -{ - nsCCharSeparatedTokenizer tokens(aList, ','); - bool found = false; - while (!found && tokens.hasMoreTokens()) { - found = tokens.nextToken().Equals(aToken); - } - return found; -} - -static bool -IsWebSocketRequest(InternalRequest* aRequest, uint32_t aHttpVersion) -{ - if (aHttpVersion < 1) { - return false; - } - - nsAutoCString str; - aRequest->GetMethod(str); - if (!str.EqualsLiteral("GET")) { - return false; - } - - InternalHeaders* headers = aRequest->Headers(); - ErrorResult res; - - headers->GetFirst(NS_LITERAL_CSTRING("upgrade"), str, res); - MOZ_ASSERT(!res.Failed()); - if (!str.EqualsLiteral("websocket")) { - return false; - } - - headers->GetFirst(NS_LITERAL_CSTRING("connection"), str, res); - MOZ_ASSERT(!res.Failed()); - if (!ContainsToken(str, NS_LITERAL_CSTRING("Upgrade"))) { - return false; - } - - headers->GetFirst(NS_LITERAL_CSTRING("sec-websocket-key"), str, res); - MOZ_ASSERT(!res.Failed()); - nsAutoCString binary; - if (NS_FAILED(Base64Decode(str, binary)) || binary.Length() != 16) { - return false; - } - - nsresult rv; - headers->GetFirst(NS_LITERAL_CSTRING("sec-websocket-version"), str, res); - MOZ_ASSERT(!res.Failed()); - if (str.ToInteger(&rv) != 13 || NS_FAILED(rv)) { - return false; - } - - return true; -} - -nsresult -HttpServer::Connection::ConsumeLine(const char* aBuffer, - size_t aLength) -{ - MOZ_ASSERT(mState == eRequestLine || - mState == eHeaders); - - if (MOZ_LOG_TEST(gHttpServerLog, mozilla::LogLevel::Verbose)) { - nsCString line(aBuffer, aLength); - LOG_V("HttpServer::Connection::ConsumeLine(%p) - \"%s\"", this, line.get()); - } - - if (mState == eRequestLine) { - LOG_V("HttpServer::Connection::ConsumeLine(%p) - Parsing request line", this); - NS_ENSURE_FALSE(mCloseAfterRequest, NS_ERROR_UNEXPECTED); - - if (aLength == 0) { - // Ignore empty lines before the request line - return NS_OK; - } - MOZ_ASSERT(!mPendingReq); - - // Process request line - nsCWhitespaceTokenizer tokens(Substring(aBuffer, aLength)); - - NS_ENSURE_TRUE(tokens.hasMoreTokens(), NS_ERROR_UNEXPECTED); - nsDependentCSubstring method = tokens.nextToken(); - NS_ENSURE_TRUE(NS_IsValidHTTPToken(method), NS_ERROR_UNEXPECTED); - NS_ENSURE_TRUE(tokens.hasMoreTokens(), NS_ERROR_UNEXPECTED); - nsDependentCSubstring url = tokens.nextToken(); - // Seems like it's also allowed to pass full urls with scheme+host+port. - // May need to support that. - NS_ENSURE_TRUE(url.First() == '/', NS_ERROR_UNEXPECTED); - mPendingReq = new InternalRequest(url, /* aURLFragment */ EmptyCString()); - mPendingReq->SetMethod(method); - NS_ENSURE_TRUE(tokens.hasMoreTokens(), NS_ERROR_UNEXPECTED); - nsDependentCSubstring version = tokens.nextToken(); - NS_ENSURE_TRUE(StringBeginsWith(version, NS_LITERAL_CSTRING("HTTP/1.")), - NS_ERROR_UNEXPECTED); - nsresult rv; - // This integer parsing is likely not strict enough. - nsCString reqVersion; - reqVersion = Substring(version, MOZ_ARRAY_LENGTH("HTTP/1.") - 1); - mPendingReqVersion = reqVersion.ToInteger(&rv); - NS_ENSURE_SUCCESS(rv, NS_ERROR_UNEXPECTED); - - NS_ENSURE_FALSE(tokens.hasMoreTokens(), NS_ERROR_UNEXPECTED); - - LOG_V("HttpServer::Connection::ConsumeLine(%p) - Parsed request line", this); - - mState = eHeaders; - - return NS_OK; - } - - if (aLength == 0) { - LOG_V("HttpServer::Connection::ConsumeLine(%p) - Found end of headers", this); - - MaybeAddPendingHeader(); - - ErrorResult res; - mPendingReq->Headers()->SetGuard(HeadersGuardEnum::Immutable, res); - - // Check for WebSocket - if (IsWebSocketRequest(mPendingReq, mPendingReqVersion)) { - LOG_V("HttpServer::Connection::ConsumeLine(%p) - Fire OnWebSocket", this); - - mState = ePause; - mPendingWebSocketRequest = mPendingReq.forget(); - mPendingReqVersion = 0; - - RefPtr listener = mServer->mListener; - RefPtr request = mPendingWebSocketRequest; - nsCOMPtr event = - NS_NewRunnableFunction([listener, request] () - { - listener->OnWebSocket(request); - }); - NS_DispatchToCurrentThread(event); - - return NS_OK; - } - - nsAutoCString header; - mPendingReq->Headers()->GetFirst(NS_LITERAL_CSTRING("connection"), - header, - res); - MOZ_ASSERT(!res.Failed()); - // 1.0 defaults to closing connections. - // 1.1 and higher defaults to keep-alive. - if (ContainsToken(header, NS_LITERAL_CSTRING("close")) || - (mPendingReqVersion == 0 && - !ContainsToken(header, NS_LITERAL_CSTRING("keep-alive")))) { - mCloseAfterRequest = true; - } - - mPendingReq->Headers()->GetFirst(NS_LITERAL_CSTRING("content-length"), - header, - res); - MOZ_ASSERT(!res.Failed()); - - LOG_V("HttpServer::Connection::ConsumeLine(%p) - content-length is \"%s\"", - this, header.get()); - - if (!header.IsEmpty()) { - nsresult rv; - mRemainingBodySize = header.ToInteger(&rv); - NS_ENSURE_SUCCESS(rv, rv); - } else { - mRemainingBodySize = 0; - } - - if (mRemainingBodySize) { - LOG_V("HttpServer::Connection::ConsumeLine(%p) - Starting consume body", this); - mState = eBody; - - // We use an unlimited buffer size here to ensure - // that we get to the next request even if the webpage hangs on - // to the request indefinitely without consuming the body. - nsCOMPtr input; - nsCOMPtr output; - nsresult rv = NS_NewPipe(getter_AddRefs(input), - getter_AddRefs(output), - 0, // Segment size - UINT32_MAX, // Unlimited buffer size - false, // not nonBlockingInput - true); // nonBlockingOutput - NS_ENSURE_SUCCESS(rv, rv); - - mCurrentRequestBody = do_QueryInterface(output); - mPendingReq->SetBody(input); - } else { - LOG_V("HttpServer::Connection::ConsumeLine(%p) - No body", this); - mState = eRequestLine; - } - - mPendingRequests.AppendElement(PendingRequest(mPendingReq, nullptr)); - - LOG_V("HttpServer::Connection::ConsumeLine(%p) - Fire OnRequest", this); - - RefPtr listener = mServer->mListener; - RefPtr request = mPendingReq.forget(); - nsCOMPtr event = - NS_NewRunnableFunction([listener, request] () - { - listener->OnRequest(request); - }); - NS_DispatchToCurrentThread(event); - - mPendingReqVersion = 0; - - return NS_OK; - } - - // Parse header line - if (aBuffer[0] == ' ' || aBuffer[0] == '\t') { - LOG_V("HttpServer::Connection::ConsumeLine(%p) - Add to header %s", - this, - mPendingHeaderName.get()); - - NS_ENSURE_FALSE(mPendingHeaderName.IsEmpty(), - NS_ERROR_UNEXPECTED); - - // We might need to do whitespace trimming/compression here. - mPendingHeaderValue.Append(aBuffer, aLength); - return NS_OK; - } - - MaybeAddPendingHeader(); - - const char* colon = static_cast(memchr(aBuffer, ':', aLength)); - NS_ENSURE_TRUE(colon, NS_ERROR_UNEXPECTED); - - ToLowerCase(Substring(aBuffer, colon - aBuffer), mPendingHeaderName); - mPendingHeaderValue.Assign(colon + 1, aLength - (colon - aBuffer) - 1); - - NS_ENSURE_TRUE(NS_IsValidHTTPToken(mPendingHeaderName), - NS_ERROR_UNEXPECTED); - - LOG_V("HttpServer::Connection::ConsumeLine(%p) - Parsed header %s", - this, - mPendingHeaderName.get()); - - return NS_OK; -} - -void -HttpServer::Connection::MaybeAddPendingHeader() -{ - if (mPendingHeaderName.IsEmpty()) { - return; - } - - // We might need to do more whitespace trimming/compression here. - mPendingHeaderValue.Trim(" \t"); - - ErrorResult rv; - mPendingReq->Headers()->Append(mPendingHeaderName, mPendingHeaderValue, rv); - mPendingHeaderName.Truncate(); -} - -bool -HttpServer::Connection::TryHandleResponse(InternalRequest* aRequest, - InternalResponse* aResponse) -{ - bool handledResponse = false; - for (uint32_t i = 0; i < mPendingRequests.Length(); ++i) { - PendingRequest& pending = mPendingRequests[i]; - if (pending.first() == aRequest) { - MOZ_ASSERT(!handledResponse); - MOZ_ASSERT(!pending.second()); - - pending.second() = aResponse; - if (i != 0) { - return true; - } - handledResponse = true; - } - - if (handledResponse && !pending.second()) { - // Shortcut if we've handled the response, and - // we don't have more responses to send - return true; - } - - if (i == 0 && pending.second()) { - RefPtr resp = pending.second().forget(); - mPendingRequests.RemoveElementAt(0); - QueueResponse(resp); - --i; - } - } - - return handledResponse; -} - -already_AddRefed -HttpServer::Connection::HandleAcceptWebSocket(const Optional& aProtocol, - ErrorResult& aRv) -{ - MOZ_ASSERT(mPendingWebSocketRequest); - - RefPtr response = - new InternalResponse(101, NS_LITERAL_CSTRING("Switching Protocols")); - - InternalHeaders* headers = response->Headers(); - headers->Set(NS_LITERAL_CSTRING("Upgrade"), - NS_LITERAL_CSTRING("websocket"), - aRv); - headers->Set(NS_LITERAL_CSTRING("Connection"), - NS_LITERAL_CSTRING("Upgrade"), - aRv); - if (aProtocol.WasPassed()) { - NS_ConvertUTF16toUTF8 protocol(aProtocol.Value()); - nsAutoCString reqProtocols; - mPendingWebSocketRequest->Headers()-> - GetFirst(NS_LITERAL_CSTRING("Sec-WebSocket-Protocol"), reqProtocols, aRv); - if (!ContainsToken(reqProtocols, protocol)) { - // Should throw a better error here - aRv.Throw(NS_ERROR_FAILURE); - return nullptr; - } - - headers->Set(NS_LITERAL_CSTRING("Sec-WebSocket-Protocol"), - protocol, aRv); - } - - nsAutoCString key, hash; - mPendingWebSocketRequest->Headers()-> - GetFirst(NS_LITERAL_CSTRING("Sec-WebSocket-Key"), key, aRv); - nsresult rv = mozilla::net::CalculateWebSocketHashedSecret(key, hash); - if (NS_FAILED(rv)) { - aRv.Throw(rv); - return nullptr; - } - headers->Set(NS_LITERAL_CSTRING("Sec-WebSocket-Accept"), hash, aRv); - - nsAutoCString extensions, negotiatedExtensions; - mPendingWebSocketRequest->Headers()-> - GetFirst(NS_LITERAL_CSTRING("Sec-WebSocket-Extensions"), extensions, aRv); - mozilla::net::ProcessServerWebSocketExtensions(extensions, - negotiatedExtensions); - if (!negotiatedExtensions.IsEmpty()) { - headers->Set(NS_LITERAL_CSTRING("Sec-WebSocket-Extensions"), - negotiatedExtensions, aRv); - } - - RefPtr result = new TransportProvider(); - mWebSocketTransportProvider = result; - - QueueResponse(response); - - return result.forget(); -} - -void -HttpServer::Connection::HandleWebSocketResponse(InternalResponse* aResponse) -{ - MOZ_ASSERT(mPendingWebSocketRequest); - - mState = eRequestLine; - mPendingWebSocketRequest = nullptr; - mInput->AsyncWait(this, 0, 0, NS_GetCurrentThread()); - - QueueResponse(aResponse); -} - -void -HttpServer::Connection::QueueResponse(InternalResponse* aResponse) -{ - bool chunked = false; - - RefPtr headers = new InternalHeaders(*aResponse->Headers()); - { - ErrorResult res; - headers->SetGuard(HeadersGuardEnum::None, res); - } - nsCOMPtr body; - int64_t bodySize; - aResponse->GetBody(getter_AddRefs(body), &bodySize); - - if (body && bodySize >= 0) { - nsCString sizeStr; - sizeStr.AppendInt(bodySize); - - LOG_V("HttpServer::Connection::QueueResponse(%p) - " - "Setting content-length to %s", - this, sizeStr.get()); - - ErrorResult res; - headers->Set(NS_LITERAL_CSTRING("content-length"), sizeStr, res); - } else if (body) { - // Use chunked transfer encoding - LOG_V("HttpServer::Connection::QueueResponse(%p) - Chunked transfer-encoding", - this); - - ErrorResult res; - headers->Set(NS_LITERAL_CSTRING("transfer-encoding"), - NS_LITERAL_CSTRING("chunked"), - res); - headers->Delete(NS_LITERAL_CSTRING("content-length"), res); - chunked = true; - - } else { - LOG_V("HttpServer::Connection::QueueResponse(%p) - " - "No body - setting content-length to 0", this); - - ErrorResult res; - headers->Set(NS_LITERAL_CSTRING("content-length"), - NS_LITERAL_CSTRING("0"), res); - } - - nsCString head(NS_LITERAL_CSTRING("HTTP/1.1 ")); - head.AppendInt(aResponse->GetStatus()); - // XXX is the statustext security checked? - head.Append(NS_LITERAL_CSTRING(" ") + - aResponse->GetStatusText() + - NS_LITERAL_CSTRING("\r\n")); - - AutoTArray entries; - headers->GetEntries(entries); - - for (auto header : entries) { - head.Append(header.mName + - NS_LITERAL_CSTRING(": ") + - header.mValue + - NS_LITERAL_CSTRING("\r\n")); - } - - head.Append(NS_LITERAL_CSTRING("\r\n")); - - mOutputBuffers.AppendElement()->mString = head; - if (body) { - OutputBuffer* bodyBuffer = mOutputBuffers.AppendElement(); - bodyBuffer->mStream = body; - bodyBuffer->mChunked = chunked; - } - - OnOutputStreamReady(mOutput); -} - -namespace { - -typedef MozPromise StreamCopyPromise; - -class StreamCopier final : public nsIOutputStreamCallback - , public nsIInputStreamCallback - , public nsIRunnable -{ -public: - static RefPtr - Copy(nsIInputStream* aSource, nsIAsyncOutputStream* aSink, - bool aChunked) - { - RefPtr copier = new StreamCopier(aSource, aSink, aChunked); - - RefPtr p = copier->mPromise.Ensure(__func__); - - nsresult rv = copier->mTarget->Dispatch(copier, NS_DISPATCH_NORMAL); - if (NS_FAILED(rv)) { - copier->mPromise.Resolve(rv, __func__); - } - - return p; - } - - NS_DECL_THREADSAFE_ISUPPORTS - NS_DECL_NSIINPUTSTREAMCALLBACK - NS_DECL_NSIOUTPUTSTREAMCALLBACK - NS_DECL_NSIRUNNABLE - -private: - StreamCopier(nsIInputStream* aSource, nsIAsyncOutputStream* aSink, - bool aChunked) - : mSource(aSource) - , mAsyncSource(do_QueryInterface(aSource)) - , mSink(aSink) - , mTarget(do_GetService(NS_STREAMTRANSPORTSERVICE_CONTRACTID)) - , mChunkRemaining(0) - , mChunked(aChunked) - , mAddedFinalSeparator(false) - , mFirstChunk(aChunked) - { - } - ~StreamCopier() {} - - static nsresult FillOutputBufferHelper(nsIOutputStream* aOutStr, - void* aClosure, - char* aBuffer, - uint32_t aOffset, - uint32_t aCount, - uint32_t* aCountRead); - nsresult FillOutputBuffer(char* aBuffer, - uint32_t aCount, - uint32_t* aCountRead); - - nsCOMPtr mSource; - nsCOMPtr mAsyncSource; - nsCOMPtr mSink; - MozPromiseHolder mPromise; - nsCOMPtr mTarget; // XXX we should cache this somewhere - uint32_t mChunkRemaining; - nsCString mSeparator; - bool mChunked; - bool mAddedFinalSeparator; - bool mFirstChunk; -}; - -NS_IMPL_ISUPPORTS(StreamCopier, - nsIOutputStreamCallback, - nsIInputStreamCallback, - nsIRunnable) - -struct WriteState -{ - StreamCopier* copier; - nsresult sourceRv; -}; - -// This function only exists to enable FillOutputBuffer to be a non-static -// function where we can use member variables more easily. -nsresult -StreamCopier::FillOutputBufferHelper(nsIOutputStream* aOutStr, - void* aClosure, - char* aBuffer, - uint32_t aOffset, - uint32_t aCount, - uint32_t* aCountRead) -{ - WriteState* ws = static_cast(aClosure); - ws->sourceRv = ws->copier->FillOutputBuffer(aBuffer, aCount, aCountRead); - return ws->sourceRv; -} - -nsresult -CheckForEOF(nsIInputStream* aIn, - void* aClosure, - const char* aBuffer, - uint32_t aToOffset, - uint32_t aCount, - uint32_t* aWriteCount) -{ - *static_cast(aClosure) = true; - *aWriteCount = 0; - return NS_BINDING_ABORTED; -} - -nsresult -StreamCopier::FillOutputBuffer(char* aBuffer, - uint32_t aCount, - uint32_t* aCountRead) -{ - nsresult rv = NS_OK; - while (mChunked && mSeparator.IsEmpty() && !mChunkRemaining && - !mAddedFinalSeparator) { - uint64_t avail; - rv = mSource->Available(&avail); - if (rv == NS_BASE_STREAM_CLOSED) { - avail = 0; - rv = NS_OK; - } - NS_ENSURE_SUCCESS(rv, rv); - - mChunkRemaining = avail > UINT32_MAX ? UINT32_MAX : - static_cast(avail); - - if (!mChunkRemaining) { - // Either it's an non-blocking stream without any data - // currently available, or we're at EOF. Sadly there's no way - // to tell other than to read from the stream. - bool hadData = false; - uint32_t numRead; - rv = mSource->ReadSegments(CheckForEOF, &hadData, 1, &numRead); - if (rv == NS_BASE_STREAM_CLOSED) { - avail = 0; - rv = NS_OK; - } - NS_ENSURE_SUCCESS(rv, rv); - MOZ_ASSERT(numRead == 0); - - if (hadData) { - // The source received data between the call to Available and the - // call to ReadSegments. Restart with a new call to Available - continue; - } - - // We're at EOF, write a separator with 0 - mAddedFinalSeparator = true; - } - - if (mFirstChunk) { - mFirstChunk = false; - MOZ_ASSERT(mSeparator.IsEmpty()); - } else { - // For all chunks except the first, add the newline at the end - // of the previous chunk of data - mSeparator.AssignLiteral("\r\n"); - } - mSeparator.AppendInt(mChunkRemaining, 16); - mSeparator.AppendLiteral("\r\n"); - - if (mAddedFinalSeparator) { - mSeparator.AppendLiteral("\r\n"); - } - - break; - } - - // If we're doing chunked encoding, we should either have a chunk size, - // or we should have reached the end of the input stream. - MOZ_ASSERT_IF(mChunked, mChunkRemaining || mAddedFinalSeparator); - // We should only have a separator if we're doing chunked encoding - MOZ_ASSERT_IF(!mSeparator.IsEmpty(), mChunked); - - if (!mSeparator.IsEmpty()) { - *aCountRead = std::min(mSeparator.Length(), aCount); - memcpy(aBuffer, mSeparator.BeginReading(), *aCountRead); - mSeparator.Cut(0, *aCountRead); - rv = NS_OK; - } else if (mChunked) { - *aCountRead = 0; - if (mChunkRemaining) { - rv = mSource->Read(aBuffer, - std::min(aCount, mChunkRemaining), - aCountRead); - mChunkRemaining -= *aCountRead; - } - } else { - rv = mSource->Read(aBuffer, aCount, aCountRead); - } - - if (NS_SUCCEEDED(rv) && *aCountRead == 0) { - rv = NS_BASE_STREAM_CLOSED; - } - - return rv; -} - -NS_IMETHODIMP -StreamCopier::Run() -{ - nsresult rv; - while (1) { - WriteState state = { this, NS_OK }; - uint32_t written; - rv = mSink->WriteSegments(FillOutputBufferHelper, &state, - mozilla::net::nsIOService::gDefaultSegmentSize, - &written); - MOZ_ASSERT(NS_SUCCEEDED(rv) || NS_SUCCEEDED(state.sourceRv)); - if (rv == NS_BASE_STREAM_WOULD_BLOCK) { - mSink->AsyncWait(this, 0, 0, mTarget); - return NS_OK; - } - if (NS_FAILED(rv)) { - mPromise.Resolve(rv, __func__); - return NS_OK; - } - - if (state.sourceRv == NS_BASE_STREAM_WOULD_BLOCK) { - MOZ_ASSERT(mAsyncSource); - mAsyncSource->AsyncWait(this, 0, 0, mTarget); - mSink->AsyncWait(this, nsIAsyncInputStream::WAIT_CLOSURE_ONLY, - 0, mTarget); - - return NS_OK; - } - if (state.sourceRv == NS_BASE_STREAM_CLOSED) { - // We're done! - // No longer interested in callbacks about either stream closing - mSink->AsyncWait(nullptr, 0, 0, nullptr); - if (mAsyncSource) { - mAsyncSource->AsyncWait(nullptr, 0, 0, nullptr); - } - - mSource->Close(); - mSource = nullptr; - mAsyncSource = nullptr; - mSink = nullptr; - - mPromise.Resolve(NS_OK, __func__); - - return NS_OK; - } - - if (NS_FAILED(state.sourceRv)) { - mPromise.Resolve(state.sourceRv, __func__); - return NS_OK; - } - } - - MOZ_ASSUME_UNREACHABLE_MARKER(); -} - -NS_IMETHODIMP -StreamCopier::OnInputStreamReady(nsIAsyncInputStream* aStream) -{ - MOZ_ASSERT(aStream == mAsyncSource || - (!mSource && !mAsyncSource && !mSink)); - return mSource ? Run() : NS_OK; -} - -NS_IMETHODIMP -StreamCopier::OnOutputStreamReady(nsIAsyncOutputStream* aStream) -{ - MOZ_ASSERT(aStream == mSink || - (!mSource && !mAsyncSource && !mSink)); - return mSource ? Run() : NS_OK; -} - -} // namespace - -NS_IMETHODIMP -HttpServer::Connection::OnOutputStreamReady(nsIAsyncOutputStream* aStream) -{ - MOZ_ASSERT(aStream == mOutput || !mOutput); - if (!mOutput) { - return NS_OK; - } - - nsresult rv; - - while (!mOutputBuffers.IsEmpty()) { - if (!mOutputBuffers[0].mStream) { - nsCString& buffer = mOutputBuffers[0].mString; - while (!buffer.IsEmpty()) { - uint32_t written = 0; - rv = mOutput->Write(buffer.BeginReading(), - buffer.Length(), - &written); - - buffer.Cut(0, written); - - if (rv == NS_BASE_STREAM_WOULD_BLOCK) { - return mOutput->AsyncWait(this, 0, 0, NS_GetCurrentThread()); - } - - if (NS_FAILED(rv)) { - Close(); - return NS_OK; - } - } - mOutputBuffers.RemoveElementAt(0); - } else { - if (mOutputCopy) { - // we're already copying the stream - return NS_OK; - } - - mOutputCopy = - StreamCopier::Copy(mOutputBuffers[0].mStream, - mOutput, - mOutputBuffers[0].mChunked); - - RefPtr self = this; - - mOutputCopy-> - Then(AbstractThread::MainThread(), - __func__, - [self, this] (nsresult aStatus) { - MOZ_ASSERT(mOutputBuffers[0].mStream); - LOG_V("HttpServer::Connection::OnOutputStreamReady(%p) - " - "Sent body. Status 0x%lx", - this, aStatus); - - mOutputBuffers.RemoveElementAt(0); - mOutputCopy = nullptr; - OnOutputStreamReady(mOutput); - }, - [] (bool) { MOZ_ASSERT_UNREACHABLE("Reject unexpected"); }); - } - } - - if (mPendingRequests.IsEmpty()) { - if (mCloseAfterRequest) { - LOG_V("HttpServer::Connection::OnOutputStreamReady(%p) - Closing channel", - this); - Close(); - } else if (mWebSocketTransportProvider) { - mInput->AsyncWait(nullptr, 0, 0, nullptr); - mOutput->AsyncWait(nullptr, 0, 0, nullptr); - - mWebSocketTransportProvider->SetTransport(mTransport, mInput, mOutput); - mTransport = nullptr; - mInput = nullptr; - mOutput = nullptr; - mWebSocketTransportProvider = nullptr; - } - } - - return NS_OK; -} - -void -HttpServer::Connection::Close() -{ - if (!mTransport) { - MOZ_ASSERT(!mOutput && !mInput); - return; - } - - mTransport->Close(NS_BINDING_ABORTED); - if (mInput) { - mInput->Close(); - mInput = nullptr; - } - if (mOutput) { - mOutput->Close(); - mOutput = nullptr; - } - - mTransport = nullptr; - - mInputBuffer.Truncate(); - mOutputBuffers.Clear(); - mPendingRequests.Clear(); -} - - -} // namespace net -} // namespace mozilla diff --git a/dom/flyweb/HttpServer.h b/dom/flyweb/HttpServer.h deleted file mode 100644 index dab601c247..0000000000 --- a/dom/flyweb/HttpServer.h +++ /dev/null @@ -1,193 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_dom_HttpServer_h -#define mozilla_dom_HttpServer_h - -#include "nsISupportsImpl.h" -#include "mozilla/DOMEventTargetHelper.h" -#include "nsITLSServerSocket.h" -#include "nsIAsyncInputStream.h" -#include "nsIAsyncOutputStream.h" -#include "mozilla/Variant.h" -#include "nsIRequestObserver.h" -#include "mozilla/MozPromise.h" -#include "nsITransportProvider.h" -#include "nsILocalCertService.h" - -class nsIX509Cert; - -namespace mozilla { -namespace dom { - -extern bool -ContainsToken(const nsCString& aList, const nsCString& aToken); - -class InternalRequest; -class InternalResponse; - -class HttpServerListener -{ -public: - // switch to NS_INLINE_DECL_PURE_VIRTUAL_REFCOUNTING when that lands - NS_IMETHOD_(MozExternalRefCountType) AddRef(void) = 0; - NS_IMETHOD_(MozExternalRefCountType) Release(void) = 0; - - virtual void OnServerStarted(nsresult aStatus) = 0; - virtual void OnRequest(InternalRequest* aRequest) = 0; - virtual void OnWebSocket(InternalRequest* aConnectRequest) = 0; - virtual void OnServerClose() = 0; -}; - -class HttpServer final : public nsIServerSocketListener, - public nsILocalCertGetCallback -{ -public: - HttpServer(); - - NS_DECL_ISUPPORTS - NS_DECL_NSISERVERSOCKETLISTENER - NS_DECL_NSILOCALCERTGETCALLBACK - - void Init(int32_t aPort, bool aHttps, HttpServerListener* aListener); - - void SendResponse(InternalRequest* aRequest, InternalResponse* aResponse); - already_AddRefed - AcceptWebSocket(InternalRequest* aConnectRequest, - const Optional& aProtocol, - ErrorResult& aRv); - void SendWebSocketResponse(InternalRequest* aConnectRequest, - InternalResponse* aResponse); - - void Close(); - - void GetCertKey(nsACString& aKey); - - int32_t GetPort() - { - return mPort; - } - -private: - ~HttpServer(); - - nsresult StartServerSocket(nsIX509Cert* aCert); - void NotifyStarted(nsresult aStatus); - - class TransportProvider final : public nsITransportProvider - { - public: - NS_DECL_ISUPPORTS - NS_DECL_NSITRANSPORTPROVIDER - - void SetTransport(nsISocketTransport* aTransport, - nsIAsyncInputStream* aInput, - nsIAsyncOutputStream* aOutput); - - private: - virtual ~TransportProvider(); - void MaybeNotify(); - - nsCOMPtr mListener; - nsCOMPtr mTransport; - nsCOMPtr mInput; - nsCOMPtr mOutput; - }; - - class Connection final : public nsIInputStreamCallback - , public nsIOutputStreamCallback - , public nsITLSServerSecurityObserver - { - public: - Connection(nsISocketTransport* aTransport, - HttpServer* aServer, - nsresult& rv); - - NS_DECL_ISUPPORTS - NS_DECL_NSIINPUTSTREAMCALLBACK - NS_DECL_NSIOUTPUTSTREAMCALLBACK - NS_DECL_NSITLSSERVERSECURITYOBSERVER - - bool TryHandleResponse(InternalRequest* aRequest, - InternalResponse* aResponse); - already_AddRefed - HandleAcceptWebSocket(const Optional& aProtocol, - ErrorResult& aRv); - void HandleWebSocketResponse(InternalResponse* aResponse); - bool HasPendingWebSocketRequest(InternalRequest* aRequest) - { - return aRequest == mPendingWebSocketRequest; - } - - void Close(); - - private: - ~Connection(); - - void SetSecurityObserver(bool aListen); - - static nsresult ReadSegmentsFunc(nsIInputStream* aIn, - void* aClosure, - const char* aBuffer, - uint32_t aToOffset, - uint32_t aCount, - uint32_t* aWriteCount); - nsresult ConsumeInput(const char*& aBuffer, - const char* aEnd); - nsresult ConsumeLine(const char* aBuffer, - size_t aLength); - void MaybeAddPendingHeader(); - - void QueueResponse(InternalResponse* aResponse); - - RefPtr mServer; - nsCOMPtr mTransport; - nsCOMPtr mInput; - nsCOMPtr mOutput; - - enum { eRequestLine, eHeaders, eBody, ePause } mState; - RefPtr mPendingReq; - uint32_t mPendingReqVersion; - nsCString mInputBuffer; - nsCString mPendingHeaderName; - nsCString mPendingHeaderValue; - uint32_t mRemainingBodySize; - nsCOMPtr mCurrentRequestBody; - bool mCloseAfterRequest; - - typedef Pair, - RefPtr> PendingRequest; - nsTArray mPendingRequests; - RefPtr> mOutputCopy; - - RefPtr mPendingWebSocketRequest; - RefPtr mWebSocketTransportProvider; - - struct OutputBuffer { - nsCString mString; - nsCOMPtr mStream; - bool mChunked; - }; - - nsTArray mOutputBuffers; - }; - - friend class Connection; - - RefPtr mListener; - nsCOMPtr mServerSocket; - nsCOMPtr mCert; - - nsTArray> mConnections; - - int32_t mPort; - bool mHttps; -}; - -} // namespace dom -} // namespace mozilla - -#endif // mozilla_dom_HttpServer_h diff --git a/dom/flyweb/PFlyWebPublishedServer.ipdl b/dom/flyweb/PFlyWebPublishedServer.ipdl deleted file mode 100644 index 4d08a47fc4..0000000000 --- a/dom/flyweb/PFlyWebPublishedServer.ipdl +++ /dev/null @@ -1,38 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set sw=2 ts=8 et ft=cpp : */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -include protocol PContent; -include protocol PSendStream; -include protocol PFileDescriptorSet; -include protocol PTransportProvider; -include FetchTypes; -include ChannelInfo; -include PBackgroundSharedTypes; - -namespace mozilla { -namespace dom { - -async protocol PFlyWebPublishedServer -{ - manager PContent; - -child: - async ServerReady(nsresult aStatus); - async FetchRequest(IPCInternalRequest aRequest, uint64_t aRequestId); - async WebSocketRequest(IPCInternalRequest aRequest, uint64_t aRequestId, - PTransportProvider aProvider); - async ServerClose(); - -parent: - async __delete__(); - - async FetchResponse(IPCInternalResponse aResponse, uint64_t aRequestId); - async WebSocketResponse(IPCInternalResponse aResponse, uint64_t aRequestId); - async WebSocketAccept(nsString aProtocol, uint64_t aRequestId); -}; - -} // namespace dom -} // namespace mozilla diff --git a/dom/flyweb/moz.build b/dom/flyweb/moz.build deleted file mode 100644 index aa8c034b7c..0000000000 --- a/dom/flyweb/moz.build +++ /dev/null @@ -1,42 +0,0 @@ -# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*- -# vim: set filetype=python: -# This Source Code Form is subject to the terms of the Mozilla Public -# License, v. 2.0. If a copy of the MPL was not distributed with this -# file, You can obtain one at http://mozilla.org/MPL/2.0/. - -EXPORTS.mozilla.dom += [ - 'FlyWebDiscoveryManager.h', - 'FlyWebPublishedServer.h', - 'FlyWebPublishedServerIPC.h', - 'FlyWebPublishOptionsIPCSerializer.h', - 'FlyWebServerEvents.h', - 'FlyWebService.h', - 'HttpServer.h', -] - -UNIFIED_SOURCES += [ - 'FlyWebDiscoveryManager.cpp', - 'FlyWebPublishedServer.cpp', - 'FlyWebServerEvents.cpp', - 'FlyWebService.cpp', - 'HttpServer.cpp' -] - -IPDL_SOURCES += [ - 'PFlyWebPublishedServer.ipdl', -] - -FINAL_LIBRARY = 'xul' - -LOCAL_INCLUDES += [ - '/dom/base', - '/netwerk/base', - '/netwerk/dns', - '/netwerk/protocol/websocket', - '/xpcom/io' -] - -include('/ipc/chromium/chromium-config.mozbuild') - -if CONFIG['GNU_CXX']: - CXXFLAGS += ['-Wshadow'] diff --git a/dom/ipc/ContentChild.cpp b/dom/ipc/ContentChild.cpp index 41856eef8e..6b914372b0 100644 --- a/dom/ipc/ContentChild.cpp +++ b/dom/ipc/ContentChild.cpp @@ -29,7 +29,6 @@ #include "mozilla/dom/DataTransfer.h" #include "mozilla/dom/DOMStorageIPC.h" #include "mozilla/dom/ExternalHelperAppChild.h" -#include "mozilla/dom/FlyWebPublishedServerIPC.h" #include "mozilla/dom/GetFilesHelper.h" #include "mozilla/dom/ProcessGlobal.h" #include "mozilla/dom/PushNotifier.h" @@ -1415,22 +1414,6 @@ ContentChild::SendPBlobConstructor(PBlobChild* aActor, return PContentChild::SendPBlobConstructor(aActor, aParams); } -PFlyWebPublishedServerChild* -ContentChild::AllocPFlyWebPublishedServerChild(const nsString& name, - const FlyWebPublishOptions& params) -{ - MOZ_CRASH("We should never be manually allocating PFlyWebPublishedServerChild actors"); - return nullptr; -} - -bool -ContentChild::DeallocPFlyWebPublishedServerChild(PFlyWebPublishedServerChild* aActor) -{ - RefPtr actor = - dont_AddRef(static_cast(aActor)); - return true; -} - bool ContentChild::RecvNotifyEmptyHTTPCache() { diff --git a/dom/ipc/ContentChild.h b/dom/ipc/ContentChild.h index 403328a212..2b36560e2a 100644 --- a/dom/ipc/ContentChild.h +++ b/dom/ipc/ContentChild.h @@ -297,12 +297,6 @@ public: virtual bool DeallocPStorageChild(PStorageChild* aActor) override; - virtual PFlyWebPublishedServerChild* - AllocPFlyWebPublishedServerChild(const nsString& name, - const FlyWebPublishOptions& params) override; - - virtual bool DeallocPFlyWebPublishedServerChild(PFlyWebPublishedServerChild* aActor) override; - virtual bool RecvNotifyEmptyHTTPCache() override; virtual PSpeechSynthesisChild* AllocPSpeechSynthesisChild() override; diff --git a/dom/ipc/ContentParent.cpp b/dom/ipc/ContentParent.cpp index c32c9abaf6..5b7c75e90a 100644 --- a/dom/ipc/ContentParent.cpp +++ b/dom/ipc/ContentParent.cpp @@ -52,7 +52,6 @@ #include "mozilla/dom/power/PowerManagerService.h" #include "mozilla/dom/Permissions.h" #include "mozilla/dom/PushNotifier.h" -#include "mozilla/dom/FlyWebPublishedServerIPC.h" #include "mozilla/dom/quota/QuotaManagerService.h" #include "mozilla/dom/time/DateCacheCleaner.h" #include "mozilla/embedding/printingui/PrintingParent.h" @@ -3121,23 +3120,6 @@ ContentParent::DeallocPStorageParent(PStorageParent* aActor) return true; } -PFlyWebPublishedServerParent* -ContentParent::AllocPFlyWebPublishedServerParent(const nsString& name, - const FlyWebPublishOptions& params) -{ - RefPtr actor = - new FlyWebPublishedServerParent(name, params); - return actor.forget().take(); -} - -bool -ContentParent::DeallocPFlyWebPublishedServerParent(PFlyWebPublishedServerParent* aActor) -{ - RefPtr actor = - dont_AddRef(static_cast(aActor)); - return true; -} - PSpeechSynthesisParent* ContentParent::AllocPSpeechSynthesisParent() { diff --git a/dom/ipc/ContentParent.h b/dom/ipc/ContentParent.h index a4ddb9c64c..f6f3e64db3 100644 --- a/dom/ipc/ContentParent.h +++ b/dom/ipc/ContentParent.h @@ -800,12 +800,6 @@ private: virtual bool DeallocPStorageParent(PStorageParent* aActor) override; - virtual PFlyWebPublishedServerParent* - AllocPFlyWebPublishedServerParent(const nsString& name, - const FlyWebPublishOptions& params) override; - - virtual bool DeallocPFlyWebPublishedServerParent(PFlyWebPublishedServerParent* aActor) override; - virtual PSpeechSynthesisParent* AllocPSpeechSynthesisParent() override; virtual bool diff --git a/dom/ipc/PContent.ipdl b/dom/ipc/PContent.ipdl index 9ed8363d70..5b15433d58 100644 --- a/dom/ipc/PContent.ipdl +++ b/dom/ipc/PContent.ipdl @@ -44,7 +44,6 @@ include protocol PRemoteSpellcheckEngine; include protocol PWebBrowserPersistDocument; include protocol PWebrtcGlobal; include protocol PVideoDecoderManager; -include protocol PFlyWebPublishedServer; include DOMTypes; include JavaScriptTypes; include InputStreamParams; @@ -87,7 +86,6 @@ using class mozilla::dom::ipc::StructuredCloneData from "mozilla/dom/ipc/Structu using mozilla::DataStorageType from "ipc/DataStorageIPCUtils.h"; using mozilla::DocShellOriginAttributes from "mozilla/ipc/BackgroundUtils.h"; using struct mozilla::layers::TextureFactoryIdentifier from "mozilla/layers/CompositorTypes.h"; -using struct mozilla::dom::FlyWebPublishOptions from "mozilla/dom/FlyWebPublishOptionsIPCSerializer.h"; union ChromeRegistryItem { @@ -259,7 +257,6 @@ nested(upto inside_cpow) sync protocol PContent manages PRemoteSpellcheckEngine; manages PWebBrowserPersistDocument; manages PWebrtcGlobal; - manages PFlyWebPublishedServer; both: // Depending on exactly how the new browser is being created, it might be @@ -668,8 +665,6 @@ parent: async PWebrtcGlobal(); - async PFlyWebPublishedServer(nsString name, FlyWebPublishOptions params); - // Services remoting async StartVisitedQuery(URIParams uri); diff --git a/dom/mathml/nsMathMLElement.cpp b/dom/mathml/nsMathMLElement.cpp index d6aef876c7..2be9316824 100644 --- a/dom/mathml/nsMathMLElement.cpp +++ b/dom/mathml/nsMathMLElement.cpp @@ -9,6 +9,7 @@ #include "base/compiler_specific.h" #include "mozilla/ArrayUtils.h" #include "nsGkAtoms.h" +#include "nsITableCellLayout.h" // for MAX_COLSPAN / MAX_ROWSPAN #include "nsCRT.h" #include "nsLayoutStylesheetCache.h" #include "nsRuleData.h" @@ -150,8 +151,9 @@ nsMathMLElement::ParseAttribute(int32_t aNamespaceID, const nsAString& aValue, nsAttrValue& aResult) { + MOZ_ASSERT(IsMathMLElement()); if (aNamespaceID == kNameSpaceID_None) { - if (IsMathMLElement(nsGkAtoms::math) && aAttribute == nsGkAtoms::mode) { + if (mNodeInfo->Equals(nsGkAtoms::math) && aAttribute == nsGkAtoms::mode) { WarnDeprecated(nsGkAtoms::mode->GetUTF16String(), nsGkAtoms::display->GetUTF16String(), OwnerDoc()); } @@ -165,6 +167,16 @@ nsMathMLElement::ParseAttribute(int32_t aNamespaceID, aAttribute == nsGkAtoms::mathbackground_) { return aResult.ParseColor(aValue); } + if (mNodeInfo->Equals(nsGkAtoms::mtd_)) { + if (aAttribute == nsGkAtoms::columnspan_) { + aResult.ParseClampedNonNegativeInt(aValue, 1, 1, MAX_COLSPAN); + return true; + } + if (aAttribute == nsGkAtoms::rowspan) { + aResult.ParseClampedNonNegativeInt(aValue, 1, 0, MAX_ROWSPAN); + return true; + } + } } return nsMathMLElementBase::ParseAttribute(aNamespaceID, aAttribute, @@ -209,6 +221,8 @@ static Element::MappedAttributeEntry sDirStyles[] = { bool nsMathMLElement::IsAttributeMapped(const nsIAtom* aAttribute) const { + MOZ_ASSERT(IsMathMLElement()); + static const MappedAttributeEntry* const mtableMap[] = { sMtableStyles, sCommonPresStyles @@ -240,10 +254,10 @@ nsMathMLElement::IsAttributeMapped(const nsIAtom* aAttribute) const if (IsAnyOfMathMLElements(nsGkAtoms::mstyle_, nsGkAtoms::math)) return FindAttributeDependence(aAttribute, mstyleMap); - if (IsMathMLElement(nsGkAtoms::mtable_)) + if (mNodeInfo->Equals(nsGkAtoms::mtable_)) return FindAttributeDependence(aAttribute, mtableMap); - if (IsMathMLElement(nsGkAtoms::mrow_)) + if (mNodeInfo->Equals(nsGkAtoms::mrow_)) return FindAttributeDependence(aAttribute, mrowMap); if (IsAnyOfMathMLElements(nsGkAtoms::maction_, diff --git a/dom/moz.build b/dom/moz.build index 731c9af722..cfcf6f8655 100644 --- a/dom/moz.build +++ b/dom/moz.build @@ -52,7 +52,6 @@ DIRS += [ 'fetch', 'filehandle', 'filesystem', - 'flyweb', 'gamepad', 'geolocation', 'grid', diff --git a/dom/webidl/FlyWebDiscoveryManager.webidl b/dom/webidl/FlyWebDiscoveryManager.webidl deleted file mode 100644 index 963cebf206..0000000000 --- a/dom/webidl/FlyWebDiscoveryManager.webidl +++ /dev/null @@ -1,39 +0,0 @@ -/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - */ - -dictionary FlyWebDiscoveredService { - DOMString serviceId = ""; - DOMString displayName = ""; - DOMString transport = ""; - DOMString serviceType = ""; - DOMString cert = ""; - DOMString path = ""; -}; - -dictionary FlyWebPairedService { - FlyWebDiscoveredService discoveredService; - DOMString hostname = ""; - DOMString uiUrl = ""; -}; - -callback interface FlyWebPairingCallback { - void pairingSucceeded(optional FlyWebPairedService service); - void pairingFailed(DOMString error); -}; - -callback interface FlyWebDiscoveryCallback { - void onDiscoveredServicesChanged(sequence serviceList); -}; - -[ChromeOnly, ChromeConstructor, Exposed=(Window,System)] -interface FlyWebDiscoveryManager { - sequence listServices(); - - unsigned long startDiscovery(FlyWebDiscoveryCallback aCallback); - void stopDiscovery(unsigned long aId); - - void pairWithService(DOMString serviceId, FlyWebPairingCallback callback); -}; diff --git a/dom/webidl/FlyWebFetchEvent.webidl b/dom/webidl/FlyWebFetchEvent.webidl deleted file mode 100644 index 4bee424e5a..0000000000 --- a/dom/webidl/FlyWebFetchEvent.webidl +++ /dev/null @@ -1,13 +0,0 @@ -/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - */ - -[Pref="dom.flyweb.enabled"] -interface FlyWebFetchEvent : Event { - [SameObject] readonly attribute Request request; - - [Throws] - void respondWith(Promise r); -}; diff --git a/dom/webidl/FlyWebPublish.webidl b/dom/webidl/FlyWebPublish.webidl deleted file mode 100644 index 0c8714a2ad..0000000000 --- a/dom/webidl/FlyWebPublish.webidl +++ /dev/null @@ -1,23 +0,0 @@ -/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - */ - -[Pref="dom.flyweb.enabled"] -interface FlyWebPublishedServer : EventTarget { - readonly attribute DOMString name; - readonly attribute DOMString? uiUrl; - - void close(); - - attribute EventHandler onclose; - attribute EventHandler onfetch; - attribute EventHandler onwebsocket; -}; - -dictionary FlyWebPublishOptions { - DOMString? uiUrl = null; // URL to user interface. Can be different server. Makes - // endpoint show up in browser's "local services" UI. - // If relative, resolves against the root of the server. -}; diff --git a/dom/webidl/FlyWebWebSocketEvent.webidl b/dom/webidl/FlyWebWebSocketEvent.webidl deleted file mode 100644 index 9a47c6decb..0000000000 --- a/dom/webidl/FlyWebWebSocketEvent.webidl +++ /dev/null @@ -1,16 +0,0 @@ -/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - */ - -[Pref="dom.flyweb.enabled"] -interface FlyWebWebSocketEvent : Event { - [SameObject] readonly attribute Request request; - - [Throws] - WebSocket accept(optional DOMString protocol); - - [Throws] - void respondWith(Promise r); -}; diff --git a/dom/webidl/Navigator.webidl b/dom/webidl/Navigator.webidl index 7ca612f986..4536d7d25f 100644 --- a/dom/webidl/Navigator.webidl +++ b/dom/webidl/Navigator.webidl @@ -132,12 +132,6 @@ partial interface Navigator { Promise getBattery(); }; -partial interface Navigator { - [NewObject, Pref="dom.flyweb.enabled"] - Promise publishServer(DOMString name, - optional FlyWebPublishOptions options); -}; - // http://www.w3.org/TR/vibration/#vibration-interface partial interface Navigator { // We don't support sequences in unions yet diff --git a/dom/webidl/moz.build b/dom/webidl/moz.build index 638c5cc1c7..6cdfc781dd 100644 --- a/dom/webidl/moz.build +++ b/dom/webidl/moz.build @@ -151,10 +151,6 @@ WEBIDL_FILES = [ 'FileSystemDirectoryReader.webidl', 'FileSystemEntry.webidl', 'FileSystemFileEntry.webidl', - 'FlyWebDiscoveryManager.webidl', - 'FlyWebFetchEvent.webidl', - 'FlyWebPublish.webidl', - 'FlyWebWebSocketEvent.webidl', 'FocusEvent.webidl', 'FontFace.webidl', 'FontFaceSet.webidl', diff --git a/layout/build/nsLayoutModule.cpp b/layout/build/nsLayoutModule.cpp index 3271a640d9..4455da1227 100644 --- a/layout/build/nsLayoutModule.cpp +++ b/layout/build/nsLayoutModule.cpp @@ -178,8 +178,6 @@ static void Shutdown(); #include "AudioChannelService.h" #include "mozilla/net/WebSocketEventService.h" -#include "mozilla/dom/FlyWebService.h" - #include "mozilla/dom/power/PowerManagerService.h" #include "mozilla/dom/time/TimeService.h" #include "StreamingProtocolService.h" @@ -510,17 +508,12 @@ NS_GENERIC_FACTORY_CONSTRUCTOR_INIT(Geolocation, Init) #define NS_WEBSOCKETEVENT_SERVICE_CID \ { 0x31689828, 0xda66, 0x49a6, { 0x87, 0x0c, 0xdf, 0x62, 0xb8, 0x3f, 0xe7, 0x89 }} -#define NS_FLYWEB_SERVICE_CID \ - { 0x5de19ef0, 0x895e, 0x4c0c, { 0xa6, 0xe0, 0xea, 0xe0, 0x23, 0x2b, 0x84, 0x5a } } - NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(nsGeolocationService, nsGeolocationService::GetGeolocationService) NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(AudioChannelService, AudioChannelService::GetOrCreate) NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(WebSocketEventService, WebSocketEventService::GetOrCreate) -NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(FlyWebService, FlyWebService::GetOrCreateAddRefed) - #ifdef MOZ_WEBSPEECH_TEST_BACKEND NS_GENERIC_FACTORY_CONSTRUCTOR(FakeSpeechRecognitionService) #endif @@ -657,7 +650,6 @@ NS_DEFINE_NAMED_CID(NS_GEOLOCATION_SERVICE_CID); NS_DEFINE_NAMED_CID(NS_GEOLOCATION_CID); NS_DEFINE_NAMED_CID(NS_AUDIOCHANNEL_SERVICE_CID); NS_DEFINE_NAMED_CID(NS_WEBSOCKETEVENT_SERVICE_CID); -NS_DEFINE_NAMED_CID(NS_FLYWEB_SERVICE_CID); NS_DEFINE_NAMED_CID(NS_FOCUSMANAGER_CID); NS_DEFINE_NAMED_CID(NS_CONTENTSECURITYMANAGER_CID); NS_DEFINE_NAMED_CID(CSPSERVICE_CID); @@ -919,7 +911,6 @@ static const mozilla::Module::CIDEntry kLayoutCIDs[] = { { &kNS_GEOLOCATION_CID, false, nullptr, GeolocationConstructor }, { &kNS_AUDIOCHANNEL_SERVICE_CID, false, nullptr, AudioChannelServiceConstructor }, { &kNS_WEBSOCKETEVENT_SERVICE_CID, false, nullptr, WebSocketEventServiceConstructor }, - { &kNS_FLYWEB_SERVICE_CID, false, nullptr, FlyWebServiceConstructor }, { &kNS_FOCUSMANAGER_CID, false, nullptr, CreateFocusManager }, #ifdef MOZ_WEBSPEECH_TEST_BACKEND { &kNS_FAKE_SPEECH_RECOGNITION_SERVICE_CID, false, nullptr, FakeSpeechRecognitionServiceConstructor }, @@ -1046,8 +1037,6 @@ static const mozilla::Module::ContractIDEntry kLayoutContracts[] = { { "@mozilla.org/geolocation;1", &kNS_GEOLOCATION_CID }, { "@mozilla.org/audiochannel/service;1", &kNS_AUDIOCHANNEL_SERVICE_CID }, { "@mozilla.org/websocketevent/service;1", &kNS_WEBSOCKETEVENT_SERVICE_CID }, - { "@mozilla.org/flyweb-service;1", &kNS_FLYWEB_SERVICE_CID }, - { NS_NETWORK_PROTOCOL_CONTRACTID_PREFIX "flyweb", &kNS_FLYWEB_SERVICE_CID }, { "@mozilla.org/focus-manager;1", &kNS_FOCUSMANAGER_CID }, #ifdef MOZ_WEBSPEECH_TEST_BACKEND { NS_SPEECH_RECOGNITION_SERVICE_CONTRACTID_PREFIX "fake", &kNS_FAKE_SPEECH_RECOGNITION_SERVICE_CID }, diff --git a/layout/mathml/nsMathMLmtableFrame.cpp b/layout/mathml/nsMathMLmtableFrame.cpp index fd184e6375..1ff8a28ef0 100644 --- a/layout/mathml/nsMathMLmtableFrame.cpp +++ b/layout/mathml/nsMathMLmtableFrame.cpp @@ -1160,47 +1160,6 @@ nsMathMLmtdFrame::Init(nsIContent* aContent, RemoveStateBits(NS_FRAME_FONT_INFLATION_FLOW_ROOT); } -int32_t -nsMathMLmtdFrame::GetRowSpan() -{ - int32_t rowspan = 1; - - // Don't look at the content's rowspan if we're not an mtd or a pseudo cell. - if (mContent->IsMathMLElement(nsGkAtoms::mtd_) && - !StyleContext()->GetPseudo()) { - nsAutoString value; - mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::rowspan, value); - if (!value.IsEmpty()) { - nsresult error; - rowspan = value.ToInteger(&error); - if (NS_FAILED(error) || rowspan < 0) - rowspan = 1; - rowspan = std::min(rowspan, MAX_ROWSPAN); - } - } - return rowspan; -} - -int32_t -nsMathMLmtdFrame::GetColSpan() -{ - int32_t colspan = 1; - - // Don't look at the content's colspan if we're not an mtd or a pseudo cell. - if (mContent->IsMathMLElement(nsGkAtoms::mtd_) && - !StyleContext()->GetPseudo()) { - nsAutoString value; - mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::columnspan_, value); - if (!value.IsEmpty()) { - nsresult error; - colspan = value.ToInteger(&error); - if (NS_FAILED(error) || colspan <= 0 || colspan > MAX_COLSPAN) - colspan = 1; - } - } - return colspan; -} - nsresult nsMathMLmtdFrame::AttributeChanged(int32_t aNameSpaceID, nsIAtom* aAttribute, diff --git a/layout/mathml/nsMathMLmtableFrame.h b/layout/mathml/nsMathMLmtableFrame.h index 5cb4fc4a2f..725991c179 100644 --- a/layout/mathml/nsMathMLmtableFrame.h +++ b/layout/mathml/nsMathMLmtableFrame.h @@ -257,8 +257,6 @@ public: nsDisplayListBuilder* aBuilder, const nsDisplayListSet& aLists) override; - virtual int32_t GetRowSpan() override; - virtual int32_t GetColSpan() override; virtual bool IsFrameOfType(uint32_t aFlags) const override { return nsTableCellFrame::IsFrameOfType(aFlags & ~(nsIFrame::eMathML)); diff --git a/layout/tables/celldata.h b/layout/tables/celldata.h index b744b51752..ac7be58d76 100644 --- a/layout/tables/celldata.h +++ b/layout/tables/celldata.h @@ -6,6 +6,7 @@ #define CellData_h__ #include "nsISupports.h" +#include "nsITableCellLayout.h" // for MAX_COLSPAN / MAX_ROWSPAN #include "nsCoord.h" #include "mozilla/gfx/Types.h" #include "mozilla/WritingModes.h" @@ -15,11 +16,6 @@ class nsTableCellFrame; class nsCellMap; class BCCellData; - -#define MAX_ROWSPAN 65534 // the cellmap can not handle more. -#define MAX_COLSPAN 1000 // limit as IE and opera do. If this ever changes, - // change COL_SPAN_OFFSET/COL_SPAN_SHIFT accordingly. - /** * Data stored by nsCellMap to rationalize rowspan and colspan cells. */ diff --git a/layout/tables/nsITableCellLayout.h b/layout/tables/nsITableCellLayout.h index e761d76be1..a366b150eb 100644 --- a/layout/tables/nsITableCellLayout.h +++ b/layout/tables/nsITableCellLayout.h @@ -7,6 +7,10 @@ #include "nsQueryFrame.h" +#define MAX_ROWSPAN 65534 // the cellmap can not handle more. +#define MAX_COLSPAN 1000 // limit as IE and opera do. If this ever changes, +// change COL_SPAN_OFFSET/COL_SPAN_SHIFT accordingly. + /** * nsITableCellLayout * interface for layout objects that act like table cells. diff --git a/layout/tables/nsTableCellFrame.cpp b/layout/tables/nsTableCellFrame.cpp index 2862bb201f..cd846efa24 100644 --- a/layout/tables/nsTableCellFrame.cpp +++ b/layout/tables/nsTableCellFrame.cpp @@ -711,16 +711,18 @@ nsTableCellFrame::GetCellBaseline() const borderPadding; } -int32_t nsTableCellFrame::GetRowSpan() +int32_t +nsTableCellFrame::GetRowSpan() { int32_t rowSpan=1; - nsGenericHTMLElement *hc = nsGenericHTMLElement::FromContent(mContent); // Don't look at the content's rowspan if we're a pseudo cell - if (hc && !StyleContext()->GetPseudo()) { - const nsAttrValue* attr = hc->GetParsedAttr(nsGkAtoms::rowspan); + if (!StyleContext()->GetPseudo()) { + dom::Element* elem = mContent->AsElement(); + const nsAttrValue* attr = elem->GetParsedAttr(nsGkAtoms::rowspan); // Note that we don't need to check the tag name, because only table cells - // and table headers parse the "rowspan" attribute into an integer. + // (including MathML ) and table headers parse the "rowspan" attribute + // into an integer. if (attr && attr->Type() == nsAttrValue::eInteger) { rowSpan = attr->GetIntegerValue(); } @@ -728,16 +730,20 @@ int32_t nsTableCellFrame::GetRowSpan() return rowSpan; } -int32_t nsTableCellFrame::GetColSpan() +int32_t +nsTableCellFrame::GetColSpan() { int32_t colSpan=1; - nsGenericHTMLElement *hc = nsGenericHTMLElement::FromContent(mContent); // Don't look at the content's colspan if we're a pseudo cell - if (hc && !StyleContext()->GetPseudo()) { - const nsAttrValue* attr = hc->GetParsedAttr(nsGkAtoms::colspan); + if (!StyleContext()->GetPseudo()) { + dom::Element* elem = mContent->AsElement(); + const nsAttrValue* attr = elem->GetParsedAttr( + MOZ_UNLIKELY(elem->IsMathMLElement()) ? nsGkAtoms::columnspan_ + : nsGkAtoms::colspan); // Note that we don't need to check the tag name, because only table cells - // and table headers parse the "colspan" attribute into an integer. + // (including MathML ) and table headers parse the "colspan" attribute + // into an integer. if (attr && attr->Type() == nsAttrValue::eInteger) { colSpan = attr->GetIntegerValue(); } diff --git a/layout/tables/nsTableCellFrame.h b/layout/tables/nsTableCellFrame.h index e8dad5c20f..ea527b3c59 100644 --- a/layout/tables/nsTableCellFrame.h +++ b/layout/tables/nsTableCellFrame.h @@ -165,11 +165,11 @@ public: /** * return the cell's specified row span. this is what was specified in the - * content model or in the style info, and is always >= 1. + * content model or in the style info, and is always >= 0. * to get the effective row span (the actual value that applies), use GetEffectiveRowSpan() * @see nsTableFrame::GetEffectiveRowSpan() */ - virtual int32_t GetRowSpan(); + int32_t GetRowSpan(); // there is no set row index because row index depends on the cell's parent row only @@ -191,7 +191,7 @@ public: * to get the effective col span (the actual value that applies), use GetEffectiveColSpan() * @see nsTableFrame::GetEffectiveColSpan() */ - virtual int32_t GetColSpan(); + int32_t GetColSpan(); /** return the cell's column index (starting at 0 for the first column) */ virtual nsresult GetColIndex(int32_t &aColIndex) const override; diff --git a/modules/libpref/init/all.js b/modules/libpref/init/all.js index 92fcf8bdc7..2d9dae7cec 100644 --- a/modules/libpref/init/all.js +++ b/modules/libpref/init/all.js @@ -4972,8 +4972,6 @@ pref("dom.forms.inputmode", true); // InputMethods for soft keyboards in B2G pref("dom.mozInputMethod.enabled", false); -pref("dom.flyweb.enabled", false); - // Enable mapped array buffer by default. pref("dom.mapped_arraybuffer.enabled", true); diff --git a/netwerk/base/nsSocketTransportService2.cpp b/netwerk/base/nsSocketTransportService2.cpp index 30519586c4..5e6e5425b8 100644 --- a/netwerk/base/nsSocketTransportService2.cpp +++ b/netwerk/base/nsSocketTransportService2.cpp @@ -25,7 +25,6 @@ #include "nsThreadUtils.h" #include "nsIFile.h" #include "nsIWidget.h" -#include "mozilla/dom/FlyWebService.h" #if defined(XP_WIN) #include "mozilla/WindowsVersion.h" @@ -685,20 +684,6 @@ nsSocketTransportService::CreateRoutedTransport(const char **types, nsIProxyInfo *proxyInfo, nsISocketTransport **result) { - // Check FlyWeb table for host mappings. If one exists, then use that. - RefPtr fws = - mozilla::dom::FlyWebService::GetExisting(); - if (fws) { - nsresult rv = fws->CreateTransportForHost(types, typeCount, host, port, - hostRoute, portRoute, - proxyInfo, result); - NS_ENSURE_SUCCESS(rv, rv); - - if (*result) { - return NS_OK; - } - } - NS_ENSURE_TRUE(mInitialized, NS_ERROR_NOT_INITIALIZED); NS_ENSURE_TRUE(port >= 0 && port <= 0xFFFF, NS_ERROR_ILLEGAL_VALUE); diff --git a/toolkit/components/alerts/jar.mn b/toolkit/components/alerts/jar.mn index c45939078f..c9bd127dd1 100644 --- a/toolkit/components/alerts/jar.mn +++ b/toolkit/components/alerts/jar.mn @@ -5,4 +5,4 @@ toolkit.jar: content/global/alerts/alert.css (resources/content/alert.css) content/global/alerts/alert.xul (resources/content/alert.xul) - content/global/alerts/alert.js (resources/content/alert.js) +* content/global/alerts/alert.js (resources/content/alert.js) diff --git a/toolkit/components/alerts/resources/content/alert.js b/toolkit/components/alerts/resources/content/alert.js index 12068b5488..e9725bedb0 100644 --- a/toolkit/components/alerts/resources/content/alert.js +++ b/toolkit/components/alerts/resources/content/alert.js @@ -4,7 +4,6 @@ var {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components; -Cu.import("resource://gre/modules/AppConstants.jsm"); Cu.import("resource://gre/modules/Services.jsm"); /* @@ -26,10 +25,15 @@ const NS_ALERT_HORIZONTAL = 1; const NS_ALERT_LEFT = 2; const NS_ALERT_TOP = 4; -const WINDOW_MARGIN = AppConstants.platform == "win" ? 0 : 10; -const BODY_TEXT_LIMIT = 200; -const WINDOW_SHADOW_SPREAD = AppConstants.platform == "win" ? 10 : 0; +#ifdef XP_WIN +const WINDOW_MARGIN = 0; +const WINDOW_SHADOW_SPREAD = 10; +#else +const WINDOW_MARGIN = 10; +const WINDOW_SHADOW_SPREAD = 0; +#endif +const BODY_TEXT_LIMIT = 200; var gOrigin = 0; // Default value: alert from bottom right. var gReplacedWindow = null; diff --git a/toolkit/components/apppicker/content/appPicker.js b/toolkit/components/apppicker/content/appPicker.js index 469a6ca231..21a007632b 100644 --- a/toolkit/components/apppicker/content/appPicker.js +++ b/toolkit/components/apppicker/content/appPicker.js @@ -2,8 +2,6 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -Components.utils.import("resource://gre/modules/AppConstants.jsm"); - function AppPicker() {} AppPicker.prototype = @@ -115,19 +113,19 @@ AppPicker.prototype = * Retrieve the pretty description from the file */ getFileDisplayName: function getFileDisplayName(file) { - if (AppConstants.platform == "win") { - if (file instanceof Components.interfaces.nsILocalFileWin) { - try { - return file.getVersionInfoField("FileDescription"); - } catch (e) {} - } - } else if (AppConstants.platform == "macosx") { - if (file instanceof Components.interfaces.nsILocalFileMac) { - try { - return file.bundleDisplayName; - } catch (e) {} - } +#ifdef XP_WIN + if (file instanceof Components.interfaces.nsILocalFileWin) { + try { + return file.getVersionInfoField("FileDescription"); + } catch (e) {} } +#elifdef XP_MACOSX + if (file instanceof Components.interfaces.nsILocalFileMac) { + try { + return file.bundleDisplayName; + } catch (e) {} + } +#endif return file.leafName; }, @@ -183,13 +181,13 @@ AppPicker.prototype = var fileLoc = Components.classes["@mozilla.org/file/directory_service;1"] .getService(Components.interfaces.nsIProperties); var startLocation; - if (AppConstants.platform == "win") { - startLocation = "ProgF"; // Program Files - } else if (AppConstants.platform == "macosx") { - startLocation = "LocApp"; // Local Applications - } else { - startLocation = "Home"; - } +#ifdef XP_WIN + startLocation = "ProgF"; // Program Files +#elifdef XP_MACOSX + startLocation = "LocApp"; // Local Applications +#else + startLocation = "Home"; +#endif fp.displayDirectory = fileLoc.get(startLocation, Components.interfaces.nsILocalFile); diff --git a/toolkit/components/apppicker/jar.mn b/toolkit/components/apppicker/jar.mn index 60e029d8a7..d8431c3fea 100644 --- a/toolkit/components/apppicker/jar.mn +++ b/toolkit/components/apppicker/jar.mn @@ -4,5 +4,5 @@ toolkit.jar: content/global/appPicker.xul (content/appPicker.xul) - content/global/appPicker.js (content/appPicker.js) +* content/global/appPicker.js (content/appPicker.js) diff --git a/toolkit/components/jsdownloads/src/DownloadIntegration.jsm b/toolkit/components/jsdownloads/src/DownloadIntegration.jsm index a6875ec48f..995cc06695 100644 --- a/toolkit/components/jsdownloads/src/DownloadIntegration.jsm +++ b/toolkit/components/jsdownloads/src/DownloadIntegration.jsm @@ -28,8 +28,7 @@ Cu.import("resource://gre/modules/XPCOMUtils.jsm"); XPCOMUtils.defineLazyModuleGetter(this, "AsyncShutdown", "resource://gre/modules/AsyncShutdown.jsm"); -XPCOMUtils.defineLazyModuleGetter(this, "AppConstants", - "resource://gre/modules/AppConstants.jsm"); + XPCOMUtils.defineLazyModuleGetter(this, "DeferredTask", "resource://gre/modules/DeferredTask.jsm"); XPCOMUtils.defineLazyModuleGetter(this, "Downloads", @@ -696,8 +695,11 @@ this.DownloadIntegration = { fileExtension = match[1]; } - let isWindowsExe = AppConstants.platform == "win" && - fileExtension.toLowerCase() == "exe"; +#ifdef XP_WIN + let isWindowsExe = fileExtension.toLowerCase() == "exe"; +#else + let isWindowsExe = false; +#endif // Ask for confirmation if the file is executable, except for .exe on // Windows where the operating system will show the prompt based on the diff --git a/toolkit/components/jsdownloads/src/DownloadUIHelper.jsm b/toolkit/components/jsdownloads/src/DownloadUIHelper.jsm index ce165205bb..d4ce248e30 100644 --- a/toolkit/components/jsdownloads/src/DownloadUIHelper.jsm +++ b/toolkit/components/jsdownloads/src/DownloadUIHelper.jsm @@ -22,7 +22,6 @@ const Cu = Components.utils; const Cr = Components.results; Cu.import("resource://gre/modules/XPCOMUtils.jsm"); -Cu.import("resource://gre/modules/AppConstants.jsm"); XPCOMUtils.defineLazyModuleGetter(this, "OS", "resource://gre/modules/osfile.jsm"); @@ -186,17 +185,17 @@ this.DownloadPrompter.prototype = { switch (aPromptType) { case this.ON_QUIT: title = s.quitCancelDownloadsAlertTitle; - if (AppConstants.platform != "macosx") { - message = aDownloadsCount > 1 - ? s.quitCancelDownloadsAlertMsgMultiple(aDownloadsCount) - : s.quitCancelDownloadsAlertMsg; - cancelButton = s.dontQuitButtonWin; - } else { - message = aDownloadsCount > 1 - ? s.quitCancelDownloadsAlertMsgMacMultiple(aDownloadsCount) - : s.quitCancelDownloadsAlertMsgMac; - cancelButton = s.dontQuitButtonMac; - } +#ifdef XP_MACOSX + message = aDownloadsCount > 1 + ? s.quitCancelDownloadsAlertMsgMacMultiple(aDownloadsCount) + : s.quitCancelDownloadsAlertMsgMac; + cancelButton = s.dontQuitButtonMac; +#else + message = aDownloadsCount > 1 + ? s.quitCancelDownloadsAlertMsgMultiple(aDownloadsCount) + : s.quitCancelDownloadsAlertMsg; + cancelButton = s.dontQuitButtonWin; +#endif break; case this.ON_OFFLINE: title = s.offlineCancelDownloadsAlertTitle; diff --git a/toolkit/components/jsdownloads/src/moz.build b/toolkit/components/jsdownloads/src/moz.build index 87abed62ef..ac37682080 100644 --- a/toolkit/components/jsdownloads/src/moz.build +++ b/toolkit/components/jsdownloads/src/moz.build @@ -19,11 +19,11 @@ EXTRA_JS_MODULES += [ 'DownloadList.jsm', 'Downloads.jsm', 'DownloadStore.jsm', - 'DownloadUIHelper.jsm', ] EXTRA_PP_JS_MODULES += [ 'DownloadIntegration.jsm', + 'DownloadUIHelper.jsm', ] FINAL_LIBRARY = 'xul' diff --git a/toolkit/components/passwordmgr/OSCrypto.jsm b/toolkit/components/passwordmgr/OSCrypto.jsm index 04254f66f5..3d2b27c4e8 100644 --- a/toolkit/components/passwordmgr/OSCrypto.jsm +++ b/toolkit/components/passwordmgr/OSCrypto.jsm @@ -8,15 +8,14 @@ "use strict"; -Components.utils.import("resource://gre/modules/AppConstants.jsm"); Components.utils.import("resource://gre/modules/Services.jsm"); this.EXPORTED_SYMBOLS = ["OSCrypto"]; var OSCrypto = {}; -if (AppConstants.platform == "win") { - Services.scriptloader.loadSubScript("resource://gre/modules/OSCrypto_win.js", this); -} else { - throw new Error("OSCrypto.jsm isn't supported on this platform"); -} +#ifdef XP_WIN +Services.scriptloader.loadSubScript("resource://gre/modules/OSCrypto_win.js", this); +#else +throw new Error("OSCrypto.jsm isn't supported on this platform"); +#endif diff --git a/toolkit/components/passwordmgr/content/passwordManager.js b/toolkit/components/passwordmgr/content/passwordManager.js index 327ebbdf84..662f212790 100644 --- a/toolkit/components/passwordmgr/content/passwordManager.js +++ b/toolkit/components/passwordmgr/content/passwordManager.js @@ -5,7 +5,6 @@ /** * =================== SAVED SIGNONS CODE =================== ***/ const { classes: Cc, interfaces: Ci, results: Cr, utils: Cu } = Components; -Cu.import("resource://gre/modules/AppConstants.jsm"); Cu.import("resource://gre/modules/XPCOMUtils.jsm"); Cu.import("resource://gre/modules/Services.jsm"); @@ -486,9 +485,13 @@ function HandleSignonKeyPress(e) { if (signonsTree.getAttribute("editing")) { return; } + +#ifdef XP_MACOSX if (e.keyCode == KeyboardEvent.DOM_VK_DELETE || - (AppConstants.platform == "macosx" && - e.keyCode == KeyboardEvent.DOM_VK_BACK_SPACE)) { + e.keyCode == KeyboardEvent.DOM_VK_BACK_SPACE) { +#else + if (e.keyCode == KeyboardEvent.DOM_VK_DELETE) { +#endif DeleteSignon(); } } diff --git a/toolkit/components/passwordmgr/moz.build b/toolkit/components/passwordmgr/moz.build index e54e6ba2d3..af9a4ab03a 100644 --- a/toolkit/components/passwordmgr/moz.build +++ b/toolkit/components/passwordmgr/moz.build @@ -32,11 +32,11 @@ XPIDL_MODULE = 'loginmgr' EXTRA_COMPONENTS += [ 'crypto-SDR.js', 'nsLoginInfo.js', - 'nsLoginManager.js', 'nsLoginManagerPrompter.js', ] EXTRA_PP_COMPONENTS += [ + 'nsLoginManager.js', 'passwordmgr.manifest', ] @@ -46,9 +46,10 @@ EXTRA_JS_MODULES += [ 'LoginManagerContent.jsm', 'LoginManagerParent.jsm', 'LoginRecipes.jsm', - 'OSCrypto.jsm', ] +EXTRA_PP_JS_MODULES += ['OSCrypto.jsm'] + if CONFIG['OS_TARGET'] == 'Android': EXTRA_COMPONENTS += [ 'storage-mozStorage.js', diff --git a/toolkit/components/passwordmgr/nsLoginManager.js b/toolkit/components/passwordmgr/nsLoginManager.js index 514351fa52..87466fe5c1 100644 --- a/toolkit/components/passwordmgr/nsLoginManager.js +++ b/toolkit/components/passwordmgr/nsLoginManager.js @@ -8,7 +8,6 @@ const { classes: Cc, interfaces: Ci, results: Cr, utils: Cu } = Components; const PERMISSION_SAVE_LOGINS = "login-saving"; -Cu.import("resource://gre/modules/AppConstants.jsm"); Cu.import("resource://gre/modules/XPCOMUtils.jsm"); Cu.import("resource://gre/modules/Services.jsm"); Cu.import("resource://gre/modules/Timer.jsm"); @@ -113,12 +112,12 @@ LoginManager.prototype = { _initStorage() { - let contractID; - if (AppConstants.platform == "android") { - contractID = "@mozilla.org/login-manager/storage/mozStorage;1"; - } else { - contractID = "@mozilla.org/login-manager/storage/json;1"; - } +#ifdef MOZ_WIDGET_ANDROID + let contractID = "@mozilla.org/login-manager/storage/mozStorage;1"; +#else + let contractID = "@mozilla.org/login-manager/storage/json;1"; +#endif + try { let catMan = Cc["@mozilla.org/categorymanager;1"]. getService(Ci.nsICategoryManager); diff --git a/toolkit/components/places/PlacesUtils.jsm b/toolkit/components/places/PlacesUtils.jsm index 5f6e81f18a..259fb7aa7d 100644 --- a/toolkit/components/places/PlacesUtils.jsm +++ b/toolkit/components/places/PlacesUtils.jsm @@ -30,7 +30,6 @@ const { classes: Cc, interfaces: Ci, results: Cr, utils: Cu } = Components; Cu.importGlobalProperties(["URL"]); Cu.import("resource://gre/modules/XPCOMUtils.jsm"); -Cu.import("resource://gre/modules/AppConstants.jsm"); XPCOMUtils.defineLazyModuleGetter(this, "Services", "resource://gre/modules/Services.jsm"); XPCOMUtils.defineLazyModuleGetter(this, "NetUtil", @@ -64,7 +63,11 @@ const MIN_TRANSACTIONS_FOR_BATCH = 5; // On Mac OSX, the transferable system converts "\r\n" to "\n\n", where // we really just want "\n". On other platforms, the transferable system // converts "\r\n" to "\n". -const NEWLINE = AppConstants.platform == "macosx" ? "\n" : "\r\n"; +#ifdef XP_MACOSX +const NEWLINE = "\n"; +#else +const NEWLINE = "\r\n"; +#endif function QI_node(aNode, aIID) { var result = null; diff --git a/toolkit/components/places/moz.build b/toolkit/components/places/moz.build index 85e1e93e1e..478b18e02f 100644 --- a/toolkit/components/places/moz.build +++ b/toolkit/components/places/moz.build @@ -72,9 +72,10 @@ if CONFIG['MOZ_PLACES']: 'PlacesSearchAutocompleteProvider.jsm', 'PlacesSyncUtils.jsm', 'PlacesTransactions.jsm', - 'PlacesUtils.jsm', ] + EXTRA_PP_JS_MODULES += ['PlacesUtils.jsm'] + EXTRA_COMPONENTS += [ 'ColorAnalyzer.js', 'nsLivemarkService.js', diff --git a/toolkit/components/printing/content/printPreviewBindings.xml b/toolkit/components/printing/content/printPreviewBindings.xml index 182ecc1993..c33b22e36e 100644 --- a/toolkit/components/printing/content/printPreviewBindings.xml +++ b/toolkit/components/printing/content/printPreviewBindings.xml @@ -161,10 +161,14 @@ let $ = id => document.getAnonymousElementByAttribute(this, "anonid", id); let ltr = document.documentElement.matches(":root:-moz-locale-dir(ltr)"); +#ifdef XP_WIN // Windows 7 doesn't support ⏮ and ⏭ by default, and fallback doesn't // always work (bug 1343330). - let {AppConstants} = Components.utils.import("resource://gre/modules/AppConstants.jsm", {}); - let useCompatCharacters = AppConstants.isPlatformAndVersionAtMost("win", "6.1"); + let useCompatCharacters = Services.vc.compare(Services.sysinfo.getProperty("version"), "6.1") <= 0; +#else + let useCompatCharacters = false; +#endif + let leftEnd = useCompatCharacters ? "⏪" : "⏮"; let rightEnd = useCompatCharacters ? "⏩" : "⏭"; $("navigateHome").label = ltr ? leftEnd : rightEnd; diff --git a/toolkit/components/printing/jar.mn b/toolkit/components/printing/jar.mn index 40f9acf2b0..a0e9510304 100644 --- a/toolkit/components/printing/jar.mn +++ b/toolkit/components/printing/jar.mn @@ -13,7 +13,7 @@ toolkit.jar: #endif content/global/printPageSetup.js (content/printPageSetup.js) content/global/printPageSetup.xul (content/printPageSetup.xul) - content/global/printPreviewBindings.xml (content/printPreviewBindings.xml) +* content/global/printPreviewBindings.xml (content/printPreviewBindings.xml) content/global/printPreviewProgress.js (content/printPreviewProgress.js) content/global/printPreviewProgress.xul (content/printPreviewProgress.xul) content/global/printProgress.js (content/printProgress.js) diff --git a/toolkit/components/satchel/FormHistory.jsm b/toolkit/components/satchel/FormHistory.jsm index 3d4a9fc436..ca9a28f1f6 100644 --- a/toolkit/components/satchel/FormHistory.jsm +++ b/toolkit/components/satchel/FormHistory.jsm @@ -91,7 +91,6 @@ const Cr = Components.results; Components.utils.import("resource://gre/modules/XPCOMUtils.jsm"); Components.utils.import("resource://gre/modules/Services.jsm"); -Components.utils.import("resource://gre/modules/AppConstants.jsm"); XPCOMUtils.defineLazyServiceGetter(this, "uuidService", "@mozilla.org/uuid-generator;1", @@ -102,7 +101,11 @@ const DAY_IN_MS = 86400000; // 1 day in milliseconds const MAX_SEARCH_TOKENS = 10; const NOOP = function noop() {}; -var supportsDeletedTable = AppConstants.platform == "android"; +#ifdef MOZ_WIDGET_ANDROID +var supportsDeletedTable = true; +#else +var supportsDeletedTable = false; +#endif var Prefs = { initialized: false, diff --git a/toolkit/components/satchel/moz.build b/toolkit/components/satchel/moz.build index 239f412bcf..883ee9f230 100644 --- a/toolkit/components/satchel/moz.build +++ b/toolkit/components/satchel/moz.build @@ -28,17 +28,19 @@ LOCAL_INCLUDES += [ EXTRA_COMPONENTS += [ 'FormHistoryStartup.js', 'nsFormAutoComplete.js', - 'nsFormHistory.js', 'nsInputListAutoComplete.js', 'satchel.manifest', ] +EXTRA_PP_COMPONENTS += ['nsFormHistory.js'] + EXTRA_JS_MODULES += [ 'AutoCompletePopup.jsm', - 'FormHistory.jsm', 'nsFormAutoCompleteResult.jsm', ] +EXTRA_PP_JS_MODULES += ['FormHistory.jsm'] + FINAL_LIBRARY = 'xul' JAR_MANIFESTS += ['jar.mn'] diff --git a/toolkit/components/satchel/nsFormHistory.js b/toolkit/components/satchel/nsFormHistory.js index d68be2d587..9d67f0729f 100644 --- a/toolkit/components/satchel/nsFormHistory.js +++ b/toolkit/components/satchel/nsFormHistory.js @@ -12,8 +12,6 @@ Components.utils.import("resource://gre/modules/Services.jsm"); XPCOMUtils.defineLazyModuleGetter(this, "Deprecated", "resource://gre/modules/Deprecated.jsm"); -XPCOMUtils.defineLazyModuleGetter(this, "AppConstants", - "resource://gre/modules/AppConstants.jsm"); const DB_VERSION = 4; const DAY_IN_MS = 86400000; // 1 day in milliseconds @@ -351,26 +349,26 @@ FormHistory.prototype = { }, moveToDeletedTable : function moveToDeletedTable(values, params) { - if (AppConstants.platform == "android") { - this.log("Moving entries to deleted table."); +#ifdef MOZ_WIDGET_ANDROID + this.log("Moving entries to deleted table."); - let stmt; + let stmt; - try { - // Move the entries to the deleted items table. - let query = "INSERT INTO moz_deleted_formhistory (guid, timeDeleted) "; - if (values) query += values; - stmt = this.dbCreateStatement(query, params); - stmt.execute(); - } catch (e) { - this.log("Moving deleted entries failed: " + e); - throw e; - } finally { - if (stmt) { - stmt.reset(); - } - } - } + try { + // Move the entries to the deleted items table. + let query = "INSERT INTO moz_deleted_formhistory (guid, timeDeleted) "; + if (values) query += values; + stmt = this.dbCreateStatement(query, params); + stmt.execute(); + } catch (e) { + this.log("Moving deleted entries failed: " + e); + throw e; + } finally { + if (stmt) { + stmt.reset(); + } + } +#endif }, get dbConnection() { diff --git a/toolkit/components/thumbnails/PageThumbUtils.jsm b/toolkit/components/thumbnails/PageThumbUtils.jsm index dda3a81b3c..fb5d67ddb5 100644 --- a/toolkit/components/thumbnails/PageThumbUtils.jsm +++ b/toolkit/components/thumbnails/PageThumbUtils.jsm @@ -14,7 +14,6 @@ const { classes: Cc, interfaces: Ci, utils: Cu } = Components; Cu.import("resource://gre/modules/XPCOMUtils.jsm", this); Cu.import("resource://gre/modules/Services.jsm"); Cu.import("resource://gre/modules/Promise.jsm", this); -Cu.import("resource://gre/modules/AppConstants.jsm"); XPCOMUtils.defineLazyModuleGetter(this, "BrowserUtils", "resource://gre/modules/BrowserUtils.jsm"); @@ -72,15 +71,17 @@ this.PageThumbUtils = { let windowScale = aWindow ? aWindow.devicePixelRatio : systemScale; let scale = Math.max(systemScale, windowScale); +#ifdef XP_MACOSX /** * * On retina displays, we can sometimes go down this path * without a window object. In those cases, force 2x scaling * as the system scale doesn't represent the 2x scaling * on OS X. */ - if (AppConstants.platform == "macosx" && !aWindow) { + if (!aWindow) { scale = 2; } +#endif /** * * THESE VALUES ARE DEFINED IN newtab.css and hard coded. diff --git a/toolkit/components/thumbnails/moz.build b/toolkit/components/thumbnails/moz.build index e4a178998f..bd7c1d3444 100644 --- a/toolkit/components/thumbnails/moz.build +++ b/toolkit/components/thumbnails/moz.build @@ -15,11 +15,11 @@ EXTRA_COMPONENTS += [ EXTRA_JS_MODULES += [ 'PageThumbs.jsm', 'PageThumbsWorker.js', - 'PageThumbUtils.jsm', ] EXTRA_PP_JS_MODULES += [ 'BackgroundPageThumbs.jsm', + 'PageThumbUtils.jsm', ] diff --git a/toolkit/mozapps/downloads/DownloadTaskbarProgress.jsm b/toolkit/mozapps/downloads/DownloadTaskbarProgress.jsm index bccbeda567..e015ded2a1 100644 --- a/toolkit/mozapps/downloads/DownloadTaskbarProgress.jsm +++ b/toolkit/mozapps/downloads/DownloadTaskbarProgress.jsm @@ -16,7 +16,6 @@ const Cu = Components.utils; const Cr = Components.results; Cu.import("resource://gre/modules/XPCOMUtils.jsm"); -Cu.import("resource://gre/modules/AppConstants.jsm"); XPCOMUtils.defineLazyModuleGetter(this, "Services", "resource://gre/modules/Services.jsm"); @@ -177,33 +176,33 @@ var DownloadTaskbarProgressUpdater = */ _setActiveWindow: function DTPU_setActiveWindow(aWindow, aIsDownloadWindow) { - if (AppConstants.platform == "win") { - // Clear out the taskbar for the old active window. (If there was no active - // window, this is a no-op.) - this._clearTaskbar(); +#ifdef XP_WIN + // Clear out the taskbar for the old active window. (If there was no active + // window, this is a no-op.) + this._clearTaskbar(); - this._activeWindowIsDownloadWindow = aIsDownloadWindow; - if (aWindow) { - // Get the taskbar progress for this window - let docShell = aWindow.QueryInterface(Ci.nsIInterfaceRequestor). - getInterface(Ci.nsIWebNavigation). - QueryInterface(Ci.nsIDocShellTreeItem).treeOwner. - QueryInterface(Ci.nsIInterfaceRequestor). - getInterface(Ci.nsIXULWindow).docShell; - let taskbarProgress = this._taskbar.getTaskbarProgress(docShell); - this._activeTaskbarProgress = taskbarProgress; + this._activeWindowIsDownloadWindow = aIsDownloadWindow; + if (aWindow) { + // Get the taskbar progress for this window + let docShell = aWindow.QueryInterface(Ci.nsIInterfaceRequestor). + getInterface(Ci.nsIWebNavigation). + QueryInterface(Ci.nsIDocShellTreeItem).treeOwner. + QueryInterface(Ci.nsIInterfaceRequestor). + getInterface(Ci.nsIXULWindow).docShell; + let taskbarProgress = this._taskbar.getTaskbarProgress(docShell); + this._activeTaskbarProgress = taskbarProgress; - this._updateTaskbar(); - // _onActiveWindowUnload is idempotent, so we don't need to check whether - // we've already set this before or not. - aWindow.addEventListener("unload", function () { - DownloadTaskbarProgressUpdater._onActiveWindowUnload(taskbarProgress); - }, false); - } - else { - this._activeTaskbarProgress = null; - } + this._updateTaskbar(); + // _onActiveWindowUnload is idempotent, so we don't need to check whether + // we've already set this before or not. + aWindow.addEventListener("unload", function () { + DownloadTaskbarProgressUpdater._onActiveWindowUnload(taskbarProgress); + }, false); } + else { + this._activeTaskbarProgress = null; + } +#endif }, // / Current state displayed on the active window's taskbar item @@ -213,14 +212,15 @@ var DownloadTaskbarProgressUpdater = _shouldSetState: function DTPU_shouldSetState() { - if (AppConstants.platform == "win") { - // If the active window is not the download manager window, set the state - // only if it is normal or indeterminate. - return this._activeWindowIsDownloadWindow || - (this._taskbarState == Ci.nsITaskbarProgress.STATE_NORMAL || - this._taskbarState == Ci.nsITaskbarProgress.STATE_INDETERMINATE); - } +#ifdef XP_WIN + // If the active window is not the download manager window, set the state + // only if it is normal or indeterminate. + return this._activeWindowIsDownloadWindow || + (this._taskbarState == Ci.nsITaskbarProgress.STATE_NORMAL || + this._taskbarState == Ci.nsITaskbarProgress.STATE_INDETERMINATE); +#else return true; +#endif }, /** diff --git a/toolkit/mozapps/downloads/content/downloads.js b/toolkit/mozapps/downloads/content/downloads.js index 2fdb19a743..66230592ff 100644 --- a/toolkit/mozapps/downloads/content/downloads.js +++ b/toolkit/mozapps/downloads/content/downloads.js @@ -19,7 +19,6 @@ var Cu = Components.utils; Cu.import("resource://gre/modules/XPCOMUtils.jsm"); Cu.import("resource://gre/modules/DownloadUtils.jsm"); Cu.import("resource://gre/modules/Services.jsm"); -Cu.import("resource://gre/modules/AppConstants.jsm"); XPCOMUtils.defineLazyModuleGetter(this, "PluralForm", "resource://gre/modules/PluralForm.jsm"); @@ -253,18 +252,18 @@ function openDownload(aDownload) dontAsk = !pref.getBoolPref(PREF_BDM_CONFIRMOPENEXE); } catch (e) { } - if (AppConstants.platform == "win") { - // On Vista and above, we rely on native security prompting for - // downloaded content unless it's disabled. - try { - var sysInfo = Cc["@mozilla.org/system-info;1"]. - getService(Ci.nsIPropertyBag2); - if (parseFloat(sysInfo.getProperty("version")) >= 6 && - pref.getBoolPref(PREF_BDM_SCANWHENDONE)) { - dontAsk = true; - } - } catch (ex) { } - } +#ifdef XP_WIN + // On Vista and above, we rely on native security prompting for + // downloaded content unless it's disabled. + try { + var sysInfo = Cc["@mozilla.org/system-info;1"]. + getService(Ci.nsIPropertyBag2); + if (parseFloat(sysInfo.getProperty("version")) >= 6 && + pref.getBoolPref(PREF_BDM_SCANWHENDONE)) { + dontAsk = true; + } + } catch (ex) { } +#endif if (!dontAsk) { var strings = document.getElementById("downloadStrings"); @@ -478,10 +477,11 @@ var gDownloadObserver = { removeFromView(dl); break; case "browser-lastwindow-close-granted": - if (AppConstants.platform != "macosx" && - gDownloadManager.activeDownloadCount == 0) { +#ifndef XP_MACOSX + if (gDownloadManager.activeDownloadCount == 0) { setTimeout(gCloseDownloadManager, 0); } +#endif break; } } diff --git a/toolkit/mozapps/downloads/jar.mn b/toolkit/mozapps/downloads/jar.mn index eb761b0d99..29a3d0ee24 100644 --- a/toolkit/mozapps/downloads/jar.mn +++ b/toolkit/mozapps/downloads/jar.mn @@ -6,7 +6,7 @@ toolkit.jar: % content mozapps %content/mozapps/ * content/mozapps/downloads/unknownContentType.xul (content/unknownContentType.xul) * content/mozapps/downloads/downloads.xul (content/downloads.xul) - content/mozapps/downloads/downloads.js (content/downloads.js) +* content/mozapps/downloads/downloads.js (content/downloads.js) content/mozapps/downloads/DownloadProgressListener.js (content/DownloadProgressListener.js) content/mozapps/downloads/downloads.css (content/downloads.css) content/mozapps/downloads/download.xml (content/download.xml) diff --git a/toolkit/mozapps/downloads/moz.build b/toolkit/mozapps/downloads/moz.build index 1850ea7ded..9ad0814750 100644 --- a/toolkit/mozapps/downloads/moz.build +++ b/toolkit/mozapps/downloads/moz.build @@ -17,8 +17,9 @@ EXTRA_PP_COMPONENTS += [ EXTRA_JS_MODULES += [ 'DownloadLastDir.jsm', 'DownloadPaths.jsm', - 'DownloadTaskbarProgress.jsm', 'DownloadUtils.jsm', ] +EXTRA_PP_JS_MODULES += ['DownloadTaskbarProgress.jsm'] + JAR_MANIFESTS += ['jar.mn'] \ No newline at end of file diff --git a/toolkit/mozapps/downloads/nsHelperAppDlg.js b/toolkit/mozapps/downloads/nsHelperAppDlg.js index 27c0fede0b..243db1c2fd 100644 --- a/toolkit/mozapps/downloads/nsHelperAppDlg.js +++ b/toolkit/mozapps/downloads/nsHelperAppDlg.js @@ -4,7 +4,6 @@ const {utils: Cu, interfaces: Ci, classes: Cc, results: Cr} = Components; Cu.import("resource://gre/modules/Services.jsm"); -Cu.import("resource://gre/modules/AppConstants.jsm"); Cu.import("resource://gre/modules/XPCOMUtils.jsm"); XPCOMUtils.defineLazyModuleGetter(this, "EnableDelayHelper", "resource://gre/modules/SharedPromptUtils.jsm"); @@ -408,22 +407,22 @@ nsUnknownContentTypeDialog.prototype = { // is now caught properly in the caller of validateLeafName. var createdFile = DownloadPaths.createNiceUniqueFile(aLocalFolder); - if (AppConstants.platform == "win") { - let ext; - try { - // We can fail here if there's no primary extension set - ext = "." + this.mLauncher.MIMEInfo.primaryExtension; - } catch (e) { } +#ifdef XP_WIN + let ext; + try { + // We can fail here if there's no primary extension set + ext = "." + this.mLauncher.MIMEInfo.primaryExtension; + } catch (e) { } - // Append a file extension if it's an executable that doesn't have one - // but make sure we actually have an extension to add - let leaf = createdFile.leafName; - if (ext && leaf.slice(-ext.length) != ext && createdFile.isExecutable()) { - createdFile.remove(false); - aLocalFolder.leafName = leaf + ext; - createdFile = DownloadPaths.createNiceUniqueFile(aLocalFolder); - } + // Append a file extension if it's an executable that doesn't have one + // but make sure we actually have an extension to add + let leaf = createdFile.leafName; + if (ext && leaf.slice(-ext.length) != ext && createdFile.isExecutable()) { + createdFile.remove(false); + aLocalFolder.leafName = leaf + ext; + createdFile = DownloadPaths.createNiceUniqueFile(aLocalFolder); } +#endif return createdFile; }, @@ -639,22 +638,22 @@ nsUnknownContentTypeDialog.prototype = { // Returns true if opening the default application makes sense. openWithDefaultOK: function() { - // The checking is different on Windows... - if (AppConstants.platform == "win") { - // Windows presents some special cases. - // We need to prevent use of "system default" when the file is - // executable (so the user doesn't launch nasty programs downloaded - // from the web), and, enable use of "system default" if it isn't - // executable (because we will prompt the user for the default app - // in that case). +#ifdef XP_WIN + // Windows presents some special cases. + // We need to prevent use of "system default" when the file is + // executable (so the user doesn't launch nasty programs downloaded + // from the web), and, enable use of "system default" if it isn't + // executable (because we will prompt the user for the default app + // in that case). - // Default is Ok if the file isn't executable (and vice-versa). - return !this.mLauncher.targetFileIsExecutable; - } + // Default is Ok if the file isn't executable (and vice-versa). + return !this.mLauncher.targetFileIsExecutable; +#else // On other platforms, default is Ok if there is a default app. // Note that nsIMIMEInfo providers need to ensure that this holds true // on each platform. return this.mLauncher.MIMEInfo.hasDefaultHandler; +#endif }, // Set "default" application description field. @@ -675,10 +674,11 @@ nsUnknownContentTypeDialog.prototype = { // getPath: getPath: function (aFile) { - if (AppConstants.platform == "macosx") { - return aFile.leafName || aFile.path; - } +#ifdef XP_MACOSX + return aFile.leafName || aFile.path; +#else return aFile.path; +#endif }, // initAppAndSaveToDiskValues: @@ -980,19 +980,20 @@ nsUnknownContentTypeDialog.prototype = { // Retrieve the pretty description from the file getFileDisplayName: function getFileDisplayName(file) { - if (AppConstants.platform == "win") { - if (file instanceof Components.interfaces.nsILocalFileWin) { - try { - return file.getVersionInfoField("FileDescription"); - } catch (e) {} - } - } else if (AppConstants.platform == "macosx") { - if (file instanceof Components.interfaces.nsILocalFileMac) { - try { - return file.bundleDisplayName; - } catch (e) {} - } +#ifdef XP_WIN + if (file instanceof Components.interfaces.nsILocalFileWin) { + try { + return file.getVersionInfoField("FileDescription"); + } catch (e) {} } +#elifdef XP_MACOSX + if (file instanceof Components.interfaces.nsILocalFileMac) { + try { + return file.bundleDisplayName; + } catch (e) {} + } +#endif + return file.leafName; }, @@ -1006,10 +1007,11 @@ nsUnknownContentTypeDialog.prototype = { var otherHandler = this.dialogElement("otherHandler"); otherHandler.removeAttribute("hidden"); otherHandler.setAttribute("path", this.getPath(this.chosenApp.executable)); - if (AppConstants.platform == "win") - otherHandler.label = this.getFileDisplayName(this.chosenApp.executable); - else - otherHandler.label = this.chosenApp.name; +#ifdef XP_WIN + otherHandler.label = this.getFileDisplayName(this.chosenApp.executable); +#else + otherHandler.label = this.chosenApp.name; +#endif this.dialogElement("openHandler").selectedIndex = 1; this.dialogElement("openHandler").setAttribute("lastSelectedItemID", "otherHandler"); @@ -1025,50 +1027,49 @@ nsUnknownContentTypeDialog.prototype = { }, // chooseApp: Open file picker and prompt user for application. chooseApp: function() { - if (AppConstants.platform == "win") { - // Protect against the lack of an extension - var fileExtension = ""; - try { - fileExtension = this.mLauncher.MIMEInfo.primaryExtension; - } catch(ex) { - } +#ifdef XP_WIN + // Protect against the lack of an extension + var fileExtension = ""; + try { + fileExtension = this.mLauncher.MIMEInfo.primaryExtension; + } catch(ex) { + } - // Try to use the pretty description of the type, if one is available. - var typeString = this.mLauncher.MIMEInfo.description; + // Try to use the pretty description of the type, if one is available. + var typeString = this.mLauncher.MIMEInfo.description; - if (!typeString) { - // If there is none, use the extension to - // identify the file, e.g. "ZIP file" - if (fileExtension) { - typeString = - this.dialogElement("strings"). - getFormattedString("fileType", [fileExtension.toUpperCase()]); - } else { - // If we can't even do that, just give up and show the MIME type. - typeString = this.mLauncher.MIMEInfo.MIMEType; - } - } - - var params = {}; - params.title = - this.dialogElement("strings").getString("chooseAppFilePickerTitle"); - params.description = typeString; - params.filename = this.mLauncher.suggestedFileName; - params.mimeInfo = this.mLauncher.MIMEInfo; - params.handlerApp = null; - - this.mDialog.openDialog("chrome://global/content/appPicker.xul", null, - "chrome,modal,centerscreen,titlebar,dialog=yes", - params); - - if (params.handlerApp && - params.handlerApp.executable && - params.handlerApp.executable.isFile()) { - // Remember the file they chose to run. - this.chosenApp = params.handlerApp; + if (!typeString) { + // If there is none, use the extension to + // identify the file, e.g. "ZIP file" + if (fileExtension) { + typeString = + this.dialogElement("strings"). + getFormattedString("fileType", [fileExtension.toUpperCase()]); + } else { + // If we can't even do that, just give up and show the MIME type. + typeString = this.mLauncher.MIMEInfo.MIMEType; } } - else { + + var params = {}; + params.title = + this.dialogElement("strings").getString("chooseAppFilePickerTitle"); + params.description = typeString; + params.filename = this.mLauncher.suggestedFileName; + params.mimeInfo = this.mLauncher.MIMEInfo; + params.handlerApp = null; + + this.mDialog.openDialog("chrome://global/content/appPicker.xul", null, + "chrome,modal,centerscreen,titlebar,dialog=yes", + params); + + if (params.handlerApp && + params.handlerApp.executable && + params.handlerApp.executable.isFile()) { + // Remember the file they chose to run. + this.chosenApp = params.handlerApp; + } +#else #if MOZ_WIDGET_GTK == 3 var nsIApplicationChooser = Components.interfaces.nsIApplicationChooser; var appChooser = Components.classes["@mozilla.org/applicationchooser;1"] @@ -1103,6 +1104,7 @@ nsUnknownContentTypeDialog.prototype = { this.chosenApp = localHandlerApp; } #endif // MOZ_WIDGET_GTK == 3 +#endif // XP_WIN } this.finishChooseApp(); }, diff --git a/toolkit/mozapps/extensions/GMPUtils.jsm b/toolkit/mozapps/extensions/GMPUtils.jsm index a199b4d86b..7f74b3c05e 100644 --- a/toolkit/mozapps/extensions/GMPUtils.jsm +++ b/toolkit/mozapps/extensions/GMPUtils.jsm @@ -16,7 +16,6 @@ this.EXPORTED_SYMBOLS = [ "EME_ADOBE_ID", Cu.import("resource://gre/modules/Preferences.jsm"); Cu.import("resource://gre/modules/Services.jsm"); -Cu.import("resource://gre/modules/AppConstants.jsm"); // GMP IDs const OPEN_H264_ID = "gmp-gmpopenh264"; @@ -73,24 +72,32 @@ this.GMPUtils = { return true; } if (aPlugin.id == EME_ADOBE_ID) { +#if defined(XP_WIN) // Windows Vista and later only supported by Adobe EME. - return AppConstants.isPlatformAndVersionAtLeast("win", "6"); + return true; +#else + return false; +#endif } else if (aPlugin.id == WIDEVINE_ID) { + +#if defined(XP_WIN) || defined(XP_LINUX) || defined(XP_MACOSX) // The Widevine plugin is available for Windows versions Vista and later, // Mac OSX, and Linux. - return AppConstants.isPlatformAndVersionAtLeast("win", "6") || - AppConstants.platform == "macosx" || - AppConstants.platform == "linux"; + return true; +#else + return false; +#endif } return true; }, _is32bitModeMacOS: function() { - if (AppConstants.platform != "macosx") { - return false; - } +#ifdef XP_MACOSX return Services.appinfo.XPCOMABI.split("-")[0] == "x86"; +#else + return false; +#endif }, /** diff --git a/toolkit/mozapps/extensions/moz.build b/toolkit/mozapps/extensions/moz.build index 104e8d734d..b65ce4c689 100644 --- a/toolkit/mozapps/extensions/moz.build +++ b/toolkit/mozapps/extensions/moz.build @@ -29,13 +29,13 @@ EXTRA_PP_COMPONENTS += [ EXTRA_JS_MODULES += [ 'ChromeManifestParser.jsm', 'DeferredSave.jsm', - 'GMPUtils.jsm', 'LightweightThemeManager.jsm', ] EXTRA_PP_JS_MODULES += [ 'AddonManager.jsm', 'GMPInstallManager.jsm', + 'GMPUtils.jsm', ] # Additional debugging info is exposed in debug builds diff --git a/toolkit/mozapps/update/moz.build b/toolkit/mozapps/update/moz.build index 5f1d567647..f80e5bf5c5 100644 --- a/toolkit/mozapps/update/moz.build +++ b/toolkit/mozapps/update/moz.build @@ -18,11 +18,12 @@ XPIDL_SOURCES += [ TEST_DIRS += ['tests'] EXTRA_COMPONENTS += [ - 'nsUpdateService.js', 'nsUpdateService.manifest', 'nsUpdateServiceStub.js', ] +EXTRA_PP_COMPONENTS += ['nsUpdateService.js'] + JAR_MANIFESTS += ['jar.mn'] with Files('**'): diff --git a/toolkit/mozapps/update/nsUpdateService.js b/toolkit/mozapps/update/nsUpdateService.js index dca0a007eb..84c92c6f41 100644 --- a/toolkit/mozapps/update/nsUpdateService.js +++ b/toolkit/mozapps/update/nsUpdateService.js @@ -12,7 +12,6 @@ Cu.import("resource://gre/modules/XPCOMUtils.jsm", this); Cu.import("resource://gre/modules/FileUtils.jsm", this); Cu.import("resource://gre/modules/Services.jsm", this); Cu.import("resource://gre/modules/ctypes.jsm", this); -Cu.import("resource://gre/modules/AppConstants.jsm", this); Cu.importGlobalProperties(["XMLHttpRequest"]); const UPDATESERVICE_CID = Components.ID("{B3C290A6-3943-4B89-8BBE-C01EB7B3B311}"); @@ -219,10 +218,7 @@ function closeHandle(handle) { * @return The Win32 handle to the mutex. */ function createMutex(aName, aAllowExisting = true) { - if (AppConstants.platform != "win") { - throw Cr.NS_ERROR_NOT_IMPLEMENTED; - } - +#ifdef XP_WIN const INITIAL_OWN = 1; const ERROR_ALREADY_EXISTS = 0xB7; let lib = ctypes.open("kernel32.dll"); @@ -246,6 +242,9 @@ function createMutex(aName, aAllowExisting = true) { } return handle; +#else + throw Cr.NS_ERROR_NOT_IMPLEMENTED; +#endif } /** @@ -257,10 +256,7 @@ function createMutex(aName, aAllowExisting = true) { * @return Global mutex path */ function getPerInstallationMutexName(aGlobal = true) { - if (AppConstants.platform != "win") { - throw Cr.NS_ERROR_NOT_IMPLEMENTED; - } - +#ifdef XP_WIN let hasher = Cc["@mozilla.org/security/hash;1"]. createInstance(Ci.nsICryptoHash); hasher.init(hasher.SHA1); @@ -274,6 +270,9 @@ function getPerInstallationMutexName(aGlobal = true) { hasher.update(data, data.length); return (aGlobal ? "Global\\" : "") + "MozillaUpdateMutex-" + hasher.finish(true); +#else + throw Cr.NS_ERROR_NOT_IMPLEMENTED; +#endif } /** @@ -285,13 +284,14 @@ function getPerInstallationMutexName(aGlobal = true) { * @return true if this instance holds the update mutex */ function hasUpdateMutex() { - if (AppConstants.platform != "win") { - return true; - } +#ifdef XP_WIN if (!gUpdateMutexHandle) { gUpdateMutexHandle = createMutex(getPerInstallationMutexName(true), false); } return !!gUpdateMutexHandle; +#else + return true; +#endif } /** @@ -322,10 +322,7 @@ function areDirectoryEntriesWriteable(aDir) { * @return true if elevation is required, false otherwise */ function getElevationRequired() { - if (AppConstants.platform != "macosx") { - return false; - } - +#ifdef XP_MACOSX try { // Recursively check that the application bundle (and its descendants) can // be written to. @@ -344,6 +341,7 @@ function getElevationRequired() { } LOG("getElevationRequired - able to write to application bundle, elevation " + "not required"); +#endif return false; } @@ -355,85 +353,86 @@ function getElevationRequired() { * @return true if an update can be applied, false otherwise */ function getCanApplyUpdates() { - if (AppConstants.platform != "macosx") { - try { - let updateTestFile = getUpdateFile([FILE_UPDATE_TEST]); - LOG("getCanApplyUpdates - testing write access " + updateTestFile.path); - testWriteAccess(updateTestFile, false); - if (AppConstants.platform == "win") { - // Example windowsVersion: Windows XP == 5.1 - let windowsVersion = Services.sysinfo.getProperty("version"); - LOG("getCanApplyUpdates - windowsVersion = " + windowsVersion); +#ifndef XP_MACOSX + try { + let updateTestFile = getUpdateFile([FILE_UPDATE_TEST]); + LOG("getCanApplyUpdates - testing write access " + updateTestFile.path); + testWriteAccess(updateTestFile, false); - /** - * For Vista, updates can be performed to a location requiring admin - * privileges by requesting elevation via the UAC prompt when launching - * updater.exe if the appDir is under the Program Files directory - * (e.g. C:\Program Files\) and UAC is turned on and we can elevate - * (e.g. user has a split token). - * - * Note: this does note attempt to handle the case where UAC is turned on - * and the installation directory is in a restricted location that - * requires admin privileges to update other than Program Files. - */ - let userCanElevate = false; +#ifdef XP_WIN + // Example windowsVersion: Windows XP == 5.1 + let windowsVersion = Services.sysinfo.getProperty("version"); + LOG("getCanApplyUpdates - windowsVersion = " + windowsVersion); - if (parseFloat(windowsVersion) >= 6) { - try { - // KEY_UPDROOT will fail and throw an exception if - // appDir is not under the Program Files, so we rely on that - let dir = Services.dirsvc.get(KEY_UPDROOT, Ci.nsIFile); - // appDir is under Program Files, so check if the user can elevate - userCanElevate = Services.appinfo.QueryInterface(Ci.nsIWinAppHelper). - userCanElevate; - LOG("getCanApplyUpdates - on Vista, userCanElevate: " + userCanElevate); - } - catch (ex) { - // When the installation directory is not under Program Files, - // fall through to checking if write access to the - // installation directory is available. - LOG("getCanApplyUpdates - on Vista, appDir is not under Program Files"); - } - } + /** + * For Vista, updates can be performed to a location requiring admin + * privileges by requesting elevation via the UAC prompt when launching + * updater.exe if the appDir is under the Program Files directory + * (e.g. C:\Program Files\) and UAC is turned on and we can elevate + * (e.g. user has a split token). + * + * Note: this does note attempt to handle the case where UAC is turned on + * and the installation directory is in a restricted location that + * requires admin privileges to update other than Program Files. + */ + let userCanElevate = false; - /** - * On Windows, we no longer store the update under the app dir. - * - * If we are on Windows (including Vista, if we can't elevate) we need to - * to check that we can create and remove files from the actual app - * directory (like C:\Program Files\Mozilla Firefox). If we can't - * (because this user is not an adminstrator, for example) canUpdate() - * should return false. - * - * For Vista, we perform this check to enable updating the application - * when the user has write access to the installation directory under the - * following scenarios: - * 1) the installation directory is not under Program Files - * (e.g. C:\Program Files) - * 2) UAC is turned off - * 3) UAC is turned on and the user is not an admin - * (e.g. the user does not have a split token) - * 4) UAC is turned on and the user is already elevated, so they can't be - * elevated again - */ - if (!userCanElevate) { - // if we're unable to create the test file this will throw an exception. - let appDirTestFile = getAppBaseDir(); - appDirTestFile.append(FILE_UPDATE_TEST); - LOG("getCanApplyUpdates - testing write access " + appDirTestFile.path); - if (appDirTestFile.exists()) { - appDirTestFile.remove(false); - } - appDirTestFile.create(Ci.nsILocalFile.NORMAL_FILE_TYPE, FileUtils.PERMS_FILE); - appDirTestFile.remove(false); - } + if (parseFloat(windowsVersion) >= 6) { + try { + // KEY_UPDROOT will fail and throw an exception if + // appDir is not under the Program Files, so we rely on that + let dir = Services.dirsvc.get(KEY_UPDROOT, Ci.nsIFile); + // appDir is under Program Files, so check if the user can elevate + userCanElevate = Services.appinfo.QueryInterface(Ci.nsIWinAppHelper). + userCanElevate; + LOG("getCanApplyUpdates - on Vista, userCanElevate: " + userCanElevate); + } + catch (ex) { + // When the installation directory is not under Program Files, + // fall through to checking if write access to the + // installation directory is available. + LOG("getCanApplyUpdates - on Vista, appDir is not under Program Files"); } - } catch (e) { - LOG("getCanApplyUpdates - unable to apply updates. Exception: " + e); - // No write privileges to install directory - return false; } - } + + /** + * On Windows, we no longer store the update under the app dir. + * + * If we are on Windows (including Vista, if we can't elevate) we need to + * to check that we can create and remove files from the actual app + * directory (like C:\Program Files\Mozilla Firefox). If we can't + * (because this user is not an adminstrator, for example) canUpdate() + * should return false. + * + * For Vista, we perform this check to enable updating the application + * when the user has write access to the installation directory under the + * following scenarios: + * 1) the installation directory is not under Program Files + * (e.g. C:\Program Files) + * 2) UAC is turned off + * 3) UAC is turned on and the user is not an admin + * (e.g. the user does not have a split token) + * 4) UAC is turned on and the user is already elevated, so they can't be + * elevated again + */ + if (!userCanElevate) { + // if we're unable to create the test file this will throw an exception. + let appDirTestFile = getAppBaseDir(); + appDirTestFile.append(FILE_UPDATE_TEST); + LOG("getCanApplyUpdates - testing write access " + appDirTestFile.path); + if (appDirTestFile.exists()) { + appDirTestFile.remove(false); + } + appDirTestFile.create(Ci.nsILocalFile.NORMAL_FILE_TYPE, FileUtils.PERMS_FILE); + appDirTestFile.remove(false); + } +#endif // XP_WIN + } catch (e) { + LOG("getCanApplyUpdates - unable to apply updates. Exception: " + e); + // No write privileges to install directory + return false; + } +#endif // !XP_MACOSX LOG("getCanApplyUpdates - able to apply updates"); return true; @@ -454,27 +453,29 @@ XPCOMUtils.defineLazyGetter(this, "gCanStageUpdatesSession", function aus_gCSUS( try { let updateTestFile; - if (AppConstants.platform == "macosx") { - updateTestFile = getUpdateFile([FILE_UPDATE_TEST]); - } else { - updateTestFile = getInstallDirRoot(); - updateTestFile.append(FILE_UPDATE_TEST); - } +#ifdef XP_MACOSX + updateTestFile = getUpdateFile([FILE_UPDATE_TEST]); +#else + updateTestFile = getInstallDirRoot(); + updateTestFile.append(FILE_UPDATE_TEST); +#endif + LOG("gCanStageUpdatesSession - testing write access " + updateTestFile.path); testWriteAccess(updateTestFile, true); - if (AppConstants.platform != "macosx") { - // On all platforms except Mac, we need to test the parent directory as - // well, as we need to be able to move files in that directory during the - // replacing step. - updateTestFile = getInstallDirRoot().parent; - updateTestFile.append(FILE_UPDATE_TEST); - LOG("gCanStageUpdatesSession - testing write access " + - updateTestFile.path); - updateTestFile.createUnique(Ci.nsILocalFile.DIRECTORY_TYPE, - FileUtils.PERMS_DIRECTORY); - updateTestFile.remove(false); - } + +#ifndef XP_MACOSX + // On all platforms except Mac, we need to test the parent directory as + // well, as we need to be able to move files in that directory during the + // replacing step. + updateTestFile = getInstallDirRoot().parent; + updateTestFile.append(FILE_UPDATE_TEST); + LOG("gCanStageUpdatesSession - testing write access " + + updateTestFile.path); + updateTestFile.createUnique(Ci.nsILocalFile.DIRECTORY_TYPE, + FileUtils.PERMS_DIRECTORY); + updateTestFile.remove(false); +#endif // !XP_MACOSX } catch (e) { LOG("gCanStageUpdatesSession - unable to stage updates. Exception: " + e); @@ -593,10 +594,10 @@ function getAppBaseDir() { */ function getInstallDirRoot() { let dir = getAppBaseDir(); - if (AppConstants.platform == "macosx") { - // On Mac, we store the Updated.app directory inside the bundle directory. - dir = dir.parent.parent; - } +#ifdef XP_MACOSX + // On Mac, we store the Updated.app directory inside the bundle directory. + dir = dir.parent.parent; +#endif return dir; } @@ -879,31 +880,33 @@ function handleUpdateFailure(update, errorCode) { let cancelations = Services.prefs.getIntPref(PREF_APP_UPDATE_CANCELATIONS, 0); cancelations++; Services.prefs.setIntPref(PREF_APP_UPDATE_CANCELATIONS, cancelations); - if (AppConstants.platform == "macosx") { - let osxCancelations = Services.prefs.getIntPref(PREF_APP_UPDATE_CANCELATIONS_OSX, 0); - osxCancelations++; - Services.prefs.setIntPref(PREF_APP_UPDATE_CANCELATIONS_OSX, - osxCancelations); - let maxCancels = Services.prefs.getIntPref( - PREF_APP_UPDATE_CANCELATIONS_OSX_MAX, - DEFAULT_CANCELATIONS_OSX_MAX); - // Prevent the preference from setting a value greater than 5. - maxCancels = Math.min(maxCancels, 5); - if (osxCancelations >= maxCancels) { - cleanupActiveUpdate(); - } else { - writeStatusFile(getUpdatesDir(), - update.state = STATE_PENDING_ELEVATE); - } - update.statusText = gUpdateBundle.GetStringFromName("elevationFailure"); - update.QueryInterface(Ci.nsIWritablePropertyBag); - update.setProperty("patchingFailed", "elevationFailure"); - let prompter = Cc["@mozilla.org/updates/update-prompt;1"]. - createInstance(Ci.nsIUpdatePrompt); - prompter.showUpdateError(update); + +#ifdef XP_MACOSX + let osxCancelations = Services.prefs.getIntPref(PREF_APP_UPDATE_CANCELATIONS_OSX, 0); + osxCancelations++; + Services.prefs.setIntPref(PREF_APP_UPDATE_CANCELATIONS_OSX, + osxCancelations); + let maxCancels = Services.prefs.getIntPref( + PREF_APP_UPDATE_CANCELATIONS_OSX_MAX, + DEFAULT_CANCELATIONS_OSX_MAX); + // Prevent the preference from setting a value greater than 5. + maxCancels = Math.min(maxCancels, 5); + if (osxCancelations >= maxCancels) { + cleanupActiveUpdate(); } else { - writeStatusFile(getUpdatesDir(), update.state = STATE_PENDING); + writeStatusFile(getUpdatesDir(), + update.state = STATE_PENDING_ELEVATE); } + update.statusText = gUpdateBundle.GetStringFromName("elevationFailure"); + update.QueryInterface(Ci.nsIWritablePropertyBag); + update.setProperty("patchingFailed", "elevationFailure"); + let prompter = Cc["@mozilla.org/updates/update-prompt;1"]. + createInstance(Ci.nsIUpdatePrompt); + prompter.showUpdateError(update); +#else + writeStatusFile(getUpdatesDir(), update.state = STATE_PENDING); +#endif + return true; } @@ -1483,12 +1486,15 @@ UpdateService.prototype = { Services.obs.removeObserver(this, topic); Services.prefs.removeObserver(PREF_APP_UPDATE_LOG, this); - if (AppConstants.platform == "win" && gUpdateMutexHandle) { +#ifdef XP_WIN + if (gUpdateMutexHandle) { // If we hold the update mutex, let it go! // The OS would clean this up sometime after shutdown, // but that would have no guarantee on timing. closeHandle(gUpdateMutexHandle); } +#endif + if (this._retryTimer) { this._retryTimer.cancel(); } @@ -1845,7 +1851,8 @@ UpdateService.prototype = { }); let update = minorUpdate || majorUpdate; - if (AppConstants.platform == "macosx" && update) { +#ifdef XP_MACOSX + if (update) { if (getElevationRequired()) { let installAttemptVersion = Services.prefs.getCharPref( PREF_APP_UPDATE_ELEVATE_VERSION, @@ -1895,6 +1902,7 @@ UpdateService.prototype = { } } } +#endif return update; }, @@ -2890,11 +2898,11 @@ Downloader.prototype = { LOG("Downloader:_verifyDownload downloaded size == expected size."); +#ifdef MOZ_VERIFY_MAR_SIGNATURE // The hash check is not necessary when mar signatures are used to verify // the downloaded mar file. - if (AppConstants.MOZ_VERIFY_MAR_SIGNATURE) { - return true; - } + return true; +#endif let fileStream = Cc["@mozilla.org/network/file-input-stream;1"]. createInstance(Ci.nsIFileInputStream); diff --git a/toolkit/profile/content/createProfileWizard.js b/toolkit/profile/content/createProfileWizard.js index 14d006b317..aa87eacd71 100644 --- a/toolkit/profile/content/createProfileWizard.js +++ b/toolkit/profile/content/createProfileWizard.js @@ -5,8 +5,6 @@ const C = Components.classes; const I = Components.interfaces; -Components.utils.import("resource://gre/modules/AppConstants.jsm"); - const ToolkitProfileService = "@mozilla.org/toolkit/profile-service;1"; var gProfileService; @@ -118,12 +116,11 @@ function checkCurrentInput(currentInput) if (!errorMessage) { finishText.className = ""; - if (AppConstants.platform == "macosx") { - finishText.firstChild.data = gProfileManagerBundle.getString("profileFinishTextMac"); - } - else { - finishText.firstChild.data = gProfileManagerBundle.getString("profileFinishText"); - } +#ifdef XP_MACOSX + finishText.firstChild.data = gProfileManagerBundle.getString("profileFinishTextMac"); +#else + finishText.firstChild.data = gProfileManagerBundle.getString("profileFinishText"); +#endif canAdvance = true; } else { diff --git a/toolkit/profile/content/profileSelection.js b/toolkit/profile/content/profileSelection.js index 02b9d68732..05ef6f5edb 100644 --- a/toolkit/profile/content/profileSelection.js +++ b/toolkit/profile/content/profileSelection.js @@ -4,7 +4,6 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -Components.utils.import("resource://gre/modules/AppConstants.jsm"); Components.utils.import("resource://gre/modules/Services.jsm"); const C = Components.classes; @@ -135,8 +134,9 @@ function onProfilesKey(aEvent) switch ( aEvent.keyCode ) { case KeyEvent.DOM_VK_BACK_SPACE: - if (AppConstants.platform != "macosx") - break; +#ifndef XP_MACOSX + break; +#endif case KeyEvent.DOM_VK_DELETE: ConfirmDelete(); break; diff --git a/toolkit/profile/jar.mn b/toolkit/profile/jar.mn index 9b7c22266e..1c4afac4ca 100644 --- a/toolkit/profile/jar.mn +++ b/toolkit/profile/jar.mn @@ -3,7 +3,7 @@ # file, You can obtain one at http://mozilla.org/MPL/2.0/. toolkit.jar: - content/mozapps/profile/createProfileWizard.js (content/createProfileWizard.js) +* content/mozapps/profile/createProfileWizard.js (content/createProfileWizard.js) * content/mozapps/profile/createProfileWizard.xul (content/createProfileWizard.xul) - content/mozapps/profile/profileSelection.js (content/profileSelection.js) +* content/mozapps/profile/profileSelection.js (content/profileSelection.js) content/mozapps/profile/profileSelection.xul (content/profileSelection.xul)