File indexing completed on 2025-01-12 03:39:40

0001 /*
0002     SPDX-FileCopyrightText: 2017 Chinmoy Ranjan Pradhan <chinmoyrp65@gmail.com>
0003 
0004     SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
0005 */
0006 
0007 #include "fdsender.h"
0008 
0009 #include "../sharefd_p.h"
0010 #include <cerrno>
0011 #include <string.h>
0012 
0013 FdSender::FdSender(const std::string &path)
0014     : m_socketDes(-1)
0015 {
0016     const SocketAddress addr(path);
0017     if (!addr.address()) {
0018         std::cerr << "Invalid socket address:" << path << std::endl;
0019         return;
0020     }
0021 
0022     m_socketDes = ::socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK, 0);
0023     if (m_socketDes == -1) {
0024         std::cerr << "socket error:" << strerror(errno) << std::endl;
0025         return;
0026     }
0027 
0028     if (::connect(m_socketDes, addr.address(), addr.length()) != 0) {
0029         std::cerr << "connection error:" << strerror(errno) << std::endl;
0030         ::close(m_socketDes);
0031         m_socketDes = -1;
0032         return;
0033     }
0034 }
0035 
0036 FdSender::~FdSender()
0037 {
0038     if (m_socketDes >= 0) {
0039         ::close(m_socketDes);
0040     }
0041 }
0042 
0043 bool FdSender::sendFileDescriptor(int fd)
0044 {
0045     FDMessageHeader msg;
0046     cmsghdr *cmsg = msg.cmsgHeader();
0047     cmsg->cmsg_len = CMSG_LEN(sizeof(int));
0048     cmsg->cmsg_type = SCM_RIGHTS;
0049     cmsg->cmsg_level = SOL_SOCKET;
0050     memcpy(CMSG_DATA(cmsg), &fd, sizeof fd);
0051     bool success = sendmsg(m_socketDes, msg.message(), 0) == 2;
0052     ::close(m_socketDes);
0053     return success;
0054 }
0055 
0056 bool FdSender::isConnected() const
0057 {
0058     return m_socketDes >= 0;
0059 }