This repository has been archived by the owner on Jan 16, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.go
102 lines (81 loc) · 2.15 KB
/
server.go
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package main
import (
"net"
"os"
"strconv"
"strings"
"time"
"github.com/miekg/dns"
)
type server struct {
host string
port int
maxjobs int
maxqueries int
handler *gnoccoHandler
}
func (s *server) Addr() string {
return net.JoinHostPort(s.host, strconv.Itoa(s.port))
}
func (s *server) dumpCache() {
logger.Info("Dumping cache at %v", time.Now())
files := []string{mainconfig.Cache.CachePath + "/pcache", mainconfig.Cache.CachePath + "/ncache"}
for _, file := range files {
_ = os.MkdirAll(mainconfig.Cache.CachePath, 0755)
if fl, err := os.Create(file); err == nil {
defer fl.Close()
if strings.HasSuffix(file, "pcache") {
s.handler.Cache.dump(fl, true)
} else {
s.handler.Cache.dump(fl, false)
}
} else {
logger.Error("%s", err)
}
}
}
func (s *server) run() {
s.handler = newHandler(s.maxjobs)
if _, err := os.Stat(mainconfig.Cache.CachePath + "/pcache"); err == nil {
var file, err = os.OpenFile(mainconfig.Cache.CachePath+"/pcache", os.O_RDWR, 0644)
if err == nil {
s.handler.Cache.load(file, true)
}
}
if _, err := os.Stat(mainconfig.Cache.CachePath + "/ncache"); err == nil {
var file, err = os.OpenFile(mainconfig.Cache.CachePath+"/ncache", os.O_RDWR, 0644)
if err == nil {
s.handler.Cache.load(file, false)
}
}
tcpHandler := dns.NewServeMux()
tcpHandler.HandleFunc(".", s.handler.doTCP)
tcpServer := &dns.Server{Addr: s.Addr(),
Net: "tcp",
Handler: tcpHandler}
go s.start(tcpServer)
udpHandler := dns.NewServeMux()
udpHandler.HandleFunc(".", s.handler.doUDP)
udpServer := &dns.Server{Addr: s.Addr(),
Net: "udp",
Handler: udpHandler,
UDPSize: 65535}
go s.start(udpServer)
go s.startCacheDumping()
}
func (s *server) start(ds *dns.Server) {
logger.Info("Start %s listener on %s", ds.Net, ds.Addr)
err := ds.ListenAndServe()
if err != nil {
logger.Fatal("Start %s listener on %s failed:%s", ds.Net, ds.Addr, err.Error())
}
}
func (s *server) shutDown() {
logger.Info("Shutdown called.")
}
func (s *server) startCacheDumping() {
interval := mainconfig.Cache.DumpInterval
for _ = range time.Tick(time.Duration(interval) * time.Second) {
s.dumpCache()
}
}