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