OSDN Git Service

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