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