.\" Must use -- tbl and pic -- with this one
.\" @(#)rpc.prog.ms 2.3 88/08/11 4.0 RPCSRC
.IX "Network Programming" "" "" "" PAGE MAJOR
.\" prevent excess underlining in nroff
.OH 'Remote Procedure Call Programming Guide''Page %'
.EH 'Page %''Remote Procedure Call Programming Guide'
\&Remote Procedure Call Programming Guide
.IX "RPC Programming Guide"
This document assumes a working knowledge of network theory. It is
intended for programmers who wish to write network applications using
remote procedure calls (explained below), and who want to understand
the RPC mechanisms usually hidden by the
is described in detail in the previous chapter, the
.I "\fBrpcgen\fP \fIProgramming Guide\fP".
.IX rpcgen "" \fIrpcgen\fP
Before attempting to write a network application, or to convert an
existing non-network application to run over the network, you may want to
understand the material in this chapter. However, for most applications,
you can circumvent the need to cope with the details presented here by using
.I "Generating XDR Routines"
section of that chapter contains the complete source for a working RPC
service\(ema remote directory listing service which uses
to generate XDR routines as well as client and server stubs.
What are remote procedure calls? Simply put, they are the high-level
communications paradigm used in the operating system.
RPC presumes the existence of
low-level networking mechanisms (such as TCP/IP and UDP/IP), and upon them
it implements a logical client to server communications system designed
specifically for the support of network applications. With RPC, the client
makes a procedure call to send a data packet to the server. When the
packet arrives, the server calls a dispatch routine, performs whatever
service is requested, sends back the reply, and the procedure call returns
The RPC interface can be seen as being divided into three layers.\**
For a complete specification of the routines in the remote procedure
.IX RPC "The Highest Layer"
The highest layer is totally transparent to the operating system,
machine and network upon which is is run. It's probably best to
think of this level as a way of
a \fIpart of\fP RPC proper. Programmers who write RPC routines
should (almost) always make this layer available to others by way
of a simple C front end that entirely hides the networking.
To illustrate, at this level a program can simply make a call to
a C routine which returns the number of users on a remote machine.
The user is not explicitly aware of using RPC \(em they simply
call a procedure, just as they would call
.IX RPC "The Middle Layer"
The middle layer is really \*QRPC proper.\*U Here, the user doesn't
need to consider details about sockets, the UNIX system, or other low-level
implementation mechanisms. They simply make remote procedure calls
to routines on other machines. The selling point here is simplicity.
It's this layer that allows RPC to pass the \*Qhello world\*U test \(em
simple things should be simple. The middle-layer routines are used
RPC calls are made with the system routines
The first two of these are the most fundamental:
obtains a unique system-wide procedure-identification number, and
actually executes a remote procedure call. At the middle level, a
is implemented by way of these two routines.
The middle layer is unfortunately rarely used in serious programming
due to its inflexibility (simplicity). It does not allow timeout
specifications or the choice of transport. It allows no UNIX
process control or flexibility in case of errors. It doesn't support
multiple kinds of call authentication. The programmer rarely needs
all these kinds of control, but one or two of them is often necessary.
.IX RPC "The Lowest Layer"
The lowest layer does allow these details to be controlled by the
programmer, and for that reason it is often necessary. Programs
written at this level are also most efficient, but this is rarely a
real issue \(em since RPC clients and servers rarely generate
Although this document only discusses the interface to C,
remote procedure calls can be made from any language.
Even though this document discusses RPC
when it is used to communicate
between processes on different machines,
it works just as well for communication
between different processes on the same machine.
Here is a diagram of the RPC paradigm:
\fBFigure 1-1\fI Network Communication with the Remote Reocedure Call\fR
L1: arrow down 1i "client " rjust "program " rjust
L2: line right 1.5i "\fIcallrpc\fP" "function"
move up 1.5i; line dotted down 6i; move up 4.5i
L3: arrow down 1i "invoke " rjust "service " rjust
L4: arrow right 1.5i "call" "service"
L5: arrow down 1i " service" ljust " executes" ljust
L6: arrow left 1.5i "\fIreturn\fP" "answer"
L7: arrow down 1i "request " rjust "completed " rjust
arrow left 1.5i "\fIreturn\fP" "reply"
L9: arrow down 1i "program " rjust "continues " rjust
line dashed down from L2 to L9
line dashed down from L4 to L7
line dashed up 1i from L3 "service " rjust "daemon " rjust
arrow dashed down 1i from L8
move left 1.2i from L2; move down
.IX "highest layer of RPC"
Imagine you're writing a program that needs to know
how many users are logged into a remote machine.
You can do this by calling the RPC library routine
fprintf(stderr, "usage: rnusers hostname\en");
if ((num = rnusers(argv[1])) < 0) {
fprintf(stderr, "error: rnusers\en");
printf("%d users on %s\en", num, argv[1]);
RPC library routines such as
are in the RPC services library
Thus, the program above should be compiled with
% cc \fIprogram.c -lrpcsvc\fP
like the other RPC library routines, is documented in section 3R
.I "System Interface Manual for the Sun Workstation" ,
the same section which documents the standard Sun RPC services.
manual page for an explanation of the documentation strategy
for these services and their RPC protocols.
Here are some of the RPC service library routines available to the
\fBTable 3-3\fI RPC Service Library Routines\RP
rnusers&Return number of users on remote machine
rusers&Return information about users on remote machine
havedisk&Determine if remote machine has disk
rstats&Get performance data from remote kernel
rwall&Write to specified remote machines
yppasswd&Update user password in Yellow Pages
Other RPC services \(em for example
\(em are not available to the C programmer as library routines.
have RPC program numbers so they can be invoked with
which will be discussed in the next section. Most of them also
protocol description files. (The
protocol compiler radically simplifies the process of developing
See the \fBrpcgen\fI Programming Guide\fR
for detailed information about
protocol description files).
.IX "intermediate layer of RPC"
.IX "RPC" "intermediate layer"
The simplest interface, which explicitly makes RPC calls, uses the
Using this method, the number of remote users can be gotten as follows:
#include <rpcsvc/rusers.h>
fprintf(stderr, "usage: nusers hostname\en");
if (stat = callrpc(argv[1],
RUSERSPROG, RUSERSVERS, RUSERSPROC_NUM,
xdr_void, 0, xdr_u_long, &nusers) != 0) {
printf("%d users on %s\en", nusers, argv[1]);
Each RPC procedure is uniquely defined by a program number,
version number, and procedure number. The program number
specifies a group of related remote procedures, each of
which has a different procedure number. Each program also
has a version number, so when a minor change is made to a
remote service (adding a new procedure, for example), a new
program number doesn't have to be assigned. When you want
to call a procedure to find the number of remote users, you
look up the appropriate program, version and procedure numbers
in a manual, just as you look up the name of a memory allocator
when you want to allocate memory.
The simplest way of making remote procedure calls is with the the RPC
It has eight parameters. The first is the name of the remote server
machine. The next three parameters are the program, version, and procedure
numbers\(emtogether they identify the procedure to be called.
The fifth and sixth parameters are an XDR filter and an argument to
be encoded and passed to the remote procedure.
The final two parameters are a filter for decoding the results
returned by the remote procedure and a pointer to the place where
the procedure's results are to be stored. Multiple arguments and
results are handled by embedding them in structures. If
completes successfully, it returns zero; else it returns a nonzero
value. The return codes (of type
.IX "enum clnt_stat (in RPC programming)" "" "\fIenum clnt_stat\fP (in RPC programming)"
cast into an integer) are found in
Since data types may be represented differently on different machines,
needs both the type of the RPC argument, as well as
a pointer to the argument itself (and similarly for the result). For
as its first return parameter, which says
that the result is of type
as its second return parameter,
which is a pointer to where the long result will be placed. Since
takes no argument, the argument parameter of
After trying several times to deliver a message, if
gets no answer, it returns with an error code.
The delivery mechanism is UDP,
which stands for User Datagram Protocol.
Methods for adjusting the number of retries
or for using a different protocol require you to use the lower
layer of the RPC library, discussed later in this document.
The remote server procedure
corresponding to the above might look like this:
* Code here to compute the number of users
* and place result in variable \fInusers\fP.
It takes one argument, which is a pointer to the input
of the remote procedure call (ignored in our example),
and it returns a pointer to the result.
In the current version of C,
character pointers are the generic pointers,
so both the input argument and the return value are cast to
Normally, a server registers all of the RPC calls it plans
to handle, and then goes into an infinite loop waiting to service requests.
In this example, there is only a single procedure
to register, so the main body of the server would look like this:
#include <rpcsvc/rusers.h>
registerrpc(RUSERSPROG, RUSERSVERS, RUSERSPROC_NUM,
nuser, xdr_void, xdr_u_long);
svc_run(); /* \fINever returns\fP */
fprintf(stderr, "Error: svc_run returned!\en");
routine registers a C procedure as corresponding to a
given RPC procedure number. The first three parameters,
are the program, version, and procedure numbers
of the remote procedure to be registered;
is the name of the local procedure that implements the remote
are the XDR filters for the remote procedure's arguments and
results, respectively. (Multiple arguments or multiple results
are passed as structures).
Only the UDP transport mechanism can use
thus, it is always safe in conjunction with calls generated by
Warning: the UDP transport mechanism can only deal with
arguments and results less than 8K bytes in length.
After registering the local procedure, the server program's
the RPC library's remote procedure dispatcher. It is this
function that calls the remote procedures in response to RPC
call messages. Note that the dispatcher takes care of decoding
remote procedure arguments and encoding results, using the XDR
filters specified when the remote procedure was registered.
\&Assigning Program Numbers
.IX "program number assignment"
.IX "assigning program numbers"
Program numbers are assigned in groups of
according to the following chart:
0x0 - 0x1fffffff \fRDefined by Sun\fP
0x20000000 - 0x3fffffff \fRDefined by user\fP
0x40000000 - 0x5fffffff \fRTransient\fP
0x60000000 - 0x7fffffff \fRReserved\fP
0x80000000 - 0x9fffffff \fRReserved\fP
0xa0000000 - 0xbfffffff \fRReserved\fP
0xc0000000 - 0xdfffffff \fRReserved\fP
0xe0000000 - 0xffffffff \fRReserved\fP
Sun Microsystems administers the first group of numbers, which
should be identical for all Sun customers. If a customer
develops an application that might be of general interest, that
application should be given an assigned number in the first
range. The second group of numbers is reserved for specific
customer applications. This range is intended primarily for
debugging new programs. The third group is reserved for
applications that generate program numbers dynamically. The
final groups are reserved for future use, and should not be
To register a protocol specification, send a request by network
Please include a compilable
\*Q.x\*U file describing your protocol.
You will be given a unique program number in return.
.IX administration "of RPC"
The RPC program numbers and protocol specifications
of standard Sun RPC services can be
found in the include files in
.I "/usr/include/rpcsvc" .
These services, however, constitute only a small subset
of those which have been registered. The complete list of
registered programs, as of the time when this manual was
\fBTable 3-2\fI RPC Registered Programs\fR
RPC Number&Program&Description
100000&PMAPPROG&portmapper
100001&RSTATPROG&remote stats
100002&RUSERSPROG&remote users
100004&YPPROG&Yellow Pages
100005&MOUNTPROG&mount demon
100006&DBXPROG&remote dbx
100007&YPBINDPROG&yp binder
100008&WALLPROG&shutdown msg
100009&YPPASSWDPROG&yppasswd server
100010ÐERSTATPROGðer stats
100011&RQUOTAPROG&disk quotas
100012&SPRAYPROG&spray packets
100013&IBM3270PROG&3270 mapper
100014&IBMRJEPROG&RJE mapper
100015&SELNSVCPROG&selection service
100016&RDATABASEPROG&remote database access
100017&REXECPROG&remote execution
100018&ALICEPROG&Alice Office Automation
100019&SCHEDPROG&scheduling service
100020&LOCKPROG&local lock manager
100021&NETLOCKPROG&network lock manager
100022&X25PROG&x.25 inr protocol
100023&STATMON1PROG&status monitor 1
100024&STATMON2PROG&status monitor 2
100025&SELNLIBPROG&selection library
100026&BOOTPARAMPROG&boot parameters service
100027&MAZEPROG&mazewars game
100028&YPUPDATEPROG&yp update
100029&KEYSERVEPROG&key server
100030&SECURECMDPROG&secure login
100031&NETFWDIPROG&nfs net forwarder init
100032&NETFWDTPROG&nfs net forwarder trans
100033&SUNLINKMAP_PROG&sunlink MAP
100034&NETMONPROG&network monitor
100035&DBASEPROG&lightweight database
100036&PWDAUTHPROG&password authorization
100037&TFSPROG&translucent file svc
100038&NSEPROG&nse server
100039&NSE_ACTIVATE_PROG&nse activate daemon
150001&PCNFSDPROG&pc passwd authorization
200000&PYRAMIDLOCKINGPROG&Pyramid-locking
200001&PYRAMIDSYS5&Pyramid-sys5
200002&CADDS_IMAGE&CV cadds_image
300001&ADT_RFLOCKPROG&ADT file locking
\&Passing Arbitrary Data Types
.IX "arbitrary data types"
In the previous example, the RPC call passes a single
RPC can handle arbitrary data structures, regardless of
different machines' byte orders or structure layout conventions,
by always converting them to a network standard called
.I "External Data Representation"
sending them over the wire.
The process of converting from a particular machine representation
and the reverse process is called
The type field parameters of
can be a built-in procedure like
in the previous example, or a user supplied one.
XDR has these built-in type routines:
.IX RPC "built-in routines"
xdr_int() xdr_u_int() xdr_enum()
xdr_long() xdr_u_long() xdr_bool()
xdr_short() xdr_u_short() xdr_wrapstring()
exists, but cannot be used with
which only pass two parameters to their XDR routines.
has only two parameters, and is thus OK. It calls
As an example of a user-defined type routine,
if you wanted to send the structure
callrpc(hostname, PROGNUM, VERSNUM, PROCNUM,
xdr_simple, &simple ...);
xdr_simple(xdrsp, simplep)
if (!xdr_int(xdrsp, &simplep->a))
if (!xdr_short(xdrsp, &simplep->b))
An XDR routine returns nonzero (true in the sense of C) if it
completes successfully, and zero otherwise.
A complete description of XDR is in the
.I "XDR Protocol Specification"
section of this manual, only few implementation examples are
In addition to the built-in primitives,
there are also the prefabricated building blocks:
xdr_array() xdr_bytes() xdr_reference()
xdr_vector() xdr_union() xdr_pointer()
xdr_string() xdr_opaque()
To send a variable array of integers,
you might package them up as a structure like this
and make an RPC call such as
callrpc(hostname, PROGNUM, VERSNUM, PROCNUM,
xdr_varintarr(xdrsp, arrp)
return (xdr_array(xdrsp, &arrp->data, &arrp->arrlnth,
MAXLEN, sizeof(int), xdr_int));
This routine takes as parameters the XDR handle,
a pointer to the array, a pointer to the size of the array,
the maximum allowable array size,
the size of each array element,
and an XDR routine for handling each array element.
If the size of the array is known in advance, one can use
which serializes fixed-length arrays.
xdr_intarr(xdrsp, intarr)
return (xdr_vector(xdrsp, intarr, SIZE, sizeof(int),
XDR always converts quantities to 4-byte multiples when serializing.
Thus, if either of the examples above involved characters
instead of integers, each character would occupy 32 bits.
That is the reason for the XDR routine
except that it packs characters;
has four parameters, similar to the first four parameters of
For null-terminated strings, there is also the
routine, which is the same as
without the length parameter.
On serializing it gets the string length from
and on deserializing it creates a null-terminated string.
Here is a final example that calls the previously written
as well as the built-in functions
xdr_finalexample(xdrsp, finalp)
struct finalexample *finalp;
if (!xdr_string(xdrsp, &finalp->string, MAXSTRLEN))
if (!xdr_reference(xdrsp, &finalp->simplep,
sizeof(struct simple), xdr_simple);
Note that we could as easily call
.IX "lowest layer of RPC"
In the examples given so far,
RPC takes care of many details automatically for you.
In this section, we'll show you how you can change the defaults
by using lower layers of the RPC library.
It is assumed that you are familiar with sockets
and the system calls for dealing with them.
There are several occasions when you may need to use lower layers of
RPC. First, you may need to use TCP, since the higher layer uses UDP,
which restricts RPC calls to 8K bytes of data. Using TCP permits calls
to send long streams of data.
section below. Second, you may want to allocate and free memory
while serializing or deserializing with XDR routines.
There is no call at the higher level to let
you free memory explicitly.
For more explanation, see the
.I "Memory Allocation with XDR"
Third, you may need to perform authentication
on either the client or server side, by supplying
credentials or verifying them.
See the explanation in the
\&More on the Server Side
program shown below does the same thing as the one using
above, but is written using a lower layer of the RPC package:
#include <rpcsvc/rusers.h>
transp = svcudp_create(RPC_ANYSOCK);
fprintf(stderr, "can't create an RPC server\en");
pmap_unset(RUSERSPROG, RUSERSVERS);
if (!svc_register(transp, RUSERSPROG, RUSERSVERS,
fprintf(stderr, "can't register RUSER service\en");
svc_run(); /* \fINever returns\fP */
fprintf(stderr, "should never reach this point\en");
switch (rqstp->rq_proc) {
if (!svc_sendreply(transp, xdr_void, 0))
fprintf(stderr, "can't reply to RPC call\en");
* Code here to compute the number of users
* and assign it to the variable \fInusers\fP
if (!svc_sendreply(transp, xdr_u_long, &nusers))
fprintf(stderr, "can't reply to RPC call\en");
First, the server gets a transport handle, which is used
for receiving and replying to RPC messages.
If you require a more reliable protocol, call
the RPC library creates a socket
on which to receive and reply to RPC calls. Otherwise,
expects its argument to be a valid socket number.
If you specify your own socket, it can be bound or unbound.
If it is bound to a port by the user, the port numbers of
(the low-level client routine) must match.
If the user specifies the
argument, the RPC library routines will open sockets.
Otherwise they will expect the user to do so. The routines
will cause the RPC library routines to
their socket if it is not bound already.
A service may choose to register its port number with the
local portmapper service. This is done is done by specifying
a non-zero protocol number in
Incidently, a client can discover the server's port number by
consulting the portmapper on their server's machine. This can
be done automatically by specifying a zero port number in
any previous trace of it is erased before restarting.
from the port mapper's tables.
Finally, we associate the program number for
is normally the protocol being used,
there are no XDR routines involved
in the registration process.
Also, registration is done on the program,
rather than procedure, level.
must call and dispatch the appropriate XDR routines
based on the procedure number.
two things are handled by
The first is that procedure
(currently zero) returns with no results.
This can be used as a simple test
for detecting if a remote program is running.
Second, there is a check for invalid procedure numbers.
is called to handle the error.
The user service routine serializes the results and returns
them to the RPC caller via
Its first parameter is the
handle, the second is the XDR routine,
and the third is a pointer to the data to be returned.
Not illustrated above is how a server
handles an RPC program that receives data.
As an example, we can add a procedure
depending on whether there are nusers logged on.
if (!svc_getargs(transp, xdr_u_int, &nuserquery) {
* Code to set \fInusers\fP = number of users
if (nuserquery == nusers)
if (!svc_sendreply(transp, xdr_bool, &bool)) {
fprintf(stderr, "can't reply to RPC call\en");
and a pointer to where the input is to be placed as arguments.
\&Memory Allocation with XDR
.IX "memory allocation with XDR"
.IX XDR "memory allocation"
XDR routines not only do input and output,
they also do memory allocation.
This is why the second parameter of
is a pointer to an array, rather than the array itself.
allocates space for the array and returns a pointer to it,
putting the size of the array in the third argument.
As an example, consider the following XDR routine
which deals with a fixed array of bytes with length
xdr_chararr1(xdrsp, chararr)
return (xdr_bytes(xdrsp, &p, &len, SIZE));
If space has already been allocated in
it can be called from a server like this:
svc_getargs(transp, xdr_chararr1, chararr);
If you want XDR to do the allocation,
you would have to rewrite this routine in the following way:
xdr_chararr2(xdrsp, chararrp)
return (xdr_bytes(xdrsp, charrarrp, &len, SIZE));
Then the RPC call might look like this:
svc_getargs(transp, xdr_chararr2, &arrptr);
svc_freeargs(transp, xdr_chararr2, &arrptr);
Note that, after being used, the character array can be freed with
will not attempt to free any memory if the variable indicating it
is NULL. For example, in the the routine
was NULL, then it would not be freed. The same is true for
To summarize, each XDR routine is responsible
for serializing, deserializing, and freeing memory.
When an XDR routine is called from
the serializing part is used.
the deserializer is used.
the memory deallocator is used. When building simple examples like those
in this section, a user doesn't have to worry
.I "External Data Representation: Sun Technical Notes"
for examples of more sophisticated XDR routines that determine
which of the three modes they are in and adjust their behavior accordingly.
you have no control over the RPC delivery
mechanism or the socket used to transport the data.
To illustrate the layer of RPC that lets you adjust these
parameters, consider the following code to call the
#include <rpcsvc/rusers.h>
struct timeval pertry_timeout, total_timeout;
struct sockaddr_in server_addr;
enum clnt_stat clnt_stat;
fprintf(stderr, "usage: nusers hostname\en");
if ((hp = gethostbyname(argv[1])) == NULL) {
fprintf(stderr, "can't get addr for %s\en",argv[1]);
pertry_timeout.tv_sec = 3;
pertry_timeout.tv_usec = 0;
bcopy(hp->h_addr, (caddr_t)&server_addr.sin_addr,
server_addr.sin_family = AF_INET;
server_addr.sin_port = 0;
if ((client = clntudp_create(&server_addr, RUSERSPROG,
RUSERSVERS, pertry_timeout, &sock)) == NULL) {
clnt_pcreateerror("clntudp_create");
total_timeout.tv_sec = 20;
total_timeout.tv_usec = 0;
clnt_stat = clnt_call(client, RUSERSPROC_NUM, xdr_void,
0, xdr_u_long, &nusers, total_timeout);
if (clnt_stat != RPC_SUCCESS) {
clnt_perror(client, "rpc");
pointer rather than a host name. The parameters to
pointer, the procedure number,
the XDR routine for serializing the argument,
a pointer to the argument,
the XDR routine for deserializing the return value,
a pointer to where the return value will be placed,
and the time in seconds to wait for a reply.
pointer is encoded with the transport mechanism.
pointer. To get TCP (Transmission Control Protocol), you would use
are the server address, the program number, the version number,
a timeout value (between tries), and a pointer to a socket.
is the total time to wait for a response.
Thus, the number of tries is the
always deallocates the space associated with the
handle. It closes the socket associated with the
handle, however, only if the RPC library opened it. It the
socket was opened by the user, it stays open. This makes it
possible, in cases where there are multiple client handles
using the same socket, to destroy one handle without closing
the socket that other handles are using.
To make a stream connection, the call to
is replaced with a call to
clnttcp_create(&server_addr, prognum, versnum, &sock,
There is no timeout argument; instead, the receive and send buffer
sizes must be specified. When the
call is made, a TCP connection is established.
handle would use this connection.
The server side of an RPC call using TCP has
transp = svctcp_create(RPC_ANYSOCK, 0, 0);
The last two arguments to
are send and receive sizes respectively. If `0' is specified for
either of these, the system chooses a reasonable default.
.IX "RPC" "miscellaneous features"
.IX "miscellaneous RPC features"
This section discusses some other aspects of RPC
that are occasionally useful.
\&Select on the Server Side
.IX RPC select() RPC \fIselect()\fP
.IX select() "" \fIselect()\fP "on the server side"
Suppose a process is processing RPC requests
while performing some other activity.
If the other activity involves periodically updating a data structure,
the process can set an alarm signal before calling
But if the other activity
involves waiting on a a file descriptor, the
int dtbsz = getdtablesize();
switch (select(dtbsz, &readfds, NULL,NULL,NULL)) {
All you need to know are the file descriptors
of the socket(s) associated with the programs you are waiting on.
Thus you can have your own
.IX select() "" \fIselect()\fP
that waits on both the RPC socket,
and your own descriptors. Note that
is a bit mask of all the file descriptors that RPC is using for
services. It can change everytime that
RPC library routine is called, because descriptors are constantly
being opened and closed, for example for TCP connections.
is a daemon that converts RPC program numbers
into DARPA protocol port numbers; see the
man page. You can't do broadcast RPC without the portmapper.
Here are the main differences between
broadcast RPC and normal RPC calls:
Normal RPC expects one answer, whereas
broadcast RPC expects many answers
(one or more answer from each responding machine).
Broadcast RPC can only be supported by packet-oriented (connectionless)
transport protocols like UPD/IP.
The implementation of broadcast RPC
treats all unsuccessful responses as garbage by filtering them out.
Thus, if there is a version mismatch between the
broadcaster and a remote service,
the user of broadcast RPC never knows.
All broadcast messages are sent to the portmap port.
Thus, only services that register themselves with their portmapper
are accessible via the broadcast RPC mechanism.
Broadcast requests are limited in size to the MTU (Maximum Transfer
Unit) of the local network. For Ethernet, the MTU is 1500 bytes.
.IX "broadcast RPC" synopsis
.IX "RPC" "broadcast synopsis"
#include <rpc/pmap_clnt.h>
enum clnt_stat clnt_stat;
clnt_stat = clnt_broadcast(prognum, versnum, procnum,
inproc, in, outproc, out, eachresult)
u_long prognum; /* \fIprogram number\fP */
u_long versnum; /* \fIversion number\fP */
u_long procnum; /* \fIprocedure number\fP */
xdrproc_t inproc; /* \fIxdr routine for args\fP */
caddr_t in; /* \fIpointer to args\fP */
xdrproc_t outproc; /* \fIxdr routine for results\fP */
caddr_t out; /* \fIpointer to results\fP */
bool_t (*eachresult)();/* \fIcall with each result gotten\fP */
is called each time a valid result is obtained.
It returns a boolean that indicates
whether or not the user wants more responses.
done = eachresult(resultsp, raddr)
struct sockaddr_in *raddr; /* \fIAddr of responding machine\fP */
then broadcasting stops and
Otherwise, the routine waits for another response.
The request is rebroadcast
after a few seconds of waiting.
If no responses come back,
The RPC architecture is designed so that clients send a call message,
and wait for servers to reply that the call succeeded.
This implies that clients do not compute
while servers are processing a call.
This is inefficient if the client does not want or need
an acknowledgement for every message sent.
It is possible for clients to continue computing
while waiting for a response,
using RPC batch facilities.
RPC messages can be placed in a \*Qpipeline\*U of calls
to a desired server; this is called batching.
1) each RPC call in the pipeline requires no response from the server,
and the server does not send a response message; and
2) the pipeline of calls is transported on a reliable
byte stream transport such as TCP/IP.
Since the server does not respond to every call,
the client can generate new calls in parallel
with the server executing previous calls.
Furthermore, the TCP/IP implementation can buffer up
many call messages, and send them to the server in one
system call. This overlapped execution
greatly decreases the interprocess communication overhead of
the client and server processes,
and the total elapsed time of a series of calls.
Since the batched calls are buffered,
the client should eventually do a nonbatched call
in order to flush the pipeline.
A contrived example of batching follows.
Assume a string rendering service (like a window system)
has two similar calls: one renders a string and returns void results,
while the other renders a string and remains silent.
The service (using the TCP/IP transport) may look like:
#include <suntool/windows.h>
transp = svctcp_create(RPC_ANYSOCK, 0, 0);
fprintf(stderr, "can't create an RPC server\en");
pmap_unset(WINDOWPROG, WINDOWVERS);
if (!svc_register(transp, WINDOWPROG, WINDOWVERS,
windowdispatch, IPPROTO_TCP)) {
fprintf(stderr, "can't register WINDOW service\en");
svc_run(); /* \fINever returns\fP */
fprintf(stderr, "should never reach this point\en");
windowdispatch(rqstp, transp)
switch (rqstp->rq_proc) {
if (!svc_sendreply(transp, xdr_void, 0))
fprintf(stderr, "can't reply to RPC call\en");
if (!svc_getargs(transp, xdr_wrapstring, &s)) {
fprintf(stderr, "can't decode arguments\en");
* Tell caller he screwed up
* Code here to render the string \fIs\fP
if (!svc_sendreply(transp, xdr_void, NULL))
fprintf(stderr, "can't reply to RPC call\en");
case RENDERSTRING_BATCHED:
if (!svc_getargs(transp, xdr_wrapstring, &s)) {
fprintf(stderr, "can't decode arguments\en");
* We are silent in the face of protocol errors
* Code here to render string s, but send no reply!
* Now free string allocated while decoding arguments
svc_freeargs(transp, xdr_wrapstring, &s);
Of course the service could have one procedure
that takes the string and a boolean
to indicate whether or not the procedure should respond.
In order for a client to take advantage of batching,
the client must perform RPC calls on a TCP-based transport
and the actual calls must have the following attributes:
1) the result's XDR routine must be zero
and 2) the RPC call's timeout must be zero.
Here is an example of a client that uses batching to render a
bunch of strings; the batching is flushed when the client gets
#include <suntool/windows.h>
struct timeval pertry_timeout, total_timeout;
struct sockaddr_in server_addr;
enum clnt_stat clnt_stat;
char buf[1000], *s = buf;
if ((client = clnttcp_create(&server_addr,
WINDOWPROG, WINDOWVERS, &sock, 0, 0)) == NULL) {
perror("clnttcp_create");
total_timeout.tv_sec = 0;
total_timeout.tv_usec = 0;
while (scanf("%s", s) != EOF) {
clnt_stat = clnt_call(client, RENDERSTRING_BATCHED,
xdr_wrapstring, &s, NULL, NULL, total_timeout);
if (clnt_stat != RPC_SUCCESS) {
clnt_perror(client, "batched rpc");
/* \fINow flush the pipeline\fP */
total_timeout.tv_sec = 20;
clnt_stat = clnt_call(client, NULLPROC, xdr_void, NULL,
xdr_void, NULL, total_timeout);
if (clnt_stat != RPC_SUCCESS) {
clnt_perror(client, "rpc");
Since the server sends no message,
the clients cannot be notified of any of the failures that may occur.
Therefore, clients are on their own when it comes to handling errors.
The above example was completed to render
all of the (2000) lines in the file
The rendering service did nothing but throw the lines away.
The example was run in the following four configurations:
1) machine to itself, regular RPC;
2) machine to itself, batched RPC;
3) machine to another, regular RPC; and
4) machine to another, batched RPC.
The results are as follows:
only requires six seconds.
These timings show the advantage of protocols
that allow for overlapped execution,
though these protocols are often hard to design.
.IX "RPC" "authentication"
In the examples presented so far,
the caller never identified itself to the server,
and the server never required an ID from the caller.
Clearly, some network services, such as a network filesystem,
require stronger security than what has been presented so far.
In reality, every RPC call is authenticated by
the RPC package on the server, and similarly,
the RPC client package generates and sends authentication parameters.
Just as different transports (TCP/IP or UDP/IP)
can be used when creating RPC clients and servers,
different forms of authentication can be associated with RPC clients;
the default authentication type used as a default is type
The authentication subsystem of the RPC package is open ended.
That is, numerous types of authentication are easy to support.
.IX "UNIX Authentication"
.IP "\fIThe Client Side\fP"
When a caller creates a new RPC client handle as in:
clnt = clntudp_create(address, prognum, versnum,
the appropriate transport instance defaults
the associate authentication handle to be
clnt->cl_auth = authnone_create();
The RPC client can choose to use
style authentication by setting
after creating the RPC client handle:
clnt->cl_auth = authunix_create_default();
This causes each RPC call associated with
to carry with it the following authentication credentials structure:
* UNIX style credentials.
u_long aup_time; /* \fIcredentials creation time\fP */
char *aup_machname; /* \fIhost name where client is\fP */
int aup_uid; /* \fIclient's UNIX effective uid\fP */
int aup_gid; /* \fIclient's current group id\fP */
u_int aup_len; /* \fIelement length of aup_gids\fP */
int *aup_gids; /* \fIarray of groups user is in\fP */
.I authunix_create_default()
by invoking the appropriate system calls.
Since the RPC user created this new style of authentication,
the user is responsible for destroying it with:
auth_destroy(clnt->cl_auth);
This should be done in all cases, to conserve memory.
.IP "\fIThe Server Side\fP"
Service implementors have a harder time dealing with authentication issues
since the RPC package passes the service dispatch routine a request
that has an arbitrary authentication style associated with it.
Consider the fields of a request handle passed to a service dispatch routine:
u_long rq_prog; /* \fIservice program number\fP */
u_long rq_vers; /* \fIservice protocol vers num\fP */
u_long rq_proc; /* \fIdesired procedure number\fP */
struct opaque_auth rq_cred; /* \fIraw credentials from wire\fP */
caddr_t rq_clntcred; /* \fIcredentials (read only)\fP */
is mostly opaque, except for one field of interest:
the style or flavor of authentication credentials:
* Authentication info. Mostly opaque to the programmer.
enum_t oa_flavor; /* \fIstyle of credentials\fP */
caddr_t oa_base; /* \fIaddress of more auth stuff\fP */
u_int oa_length; /* \fInot to exceed \fIMAX_AUTH_BYTES */
The RPC package guarantees the following
to the service dispatch routine:
is well formed. Thus the service implementor may inspect the request's
to determine which style of authentication the caller used.
The service implementor may also wish to inspect the other fields of
if the style is not one of the styles supported by the RPC package.
or points to a well formed structure
that corresponds to a supported style of authentication credentials.
style is currently supported, so (currently)
could be cast to a pointer to an
the service implementor may wish to inspect the other (opaque) fields of
in case the service knows about a new type of authentication
that the RPC package does not know about.
Our remote users service example can be extended so that
it computes results for all users except UID 16:
struct authunix_parms *unix_cred;
* we don't care about authentication for null proc
if (rqstp->rq_proc == NULLPROC) {
if (!svc_sendreply(transp, xdr_void, 0)) {
fprintf(stderr, "can't reply to RPC call\en");
switch (rqstp->rq_cred.oa_flavor) {
(struct authunix_parms *)rqstp->rq_clntcred;
uid = unix_cred->aup_uid;
switch (rqstp->rq_proc) {
* make sure caller is allowed to call this proc
svcerr_systemerr(transp);
* Code here to compute the number of users
* and assign it to the variable \fInusers\fP
if (!svc_sendreply(transp, xdr_u_long, &nusers)) {
fprintf(stderr, "can't reply to RPC call\en");
A few things should be noted here.
First, it is customary not to check
the authentication parameters associated with the
Second, if the authentication parameter's type is not suitable
for your service, you should call
And finally, the service protocol itself should return status
for access denied; in the case of our example, the protocol
does not have such a status, so we call the service primitive
The last point underscores the relation between
the RPC authentication package and the services;
and not with individual services'
The services themselves must implement their own access control policies
and reflect these policies as return statuses in their protocols.
UNIX authentication is quite easy to defeat. Instead of using
.I authunix_create_default (),
and then modify the RPC authentication handle it returns by filling in
whatever user ID and hostname they wish the server to think they have.
DES authentication is thus recommended for people who want more security
than UNIX authentication offers.
The details of the DES authentication protocol are complicated and
.I "Remote Procedure Calls: Protocol Specification"
In order for DES authentication to work, the
daemon must be running on both the server and client machines. The
users on these machines need public keys assigned by the network
database. And, they need to have decrypted their secret keys
using their login password. This automatically happens when one
or can be done manually using
explains more how to setup secure networking.
If a client wishes to use DES authentication, it must set its
authentication handle appropriately. Here is an example:
authdes_create(servername, 60, &server_addr, NULL);
The first argument is the network name or \*Qnetname\*U of the owner of
the server process. Typically, server processes are root processes
and their netname can be derived using the following call:
char servername[MAXNETNAMELEN];
host2netname(servername, rhostname, NULL);
is the hostname of the machine the server process is running on.
to contain this root process's netname. If the
server process was run by a regular user, one could use the call
instead. Here is an example for a server process with the same user
char servername[MAXNETNAMELEN];
user2netname(servername, getuid(), NULL);
The last argument to both of these calls,
is the name of the naming domain where the server is located. The
used here means \*Quse the local domain name.\*U
is a lifetime for the credential. Here it is set to sixty
seconds. What that means is that the credential will expire 60
seconds from now. If some mischievous user tries to reuse the
credential, the server RPC subsystem will recognize that it has
expired and not grant any requests. If the same mischievous user
tries to reuse the credential within the sixty second lifetime,
he will still be rejected because the server RPC subsystem
remembers which credentials it has already seen in the near past,
and will not grant requests to duplicates.
is the address of the host to synchronize with. In order for DES
authentication to work, the server and client must agree upon the
time. Here we pass the address of the server itself, so the
client and server will both be using the same time: the server's
time. The argument can be
which means \*Qdon't bother synchronizing.\*U You should only do this
if you are sure the client and server are already synchronized.
is the address of a DES encryption key to use for encrypting
timestamps and data. If this argument is
as it is in this example, a random key will be chosen. The client
may find out the encryption key being used by consulting the
field of the authentication handle.
The server side is a lot simpler than the client side. Here is the
previous example rewritten to use
#include <rpc/auth_des.h>
struct authdes_cred *des_cred;
* we don't care about authentication for null proc
if (rqstp->rq_proc == NULLPROC) {
/* \fIsame as before\fP */
switch (rqstp->rq_cred.oa_flavor) {
(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);
* The rest is the same as before
Note the use of the routine
it takes a network ID and converts to a unix ID.
also supplies the group IDs which we don't use in this example,
but which may be useful to other UNIX programs.
.IX inetd "" "using \fIinetd\fP"
An RPC server can be started from
The only difference from the usual code is that the service
creation routine should be called in the following form:
transp = svcudp_create(0); /* \fIFor UDP\fP */
transp = svctcp_create(0,0,0); /* \fIFor listener TCP sockets\fP */
transp = svcfd_create(0,0,0); /* \fIFor connected TCP sockets\fP */
passes a socket as file descriptor 0.
svc_register(transp, PROGNUM, VERSNUM, service, 0);
with the final flag as 0,
since the program would already be registered by
Remember that if you want to exit
from the server process and return control to
you need to explicitly exit, since
for RPC services is in one of the following two forms:
p_name/version dgram rpc/udp wait/nowait user server args
p_name/version stream rpc/tcp wait/nowait user server args
is the symbolic name of the program as it appears in
is the program implementing the server,
are the program and version numbers of the service.
For more information, see
If the same program handles multiple versions,
then the version number can be a range,
rstatd/1-2 dgram rpc/udp wait root /usr/etc/rpc.rstatd
By convention, the first version number of program
and the most recent version is
Suppose there is a new version of the
then a server that wants to support both versions
would do a double register.
if (!svc_register(transp, RUSERSPROG, RUSERSVERS_ORIG,
fprintf(stderr, "can't register RUSER service\en");
if (!svc_register(transp, RUSERSPROG, RUSERSVERS_SHORT,
fprintf(stderr, "can't register RUSER service\en");
Both versions can be handled by the same C procedure:
switch (rqstp->rq_proc) {
if (!svc_sendreply(transp, xdr_void, 0)) {
fprintf(stderr, "can't reply to RPC call\en");
* Code here to compute the number of users
* and assign it to the variable \fInusers\fP
switch (rqstp->rq_vers) {
if (!svc_sendreply(transp, xdr_u_long,
fprintf(stderr,"can't reply to RPC call\en");
if (!svc_sendreply(transp, xdr_u_short,
fprintf(stderr,"can't reply to RPC call\en");
Here is an example that is essentially
call takes its standard input and sends it to the server
which prints it on standard output.
This also illustrates an XDR procedure that behaves differently
on serialization than on deserialization.
* on decode, read from wire, write onto fp
* on encode, read from fp, write onto wire
if (xdrs->x_op == XDR_FREE)/* nothing to free */
if (xdrs->x_op == XDR_ENCODE) {
if ((size = fread(buf, sizeof(char), BUFSIZ,
fp)) == 0 && ferror(fp)) {
fprintf(stderr, "can't fread\en");
if (!xdr_bytes(xdrs, &p, &size, BUFSIZ))
if (xdrs->x_op == XDR_DECODE) {
if (fwrite(buf, sizeof(char), size,
fprintf(stderr, "can't fwrite\en");
fprintf(stderr, "usage: %s servername\en", argv[0]);
if ((err = callrpctcp(argv[1], RCPPROG, RCPPROC,
RCPVERS, xdr_rcp, stdin, xdr_void, 0) != 0)) {
fprintf(stderr, "can't make RPC call\en");
callrpctcp(host, prognum, procnum, versnum,
inproc, in, outproc, out)
xdrproc_t inproc, outproc;
struct sockaddr_in server_addr;
int socket = RPC_ANYSOCK;
enum clnt_stat clnt_stat;
struct timeval total_timeout;
if ((hp = gethostbyname(host)) == NULL) {
fprintf(stderr, "can't get addr for '%s'\en", host);
bcopy(hp->h_addr, (caddr_t)&server_addr.sin_addr,
server_addr.sin_family = AF_INET;
server_addr.sin_port = 0;
if ((client = clnttcp_create(&server_addr, prognum,
versnum, &socket, BUFSIZ, BUFSIZ)) == NULL) {
total_timeout.tv_sec = 20;
total_timeout.tv_usec = 0;
clnt_stat = clnt_call(client, procnum,
inproc, in, outproc, out, total_timeout);
register SVCXPRT *transp;
int rcp_service(), xdr_rcp();
if ((transp = svctcp_create(RPC_ANYSOCK,
BUFSIZ, BUFSIZ)) == NULL) {
fprintf("svctcp_create: error\en");
pmap_unset(RCPPROG, RCPVERS);
if (!svc_register(transp,
RCPPROG, RCPVERS, rcp_service, IPPROTO_TCP)) {
fprintf(stderr, "svc_register: error\en");
svc_run(); /* \fInever returns\fP */
fprintf(stderr, "svc_run should never return\en");
rcp_service(rqstp, transp)
register struct svc_req *rqstp;
register SVCXPRT *transp;
switch (rqstp->rq_proc) {
if (svc_sendreply(transp, xdr_void, 0) == 0) {
fprintf(stderr, "err: rcp_service");
if (!svc_getargs(transp, xdr_rcp, stdout)) {
if (!svc_sendreply(transp, xdr_void, 0)) {
fprintf(stderr, "can't reply\en");
.IX RPC "callback procedures"
Occasionally, it is useful to have a server become a client,
and make an RPC call back to the process which is its client.
An example is remote debugging,
where the client is a window system program,
and the server is a debugger running on the remote machine.
the user clicks a mouse button at the debugging window,
which converts this to a debugger command,
and then makes an RPC call to the server
(where the debugger is actually running),
telling it to execute that command.
However, when the debugger hits a breakpoint, the roles are reversed,
and the debugger wants to make an rpc call to the window program,
so that it can inform the user that a breakpoint has been reached.
In order to do an RPC callback,
you need a program number to make the RPC call on.
Since this will be a dynamically generated program number,
it should be in the transient range,
.I "0x40000000 - 0x5fffffff" .
returns a valid program number in the transient range,
and registers it with the portmapper.
It only talks to the portmapper running on the same machine as the
routine itself. The call to
is a test and set operation,
in that it indivisibly tests whether a program number
has already been registered,
and if it has not, then reserves it. On return, the
argument will contain a socket that can be used
gettransient(proto, vers, sockp)
static int prognum = 0x40000000;
fprintf(stderr, "unknown protocol type\en");
if (*sockp == RPC_ANYSOCK) {
if ((s = socket(AF_INET, socktype, 0)) < 0) {
addr.sin_addr.s_addr = 0;
addr.sin_family = AF_INET;
* may be already bound, so don't check for error
if (getsockname(s, &addr, &len)< 0) {
while (!pmap_set(prognum++, vers, proto,
ntohs(addr.sin_port))) continue;
is necessary to ensure that the port number in
man page for more details on the conversion of network
addresses from network to host byte order.
The following pair of programs illustrate how to use the
The client makes an RPC call to the server,
passing it a transient program number.
Then the client waits around to receive a callback
from the server at that program number.
The server registers the program
so that it can receive the RPC call
informing it of the callback program number.
Then at some random time (on receiving an
signal in this example), it sends a callback RPC call,
using the program number it received earlier.
gethostname(hostname, sizeof(hostname));
x = gettransient(IPPROTO_UDP, 1, &s);
fprintf(stderr, "client gets prognum %d\en", x);
if ((xprt = svcudp_create(s)) == NULL) {
fprintf(stderr, "rpc_server: svcudp_create\en");
/* protocol is 0 - gettransient does registering
(void)svc_register(xprt, x, 1, callback, 0);
ans = callrpc(hostname, EXAMPLEPROG, EXAMPLEVERS,
EXAMPLEPROC_CALLBACK, xdr_int, &x, xdr_void, 0);
if ((enum clnt_stat) ans != RPC_SUCCESS) {
fprintf(stderr, "call: ");
fprintf(stderr, "Error: svc_run shouldn't return\en");
register struct svc_req *rqstp;
register SVCXPRT *transp;
switch (rqstp->rq_proc) {
if (!svc_sendreply(transp, xdr_void, 0)) {
fprintf(stderr, "err: exampleprog\en");
if (!svc_getargs(transp, xdr_void, 0)) {
fprintf(stderr, "client got callback\en");
if (!svc_sendreply(transp, xdr_void, 0)) {
fprintf(stderr, "err: exampleprog");
int pnum; /* \fIprogram number for callback routine\fP */
gethostname(hostname, sizeof(hostname));
registerrpc(EXAMPLEPROG, EXAMPLEVERS,
EXAMPLEPROC_CALLBACK, getnewprog, xdr_int, xdr_void);
fprintf(stderr, "server going into svc_run\en");
signal(SIGALRM, docallback);
fprintf(stderr, "Error: svc_run shouldn't return\en");
ans = callrpc(hostname, pnum, 1, 1, xdr_void, 0,
fprintf(stderr, "server: ");