blob: 5e9153e2f8537660d1eb797c84fd60278c9a3d72 [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>
16
17// Wrapper for boost::async_pipe ensuring proper pipe cleanup
18class CredentialsPipe
19{
20 public:
Ed Tanous3bfa3b22024-01-31 12:18:03 -080021 explicit CredentialsPipe(boost::asio::io_context& io) : impl(io), read(io)
22 {
23 boost::system::error_code ec;
24 boost::asio::connect_pipe(read, impl, ec);
25 if (ec)
26 {
27 BMCWEB_LOG_CRITICAL("Failed to connect pipe {}", ec.what());
28 }
29 }
Ed Tanous11e8f602023-08-24 14:25:18 -070030
31 CredentialsPipe(const CredentialsPipe&) = delete;
32 CredentialsPipe(CredentialsPipe&&) = delete;
33 CredentialsPipe& operator=(const CredentialsPipe&) = delete;
34 CredentialsPipe& operator=(CredentialsPipe&&) = delete;
35
36 ~CredentialsPipe()
37 {
38 explicit_bzero(user.data(), user.capacity());
39 explicit_bzero(pass.data(), pass.capacity());
40 }
41
Ed Tanous3bfa3b22024-01-31 12:18:03 -080042 int releaseFd()
Ed Tanous11e8f602023-08-24 14:25:18 -070043 {
Ed Tanous3bfa3b22024-01-31 12:18:03 -080044 return read.release();
Ed Tanous11e8f602023-08-24 14:25:18 -070045 }
46
47 template <typename WriteHandler>
48 void asyncWrite(std::string&& username, std::string&& password,
49 WriteHandler&& handler)
50 {
51 user = std::move(username);
52 pass = std::move(password);
53
54 // Add +1 to ensure that the null terminator is included.
55 std::array<boost::asio::const_buffer, 2> buffer{
56 {{user.data(), user.size() + 1}, {pass.data(), pass.size() + 1}}};
57 boost::asio::async_write(impl, buffer,
58 std::forward<WriteHandler>(handler));
59 }
60
Ed Tanous3bfa3b22024-01-31 12:18:03 -080061 boost::asio::writable_pipe impl;
62 boost::asio::readable_pipe read;
Ed Tanous11e8f602023-08-24 14:25:18 -070063
64 private:
65 std::string user;
66 std::string pass;
67};