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