ONC+ Developer's Guide

Advanced RPC Programming Techniques

This section addresses areas of occasional interest to developers using the lower level interfaces of the RPC package. The topics are:

poll() on the Server Side

This section applies only to servers running RPC in single-threaded (default) mode.

A process that services RPC requests and performs some other activity cannot always call svc_run(). If the other activity periodically updates a data structure, the process can set a SIGALRM signal before calling svc_run(). This allows the signal handler to process the data structure and return control to svc_run() when done.

A process can bypass svc_run() and access the dispatcher directly with the svc_getreqset() call. Given the file descriptors of the transport endpoints associated with the programs being waited on, the process can have its own poll() that waits on both the RPC file descriptors and its own descriptors.

Example 4-20 shows svc_run(). svc_pollset is an array of pollfd structures that is derived, through a call to __rpc_select_to_poll(), from svc_fdset(). The array can change every time any RPC library routine is called, because descriptors are constantly being opened and closed. svc_getreq_poll() is called when poll() determines that an RPC request has arrived on some RPC file descriptors.


Note -

The functions __rpc_dtbsize() and __rpc_select_to_poll() are not part of the SVID, but they are available in the libnsl library. The descriptions of these functions are included here so that you may create versions of these functions for non-Solaris implementations.


int __rpc_select_to_poll(int fdmax, fd_set *fdset,
															struct pollfd *pollset)

Given an fd_set pointer and the number of bits to check in it, this function initializes the supplied pollfd array for RPC's use. RPC polls only for input events. The number of pollfd slots that were initialized is returned.

int __rpc_dtbsize()

This function calls the getrlimit() function to determine the maximum value that the system may assign to a newly created file descriptor. The result is cached for efficiency.

For more information on the SVID routines in this section, see the rpc_svc_calls(3N) and the poll(2)man pages.


Example 4-20 svc_run() and poll()

void
svc_run()
{
	int nfds;
	int dtbsize = __rpc_dtbsize();
	int i;
	struct pollfd svc_pollset[fd_setsize];

	for (;;) {
		/*
		 * Check whether there is any server fd on which we may have
		 * to wait.
		 */
		nfds = __rpc_select_to_poll(dtbsize, &svc_fdset,
		                            svc_pollset);
		if (nfds == 0)
			break;	/* None waiting, hence quit */

		switch (i = poll(svc_pollset, nfds, -1)) {
		case -1:
			/*
			 * We ignore all errors, continuing with the assumption
			 * that it was set by the signal handlers (or any
			 * other outside event) and not caused by poll().
			 */
		case 0:
			continue;
		default:
			svc_getreq_poll(svc_pollset, i);
		}
	}
}

Broadcast RPC

When an RPC broadcast is issued, a message is sent to all rpcbind daemons on a network. An rpcbind daemon with which the requested service is registered forwards the request to the server. The main differences between broadcast RPC and normal RPC calls are:

Example 4-21 shows how rpc_broadcast() is used and describes its arguments.


Example 4-21 RPC Broadcast

/*
 * bcast.c: example of RPC broadcasting use.
 */

#include <stdio.h>
#include <rpc/rpc.h>

main(argc, argv)
	int argc;
	char *argv[];
{
	enum clnt_stat rpc_stat;
	u_long prognum, vers;
	struct rpcent *re;

	if(argc != 3) {
		fprintf(stderr, "usage : %s RPC_PROG VERSION\n", argv[0]);
		exit(1);
	}
	if (isdigit( *argv[1]))
		prognum = atoi(argv[1]);
	else {
		re = getrpcbyname(argv[1]);
		if (! re) {
			fprintf(stderr, "Unknown RPC service %s\n", argv[1]);
			exit(1);
		}
		prognum = re->r_number;
	}
	vers = atoi(argv[2]);
	rpc_stat = rpc_broadcast(prognum, vers, NULLPROC, xdr_void,
	           (char *)NULL, xdr_void, (char *)NULL, bcast_proc,
NULL);
	if ((rpc_stat != RPC_SUCCESS) && (rpc_stat != RPC_TIMEDOUT)) {
		fprintf(stderr, "broadcast failed: %s\n",
		         clnt_sperrno(rpc_stat));
		exit(1);
	}
	exit(0);
}

