forked from jetkvm/kvm
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathota.go
More file actions
1537 lines (1351 loc) · 43.4 KB
/
ota.go
File metadata and controls
1537 lines (1351 loc) · 43.4 KB
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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package kvm
import (
"archive/zip"
"bytes"
"context"
"crypto/sha256"
"crypto/tls"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"time"
"github.com/Masterminds/semver/v3"
"github.com/gwatts/rootcerts"
"github.com/rs/zerolog"
)
type UpdateMetadata struct {
AppVersion string `json:"appVersion"`
AppUrl string `json:"appUrl"`
AppHash string `json:"appHash"`
SystemVersion string `json:"systemVersion"`
SystemUrl string `json:"systemUrl"`
SystemHash string `json:"systemHash"`
}
type LocalMetadata struct {
AppVersion string `json:"appVersion"`
SystemVersion string `json:"systemVersion"`
}
type RemoteMetadata struct {
AppVersion string `json:"appVersion"`
AppUrl string `json:"appUrl"`
AppHash string `json:"appHash"`
SystemUrl string `json:"systemUrl"`
SystemHash string `json:"systemHash,omitempty"`
SystemVersion string `json:"systemVersion"`
}
// UpdateStatus represents the current update status
type UpdateStatus struct {
Local *LocalMetadata `json:"local"`
Remote *RemoteMetadata `json:"remote"`
SystemUpdateAvailable bool `json:"systemUpdateAvailable"`
AppUpdateAvailable bool `json:"appUpdateAvailable"`
// for backwards compatibility
Error string `json:"error,omitempty"`
}
var UpdateGithubAppReleaseUrls = []string{
"https://api.github.com/repos/LuckfoxTECH/kvm/releases/latest",
"https://api.github.com/repos/LuckfoxTECH/kvm_app/releases/latest",
"https://api.github.com/repos/luckfox-eng29/kvm/releases/latest",
"https://api.github.com/repos/luckfox-eng29/kvm_app/releases/latest",
}
var UpdateGiteeAppReleaseUrls = []string{
"https://gitee.com/api/v5/repos/LuckfoxTECH/kvm/releases/latest",
"https://gitee.com/api/v5/repos/LuckfoxTECH/kvm_app/releases/latest",
"https://gitee.com/api/v5/repos/luckfox-eng29/kvm/releases/latest",
"https://gitee.com/api/v5/repos/luckfox-eng29/kvm_app/releases/latest",
}
var UpdateGithubSystemReleaseUrls = []string{
"https://api.github.com/repos/LuckfoxTECH/kvm_system/releases/latest",
"https://api.github.com/repos/luckfox-eng29/kvm_system/releases/latest",
}
var UpdateGiteeSystemReleaseUrls = []string{
"https://gitee.com/api/v5/repos/LuckfoxTECH/kvm_system/releases/latest",
"https://gitee.com/api/v5/repos/luckfox-eng29/kvm_system/releases/latest",
}
var UpdateGiteeSystemZipUrls = []string{
"https://gitee.com/LuckfoxTECH/kvm_system/archive/refs/tags/",
"https://gitee.com/luckfox-eng29/kvm_system/archive/refs/tags/",
}
const cdnUpdateBaseURL = "https://cdn.picokvm.top/luckfox_picokvm_firmware/lastest/"
var builtAppVersion = "0.1.2+dev"
var updateSource = "github"
var customUpdateBaseURL string
const (
updateSourceGithub = "github"
updateSourceGitee = "gitee"
updateSourceCDN = "cdn"
updateSourceCustom = "custom"
)
func rpcSetUpdateSource(source string) error {
switch source {
case updateSourceGithub, updateSourceGitee, updateSourceCDN, updateSourceCustom:
default:
return fmt.Errorf("invalid update source: %s", source)
}
updateSource = source
return nil
}
func GetLocalVersion() (systemVersion *semver.Version, appVersion *semver.Version, err error) {
appVersion, err = semver.NewVersion(builtAppVersion)
if err != nil {
return nil, nil, fmt.Errorf("invalid built-in app version: %w", err)
}
systemVersionBytes, err := os.ReadFile("/version")
if err != nil {
return nil, appVersion, fmt.Errorf("error reading system version: %w", err)
}
systemVersion, err = semver.NewVersion(strings.TrimSpace(string(systemVersionBytes)))
if err != nil {
return nil, appVersion, fmt.Errorf("invalid system version: %w", err)
}
return systemVersion, appVersion, nil
}
func fetchUpdateMetadata(ctx context.Context, deviceId string, includePreRelease bool) (*RemoteMetadata, error) {
if updateSource == updateSourceCDN || updateSource == updateSourceCustom {
baseURL := cdnUpdateBaseURL
if updateSource == updateSourceCustom {
if strings.TrimSpace(customUpdateBaseURL) == "" {
return nil, fmt.Errorf("custom update base URL is not set")
}
baseURL = customUpdateBaseURL
}
return fetchUpdateMetadataFromBaseURL(ctx, baseURL)
}
_, _ = deviceId, includePreRelease
appVersionRemote, appURL, appSha256, err := fetchKvmAppLatestRelease(ctx)
if err != nil {
return nil, err
}
systemVersionRemote, systemZipURL, err := fetchKvmSystemLatestRelease(ctx)
if err != nil {
return nil, err
}
return &RemoteMetadata{
AppUrl: appURL,
AppVersion: appVersionRemote,
AppHash: appSha256,
SystemUrl: systemZipURL,
SystemVersion: systemVersionRemote,
}, nil
}
func fetchKvmAppLatestRelease(ctx context.Context) (tag string, downloadURL string, sha256 string, err error) {
apiURLs := UpdateGithubAppReleaseUrls
fallbackToGithub := false
if updateSource == updateSourceGitee {
apiURLs = UpdateGiteeAppReleaseUrls
fallbackToGithub = true
}
tryFetch := func(urls []string) (string, string, string, error) {
var lastErr error
for _, apiURL := range urls {
req, err := http.NewRequestWithContext(ctx, "GET", apiURL, nil)
if err != nil {
lastErr = fmt.Errorf("failed to create release request for %s: %w", apiURL, err)
continue
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
lastErr = fmt.Errorf("failed to fetch release from %s: %w", apiURL, err)
continue
}
output, readErr := io.ReadAll(resp.Body)
resp.Body.Close()
if readErr != nil {
lastErr = fmt.Errorf("failed to read release response from %s: %w", apiURL, readErr)
continue
}
if resp.StatusCode != http.StatusOK {
lastErr = fmt.Errorf(
"failed to fetch release from %s: status %d: %s",
apiURL,
resp.StatusCode,
strings.TrimSpace(string(output)),
)
continue
}
var release struct {
TagName string `json:"tag_name"`
Assets []releaseAsset `json:"assets"`
}
if err := json.Unmarshal(output, &release); err != nil {
lastErr = fmt.Errorf("failed to parse releases JSON from %s: %w", apiURL, err)
continue
}
tag := strings.TrimSpace(release.TagName)
if tag == "" {
lastErr = fmt.Errorf("empty tag_name from %s", apiURL)
continue
}
var downloadURL string
var sha256 string
if len(release.Assets) > 0 {
downloadURL = release.Assets[0].BrowserDownloadURL
sha256 = release.Assets[0].Digest
}
sha256 = strings.TrimPrefix(strings.TrimSpace(sha256), "sha256:")
if strings.TrimSpace(downloadURL) == "" {
lastErr = fmt.Errorf("empty app download url from %s", apiURL)
continue
}
return tag, downloadURL, sha256, nil
}
if lastErr == nil {
lastErr = fmt.Errorf("no app release API URLs configured")
}
return "", "", "", lastErr
}
var lastErr error
tag, downloadURL, sha256, err = tryFetch(apiURLs)
if err == nil {
return tag, downloadURL, sha256, nil
}
lastErr = err
if updateSource == updateSourceGitee && fallbackToGithub {
tag, downloadURL, sha256, err = tryFetch(UpdateGithubAppReleaseUrls)
if err == nil {
downloadURL = strings.Replace(downloadURL, "github.com", "gitee.com", 1)
return tag, downloadURL, sha256, nil
}
lastErr = fmt.Errorf("gitee app release fetch failed (%v); github fallback failed (%w)", lastErr, err)
}
return "", "", "", lastErr
}
type releaseAsset struct {
BrowserDownloadURL string `json:"browser_download_url"`
Name string `json:"name"`
Digest string `json:"digest"`
}
func pickZipAssetURL(assets []releaseAsset) string {
for _, a := range assets {
u := strings.TrimSpace(a.BrowserDownloadURL)
if u == "" {
continue
}
name := strings.ToLower(strings.TrimSpace(a.Name))
if strings.HasSuffix(name, ".zip") || strings.HasSuffix(strings.ToLower(u), ".zip") {
return u
}
}
if len(assets) == 1 {
return strings.TrimSpace(assets[0].BrowserDownloadURL)
}
return ""
}
func fetchKvmSystemLatestRelease(ctx context.Context) (tag string, zipURL string, err error) {
apiURLs := UpdateGithubSystemReleaseUrls
fallbackToGithub := false
if updateSource == updateSourceGitee {
apiURLs = UpdateGiteeSystemReleaseUrls
fallbackToGithub = true
}
var lastErr error
for _, apiURL := range apiURLs {
req, err := http.NewRequestWithContext(ctx, "GET", apiURL, nil)
if err != nil {
lastErr = fmt.Errorf("error creating system release request: %w", err)
continue
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
lastErr = fmt.Errorf("error fetching system release: %w", err)
continue
}
body, readErr := io.ReadAll(resp.Body)
resp.Body.Close()
if readErr != nil {
lastErr = fmt.Errorf("error reading system release response: %w", readErr)
continue
}
if resp.StatusCode != http.StatusOK {
lastErr = fmt.Errorf(
"unexpected status code fetching system release from %s: %d, %s",
apiURL,
resp.StatusCode,
strings.TrimSpace(string(body)),
)
continue
}
var release struct {
TagName string `json:"tag_name"`
ZipballURL string `json:"zipball_url"`
Assets []releaseAsset `json:"assets"`
}
if err := json.Unmarshal(body, &release); err != nil {
lastErr = fmt.Errorf("error parsing system release JSON from %s: %w", apiURL, err)
continue
}
tag := strings.TrimSpace(release.TagName)
if tag == "" {
lastErr = fmt.Errorf("empty system tag_name from %s", apiURL)
continue
}
if u := pickZipAssetURL(release.Assets); strings.TrimSpace(u) != "" {
return tag, strings.TrimSpace(u), nil
}
if strings.TrimSpace(release.ZipballURL) != "" {
return tag, strings.TrimSpace(release.ZipballURL), nil
}
lastErr = fmt.Errorf("no usable system archive url in release response from %s", apiURL)
continue
}
if lastErr == nil {
lastErr = fmt.Errorf("no system release API URLs configured")
}
if updateSource == updateSourceGitee && fallbackToGithub {
var githubErr error
var githubTag string
var githubZipURL string
for i, apiURL := range UpdateGithubSystemReleaseUrls {
githubTag, githubZipURL, githubErr = func(apiURL string) (string, string, error) {
req, err := http.NewRequestWithContext(ctx, "GET", apiURL, nil)
if err != nil {
return "", "", fmt.Errorf("error creating system release request: %w", err)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return "", "", fmt.Errorf("error fetching system release: %w", err)
}
body, readErr := io.ReadAll(resp.Body)
resp.Body.Close()
if readErr != nil {
return "", "", fmt.Errorf("error reading system release response: %w", readErr)
}
if resp.StatusCode != http.StatusOK {
return "", "", fmt.Errorf(
"unexpected status code fetching system release from %s: %d, %s",
apiURL,
resp.StatusCode,
strings.TrimSpace(string(body)),
)
}
var release struct {
TagName string `json:"tag_name"`
ZipballURL string `json:"zipball_url"`
Assets []releaseAsset `json:"assets"`
}
if err := json.Unmarshal(body, &release); err != nil {
return "", "", fmt.Errorf("error parsing system release JSON from %s: %w", apiURL, err)
}
tag := strings.TrimSpace(release.TagName)
if tag == "" {
return "", "", fmt.Errorf("empty system tag_name from %s", apiURL)
}
if u := pickZipAssetURL(release.Assets); strings.TrimSpace(u) != "" {
return tag, strings.TrimSpace(u), nil
}
if strings.TrimSpace(release.ZipballURL) != "" {
return tag, strings.TrimSpace(release.ZipballURL), nil
}
return "", "", fmt.Errorf("no usable system archive url in release response from %s", apiURL)
}(apiURL)
if githubErr == nil && strings.TrimSpace(githubTag) != "" {
_ = githubZipURL
selectedZipURL := ""
if i < len(UpdateGiteeSystemZipUrls) {
selectedZipURL = UpdateGiteeSystemZipUrls[i]
} else if len(UpdateGiteeSystemZipUrls) > 0 {
selectedZipURL = UpdateGiteeSystemZipUrls[0]
}
if strings.TrimSpace(selectedZipURL) != "" {
zipTag := strings.TrimSpace(githubTag)
if v, parseErr := semver.NewVersion(zipTag); parseErr == nil && v != nil {
zipTag = v.String()
} else {
zipTag = strings.TrimPrefix(zipTag, "v")
zipTag = strings.TrimPrefix(zipTag, "V")
}
zipURL := strings.TrimRight(selectedZipURL, "/") + "/" + zipTag + ".zip"
return githubTag, zipURL, nil
}
githubErr = fmt.Errorf("no gitee system zip urls configured")
break
}
}
return "", "", fmt.Errorf("gitee system release fetch failed (%v); github fallback failed (%w)", lastErr, githubErr)
}
return "", "", lastErr
}
func fetchUpdateMetadataFromBaseURL(ctx context.Context, baseURL string) (*RemoteMetadata, error) {
baseURL = normalizeBaseURL(baseURL)
versionURL, err := resolveURL(baseURL, "version.txt")
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, "GET", versionURL, nil)
if err != nil {
return nil, fmt.Errorf("error creating request: %w", err)
}
client := http.Client{
Timeout: 30 * time.Second,
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
TLSHandshakeTimeout: 30 * time.Second,
TLSClientConfig: &tls.Config{
RootCAs: rootcerts.ServerCertPool(),
},
},
}
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("error fetching version.txt: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("unexpected status code fetching version.txt: %d", resp.StatusCode)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("error reading version.txt: %w", err)
}
appVersion, systemVersion, err := parseVersionTxt(string(body))
if err != nil {
return nil, err
}
appURL, err := resolveURL(baseURL, "kvm_app")
if err != nil {
return nil, err
}
appHash, err := fetchFirstSHA256FromBaseURL(ctx, baseURL, []string{"kvm_app.sha2565", "kvm_app.sha256"})
if err != nil {
return nil, err
}
systemURL, err := resolveURL(baseURL, "update_system.zip")
if err != nil {
return nil, err
}
systemHash, err := fetchFirstSHA256FromBaseURL(ctx, baseURL, []string{"update_system.zip.sha2565", "update_system.zip.sha256"})
if err != nil {
var urlErr error
systemURL, urlErr = resolveURL(baseURL, "update_system.tar")
if urlErr != nil {
return nil, err
}
var hashErr error
systemHash, hashErr = fetchFirstSHA256FromBaseURL(ctx, baseURL, []string{"update_system.tar.sha256"})
if hashErr != nil {
return nil, err
}
}
return &RemoteMetadata{
AppVersion: appVersion,
AppUrl: appURL,
AppHash: appHash,
SystemVersion: systemVersion,
SystemUrl: systemURL,
SystemHash: systemHash,
}, nil
}
func extractUpdateSystemTarFromZip(zipPath string, tarPath string) error {
r, err := zip.OpenReader(zipPath)
if err != nil {
return fmt.Errorf("failed to open update_system.zip: %w", err)
}
defer r.Close()
var tarFile *zip.File
for _, f := range r.File {
if strings.TrimSpace(f.Name) == "" {
continue
}
if filepath.Base(f.Name) == "update_system.tar" {
tarFile = f
break
}
}
if tarFile == nil {
return fmt.Errorf("update_system.tar not found in %s", zipPath)
}
rc, err := tarFile.Open()
if err != nil {
return fmt.Errorf("failed to open update_system.tar in zip: %w", err)
}
defer rc.Close()
tmpPath := tarPath + ".tmp"
_ = os.Remove(tmpPath)
out, err := os.Create(tmpPath)
if err != nil {
return fmt.Errorf("failed to create %s: %w", tmpPath, err)
}
_, copyErr := io.Copy(out, rc)
closeErr := out.Close()
if copyErr != nil {
_ = os.Remove(tmpPath)
return fmt.Errorf("failed to extract update_system.tar: %w", copyErr)
}
if closeErr != nil {
_ = os.Remove(tmpPath)
return fmt.Errorf("failed to close %s: %w", tmpPath, closeErr)
}
_ = os.Remove(tarPath)
if err := os.Rename(tmpPath, tarPath); err != nil {
_ = os.Remove(tmpPath)
return fmt.Errorf("failed to move extracted tar: %w", err)
}
return nil
}
func fetchFirstSHA256FromBaseURL(ctx context.Context, baseURL string, candidates []string) (string, error) {
var lastErr error
for _, name := range candidates {
u, err := resolveURL(baseURL, name)
if err != nil {
lastErr = err
continue
}
hash, err := fetchSHA256FromURL(ctx, u)
if err == nil {
return hash, nil
}
lastErr = err
}
if lastErr == nil {
lastErr = fmt.Errorf("no sha256 candidates provided")
}
return "", lastErr
}
func fetchSHA256FromURL(ctx context.Context, shaURL string) (string, error) {
req, err := http.NewRequestWithContext(ctx, "GET", shaURL, nil)
if err != nil {
return "", fmt.Errorf("error creating request: %w", err)
}
client := http.Client{
Timeout: 30 * time.Second,
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
TLSHandshakeTimeout: 30 * time.Second,
TLSClientConfig: &tls.Config{
RootCAs: rootcerts.ServerCertPool(),
},
},
}
resp, err := client.Do(req)
if err != nil {
return "", fmt.Errorf("error fetching sha256 file: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("unexpected status code fetching sha256 file: %d", resp.StatusCode)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", fmt.Errorf("error reading sha256 file: %w", err)
}
hash, err := parseSHA256Text(string(body))
if err != nil {
return "", fmt.Errorf("invalid sha256 file content: %w", err)
}
return hash, nil
}
func parseSHA256Text(s string) (string, error) {
re := regexp.MustCompile(`(?i)\b([a-f0-9]{64})\b`)
match := re.FindStringSubmatch(s)
if len(match) < 2 {
return "", fmt.Errorf("no sha256 hash found")
}
hash := strings.ToLower(strings.TrimSpace(match[1]))
hash = strings.TrimPrefix(hash, "sha256:")
return hash, nil
}
func normalizeBaseURL(baseURL string) string {
s := strings.TrimSpace(baseURL)
if s == "" {
return s
}
if !strings.HasPrefix(s, "http://") && !strings.HasPrefix(s, "https://") {
s = "https://" + s
}
if !strings.HasSuffix(s, "/") {
s += "/"
}
return s
}
func resolveURL(baseURL string, path string) (string, error) {
u, err := url.Parse(baseURL)
if err != nil {
return "", fmt.Errorf("invalid base URL: %w", err)
}
ref, err := url.Parse(path)
if err != nil {
return "", fmt.Errorf("invalid URL path: %w", err)
}
return u.ResolveReference(ref).String(), nil
}
func parseVersionTxt(s string) (appVersion string, systemVersion string, err error) {
reApp := regexp.MustCompile(`(?i)\bAppVersion\s*:\s*([0-9A-Za-z.\-+v]+)\b`)
reSys := regexp.MustCompile(`(?i)\bSystemVersion\s*:\s*([0-9A-Za-z.\-+v]+)\b`)
appMatch := reApp.FindStringSubmatch(s)
sysMatch := reSys.FindStringSubmatch(s)
if len(appMatch) < 2 || len(sysMatch) < 2 {
return "", "", fmt.Errorf("invalid version.txt format")
}
appVersion = strings.TrimSpace(appMatch[1])
systemVersion = strings.TrimSpace(sysMatch[1])
return appVersion, systemVersion, nil
}
func shouldProxyUpdateDownloadURL(u *url.URL) bool {
if u == nil {
return false
}
host := strings.ToLower(strings.TrimSpace(u.Hostname()))
if host == "" {
return false
}
if host == "github.com" || host == "api.github.com" || host == "codeload.github.com" || host == "raw.githubusercontent.com" {
return true
}
if strings.HasSuffix(host, ".github.com") || strings.HasSuffix(host, ".githubusercontent.com") || strings.HasSuffix(host, ".githubassets.com") {
return true
}
return false
}
func applyUpdateDownloadProxyPrefix(rawURL string) string {
if config == nil {
return rawURL
}
proxy := strings.TrimSpace(config.UpdateDownloadProxy)
if proxy == "" {
return rawURL
}
proxy = strings.TrimRight(proxy, "/") + "/"
if strings.HasPrefix(rawURL, proxy) {
return rawURL
}
parsed, err := url.Parse(rawURL)
if err != nil || parsed == nil {
return rawURL
}
if parsed.Scheme != "http" && parsed.Scheme != "https" {
return rawURL
}
if !shouldProxyUpdateDownloadURL(parsed) {
return rawURL
}
return proxy + rawURL
}
func downloadFile(
ctx context.Context,
path string,
url string,
downloadProgress *float32,
downloadSpeedBps *float32,
) error {
//if _, err := os.Stat(path); err == nil {
// if err := os.Remove(path); err != nil {
// return fmt.Errorf("error removing existing file: %w", err)
// }
//}
finalURL := applyUpdateDownloadProxyPrefix(url)
otaLogger.Info().Str("path", path).Str("url", finalURL).Msg("downloading file")
unverifiedPath := path + ".unverified"
if _, err := os.Stat(unverifiedPath); err == nil {
if err := os.Remove(unverifiedPath); err != nil {
return fmt.Errorf("error removing existing unverified file: %w", err)
}
}
file, err := os.Create(unverifiedPath)
if err != nil {
return fmt.Errorf("error creating file: %w", err)
}
defer file.Close()
req, err := http.NewRequestWithContext(ctx, "GET", finalURL, nil)
if err != nil {
return fmt.Errorf("error creating request: %w", err)
}
client := http.Client{
Timeout: 10 * time.Minute,
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
TLSHandshakeTimeout: 30 * time.Second,
TLSClientConfig: &tls.Config{
RootCAs: rootcerts.ServerCertPool(),
},
},
}
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("error downloading file: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("unexpected status code: %d", resp.StatusCode)
}
totalSize := resp.ContentLength
hasKnownSize := totalSize > 0
var written int64
var lastProgressBytes int64
lastProgressAt := time.Now()
lastReportedProgress := float32(0)
lastSpeedAt := time.Now()
var lastSpeedBytes int64
if downloadProgress != nil {
*downloadProgress = 0
}
if downloadSpeedBps != nil {
*downloadSpeedBps = 0
}
if downloadProgress != nil || downloadSpeedBps != nil {
triggerOTAStateUpdate()
}
buf := make([]byte, 32*1024)
for {
nr, er := resp.Body.Read(buf)
if nr > 0 {
nw, ew := file.Write(buf[0:nr])
if nw < nr {
return fmt.Errorf("short write: %d < %d", nw, nr)
}
written += int64(nw)
if ew != nil {
return fmt.Errorf("error writing to file: %w", ew)
}
now := time.Now()
speedUpdated := false
progressUpdated := false
if downloadSpeedBps != nil {
dt := now.Sub(lastSpeedAt)
if dt >= 1*time.Second {
seconds := float32(dt.Seconds())
if seconds <= 0 {
*downloadSpeedBps = 0
} else {
*downloadSpeedBps = float32(written-lastSpeedBytes) / seconds
}
lastSpeedAt = now
lastSpeedBytes = written
speedUpdated = true
}
}
if hasKnownSize && downloadProgress != nil {
progress := float32(written) / float32(totalSize)
if progress-lastReportedProgress >= 0.001 || now.Sub(lastProgressAt) >= 1*time.Second {
lastReportedProgress = progress
*downloadProgress = lastReportedProgress
lastProgressAt = now
progressUpdated = true
}
}
if !hasKnownSize && downloadProgress != nil {
if *downloadProgress <= 0 {
*downloadProgress = 0.01
lastProgressBytes = written
progressUpdated = true
} else if written-lastProgressBytes >= 1024*1024 {
next := *downloadProgress + 0.01
if next > 0.99 {
next = 0.99
}
if next-*downloadProgress >= 0.01 {
*downloadProgress = next
lastProgressBytes = written
progressUpdated = true
}
}
}
if speedUpdated || progressUpdated {
triggerOTAStateUpdate()
}
}
if er != nil {
if er == io.EOF {
break
}
return fmt.Errorf("error reading response body: %w", er)
}
}
if hasKnownSize && written != totalSize {
return fmt.Errorf("incomplete download: wrote %d bytes, expected %d bytes", written, totalSize)
}
if downloadProgress != nil && !hasKnownSize {
*downloadProgress = 1
if downloadSpeedBps != nil {
*downloadSpeedBps = 0
}
triggerOTAStateUpdate()
}
if downloadSpeedBps != nil && hasKnownSize {
*downloadSpeedBps = 0
triggerOTAStateUpdate()
}
file.Close()
// Flush filesystem buffers to ensure all data is written to disk
err = exec.Command("sync").Run()
if err != nil {
otaLogger.Warn().Err(err).Msg("Failed to flush filesystem buffers")
}
// Clear the filesystem caches to force a read from disk
err = os.WriteFile("/proc/sys/vm/drop_caches", []byte("1"), 0644)
if err != nil {
otaLogger.Warn().Err(err).Msg("Failed to clear filesystem caches")
}
// without check
//if err := os.Rename(unverifiedPath, path); err != nil {
// return fmt.Errorf("error renaming file: %w", err)
//}
//if err := os.Chmod(path, 0755); err != nil {
// return fmt.Errorf("error making file executable: %w", err)
//}
return nil
}
func prepareSystemUpdateTarFromKvmSystemZip(
ctx context.Context,
zipURL string,
outputTarPath string,
downloadProgress *float32,
downloadSpeedBps *float32,
verificationProgress *float32,
scopedLogger *zerolog.Logger,
) error {
if scopedLogger == nil {
scopedLogger = otaLogger
}
baseDir := "/userdata/picokvm"
workDir := filepath.Join(baseDir, "kvm_system_work")
extractDir := filepath.Join(workDir, "extract")
zipPath := filepath.Join(workDir, "master.zip")
if err := os.MkdirAll(workDir, 0755); err != nil {
return fmt.Errorf("error creating work dir: %w", err)
}
if err := os.RemoveAll(extractDir); err != nil {
return fmt.Errorf("error cleaning extract dir: %w", err)
}
if err := os.MkdirAll(extractDir, 0755); err != nil {
return fmt.Errorf("error creating extract dir: %w", err)
}
if verificationProgress != nil {
*verificationProgress = 0
triggerOTAStateUpdate()
}
maxAttempts := 3
var lastErr error
for attempt := 1; attempt <= maxAttempts; attempt++ {
if downloadProgress != nil {
*downloadProgress = 0
}
if downloadSpeedBps != nil {
*downloadSpeedBps = 0
}
if downloadProgress != nil || downloadSpeedBps != nil {
triggerOTAStateUpdate()
}
if err := downloadFile(ctx, zipPath, zipURL, downloadProgress, downloadSpeedBps); err != nil {
lastErr = err
} else {
zipUnverifiedPath := zipPath + ".unverified"
if _, err := os.Stat(zipUnverifiedPath); err != nil {
lastErr = fmt.Errorf("downloaded zip not found: %s: %w", zipUnverifiedPath, err)
} else {
if err := unzipArchive(zipUnverifiedPath, extractDir); err != nil {
lastErr = err
} else {
lastErr = nil
break
}
}
}
_ = os.Remove(zipPath + ".unverified")
_ = os.RemoveAll(extractDir)
_ = os.MkdirAll(extractDir, 0755)
if attempt < maxAttempts {
time.Sleep(time.Duration(attempt*2) * time.Second)
}
}
if lastErr != nil {
return lastErr
}
extractedRoot := filepath.Join(extractDir, "kvm_system-master")
if _, err := os.Stat(extractedRoot); err != nil {
entries, readErr := os.ReadDir(extractDir)
if readErr != nil {
return fmt.Errorf("error reading extracted dir: %w", readErr)
}
found := ""
for _, entry := range entries {
if entry.IsDir() {
found = filepath.Join(extractDir, entry.Name())
break
}
}
if found == "" {
return fmt.Errorf("unable to find extracted root dir in %s", extractDir)
}
extractedRoot = found
}
scriptPath := filepath.Join(extractedRoot, "split_and_check_md5.sh")
if _, err := os.Stat(scriptPath); err != nil {
return fmt.Errorf("split_and_check_md5.sh not found: %w", err)