swc

Unnamed repository; edit this file 'description' to name the repository.
git clone git://git.nihaljere.xyz/swc
Log | Files | Refs | README | LICENSE

protocol.c (1385B)


      1 #include "protocol.h"
      2 
      3 #include <sys/socket.h>
      4 #include <stdio.h>
      5 #include <string.h>
      6 
      7 ssize_t
      8 send_fd(int socket, int fd, struct iovec *iov, int iovlen)
      9 {
     10 	char control[CMSG_SPACE(sizeof(fd))];
     11 	struct msghdr message = {
     12 		.msg_name = NULL,
     13 		.msg_namelen = 0,
     14 		.msg_iov = iov,
     15 		.msg_iovlen = iovlen,
     16 	};
     17 	struct cmsghdr *cmsg;
     18 
     19 	if (fd != -1) {
     20 		message.msg_control = control,
     21 		message.msg_controllen = sizeof(control);
     22 
     23 		cmsg = CMSG_FIRSTHDR(&message);
     24 		cmsg->cmsg_len = CMSG_LEN(sizeof(fd));
     25 		cmsg->cmsg_level = SOL_SOCKET;
     26 		cmsg->cmsg_type = SCM_RIGHTS;
     27 
     28 		memcpy(CMSG_DATA(cmsg), &fd, sizeof(fd));
     29 	} else {
     30 		message.msg_control = NULL;
     31 		message.msg_controllen = 0;
     32 	}
     33 
     34 	return sendmsg(socket, &message, 0);
     35 }
     36 
     37 ssize_t
     38 receive_fd(int socket, int *fd, struct iovec *iov, int iovlen)
     39 {
     40 	ssize_t size;
     41 	char control[CMSG_SPACE(sizeof(*fd))];
     42 	struct msghdr message = {
     43 		.msg_name = NULL,
     44 		.msg_namelen = 0,
     45 		.msg_iov = iov,
     46 		.msg_iovlen = iovlen,
     47 	};
     48 	struct cmsghdr *cmsg;
     49 
     50 	if (fd) {
     51 		*fd = -1;
     52 		message.msg_control = &control;
     53 		message.msg_controllen = sizeof(control);
     54 	}
     55 
     56 	size = recvmsg(socket, &message, 0);
     57 	if (size < 0)
     58 		return -1;
     59 
     60 	cmsg = CMSG_FIRSTHDR(&message);
     61 	if (fd && cmsg && cmsg->cmsg_len == CMSG_LEN(sizeof(*fd)) && cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS)
     62 		memcpy(fd, CMSG_DATA(cmsg), sizeof(*fd));
     63 
     64 	return size;
     65 }