Lc Listing 174 recvcredcThe recvcredc source module

10 11 12

18 19

* Send a file descriptor */

#include "common.h"

* Receive Data & Credentials:

* ARGUMENTS:

s Socket to read from credp Ptr to receiving area for cred. buf Ptr to receiving buffer for data bufsiz Maximum # of bytes for buffer addr Ptr to buffer to receive peer address (or NULL) alen Ptr to Maximum byte length (updated with actual length upon return.)

26: * The value -1 is returned with errno set

27: * to ENOENT, if data is returned without

28: * any credentials.

30: int

31: recv_cred(

33: struct ucred *credp, /* Credential buffer */

37: socklen_t *alen) { /* Ptr to addr length */ 38:

40: struct msghdr msgh; /* Message header */

42: struct cmsghdr *cmsgp = NULL;

43: char mbuf[CMSG_SPACE(sizeof *credp)]; 44:

46: * Zero out message areas:

48: memset(&msgh,0,sizeof msgh);

49: memset(mbuf,0,sizeof mbuf); 50:

52: * Establish datagram address (if any):

64: * Initialize our 1 I/O element vector:

70: * Initialize control structure:

72: msgh.msg_control = mbuf;

73: msgh.msg_controllen = sizeof mbuf;

76: * Receive a message:

86: * If ptr alen is non-NULL, return the

87: * returned address length (datagrams):

93: * Walk the list of control messages:

100: && cmsgp->cmsg_type == SCM_CREDENTIALS ) {

101:

103: * Pass back credentials struct:

107:

113: * There were no credentials found. An error

114: * is returned here, since this application

115: * insists on getting credentials.

117: errno = ENOENT;

Copyright © Macmillan Computer Publishing, Inc.

The highlights of this source module are as follows:

• The arguments used by the function recv_cred() are described in the program comments in lines 11 to 19.

• Lines 39 to 43 define the various variables and control structures needed.

• The function body is defined in lines 44 to 119.

The general procedure used by the recv_cred() function is as follows:

1. Lines 48 to 73 perform all of the initialization required in preparation for the recvmsg(2) function call.

2. Lines 78 to 83 accomplish the read function by calling upon recvmsg(2). This function reads both data and ancillary data at the same time.

3. Lines 92 to 110 extract the user credentials from the ancillary data. If the credentials are found, the number of data bytes received is returned in line 108.

4. When no credentials are received, this recv_cred() function returns -1 with errno set to ENOENT (lines 112 to 118). This tells the calling program that no user credentials were returned.

The struct ucred used in line 33 of Listing 17.4 is not portable to all UNIX platforms. For example, FreeBSD uses the struct cmsgcred instead.

Was this article helpful?

0 0

Post a comment