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