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