OSDN Git Service

mmap/mremap/socket/rewind gone
[uclinux-h8/uClibc.git] / libc / inet / rpc / clnt_udp.c
1 /* @(#)clnt_udp.c       2.2 88/08/01 4.0 RPCSRC */
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 #if 0
31 static char sccsid[] = "@(#)clnt_udp.c 1.39 87/08/11 Copyr 1984 Sun Micro";
32 #endif
33
34 /*
35  * clnt_udp.c, Implements a UDP/IP based, client side RPC.
36  *
37  * Copyright (C) 1984, Sun Microsystems, Inc.
38  */
39
40 /* CMSG_NXTHDR is using it */
41 #define __cmsg_nxthdr __cmsg_nxthdr_internal
42
43 #define authnone_create __authnone_create
44 #define xdrmem_create __xdrmem_create
45 #define xdr_callhdr __xdr_callhdr
46 #define xdr_replymsg __xdr_replymsg
47 #define xdr_opaque_auth __xdr_opaque_auth
48 #define pmap_getport __pmap_getport
49 #define _seterr_reply __seterr_reply
50 #define setsockopt __setsockopt
51 #define bindresvport __bindresvport
52 #define recvfrom __recvfrom
53 #define sendto __sendto
54 #define recvmsg __recvmsg
55
56 #define __FORCE_GLIBC
57 #include <features.h>
58
59 #include <stdio.h>
60 #include <unistd.h>
61 #include <rpc/rpc.h>
62 #include <rpc/xdr.h>
63 #include <rpc/clnt.h>
64 #include <sys/poll.h>
65 #include <sys/socket.h>
66 #include <sys/ioctl.h>
67 #include <netdb.h>
68 #include <errno.h>
69 #include <rpc/pmap_clnt.h>
70 #include <net/if.h>
71 #ifdef USE_IN_LIBIO
72 # include <wchar.h>
73 #endif
74
75 #ifdef IP_RECVERR
76 #include "errqueue.h"
77 #include <sys/uio.h>
78 #endif
79
80 extern u_long _create_xid (void) attribute_hidden;
81
82 /*
83  * UDP bases client side rpc operations
84  */
85 static enum clnt_stat clntudp_call (CLIENT *, u_long, xdrproc_t, caddr_t,
86                                     xdrproc_t, caddr_t, struct timeval);
87 static void clntudp_abort (void);
88 static void clntudp_geterr (CLIENT *, struct rpc_err *);
89 static bool_t clntudp_freeres (CLIENT *, xdrproc_t, caddr_t);
90 static bool_t clntudp_control (CLIENT *, int, char *);
91 static void clntudp_destroy (CLIENT *);
92
93 static struct clnt_ops udp_ops =
94 {
95   clntudp_call,
96   clntudp_abort,
97   clntudp_geterr,
98   clntudp_freeres,
99   clntudp_destroy,
100   clntudp_control
101 };
102
103 /*
104  * Private data kept per client handle
105  */
106 struct cu_data
107   {
108     int cu_sock;
109     bool_t cu_closeit;
110     struct sockaddr_in cu_raddr;
111     int cu_rlen;
112     struct timeval cu_wait;
113     struct timeval cu_total;
114     struct rpc_err cu_error;
115     XDR cu_outxdrs;
116     u_int cu_xdrpos;
117     u_int cu_sendsz;
118     char *cu_outbuf;
119     u_int cu_recvsz;
120     char cu_inbuf[1];
121   };
122
123 /*
124  * Create a UDP based client handle.
125  * If *sockp<0, *sockp is set to a newly created UPD socket.
126  * If raddr->sin_port is 0 a binder on the remote machine
127  * is consulted for the correct port number.
128  * NB: It is the clients responsibility to close *sockp.
129  * NB: The rpch->cl_auth is initialized to null authentication.
130  *     Caller may wish to set this something more useful.
131  *
132  * wait is the amount of time used between retransmitting a call if
133  * no response has been heard; retransmission occurs until the actual
134  * rpc call times out.
135  *
136  * sendsz and recvsz are the maximum allowable packet sizes that can be
137  * sent and received.
138  */
139 CLIENT attribute_hidden *
140 __clntudp_bufcreate (struct sockaddr_in *raddr, u_long program, u_long version,
141                    struct timeval wait, int *sockp, u_int sendsz,
142                    u_int recvsz)
143 {
144   CLIENT *cl;
145   struct cu_data *cu = NULL;
146   struct rpc_msg call_msg;
147
148   cl = (CLIENT *) mem_alloc (sizeof (CLIENT));
149   sendsz = ((sendsz + 3) / 4) * 4;
150   recvsz = ((recvsz + 3) / 4) * 4;
151   cu = (struct cu_data *) mem_alloc (sizeof (*cu) + sendsz + recvsz);
152   if (cl == NULL || cu == NULL)
153     {
154       struct rpc_createerr *ce = &get_rpc_createerr ();
155 #ifdef USE_IN_LIBIO
156       if (_IO_fwide (stderr, 0) > 0)
157         (void) __fwprintf (stderr, L"%s",
158                            _("clntudp_create: out of memory\n"));
159       else
160 #endif
161         (void) fputs (_("clntudp_create: out of memory\n"), stderr);
162       ce->cf_stat = RPC_SYSTEMERROR;
163       ce->cf_error.re_errno = ENOMEM;
164       goto fooy;
165     }
166   cu->cu_outbuf = &cu->cu_inbuf[recvsz];
167
168   if (raddr->sin_port == 0)
169     {
170       u_short port;
171       if ((port =
172            pmap_getport (raddr, program, version, IPPROTO_UDP)) == 0)
173         {
174           goto fooy;
175         }
176       raddr->sin_port = htons (port);
177     }
178   cl->cl_ops = &udp_ops;
179   cl->cl_private = (caddr_t) cu;
180   cu->cu_raddr = *raddr;
181   cu->cu_rlen = sizeof (cu->cu_raddr);
182   cu->cu_wait = wait;
183   cu->cu_total.tv_sec = -1;
184   cu->cu_total.tv_usec = -1;
185   cu->cu_sendsz = sendsz;
186   cu->cu_recvsz = recvsz;
187   call_msg.rm_xid = _create_xid ();
188   call_msg.rm_direction = CALL;
189   call_msg.rm_call.cb_rpcvers = RPC_MSG_VERSION;
190   call_msg.rm_call.cb_prog = program;
191   call_msg.rm_call.cb_vers = version;
192   xdrmem_create (&(cu->cu_outxdrs), cu->cu_outbuf,
193                  sendsz, XDR_ENCODE);
194   if (!xdr_callhdr (&(cu->cu_outxdrs), &call_msg))
195     {
196       goto fooy;
197     }
198   cu->cu_xdrpos = XDR_GETPOS (&(cu->cu_outxdrs));
199   if (*sockp < 0)
200     {
201       int dontblock = 1;
202
203       *sockp = __socket (AF_INET, SOCK_DGRAM, IPPROTO_UDP);
204       if (*sockp < 0)
205         {
206           struct rpc_createerr *ce = &get_rpc_createerr ();
207           ce->cf_stat = RPC_SYSTEMERROR;
208           ce->cf_error.re_errno = errno;
209           goto fooy;
210         }
211       /* attempt to bind to prov port */
212       (void) bindresvport (*sockp, (struct sockaddr_in *) 0);
213       /* the sockets rpc controls are non-blocking */
214       (void) __ioctl (*sockp, FIONBIO, (char *) &dontblock);
215 #ifdef IP_RECVERR
216       {
217         int on = 1;
218         setsockopt(*sockp, SOL_IP, IP_RECVERR, &on, sizeof(on));
219       }
220 #endif
221       cu->cu_closeit = TRUE;
222     }
223   else
224     {
225       cu->cu_closeit = FALSE;
226     }
227   cu->cu_sock = *sockp;
228   cl->cl_auth = authnone_create ();
229   return cl;
230 fooy:
231   if (cu)
232     mem_free ((caddr_t) cu, sizeof (*cu) + sendsz + recvsz);
233   if (cl)
234     mem_free ((caddr_t) cl, sizeof (CLIENT));
235   return (CLIENT *) NULL;
236 }
237 strong_alias(__clntudp_bufcreate,clntudp_bufcreate)
238
239 CLIENT attribute_hidden *
240 __clntudp_create (struct sockaddr_in *raddr, u_long program, u_long version, struct timeval wait, int *sockp)
241 {
242
243   return __clntudp_bufcreate (raddr, program, version, wait, sockp,
244                             UDPMSGSIZE, UDPMSGSIZE);
245 }
246 strong_alias(__clntudp_create,clntudp_create)
247
248 static int
249 is_network_up (int sock)
250 {
251   struct ifconf ifc;
252   char buf[UDPMSGSIZE];
253   struct ifreq ifreq, *ifr;
254   int n;
255
256   ifc.ifc_len = sizeof (buf);
257   ifc.ifc_buf = buf;
258   if (__ioctl(sock, SIOCGIFCONF, (char *) &ifc) == 0)
259     {
260       ifr = ifc.ifc_req;
261       for (n = ifc.ifc_len / sizeof (struct ifreq); n > 0; n--, ifr++)
262         {
263           ifreq = *ifr;
264           if (__ioctl (sock, SIOCGIFFLAGS, (char *) &ifreq) < 0)
265             break;
266
267           if ((ifreq.ifr_flags & IFF_UP)
268               && ifr->ifr_addr.sa_family == AF_INET)
269             return 1;
270         }
271     }
272   return 0;
273 }
274
275 static enum clnt_stat
276 clntudp_call (cl, proc, xargs, argsp, xresults, resultsp, utimeout)
277      CLIENT *cl;        /* client handle */
278      u_long proc;               /* procedure number */
279      xdrproc_t xargs;           /* xdr routine for args */
280      caddr_t argsp;             /* pointer to args */
281      xdrproc_t xresults;        /* xdr routine for results */
282      caddr_t resultsp;          /* pointer to results */
283      struct timeval utimeout;   /* seconds to wait before giving up */
284 {
285   struct cu_data *cu = (struct cu_data *) cl->cl_private;
286   XDR *xdrs;
287   int outlen = 0;
288   int inlen;
289   socklen_t fromlen;
290   struct pollfd fd;
291   int milliseconds = (cu->cu_wait.tv_sec * 1000) +
292     (cu->cu_wait.tv_usec / 1000);
293   struct sockaddr_in from;
294   struct rpc_msg reply_msg;
295   XDR reply_xdrs;
296   struct timeval time_waited;
297   bool_t ok;
298   int nrefreshes = 2;           /* number of times to refresh cred */
299   struct timeval timeout;
300   int anyup;                    /* any network interface up */
301
302   if (cu->cu_total.tv_usec == -1)
303     {
304       timeout = utimeout;       /* use supplied timeout */
305     }
306   else
307     {
308       timeout = cu->cu_total;   /* use default timeout */
309     }
310
311   time_waited.tv_sec = 0;
312   time_waited.tv_usec = 0;
313 call_again:
314   xdrs = &(cu->cu_outxdrs);
315   if (xargs == NULL)
316     goto get_reply;
317   xdrs->x_op = XDR_ENCODE;
318   XDR_SETPOS (xdrs, cu->cu_xdrpos);
319   /*
320    * the transaction is the first thing in the out buffer
321    */
322   (*(uint32_t *) (cu->cu_outbuf))++;
323   if ((!XDR_PUTLONG (xdrs, (long *) &proc)) ||
324       (!AUTH_MARSHALL (cl->cl_auth, xdrs)) ||
325       (!(*xargs) (xdrs, argsp)))
326     return (cu->cu_error.re_status = RPC_CANTENCODEARGS);
327   outlen = (int) XDR_GETPOS (xdrs);
328
329 send_again:
330   if (sendto (cu->cu_sock, cu->cu_outbuf, outlen, 0,
331               (struct sockaddr *) &(cu->cu_raddr), cu->cu_rlen)
332       != outlen)
333     {
334       cu->cu_error.re_errno = errno;
335       return (cu->cu_error.re_status = RPC_CANTSEND);
336     }
337
338   /*
339    * Hack to provide rpc-based message passing
340    */
341   if (timeout.tv_sec == 0 && timeout.tv_usec == 0)
342     {
343       return (cu->cu_error.re_status = RPC_TIMEDOUT);
344     }
345  get_reply:
346   /*
347    * sub-optimal code appears here because we have
348    * some clock time to spare while the packets are in flight.
349    * (We assume that this is actually only executed once.)
350    */
351   reply_msg.acpted_rply.ar_verf = _null_auth;
352   reply_msg.acpted_rply.ar_results.where = resultsp;
353   reply_msg.acpted_rply.ar_results.proc = xresults;
354   fd.fd = cu->cu_sock;
355   fd.events = POLLIN;
356   anyup = 0;
357   for (;;)
358     {
359       switch (poll (&fd, 1, milliseconds))
360         {
361
362         case 0:
363           if (anyup == 0)
364             {
365               anyup = is_network_up (cu->cu_sock);
366               if (!anyup)
367                 return (cu->cu_error.re_status = RPC_CANTRECV);
368             }
369
370           time_waited.tv_sec += cu->cu_wait.tv_sec;
371           time_waited.tv_usec += cu->cu_wait.tv_usec;
372           while (time_waited.tv_usec >= 1000000)
373             {
374               time_waited.tv_sec++;
375               time_waited.tv_usec -= 1000000;
376             }
377           if ((time_waited.tv_sec < timeout.tv_sec) ||
378               ((time_waited.tv_sec == timeout.tv_sec) &&
379                (time_waited.tv_usec < timeout.tv_usec)))
380             goto send_again;
381           return (cu->cu_error.re_status = RPC_TIMEDOUT);
382
383           /*
384            * buggy in other cases because time_waited is not being
385            * updated.
386            */
387         case -1:
388           if (errno == EINTR)
389             continue;
390           cu->cu_error.re_errno = errno;
391           return (cu->cu_error.re_status = RPC_CANTRECV);
392         }
393 #ifdef IP_RECVERR
394       if (fd.revents & POLLERR)
395         {
396           struct msghdr msg;
397           struct cmsghdr *cmsg;
398           struct sock_extended_err *e;
399           struct sockaddr_in err_addr;
400           struct iovec iov;
401           char *cbuf = (char *) alloca (outlen + 256);
402           int ret;
403
404           iov.iov_base = cbuf + 256;
405           iov.iov_len = outlen;
406           msg.msg_name = (void *) &err_addr;
407           msg.msg_namelen = sizeof (err_addr);
408           msg.msg_iov = &iov;
409           msg.msg_iovlen = 1;
410           msg.msg_flags = 0;
411           msg.msg_control = cbuf;
412           msg.msg_controllen = 256;
413           ret = recvmsg (cu->cu_sock, &msg, MSG_ERRQUEUE);
414           if (ret >= 0
415               && __memcmp (cbuf + 256, cu->cu_outbuf, ret) == 0
416               && (msg.msg_flags & MSG_ERRQUEUE)
417               && ((msg.msg_namelen == 0
418                    && ret >= 12)
419                   || (msg.msg_namelen == sizeof (err_addr)
420                       && err_addr.sin_family == AF_INET
421                       && __memcmp (&err_addr.sin_addr, &cu->cu_raddr.sin_addr,
422                                  sizeof (err_addr.sin_addr)) == 0
423                       && err_addr.sin_port == cu->cu_raddr.sin_port)))
424             for (cmsg = CMSG_FIRSTHDR (&msg); cmsg;
425                  cmsg = CMSG_NXTHDR (&msg, cmsg))
426               if (cmsg->cmsg_level == SOL_IP && cmsg->cmsg_type == IP_RECVERR)
427                 {
428                   e = (struct sock_extended_err *) CMSG_DATA(cmsg);
429                   cu->cu_error.re_errno = e->ee_errno;
430                   return (cu->cu_error.re_status = RPC_CANTRECV);
431                 }
432         }
433 #endif
434       do
435         {
436           fromlen = sizeof (struct sockaddr);
437           inlen = recvfrom (cu->cu_sock, cu->cu_inbuf,
438                             (int) cu->cu_recvsz, 0,
439                             (struct sockaddr *) &from, &fromlen);
440         }
441       while (inlen < 0 && errno == EINTR);
442       if (inlen < 0)
443         {
444           if (errno == EWOULDBLOCK)
445             continue;
446           cu->cu_error.re_errno = errno;
447           return (cu->cu_error.re_status = RPC_CANTRECV);
448         }
449       if (inlen < 4)
450         continue;
451
452       /* see if reply transaction id matches sent id.
453         Don't do this if we only wait for a replay */
454       if (xargs != NULL
455           && (*((u_int32_t *) (cu->cu_inbuf))
456               != *((u_int32_t *) (cu->cu_outbuf))))
457         continue;
458       /* we now assume we have the proper reply */
459       break;
460     }
461
462   /*
463    * now decode and validate the response
464    */
465   xdrmem_create (&reply_xdrs, cu->cu_inbuf, (u_int) inlen, XDR_DECODE);
466   ok = xdr_replymsg (&reply_xdrs, &reply_msg);
467   /* XDR_DESTROY(&reply_xdrs);  save a few cycles on noop destroy */
468   if (ok)
469     {
470       _seterr_reply (&reply_msg, &(cu->cu_error));
471       if (cu->cu_error.re_status == RPC_SUCCESS)
472         {
473           if (!AUTH_VALIDATE (cl->cl_auth,
474                               &reply_msg.acpted_rply.ar_verf))
475             {
476               cu->cu_error.re_status = RPC_AUTHERROR;
477               cu->cu_error.re_why = AUTH_INVALIDRESP;
478             }
479           if (reply_msg.acpted_rply.ar_verf.oa_base != NULL)
480             {
481               xdrs->x_op = XDR_FREE;
482               (void) xdr_opaque_auth (xdrs,
483                                       &(reply_msg.acpted_rply.ar_verf));
484             }
485         }                       /* end successful completion */
486       else
487         {
488           /* maybe our credentials need to be refreshed ... */
489           if (nrefreshes > 0 && AUTH_REFRESH (cl->cl_auth))
490             {
491               nrefreshes--;
492               goto call_again;
493             }
494         }                       /* end of unsuccessful completion */
495     }                           /* end of valid reply message */
496   else
497     {
498       cu->cu_error.re_status = RPC_CANTDECODERES;
499     }
500   return cu->cu_error.re_status;
501 }
502
503 static void
504 clntudp_geterr (CLIENT *cl, struct rpc_err *errp)
505 {
506   struct cu_data *cu = (struct cu_data *) cl->cl_private;
507
508   *errp = cu->cu_error;
509 }
510
511
512 static bool_t
513 clntudp_freeres (CLIENT *cl, xdrproc_t xdr_res, caddr_t res_ptr)
514 {
515   struct cu_data *cu = (struct cu_data *) cl->cl_private;
516   XDR *xdrs = &(cu->cu_outxdrs);
517
518   xdrs->x_op = XDR_FREE;
519   return (*xdr_res) (xdrs, res_ptr);
520 }
521
522 static void
523 clntudp_abort (void)
524 {
525 }
526
527 static bool_t
528 clntudp_control (CLIENT *cl, int request, char *info)
529 {
530   struct cu_data *cu = (struct cu_data *) cl->cl_private;
531
532   switch (request)
533     {
534     case CLSET_FD_CLOSE:
535       cu->cu_closeit = TRUE;
536       break;
537     case CLSET_FD_NCLOSE:
538       cu->cu_closeit = FALSE;
539       break;
540     case CLSET_TIMEOUT:
541       cu->cu_total = *(struct timeval *) info;
542       break;
543     case CLGET_TIMEOUT:
544       *(struct timeval *) info = cu->cu_total;
545       break;
546     case CLSET_RETRY_TIMEOUT:
547       cu->cu_wait = *(struct timeval *) info;
548       break;
549     case CLGET_RETRY_TIMEOUT:
550       *(struct timeval *) info = cu->cu_wait;
551       break;
552     case CLGET_SERVER_ADDR:
553       *(struct sockaddr_in *) info = cu->cu_raddr;
554       break;
555     case CLGET_FD:
556       *(int *)info = cu->cu_sock;
557       break;
558     case CLGET_XID:
559       /*
560        * use the knowledge that xid is the
561        * first element in the call structure *.
562        * This will get the xid of the PREVIOUS call
563        */
564       *(u_long *)info = ntohl(*(u_long *)cu->cu_outbuf);
565       break;
566     case CLSET_XID:
567       /* This will set the xid of the NEXT call */
568       *(u_long *)cu->cu_outbuf =  htonl(*(u_long *)info - 1);
569       /* decrement by 1 as clntudp_call() increments once */
570     case CLGET_VERS:
571       /*
572        * This RELIES on the information that, in the call body,
573        * the version number field is the fifth field from the
574        * begining of the RPC header. MUST be changed if the
575        * call_struct is changed
576        */
577       *(u_long *)info = ntohl(*(u_long *)(cu->cu_outbuf +
578                                           4 * BYTES_PER_XDR_UNIT));
579       break;
580     case CLSET_VERS:
581       *(u_long *)(cu->cu_outbuf + 4 * BYTES_PER_XDR_UNIT)
582         = htonl(*(u_long *)info);
583       break;
584     case CLGET_PROG:
585       /*
586        * This RELIES on the information that, in the call body,
587        * the program number field is the  field from the
588        * begining of the RPC header. MUST be changed if the
589        * call_struct is changed
590        */
591       *(u_long *)info = ntohl(*(u_long *)(cu->cu_outbuf +
592                                           3 * BYTES_PER_XDR_UNIT));
593       break;
594     case CLSET_PROG:
595       *(u_long *)(cu->cu_outbuf + 3 * BYTES_PER_XDR_UNIT)
596         = htonl(*(u_long *)info);
597       break;
598     /* The following are only possible with TI-RPC */
599     case CLGET_SVC_ADDR:
600     case CLSET_SVC_ADDR:
601     case CLSET_PUSH_TIMOD:
602     case CLSET_POP_TIMOD:
603     default:
604       return FALSE;
605     }
606   return TRUE;
607 }
608
609 static void
610 clntudp_destroy (CLIENT *cl)
611 {
612   struct cu_data *cu = (struct cu_data *) cl->cl_private;
613
614   if (cu->cu_closeit)
615     {
616       (void) __close (cu->cu_sock);
617     }
618   XDR_DESTROY (&(cu->cu_outxdrs));
619   mem_free ((caddr_t) cu, (sizeof (*cu) + cu->cu_sendsz + cu->cu_recvsz));
620   mem_free ((caddr_t) cl, sizeof (CLIENT));
621 }