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