blob: dc3e4908e87527f0de2915293be7cf011fa6fe97 [file] [log] [blame]
Ed Tanous40e9b922024-09-10 13:50:16 -07001// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright OpenBMC Authors
Ed Tanous11e8f602023-08-24 14:25:18 -07003#pragma once
4
Ed Tanous3bfa3b22024-01-31 12:18:03 -08005#include "logging.hpp"
6
Ed Tanous11e8f602023-08-24 14:25:18 -07007#include <boost/asio/buffer.hpp>
Ed Tanous3bfa3b22024-01-31 12:18:03 -08008#include <boost/asio/connect_pipe.hpp>
Ed Tanous11e8f602023-08-24 14:25:18 -07009#include <boost/asio/io_context.hpp>
Ed Tanous3bfa3b22024-01-31 12:18:03 -080010#include <boost/asio/readable_pipe.hpp>
11#include <boost/asio/writable_pipe.hpp>
Ed Tanous11e8f602023-08-24 14:25:18 -070012#include <boost/asio/write.hpp>
Ed Tanous11e8f602023-08-24 14:25:18 -070013
14#include <array>
15#include <string>
Ed Tanousd7857202025-01-28 15:32:26 -080016#include <utility>
Ed Tanous11e8f602023-08-24 14:25:18 -070017
18// Wrapper for boost::async_pipe ensuring proper pipe cleanup
19class CredentialsPipe
20{
21 public:
Ed Tanous3bfa3b22024-01-31 12:18:03 -080022 explicit CredentialsPipe(boost::asio::io_context& io) : impl(io), read(io)
23 {
24 boost::system::error_code ec;
Ed Tanousd7857202025-01-28 15:32:26 -080025
26 // Unclear why tidy complains here.
27 // NOLINTNEXTLINE(misc-include-cleaner)
Ed Tanous3bfa3b22024-01-31 12:18:03 -080028 boost::asio::connect_pipe(read, impl, ec);
29 if (ec)
30 {
31 BMCWEB_LOG_CRITICAL("Failed to connect pipe {}", ec.what());
32 }
33 }
Ed Tanous11e8f602023-08-24 14:25:18 -070034
35 CredentialsPipe(const CredentialsPipe&) = delete;
36 CredentialsPipe(CredentialsPipe&&) = delete;
37 CredentialsPipe& operator=(const CredentialsPipe&) = delete;
38 CredentialsPipe& operator=(CredentialsPipe&&) = delete;
39
40 ~CredentialsPipe()
41 {
Ed Tanousd7857202025-01-28 15:32:26 -080042 // NOLINTNEXTLINE(misc-include-cleaner)
Ed Tanous11e8f602023-08-24 14:25:18 -070043 explicit_bzero(user.data(), user.capacity());
44 explicit_bzero(pass.data(), pass.capacity());
45 }
46
Ed Tanous3bfa3b22024-01-31 12:18:03 -080047 int releaseFd()
Ed Tanous11e8f602023-08-24 14:25:18 -070048 {
Ed Tanous3bfa3b22024-01-31 12:18:03 -080049 return read.release();
Ed Tanous11e8f602023-08-24 14:25:18 -070050 }
51
52 template <typename WriteHandler>
53 void asyncWrite(std::string&& username, std::string&& password,
54 WriteHandler&& handler)
55 {
56 user = std::move(username);
57 pass = std::move(password);
58
59 // Add +1 to ensure that the null terminator is included.
60 std::array<boost::asio::const_buffer, 2> buffer{
61 {{user.data(), user.size() + 1}, {pass.data(), pass.size() + 1}}};
62 boost::asio::async_write(impl, buffer,
63 std::forward<WriteHandler>(handler));
64 }
65
Ed Tanous3bfa3b22024-01-31 12:18:03 -080066 boost::asio::writable_pipe impl;
67 boost::asio::readable_pipe read;
Ed Tanous11e8f602023-08-24 14:25:18 -070068
69 private:
70 std::string user;
71 std::string pass;
72};