xref: /openbsd-src/lib/libc/rpc/svc_tcp.c (revision 4c1e55dc91edd6e69ccc60ce855900fbc12cf34f)
1 /*	$OpenBSD: svc_tcp.c,v 1.30 2010/09/01 14:43:34 millert 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  * svc_tcp.c, Server side for TCP/IP based RPC.
36  *
37  * Actually implements two flavors of transporter -
38  * a tcp rendezvouser (a listner and connection establisher)
39  * and a record/tcp stream.
40  */
41 
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <string.h>
45 #include <unistd.h>
46 #include <rpc/rpc.h>
47 #include <sys/socket.h>
48 #include <errno.h>
49 
50 #include <netinet/in_systm.h>
51 #include <netinet/in.h>
52 #include <netinet/ip.h>
53 #include <netinet/ip_var.h>
54 
55 /*
56  * Ops vector for TCP/IP based rpc service handle
57  */
58 static bool_t		svctcp_recv(SVCXPRT *xprt, struct rpc_msg *msg);
59 static enum xprt_stat	svctcp_stat(SVCXPRT *xprt);
60 static bool_t		svctcp_getargs(SVCXPRT *xprt, xdrproc_t xdr_args,
61 			    caddr_t args_ptr);
62 static bool_t		svctcp_reply(SVCXPRT *xprt, struct rpc_msg *msg);
63 static bool_t		svctcp_freeargs(SVCXPRT *xprt, xdrproc_t xdr_args,
64 			    caddr_t args_ptr);
65 static void		svctcp_destroy(SVCXPRT *xprt);
66 
67 static struct xp_ops svctcp_op = {
68 	svctcp_recv,
69 	svctcp_stat,
70 	svctcp_getargs,
71 	svctcp_reply,
72 	svctcp_freeargs,
73 	svctcp_destroy
74 };
75 
76 /*
77  * Ops vector for TCP/IP rendezvous handler
78  */
79 static bool_t		rendezvous_request(SVCXPRT *xprt, struct rpc_msg *);
80 static enum xprt_stat	rendezvous_stat(SVCXPRT *xprt);
81 
82 static struct xp_ops svctcp_rendezvous_op = {
83 	rendezvous_request,
84 	rendezvous_stat,
85 	/* XXX abort illegal in library */
86 	(bool_t (*)(struct __rpc_svcxprt *, xdrproc_t, caddr_t))abort,
87 	(bool_t (*)(struct __rpc_svcxprt *, struct rpc_msg *))abort,
88 	(bool_t (*)(struct __rpc_svcxprt *, xdrproc_t, caddr_t))abort,
89 	svctcp_destroy
90 };
91 
92 static int readtcp(SVCXPRT *xprt, caddr_t buf, int len),
93     writetcp(SVCXPRT *xprt, caddr_t buf, int len);
94 static SVCXPRT *makefd_xprt(int fd, u_int sendsize, u_int recvsize);
95 
96 struct tcp_rendezvous { /* kept in xprt->xp_p1 */
97 	u_int sendsize;
98 	u_int recvsize;
99 };
100 
101 struct tcp_conn {  /* kept in xprt->xp_p1 */
102 	enum xprt_stat strm_stat;
103 	u_long x_id;
104 	XDR xdrs;
105 	char verf_body[MAX_AUTH_BYTES];
106 };
107 
108 /*
109  * Usage:
110  *	xprt = svctcp_create(sock, send_buf_size, recv_buf_size);
111  *
112  * Creates, registers, and returns a (rpc) tcp based transporter.
113  * Once *xprt is initialized, it is registered as a transporter
114  * see (svc.h, xprt_register).  This routine returns
115  * a NULL if a problem occurred.
116  *
117  * If sock<0 then a socket is created, else sock is used.
118  * If the socket, sock is not bound to a port then svctcp_create
119  * binds it to an arbitrary port.  The routine then starts a tcp
120  * listener on the socket's associated port.  In any (successful) case,
121  * xprt->xp_sock is the registered socket number and xprt->xp_port is the
122  * associated port number.
123  *
124  * Since tcp streams do buffered io similar to stdio, the caller can specify
125  * how big the send and receive buffers are via the second and third parms;
126  * 0 => use the system default.
127  */
128 SVCXPRT *
129 svctcp_create(int sock, u_int sendsize, u_int recvsize)
130 {
131 	bool_t madesock = FALSE;
132 	SVCXPRT *xprt;
133 	struct tcp_rendezvous *r;
134 	struct sockaddr_in addr;
135 	socklen_t len = sizeof(struct sockaddr_in);
136 
137 	if (sock == RPC_ANYSOCK) {
138 		if ((sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) {
139 			perror("svctcp_.c - udp socket creation problem");
140 			return (NULL);
141 		}
142 		madesock = TRUE;
143 	}
144 	memset(&addr, 0, sizeof (addr));
145 	addr.sin_len = sizeof(struct sockaddr_in);
146 	addr.sin_family = AF_INET;
147 	if (bindresvport(sock, &addr)) {
148 		addr.sin_port = 0;
149 		(void)bind(sock, (struct sockaddr *)&addr, len);
150 	}
151 	if ((getsockname(sock, (struct sockaddr *)&addr, &len) != 0)  ||
152 	    (listen(sock, 2) != 0)) {
153 		perror("svctcp_.c - cannot getsockname or listen");
154 		if (madesock)
155 			(void)close(sock);
156 		return (NULL);
157 	}
158 	r = (struct tcp_rendezvous *)mem_alloc(sizeof(*r));
159 	if (r == NULL) {
160 		(void)fprintf(stderr, "svctcp_create: out of memory\n");
161 		if (madesock)
162 			(void)close(sock);
163 		return (NULL);
164 	}
165 	r->sendsize = sendsize;
166 	r->recvsize = recvsize;
167 	xprt = (SVCXPRT *)mem_alloc(sizeof(SVCXPRT));
168 	if (xprt == NULL) {
169 		(void)fprintf(stderr, "svctcp_create: out of memory\n");
170 		if (madesock)
171 			(void)close(sock);
172 		free(r);
173 		return (NULL);
174 	}
175 	xprt->xp_p2 = NULL;
176 	xprt->xp_p1 = (caddr_t)r;
177 	xprt->xp_verf = _null_auth;
178 	xprt->xp_ops = &svctcp_rendezvous_op;
179 	xprt->xp_port = ntohs(addr.sin_port);
180 	xprt->xp_sock = sock;
181 	if (__xprt_register(xprt) == 0) {
182 		if (madesock)
183 			(void)close(sock);
184 		free(r);
185 		free(xprt);
186 		return (NULL);
187 	}
188 	return (xprt);
189 }
190 
191 /*
192  * Like svtcp_create(), except the routine takes any *open* UNIX file
193  * descriptor as its first input.
194  */
195 SVCXPRT *
196 svcfd_create(int fd, u_int sendsize, u_int recvsize)
197 {
198 
199 	return (makefd_xprt(fd, sendsize, recvsize));
200 }
201 
202 static SVCXPRT *
203 makefd_xprt(int fd, u_int sendsize, u_int recvsize)
204 {
205 	SVCXPRT *xprt;
206 	struct tcp_conn *cd;
207 
208 	xprt = (SVCXPRT *)mem_alloc(sizeof(SVCXPRT));
209 	if (xprt == NULL) {
210 		(void) fprintf(stderr, "svc_tcp: makefd_xprt: out of memory\n");
211 		goto done;
212 	}
213 	cd = (struct tcp_conn *)mem_alloc(sizeof(struct tcp_conn));
214 	if (cd == NULL) {
215 		(void) fprintf(stderr, "svc_tcp: makefd_xprt: out of memory\n");
216 		mem_free((char *) xprt, sizeof(SVCXPRT));
217 		xprt = NULL;
218 		goto done;
219 	}
220 	cd->strm_stat = XPRT_IDLE;
221 	xdrrec_create(&(cd->xdrs), sendsize, recvsize,
222 	    (caddr_t)xprt, (int(*)(caddr_t, caddr_t, int))readtcp,
223 	    (int(*)(caddr_t, caddr_t, int))writetcp);
224 	xprt->xp_p2 = NULL;
225 	xprt->xp_p1 = (caddr_t)cd;
226 	xprt->xp_verf.oa_base = cd->verf_body;
227 	xprt->xp_addrlen = 0;
228 	xprt->xp_ops = &svctcp_op;  /* truely deals with calls */
229 	xprt->xp_port = 0;  /* this is a connection, not a rendezvouser */
230 	xprt->xp_sock = fd;
231 	if (__xprt_register(xprt) == 0) {
232 		free(xprt);
233 		free(cd);
234 		return (NULL);
235 	}
236     done:
237 	return (xprt);
238 }
239 
240 /* ARGSUSED */
241 static bool_t
242 rendezvous_request(SVCXPRT *xprt, struct rpc_msg *ignored)
243 {
244 	int sock;
245 	struct tcp_rendezvous *r;
246 	struct sockaddr_in addr;
247 	socklen_t len;
248 
249 	r = (struct tcp_rendezvous *)xprt->xp_p1;
250     again:
251 	len = sizeof(struct sockaddr_in);
252 	if ((sock = accept(xprt->xp_sock, (struct sockaddr *)&addr,
253 	    &len)) < 0) {
254 		if (errno == EINTR)
255 			goto again;
256 	       return (FALSE);
257 	}
258 
259 #ifdef IP_OPTIONS
260 	{
261 		struct ipoption opts;
262 		socklen_t optsize = sizeof(opts);
263 		int i;
264 
265 		if (!getsockopt(sock, IPPROTO_IP, IP_OPTIONS, (char *)&opts,
266 		    &optsize) && optsize != 0) {
267 			for (i = 0; (char *)&opts.ipopt_list[i] - (char *)&opts <
268 			    optsize; ) {
269 				u_char c = (u_char)opts.ipopt_list[i];
270 				if (c == IPOPT_LSRR || c == IPOPT_SSRR) {
271 					close(sock);
272 					return (FALSE);
273 				}
274 				if (c == IPOPT_EOL)
275 					break;
276 				i += (c == IPOPT_NOP) ? 1 :
277 				    (u_char)opts.ipopt_list[i+1];
278 			}
279 		}
280 	}
281 #endif
282 
283 	/*
284 	 * XXX careful for ftp bounce attacks. If discovered, close the
285 	 * socket and look for another connection.
286 	 */
287 	if (addr.sin_port == htons(20)) {
288 		close(sock);
289 		return (FALSE);
290 	}
291 
292 	/*
293 	 * make a new transporter (re-uses xprt)
294 	 */
295 	xprt = makefd_xprt(sock, r->sendsize, r->recvsize);
296 	xprt->xp_raddr = addr;
297 	xprt->xp_addrlen = len;
298 	return (FALSE); /* there is never an rpc msg to be processed */
299 }
300 
301 /* ARGSUSED */
302 static enum xprt_stat
303 rendezvous_stat(SVCXPRT *xprt)
304 {
305 
306 	return (XPRT_IDLE);
307 }
308 
309 static void
310 svctcp_destroy(SVCXPRT *xprt)
311 {
312 	struct tcp_conn *cd = (struct tcp_conn *)xprt->xp_p1;
313 
314 	xprt_unregister(xprt);
315 	if (xprt->xp_sock != -1)
316 		(void)close(xprt->xp_sock);
317 	xprt->xp_sock = -1;
318 	if (xprt->xp_port != 0) {
319 		/* a rendezvouser socket */
320 		xprt->xp_port = 0;
321 	} else {
322 		/* an actual connection socket */
323 		XDR_DESTROY(&(cd->xdrs));
324 	}
325 	mem_free((caddr_t)cd, sizeof(struct tcp_conn));
326 	mem_free((caddr_t)xprt, sizeof(SVCXPRT));
327 }
328 
329 /*
330  * All read operations timeout after 35 seconds.
331  * A timeout is fatal for the connection.
332  */
333 static struct timeval wait_per_try = { 35, 0 };
334 
335 /*
336  * reads data from the tcp conection.
337  * any error is fatal and the connection is closed.
338  * (And a read of zero bytes is a half closed stream => error.)
339  */
340 static int
341 readtcp(SVCXPRT *xprt, caddr_t buf, int len)
342 {
343 	int sock = xprt->xp_sock;
344 	int delta, nready;
345 	struct timeval start;
346 	struct timeval tmp1, tmp2;
347 	struct pollfd *pfd = NULL;
348 
349 	pfd = (struct pollfd *)calloc(sizeof(*pfd), (svc_max_pollfd + 1));
350 	if (pfd == NULL)
351 		goto fatal_err;
352 	pfd[0].fd = sock;
353 	pfd[0].events = POLLIN;
354 	memcpy(&pfd[1], svc_pollfd, (sizeof(*pfd) * svc_max_pollfd));
355 
356 	/*
357 	 * All read operations timeout after 35 seconds.
358 	 * A timeout is fatal for the connection.
359 	 */
360 	delta = wait_per_try.tv_sec * 1000;
361 	gettimeofday(&start, NULL);
362 	do {
363 		nready = poll(pfd, svc_max_pollfd + 1, delta);
364 		switch (nready) {
365 		case -1:
366 			if (errno != EINTR)
367 				goto fatal_err;
368 			gettimeofday(&tmp1, NULL);
369 			timersub(&tmp1, &start, &tmp2);
370 			timersub(&wait_per_try, &tmp2, &tmp1);
371 			if (tmp1.tv_sec < 0 || !timerisset(&tmp1))
372 				goto fatal_err;
373 			delta = tmp1.tv_sec * 1000 + tmp1.tv_usec / 1000;
374 			continue;
375 		case 0:
376 			goto fatal_err;
377 		default:
378 			if (pfd[0].revents == 0) {
379 				svc_getreq_poll(&pfd[1], nready);
380 				gettimeofday(&tmp1, NULL);
381 				timersub(&tmp1, &start, &tmp2);
382 				timersub(&wait_per_try, &tmp2, &tmp1);
383 				if (tmp1.tv_sec < 0 || !timerisset(&tmp1))
384 					goto fatal_err;
385 				delta = tmp1.tv_sec * 1000 + tmp1.tv_usec / 1000;
386 				continue;
387 			}
388 		}
389 	} while (pfd[0].revents == 0);
390 	if ((len = read(sock, buf, len)) > 0) {
391 		if (pfd)
392 			free(pfd);
393 		return (len);
394 	}
395 fatal_err:
396 	((struct tcp_conn *)(xprt->xp_p1))->strm_stat = XPRT_DIED;
397 	if (pfd)
398 		free(pfd);
399 	return (-1);
400 }
401 
402 /*
403  * writes data to the tcp connection.
404  * Any error is fatal and the connection is closed.
405  */
406 static int
407 writetcp(SVCXPRT *xprt, caddr_t buf, int len)
408 {
409 	int i, cnt;
410 
411 	for (cnt = len; cnt > 0; cnt -= i, buf += i) {
412 		if ((i = write(xprt->xp_sock, buf, cnt)) < 0) {
413 			((struct tcp_conn *)(xprt->xp_p1))->strm_stat =
414 			    XPRT_DIED;
415 			return (-1);
416 		}
417 	}
418 	return (len);
419 }
420 
421 static enum xprt_stat
422 svctcp_stat(SVCXPRT *xprt)
423 {
424 	struct tcp_conn *cd =
425 	    (struct tcp_conn *)(xprt->xp_p1);
426 
427 	if (cd->strm_stat == XPRT_DIED)
428 		return (XPRT_DIED);
429 	if (! xdrrec_eof(&(cd->xdrs)))
430 		return (XPRT_MOREREQS);
431 	return (XPRT_IDLE);
432 }
433 
434 static bool_t
435 svctcp_recv(SVCXPRT *xprt, struct rpc_msg *msg)
436 {
437 	struct tcp_conn *cd =
438 	    (struct tcp_conn *)(xprt->xp_p1);
439 	XDR *xdrs = &(cd->xdrs);
440 
441 	xdrs->x_op = XDR_DECODE;
442 	(void)xdrrec_skiprecord(xdrs);
443 	if (xdr_callmsg(xdrs, msg)) {
444 		cd->x_id = msg->rm_xid;
445 		return (TRUE);
446 	}
447 	cd->strm_stat = XPRT_DIED;	/* XXX */
448 	return (FALSE);
449 }
450 
451 static bool_t
452 svctcp_getargs(SVCXPRT *xprt, xdrproc_t xdr_args, caddr_t args_ptr)
453 {
454 
455 	return ((*xdr_args)(&(((struct tcp_conn *)(xprt->xp_p1))->xdrs), args_ptr));
456 }
457 
458 static bool_t
459 svctcp_freeargs(SVCXPRT *xprt, xdrproc_t xdr_args, caddr_t args_ptr)
460 {
461 	XDR *xdrs =
462 	    &(((struct tcp_conn *)(xprt->xp_p1))->xdrs);
463 
464 	xdrs->x_op = XDR_FREE;
465 	return ((*xdr_args)(xdrs, args_ptr));
466 }
467 
468 static bool_t
469 svctcp_reply(SVCXPRT *xprt, struct rpc_msg *msg)
470 {
471 	struct tcp_conn *cd =
472 	    (struct tcp_conn *)(xprt->xp_p1);
473 	XDR *xdrs = &(cd->xdrs);
474 	bool_t stat;
475 
476 	xdrs->x_op = XDR_ENCODE;
477 	msg->rm_xid = cd->x_id;
478 	stat = xdr_replymsg(xdrs, msg);
479 	(void)xdrrec_endofrecord(xdrs, TRUE);
480 	return (stat);
481 }
482