1
2
3
4
5
6
7
8
9
10
11
12
13#include "qemu/osdep.h"
14#include <sys/socket.h>
15#include <sys/un.h>
16
17
18
19
20
21
22
23static int send_fd(int fd, int fd_to_send)
24{
25 struct msghdr msg;
26 struct iovec iov[1];
27 int ret;
28 char control[CMSG_SPACE(sizeof(int))];
29 struct cmsghdr *cmsg;
30
31 memset(&msg, 0, sizeof(msg));
32 memset(control, 0, sizeof(control));
33
34
35 iov[0].iov_base = (void *)" ";
36 iov[0].iov_len = 1;
37
38 msg.msg_iov = iov;
39 msg.msg_iovlen = 1;
40
41 msg.msg_control = control;
42 msg.msg_controllen = sizeof(control);
43
44 cmsg = CMSG_FIRSTHDR(&msg);
45
46 cmsg->cmsg_len = CMSG_LEN(sizeof(int));
47 cmsg->cmsg_level = SOL_SOCKET;
48 cmsg->cmsg_type = SCM_RIGHTS;
49 memcpy(CMSG_DATA(cmsg), &fd_to_send, sizeof(int));
50
51 do {
52 ret = sendmsg(fd, &msg, 0);
53 } while (ret < 0 && errno == EINTR);
54
55 if (ret < 0) {
56 fprintf(stderr, "Failed to send msg, reason: %s\n", strerror(errno));
57 }
58
59 return ret;
60}
61
62
63static int get_fd_num(const char *fd_str)
64{
65 int sock;
66 char *err;
67
68 errno = 0;
69 sock = strtol(fd_str, &err, 10);
70 if (errno) {
71 fprintf(stderr, "Failed in strtol for socket fd, reason: %s\n",
72 strerror(errno));
73 return -1;
74 }
75 if (!*fd_str || *err || sock < 0) {
76 fprintf(stderr, "bad numerical value for socket fd '%s'\n", fd_str);
77 return -1;
78 }
79
80 return sock;
81}
82
83
84
85
86
87
88int main(int argc, char **argv, char **envp)
89{
90 int sock, fd, ret;
91
92#ifdef SOCKET_SCM_DEBUG
93 int i;
94 for (i = 0; i < argc; i++) {
95 fprintf(stderr, "Parameter %d: %s\n", i, argv[i]);
96 }
97#endif
98
99 if (argc != 3) {
100 fprintf(stderr,
101 "Usage: %s < socket-fd > < file-path >\n",
102 argv[0]);
103 return EXIT_FAILURE;
104 }
105
106
107 sock = get_fd_num(argv[1]);
108 if (sock < 0) {
109 return EXIT_FAILURE;
110 }
111
112
113
114
115 fd = open(argv[2], O_RDONLY);
116 if (fd < 0) {
117 fprintf(stderr, "Failed to open file '%s'\n", argv[2]);
118 return EXIT_FAILURE;
119 }
120
121 ret = send_fd(sock, fd);
122 if (ret < 0) {
123 close(fd);
124 return EXIT_FAILURE;
125 }
126
127 close(fd);
128 return EXIT_SUCCESS;
129}
130