home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 January / usenetsourcesnewsgroupsinfomagicjanuary1994.iso / sources / unix / volume1 / rpc / part03 < prev    next >
Encoding:
Internet Message Format  |  1986-11-30  |  50.0 KB

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