the process can set an alarm signal before calling svc_run() But if the other activity involves waiting on a a file descriptor, the svc_run() call won't work. The code for svc_run() is as follows: void svc_run() {
    fd_set readfds;
    int dtbsz = getdtablesize();
    for (;;) {
        readfds = svc_fds;
        switch (select(dtbsz, &readfds, NULL,NULL,NULL)) {
        case -1:
            if (errno == EINTR)
                continue;
            perror("select");
            return;
        case 0:
            break;
        default:
            svc_getreqset(&readfds);
        }
    } }

You can bypass svc_run() and call svc_getreqset() yourself. 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 select() that waits on both the RPC socket, and your own descriptors. Note that svc_fds() is a bit mask of all the file descriptors that RPC is using for services. It can change everytime that any RPC library routine is called, because descriptors are constantly being opened and closed, for example for TCP connections. Broadcast RPC

The portmapper is a daemon that converts RPC program numbers into DARPA protocol port numbers; see the portmap man page. You can't do broadcast RPC without the portmapper. Here are the main differences between broadcast RPC and normal RPC calls:

1.  Normal RPC expects one answer, whereas broadcast RPC expects many answers (one or more answer from each responding machine).

2.  Broadcast RPC can only be supported by packet-oriented (connectionless) transport protocols like UPD/IP.

3.  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.

4.  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.

5.  Broadcast requests are limited in size to the MTU (Maximum Transfer Unit) of the local network. For Ethernet, the MTU is 1500 bytes. Broadcast RPC 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; /* program number */
        u_long versnum; /* version number */
        u_long procnum; /* procedure number */
        xdrproc_t inproc; /* xdr routine for args */
        caddr_t in; /* pointer to args */
        xdrproc_t outproc; /* xdr routine for results */
        caddr_t out; /* pointer to results */
        bool_t (*eachresult)();/* call with each result gotten */ The procedure eachresult() is called each time a valid result is obtained. It returns a boolean that indicates whether or not the user wants more responses. bool_t done;
        . . . done = eachresult(resultsp, raddr)
        caddr_t resultsp;
        struct sockaddr_in *raddr; /* Addr of responding machine */ If done is TRUE , then broadcasting stops and clnt_broadcast() returns successfully. Otherwise, the routine waits for another response. The request is rebroadcast after a few seconds of waiting. If no responses come back, the routine returns with RPC_TIMEDOUT . Batching

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 pipeline of calls to a desired server; this is called batching. Batching assumes that: 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 write() 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 <stdio.h> #include <rpc/rpc.h> #include <suntool/windows.h> void windowdispatch(); main() {
    SVCXPRT *transp;
    transp = svctcp_create(RPC_ANYSOCK, 0, 0);
    if (transp == NULL){
        fprintf(stderr, "can't create an RPC server\n");
        exit(1);
    }
    pmap_unset(WINDOWPROG, WINDOWVERS);
    if (!svc_register(transp, WINDOWPROG, WINDOWVERS,
      windowdispatch, IPPROTO_TCP)) {
        fprintf(stderr, "can't register WINDOW service\n");
        exit(1);
    }
    svc_run(); /* Never returns */
    fprintf(stderr, "should never reach this point\n"); } void windowdispatch(rqstp, transp)
    struct svc_req *rqstp;
    SVCXPRT *transp; {
    char *s = NULL;
    switch (rqstp->rq_proc) {
    case NULLPROC:
        if (!svc_sendreply(transp, xdr_void, 0))
            fprintf(stderr, "can't reply to RPC call\n");
        return;
    case RENDERSTRING:
        if (!svc_getargs(transp, xdr_wrapstring, &s)) {
            fprintf(stderr, "can't decode arguments\n");
            /*
             * Tell caller he screwed up
             */
            svcerr_decode(transp);
            break;
        }
        /*
         * Code here to render the string s
         */
        if (!svc_sendreply(transp, xdr_void, NULL))
            fprintf(stderr, "can't reply to RPC call\n");
        break;
    case RENDERSTRING_BATCHED:
        if (!svc_getargs(transp, xdr_wrapstring, &s)) {
            fprintf(stderr, "can't decode arguments\n");
            /*
             * We are silent in the face of protocol errors
             */
            break;
        }
        /*
         * Code here to render string s, but send no reply!
         */
        break;
    default:
        svcerr_noproc(transp);
        return;
    }
    /*
     * Now free string allocated while decoding arguments
     */
    svc_freeargs(transp, xdr_wrapstring, &s); } 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 NULL ), 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 a null string (EOF): #include <stdio.h> #include <rpc/rpc.h> #include <sys/socket.h> #include <sys/time.h> #include <netdb.h> #include <suntool/windows.h> main(argc, argv)
    int argc;
    char **argv; {
    struct hostent *hp;
    struct timeval pertry_timeout, total_timeout;
    struct sockaddr_in server_addr;
    int sock = RPC_ANYSOCK;
    register CLIENT *client;
    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");
        exit(-1);
    }
    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");
            exit(-1);
        }
    }
    /* Now flush the pipeline */
    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");
        exit(-1);
    }
    clnt_destroy(client);
    exit(0); } 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 /etc/termcap . 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: 1) 50 seconds; 2) 16 seconds; 3) 52 seconds; 4) 10 seconds. Running fscanf() on /etc/termcap only requires six seconds. These timings show the advantage of protocols that allow for overlapped execution, though these protocols are often hard to design. 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 none .

