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 | #ifndef SHAREFD_P_H |
8 | #define SHAREFD_P_H |
9 | |
10 | #include <iostream> |
11 | #include <stddef.h> |
12 | #include <string.h> |
13 | #include <sys/socket.h> |
14 | #include <sys/un.h> |
15 | #include <unistd.h> |
16 | |
17 | // fix SOCK_NONBLOCK for e.g. macOS |
18 | #ifndef SOCK_NONBLOCK |
19 | #include <fcntl.h> |
20 | #define SOCK_NONBLOCK O_NONBLOCK |
21 | #endif |
22 | |
23 | class SocketAddress |
24 | { |
25 | const sockaddr_un addr; |
26 | |
27 | public: |
28 | explicit SocketAddress(const std::string &path) |
29 | : addr(make_address(path)) |
30 | { |
31 | } |
32 | |
33 | int length() const |
34 | { |
35 | return offsetof(struct sockaddr_un, sun_path) + strlen(s: addr.sun_path) + 1; |
36 | } |
37 | const sockaddr *address() const |
38 | { |
39 | return addr.sun_path[0] ? reinterpret_cast<const sockaddr *>(&addr) : nullptr; |
40 | } |
41 | |
42 | private: |
43 | static sockaddr_un make_address(const std::string &path) |
44 | { |
45 | sockaddr_un a; |
46 | memset(s: &a, c: 0, n: sizeof a); |
47 | a.sun_family = AF_UNIX; |
48 | const size_t pathSize = path.size(); |
49 | if (pathSize > 0 && pathSize < sizeof(a.sun_path) - 1) { |
50 | memcpy(dest: a.sun_path, src: path.c_str(), n: pathSize + 1); |
51 | } |
52 | return a; |
53 | } |
54 | }; |
55 | |
56 | class |
57 | { |
58 | char [2]; |
59 | char [CMSG_SPACE(sizeof(int))]; |
60 | iovec ; |
61 | msghdr ; |
62 | |
63 | public: |
64 | () |
65 | : io_buf{0} |
66 | , cmsg_buf{0} |
67 | { |
68 | memset(s: &io, c: 0, n: sizeof io); |
69 | io.iov_base = &io_buf; |
70 | io.iov_len = sizeof io_buf; |
71 | |
72 | memset(s: &msg, c: 0, n: sizeof msg); |
73 | msg.msg_iov = &io; |
74 | msg.msg_iovlen = 1; |
75 | msg.msg_control = &cmsg_buf; |
76 | msg.msg_controllen = sizeof cmsg_buf; |
77 | } |
78 | |
79 | msghdr *() |
80 | { |
81 | return &msg; |
82 | } |
83 | |
84 | cmsghdr *() |
85 | { |
86 | return CMSG_FIRSTHDR(&msg); |
87 | } |
88 | }; |
89 | |
90 | #endif |
91 | |