From 392c7b6ee19ed38650fc9d7f4f3750d965e94da5 Mon Sep 17 00:00:00 2001
From: Simon Zolin <s.zolin@adguard.com>
Date: Wed, 24 Apr 2019 15:02:41 +0300
Subject: [PATCH] - control: fix race in /control/version.json handler

---
 control.go | 12 ++++++++++--
 1 file changed, 10 insertions(+), 2 deletions(-)

diff --git a/control.go b/control.go
index 35214d82..036e44a8 100644
--- a/control.go
+++ b/control.go
@@ -559,11 +559,17 @@ func checkDNS(input string, bootstrap []string) error {
 
 func handleGetVersionJSON(w http.ResponseWriter, r *http.Request) {
 	log.Tracef("%s %v", r.Method, r.URL)
+
 	now := time.Now()
-	if now.Sub(versionCheckLastTime) <= versionCheckPeriod && len(versionCheckJSON) != 0 {
+	controlLock.Lock()
+	cached := now.Sub(versionCheckLastTime) <= versionCheckPeriod && len(versionCheckJSON) != 0
+	data := versionCheckJSON
+	controlLock.Unlock()
+
+	if cached {
 		// return cached copy
 		w.Header().Set("Content-Type", "application/json")
-		w.Write(versionCheckJSON)
+		w.Write(data)
 		return
 	}
 
@@ -589,8 +595,10 @@ func handleGetVersionJSON(w http.ResponseWriter, r *http.Request) {
 		httpError(w, http.StatusInternalServerError, "Couldn't write body: %s", err)
 	}
 
+	controlLock.Lock()
 	versionCheckLastTime = now
 	versionCheckJSON = body
+	controlLock.Unlock()
 }
 
 // ---------