diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml index 610c3b0..0eb4364 100644 --- a/.github/workflows/pages.yml +++ b/.github/workflows/pages.yml @@ -22,7 +22,7 @@ jobs: site: uses: D-Modem/brand/.github/workflows/site.yml@main with: - go-version: "1.24" + go-version: "1.26" prepare: | go run ./internal/confedit/refdoc git diff --exit-code docs/wiki/Configuration-Reference.md || { echo "::error::docs/wiki/Configuration-Reference.md is out of date: go generate ./internal/confedit"; exit 1; } diff --git a/README.md b/README.md index fb23dda..547b751 100644 --- a/README.md +++ b/README.md @@ -34,13 +34,14 @@ Main menu - Networks: FidoNet and other FTNs, QWK, NNTP newsgroups, IRC, AIM and ICQ, and MRC - Terminals: ANSI, VT, PETSCII, RIPscrip, sixel and 3270 graphics - On the web: a forum, image boards, a web terminal and an HTTP API +- Time: follows NTP, NTS and PTP servers, and serves all three - SQLite, PostgreSQL, MySQL or MariaDB The full list is on the [wiki's home page](https://github.com/D-Modem/bbs/wiki/Home). ## Quick start -Go 1.24 or later: +Go 1.26 or later: ``` make # or: go build ./cmd/bbs diff --git a/bbs.conf.sample b/bbs.conf.sample index 84b29ad..5ad4e9c 100644 --- a/bbs.conf.sample +++ b/bbs.conf.sample @@ -687,6 +687,71 @@ address = 127.0.0.1:2513 ; file areas listed and downloadable ;files = no +; Time. The BBS's clock can follow time servers, and the BBS can be a +; time server itself: NTP, NTS (NTP made secure with TLS keys) and PTP. +; With no servers it tells of the system clock (kept by chrony, ntpd ...). +;[time] +; servers followed: KIND HOST, by commas. ntp HOST[:PORT], nts HOST[:PORT] +; (its NTS-KE port, 4460 if none), ptp HOST (unicast; ports 319 and 320) +;servers = nts time.cloudflare.com, nts nts.netnod.se, ntp pool.ntp.org +; seconds between asking them (16 at least) +;poll = 64 +; set the system clock (Linux; root, or CAP_SYS_TIME kept: with [general] +; user, systemd's AmbientCapabilities=CAP_SYS_TIME). No: the BBS keeps +; the offset and serves corrected time, leaving the system clock alone +;set_clock = no +; with no servers: the stratum told (0: 3 while the kernel says the clock +; is synchronised, else unsynchronised), and stratum 1's reference (GPS, PPS) +;stratum = 0 +;refid = GPS +; a PEM file NTS-KE servers' certificates are checked against ("": the system's) +;root_cas = /etc/bbs/nts-ca.pem +; TAI - UTC, in seconds, for PTP (37 since 2017) +;utc_offset = 37 + +; an NTP server (UDP). Port 123 needs CAP_NET_BIND_SERVICE +;[ntp] +;address = :123 +; requests a second an address may make (0: no limit), and at once +;rate = 2 +;burst = 16 + +; an NTS-KE server (RFC 8915): TLS 1.3, its clients' keys and cookies for +; [ntp], which then answers NTS-secured requests too. The certificate is +; read again when its file changes (a renewal) +;[nts] +;address = :4460 +;tls_cert = /etc/bbs/cert.pem +;tls_key = /etc/bbs/key.pem +; the NTP server clients are told to use ("": this one) +;ntp_host = time.example.org +;max_clients = 64 +;max_per_ip = 8 + +; a PTP grandmaster (IEEE 1588, UDP ports 319 and 320, as root): two-step, +; end to end. Multicast to 224.0.1.129 on interface, and unicast to the +; clients that ask (linuxptp's unicast_master_table, ptp4u's clients) +;[ptp] +; the address bound ("": all) +;address = +; multicast's interface, and hardware timestamps' ("": no multicast) +;interface = eth0 +;multicast = yes +;unicast = yes +;domain = 0 +;priority1 = 128 +;priority2 = 128 +; intervals, as powers of two seconds: multicast syncs (0: 1 s) and +; announcements (1: 2 s); the shortest a unicast client is granted (-4: 1/16 s) +;log_sync_interval = 0 +;log_announce_interval = 1 +;log_min_interval = -4 +; unicast clients at once +;max_clients = 256 +; software (the kernel's stamps) or hardware (the network card's: its +; clock kept on the system's, phc2sys -s CLOCK_REALTIME -c eth0 -O 0) +;timestamping = software + ; Menus of the sysop's. [menu main] takes the place of the built-in main ; menu (on 3270s too); others are reached from it. Each item is ; KEY = ACTION Label: one character (not ; or #), then what it does: diff --git a/docs/wiki/Building.md b/docs/wiki/Building.md index 357d8a6..377a795 100644 --- a/docs/wiki/Building.md +++ b/docs/wiki/Building.md @@ -1,4 +1,4 @@ -This page shows how to build bbs from source. You need Go 1.24 or later. +This page shows how to build bbs from source. You need Go 1.26 or later. ``` make # or: go build ./cmd/bbs diff --git a/docs/wiki/Configuration-Reference.md b/docs/wiki/Configuration-Reference.md index 98ee3bf..542d7e6 100644 --- a/docs/wiki/Configuration-Reference.md +++ b/docs/wiki/Configuration-Reference.md @@ -35,6 +35,10 @@ the file is laid out. | [`[mrc]`](#mrc) | Multi Relay Chat: the BBSes' chat network. | | [`[finger]`](#finger) | finger: who is on ("finger @host"), and who a user is ("finger name@host"). | | [`[gopher]`](#gopher) | gopher: about the system, who is on, and what areas the sysop opens: no login, so anyone sees them. | +| [`[time]`](#time) | Time. | +| [`[ntp]`](#ntp) | an NTP server (UDP). | +| [`[nts]`](#nts) | an NTS-KE server (RFC 8915): TLS 1.3, its clients' keys and cookies for [ntp], which then answers NTS-secured requests too. | +| [`[ptp]`](#ptp) | a PTP grandmaster (IEEE 1588, UDP ports 319 and 320, as root): two-step, end to end. | | [`[menu NAME]`](#menu-name) | A menu of the sysop's: [menu main] takes the place of the built-in main menu; others are reached from it (menu:NAME). | | [`[strings]`](#strings) | The prompts and messages, with @-codes and tags. | @@ -488,6 +492,66 @@ gopher: about the system, who is on, and what areas the sysop opens: no login, s | `files` | | | file areas listed and downloadable. Examples: `no`. | +## `[time]` + +Time. The BBS's clock can follow time servers, and the BBS can be a time server itself: NTP, NTS (NTP made secure with TLS keys) and PTP. With no servers it tells of the system clock (kept by chrony, ntpd ...). + +| key | default | live | what it does | +|---|---|---|---| +| `servers` | | | servers followed: KIND HOST, by commas. ntp HOST[:PORT], nts HOST[:PORT] (its NTS-KE port, 4460 if none), ptp HOST (unicast; ports 319 and 320) Examples: `nts time.cloudflare.com, nts nts.netnod.se, ntp pool.ntp.org`. | +| `poll` | | | seconds between asking them (16 at least) Examples: `64`. | +| `set_clock` | | | set the system clock (Linux; root, or CAP_SYS_TIME kept: with [general] user, systemd's AmbientCapabilities=CAP_SYS_TIME). No: the BBS keeps the offset and serves corrected time, leaving the system clock alone. Examples: `no`. | +| `stratum` | | | with no servers: the stratum told (0: 3 while the kernel says the clock is synchronised, else unsynchronised), and stratum 1's reference (GPS, PPS) Examples: `0`. | +| `refid` | | | with no servers: the stratum told (0: 3 while the kernel says the clock is synchronised, else unsynchronised), and stratum 1's reference (GPS, PPS) Examples: `GPS`. | +| `root_cas` | | | a PEM file NTS-KE servers' certificates are checked against ("": the system's) Examples: `/etc/bbs/nts-ca.pem`. | +| `utc_offset` | | | TAI - UTC, in seconds, for PTP (37 since 2017) Examples: `37`. | + + +## `[ntp]` + +an NTP server (UDP). Port 123 needs CAP_NET_BIND_SERVICE. + +| key | default | live | what it does | +|---|---|---|---| +| `address` | | | See the section above. Examples: `:123`. | +| `rate` | | | requests a second an address may make (0: no limit), and at once. Examples: `2`. | +| `burst` | | | requests a second an address may make (0: no limit), and at once. Examples: `16`. | + + +## `[nts]` + +an NTS-KE server (RFC 8915): TLS 1.3, its clients' keys and cookies for [ntp], which then answers NTS-secured requests too. The certificate is read again when its file changes (a renewal) + +| key | default | live | what it does | +|---|---|---|---| +| `address` | | | See the section above. Examples: `:4460`. | +| `tls_cert` | | | See the section above. Examples: `/etc/bbs/cert.pem`. | +| `tls_key` | | | See the section above. Examples: `/etc/bbs/key.pem`. | +| `ntp_host` | | | the NTP server clients are told to use ("": this one) Examples: `time.example.org`. | +| `max_clients` | | | the NTP server clients are told to use ("": this one) Examples: `64`. | +| `max_per_ip` | | | the NTP server clients are told to use ("": this one) Examples: `8`. | + + +## `[ptp]` + +a PTP grandmaster (IEEE 1588, UDP ports 319 and 320, as root): two-step, end to end. Multicast to 224.0.1.129 on interface, and unicast to the clients that ask (linuxptp's unicast_master_table, ptp4u's clients) + +| key | default | live | what it does | +|---|---|---|---| +| `address` | | | the address bound ("": all) | +| `interface` | | | multicast's interface, and hardware timestamps' ("": no multicast) Examples: `eth0`. | +| `multicast` | | | multicast's interface, and hardware timestamps' ("": no multicast) Examples: `yes`. | +| `unicast` | | | multicast's interface, and hardware timestamps' ("": no multicast) Examples: `yes`. | +| `domain` | | | multicast's interface, and hardware timestamps' ("": no multicast) Examples: `0`. | +| `priority1` | | | multicast's interface, and hardware timestamps' ("": no multicast) Examples: `128`. | +| `priority2` | | | multicast's interface, and hardware timestamps' ("": no multicast) Examples: `128`. | +| `log_sync_interval` | | | intervals, as powers of two seconds: multicast syncs (0: 1 s) and announcements (1: 2 s); the shortest a unicast client is granted (-4: 1/16 s) Examples: `0`. | +| `log_announce_interval` | | | intervals, as powers of two seconds: multicast syncs (0: 1 s) and announcements (1: 2 s); the shortest a unicast client is granted (-4: 1/16 s) Examples: `1`. | +| `log_min_interval` | | | intervals, as powers of two seconds: multicast syncs (0: 1 s) and announcements (1: 2 s); the shortest a unicast client is granted (-4: 1/16 s) Examples: `-4`. | +| `max_clients` | | | unicast clients at once. Examples: `256`. | +| `timestamping` | | | software (the kernel's stamps) or hardware (the network card's: its clock kept on the system's, phc2sys -s CLOCK_REALTIME -c eth0 -O 0) Examples: `software`. | + + ## `[menu NAME]` A menu of the sysop's: [menu main] takes the place of the built-in main menu; others are reached from it (menu:NAME). diff --git a/docs/wiki/Home.md b/docs/wiki/Home.md index 8357ebb..b34dc79 100644 --- a/docs/wiki/Home.md +++ b/docs/wiki/Home.md @@ -82,6 +82,7 @@ which is generated from `bbs.conf.sample`. for AIM and ICQ clients on the same chat, and [MRC](MRC), the chat network shared with other BBSes - [Finger and gopher](Finger-and-Gopher) +- [Time](Time): NTP, NTS and PTP, followed and served **On the web** @@ -137,6 +138,7 @@ which is generated from `bbs.conf.sample`. | [AIM and ICQ](AIM-and-ICQ) | the OSCAR server: AIM and ICQ clients, buddies, IMs and chat rooms | | [MRC](MRC) | Multi Relay Chat: chat rooms shared with other BBSes | | [Finger and gopher](Finger-and-Gopher) | who is on, and the BBS in gopherspace | +| [Time](Time) | NTP, NTS and PTP: the clock following time servers, and serving time | | [Web forum](Web-Forum) | the message areas as a web forum | | [Image boards](Image-Boards) | anonymous image boards, in the style of kusaba x and 4chan | | [HTTP API](HTTP-API) | REST, events, WebSockets in JSON and protobuf, tokens, metrics | diff --git a/docs/wiki/Time.md b/docs/wiki/Time.md new file mode 100644 index 0000000..393dda3 --- /dev/null +++ b/docs/wiki/Time.md @@ -0,0 +1,152 @@ +The BBS can keep its own time and serve it. It can follow time servers +over NTP, NTS (NTP secured with keys from a TLS exchange) and PTP. It can +also be an NTP server, an NTS-KE server and a PTP grandmaster. All of it +is off unless its section is in the configuration. + +The protocols' packets come from Meta's +[facebook/time](https://github.com/facebook/time) (Apache-2.0). The +servers and clients are the BBS's own. + +## Following time servers + +``` +[time] +servers = nts time.cloudflare.com, nts nts.netnod.se, ntp pool.ntp.org +poll = 64 +set_clock = no +``` + +Each poll, every server is asked. NTP and NTS servers are asked four +times, and the answer with the shortest round trip counts. The clock then +takes the median of the servers' offsets, so one wrong server is outvoted. + +- `ntp HOST[:PORT]` is plain NTP. +- `nts HOST[:PORT]` is NTS. The port is the NTS-KE port (4460 if none). + The key exchange gives eight cookies, each request spends one and asks + for one back, and a new exchange is made when cookies run out or the + server stops knowing them. `root_cas` names a PEM file to trust instead + of the system's roots, for a private server. +- `ptp HOST` asks a PTP grandmaster for unicast transmission (announce + every 2 s, sync every 1 s, for 60 s at a time, renewed). It needs ports + 319 and 320, so the BBS must start as root (it binds them before it + becomes `[general] user`). + +With `set_clock = no` (the default), the system clock is left alone. The +BBS keeps the offset it measures and serves the corrected time. With +`set_clock = yes` (Linux), it steps the system clock when it is more than +128 ms out and slews it otherwise, and tells the kernel the clock is +synchronised. That needs root, or `CAP_SYS_TIME` kept after the BBS gives +up root (systemd: `AmbientCapabilities=CAP_SYS_TIME`). Don't turn it on +next to chrony or ntpd, which would fight it. If it can't set the clock, +it says so once in the log and falls back to correcting its own time. + +With no servers, the BBS tells of the system clock: stratum 3 while the +kernel says it is synchronised, unsynchronised otherwise. `stratum` says +otherwise, for example `stratum = 1` and `refid = GPS` on a machine whose +clock a GPS keeps. + +`bbs time` asks the configured servers once and prints each offset. +`bbs time nts time.cloudflare.com` asks one server instead: + +``` +$ bbs time nts time.cloudflare.com ntp pool.ntp.org +nts time.cloudflare.com offset +412µs, round trip 9.8ms, stratum 3, leap 0 +ntp pool.ntp.org offset +380µs, round trip 21ms, stratum 2, leap 0 +``` + +## NTP server + +``` +[ntp] +address = :123 +rate = 2 ; requests a second an address may make (0: no limit) +burst = 16 ; and at once +``` + +Only client requests (mode 3) are answered, so the control and private +modes used for amplification attacks get nothing. Addresses banned by the +guard (`[security]`) get nothing either. The stratum told is one past the +server followed, and the reference ID is that server's address. + +## NTS-KE server + +``` +[nts] +address = :4460 +tls_cert = /etc/bbs/cert.pem +tls_key = /etc/bbs/key.pem +ntp_host = time.example.org ; told to clients ("": this host) +``` + +NTS needs `[ntp]` too: the key exchange hands out cookies, and the NTP +server answers requests that carry them, authenticated. The cookie key +changes each day, and the last week's keys are kept, so cookies stay good. +A restart makes new keys. Clients then get an NTS NAK and exchange keys +again by themselves. The certificate is read again when its file changes, +so a renewal needs no restart. AES-SIV-CMAC-256, AES-128-GCM-SIV and +AES-SIV-CMAC-512 are offered. GCM-SIV goes only to clients that say they +make its keys as the RFC says (chrony before 4.4 did not). + +A chrony client: + +``` +server time.example.org iburst nts +``` + +## PTP grandmaster + +``` +[ptp] +interface = eth0 +multicast = yes +unicast = yes +domain = 0 +timestamping = software +``` + +The BBS is a two-step, end-to-end grandmaster on UDP ports 319 and 320. + +- **Multicast** (with `interface`): announce and sync go to 224.0.1.129. + Delay requests are answered to the client directly, the hybrid mode + linuxptp and others accept. +- **Unicast**: clients that ask (linuxptp's `unicast_master_table`, + Meta's ptp4u clients, `ptp HOST` on another BBS) are granted announce, + sync and delay responses, up to `max_clients`, no faster than + `log_min_interval`. + +Time on the wire is TAI (UTC + `utc_offset`, 37). The clock class is 6 +while the BBS's clock is synchronised, 248 otherwise. The time source +says where the time comes from (NTP, PTP, GNSS, or the internal +oscillator). + +Timestamps are the kernel's on Linux (`SO_TIMESTAMPING`). Elsewhere +packets are stamped as they are read and written. `timestamping = +hardware` uses the network card's clock, which has to be kept on the +system clock (`phc2sys -s CLOCK_REALTIME -c eth0 -O 0`). The card is set +up as root, before the BBS gives root up. + +A linuxptp client, by unicast: + +``` +[global] +clientOnly 1 +[unicast_master_table] +table_id 1 +logQueryInterval 2 +UDPv4 192.0.2.10 +[eth0] +unicast_master_table 1 +``` + +## Tested with + +- chrony 4.5 as an NTP and NTS client of the BBS, and as an NTP and NTS + server the BBS follows (port negotiation included). +- linuxptp 4.0 `ptp4l` as a multicast and as a unicast client of the + grandmaster (within about a microsecond, software timestamps, over a + virtual Ethernet link), and as a unicast grandmaster the BBS follows. +- Meta's NTS-KE server, whose cookies the BBS's NTP server opens. + +In that test, the BBS read a `ptp4l` grandmaster on software timestamps +37 seconds off: that grandmaster sends the system clock's UTC as PTP's +TAI. A grandmaster whose card's clock is on TAI doesn't have this problem. diff --git a/docs/wiki/_Sidebar.md b/docs/wiki/_Sidebar.md index 4dcd373..25c27f4 100644 --- a/docs/wiki/_Sidebar.md +++ b/docs/wiki/_Sidebar.md @@ -36,6 +36,7 @@ - [AIM and ICQ](AIM-and-ICQ) - [MRC](MRC) - [Finger and gopher](Finger-and-Gopher) +- [Time: NTP, NTS and PTP](Time) - [Web forum](Web-Forum) - [Image boards](Image-Boards) - [HTTP API](HTTP-API) diff --git a/go.mod b/go.mod index 1c9be65..504d7d6 100644 --- a/go.mod +++ b/go.mod @@ -18,6 +18,7 @@ require ( github.com/spf13/afero v1.15.0 golang.org/x/crypto v0.52.0 golang.org/x/image v0.23.0 + golang.org/x/net v0.55.0 golang.org/x/sys v0.45.0 golang.org/x/term v0.43.0 golang.org/x/text v0.37.0 diff --git a/go.sum b/go.sum index b67a21c..d3b906b 100644 --- a/go.sum +++ b/go.sum @@ -74,6 +74,8 @@ golang.org/x/image v0.23.0 h1:HseQ7c2OpPKTPVzNjG5fwJsOTCiiwS4QdsYi5XU6H68= golang.org/x/image v0.23.0/go.mod h1:wJJBTdLfCCf3tiHa1fNxpZmUI4mmoZvwMCPP0ddoNKY= golang.org/x/mod v0.35.0 h1:Ww1D637e6Pg+Zb2KrWfHQUnH2dQRLBQyAtpr/haaJeM= golang.org/x/mod v0.35.0/go.mod h1:+GwiRhIInF8wPm+4AoT6L0FA1QWAad3OMdTRx4tFYlU= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4= golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= diff --git a/internal/server/timeconfig.go b/internal/server/timeconfig.go index 960e6d4..a653deb 100644 --- a/internal/server/timeconfig.go +++ b/internal/server/timeconfig.go @@ -150,9 +150,9 @@ func (c *Config) timeSections(cf *config.File) error { return err } ints := []struct { - key string + key string def, lo, hi int - set func(int) + set func(int) }{ {"domain", 0, 0, 239, func(v int) { p.Domain = uint8(v) }}, {"priority1", 128, 0, 255, func(v int) { p.Priority1 = uint8(v) }}, diff --git a/internal/server/timeconfig_test.go b/internal/server/timeconfig_test.go new file mode 100644 index 0000000..b8e1733 --- /dev/null +++ b/internal/server/timeconfig_test.go @@ -0,0 +1,49 @@ +package server + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +// TestTimeConfig: [time], [ntp], [nts] and [ptp] read, and what they +// need of each other checked. +func TestTimeConfig(t *testing.T) { + dir := t.TempDir() + load := func(conf string) (*Config, error) { + p := filepath.Join(dir, "bbs.conf") + os.WriteFile(p, []byte("[general]\ndatabase = "+filepath.Join(dir, "bbs.db")+"\n[listen telnet]\naddress = :2323\n"+conf), 0600) + return Load(p) + } + c, err := load("[time]\nservers = nts time.cloudflare.com, ptp 192.0.2.1\npoll = 32\n[ntp]\naddress = 127.0.0.1:1123\n") + if err != nil { + t.Fatal(err) + } + ts := c.Time + if len(ts.Sync.Servers) != 2 || ts.Sync.Poll.Seconds() != 32 || ts.NTP.Address != "127.0.0.1:1123" || + ts.NTP.Rate != 2 || ts.PTP == nil || ts.PTP.Master || ts.UTCOffset != 37 { + t.Errorf("%+v %+v", ts, ts.PTP) + } + if c, err = load("[ptp]\ndomain = 4\nlog_min_interval = -2\n"); err != nil || !c.Time.PTP.Master || + c.Time.PTP.Domain != 4 || c.Time.PTP.MinLog != -2 || c.Time.PTP.Multicast || !c.Time.PTP.Unicast { + t.Errorf("%+v %v", c.Time.PTP, err) + } + for conf, want := range map[string]string{ + "[nts]\ntls_cert = x\ntls_key = y\n": "needs [ntp]", + "[ntp]\n[nts]\n": "tls_cert", + "[time]\nservers = sntp x\n": "servers", + "[ptp]\nmulticast = yes\n": "interface", + "[ptp]\ntimestamping = hardware\n": "interface", + "[ptp]\naddress = eth0\n": "address", + "[time]\nrefid = TOOLONG\n": "refid", + "[ntp]\naddress = 123\n": "address", + } { + if _, err := load(conf); err == nil || !strings.Contains(err.Error(), want) { + t.Errorf("%q: %v", conf, err) + } + } + if c, _ := load(""); c.Time != nil { + t.Error("time without its sections") + } +} diff --git a/internal/timesync/clock.go b/internal/timesync/clock.go index bdd0a57..72a3ef0 100644 --- a/internal/timesync/clock.go +++ b/internal/timesync/clock.go @@ -58,7 +58,7 @@ type Local struct { // servers it follows measure, or the system's set by it. type Clock struct { Local Local - SetClock bool // sets the system clock (else corrects its own reading) + SetClock bool // sets the system clock (else corrects its own reading) Log func(string, ...any) // nil: none mu sync.Mutex @@ -115,6 +115,11 @@ func (c *Clock) local() Ref { Updated: time.Now().Truncate(time.Minute), TimeSrc: SourceInternal, RefID: refASCII("LOCL")} if c.Local.Stratum > 0 { r.Synced, r.Stratum = true, uint8(c.Local.Stratum) + if !k.synced { + // the kernel's error bound is its unsynchronised 16 s: the + // sysop says better + r.RootDisp = time.Millisecond + } if r.Stratum == 1 && c.Local.RefID != "" { r.RefID = refASCII(c.Local.RefID) r.TimeSrc = SourceOther diff --git a/internal/timesync/ntp.go b/internal/timesync/ntp.go index c84811d..5e1ea9e 100644 --- a/internal/timesync/ntp.go +++ b/internal/timesync/ntp.go @@ -47,10 +47,10 @@ const precision = -20 // NTS-KE server's keys. type NTPServer struct { Clock *Clock - Keys ntske.Keystore // nil: NTS-secured requests answered as plain ones - Refuse func(net.IP) bool // nil: none refused - Rate float64 // requests a second an address may make (0: no limit) - Burst int // and at once + Keys ntske.Keystore // nil: NTS-secured requests answered as plain ones + Refuse func(net.IP) bool // nil: none refused + Rate float64 // requests a second an address may make (0: no limit) + Burst int // and at once Log func(string, ...any) // nil: none lim limiter diff --git a/internal/timesync/ptp.go b/internal/timesync/ptp.go index fc47650..c069dd6 100644 --- a/internal/timesync/ptp.go +++ b/internal/timesync/ptp.go @@ -25,14 +25,14 @@ const ( // PTPSettings are the [ptp] section's. type PTPSettings struct { - Address string // the address bound ("": all), on ports 319 and 320 - Interface string // multicast's, and hardware timestamps' ("": no multicast) - Master bool // a grandmaster ([ptp]); else only a client of ptp servers - Multicast bool // sends announcements and syncs to the group on Interface - Unicast bool // grants unicast transmission to clients that ask - Domain uint8 - Priority1 uint8 - Priority2 uint8 + Address string // the address bound ("": all), on ports 319 and 320 + Interface string // multicast's, and hardware timestamps' ("": no multicast) + Master bool // a grandmaster ([ptp]); else only a client of ptp servers + Multicast bool // sends announcements and syncs to the group on Interface + Unicast bool // grants unicast transmission to clients that ask + Domain uint8 + Priority1 uint8 + Priority2 uint8 SyncLog int8 // multicast syncs every 2^SyncLog seconds AnnounceLog int8 MinLog int8 // the shortest interval granted unicast clients (2^MinLog s) @@ -71,7 +71,7 @@ type PTP struct { wmu sync.Mutex // an event packet's write and the reading of its stamp mu sync.Mutex - grants map[string]*grant // unicast clients, by address + grants map[string]*grant // unicast clients, by address clients map[string]*ptpUpstream // servers followed, by address seq [2]uint16 // announce and sync sequence numbers: one count for all // (multicast and every unicast client), so one that gets both never @@ -562,15 +562,15 @@ type ptpUpstream struct { host string ip net.IP - mu sync.Mutex - ann *ptp.Announce - granted time.Time // the sync grant's end - syncs map[uint16]time.Time // a Sync's arrival, by sequence, till its Follow_Up - t1, t2 time.Time // the last sync's: when it went (TAI) and came - reqSeq uint16 - reqs map[uint16]time.Time // a Delay_Req's sending, by sequence - sigSeq uint16 - samples []Sample + mu sync.Mutex + ann *ptp.Announce + granted time.Time // the sync grant's end + syncs map[uint16]time.Time // a Sync's arrival, by sequence, till its Follow_Up + t1, t2 time.Time // the last sync's: when it went (TAI) and came + reqSeq uint16 + reqs map[uint16]time.Time // a Delay_Req's sending, by sequence + sigSeq uint16 + samples []Sample } // run asks for unicast transmission and keeps asking before it runs out. diff --git a/internal/timesync/stamp_linux.go b/internal/timesync/stamp_linux.go index 4585524..f503d9f 100644 --- a/internal/timesync/stamp_linux.go +++ b/internal/timesync/stamp_linux.go @@ -1,11 +1,11 @@ package timesync import ( + "encoding/binary" "errors" "net" "time" - "github.com/facebook/time/timestamp" "golang.org/x/sys/unix" ) @@ -19,19 +19,26 @@ func EnableTimestamps(c *net.UDPConn, hardware bool, iface string) error { } var serr error err = rc.Control(func(fd uintptr) { - if !hardware { - serr = timestamp.EnableSWTimestamps(int(fd)) - return + flags := unix.SOF_TIMESTAMPING_TX_SOFTWARE | unix.SOF_TIMESTAMPING_RX_SOFTWARE | unix.SOF_TIMESTAMPING_SOFTWARE + if hardware { + if stamping(int(fd))&unix.SOF_TIMESTAMPING_TX_HARDWARE != 0 { + return // on already: as root, before + } + cfg := &unix.HwTstampConfig{Tx_type: unix.HWTSTAMP_TX_ON, Rx_filter: unix.HWTSTAMP_FILTER_ALL} + if serr = unix.IoctlSetHwTstamp(int(fd), iface, cfg); serr != nil { + // some cards stamp PTP's event packets alone + cfg.Rx_filter = unix.HWTSTAMP_FILTER_PTP_V2_EVENT + if serr = unix.IoctlSetHwTstamp(int(fd), iface, cfg); serr != nil { + return + } + } + flags = unix.SOF_TIMESTAMPING_TX_HARDWARE | unix.SOF_TIMESTAMPING_RX_HARDWARE | unix.SOF_TIMESTAMPING_RAW_HARDWARE } - if already(int(fd)) { - return // as root, before + flags |= unix.SOF_TIMESTAMPING_OPT_TSONLY + // the 64-bit stamps (Linux 5.1), else the old ones + if serr = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_TIMESTAMPING_NEW, flags); serr != nil { + serr = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_TIMESTAMPING_OLD, flags) } - ifc, err := net.InterfaceByName(iface) - if err != nil { - serr = err - return - } - serr = timestamp.EnableHWTimestamps(int(fd), ifc) }) if err != nil { return err @@ -39,39 +46,114 @@ func EnableTimestamps(c *net.UDPConn, hardware bool, iface string) error { return serr } -// already: hardware stamps are on (set as root, the socket handed down). -func already(fd int) bool { - v, err := unix.GetsockoptInt(fd, unix.SOL_SOCKET, unix.SO_TIMESTAMPING_NEW) - if err != nil { - v, err = unix.GetsockoptInt(fd, unix.SOL_SOCKET, unix.SO_TIMESTAMPING) +// stamping is the socket's SO_TIMESTAMPING flags. +func stamping(fd int) int { + if v, err := unix.GetsockoptInt(fd, unix.SOL_SOCKET, unix.SO_TIMESTAMPING_NEW); err == nil { + return v } - return err == nil && v&unix.SOF_TIMESTAMPING_TX_HARDWARE != 0 + v, _ := unix.GetsockoptInt(fd, unix.SOL_SOCKET, unix.SO_TIMESTAMPING_OLD) + return v +} + +// stampOf is the time in a SO_TIMESTAMPING control message: of its three +// stamps, the software one or else the network card's. +func stampOf(oob []byte) (time.Time, bool) { + msgs, err := unix.ParseSocketControlMessage(oob) + if err != nil { + return time.Time{}, false + } + for _, m := range msgs { + if m.Header.Level != unix.SOL_SOCKET { + continue + } + var ts [3]time.Time + switch m.Header.Type { + case unix.SO_TIMESTAMPING_NEW: // struct __kernel_timespec: two int64s + if len(m.Data) < 48 { + continue + } + for i := range ts { + s := int64(binary.NativeEndian.Uint64(m.Data[i*16:])) + ns := int64(binary.NativeEndian.Uint64(m.Data[i*16+8:])) + ts[i] = time.Unix(s, ns) + } + case unix.SO_TIMESTAMPING_OLD: // struct timespec: two longs + n := len(m.Data) / 6 + if n != 4 && n != 8 { + continue + } + for i := range ts { + s, ns := word(m.Data[2*i*n:], n), word(m.Data[(2*i+1)*n:], n) + ts[i] = time.Unix(s, ns) + } + default: + continue + } + for _, t := range []time.Time{ts[0], ts[2]} { + if t.Unix() != 0 || t.Nanosecond() != 0 { + return t, true + } + } + } + return time.Time{}, false +} + +func word(b []byte, n int) int64 { + if n == 4 { + return int64(int32(binary.NativeEndian.Uint32(b))) + } + return int64(binary.NativeEndian.Uint64(b)) } // rxStamp is a received packet's stamp from its control messages. -func rxStamp(oob []byte) (time.Time, bool) { - t, err := timestamp.ReadRXTimestamp(oob, len(oob)) - return t, err == nil && !t.IsZero() -} +func rxStamp(oob []byte) (time.Time, bool) { return stampOf(oob) } -// txStamp is the stamp of the packet c sent last. +// txWait is how long the stamp of a packet sent is waited for. +const txWait = 10 * time.Millisecond + +// txStamp is the stamp of the packet c sent last: read from the socket's +// error queue, which is emptied (a stamp late from before is not taken +// for this one's). func txStamp(c *net.UDPConn) (time.Time, error) { rc, err := c.SyscallConn() if err != nil { return time.Time{}, err } var t time.Time - var serr error - if err := rc.Control(func(fd uintptr) { t, _, serr = timestamp.ReadTXtimestamp(int(fd)) }); err != nil { + found := false + err = rc.Control(func(fd uintptr) { + oob := make([]byte, 256) + deadline := time.Now().Add(txWait) + for { + _, oobn, _, _, err := unix.Recvmsg(int(fd), nil, oob, unix.MSG_ERRQUEUE|unix.MSG_DONTWAIT) + if err == nil { + if st, ok := stampOf(oob[:oobn]); ok { + t, found = st, true + } + continue + } + if found || !errors.Is(err, unix.EAGAIN) { + return + } + left := time.Until(deadline) + if left <= 0 { + return + } + to := unix.NsecToTimespec(left.Nanoseconds()) + unix.Ppoll([]unix.PollFd{{Fd: int32(fd), Events: unix.POLLERR}}, &to, nil) + } + }) + if err != nil { return time.Time{}, err } - if serr == nil && t.IsZero() { - serr = errors.New("no transmit stamp") + if !found { + return time.Time{}, errors.New("no transmit stamp") } - return t, serr + return t, nil } -// joinGroup has c take a multicast group's packets on iface. +// joinGroup has c take a multicast group's packets on iface, and send +// multicast there. func joinGroup(c *net.UDPConn, iface *net.Interface, group net.IP) error { rc, err := c.SyscallConn() if err != nil { @@ -79,11 +161,12 @@ func joinGroup(c *net.UDPConn, iface *net.Interface, group net.IP) error { } var serr error if err := rc.Control(func(fd uintptr) { - if serr = timestamp.JoinMulticast(int(fd), iface, group); serr != nil { + mreq := &unix.IPMreqn{Ifindex: int32(iface.Index)} + copy(mreq.Multiaddr[:], group.To4()) + if serr = unix.SetsockoptIPMreqn(int(fd), unix.IPPROTO_IP, unix.IP_ADD_MEMBERSHIP, mreq); serr != nil { return } - mreq := &unix.IPMreqn{Ifindex: int32(iface.Index)} - serr = unix.SetsockoptIPMreqn(int(fd), unix.IPPROTO_IP, unix.IP_MULTICAST_IF, mreq) + serr = unix.SetsockoptIPMreqn(int(fd), unix.IPPROTO_IP, unix.IP_MULTICAST_IF, &unix.IPMreqn{Ifindex: int32(iface.Index)}) }); err != nil { return err } diff --git a/internal/timesync/sysclock_other.go b/internal/timesync/sysclock_other.go index ed2fd88..59dbcfb 100644 --- a/internal/timesync/sysclock_other.go +++ b/internal/timesync/sysclock_other.go @@ -18,5 +18,5 @@ func kernelStatus() kernel { return kernel{synced: true} } var errNoSet = errors.New("setting the clock is done on Linux only") -func stepClock(time.Duration) error { return errNoSet } +func stepClock(time.Duration) error { return errNoSet } func slewClock(_, _ time.Duration) error { return errNoSet } diff --git a/mkdocs.yml b/mkdocs.yml index 7d051a6..c13f208 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -53,6 +53,7 @@ nav: - "AIM and ICQ": AIM-and-ICQ.md - "MRC": MRC.md - "Finger and gopher": Finger-and-Gopher.md + - "Time: NTP, NTS and PTP": Time.md - "Web forum": Web-Forum.md - "Image boards": Image-Boards.md - "HTTP API": HTTP-API.md