1 /*	$OpenBSD: clnt_tcp.c,v 1.22 2005/08/08 08:05:35 espie Exp $ */
2 /*
3  * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
4  * unrestricted use provided that this legend is included on all tape
5  * media and as a part of the software program in whole or part.  Users
6  * may copy or modify Sun RPC without charge, but are not authorized
7  * to license or distribute it to anyone else except as part of a product or
8  * program developed by the user.
9  *
10  * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
11  * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
12  * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
13  *
14  * Sun RPC is provided with no support and without any obligation on the
15  * part of Sun Microsystems, Inc. to assist in its use, correction,
16  * modification or enhancement.
17  *
18  * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
19  * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
20  * OR ANY PART THEREOF.
21  *
22  * In no event will Sun Microsystems, Inc. be liable for any lost revenue
23  * or profits or other special, indirect and consequential damages, even if
24  * Sun has been advised of the possibility of such damages.
25  *
26  * Sun Microsystems, Inc.
27  * 2550 Garcia Avenue
28  * Mountain View, California  94043
29  */
30 
31 /*
32  * clnt_tcp.c, Implements a TCP/IP based, client side RPC.
33  *
34  * Copyright (C) 1984, Sun Microsystems, Inc.
35  *
36  * TCP based RPC supports 'batched calls'.
37  * A sequence of calls may be batched-up in a send buffer.  The rpc call
38  * return immediately to the client even though the call was not necessarily
39  * sent.  The batching occurs if the results' xdr routine is NULL (0) AND
40  * the rpc timeout value is zero (see clnt.h, rpc).
41  *
42  * Clients should NOT casually batch calls that in fact return results; that is,
43  * the server side should be aware that a call is batched and not produce any
44  * return message.  Batched calls that produce many result messages can
45  * deadlock (netlock) the client and the server....
46  *
47  * Now go hang yourself.
48  */
49 
50 #include <stdio.h>
51 #include <stdlib.h>
52 #include <string.h>
53 #include <unistd.h>
54 #include <rpc/rpc.h>
55 #include <sys/socket.h>
56 #include <netdb.h>
57 #include <errno.h>
58 #include <rpc/pmap_clnt.h>
59 
60 __RCSID("$MirOS: src/lib/libc/rpc/clnt_tcp.c,v 1.2 2009/11/09 21:30:53 tg Exp $");
61 
62 #define MCALL_MSG_SIZE 24
63 
64 static enum clnt_stat	clnttcp_call(CLIENT *, u_long, xdrproc_t, caddr_t,
65 			    xdrproc_t, caddr_t, struct timeval);
66 static void		clnttcp_abort(CLIENT *);
67 static void		clnttcp_geterr(CLIENT *, struct rpc_err *);
68 static bool_t		clnttcp_freeres(CLIENT *, xdrproc_t, caddr_t);
69 static bool_t           clnttcp_control(CLIENT *, u_int, void *);
70 static void		clnttcp_destroy(CLIENT *);
71 
72 static struct clnt_ops tcp_ops = {
73 	clnttcp_call,
74 	clnttcp_abort,
75 	clnttcp_geterr,
76 	clnttcp_freeres,
77 	clnttcp_destroy,
78 	clnttcp_control
79 };
80 
81 struct ct_data {
82 	int		ct_sock;
83 	bool_t		ct_closeit;
84 	struct timeval	ct_wait;
85 	bool_t          ct_waitset;       /* wait set by clnt_control? */
86 	struct sockaddr_in ct_addr;
87 	struct rpc_err	ct_error;
88 	char		ct_mcall[MCALL_MSG_SIZE];	/* marshalled callmsg */
89 	u_int		ct_mpos;			/* pos after marshal */
90 	XDR		ct_xdrs;
91 };
92 
93 static int	readtcp(struct ct_data *, caddr_t, int);
94 static int	writetcp(struct ct_data *, caddr_t, int);
95 
96 /*
97  * Create a client handle for a tcp/ip connection.
98  * If *sockp<0, *sockp is set to a newly created TCP socket and it is
99  * connected to raddr.  If *sockp non-negative then
100  * raddr is ignored.  The rpc/tcp package does buffering
101  * similar to stdio, so the client must pick send and receive buffer sizes,];
102  * 0 => use the default.
103  * If raddr->sin_port is 0, then a binder on the remote machine is
104  * consulted for the right port number.
105  * NB: *sockp is copied into a private area.
106  * NB: It is the clients responsibility to close *sockp.
107  * NB: The rpch->cl_auth is set null authentication.  Caller may wish to set this
108  * something more useful.
109  */
110 CLIENT *
clnttcp_create(struct sockaddr_in * raddr,u_long prog,u_long vers,int * sockp,u_int sendsz,u_int recvsz)111 clnttcp_create(struct sockaddr_in *raddr, u_long prog, u_long vers, int *sockp,
112     u_int sendsz, u_int recvsz)
113 {
114 	CLIENT *h;
115 	struct ct_data *ct = NULL;
116 	struct timeval now;
117 	struct rpc_msg call_msg;
118 
119 	h  = (CLIENT *)mem_alloc(sizeof(*h));
120 	if (h == NULL) {
121 		(void)fprintf(stderr, "clnttcp_create: out of memory\n");
122 		rpc_createerr.cf_stat = RPC_SYSTEMERROR;
123 		rpc_createerr.cf_error.re_errno = errno;
124 		goto fooy;
125 	}
126 	ct = (struct ct_data *)mem_alloc(sizeof(*ct));
127 	if (ct == NULL) {
128 		(void)fprintf(stderr, "clnttcp_create: out of memory\n");
129 		rpc_createerr.cf_stat = RPC_SYSTEMERROR;
130 		rpc_createerr.cf_error.re_errno = errno;
131 		goto fooy;
132 	}
133 
134 	/*
135 	 * If no port number given ask the pmap for one
136 	 */
137 	if (raddr->sin_port == 0) {
138 		u_short port;
139 		if ((port = pmap_getport(raddr, prog, vers, IPPROTO_TCP)) == 0) {
140 			mem_free((caddr_t)ct, sizeof(struct ct_data));
141 			mem_free((caddr_t)h, sizeof(CLIENT));
142 			return (NULL);
143 		}
144 		raddr->sin_port = htons(port);
145 	}
146 
147 	/*
148 	 * If no socket given, open one
149 	 */
150 	if (*sockp < 0) {
151 		*sockp = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
152 		(void)bindresvport(*sockp, NULL);
153 		if ((*sockp < 0)
154 		    || (connect(*sockp, (struct sockaddr *)raddr,
155 		    sizeof(*raddr)) < 0)) {
156 			rpc_createerr.cf_stat = RPC_SYSTEMERROR;
157 			rpc_createerr.cf_error.re_errno = errno;
158 			if (*sockp != -1)
159 				(void)close(*sockp);
160 			goto fooy;
161 		}
162 		ct->ct_closeit = TRUE;
163 	} else {
164 		ct->ct_closeit = FALSE;
165 	}
166 
167 	/*
168 	 * Set up private data struct
169 	 */
170 	ct->ct_sock = *sockp;
171 	ct->ct_wait.tv_usec = 0;
172 	ct->ct_waitset = FALSE;
173 	ct->ct_addr = *raddr;
174 
175 	/*
176 	 * Initialize call message
177 	 */
178 	(void)gettimeofday(&now, NULL);
179 	call_msg.rm_xid = arc4random();
180 	call_msg.rm_direction = CALL;
181 	call_msg.rm_call.cb_rpcvers = RPC_MSG_VERSION;
182 	call_msg.rm_call.cb_prog = prog;
183 	call_msg.rm_call.cb_vers = vers;
184 
185 	/*
186 	 * pre-serialize the staic part of the call msg and stash it away
187 	 */
188 	xdrmem_create(&(ct->ct_xdrs), ct->ct_mcall, MCALL_MSG_SIZE,
189 	    XDR_ENCODE);
190 	if (! xdr_callhdr(&(ct->ct_xdrs), &call_msg)) {
191 		if (ct->ct_closeit) {
192 			(void)close(*sockp);
193 		}
194 		goto fooy;
195 	}
196 	ct->ct_mpos = XDR_GETPOS(&(ct->ct_xdrs));
197 	XDR_DESTROY(&(ct->ct_xdrs));
198 
199 	/*
200 	 * Create a client handle which uses xdrrec for serialization
201 	 * and authnone for authentication.
202 	 */
203 	xdrrec_create(&(ct->ct_xdrs), sendsz, recvsz,
204 	    (caddr_t)ct, (int(*)(caddr_t, caddr_t, int))readtcp,
205 	    (int(*)(caddr_t, caddr_t, int))writetcp);
206 	h->cl_ops = &tcp_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 (NULL);
220 }
221 
222 static enum clnt_stat
clnttcp_call(CLIENT * h,u_long proc,xdrproc_t xdr_args,caddr_t args_ptr,xdrproc_t xdr_results,caddr_t results_ptr,struct timeval timeout)223 clnttcp_call(CLIENT *h, u_long proc, xdrproc_t xdr_args, caddr_t args_ptr,
224     xdrproc_t xdr_results, caddr_t results_ptr, struct timeval timeout)
225 {
226 	struct ct_data *ct = (struct ct_data *) h->cl_private;
227 	XDR *xdrs = &(ct->ct_xdrs);
228 	struct rpc_msg reply_msg;
229 	u_long x_id;
230 	u_int32_t *msg_x_id = (u_int32_t *)(ct->ct_mcall);	/* yuk */
231 	bool_t shipnow;
232 	int refreshes = 2;
233 
234 	if (!ct->ct_waitset) {
235 		ct->ct_wait = timeout;
236 	}
237 
238 	shipnow =
239 	    (xdr_results == NULL && timeout.tv_sec == 0
240 	    && timeout.tv_usec == 0) ? FALSE : TRUE;
241 
242 call_again:
243 	xdrs->x_op = XDR_ENCODE;
244 	ct->ct_error.re_status = RPC_SUCCESS;
245 	x_id = ntohl(--(*msg_x_id));
246 	if ((! XDR_PUTBYTES(xdrs, ct->ct_mcall, ct->ct_mpos)) ||
247 	    (! XDR_PUTLONG(xdrs, (long *)&proc)) ||
248 	    (! AUTH_MARSHALL(h->cl_auth, xdrs)) ||
249 	    (! (*xdr_args)(xdrs, args_ptr))) {
250 		if (ct->ct_error.re_status == RPC_SUCCESS)
251 			ct->ct_error.re_status = RPC_CANTENCODEARGS;
252 		(void)xdrrec_endofrecord(xdrs, TRUE);
253 		return (ct->ct_error.re_status);
254 	}
255 	if (! xdrrec_endofrecord(xdrs, shipnow))
256 		return (ct->ct_error.re_status = RPC_CANTSEND);
257 	if (! shipnow)
258 		return (RPC_SUCCESS);
259 	/*
260 	 * Hack to provide rpc-based message passing
261 	 */
262 	if (timeout.tv_sec == 0 && timeout.tv_usec == 0) {
263 		return(ct->ct_error.re_status = RPC_TIMEDOUT);
264 	}
265 
266 
267 	/*
268 	 * Keep receiving until we get a valid transaction id
269 	 */
270 	xdrs->x_op = XDR_DECODE;
271 	while (TRUE) {
272 		reply_msg.acpted_rply.ar_verf = _null_auth;
273 		reply_msg.acpted_rply.ar_results.where = NULL;
274 		reply_msg.acpted_rply.ar_results.proc = xdr_void;
275 		if (! xdrrec_skiprecord(xdrs))
276 			return (ct->ct_error.re_status);
277 		/* now decode and validate the response header */
278 		if (! xdr_replymsg(xdrs, &reply_msg)) {
279 			if (ct->ct_error.re_status == RPC_SUCCESS)
280 				continue;
281 			return (ct->ct_error.re_status);
282 		}
283 		if (reply_msg.rm_xid == x_id)
284 			break;
285 	}
286 
287 	/*
288 	 * process header
289 	 */
290 	_seterr_reply(&reply_msg, &(ct->ct_error));
291 	if (ct->ct_error.re_status == RPC_SUCCESS) {
292 		if (! AUTH_VALIDATE(h->cl_auth, &reply_msg.acpted_rply.ar_verf)) {
293 			ct->ct_error.re_status = RPC_AUTHERROR;
294 			ct->ct_error.re_why = AUTH_INVALIDRESP;
295 		} else if (! (*xdr_results)(xdrs, results_ptr)) {
296 			if (ct->ct_error.re_status == RPC_SUCCESS)
297 				ct->ct_error.re_status = RPC_CANTDECODERES;
298 		}
299 		/* free verifier ... */
300 		if (reply_msg.acpted_rply.ar_verf.oa_base != NULL) {
301 			xdrs->x_op = XDR_FREE;
302 			(void)xdr_opaque_auth(xdrs, &(reply_msg.acpted_rply.ar_verf));
303 		}
304 	}  /* end successful completion */
305 	else {
306 		/* maybe our credentials need to be refreshed ... */
307 		if (refreshes-- && AUTH_REFRESH(h->cl_auth))
308 			goto call_again;
309 	}  /* end of unsuccessful completion */
310 	return (ct->ct_error.re_status);
311 }
312 
313 static void
clnttcp_geterr(CLIENT * h,struct rpc_err * errp)314 clnttcp_geterr(CLIENT *h, struct rpc_err *errp)
315 {
316 	struct ct_data *ct =
317 	    (struct ct_data *) h->cl_private;
318 
319 	*errp = ct->ct_error;
320 }
321 
322 static bool_t
clnttcp_freeres(CLIENT * cl,xdrproc_t xdr_res,caddr_t res_ptr)323 clnttcp_freeres(CLIENT *cl, xdrproc_t xdr_res, caddr_t res_ptr)
324 {
325 	struct ct_data *ct = (struct ct_data *)cl->cl_private;
326 	XDR *xdrs = &(ct->ct_xdrs);
327 
328 	xdrs->x_op = XDR_FREE;
329 	return ((*xdr_res)(xdrs, res_ptr));
330 }
331 
332 static void
clnttcp_abort(CLIENT * clnt __unused)333 clnttcp_abort(CLIENT *clnt __unused)
334 {
335 }
336 
337 static bool_t
clnttcp_control(CLIENT * cl,u_int request,void * info)338 clnttcp_control(CLIENT *cl, u_int request, void *info)
339 {
340 	struct ct_data *ct = (struct ct_data *)cl->cl_private;
341 
342 	switch (request) {
343 	case CLSET_TIMEOUT:
344 		ct->ct_wait = *(struct timeval *)info;
345 		ct->ct_waitset = TRUE;
346 		break;
347 	case CLGET_TIMEOUT:
348 		*(struct timeval *)info = ct->ct_wait;
349 		break;
350 	case CLGET_SERVER_ADDR:
351 		*(struct sockaddr_in *)info = ct->ct_addr;
352 		break;
353 	default:
354 		return (FALSE);
355 	}
356 	return (TRUE);
357 }
358 
359 
360 static void
clnttcp_destroy(CLIENT * h)361 clnttcp_destroy(CLIENT *h)
362 {
363 	struct ct_data *ct =
364 	    (struct ct_data *) h->cl_private;
365 
366 	if (ct->ct_closeit) {
367 		(void)close(ct->ct_sock);
368 	}
369 	XDR_DESTROY(&(ct->ct_xdrs));
370 	mem_free((caddr_t)ct, sizeof(struct ct_data));
371 	mem_free((caddr_t)h, sizeof(CLIENT));
372 }
373 
374 /*
375  * Interface between xdr serializer and tcp connection.
376  * Behaves like the system calls, read & write, but keeps some error state
377  * around for the rpc level.
378  */
379 static int
readtcp(struct ct_data * ct,caddr_t buf,int len)380 readtcp(struct ct_data *ct, caddr_t buf, int len)
381 {
382 	struct pollfd pfd[1];
383 	struct timeval start, after, duration, tmp;
384 	int delta, r, save_errno;
385 
386 	if (len == 0)
387 		return (0);
388 
389 	pfd[0].fd = ct->ct_sock;
390 	pfd[0].events = POLLIN;
391 	delta = ct->ct_wait.tv_sec * 1000 + ct->ct_wait.tv_usec / 1000;
392 	gettimeofday(&start, NULL);
393 	for (;;) {
394 		r = poll(pfd, 1, delta);
395 		save_errno = errno;
396 
397 		gettimeofday(&after, NULL);
398 		timersub(&start, &after, &duration);
399 		timersub(&ct->ct_wait, &duration, &tmp);
400 		delta = tmp.tv_sec * 1000 + tmp.tv_usec / 1000;
401 		if (delta <= 0)
402 			r = 0;
403 
404 		switch (r) {
405 		case 0:
406 			ct->ct_error.re_status = RPC_TIMEDOUT;
407 			return (-1);
408 		case 1:
409 			if (pfd[0].revents & POLLNVAL)
410 				errno = EBADF;
411 			else if (pfd[0].revents & POLLERR)
412 				errno = EIO;
413 			else
414 				break;
415 			/* FALLTHROUGH */
416 		case -1:
417 			if (errno == EINTR)
418 				continue;
419 			ct->ct_error.re_status = RPC_CANTRECV;
420 			ct->ct_error.re_errno = save_errno;
421 			return (-1);
422 		}
423 		break;
424 	}
425 
426 	switch (len = read(ct->ct_sock, buf, len)) {
427 	case 0:
428 		/* premature eof */
429 		ct->ct_error.re_errno = ECONNRESET;
430 		ct->ct_error.re_status = RPC_CANTRECV;
431 		len = -1;  /* it's really an error */
432 		break;
433 	case -1:
434 		ct->ct_error.re_errno = errno;
435 		ct->ct_error.re_status = RPC_CANTRECV;
436 		break;
437 	}
438 	return (len);
439 }
440 
441 static int
writetcp(struct ct_data * ct,caddr_t buf,int len)442 writetcp(struct ct_data *ct, caddr_t buf, int len)
443 {
444 	int i, cnt;
445 
446 	for (cnt = len; cnt > 0; cnt -= i, buf += i) {
447 		if ((i = write(ct->ct_sock, buf, cnt)) == -1) {
448 			ct->ct_error.re_errno = errno;
449 			ct->ct_error.re_status = RPC_CANTSEND;
450 			return (-1);
451 		}
452 	}
453 	return (len);
454 }
455