1 /* net/recvfd.c - Receive a file descriptor over a socket
2 * Copyright (C) 2002,2005 Bruce Guenter <bruce@untroubled.org>
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) any later version.
8 *
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
13 *
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
17 */
18 #include <sys/types.h>
19 #include <errno.h>
20 #include <string.h>
21 #include "cmsg.h"
22 #include "socket.h"
23
24 /** Receive a file descriptor over a socket. */
socket_recvfd(int sock)25 int socket_recvfd(int sock)
26 {
27 #if defined(CMSG_FIRSTHDR) && defined(MSG_NOSIGNAL) && defined(SCM_RIGHTS)
28 char cbuf[CMSG_SPACE(sizeof(int))];
29 struct msghdr msg;
30 struct cmsghdr* cm;
31 int fd;
32
33 memset(&msg, 0, sizeof msg);
34 msg.msg_control = cbuf;
35 msg.msg_controllen = sizeof cbuf;
36 cm = CMSG_FIRSTHDR(&msg);
37 cm->cmsg_len = CMSG_LEN(sizeof(int));
38 cm->cmsg_level = SOL_SOCKET;
39 cm->cmsg_type = SCM_RIGHTS;
40
41 if (recvmsg(sock, &msg, MSG_NOSIGNAL) == -1) return -1;
42 memcpy(&fd, CMSG_DATA(cm), sizeof fd);
43 return fd;
44 #else
45 errno = ENOSYS;
46 return -1;
47 #endif
48 }
49