Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit daddd8b2 authored by Jeremy Wu's avatar Jeremy Wu Committed by Automerger Merge Worker
Browse files

Merge "Floss: add MMC DBus service daemon and related conf files." into main am: 85915d19

parents 8e2d0746 85915d19
Loading
Loading
Loading
Loading
+88 −0
Original line number Diff line number Diff line
#
#  Copyright 2023 The Android Open Source Project
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at:
#
#  http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.
#

import("//common-mk/install_config.gni")

group("mmc") {
  deps = [
    ":install_dbus_config",
    ":install_init",
    ":install_minijail_config",
    ":install_system_service",
    ":install_tmpfiles_config",
    ":mmc_service",
  ]
}

pkg_config("target_defaults") {
  include_dirs = [
    "//bt/system",
    "//bt/system/include",
    "//bt/system/stack",
    "//bt/system/stack/include",
  ]
  pkg_deps = [
    "libchrome",
  ]
  if (use.fuzzer) {
    pkg_deps += [ "protobuf" ]
  } else {
    pkg_deps += [ "protobuf-lite" ]
  }
}

install_config("install_dbus_config") {
  sources = [ "dbus_permissions/org.chromium.mmc.CodecManager.conf" ]
  install_path = "/etc/dbus-1/system.d"
}

install_config("install_system_service") {
  sources = [ "dbus_service/org.chromium.mmc.CodecManager.service" ]
  install_path = "/usr/share/dbus-1/system-services"
}

install_config("install_init") {
  sources = [ "init/mmc_service.conf" ]
  install_path = "/etc/init"
}

install_config("install_tmpfiles_config") {
  sources = [ "tmpfiles.d/mmc.conf" ]
  install_path = "/usr/lib/tmpfiles.d"
}

install_config("install_minijail_config") {
  sources = [ "minijail/mmc.conf" ]
  install_path = "/usr/share/minijail"
}

source_set("libmmc") {
  configs += [ ":target_defaults" ]
  sources = [
    "daemon/service.cc",
  ]
  deps = [
    "//bt/system/common",
    "//bt/system/stack/mmc/proto:mmc_service_proto",
    "//bt/system/stack/mmc/codec_server:libcodec_server_hfp_lc3",
  ]
}

