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