aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/updater/downloader.go
blob: a61acbd45f01d4fd631e9e72627c374f80de6765 (plain) (blame)
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
/* SPDX-License-Identifier: MIT
 *
 * Copyright (C) 2019-2020 WireGuard LLC. All Rights Reserved.
 */

package updater

import (
	"crypto/hmac"
	"errors"
	"fmt"
	"hash"
	"io"
	"sync/atomic"

	"golang.org/x/crypto/blake2b"

	"golang.zx2c4.com/wireguard/windows/elevate"
	"golang.zx2c4.com/wireguard/windows/updater/winhttp"
	"golang.zx2c4.com/wireguard/windows/version"
)

type DownloadProgress struct {
	Activity        string
	BytesDownloaded uint64
	BytesTotal      uint64
	Error           error
	Complete        bool
}

type progressHashWatcher struct {
	dp        *DownloadProgress
	c         chan DownloadProgress
	hashState hash.Hash
}

func (pm *progressHashWatcher) Write(p []byte) (int, error) {
	bytes := len(p)
	pm.dp.BytesDownloaded += uint64(bytes)
	pm.c <- *pm.dp
	pm.hashState.Write(p)
	return bytes, nil
}

type UpdateFound struct {
	name string
	hash [blake2b.Size256]byte
}

func CheckForUpdate() (updateFound *UpdateFound, err error) {
	updateFound, _, _, err = checkForUpdate(false)
	return
}

func checkForUpdate(keepSession bool) (*UpdateFound, *winhttp.Session, *winhttp.Connection, error) {
	if !version.IsRunningOfficialVersion() {
		return nil, nil, nil, errors.New("Build is not official, so updates are disabled")
	}
	session, err := winhttp.NewSession(version.UserAgent())
	if err != nil {
		return nil, nil, nil, err
	}
	defer func() {
		if err != nil || !keepSession {
			session.Close()
		}
	}()
	connection, err := session.Connect(updateServerHost, updateServerPort, updateServerUseHttps)
	if err != nil {
		return nil, nil, nil, err
	}
	defer func() {
		if err != nil || !keepSession {
			connection.Close()
		}
	}()
	response, err := connection.Get(latestVersionPath, true)
	if err != nil {
		return nil, nil, nil, err
	}
	defer response.Close()
	var fileList [1024 * 512] /* 512 KiB */ byte
	bytesRead, err := response.Read(fileList[:])
	if err != nil && (err != io.EOF || bytesRead == 0) {
		return nil, nil, nil, err
	}
	files, err := readFileList(fileList[:bytesRead])
	if err != nil {
		return nil, nil, nil, err
	}
	updateFound, err := findCandidate(files)
	if err != nil {
		return nil, nil, nil, err
	}
	if keepSession {
		return updateFound, session, connection, nil
	}
	return updateFound, nil, nil, nil
}

var updateInProgress = uint32(0)

func DownloadVerifyAndExecute(userToken uintptr) (progress chan DownloadProgress) {
	progress = make(chan DownloadProgress, 128)
	progress <- DownloadProgress{Activity: "Initializing"}

	if !atomic.CompareAndSwapUint32(&updateInProgress, 0, 1) {
		progress <- DownloadProgress{Error: errors.New("An update is already in progress")}
		return
	}

	doIt := func() {
		defer atomic.StoreUint32(&updateInProgress, 0)

		progress <- DownloadProgress{Activity: "Checking for update"}
		update, session, connection, err := checkForUpdate(true)
		if err != nil {
			progress <- DownloadProgress{Error: err}
			return
		}
		defer connection.Close()
		defer session.Close()
		if update == nil {
			progress <- DownloadProgress{Error: errors.New("No update was found")}
			return
		}

		progress <- DownloadProgress{Activity: "Creating temporary file"}
		file, err := msiTempFile()
		if err != nil {
			progress <- DownloadProgress{Error: err}
			return
		}
		progress <- DownloadProgress{Activity: fmt.Sprintf("Msi destination is %#q", file.Name())}
		defer func() {
			if file != nil {
				file.Delete()
			}
		}()

		dp := DownloadProgress{Activity: "Downloading update"}
		progress <- dp
		response, err := connection.Get(fmt.Sprintf(msiPath, update.name), false)
		if err != nil {
			progress <- DownloadProgress{Error: err}
			return
		}
		defer response.Close()
		length, err := response.Length()
		if err == nil && length >= 0 {
			dp.BytesTotal = length
			progress <- dp
		}
		hasher, err := blake2b.New256(nil)
		if err != nil {
			progress <- DownloadProgress{Error: err}
			return
		}
		pm := &progressHashWatcher{&dp, progress, hasher}
		_, err = io.Copy(file, io.TeeReader(io.LimitReader(response, 1024*1024*100 /* 100 MiB */), pm))
		if err != nil {
			progress <- DownloadProgress{Error: err}
			return
		}
		if !hmac.Equal(hasher.Sum(nil), update.hash[:]) {
			progress <- DownloadProgress{Error: errors.New("The downloaded update has the wrong hash")}
			return
		}

		progress <- DownloadProgress{Activity: "Verifying authenticode signature"}
		if !verifyAuthenticode(file.ExclusivePath()) {
			progress <- DownloadProgress{Error: errors.New("The downloaded update does not have an authentic authenticode signature")}
			return
		}

		progress <- DownloadProgress{Activity: "Installing update"}
		err = runMsi(file, userToken)
		if err != nil {
			progress <- DownloadProgress{Error: err}
			return
		}

		progress <- DownloadProgress{Complete: true}
	}
	if userToken == 0 {
		go func() {
			err := elevate.DoAsSystem(func() error {
				doIt()
				return nil
			})
			if err != nil {
				progress <- DownloadProgress{Error: err}
			}
		}()
	} else {
		go doIt()
	}

	return progress
}