Skip to content

Commit e8129f1

Browse files
committed
* refactor
1. Auth module was initialized inside dns.go - now it's moved to initWeb() 2. stopHTTPServer() wasn't called on server stop - now we do that 3. Don't use postInstall() HTTP filter where it's not necessary. Now we register handlers after installation is complete.
1 parent c779076 commit e8129f1

File tree

7 files changed

+74
-35
lines changed

7 files changed

+74
-35
lines changed

dhcpd/dhcpd.go

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ import (
1818
const defaultDiscoverTime = time.Second * 3
1919
const leaseExpireStatic = 1
2020

21+
var webHandlersRegistered = false
22+
2123
// Lease contains the necessary information about a DHCP lease
2224
// field ordering is important -- yaml fields will mirror ordering from here
2325
type Lease struct {
@@ -121,9 +123,6 @@ func Create(config ServerConfig) *Server {
121123
return nil
122124
}
123125
}
124-
if s.conf.HTTPRegister != nil {
125-
s.registerHandlers()
126-
}
127126

128127
// we can't delay database loading until DHCP server is started,
129128
// because we need static leases functionality available beforehand
@@ -221,6 +220,11 @@ func (s *Server) setConfig(config ServerConfig) error {
221220
// Start will listen on port 67 and serve DHCP requests.
222221
func (s *Server) Start() error {
223222

223+
if !webHandlersRegistered && s.conf.HTTPRegister != nil {
224+
webHandlersRegistered = true
225+
s.registerHandlers()
226+
}
227+
224228
// TODO: don't close if interface and addresses are the same
225229
if s.conn != nil {
226230
s.closeConn()

home/clients.go

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@ const (
2424
clientsUpdatePeriod = 1 * time.Hour
2525
)
2626

27+
var webHandlersRegistered = false
28+
2729
// Client information
2830
type Client struct {
2931
IDs []string
@@ -98,13 +100,21 @@ func (clients *clientsContainer) Init(objects []clientObject, dhcpServer *dhcpd.
98100
clients.addFromConfig(objects)
99101

100102
if !clients.testing {
101-
go clients.periodicUpdate()
102-
103103
clients.addFromDHCP()
104104
clients.dhcpServer.SetOnLeaseChanged(clients.onDHCPLeaseChanged)
105+
}
106+
}
105107

106-
clients.registerWebHandlers()
108+
// Start - start the module
109+
func (clients *clientsContainer) Start() {
110+
if !clients.testing {
111+
if !webHandlersRegistered {
112+
webHandlersRegistered = true
113+
clients.registerWebHandlers()
114+
}
115+
go clients.periodicUpdate()
107116
}
117+
108118
}
109119

110120
// Reload - reload auto-clients

home/control.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -258,12 +258,14 @@ func preInstallHandler(handler http.Handler) http.Handler {
258258
// it also enforces HTTPS if it is enabled and configured
259259
func postInstall(handler func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) {
260260
return func(w http.ResponseWriter, r *http.Request) {
261+
261262
if Context.firstRun &&
262263
!strings.HasPrefix(r.URL.Path, "/install.") &&
263264
r.URL.Path != "/favicon.png" {
264-
http.Redirect(w, r, "/install.html", http.StatusSeeOther) // should not be cacheable
265+
http.Redirect(w, r, "/install.html", http.StatusFound)
265266
return
266267
}
268+
267269
// enforce https?
268270
if config.TLS.ForceHTTPS && r.TLS == nil && config.TLS.Enabled && config.TLS.PortHTTPS != 0 && Context.httpsServer.server != nil {
269271
// yes, and we want host from host:port
@@ -282,6 +284,7 @@ func postInstall(handler func(http.ResponseWriter, *http.Request)) func(http.Res
282284
http.Redirect(w, r, newURL.String(), http.StatusTemporaryRedirect)
283285
return
284286
}
287+
285288
w.Header().Set("Access-Control-Allow-Origin", "*")
286289
handler(w, r)
287290
}

home/control_install.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -356,6 +356,8 @@ func handleInstallConfigure(w http.ResponseWriter, r *http.Request) {
356356
return
357357
}
358358

359+
registerControlHandlers()
360+
359361
// this needs to be done in a goroutine because Shutdown() is a blocking call, and it will block
360362
// until all requests are finished, and _we_ are inside a request right now, so it will block indefinitely
361363
if restartHTTP {

home/control_update.go

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -476,7 +476,6 @@ func doUpdate(u *updateInfo) error {
476476
func finishUpdate(u *updateInfo) {
477477
log.Info("Stopping all tasks")
478478
cleanup()
479-
stopHTTPServer()
480479
cleanupAlways()
481480

482481
if runtime.GOOS == "windows" {

home/dns.go

Lines changed: 3 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ package home
33
import (
44
"fmt"
55
"net"
6-
"os"
76
"path/filepath"
87

98
"github.com/AdguardTeam/AdGuardHome/dnsfilter"
@@ -25,13 +24,9 @@ func onConfigModified() {
2524
// Please note that we must do it even if we don't start it
2625
// so that we had access to the query log and the stats
2726
func initDNSServer() error {
27+
var err error
2828
baseDir := Context.getDataDir()
2929

30-
err := os.MkdirAll(baseDir, 0755)
31-
if err != nil {
32-
return fmt.Errorf("Cannot create DNS data dir at %s: %s", baseDir, err)
33-
}
34-
3530
statsConf := stats.Config{
3631
Filename: filepath.Join(baseDir, "stats.db"),
3732
LimitDays: config.DNS.StatsInterval,
@@ -70,14 +65,6 @@ func initDNSServer() error {
7065
return fmt.Errorf("dnsServer.Prepare: %s", err)
7166
}
7267

73-
sessFilename := filepath.Join(baseDir, "sessions.db")
74-
Context.auth = InitAuth(sessFilename, config.Users, config.WebSessionTTLHours*60*60)
75-
if Context.auth == nil {
76-
closeDNSServer()
77-
return fmt.Errorf("Couldn't initialize Auth module")
78-
}
79-
config.Users = nil
80-
8168
Context.rdns = InitRDNS(Context.dnsServer, &Context.clients)
8269
Context.whois = initWhois(&Context.clients)
8370

@@ -224,6 +211,8 @@ func startDNSServer() error {
224211

225212
enableFilters(false)
226213

214+
Context.clients.Start()
215+
227216
err := Context.dnsServer.Start()
228217
if err != nil {
229218
return errorx.Decorate(err, "Couldn't start forwarding DNS server")
@@ -295,11 +284,6 @@ func closeDNSServer() {
295284
Context.queryLog = nil
296285
}
297286

298-
if Context.auth != nil {
299-
Context.auth.Close()
300-
Context.auth = nil
301-
}
302-
303287
Context.filters.Close()
304288

305289
log.Debug("Closed all DNS modules")

home/home.go

Lines changed: 45 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -227,15 +227,30 @@ func run(args options) {
227227
if args.bindPort != 0 {
228228
config.BindPort = args.bindPort
229229
}
230+
if len(args.pidFile) != 0 && writePIDFile(args.pidFile) {
231+
Context.pidFileName = args.pidFile
232+
}
230233

231234
if !Context.firstRun {
232235
// Save the updated config
233236
err := config.write()
234237
if err != nil {
235238
log.Fatal(err)
236239
}
240+
}
241+
242+
err := os.MkdirAll(Context.getDataDir(), 0755)
243+
if err != nil {
244+
log.Fatalf("Cannot create DNS data dir at %s: %s", Context.getDataDir(), err)
245+
}
237246

238-
err = initDNSServer()
247+
err = initWeb()
248+
if err != nil {
249+
log.Fatalf("%s", err)
250+
}
251+
252+
if !Context.firstRun {
253+
err := initDNSServer()
239254
if err != nil {
240255
log.Fatalf("%s", err)
241256
}
@@ -252,26 +267,41 @@ func run(args options) {
252267
}
253268
}
254269

255-
if len(args.pidFile) != 0 && writePIDFile(args.pidFile) {
256-
Context.pidFileName = args.pidFile
270+
startWeb()
271+
272+
// wait indefinitely for other go-routines to complete their job
273+
select {}
274+
}
275+
276+
// Initialize Web modules
277+
func initWeb() error {
278+
sessFilename := filepath.Join(Context.getDataDir(), "sessions.db")
279+
Context.auth = InitAuth(sessFilename, config.Users, config.WebSessionTTLHours*60*60)
280+
if Context.auth == nil {
281+
return fmt.Errorf("Couldn't initialize Auth module")
257282
}
283+
config.Users = nil
258284

259285
// Initialize and run the admin Web interface
260286
box := packr.NewBox("../build/static")
261287

262288
// if not configured, redirect / to /install.html, otherwise redirect /install.html to /
263289
http.Handle("/", postInstallHandler(optionalAuthHandler(gziphandler.GzipHandler(http.FileServer(box)))))
264-
registerControlHandlers()
265290

266291
// add handlers for /install paths, we only need them when we're not configured yet
267292
if Context.firstRun {
268293
log.Info("This is the first launch of AdGuard Home, redirecting everything to /install.html ")
269294
http.Handle("/install.html", preInstallHandler(http.FileServer(box)))
270295
registerInstallHandlers()
296+
} else {
297+
registerControlHandlers()
271298
}
272299

273300
Context.httpsServer.cond = sync.NewCond(&Context.httpsServer.Mutex)
301+
return nil
302+
}
274303

304+
func startWeb() {
275305
// for https, we have a separate goroutine loop
276306
go httpServerLoop()
277307

@@ -291,9 +321,6 @@ func run(args options) {
291321
}
292322
// We use ErrServerClosed as a sign that we need to rebind on new address, so go back to the start of the loop
293323
}
294-
295-
// wait indefinitely for other go-routines to complete their job
296-
select {}
297324
}
298325

299326
func httpServerLoop() {
@@ -458,6 +485,8 @@ func configureLogger(args options) {
458485
func cleanup() {
459486
log.Info("Stopping AdGuard Home")
460487

488+
stopHTTPServer()
489+
461490
err := stopDNSServer()
462491
if err != nil {
463492
log.Error("Couldn't stop DNS server: %s", err)
@@ -475,7 +504,15 @@ func stopHTTPServer() {
475504
if Context.httpsServer.server != nil {
476505
_ = Context.httpsServer.server.Shutdown(context.TODO())
477506
}
478-
_ = Context.httpServer.Shutdown(context.TODO())
507+
if Context.httpServer != nil {
508+
_ = Context.httpServer.Shutdown(context.TODO())
509+
}
510+
511+
if Context.auth != nil {
512+
Context.auth.Close()
513+
Context.auth = nil
514+
}
515+
479516
log.Info("Stopped HTTP server")
480517
}
481518

0 commit comments

Comments
 (0)