Filter and Backend Programming

Headers cups/backend.h
cups/sidechannel.h
cups/snmp.h
Library -lcups
See Also Programming: Introduction to CUPS Programming
Programming: CUPS API
Programming: PPD API
Programming: Raster API

Contents

Overview

Filters, printer drivers, port monitors, and backends use a common interface for processing print jobs and communicating status information to the scheduler. Each filter is run with a standard set of command-line arguments:

argv[1]
The job ID
argv[2]
The user printing the job
argv[3]
The job name/title
argv[4]
The number of copies to print
argv[5]
The options that were provided when the job was submitted
argv[6]
The file to print (first filter only)

The scheduler runs one or more of these programs to print any given job. The first filter reads from the print file and writes to the standard output, while the remaining filters read from the standard input and write to the standard output. The backend is the last filter in the chain and writes to the device.

Security Considerations

It is always important to use security programming practices. Filters and most backends are run as a non-priviledged user, so the major security consideration is resource utilization - filters should not depend on unlimited amounts of CPU, memory, or disk space, and should protect against conditions that could lead to excess usage of any resource like infinite loops and unbounded recursion. In addition, filters must never allow the user to specify an arbitrary file path to a separator page, template, or other file used by the filter since that can lead to an unauthorized disclosure of information. Always treat input as suspect and validate it!

If you are developing a backend that runs as root, make sure to check for potential buffer overflows, integer under/overflow conditions, and file accesses since these can lead to privilege escalations. When writing files, always validate the file path and never allow a user to determine where to store a file.

Note:

Never write files to a user's home directory. Aside from the security implications, CUPS is a network print service and as such the network user may not be the same as the local user and/or there may not be a local home directory to write to.

In addition, some operating systems provide additional security mechanisms that further limit file system access, even for backends running as root. On Mac OS X, for example, no backend may write to a user's home directory.

Temporary Files

Temporary files should be created in the directory specified by the "TMPDIR" environment variable. The cupsTempFile2 function can be used to safely create temporary files in this directory.

Copy Generation

The argv[4] argument specifies the number of copies to produce of the input file. In general, you should only generate copies if the filename argument is supplied. The only exception to this are filters that produce device-independent PostScript output, since the PostScript filter pstops is responsible for generating copies of PostScript files.

Exit Codes

Filters must exit with status 0 when they successfully generate print data or 1 when they encounter an error. Backends can return any of the cups_backend_t constants.

Environment Variables

The following environment variables are defined by the printing system:

APPLE_LANGUAGES
The Apple language identifier associated with the job (Mac OS X only).
CHARSET
The job character set, typically "utf-8".
CLASS
When a job is submitted to a printer class, contains the name of the destination printer class. Otherwise this environment variable will not be set.
CONTENT_TYPE
The MIME type associated with the file (e.g. application/postscript).
CUPS_CACHEDIR
The directory where cache files can be stored.
CUPS_DATADIR
The directory where data files can be found.
CUPS_SERVERROOT
The root directory of the server.
DEVICE_URI
The device-uri associated with the printer.
FINAL_CONTENT_TYPE
The MIME type associated with the printer (e.g. application/vnd.cups-postscript).
LANG
The language locale associated with the job.
PPD
The full pathname of the PostScript Printer Description (PPD) file for this printer.
PRINTER
The name of the printer.
RIP_CACHE
The recommended amount of memory to use for Raster Image Processors (RIPs).

Communicating with the Scheduler

Filters and backends communicate wih the scheduler by writing messages to the standard error file. For example, the following code sets the current printer state message to "Printing page 5":

int page = 5;

fprintf(stderr, "INFO: Printing page %d\n", page);

Each message is a single line of text starting with one of the following prefix strings:

