summaryrefslogtreecommitdiff
path: root/internal/ntp/ntp.go
blob: 82bdbb53638c0a257d665f4c10ebd7c99cb18106 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package ntp

import (
	"encoding/binary"
	"errors"
	"fmt"
	"net"
	"time"

	"github.com/authelia/authelia/v4/internal/configuration/schema"
	"github.com/authelia/authelia/v4/internal/logging"
)

// NewProvider instantiate a ntp provider given a configuration.
func NewProvider(config *schema.NTP) *Provider {
	return &Provider{
		config: config,
		log:    logging.Logger(),
	}
}

// StartupCheck implements the startup check provider interface.
func (p *Provider) StartupCheck() (err error) {
	var offset time.Duration

	if offset, err = p.GetOffset(); err != nil {
		p.log.WithError(err).Warnf("Could not determine the clock offset due to an error")

		return nil
	}

	if offset > p.config.MaximumDesync {
		return errors.New("the system clock is not synchronized accurately enough with the configured NTP server")
	}

	return nil
}

// GetOffset returns the current offset for this provider.
func (p *Provider) GetOffset() (offset time.Duration, err error) {
	var conn net.Conn

	if conn, err = net.Dial(p.config.Address.Network(), p.config.Address.NetworkAddress()); err != nil {
		return offset, fmt.Errorf("error occurred during dial: %w", err)
	}

	defer func() {
		if closeErr := conn.Close(); closeErr != nil {
			p.log.WithError(err).Error("Error occurred closing connection with NTP sever")
		}
	}()

	if err = conn.SetDeadline(time.Now().Add(5 * time.Second)); err != nil {
		return offset, fmt.Errorf("error occurred setting connection deadline: %w", err)
	}

	version := ntpV4
	if p.config.Version == 3 {
		version = ntpV3
	}

	req := &ntpPacket{LeapVersionMode: ntpLeapVersionClientMode(version)}

	if err = binary.Write(conn, binary.BigEndian, req); err != nil {
		return offset, fmt.Errorf("error occurred writing ntp packet request to the connection: %w", err)
	}

	now := time.Now()

	resp := &ntpPacket{}

	if err = binary.Read(conn, binary.BigEndian, resp); err != nil {
		return offset, fmt.Errorf("error occurred reading ntp packet response to the connection: %w", err)
	}

	ntpTime := ntpPacketToTime(resp)

	return calcOffset(now, ntpTime), nil
}