1 /* Copyright (C) 2011 Free Software Foundation, Inc.
3 This program is free software: you can redistribute it and/or modify
4 it under the terms of the GNU General Public License as published by
5 the Free Software Foundation; either version 3 of the License, or
6 (at your option) any later version.
8 This program is distributed in the hope that it will be useful,
9 but WITHOUT ANY WARRANTY; without even the implied warranty of
10 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 GNU General Public License for more details.
13 You should have received a copy of the GNU General Public License
14 along with this program. If not, see <http://www.gnu.org/licenses/>. */
25 #include <sys/types.h>
28 #include <sys/socket.h>
33 /* sendfd sends the file descriptor fd along the socket
34 to a process calling recvfd on the other end.
36 Return 0 on success, or -1 with errno set in case of error.
39 sendfd (int sock, int fd)
45 /* send at least one char */
46 iov[0].iov_base = &send;
54 #if HAVE_UNIXSOCKET_SCM_RIGHTS_BSD44_WAY
56 char buf[CMSG_SPACE (sizeof (fd))];
58 msg.msg_control = buf;
59 msg.msg_controllen = sizeof (buf);
60 cmsg = CMSG_FIRSTHDR (&msg);
61 cmsg->cmsg_level = SOL_SOCKET;
62 cmsg->cmsg_type = SCM_RIGHTS;
63 cmsg->cmsg_len = CMSG_LEN (sizeof (int));
64 /* Initialize the payload: */
65 memcpy (CMSG_DATA (cmsg), &fd, sizeof (fd));
66 msg.msg_controllen = cmsg->cmsg_len;
67 #elif HAVE_UNIXSOCKET_SCM_RIGHTS_BSD43_WAY
68 msg.msg_accrights = &fd;
69 msg.msg_accrightslen = sizeof (fd);
76 if (sendmsg (sock, &msg, 0) != iov[0].iov_len)
81 /* recvfd receives a file descriptor through the socket.
83 Return 0 on success, or -1 with errno set in case of error.
92 /* send at least one char */
93 iov[0].iov_base = &recv;
101 #if HAVE_UNIXSOCKET_SCM_RIGHTS_BSD44_WAY
103 struct cmsghdr *cmsg;
104 char buf[CMSG_SPACE (sizeof (fd))];
107 msg.msg_control = buf;
108 msg.msg_controllen = sizeof (buf);
109 cmsg = CMSG_FIRSTHDR (&msg);
110 cmsg->cmsg_level = SOL_SOCKET;
111 cmsg->cmsg_type = SCM_RIGHTS;
112 cmsg->cmsg_len = CMSG_LEN (sizeof (int));
113 /* Initialize the payload: */
114 memcpy (CMSG_DATA (cmsg), &mone, sizeof (mone));
115 msg.msg_controllen = cmsg->cmsg_len;
117 if (recvmsg (sock, &msg, 0) < 0)
120 cmsg = CMSG_FIRSTHDR (&msg);
122 if (cmsg == NULL || cmsg->cmsg_len != CMSG_LEN (sizeof (int))
123 || cmsg->cmsg_level != SOL_SOCKET || cmsg->cmsg_type != SCM_RIGHTS)
125 /* fake errno: at end the file is not available */
130 memcpy (&fd, CMSG_DATA (cmsg), sizeof (fd));
132 #elif HAVE_UNIXSOCKET_SCM_RIGHTS_BSD43_WAY
135 msg.msg_accrights = &fd;
136 msg.msg_accrightslen = sizeof (fd);
137 if (recvmsg (sock, &msg, 0) < 0)