The authentication subsystem of the RPC package is open ended. That is, numerous types of authentication are easy to support. UNIX Authentication

The Client Side

When a caller creates a new RPC client handle as in: clnt = clntudp_create(address, prognum, versnum,
              wait, sockp) the appropriate transport instance defaults the associate authentication handle to be clnt->cl_auth = authnone_create(); The RPC client can choose to use UNIX style authentication by setting clnt->cl_auth after creating the RPC client handle: clnt->cl_auth = authunix_create_default(); This causes each RPC call associated with clnt to carry with it the following authentication credentials structure: /*
 * UNIX style credentials.
 */ struct authunix_parms {
    u_long aup_time; /* credentials creation time */
    char *aup_machname; /* host name where client is */
    int aup_uid; /* client's UNIX effective uid */
    int aup_gid; /* client's current group id */
    u_int aup_len; /* element length of aup_gids */
    int *aup_gids; /* array of groups user is in */ }; These fields are set by 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.

The Server Side

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: /*
 * An RPC Service request
 */ struct svc_req {
    u_long    rq_prog;        /* service program number */
    u_long    rq_vers;        /* service protocol vers num */
    u_long    rq_proc;        /* desired procedure number */
    struct opaque_auth rq_cred; /* raw credentials from wire */
    caddr_t rq_clntcred; /* credentials (read only) */ }; The rq_cred is mostly opaque, except for one field of interest: the style or flavor of authentication credentials: /*
 * Authentication info. Mostly opaque to the programmer.
 */ struct opaque_auth {
    enum_t oa_flavor; /* style of credentials */
    caddr_t oa_base; /* address of more auth stuff */
    u_int oa_length; /* not to exceed MAX_AUTH_BYTES */ }; The RPC package guarantees the following to the service dispatch routine:

1.  That the request's rq_cred is well formed. Thus the service implementor may inspect the request's rq_cred.oa_flavor to determine which style of authentication the caller used. The service implementor may also wish to inspect the other fields of rq_cred if the style is not one of the styles supported by the RPC package.

