File indexing completed on 2025-02-09 04:24:08
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 #ifndef SHAREFD_P_H 0008 #define SHAREFD_P_H 0009 0010 #include <iostream> 0011 #include <stddef.h> 0012 #include <string.h> 0013 #include <sys/socket.h> 0014 #include <sys/un.h> 0015 #include <unistd.h> 0016 0017 // fix SOCK_NONBLOCK for e.g. macOS 0018 #ifndef SOCK_NONBLOCK 0019 #include <fcntl.h> 0020 #define SOCK_NONBLOCK O_NONBLOCK 0021 #endif 0022 0023 class SocketAddress 0024 { 0025 const sockaddr_un addr; 0026 0027 public: 0028 explicit SocketAddress(const std::string &path) 0029 : addr(make_address(path)) 0030 { 0031 } 0032 0033 int length() const 0034 { 0035 return offsetof(struct sockaddr_un, sun_path) + strlen(addr.sun_path) + 1; 0036 } 0037 const sockaddr *address() const 0038 { 0039 return addr.sun_path[0] ? reinterpret_cast<const sockaddr *>(&addr) : nullptr; 0040 } 0041 0042 private: 0043 static sockaddr_un make_address(const std::string &path) 0044 { 0045 sockaddr_un a; 0046 memset(&a, 0, sizeof a); 0047 a.sun_family = AF_UNIX; 0048 const size_t pathSize = path.size(); 0049 if (pathSize > 0 && pathSize < sizeof(a.sun_path) - 1) { 0050 memcpy(a.sun_path, path.c_str(), pathSize + 1); 0051 } 0052 return a; 0053 } 0054 }; 0055 0056 class FDMessageHeader 0057 { 0058 char io_buf[2]; 0059 char cmsg_buf[CMSG_SPACE(sizeof(int))]; 0060 iovec io; 0061 msghdr msg; 0062 0063 public: 0064 FDMessageHeader() 0065 : io_buf{0} 0066 , cmsg_buf{0} 0067 { 0068 memset(&io, 0, sizeof io); 0069 io.iov_base = &io_buf; 0070 io.iov_len = sizeof io_buf; 0071 0072 memset(&msg, 0, sizeof msg); 0073 msg.msg_iov = &io; 0074 msg.msg_iovlen = 1; 0075 msg.msg_control = &cmsg_buf; 0076 msg.msg_controllen = sizeof cmsg_buf; 0077 } 0078 0079 msghdr *message() 0080 { 0081 return &msg; 0082 } 0083 0084 cmsghdr *cmsgHeader() 0085 { 0086 return CMSG_FIRSTHDR(&msg); 0087 } 0088 }; 0089 0090 #endif