OSDN Git Service

4221eff63b4709a9a81b81a22710b3b0c9aa7f56
[uclinux-h8/uClibc.git] / libc / inet / rpc / clnt_tcp.c
1 /* @(#)clnt_tcp.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_tcp.c 1.37 87/10/05 Copyr 1984 Sun Micro";
32 #endif
33
34 /*
35  * clnt_tcp.c, Implements a TCP/IP based, client side RPC.
36  *
37  * Copyright (C) 1984, Sun Microsystems, Inc.
38  *
39  * TCP based RPC supports 'batched calls'.
40  * A sequence of calls may be batched-up in a send buffer.  The rpc call
41  * return immediately to the client even though the call was not necessarily
42  * sent.  The batching occurs if the results' xdr routine is NULL (0) AND
43  * the rpc timeout value is zero (see clnt.h, rpc).
44  *
45  * Clients should NOT casually batch calls that in fact return results; that is,
46  * the server side should be aware that a call is batched and not produce any
47  * return message.  Batched calls that produce many result messages can
48  * deadlock (netlock) the client and the server....
49  *
50  * Now go hang yourself.
51  */
52
53 #define authnone_create __authnone_create
54 #define xdrrec_create __xdrrec_create
55 #define xdrrec_endofrecord __xdrrec_endofrecord
56 #define xdrrec_skiprecord __xdrrec_skiprecord
57 #define xdr_callhdr __xdr_callhdr
58 #define xdr_replymsg __xdr_replymsg
59 #define xdr_opaque_auth __xdr_opaque_auth
60 #define xdrmem_create __xdrmem_create
61 #define pmap_getport __pmap_getport
62
63 #define __FORCE_GLIBC
64 #include <features.h>
65
66 #include <netdb.h>
67 #include <errno.h>
68 #include <stdio.h>
69 #include <unistd.h>
70 #include <rpc/rpc.h>
71 #include <sys/poll.h>
72 #include <sys/socket.h>
73 #include <rpc/pmap_clnt.h>
74 #ifdef USE_IN_LIBIO
75 # include <wchar.h>
76 #endif
77
78 extern u_long _create_xid (void) attribute_hidden;
79
80 #define MCALL_MSG_SIZE 24
81
82 struct ct_data
83   {
84     int ct_sock;
85     bool_t ct_closeit;
86     struct timeval ct_wait;
87     bool_t ct_waitset;          /* wait set by clnt_control? */
88     struct sockaddr_in ct_addr;
89     struct rpc_err ct_error;
90     char ct_mcall[MCALL_MSG_SIZE];      /* marshalled callmsg */
91     u_int ct_mpos;              /* pos after marshal */
92     XDR ct_xdrs;
93   };
94
95 static int readtcp (char *, char *, int);
96 static int writetcp (char *, char *, int);
97
98 static enum clnt_stat clnttcp_call (CLIENT *, u_long, xdrproc_t, caddr_t,
99                                     xdrproc_t, caddr_t, struct timeval);
100 static void clnttcp_abort (void);
101 static void clnttcp_geterr (CLIENT *, struct rpc_err *);
102 static bool_t clnttcp_freeres (CLIENT *, xdrproc_t, caddr_t);
103 static bool_t clnttcp_control (CLIENT *, int, char *);
104 static void clnttcp_destroy (CLIENT *);
105
106 static struct clnt_ops tcp_ops =
107 {
108   clnttcp_call,
109   clnttcp_abort,
110   clnttcp_geterr,
111   clnttcp_freeres,
112   clnttcp_destroy,
113   clnttcp_control
114 };
115
116 /*
117  * Create a client handle for a tcp/ip connection.
118  * If *sockp<0, *sockp is set to a newly created TCP socket and it is
119  * connected to raddr.  If *sockp non-negative then
120  * raddr is ignored.  The rpc/tcp package does buffering
121  * similar to stdio, so the client must pick send and receive buffer sizes,];
122  * 0 => use the default.
123  * If raddr->sin_port is 0, then a binder on the remote machine is
124  * consulted for the right port number.
125  * NB: *sockp is copied into a private area.
126  * NB: It is the clients responsibility to close *sockp.
127  * NB: The rpch->cl_auth is set null authentication.  Caller may wish to set this
128  * something more useful.
129  */
130 CLIENT attribute_hidden *
131 __clnttcp_create (struct sockaddr_in *raddr, u_long prog, u_long vers,
132                 int *sockp, u_int sendsz, u_int recvsz)
133 {
134   CLIENT *h;
135   struct ct_data *ct;
136   struct rpc_msg call_msg;
137
138   h = (CLIENT *) mem_alloc (sizeof (*h));
139   ct = (struct ct_data *) mem_alloc (sizeof (*ct));
140   if (h == NULL || ct == NULL)
141     {
142       struct rpc_createerr *ce = &get_rpc_createerr ();
143 #ifdef USE_IN_LIBIO
144       if (_IO_fwide (stderr, 0) > 0)
145         (void) __fwprintf (stderr, L"%s",
146                            _("clnttcp_create: out of memory\n"));
147       else
148 #endif
149         (void) fputs (_("clnttcp_create: out of memory\n"), stderr);
150       ce->cf_stat = RPC_SYSTEMERROR;
151       ce->cf_error.re_errno = ENOMEM;
152       goto fooy;
153     }
154
155   /*
156    * If no port number given ask the pmap for one
157    */
158   if (raddr->sin_port == 0)
159     {
160       u_short port;
161       if ((port = pmap_getport (raddr, prog, vers, IPPROTO_TCP)) == 0)
162         {
163           mem_free ((caddr_t) ct, sizeof (struct ct_data));
164           mem_free ((caddr_t) h, sizeof (CLIENT));
165           return ((CLIENT *) NULL);
166         }
167       raddr->sin_port = htons (port);
168     }
169
170   /*
171    * If no socket given, open one
172    */
173   if (*sockp < 0)
174     {
175       *sockp = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
176       (void) bindresvport (*sockp, (struct sockaddr_in *) 0);
177       if ((*sockp < 0)
178           || (connect (*sockp, (struct sockaddr *) raddr,
179                          sizeof (*raddr)) < 0))
180         {
181           struct rpc_createerr *ce = &get_rpc_createerr ();
182           ce->cf_stat = RPC_SYSTEMERROR;
183           ce->cf_error.re_errno = errno;
184           if (*sockp >= 0)
185             (void) __close (*sockp);
186           goto fooy;
187         }
188       ct->ct_closeit = TRUE;
189     }
190   else
191     {
192       ct->ct_closeit = FALSE;
193     }
194
195   /*
196    * Set up private data struct
197    */
198   ct->ct_sock = *sockp;
199   ct->ct_wait.tv_usec = 0;
200   ct->ct_waitset = FALSE;
201   ct->ct_addr = *raddr;
202
203   /*
204    * Initialize call message
205    */
206   call_msg.rm_xid = _create_xid ();
207   call_msg.rm_direction = CALL;
208   call_msg.rm_call.cb_rpcvers = RPC_MSG_VERSION;
209   call_msg.rm_call.cb_prog = prog;
210   call_msg.rm_call.cb_vers = vers;
211
212   /*
213    * pre-serialize the static part of the call msg and stash it away
214    */
215   xdrmem_create (&(ct->ct_xdrs), ct->ct_mcall, MCALL_MSG_SIZE,
216                  XDR_ENCODE);
217   if (!xdr_callhdr (&(ct->ct_xdrs), &call_msg))
218     {
219       if (ct->ct_closeit)
220         {
221           (void) __close (*sockp);
222         }
223       goto fooy;
224     }
225   ct->ct_mpos = XDR_GETPOS (&(ct->ct_xdrs));
226   XDR_DESTROY (&(ct->ct_xdrs));
227
228   /*
229    * Create a client handle which uses xdrrec for serialization
230    * and authnone for authentication.
231    */
232   xdrrec_create (&(ct->ct_xdrs), sendsz, recvsz,
233                  (caddr_t) ct, readtcp, writetcp);
234   h->cl_ops = &tcp_ops;
235   h->cl_private = (caddr_t) ct;
236   h->cl_auth = authnone_create ();
237   return h;
238
239 fooy:
240   /*
241    * Something goofed, free stuff and barf
242    */
243   mem_free ((caddr_t) ct, sizeof (struct ct_data));
244   mem_free ((caddr_t) h, sizeof (CLIENT));
245   return ((CLIENT *) NULL);
246 }
247 strong_alias(__clnttcp_create,clnttcp_create)
248
249 static enum clnt_stat
250 clnttcp_call (h, proc, xdr_args, args_ptr, xdr_results, results_ptr, timeout)
251      CLIENT *h;
252      u_long proc;
253      xdrproc_t xdr_args;
254      caddr_t args_ptr;
255      xdrproc_t xdr_results;
256      caddr_t results_ptr;
257      struct timeval timeout;
258 {
259   struct ct_data *ct = (struct ct_data *) h->cl_private;
260   XDR *xdrs = &(ct->ct_xdrs);
261   struct rpc_msg reply_msg;
262   u_long x_id;
263   u_int32_t *msg_x_id = (u_int32_t *) (ct->ct_mcall);   /* yuk */
264   bool_t shipnow;
265   int refreshes = 2;
266
267   if (!ct->ct_waitset)
268     {
269       ct->ct_wait = timeout;
270     }
271
272   shipnow =
273     (xdr_results == (xdrproc_t) 0 && ct->ct_wait.tv_sec == 0
274      && ct->ct_wait.tv_usec == 0) ? FALSE : TRUE;
275
276 call_again:
277   xdrs->x_op = XDR_ENCODE;
278   ct->ct_error.re_status = RPC_SUCCESS;
279   x_id = ntohl (--(*msg_x_id));
280   if ((!XDR_PUTBYTES (xdrs, ct->ct_mcall, ct->ct_mpos)) ||
281       (!XDR_PUTLONG (xdrs, (long *) &proc)) ||
282       (!AUTH_MARSHALL (h->cl_auth, xdrs)) ||
283       (!(*xdr_args) (xdrs, args_ptr)))
284     {
285       if (ct->ct_error.re_status == RPC_SUCCESS)
286         ct->ct_error.re_status = RPC_CANTENCODEARGS;
287       (void) xdrrec_endofrecord (xdrs, TRUE);
288       return (ct->ct_error.re_status);
289     }
290   if (!xdrrec_endofrecord (xdrs, shipnow))
291     return ct->ct_error.re_status = RPC_CANTSEND;
292   if (!shipnow)
293     return RPC_SUCCESS;
294   /*
295    * Hack to provide rpc-based message passing
296    */
297   if (ct->ct_wait.tv_sec == 0 && ct->ct_wait.tv_usec == 0)
298     {
299       return ct->ct_error.re_status = RPC_TIMEDOUT;
300     }
301
302
303   /*
304    * Keep receiving until we get a valid transaction id
305    */
306   xdrs->x_op = XDR_DECODE;
307   while (TRUE)
308     {
309       reply_msg.acpted_rply.ar_verf = _null_auth;
310       reply_msg.acpted_rply.ar_results.where = NULL;
311       reply_msg.acpted_rply.ar_results.proc = (xdrproc_t)xdr_void;
312       if (!xdrrec_skiprecord (xdrs))
313         return (ct->ct_error.re_status);
314       /* now decode and validate the response header */
315       if (!xdr_replymsg (xdrs, &reply_msg))
316         {
317           if (ct->ct_error.re_status == RPC_SUCCESS)
318             continue;
319           return ct->ct_error.re_status;
320         }
321       if ((u_int32_t) reply_msg.rm_xid == (u_int32_t) x_id)
322         break;
323     }
324
325   /*
326    * process header
327    */
328   _seterr_reply (&reply_msg, &(ct->ct_error));
329   if (ct->ct_error.re_status == RPC_SUCCESS)
330     {
331       if (!AUTH_VALIDATE (h->cl_auth, &reply_msg.acpted_rply.ar_verf))
332         {
333           ct->ct_error.re_status = RPC_AUTHERROR;
334           ct->ct_error.re_why = AUTH_INVALIDRESP;
335         }
336       else if (!(*xdr_results) (xdrs, results_ptr))
337         {
338           if (ct->ct_error.re_status == RPC_SUCCESS)
339             ct->ct_error.re_status = RPC_CANTDECODERES;
340         }
341       /* free verifier ... */
342       if (reply_msg.acpted_rply.ar_verf.oa_base != NULL)
343         {
344           xdrs->x_op = XDR_FREE;
345           (void) xdr_opaque_auth (xdrs, &(reply_msg.acpted_rply.ar_verf));
346         }
347     }                           /* end successful completion */
348   else
349     {
350       /* maybe our credentials need to be refreshed ... */
351       if (refreshes-- && AUTH_REFRESH (h->cl_auth))
352         goto call_again;
353     }                           /* end of unsuccessful completion */
354   return ct->ct_error.re_status;
355 }
356
357 static void
358 clnttcp_geterr (h, errp)
359      CLIENT *h;
360      struct rpc_err *errp;
361 {
362   struct ct_data *ct =
363   (struct ct_data *) h->cl_private;
364
365   *errp = ct->ct_error;
366 }
367
368 static bool_t
369 clnttcp_freeres (cl, xdr_res, res_ptr)
370      CLIENT *cl;
371      xdrproc_t xdr_res;
372      caddr_t res_ptr;
373 {
374   struct ct_data *ct = (struct ct_data *) cl->cl_private;
375   XDR *xdrs = &(ct->ct_xdrs);
376
377   xdrs->x_op = XDR_FREE;
378   return (*xdr_res) (xdrs, res_ptr);
379 }
380
381 static void
382 clnttcp_abort ()
383 {
384 }
385
386 static bool_t
387 clnttcp_control (CLIENT *cl, int request, char *info)
388 {
389   struct ct_data *ct = (struct ct_data *) cl->cl_private;
390
391
392   switch (request)
393     {
394     case CLSET_FD_CLOSE:
395       ct->ct_closeit = TRUE;
396       break;
397     case CLSET_FD_NCLOSE:
398       ct->ct_closeit = FALSE;
399       break;
400     case CLSET_TIMEOUT:
401       ct->ct_wait = *(struct timeval *) info;
402       ct->ct_waitset = TRUE;
403       break;
404     case CLGET_TIMEOUT:
405       *(struct timeval *) info = ct->ct_wait;
406       break;
407     case CLGET_SERVER_ADDR:
408       *(struct sockaddr_in *) info = ct->ct_addr;
409       break;
410     case CLGET_FD:
411       *(int *)info = ct->ct_sock;
412       break;
413     case CLGET_XID:
414       /*
415        * use the knowledge that xid is the
416        * first element in the call structure *.
417        * This will get the xid of the PREVIOUS call
418        */
419       *(u_long *)info = ntohl (*(u_long *)ct->ct_mcall);
420       break;
421     case CLSET_XID:
422       /* This will set the xid of the NEXT call */
423       *(u_long *)ct->ct_mcall =  htonl (*(u_long *)info - 1);
424       /* decrement by 1 as clnttcp_call() increments once */
425     case CLGET_VERS:
426       /*
427        * This RELIES on the information that, in the call body,
428        * the version number field is the fifth field from the
429        * begining of the RPC header. MUST be changed if the
430        * call_struct is changed
431        */
432       *(u_long *)info = ntohl (*(u_long *)(ct->ct_mcall +
433                                            4 * BYTES_PER_XDR_UNIT));
434       break;
435     case CLSET_VERS:
436       *(u_long *)(ct->ct_mcall + 4 * BYTES_PER_XDR_UNIT)
437         = htonl (*(u_long *)info);
438       break;
439     case CLGET_PROG:
440       /*
441        * This RELIES on the information that, in the call body,
442        * the program number field is the  field from the
443        * begining of the RPC header. MUST be changed if the
444        * call_struct is changed
445        */
446       *(u_long *)info = ntohl(*(u_long *)(ct->ct_mcall +
447                                           3 * BYTES_PER_XDR_UNIT));
448       break;
449     case CLSET_PROG:
450       *(u_long *)(ct->ct_mcall + 3 * BYTES_PER_XDR_UNIT)
451         = htonl(*(u_long *)info);
452       break;
453     /* The following are only possible with TI-RPC */
454     case CLGET_RETRY_TIMEOUT:
455     case CLSET_RETRY_TIMEOUT:
456     case CLGET_SVC_ADDR:
457     case CLSET_SVC_ADDR:
458     case CLSET_PUSH_TIMOD:
459     case CLSET_POP_TIMOD:
460     default:
461       return FALSE;
462     }
463   return TRUE;
464 }
465
466
467 static void
468 clnttcp_destroy (CLIENT *h)
469 {
470   struct ct_data *ct =
471   (struct ct_data *) h->cl_private;
472
473   if (ct->ct_closeit)
474     {
475       (void) __close (ct->ct_sock);
476     }
477   XDR_DESTROY (&(ct->ct_xdrs));
478   mem_free ((caddr_t) ct, sizeof (struct ct_data));
479   mem_free ((caddr_t) h, sizeof (CLIENT));
480 }
481
482 /*
483  * Interface between xdr serializer and tcp connection.
484  * Behaves like the system calls, read & write, but keeps some error state
485  * around for the rpc level.
486  */
487 static int
488 readtcp (char *ctptr, char *buf, int len)
489 {
490   struct ct_data *ct = (struct ct_data *)ctptr;
491   struct pollfd fd;
492   int milliseconds = (ct->ct_wait.tv_sec * 1000) +
493     (ct->ct_wait.tv_usec / 1000);
494
495   if (len == 0)
496     return 0;
497
498   fd.fd = ct->ct_sock;
499   fd.events = POLLIN;
500   while (TRUE)
501     {
502       switch (poll(&fd, 1, milliseconds))
503         {
504         case 0:
505           ct->ct_error.re_status = RPC_TIMEDOUT;
506           return -1;
507
508         case -1:
509           if (errno == EINTR)
510             continue;
511           ct->ct_error.re_status = RPC_CANTRECV;
512           ct->ct_error.re_errno = errno;
513           return -1;
514         }
515       break;
516     }
517   switch (len = __read (ct->ct_sock, buf, len))
518     {
519
520     case 0:
521       /* premature eof */
522       ct->ct_error.re_errno = ECONNRESET;
523       ct->ct_error.re_status = RPC_CANTRECV;
524       len = -1;                 /* it's really an error */
525       break;
526
527     case -1:
528       ct->ct_error.re_errno = errno;
529       ct->ct_error.re_status = RPC_CANTRECV;
530       break;
531     }
532   return len;
533 }
534
535 static int
536 writetcp (char *ctptr, char *buf, int len)
537 {
538   int i, cnt;
539   struct ct_data *ct = (struct ct_data*)ctptr;
540
541   for (cnt = len; cnt > 0; cnt -= i, buf += i)
542     {
543       if ((i = __write (ct->ct_sock, buf, cnt)) == -1)
544         {
545           ct->ct_error.re_errno = errno;
546           ct->ct_error.re_status = RPC_CANTSEND;
547           return -1;
548         }
549     }
550   return len;
551 }