ALERT: message
Sets the printer-state-message attribute and adds the specified message to the current error log file using the "alert" log level.
ATTR: attribute=value [attribute=value]
Sets the named printer or job attribute(s). Typically this is used to set the marker-colors, marker-levels, marker-names, marker-types, printer-alert, and printer-alert-description printer attributes.
CRIT: message
Sets the printer-state-message attribute and adds the specified message to the current error log file using the "critical" log level.
DEBUG: message
Sets the printer-state-message attribute and adds the specified message to the current error log file using the "debug" log level.
DEBUG2: message
Sets the printer-state-message attribute and adds the specified message to the current error log file using the "debug2" log level.
EMERG: message
Sets the printer-state-message attribute and adds the specified message to the current error log file using the "emergency" log level.
ERROR: message
Sets the printer-state-message attribute and adds the specified message to the current error log file using the "error" log level.
INFO: message
Sets the printer-state-message attribute. If the current log level is set to "debug2", also adds the specified message to the current error log file using the "info" log level.
NOTICE: message
Sets the printer-state-message attribute and adds the specified message to the current error log file using the "notice" log level.
PAGE: page-number #-copies
PAGE: total #-pages
Adds an entry to the current page log file. The first form adds #-copies to the job-media-sheets-completed attribute. The second form sets the job-media-sheets-completed attribute to #-pages.
STATE: printer-state-reason [printer-state-reason ...]
STATE: + printer-state-reason [printer-state-reason ...]
STATE: - printer-state-reason [printer-state-reason ...]
Sets, adds, or removes printer-state-reason keywords to the current queue. Typically this is used to indicate media, ink, and toner conditions on a printer.
WARNING: message
Sets the printer-state-message attribute and adds the specified message to the current error log file using the "warning" log level.

Messages without one of these prefixes are treated as if they began with the "DEBUG:" prefix string.

Communicating with the Backend

Filters can communicate with the backend via the cupsBackChannelRead and cupsSideChannelDoRequest functions. The cupsBackChannelRead function reads data that has been sent back from the device and is typically used to obtain status and configuration information. For example, the following code polls the backend for back-channel data:

#include <cups/cups.h>

char buffer[8192];
ssize_t bytes;

/* Use a timeout of 0.0 seconds to poll for back-channel data */
bytes = cupsBackChannelRead(buffer, sizeof(buffer), 0.0);
The cupsSideChannelDoRequest function allows you to get out-of-band status information and do synchronization with the device. For example, the following code gets the current IEEE-1284 device ID string from the backend:

#include <cups/sidechannel.h>

char data[2049];
int datalen;
cups_sc_status_t status;

/* Tell cupsSideChannelDoRequest() how big our buffer is, less 1 byte for nul-termination... */
datalen = sizeof(data) - 1;

/* Get the IEEE-1284 device ID, waiting for up to 1 second */
status = cupsSideChannelDoRequest(CUPS_SC_CMD_GET_DEVICE_ID, data, &datalen, 1.0);

/* Use the returned value if OK was returned and the length is non-zero */
if (status == CUPS_SC_STATUS_OK && datalen > 0)
  data[datalen] = '\0';
else
  data[0] = '\0';

Backends communicate with filters using the reciprocal functions cupsBackChannelWrite, cupsSideChannelRead, and cupsSideChannelWrite. We recommend writing back-channel data using a timeout of 1.0 seconds:

#include <cups/cups.h>

char buffer[8192];
ssize_t bytes;

/* Use a timeout of 1.0 seconds to give filters a chance to read */
cupsBackChannelWrite(buffer, bytes, 1.0);

The cupsSideChannelRead function reads a side-channel command from a filter, driver, or port monitor. Backends can either poll for commands using a timeout of 0.0, wait indefinitely for commands using a timeout of -1.0 (probably in a separate thread for that purpose), or use select or poll on the CUPS_SC_FD file descriptor (4) to handle input and output on several file descriptors at the same time. Backends can pass NULL for the data and datalen parameters since none of the commands sent by upstream filters contain any data at this time.

Once a command is processed, the backend uses the cupsSideChannelWrite function to send its response. For example, the following code shows how to poll for a side-channel command and respond to it:

#include <cups/sidechannel.h>

cups_sc_command_t command;
cups_sc_status_t status;

