chiark / gitweb /
60ca2666379bfaed7e52d1c38411349905057638
[chiark-utils.git] / fishdescriptor / donate.c
1 /*
2  * Copyright (C) 2009 Citrix Ltd.
3  * Copyright (C) 2017 Citrix Ltd.
4  *
5  *  This program is free software: you can redistribute it and/or modify
6  *  it under the terms of the GNU General Public License as published by
7  *  the Free Software Foundation, either version 3 of the License, or
8  *  (at your option) any later version.
9  *
10  *  This program is distributed in the hope that it will be useful,
11  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  *  GNU General Public License for more details.
14  *
15  *  You should have received a copy of the GNU General Public License
16  *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
17  */
18
19 /* return conventions: functions here return errno values */
20
21 static int fishdescriptor_sendmsg_fds(int carrier,
22                                       int nfds, const int fds[]) {
23   struct msghdr msg = { 0 };
24   struct cmsghdr *cmsg;
25   size_t spaceneeded = nfds * sizeof(fds[0]);
26   char control[CMSG_SPACE(spaceneeded)];
27   struct iovec iov;
28   int r;
29
30   iov.iov_base = &nfds;
31   iov.iov_len  = sizeof(nfds);
32
33   /* compose the message */
34   msg.msg_iov = &iov;
35   msg.msg_iovlen = 1;
36   msg.msg_control = control;
37   msg.msg_controllen = sizeof(control);
38
39   /* attach open fd */
40   cmsg = CMSG_FIRSTHDR(&msg);
41   cmsg->cmsg_level = SOL_SOCKET;
42   cmsg->cmsg_type = SCM_RIGHTS;
43   cmsg->cmsg_len = CMSG_LEN(spaceneeded);
44   memcpy(CMSG_DATA(cmsg), fds, spaceneeded);
45
46   msg.msg_controllen = cmsg->cmsg_len;
47     
48   r = sendmsg(carrier, &msg, 0);
49   if (r < 0)
50     return 0;
51 }