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