Merge from vendor branch BZIP:
[dragonfly.git] / lib / libc / rpc / auth_time.c
1 #pragma ident   "@(#)auth_time.c        1.4     92/11/10 SMI"
2
3 /*
4  *      auth_time.c
5  *
6  * This module contains the private function __rpc_get_time_offset()
7  * which will return the difference in seconds between the local system's
8  * notion of time and a remote server's notion of time. This must be
9  * possible without calling any functions that may invoke the name
10  * service. (netdir_getbyxxx, getXbyY, etc). The function is used in the
11  * synchronize call of the authdes code to synchronize clocks between
12  * NIS+ clients and their servers.
13  *
14  * Note to minimize the amount of duplicate code, portions of the
15  * synchronize() function were folded into this code, and the synchronize
16  * call becomes simply a wrapper around this function. Further, if this
17  * function is called with a timehost it *DOES* recurse to the name
18  * server so don't use it in that mode if you are doing name service code.
19  *
20  *      Copyright (c) 1992 Sun Microsystems Inc.
21  *      All rights reserved.
22  *
23  * Side effects :
24  *      When called a client handle to a RPCBIND process is created
25  *      and destroyed. Two strings "netid" and "uaddr" are malloc'd
26  *      and returned. The SIGALRM processing is modified only if
27  *      needed to deal with TCP connections.
28  *
29  * NOTE: This code has had the crap beaten out it in order to convert
30  *       it from TI-RPC back to TD-RPC for use on FreeBSD.
31  *
32  * $FreeBSD: src/lib/libc/rpc/auth_time.c,v 1.4 2000/01/27 23:06:35 jasone Exp $
33  * $DragonFly: src/lib/libc/rpc/auth_time.c,v 1.3 2005/01/31 22:29:38 dillon Exp $
34  */
35 #include "namespace.h"
36 #include <stdio.h>
37 #include <syslog.h>
38 #include <string.h>
39 #include <stdlib.h>
40 #include <unistd.h>
41 #include <netdb.h>
42 #include <sys/signal.h>
43 #include <sys/errno.h>
44 #include <sys/socket.h>
45 #include <netinet/in.h>
46 #include <arpa/inet.h>
47 #include <rpc/rpc.h>
48 #include <rpc/rpc_com.h>
49 #undef NIS
50 #include <rpcsvc/nis.h>
51 #include "un-namespace.h"
52
53 /*
54  * FreeBSD currently uses RPC 4.0, which uses portmap rather than
55  * rpcbind. Consequently, we need to fake up these values here.
56  * Luckily, the RPCB_GETTIME procedure uses only base XDR data types
57  * so we don't need anything besides these magic numbers.
58  */
59 #define RPCBPROG (u_long)100000
60 #define RPCBVERS (u_long)3
61 #define RPCBPROC_GETTIME (u_long)6
62
63 #ifdef TESTING
64 #define msg(x)  printf("ERROR: %s\n", x)
65 /* #define msg(x) syslog(LOG_ERR, "%s", x) */
66 #else
67 #define msg(x)
68 #endif
69
70 static int saw_alarm = 0;
71
72 static void
73 alarm_hndler(s)
74         int     s;
75 {
76         saw_alarm = 1;
77         return;
78 }
79
80 /*
81  * The internet time server defines the epoch to be Jan 1, 1900
82  * whereas UNIX defines it to be Jan 1, 1970. To adjust the result
83  * from internet time-service time, into UNIX time we subtract the
84  * following offset :
85  */
86 #define NYEARS  (1970 - 1900)
87 #define TOFFSET ((u_long)60*60*24*(365*NYEARS + (NYEARS/4)))
88
89
90 /*
91  * Stolen from rpc.nisd:
92  * Turn a 'universal address' into a struct sockaddr_in.
93  * Bletch.
94  */
95 static int uaddr_to_sockaddr(uaddr, sin)
96 #ifdef foo
97         endpoint                *endpt;
98 #endif
99         char                    *uaddr;
100         struct sockaddr_in      *sin;
101 {
102         unsigned char           p_bytes[2];
103         int                     i;
104         unsigned long           a[6];
105
106         i = sscanf(uaddr, "%lu.%lu.%lu.%lu.%lu.%lu", &a[0], &a[1], &a[2],
107                                                 &a[3], &a[4], &a[5]);
108
109         if (i < 6)
110                 return(1);
111
112         for (i = 0; i < 4; i++)
113                 sin->sin_addr.s_addr |= (a[i] & 0x000000FF) << (8 * i);
114
115         p_bytes[0] = (unsigned char)a[4] & 0x000000FF;
116         p_bytes[1] = (unsigned char)a[5] & 0x000000FF;
117
118         sin->sin_family = AF_INET; /* always */
119         bcopy((char *)&p_bytes, (char *)&sin->sin_port, 2);
120
121         return (0);
122 }
123
124 /*
125  * free_eps()
126  *
127  * Free the strings that were strduped into the eps structure.
128  */
129 static void
130 free_eps(eps, num)
131         endpoint        eps[];
132         int             num;
133 {
134         int             i;
135
136         for (i = 0; i < num; i++) {
137                 free(eps[i].uaddr);
138                 free(eps[i].proto);
139                 free(eps[i].family);
140         }
141         return;
142 }
143
144 /*
145  * get_server()
146  *
147  * This function constructs a nis_server structure description for the
148  * indicated hostname.
149  *
150  * NOTE: There is a chance we may end up recursing here due to the
151  * fact that gethostbyname() could do an NIS search. Ideally, the
152  * NIS+ server will call __rpc_get_time_offset() with the nis_server
153  * structure already populated.
154  */
155 static nis_server *
156 get_server(sin, host, srv, eps, maxep)
157         struct sockaddr_in *sin;
158         char            *host;  /* name of the time host        */
159         nis_server      *srv;   /* nis_server struct to use.    */
160         endpoint        eps[];  /* array of endpoints           */
161         int             maxep;  /* max array size               */
162 {
163         char                    hname[256];
164         int                     num_ep = 0, i;
165         struct hostent          *he;
166         struct hostent          dummy;
167         char                    *ptr[2];
168
169         if (host == NULL && sin == NULL)
170                 return (NULL);
171
172         if (sin == NULL) {
173                 he = gethostbyname(host);
174                 if (he == NULL)
175                         return(NULL);
176         } else {
177                 he = &dummy;
178                 ptr[0] = (char *)&sin->sin_addr.s_addr;
179                 ptr[1] = NULL;
180                 dummy.h_addr_list = ptr;
181         }
182
183         /*
184          * This is lame. We go around once for TCP, then again
185          * for UDP.
186          */
187         for (i = 0; (he->h_addr_list[i] != NULL) && (num_ep < maxep);
188                                                 i++, num_ep++) {
189                 struct in_addr *a;
190
191                 a = (struct in_addr *)he->h_addr_list[i];
192                 snprintf(hname, sizeof(hname), "%s.0.111", inet_ntoa(*a));
193                 eps[num_ep].uaddr = strdup(hname);
194                 eps[num_ep].family = strdup("inet");
195                 eps[num_ep].proto =  strdup("tcp");
196         }
197
198         for (i = 0; (he->h_addr_list[i] != NULL) && (num_ep < maxep);
199                                                 i++, num_ep++) {
200                 struct in_addr *a;
201
202                 a = (struct in_addr *)he->h_addr_list[i];
203                 snprintf(hname, sizeof(hname), "%s.0.111", inet_ntoa(*a));
204                 eps[num_ep].uaddr = strdup(hname);
205                 eps[num_ep].family = strdup("inet");
206                 eps[num_ep].proto =  strdup("udp");
207         }
208
209         srv->name = (nis_name) host;
210         srv->ep.ep_len = num_ep;
211         srv->ep.ep_val = eps;
212         srv->key_type = NIS_PK_NONE;
213         srv->pkey.n_bytes = NULL;
214         srv->pkey.n_len = 0;
215         return (srv);
216 }
217
218 /*
219  * __rpc_get_time_offset()
220  *
221  * This function uses a nis_server structure to contact the a remote
222  * machine (as named in that structure) and returns the offset in time
223  * between that machine and this one. This offset is returned in seconds
224  * and may be positive or negative.
225  *
226  * The first time through, a lot of fiddling is done with the netconfig
227  * stuff to find a suitable transport. The function is very aggressive
228  * about choosing UDP or at worst TCP if it can. This is because
229  * those transports support both the RCPBIND call and the internet
230  * time service.
231  *
232  * Once through, *uaddr is set to the universal address of
233  * the machine and *netid is set to the local netid for the transport
234  * that uaddr goes with. On the second call, the netconfig stuff
235  * is skipped and the uaddr/netid pair are used to fetch the netconfig
236  * structure and to then contact the machine for the time.
237  *
238  * td = "server" - "client"
239  */
240 int
241 __rpc_get_time_offset(td, srv, thost, uaddr, netid)
242         struct timeval  *td;     /* Time difference                     */
243         nis_server      *srv;    /* NIS Server description              */
244         char            *thost;  /* if no server, this is the timehost  */
245         char            **uaddr; /* known universal address             */
246         struct sockaddr_in *netid; /* known network identifier          */
247 {
248         CLIENT                  *clnt;          /* Client handle        */
249         endpoint                *ep,            /* useful endpoints     */
250                                 *useep = NULL;  /* endpoint of xp       */
251         char                    *useua = NULL;  /* uaddr of selected xp */
252         int                     epl, i;         /* counters             */
253         enum clnt_stat          status;         /* result of clnt_call  */
254         u_long                  thetime, delta;
255         int                     needfree = 0;
256         struct timeval          tv;
257         int                     time_valid;
258         int                     udp_ep = -1, tcp_ep = -1;
259         int                     a1, a2, a3, a4;
260         char                    ut[64], ipuaddr[64];
261         endpoint                teps[32];
262         nis_server              tsrv;
263         void                    (*oldsig)() = NULL; /* old alarm handler */
264         struct sockaddr_in      sin;
265         int                     s = RPC_ANYSOCK, len;
266         int                     type = 0;
267
268         td->tv_sec = 0;
269         td->tv_usec = 0;
270
271         /*
272          * First check to see if we need to find and address for this
273          * server.
274          */
275         if (*uaddr == NULL) {
276                 if ((srv != NULL) && (thost != NULL)) {
277                         msg("both timehost and srv pointer used!");
278                         return (0);
279                 }
280                 if (! srv) {
281                         srv = get_server(netid, thost, &tsrv, teps, 32);
282                         if (srv == NULL) {
283                                 msg("unable to contruct server data.");
284                                 return (0);
285                         }
286                         needfree = 1;   /* need to free data in endpoints */
287                 }
288
289                 ep = srv->ep.ep_val;
290                 epl = srv->ep.ep_len;
291
292                 /* Identify the TCP and UDP endpoints */
293                 for (i = 0;
294                         (i < epl) && ((udp_ep == -1) || (tcp_ep == -1)); i++) {
295                         if (strcasecmp(ep[i].proto, "udp") == 0)
296                                 udp_ep = i;
297                         if (strcasecmp(ep[i].proto, "tcp") == 0)
298                                 tcp_ep = i;
299                 }
300
301                 /* Check to see if it is UDP or TCP */
302                 if (tcp_ep > -1) {
303                         useep = &ep[tcp_ep];
304                         useua = ep[tcp_ep].uaddr;
305                         type = SOCK_STREAM;
306                 } else if (udp_ep > -1) {
307                         useep = &ep[udp_ep];
308                         useua = ep[udp_ep].uaddr;
309                         type = SOCK_DGRAM;
310                 }
311
312                 if (useep == NULL) {
313                         msg("no acceptable transport endpoints.");
314                         if (needfree)
315                                 free_eps(teps, tsrv.ep.ep_len);
316                         return (0);
317                 }
318         }
319
320         /*
321          * Create a sockaddr from the uaddr.
322          */
323         if (*uaddr != NULL)
324                 useua = *uaddr;
325
326         /* Fixup test for NIS+ */
327         sscanf(useua, "%d.%d.%d.%d.", &a1, &a2, &a3, &a4);
328         sprintf(ipuaddr, "%d.%d.%d.%d.0.111", a1, a2, a3, a4);
329         useua = &ipuaddr[0];
330
331         bzero((char *)&sin, sizeof(sin));
332         if (uaddr_to_sockaddr(useua, &sin)) {
333                 msg("unable to translate uaddr to sockaddr.");
334                 if (needfree)
335                         free_eps(teps, tsrv.ep.ep_len);
336                 return (0);
337         }
338
339         /*
340          * Create the client handle to rpcbind. Note we always try
341          * version 3 since that is the earliest version that supports
342          * the RPCB_GETTIME call. Also it is the version that comes
343          * standard with SVR4. Since most everyone supports TCP/IP
344          * we could consider trying the rtime call first.
345          */
346         clnt = clnttcp_create(&sin, RPCBPROG, RPCBVERS, &s, 0, 0);
347         if (clnt == NULL) {
348                 msg("unable to create client handle to rpcbind.");
349                 if (needfree)
350                         free_eps(teps, tsrv.ep.ep_len);
351                 return (0);
352         }
353
354         tv.tv_sec = 5;
355         tv.tv_usec = 0;
356         time_valid = 0;
357         status = clnt_call(clnt, RPCBPROC_GETTIME, xdr_void, NULL,
358                                         xdr_u_long, (char *)&thetime, tv);
359         /*
360          * The only error we check for is anything but success. In
361          * fact we could have seen PROGMISMATCH if talking to a 4.1
362          * machine (pmap v2) or TIMEDOUT if the net was busy.
363          */
364         if (status == RPC_SUCCESS)
365                 time_valid = 1;
366         else {
367                 int save;
368
369                 /* Blow away possible stale CLNT handle. */
370                 if (clnt != NULL) {
371                         clnt_destroy(clnt);
372                         clnt = NULL;
373                 }
374
375                 /*
376                  * Convert PMAP address into timeservice address
377                  * We take advantage of the fact that we "know" what
378                  * the universal address looks like for inet transports.
379                  *
380                  * We also know that the internet timeservice is always
381                  * listening on port 37.
382                  */
383                 sscanf(useua, "%d.%d.%d.%d.", &a1, &a2, &a3, &a4);
384                 sprintf(ut, "%d.%d.%d.%d.0.37", a1, a2, a3, a4);
385
386                 if (uaddr_to_sockaddr(ut, &sin)) {
387                         msg("cannot convert timeservice uaddr to sockaddr.");
388                         goto error;
389                 }
390
391                 s = _socket(AF_INET, type, 0);
392                 if (s == -1) {
393                         msg("unable to open fd to network.");
394                         goto error;
395                 }
396
397                 /*
398                  * Now depending on whether or not we're talking to
399                  * UDP we set a timeout or not.
400                  */
401                 if (type == SOCK_DGRAM) {
402                         struct timeval timeout = { 20, 0 };
403                         struct sockaddr_in from;
404                         fd_set readfds;
405                         int res;
406
407                         if (_sendto(s, &thetime, sizeof(thetime), 0,
408                                 (struct sockaddr *)&sin, sizeof(sin)) == -1) {
409                                 msg("udp : sendto failed.");
410                                 goto error;
411                         }
412                         do {
413                                 FD_ZERO(&readfds);
414                                 FD_SET(s, &readfds);
415                                 res = _select(_rpc_dtablesize(), &readfds,
416                                      (fd_set *)NULL, (fd_set *)NULL, &timeout);
417                         } while (res < 0 && errno == EINTR);
418                         if (res <= 0)
419                                 goto error;
420                         len = sizeof(from);
421                         res = _recvfrom(s, (char *)&thetime, sizeof(thetime), 0,
422                                        (struct sockaddr *)&from, &len);
423                         if (res == -1) {
424                                 msg("recvfrom failed on udp transport.");
425                                 goto error;
426                         }
427                         time_valid = 1;
428                 } else {
429                         int res;
430
431                         oldsig = (void (*)())signal(SIGALRM, alarm_hndler);
432                         saw_alarm = 0; /* global tracking the alarm */
433                         alarm(20); /* only wait 20 seconds */
434                         res = _connect(s, (struct sockaddr *)&sin, sizeof(sin));
435                         if (res == -1) {
436                                 msg("failed to connect to tcp endpoint.");
437                                 goto error;
438                         }
439                         if (saw_alarm) {
440                                 msg("alarm caught it, must be unreachable.");
441                                 goto error;
442                         }
443                         res = _read(s, (char *)&thetime, sizeof(thetime));
444                         if (res != sizeof(thetime)) {
445                                 if (saw_alarm)
446                                         msg("timed out TCP call.");
447                                 else
448                                         msg("wrong size of results returned");
449
450                                 goto error;
451                         }
452                         time_valid = 1;
453                 }
454                 save = errno;
455                 (void)_close(s);
456                 errno = save;
457                 s = RPC_ANYSOCK;
458
459                 if (time_valid) {
460                         thetime = ntohl(thetime);
461                         thetime = thetime - TOFFSET; /* adjust to UNIX time */
462                 } else
463                         thetime = 0;
464         }
465
466         gettimeofday(&tv, 0);
467
468 error:
469         /*
470          * clean up our allocated data structures.
471          */
472
473         if (s != RPC_ANYSOCK)
474                 (void)_close(s);
475
476         if (clnt != NULL)
477                 clnt_destroy(clnt);
478
479         alarm(0);       /* reset that alarm if its outstanding */
480         if (oldsig) {
481                 signal(SIGALRM, oldsig);
482         }
483
484         /*
485          * note, don't free uaddr strings until after we've made a
486          * copy of them.
487          */
488         if (time_valid) {
489                 if (*uaddr == NULL)
490                         *uaddr = strdup(useua);
491
492                 /* Round to the nearest second */
493                 tv.tv_sec += (tv.tv_sec > 500000) ? 1 : 0;
494                 delta = (thetime > tv.tv_sec) ? thetime - tv.tv_sec :
495                                                 tv.tv_sec - thetime;
496                 td->tv_sec = (thetime < tv.tv_sec) ? - delta : delta;
497                 td->tv_usec = 0;
498         } else {
499                 msg("unable to get the server's time.");
500         }
501
502         if (needfree)
503                 free_eps(teps, tsrv.ep.ep_len);
504
505         return (time_valid);
506 }