Compare commits

..
2 Commits
Author SHA1 Message Date
mikeandClaude Opus 5.5 c91dbe9f7d Add self-update, release 1.0.2
nscan update installs the newest release from git.micw.org, nscan
update -c only checks; --update and --check-update work as well. The
download lands next to the running binary, is started once with
--version and only then replaces it.

Once a day an ordinary run asks in the background and mentions a newer
release in the title bar and on stderr, only on a terminal and not with
NSCAN_NO_UPDATE_CHECK set. selfupdate.go is goca's copyable template.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-26 16:25:36 +01:00
mikeandClaude Opus 5.5 60257239d7 Size table columns to their content, release 1.0.1
Each column of the device list is as wide as its widest cell and the
services get the rest of the line, instead of fixed widths and weights.
When the terminal is too narrow, the widest of name, vendor and services
are shortened first, never below their minimum.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-26 16:16:59 +01:00
12 changed files with 869 additions and 45 deletions

No files matched your search

+13
View File
@@ -1,5 +1,18 @@
# Changelog
## 1.0.2 – 2026-10-26
- Self-update: `nscan update` installs the newest release, `nscan update -c` only
checks (also `--update` and `--check-update`). Once a day nscan checks in the
background and mentions a newer release in the title bar and on stderr; set
`NSCAN_NO_UPDATE_CHECK=1` to turn that off.
## 1.0.1 – 2026-10-26
- The device list sizes its columns to their content and gives the remaining width to
the services. When the terminal is too narrow, the widest of name, vendor and services
are shortened first.
## 1.0.0 – 2026-10-26
First release.
+30 -3
View File
@@ -59,7 +59,7 @@ Download the file for your system from the
| Linux, ARM64 (e.g. Pi) | `nscan-linux-arm64` |
```sh
curl -fLo nscan https://git.micw.org/mike/nscan/releases/download/1.0.0/nscan-darwin-arm64
curl -fLo nscan https://git.micw.org/mike/nscan/releases/download/1.0.2/nscan-darwin-arm64
chmod +x nscan
sudo mv nscan /usr/local/bin/
```
@@ -78,6 +78,26 @@ cd nscan
go build -o nscan .
```
### Updating
```sh
nscan update # download the newest release and replace the running binary
nscan update -c # only check
```
`--update` and `--check-update` work as well. If nscan lives in a directory you cannot
write to, such as `/usr/local/bin`, run `sudo nscan update`. The new binary is downloaded
next to the old one and started once with `--version` before it replaces the old one,
so a broken download never takes its place.
Once a day, nscan also asks git.micw.org in the background whether there is a newer
release. If so, it says so on the next run: in the title bar of the interface, and as a
line on stderr after a command. Nothing is installed without `nscan update`. The check
stays quiet when stderr is not a terminal (pipes, scripts, cron). Set
`NSCAN_NO_UPDATE_CHECK=1` to turn it off.
Self-update arrived in 1.0.2. Replace older versions by hand once.
## Quick start
```sh
@@ -103,7 +123,9 @@ nscan scan # scan once, print a table, exit
The list updates while a scan runs and rescans every minute. `●` marks devices that are
online, `○` those that are gone (shown in cumulative mode), `⚑` tracked devices and `✓`
whitelisted ones. New devices and tracked devices that come or go appear in the event
line at the bottom and ring the terminal bell.
line at the bottom and ring the terminal bell. Each column is as wide as its content, and
the services get the rest of the line. In a narrow terminal, the widest of name, vendor
and services give way first.
Press <kbd>enter</kbd> for everything nscan knows about a device. That includes all of its
Bonjour services and the open ports from the last port scan.
@@ -171,6 +193,7 @@ nscan interfaces list network interfaces
nscan oui update download the vendor database from the IEEE
nscan oui import <file> import oui.csv/oui.txt manually
nscan oui lookup <mac> show the vendor of a MAC address
nscan update [-c] install the newest release (-c: only check)
nscan version print the version
```
@@ -248,6 +271,10 @@ nscan keeps its state in `~/.config/nscan/` (or `$XDG_CONFIG_HOME/nscan`, or
Devices are keyed by MAC address, so a custom name follows a device when its IP address
changes. Exports (<kbd>e</kbd>) go to `nscan-<date>-<time>.json` and `.csv`.
The result of the daily update check is kept in the user cache directory
(`~/Library/Caches/nscan/update.json` on macOS, `~/.cache/nscan/update.json` on Linux).
Losing it only means asking once more.
## Troubleshooting
**Only my own machine shows up (macOS).** Grant your terminal app access under
@@ -280,7 +307,7 @@ named `nscan-<os>-<arch>`, with the version from `version.txt` compiled in. A pl
[mgsh](https://git.micw.org/mike/mgsh), which attaches everything in `./bin`:
```sh
./build.sh && mgsh release 1.0.1
./build.sh && mgsh release @micw $(cat version.txt)
```
See [CHANGELOG.md](CHANGELOG.md) for what changed in each version.
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 422 KiB

After

Width:  |  Height:  |  Size: 423 KiB

+1
View File
@@ -38,6 +38,7 @@ type Config struct {
OUI *oui.DB
ExportDir string
Version string // shown in the title bar and the help screen
Update string // a newer release, if one is known
}
// Run starts the interface and blocks until the user quits.
+70
View File
@@ -3,12 +3,14 @@ package tui
import (
"net"
"net/netip"
"slices"
"strings"
"testing"
"time"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/x/ansi"
"github.com/mattn/go-runewidth"
"nscan/internal/oui"
"nscan/internal/scanner"
@@ -177,3 +179,71 @@ func TestStoredDevicesGetVendor(t *testing.T) {
t.Error("no hint about the missing vendor database")
}
}
func TestLayoutFollowsContent(t *testing.T) {
m := testModel(t)
gw := host("192.168.1.1", "3c:a6:2f:00:00:01")
gw.Gateway = true
pi := host("192.168.1.33", "b8:27:eb:00:00:03")
pi.MDNSName = "raspberrypi"
for _, typ := range []string{"_ssh._tcp", "_sftp-ssh._tcp", "_smb._tcp", "_http._tcp", "_workstation._tcp", "_rfb._tcp", "_afpovertcp._tcp", "_device-info._tcp"} {
pi.Services = append(pi.Services, scanner.Service{Type: typ, Instance: "raspberrypi"})
}
m.upsert(gw)
m.upsert(pi)
m.refresh()
width := func(cols []column, widths []int, c column) int {
return widths[slices.Index(cols, c)]
}
total := func(widths []int) int {
n := rowPrefix + 2*(len(widths)-1)
for _, w := range widths {
n += w
}
return n
}
services := runewidth.StringWidth(serviceSummary(pi.Services))
// Wide enough: every column as wide as its content, the rest for services.
m.Update(tea.WindowSizeMsg{Width: 200, Height: 30})
cols, widths := m.layout(time.Now())
if got := width(cols, widths, colName); got != len("raspberrypi") {
t.Errorf("name column %d wide, want %d", got, len("raspberrypi"))
}
if got := width(cols, widths, colIP); got != len("192.168.1.33") {
t.Errorf("IP column %d wide", got)
}
if got := width(cols, widths, colServices); got <= services {
t.Errorf("services column %d wide, want more than its content (%d)", got, services)
}
if got := total(widths); got != 200 {
t.Errorf("table %d wide, want 200", got)
}
// Too narrow: the long service list gives up width, the short name does not.
m.Update(tea.WindowSizeMsg{Width: 100, Height: 30})
cols, widths = m.layout(time.Now())
if got := width(cols, widths, colName); got != len("raspberrypi") {
t.Errorf("name column %d wide at 100 columns, want %d", got, len("raspberrypi"))
}
if got := width(cols, widths, colServices); got >= services || got < colMin[colServices] {
t.Errorf("services column %d wide at 100 columns", got)
}
if got := total(widths); got != 100 {
t.Errorf("table %d wide, want 100", got)
}
}
func TestUpdateHintShown(t *testing.T) {
m := testModel(t)
m.cfg.Version, m.cfg.Update = "1.0.1", "1.0.2"
m.Update(tea.WindowSizeMsg{Width: 120, Height: 40})
if got := ansi.Strip(m.View()); !strings.Contains(got, "nscan 1.0.1 → 1.0.2") {
t.Errorf("title bar without the update: %q", strings.SplitN(got, "\n", 2)[0])
}
m.Update(key("?"))
if got := ansi.Strip(m.View()); !strings.Contains(got, "1.0.2 is available, run nscan update") {
t.Error("help screen does not mention the update")
}
}
+1
View File
@@ -50,6 +50,7 @@ var (
styleBar = fg(mwxWhite).Background(mwxSurface)
styleBarName = fg(mwxViolet).Background(mwxSurface).Bold(true)
styleBarDim = fg(mwxGrey).Background(mwxSurface)
styleBarWarn = fg(mwxYellow).Background(mwxSurface)
// The selected row looks like fzf's current line: white on darker with a
// violet pointer.
+48 -27
View File
@@ -29,12 +29,9 @@ const (
var colTitles = [numCols]string{"Name", "IP address", "MAC address", "Vendor", "Last seen", "Ping", "Services"}
// Fixed-width columns; the others share the remaining space by weight.
var (
colFixed = map[column]int{colIP: 15, colMAC: 17, colLastSeen: 10, colRTT: 8}
colMin = map[column]int{colName: 14, colVendor: 10, colServices: 10}
colWeight = map[column]int{colName: 5, colVendor: 3, colServices: 3}
)
// colMin lists the columns that give up width when the table does not fit,
// and how narrow they may get. The others always get what their content needs.
var colMin = map[column]int{colName: 14, colVendor: 10, colServices: 10}
var sortOrder = []column{colName, colIP, colMAC, colVendor, colLastSeen, colRTT}
@@ -45,40 +42,57 @@ func nextSortColumn(c column) column {
const rowPrefix = 6 // "▸ ●⚑✓ "
func (m *model) layout() ([]column, []int) {
// layout sizes every visible column to its widest cell. When the table does not
// fit, the widest of the shrinkable columns are cut back first, so a long
// service list does not squeeze a short name. Space left over goes to the last
// column.
func (m *model) layout(now time.Time) ([]column, []int) {
var cols []column
for c := range numCols {
if m.cols[c] {
cols = append(cols, c)
}
}
avail := m.w - rowPrefix - 2*max(0, len(cols)-1)
fixed, weights := 0, 0
for _, c := range cols {
if w, ok := colFixed[c]; ok {
fixed += w
} else {
weights += colWeight[c]
}
}
flex := max(0, avail-fixed)
widths := make([]int, len(cols))
lastFlex, used := -1, 0
used := 0
for i, c := range cols {
if w, ok := colFixed[c]; ok {
widths[i] = w
continue
w := runewidth.StringWidth(colTitles[c])
if slices.Contains(sortOrder, c) {
w += 2 // room for the sort arrow, so columns do not move with it
}
widths[i] = max(colMin[c], flex*colWeight[c]/weights)
used += widths[i]
lastFlex = i
for _, d := range m.list {
w = max(w, runewidth.StringWidth(m.cellText(d, c, now)))
}
widths[i] = w
used += w
}
if lastFlex >= 0 && used < flex {
widths[lastFlex] += flex - used
avail := m.w - rowPrefix - 2*max(0, len(cols)-1)
if used > avail {
shrink(cols, widths, used-avail)
} else if len(widths) > 0 {
widths[len(widths)-1] += avail - used
}
return cols, widths
}
// shrink takes over cells away from the shrinkable columns, one at a time from
// the widest (the rightmost of equals, so names are cut last), and never below
// colMin. If that is not enough, the rows are clipped at the terminal edge.
func shrink(cols []column, widths []int, over int) {
for ; over > 0; over-- {
widest := -1
for i, c := range cols {
if lo, ok := colMin[c]; ok && widths[i] > lo && (widest < 0 || widths[i] >= widths[widest]) {
widest = i
}
}
if widest < 0 {
return
}
widths[widest]--
}
}
// fit truncates or pads s to exactly w cells.
func fit(s string, w int) string {
if w <= 0 {
@@ -141,6 +155,9 @@ func (m *model) titleBar(right string) string {
if m.cfg.Version != "" {
left += styleBarDim.Render(m.cfg.Version + " ")
}
if m.cfg.Update != "" {
left += styleBarWarn.Render("→ " + m.cfg.Update + " ")
}
left += styleBar.Render(" ")
info := fmt.Sprintf("%s · %s", n.Iface.Name, m.cfg.Range)
if n.Gateway.IsValid() {
@@ -192,7 +209,7 @@ func (m *model) viewList() string {
}
lines = append(lines, " "+status, " "+m.scanStatus(now), "")
cols, widths := m.layout()
cols, widths := m.layout(now)
header := strings.Repeat(" ", rowPrefix)
for i, c := range cols {
title := colTitles[c]
@@ -535,6 +552,10 @@ func (m *model) viewHelp() string {
if m.cfg.Version != "" {
lines = append(lines, styleDim.Render(" Version: ")+m.cfg.Version)
}
if m.cfg.Update != "" {
lines = append(lines, styleDim.Render(" Update: ")+styleWarn.Render(m.cfg.Update+" is available")+
styleDim.Render(", run ")+"nscan update"+styleDim.Render(" after quitting"))
}
body := lines[1:]
m.helpOff = min(m.helpOff, max(0, len(body)-(m.h-2)))
return m.screen(append([]string{lines[0]}, body[m.helpOff:]...), m.footer("↑/↓ scroll", "esc back"))
+55 -13
View File
@@ -36,6 +36,7 @@ const usage = `Usage:
nscan oui update download the vendor database from the IEEE
nscan oui import <file> import oui.csv/oui.txt manually
nscan oui lookup <mac> show the vendor of a MAC address
nscan update [-c] install the newest release (-c: only check)
nscan version print the version
Options for the interface and "scan":
@@ -70,34 +71,63 @@ func run(args []string) error {
args[0] = "version"
case "-h", "-help", "--help":
args[0] = "help"
case "-update", "--update":
args[0] = "update"
case "-check-update", "--check-update":
args = []string{"update", "-c"}
case updateRefreshFlag: // the background look, deliberately not in the help
selfUpdate.refresh()
return nil
}
}
if len(args) > 0 && !strings.HasPrefix(args[0], "-") {
cmd, args = args[0], args[1:]
}
var err error
switch cmd {
case "", "ui":
return runUI(args)
case "scan":
return runScan(args)
case "ping":
return runPing(args)
case "ports":
return runPorts(args)
case "wol":
return runWOL(args)
case "interfaces", "ifaces":
return runInterfaces()
case "oui":
return runOUI(args)
case "help":
printUsage(os.Stdout)
return nil
case "version":
fmt.Println("nscan " + Version)
return nil
case "update":
return runUpdate(args)
case "scan":
err = runScan(args)
case "ping":
err = runPing(args)
case "ports":
err = runPorts(args)
case "wol":
err = runWOL(args)
case "interfaces", "ifaces":
err = runInterfaces()
case "oui":
err = runOUI(args)
default:
return fmt.Errorf("unknown command %q (see nscan help)", cmd)
}
return fmt.Errorf("unknown command %q (see nscan help)", cmd)
// Costs nothing: the hint comes from a note in the cache, and the asking
// happens at most once a day, in the background.
if hint := selfUpdate.daily(); hint != "" {
fmt.Fprintln(os.Stderr, hint)
}
return err
}
func runUpdate(args []string) error {
fl := newFlags("update")
checkOnly := fl.Bool("c", false, "only check")
if err := fl.Parse(args); err != nil {
return err
}
if *checkOnly {
return selfUpdate.check(os.Stdout)
}
return selfUpdate.install(os.Stdout)
}
func newFlags(name string) *flag.FlagSet {
@@ -173,6 +203,17 @@ func runUI(args []string) error {
if err != nil {
return err
}
hint, newer := selfUpdate.daily(), ""
if hint != "" {
newer = selfUpdate.loadState().Latest
}
// The hint goes to the terminal again after the interface has closed,
// where `nscan update` can be typed right away.
defer func() {
if hint != "" {
fmt.Fprintln(os.Stderr, hint)
}
}()
return tui.Run(tui.Config{
Network: n,
Range: spec,
@@ -186,6 +227,7 @@ func runUI(args []string) error {
OUI: db,
ExportDir: *exportDir,
Version: Version,
Update: newer,
})
}
+494
View File
@@ -0,0 +1,494 @@
// selfupdate.go — updating oneself from the releases of a Gitea instance.
//
// The file is meant to be copied: take it into another program, adjust the
// configuration block below, hang `--update` and `--check-update` into the
// options — done. It needs nothing but the standard library, and apart from
// that block it brings no names that do not begin with "selfUpdate" or
// "update".
//
// It assumes the layout build.sh produces: one release per version, whose tag
// is the bare number (1.0.2, a leading "v" is allowed), holding one asset
// "<name>-<goos>-<goarch>" each — that is, exactly the files from ./bin.
//
// Taken from goca. In nscan, `nscan update` and `nscan update -c` are the
// spellings of --update and --check-update, and the hints name them.
// Under /api/v1/repos/<owner>/<repo>/releases/latest Gitea hands out the newest
// release that is neither a draft nor a prerelease; GitHub speaks the same
// route with different field names and is therefore not covered.
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"time"
)
// ------------------------------------------------------------ Configuration
var selfUpdate = selfUpdater{
repo: "https://git.micw.org/mike/nscan",
asset: "nscan",
current: Version, // from version.go, set by build.sh
verify: []string{"--version"},
every: 24 * time.Hour,
quietEnv: "NSCAN_NO_UPDATE_CHECK",
}
type selfUpdater struct {
repo string // repo URL as in the browser: https://host/owner/repo
asset string // base name of the assets, "-<goos>-<goarch>" is added
current string // the running version
verify []string // trial run of the download; empty skips it
every time.Duration // how often to look on its own; 0 turns that off
quietEnv string // this environment variable set: keep quiet as well
}
// updateRefreshFlag is the option the program calls itself with, in the
// background. It is deliberately absent from the help.
const updateRefreshFlag = "--update-refresh"
// ------------------------------------------------------------ Looking by itself
// daily is the hook for the ordinary run of the program. It costs nothing: in
// the foreground the network is never touched. What comes back is the line
// pointing at a new version — or "", when there is nothing to say; what it
// looks like is up to the caller. Should the note be older than `every`, daily
// starts a background run on the side, whose answer the next call will find
// waiting.
func (u selfUpdater) daily() string {
if u.every <= 0 || os.Getenv(u.quietEnv) != "" || !updateOnTerminal() {
return ""
}
st := u.loadState() // no file: the zero value, hence due at once
if time.Since(st.Checked) >= u.every {
// The timestamp moves on before the asking, not after: otherwise two
// simultaneous runs start two queries, and a server that is not in the
// mood would get a new one on every call. If the note does not stay
// put, nothing is asked either — else an unwritable cache directory
// would mean one process per call.
st.Checked = time.Now()
if u.saveState(st) == nil {
u.spawnRefresh()
}
}
if st.Latest == "" || updateCompare(st.Latest, u.current) <= 0 {
return ""
}
return fmt.Sprintf("%s %s is available, run '%s update'", u.asset, st.Latest, u.asset)
}
// refresh is the background run: ask, write it down, stay quiet. The writing
// down is done by latest; if the query fails, the old state remains.
func (u selfUpdater) refresh() {
_, _ = u.latest()
}
// spawnRefresh calls this program once more, only to ask, and does not wait.
// Without a Wait the child is adopted by init when this process ends — it thus
// outlives the call, and the call's output stays untouched by it.
func (u selfUpdater) spawnRefresh() {
exe, err := os.Executable()
if err != nil {
return
}
cmd := exec.Command(exe, updateRefreshFlag)
cmd.Stdin, cmd.Stdout, cmd.Stderr = nil, nil, nil // everything to /dev/null
if cmd.Start() == nil {
cmd.Process.Release()
}
}
// The hint is meant for the person sitting there. Running in a pipe, in a
// script or under cron, the program neither asks nor says anything.
func updateOnTerminal() bool {
st, err := os.Stderr.Stat()
return err == nil && st.Mode()&os.ModeCharDevice != 0
}
// --------------------------------------------------------------------- Note
// updateState is what is left between two calls: when the last question was
// asked and what came of it.
type updateState struct {
Checked time.Time `json:"checked"`
Latest string `json:"latest"`
}
// The note lives in the cache directory, not in the configuration: if it gets
// lost, the only cost is asking once too early.
func (u selfUpdater) statePath() (string, error) {
dir, err := os.UserCacheDir()
if err != nil {
return "", err
}
return filepath.Join(dir, u.asset, "update.json"), nil
}
func (u selfUpdater) loadState() updateState {
var st updateState
path, err := u.statePath()
if err != nil {
return st
}
b, err := os.ReadFile(path)
if err != nil {
return st
}
json.Unmarshal(b, &st) // a broken file counts as none
return st
}
func (u selfUpdater) saveState(st updateState) error {
path, err := u.statePath()
if err != nil {
return err
}
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return err
}
b, err := json.Marshal(st)
if err != nil {
return err
}
// By way of a file alongside, so that a simultaneous run never comes upon
// half a JSON.
tmp := path + ".new"
if err := os.WriteFile(tmp, b, 0o644); err != nil {
return err
}
if err := os.Rename(tmp, path); err != nil {
os.Remove(tmp)
return err
}
return nil
}
// ------------------------------------------------------------------ The work
// check only looks and touches nothing.
func (u selfUpdater) check(w io.Writer) error {
rel, err := u.latest()
if err != nil {
return err
}
if updateCompare(rel.TagName, u.current) <= 0 {
fmt.Fprintf(w, "%s %s is up to date\n", u.asset, u.current)
return nil
}
fmt.Fprintf(w, "%s %s is available, running %s\n %s\n run '%s update' to install it\n",
u.asset, rel.TagName, u.current, rel.HTMLURL, u.asset)
return nil
}
// install fetches the newest release and replaces the running file with it.
func (u selfUpdater) install(w io.Writer) error {
rel, err := u.latest()
if err != nil {
return err
}
if updateCompare(rel.TagName, u.current) <= 0 {
fmt.Fprintf(w, "%s %s is up to date\n", u.asset, u.current)
return nil
}
want := fmt.Sprintf("%s-%s-%s", u.asset, runtime.GOOS, runtime.GOARCH)
if runtime.GOOS == "windows" {
want += ".exe" // build.sh keeps the extension on the Windows asset
}
var src *updateAsset
for i := range rel.Assets {
if rel.Assets[i].Name == want {
src = &rel.Assets[i]
break
}
}
if src == nil {
names := make([]string, len(rel.Assets))
for i, a := range rel.Assets {
names[i] = a.Name
}
return fmt.Errorf("release %s has no %q (only %s)", rel.TagName, want, strings.Join(names, ", "))
}
exe, err := os.Executable()
if err != nil {
return fmt.Errorf("cannot locate the running binary: %w", err)
}
// An installed nscan may be a symlink into ./bin. What should be replaced
// is the file behind it, not the link.
if real, err := filepath.EvalSymlinks(exe); err == nil {
exe = real
}
mode := os.FileMode(0o755)
if st, err := os.Stat(exe); err == nil {
mode = st.Mode().Perm()
}
fmt.Fprintf(w, "downloading %s %s (%s)\n", want, rel.TagName, updateSize(src.Size))
tmp, err := u.download(src, exe, mode)
if err != nil {
return err
}
defer os.Remove(tmp) // only bites when the renaming below falls through
if err := u.probe(tmp, rel.TagName); err != nil {
return err
}
if err := updateReplace(tmp, exe); err != nil {
return err
}
fmt.Fprintf(w, "%s %s → %s, at %s\n", u.asset, u.current, rel.TagName, exe)
return nil
}
func (u selfUpdater) download(a *updateAsset, exe string, mode os.FileMode) (string, error) {
// The new file comes into being next to the old one: same filesystem, so
// the renaming at the end is one atomic step and not half a copy. It also
// comes into being before the first byte — a missing write permission ought
// to show up before a few megabytes have gone down the wire.
dir := filepath.Dir(exe)
f, err := os.CreateTemp(dir, "."+filepath.Base(exe)+".new")
if err != nil {
var pe *os.PathError // the path is in the message already
if errors.As(err, &pe) {
err = pe.Err
}
return "", fmt.Errorf("cannot write to %s: %w (use sudo, or install %s elsewhere)", dir, err, u.asset)
}
tmp := f.Name()
resp, err := updateGet(context.Background(), a.URL)
if err != nil {
f.Close()
os.Remove(tmp)
return "", err
}
defer resp.Body.Close()
n, err := io.Copy(f, resp.Body)
if cerr := f.Close(); err == nil {
err = cerr
}
if err == nil && a.Size > 0 && n != a.Size {
err = fmt.Errorf("got %d of %d bytes from %s", n, a.Size, a.URL)
}
if err == nil {
err = os.Chmod(tmp, mode)
}
if err != nil {
os.Remove(tmp)
return "", err
}
return tmp, nil
}
// probe calls the freshly fetched runner once. That catches a file that is
// truncated, built for the wrong platform, or not executable in the first
// place, before it replaces the running one.
func (u selfUpdater) probe(path, tag string) error {
if len(u.verify) == 0 {
return nil
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
out, err := exec.CommandContext(ctx, path, u.verify...).CombinedOutput()
if err != nil {
return fmt.Errorf("the downloaded binary does not run: %w", err)
}
if !strings.Contains(string(out), strings.TrimPrefix(tag, "v")) {
return fmt.Errorf("the downloaded binary reports %q, expected %s",
strings.TrimSpace(string(out)), tag)
}
return nil
}
// updateReplace swaps the running file for the new one.
func updateReplace(tmp, exe string) error {
if err := os.Rename(tmp, exe); err == nil {
return nil
}
// Unix overwrites the file of a running program without complaint, Windows
// does not: there the old one has to be got out of the way first. Deleting
// it becomes possible when this process ends at the earliest — so the
// tidying up is allowed to fail.
old := exe + ".old"
os.Remove(old)
if err := os.Rename(exe, old); err != nil {
return fmt.Errorf("cannot replace %s: %w", exe, err)
}
if err := os.Rename(tmp, exe); err != nil {
os.Rename(old, exe) // back to how it was
return fmt.Errorf("cannot replace %s: %w", exe, err)
}
os.Remove(old)
return nil
}
// -------------------------------------------------------------------- Gitea
type updateRelease struct {
TagName string `json:"tag_name"`
HTMLURL string `json:"html_url"`
Assets []updateAsset `json:"assets"`
}
type updateAsset struct {
Name string `json:"name"`
Size int64 `json:"size"`
URL string `json:"browser_download_url"`
}
func (u selfUpdater) latest() (updateRelease, error) {
base, err := u.apiBase()
if err != nil {
return updateRelease{}, err
}
// The question is a small one; if it hangs, it does not hang for long. The
// generous time limit of updateClient is meant for the download.
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
resp, err := updateGet(ctx, base+"/releases/latest")
if err != nil {
return updateRelease{}, err
}
defer resp.Body.Close()
var rel updateRelease
if err := json.NewDecoder(resp.Body).Decode(&rel); err != nil {
return updateRelease{}, fmt.Errorf("unexpected answer from %s: %w", base, err)
}
if rel.TagName == "" {
return updateRelease{}, fmt.Errorf("%s has no releases", u.repo)
}
// Every question that succeeds fills the note — no matter whether it came
// from --update, from --check-update or from the background run.
u.saveState(updateState{Checked: time.Now(), Latest: rel.TagName})
return rel, nil
}
// apiBase turns https://host/owner/repo into the API root of the repo.
func (u selfUpdater) apiBase() (string, error) {
bad := fmt.Errorf("repo %q: expected https://host/owner/repo", u.repo)
ref, err := url.Parse(strings.TrimSuffix(strings.TrimSuffix(u.repo, "/"), ".git"))
if err != nil || ref.Host == "" {
return "", bad
}
parts := strings.Split(strings.Trim(ref.Path, "/"), "/")
if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
return "", bad
}
return fmt.Sprintf("%s://%s/api/v1/repos/%s/%s", ref.Scheme, ref.Host, parts[0], parts[1]), nil
}
// One time limit for all of it: the look costs a few hundred milliseconds, the
// download a few megabytes — both may hang, but not forever.
//
// The certificate is verified, plainly, by the default transport: on a host
// that cannot build the chain, the update check fails loudly rather than
// accepting whatever binary the network hands it.
var updateClient = &http.Client{Timeout: 5 * time.Minute}
func updateGet(ctx context.Context, target string) (*http.Response, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, target, nil)
if err != nil {
return nil, err
}
req.Header.Set("User-Agent", "selfupdate.go (+"+runtime.GOOS+"/"+runtime.GOARCH+")")
resp, err := updateClient.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
resp.Body.Close()
return nil, fmt.Errorf("GET %s: %s", target, resp.Status)
}
return resp, nil
}
// ------------------------------------------------------------------ Numbers
// updateCompare compares two versions component by component, numerically, so
// that 1.1.10 lands behind 1.1.9 and not in front of it. A leading "v" does not
// count, missing places count as 0 (1.1 == 1.1.0), and a suffix on the number
// makes the version older, not newer (1.1.6-rc1 < 1.1.6). The result is the one
// of strings.Compare: -1, 0, 1.
func updateCompare(a, b string) int {
as := strings.Split(strings.TrimPrefix(a, "v"), ".")
bs := strings.Split(strings.TrimPrefix(b, "v"), ".")
for i := 0; i < len(as) || i < len(bs); i++ {
x, y := "0", "0"
if i < len(as) {
x = as[i]
}
if i < len(bs) {
y = bs[i]
}
if c := updateComparePart(x, y); c != 0 {
return c
}
}
return 0
}
func updateComparePart(a, b string) int {
na, ra := updateSplitNum(a)
nb, rb := updateSplitNum(b)
switch {
case na != nb:
if na < nb {
return -1
}
return 1
case ra == rb:
return 0
case ra == "": // 1.1.6 is finished, 1.1.6-rc1 is not yet
return 1
case rb == "":
return -1
}
return strings.Compare(ra, rb)
}
// updateSplitNum separates "10-rc1" into 10 and "-rc1".
func updateSplitNum(s string) (int, string) {
i := 0
for i < len(s) && s[i] >= '0' && s[i] <= '9' {
i++
}
n, _ := strconv.Atoi(s[:i])
return n, s[i:]
}
// updateSize is deliberately a small formatting of its own — the file is meant
// to stand on its own.
func updateSize(b int64) string {
const k = 1024
switch {
case b > k*k:
return fmt.Sprintf("%.1f MB", float64(b)/k/k)
case b > k:
return fmt.Sprintf("%.1f KB", float64(b)/k)
default:
return fmt.Sprintf("%d B", b)
}
}
+155
View File
@@ -0,0 +1,155 @@
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
)
func TestUpdateCompare(t *testing.T) {
tests := []struct {
a, b string
want int
}{
{"1.0.1", "1.0.0", 1},
{"1.0.10", "1.0.9", 1},
{"v1.0.2", "1.0.2", 0},
{"1.1", "1.1.0", 0},
{"1.0.2-rc1", "1.0.2", -1},
{"0.9.9", "1.0.0", -1},
}
for _, tt := range tests {
if got := updateCompare(tt.a, tt.b); got != tt.want {
t.Errorf("updateCompare(%q, %q) = %d, want %d", tt.a, tt.b, got, tt.want)
}
}
}
func TestUpdateAPIBase(t *testing.T) {
got, err := selfUpdate.apiBase()
if err != nil || got != "https://git.micw.org/api/v1/repos/mike/nscan" {
t.Errorf("apiBase = %q, %v", got, err)
}
if _, err := (selfUpdater{repo: "https://git.micw.org/nscan"}).apiBase(); err == nil {
t.Error("repo without owner accepted")
}
}
// fakeForge serves a Gitea release with tag 9.9.9 whose asset is a shell
// script answering --version like nscan does.
func fakeForge(t *testing.T, size int64) (*httptest.Server, []byte) {
t.Helper()
bin := []byte("#!/bin/sh\necho nscan 9.9.9\n")
if size == 0 {
size = int64(len(bin))
}
mux := http.NewServeMux()
var srv *httptest.Server
mux.HandleFunc("/api/v1/repos/mike/nscan/releases/latest", func(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(map[string]any{
"tag_name": "9.9.9",
"html_url": srv.URL + "/mike/nscan/releases/tag/9.9.9",
"assets": []map[string]any{{
"name": fmt.Sprintf("nscan-%s-%s", runtime.GOOS, runtime.GOARCH),
"size": size,
"browser_download_url": srv.URL + "/download",
}},
})
})
mux.HandleFunc("/download", func(w http.ResponseWriter, r *http.Request) { w.Write(bin) })
srv = httptest.NewServer(mux)
t.Cleanup(srv.Close)
return srv, bin
}
// isolateCache keeps the update note out of the real cache directory.
func isolateCache(t *testing.T) {
dir := t.TempDir()
t.Setenv("HOME", dir)
t.Setenv("XDG_CACHE_HOME", dir)
}
func TestUpdateCheck(t *testing.T) {
isolateCache(t)
srv, _ := fakeForge(t, 0)
u := selfUpdater{repo: srv.URL + "/mike/nscan", asset: "nscan", current: "1.0.1"}
var out bytes.Buffer
if err := u.check(&out); err != nil {
t.Fatal(err)
}
if !strings.Contains(out.String(), "nscan 9.9.9 is available, running 1.0.1") ||
!strings.Contains(out.String(), "run 'nscan update'") {
t.Errorf("check said %q", out.String())
}
if st := u.loadState(); st.Latest != "9.9.9" || st.Checked.IsZero() {
t.Errorf("note after check: %+v", st)
}
out.Reset()
u.current = "9.9.9"
if err := u.check(&out); err != nil || !strings.Contains(out.String(), "up to date") {
t.Errorf("check on the newest version said %q, %v", out.String(), err)
}
}
func TestUpdateDownloadProbeReplace(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("the fake binary is a shell script")
}
isolateCache(t)
srv, bin := fakeForge(t, 0)
u := selfUpdater{repo: srv.URL + "/mike/nscan", asset: "nscan", current: "1.0.1", verify: []string{"--version"}}
rel, err := u.latest()
if err != nil {
t.Fatal(err)
}
exe := filepath.Join(t.TempDir(), "nscan")
if err := os.WriteFile(exe, []byte("old"), 0o755); err != nil {
t.Fatal(err)
}
tmp, err := u.download(&rel.Assets[0], exe, 0o755)
if err != nil {
t.Fatal(err)
}
if filepath.Dir(tmp) != filepath.Dir(exe) {
t.Errorf("download landed in %s, not next to the binary", tmp)
}
if err := u.probe(tmp, "9.9.8"); err == nil {
t.Error("probe accepted a binary reporting another version")
}
if err := u.probe(tmp, rel.TagName); err != nil {
t.Fatal(err)
}
if err := updateReplace(tmp, exe); err != nil {
t.Fatal(err)
}
if got, _ := os.ReadFile(exe); !bytes.Equal(got, bin) {
t.Errorf("binary after replace: %q", got)
}
}
func TestUpdateRejectsShortDownload(t *testing.T) {
isolateCache(t)
srv, _ := fakeForge(t, 1<<20) // the release claims more than is served
u := selfUpdater{repo: srv.URL + "/mike/nscan", asset: "nscan", current: "1.0.1"}
rel, err := u.latest()
if err != nil {
t.Fatal(err)
}
dir := t.TempDir()
if _, err := u.download(&rel.Assets[0], filepath.Join(dir, "nscan"), 0o755); err == nil {
t.Fatal("short download accepted")
}
if left, _ := os.ReadDir(dir); len(left) != 0 {
t.Errorf("leftovers after a failed download: %v", left)
}
}
+1 -1
View File
@@ -3,4 +3,4 @@ package main
// Version is a var, not a const, so build.sh can put the built number in via
// -ldflags "-X main.Version=…". The value here only shows up in a bare
// `go build`; the version actually built is the one in version.txt.
var Version = "1.0.0"
var Version = "1.0.2"
+1 -1
View File
@@ -1 +1 @@
1.0.0
1.0.2