-
Notifications
You must be signed in to change notification settings - Fork 0
/
update.go
162 lines (110 loc) · 2.32 KB
/
update.go
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
package update
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"github.com/EmpiresMod/GameLauncher/checksum"
//"github.com/EmpiresMod/GameLauncher/signer"
)
const (
FilePerm = 0640
DirectoryPerm = 0750
CheckSumPostix = ".sha256"
TempPostix = ".tmp"
SignatirePostfix = ".sig"
)
// Error represents an Error reported in the HTTP session.
type Error struct {
// Error message
HTTPStatus string
// The request sent to the server
Request string
}
// Error returns a string representation of the HTTP error
func (e *Error) Error() string {
return fmt.Sprintf("update: %s %s\n", e.HTTPStatus, e.Request)
}
type Update struct {
// Path to file
FileName string
// URL of update
URL string
// Checksum of remote file
CheckSum []byte
// Signature of file
Signature []byte
}
func New() *Update {
return new(Update)
}
func (u *Update) Fetch() (b []byte, err error) {
resp, err := http.Get(u.URL)
if err != nil {
return
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
return nil, &Error{resp.Status, u.URL}
}
return ioutil.ReadAll(resp.Body)
}
func (u *Update) GetSignature() ([]byte, error) {
resp, err := http.Get(u.URL + SignatirePostfix)
if err != nil {
return nil, nil
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
return nil, &Error{resp.Status, u.URL}
}
return ioutil.ReadAll(resp.Body)
}
func (u *Update) GetCheckSum() ([]byte, error) {
resp, err := http.Get(u.URL + CheckSumPostix)
if err != nil {
return nil, nil
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
return nil, &Error{resp.Status, u.URL}
}
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return bytes.Fields(b)[0], nil
}
// Check for updates to file. Returns true for updates and false for no updates
func (u *Update) Check() (ok bool, err error) {
if !fileExists(u.FileName) {
ok = true
return
}
a, err := checksum.GenerateFileCheckSum(u.FileName)
if err != nil {
return
}
if len(u.CheckSum) == 0 {
u.CheckSum, err = u.GetCheckSum()
if err != nil {
return
}
}
if checksum.Compare(a, u.CheckSum) {
ok = false
return
}
ok = true
return
}
func (u *Update) Update() (err error) {
b, err := u.Fetch()
if err != nil {
return
}
if err = ioutil.WriteFile(u.FileName, b, FilePerm); err != nil {
return
}
return
}