Files
Deployr/internal/provider/inf.go
T
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

272 lines
7.4 KiB
Go

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, "; ")
}