Changeset View
Changeset View
Standalone View
Standalone View
src/ioslaves/file/kauth/fdsender.cpp
- This file was added.
1 | /*** | ||||
---|---|---|---|---|---|
2 | Copyright (C) 2017 by Chinmoy Ranjan Pradhan <chinmoyrp65@gmail.com> | ||||
3 | | ||||
4 | This library is free software; you can redistribute it and/or | ||||
5 | modify it under the terms of the GNU Lesser General Public | ||||
6 | License as published by the Free Software Foundation; either | ||||
7 | version 2.1 of the License, or (at your option) version 3, or any | ||||
8 | later version accepted by the membership of KDE e.V. (or its | ||||
9 | successor approved by the membership of KDE e.V.), which shall | ||||
10 | act as a proxy defined in Section 6 of version 3 of the license. | ||||
11 | | ||||
12 | This library is distributed in the hope that it will be useful, | ||||
13 | but WITHOUT ANY WARRANTY; without even the implied warranty of | ||||
14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU | ||||
15 | Lesser General Public License for more details. | ||||
16 | | ||||
17 | You should have received a copy of the GNU Lesser General Public | ||||
18 | License along with this library. If not, see <http://www.gnu.org/licenses/>. | ||||
19 | ***/ | ||||
20 | | ||||
21 | #include <unistd.h> | ||||
22 | #include <sys/socket.h> | ||||
23 | | ||||
24 | #include "../sharefd_p.h" | ||||
25 | #include "fdsender.h" | ||||
26 | | ||||
27 | FdSender::FdSender(const std::string &path) | ||||
28 | : m_socketDes(-1) | ||||
29 | { | ||||
30 | m_socketDes = ::socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK, 0); | ||||
31 | if (m_socketDes == -1) { | ||||
32 | std::cerr << "socket error:" << strerror(errno) << std::endl; | ||||
33 | return; | ||||
34 | } | ||||
35 | | ||||
36 | SocketAddress addr(path); | ||||
37 | if (::connect(m_socketDes, addr.address(), addr.length()) != 0) { | ||||
38 | std::cerr << "connection error:" << strerror(errno) << std::endl; | ||||
39 | ::close(m_socketDes); | ||||
40 | m_socketDes = -1; | ||||
41 | return; | ||||
42 | } | ||||
43 | } | ||||
44 | | ||||
45 | FdSender::~FdSender() | ||||
46 | { | ||||
47 | if (m_socketDes >= 0) { | ||||
48 | ::close(m_socketDes); | ||||
49 | } | ||||
50 | } | ||||
51 | | ||||
52 | bool FdSender::sendFileDescriptor(int fd) | ||||
53 | { | ||||
54 | FDMessageHeader msg; | ||||
55 | cmsghdr *cmsg = msg.cmsgHeader(); | ||||
56 | cmsg->cmsg_len = CMSG_LEN(sizeof(int)); | ||||
57 | cmsg->cmsg_type = SCM_RIGHTS; | ||||
58 | cmsg->cmsg_level = SOL_SOCKET; | ||||
59 | memcpy(CMSG_DATA(cmsg), &fd, sizeof fd); | ||||
60 | bool success = sendmsg(m_socketDes, msg.message(), 0) == 2; | ||||
61 | ::close(m_socketDes); | ||||
62 | return success; | ||||
63 | } | ||||
64 | | ||||
65 | bool FdSender::isConnected() const | ||||
66 | { | ||||
67 | return m_socketDes >= 0; | ||||
68 | } |