[MediaStream][Mac] Revoke sandbox extensions when capture ends
authoreric.carlson@apple.com <eric.carlson@apple.com@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Thu, 8 Dec 2016 02:25:57 +0000 (02:25 +0000)
committereric.carlson@apple.com <eric.carlson@apple.com@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Thu, 8 Dec 2016 02:25:57 +0000 (02:25 +0000)
https://bugs.webkit.org/show_bug.cgi?id=165476

Reviewed by Brady Eidson.
Source/WebKit2:

Track media capture by process so it is possible to revoke the sandbox extensions issued to
a web process when capture stops. Allocate WK2 user media permission manager lazily rather
than every time a page is created as most pages won't need one.

* CMakeLists.txt: Add new files.

* UIProcess/UserMediaPermissionRequestManagerProxy.cpp:
(WebKit::UserMediaPermissionRequestManagerProxy::UserMediaPermissionRequestManagerProxy): Register
  with process manager.
(WebKit::UserMediaPermissionRequestManagerProxy::~UserMediaPermissionRequestManagerProxy):
(WebKit::UserMediaPermissionRequestManagerProxy::userMediaAccessWasGranted): Move sandbox
  extension code to the process manager.
(WebKit::UserMediaPermissionRequestManagerProxy::stopCapture): New.
(WebKit::UserMediaPermissionRequestManagerProxy::startedCaptureSession): New, report state
  change to the process manager.
(WebKit::UserMediaPermissionRequestManagerProxy::endedCaptureSession): Ditto.
* UIProcess/UserMediaPermissionRequestManagerProxy.h:

* UIProcess/UserMediaProcessManager.cpp: Added.
(WebKit::ProcessState::ProcessState):
(WebKit::ProcessState::managers):
(WebKit::ProcessState::sandboxExtensionsGranted):
(WebKit::ProcessState::setSandboxExtensionsGranted):
(WebKit::stateMap):
(WebKit::processState):
(WebKit::ProcessState::addRequestManager):
(WebKit::ProcessState::removeRequestManager):
(WebKit::UserMediaProcessManager::singleton):
(WebKit::UserMediaProcessManager::addUserMediaPermissionRequestManagerProxy):
(WebKit::UserMediaProcessManager::removeUserMediaPermissionRequestManagerProxy):
(WebKit::UserMediaProcessManager::willCreateMediaStream):
(WebKit::UserMediaProcessManager::startedCaptureSession):
(WebKit::UserMediaProcessManager::endedCaptureSession):
* UIProcess/UserMediaProcessManager.h: Added.

* UIProcess/WebPageProxy.cpp:
(WebKit::WebPageProxy::WebPageProxy): Don't allocate m_userMediaPermissionRequestManager.
(WebKit::WebPageProxy::resetState): Set m_userMediaPermissionRequestManager to null.
(WebKit::WebPageProxy::userMediaPermissionRequestManager): Allocate m_userMediaPermissionRequestManager
  lazily as most pages don't need it.
(WebKit::WebPageProxy::requestUserMediaPermissionForFrame): Call userMediaPermissionRequestManager().
(WebKit::WebPageProxy::enumerateMediaDevicesForFrame): Ditto.
(WebKit::WebPageProxy::clearUserMediaState): Ditto.
(WebKit::WebPageProxy::isPlayingMediaDidChange): Report capture state changes to the request
  manager proxy.
* UIProcess/WebPageProxy.h:

* WebKit2.xcodeproj/project.pbxproj: Add new files.

* WebProcess/MediaStream/MediaDeviceSandboxExtensions.cpp: Added.
(WebKit::MediaDeviceSandboxExtensions::MediaDeviceSandboxExtensions):
(WebKit::MediaDeviceSandboxExtensions::encode):
(WebKit::MediaDeviceSandboxExtensions::decode):
(WebKit::MediaDeviceSandboxExtensions::operator[]):
(WebKit::MediaDeviceSandboxExtensions::size):
* WebProcess/MediaStream/MediaDeviceSandboxExtensions.h: Added.

* WebProcess/MediaStream/UserMediaPermissionRequestManager.cpp:
(WebKit::UserMediaPermissionRequestManager::~UserMediaPermissionRequestManager): Sandbox extension
  is now in a HashMap, not a Vector.
(WebKit::UserMediaPermissionRequestManager::grantUserMediaDeviceSandboxExtensions): Record
  IDs with extensions so they can be revoked later.
(WebKit::UserMediaPermissionRequestManager::revokeUserMediaDeviceSandboxExtensions): New.
(WebKit::UserMediaPermissionRequestManager::grantUserMediaDevicesSandboxExtension): Deleted.
* WebProcess/MediaStream/UserMediaPermissionRequestManager.h:

* WebProcess/WebPage/WebPage.cpp:
(WebKit::WebPage::grantUserMediaDeviceSandboxExtensions):
(WebKit::WebPage::revokeUserMediaDeviceSandboxExtensions):
(WebKit::WebPage::grantUserMediaDevicesSandboxExtension): Deleted.
* WebProcess/WebPage/WebPage.h:
* WebProcess/WebPage/WebPage.messages.in:

Tools:

Add a test which loads a page that calls navigator.mediaDevices.enumerateDevices, kills the
page, and loads the same page again to ensure that the WK2 UserMediaPermissionRequestManagerProxy
is reset and recreated when a web page exits and is reloaded.

* TestWebKitAPI/PlatformGTK.cmake:
* TestWebKitAPI/TestWebKitAPI.xcodeproj/project.pbxproj:
* TestWebKitAPI/Tests/WebKit2/EnumerateMediaDevices.cpp: Added.
(TestWebKitAPI::checkUserMediaPermissionCallback):
(TestWebKitAPI::TEST):
* TestWebKitAPI/Tests/WebKit2/enumerateMediaDevices.html: Added.

git-svn-id: https://svn.webkit.org/repository/webkit/trunk@209512 268f45cc-cd09-0410-ab3c-d52691b4dbfc

21 files changed:
Source/WebKit2/CMakeLists.txt
Source/WebKit2/ChangeLog
Source/WebKit2/UIProcess/UserMediaPermissionRequestManagerProxy.cpp
Source/WebKit2/UIProcess/UserMediaPermissionRequestManagerProxy.h
Source/WebKit2/UIProcess/UserMediaProcessManager.cpp [new file with mode: 0644]
Source/WebKit2/UIProcess/UserMediaProcessManager.h [new file with mode: 0644]
Source/WebKit2/UIProcess/WebPageProxy.cpp
Source/WebKit2/UIProcess/WebPageProxy.h
Source/WebKit2/WebKit2.xcodeproj/project.pbxproj
Source/WebKit2/WebProcess/MediaStream/MediaDeviceSandboxExtensions.cpp [new file with mode: 0644]
Source/WebKit2/WebProcess/MediaStream/MediaDeviceSandboxExtensions.h [new file with mode: 0644]
Source/WebKit2/WebProcess/MediaStream/UserMediaPermissionRequestManager.cpp
Source/WebKit2/WebProcess/MediaStream/UserMediaPermissionRequestManager.h
Source/WebKit2/WebProcess/WebPage/WebPage.cpp
Source/WebKit2/WebProcess/WebPage/WebPage.h
Source/WebKit2/WebProcess/WebPage/WebPage.messages.in
Tools/ChangeLog
Tools/TestWebKitAPI/PlatformGTK.cmake
Tools/TestWebKitAPI/TestWebKitAPI.xcodeproj/project.pbxproj
Tools/TestWebKitAPI/Tests/WebKit2/EnumerateMediaDevices.cpp [new file with mode: 0644]
Tools/TestWebKitAPI/Tests/WebKit2/enumerateMediaDevices.html [new file with mode: 0644]

