ipp

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 26, 2026 License: MIT Imports: 36 Imported by: 0

Documentation

Overview

Package ipp reads and writes the messages of the Internet Printing Protocol (RFC 8010) and speaks it to printers (RFC 8011, PWG 5100.12: IPP/2.x). It is what bdf print and the print server talk to a printer, to a CUPS queue, and to each other with.

A Message is a request or a response: a version, an operation or a status, a request id, and groups of attributes, each attribute a name with one or more values. Encode writes one and Decode reads one from the start of a body, leaving a document that follows it unread.

A message from the network is as untrusted as any other input: Decode is bounded by Limits and refuses what passes them.

Index

Constants

View Source
const (
	UnitsDPI  uint8 = 3
	UnitsDPCM uint8 = 4
)

Units of a Resolution.

Variables

View Source
var (
	// ErrAuth is returned when the printer wants a user and password the
	// client does not have, or refuses the ones it has.
	ErrAuth = errors.New("ipp: the printer asks for authentication")
	// ErrProtocol is returned when the answer is not an IPP message.
	ErrProtocol = errors.New("ipp: the answer is not an IPP message")
)

Errors of talking to a printer.

View Source
var (
	Version11 = Version{1, 1}
	Version20 = Version{2, 0}
)

Versions of the protocol.

View Source
var DefaultLimits = Limits{MaxBytes: 4 << 20, MaxAttributes: 10000, MaxValueBytes: 64 << 10, MaxValues: 1000, MaxDepth: 8}

DefaultLimits are the limits of Decode when none are given: 4 MiB, 10,000 attributes, 64 KiB a value, 1,000 values an attribute, and collections 8 deep.

View Source
var ErrCertificateChanged = errors.New("ipp: the certificate of the printer changed since it was recorded")

ErrCertificateChanged is returned when a host's certificate is not the one the store recorded.

View Source
var ErrEncode = errors.New("ipp: the message cannot be encoded")

ErrEncode is wrapped by the errors of encoding a message that the encoding cannot carry.

View Source
var ErrLimit = errors.New("ipp: the message passes a limit")

ErrLimit is wrapped by the error of a message that passes a limit.

View Source
var ErrMalformed = errors.New("ipp: malformed message")

ErrMalformed is wrapped by the error of a message that is not an IPP message.

View Source
var IconSizes = []int{48, 128, 512}

IconSizes are the sizes of printer-icons: small, large, and the one AirPrint shows.

View Source
var JobTemplateAttrs = []string{
	"copies", "finishings", "ipp-attribute-fidelity", "job-account-id", "job-accounting-user-id", "job-hold-until", "job-name",
	"job-priority", "media", "media-col",
	"multiple-document-handling", "number-up", "orientation-requested", "output-bin", "overrides", "page-ranges",
	"print-color-mode", "print-content-optimize", "print-quality", "print-rendering-intent", "print-scaling",
	"printer-resolution", "sides",
}

JobTemplateAttrs are the job template attributes of a request that makes a job (RFC 8011 §5.2, with those of IPP Everywhere): what "job-template" stands for in requested-attributes, and what a printer lists in job-creation-attributes-supported.

View Source
var PrinterAttributes = []string{
	"printer-uri-supported", "uri-authentication-supported", "uri-security-supported",
	"printer-name", "printer-info", "printer-make-and-model", "printer-location", "printer-uuid", "printer-device-id",
	"printer-state", "printer-state-reasons", "printer-state-message", "printer-is-accepting-jobs",
	"ipp-versions-supported", "operations-supported", "printer-config-change-time",
	"document-format-supported", "document-format-default", "pdf-versions-supported",
	"media-supported", "media-ready", "media-default", "media-source-supported", "media-type-supported", "media-col-supported",
	"sides-supported", "sides-default", "print-color-mode-supported", "print-color-mode-default",
	"print-quality-supported", "print-quality-default", "printer-resolution-supported", "printer-resolution-default",
	"copies-supported", "copies-default", "page-ranges-supported", "print-scaling-supported", "print-scaling-default",
	"number-up-supported", "orientation-requested-supported", "multiple-document-handling-supported",
	"finishings-supported", "finishings-default", "output-bin-supported", "output-bin-default",
	"pwg-raster-document-resolution-supported", "pwg-raster-document-type-supported", "pwg-raster-document-sheet-back",
	"urf-supported", "pclm-strip-height-preferred", "pclm-raster-back-side", "pclm-source-resolution-supported",
	"pclm-compression-method-preferred",
	"job-password-supported", "job-password-encryption-supported", "job-account-id-supported", "job-accounting-user-id-supported",
	"identify-actions-supported", "job-creation-attributes-supported",
}

PrinterAttributes are the attributes GetPrinterAttributes asks for when given none: what Printer reads. media-col-database is not among them (it is large on some printers); ask for it by name.

Functions

func DefaultTrustPath

func DefaultTrustPath() (string, error)

DefaultTrustPath returns the file of the user's store.

func Fingerprint

func Fingerprint(c *x509.Certificate) string

Fingerprint returns "sha256:" and the hex of the SHA-256 of the certificate.

func IsStatus

func IsStatus(err error, st Status) bool

IsStatus reports whether err is a StatusError of the status.

func ParseURL