executable("mmc_service") {
  configs += [ ":target_defaults" ]
  deps = [ ":libmmc" ]
  sources = [ "main.cc" ]
}
+43 −0
Original line number Diff line number Diff line
/*
 * Copyright 2023 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef MMC_DAEMON_DBUS_CONSTANTS_H_
#define MMC_DAEMON_DBUS_CONSTANTS_H_

namespace mmc {

// DBus constants.
constexpr char kMmcServiceName[] = "org.chromium.mmc.CodecManager";
constexpr char kMmcServiceInterface[] = "org.chromium.mmc.CodecManager";
constexpr char kMmcServicePath[] = "/org/chromium/mmc/CodecManager";
const char kMmcServiceError[] = "org.chromium.mmc.CodecManager.Error";
constexpr char kCodecInitMethod[] = "CodecInit";
constexpr char kCodecCleanUpMethod[] = "CodecCleanUp";

// Socket constants.
const char kMmcSocketName[] = "/run/mmc/sockets/";
// The maximum number of socket pending connections.
// MMC daemon expects at most two clients, decoder and encoder of one codec.
constexpr int kClientMaximum = 2;
// Socket default maximum buffer size.
constexpr int kMaximumBufferSize = 32768;

// Thread constants.
constexpr char kWorkerThreadName[] = "bt_mmc_worker_thread";
constexpr int kThreadCheckTimeout = 1;
}  // namespace mmc

#endif  // MMC_DAEMON_DBUS_CONSTANTS_H_
+310 −0
Original line number Diff line number Diff line
/*
 * Copyright 2023 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "mmc/daemon/service.h"

#include <base/functional/bind.h>
#include <base/functional/callback_helpers.h>
#include <base/logging.h>
#include <base/stl_util.h>
#include <base/task/single_thread_task_runner.h>
#include <base/unguessable_token.h>
#include <errno.h>
#include <poll.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/un.h>
#include <unistd.h>

#include <array>
#include <cstring>
#include <future>

#include "common/message_loop_thread.h"
#include "mmc/codec_server/hfp_lc3_mmc_decoder.h"
#include "mmc/codec_server/hfp_lc3_mmc_encoder.h"
#include "mmc/daemon/constants.h"
#include "mmc/mmc_interface/mmc_interface.h"
#include "mmc/proto/mmc_service.pb.h"

namespace mmc {
namespace {
// Task that would run on the thread.
void StartSocketListener(int fd, struct sockaddr_un addr,
                         std::promise<void> task_ended,
                         std::unique_ptr<MmcInterface> codec_server) {
  socklen_t addr_size = sizeof(struct sockaddr_un);
  int client_fd = accept(fd, (struct sockaddr*)&addr, &addr_size);
  // |fd| is only used for accept.
  close(fd);

  if (client_fd < 0) {
    LOG(ERROR) << "Failed to accept: " << strerror(errno);
    codec_server.release();
    task_ended.set_value();
    return;
  }

  std::array<uint8_t, kMaximumBufferSize> i_buf = {};
  std::array<uint8_t, kMaximumBufferSize> o_buf = {};

  struct pollfd pfd;
  pfd.fd = client_fd;
  pfd.events = POLLIN;

  while (1) {
    // Blocking poll.
    int poll_ret = poll(&pfd, 1, -1);
    if (poll_ret <= 0) {
      LOG(ERROR) << "Poll failed: " << strerror(errno);
      break;
    }

    // Ignore remaining data in the closed socket.
    if (pfd.revents & (POLLHUP | POLLNVAL)) {
      LOG(INFO) << "Socket disconnected";
      break;
    }

    int i_data_len =
        recv(client_fd, i_buf.data(), kMaximumBufferSize, MSG_NOSIGNAL);
    if (i_data_len <= 0) {
      LOG(ERROR) << "Failed to recv data: " << strerror(errno);
      break;
    }

    // Start transcode.
    int o_data_len = codec_server->transcode(i_buf.data(), i_data_len,
                                             o_buf.data(), kMaximumBufferSize);
    if (o_data_len < 0) {
      LOG(ERROR) << "Failed to transcode: " << strerror(-o_data_len);
      break;
    }

    int sent_rc = send(client_fd, o_buf.data(), o_data_len, MSG_NOSIGNAL);
    if (sent_rc <= 0) {
      LOG(ERROR) << "Failed to send data: " << strerror(errno);
      break;
    }
    o_buf.fill(0);
  }
  close(client_fd);
  unlink(addr.sun_path);
  codec_server.release();
  task_ended.set_value();
  return;
}

}  // namespace

Service::Service(base::OnceClosure shutdown_callback)
    : shutdown_callback_(std::move(shutdown_callback)),
      weak_ptr_factory_(this) {}

bool Service::Init() {
  // Set up the dbus service.
  dbus::Bus::Options opts;
  opts.bus_type = dbus::Bus::SYSTEM;
  bus_ = new dbus::Bus(std::move(opts));

  if (!bus_->Connect()) {
    LOG(ERROR) << "Failed to connect to system bus";
    return false;
  }

  exported_object_ = bus_->GetExportedObject(dbus::ObjectPath(kMmcServicePath));
  if (!exported_object_) {
    LOG(ERROR) << "Failed to export " << kMmcServicePath << " object";
    return false;
  }

  using ServiceMethod = void (Service::*)(dbus::MethodCall*,
                                          dbus::ExportedObject::ResponseSender);
  const std::map<const char*, ServiceMethod> kServiceMethods = {
      {kCodecInitMethod, &Service::CodecInit},
      {kCodecCleanUpMethod, &Service::CodecCleanUp},
  };

  for (const auto& iter : kServiceMethods) {
    bool ret = exported_object_->ExportMethodAndBlock(
        kMmcServiceInterface, iter.first,
        base::BindRepeating(iter.second, weak_ptr_factory_.GetWeakPtr()));
    if (!ret) {
      LOG(ERROR) << "Failed to export method: " << iter.first;
      return false;
    }
  }

  if (!bus_->RequestOwnershipAndBlock(kMmcServiceName,
                                      dbus::Bus::REQUIRE_PRIMARY)) {
    LOG(ERROR) << "Failed to take ownership of " << kMmcServiceName;
    return false;
  }
  return true;
}

void Service::CodecInit(dbus::MethodCall* method_call,
                        dbus::ExportedObject::ResponseSender sender) {
  dbus::MessageReader reader(method_call);
  auto dbus_response = dbus::Response::FromMethodCall(method_call);

  dbus::MessageWriter writer(dbus_response.get());

  CodecInitRequest request;
  CodecInitResponse response;

  if (!reader.PopArrayOfBytesAsProto(&request)) {
    std::move(sender).Run(dbus::ErrorResponse::FromMethodCall(
        method_call, kMmcServiceError,
        "Unable to parse CodecInitRequest from message"));
    return;
  }

  if (!request.has_config()) {
    std::move(sender).Run(dbus::ErrorResponse::FromMethodCall(
        method_call, kMmcServiceError, "'Config Param' must be set"));
    return;
  }

  // Create codec server instance.
  std::unique_ptr<MmcInterface> codec_server;
  if (request.config().has_hfp_lc3_decoder_param()) {
    codec_server = std::make_unique<HfpLc3Decoder>();
  } else if (request.config().has_hfp_lc3_encoder_param()) {
    codec_server = std::make_unique<HfpLc3Encoder>();
  } else {
    std::move(sender).Run(dbus::ErrorResponse::FromMethodCall(
        method_call, kMmcServiceError, "Codec type must be specified"));
    return;
  }

  int frame_size = codec_server->init(request.config());
  if (frame_size < 0) {
    std::move(sender).Run(dbus::ErrorResponse::FromMethodCall(
        method_call, kMmcServiceError,
        "Init codec server failed: " + std::string(strerror(-frame_size))));
    return;
  }
  response.set_input_frame_size(frame_size);

  // Generate socket name for client.
  std::string socket_path =
      std::string(kMmcSocketName) + base::UnguessableToken::Create().ToString();
  response.set_socket_token(socket_path);

  int skt_fd = socket(AF_UNIX, SOCK_SEQPACKET, 0);
  if (skt_fd < 0) {
    std::move(sender).Run(dbus::ErrorResponse::FromMethodCall(
        method_call, kMmcServiceError,
        "Create socket failed: " + std::string(strerror(errno))));
    return;
  }

  struct sockaddr_un addr = {};
  addr.sun_family = AF_UNIX;
  strncpy(addr.sun_path, response.socket_token().c_str(),
          sizeof(addr.sun_path) - 1);
  unlink(addr.sun_path);

  if (bind(skt_fd, (struct sockaddr*)&addr, sizeof(struct sockaddr_un)) == -1) {
    std::move(sender).Run(dbus::ErrorResponse::FromMethodCall(
        method_call, kMmcServiceError,
        "Bind socket failed: " + std::string(strerror(errno))));
    return;
  }

  // mmc_service group can read/write the socket.
  int rc = chmod(addr.sun_path, 0770);
  if (rc < 0) {
    std::move(sender).Run(dbus::ErrorResponse::FromMethodCall(
        method_call, kMmcServiceError,
        "Chmod socket failed: " + std::string(strerror(errno))));
    return;
  }

  if (listen(skt_fd, kClientMaximum) == -1) {
    std::move(sender).Run(dbus::ErrorResponse::FromMethodCall(
        method_call, kMmcServiceError,
        "Listen socket failed: " + std::string(strerror(errno))));
    return;
  }

  // Create a thread and pass codec server and socket fd to it.
  if (!StartWorkerThread(skt_fd, std::move(addr), std::move(codec_server))) {
    std::move(sender).Run(dbus::ErrorResponse::FromMethodCall(
        method_call, kMmcServiceError, "No free thread available"));
    return;
  }

  writer.AppendProtoAsArrayOfBytes(response);
  std::move(sender).Run(std::move(dbus_response));
  return;
}

void Service::CodecCleanUp(dbus::MethodCall* method_call,
                           dbus::ExportedObject::ResponseSender sender) {
  auto dbus_response = dbus::Response::FromMethodCall(method_call);
  RemoveIdleThread();
  std::move(sender).Run(std::move(dbus_response));
  return;
}

bool Service::StartWorkerThread(int fd, struct sockaddr_un addr,
                                std::unique_ptr<MmcInterface> codec_server) {
  // Each thread has its associated future to indicate task completion.
  std::promise<void> task_ended;
  thread_pool_.push_back(std::make_pair(
      std::make_unique<bluetooth::common::MessageLoopThread>(kWorkerThreadName),
      std::make_unique<std::future<void>>(task_ended.get_future())));

  // Start up thread and assign task to it.
  thread_pool_.back().first->StartUp();
  if (!thread_pool_.back().first->IsRunning()) {
    LOG(ERROR) << "Failed to start thread";
    return false;
  }

  // Real-time scheduling increases thread priority.
  // Without it, the thread still works.
  if (!thread_pool_.back().first->EnableRealTimeScheduling()) {
    LOG(WARNING) << "Failed to enable real time scheduling";
  }

  if (!thread_pool_.back().first->DoInThread(
          FROM_HERE,
          base::BindOnce(&StartSocketListener, fd, std::move(addr),
                         std::move(task_ended), std::move(codec_server)))) {
    LOG(ERROR) << "Failed to run task";
    return false;
  }

  return true;
}

void Service::RemoveIdleThread() {
  for (auto thread = thread_pool_.begin(); thread != thread_pool_.end();) {
    if (thread->second->wait_for(std::chrono::milliseconds(
            kThreadCheckTimeout)) == std::future_status::ready) {
      // The task is over, close the thread and remove it from the thread pool.
      thread->first->ShutDown();
      thread = thread_pool_.erase(thread);
    } else {
      thread++;
    }
  }
}

}  // namespace mmc
+92 −0
Original line number Diff line number Diff line
/*
 * Copyright 2023 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef MMC_DAEMON_SERVICE_H_
#define MMC_DAEMON_SERVICE_H_

#include <base/functional/callback.h>
#include <base/memory/ref_counted.h>
#include <base/memory/weak_ptr.h>
#include <dbus/bus.h>
#include <dbus/exported_object.h>
#include <dbus/message.h>
#include <sys/un.h>

#include <future>
#include <map>
#include <memory>

#include "common/message_loop_thread.h"
#include "mmc/mmc_interface/mmc_interface.h"

namespace mmc {

class Service final {
 public:
  explicit Service(base::OnceClosure shutdown_callback);

  // Service is neither copyable nor movable.
  Service(const Service&) = delete;
  Service& operator=(const Service&) = delete;

  // Connects to DBus and exports methods for client to call.
  bool Init();

 private:
  /* DBus Methods */
  // Main thread creates a codec server instance and a socket,
  // and calls |StartWorkerThread| to let one thread start listening on the
  // socket.
  //
  // Expected input message:
  //   |CodecInitRequest| with |ConfigParam| set.
  // Response:
  //   |CodecInitResponse|, if |CodecInit| succeeded.
  //   ErrorResponse, otherwise.
  void CodecInit(dbus::MethodCall* method_call,
                 dbus::ExportedObject::ResponseSender sender);

  // Main thread removes idle threads from the thread poll.
  //
  // No input message needed.
  // Response:
  //   dbus::Response, implying |CodecCleanUp| finished.
  void CodecCleanUp(dbus::MethodCall* method_call,
                    dbus::ExportedObject::ResponseSender sender);

  /* Thread Management*/
  // Adds a thread to the thread pool and makes it listen on the socket fd.
  bool StartWorkerThread(int fd, struct sockaddr_un addr,
                         std::unique_ptr<MmcInterface> codec_server);

  // Removes idle threads from the thread pool.
  void RemoveIdleThread();

  base::OnceClosure shutdown_callback_;

  scoped_refptr<dbus::Bus> bus_;
  dbus::ExportedObject* exported_object_;  // Owned by the Bus object.

  std::vector<std::pair<std::unique_ptr<bluetooth::common::MessageLoopThread>,
                        std::unique_ptr<std::future<void>>>>
      thread_pool_;

  base::WeakPtrFactory<Service> weak_ptr_factory_;
};

}  // namespace mmc

