Page: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
16 17 18

Chapter 6


RPCGEN

6.1 THE RPCGEN PROTOCOL COMPILER

The details of programming applications to use Remote Procedure Calls can be overwhelming. Perhaps the most daunting is writing the XDR routines necessary to convert procedure arguments and results into their network format and vice-versa.

Fortunately, rpcgen exists to help programmers write RPC applications simply and directly. 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.

rpcgen is a compiler. It accepts a remote program interface definition written in a language, called RPC Language, that is similar to C. It produces a C language output that 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. Similarly, the server stub hides the network from server procedures to be invoked by remote clients. rpcgen's output files can be compiled and linked in the usual way. The developer writes server procedures in any language that observes Sun calling conventionsand links them with the server skeleton produced by 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 rpcgen. Linking this program with rpcgen's stubs creates an executable program. (At present the main program must be written in C). rpcgen options can be used to suppress stub generation and to specify the transport to be used by the server stub.

Like all compilers, rpcgen reduces the development time that would otherwise be spent coding and debugging low-level routines. All compilers, including 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. rpcgen is no exception. In speed-critical applications, hand-written routines can be linked with the rpcgen output without any difficulty. Also, you can proceed by using rpcgen output as a starting point, and rewriting it as necessary.

Home


6.2 CONVERTING LOCAL PROCEDURES INTO REMOTE PROCEDURES

If you have an application that runs on a single machine, you can convert it to run over the network. The following example illustrates such a conversion -- a program that prints a message to the console.

Example:


     /*
      * printmsg.c: print a message on the console
      */
     #include <stdio.h>

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

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

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

               f = fopen("/dev/console", "w");
               if     (f = = NULL) {
                         return      (0);
               }
               fprintf(f, "%s\n", msg);
               fclose(f);
               return(1);
     }

Home


And then, of course:


     example% cc printmsg.c -o printmsg
     example% printmsg "Hello, there."
     Message delivered!
     example%

If printmessage is turned into a remote procedure, it can be called from anywhere in the network. Ideally, you would like to put a keyword like remote in front of a procedure to turn it into a remote procedure. Unfortunately, C language constraints must be observed, since it existed long before RPC. But even without language support, it is not difficult to make a procedure remote.

In general, it is necessary to figure out what the types are for all procedure inputs and outputs. In this case, the procedure printmessage takes a string as input and returns an integer as output. Knowing this, you can write a protocol specification in RPC language that describes the remote version of printmessage as follows.


     /*
       * msg.x:       Remote message printing protocol
      */

     program     MESSAGEPROG {
                    version      MESSAGEVERS {
                              int      PRINTMESSAGE(string) = 1;
                    } = 1;
     } = 99;

Remote procedures are part of remote programs, so you actually declare an entire remote program that contains the single procedure PRINTMESSAGE. This procedure is declared to be in version 1 of the remote program. No null procedure (procedure 0) is necessary because rpcgen generates it automatically.

Everything is declared with all capital letters. This is not required, but is a good convention to follow.

Also, 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 can 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.

There are just two more things to write. First, write the remote procedure itself. The definition of a remote procedure to implement the PRINTMESSAGE procedure declared previously follows.


     /*
      * msg_proc.c: implementation of the remote procedure "printmessage"
      */

     #include     <stdio.h>
     #include      <rpc/rpc.h>               /* always needed */
     #include      "msg.h"               /* need this too: msg.h will be generated by rpcgen */

     /*
      * Remote version of "printmessage"
      */

Home



     int *
     printmessage_1(msg)
               char **msg;
     {
               static int result;     /* must be static! */
               FILE *f;

               f = fopen("/dev/console", "w");
               if      (f = = NULL) {
                         result =     0;
                         return      (&result);
               }
               fprintf(f, "%s\n", *msg);
               fclose(f);
                result =     1;
               return      (&result);
     }

In this example, the declaration of the remote procedure printmessage_1 differs from that of the local procedure printmessage in three ways:

  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.

  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.

  3. It has an _1 appended to its name. In general, all remote procedures called by rpcgen are named by the following rule. The name in the program definition (here PRINTMESSAGE) is converted to lowercase, an underbar (_) is appended to the name, and the version number (here 1) is added after the underbar.

