vscode-winsta11er/common/common.go

252 строки
6.1 KiB
Go
Исходник Обычный вид История

2021-08-20 01:45:44 +03:00
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
2021-09-07 21:54:28 +03:00
package common
2021-08-14 00:06:22 +03:00
import (
"bytes"
2021-08-17 17:53:09 +03:00
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
2021-08-17 17:53:09 +03:00
"errors"
2021-08-14 00:06:22 +03:00
"fmt"
"io"
"io/ioutil"
2021-08-17 17:53:09 +03:00
"net"
2021-08-14 00:06:22 +03:00
"net/http"
"os"
"os/exec"
"runtime"
2021-08-17 17:53:09 +03:00
"sync"
"time"
2021-08-14 00:06:22 +03:00
)
2021-09-07 21:54:28 +03:00
func MainBase(quality string) {
2021-08-25 00:45:11 +03:00
arch_pkg := GetSystemInfo()
2021-09-07 21:54:28 +03:00
installer_dir, err := SetupTemporaryDirectory(quality)
2021-08-17 17:53:09 +03:00
checkError(err)
2021-09-07 21:54:28 +03:00
release_info, err := GetReleaseInfo(arch_pkg, quality)
checkError(err)
2021-08-25 00:45:11 +03:00
installer_path, err := DownloadInstaller(installer_dir, arch_pkg, release_info)
2021-08-17 17:53:09 +03:00
checkError(err)
err = RunInstaller(installer_path)
checkError(err)
err = Cleanup(installer_dir)
checkError(err)
2021-08-14 00:06:22 +03:00
}
2021-08-25 00:45:11 +03:00
func GetSystemInfo() (arch_pkg string) {
2021-08-14 00:06:22 +03:00
switch runtime.GOARCH {
case "amd64":
2021-08-25 00:45:11 +03:00
arch_pkg = "x64-user"
2021-08-14 00:06:22 +03:00
case "386":
2021-08-25 00:45:11 +03:00
arch_pkg = "user"
2021-08-14 00:06:22 +03:00
case "arm64":
2021-08-25 00:45:11 +03:00
arch_pkg = "arm64-user"
2021-08-14 00:06:22 +03:00
}
return
}
2021-09-07 21:54:28 +03:00
func SetupTemporaryDirectory(quality string) (installer_dir string, err error) {
return ioutil.TempDir("", fmt.Sprintf("vscode-winsta11er-%s", quality))
2021-08-14 00:06:22 +03:00
}
type ReleaseInfo struct {
Url string `json:"url"`
Name string `json:"name"`
Sha256Hash string `json:"sha256hash"`
}
2021-09-07 21:54:28 +03:00
func GetReleaseInfo(arch_pkg string, quality string) (info *ReleaseInfo, err error) {
apiUrl := fmt.Sprintf("https://update.code.visualstudio.com/api/update/win32-%s/%s/latest", arch_pkg, quality)
fmt.Printf("Requesting hash from %s.\n", apiUrl)
client := http.Client{
Timeout: 30 * time.Second,
}
req, err := http.NewRequest("GET", apiUrl, nil)
if err != nil {
return nil, err
}
req.Header.Set("User-Agent", "cli/vscode-winsta11er")
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
return nil, errors.New("invalid response status code")
}
info = &ReleaseInfo{}
err = json.NewDecoder(resp.Body).Decode(info)
if err != nil {
return nil, err
}
if info.Url == "" || info.Name == "" || info.Sha256Hash == "" {
return nil, errors.New("missing required fields in API response")
}
return info, nil
}
2021-08-14 00:06:22 +03:00
2021-08-25 00:45:11 +03:00
func DownloadInstaller(installer_dir, arch_pkg string, info *ReleaseInfo) (installer_path string, err error) {
fmt.Printf("Downloading installer from %s.\n", info.Url)
2021-08-14 00:06:22 +03:00
2021-08-25 00:45:11 +03:00
file, err := os.CreateTemp(installer_dir, fmt.Sprintf("vscode-win32-%s*.exe", arch_pkg))
2021-08-17 17:53:09 +03:00
if err != nil {
return "", err
}
defer file.Close()
2021-08-14 00:06:22 +03:00
client := http.Client{
// Disable timeout here because file can take a while to download on slow connections
// Instead, we're using a function that reads from the stream and makes sure data is flowing constantly
Timeout: 0,
2021-08-17 17:53:09 +03:00
Transport: &http.Transport{
Dial: (&net.Dialer{
Timeout: 30 * time.Second,
}).Dial,
TLSHandshakeTimeout: 15 * time.Second,
ResponseHeaderTimeout: 15 * time.Second,
},
2021-08-14 00:06:22 +03:00
}
// Request the file
req, err := http.NewRequest("GET", info.Url, nil)
if err != nil {
return "", err
}
req.Header.Set("User-Agent", "cli/vscode-winsta11er")
resp, err := client.Do(req)
2021-08-17 17:53:09 +03:00
if err != nil {
return "", err
}
2021-08-14 00:06:22 +03:00
defer resp.Body.Close()
2021-08-17 17:53:09 +03:00
if resp.StatusCode < 200 || resp.StatusCode > 299 {
return "", errors.New("invalid response status code")
}
2021-08-14 00:06:22 +03:00
// Copy the stream to the file and calculate the hash
_, err = copyWithTimeout(context.Background(), file, resp.Body, info.Sha256Hash)
2021-08-17 17:53:09 +03:00
if err != nil {
return "", err
}
2021-08-14 00:06:22 +03:00
fmt.Printf("Downloaded installer to file %s.\n", file.Name())
installer_path = file.Name()
2021-08-17 17:53:09 +03:00
return installer_path, nil
2021-08-14 00:06:22 +03:00
}
2021-08-17 17:53:09 +03:00
func RunInstaller(installer_path string) error {
2021-08-14 00:06:22 +03:00
path, err := exec.LookPath(installer_path)
2021-08-17 17:53:09 +03:00
if err != nil {
return err
}
2021-08-14 00:06:22 +03:00
cmd := exec.Command(path, "/verysilent", "/mergetasks=!runcode")
stdout, err := cmd.Output()
2021-08-17 17:53:09 +03:00
if err != nil {
return err
}
2021-08-14 00:06:22 +03:00
fmt.Println(string(stdout))
2021-08-17 17:53:09 +03:00
return nil
2021-08-14 00:06:22 +03:00
}
2021-08-17 17:53:09 +03:00
func Cleanup(installer_dir string) error {
return os.RemoveAll(installer_dir)
2021-08-14 00:06:22 +03:00
}
func checkError(e error) {
if e != nil {
panic(e)
}
}
2021-08-17 17:53:09 +03:00
func copyWithTimeout(ctx context.Context, dst io.Writer, src io.Reader, expectedHash string) (int64, error) {
2021-08-17 17:53:09 +03:00
// Every 5 seconds, ensure at least 200 bytes (40 bytes/second average) are read
interval := 5
minCopyBytes := int64(200)
prevWritten := int64(0)
written := int64(0)
expectedHashBytes, err := hex.DecodeString(expectedHash)
if err != nil {
return 0, fmt.Errorf("error decoding hash from hex: %v", err)
}
h := sha256.New()
2021-08-17 17:53:09 +03:00
done := make(chan error)
mu := sync.Mutex{}
t := time.NewTicker(time.Duration(interval) * time.Second)
defer t.Stop()
// Read the stream, 32KB at a time
go func() {
var (
writeErr, readErr, hashErr error
writeBytes, readBytes int
buf = make([]byte, 32<<10)
)
2021-08-17 17:53:09 +03:00
for {
readBytes, readErr = src.Read(buf)
2021-08-17 17:53:09 +03:00
if readBytes > 0 {
// Add to the hash
_, hashErr = h.Write(buf[0:readBytes])
if hashErr != nil {
done <- hashErr
return
}
// Write to disk and update the number of bytes written
writeBytes, writeErr = dst.Write(buf[0:readBytes])
2021-08-17 17:53:09 +03:00
mu.Lock()
written += int64(writeBytes)
mu.Unlock()
if writeErr != nil {
done <- writeErr
return
}
}
if readErr != nil {
// If error is EOF, means we read the entire file, so don't consider that as error
2021-08-17 17:53:09 +03:00
if readErr != io.EOF {
done <- readErr
return
2021-08-17 17:53:09 +03:00
}
// Compute and compare the checksum
hash := h.Sum(nil)
if !bytes.Equal(expectedHashBytes, hash[:]) {
done <- errors.New("downloaded file's hash doesn't match")
return
}
// No error
done <- nil
2021-08-17 17:53:09 +03:00
return
}
}
}()
for {
select {
case <-ctx.Done():
return written, ctx.Err()
case <-t.C:
mu.Lock()
if written < prevWritten+minCopyBytes {
mu.Unlock()
return written, fmt.Errorf("stream stalled: received %d bytes over the last %d seconds", written, interval)
}
prevWritten = written
mu.Unlock()
case e := <-done:
return written, e
}
}
}