2.  That the request's rq_clntcred field is either NULL or points to a well formed structure that corresponds to a supported style of authentication credentials. Remember that only unix style is currently supported, so (currently) rq_clntcred could be cast to a pointer to an authunix_parms structure. If rq_clntcred is NULL , the service implementor may wish to inspect the other (opaque) fields of rq_cred 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: nuser(rqstp, transp)
    struct svc_req *rqstp;
    SVCXPRT *transp; {
    struct authunix_parms *unix_cred;
    int uid;
    unsigned long nusers;
    /*
     * 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\n");
            return (1);
         }
         return;
    }
    /*
     * now get the uid
     */
    switch (rqstp->rq_cred.oa_flavor) {
    case AUTH_UNIX:
        unix_cred =
            (struct authunix_parms *)rqstp->rq_clntcred;
        uid = unix_cred->aup_uid;
        break;
    case AUTH_NULL:
    default:
        svcerr_weakauth(transp);
        return;
    }
    switch (rqstp->rq_proc) {
    case RUSERSPROC_NUM:
        /*
         * make sure caller is allowed to call this proc
         */
        if (uid == 16) {
            svcerr_systemerr(transp);
            return;
        }
        /*
         * Code here to compute the number of users
         * and assign it to the variable nusers
         */
        if (!svc_sendreply(transp, xdr_u_long, &nusers)) {
            fprintf(stderr, "can't reply to RPC call\n");
            return (1);
        }
        return;
    default:
        svcerr_noproc(transp);
        return;
    } } A few things should be noted here. First, it is customary not to check the authentication parameters associated with the NULLPROC (procedure number zero). Second, if the authentication parameter's type is not suitable for your service, you should call svcerr_weakauth() . 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 svcerr_systemerr() instead.

The last point underscores the relation between the RPC authentication package and the services; RPC deals only with authentication and not with individual services' access control . The services themselves must implement their own access control policies and reflect these policies as return statuses in their protocols. DES Authentication

UNIX authentication is quite easy to defeat. Instead of using authunix_create_default (), one can call authunix_create() 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 are not explained here. See Remote Procedure Calls: Protocol Specification for the details.

In order for DES authentication to work, the keyserv(8c) daemon must be running on both the server and client machines. The users on these machines need public keys assigned by the network administrator in the publickey(5) database. And, they need to have decrypted their secret keys using their login password. This automatically happens when one logs in using login(1) , or can be done manually using keylogin(1) . The Network Services chapter explains more how to setup secure networking.

Client Side

If a client wishes to use DES authentication, it must set its authentication handle appropriately. Here is an example: cl->cl_auth =
    authdes_create(servername, 60, &server_addr, NULL); The first argument is the network name or netname 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); Here, rhostname is the hostname of the machine the server process is running on. host2netname() fills in servername to contain this root process's netname. If the server process was run by a regular user, one could use the call user2netname() instead. Here is an example for a server process with the same user ID as the client: char servername[MAXNETNAMELEN]; user2netname(servername, getuid(), NULL); The last argument to both of these calls, user2netname() and host2netname (), is the name of the naming domain where the server is located. The NULL used here means use the local domain name.

The second argument to authdes_create() 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.

The third argument to authdes_create() 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 NULL , which means don't bother synchronizing. You should only do this if you are sure the client and server are already synchronized.

The final argument to authdes_create() is the address of a DES encryption key to use for encrypting timestamps and data. If this argument is NULL , 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 ah_key field of the authentication handle.

Server Side

