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