forked from pydio/cells
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tools.go
228 lines (205 loc) · 7.18 KB
/
tools.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
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
/*
* Copyright (c) 2018. Abstrium SAS <team (at) pydio.com>
* This file is part of Pydio Cells.
*
* Pydio Cells is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Pydio Cells is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Pydio Cells. If not, see <http://www.gnu.org/licenses/>.
*
* The latest code can be found at <https://pydio.com>.
*/
// Package update provides connection to a remote update server for upgrading cells binary
package update
import (
"context"
"crypto"
"crypto/rsa"
"encoding/asn1"
"encoding/base64"
"encoding/json"
"encoding/pem"
"fmt"
"io/ioutil"
"math"
"net/http"
"net/url"
"os"
"path/filepath"
"runtime"
"sort"
"strings"
"github.com/hashicorp/go-version"
"github.com/golang/protobuf/jsonpb"
update2 "github.com/inconshreveable/go-update"
"github.com/micro/go-micro/errors"
"go.uber.org/zap"
"github.com/pydio/cells/common"
"github.com/pydio/cells/common/config"
"github.com/pydio/cells/common/log"
"github.com/pydio/cells/common/proto/update"
"github.com/pydio/cells/common/service"
"github.com/pydio/cells/common/utils/net"
)
// LoadUpdates will post a Json query to the update server to detect if there are any
// updates available
func LoadUpdates(ctx context.Context, conf common.ConfigValues, request *update.UpdateRequest) ([]*update.Package, error) {
urlConf := conf.String("updateUrl")
if urlConf == "" {
return nil, errors.BadRequest(common.SERVICE_UPDATE, "cannot find update url")
}
parsed, e := url.Parse(urlConf)
if e != nil {
return nil, errors.BadRequest(common.SERVICE_UPDATE, e.Error())
}
if strings.Trim(parsed.Path, "/") == "" {
parsed.Path = "/a/update-server"
}
channel := conf.String("channel")
if channel == "" {
channel = "stable"
}
// Set default values
if request.PackageName == "" {
request.PackageName = common.PackageType
}
request.Channel = channel
if request.PackageName != common.PackageType {
// This is an "upgrade" (from one package to another)
// compute a version lower than current to get the current in the results set
segments := common.Version().Segments()
lower := service.ValidVersion(fmt.Sprintf("%v.%v.%v", math.Max(float64(segments[0]-1), 0), math.Max(float64(segments[1]-1), 0), 0))
log.Logger(ctx).Info("Sending a lower version", zap.String("v", lower.String()))
request.CurrentVersion = lower.String()
} else {
// This is an "update" : send current version to get the more recent ones
request.CurrentVersion = common.Version().String()
}
request.GOOS = runtime.GOOS
request.GOARCH = runtime.GOARCH
log.Logger(ctx).Info("Posting Request for update", zap.Any("request", request))
marshaller := jsonpb.Marshaler{}
jsonReq, _ := marshaller.MarshalToString(request)
reader := strings.NewReader(string(jsonReq))
response, err := http.Post(strings.TrimRight(parsed.String(), "/")+"/", "application/json", reader)
if err != nil {
return nil, err
}
if response.StatusCode != 200 {
rErr := fmt.Errorf("could not connect to the update server, error code was %d", response.StatusCode)
if response.StatusCode == 500 {
var jsonErr struct {
Title string
Detail string
}
data, _ := ioutil.ReadAll(response.Body)
if e := json.Unmarshal(data, &jsonErr); e == nil {
rErr = fmt.Errorf("failed connecting to the update server (%s), error code %d", jsonErr.Title, response.StatusCode)
}
}
return nil, rErr
}
var updateResponse update.UpdateResponse
if e := jsonpb.Unmarshal(response.Body, &updateResponse); e != nil {
return nil, e
}
if request.LicenseInfo != nil {
lic, ok := request.LicenseInfo["Key"]
save, sOk := request.LicenseInfo["Save"]
if ok && sOk && save == "true" {
// Save license now : the check for update including license key passed without error,
// this license must thus be valid
log.Logger(ctx).Info("Saving LicenseKey to file now", zap.String("lic", lic))
filePath := filepath.Join(config.ApplicationWorkingDir(), "pydio-license")
if err := ioutil.WriteFile(filePath, []byte(lic), 0755); err != nil {
return nil, fmt.Errorf("could not save license file to %s (%s), aborting upgrade", filePath, err.Error())
}
}
}
// When upgrading, filter out versions lesser than current
if request.PackageName != common.PackageType {
var bins []*update.Package
for _, b := range updateResponse.AvailableBinaries {
if service.ValidVersion(b.GetVersion()).LessThan(common.Version()) {
continue
}
bins = append(bins, b)
}
updateResponse.AvailableBinaries = bins
}
// Sort by version using hashicorp sorting (X.X.X-rc should appear before X.X.X)
sort.Slice(updateResponse.AvailableBinaries, func(i, j int) bool {
va, _ := version.NewVersion(updateResponse.AvailableBinaries[i].Version)
vb, _ := version.NewVersion(updateResponse.AvailableBinaries[j].Version)
return va.LessThan(vb)
})
return updateResponse.AvailableBinaries, nil
}
// ApplyUpdate uses the info of an update.Package to download the binary and replace
// the current running binary. A restart is necessary afterward.
// The dryRun option will download the binary and just put it in the /tmp folder
func ApplyUpdate(ctx context.Context, p *update.Package, conf common.ConfigValues, dryRun bool, pgChan chan float64, doneChan chan bool, errorChan chan error) {
defer func() {
close(doneChan)
}()
if resp, err := http.Get(p.BinaryURL); err != nil {
errorChan <- err
return
} else {
defer resp.Body.Close()
if resp.StatusCode != 200 {
plain, _ := ioutil.ReadAll(resp.Body)
errorChan <- errors.New("binary.download.error", "Error while downloading binary:"+string(plain), int32(resp.StatusCode))
return
}
targetPath := ""
if dryRun {
targetPath = filepath.Join(os.TempDir(), "pydio-update")
}
if p.BinaryChecksum == "" || p.BinarySignature == "" {
errorChan <- fmt.Errorf("Missing checksum and signature infos")
return
}
checksum, e := base64.StdEncoding.DecodeString(p.BinaryChecksum)
if e != nil {
errorChan <- e
return
}
signature, e := base64.StdEncoding.DecodeString(p.BinarySignature)
if e != nil {
errorChan <- e
return
}
pKey := conf.Get("publicKey").(string)
block, _ := pem.Decode([]byte(pKey))
var pubKey rsa.PublicKey
if _, err := asn1.Unmarshal(block.Bytes, &pubKey); err != nil {
errorChan <- err
return
}
dataDir, _ := config.ServiceDataDir(common.SERVICE_GRPC_NAMESPACE_ + common.SERVICE_UPDATE)
oldPath := filepath.Join(dataDir, "revision-"+common.BuildStamp)
reader := net.BodyWithProgressMonitor(resp, pgChan, nil)
er := update2.Apply(reader, update2.Options{
Checksum: checksum,
Signature: signature,
TargetPath: targetPath,
OldSavePath: oldPath,
Hash: crypto.SHA256,
PublicKey: &pubKey,
Verifier: update2.NewRSAVerifier(),
})
if er != nil {
errorChan <- er
}
return
}
}