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