diff --git a/README.md b/README.md index f2ac95a..36807d7 100644 --- a/README.md +++ b/README.md @@ -225,6 +225,34 @@ Full format reference and worked examples: [docs/CATALOG.md](docs/CATALOG.md). | `flatpak` | Linux | System-wide as root, per-user otherwise | | `snap` | Linux | | | `direct` | all | Vendor download: msi, exe, msu, dmg, pkg, deb, rpm, zip, tar.gz, AppImage | +| `driver` | Windows | Printer and scanner drivers via `pnputil`, from a URL or your driver share | + +## Printer and scanner drivers + +``` +deployr install @printers +deployr install hp-upd-pcl6 xerox-gpd-pcl6 +deployr install @scanners +``` + +Deployr stages the package into the driver store with `pnputil` and registers it +with the print spooler, so it shows up in Add Printer. It reads driver names out +of the package's own INF files and matches on a prefix, so you never type +`HP Universal Printing PCL 6 (v7.1.0)` and never chase the version suffix when +the vendor bumps it. + +Vendor driver URLs are version-pinned and several are EULA-gated, so the catalog +points at **your own driver share** instead: + +```powershell +setx /m DEPLOYR_DRIVERS \\fileserver\drivers +``` + +Ships with universal drivers for HP, Xerox, Ricoh, Sharp, Canon, Kyocera, Konica +Minolta, Lexmark, Brother, Toshiba, Epson, Muratec and Zebra, plus scanner +packages for the Fujitsu/Ricoh fi series, ScanSnap, Canon DR, Epson, Brother, +Visioneer/DocuMate and Kodak Alaris. Full details, including per-site overlays: +[docs/PRINTERS.md](docs/PRINTERS.md). ## Building diff --git a/docs/PRINTERS.md b/docs/PRINTERS.md new file mode 100644 index 0000000..70b676a --- /dev/null +++ b/docs/PRINTERS.md @@ -0,0 +1,184 @@ +# Printer and scanner drivers + +Deployr installs Windows printer and scanner drivers the same way it installs +applications: pick them in the UI or name them on the command line. + +``` +deployr install @printers +deployr install hp-upd-pcl6 xerox-gpd-pcl6 +deployr install @scanners +deployr status --catalog ... | findstr driver +``` + +Under the hood it stages the package into the Windows driver store with +`pnputil`, then registers the driver with the print spooler so it appears in +Add Printer. Detection reads the spooler, so a run is idempotent even when a +technician installed the driver by hand. + +**This is Windows only.** macOS and Linux print through CUPS, where the driver +is part of the queue rather than a separately installed component. + +## Point it at your driver share first + +Vendor driver packages are version-pinned (`upd-pcl6-x64-7.3.0.24923.exe`) and +several vendors put theirs behind a click-through EULA, so there is no stable +URL anyone can ship in a catalog. Mirror the packages on your own share instead +— which is what you want anyway: a known-good version, on the LAN, at LAN speed. + +```powershell +setx /m DEPLOYR_DRIVERS \\fileserver\drivers +``` + +Lay it out one folder per package, matching the paths in the catalog: + +``` +\\fileserver\drivers\ + hp\upd-pcl6\ <- the extracted driver (the folder with the .inf in it) + hp\upd-ps\ + xerox\gpd-pcl6\ + ricoh\pcl6-upd\ + sharp\ud\ + canon\generic-plus-ufr2\ + fujitsu\paperstream-ip\ <- an .msi is fine too +``` + +A folder is preferred: `pnputil` stages it directly with no unpacking step. A +`.zip` of the same folder works, as does an `.msi`. An `.exe` needs the vendor's +silent switches in `silent_args`. + +Check what a machine can see: + +``` +deployr info hp-upd-pcl6 +deployr install hp-upd-pcl6 --dry-run --verbose +``` + +If `DEPLOYR_DRIVERS` is not set, deployr says so by name rather than failing +with a confusing "file not found". + +## You do not have to type exact driver names + +Printer driver names carry the version — `HP Universal Printing PCL 6 (v7.1.0)` +— so an exact name goes stale at the vendor's next release. Deployr reads the +model names out of the package's own INF files and matches on a **prefix**: + +```yaml +- provider: driver + url: $DEPLOYR_DRIVERS/hp/upd-pcl6 + driver_match: HP Universal Printing PCL 6 # version suffix not needed +``` + +If the prefix matches nothing, the error lists the names the package actually +provides, so you can correct the entry without guessing: + +``` +fail hp-upd-pcl6 no driver in this package matches "HP Universal Print PCL6"; + the package provides: HP Universal Printing PCL 6 (v7.1.0); HP Universal + Printing PS (v7.1.0); ... and 3 more +``` + +INF files are frequently UTF-16 and use `%token%` names resolved from a +`[Strings]` table; deployr handles both. + +## Scanners + +Scanners are TWAIN/WIA rather than spooler drivers, so there is nothing to +register — staging the package is the whole job. That is what leaving +`driver_match` unset means: + +```yaml +- id: paperstream-ip + name: PaperStream IP (Ricoh/Fujitsu fi series) + categories: [scanner-driver] + windows: + sources: + - provider: driver + url: $DEPLOYR_DRIVERS/fujitsu/paperstream-ip + kind: msi # no driver_match: stage/install only + detect: + registry: ["PaperStream IP"] +``` + +Detection for scanners uses the uninstall registry entry, since a TWAIN data +source has no spooler record. `paths` works too, for example +`%SystemRoot%/twain_64/*PaperStream*`. + +## What ships in the catalog + +Printer drivers (`deployr list --category printer-driver`): + +| Vendor | Entries | +| --- | --- | +| HP | `hp-upd-pcl6`, `hp-upd-ps` | +| Xerox | `xerox-gpd-pcl6`, `xerox-gpd-ps` | +| Ricoh | `ricoh-upd-pcl6`, `ricoh-upd-ps` | +| Sharp | `sharp-ud` | +| Canon | `canon-generic-plus-ufr`, `canon-generic-plus-pcl6` | +| Kyocera | `kyocera-kx` | +| Konica Minolta | `konica-universal-pcl` | +| Lexmark | `lexmark-universal` | +| Brother | `brother-universal` | +| Toshiba | `toshiba-universal` | +| Epson | `epson-universal` | +| Muratec | `muratec-mfx` | +| Zebra | `zebra-zdesigner` | + +Scanner drivers (`deployr list --category scanner-driver`): `paperstream-ip`, +`scansnap-home`, `canon-dr-driver`, `epson-scan2`, `brother-iprintscan`, +`visioneer-twain`, `kodak-alaris-scanner`, `hp-scan-extended`, `sharp-twain`, +`ricoh-twain`, `konica-twain`. + +Profiles: `@printers` (HP, Xerox, Ricoh, Sharp), `@printers-all`, `@scanners`. + +The `driver_match` prefixes are deployr's best guess at each vendor's driver +name. The first time you run one, check the result — if the prefix is wrong the +error tells you the right name, and you fix it once in an overlay. + +## Site-specific printers + +Most sites have one or two specific machines rather than a universal driver. +Put those in an overlay next to the shipped catalog: + +`C:\ProgramData\Deployr\catalog.d\acme-printers.yaml` + +```yaml +apps: + - id: acme-frontdesk-mfp + name: Acme Front Desk MFP (Ricoh IM C3000) + categories: [printer-driver] + windows: + sources: + - provider: driver + url: \\acme-dc01\drivers\ricoh\im-c3000 + driver_match: RICOH IM C3000 + detect: + printer_drivers: ["RICOH IM C3000"] + +profiles: + acme-onboard: [acme-frontdesk-mfp, chrome, adobereader, 7zip] +``` + +Then any machine at that site is one line: + +``` +deployr install @acme-onboard +``` + +Note that the overlay's `url` points straight at the client's own server, so it +does not need `DEPLOYR_DRIVERS` at all. + +## Removing a driver + +``` +deployr uninstall hp-upd-pcl6 +``` + +The spooler refuses to remove a driver a printer still uses, and deployr reports +that plainly — remove the printer first. + +## A note on where printing is going + +Microsoft has been phasing out third-party v3 print drivers in favour of IPP and +Mopria class drivers. Newer devices increasingly need no vendor driver at all, +and Windows Protected Print Mode blocks them outright. This is for the fleet you +still have to support, not the direction to build new sites in. diff --git a/internal/catalog/data/apps.yaml b/internal/catalog/data/apps.yaml index dac8570..0649c64 100644 --- a/internal/catalog/data/apps.yaml +++ b/internal/catalog/data/apps.yaml @@ -1161,6 +1161,407 @@ apps: detect: registry: ["HWiNFO"] + + # ----------------------------------------------------- printer drivers --- + # + # Printer driver packages are version-pinned and several vendors put theirs + # behind a click-through EULA, so there is no stable URL to ship. These + # entries point at your own driver share instead: + # + # setx /m DEPLOYR_DRIVERS \\fileserver\drivers + # + # Under it, one folder per package holding the extracted driver (the folder + # with the .inf files in it), or a .zip of the same. A folder is preferred -- + # pnputil stages it directly with no unpacking step. + # + # driver_match is a PREFIX of the driver name as the spooler knows it, so the + # version suffix vendors stamp on ("(v7.1.0)") does not have to be tracked. + # If a match is wrong, deployr lists the names the package actually provides, + # which is how you correct the entry. See docs/PRINTERS.md. + + - id: hp-upd-pcl6 + name: HP Universal Print Driver (PCL 6) + description: HP's universal driver for LaserJet and OfficeJet fleets + homepage: https://support.hp.com/us-en/drivers + categories: [printer-driver] + aliases: [hp-upd, hpupd] + windows: + sources: + - provider: driver + url: $DEPLOYR_DRIVERS/hp/upd-pcl6 + driver_match: HP Universal Printing PCL 6 + detect: + printer_drivers: ["HP Universal Printing PCL 6"] + + - id: hp-upd-ps + name: HP Universal Print Driver (PostScript) + homepage: https://support.hp.com/us-en/drivers + categories: [printer-driver] + windows: + sources: + - provider: driver + url: $DEPLOYR_DRIVERS/hp/upd-ps + driver_match: HP Universal Printing PS + detect: + printer_drivers: ["HP Universal Printing PS"] + + - id: xerox-gpd-pcl6 + name: Xerox Global Print Driver (PCL 6) + description: One driver for a mixed Xerox fleet + homepage: https://www.support.xerox.com/en-us/global-print-driver + categories: [printer-driver] + aliases: [xerox-gpd, xerox] + windows: + sources: + - provider: driver + url: $DEPLOYR_DRIVERS/xerox/gpd-pcl6 + driver_match: Xerox Global Print Driver PCL6 + detect: + printer_drivers: ["Xerox Global Print Driver PCL6", "Xerox Global Print Driver"] + + - id: xerox-gpd-ps + name: Xerox Global Print Driver (PostScript) + homepage: https://www.support.xerox.com/en-us/global-print-driver + categories: [printer-driver] + windows: + sources: + - provider: driver + url: $DEPLOYR_DRIVERS/xerox/gpd-ps + driver_match: Xerox Global Print Driver PS + detect: + printer_drivers: ["Xerox Global Print Driver PS"] + + - id: ricoh-upd-pcl6 + name: Ricoh PCL6 Universal Driver + homepage: https://www.ricoh-usa.com/en/support-and-download + categories: [printer-driver] + aliases: [ricoh, ricoh-upd] + windows: + sources: + - provider: driver + url: $DEPLOYR_DRIVERS/ricoh/pcl6-upd + driver_match: RICOH PCL6 UniversalDriver + detect: + printer_drivers: ["RICOH PCL6 UniversalDriver", "RICOH PCL6 Universal"] + + - id: ricoh-upd-ps + name: Ricoh PostScript Universal Driver + homepage: https://www.ricoh-usa.com/en/support-and-download + categories: [printer-driver] + windows: + sources: + - provider: driver + url: $DEPLOYR_DRIVERS/ricoh/ps-upd + driver_match: RICOH PS Universal Driver + detect: + printer_drivers: ["RICOH PS Universal Driver", "RICOH PS Universal"] + + - id: sharp-ud + name: Sharp Universal Driver + description: Sharp's universal driver for MX/BP series MFPs + homepage: https://global.sharp/restricted/products/copier/downloads/select_us_driver.html + categories: [printer-driver] + aliases: [sharp] + windows: + sources: + - provider: driver + url: $DEPLOYR_DRIVERS/sharp/ud + driver_match: SHARP UD + detect: + printer_drivers: ["SHARP UD"] + + - id: canon-generic-plus-ufr + name: Canon Generic Plus UFR II + homepage: https://www.usa.canon.com/support + categories: [printer-driver] + aliases: [canon, canon-ufr] + windows: + sources: + - provider: driver + url: $DEPLOYR_DRIVERS/canon/generic-plus-ufr2 + driver_match: Canon Generic Plus UFR II + detect: + printer_drivers: ["Canon Generic Plus UFR II"] + + - id: canon-generic-plus-pcl6 + name: Canon Generic Plus PCL6 + homepage: https://www.usa.canon.com/support + categories: [printer-driver] + windows: + sources: + - provider: driver + url: $DEPLOYR_DRIVERS/canon/generic-plus-pcl6 + driver_match: Canon Generic Plus PCL6 + detect: + printer_drivers: ["Canon Generic Plus PCL6"] + + - id: kyocera-kx + name: Kyocera KX Driver + homepage: https://www.kyoceradocumentsolutions.us/en/support/downloads.html + categories: [printer-driver] + aliases: [kyocera] + windows: + sources: + - provider: driver + url: $DEPLOYR_DRIVERS/kyocera/kx + driver_match: Kyocera + detect: + printer_drivers: ["Kyocera"] + + - id: konica-universal-pcl + name: Konica Minolta Universal PCL + homepage: https://www.konicaminolta.us/business/support/downloads + categories: [printer-driver] + aliases: [konica, konicaminolta] + windows: + sources: + - provider: driver + url: $DEPLOYR_DRIVERS/konica/universal-pcl + driver_match: KONICA MINOLTA Universal + detect: + printer_drivers: ["KONICA MINOLTA Universal"] + + - id: lexmark-universal + name: Lexmark Universal Print Driver + homepage: https://support.lexmark.com/en_us/drivers.html + categories: [printer-driver] + aliases: [lexmark] + windows: + sources: + - provider: driver + url: $DEPLOYR_DRIVERS/lexmark/universal + driver_match: Lexmark Universal + detect: + printer_drivers: ["Lexmark Universal"] + + - id: brother-universal + name: Brother Universal Printer Driver + homepage: https://support.brother.com/g/b/productsearch.aspx + categories: [printer-driver] + aliases: [brother] + windows: + sources: + - provider: driver + url: $DEPLOYR_DRIVERS/brother/universal + driver_match: Brother Universal Printer + detect: + printer_drivers: ["Brother Universal Printer"] + + - id: toshiba-universal + name: Toshiba Universal Printer 2 + homepage: https://www.toshibatec.com/support/ + categories: [printer-driver] + aliases: [toshiba] + windows: + sources: + - provider: driver + url: $DEPLOYR_DRIVERS/toshiba/universal2 + driver_match: TOSHIBA Universal Printer + detect: + printer_drivers: ["TOSHIBA Universal Printer"] + + - id: epson-universal + name: Epson Universal Print Driver + homepage: https://epson.com/Support/Printers/sh/s1 + categories: [printer-driver] + aliases: [epson] + windows: + sources: + - provider: driver + url: $DEPLOYR_DRIVERS/epson/universal + driver_match: EPSON Universal Print Driver + detect: + printer_drivers: ["EPSON Universal Print Driver"] + + - id: muratec-mfx + name: Muratec MFX Driver + homepage: https://www.muratec.com/drivers-and-support/drivers/ + categories: [printer-driver] + aliases: [muratec] + windows: + sources: + - provider: driver + url: $DEPLOYR_DRIVERS/muratec/mfx + driver_match: Muratec + detect: + printer_drivers: ["Muratec"] + notes: Muratec ships model-specific drivers rather than a universal one; point this entry at the package for the model on site. + + - id: zebra-zdesigner + name: Zebra ZDesigner Driver + description: Label and receipt printers + homepage: https://www.zebra.com/us/en/support-downloads/printer-software.html + categories: [printer-driver] + aliases: [zebra] + windows: + sources: + - provider: driver + url: $DEPLOYR_DRIVERS/zebra/zdesigner + driver_match: ZDesigner + detect: + printer_drivers: ["ZDesigner"] + + + # ----------------------------------------------------- scanner drivers --- + # + # Scanners are TWAIN/WIA rather than spooler drivers, so there is nothing to + # register: staging the package into the driver store is the whole job. That + # is what leaving driver_match unset means. + # + # Most business scanners ship a vendor installer instead of a bare INF. For + # those, mirror the MSI and the entry installs it silently; an .exe needs the + # vendor's silent switches in silent_args. Detection is the uninstall entry, + # because a TWAIN data source has no spooler record to look up. + + - id: paperstream-ip + name: PaperStream IP (Ricoh/Fujitsu fi series) + description: TWAIN/ISIS driver for fi-series production scanners + homepage: https://www.pfu.ricoh.com/global/scanners/fi/downloads/ + categories: [scanner-driver] + aliases: [fujitsu-fi, fi-series, paperstream] + windows: + sources: + - provider: driver + url: $DEPLOYR_DRIVERS/fujitsu/paperstream-ip + kind: msi + detect: + registry: ["PaperStream IP"] + paths: ["%SystemRoot%/twain_64/*PaperStream*", "%SystemRoot%/twain_32/*PaperStream*"] + + - id: scansnap-home + name: ScanSnap Home + description: Software and driver for ScanSnap desktop scanners + homepage: https://www.pfu.ricoh.com/global/scanners/scansnap/dl/ + categories: [scanner-driver] + aliases: [scansnap] + windows: + sources: + - provider: driver + url: $DEPLOYR_DRIVERS/fujitsu/scansnap-home + kind: msi + detect: + registry: ["ScanSnap Home"] + + - id: canon-dr-driver + name: Canon imageFORMULA DR Driver + description: TWAIN/ISIS driver for imageFORMULA DR document scanners + homepage: https://www.usa.canon.com/support + categories: [scanner-driver] + aliases: [canon-dr, imageformula] + windows: + sources: + - provider: driver + url: $DEPLOYR_DRIVERS/canon/dr-driver + kind: msi + detect: + registry: ["Canon DR", "CANON DR"] + paths: ["%SystemRoot%/twain_64/CANONDR*"] + + - id: epson-scan2 + name: Epson Scan 2 + homepage: https://epson.com/Support/Printers/sh/s1 + categories: [scanner-driver] + aliases: [epson-scan] + windows: + sources: + - provider: driver + url: $DEPLOYR_DRIVERS/epson/scan2 + kind: msi + detect: + registry: ["Epson Scan 2", "EPSON Scan 2"] + + - id: brother-iprintscan + name: Brother iPrint&Scan + homepage: https://support.brother.com/g/b/productsearch.aspx + categories: [scanner-driver] + aliases: [brother-scan] + windows: + sources: + - provider: driver + url: $DEPLOYR_DRIVERS/brother/iprintscan + kind: msi + detect: + registry: ["Brother iPrint&Scan", "iPrint&Scan"] + + - id: visioneer-twain + name: Visioneer / Xerox DocuMate Driver + description: TWAIN driver for Xerox DocuMate and Visioneer scanners + homepage: https://www.visioneer.com/support/downloads + categories: [scanner-driver] + aliases: [documate, visioneer] + windows: + sources: + - provider: driver + url: $DEPLOYR_DRIVERS/xerox/documate + kind: msi + detect: + registry: ["Visioneer", "Xerox DocuMate"] + + - id: kodak-alaris-scanner + name: Kodak Alaris Scanner Driver + description: TWAIN/ISIS driver for S2000 and i-series scanners + homepage: https://support.alarisworld.com/ + categories: [scanner-driver] + aliases: [kodak, alaris] + windows: + sources: + - provider: driver + url: $DEPLOYR_DRIVERS/kodak/alaris + kind: msi + detect: + registry: ["Kodak Alaris", "Alaris Smart Touch"] + + - id: hp-scan-extended + name: HP Scan and Capture + description: Scanning component for HP MFPs and ScanJets + homepage: https://support.hp.com/us-en/drivers + categories: [scanner-driver] + aliases: [hp-scan, scanjet] + windows: + sources: + - provider: driver + url: $DEPLOYR_DRIVERS/hp/scan + kind: msi + detect: + registry: ["HP Scan", "HP ScanJet"] + + - id: sharp-twain + name: Sharp TWAIN Driver + description: Pull-scanning from Sharp MFPs + homepage: https://global.sharp/restricted/products/copier/downloads/select_us_driver.html + categories: [scanner-driver] + windows: + sources: + - provider: driver + url: $DEPLOYR_DRIVERS/sharp/twain + detect: + registry: ["Sharp TWAIN", "SHARP TWAIN"] + paths: ["%SystemRoot%/twain_64/Sharp*"] + + - id: ricoh-twain + name: Ricoh TWAIN Driver + description: Pull-scanning from Ricoh MFPs + homepage: https://www.ricoh-usa.com/en/support-and-download + categories: [scanner-driver] + windows: + sources: + - provider: driver + url: $DEPLOYR_DRIVERS/ricoh/twain + detect: + registry: ["RICOH TWAIN", "Ricoh TWAIN"] + paths: ["%SystemRoot%/twain_64/Ricoh*"] + + - id: konica-twain + name: Konica Minolta TWAIN Driver + homepage: https://www.konicaminolta.us/business/support/downloads + categories: [scanner-driver] + windows: + sources: + - provider: driver + url: $DEPLOYR_DRIVERS/konica/twain + detect: + registry: ["KONICA MINOLTA TWAIN", "KONICA MINOLTA Scan"] + # Profiles are named bundles: `deployr install @standard`. profiles: standard: @@ -1201,3 +1602,32 @@ profiles: - audacity - handbrake - gimp + # Printer and scanner bundles need DEPLOYR_DRIVERS pointed at your driver + # share -- see docs/PRINTERS.md. + printers: + - hp-upd-pcl6 + - xerox-gpd-pcl6 + - ricoh-upd-pcl6 + - sharp-ud + printers-all: + - hp-upd-pcl6 + - hp-upd-ps + - xerox-gpd-pcl6 + - xerox-gpd-ps + - ricoh-upd-pcl6 + - ricoh-upd-ps + - sharp-ud + - canon-generic-plus-ufr + - canon-generic-plus-pcl6 + - kyocera-kx + - konica-universal-pcl + - lexmark-universal + - brother-universal + - toshiba-universal + - epson-universal + - muratec-mfx + scanners: + - paperstream-ip + - canon-dr-driver + - epson-scan2 + - brother-iprintscan diff --git a/internal/catalog/load.go b/internal/catalog/load.go index f252e57..52b0903 100644 --- a/internal/catalog/load.go +++ b/internal/catalog/load.go @@ -143,11 +143,18 @@ func (c *Catalog) validate(origin string) error { if s.Provider == "" { return fmt.Errorf("%s: app %q %s source %d has no provider", origin, app.ID, goos, i+1) } - if s.Provider == "direct" && s.URL == "" && len(s.URLs) == 0 { - return fmt.Errorf("%s: app %q %s direct source has no url", origin, app.ID, goos) - } - if s.Provider != "direct" && s.ID == "" { - return fmt.Errorf("%s: app %q %s %s source has no id", origin, app.ID, goos, s.Provider) + // direct and driver sources carry a location rather than a + // package identifier; everything else needs an id. + switch s.Provider { + case "direct", "driver": + if s.URL == "" && len(s.URLs) == 0 { + return fmt.Errorf("%s: app %q %s %s source has no url or path", + origin, app.ID, goos, s.Provider) + } + default: + if s.ID == "" { + return fmt.Errorf("%s: app %q %s %s source has no id", origin, app.ID, goos, s.Provider) + } } } } diff --git a/internal/catalog/types.go b/internal/catalog/types.go index 3065814..ee6daa4 100644 --- a/internal/catalog/types.go +++ b/internal/catalog/types.go @@ -76,6 +76,13 @@ type Source struct { // UninstallID lets uninstall fall back to a different identifier, e.g. the // registry DisplayName for something installed from a vendor MSI. UninstallID string `yaml:"uninstall_id,omitempty"` + + // DriverMatch applies to the "driver" provider: the prefix of the printer + // driver name to register out of the package, e.g. "HP Universal Printing + // PCL 6". Matching on a prefix means the version suffix vendors stamp into + // the name does not have to be tracked. Empty registers every model the + // package declares. + DriverMatch string `yaml:"driver_match,omitempty"` } // URLFor returns the download URL for a GOARCH. @@ -110,11 +117,16 @@ type Detect struct { Paths []string `yaml:"paths,omitempty"` // Registry are Windows uninstall-entry DisplayName prefixes. Registry []string `yaml:"registry,omitempty"` + // PrinterDrivers are printer driver name prefixes to look for in the + // Windows print subsystem. A printer driver leaves no uninstall entry, so + // this is the only way to tell one is present. + PrinterDrivers []string `yaml:"printer_drivers,omitempty"` } // Empty reports whether there is nothing to check. func (d Detect) Empty() bool { - return len(d.Commands) == 0 && len(d.Paths) == 0 && len(d.Registry) == 0 + return len(d.Commands) == 0 && len(d.Paths) == 0 && + len(d.Registry) == 0 && len(d.PrinterDrivers) == 0 } // TargetFor returns the recipe for a GOOS, or nil when unsupported. diff --git a/internal/detect/detect.go b/internal/detect/detect.go index 632bc3e..910de63 100644 --- a/internal/detect/detect.go +++ b/internal/detect/detect.go @@ -7,6 +7,7 @@ import ( "os/exec" "path/filepath" "runtime" + "strconv" "strings" "time" @@ -31,6 +32,14 @@ func Installed(d catalog.Detect) (bool, string) { return false, "" } + if len(d.PrinterDrivers) > 0 && runtime.GOOS == "windows" { + if driver, ok := FindPrinterDriver(d.PrinterDrivers); ok { + // The version lives inside the name for most printer drivers, so + // report the name rather than a bare major version number. + return true, driverVersion(driver) + } + } + if len(d.Registry) > 0 && runtime.GOOS == "windows" { if entry, ok := FindRegistry(d.Registry); ok { return true, entry.DisplayVersion @@ -52,6 +61,23 @@ func Installed(d catalog.Detect) (bool, string) { return false, "" } +// driverVersion pulls the version out of a printer driver name, which is where +// vendors put it -- "HP Universal Printing PCL 6 (v7.1.0)" yields "v7.1.0". +// Falls back to the spooler's major version when the name carries none. +func driverVersion(d PrinterDriver) string { + if open := strings.LastIndex(d.Name, "("); open >= 0 { + if close := strings.LastIndex(d.Name, ")"); close > open { + if inner := strings.TrimSpace(d.Name[open+1 : close]); inner != "" { + return inner + } + } + } + if d.MajorVersion > 0 { + return "v" + strconv.Itoa(d.MajorVersion) + } + return "" +} + // bundleVersion reads CFBundleShortVersionString from a macOS .app bundle. // Everything else has no cheap, universal version probe, so we report none // rather than guessing. diff --git a/internal/detect/printerdriver_other.go b/internal/detect/printerdriver_other.go new file mode 100644 index 0000000..6ec868f --- /dev/null +++ b/internal/detect/printerdriver_other.go @@ -0,0 +1,18 @@ +//go:build !windows + +package detect + +// PrinterDriver is one driver registered with the Windows print subsystem. +type PrinterDriver struct { + Name string + MajorVersion int + Manufacturer string +} + +// PrinterDrivers has nothing to read outside Windows: macOS and Linux print +// through CUPS, where the driver is part of the queue rather than a separately +// installed component. +func PrinterDrivers() []PrinterDriver { return nil } + +// FindPrinterDriver never matches outside Windows. +func FindPrinterDriver([]string) (PrinterDriver, bool) { return PrinterDriver{}, false } diff --git a/internal/detect/printerdriver_windows.go b/internal/detect/printerdriver_windows.go new file mode 100644 index 0000000..d3ecd1c --- /dev/null +++ b/internal/detect/printerdriver_windows.go @@ -0,0 +1,77 @@ +package detect + +import ( + "context" + "encoding/json" + "os/exec" + "strings" + "sync" + "syscall" + "time" +) + +// PrinterDriver is one driver registered with the Windows print subsystem. +type PrinterDriver struct { + Name string `json:"Name"` + MajorVersion int `json:"MajorVersion"` + Manufacturer string `json:"Manufacturer"` +} + +var ( + printerOnce sync.Once + printerList []PrinterDriver +) + +// PrinterDrivers returns the printer drivers installed on this machine, read +// once per process. A printer driver has no uninstall registry entry and no +// file on PATH, so the spooler is the only source of truth for whether one is +// present. +func PrinterDrivers() []PrinterDriver { + printerOnce.Do(func() { + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + + cmd := exec.CommandContext(ctx, "powershell", "-NoProfile", "-NonInteractive", "-Command", + "Get-PrinterDriver | Select-Object Name,MajorVersion,Manufacturer | ConvertTo-Json -Compress") + cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true} + out, err := cmd.Output() + if err != nil { + return + } + + trimmed := strings.TrimSpace(string(out)) + if trimmed == "" { + return + } + // ConvertTo-Json emits a bare object when there is exactly one result. + if strings.HasPrefix(trimmed, "{") { + var one PrinterDriver + if json.Unmarshal([]byte(trimmed), &one) == nil { + printerList = []PrinterDriver{one} + } + return + } + _ = json.Unmarshal([]byte(trimmed), &printerList) + }) + return printerList +} + +// FindPrinterDriver returns the first installed driver whose name starts with +// one of the prefixes. Prefix matching is deliberate: vendors stamp a version +// into the driver name ("HP Universal Printing PCL 6 (v7.1.0)") and it changes +// with every release. +func FindPrinterDriver(prefixes []string) (PrinterDriver, bool) { + drivers := PrinterDrivers() + for _, prefix := range prefixes { + p := strings.ToLower(strings.TrimSpace(prefix)) + if p == "" { + continue + } + for _, d := range drivers { + if strings.HasPrefix(strings.ToLower(d.Name), p) { + return d, true + } + } + } + return PrinterDriver{}, false +} diff --git a/internal/platform/platform.go b/internal/platform/platform.go index 13b502c..b24a4b6 100644 --- a/internal/platform/platform.go +++ b/internal/platform/platform.go @@ -116,6 +116,45 @@ func firstWritable(candidates ...string) string { var winVar = regexp.MustCompile(`%([A-Za-z_][A-Za-z0-9_()]*)%`) +// ExpandVars resolves $VAR, ${VAR} and Windows-style %VAR% in a string, without +// touching path separators. Use this for anything that is not a filesystem path +// -- a URL in particular, which filepath.Clean would mangle into "https:/host". +func ExpandVars(s string) string { + if s == "" { + return "" + } + s = winVar.ReplaceAllStringFunc(s, func(m string) string { + return os.Getenv(strings.Trim(m, "%")) + }) + return os.ExpandEnv(s) +} + +var unixVar = regexp.MustCompile(`\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?`) + +// MissingVars returns the environment variables a string references that are +// unset or empty. Expansion turns those into nothing, which produces a baffling +// "no such file" three layers down; naming the variable up front does not. +func MissingVars(s string) []string { + var missing []string + seen := map[string]bool{} + note := func(name string) { + if name == "" || seen[name] { + return + } + seen[name] = true + if os.Getenv(name) == "" { + missing = append(missing, name) + } + } + for _, m := range winVar.FindAllStringSubmatch(s, -1) { + note(m[1]) + } + for _, m := range unixVar.FindAllStringSubmatch(s, -1) { + note(m[1]) + } + return missing +} + // ExpandPath resolves ~, $VAR/${VAR} and Windows-style %VAR% in a path. // Unset variables expand to empty, matching shell behaviour. func ExpandPath(p string) string { @@ -127,10 +166,14 @@ func ExpandPath(p string) string { p = filepath.Join(home, strings.TrimPrefix(p, "~")) } } - p = winVar.ReplaceAllStringFunc(p, func(m string) string { - return os.Getenv(strings.Trim(m, "%")) - }) - p = os.ExpandEnv(p) + p = ExpandVars(p) + if p == "" { + return "" + } + // A UNC path must keep its leading double slash, which Clean would eat. + if strings.HasPrefix(p, `\\`) || strings.HasPrefix(p, "//") { + return `\\` + filepath.Clean(strings.TrimLeft(p, `\/`)) + } return filepath.Clean(p) } diff --git a/internal/provider/direct.go b/internal/provider/direct.go index 981a9a1..4bd0ded 100644 --- a/internal/provider/direct.go +++ b/internal/provider/direct.go @@ -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": diff --git a/internal/provider/driver.go b/internal/provider/driver.go new file mode 100644 index 0000000..2b85061 --- /dev/null +++ b/internal/provider/driver.go @@ -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, "'", "''") } diff --git a/internal/provider/inf.go b/internal/provider/inf.go new file mode 100644 index 0000000..e53e83d --- /dev/null +++ b/internal/provider/inf.go @@ -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, "; ") +} diff --git a/internal/provider/inf_test.go b/internal/provider/inf_test.go new file mode 100644 index 0000000..a523ec0 --- /dev/null +++ b/internal/provider/inf_test.go @@ -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)) +} diff --git a/internal/provider/provider.go b/internal/provider/provider.go index f64e6db..f843183 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -77,6 +77,7 @@ func init() { register(&flatpak{}) register(&snap{}) register(&direct{}) + register(&printerDriver{}) } // Get returns the provider registered under name.