The function in Example 4-22 collects replies to the broadcast. Normal operation is to collect either the first reply or all replies. bcast_proc() displays the IP address of the server that has responded. Since the function returns FALSE it will continue to collect responses, and the RPC client code will continue to resend the broadcast until it times out.


Example 4-22 Collect Broadcast Replies

bool_t
bcast_proc(res, t_addr, nconf)
	void *res;									/* Nothing comes back */
	struct t_bind *t_addr;					/* Who sent us the reply */
	struct netconfig *nconf;
{
	register struct hostent *hp;
	char *naddr;

	naddr = taddr2naddr(nconf, &taddr->addr);
	if (naddr == (char *) NULL) {
		fprintf(stderr,"Responded: unknown\n");
	} else {
		fprintf(stderr,"Responded: %s\n", naddr);
		free(naddr);
	}
	return(FALSE);
}

If done is TRUE, then broadcasting stops, and rpc_broadcast() returns successfully. Otherwise, the routine waits for another response. The request is rebroadcast after a few seconds of waiting. If no responses come back, the routine returns with RPC_TIMEDOUT.

Batching

RPC is designed so that clients send a call message and wait for servers to reply to the call. This implies that a client is blocked while the server processes the call. This is inefficient when the client does not need each message acknowledged.

RPC batching lets clients process asynchronously. RPC messages can be placed in a pipeline of calls to a server. Batching requires that:

Because the server does not respond to each call, the client can send new calls in parallel with the server processing previous calls. The transport can buffer many call messages and send them to the server in one write() system call. This decreases interprocess communication overhead and the total time of a series of calls. The client should end with a nonbatched call to flush the pipeline.

Failed Cross Reference Formatshows the unbatched version of the client. It scans the character array, buf, for delimited strings and sends each string to the server.


Example 4-23 Unbatched Client

#include <stdio.h>
#include <rpc/rpc.h>
#include "windows.h"

main(argc, argv)
	int argc;
	char **argv;
{
	struct timeval total_timeout;
	register CLIENT *client;
	enum clnt_stat clnt_stat;
	char buf[1000], *s = buf;

	if ((client = clnt_create( argv[1], WINDOWPROG, WINDOWVERS,
								"circuit_v")) == (CLIENT *) NULL) {
		clnt_pcreateerror("clnt_create");
		exit(1);
	}

	total_timeout.tv_sec = 20;
	total_timeout.tv_usec = 0;
	while (scanf( "%s", s ) != EOF) {
		if (clnt_call(client, RENDERSTRING, xdr_wrapstring, &s,
		   xdr_void, (caddr_t) NULL, total_timeout) != RPC_SUCCESS) {
			clnt_perror(client, "rpc");
			exit(1);
		}
	}

	clnt_destroy( client );
	exit(0);
}

Failed Cross Reference Formatshows the batched version of the client. It does not wait after each string is sent to the server. It waits only for an ending response from the server.


Example 4-24 Batched Client

#include <stdio.h>
#include <rpc/rpc.h>
#include "windows.h"

main(argc, argv)
	int argc;
	char **argv;
{
	struct timeval total_timeout;
	register CLIENT *client;
	enum clnt_stat clnt_stat;
	char buf[1000], *s = buf;

	if ((client = clnt_create( argv[1], WINDOWPROG, WINDOWVERS,
									"circuit_v")) == (CLIENT *) NULL) {
		clnt_pcreateerror("clnt_create");
		exit(1);
	}
	timerclear(&total_timeout);
	while (scanf("%s", s) != EOF)
		clnt_call(client, RENDERSTRING_BATCHED, xdr_wrapstring,
		           &s, xdr_void, (caddr_t) NULL, total_timeout);
	/* Now flush the pipeline */
	total_timeout.tv_sec = 20;
	clnt_stat = clnt_call(client, NULLPROC, xdr_void,
	         (caddr_t) NULL, xdr_void, (caddr_t) NULL,
total_timeout);
	if (clnt_stat != RPC_SUCCESS) {
		clnt_perror(client, "rpc");
		exit(1);
	}
	clnt_destroy(client);
	exit(0);
}

