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