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