xref: /openbsd/lib/libc/rpc/clnt_udp.c (revision a49620e5)
1 /*	$OpenBSD: clnt_udp.c,v 1.35 2018/01/06 15:37:36 cheloha Exp $ */
2 
3 /*
4  * Copyright (c) 2010, Oracle America, Inc.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions are
8  * met:
9  *
10  *     * Redistributions of source code must retain the above copyright
11  *       notice, this list of conditions and the following disclaimer.
12  *     * Redistributions in binary form must reproduce the above
13  *       copyright notice, this list of conditions and the following
14  *       disclaimer in the documentation and/or other materials
15  *       provided with the distribution.
16  *     * Neither the name of the "Oracle America, 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
21  *   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  *   FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
24  *   COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
25  *   INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  *   DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
27  *   GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28  *   INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
29  *   WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
30  *   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31  *   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32  */
33 
34 /*
35  * clnt_udp.c, Implements a UDP/IP based, client side RPC.
36  */
37 
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <unistd.h>
42 #include <fcntl.h>
43 #include <rpc/rpc.h>
44 #include <sys/socket.h>
45 #include <netdb.h>
46 #include <errno.h>
47 #include <rpc/pmap_clnt.h>
48 
49 /*
50  * UDP bases client side rpc operations
51  */
52 static enum clnt_stat	clntudp_call(CLIENT *, u_long, xdrproc_t, caddr_t,
53 			    xdrproc_t, caddr_t, struct timeval);
54 static void		clntudp_abort(CLIENT *);
55 static void		clntudp_geterr(CLIENT *, struct rpc_err *);
56 static bool_t		clntudp_freeres(CLIENT *, xdrproc_t, caddr_t);
57 static bool_t           clntudp_control(CLIENT *, u_int, void *);
58 static void		clntudp_destroy(CLIENT *);
59 
60 static struct clnt_ops udp_ops = {
61 	clntudp_call,
62 	clntudp_abort,
63 	clntudp_geterr,
64 	clntudp_freeres,
65 	clntudp_destroy,
66 	clntudp_control
67 };
68 
69 /*
70  * Private data kept per client handle
71  */
72 struct cu_data {
73 	int		   cu_sock;
74 	bool_t		   cu_closeit;
75 	struct sockaddr_in cu_raddr;
76 	int		   cu_rlen;
77 	struct timeval	   cu_wait;
78 	struct timeval     cu_total;
79 	struct rpc_err	   cu_error;
80 	XDR		   cu_outxdrs;
81 	u_int		   cu_xdrpos;
82 	u_int		   cu_sendsz;
83 	char		   *cu_outbuf;
84 	u_int		   cu_recvsz;
85 	char		   cu_inbuf[1];
86 };
87 
88 /*
89  * Create a UDP based client handle.
90  * If *sockp<0, *sockp is set to a newly created UPD socket.
91  * If raddr->sin_port is 0 a binder on the remote machine
92  * is consulted for the correct port number.
93  * NB: It is the client's responsibility to close *sockp, unless
94  *	clntudp_bufcreate() was called with *sockp = -1 (so it created
95  *	the socket), and CLNT_DESTROY() is used.
96  * NB: The rpch->cl_auth is initialized to null authentication.
97  *     Caller may wish to set this something more useful.
98  *
99  * wait is the amount of time used between retransmitting a call if
100  * no response has been heard;  retransmission occurs until the actual
101  * rpc call times out.
102  *
103  * sendsz and recvsz are the maximum allowable packet sizes that can be
104  * sent and received.
105  */
106 CLIENT *
107 clntudp_bufcreate(struct sockaddr_in *raddr, u_long program, u_long version,
108     struct timeval wait, int *sockp, u_int sendsz, u_int recvsz)
109 {
110 	CLIENT *cl;
111 	struct cu_data *cu = NULL;
112 	struct rpc_msg call_msg;
113 
114 	cl = (CLIENT *)mem_alloc(sizeof(CLIENT));
115 	if (cl == NULL) {
116 		rpc_createerr.cf_stat = RPC_SYSTEMERROR;
117 		rpc_createerr.cf_error.re_errno = errno;
118 		goto fooy;
119 	}
120 	sendsz = ((sendsz + 3) / 4) * 4;
121 	recvsz = ((recvsz + 3) / 4) * 4;
122 	cu = (struct cu_data *)mem_alloc(sizeof(*cu) + sendsz + recvsz);
123 	if (cu == NULL) {
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 	if (raddr->sin_port == 0) {
131 		u_short port;
132 		if ((port =
133 		    pmap_getport(raddr, program, version, IPPROTO_UDP)) == 0) {
134 			goto fooy;
135 		}
136 		raddr->sin_port = htons(port);
137 	}
138 	cl->cl_ops = &udp_ops;
139 	cl->cl_private = (caddr_t)cu;
140 	cu->cu_raddr = *raddr;
141 	cu->cu_rlen = sizeof (cu->cu_raddr);
142 	cu->cu_wait = wait;
143 	cu->cu_total.tv_sec = -1;
144 	cu->cu_total.tv_usec = -1;
145 	cu->cu_sendsz = sendsz;
146 	cu->cu_recvsz = recvsz;
147 	call_msg.rm_xid = arc4random();
148 	call_msg.rm_direction = CALL;
149 	call_msg.rm_call.cb_rpcvers = RPC_MSG_VERSION;
150 	call_msg.rm_call.cb_prog = program;
151 	call_msg.rm_call.cb_vers = version;
152 	xdrmem_create(&(cu->cu_outxdrs), cu->cu_outbuf,
153 	    sendsz, XDR_ENCODE);
154 	if (!xdr_callhdr(&(cu->cu_outxdrs), &call_msg)) {
155 		goto fooy;
156 	}
157 	cu->cu_xdrpos = XDR_GETPOS(&(cu->cu_outxdrs));
158 	if (*sockp < 0) {
159 		*sockp = socket(AF_INET, SOCK_DGRAM | SOCK_NONBLOCK,
160 		    IPPROTO_UDP);
161 		if (*sockp < 0) {
162 			rpc_createerr.cf_stat = RPC_SYSTEMERROR;
163 			rpc_createerr.cf_error.re_errno = errno;
164 			goto fooy;
165 		}
166 		/* attempt to bind to priv port */
167 		(void)bindresvport(*sockp, NULL);
168 		cu->cu_closeit = TRUE;
169 	} else {
170 		cu->cu_closeit = FALSE;
171 	}
172 	cu->cu_sock = *sockp;
173 	cl->cl_auth = authnone_create();
174 	if (cl->cl_auth == NULL) {
175 		rpc_createerr.cf_stat = RPC_SYSTEMERROR;
176 		rpc_createerr.cf_error.re_errno = errno;
177 		goto fooy;
178 	}
179 	return (cl);
180 fooy:
181 	if (cu)
182 		mem_free((caddr_t)cu, sizeof(*cu) + sendsz + recvsz);
183 	if (cl)
184 		mem_free((caddr_t)cl, sizeof(CLIENT));
185 	return (NULL);
186 }
187 DEF_WEAK(clntudp_bufcreate);
188 
189 CLIENT *
190 clntudp_create(struct sockaddr_in *raddr, u_long program, u_long version,
191     struct timeval wait, int *sockp)
192 {
193 
194 	return(clntudp_bufcreate(raddr, program, version, wait, sockp,
195 	    UDPMSGSIZE, UDPMSGSIZE));
196 }
197 DEF_WEAK(clntudp_create);
198 
199 static enum clnt_stat
200 clntudp_call(CLIENT *cl,	/* client handle */
201     u_long proc,		/* procedure number */
202     xdrproc_t xargs,		/* xdr routine for args */
203     caddr_t argsp,		/* pointer to args */
204     xdrproc_t xresults,		/* xdr routine for results */
205     caddr_t resultsp,		/* pointer to results */
206     struct timeval utimeout)	/* seconds to wait before giving up */
207 {
208 	struct cu_data *cu = (struct cu_data *)cl->cl_private;
209 	XDR *xdrs;
210 	int outlen;
211 	int inlen;
212 	socklen_t fromlen;
213 	struct pollfd pfd[1];
214 	struct sockaddr_in from;
215 	struct rpc_msg reply_msg;
216 	XDR reply_xdrs;
217 	struct timespec time_waited, start, after, duration, wait;
218 	bool_t ok;
219 	int nrefreshes = 2;	/* number of times to refresh cred */
220 	struct timespec timeout;
221 
222 	if (cu->cu_total.tv_usec == -1)
223 		TIMEVAL_TO_TIMESPEC(&utimeout, &timeout);     /* use supplied timeout */
224 	else
225 		TIMEVAL_TO_TIMESPEC(&cu->cu_total, &timeout); /* use default timeout */
226 
227 	pfd[0].fd = cu->cu_sock;
228 	pfd[0].events = POLLIN;
229 	timespecclear(&time_waited);
230 	TIMEVAL_TO_TIMESPEC(&cu->cu_wait, &wait);
231 call_again:
232 	xdrs = &(cu->cu_outxdrs);
233 	xdrs->x_op = XDR_ENCODE;
234 	XDR_SETPOS(xdrs, cu->cu_xdrpos);
235 	/*
236 	 * the transaction is the first thing in the out buffer
237 	 */
238 	(*(u_short *)(cu->cu_outbuf))++;
239 	if (!XDR_PUTLONG(xdrs, (long *)&proc) ||
240 	    !AUTH_MARSHALL(cl->cl_auth, xdrs) ||
241 	    !(*xargs)(xdrs, argsp)) {
242 		return (cu->cu_error.re_status = RPC_CANTENCODEARGS);
243 	}
244 	outlen = (int)XDR_GETPOS(xdrs);
245 
246 send_again:
247 	if (sendto(cu->cu_sock, cu->cu_outbuf, outlen, 0,
248 	    (struct sockaddr *)&(cu->cu_raddr), cu->cu_rlen) != outlen) {
249 		cu->cu_error.re_errno = errno;
250 		return (cu->cu_error.re_status = RPC_CANTSEND);
251 	}
252 
253 	/*
254 	 * Hack to provide rpc-based message passing
255 	 */
256 	if (!timespecisset(&timeout))
257 		return (cu->cu_error.re_status = RPC_TIMEDOUT);
258 
259 	/*
260 	 * sub-optimal code appears here because we have
261 	 * some clock time to spare while the packets are in flight.
262 	 * (We assume that this is actually only executed once.)
263 	 */
264 	reply_msg.acpted_rply.ar_verf = _null_auth;
265 	reply_msg.acpted_rply.ar_results.where = resultsp;
266 	reply_msg.acpted_rply.ar_results.proc = xresults;
267 
268 	clock_gettime(CLOCK_MONOTONIC, &start);
269 	for (;;) {
270 		switch (ppoll(pfd, 1, &wait, NULL)) {
271 		case 0:
272 			timespecadd(&time_waited, &wait, &time_waited);
273 			if (timespeccmp(&time_waited, &timeout, <))
274 				goto send_again;
275 			return (cu->cu_error.re_status = RPC_TIMEDOUT);
276 		case 1:
277 			if (pfd[0].revents & POLLNVAL)
278 				errno = EBADF;
279 			else if (pfd[0].revents & POLLERR)
280 				errno = EIO;
281 			else
282 				break;
283 			/* FALLTHROUGH */
284 		case -1:
285 			if (errno == EINTR) {
286 				clock_gettime(CLOCK_MONOTONIC, &after);
287 				timespecsub(&after, &start, &duration);
288 				timespecadd(&time_waited, &duration, &time_waited);
289 				if (timespeccmp(&time_waited, &timeout, <))
290 					continue;
291 				return (cu->cu_error.re_status = RPC_TIMEDOUT);
292 			}
293 			cu->cu_error.re_errno = errno;
294 			return (cu->cu_error.re_status = RPC_CANTRECV);
295 		}
296 
297 		do {
298 			fromlen = sizeof(struct sockaddr);
299 			inlen = recvfrom(cu->cu_sock, cu->cu_inbuf,
300 			    (int) cu->cu_recvsz, 0,
301 			    (struct sockaddr *)&from, &fromlen);
302 		} while (inlen < 0 && errno == EINTR);
303 		if (inlen < 0) {
304 			if (errno == EWOULDBLOCK)
305 				continue;
306 			cu->cu_error.re_errno = errno;
307 			return (cu->cu_error.re_status = RPC_CANTRECV);
308 		}
309 		if (inlen < sizeof(u_int32_t))
310 			continue;
311 		/* see if reply transaction id matches sent id */
312 		if (((struct rpc_msg *)(cu->cu_inbuf))->rm_xid !=
313 		    ((struct rpc_msg *)(cu->cu_outbuf))->rm_xid)
314 			continue;
315 		/* we now assume we have the proper reply */
316 		break;
317 	}
318 
319 	/*
320 	 * now decode and validate the response
321 	 */
322 	xdrmem_create(&reply_xdrs, cu->cu_inbuf, (u_int)inlen, XDR_DECODE);
323 	ok = xdr_replymsg(&reply_xdrs, &reply_msg);
324 	/* XDR_DESTROY(&reply_xdrs);  save a few cycles on noop destroy */
325 	if (ok) {
326 #if 0
327 		/*
328 		 * XXX Would like to check these, but call_msg is not
329 		 * around.
330 		 */
331 		if (reply_msg.rm_call.cb_prog != call_msg.rm_call.cb_prog ||
332 		    reply_msg.rm_call.cb_vers != call_msg.rm_call.cb_vers ||
333 		    reply_msg.rm_call.cb_proc != call_msg.rm_call.cb_proc) {
334 			goto call_again;	/* XXX spin? */
335 		}
336 #endif
337 
338 		_seterr_reply(&reply_msg, &(cu->cu_error));
339 		if (cu->cu_error.re_status == RPC_SUCCESS) {
340 			if (!AUTH_VALIDATE(cl->cl_auth,
341 			    &reply_msg.acpted_rply.ar_verf)) {
342 				cu->cu_error.re_status = RPC_AUTHERROR;
343 				cu->cu_error.re_why = AUTH_INVALIDRESP;
344 			}
345 			if (reply_msg.acpted_rply.ar_verf.oa_base != NULL) {
346 				xdrs->x_op = XDR_FREE;
347 				(void)xdr_opaque_auth(xdrs,
348 				    &(reply_msg.acpted_rply.ar_verf));
349 			}
350 		} else {
351 			/* maybe our credentials need to be refreshed ... */
352 			if (nrefreshes > 0 && AUTH_REFRESH(cl->cl_auth)) {
353 				nrefreshes--;
354 				goto call_again;
355 			}
356 		}
357 	} else {
358 		/* xdr_replymsg() may have left some things allocated */
359 		int op = reply_xdrs.x_op;
360 		reply_xdrs.x_op = XDR_FREE;
361 		xdr_replymsg(&reply_xdrs, &reply_msg);
362 		reply_xdrs.x_op = op;
363 		cu->cu_error.re_status = RPC_CANTDECODERES;
364 	}
365 
366 	return (cu->cu_error.re_status);
367 }
368 
369 static void
370 clntudp_geterr(CLIENT *cl, struct rpc_err *errp)
371 {
372 	struct cu_data *cu = (struct cu_data *)cl->cl_private;
373 
374 	*errp = cu->cu_error;
375 }
376 
377 
378 static bool_t
379 clntudp_freeres(CLIENT *cl, xdrproc_t xdr_res, caddr_t res_ptr)
380 {
381 	struct cu_data *cu = (struct cu_data *)cl->cl_private;
382 	XDR *xdrs = &(cu->cu_outxdrs);
383 
384 	xdrs->x_op = XDR_FREE;
385 	return ((*xdr_res)(xdrs, res_ptr));
386 }
387 
388 static void
389 clntudp_abort(CLIENT *clnt)
390 {
391 }
392 
393 static bool_t
394 clntudp_control(CLIENT *cl, u_int request, void *info)
395 {
396 	struct cu_data *cu = (struct cu_data *)cl->cl_private;
397 
398 	switch (request) {
399 	case CLSET_TIMEOUT:
400 		cu->cu_total = *(struct timeval *)info;
401 		break;
402 	case CLGET_TIMEOUT:
403 		*(struct timeval *)info = cu->cu_total;
404 		break;
405 	case CLSET_RETRY_TIMEOUT:
406 		cu->cu_wait = *(struct timeval *)info;
407 		break;
408 	case CLGET_RETRY_TIMEOUT:
409 		*(struct timeval *)info = cu->cu_wait;
410 		break;
411 	case CLGET_SERVER_ADDR:
412 		*(struct sockaddr_in *)info = cu->cu_raddr;
413 		break;
414 	default:
415 		return (FALSE);
416 	}
417 	return (TRUE);
418 }
419 
420 static void
421 clntudp_destroy(CLIENT *cl)
422 {
423 	struct cu_data *cu = (struct cu_data *)cl->cl_private;
424 
425 	if (cu->cu_closeit && cu->cu_sock != -1) {
426 		(void)close(cu->cu_sock);
427 	}
428 	XDR_DESTROY(&(cu->cu_outxdrs));
429 	mem_free((caddr_t)cu, (sizeof(*cu) + cu->cu_sendsz + cu->cu_recvsz));
430 	mem_free((caddr_t)cl, sizeof(CLIENT));
431 }
432