Skip to content

LAN-Orangutan is a self-hosted network discovery tool. Find every device on your LAN, label and group them, snapshot your network and compare it later, and get flagged when something unexpected shows up. Single binary, no setup, Tailscale built in. Built by 291 Group.

v3.0.1

filebaybd380b16fbcf
diff --git a/README.md b/README.md
index e73eb72..f43a0b8 100644
--- a/README.md
+++ b/README.md
@@ -24,7 +24,8 @@ By [291 Group](https://291group.com)
- 🔍 Auto-discover devices using nmap
- 🏷️ Label, group, and add notes to devices
- 🌐 Multi-network support
-- 🔗 Tailscale integration
+- 🔗 Tailscale integration - tailnet peers discovered automatically
+- 📊 Live scan progress you can cancel
- 💻 Modern web dashboard with light/dark mode
- ⌨️ Full CLI with JSON output
- 🍎 Cross-platform (Linux, macOS, Windows)
@@ -100,6 +101,31 @@ The web dashboard provides:
- Auto-refresh option
- Keyboard shortcuts (/ to search, R to refresh, T to toggle theme)
+### Scan progress
+
+Scans run in the background, so the dashboard stays responsive and a long scan
+will not time out. Progress shows which network is being scanned, how many
+devices have been found, and a time estimate based on how long that network took
+to scan last time. Scanning a large network takes a few minutes, and you can
+cancel at any point.
+
+The first scan of a network has no previous timing to estimate from, so it shows
+elapsed time instead of a percentage.
+
+## Tailscale
+
+Tailscale devices are picked up automatically: if Tailscale is connected, its
+peers are added to your device list alongside the machines found on your local
+networks.
+
+Tailscale peers cannot be found by scanning, because Tailscale gives every node
+its own single-address network, leaving no range to sweep. Instead the peers are
+read from Tailscale itself, which is faster and needs no elevated privileges.
+
+Only peers that are currently online are listed, and they are shown with their
+Tailscale hostname and operating system. Peers have no MAC address, so no
+hardware vendor is looked up for them.
+
## Configuration
Config file location:
diff --git a/internal/api/api.go b/internal/api/api.go
index ebf4d5e..b46137f 100644
--- a/internal/api/api.go
+++ b/internal/api/api.go
@@ -4,8 +4,10 @@ package api
import (
"context"
"encoding/json"
+ "errors"
"net/http"
"strings"
+ "sync"
"time"
"github.com/291-Group/LAN-Orangutan/internal/config"
@@ -20,6 +22,11 @@ type Handler struct {
store *storage.Storage
cfg *config.Config
scanner *scanner.Scanner
+
+ // jobMu guards job, which holds the most recent background scan. Only one
+ // scan runs at a time.
+ jobMu sync.Mutex
+ job *scanJob
}
// NewHandler creates a new API handler
@@ -60,6 +67,12 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
h.handleNetworks(w, r)
case path == "scan":
h.handleScan(w, r)
+ case path == "scan/start":
+ h.handleScanStart(w, r)
+ case path == "scan/progress":
+ h.handleScanProgress(w, r)
+ case path == "scan/cancel":
+ h.handleScanCancel(w, r)
case path == "tailscale":
h.handleTailscale(w, r)
case path == "stats":
@@ -173,6 +186,12 @@ func (h *Handler) handleScan(w http.ResponseWriter, r *http.Request) {
return
}
+ // "all" scans every detected network, matching the CLI's behaviour
+ if strings.EqualFold(cidr, "all") {
+ h.scanAllNetworks(w, r)
+ return
+ }
+
// Validate CIDR
if !network.ValidateCIDR(cidr) {
h.error(w, http.StatusBadRequest, "invalid CIDR format")
@@ -215,6 +234,199 @@ func (h *Handler) handleScan(w http.ResponseWriter, r *http.Request) {
h.success(w, result)
}
+// networkScanSummary reports the outcome of scanning a single network as part
+// of a scan-all request.
+type networkScanSummary struct {
+ Network string `json:"network"`
+ Status string `json:"status"` // scanned, skipped or failed
+ DeviceCount int `json:"device_count"`
+ Duration float64 `json:"duration"`
+ Error string `json:"error,omitempty"`
+}
+
+// scanAllResult aggregates the per-network outcomes of a scan-all request.
+type scanAllResult struct {
+ Success bool `json:"success"`
+ Networks []networkScanSummary `json:"networks"`
+ NetworkCount int `json:"network_count"`
+ ScannedCount int `json:"scanned_count"`
+ DeviceCount int `json:"device_count"`
+ Timestamp time.Time `json:"timestamp"`
+}
+
+// scanAllNetworks scans every detected network. A network that is rate limited
+// or fails is reported in the response rather than failing the whole request,
+// so one bad interface cannot mask results from the others.
+func (h *Handler) scanAllNetworks(w http.ResponseWriter, r *http.Request) {
+ detected, err := network.DetectNetworks()
+ if err != nil {
+ h.error(w, http.StatusInternalServerError, "failed to detect networks: "+err.Error())
+ return
+ }
+ if len(detected) == 0 {
+ h.error(w, http.StatusNotFound, "no networks detected")
+ return
+ }
+
+ result := scanAllResult{
+ Networks: make([]networkScanSummary, 0, len(detected)),
+ NetworkCount: len(detected),
+ Timestamp: time.Now(),
+ }
+
+ for _, n := range detected {
+ summary := networkScanSummary{Network: n.CIDR}
+
+ lastScan := h.store.GetLastScan(n.CIDR)
+ if canScan, waitTime := h.scanner.CheckRateLimit(lastScan); !canScan {
+ summary.Status = "skipped"
+ summary.Error = "rate limited, wait " + waitTime.Round(time.Second).String()
+ result.Networks = append(result.Networks, summary)
+ continue
+ }
+
+ scan, err := h.scanNetwork(r.Context(), n.CIDR)
+ if err != nil {
+ summary.Status = "failed"
+ summary.Error = err.Error()
+ result.Networks = append(result.Networks, summary)
+ continue
+ }
+
+ summary.Status = "scanned"
+ summary.DeviceCount = scan.DeviceCount
+ summary.Duration = scan.Duration
+ result.Networks = append(result.Networks, summary)
+ result.ScannedCount++
+ result.DeviceCount += scan.DeviceCount
+ }
+
+ // Only a request where nothing at all could be scanned counts as a failure.
+ result.Success = result.ScannedCount > 0
+ h.success(w, result)
+}
+
+// resolveScanTargets turns the network parameter into the list of networks to
+// scan. "all" expands to every detected network, matching the CLI.
+func (h *Handler) resolveScanTargets(cidr string) ([]string, error) {
+ if !strings.EqualFold(cidr, "all") {
+ if !network.ValidateCIDR(cidr) {
+ return nil, errors.New("invalid CIDR format")
+ }
+ return []string{cidr}, nil
+ }
+
+ detected, err := network.DetectNetworks()
+ if err != nil {
+ return nil, errors.New("failed to detect networks: " + err.Error())
+ }
+ if len(detected) == 0 {
+ return nil, errors.New("no networks detected")
+ }
+
+ networks := make([]string, 0, len(detected))
+ for _, n := range detected {
+ networks = append(networks, n.CIDR)
+ }
+ return networks, nil
+}
+
+// handleScanStart handles POST /api/scan/start, which begins a scan in the
+// background and returns immediately. Scanning a large network takes minutes,
+// so the UI starts a job and polls /api/scan/progress rather than holding a
+// request open for the duration.
+func (h *Handler) handleScanStart(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost {
+ h.error(w, http.StatusMethodNotAllowed, "method not allowed")
+ return
+ }
+
+ cidr := r.URL.Query().Get("network")
+ if cidr == "" {
+ h.error(w, http.StatusBadRequest, "network parameter required")
+ return
+ }
+
+ networks, err := h.resolveScanTargets(cidr)
+ if err != nil {
+ h.error(w, http.StatusBadRequest, err.Error())
+ return
+ }
+
+ h.jobMu.Lock()
+ defer h.jobMu.Unlock()
+
+ if h.job != nil && h.job.isRunning() {
+ h.error(w, http.StatusConflict, "a scan is already running")
+ return
+ }
+
+ h.job = h.startScanJob(networks)
+ h.success(w, h.job.snapshot())
+}
+
+// handleScanProgress handles GET /api/scan/progress.
+func (h *Handler) handleScanProgress(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet {
+ h.error(w, http.StatusMethodNotAllowed, "method not allowed")
+ return
+ }
+
+ h.jobMu.Lock()
+ job := h.job
+ h.jobMu.Unlock()
+
+ if job == nil {
+ h.success(w, scanProgress{Status: "idle", Percent: percentUnknown})
+ return
+ }
+ h.success(w, job.snapshot())
+}
+
+// handleScanCancel handles POST /api/scan/cancel.
+func (h *Handler) handleScanCancel(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost {
+ h.error(w, http.StatusMethodNotAllowed, "method not allowed")
+ return
+ }
+
+ h.jobMu.Lock()
+ job := h.job
+ h.jobMu.Unlock()
+
+ if job == nil || !job.isRunning() {
+ h.error(w, http.StatusConflict, "no scan is running")
+ return
+ }
+
+ job.cancel()
+ h.success(w, map[string]string{"message": "scan cancelled"})
+}
+
+// scanNetwork scans a single network and merges the results into storage.
+func (h *Handler) scanNetwork(ctx context.Context, cidr string) (*types.ScanResult, error) {
+ ctx, cancel := context.WithTimeout(ctx, 5*time.Minute)
+ defer cancel()
+
+ result, err := h.scanner.Scan(ctx, cidr)
+ if err != nil {
+ return nil, err
+ }
+ if !result.Success {
+ return nil, errors.New(result.Error)
+ }
+
+ if err := h.store.MergeDevices(result.Devices); err != nil {
+ return nil, errors.New("failed to save devices")
+ }
+ h.store.SetLastScan(cidr, time.Now())
+ // Remember how long this took so the next scan of the same network can show
+ // a progress estimate based on real measured time.
+ h.store.SetLastDuration(cidr, result.Duration)
+
+ return result, nil
+}
+
// handleTailscale handles GET /api/tailscale
func (h *Handler) handleTailscale(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
diff --git a/internal/api/scanjob.go b/internal/api/scanjob.go
new file mode 100644
index 0000000..64aba74
--- /dev/null
+++ b/internal/api/scanjob.go
@@ -0,0 +1,209 @@
+package api
+
+import (
+ "context"
+ "fmt"
+ "sync"
+ "time"
+)
+
+// scanJobTimeout caps how long a single network may be scanned for before it is
+// abandoned. Large networks are slow, so this is deliberately generous.
+const scanJobTimeout = 10 * time.Minute
+
+// percentUnknown is reported when a network has never been scanned before and
+// there is therefore no timing history to estimate progress from.
+const percentUnknown = -1
+
+// scanJob tracks a scan running in the background. Scans of large networks take
+// minutes, which is far too long to hold an HTTP request open, so the scan runs
+// detached and the UI polls for progress.
+type scanJob struct {
+ id string
+ networks []string
+ cancel context.CancelFunc
+
+ mu sync.RWMutex
+ status string // running, done, cancelled or failed
+ currentNetwork string
+ networkIndex int // 1-based; 0 before the first network starts
+ deviceCount int
+ startedAt time.Time
+ networkStartedAt time.Time
+ // estimatedSeconds is how long the current network took to scan last time,
+ // or 0 when it has never been scanned before.
+ estimatedSeconds float64
+ results []networkScanSummary
+ err string
+}
+
+// scanProgress is the snapshot of a job returned to the UI.
+type scanProgress struct {
+ JobID string `json:"job_id"`
+ Status string `json:"status"`
+ CurrentNetwork string `json:"current_network,omitempty"`
+ NetworkIndex int `json:"network_index"`
+ NetworkCount int `json:"network_count"`
+ DeviceCount int `json:"device_count"`
+ Elapsed float64 `json:"elapsed"`
+ // Percent is the estimated completion of the whole job, or -1 when the
+ // current network has no timing history and progress cannot be estimated.
+ Percent float64 `json:"percent"`
+ // Remaining is the estimated number of seconds left, omitted when unknown.
+ Remaining *float64 `json:"remaining,omitempty"`
+ Networks []networkScanSummary `json:"networks"`
+ Error string `json:"error,omitempty"`
+}
+
+// snapshot returns the current progress of the job. The estimate is based on
+// how long each network took to scan previously, which is real measured data,
+// but it is only ever an estimate: nmap cannot report incremental progress for
+// a ping sweep, so there is nothing more accurate to use.
+func (j *scanJob) snapshot() scanProgress {
+ j.mu.RLock()
+ defer j.mu.RUnlock()
+
+ p := scanProgress{
+ JobID: j.id,
+ Status: j.status,
+ CurrentNetwork: j.currentNetwork,
+ NetworkIndex: j.networkIndex,
+ NetworkCount: len(j.networks),
+ DeviceCount: j.deviceCount,
+ Elapsed: time.Since(j.startedAt).Seconds(),
+ Percent: percentUnknown,
+ Networks: append([]networkScanSummary(nil), j.results...),
+ Error: j.err,
+ }
+
+ // Only a job that ran to completion is 100%. A cancelled or failed job
+ // stopped wherever it stopped, so leave its progress unknown rather than
+ // reporting it as finished.
+ if j.status == "done" {
+ p.Percent = 100
+ return p
+ }
+ if j.status != "running" {
+ return p
+ }
+
+ // Without timing history for the current network there is no honest way to
+ // estimate progress, so report it as unknown and let the UI show an
+ // indeterminate state rather than invent a number.
+ if j.estimatedSeconds <= 0 || j.networkIndex == 0 {
+ return p
+ }
+
+ // Weight every network equally: finished ones count in full, and the
+ // current one counts as its own elapsed fraction. Cap the fraction just
+ // below 1 so a network that overruns its estimate does not appear complete
+ // while it is still working.
+ fraction := time.Since(j.networkStartedAt).Seconds() / j.estimatedSeconds
+ if fraction > 0.99 {
+ fraction = 0.99
+ }
+ p.Percent = (float64(j.networkIndex-1) + fraction) / float64(len(j.networks)) * 100
+
+ remaining := (1 - fraction) * j.estimatedSeconds
+ p.Remaining = &remaining
+ return p
+}
+
+// startScanJob begins scanning the given networks in the background. The caller
+// must hold h.jobMu.
+func (h *Handler) startScanJob(networks []string) *scanJob {
+ ctx, cancel := context.WithCancel(context.Background())
+
+ job := &scanJob{
+ id: fmt.Sprintf("scan-%d", time.Now().UnixNano()),
+ networks: networks,
+ cancel: cancel,
+ status: "running",
+ startedAt: time.Now(),
+ results: make([]networkScanSummary, 0, len(networks)),
+ }
+
+ go job.run(ctx, h)
+ return job
+}
+
+// run scans each network in turn, recording the outcome of each. A network that
+// is rate limited or fails does not abort the job, so one bad interface cannot
+// hide results from the others.
+func (j *scanJob) run(ctx context.Context, h *Handler) {
+ for i, cidr := range j.networks {
+ if ctx.Err() != nil {
+ j.finish("cancelled", "")
+ return
+ }
+
+ j.beginNetwork(cidr, i+1, h.store.GetLastDuration(cidr))
+
+ summary := networkScanSummary{Network: cidr}
+
+ lastScan := h.store.GetLastScan(cidr)
+ if canScan, waitTime := h.scanner.CheckRateLimit(lastScan); !canScan {
+ summary.Status = "skipped"
+ summary.Error = "rate limited, wait " + waitTime.Round(time.Second).String()
+ j.addResult(summary, 0)
+ continue
+ }
+
+ scanCtx, cancel := context.WithTimeout(ctx, scanJobTimeout)
+ result, err := h.scanNetwork(scanCtx, cidr)
+ cancel()
+
+ if err != nil {
+ // A cancelled job surfaces as a scan error, but it is not a failure.
+ if ctx.Err() != nil {
+ j.finish("cancelled", "")
+ return
+ }
+ summary.Status = "failed"
+ summary.Error = err.Error()
+ j.addResult(summary, 0)
+ continue
+ }
+
+ summary.Status = "scanned"
+ summary.DeviceCount = result.DeviceCount
+ summary.Duration = result.Duration
+ j.addResult(summary, result.DeviceCount)
+ }
+
+ j.finish("done", "")
+}
+
+// beginNetwork records that the job has started scanning a network.
+func (j *scanJob) beginNetwork(cidr string, index int, estimate float64) {
+ j.mu.Lock()
+ defer j.mu.Unlock()
+ j.currentNetwork = cidr
+ j.networkIndex = index
+ j.networkStartedAt = time.Now()
+ j.estimatedSeconds = estimate
+}
+
+// addResult records the outcome of one network.
+func (j *scanJob) addResult(summary networkScanSummary, devices int) {
+ j.mu.Lock()
+ defer j.mu.Unlock()
+ j.results = append(j.results, summary)
+ j.deviceCount += devices
+}
+
+// finish marks the job as no longer running.
+func (j *scanJob) finish(status, err string) {
+ j.mu.Lock()
+ defer j.mu.Unlock()
+ j.status = status
+ j.err = err
+ j.currentNetwork = ""
+}
+
+// isRunning reports whether the job is still in progress.
+func (j *scanJob) isRunning() bool {
+ j.mu.RLock()
+ defer j.mu.RUnlock()
+ return j.status == "running"
+}
diff --git a/internal/cli/status.go b/internal/cli/status.go
index 85ac800..790a34d 100644
--- a/internal/cli/status.go
+++ b/internal/cli/status.go
@@ -79,10 +79,14 @@ func runStatus(cmd *cobra.Command, args []string) error {
} else if !ts.Running {
fmt.Println(" Installed but not running")
} else {
- fmt.Printf(" Status: %s\n", ts.BackendState)
- fmt.Printf(" IP: %s\n", ts.SelfIP)
- fmt.Printf(" Hostname: %s\n", ts.SelfHostname)
- fmt.Printf(" Peers: %d\n", ts.PeerCount)
+ fmt.Printf(" Status: %s\n", ts.StatusLabel())
+ // The IP and peer count are cached from the last session and go stale
+ // once Tailscale stops, so only report them while connected.
+ if ts.Connected {
+ fmt.Printf(" IP: %s\n", ts.SelfIP)
+ fmt.Printf(" Hostname: %s\n", ts.SelfHostname)
+ fmt.Printf(" Peers: %d\n", ts.PeerCount)
+ }
}
// Server config
diff --git a/internal/network/detect.go b/internal/network/detect.go
index accac68..ad6835f 100644
--- a/internal/network/detect.go
+++ b/internal/network/detect.go
@@ -54,9 +54,9 @@ func DetectNetworks() ([]types.Network, error) {
network := types.Network{
CIDR: cidr,
Interface: iface.Name,
- FriendlyName: getFriendlyName(iface.Name),
+ FriendlyName: getFriendlyName(iface.Name, ipNet.IP),
IP: ipNet.IP.String(),
- IsTailscale: isTailscaleInterface(iface.Name),
+ IsTailscale: isTailscaleInterface(iface.Name, ipNet.IP),
IsWireless: isWirelessInterface(iface.Name),
}
networks = append(networks, network)
@@ -91,9 +91,9 @@ func calculateCIDR(ip string, prefixLen int) string {
}
// getFriendlyName returns a user-friendly name for an interface
-func getFriendlyName(ifname string) string {
+func getFriendlyName(ifname string, ip net.IP) string {
switch {
- case strings.HasPrefix(ifname, "tailscale") || ifname == "utun4":
+ case isTailscaleInterface(ifname, ip):
return "Tailscale VPN"
case strings.HasPrefix(ifname, "wlan") || strings.HasPrefix(ifname, "wlp"):
return "Wi-Fi"
@@ -125,9 +125,39 @@ func getFriendlyName(ifname string) string {
}
}
-// isTailscaleInterface returns true if the interface is a Tailscale interface
-func isTailscaleInterface(ifname string) bool {
- return strings.HasPrefix(ifname, "tailscale") || ifname == "utun4"
+// tailscaleCGNAT is the address range Tailscale assigns to every node.
+var tailscaleCGNAT = &net.IPNet{
+ IP: net.IPv4(100, 64, 0, 0),
+ Mask: net.CIDRMask(10, 32),
+}
+
+// IsTailscaleNetwork reports whether a CIDR belongs to the Tailscale network.
+// Tailscale hands every node a single-address /32, so such a network cannot be
+// swept for devices; its peers have to be read from Tailscale itself.
+func IsTailscaleNetwork(cidr string) bool {
+ ip, _, err := net.ParseCIDR(cidr)
+ if err != nil {
+ return false
+ }
+ return tailscaleCGNAT.Contains(ip.To4())
+}
+
+// isTailscaleInterface returns true if the interface is a Tailscale interface.
+//
+// The interface name alone is not enough to tell: Linux uses "tailscale0", but
+// macOS uses a utun device whose number depends on how many tunnels happen to
+// exist, so it is not always utun4. Fall back to checking whether the address
+// sits in the range Tailscale assigns, which is what actually identifies it.
+// The range is only trusted on a tunnel interface, since it is shared with
+// carrier-grade NAT that an ISP could legitimately hand out on a real NIC.
+func isTailscaleInterface(ifname string, ip net.IP) bool {
+ if strings.HasPrefix(strings.ToLower(ifname), "tailscale") {
+ return true
+ }
+ if !strings.HasPrefix(ifname, "utun") && !strings.HasPrefix(ifname, "tun") {
+ return false
+ }
+ return ip != nil && tailscaleCGNAT.Contains(ip.To4())
}
// isWirelessInterface returns true if the interface is a wireless interface
diff --git a/internal/network/tailscale.go b/internal/network/tailscale.go
index 1e87ff3..e51427a 100644
--- a/internal/network/tailscale.go
+++ b/internal/network/tailscale.go
@@ -2,6 +2,7 @@ package network
import (
"encoding/json"
+ "net"
"os/exec"
"runtime"
"strings"
@@ -17,17 +18,116 @@ type tailscaleStatusJSON struct {
Name string `json:"Name"`
} `json:"CurrentTailnet"`
Self struct {
- DNSName string `json:"DNSName"`
+ DNSName string `json:"DNSName"`
+ HostName string `json:"HostName"`
+ OS string `json:"OS"`
TailscaleIPs []string `json:"TailscaleIPs"`
} `json:"Self"`
- Peer map[string]struct {
- HostName string `json:"HostName"`
- } `json:"Peer"`
+ Peer map[string]tailscalePeerJSON `json:"Peer"`
ExitNodeStatus struct {
ID string `json:"ID"`
} `json:"ExitNodeStatus"`
}
+// tailscalePeerJSON represents one peer in `tailscale status --json`
+type tailscalePeerJSON struct {
+ TailscaleIPs []string `json:"TailscaleIPs"`
+ HostName string `json:"HostName"`
+ DNSName string `json:"DNSName"`
+ OS string `json:"OS"`
+ Online bool `json:"Online"`
+}
+
+// shortName returns the peer's friendly name, preferring the hostname and
+// falling back to the first label of its DNS name.
+func (p tailscalePeerJSON) shortName() string {
+ if p.HostName != "" {
+ return p.HostName
+ }
+ name := strings.TrimSuffix(p.DNSName, ".")
+ if name == "" {
+ return ""
+ }
+ return strings.Split(name, ".")[0]
+}
+
+// ipv4 returns the peer's Tailscale IPv4 address, or "" if it has none.
+func (p tailscalePeerJSON) ipv4() string {
+ for _, addr := range p.TailscaleIPs {
+ if ip := net.ParseIP(addr); ip != nil && ip.To4() != nil {
+ return addr
+ }
+ }
+ return ""
+}
+
+// toDevice converts a peer into a device record.
+func (p tailscalePeerJSON) toDevice() types.Device {
+ return types.Device{
+ IP: p.ipv4(),
+ Hostname: p.shortName(),
+ // Tailscale peers have no MAC address to look a hardware vendor up
+ // from, but it does report each peer's operating system, which is the
+ // most useful thing to identify it by.
+ Vendor: p.OS,
+ }
+}
+
+// GetTailscaleDevices returns the devices currently reachable over Tailscale,
+// including this machine.
+//
+// Tailscale peers cannot be found by scanning: every node sits on its own /32,
+// so there is no subnet to sweep. Tailscale already knows the whole tailnet, so
+// the peers are read from it directly instead.
+//
+// Only peers that are currently online are returned. Offline peers are known to
+// Tailscale but reporting them as discovered would mark them as seen just now.
+func GetTailscaleDevices() []types.Device {
+ tailscaleBin := findTailscaleBinary()
+ if tailscaleBin == "" {
+ return nil
+ }
+
+ output, err := exec.Command(tailscaleBin, "status", "--json").Output()
+ if err != nil {
+ return nil
+ }
+
+ var tsStatus tailscaleStatusJSON
+ if err := json.Unmarshal(output, &tsStatus); err != nil {
+ return nil
+ }
+
+ // A stopped or logged-out Tailscale still lists the peers it saw last time,
+ // none of which are reachable now.
+ if tsStatus.BackendState != "Running" {
+ return nil
+ }
+
+ var devices []types.Device
+
+ self := tailscalePeerJSON{
+ TailscaleIPs: tsStatus.Self.TailscaleIPs,
+ HostName: tsStatus.Self.HostName,
+ DNSName: tsStatus.Self.DNSName,
+ OS: tsStatus.Self.OS,
+ }
+ if d := self.toDevice(); d.IP != "" {
+ devices = append(devices, d)
+ }
+
+ for _, peer := range tsStatus.Peer {
+ if !peer.Online {
+ continue
+ }
+ if d := peer.toDevice(); d.IP != "" {
+ devices = append(devices, d)
+ }
+ }
+
+ return devices
+}
+
// findTailscaleBinary finds the tailscale CLI binary path
func findTailscaleBinary() string {
// First check if it's in PATH
@@ -90,9 +190,13 @@ func GetTailscaleStatus() types.TailscaleStatus {
return status
}
+ // The daemon answered, but that only means Tailscale is installed and its
+ // service is up. The user may still be logged out or have stopped it, so
+ // the backend state decides whether it is actually connected.
status.Running = true
status.Version = tsStatus.Version
status.BackendState = tsStatus.BackendState
+ status.Connected = tsStatus.BackendState == "Running"
status.TailnetName = tsStatus.CurrentTailnet.Name
status.PeerCount = len(tsStatus.Peer)
@@ -119,6 +223,5 @@ func GetTailscaleStatus() types.TailscaleStatus {
// IsTailscaleConnected returns true if Tailscale is connected
func IsTailscaleConnected() bool {
- status := GetTailscaleStatus()
- return status.Installed && status.Running && status.BackendState == "Running"
+ return GetTailscaleStatus().Connected
}
diff --git a/internal/scanner/scanner.go b/internal/scanner/scanner.go
index d5b374b..d501ef4 100644
--- a/internal/scanner/scanner.go
+++ b/internal/scanner/scanner.go
@@ -11,6 +11,7 @@ import (
"strings"
"time"
+ "github.com/291-Group/LAN-Orangutan/internal/network"
"github.com/291-Group/LAN-Orangutan/internal/types"
)
@@ -34,10 +35,10 @@ type nmapRun struct {
// nmapHost represents a host element in nmap XML output
type nmapHost struct {
- Status nmapStatus `xml:"status"`
- Addresses []nmapAddress `xml:"address"`
- Hostnames nmapHostnames `xml:"hostnames"`
- Times nmapTimes `xml:"times"`
+ Status nmapStatus `xml:"status"`
+ Addresses []nmapAddress `xml:"address"`
+ Hostnames nmapHostnames `xml:"hostnames"`
+ Times nmapTimes `xml:"times"`
}
// nmapStatus represents the host status
@@ -78,6 +79,13 @@ func (s *Scanner) Scan(ctx context.Context, cidr string) (*types.ScanResult, err
startTime := time.Now()
+ // Tailscale gives every node its own /32, so there is no subnet to sweep
+ // and a scan could only ever find this machine. Tailscale already knows the
+ // whole tailnet, so ask it for the peers instead.
+ if network.IsTailscaleNetwork(cidr) {
+ return s.scanTailscale(cidr, startTime), nil
+ }
+
// Try nmap first
devices, scanner, err := s.scanWithNmap(ctx, cidr)
if err != nil {
@@ -106,6 +114,29 @@ func (s *Scanner) Scan(ctx context.Context, cidr string) (*types.ScanResult, err
}, nil
}
+// scanTailscale lists the devices reachable over Tailscale.
+func (s *Scanner) scanTailscale(cidr string, startTime time.Time) *types.ScanResult {
+ devices := network.GetTailscaleDevices()
+ if devices == nil {
+ return &types.ScanResult{
+ Success: false,
+ Error: "Tailscale is not connected",
+ Network: cidr,
+ Timestamp: time.Now(),
+ }
+ }
+
+ return &types.ScanResult{
+ Success: true,
+ Devices: devices,
+ DeviceCount: len(devices),
+ Network: cidr,
+ Scanner: "tailscale",
+ Duration: time.Since(startTime).Seconds(),
+ Timestamp: time.Now(),
+ }
+}
+
// scanWithNmap performs a scan using nmap
func (s *Scanner) scanWithNmap(ctx context.Context, cidr string) ([]types.Device, string, error) {
// Check if nmap is available
diff --git a/internal/storage/storage.go b/internal/storage/storage.go
index 35a1b50..2262eda 100644
--- a/internal/storage/storage.go
+++ b/internal/storage/storage.go
@@ -28,7 +28,8 @@ func New(devicesFile, stateFile string) (*Storage, error) {
stateFile: stateFile,
devices: make(map[string]*types.Device),
state: &types.ScanState{
- LastScan: make(map[string]time.Time),
+ LastScan: make(map[string]time.Time),
+ LastDuration: make(map[string]float64),
},
}
@@ -73,7 +74,19 @@ func (s *Storage) loadState() error {
return nil
}
- return json.Unmarshal(data, &s.state)
+ if err := json.Unmarshal(data, &s.state); err != nil {
+ return err
+ }
+
+ // State files written before durations were tracked have no such map, so
+ // recreate it rather than leave a nil map that cannot be written to.
+ if s.state.LastScan == nil {
+ s.state.LastScan = make(map[string]time.Time)
+ }
+ if s.state.LastDuration == nil {
+ s.state.LastDuration = make(map[string]float64)
+ }
+ return nil
}
// saveDevices writes devices to the JSON file atomically
@@ -255,6 +268,26 @@ func (s *Storage) SetLastScan(network string, t time.Time) error {
return s.saveState()
}
+// GetLastDuration returns how long the previous scan of a network took, in
+// seconds. It returns 0 when the network has not been scanned before.
+func (s *Storage) GetLastDuration(network string) float64 {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+ return s.state.LastDuration[network]
+}
+
+// SetLastDuration records how long a scan of a network took, in seconds.
+func (s *Storage) SetLastDuration(network string, seconds float64) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ if s.state.LastDuration == nil {
+ s.state.LastDuration = make(map[string]float64)
+ }
+ s.state.LastDuration[network] = seconds
+ return s.saveState()
+}
+
// GetStats returns device statistics
func (s *Storage) GetStats() types.DeviceStats {
s.mu.RLock()
diff --git a/internal/types/types.go b/internal/types/types.go
index e451369..e327ec2 100644
--- a/internal/types/types.go
+++ b/internal/types/types.go
@@ -40,6 +40,9 @@ type Network struct {
// ScanState holds the last scan time for rate limiting
type ScanState struct {
LastScan map[string]time.Time `json:"last_scan"`
+ // LastDuration records how long the previous scan of each network took,
+ // in seconds, so the UI can estimate progress for subsequent scans.
+ LastDuration map[string]float64 `json:"last_duration,omitempty"`
}
// ScanResult represents the outcome of a network scan
@@ -56,8 +59,13 @@ type ScanResult struct {
// TailscaleStatus represents Tailscale connection status
type TailscaleStatus struct {
- Installed bool `json:"installed"`
- Running bool `json:"running"`
+ Installed bool `json:"installed"`
+ // Running reports only that the Tailscale daemon answered. It stays true
+ // when the user is logged out or has stopped Tailscale, so it must not be
+ // used to decide whether traffic can flow: use Connected for that.
+ Running bool `json:"running"`
+ // Connected reports whether Tailscale is actually up and usable.
+ Connected bool `json:"connected"`
BackendState string `json:"backend_state"`
Version string `json:"version"`
TailnetName string `json:"tailnet_name"`
@@ -67,6 +75,33 @@ type TailscaleStatus struct {
ExitNode string `json:"exit_node,omitempty"`
}
+// StatusLabel describes the Tailscale connection in words suitable for display.
+func (t TailscaleStatus) StatusLabel() string {
+ if !t.Installed {
+ return "Not installed"
+ }
+ if !t.Running {
+ return "Not running"
+ }
+
+ switch t.BackendState {
+ case "Running":
+ return "Connected"
+ case "Stopped":
+ return "Stopped"
+ case "NeedsLogin":
+ return "Logged out"
+ case "NeedsMachineAuth":
+ return "Awaiting approval"
+ case "Starting":
+ return "Starting"
+ case "NoState", "":
+ return "Unknown"
+ default:
+ return t.BackendState
+ }
+}
+
// APIResponse is the standard API response wrapper
type APIResponse struct {
Success bool `json:"success"`
diff --git a/internal/web/static/app.js b/internal/web/static/app.js
index fd559b9..fb87aef 100644
--- a/internal/web/static/app.js
+++ b/internal/web/static/app.js
@@ -60,44 +60,112 @@ async function api(action, params = {}, method = 'GET') {
}
// Network scanning
-async function scanNetwork(cidr) {
- const progress = document.getElementById('scan-progress');
- if (progress) progress.style.display = 'flex';
+//
+// Scans run in the background on the server and the page polls for progress.
+// A large network takes minutes, which is far too long to hold a request open.
+const SCAN_POLL_MS = 1000;
+
+function formatSeconds(total) {
+ const s = Math.max(0, Math.round(total));
+ return s < 60 ? `${s}s` : `${Math.floor(s / 60)}m ${String(s % 60).padStart(2, '0')}s`;
+}
+
+function showScanProgress(p) {
+ const panel = document.getElementById('scan-progress');
+ if (!panel) return;
+ panel.style.display = 'flex';
+
+ const title = document.getElementById('scan-title');
+ if (title) title.textContent = p.current_network ? `Scanning ${p.current_network}` : 'Starting scan...';
+
+ // percent is -1 when the network has never been scanned and there is no
+ // timing history to estimate from. Show a sweeping bar rather than a
+ // made-up number.
+ const bar = document.getElementById('scan-bar');
+ const fill = document.getElementById('scan-bar-fill');
+ const known = p.percent >= 0;
+ if (bar) bar.classList.toggle('indeterminate', !known);
+ if (fill) fill.style.width = known ? `${Math.min(100, p.percent)}%` : '';
+
+ const detail = document.getElementById('scan-detail');
+ if (detail) {
+ const parts = [];
+ if (p.network_count > 1) parts.push(`Network ${p.network_index} of ${p.network_count}`);
+ parts.push(`${p.device_count} device${p.device_count === 1 ? '' : 's'} found`);
+ detail.textContent = parts.join(' · ');
+ }
+
+ const eta = document.getElementById('scan-eta');
+ if (eta) {
+ eta.textContent = known && p.remaining != null
+ ? `~${formatSeconds(p.remaining)} left · ${Math.round(p.percent)}%`
+ : `${formatSeconds(p.elapsed)} elapsed`;
+ }
+}
+
+function hideScanProgress() {
+ const panel = document.getElementById('scan-progress');
+ if (panel) panel.style.display = 'none';
+}
+
+async function cancelScan() {
try {
- const result = await api('scan', { network: cidr });
- if (result.success) {
- showToast(`Found ${result.data?.device_count || 0} devices`, 'success');
- setTimeout(() => location.reload(), 1000);
- } else {
- showToast(result.error || 'Scan failed', 'error');
- }
+ await api('scan/cancel', {}, 'POST');
+ showToast('Scan cancelled', 'warning');
} catch (e) {
- const isRateLimit = e.message.toLowerCase().includes('rate limit');
- showToast(isRateLimit ? e.message : 'Scan failed: ' + e.message, isRateLimit ? 'warning' : 'error');
- } finally {
- if (progress) progress.style.display = 'none';
+ showToast('Could not cancel: ' + e.message, 'error');
}
}
-async function scanAllNetworks() {
- const progress = document.getElementById('scan-progress');
- if (progress) progress.style.display = 'flex';
+// Reports the outcome of a finished job. Networks that were rate limited or
+// failed are surfaced rather than being hidden behind a success message.
+function reportScanOutcome(p) {
+ const scanned = (p.networks || []).filter(n => n.status === 'scanned');
+ if (p.status === 'cancelled') {
+ showToast('Scan cancelled', 'warning');
+ if (scanned.length) setTimeout(() => location.reload(), 1000);
+ return;
+ }
+ if (scanned.length === 0) {
+ const reason = (p.networks || []).find(n => n.error)?.error;
+ showToast(reason ? 'Scan failed: ' + reason : 'No networks could be scanned', 'warning');
+ return;
+ }
+ const where = p.network_count > 1 ? ` across ${scanned.length} network${scanned.length === 1 ? '' : 's'}` : '';
+ showToast(`Found ${p.device_count} device${p.device_count === 1 ? '' : 's'}${where}`, 'success');
+ setTimeout(() => location.reload(), 1000);
+}
+
+async function runScan(target) {
try {
- const result = await api('scan', { network: 'all' });
- if (result.success) {
- showToast('Scan complete', 'success');
- setTimeout(() => location.reload(), 1000);
- } else {
- showToast(result.error || 'Scan failed', 'error');
+ const started = await api(`scan/start?network=${encodeURIComponent(target)}`, {}, 'POST');
+ showScanProgress(started.data);
+
+ while (true) {
+ await new Promise(r => setTimeout(r, SCAN_POLL_MS));
+ const progress = (await api('scan/progress')).data;
+ if (progress.status !== 'running') {
+ hideScanProgress();
+ reportScanOutcome(progress);
+ return;
+ }
+ showScanProgress(progress);
}
} catch (e) {
+ hideScanProgress();
const isRateLimit = e.message.toLowerCase().includes('rate limit');
showToast(isRateLimit ? e.message : 'Scan failed: ' + e.message, isRateLimit ? 'warning' : 'error');
- } finally {
- if (progress) progress.style.display = 'none';
}
}
+async function scanNetwork(cidr) {
+ await runScan(cidr);
+}
+
+async function scanAllNetworks() {
+ await runScan('all');
+}
+
// Device filtering
function filterDevices() {
const search = (document.getElementById('device-search')?.value || '').toLowerCase();
diff --git a/internal/web/static/style.css b/internal/web/static/style.css
index 5d4a4e8..b441297 100644
--- a/internal/web/static/style.css
+++ b/internal/web/static/style.css
@@ -761,10 +761,11 @@ a:hover { color: var(--accent-hover); }
border-radius: var(--radius-lg);
box-shadow: 0 10px 40px rgba(0,0,0,0.15);
display: flex;
- align-items: center;
- gap: 1rem;
+ flex-direction: column;
+ gap: 0.75rem;
z-index: 200;
border: 1px solid var(--border-color);
+ width: min(420px, calc(100vw - 2rem));
}
.scan-spinner {
@@ -780,6 +781,71 @@ a:hover { color: var(--accent-hover); }
to { transform: rotate(360deg); }
}
+.scan-progress-head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 1.5rem;
+}
+
+#scan-title {
+ font-weight: 600;
+}
+
+.scan-cancel {
+ background: transparent;
+ border: 1px solid var(--border-color);
+ color: var(--text-secondary);
+}
+
+.scan-cancel:hover {
+ border-color: var(--accent-primary);
+ color: var(--accent-primary);
+}
+
+.scan-bar {
+ position: relative;
+ height: 8px;
+ border-radius: 999px;
+ background: var(--border-color);
+ overflow: hidden;
+}
+
+.scan-bar-fill {
+ height: 100%;
+ width: 0;
+ border-radius: 999px;
+ background: var(--accent-primary);
+ transition: width 0.4s ease;
+}
+
+/* A network that has never been scanned has no timing history, so there is no
+ honest percentage to show. Sweep the bar instead of inventing a number. */
+.scan-bar.indeterminate .scan-bar-fill {
+ width: 35%;
+ transition: none;
+ animation: scan-sweep 1.4s ease-in-out infinite;
+}
+
+@keyframes scan-sweep {
+ 0% { transform: translateX(-100%); }
+ 100% { transform: translateX(340%); }
+}
+
+.scan-progress-meta {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 1.5rem;
+ font-size: 0.85rem;
+ color: var(--text-secondary);
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .scan-bar.indeterminate .scan-bar-fill { animation-duration: 3s; }
+ .scan-spinner { animation-duration: 2s; }
+}
+
/* Empty State */
.empty-state {
text-align: center;
diff --git a/internal/web/templates/index.html b/internal/web/templates/index.html
index cdd49ea..5f97559 100644
--- a/internal/web/templates/index.html
+++ b/internal/web/templates/index.html
@@ -51,8 +51,11 @@
<section class="section">
<h2 class="section-title">Networks</h2>
<div class="network-cards">
- {{range .Networks}}
- <div class="card network-card {{if .IsTailscale}}tailscale{{end}}">
+ {{/* Tailscale gets its own card below, and its interface is a
+ single-address /32 that there is no point sweeping, so it is
+ skipped here rather than shown twice. */}}
+ {{range .Networks}}{{if not .IsTailscale}}
+ <div class="card network-card">
<div class="card-header">
<span class="network-name">{{.FriendlyName}}</span>
<span class="status-badge online">Active</span>
@@ -75,15 +78,18 @@
<button class="btn btn-primary btn-sm" onclick="scanNetwork('{{.CIDR}}')">Scan Network</button>
</div>
</div>
- {{end}}
+ {{end}}{{end}}
{{if and .Tailscale.Installed .Tailscale.Running}}
<div class="card network-card tailscale">
<div class="card-header">
<span class="network-name">Tailscale VPN</span>
- <span class="status-badge online">Connected</span>
+ <span class="status-badge {{if .Tailscale.Connected}}online{{else}}offline{{end}}">{{.Tailscale.StatusLabel}}</span>
</div>
<div class="card-body">
+ {{/* The IP and peer list linger from the last session after
+ Tailscale is stopped, so only show them while connected. */}}
+ {{if .Tailscale.Connected}}
{{if .Tailscale.SelfIP}}
<div class="network-detail">
<span class="label">Your IP</span>
@@ -94,6 +100,11 @@
<span class="label">Peers</span>
<span class="value">{{.Tailscale.PeerCount}} devices</span>
</div>
+ {{else}}
+ <div class="network-detail">
+ <span class="label">Not connected</span>
+ </div>
+ {{end}}
</div>
</div>
{{end}}
@@ -257,8 +268,17 @@
<div id="toast" class="toast"></div>
<div id="scan-progress" class="scan-progress" style="display:none">
- <div class="scan-spinner"></div>
- <span>Scanning network...</span>
+ <div class="scan-progress-head">
+ <span id="scan-title">Scanning network...</span>
+ <button type="button" class="btn btn-sm scan-cancel" id="scan-cancel" onclick="cancelScan()">Cancel</button>
+ </div>
+ <div class="scan-bar" id="scan-bar">
+ <div class="scan-bar-fill" id="scan-bar-fill"></div>
+ </div>
+ <div class="scan-progress-meta">
+ <span id="scan-detail"></span>
+ <span id="scan-eta"></span>
+ </div>
</div>
<footer class="footer">
diff --git a/internal/web/templates/settings.html b/internal/web/templates/settings.html
index 2701f39..48fc72c 100644
--- a/internal/web/templates/settings.html
+++ b/internal/web/templates/settings.html
@@ -52,14 +52,17 @@
<div class="card">
<div class="status-row">
<span class="status-label">Status:</span>
- {{if .Tailscale.Running}}
- <span class="status-value online">✓ Connected</span>
+ {{if .Tailscale.Connected}}
+ <span class="status-value online">✓ {{.Tailscale.StatusLabel}}</span>
{{else if .Tailscale.Installed}}
- <span class="status-value offline">✗ Disconnected</span>
+ <span class="status-value offline">✗ {{.Tailscale.StatusLabel}}</span>
{{else}}
<span class="status-value warning">Not Installed</span>
{{end}}
</div>
+ {{/* These details are cached from the last session and go stale
+ once Tailscale stops, so only show them while connected. */}}
+ {{if .Tailscale.Connected}}
{{if .Tailscale.SelfIP}}
<div class="status-row">
<span class="status-label">IP:</span>
@@ -72,7 +75,6 @@
<span class="status-value">{{.Tailscale.SelfHostname}}</span>
</div>
{{end}}
- {{if .Tailscale.Running}}
<div class="status-row">
<span class="status-label">Peers:</span>
<span class="status-value">{{.Tailscale.PeerCount}}</span>