rdate.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * The Rdate command will ask a time server for the RFC 868 time
  4. * and optionally set the system time.
  5. *
  6. * by Sterling Huxley <sterling@europa.com>
  7. *
  8. * Licensed under GPL v2 or later, see file License for details.
  9. */
  10. #include <sys/time.h>
  11. #include <sys/types.h>
  12. #include <sys/socket.h>
  13. #include <netinet/in.h>
  14. #include <netdb.h>
  15. #include <stdio.h>
  16. #include <string.h>
  17. #include <time.h>
  18. #include <stdlib.h>
  19. #include <unistd.h>
  20. #include <signal.h>
  21. #include "busybox.h"
  22. static const int RFC_868_BIAS = 2208988800UL;
  23. static void socket_timeout(int sig)
  24. {
  25. bb_error_msg_and_die("timeout connecting to time server");
  26. }
  27. static time_t askremotedate(const char *host)
  28. {
  29. unsigned long nett;
  30. struct sockaddr_in s_in;
  31. int fd;
  32. bb_lookup_host(&s_in, host);
  33. s_in.sin_port = bb_lookup_port("time", "tcp", 37);
  34. /* Add a timeout for dead or inaccessible servers */
  35. alarm(10);
  36. signal(SIGALRM, socket_timeout);
  37. fd = xconnect(&s_in);
  38. if (safe_read(fd, (void *)&nett, 4) != 4) /* read time from server */
  39. bb_error_msg_and_die("%s did not send the complete time", host);
  40. close(fd);
  41. /* convert from network byte order to local byte order.
  42. * RFC 868 time is the number of seconds
  43. * since 00:00 (midnight) 1 January 1900 GMT
  44. * the RFC 868 time 2,208,988,800 corresponds to 00:00 1 Jan 1970 GMT
  45. * Subtract the RFC 868 time to get Linux epoch
  46. */
  47. return(ntohl(nett) - RFC_868_BIAS);
  48. }
  49. int rdate_main(int argc, char **argv)
  50. {
  51. time_t remote_time;
  52. unsigned long flags;
  53. bb_opt_complementally = "-1";
  54. flags = bb_getopt_ulflags(argc, argv, "sp");
  55. remote_time = askremotedate(argv[optind]);
  56. if (flags & 1) {
  57. time_t current_time;
  58. time(&current_time);
  59. if (current_time == remote_time)
  60. bb_error_msg("Current time matches remote time.");
  61. else
  62. if (stime(&remote_time) < 0)
  63. bb_perror_msg_and_die("Could not set time of day");
  64. /* No need to check for the -p flag as it's the only option left */
  65. } else printf("%s", ctime(&remote_time));
  66. return EXIT_SUCCESS;
  67. }