mirror of
https://github.com/kfattic/cupsadmin.git
synced 2026-11-13 19:06:43 -05:00
Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4832b74c3a | ||
|
|
366bd74225 | ||
|
|
cf0241beac | ||
|
|
42c1381ebf | ||
|
|
d81de4a531 |
14
CLAUDE.md
14
CLAUDE.md
@@ -29,6 +29,10 @@ Private maintainer notes, if present, are in `CLAUDE.local.md` (gitignored).
|
||||
- **Queue defaults are written with `lpadmin -p <queue> -o key=value`** (into the queue's PPD /
|
||||
printers.conf, for every user) — never `lpoptions`. `~/.cups/lpoptions` is only read, to point out
|
||||
a per-user override.
|
||||
- **Driver filter check** (`DriverFilters.swift`): resolves each `*cupsFilter`/`*cupsFilter2` program
|
||||
(bare names under `/usr/libexec/cups/filter`, skipping `maxsize(n)` and `-`) and reads its Mach-O header
|
||||
directly — any arm64 CPU type counts as native, including subtypes `lipo` can't name. Intel-only →
|
||||
"Driver needs Rosetta"; not found → "Driver filter missing" (shown first).
|
||||
- **PPD options** keep their `*OpenGroup`, UI type and `*ParamCustom` type/range. Custom values are
|
||||
written as `Custom.<value>` and quoted when they contain spaces (unquoted, `lpadmin` silently truncates).
|
||||
- **Quick actions** are vendor-neutral. `QuickActions.swift` defines the actions; what each writes comes
|
||||
@@ -53,10 +57,12 @@ swift build # debug build of everything
|
||||
- Package: tools-version 6.0, Swift 5 language mode, macOS 14 minimum.
|
||||
- `build.sh` reads `CODESIGN_APP_IDENTITY`, `CODESIGN_PKG_IDENTITY`, `NOTARY_PROFILE` (and optional
|
||||
`CODESIGN_TEAM_ID`) from the environment or an untracked `build.env`. Never hard-code identities.
|
||||
- The PKG is payload-free (`pkgbuild --nopayload --scripts`): `pkg/postinstall` installs the CLI to
|
||||
`/usr/local/bin` and the notarized, stapled app to `/Applications`. A payload's "." entry is recorded as
|
||||
root:wheel for its install location, which would reset an existing `/usr/local/bin` (Homebrew) or
|
||||
`/Applications` (root:admin 775). The app is notarized and stapled before packaging; the PKG after.
|
||||
- PKG layout: the app is a payload (`pkgbuild --root` with a staging `Applications/` that is really
|
||||
root:admin 775 and `--ownership preserve`, `BundleIsRelocatable` false), so it gets a receipt and the
|
||||
package records the system's own ownership. `--ownership recommended` would record Applications as
|
||||
root:wheel — don't use it. The CLI is not a payload: the binary ships in Scripts and `pkg/postinstall`
|
||||
copies it, because a `/usr/local/bin` payload entry would reset a Homebrew-owned folder. The build
|
||||
verifies both BOM ownership entries. The app is notarized and stapled before packaging; the PKG after.
|
||||
- The app icon master is `Icon/AppIcon-1024.png`; `build.sh` generates `AppIcon.icns` from it. Don't redraw it.
|
||||
- Live tests are opt-in and write to queues: `CUPSKIT_LIVE_QUEUE=<queue>`, `CUPSKIT_LIVE_JOBS=<a>,<b>`,
|
||||
`CUPSKIT_LIVE_QUICK=<ricoh>,<generic>`. Use throwaway queues (e.g. `lpd://127.0.0.1/…`, paused) and
|
||||
|
||||
22
README.md
22
README.md
@@ -1,19 +1,23 @@
|
||||
# CUPS Admin for macOS
|
||||
|
||||

|
||||
*Jobs: hold, release, move or cancel jobs on any queue.*
|
||||
|
||||

