6bef9e9214f154785cca2b6c81dc3a2f443c6486
[games.git] / lib / libc / rpc / clnt_unix.c
1 /*
2  * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
3  * unrestricted use provided that this legend is included on all tape
4  * media and as a part of the software program in whole or part.  Users
5  * may copy or modify Sun RPC without charge, but are not authorized
6  * to license or distribute it to anyone else except as part of a product or
7  * program developed by the user.
8  *
9  * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
10  * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
11  * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
12  *
13  * Sun RPC is provided with no support and without any obligation on the
14  * part of Sun Microsystems, Inc. to assist in its use, correction,
15  * modification or enhancement.
16  *
17  * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
18  * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
19  * OR ANY PART THEREOF.
20  *
21  * In no event will Sun Microsystems, Inc. be liable for any lost revenue
22  * or profits or other special, indirect and consequential damages, even if
23  * Sun has been advised of the possibility of such damages.
24  *
25  * Sun Microsystems, Inc.
26  * 2550 Garcia Avenue
27  * Mountain View, California  94043
28  *
29  * @(#)clnt_unix.c 1.37 87/10/05 Copyr 1984 Sun Micro
30  * @(#)clnt_unix.c      2.2 88/08/01 4.0 RPCSRC
31  * $FreeBSD: src/lib/libc/rpc/clnt_unix.c,v 1.5 2000/01/27 23:06:37 jasone Exp $
32  * $DragonFly: src/lib/libc/rpc/clnt_unix.c,v 1.4 2005/01/31 22:29:38 dillon Exp $
33  */
34
35 /*
36  * clnt_unix.c, Implements a AF_UNIX based, client side RPC.
37  *
38  * Copyright (C) 1984, Sun Microsystems, Inc.
39  *
40  * AF_UNIX based RPC supports 'batched calls'.
41  * A sequence of calls may be batched-up in a send buffer.  The rpc call
42  * return immediately to the client even though the call was not necessarily
43  * sent.  The batching occurs if the results' xdr routine is NULL (0) AND
44  * the rpc timeout value is zero (see clnt.h, rpc).
45  *
46  * Clients should NOT casually batch calls that in fact return results; that is,
47  * the server side should be aware that a call is batched and not produce any
48  * return message.  Batched calls that produce many result messages can
49  * deadlock (netlock) the client and the server....
50  *
51  * Now go hang yourself.
52  */
53
54 #include "namespace.h"
55 #include <stdio.h>
56 #include <stdlib.h>
57 #include <unistd.h>
58 #include <string.h>
59 #include <rpc/rpc.h>
60 #include <sys/uio.h>
61 #include <sys/socket.h>
62 #include <sys/un.h>
63 #include <netdb.h>
64 #include <errno.h>
65 #include <rpc/pmap_clnt.h>
66 #include "un-namespace.h"
67
68 #define MCALL_MSG_SIZE 24
69
70 static int      readunix();
71 static int      writeunix();
72
73 static enum clnt_stat   clntunix_call();
74 static void             clntunix_abort();
75 static void             clntunix_geterr();
76 static bool_t           clntunix_freeres();
77 static bool_t           clntunix_control();
78 static void             clntunix_destroy();
79
80 static struct clnt_ops unix_ops = {
81         clntunix_call,
82         clntunix_abort,
83         clntunix_geterr,
84         clntunix_freeres,
85         clntunix_destroy,
86         clntunix_control
87 };
88
89 struct ct_data {
90         int             ct_sock;
91         bool_t          ct_closeit;
92         struct timeval  ct_wait;
93         bool_t          ct_waitset;       /* wait set by clnt_control? */
94         struct sockaddr_un ct_addr;
95         struct rpc_err  ct_error;
96         char            ct_mcall[MCALL_MSG_SIZE];       /* marshalled callmsg */
97         u_int           ct_mpos;                        /* pos after marshal */
98         XDR             ct_xdrs;
99 };
100
101 /*
102  * Create a client handle for a unix/ip connection.
103  * If *sockp<0, *sockp is set to a newly created TCP socket and it is
104  * connected to raddr.  If *sockp non-negative then
105  * raddr is ignored.  The rpc/unix package does buffering
106  * similar to stdio, so the client must pick send and receive buffer sizes,];
107  * 0 => use the default.
108  * If raddr->sin_port is 0, then a binder on the remote machine is
109  * consulted for the right port number.
110  * NB: *sockp is copied into a private area.
111  * NB: It is the clients responsibility to close *sockp.
112  * NB: The rpch->cl_auth is set null authentication.  Caller may wish to set this
113  * something more useful.
114  */
115 CLIENT *
116 clntunix_create(raddr, prog, vers, sockp, sendsz, recvsz)
117         struct sockaddr_un *raddr;
118         u_long prog;
119         u_long vers;
120         int *sockp;
121         u_int sendsz;
122         u_int recvsz;
123 {
124         CLIENT *h;
125         struct ct_data *ct = NULL;
126         struct timeval now;
127         struct rpc_msg call_msg;
128         static u_int32_t disrupt;
129         int len;
130
131         if (disrupt == 0)
132                 disrupt = (u_int32_t)(long)raddr;
133
134         h  = (CLIENT *)mem_alloc(sizeof(*h));
135         if (h == NULL) {
136                 (void)fprintf(stderr, "clntunix_create: out of memory\n");
137                 rpc_createerr.cf_stat = RPC_SYSTEMERROR;
138                 rpc_createerr.cf_error.re_errno = errno;
139                 goto fooy;
140         }
141         ct = (struct ct_data *)mem_alloc(sizeof(*ct));
142         if (ct == NULL) {
143                 (void)fprintf(stderr, "clntunix_create: out of memory\n");
144                 rpc_createerr.cf_stat = RPC_SYSTEMERROR;
145                 rpc_createerr.cf_error.re_errno = errno;
146                 goto fooy;
147         }
148
149         /*
150          * If no socket given, open one
151          */
152         if (*sockp < 0) {
153                 *sockp = _socket(AF_UNIX, SOCK_STREAM, 0);
154                 len = strlen(raddr->sun_path) + sizeof(raddr->sun_family) +
155                         sizeof(raddr->sun_len) + 1;
156                 raddr->sun_len = len;
157                 if ((*sockp < 0)
158                     || (_connect(*sockp, (struct sockaddr *)raddr, len) < 0)) {
159                         rpc_createerr.cf_stat = RPC_SYSTEMERROR;
160                         rpc_createerr.cf_error.re_errno = errno;
161                         if (*sockp != -1)
162                                 (void)_close(*sockp);
163                         goto fooy;
164                 }
165                 ct->ct_closeit = TRUE;
166         } else {
167                 ct->ct_closeit = FALSE;
168         }
169
170         /*
171          * Set up private data struct
172          */
173         ct->ct_sock = *sockp;
174         ct->ct_wait.tv_usec = 0;
175         ct->ct_waitset = FALSE;
176         ct->ct_addr = *raddr;
177
178         /*
179          * Initialize call message
180          */
181         (void)gettimeofday(&now, (struct timezone *)0);
182         call_msg.rm_xid = (++disrupt) ^ getpid() ^ now.tv_sec ^ now.tv_usec;
183         call_msg.rm_direction = CALL;
184         call_msg.rm_call.cb_rpcvers = RPC_MSG_VERSION;
185         call_msg.rm_call.cb_prog = prog;
186         call_msg.rm_call.cb_vers = vers;
187
188         /*
189          * pre-serialize the static part of the call msg and stash it away
190          */
191         xdrmem_create(&(ct->ct_xdrs), ct->ct_mcall, MCALL_MSG_SIZE,
192             XDR_ENCODE);
193         if (! xdr_callhdr(&(ct->ct_xdrs), &call_msg)) {
194                 if (ct->ct_closeit) {
195                         (void)_close(*sockp);
196                 }
197                 goto fooy;
198         }
199         ct->ct_mpos = XDR_GETPOS(&(ct->ct_xdrs));
200         XDR_DESTROY(&(ct->ct_xdrs));
201
202         /*
203          * Create a client handle which uses xdrrec for serialization
204          * and authnone for authentication.
205          */
206         xdrrec_create(&(ct->ct_xdrs), sendsz, recvsz,
207             (caddr_t)ct, readunix, writeunix);
208         h->cl_ops = &unix_ops;
209         h->cl_private = (caddr_t) ct;
210         h->cl_auth = authnone_create();
211         return (h);
212
213 fooy:
214         /*
215          * Something goofed, free stuff and barf
216          */
217         if (ct)
218                 mem_free((caddr_t)ct, sizeof(struct ct_data));
219         if (h)
220                 mem_free((caddr_t)h, sizeof(CLIENT));
221         return ((CLIENT *)NULL);
222 }
223
224 static enum clnt_stat
225 clntunix_call(h, proc, xdr_args, args_ptr, xdr_results, results_ptr, timeout)
226         CLIENT *h;
227         u_long proc;
228         xdrproc_t xdr_args;
229         caddr_t args_ptr;
230         xdrproc_t xdr_results;
231         caddr_t results_ptr;
232         struct timeval timeout;
233 {
234         struct ct_data *ct = (struct ct_data *) h->cl_private;
235         XDR *xdrs = &(ct->ct_xdrs);
236         struct rpc_msg reply_msg;
237         u_long x_id;
238         u_int32_t *msg_x_id = (u_int32_t *)(ct->ct_mcall);      /* yuk */
239         bool_t shipnow;
240         int refreshes = 2;
241
242         if (!ct->ct_waitset) {
243                 ct->ct_wait = timeout;
244         }
245
246         shipnow =
247             (xdr_results == (xdrproc_t)0 && timeout.tv_sec == 0
248             && timeout.tv_usec == 0) ? FALSE : TRUE;
249
250 call_again:
251         xdrs->x_op = XDR_ENCODE;
252         ct->ct_error.re_status = RPC_SUCCESS;
253         x_id = ntohl(--(*msg_x_id));
254         if ((! XDR_PUTBYTES(xdrs, ct->ct_mcall, ct->ct_mpos)) ||
255             (! XDR_PUTLONG(xdrs, (long *)&proc)) ||
256             (! AUTH_MARSHALL(h->cl_auth, xdrs)) ||
257             (! (*xdr_args)(xdrs, args_ptr))) {
258                 if (ct->ct_error.re_status == RPC_SUCCESS)
259                         ct->ct_error.re_status = RPC_CANTENCODEARGS;
260                 (void)xdrrec_endofrecord(xdrs, TRUE);
261                 return (ct->ct_error.re_status);
262         }
263         if (! xdrrec_endofrecord(xdrs, shipnow))
264                 return (ct->ct_error.re_status = RPC_CANTSEND);
265         if (! shipnow)
266                 return (RPC_SUCCESS);
267         /*
268          * Hack to provide rpc-based message passing
269          */
270         if (timeout.tv_sec == 0 && timeout.tv_usec == 0) {
271                 return(ct->ct_error.re_status = RPC_TIMEDOUT);
272         }
273
274
275         /*
276          * Keep receiving until we get a valid transaction id
277          */
278         xdrs->x_op = XDR_DECODE;
279         while (TRUE) {
280                 reply_msg.acpted_rply.ar_verf = _null_auth;
281                 reply_msg.acpted_rply.ar_results.where = NULL;
282                 reply_msg.acpted_rply.ar_results.proc = xdr_void;
283                 if (! xdrrec_skiprecord(xdrs))
284                         return (ct->ct_error.re_status);
285                 /* now decode and validate the response header */
286                 if (! xdr_replymsg(xdrs, &reply_msg)) {
287                         if (ct->ct_error.re_status == RPC_SUCCESS)
288                                 continue;
289                         return (ct->ct_error.re_status);
290                 }
291                 if (reply_msg.rm_xid == x_id)
292                         break;
293         }
294
295         /*
296          * process header
297          */
298         _seterr_reply(&reply_msg, &(ct->ct_error));
299         if (ct->ct_error.re_status == RPC_SUCCESS) {
300                 if (! AUTH_VALIDATE(h->cl_auth, &reply_msg.acpted_rply.ar_verf)) {
301                         ct->ct_error.re_status = RPC_AUTHERROR;
302                         ct->ct_error.re_why = AUTH_INVALIDRESP;
303                 } else if (! (*xdr_results)(xdrs, results_ptr)) {
304                         if (ct->ct_error.re_status == RPC_SUCCESS)
305                                 ct->ct_error.re_status = RPC_CANTDECODERES;
306                 }
307                 /* free verifier ... */
308                 if (reply_msg.acpted_rply.ar_verf.oa_base != NULL) {
309                         xdrs->x_op = XDR_FREE;
310                         (void)xdr_opaque_auth(xdrs, &(reply_msg.acpted_rply.ar_verf));
311                 }
312         }  /* end successful completion */
313         else {
314                 /* maybe our credentials need to be refreshed ... */
315                 if (refreshes-- && AUTH_REFRESH(h->cl_auth))
316                         goto call_again;
317         }  /* end of unsuccessful completion */
318         return (ct->ct_error.re_status);
319 }
320
321 static void
322 clntunix_geterr(h, errp)
323         CLIENT *h;
324         struct rpc_err *errp;
325 {
326         struct ct_data *ct =
327             (struct ct_data *) h->cl_private;
328
329         *errp = ct->ct_error;
330 }
331
332 static bool_t
333 clntunix_freeres(cl, xdr_res, res_ptr)
334         CLIENT *cl;
335         xdrproc_t xdr_res;
336         caddr_t res_ptr;
337 {
338         struct ct_data *ct = (struct ct_data *)cl->cl_private;
339         XDR *xdrs = &(ct->ct_xdrs);
340
341         xdrs->x_op = XDR_FREE;
342         return ((*xdr_res)(xdrs, res_ptr));
343 }
344
345 static void
346 clntunix_abort()
347 {
348 }
349
350
351 static bool_t
352 clntunix_control(cl, request, info)
353         CLIENT *cl;
354         int request;
355         char *info;
356 {
357         struct ct_data *ct = (struct ct_data *)cl->cl_private;
358         struct timeval *tv;
359         int len;
360
361         switch (request) {
362         case CLSET_FD_CLOSE:
363                 ct->ct_closeit = TRUE;
364                 break;
365         case CLSET_FD_NCLOSE:
366                 ct->ct_closeit = FALSE;
367                 break;
368         case CLSET_TIMEOUT:
369                 if (info == NULL)
370                         return(FALSE);
371                 tv = (struct timeval *)info;
372                 ct->ct_wait.tv_sec = tv->tv_sec;
373                 ct->ct_wait.tv_usec = tv->tv_usec;
374                 ct->ct_waitset = TRUE;
375                 break;
376         case CLGET_TIMEOUT:
377                 if (info == NULL)
378                         return(FALSE);
379                 *(struct timeval *)info = ct->ct_wait;
380                 break;
381         case CLGET_SERVER_ADDR:
382                 if (info == NULL)
383                         return(FALSE);
384                 *(struct sockaddr_un *)info = ct->ct_addr;
385                 break;
386         case CLGET_FD:
387                 if (info == NULL)
388                         return(FALSE);
389                 *(int *)info = ct->ct_sock;
390                 break;
391         case CLGET_XID:
392                 /*
393                  * use the knowledge that xid is the
394                  * first element in the call structure *.
395                  * This will get the xid of the PREVIOUS call
396                  */
397                 if (info == NULL)
398                         return(FALSE);
399                 *(u_long *)info = ntohl(*(u_long *)ct->ct_mcall);
400                 break;
401         case CLSET_XID:
402                 /* This will set the xid of the NEXT call */
403                 if (info == NULL)
404                         return(FALSE);
405                 *(u_long *)ct->ct_mcall =  htonl(*(u_long *)info - 1);
406                 /* decrement by 1 as clntunix_call() increments once */
407         case CLGET_VERS:
408                 /*
409                  * This RELIES on the information that, in the call body,
410                  * the version number field is the fifth field from the
411                  * begining of the RPC header. MUST be changed if the
412                  * call_struct is changed
413                  */
414                 if (info == NULL)
415                         return(FALSE);
416                 *(u_long *)info = ntohl(*(u_long *)(ct->ct_mcall +
417                                                 4 * BYTES_PER_XDR_UNIT));
418                 break;
419         case CLSET_VERS:
420                 if (info == NULL)
421                         return(FALSE);
422                 *(u_long *)(ct->ct_mcall + 4 * BYTES_PER_XDR_UNIT)
423                                 = htonl(*(u_long *)info);
424                 break;
425         case CLGET_PROG:
426                 /*
427                  * This RELIES on the information that, in the call body,
428                  * the program number field is the  field from the
429                  * begining of the RPC header. MUST be changed if the
430                  * call_struct is changed
431                  */
432                 if (info == NULL)
433                         return(FALSE);
434                 *(u_long *)info = ntohl(*(u_long *)(ct->ct_mcall +
435                                                 3 * BYTES_PER_XDR_UNIT));
436                 break;
437         case CLSET_PROG:
438                 if (info == NULL)
439                         return(FALSE);
440                 *(u_long *)(ct->ct_mcall + 3 * BYTES_PER_XDR_UNIT)
441                                 = htonl(*(u_long *)info);
442                 break;
443         case CLGET_LOCAL_ADDR:
444                 len = sizeof(struct sockaddr);
445                 if (_getsockname(ct->ct_sock, (struct sockaddr *)info, &len) <0)
446                         return(FALSE);
447                 break;
448         case CLGET_RETRY_TIMEOUT:
449         case CLSET_RETRY_TIMEOUT:
450         case CLGET_SVC_ADDR:
451         case CLSET_SVC_ADDR:
452         case CLSET_PUSH_TIMOD:
453         case CLSET_POP_TIMOD:
454         default:
455                 return (FALSE);
456         }
457         return (TRUE);
458 }
459
460
461 static void
462 clntunix_destroy(h)
463         CLIENT *h;
464 {
465         struct ct_data *ct =
466             (struct ct_data *) h->cl_private;
467
468         if (ct->ct_closeit) {
469                 (void)_close(ct->ct_sock);
470         }
471         XDR_DESTROY(&(ct->ct_xdrs));
472         mem_free((caddr_t)ct, sizeof(struct ct_data));
473         mem_free((caddr_t)h, sizeof(CLIENT));
474 }
475
476 /*
477  * _read() and _write() are replaced with _recvmsg()/_sendmsg() so that
478  * we can pass ancillary control data. In this case, the data constists
479  * of credential information which the kernel will fill in for us.
480  * XXX: This code is specific to FreeBSD and will not work on other
481  * platforms without the requisite kernel modifications.
482  */
483 struct cmessage {
484         struct cmsghdr cmsg;
485         struct cmsgcred cmcred;
486 };
487
488 static int __msgread(sock, buf, cnt)
489         int sock;
490         void *buf;
491         size_t cnt;
492 {
493         struct iovec iov[1];
494         struct msghdr msg;
495         struct cmessage cm;
496
497         bzero((char *)&cm, sizeof(cm));
498         iov[0].iov_base = buf;
499         iov[0].iov_len = cnt;
500
501         msg.msg_iov = iov;
502         msg.msg_iovlen = 1;
503         msg.msg_name = NULL;
504         msg.msg_namelen = 0;
505         msg.msg_control = (caddr_t)&cm;
506         msg.msg_controllen = sizeof(struct cmessage);
507         msg.msg_flags = 0;
508
509         return(_recvmsg(sock, &msg, 0));
510 }
511
512 static int __msgwrite(sock, buf, cnt)
513         int sock;
514         void *buf;
515         size_t cnt;
516 {
517         struct iovec iov[1];
518         struct msghdr msg;
519         struct cmessage cm;
520
521         bzero((char *)&cm, sizeof(cm));
522         iov[0].iov_base = buf;
523         iov[0].iov_len = cnt;
524
525         cm.cmsg.cmsg_type = SCM_CREDS;
526         cm.cmsg.cmsg_level = SOL_SOCKET;
527         cm.cmsg.cmsg_len = sizeof(struct cmessage);
528
529         msg.msg_iov = iov;
530         msg.msg_iovlen = 1;
531         msg.msg_name = NULL;
532         msg.msg_namelen = 0;
533         msg.msg_control = (caddr_t)&cm;
534         msg.msg_controllen = sizeof(struct cmessage);
535         msg.msg_flags = 0;
536
537         return(_sendmsg(sock, &msg, 0));
538 }
539
540 /*
541  * Interface between xdr serializer and unix connection.
542  * Behaves like the system calls, read & write, but keeps some error state
543  * around for the rpc level.
544  */
545 static int
546 readunix(ct, buf, len)
547         struct ct_data *ct;
548         caddr_t buf;
549         int len;
550 {
551         fd_set *fds, readfds;
552         struct timeval start, after, duration, delta, tmp, tv;
553         int r, save_errno;
554
555         if (len == 0)
556                 return (0);
557
558         if (ct->ct_sock + 1 > FD_SETSIZE) {
559                 int bytes = howmany(ct->ct_sock + 1, NFDBITS) * sizeof(fd_mask);
560                 fds = (fd_set *)malloc(bytes);
561                 if (fds == NULL)
562                         return (-1);
563                 memset(fds, 0, bytes);
564         } else {
565                 fds = &readfds;
566                 FD_ZERO(fds);
567         }
568
569         gettimeofday(&start, NULL);
570         delta = ct->ct_wait;
571         while (TRUE) {
572                 /* XXX we know the other bits are still clear */
573                 FD_SET(ct->ct_sock, fds);
574                 tv = delta;     /* in case select writes back */
575                 r = _select(ct->ct_sock+1, fds, NULL, NULL, &tv);
576                 save_errno = errno;
577
578                 gettimeofday(&after, NULL);
579                 timersub(&start, &after, &duration);
580                 timersub(&delta, &duration, &tmp);
581                 delta = tmp;
582                 if (delta.tv_sec < 0 || !timerisset(&delta))
583                         r = 0;
584
585                 switch (r) {
586                 case 0:
587                         if (fds != &readfds)
588                                 free(fds);
589                         ct->ct_error.re_status = RPC_TIMEDOUT;
590                         return (-1);
591
592                 case -1:
593                         if (errno == EINTR)
594                                 continue;
595                         if (fds != &readfds)
596                                 free(fds);
597                         ct->ct_error.re_status = RPC_CANTRECV;
598                         ct->ct_error.re_errno = save_errno;
599                         return (-1);
600                 }
601                 break;
602         }
603         switch (len = __msgread(ct->ct_sock, buf, len)) {
604
605         case 0:
606                 /* premature eof */
607                 ct->ct_error.re_errno = ECONNRESET;
608                 ct->ct_error.re_status = RPC_CANTRECV;
609                 len = -1;  /* it's really an error */
610                 break;
611
612         case -1:
613                 ct->ct_error.re_errno = errno;
614                 ct->ct_error.re_status = RPC_CANTRECV;
615                 break;
616         }
617         return (len);
618 }
619
620 static int
621 writeunix(ct, buf, len)
622         struct ct_data *ct;
623         caddr_t buf;
624         int len;
625 {
626         int i, cnt;
627
628         for (cnt = len; cnt > 0; cnt -= i, buf += i) {
629                 if ((i = __msgwrite(ct->ct_sock, buf, cnt)) == -1) {
630                         ct->ct_error.re_errno = errno;
631                         ct->ct_error.re_status = RPC_CANTSEND;
632                         return (-1);
633                 }
634         }
635         return (len);
636 }