]>
git.ipfire.org Git - thirdparty/cups.git/blob - backend/lpd.c
4 * Line Printer Daemon backend for the Common UNIX Printing System (CUPS).
6 * Copyright 1997-2005 by Easy Software Products, all rights reserved.
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
15 * Attn: CUPS Licensing Information
16 * Easy Software Products
17 * 44141 Airport View Drive, Suite 204
18 * Hollywood, Maryland 20636 USA
20 * Voice: (301) 373-9600
21 * EMail: cups-info@cups.org
22 * WWW: http://www.cups.org
24 * This file is subject to the Apple OS-Developed Software exception.
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.
38 * Include necessary headers.
41 #include <cups/backend.h>
42 #include <cups/cups.h>
47 #include <cups/http-private.h>
48 #include <cups/string.h>
50 #include <sys/types.h>
57 # include <sys/socket.h>
58 # include <netinet/in.h>
59 # include <arpa/inet.h>
68 static char tmpfilename
[1024] = ""; /* Temporary spool file name */
69 static int abort_job
= 0; /* Non-zero if we get SIGTERM */
73 * The order for control and data files in LPD requests...
76 #define ORDER_CONTROL_DATA 0 /* Control file first, then data */
77 #define ORDER_DATA_CONTROL 1 /* Data file first, then control */
84 #define RESERVE_NONE 0 /* Don't reserve a priviledged port */
85 #define RESERVE_RFC1179 1 /* Reserve port 721-731 */
86 #define RESERVE_ANY 2 /* Reserve port 1-1023 */
93 static int lpd_command(int lpd_fd
, int timeout
, char *format
, ...);
94 static int lpd_queue(const char *hostname
, int port
, const char *printer
,
96 const char *user
, const char *title
, int copies
,
97 int banner
, int format
, int order
, int reserve
,
98 int manual_copies
, int timeout
);
99 static void lpd_timeout(int sig
);
100 static int lpd_write(int lpd_fd
, char *buffer
, int length
);
101 #ifndef HAVE_RRESVPORT_AF
102 extern int rresvport_af(int *port
, int family
);
103 #endif /* !HAVE_RRESVPORT_AF */
104 static void sigterm_handler(int sig
);
108 * 'main()' - Send a file to the printer or server.
112 * printer-uri job-id user title copies options [file]
115 int /* O - Exit status */
116 main(int argc
, /* I - Number of command-line arguments (6 or 7) */
117 char *argv
[]) /* I - Command-line arguments */
119 char method
[255], /* Method in URI */
120 hostname
[1024], /* Hostname */
121 username
[255], /* Username info */
122 resource
[1024], /* Resource info (printer name) */
123 *options
, /* Pointer to options */
124 name
[255], /* Name of option */
125 value
[255], /* Value of option */
126 *ptr
, /* Pointer into name or value */
127 *filename
, /* File to print */
128 title
[256]; /* Title string */
129 int port
; /* Port number */
130 int status
; /* Status of LPD job */
131 int banner
; /* Print banner page? */
132 int format
; /* Print format */
133 int order
; /* Order of control/data files */
134 int reserve
; /* Reserve priviledged port? */
135 int sanitize_title
; /* Sanitize title string? */
136 int manual_copies
, /* Do manual copies? */
137 timeout
, /* 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 */
145 * Make sure status messages are not buffered...
148 setbuf(stderr
, NULL
);
151 * Ignore SIGPIPE and catch SIGTERM signals...
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
);
162 sigemptyset(&action
.sa_mask
);
163 sigaddset(&action
.sa_mask
, SIGTERM
);
164 action
.sa_handler
= sigterm_handler
;
165 sigaction(SIGTERM
, &action
, NULL
);
167 signal(SIGPIPE
, SIG_IGN
);
168 signal(SIGTERM
, sigterm_handler
);
169 #endif /* HAVE_SIGSET */
172 * Check command-line...
177 puts("network lpd \"Unknown\" \"LPD/LPR Host or Printer\"");
178 return (CUPS_BACKEND_OK
);
180 else if (argc
< 6 || argc
> 7)
182 fprintf(stderr
, "Usage: %s job-id user title copies options [file]\n",
184 return (CUPS_BACKEND_FAILED
);
188 * If we have 7 arguments, print the file named on the command-line.
189 * Otherwise, copy stdin to a temporary file and print the temporary
196 * Copy stdin to a temporary file...
199 int fd
; /* Temporary file */
200 char buffer
[8192]; /* Buffer for copying */
201 int bytes
; /* Number of bytes read */
204 if ((fd
= cupsTempFd(tmpfilename
, sizeof(tmpfilename
))) < 0)
206 perror("ERROR: unable to create temporary file");
207 return (CUPS_BACKEND_FAILED
);
210 while ((bytes
= fread(buffer
, 1, sizeof(buffer
), stdin
)) > 0)
211 if (write(fd
, buffer
, bytes
) < bytes
)
213 perror("ERROR: unable to write to temporary file");
216 return (CUPS_BACKEND_FAILED
);
220 filename
= tmpfilename
;
226 * Extract the hostname and printer name from the URI...
229 httpSeparate(argv
[0], method
, username
, hostname
, &port
, resource
);
234 * If no username is in the device URI, then use the print job user...
237 strlcpy(username
, argv
[2], sizeof(username
));
241 * See if there are any options...
246 order
= ORDER_CONTROL_DATA
;
247 reserve
= RESERVE_ANY
;
252 #if defined(__APPLE__)
253 /* We want to pass utf-8 characters, not re-map them (3071945) */
257 if ((options
= strchr(resource
, '?')) != NULL
)
260 * Yup, terminate the device name string and move to the first
261 * character of the options...
276 for (ptr
= name
; *options
&& *options
!= '=';)
277 if (ptr
< (name
+ sizeof(name
) - 1))
289 for (ptr
= value
; *options
&& *options
!= '+' && *options
!= '&';)
290 if (ptr
< (value
+ sizeof(value
) - 1))
301 * Process the option...
304 if (strcasecmp(name
, "banner") == 0)
310 banner
= !value
[0] ||
311 strcasecmp(value
, "on") == 0 ||
312 strcasecmp(value
, "yes") == 0 ||
313 strcasecmp(value
, "true") == 0;
315 else if (strcasecmp(name
, "format") == 0 && value
[0])
318 * Set output format...
321 if (strchr("cdfglnoprtv", value
[0]) != NULL
)
324 fprintf(stderr
, "ERROR: Unknown format character \"%c\"\n", value
[0]);
326 else if (strcasecmp(name
, "order") == 0 && value
[0])
329 * Set control/data order...
332 if (strcasecmp(value
, "control,data") == 0)
333 order
= ORDER_CONTROL_DATA
;
334 else if (strcasecmp(value
, "data,control") == 0)
335 order
= ORDER_DATA_CONTROL
;
337 fprintf(stderr
, "ERROR: Unknown file order \"%s\"\n", value
);
339 else if (strcasecmp(name
, "reserve") == 0)
342 * Set port reservation mode...
346 !strcasecmp(value
, "on") ||
347 !strcasecmp(value
, "yes") ||
348 !strcasecmp(value
, "true") ||
349 !strcasecmp(value
, "rfc1179"))
350 reserve
= RESERVE_RFC1179
;
351 else if (!strcasecmp(value
, "any"))
352 reserve
= RESERVE_ANY
;
354 reserve
= RESERVE_NONE
;
356 else if (strcasecmp(name
, "manual_copies") == 0)
359 * Set manual copies...
362 manual_copies
= !value
[0] ||
363 strcasecmp(value
, "on") == 0 ||
364 strcasecmp(value
, "yes") == 0 ||
365 strcasecmp(value
, "true") == 0;
367 else if (strcasecmp(name
, "sanitize_title") == 0)
370 * Set sanitize title...
373 sanitize_title
= !value
[0] ||
374 strcasecmp(value
, "on") == 0 ||
375 strcasecmp(value
, "yes") == 0 ||
376 strcasecmp(value
, "true") == 0;
378 else if (strcasecmp(name
, "timeout") == 0)
385 timeout
= atoi(value
);
391 * Sanitize the document title...
394 strlcpy(title
, argv
[3], sizeof(title
));
399 * Sanitize the title string so that we don't cause problems on
403 for (ptr
= title
; *ptr
; ptr
++)
404 if (!isalnum(*ptr
& 255) && !isspace(*ptr
& 255))
416 manual_copies
= atoi(argv
[4]);
422 copies
= atoi(argv
[4]);
425 status
= lpd_queue(hostname
, port
, resource
+ 1, filename
,
426 username
, title
, copies
,
427 banner
, format
, order
, reserve
, manual_copies
, timeout
);
430 fprintf(stderr
, "PAGE: 1 %d\n", atoi(argv
[4]));
433 status
= lpd_queue(hostname
, port
, resource
+ 1, filename
,
435 banner
, format
, order
, reserve
, 1, timeout
);
438 * Remove the temporary file if necessary...
445 * Return the queue status...
453 * 'lpd_command()' - Send an LPR command sequence and wait for a reply.
456 static int /* O - Status of command */
457 lpd_command(int fd
, /* I - Socket connection to LPD host */
458 int timeout
, /* I - Seconds to wait for a response */
459 char *format
, /* I - printf()-style format string */
460 ...) /* I - Additional args as necessary */
462 va_list ap
; /* Argument pointer */
463 char buf
[1024]; /* Output buffer */
464 int bytes
; /* Number of bytes to output */
465 char status
; /* Status from command */
469 * Don't try to send commands if the job has been cancelled...
476 * Format the string...
479 va_start(ap
, format
);
480 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
483 fprintf(stderr
, "DEBUG: lpd_command %2.2x %s", buf
[0], buf
+ 1);
486 * Send the command...
489 fprintf(stderr
, "DEBUG: Sending command string (%d bytes)...\n", bytes
);
491 if (lpd_write(fd
, buf
, bytes
) < bytes
)
493 perror("ERROR: Unable to send LPD command");
498 * Read back the status from the command and return it...
501 fprintf(stderr
, "DEBUG: Reading command status...\n");
505 if (recv(fd
, &status
, 1, 0) < 1)
507 fprintf(stderr
, "WARNING: Remote host did not respond with command "
508 "status byte after %d seconds!\n", timeout
);
514 fprintf(stderr
, "DEBUG: lpd_command returning %d\n", status
);
521 * 'lpd_queue()' - Queue a file using the Line Printer Daemon protocol.
524 static int /* O - Zero on success, non-zero on failure */
525 lpd_queue(const char *hostname
, /* I - Host to connect to */
526 int port
, /* I - Port to connect on */
527 const char *printer
, /* I - Printer/queue name */
528 const char *filename
, /* I - File to print */
529 const char *user
, /* I - Requesting user */
530 const char *title
, /* I - Job title */
531 int copies
, /* I - Number of copies */
532 int banner
, /* I - Print LPD banner? */
533 int format
, /* I - Format specifier */
534 int order
, /* I - Order of data/control files */
535 int reserve
, /* I - Reserve ports? */
536 int manual_copies
, /* I - Do copies by hand... */
537 int timeout
) /* I - Timeout... */
539 FILE *fp
; /* Job file */
540 char localhost
[255]; /* Local host name */
541 int error
; /* Error number */
542 struct stat filestats
; /* File statistics */
543 int lport
; /* LPD connection local port */
544 int fd
; /* LPD socket */
545 char control
[10240], /* LPD control 'file' */
546 *cptr
; /* Pointer into control file string */
547 char status
; /* Status byte from command */
548 char portname
[255]; /* Port name */
549 http_addrlist_t
*addrlist
, /* Address list */
550 *addr
; /* Socket address */
551 int copy
; /* Copies written */
552 size_t nbytes
; /* Number of bytes written */
553 off_t tbytes
; /* Total bytes written */
554 char buffer
[65536]; /* Output buffer */
555 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
556 struct sigaction action
; /* Actions for POSIX signals */
557 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
561 * Setup an alarm handler for timeouts...
564 #ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
565 sigset(SIGALRM
, lpd_timeout
);
566 #elif defined(HAVE_SIGACTION)
567 memset(&action
, 0, sizeof(action
));
569 sigemptyset(&action
.sa_mask
);
570 action
.sa_handler
= lpd_timeout
;
571 sigaction(SIGALRM
, &action
, NULL
);
573 signal(SIGALRM
, lpd_timeout
);
574 #endif /* HAVE_SIGSET */
577 * Find the printer...
580 sprintf(portname
, "%d", port
);
582 if ((addrlist
= httpAddrGetList(hostname
, AF_UNSPEC
, portname
)) == NULL
)
584 fprintf(stderr
, "ERROR: Unable to locate printer \'%s\'!\n",
586 return (CUPS_BACKEND_STOP
);
590 * Loop forever trying to print the file...
596 * First try to reserve a port for this connection...
599 fprintf(stderr
, "INFO: Attempting to connect to host %s for printer %s\n",
602 for (lport
= reserve
== RESERVE_RFC1179
? 732 : 1024, addr
= addrlist
;;
606 * Stop if this job has been cancelled...
611 httpAddrFreeList(addrlist
);
613 return (CUPS_BACKEND_FAILED
);
617 * Choose the next priviledged port...
625 if (lport
< 721 && reserve
== RESERVE_RFC1179
)
631 if (geteuid() || !reserve
)
633 if (getuid() || !reserve
)
634 #endif /* HAVE_GETEUID */
637 * Just create a regular socket...
640 if ((fd
= socket(addr
->addr
.addr
.sa_family
, SOCK_STREAM
, 0)) < 0)
642 perror("ERROR: Unable to create socket");
653 * We're running as root and want to comply with RFC 1179. Reserve a
654 * priviledged lport between 721 and 731...
657 if ((fd
= rresvport_af(&lport
, addr
->addr
.addr
.sa_family
)) < 0)
659 perror("ERROR: Unable to reserve port");
667 * Connect to the printer or server...
672 httpAddrFreeList(addrlist
);
676 return (CUPS_BACKEND_FAILED
);
679 if (!connect(fd
, &(addr
->addr
.addr
), httpAddrLength(&(addr
->addr
))))
689 if (getenv("CLASS") != NULL
)
692 * If the CLASS environment variable is set, the job was submitted
693 * to a class and not to a specific queue. In this case, we want
694 * to abort immediately so that the job can be requeued on the next
695 * available printer in the class.
698 fprintf(stderr
, "INFO: Unable to connect to %s, queuing on next printer in class...\n",
701 httpAddrFreeList(addrlist
);
704 * Sleep 5 seconds to keep the job from requeuing too rapidly...
709 return (CUPS_BACKEND_FAILED
);
712 if (error
== ECONNREFUSED
|| error
== EHOSTDOWN
||
713 error
== EHOSTUNREACH
)
715 fprintf(stderr
, "WARNING: Network host \'%s\' is busy, down, or unreachable; will retry in 30 seconds...\n",
719 else if (error
== EADDRINUSE
)
722 * Try on another port...
729 perror("ERROR: Unable to connect to printer; will retry in 30 seconds...");
734 fprintf(stderr
, "INFO: Connected to %s...\n", hostname
);
735 fprintf(stderr
, "DEBUG: Connected on ports %d (local %d)...\n", port
,
739 * Next, open the print file and figure out its size...
742 if (stat(filename
, &filestats
))
744 httpAddrFreeList(addrlist
);
747 perror("ERROR: unable to stat print file");
748 return (CUPS_BACKEND_FAILED
);
751 filestats
.st_size
*= manual_copies
;
753 if ((fp
= fopen(filename
, "rb")) == NULL
)
755 httpAddrFreeList(addrlist
);
758 perror("ERROR: unable to open print file for reading");
759 return (CUPS_BACKEND_FAILED
);
763 * Send a job header to the printer, specifying no banner page and
767 if (lpd_command(fd
, timeout
, "\002%s\n",
768 printer
)) /* Receive print job(s) */
770 httpAddrFreeList(addrlist
);
772 return (CUPS_BACKEND_FAILED
);
775 httpGetHostname(localhost
, sizeof(localhost
));
776 localhost
[31] = '\0'; /* RFC 1179, Section 7.2 - host name < 32 chars */
778 snprintf(control
, sizeof(control
), "H%s\nP%s\nJ%s\n", localhost
, user
,
780 cptr
= control
+ strlen(control
);
784 snprintf(cptr
, sizeof(control
) - (cptr
- control
), "C%s\nL%s\n",
786 cptr
+= strlen(cptr
);
791 snprintf(cptr
, sizeof(control
) - (cptr
- control
), "%cdfA%03d%.15s\n", format
,
792 getpid() % 1000, localhost
);
793 cptr
+= strlen(cptr
);
797 snprintf(cptr
, sizeof(control
) - (cptr
- control
),
798 "UdfA%03d%.15s\nN%s\n",
799 getpid() % 1000, localhost
, title
);
801 fprintf(stderr
, "DEBUG: Control file is:\n%s", control
);
803 if (order
== ORDER_CONTROL_DATA
)
805 if (lpd_command(fd
, timeout
, "\002%d cfA%03.3d%.15s\n", strlen(control
),
806 getpid() % 1000, localhost
))
808 httpAddrFreeList(addrlist
);
811 return (CUPS_BACKEND_FAILED
);
814 fprintf(stderr
, "INFO: Sending control file (%u bytes)\n",
815 (unsigned)strlen(control
));
817 if (lpd_write(fd
, control
, strlen(control
) + 1) < (strlen(control
) + 1))
820 perror("ERROR: Unable to write control file");
826 if (read(fd
, &status
, 1) < 1)
828 fprintf(stderr
, "WARNING: Remote host did not respond with control "
829 "status byte after %d seconds!\n", timeout
);
837 fprintf(stderr
, "ERROR: Remote host did not accept control file (%d)\n",
840 fputs("INFO: Control file sent successfully\n", stderr
);
848 * Send the print file...
851 if (lpd_command(fd
, timeout
, "\003" CUPS_LLFMT
" dfA%03.3d%.15s\n",
852 CUPS_LLCAST filestats
.st_size
, getpid() % 1000,
855 httpAddrFreeList(addrlist
);
858 return (CUPS_BACKEND_FAILED
);
861 fprintf(stderr
, "INFO: Sending data file (" CUPS_LLFMT
" bytes)\n",
862 CUPS_LLCAST filestats
.st_size
);
865 for (copy
= 0; copy
< manual_copies
; copy
++)
869 while ((nbytes
= fread(buffer
, 1, sizeof(buffer
), fp
)) > 0)
871 fprintf(stderr
, "INFO: Spooling LPR job, %.0f%% complete...\n",
872 100.0 * tbytes
/ filestats
.st_size
);
874 if (lpd_write(fd
, buffer
, nbytes
) < nbytes
)
876 perror("ERROR: Unable to send print file to printer");
884 if (tbytes
< filestats
.st_size
)
886 else if (lpd_write(fd
, "", 1) < 1)
888 perror("ERROR: Unable to send trailing nul to printer");
894 * Read the status byte from the printer; if we can't read the byte
895 * back now, we should set status to "errno", however at this point
896 * we know the printer got the whole file and we don't necessarily
897 * want to requeue it over and over...
902 if (recv(fd
, &status
, 1, 0) < 1)
904 fprintf(stderr
, "WARNING: Remote host did not respond with data "
905 "status byte after %d seconds!\n", timeout
);
913 fprintf(stderr
, "ERROR: Remote host did not accept data file (%d)\n",
916 fputs("INFO: Data file sent successfully\n", stderr
);
919 if (status
== 0 && order
== ORDER_DATA_CONTROL
)
921 if (lpd_command(fd
, timeout
, "\002%d cfA%03.3d%.15s\n", strlen(control
),
922 getpid() % 1000, localhost
))
924 httpAddrFreeList(addrlist
);
927 return (CUPS_BACKEND_FAILED
);
930 fprintf(stderr
, "INFO: Sending control file (%lu bytes)\n",
931 (unsigned long)strlen(control
));
933 if (lpd_write(fd
, control
, strlen(control
) + 1) < (strlen(control
) + 1))
936 perror("ERROR: Unable to write control file");
942 if (read(fd
, &status
, 1) < 1)
944 fprintf(stderr
, "WARNING: Remote host did not respond with control "
945 "status byte after %d seconds!\n", timeout
);
953 fprintf(stderr
, "ERROR: Remote host did not accept control file (%d)\n",
956 fputs("INFO: Control file sent successfully\n", stderr
);
960 * Close the socket connection and input file...
968 httpAddrFreeList(addrlist
);
970 return (CUPS_BACKEND_OK
);
974 * Waiting for a retry...
980 httpAddrFreeList(addrlist
);
983 * If we get here, then the job has been cancelled...
986 return (CUPS_BACKEND_FAILED
);
991 * 'lpd_timeout()' - Handle timeout alarms...
995 lpd_timeout(int sig
) /* I - Signal number */
999 #if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
1000 signal(SIGALRM
, lpd_timeout
);
1001 #endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
1006 * 'lpd_write()' - Write a buffer of data to an LPD server.
1009 static int /* O - Number of bytes written or -1 on error */
1010 lpd_write(int lpd_fd
, /* I - LPD socket */
1011 char *buffer
, /* I - Buffer to write */
1012 int length
) /* I - Number of bytes to write */
1014 int bytes
, /* Number of bytes written */
1015 total
; /* Total number of bytes written */
1022 while ((bytes
= send(lpd_fd
, buffer
, length
- total
, 0)) >= 0)
1027 if (total
== length
)
1038 #ifndef HAVE_RRESVPORT_AF
1040 * 'rresvport_af()' - A simple implementation of rresvport_af().
1043 int /* O - Socket or -1 on error */
1044 rresvport_af(int *port
, /* IO - Port number to bind to */
1045 int family
) /* I - Address family */
1047 http_addr_t addr
; /* Socket address */
1048 int fd
; /* Socket file descriptor */
1052 * Try to create an IPv4 socket...
1055 if ((fd
= socket(family
, SOCK_STREAM
, 0)) < 0)
1059 * Initialize the address buffer...
1062 memset(&addr
, 0, sizeof(addr
));
1063 addr
.addr
.sa_family
= family
;
1066 * Try to bind the socket to a reserved port...
1072 * Set the port number...
1076 if (family
== AF_INET6
1077 addr
.ipv6
.sin6_port
= htons(*port
);
1079 # endif /* AF_INET6 */
1080 addr
.ipv4
.sin_port
= htons(*port
);
1083 * Try binding the port to the socket; return if all is OK...
1086 if (!bind(fd
, (struct sockaddr
*)&addr
, sizeof(addr
)))
1090 * Stop if we have any error other than "address already in use"...
1093 if (errno
!= EADDRINUSE
)
1105 * Try the next port...
1112 * Wasn't able to bind to a reserved port, so close the socket and return
1124 #endif /* !HAVE_RRESVPORT_AF */
1128 * 'sigterm_handler()' - Handle 'terminate' signals that stop the backend.
1132 sigterm_handler(int sig
) /* I - Signal */
1134 (void)sig
; /* remove compiler warnings... */