|
||||
*Options: the queue's driver settings as a form, applied with `lpadmin` and read back.*
|
||||
|
||||
**CUPS Admin** is a native macOS app that puts back the CUPS web interface (`http://localhost:631`) Apple removed in macOS 27 — `cupsd`, `lpadmin` and IPP Everywhere queues all still work, only the browser admin page is gone. The sidebar lists every queue with its state and active jobs; select one to see its status, hold, release, move or cancel its jobs, and change its default options the way the old "Set Default Options" page did, including per-driver settings like Ricoh user codes. Common changes (color or black & white, duplex, Letter paper, a user code, the default printer) are one-click Quick Actions, and every change is read back from cupsd so nothing fails silently. It ships with `cupsadmin`, a command-line tool for scripts, Mosyle/Jamf/Munki commands and quick checks. No third-party dependencies; builds with the Xcode Command Line Tools alone.
|
||||
|
||||
## Install
|
||||
|
||||
> Status: the CLI is stable. The app (1.1) covers printers, jobs, queue options and quick actions; printer discovery, classes, the server page and the Attributes/Log tabs are still to come — see [Releases](../../releases).
|
||||
> Status: The CLI and app are both usable today; the app doesn't yet cover every page of the old web interface.
|
||||
|
||||
Download the signed, notarized PKG from the latest [release](../../releases). It installs:
|
||||
|
||||
- `/usr/local/bin/cupsadmin`
|
||||
- `/Applications/CUPS Admin.app`
|
||||
|
||||
The package is payload-free and installs both via a postinstall script, so it never changes the ownership of an existing `/usr/local/bin` (Homebrew on Intel Macs is safe) or of `/Applications`. For Munki, use an `installs` array pointing at `/usr/local/bin/cupsadmin` and `/Applications/CUPS Admin.app`; there is no payload file list to key off.
|
||||
The app is a normal payload install with a receipt (`pkgutil --files edu.wku.cupsadmin`). The CLI is installed by a postinstall script instead, so the package never changes the ownership of an existing `/usr/local/bin` (Homebrew on Intel Macs is safe). For Munki, only the CLI needs an `installs` array entry, pointing at `/usr/local/bin/cupsadmin`; the app is covered by the receipt.
|
||||
|
||||
Requires macOS 14 or later. Universal (Apple silicon and Intel).
|
||||
|
||||
@@ -21,6 +25,7 @@ Requires macOS 14 or later. Universal (Apple silicon and Intel).
|
||||
|
||||
```
|
||||
cupsadmin printers # every queue: state, reasons, accepting, shared, URI
|
||||
cupsadmin printers --rosetta # only queues whose driver filters are Intel-only or missing
|
||||
cupsadmin printer <queue> # one queue in detail (--all for every IPP attribute)
|
||||
cupsadmin jobs [queue] # active jobs (--completed, --all-jobs)
|
||||
cupsadmin cancel <job-id> # cancel one job
|
||||
@@ -60,7 +65,7 @@ Which keywords an action writes comes from a driver profile (`Sources/CupsKit/Re
|
||||
| Ricoh M C251FW PS | ✓ color, black & white, duplex, Letter (no user code) |
|
||||
| Ricoh PCL (e.g. SP 3710DN) | ✓ duplex, Letter (generic) |
|
||||
| Any other PPD, IPP Everywhere / AirPrint | ✓ color, black & white, duplex, Letter where the queue supports them (generic) |
|
||||
| Canon, HP, Xerox, Konica Minolta user/department codes | not yet — contribute a profile |
|
||||
| Canon, HP, Xerox, Konica Minolta user/department codes | no built-in profile — add one (below) |
|
||||
|
||||
### Adding your printer's driver
|
||||
|
||||
@@ -98,16 +103,19 @@ VERSION=1.2.3 ./build.sh
|
||||
|
||||
Or put those three lines (without `export`) in a `build.env` next to `build.sh`; it's read if present and gitignored. Variables already set in the environment win.
|
||||
|
||||
`build.sh` builds a universal binary (per-architecture `swift build` + `lipo`), signs the CLI and app with the hardened runtime, notarizes and staples the app, builds the payload-free PKG, notarizes and staples it, and verifies both with `spctl`. Use `./build.sh --build-only` to skip signing and notarization. `./build.sh --screenshots` regenerates the README screenshot from three temporary demo queues. Run `./test.sh` for the test suite (`CUPSKIT_LIVE_QUEUE=<throwaway queue>` enables the live tests; `CUPSKIT_LIVE_JOBS` and `CUPSKIT_LIVE_QUICK` take two throwaway queues each for the job and quick-action tests).
|
||||
`build.sh` builds a universal binary (per-architecture `swift build` + `lipo`), signs the CLI and app with the hardened runtime, notarizes and staples the app, builds the PKG (app as payload, CLI via postinstall), notarizes and staples it, and verifies both with `spctl`. Building the PKG asks for admin rights once, to give the staged `Applications` folder the system's root:admin ownership. Use `./build.sh --build-only` to skip signing and notarization. `./build.sh --screenshots` regenerates the README screenshot from three temporary demo queues. Run `./test.sh` for the test suite (`CUPSKIT_LIVE_QUEUE=<throwaway queue>` enables the live tests; `CUPSKIT_LIVE_JOBS` and `CUPSKIT_LIVE_QUICK` take two throwaway queues each for the job and quick-action tests).
|
||||
|
||||
## Notes for admins
|
||||
|
||||
- Queue defaults written by `set`, `quick` and the app's Options page go into `/etc/cups/ppd/<queue>.ppd` via `lpadmin`, so they apply to every user on the Mac — the same thing the web UI's "Set Default Options" did. Per-user `~/.cups/lpoptions` overrides still win for that user's own jobs.
|
||||
- PPD files are world-readable. A locked-print password or login password set as a queue default is stored in plain text; the tool warns before doing that. User codes are accounting codes, not secrets.
|
||||
- New queues default to `printer-is-shared=false`. `lpadmin` defaults to shared; this tool doesn't.
|
||||
- Driver filters named in a queue's PPD (`*cupsFilter`, `*cupsFilter2`) are checked for an arm64 slice. Queues whose filters are Intel-only show "Driver needs Rosetta" in the app's header and sidebar tooltip and a `WARNING` line in `cupsadmin printer` and `ppdreport`; filters that don't exist show "Driver filter missing". `cupsadmin printers --rosetta` lists the affected queues, for fleet reporting.
|
||||
|
||||
## License
|
||||
## About
|
||||
|
||||
MIT — see `LICENSE`.
|
||||
Built at Western Kentucky University by Kurt Fattic to replace the CUPS admin pages for a fleet of about 1,000 Macs, and written with Claude. MIT licensed — see `LICENSE`. Not affiliated with Apple or OpenPrinting.
|
||||
|
||||
Built at Western Kentucky University by Kurt Fattic, with Claude. Not affiliated with Apple or OpenPrinting.
|
||||
The Intel-only driver check was inspired by Willem Groenewald's opencups.
|
||||
|
||||
Bug reports and driver profiles for other printers are welcome through [Issues](../../issues) and [Pull Requests](../../pulls).
|
||||
|
||||
@@ -210,7 +210,8 @@ struct SidebarView: View {
|
||||
List(selection: $selection) {
|
||||
Section("Printers") {
|
||||
ForEach(filtered) { printer in
|
||||
PrinterRow(printer: printer, isDefault: store.defaultPrinter == printer.name)
|
||||
PrinterRow(printer: printer, isDefault: store.defaultPrinter == printer.name,
|
||||
driverWarning: store.driverFilters[printer.name]?.headline)
|
||||
.tag(printer.name)
|
||||
.contextMenu { menu(for: printer) }
|
||||
}
|
||||
@@ -311,6 +312,8 @@ struct QuickActionItems: View {
|
||||
struct PrinterRow: View {
|
||||
let printer: PrinterSummary
|
||||
var isDefault = false
|
||||
/// "Driver needs Rosetta" / "Driver filter missing", added to the tooltip.
|
||||
var driverWarning: String?
|
||||
|
||||
var body: some View {
|
||||
HStack(spacing: 8) {
|
||||
@@ -339,7 +342,7 @@ struct PrinterRow: View {
|
||||
}
|
||||
}
|
||||
.badge(printer.jobCount)
|
||||
.help(printer.stateSummary)
|
||||
.help(driverWarning.map { "\(printer.stateSummary) · \($0)" } ?? printer.stateSummary)
|
||||
.accessibilityElement(children: .combine)
|
||||
.accessibilityValue(printer.stateSummary)
|
||||
}
|
||||
|
||||
@@ -37,6 +37,8 @@ enum JobFilter: String, CaseIterable, Identifiable {
|
||||
final class PrinterDetailModel {
|
||||
let queue: String
|
||||
private(set) var printer: IPPGroup?
|
||||
/// Intel-only or missing driver filters, from the queue's PPD.
|
||||
private(set) var driverFilters: DriverFilterReport?
|
||||
private(set) var jobs: [JobSummary] = []
|
||||
private(set) var loadError: String?
|
||||
private(set) var isWorking = false
|
||||
@@ -73,6 +75,11 @@ final class PrinterDetailModel {
|
||||
do {
|
||||
printer = try await store.client.getPrinterAttributes(queue: queue, requested: Self.headerAttributes)
|
||||
loadError = nil
|
||||
if let text = try await store.client.getPPD(queue: queue) {
|
||||
driverFilters = await Task.detached { DriverFilterCheck.check(PPD(text: text)) }.value
|
||||
} else {
|
||||
driverFilters = nil
|
||||
}
|
||||
} catch {
|
||||
loadError = String(describing: error)
|
||||
store.report("ERROR: \(queue): \(error)")
|
||||
|
||||
@@ -12,7 +12,7 @@ struct PrinterDetailView: View {
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
if let printer = model.printer {
|
||||
PrinterHeaderView(printer: printer, ppdPath: model.ppdPath)
|
||||
PrinterHeaderView(printer: printer, ppdPath: model.ppdPath, driverFilters: model.driverFilters)
|
||||
Divider()
|
||||
} else if let error = model.loadError {
|
||||
ContentUnavailableView("Can’t Load \(model.queue)", systemImage: "exclamationmark.triangle",
|
||||
@@ -35,6 +35,7 @@ struct PrinterDetailView: View {
|
||||
struct PrinterHeaderView: View {
|
||||
let printer: IPPGroup
|
||||
let ppdPath: String?
|
||||
let driverFilters: DriverFilterReport?
|
||||
|
||||
private var state: Int? { printer.int("printer-state") }
|
||||
private var accepting: Bool { printer.bool("printer-is-accepting-jobs") ?? true }
|
||||
@@ -64,6 +65,13 @@ struct PrinterHeaderView: View {
|
||||
}
|
||||
LabeledContent("Accepting jobs", value: accepting ? "Yes" : "No")
|
||||
LabeledContent("Shared", value: printer.bool("printer-is-shared") == true ? "Yes" : "No")
|
||||
if let headline = driverFilters?.headline {
|
||||
LabeledContent("Driver") {
|
||||
Label(headline, systemImage: "exclamationmark.triangle.fill")
|
||||
.symbolRenderingMode(.multicolor)
|
||||
}
|
||||
.help(driverFilters?.detail ?? headline)
|
||||
}
|
||||
}
|
||||
}
|
||||
Form {
|
||||
@@ -93,7 +101,7 @@ struct PrinterHeaderView: View {
|
||||
.formStyle(.grouped)
|
||||
.scrollDisabled(true)
|
||||
.textSelection(.enabled)
|
||||
.frame(height: 262)
|
||||
.frame(height: driverFilters?.isFlagged == true ? 300 : 262)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -103,6 +103,8 @@ final class PrinterStore {
|
||||
private(set) var defaultPrinter: String?
|
||||
/// Driver PPD + IPP attributes per queue, for enabling Quick Actions.
|
||||
private(set) var drivers: [String: DriverContext] = [:]
|
||||
/// Filter check per queue (Intel-only or missing filters), from the cached PPDs.
|
||||
private(set) var driverFilters: [String: DriverFilterReport] = [:]
|
||||
var failure: Failure?
|
||||
|
||||
let client = CupsClient()
|
||||
@@ -201,6 +203,11 @@ final class PrinterStore {
|
||||
for printer in printers where drivers[printer.name] == nil {
|
||||
if let context = try? await DriverContext.load(client: client, queue: printer.name) {
|
||||
drivers[printer.name] = context
|
||||
if let ppd = context.ppd {
|
||||
driverFilters[printer.name] = await Task.detached { DriverFilterCheck.check(ppd) }.value
|
||||
} else {
|
||||
driverFilters[printer.name] = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
157
Sources/CupsKit/DriverFilters.swift
Normal file
157
Sources/CupsKit/DriverFilters.swift
Normal file
@@ -0,0 +1,157 @@
|
||||
import Darwin
|
||||
import Foundation
|
||||
|
||||
/// One filter program a PPD names in `*cupsFilter` / `*cupsFilter2`, and whether it can run natively.
|
||||
public struct DriverFilter: Hashable {
|
||||
public enum Status: Hashable {
|
||||
/// Has an arm64 slice (arm64, arm64e or newer subtypes).
|
||||
case native(architectures: [String])
|
||||
/// Intel only: needs Rosetta on Apple silicon.
|
||||
case intelOnly(architectures: [String])
|
||||
/// A script (`#!`); runs wherever its interpreter does.
|
||||
case script(interpreter: String)
|
||||
/// `-`: no program, cupsd passes the data through.
|
||||
case passthrough
|
||||
case missing
|
||||
/// Exists but isn't a Mach-O binary or script this check understands.
|
||||
case unrecognized
|
||||
}
|
||||
|
||||
public let keyword: String
|
||||
/// The line's value, e.g. `application/vnd.cups-postscript 0 /Library/Printers/…/pstopsRV2`.
|
||||
public let line: String
|
||||
public let program: String
|
||||
/// Resolved absolute path; nil for `-`.
|
||||
public let path: String?
|
||||
public let status: Status
|
||||
|
||||
public var name: String { (program as NSString).lastPathComponent }
|
||||
}
|
||||
|
||||
public struct DriverFilterReport: Hashable {
|
||||
public let filters: [DriverFilter]
|
||||
|
||||
public var intelOnly: [DriverFilter] { filters.filter { if case .intelOnly = $0.status { return true } else { return false } } }
|
||||
public var missing: [DriverFilter] { filters.filter { $0.status == .missing } }
|
||||
public var needsRosetta: Bool { !intelOnly.isEmpty }
|
||||
public var hasMissingFilter: Bool { !missing.isEmpty }
|
||||
public var isFlagged: Bool { needsRosetta || hasMissingFilter }
|
||||
|
||||
/// "Driver filter missing" (worse, shown first) or "Driver needs Rosetta"; nil when fine.
|
||||
public var headline: String? {
|
||||
if hasMissingFilter { return "Driver filter missing" }
|
||||
if needsRosetta { return "Driver needs Rosetta" }
|
||||
return nil
|
||||
}
|
||||
|
||||
/// e.g. "pstopsRV2, commandfilterRV1 are Intel-only (x86_64); /Library/…/foo not found".
|
||||
public var detail: String? {
|
||||
var parts: [String] = []
|
||||
if !missing.isEmpty {
|
||||
parts.append(missing.compactMap(\.path).joined(separator: ", ") + " not found")
|
||||
}
|
||||
if !intelOnly.isEmpty {
|
||||
let names = intelOnly.map(\.name)
|
||||
let archs = Set(intelOnly.flatMap { if case .intelOnly(let a) = $0.status { return a } else { return [] } }).sorted()
|
||||
parts.append("\(names.joined(separator: ", ")) \(names.count == 1 ? "is" : "are") Intel-only (\(archs.joined(separator: ", ")))")
|
||||
}
|
||||
return parts.isEmpty ? nil : parts.joined(separator: "; ")
|
||||
}
|
||||
|
||||
/// One line for CLI output: "Driver needs Rosetta — pstopsRV2 is Intel-only (x86_64)".
|
||||
public var warning: String? {
|
||||
guard let headline, let detail else { return nil }
|
||||
return "\(headline) — \(detail)"
|
||||
}
|
||||
}
|
||||
|
||||
public enum DriverFilterCheck {
|
||||
/// Where cupsd looks for filters named without a path.
|
||||
public static let filterDirectory = "/usr/libexec/cups/filter"
|
||||
|
||||
public static func check(_ ppd: PPD, filterDirectory: String = filterDirectory) -> DriverFilterReport {
|
||||
var seen = Set<String>()
|
||||
var filters: [DriverFilter] = []
|
||||
for (keyword, value) in ppd.filterLines {
|
||||
// cupsFilter: "type cost program"; cupsFilter2: "source destination cost [maxsize(n)] program".
|
||||
var fields = value.split(separator: " ", omittingEmptySubsequences: true).map(String.init)
|
||||
let skip = keyword == "cupsFilter2" ? 3 : 2
|
||||
guard fields.count > skip else { continue }
|
||||
fields.removeFirst(skip)
|
||||
if let first = fields.first, first.hasPrefix("maxsize("), first.hasSuffix(")") { fields.removeFirst() }
|
||||
guard !fields.isEmpty else { continue }
|
||||
let program = fields.joined(separator: " ")
|
||||
let path: String? = program == "-" ? nil
|
||||
: program.hasPrefix("/") ? program : (filterDirectory as NSString).appendingPathComponent(program)
|
||||
guard seen.insert(path ?? "-\(keyword)").inserted else { continue }
|
||||
let status: DriverFilter.Status = path.map(Self.status(atPath:)) ?? .passthrough
|
||||
filters.append(DriverFilter(keyword: keyword, line: value, program: program, path: path, status: status))
|
||||
}
|
||||
return DriverFilterReport(filters: filters)
|
||||
}
|
||||
|
||||
/// Reads the file's header: Mach-O (thin or universal) or `#!` script.
|
||||
public static func status(atPath path: String) -> DriverFilter.Status {
|
||||
guard FileManager.default.fileExists(atPath: path) else { return .missing }
|
||||
guard let handle = FileHandle(forReadingAtPath: path) else { return .unrecognized }
|
||||
defer { try? handle.close() }
|
||||
let header = [UInt8](handle.readData(ofLength: 4096))
|
||||
return status(header: header)
|
||||
}
|
||||
|
||||
static func status(header b: [UInt8]) -> DriverFilter.Status {
|
||||
guard b.count >= 8 else { return .unrecognized }
|
||||
if b[0] == UInt8(ascii: "#"), b[1] == UInt8(ascii: "!") {
|
||||
let line = b.prefix { $0 != UInt8(ascii: "\n") }.dropFirst(2)
|
||||
return .script(interpreter: String(decoding: line, as: UTF8.self).trimmingCharacters(in: .whitespaces))
|
||||
}
|
||||
func be32(_ i: Int) -> UInt32 { UInt32(b[i]) << 24 | UInt32(b[i + 1]) << 16 | UInt32(b[i + 2]) << 8 | UInt32(b[i + 3]) }
|
||||
func le32(_ i: Int) -> UInt32 { UInt32(b[i + 3]) << 24 | UInt32(b[i + 2]) << 16 | UInt32(b[i + 1]) << 8 | UInt32(b[i]) }
|
||||
|
||||
var cpuTypes: [(type: UInt32, subtype: UInt32)] = []
|
||||
switch be32(0) {
|
||||
case 0xCAFEBABE, 0xCAFEBABF: // universal (fat32 / fat64)
|
||||
let count = Int(be32(4))
|
||||
let entrySize = be32(0) == 0xCAFEBABF ? 32 : 20
|
||||
guard count > 0, count < 32 else { return .unrecognized } // Java class files share the magic
|
||||
for i in 0 ..< count {
|
||||
let offset = 8 + i * entrySize
|
||||
guard offset + 8 <= b.count else { break }
|
||||
cpuTypes.append((be32(offset), be32(offset + 4) & 0x00FF_FFFF))
|
||||
}
|
||||
default:
|
||||
switch le32(0) {
|
||||
case 0xFEEDFACF, 0xFEEDFACE: // thin Mach-O, little-endian
|
||||
cpuTypes.append((le32(4), le32(8) & 0x00FF_FFFF))
|
||||
default:
|
||||
return .unrecognized
|
||||
}
|
||||
}
|
||||
let names = cpuTypes.map { architectureName(type: $0.type, subtype: $0.subtype) }
|
||||
if cpuTypes.contains(where: { $0.type == 0x0100_000C }) { return .native(architectures: names) }
|
||||
if cpuTypes.contains(where: { $0.type == 0x0100_0007 || $0.type == 7 }) { return .intelOnly(architectures: names) }
|
||||
return .unrecognized
|
||||
}
|
||||
|
||||
static func architectureName(type: UInt32, subtype: UInt32) -> String {
|
||||
switch type {
|
||||
case 0x0100_0007: return "x86_64"
|
||||
case 7: return "i386"
|
||||
case 0x0100_000C: return subtype == 2 ? "arm64e" : "arm64"
|
||||
case 0x0200_000C: return "arm64_32"
|
||||
case 12: return "arm"
|
||||
default: return "cpu\(type)"
|
||||
}
|
||||
}
|
||||
|
||||
/// True on Apple silicon (also when this process itself runs under Rosetta).
|
||||
public static var hostIsAppleSilicon: Bool {
|
||||
var value: Int32 = 0
|
||||
var size = MemoryLayout<Int32>.size
|
||||
return sysctlbyname("hw.optional.arm64", &value, &size, nil, 0) == 0 && value == 1
|
||||
}
|
||||
|
||||
public static var rosettaInstalled: Bool {
|
||||
FileManager.default.fileExists(atPath: "/Library/Apple/usr/libexec/oah/libRosettaRuntime")
|
||||
}
|
||||
}
|
||||
@@ -57,6 +57,8 @@ public struct PPD {
|
||||
public private(set) var groups: [String] = []
|
||||
/// Top-level `*Key: value` attributes (NickName, Manufacturer, ...), first occurrence wins.
|
||||
public private(set) var attributes: [String: String] = [:]
|
||||
/// Every `*cupsFilter` / `*cupsFilter2` line, in order, with the quotes removed.
|
||||
public private(set) var filterLines: [(keyword: String, value: String)] = []
|
||||
|
||||
public init(text: String) {
|
||||
var defaults: [String: String] = [:]
|
||||
@@ -122,6 +124,9 @@ public struct PPD {
|
||||
let (choice, label) = Self.splitText(String(parts[1]))
|
||||
current!.choices.append(choice)
|
||||
current!.choiceList.append(Choice(keyword: choice, text: label ?? choice))
|
||||
} else if parts.count == 1, mainKey == "cupsFilter" || mainKey == "cupsFilter2" {
|
||||
filterLines.append((mainKey, value.trimmingCharacters(in: CharacterSet(charactersIn: "\""))))
|
||||
if attributes[mainKey] == nil { attributes[mainKey] = filterLines.last!.value }
|
||||
} else if parts.count == 1, attributes[mainKey] == nil {
|
||||
attributes[mainKey] = value.trimmingCharacters(in: CharacterSet(charactersIn: "\""))
|
||||
}
|
||||
|
||||
@@ -37,6 +37,22 @@ enum PPDReportCommand {
|
||||
action.isAvailable(in: context) ? action.id : "\(action.id) (unavailable)"
|
||||
}
|
||||
print("Quick: \(quick.joined(separator: ", "))")
|
||||
let filters = DriverFilterCheck.check(ppd)
|
||||
if !filters.filters.isEmpty {
|
||||
print("Filters: " + filters.filters.map { filter -> String in
|
||||
switch filter.status {
|
||||
case .native(let archs): return "\(filter.name) (\(archs.joined(separator: " ")))"
|
||||
case .intelOnly(let archs): return "\(filter.name) (\(archs.joined(separator: " ")) only)"
|
||||
case .script: return "\(filter.name) (script)"
|
||||
case .passthrough: return "- (pass-through)"
|
||||
case .missing: return "\(filter.name) (missing)"
|
||||
case .unrecognized: return "\(filter.name) (unrecognized)"
|
||||
}
|
||||
}.joined(separator: ", "))
|
||||
}
|
||||
if let warning = filters.warning {
|
||||
print("WARNING: \(warning)")
|
||||
}
|
||||
|
||||
for group in ppd.groups {
|
||||
print("\n\(group)")
|
||||
|
||||
@@ -100,8 +100,51 @@ enum PrinterCommand {
|
||||
: label + ":" + String(repeating: " ", count: width - label.count)
|
||||
print("\(heading) \(value)")
|
||||
}
|
||||
if let ppdText = try? await client.getPPD(queue: queue),
|
||||
let warning = DriverFilterCheck.check(PPD(text: ppdText)).warning {
|
||||
print("\nWARNING: \(warning)")
|
||||
}
|
||||
print("\n(use --all for every attribute)")
|
||||
|
||||
return "OK: \(queue) \(Format.printerState(p.int("printer-state"))), reasons \(Format.reasons(p.strings("printer-state-reasons")))"
|
||||
}
|
||||
}
|
||||
|
||||
/// `printers --rosetta`: queues whose PPD filters have no arm64 slice or don't exist.
|
||||
enum RosettaCommand {
|
||||
static func run(client: CupsClient) async throws -> String {
|
||||
let printers = try await client.getPrinters(requested: ["printer-name"])
|
||||
let names = printers.compactMap { $0.string("printer-name") }
|
||||
.sorted { $0.localizedStandardCompare($1) == .orderedAscending }
|
||||
|
||||
var rows: [[String]] = []
|
||||
var affected = 0
|
||||
for name in names {
|
||||
guard let text = try await client.getPPD(queue: name) else { continue }
|
||||
let report = DriverFilterCheck.check(PPD(text: text))
|
||||
guard report.isFlagged else { continue }
|
||||
affected += 1
|
||||
let flagged = report.missing + report.intelOnly
|
||||
for (i, filter) in flagged.enumerated() {
|
||||
let what: String
|
||||
switch filter.status {
|
||||
case .intelOnly(let archs): what = archs.joined(separator: " ")
|
||||
case .missing: what = "missing"
|
||||
default: what = ""
|
||||
}
|
||||
rows.append([i == 0 ? name : "", i == 0 ? (report.headline ?? "") : "", what, filter.path ?? filter.program])
|
||||
}
|
||||
}
|
||||
|
||||
let host = DriverFilterCheck.hostIsAppleSilicon
|
||||
? "Apple silicon, Rosetta \(DriverFilterCheck.rosettaInstalled ? "installed" : "NOT installed")"
|
||||
: "Intel Mac (Intel-only filters run natively here)"
|
||||
if rows.isEmpty {
|
||||
print("No queues need Rosetta or have missing driver filters. This Mac: \(host).")
|
||||
return "OK: none of \(names.count) queues need Rosetta or have missing filters"
|
||||
}
|
||||
printTable(headers: ["QUEUE", "PROBLEM", "ARCH", "FILTER"], rows: rows)
|
||||
print("\nThis Mac: \(host).")
|
||||
return "OK: \(affected) of \(names.count) queues need Rosetta or have missing filters"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,6 +28,7 @@ let usage = """
|
||||
usage: cupsadmin <command> [args]
|
||||
|
||||
printers all queues: state, reasons, accepting, shared, device URI
|
||||
printers --rosetta only queues whose driver filters are Intel-only or missing
|
||||
printer <queue> [--all] one queue in detail (--all dumps every IPP attribute)
|
||||
jobs [queue] [--completed | --all-jobs]
|
||||
active jobs (all queues unless one is given)
|
||||
@@ -80,9 +81,10 @@ func runCommand(_ args: [String]) async throws -> String {
|
||||
return "OK: help"
|
||||
|
||||
case "printers":
|
||||
let rosetta = takeFlag("--rosetta")
|
||||
try rejectUnknownFlags()
|
||||
guard rest.isEmpty else { throw CupsAdminError.usage("printers takes no arguments") }
|
||||
return try await PrintersCommand.run(client: client)
|
||||
return rosetta ? try await RosettaCommand.run(client: client) : try await PrintersCommand.run(client: client)
|
||||
|
||||
case "printer":
|
||||
let dumpAll = takeFlag("--all")
|
||||
|
||||
103
Tests/CupsKitTests/DriverFilterTests.swift
Normal file
103
Tests/CupsKitTests/DriverFilterTests.swift
Normal file
@@ -0,0 +1,103 @@
|
||||
@testable import CupsKit
|
||||
import Foundation
|
||||
import Testing
|
||||
|
||||
private func le32(_ v: UInt32) -> [UInt8] { [UInt8(v & 0xFF), UInt8(v >> 8 & 0xFF), UInt8(v >> 16 & 0xFF), UInt8(v >> 24)] }
|
||||
private func be32(_ v: UInt32) -> [UInt8] { [UInt8(v >> 24), UInt8(v >> 16 & 0xFF), UInt8(v >> 8 & 0xFF), UInt8(v & 0xFF)] }
|
||||
private let x86_64: UInt32 = 0x0100_0007, arm64: UInt32 = 0x0100_000C
|
||||
|
||||
/// Thin 64-bit Mach-O header (little-endian).
|
||||
private func thin(_ cpu: UInt32, subtype: UInt32 = 0) -> [UInt8] {
|
||||
var bytes: [UInt8] = le32(0xFEEDFACF)
|
||||
bytes += le32(cpu)
|
||||
bytes += le32(subtype)
|
||||
bytes += [UInt8](repeating: 0, count: 20)
|
||||
return bytes
|
||||
}
|
||||
|
||||
/// Universal (fat32) header with the given slices.
|
||||
private func fat(_ slices: [(UInt32, UInt32)]) -> [UInt8] {
|
||||
var bytes: [UInt8] = be32(0xCAFEBABE)
|
||||
bytes += be32(UInt32(slices.count))
|
||||
for (cpu, subtype) in slices {
|
||||
bytes += be32(cpu)
|
||||
bytes += be32(subtype)
|
||||
bytes += be32(0x4000) // offset
|
||||
bytes += be32(0x1000) // size
|
||||
bytes += be32(14) // align
|
||||
}
|
||||
return bytes
|
||||
}
|
||||
|
||||
@Suite struct MachOArchitectures {
|
||||
@Test func thinAndUniversalBinaries() {
|
||||
#expect(DriverFilterCheck.status(header: thin(arm64)) == .native(architectures: ["arm64"]))
|
||||
#expect(DriverFilterCheck.status(header: thin(x86_64)) == .intelOnly(architectures: ["x86_64"]))
|
||||
#expect(DriverFilterCheck.status(header: fat([(x86_64, 3), (arm64, 2)])) == .native(architectures: ["x86_64", "arm64e"]))
|
||||
#expect(DriverFilterCheck.status(header: fat([(x86_64, 3), (7, 3)])) == .intelOnly(architectures: ["x86_64", "i386"]))
|
||||
// A newer arm64 subtype lipo can't name (seen on macOS 27's rastertohp) still counts as arm64.
|
||||
#expect(DriverFilterCheck.status(header: fat([(x86_64, 3), (arm64, 12)])) == .native(architectures: ["x86_64", "arm64"]))
|
||||
}
|
||||
|
||||
@Test func scriptsAndOtherFiles() {
|
||||
#expect(DriverFilterCheck.status(header: Array("#!/bin/sh\nexec foo\n".utf8)) == .script(interpreter: "/bin/sh"))
|
||||
#expect(DriverFilterCheck.status(header: Array("%PDF-1.4 not a filter".utf8)) == .unrecognized)
|
||||
#expect(DriverFilterCheck.status(header: [0xCA, 0xFE, 0xBA, 0xBE, 0, 0, 0, 52]) == .unrecognized) // Java class file
|
||||
}
|
||||
|
||||
@Test(.enabled(if: FileManager.default.fileExists(atPath: "/usr/libexec/cups/filter/rastertohp")))
|
||||
func appleFilterIsNative() {
|
||||
guard case .native = DriverFilterCheck.status(atPath: "/usr/libexec/cups/filter/rastertohp") else {
|
||||
Issue.record("rastertohp should have an arm64 slice"); return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Suite struct FilterLines {
|
||||
@Test func resolvesAndClassifiesEveryFilter() throws {
|
||||
let dir = FileManager.default.temporaryDirectory.appendingPathComponent("cupsadmin-filters-\(UUID().uuidString)")
|
||||
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
|
||||
defer { try? FileManager.default.removeItem(at: dir) }
|
||||
try Data(thin(arm64)).write(to: dir.appendingPathComponent("nativefilter"))
|
||||
let intel = dir.appendingPathComponent("Vendor Filters/pstopsvendor")
|
||||
try FileManager.default.createDirectory(at: intel.deletingLastPathComponent(), withIntermediateDirectories: true)
|
||||
try Data(fat([(x86_64, 3)])).write(to: intel)
|
||||
|
||||
let ppd = PPD(text: """
|
||||
*PPD-Adobe: "4.3"
|
||||
*cupsFilter: "application/vnd.cups-raster 50 nativefilter"
|
||||
*cupsFilter: "application/vnd.cups-postscript 0 \(intel.path)"
|
||||
*cupsFilter2: "application/vnd.cups-pdf application/pdf 0 maxsize(0) -"
|
||||
*cupsFilter: "application/vnd.cups-command 0 /Library/Printers/Nobody/Filters/gone"
|
||||
*cupsFilter: "application/vnd.cups-postscript 0 \(intel.path)"
|
||||
""")
|
||||
#expect(ppd.filterLines.count == 5)
|
||||
|
||||
let report = DriverFilterCheck.check(ppd, filterDirectory: dir.path)
|
||||
#expect(report.filters.count == 4) // duplicate pstopsvendor line counted once
|
||||
#expect(report.filters[0].status == .native(architectures: ["arm64"]))
|
||||
#expect(report.filters[0].path == dir.appendingPathComponent("nativefilter").path)
|
||||
#expect(report.filters[1].status == .intelOnly(architectures: ["x86_64"]))
|
||||
#expect(report.filters[2].status == .passthrough)
|
||||
#expect(report.filters[3].status == .missing)
|
||||
|
||||
#expect(report.needsRosetta && report.hasMissingFilter)
|
||||
#expect(report.headline == "Driver filter missing") // missing outranks Rosetta
|
||||
#expect(report.detail == "/Library/Printers/Nobody/Filters/gone not found; pstopsvendor is Intel-only (x86_64)")
|
||||
}
|
||||
|
||||
@Test func rosettaOnlyAndClean() {
|
||||
let passthrough = PPD(text: "*cupsFilter2: \"application/vnd.cups-pdf application/pdf 0 maxsize(0) -\"\n*cupsFilter: \"image/urf 10 -\"\n")
|
||||
let clean = DriverFilterCheck.check(passthrough)
|
||||
#expect(!clean.isFlagged && clean.headline == nil && clean.warning == nil)
|
||||
|
||||
let none = DriverFilterCheck.check(PPD(text: "*NickName: \"No filters\"\n"))
|
||||
#expect(none.filters.isEmpty && !none.isFlagged)
|
||||
}
|
||||
|
||||
@Test(.enabled(if: hasVendorPPD("RICOH IM C4500")))
|
||||
func ricohVendorPPDNamesItsFilters() throws {
|
||||
let report = DriverFilterCheck.check(try #require(vendorPPD("RICOH IM C4500")))
|
||||
#expect(report.filters.map(\.name) == ["commandfilterRV1", "pstopsRV2"] || report.filters.map(\.name) == ["pstopsRV2", "commandfilterRV1"])
|
||||
}
|
||||
}
|
||||
174
build.sh
174
build.sh
@@ -1,10 +1,13 @@
|
||||
#!/bin/bash
|
||||
# Universal release build -> signed CLI + signed, notarized, stapled "CUPS Admin.app" -> signed payload-free PKG
|
||||
# (postinstall installs /usr/local/bin/cupsadmin and /Applications/CUPS Admin.app) -> notarize -> staple -> spctl.
|
||||
# Universal release build -> signed CLI + signed, notarized, stapled "CUPS Admin.app" -> signed PKG
|
||||
# (payload: /Applications/CUPS Admin.app; postinstall: /usr/local/bin/cupsadmin) -> notarize -> staple -> spctl.
|
||||
# The pkg step needs admin rights once (sudo in Terminal, or an administrator password dialog) to make the
|
||||
# staging Applications folder root:admin 775 so the package records the system's real ownership.
|
||||
# Usage: ./build.sh full pipeline (VERSION=1.2.0 ./build.sh to set the version)
|
||||
# ./build.sh --build-only build CLI and app, ad-hoc signed; no identities, no pkg, no notarization
|
||||
# ./build.sh --screenshots build like --build-only, then regenerate docs/screenshots/app-jobs.png
|
||||
# (creates three demo queues on 127.0.0.1 with held jobs, deletes them after)
|
||||
# ./build.sh --screenshots build like --build-only, then regenerate docs/screenshots/app-jobs.png and
|
||||
# app-options.png (creates four demo queues on 127.0.0.1 — one on Ricoh's
|
||||
# IM C4500 PPD — with held jobs, and deletes them after)
|
||||
#
|
||||
# Signing settings come from the environment, or from an untracked build.env next to this script
|
||||
# (plain KEY=value lines; a variable already set in the environment wins):
|
||||
@@ -43,8 +46,10 @@ step() { STATUS="ERROR: failed at: $1"; echo; echo "==> $1"; }
|
||||
|
||||
# --- screenshots (--screenshots) ------------------------------------------------
|
||||
# Demo queues with generic names so the README never shows real queue names or users.
|
||||
DEMO_QUEUES="Front_Office Library_Color Lab_Mono"
|
||||
SHOT="docs/screenshots/app-jobs.png"
|
||||
DEMO_QUEUES="Copy_Room Front_Office Library_Color Lab_Mono"
|
||||
SHOT_JOBS="docs/screenshots/app-jobs.png"
|
||||
SHOT_OPTIONS="docs/screenshots/app-options.png"
|
||||
RICOH_DEMO_PPD="/Library/Printers/PPDs/Contents/Resources/RICOH IM C4500"
|
||||
APP_DOMAIN="edu.wku.cupsadmin.app"
|
||||
SAVED_PREFS=""
|
||||
|
||||
@@ -60,21 +65,57 @@ cleanup_screenshots() {
|
||||
fi
|
||||
}
|
||||
|
||||
# capture_app <queue> <tab> <file>: launch the app on one queue and tab, capture its window.
|
||||
capture_app() {
|
||||
local queue="$1" tab="$2" file="$3" window="" finder
|
||||
osascript -e 'quit app "CUPS Admin"' >/dev/null 2>&1 || true
|
||||
for _ in 1 2 3 4 5; do pgrep -f "CUPS Admin.app/Contents/MacOS" >/dev/null || break; sleep 1; done
|
||||
defaults write "$APP_DOMAIN" selectedQueue "$queue"
|
||||
defaults write "$APP_DOMAIN" detailTab "$tab"
|
||||
defaults write "$APP_DOMAIN" "NSWindow Frame main" "120 120 1400 860 $SCREEN "
|
||||
open "$APP" --args --only-queues "${DEMO_QUEUES// /,}"
|
||||
|
||||
finder=$(mktemp -t cupsadmin-window).swift
|
||||
cat > "$finder" <<'SWIFT'
|
||||
import CoreGraphics
|
||||
let windows = CGWindowListCopyWindowInfo([.optionOnScreenOnly, .excludeDesktopElements], kCGNullWindowID) as? [[String: Any]] ?? []
|
||||
if let w = windows.first(where: { ($0[kCGWindowOwnerName as String] as? String) == "CUPS Admin" && ($0[kCGWindowLayer as String] as? Int) == 0 }),
|
||||
let id = w[kCGWindowNumber as String] as? Int { print(id) }
|
||||
SWIFT
|
||||
for _ in $(seq 1 30); do window=$(swift "$finder" 2>/dev/null || true); [ -n "$window" ] && break; sleep 1; done
|
||||
rm -f "$finder"
|
||||
[ -n "$window" ] || { STATUS="ERROR: CUPS Admin window didn't appear on this Space"; exit 1; }
|
||||
sleep 3 # let the sidebar, header and tab content load
|
||||
# Capture it as the active window (colored traffic lights, accent-colored selection).
|
||||
osascript -e "tell application id \"$APP_DOMAIN\" to activate" >/dev/null 2>&1 || true
|
||||
open "$APP"
|
||||
sleep 2
|
||||
mkdir -p "$(dirname "$file")"
|
||||
screencapture -x -o -l "$window" "$file" \
|
||||
|| { STATUS="ERROR: screencapture failed (Terminal needs Screen Recording permission)"; exit 1; }
|
||||
echo "captured $file ($(sips -g pixelWidth -g pixelHeight "$file" | awk '/pixel/ {print $2}' | paste -sd x -))"
|
||||
}
|
||||
|
||||
take_screenshots() {
|
||||
step "screenshots"
|
||||
[ "$(defaults read -g AppleInterfaceStyle 2>/dev/null)" != "Dark" ] \
|
||||
|| { STATUS="ERROR: switch macOS to Light appearance first (the README screenshot is light mode)"; exit 1; }
|
||||
|| { STATUS="ERROR: switch macOS to Light appearance first (the README screenshots are light mode)"; exit 1; }
|
||||
[ -f "$RICOH_DEMO_PPD" ] \
|
||||
|| { STATUS="ERROR: the Options screenshot needs Ricoh's driver ($RICOH_DEMO_PPD not found)"; exit 1; }
|
||||
cleanup_screenshots
|
||||
|
||||
# Save the user's app settings (window frame, selection, tab); restored in cleanup.
|
||||
SAVED_PREFS=$(mktemp -t cupsadmin-prefs).plist
|
||||
defaults export "$APP_DOMAIN" "$SAVED_PREFS" 2>/dev/null || defaults export "$APP_DOMAIN" - >/dev/null 2>&1 || true
|
||||
defaults export "$APP_DOMAIN" "$SAVED_PREFS" 2>/dev/null || true
|
||||
[ -s "$SAVED_PREFS" ] || printf '{}' | plutil -convert xml1 -o "$SAVED_PREFS" -
|
||||
|
||||
for queue in $DEMO_QUEUES; do
|
||||
for queue in Front_Office Library_Color Lab_Mono; do
|
||||
lpadmin -p "$queue" -v "lpd://127.0.0.1/$queue" -m drv:///sample.drv/generic.ppd \
|
||||
-D "${queue//_/ }" -L "Building A" -o printer-is-shared=false -E 2>&1 | grep -v deprecated || true
|
||||
done
|
||||
# A Ricoh queue for the Options tab, set to Letter + fit to nearest size (what a US site uses).
|
||||
lpadmin -p Copy_Room -v lpd://127.0.0.1/Copy_Room -P "$RICOH_DEMO_PPD" -D "Copy Room" -L "Building A" \
|
||||
-o printer-is-shared=false -o PageSize=Letter -o RIPaperPolicy=NearestSizeAdjust -E 2>&1 | grep -v deprecated || true
|
||||
# Held jobs never leave the Mac; owners are generic names, not the person running the build.
|
||||
lp -d Front_Office -U alex -H hold -t "Quarterly budget.pdf" /etc/hosts >/dev/null
|
||||
lp -d Front_Office -U jordan -H hold -t "Staff meeting agenda" /etc/hosts >/dev/null
|
||||
@@ -83,37 +124,13 @@ take_screenshots() {
|
||||
lp -d Library_Color -U jordan -H hold -t "Event poster" /etc/hosts >/dev/null
|
||||
|
||||
SCREEN=$(osascript -e 'tell application "Finder" to get bounds of window of desktop' | tr -d ' ' | tr ',' ' ')
|
||||
defaults write "$APP_DOMAIN" selectedQueue Front_Office
|
||||
defaults write "$APP_DOMAIN" detailTab jobs
|
||||
defaults write "$APP_DOMAIN" "NSWindow Frame main" "120 120 1400 860 $SCREEN "
|
||||
open "$APP" --args --only-queues "${DEMO_QUEUES// /,}"
|
||||
|
||||
FINDER=$(mktemp -t cupsadmin-window).swift
|
||||
cat > "$FINDER" <<'SWIFT'
|
||||
import CoreGraphics
|
||||
let windows = CGWindowListCopyWindowInfo([.optionOnScreenOnly, .excludeDesktopElements], kCGNullWindowID) as? [[String: Any]] ?? []
|
||||
if let w = windows.first(where: { ($0[kCGWindowOwnerName as String] as? String) == "CUPS Admin" && ($0[kCGWindowLayer as String] as? Int) == 0 }),
|
||||
let id = w[kCGWindowNumber as String] as? Int { print(id) }
|
||||
SWIFT
|
||||
WINDOW=""
|
||||
for _ in $(seq 1 30); do WINDOW=$(swift "$FINDER" 2>/dev/null || true); [ -n "$WINDOW" ] && break; sleep 1; done
|
||||
rm -f "$FINDER"
|
||||
[ -n "$WINDOW" ] || { STATUS="ERROR: CUPS Admin window didn't appear on this Space"; exit 1; }
|
||||
sleep 3 # let the sidebar, header and jobs load
|
||||
# Capture it as the active window (colored traffic lights, accent-colored selection).
|
||||
osascript -e "tell application id \"$APP_DOMAIN\" to activate" >/dev/null 2>&1 || true
|
||||
open "$APP"
|
||||
sleep 2
|
||||
mkdir -p "$(dirname "$SHOT")"
|
||||
screencapture -x -o -l "$WINDOW" "$SHOT" \
|
||||
|| { STATUS="ERROR: screencapture failed (Terminal needs Screen Recording permission)"; exit 1; }
|
||||
SHOT_SIZE="$(sips -g pixelWidth -g pixelHeight "$SHOT" | awk '/pixel/ {print $2}' | paste -sd x -)"
|
||||
echo "captured $SHOT ($SHOT_SIZE)"
|
||||
capture_app Front_Office jobs "$SHOT_JOBS"
|
||||
capture_app Copy_Room options "$SHOT_OPTIONS"
|
||||
}
|
||||
|
||||
# --- configuration -------------------------------------------------------------
|
||||
cd "$(dirname "$0")"
|
||||
VERSION="${VERSION:-1.1.0}"
|
||||
VERSION="${VERSION:-1.1.1}"
|
||||
IDENTIFIER="edu.wku.cupsadmin"
|
||||
|
||||
# build.env fills in only what the environment doesn't already set.
|
||||
@@ -259,7 +276,7 @@ echo "app architectures: $(lipo -archs "$APP/Contents/MacOS/$APP_EXECUTABLE")"
|
||||
|
||||
if [ $SCREENSHOTS -eq 1 ]; then
|
||||
take_screenshots
|
||||
STATUS="OK: regenerated $SHOT (${SHOT_SIZE})"
|
||||
STATUS="OK: regenerated $SHOT_JOBS and $SHOT_OPTIONS"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
@@ -306,42 +323,83 @@ xcrun stapler validate "$APP"
|
||||
spctl_check execute "$APP" "$DIST/spctl-app.txt"
|
||||
|
||||
# --- build + sign pkg -----------------------------------------------------------
|
||||
# Payload-free for the app too: an /Applications payload's "." entry is recorded as root:wheel, but
|
||||
# /Applications is root:admin 775 — installing it could take away admins' drag-install rights.
|
||||
# pkg/postinstall copies both the CLI and the stapled app instead.
|
||||
# App: a normal payload with a receipt. The staging root mirrors the system — "/" root:wheel 755,
|
||||
# Applications root:admin 775, the app root:wheel — and pkgbuild --ownership preserve records exactly
|
||||
# that, so installing never changes /Applications' ownership. (--ownership recommended would record
|
||||
# Applications as root:wheel.) Making files root-owned needs admin rights, once per build.
|
||||
# CLI: stays payload-free — the binary rides in Scripts and pkg/postinstall copies it, because a
|
||||
# /usr/local/bin payload entry would reset an existing Homebrew-owned /usr/local/bin.
|
||||
|
||||
# as_root "<command>": sudo when there's a terminal (or cached credentials), else the standard
|
||||
# administrator password dialog. Never stores a password.
|
||||
as_root() {
|
||||
if sudo -n true 2>/dev/null || [ -t 0 ]; then
|
||||
sudo /bin/sh -c "$1"
|
||||
else
|
||||
local escaped="${1//\\/\\\\}"
|
||||
escaped="${escaped//\"/\\\"}"
|
||||
osascript -e "do shell script \"$escaped\" with administrator privileges" >/dev/null
|
||||
fi
|
||||
}
|
||||
|
||||
step "build and sign pkg"
|
||||
rm -f "$PKG"
|
||||
rm -rf "$SCRIPTS/CUPS Admin.app"
|
||||
cp pkg/postinstall "$SCRIPTS/postinstall"
|
||||
chmod 755 "$SCRIPTS/postinstall"
|
||||
rm -rf "$SCRIPTS/CUPS Admin.app"
|
||||
ditto "$APP" "$SCRIPTS/CUPS Admin.app"
|
||||
pkgbuild --nopayload --scripts "$SCRIPTS" --identifier "$IDENTIFIER" --version "$VERSION" \
|
||||
|
||||
PKGROOT="$PWD/$DIST/pkgroot-$$"
|
||||
mkdir -p "$PKGROOT/Applications"
|
||||
ditto "$APP" "$PKGROOT/Applications/CUPS Admin.app"
|
||||
echo "setting staging ownership (admin rights needed once)"
|
||||
# Also removes root-owned staging folders left by earlier builds.
|
||||
as_root "find '$PWD/$DIST' -maxdepth 1 -name 'pkgroot-*' ! -name 'pkgroot-$$' -exec rm -rf {} + ; \
|
||||
chown root:wheel '$PKGROOT' && chmod 755 '$PKGROOT' && \
|
||||
chown root:admin '$PKGROOT/Applications' && chmod 775 '$PKGROOT/Applications' && \
|
||||
chown -R root:wheel '$PKGROOT/Applications/CUPS Admin.app' && chmod -R go-w '$PKGROOT/Applications/CUPS Admin.app'" \
|
||||
|| { STATUS="ERROR: couldn't set staging ownership (admin rights are needed for the app payload)"; exit 1; }
|
||||
|
||||
COMPONENTS="$DIST/components.plist"
|
||||
pkgbuild --analyze --root "$PKGROOT" "$COMPONENTS" >/dev/null
|
||||
# Install exactly at /Applications/CUPS Admin.app, never "relocated" to another copy LaunchServices knows about.
|
||||
plutil -replace 0.BundleIsRelocatable -bool NO "$COMPONENTS"
|
||||
plutil -replace 0.BundleOverwriteAction -string upgrade "$COMPONENTS"
|
||||
pkgbuild --root "$PKGROOT" --install-location / --ownership preserve --component-plist "$COMPONENTS" \
|
||||
--scripts "$SCRIPTS" --identifier "$IDENTIFIER" --version "$VERSION" \
|
||||
--sign "$INSTALLER_SIGN_ID" --timestamp "$PKG"
|
||||
pkgutil --check-signature "$PKG"
|
||||
|
||||
step "verify pkg contents"
|
||||
echo "pkgutil --payload-files $PKG:"
|
||||
PAYLOAD_FILES=$(pkgutil --payload-files "$PKG" 2>&1 || true)
|
||||
echo "${PAYLOAD_FILES:-(no output)}"
|
||||
if [ -n "$(printf '%s' "$PAYLOAD_FILES" | grep -v -i 'no payload' || true)" ]; then
|
||||
STATUS="ERROR: pkg has payload entries; expected none"
|
||||
exit 1
|
||||
PAYLOAD_FILES=$(pkgutil --payload-files "$PKG")
|
||||
echo "payload: $(echo "$PAYLOAD_FILES" | wc -l | tr -d ' ') entries, top level:"
|
||||
echo "$PAYLOAD_FILES" | awk -F/ 'NF <= 3' | sed 's/^/ /'
|
||||
if echo "$PAYLOAD_FILES" | grep -v -E '^\.$|^\./Applications$|^\./Applications/CUPS Admin\.app(/|$)' | grep -q .; then
|
||||
STATUS="ERROR: payload contains something other than /Applications/CUPS Admin.app"; exit 1
|
||||
fi
|
||||
EXPANDED="$DIST/expanded"
|
||||
rm -rf "$EXPANDED"
|
||||
pkgutil --expand "$PKG" "$EXPANDED"
|
||||
# pkgutil --expand unpacks the Scripts archive into a directory.
|
||||
BOM_ROOT=$(lsbom "$EXPANDED/Bom" | awk -F'\t' '$1=="."{print $2, $3}')
|
||||
BOM_APPS=$(lsbom "$EXPANDED/Bom" | awk -F'\t' '$1=="./Applications"{print $2, $3}')
|
||||
BOM_APP=$(lsbom "$EXPANDED/Bom" | awk -F'\t' '$1=="./Applications/CUPS Admin.app"{print $2, $3}')
|
||||
echo "BOM: / $BOM_ROOT · /Applications $BOM_APPS · CUPS Admin.app $BOM_APP"
|
||||
[ "$BOM_ROOT" = "40755 0/0" ] && [ "$BOM_APPS" = "40775 0/80" ] && [ "$BOM_APP" = "40755 0/0" ] \
|
||||
|| { STATUS="ERROR: pkg ownership doesn't match the system (expected / 40755 0/0, /Applications 40775 0/80, app 40755 0/0)"; exit 1; }
|
||||
echo "Scripts: $(ls "$EXPANDED/Scripts" | tr '\n' ' ')"
|
||||
[ -x "$EXPANDED/Scripts/postinstall" ] && [ -f "$EXPANDED/Scripts/cupsadmin" ] && [ -d "$EXPANDED/Scripts/CUPS Admin.app" ] \
|
||||
|| { STATUS="ERROR: Scripts missing postinstall, cupsadmin or CUPS Admin.app"; exit 1; }
|
||||
[ -x "$EXPANDED/Scripts/postinstall" ] && [ -f "$EXPANDED/Scripts/cupsadmin" ] && [ ! -e "$EXPANDED/Scripts/CUPS Admin.app" ] \
|
||||
|| { STATUS="ERROR: Scripts should hold only postinstall and cupsadmin"; exit 1; }
|
||||
codesign --verify --strict "$EXPANDED/Scripts/cupsadmin" \
|
||||
|| { STATUS="ERROR: binary inside pkg Scripts lost its signature"; exit 1; }
|
||||
codesign --verify --deep --strict "$EXPANDED/Scripts/CUPS Admin.app" \
|
||||
|| { STATUS="ERROR: app inside pkg Scripts lost its signature"; exit 1; }
|
||||
xcrun stapler validate "$EXPANDED/Scripts/CUPS Admin.app" >/dev/null \
|
||||
|| { STATUS="ERROR: app inside pkg Scripts lost its stapled ticket"; exit 1; }
|
||||
echo "inside pkg: cupsadmin signed ($(lipo -archs "$EXPANDED/Scripts/cupsadmin")), CUPS Admin.app signed and stapled"
|
||||
rm -rf "$EXPANDED"
|
||||
FULL="$DIST/expanded-full"
|
||||
rm -rf "$FULL"
|
||||
pkgutil --expand-full "$PKG" "$FULL"
|
||||
codesign --verify --deep --strict "$FULL/Payload/Applications/CUPS Admin.app" \
|
||||
|| { STATUS="ERROR: app in the payload lost its signature"; exit 1; }
|
||||
xcrun stapler validate "$FULL/Payload/Applications/CUPS Admin.app" >/dev/null \
|
||||
|| { STATUS="ERROR: app in the payload lost its stapled ticket"; exit 1; }
|
||||
echo "inside pkg: CUPS Admin.app signed and stapled (payload), cupsadmin signed (Scripts)"
|
||||
rm -rf "$FULL"
|
||||
|
||||
# --- notarize + staple pkg ------------------------------------------------------
|
||||
step "notarize pkg (uploads to Apple and waits)"
|
||||
@@ -357,4 +415,4 @@ spctl_check execute "$APP" "$DIST/spctl-app.txt"
|
||||
|
||||
echo
|
||||
echo "install: sudo installer -pkg $PKG -target /"
|
||||
STATUS="OK: $PKG (CLI + CUPS Admin.app) signed, app and pkg notarized, stapled, spctl accepted"
|
||||
STATUS="OK: $PKG (app payload + CLI postinstall) signed, app and pkg notarized, stapled, spctl accepted"
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 143 KiB After Width: | Height: | Size: 147 KiB |
BIN
docs/screenshots/app-options.png
Normal file
BIN
docs/screenshots/app-options.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 133 KiB |
@@ -1,32 +1,18 @@
|
||||
#!/bin/bash
|
||||
# cupsadmin postinstall (payload-free pkg): the CLI binary and CUPS Admin.app ship in the Scripts
|
||||
# archive next to this file. Never changes ownership/permissions of an existing /usr/local/bin
|
||||
# (Homebrew on Intel owns it) or of /Applications (root:admin 775).
|
||||
# cupsadmin postinstall: installs the CLI. The binary ships in the Scripts archive next to this file
|
||||
# (not in the payload), so the package never changes ownership/permissions of an existing
|
||||
# /usr/local/bin (Homebrew on Intel owns it). CUPS Admin.app is a normal payload with a receipt.
|
||||
set -euo pipefail
|
||||
|
||||
TARGET="${3:-/}"
|
||||
HERE="$(cd "$(dirname "$0")" && pwd)"
|
||||
|
||||
# --- CLI -------------------------------------------------------------------------
|
||||
DEST_DIR="${TARGET%/}/usr/local/bin"
|
||||
|
||||
if [ ! -d "$DEST_DIR" ]; then
|
||||
mkdir -p -m 755 "$DEST_DIR"
|
||||
echo "cupsadmin: created $DEST_DIR"
|
||||
fi
|
||||
|
||||
# -S: copy to a temp file and rename, so a running cupsadmin is never half-written.
|
||||
install -S -m 755 -o root -g wheel "$HERE/cupsadmin" "$DEST_DIR/cupsadmin"
|
||||
echo "cupsadmin: installed $DEST_DIR/cupsadmin"
|
||||
|
||||
# --- app -------------------------------------------------------------------------
|
||||
if [ -d "$HERE/CUPS Admin.app" ]; then
|
||||
APPS="${TARGET%/}/Applications"
|
||||
STAGE="$APPS/.CUPS Admin.app.installing"
|
||||
rm -rf "$STAGE"
|
||||
ditto "$HERE/CUPS Admin.app" "$STAGE"
|
||||
chown -R root:wheel "$STAGE"
|
||||
chmod -R go-w "$STAGE"
|
||||
# Swap in place so a half-copied bundle is never at the real path.
|
||||
rm -rf "$APPS/CUPS Admin.app"
|
||||
mv "$STAGE" "$APPS/CUPS Admin.app"
|
||||
echo "cupsadmin: installed $APPS/CUPS Admin.app"
|
||||
fi
|
||||
|
||||
Reference in New Issue
Block a user