Example 4-25 shows the dispatch portion of the batched server. Because the server sends no message, the clients are not notified of failures.


Example 4-25 Batched Server

#include <stdio.h>
#include <rpc/rpc.h>
#include "windows.h"

void
windowdispatch(rqstp, transp)
	struct svc_req *rqstp;
	SVCXPRT *transp;
{
	char    *s = NULL;

	switch(rqstp->rq_proc) {
		case NULLPROC:
			if (!svc_sendreply( transp, xdr_void, NULL))
				fprintf(stderr, "can't reply to RPC call\n");
			return;
		case RENDERSTRING:
			if (!svc_getargs( transp, xdr_wrapstring, &s)) {
				fprintf(stderr, "can't decode arguments\n");
				/* Tell caller an error occurred */
				svcerr_decode(transp);
				break;
			}
			/* Code here to render the string s */
			if (!svc_sendreply( transp, xdr_void, (caddr_t) NULL))
				fprintf( stderr, "can't reply to RPC call\n");
			break;
		case RENDERSTRING_BATCHED:
			if (!svc_getargs(transp, xdr_wrapstring, &s)) {
				fprintf(stderr, "can't decode arguments\n");
				/* Be silent in the face of protocol errors */
				break;
			}
			/* Code here to render string s, but send no reply! */
			break;
		default:
			svcerr_noproc(transp);
			return;
	}
	/* Now free string allocated while decoding arguments */
	svc_freeargs(transp, xdr_wrapstring, &s);
}

Batching Performance

To illustrate the benefits of batching, the examples in Failed Cross Reference Format, Failed Cross Reference Format, and Example 4-25were completed to render the lines in a 25144-line file. The rendering service simply throws the lines away. The batched version of the application was four times as fast as the unbatched version.

Authentication

In all of the preceding examples in this chapter, the caller has not identified itself to the server, and the server has not required identification of the caller. Some network services, such as a network file system, require caller identification. Refer to System Administration Guide, to implement any of the authentication methods described in this section.

Just as different transports can be used when creating RPC clients and servers, different "flavors" of authentication can be associated with RPC clients. The authentication subsystem of RPC is open ended. So, many flavors of authentication can be supported. The authentication protocols are further defined in Appendix B, RPC Protocol and Language Specification."

Sun RPC currently supports the authentication flavors shown in Failed Cross Reference Format.

Table 4-6 Authentication Methods Supported By Sun RPC

AUTH_NONE

Default. No authentication performed 

AUTH_SYS

An authentication flavor based on UNIX operating system, process permissions authentication 

AUTH_SHORT

An alternate flavor of AUTH_SYS used by some servers for efficiency. Client programs using AUTH_SYS authentication can receive AUTH_SHORT response verifiers from some servers. See Appendix B, RPC Protocol and Language Specification for details

AUTH_DES

An authentication flavor based on DES encryption techniques 

AUTH_KERB

Version 4 Kerberos authentication based on DES framework

When a caller creates a new RPC client handle as in:

clnt = clnt_create(host, prognum, versnum, nettype);

the appropriate client-creation routine sets the associated authentication handle to:

clnt->cl_auth = authnone_create();

If you create a new instance of authentication, you must destroy it with auth_destroy(clnt->cl_auth). This should be done to conserve memory.

On the server side, the RPC package passes the service-dispatch routine a request that has an arbitrary authentication style associated with it. The request handle passed to a service-dispatch routine contains the structure rq_cred. It is opaque, except for one field: the flavor of the authentication credentials.

/*
 * Authentication data
 */
struct opaque_auth {
   enum_t    oa_flavor;		/* style of credentials */
   caddr_t   oa_base;			/* address of more auth stuff */
   u_int     oa_length;		/* not to exceed MAX_AUTH_BYTES */
};

