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