#endif  // MMC_DAEMON_SERVICE_H_
+47 −0
Original line number Diff line number Diff line
<!DOCTYPE busconfig PUBLIC
 "-//freedesktop//DTD D-BUS Bus Configuration 1.0//EN"
 "http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
<!--
  Copyright (C) 2023 The Android Open Source Project

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<busconfig>
  <!-- User mmc_service owns the interface
       org.chromium.mmc.CodecManager. -->
  <policy user="mmc_service">
    <allow own="org.chromium.mmc.CodecManager" />
  </policy>

  <policy user="bluetooth">
    <!--User bluetooth can send messages to the owner of the given service
        and call CodecInit or CodecCleanUp from the interface
        org.chromium.mmc.CodecManager.-->
    <allow send_destination="org.chromium.mmc.CodecManager"
           send_interface="org.chromium.mmc.CodecManager"
           send_member="CodecInit" />
    <allow send_destination="org.chromium.mmc.CodecManager"
           send_interface="org.chromium.mmc.CodecManager"
           send_member="CodecCleanUp" />
  </policy>

  <!-- For testing. -->
  <policy user="root">
    <allow send_destination="org.chromium.mmc.CodecManager"
           send_interface="org.chromium.mmc.CodecManager"
           send_member="CodecInit"/>
    <allow send_destination="org.chromium.mmc.CodecManager"
           send_interface="org.chromium.mmc.CodecManager"
           send_member="CodecCleanUp" />
  </policy>
</busconfig>
Loading