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