The server side is a lot simpler than the client side. Here is the previous example rewritten to use AUTH_DES instead of AUTH_UNIX : #include <sys/time.h> #include <rpc/auth_des.h>
    . . .
    . . . nuser(rqstp, transp)
    struct svc_req *rqstp;
    SVCXPRT *transp; {
    struct authdes_cred *des_cred;
    int uid;
    int gid;
    int gidlen;
    int gidlist[10];
    /*
     * we don't care about authentication for null proc
     */
    if (rqstp->rq_proc == NULLPROC) {
        /* same as before */
    }
    /*
     * now get the uid
     */
    switch (rqstp->rq_cred.oa_flavor) {
    case AUTH_DES:
        des_cred =
            (struct authdes_cred *) rqstp->rq_clntcred;
        if (! netname2user(des_cred->adc_fullname.name,
            &uid, &gid, &gidlen, gidlist))
        {
            fprintf(stderr, "unknown user: %s,
                des_cred->adc_fullname.name);
            svcerr_systemerr(transp);
            return;
        }
        break;
    case AUTH_NULL:
    default:
        svcerr_weakauth(transp);
        return;
    }
    /*
     * The rest is the same as before
      */ Note the use of the routine netname2user (), the inverse of user2netname (): it takes a network ID and converts to a unix ID. netname2user () also supplies the group IDs which we don't use in this example, but which may be useful to other UNIX programs. Using Inetd

An RPC server can be started from inetd The only difference from the usual code is that the service creation routine should be called in the following form: transp = svcudp_create(0); /* For UDP */ transp = svctcp_create(0,0,0); /* For listener TCP sockets */ transp = svcfd_create(0,0,0); /* For connected TCP sockets */ since inet passes a socket as file descriptor 0. Also, svc_register() should be called as svc_register(transp, PROGNUM, VERSNUM, service, 0); with the final flag as 0, since the program would already be registered by inetd Remember that if you want to exit from the server process and return control to inet you need to explicitly exit, since svc_run() never returns.

The format of entries in /etc/inetd.conf 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 where p_name is the symbolic name of the program as it appears in rpc(5) , server is the program implementing the server, and program and version are the program and version numbers of the service. For more information, see inetd.conf(5) .

If the same program handles multiple versions, then the version number can be a range, as in this example: rstatd/1-2 dgram rpc/udp wait root /usr/etc/rpc.rstatd More Examples

Versions

By convention, the first version number of program PROG is PROGVERS_ORIG and the most recent version is PROGVERS Suppose there is a new version of the user program that returns an unsigned short rather than a long . If we name this version RUSERSVERS_SHORT then a server that wants to support both versions would do a double register. if (!svc_register(transp, RUSERSPROG, RUSERSVERS_ORIG,
  nuser, IPPROTO_TCP)) {
    fprintf(stderr, "can't register RUSER service\n");
    exit(1); } if (!svc_register(transp, RUSERSPROG, RUSERSVERS_SHORT,
  nuser, IPPROTO_TCP)) {
    fprintf(stderr, "can't register RUSER service\n");
    exit(1); } Both versions can be handled by the same C procedure: nuser(rqstp, transp)
    struct svc_req *rqstp;
    SVCXPRT *transp; {
    unsigned long nusers;
    unsigned short nusers2;
    switch (rqstp->rq_proc) {
    case NULLPROC:
        if (!svc_sendreply(transp, xdr_void, 0)) {
            fprintf(stderr, "can't reply to RPC call\n");
            return (1);
        }
        return;
    case RUSERSPROC_NUM:
        /*
         * Code here to compute the number of users
         * and assign it to the variable nusers
         */
        nusers2 = nusers;
        switch (rqstp->rq_vers) {
        case RUSERSVERS_ORIG:
            if (!svc_sendreply(transp, xdr_u_long,
            &nusers)) {
                fprintf(stderr,"can't reply to RPC call\n");
            }
            break;
        case RUSERSVERS_SHORT:
            if (!svc_sendreply(transp, xdr_u_short,
            &nusers2)) {
                fprintf(stderr,"can't reply to RPC call\n");
            }
            break;
        }
    default:
        svcerr_noproc(transp);
        return;
    } } TCP

Here is an example that is essentially rcp. The initiator of the RPC snd call takes its standard input and sends it to the server rcv which prints it on standard output. The RPC call uses TCP. This also illustrates an XDR procedure that behaves differently on serialization than on deserialization. /*
 * The xdr routine:
 *    on decode, read from wire, write onto fp
 *    on encode, read from fp, write onto wire
 */ #include <stdio.h> #include <rpc/rpc.h> xdr_rcp(xdrs, fp)
    XDR *xdrs;
    FILE *fp; {
    unsigned long size;
    char buf[BUFSIZ], *p;
    if (xdrs->x_op == XDR_FREE)/* nothing to free */
        return 1;
    while (1) {
        if (xdrs->x_op == XDR_ENCODE) {
            if ((size = fread(buf, sizeof(char), BUFSIZ,
              fp)) == 0 && ferror(fp)) {
                fprintf(stderr, "can't fread\n");
                return (1);
            }
        }
        p = buf;
        if (!xdr_bytes(xdrs, &p, &size, BUFSIZ))
            return 0;
        if (size == 0)
            return 1;
        if (xdrs->x_op == XDR_DECODE) {
            if (fwrite(buf, sizeof(char), size,
              fp) != size) {
                fprintf(stderr, "can't fwrite\n");
                return (1);
            }
        }
    } } /*
 * The sender routines
 */ #include <stdio.h> #include <netdb.h> #include <rpc/rpc.h> #include <sys/socket.h> #include <sys/time.h> main(argc, argv)
    int argc;
    char **argv; {
    int xdr_rcp();
    int err;
    if (argc < 2) {
        fprintf(stderr, "usage: %s servername\n", argv[0]);
        exit(-1);
    }
    if ((err = callrpctcp(argv[1], RCPPROG, RCPPROC,
      RCPVERS, xdr_rcp, stdin, xdr_void, 0) != 0)) {
        clnt_perrno(err);
        fprintf(stderr, "can't make RPC call\n");
        exit(1);
    }
    exit(0); } callrpctcp(host, prognum, procnum, versnum,
           inproc, in, outproc, out)
    char *host, *in, *out;
    xdrproc_t inproc, outproc; {
    struct sockaddr_in server_addr;
    int socket = RPC_ANYSOCK;
    enum clnt_stat clnt_stat;
    struct hostent *hp;
    register CLIENT *client;
    struct timeval total_timeout;
    if ((hp = gethostbyname(host)) == NULL) {
        fprintf(stderr, "can't get addr for '%s'\n", host);
        return (-1);
    }
    bcopy(hp->h_addr, (caddr_t)&server_addr.sin_addr,
        hp->h_length);
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = 0;
    if ((client = clnttcp_create(&server_addr, prognum,
      versnum, &socket, BUFSIZ, BUFSIZ)) == NULL) {
        perror("rpctcp_create");
        return (-1);
    }
    total_timeout.tv_sec = 20;
    total_timeout.tv_usec = 0;
    clnt_stat = clnt_call(client, procnum,
        inproc, in, outproc, out, total_timeout);
    clnt_destroy(client);
    return (int)clnt_stat; } /*
 * The receiving routines
 */ #include <stdio.h> #include <rpc/rpc.h> main() {
    register SVCXPRT *transp;
     int rcp_service(), xdr_rcp();
    if ((transp = svctcp_create(RPC_ANYSOCK,
      BUFSIZ, BUFSIZ)) == NULL) {
        fprintf("svctcp_create: error\n");
        exit(1);
    }
    pmap_unset(RCPPROG, RCPVERS);
    if (!svc_register(transp,
      RCPPROG, RCPVERS, rcp_service, IPPROTO_TCP)) {
        fprintf(stderr, "svc_register: error\n");
        exit(1);
    }
    svc_run(); /* never returns */
    fprintf(stderr, "svc_run should never return\n"); } rcp_service(rqstp, transp)
    register struct svc_req *rqstp;
    register SVCXPRT *transp; {
    switch (rqstp->rq_proc) {
    case NULLPROC:
        if (svc_sendreply(transp, xdr_void, 0) == 0) {
            fprintf(stderr, "err: rcp_service");
            return (1);
        }
        return;
    case RCPPROC_FP:
        if (!svc_getargs(transp, xdr_rcp, stdout)) {
            svcerr_decode(transp);
            return;
        }
        if (!svc_sendreply(transp, xdr_void, 0)) {
            fprintf(stderr, "can't reply\n");
            return;
        }
        return (0);
    default:
        svcerr_noproc(transp);
        return;
    } } 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. Most of the time, 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, 0x40000000 - 0x5fffffff . The routine gettransient() 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 gettransient() routine itself. The call to pmap_set() 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 sockp argument will contain a socket that can be used as the argument to an svcudp_create() or svctcp_create() call. #include <stdio.h> #include <rpc/rpc.h> #include <sys/socket.h> gettransient(proto, vers, sockp)
    int proto, vers, *sockp; {
    static int prognum = 0x40000000;
    int s, len, socktype;
    struct sockaddr_in addr;
    switch(proto) {
        case IPPROTO_UDP:
            socktype = SOCK_DGRAM;
            break;
        case IPPROTO_TCP:
            socktype = SOCK_STREAM;
            break;
        default:
            fprintf(stderr, "unknown protocol type\n");
            return 0;
    }
    if (*sockp == RPC_ANYSOCK) {
        if ((s = socket(AF_INET, socktype, 0)) < 0) {
            perror("socket");
            return (0);
        }
        *sockp = s;
    }
    else
        s = *sockp;
    addr.sin_addr.s_addr = 0;
    addr.sin_family = AF_INET;
    addr.sin_port = 0;
    len = sizeof(addr);
    /*
     * may be already bound, so don't check for error
     */
    bind(s, &addr, len);
    if (getsockname(s, &addr, &len)< 0) {
        perror("getsockname");
        return (0);
    }
    while (!pmap_set(prognum++, vers, proto,
        ntohs(addr.sin_port))) continue;
    return (prognum-1); }

