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