Check, preview and apply look at the repository's release tags and the channel together; the new nixos-router is a highlighted row in the preview table. The update server section and the separate git update are gone; bundles stay. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
323 lines
9.0 KiB
Go
323 lines
9.0 KiB
Go
package main
|
|
|
|
import (
|
|
"archive/tar"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"mime/multipart"
|
|
"net/http"
|
|
"net/url"
|
|
"os"
|
|
"path"
|
|
"path/filepath"
|
|
"regexp"
|
|
"strings"
|
|
)
|
|
|
|
// Updates arrive as a tar of a signed binary cache (see lib.mkRelease):
|
|
//
|
|
// latest
|
|
// cache/nix-cache-info
|
|
// cache/<hash>.narinfo
|
|
// cache/nar/<hash>.nar[.zst|.xz]
|
|
//
|
|
// The UI only stages the files; router-update (root, a systemd unit) verifies
|
|
// the signatures. Extraction is still strict: only these names, only regular
|
|
// files, bounded in size, so a hostile bundle cannot write elsewhere.
|
|
|
|
const (
|
|
maxBundle = 8 << 30 // bytes in all
|
|
maxLatest = 64 << 10
|
|
)
|
|
|
|
var bundleNames = []*regexp.Regexp{
|
|
regexp.MustCompile(`^latest$`),
|
|
regexp.MustCompile(`^cache/nix-cache-info$`),
|
|
regexp.MustCompile(`^cache/[0-9a-z]{32}\.narinfo$`),
|
|
regexp.MustCompile(`^cache/nar/[0-9a-z]{20,64}\.nar(\.[a-z0-9]{1,5})?$`),
|
|
}
|
|
|
|
// unbundle extracts a bundle into dir, which it replaces.
|
|
func unbundle(r io.Reader, dir string) error {
|
|
dir = filepath.Clean(dir)
|
|
tmp := dir + ".tmp"
|
|
if err := os.RemoveAll(tmp); err != nil {
|
|
return err
|
|
}
|
|
if err := os.MkdirAll(filepath.Join(tmp, "cache", "nar"), 0o700); err != nil {
|
|
return err
|
|
}
|
|
if err := extract(tar.NewReader(r), tmp); err != nil {
|
|
os.RemoveAll(tmp)
|
|
return err
|
|
}
|
|
for _, f := range []string{"latest", "cache/nix-cache-info"} {
|
|
if _, err := os.Stat(filepath.Join(tmp, f)); err != nil {
|
|
os.RemoveAll(tmp)
|
|
return fmt.Errorf("not an update bundle: %s is missing", f)
|
|
}
|
|
}
|
|
if err := os.RemoveAll(dir); err != nil {
|
|
return err
|
|
}
|
|
return os.Rename(tmp, dir)
|
|
}
|
|
|
|
func extract(tr *tar.Reader, root string) error {
|
|
var total int64
|
|
for {
|
|
hdr, err := tr.Next()
|
|
if errors.Is(err, io.EOF) {
|
|
return nil
|
|
}
|
|
if err != nil {
|
|
return fmt.Errorf("not an update bundle: %w", err)
|
|
}
|
|
name := path.Clean(strings.TrimPrefix(hdr.Name, "./"))
|
|
switch hdr.Typeflag {
|
|
case tar.TypeDir:
|
|
// Directories are made here; the entries only have to be harmless.
|
|
switch name {
|
|
case ".", "cache", "cache/nar", "cache/log", "cache/realisations":
|
|
continue
|
|
}
|
|
return fmt.Errorf("unexpected directory %q in the bundle", hdr.Name)
|
|
case tar.TypeReg:
|
|
default:
|
|
return fmt.Errorf("unexpected entry %q in the bundle (only plain files are allowed)", hdr.Name)
|
|
}
|
|
ok := false
|
|
for _, re := range bundleNames {
|
|
ok = ok || re.MatchString(name)
|
|
}
|
|
if !ok {
|
|
return fmt.Errorf("unexpected file %q in the bundle", hdr.Name)
|
|
}
|
|
limit := int64(maxBundle) - total
|
|
if name == "latest" {
|
|
limit = min(limit, maxLatest)
|
|
}
|
|
if hdr.Size > limit {
|
|
return fmt.Errorf("the bundle is too large (%q)", hdr.Name)
|
|
}
|
|
f, err := os.OpenFile(filepath.Join(root, filepath.FromSlash(name)), os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
|
|
if err != nil {
|
|
return fmt.Errorf("%q appears twice in the bundle", hdr.Name)
|
|
}
|
|
n, err := io.Copy(f, tr)
|
|
total += n
|
|
if cerr := f.Close(); err == nil {
|
|
err = cerr
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
|
|
// Release describes a version of nixos-router (/etc/router-release, and the
|
|
// latest file of an update).
|
|
type Release struct {
|
|
Version string `json:"version"`
|
|
Serial int64 `json:"serial"`
|
|
Rev string `json:"rev"`
|
|
Schema int `json:"schema"`
|
|
}
|
|
|
|
func (s System) releasePath() string {
|
|
if s.ReleaseFile != "" {
|
|
return s.ReleaseFile
|
|
}
|
|
return "/etc/router-release"
|
|
}
|
|
|
|
func (s System) installedRelease() Release {
|
|
var r Release
|
|
if data, err := os.ReadFile(s.releasePath()); err == nil {
|
|
json.Unmarshal(data, &r)
|
|
}
|
|
return r
|
|
}
|
|
|
|
func (s System) updateDir() string { return filepath.Join(s.StateDir, "update") }
|
|
|
|
// requestUpdate asks the router-update unit to install what is staged; it
|
|
// reads this file. (Updates from the repository are router-upgrade's.)
|
|
func (s System) requestUpdate(mode, url string, force bool) error {
|
|
data, _ := json.Marshal(map[string]any{"mode": mode, "url": url, "force": force})
|
|
if err := os.MkdirAll(s.updateDir(), 0o700); err != nil {
|
|
return err
|
|
}
|
|
if err := writeFileAtomic(filepath.Join(s.updateDir(), "request.json"), data, 0o600); err != nil {
|
|
return err
|
|
}
|
|
return startUnit("router-update.service")
|
|
}
|
|
|
|
// startUnit is replaced in tests.
|
|
var startUnit = func(unit string) error {
|
|
_, err := command("systemctl", "start", "--no-block", unit)
|
|
return err
|
|
}
|
|
|
|
// UpdateStatus is the state of a one-shot unit (router-update, router-upgrade)
|
|
// and what its last run logged.
|
|
type UpdateStatus struct {
|
|
Running bool
|
|
Result string // of the last run; "" if none
|
|
Log string
|
|
}
|
|
|
|
func unitRun(unit string) UpdateStatus {
|
|
st := UpdateStatus{}
|
|
st.Running = unitProperty(unit, "ActiveState") == "activating"
|
|
if inv := unitProperty(unit, "InvocationID"); inv != "" {
|
|
if !st.Running {
|
|
st.Result = unitProperty(unit, "Result")
|
|
}
|
|
st.Log, _ = command("journalctl", "--no-pager", "-o", "cat", "-n", "200", "_SYSTEMD_INVOCATION_ID="+inv)
|
|
}
|
|
return st
|
|
}
|
|
|
|
func (s System) UpdateStatus() UpdateStatus { return unitRun("router-update.service") }
|
|
|
|
// updateProgress is how far router-update has come, from the last step its log
|
|
// names: a share of the whole (the build at the end takes the longest, so the
|
|
// bar is only a guide) and what it is doing.
|
|
func updateProgress(log string) (int, string) {
|
|
steps := []struct {
|
|
marker string
|
|
pct int
|
|
what string
|
|
}{
|
|
{"router-update: verifying", 10, "Verifying the signature"},
|
|
{"router-update: importing", 30, "Importing the release"},
|
|
{"router-update: installed", 50, "Checking the version"},
|
|
{"router-update: building and activating", 70, "Building and activating the new version"},
|
|
}
|
|
pct, what := 5, "Starting"
|
|
best := -1
|
|
for _, s := range steps {
|
|
if i := strings.LastIndex(log, s.marker); i > best {
|
|
best, pct, what = i, s.pct, s.what
|
|
}
|
|
}
|
|
return pct, what
|
|
}
|
|
|
|
type updateData struct {
|
|
Installed Release
|
|
Progress int // percent, while updating
|
|
Step string // what it does now
|
|
Status UpdateStatus
|
|
Pending bool // an update waits for confirmation
|
|
}
|
|
|
|
func (a *app) updateData() updateData {
|
|
st := a.sys.Status()
|
|
d := updateData{
|
|
Installed: a.sys.installedRelease(),
|
|
Status: a.sys.UpdateStatus(),
|
|
Pending: st.RollbackIn > 0,
|
|
}
|
|
d.Progress, d.Step = updateProgress(d.Status.Log)
|
|
return d
|
|
}
|
|
|
|
// updatesData is the Updates page: the router software (a release of
|
|
// nixos-router) and the packages (nixpkgs) on one page.
|
|
type updatesData struct {
|
|
Update updateData
|
|
Upgrade upgradeData
|
|
}
|
|
|
|
func (a *app) updatesData() updatesData {
|
|
return updatesData{Update: a.updateData(), Upgrade: a.upgradeData()}
|
|
}
|
|
|
|
func (a *app) updatePage(w http.ResponseWriter, r *http.Request, sess session) {
|
|
d := a.updatesData()
|
|
p := page{Title: "Updates", CSRF: sess.csrf, LoggedIn: true, Data: d, Flash: r.URL.Query().Get("msg")}
|
|
if d.Update.Status.Running || d.Upgrade.Run.Running {
|
|
p.Live = 3
|
|
}
|
|
a.render(w, "update", p)
|
|
}
|
|
|
|
// upgradeRedirect sends the old address of the packages part to the page.
|
|
func upgradeRedirect(w http.ResponseWriter, r *http.Request, _ session) {
|
|
http.Redirect(w, r, "/update#packages", http.StatusSeeOther)
|
|
}
|
|
|
|
func (a *app) updateBack(w http.ResponseWriter, r *http.Request, msg string) {
|
|
http.Redirect(w, r, "/update?msg="+url.QueryEscape(msg), http.StatusSeeOther)
|
|
}
|
|
|
|
func (a *app) busy() bool {
|
|
st := a.sys.Status()
|
|
return st.Applying || st.ConfirmRunning || st.RollbackIn > 0 || a.sys.UpdateStatus().Running || a.sys.UpgradeStatus().Running
|
|
}
|
|
|
|
// updateUpload takes a bundle as multipart/form-data and streams it into the
|
|
// staging directory; a bundle is hundreds of megabytes. The CSRF token is in
|
|
// the query string, since the body must not be read before it is checked.
|
|
func (a *app) updateUpload(w http.ResponseWriter, r *http.Request) {
|
|
sess, ok := a.session(r)
|
|
if !ok {
|
|
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
|
return
|
|
}
|
|
if !sameOrigin(r) || r.URL.Query().Get("csrf") != sess.csrf {
|
|
http.Error(w, "forbidden", http.StatusForbidden)
|
|
return
|
|
}
|
|
if a.busy() {
|
|
a.updateBack(w, r, "Another change is in progress or waiting for confirmation.")
|
|
return
|
|
}
|
|
mr, err := r.MultipartReader()
|
|
if err != nil {
|
|
a.updateBack(w, r, "Not an upload: "+err.Error())
|
|
return
|
|
}
|
|
force := false
|
|
for {
|
|
part, err := mr.NextPart()
|
|
if errors.Is(err, io.EOF) {
|
|
a.updateBack(w, r, "No file was uploaded.")
|
|
return
|
|
}
|
|
if err != nil {
|
|
a.updateBack(w, r, "Upload failed: "+err.Error())
|
|
return
|
|
}
|
|
if part.FormName() == "force" {
|
|
force = true
|
|
continue
|
|
}
|
|
if part.FormName() == "bundle" && part.FileName() != "" {
|
|
a.stageBundle(w, r, part, force)
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
func (a *app) stageBundle(w http.ResponseWriter, r *http.Request, part *multipart.Part, force bool) {
|
|
if err := os.MkdirAll(a.sys.updateDir(), 0o700); err != nil {
|
|
a.updateBack(w, r, "Could not stage the bundle: "+err.Error())
|
|
return
|
|
}
|
|
if err := unbundle(part, filepath.Join(a.sys.updateDir(), "staged")); err != nil {
|
|
a.updateBack(w, r, "Rejected: "+err.Error())
|
|
return
|
|
}
|
|
if err := a.sys.requestUpdate("staged", "", force); err != nil {
|
|
a.updateBack(w, r, "Could not start the update: "+err.Error())
|
|
return
|
|
}
|
|
a.updateBack(w, r, "Bundle received; verifying and installing.")
|
|
}
|