The RPC package guarantees the following to the service-dispatch routine:

AUTH_SYS Authentication

The client can use AUTH_SYS (called AUTH_UNIX in previous releases) style authentication by setting clnt->cl_auth after creating the RPC client handle:

clnt->cl_auth = authsys_create_default();

This causes each RPC call associated with clnt to carry with it the following credentials-authentication structure shown in Failed Cross Reference Format.


Example 4-26 AUTH_SYS Credential Structure

/*
 * AUTH_SYS flavor credentials.
 */
struct authsys_parms {
	u_long aup_time;					/* credentials creation time */
	char *aup_machname;				/* client's host name */
	uid_t aup_uid;						/* client's effective uid */
	gid_t aup_gid;						/* client's current group id */
	u_int aup_len;						/* element length of aup_gids*/
	gid_t *aup_gids;					/* array of groups user is in */
};

rpc.broadcast defaults to AUTH_SYS authentication.

Example 4-27 shows a server, with procedure RUSERPROC_1(), that returns the number of users on the network. As an example of authentication, it checks AUTH_SYS credentials and does not service requests from callers whose uid is 16.


Example 4-27 Authentication Server

nuser(rqstp, transp)
	struct svc_req *rqstp;
	SVCXPRT *transp;
{
	struct authsys_parms *sys_cred;
	uid_t uid;
	unsigned long nusers;

	/* NULLPROC should never be authenticated */
	if (rqstp->rq_proc == NULLPROC) {
		if (!svc_sendreply( transp, xdr_void, (caddr_t) NULL))
			fprintf(stderr, "can't reply to RPC call\n");
		return;
	}

	/* now get the uid */
	switch(rqstp->rq_cred.oa_flavor) {
		case AUTH_SYS:
			sys_cred = (struct authsys_parms *) rqstp->rq_clntcred;
			uid = sys_cred->aup_uid;
			break;
		default:
			svcerr_weakauth(transp);
			return;
	}
	switch(rqstp->rq_proc) {
		case RUSERSPROC_1:
			/* make sure caller is allowed to call this proc */
			if (uid == 16) {
				svcerr_systemerr(transp);

				return;
			}
			/*
			 * Code here to compute the number of users and assign it
			 * to the variable nusers
			 */
			if (!svc_sendreply( transp, xdr_u_long, &nusers))
				fprintf(stderr, "can't reply to RPC call\n");
			return;
		default:
			svcerr_noproc(transp);
			return;
	}
}

Note the following:

The last point underscores the relation between the RPC authentication package and the services: RPC deals only with authentication and not with an individual service's access control. The services themselves must establish access-control policies and reflect these policies as return statuses in their protocols.

AUTH_DES Authentication

Use AUTH_DES authentication for programs that require more security than AUTH_SYS provides. AUTH_SYS authentication is easy to defeat. For example, instead of using authsys_create_default(), a program can call authsys_create() and change the RPC authentication handle to give itself any desired user ID and hostname.

AUTH_DES authentication requires that keyserv() daemons are running on both the server and client hosts. The NIS or NIS+ naming service must also be running. Users on these hosts need public/secret key pairs assigned by the network administrator in the publickey() database. They must also have decrypted their secret keys with the keylogin() command (normally done by login() unless the login password and secure-RPC password differ).

To use AUTH_DES authentication, a client must set its authentication handle appropriately. For example:

cl->cl_auth = authdes_seccreate(servername, 60, server,
						       (char *)NULL);

The first argument is the network name or "netname" of the owner of the server process. Server processes are usually root processes, and you can get their netnames with the following call:

char servername[MAXNETNAMELEN];
host2netname(servername, server, (char *)NULL);

servername points to the receiving string and server is the name of the host the server process is running on. If the server process was run by a non-root user, use the call user2netname() as follows:

char servername[MAXNETNAMELEN];
user2netname(servername, serveruid(), (char *)NULL);

serveruid() is the user id of the server process. The last argument of both functions is the name of the domain that contains the server. NULL means "use the local domain name."

