-
Notifications
You must be signed in to change notification settings - Fork 0
/
update.go
381 lines (312 loc) · 8.4 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
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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
package plasmactlupdate
import (
"errors"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"github.com/launchrctl/keyring"
"github.com/launchrctl/launchr"
)
const (
sudoCmd = "sudo"
doasCmd = "doas"
chmodCmd = "chmod"
)
type updateAction struct {
k keyring.Keyring
c keyring.CredentialsItem
ext string
fName string
fTmpPath string
fPath string
fDir string
sudoCmd string
}
func isCommandAvailable(name string) (bool, string) {
var cmdPath string
cmdPath, err := exec.LookPath(name)
if err != nil {
return false, ""
}
return true, cmdPath
}
// createUpdateAction instance.
func createUpdateAction(kr keyring.Keyring, cr keyring.CredentialsItem) (*updateAction, error) {
sudoAvailable, _ := isCommandAvailable(sudoCmd)
doasAvailable, _ := isCommandAvailable(doasCmd)
chmodAvailable, _ := isCommandAvailable(chmodCmd)
if !sudoAvailable && !doasAvailable {
return nil, fmt.Errorf("neither sudo or doas is available on your system. Please install one of them")
}
if !chmodAvailable {
return nil, fmt.Errorf("chmod is not available on your system. Please install it")
}
var cmd string
if sudoAvailable {
cmd = sudoCmd
} else {
cmd = doasCmd
}
return &updateAction{k: kr, c: cr, sudoCmd: cmd}, nil
}
// Errors.
var (
errUnsupportedOS = errors.New("unsupported operating system")
errUnsupportedArch = errors.New("unsupported architecture")
errInvalidCreds = errors.New("failed to validate credentials")
errMalformedKeyring = errors.New("the keyring is malformed or wrong passphrase provided")
)
// Define the URL pattern for the file.
const (
baseURL = "https://repositories.skilld.cloud/repository/pla-plasmactl-raw"
releasePath = "stable_release"
binPathMask = "%s/%s/plasmactl_%s_%s%s"
)
// initVars initialize plugin variables.
func (u *updateAction) initVars() (string, string, error) {
// Get username and password.
if err := u.getCredentials(); err != nil {
return "", "", err
}
// Get the operating system type.
currOS, err := u.getOS()
if err != nil {
return "", "", err
}
err = u.findExecPaths()
if err != nil {
return "", "", err
}
u.fTmpPath = filepath.Join(os.TempDir(), u.fName)
// Get the machine architecture.
arch, err := getArch()
if err != nil {
return "", "", err
}
u.c.URL = fmt.Sprintf("%s/%s", baseURL, releasePath)
launchr.Log().Debug("initialized environment", "os", currOS, "arch", arch, "temp_path", u.fTmpPath, "url", u.c.URL)
return currOS, arch, nil
}
func (u *updateAction) findExecPaths() error {
execPath, err := os.Executable()
if err != nil {
return err
}
fi, err := os.Lstat(execPath)
if err != nil {
return err
}
var path string
if fi.Mode()&os.ModeSymlink != 0 {
evalPath, err := filepath.EvalSymlinks(execPath)
if err != nil {
return err
}
path = evalPath
} else {
path = execPath
}
u.fDir = filepath.Dir(path)
u.fPath = strings.TrimSpace(path)
u.fName = filepath.Base(path)
return nil
}
// getCredentials stores username and password credentials.
func (u *updateAction) getCredentials() error {
repoURL := fmt.Sprintf("%s/%s", baseURL, releasePath)
launchr.Log().Debug("get credentials for source url of release", "url", repoURL)
// Get credentials and save in keyring.
ci, err := u.k.GetForURL(repoURL)
if err != nil {
if errors.Is(err, keyring.ErrEmptyPass) {
return err
} else if !errors.Is(err, keyring.ErrNotFound) {
return errMalformedKeyring
}
ci.URL = repoURL
ci.Username = u.c.Username
ci.Password = u.c.Password
if ci.Username == "" || ci.Password == "" {
launchr.Term().Info().Printfln("Enter credentials for %s", ci.URL)
if err = keyring.RequestCredentialsFromTty(&ci); err != nil {
return err
}
}
if err = u.k.AddItem(ci); err != nil {
return err
}
err = u.k.Save()
}
u.c = ci
return err
}
// getOS check operating system supports and set extension package file.
func (u *updateAction) getOS() (os string, err error) {
os = runtime.GOOS
if os == "windows" {
u.ext = ".exe"
} else if os != "linux" && os != "darwin" {
launchr.Term().Error().Printfln("Unsupported operating system: %s", os)
return "", errUnsupportedOS
}
return os, nil
}
// getArch get OS arch.
func getArch() (arch string, err error) {
arch = runtime.GOARCH
if arch == "amd64" || arch == "386" || arch == "arm64" {
return arch, nil
}
launchr.Term().Printfln("Unsupported architecture: %s", arch)
return "", errUnsupportedArch
}
// validateCredentials make request to validate credentials and return HTTP status code.
func (u *updateAction) validateCredentials() error {
r, err := u.sendRequest()
if err != nil {
return err
}
defer r.Body.Close()
switch r.StatusCode {
case 0:
launchr.Term().Error().Println("Failed to validate credentials. Access denied.")
return errInvalidCreds
case 200:
launchr.Term().Success().Println("Valid credentials. Access granted.")
case 401:
launchr.Term().Error().Printfln("HTTP %d: Unauthorized. Credentials seems to be invalid.", r.StatusCode)
return errInvalidCreds
case 404:
launchr.Term().Error().Printfln("HTTP %d: Not Found. File %s does not exist.", r.StatusCode, u.c.URL)
return errInvalidCreds
default:
launchr.Term().Error().Printfln(
"HTTP %d. An issue appeared while trying to validate credentials against %s.",
r.StatusCode,
u.c.URL,
)
}
return nil
}
// sendRequest send HTTP request, make authorization and return response.
func (u *updateAction) sendRequest() (*http.Response, error) {
client := &http.Client{}
req, err := http.NewRequest("GET", u.c.URL, nil)
if err != nil {
return nil, err
}
req.SetBasicAuth(u.c.Username, u.c.Password)
resp, err := client.Do(req)
if err != nil {
return nil, err
}
return resp, nil
}
// getStableRelease send request and get stable release version.
func (u *updateAction) getStableRelease() (string, error) {
resp, err := u.sendRequest()
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
r := strings.TrimSpace(string(body))
launchr.Term().Printfln("Stable release: %s", r)
return r, nil
}
// downloadFile Download the file using with Basic Auth header.
func (u *updateAction) downloadFile() error {
resp, err := u.sendRequest()
if err != nil {
return err
}
defer resp.Body.Close()
out, err := os.Create(u.fTmpPath)
if err != nil {
return err
}
defer out.Close()
if _, err = io.Copy(out, resp.Body); err != nil {
return err
}
fileInfo, err := os.Stat(u.fTmpPath)
if err != nil {
return err
}
fileMode := fileInfo.Mode()
fileMode |= 0111
if err = os.Chmod(u.fTmpPath, fileMode); err != nil {
return err
}
return nil
}
// installFile copy file to the bin folder and remove temp file.
func (u *updateAction) installFile(dirPath string) error {
launchr.Term().Printfln("Installing %s binary under %s", u.fName, dirPath)
info, err := os.Stat(u.fDir)
if err != nil {
return err
}
pathPerm := fmt.Sprintf("%04o", info.Mode().Perm())
// Copy temp file in the plasmactl folder.
src, err := os.Open(u.fTmpPath)
if err != nil {
return err
}
defer src.Close()
// Set temp permissions for the folder with plasmactl.
if err = u.setPermissions("777", u.fDir); err != nil {
return err
}
defer func() {
if errDefer := u.setPermissions(pathPerm, u.fDir); errDefer != nil {
launchr.Log().Error("error during setting folder permissions", "dir", u.fDir, "error", errDefer)
}
}()
fTmpName := u.fPath + ".tmp"
dst, err := os.Create(filepath.Clean(fTmpName))
if err != nil {
return err
}
defer dst.Close()
_, err = io.Copy(dst, src)
if err != nil {
return err
}
// Rename temp file to plasmactl.
if err = os.Rename(fTmpName, u.fPath); err != nil {
return err
}
// Set plasmactl permissions.
if err = u.setPermissions("755", u.fPath); err != nil {
return err
}
return nil
}
func (u *updateAction) setPermissions(permissions, target string) error {
var cmd *exec.Cmd
if u.sudoCmd == "sudo" {
cmd = exec.Command(sudoCmd, chmodCmd, permissions, target)
} else {
cmd = exec.Command(doasCmd, chmodCmd, permissions, target)
}
err := cmd.Run()
return err
}
// exitWithError exit with error and remove temp file.
func (u *updateAction) exitWithError() {
if _, err := os.Stat(u.fTmpPath); err == nil {
if err = os.Remove(u.fTmpPath); err != nil {
launchr.Log().Error("error deleting file", "file", u.fTmpPath, "error", err)
}
}
launchr.Term().Error().Println("Update failed")
}