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