The second argument of authdes_seccreate() is the lifetime (known also as the window) of the client's credential, here, 60 seconds. A credential will expire 60 seconds after the client makes an RPC call. If a program tries to reuse the credential, the server RPC subsystem recognizes that it has expired and does not service the request carrying the expired credential. If any program tries to reuse a credential within its lifetime, it is rejected, because the server RPC subsystem saves credentials it has seen in the near past and does not serve duplicates.

The third argument of authdes_seccreate() is the name of the timehost used to synchronize clocks. AUTH_DES authentication requires that server and client agree on the time. The example specifies to synchronize with the server. A (char *)NULL says not to synchronize. Do this only when you are sure that the client and server are already synchronized.

The fourth argument of authdes_seccreate() points to a DES encryption key to encrypt time stamps and data. If this argument is (char *)NULL, as it is in this example, a random key is chosen. The ah_key field of the authentication handle contains the key.

The server side is simpler than the client. Example 4-28shows the server in Example 4-27 changed to use AUTH_DES.


Example 4-28 AUTH_DES Server

#include <rpc/rpc.h>
	...
	...
nuser(rqstp, transp)
	struct svc_req *rqstp;
	SVCXPRT *transp;
{
	struct authdes_cred *des_cred;
	uid_t uid;
	gid_t gid;
	int gidlen;
	gid_t gidlist[10];

	/* NULLPROC should never be authenticated */
	if (rqstp->rq_proc == NULLPROC) {
		/* same as before */
	}
	/* now get the uid */
	switch(rqstp->rq_cred.oa_flavor) {
		case AUTH_DES:
			des_cred = (struct authdes_cred *) rqstp->rq_clntcred;
			if (! netname2user( des_cred->adc_fullname.name, &uid,
			                    &gid, &gidlen, gidlist)) {
				fprintf(stderr, "unknown user: %s\n",
				         des_cred->adc_fullname.name);
				svcerr_systemerr(transp);
				return;
			}
			break;
		default:
			svcerr_weakauth(transp);
			return;
	}
	/* The rest is the same as before */

Note the routine netname2user() converts a network name (or "netname" of a user) to a local system ID. It also supplies group IDs (not used in this example).

AUTH_KERB Authentication

SunOS 5.x includes support for most client-side features of Kerberos 4.0, except klogin. AUTH_KERB is conceptually similar to AUTH_DES; the essential difference is that DES passes a network name and DES-encrypted session key, while Kerberos passes the encrypted service ticket. The other factors that affect implementation and interoperability are given in the following subsections.

For more information, see the kerberos(3N)man page and the Steiner-Neuman-Shiller paper [Steiner, Jennifer G., Neuman, Clifford, and Schiller, Jeffrey J. "Kerberos: An Authentication Service for Open Network Systems." USENIX Conference Proceedings, USENIX Association, Berkeley, CA, June 1988.] on the MIT Project Athena implementation of Kerberos. You may access MIT documentation through the FTP directory /pub/kerberos/doc on athena-dist.mit.edu, or through Mosaic, using the document URL, ftp://athena-dist.mit.edu/pub/kerberos/doc.

Time Synchronization

Kerberos uses the concept of a time window in which its credentials are valid. It does not place restrictions on the clocks of the client or server. The client is required to determine the time bias between itself and the server and compensate for the difference by adjusting the window time specified to the server. Specifically, the window is passed as an argument to authkerb_seccreate(); the window does not change. If a timehost is specified as an argument, the client side gets the time from the timehost and alters its timestamp by the difference in time. Various methods of time synchronization are available. See the kerberos_rpc(3N)man page for more information.

Well-Known Names

Kerberos users are identified by a primary name, instance, and realm. The RPC authentication code ignores the realm and instance, while the Kerberos library code does not. The assumption is that user names are the same between client and server. This enables a server to translate a primary name into user identification information. Two forms of well-known names are used (omitting the realm):

Encryption

Kerberos uses cipher block chaining (CBC) mode when sending a full name credential (one that includes the ticket and window), and electronic code book (ECB) mode otherwise. CBC and ECB are two methods of DES encryption. See the des_crypt(3) man page for more information. The session key is used as the initial input vector for CBC mode. The notation

xdr_type(object)

means that XDR is used on object as a type. The length in the next code section is the size, in bytes of the credential or verifier, rounded up to 4-byte units. The full name credential and verifier are obtained as follows:

xdr_long(timestamp.seconds)
xdr_long(timestamp.useconds)
xdr_long(window)
xdr_long(window - 1)

After encryption with CBC with input vector equal to the session key, the output is two DES cipher blocks:

CB0
CB1.low
CB1.high

The credential is:

xdr_long(AUTH_KERB)
xdr_long(length)
xdr_enum(AKN_FULLNAME)
xdr_bytes(ticket)
xdr_opaque(CB1.high)

The verifier is:

xdr_long(AUTH_KERB)
xdr_long(length)
xdr_opaque(CB0)
xdr_opaque(CB1.low)

The nickname exchange yields:

xdr_long(timestamp.seconds)
xdr_long(timestamp.useconds)

The nickname is encrypted with ECB to obtain ECB0, and the credential is:

xdr_long(AUTH_KERB)
xdr_long(length)
xdr_enum(AKN_NICKNAME)
xdr_opaque(akc_nickname)

The verifier is:

xdr_long(AUTH_KERB)
xdr_long(length)
xdr_opaque(ECB0)
xdr_opaque(0)

Using Port Monitors

RPC servers can be started by port monitors such as inetd and listen. Port monitors listen for requests and spawn servers in response. The forked server process is passed file descriptor 0 on which the request has been accepted. For inetd, when the server is done, it may exit immediately or wait a given interval for another service request.

For listen, servers should exit immediately after replying because listen() always spawns a new process. The following function call creates a SVCXPRT handle to be used by the services started by port monitors:

transp = svc_tli_create(0, nconf, (struct t_bind *)NULL, 0, 0)

nconf is the netconfig structure of the transport from which the request is received.

Because the port monitors have already registered the service with rpcbind, there is no need for the service to register with rpcbind. But it must call svc_reg() to register the service procedure:

svc_reg(transp, PROGNUM, VERSNUM, dispatch,(struct netconfig *)NULL)

The netconfig structure here is NULL to prevent svc_reg() from registering the service with rpcbind.


Note -

Study rpcgen-generated server stubs to see the sequence in which these routines are called.


For connection-oriented transports, the following routine provides a lower level interface:

transp = svc_fd_create(0, recvsize, sendsize);

A 0 file descriptor is the first argument. You can set the value of recvsize and sendsize to any appropriate buffer size. A 0 for either argument causes a system default size to be chosen. Application servers that do not do any listening of their own use svc_fd_create().

Using inetd

Entries in /etc/inet/inetd.conf have different formats for socket-based, TLI-based, and RPC services. The format of inetd.conf entries for RPC services is:

rpc_prog/vers endpoint_type rpc/proto flags user pathname args
where: 
Table 4-7 RPC inetd Services

rpc_prog/vers

The name of an RPC program followed by a / and the version number or a range of version numbers. 

endpoint_type 

One of dgram (for connectionless sockets), stream (for connection mode sockets), or tli (for TLI endpoints).

proto 

May be * (for all supported transports), a nettype, a netid, or a comma separated list of nettype and netid. 

flags 

Either wait or nowait.

user 

Must exist in the effective passwd database. 

athname

Full path name of the server daemon. 

args 

Arguments to be passed to the daemon on invocation. 

For example:

rquotad/1 tli rpc/udp wait root /usr/lib/nfs/rquotad rquotad

For more information, see the inetd.conf(4) man page.

Using the Listener

Use pmadm to add RPC services:

pmadm -a -p pm_tag -s svctag -i id -v vers \

 	-m `nlsadmin -c command -D -R prog:vers`

The arguments are: -a means to add a service, -p pm_tag specifies a tag associated with the port monitor providing access to the service, -s svctag is the server's identifying code, -i id is the /etc/passwd user name assigned to service svctag, -v ver is the version number for the port monitor's data base file, and -m specifies the nlsadmin command to invoke the service. nlsadmin can have additional arguments. For example, to add version 1 of a remote program server named rusersd, a pmadm command is:

# pmadm -a -p tcp -s rusers -i root -v 4 \
   -m `nlsadmin -c /usr/sbin/rpc.ruserd -D -R 100002:1`

The command is given root permissions, installed in version 4 of the listener data base file, and is made available over TCP transports. Because of the complexity of the arguments and options to pmadm, use a command script or the menu system to add RPC services. To use the menu system, enter sysadm ports and choose the -port_services option.

After adding a service, the listener must be re-initialized before the service is available. To do this, stop and restart the listener, as follows (note that rpcbind must be running):

# sacadm -k -p pmtag
# sacadm -s -p pmtag

For more information, such as how to set up the listener process, see the listen(1M), pmadm(1M), sacadm(1M) and sysadm(1M) man pages and the TCP/IP and Data Communications Administration Guide.

Multiple Server Versions

By convention, the first version number of a program, PROG, is named PROGVERS_ORIG and the most recent version is named PROGVERS. Program version numbers must be assigned consecutively. Leaving a gap in the program version sequence can cause the search algorithm to not find a matching program version number that is defined.

Version numbers should never be changed by anyone other than the owner of a program. Adding a version number to a program that you do not own can cause severe problems when the owner increments the version number. Sun registers version numbers and answers questions about them (rpc@Sun.com).

Suppose a new version of the ruser program returns an unsigned short rather than a long. If you name this version RUSERSVERS_SHORT, a server that wants to support both versions would do a double register. The same server handle is used for both registrations.


Example 4-29 Server Handle for Two Versions of Single Routine

if (!svc_reg(transp, RUSERSPROG, RUSERSVERS_ORIG, 
						nuser, nconf))
{
	fprintf(stderr, "can't register RUSER service\n");
	exit(1);
}
if (!svc_reg(transp, RUSERSPROG, RUSERSVERS_SHORT, nuser,
						nconf)) {
	fprintf(stderr, "can't register RUSER service\n");
	exit(1);
}

Both versions can be performed by a single procedure.


Example 4-30 Procedure for Two Versions of Single Routine

void
nuser(rqstp, transp)
	struct svc_req *rqstp;
	SVCXPRT *transp;
{
	unsigned long nusers;
	unsigned short nusers2;
	switch(rqstp->rq_proc) {
		case NULLPROC:
			if (!svc_sendreply( transp, xdr_void, 0))
				fprintf(stderr, "can't reply to RPC call\n");
			return;
		case RUSERSPROC_NUM:
			/*
			 * Code here to compute the number of users
			 * and assign it to the variable nusers
			 */
		switch(rqstp->rq_vers) {
			case RUSERSVERS_ORIG:
				if (! svc_sendreply( transp, xdr_u_long, &nusers))
					fprintf(stderr, "can't reply to RPC call\n");
				break;
			case RUSERSVERS_SHORT:
				nusers2 = nusers;
				if (! svc_sendreply( transp, xdr_u_short, &nusers2))
					fprintf(stderr, "can't reply to RPC call\n");
				break;
		}
		default:
			svcerr_noproc(transp);
			return;
	}
	return;
}

Multiple Client Versions

Since different hosts may run different versions of RPC servers, a client should be capable of accommodating the variations. For example, one server may run the old version of RUSERSPROG(RUSERSVERS_ORIG) while another server runs the newer version (RUSERSVERS_SHORT).

If the version on a server does not match the version number in the client creation call, clnt_call() fails with an RPCPROGVERSMISMATCH error. You can get the version numbers supported by a server and then create a client handle with the appropriate version number. Use either the routine in Example 4-31, or clnt_create_vers(). See the rpc(3N)man page for more details.


Example 4-31 RPC Versions on Client Side

main()
{
	enum clnt_stat status;
	u_short num_s;
	u_int num_l;
	struct rpc_err rpcerr;
	int maxvers, minvers;
	CLIENT *clnt;

	clnt = clnt_create("remote", RUSERSPROG, RUSERSVERS_SHORT,
			             "datagram_v");
	if (clnt == (CLIENT *) NULL) {
		clnt_pcreateerror("unable to create client handle");
		exit(1);
	}
	to.tv_sec = 10;							/* set the time outs */
	to.tv_usec = 0;

	status = clnt_call(clnt, RUSERSPROC_NUM, xdr_void,
	                  (caddr_t) NULL, xdr_u_short, 
                  (caddr_t)&num_s, to);
	if (status == RPC_SUCCESS) {			/* Found latest version number */
		printf("num = %d\n", num_s);
		exit(0);
	}
	if (status != RPC_PROGVERSMISMATCH) {		/* Some other error */
		clnt_perror(clnt, "rusers");
		exit(1);
	}
	/* This version not supported */
	clnt_geterr(clnt, &rpcerr);
	maxvers = rpcerr.re_vers.high;		/* highest version supported */
	minvers = rpcerr.re_vers.low;		/*lowest version supported */
	if (RUSERSVERS_SHORT < minvers || RUSERSVERS_SHORT > maxvers)
{
			                       /* doesn't meet minimum standards */
		clnt_perror(clnt, "version mismatch");
		exit(1);
	}
	(void) clnt_control(clnt, CLSET_VERSION, RUSERSVERS_ORIG);
	status = clnt_call(clnt, RUSERSPROC_NUM, xdr_void,
			 (caddr_t) NULL, xdr_u_long, (caddr_t)&num_l, to);
	if (status == RPC_SUCCESS)
			               /* We found a version number we recognize */
		printf("num = %d\n", num_l);
	else {
		clnt_perror(clnt, "rusers");
		exit(1);
	}
}

Using Transient RPC Program Numbers

Occasionally, it is useful for an application to use RPC program numbers that are generated dynamically. This could be used for implementing callback procedures, for example. In the callback example, a client program typically registers an RPC service using a dynamically generated, or transient, RPC program number and passes this on to a server along with a request. The server will then call back the client program using the transient RPC program number in order to supply the results. Such a mechanism may be necessary if processing the client's request will take a huge amount of time and the client cannot block (assuming it is single-threaded); in this case, the server will acknowledge the client's request, and call back later with the results. Another use of callbacks is to generate periodic reports from a server; the client makes an RPC call to start the reporting, and the server periodically calls back the client with reports using the transient RPC program number supplied by the client program.

Dynamically generated, or transient, RPC program numbers are in the transient range, 0x40000000 - 0x5fffffff. The following routine creates a service based on a transient RPC program for a given transport type. The service handle and the transient rpc program number are returned. The caller supplies the service dispatch routine, the version, and the transport type.


Example 4-32 Transient RPC Program--Server Side

SVCXPRT *register_transient_prog(dispatch, program, version, netid)
	void (*dispatch)(); /* service dispatch routine */
	u_long *program;    /* returned transient RPC number */
	u_long version;     /* program version */
	char *netid;        /* transport id */
{
	SVCXPRT  *transp;
	struct netconfig *nconf;
	u_long prognum;
	if ((nconf = getnetconfigent(netid)) == (struct netconfig
*)NULL)
		return ((SVCXPRT *)NULL);
	if ((transp = svc_tli_create(RPC_ANYFD, nconf,
				(struct t_bind *)NULL, 0, 0)) == (SVCXPRT *)NULL) {
		freenetconfigent(nconf);
		return ((SVCXPRT *)NULL);
	}
	prognum = 0x40000000;
	while (prognum < 0x60000000 && svc_reg(transp, prognum,
version,
									dispatch, nconf) == 0) {
		prognum++;
	}
	freenetconfigent(nconf);
	if (prognum >= 0x60000000) {
		svc_destroy(transp);
		return ((SVCXPRT *)NULL);
	}
	*program = prognum;
	return (transp);
}