/* Poll for a command... */
if (!cupsSideChannelRead(&command, &status, NULL, NULL, 0.0))
{
  char data[2048];
  int datalen;

  switch (command)
  {
    /* handle supported commands, file data/datalen/status with values as needed */

    default :
        status  = CUPS_SC_STATUS_NOT_IMPLEMENTED;
	datalen = 0;
	break;
  }

  /* Send a response... */
  cupsSideChannelWrite(command, status, data, datalen, 1.0);
}

Doing SNMP Queries with Network Printers

The Simple Network Management Protocol (SNMP) allows you to get the current status, page counter, and supply levels from most network printers. Every piece of information is associated with an Object Identifier (OID), and every printer has a community name associated with it. OIDs can be queried directly or by "walking" over a range of OIDs with a common prefix.

The CUPS SNMP functions provide a simple API for querying network printers. Queries are made using a datagram socket that is created using cupsSNMPOpen and destroyed using cupsSNMPClose:

#include <cups/snmp.h>

int snmp = cupsSNMPOpen(AF_INET);

/* do some queries */

cupsSNMPClose(snmp);

OIDs are simple C arrays of integers, terminated by a value of -1. For example, the page counter OID .1.3.6.1.2.1.43.10.2.1.4.1.1 would be:

int page_counter_oid[] = { 1, 3, 6, 1, 2, 1, 43, 10, 2, 1, 4, 1, 1, -1 };

You send a query using cupsSNMPWrite and read the value back using cupsSNMPRead. The value is read into a structure called cups_snmp_t:

#include <cups/snmp.h>

int page_counter_oid[] = { 1, 3, 6, 1, 2, 1, 43, 10, 2, 1, 4, 1, 1, -1 };
http_addrlist_t *host = httpAddrGetList("myprinter", AF_UNSPEC, "161");
int snmp = cupsSNMPOpen(host->addr.addr.sa_family);
cups_snmp_t packet;

cupsSNMPWrite(snmp, &(host->addr), CUPS_SNMP_VERSION_1,
                cupsSNMPDefaultCommunity(), CUPS_ASN1_GET_REQUEST, 1,
                page_counter_oid);
if (cupsSNMPRead(snmp, &packet, 5000))
{
  /* Do something with the value */
  printf("Page counter is: %d\n", packet.object_value.integer);
}

The cupsSNMPWalk function allows you to query a whole group of OIDs, calling a function of your choice for each OID that is found:

#include <cups/snmp.h>

void
my_callback(cups_snmp_t *packet, void *data)
{
  /* Do something with the value */
}

int printer_mib_oid[] = { 1, 3, 6, 1, 2, 1, 43, -1 };
http_addrlist_t *host = httpAddrGetList("myprinter", AF_UNSPEC, "161");
int snmp = cupsSNMPOpen(host->addr.addr.sa_family);
void *my_data;

cupsSNMPWalk(snmp, &(host->addr), CUPS_SNMP_VERSION_1,
               cupsSNMPDefaultCommunity(), printer_mib_oid, my_callback, my_data);

Functions

 CUPS 1.2 cupsBackChannelRead

Read data from the backchannel.

ssize_t cupsBackChannelRead (
    char *buffer,
    size_t bytes,
    double timeout
);

Parameters

buffer
Buffer to read
bytes
Bytes to read
timeout
Timeout in seconds

Return Value

Bytes read or -1 on error

Discussion

Reads up to "bytes" bytes from the backchannel. The "timeout" parameter controls how many seconds to wait for the data - use 0.0 to return immediately if there is no data, -1.0 to wait for data indefinitely.

 CUPS 1.2 cupsBackChannelWrite

Write data to the backchannel.

ssize_t cupsBackChannelWrite (
    const char *buffer,
    size_t bytes,
    double timeout
);

Parameters

buffer
Buffer to write
bytes
Bytes to write
timeout
Timeout in seconds

Return Value

Bytes written or -1 on error

Discussion

Writes "bytes" bytes to the backchannel. The "timeout" parameter controls how many seconds to wait for the data to be written - use 0.0 to return immediately if the data cannot be written, -1.0 to wait indefinitely.

cupsBackendDeviceURI

Get the device URI for a backend.

const char *cupsBackendDeviceURI (
    char **argv
);

Parameters

argv
Command-line arguments

