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