Files
ClaudeandClaude Opus 5 7ee270e128 Add printer and scanner driver support
A new "driver" provider installs Windows printer and scanner drivers through
the same catalog, UI and profiles as everything else: stage the package into the
driver store with pnputil, then register it with the print spooler so it turns
up in Add Printer.

Driver names are matched by PREFIX against the names read out of the package's
own INF files. Vendors stamp the version into the name -- "HP Universal Printing
PCL 6 (v7.1.0)" -- so an exact name in a catalog goes stale at the next release,
and a wrong one is unrecoverable without knowing what the package contains. When
a prefix matches nothing, the error lists the names the package actually
provides, which turns a dead end into a one-line fix.

INF parsing handles what real files are, not what the spec suggests: Windows
ships its own printer INFs as UTF-16LE and vendor packages follow suit, so
reading them as UTF-8 finds nothing at all. Verified against every prn*.inf on
a stock Windows install -- that test is what caught the encoding bug, since the
hand-written sample parsed fine.

Scanners are TWAIN/WIA rather than spooler drivers, so there is nothing to
register: leaving driver_match unset means stage-only. Detection falls back to
the uninstall entry, because a TWAIN data source has no spooler record.

Packages come from a driver share rather than the web. Vendor URLs are
version-pinned and several are EULA-gated, so nothing stable can be shipped in a
catalog; a UNC path or local folder is used in place with no download at all,
which is faster and is what a shop wants anyway. $DEPLOYR_DRIVERS names the
share, and an unset variable is reported by name rather than surfacing three
layers down as "no such file".

Ships universal drivers for HP, Xerox, Ricoh, Sharp, Canon, Kyocera, Konica
Minolta, Lexmark, Brother, Toshiba, Epson, Muratec and Zebra, plus scanner
packages for the fi series, ScanSnap, Canon DR, Epson, Brother, Visioneer and
Kodak Alaris. Profiles: @printers, @printers-all, @scanners.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 17:47:24 -05:00

366 lines
12 KiB
Go

