#include "apue.h"
#include <sys/socket.h>
#define CONTROLLEN CMSG_LEN(sizeof(int))
static struct cmsghdr *cmptr=NULL;
int recv_fd(int fd, uid_t *uidptr, ssize_t (*userfunc)(int, const void *, size_t))
{
int newfd, nr, status;
char *ptr;
char buf[MAXLINE];
struct iovec iov[1];
struct msghdr msg;
status=-1;
for( ; ; )
{
iov[0].iov_base=buf;
iov[0].iov_len=sizeof(buf);
msg.msg_iov=iov;
msg.msg_iovlen=1;
msg.msg_name=NULL;
msg.msg_namelen=0;
if(cmptr==NULL & (cmptr=malloc(CONTROLLEN))<0)
{
return -1;
}
msg.msg_control=cmptr;
msg.msg_controllen=CONTROLLEN;
if((nr=recvmsg(fd,&msg,0))<0)
{
err_ret("recvmsg error");
return -1;
}
else if(nr==0)
{
err_ret("connection closed by server");
return -1;
}
for(ptr=buf;ptr<&buf[nr];)
{
if(*ptr++==0)
{
if(ptr!=&buf[nr-1])
err_dump("message format error");
status=*ptr&0xFF;
if(status==0)
{
if(msg.msg_controllen!=CONTROLLEN)
{
err_dump("status = 0 buf no fd");
}
newfd=*(int *)CMSG_DATA(cmptr);
}
else
{
newfd=-status;
}
nr-=2;
}
}
if(nr>0&&(*userfunc)(STDERR_FILENO, buf, nr)!=nr)
return -1;
if(status>=0)
return newfd;
}
}
Receiving a file descriptor over a UNIX domain socket
Some UNIX domain socket implementations provide similar functionality when exchanging messages, but their interfaces differ.
FreeBSD 8.0 and Linux 3.2.0 provide support for sending credentials over UNIX domain sockets, but they do it differently. Mac OS X 10.6.8 is derived in part from FreeBSD, but has credential passing disabled. Solaris 10 doesn’t support sending credentials over UNIX domain sockets. However, it supports the ability to obtain the credentials of a process passing a file descriptor over a STREAMS pipe, although we do not discuss the details here.
With FreeBSD, credentials are transmitted as a cmsgcred structure:
#define CMGROUP_MAX 16
struct cmsgcred {
pid_t cmcred_pid; /* sender’s process ID */
uid_t cmcred_uid; /* sender’s real UID */
uid_t cmcred_euid; /* sender’s effective UID */
gid_t cmcred_gid; /* sender’s real GID */
short cmcred_ngroups; /* number of groups */
gid_t cmcred_groups[CMGROUP_MAX]; /* groups */
};
When we transmit credentials, we need to reserve space only for the cmsgcred structure. The kernel will fill in this structure for us to prevent an application from pretending to have a different identity.
On Linux, credentials are transmitted as a ucred structure:
struct ucred {
pid_t pid; /* sender’s process ID */
uid_t uid; /* sender’s user ID */
gid_t gid; /* sender’s group ID */
};
Unlike FreeBSD, Linux requires that we initialize this structure before transmission. The kernel will ensure that applications either use values that correspond to the caller or have the appropriate privilege to use other values.