xref: /freebsd/contrib/ntp/libntp/buftvtots.c (revision 2be1a816b9ff69588e55be0a84cbe2a31efc0f2f)
1 /*
2  * buftvtots - pull a Unix-format (struct timeval) time stamp out of
3  *	       an octet stream and convert it to a l_fp time stamp.
4  *	       This is useful when using the clock line discipline.
5  */
6 
7 #ifdef HAVE_CONFIG_H
8 #include "config.h"
9 #endif
10 #include "ntp_fp.h"
11 #include "ntp_unixtime.h"
12 
13 int
14 buftvtots(
15 	const char *bufp,
16 	l_fp *ts
17 	)
18 {
19 	register const u_char *bp;
20 	register u_long sec;
21 	register u_long usec;
22 	struct timeval tv;
23 
24 #ifdef WORDS_BIGENDIAN
25 	bp = (const u_char *)bufp;
26 
27 	sec = (u_long)*bp++ & 0xff;
28 	sec <<= 8;
29 	sec += (u_long)*bp++ & 0xff;
30 	sec <<= 8;
31 	sec += (u_long)*bp++ & 0xff;
32 	sec <<= 8;
33 	sec += (u_long)*bp++ & 0xff;
34 
35 	if (sizeof(tv.tv_sec) == 8) {
36 		sec += (u_long)*bp++ & 0xff;
37 		sec <<= 8;
38 		sec += (u_long)*bp++ & 0xff;
39 		sec <<= 8;
40 		sec += (u_long)*bp++ & 0xff;
41 		sec <<= 8;
42 		sec += (u_long)*bp++ & 0xff;
43 	}
44 
45 	usec = (u_long)*bp++ & 0xff;
46 	usec <<= 8;
47 	usec += (u_long)*bp++ & 0xff;
48 	usec <<= 8;
49 	usec += (u_long)*bp++ & 0xff;
50 	usec <<= 8;
51 	usec += (u_long)*bp++ & 0xff;
52 
53 	if (sizeof(tv.tv_usec) == 8) {
54 		usec += (u_long)*bp++ & 0xff;
55 		usec <<= 8;
56 		usec += (u_long)*bp++ & 0xff;
57 		usec <<= 8;
58 		usec += (u_long)*bp++ & 0xff;
59 		usec <<= 8;
60 		usec += (u_long)*bp & 0xff;
61 	}
62 #else
63 	bp = (const u_char *)bufp + 7;
64 
65 	usec = (u_long)*bp-- & 0xff;
66 	usec <<= 8;
67 	usec += (u_long)*bp-- & 0xff;
68 	usec <<= 8;
69 	usec += (u_long)*bp-- & 0xff;
70 	usec <<= 8;
71 	usec += (u_long)*bp-- & 0xff;
72 
73 	if (sizeof(tv.tv_usec) == 8) {
74 		usec += (u_long)*bp-- & 0xff;
75 		usec <<= 8;
76 		usec += (u_long)*bp-- & 0xff;
77 		usec <<= 8;
78 		usec += (u_long)*bp-- & 0xff;
79 		usec <<= 8;
80 		usec += (u_long)*bp-- & 0xff;
81 	}
82 
83 	sec = (u_long)*bp-- & 0xff;
84 	sec <<= 8;
85 	sec += (u_long)*bp-- & 0xff;
86 	sec <<= 8;
87 	sec += (u_long)*bp-- & 0xff;
88 	sec <<= 8;
89 	sec += (u_long)*bp-- & 0xff;
90 
91 	if (sizeof (tv.tv_sec) == 8) {
92 		sec += (u_long)*bp-- & 0xff;
93 		sec <<= 8;
94 		sec += (u_long)*bp-- & 0xff;
95 		sec <<= 8;
96 		sec += (u_long)*bp-- & 0xff;
97 		sec <<= 8;
98 		sec += (u_long)*bp & 0xff;
99 	}
100 #endif
101 	ts->l_ui = sec + (u_long)JAN_1970;
102 	if (usec > 999999)
103 	    return 0;
104 	TVUTOTSF(usec, ts->l_uf);
105 	return 1;
106 }
107