index c44f4aa..ab8c253 100644 (file)
@@ -376,6 +376,7 @@ set(WebKit2_SOURCES
     UIProcess/UserMediaPermissionCheckProxy.cpp
     UIProcess/UserMediaPermissionRequestManagerProxy.cpp
     UIProcess/UserMediaPermissionRequestProxy.cpp
+    UIProcess/UserMediaProcessManager.cpp
     UIProcess/VisitedLinkStore.cpp
     UIProcess/WebBackForwardList.cpp
     UIProcess/WebColorPicker.cpp
@@ -588,6 +589,7 @@ set(WebKit2_SOURCES
     WebProcess/InjectedBundle/DOM/InjectedBundleNodeHandle.cpp
     WebProcess/InjectedBundle/DOM/InjectedBundleRangeHandle.cpp
 
+    WebProcess/MediaStream/MediaDeviceSandboxExtensions.cpp
     WebProcess/MediaStream/UserMediaPermissionRequestManager.cpp
 
     WebProcess/Network/NetworkProcessConnection.cpp
index 2153c30..2638d87 100644 (file)
@@ -1,3 +1,83 @@
+2016-12-07  Eric Carlson  <eric.carlson@apple.com>
+
+        [MediaStream][Mac] Revoke sandbox extensions when capture ends
+        https://bugs.webkit.org/show_bug.cgi?id=165476
+
+        Reviewed by Brady Eidson.
+
+        Track media capture by process so it is possible to revoke the sandbox extensions issued to
+        a web process when capture stops. Allocate WK2 user media permission manager lazily rather
+        than every time a page is created as most pages won't need one.
+
+        * CMakeLists.txt: Add new files.
+
+        * UIProcess/UserMediaPermissionRequestManagerProxy.cpp:
+        (WebKit::UserMediaPermissionRequestManagerProxy::UserMediaPermissionRequestManagerProxy): Register
+          with process manager.
+        (WebKit::UserMediaPermissionRequestManagerProxy::~UserMediaPermissionRequestManagerProxy):
+        (WebKit::UserMediaPermissionRequestManagerProxy::userMediaAccessWasGranted): Move sandbox 
+          extension code to the process manager.
+        (WebKit::UserMediaPermissionRequestManagerProxy::stopCapture): New.
+        (WebKit::UserMediaPermissionRequestManagerProxy::startedCaptureSession): New, report state
+          change to the process manager.
+        (WebKit::UserMediaPermissionRequestManagerProxy::endedCaptureSession): Ditto.
+        * UIProcess/UserMediaPermissionRequestManagerProxy.h:
+
+        * UIProcess/UserMediaProcessManager.cpp: Added.
+        (WebKit::ProcessState::ProcessState):
+        (WebKit::ProcessState::managers):
+        (WebKit::ProcessState::sandboxExtensionsGranted):
+        (WebKit::ProcessState::setSandboxExtensionsGranted):
+        (WebKit::stateMap):
+        (WebKit::processState):
+        (WebKit::ProcessState::addRequestManager):
+        (WebKit::ProcessState::removeRequestManager):
+        (WebKit::UserMediaProcessManager::singleton):
+        (WebKit::UserMediaProcessManager::addUserMediaPermissionRequestManagerProxy):
+        (WebKit::UserMediaProcessManager::removeUserMediaPermissionRequestManagerProxy):
+        (WebKit::UserMediaProcessManager::willCreateMediaStream):
+        (WebKit::UserMediaProcessManager::startedCaptureSession):
+        (WebKit::UserMediaProcessManager::endedCaptureSession):
+        * UIProcess/UserMediaProcessManager.h: Added.
+
+        * UIProcess/WebPageProxy.cpp:
+        (WebKit::WebPageProxy::WebPageProxy): Don't allocate m_userMediaPermissionRequestManager.
+        (WebKit::WebPageProxy::resetState): Set m_userMediaPermissionRequestManager to null.
+        (WebKit::WebPageProxy::userMediaPermissionRequestManager): Allocate m_userMediaPermissionRequestManager
+          lazily as most pages don't need it.
+        (WebKit::WebPageProxy::requestUserMediaPermissionForFrame): Call userMediaPermissionRequestManager().
+        (WebKit::WebPageProxy::enumerateMediaDevicesForFrame): Ditto.
+        (WebKit::WebPageProxy::clearUserMediaState): Ditto.
+        (WebKit::WebPageProxy::isPlayingMediaDidChange): Report capture state changes to the request
+          manager proxy.
+        * UIProcess/WebPageProxy.h:
+
+        * WebKit2.xcodeproj/project.pbxproj: Add new files.
+
+        * WebProcess/MediaStream/MediaDeviceSandboxExtensions.cpp: Added.
+        (WebKit::MediaDeviceSandboxExtensions::MediaDeviceSandboxExtensions):
+        (WebKit::MediaDeviceSandboxExtensions::encode):
+        (WebKit::MediaDeviceSandboxExtensions::decode):
+        (WebKit::MediaDeviceSandboxExtensions::operator[]):
+        (WebKit::MediaDeviceSandboxExtensions::size):
+        * WebProcess/MediaStream/MediaDeviceSandboxExtensions.h: Added.
+
+        * WebProcess/MediaStream/UserMediaPermissionRequestManager.cpp:
+        (WebKit::UserMediaPermissionRequestManager::~UserMediaPermissionRequestManager): Sandbox extension
+          is now in a HashMap, not a Vector.
+        (WebKit::UserMediaPermissionRequestManager::grantUserMediaDeviceSandboxExtensions): Record
+          IDs with extensions so they can be revoked later.
+        (WebKit::UserMediaPermissionRequestManager::revokeUserMediaDeviceSandboxExtensions): New.
+        (WebKit::UserMediaPermissionRequestManager::grantUserMediaDevicesSandboxExtension): Deleted.
+        * WebProcess/MediaStream/UserMediaPermissionRequestManager.h:
+
+        * WebProcess/WebPage/WebPage.cpp:
+        (WebKit::WebPage::grantUserMediaDeviceSandboxExtensions):
+        (WebKit::WebPage::revokeUserMediaDeviceSandboxExtensions):
+        (WebKit::WebPage::grantUserMediaDevicesSandboxExtension): Deleted.
+        * WebProcess/WebPage/WebPage.h:
+        * WebProcess/WebPage/WebPage.messages.in:
+
 2016-12-07  Jeremy Jones  <jeremyj@apple.com>
 
         One esc to exit fullscreen and pointer lock
index 45b5a2c..af584dc 100644 (file)
@@ -22,6 +22,7 @@
 
 #include "APISecurityOrigin.h"
 #include "APIUIClient.h"
+#include "UserMediaProcessManager.h"
 #include "WebPageMessages.h"
 #include "WebPageProxy.h"
 #include "WebProcessProxy.h"
@@ -92,6 +93,17 @@ FrameAuthorizationState& UserMediaPermissionRequestManagerProxy::stateForRequest
 UserMediaPermissionRequestManagerProxy::UserMediaPermissionRequestManagerProxy(WebPageProxy& page)
     : m_page(page)
 {
+#if ENABLE(MEDIA_STREAM)
+    UserMediaProcessManager::singleton().addUserMediaPermissionRequestManagerProxy(*this);
+#endif
+}
+
+UserMediaPermissionRequestManagerProxy::~UserMediaPermissionRequestManagerProxy()
+{
+#if ENABLE(MEDIA_STREAM)
+    UserMediaProcessManager::singleton().removeUserMediaPermissionRequestManagerProxy(*this);
+#endif
+    invalidateRequests();
 }
 
 void UserMediaPermissionRequestManagerProxy::invalidateRequests()
@@ -197,29 +209,7 @@ void UserMediaPermissionRequestManagerProxy::userMediaAccessWasGranted(uint64_t
     fameState.setHasPermissionToUseCaptureDevice(audioDeviceUID, true);
     fameState.setHasPermissionToUseCaptureDevice(videoDeviceUID, true);
 
-    size_t extensionCount = 0;
-    unsigned requiredExtensions = SandboxExtensionsGranted::None;
-    if (!audioDeviceUID.isEmpty()) {
-        requiredExtensions |= SandboxExtensionsGranted::Audio;
-        extensionCount++;
-    }
-    if (!videoDeviceUID.isEmpty()) {
-        requiredExtensions |= SandboxExtensionsGranted::Video;
-        extensionCount++;
-    }
-
-    unsigned currentExtensions = m_pageSandboxExtensionsGranted;
-    if (!(requiredExtensions & currentExtensions)) {
-        ASSERT(extensionCount);
-        m_pageSandboxExtensionsGranted = requiredExtensions | currentExtensions;
-        SandboxExtension::HandleArray handles;
-        handles.allocate(extensionCount);
-        if (!videoDeviceUID.isEmpty())
-            SandboxExtension::createHandleForGenericExtension("com.apple.webkit.camera", handles[--extensionCount]);
-        if (!audioDeviceUID.isEmpty())
-            SandboxExtension::createHandleForGenericExtension("com.apple.webkit.microphone", handles[--extensionCount]);
-        m_page.process().send(Messages::WebPage::GrantUserMediaDevicesSandboxExtension(handles), m_page.pageID());
-    }
+    UserMediaProcessManager::singleton().willCreateMediaStream(*this, !audioDeviceUID.isEmpty(), !videoDeviceUID.isEmpty());
 
     m_page.process().send(Messages::WebPage::UserMediaAccessWasGranted(userMediaID, audioDeviceUID, videoDeviceUID), m_page.pageID());
 #else
@@ -342,4 +332,34 @@ void UserMediaPermissionRequestManagerProxy::syncWithWebCorePrefs() const
 #endif
 }
 
+void UserMediaPermissionRequestManagerProxy::stopCapture()
+{
+    if (!m_page.isValid())
+        return;
+
+#if ENABLE(MEDIA_STREAM)
+    m_page.setMuted(WebCore::MediaProducer::CaptureDevicesAreMuted);
+#endif
+}
+
+void UserMediaPermissionRequestManagerProxy::startedCaptureSession()
+{
+    if (!m_page.isValid())
+        return;
+
+#if ENABLE(MEDIA_STREAM)
+    UserMediaProcessManager::singleton().startedCaptureSession(*this);
+#endif
+}
+
+void UserMediaPermissionRequestManagerProxy::endedCaptureSession()
+{
+    if (!m_page.isValid())
+        return;
+
+#if ENABLE(MEDIA_STREAM)
+    UserMediaProcessManager::singleton().endedCaptureSession(*this);
+#endif
+}
+
 } // namespace WebKit
index 1d565e4..e5fd48a 100644 (file)
@@ -53,6 +53,9 @@ private:
 class UserMediaPermissionRequestManagerProxy {
 public:
     explicit UserMediaPermissionRequestManagerProxy(WebPageProxy&);
+    ~UserMediaPermissionRequestManagerProxy();
+
+    WebPageProxy& page() const { return m_page; }
 
     void invalidateRequests();
 
@@ -68,6 +71,10 @@ public:
 
     void clearCachedState();
 
+    void startedCaptureSession();
+    void endedCaptureSession();
+    void stopCapture();
+
 private:
     Ref<UserMediaPermissionRequestProxy> createRequest(uint64_t userMediaID, uint64_t frameID, const String&userMediaDocumentOriginIdentifier, const String& topLevelDocumentOriginIdentifier, const Vector<String>& audioDeviceUIDs, const Vector<String>& videoDeviceUIDs);
     void denyRequest(uint64_t userMediaID, UserMediaPermissionRequestProxy::UserMediaAccessDenialReason, const String& invalidConstraint);
@@ -76,14 +83,6 @@ private:
 
     HashMap<uint64_t, RefPtr<UserMediaPermissionRequestProxy>> m_pendingUserMediaRequests;
     HashMap<uint64_t, RefPtr<UserMediaPermissionCheckProxy>> m_pendingDeviceRequests;
-
-    enum SandboxExtensionsGranted {
-        None = 0,
-        Video = 1 << 0,
-        Audio = 1 << 1
-    };
-    unsigned m_pageSandboxExtensionsGranted;
-
     HashMap<uint64_t, std::unique_ptr<FrameAuthorizationState>> m_frameStates;
 
     WebPageProxy& m_page;
diff --git a/Source/WebKit2/UIProcess/UserMediaProcessManager.cpp b/Source/WebKit2/UIProcess/UserMediaProcessManager.cpp
new file mode 100644 (file)
index 0000000..664f266
--- /dev/null
@@ -0,0 +1,198 @@
+/*
+ * Copyright (C) 2016 Apple Inc. All rights reserved.
+ *
+ *  This library is free software; you can redistribute it and/or
+ *  modify it under the terms of the GNU Lesser General Public
+ *  License as published by the Free Software Foundation; either
+ *  version 2 of the License, or (at your option) any later version.
+ *
+ *  This library is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ *  Lesser General Public License for more details.
+ *
+ *  You should have received a copy of the GNU Lesser General Public
+ *  License along with this library; if not, write to the Free Software
+ *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+#include "config.h"
+#include "UserMediaProcessManager.h"
+
+#if ENABLE(MEDIA_STREAM)
+
+#include "MediaDeviceSandboxExtensions.h"
+#include "WebPageMessages.h"
+#include "WebPageProxy.h"
+#include "WebProcessProxy.h"
+#include <wtf/HashMap.h>
+#include <wtf/NeverDestroyed.h>
+
+namespace WebKit {
+
+static const char* const audioExtensionPath = "com.apple.webkit.microphone";
+static const char* const videoExtensionPath = "com.apple.webkit.camera";
+
+class ProcessState {
+public:
+    ProcessState() { }
+    ProcessState(const ProcessState&) = delete;
+
+    void addRequestManager(UserMediaPermissionRequestManagerProxy&);
+    void removeRequestManager(UserMediaPermissionRequestManagerProxy&);
+    Vector<UserMediaPermissionRequestManagerProxy*>& managers() { return m_managers; }
+
+    enum SandboxExtensionsGranted {
+        None = 0,
+        Video = 1 << 0,
+        Audio = 1 << 1
+    };
+
+    SandboxExtensionsGranted sandboxExtensionsGranted() { return m_pageSandboxExtensionsGranted; }
+    void setSandboxExtensionsGranted(unsigned granted) { m_pageSandboxExtensionsGranted = static_cast<SandboxExtensionsGranted>(granted); }
+
+private:
+    Vector<UserMediaPermissionRequestManagerProxy*> m_managers;
+    SandboxExtensionsGranted m_pageSandboxExtensionsGranted { SandboxExtensionsGranted::None };
+};
+
+static HashMap<WebProcessProxy*, std::unique_ptr<ProcessState>>& stateMap()
+{
+    static NeverDestroyed<HashMap<WebProcessProxy*, std::unique_ptr<ProcessState>>> map;
+    return map;
+}
+
+static ProcessState& processState(WebProcessProxy& process)
+{
+    auto& state = stateMap().add(&process, nullptr).iterator->value;
+    if (state)
+        return *state;
+
+    state = std::make_unique<ProcessState>();
+    return *state;
+}
+
+void ProcessState::addRequestManager(UserMediaPermissionRequestManagerProxy& proxy)
+{
+    ASSERT(!m_managers.contains(&proxy));
+    m_managers.append(&proxy);
+}
+
+void ProcessState::removeRequestManager(UserMediaPermissionRequestManagerProxy& proxy)
+{
+    ASSERT(m_managers.contains(&proxy));
+    m_managers.removeFirstMatching([&proxy](auto other) {
+        return other == &proxy;
+    });
+}
+
+UserMediaProcessManager& UserMediaProcessManager::singleton()
+{
+    static NeverDestroyed<UserMediaProcessManager> manager;
+    return manager;
+}
+
+void UserMediaProcessManager::addUserMediaPermissionRequestManagerProxy(UserMediaPermissionRequestManagerProxy& proxy)
+{
+    processState(proxy.page().process()).addRequestManager(proxy);
+}
+
+void UserMediaProcessManager::removeUserMediaPermissionRequestManagerProxy(UserMediaPermissionRequestManagerProxy& proxy)
+{
+    endedCaptureSession(proxy);
+
+    auto& state = processState(proxy.page().process());
+    state.removeRequestManager(proxy);
+    if (state.managers().isEmpty()) {
+        auto it = stateMap().find(&proxy.page().process());
+        stateMap().remove(it);
+    }
+}
+
+void UserMediaProcessManager::willCreateMediaStream(UserMediaPermissionRequestManagerProxy& proxy, bool withAudio, bool withVideo)
+{
+    ASSERT(stateMap().contains(&proxy.page().process()));
+
+    auto& state = processState(proxy.page().process());
+    size_t extensionCount = 0;
+    unsigned requiredExtensions = ProcessState::SandboxExtensionsGranted::None;
+
+    if (withAudio) {
+        requiredExtensions |= ProcessState::SandboxExtensionsGranted::Audio;
+        extensionCount++;
+    }
+    if (withVideo) {
+        requiredExtensions |= ProcessState::SandboxExtensionsGranted::Video;
+        extensionCount++;
+    }
+
+    unsigned currentExtensions = state.sandboxExtensionsGranted();
+    if (!(requiredExtensions & currentExtensions)) {
+        SandboxExtension::HandleArray handles;
+        handles.allocate(extensionCount);
+
+        Vector<String> ids;
+        ids.reserveCapacity(extensionCount);
+
+        if (withAudio && requiredExtensions & ProcessState::SandboxExtensionsGranted::Audio) {
+            if (SandboxExtension::createHandleForGenericExtension(audioExtensionPath, handles[--extensionCount])) {
+                ids.append(ASCIILiteral(audioExtensionPath));
+                currentExtensions |= ProcessState::SandboxExtensionsGranted::Audio;
+            }
+        }
+
+        if (withVideo && requiredExtensions & ProcessState::SandboxExtensionsGranted::Video) {
+            if (SandboxExtension::createHandleForGenericExtension(videoExtensionPath, handles[--extensionCount])) {
+                ids.append(ASCIILiteral(videoExtensionPath));
+                currentExtensions |= ProcessState::SandboxExtensionsGranted::Video;
+            }
+        }
+
+        state.setSandboxExtensionsGranted(currentExtensions);
+        proxy.page().process().send(Messages::WebPage::GrantUserMediaDeviceSandboxExtensions(MediaDeviceSandboxExtensions(ids, WTFMove(handles))), proxy.page().pageID());
+    }
+}
+
+void UserMediaProcessManager::startedCaptureSession(UserMediaPermissionRequestManagerProxy& proxy)
+{
+    ASSERT(stateMap().contains(&proxy.page().process()));
+}
+
+void UserMediaProcessManager::endedCaptureSession(UserMediaPermissionRequestManagerProxy& proxy)
+{
+    ASSERT(stateMap().contains(&proxy.page().process()));
+
+    auto& state = processState(proxy.page().process());
+    bool hasAudioCapture = false;
+    bool hasVideoCapture = false;
+    for (auto& manager : state.managers()) {
+        if (manager->page().hasActiveAudioStream())
+            hasAudioCapture = true;
+        if (manager->page().hasActiveVideoStream())
+            hasVideoCapture = true;
+    }
+
+    if (hasAudioCapture && hasVideoCapture)
+        return;
+
+    Vector<String> params;
+    unsigned currentExtensions = state.sandboxExtensionsGranted();
+    if (!hasAudioCapture && currentExtensions & ProcessState::SandboxExtensionsGranted::Audio) {
+        params.append(ASCIILiteral(audioExtensionPath));
+        currentExtensions &= ~ProcessState::SandboxExtensionsGranted::Audio;
+    }
+    if (!hasVideoCapture && currentExtensions & ProcessState::SandboxExtensionsGranted::Video) {
+        params.append(ASCIILiteral(videoExtensionPath));
+        currentExtensions &= ~ProcessState::SandboxExtensionsGranted::Video;
+    }
+
+    if (params.isEmpty())
+        return;
+
+    state.setSandboxExtensionsGranted(currentExtensions);
+    proxy.page().process().send(Messages::WebPage::RevokeUserMediaDeviceSandboxExtensions(params), proxy.page().pageID());
+}
+
+} // namespace WebKit
+
+#endif
diff --git a/Source/WebKit2/UIProcess/UserMediaProcessManager.h b/Source/WebKit2/UIProcess/UserMediaProcessManager.h
new file mode 100644 (file)
index 0000000..4e450bc
--- /dev/null
@@ -0,0 +1,45 @@
+/*
+ * Copyright (C) 2016 Apple Inc. All rights reserved.
+ *
+ *  This library is free software; you can redistribute it and/or
+ *  modify it under the terms of the GNU Lesser General Public
+ *  License as published by the Free Software Foundation; either
+ *  version 2 of the License, or (at your option) any later version.
+ *
+ *  This library is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ *  Lesser General Public License for more details.
+ *
+ *  You should have received a copy of the GNU Lesser General Public
+ *  License along with this library; if not, write to the Free Software
+ *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+#pragma once
+
+#if ENABLE(MEDIA_STREAM)
+
+#include "UserMediaPermissionRequestManagerProxy.h"
+
+namespace WebKit {
+
+class WebProcessProxy;
+
+class UserMediaProcessManager {
+public:
+
+    static UserMediaProcessManager& singleton();
+
+    void addUserMediaPermissionRequestManagerProxy(UserMediaPermissionRequestManagerProxy&);
+    void removeUserMediaPermissionRequestManagerProxy(UserMediaPermissionRequestManagerProxy&);
+
+    void willCreateMediaStream(UserMediaPermissionRequestManagerProxy&, bool withAudio, bool withVideo);
+
+    void startedCaptureSession(UserMediaPermissionRequestManagerProxy&);
+    void endedCaptureSession(UserMediaPermissionRequestManagerProxy&);
+};
+
+} // namespace WebKit
+
+#endif
index ef37d6a..142353d 100644 (file)
@@ -358,7 +358,6 @@ WebPageProxy::WebPageProxy(PageClient& pageClient, WebProcessProxy& process, uin
 #endif
     , m_geolocationPermissionRequestManager(*this)
     , m_notificationPermissionRequestManager(*this)
-    , m_userMediaPermissionRequestManager(*this)
     , m_activityState(ActivityState::NoFlags)
     , m_viewWasEverInWindow(false)
 #if PLATFORM(IOS)
@@ -5376,8 +5375,9 @@ void WebPageProxy::resetState(ResetStateReason resetStateReason)
 #if ENABLE(GEOLOCATION)
     m_geolocationPermissionRequestManager.invalidateRequests();
 #endif
+
 #if ENABLE(MEDIA_STREAM)
-    m_userMediaPermissionRequestManager.invalidateRequests();
+    m_userMediaPermissionRequestManager = nullptr;
 #endif
 
     m_notificationPermissionRequestManager.invalidateRequests();
@@ -5692,12 +5692,21 @@ void WebPageProxy::requestGeolocationPermissionForFrame(uint64_t geolocationID,
     request->deny();
 }
 
+UserMediaPermissionRequestManagerProxy& WebPageProxy::userMediaPermissionRequestManager()
+{
+    if (m_userMediaPermissionRequestManager)
+        return *m_userMediaPermissionRequestManager;
+
+    m_userMediaPermissionRequestManager = std::make_unique<UserMediaPermissionRequestManagerProxy>(*this);
+    return *m_userMediaPermissionRequestManager;
+}
+
 void WebPageProxy::requestUserMediaPermissionForFrame(uint64_t userMediaID, uint64_t frameID, String userMediaDocumentOriginIdentifier, String topLevelDocumentOriginIdentifier, const WebCore::MediaConstraintsData& audioConstraintsData, const WebCore::MediaConstraintsData& videoConstraintsData)
 {
 #if ENABLE(MEDIA_STREAM)
     MESSAGE_CHECK(m_process->webFrame(frameID));
 
-    m_userMediaPermissionRequestManager.requestUserMediaPermissionForFrame(userMediaID, frameID, userMediaDocumentOriginIdentifier, topLevelDocumentOriginIdentifier, audioConstraintsData, videoConstraintsData);
+    userMediaPermissionRequestManager().requestUserMediaPermissionForFrame(userMediaID, frameID, userMediaDocumentOriginIdentifier, topLevelDocumentOriginIdentifier, audioConstraintsData, videoConstraintsData);
 #else
     UNUSED_PARAM(userMediaID);
     UNUSED_PARAM(frameID);
@@ -5714,7 +5723,7 @@ void WebPageProxy::enumerateMediaDevicesForFrame(uint64_t userMediaID, uint64_t
     WebFrameProxy* frame = m_process->webFrame(frameID);
     MESSAGE_CHECK(frame);
 
-    m_userMediaPermissionRequestManager.enumerateMediaDevicesForFrame(userMediaID, frameID, userMediaDocumentOriginIdentifier, topLevelDocumentOriginIdentifier);
+    userMediaPermissionRequestManager().enumerateMediaDevicesForFrame(userMediaID, frameID, userMediaDocumentOriginIdentifier, topLevelDocumentOriginIdentifier);
 #else
     UNUSED_PARAM(userMediaID);
     UNUSED_PARAM(frameID);
@@ -5726,7 +5735,7 @@ void WebPageProxy::enumerateMediaDevicesForFrame(uint64_t userMediaID, uint64_t
 void WebPageProxy::clearUserMediaState()
 {
 #if ENABLE(MEDIA_STREAM)
-    m_userMediaPermissionRequestManager.clearCachedState();
+    userMediaPermissionRequestManager().clearCachedState();
 #endif
 }
 
@@ -6409,15 +6418,21 @@ void WebPageProxy::isPlayingMediaDidChange(MediaProducer::MediaStateFlags state,
 
     WebCore::MediaProducer::MediaStateFlags oldMediaStateHasActiveCapture = m_mediaState & (WebCore::MediaProducer::HasActiveAudioCaptureDevice | WebCore::MediaProducer::HasActiveVideoCaptureDevice);
     WebCore::MediaProducer::MediaStateFlags newMediaStateHasActiveCapture = state & (WebCore::MediaProducer::HasActiveAudioCaptureDevice | WebCore::MediaProducer::HasActiveVideoCaptureDevice);
-    if (!oldMediaStateHasActiveCapture && newMediaStateHasActiveCapture)
-        m_uiClient->didBeginCaptureSession();
-    if (oldMediaStateHasActiveCapture && !newMediaStateHasActiveCapture)
-        m_uiClient->didEndCaptureSession();
 
     MediaProducer::MediaStateFlags playingMediaMask = MediaProducer::IsPlayingAudio | MediaProducer::IsPlayingVideo;
     MediaProducer::MediaStateFlags oldState = m_mediaState;
     m_mediaState = state;
 
+#if ENABLE(MEDIA_STREAM)
+    if (!oldMediaStateHasActiveCapture && newMediaStateHasActiveCapture) {
+        m_uiClient->didBeginCaptureSession();
+        userMediaPermissionRequestManager().startedCaptureSession();
+    } else if (oldMediaStateHasActiveCapture && !newMediaStateHasActiveCapture) {
+        m_uiClient->didEndCaptureSession();
+        userMediaPermissionRequestManager().endedCaptureSession();
+    }
+#endif
+
     activityStateDidChange(ActivityState::IsAudible);
 
     playingMediaMask |= MediaProducer::HasActiveAudioCaptureDevice | MediaProducer::HasActiveVideoCaptureDevice;
index 861801e..3f865aa 100644 (file)
@@ -1049,6 +1049,8 @@ public:
 
     bool isPlayingAudio() const { return !!(m_mediaState & WebCore::MediaProducer::IsPlayingAudio); }
     void isPlayingMediaDidChange(WebCore::MediaProducer::MediaStateFlags, uint64_t);
+    bool hasActiveAudioStream() const { return m_mediaState & WebCore::MediaProducer::HasActiveAudioCaptureDevice; }
+    bool hasActiveVideoStream() const { return m_mediaState & WebCore::MediaProducer::HasActiveVideoCaptureDevice; }
     WebCore::MediaProducer::MediaStateFlags mediaStateFlags() const { return m_mediaState; }
 
 #if PLATFORM(MAC)
@@ -1295,6 +1297,7 @@ private:
     void reachedApplicationCacheOriginQuota(const String& originIdentifier, uint64_t currentQuota, uint64_t totalBytesNeeded, PassRefPtr<Messages::WebPageProxy::ReachedApplicationCacheOriginQuota::DelayedReply>);
     void requestGeolocationPermissionForFrame(uint64_t geolocationID, uint64_t frameID, String originIdentifier);
 
+    UserMediaPermissionRequestManagerProxy& userMediaPermissionRequestManager();
     void requestUserMediaPermissionForFrame(uint64_t userMediaID, uint64_t frameID, String userMediaDocumentOriginIdentifier, String topLevelDocumentOriginIdentifier, const WebCore::MediaConstraintsData& audioConstraints, const WebCore::MediaConstraintsData& videoConstraints);
     void enumerateMediaDevicesForFrame(uint64_t userMediaID, uint64_t frameID, String userMediaDocumentOriginIdentifier, String topLevelDocumentOriginIdentifier);
 
@@ -1688,7 +1691,9 @@ private:
     GeolocationPermissionRequestManagerProxy m_geolocationPermissionRequestManager;
     NotificationPermissionRequestManagerProxy m_notificationPermissionRequestManager;
 
-    UserMediaPermissionRequestManagerProxy m_userMediaPermissionRequestManager;
+#if ENABLE(MEDIA_STREAM)
+    std::unique_ptr<UserMediaPermissionRequestManagerProxy> m_userMediaPermissionRequestManager;
+#endif
 
     WebCore::ActivityState::Flags m_activityState;
     bool m_viewWasEverInWindow;
index 47d5d1e..22ab5f0 100644 (file)
@@ -58,6 +58,9 @@
                07297F9F1C17BBEA003F0735 /* UserMediaPermissionCheckProxy.h in Headers */ = {isa = PBXBuildFile; fileRef = 07297F9D1C17BBEA003F0735 /* UserMediaPermissionCheckProxy.h */; };
                07297FA21C186ADB003F0735 /* WKUserMediaPermissionCheck.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 07297FA01C186ADB003F0735 /* WKUserMediaPermissionCheck.cpp */; };
                07297FA31C186ADB003F0735 /* WKUserMediaPermissionCheck.h in Headers */ = {isa = PBXBuildFile; fileRef = 07297FA11C186ADB003F0735 /* WKUserMediaPermissionCheck.h */; settings = {ATTRIBUTES = (Private, ); }; };
+               074E75FD1DF2211500D318EC /* UserMediaProcessManager.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 074E75FC1DF2002400D318EC /* UserMediaProcessManager.cpp */; };
+               074E75FE1DF2211900D318EC /* UserMediaProcessManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 074E75FB1DF1FD1300D318EC /* UserMediaProcessManager.h */; };
+               074E76021DF707BE00D318EC /* MediaDeviceSandboxExtensions.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 074E76001DF7075D00D318EC /* MediaDeviceSandboxExtensions.cpp */; };
                076E884E1A13CADF005E90FC /* APIContextMenuClient.h in Headers */ = {isa = PBXBuildFile; fileRef = 076E884D1A13CADF005E90FC /* APIContextMenuClient.h */; };
                07A5EBBB1C7BA43E00B9CA69 /* WKFrameHandleRef.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 07A5EBB91C7BA43E00B9CA69 /* WKFrameHandleRef.cpp */; };
                07A5EBBC1C7BA43E00B9CA69 /* WKFrameHandleRef.h in Headers */ = {isa = PBXBuildFile; fileRef = 07A5EBBA1C7BA43E00B9CA69 /* WKFrameHandleRef.h */; settings = {ATTRIBUTES = (Private, ); }; };
                07297F9D1C17BBEA003F0735 /* UserMediaPermissionCheckProxy.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = UserMediaPermissionCheckProxy.h; sourceTree = "<group>"; };
                07297FA01C186ADB003F0735 /* WKUserMediaPermissionCheck.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = WKUserMediaPermissionCheck.cpp; sourceTree = "<group>"; };
                07297FA11C186ADB003F0735 /* WKUserMediaPermissionCheck.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WKUserMediaPermissionCheck.h; sourceTree = "<group>"; };
+               074E75FB1DF1FD1300D318EC /* UserMediaProcessManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = UserMediaProcessManager.h; sourceTree = "<group>"; };
+               074E75FC1DF2002400D318EC /* UserMediaProcessManager.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = UserMediaProcessManager.cpp; sourceTree = "<group>"; };
+               074E76001DF7075D00D318EC /* MediaDeviceSandboxExtensions.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = MediaDeviceSandboxExtensions.cpp; sourceTree = "<group>"; };
+               074E76011DF7075D00D318EC /* MediaDeviceSandboxExtensions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MediaDeviceSandboxExtensions.h; sourceTree = "<group>"; };
                076E884D1A13CADF005E90FC /* APIContextMenuClient.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = APIContextMenuClient.h; sourceTree = "<group>"; };
                076E884F1A13CBC6005E90FC /* APIInjectedBundlePageContextMenuClient.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = APIInjectedBundlePageContextMenuClient.h; sourceTree = "<group>"; };
                07A5EBB91C7BA43E00B9CA69 /* WKFrameHandleRef.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = WKFrameHandleRef.cpp; sourceTree = "<group>"; };
                4A410F4119AF7B27002EBAB5 /* MediaStream */ = {
                        isa = PBXGroup;
                        children = (
+                               074E76001DF7075D00D318EC /* MediaDeviceSandboxExtensions.cpp */,
+                               074E76011DF7075D00D318EC /* MediaDeviceSandboxExtensions.h */,
                                4A410F4219AF7B27002EBAB5 /* UserMediaPermissionRequestManager.cpp */,
                                4A410F4319AF7B27002EBAB5 /* UserMediaPermissionRequestManager.h */,
                        );
                BC032DC310F438260058C15A /* UIProcess */ = {
                        isa = PBXGroup;
                        children = (
+                               074E75FC1DF2002400D318EC /* UserMediaProcessManager.cpp */,
+                               074E75FB1DF1FD1300D318EC /* UserMediaProcessManager.h */,
                                BC032DC410F4387C0058C15A /* API */,
                                1AB1F7761D1B30A9007C9BD1 /* ApplePay */,
                                512F588D12A8836F00629530 /* Authentication */,
                                BC0E619812D6CD120012A72A /* WKGeolocationPosition.h in Headers */,
                                0FCB4E4F18BBE044000FCFC9 /* WKGeolocationProviderIOS.h in Headers */,
                                BCC8B374125FB69000DE46A4 /* WKGeometry.h in Headers */,
+                               074E75FE1DF2211900D318EC /* UserMediaProcessManager.h in Headers */,
                                1A422F8B18B29B5400D8CD96 /* WKHistoryDelegatePrivate.h in Headers */,
                                B62E7312143047B00069EC35 /* WKHitTestResult.h in Headers */,
                                5110AE0D133C16CB0072717A /* WKIconDatabase.h in Headers */,
                                0F5E200318E77051003EC3E5 /* PlatformCAAnimationRemote.mm in Sources */,
                                2DA049B3180CCCD300AAFA9E /* PlatformCALayerRemote.cpp in Sources */,
                                2D8710161828415D0018FA01 /* PlatformCALayerRemoteCustom.mm in Sources */,
+                               074E75FD1DF2211500D318EC /* UserMediaProcessManager.cpp in Sources */,
                                2D8949F0182044F600E898AA /* PlatformCALayerRemoteTiledBacking.cpp in Sources */,
                                BCC43ABA127B95DC00317F16 /* PlatformPopupMenuData.cpp in Sources */,
                                1A6FB7D211E651E200DB1371 /* Plugin.cpp in Sources */,
                                1A256E3718A1A788006FB922 /* WKNavigationAction.mm in Sources */,
                                2D3A65DA1A7C3A1F00CAC637 /* WKNavigationActionRef.cpp in Sources */,
                                370F34A21829BE1E009027C8 /* WKNavigationData.mm in Sources */,
+                               074E76021DF707BE00D318EC /* MediaDeviceSandboxExtensions.cpp in Sources */,
                                BCF69FAA1176D1CB00471A52 /* WKNavigationDataRef.cpp in Sources */,
                                2D3A65E21A7C3A9300CAC637 /* WKNavigationRef.cpp in Sources */,
                                1A1B0EB518A424950038481A /* WKNavigationResponse.mm in Sources */,
diff --git a/Source/WebKit2/WebProcess/MediaStream/MediaDeviceSandboxExtensions.cpp b/Source/WebKit2/WebProcess/MediaStream/MediaDeviceSandboxExtensions.cpp
new file mode 100644 (file)
index 0000000..2a4fb52
--- /dev/null
@@ -0,0 +1,80 @@
+/*
+ * Copyright (C) 2016 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "MediaDeviceSandboxExtensions.h"
+
+#if ENABLE(MEDIA_STREAM)
+
+#include "WebCoreArgumentCoders.h"
+
+namespace WebKit {
+
+MediaDeviceSandboxExtensions::MediaDeviceSandboxExtensions(Vector<String> ids, SandboxExtension::HandleArray&& handles)
+    : m_ids(ids)
+    , m_handles(WTFMove(handles))
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(m_ids.size() == m_handles.size());
+}
+
+void MediaDeviceSandboxExtensions::encode(IPC::Encoder& encoder) const
+{
+    encoder << m_ids;
+    m_handles.encode(encoder);
+}
+
+bool MediaDeviceSandboxExtensions::decode(IPC::Decoder& decoder, MediaDeviceSandboxExtensions& result)
+{
+    if (!decoder.decode(result.m_ids))
+        return false;
+
+    if (!SandboxExtension::HandleArray::decode(decoder, result.m_handles))
+        return false;
+
+    return true;
+}
+
+std::pair<String, RefPtr<SandboxExtension>> MediaDeviceSandboxExtensions::operator[](size_t i)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(m_ids.size() == m_handles.size());
+    ASSERT_WITH_SECURITY_IMPLICATION(i < m_ids.size());
+    return { m_ids[i], SandboxExtension::create(m_handles[i]) };
+}
+
+const std::pair<String, RefPtr<SandboxExtension>> MediaDeviceSandboxExtensions::operator[](size_t i) const
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(m_ids.size() == m_handles.size());
+    ASSERT_WITH_SECURITY_IMPLICATION(i < m_ids.size());
+    return { m_ids[i], SandboxExtension::create(m_handles[i]) };
+}
+
+size_t MediaDeviceSandboxExtensions::size() const
+{
+    return m_ids.size();
+}
+
+} // namespace WebKit
+
+#endif // ENABLE(MEDIA_STREAM)
diff --git a/Source/WebKit2/WebProcess/MediaStream/MediaDeviceSandboxExtensions.h b/Source/WebKit2/WebProcess/MediaStream/MediaDeviceSandboxExtensions.h
new file mode 100644 (file)
index 0000000..a270f4e
--- /dev/null
@@ -0,0 +1,59 @@
+/*
+ * Copyright (C) 2016 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#pragma once
+
+#if ENABLE(MEDIA_STREAM)
+
+#include "SandboxExtension.h"
+#include <wtf/Noncopyable.h>
+#include <wtf/RefPtr.h>
+
+namespace WebKit {
+
+class MediaDeviceSandboxExtensions {
+    WTF_MAKE_NONCOPYABLE(MediaDeviceSandboxExtensions);
+public:
+    MediaDeviceSandboxExtensions()
+    {
+    }
+
+    MediaDeviceSandboxExtensions(Vector<String> ids, SandboxExtension::HandleArray&& handles);
+
+    std::pair<String, RefPtr<SandboxExtension>> operator[](size_t i);
+    const std::pair<String, RefPtr<SandboxExtension>> operator[](size_t i) const;
+    size_t size() const;
+
+    void encode(IPC::Encoder&) const;
+    static bool decode(IPC::Decoder&, MediaDeviceSandboxExtensions&);
+
+private:
+    Vector<String> m_ids;
+    SandboxExtension::HandleArray m_handles;
+};
+
+} // namespace WebKit
+
+#endif // ENABLE(MEDIA_STREAM)
index bfadbaa..734c105 100644 (file)
@@ -52,7 +52,7 @@ UserMediaPermissionRequestManager::UserMediaPermissionRequestManager(WebPage& pa
 UserMediaPermissionRequestManager::~UserMediaPermissionRequestManager()
 {
     for (auto& sandboxExtension : m_userMediaDeviceSandboxExtensions)
-        sandboxExtension->revoke();
+        sandboxExtension.value->revoke();
 }
 
 void UserMediaPermissionRequestManager::startUserMediaRequest(UserMediaRequest& request)
@@ -202,15 +202,21 @@ void UserMediaPermissionRequestManager::didCompleteMediaDeviceEnumeration(uint64
     request->setDeviceInfo(deviceList, mediaDeviceIdentifierHashSalt, hasPersistentAccess);
 }
 
-void UserMediaPermissionRequestManager::grantUserMediaDevicesSandboxExtension(const SandboxExtension::HandleArray& sandboxExtensionHandles)
+void UserMediaPermissionRequestManager::grantUserMediaDeviceSandboxExtensions(const MediaDeviceSandboxExtensions& extensions)
 {
-    ASSERT(m_userMediaDeviceSandboxExtensions.size() <= 2);
+    for (size_t i = 0; i < extensions.size(); i++) {
+        auto& extension = extensions[i];
+        extension.second->consume();
+        m_userMediaDeviceSandboxExtensions.add(extension.first, extension.second.copyRef());
+    }
+}
 
-    for (size_t i = 0; i < sandboxExtensionHandles.size(); i++) {
-        if (auto extension = SandboxExtension::create(sandboxExtensionHandles[i])) {
-            extension->consume();
-            m_userMediaDeviceSandboxExtensions.append(extension.release());
-        }
+void UserMediaPermissionRequestManager::revokeUserMediaDeviceSandboxExtensions(const Vector<String>& extensionIDs)
+{
+    for (const auto& extensionID : extensionIDs) {
+        auto extension = m_userMediaDeviceSandboxExtensions.take(extensionID);
+        if (extension)
+            extension->revoke();
     }
 }
 
index 318aaf2..e8a96c2 100644 (file)
@@ -22,6 +22,7 @@
 
 #if ENABLE(MEDIA_STREAM)
 
+#include "MediaDeviceSandboxExtensions.h"
 #include "SandboxExtension.h"
 #include <WebCore/MediaCanStartListener.h>
 #include <WebCore/MediaConstraints.h>
@@ -51,7 +52,8 @@ public:
     void cancelMediaDevicesEnumeration(WebCore::MediaDevicesEnumerationRequest&);
     void didCompleteMediaDeviceEnumeration(uint64_t, const Vector<WebCore::CaptureDevice>& deviceList, const String& deviceIdentifierHashSalt, bool originHasPersistentAccess);
 
-    void grantUserMediaDevicesSandboxExtension(const SandboxExtension::HandleArray&);
+    void grantUserMediaDeviceSandboxExtensions(const MediaDeviceSandboxExtensions&);
+    void revokeUserMediaDeviceSandboxExtensions(const Vector<String>&);
 
 private:
     void sendUserMediaRequest(WebCore::UserMediaRequest&);
@@ -69,7 +71,7 @@ private:
     HashMap<uint64_t, RefPtr<WebCore::MediaDevicesEnumerationRequest>> m_idToMediaDevicesEnumerationRequestMap;
     HashMap<RefPtr<WebCore::MediaDevicesEnumerationRequest>, uint64_t> m_mediaDevicesEnumerationRequestToIDMap;
 
-    Vector<RefPtr<SandboxExtension>> m_userMediaDeviceSandboxExtensions;
+    HashMap<String, RefPtr<SandboxExtension>> m_userMediaDeviceSandboxExtensions;
 
     HashMap<RefPtr<WebCore::Document>, Vector<RefPtr<WebCore::UserMediaRequest>>> m_blockedRequests;
 };
index ab5efe7..368c917 100644 (file)
@@ -3700,9 +3700,14 @@ void WebPage::didCompleteMediaDeviceEnumeration(uint64_t userMediaID, const Vect
     m_userMediaPermissionRequestManager.didCompleteMediaDeviceEnumeration(userMediaID, devices, deviceIdentifierHashSalt, originHasPersistentAccess);
 }
 
-void WebPage::grantUserMediaDevicesSandboxExtension(const SandboxExtension::HandleArray& handles)
+void WebPage::grantUserMediaDeviceSandboxExtensions(const MediaDeviceSandboxExtensions& extensions)
 {
-    m_userMediaPermissionRequestManager.grantUserMediaDevicesSandboxExtension(handles);
+    m_userMediaPermissionRequestManager.grantUserMediaDeviceSandboxExtensions(extensions);
+}
+
+void WebPage::revokeUserMediaDeviceSandboxExtensions(const Vector<String>& extensionIDs)
+{
+    m_userMediaPermissionRequestManager.revokeUserMediaDeviceSandboxExtensions(extensionIDs);
 }
 #endif
 
index c1e8cfd..c595de3 100644 (file)
@@ -1178,7 +1178,8 @@ private:
     void userMediaAccessWasDenied(uint64_t userMediaID, uint64_t reason, String invalidConstraint);
 
     void didCompleteMediaDeviceEnumeration(uint64_t userMediaID, const Vector<WebCore::CaptureDevice>& devices, const String& deviceIdentifierHashSalt, bool originHasPersistentAccess);
-    void grantUserMediaDevicesSandboxExtension(const SandboxExtension::HandleArray&);
+    void grantUserMediaDeviceSandboxExtensions(const MediaDeviceSandboxExtensions&);
+    void revokeUserMediaDeviceSandboxExtensions(const Vector<String>&);
 #endif
 
     void advanceToNextMisspelling(bool startBeforeSelection);
index 81e6c3a..43317b4 100644 (file)
@@ -292,7 +292,8 @@ messages -> WebPage LegacyReceiver {
     UserMediaAccessWasGranted(uint64_t userMediaID, String audioDeviceUID, String videoDeviceUID)
     UserMediaAccessWasDenied(uint64_t userMediaID, uint64_t reason, String invalidConstraint)
     DidCompleteMediaDeviceEnumeration(uint64_t userMediaID, Vector<WebCore::CaptureDevice> devices, String mediaDeviceIdentifierHashSalt, bool hasPersistentAccess)
-    GrantUserMediaDevicesSandboxExtension(WebKit::SandboxExtension::HandleArray sandboxExtensionHandle)
+    GrantUserMediaDeviceSandboxExtensions(WebKit::MediaDeviceSandboxExtensions sandboxExtensions)
+    RevokeUserMediaDeviceSandboxExtensions(Vector<String> sandboxExtensionIDs)
 #endif
 
     # Notification
index f297b98..9dc685d 100644 (file)
@@ -1,3 +1,21 @@
+2016-12-07  Eric Carlson  <eric.carlson@apple.com>
+
+        [MediaStream][Mac] Revoke sandbox extensions when capture ends
+        https://bugs.webkit.org/show_bug.cgi?id=165476
+
+        Reviewed by Brady Eidson.
+        
+        Add a test which loads a page that calls navigator.mediaDevices.enumerateDevices, kills the
+        page, and loads the same page again to ensure that the WK2 UserMediaPermissionRequestManagerProxy
+        is reset and recreated when a web page exits and is reloaded.
+
+        * TestWebKitAPI/PlatformGTK.cmake:
+        * TestWebKitAPI/TestWebKitAPI.xcodeproj/project.pbxproj:
+        * TestWebKitAPI/Tests/WebKit2/EnumerateMediaDevices.cpp: Added.
+        (TestWebKitAPI::checkUserMediaPermissionCallback):
+        (TestWebKitAPI::TEST):
+        * TestWebKitAPI/Tests/WebKit2/enumerateMediaDevices.html: Added.
+
 2016-12-07  Jeremy Jones  <jeremyj@apple.com>
 
         One esc to exit fullscreen and pointer lock
index 91a2c9e..639d197 100644 (file)
@@ -75,6 +75,7 @@ add_executable(TestWebKit2
     ${TESTWEBKITAPI_DIR}/Tests/WebKit2/DOMWindowExtensionBasic.cpp
     ${TESTWEBKITAPI_DIR}/Tests/WebKit2/DOMWindowExtensionNoCache.cpp
     ${TESTWEBKITAPI_DIR}/Tests/WebKit2/DownloadDecideDestinationCrash.cpp
+    ${TESTWEBKITAPI_DIR}/Tests/WebKit2/EnumerateMediaDevices.cpp
     ${TESTWEBKITAPI_DIR}/Tests/WebKit2/EvaluateJavaScript.cpp
     ${TESTWEBKITAPI_DIR}/Tests/WebKit2/FailedLoad.cpp
     ${TESTWEBKITAPI_DIR}/Tests/WebKit2/Find.cpp
index 0cbd57b..e87c68f 100644 (file)
@@ -22,6 +22,8 @@
 /* End PBXAggregateTarget section */
 
 /* Begin PBXBuildFile section */
+               07492B3B1DF8B14C00633DE1 /* EnumerateMediaDevices.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 07492B3A1DF8AE2D00633DE1 /* EnumerateMediaDevices.cpp */; };
+               07492B3C1DF8B86600633DE1 /* enumerateMediaDevices.html in Copy Resources */ = {isa = PBXBuildFile; fileRef = 07492B391DF8ADA400633DE1 /* enumerateMediaDevices.html */; };
                0F139E771A423A5B00F590F5 /* WeakObjCPtr.mm in Sources */ = {isa = PBXBuildFile; fileRef = 0F139E751A423A5300F590F5 /* WeakObjCPtr.mm */; };
                0F139E781A423A6B00F590F5 /* PlatformUtilitiesCocoa.mm in Sources */ = {isa = PBXBuildFile; fileRef = 0F139E721A423A2B00F590F5 /* PlatformUtilitiesCocoa.mm */; };
                0F139E791A42457000F590F5 /* PlatformUtilitiesCocoa.mm in Sources */ = {isa = PBXBuildFile; fileRef = 0F139E721A423A2B00F590F5 /* PlatformUtilitiesCocoa.mm */; };
                        dstPath = TestWebKitAPI.resources;
                        dstSubfolderSpec = 7;
                        files = (
+                               07492B3C1DF8B86600633DE1 /* enumerateMediaDevices.html in Copy Resources */,
                                9B270FEE1DDC2C0B002D53F3 /* closed-shadow-tree-test.html in Copy Resources */,
                                F4C2AB221DD6D95E00E06D5B /* enormous-video-with-sound.html in Copy Resources */,
                                8349D3C41DB9728E004A9F65 /* link-with-download-attribute.html in Copy Resources */,
 /* Begin PBXFileReference section */
                00BC16851680FE810065F1E5 /* PublicSuffix.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = PublicSuffix.mm; sourceTree = "<group>"; };
                00CD9F6215BE312C002DA2CE /* BackForwardList.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = BackForwardList.mm; sourceTree = "<group>"; };
+               07492B391DF8ADA400633DE1 /* enumerateMediaDevices.html */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.html; path = enumerateMediaDevices.html; sourceTree = "<group>"; };
+               07492B3A1DF8AE2D00633DE1 /* EnumerateMediaDevices.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = EnumerateMediaDevices.cpp; sourceTree = "<group>"; };
                0766DD1F1A5AD5200023E3BB /* PendingAPIRequestURL.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = PendingAPIRequestURL.cpp; sourceTree = "<group>"; };
                0BCD833414857CE400EA2003 /* HashMap.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = HashMap.cpp; sourceTree = "<group>"; };
                0BCD85691485C98B00EA2003 /* SetForScope.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SetForScope.cpp; sourceTree = "<group>"; };
                BC9096411255616000083756 /* WebKit2 */ = {
                        isa = PBXGroup;
                        children = (
+                               07492B3A1DF8AE2D00633DE1 /* EnumerateMediaDevices.cpp */,
                                AD57AC1E1DA7464D00FF1BDE /* DidRemoveFrameFromHiearchyInPageCache_Bundle.cpp */,
                                AD57AC1F1DA7464D00FF1BDE /* DidRemoveFrameFromHiearchyInPageCache.cpp */,
                                0F139E741A423A4600F590F5 /* cocoa */,
                BC90977B125571AE00083756 /* Resources */ = {
                        isa = PBXGroup;
                        children = (
+                               07492B391DF8ADA400633DE1 /* enumerateMediaDevices.html */,
                                C045F9461385C2F800C0F3CD /* 18-characters.html */,
                                1C2B81851C89252300A5529F /* Ahem.ttf */,
                                93D3D19B17B1A7B000C7C415 /* all-content-in-one-iframe.html */,
                                7CCE7ED31A411A7E00447C4C /* TypingStyleCrash.mm in Sources */,
                                7CCE7EDE1A411A9200447C4C /* URL.cpp in Sources */,
                                7CCE7EB01A411A4400447C4C /* URLExtras.mm in Sources */,
+                               07492B3B1DF8B14C00633DE1 /* EnumerateMediaDevices.cpp in Sources */,
                                7A6A2C701DCCFA8C00C0D085 /* LocalStorageQuirkTest.mm in Sources */,
                                2DFF7B6D1DA487AF00814614 /* SnapshotStore.mm in Sources */,
                                5C6E65441D5CEFD400F7862E /* URLParser.cpp in Sources */,
diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/EnumerateMediaDevices.cpp b/Tools/TestWebKitAPI/Tests/WebKit2/EnumerateMediaDevices.cpp
new file mode 100644 (file)
index 0000000..67b04b2
--- /dev/null
@@ -0,0 +1,83 @@
+/*
+ * Copyright (C) 2016 Apple Inc. All rights reserved.
+ *
+ *  This library is free software; you can redistribute it and/or
+ *  modify it under the terms of the GNU Lesser General Public
+ *  License as published by the Free Software Foundation; either
+ *  version 2 of the License, or (at your option) any later version.
+ *
+ *  This library is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ *  Lesser General Public License for more details.
+ *
+ *  You should have received a copy of the GNU Lesser General Public
+ *  License along with this library; if not, write to the Free Software
+ *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+#include "config.h"
+
+#if WK_HAVE_C_SPI
+
+#if ENABLE(MEDIA_STREAM)
+#include "PlatformUtilities.h"
+#include "PlatformWebView.h"
+#include "Test.h"
+#include <WebKit/WKPreferencesRef.h>
+#include <WebKit/WKPreferencesRefPrivate.h>
+#include <WebKit/WKRetainPtr.h>
+#include <WebKit/WKUserMediaPermissionCheck.h>
+#include <string.h>
+#include <vector>
+
+namespace TestWebKitAPI {
+
+static bool loadedFirstTime;
+static bool loadedSecondTime;
+
+void checkUserMediaPermissionCallback(WKPageRef, WKFrameRef, WKSecurityOriginRef, WKSecurityOriginRef, WKUserMediaPermissionCheckRef permissionRequest, const void*)
+{
+    WKUserMediaPermissionCheckSetUserMediaAccessInfo(permissionRequest, WKStringCreateWithUTF8CString("0x123456789"), true);
+    if (!loadedFirstTime) {
+        loadedFirstTime = true;
+        return;
+    }
+
+    loadedSecondTime = true;
+}
+
+TEST(WebKit2, EnumerateDevices)
+{
+    auto context = adoptWK(WKContextCreate());
+
+    WKRetainPtr<WKPageGroupRef> pageGroup(AdoptWK, WKPageGroupCreateWithIdentifier(Util::toWK("EnumerateDevices").get()));
+    WKPreferencesRef preferences = WKPageGroupGetPreferences(pageGroup.get());
+    WKPreferencesSetFileAccessFromFileURLsAllowed(preferences, true);
+    WKPreferencesSetMediaCaptureRequiresSecureConnection(preferences, false);
+
+    WKPageUIClientV6 uiClient;
+    memset(&uiClient, 0, sizeof(uiClient));
+    uiClient.base.version = 6;
+    uiClient.checkUserMediaPermissionForOrigin = checkUserMediaPermissionCallback;
+
+    PlatformWebView webView(context.get());
+    WKPageSetPageUIClient(webView.page(), &uiClient.base);
+
+    auto url = adoptWK(Util::createURLForResource("enumerateMediaDevices", "html"));
+
+    // Load and kill the page.
+    WKPageLoadURL(webView.page(), url.get());
+    Util::run(&loadedFirstTime);
+    WKPageTerminate(webView.page());
+
+    // Load it again to make sure the user media process manager doesn't assert.
+    WKPageLoadURL(webView.page(), url.get());
+    Util::run(&loadedSecondTime);
+}
+
+} // namespace TestWebKitAPI
+
+#endif // ENABLE(MEDIA_STREAM)
+
+#endif // WK_HAVE_C_SPI
diff --git a/Tools/TestWebKitAPI/Tests/WebKit2/enumerateMediaDevices.html b/Tools/TestWebKitAPI/Tests/WebKit2/enumerateMediaDevices.html
new file mode 100644 (file)
index 0000000..ffde3ce
--- /dev/null
@@ -0,0 +1,24 @@
+<html>
+    <head>
+        <script>
+            function enumerate(devices)
+            {
+                console.log("enumerateDevices succeeded");
+            }
+
+            function userMediaError(error)
+            {
+                console.log(error);
+            }
+
+            function test()
+            {
+                navigator.mediaDevices.enumerateDevices()
+                    .then(enumerate)
+                    .catch(userMediaError);
+            }
+        </script>
+    </head>
+    <body onload="test()">
+    </body>
+</html>