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 2 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/>. */
23 #include <sys/types.h>
26 #ifdef HAVE_SYS_SOCKET_H
27 #include <sys/socket.h>
32 #ifdef HAVE_WINSOCK2_H
36 /* Sendfd sends the file descriptor fd along the socket
37 to a process calling recvfd on the other end.
39 return -1 in case of error, 0 on success
42 sendfd (int sock, int fd)
48 /* send at least one char */
49 iov[0].iov_base = &send;
57 #ifdef HAVE_UNIXSOCKET_SCM_RIGHTS_BSD44_WAY
59 char buf[CMSG_SPACE (sizeof (fd))];
61 msg.msg_control = buf;
62 msg.msg_controllen = sizeof (buf);
63 cmsg = CMSG_FIRSTHDR (&msg);
64 cmsg->cmsg_level = SOL_SOCKET;
65 cmsg->cmsg_type = SCM_RIGHTS;
66 cmsg->cmsg_len = CMSG_LEN (sizeof (int));
67 /* Initialize the payload: */
68 memcpy (CMSG_DATA (cmsg), &fd, sizeof (fd));
69 msg.msg_controllen = cmsg->cmsg_len;
70 #elif HAVE_UNIXSOCKET_SCM_RIGHTS_BSD43_WAY
71 msg.msg_accrights = &fd;
72 msg.msg_accrightslen = sizeof (fd);
79 if (sendmsg (sock, &msg, 0) != iov[0].iov_len)
84 /* Sendfd sends the file descriptor fd along the socket
85 to a process calling recvfd on the other end.
87 return -1 in case of error, fd on success
98 /* send at least one char */
99 iov[0].iov_base = &recv;
107 #ifdef HAVE_UNIXSOCKET_SCM_RIGHTS_BSD44_WAY
108 struct cmsghdr *cmsg;
109 char buf[CMSG_SPACE (sizeof (fd))];
111 msg.msg_control = buf;
112 msg.msg_controllen = sizeof (buf);
113 cmsg = CMSG_FIRSTHDR (&msg);
114 cmsg->cmsg_level = SOL_SOCKET;
115 cmsg->cmsg_type = SCM_RIGHTS;
116 cmsg->cmsg_len = CMSG_LEN (sizeof (int));
117 /* Initialize the payload: */
118 memcpy (CMSG_DATA (cmsg), &mone, sizeof (mone));
119 msg.msg_controllen = cmsg->cmsg_len;
121 if (recvmsg (sock, &msg, 0) < 0)
124 cmsg = CMSG_FIRSTHDR (&msg);
126 if (cmsg == NULL || cmsg->cmsg_len != CMSG_LEN (sizeof (int))
127 || cmsg->cmsg_level != SOL_SOCKET || cmsg->cmsg_type != SCM_RIGHTS)
129 /* fake errno: at end the file is not available */
134 memcpy (&fd, CMSG_DATA (cmsg), sizeof (fd));
136 #elif HAVE_UNIXSOCKET_SCM_RIGHTS_BSD43_WAY
137 msg.msg_accrights = &fd;
138 msg.msg_accrightslen = sizeof (fd);
139 if (recvmsg (sock, &msg, 0) < 0)