Return Value

Device URI or NULL

Discussion

The "argv" argument is the argv argument passed to main(). This function returns the device URI passed in the DEVICE_URI environment variable or the device URI passed in argv[0], whichever is found first.

 CUPS 1.4 cupsSNMPClose

Close a SNMP socket.

void cupsSNMPClose (
    int fd
);

Parameters

fd
SNMP socket file descriptor

 CUPS 1.4 cupsSNMPCopyOID

Copy an OID.

int *cupsSNMPCopyOID (
    int *dst,
    const int *src,
    int dstsize
);

Parameters

dst
Destination OID
src
Source OID
dstsize
Number of integers in dst

Return Value

New OID

Discussion

The array pointed to by "src" is terminated by the value -1.

 CUPS 1.4 cupsSNMPDefaultCommunity

Get the default SNMP community name.

const char *cupsSNMPDefaultCommunity (void);

Return Value

Default community name

Discussion

The default community name is the first community name found in the snmp.conf file. If no community name is defined there, "public" is used.

 CUPS 1.4 cupsSNMPIsOID

Test whether a SNMP response contains the specified OID.

int cupsSNMPIsOID (
    cups_snmp_t *packet,
    const int *oid
);

Parameters

packet
Response packet
oid
OID

Return Value

1 if equal, 0 if not equal

Discussion

The array pointed to by "oid" is terminated by the value -1.

 CUPS 1.4 cupsSNMPIsOIDPrefixed

Test whether a SNMP response uses the specified OID prefix.

int cupsSNMPIsOIDPrefixed (
    cups_snmp_t *packet,
    const int *prefix
);

Parameters

packet
Response packet
prefix
OID prefix

Return Value

1 if prefixed, 0 if not prefixed

Discussion

The array pointed to by "prefix" is terminated by the value -1.

 CUPS 1.4 cupsSNMPOpen

Open a SNMP socket.

int cupsSNMPOpen (
    int family
);

Parameters

family
Address family - AF_INET or AF_INET6

Return Value

SNMP socket file descriptor

 CUPS 1.4 cupsSNMPRead

Read and parse a SNMP response.

cups_snmp_t *cupsSNMPRead (
    int fd,
    cups_snmp_t *packet,
    int msec
);

Parameters

fd
SNMP socket file descriptor
packet
SNMP packet buffer
msec
Timeout in milliseconds

Return Value

SNMP packet or NULL if none

Discussion

If "timeout" is negative, cupsSNMPRead will wait for a response indefinitely.

 CUPS 1.4 cupsSNMPSetDebug

Enable/disable debug logging to stderr.

void cupsSNMPSetDebug (
    int level
);

Parameters

level
1 to enable debug output, 0 otherwise

 CUPS 1.4 cupsSNMPWalk

Enumerate a group of OIDs.

int cupsSNMPWalk (
    int fd,
    http_addr_t *address,
    int version,
    const char *community,
    const int *prefix,
    int msec,
    cups_snmp_cb_t cb,
    void *data
);

Parameters

fd
SNMP socket
address
Address to query
version
SNMP version
community
Community name
prefix
OID prefix
msec
Timeout for each response in milliseconds
cb
Function to call for each response
data
User data pointer that is passed to the callback function

Return Value

Number of OIDs found or -1 on error

Discussion

This function queries all of the OIDs with the specified OID prefix, calling the "cb" function for every response that is received.

The array pointed to by "prefix" is terminated by the value -1.

 CUPS 1.4 cupsSNMPWrite

Send an SNMP query packet.

int cupsSNMPWrite (
    int fd,
    http_addr_t *address,
    int version,
    const char *community,
    cups_asn1_t request_type,
    const unsigned request_id,
    const int *oid
);

Parameters

fd
SNMP socket
address
Address to send to
version
SNMP version
community
Community name
request_type
Request type
request_id
Request ID
oid
OID

Return Value

1 on success, 0 on error

Discussion

The array pointed to by "oid" is terminated by the value -1.

 CUPS 1.3 cupsSideChannelDoRequest

Send a side-channel command to a backend and wait for a response.

