1 /*
2 * Copyright (C) 2021-2022 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
16 #include "socket_util.h"
17 #include <cerrno>
18 #include <cstring>
19 #include <sys/socket.h>
20 #include "log.h"
21 #include "securec.h"
22
23 namespace OHOS {
24 namespace bluetooth {
SocketSendData(int sockFd,const uint8_t * buf,int len)25 int SocketUtil::SocketSendData(int sockFd, const uint8_t *buf, int len)
26 {
27 int sendSize = len;
28
29 while (sendSize) {
30 ssize_t size = send(sockFd, buf, sendSize, 0);
31 if (size <= 0) {
32 return -1;
33 }
34 if (size > sendSize) {
35 return -1;
36 }
37 buf += size;
38 sendSize -= size;
39 }
40 return len;
41 }
42
SocketSendFd(int sockFd,const uint8_t * buf,int len,int acceptFd)43 int SocketUtil::SocketSendFd(int sockFd, const uint8_t *buf, int len, int acceptFd)
44 {
45 LOG_INFO("[sock]%{public}s", __func__);
46
47 if ((sockFd == -1 || acceptFd == -1)) {
48 return -1;
49 }
50
51 int sendSize = len;
52 struct msghdr msghdr = {};
53 struct iovec iovec = {};
54 struct cmsghdr *cmsghdr;
55 char msgbuffer[CMSG_SPACE(1)] = {0};
56
57 (void)memset_s(&msghdr, sizeof(msghdr), 0, sizeof(msghdr));
58 (void)memset_s(&iovec, sizeof(iovec), 0, sizeof(iovec));
59
60 msghdr.msg_control = msgbuffer;
61 msghdr.msg_controllen = sizeof(msgbuffer);
62 cmsghdr = CMSG_FIRSTHDR(&msghdr);
63 cmsghdr->cmsg_len = CMSG_LEN(sizeof(acceptFd));
64 cmsghdr->cmsg_type = SCM_RIGHTS;
65 cmsghdr->cmsg_level = SOL_SOCKET;
66 (void)memcpy_s(CMSG_DATA(cmsghdr), sizeof(acceptFd), &acceptFd, sizeof(acceptFd));
67
68 while (len > 0) {
69 iovec.iov_base = const_cast<void *>(static_cast<const void *>(buf));
70 iovec.iov_len = len;
71
72 msghdr.msg_iov = &iovec;
73 msghdr.msg_iovlen = 1;
74
75 #ifdef DARWIN_PLATFORM
76 ssize_t size = sendmsg(sockFd, &msghdr, 0);
77 #else
78 ssize_t size = sendmsg(sockFd, &msghdr, MSG_NOSIGNAL);
79 #endif
80 LOG_INFO("[sock]%{public}s sendmsg size:%{public}zu", __func__, size);
81 if (size < 0) {
82 sendSize = -1;
83 break;
84 }
85
86 buf += size;
87 len -= size;
88 (void)memset_s(&msghdr, sizeof(msghdr), 0, sizeof(msghdr));
89 }
90 LOG_INFO("[sock]%{public}s close accept_fd:%{public}d after sent", __func__, acceptFd);
91 return sendSize;
92 }
93 } // namespace bluetooth
94 } // namespace OHOS
95