]> git.ipfire.org Git - thirdparty/cups.git/blame - backend/lpd.c
Merge changes from CUPS 1.5svn-r8842.
[thirdparty/cups.git] / backend / lpd.c
CommitLineData
ef416fc2 1/*
b19ccc9e 2 * "$Id: lpd.c 7740 2008-07-14 23:58:05Z mike $"
ef416fc2 3 *
4 * Line Printer Daemon backend for the Common UNIX Printing System (CUPS).
5 *
8b116e60 6 * Copyright 2007-2009 by Apple Inc.
f42414bf 7 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
ef416fc2 8 *
9 * These coded instructions, statements, and computer programs are the
bc44d920 10 * property of Apple Inc. and are protected by Federal copyright
11 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
ef416fc2 12 * "LICENSE" which should have been included with this file. If this
bc44d920 13 * file is missing or damaged, see the license at "http://www.cups.org/".
ef416fc2 14 *
15 * This file is subject to the Apple OS-Developed Software exception.
16 *
17 * Contents:
18 *
19 * main() - Send a file to the printer or server.
20 * lpd_command() - Send an LPR command sequence and wait for a reply.
21 * lpd_queue() - Queue a file using the Line Printer Daemon protocol.
22 * lpd_timeout() - Handle timeout alarms...
23 * lpd_write() - Write a buffer of data to an LPD server.
24 * rresvport_af() - A simple implementation of rresvport_af().
25 * sigterm_handler() - Handle 'terminate' signals that stop the backend.
26 */
27
28/*
29 * Include necessary headers.
30 */
31
ef416fc2 32#include <cups/http-private.h>
7a14d768 33#include "backend-private.h"
ef416fc2 34#include <stdarg.h>
ef416fc2 35#include <sys/types.h>
36#include <sys/stat.h>
ef416fc2 37
38#ifdef WIN32
39# include <winsock.h>
40#else
41# include <sys/socket.h>
42# include <netinet/in.h>
43# include <arpa/inet.h>
44# include <netdb.h>
45#endif /* WIN32 */
fa73b229 46#ifdef __APPLE__
47# include <CoreFoundation/CFNumber.h>
48# include <CoreFoundation/CFPreferences.h>
49#endif /* __APPLE__ */
ef416fc2 50
51
52/*
53 * Globals...
54 */
55
56static char tmpfilename[1024] = ""; /* Temporary spool file name */
57static int abort_job = 0; /* Non-zero if we get SIGTERM */
58
59
f42414bf 60/*
61 * Print mode...
62 */
63
64#define MODE_STANDARD 0 /* Queue a copy */
65#define MODE_STREAM 1 /* Stream a copy */
66
67
ef416fc2 68/*
69 * The order for control and data files in LPD requests...
70 */
71
72#define ORDER_CONTROL_DATA 0 /* Control file first, then data */
73#define ORDER_DATA_CONTROL 1 /* Data file first, then control */
74
75
76/*
77 * What to reserve...
78 */
79
80#define RESERVE_NONE 0 /* Don't reserve a priviledged port */
81#define RESERVE_RFC1179 1 /* Reserve port 721-731 */
82#define RESERVE_ANY 2 /* Reserve port 1-1023 */
83
84
85/*
86 * Local functions...
87 */
88
89static int lpd_command(int lpd_fd, int timeout, char *format, ...);
90static int lpd_queue(const char *hostname, int port, const char *printer,
f42414bf 91 int print_fd, int mode, const char *user,
92 const char *title, int copies, int banner,
93 int format, int order, int reserve,
fa73b229 94 int manual_copies, int timeout, int contimeout);
ef416fc2 95static void lpd_timeout(int sig);
96static int lpd_write(int lpd_fd, char *buffer, int length);
97#ifndef HAVE_RRESVPORT_AF
98static int rresvport_af(int *port, int family);
99#endif /* !HAVE_RRESVPORT_AF */
100static void sigterm_handler(int sig);
101
102
103/*
104 * 'main()' - Send a file to the printer or server.
105 *
106 * Usage:
107 *
108 * printer-uri job-id user title copies options [file]
109 */
110
111int /* O - Exit status */
112main(int argc, /* I - Number of command-line arguments (6 or 7) */
113 char *argv[]) /* I - Command-line arguments */
114{
1f0275e3 115 const char *device_uri; /* Device URI */
acb056cb 116 char scheme[255], /* Scheme in URI */
7a14d768
MS
117 hostname[1024], /* Hostname */
118 username[255], /* Username info */
119 resource[1024], /* Resource info (printer name) */
120 *options, /* Pointer to options */
121 *name, /* Name of option */
122 *value, /* Value of option */
123 sep, /* Separator character */
124 *filename, /* File to print */
125 title[256]; /* Title string */
126 int port; /* Port number */
127 int fd; /* Print file */
128 int status; /* Status of LPD job */
129 int mode; /* Print mode */
130 int banner; /* Print banner page? */
131 int format; /* Print format */
132 int order; /* Order of control/data files */
133 int reserve; /* Reserve priviledged port? */
134 int sanitize_title; /* Sanitize title string? */
135 int manual_copies, /* Do manual copies? */
136 timeout, /* Timeout */
137 contimeout, /* Connection timeout */
138 copies; /* Number of copies */
ef416fc2 139#if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
7a14d768 140 struct sigaction action; /* Actions for POSIX signals */
ef416fc2 141#endif /* HAVE_SIGACTION && !HAVE_SIGSET */
142
143
144 /*
145 * Make sure status messages are not buffered...
146 */
147
148 setbuf(stderr, NULL);
149
150 /*
151 * Ignore SIGPIPE and catch SIGTERM signals...
152 */
153
154#ifdef HAVE_SIGSET
155 sigset(SIGPIPE, SIG_IGN);
156 sigset(SIGTERM, sigterm_handler);
157#elif defined(HAVE_SIGACTION)
158 memset(&action, 0, sizeof(action));
159 action.sa_handler = SIG_IGN;
160 sigaction(SIGPIPE, &action, NULL);
161
162 sigemptyset(&action.sa_mask);
163 sigaddset(&action.sa_mask, SIGTERM);
164 action.sa_handler = sigterm_handler;
165 sigaction(SIGTERM, &action, NULL);
166#else
167 signal(SIGPIPE, SIG_IGN);
168 signal(SIGTERM, sigterm_handler);
169#endif /* HAVE_SIGSET */
170
171 /*
172 * Check command-line...
173 */
174
175 if (argc == 1)
176 {
8b450588
MS
177 printf("network lpd \"Unknown\" \"%s\"\n",
178 _cupsLangString(cupsLangDefault(), _("LPD/LPR Host or Printer")));
ef416fc2 179 return (CUPS_BACKEND_OK);
180 }
181 else if (argc < 6 || argc > 7)
182 {
db1f069b
MS
183 _cupsLangPrintf(stderr,
184 _("Usage: %s job-id user title copies options [file]\n"),
185 argv[0]);
ef416fc2 186 return (CUPS_BACKEND_FAILED);
187 }
188
ef416fc2 189 /*
190 * Extract the hostname and printer name from the URI...
191 */
192
1f0275e3
MS
193 if ((device_uri = cupsBackendDeviceURI(argv)) == NULL)
194 return (CUPS_BACKEND_FAILED);
195
acb056cb
MS
196 httpSeparateURI(HTTP_URI_CODING_ALL, device_uri, scheme, sizeof(scheme),
197 username, sizeof(username), hostname, sizeof(hostname), &port,
ef416fc2 198 resource, sizeof(resource));
199
a41f09e2
MS
200 if (!port)
201 port = 515; /* Default to port 515 */
202
ef416fc2 203 if (!username[0])
204 {
205 /*
206 * If no username is in the device URI, then use the print job user...
207 */
208
209 strlcpy(username, argv[2], sizeof(username));
210 }
211
212 /*
213 * See if there are any options...
214 */
215
f42414bf 216 mode = MODE_STANDARD;
fa73b229 217 banner = 0;
218 format = 'l';
219 order = ORDER_CONTROL_DATA;
220 reserve = RESERVE_ANY;
221 manual_copies = 1;
222 timeout = 300;
223 contimeout = 7 * 24 * 60 * 60;
ef416fc2 224
fa73b229 225#ifdef __APPLE__
c0e1af83 226 /*
227 * We want to pass utf-8 characters, not re-map them (3071945)
228 */
229
fa73b229 230 sanitize_title = 0;
231
c0e1af83 232 /*
233 * Get the default timeout from a system preference...
234 */
235
fa73b229 236 {
237 CFPropertyListRef pvalue; /* Preference value */
238 SInt32 toval; /* Timeout value */
239
240
241 pvalue = CFPreferencesCopyValue(CFSTR("timeout"),
242 CFSTR("com.apple.print.backends"),
243 kCFPreferencesAnyUser,
244 kCFPreferencesCurrentHost);
245 if (pvalue)
246 {
247 if (CFGetTypeID(pvalue) == CFNumberGetTypeID())
248 {
249 CFNumberGetValue(pvalue, kCFNumberSInt32Type, &toval);
250 contimeout = (int)toval;
251 }
252
253 CFRelease(pvalue);
254 }
255 }
256#else
257 sanitize_title = 1;
258#endif /* __APPLE__ */
ef416fc2 259
260 if ((options = strchr(resource, '?')) != NULL)
261 {
262 /*
263 * Yup, terminate the device name string and move to the first
264 * character of the options...
265 */
266
267 *options++ = '\0';
268
269 /*
270 * Parse options...
271 */
272
273 while (*options)
274 {
275 /*
276 * Get the name...
277 */
278
db1f069b 279 name = options;
ef416fc2 280
db1f069b
MS
281 while (*options && *options != '=' && *options != '+' && *options != '&')
282 options ++;
283
284 if ((sep = *options) != '\0')
285 *options++ = '\0';
286
287 if (sep == '=')
ef416fc2 288 {
289 /*
290 * Get the value...
291 */
292
db1f069b 293 value = options;
ef416fc2 294
db1f069b 295 while (*options && *options != '+' && *options != '&')
ef416fc2 296 options ++;
db1f069b
MS
297
298 if (*options)
299 *options++ = '\0';
ef416fc2 300 }
301 else
db1f069b 302 value = (char *)"";
ef416fc2 303
304 /*
305 * Process the option...
306 */
307
fa73b229 308 if (!strcasecmp(name, "banner"))
ef416fc2 309 {
310 /*
311 * Set the banner...
312 */
313
fa73b229 314 banner = !value[0] || !strcasecmp(value, "on") ||
315 !strcasecmp(value, "yes") || !strcasecmp(value, "true");
ef416fc2 316 }
fa73b229 317 else if (!strcasecmp(name, "format") && value[0])
ef416fc2 318 {
319 /*
320 * Set output format...
321 */
322
fa73b229 323 if (strchr("cdfglnoprtv", value[0]))
ef416fc2 324 format = value[0];
325 else
db1f069b
MS
326 _cupsLangPrintf(stderr, _("ERROR: Unknown format character \"%c\"\n"),
327 value[0]);
ef416fc2 328 }
f42414bf 329 else if (!strcasecmp(name, "mode") && value[0])
330 {
331 /*
332 * Set control/data order...
333 */
334
335 if (!strcasecmp(value, "standard"))
bc44d920 336 mode = MODE_STANDARD;
f42414bf 337 else if (!strcasecmp(value, "stream"))
bc44d920 338 mode = MODE_STREAM;
f42414bf 339 else
db1f069b
MS
340 _cupsLangPrintf(stderr, _("ERROR: Unknown print mode \"%s\"\n"),
341 value);
f42414bf 342 }
fa73b229 343 else if (!strcasecmp(name, "order") && value[0])
ef416fc2 344 {
345 /*
346 * Set control/data order...
347 */
348
fa73b229 349 if (!strcasecmp(value, "control,data"))
ef416fc2 350 order = ORDER_CONTROL_DATA;
fa73b229 351 else if (!strcasecmp(value, "data,control"))
ef416fc2 352 order = ORDER_DATA_CONTROL;
353 else
db1f069b
MS
354 _cupsLangPrintf(stderr, _("ERROR: Unknown file order \"%s\"\n"),
355 value);
ef416fc2 356 }
fa73b229 357 else if (!strcasecmp(name, "reserve"))
ef416fc2 358 {
359 /*
360 * Set port reservation mode...
361 */
362
fa73b229 363 if (!value[0] || !strcasecmp(value, "on") ||
364 !strcasecmp(value, "yes") || !strcasecmp(value, "true") ||
ef416fc2 365 !strcasecmp(value, "rfc1179"))
366 reserve = RESERVE_RFC1179;
367 else if (!strcasecmp(value, "any"))
368 reserve = RESERVE_ANY;
369 else
370 reserve = RESERVE_NONE;
371 }
fa73b229 372 else if (!strcasecmp(name, "manual_copies"))
ef416fc2 373 {
374 /*
375 * Set manual copies...
376 */
377
fa73b229 378 manual_copies = !value[0] || !strcasecmp(value, "on") ||
379 !strcasecmp(value, "yes") || !strcasecmp(value, "true");
ef416fc2 380 }
fa73b229 381 else if (!strcasecmp(name, "sanitize_title"))
ef416fc2 382 {
383 /*
384 * Set sanitize title...
385 */
386
fa73b229 387 sanitize_title = !value[0] || !strcasecmp(value, "on") ||
8b116e60 388 !strcasecmp(value, "yes") || !strcasecmp(value, "true");
ef416fc2 389 }
fa73b229 390 else if (!strcasecmp(name, "timeout"))
ef416fc2 391 {
392 /*
393 * Set the timeout...
394 */
395
396 if (atoi(value) > 0)
397 timeout = atoi(value);
398 }
fa73b229 399 else if (!strcasecmp(name, "contimeout"))
400 {
401 /*
c0e1af83 402 * Set the connection timeout...
fa73b229 403 */
404
405 if (atoi(value) > 0)
406 contimeout = atoi(value);
407 }
ef416fc2 408 }
409 }
410
f42414bf 411 if (mode == MODE_STREAM)
412 order = ORDER_CONTROL_DATA;
413
414 /*
415 * If we have 7 arguments, print the file named on the command-line.
416 * Otherwise, copy stdin to a temporary file and print the temporary
417 * file.
418 */
419
420 if (argc == 6 && mode == MODE_STANDARD)
421 {
422 /*
423 * Copy stdin to a temporary file...
424 */
425
e07d4801
MS
426 http_addrlist_t *addrlist; /* Address list */
427 int snmp_fd; /* SNMP socket */
f42414bf 428
429
acb056cb
MS
430 fputs("STATE: +connecting-to-device\n", stderr);
431 fprintf(stderr, "DEBUG: Looking up \"%s\"...\n", hostname);
432
e07d4801
MS
433 if ((addrlist = httpAddrGetList(hostname, AF_UNSPEC, "1")) == NULL)
434 {
435 _cupsLangPrintf(stderr, _("ERROR: Unable to locate printer \'%s\'!\n"),
436 hostname);
437 return (CUPS_BACKEND_STOP);
438 }
439
440 snmp_fd = _cupsSNMPOpen(addrlist->addr.addr.sa_family);
441
f42414bf 442 if ((fd = cupsTempFd(tmpfilename, sizeof(tmpfilename))) < 0)
443 {
080811b1 444 _cupsLangPrintError(_("ERROR: Unable to create temporary file"));
f42414bf 445 return (CUPS_BACKEND_FAILED);
446 }
447
8b116e60
MS
448 _cupsLangPuts(stderr, _("INFO: Copying print data...\n"));
449
4e6f60f0 450 backendRunLoop(-1, fd, snmp_fd, &(addrlist->addr), 0, backendNetworkSideCB);
e07d4801
MS
451
452 if (snmp_fd >= 0)
453 _cupsSNMPClose(snmp_fd);
454
455 httpAddrFreeList(addrlist);
f42414bf 456 }
457 else if (argc == 6)
458 {
459 /*
460 * Stream from stdin...
461 */
462
463 filename = NULL;
464 fd = 0;
465 }
466 else
467 {
468 filename = argv[6];
469 fd = open(filename, O_RDONLY);
470
471 if (fd == -1)
472 {
db1f069b
MS
473 _cupsLangPrintf(stderr, _("ERROR: Unable to open print file %s: %s\n"),
474 filename, strerror(errno));
f42414bf 475 return (CUPS_BACKEND_FAILED);
476 }
477 }
478
ef416fc2 479 /*
480 * Sanitize the document title...
481 */
482
483 strlcpy(title, argv[3], sizeof(title));
484
485 if (sanitize_title)
486 {
487 /*
488 * Sanitize the title string so that we don't cause problems on
489 * the remote end...
490 */
491
db1f069b
MS
492 char *ptr;
493
ef416fc2 494 for (ptr = title; *ptr; ptr ++)
495 if (!isalnum(*ptr & 255) && !isspace(*ptr & 255))
496 *ptr = '_';
497 }
498
499 /*
500 * Queue the job...
501 */
502
503 if (argc > 6)
504 {
505 if (manual_copies)
506 {
507 manual_copies = atoi(argv[4]);
508 copies = 1;
509 }
510 else
511 {
512 manual_copies = 1;
513 copies = atoi(argv[4]);
514 }
515
f42414bf 516 status = lpd_queue(hostname, port, resource + 1, fd, mode,
ef416fc2 517 username, title, copies,
fa73b229 518 banner, format, order, reserve, manual_copies,
519 timeout, contimeout);
ef416fc2 520
521 if (!status)
522 fprintf(stderr, "PAGE: 1 %d\n", atoi(argv[4]));
523 }
524 else
f42414bf 525 status = lpd_queue(hostname, port, resource + 1, fd, mode,
ef416fc2 526 username, title, 1,
fa73b229 527 banner, format, order, reserve, 1,
528 timeout, contimeout);
ef416fc2 529
530 /*
531 * Remove the temporary file if necessary...
532 */
533
534 if (tmpfilename[0])
535 unlink(tmpfilename);
536
f42414bf 537 if (fd)
538 close(fd);
539
ef416fc2 540 /*
541 * Return the queue status...
542 */
543
544 return (status);
545}
546
547
548/*
549 * 'lpd_command()' - Send an LPR command sequence and wait for a reply.
550 */
551
552static int /* O - Status of command */
553lpd_command(int fd, /* I - Socket connection to LPD host */
554 int timeout, /* I - Seconds to wait for a response */
555 char *format, /* I - printf()-style format string */
556 ...) /* I - Additional args as necessary */
557{
558 va_list ap; /* Argument pointer */
559 char buf[1024]; /* Output buffer */
560 int bytes; /* Number of bytes to output */
561 char status; /* Status from command */
562
563
564 /*
565 * Don't try to send commands if the job has been cancelled...
566 */
567
568 if (abort_job)
569 return (-1);
570
571 /*
572 * Format the string...
573 */
574
575 va_start(ap, format);
576 bytes = vsnprintf(buf, sizeof(buf), format, ap);
577 va_end(ap);
578
579 fprintf(stderr, "DEBUG: lpd_command %2.2x %s", buf[0], buf + 1);
580
581 /*
582 * Send the command...
583 */
584
585 fprintf(stderr, "DEBUG: Sending command string (%d bytes)...\n", bytes);
586
587 if (lpd_write(fd, buf, bytes) < bytes)
588 {
080811b1 589 _cupsLangPrintError(_("ERROR: Unable to send LPD command"));
ef416fc2 590 return (-1);
591 }
592
593 /*
594 * Read back the status from the command and return it...
595 */
596
c0e1af83 597 fputs("DEBUG: Reading command status...\n", stderr);
ef416fc2 598
599 alarm(timeout);
600
601 if (recv(fd, &status, 1, 0) < 1)
602 {
db1f069b
MS
603 _cupsLangPrintf(stderr,
604 _("WARNING: Remote host did not respond with command "
605 "status byte after %d seconds!\n"), timeout);
ef416fc2 606 status = errno;
607 }
608
609 alarm(0);
610
611 fprintf(stderr, "DEBUG: lpd_command returning %d\n", status);
612
613 return (status);
614}
615
616
617/*
618 * 'lpd_queue()' - Queue a file using the Line Printer Daemon protocol.
619 */
620
621static int /* O - Zero on success, non-zero on failure */
622lpd_queue(const char *hostname, /* I - Host to connect to */
623 int port, /* I - Port to connect on */
624 const char *printer, /* I - Printer/queue name */
f42414bf 625 int print_fd, /* I - File to print */
626 int mode, /* I - Print mode */
ef416fc2 627 const char *user, /* I - Requesting user */
628 const char *title, /* I - Job title */
629 int copies, /* I - Number of copies */
630 int banner, /* I - Print LPD banner? */
631 int format, /* I - Format specifier */
632 int order, /* I - Order of data/control files */
633 int reserve, /* I - Reserve ports? */
634 int manual_copies, /* I - Do copies by hand... */
fa73b229 635 int timeout, /* I - Timeout... */
636 int contimeout) /* I - Connection timeout */
ef416fc2 637{
ef416fc2 638 char localhost[255]; /* Local host name */
639 int error; /* Error number */
640 struct stat filestats; /* File statistics */
641 int lport; /* LPD connection local port */
642 int fd; /* LPD socket */
643 char control[10240], /* LPD control 'file' */
644 *cptr; /* Pointer into control file string */
645 char status; /* Status byte from command */
646 char portname[255]; /* Port name */
c0e1af83 647 int delay; /* Delay for retries... */
26d47ec6 648 char addrname[256]; /* Address name */
ef416fc2 649 http_addrlist_t *addrlist, /* Address list */
650 *addr; /* Socket address */
426c6a59
MS
651 int snmp_fd, /* SNMP socket */
652 have_supplies; /* Printer supports supply levels? */
ef416fc2 653 int copy; /* Copies written */
fa73b229 654 time_t start_time; /* Time of first connect */
fa73b229 655 int recoverable; /* Recoverable error shown? */
ef416fc2 656 size_t nbytes; /* Number of bytes written */
657 off_t tbytes; /* Total bytes written */
a74454a7 658 char buffer[32768]; /* Output buffer */
ef416fc2 659#if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
660 struct sigaction action; /* Actions for POSIX signals */
661#endif /* HAVE_SIGACTION && !HAVE_SIGSET */
662
663
664 /*
665 * Setup an alarm handler for timeouts...
666 */
667
668#ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
669 sigset(SIGALRM, lpd_timeout);
670#elif defined(HAVE_SIGACTION)
671 memset(&action, 0, sizeof(action));
672
673 sigemptyset(&action.sa_mask);
674 action.sa_handler = lpd_timeout;
675 sigaction(SIGALRM, &action, NULL);
676#else
677 signal(SIGALRM, lpd_timeout);
678#endif /* HAVE_SIGSET */
679
680 /*
681 * Find the printer...
682 */
683
684 sprintf(portname, "%d", port);
685
acb056cb 686 fputs("STATE: +connecting-to-device\n", stderr);
1340db2d
MS
687 fprintf(stderr, "DEBUG: Looking up \"%s\"...\n", hostname);
688
ef416fc2 689 if ((addrlist = httpAddrGetList(hostname, AF_UNSPEC, portname)) == NULL)
690 {
db1f069b
MS
691 _cupsLangPrintf(stderr, _("ERROR: Unable to locate printer \'%s\'!\n"),
692 hostname);
ef416fc2 693 return (CUPS_BACKEND_STOP);
694 }
695
fa73b229 696 /*
c0e1af83 697 * Remember when we started trying to connect to the printer...
fa73b229 698 */
699
fa73b229 700 recoverable = 0;
fa73b229 701 start_time = time(NULL);
702
ef416fc2 703 /*
704 * Loop forever trying to print the file...
705 */
706
707 while (!abort_job)
708 {
709 /*
710 * First try to reserve a port for this connection...
711 */
712
acb056cb
MS
713 fprintf(stderr, "DEBUG: Connecting to %s:%d for printer %s\n", hostname,
714 port, printer);
8b450588 715 _cupsLangPuts(stderr, _("INFO: Connecting to printer...\n"));
ef416fc2 716
c0e1af83 717 for (lport = reserve == RESERVE_RFC1179 ? 732 : 1024, addr = addrlist,
718 delay = 5;;
ef416fc2 719 addr = addr->next)
720 {
721 /*
722 * Stop if this job has been cancelled...
723 */
724
725 if (abort_job)
726 {
727 httpAddrFreeList(addrlist);
728
729 return (CUPS_BACKEND_FAILED);
730 }
731
732 /*
733 * Choose the next priviledged port...
734 */
735
736 if (!addr)
737 addr = addrlist;
738
739 lport --;
740
741 if (lport < 721 && reserve == RESERVE_RFC1179)
742 lport = 731;
743 else if (lport < 1)
744 lport = 1023;
745
746#ifdef HAVE_GETEUID
747 if (geteuid() || !reserve)
748#else
749 if (getuid() || !reserve)
750#endif /* HAVE_GETEUID */
751 {
752 /*
753 * Just create a regular socket...
754 */
755
756 if ((fd = socket(addr->addr.addr.sa_family, SOCK_STREAM, 0)) < 0)
757 {
080811b1 758 _cupsLangPrintError(_("ERROR: Unable to create socket"));
ef416fc2 759 sleep(1);
760
761 continue;
762 }
763
764 lport = 0;
765 }
766 else
767 {
768 /*
769 * We're running as root and want to comply with RFC 1179. Reserve a
770 * priviledged lport between 721 and 731...
771 */
772
773 if ((fd = rresvport_af(&lport, addr->addr.addr.sa_family)) < 0)
774 {
080811b1 775 _cupsLangPrintError(_("ERROR: Unable to reserve port"));
ef416fc2 776 sleep(1);
777
778 continue;
779 }
780 }
781
782 /*
783 * Connect to the printer or server...
784 */
785
786 if (abort_job)
787 {
788 httpAddrFreeList(addrlist);
789
790 close(fd);
791
792 return (CUPS_BACKEND_FAILED);
793 }
794
795 if (!connect(fd, &(addr->addr.addr), httpAddrLength(&(addr->addr))))
796 break;
797
798 error = errno;
799 close(fd);
800 fd = -1;
801
802 if (addr->next)
803 continue;
804
805 if (getenv("CLASS") != NULL)
806 {
807 /*
808 * If the CLASS environment variable is set, the job was submitted
809 * to a class and not to a specific queue. In this case, we want
810 * to abort immediately so that the job can be requeued on the next
811 * available printer in the class.
812 */
813
db1f069b
MS
814 _cupsLangPuts(stderr,
815 _("INFO: Unable to contact printer, queuing on next "
816 "printer in class...\n"));
ef416fc2 817
818 httpAddrFreeList(addrlist);
819
820 /*
821 * Sleep 5 seconds to keep the job from requeuing too rapidly...
822 */
823
824 sleep(5);
825
826 return (CUPS_BACKEND_FAILED);
827 }
828
829 if (error == ECONNREFUSED || error == EHOSTDOWN ||
830 error == EHOSTUNREACH)
831 {
fa73b229 832 if (contimeout && (time(NULL) - start_time) > contimeout)
833 {
db1f069b 834 _cupsLangPuts(stderr, _("ERROR: Printer not responding!\n"));
fa73b229 835 return (CUPS_BACKEND_FAILED);
836 }
837
fa73b229 838 recoverable = 1;
c0e1af83 839
db1f069b
MS
840 _cupsLangPrintf(stderr,
841 _("WARNING: recoverable: Network host \'%s\' is busy; "
842 "will retry in %d seconds...\n"), hostname, delay);
c0e1af83 843
844 sleep(delay);
845
846 if (delay < 30)
847 delay += 5;
ef416fc2 848 }
849 else if (error == EADDRINUSE)
850 {
851 /*
852 * Try on another port...
853 */
854
855 sleep(1);
856 }
857 else
858 {
fa73b229 859 recoverable = 1;
c0e1af83 860
861 fprintf(stderr, "DEBUG: Connection error: %s\n", strerror(errno));
db1f069b
MS
862 _cupsLangPuts(stderr,
863 _("ERROR: recoverable: Unable to connect to printer; "
864 "will retry in 30 seconds...\n"));
c0e1af83 865 sleep(30);
ef416fc2 866 }
867 }
868
fa73b229 869 if (recoverable)
870 {
871 /*
872 * If we've shown a recoverable error make sure the printer proxies
873 * have a chance to see the recovered message. Not pretty but
874 * necessary for now...
875 */
876
877 fputs("INFO: recovered: \n", stderr);
878 sleep(5);
879 }
fa73b229 880
757d2cad 881 fputs("STATE: -connecting-to-device\n", stderr);
8b450588 882 _cupsLangPuts(stderr, _("INFO: Connected to printer...\n"));
26d47ec6 883
884#ifdef AF_INET6
885 if (addr->addr.addr.sa_family == AF_INET6)
886 fprintf(stderr, "DEBUG: Connected to [%s]:%d (IPv6) (local port %d)...\n",
c0e1af83 887 httpAddrString(&addr->addr, addrname, sizeof(addrname)),
888 ntohs(addr->addr.ipv6.sin6_port), lport);
26d47ec6 889 else
890#endif /* AF_INET6 */
891 if (addr->addr.addr.sa_family == AF_INET)
892 fprintf(stderr, "DEBUG: Connected to %s:%d (IPv4) (local port %d)...\n",
c0e1af83 893 httpAddrString(&addr->addr, addrname, sizeof(addrname)),
894 ntohs(addr->addr.ipv4.sin_port), lport);
ef416fc2 895
7a14d768
MS
896 /*
897 * See if the printer supports SNMP...
898 */
899
900 if ((snmp_fd = _cupsSNMPOpen(addr->addr.addr.sa_family)) >= 0)
426c6a59
MS
901 have_supplies = !backendSNMPSupplies(snmp_fd, &(addr->addr), NULL, NULL);
902 else
903 have_supplies = 0;
7a14d768
MS
904
905 /*
906 * Check for side-channel requests...
907 */
908
909 backendCheckSideChannel(snmp_fd, &(addr->addr));
910
ef416fc2 911 /*
912 * Next, open the print file and figure out its size...
913 */
914
f42414bf 915 if (print_fd)
ef416fc2 916 {
c0e1af83 917 /*
918 * Use the size from the print file...
919 */
920
f42414bf 921 if (fstat(print_fd, &filestats))
922 {
923 httpAddrFreeList(addrlist);
924 close(fd);
ef416fc2 925
080811b1 926 _cupsLangPrintError(_("ERROR: unable to stat print file"));
f42414bf 927 return (CUPS_BACKEND_FAILED);
928 }
ef416fc2 929
f42414bf 930 filestats.st_size *= manual_copies;
ef416fc2 931 }
f42414bf 932 else
c0e1af83 933 {
934 /*
935 * Use a "very large value" for the size so that the printer will
936 * keep printing until we close the connection...
937 */
938
f42414bf 939#ifdef _LARGEFILE_SOURCE
940 filestats.st_size = (size_t)(999999999999.0);
941#else
942 filestats.st_size = 2147483647;
943#endif /* _LARGEFILE_SOURCE */
c0e1af83 944 }
ef416fc2 945
946 /*
947 * Send a job header to the printer, specifying no banner page and
948 * literal output...
949 */
950
951 if (lpd_command(fd, timeout, "\002%s\n",
952 printer)) /* Receive print job(s) */
953 {
954 httpAddrFreeList(addrlist);
955 close(fd);
956 return (CUPS_BACKEND_FAILED);
957 }
958
757d2cad 959 httpGetHostname(NULL, localhost, sizeof(localhost));
ef416fc2 960
961 snprintf(control, sizeof(control),
962 "H%.31s\n" /* RFC 1179, Section 7.2 - host name <= 31 chars */
963 "P%.31s\n" /* RFC 1179, Section 7.2 - user name <= 31 chars */
964 "J%.99s\n", /* RFC 1179, Section 7.2 - job name <= 99 chars */
965 localhost, user, title);
966 cptr = control + strlen(control);
967
968 if (banner)
969 {
970 snprintf(cptr, sizeof(control) - (cptr - control),
971 "C%.31s\n" /* RFC 1179, Section 7.2 - class name <= 31 chars */
972 "L%s\n",
973 localhost, user);
974 cptr += strlen(cptr);
975 }
976
977 while (copies > 0)
978 {
979 snprintf(cptr, sizeof(control) - (cptr - control), "%cdfA%03d%.15s\n",
980 format, (int)getpid() % 1000, localhost);
981 cptr += strlen(cptr);
982 copies --;
983 }
984
985 snprintf(cptr, sizeof(control) - (cptr - control),
986 "UdfA%03d%.15s\n"
987 "N%.131s\n", /* RFC 1179, Section 7.2 - sourcefile name <= 131 chars */
988 (int)getpid() % 1000, localhost, title);
989
990 fprintf(stderr, "DEBUG: Control file is:\n%s", control);
991
992 if (order == ORDER_CONTROL_DATA)
993 {
7a14d768
MS
994 /*
995 * Check for side-channel requests...
996 */
997
998 backendCheckSideChannel(snmp_fd, &(addr->addr));
999
1000 /*
1001 * Send the control file...
1002 */
1003
ef416fc2 1004 if (lpd_command(fd, timeout, "\002%d cfA%03.3d%.15s\n", strlen(control),
1005 (int)getpid() % 1000, localhost))
1006 {
1007 httpAddrFreeList(addrlist);
1008 close(fd);
1009
1010 return (CUPS_BACKEND_FAILED);
1011 }
1012
db1f069b
MS
1013 _cupsLangPrintf(stderr, _("INFO: Sending control file (%u bytes)\n"),
1014 (unsigned)strlen(control));
ef416fc2 1015
1016 if (lpd_write(fd, control, strlen(control) + 1) < (strlen(control) + 1))
1017 {
1018 status = errno;
080811b1 1019 _cupsLangPrintError(_("ERROR: Unable to write control file"));
ef416fc2 1020 }
1021 else
1022 {
1023 alarm(timeout);
1024
1025 if (read(fd, &status, 1) < 1)
1026 {
db1f069b
MS
1027 _cupsLangPrintf(stderr,
1028 _("WARNING: Remote host did not respond with control "
1029 "status byte after %d seconds!\n"), timeout);
ef416fc2 1030 status = errno;
1031 }
1032
1033 alarm(0);
1034 }
1035
1036 if (status != 0)
db1f069b
MS
1037 _cupsLangPrintf(stderr,
1038 _("ERROR: Remote host did not accept control file "
1039 "(%d)\n"), status);
ef416fc2 1040 else
db1f069b 1041 _cupsLangPuts(stderr, _("INFO: Control file sent successfully\n"));
ef416fc2 1042 }
1043 else
1044 status = 0;
1045
1046 if (status == 0)
1047 {
7a14d768
MS
1048 /*
1049 * Check for side-channel requests...
1050 */
1051
1052 backendCheckSideChannel(snmp_fd, &(addr->addr));
1053
ef416fc2 1054 /*
1055 * Send the print file...
1056 */
1057
1058 if (lpd_command(fd, timeout, "\003" CUPS_LLFMT " dfA%03.3d%.15s\n",
1059 CUPS_LLCAST filestats.st_size, (int)getpid() % 1000,
1060 localhost))
1061 {
1062 httpAddrFreeList(addrlist);
1063 close(fd);
1064
1065 return (CUPS_BACKEND_FAILED);
1066 }
1067
db1f069b 1068 _cupsLangPrintf(stderr,
c0e1af83 1069#ifdef HAVE_LONG_LONG
db1f069b 1070 _("INFO: Sending data file (%lld bytes)\n"),
c0e1af83 1071#else
db1f069b 1072 _("INFO: Sending data file (%ld bytes)\n"),
c0e1af83 1073#endif /* HAVE_LONG_LONG */
db1f069b 1074 CUPS_LLCAST filestats.st_size);
ef416fc2 1075
1076 tbytes = 0;
1077 for (copy = 0; copy < manual_copies; copy ++)
1078 {
f42414bf 1079 lseek(print_fd, 0, SEEK_SET);
ef416fc2 1080
f42414bf 1081 while ((nbytes = read(print_fd, buffer, sizeof(buffer))) > 0)
ef416fc2 1082 {
db1f069b
MS
1083 _cupsLangPrintf(stderr,
1084 _("INFO: Spooling LPR job, %.0f%% complete...\n"),
1085 100.0 * tbytes / filestats.st_size);
ef416fc2 1086
1087 if (lpd_write(fd, buffer, nbytes) < nbytes)
1088 {
080811b1 1089 _cupsLangPrintError(_("ERROR: Unable to send print file to printer"));
ef416fc2 1090 break;
1091 }
1092 else
1093 tbytes += nbytes;
1094 }
1095 }
1096
f42414bf 1097 if (mode == MODE_STANDARD)
ef416fc2 1098 {
f42414bf 1099 if (tbytes < filestats.st_size)
1100 status = errno;
1101 else if (lpd_write(fd, "", 1) < 1)
1102 {
080811b1 1103 _cupsLangPrintError(_("ERROR: Unable to send trailing nul to printer"));
f42414bf 1104 status = errno;
1105 }
1106 else
1107 {
1108 /*
1109 * Read the status byte from the printer; if we can't read the byte
1110 * back now, we should set status to "errno", however at this point
1111 * we know the printer got the whole file and we don't necessarily
1112 * want to requeue it over and over...
1113 */
ef416fc2 1114
f42414bf 1115 alarm(timeout);
ef416fc2 1116
f42414bf 1117 if (recv(fd, &status, 1, 0) < 1)
1118 {
db1f069b
MS
1119 _cupsLangPrintf(stderr,
1120 _("WARNING: Remote host did not respond with data "
1121 "status byte after %d seconds!\n"), timeout);
f42414bf 1122 status = 0;
1123 }
ef416fc2 1124
f42414bf 1125 alarm(0);
1126 }
ef416fc2 1127 }
f42414bf 1128 else
1129 status = 0;
ef416fc2 1130
1131 if (status != 0)
db1f069b
MS
1132 _cupsLangPrintf(stderr,
1133 _("ERROR: Remote host did not accept data file (%d)\n"),
1134 status);
ef416fc2 1135 else
db1f069b 1136 _cupsLangPuts(stderr, _("INFO: Data file sent successfully\n"));
ef416fc2 1137 }
1138
1139 if (status == 0 && order == ORDER_DATA_CONTROL)
1140 {
7a14d768
MS
1141 /*
1142 * Check for side-channel requests...
1143 */
1144
1145 backendCheckSideChannel(snmp_fd, &(addr->addr));
1146
1147 /*
1148 * Send control file...
1149 */
1150
ef416fc2 1151 if (lpd_command(fd, timeout, "\002%d cfA%03.3d%.15s\n", strlen(control),
1152 (int)getpid() % 1000, localhost))
1153 {
1154 httpAddrFreeList(addrlist);
1155 close(fd);
1156
1157 return (CUPS_BACKEND_FAILED);
1158 }
1159
db1f069b
MS
1160 _cupsLangPrintf(stderr, _("INFO: Sending control file (%lu bytes)\n"),
1161 (unsigned long)strlen(control));
ef416fc2 1162
1163 if (lpd_write(fd, control, strlen(control) + 1) < (strlen(control) + 1))
1164 {
1165 status = errno;
080811b1 1166 _cupsLangPrintError(_("ERROR: Unable to write control file"));
ef416fc2 1167 }
1168 else
1169 {
1170 alarm(timeout);
1171
1172 if (read(fd, &status, 1) < 1)
1173 {
db1f069b
MS
1174 _cupsLangPrintf(stderr,
1175 _("WARNING: Remote host did not respond with control "
1176 "status byte after %d seconds!\n"), timeout);
ef416fc2 1177 status = errno;
1178 }
1179
1180 alarm(0);
1181 }
1182
1183 if (status != 0)
db1f069b
MS
1184 _cupsLangPrintf(stderr,
1185 _("ERROR: Remote host did not accept control file "
1186 "(%d)\n"), status);
ef416fc2 1187 else
db1f069b 1188 _cupsLangPuts(stderr, _("INFO: Control file sent successfully\n"));
ef416fc2 1189 }
1190
7a14d768 1191 /*
52f6f666 1192 * Collect the final supply levels as needed...
7a14d768
MS
1193 */
1194
426c6a59 1195 if (have_supplies)
52f6f666 1196 backendSNMPSupplies(snmp_fd, &(addr->addr), NULL, NULL);
7a14d768 1197
ef416fc2 1198 /*
1199 * Close the socket connection and input file...
1200 */
1201
1202 close(fd);
ef416fc2 1203
1204 if (status == 0)
1205 {
1206 httpAddrFreeList(addrlist);
1207
1208 return (CUPS_BACKEND_OK);
1209 }
1210
1211 /*
1212 * Waiting for a retry...
1213 */
1214
1215 sleep(30);
1216 }
1217
1218 httpAddrFreeList(addrlist);
1219
1220 /*
1221 * If we get here, then the job has been cancelled...
1222 */
1223
1224 return (CUPS_BACKEND_FAILED);
1225}
1226
1227
1228/*
1229 * 'lpd_timeout()' - Handle timeout alarms...
1230 */
1231
1232static void
1233lpd_timeout(int sig) /* I - Signal number */
1234{
1235 (void)sig;
1236
1237#if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
1238 signal(SIGALRM, lpd_timeout);
1239#endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
1240}
1241
1242
1243/*
1244 * 'lpd_write()' - Write a buffer of data to an LPD server.
1245 */
1246
1247static int /* O - Number of bytes written or -1 on error */
1248lpd_write(int lpd_fd, /* I - LPD socket */
1249 char *buffer, /* I - Buffer to write */
1250 int length) /* I - Number of bytes to write */
1251{
1252 int bytes, /* Number of bytes written */
1253 total; /* Total number of bytes written */
1254
1255
1256 if (abort_job)
1257 return (-1);
1258
1259 total = 0;
1260 while ((bytes = send(lpd_fd, buffer, length - total, 0)) >= 0)
1261 {
1262 total += bytes;
1263 buffer += bytes;
1264
1265 if (total == length)
1266 break;
1267 }
1268
1269 if (bytes < 0)
1270 return (-1);
1271 else
1272 return (length);
1273}
1274
1275
1276#ifndef HAVE_RRESVPORT_AF
1277/*
1278 * 'rresvport_af()' - A simple implementation of rresvport_af().
1279 */
1280
1281static int /* O - Socket or -1 on error */
1282rresvport_af(int *port, /* IO - Port number to bind to */
1283 int family) /* I - Address family */
1284{
1285 http_addr_t addr; /* Socket address */
1286 int fd; /* Socket file descriptor */
1287
1288
1289 /*
1290 * Try to create an IPv4 socket...
1291 */
1292
1293 if ((fd = socket(family, SOCK_STREAM, 0)) < 0)
1294 return (-1);
1295
1296 /*
1297 * Initialize the address buffer...
1298 */
1299
1300 memset(&addr, 0, sizeof(addr));
1301 addr.addr.sa_family = family;
1302
1303 /*
1304 * Try to bind the socket to a reserved port...
1305 */
1306
1307 while (*port > 511)
1308 {
1309 /*
1310 * Set the port number...
1311 */
1312
1313# ifdef AF_INET6
1314 if (family == AF_INET6)
1315 addr.ipv6.sin6_port = htons(*port);
1316 else
1317# endif /* AF_INET6 */
1318 addr.ipv4.sin_port = htons(*port);
1319
1320 /*
1321 * Try binding the port to the socket; return if all is OK...
1322 */
1323
1324 if (!bind(fd, (struct sockaddr *)&addr, sizeof(addr)))
1325 return (fd);
1326
1327 /*
1328 * Stop if we have any error other than "address already in use"...
1329 */
1330
1331 if (errno != EADDRINUSE)
1332 {
1333# ifdef WIN32
1334 closesocket(fd);
1335# else
1336 close(fd);
1337# endif /* WIN32 */
1338
1339 return (-1);
1340 }
1341
1342 /*
1343 * Try the next port...
1344 */
1345
1346 (*port)--;
1347 }
1348
1349 /*
1350 * Wasn't able to bind to a reserved port, so close the socket and return
1351 * -1...
1352 */
1353
1354# ifdef WIN32
1355 closesocket(fd);
1356# else
1357 close(fd);
1358# endif /* WIN32 */
1359
1360 return (-1);
1361}
1362#endif /* !HAVE_RRESVPORT_AF */
1363
1364
1365/*
1366 * 'sigterm_handler()' - Handle 'terminate' signals that stop the backend.
1367 */
1368
1369static void
1370sigterm_handler(int sig) /* I - Signal */
1371{
1372 (void)sig; /* remove compiler warnings... */
1373
1374 abort_job = 1;
1375}
1376
1377
1378/*
b19ccc9e 1379 * End of "$Id: lpd.c 7740 2008-07-14 23:58:05Z mike $".
ef416fc2 1380 */