cups_sc_status_t cupsSideChannelDoRequest (
    cups_sc_command_t command,
    char *data,
    int *datalen,
    double timeout
);

Parameters

command
Command to send
data
Response data buffer pointer
datalen
Size of data buffer on entry, number of bytes in buffer on return
timeout
Timeout in seconds

Return Value

Status of command

Discussion

This function is normally only called by filters, drivers, or port monitors in order to communicate with the backend used by the current printer. Programs must be prepared to handle timeout or "not implemented" status codes, which indicate that the backend or device do not support the specified side-channel command.

The "datalen" parameter must be initialized to the size of the buffer pointed to by the "data" parameter. cupsSideChannelDoRequest() will update the value to contain the number of data bytes in the buffer.

 CUPS 1.3 cupsSideChannelRead

Read a side-channel message.

int cupsSideChannelRead (
    cups_sc_command_t *command,
    cups_sc_status_t *status,
    char *data,
    int *datalen,
    double timeout
);

Parameters

command
Command code
status
Status code
data
Data buffer pointer
datalen
Size of data buffer on entry, number of bytes in buffer on return
timeout
Timeout in seconds

Return Value

0 on success, -1 on error

Discussion

This function is normally only called by backend programs to read commands from a filter, driver, or port monitor program. The caller must be prepared to handle incomplete or invalid messages and return the corresponding status codes.

The "datalen" parameter must be initialized to the size of the buffer pointed to by the "data" parameter. cupsSideChannelDoRequest() will update the value to contain the number of data bytes in the buffer.

 CUPS 1.3 cupsSideChannelWrite

Write a side-channel message.

int cupsSideChannelWrite (
    cups_sc_command_t command,
    cups_sc_status_t status,
    const char *data,
    int datalen,
    double timeout
);

Parameters

command
Command code
status
Status code
data
Data buffer pointer
datalen
Number of bytes of data
timeout
Timeout in seconds

Return Value

0 on success, -1 on error

Discussion

This function is normally only called by backend programs to send responses to a filter, driver, or port monitor program.

Data Types

cups_asn1_t

ASN1 request/object types

typedef enum cups_asn1_e cups_asn1_t;

cups_backend_t

Backend exit codes

typedef enum cups_backend_e cups_backend_t;

cups_sc_bidi_t

Bidirectional capabilities

typedef enum cups_sc_bidi_e cups_sc_bidi_t;

cups_sc_command_t

Request command codes

typedef enum cups_sc_command_e cups_sc_command_t;

cups_sc_state_t

Printer state bits

typedef enum cups_sc_state_e cups_sc_state_t;

cups_sc_status_t

Response status codes

typedef enum cups_sc_status_e cups_sc_status_t;

cups_snmp_cb_t

Prototypes...

typedef void (*cups_snmp_cb_t)(cups_snmp_t *packet, void *data);

cups_snmp_t

SNMP data packet

typedef struct cups_snmp_s cups_snmp_t;

Structures

cups_snmp_hexstring_s

Hex-STRING value

struct cups_snmp_hexstring_s {
    unsigned char bytes[CUPS_SNMP_MAX_STRING];
    int num_bytes;
};

Members

bytes[CUPS_SNMP_MAX_STRING]
Bytes in string
num_bytes
Number of bytes

cups_snmp_s

SNMP data packet

struct cups_snmp_s {
    http_addr_t address;
    char community[CUPS_SNMP_MAX_STRING];
    const char *error;
    int error_index;
    int error_status;
    int object_name[CUPS_SNMP_MAX_OID];
    cups_asn1_t object_type;
    union cups_snmp_value_u object_value;
    int request_id;
    cups_asn1_t request_type;
    int version;
};

Members

address
Source address
community[CUPS_SNMP_MAX_STRING]
Community name
error
Encode/decode error
error_index
error-index value
error_status
error-status value
object_name[CUPS_SNMP_MAX_OID]
object-name value
object_type
object-value type
object_value
object-value value
request_id
request-id value
request_type
Request type
version
Version number

Unions

cups_snmp_value_u

Object value

