OSDN Git Service

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