-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Expand file tree
/
Copy pathcontrolupdate.go
More file actions
292 lines (242 loc) · 7.47 KB
/
controlupdate.go
File metadata and controls
292 lines (242 loc) · 7.47 KB
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
package home
import (
"context"
"encoding/json"
"fmt"
"log/slog"
"net/http"
"os"
"runtime"
"syscall"
"time"
"github.com/AdguardTeam/AdGuardHome/internal/aghalg"
"github.com/AdguardTeam/AdGuardHome/internal/aghhttp"
"github.com/AdguardTeam/AdGuardHome/internal/aghnet"
"github.com/AdguardTeam/AdGuardHome/internal/updater"
"github.com/AdguardTeam/golibs/errors"
"github.com/AdguardTeam/golibs/logutil/slogutil"
"github.com/AdguardTeam/golibs/osutil"
"github.com/AdguardTeam/golibs/osutil/executil"
)
// temporaryError is the interface for temporary errors from the Go standard
// library.
type temporaryError interface {
error
Temporary() (ok bool)
}
// handleVersionJSON is the handler for the POST /control/version.json HTTP API.
//
// TODO(a.garipov): Find out if this API used with a GET method by anyone.
func (web *webAPI) handleVersionJSON(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
l := web.logger
resp := &versionResponse{}
if web.conf.disableUpdate {
resp.Disabled = true
aghhttp.WriteJSONResponseOK(ctx, l, w, r, resp)
return
}
req := &struct {
Recheck bool `json:"recheck_now"`
}{}
var err error
if r.ContentLength != 0 {
err = json.NewDecoder(r.Body).Decode(req)
if err != nil {
aghhttp.ErrorAndLog(ctx, l, r, w, http.StatusBadRequest, "parsing request: %s", err)
return
}
}
err = web.requestVersionInfo(ctx, resp, req.Recheck)
if err != nil {
// Don't wrap the error, because it's informative enough as is.
aghhttp.ErrorAndLog(ctx, l, r, w, http.StatusBadGateway, "%s", err)
return
}
err = resp.setAllowedToAutoUpdate(ctx, l, web.tlsManager)
if err != nil {
// Don't wrap the error, because it's informative enough as is.
aghhttp.ErrorAndLog(ctx, l, r, w, http.StatusInternalServerError, "%s", err)
return
}
aghhttp.WriteJSONResponseOK(ctx, l, w, r, resp)
}
// requestVersionInfo sets the VersionInfo field of resp if it can reach the
// update server.
func (web *webAPI) requestVersionInfo(
ctx context.Context,
resp *versionResponse,
recheck bool,
) (err error) {
updater := web.conf.updater
for range 3 {
resp.VersionInfo, err = updater.VersionInfo(ctx, recheck)
if err == nil {
return nil
}
if tmpErr, ok := errors.AsType[temporaryError](err); ok && tmpErr.Temporary() {
// Temporary network error. This case may happen while we're
// restarting our DNS server. Log and sleep for some time.
//
// See https://github.com/AdguardTeam/AdGuardHome/issues/934.
const sleepTime = 2 * time.Second
err = fmt.Errorf("temp net error: %w; sleeping for %s and retrying", err, sleepTime)
web.logger.InfoContext(ctx, "updating version info", slogutil.KeyError, err)
time.Sleep(sleepTime)
continue
}
break
}
if err != nil {
return fmt.Errorf("getting version info: %w", err)
}
return nil
}
// handleUpdate performs an update to the latest available version procedure.
func (web *webAPI) handleUpdate(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
l := web.logger
updater := web.conf.updater
if updater.NewVersion() == "" {
aghhttp.ErrorAndLog(
ctx,
l,
r,
w,
http.StatusBadRequest,
"/update request isn't allowed now",
)
return
}
// Retain the current absolute path of the executable, since the updater is
// likely to change the position current one to the backup directory.
//
// See https://github.com/AdguardTeam/AdGuardHome/issues/4735.
execPath, err := os.Executable()
if err != nil {
aghhttp.ErrorAndLog(ctx, l, r, w, http.StatusInternalServerError, "getting path: %s", err)
return
}
err = updater.Update(ctx, false)
if err != nil {
aghhttp.ErrorAndLog(ctx, l, r, w, http.StatusInternalServerError, "%s", err)
return
}
aghhttp.OK(ctx, web.logger, w)
rc := http.NewResponseController(w)
err = rc.Flush()
if err != nil {
web.logger.WarnContext(ctx, "flushing response", slogutil.KeyError, err)
}
// The background context is used because the underlying functions wrap it
// with timeout and shut down the server, which handles current request. It
// also should be done in a separate goroutine for the same reason.
go finishUpdate(
context.Background(),
web.logger,
web.cmdCons,
execPath,
web.conf.runningAsService,
)
}
// versionResponse is the response for /control/version.json endpoint.
type versionResponse struct {
updater.VersionInfo
Disabled bool `json:"disabled"`
}
// maxPrivilegedPort is the maximum port number. This only applies to Unix, as
// on Windows, [aghnet.CanBindPrivilegedPorts] always returns `true`, `nil`.
const maxPrivilegedPort = 1024
// setAllowedToAutoUpdate sets CanAutoUpdate to true if AdGuard Home is actually
// allowed to perform an automatic update by the OS. l and tlsMgr must not be
// nil.
func (vr *versionResponse) setAllowedToAutoUpdate(
ctx context.Context,
l *slog.Logger,
tlsMgr *tlsManager,
) (err error) {
if vr.CanAutoUpdate != aghalg.NBTrue {
return nil
}
canUpdate := true
if tlsConfUsesPrivilegedPorts(tlsMgr.extendedTLSConfig()) ||
config.HTTPConfig.Address.Port() < maxPrivilegedPort ||
config.DNS.Port < maxPrivilegedPort {
canUpdate, err = aghnet.CanBindPrivilegedPorts(ctx, l)
if err != nil {
return fmt.Errorf("checking ability to bind privileged ports: %w", err)
}
}
vr.CanAutoUpdate = aghalg.BoolToNullBool(canUpdate)
return nil
}
// tlsConfUsesPrivilegedPorts returns true if the provided TLS configuration
// indicates that privileged ports are used. c must be valid
func tlsConfUsesPrivilegedPorts(c *tlsConfigSettings) (ok bool) {
return c.Enabled && (c.PortHTTPS < maxPrivilegedPort ||
c.PortDNSOverTLS < maxPrivilegedPort ||
c.PortDNSOverQUIC < maxPrivilegedPort)
}
// finishUpdate completes an update procedure. It is intended to be used as a
// goroutine. l and cmdCons must not be nil.
func finishUpdate(
ctx context.Context,
l *slog.Logger,
cmdCons executil.CommandConstructor,
execPath string,
runningAsService bool,
) {
defer slogutil.RecoverAndExit(ctx, l, osutil.ExitCodeFailure)
l.InfoContext(ctx, "stopping all tasks")
cleanup(ctx)
cleanupAlways()
if runtime.GOOS == "windows" {
finalizeWindowsUpdate(ctx, l, cmdCons, execPath, runningAsService)
os.Exit(osutil.ExitCodeSuccess)
}
var err error
l.InfoContext(ctx, "restarting", "exec_path", execPath, "args", os.Args[1:])
err = syscall.Exec(execPath, os.Args, os.Environ())
if err != nil {
panic(fmt.Errorf("restarting: %w", err))
}
}
// finalizeWindowsUpdate completes an update procedure on windows. l and
// cmdCons must not be nil.
func finalizeWindowsUpdate(ctx context.Context,
l *slog.Logger,
cmdCons executil.CommandConstructor,
execPath string,
runningAsService bool,
) {
var commandConf *executil.CommandConfig
if runningAsService {
// NOTE: We can't restart the service via "kardianos/service" package,
// because it kills the process first we can't start a new instance,
// because Windows doesn't allow it.
//
// TODO(a.garipov): Recheck the claim above.
commandConf = &executil.CommandConfig{
Path: "cmd",
Args: []string{"/c", "net stop AdGuardHome & net start AdGuardHome"},
}
} else {
commandConf = &executil.CommandConfig{
Path: execPath,
Args: os.Args[1:],
Stdin: os.Stdin,
Stdout: os.Stdout,
Stderr: os.Stderr,
}
}
l.InfoContext(ctx, "restarting", "exec_path", execPath, "args", os.Args[1:])
var cmd executil.Command
cmd, err := cmdCons.New(ctx, commandConf)
if err != nil {
panic(fmt.Errorf("constructing cmd: %w", err))
}
err = cmd.Start(ctx)
if err != nil {
panic(fmt.Errorf("restarting: %w", err))
}
}