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