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>
This commit is contained in:
1 parent
7daceac077
commit
7ee270e128
14 files changed
+1738
-11
No files matched your search
@@ -487,7 +487,7 @@ func InferKind(rawURL string) string {
|
||||
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"} {
|
||||
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":
|
||||
|
||||
@@ -0,0 +1,365 @@
|
||||
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, "'", "''") }
|
||||
@@ -0,0 +1,271 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode/utf16"
|
||||
)
|
||||
|
||||
// Printer driver names are version-stamped and punctuation-heavy -- "HP
|
||||
// Universal Printing PCL 6 (v7.1.0)" -- so requiring an operator to type one
|
||||
// exactly, and to retype it at every driver release, is a trap. Instead we read
|
||||
// the model names out of the package's own INF files and match on a prefix.
|
||||
|
||||
// infModel is one printer model a driver package can install.
|
||||
type infModel struct {
|
||||
// Name is the driver name the spooler knows it by, e.g.
|
||||
// "HP Universal Printing PCL 6 (v7.1.0)".
|
||||
Name string
|
||||
// INF is the file the name came from.
|
||||
INF string
|
||||
}
|
||||
|
||||
// findINFs returns every .inf file under dir.
|
||||
func findINFs(dir string) ([]string, error) {
|
||||
var out []string
|
||||
err := filepath.WalkDir(dir, func(path string, entry os.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return nil // an unreadable subdirectory is not fatal
|
||||
}
|
||||
if !entry.IsDir() && strings.EqualFold(filepath.Ext(path), ".inf") {
|
||||
out = append(out, path)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
sort.Strings(out)
|
||||
return out, err
|
||||
}
|
||||
|
||||
// infDriverNames extracts the printer driver names an INF declares.
|
||||
//
|
||||
// The format is: [Manufacturer] names one or more model sections, and each of
|
||||
// those lists `"Driver Name" = InstallSection, HardwareID`. Names are often
|
||||
// %tokens% that resolve from [Strings].
|
||||
func infDriverNames(path string) ([]infModel, error) {
|
||||
sections, strs, err := parseINF(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// [Manufacturer] entries look like: %HP% = HP, NTamd64.10.0
|
||||
// The right-hand side names the model section, optionally with decorations
|
||||
// appended to it (HP.NTamd64.10.0), and every variant has to be checked.
|
||||
var modelSections []string
|
||||
for _, line := range sections["manufacturer"] {
|
||||
_, value, ok := splitEntry(line)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
parts := strings.Split(value, ",")
|
||||
base := strings.TrimSpace(parts[0])
|
||||
if base == "" {
|
||||
continue
|
||||
}
|
||||
modelSections = append(modelSections, base)
|
||||
for _, deco := range parts[1:] {
|
||||
deco = strings.TrimSpace(deco)
|
||||
if deco != "" {
|
||||
modelSections = append(modelSections, base+"."+deco)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
seen := map[string]bool{}
|
||||
var out []infModel
|
||||
for _, section := range modelSections {
|
||||
for _, line := range sections[strings.ToLower(section)] {
|
||||
name, _, ok := splitEntry(line)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
name = resolveTokens(unquote(name), strs)
|
||||
if name == "" || seen[name] {
|
||||
continue
|
||||
}
|
||||
seen[name] = true
|
||||
out = append(out, infModel{Name: name, INF: path})
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// maxINFSize guards against pointing this at something that is not an INF.
|
||||
const maxINFSize = 16 << 20
|
||||
|
||||
// parseINF reads an INF into sections (keyed lowercase) and its [Strings] table.
|
||||
func parseINF(path string) (map[string][]string, map[string]string, error) {
|
||||
info, err := os.Stat(path)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if info.Size() > maxINFSize {
|
||||
return nil, nil, fmt.Errorf("%s is %d bytes, too large to be an INF", path, info.Size())
|
||||
}
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
sections := map[string][]string{}
|
||||
strs := map[string]string{}
|
||||
current := ""
|
||||
|
||||
scanner := bufio.NewScanner(strings.NewReader(decodeINF(raw)))
|
||||
scanner.Buffer(make([]byte, 0, 64*1024), 4*1024*1024)
|
||||
for scanner.Scan() {
|
||||
line := strings.TrimSpace(stripBOM(scanner.Text()))
|
||||
if line == "" || strings.HasPrefix(line, ";") {
|
||||
continue
|
||||
}
|
||||
if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") {
|
||||
current = strings.ToLower(strings.TrimSpace(line[1 : len(line)-1]))
|
||||
continue
|
||||
}
|
||||
// Trailing comments are legal on entry lines.
|
||||
if i := strings.Index(line, ";"); i >= 0 && !strings.Contains(line[:i], "\"") {
|
||||
line = strings.TrimSpace(line[:i])
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
}
|
||||
sections[current] = append(sections[current], line)
|
||||
|
||||
if current == "strings" {
|
||||
if key, value, ok := splitEntry(line); ok {
|
||||
strs[strings.ToLower(strings.TrimSpace(key))] = unquote(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
return sections, strs, scanner.Err()
|
||||
}
|
||||
|
||||
// splitEntry splits `key = value` on the first equals sign outside quotes.
|
||||
func splitEntry(line string) (string, string, bool) {
|
||||
inQuote := false
|
||||
for i, r := range line {
|
||||
switch r {
|
||||
case '"':
|
||||
inQuote = !inQuote
|
||||
case '=':
|
||||
if !inQuote {
|
||||
return strings.TrimSpace(line[:i]), strings.TrimSpace(line[i+1:]), true
|
||||
}
|
||||
}
|
||||
}
|
||||
return "", "", false
|
||||
}
|
||||
|
||||
func unquote(s string) string {
|
||||
s = strings.TrimSpace(s)
|
||||
if len(s) >= 2 && strings.HasPrefix(s, "\"") && strings.HasSuffix(s, "\"") {
|
||||
return s[1 : len(s)-1]
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// resolveTokens expands %Token% references from the [Strings] table. Unknown
|
||||
// tokens are left as-is: a half-resolved name is more debuggable than a blank.
|
||||
func resolveTokens(s string, strs map[string]string) string {
|
||||
if !strings.Contains(s, "%") {
|
||||
return s
|
||||
}
|
||||
var b strings.Builder
|
||||
for {
|
||||
start := strings.Index(s, "%")
|
||||
if start < 0 {
|
||||
b.WriteString(s)
|
||||
break
|
||||
}
|
||||
end := strings.Index(s[start+1:], "%")
|
||||
if end < 0 {
|
||||
b.WriteString(s)
|
||||
break
|
||||
}
|
||||
end += start + 1
|
||||
|
||||
token := s[start+1 : end]
|
||||
b.WriteString(s[:start])
|
||||
if value, ok := strs[strings.ToLower(token)]; ok {
|
||||
b.WriteString(value)
|
||||
} else {
|
||||
b.WriteString(s[start : end+1])
|
||||
}
|
||||
s = s[end+1:]
|
||||
}
|
||||
return strings.TrimSpace(b.String())
|
||||
}
|
||||
|
||||
// decodeINF converts an INF's bytes to text. Windows ships its own printer INFs
|
||||
// as UTF-16LE, and plenty of vendor packages follow suit, so treating the file
|
||||
// as UTF-8 yields NUL-separated bytes that match nothing at all.
|
||||
func decodeINF(data []byte) string {
|
||||
switch {
|
||||
case len(data) >= 2 && data[0] == 0xFF && data[1] == 0xFE:
|
||||
return decodeUTF16(data[2:], binary.LittleEndian)
|
||||
case len(data) >= 2 && data[0] == 0xFE && data[1] == 0xFF:
|
||||
return decodeUTF16(data[2:], binary.BigEndian)
|
||||
case len(data) >= 3 && data[0] == 0xEF && data[1] == 0xBB && data[2] == 0xBF:
|
||||
return string(data[3:])
|
||||
default:
|
||||
return string(data)
|
||||
}
|
||||
}
|
||||
|
||||
func decodeUTF16(b []byte, order binary.ByteOrder) string {
|
||||
if len(b)%2 == 1 {
|
||||
b = b[:len(b)-1]
|
||||
}
|
||||
units := make([]uint16, len(b)/2)
|
||||
for i := range units {
|
||||
units[i] = order.Uint16(b[i*2:])
|
||||
}
|
||||
return string(utf16.Decode(units))
|
||||
}
|
||||
|
||||
// stripBOM removes a UTF-8 byte order mark, which vendor INFs frequently carry
|
||||
// and which would otherwise corrupt the first section header.
|
||||
func stripBOM(s string) string {
|
||||
return strings.TrimPrefix(s, string([]byte{0xEF, 0xBB, 0xBF}))
|
||||
}
|
||||
|
||||
// matchDriverNames returns the models whose name starts with the catalog's
|
||||
// match string, case-insensitively. Callers handle the empty-match case before
|
||||
// getting here -- it means "stage only, do not register".
|
||||
func matchDriverNames(models []infModel, match string) []infModel {
|
||||
if strings.TrimSpace(match) == "" {
|
||||
return models
|
||||
}
|
||||
prefix := strings.ToLower(strings.TrimSpace(match))
|
||||
var out []infModel
|
||||
for _, m := range models {
|
||||
if strings.HasPrefix(strings.ToLower(m.Name), prefix) {
|
||||
out = append(out, m)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// driverNameList renders model names for an error message, capped so a
|
||||
// universal driver's hundreds of models do not bury the actual problem.
|
||||
func driverNameList(models []infModel, limit int) string {
|
||||
names := make([]string, 0, len(models))
|
||||
seen := map[string]bool{}
|
||||
for _, m := range models {
|
||||
if !seen[m.Name] {
|
||||
seen[m.Name] = true
|
||||
names = append(names, m.Name)
|
||||
}
|
||||
}
|
||||
sort.Strings(names)
|
||||
if len(names) > limit {
|
||||
extra := len(names) - limit
|
||||
names = append(names[:limit], "... and "+strconv.Itoa(extra)+" more")
|
||||
}
|
||||
return strings.Join(names, "; ")
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"testing"
|
||||
"unicode/utf16"
|
||||
)
|
||||
|
||||
// A cut-down but structurally faithful printer INF: %token% names, decorated
|
||||
// model sections, quoted names containing the separator characters, comments,
|
||||
// and a [Strings] table.
|
||||
const sampleINF = `; Sample printer INF
|
||||
[Version]
|
||||
Signature="$Windows NT$"
|
||||
Class=Printer
|
||||
Provider=%VENDOR%
|
||||
|
||||
[Manufacturer]
|
||||
%VENDOR%=Vendor,NTamd64.10.0,NTarm64.10.0
|
||||
|
||||
[Vendor.NTamd64.10.0]
|
||||
%MODEL_UPD% = UPD_Install, VENDOR_UPD_PCL6 ; the universal driver
|
||||
"Vendor LaserJet 4000 PCL 6" = LJ_Install, VENDOR_LJ4000
|
||||
|
||||
[Vendor.NTarm64.10.0]
|
||||
%MODEL_UPD% = UPD_Install, VENDOR_UPD_PCL6
|
||||
|
||||
[Vendor]
|
||||
%MODEL_LEGACY% = Legacy_Install, VENDOR_LEGACY
|
||||
|
||||
[Strings]
|
||||
VENDOR = "Vendor Inc"
|
||||
MODEL_UPD = "Vendor Universal Printing PCL 6 (v7.1.0)"
|
||||
MODEL_LEGACY = "Vendor Legacy Driver"
|
||||
`
|
||||
|
||||
func writeINF(t *testing.T, content string) string {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "vendor.inf")
|
||||
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
func TestINFDriverNames(t *testing.T) {
|
||||
models, err := infDriverNames(writeINF(t, sampleINF))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
got := map[string]bool{}
|
||||
for _, m := range models {
|
||||
got[m.Name] = true
|
||||
}
|
||||
|
||||
for _, want := range []string{
|
||||
"Vendor Universal Printing PCL 6 (v7.1.0)", // resolved from %MODEL_UPD%
|
||||
"Vendor LaserJet 4000 PCL 6", // literal quoted name
|
||||
"Vendor Legacy Driver", // undecorated model section
|
||||
} {
|
||||
if !got[want] {
|
||||
t.Errorf("missing driver name %q; got %v", want, keys(got))
|
||||
}
|
||||
}
|
||||
if len(models) != 3 {
|
||||
t.Errorf("expected 3 unique models, got %d: %v", len(models), keys(got))
|
||||
}
|
||||
}
|
||||
|
||||
func keys(m map[string]bool) []string {
|
||||
out := make([]string, 0, len(m))
|
||||
for k := range m {
|
||||
out = append(out, k)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestINFHandlesBOMAndComments(t *testing.T) {
|
||||
// A UTF-8 BOM in front of the first section header is common in vendor
|
||||
// INFs and would otherwise make [Version] unparseable.
|
||||
withBOM := string([]byte{0xEF, 0xBB, 0xBF}) + sampleINF
|
||||
models, err := infDriverNames(writeINF(t, withBOM))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(models) != 3 {
|
||||
t.Fatalf("BOM broke parsing: got %d models", len(models))
|
||||
}
|
||||
}
|
||||
|
||||
// Windows ships its own printer INFs as UTF-16LE and many vendor packages do
|
||||
// the same. Read as UTF-8 they are NUL-separated bytes that match nothing, so
|
||||
// this is the difference between the provider working and silently finding no
|
||||
// drivers at all.
|
||||
func TestINFDecodesUTF16(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
bom []byte
|
||||
enc binary.ByteOrder
|
||||
}{
|
||||
{"utf16le", []byte{0xFF, 0xFE}, binary.LittleEndian},
|
||||
{"utf16be", []byte{0xFE, 0xFF}, binary.BigEndian},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
units := utf16.Encode([]rune(sampleINF))
|
||||
data := append([]byte{}, tc.bom...)
|
||||
for _, u := range units {
|
||||
b := make([]byte, 2)
|
||||
tc.enc.PutUint16(b, u)
|
||||
data = append(data, b...)
|
||||
}
|
||||
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "vendor.inf")
|
||||
if err := os.WriteFile(path, data, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
models, err := infDriverNames(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(models) != 3 {
|
||||
t.Fatalf("got %d models from a %s INF, want 3", len(models), tc.name)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMatchDriverNamesIsPrefixAndCaseInsensitive(t *testing.T) {
|
||||
models := []infModel{
|
||||
{Name: "HP Universal Printing PCL 6 (v7.1.0)"},
|
||||
{Name: "HP Universal Printing PS (v7.1.0)"},
|
||||
{Name: "HP LaserJet 4250 PCL6"},
|
||||
}
|
||||
|
||||
pcl6 := matchDriverNames(models, "HP Universal Printing PCL 6")
|
||||
if len(pcl6) != 1 || pcl6[0].Name != "HP Universal Printing PCL 6 (v7.1.0)" {
|
||||
t.Errorf("prefix match returned %v", pcl6)
|
||||
}
|
||||
|
||||
// The version suffix must not have to be typed, and case must not matter.
|
||||
if got := matchDriverNames(models, "hp universal printing"); len(got) != 2 {
|
||||
t.Errorf("case-insensitive prefix returned %d, want 2", len(got))
|
||||
}
|
||||
if got := matchDriverNames(models, "Brother"); len(got) != 0 {
|
||||
t.Errorf("non-matching prefix returned %v", got)
|
||||
}
|
||||
if got := matchDriverNames(models, ""); len(got) != 3 {
|
||||
t.Errorf("empty match should return everything, got %d", len(got))
|
||||
}
|
||||
}
|
||||
|
||||
func TestFindINFs(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
nested := filepath.Join(dir, "amd64")
|
||||
if err := os.MkdirAll(nested, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, name := range []string{
|
||||
filepath.Join(dir, "driver.inf"),
|
||||
filepath.Join(dir, "driver.cat"),
|
||||
filepath.Join(nested, "other.INF"), // case must not matter
|
||||
} {
|
||||
if err := os.WriteFile(name, []byte("x"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
found, err := findINFs(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(found) != 2 {
|
||||
t.Errorf("found %v, want the two .inf files", found)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveTokensLeavesUnknownTokens(t *testing.T) {
|
||||
strs := map[string]string{"known": "Resolved"}
|
||||
if got := resolveTokens("%KNOWN% Driver", strs); got != "Resolved Driver" {
|
||||
t.Errorf("got %q", got)
|
||||
}
|
||||
// A half-resolved name is more debuggable than a blank one.
|
||||
if got := resolveTokens("%MYSTERY% Driver", strs); got != "%MYSTERY% Driver" {
|
||||
t.Errorf("got %q", got)
|
||||
}
|
||||
if got := resolveTokens("100% Compatible", strs); got != "100% Compatible" {
|
||||
t.Errorf("stray percent mangled: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSplitEntryIgnoresEqualsInsideQuotes(t *testing.T) {
|
||||
key, value, ok := splitEntry(`"Driver = Special" = Install_Section, HWID`)
|
||||
if !ok || key != `"Driver = Special"` || value != "Install_Section, HWID" {
|
||||
t.Errorf("got key=%q value=%q ok=%v", key, value, ok)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLocalPathStripsFileScheme(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
`file:///C:/drivers/hp`: `C:/drivers/hp`,
|
||||
`file://server/drivers`: `server/drivers`,
|
||||
`\\server\drivers\hp`: `\\server\drivers\hp`,
|
||||
`C:\drivers\hp`: `C:\drivers\hp`,
|
||||
`https://example.test/x`: `https://example.test/x`,
|
||||
}
|
||||
for in, want := range cases {
|
||||
if got := localPath(in); got != want {
|
||||
t.Errorf("localPath(%q) = %q, want %q", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsLocalSource(t *testing.T) {
|
||||
local := []string{`\\fileserver\drivers\hp`, `C:\drivers`, `C:/drivers`, `file:///C:/d`, `/srv/drivers`}
|
||||
remote := []string{"https://example.test/d.zip", "http://example.test/d.zip", "example.test/d"}
|
||||
for _, s := range local {
|
||||
if !isLocalSource(s) {
|
||||
t.Errorf("%q should be local", s)
|
||||
}
|
||||
}
|
||||
for _, s := range remote {
|
||||
if isLocalSource(s) {
|
||||
t.Errorf("%q should be remote", s)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestParseRealWindowsPrinterINFs runs the parser over the printer INFs Windows
|
||||
// ships, which is the only cheap source of genuine vendor-shaped INF files.
|
||||
func TestParseRealWindowsPrinterINFs(t *testing.T) {
|
||||
if runtime.GOOS != "windows" {
|
||||
t.Skip("no Windows INF directory")
|
||||
}
|
||||
matches, err := filepath.Glob(`C:\Windows\INF\prn*.inf`)
|
||||
if err != nil || len(matches) == 0 {
|
||||
t.Skip("no printer INFs on this machine")
|
||||
}
|
||||
|
||||
parsed := 0
|
||||
for _, path := range matches {
|
||||
models, err := infDriverNames(path)
|
||||
if err != nil {
|
||||
continue // an unreadable INF is a permissions problem, not a parser bug
|
||||
}
|
||||
for _, m := range models {
|
||||
if m.Name == "" {
|
||||
t.Errorf("%s produced an empty driver name", path)
|
||||
}
|
||||
}
|
||||
if len(models) > 0 {
|
||||
parsed++
|
||||
}
|
||||
}
|
||||
if parsed == 0 {
|
||||
t.Errorf("parsed %d printer INFs but found no driver names in any of them", len(matches))
|
||||
}
|
||||
t.Logf("extracted driver names from %d of %d Windows printer INFs", parsed, len(matches))
|
||||
}
|
||||
@@ -77,6 +77,7 @@ func init() {
|
||||
register(&flatpak{})
|
||||
register(&snap{})
|
||||
register(&direct{})
|
||||
register(&printerDriver{})
|
||||
}
|
||||
|
||||
// Get returns the provider registered under name.
|
||||
|
||||
Reference in new issue
Block a user