File: recvfd.c

package info (click to toggle)
superd 0.0.3-4
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 136 kB
  • ctags: 85
  • sloc: ansic: 721; makefile: 103; sh: 27
file content (105 lines) | stat: -rw-r--r-- 2,022 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#include "recvfd.h"

#ifdef __GLIBC__

ssize_t
read_fd(int fd, void *ptr, size_t nbytes, int *recvfd)
{
	struct msghdr	msg;
	struct iovec	iov[1];
	ssize_t			n;

	union {
	  struct cmsghdr	cm;
	  char				control[CMSG_SPACE(sizeof(int))];
	} control_un;
	struct cmsghdr	*cmptr;

	msg.msg_control = control_un.control;
	msg.msg_controllen = sizeof(control_un.control);

	msg.msg_name = NULL;
	msg.msg_namelen = 0;

	iov[0].iov_base = ptr;
	iov[0].iov_len = nbytes;
	msg.msg_iov = iov;
	msg.msg_iovlen = 1;

	if ( (n = recvmsg(fd, &msg, 0)) <= 0)
		return(n);

	if ( (cmptr = CMSG_FIRSTHDR(&msg)) != NULL &&
	    cmptr->cmsg_len == CMSG_LEN(sizeof(int))) {
		if (cmptr->cmsg_level != SOL_SOCKET)
			err_quit("control level != SOL_SOCKET");
		if (cmptr->cmsg_type != SCM_RIGHTS)
			err_quit("control type != SCM_RIGHTS");
		*recvfd = *((int *) CMSG_DATA(cmptr));
	} else
		*recvfd = -1;		/* descriptor was not passed */

	return(n);
}
/* end read_fd */


/* this little wrapper is so we can consistantly use sendfd() and recvfd()
   all across the board
*/

int recvfd(int sockfd) {
  char passbuf[2];
  int incomingfd;

  read_fd(sockfd, passbuf, sizeof(passbuf), &incomingfd);

  return incomingfd;
}




#else

/* Solaris and 4.3 BSD style systems only */


int recvfd(int sockfd) {

  int truefd;    
  struct iovec iov[1];
  struct msghdr msg;
  struct pollfd udpollfd;
  
  udpollfd.events = POLLIN;
  udpollfd.fd = sockfd;
  
  iov[0].iov_base = (char *) 0;
  iov[0].iov_len = 0;
  msg.msg_iov = iov;
  msg.msg_iovlen = 1;
  msg.msg_name = NULL;
  msg.msg_namelen = 0;
  
  msg.msg_accrights = (caddr_t) &truefd;
  msg.msg_accrightslen = sizeof(truefd);   
  
  poll(&udpollfd, 1, -1);
  
  if (Recvmsg(sockfd, &msg, 0) < 0) {
    fprintf(stderr, "Recvmsg Error.\n");
    exit(-1);
  }

  if ( msg.msg_accrightslen != sizeof(truefd) ) {
    fprintf(stderr, "accrightslen is: %i\n", (int)msg.msg_accrightslen);
    fprintf(stderr, "recvsk: FD not txferred.\n");
    return -1;
  } 

  return truefd;
}          


#endif