Programmation Avancée en C


flightoffd.c

00001 /*********************************************************************
00002  *             This file is a part of True Nyms.                     *
00003  *            See the LICENSE file for copyright.                    *
00004  *********************************************************************/
00005 
00006 #include <sys/types.h>
00007 #include <sys/socket.h>
00008 #include <sys/uio.h>
00009 #include <stdio.h>
00010 #include <stdlib.h>
00011 #include <string.h>
00012 #include <errno.h>
00013 
00014 /** sock doit être une socket Unix. */
00015 int retrievefd(int sock) {
00016         int fd = -1;
00017         unsigned char* databuf[1] = {0};
00018 
00019         struct iovec vec = {0};
00020         vec.iov_base = databuf;
00021         vec.iov_len = 1;
00022 
00023         struct msghdr msg = {0};
00024         char buf[CMSG_SPACE(sizeof fd)];  /* Ancillary data buffer. */
00025         msg.msg_name = NULL;
00026         msg.msg_namelen = 0;
00027         msg.msg_iov = &vec;
00028         msg.msg_iovlen = 1;
00029         msg.msg_control = buf;
00030         msg.msg_controllen = sizeof buf;
00031 
00032         int err = recvmsg(sock, &msg, 0);
00033         if (err < 0) {
00034                 fprintf(stderr, "retrievefd: recvmsg: %s", strerror(errno));
00035                 exit(1);
00036         }
00037 
00038         struct cmsghdr *cmsg;
00039         cmsg = CMSG_FIRSTHDR(&msg);
00040         if (cmsg == NULL || cmsg->cmsg_type != SCM_RIGHTS) {
00041                 return -1;
00042         }
00043         int *fdptr = (int *)CMSG_DATA(cmsg);
00044         fd = *fdptr;
00045 
00046         return fd;
00047 }
00048 
00049 /** sock doit être une socket Unix. */
00050 int sendfd(int sock, int fd) {
00051         struct msghdr msg = {0};
00052         struct cmsghdr *cmsg;
00053 
00054         char buf[CMSG_SPACE(fd)];  /* Ancillary data buffer. */
00055         int *fdptr;
00056 
00057         unsigned char databuf[1] = {0};
00058         struct iovec vec = {0};
00059         vec.iov_base = databuf;
00060         vec.iov_len = 1;
00061 
00062         databuf[0] = (unsigned char) 1;
00063 
00064         msg.msg_control = buf;
00065         msg.msg_controllen = sizeof(buf);
00066         msg.msg_iov = &vec;
00067         msg.msg_iovlen = 1;
00068         cmsg = CMSG_FIRSTHDR(&msg);
00069         cmsg->cmsg_level = SOL_SOCKET;
00070         cmsg->cmsg_type = SCM_RIGHTS;
00071         cmsg->cmsg_len = CMSG_LEN(sizeof(int));
00072         fdptr = (int *)CMSG_DATA(cmsg);
00073         *fdptr = fd;
00074         msg.msg_controllen = cmsg->cmsg_len;
00075 
00076         int err = sendmsg(sock, &msg, 0);
00077         if (err < 0) {
00078                 fprintf(stderr, "sendmsg: %s", strerror(errno));
00079                 return -1;
00080         }
00081         return 0;
00082 }
00083 
00084 
00085 int
00086 main()
00087 {
00088         return 0;
00089 }