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