1 | /* |
---|---|
2 | SPDX-FileCopyrightText: 2017 Chinmoy Ranjan Pradhan <chinmoyrp65@gmail.com> |
3 | |
4 | SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL |
5 | */ |
6 | |
7 | #include "fdsender.h" |
8 | |
9 | #include "../sharefd_p.h" |
10 | #include <cerrno> |
11 | #include <string.h> |
12 | |
13 | FdSender::FdSender(const std::string &path) |
14 | : m_socketDes(-1) |
15 | { |
16 | const SocketAddress addr(path); |
17 | if (!addr.address()) { |
18 | std::cerr << "Invalid socket address:"<< path << std::endl; |
19 | return; |
20 | } |
21 | |
22 | m_socketDes = ::socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK, protocol: 0); |
23 | if (m_socketDes == -1) { |
24 | std::cerr << "socket error:"<< strerror(errno) << std::endl; |
25 | return; |
26 | } |
27 | |
28 | if (::connect(fd: m_socketDes, addr: addr.address(), len: addr.length()) != 0) { |
29 | std::cerr << "connection error:"<< strerror(errno) << std::endl; |
30 | ::close(fd: m_socketDes); |
31 | m_socketDes = -1; |
32 | return; |
33 | } |
34 | } |
35 | |
36 | FdSender::~FdSender() |
37 | { |
38 | if (m_socketDes >= 0) { |
39 | ::close(fd: m_socketDes); |
40 | } |
41 | } |
42 | |
43 | bool FdSender::sendFileDescriptor(int fd) |
44 | { |
45 | FDMessageHeader msg; |
46 | cmsghdr *cmsg = msg.cmsgHeader(); |
47 | cmsg->cmsg_len = CMSG_LEN(sizeof(int)); |
48 | cmsg->cmsg_type = SCM_RIGHTS; |
49 | cmsg->cmsg_level = SOL_SOCKET; |
50 | memcpy(CMSG_DATA(cmsg), src: &fd, n: sizeof fd); |
51 | bool success = sendmsg(fd: m_socketDes, message: msg.message(), flags: 0) == 2; |
52 | ::close(fd: m_socketDes); |
53 | return success; |
54 | } |
55 | |
56 | bool FdSender::isConnected() const |
57 | { |
58 | return m_socketDes >= 0; |
59 | } |
60 |