func ParseURL(s string) (httpURL, printerURI string, err error)

ParseURL turns a printer URL into the URL requests go to, and the printer-uri the requests name. ipp and http become http on port 631 unless a port is given; ipps and https become https.

func PrinterGroups

func PrinterGroups(attrs []Attribute) map[string][]string

PrinterGroups are the groups of a printer's attributes that requested-attributes names: "job-template" the -default, -supported, -ready and -database of the job template attributes, and "printer-description" the others.

func Requested

func Requested(op *Group, def []string) []string

Requested is the requested-attributes of the operation group of a request, or def without it.

func ServeIcon

func ServeIcon(w http.ResponseWriter, r *http.Request, file string)

ServeIcon serves the icon file names ("128.png"), one of IconSizes.

Types

type Advertisement struct {
	// Instance is the instance's name, a label of 63 bytes at most
	// ("Office @ server"); a name another host has is renamed "Office @
	// server (2)" and so on.
	Instance string
	Type     string
	Subtypes []string
	Port     int
	// TXT are the keys and values of the TXT record, "key=value" each.
	TXT []string
}

Advertisement is a service to advertise with DNS-SD: an instance of a type ("_ipp._tcp"), with subtypes ("_print", "_universal"), on a port of this machine, with its TXT record.

type Attribute

type Attribute struct {
	Name   string
	Values []Value
}

Attribute is a named value, or several (a 1setOf).

func Attr

func Attr(name string, values ...Value) Attribute

Attr makes an attribute.

func Filter

func Filter(attrs []Attribute, req []string, groups map[string][]string) []Attribute

Filter keeps the attributes requested: by name, or by the names of groups ("all", "job-template" …) that groups maps to the names in them.

func Get

func Get(members []Attribute, name string) *Attribute

Get returns the first attribute of the name among members of a collection, or nil.

func (*Attribute) Bool

func (a *Attribute) Bool() (b, ok bool)

Bool returns the first boolean value.

func (*Attribute) Collections

func (a *Attribute) Collections() [][]Attribute

Collections returns the collection values of the attribute.

func (*Attribute) First

func (a *Attribute) First() (v Value, ok bool)

First returns the first value of the attribute. The attribute may be nil: ok is then false.

func (*Attribute) Has

func (a *Attribute) Has(s string) bool

Has reports whether a character-string value of the attribute is s.

func (*Attribute) Int

func (a *Attribute) Int() (n int32, ok bool)

Int returns the first integer, enum or boolean value.

func (*Attribute) Ints

func (a *Attribute) Ints() []int32

Ints returns the integer, enum and boolean values of the attribute.

func (*Attribute) OutOfBand

func (a *Attribute) OutOfBand() Tag

OutOfBand returns the tag of an out-of-band first value (unsupported, unknown, no-value …), or 0.

func (*Attribute) Ranges

func (a *Attribute) Ranges() []Range

Ranges returns the rangeOfInteger values of the attribute.

func (*Attribute) Resolutions

func (a *Attribute) Resolutions() []Resolution

Resolutions returns the resolution values of the attribute.

func (Attribute) String

func (a Attribute) String() string

String renders the values of the attribute, separated by commas.

func (*Attribute) Strings

func (a *Attribute) Strings() []string

Strings returns the character-string values of the attribute (keywords, names, texts, URIs …), skipping the others. The attribute may be nil.

func (*Attribute) Text

func (a *Attribute) Text() string

Text returns the first character-string value, or "".

type Client

type Client struct {
	// URL is the printer's: ipp://host[:631]/ipp/print, ipps://… for
	// TLS, or the http:// and https:// forms of the same. A CUPS queue is
	// ipp://localhost:631/printers/<name>.
	URL string
	// HTTP sends the requests. nil uses a client with a dialing timeout
	// and the TLS configuration of TLS.
	HTTP *http.Client
	// TLS verifies the certificate of an ipps printer. nil verifies with
	// the roots of the system.
	TLS TLSPolicy
	// User is the requesting-user-name of the requests: the user of the
	// process when "".
	User string
	// Language is the attributes-natural-language: "en" when "".
	Language string
	// Username and Password answer a printer that asks for Basic
	// authentication.
	Username, Password string
	// Limits bound the decoding of responses: DefaultLimits when nil.
	Limits *Limits
	// Version is the version requests name: 2.0 when zero. A printer
	// that answers server-error-version-not-supported is asked again with
	// 1.1, once.
	Version Version
	// Timeout bounds a request that sends no document: 30 seconds when
	// zero. A request that sends a document is bounded by its context
	// alone.
	Timeout time.Duration
	// contains filtered or unexported fields
}

Client speaks IPP to one printer, or to one queue of a CUPS server, at a URL. Its zero value is not usable: set URL. The other fields are optional.

func (*Client) CancelJob

func (c *Client) CancelJob(ctx context.Context, jobID int32) error

CancelJob cancels a job.

func (*Client) CreateJob

func (c *Client) CreateJob(ctx context.Context, name string, job []Attribute) (*JobStatus, error)

CreateJob creates a job of the attributes, to send documents to.

func (*Client) CupsGetPrinters

func (c *Client) CupsGetPrinters(ctx context.Context) ([]CupsPrinter, error)