The last thing to do is declare the main client program that calls the remote procedure as follows.


     /*
      * rprintmsg.c: remote version of "printmsg.c"
      */
     #include <stdio.h>
     #include <rpc/rpc.h>                         /* always needed */
     #include <sys/socket.h>
     #include <sys/time.h>
     #include <netdb.h>
     #include "msg.h"                              /* need this too: msg.h will be generated by rpcgen */

     main(argc, argv)
               int argc;
               char *argv[];
     {
               CLIENT *cl;
               int *result;
               char *server;
               char *message;
               struct hostent *hp;
               struct sockaddr_in sin;

Home




          int sock;
          struct timeval tv;

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

          /*
           * Save values of command line arguments
           */
          server  = argv[1];
          message = argv[2];

          /*
           * Create client "handle" used for calling MESSAGEPROG on  the
           * server designated on the command line. We tell the RPC package
           * to  use the "tcp" protocol  when contacting the server.
          */
          hp = gethostbyname(server);
          if     (hp = =  NULL) {
                    fprintf("cannot get addr for `%s'\n",server);
                    return(NULL);
          }
          sin.sin_family = AF_INET;
          sin.sin_port = 0;
          (void) memcpy((char *)&sin.sin_addr, hp-->h_addr, hp-->h_length);
          sock = RPC_ANYSOCK;
          tv.tv_sec = 60;
          tv.tv_usec = 0;
          cl = clnttcp_create(&sin, MESSAGEPROG, MESSAGEVERS, &sock, 0, 0);
          if     (cl = = NULL) {
                      /*
                     * Couldn't establish connection with server.
                     * Print error message and die.
                     */
                    clnt_ pcreateerror(server);
                    exit(1);
          }

          /*
           * Call the remote procedure "printmessage" on the server
           */
          result = printmessage_1(&message, cl);
          if     (result = = NULL) {
                    /*
           * An error occurred while calling the server.
           * Print error message and die.
           */
          clnt_ perror(cl, server);
          exit(1);
     }

Home




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

     /*
      * The message got printed on the server's console
      */
     printf("Message delivered to %s!\n", server);
}

Note that:

This is how to put all of the pieces together.


     example%      rpcgenmsg.x
     example%      ccrprintmsg.cmsg_clnt.c  -o rprintmsg
     example%      ccmsg_proc.cmsg_svc.c  -o msg_server

In this example, two programs were compiled together -- the client program printmsg and the server program msg_server. Before doing this, rpcgen filled in the missing pieces.

rpcgen did the following with the input file msg.x:

  1. It created a header file called msg.h that contained #define's for MESSAGEPROG, MESSAGEVERS and PRINTMESSAGE for use in the other modules.

  2. It created client stub routines in the msg_clnt.c file. In this case there is only one, the printmessage_1 that was referred to from the 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 FOOx, the client stubs output file is called FOO_clnt.c.

  3. It created the server program that calls printmessage_1 in msg_ proc.c. This server program is named msg_svc.c. The rule for naming the server output file is similar to the previous one: for an input file called FOOx, the output server file is named FOO_svc.c.

Home


Now for 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.


     moon %  msg_server&

Then, on the local machine ("SUPER-UX"), print a message on the console "moon."


     SUPER-UX % print msg moon "Hello,  moon."

The message is printed to moon. 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.

6.3 GENERATING XDR ROUTINES

The previous example only demonstrated the automatic generation of client and server RPC code. rpcgen may also be used to generate XDR routines. The routines necessary to convert local data structures into network format and vice-versa. This example presents a complete RPC service -- a remote directory listing service, that uses rpcgen not only to generate stub routines, but also to generate the XDR routines. The protocol description file is shown in the following example.

Example:


     /*
      * dir.x:  Remote directory listing protocol
      */
     const MAXNAMELEN = 255;          /* maximum length of a directory entry */

     typedef string nametype<MAXNAMELEN>;          /* a directory entry */

     typedef struct namenode *namelist;                    /* a link in the listing */

     /*
      * A node in the directory listing
      */
     struct      namenode {
           nametype name;               /* name of directory entry */
           namelist next;                    /* next entry */
     };

     /* 
      * The result of a READDIR operation.
      */
     union readdir_res switch (int errno) {
     case 0:
          namelist list;          /* no error: return directory listing */
     default:
          void;                    /* error occurred: nothing else to return */
     };

     /*
      * The directory program definition
      */
     program DIRPROG {
          version DIRVERS {
               readdir_res READDIR(nametype) = 1;
          } = 1;
     } = 76;

Home


Running rpcgen on 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 dir_xdr.c.

The following example shows the implementation of the READDIR procedure.

Example:


     /*
      * dir_ proc.c: remote readdir implementation
      */
     #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;          /* must be static! */

          /*
           * Open directory
           */
          dirp = opendir(*dirname);
          if (dirp = = NULL) {
               res.errno = errno;
               return (&res);
          }

          /*
           * Collect directory entries
           */
          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;
          /*
           * Return the result
           */
          res.errno = 0;
          closedir(dirp);
          return (&res);
     }

Home


Finally, there is the client side program to call the server:


     /*
      * rls.c: Remote directory listing client
      */
     #include <stdio.h>
     #include <rpc/rpc.h>               /* always need this */
     #include <sys/socket.h>
     #include <sys/time.h>
     #include <netdb.h>
     #include "dir.h"               /* need this too: will be generated by rpcgen */

     extern      int      errno;

     main      (argc,      argv)
          int      argc;
          char      *argv[];
     {
          CLIENT *cl;
          char *server;
          char *dir;
          readdir_res *result;
          namelist nl;
          struct hostent *hp;
          struct sockaddr_in sin;
          int sock;
          struct timeval tv;

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

          /*
           * Remember what our command line arguments refer to
           */
          server  = argv[1];
          dir = argv[2];

     /*
            * Create client "handle" used for calling DIRPROG on the
           * server designated on the command line. We tell the RPC package
           * to use the "tcp" protocol when contacting the server.
           */

Home




          hp = gethostbyname(server);
          if (hp = = NULL) {
               fprint("cannot get addr for `%s'\n",server);
               return(NULL);
          }
          sin.sin_family = AF_INET;
          sin.sin_port = 0;
          (void) memcpy((char *)&sin_addr, hp-->h_addr. hp-->_length);
          sock = RPC_ANYSOCK;
          tv.tv_sec = 60;
          tv.tv_usec = 0;
          cl = clnttcp_create(&sin, DIRPROG, DIRVERS, &sock, 0, 0);
          if (cl = = NULL) {
               /*
                * Couldn't establish connection with server.
                * Print error message and die.
                */
               clnt_ pcreateerror(server);
               exit(1);
          }

          /*
           * Call the remote procedure readdir on the server
           */
          result = readdir_1(&dir, cl);
          if (result = = NULL) {
               /*
                * An error occurred while calling the server.
                * Print error message and die.
                */
               clnt_ perror(cl, server);
               exit(1);
          }

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

Home



          /*
           * Successfully got a directory listing.
           * Print it out.
           */
          for (nl = result-->readdir_res_u.list; nl != NULL;
               nl = nl-->next) {
               printf("%s", nl-->name);
          }
     }
Compile everything, and run.

          SUPER-UX%rpcgendir.x
          SUPER-UX%ccrls.cdir_clnt.cdir_xdr.c -orls
          SUPER-UX%ccdir_svc.cdir_proc.cdir_xdr.c-odir _svc
          SUPER-UX%dir_svc&

          moon%rlsSUPER-UX/usr/pub
          ascii
          eqnchar
          greek
          kbd
          marg8
          tabclr
          tabs
          tabs4
          moon%

A final note about 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 are executed as ordinary local procedure calls and the program can be debugged with a local debugger such as dbx. When the program is working, the client program can be linked to the client stub produced by rpcgen and the server procedures can be linked to the server stub produced by rpcgen.

NOTE

If you do this, you may want to comment out calls to RPC library routines and have client-side routines call server routines directly.

6.4 THE C-PREPROCESSOR

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:


     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

Home


Also, rpcgen does a little reprocessing 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.



     /*
      * time.x: Remote time protocol
      */
     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

