home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 January / usenetsourcesnewsgroupsinfomagicjanuary1994.iso / sources / unix / volume6 / rpc2 / part02 / rpc / doc / rpc.prog.p1
Encoding:
Text File  |  1986-11-30  |  48.2 KB  |  2,012 lines

  1. .PL RIGHT
  2. .TL
  3. Remote Procedure Call
  4. .br
  5. Programming Guide
  6. .bp
  7. .NH
  8. Introduction
  9. .LP
  10. This document is intended for programmers
  11. who wish to write network applications
  12. using remote procedure calls (explained below),
  13. thus avoiding low-level system primitives based on sockets.
  14. The reader must be familiar with the C programming language,
  15. and should have a working knowledge of network theory.
  16. .LP
  17. Programs that communicate over a network
  18. need a paradigm for communication.
  19. A low-level mechanism might
  20. send a signal on the arrival of incoming packets,
  21. causing a network signal handler to execute.
  22. A high-level mechanism would be the Ada
  23. .LW rendezvous .
  24. The method used at Sun is the
  25. Remote Procedure Call (RPC) paradigm,
  26. in which a client communicates with a server.
  27. In this process,
  28. the client first calls a procedure to send a data packet to the server.
  29. When the packet arrives, the server calls a dispatch routine,
  30. performs whatever service is requested, sends back the reply,
  31. and the procedure call returns to the client.
  32. .NH 2
  33. Layers of RPC
  34. .LP
  35. The RPC interface is divided into three layers.
  36. The highest layer is totally transparent to the programmer.
  37. To illustrate,
  38. at this level a program can contain a call to
  39. .LW rnusers() ,
  40. which returns the number of users on a remote machine.
  41. You don't have to be aware that RPC is being used,
  42. since you simply make the call in a program,
  43. just as you would call
  44. .LW malloc() .
  45. .LP
  46. At the middle layer, the routines
  47. .LW registerrpc()
  48. and
  49. .LW callrpc()
  50. are used to make RPC calls:
  51. .LW registerrpc()
  52. obtains a unique system-wide number, while
  53. .LW callrpc()
  54. executes a remote procedure call.
  55. The
  56. .LW rnusers()
  57. call is implemented using these two routines.
  58. The middle-layer routines are designed for most common applications,
  59. and shield the user from knowing about sockets.
  60. .LP
  61. The lowest layer is for more sophisticated applications,
  62. such as altering the defaults of the routines.
  63. At this layer, you can explicitly manipulate
  64. sockets that transmit RPC messages.
  65. This level should be avoided if possible.
  66. .LP
  67. Section 2 of this manual illustrates use of the highest two layers
  68. while Section 3 presents the low-level interface.
  69. Section 4 of the manual discusses miscellaneous topics.
  70. The final section summarizes
  71. all the entry points into the RPC system.
  72. .LP
  73. Although this document only discusses the interface to C,
  74. remote procedure calls can be made from any language.
  75. Even though this document discusses RPC
  76. when it is used to communicate
  77. between processes on different machines,
  78. it works just as well for communication
  79. between different processes on the same machine.
  80. .NH 2
  81. The RPC Paradigm
  82. .LP
  83. Here is a diagram of the RPC paradigm:
  84. .LP
  85. .PL FULL
  86. .PS
  87. L1: arrow down 1i "client " rjust "program " rjust
  88. L2: line right 1.5i "\fLcallrpc()\fP" "function"
  89. move up 1.5i; line dotted down 6i; move up 4.5i
  90. arrow right 1i
  91. L3: arrow down 1i "execute " rjust "request " rjust
  92. L4: arrow right 1.5i "call" "service"
  93. L5: arrow down 1i " service" ljust " executes" ljust
  94. L6: arrow left 1.5i "\fLreturn\fP" "answer"
  95. L7: arrow down 1i "request " rjust "completed " rjust
  96. L8: line left 1i
  97. arrow left 1.5i "\fLreturn\fP" "reply"
  98. L9: arrow down 1i "program " rjust "continues " rjust
  99. line dashed down from L2 to L9
  100. line dashed down from L4 to L7
  101. line dashed up 1i from L3 "service " rjust "daemon " rjust
  102. arrow dashed down 1i from L8
  103. move right 1i from L3
  104. box invis "Machine B"
  105. move left 1.2i from L2; move down
  106. box invis "Machine A"
  107. .PE
  108. .FN "Network Communication with the Remote Procedure Call"
  109. .PL RIGHT
  110. .bp
  111. .NH
  112. Higher Layers of RPC
  113. .NH 2
  114. Highest Layer
  115. .LP
  116. Imagine you're writing a program that needs to know
  117. how many users are logged into a remote machine.
  118. You can do this by calling the library routine
  119. .LW rnusers() ,
  120. as illustrated below:
  121. .BS
  122. .LS
  123. #include <stdio.h>
  124. .sp.5
  125. main(argc, argv)
  126.     int argc;
  127.     char **argv;
  128. {
  129.     unsigned num;
  130. .sp.5
  131.     if (argc < 2) {
  132.         fprintf(stderr, "usage: rnusers hostname\en");
  133.         exit(1);
  134.     }
  135.     if ((num = rnusers(argv[1])) < 0) {
  136.         fprintf(stderr, "error: rnusers\en");
  137.         exit(-1);
  138.     }
  139.     printf("%d users on %s\en", num, argv[1]);
  140.     exit(0);
  141. }
  142. .Lf
  143. .BE
  144. RPC library routines such as
  145. .LW rnusers()
  146. are in the RPC services library
  147. .LW librpcsvc.a .
  148. Thus, the program above should be compiled with
  149. .BS
  150. .LS
  151. % cc \fIprogram\fP.c -lrpcsvc
  152. .Lf
  153. .BE
  154. This routine, and other RPC library routines,
  155. are documented in section 3R of the
  156. .I "System Interface Manual for the Sun Workstation" .
  157. Here is a table of RPC service library routines
  158. available to the C programmer:
  159. .TN "RPC Service Library Routines"
  160. .TS
  161. box;
  162. cfBI s
  163. c c
  164. lfL l.
  165. .sp.5
  166. \s+2RPC Service Library Routines\s-2
  167. .sp.5
  168. _
  169. \fIroutine    description\fP
  170. _
  171. rnusers()    return number of users on remote machine
  172. rusers()    return information about users on remote machine
  173. havedisk()    determine if remote machine has disk
  174. rstat()     get performance data from remote kernel
  175. rwall()     write to specified remote machines
  176. getmaster()    get name of YP master
  177. getrpcport()    get RPC port number
  178. yppasswd()    update user password in yellow pages
  179. .TE
  180. .LP
  181. The other RPC services \(em
  182. .LW ether ,
  183. .LW mount ,
  184. .LW rquota ,
  185. and
  186. .LW spray
  187. \(em are not available to the C programmer as library routines.
  188. They do, however,
  189. have RPC program numbers so they can be invoked with
  190. .LW callrpc() ,
  191. which will be discussed in the next section.
  192. .bp
  193. .NH 2
  194. Intermediate Layer
  195. .LP
  196. The simplest interface, which explicitly makes RPC
  197. calls, uses the functions
  198. .LW callrpc()
  199. and
  200. .LW registerrpc() .
  201. Using this method, another way to get the number of remote users is:
  202. .BS
  203. .LS
  204. #include <stdio.h>
  205. #include <rpcsvc/rusers.h>
  206. .sp.5
  207. main(argc, argv)
  208.     int argc;
  209.     char **argv;
  210. {
  211.     unsigned long nusers;
  212. .sp.5
  213.     if (argc < 2) {
  214.         fprintf(stderr, "usage: nusers hostname\en");
  215.         exit(-1);
  216.     }
  217.     if (callrpc(argv[1],
  218.       RUSERSPROG, RUSERSVERS, RUSERSPROC_NUM,
  219.       xdr_void, 0, xdr_u_long, &nusers) != 0) {
  220.         fprintf(stderr, "error: callrpc\en");
  221.         exit(1);
  222.     }
  223.     printf("%d users on %s\en", nusers, argv[1]);
  224.     exit(0);
  225. }
  226. .Lf
  227. .BE
  228. A program number, version number, and procedure number
  229. defines each RPC procedure.
  230. The program number defines a group
  231. of related remote procedures, each of which has a different
  232. procedure number.
  233. Each program also has a version number,
  234. so when a minor change is made to a remote service
  235. (adding a new procedure, for example),
  236. a new program number doesn't have to be assigned.
  237. When you want to call a procedure to
  238. find the number of remote users, you look up the appropriate
  239. program, version and procedure numbers
  240. in a manual, similar to when you look up the name of memory
  241. allocator when you want to allocate memory.
  242. .LP
  243. The simplest routine in the RPC library
  244. used to make remote procedure calls is
  245. .LW callrpc() .
  246. It has eight parameters.
  247. The first is the name of the remote machine.
  248. The next three parameters
  249. are the program, version, and procedure numbers.
  250. The following two parameters
  251. define the argument of the RPC call, and the final two parameters
  252. are for the return value of the call.
  253. If it completes successfully,
  254. .LW callrpc()
  255. returns zero, but nonzero otherwise.
  256. The exact meaning of the return codes is found in
  257. .LW <rpc/clnt.h> ,
  258. and is in fact an
  259. .LW "enum clnt_stat"
  260. cast into an integer.
  261. .LP
  262. Since data types may be represented differently on different machines,
  263. .LW callrpc()
  264. needs both the type of the RPC argument, as well as
  265. a pointer to the argument itself (and similarly for the result).  For
  266. .LW RUSERSPROC_NUM ,
  267. the return value is an
  268. .LW "unsigned long" ,
  269. so
  270. .LW callrpc()
  271. has
  272. .LW xdr_u_long
  273. as its first return parameter, which says
  274. that the result is of type
  275. .LW "unsigned long" ,
  276. and
  277. .LW &nusers
  278. as its second return parameter,
  279. which is a pointer to where the long result will be placed.  Since
  280. .LW RUSERSPROC_NUM
  281. takes no argument, the argument parameter of
  282. .LW callrpc()
  283. is
  284. .LW xdr_void .
  285. .LP
  286. After trying several times to deliver a message, if
  287. .LW callrpc()
  288. gets no answer, it returns with an error code.
  289. The delivery mechanism is UDP,
  290. which stands for User Datagram Protocol.
  291. Methods for adjusting the number of retries
  292. or for using a different protocol require you to use the lower
  293. layer of the RPC library, discussed later in this document.
  294. The remote server procedure
  295. corresponding to the above might look like this:
  296. .BS
  297. .LS
  298. char *
  299. nuser(indata)
  300.     char *indata;
  301. {
  302.     static int nusers;
  303. .sp.5
  304.     /*
  305.      * code here to compute the number of users
  306.      * and place result in variable nusers
  307.      */
  308.     return((char *)&nusers);
  309. }
  310. .Lf
  311. .BE
  312. .LP
  313. It takes one argument, which is a pointer to the input
  314. of the remote procedure call (ignored in our example),
  315. and it returns a pointer to the result.
  316. In the current version of C,
  317. character pointers are the generic pointers,
  318. so both the input argument and the return value are cast to
  319. .LW "char *" .
  320. .LP
  321. Normally, a server registers all of the RPC calls it plans
  322. to handle, and then goes into an infinite loop waiting to service requests.
  323. In this example, there is only a single procedure
  324. to register, so the main body of the server would look like this:
  325. .BS
  326. .LS
  327. #include <stdio.h>
  328. #include <rpcsvc/rusers.h>
  329. .sp.5
  330. char *nuser();
  331. .sp.5
  332. main()
  333. {
  334.     registerrpc(RUSERSPROG, RUSERSVERS, RUSERSPROC_NUM,
  335.         nuser, xdr_void, xdr_u_long);
  336.     svc_run();        /* never returns */
  337.     fprintf(stderr, "Error: svc_run returned!\en");
  338.     exit(1);
  339. }
  340. .Lf
  341. .BE
  342. .LP
  343. The
  344. .LW registerrpc()
  345. routine establishes what C procedure
  346. corresponds to each RPC procedure number.
  347. The first three parameters,
  348. .LW RUSERPROG ,
  349. .LW RUSERSVERS ,
  350. and
  351. .LW RUSERSPROC_NUM
  352. are the program, version, and procedure numbers
  353. of the remote procedure to be registered;
  354. .LW nuser()
  355. is the name of the C procedure implementing it;
  356. and
  357. .LW xdr_void
  358. and
  359. .LW xdr_u_long
  360. are the types of the input to and output from the procedure.
  361. .LP
  362. Only the UDP transport mechanism can use
  363. .LW registerrpc() ;
  364. thus, it is always safe in conjunction with calls generated by
  365. .LW callrpc() .
  366. .LP
  367. Warning: the UDP transport mechanism can only deal with
  368. arguments and results less than 8K bytes in length.
  369. .NH 2
  370. Assigning Program Numbers
  371. .LP
  372. Program numbers are assigned in groups of 0x20000000 (536870912)
  373. according to the following chart:
  374. .BS
  375. .LS
  376.        0 - 1fffffff    defined by sun
  377. 20000000 - 3fffffff    defined by user
  378. 40000000 - 5fffffff    transient
  379. 60000000 - 7fffffff    reserved
  380. 80000000 - 9fffffff    reserved
  381. a0000000 - bfffffff    reserved
  382. c0000000 - dfffffff    reserved
  383. e0000000 - ffffffff    reserved
  384. .Lf
  385. .BE
  386. Sun Microsystems administers the first group of numbers,
  387. which should be identical for all Sun customers.
  388. If a customer develops an application that might be of general interest,
  389. that application should be given an assigned number in the first range.
  390. The second group of numbers is reserved for specific customer applications.
  391. This range is intended primarily for debugging new programs.
  392. The third group is reserved for applications that
  393. generate program numbers dynamically.
  394. The final groups are reserved for future use, and should not be used.
  395. .LP
  396. To register a protocol specification,
  397. send a request by network mail to
  398. .LW sun!rpc ,
  399. or write to:
  400. .DS
  401. RPC Administrator
  402. Sun Microsystems
  403. 2550 Garcia Ave.
  404. Mountain View, CA 94043
  405. .DE
  406. Please include a complete protocol specification,
  407. similar to those in this manual for NFS and YP.
  408. You will be given a unique program number in return.
  409. .NH 2
  410. Passing Arbitrary Data Types
  411. .LP
  412. In the previous example, the RPC call passes a single
  413. .LW "unsigned long" .
  414. RPC can handle arbitrary data structures, regardless of
  415. different machines' byte orders or structure layout conventions,
  416. by always converting them to a network standard called
  417. .I "eXternal Data Representation"
  418. (XDR) before
  419. sending them over the wire.
  420. The process of converting from a particular machine representation
  421. to XDR format is called
  422. .I serializing ,
  423. and the reverse process is called
  424. .I deserializing .
  425. The type field parameters of
  426. .LW callrpc()
  427. and
  428. .LW registerrpc()
  429. can be a built-in procedure like
  430. .LW xdr_u_long()
  431. in the previous example, or a user supplied one.
  432. XDR has these built-in type routines:
  433. .BS
  434. .LS
  435. xdr_int()      xdr_u_int()      xdr_enum()
  436. xdr_long()     xdr_u_long()     xdr_bool()
  437. xdr_short()    xdr_u_short()    xdr_string()
  438. .Lf
  439. .BE
  440. As an example of a user-defined type routine,
  441. if you wanted to send the structure
  442. .BS
  443. .LS
  444. struct simple {
  445.     int a;
  446.     short b;
  447. } simple;
  448. .Lf
  449. .BE
  450. then you would call
  451. .LW callrpc()
  452. as
  453. .BS
  454. .LS
  455. callrpc(hostname, PROGNUM, VERSNUM, PROCNUM,
  456.         xdr_simple, &simple ...);
  457. .Lf
  458. .BE
  459. where
  460. .LW xdr_simple()
  461. is written as:
  462. .BS
  463. .LS
  464. #include <rpc/rpc.h>
  465. .sp.5
  466. xdr_simple(xdrsp, simplep)
  467.     XDR *xdrsp;
  468.     struct simple *simplep;
  469. {
  470.     if (!xdr_int(xdrsp, &simplep->a))
  471.         return (0);
  472.     if (!xdr_short(xdrsp, &simplep->b))
  473.         return (0);
  474.     return (1);
  475. }
  476. .Lf
  477. .BE
  478. .LP
  479. An XDR routine returns nonzero (true in the sense of C)
  480. if it completes successfully, and zero otherwise.
  481. A complete description of XDR is in the
  482. .I "XDR Protocol Specification" ,
  483. so this section only gives a few examples of XDR implementation.
  484. .LP
  485. In addition to the built-in primitives,
  486. there are also the prefabricated building blocks:
  487. .BS
  488. .LS
  489. xdr_array()       xdr_bytes()
  490. xdr_reference()   xdr_union()
  491. .Lf
  492. .BE
  493. To send a variable array of integers,
  494. you might package them up as a structure like this
  495. .BS
  496. .LS
  497. struct varintarr {
  498.     int *data;
  499.     int arrlnth;
  500. } arr;
  501. .Lf
  502. .BE
  503. and make an RPC call such as
  504. .BS
  505. .LS
  506. callrpc(hostname, PROGNUM, VERSNUM, PROCNUM,
  507.         xdr_varintarr, &arr...);
  508. .Lf
  509. .BE
  510. with
  511. .LW xdr_varintarr()
  512. defined as:
  513. .BS
  514. .LS
  515. xdr_varintarr(xdrsp, arrp)
  516.     XDR *xdrsp;
  517.     struct varintarr *arrp;
  518. {
  519.     xdr_array(xdrsp, &arrp->data, &arrp->arrlnth, MAXLEN,
  520.         sizeof(int), xdr_int);
  521. }
  522. .Lf
  523. .BE
  524. This routine takes as parameters the XDR handle,
  525. a pointer to the array, a pointer to the size of the array,
  526. the maximum allowable array size,
  527. the size of each array element,
  528. and an XDR routine for handling each array element.
  529. .LP
  530. If the size of the array is known in advance, then
  531. the following could also be used to send
  532. out an array of length
  533. .LW SIZE :
  534. .BS
  535. .LS
  536. int intarr[SIZE];
  537. .sp.5
  538. xdr_intarr(xdrsp, intarr)
  539.     XDR *xdrsp;
  540.     int intarr[];
  541. {
  542.     int i;
  543. .sp.5
  544.     for (i = 0; i < SIZE; i++) {
  545.         if (!xdr_int(xdrsp, &intarr[i]))
  546.             return (0);
  547.     }
  548.     return (1);
  549. }
  550. .Lf
  551. .BE
  552. .LP
  553. XDR always converts quantities to 4-byte multiples when deserializing.
  554. Thus, if either of the examples above involved characters
  555. instead of integers, each character would occupy 32 bits.
  556. That is the reason for the XDR routine
  557. .LW xdr_bytes() ,
  558. which is like
  559. .LW xdr_array()
  560. except that it packs characters;
  561. .LW xdr_bytes()
  562. has four parameters, similar to the first four parameters of
  563. .LW xdr_array() .
  564. For null-terminated strings, there is also the
  565. .LW xdr_string()
  566. routine, which is the same as
  567. .LW xdr_bytes()
  568. without the length parameter.
  569. On serializing it gets the string length from
  570. .LW strlen() ,
  571. and on deserializing it creates a null-terminated string.
  572. .LP
  573. Here is a final example that calls the previously written
  574. .LW xdr_simple()
  575. as well as the built-in functions
  576. .LW xdr_string()
  577. and
  578. .LW xdr_reference() ,
  579. which chases pointers:
  580. .BS
  581. .LS
  582. struct finalexample {
  583.     char *string;
  584.     struct simple *simplep;
  585. } finalexample;
  586. .sp.5
  587. xdr_finalexample(xdrsp, finalp)
  588.     XDR *xdrsp;
  589.     struct finalexample *finalp;
  590. {
  591.     int i;
  592. .sp.5
  593.     if (!xdr_string(xdrsp, &finalp->string, MAXSTRLEN))
  594.         return (0);
  595.     if (!xdr_reference(xdrsp, &finalp->simplep,
  596.       sizeof(struct simple), xdr_simple);
  597.         return (0);
  598.     return (1);
  599. }
  600. .Lf
  601. .BE
  602. .bp
  603. .NH
  604. Lowest Layer of RPC
  605. .LP
  606. In the examples given so far,
  607. RPC takes care of many details automatically for you.
  608. In this section, we'll show you how you can change the defaults
  609. by using lower layers of the RPC library.
  610. It is assumed that you are familiar with sockets
  611. and the system calls for dealing with them.
  612. If not, consult the
  613. .I "IPC Primer" .
  614. .LP
  615. There are several occasions when you may need to use lower layers of RPC.
  616. First, you may need to use TCP.
  617. The higher layer uses UDP,
  618. which restricts RPC calls to 8K bytes of data.
  619. Using TCP permits calls to send long streams of data.
  620. For an example, see section 5.2 below.
  621. Second, you may want to allocate and free memory
  622. while serializing or deserializing with XDR routines.
  623. There is no call at the higher level to let you free memory explicitly.
  624. For more explanation, see section 3.2 below.
  625. Third, you may need to perform authentication
  626. on either the client or server side,
  627. by supplying credentials or verifying them.
  628. See the explanation in section 4.4 below.
  629. .NH 2
  630. More on the Server Side
  631. .LP
  632. The server for the
  633. .LW nusers
  634. program shown below does the same thing as the one using
  635. .LW registerrpc()
  636. above, but is written using a lower layer of the RPC package:
  637. .BS
  638. .LS no
  639. #include <stdio.h>
  640. #include <rpc/rpc.h>
  641. #include <rpcsvc/rusers.h>
  642. .sp.5
  643. main()
  644. {
  645.     SVCXPRT *transp;
  646.     int nuser();
  647. .sp.5
  648.     transp = svcudp_create(RPC_ANYSOCK);
  649.     if (transp == NULL){
  650.         fprintf(stderr, "can't create an RPC server\en");
  651.         exit(1);
  652.     }
  653.     pmap_unset(RUSERSPROG, RUSERSVERS);
  654.     if (!svc_register(transp, RUSERSPROG, RUSERSVERS,
  655.               nuser, IPPROTO_UDP)) {
  656.         fprintf(stderr, "can't register RUSER service\en");
  657.         exit(1);
  658.     }
  659.     svc_run();  /* never returns */
  660.     fprintf(stderr, "should never reach this point\en");
  661. }
  662. .sp.5
  663. nuser(rqstp, tranp)
  664.     struct svc_req *rqstp;
  665.     SVCXPRT *transp;
  666. {
  667.     unsigned long nusers;
  668. .sp.5
  669.     switch (rqstp->rq_proc) {
  670.     case NULLPROC:
  671.         if (!svc_sendreply(transp, xdr_void, 0)) {
  672.             fprintf(stderr, "can't reply to RPC call\en");
  673.             exit(1);
  674.         }
  675.         return;
  676.     case RUSERSPROC_NUM:
  677.         /*
  678.          * code here to compute the number of users
  679.          * and put in variable nusers
  680.          */
  681.         if (!svc_sendreply(transp, xdr_u_long, &nusers) {
  682.             fprintf(stderr, "can't reply to RPC call\en");
  683.             exit(1);
  684.         }
  685.         return;
  686.     default:
  687.         svcerr_noproc(transp);
  688.         return;
  689.     }
  690. }
  691. .Lf
  692. .BE
  693. .LP
  694. First, the server gets a transport handle, which is used
  695. for sending out RPC messages.
  696. .LW registerrpc()
  697. uses
  698. .LW svcudp_create()
  699. to get a UDP handle.
  700. If you require a reliable protocol, call
  701. .LW svctcp_create()
  702. instead.
  703. If the argument to
  704. .LW svcudp_create()
  705. is
  706. .LW RPC_ANYSOCK ,
  707. the RPC library creates a socket
  708. on which to send out RPC calls.
  709. Otherwise,
  710. .LW svcudp_create()
  711. expects its argument to be a valid socket number.
  712. If you specify your own socket, it can be bound or unbound.
  713. If it is bound to a port by the user, the port numbers of
  714. .LW svcudp_create()
  715. and
  716. .LW clntudp_create()
  717. (the low-level client routine) must match.
  718. .LP
  719. When the user specifies
  720. .LW RPC_ANYSOCK
  721. for a socket or gives an unbound socket,
  722. the system determines port numbers in the following way:
  723. when a server starts up,
  724. it advertises to a port mapper demon on its local machine,
  725. which picks a port number for the RPC procedure
  726. if the socket specified to
  727. .LW svcudp_create()
  728. isn't already bound.
  729. When the
  730. .LW clntudp_create()
  731. call is made with an unbound socket,
  732. the system queries the port mapper on
  733. the machine to which the call is being made,
  734. and gets the appropriate port number.
  735. If the port mapper is not running
  736. or has no port corresponding to the RPC call,
  737. the RPC call fails.
  738. Users can make RPC calls
  739. to the port mapper themselves.
  740. The appropriate procedure
  741. numbers are in the include file
  742. .LW <rpc/pmap_prot.h> .
  743. .LP
  744. After creating an
  745. .LW SVCXPRT ,
  746. the next step is to call
  747. .LW pmap_unset()
  748. so that if the
  749. .LW nusers
  750. server crashed earlier,
  751. any previous trace of it is erased before restarting.
  752. More precisely,
  753. .LW pmap_unset()
  754. erases the entry for
  755. .LW RUSERSPROG
  756. from the port mapper's tables.
  757. .LP
  758. Finally, we associate the program number for
  759. .LW nusers
  760. with the procedure
  761. .LW nuser() .
  762. The final argument to
  763. .LW svc_register()
  764. is normally the protocol being used,
  765. which, in this case, is
  766. .LW IPPROTO_UDP .
  767. Notice that unlike
  768. .LW registerrpc() ,
  769. there are no XDR routines involved
  770. in the registration process.
  771. Also, registration is done on the program,
  772. rather than procedure, level.
  773. .LP
  774. The user routine
  775. .LW nuser()
  776. must call and dispatch the appropriate XDR routines
  777. based on the procedure number.
  778. Note that
  779. two things are handled by
  780. .LW nuser()
  781. that
  782. .LW registerrpc()
  783. handles automatically.
  784. The first is that procedure
  785. .LW NULLPROC
  786. (currently zero) returns with no arguments.
  787. This can be used as a simple test
  788. for detecting if a remote program is running.
  789. Second, there is a check for invalid procedure numbers.
  790. If one is detected,
  791. .LW svcerr_noproc()
  792. is called to handle the error.
  793. .LP
  794. The user service routine serializes the results and returns
  795. them to the RPC caller via
  796. .LW svc_sendreply() .
  797. Its first parameter is the
  798. .LW SVCXPRT
  799. handle, the second is the XDR routine,
  800. and the third is a pointer to the data to be returned.
  801. Not illustrated above is how a server
  802. handles an RPC program that passes data.
  803. As an example, we can add a procedure
  804. .LW RUSERSPROC_BOOL ,
  805. which has an argument
  806. .LW nusers ,
  807. and returns
  808. .LW TRUE
  809. or
  810. .LW FALSE
  811. depending on whether there are nusers logged on.
  812. It would look like this:
  813. .BS
  814. .LS
  815. case RUSERSPROC_BOOL: {
  816.     int bool;
  817.     unsigned nuserquery;
  818. .sp.5
  819.     if (!svc_getargs(transp, xdr_u_int, &nuserquery) {
  820.         svcerr_decode(transp);
  821.         return;
  822.     }
  823.     /*
  824.      * code to set nusers = number of users
  825.      */
  826.     if (nuserquery == nusers)
  827.         bool = TRUE;
  828.     else
  829.         bool = FALSE;
  830.     if (!svc_sendreply(transp, xdr_bool, &bool){
  831.          fprintf(stderr, "can't reply to RPC call\en");
  832.          exit(1);
  833.     }
  834.     return;
  835. }
  836. .Lf
  837. .BE
  838. .LP
  839. The relevant routine is
  840. .LW svc_getargs() ,
  841. which takes an
  842. .LW SVCXPRT
  843. handle, the XDR routine,
  844. and a pointer to where the input is to be placed as arguments.
  845. .NH 2
  846. Memory Allocation with XDR
  847. .LP
  848. XDR routines not only do input and output,
  849. they also do memory allocation.
  850. This is why the second parameter of
  851. .LW xdr_array()
  852. is a pointer to an array, rather than the array itself.
  853. If it is
  854. .LW NULL ,
  855. then
  856. .LW xdr_array()
  857. allocates space for the array and returns a pointer to it,
  858. putting the size of the array in the third argument.
  859. As an example, consider the following XDR routine
  860. .LW xdr_chararr1() ,
  861. which deals with a fixed array of bytes with length
  862. .LW SIZE :
  863. .BS
  864. .LS
  865. xdr_chararr1(xdrsp, chararr)
  866.     XDR *xdrsp;
  867.     char chararr[];
  868. {
  869.     char *p;
  870.     int len;
  871. .sp.5
  872.     p = chararr;
  873.     len = SIZE;
  874.     return (xdr_bytes(xdrsp, &p, &len, SIZE));
  875. }
  876. .Lf
  877. .BE
  878. It might be called from a server like this,
  879. .BS
  880. .LS
  881. char chararr[SIZE];
  882. .sp.5
  883. svc_getargs(transp, xdr_chararr1, chararr);
  884. .Lf
  885. .BE
  886. where
  887. .LW chararr
  888. has already allocated space.
  889. If you want XDR to do the allocation,
  890. you would have to rewrite this routine in the following way:
  891. .BS
  892. .LS
  893. xdr_chararr2(xdrsp, chararrp)
  894.     XDR *xdrsp;
  895.     char **chararrp;
  896. {
  897.     int len;
  898. .sp.5
  899.     len = SIZE;
  900.     return (xdr_bytes(xdrsp, charrarrp, &len, SIZE));
  901. }
  902. .Lf
  903. .BE
  904. Then the RPC call might look like this:
  905. .BS
  906. .LS
  907. char *arrptr;
  908. .sp.5
  909. arrptr = NULL;
  910. svc_getargs(transp, xdr_chararr2, &arrptr);
  911. /*
  912.  * use the result here
  913.  */
  914. svc_freeargs(transp, xdr_chararr2, &arrptr);
  915. .Lf
  916. .BE
  917. After using the character array, it can be freed with
  918. .LW svc_freeargs() .
  919. In the routine
  920. .LW xdr_finalexample()
  921. given earlier, if
  922. .LW finalp->string
  923. was
  924. .LW NULL
  925. in the call
  926. .BS
  927. .LS
  928. svc_getargs(transp, xdr_finalexample, &finalp);
  929. .Lf
  930. .BE
  931. then
  932. .BS
  933. .LS
  934. svc_freeargs(xdrsp, xdr_finalexample, &finalp);
  935. .Lf
  936. .BE
  937. frees the array allocated to hold
  938. .LW finalp->string ;
  939. otherwise, it frees nothing.
  940. The same is true for
  941. .LW finalp->simplep .
  942. .LP
  943. To summarize, each XDR routine is responsible
  944. for serializing, deserializing, and allocating memory.
  945. When an XDR routine is called from
  946. .LW callrpc() ,
  947. the serializing part is used.
  948. When called from
  949. .LW svc_getargs() ,
  950. the deserializer is used.
  951. And when called from
  952. .LW svc_freeargs() ,
  953. the memory deallocator is used.
  954. When building simple examples like those in this section,
  955. a user doesn't have to worry about the three modes.
  956. The XDR reference manual has examples of more
  957. sophisticated XDR routines that
  958. determine which of the three modes they are in
  959. to function correctly.
  960. .NH 2
  961. The Calling Side
  962. .LP
  963. When you use
  964. .LW callrpc() ,
  965. you have no control over the RPC delivery
  966. mechanism or the socket used to transport the data.
  967. To illustrate the layer of RPC that lets you adjust these
  968. parameters, consider the following code to call the
  969. .LW nusers
  970. service:
  971. .BS
  972. .LS no
  973. #include <stdio.h>
  974. #include <rpc/rpc.h>
  975. #include <rpcsvc/rusers.h>
  976. #include <sys/socket.h>
  977. #include <sys/time.h>
  978. #include <netdb.h>
  979. .sp.5
  980. main(argc, argv)
  981.     int argc;
  982.     char **argv;
  983. {
  984.     struct hostent *hp;
  985.     struct timeval pertry_timeout, total_timeout;
  986.     struct sockaddr_in server_addr;
  987.     int addrlen, sock = RPC_ANYSOCK;
  988.     register CLIENT *client;
  989.     enum clnt_stat clnt_stat;
  990.     unsigned long nusers;
  991. .sp.5
  992.     if (argc < 2) {
  993.         fprintf(stderr, "usage: nusers hostname\en");
  994.         exit(-1);
  995.     }
  996.     if ((hp = gethostbyname(argv[1])) == NULL) {
  997.         fprintf(stderr, "can't get addr for %s\en",argv[1]);
  998.         exit(-1);
  999.     }
  1000.     pertry_timeout.tv_sec = 3;
  1001.     pertry_timeout.tv_usec = 0;
  1002.     addrlen = sizeof(struct sockaddr_in);
  1003.     bcopy(hp->h_addr, (caddr_t)&server_addr.sin_addr,
  1004.         hp->h_length);
  1005.     server_addr.sin_family = AF_INET;
  1006.     server_addr.sin_port =  0;
  1007.     if ((client = clntudp_create(&server_addr, RUSERSPROG,
  1008.       RUSERSVERS, pertry_timeout, &sock)) == NULL) {
  1009.         clnt_pcreateerror("clntudp_create");
  1010.         exit(-1);
  1011.     }
  1012.     total_timeout.tv_sec = 20;
  1013.     total_timeout.tv_usec = 0;
  1014.     clnt_stat = clnt_call(client, RUSERSPROC_NUM, xdr_void,
  1015.         0, xdr_u_long, &nusers, total_timeout);
  1016.     if (clnt_stat != RPC_SUCCESS) {
  1017.         clnt_perror(client, "rpc");
  1018.         exit(-1);
  1019.     }
  1020.     clnt_destroy(client);
  1021. }
  1022. .Lf
  1023. .BE
  1024. The low-level version of
  1025. .LW callrpc()
  1026. is
  1027. .LW clnt_call() ,
  1028. which takes a
  1029. .LW CLIENT
  1030. pointer rather than a host name.  The parameters to
  1031. .LW clnt_call()
  1032. are a
  1033. .LW CLIENT
  1034. pointer, the procedure number,
  1035. the XDR routine for serializing the argument,
  1036. a pointer to the argument,
  1037. the XDR routine for deserializing the return value,
  1038. a pointer to where the return value will be placed,
  1039. and the time in seconds to wait for a reply.
  1040. .LP
  1041. The
  1042. .LW CLIENT
  1043. pointer is encoded with the transport mechanism.
  1044. .LW callrpc()
  1045. uses UDP, thus it calls
  1046. .LW clntudp_create()
  1047. to get a
  1048. .LW CLIENT
  1049. pointer.  To get TCP (Transport Control Protocol), you would use
  1050. .LW clnttcp_create() .
  1051. .LP
  1052. The parameters to
  1053. .LW clntudp_create()
  1054. are the server address, the length of the server address,
  1055. the program number, the version number,
  1056. a timeout value (between tries), and a pointer to a socket.
  1057. The final argument to
  1058. .LW clnt_call()
  1059. is the total time to wait for a response.
  1060. Thus, the number of tries is the
  1061. .LW clnt_call()
  1062. timeout divided by the
  1063. .LW clntudp_create()
  1064. timeout.
  1065. .LP
  1066. There is one thing to note when using the
  1067. .LW clnt_destroy()
  1068. call.
  1069. It deallocates any space associated with the
  1070. .LW CLIENT
  1071. handle, but it does not close the socket associated with it,
  1072. which was passed as an argument to
  1073. .LW clntudp_create() .
  1074. The reason is that if
  1075. there are multiple client handles using the same socket,
  1076. then it is possible to close one handle
  1077. without destroying the socket that other handles
  1078. are using.
  1079. .LP
  1080. To make a stream connection, the call to
  1081. .LW clntudp_create()
  1082. is replaced with a call to
  1083. .LW clnttcp_create() .
  1084. .BS
  1085. .LS
  1086. clnttcp_create(&server_addr, prognum, versnum, &socket,
  1087.                inputsize, outputsize);
  1088. .Lf
  1089. .BE
  1090. There is no timeout argument; instead, the receive and send buffer
  1091. sizes must be specified.  When the
  1092. .LW clnttcp_create()
  1093. call is made, a TCP connection is established.
  1094. All RPC calls using that
  1095. .LW CLIENT
  1096. handle would use this connection.
  1097. The server side of an RPC call using TCP has
  1098. .LW svcudp_create()
  1099. replaced by
  1100. .LW svctcp_create() .
  1101. .bp
  1102. .NH
  1103. Other RPC Features
  1104. .LP
  1105. This section discusses some other aspects of RPC
  1106. that are occasionally useful.
  1107. .NH 2
  1108. Select on the Server Side
  1109. .LP
  1110. Suppose a process is processing RPC requests
  1111. while performing some other activity.
  1112. If the other activity involves periodically updating a data structure,
  1113. the process can set an alarm signal before calling
  1114. .LW svc_run() .
  1115. But if the other activity
  1116. involves waiting on a a file descriptor, the
  1117. .LW svc_run()
  1118. call won't work.
  1119. The code for
  1120. .LW svc_run()
  1121. is as follows:
  1122. .BS
  1123. .LS
  1124. void
  1125. svc_run()
  1126. {
  1127.     int readfds;
  1128. .sp.5
  1129.     for (;;) {
  1130.         readfds = svc_fds;
  1131.         switch (select(32, &readfds, NULL, NULL, NULL)) {
  1132. .sp.5
  1133.         case -1:
  1134.             if (errno == EINTR)
  1135.                 continue;
  1136.             perror("rstat: select");
  1137.             return;
  1138.         case 0:
  1139.             break;
  1140.         default:
  1141.             svc_getreq(readfds);
  1142.         }
  1143.     }
  1144. }
  1145. .Lf
  1146. .BE
  1147. .LP
  1148. You can bypass
  1149. .LW svc_run()
  1150. and call
  1151. .LW svc_getreq()
  1152. yourself.
  1153. All you need to know are the file descriptors
  1154. of the socket(s) associated with the programs you are waiting on.
  1155. Thus you can have your own
  1156. .LW select()
  1157. that waits on both the RPC socket,
  1158. and your own descriptors.
  1159. .NH 2
  1160. Broadcast RPC
  1161. .LP
  1162. The
  1163. .I portmapper
  1164. is a daemon that converts RPC program numbers
  1165. into DARPA protocol port numbers; see
  1166. .LW portmap (8).
  1167. You can't do broadcast RPC without the portmapper,
  1168. .LW pmap ,
  1169. in conjunction with standard RPC protocols.
  1170. Here are the main differences between
  1171. broadcast RPC and normal RPC calls:
  1172. .IP 1.
  1173. Normal RPC expects one answer, whereas
  1174. broadcast RPC expects many answers
  1175. (one or more answer from each responding machine).
  1176. .IP 2.
  1177. Broadcast RPC can only be supported by packet-oriented (connectionless)
  1178. transport protocols like UPD/IP.
  1179. .IP 3.
  1180. The implementation of broadcast RPC
  1181. treats all unsuccessful responses as garbage by filtering them out.
  1182. Thus, if there is a version mismatch between the
  1183. broadcaster and a remote service,
  1184. the user of broadcast RPC never knows.
  1185. .IP 4.
  1186. All broadcast messages are sent to the portmap port.
  1187. Thus, only services that register themselves with their portmapper
  1188. are accessible via the broadcast RPC mechanism.
  1189. .NH 3
  1190. Broadcast RPC Synopsis
  1191. .LP
  1192. .BS
  1193. .LS
  1194. #include <rpc/pmap_clnt.h>
  1195. .sp.5
  1196. enum clnt_stat    clnt_stat;
  1197. .sp.5
  1198. clnt_stat =
  1199. clnt_broadcast(prog, vers, proc, xargs, argsp, xresults,
  1200.     resultsp, eachresult)
  1201. u_long        prog;        /* program number */
  1202. u_long        vers;        /* version number */
  1203. u_long        proc;        /* procedure number */
  1204. xdrproc_t    xargs;        /* xdr routine for args */
  1205. caddr_t        argsp;        /* pointer to args */
  1206. xdrproc_t    xresults;    /* xdr routine for results */
  1207. caddr_t        resultsp;    /* pointer to results */
  1208. bool_t (*eachresult)();    /* call with each result gotten */
  1209. .Lf
  1210. .BE
  1211. The procedure
  1212. .LW eachresult()
  1213. is called each time a valid result is obtained.
  1214. It returns a boolean that indicates
  1215. whether or not the client wants more responses.
  1216. .BS
  1217. .LS
  1218. bool_t            done;
  1219. .sp.5
  1220. done =
  1221. eachresult(resultsp, raddr)
  1222. caddr_t resultsp;
  1223. struct sockaddr_in *raddr;  /* addr of responding machine */
  1224. .Lf
  1225. .BE
  1226. If
  1227. .LW done
  1228. is
  1229. .LW TRUE ,
  1230. then broadcasting stops and
  1231. .LW clnt_broadcast()
  1232. returns successfully.
  1233. Otherwise, the routine waits for another response.
  1234. The request is rebroadcast
  1235. after a few seconds of waiting.
  1236. If no responses come back,
  1237. the routine returns with
  1238. .LW RPC_TIMEDOUT .
  1239. To interpret
  1240. .LW clnt_stat
  1241. errors, feed the error code to
  1242. .LW clnt_perrno() .
  1243. .NH 2
  1244. Batching
  1245. .LP
  1246. The RPC architecture is designed so that clients send a call message,
  1247. and wait for servers to reply that the call succeeded.
  1248. This implies that clients do not compute
  1249. while servers are processing a call.
  1250. This is inefficient if the client does not want or need
  1251. an acknowledgement for every message sent.
  1252. It is possible for clients to continue computing
  1253. while waiting for a response,
  1254. using RPC batch facilities.
  1255. .LP
  1256. RPC messages can be placed in a ``pipeline'' of calls
  1257. to a desired server; this is called batching.
  1258. Batching assumes that:
  1259. 1) each RPC call in the pipeline requires no response from the server,
  1260. and the server does not send a response message; and
  1261. 2) the pipeline of calls is transported on a reliable
  1262. byte stream transport such as TCP/IP.
  1263. Since the server does not respond to every call,
  1264. the client can generate new calls in parallel
  1265. with the server executing previous calls.
  1266. Furthermore, the TCP/IP implementation can buffer up
  1267. many call messages, and send them to the server in one
  1268. .LW write()
  1269. system call.  This overlapped execution
  1270. greatly decreases the interprocess communication overhead of
  1271. the client and server processes,
  1272. and the total elapsed time of a series of calls.
  1273. .LP
  1274. Since the batched calls are buffered,
  1275. the client should eventually do a legitimate call
  1276. in order to flush the pipeline.
  1277. .LP
  1278. A contrived example of batching follows.
  1279. Assume a string rendering service (like a window system)
  1280. has two similar calls: one renders a string and returns void results,
  1281. while the other renders a string and remains silent.
  1282. The service (using the TCP/IP transport) may look like:
  1283. .BS
  1284. .LS no
  1285. #include <stdio.h>
  1286. #include <rpc/rpc.h>
  1287. #include <rpcsvc/windows.h>
  1288. .sp.5
  1289. void windowdispatch();
  1290. .sp.5
  1291. main()
  1292. {
  1293.     SVCXPRT *transp;
  1294. .sp.5
  1295.     transp = svctcp_create(RPC_ANYSOCK, 0, 0);
  1296.     if (transp == NULL){
  1297.         fprintf(stderr, "can't create an RPC server\en");
  1298.         exit(1);
  1299.     }
  1300.     pmap_unset(WINDOWPROG, WINDOWVERS);
  1301.     if (!svc_register(transp, WINDOWPROG, WINDOWVERS,
  1302.       windowdispatch, IPPROTO_TCP)) {
  1303.         fprintf(stderr, "can't register WINDOW service\en");
  1304.         exit(1);
  1305.     }
  1306.     svc_run();  /* never returns */
  1307.     fprintf(stderr, "should never reach this point\en");
  1308. }
  1309. .sp.5
  1310. void
  1311. windowdispatch(rqstp, transp)
  1312.     struct svc_req *rqstp;
  1313.     SVCXPRT *transp;
  1314. {
  1315.     char *s = NULL;
  1316. .sp.5
  1317.     switch (rqstp->rq_proc) {
  1318.     case NULLPROC:
  1319.         if (!svc_sendreply(transp, xdr_void, 0)) {
  1320.             fprintf(stderr, "can't reply to RPC call\en");
  1321.             exit(1);
  1322.         }
  1323.         return;
  1324.     case RENDERSTRING:
  1325.         if (!svc_getargs(transp, xdr_wrapstring, &s)) {
  1326.             fprintf(stderr, "can't decode arguments\en");
  1327.             /*
  1328.              * tell caller he screwed up
  1329.              */
  1330.             svcerr_decode(transp);
  1331.             break;
  1332.         }
  1333.         /*
  1334.          * call here to render the string s
  1335.          */
  1336.         if (!svc_sendreply(transp, xdr_void, NULL)) {
  1337.             fprintf(stderr, "can't reply to RPC call\en");
  1338.             exit(1);
  1339.         }
  1340.         break;
  1341.     case RENDERSTRING_BATCHED:
  1342.         if (!svc_getargs(transp, xdr_wrapstring, &s)) {
  1343.             fprintf(stderr, "can't decode arguments\en");
  1344.             /*
  1345.              * we are silent in the face of protocol errors
  1346.              */
  1347.             break;
  1348.         }
  1349.         /*
  1350.          * call here to render string s, but send no reply!
  1351.          */
  1352.         break;
  1353.     default:
  1354.         svcerr_noproc(transp);
  1355.         return;
  1356.     }
  1357.     /*
  1358.      * now free string allocated while decoding arguments
  1359.      */
  1360.     svc_freeargs(transp, xdr_wrapstring, &s);
  1361. }
  1362. .Lf
  1363. .BE
  1364. Of course the service could have one procedure
  1365. that takes the string and a boolean
  1366. to indicate whether or not the procedure should respond.
  1367. .LP
  1368. In order for a client to take advantage of batching,
  1369. the client must perform RPC calls on a TCP-based transport
  1370. and the actual calls must have the following attributes:
  1371. 1) the result's XDR routine must be zero
  1372. .LW NULL ), (
  1373. and 2) the RPC call's timeout must be zero.
  1374. .LP
  1375. Here is an example of a client that uses batching
  1376. to render a bunch of strings;
  1377. the batching is flushed when the client gets a null string:
  1378. .BS
  1379. .LS no
  1380. #include <stdio.h>
  1381. #include <rpc/rpc.h>
  1382. #include <rpcsvc/windows.h>
  1383. #include <sys/socket.h>
  1384. #include <sys/time.h>
  1385. #include <netdb.h>
  1386. .sp.5
  1387. main(argc, argv)
  1388.     int argc;
  1389.     char **argv;
  1390. {
  1391.     struct hostent *hp;
  1392.     struct timeval pertry_timeout, total_timeout;
  1393.     struct sockaddr_in server_addr;
  1394.     int addrlen, sock = RPC_ANYSOCK;
  1395.     register CLIENT *client;
  1396.     enum clnt_stat clnt_stat;
  1397.     char buf[1000], *s = buf;
  1398. .sp.5
  1399.     /* initial as in example 3.3
  1400.      */
  1401.     if ((client = clnttcp_create(&server_addr,
  1402.       WINDOWPROG, WINDOWVERS, &sock, 0, 0)) == NULL) {
  1403.         perror("clnttcp_create");
  1404.         exit(-1);
  1405.     }
  1406.     total_timeout.tv_sec = 0;
  1407.     total_timeout.tv_usec = 0;
  1408.     while (scanf("%s", s) != EOF) {
  1409.         clnt_stat = clnt_call(client, RENDERSTRING_BATCHED,
  1410.             xdr_wrapstring, &s, NULL, NULL, total_timeout);
  1411.         if (clnt_stat != RPC_SUCCESS) {
  1412.             clnt_perror(client, "batched rpc");
  1413.             exit(-1);
  1414.         }
  1415.     }
  1416.     /* now flush the pipeline
  1417.      */
  1418.     total_timeout.tv_sec = 20;
  1419.     clnt_stat = clnt_call(client, NULLPROC, xdr_void, NULL,
  1420.         xdr_void, NULL, total_timeout);
  1421.     if (clnt_stat != RPC_SUCCESS) {
  1422.         clnt_perror(client, "rpc");
  1423.         exit(-1);
  1424.     }
  1425.     clnt_destroy(client);
  1426. }
  1427. .Lf
  1428. .BE
  1429. Since the server sends no message,
  1430. the clients cannot be notified of any of the failures that may occur.
  1431. Therefore, clients are on their own when it comes to handling errors.
  1432. .LP
  1433. The above example was completed to render
  1434. all of the (2000) lines in the file
  1435. .I /etc/termcap .
  1436. The rendering service did nothing but throw the lines away.
  1437. The example was run in the following four configurations:
  1438. 1) machine to itself, regular RPC;
  1439. 2) machine to itself, batched RPC;
  1440. 3) machine to another, regular RPC; and
  1441. 4) machine to another, batched RPC.
  1442. The results are as follows:
  1443. 1) 50 seconds;
  1444. 2) 16 seconds;
  1445. 3) 52 seconds;
  1446. 4) 10 seconds.
  1447. Running
  1448. .LW fscanf()
  1449. on
  1450. .I /etc/termcap
  1451. only requires six seconds.
  1452. These timings show the advantage of protocols
  1453. that allow for overlapped execution,
  1454. though these protocols are often hard to design.
  1455. .NH 2
  1456. Authentication
  1457. .LP
  1458. In the examples presented so far,
  1459. the caller never identified itself to the server,
  1460. and the server never required an ID from the caller.
  1461. Clearly, some network services, such as a network filesystem,
  1462. require stronger security than what has been presented so far.
  1463. .LP
  1464. In reality, every RPC call is authenticated by
  1465. the RPC package on the server, and similarly,
  1466. the RPC client package generates and sends authentication parameters.
  1467. Just as different transports (TCP/IP or UDP/IP)
  1468. can be used when creating RPC clients and servers,
  1469. different forms of authentication can be associated with RPC clients;
  1470. the default authentication type used as a default is type
  1471. .I none .
  1472. .LP
  1473. The authentication subsystem of the RPC package is open ended.
  1474. That is, numerous types of authentication are easy to support.
  1475. However, this section deals only with
  1476. .I unix
  1477. type authentication, which besides
  1478. .I none
  1479. is the only supported type.
  1480. .NH 3
  1481. The Client Side
  1482. .LP
  1483. When a caller creates a new RPC client handle as in:
  1484. .BS
  1485. .LS
  1486. clnt = clntudp_create(address, prognum, versnum,
  1487.               wait, sockp)
  1488. .Lf
  1489. .BE
  1490. the appropriate transport instance defaults
  1491. the associate authentication handle to be
  1492. .BS
  1493. .LS
  1494. clnt->cl_auth = authnone_create();
  1495. .Lf
  1496. .BE
  1497. The RPC client can choose to use
  1498. .I unix
  1499. style authentication by setting
  1500. .LW clnt->cl_auth
  1501. after creating the RPC client handle:
  1502. .BS
  1503. .LS
  1504. clnt->cl_auth = authunix_create_default();
  1505. .Lf
  1506. .BE
  1507. This causes each RPC call associated with
  1508. .LW clnt
  1509. to carry with it the following authentication credentials structure:
  1510. .BS
  1511. .LS
  1512. /*
  1513.  * Unix style credentials.
  1514.  */
  1515. struct authunix_parms {
  1516.     u_long     aup_time;    /* credentials creation time */
  1517.     char *aup_machname;    /* host name where client is */
  1518.     int     aup_uid;    /* client's UNIX effective uid */
  1519.     int     aup_gid;    /* client's current group id */
  1520.     u_int    aup_len;    /* element length of aup_gids */
  1521.     int     *aup_gids;    /* array of groups user is in */
  1522. };
  1523. .Lf
  1524. .BE
  1525. These fields are set by
  1526. .LW authunix_create_default()
  1527. by invoking the appropriate system calls.
  1528. Since the RPC user created this new style of authentication,
  1529. the user is responsible for destroying it with:
  1530. .BS
  1531. .LS
  1532. auth_destroy(clnt->cl_auth);
  1533. .Lf
  1534. .BE
  1535. This should be done in all cases, to conserve memory.
  1536. .NH 3
  1537. The Server Side
  1538. .LP
  1539. Service implementors have a harder time dealing with authentication issues
  1540. since the RPC package passes the service dispatch routine a request
  1541. that has an arbitrary authentication style associated with it.
  1542. Consider the fields of a request handle passed to a service dispatch routine:
  1543. .BS
  1544. .LS
  1545. /*
  1546.  * An RPC Service request
  1547.  */
  1548. struct svc_req {
  1549.     u_long    rq_prog;        /* service program number */
  1550.     u_long    rq_vers;        /* service protocol vers num */
  1551.     u_long    rq_proc;        /* desired procedure number */
  1552.     struct opaque_auth
  1553.             rq_cred;        /* raw credentials from wire */
  1554.     caddr_t rq_clntcred;    /* credentials (read only) */
  1555. };
  1556. .Lf
  1557. .BE
  1558. The
  1559. .LW rq_cred
  1560. is mostly opaque, except for one field of interest:
  1561. the style of authentication credentials:
  1562. .BS
  1563. .LS
  1564. /*
  1565.  * Authentication info.  Mostly opaque to the programmer.
  1566.  */
  1567. struct opaque_auth {
  1568.     enum_t    oa_flavor;    /* style of credentials */
  1569.     caddr_t    oa_base;    /* address of more auth stuff */
  1570.     u_int    oa_length;    /* not to exceed MAX_AUTH_BYTES */
  1571. };
  1572. .Lf
  1573. .BE
  1574. The RPC package guarantees the following
  1575. to the service dispatch routine:
  1576. .IP 1.
  1577. That the request's
  1578. .LW rq_cred
  1579. is well formed.  Thus the service implementor may inspect the request's
  1580. .LW rq_cred.oa_flavor
  1581. to determine which style of authentication the caller used.
  1582. The service implementor may also wish to inspect the other fields of
  1583. .LW rq_cred
  1584. if the style is not one of the styles supported by the RPC package.
  1585. .IP 2.
  1586. That the request's
  1587. .LW rq_clntcred
  1588. field is either
  1589. .LW NULL
  1590. or points to a well formed structure
  1591. that corresponds to a supported style of authentication credentials.
  1592. Remember that only
  1593. .I unix
  1594. style is currently supported, so (currently)
  1595. .LW rq_clntcred
  1596. could be cast to a pointer to an
  1597. .LW authunix_parms
  1598. structure.  If
  1599. .LW rq_clntcred
  1600. is
  1601. .LW NULL ,
  1602. the service implementor may wish to inspect the other (opaque) fileds of
  1603. .LW rq_cred
  1604. in case the service knows about a new type of authentication
  1605. that the RPC package does not know about.
  1606. .LP
  1607. Our remote users service example can be extended so that
  1608. it computes results for all users except UID 16:
  1609. .BS
  1610. .LS no
  1611. nuser(rqstp, tranp)
  1612.     struct svc_req *rqstp;
  1613.     SVCXPRT *transp;
  1614. {
  1615.     struct authunix_parms *unix_cred;
  1616.     int uid;
  1617.     unsigned long nusers;
  1618. .sp.5
  1619.     /*
  1620.      * we don't care about authentication for null proc
  1621.      */
  1622.     if (rqstp->rq_proc == NULLPROC) {
  1623.         if (!svc_sendreply(transp, xdr_void, 0)) {
  1624.             fprintf(stderr, "can't reply to RPC call\en");
  1625.             exit(1);
  1626.          }
  1627.          return;
  1628.     }
  1629.     /*
  1630.      * now get the uid
  1631.      */
  1632.     switch (rqstp->rq_cred.oa_flavor) {
  1633.     case AUTH_UNIX:
  1634.         unix_cred = (struct authunix_parms *)rqstp->rq_clntcred;
  1635.         uid = unix_cred->aup_uid;
  1636.         break;
  1637.     case AUTH_NULL:
  1638.     default:
  1639.         svcerr_weakauth(transp);
  1640.         return;
  1641.     }
  1642.     switch (rqstp->rq_proc) {
  1643.     case RUSERSPROC_NUM:
  1644.         /*
  1645.          * make sure caller is allowed to call this proc
  1646.          */
  1647.         if (uid == 16) {
  1648.             svcerr_systemerr(transp);
  1649.             return;
  1650.         }
  1651.         /*
  1652.          * code here to compute the number of users
  1653.          * and put in variable nusers
  1654.          */
  1655.         if (!svc_sendreply(transp, xdr_u_long, &nusers) {
  1656.             fprintf(stderr, "can't reply to RPC call\en");
  1657.             exit(1);
  1658.         }
  1659.         return;
  1660.     default:
  1661.         svcerr_noproc(transp);
  1662.         return;
  1663.     }
  1664. }
  1665. .Lf
  1666. .BE
  1667. A few things should be noted here.
  1668. First, it is customary not to check
  1669. the authentication parameters associated with the
  1670. .LW NULLPROC
  1671. (procedure number zero).
  1672. Second, if the authentication parameter's type is not suitable
  1673. for your service, you should call
  1674. .LW svcerr_weakauth() .
  1675. And finally, the service protocol itself should return status
  1676. for access denied; in the case of our example, the protocol
  1677. does not have such a status, so we call the service primitive
  1678. .LW svcerr_systemerr()
  1679. instead.
  1680. .LP
  1681. The last point underscores the relation between
  1682. the RPC authentication package and the services;
  1683. RPC deals only with authentication and not with
  1684. individual services' access control.
  1685. The services themselves must implement their own access control policies
  1686. and reflect these policies as return statuses in their protocols.
  1687. .NH 2
  1688. Using Inetd
  1689. .LP
  1690. An RPC server can be started from
  1691. .LW inetd .
  1692. The only difference
  1693. from the usual code is that
  1694. .LW svcudp_create()
  1695. should be called as
  1696. .BS
  1697. .LS
  1698. transp = svcudp_create(0);
  1699. .Lf
  1700. .BE
  1701. since
  1702. .LW inet
  1703. passes a socket as file descriptor 0.
  1704. Also,
  1705. .LW svc_register()
  1706. should be called as
  1707. .BS
  1708. .LS
  1709. svc_register(transp, PROGNUM, VERSNUM, service, 0);
  1710. .Lf
  1711. .BE
  1712. with the final flag as 0,
  1713. since the program would already be registered by
  1714. .LW inetd .
  1715. Remember that if you want to exit
  1716. from the server process and return control to
  1717. .LW inet ,
  1718. you need to explicitly exit, since
  1719. .LW svc_run()
  1720. never returns.
  1721. .LP
  1722. The format of entries in /etc/servers for RPC services is
  1723. .BS
  1724. .LS
  1725. rpc udp \fIserver \0program \0version\fP
  1726. .Lf
  1727. .BE
  1728. where
  1729. .I server
  1730. is the C code implementing the server,
  1731. and
  1732. .I program
  1733. and
  1734. .I version
  1735. are the program and version numbers of the service.
  1736. The key word
  1737. .LW udp
  1738. can be replaced by
  1739. .LW tcp
  1740. for TCP-based RPC services.
  1741. .LP
  1742. If the same program handles multiple versions,
  1743. then the version number can be a range,
  1744. as in this example:
  1745. .BS
  1746. .LS
  1747. rpc udp /usr/etc/rstatd 100001 1-2
  1748. .Lf
  1749. .BE
  1750. .bp
  1751. .NH
  1752. More Examples
  1753. .NH 2
  1754. Versions
  1755. .LP
  1756. By convention, the first version number of program
  1757. .LW PROG
  1758. is
  1759. .LW PROGVERS_ORIG
  1760. and the most recent version is
  1761. .LW PROGVERS .
  1762. Suppose there is a new version of the
  1763. .LW user
  1764. program that returns an
  1765. .LW "unsigned short"
  1766. rather than a
  1767. .LW long .
  1768. If we name this version
  1769. .LW RUSERSVERS_SHORT ,
  1770. then a server that wants to support both versions
  1771. would do a double register.
  1772. .BS
  1773. .LS
  1774. if (!svc_register(transp, RUSERSPROG, RUSERSVERS_ORIG,
  1775.   nuser, IPPROTO_TCP)) {
  1776.     fprintf(stderr, "can't register RUSER service\en");
  1777.     exit(1);
  1778. }
  1779. if (!svc_register(transp, RUSERSPROG, RUSERSVERS_SHORT,
  1780.   nuser, IPPROTO_TCP)) {
  1781.     fprintf(stderr, "can't register RUSER service\en");
  1782.     exit(1);
  1783. }
  1784. .Lf
  1785. .BE
  1786. Both versions can be handled by the same C procedure:
  1787. .BS
  1788. .LS no
  1789. nuser(rqstp, tranp)
  1790.     struct svc_req *rqstp;
  1791.     SVCXPRT *transp;
  1792. {
  1793.     unsigned long nusers;
  1794.     unsigned short nusers2
  1795. .sp.5
  1796.     switch (rqstp->rq_proc) {
  1797.     case NULLPROC:
  1798.         if (!svc_sendreply(transp, xdr_void, 0)) {
  1799.             fprintf(stderr, "can't reply to RPC call\en");
  1800.             exit(1);
  1801.         }
  1802.         return;
  1803.     case RUSERSPROC_NUM:
  1804.         /*
  1805.          * code here to compute the number of users
  1806.          * and put in variable nusers
  1807.          */
  1808.         nusers2 = nusers;
  1809.         if (rqstp->rq_vers != RUSERSVERS_ORIG)
  1810.             return;
  1811.         if (!svc_sendreply(transp, xdr_u_long, &nusers) {
  1812.             fprintf(stderr, "can't reply to RPC call\en");
  1813.             exit(1);
  1814.         } else
  1815.         if (!svc_sendreply(transp, xdr_u_short, &nusers2) {
  1816.             fprintf(stderr, "can't reply to RPC call\en");
  1817.             exit(1);
  1818.         }
  1819.         return;
  1820.     default:
  1821.         svcerr_noproc(transp);
  1822.         return;
  1823.     }
  1824. }
  1825. .Lf
  1826. .BE
  1827. .NH 2
  1828. TCP
  1829. .LP
  1830. Here is an example that is essentially
  1831. .LW rcp .
  1832. The initiator of the RPC
  1833. .LW snd()
  1834. call takes its standard input and sends it to the server
  1835. .LW rcv() ,
  1836. which prints it on standard output.
  1837. The RPC call uses TCP.
  1838. This also illustrates an XDR procedure that behaves differently
  1839. on serialization than on deserialization.
  1840. .BS
  1841. .LS no
  1842. /*
  1843.  * The xdr routine:
  1844.  *        on decode, read from wire, write onto fp
  1845.  *        on encode, read from fp, write onto wire
  1846.  */
  1847. #include <stdio.h>
  1848. #include <rpc/rpc.h>
  1849. .sp.5
  1850. xdr_rcp(xdrs, fp)
  1851.     XDR *xdrs;
  1852.     FILE *fp;
  1853. {
  1854.     unsigned long size;
  1855.     char buf[BUFSIZ], *p;
  1856. .sp.5
  1857.     if (xdrs->x_op == XDR_FREE)/* nothing to free */
  1858.         return 1;
  1859.     while (1) {
  1860.         if (xdrs->x_op == XDR_ENCODE) {
  1861.             if ((size = fread(buf, sizeof(char), BUFSIZ,
  1862.               fp)) == 0 && ferror(fp)) {
  1863.                 fprintf(stderr, "can't fread\en");
  1864.                 exit(1);
  1865.             }
  1866.         }
  1867.         p = buf;
  1868.         if (!xdr_bytes(xdrs, &p, &size, BUFSIZ))
  1869.             return 0;
  1870.         if (size == 0)
  1871.             return 1;
  1872.         if (xdrs->x_op == XDR_DECODE) {
  1873.             if (fwrite(buf, sizeof(char), size,
  1874.               fp) != size) {
  1875.                 fprintf(stderr, "can't fwrite\en");
  1876.                 exit(1);
  1877.             }
  1878.         }
  1879.     }
  1880. }
  1881. .sp.5
  1882. /*
  1883.  * The sender routines
  1884.  */
  1885. #include <stdio.h>
  1886. #include <netdb.h>
  1887. #include <rpc/rpc.h>
  1888. #include <sys/socket.h>
  1889. #include <sys/time.h>
  1890. .sp.5
  1891. main(argc, argv)
  1892.     int argc;
  1893.     char **argv;
  1894. {
  1895.     int err;
  1896. .sp.5
  1897.     if (argc < 2) {
  1898.         fprintf(stderr, "usage: %s servername\en", argv[0]);
  1899.         exit(-1);
  1900.     }
  1901.     if ((err = callrpctcp(argv[1], RCPPROG, RCPPROC_FP,
  1902.       RCPVERS, xdr_rcp, stdin, xdr_void, 0) != 0)) {
  1903.         clnt_perrno(err);
  1904.         fprintf(stderr, "can't make RPC call\en");
  1905.         exit(1);
  1906.     }
  1907. }
  1908. .sp.5
  1909. callrpctcp(host, prognum, procnum, versnum,
  1910.            inproc, in, outproc, out)
  1911.     char *host, *in, *out;
  1912.     xdrproc_t inproc, outproc;
  1913. {
  1914.     struct sockaddr_in server_addr;
  1915.     int socket = RPC_ANYSOCK;
  1916.     enum clnt_stat clnt_stat;
  1917.     struct hostent *hp;
  1918.     register CLIENT *client;
  1919.     struct timeval total_timeout;
  1920. .sp.5
  1921.     if ((hp = gethostbyname(host)) == NULL) {
  1922.         fprintf(stderr, "can't get addr for '%s'\en", host);
  1923.         exit(-1);
  1924.     }
  1925.     bcopy(hp->h_addr, (caddr_t)&server_addr.sin_addr,
  1926.         hp->h_length);
  1927.     server_addr.sin_family = AF_INET;
  1928.     server_addr.sin_port =  0;
  1929.     if ((client = clnttcp_create(&server_addr, prognum,
  1930.       versnum, &socket, BUFSIZ, BUFSIZ)) == NULL) {
  1931.         perror("rpctcp_create");
  1932.         exit(-1);
  1933.     }
  1934.     total_timeout.tv_sec = 20;
  1935.     total_timeout.tv_usec = 0;
  1936.     clnt_stat = clnt_call(client, procnum,
  1937.         inproc, in, outproc, out, total_timeout);
  1938.     clnt_destroy(client)
  1939.     return (int)clnt_stat;
  1940. }
  1941. .sp.5
  1942. /*
  1943.  * The receiving routines
  1944.  */
  1945. #include <stdio.h>
  1946. #include <rpc/rpc.h>
  1947. .sp.5
  1948. main()
  1949. {
  1950.     register SVCXPRT *transp;
  1951. .sp.5
  1952.     if ((transp = svctcp_create(RPC_ANYSOCK,
  1953.       BUFSIZ, BUFSIZ)) == NULL) {
  1954.         fprintf("svctcp_create: error\en");
  1955.         exit(1);
  1956.     }
  1957.     pmap_unset(RCPPROG, RCPVERS);
  1958.     if (!svc_register(transp,
  1959.       RCPPROG, RCPVERS, rcp_service, IPPROTO_TCP)) {
  1960.         fprintf(stderr, "svc_register: error\en");
  1961.         exit(1);
  1962.     }
  1963.     svc_run();  /* never returns */
  1964.     fprintf(stderr, "svc_run should never return\en");
  1965. }
  1966. .sp.5
  1967. rcp_service(rqstp, transp)
  1968.     register struct svc_req *rqstp;
  1969.     register SVCXPRT *transp;
  1970. {
  1971.     switch (rqstp->rq_proc) {
  1972.     case NULLPROC:
  1973.         if (svc_sendreply(transp, xdr_void, 0) == 0) {
  1974.             fprintf(stderr, "err: rcp_service");
  1975.             exit(1);
  1976.         }
  1977.         return;
  1978.     case RCPPROC_FP:
  1979.         if (!svc_getargs(transp, xdr_rcp, stdout)) {
  1980.             svcerr_decode(transp);
  1981.             return;
  1982.         }
  1983.         if (!svc_sendreply(transp, xdr_void, 0)) {
  1984.             fprintf(stderr, "can't reply\en");
  1985.             return;
  1986.         }
  1987.         exit(0);
  1988.     default:
  1989.         svcerr_noproc(transp);
  1990.         return;
  1991.     }
  1992. }
  1993. .Lf
  1994. .BE
  1995. .NH 2
  1996. Callback Procedures
  1997. .LP
  1998. Occasionally, it is useful to have a server become a client,
  1999. and make an RPC call back the process which is its client.
  2000. An example is remote debugging,
  2001. where the client is a window system program,
  2002. and the server is a debugger running on the remote machine.
  2003. Most of the time,
  2004. the user clicks a mouse button at the debugging window,
  2005. which converts this to a debugger command,
  2006. and then makes an RPC call to the server
  2007. (where the debugger is actually running),
  2008. telling it to execute that command.
  2009. However, when the debugger hits a breakpoint, the roles are reversed,
  2010. and the debugger wants to make an rpc call to the window program,
  2011. so that it can inform the user that a breakpoint has been reached.
  2012.