CupsGetPrinters lists the queues of a CUPS server. The client's URL is the server's (ipp://localhost:631/).

func (*Client) Do

func (c *Client) Do(ctx context.Context, m *Message, doc io.Reader) (*Message, error)

Do sends a request, with the document that follows it in the body when doc is not nil, and returns the response. A response whose status is not a success is returned with a StatusError. The document is streamed: the request body is chunked and waits for the printer's 100 Continue before it is sent, so a refused request sends none of it.

func (*Client) DoStream

func (c *Client) DoStream(ctx context.Context, m *Message) (*Message, io.ReadCloser, error)

DoStream sends a request and returns the response with what follows it in the body: the document of Fetch-Document. The caller closes the body; a response that is not a success is returned with a StatusError and no body.

func (*Client) GetJobAttributes

func (c *Client) GetJobAttributes(ctx context.Context, jobID int32) (*JobStatus, error)

GetJobAttributes asks about a job.

func (*Client) GetJobs

func (c *Client) GetJobs(ctx context.Context, which string, mine bool, limit int) ([]*JobStatus, error)

GetJobs lists jobs: which is "completed", "not-completed" or "all" ("" asks for the ones not completed), mine limits them to the user's.

func (*Client) GetPrinterAttributes

func (c *Client) GetPrinterAttributes(ctx context.Context, requested ...string) (*Printer, error)

GetPrinterAttributes asks the printer about itself: the attributes named, or the ones Printer reads when none are (see PrinterAttributes).

func (*Client) IdentifyPrinter

func (c *Client) IdentifyPrinter(ctx context.Context, actions ...string) error

IdentifyPrinter asks the printer to make itself known: by the actions ("flash", "sound", "display", "speak"), or its default.

func (*Client) NewRequest

func (c *Client) NewRequest(op Op) *Message

NewRequest makes a request of the operation with the client's charset, language, printer-uri and requesting-user-name.

func (*Client) PrintJob

func (c *Client) PrintJob(ctx context.Context, name, format string, job []Attribute, doc io.Reader, op ...Attribute) (*JobStatus, error)

PrintJob prints one document as a job of the attributes, streaming doc. op are more operation attributes of the document (document-metadata …).

func (*Client) PrinterURI

func (c *Client) PrinterURI() string

PrinterURI returns the printer-uri the client names in requests.

func (*Client) SendDocument

func (c *Client) SendDocument(ctx context.Context, jobID int32, name, format string, doc io.Reader, last bool, op ...Attribute) (*JobStatus, error)

SendDocument sends a document of the format to a job, streaming doc. last tells the printer the job has no more documents. op are more operation attributes of the document (document-metadata …).

func (*Client) ValidateJob

func (c *Client) ValidateJob(ctx context.Context, job []Attribute, format string) error

ValidateJob asks whether a job of the attributes, in the document format, would be accepted. A nil error means yes; a StatusError says what is not supported.

type CupsPrinter

type CupsPrinter struct {
	Name      string
	URI       string // printer-uri-supported: the queue's URL
	Info      string
	MakeModel string
	Location  string
	State     PrinterState
	Reasons   []string
	Accepting bool
	IsClass   bool
	DeviceURI string
}

CupsPrinter is a queue of a CUPS server, as CUPS-Get-Printers lists them.

type Group

type Group struct {
	Tag   Tag
	Attrs []Attribute
}

Group is a group of attributes, begun by a group tag.

func (*Group) Get

func (g *Group) Get(name string) *Attribute

Get returns the first attribute of the name, or nil.

type JobState

type JobState int32

JobState is the state of a job (RFC 8011 §5.3.7, "job-state").

const (
	JobPending           JobState = 3
	JobPendingHeld       JobState = 4
	JobProcessing        JobState = 5
	JobProcessingStopped JobState = 6
	JobCanceled          JobState = 7
	JobAborted           JobState = 8
	JobCompleted         JobState = 9
)

Job states.

func (JobState) Done

func (s JobState) Done() bool

Done reports whether the job is over: canceled, aborted or completed.

func (JobState) MarshalText

func (s JobState) MarshalText() ([]byte, error)

MarshalText writes the keyword of the state ("pending" …).

func (JobState) String

func (s JobState) String() string

String returns the keyword of the state.

func (*JobState) UnmarshalText

func (s *JobState) UnmarshalText(b []byte) error

UnmarshalText reads the keyword of a state.

type JobStatus

type JobStatus struct {
	ID          int32
	URI         string
	Name        string
	State       JobState
	Reasons     []string
	Message     string // job-state-message
	Impressions int32  // job-impressions-completed, or -1 when the printer does not say
	// Attrs are the job attributes as received.
	Attrs []Attribute
	// Unsupported are the attributes the printer did not take, as the
	// answer to a request that makes a job listed them (its
	// unsupported-attributes group).
	Unsupported []Attribute
}

JobStatus is what a printer tells of a job.

func (*JobStatus) String

func (j *JobStatus) String() string

type Limits

type Limits struct {
	MaxBytes      int
	MaxAttributes int
	MaxValueBytes int
	MaxValues     int
	MaxDepth      int
}

Limits bound what Decode accepts of a message: its bytes, its attributes (the members of collections included), the bytes of one value, the values of one attribute, and the nesting of collections. A zero field takes the default.

type Media

type Media struct {
	SizeName string // media-size-name, when given
	// X and Y are the width and height in hundredths of a millimetre.
	X, Y   int32
	Source string
	Type   string
	Color  string
	// Margins in hundredths of a millimetre: left, right, top, bottom.
	Left, Right, Top, Bottom int32
}

Media is a size of paper a printer has or takes (an entry of media-col-database or media-ready in collection form).

func ParseMedia

func ParseMedia(c []Attribute) Media

ParseMedia reads a media-col collection.

type Message

type Message struct {
	Version Version
	// Code is the operation of a request (Op) or the status of a
	// response (Status).
	Code      uint16
	RequestID uint32
	Groups    []Group
}

Message is a request or a response.

func Decode

func Decode(r io.Reader, lim *Limits) (*Message, error)

Decode reads a message from the start of r: its header, its groups, and the end-of-attributes tag, leaving what follows (the document of a Print-Job or Send-Document) unread. r is read with a bufio.Reader unless it is one, so the caller that reads on should read from the returned reader.

func DecodeFrom

func DecodeFrom(r io.Reader, lim *Limits) (*Message, *bufio.Reader, error)

DecodeFrom is Decode that also returns the buffered reader positioned after the message, for the document that follows it.

func NewRequest

func NewRequest(op Op, id uint32, charset, lang string) *Message

NewRequest makes a request of the operation, with the operation group begun by the charset and the language that RFC 8011 requires first ("utf-8" and "en" when "").

func NewResponse

func NewResponse(st Status, id uint32, charset, lang string) *Message

NewResponse makes a response of the status to a request, with the same first two attributes.

func Unmarshal

func Unmarshal(b []byte, lim *Limits) (*Message, error)

Unmarshal decodes a message from bytes. Anything after the message is ignored.

func (*Message) Add

func (m *Message) Add(tag Tag, attrs ...Attribute)

Add adds attributes to the first group of the tag, making the group when the message has none.

func (*Message) AppendTo

func (m *Message) AppendTo(buf []byte) ([]byte, error)

AppendTo appends the encoding of the message to buf.

func (*Message) Attr

func (m *Message) Attr(tag Tag, name string) *Attribute

Attr returns the first attribute of the name in the first group of the tag, or nil.

func (*Message) Encode

func (m *Message) Encode(w io.Writer) error

Encode writes the encoding of the message.

func (*Message) Group

func (m *Message) Group(tag Tag) *Group

Group returns the first group of the tag, or nil.

func (*Message) Marshal

func (m *Message) Marshal() ([]byte, error)

Marshal returns the encoding of the message.

func (*Message) Op

func (m *Message) Op() Op

Op returns the code as the operation of a request.

func (*Message) Status

func (m *Message) Status() Status

Status returns the code as the status of a response.

type Op

type Op uint16

Op is the operation of a request (RFC 8011 §5.4.15 and the IANA IPP registry).

const (
	OpPrintJob                   Op = 0x0002
	OpPrintURI                   Op = 0x0003
	OpValidateJob                Op = 0x0004
	OpCreateJob                  Op = 0x0005
	OpSendDocument               Op = 0x0006
	OpSendURI                    Op = 0x0007
	OpCancelJob                  Op = 0x0008
	OpGetJobAttributes           Op = 0x0009
	OpGetJobs                    Op = 0x000a
	OpGetPrinterAttributes       Op = 0x000b
	OpHoldJob                    Op = 0x000c
	OpReleaseJob                 Op = 0x000d
	OpRestartJob                 Op = 0x000e
	OpPausePrinter               Op = 0x0010
	OpResumePrinter              Op = 0x0011
	OpPurgeJobs                  Op = 0x0012
	OpSetPrinterAttributes       Op = 0x0013
	OpSetJobAttributes           Op = 0x0014
	OpGetPrinterSupportedValues  Op = 0x0015
	OpCreatePrinterSubscriptions Op = 0x0016
	OpCreateJobSubscriptions     Op = 0x0017
	OpGetSubscriptionAttributes  Op = 0x0018
	OpGetSubscriptions           Op = 0x0019
	OpRenewSubscription          Op = 0x001a
	OpCancelSubscription         Op = 0x001b
	OpGetNotifications           Op = 0x001c
	OpHoldNewJobs                Op = 0x0022
	OpReleaseHeldNewJobs         Op = 0x0023
	OpCancelCurrentJob           Op = 0x0027
	OpCancelJobs                 Op = 0x0038
	OpCancelMyJobs               Op = 0x0039
	OpResubmitJob                Op = 0x003a
	OpCloseJob                   Op = 0x003b
	OpIdentifyPrinter            Op = 0x003c
	OpValidateDocument           Op = 0x003d

	// Operations of the IPP Shared Infrastructure Extensions (PWG
	// 5100.18): a proxy fetches jobs from an infrastructure printer and
	// reports them.
	OpAcknowledgeDocument          Op = 0x003f
	OpAcknowledgeIdentifyPrinter   Op = 0x0040
	OpAcknowledgeJob               Op = 0x0041
	OpFetchDocument                Op = 0x0042
	OpFetchJob                     Op = 0x0043
	OpGetOutputDeviceAttributes    Op = 0x0044
	OpUpdateActiveJobs             Op = 0x0045
	OpDeregisterOutputDevice       Op = 0x0046
	OpUpdateDocumentStatus         Op = 0x0047
	OpUpdateJobStatus              Op = 0x0048
	OpUpdateOutputDeviceAttributes Op = 0x0049

	// Private operations of CUPS (its cups-ipp registrations).
	OpCupsGetDefault       Op = 0x4001
	OpCupsGetPrinters      Op = 0x4002
	OpCupsAddModifyPrinter Op = 0x4003
	OpCupsDeletePrinter    Op = 0x4004
	OpCupsGetClasses       Op = 0x4005
	OpCupsAcceptJobs       Op = 0x4008
	OpCupsRejectJobs       Op = 0x4009
	OpCupsSetDefault       Op = 0x400a
	OpCupsMoveJob          Op = 0x400d
	OpCupsGetDocument      Op = 0x4027
)

Operations.

func (Op) String

func (o Op) String() string

String returns the name of the operation, or its number.

type Printer

type Printer struct {
	URI      string   // the URL asked
	URIs     []string // printer-uri-supported
	Auth     []string // uri-authentication-supported, parallel to URIs
	Security []string // uri-security-supported, parallel to URIs

	Name      string
	Info      string
	MakeModel string
	Location  string
	UUID      string
	DeviceID  string

	State         PrinterState
	Reasons       []string
	StateMessage  string
	AcceptingJobs bool

	Versions         []string
	Operations       []Op
	ConfigChangeTime int32

	Formats       []string // document-format-supported
	DefaultFormat string
	PDFVersions   []string

	Media        []string // media-supported
	MediaReady   []string
	MediaDefault string
	MediaSources []string
	MediaTypes   []string
	MediaCol     bool    // media-col is accepted (media-col-supported names members)
	MediaColDB   []Media // media-col-database, when asked for

	Sides             []string
	SidesDefault      string
	ColorModes        []string
	ColorModeDefault  string
	Qualities         []int32 // print-quality-supported: 3 draft, 4 normal, 5 high
	QualityDefault    int32
	Resolutions       []Resolution
	ResolutionDefault Resolution
	Copies            Range // copies-supported; {1,1} when not said
	PageRanges        bool
	Scaling           []string
	ScalingDefault    string
	NumberUp          []int32
	Orientations      []int32
	DocumentHandling  []string
	Finishings        []int32
	FinishingsDefault []int32
	OutputBins        []string
	OutputBinDefault  string

	PWGRasterResolutions []Resolution
	PWGRasterTypes       []string
	PWGRasterSheetBack   string
	URF                  []string
	// PCLm is set for a printer that takes PCLm: the height of its strips
	// (pclm-strip-height-preferred), the transform of the back of a sheet
	// (pclm-raster-back-side), its resolutions and its compressions
	// ("flate", "jpeg", "rle"), most preferred first
	PCLm            bool
	PCLmStripHeight int32
	PCLmBackSide    string
	PCLmResolutions []Resolution
	PCLmCompression []string

	JobPassword           int32 // job-password-supported: the length, 0 when not supported
	JobPasswordEncryption []string
	JobAccountID          bool
	JobAccountingUserID   bool
	IdentifyActions       []string
	JobCreationAttrs      []string

	// Attrs are the printer attributes as received.
	Attrs []Attribute
}

Printer is what a printer says of itself in Get-Printer-Attributes: its names and state, and what it supports, read into fields for the attributes a job needs, with all of them in Attrs.

func ParsePrinter

func ParsePrinter(m *Message) *Printer

ParsePrinter reads a Get-Printer-Attributes response.

func (*Printer) Has

func (p *Printer) Has(name string) (*Attribute, bool)

Has reports whether an attribute of the name is among the printer's, and returns it.

func (*Printer) SortedFormats

func (p *Printer) SortedFormats() []string

SortedFormats returns the formats the printer supports, sorted.

func (*Printer) Summary

func (p *Printer) Summary() []string

Summary lines the printer up for people: a name, the model, the state, the formats and the main capabilities, one a line.

func (*Printer) Supports

func (p *Printer) Supports(format string) bool

Supports reports whether the printer takes documents of the format (a media type such as "application/pdf" or "image/pwg-raster").

func (*Printer) SupportsOp

func (p *Printer) SupportsOp(op Op) bool

SupportsOp reports whether the printer names the operation among operations-supported.

type PrinterState

type PrinterState int32

PrinterState is the state of a printer (RFC 8011 §5.4.11, "printer-state").

const (
	PrinterIdle       PrinterState = 3
	PrinterProcessing PrinterState = 4
	PrinterStopped    PrinterState = 5
)

Printer states.

func (PrinterState) String

func (s PrinterState) String() string

String returns the keyword of the state.

type Range

type Range struct{ Lo, Hi int32 }

Range is a rangeOfInteger value.

func (Range) String

func (r Range) String() string

type Resolution

type Resolution struct {
	X, Y  int32
	Units uint8
}

Resolution is a resolution value: dots per inch (UnitsDPI) or per centimetre (UnitsDPCM), across the feed and along it.

func (Resolution) String

func (r Resolution) String() string

type Responder

type Responder struct {
	// contains filtered or unexported fields
}

Responder advertises services with multicast DNS (RFC 6762) and DNS-SD (RFC 6763): it probes for its instance names, announces its records, answers the questions for them, and says goodbye when it stops. It shares the port of mDNS with the system's responder (Bonjour, Avahi, Windows), as both bind it reusably; the records of the host's address it answers are those the system's responder answers too, so they agree.

func Advertise(ctx context.Context, ads []Advertisement, o ResponderOptions) (*Responder, error)

Advertise advertises services until ctx ends (it then says goodbye): it returns once the names are probed and announced.

func (*Responder) Close

func (r *Responder) Close()

Close says goodbye (the records with a TTL of 0) and closes the sockets.

func (*Responder) Host

func (r *Responder) Host() string

Host is the host name advertised ("server-bdf.local."), as probed.

func (*Responder) Names

func (r *Responder) Names() []string

Names are the services' full instance names, as advertised.

func (*Responder) SetTXT

func (r *Responder) SetTXT(txt [][]string)

SetTXT changes the TXT records of the services (in the order they were given) and announces them: what a printer can do is known after it is advertised.

type ResponderOptions

type ResponderOptions struct {
	// Host is the host name the services are on, in .local
	// ("server-bdf.local"), whose addresses the responder answers: a name
	// of its own, not the system's (whose responder would take the
	// records of another as a conflict, and rename the machine). It is
	// probed as the instances are, and renamed "server-bdf-2.local" when
	// another host has it.
	Host string
	// Log receives what happens; nothing by default.
	Log *slog.Logger
	// Port is the port of mDNS: 5353 but in tests, whose responders are
	// asked directly on the loopback.
	Port int
	// Interfaces bound the interfaces advertised on; all those up with
	// multicast by default. Loopback adds 127.0.0.1 and ::1 (for tests).
	Interfaces []net.Interface
	Loopback   bool
}

ResponderOptions configure a Responder.

type Service

type Service struct {
	// Name is the instance name the printer advertises ("Canon MF Series").
	Name string
	// Host and Port are from the SRV record: the printer's host name
	// ("printer.local") and the port of its IPP server.
	Host string
	Port int
	// Addrs are the addresses of the host, from its A and AAAA records.
	Addrs []net.IP
	// TXT holds the keys of the TXT record: rp (the path), pdl (the
	// formats), ty (the model), note, adminurl, UUID, URF, TLS, Color,
	// Duplex, kind, air, priority …
	TXT map[string]string
	// Secure tells the service was found as _ipps._tcp: it speaks TLS.
	Secure bool
	// Local tells a printer of this machine, at a loopback address: one
	// of USB that ipp-usb (Linux) or the system (macOS) shows as an IPP
	// printer, or a queue the machine shares.
	Local bool
	// URL is the printer's URL for a Client: ipp or ipps, the first
	// address (an IPv4 one when there is one) and the port, and the
	// path of rp. An address stands in for the host because the
	// resolution of .local names is not everywhere.
	URL string
}

Service is an IPP printer that DNS-SD (RFC 6763) on the local links (mDNS, RFC 6762) found.

func Browse

func Browse(ctx context.Context, timeout time.Duration) ([]Service, error)

Browse looks for IPP printers on the local links for the timeout (two seconds when zero) and returns them, sorted by name. Both _ipp._tcp and _ipps._tcp are asked for; a printer that answers both is listed once, as secure.

The queries are sent from a port of the kernel's choosing with the unicast-response bit, so the answers come back to it and the port of mDNS (5353) is not bound, which leaves Avahi and Bonjour alone; answers that printers multicast anyway are read from a listener on the group. The responder of this machine is also asked directly at 127.0.0.1 (RFC 6762 §5.5): printers of USB that speak IPP (IPP over USB) are advertised on the loopback, which has no multicast on Linux.

func (*Service) Formats

func (s *Service) Formats() []string

Formats returns the document formats the TXT record names (pdl).

type Status

type Status uint16

Status is the status code of a response (RFC 8011 §5.4.15 and appendix B).

const (
	StatusOK                     Status = 0x0000
	StatusOKIgnoredOrSubstituted Status = 0x0001
	StatusOKConflicting          Status = 0x0002
	StatusOKIgnoredSubscriptions Status = 0x0003
	StatusOKTooManyEvents        Status = 0x0005
	StatusOKEventsComplete       Status = 0x0007

	StatusClientErrorBadRequest                     Status = 0x0400
	StatusClientErrorForbidden                      Status = 0x0401
	StatusClientErrorNotAuthenticated               Status = 0x0402
	StatusClientErrorNotAuthorized                  Status = 0x0403
	StatusClientErrorNotPossible                    Status = 0x0404
	StatusClientErrorTimeout                        Status = 0x0405
	StatusClientErrorNotFound                       Status = 0x0406
	StatusClientErrorGone                           Status = 0x0407
	StatusClientErrorRequestEntityTooLarge          Status = 0x0408
	StatusClientErrorRequestValueTooLong            Status = 0x0409
	StatusClientErrorDocumentFormatNotSupported     Status = 0x040a
	StatusClientErrorAttributesOrValuesNotSupported Status = 0x040b
	StatusClientErrorURISchemeNotSupported          Status = 0x040c
	StatusClientErrorCharsetNotSupported            Status = 0x040d
	StatusClientErrorConflictingAttributes          Status = 0x040e
	StatusClientErrorCompressionNotSupported        Status = 0x040f
	StatusClientErrorCompressionError               Status = 0x0410
	StatusClientErrorDocumentFormatError            Status = 0x0411
	StatusClientErrorDocumentAccessError            Status = 0x0412
	StatusClientErrorAttributesNotSettable          Status = 0x0413
	StatusClientErrorIgnoreAllSubscriptions         Status = 0x0414
	StatusClientErrorTooManySubscriptions           Status = 0x0415
	StatusClientErrorDocumentPasswordError          Status = 0x0418
	StatusClientErrorDocumentPermissionError        Status = 0x0419
	StatusClientErrorDocumentSecurityError          Status = 0x041a
	StatusClientErrorDocumentUnprintableError       Status = 0x041b
	StatusClientErrorAccountInfoNeeded              Status = 0x041c
	StatusClientErrorAccountClosed                  Status = 0x041d
	StatusClientErrorAccountLimitReached            Status = 0x041e
	StatusClientErrorAccountAuthorizationFailed     Status = 0x041f
	StatusClientErrorNotFetchable                   Status = 0x0420

	StatusServerErrorInternal                         Status = 0x0500
	StatusServerErrorOperationNotSupported            Status = 0x0501
	StatusServerErrorServiceUnavailable               Status = 0x0502
	StatusServerErrorVersionNotSupported              Status = 0x0503
	StatusServerErrorDeviceError                      Status = 0x0504
	StatusServerErrorTemporaryError                   Status = 0x0505
	StatusServerErrorNotAcceptingJobs                 Status = 0x0506
	StatusServerErrorBusy                             Status = 0x0507
	StatusServerErrorJobCanceled                      Status = 0x0508
	StatusServerErrorMultipleDocumentJobsNotSupported Status = 0x0509
	StatusServerErrorPrinterIsDeactivated             Status = 0x050a
	StatusServerErrorTooManyJobs                      Status = 0x050b
	StatusServerErrorTooManyDocuments                 Status = 0x050c
)

Status codes.

func (Status) ClientError

func (s Status) ClientError() bool

ClientError reports whether the status is a client error (0x0400 to 0x04ff): the request was wrong.

func (Status) OK

func (s Status) OK() bool

OK reports whether the status is a success (0x0000 to 0x00ff).

func (Status) ServerError

func (s Status) ServerError() bool

ServerError reports whether the status is a server error (0x0500 to 0x05ff): the printer could not do it.

func (Status) String

func (s Status) String() string

String returns the name of the status code, or its number.

type StatusError

type StatusError struct {
	Op      Op
	Status  Status
	Message string // status-message, when the printer gave one
	// Unsupported are the attributes of the unsupported-attributes
	// group, when there is one.
	Unsupported []Attribute
}

StatusError is the error of a response whose status is not a success.

func (*StatusError) Error

func (e *StatusError) Error() string

type TLSPolicy

type TLSPolicy struct {
	// Store records the fingerprints of certificates the roots of the
	// system do not verify, by the host of the URL, and refuses a host
	// whose certificate changed. nil keeps none: such a certificate is
	// refused.
	Store *TrustStore
	// Insecure takes any certificate. For testing, or a network that is
	// trusted as a whole.
	Insecure bool
}

TLSPolicy says how the certificate of an ipps printer is verified. The zero value verifies with the roots of the system, as any HTTPS client does. Printers mostly have certificates of their own making, so Store lets the first connection record the certificate's fingerprint and later ones require the same (trust on first use, as CUPS does); Insecure takes any certificate.

type Tag

type Tag uint8

Tag is the tag of a value or of a group of attributes in the encoding of a message (RFC 8010 §3.5). The tags below 0x10 begin groups; the others name the type of a value, or that a value is out of band.

const (
	TagOperation         Tag = 0x01
	TagJob               Tag = 0x02
	TagEnd               Tag = 0x03 // end-of-attributes
	TagPrinter           Tag = 0x04
	TagUnsupportedGroup  Tag = 0x05
	TagSubscription      Tag = 0x06
	TagEventNotification Tag = 0x07
	TagResource          Tag = 0x08
	TagDocument          Tag = 0x09
	TagSystem            Tag = 0x0a
)

Group tags (RFC 8010 §3.5.1).

const (
	TagUnsupported     Tag = 0x10
	TagDefault         Tag = 0x11
	TagUnknown         Tag = 0x12
	TagNoValue         Tag = 0x13
	TagNotSettable     Tag = 0x15
	TagDeleteAttribute Tag = 0x16
	TagAdminDefine     Tag = 0x17
)

Out-of-band value tags: a value that is not there, and why (RFC 8010 §3.5.2, RFC 8011 §5.1.1).

const (
	TagInteger Tag = 0x21
	TagBoolean Tag = 0x22
	TagEnum    Tag = 0x23

	TagOctetString     Tag = 0x30
	TagDateTime        Tag = 0x31
	TagResolution      Tag = 0x32
	TagRange           Tag = 0x33 // rangeOfInteger
	TagBeginCollection Tag = 0x34
	TagTextLang        Tag = 0x35 // textWithLanguage
	TagNameLang        Tag = 0x36 // nameWithLanguage
	TagEndCollection   Tag = 0x37

	TagText           Tag = 0x41 // textWithoutLanguage
	TagName           Tag = 0x42 // nameWithoutLanguage
	TagReservedString Tag = 0x43
	TagKeyword        Tag = 0x44
	TagURI            Tag = 0x45
	TagURIScheme      Tag = 0x46
	TagCharset        Tag = 0x47
	TagLanguage       Tag = 0x48 // naturalLanguage
	TagMimeType       Tag = 0x49 // mimeMediaType
	TagMemberName     Tag = 0x4a // memberAttrName

	TagExtension Tag = 0x7f
)

Value tags of the types of values (RFC 8010 §3.5.2).

func (Tag) IsGroup

func (t Tag) IsGroup() bool

IsGroup reports whether the tag begins a group of attributes.

func (Tag) IsOutOfBand

func (t Tag) IsOutOfBand() bool

IsOutOfBand reports whether the tag stands for a value that is not there.

func (Tag) IsString

func (t Tag) IsString() bool

IsString reports whether the value of the tag is a character string (RFC 8010's character-string types, 0x40 to 0x5f).

func (Tag) String

func (t Tag) String() string

String returns the name of the tag in the registry, or its number.

type TrustBackend

type TrustBackend interface {
	Load() (map[string]string, error)
	Save(map[string]string) error
}

TrustBackend keeps the fingerprints of a TrustStore, by host.

type TrustStore

type TrustStore struct {
	// Path is the file: $XDG_CONFIG_HOME/bdf/printers.json by default
	// (DefaultTrustPath).
	Path string
	// ReadOnly refuses hosts not yet recorded instead of recording them.
	ReadOnly bool
	// Backend keeps the fingerprints instead of the file at Path: a
	// print server keeps them in its own store.
	Backend TrustBackend
	// Pinned are fingerprints set beforehand, by host ("sha256:…"): such
	// a host must have that certificate, and nothing is recorded for it.
	Pinned map[string]string
	// contains filtered or unexported fields
}

TrustStore keeps the fingerprints of the certificates of printers that the roots of the system do not verify, by host, in a JSON file.

func (*TrustStore) Forget

func (s *TrustStore) Forget(host string) error

Forget removes the fingerprint recorded for a host.

type Value

type Value struct {
	Tag   Tag
	Int   int32
	Str   string
	Lang  string
	Time  time.Time
	Res   Resolution
	Range Range
	Coll  []Attribute
	Raw   []byte
}

Value is one value of an attribute. Tag tells its type and which of the fields holds it: Int for integer and enum (and boolean, as 0 or 1); Str for the character strings, octetString and the text of textWithLanguage and nameWithLanguage (whose language is Lang); Time for dateTime; Res for resolution; Range for rangeOfInteger; Coll for a collection; none for an out-of-band value. Raw holds the bytes of a value whose tag the package does not know, as they were.

func Boolean

func Boolean(b bool) Value

Boolean makes a boolean value.

func Charset

func Charset(s string) Value

Charset makes a charset value.

func Collection

func Collection(members ...Attribute) Value

Collection makes a collection value of member attributes.

func DateTime

func DateTime(t time.Time) Value

DateTime makes a dateTime value.

func Enum

func Enum(n int) Value

Enum makes an enum value.

func Enums

func Enums(ns []int) []Value

Enums are the values of an attribute of enums.

func Integer

func Integer(n int) Value

Integer makes an integer value.

func Keyword

func Keyword(s string) Value

Keyword makes a keyword value.

func Keywords

func Keywords(s []string) []Value

Keywords are the values of an attribute of keywords.

func Language

func Language(s string) Value

Language makes a naturalLanguage value.

func MimeType

func MimeType(s string) Value

MimeType makes a mimeMediaType value.

func MimeTypes

func MimeTypes(s []string) []Value

MimeTypes are the values of an attribute of MIME types.

func Name

func Name(s string) Value

Name makes a nameWithoutLanguage value.

func NameLang

func NameLang(lang, s string) Value

NameLang makes a nameWithLanguage value.

func NewRange

func NewRange(lo, hi int) Value

NewRange makes a rangeOfInteger value.

func NewResolution

func NewResolution(x, y int, units uint8) Value

NewResolution makes a resolution value.

func OctetString

func OctetString(b []byte) Value

OctetString makes an octetString value.

func OutOfBand

func OutOfBand(tag Tag) Value

OutOfBand makes a value that is not there (TagUnsupported, TagUnknown, TagNoValue …).

func Text

func Text(s string) Value

Text makes a textWithoutLanguage value.

func TextLang

func TextLang(lang, s string) Value

TextLang makes a textWithLanguage value.

func URI

func URI(s string) Value

URI makes a uri value.

func URIScheme

func URIScheme(s string) Value

URIScheme makes a uriScheme value.

func (Value) Bool

func (v Value) Bool() bool

Bool returns a boolean value, or whether an integer is not zero.

func (Value) String

func (v Value) String() string

String renders the value for people: a number, a keyword, a time, a resolution, a range, a collection in braces, the tag of an out-of-band value, or the hex of unknown bytes.

type Version

type Version struct{ Major, Minor uint8 }

Version is the version of the protocol a message names.

func (Version) String

func (v Version) String() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL