1 /* vi: set sw=4 ts=4: */
3 * The Rdate command will ask a time server for the RFC 868 time
4 * and optionally set the system time.
6 * by Sterling Huxley <sterling@europa.com>
8 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
11 //config: bool "rdate"
14 //config: The rdate utility allows you to synchronize the date and time of your
15 //config: system clock with the date and time of a remote networked system using
16 //config: the RFC868 protocol, which is built into the inetd daemon on most
19 //applet:IF_RDATE(APPLET(rdate, BB_DIR_USR_SBIN, BB_SUID_DROP))
21 //kbuild:lib-$(CONFIG_RDATE) += rdate.o
23 //usage:#define rdate_trivial_usage
24 //usage: "[-s/-p] HOST"
25 //usage:#define rdate_full_usage "\n\n"
26 //usage: "Set and print time from HOST using RFC 868\n"
27 //usage: "\n -s Only set system time"
28 //usage: "\n -p Only print time"
32 enum { RFC_868_BIAS = 2208988800UL };
34 static void socket_timeout(int sig UNUSED_PARAM)
36 bb_error_msg_and_die("timeout connecting to time server");
39 static time_t askremotedate(const char *host)
44 /* Add a timeout for dead or inaccessible servers */
46 signal(SIGALRM, socket_timeout);
48 fd = create_and_connect_stream_or_die(host, bb_lookup_port("time", "tcp", 37));
50 if (safe_read(fd, &nett, 4) != 4) /* read time from server */
51 bb_error_msg_and_die("%s: %s", host, "short read");
52 if (ENABLE_FEATURE_CLEAN_UP)
55 /* Convert from network byte order to local byte order.
56 * RFC 868 time is the number of seconds
57 * since 00:00 (midnight) 1 January 1900 GMT
58 * the RFC 868 time 2,208,988,800 corresponds to 00:00 1 Jan 1970 GMT
59 * Subtract the RFC 868 time to get Linux epoch.
61 nett = ntohl(nett) - RFC_868_BIAS;
63 if (sizeof(time_t) > 4) {
64 /* Now we have 32-bit lsb of a wider time_t
65 * Imagine that nett = 0x00000001,
66 * current time cur = 0x123ffffffff.
67 * Assuming our time is not some 40 years off,
68 * remote time must be 0x12400000001.
69 * Need to adjust out time by (int32_t)(nett - cur).
71 time_t cur = time(NULL);
72 int32_t adjust = (int32_t)(nett - (uint32_t)cur);
75 /* This is not going to work, but what can we do */
79 int rdate_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
80 int rdate_main(int argc UNUSED_PARAM, char **argv)
85 opt_complementary = "-1";
86 flags = getopt32(argv, "sp");
88 remote_time = askremotedate(argv[optind]);
90 /* Manpages of various Unixes are confusing. What happens is:
91 * (no opts) set and print time
92 * -s: set time ("do not print the time")
93 * -p: print time ("do not set, just print the remote time")
94 * -sp: print time (that's what we do, not sure this is right)
97 if (!(flags & 2)) { /* no -p (-s may be present) */
98 if (time(NULL) == remote_time)
99 bb_error_msg("current time matches remote time");
101 if (stime(&remote_time) < 0)
102 bb_perror_msg_and_die("can't set time of day");
105 if (flags != 1) /* not lone -s */
106 printf("%s", ctime(&remote_time));