aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--License9
-rw-r--r--Readme.md43
-rw-r--r--engine/internal.go165
-rw-r--r--getter/time-app.go185
-rw-r--r--go.mod3
-rw-r--r--main.go61
-rw-r--r--network/protocol.go39
7 files changed, 505 insertions, 0 deletions
diff --git a/License b/License
new file mode 100644
index 0000000..d99884b
--- /dev/null
+++ b/License
@@ -0,0 +1,9 @@
+MIT License
+
+Copyright (c) 2020 Sina Ghaderi
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/Readme.md b/Readme.md
new file mode 100644
index 0000000..78a93cb
--- /dev/null
+++ b/Readme.md
@@ -0,0 +1,43 @@
+# Nano NTP
+An NTP server implementation in golang base on [btfak](https://github.com/btfak/sntp) and [beevik](https://github.com/beevik/ntp)
+This NTP Server first acts like a ntp relay and ask time from upstream NTP servers, if relay can't reach them, then will pass it's own local time to the clients
+
+### Installation
+Installation for linux, runing only on linux. ([TinyCore Linux 32-bit](http://tinycorelinux.net/11.x/x86/release) Is Recommended)
+
+```
+# go get https://github.com/sina-ghaderi/nanontp.git
+# cd nanontp
+# GOOS=linux go build -o ntp-amd64 # 64-Bit Build
+# GOOS=linux GOARCH=386 go build -o ntp-i386 # 32-Bit Build
+
+```
+
+### Usage and Options
+```
+usage of snix ntp server:
+./ntp-server -net [ipv4:port] ntp-domain.com:port ntp-domain.org:port ...
+
+options:
+ --net string udp network to listen on <ipv4:port> (default "0.0.0.0:123")
+ --h print this banner and exit
+example:
+ ./nanontp --net 0.0.0.0:123 time.google.com:123 ntp.day.ir:123 10.10.10.10:123
+
+Copyright (c) 2020 slc.snix.ir, All rights reserved.
+Developed BY a.esmaeilpour@irisaco.com And s.ghaderi1999@gmail.com
+This work is licensed under the terms of the MIT license.
+
+```
+
+### Runing Nano NTP
+```
+# ./ntp-amd64 -net 0.0.0.0:123 ntp.day.ir:123 132.163.96.5:123 129.6.15.27:123
+2020/08/21 20:41:31 ntp server listening on (UDP) 0.0.0.0:123
+------------------ Logs and Errors ------------------
+2020/08/21 20:44:20 request ---> asking for time from 127.0.0.1:60924
+2020/08/21 20:44:20 access ----> trying to ntp server: ntp.day.ir:123
+2020/08/21 20:44:21 success ---> time received from: ntp.day.ir:123
+2020/08/21 20:44:21 response --> answering to the client 127.0.0.1:60924
+
+```
diff --git a/engine/internal.go b/engine/internal.go
new file mode 100644
index 0000000..367807d
--- /dev/null
+++ b/engine/internal.go
@@ -0,0 +1,165 @@
+package engine
+
+import (
+ "fmt"
+ "log"
+ "net"
+ "runtime"
+ "strconv"
+ "time"
+)
+
+type Transport interface {
+ Write(data string, addr string, port int)
+}
+
+type udpTransport struct {
+ conn *net.UDPConn
+}
+
+func (p *udpTransport) setConn(conn *net.UDPConn) {
+ p.conn = conn
+}
+
+func (p *udpTransport) Write(data string, addr string, port int) {
+ laddr, err := net.ResolveUDPAddr("udp", addr+":"+strconv.Itoa(port))
+ if err != nil {
+ fmt.Println("resolve addr err: ", err)
+ return
+ }
+ _, er := p.conn.WriteTo([]byte(data), laddr)
+ if er != nil {
+ fmt.Println("resolve addr err: ", err)
+ return
+ }
+}
+
+type _reactor struct {
+ udp_listeners map[int]UdpClient
+ udp_conn map[int]*net.UDPConn
+ timer []*LaterCalling
+}
+
+func (p *_reactor) ListenUdp(addaport string, udp UdpClient) {
+ laddr, err := net.ResolveUDPAddr("udp", addaport)
+ if err == nil {
+ p.listenUdp(laddr, udp)
+ } else {
+ log.Println("resolve addr err: ", err)
+ return
+ }
+}
+
+type UdpClient interface {
+ DatagramReceived(data []byte, addr net.Addr)
+ SetUdpTransport(Transport)
+}
+
+func (p *_reactor) listenUdp(addr *net.UDPAddr, udp UdpClient) {
+ p.initReactor()
+ p.udp_listeners[addr.Port] = udp
+ log.Println("ntp server listening on (UDP)", addr.String())
+ c, erl := net.ListenUDP("udp", addr)
+ if erl != nil {
+ log.Fatal("listen error: ", erl)
+ } else {
+ p.udp_conn[addr.Port] = c
+ }
+ transport := new(udpTransport)
+ transport.setConn(c)
+ udp.SetUdpTransport(transport)
+}
+
+func (p *_reactor) initReactor() {
+ if p.udp_listeners == nil {
+ p.udp_listeners = make(map[int]UdpClient)
+ }
+ if p.udp_conn == nil {
+ p.udp_conn = make(map[int]*net.UDPConn)
+ }
+}
+
+var (
+ Reactor = new(_reactor)
+ listening_chan chan int
+)
+
+type LaterCalling struct {
+ millisecond int
+ call func()
+}
+
+type reactor interface {
+ ListenUdp(port int, client UdpClient)
+ CallLater(microsecond int, latercaller func())
+ Run()
+}
+
+func (p *_reactor) CallLater(millisecond int, lc func()) {
+ calling := new(LaterCalling)
+ calling.millisecond = millisecond
+ calling.call = lc
+ p.timer = append(p.timer, calling)
+}
+
+func (p *_reactor) Run() {
+ runtime.GOMAXPROCS(len(p.udp_conn))
+ for port, l := range p.udp_conn {
+ go handleUdpConnection(l, p.udp_listeners[port])
+ }
+ for len(p.timer) > 0 {
+ caller := p.timer[0]
+ p.timer = p.timer[1:]
+ selectTimer(caller)
+ }
+ for {
+ fmt.Println("------------------ Logs and Errors ------------------")
+ select {
+ case <-listening_chan:
+ fmt.Println("-----------------------------------------------------")
+
+ }
+ }
+}
+
+func selectTimer(caller *LaterCalling) {
+ select {
+ case <-time.After(time.Duration(caller.millisecond) * time.Millisecond):
+ caller.call()
+ }
+}
+
+func handleUdpConnection(conn *net.UDPConn, client UdpClient) {
+ for {
+ data := make([]byte, 512)
+ read_length, remoteAddr, err := conn.ReadFromUDP(data[0:])
+ if err != nil {
+ return
+ } else {
+ }
+ if read_length > 0 {
+ go panicWrapping(func() {
+ client.DatagramReceived(data[0:read_length], remoteAddr)
+ })
+ }
+ }
+}
+
+func panicWrapping(f func()) {
+ defer func() {
+ recover()
+ }()
+ f()
+}
+
+type UdpHandler struct {
+ udptransport Transport
+}
+
+func (p *UdpHandler) SetUdpTransport(transport Transport) {
+ p.udptransport = transport
+}
+
+func (p *UdpHandler) UdpWrite(data string, addr string, port int) {
+ p.udptransport.Write(data, addr, port)
+}
diff --git a/getter/time-app.go b/getter/time-app.go
new file mode 100644
index 0000000..cd91751
--- /dev/null
+++ b/getter/time-app.go
@@ -0,0 +1,185 @@
+package getter
+
+import (
+ "encoding/binary"
+ "errors"
+ "log"
+ "net"
+ "time"
+)
+
+const (
+ InfoColor = "\033[1;34m%s\033[0m"
+ NoticeColor = "\033[1;36m%s\033[0m"
+ WarningColor = "\033[1;33m%s\033[0m"
+ ErrorColor = "\033[1;31m%s\033[0m"
+ DebugColor = "\033[0;36m%s\033[0m"
+)
+const (
+ LI_NO_WARNING = 0
+ LI_ALARM_CONDITION = 3
+ VN_FIRST = 1
+ VN_LAST = 4
+ MODE_CLIENT = 3
+ FROM_1900_TO_1970 = 2208988800
+)
+
+func Serve(req []byte, addr net.Addr) ([]byte, error) {
+ if validFormat(req) {
+ res := generate(req, addr)
+ return res, nil
+ }
+ return []byte{}, errors.New("invalid format.")
+}
+
+func validFormat(req []byte) bool {
+ var l = req[0] >> 6
+ var v = (req[0] << 2) >> 5
+ var m = (req[0] << 5) >> 5
+ if (l == LI_NO_WARNING) || (l == LI_ALARM_CONDITION) {
+ if (v >= VN_FIRST) && (v <= VN_LAST) {
+ if m == MODE_CLIENT {
+ return true
+ }
+ }
+ }
+ return false
+}
+func unix2ntp(u int64) int64 {
+ return u + FROM_1900_TO_1970
+}
+
+func ntp2unix(n int64) int64 {
+ return n - FROM_1900_TO_1970
+}
+
+func int2bytes(i int64) []byte {
+ var b = make([]byte, 4)
+ h1 := i >> 24
+ h2 := (i >> 16) - (h1 << 8)
+ h3 := (i >> 8) - (h1 << 16) - (h2 << 8)
+ h4 := byte(i)
+ b[0] = byte(h1)
+ b[1] = byte(h2)
+ b[2] = byte(h3)
+ b[3] = byte(h4)
+ return b
+}
+
+func NTPPickup(upntp []string, ClientIP net.Addr) time.Time {
+ for _, addr := range upntp {
+ log.Println("\033[1;34mrequest\033[0m ---> asking for time from", ClientIP)
+ log.Println("\033[1;36maccess\033[0m ----> trying to ntp server:", addr)
+ custom, err := ntpaccessclient(addr)
+ if err == nil {
+ log.Println("\033[1;32msuccess\033[0m ---> time received from:", addr)
+ log.Println("\033[1;32mresponse\033[0m --> answering to the client", ClientIP)
+ return custom
+ }
+ log.Printf("\033[1;31merror\033[0m -----> ntp address: %v (%v)\n", addr, err)
+
+ }
+ log.Println("\033[1;31merror\033[0m -----> can not get anything from ntp servers!")
+ log.Println("\033[1;33mwarining\033[0m --> passing system time to client (might be wrong!)")
+ return time.Now()
+}
+
+var ArgNTP []string
+
+func generate(req []byte, addr net.Addr) []byte {
+ custom := NTPPickup(ArgNTP, addr)
+ var second = unix2ntp(custom.Unix())
+ var fraction = unix2ntp(int64(custom.Nanosecond()))
+ var res = make([]byte, 48)
+ var vn = req[0] & 0x38
+ res[0] = vn + 4
+ res[1] = 1
+ res[2] = req[2]
+ res[3] = 0xEC
+ res[12] = 0x4E
+ res[13] = 0x49
+ res[14] = 0x43
+ res[15] = 0x54
+ copy(res[16:20], int2bytes(second)[0:])
+ copy(res[24:32], req[40:48])
+ copy(res[32:36], int2bytes(second)[0:])
+ copy(res[36:40], int2bytes(fraction)[0:])
+ copy(res[40:48], res[32:40])
+ return res
+}
+
+type mode byte
+
+const (
+ reserved mode = 0 + iota
+ symmetricActive
+ symmetricPassive
+ client
+ server
+ broadcast
+ controlMessage
+ reservedPrivate
+)
+
+type ntpTime struct {
+ Seconds uint32
+ Fraction uint32
+}
+
+func (t ntpTime) UTC() time.Time {
+ nsec := uint64(t.Seconds)*1e9 + (uint64(t.Fraction) * 1e9 >> 32)
+ return time.Date(1900, 1, 1, 0, 0, 0, 0, time.UTC).Add(time.Duration(nsec))
+}
+
+type msg struct {
+ LiVnMode byte
+ Stratum byte
+ Poll byte
+ Precision byte
+ RootDelay uint32
+ RootDispersion uint32
+ ReferenceId uint32
+ ReferenceTime ntpTime
+ OriginTime ntpTime
+ ReceiveTime ntpTime
+ TransmitTime ntpTime
+}
+
+func (m *msg) SetVersion(v byte) {
+ m.LiVnMode = (m.LiVnMode & 0xc7) | v<<3
+}
+
+func (m *msg) SetMode(md mode) {
+ m.LiVnMode = (m.LiVnMode & 0xf8) | byte(md)
+}
+
+func ntpaccessclient(host string) (time.Time, error) {
+ raddr, err := net.ResolveUDPAddr("udp", host)
+ if err != nil {
+ return time.Now(), err
+ }
+
+ con, err := net.DialUDP("udp", nil, raddr)
+ if err != nil {
+ return time.Now(), err
+ }
+ defer con.Close()
+ con.SetDeadline(time.Now().Add(5 * time.Second))
+
+ m := new(msg)
+ m.SetMode(client)
+ m.SetVersion(4)
+
+ err = binary.Write(con, binary.BigEndian, m)
+ if err != nil {
+ return time.Now(), err
+ }
+
+ err = binary.Read(con, binary.BigEndian, m)
+ if err != nil {
+ return time.Now(), err
+ }
+
+ t := m.ReceiveTime.UTC().Local()
+ return t, nil
+}
diff --git a/go.mod b/go.mod
new file mode 100644
index 0000000..4a222ff
--- /dev/null
+++ b/go.mod
@@ -0,0 +1,3 @@
+module snix.ir/nanontp
+
+go 1.18
diff --git a/main.go b/main.go
new file mode 100644
index 0000000..c43fb0b
--- /dev/null
+++ b/main.go
@@ -0,0 +1,61 @@
+package main
+
+import (
+ "flag"
+ "fmt"
+ "os"
+ "regexp"
+
+ "snix.ir/nanontp/engine"
+ "snix.ir/nanontp/getter"
+ "snix.ir/nanontp/network"
+)
+
+const regIPPORT string = "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]):()([1-9]|[1-5]?[0-9]{2,4}|6[1-4][0-9]{3}|65[1-4][0-9]{2}|655[1-2][0-9]|6553[1-5])$"
+const regDomainIPport string = "^(((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)|((\\*\\.)?([a-zA-Z0-9-]+\\.){0,5}[a-zA-Z0-9-][a-zA-Z0-9-]+\\.[a-zA-Z]{2,63}?)):([1-9]|[1-5]?[0-9]{2,4}|6[1-4][0-9]{3}|65[1-4][0-9]{2}|655[1-2][0-9]|6553[1-5])$"
+
+func main() {
+ flag.Usage = usage
+ ipup := flag.String("net", "0.0.0.0:123", "udp network to listen on <ipv4:port>")
+ flag.Parse()
+ if match, _ := regexp.MatchString(regIPPORT, *ipup); !match {
+ fmt.Printf("fatal: %v is not a valid <ipv4:port> address\n", *ipup)
+ flag.Usage()
+ os.Exit(2)
+ }
+ getter.ArgNTP = flag.Args()
+
+ if len(getter.ArgNTP) == 0 {
+ fmt.Println("fatal: you must give me a upstream ntp server <ipv4-or-domain:port>")
+ flag.Usage()
+ os.Exit(2)
+
+ }
+ for _, x := range getter.ArgNTP {
+ if match, _ := regexp.MatchString(regDomainIPport, x); !match {
+ fmt.Printf("fatal: %v is not a valid ntp upstream address\n", x)
+ flag.Usage()
+ os.Exit(2)
+ }
+ }
+
+ var handler = network.GetHandler()
+ engine.Reactor.ListenUdp(*ipup, handler)
+ engine.Reactor.Run()
+}
+
+func usage() {
+ fmt.Printf(`usage of snix ntp server:
+%v -net [ipv4:port] ntp-domain.com:port ntp-domain.org:port ...
+
+options:
+ --net string udp network to listen on <ipv4:port> (default "0.0.0.0:123")
+ --h print this banner and exit
+example:
+ %v --net 0.0.0.0:123 time.google.com:123 ntp.day.ir:123 10.10.10.10:123
+
+Copyright (c) 2020 slc.snix.ir, All rights reserved.
+Developed BY a.esmaeilpour@irisaco.com And s.ghaderi1999@gmail.com
+This work is licensed under the terms of the MIT license.
+`, os.Args[0], os.Args[0])
+}
diff --git a/network/protocol.go b/network/protocol.go
new file mode 100644
index 0000000..e7c2536
--- /dev/null
+++ b/network/protocol.go
@@ -0,0 +1,39 @@
+package network
+
+import (
+ "net"
+ "strconv"
+ "strings"
+
+ "snix.ir/nanontp/engine"
+ "snix.ir/nanontp/getter"
+)
+
+var handler *Handler
+
+type Handler struct {
+ engine.UdpHandler
+}
+
+func GetHandler() *Handler {
+ if handler == nil {
+ handler = new(Handler)
+ }
+ return handler
+}
+
+var UDPRemoteAddr *net.UDPAddr
+
+func (p *Handler) DatagramReceived(data []byte, addr net.Addr) {
+ res, err := getter.Serve(data, addr)
+ if err == nil {
+ ip, port := spliteAddr(addr.String())
+ p.UdpWrite(string(res), ip, port)
+ }
+}
+func spliteAddr(addr string) (string, int) {
+ ip := strings.Split(addr, ":")[0]
+ port := strings.Split(addr, ":")[1]
+ p, _ := strconv.Atoi(port)
+ return ip, p
+}

Snix LLC Git Repository Holder Copyright(C) 2022 All Rights Reserved Email To Snix.IR