1
/* fd passing over unix sockets */
4
* Copyright (C) 2002-2005 Novell/SUSE
5
* Copyright (C) 2010 Canonical, Ltd.
7
* This program is free software; you can redistribute it and/or
8
* modify it under the terms of the GNU General Public License as
9
* published by the Free Software Foundation, version 2 of the
13
/* this is very ugly */
15
#define _XOPEN_SOURCE 500
18
#include <sys/types.h>
21
#include <sys/socket.h>
31
int main (int argc, char * argv[]) {
32
int sock, in_sock, fd;
33
struct sockaddr_un local, remote;
34
int len, exec_now, pfd_ret;
36
char comparison_buffer[17];
37
char inbound_buffer[17];
40
struct cmsghdr *ctrl_mesg;
46
if (argc < 4 || argc > 5 || (argc == 5 && (strcmp(argv[4], "delete_file") != 0))) {
47
fprintf(stderr, "Usage: %s <file>\n", argv[0]);
51
if ((fd = open(argv[1], O_RDONLY)) < 0) {
52
fprintf(stderr, "FAIL - open failed: %s\n",
57
if (pread(fd, comparison_buffer, 16,0) <= 0) {
58
fprintf(stderr, "FAIL - read failed: %s\n",
64
if (unlink(argv[1]) == -1){
65
fprintf(stderr, "FAIL: unlink before passing fd - %s\n",
71
sock = socket(AF_UNIX, SOCK_STREAM, 0);
73
fprintf(stderr, "FAIL - socket failed: %s\n",
78
local.sun_family = AF_UNIX;
79
strcpy(local.sun_path, argv[2]);
80
unlink(local.sun_path);
81
len = strlen(local.sun_path) + sizeof(local.sun_family);
83
if (bind(sock, (struct sockaddr *) &local, len) != 0) {
84
fprintf(stderr, "FAIL - bind failed: %s\n",
89
if (listen(sock, 2) != 0) {
90
fprintf(stderr, "FAIL - listen failed: %s\n",
98
execlp(argv[3], argv[3], argv[2], NULL);
102
len2 = sizeof(remote);
106
pfd_ret = poll(&pfd, 1, 500);
108
if ((in_sock = accept(sock, (struct sockaddr*)&remote, &len2)) == -1) {
109
fprintf(stderr, "FAIL - accept: %s\n",
114
vect.iov_base = argv[2];
115
vect.iov_len = strlen(argv[2]) + 1;
117
mesg.msg_name = NULL;
118
mesg.msg_namelen = 0;
119
mesg.msg_iov = &vect;
122
ctrl_mesg = alloca(sizeof(struct cmsghdr) + sizeof(fd));
123
ctrl_mesg->cmsg_len = sizeof(struct cmsghdr) + sizeof(fd);
124
ctrl_mesg->cmsg_level = SOL_SOCKET;
125
ctrl_mesg->cmsg_type = SCM_RIGHTS;
127
memcpy(CMSG_DATA(ctrl_mesg), &fd, sizeof(fd));
128
mesg.msg_control = ctrl_mesg;
129
mesg.msg_controllen = ctrl_mesg->cmsg_len;
132
if (sendmsg(in_sock, &mesg, 0) != vect.iov_len) {
133
fprintf(stderr, "FAIL - could not sendmsg\n");
137
/* Check for info re: reading the file */
138
memset(inbound_buffer, 0, sizeof(inbound_buffer));
139
if (recv(in_sock, inbound_buffer, 16,0) == -1 ) {
140
fprintf(stderr, "FAIL - recv %s\n",
145
if (strncmp(comparison_buffer, inbound_buffer,10) != 0) {
146
fprintf(stderr, "FAIL - buffer comparison. Got \"%s\", expected \"%s\"\n", inbound_buffer, comparison_buffer);
155
fprintf(stderr, "FAIL - poll() timed out\n");