Note:
The call to ntohs() is necessary to ensure that the port number in addr.sin_port , which is in network byte order, is passed in host byte order (as pmap_set() expects). See the byteorder(3N) 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 gettransient() routine. 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 EXAMPLEPROG so that it can receive the RPC call informing it of the callback program number. Then at some random time (on receiving an ALRM signal in this example), it sends a callback RPC call, using the program number it received earlier. /*
 * client
 */ #include <stdio.h> #include <rpc/rpc.h> int callback(); char hostname[256]; main() {
    int x, ans, s;
    SVCXPRT *xprt;
    gethostname(hostname, sizeof(hostname));
    s = RPC_ANYSOCK;
    x = gettransient(IPPROTO_UDP, 1, &s);
    fprintf(stderr, "client gets prognum %d\n", x);
    if ((xprt = svcudp_create(s)) == NULL) {
      fprintf(stderr, "rpc_server: svcudp_create\n");
        exit(1);
    }
    /* 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: ");
        clnt_perrno(ans);
        fprintf(stderr, "\n");
    }
    svc_run();
    fprintf(stderr, "Error: svc_run shouldn't return\n"); } callback(rqstp, transp)
    register struct svc_req *rqstp;
    register SVCXPRT *transp; {
    switch (rqstp->rq_proc) {
        case 0:
            if (!svc_sendreply(transp, xdr_void, 0)) {
                fprintf(stderr, "err: exampleprog\n");
                return (1);
            }
            return (0);
        case 1:
            if (!svc_getargs(transp, xdr_void, 0)) {
                svcerr_decode(transp);
                return (1);
            }
            fprintf(stderr, "client got callback\n");
            if (!svc_sendreply(transp, xdr_void, 0)) {
                fprintf(stderr, "err: exampleprog");
                return (1);
            }
    } } /*
 * server
 */ #include <stdio.h> #include <rpc/rpc.h> #include <sys/signal.h> char *getnewprog(); char hostname[256]; int docallback();
int pnum;    /* program number for callback routine */
main() {
    gethostname(hostname, sizeof(hostname));
    registerrpc(EXAMPLEPROG, EXAMPLEVERS,
      EXAMPLEPROC_CALLBACK, getnewprog, xdr_int, xdr_void);
    fprintf(stderr, "server going into svc_run\n");
    signal(SIGALRM, docallback);
    alarm(10);
    svc_run();
    fprintf(stderr, "Error: svc_run shouldn't return\n"); } char * getnewprog(pnump)
    char *pnump; {
    pnum = *(int *)pnump;
    return NULL; } docallback() {
    int ans;
    ans = callrpc(hostname, pnum, 1, 1, xdr_void, 0,
        xdr_void, 0);
    if (ans != 0) {
        fprintf(stderr, "server: ");
        clnt_perrno(ans);
        fprintf(stderr, "\n");
    } }