The `%' feature is not generally recommended because there is no guarantee that the compiler will put the output where you intended.

6.5 RPC LANGUAGE

RPC language is an extension XDR. The sole extension is the addition of the program type. For a complete description of XDR language syntax, see Chapter 5, eXternal Data Representation. For a description of RPC extensions to the XDR language, see Chapter 4, Remote Procedure Calls.

XDR language is so close to C that if you know C, you already know most of XDR. The RPC language syntax is described here, and some examples are included. How the various RPC and XDR type definitions are compiled into C-type definitions in the output header file is also described.

6.5.1 Definitions

An RPC language file consists of a series of definitions.


     definition-list:
          definition ";"
          definition ";" definition-list

It recognizes six types of definitions.


     definition:
          enum-definition
          struct-definition
          union-definition
          typedef-definition
          const-definition
          program-definition

Home


6.5.2 Structures

An XDR struct is declared almost exactly like its C counterpart. It looks like the following:


     struct-definition:
          "struct" struct-ident "{"
               declaration-list
          "}"

     declaration-list:
          declaration ";"
          declaration ";" declaration-list

In the following example, an XDR structure defines a two-dimensional coordinate. The C structure that the XDR structure is compiled into in the output header file is also shown.



     struct coord {                         struct coord {
          intx;                 -->                      int x;
          inty;                                            int y;
     };                                           };
                                                   typedef  struct  coord coord;

The output is identical to the input, except for the added typedef at the end of the output. This allows you to use coord instead of struct coord when declaring items.

6.5.3 Unions

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.



     union-definition:
          "union" union-ident "switch" "(" declaration ")" "{"
               case-list
          "}"

     case-list:
          "case" value ":" declaration ";"
          "default" ":" declaration ";"
          "case" value ":" declaration ";" case-list

Here is an example of a type that might be returned as the result of a read data operation. If there is no error, a block of data is returned. Otherwise, nothing is return.


     union read_result switch (int errno) {
     case 0:
          opaque data[1024];
     default:
          void;
     };

Home


It is compiled into the following:


     structread_result      {
               int errno;
               union {
                         char data[1024];
               }      read_result_u;
     };
     typedefstructread_result read_result;

The union component of the output struct has the name as the type name, except for the trailing _u.

6.5.4 Enumerations

XDR enumerations have the same syntax as C enumerations.



     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

The following is a short example of an XDR enum, and the C enum into which it is compiled.



     enum colortype {                        enum colortype {
               RED = 0,                              RED = 0,
               GREEN = 1,   -->                 GREEN = 1,
               BLUE = 2                             BLUE = 2
     };                                                };
                                                         typedef enum colortype colortype;

6.5.5 Typedef

XDR typedefs have the same syntax as C typedefs.


     typedef-definition:
               "typedef" declaration

Here is an example that defines a fname_type used for declaring file name strings that have a maximum length of 255 characters.


     typedef string fname_type<255>;  -->  typedef char *fname_type;

Home


6.5.6 Constants

XDR constants symbolic constants that may be used wherever an integer constant is used, for example, in array size specifications.


     const-definition:
               "const" const-ident "=" integer

For example, the following defines a constant DOZEN equal to 12.


     const DOZEN = 12;    -->  #define DOZEN 12

6.5.7 Programs

RPC programs are declared using the following syntax:



     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

For example, here is the time protocol, revisited:


     /*
      * time.x: Get or set the time. Time is represented as number of seconds
      * since 0:00, January 1, 1970.
      */
     program      TIMEPROG {
                    version           TIMEVERS {
                                   unsigned int TIMEGET(void) = 1;
                                   void TIMESET(unsigned) = 2;
                    } = 1;
     } = 44;

Home


This file compiles into #defines in the output header file:


#define TIMEPROG 44 #define TIMEVERS 1 #define TIMEGET 1 #define TIMESET 2

6.5.8 Declarations

In XDR, there are only four kinds of declarations.


     declaration:
          simple-declaration
          fixed-array-declaration
          variable-array-declaration
          pointer-declaration

Home


6.5.9 Special Cases

There are a few exceptions to the previous rules.

Home


Home

Contents Previous Chapter Index