v13i089: Sun RPC, release 3.9, Part12/15

Rich Salz rsalz at bbn.com
Fri Mar 4 04:43:46 AEST 1988


Submitted-by: Stephen X. Nahm <sxn at Sun.COM>
Posting-number: Volume 13, Issue 89
Archive-name: rpc3.9/part12

#! /bin/sh
# This is a shell archive. To extract, remove the header and type "sh filename"
#
cd doc
echo x - rpc.rfc.ms
sed -e 's/^X//' > rpc.rfc.ms <<'Funky_Stuff'
X.\" @(#)rpc.rfc.ms	1.2 87/11/09 3.9 RPCSRC
X.de BT
X.if \\n%=1 .tl ''- % -''
X..
X.ND
X.\" prevent excess underlining in nroff
X.if n .fp 2 R
X.OH 'Remote Procedure Calls: Protocol Specification''Page %'
X.EH 'Page %''Remote Procedure Calls: Protocol Specification'
X.if \\n%=1 .bp
X.SH
\&Remote Procedure Calls: Protocol Specification
X.LP
X.NH 0
\&Status of this Memo
X.LP
Note: This chapter specifies a protocol that Sun Microsystems, Inc.,
and others are using.  It has been submitted to the ARPA-Internet
for consideration as an RFC.  \fBCertain details may change as a result
of comments made during the review of this draft standard.\fP  
X.LP
X.NH 1
\&Introduction
X.LP
This chapter specifies  a  message protocol  used in implementing
Sun's Remote Procedure Call (RPC) package.  (The message protocol is
specified with the eXternal Data Representation (XDR) language.
See the
\fIeXternal Data Representation Standard\fP
for the details.  Here, we assume that  the  reader is familiar  
with XDR and do not attempt to justify RPC or  its uses).  The paper
by Birrell and Nelson [1]  is recommended as an  excellent background
to  and justification of RPC.
X.NH 2
\&Terminology
X.LP
This chapter discusses servers, services, programs, procedures,
clients, and versions.  A server is a piece of software where network
services are implemented.  A network service is a collection of one
or more remote programs.  A remote program implements one or more
remote procedures; the procedures, their parameters, and results are
documented in the specific program's protocol specification (see the
\fIPort Mapper Program Protocol\fP\, below, for an example).  Network
clients are pieces of software that initiate remote procedure calls
to services.  A server may support more than one version of a remote
program in order to be forward compatible with changing protocols.
X.LP
For example, a network file service may be composed of two programs.
One program may deal with high-level applications such as file system
access control and locking.  The other may deal with low-level file
IO and have procedures like "read" and "write".  A client machine of
the network file service would call the procedures associated with
the two programs of the service on behalf of some user on the client
machine.
X.NH 2
\&The RPC Model
X.LP
The remote procedure call model is similar to the local procedure
call model.  In the local case, the caller places arguments to a
procedure in some well-specified location (such as a result
register).  It then transfers control to the procedure, and
eventually gains back control.  At that point, the results of the
procedure are extracted from the well-specified location, and the
caller continues execution.
X.LP
The remote procedure call is similar, in that one thread of control
logically winds through two processes\(emone is the caller's process,
the other is a server's process.  That is, the caller process sends a
call message to the server process and waits (blocks) for a reply
message.  The call message contains the procedure's parameters, among
other things.  The reply message contains the procedure's results,
among other things.  Once the reply message is received, the results
of the procedure are extracted, and caller's execution is resumed.
X.LP
On the server side, a process is dormant awaiting the arrival of a
call message.  When one arrives, the server process extracts the
procedure's parameters, computes the results, sends a reply message,
and then awaits the next call message.
X.LP
Note that in this model, only one of the two processes is active at
any given time.  However, this model is only given as an example.
The RPC protocol makes no restrictions on the concurrency model
implemented, and others are possible.  For example, an implementation
may choose to have RPC calls be asynchronous, so that the client may
do useful work while waiting for the reply from the server.  Another
possibility is to have the server create a task to process an
incoming request, so that the server can be free to receive other
requests.
X.NH 2
\&Transports and Semantics
X.LP
The RPC protocol is independent of transport protocols.  That is, RPC
does not care how a message is passed from one process to another.
The protocol deals only with specification and interpretation of
messages.
X.LP
It is important to point out that RPC does not try to implement any
kind of reliability and that the application must be aware of the
type of transport protocol underneath RPC.  If it knows it is running
on top of a reliable transport such as TCP/IP[6], then most of the
work is already done for it.  On the other hand, if it is running on
top of an unreliable transport such as UDP/IP[7], it must implement
is own retransmission and time-out policy as the RPC layer does not
provide this service.
X.LP
Because of transport independence, the RPC protocol does not attach
specific semantics to the remote procedures or their execution.
Semantics can be inferred from (but should be explicitly specified
by) the underlying transport protocol.  For example, consider RPC
running on top of an unreliable transport such as UDP/IP.  If an
application retransmits RPC messages after short time-outs, the only
thing it can infer if it receives no reply is that the procedure was
executed zero or more times.  If it does receive a reply, then it can
infer that the procedure was executed at least once.
X.LP
A server may wish to remember previously granted requests from a
client and not regrant them in order to insure some degree of
execute-at-most-once semantics.  A server can do this by taking
advantage of the transaction ID that is packaged with every RPC
request.  The main use of this transaction is by the client RPC layer
in matching replies to requests.  However, a client application may
choose to reuse its previous transaction ID when retransmitting a
request.  The server application, knowing this fact, may choose to
remember this ID after granting a request and not regrant requests
with the same ID in order to achieve some degree of
execute-at-most-once semantics.  The server is not allowed to examine
this ID in any other way except as a test for equality.
X.LP
On the other hand, if using a reliable transport such as TCP/IP, the
application can infer from a reply message that the procedure was
executed exactly once, but if it receives no reply message, it cannot
assume the remote procedure was not executed.  Note that even if a
connection-oriented protocol like TCP is used, an application still
needs time-outs and reconnection to handle server crashes.
X.LP
There are other possibilities for transports besides datagram- or
connection-oriented protocols.  For example, a request-reply protocol
such as VMTP[2] is perhaps the most natural transport for RPC.
X.SH
X.I
NOTE:  At Sun, RPC is currently implemented on top of both TCP/IP
and UDP/IP transports.
X.LP
X.NH 2
\&Binding and Rendezvous Independence
X.LP
The act of binding a client to a service is NOT part of the remote
procedure call specification.  This important and necessary function
is left up to some higher-level software.  (The software may use RPC
itself\(emsee the \fIPort Mapper Program Protocol\fP\, below).
X.LP
Implementors should think of the RPC protocol as the jump-subroutine
instruction ("JSR") of a network; the loader (binder) makes JSR
useful, and the loader itself uses JSR to accomplish its task.
Likewise, the network makes RPC useful, using RPC to accomplish this
task.
X.NH 2
\&Authentication
X.LP
The RPC protocol provides the fields necessary for a client to
identify itself to a service and vice-versa.  Security and access
control mechanisms can be built on top of the message authentication.
Several different authentication protocols can be supported.  A field
in the RPC header indicates which protocol is being used.  More
information on specific authentication protocols can be found in the
\fIAuthentication Protocols\fP\,
below.
X.KS
X.NH 1
\&RPC Protocol Requirements
X.LP
The RPC protocol must provide for the following:
X.IP  1.
Unique specification of a procedure to be called.
X.IP  2.
Provisions for matching response messages to request messages.
X.KE
X.IP  3.
Provisions for authenticating the caller to service and vice-versa.
X.LP
Besides these requirements, features that detect the following are
worth supporting because of protocol roll-over errors, implementation
bugs, user error, and network administration:
X.IP  1.
RPC protocol mismatches.
X.IP  2.
Remote program protocol version mismatches.
X.IP  3.
Protocol errors (such as misspecification of a procedure's parameters).
X.IP  4.
Reasons why remote authentication failed.
X.IP  5.
Any other reasons why the desired procedure was not called.
X.NH 2
\&Programs and Procedures
X.LP
The RPC call message has three unsigned fields:  remote program
number, remote program version number, and remote procedure number.
The three fields uniquely identify the procedure to be called.
Program numbers are administered by some central authority (like
Sun).  Once an implementor has a program number, he can implement his
remote program; the first implementation would most likely have the
version number of 1.  Because most new protocols evolve into better,
stable, and mature protocols, a version field of the call message
identifies which version of the protocol the caller is using.
Version numbers make speaking old and new protocols through the same
server process possible.
X.LP
The procedure number identifies the procedure to be called.  These
numbers are documented in the specific program's protocol
specification.  For example, a file service's protocol specification
may state that its procedure number 5 is "read" and procedure number
12 is "write".
X.LP
Just as remote program protocols may change over several versions,
the actual RPC message protocol could also change.  Therefore, the
call message also has in it the RPC version number, which is always
equal to two for the version of RPC described here.
X.LP
The reply message to a request  message  has enough  information to
distinguish the following error conditions:
X.IP  1.
The remote implementation of RPC does speak protocol version 2.
The lowest and highest supported RPC version numbers are returned.
X.IP  2.
The remote program is not available on the remote system.
X.IP  3.
The remote program does not support the requested version number.
The lowest and highest supported remote program version numbers are
returned.
X.IP  4.
The requested procedure number does not exist.  (This is usually a
caller side protocol or programming error.)
X.IP  5.
The parameters to the remote procedure appear to be garbage from the
server's point of view.  (Again, this is usually caused by a
disagreement about the protocol between client and service.)
X.NH 2
\&Authentication
X.LP
Provisions for authentication of caller to service and vice-versa are
provided as a part of the RPC protocol.  The call message has two
authentication fields, the credentials and verifier.  The reply
message has one authentication field, the response verifier.  The RPC
protocol specification defines all three fields to be the following
opaque type:
X.DS
X.ft CW
X.vs 11
enum auth_flavor {
    AUTH_NULL        = 0,
    AUTH_UNIX        = 1,
    AUTH_SHORT       = 2,
    /* \fIand more to be defined\fP */
};

struct opaque_auth {
    auth_flavor flavor;
    opaque body<400>;
};
X.DE
X.LP
In simple English, any
X.I opaque_auth 
structure is an 
X.I auth_flavor 
enumeration followed by bytes which are  opaque to the RPC protocol
implementation.
X.LP
The interpretation and semantics  of the data contained  within the
authentication   fields  is specified  by  individual,  independent
authentication  protocol specifications.   (See 
\fIAuthentication Protocols\fP\,
below, for definitions of the various authentication protocols.)
X.LP
If authentication parameters were   rejected, the  response message
contains information stating why they were rejected.
X.NH 2
\&Program Number Assignment
X.LP
Program numbers are given out in groups of
X.I 0x20000000 
(decimal 536870912) according to the following chart:
X.TS
box tab (&) ;
lfI lfI
rfL cfI .
Program Numbers&Description
_
X.sp .5
0 - 1fffffff&Defined by Sun
20000000 - 3fffffff&Defined by user
40000000 - 5fffffff&Transient
60000000 - 7fffffff&Reserved
80000000 - 9fffffff&Reserved
a0000000 - bfffffff&Reserved
c0000000 - dfffffff&Reserved
e0000000 - ffffffff&Reserved
X.TE
X.LP
The first group is a range of numbers administered by Sun
Microsystems and should be identical for all sites.  The second range
is for applications peculiar to a particular site.  This range is
intended primarily for debugging new programs.  When a site develops
an application that might be of general interest, that application
should be given an assigned number in the first range.  The third
group is for applications that generate program numbers dynamically.
The final groups are reserved for future use, and should not be used.
X.NH 2
\&Other Uses of the RPC Protocol
X.LP
The intended use of this protocol is for calling remote procedures.
That is, each call message is matched with a response message.
However, the protocol itself is a message-passing protocol with which
other (non-RPC) protocols can be implemented.  Sun currently uses, or
perhaps abuses, the RPC message protocol for the following two
(non-RPC) protocols:  batching (or pipelining) and broadcast RPC.
These two protocols are discussed but not defined below.
X.NH 3
\&Batching
X.LP
Batching allows a client to send an arbitrarily large sequence of
call messages to a server; batching typically uses reliable byte
stream protocols (like TCP/IP) for its transport.  In the case of
batching, the client never waits for a reply from the server, and the
server does not send replies to batch requests.  A sequence of batch
calls is usually terminated by a legitimate RPC in order to flush the
pipeline (with positive acknowledgement).
X.NH 3
\&Broadcast RPC
X.LP
In broadcast RPC-based protocols, the client sends a broadcast packet
to the network and waits for numerous replies.  Broadcast RPC uses
unreliable, packet-based protocols (like UDP/IP) as its transports.
Servers that support broadcast protocols only respond when the
request is successfully processed, and are silent in the face of
errors.  Broadcast RPC uses the Port Mapper RPC service to achieve
its semantics.  See the \fIPort Mapper Program Protocol\fP\, below,
for more information.
X.KS
X.NH 1
\&The RPC Message Protocol
X.LP
This section defines the RPC message protocol in the XDR data
description language.  The message is defined in a top-down style.
X.ie t .DS
X.el .DS L
X.ft CW
enum msg_type {
	CALL  = 0,
	REPLY = 1
};

X.ft I
/*
* A reply to a call message can take on two forms:
* The message was either accepted or rejected.
*/
X.ft CW
enum reply_stat {
	MSG_ACCEPTED = 0,
	MSG_DENIED   = 1
};

X.ft I
/*
* Given that a call message was accepted,  the following is the
* status of an attempt to call a remote procedure.
*/
X.ft CW
enum accept_stat {
	SUCCESS       = 0, /* \fIRPC executed successfully       \fP*/
	PROG_UNAVAIL  = 1, /* \fIremote hasn't exported program  \fP*/
	PROG_MISMATCH = 2, /* \fIremote can't support version #  \fP*/
	PROC_UNAVAIL  = 3, /* \fIprogram can't support procedure \fP*/
	GARBAGE_ARGS  = 4  /* \fIprocedure can't decode params   \fP*/
};
X.DE
X.ie t .DS
X.el .DS L
X.ft I
/*
* Reasons why a call message was rejected:
*/
X.ft CW
enum reject_stat {
	RPC_MISMATCH = 0, /* \fIRPC version number != 2          \fP*/
	AUTH_ERROR = 1    /* \fIremote can't authenticate caller \fP*/
};

X.ft I
/*
* Why authentication failed:
*/
X.ft CW
enum auth_stat {
	AUTH_BADCRED      = 1,  /* \fIbad credentials (seal broken) \fP*/
	AUTH_REJECTEDCRED = 2,  /* \fIclient must begin new session \fP*/
	AUTH_BADVERF      = 3,  /* \fIbad verifier (seal broken)    \fP*/
	AUTH_REJECTEDVERF = 4,  /* \fIverifier expired or replayed  \fP*/
	AUTH_TOOWEAK      = 5   /* \fIrejected for security reasons \fP*/
};
X.DE
X.KE
X.ie t .DS
X.el .DS L
X.ft I
/*
* The  RPC  message: 
* All   messages  start with   a transaction  identifier,  xid,
* followed  by a  two-armed  discriminated union.   The union's
* discriminant is a  msg_type which switches to  one of the two
* types   of the message.   The xid  of a \fIREPLY\fP  message always
* matches  that of the initiating \fICALL\fP   message.   NB: The xid
* field is only  used for clients  matching reply messages with
* call messages  or for servers detecting  retransmissions; the
* service side  cannot treat this id  as any type   of sequence
* number.
*/
X.ft CW
struct rpc_msg {
	unsigned int xid;
	union switch (msg_type mtype) {
		case CALL:
			call_body cbody;
		case REPLY:  
			reply_body rbody;
	} body;
};
X.DE
X.ie t .DS
X.el .DS L
X.ft I
/*
* Body of an RPC request call: 
* In version 2 of the  RPC protocol specification, rpcvers must
* be equal to 2.  The  fields prog,  vers, and proc specify the
* remote program, its version number, and the  procedure within
* the remote program to be called.  After these  fields are two
* authentication  parameters: cred (authentication credentials)
* and verf  (authentication verifier).  The  two authentication
* parameters are   followed by  the  parameters  to  the remote
* procedure,  which  are specified  by  the  specific   program
* protocol.
*/
X.ft CW
struct call_body {
	unsigned int rpcvers;  /* \fImust be equal to two (2) \fP*/
	unsigned int prog;
	unsigned int vers;
	unsigned int proc;
	opaque_auth cred;
	opaque_auth verf;
	/* \fIprocedure specific parameters start here \fP*/
};
X.DE
X.ie t .DS
X.el .DS L
X.ft I
/*
* Body of a reply to an RPC request:
* The call message was either accepted or rejected.
*/
X.ft CW
union reply_body switch (reply_stat stat) {
	case MSG_ACCEPTED:  
		accepted_reply areply;
	case MSG_DENIED:  
		rejected_reply rreply;
} reply;
X.DE
X.ie t .DS
X.el .DS L
X.ft I
/*
* Reply to   an RPC request  that  was accepted  by the server:
* there could be an error even though the request was accepted.
* The first field is an authentication verifier that the server
* generates in order to  validate itself  to the caller.  It is
* followed by    a  union whose     discriminant  is   an  enum
* accept_stat.  The  \fISUCCESS\fP  arm of    the union  is  protocol
* specific.  The \fIPROG_UNAVAIL\fP, \fIPROC_UNAVAIL\fP, and \fIGARBAGE_ARGP\fP
* arms of the union are void.   The \fIPROG_MISMATCH\fP arm specifies
* the lowest and highest version numbers of the  remote program
* supported by the server.
*/
X.ft CW
struct accepted_reply {
	opaque_auth verf;
	union switch (accept_stat stat) {
		case SUCCESS:
			opaque results[0];
			/* \fIprocedure-specific results start here\fP */
		case PROG_MISMATCH:
			struct {
				unsigned int low;
				unsigned int high;
			} mismatch_info;
		default:
X.ft I
			/*
			* Void.  Cases include \fIPROG_UNAVAIL, PROC_UNAVAIL\fP,
			* and \fIGARBAGE_ARGS\fP.
			*/
X.ft CW
			void;
	} reply_data;
};
X.DE
X.ie t .DS
X.el .DS L
X.ft I
/*
* Reply to an RPC request that was rejected by the server: 
* The request  can   be rejected for   two reasons:  either the
* server   is not  running a   compatible  version  of the  RPC
* protocol    (\fIRPC_MISMATCH\fP), or    the  server   refuses    to
* authenticate the  caller  (\fIAUTH_ERROR\fP).  In  case of  an  RPC
* version mismatch,  the server returns the  lowest and highest
* supported    RPC  version    numbers.  In   case   of refused
* authentication, failure status is returned.
*/
X.ft CW
union rejected_reply switch (reject_stat stat) {
	case RPC_MISMATCH:
		struct {
			unsigned int low;
			unsigned int high;
		} mismatch_info;
	case AUTH_ERROR: 
		auth_stat stat;
};
X.DE
X.NH 1
\&Authentication Protocols
X.LP
As previously stated, authentication parameters are opaque, but
open-ended to the rest of the RPC protocol.  This section defines
some "flavors" of authentication implemented at (and supported by)
Sun.  Other sites are free to invent new authentication types, with
the same rules of flavor number assignment as there is for program
number assignment.
X.NH 2
\&Null Authentication
X.LP
Often calls must be made where the caller does not know who he is or
the server does not care who the caller is.  In this case, the flavor
value (the discriminant of the \fIopaque_auth\fP's union) of the RPC
message's credentials, verifier, and response verifier is
X.I AUTH_NULL .
The  bytes of the opaque_auth's body  are undefined.
It is recommended that the opaque length be zero.
X.NH 2
\&UNIX Authentication
X.LP
The caller of a remote procedure may wish to identify himself as he
is identified on a UNIX system.  The  value of the credential's
discriminant of an RPC call  message is  
X.I AUTH_UNIX .
the credential's opaque body encode the the following structure:
X.DS
X.ft CW
struct auth_unix {
	unsigned int stamp;
	string machinename<255>;
	unsigned int uid;
	unsigned int gid;
	unsigned int gids<10>;
};
X.DE
The 
X.I stamp 
is an  arbitrary    ID which the  caller machine   may
generate.  The 
X.I machinename 
is the  name of the  caller's machine (like  "krypton").  The 
X.I uid 
is  the caller's effective user  ID.  The  
X.I gid 
is  the caller's effective  group  ID.  The 
X.I gids 
is  a
counted array of groups which contain the caller as  a member.  The
verifier accompanying the  credentials  should  be  of  
X.I AUTH_NULL
(defined above).
X.LP
The value of the discriminant of  the response verifier received in
the  reply  message  from  the    server  may   be   
X.I AUTH_NULL 
or
X.I AUTH_SHORT .
In  the  case  of 
X.I AUTH_SHORT ,
the bytes of the response verifier's string encode an opaque
structure.  This new opaque structure may now be passed to the server
instead of the original
X.I AUTH_UNIX
flavor credentials.  The server keeps a cache which maps shorthand
opaque structures (passed back by way of an
X.I AUTH_SHORT
style response verifier) to the original credentials of the caller.
The caller can save network bandwidth and server cpu cycles by using
the new credentials.
X.LP
The server may flush the shorthand opaque structure at any time.  If
this happens, the remote procedure call message will be rejected due
to an authentication error.  The reason for the failure will be
X.I AUTH_REJECTEDCRED .
At this point, the caller may wish to try the original
X.I AUTH_UNIX
style of credentials.
X.KS
X.NH 1
\&Record Marking Standard
X.LP
When RPC messages are passed on top of a byte stream protocol (like
TCP/IP), it is necessary, or at least desirable, to delimit one
message from another in order to detect and possibly recover from
user protocol errors.  This is called record marking (RM).  Sun uses
this RM/TCP/IP transport for passing RPC messages on TCP streams.
One RPC message fits into one RM record.
X.LP
A record is composed of one or more record fragments.  A record
fragment is a four-byte header followed by 0 to (2**31) - 1 bytes of
fragment data.  The bytes encode an unsigned binary number; as with
XDR integers, the byte order is from highest to lowest.  The number
encodes two values\(ema boolean which indicates whether the fragment
is the last fragment of the record (bit value 1 implies the fragment
is the last fragment) and a 31-bit unsigned binary value which is the
length in bytes of the fragment's data.  The boolean value is the
highest-order bit of the header; the length is the 31 low-order bits.
(Note that this record specification is NOT in XDR standard form!)
X.KE
X.KS
X.NH 1
\&The RPC Language
X.LP
Just as there was a need to describe the XDR data-types in a formal
language, there is also need to describe the procedures that operate
on these XDR data-types in a formal language as well.  We use the RPC
Language for this purpose.  It is an extension to the XDR language.
The following example is used to describe the essence of the
language.
X.NH 2
\&An Example Service Described in the RPC Language
X.LP
Here is an example of the specification of a simple ping program.
X.ie t .DS
X.el .DS L
X.vs 11
X.ft I
/*
* Simple ping program
*/
X.ft CW
program PING_PROG {
	/* \fILatest and greatest version\fP */
	version PING_VERS_PINGBACK {
	void 
	PINGPROC_NULL(void) = 0;

X.ft I
	/*
	* Ping the caller, return the round-trip time
	* (in microseconds). Returns -1 if the operation
	* timed out.
	*/
X.ft CW
	int
	PINGPROC_PINGBACK(void) = 1;        
} = 2;     

X.ft I
/*
* Original version
*/
X.ft CW
version PING_VERS_ORIG {
	void 
	PINGPROC_NULL(void) = 0;
	} = 1;
} = 1;

const PING_VERS = 2;      /* \fIlatest version \fP*/
X.vs
X.DE
X.KE
X.LP
The first version described is
X.I PING_VERS_PINGBACK
with  two procedures,   
X.I PINGPROC_NULL 
and 
X.I PINGPROC_PINGBACK.
X.I PINGPROC_NULL 
takes no arguments and returns no results, but it is useful for
computing round-trip times from the client to the server and back
again.  By convention, procedure 0 of any RPC protocol should have
the same semantics, and never require any kind of authentication.
The second procedure is used for the client to have the server do a
reverse ping operation back to the client, and it returns the amount
of time (in microseconds) that the operation used.  The next version,
X.I PING_VERS_ORIG ,
is the original version of the protocol
and it does not contain
X.I PINGPROC_PINGBACK
procedure. It  is useful
for compatibility  with old client  programs,  and as  this program
matures it may be dropped from the protocol entirely.
X.KS
X.NH 2
\&The RPC Language Specification
X.LP
The  RPC language is identical to  the XDR language, except for the
added definition of a
X.I program-def 
described below.
X.DS
X.ft CW
program-def:
	"program" identifier "{"
		version-def 
		version-def *
	"}" "=" constant ";"

version-def:
	"version" identifier "{"
		procedure-def
		procedure-def *
	"}" "=" constant ";"

procedure-def:
	type-specifier identifier "(" type-specifier ")"
	"=" constant ";"
X.DE
X.KE
X.NH 2
\&Syntax Notes
X.IP  1.
The following keywords  are  added  and   cannot  be used   as
identifiers: "program" and "version";
X.IP  2.
A version name cannot occur more than once within the  scope of
a program definition. Nor can a version number occur more than once
within the scope of a program definition.
X.IP  3.
A procedure name cannot occur  more than once within  the scope
of a version definition. Nor can a procedure number occur more than
once within the scope of version definition.
X.IP  4.
Program identifiers are in the same name space as  constant and
type identifiers.
X.IP  5.
Only unsigned constants can  be assigned to programs, versions
and procedures.
X.NH 1
\&Port Mapper Program Protocol
X.LP
The port mapper program maps RPC program and version numbers to
transport-specific port numbers.  This program makes dynamic binding
of remote programs possible.
X.LP
This is desirable because the range of reserved port numbers is very
small and the number of potential remote programs is very large.  By
running only the port mapper on a reserved port, the port numbers of
other remote programs can be ascertained by querying the port mapper.
X.LP
The port mapper also aids in broadcast RPC.  A given RPC program will
usually have different port number bindings on different machines, so
there is no way to directly broadcast to all of these programs.  The
port mapper, however, does have a fixed port number.  So, to
broadcast to a given program, the client actually sends its message
to the port mapper located at the broadcast address.  Each port
mapper that picks up the broadcast then calls the local service
specified by the client.  When the port mapper gets the reply from
the local service, it sends the reply on back to the client.
X.KS
X.NH 2
\&Port Mapper Protocol Specification (in RPC Language)
X.ie t .DS
X.el .DS L
X.ft CW
X.vs 11
const PMAP_PORT = 111;      /* \fIportmapper port number \fP*/

X.ft I
/*
* A mapping of (program, version, protocol) to port number
*/
X.ft CW
struct mapping {
	unsigned int prog;
	unsigned int vers;
	unsigned int prot;
	unsigned int port;
};

X.ft I
/* 
* Supported values for the "prot" field
*/
X.ft CW
const IPPROTO_TCP = 6;      /* \fIprotocol number for TCP/IP \fP*/
const IPPROTO_UDP = 17;     /* \fIprotocol number for UDP/IP \fP*/

X.ft I
/*
* A list of mappings
*/
X.ft CW
struct *pmaplist {
	mapping map;
	pmaplist next;
};
X.vs
X.DE
X.ie t .DS
X.el .DS L
X.vs 11
X.ft I
/*
* Arguments to callit
*/
X.ft CW
struct call_args {
	unsigned int prog;
	unsigned int vers;
	unsigned int proc;
	opaque args<>;
};  

X.ft I
/*
* Results of callit
*/
X.ft CW
struct call_result {
	unsigned int port;
	opaque res<>;
};
X.vs
X.DE
X.KE
X.ie t .DS
X.el .DS L
X.vs 11
X.ft I
/*
* Port mapper procedures
*/
X.ft CW
program PMAP_PROG {
	version PMAP_VERS {
		void 
		PMAPPROC_NULL(void)         = 0;

		bool
		PMAPPROC_SET(mapping)       = 1;

		bool
		PMAPPROC_UNSET(mapping)     = 2;

		unsigned int
		PMAPPROC_GETPORT(mapping)   = 3;

		pmaplist
		PMAPPROC_DUMP(void)         = 4;

		call_result
		PMAPPROC_CALLIT(call_args)  = 5;
	} = 2;
} = 100000;
X.vs
X.DE
X.NH 2
\&Port Mapper Operation
X.LP
The portmapper program currently supports two protocols (UDP/IP and
TCP/IP).  The portmapper is contacted by talking to it on assigned
port number 111 (SUNRPC [8]) on either of these protocols.  The
following is a description of each of the portmapper procedures:
X.IP \fBPMAPPROC_NULL:\fP
This procedure does no work.  By convention, procedure zero of any
protocol takes no parameters and returns no results.
X.IP \fBPMAPPROC_SET:\fP
When a program first becomes available on a machine, it registers
itself with the port mapper program on the same machine.  The program
passes its program number "prog", version number "vers", transport
protocol number "prot", and the port "port" on which it awaits
service request.  The procedure returns a boolean response whose
value is
X.I TRUE
if the procedure successfully established the mapping and 
X.I FALSE 
otherwise.  The procedure refuses to establish
a mapping if one already exists for the tuple "(prog, vers, prot)".
X.IP \fBPMAPPROC_UNSET:\fP
When a program becomes unavailable, it should unregister itself with
the port mapper program on the same machine.  The parameters and
results have meanings identical to those of
X.I PMAPPROC_SET .
The protocol and port number fields of the argument are ignored.
X.IP \fBPMAPPROC_GETPORT:\fP
Given a program number "prog", version number "vers", and transport
protocol number "prot", this procedure returns the port number on
which the program is awaiting call requests.  A port value of zeros
means the program has not been registered.  The "port" field of the
argument is ignored.
X.IP \fBPMAPPROC_DUMP:\fP
This procedure enumerates all entries in the port mapper's database.
The procedure takes no parameters and returns a list of program,
version, protocol, and port values.
X.IP \fBPMAPPROC_CALLIT:\fP
This procedure allows a caller to call another remote procedure on
the same machine without knowing the remote procedure's port number.
It is intended for supporting broadcasts to arbitrary remote programs
via the well-known port mapper's port.  The parameters "prog",
"vers", "proc", and the bytes of "args" are the program number,
version number, procedure number, and parameters of the remote
procedure.
X.LP
X.B Note:
X.RS
X.IP  1.
This procedure only sends a response if the procedure was
successfully executed and is silent (no response) otherwise.
X.IP  2.
The port mapper communicates with the remote program using UDP/IP
only.
X.RE
X.LP
The procedure returns the remote program's port number, and the bytes
of results are the results of the remote procedure.
X.bp
X.NH 1
\&References
X.LP
[1]  Birrell, Andrew D. & Nelson, Bruce Jay; "Implementing Remote
Procedure Calls"; XEROX CSL-83-7, October 1983.
X.LP
[2]  Cheriton, D.; "VMTP:  Versatile Message Transaction Protocol",
Preliminary Version 0.3; Stanford University, January 1987.
X.LP
[3]  Diffie & Hellman; "Net Directions in Cryptography"; IEEE
Transactions on Information Theory IT-22, November 1976.
X.LP
[4]  Harrenstien, K.; "Time Server", RFC 738; Information Sciences
Institute, October 1977.
X.LP
[5]  National Bureau of Standards; "Data Encryption Standard"; Federal
Information Processing Standards Publication 46, January 1977.
X.LP
[6]  Postel, J.; "Transmission Control Protocol - DARPA Internet
Program Protocol Specification", RFC 793; Information Sciences
Institute, September 1981.
X.LP
[7]  Postel, J.; "User Datagram Protocol", RFC 768; Information Sciences
Institute, August 1980.
X.LP
[8]  Reynolds, J.  & Postel, J.; "Assigned Numbers", RFC 923; Information
Sciences Institute, October 1984.
Funky_Stuff
echo x - rpcgen.ms
sed -e 's/^X//' > rpcgen.ms <<'Funky_Stuff'
X.\" @(#)rpcgen.ms	1.2 87/11/09 3.9 RPCSRC
X.de BT
X.if \\n%=1 .tl ''- % -''
X..
X.ND
X.\" prevent excess underlining in nroff
X.if n .fp 2 R
X.OH '\fBrpcgen\fP Programming Guide''Page %'
X.EH 'Page %''\fBrpcgen\fP Programming Guide'
X.if \\n%=1 .bp
X.SH
\&\fBrpcgen\fP Programming Guide
X.NH 0
\&The \fBrpcgen\fP Protocol Compiler
X.IX rpcgen "" \fIrpcgen\fP "" PAGE MAJOR
X.LP
X.IX RPC "" "" \fIrpcgen\fP
The details of programming applications to use Remote Procedure Calls 
can be overwhelming.  Perhaps most daunting is the writing of the XDR 
routines necessary to convert procedure arguments and results into 
their network format and vice-versa.  
X.LP
Fortunately, 
X.I rpcgen 
exists to help programmers write RPC applications simply and directly.
X.I rpcgen 
does most of the dirty work, allowing programmers to debug 
the  main  features of their application, instead of requiring them to
spend most of their time debugging their network interface code.
X.LP
X.I rpcgen 
is a  compiler.  It accepts a remote program interface definition written
in a language, called RPC Language, which is similar to C.  It produces a C
language output which includes stub versions of the client routines, a
server skeleton, XDR filter routines for both parameters and results, and a
header file that contains common definitions. The client stubs interface
with the RPC library and effectively hide the network from their callers.
The server stub similarly hides the network from the server procedures that
are to be invoked by remote clients.
X.I rpcgen 's
output files can be compiled and linked in the usual way.  The developer
writes server procedures\(emin any language that observes Sun calling
conventions\(emand links them with the server skeleton produced by
X.I rpcgen 
to get an executable server program.  To use a remote program, a programmer
writes an ordinary main program that makes local procedure calls to the 
client stubs produced by
X.I rpcgen .
Linking this program with 
X.I rpcgen 's
stubs creates an executable program.  (At present the main program must be 
written in C).
X.I rpcgen 
options can be used to suppress stub generation and to specify the transport
to be used by the server stub.
X.LP
Like all compilers, 
X.I rpcgen 
reduces development time
that would otherwise be spent coding and debugging low-level routines.
All compilers, including 
X.I rpcgen ,
do this at a small cost in efficiency
and flexibility.  However,   many compilers allow  escape  hatches for
programmers to  mix low-level code with  high-level code. 
X.I rpcgen 
is no exception.  In speed-critical applications, hand-written routines 
can be linked with the 
X.I rpcgen 
output without any difficulty.  Also, one may proceed by using
X.I rpcgen 
output as a starting point, and rewriting it as necessary.
X.NH 1
\&Converting Local Procedures into Remote Procedures
X.IX rpcgen "local procedures" \fIrpcgen\fP
X.IX rpcgen "remote procedures" \fIrpcgen\fP
X.LP
Assume an application that runs on a single machine, one which we want 
to convert to run over the network.  Here we will demonstrate such a 
conversion by way of a simple example\(ema program that prints a 
message to the console:
X.ie t .DS
X.el .DS L
X.ft I
/*
 * printmsg.c: print a message on the console
 */
X.ft CW
#include <stdio.h>

main(argc, argv)
	int argc;
	char *argv[];
{
	char *message;

	if (argc < 2) {
		fprintf(stderr, "usage: %s <message>\en", argv[0]);
		exit(1);
	}
	message = argv[1];

	if (!printmessage(message)) {
		fprintf(stderr, "%s: couldn't print your message\en",
			argv[0]);
		exit(1);
	} 
	printf("Message delivered!\n");
}
X.ft I
/*
 * Print a message to the console.
 * Return a boolean indicating whether the message was actually printed.
 */
X.ft CW
printmessage(msg)
	char *msg;
{
	FILE *f;

	f = fopen("/dev/console", "w");
	if (f == NULL) {
		return (0);
	}
	fprintf(f, "%s\en", msg);
	fclose(f);
	return(1);
}
X.DE
X.LP
And then, of course:
X.ie t .DS
X.el .DS L
X.ft CW
example%  \fBcc printmsg.c -o printmsg\fP
example%  \fBprintmsg "Hello, there."\fP
Message delivered!
example%
X.DE
X.LP
If  
X.I printmessage 
was turned into  a remote procedure,
then it could be  called from anywhere in   the network.  
Ideally,  one would just  like to stick   a  keyword like  
X.I remote 
in  front  of a
procedure to turn it into a  remote procedure.  Unfortunately,
we  have to live  within the  constraints of  the   C language, since 
it existed   long before  RPC did.  But   even without language 
support, it's not very difficult to make a procedure remote.
X.LP
In  general, it's necessary to figure  out  what the types are for
all procedure inputs and outputs.  In  this case,   we  have a 
procedure
X.I printmessage 
which takes a  string as input, and returns  an integer
as output.  Knowing  this, we can write a  protocol specification in RPC
language that  describes the remote  version of 
X.I printmessage .
Here it is:
X.ie t .DS
X.el .DS L
X.ft I
/*
 * msg.x: Remote message printing protocol
 */
X.ft CW

program MESSAGEPROG {
	version MESSAGEVERS {
		int PRINTMESSAGE(string) = 1;
	} = 1;
} = 99;
X.DE
X.LP
Remote procedures are part of remote programs, so we actually declared
an  entire  remote program  here  which contains  the single procedure
X.I PRINTMESSAGE .
This procedure was declared to be  in version  1 of the
remote program.  No null procedure (procedure 0) is necessary because
X.I rpcgen 
generates it automatically.
X.LP
Notice that everything is declared with all capital  letters.  This is
not required, but is a good convention to follow.
X.LP
Notice also that the argument type is "string" and not "char *".  This
is because a "char *" in C is ambiguous. Programmers usually intend it
to mean  a null-terminated string   of characters, but  it  could also
represent a pointer to a single character or a  pointer to an array of
characters.  In  RPC language,  a  null-terminated  string is 
unambiguously called a "string". 
X.LP
There are  just two more things to  write.  First, there is the remote
procedure itself.  Here's the definition of a remote procedure
to implement the
X.I PRINTMESSAGE
procedure we declared above:
X.ie t .DS
X.el .DS L
X.vs 11
X.ft I
/*
 * msg_proc.c: implementation of the remote procedure "printmessage"
 */
X.ft CW

#include <stdio.h>
#include <rpc/rpc.h>    /* \fIalways needed\fP  */
#include "msg.h"        /* \fIneed this too: msg.h will be generated by rpcgen\fP */

X.ft I
/*
 * Remote verson of "printmessage"
 */
X.ft CW
int *
printmessage_1(msg)
	char **msg;
{
	static int result;  /* \fImust be static!\fP */
	FILE *f;

	f = fopen("/dev/console", "w");
	if (f == NULL) {
		result = 0;
		return (&result);
	}
	fprintf(f, "%s\en", *msg);
	fclose(f);
	result = 1;
	return (&result);
}
X.vs
X.DE
X.LP
Notice here that the declaration of the remote procedure
X.I printmessage_1 
differs from that of the local procedure
X.I printmessage 
in three ways:
X.IP  1.
It takes a pointer to a string instead of a string itself.  This
is true of all  remote procedures:  they always take pointers to  their
arguments rather than the arguments themselves.
X.IP  2.
It returns a pointer to an  integer instead of  an integer itself. This is
also generally true of remote procedures: they always return a pointer
to their results.
X.IP  3.
It has  an "_1" appended to  its name.   In  general, all  remote
procedures called by 
X.I rpcgen 
are named by  the following rule: the name in the program  definition  
(here 
X.I PRINTMESSAGE )
is converted   to all
lower-case   letters, an underbar ("_")   is appended  to it, and
finally the version number (here 1) is appended.
X.LP
The last thing to do is declare the main client program that will call
the remote procedure. Here it is:
X.ie t .DS
X.el .DS L
X.ft I
/*
 * rprintmsg.c: remote version of "printmsg.c"
 */
X.ft CW
#include <stdio.h>
#include <rpc/rpc.h>     /* \fIalways needed\fP  */
#include "msg.h"         /* \fIneed this too: msg.h will be generated by rpcgen\fP */

main(argc, argv)
	int argc;
	char *argv[];
{
	CLIENT *cl;
	int *result;
	char *server;
	char *message;

	if (argc < 3) {
		fprintf(stderr, "usage: %s host message\en", argv[0]);
		exit(1);
	}

X.ft I
	/*
	 * Save values of command line arguments 
	 */
X.ft CW
	server = argv[1];
	message = argv[2];

X.ft I
	/*
	 * Create client "handle" used for calling \fIMESSAGEPROG\fP on the
	 * server designated on the command line. We tell the RPC package
	 * to use the "tcp" protocol when contacting the server.
	 */
X.ft CW
	cl = clnt_create(server, MESSAGEPROG, MESSAGEVERS, "tcp");
	if (cl == NULL) {
X.ft I
		/*
		 * Couldn't establish connection with server.
		 * Print error message and die.
		 */
X.ft CW
		clnt_pcreateerror(server);
		exit(1);
	}
	
X.ft I
	/*
	 * Call the remote procedure "printmessage" on the server
	 */
X.ft CW
	result = printmessage_1(&message, cl);
	if (result == NULL) {
X.ft I
		/*
		 * An error occurred while calling the server. 
	 	 * Print error message and die.
		 */
X.ft CW
		clnt_perror(cl, server);
		exit(1);
	}

X.ft I
	/*
	 * Okay, we successfully called the remote procedure.
	 */
X.ft CW
	if (*result == 0) {
X.ft I
		/*
		 * Server was unable to print our message. 
		 * Print error message and die.
		 */
X.ft CW
		fprintf(stderr, "%s: %s couldn't print your message\en", 
			argv[0], server);	
		exit(1);
	} 

X.ft I
	/*
	 * The message got printed on the server's console
	 */
X.ft CW
	printf("Message delivered to %s!\en", server);
}
X.DE
There are two things to note here:
X.IP  1.
X.IX "client handle"
First a client "handle" is created  using the RPC library routine
X.I clnt_create .
This client handle will be passed  to the stub routines
which call the remote procedure.
X.IP  2.
The remote procedure  
X.I printmessage_1 
is called exactly  the same way as it is  declared in 
X.I msg_proc.c 
except for the inserted client handle as the first argument.
X.LP
Here's how to put all of the pieces together:
X.ie t .DS
X.el .DS L
X.ft CW
example%  \fBrpcgen msg.x\fP
example%  \fBcc rprintmsg.c msg_clnt.c -o rprintmsg\fP
example%  \fBcc msg_proc.c msg_svc.c -o msg_server\fP
X.DE
Two programs were compiled here: the client program 
X.I printmsg 
and the server  program 
X.I msg_server .
Before doing this  though,  
X.I rpcgen 
was used to fill in the missing pieces.  
X.LP
Here is what 
X.I rpcgen 
did with the input file 
X.I msg.x :
X.IP  1.
It created a header file called 
X.I msg.h 
that contained \fI#define\fP's for
X.I MESSAGEPROG ,
X.I MESSAGEVERS 
and    
X.I PRINTMESSAGE 
for use in  the  other modules.
X.IP  2.
It created client "stub" routines in the 
X.I msg_clnt.c 
file.   In this case there is only one, the 
X.I printmessage_1 
that was referred to from the
X.I printmsg 
client program.  The name  of the output file for
client stub routines is always formed in this way:  if the name of the
input file is  
X.I FOO.x ,
the   client  stubs   output file is    called
X.I FOO_clnt.c .
X.IP  3.
It created  the  server   program which calls   
X.I printmessage_1 
in
X.I msg_proc.c .
This server program is named  
X.I msg_svc.c .
The rule for naming the server output file is similar  to the 
previous one:  for an input  file   called  
X.I FOO.x ,
the   output   server   file is  named
X.I FOO_svc.c .
X.LP
Now we're ready to have some fun.  First, copy the server to a
remote machine and run it.  For this  example,  the
machine is called "moon".  Server processes are run in the 
background, because they never exit.
X.ie t .DS
X.el .DS L
X.ft CW
moon% msg_server &	       
X.DE
Then on our local machine ("sun") we can print a message on "moon"s 
console.
X.ie t .DS
X.el .DS L
X.ft CW
sun% printmsg moon "Hello, moon."
X.DE
The message will   get printed to  "moon"s  console. You  can print  a
message on anybody's console (including your own) with this program if
you are able to copy the server to their machine and run it.
X.NH 1
\&Generating XDR Routines
X.IX RPC "generating XDR routines"
X.LP
The previous example  only demonstrated  the  automatic generation of
client  and server RPC  code. 
X.I rpcgen 
may also  be used to generate XDR routines, that  is,  the routines
necessary to  convert   local  data
structures into network format and vice-versa.  This example presents
a complete RPC service\(ema remote directory listing service, which uses
X.I rpcgen
not  only  to generate stub routines, but also to  generate  the XDR
routines.  Here is the protocol description file:
X.ie t .DS
X.el .DS L
X.ft I
/*
 * dir.x: Remote directory listing protocol
 */
X.ft CW
const MAXNAMELEN = 255;		/* \fImaximum length of a directory entry\fP */

typedef string nametype<MAXNAMELEN>;	/* \fIa directory entry\fP */

typedef struct namenode *namelist;		/* \fIa link in the listing\fP */

X.ft I
/*
 * A node in the directory listing
 */
X.ft CW
struct namenode {
	nametype name;		/* \fIname of directory entry\fP */
	namelist next;		/* \fInext entry\fP */
};

X.ft I
/*
 * The result of a READDIR operation.
 */
X.ft CW
union readdir_res switch (int errno) {
case 0:
	namelist list;	/* \fIno error: return directory listing\fP */
default:
	void;		/* \fIerror occurred: nothing else to return\fP */
};

X.ft I
/*
 * The directory program definition
 */
X.ft CW
program DIRPROG {
	version DIRVERS {
		readdir_res
		READDIR(nametype) = 1;
	} = 1;
} = 76;
X.DE
Running 
X.I rpcgen 
on 
X.I dir.x 
creates four output files. Three are the same
as before: header file, client stub routines  and server skeleton. The
fourth are the XDR routines necessary for converting the data types we
declared into XDR format and vice-versa. These are  output in the file
X.I dir_xdr.c .
X.LP
Here is the implementation of the "READDIR" procedure:
X.ie t .DS
X.el .DS L
X.vs 11
X.ft I
/*
 * dir_proc.c: remote readdir implementation
 */
X.ft CW
#include <rpc/rpc.h>
#include <sys/dir.h>
#include "dir.h"

extern int errno;
extern char *malloc();
extern char *strdup();

readdir_res *
readdir_1(dirname)
	nametype *dirname;
{
	DIR *dirp;
	struct direct *d;
	namelist nl;
	namelist *nlp;
	static readdir_res res; /* \fImust be static\fP! */
	
X.ft I
	/*
	 * Open directory
	 */
X.ft CW
	dirp = opendir(*dirname);
	if (dirp == NULL) {
		res.errno = errno;
		return (&res);
	}

X.ft I
	/*
	 * Free previous result
	 */
X.ft CW
	xdr_free(xdr_readdir_res, &res);

X.ft I
	/*
	 * Collect directory entries
	 */
X.ft CW
	nlp = &res.readdir_res_u.list;
	while (d = readdir(dirp)) {
		nl = *nlp = (namenode *) malloc(sizeof(namenode));
		nl->name = strdup(d->d_name);
		nlp = &nl->next;
	}
	*nlp = NULL;

X.ft I
	/*
	 * Return the result
	 */
X.ft CW
	res.errno = 0;
	closedir(dirp);
	return (&res);
}
X.vs
X.DE
Finally, there is the client side program to call the server:
X.ie t .DS
X.el .DS L
X.ft I
/*
 * rls.c: Remote directory listing client
 */
X.ft CW
#include <stdio.h>
#include <rpc/rpc.h>	/* \fIalways need this\fP */
#include "dir.h"		/* \fIneed this too: will be generated by rpcgen\fP */

extern int errno;

main(argc, argv)
	int argc;
	char *argv[];
{
	CLIENT *cl;
	char *server;
	char *dir;
	readdir_res *result;
	namelist nl;
	

	if (argc != 3) {
		fprintf(stderr, "usage: %s host directory\en", argv[0]);
		exit(1);
	}

X.ft I
	/*
	 * Remember what our command line arguments refer to
	 */
X.ft CW
	server = argv[1];
	dir = argv[2];

X.ft I
	/*
	 * Create client "handle" used for calling \fIMESSAGEPROG\fP on the
	 * server designated on the command line. We tell the RPC package
	 * to use the "tcp" protocol when contacting the server.
	 */
X.ft CW
	cl = clnt_create(server, DIRPROG, DIRVERS, "tcp");
	if (cl == NULL) {
X.ft I
		/*
		 * Couldn't establish connection with server.
		 * Print error message and die.
		 */
X.ft CW
		clnt_pcreateerror(server);
		exit(1);
	}
	
X.ft I
	/*
	 * Call the remote procedure \fIreaddir\fP on the server
	 */
X.ft CW
	result = readdir_1(&dir, cl);
	if (result == NULL) {
X.ft I
		/*
		 * An error occurred while calling the server. 
	 	 * Print error message and die.
		 */
X.ft CW
		clnt_perror(cl, server);
		exit(1);
	}

X.ft I
	/*
	 * Okay, we successfully called the remote procedure.
	 */
X.ft CW
	if (result->errno != 0) {
X.ft I
		/*
		 * A remote system error occurred.
		 * Print error message and die.
		 */
X.ft CW
		errno = result->errno;
		perror(dir);
		exit(1);
	}

X.ft I
	/*
	 * Successfully got a directory listing.
	 * Print it out.
	 */
X.ft CW
	for (nl = result->readdir_res_u.list; nl != NULL; 
	  nl = nl->next) {
		printf("%s\n", nl->name);
	}
}
X.DE
Compile everything, and run.
X.DS
X.ft CW
sun%  \fBrpcgen dir.x\fP
sun%  \fBcc rls.c dir_clnt.c dir_xdr.c -o rls\fP
sun%  \fBcc dir_svc.c dir_proc.c dir_xdr.c -o dir_svc\fP

sun%  \fBdir_svc &\fP

moon%  \fBrls sun /usr/pub\fP
\&.
\&..
ascii
eqnchar
greek
kbd
marg8
tabclr
tabs
tabs4
moon%
X.DE
X.LP
X.IX debugging rpcgen "" \fIrpcgen\fP
A final note about 
X.I rpcgen :
The client program and the server procedure can be tested together 
as a single program by simply linking them with each other rather 
than with the client and server stubs.  The procedure calls will be
executed as ordinary local procedure calls and the program can be 
debugged with a local debugger such as 
X.I dbx .
When the program is working, the client program can be linked to 
the client stub produced by 
X.I rpcgen 
and the server procedures can be linked to the server stub produced
by 
X.I rpcgen .
X.SH
X.I NOTE :
\fIIf you do this, you may want to comment out calls to RPC library
routines, and have client-side routines call server routines
directly.\fP
X.LP
X.NH 1
\&The C-Preprocessor
X.IX rpcgen "C-preprocessor" \fIrpcgen\fP
X.LP
The C-preprocessor is  run on all input  files before they are
compiled, so all the preprocessor  directives are legal within a  ".x"
file. Four symbols may be defined, depending upon which output file is
getting generated. The symbols are:
X.TS
box tab (&);
lfI lfI
lfL l .
Symbol&Usage
_
RPC_HDR&for header-file output
RPC_XDR&for XDR routine output
RPC_SVC&for server-skeleton output
RPC_CLNT&for client stub output
X.TE
X.LP
Also, 
X.I rpcgen 
does  a little preprocessing   of its own. Any  line that
begins  with  a percent sign is passed  directly into the output file,
without any interpretation of the line.  Here is a simple example that
demonstrates the preprocessing features.
X.ie t .DS
X.el .DS L
X.ft I
/*
 * time.x: Remote time protocol
 */
X.ft CW
program TIMEPROG {
        version TIMEVERS {
                unsigned int TIMEGET(void) = 1;
        } = 1;
} = 44;

#ifdef RPC_SVC
%int *
%timeget_1()
%{
%        static int thetime;
%
%        thetime = time(0);
%        return (&thetime);
%}
#endif
X.DE
The '%' feature is not generally recommended, as there is no guarantee
that the compiler will stick the output where you intended.
X.NH 1
\&RPC Language
X.IX RPCL
X.IX rpcgen "RPC Language" \fIrpcgen\fP
X.LP
RPC language is an extension of XDR  language.   The sole extension is
the addition of the
X.I program 
type.  For a complete description of the XDR language syntax, see the
\fIeXternal Data Representation Standard: Protocol Specification\fP
chapter.  For a description of the RPC extensions to the XDR language,
see the
\fIRemote Procedure Calls: Protocol Specification\fP
chapter.
X.LP
However, XDR language is so close to C that if you know C, you know most
of it already.  We describe here  the syntax of the RPC language,
showing a  few examples along the way.   We also show how  the various
RPC and XDR type definitions get  compiled into C  type definitions in
the output header file.
X.KS
X.NH 2
\&Definitions
X.IX rpcgen definitions \fIrpcgen\fP
X.LP
An RPC language file consists of a series of definitions.
X.DS L
X.ft CW
    definition-list:
        definition ";"
        definition ";" definition-list
X.DE
X.KE
It recognizes five types of definitions. 
X.DS L
X.ft CW
    definition:
        enum-definition
        struct-definition
        union-definition
        typedef-definition
        const-definition
        program-definition
X.DE
X.NH 2
\&Structures
X.IX rpcgen structures \fIrpcgen\fP
X.LP
An XDR struct  is declared almost exactly like  its C counterpart.  It
looks like the following:
X.DS L
X.ft CW
    struct-definition:
        "struct" struct-ident "{"
            declaration-list
        "}"

    declaration-list:
        declaration ";"
        declaration ";" declaration-list
X.DE
As  an example, here is an  XDR structure to define  a two-dimensional
coordinate, and the C structure  that it  gets compiled into  in the
output header file.
X.DS
X.ft CW
   struct coord {             struct coord {
        int x;       -->           int x;
        int y;                     int y;
   };                         };
                              typedef struct coord coord;
X.DE
The output is identical to the  input, except  for the added
X.I typedef
at the end of  the output. This allows  one to use "coord" instead  of
"struct coord" when declaring items.
X.NH 2
\&Unions
X.IX rpcgen unions \fIrpcgen\fP
X.LP
XDR unions are discriminated unions, and look quite different from C
unions. They are more analogous to  Pascal variant records than they
are to C unions.
X.DS L
X.ft CW
    union-definition:
        "union" union-ident "switch" "(" declaration ")" "{"
            case-list
        "}"

    case-list:
        "case" value ":" declaration ";"
        "default" ":" declaration ";"
        "case" value ":" declaration ";" case-list
X.DE
Here is an example of a type that might be returned as the result of a
"read data" operation.  If there is no  error, return a block of data.
Otherwise, don't return anything.
X.DS L
X.ft CW
    union read_result switch (int errno) {
    case 0:
        opaque data[1024];
    default:
        void;
    };
X.DE
It gets compiled into the following:
X.DS L
X.ft CW
    struct read_result {
        int errno;
        union {
            char data[1024];
        } read_result_u;
    };
    typedef struct read_result read_result;
X.DE
Notice that the union component of the  output struct  has the name as
the type name, except for the trailing "_u".
X.NH 2
\&Enumerations
X.IX rpcgen enumerations \fIrpcgen\fP
X.LP
XDR enumerations have the same syntax as C enumerations.
X.DS L
X.ft CW
    enum-definition:
        "enum" enum-ident "{"
            enum-value-list
        "}"

    enum-value-list:
        enum-value
        enum-value "," enum-value-list

    enum-value:
        enum-value-ident 
        enum-value-ident "=" value
X.DE
Here is a short example of  an XDR enum,  and the C enum that  it gets
compiled into.
X.DS L
X.ft CW
     enum colortype {      enum colortype {
          RED = 0,              RED = 0,
          GREEN = 1,   -->      GREEN = 1,
          BLUE = 2              BLUE = 2,
     };                    };
                           typedef enum colortype colortype;
X.DE
X.NH 2
\&Typedef
X.IX rpcgen typedef \fIrpcgen\fP
X.LP
XDR typedefs have the same syntax as C typedefs.
X.DS L
X.ft CW
    typedef-definition:
        "typedef" declaration
X.DE
Here  is an example  that defines a  
X.I fname_type 
used  for declaring
file name strings that have a maximum length of 255 characters.
X.DS L
X.ft CW
    typedef string fname_type<255>; --> typedef char *fname_type;
X.DE
X.NH 2
\&Constants
X.IX rpcgen constants \fIrpcgen\fP
X.LP
XDR constants  symbolic constants  that may be  used wherever  a
integer constant is used, for example, in array size specifications.
X.DS L
X.ft CW
    const-definition:
        "const" const-ident "=" integer
X.DE
For example, the following defines a constant
X.I DOZEN 
equal to 12.
X.DS L
X.ft CW
    const DOZEN = 12;  -->  #define DOZEN 12
X.DE
X.NH 2
\&Programs
X.IX rpcgen programs \fIrpcgen\fP
X.LP
RPC programs are declared using the following syntax:
X.DS L
X.ft CW
    program-definition:
        "program" program-ident "{" 
            version-list
        "}" "=" value 

    version-list:
        version ";"
        version ";" version-list

    version:
        "version" version-ident "{"
            procedure-list 
        "}" "=" value

    procedure-list:
        procedure ";"
        procedure ";" procedure-list

    procedure:
        type-ident procedure-ident "(" type-ident ")" "=" value
X.DE
For example, here is the time protocol, revisited:
X.ie t .DS
X.el .DS L
X.ft I
/*
 * time.x: Get or set the time. Time is represented as number of seconds
 * since 0:00, January 1, 1970.
 */
X.ft CW
program TIMEPROG {
    version TIMEVERS {
        unsigned int TIMEGET(void) = 1;
        void TIMESET(unsigned) = 2;
    } = 1;
} = 44;        
X.DE
This file compiles into #defines in the output header file:
X.ie t .DS
X.el .DS L
X.ft CW
#define TIMEPROG 44
#define TIMEVERS 1
#define TIMEGET 1
#define TIMESET 2
X.DE
X.NH 2
\&Declarations
X.IX rpcgen declarations \fIrpcgen\fP
X.LP
In XDR, there are only four kinds of declarations.  
X.DS L
X.ft CW
    declaration:
        simple-declaration
        fixed-array-declaration
        variable-array-declaration
        pointer-declaration
X.DE
\fB1) Simple declarations\fP are just like simple C declarations.
X.DS L
X.ft CW
    simple-declaration:
        type-ident variable-ident
X.DE
Example:
X.DS L
X.ft CW
    colortype color;    --> colortype color;
X.DE
\fB2) Fixed-length Array Declarations\fP are just like C array declarations:
X.DS L
X.ft CW
    fixed-array-declaration:
        type-ident variable-ident "[" value "]"
X.DE
Example:
X.DS L
X.ft CW
    colortype palette[8];    --> colortype palette[8];
X.DE
\fB3) Variable-Length Array Declarations\fP have no explicit syntax 
in C, so XDR invents its own using angle-brackets.
X.DS L
X.ft CW
variable-array-declaration:
    type-ident variable-ident "<" value ">"
    type-ident variable-ident "<" ">"
X.DE
The maximum size is specified between the angle brackets. The size may
be omitted, indicating that the array may be of any size.
X.DS L
X.ft CW
    int heights<12>;    /* \fIat most 12 items\fP */
    int widths<>;       /* \fIany number of items\fP */
X.DE
Since  variable-length  arrays have no  explicit  syntax in  C,  these
declarations are actually  compiled into "struct"s.  For example,  the
"heights" declaration gets compiled into the following struct:
X.DS L
X.ft CW
    struct {
        u_int heights_len;  /* \fI# of items in array\fP */
        int *heights_val;   /* \fIpointer to array\fP */
    } heights;
X.DE
Note  that the number  of items in  the array is stored in  the "_len"
component  and the  pointer  to   the array is  stored  in  the "_val"
component. The first part of each of these component's names is the
same as the name of the declared XDR variable.
X.LP
\fB4) Pointer Declarations\fP are made in 
XDR  exactly as they  are  in C.  You  can't
really send pointers over the network,  but  you  can use XDR pointers
for sending recursive data types such as lists and trees.  The type is
actually called "optional-data", not "pointer", in XDR language.
X.DS L
X.ft CW
    pointer-declaration:
        type-ident "*" variable-ident
X.DE
Example:
X.DS L
X.ft CW
    listitem *next;  -->  listitem *next;
X.DE
X.NH 2
\&Special Cases
X.IX rpcgen "special cases" \fIrpcgen\fP
X.LP
There are a few exceptions to the rules described above.
X.LP
X.B Booleans:
C has no built-in boolean type. However, the RPC library does  a
boolean type   called 
X.I bool_t 
that   is either  
X.I TRUE 
or  
X.I FALSE .
Things declared as  type 
X.I bool 
in  XDR language  are  compiled  into
X.I bool_t 
in the output header file.
X.LP
Example:
X.DS L
X.ft CW
    bool married;  -->  bool_t married;
X.DE
X.B Strings:
C has  no built-in string  type, but  instead uses the null-terminated
"char *" convention.  In XDR  language, strings are declared using the
"string" keyword,  and  compiled into "char  *"s in the  output header
file. The  maximum size contained  in the angle brackets specifies the
maximum number of characters allowed in the  strings (not counting the
X.I NULL 
character). The maximum size may be left off, indicating a string
of arbitrary length.
X.LP
Examples:
X.DS L
X.ft CW
    string name<32>;    -->  char *name;
    string longname<>;  -->  char *longname;
X.DE
X.B "Opaque  Data:"
Opaque data is used in RPC and XDR to describe untyped  data, that is,
just  sequences of arbitrary  bytes.  It may be  declared  either as a
fixed or variable length array.
X.DS L
Examples:
X.ft CW
    opaque diskblock[512];  -->  char diskblock[512];

    opaque filedata<1024>;  -->  struct {
                                    u_int filedata_len;
                                    char *filedata_val;
                                 } filedata;
X.DE
X.B Voids:
In a void declaration, the variable is  not named.  The declaration is
just "void" and nothing else.  Void declarations can only occur in two
places: union definitions and program definitions (as the  argument or
result of a remote procedure).
Funky_Stuff
cd ..
echo more files to follow
exit
-- 
Please send comp.sources.unix-related mail to rsalz at uunet.uu.net.



More information about the Comp.sources.unix mailing list