1 /*
2 * Copyright (C) 2024 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 #include "host/commands/process_sandboxer/proxy_common.h"
17
18 #include <sys/socket.h>
19 #include <sys/uio.h>
20
21 #include <cerrno>
22 #include <cstdlib>
23 #include <cstring>
24 #include <optional>
25 #include <string>
26 #include <string_view>
27
28 #include <absl/status/status.h>
29 #include <absl/status/statusor.h>
30
31 namespace cuttlefish::process_sandboxer {
32
RecvFrom(int sock)33 absl::StatusOr<Message> Message::RecvFrom(int sock) {
34 msghdr empty_hdr = {};
35 int len = recvmsg(sock, &empty_hdr, MSG_PEEK | MSG_TRUNC);
36 if (len < 0) {
37 return absl::ErrnoToStatus(errno, "recvmsg with MSG_PEEK failed");
38 }
39
40 Message message;
41 message.data_ = std::string(len, '\0');
42
43 iovec msg_iovec = iovec{
44 .iov_base = reinterpret_cast<void*>(message.data_.data()),
45 .iov_len = static_cast<size_t>(len),
46 };
47
48 union {
49 char buf[CMSG_SPACE(sizeof(ucred))];
50 struct cmsghdr align;
51 } cmsg_data;
52 std::memset(cmsg_data.buf, 0, sizeof(cmsg_data.buf));
53
54 msghdr hdr = msghdr{
55 .msg_iov = &msg_iovec,
56 .msg_iovlen = 1,
57 .msg_control = cmsg_data.buf,
58 .msg_controllen = sizeof(cmsg_data.buf),
59 };
60
61 auto recvmsg_ret = recvmsg(sock, &hdr, 0);
62 if (recvmsg_ret < 0) {
63 return absl::ErrnoToStatus(errno, "recvmsg failed");
64 }
65
66 for (auto cmsg = CMSG_FIRSTHDR(&hdr); cmsg != nullptr;
67 cmsg = CMSG_NXTHDR(&hdr, cmsg)) {
68 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_CREDENTIALS) {
69 message.credentials_ = *(ucred*)CMSG_DATA(cmsg);
70 }
71 }
72
73 return message;
74 }
75
Data() const76 const std::string& Message::Data() const { return data_; }
77
Credentials() const78 const std::optional<ucred>& Message::Credentials() const {
79 return credentials_;
80 }
81
SendStringMsg(int sock,std::string_view msg)82 absl::StatusOr<size_t> SendStringMsg(int sock, std::string_view msg) {
83 iovec msg_iovec = iovec{
84 .iov_base = (void*)msg.data(),
85 .iov_len = msg.length(),
86 };
87
88 msghdr hdr = msghdr{
89 .msg_iov = &msg_iovec,
90 .msg_iovlen = 1,
91 };
92
93 auto ret = sendmsg(sock, &hdr, MSG_EOR | MSG_NOSIGNAL);
94 return ret >= 0 ? absl::StatusOr<size_t>(ret)
95 : absl::ErrnoToStatus(errno, "sendmsg failed");
96 }
97
98 } // namespace cuttlefish::process_sandboxer
99