union cups_snmp_value_u {
    int boolean;
    unsigned counter;
    unsigned gauge;
    struct cups_snmp_hexstring_s hex_string;
    int integer;
    int oid[CUPS_SNMP_MAX_OID];
    char string[CUPS_SNMP_MAX_STRING];
    unsigned timeticks;
};

Members

boolean
Boolean value
counter
Counter value
gauge
Gauge value
hex_string
Hex string value
integer
Integer value
oid[CUPS_SNMP_MAX_OID]
OID value
string[CUPS_SNMP_MAX_STRING]
String value
timeticks
Timeticks value

Constants

cups_asn1_e

ASN1 request/object types

Constants

CUPS_ASN1_BIT_STRING
BIT STRING
CUPS_ASN1_BOOLEAN
BOOLEAN
CUPS_ASN1_COUNTER
32-bit unsigned aka Counter32
CUPS_ASN1_END_OF_CONTENTS
End-of-contents
CUPS_ASN1_GAUGE
32-bit unsigned aka Gauge32
CUPS_ASN1_GET_NEXT_REQUEST
GetNextRequest-PDU
CUPS_ASN1_GET_REQUEST
GetRequest-PDU
CUPS_ASN1_GET_RESPONSE
GetResponse-PDU
CUPS_ASN1_HEX_STRING
Binary string aka Hex-STRING
CUPS_ASN1_INTEGER
INTEGER or ENUMERATION
CUPS_ASN1_NULL_VALUE
NULL VALUE
CUPS_ASN1_OCTET_STRING
OCTET STRING
CUPS_ASN1_OID
OBJECT IDENTIFIER
CUPS_ASN1_SEQUENCE
SEQUENCE
CUPS_ASN1_TIMETICKS
32-bit unsigned aka Timeticks32

cups_backend_e

Backend exit codes

Constants

CUPS_BACKEND_AUTH_REQUIRED
Job failed, authentication required
CUPS_BACKEND_CANCEL
Job failed, cancel job
CUPS_BACKEND_FAILED
Job failed, use error-policy
CUPS_BACKEND_HOLD
Job failed, hold job
CUPS_BACKEND_OK
Job completed successfully
CUPS_BACKEND_STOP
Job failed, stop queue

cups_sc_bidi_e

Bidirectional capabilities

Constants

CUPS_SC_BIDI_NOT_SUPPORTED
Bidirectional I/O is not supported
CUPS_SC_BIDI_SUPPORTED
Bidirectional I/O is supported

cups_sc_command_e

Request command codes

Constants

CUPS_SC_CMD_DRAIN_OUTPUT
Drain all pending output
CUPS_SC_CMD_GET_BIDI
Return bidirectional capabilities
CUPS_SC_CMD_GET_DEVICE_ID
Return the IEEE-1284 device ID
CUPS_SC_CMD_GET_STATE
Return the device state
CUPS_SC_CMD_SOFT_RESET
Do a soft reset

cups_sc_state_e

Printer state bits

Constants

CUPS_SC_STATE_BUSY
Device is busy
CUPS_SC_STATE_ERROR
Other error condition
CUPS_SC_STATE_MARKER_EMPTY
Toner/ink out condition
CUPS_SC_STATE_MARKER_LOW
Toner/ink low condition
CUPS_SC_STATE_MEDIA_EMPTY
Paper out condition
CUPS_SC_STATE_MEDIA_LOW
Paper low condition
CUPS_SC_STATE_OFFLINE
Device is off-line
CUPS_SC_STATE_ONLINE
Device is on-line

cups_sc_status_e

Response status codes

Constants

CUPS_SC_STATUS_BAD_MESSAGE
The command/response message was invalid
CUPS_SC_STATUS_IO_ERROR
An I/O error occurred
CUPS_SC_STATUS_NONE
No status
CUPS_SC_STATUS_NOT_IMPLEMENTED
Command not implemented
CUPS_SC_STATUS_NO_RESPONSE
The device did not respond
CUPS_SC_STATUS_OK
Operation succeeded
CUPS_SC_STATUS_TIMEOUT
The backend did not respond
CUPS_SC_STATUS_TOO_BIG
Response too big