]> git.ipfire.org Git - thirdparty/cups.git/blob - backend/ipp.c
Abort the outer loop if we get a failure from Send-Document.
[thirdparty/cups.git] / backend / ipp.c
1 /*
2 * "$Id$"
3 *
4 * IPP backend for CUPS.
5 *
6 * Copyright 2007-2012 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 * cancel_job() - Cancel a print job.
21 * check_printer_state() - Check the printer state.
22 * compress_files() - Compress print files.
23 * monitor_printer() - Monitor the printer state.
24 * new_request() - Create a new print creation or validation
25 * request.
26 * password_cb() - Disable the password prompt for
27 * cupsDoFileRequest().
28 * quote_string() - Quote a string value.
29 * report_attr() - Report an IPP attribute value.
30 * report_printer_state() - Report the printer state.
31 * run_as_user() - Run the IPP backend as the printing user.
32 * sigterm_handler() - Handle 'terminate' signals that stop the backend.
33 * timeout_cb() - Handle HTTP timeouts.
34 * update_reasons() - Update the printer-state-reasons values.
35 */
36
37 /*
38 * Include necessary headers.
39 */
40
41 #include "backend-private.h"
42 #include <cups/array-private.h>
43 #include <sys/types.h>
44 #include <sys/stat.h>
45 #include <sys/wait.h>
46 #if defined(HAVE_GSSAPI) && defined(HAVE_XPC)
47 # include <xpc/xpc.h>
48 # define kPMPrintUIToolAgent "com.apple.printuitool.agent"
49 # define kPMStartJob 100
50 # define kPMWaitForJob 101
51 # ifdef HAVE_XPC_PRIVATE_H
52 # include <xpc/private.h>
53 # else
54 extern void xpc_connection_set_target_uid(xpc_connection_t connection,
55 uid_t uid);
56 # endif /* HAVE_XPC_PRIVATE_H */
57 #endif /* HAVE_GSSAPI && HAVE_XPC */
58
59
60 /*
61 * Types...
62 */
63
64 typedef struct _cups_monitor_s /**** Monitoring data ****/
65 {
66 const char *uri, /* Printer URI */
67 *hostname, /* Hostname */
68 *user, /* Username */
69 *resource; /* Resource path */
70 int port, /* Port number */
71 version, /* IPP version */
72 job_id, /* Job ID for submitted job */
73 get_job_attrs; /* Support Get-Job-Attributes? */
74 const char *job_name; /* Job name for submitted job */
75 http_encryption_t encryption; /* Use encryption? */
76 ipp_jstate_t job_state; /* Current job state */
77 ipp_pstate_t printer_state; /* Current printer state */
78 } _cups_monitor_t;
79
80
81 /*
82 * Globals...
83 */
84
85 static const char *auth_info_required;
86 /* New auth-info-required value */
87 #if defined(HAVE_GSSAPI) && defined(HAVE_XPC)
88 static int child_pid = 0; /* Child process ID */
89 #endif /* HAVE_GSSAPI && HAVE_XPC */
90 static const char * const jattrs[] = /* Job attributes we want */
91 {
92 "job-impressions-completed",
93 "job-media-sheets-completed",
94 "job-name",
95 "job-originating-user-name",
96 "job-state",
97 "job-state-reasons"
98 };
99 static int job_canceled = 0;
100 /* Job cancelled? */
101 static char username[256] = "",
102 /* Username for device URI */
103 *password = NULL;
104 /* Password for device URI */
105 static int password_tries = 0;
106 /* Password tries */
107 static const char * const pattrs[] = /* Printer attributes we want */
108 {
109 "copies-supported",
110 "cups-version",
111 "document-format-supported",
112 "marker-colors",
113 "marker-high-levels",
114 "marker-levels",
115 "marker-low-levels",
116 "marker-message",
117 "marker-names",
118 "marker-types",
119 "media-col-supported",
120 "multiple-document-handling-supported",
121 "operations-supported",
122 "printer-alert",
123 "printer-alert-description",
124 "printer-is-accepting-jobs",
125 "printer-state",
126 "printer-state-message",
127 "printer-state-reasons"
128 };
129 static const char * const remote_job_states[] =
130 { /* Remote job state keywords */
131 "+cups-remote-pending",
132 "+cups-remote-pending-held",
133 "+cups-remote-processing",
134 "+cups-remote-stopped",
135 "+cups-remote-canceled",
136 "+cups-remote-aborted",
137 "+cups-remote-completed"
138 };
139 static _cups_mutex_t report_mutex = _CUPS_MUTEX_INITIALIZER;
140 /* Mutex to control access */
141 static int num_attr_cache = 0;
142 /* Number of cached attributes */
143 static cups_option_t *attr_cache = NULL;
144 /* Cached attributes */
145 static cups_array_t *state_reasons; /* Array of printe-state-reasons keywords */
146 static char tmpfilename[1024] = "";
147 /* Temporary spool file name */
148
149
150 /*
151 * Local functions...
152 */
153
154 static void cancel_job(http_t *http, const char *uri, int id,
155 const char *resource, const char *user,
156 int version);
157 static ipp_pstate_t check_printer_state(http_t *http, const char *uri,
158 const char *resource,
159 const char *user, int version);
160 #ifdef HAVE_LIBZ
161 static void compress_files(int num_files, char **files);
162 #endif /* HAVE_LIBZ */
163 static void *monitor_printer(_cups_monitor_t *monitor);
164 static ipp_t *new_request(ipp_op_t op, int version, const char *uri,
165 const char *user, const char *title,
166 int num_options, cups_option_t *options,
167 const char *compression, int copies,
168 const char *format, _ppd_cache_t *pc,
169 ipp_attribute_t *media_col_sup,
170 ipp_attribute_t *doc_handling_sup);
171 static const char *password_cb(const char *prompt, http_t *http,
172 const char *method, const char *resource,
173 void *user_data);
174 static const char *quote_string(const char *s, char *q, size_t qsize);
175 static void report_attr(ipp_attribute_t *attr);
176 static void report_printer_state(ipp_t *ipp);
177 #if defined(HAVE_GSSAPI) && defined(HAVE_XPC)
178 static int run_as_user(char *argv[], uid_t uid,
179 const char *device_uri, int fd);
180 #endif /* HAVE_GSSAPI && HAVE_XPC */
181 static void sigterm_handler(int sig);
182 static int timeout_cb(http_t *http, void *user_data);
183 static void update_reasons(ipp_attribute_t *attr, const char *s);
184
185
186 /*
187 * 'main()' - Send a file to the printer or server.
188 *
189 * Usage:
190 *
191 * printer-uri job-id user title copies options [file]
192 */
193
194 int /* O - Exit status */
195 main(int argc, /* I - Number of command-line args */
196 char *argv[]) /* I - Command-line arguments */
197 {
198 int i; /* Looping var */
199 int send_options; /* Send job options? */
200 int num_options; /* Number of printer options */
201 cups_option_t *options; /* Printer options */
202 const char *device_uri; /* Device URI */
203 char scheme[255], /* Scheme in URI */
204 hostname[1024], /* Hostname */
205 resource[1024], /* Resource info (printer name) */
206 addrname[256], /* Address name */
207 *optptr, /* Pointer to URI options */
208 *name, /* Name of option */
209 *value, /* Value of option */
210 sep; /* Separator character */
211 http_addrlist_t *addrlist; /* Address of printer */
212 int snmp_enabled = 1; /* Is SNMP enabled? */
213 int snmp_fd, /* SNMP socket */
214 start_count, /* Page count via SNMP at start */
215 page_count, /* Page count via SNMP */
216 have_supplies; /* Printer supports supply levels? */
217 int num_files; /* Number of files to print */
218 char **files, /* Files to print */
219 *compatfile = NULL; /* Compatibility filename */
220 off_t compatsize = 0; /* Size of compatibility file */
221 int port; /* Port number (not used) */
222 char portname[255]; /* Port name */
223 char uri[HTTP_MAX_URI]; /* Updated URI without user/pass */
224 char print_job_name[1024]; /* Update job-name for Print-Job */
225 http_status_t http_status; /* Status of HTTP request */
226 ipp_status_t ipp_status; /* Status of IPP request */
227 http_t *http; /* HTTP connection */
228 ipp_t *request, /* IPP request */
229 *response, /* IPP response */
230 *supported; /* get-printer-attributes response */
231 time_t start_time; /* Time of first connect */
232 int contimeout; /* Connection timeout */
233 int delay, /* Delay for retries */
234 prev_delay; /* Previous delay */
235 const char *compression; /* Compression mode */
236 int waitjob, /* Wait for job complete? */
237 waitprinter; /* Wait for printer ready? */
238 _cups_monitor_t monitor; /* Monitoring data */
239 ipp_attribute_t *job_id_attr; /* job-id attribute */
240 int job_id; /* job-id value */
241 ipp_attribute_t *job_sheets; /* job-media-sheets-completed */
242 ipp_attribute_t *job_state; /* job-state */
243 ipp_attribute_t *copies_sup; /* copies-supported */
244 ipp_attribute_t *cups_version; /* cups-version */
245 ipp_attribute_t *format_sup; /* document-format-supported */
246 ipp_attribute_t *media_col_sup; /* media-col-supported */
247 ipp_attribute_t *operations_sup; /* operations-supported */
248 ipp_attribute_t *doc_handling_sup; /* multiple-document-handling-supported */
249 ipp_attribute_t *printer_state; /* printer-state attribute */
250 ipp_attribute_t *printer_accepting; /* printer-is-accepting-jobs */
251 int create_job = 0, /* Does printer support Create-Job? */
252 get_job_attrs = 0, /* Does printer support Get-Job-Attributes? */
253 send_document = 0, /* Does printer support Send-Document? */
254 validate_job = 0; /* Does printer support Validate-Job? */
255 int copies, /* Number of copies for job */
256 copies_remaining; /* Number of copies remaining */
257 const char *content_type, /* CONTENT_TYPE environment variable */
258 *final_content_type, /* FINAL_CONTENT_TYPE environment var */
259 *document_format; /* document-format value */
260 int fd; /* File descriptor */
261 off_t bytes = 0; /* Bytes copied */
262 char buffer[16384]; /* Copy buffer */
263 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
264 struct sigaction action; /* Actions for POSIX signals */
265 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
266 int version; /* IPP version */
267 ppd_file_t *ppd; /* PPD file */
268 _ppd_cache_t *pc; /* PPD cache and mapping data */
269 fd_set input; /* Input set for select() */
270
271
272 /*
273 * Make sure status messages are not buffered...
274 */
275
276 setbuf(stderr, NULL);
277
278 /*
279 * Ignore SIGPIPE and catch SIGTERM signals...
280 */
281
282 #ifdef HAVE_SIGSET
283 sigset(SIGPIPE, SIG_IGN);
284 sigset(SIGTERM, sigterm_handler);
285 #elif defined(HAVE_SIGACTION)
286 memset(&action, 0, sizeof(action));
287 action.sa_handler = SIG_IGN;
288 sigaction(SIGPIPE, &action, NULL);
289
290 sigemptyset(&action.sa_mask);
291 sigaddset(&action.sa_mask, SIGTERM);
292 action.sa_handler = sigterm_handler;
293 sigaction(SIGTERM, &action, NULL);
294 #else
295 signal(SIGPIPE, SIG_IGN);
296 signal(SIGTERM, sigterm_handler);
297 #endif /* HAVE_SIGSET */
298
299 /*
300 * Check command-line...
301 */
302
303 if (argc == 1)
304 {
305 char *s;
306
307 if ((s = strrchr(argv[0], '/')) != NULL)
308 s ++;
309 else
310 s = argv[0];
311
312 printf("network %s \"Unknown\" \"%s (%s)\"\n",
313 s, _cupsLangString(cupsLangDefault(),
314 _("Internet Printing Protocol")), s);
315 return (CUPS_BACKEND_OK);
316 }
317 else if (argc < 6)
318 {
319 _cupsLangPrintf(stderr,
320 _("Usage: %s job-id user title copies options [file]"),
321 argv[0]);
322 return (CUPS_BACKEND_STOP);
323 }
324
325 /*
326 * Get the device URI...
327 */
328
329 while ((device_uri = cupsBackendDeviceURI(argv)) == NULL)
330 {
331 _cupsLangPrintFilter(stderr, "INFO", _("Unable to locate printer."));
332 sleep(10);
333
334 if (getenv("CLASS") != NULL)
335 return (CUPS_BACKEND_FAILED);
336 }
337
338 if ((auth_info_required = getenv("AUTH_INFO_REQUIRED")) == NULL)
339 auth_info_required = "none";
340
341 state_reasons = _cupsArrayNewStrings(getenv("PRINTER_STATE_REASONS"), ',');
342
343 #ifdef HAVE_GSSAPI
344 /*
345 * For Kerberos, become the printing user (if we can) to get the credentials
346 * that way.
347 */
348
349 if (!getuid() && (value = getenv("AUTH_UID")) != NULL)
350 {
351 uid_t uid = (uid_t)atoi(value);
352 /* User ID */
353
354 # ifdef HAVE_XPC
355 if (uid > 0)
356 {
357 if (argc == 6)
358 return (run_as_user(argv, uid, device_uri, 0));
359 else
360 {
361 int status = 0; /* Exit status */
362
363 for (i = 6; i < argc && !status && !job_canceled; i ++)
364 {
365 if ((fd = open(argv[i], O_RDONLY)) >= 0)
366 {
367 status = run_as_user(argv, uid, device_uri, fd);
368 close(fd);
369 }
370 else
371 {
372 _cupsLangPrintError("ERROR", _("Unable to open print file"));
373 status = CUPS_BACKEND_FAILED;
374 }
375 }
376
377 return (status);
378 }
379 }
380
381 # else /* No XPC, just try to run as the user ID */
382 if (uid > 0)
383 seteuid(uid);
384 # endif /* HAVE_XPC */
385 }
386 #endif /* HAVE_GSSAPI */
387
388 /*
389 * Get the (final) content type...
390 */
391
392 if ((content_type = getenv("CONTENT_TYPE")) == NULL)
393 content_type = "application/octet-stream";
394
395 if ((final_content_type = getenv("FINAL_CONTENT_TYPE")) == NULL)
396 {
397 final_content_type = content_type;
398
399 if (!strncmp(final_content_type, "printer/", 8))
400 final_content_type = "application/vnd.cups-raw";
401 }
402
403 /*
404 * Extract the hostname and printer name from the URI...
405 */
406
407 httpSeparateURI(HTTP_URI_CODING_ALL, device_uri, scheme, sizeof(scheme),
408 username, sizeof(username), hostname, sizeof(hostname), &port,
409 resource, sizeof(resource));
410
411 if (!port)
412 port = IPP_PORT; /* Default to port 631 */
413
414 if (!strcmp(scheme, "https"))
415 cupsSetEncryption(HTTP_ENCRYPT_ALWAYS);
416 else
417 cupsSetEncryption(HTTP_ENCRYPT_IF_REQUESTED);
418
419 /*
420 * See if there are any options...
421 */
422
423 compression = NULL;
424 version = 20;
425 waitjob = 1;
426 waitprinter = 1;
427 contimeout = 7 * 24 * 60 * 60;
428
429 if ((optptr = strchr(resource, '?')) != NULL)
430 {
431 /*
432 * Yup, terminate the device name string and move to the first
433 * character of the optptr...
434 */
435
436 *optptr++ = '\0';
437
438 /*
439 * Then parse the optptr...
440 */
441
442 while (*optptr)
443 {
444 /*
445 * Get the name...
446 */
447
448 name = optptr;
449
450 while (*optptr && *optptr != '=' && *optptr != '+' && *optptr != '&')
451 optptr ++;
452
453 if ((sep = *optptr) != '\0')
454 *optptr++ = '\0';
455
456 if (sep == '=')
457 {
458 /*
459 * Get the value...
460 */
461
462 value = optptr;
463
464 while (*optptr && *optptr != '+' && *optptr != '&')
465 optptr ++;
466
467 if (*optptr)
468 *optptr++ = '\0';
469 }
470 else
471 value = (char *)"";
472
473 /*
474 * Process the option...
475 */
476
477 if (!_cups_strcasecmp(name, "waitjob"))
478 {
479 /*
480 * Wait for job completion?
481 */
482
483 waitjob = !_cups_strcasecmp(value, "on") ||
484 !_cups_strcasecmp(value, "yes") ||
485 !_cups_strcasecmp(value, "true");
486 }
487 else if (!_cups_strcasecmp(name, "waitprinter"))
488 {
489 /*
490 * Wait for printer idle?
491 */
492
493 waitprinter = !_cups_strcasecmp(value, "on") ||
494 !_cups_strcasecmp(value, "yes") ||
495 !_cups_strcasecmp(value, "true");
496 }
497 else if (!_cups_strcasecmp(name, "encryption"))
498 {
499 /*
500 * Enable/disable encryption?
501 */
502
503 if (!_cups_strcasecmp(value, "always"))
504 cupsSetEncryption(HTTP_ENCRYPT_ALWAYS);
505 else if (!_cups_strcasecmp(value, "required"))
506 cupsSetEncryption(HTTP_ENCRYPT_REQUIRED);
507 else if (!_cups_strcasecmp(value, "never"))
508 cupsSetEncryption(HTTP_ENCRYPT_NEVER);
509 else if (!_cups_strcasecmp(value, "ifrequested"))
510 cupsSetEncryption(HTTP_ENCRYPT_IF_REQUESTED);
511 else
512 {
513 _cupsLangPrintFilter(stderr, "ERROR",
514 _("Unknown encryption option value: \"%s\"."),
515 value);
516 }
517 }
518 else if (!_cups_strcasecmp(name, "snmp"))
519 {
520 /*
521 * Enable/disable SNMP stuff...
522 */
523
524 snmp_enabled = !value[0] || !_cups_strcasecmp(value, "on") ||
525 _cups_strcasecmp(value, "yes") ||
526 _cups_strcasecmp(value, "true");
527 }
528 else if (!_cups_strcasecmp(name, "version"))
529 {
530 if (!strcmp(value, "1.0"))
531 version = 10;
532 else if (!strcmp(value, "1.1"))
533 version = 11;
534 else if (!strcmp(value, "2.0"))
535 version = 20;
536 else if (!strcmp(value, "2.1"))
537 version = 21;
538 else if (!strcmp(value, "2.2"))
539 version = 22;
540 else
541 {
542 _cupsLangPrintFilter(stderr, "ERROR",
543 _("Unknown version option value: \"%s\"."),
544 value);
545 }
546 }
547 #ifdef HAVE_LIBZ
548 else if (!_cups_strcasecmp(name, "compression"))
549 {
550 if (!_cups_strcasecmp(value, "true") || !_cups_strcasecmp(value, "yes") ||
551 !_cups_strcasecmp(value, "on") || !_cups_strcasecmp(value, "gzip"))
552 compression = "gzip";
553 }
554 #endif /* HAVE_LIBZ */
555 else if (!_cups_strcasecmp(name, "contimeout"))
556 {
557 /*
558 * Set the connection timeout...
559 */
560
561 if (atoi(value) > 0)
562 contimeout = atoi(value);
563 }
564 else
565 {
566 /*
567 * Unknown option...
568 */
569
570 _cupsLangPrintFilter(stderr, "ERROR",
571 _("Unknown option \"%s\" with value \"%s\"."),
572 name, value);
573 }
574 }
575 }
576
577 /*
578 * If we have 7 arguments, print the file named on the command-line.
579 * Otherwise, copy stdin to a temporary file and print the temporary
580 * file.
581 */
582
583 if (argc == 6)
584 {
585 num_files = 0;
586 files = NULL;
587 send_options = !_cups_strcasecmp(final_content_type, "application/pdf") ||
588 !_cups_strcasecmp(final_content_type, "application/vnd.cups-pdf") ||
589 !_cups_strncasecmp(final_content_type, "image/", 6);
590
591 fputs("DEBUG: Sending stdin for job...\n", stderr);
592 }
593 else
594 {
595 /*
596 * Point to the files on the command-line...
597 */
598
599 num_files = argc - 6;
600 files = argv + 6;
601 send_options = 1;
602
603 #ifdef HAVE_LIBZ
604 if (compression)
605 compress_files(num_files, files);
606 #endif /* HAVE_LIBZ */
607
608 fprintf(stderr, "DEBUG: %d files to send in job...\n", num_files);
609 }
610
611 /*
612 * Set the authentication info, if any...
613 */
614
615 cupsSetPasswordCB2(password_cb, NULL);
616
617 if (username[0])
618 {
619 /*
620 * Use authentication information in the device URI...
621 */
622
623 if ((password = strchr(username, ':')) != NULL)
624 *password++ = '\0';
625
626 cupsSetUser(username);
627 }
628 else
629 {
630 /*
631 * Try loading authentication information from the environment.
632 */
633
634 const char *ptr = getenv("AUTH_USERNAME");
635
636 if (ptr)
637 {
638 strlcpy(username, ptr, sizeof(username));
639 cupsSetUser(ptr);
640 }
641
642 password = getenv("AUTH_PASSWORD");
643 }
644
645 /*
646 * Try finding the remote server...
647 */
648
649 start_time = time(NULL);
650
651 sprintf(portname, "%d", port);
652
653 update_reasons(NULL, "+connecting-to-device");
654 fprintf(stderr, "DEBUG: Looking up \"%s\"...\n", hostname);
655
656 while ((addrlist = httpAddrGetList(hostname, AF_UNSPEC, portname)) == NULL)
657 {
658 _cupsLangPrintFilter(stderr, "INFO",
659 _("Unable to locate printer \"%s\"."), hostname);
660 sleep(10);
661
662 if (getenv("CLASS") != NULL)
663 {
664 update_reasons(NULL, "-connecting-to-device");
665 return (CUPS_BACKEND_STOP);
666 }
667
668 if (job_canceled)
669 return (CUPS_BACKEND_OK);
670 }
671
672 http = _httpCreate(hostname, port, addrlist, cupsEncryption(), AF_UNSPEC);
673 httpSetTimeout(http, 30.0, timeout_cb, NULL);
674
675 /*
676 * See if the printer supports SNMP...
677 */
678
679 if (snmp_enabled)
680 snmp_fd = _cupsSNMPOpen(addrlist->addr.addr.sa_family);
681 else
682 snmp_fd = -1;
683
684 if (snmp_fd >= 0)
685 have_supplies = !backendSNMPSupplies(snmp_fd, &(addrlist->addr),
686 &start_count, NULL);
687 else
688 have_supplies = start_count = 0;
689
690 /*
691 * Wait for data from the filter...
692 */
693
694 if (num_files == 0)
695 {
696 if (!backendWaitLoop(snmp_fd, &(addrlist->addr), 0, backendNetworkSideCB))
697 return (CUPS_BACKEND_OK);
698 else if ((bytes = read(0, buffer, sizeof(buffer))) <= 0)
699 return (CUPS_BACKEND_OK);
700 }
701
702 /*
703 * Try connecting to the remote server...
704 */
705
706 delay = _cupsNextDelay(0, &prev_delay);
707
708 do
709 {
710 fprintf(stderr, "DEBUG: Connecting to %s:%d\n", hostname, port);
711 _cupsLangPrintFilter(stderr, "INFO", _("Connecting to printer."));
712
713 if (httpReconnect(http))
714 {
715 int error = errno; /* Connection error */
716
717 if (http->status == HTTP_PKI_ERROR)
718 update_reasons(NULL, "+cups-certificate-error");
719
720 if (job_canceled)
721 break;
722
723 if (getenv("CLASS") != NULL)
724 {
725 /*
726 * If the CLASS environment variable is set, the job was submitted
727 * to a class and not to a specific queue. In this case, we want
728 * to abort immediately so that the job can be requeued on the next
729 * available printer in the class.
730 */
731
732 _cupsLangPrintFilter(stderr, "INFO",
733 _("Unable to contact printer, queuing on next "
734 "printer in class."));
735
736 /*
737 * Sleep 5 seconds to keep the job from requeuing too rapidly...
738 */
739
740 sleep(5);
741
742 update_reasons(NULL, "-connecting-to-device");
743
744 return (CUPS_BACKEND_FAILED);
745 }
746
747 fprintf(stderr, "DEBUG: Connection error: %s\n", strerror(errno));
748
749 if (errno == ECONNREFUSED || errno == EHOSTDOWN ||
750 errno == EHOSTUNREACH)
751 {
752 if (contimeout && (time(NULL) - start_time) > contimeout)
753 {
754 _cupsLangPrintFilter(stderr, "ERROR",
755 _("The printer is not responding."));
756 update_reasons(NULL, "-connecting-to-device");
757 return (CUPS_BACKEND_FAILED);
758 }
759
760 switch (error)
761 {
762 case EHOSTDOWN :
763 _cupsLangPrintFilter(stderr, "WARNING",
764 _("The printer may not exist or "
765 "is unavailable at this time."));
766 break;
767
768 case EHOSTUNREACH :
769 _cupsLangPrintFilter(stderr, "WARNING",
770 _("The printer is unreachable at this "
771 "time."));
772 break;
773
774 case ECONNREFUSED :
775 default :
776 _cupsLangPrintFilter(stderr, "WARNING",
777 _("The printer is in use."));
778 break;
779 }
780
781 sleep(delay);
782
783 delay = _cupsNextDelay(delay, &prev_delay);
784 }
785 else
786 {
787 _cupsLangPrintFilter(stderr, "ERROR",
788 _("The printer is not responding."));
789 sleep(30);
790 }
791
792 if (job_canceled)
793 break;
794 }
795 else
796 update_reasons(NULL, "-cups-certificate-error");
797 }
798 while (http->fd < 0);
799
800 if (job_canceled)
801 return (CUPS_BACKEND_OK);
802 else if (!http)
803 return (CUPS_BACKEND_FAILED);
804
805 update_reasons(NULL, "-connecting-to-device");
806 _cupsLangPrintFilter(stderr, "INFO", _("Connected to printer."));
807
808 fprintf(stderr, "DEBUG: Connected to %s:%d...\n",
809 httpAddrString(http->hostaddr, addrname, sizeof(addrname)),
810 _httpAddrPort(http->hostaddr));
811
812 /*
813 * Build a URI for the printer and fill the standard IPP attributes for
814 * an IPP_PRINT_FILE request. We can't use the URI in argv[0] because it
815 * might contain username:password information...
816 */
817
818 httpAssembleURI(HTTP_URI_CODING_ALL, uri, sizeof(uri), scheme, NULL, hostname,
819 port, resource);
820
821 /*
822 * First validate the destination and see if the device supports multiple
823 * copies...
824 */
825
826 copies_sup = NULL;
827 cups_version = NULL;
828 format_sup = NULL;
829 media_col_sup = NULL;
830 supported = NULL;
831 operations_sup = NULL;
832 doc_handling_sup = NULL;
833
834 do
835 {
836 /*
837 * Check for side-channel requests...
838 */
839
840 backendCheckSideChannel(snmp_fd, http->hostaddr);
841
842 /*
843 * Build the IPP request...
844 */
845
846 request = ippNewRequest(IPP_GET_PRINTER_ATTRIBUTES);
847 request->request.op.version[0] = version / 10;
848 request->request.op.version[1] = version % 10;
849
850 ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri",
851 NULL, uri);
852
853 ippAddStrings(request, IPP_TAG_OPERATION, IPP_TAG_KEYWORD,
854 "requested-attributes", sizeof(pattrs) / sizeof(pattrs[0]),
855 NULL, pattrs);
856
857 /*
858 * Do the request...
859 */
860
861 fputs("DEBUG: Getting supported attributes...\n", stderr);
862
863 if (http->version < HTTP_1_1)
864 {
865 fprintf(stderr, "DEBUG: Printer responded with HTTP version %d.%d.\n",
866 http->version / 100, http->version % 100);
867 update_reasons(NULL, "+cups-ipp-conformance-failure-report,"
868 "cups-ipp-wrong-http-version");
869 }
870
871 supported = cupsDoRequest(http, request, resource);
872 ipp_status = cupsLastError();
873
874 fprintf(stderr, "DEBUG: Get-Printer-Attributes: %s (%s)\n",
875 ippErrorString(ipp_status), cupsLastErrorString());
876
877 if (ipp_status <= IPP_OK_CONFLICT)
878 password_tries = 0;
879 else
880 {
881 fprintf(stderr, "DEBUG: Get-Printer-Attributes returned %s.\n",
882 ippErrorString(ipp_status));
883
884 if (ipp_status == IPP_PRINTER_BUSY ||
885 ipp_status == IPP_SERVICE_UNAVAILABLE)
886 {
887 if (contimeout && (time(NULL) - start_time) > contimeout)
888 {
889 _cupsLangPrintFilter(stderr, "ERROR",
890 _("The printer is not responding."));
891 return (CUPS_BACKEND_FAILED);
892 }
893
894 _cupsLangPrintFilter(stderr, "INFO", _("The printer is in use."));
895
896 report_printer_state(supported);
897
898 sleep(delay);
899
900 delay = _cupsNextDelay(delay, &prev_delay);
901 }
902 else if ((ipp_status == IPP_BAD_REQUEST ||
903 ipp_status == IPP_VERSION_NOT_SUPPORTED) && version > 10)
904 {
905 /*
906 * Switch to IPP/1.1 or IPP/1.0...
907 */
908
909 if (version >= 20)
910 {
911 _cupsLangPrintFilter(stderr, "INFO",
912 _("The printer does not support IPP/%d.%d, trying "
913 "IPP/%s."), version / 10, version % 10, "1.1");
914 version = 11;
915 }
916 else
917 {
918 _cupsLangPrintFilter(stderr, "INFO",
919 _("The printer does not support IPP/%d.%d, trying "
920 "IPP/%s."), version / 10, version % 10, "1.0");
921 version = 10;
922 }
923
924 httpReconnect(http);
925 }
926 else if (ipp_status == IPP_NOT_FOUND)
927 {
928 _cupsLangPrintFilter(stderr, "ERROR",
929 _("The printer URI is incorrect or no longer "
930 "exists."));
931
932 ippDelete(supported);
933
934 return (CUPS_BACKEND_STOP);
935 }
936 else if (ipp_status == IPP_FORBIDDEN ||
937 ipp_status == IPP_AUTHENTICATION_CANCELED)
938 {
939 const char *www_auth = httpGetField(http, HTTP_FIELD_WWW_AUTHENTICATE);
940 /* WWW-Authenticate field value */
941
942 if (!strncmp(www_auth, "Negotiate", 9))
943 auth_info_required = "negotiate";
944 else if (www_auth[0])
945 auth_info_required = "username,password";
946
947 fprintf(stderr, "ATTR: auth-info-required=%s\n", auth_info_required);
948 return (CUPS_BACKEND_AUTH_REQUIRED);
949 }
950 else if (ipp_status != IPP_NOT_AUTHORIZED)
951 {
952 _cupsLangPrintFilter(stderr, "ERROR",
953 _("Unable to get printer status."));
954 sleep(10);
955 }
956
957 ippDelete(supported);
958 supported = NULL;
959 continue;
960 }
961
962 if (!getenv("CLASS"))
963 {
964 /*
965 * Check printer-is-accepting-jobs = false and printer-state-reasons for the
966 * "spool-area-full" keyword...
967 */
968
969 int busy = 0;
970
971 if ((printer_accepting = ippFindAttribute(supported,
972 "printer-is-accepting-jobs",
973 IPP_TAG_BOOLEAN)) != NULL &&
974 !printer_accepting->values[0].boolean)
975 busy = 1;
976 else if (!printer_accepting)
977 update_reasons(NULL, "+cups-ipp-conformance-failure-report,"
978 "cups-ipp-missing-printer-is-accepting-jobs");
979
980 if ((printer_state = ippFindAttribute(supported,
981 "printer-state-reasons",
982 IPP_TAG_KEYWORD)) != NULL && !busy)
983 {
984 for (i = 0; i < printer_state->num_values; i ++)
985 if (!strcmp(printer_state->values[0].string.text,
986 "spool-area-full") ||
987 !strncmp(printer_state->values[0].string.text, "spool-area-full-",
988 16))
989 {
990 busy = 1;
991 break;
992 }
993 }
994 else
995 update_reasons(NULL, "+cups-ipp-conformance-failure-report,"
996 "cups-ipp-missing-printer-state-reasons");
997
998 if (busy)
999 {
1000 _cupsLangPrintFilter(stderr, "INFO", _("The printer is in use."));
1001
1002 report_printer_state(supported);
1003
1004 sleep(delay);
1005
1006 delay = _cupsNextDelay(delay, &prev_delay);
1007
1008 ippDelete(supported);
1009 supported = NULL;
1010 continue;
1011 }
1012 }
1013
1014 /*
1015 * Check for supported attributes...
1016 */
1017
1018 if ((copies_sup = ippFindAttribute(supported, "copies-supported",
1019 IPP_TAG_RANGE)) != NULL)
1020 {
1021 /*
1022 * Has the "copies-supported" attribute - does it have an upper
1023 * bound > 1?
1024 */
1025
1026 fprintf(stderr, "DEBUG: copies-supported=%d-%d\n",
1027 copies_sup->values[0].range.lower,
1028 copies_sup->values[0].range.upper);
1029
1030 if (copies_sup->values[0].range.upper <= 1)
1031 copies_sup = NULL; /* No */
1032 }
1033
1034 cups_version = ippFindAttribute(supported, "cups-version", IPP_TAG_TEXT);
1035
1036 if ((format_sup = ippFindAttribute(supported, "document-format-supported",
1037 IPP_TAG_MIMETYPE)) != NULL)
1038 {
1039 fprintf(stderr, "DEBUG: document-format-supported (%d values)\n",
1040 format_sup->num_values);
1041 for (i = 0; i < format_sup->num_values; i ++)
1042 fprintf(stderr, "DEBUG: [%d] = \"%s\"\n", i,
1043 format_sup->values[i].string.text);
1044 }
1045
1046 if ((media_col_sup = ippFindAttribute(supported, "media-col-supported",
1047 IPP_TAG_KEYWORD)) != NULL)
1048 {
1049 fprintf(stderr, "DEBUG: media-col-supported (%d values)\n",
1050 media_col_sup->num_values);
1051 for (i = 0; i < media_col_sup->num_values; i ++)
1052 fprintf(stderr, "DEBUG: [%d] = \"%s\"\n", i,
1053 media_col_sup->values[i].string.text);
1054 }
1055
1056 if ((operations_sup = ippFindAttribute(supported, "operations-supported",
1057 IPP_TAG_ENUM)) != NULL)
1058 {
1059 for (i = 0; i < operations_sup->num_values; i ++)
1060 if (operations_sup->values[i].integer == IPP_PRINT_JOB)
1061 break;
1062
1063 if (i >= operations_sup->num_values)
1064 update_reasons(NULL, "+cups-ipp-conformance-failure-report,"
1065 "cups-ipp-missing-print-job");
1066
1067 for (i = 0; i < operations_sup->num_values; i ++)
1068 if (operations_sup->values[i].integer == IPP_CANCEL_JOB)
1069 break;
1070
1071 if (i >= operations_sup->num_values)
1072 update_reasons(NULL, "+cups-ipp-conformance-failure-report,"
1073 "cups-ipp-missing-cancel-job");
1074
1075 for (i = 0; i < operations_sup->num_values; i ++)
1076 if (operations_sup->values[i].integer == IPP_GET_JOB_ATTRIBUTES)
1077 break;
1078
1079 if (i >= operations_sup->num_values)
1080 update_reasons(NULL, "+cups-ipp-conformance-failure-report,"
1081 "cups-ipp-missing-get-job-attributes");
1082
1083 for (i = 0; i < operations_sup->num_values; i ++)
1084 if (operations_sup->values[i].integer == IPP_GET_PRINTER_ATTRIBUTES)
1085 break;
1086
1087 if (i >= operations_sup->num_values)
1088 update_reasons(NULL, "+cups-ipp-conformance-failure-report,"
1089 "cups-ipp-missing-get-printer-attributes");
1090
1091 for (i = 0; i < operations_sup->num_values; i ++)
1092 {
1093 if (operations_sup->values[i].integer == IPP_VALIDATE_JOB)
1094 validate_job = 1;
1095 else if (operations_sup->values[i].integer == IPP_CREATE_JOB)
1096 create_job = 1;
1097 else if (operations_sup->values[i].integer == IPP_SEND_DOCUMENT)
1098 send_document = 1;
1099 else if (operations_sup->values[i].integer == IPP_GET_JOB_ATTRIBUTES)
1100 get_job_attrs = 1;
1101 }
1102
1103 if (create_job && !send_document)
1104 {
1105 fputs("DEBUG: Printer supports Create-Job but not Send-Document.\n",
1106 stderr);
1107 create_job = 0;
1108
1109 update_reasons(NULL, "+cups-ipp-conformance-failure-report,"
1110 "cups-ipp-missing-send-document");
1111 }
1112
1113 if (!validate_job)
1114 update_reasons(NULL, "+cups-ipp-conformance-failure-report,"
1115 "cups-ipp-missing-validate-job");
1116 }
1117 else
1118 update_reasons(NULL, "+cups-ipp-conformance-failure-report,"
1119 "cups-ipp-missing-operations-supported");
1120
1121 doc_handling_sup = ippFindAttribute(supported,
1122 "multiple-document-handling-supported",
1123 IPP_TAG_KEYWORD);
1124
1125 report_printer_state(supported);
1126 }
1127 while (!job_canceled && ipp_status > IPP_OK_CONFLICT);
1128
1129 if (job_canceled)
1130 return (CUPS_BACKEND_OK);
1131
1132 /*
1133 * See if the printer is accepting jobs and is not stopped; if either
1134 * condition is true and we are printing to a class, requeue the job...
1135 */
1136
1137 if (getenv("CLASS") != NULL)
1138 {
1139 printer_state = ippFindAttribute(supported, "printer-state",
1140 IPP_TAG_ENUM);
1141 printer_accepting = ippFindAttribute(supported, "printer-is-accepting-jobs",
1142 IPP_TAG_BOOLEAN);
1143
1144 if (printer_state == NULL ||
1145 (printer_state->values[0].integer > IPP_PRINTER_PROCESSING &&
1146 waitprinter) ||
1147 printer_accepting == NULL ||
1148 !printer_accepting->values[0].boolean)
1149 {
1150 /*
1151 * If the CLASS environment variable is set, the job was submitted
1152 * to a class and not to a specific queue. In this case, we want
1153 * to abort immediately so that the job can be requeued on the next
1154 * available printer in the class.
1155 */
1156
1157 _cupsLangPrintFilter(stderr, "INFO",
1158 _("Unable to contact printer, queuing on next "
1159 "printer in class."));
1160
1161 ippDelete(supported);
1162 httpClose(http);
1163
1164 /*
1165 * Sleep 5 seconds to keep the job from requeuing too rapidly...
1166 */
1167
1168 sleep(5);
1169
1170 return (CUPS_BACKEND_FAILED);
1171 }
1172 }
1173
1174 /*
1175 * See if the printer supports multiple copies...
1176 */
1177
1178 copies = atoi(argv[4]);
1179
1180 if (copies_sup || argc < 7)
1181 copies_remaining = 1;
1182 else
1183 copies_remaining = copies;
1184
1185 /*
1186 * Prepare remaining printing options...
1187 */
1188
1189 options = NULL;
1190 pc = NULL;
1191
1192 if (send_options)
1193 {
1194 num_options = cupsParseOptions(argv[5], 0, &options);
1195
1196 if (!cups_version && media_col_sup)
1197 {
1198 /*
1199 * Load the PPD file and generate PWG attribute mapping information...
1200 */
1201
1202 ppd = ppdOpenFile(getenv("PPD"));
1203 pc = _ppdCacheCreateWithPPD(ppd);
1204
1205 ppdClose(ppd);
1206 }
1207 }
1208 else
1209 num_options = 0;
1210
1211 document_format = NULL;
1212
1213 if (format_sup != NULL)
1214 {
1215 for (i = 0; i < format_sup->num_values; i ++)
1216 if (!_cups_strcasecmp(final_content_type,
1217 format_sup->values[i].string.text))
1218 {
1219 document_format = final_content_type;
1220 break;
1221 }
1222
1223 if (!document_format)
1224 {
1225 for (i = 0; i < format_sup->num_values; i ++)
1226 if (!_cups_strcasecmp("application/octet-stream",
1227 format_sup->values[i].string.text))
1228 {
1229 document_format = "application/octet-stream";
1230 break;
1231 }
1232 }
1233 }
1234
1235 fprintf(stderr, "DEBUG: final_content_type=\"%s\", document_format=\"%s\"\n",
1236 final_content_type, document_format ? document_format : "(null)");
1237
1238 /*
1239 * If the printer does not support HTTP/1.1 (which IPP requires), copy stdin
1240 * to a temporary file so that we can do a HTTP/1.0 submission...
1241 *
1242 * (I hate compatibility hacks!)
1243 */
1244
1245 if (http->version < HTTP_1_1 && num_files == 0)
1246 {
1247 if ((fd = cupsTempFd(tmpfilename, sizeof(tmpfilename))) < 0)
1248 {
1249 perror("DEBUG: Unable to create temporary file");
1250 return (CUPS_BACKEND_FAILED);
1251 }
1252
1253 _cupsLangPrintFilter(stderr, "INFO", _("Copying print data."));
1254
1255 if ((compatsize = write(fd, buffer, bytes)) < 0)
1256 {
1257 perror("DEBUG: Unable to write temporary file");
1258 return (CUPS_BACKEND_FAILED);
1259 }
1260
1261 if ((bytes = backendRunLoop(-1, fd, snmp_fd, &(addrlist->addr), 0, 0,
1262 backendNetworkSideCB)) < 0)
1263 return (CUPS_BACKEND_FAILED);
1264
1265 compatsize += bytes;
1266
1267 close(fd);
1268
1269 compatfile = tmpfilename;
1270 files = &compatfile;
1271 num_files = 1;
1272 }
1273 else if (http->version < HTTP_1_1 && num_files == 1)
1274 {
1275 struct stat fileinfo; /* File information */
1276
1277 if (!stat(files[0], &fileinfo))
1278 compatsize = fileinfo.st_size;
1279 }
1280
1281 /*
1282 * If the printer only claims to support IPP/1.0, or if the user specifically
1283 * included version=1.0 in the URI, then do not try to use Create-Job or
1284 * Send-Document. This is another dreaded compatibility hack, but unfortunately
1285 * there are enough broken printers out there that we need this for now...
1286 */
1287
1288 if (version == 10)
1289 create_job = send_document = 0;
1290
1291 /*
1292 * Start monitoring the printer in the background...
1293 */
1294
1295 monitor.uri = uri;
1296 monitor.hostname = hostname;
1297 monitor.user = argv[2];
1298 monitor.resource = resource;
1299 monitor.port = port;
1300 monitor.version = version;
1301 monitor.job_id = 0;
1302 monitor.get_job_attrs = get_job_attrs;
1303 monitor.encryption = cupsEncryption();
1304 monitor.job_state = IPP_JOB_PENDING;
1305 monitor.printer_state = IPP_PRINTER_IDLE;
1306
1307 if (create_job)
1308 {
1309 monitor.job_name = argv[3];
1310 }
1311 else
1312 {
1313 snprintf(print_job_name, sizeof(print_job_name), "%s - %s", argv[1],
1314 argv[3]);
1315 monitor.job_name = print_job_name;
1316 }
1317
1318 _cupsThreadCreate((_cups_thread_func_t)monitor_printer, &monitor);
1319
1320 /*
1321 * Validate access to the printer...
1322 */
1323
1324 while (!job_canceled && validate_job)
1325 {
1326 request = new_request(IPP_VALIDATE_JOB, version, uri, argv[2],
1327 monitor.job_name, num_options, options, compression,
1328 copies_sup ? copies : 1, document_format, pc,
1329 media_col_sup, doc_handling_sup);
1330
1331 ippDelete(cupsDoRequest(http, request, resource));
1332
1333 ipp_status = cupsLastError();
1334
1335 fprintf(stderr, "DEBUG: Validate-Job: %s (%s)\n",
1336 ippErrorString(ipp_status), cupsLastErrorString());
1337
1338 if (job_canceled)
1339 break;
1340
1341 if (ipp_status == IPP_SERVICE_UNAVAILABLE || ipp_status == IPP_PRINTER_BUSY)
1342 {
1343 _cupsLangPrintFilter(stderr, "INFO", _("The printer is in use."));
1344 sleep(10);
1345 }
1346 else if (ipp_status == IPP_DOCUMENT_FORMAT)
1347 goto cleanup;
1348 else if (ipp_status == IPP_FORBIDDEN ||
1349 ipp_status == IPP_AUTHENTICATION_CANCELED)
1350 {
1351 const char *www_auth = httpGetField(http, HTTP_FIELD_WWW_AUTHENTICATE);
1352 /* WWW-Authenticate field value */
1353
1354 if (!strncmp(www_auth, "Negotiate", 9))
1355 auth_info_required = "negotiate";
1356 else if (www_auth[0])
1357 auth_info_required = "username,password";
1358
1359 goto cleanup;
1360 }
1361 else if (ipp_status == IPP_OPERATION_NOT_SUPPORTED)
1362 {
1363 /*
1364 * This is all too common...
1365 */
1366
1367 update_reasons(NULL, "+cups-ipp-conformance-failure-report,"
1368 "cups-ipp-missing-validate-job");
1369 break;
1370 }
1371 else if (ipp_status < IPP_REDIRECTION_OTHER_SITE ||
1372 ipp_status == IPP_BAD_REQUEST)
1373 break;
1374 }
1375
1376 /*
1377 * Then issue the print-job request...
1378 */
1379
1380 job_id = 0;
1381
1382 while (!job_canceled && copies_remaining > 0)
1383 {
1384 /*
1385 * Check for side-channel requests...
1386 */
1387
1388 backendCheckSideChannel(snmp_fd, http->hostaddr);
1389
1390 /*
1391 * Build the IPP job creation request...
1392 */
1393
1394 if (job_canceled)
1395 break;
1396
1397 request = new_request((num_files > 1 || create_job) ? IPP_CREATE_JOB :
1398 IPP_PRINT_JOB,
1399 version, uri, argv[2], monitor.job_name, num_options,
1400 options, compression, copies_sup ? copies : 1,
1401 document_format, pc, media_col_sup, doc_handling_sup);
1402
1403 /*
1404 * Do the request...
1405 */
1406
1407 if (num_files > 1 || create_job)
1408 response = cupsDoRequest(http, request, resource);
1409 else
1410 {
1411 size_t length = 0; /* Length of request */
1412
1413 if (compatsize > 0)
1414 {
1415 fputs("DEBUG: Sending file using HTTP/1.0 Content-Length...\n", stderr);
1416 length = ippLength(request) + (size_t)compatsize;
1417 }
1418 else
1419 fputs("DEBUG: Sending file using HTTP/1.1 chunking...\n", stderr);
1420
1421 http_status = cupsSendRequest(http, request, resource, length);
1422 if (http_status == HTTP_CONTINUE && request->state == IPP_DATA)
1423 {
1424 if (num_files == 1)
1425 {
1426 if ((fd = open(files[0], O_RDONLY)) < 0)
1427 {
1428 _cupsLangPrintError("ERROR", _("Unable to open print file"));
1429 return (CUPS_BACKEND_FAILED);
1430 }
1431 }
1432 else
1433 {
1434 fd = 0;
1435 http_status = cupsWriteRequestData(http, buffer, bytes);
1436 }
1437
1438 while (http_status == HTTP_CONTINUE &&
1439 (!job_canceled || compatsize > 0))
1440 {
1441 /*
1442 * Check for side-channel requests and more print data...
1443 */
1444
1445 FD_ZERO(&input);
1446 FD_SET(fd, &input);
1447 FD_SET(snmp_fd, &input);
1448
1449 while (select(fd > snmp_fd ? fd + 1 : snmp_fd + 1, &input, NULL, NULL,
1450 NULL) <= 0 && !job_canceled);
1451
1452 if (FD_ISSET(snmp_fd, &input))
1453 backendCheckSideChannel(snmp_fd, http->hostaddr);
1454
1455 if (FD_ISSET(fd, &input))
1456 {
1457 if ((bytes = read(fd, buffer, sizeof(buffer))) > 0)
1458 {
1459 fprintf(stderr, "DEBUG: Read %d bytes...\n", (int)bytes);
1460
1461 if (cupsWriteRequestData(http, buffer, bytes) != HTTP_CONTINUE)
1462 break;
1463 }
1464 else if (bytes == 0 || (errno != EINTR && errno != EAGAIN))
1465 break;
1466 }
1467 }
1468
1469 if (num_files == 1)
1470 close(fd);
1471 }
1472
1473 response = cupsGetResponse(http, resource);
1474 ippDelete(request);
1475 }
1476
1477 ipp_status = cupsLastError();
1478
1479 fprintf(stderr, "DEBUG: %s: %s (%s)\n",
1480 (num_files > 1 || create_job) ? "Create-Job" : "Print-Job",
1481 ippErrorString(ipp_status), cupsLastErrorString());
1482
1483 if (ipp_status > IPP_OK_CONFLICT)
1484 {
1485 job_id = 0;
1486
1487 if (job_canceled)
1488 break;
1489
1490 if (ipp_status == IPP_SERVICE_UNAVAILABLE ||
1491 ipp_status == IPP_NOT_POSSIBLE ||
1492 ipp_status == IPP_PRINTER_BUSY)
1493 {
1494 _cupsLangPrintFilter(stderr, "INFO", _("The printer is in use."));
1495 sleep(10);
1496
1497 if (num_files == 0)
1498 {
1499 /*
1500 * We can't re-submit when we have no files to print, so exit
1501 * immediately with the right status code...
1502 */
1503
1504 goto cleanup;
1505 }
1506 }
1507 else if (ipp_status == IPP_ERROR_JOB_CANCELED ||
1508 ipp_status == IPP_NOT_AUTHORIZED)
1509 goto cleanup;
1510 else
1511 {
1512 /*
1513 * Update auth-info-required as needed...
1514 */
1515
1516 _cupsLangPrintFilter(stderr, "ERROR",
1517 _("Print file was not accepted."));
1518
1519 if (ipp_status == IPP_FORBIDDEN ||
1520 ipp_status == IPP_AUTHENTICATION_CANCELED)
1521 {
1522 const char *www_auth = httpGetField(http, HTTP_FIELD_WWW_AUTHENTICATE);
1523 /* WWW-Authenticate field value */
1524
1525 if (!strncmp(www_auth, "Negotiate", 9))
1526 auth_info_required = "negotiate";
1527 else if (www_auth[0])
1528 auth_info_required = "username,password";
1529 }
1530 else if (ipp_status == IPP_REQUEST_VALUE)
1531 {
1532 /*
1533 * Print file is too large, abort this job...
1534 */
1535
1536 goto cleanup;
1537 }
1538 else
1539 sleep(10);
1540
1541 if (num_files == 0)
1542 {
1543 /*
1544 * We can't re-submit when we have no files to print, so exit
1545 * immediately with the right status code...
1546 */
1547
1548 goto cleanup;
1549 }
1550 }
1551 }
1552 else if ((job_id_attr = ippFindAttribute(response, "job-id",
1553 IPP_TAG_INTEGER)) == NULL)
1554 {
1555 _cupsLangPrintFilter(stderr, "INFO",
1556 _("Print file accepted - job ID unknown."));
1557 update_reasons(NULL, "+cups-ipp-conformance-failure-report,"
1558 "cups-ipp-missing-job-id");
1559 job_id = 0;
1560 }
1561 else
1562 {
1563 password_tries = 0;
1564 monitor.job_id = job_id = job_id_attr->values[0].integer;
1565 _cupsLangPrintFilter(stderr, "INFO",
1566 _("Print file accepted - job ID %d."), job_id);
1567 }
1568
1569 fprintf(stderr, "DEBUG: job-id=%d\n", job_id);
1570 ippDelete(response);
1571
1572 if (job_canceled)
1573 break;
1574
1575 if (job_id && (num_files > 1 || create_job))
1576 {
1577 for (i = 0; num_files == 0 || i < num_files; i ++)
1578 {
1579 /*
1580 * Check for side-channel requests...
1581 */
1582
1583 backendCheckSideChannel(snmp_fd, http->hostaddr);
1584
1585 /*
1586 * Send the next file in the job...
1587 */
1588
1589 request = ippNewRequest(IPP_SEND_DOCUMENT);
1590 request->request.op.version[0] = version / 10;
1591 request->request.op.version[1] = version % 10;
1592
1593 ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri",
1594 NULL, uri);
1595
1596 ippAddInteger(request, IPP_TAG_OPERATION, IPP_TAG_INTEGER, "job-id",
1597 job_id);
1598
1599 if (argv[2][0])
1600 ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME,
1601 "requesting-user-name", NULL, argv[2]);
1602
1603 if ((i + 1) >= num_files)
1604 ippAddBoolean(request, IPP_TAG_OPERATION, "last-document", 1);
1605
1606 if (document_format)
1607 ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_MIMETYPE,
1608 "document-format", NULL, document_format);
1609
1610 if (compression)
1611 ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_KEYWORD,
1612 "compression", NULL, compression);
1613
1614 fprintf(stderr, "DEBUG: Sending file %d using chunking...\n", i + 1);
1615 http_status = cupsSendRequest(http, request, resource, 0);
1616 if (http_status == HTTP_CONTINUE && request->state == IPP_DATA)
1617 {
1618 if (num_files == 0)
1619 {
1620 fd = 0;
1621 http_status = cupsWriteRequestData(http, buffer, bytes);
1622 }
1623 else
1624 {
1625 if ((fd = open(files[i], O_RDONLY)) < 0)
1626 {
1627 _cupsLangPrintError("ERROR", _("Unable to open print file"));
1628 return (CUPS_BACKEND_FAILED);
1629 }
1630 }
1631 }
1632 else
1633 fd = -1;
1634
1635 if (fd >= 0)
1636 {
1637 while (!job_canceled && http_status == HTTP_CONTINUE &&
1638 (bytes = read(fd, buffer, sizeof(buffer))) > 0)
1639 {
1640 if ((http_status = cupsWriteRequestData(http, buffer, bytes))
1641 != HTTP_CONTINUE)
1642 break;
1643 else
1644 {
1645 /*
1646 * Check for side-channel requests...
1647 */
1648
1649 backendCheckSideChannel(snmp_fd, http->hostaddr);
1650 }
1651 }
1652
1653 if (fd > 0)
1654 close(fd);
1655 }
1656
1657 ippDelete(cupsGetResponse(http, resource));
1658 ippDelete(request);
1659
1660 fprintf(stderr, "DEBUG: Send-Document: %s (%s)\n",
1661 ippErrorString(cupsLastError()), cupsLastErrorString());
1662
1663 if (cupsLastError() > IPP_OK_CONFLICT)
1664 {
1665 ipp_status = cupsLastError();
1666
1667 _cupsLangPrintFilter(stderr, "ERROR",
1668 _("Unable to add document to print job."));
1669 break;
1670 }
1671 else
1672 {
1673 password_tries = 0;
1674
1675 if (num_files == 0 || fd < 0)
1676 break;
1677 }
1678 }
1679 }
1680
1681 if (ipp_status <= IPP_OK_CONFLICT && argc > 6)
1682 {
1683 fprintf(stderr, "PAGE: 1 %d\n", copies_sup ? atoi(argv[4]) : 1);
1684 copies_remaining --;
1685 }
1686 else if (ipp_status == IPP_SERVICE_UNAVAILABLE ||
1687 ipp_status == IPP_NOT_POSSIBLE ||
1688 ipp_status == IPP_PRINTER_BUSY)
1689 continue;
1690 else if (ipp_status == IPP_REQUEST_VALUE ||
1691 ipp_status == IPP_ERROR_JOB_CANCELED ||
1692 ipp_status == IPP_NOT_AUTHORIZED ||
1693 ipp_status == IPP_INTERNAL_ERROR)
1694 {
1695 /*
1696 * Print file is too large, job was canceled, we need new
1697 * authentication data, or we had some sort of error...
1698 */
1699
1700 goto cleanup;
1701 }
1702 else if (ipp_status == IPP_NOT_FOUND)
1703 {
1704 /*
1705 * Printer does not actually implement support for Create-Job/
1706 * Send-Document, so log the conformance issue and stop the printer.
1707 */
1708
1709 fputs("DEBUG: This printer claims to support Create-Job and "
1710 "Send-Document, but those operations failed.\n", stderr);
1711 fputs("DEBUG: Add '?version=1.0' to the device URI to use legacy "
1712 "compatibility mode.\n", stderr);
1713 update_reasons(NULL, "+cups-ipp-conformance-failure-report,"
1714 "cups-ipp-missing-send-document");
1715
1716 ipp_status = IPP_INTERNAL_ERROR; /* Force queue to stop */
1717
1718 goto cleanup;
1719 }
1720 else
1721 copies_remaining --;
1722
1723 /*
1724 * Wait for the job to complete...
1725 */
1726
1727 if (!job_id || !waitjob || !get_job_attrs)
1728 continue;
1729
1730 _cupsLangPrintFilter(stderr, "INFO", _("Waiting for job to complete."));
1731
1732 for (delay = _cupsNextDelay(0, &prev_delay); !job_canceled;)
1733 {
1734 /*
1735 * Check for side-channel requests...
1736 */
1737
1738 backendCheckSideChannel(snmp_fd, http->hostaddr);
1739
1740 /*
1741 * Build an IPP_GET_JOB_ATTRIBUTES request...
1742 */
1743
1744 request = ippNewRequest(IPP_GET_JOB_ATTRIBUTES);
1745 request->request.op.version[0] = version / 10;
1746 request->request.op.version[1] = version % 10;
1747
1748 ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri",
1749 NULL, uri);
1750
1751 ippAddInteger(request, IPP_TAG_OPERATION, IPP_TAG_INTEGER, "job-id",
1752 job_id);
1753
1754 if (argv[2][0])
1755 ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME,
1756 "requesting-user-name", NULL, argv[2]);
1757
1758 ippAddStrings(request, IPP_TAG_OPERATION, IPP_TAG_KEYWORD,
1759 "requested-attributes", sizeof(jattrs) / sizeof(jattrs[0]),
1760 NULL, jattrs);
1761
1762 /*
1763 * Do the request...
1764 */
1765
1766 httpReconnect(http);
1767 response = cupsDoRequest(http, request, resource);
1768 ipp_status = cupsLastError();
1769
1770 if (ipp_status == IPP_NOT_FOUND || ipp_status == IPP_NOT_POSSIBLE)
1771 {
1772 /*
1773 * Job has gone away and/or the server has no job history...
1774 */
1775
1776 update_reasons(NULL, "+cups-ipp-conformance-failure-report,"
1777 "cups-ipp-missing-job-history");
1778 ippDelete(response);
1779
1780 ipp_status = IPP_OK;
1781 break;
1782 }
1783
1784 fprintf(stderr, "DEBUG: Get-Job-Attributes: %s (%s)\n",
1785 ippErrorString(ipp_status), cupsLastErrorString());
1786
1787 if (ipp_status <= IPP_OK_CONFLICT)
1788 password_tries = 0;
1789 else
1790 {
1791 if (ipp_status != IPP_SERVICE_UNAVAILABLE &&
1792 ipp_status != IPP_PRINTER_BUSY)
1793 {
1794 ippDelete(response);
1795 ipp_status = IPP_OK;
1796 break;
1797 }
1798 }
1799
1800 if (response)
1801 {
1802 if ((job_state = ippFindAttribute(response, "job-state",
1803 IPP_TAG_ENUM)) != NULL)
1804 {
1805 /*
1806 * Reflect the remote job state in the local queue...
1807 */
1808
1809 if (cups_version &&
1810 job_state->values[0].integer >= IPP_JOB_PENDING &&
1811 job_state->values[0].integer <= IPP_JOB_COMPLETED)
1812 update_reasons(NULL,
1813 remote_job_states[job_state->values[0].integer -
1814 IPP_JOB_PENDING]);
1815
1816 if ((job_sheets = ippFindAttribute(response,
1817 "job-media-sheets-completed",
1818 IPP_TAG_INTEGER)) == NULL)
1819 job_sheets = ippFindAttribute(response,
1820 "job-impressions-completed",
1821 IPP_TAG_INTEGER);
1822
1823 if (job_sheets)
1824 fprintf(stderr, "PAGE: total %d\n",
1825 job_sheets->values[0].integer);
1826
1827 /*
1828 * Stop polling if the job is finished or pending-held...
1829 */
1830
1831 if (job_state->values[0].integer > IPP_JOB_STOPPED)
1832 {
1833 ippDelete(response);
1834 break;
1835 }
1836 }
1837 else if (ipp_status != IPP_SERVICE_UNAVAILABLE &&
1838 ipp_status != IPP_NOT_POSSIBLE &&
1839 ipp_status != IPP_PRINTER_BUSY)
1840 {
1841 /*
1842 * If the printer does not return a job-state attribute, it does not
1843 * conform to the IPP specification - break out immediately and fail
1844 * the job...
1845 */
1846
1847 update_reasons(NULL, "+cups-ipp-conformance-failure-report,"
1848 "cups-ipp-missing-job-state");
1849 ipp_status = IPP_INTERNAL_ERROR;
1850 break;
1851 }
1852 }
1853
1854 ippDelete(response);
1855
1856 /*
1857 * Wait before polling again...
1858 */
1859
1860 sleep(delay);
1861
1862 delay = _cupsNextDelay(delay, &prev_delay);
1863 }
1864 }
1865
1866 /*
1867 * Cancel the job as needed...
1868 */
1869
1870 if (job_canceled > 0 && job_id > 0)
1871 cancel_job(http, uri, job_id, resource, argv[2], version);
1872
1873 /*
1874 * Check the printer state and report it if necessary...
1875 */
1876
1877 check_printer_state(http, uri, resource, argv[2], version);
1878
1879 /*
1880 * Collect the final page count as needed...
1881 */
1882
1883 if (have_supplies &&
1884 !backendSNMPSupplies(snmp_fd, http->hostaddr, &page_count, NULL) &&
1885 page_count > start_count)
1886 fprintf(stderr, "PAGE: total %d\n", page_count - start_count);
1887
1888 #ifdef HAVE_GSSAPI
1889 /*
1890 * See if we used Kerberos at all...
1891 */
1892
1893 if (http->gssctx)
1894 auth_info_required = "negotiate";
1895 #endif /* HAVE_GSSAPI */
1896
1897 /*
1898 * Free memory...
1899 */
1900
1901 cleanup:
1902
1903 cupsFreeOptions(num_options, options);
1904 _ppdCacheDestroy(pc);
1905
1906 httpClose(http);
1907
1908 ippDelete(supported);
1909
1910 /*
1911 * Remove the temporary file(s) if necessary...
1912 */
1913
1914 if (tmpfilename[0])
1915 unlink(tmpfilename);
1916
1917 #ifdef HAVE_LIBZ
1918 if (compression)
1919 {
1920 for (i = 0; i < num_files; i ++)
1921 unlink(files[i]);
1922 }
1923 #endif /* HAVE_LIBZ */
1924
1925 /*
1926 * Return the queue status...
1927 */
1928
1929 if (ipp_status == IPP_NOT_AUTHORIZED || ipp_status == IPP_FORBIDDEN ||
1930 ipp_status == IPP_AUTHENTICATION_CANCELED ||
1931 ipp_status <= IPP_OK_CONFLICT)
1932 fprintf(stderr, "ATTR: auth-info-required=%s\n", auth_info_required);
1933
1934 if (ipp_status == IPP_NOT_AUTHORIZED || ipp_status == IPP_FORBIDDEN ||
1935 ipp_status == IPP_AUTHENTICATION_CANCELED)
1936 return (CUPS_BACKEND_AUTH_REQUIRED);
1937 else if (ipp_status == IPP_INTERNAL_ERROR)
1938 return (CUPS_BACKEND_STOP);
1939 else if (ipp_status == IPP_CONFLICT)
1940 return (CUPS_BACKEND_FAILED);
1941 else if (ipp_status == IPP_REQUEST_VALUE ||
1942 ipp_status == IPP_DOCUMENT_FORMAT || job_canceled < 0)
1943 {
1944 if (ipp_status == IPP_REQUEST_VALUE)
1945 _cupsLangPrintFilter(stderr, "ERROR", _("Print job too large."));
1946 else if (ipp_status == IPP_DOCUMENT_FORMAT)
1947 _cupsLangPrintFilter(stderr, "ERROR",
1948 _("Printer cannot print supplied content."));
1949 else
1950 _cupsLangPrintFilter(stderr, "ERROR", _("Print job canceled at printer."));
1951
1952 return (CUPS_BACKEND_CANCEL);
1953 }
1954 else if (ipp_status > IPP_OK_CONFLICT && ipp_status != IPP_ERROR_JOB_CANCELED)
1955 return (CUPS_BACKEND_RETRY_CURRENT);
1956 else
1957 return (CUPS_BACKEND_OK);
1958 }
1959
1960
1961 /*
1962 * 'cancel_job()' - Cancel a print job.
1963 */
1964
1965 static void
1966 cancel_job(http_t *http, /* I - HTTP connection */
1967 const char *uri, /* I - printer-uri */
1968 int id, /* I - job-id */
1969 const char *resource, /* I - Resource path */
1970 const char *user, /* I - requesting-user-name */
1971 int version) /* I - IPP version */
1972 {
1973 ipp_t *request; /* Cancel-Job request */
1974
1975
1976 _cupsLangPrintFilter(stderr, "INFO", _("Canceling print job."));
1977
1978 request = ippNewRequest(IPP_CANCEL_JOB);
1979 request->request.op.version[0] = version / 10;
1980 request->request.op.version[1] = version % 10;
1981
1982 ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri",
1983 NULL, uri);
1984 ippAddInteger(request, IPP_TAG_OPERATION, IPP_TAG_INTEGER, "job-id", id);
1985
1986 if (user && user[0])
1987 ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME,
1988 "requesting-user-name", NULL, user);
1989
1990 /*
1991 * Do the request...
1992 */
1993
1994 ippDelete(cupsDoRequest(http, request, resource));
1995
1996 if (cupsLastError() > IPP_OK_CONFLICT)
1997 _cupsLangPrintFilter(stderr, "ERROR", _("Unable to cancel print job."));
1998 }
1999
2000
2001 /*
2002 * 'check_printer_state()' - Check the printer state.
2003 */
2004
2005 static ipp_pstate_t /* O - Current printer-state */
2006 check_printer_state(
2007 http_t *http, /* I - HTTP connection */
2008 const char *uri, /* I - Printer URI */
2009 const char *resource, /* I - Resource path */
2010 const char *user, /* I - Username, if any */
2011 int version) /* I - IPP version */
2012 {
2013 ipp_t *request, /* IPP request */
2014 *response; /* IPP response */
2015 ipp_attribute_t *attr; /* Attribute in response */
2016 ipp_pstate_t printer_state = IPP_PRINTER_STOPPED;
2017 /* Current printer-state */
2018
2019
2020 /*
2021 * Send a Get-Printer-Attributes request and log the results...
2022 */
2023
2024 request = ippNewRequest(IPP_GET_PRINTER_ATTRIBUTES);
2025 request->request.op.version[0] = version / 10;
2026 request->request.op.version[1] = version % 10;
2027
2028 ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri",
2029 NULL, uri);
2030
2031 if (user && user[0])
2032 ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME,
2033 "requesting-user-name", NULL, user);
2034
2035 ippAddStrings(request, IPP_TAG_OPERATION, IPP_TAG_KEYWORD,
2036 "requested-attributes",
2037 (int)(sizeof(pattrs) / sizeof(pattrs[0])), NULL, pattrs);
2038
2039 if ((response = cupsDoRequest(http, request, resource)) != NULL)
2040 {
2041 report_printer_state(response);
2042
2043 if ((attr = ippFindAttribute(response, "printer-state",
2044 IPP_TAG_ENUM)) != NULL)
2045 printer_state = (ipp_pstate_t)attr->values[0].integer;
2046
2047 ippDelete(response);
2048 }
2049
2050 fprintf(stderr, "DEBUG: Get-Printer-Attributes: %s (%s)\n",
2051 ippErrorString(cupsLastError()), cupsLastErrorString());
2052
2053 if (cupsLastError() <= IPP_OK_CONFLICT)
2054 password_tries = 0;
2055
2056 /*
2057 * Return the printer-state value...
2058 */
2059
2060 return (printer_state);
2061 }
2062
2063
2064 #ifdef HAVE_LIBZ
2065 /*
2066 * 'compress_files()' - Compress print files.
2067 */
2068
2069 static void
2070 compress_files(int num_files, /* I - Number of files */
2071 char **files) /* I - Files */
2072 {
2073 int i, /* Looping var */
2074 fd; /* Temporary file descriptor */
2075 ssize_t bytes; /* Bytes read/written */
2076 size_t total; /* Total bytes read */
2077 cups_file_t *in, /* Input file */
2078 *out; /* Output file */
2079 struct stat outinfo; /* Output file information */
2080 char filename[1024], /* Temporary filename */
2081 buffer[32768]; /* Copy buffer */
2082
2083
2084 fprintf(stderr, "DEBUG: Compressing %d job files...\n", num_files);
2085 for (i = 0; i < num_files; i ++)
2086 {
2087 if ((fd = cupsTempFd(filename, sizeof(filename))) < 0)
2088 {
2089 _cupsLangPrintError("ERROR", _("Unable to create compressed print file"));
2090 exit(CUPS_BACKEND_FAILED);
2091 }
2092
2093 if ((out = cupsFileOpenFd(fd, "w9")) == NULL)
2094 {
2095 _cupsLangPrintError("ERROR", _("Unable to open compressed print file"));
2096 exit(CUPS_BACKEND_FAILED);
2097 }
2098
2099 if ((in = cupsFileOpen(files[i], "r")) == NULL)
2100 {
2101 _cupsLangPrintError("ERROR", _("Unable to open print file"));
2102 cupsFileClose(out);
2103 exit(CUPS_BACKEND_FAILED);
2104 }
2105
2106 total = 0;
2107 while ((bytes = cupsFileRead(in, buffer, sizeof(buffer))) > 0)
2108 if (cupsFileWrite(out, buffer, bytes) < bytes)
2109 {
2110 _cupsLangPrintError("ERROR",
2111 _("Unable to generate compressed print file"));
2112 cupsFileClose(in);
2113 cupsFileClose(out);
2114 exit(CUPS_BACKEND_FAILED);
2115 }
2116 else
2117 total += bytes;
2118
2119 cupsFileClose(out);
2120 cupsFileClose(in);
2121
2122 files[i] = strdup(filename);
2123
2124 if (!stat(filename, &outinfo))
2125 fprintf(stderr,
2126 "DEBUG: File %d compressed to %.1f%% of original size, "
2127 CUPS_LLFMT " bytes...\n",
2128 i + 1, 100.0 * outinfo.st_size / total,
2129 CUPS_LLCAST outinfo.st_size);
2130 }
2131 }
2132 #endif /* HAVE_LIBZ */
2133
2134
2135 /*
2136 * 'monitor_printer()' - Monitor the printer state.
2137 */
2138
2139 static void * /* O - Thread exit code */
2140 monitor_printer(
2141 _cups_monitor_t *monitor) /* I - Monitoring data */
2142 {
2143 http_t *http; /* Connection to printer */
2144 ipp_t *request, /* IPP request */
2145 *response; /* IPP response */
2146 ipp_attribute_t *attr; /* Attribute in response */
2147 int delay, /* Current delay */
2148 prev_delay; /* Previous delay */
2149 ipp_op_t job_op; /* Operation to use */
2150 int job_id; /* Job ID */
2151 const char *job_name; /* Job name */
2152 ipp_jstate_t job_state; /* Job state */
2153 const char *job_user; /* Job originating user name */
2154
2155
2156 /*
2157 * Make a copy of the printer connection...
2158 */
2159
2160 http = _httpCreate(monitor->hostname, monitor->port, NULL, monitor->encryption,
2161 AF_UNSPEC);
2162 httpSetTimeout(http, 30.0, timeout_cb, NULL);
2163 if (username[0])
2164 cupsSetUser(username);
2165 cupsSetPasswordCB2(password_cb, NULL);
2166
2167 /*
2168 * Loop until the job is canceled, aborted, or completed.
2169 */
2170
2171 delay = _cupsNextDelay(0, &prev_delay);
2172
2173 while (monitor->job_state < IPP_JOB_CANCELED && !job_canceled)
2174 {
2175 /*
2176 * Reconnect to the printer...
2177 */
2178
2179 if (!httpReconnect(http))
2180 {
2181 /*
2182 * Connected, so check on the printer state...
2183 */
2184
2185 monitor->printer_state = check_printer_state(http, monitor->uri,
2186 monitor->resource,
2187 monitor->user,
2188 monitor->version);
2189
2190 /*
2191 * Check the status of the job itself...
2192 */
2193
2194 job_op = (monitor->job_id > 0 && monitor->get_job_attrs) ?
2195 IPP_GET_JOB_ATTRIBUTES : IPP_GET_JOBS;
2196 request = ippNewRequest(job_op);
2197 request->request.op.version[0] = monitor->version / 10;
2198 request->request.op.version[1] = monitor->version % 10;
2199
2200 ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri",
2201 NULL, monitor->uri);
2202 if (job_op == IPP_GET_JOB_ATTRIBUTES)
2203 ippAddInteger(request, IPP_TAG_OPERATION, IPP_TAG_INTEGER, "job-id",
2204 monitor->job_id);
2205
2206 if (monitor->user && monitor->user[0])
2207 ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME,
2208 "requesting-user-name", NULL, monitor->user);
2209
2210 ippAddStrings(request, IPP_TAG_OPERATION, IPP_TAG_KEYWORD,
2211 "requested-attributes",
2212 (int)(sizeof(jattrs) / sizeof(jattrs[0])), NULL, jattrs);
2213
2214 /*
2215 * Do the request...
2216 */
2217
2218 response = cupsDoRequest(http, request, monitor->resource);
2219
2220 fprintf(stderr, "DEBUG: (monitor) %s: %s (%s)\n", ippOpString(job_op),
2221 ippErrorString(cupsLastError()), cupsLastErrorString());
2222
2223 if (cupsLastError() <= IPP_OK_CONFLICT)
2224 password_tries = 0;
2225
2226 if (job_op == IPP_GET_JOB_ATTRIBUTES)
2227 {
2228 if ((attr = ippFindAttribute(response, "job-state",
2229 IPP_TAG_ENUM)) != NULL)
2230 monitor->job_state = (ipp_jstate_t)attr->values[0].integer;
2231 else
2232 monitor->job_state = IPP_JOB_COMPLETED;
2233 }
2234 else if (response)
2235 {
2236 for (attr = response->attrs; attr; attr = attr->next)
2237 {
2238 job_id = 0;
2239 job_name = NULL;
2240 job_state = IPP_JOB_PENDING;
2241 job_user = NULL;
2242
2243 while (attr && attr->group_tag != IPP_TAG_JOB)
2244 attr = attr->next;
2245
2246 if (!attr)
2247 break;
2248
2249 while (attr && attr->group_tag == IPP_TAG_JOB)
2250 {
2251 if (!strcmp(attr->name, "job-id") &&
2252 attr->value_tag == IPP_TAG_INTEGER)
2253 job_id = attr->values[0].integer;
2254 else if (!strcmp(attr->name, "job-name") &&
2255 (attr->value_tag == IPP_TAG_NAME ||
2256 attr->value_tag == IPP_TAG_NAMELANG))
2257 job_name = attr->values[0].string.text;
2258 else if (!strcmp(attr->name, "job-state") &&
2259 attr->value_tag == IPP_TAG_ENUM)
2260 job_state = attr->values[0].integer;
2261 else if (!strcmp(attr->name, "job-originating-user-name") &&
2262 (attr->value_tag == IPP_TAG_NAME ||
2263 attr->value_tag == IPP_TAG_NAMELANG))
2264 job_user = attr->values[0].string.text;
2265
2266 attr = attr->next;
2267 }
2268
2269 if (job_id > 0 && job_name && !strcmp(job_name, monitor->job_name) &&
2270 job_user && monitor->user && !strcmp(job_user, monitor->user))
2271 {
2272 monitor->job_id = job_id;
2273 monitor->job_state = job_state;
2274 break;
2275 }
2276
2277 if (!attr)
2278 break;
2279 }
2280 }
2281
2282 ippDelete(response);
2283
2284 fprintf(stderr, "DEBUG: (monitor) job-state=%s\n",
2285 ippEnumString("job-state", monitor->job_state));
2286
2287 if (!job_canceled &&
2288 (monitor->job_state == IPP_JOB_CANCELED ||
2289 monitor->job_state == IPP_JOB_ABORTED))
2290 job_canceled = -1;
2291
2292 /*
2293 * Disconnect from the printer - we'll reconnect on the next poll...
2294 */
2295
2296 _httpDisconnect(http);
2297 }
2298
2299 /*
2300 * Sleep for N seconds...
2301 */
2302
2303 sleep(delay);
2304
2305 delay = _cupsNextDelay(delay, &prev_delay);
2306 }
2307
2308 /*
2309 * Cancel the job if necessary...
2310 */
2311
2312 if (job_canceled > 0 && monitor->job_id > 0)
2313 if (!httpReconnect(http))
2314 cancel_job(http, monitor->uri, monitor->job_id, monitor->resource,
2315 monitor->user, monitor->version);
2316
2317 /*
2318 * Cleanup and return...
2319 */
2320
2321 httpClose(http);
2322
2323 return (NULL);
2324 }
2325
2326
2327 /*
2328 * 'new_request()' - Create a new print creation or validation request.
2329 */
2330
2331 static ipp_t * /* O - Request data */
2332 new_request(
2333 ipp_op_t op, /* I - IPP operation code */
2334 int version, /* I - IPP version number */
2335 const char *uri, /* I - printer-uri value */
2336 const char *user, /* I - requesting-user-name value */
2337 const char *title, /* I - job-name value */
2338 int num_options, /* I - Number of options to send */
2339 cups_option_t *options, /* I - Options to send */
2340 const char *compression, /* I - compression value or NULL */
2341 int copies, /* I - copies value or 0 */
2342 const char *format, /* I - document-format value or NULL */
2343 _ppd_cache_t *pc, /* I - PPD cache and mapping data */
2344 ipp_attribute_t *media_col_sup, /* I - media-col-supported values */
2345 ipp_attribute_t *doc_handling_sup) /* I - multiple-document-handling-supported values */
2346 {
2347 int i; /* Looping var */
2348 ipp_t *request; /* Request data */
2349 const char *keyword; /* PWG keyword */
2350 _pwg_size_t *size; /* PWG media size */
2351 ipp_t *media_col, /* media-col value */
2352 *media_size; /* media-size value */
2353 const char *media_source, /* media-source value */
2354 *media_type, /* media-type value */
2355 *collate_str, /* multiple-document-handling value */
2356 *mandatory; /* Mandatory attributes */
2357
2358
2359 /*
2360 * Create the IPP request...
2361 */
2362
2363 request = ippNewRequest(op);
2364 request->request.op.version[0] = version / 10;
2365 request->request.op.version[1] = version % 10;
2366
2367 fprintf(stderr, "DEBUG: %s IPP/%d.%d\n",
2368 ippOpString(request->request.op.operation_id),
2369 request->request.op.version[0],
2370 request->request.op.version[1]);
2371
2372 /*
2373 * Add standard attributes...
2374 */
2375
2376 ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri",
2377 NULL, uri);
2378 fprintf(stderr, "DEBUG: printer-uri=\"%s\"\n", uri);
2379
2380 if (user && *user)
2381 {
2382 ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME,
2383 "requesting-user-name", NULL, user);
2384 fprintf(stderr, "DEBUG: requesting-user-name=\"%s\"\n", user);
2385 }
2386
2387 if (title && *title)
2388 {
2389 ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME, "job-name", NULL,
2390 title);
2391 fprintf(stderr, "DEBUG: job-name=\"%s\"\n", title);
2392 }
2393
2394 if (format && op != IPP_CREATE_JOB)
2395 {
2396 ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_MIMETYPE,
2397 "document-format", NULL, format);
2398 fprintf(stderr, "DEBUG: document-format=\"%s\"\n", format);
2399 }
2400
2401 #ifdef HAVE_LIBZ
2402 if (compression && op != IPP_CREATE_JOB)
2403 {
2404 ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_KEYWORD,
2405 "compression", NULL, compression);
2406 fprintf(stderr, "DEBUG: compression=\"%s\"\n", compression);
2407 }
2408 #endif /* HAVE_LIBZ */
2409
2410 /*
2411 * Handle options on the command-line...
2412 */
2413
2414 if (num_options > 0)
2415 {
2416 if (pc)
2417 {
2418 int num_finishings = 0, /* Number of finishing values */
2419 finishings[10]; /* Finishing enum values */
2420
2421 /*
2422 * Send standard IPP attributes...
2423 */
2424
2425 if (pc->password &&
2426 (keyword = cupsGetOption("job-password", num_options,
2427 options)) != NULL)
2428 {
2429 ippAddOctetString(request, IPP_TAG_OPERATION, "job-password",
2430 keyword, strlen(keyword));
2431 ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_KEYWORD,
2432 "job-password-encryption", NULL, "none");
2433 }
2434
2435 if (pc->account_id &&
2436 (keyword = cupsGetOption("job-account-id", num_options,
2437 options)) != NULL)
2438 ippAddString(request, IPP_TAG_JOB, IPP_TAG_NAME, "job-account-id",
2439 NULL, keyword);
2440
2441 if (pc->account_id &&
2442 (keyword = cupsGetOption("job-accounting-user-id", num_options,
2443 options)) != NULL)
2444 ippAddString(request, IPP_TAG_JOB, IPP_TAG_NAME,
2445 "job-accounting-user-id", NULL, keyword);
2446
2447 for (mandatory = (char *)cupsArrayFirst(pc->mandatory);
2448 mandatory;
2449 mandatory = (char *)cupsArrayNext(pc->mandatory))
2450 {
2451 if (strcmp(mandatory, "copies") &&
2452 strcmp(mandatory, "destination-uris") &&
2453 strcmp(mandatory, "finishings") &&
2454 strcmp(mandatory, "job-account-id") &&
2455 strcmp(mandatory, "job-accounting-user-id") &&
2456 strcmp(mandatory, "job-password") &&
2457 strcmp(mandatory, "media") &&
2458 strncmp(mandatory, "media-col", 9) &&
2459 strcmp(mandatory, "multiple-document-handling") &&
2460 strcmp(mandatory, "output-bin") &&
2461 strcmp(mandatory, "print-color-mode") &&
2462 strcmp(mandatory, "print-quality") &&
2463 strcmp(mandatory, "sides") &&
2464 (keyword = cupsGetOption(mandatory, num_options, options)) != NULL)
2465 {
2466 _ipp_option_t *opt = _ippFindOption(mandatory);
2467 /* Option type */
2468 ipp_tag_t value_tag = opt ? opt->value_tag : IPP_TAG_NAME;
2469 /* Value type */
2470
2471 switch (value_tag)
2472 {
2473 case IPP_TAG_INTEGER :
2474 case IPP_TAG_ENUM :
2475 ippAddInteger(request, IPP_TAG_JOB, value_tag, mandatory,
2476 atoi(keyword));
2477 break;
2478 case IPP_TAG_BOOLEAN :
2479 ippAddBoolean(request, IPP_TAG_JOB, mandatory,
2480 !_cups_strcasecmp(keyword, "true"));
2481 break;
2482 case IPP_TAG_RANGE :
2483 {
2484 int lower, upper; /* Range */
2485
2486 if (sscanf(keyword, "%d-%d", &lower, &upper) != 2)
2487 lower = upper = atoi(keyword);
2488
2489 ippAddRange(request, IPP_TAG_JOB, mandatory, lower, upper);
2490 }
2491 break;
2492 case IPP_TAG_STRING :
2493 ippAddOctetString(request, IPP_TAG_JOB, mandatory, keyword,
2494 strlen(keyword));
2495 break;
2496 default :
2497 ippAddString(request, IPP_TAG_JOB, value_tag, mandatory,
2498 NULL, keyword);
2499 break;
2500 }
2501 }
2502 }
2503
2504 if ((keyword = cupsGetOption("PageSize", num_options, options)) == NULL)
2505 keyword = cupsGetOption("media", num_options, options);
2506
2507 if ((size = _ppdCacheGetSize(pc, keyword)) != NULL)
2508 {
2509 /*
2510 * Add a media-col value...
2511 */
2512
2513 media_size = ippNew();
2514 ippAddInteger(media_size, IPP_TAG_ZERO, IPP_TAG_INTEGER,
2515 "x-dimension", size->width);
2516 ippAddInteger(media_size, IPP_TAG_ZERO, IPP_TAG_INTEGER,
2517 "y-dimension", size->length);
2518
2519 media_col = ippNew();
2520 ippAddCollection(media_col, IPP_TAG_ZERO, "media-size", media_size);
2521
2522 media_source = _ppdCacheGetSource(pc, cupsGetOption("InputSlot",
2523 num_options,
2524 options));
2525 media_type = _ppdCacheGetType(pc, cupsGetOption("MediaType",
2526 num_options,
2527 options));
2528
2529 for (i = 0; i < media_col_sup->num_values; i ++)
2530 {
2531 if (!strcmp(media_col_sup->values[i].string.text,
2532 "media-left-margin"))
2533 ippAddInteger(media_col, IPP_TAG_ZERO, IPP_TAG_INTEGER,
2534 "media-left-margin", size->left);
2535 else if (!strcmp(media_col_sup->values[i].string.text,
2536 "media-bottom-margin"))
2537 ippAddInteger(media_col, IPP_TAG_ZERO, IPP_TAG_INTEGER,
2538 "media-bottom-margin", size->bottom);
2539 else if (!strcmp(media_col_sup->values[i].string.text,
2540 "media-right-margin"))
2541 ippAddInteger(media_col, IPP_TAG_ZERO, IPP_TAG_INTEGER,
2542 "media-right-margin", size->right);
2543 else if (!strcmp(media_col_sup->values[i].string.text,
2544 "media-top-margin"))
2545 ippAddInteger(media_col, IPP_TAG_ZERO, IPP_TAG_INTEGER,
2546 "media-top-margin", size->top);
2547 else if (!strcmp(media_col_sup->values[i].string.text,
2548 "media-source") && media_source)
2549 ippAddString(media_col, IPP_TAG_ZERO, IPP_TAG_KEYWORD,
2550 "media-source", NULL, media_source);
2551 else if (!strcmp(media_col_sup->values[i].string.text,
2552 "media-type") && media_type)
2553 ippAddString(media_col, IPP_TAG_ZERO, IPP_TAG_KEYWORD,
2554 "media-type", NULL, media_type);
2555 }
2556
2557 ippAddCollection(request, IPP_TAG_JOB, "media-col", media_col);
2558 }
2559
2560 if ((keyword = cupsGetOption("output-bin", num_options,
2561 options)) == NULL)
2562 keyword = _ppdCacheGetBin(pc, cupsGetOption("OutputBin", num_options,
2563 options));
2564
2565 if (keyword)
2566 ippAddString(request, IPP_TAG_JOB, IPP_TAG_KEYWORD, "output-bin",
2567 NULL, keyword);
2568
2569 if ((keyword = cupsGetOption("print-color-mode", num_options,
2570 options)) != NULL)
2571 ippAddString(request, IPP_TAG_JOB, IPP_TAG_KEYWORD, "print-color-mode",
2572 NULL, keyword);
2573 else if ((keyword = cupsGetOption("ColorModel", num_options,
2574 options)) != NULL)
2575 {
2576 if (!_cups_strcasecmp(keyword, "Gray"))
2577 ippAddString(request, IPP_TAG_JOB, IPP_TAG_KEYWORD,
2578 "print-color-mode", NULL, "monochrome");
2579 else
2580 ippAddString(request, IPP_TAG_JOB, IPP_TAG_KEYWORD,
2581 "print-color-mode", NULL, "color");
2582 }
2583
2584 if ((keyword = cupsGetOption("print-quality", num_options,
2585 options)) != NULL)
2586 ippAddInteger(request, IPP_TAG_JOB, IPP_TAG_ENUM, "print-quality",
2587 atoi(keyword));
2588 else if ((keyword = cupsGetOption("cupsPrintQuality", num_options,
2589 options)) != NULL)
2590 {
2591 if (!_cups_strcasecmp(keyword, "draft"))
2592 ippAddInteger(request, IPP_TAG_JOB, IPP_TAG_ENUM, "print-quality",
2593 IPP_QUALITY_DRAFT);
2594 else if (!_cups_strcasecmp(keyword, "normal"))
2595 ippAddInteger(request, IPP_TAG_JOB, IPP_TAG_ENUM, "print-quality",
2596 IPP_QUALITY_NORMAL);
2597 else if (!_cups_strcasecmp(keyword, "high"))
2598 ippAddInteger(request, IPP_TAG_JOB, IPP_TAG_ENUM, "print-quality",
2599 IPP_QUALITY_HIGH);
2600 }
2601
2602 if ((keyword = cupsGetOption("sides", num_options, options)) != NULL)
2603 ippAddString(request, IPP_TAG_JOB, IPP_TAG_KEYWORD, "sides",
2604 NULL, keyword);
2605 else if (pc->sides_option &&
2606 (keyword = cupsGetOption(pc->sides_option, num_options,
2607 options)) != NULL)
2608 {
2609 if (!_cups_strcasecmp(keyword, pc->sides_1sided))
2610 ippAddString(request, IPP_TAG_JOB, IPP_TAG_KEYWORD, "sides",
2611 NULL, "one-sided");
2612 else if (!_cups_strcasecmp(keyword, pc->sides_2sided_long))
2613 ippAddString(request, IPP_TAG_JOB, IPP_TAG_KEYWORD, "sides",
2614 NULL, "two-sided-long-edge");
2615 if (!_cups_strcasecmp(keyword, pc->sides_2sided_short))
2616 ippAddString(request, IPP_TAG_JOB, IPP_TAG_KEYWORD, "sides",
2617 NULL, "two-sided-short-edge");
2618 }
2619
2620 if ((keyword = cupsGetOption("multiple-document-handling",
2621 num_options, options)) != NULL)
2622 {
2623 if (strstr(keyword, "uncollated"))
2624 keyword = "false";
2625 else
2626 keyword = "true";
2627 }
2628 else if ((keyword = cupsGetOption("collate", num_options,
2629 options)) == NULL)
2630 keyword = "true";
2631
2632 if (format)
2633 {
2634 if (!_cups_strcasecmp(format, "image/gif") ||
2635 !_cups_strcasecmp(format, "image/jp2") ||
2636 !_cups_strcasecmp(format, "image/jpeg") ||
2637 !_cups_strcasecmp(format, "image/png") ||
2638 !_cups_strcasecmp(format, "image/tiff") ||
2639 !_cups_strncasecmp(format, "image/x-", 8))
2640 {
2641 /*
2642 * Collation makes no sense for single page image formats...
2643 */
2644
2645 keyword = "false";
2646 }
2647 else if (!_cups_strncasecmp(format, "image/", 6) ||
2648 !_cups_strcasecmp(format, "application/vnd.cups-raster"))
2649 {
2650 /*
2651 * Multi-page image formats will have copies applied by the upstream
2652 * filters...
2653 */
2654
2655 copies = 1;
2656 }
2657 }
2658
2659 if (doc_handling_sup)
2660 {
2661 if (!_cups_strcasecmp(keyword, "true"))
2662 collate_str = "separate-documents-collated-copies";
2663 else
2664 collate_str = "separate-documents-uncollated-copies";
2665
2666 for (i = 0; i < doc_handling_sup->num_values; i ++)
2667 if (!strcmp(doc_handling_sup->values[i].string.text, collate_str))
2668 {
2669 ippAddString(request, IPP_TAG_JOB, IPP_TAG_KEYWORD,
2670 "multiple-document-handling", NULL, collate_str);
2671 break;
2672 }
2673
2674 if (i >= doc_handling_sup->num_values)
2675 copies = 1;
2676 }
2677
2678 /*
2679 * Map finishing options...
2680 */
2681
2682 num_finishings = _ppdCacheGetFinishingValues(pc, num_options, options,
2683 (int)(sizeof(finishings) /
2684 sizeof(finishings[0])),
2685 finishings);
2686 if (num_finishings > 0)
2687 ippAddIntegers(request, IPP_TAG_JOB, IPP_TAG_ENUM, "finishings",
2688 num_finishings, finishings);
2689
2690 /*
2691 * Map FaxOut options...
2692 */
2693
2694 if ((keyword = cupsGetOption("phone", num_options, options)) != NULL)
2695 {
2696 ipp_t *destination; /* destination collection */
2697 char tel_uri[1024]; /* tel: URI */
2698
2699 destination = ippNew();
2700
2701 httpAssembleURI(HTTP_URI_CODING_ALL, tel_uri, sizeof(tel_uri), "tel",
2702 NULL, NULL, 0, keyword);
2703 ippAddString(destination, IPP_TAG_JOB, IPP_TAG_URI, "destination-uri",
2704 NULL, tel_uri);
2705
2706 if ((keyword = cupsGetOption("faxPrefix", num_options,
2707 options)) != NULL && *keyword)
2708 ippAddString(destination, IPP_TAG_JOB, IPP_TAG_TEXT,
2709 "pre-dial-string", NULL, keyword);
2710
2711 ippAddCollection(request, IPP_TAG_JOB, "destination-uris", destination);
2712 ippDelete(destination);
2713 }
2714 }
2715 else
2716 {
2717 /*
2718 * When talking to another CUPS server, send all options...
2719 */
2720
2721 cupsEncodeOptions2(request, num_options, options, IPP_TAG_JOB);
2722 }
2723
2724 if (copies > 1 && (!pc || copies <= pc->max_copies))
2725 ippAddInteger(request, IPP_TAG_JOB, IPP_TAG_INTEGER, "copies", copies);
2726 }
2727
2728 return (request);
2729 }
2730
2731
2732 /*
2733 * 'password_cb()' - Disable the password prompt for cupsDoFileRequest().
2734 */
2735
2736 static const char * /* O - Password */
2737 password_cb(const char *prompt, /* I - Prompt (not used) */
2738 http_t *http, /* I - Connection */
2739 const char *method, /* I - Request method (not used) */
2740 const char *resource, /* I - Resource path (not used) */
2741 void *user_data) /* I - User data (not used) */
2742 {
2743 char def_username[HTTP_MAX_VALUE]; /* Default username */
2744
2745
2746 fprintf(stderr, "DEBUG: password_cb(prompt=\"%s\"), password=%p, "
2747 "password_tries=%d\n", prompt, password, password_tries);
2748
2749 (void)prompt;
2750 (void)method;
2751 (void)resource;
2752 (void)user_data;
2753
2754 /*
2755 * Remember that we need to authenticate...
2756 */
2757
2758 auth_info_required = "username,password";
2759
2760 if (httpGetSubField(http, HTTP_FIELD_WWW_AUTHENTICATE, "username",
2761 def_username))
2762 {
2763 char quoted[HTTP_MAX_VALUE * 2 + 4];
2764 /* Quoted string */
2765
2766 fprintf(stderr, "ATTR: auth-info-default=%s,\n",
2767 quote_string(def_username, quoted, sizeof(quoted)));
2768 }
2769
2770 if (password && *password && password_tries < 3)
2771 {
2772 password_tries ++;
2773
2774 return (password);
2775 }
2776 else
2777 {
2778 /*
2779 * Give up after 3 tries or if we don't have a password to begin with...
2780 */
2781
2782 return (NULL);
2783 }
2784 }
2785
2786
2787 /*
2788 * 'quote_string()' - Quote a string value.
2789 */
2790
2791 static const char * /* O - Quoted string */
2792 quote_string(const char *s, /* I - String */
2793 char *q, /* I - Quoted string buffer */
2794 size_t qsize) /* I - Size of quoted string buffer */
2795 {
2796 char *qptr, /* Pointer into string buffer */
2797 *qend; /* End of string buffer */
2798
2799
2800 qptr = q;
2801 qend = q + qsize - 5;
2802
2803 if (qend < q)
2804 {
2805 *q = '\0';
2806 return (q);
2807 }
2808
2809 *qptr++ = '\'';
2810 *qptr++ = '\"';
2811
2812 while (*s && qptr < qend)
2813 {
2814 if (*s == '\\' || *s == '\"' || *s == '\'')
2815 {
2816 if (q < (qend - 3))
2817 {
2818 *qptr++ = '\\';
2819 *qptr++ = '\\';
2820 *qptr++ = '\\';
2821 }
2822 else
2823 break;
2824 }
2825
2826 *qptr++ = *s++;
2827 }
2828
2829 *qptr++ = '\"';
2830 *qptr++ = '\'';
2831 *qptr = '\0';
2832
2833 return (q);
2834 }
2835
2836
2837 /*
2838 * 'report_attr()' - Report an IPP attribute value.
2839 */
2840
2841 static void
2842 report_attr(ipp_attribute_t *attr) /* I - Attribute */
2843 {
2844 int i; /* Looping var */
2845 char value[1024], /* Value string */
2846 *valptr; /* Pointer into value string */
2847 const char *cached; /* Cached attribute */
2848
2849
2850 /*
2851 * Convert the attribute values into quoted strings...
2852 */
2853
2854 for (i = 0, valptr = value;
2855 i < attr->num_values && valptr < (value + sizeof(value) - 10);
2856 i ++)
2857 {
2858 if (i > 0)
2859 *valptr++ = ',';
2860
2861 switch (attr->value_tag)
2862 {
2863 case IPP_TAG_INTEGER :
2864 case IPP_TAG_ENUM :
2865 snprintf(valptr, sizeof(value) - (valptr - value), "%d",
2866 attr->values[i].integer);
2867 valptr += strlen(valptr);
2868 break;
2869
2870 case IPP_TAG_TEXT :
2871 case IPP_TAG_NAME :
2872 case IPP_TAG_KEYWORD :
2873 quote_string(attr->values[i].string.text, valptr,
2874 value + sizeof(value) - valptr);
2875 valptr += strlen(valptr);
2876 break;
2877
2878 default :
2879 /*
2880 * Unsupported value type...
2881 */
2882
2883 return;
2884 }
2885 }
2886
2887 *valptr = '\0';
2888
2889 _cupsMutexLock(&report_mutex);
2890
2891 if ((cached = cupsGetOption(attr->name, num_attr_cache,
2892 attr_cache)) == NULL || strcmp(cached, value))
2893 {
2894 /*
2895 * Tell the scheduler about the new values...
2896 */
2897
2898 num_attr_cache = cupsAddOption(attr->name, value, num_attr_cache,
2899 &attr_cache);
2900 fprintf(stderr, "ATTR: %s=%s\n", attr->name, value);
2901 }
2902
2903 _cupsMutexUnlock(&report_mutex);
2904 }
2905
2906
2907 /*
2908 * 'report_printer_state()' - Report the printer state.
2909 */
2910
2911 static void
2912 report_printer_state(ipp_t *ipp) /* I - IPP response */
2913 {
2914 ipp_attribute_t *pa, /* printer-alert */
2915 *pam, /* printer-alert-message */
2916 *psm, /* printer-state-message */
2917 *reasons, /* printer-state-reasons */
2918 *marker; /* marker-* attributes */
2919 char value[1024], /* State/message string */
2920 *valptr; /* Pointer into string */
2921 static int ipp_supplies = -1;
2922 /* Report supply levels? */
2923
2924
2925 /*
2926 * Report alerts and messages...
2927 */
2928
2929 if ((pa = ippFindAttribute(ipp, "printer-alert", IPP_TAG_TEXT)) != NULL)
2930 report_attr(pa);
2931
2932 if ((pam = ippFindAttribute(ipp, "printer-alert-message",
2933 IPP_TAG_TEXT)) != NULL)
2934 report_attr(pam);
2935
2936 if ((psm = ippFindAttribute(ipp, "printer-state-message",
2937 IPP_TAG_TEXT)) != NULL)
2938 {
2939 char *ptr; /* Pointer into message */
2940
2941
2942 strlcpy(value, "INFO: ", sizeof(value));
2943 for (ptr = psm->values[0].string.text, valptr = value + 6;
2944 *ptr && valptr < (value + sizeof(value) - 6);
2945 ptr ++)
2946 {
2947 if (*ptr < ' ' && *ptr > 0 && *ptr != '\t')
2948 {
2949 /*
2950 * Substitute "<XX>" for the control character; sprintf is safe because
2951 * we always leave 6 chars free at the end...
2952 */
2953
2954 sprintf(valptr, "<%02X>", *ptr);
2955 valptr += 4;
2956 }
2957 else
2958 *valptr++ = *ptr;
2959 }
2960
2961 *valptr++ = '\n';
2962 *valptr = '\0';
2963
2964 fputs(value, stderr);
2965 }
2966
2967 /*
2968 * Now report printer-state-reasons, filtering out some of the reasons we never
2969 * want to set...
2970 */
2971
2972 if ((reasons = ippFindAttribute(ipp, "printer-state-reasons",
2973 IPP_TAG_KEYWORD)) == NULL)
2974 return;
2975
2976 update_reasons(reasons, NULL);
2977
2978 /*
2979 * Relay the current marker-* attribute values...
2980 */
2981
2982 if (ipp_supplies < 0)
2983 {
2984 ppd_file_t *ppd; /* PPD file */
2985 ppd_attr_t *ppdattr; /* Attribute in PPD file */
2986
2987 if ((ppd = ppdOpenFile(getenv("PPD"))) != NULL &&
2988 (ppdattr = ppdFindAttr(ppd, "cupsIPPSupplies", NULL)) != NULL &&
2989 ppdattr->value && _cups_strcasecmp(ppdattr->value, "true"))
2990 ipp_supplies = 0;
2991 else
2992 ipp_supplies = 1;
2993
2994 ppdClose(ppd);
2995 }
2996
2997 if (ipp_supplies > 0)
2998 {
2999 if ((marker = ippFindAttribute(ipp, "marker-colors", IPP_TAG_NAME)) != NULL)
3000 report_attr(marker);
3001 if ((marker = ippFindAttribute(ipp, "marker-high-levels",
3002 IPP_TAG_INTEGER)) != NULL)
3003 report_attr(marker);
3004 if ((marker = ippFindAttribute(ipp, "marker-levels",
3005 IPP_TAG_INTEGER)) != NULL)
3006 report_attr(marker);
3007 if ((marker = ippFindAttribute(ipp, "marker-low-levels",
3008 IPP_TAG_INTEGER)) != NULL)
3009 report_attr(marker);
3010 if ((marker = ippFindAttribute(ipp, "marker-message",
3011 IPP_TAG_TEXT)) != NULL)
3012 report_attr(marker);
3013 if ((marker = ippFindAttribute(ipp, "marker-names", IPP_TAG_NAME)) != NULL)
3014 report_attr(marker);
3015 if ((marker = ippFindAttribute(ipp, "marker-types",
3016 IPP_TAG_KEYWORD)) != NULL)
3017 report_attr(marker);
3018 }
3019 }
3020
3021
3022 #if defined(HAVE_GSSAPI) && defined(HAVE_XPC)
3023 /*
3024 * 'run_as_user()' - Run the IPP backend as the printing user.
3025 *
3026 * This function uses an XPC-based user agent to run the backend as the printing
3027 * user. We need to do this in order to have access to the user's Kerberos
3028 * credentials.
3029 */
3030
3031 static int /* O - Exit status */
3032 run_as_user(char *argv[], /* I - Command-line arguments */
3033 uid_t uid, /* I - User ID */
3034 const char *device_uri, /* I - Device URI */
3035 int fd) /* I - File to print */
3036 {
3037 const char *auth_negotiate;/* AUTH_NEGOTIATE env var */
3038 xpc_connection_t conn; /* Connection to XPC service */
3039 xpc_object_t request; /* Request message dictionary */
3040 __block xpc_object_t response; /* Response message dictionary */
3041 dispatch_semaphore_t sem; /* Semaphore for waiting for response */
3042 int status = CUPS_BACKEND_FAILED;
3043 /* Status of request */
3044
3045
3046 fprintf(stderr, "DEBUG: Running IPP backend as UID %d.\n", (int)uid);
3047
3048 /*
3049 * Connect to the user agent for the specified UID...
3050 */
3051
3052 conn = xpc_connection_create_mach_service(kPMPrintUIToolAgent,
3053 dispatch_get_global_queue(0, 0), 0);
3054 if (!conn)
3055 {
3056 _cupsLangPrintFilter(stderr, "ERROR",
3057 _("Unable to start backend process."));
3058 fputs("DEBUG: Unable to create connection to agent.\n", stderr);
3059 goto cleanup;
3060 }
3061
3062 xpc_connection_set_event_handler(conn,
3063 ^(xpc_object_t event)
3064 {
3065 xpc_type_t messageType = xpc_get_type(event);
3066
3067 if (messageType == XPC_TYPE_ERROR)
3068 {
3069 if (event == XPC_ERROR_CONNECTION_INTERRUPTED)
3070 fprintf(stderr, "DEBUG: Interrupted connection to service %s.\n",
3071 xpc_connection_get_name(conn));
3072 else if (event == XPC_ERROR_CONNECTION_INVALID)
3073 fprintf(stderr, "DEBUG: Connection invalid for service %s.\n",
3074 xpc_connection_get_name(conn));
3075 else
3076 fprintf(stderr, "DEBUG: Unxpected error for service %s: %s\n",
3077 xpc_connection_get_name(conn),
3078 xpc_dictionary_get_string(event, XPC_ERROR_KEY_DESCRIPTION));
3079 }
3080 });
3081 xpc_connection_set_target_uid(conn, uid);
3082 xpc_connection_resume(conn);
3083
3084 /*
3085 * Try starting the backend...
3086 */
3087
3088 request = xpc_dictionary_create(NULL, NULL, 0);
3089 xpc_dictionary_set_int64(request, "command", kPMStartJob);
3090 xpc_dictionary_set_string(request, "device-uri", device_uri);
3091 xpc_dictionary_set_string(request, "job-id", argv[1]);
3092 xpc_dictionary_set_string(request, "user", argv[2]);
3093 xpc_dictionary_set_string(request, "title", argv[3]);
3094 xpc_dictionary_set_string(request, "copies", argv[4]);
3095 xpc_dictionary_set_string(request, "options", argv[5]);
3096 xpc_dictionary_set_string(request, "auth-info-required",
3097 getenv("AUTH_INFO_REQUIRED"));
3098 if ((auth_negotiate = getenv("AUTH_NEGOTIATE")) != NULL)
3099 xpc_dictionary_set_string(request, "auth-negotiate", auth_negotiate);
3100 xpc_dictionary_set_fd(request, "stdin", fd);
3101 xpc_dictionary_set_fd(request, "stderr", 2);
3102 xpc_dictionary_set_fd(request, "side-channel", CUPS_SC_FD);
3103
3104 sem = dispatch_semaphore_create(0);
3105 response = NULL;
3106
3107 xpc_connection_send_message_with_reply(conn, request,
3108 dispatch_get_global_queue(0,0),
3109 ^(xpc_object_t reply)
3110 {
3111 /* Save the response and wake up */
3112 if (xpc_get_type(reply)
3113 == XPC_TYPE_DICTIONARY)
3114 response = xpc_retain(reply);
3115
3116 dispatch_semaphore_signal(sem);
3117 });
3118
3119 dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
3120 xpc_release(request);
3121 dispatch_release(sem);
3122
3123 if (response)
3124 {
3125 child_pid = xpc_dictionary_get_int64(response, "child-pid");
3126
3127 xpc_release(response);
3128
3129 if (child_pid)
3130 fprintf(stderr, "DEBUG: Child PID=%d.\n", child_pid);
3131 else
3132 {
3133 _cupsLangPrintFilter(stderr, "ERROR",
3134 _("Unable to start backend process."));
3135 fputs("DEBUG: No child PID.\n", stderr);
3136 goto cleanup;
3137 }
3138 }
3139 else
3140 {
3141 _cupsLangPrintFilter(stderr, "ERROR",
3142 _("Unable to start backend process."));
3143 fputs("DEBUG: No reply from agent.\n", stderr);
3144 goto cleanup;
3145 }
3146
3147 /*
3148 * Then wait for the backend to finish...
3149 */
3150
3151 request = xpc_dictionary_create(NULL, NULL, 0);
3152 xpc_dictionary_set_int64(request, "command", kPMWaitForJob);
3153 xpc_dictionary_set_fd(request, "stderr", 2);
3154
3155 sem = dispatch_semaphore_create(0);
3156 response = NULL;
3157
3158 xpc_connection_send_message_with_reply(conn, request,
3159 dispatch_get_global_queue(0,0),
3160 ^(xpc_object_t reply)
3161 {
3162 /* Save the response and wake up */
3163 if (xpc_get_type(reply)
3164 == XPC_TYPE_DICTIONARY)
3165 response = xpc_retain(reply);
3166
3167 dispatch_semaphore_signal(sem);
3168 });
3169
3170 dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
3171 xpc_release(request);
3172 dispatch_release(sem);
3173
3174 if (response)
3175 {
3176 status = xpc_dictionary_get_int64(response, "status");
3177
3178 if (status == SIGTERM || status == SIGKILL || status == SIGPIPE)
3179 {
3180 fprintf(stderr, "DEBUG: Child terminated on signal %d.\n", status);
3181 status = CUPS_BACKEND_FAILED;
3182 }
3183 else if (WIFSIGNALED(status))
3184 {
3185 fprintf(stderr, "DEBUG: Child crashed on signal %d.\n", status);
3186 status = CUPS_BACKEND_STOP;
3187 }
3188 else if (WIFEXITED(status))
3189 {
3190 status = WEXITSTATUS(status);
3191 fprintf(stderr, "DEBUG: Child exited with status %d.\n", status);
3192 }
3193
3194 xpc_release(response);
3195 }
3196 else
3197 _cupsLangPrintFilter(stderr, "ERROR",
3198 _("Unable to get backend exit status."));
3199
3200 cleanup:
3201
3202 if (conn)
3203 {
3204 xpc_connection_suspend(conn);
3205 xpc_connection_cancel(conn);
3206 xpc_release(conn);
3207 }
3208
3209 return (status);
3210 }
3211 #endif /* HAVE_GSSAPI && HAVE_XPC */
3212
3213
3214 /*
3215 * 'sigterm_handler()' - Handle 'terminate' signals that stop the backend.
3216 */
3217
3218 static void
3219 sigterm_handler(int sig) /* I - Signal */
3220 {
3221 (void)sig; /* remove compiler warnings... */
3222
3223 write(2, "DEBUG: Got SIGTERM.\n", 20);
3224
3225 #if defined(HAVE_GSSAPI) && defined(HAVE_XPC)
3226 if (child_pid)
3227 {
3228 kill(child_pid, sig);
3229 child_pid = 0;
3230 }
3231 #endif /* HAVE_GSSAPI && HAVE_XPC */
3232
3233 if (!job_canceled)
3234 {
3235 /*
3236 * Flag that the job should be canceled...
3237 */
3238
3239 write(2, "DEBUG: job_canceled = 1.\n", 25);
3240
3241 job_canceled = 1;
3242 return;
3243 }
3244
3245 /*
3246 * The scheduler already tried to cancel us once, now just terminate
3247 * after removing our temp file!
3248 */
3249
3250 if (tmpfilename[0])
3251 unlink(tmpfilename);
3252
3253 exit(1);
3254 }
3255
3256
3257 /*
3258 * 'timeout_cb()' - Handle HTTP timeouts.
3259 */
3260
3261 static int /* O - 1 to continue, 0 to cancel */
3262 timeout_cb(http_t *http, /* I - Connection to server (unused) */
3263 void *user_data) /* I - User data (unused) */
3264 {
3265 (void)http;
3266 (void)user_data;
3267
3268 return (!job_canceled);
3269 }
3270
3271
3272 /*
3273 * 'update_reasons()' - Update the printer-state-reasons values.
3274 */
3275
3276 static void
3277 update_reasons(ipp_attribute_t *attr, /* I - printer-state-reasons or NULL */
3278 const char *s) /* I - STATE: string or NULL */
3279 {
3280 char op; /* Add (+), remove (-), replace (\0) */
3281 cups_array_t *new_reasons; /* New reasons array */
3282 char *reason, /* Current reason */
3283 add[2048], /* Reasons added string */
3284 *addptr, /* Pointer into add string */
3285 rem[2048], /* Reasons removed string */
3286 *remptr; /* Pointer into remove string */
3287 const char *addprefix, /* Current add string prefix */
3288 *remprefix; /* Current remove string prefix */
3289
3290
3291 fprintf(stderr, "DEBUG: update_reasons(attr=%d(%s%s), s=\"%s\")\n",
3292 attr ? attr->num_values : 0, attr ? attr->values[0].string.text : "",
3293 attr && attr->num_values > 1 ? ",..." : "", s ? s : "(null)");
3294
3295 /*
3296 * Create an array of new reason keyword strings...
3297 */
3298
3299 if (attr)
3300 {
3301 int i; /* Looping var */
3302
3303 new_reasons = cupsArrayNew((cups_array_func_t)strcmp, NULL);
3304 op = '\0';
3305
3306 for (i = 0; i < attr->num_values; i ++)
3307 {
3308 reason = attr->values[i].string.text;
3309
3310 if (strcmp(reason, "none") &&
3311 strcmp(reason, "none-report") &&
3312 strcmp(reason, "paused") &&
3313 strncmp(reason, "spool-area-full", 15) &&
3314 strcmp(reason, "com.apple.print.recoverable-warning") &&
3315 strncmp(reason, "cups-", 5))
3316 cupsArrayAdd(new_reasons, reason);
3317 }
3318 }
3319 else if (s)
3320 {
3321 if (*s == '+' || *s == '-')
3322 op = *s++;
3323 else
3324 op = '\0';
3325
3326 new_reasons = _cupsArrayNewStrings(s, ',');
3327 }
3328 else
3329 return;
3330
3331 /*
3332 * Compute the changes...
3333 */
3334
3335 add[0] = '\0';
3336 addprefix = "STATE: +";
3337 addptr = add;
3338 rem[0] = '\0';
3339 remprefix = "STATE: -";
3340 remptr = rem;
3341
3342 fprintf(stderr, "DEBUG2: op='%c', new_reasons=%d, state_reasons=%d\n",
3343 op ? op : ' ', cupsArrayCount(new_reasons),
3344 cupsArrayCount(state_reasons));
3345
3346 _cupsMutexLock(&report_mutex);
3347
3348 if (op == '+')
3349 {
3350 /*
3351 * Add reasons...
3352 */
3353
3354 for (reason = (char *)cupsArrayFirst(new_reasons);
3355 reason;
3356 reason = (char *)cupsArrayNext(new_reasons))
3357 {
3358 if (!cupsArrayFind(state_reasons, reason))
3359 {
3360 if (!strncmp(reason, "cups-remote-", 12))
3361 {
3362 /*
3363 * If we are setting cups-remote-xxx, remove all other cups-remote-xxx
3364 * keywords...
3365 */
3366
3367 char *temp; /* Current reason in state_reasons */
3368
3369 cupsArraySave(state_reasons);
3370
3371 for (temp = (char *)cupsArrayFirst(state_reasons);
3372 temp;
3373 temp = (char *)cupsArrayNext(state_reasons))
3374 if (!strncmp(temp, "cups-remote-", 12))
3375 {
3376 snprintf(remptr, sizeof(rem) - (remptr - rem), "%s%s", remprefix,
3377 temp);
3378 remptr += strlen(remptr);
3379 remprefix = ",";
3380
3381 cupsArrayRemove(state_reasons, temp);
3382 break;
3383 }
3384
3385 cupsArrayRestore(state_reasons);
3386 }
3387
3388 cupsArrayAdd(state_reasons, reason);
3389
3390 snprintf(addptr, sizeof(add) - (addptr - add), "%s%s", addprefix,
3391 reason);
3392 addptr += strlen(addptr);
3393 addprefix = ",";
3394 }
3395 }
3396 }
3397 else if (op == '-')
3398 {
3399 /*
3400 * Remove reasons...
3401 */
3402
3403 for (reason = (char *)cupsArrayFirst(new_reasons);
3404 reason;
3405 reason = (char *)cupsArrayNext(new_reasons))
3406 {
3407 if (cupsArrayFind(state_reasons, reason))
3408 {
3409 snprintf(remptr, sizeof(rem) - (remptr - rem), "%s%s", remprefix,
3410 reason);
3411 remptr += strlen(remptr);
3412 remprefix = ",";
3413
3414 cupsArrayRemove(state_reasons, reason);
3415 }
3416 }
3417 }
3418 else
3419 {
3420 /*
3421 * Replace reasons...
3422 */
3423
3424 for (reason = (char *)cupsArrayFirst(state_reasons);
3425 reason;
3426 reason = (char *)cupsArrayNext(state_reasons))
3427 {
3428 if (strncmp(reason, "cups-", 5) && !cupsArrayFind(new_reasons, reason))
3429 {
3430 snprintf(remptr, sizeof(rem) - (remptr - rem), "%s%s", remprefix,
3431 reason);
3432 remptr += strlen(remptr);
3433 remprefix = ",";
3434
3435 cupsArrayRemove(state_reasons, reason);
3436 }
3437 }
3438
3439 for (reason = (char *)cupsArrayFirst(new_reasons);
3440 reason;
3441 reason = (char *)cupsArrayNext(new_reasons))
3442 {
3443 if (!cupsArrayFind(state_reasons, reason))
3444 {
3445 cupsArrayAdd(state_reasons, reason);
3446
3447 snprintf(addptr, sizeof(add) - (addptr - add), "%s%s", addprefix,
3448 reason);
3449 addptr += strlen(addptr);
3450 addprefix = ",";
3451 }
3452 }
3453 }
3454
3455 _cupsMutexUnlock(&report_mutex);
3456
3457 /*
3458 * Report changes and return...
3459 */
3460
3461 if (add[0] && rem[0])
3462 fprintf(stderr, "%s\n%s\n", add, rem);
3463 else if (add[0])
3464 fprintf(stderr, "%s\n", add);
3465 else if (rem[0])
3466 fprintf(stderr, "%s\n", rem);
3467 }
3468
3469 /*
3470 * End of "$Id$".
3471 */