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