/* 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 SECURITY_SANDBOX_SANDBOXTARGET_H_
#define SECURITY_SANDBOX_SANDBOXTARGET_H_

#include <windows.h>

#include <functional>
#include <list>
#include <utility>

#include "mozilla/Assertions.h"

namespace sandbox {
class TargetServices;
}

namespace mozilla {

class SandboxTarget {
 public:
  /**
   * Obtains a pointer to the singleton instance
   */
  static SandboxTarget* Instance();

  /**
   * Used by the application to pass in the target services that provide certain
   * functions to the sandboxed code.
   * The target services must already be initialized.
   *
   * @param aTargetServices The target services that will be used
   */
  void SetTargetServices(sandbox::TargetServices* aTargetServices) {
    MOZ_ASSERT(aTargetServices);
    MOZ_ASSERT(!mTargetServices,
               "Sandbox TargetServices must only be set once.");

    mTargetServices = aTargetServices;
  }

  bool IsSandboxed() const { return mTargetServices != nullptr; }

  template <typename CallbackT>
  void RegisterSandboxStartCallback(CallbackT&& aCallback) {
    mStartObservers.push_back(std::forward<CallbackT>(aCallback));
  }

  /**
   * Called by the library that wants to "start" the sandbox, i.e. change to the
   * more secure delayed / lockdown policy.
   */
  void StartSandbox();
  /**
   * Called by content processes to lower the sandbox. This includes other
   * processing like DLL pre-loading to prevent failures after lowering.
   */
  void LowerContentSandbox();

 protected:
  SandboxTarget() : mTargetServices(nullptr) {}

  sandbox::TargetServices* mTargetServices;

 private:
  void NotifyStartObservers();
  std::list<std::function<void()>> mStartObservers;
};

}  // namespace mozilla

#endif
