xref: /openbsd-src/lib/libc/rpc/clnt_udp.c (revision 43003dfe3ad45d1698bed8a37f2b0f5b14f20d4f)
1 /*	$OpenBSD: clnt_udp.c,v 1.25 2009/06/02 14:18:19 schwarze 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_udp.c, Implements a UDP/IP based, client side RPC.
33  *
34  * Copyright (C) 1984, Sun Microsystems, Inc.
35  */
36 
37 #include <stdio.h>
38 #include <stdlib.h>
39 #include <string.h>
40 #include <unistd.h>
41 #include <rpc/rpc.h>
42 #include <sys/socket.h>
43 #include <sys/ioctl.h>
44 #include <netdb.h>
45 #include <errno.h>
46 #include <rpc/pmap_clnt.h>
47 
48 /*
49  * UDP bases client side rpc operations
50  */
51 static enum clnt_stat	clntudp_call(CLIENT *, u_long, xdrproc_t, caddr_t,
52 			    xdrproc_t, caddr_t, struct timeval);
53 static void		clntudp_abort(CLIENT *);
54 static void		clntudp_geterr(CLIENT *, struct rpc_err *);
55 static bool_t		clntudp_freeres(CLIENT *, xdrproc_t, caddr_t);
56 static bool_t           clntudp_control(CLIENT *, u_int, void *);
57 static void		clntudp_destroy(CLIENT *);
58 
59 static struct clnt_ops udp_ops = {
60 	clntudp_call,
61 	clntudp_abort,
62 	clntudp_geterr,
63 	clntudp_freeres,
64 	clntudp_destroy,
65 	clntudp_control
66 };
67 
68 /*
69  * Private data kept per client handle
70  */
71 struct cu_data {
72 	int		   cu_sock;
73 	bool_t		   cu_closeit;
74 	struct sockaddr_in cu_raddr;
75 	int		   cu_rlen;
76 	struct timeval	   cu_wait;
77 	struct timeval     cu_total;
78 	struct rpc_err	   cu_error;
79 	XDR		   cu_outxdrs;
80 	u_int		   cu_xdrpos;
81 	u_int		   cu_sendsz;
82 	char		   *cu_outbuf;
83 	u_int		   cu_recvsz;
84 	char		   cu_inbuf[1];
85 };
86 
87 /*
88  * Create a UDP based client handle.
89  * If *sockp<0, *sockp is set to a newly created UPD socket.
90  * If raddr->sin_port is 0 a binder on the remote machine
91  * is consulted for the correct port number.
92  * NB: It is the clients responsibility to close *sockp.
93  * NB: The rpch->cl_auth is initialized to null authentication.
94  *     Caller may wish to set this something more useful.
95  *
96  * wait is the amount of time used between retransmitting a call if
97  * no response has been heard;  retransmission occurs until the actual
98  * rpc call times out.
99  *
100  * sendsz and recvsz are the maximum allowable packet sizes that can be
101  * sent and received.
102  */
103 CLIENT *
104 clntudp_bufcreate(struct sockaddr_in *raddr, u_long program, u_long version,
105     struct timeval wait, int *sockp, u_int sendsz, u_int recvsz)
106 {
107 	CLIENT *cl;
108 	struct cu_data *cu = NULL;
109 	struct timeval now;
110 	struct rpc_msg call_msg;
111 
112 	cl = (CLIENT *)mem_alloc(sizeof(CLIENT));
113 	if (cl == NULL) {
114 		(void) fprintf(stderr, "clntudp_create: out of memory\n");
115 		rpc_createerr.cf_stat = RPC_SYSTEMERROR;
116 		rpc_createerr.cf_error.re_errno = errno;
117 		goto fooy;
118 	}
119 	sendsz = ((sendsz + 3) / 4) * 4;
120 	recvsz = ((recvsz + 3) / 4) * 4;
121 	cu = (struct cu_data *)mem_alloc(sizeof(*cu) + sendsz + recvsz);
122 	if (cu == NULL) {
123 		(void) fprintf(stderr, "clntudp_create: out of memory\n");
124 		rpc_createerr.cf_stat = RPC_SYSTEMERROR;
125 		rpc_createerr.cf_error.re_errno = errno;
126 		goto fooy;
127 	}
128 	cu->cu_outbuf = &cu->cu_inbuf[recvsz];
129 
130 	(void)gettimeofday(&now, NULL);
131 	if (raddr->sin_port == 0) {
132 		u_short port;
133 		if ((port =
134 		    pmap_getport(raddr, program, version, IPPROTO_UDP)) == 0) {
135 			goto fooy;
136 		}
137 		raddr->sin_port = htons(port);
138 	}
139 	cl->cl_ops = &udp_ops;
140 	cl->cl_private = (caddr_t)cu;
141 	cu->cu_raddr = *raddr;
142 	cu->cu_rlen = sizeof (cu->cu_raddr);
143 	cu->cu_wait = wait;
144 	cu->cu_total.tv_sec = -1;
145 	cu->cu_total.tv_usec = -1;
146 	cu->cu_sendsz = sendsz;
147 	cu->cu_recvsz = recvsz;
148 	call_msg.rm_xid = arc4random();
149 	call_msg.rm_direction = CALL;
150 	call_msg.rm_call.cb_rpcvers = RPC_MSG_VERSION;
151 	call_msg.rm_call.cb_prog = program;
152 	call_msg.rm_call.cb_vers = version;
153 	xdrmem_create(&(cu->cu_outxdrs), cu->cu_outbuf,
154 	    sendsz, XDR_ENCODE);
155 	if (!xdr_callhdr(&(cu->cu_outxdrs), &call_msg)) {
156 		goto fooy;
157 	}
158 	cu->cu_xdrpos = XDR_GETPOS(&(cu->cu_outxdrs));
159 	if (*sockp < 0) {
160 		int dontblock = 1;
161 
162 		*sockp = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
163 		if (*sockp < 0) {
164 			rpc_createerr.cf_stat = RPC_SYSTEMERROR;
165 			rpc_createerr.cf_error.re_errno = errno;
166 			goto fooy;
167 		}
168 		/* attempt to bind to priv port */
169 		(void)bindresvport(*sockp, NULL);
170 		/* the sockets rpc controls are non-blocking */
171 		(void)ioctl(*sockp, FIONBIO, (char *) &dontblock);
172 		cu->cu_closeit = TRUE;
173 	} else {
174 		cu->cu_closeit = FALSE;
175 	}
176 	cu->cu_sock = *sockp;
177 	cl->cl_auth = authnone_create();
178 	if (cl->cl_auth == NULL) {
179 		rpc_createerr.cf_stat = RPC_SYSTEMERROR;
180 		rpc_createerr.cf_error.re_errno = errno;
181 		goto fooy;
182 	}
183 	return (cl);
184 fooy:
185 	if (cu)
186 		mem_free((caddr_t)cu, sizeof(*cu) + sendsz + recvsz);
187 	if (cl)
188 		mem_free((caddr_t)cl, sizeof(CLIENT));
189 	return (NULL);
190 }
191 
192 CLIENT *
193 clntudp_create(struct sockaddr_in *raddr, u_long program, u_long version,
194     struct timeval wait, int *sockp)
195 {
196 
197 	return(clntudp_bufcreate(raddr, program, version, wait, sockp,
198 	    UDPMSGSIZE, UDPMSGSIZE));
199 }
200 
201 static enum clnt_stat
202 clntudp_call(CLIENT *cl,	/* client handle */
203     u_long proc,		/* procedure number */
204     xdrproc_t xargs,		/* xdr routine for args */
205     caddr_t argsp,		/* pointer to args */
206     xdrproc_t xresults,		/* xdr routine for results */
207     caddr_t resultsp,		/* pointer to results */
208     struct timeval utimeout)	/* seconds to wait before giving up */
209 {
210 	struct cu_data *cu = (struct cu_data *)cl->cl_private;
211 	XDR *xdrs;
212 	int outlen;
213 	int inlen;
214 	socklen_t fromlen;
215 	struct pollfd pfd[1];
216 	struct sockaddr_in from;
217 	struct rpc_msg reply_msg;
218 	XDR reply_xdrs;
219 	struct timeval time_waited, start, after, tmp1, tmp2;
220 	bool_t ok;
221 	int nrefreshes = 2;	/* number of times to refresh cred */
222 	struct timeval timeout;
223 
224 	if (cu->cu_total.tv_usec == -1)
225 		timeout = utimeout;     /* use supplied timeout */
226 	else
227 		timeout = cu->cu_total; /* use default timeout */
228 
229 	pfd[0].fd = cu->cu_sock;
230 	pfd[0].events = POLLIN;
231 	timerclear(&time_waited);
232 call_again:
233 	xdrs = &(cu->cu_outxdrs);
234 	xdrs->x_op = XDR_ENCODE;
235 	XDR_SETPOS(xdrs, cu->cu_xdrpos);
236 	/*
237 	 * the transaction is the first thing in the out buffer
238 	 */
239 	(*(u_short *)(cu->cu_outbuf))++;
240 	if (!XDR_PUTLONG(xdrs, (long *)&proc) ||
241 	    !AUTH_MARSHALL(cl->cl_auth, xdrs) ||
242 	    !(*xargs)(xdrs, argsp)) {
243 		return (cu->cu_error.re_status = RPC_CANTENCODEARGS);
244 	}
245 	outlen = (int)XDR_GETPOS(xdrs);
246 
247 send_again:
248 	if (sendto(cu->cu_sock, cu->cu_outbuf, outlen, 0,
249 	    (struct sockaddr *)&(cu->cu_raddr), cu->cu_rlen) != outlen) {
250 		cu->cu_error.re_errno = errno;
251 		return (cu->cu_error.re_status = RPC_CANTSEND);
252 	}
253 
254 	/*
255 	 * Hack to provide rpc-based message passing
256 	 */
257 	if (!timerisset(&timeout))
258 		return (cu->cu_error.re_status = RPC_TIMEDOUT);
259 
260 	/*
261 	 * sub-optimal code appears here because we have
262 	 * some clock time to spare while the packets are in flight.
263 	 * (We assume that this is actually only executed once.)
264 	 */
265 	reply_msg.acpted_rply.ar_verf = _null_auth;
266 	reply_msg.acpted_rply.ar_results.where = resultsp;
267 	reply_msg.acpted_rply.ar_results.proc = xresults;
268 
269 	gettimeofday(&start, NULL);
270 	for (;;) {
271 		switch (poll(pfd, 1,
272 		    cu->cu_wait.tv_sec * 1000 + cu->cu_wait.tv_usec / 1000)) {
273 		case 0:
274 			timeradd(&time_waited, &cu->cu_wait, &tmp1);
275 			time_waited = tmp1;
276 			if (timercmp(&time_waited, &timeout, <))
277 				goto send_again;
278 			return (cu->cu_error.re_status = RPC_TIMEDOUT);
279 		case 1:
280 			if (pfd[0].revents & POLLNVAL)
281 				errno = EBADF;
282 			else if (pfd[0].revents & POLLERR)
283 				errno = EIO;
284 			else
285 				break;
286 			/* FALLTHROUGH */
287 		case -1:
288 			if (errno == EINTR) {
289 				gettimeofday(&after, NULL);
290 				timersub(&after, &start, &tmp1);
291 				timeradd(&time_waited, &tmp1, &tmp2);
292 				time_waited = tmp2;
293 				if (timercmp(&time_waited, &timeout, <))
294 					continue;
295 				return (cu->cu_error.re_status = RPC_TIMEDOUT);
296 			}
297 			cu->cu_error.re_errno = errno;
298 			return (cu->cu_error.re_status = RPC_CANTRECV);
299 		}
300 
301 		do {
302 			fromlen = sizeof(struct sockaddr);
303 			inlen = recvfrom(cu->cu_sock, cu->cu_inbuf,
304 			    (int) cu->cu_recvsz, 0,
305 			    (struct sockaddr *)&from, &fromlen);
306 		} while (inlen < 0 && errno == EINTR);
307 		if (inlen < 0) {
308 			if (errno == EWOULDBLOCK)
309 				continue;
310 			cu->cu_error.re_errno = errno;
311 			return (cu->cu_error.re_status = RPC_CANTRECV);
312 		}
313 		if (inlen < sizeof(u_int32_t))
314 			continue;
315 		/* see if reply transaction id matches sent id */
316 		if (((struct rpc_msg *)(cu->cu_inbuf))->rm_xid !=
317 		    ((struct rpc_msg *)(cu->cu_outbuf))->rm_xid)
318 			continue;
319 		/* we now assume we have the proper reply */
320 		break;
321 	}
322 
323 	/*
324 	 * now decode and validate the response
325 	 */
326 	xdrmem_create(&reply_xdrs, cu->cu_inbuf, (u_int)inlen, XDR_DECODE);
327 	ok = xdr_replymsg(&reply_xdrs, &reply_msg);
328 	/* XDR_DESTROY(&reply_xdrs);  save a few cycles on noop destroy */
329 	if (ok) {
330 #if 0
331 		/*
332 		 * XXX Would like to check these, but call_msg is not
333 		 * around.
334 		 */
335 		if (reply_msg.rm_call.cb_prog != call_msg.rm_call.cb_prog ||
336 		    reply_msg.rm_call.cb_vers != call_msg.rm_call.cb_vers ||
337 		    reply_msg.rm_call.cb_proc != call_msg.rm_call.cb_proc) {
338 			goto call_again;	/* XXX spin? */
339 		}
340 #endif
341 
342 		_seterr_reply(&reply_msg, &(cu->cu_error));
343 		if (cu->cu_error.re_status == RPC_SUCCESS) {
344 			if (!AUTH_VALIDATE(cl->cl_auth,
345 			    &reply_msg.acpted_rply.ar_verf)) {
346 				cu->cu_error.re_status = RPC_AUTHERROR;
347 				cu->cu_error.re_why = AUTH_INVALIDRESP;
348 			}
349 			if (reply_msg.acpted_rply.ar_verf.oa_base != NULL) {
350 				xdrs->x_op = XDR_FREE;
351 				(void)xdr_opaque_auth(xdrs,
352 				    &(reply_msg.acpted_rply.ar_verf));
353 			}
354 		} else {
355 			/* maybe our credentials need to be refreshed ... */
356 			if (nrefreshes > 0 && AUTH_REFRESH(cl->cl_auth)) {
357 				nrefreshes--;
358 				goto call_again;
359 			}
360 		}
361 	} else {
362 		/* xdr_replymsg() may have left some things allocated */
363 		int op = reply_xdrs.x_op;
364 		reply_xdrs.x_op = XDR_FREE;
365 		xdr_replymsg(&reply_xdrs, &reply_msg);
366 		reply_xdrs.x_op = op;
367 		cu->cu_error.re_status = RPC_CANTDECODERES;
368 	}
369 
370 	return (cu->cu_error.re_status);
371 }
372 
373 static void
374 clntudp_geterr(CLIENT *cl, struct rpc_err *errp)
375 {
376 	struct cu_data *cu = (struct cu_data *)cl->cl_private;
377 
378 	*errp = cu->cu_error;
379 }
380 
381 
382 static bool_t
383 clntudp_freeres(CLIENT *cl, xdrproc_t xdr_res, caddr_t res_ptr)
384 {
385 	struct cu_data *cu = (struct cu_data *)cl->cl_private;
386 	XDR *xdrs = &(cu->cu_outxdrs);
387 
388 	xdrs->x_op = XDR_FREE;
389 	return ((*xdr_res)(xdrs, res_ptr));
390 }
391 
392 /*ARGSUSED*/
393 static void
394 clntudp_abort(CLIENT *clnt)
395 {
396 }
397 
398 static bool_t
399 clntudp_control(CLIENT *cl, u_int request, void *info)
400 {
401 	struct cu_data *cu = (struct cu_data *)cl->cl_private;
402 
403 	switch (request) {
404 	case CLSET_TIMEOUT:
405 		cu->cu_total = *(struct timeval *)info;
406 		break;
407 	case CLGET_TIMEOUT:
408 		*(struct timeval *)info = cu->cu_total;
409 		break;
410 	case CLSET_RETRY_TIMEOUT:
411 		cu->cu_wait = *(struct timeval *)info;
412 		break;
413 	case CLGET_RETRY_TIMEOUT:
414 		*(struct timeval *)info = cu->cu_wait;
415 		break;
416 	case CLGET_SERVER_ADDR:
417 		*(struct sockaddr_in *)info = cu->cu_raddr;
418 		break;
419 	default:
420 		return (FALSE);
421 	}
422 	return (TRUE);
423 }
424 
425 static void
426 clntudp_destroy(CLIENT *cl)
427 {
428 	struct cu_data *cu = (struct cu_data *)cl->cl_private;
429 
430 	if (cu->cu_closeit) {
431 		(void)close(cu->cu_sock);
432 	}
433 	XDR_DESTROY(&(cu->cu_outxdrs));
434 	mem_free((caddr_t)cu, (sizeof(*cu) + cu->cu_sendsz + cu->cu_recvsz));
435 	mem_free((caddr_t)cl, sizeof(CLIENT));
436 }
437