~ev/goget-ubuntu-touch/root-size-option

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
//
// Helpers to work with an Ubuntu image based Upgrade implementation
//
// Copyright (c) 2013 Canonical Ltd.
//
// Written by Sergio Schvezov <sergio.schvezov@canonical.com>
//
package ubuntuimage

// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License version 3, as published
// by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranties of
// MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
// PURPOSE.  See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program.  If not, see <http://www.gnu.org/licenses/>.

import (
	"bufio"
	"crypto/sha256"
	"encoding/hex"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"net/url"
	"os"
	"path/filepath"
	"syscall"

	"github.com/cheggaaa/pb"
)

func hashMatches(filePath, hash string) bool {
	h := sha256.New()
	var err error
	fileBytes, err := ioutil.ReadFile(filePath)
	if err != nil {
		return false
	}
	h.Write(fileBytes)
	hashString := hex.EncodeToString(h.Sum(nil))
	if hashString == hash {
		return true
	}
	return false
}

const commandsStart = `format system
load_keyring image-master.tar.xz image-master.tar.xz.asc
load_keyring image-signing.tar.xz image-signing.tar.xz.asc
mount system
`

func GetUbuntuCommands(files []File, downloadDir string, wipe bool, enable []string) (commandsFile string, err error) {
	tmpFile, err := ioutil.TempFile(downloadDir, "ubuntu_commands")
	if err != nil {
		return commandsFile, err
	}
	writer := bufio.NewWriter(tmpFile)
	defer func() {
		if err == nil {
			writer.Flush()
		}
	}()
	if wipe {
		writer.WriteString("format data\n")
	}
	if files != nil {
		writer.WriteString(commandsStart)
		order := func(f1, f2 *File) bool {
			return f1.Order < f2.Order
		}
		By(order).Sort(files)
		for _, file := range files {
			writer.WriteString(
				fmt.Sprintf("update %s %s\n", filepath.Base(file.Path), filepath.Base(file.Signature)))
		}
	}

	//we cannot enable "things" outside of userdata
	for i := range enable {
		writer.WriteString(fmt.Sprintf("enable %s\n", enable[i]))
	}

	writer.WriteString("unmount system\n")
	return tmpFile.Name(), err
}

func GetGPGFiles() []File {
	return []File{{Path: "/gpg/image-master.tar.xz", Signature: "/gpg/image-master.tar.xz.asc"},
		{Path: "/gpg/image-signing.tar.xz", Signature: "/gpg/image-signing.tar.xz.asc"}}
}

func getLockFd(file string) (fileLock *os.File, err error) {
	err = os.MkdirAll(filepath.Dir(file), 0700)
	if err != nil {
		return nil, err
	}
	fileLock, err = os.Create(file + "_lock")
	if err != nil {
		return nil, err
	}
	return fileLock, nil
}

//MakeRelativeToServer changes absolute paths in Path into a relative path and adds the host
//part to Server, if the Path is already relative it uses defaultServer
func (file *File) MakeRelativeToServer(defaultServer string) error {
	file.Server = defaultServer
	u, err := url.Parse(file.Path)
	if err != nil {
		return err
	}
	if u.IsAbs() {
		file.Server = u.Scheme + "://" + u.Host
		file.Path = u.Path
		file.Signature = file.Path + ".asc"
	}
	return nil
}

func (file File) Download(downloadDir string) (err error) {
	//TODO Verify downloaded gpg agains image
	path := filepath.Join(downloadDir, file.Path)
	// Create file lock to avoid multiple processes downloading the same file
	lock, err := getLockFd(path)
	if err != nil {
		return err
	}
	err = syscall.Flock(int(lock.Fd()), syscall.LOCK_EX)
	if err != nil {
		return err
	}
	defer func() {
		os.Remove(lock.Name())
		syscall.Flock(int(lock.Fd()), syscall.LOCK_UN)
	}()

	if hashMatches(path, file.Checksum) {
		return nil
	}
	for _, f := range []string{file.Signature, file.Path} {
		uri := file.Server + f
		path := filepath.Join(downloadDir, f)
		err := os.MkdirAll(filepath.Dir(path), 0700)
		if err != nil {
			return err
		}
		target, err := os.Create(path + "_")
		if err != nil {
			return err
		}
		defer func() {
			target.Close()
			if err == nil {
				os.Rename(path+"_", path)
			}
		}()
		err = download(uri, target)
		if err != nil {
			return err
		}
	}
	return err
}

func download(uri string, writer io.Writer) (err error) {
	resp, err := client.Get(uri)
	if err != nil {
		return err
	}
	if resp.StatusCode != 200 {
		return errors.New(fmt.Sprintf("Got status code %d for %s", resp.StatusCode, uri))
	}
	defer resp.Body.Close()

	// Only display a progress bar for files > 2K in size
	// nb, ContentLength is -1 for *.asc files
	if resp.ContentLength > 2048 {
		pbar := pb.New(int(resp.ContentLength))
		pbar.ShowSpeed = true
		pbar.Units = pb.U_BYTES
		pbar.Start()

		mw := io.MultiWriter(writer, pbar)
		_, err = io.Copy(mw, resp.Body)
		pbar.Finish()
	} else {
		bufReader := bufio.NewReader(resp.Body)
		bufWriter := bufio.NewWriter(writer)
		defer func() {
			if err == nil {
				err = bufWriter.Flush()
			}
		}()

		_, err = bufReader.WriteTo(bufWriter)
	}

	return err
}

func GetCacheDir() (cacheDir string) {
	cacheDir = os.Getenv("XDG_CACHE_HOME")
	if cacheDir == "" {
		cacheDir = "$HOME/.cache/"
	}
	cacheDir = os.ExpandEnv(cacheDir)
	return filepath.Join(cacheDir, "ubuntuimages")
}