Merge from vendor branch GCC:
[dragonfly.git] / lib / libc / rpc / svc_tcp.c
1 /*
2  * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
3  * unrestricted use provided that this legend is included on all tape
4  * media and as a part of the software program in whole or part.  Users
5  * may copy or modify Sun RPC without charge, but are not authorized
6  * to license or distribute it to anyone else except as part of a product or
7  * program developed by the user.
8  *
9  * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
10  * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
11  * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
12  *
13  * Sun RPC is provided with no support and without any obligation on the
14  * part of Sun Microsystems, Inc. to assist in its use, correction,
15  * modification or enhancement.
16  *
17  * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
18  * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
19  * OR ANY PART THEREOF.
20  *
21  * In no event will Sun Microsystems, Inc. be liable for any lost revenue
22  * or profits or other special, indirect and consequential damages, even if
23  * Sun has been advised of the possibility of such damages.
24  *
25  * Sun Microsystems, Inc.
26  * 2550 Garcia Avenue
27  * Mountain View, California  94043
28  *
29  * @(#)svc_tcp.c 1.21 87/08/11 Copyr 1984 Sun Micro
30  * @(#)svc_tcp.c        2.2 88/08/01 4.0 RPCSRC
31  * $FreeBSD: src/lib/libc/rpc/svc_tcp.c,v 1.18.2.3 2001/09/05 22:29:23 dec Exp $
32  * $DragonFly: src/lib/libc/rpc/svc_tcp.c,v 1.5 2005/11/13 12:27:04 swildner Exp $
33  */
34
35 /*
36  * svc_tcp.c, Server side for TCP/IP based RPC.
37  *
38  * Copyright (C) 1984, Sun Microsystems, Inc.
39  *
40  * Actually implements two flavors of transporter -
41  * a tcp rendezvouser (a listner and connection establisher)
42  * and a record/tcp stream.
43  */
44
45 #include "namespace.h"
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <unistd.h>
49 #include <string.h>
50 #include <rpc/rpc.h>
51 #include <sys/socket.h>
52 #include <sys/ioctl.h>
53 #include <errno.h>
54 #include "un-namespace.h"
55
56 /*
57  * Ops vector for TCP/IP based rpc service handle
58  */
59 static bool_t           svctcp_recv();
60 static enum xprt_stat   svctcp_stat();
61 static bool_t           svctcp_getargs();
62 static bool_t           svctcp_reply();
63 static bool_t           svctcp_freeargs();
64 static void             svctcp_destroy();
65
66 static struct xp_ops svctcp_op = {
67         svctcp_recv,
68         svctcp_stat,
69         svctcp_getargs,
70         svctcp_reply,
71         svctcp_freeargs,
72         svctcp_destroy
73 };
74
75 /*
76  * Ops vector for TCP/IP rendezvous handler
77  */
78 static bool_t           rendezvous_request();
79 static enum xprt_stat   rendezvous_stat();
80
81 static struct xp_ops svctcp_rendezvous_op = {
82         rendezvous_request,
83         rendezvous_stat,
84         (bool_t (*)())abort,
85         (bool_t (*)())abort,
86         (bool_t (*)())abort,
87         svctcp_destroy
88 };
89
90 static int readtcp(), writetcp();
91 static SVCXPRT *makefd_xprt();
92
93 struct tcp_rendezvous { /* kept in xprt->xp_p1 */
94         u_int sendsize;
95         u_int recvsize;
96 };
97
98 struct tcp_conn {  /* kept in xprt->xp_p1 */
99         enum xprt_stat strm_stat;
100         u_long x_id;
101         XDR xdrs;
102         char verf_body[MAX_AUTH_BYTES];
103 };
104
105 /*
106  * Usage:
107  *      xprt = svctcp_create(sock, send_buf_size, recv_buf_size);
108  *
109  * Creates, registers, and returns a (rpc) tcp based transporter.
110  * Once *xprt is initialized, it is registered as a transporter
111  * see (svc.h, xprt_register).  This routine returns
112  * a NULL if a problem occurred.
113  *
114  * If sock<0 then a socket is created, else sock is used.
115  * If the socket, sock is not bound to a port then svctcp_create
116  * binds it to an arbitrary port.  The routine then starts a tcp
117  * listener on the socket's associated port.  In any (successful) case,
118  * xprt->xp_sock is the registered socket number and xprt->xp_port is the
119  * associated port number.
120  *
121  * Since tcp streams do buffered io similar to stdio, the caller can specify
122  * how big the send and receive buffers are via the second and third parms;
123  * 0 => use the system default.
124  */
125 SVCXPRT *
126 svctcp_create(int sock, u_int sendsize, u_int recvsize)
127 {
128         bool_t madesock = FALSE;
129         SVCXPRT *xprt;
130         struct tcp_rendezvous *r;
131         struct sockaddr_in addr;
132         int len = sizeof(struct sockaddr_in);
133         int on;
134
135         if (sock == RPC_ANYSOCK) {
136                 if ((sock = _socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) {
137                         perror("svctcp_.c - tcp socket creation problem");
138                         return ((SVCXPRT *)NULL);
139                 }
140                 madesock = TRUE;
141         }
142         on = 1;
143         if (_ioctl(sock, FIONBIO, &on) < 0) {
144                 perror("svc_tcp.c - cannot turn on non-blocking mode");
145                 if (madesock)
146                        _close(sock);
147                 return ((SVCXPRT *)NULL);
148         }
149         memset(&addr, 0, sizeof (addr));
150         addr.sin_len = sizeof(struct sockaddr_in);
151         addr.sin_family = AF_INET;
152         if (bindresvport(sock, &addr)) {
153                 addr.sin_port = 0;
154                 _bind(sock, (struct sockaddr *)&addr, len);
155         }
156         if ((_getsockname(sock, (struct sockaddr *)&addr, &len) != 0)  ||
157             (_listen(sock, 2) != 0)) {
158                 perror("svctcp_.c - cannot getsockname or listen");
159                 if (madesock)
160                        _close(sock);
161                 return ((SVCXPRT *)NULL);
162         }
163         r = (struct tcp_rendezvous *)mem_alloc(sizeof(*r));
164         if (r == NULL) {
165                 fprintf(stderr, "svctcp_create: out of memory\n");
166                 return (NULL);
167         }
168         r->sendsize = sendsize;
169         r->recvsize = recvsize;
170         xprt = (SVCXPRT *)mem_alloc(sizeof(SVCXPRT));
171         if (xprt == NULL) {
172                 fprintf(stderr, "svctcp_create: out of memory\n");
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         xprt_register(xprt);
182         return (xprt);
183 }
184
185 /*
186  * Like svtcp_create(), except the routine takes any *open* UNIX file
187  * descriptor as its first input.
188  */
189 SVCXPRT *
190 svcfd_create(int fd, u_int sendsize, u_int recvsize)
191 {
192
193         return (makefd_xprt(fd, sendsize, recvsize));
194 }
195
196 static SVCXPRT *
197 makefd_xprt(int fd, u_int sendsize, u_int recvsize)
198 {
199         SVCXPRT *xprt;
200         struct tcp_conn *cd;
201
202         xprt = (SVCXPRT *)mem_alloc(sizeof(SVCXPRT));
203         if (xprt == (SVCXPRT *)NULL) {
204                 fprintf(stderr, "svc_tcp: makefd_xprt: out of memory\n");
205                 goto done;
206         }
207         cd = (struct tcp_conn *)mem_alloc(sizeof(struct tcp_conn));
208         if (cd == (struct tcp_conn *)NULL) {
209                 fprintf(stderr, "svc_tcp: makefd_xprt: out of memory\n");
210                 mem_free((char *) xprt, sizeof(SVCXPRT));
211                 xprt = (SVCXPRT *)NULL;
212                 goto done;
213         }
214         cd->strm_stat = XPRT_IDLE;
215         xdrrec_create(&(cd->xdrs), sendsize, recvsize,
216             (caddr_t)xprt, readtcp, writetcp);
217         xprt->xp_p2 = NULL;
218         xprt->xp_p1 = (caddr_t)cd;
219         xprt->xp_verf.oa_base = cd->verf_body;
220         xprt->xp_addrlen = 0;
221         xprt->xp_ops = &svctcp_op;  /* truely deals with calls */
222         xprt->xp_port = 0;  /* this is a connection, not a rendezvouser */
223         xprt->xp_sock = fd;
224         xprt_register(xprt);
225     done:
226         return (xprt);
227 }
228
229 static bool_t
230 rendezvous_request(SVCXPRT *xprt)
231 {
232         int sock;
233         struct tcp_rendezvous *r;
234         struct sockaddr_in addr;
235         int len;
236         int off;
237
238         r = (struct tcp_rendezvous *)xprt->xp_p1;
239     again:
240         len = sizeof(struct sockaddr_in);
241         if ((sock = _accept(xprt->xp_sock, (struct sockaddr *)&addr,
242             &len)) < 0) {
243                 if (errno == EINTR)
244                         goto again;
245                return (FALSE);
246         }
247         /*
248          * Guard against FTP bounce attacks.
249          */
250         if (addr.sin_port == htons(20)) {
251                 _close(sock);
252                 return (FALSE);
253         }
254         /*
255          * The listening socket is in FIONBIO mode and we inherit it.
256          */
257         off = 0;
258         if (_ioctl(sock, FIONBIO, &off) < 0) {
259                 _close(sock);
260                 return (FALSE);
261         }
262         /*
263          * make a new transporter (re-uses xprt)
264          */
265         xprt = makefd_xprt(sock, r->sendsize, r->recvsize);
266         xprt->xp_raddr = addr;
267         xprt->xp_addrlen = len;
268         return (FALSE); /* there is never an rpc msg to be processed */
269 }
270
271 static enum xprt_stat
272 rendezvous_stat(void)
273 {
274
275         return (XPRT_IDLE);
276 }
277
278 static void
279 svctcp_destroy(SVCXPRT *xprt)
280 {
281         struct tcp_conn *cd = (struct tcp_conn *)xprt->xp_p1;
282
283         xprt_unregister(xprt);
284         _close(xprt->xp_sock);
285         if (xprt->xp_port != 0) {
286                 /* a rendezvouser socket */
287                 xprt->xp_port = 0;
288         } else {
289                 /* an actual connection socket */
290                 XDR_DESTROY(&(cd->xdrs));
291         }
292         mem_free((caddr_t)cd, sizeof(struct tcp_conn));
293         mem_free((caddr_t)xprt, sizeof(SVCXPRT));
294 }
295
296 /*
297  * All read operations timeout after 35 seconds.
298  * A timeout is fatal for the connection.
299  */
300 static struct timeval wait_per_try = { 35, 0 };
301
302 /*
303  * reads data from the tcp conection.
304  * any error is fatal and the connection is closed.
305  * (And a read of zero bytes is a half closed stream => error.)
306  *
307  * Note: we have to be careful here not to allow ourselves to become
308  * blocked too long in this routine. While we're waiting for data from one
309  * client, another client may be trying to connect. To avoid this situation,
310  * some code from svc_run() is transplanted here: the _select() loop checks
311  * all RPC descriptors including the one we want and calls svc_getreqset2()
312  * to handle new requests if any are detected.
313  */
314 static int
315 readtcp(SVCXPRT *xprt, caddr_t buf, int len)
316 {
317         int sock = xprt->xp_sock;
318         struct timeval start, delta, tv;
319         struct timeval tmp1, tmp2;
320         fd_set *fds;
321         extern fd_set           *__svc_fdset;
322         extern int              __svc_fdsetsize;
323
324         delta = wait_per_try;
325         fds = NULL;
326         gettimeofday(&start, NULL);
327         do {
328                 int bytes = howmany(__svc_fdsetsize, NFDBITS) *
329                                 sizeof(fd_mask);
330                 if (fds != NULL)
331                         free(fds);
332                 fds = (fd_set *)malloc(bytes);
333                 if (fds == NULL)
334                         goto fatal_err;
335                 memcpy(fds, __svc_fdset, bytes);
336
337                 /* XXX we know the other bits are still clear */
338                 FD_SET(sock, fds);
339                 tv = delta;     /* in case _select() implements writeback */
340                 switch (_select(svc_maxfd + 1, fds, NULL, NULL, &tv)) {
341                 case -1:
342                         memset(fds, 0, bytes);
343                         if (errno != EINTR)
344                                 goto fatal_err;
345                         gettimeofday(&tmp1, NULL);
346                         timersub(&tmp1, &start, &tmp2);
347                         timersub(&wait_per_try, &tmp2, &tmp1);
348                         if (tmp1.tv_sec < 0 || !timerisset(&tmp1))
349                                 goto fatal_err;
350                         delta = tmp1;
351                         continue;
352                 case 0:
353                         goto fatal_err;
354                 default:
355                         if (!FD_ISSET(sock, fds)) {
356                                 svc_getreqset2(fds, svc_maxfd + 1);
357                                 gettimeofday(&tmp1, NULL);
358                                 timersub(&tmp1, &start, &tmp2);
359                                 timersub(&wait_per_try, &tmp2, &tmp1);
360                                 if (tmp1.tv_sec < 0 || !timerisset(&tmp1))
361                                         goto fatal_err;
362                                 delta = tmp1;
363                                 continue;
364                         }
365                 }
366         } while (!FD_ISSET(sock, fds));
367         if ((len = _read(sock, buf, len)) > 0) {
368                 if (fds != NULL)
369                         free(fds);
370                 return (len);
371         }
372 fatal_err:
373         ((struct tcp_conn *)(xprt->xp_p1))->strm_stat = XPRT_DIED;
374         if (fds != NULL)
375                 free(fds);
376         return (-1);
377 }
378
379 /*
380  * writes data to the tcp connection.
381  * Any error is fatal and the connection is closed.
382  */
383 static int
384 writetcp(SVCXPRT *xprt, caddr_t buf, int len)
385 {
386         int i, cnt;
387
388         for (cnt = len; cnt > 0; cnt -= i, buf += i) {
389                 if ((i = _write(xprt->xp_sock, buf, cnt)) < 0) {
390                         ((struct tcp_conn *)(xprt->xp_p1))->strm_stat =
391                             XPRT_DIED;
392                         return (-1);
393                 }
394         }
395         return (len);
396 }
397
398 static enum xprt_stat
399 svctcp_stat(SVCXPRT *xprt)
400 {
401         struct tcp_conn *cd =
402             (struct tcp_conn *)(xprt->xp_p1);
403
404         if (cd->strm_stat == XPRT_DIED)
405                 return (XPRT_DIED);
406         if (! xdrrec_eof(&(cd->xdrs)))
407                 return (XPRT_MOREREQS);
408         return (XPRT_IDLE);
409 }
410
411 static bool_t
412 svctcp_recv(SVCXPRT *xprt, struct rpc_msg *msg)
413 {
414         struct tcp_conn *cd =
415             (struct tcp_conn *)(xprt->xp_p1);
416         XDR *xdrs = &(cd->xdrs);
417
418         xdrs->x_op = XDR_DECODE;
419         xdrrec_skiprecord(xdrs);
420         if (xdr_callmsg(xdrs, msg)) {
421                 cd->x_id = msg->rm_xid;
422                 return (TRUE);
423         }
424         cd->strm_stat = XPRT_DIED;      /* XXXX */
425         return (FALSE);
426 }
427
428 static bool_t
429 svctcp_getargs(SVCXPRT *xprt, xdrproc_t xdr_args, caddr_t args_ptr)
430 {
431
432         return ((*xdr_args)(&(((struct tcp_conn *)(xprt->xp_p1))->xdrs), args_ptr));
433 }
434
435 static bool_t
436 svctcp_freeargs(SVCXPRT *xprt, xdrproc_t xdr_args, caddr_t args_ptr)
437 {
438         XDR *xdrs =
439             &(((struct tcp_conn *)(xprt->xp_p1))->xdrs);
440
441         xdrs->x_op = XDR_FREE;
442         return ((*xdr_args)(xdrs, args_ptr));
443 }
444
445 static bool_t
446 svctcp_reply(SVCXPRT *xprt, struct rpc_msg *msg)
447 {
448         struct tcp_conn *cd =
449             (struct tcp_conn *)(xprt->xp_p1);
450         XDR *xdrs = &(cd->xdrs);
451         bool_t stat;
452
453         xdrs->x_op = XDR_ENCODE;
454         msg->rm_xid = cd->x_id;
455         stat = xdr_replymsg(xdrs, msg);
456         xdrrec_endofrecord(xdrs, TRUE);
457         return (stat);
458 }