NTPTimeProvider.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. namespace RobThree\Auth\Providers\Time;
  3. /**
  4. * Takes the time from any NTP server
  5. */
  6. class NTPTimeProvider implements ITimeProvider {
  7. /** @var string */
  8. public $host;
  9. /** @var int */
  10. public $port;
  11. /** @var int */
  12. public $timeout;
  13. /**
  14. * @param string $host
  15. * @param int $port
  16. * @param int $timeout
  17. */
  18. public function __construct($host = "time.google.com", $port = 123, $timeout = 1) {
  19. $this->host = $host;
  20. if (!is_int($port) || $port <= 0 || $port > 65535) {
  21. throw new TimeException("Port must be 0 < port < 65535");
  22. }
  23. $this->port = $port;
  24. if (!is_int($timeout) || $timeout < 0) {
  25. throw new TimeException("Timeout must be >= 0");
  26. }
  27. $this->timeout = $timeout;
  28. }
  29. /**
  30. * {@inheritdoc}
  31. */
  32. public function getTime() {
  33. try {
  34. /* Create a socket and connect to NTP server */
  35. $sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
  36. socket_set_option($sock, SOL_SOCKET, SO_RCVTIMEO, [
  37. "sec" => $this->timeout,
  38. "usec" => 0,
  39. ]);
  40. socket_connect($sock, $this->host, $this->port);
  41. /* Send request */
  42. $msg = "\010" . str_repeat("\0", 47);
  43. socket_send($sock, $msg, strlen($msg), 0);
  44. /* Receive response and close socket */
  45. if (socket_recv($sock, $recv, 48, MSG_WAITALL) === false) {
  46. throw new \Exception(socket_strerror(socket_last_error($sock)));
  47. }
  48. socket_close($sock);
  49. /* Interpret response */
  50. $data = unpack("N12", $recv);
  51. $timestamp = (int) sprintf("%u", $data[9]);
  52. /* NTP is number of seconds since 0000 UT on 1 January 1900 Unix time is seconds since 0000 UT on 1 January 1970 */
  53. return $timestamp - 2208988800;
  54. } catch (\Exception $ex) {
  55. throw new TimeException(
  56. sprintf("Unable to retrieve time from %s (%s)", $this->host, $ex->getMessage()),
  57. );
  58. }
  59. }
  60. }