package provider
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"runtime"
"strings"
"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"
)
// printerDriver installs Windows printer drivers: stage the package into the
// driver store with pnputil, then register the models it declares with the
// print spooler so they appear in Add Printer.
//
// Vendor driver downloads are version-pinned and several sit behind a click-
// through EULA, so a package here is usually a file on the shop's own driver
// share rather than a URL. Both are supported; a UNC path or local directory is
// used in place with no download at all.
type printerDriver struct{}
func (p *printerDriver) Name() string { return "driver" }
func (p *printerDriver) OSes() []string { return []string{"windows"} }
func (p *printerDriver) Label() string { return "Windows printer driver (pnputil)" }
func (p *printerDriver) Available(context.Context, Opts) bool {
return runtime.GOOS == "windows"
}
func (p *printerDriver) Install(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
if runtime.GOOS != "windows" {
return Outcome{}, errors.New("printer drivers are only supported on Windows")
}
raw := src.URLFor(o.Arch)
if raw == "" {
return Outcome{}, fmt.Errorf("no driver package for %s", o.Arch)
}
// Catalog entries point at a driver share through an environment variable.
// Unset, it expands to nothing and the failure surfaces as a baffling "no
// such file" -- so say which variable is missing instead.
if missing := platform.MissingVars(raw); len(missing) > 0 {
return Outcome{}, fmt.Errorf("%s is not set; point it at your driver share "+
`(setx /m %s \\fileserver\drivers)`, strings.Join(missing, ", "), missing[0])
}
source := platform.ExpandVars(raw)
if o.DryRun {
if o.Log != nil {
o.Log.Debugf("would stage %s and register drivers matching %q", source, src.DriverMatch)
}
return Outcome{Message: "dry run"}, nil
}
dir, cleanup, err := p.stage(ctx, source, src, o)
if cleanup != nil {
defer cleanup()
}
if err != nil {
return Outcome{}, err
}
if dir == "" {
// A vendor installer handled everything itself; there is nothing to
// stage or register.
return Outcome{}, nil
}
infs, err := findINFs(dir)
if err != nil {
return Outcome{}, fmt.Errorf("scan %s: %w", dir, err)
}
if len(infs) == 0 {
return Outcome{}, fmt.Errorf("no .inf files found in %s", dir)
}
if o.Log != nil {
o.Log.Debugf("found %d INF file(s) under %s", len(infs), dir)
}
// Stage the whole package into the driver store in one pass. /subdirs is
// what makes a multi-architecture vendor package work.
res := run.Exec(ctx, run.Options{
Name: "pnputil",
Args: []string{"/add-driver", filepath.Join(dir, "*.inf"), "/subdirs", "/install"},
Timeout: o.Timeout,
Log: o.Log,
})
// pnputil returns 259 (ERROR_NO_MORE_ITEMS) when every INF was already in
// the store, which is success for our purposes.
if res.Failed() && res.ExitCode != 259 && !isRebootExit(res.ExitCode) {
return Outcome{}, fmt.Errorf("pnputil: %s", res.Error())
}
// No driver_match means this is a device driver rather than a printer --
// a scanner's TWAIN/WIA package, say. Staging it into the driver store is
// the entire job; there is no spooler to register it with.
if strings.TrimSpace(src.DriverMatch) == "" {
return Outcome{
RebootRequired: isRebootExit(res.ExitCode),
Message: fmt.Sprintf("staged %d INF file(s)", len(infs)),
}, nil
}
// Collect the driver names the package declares, then narrow to the ones
// the catalog asked for.
var models []infModel
for _, inf := range infs {
found, err := infDriverNames(inf)
if err != nil {
if o.Log != nil {
o.Log.Debugf("could not read %s: %v", inf, err)
}
continue
}
models = append(models, found...)
}
if len(models) == 0 {
return Outcome{}, fmt.Errorf("no printer models declared in the INF files under %s", dir)
}
wanted := matchDriverNames(models, src.DriverMatch)
if len(wanted) == 0 {
return Outcome{}, fmt.Errorf("no driver in this package matches %q; the package provides: %s",
src.DriverMatch, driverNameList(models, 12))
}
registered, rebootRequired, err := p.register(ctx, wanted, o)
if err != nil {
return Outcome{}, err
}
if len(registered) == 0 {
return Outcome{}, errors.New("no driver could be registered with the print spooler")
}
return Outcome{
Version: registered[0],
RebootRequired: rebootRequired,
Message: registeredMessage(registered),
}, nil
}
// register adds each matched model to the print spooler. Registering one model
// of a package is usually enough, so a failure on a later model is logged
// rather than treated as failing the whole install.
func (p *printerDriver) register(ctx context.Context, models []infModel, o Opts) ([]string, bool, error) {
var registered []string
var reboot bool
var firstErr error
for _, m := range models {
res := run.Exec(ctx, run.Options{
Name: "powershell",
Args: []string{"-NoProfile", "-NonInteractive", "-Command",
fmt.Sprintf("Add-PrinterDriver -Name '%s' -ErrorAction Stop", psQuote(m.Name))},
Timeout: o.Timeout,
Log: o.Log,
})
switch {
case !res.Failed():
registered = append(registered, m.Name)
case res.Contains("already exists") || res.Contains("0x80070705"):
registered = append(registered, m.Name)
case isRebootExit(res.ExitCode):
registered = append(registered, m.Name)
reboot = true
default:
if o.Log != nil {
o.Log.Debugf("Add-PrinterDriver %q failed: %s", m.Name, res.Error())
}
if firstErr == nil {
firstErr = fmt.Errorf("Add-PrinterDriver %q: %s", m.Name, res.Error())
}
}
}
if len(registered) == 0 && firstErr != nil {
return nil, false, firstErr
}
return registered, reboot, nil
}
func registeredMessage(names []string) string {
if len(names) == 1 {
return "registered " + names[0]
}
return fmt.Sprintf("registered %d drivers, first: %s", len(names), names[0])
}
// stage resolves the package to a directory of INF files. It returns an empty
// directory when a vendor installer did the work itself.
func (p *printerDriver) stage(ctx context.Context, source string, src catalog.Source, o Opts) (string, func(), error) {
noCleanup := func() {}
// A UNC path, a drive-letter path or a plain directory is used in place --
// no download, no copy. This is how a driver share is meant to be used.
if isLocalSource(source) {
path := platform.ExpandPath(localPath(source))
info, err := os.Stat(path)
if err != nil {
return "", noCleanup, fmt.Errorf("driver package %s: %w", path, err)
}
if info.IsDir() {
return path, noCleanup, nil
}
return p.unpack(ctx, path, src, o)
}
path, err := download.Fetch(ctx, download.Options{
URL: source,
SHA256: src.SHA256,
Dir: o.CacheDir,
Timeout: o.Timeout,
RequireChecksum: o.RequireChecksum,
Log: o.Log,
})
if err != nil {
return "", noCleanup, err
}
if !o.KeepDownloads {
defer os.Remove(path)
}
return p.unpack(ctx, path, src, o)
}
// unpack turns a package file into a directory of INF files.
func (p *printerDriver) unpack(ctx context.Context, path string, src catalog.Source, o Opts) (string, func(), error) {
kind := strings.ToLower(src.Kind)
if kind == "" {
kind = InferKind(path)
}
switch kind {
case "zip":
dir, err := os.MkdirTemp("", "deployr-driver-")
if err != nil {
return "", func() {}, err
}
cleanup := func() { os.RemoveAll(dir) }
if err := extractZip(path, dir); err != nil {
return "", cleanup, err
}
return dir, cleanup, nil
case "inf":
// The package is a bare INF: stage the directory that contains it, so
// its .cab and driver files come along.
return filepath.Dir(path), func() {}, nil
case "exe":
if len(src.SilentArgs) == 0 {
return "", func() {}, errors.New("exe driver package needs silent_args in the catalog " +
"(the vendor's extract or silent-install switches)")
}
dir := platform.ExpandPath(src.Dest)
args := make([]string, len(src.SilentArgs))
for i, a := range src.SilentArgs {
args[i] = platform.ExpandVars(a)
}
res := run.Exec(ctx, run.Options{Name: path, Args: args, Timeout: o.Timeout, Log: o.Log})
if res.Failed() && !isRebootExit(res.ExitCode) {
return "", func() {}, fmt.Errorf("driver package: %s", res.Error())
}
// With no dest the exe was a full installer, not an extractor.
return dir, func() {}, nil
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})
if res.Failed() && !isRebootExit(res.ExitCode) {
return "", func() {}, fmt.Errorf("msiexec: %s", res.Error())
}
return "", func() {}, nil
default:
return "", func() {}, fmt.Errorf("unsupported driver package kind %q (use zip, inf, exe or msi)", kind)
}
}
// Update reinstalls the package, which is how a printer driver is upgraded:
// stage the newer INF and re-register.
func (p *printerDriver) Update(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
return p.Install(ctx, src, o)
}
func (p *printerDriver) Uninstall(ctx context.Context, src catalog.Source, o Opts) (Outcome, error) {
if o.DryRun {
return Outcome{Message: "dry run"}, nil
}
prefixes := o.Detect.PrinterDrivers
if src.DriverMatch != "" {
prefixes = append([]string{src.DriverMatch}, prefixes...)
}
driver, ok := detect.FindPrinterDriver(prefixes)
if !ok {
return Outcome{NoOp: true, Message: "not installed"}, nil
}
res := run.Exec(ctx, run.Options{
Name: "powershell",
Args: []string{"-NoProfile", "-NonInteractive", "-Command",
fmt.Sprintf("Remove-PrinterDriver -Name '%s' -ErrorAction Stop", psQuote(driver.Name))},
Timeout: o.Timeout,
Log: o.Log,
})
if res.Failed() {
// The spooler refuses while a queue still uses the driver, which is a
// real answer rather than a malfunction.
if res.Contains("in use") {
return Outcome{}, fmt.Errorf("%s is still used by a printer; remove the printer first", driver.Name)
}
return Outcome{}, fmt.Errorf("Remove-PrinterDriver %q: %s", driver.Name, res.Error())
}
return Outcome{}, nil
}
// Query reports the installed driver's version from the spooler.
func (p *printerDriver) Query(_ context.Context, src catalog.Source, o Opts) (string, bool) {
prefixes := o.Detect.PrinterDrivers
if src.DriverMatch != "" {
prefixes = append([]string{src.DriverMatch}, prefixes...)
}
driver, ok := detect.FindPrinterDriver(prefixes)
if !ok {
return "", false
}
return driver.Name, true
}
// isLocalSource reports whether a catalog source points at the filesystem
// rather than the web: a UNC share, a drive-letter path, or a file:// URL.
func isLocalSource(s string) bool {
switch {
case strings.HasPrefix(s, `\\`):
return true
case strings.HasPrefix(strings.ToLower(s), "file://"):
return true
case len(s) > 2 && s[1] == ':' && (s[2] == '\\' || s[2] == '/'):
return true
case strings.HasPrefix(s, "./") || strings.HasPrefix(s, "/"):
return true
}
return false
}
// localPath strips a file:// scheme, including the leading slash that a
// file:///C:/... URL puts in front of the drive letter.
func localPath(s string) string {
if !strings.HasPrefix(strings.ToLower(s), "file://") {
return s
}
s = s[len("file://"):]
if len(s) > 2 && s[0] == '/' && s[2] == ':' {
s = s[1:]
}
return s
}
// psQuote escapes a value for a PowerShell single-quoted string.
func psQuote(s string) string { return strings.ReplaceAll(s, "'", "''") }