#include <cups/backend.h>
#include <cups/http-private.h>
#include <cups/cups.h>
#include <cups/i18n.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <ctype.h>
#include <cups/string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <signal.h>
#ifdef WIN32
# include <winsock.h>
#else
# include <sys/socket.h>
# include <netinet/in.h>
# include <arpa/inet.h>
# include <netdb.h>
#endif
#ifdef __APPLE__
# include <CoreFoundation/CFNumber.h>
# include <CoreFoundation/CFPreferences.h>
#endif
static char tmpfilename[1024] = "";
static int abort_job = 0;
#define MODE_STANDARD 0
#define MODE_STREAM 1
#define ORDER_CONTROL_DATA 0
#define ORDER_DATA_CONTROL 1
#define RESERVE_NONE 0
#define RESERVE_RFC1179 1
#define RESERVE_ANY 2
static int lpd_command(int lpd_fd, int timeout, char *format, ...);
static int lpd_queue(const char *hostname, int port, const char *printer,
int print_fd, int mode, const char *user,
const char *title, int copies, int banner,
int format, int order, int reserve,
int manual_copies, int timeout, int contimeout);
static void lpd_timeout(int sig);
static int lpd_write(int lpd_fd, char *buffer, int length);
#ifndef HAVE_RRESVPORT_AF
static int rresvport_af(int *port, int family);
#endif
static void sigterm_handler(int sig);
int
main(int argc,
char *argv[])
{
char method[255],
hostname[1024],
username[255],
resource[1024],
*options,
*name,
*value,
sep,
*filename,
title[256];
int port;
int fd;
int status;
int mode;
int banner;
int format;
int order;
int reserve;
int sanitize_title;
int manual_copies,
timeout,
contimeout,
copies;
#if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
struct sigaction action;
#endif
setbuf(stderr, NULL);
#ifdef HAVE_SIGSET
sigset(SIGPIPE, SIG_IGN);
sigset(SIGTERM, sigterm_handler);
#elif defined(HAVE_SIGACTION)
memset(&action, 0, sizeof(action));
action.sa_handler = SIG_IGN;
sigaction(SIGPIPE, &action, NULL);
sigemptyset(&action.sa_mask);
sigaddset(&action.sa_mask, SIGTERM);
action.sa_handler = sigterm_handler;
sigaction(SIGTERM, &action, NULL);
#else
signal(SIGPIPE, SIG_IGN);
signal(SIGTERM, sigterm_handler);
#endif
if (argc == 1)
{
puts("network lpd \"Unknown\" \"LPD/LPR Host or Printer\"");
return (CUPS_BACKEND_OK);
}
else if (argc < 6 || argc > 7)
{
_cupsLangPrintf(stderr,
_("Usage: %s job-id user title copies options [file]\n"),
argv[0]);
return (CUPS_BACKEND_FAILED);
}
httpSeparateURI(HTTP_URI_CODING_ALL, cupsBackendDeviceURI(argv),
method, sizeof(method), username, sizeof(username),
hostname, sizeof(hostname), &port,
resource, sizeof(resource));
if (!port)
port = 515;
if (!username[0])
{
strlcpy(username, argv[2], sizeof(username));
}
mode = MODE_STANDARD;
banner = 0;
format = 'l';
order = ORDER_CONTROL_DATA;
reserve = RESERVE_ANY;
manual_copies = 1;
timeout = 300;
contimeout = 7 * 24 * 60 * 60;
#ifdef __APPLE__
sanitize_title = 0;
{
CFPropertyListRef pvalue;
SInt32 toval;
pvalue = CFPreferencesCopyValue(CFSTR("timeout"),
CFSTR("com.apple.print.backends"),
kCFPreferencesAnyUser,
kCFPreferencesCurrentHost);
if (pvalue)
{
if (CFGetTypeID(pvalue) == CFNumberGetTypeID())
{
CFNumberGetValue(pvalue, kCFNumberSInt32Type, &toval);
contimeout = (int)toval;
}
CFRelease(pvalue);
}
}
#else
sanitize_title = 1;
#endif
if ((options = strchr(resource, '?')) != NULL)
{
*options++ = '\0';
while (*options)
{
name = options;
while (*options && *options != '=' && *options != '+' && *options != '&')
options ++;
if ((sep = *options) != '\0')
*options++ = '\0';
if (sep == '=')
{
value = options;
while (*options && *options != '+' && *options != '&')
options ++;
if (*options)
*options++ = '\0';
}
else
value = (char *)"";
if (!strcasecmp(name, "banner"))
{
banner = !value[0] || !strcasecmp(value, "on") ||
!strcasecmp(value, "yes") || !strcasecmp(value, "true");
}
else if (!strcasecmp(name, "format") && value[0])
{
if (strchr("cdfglnoprtv", value[0]))
format = value[0];
else
_cupsLangPrintf(stderr, _("ERROR: Unknown format character \"%c\"\n"),
value[0]);
}
else if (!strcasecmp(name, "mode") && value[0])
{
if (!strcasecmp(value, "standard"))
mode = MODE_STANDARD;
else if (!strcasecmp(value, "stream"))
mode = MODE_STREAM;
else
_cupsLangPrintf(stderr, _("ERROR: Unknown print mode \"%s\"\n"),
value);
}
else if (!strcasecmp(name, "order") && value[0])
{
if (!strcasecmp(value, "control,data"))
order = ORDER_CONTROL_DATA;
else if (!strcasecmp(value, "data,control"))
order = ORDER_DATA_CONTROL;
else
_cupsLangPrintf(stderr, _("ERROR: Unknown file order \"%s\"\n"),
value);
}
else if (!strcasecmp(name, "reserve"))
{
if (!value[0] || !strcasecmp(value, "on") ||
!strcasecmp(value, "yes") || !strcasecmp(value, "true") ||
!strcasecmp(value, "rfc1179"))
reserve = RESERVE_RFC1179;
else if (!strcasecmp(value, "any"))
reserve = RESERVE_ANY;
else
reserve = RESERVE_NONE;
}
else if (!strcasecmp(name, "manual_copies"))
{
manual_copies = !value[0] || !strcasecmp(value, "on") ||
!strcasecmp(value, "yes") || !strcasecmp(value, "true");
}
else if (!strcasecmp(name, "sanitize_title"))
{
sanitize_title = !value[0] || !strcasecmp(value, "on") ||
!strcasecmp(value, "yes") || !strcasecmp(value, "true");
}
else if (!strcasecmp(name, "timeout"))
{
if (atoi(value) > 0)
timeout = atoi(value);
}
else if (!strcasecmp(name, "contimeout"))
{
if (atoi(value) > 0)
contimeout = atoi(value);
}
}
}
if (mode == MODE_STREAM)
order = ORDER_CONTROL_DATA;
if (argc == 6 && mode == MODE_STANDARD)
{
char buffer[8192];
int bytes;
if ((fd = cupsTempFd(tmpfilename, sizeof(tmpfilename))) < 0)
{
perror("ERROR: unable to create temporary file");
return (CUPS_BACKEND_FAILED);
}
while ((bytes = fread(buffer, 1, sizeof(buffer), stdin)) > 0)
if (write(fd, buffer, bytes) < bytes)
{
perror("ERROR: unable to write to temporary file");
close(fd);
unlink(tmpfilename);
return (CUPS_BACKEND_FAILED);
}
filename = tmpfilename;
}
else if (argc == 6)
{
filename = NULL;
fd = 0;
}
else
{
filename = argv[6];
fd = open(filename, O_RDONLY);
if (fd == -1)
{
_cupsLangPrintf(stderr, _("ERROR: Unable to open print file %s: %s\n"),
filename, strerror(errno));
return (CUPS_BACKEND_FAILED);
}
}
strlcpy(title, argv[3], sizeof(title));
if (sanitize_title)
{
char *ptr;
for (ptr = title; *ptr; ptr ++)
if (!isalnum(*ptr & 255) && !isspace(*ptr & 255))
*ptr = '_';
}
if (argc > 6)
{
if (manual_copies)
{
manual_copies = atoi(argv[4]);
copies = 1;
}
else
{
manual_copies = 1;
copies = atoi(argv[4]);
}
status = lpd_queue(hostname, port, resource + 1, fd, mode,
username, title, copies,
banner, format, order, reserve, manual_copies,
timeout, contimeout);
if (!status)
fprintf(stderr, "PAGE: 1 %d\n", atoi(argv[4]));
}
else
status = lpd_queue(hostname, port, resource + 1, fd, mode,
username, title, 1,
banner, format, order, reserve, 1,
timeout, contimeout);
if (tmpfilename[0])
unlink(tmpfilename);
if (fd)
close(fd);
return (status);
}
static int
lpd_command(int fd,
int timeout,
char *format,
...)
{
va_list ap;
char buf[1024];
int bytes;
char status;
if (abort_job)
return (-1);
va_start(ap, format);
bytes = vsnprintf(buf, sizeof(buf), format, ap);
va_end(ap);
fprintf(stderr, "DEBUG: lpd_command %2.2x %s", buf[0], buf + 1);
fprintf(stderr, "DEBUG: Sending command string (%d bytes)...\n", bytes);
if (lpd_write(fd, buf, bytes) < bytes)
{
perror("ERROR: Unable to send LPD command");
return (-1);
}
fputs("DEBUG: Reading command status...\n", stderr);
alarm(timeout);
if (recv(fd, &status, 1, 0) < 1)
{
_cupsLangPrintf(stderr,
_("WARNING: Remote host did not respond with command "
"status byte after %d seconds!\n"), timeout);
status = errno;
}
alarm(0);
fprintf(stderr, "DEBUG: lpd_command returning %d\n", status);
return (status);
}
static int
lpd_queue(const char *hostname,
int port,
const char *printer,
int print_fd,
int mode,
const char *user,
const char *title,
int copies,
int banner,
int format,
int order,
int reserve,
int manual_copies,
int timeout,
int contimeout)
{
char localhost[255];
int error;
struct stat filestats;
int lport;
int fd;
char control[10240],
*cptr;
char status;
char portname[255];
int delay;
char addrname[256];
http_addrlist_t *addrlist,
*addr;
int copy;
time_t start_time;
int recoverable;
size_t nbytes;
off_t tbytes;
char buffer[32768];
#if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
struct sigaction action;
#endif
#ifdef HAVE_SIGSET
sigset(SIGALRM, lpd_timeout);
#elif defined(HAVE_SIGACTION)
memset(&action, 0, sizeof(action));
sigemptyset(&action.sa_mask);
action.sa_handler = lpd_timeout;
sigaction(SIGALRM, &action, NULL);
#else
signal(SIGALRM, lpd_timeout);
#endif
sprintf(portname, "%d", port);
if ((addrlist = httpAddrGetList(hostname, AF_UNSPEC, portname)) == NULL)
{
_cupsLangPrintf(stderr, _("ERROR: Unable to locate printer \'%s\'!\n"),
hostname);
return (CUPS_BACKEND_STOP);
}
recoverable = 0;
start_time = time(NULL);
while (!abort_job)
{
fputs("STATE: +connecting-to-device\n", stderr);
_cupsLangPrintf(stderr,
_("INFO: Attempting to connect to host %s for printer %s\n"),
hostname, printer);
for (lport = reserve == RESERVE_RFC1179 ? 732 : 1024, addr = addrlist,
delay = 5;;
addr = addr->next)
{
if (abort_job)
{
httpAddrFreeList(addrlist);
return (CUPS_BACKEND_FAILED);
}
if (!addr)
addr = addrlist;
lport --;
if (lport < 721 && reserve == RESERVE_RFC1179)
lport = 731;
else if (lport < 1)
lport = 1023;
#ifdef HAVE_GETEUID
if (geteuid() || !reserve)
#else
if (getuid() || !reserve)
#endif
{
if ((fd = socket(addr->addr.addr.sa_family, SOCK_STREAM, 0)) < 0)
{
perror("ERROR: Unable to create socket");
sleep(1);
continue;
}
lport = 0;
}
else
{
if ((fd = rresvport_af(&lport, addr->addr.addr.sa_family)) < 0)
{
perror("ERROR: Unable to reserve port");
sleep(1);
continue;
}
}
if (abort_job)
{
httpAddrFreeList(addrlist);
close(fd);
return (CUPS_BACKEND_FAILED);
}
if (!connect(fd, &(addr->addr.addr), httpAddrLength(&(addr->addr))))
break;
error = errno;
close(fd);
fd = -1;
if (addr->next)
continue;
if (getenv("CLASS") != NULL)
{
_cupsLangPuts(stderr,
_("INFO: Unable to contact printer, queuing on next "
"printer in class...\n"));
httpAddrFreeList(addrlist);
sleep(5);
return (CUPS_BACKEND_FAILED);
}
if (error == ECONNREFUSED || error == EHOSTDOWN ||
error == EHOSTUNREACH)
{
if (contimeout && (time(NULL) - start_time) > contimeout)
{
_cupsLangPuts(stderr, _("ERROR: Printer not responding!\n"));
return (CUPS_BACKEND_FAILED);
}
recoverable = 1;
_cupsLangPrintf(stderr,
_("WARNING: recoverable: Network host \'%s\' is busy; "
"will retry in %d seconds...\n"), hostname, delay);
sleep(delay);
if (delay < 30)
delay += 5;
}
else if (error == EADDRINUSE)
{
sleep(1);
}
else
{
recoverable = 1;
fprintf(stderr, "DEBUG: Connection error: %s\n", strerror(errno));
_cupsLangPuts(stderr,
_("ERROR: recoverable: Unable to connect to printer; "
"will retry in 30 seconds...\n"));
sleep(30);
}
}
if (recoverable)
{
fputs("INFO: recovered: \n", stderr);
sleep(5);
}
fputs("STATE: -connecting-to-device\n", stderr);
_cupsLangPrintf(stderr, _("INFO: Connected to %s...\n"), hostname);
#ifdef AF_INET6
if (addr->addr.addr.sa_family == AF_INET6)
fprintf(stderr, "DEBUG: Connected to [%s]:%d (IPv6) (local port %d)...\n",
httpAddrString(&addr->addr, addrname, sizeof(addrname)),
ntohs(addr->addr.ipv6.sin6_port), lport);
else
#endif
if (addr->addr.addr.sa_family == AF_INET)
fprintf(stderr, "DEBUG: Connected to %s:%d (IPv4) (local port %d)...\n",
httpAddrString(&addr->addr, addrname, sizeof(addrname)),
ntohs(addr->addr.ipv4.sin_port), lport);
if (print_fd)
{
if (fstat(print_fd, &filestats))
{
httpAddrFreeList(addrlist);
close(fd);
perror("ERROR: unable to stat print file");
return (CUPS_BACKEND_FAILED);
}
filestats.st_size *= manual_copies;
}
else
{
#ifdef _LARGEFILE_SOURCE
filestats.st_size = (size_t)(999999999999.0);
#else
filestats.st_size = 2147483647;
#endif
}
if (lpd_command(fd, timeout, "\002%s\n",
printer))
{
httpAddrFreeList(addrlist);
close(fd);
return (CUPS_BACKEND_FAILED);
}
httpGetHostname(NULL, localhost, sizeof(localhost));
snprintf(control, sizeof(control),
"H%.31s\n"
"P%.31s\n"
"J%.99s\n",
localhost, user, title);
cptr = control + strlen(control);
if (banner)
{
snprintf(cptr, sizeof(control) - (cptr - control),
"C%.31s\n"
"L%s\n",
localhost, user);
cptr += strlen(cptr);
}
while (copies > 0)
{
snprintf(cptr, sizeof(control) - (cptr - control), "%cdfA%03d%.15s\n",
format, (int)getpid() % 1000, localhost);
cptr += strlen(cptr);
copies --;
}
snprintf(cptr, sizeof(control) - (cptr - control),
"UdfA%03d%.15s\n"
"N%.131s\n",
(int)getpid() % 1000, localhost, title);
fprintf(stderr, "DEBUG: Control file is:\n%s", control);
if (order == ORDER_CONTROL_DATA)
{
if (lpd_command(fd, timeout, "\002%d cfA%03.3d%.15s\n", strlen(control),
(int)getpid() % 1000, localhost))
{
httpAddrFreeList(addrlist);
close(fd);
return (CUPS_BACKEND_FAILED);
}
_cupsLangPrintf(stderr, _("INFO: Sending control file (%u bytes)\n"),
(unsigned)strlen(control));
if (lpd_write(fd, control, strlen(control) + 1) < (strlen(control) + 1))
{
status = errno;
perror("ERROR: Unable to write control file");
}
else
{
alarm(timeout);
if (read(fd, &status, 1) < 1)
{
_cupsLangPrintf(stderr,
_("WARNING: Remote host did not respond with control "
"status byte after %d seconds!\n"), timeout);
status = errno;
}
alarm(0);
}
if (status != 0)
_cupsLangPrintf(stderr,
_("ERROR: Remote host did not accept control file "
"(%d)\n"), status);
else
_cupsLangPuts(stderr, _("INFO: Control file sent successfully\n"));
}
else
status = 0;
if (status == 0)
{
if (lpd_command(fd, timeout, "\003" CUPS_LLFMT " dfA%03.3d%.15s\n",
CUPS_LLCAST filestats.st_size, (int)getpid() % 1000,
localhost))
{
httpAddrFreeList(addrlist);
close(fd);
return (CUPS_BACKEND_FAILED);
}
_cupsLangPrintf(stderr,
#ifdef HAVE_LONG_LONG
_("INFO: Sending data file (%lld bytes)\n"),
#else
_("INFO: Sending data file (%ld bytes)\n"),
#endif
CUPS_LLCAST filestats.st_size);
tbytes = 0;
for (copy = 0; copy < manual_copies; copy ++)
{
lseek(print_fd, 0, SEEK_SET);
while ((nbytes = read(print_fd, buffer, sizeof(buffer))) > 0)
{
_cupsLangPrintf(stderr,
_("INFO: Spooling LPR job, %.0f%% complete...\n"),
100.0 * tbytes / filestats.st_size);
if (lpd_write(fd, buffer, nbytes) < nbytes)
{
perror("ERROR: Unable to send print file to printer");
break;
}
else
tbytes += nbytes;
}
}
if (mode == MODE_STANDARD)
{
if (tbytes < filestats.st_size)
status = errno;
else if (lpd_write(fd, "", 1) < 1)
{
perror("ERROR: Unable to send trailing nul to printer");
status = errno;
}
else
{
alarm(timeout);
if (recv(fd, &status, 1, 0) < 1)
{
_cupsLangPrintf(stderr,
_("WARNING: Remote host did not respond with data "
"status byte after %d seconds!\n"), timeout);
status = 0;
}
alarm(0);
}
}
else
status = 0;
if (status != 0)
_cupsLangPrintf(stderr,
_("ERROR: Remote host did not accept data file (%d)\n"),
status);
else
_cupsLangPuts(stderr, _("INFO: Data file sent successfully\n"));
}
if (status == 0 && order == ORDER_DATA_CONTROL)
{
if (lpd_command(fd, timeout, "\002%d cfA%03.3d%.15s\n", strlen(control),
(int)getpid() % 1000, localhost))
{
httpAddrFreeList(addrlist);
close(fd);
return (CUPS_BACKEND_FAILED);
}
_cupsLangPrintf(stderr, _("INFO: Sending control file (%lu bytes)\n"),
(unsigned long)strlen(control));
if (lpd_write(fd, control, strlen(control) + 1) < (strlen(control) + 1))
{
status = errno;
perror("ERROR: Unable to write control file");
}
else
{
alarm(timeout);
if (read(fd, &status, 1) < 1)
{
_cupsLangPrintf(stderr,
_("WARNING: Remote host did not respond with control "
"status byte after %d seconds!\n"), timeout);
status = errno;
}
alarm(0);
}
if (status != 0)
_cupsLangPrintf(stderr,
_("ERROR: Remote host did not accept control file "
"(%d)\n"), status);
else
_cupsLangPuts(stderr, _("INFO: Control file sent successfully\n"));
}
close(fd);
if (status == 0)
{
httpAddrFreeList(addrlist);
return (CUPS_BACKEND_OK);
}
sleep(30);
}
httpAddrFreeList(addrlist);
return (CUPS_BACKEND_FAILED);
}
static void
lpd_timeout(int sig)
{
(void)sig;
#if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
signal(SIGALRM, lpd_timeout);
#endif
}
static int
lpd_write(int lpd_fd,
char *buffer,
int length)
{
int bytes,
total;
if (abort_job)
return (-1);
total = 0;
while ((bytes = send(lpd_fd, buffer, length - total, 0)) >= 0)
{
total += bytes;
buffer += bytes;
if (total == length)
break;
}
if (bytes < 0)
return (-1);
else
return (length);
}
#ifndef HAVE_RRESVPORT_AF
static int
rresvport_af(int *port,
int family)
{
http_addr_t addr;
int fd;
if ((fd = socket(family, SOCK_STREAM, 0)) < 0)
return (-1);
memset(&addr, 0, sizeof(addr));
addr.addr.sa_family = family;
while (*port > 511)
{
# ifdef AF_INET6
if (family == AF_INET6)
addr.ipv6.sin6_port = htons(*port);
else
# endif
addr.ipv4.sin_port = htons(*port);
if (!bind(fd, (struct sockaddr *)&addr, sizeof(addr)))
return (fd);
if (errno != EADDRINUSE)
{
# ifdef WIN32
closesocket(fd);
# else
close(fd);
# endif
return (-1);
}
(*port)--;
}
# ifdef WIN32
closesocket(fd);
# else
close(fd);
# endif
return (-1);
}
#endif
static void
sigterm_handler(int sig)
{
(void)sig;
abort_job = 1;
}