xref: /freebsd/lib/libc/rpc/clnt_vc.c (revision 55141f2c8991b2a6adbf30bb0fe3e6cbc303f06d)
1 /*	$NetBSD: clnt_vc.c,v 1.4 2000/07/14 08:40:42 fvdl Exp $	*/
2 
3 /*-
4  * SPDX-License-Identifier: BSD-3-Clause
5  *
6  * Copyright (c) 2009, Sun Microsystems, Inc.
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions are met:
11  * - Redistributions of source code must retain the above copyright notice,
12  *   this list of conditions and the following disclaimer.
13  * - Redistributions in binary form must reproduce the above copyright notice,
14  *   this list of conditions and the following disclaimer in the documentation
15  *   and/or other materials provided with the distribution.
16  * - Neither the name of Sun Microsystems, Inc. nor the names of its
17  *   contributors may be used to endorse or promote products derived
18  *   from this software without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
24  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30  * POSSIBILITY OF SUCH DAMAGE.
31  */
32 
33 #if defined(LIBC_SCCS) && !defined(lint)
34 static char *sccsid2 = "@(#)clnt_tcp.c 1.37 87/10/05 Copyr 1984 Sun Micro";
35 static char *sccsid = "@(#)clnt_tcp.c	2.2 88/08/01 4.0 RPCSRC";
36 static char sccsid3[] = "@(#)clnt_vc.c 1.19 89/03/16 Copyr 1988 Sun Micro";
37 #endif
38 /*
39  * clnt_tcp.c, Implements a TCP/IP based, client side RPC.
40  *
41  * Copyright (C) 1984, Sun Microsystems, Inc.
42  *
43  * TCP based RPC supports 'batched calls'.
44  * A sequence of calls may be batched-up in a send buffer.  The rpc call
45  * return immediately to the client even though the call was not necessarily
46  * sent.  The batching occurs if the results' xdr routine is NULL (0) AND
47  * the rpc timeout value is zero (see clnt.h, rpc).
48  *
49  * Clients should NOT casually batch calls that in fact return results; that is,
50  * the server side should be aware that a call is batched and not produce any
51  * return message.  Batched calls that produce many result messages can
52  * deadlock (netlock) the client and the server....
53  *
54  * Now go hang yourself.
55  */
56 
57 #include "namespace.h"
58 #include "reentrant.h"
59 #include <sys/types.h>
60 #include <sys/poll.h>
61 #include <sys/syslog.h>
62 #include <sys/socket.h>
63 #include <sys/tree.h>
64 #include <sys/un.h>
65 #include <sys/uio.h>
66 
67 #include <arpa/inet.h>
68 #include <assert.h>
69 #include <err.h>
70 #include <errno.h>
71 #include <netdb.h>
72 #include <pthread.h>
73 #include <stdio.h>
74 #include <stdbool.h>
75 #include <stdlib.h>
76 #include <string.h>
77 #include <unistd.h>
78 #include <signal.h>
79 
80 #include <rpc/rpc.h>
81 #include <rpc/rpcsec_gss.h>
82 #include "un-namespace.h"
83 #include "rpc_com.h"
84 #include "mt_misc.h"
85 
86 #define MCALL_MSG_SIZE 24
87 
88 struct cmessage {
89         struct cmsghdr cmsg;
90         struct cmsgcred cmcred;
91 };
92 
93 static enum clnt_stat clnt_vc_call(CLIENT *, rpcproc_t, xdrproc_t, void *,
94     xdrproc_t, void *, struct timeval);
95 static void clnt_vc_geterr(CLIENT *, struct rpc_err *);
96 static bool_t clnt_vc_freeres(CLIENT *, xdrproc_t, void *);
97 static void clnt_vc_abort(CLIENT *);
98 static bool_t clnt_vc_control(CLIENT *, u_int, void *);
99 static void clnt_vc_destroy(CLIENT *);
100 static struct clnt_ops *clnt_vc_ops(void);
101 static bool_t time_not_ok(struct timeval *);
102 static int read_vc(void *, void *, int);
103 static int write_vc(void *, void *, int);
104 static int __msgwrite(int, void *, size_t);
105 static int __msgread(int, void *, size_t);
106 
107 struct ct_data {
108 	int		ct_fd;		/* connection's fd */
109 	bool_t		ct_closeit;	/* close it on destroy */
110 	struct timeval	ct_wait;	/* wait interval in milliseconds */
111 	bool_t          ct_waitset;	/* wait set by clnt_control? */
112 	struct netbuf	ct_addr;	/* remote addr */
113 	struct rpc_err	ct_error;
114 	union {
115 		char	ct_mcallc[MCALL_MSG_SIZE];	/* marshalled callmsg */
116 		u_int32_t ct_mcalli;
117 	} ct_u;
118 	u_int		ct_mpos;	/* pos after marshal */
119 	XDR		ct_xdrs;	/* XDR stream */
120 };
121 
122 /*
123  *      This machinery implements per-fd locks for MT-safety.  It is not
124  *      sufficient to do per-CLIENT handle locks for MT-safety because a
125  *      user may create more than one CLIENT handle with the same fd behind
126  *      it.  Therefore, we allocate an associative array of flags and condition
127  *      variables (vc_fd).  The flags and the array are protected by the
128  *      clnt_fd_lock mutex.  vc_fd_lock[fd] == 1 => a call is active on some
129  *      CLIENT handle created for that fd.  The current implementation holds
130  *      locks across the entire RPC and reply.  Yes, this is silly, and as soon
131  *      as this code is proven to work, this should be the first thing fixed.
132  *      One step at a time.
133  */
134 struct vc_fd {
135 	RB_ENTRY(vc_fd) vc_link;
136 	int fd;
137 	mutex_t mtx;
138 };
139 static inline int
140 cmp_vc_fd(struct vc_fd *a, struct vc_fd *b)
141 {
142        if (a->fd > b->fd) {
143                return (1);
144        } else if (a->fd < b->fd) {
145                return (-1);
146        } else {
147                return (0);
148        }
149 }
150 RB_HEAD(vc_fd_list, vc_fd);
151 RB_PROTOTYPE(vc_fd_list, vc_fd, vc_link, cmp_vc_fd);
152 RB_GENERATE(vc_fd_list, vc_fd, vc_link, cmp_vc_fd);
153 struct vc_fd_list vc_fd_head = RB_INITIALIZER(&vc_fd_head);
154 
155 /*
156  * Find the lock structure for the given file descriptor, or initialize it if
157  * it does not already exist.  The clnt_fd_lock mutex must be held.
158  */
159 static struct vc_fd *
160 vc_fd_find(int fd)
161 {
162 	struct vc_fd key, *elem;
163 
164 	key.fd = fd;
165 	elem = RB_FIND(vc_fd_list, &vc_fd_head, &key);
166 	if (elem == NULL) {
167 		elem = calloc(1, sizeof(*elem));
168 		elem->fd = fd;
169 		mutex_init(&elem->mtx, NULL);
170 		RB_INSERT(vc_fd_list, &vc_fd_head, elem);
171 	}
172 	return (elem);
173 }
174 
175 static void
176 release_fd_lock(struct vc_fd *elem, sigset_t mask)
177 {
178 	mutex_unlock(&elem->mtx);
179 	thr_sigsetmask(SIG_SETMASK, &mask, NULL);
180 }
181 
182 static const char clnt_vc_errstr[] = "%s : %s";
183 static const char clnt_vc_str[] = "clnt_vc_create";
184 static const char __no_mem_str[] = "out of memory";
185 
186 /*
187  * Create a client handle for a connection.
188  * Default options are set, which the user can change using clnt_control()'s.
189  * The rpc/vc package does buffering similar to stdio, so the client
190  * must pick send and receive buffer sizes, 0 => use the default.
191  * NB: fd is copied into a private area.
192  * NB: The rpch->cl_auth is set null authentication. Caller may wish to
193  * set this something more useful.
194  *
195  * fd should be an open socket
196  *
197  * fd - open file descriptor
198  * raddr - servers address
199  * prog  - program number
200  * vers  - version number
201  * sendsz - buffer send size
202  * recvsz - buffer recv size
203  */
204 CLIENT *
205 clnt_vc_create(int fd, const struct netbuf *raddr, const rpcprog_t prog,
206     const rpcvers_t vers, u_int sendsz, u_int recvsz)
207 {
208 	CLIENT *cl;			/* client handle */
209 	struct ct_data *ct = NULL;	/* client handle */
210 	struct timeval now;
211 	struct rpc_msg call_msg;
212 	static u_int32_t disrupt;
213 	struct sockaddr_storage ss;
214 	socklen_t slen;
215 	struct __rpc_sockinfo si;
216 
217 	if (disrupt == 0)
218 		disrupt = (u_int32_t)(long)raddr;
219 
220 	cl = (CLIENT *)mem_alloc(sizeof (*cl));
221 	ct = (struct ct_data *)mem_alloc(sizeof (*ct));
222 	if ((cl == (CLIENT *)NULL) || (ct == (struct ct_data *)NULL)) {
223 		(void) syslog(LOG_ERR, clnt_vc_errstr,
224 		    clnt_vc_str, __no_mem_str);
225 		rpc_createerr.cf_stat = RPC_SYSTEMERROR;
226 		rpc_createerr.cf_error.re_errno = errno;
227 		goto err;
228 	}
229 	ct->ct_addr.buf = NULL;
230 
231 	/*
232 	 * XXX - fvdl connecting while holding a mutex?
233 	 */
234 	slen = sizeof ss;
235 	if (_getpeername(fd, (struct sockaddr *)(void *)&ss, &slen) < 0) {
236 		if (errno != ENOTCONN) {
237 			rpc_createerr.cf_stat = RPC_SYSTEMERROR;
238 			rpc_createerr.cf_error.re_errno = errno;
239 			mutex_unlock(&clnt_fd_lock);
240 			goto err;
241 		}
242 		if (_connect(fd, (struct sockaddr *)raddr->buf, raddr->len) < 0){
243 			rpc_createerr.cf_stat = RPC_SYSTEMERROR;
244 			rpc_createerr.cf_error.re_errno = errno;
245 			mutex_unlock(&clnt_fd_lock);
246 			goto err;
247 		}
248 	}
249 	mutex_unlock(&clnt_fd_lock);
250 	if (!__rpc_fd2sockinfo(fd, &si))
251 		goto err;
252 
253 	ct->ct_closeit = FALSE;
254 
255 	/*
256 	 * Set up private data struct
257 	 */
258 	ct->ct_fd = fd;
259 	ct->ct_wait.tv_usec = 0;
260 	ct->ct_waitset = FALSE;
261 	ct->ct_addr.buf = malloc(raddr->maxlen);
262 	if (ct->ct_addr.buf == NULL)
263 		goto err;
264 	memcpy(ct->ct_addr.buf, raddr->buf, raddr->len);
265 	ct->ct_addr.len = raddr->len;
266 	ct->ct_addr.maxlen = raddr->maxlen;
267 
268 	/*
269 	 * Initialize call message
270 	 */
271 	(void)gettimeofday(&now, NULL);
272 	call_msg.rm_xid = ((u_int32_t)++disrupt) ^ __RPC_GETXID(&now);
273 	call_msg.rm_direction = CALL;
274 	call_msg.rm_call.cb_rpcvers = RPC_MSG_VERSION;
275 	call_msg.rm_call.cb_prog = (u_int32_t)prog;
276 	call_msg.rm_call.cb_vers = (u_int32_t)vers;
277 
278 	/*
279 	 * pre-serialize the static part of the call msg and stash it away
280 	 */
281 	xdrmem_create(&(ct->ct_xdrs), ct->ct_u.ct_mcallc, MCALL_MSG_SIZE,
282 	    XDR_ENCODE);
283 	if (! xdr_callhdr(&(ct->ct_xdrs), &call_msg)) {
284 		if (ct->ct_closeit) {
285 			(void)_close(fd);
286 		}
287 		goto err;
288 	}
289 	ct->ct_mpos = XDR_GETPOS(&(ct->ct_xdrs));
290 	XDR_DESTROY(&(ct->ct_xdrs));
291 	assert(ct->ct_mpos + sizeof(uint32_t) <= MCALL_MSG_SIZE);
292 
293 	/*
294 	 * Create a client handle which uses xdrrec for serialization
295 	 * and authnone for authentication.
296 	 */
297 	cl->cl_ops = clnt_vc_ops();
298 	cl->cl_private = ct;
299 	cl->cl_auth = authnone_create();
300 	sendsz = __rpc_get_t_size(si.si_af, si.si_proto, (int)sendsz);
301 	recvsz = __rpc_get_t_size(si.si_af, si.si_proto, (int)recvsz);
302 	xdrrec_create(&(ct->ct_xdrs), sendsz, recvsz,
303 	    cl->cl_private, read_vc, write_vc);
304 	return (cl);
305 
306 err:
307 	if (ct) {
308 		if (ct->ct_addr.len)
309 			mem_free(ct->ct_addr.buf, ct->ct_addr.len);
310 		mem_free(ct, sizeof (struct ct_data));
311 	}
312 	if (cl)
313 		mem_free(cl, sizeof (CLIENT));
314 	return ((CLIENT *)NULL);
315 }
316 
317 static enum clnt_stat
318 clnt_vc_call(CLIENT *cl, rpcproc_t proc, xdrproc_t xdr_args, void *args_ptr,
319     xdrproc_t xdr_results, void *results_ptr, struct timeval timeout)
320 {
321 	struct ct_data *ct = (struct ct_data *) cl->cl_private;
322 	XDR *xdrs = &(ct->ct_xdrs);
323 	struct rpc_msg reply_msg;
324 	struct vc_fd *elem;
325 	u_int32_t x_id;
326 	u_int32_t *msg_x_id = &ct->ct_u.ct_mcalli;    /* yuk */
327 	bool_t shipnow;
328 	int refreshes = 2;
329 	sigset_t mask, newmask;
330 	bool_t reply_stat;
331 
332 	assert(cl != NULL);
333 
334 	sigfillset(&newmask);
335 	thr_sigsetmask(SIG_SETMASK, &newmask, &mask);
336 	mutex_lock(&clnt_fd_lock);
337 	elem = vc_fd_find(ct->ct_fd);
338 	mutex_unlock(&clnt_fd_lock);
339 	mutex_lock(&elem->mtx);
340 	if (!ct->ct_waitset) {
341 		/* If time is not within limits, we ignore it. */
342 		if (time_not_ok(&timeout) == FALSE)
343 			ct->ct_wait = timeout;
344 	}
345 
346 	shipnow =
347 	    (xdr_results == NULL && timeout.tv_sec == 0
348 	    && timeout.tv_usec == 0) ? FALSE : TRUE;
349 
350 call_again:
351 	xdrs->x_op = XDR_ENCODE;
352 	ct->ct_error.re_status = RPC_SUCCESS;
353 	x_id = ntohl(--(*msg_x_id));
354 
355 	if (cl->cl_auth->ah_cred.oa_flavor != RPCSEC_GSS) {
356 		if ((! XDR_PUTBYTES(xdrs, ct->ct_u.ct_mcallc, ct->ct_mpos)) ||
357 		    (! XDR_PUTINT32(xdrs, &proc)) ||
358 		    (! AUTH_MARSHALL(cl->cl_auth, xdrs)) ||
359 		    (! (*xdr_args)(xdrs, args_ptr))) {
360 			if (ct->ct_error.re_status == RPC_SUCCESS)
361 				ct->ct_error.re_status = RPC_CANTENCODEARGS;
362 			(void)xdrrec_endofrecord(xdrs, TRUE);
363 			release_fd_lock(elem, mask);
364 			return (ct->ct_error.re_status);
365 		}
366 	} else {
367 		*(uint32_t *) &ct->ct_u.ct_mcallc[ct->ct_mpos] = htonl(proc);
368 		if (! __rpc_gss_wrap(cl->cl_auth, ct->ct_u.ct_mcallc,
369 			ct->ct_mpos + sizeof(uint32_t),
370 			xdrs, xdr_args, args_ptr)) {
371 			if (ct->ct_error.re_status == RPC_SUCCESS)
372 				ct->ct_error.re_status = RPC_CANTENCODEARGS;
373 			(void)xdrrec_endofrecord(xdrs, TRUE);
374 			release_fd_lock(elem, mask);
375 			return (ct->ct_error.re_status);
376 		}
377 	}
378 	if (! xdrrec_endofrecord(xdrs, shipnow)) {
379 		release_fd_lock(elem, mask);
380 		return (ct->ct_error.re_status = RPC_CANTSEND);
381 	}
382 	if (! shipnow) {
383 		release_fd_lock(elem, mask);
384 		return (RPC_SUCCESS);
385 	}
386 	/*
387 	 * Hack to provide rpc-based message passing
388 	 */
389 	if (timeout.tv_sec == 0 && timeout.tv_usec == 0) {
390 		release_fd_lock(elem, mask);
391 		return(ct->ct_error.re_status = RPC_TIMEDOUT);
392 	}
393 
394 
395 	/*
396 	 * Keep receiving until we get a valid transaction id
397 	 */
398 	xdrs->x_op = XDR_DECODE;
399 	while (TRUE) {
400 		reply_msg.acpted_rply.ar_verf = _null_auth;
401 		reply_msg.acpted_rply.ar_results.where = NULL;
402 		reply_msg.acpted_rply.ar_results.proc = (xdrproc_t)xdr_void;
403 		if (! xdrrec_skiprecord(xdrs)) {
404 			release_fd_lock(elem, mask);
405 			return (ct->ct_error.re_status);
406 		}
407 		/* now decode and validate the response header */
408 		if (! xdr_replymsg(xdrs, &reply_msg)) {
409 			if (ct->ct_error.re_status == RPC_SUCCESS)
410 				continue;
411 			release_fd_lock(elem, mask);
412 			return (ct->ct_error.re_status);
413 		}
414 		if (reply_msg.rm_xid == x_id)
415 			break;
416 	}
417 
418 	/*
419 	 * process header
420 	 */
421 	_seterr_reply(&reply_msg, &(ct->ct_error));
422 	if (ct->ct_error.re_status == RPC_SUCCESS) {
423 		if (! AUTH_VALIDATE(cl->cl_auth,
424 		    &reply_msg.acpted_rply.ar_verf)) {
425 			ct->ct_error.re_status = RPC_AUTHERROR;
426 			ct->ct_error.re_why = AUTH_INVALIDRESP;
427 		} else {
428 			if (cl->cl_auth->ah_cred.oa_flavor != RPCSEC_GSS) {
429 				reply_stat = (*xdr_results)(xdrs, results_ptr);
430 			} else {
431 				reply_stat = __rpc_gss_unwrap(cl->cl_auth,
432 				    xdrs, xdr_results, results_ptr);
433 			}
434 			if (! reply_stat) {
435 				if (ct->ct_error.re_status == RPC_SUCCESS)
436 					ct->ct_error.re_status =
437 						RPC_CANTDECODERES;
438 			}
439 		}
440 		/* free verifier ... */
441 		if (reply_msg.acpted_rply.ar_verf.oa_base != NULL) {
442 			xdrs->x_op = XDR_FREE;
443 			(void)xdr_opaque_auth(xdrs,
444 			    &(reply_msg.acpted_rply.ar_verf));
445 		}
446 	}  /* end successful completion */
447 	else {
448 		/* maybe our credentials need to be refreshed ... */
449 		if (refreshes-- && AUTH_REFRESH(cl->cl_auth, &reply_msg))
450 			goto call_again;
451 	}  /* end of unsuccessful completion */
452 	release_fd_lock(elem, mask);
453 	return (ct->ct_error.re_status);
454 }
455 
456 static void
457 clnt_vc_geterr(CLIENT *cl, struct rpc_err *errp)
458 {
459 	struct ct_data *ct;
460 
461 	assert(cl != NULL);
462 	assert(errp != NULL);
463 
464 	ct = (struct ct_data *) cl->cl_private;
465 	*errp = ct->ct_error;
466 }
467 
468 static bool_t
469 clnt_vc_freeres(CLIENT *cl, xdrproc_t xdr_res, void *res_ptr)
470 {
471 	struct ct_data *ct;
472 	struct vc_fd *elem;
473 	XDR *xdrs;
474 	bool_t dummy;
475 	sigset_t mask;
476 	sigset_t newmask;
477 
478 	assert(cl != NULL);
479 
480 	ct = (struct ct_data *)cl->cl_private;
481 	xdrs = &(ct->ct_xdrs);
482 
483 	sigfillset(&newmask);
484 	thr_sigsetmask(SIG_SETMASK, &newmask, &mask);
485 	mutex_lock(&clnt_fd_lock);
486 	elem = vc_fd_find(ct->ct_fd);
487 	mutex_lock(&elem->mtx);
488 	xdrs->x_op = XDR_FREE;
489 	dummy = (*xdr_res)(xdrs, res_ptr);
490 
491 	mutex_unlock(&clnt_fd_lock);
492 	release_fd_lock(elem, mask);
493 	return dummy;
494 }
495 
496 /*ARGSUSED*/
497 static void
498 clnt_vc_abort(CLIENT *cl)
499 {
500 }
501 
502 static __inline void
503 htonlp(void *dst, const void *src, uint32_t incr)
504 {
505 	/* We are aligned, so we think */
506 	*(uint32_t *)dst = htonl(*(const uint32_t *)src + incr);
507 }
508 
509 static __inline void
510 ntohlp(void *dst, const void *src)
511 {
512 	/* We are aligned, so we think */
513 	*(uint32_t *)dst = htonl(*(const uint32_t *)src);
514 }
515 
516 static bool_t
517 clnt_vc_control(CLIENT *cl, u_int request, void *info)
518 {
519 	struct ct_data *ct;
520 	struct vc_fd *elem;
521 	void *infop = info;
522 	sigset_t mask;
523 	sigset_t newmask;
524 
525 	assert(cl != NULL);
526 
527 	ct = (struct ct_data *)cl->cl_private;
528 
529 	sigfillset(&newmask);
530 	thr_sigsetmask(SIG_SETMASK, &newmask, &mask);
531 	mutex_lock(&clnt_fd_lock);
532 	elem = vc_fd_find(ct->ct_fd);
533 	mutex_unlock(&clnt_fd_lock);
534 	mutex_lock(&elem->mtx);
535 
536 	switch (request) {
537 	case CLSET_FD_CLOSE:
538 		ct->ct_closeit = TRUE;
539 		release_fd_lock(elem, mask);
540 		return (TRUE);
541 	case CLSET_FD_NCLOSE:
542 		ct->ct_closeit = FALSE;
543 		release_fd_lock(elem, mask);
544 		return (TRUE);
545 	default:
546 		break;
547 	}
548 
549 	/* for other requests which use info */
550 	if (info == NULL) {
551 		release_fd_lock(elem, mask);
552 		return (FALSE);
553 	}
554 	switch (request) {
555 	case CLSET_TIMEOUT:
556 		if (time_not_ok((struct timeval *)info)) {
557 			release_fd_lock(elem, mask);
558 			return (FALSE);
559 		}
560 		ct->ct_wait = *(struct timeval *)infop;
561 		ct->ct_waitset = TRUE;
562 		break;
563 	case CLGET_TIMEOUT:
564 		*(struct timeval *)infop = ct->ct_wait;
565 		break;
566 	case CLGET_SERVER_ADDR:
567 		(void) memcpy(info, ct->ct_addr.buf, (size_t)ct->ct_addr.len);
568 		break;
569 	case CLGET_FD:
570 		*(int *)info = ct->ct_fd;
571 		break;
572 	case CLGET_SVC_ADDR:
573 		/* The caller should not free this memory area */
574 		*(struct netbuf *)info = ct->ct_addr;
575 		break;
576 	case CLSET_SVC_ADDR:		/* set to new address */
577 		release_fd_lock(elem, mask);
578 		return (FALSE);
579 	case CLGET_XID:
580 		/*
581 		 * use the knowledge that xid is the
582 		 * first element in the call structure
583 		 * This will get the xid of the PREVIOUS call
584 		 */
585 		ntohlp(info, &ct->ct_u.ct_mcalli);
586 		break;
587 	case CLSET_XID:
588 		/* This will set the xid of the NEXT call */
589 		/* increment by 1 as clnt_vc_call() decrements once */
590 		htonlp(&ct->ct_u.ct_mcalli, info, 1);
591 		break;
592 	case CLGET_VERS:
593 		/*
594 		 * This RELIES on the information that, in the call body,
595 		 * the version number field is the fifth field from the
596 		 * beginning of the RPC header. MUST be changed if the
597 		 * call_struct is changed
598 		 */
599 		ntohlp(info, ct->ct_u.ct_mcallc + 4 * BYTES_PER_XDR_UNIT);
600 		break;
601 
602 	case CLSET_VERS:
603 		htonlp(ct->ct_u.ct_mcallc + 4 * BYTES_PER_XDR_UNIT, info, 0);
604 		break;
605 
606 	case CLGET_PROG:
607 		/*
608 		 * This RELIES on the information that, in the call body,
609 		 * the program number field is the fourth field from the
610 		 * beginning of the RPC header. MUST be changed if the
611 		 * call_struct is changed
612 		 */
613 		ntohlp(info, ct->ct_u.ct_mcallc + 3 * BYTES_PER_XDR_UNIT);
614 		break;
615 
616 	case CLSET_PROG:
617 		htonlp(ct->ct_u.ct_mcallc + 3 * BYTES_PER_XDR_UNIT, info, 0);
618 		break;
619 
620 	default:
621 		release_fd_lock(elem, mask);
622 		return (FALSE);
623 	}
624 	release_fd_lock(elem, mask);
625 	return (TRUE);
626 }
627 
628 
629 static void
630 clnt_vc_destroy(CLIENT *cl)
631 {
632 	struct ct_data *ct = (struct ct_data *) cl->cl_private;
633 	struct vc_fd *elem;
634 	int ct_fd = ct->ct_fd;
635 	sigset_t mask;
636 	sigset_t newmask;
637 
638 	assert(cl != NULL);
639 
640 	ct = (struct ct_data *) cl->cl_private;
641 
642 	sigfillset(&newmask);
643 	thr_sigsetmask(SIG_SETMASK, &newmask, &mask);
644 	mutex_lock(&clnt_fd_lock);
645 	elem = vc_fd_find(ct_fd);
646 	mutex_lock(&elem->mtx);
647 	if (ct->ct_closeit && ct->ct_fd != -1) {
648 		(void)_close(ct->ct_fd);
649 	}
650 	XDR_DESTROY(&(ct->ct_xdrs));
651 	free(ct->ct_addr.buf);
652 	mem_free(ct, sizeof(struct ct_data));
653 	if (cl->cl_netid && cl->cl_netid[0])
654 		mem_free(cl->cl_netid, strlen(cl->cl_netid) +1);
655 	if (cl->cl_tp && cl->cl_tp[0])
656 		mem_free(cl->cl_tp, strlen(cl->cl_tp) +1);
657 	mem_free(cl, sizeof(CLIENT));
658 	mutex_unlock(&clnt_fd_lock);
659 	release_fd_lock(elem, mask);
660 }
661 
662 /*
663  * Interface between xdr serializer and tcp connection.
664  * Behaves like the system calls, read & write, but keeps some error state
665  * around for the rpc level.
666  */
667 static int
668 read_vc(void *ctp, void *buf, int len)
669 {
670 	struct sockaddr sa;
671 	socklen_t sal;
672 	struct ct_data *ct = (struct ct_data *)ctp;
673 	struct pollfd fd;
674 	int milliseconds = (int)((ct->ct_wait.tv_sec * 1000) +
675 	    (ct->ct_wait.tv_usec / 1000));
676 
677 	if (len == 0)
678 		return (0);
679 	fd.fd = ct->ct_fd;
680 	fd.events = POLLIN;
681 	for (;;) {
682 		switch (_poll(&fd, 1, milliseconds)) {
683 		case 0:
684 			ct->ct_error.re_status = RPC_TIMEDOUT;
685 			return (-1);
686 
687 		case -1:
688 			if (errno == EINTR)
689 				continue;
690 			ct->ct_error.re_status = RPC_CANTRECV;
691 			ct->ct_error.re_errno = errno;
692 			return (-1);
693 		}
694 		break;
695 	}
696 
697 	sal = sizeof(sa);
698 	if ((_getpeername(ct->ct_fd, &sa, &sal) == 0) &&
699 	    (sa.sa_family == AF_LOCAL)) {
700 		len = __msgread(ct->ct_fd, buf, (size_t)len);
701 	} else {
702 		len = _read(ct->ct_fd, buf, (size_t)len);
703 	}
704 
705 	switch (len) {
706 	case 0:
707 		/* premature eof */
708 		ct->ct_error.re_errno = ECONNRESET;
709 		ct->ct_error.re_status = RPC_CANTRECV;
710 		len = -1;  /* it's really an error */
711 		break;
712 
713 	case -1:
714 		ct->ct_error.re_errno = errno;
715 		ct->ct_error.re_status = RPC_CANTRECV;
716 		break;
717 	}
718 	return (len);
719 }
720 
721 static int
722 write_vc(void *ctp, void *buf, int len)
723 {
724 	struct sockaddr sa;
725 	socklen_t sal;
726 	struct ct_data *ct = (struct ct_data *)ctp;
727 	int i, cnt;
728 
729 	sal = sizeof(sa);
730 	if ((_getpeername(ct->ct_fd, &sa, &sal) == 0) &&
731 	    (sa.sa_family == AF_LOCAL)) {
732 		for (cnt = len; cnt > 0; cnt -= i, buf = (char *)buf + i) {
733 			if ((i = __msgwrite(ct->ct_fd, buf,
734 			     (size_t)cnt)) == -1) {
735 				ct->ct_error.re_errno = errno;
736 				ct->ct_error.re_status = RPC_CANTSEND;
737 				return (-1);
738 			}
739 		}
740 	} else {
741 		for (cnt = len; cnt > 0; cnt -= i, buf = (char *)buf + i) {
742 			if ((i = _write(ct->ct_fd, buf, (size_t)cnt)) == -1) {
743 				ct->ct_error.re_errno = errno;
744 				ct->ct_error.re_status = RPC_CANTSEND;
745 				return (-1);
746 			}
747 		}
748 	}
749 	return (len);
750 }
751 
752 static struct clnt_ops *
753 clnt_vc_ops(void)
754 {
755 	static struct clnt_ops ops;
756 	sigset_t mask, newmask;
757 
758 	/* VARIABLES PROTECTED BY ops_lock: ops */
759 
760 	sigfillset(&newmask);
761 	thr_sigsetmask(SIG_SETMASK, &newmask, &mask);
762 	mutex_lock(&ops_lock);
763 	if (ops.cl_call == NULL) {
764 		ops.cl_call = clnt_vc_call;
765 		ops.cl_abort = clnt_vc_abort;
766 		ops.cl_geterr = clnt_vc_geterr;
767 		ops.cl_freeres = clnt_vc_freeres;
768 		ops.cl_destroy = clnt_vc_destroy;
769 		ops.cl_control = clnt_vc_control;
770 	}
771 	mutex_unlock(&ops_lock);
772 	thr_sigsetmask(SIG_SETMASK, &(mask), NULL);
773 	return (&ops);
774 }
775 
776 /*
777  * Make sure that the time is not garbage.   -1 value is disallowed.
778  * Note this is different from time_not_ok in clnt_dg.c
779  */
780 static bool_t
781 time_not_ok(struct timeval *t)
782 {
783 	return (t->tv_sec <= -1 || t->tv_sec > 100000000 ||
784 		t->tv_usec <= -1 || t->tv_usec > 1000000);
785 }
786 
787 static int
788 __msgread(int sock, void *buf, size_t cnt)
789 {
790 	struct iovec iov[1];
791 	struct msghdr msg;
792 	union {
793 		struct cmsghdr cmsg;
794 		char control[CMSG_SPACE(sizeof(struct cmsgcred))];
795 	} cm;
796 
797 	bzero((char *)&cm, sizeof(cm));
798 	iov[0].iov_base = buf;
799 	iov[0].iov_len = cnt;
800 
801 	msg.msg_iov = iov;
802 	msg.msg_iovlen = 1;
803 	msg.msg_name = NULL;
804 	msg.msg_namelen = 0;
805 	msg.msg_control = (caddr_t)&cm;
806 	msg.msg_controllen = CMSG_SPACE(sizeof(struct cmsgcred));
807 	msg.msg_flags = 0;
808 
809 	return(_recvmsg(sock, &msg, 0));
810 }
811 
812 static int
813 __msgwrite(int sock, void *buf, size_t cnt)
814 {
815 	struct iovec iov[1];
816 	struct msghdr msg;
817 	union {
818 		struct cmsghdr cmsg;
819 		char control[CMSG_SPACE(sizeof(struct cmsgcred))];
820 	} cm;
821 
822 	bzero((char *)&cm, sizeof(cm));
823 	iov[0].iov_base = buf;
824 	iov[0].iov_len = cnt;
825 
826 	cm.cmsg.cmsg_type = SCM_CREDS;
827 	cm.cmsg.cmsg_level = SOL_SOCKET;
828 	cm.cmsg.cmsg_len = CMSG_LEN(sizeof(struct cmsgcred));
829 
830 	msg.msg_iov = iov;
831 	msg.msg_iovlen = 1;
832 	msg.msg_name = NULL;
833 	msg.msg_namelen = 0;
834 	msg.msg_control = (caddr_t)&cm;
835 	msg.msg_controllen = CMSG_SPACE(sizeof(struct cmsgcred));
836 	msg.msg_flags = 0;
837 
838 	return(_sendmsg(sock, &msg, 0));
839 }
840