Created
November 19, 2015 22:10
-
-
Save Themaister/45f83f8bee945c9e20d8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdlib.h> | |
#include <sys/types.h> | |
#include <sys/socket.h> | |
#include <sys/wait.h> | |
#include <sys/fcntl.h> | |
#include <sys/un.h> | |
#include <stdbool.h> | |
#include <stdio.h> | |
#include <errno.h> | |
#include <stdint.h> | |
#include <unistd.h> | |
struct cmsgbuf | |
{ | |
struct cmsghdr hdr; | |
int fd; | |
}; | |
static int pull_handle(int socket) | |
{ | |
char empty; | |
struct iovec nothing = { | |
.iov_base = &empty, | |
.iov_len = 1, | |
}; | |
struct cmsgbuf msgbuf; | |
struct msghdr msg = { | |
.msg_name = NULL, | |
.msg_namelen = 0, | |
.msg_iov = ¬hing, | |
.msg_iovlen = 1, | |
.msg_flags = 0, | |
.msg_control = &msgbuf, | |
.msg_controllen = sizeof(struct cmsghdr) + sizeof(int), | |
}; | |
struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg); | |
cmsg->cmsg_len = msg.msg_controllen; | |
cmsg->cmsg_level = SOL_SOCKET; | |
cmsg->cmsg_type = SCM_RIGHTS; | |
int *dfd = (int*)CMSG_DATA(cmsg); | |
*dfd = -1; | |
fprintf(stderr, "Pulling handle ...\n"); | |
int ret = recvmsg(socket, &msg, MSG_NOSIGNAL); | |
fprintf(stderr, "Pulled handle ... %d\n", msgbuf.fd); | |
if (ret < 0) | |
return -1; | |
return msgbuf.fd; | |
} | |
int main(void) | |
{ | |
int fds[2] = { -1, -1 }; | |
int fd = -1; | |
int ret = 0; | |
if (socketpair(AF_UNIX, SOCK_STREAM, 0, fds) < 0) | |
return 1; | |
pid_t pid = fork(); | |
if (pid > 0) | |
{ | |
fd = pull_handle(fds[0]); | |
close(fds[1]); | |
if (fd < 0) | |
{ | |
ret = 1; | |
goto end; | |
} | |
char buf[1024]; | |
ssize_t len = read(fd, buf, sizeof(buf) - 1); | |
if (len < 0) | |
{ | |
ret = 1; | |
goto end; | |
} | |
buf[len] = '\0'; | |
fprintf(stderr, "%s\n", buf); | |
int stat; | |
waitpid(pid, &stat, 0); | |
} | |
else | |
{ | |
close(0); | |
dup(fds[1]); | |
close(fds[1]); | |
close(fds[0]); | |
fds[0] = -1; | |
fds[1] = -1; | |
char *argv[] = { "/tmp/test", "/tmp/grab-me", NULL }; | |
int ret = execvp("/tmp/test", argv); | |
if (ret < 0) | |
{ | |
ret = 1; | |
goto end; | |
} | |
} | |
end: | |
if (fds[0] >= 0) | |
close(fds[0]); | |
if (fds[1] >= 0) | |
close(fds[1]); | |
if (fd >= 0) | |
close(fd); | |
return ret; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment