package provider import ( "archive/zip" "context" "errors" "fmt" "io" "os" "path/filepath" "runtime" "strings" "time" "git.starwarslab.us/ATOM_IT/Deployr/internal/catalog" "git.starwarslab.us/ATOM_IT/Deployr/internal/detect" "git.starwarslab.us/ATOM_IT/Deployr/internal/download" "git.starwarslab.us/ATOM_IT/Deployr/internal/platform" "git.starwarslab.us/ATOM_IT/Deployr/internal/run" ) // direct installs straight from a vendor download. It is the fallback for // software the native package managers handle badly or not at all, and the only // route on a machine with no package manager configured. type direct struct{} func (d *direct) Name() string { return "direct" } func (d *direct) OSes() []string { return []string{"windows", "darwin", "linux"} } func (d *direct) Label() string { return "Direct vendor download" } // Available is always true: there is no local tool to probe. A missing network // surfaces as a download error, which is more useful than silently skipping. func (d *direct) Available(context.Context, Opts) bool { return true } func (d *direct) Install(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) { url := src.URLFor(o.Arch) if url == "" { return Outcome{}, fmt.Errorf("no download URL for %s/%s", runtime.GOOS, o.Arch) } kind := strings.ToLower(src.Kind) if kind == "" { kind = InferKind(url) } if kind == "" { return Outcome{}, fmt.Errorf("cannot tell the installer type of %s; set `kind` in the catalog", url) } if o.DryRun { if o.Log != nil { o.Log.Debugf("would download %s (%s) and install it", url, kind) } return Outcome{Message: "dry run"}, nil } path, err := download.Fetch(ctx, download.Options{ URL: url, SHA256: src.SHA256, Dir: o.CacheDir, Timeout: o.Timeout, RequireChecksum: o.RequireChecksum, Log: o.Log, }) if err != nil { return Outcome{}, err } if !o.KeepDownloads { defer os.Remove(path) } switch runtime.GOOS { case "windows": return d.installWindows(ctx, path, kind, src, o) case "darwin": return d.installDarwin(ctx, path, kind, src, o) case "linux": return d.installLinux(ctx, path, kind, src, o) default: return Outcome{}, fmt.Errorf("direct installs are not supported on %s", runtime.GOOS) } } // Update reinstalls from the catalog URL. Vendor "latest" links are evergreen, // so a reinstall is how you patch anything that has no package manager behind // it. Installers of this kind are in-place upgrades, not duplicates. func (d *direct) Update(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) { return d.Install(ctx, src, o) } // Query cannot report a version: the download tells us nothing about what is on // disk. Presence and version come from the catalog's detect rules instead. func (d *direct) Query(context.Context, catalog.Source, Opts) (string, bool) { return "", false } // -------------------------------------------------------------- windows --- func (d *direct) installWindows(ctx context.Context, path, kind string, src catalog.Source, o Opts) (Outcome, error) { var res run.Result switch kind { case "msi": args := append([]string{"/i", path, "/qn", "/norestart"}, src.SilentArgs...) res = run.Exec(ctx, run.Options{Name: "msiexec", Args: args, Timeout: o.Timeout, Log: o.Log}) case "msu": res = run.Exec(ctx, run.Options{Name: "wusa", Args: []string{path, "/quiet", "/norestart"}, Timeout: o.Timeout, Log: o.Log}) case "exe": if len(src.SilentArgs) == 0 { // Running a bare vendor .exe would pop a wizard on someone's // screen and then hang until the timeout. Refuse instead. return Outcome{}, errors.New("exe installer needs silent_args in the catalog") } res = run.Exec(ctx, run.Options{Name: path, Args: src.SilentArgs, Timeout: o.Timeout, Log: o.Log}) case "zip": dest := platform.ExpandPath(src.Dest) if dest == "" { return Outcome{}, errors.New("zip payload needs a dest in the catalog") } if err := extractZip(path, dest); err != nil { return Outcome{}, err } return Outcome{}, nil default: return Outcome{}, fmt.Errorf("unsupported installer kind %q on windows", kind) } switch { case !res.Failed(): return Outcome{}, nil case isRebootExit(res.ExitCode): return Outcome{RebootRequired: true}, nil case res.ExitCode == 1618: return Outcome{}, errors.New("another Windows installation is already in progress") default: return Outcome{}, fmt.Errorf("installer failed: %s", res.Error()) } } // --------------------------------------------------------------- darwin --- func (d *direct) installDarwin(ctx context.Context, path, kind string, src catalog.Source, o Opts) (Outcome, error) { switch kind { case "pkg": res := run.Exec(ctx, run.Options{ Name: "/usr/sbin/installer", Args: []string{"-pkg", path, "-target", "/"}, NeedRoot: true, Timeout: o.Timeout, Log: o.Log, }) if res.Failed() { return Outcome{}, fmt.Errorf("installer -pkg: %s", res.Error()) } return Outcome{}, nil case "dmg": return d.installDMG(ctx, path, src, o) case "zip": dest := platform.ExpandPath(src.Dest) if dest == "" { dest = "/Applications" } // ditto preserves resource forks and code signatures; unzip does not. res := run.Exec(ctx, run.Options{ Name: "/usr/bin/ditto", Args: []string{"-x", "-k", path, dest}, NeedRoot: true, Timeout: o.Timeout, Log: o.Log, }) if res.Failed() { return Outcome{}, fmt.Errorf("ditto: %s", res.Error()) } return Outcome{}, nil case "tar.gz", "tgz": return untar(ctx, path, src, o, "/usr/local") default: return Outcome{}, fmt.Errorf("unsupported installer kind %q on macOS", kind) } } // installDMG mounts a disk image, installs whatever is inside it, and always // detaches -- a leaked mount blocks the next run. func (d *direct) installDMG(ctx context.Context, path string, src catalog.Source, o Opts) (Outcome, error) { mount, err := os.MkdirTemp("", "deployr-dmg-") if err != nil { return Outcome{}, err } defer os.RemoveAll(mount) attach := run.Exec(ctx, run.Options{ Name: "/usr/bin/hdiutil", Args: []string{"attach", path, "-nobrowse", "-noverify", "-quiet", "-mountpoint", mount}, Timeout: o.Timeout, Log: o.Log, }) if attach.Failed() { return Outcome{}, fmt.Errorf("hdiutil attach: %s", attach.Error()) } defer func() { detachCtx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) defer cancel() run.Exec(detachCtx, run.Options{ Name: "/usr/bin/hdiutil", Args: []string{"detach", mount, "-quiet", "-force"}, Log: o.Log, }) }() entries, err := os.ReadDir(mount) if err != nil { return Outcome{}, fmt.Errorf("read mounted image: %w", err) } // A .pkg inside the image is the vendor's own installer: prefer it. for _, e := range entries { if strings.HasSuffix(strings.ToLower(e.Name()), ".pkg") { res := run.Exec(ctx, run.Options{ Name: "/usr/sbin/installer", Args: []string{"-pkg", filepath.Join(mount, e.Name()), "-target", "/"}, NeedRoot: true, Timeout: o.Timeout, Log: o.Log, }) if res.Failed() { return Outcome{}, fmt.Errorf("installer -pkg: %s", res.Error()) } return Outcome{}, nil } } appName := src.AppName if appName == "" { for _, e := range entries { if strings.HasSuffix(e.Name(), ".app") { appName = e.Name() break } } } if appName == "" { return Outcome{}, errors.New("no .app or .pkg found in the disk image; set app_name in the catalog") } source := filepath.Join(mount, appName) if _, err := os.Stat(source); err != nil { return Outcome{}, fmt.Errorf("%s not found in the disk image", appName) } target := filepath.Join("/Applications", appName) // ditto onto an existing bundle merges directories and leaves stale files // behind, so replace it outright. if _, err := os.Stat(target); err == nil { rm := run.Exec(ctx, run.Options{Name: "/bin/rm", Args: []string{"-rf", target}, NeedRoot: true, Timeout: o.Timeout, Log: o.Log}) if rm.Failed() { return Outcome{}, fmt.Errorf("replace %s: %s", target, rm.Error()) } } res := run.Exec(ctx, run.Options{ Name: "/usr/bin/ditto", Args: []string{source, target}, NeedRoot: true, Timeout: o.Timeout, Log: o.Log, }) if res.Failed() { return Outcome{}, fmt.Errorf("copy %s: %s", appName, res.Error()) } return Outcome{}, nil } // ---------------------------------------------------------------- linux --- func (d *direct) installLinux(ctx context.Context, path, kind string, src catalog.Source, o Opts) (Outcome, error) { switch kind { case "deb": // apt-get resolves the dependencies dpkg -i would leave broken. res := run.Exec(ctx, run.Options{ Name: "apt-get", Args: append(append([]string{"install", "-y"}, aptConfArgs...), path), Env: aptEnv, NeedRoot: true, Timeout: o.Timeout, Log: o.Log, }) if res.Failed() { return Outcome{}, fmt.Errorf("apt-get install %s: %s", filepath.Base(path), res.Error()) } return Outcome{}, nil case "rpm": for _, mgr := range []struct { bin string args []string }{ {"dnf", []string{"install", "-y", path}}, {"zypper", []string{"--non-interactive", "install", "--allow-unsigned-rpm", path}}, {"yum", []string{"install", "-y", path}}, {"rpm", []string{"-Uvh", path}}, } { if !run.Available(mgr.bin) { continue } res := run.Exec(ctx, run.Options{Name: mgr.bin, Args: mgr.args, NeedRoot: true, Timeout: o.Timeout, Log: o.Log}) if res.Failed() { return Outcome{}, fmt.Errorf("%s install: %s", mgr.bin, res.Error()) } return Outcome{}, nil } return Outcome{}, errors.New("no RPM-capable package manager found") case "sh", "run": if err := os.Chmod(path, 0o755); err != nil { return Outcome{}, err } res := run.Exec(ctx, run.Options{ Name: "/bin/sh", Args: append([]string{path}, src.SilentArgs...), NeedRoot: true, Timeout: o.Timeout, Log: o.Log, }) if res.Failed() { return Outcome{}, fmt.Errorf("install script: %s", res.Error()) } return Outcome{}, nil case "appimage": dest := platform.ExpandPath(src.Dest) if dest == "" { dest = filepath.Join("/usr/local/bin", strings.TrimSuffix(src.ID, ".AppImage")) } if err := copyFile(path, dest, 0o755); err != nil { return Outcome{}, err } return Outcome{}, nil case "zip": dest := platform.ExpandPath(src.Dest) if dest == "" { return Outcome{}, errors.New("zip payload needs a dest in the catalog") } if err := extractZip(path, dest); err != nil { return Outcome{}, err } return Outcome{}, nil case "tar.gz", "tgz": return untar(ctx, path, src, o, "/usr/local") default: return Outcome{}, fmt.Errorf("unsupported installer kind %q on linux", kind) } } func untar(ctx context.Context, path string, src catalog.Source, o Opts, fallbackDest string) (Outcome, error) { dest := platform.ExpandPath(src.Dest) if dest == "" { dest = fallbackDest } if err := os.MkdirAll(dest, 0o755); err != nil { return Outcome{}, err } res := run.Exec(ctx, run.Options{ Name: "tar", Args: []string{"-xzf", path, "-C", dest}, NeedRoot: true, Timeout: o.Timeout, Log: o.Log, }) if res.Failed() { return Outcome{}, fmt.Errorf("tar: %s", res.Error()) } return Outcome{}, nil } // ------------------------------------------------------------ uninstall --- func (d *direct) Uninstall(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) { if o.DryRun { return Outcome{Message: "dry run"}, nil } switch runtime.GOOS { case "windows": return d.uninstallWindows(ctx, src, o) case "darwin": name := src.AppName if name == "" { return Outcome{}, errors.New("no app_name in the catalog; remove this app manually") } target := filepath.Join("/Applications", name) if _, err := os.Stat(target); err != nil { return Outcome{NoOp: true, Message: "not installed"}, nil } res := run.Exec(ctx, run.Options{Name: "/bin/rm", Args: []string{"-rf", target}, NeedRoot: true, Timeout: o.Timeout, Log: o.Log}) if res.Failed() { return Outcome{}, fmt.Errorf("remove %s: %s", target, res.Error()) } return Outcome{}, nil default: pkg := src.UninstallID if pkg == "" { return Outcome{}, errors.New("no uninstall_id in the catalog; remove this app manually") } for _, mgr := range [][]string{ {"apt-get", "remove", "-y", pkg}, {"dnf", "remove", "-y", pkg}, {"zypper", "--non-interactive", "remove", pkg}, } { if !run.Available(mgr[0]) { continue } res := run.Exec(ctx, run.Options{Name: mgr[0], Args: mgr[1:], Env: aptEnv, NeedRoot: true, Timeout: o.Timeout, Log: o.Log}) if res.Failed() { return Outcome{}, fmt.Errorf("%s: %s", mgr[0], res.Error()) } return Outcome{}, nil } return Outcome{}, errors.New("no package manager available to remove this app") } } // uninstallWindows finds the app's uninstall registry entry -- which exists no // matter how it was installed -- and runs it silently. func (d *direct) uninstallWindows(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) { patterns := o.Detect.Registry if src.UninstallID != "" { patterns = append([]string{src.UninstallID}, patterns...) } entry, ok := detect.FindRegistry(patterns) if !ok { return Outcome{NoOp: true, Message: "no uninstall entry found"}, nil } if guid, isMSI := msiProductCode(entry.UninstallString); isMSI { res := run.Exec(ctx, run.Options{ Name: "msiexec", Args: []string{"/x", guid, "/qn", "/norestart"}, Timeout: o.Timeout, Log: o.Log, }) if res.Failed() && !isRebootExit(res.ExitCode) { return Outcome{}, fmt.Errorf("msiexec /x: %s", res.Error()) } return Outcome{RebootRequired: isRebootExit(res.ExitCode)}, nil } cmdline := entry.QuietUninstallString if cmdline == "" { // Without a quiet string the vendor uninstaller would open a window on // the user's desktop and wait. That is worse than reporting failure. return Outcome{}, fmt.Errorf("%s has no silent uninstall command; remove it manually", entry.DisplayName) } name, args := splitCommandLine(cmdline) if name == "" { return Outcome{}, fmt.Errorf("cannot parse uninstall command %q", cmdline) } res := run.Exec(ctx, run.Options{Name: name, Args: args, Timeout: o.Timeout, Log: o.Log}) if res.Failed() && !isRebootExit(res.ExitCode) { return Outcome{}, fmt.Errorf("uninstall %s: %s", entry.DisplayName, res.Error()) } return Outcome{RebootRequired: isRebootExit(res.ExitCode)}, nil } // msiProductCode extracts the {GUID} from an MSI uninstall string such as // `MsiExec.exe /I{90160000-008C-0000-1000-0000000FF1CE}`. func msiProductCode(uninstall string) (string, bool) { if !strings.Contains(strings.ToLower(uninstall), "msiexec") { return "", false } start := strings.Index(uninstall, "{") end := strings.Index(uninstall, "}") if start < 0 || end < start { return "", false } return uninstall[start : end+1], true } // splitCommandLine splits a Windows command line into program and arguments, // honouring double quotes around paths with spaces. func splitCommandLine(s string) (string, []string) { var parts []string var cur strings.Builder inQuote := false for _, r := range s { switch { case r == '"': inQuote = !inQuote case (r == ' ' || r == '\t') && !inQuote: if cur.Len() > 0 { parts = append(parts, cur.String()) cur.Reset() } default: cur.WriteRune(r) } } if cur.Len() > 0 { parts = append(parts, cur.String()) } if len(parts) == 0 { return "", nil } return parts[0], parts[1:] } // ----------------------------------------------------------------- misc --- // InferKind guesses the installer format from the URL file extension. It is // exported so a catalog test can check that every direct source resolves to a // kind deployr knows how to install. func InferKind(rawURL string) string { lower := strings.ToLower(rawURL) if i := strings.IndexAny(lower, "?#"); i >= 0 { lower = lower[:i] } for _, ext := range []string{".tar.gz", ".tgz", ".msi", ".msu", ".exe", ".dmg", ".pkg", ".deb", ".rpm", ".zip", ".appimage", ".inf"} { if strings.HasSuffix(lower, ext) { switch ext { case ".tgz": return "tar.gz" case ".appimage": return "appimage" default: return strings.TrimPrefix(ext, ".") } } } return "" } func copyFile(src, dest string, mode os.FileMode) error { if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil { return err } in, err := os.Open(src) if err != nil { return err } defer in.Close() out, err := os.OpenFile(dest, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, mode) if err != nil { return err } if _, err := io.Copy(out, in); err != nil { out.Close() return err } return out.Close() } // extractZip unpacks an archive, rejecting entries that would escape the // destination directory (zip slip). func extractZip(archive, dest string) error { r, err := zip.OpenReader(archive) if err != nil { return fmt.Errorf("open %s: %w", archive, err) } defer r.Close() if err := os.MkdirAll(dest, 0o755); err != nil { return err } root, err := filepath.Abs(dest) if err != nil { return err } for _, f := range r.File { target := filepath.Join(root, filepath.FromSlash(f.Name)) if !strings.HasPrefix(target, root+string(os.PathSeparator)) && target != root { return fmt.Errorf("refusing to extract %q outside %s", f.Name, dest) } if f.FileInfo().IsDir() { if err := os.MkdirAll(target, 0o755); err != nil { return err } continue } if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil { return err } rc, err := f.Open() if err != nil { return err } out, err := os.OpenFile(target, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, f.Mode()|0o200) if err != nil { rc.Close() return err } _, copyErr := io.Copy(out, rc) rc.Close() closeErr := out.Close() if copyErr != nil { return copyErr } if closeErr != nil { return closeErr } } return nil }