chiark / gitweb /
fishdescriptor: Copy fd passing C sender code from libxl
[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 Lesser General Public License as published
7  * by the Free Software Foundation; version 2.1 only. with the special
8  * exception on linking described in file LICENSE.
9  */
10
11 int libxl__sendmsg_fds(libxl__gc *gc, int carrier,
12                        const void *data, size_t datalen,
13                        int nfds, const int fds[], const char *what) {
14     struct msghdr msg = { 0 };
15     struct cmsghdr *cmsg;
16     size_t spaceneeded = nfds * sizeof(fds[0]);
17     char control[CMSG_SPACE(spaceneeded)];
18     struct iovec iov;
19     int r;
20
21     iov.iov_base = (void*)data;
22     iov.iov_len  = datalen;
23
24     /* compose the message */
25     msg.msg_iov = &iov;
26     msg.msg_iovlen = 1;
27     msg.msg_control = control;
28     msg.msg_controllen = sizeof(control);
29
30     /* attach open fd */
31     cmsg = CMSG_FIRSTHDR(&msg);
32     cmsg->cmsg_level = SOL_SOCKET;
33     cmsg->cmsg_type = SCM_RIGHTS;
34     cmsg->cmsg_len = CMSG_LEN(spaceneeded);
35     memcpy(CMSG_DATA(cmsg), fds, spaceneeded);
36
37     msg.msg_controllen = cmsg->cmsg_len;
38
39     r = sendmsg(carrier, &msg, 0);
40     if (r < 0) {
41         LOGE(ERROR, "failed to send fd-carrying message (%s)", what);
42         return ERROR_FAIL;
43     }
44
45     return 0;
46 }