xref: /developtools/hdc/hdc_rust/src/cffi/sendmsg.cpp (revision cc290419)
1/*
2 * Copyright (C) 2023 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15#include "securec.h"
16#include "sendmsg.h"
17#include "log.h"
18#include <sys/socket.h>
19#include <cstring>
20#include <alloca.h>
21#include <unistd.h>
22#include <cerrno>
23#include <cstdio>
24
25namespace Hdc {
26
27extern "C" int SendMsg(int socketFd, int fd, char* data, int size)
28{
29    constexpr int memcpyError = -2;
30    constexpr int cmsgNullptrError = -5;
31    struct iovec iov;
32    iov.iov_base = data;
33    iov.iov_len = static_cast<size_t>(size);
34    struct msghdr msg;
35    msg.msg_name = nullptr;
36    msg.msg_namelen = 0;
37    msg.msg_iov = &iov;
38    msg.msg_iovlen = 1;
39
40    int len = CMSG_SPACE(static_cast<unsigned int>(sizeof(int)));
41    char ctlBuf[len];
42    msg.msg_control = ctlBuf;
43    msg.msg_controllen = sizeof(ctlBuf);
44
45    struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg);
46    if (cmsg == nullptr) {
47        WRITE_LOG(LOG_WARN, "SendFdToApp cmsg is nullptr\n");
48        return cmsgNullptrError;
49    }
50    cmsg->cmsg_level = SOL_SOCKET;
51    cmsg->cmsg_type = SCM_RIGHTS;
52    cmsg->cmsg_len = CMSG_LEN(sizeof(int));
53    int result = -1;
54    if (memcpy_s(CMSG_DATA(cmsg), sizeof(int), &fd, sizeof(int)) != EOK) {
55        WRITE_LOG(LOG_WARN, "SendFdToApp memcpy_s error:%d\n", errno);
56        return memcpyError;
57    }
58    if ((result = sendmsg(socketFd, &msg, 0)) < 0) {
59        WRITE_LOG(LOG_WARN, "SendFdToApp sendmsg errno:%d, result:%d\n", errno, result);
60        return result;
61    }
62    WRITE_LOG(LOG_INFO, "send msg ok\n");
63    return result;
64}
65}