]> git.ipfire.org Git - thirdparty/cups.git/blobdiff - backend/ipp.c
Merge changes from CUPS 1.5b1-r9798.
[thirdparty/cups.git] / backend / ipp.c
index 95263a85e9ba34fa5ee39980e6bddaddfc027923..d19ce3778dec806bd6083d5854789e14b3d63a5f 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * "$Id: ipp.c 7948 2008-09-17 00:04:12Z mike $"
+ * "$Id: ipp.c 9759 2011-05-11 03:24:33Z mike $"
  *
  *   IPP backend for CUPS.
  *
  *   main()                 - Send a file to the printer or server.
  *   cancel_job()           - Cancel a print job.
  *   check_printer_state()  - Check the printer state.
- *   compress_files()       - Compress print files...
- *   monitor_printer()      - Monitor the printer state...
+ *   compress_files()       - Compress print files.
+ *   monitor_printer()      - Monitor the printer state.
  *   new_request()          - Create a new print creation or validation request.
  *   password_cb()          - Disable the password prompt for
  *                            cupsDoFileRequest().
  *   report_attr()          - Report an IPP attribute value.
  *   report_printer_state() - Report the printer state.
+ *   run_as_user()          - Run the IPP backend as the printing user.
  *   sigterm_handler()      - Handle 'terminate' signals that stop the backend.
  */
 
  */
 
 #include "backend-private.h"
+#include <cups/array-private.h>
 #include <sys/types.h>
 #include <sys/stat.h>
 #include <sys/wait.h>
+#if defined(HAVE_GSSAPI) && defined(HAVE_XPC)
+#  include <xpc/xpc.h>
+#  define kPMPrintUIToolAgent  "com.apple.printuitool.agent"
+#  define kPMStartJob          100
+#  define kPMWaitForJob                101
+extern void    xpc_connection_set_target_uid(xpc_connection_t connection,
+                                             uid_t uid);
+#endif /* HAVE_GSSAPI && HAVE_XPC */
 
 
 /*
@@ -62,17 +72,24 @@ typedef struct _cups_monitor_s              /**** Monitoring data ****/
  * Globals...
  */
 
-static const char *auth_info_required = "none";
+static const char      *auth_info_required;
                                        /* New auth-info-required value */
+#if defined(HAVE_GSSAPI) && defined(HAVE_XPC)
+static int             child_pid = 0;  /* Child process ID */
+#endif /* HAVE_GSSAPI && HAVE_XPC */
 static const char * const jattrs[] =   /* Job attributes we want */
 {
+  "job-impressions-completed",
   "job-media-sheets-completed",
   "job-state",
   "job-state-reasons"
 };
-static int     job_canceled = 0;       /* Job cancelled? */
-static char    *password = NULL;       /* Password for device URI */
-static int     password_tries = 0;     /* Password tries */
+static int             job_canceled = 0;
+                                       /* Job cancelled? */
+static char            *password = NULL;
+                                       /* Password for device URI */
+static int             password_tries = 0;
+                                       /* Password tries */
 static const char * const pattrs[] =   /* Printer attributes we want */
 {
   "copies-supported",
@@ -95,7 +112,25 @@ static const char * const pattrs[] =        /* Printer attributes we want */
   "printer-state-message",
   "printer-state-reasons",
 };
-static char    tmpfilename[1024] = ""; /* Temporary spool file name */
+static const char * const remote_job_states[] =
+{                                      /* Remote job state keywords */
+  "+cups-remote-pending",
+  "+cups-remote-pending-held",
+  "+cups-remote-processing",
+  "+cups-remote-stopped",
+  "+cups-remote-canceled",
+  "+cups-remote-aborted",
+  "+cups-remote-completed"
+};
+static _cups_mutex_t   report_mutex = _CUPS_MUTEX_INITIALIZER;
+                                       /* Mutex to control access */
+static int             num_attr_cache = 0;
+                                       /* Number of cached attributes */
+static cups_option_t   *attr_cache = NULL;
+                                       /* Cached attributes */
+static cups_array_t    *state_reasons; /* Array of printe-state-reasons keywords */
+static char            tmpfilename[1024] = "";
+                                       /* Temporary spool file name */
 
 
 /*
@@ -107,8 +142,7 @@ static void         cancel_job(http_t *http, const char *uri, int id,
                                   int version);
 static ipp_pstate_t    check_printer_state(http_t *http, const char *uri,
                                            const char *resource,
-                                           const char *user, int version,
-                                           int job_id);
+                                           const char *user, int version);
 #ifdef HAVE_LIBZ
 static void            compress_files(int num_files, char **files);
 #endif /* HAVE_LIBZ */
@@ -122,8 +156,13 @@ static ipp_t               *new_request(ipp_op_t op, int version, const char *uri,
                                     ipp_attribute_t *doc_handling_sup);
 static const char      *password_cb(const char *);
 static void            report_attr(ipp_attribute_t *attr);
-static int             report_printer_state(ipp_t *ipp, int job_id);
+static void            report_printer_state(ipp_t *ipp);
+#if defined(HAVE_GSSAPI) && defined(HAVE_XPC)
+static int             run_as_user(int argc, char *argv[], uid_t uid,
+                                   const char *device_uri, int fd);
+#endif /* HAVE_GSSAPI && HAVE_XPC */
 static void            sigterm_handler(int sig);
+static void            update_reasons(ipp_attribute_t *attr, const char *s);
 
 
 /*
@@ -197,7 +236,7 @@ main(int  argc,                             /* I - Number of command-line args */
                *final_content_type,    /* FINAL_CONTENT_TYPE environment var */
                *document_format;       /* document-format value */
   int          fd;                     /* File descriptor */
-  off_t                bytes;                  /* Bytes copied */
+  off_t                bytes = 0;              /* Bytes copied */
   char         buffer[16384];          /* Copy buffer */
 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
   struct sigaction action;             /* Actions for POSIX signals */
@@ -205,6 +244,7 @@ main(int  argc,                             /* I - Number of command-line args */
   int          version;                /* IPP version */
   ppd_file_t   *ppd;                   /* PPD file */
   _ppd_cache_t *pc;                    /* PPD cache and mapping data */
+  fd_set       input;                  /* Input set for select() */
 
 
  /*
@@ -260,6 +300,69 @@ main(int  argc,                            /* I - Number of command-line args */
     return (CUPS_BACKEND_STOP);
   }
 
+ /*
+  * Get the device URI...
+  */
+
+  while ((device_uri = cupsBackendDeviceURI(argv)) == NULL)
+  {
+    _cupsLangPrintFilter(stderr, "INFO", _("Unable to locate printer."));
+    sleep(10);
+
+    if (getenv("CLASS") != NULL)
+      return (CUPS_BACKEND_FAILED);
+  }
+
+  if ((auth_info_required = getenv("AUTH_INFO_REQUIRED")) == NULL)
+    auth_info_required = "none";
+
+  state_reasons = _cupsArrayNewStrings(getenv("PRINTER_STATE_REASONS"));
+
+#ifdef HAVE_GSSAPI
+ /*
+  * For Kerberos, become the printing user (if we can) to get the credentials
+  * that way.
+  */
+
+  if (!getuid() && (value = getenv("AUTH_UID")) != NULL)
+  {
+    uid_t      uid = (uid_t)atoi(value);
+                                       /* User ID */
+
+#  ifdef HAVE_XPC
+    if (uid > 0)
+    {
+      if (argc == 6)
+        return (run_as_user(argc, argv, uid, device_uri, 0));
+      else
+      {
+        int status = 0;                        /* Exit status */
+
+        for (i = 6; i < argc && !status && !job_canceled; i ++)
+       {
+         if ((fd = open(argv[i], O_RDONLY)) >= 0)
+         {
+           status = run_as_user(argc, argv, uid, device_uri, fd);
+           close(fd);
+         }
+         else
+         {
+           _cupsLangPrintError("ERROR", _("Unable to open print file"));
+           status = CUPS_BACKEND_FAILED;
+         }
+       }
+
+       return (status);
+      }
+    }
+
+#  else /* No XPC, just try to run as the user ID */
+    if (uid > 0)
+      seteuid(uid);
+#  endif /* HAVE_XPC */
+  }
+#endif /* HAVE_GSSAPI */
+
  /*
   * Get the (final) content type...
   */
@@ -279,15 +382,6 @@ main(int  argc,                            /* I - Number of command-line args */
   * Extract the hostname and printer name from the URI...
   */
 
-  while ((device_uri = cupsBackendDeviceURI(argv)) == NULL)
-  {
-    _cupsLangPrintFilter(stderr, "INFO", _("Unable to locate printer."));
-    sleep(10);
-
-    if (getenv("CLASS") != NULL)
-      return (CUPS_BACKEND_FAILED);
-  }
-
   httpSeparateURI(HTTP_URI_CODING_ALL, device_uri, scheme, sizeof(scheme),
                   username, sizeof(username), hostname, sizeof(hostname), &port,
                  resource, sizeof(resource));
@@ -358,39 +452,39 @@ main(int  argc,                           /* I - Number of command-line args */
       * Process the option...
       */
 
-      if (!strcasecmp(name, "waitjob"))
+      if (!_cups_strcasecmp(name, "waitjob"))
       {
        /*
         * Wait for job completion?
        */
 
-        waitjob = !strcasecmp(value, "on") ||
-                 !strcasecmp(value, "yes") ||
-                 !strcasecmp(value, "true");
+        waitjob = !_cups_strcasecmp(value, "on") ||
+                 !_cups_strcasecmp(value, "yes") ||
+                 !_cups_strcasecmp(value, "true");
       }
-      else if (!strcasecmp(name, "waitprinter"))
+      else if (!_cups_strcasecmp(name, "waitprinter"))
       {
        /*
         * Wait for printer idle?
        */
 
-        waitprinter = !strcasecmp(value, "on") ||
-                     !strcasecmp(value, "yes") ||
-                     !strcasecmp(value, "true");
+        waitprinter = !_cups_strcasecmp(value, "on") ||
+                     !_cups_strcasecmp(value, "yes") ||
+                     !_cups_strcasecmp(value, "true");
       }
-      else if (!strcasecmp(name, "encryption"))
+      else if (!_cups_strcasecmp(name, "encryption"))
       {
        /*
         * Enable/disable encryption?
        */
 
-        if (!strcasecmp(value, "always"))
+        if (!_cups_strcasecmp(value, "always"))
          cupsSetEncryption(HTTP_ENCRYPT_ALWAYS);
-        else if (!strcasecmp(value, "required"))
+        else if (!_cups_strcasecmp(value, "required"))
          cupsSetEncryption(HTTP_ENCRYPT_REQUIRED);
-        else if (!strcasecmp(value, "never"))
+        else if (!_cups_strcasecmp(value, "never"))
          cupsSetEncryption(HTTP_ENCRYPT_NEVER);
-        else if (!strcasecmp(value, "ifrequested"))
+        else if (!_cups_strcasecmp(value, "ifrequested"))
          cupsSetEncryption(HTTP_ENCRYPT_IF_REQUESTED);
        else
        {
@@ -399,7 +493,7 @@ main(int  argc,                             /* I - Number of command-line args */
                               value);
         }
       }
-      else if (!strcasecmp(name, "version"))
+      else if (!_cups_strcasecmp(name, "version"))
       {
         if (!strcmp(value, "1.0"))
          version = 10;
@@ -419,14 +513,14 @@ main(int  argc,                           /* I - Number of command-line args */
        }
       }
 #ifdef HAVE_LIBZ
-      else if (!strcasecmp(name, "compression"))
+      else if (!_cups_strcasecmp(name, "compression"))
       {
-        if (!strcasecmp(value, "true") || !strcasecmp(value, "yes") ||
-           !strcasecmp(value, "on") || !strcasecmp(value, "gzip"))
+        if (!_cups_strcasecmp(value, "true") || !_cups_strcasecmp(value, "yes") ||
+           !_cups_strcasecmp(value, "on") || !_cups_strcasecmp(value, "gzip"))
          compression = "gzip";
       }
 #endif /* HAVE_LIBZ */
-      else if (!strcasecmp(name, "contimeout"))
+      else if (!_cups_strcasecmp(name, "contimeout"))
       {
        /*
         * Set the connection timeout...
@@ -457,9 +551,9 @@ main(int  argc,                             /* I - Number of command-line args */
   if (argc == 6)
   {
     num_files    = 0;
-    send_options = !strcasecmp(final_content_type, "application/pdf") ||
-                   !strcasecmp(final_content_type, "application/vnd.cups-pdf") ||
-                   !strncasecmp(final_content_type, "image/", 6);
+    send_options = !_cups_strcasecmp(final_content_type, "application/pdf") ||
+                   !_cups_strcasecmp(final_content_type, "application/vnd.cups-pdf") ||
+                   !_cups_strncasecmp(final_content_type, "image/", 6);
 
     fputs("DEBUG: Sending stdin for job...\n", stderr);
   }
@@ -520,7 +614,7 @@ main(int  argc,                             /* I - Number of command-line args */
 
   sprintf(portname, "%d", port);
 
-  fputs("STATE: +connecting-to-device\n", stderr);
+  update_reasons(NULL, "+connecting-to-device");
   fprintf(stderr, "DEBUG: Looking up \"%s\"...\n", hostname);
 
   while ((addrlist = httpAddrGetList(hostname, AF_UNSPEC, portname)) == NULL)
@@ -531,7 +625,7 @@ main(int  argc,                             /* I - Number of command-line args */
 
     if (getenv("CLASS") != NULL)
     {
-      fputs("STATE: -connecting-to-device\n", stderr);
+      update_reasons(NULL, "-connecting-to-device");
       return (CUPS_BACKEND_STOP);
     }
   }
@@ -555,8 +649,12 @@ main(int  argc,                            /* I - Number of command-line args */
   */
 
   if (num_files == 0)
+  {
     if (!backendWaitLoop(snmp_fd, &(addrlist->addr), 0, backendNetworkSideCB))
       return (CUPS_BACKEND_OK);
+    else if ((bytes = read(0, buffer, sizeof(buffer))) <= 0)
+      return (CUPS_BACKEND_OK);
+  }
 
  /*
   * Try connecting to the remote server...
@@ -574,7 +672,7 @@ main(int  argc,                             /* I - Number of command-line args */
       int error = errno;               /* Connection error */
 
       if (http->status == HTTP_PKI_ERROR)
-       fputs("STATE: +cups-certificate-error\n", stderr);
+       update_reasons(NULL, "+cups-certificate-error");
 
       if (job_canceled)
        break;
@@ -598,7 +696,7 @@ main(int  argc,                             /* I - Number of command-line args */
 
        sleep(5);
 
-       fputs("STATE: -connecting-to-device\n", stderr);
+       update_reasons(NULL, "-connecting-to-device");
 
         return (CUPS_BACKEND_FAILED);
       }
@@ -612,7 +710,7 @@ main(int  argc,                             /* I - Number of command-line args */
        {
          _cupsLangPrintFilter(stderr, "ERROR",
                               _("The printer is not responding."));
-         fputs("STATE: -connecting-to-device\n", stderr);
+         update_reasons(NULL, "-connecting-to-device");
          return (CUPS_BACKEND_FAILED);
        }
 
@@ -620,22 +718,20 @@ main(int  argc,                           /* I - Number of command-line args */
        {
          case EHOSTDOWN :
              _cupsLangPrintFilter(stderr, "WARNING",
-                                  _("Network printer \"%s\" may not exist or "
-                                    "is unavailable at this time."),
-                                  hostname);
+                                  _("The printer may not exist or "
+                                    "is unavailable at this time."));
              break;
 
          case EHOSTUNREACH :
              _cupsLangPrintFilter(stderr, "WARNING",
-                                  _("Network printer \"%s\" is unreachable at "
-                                    "this time."), hostname);
+                                  _("The printer is unreachable at this "
+                                    "time."));
              break;
 
          case ECONNREFUSED :
          default :
              _cupsLangPrintFilter(stderr, "WARNING",
-                                  _("Network printer \"%s\" is busy."),
-                                  hostname);
+                                  _("The printer is busy."));
              break;
         }
 
@@ -646,8 +742,7 @@ main(int  argc,                             /* I - Number of command-line args */
       else
       {
        _cupsLangPrintFilter(stderr, "ERROR",
-                            _("Network printer \"%s\" is not responding."),
-                            hostname);
+                            _("The printer is not responding."));
        sleep(30);
       }
 
@@ -655,27 +750,19 @@ main(int  argc,                           /* I - Number of command-line args */
        break;
     }
     else
-      fputs("STATE: -cups-certificate-error\n", stderr);
+      update_reasons(NULL, "-cups-certificate-error");
   }
   while (http->fd < 0);
 
   if (job_canceled || !http)
     return (CUPS_BACKEND_FAILED);
 
-  fputs("STATE: -connecting-to-device\n", stderr);
+  update_reasons(NULL, "-connecting-to-device");
   _cupsLangPrintFilter(stderr, "INFO", _("Connected to printer."));
 
-#ifdef AF_INET6
-  if (http->hostaddr->addr.sa_family == AF_INET6)
-    fprintf(stderr, "DEBUG: Connected to [%s]:%d (IPv6)...\n",
-           httpAddrString(http->hostaddr, addrname, sizeof(addrname)),
-           ntohs(http->hostaddr->ipv6.sin6_port));
-  else
-#endif /* AF_INET6 */
-    if (http->hostaddr->addr.sa_family == AF_INET)
-      fprintf(stderr, "DEBUG: Connected to %s:%d (IPv4)...\n",
-             httpAddrString(http->hostaddr, addrname, sizeof(addrname)),
-             ntohs(http->hostaddr->ipv4.sin_port));
+  fprintf(stderr, "DEBUG: Connected to %s:%d...\n",
+         httpAddrString(http->hostaddr, addrname, sizeof(addrname)),
+         _httpAddrPort(http->hostaddr));
 
  /*
   * Build a URI for the printer and fill the standard IPP attributes for
@@ -733,16 +820,16 @@ main(int  argc,                           /* I - Number of command-line args */
     {
       fprintf(stderr, "DEBUG: Printer responded with HTTP version %d.%d.\n",
               http->version / 100, http->version % 100);
-
-      _cupsLangPrintFilter(stderr, "ERROR",
-                           _("This printer does not conform to the IPP "
-                            "standard. Please contact the manufacturer of "
-                            "your printer for assistance."));
+      update_reasons(NULL, "+cups-ipp-conformance-failure-report,"
+                          "cups-ipp-wrong-http-version");
     }
 
     supported  = cupsDoRequest(http, request, resource);
     ipp_status = cupsLastError();
 
+    fprintf(stderr, "DEBUG: Get-Printer-Attributes: %s (%s)\n",
+            ippErrorString(ipp_status), cupsLastErrorString());
+
     if (ipp_status > IPP_OK_CONFLICT)
     {
       fprintf(stderr, "DEBUG: Get-Printer-Attributes returned %s.\n",
@@ -758,11 +845,9 @@ main(int  argc,                            /* I - Number of command-line args */
          return (CUPS_BACKEND_FAILED);
        }
 
-       _cupsLangPrintFilter(stderr, "WARNING",
-                            _("Network host \"%s\" is busy; will retry in %d "
-                              "seconds."), hostname, delay);
+       _cupsLangPrintFilter(stderr, "INFO", _("The printer is busy."));
 
-        report_printer_state(supported, 0);
+        report_printer_state(supported);
 
        sleep(delay);
 
@@ -798,8 +883,7 @@ main(int  argc,                             /* I - Number of command-line args */
                             _("The printer URI is incorrect or no longer "
                               "exists."));
 
-       if (supported)
-          ippDelete(supported);
+       ippDelete(supported);
 
        return (CUPS_BACKEND_STOP);
       }
@@ -815,17 +899,67 @@ main(int  argc,                           /* I - Number of command-line args */
       else
       {
        _cupsLangPrintFilter(stderr, "ERROR",
-                            _("Unable to get printer status: %s"),
-                            cupsLastErrorString());
+                            _("Unable to get printer status."));
         sleep(10);
       }
 
-      if (supported)
-        ippDelete(supported);
-
+      ippDelete(supported);
+      supported = NULL;
       continue;
     }
 
+    if (!getenv("CLASS"))
+    {
+     /*
+      * Check printer-is-accepting-jobs = false and printer-state-reasons for the
+      * "spool-area-full" keyword...
+      */
+
+      int busy = 0;
+
+      if ((printer_accepting = ippFindAttribute(supported,
+                                               "printer-is-accepting-jobs",
+                                               IPP_TAG_BOOLEAN)) != NULL &&
+         !printer_accepting->values[0].boolean)
+        busy = 1;
+      else if (!printer_accepting)
+        update_reasons(NULL, "+cups-ipp-conformance-failure-report,"
+                            "cups-ipp-missing-printer-is-accepting-jobs");
+
+      if ((printer_state = ippFindAttribute(supported,
+                                           "printer-state-reasons",
+                                           IPP_TAG_KEYWORD)) != NULL && !busy)
+      {
+       for (i = 0; i < printer_state->num_values; i ++)
+         if (!strcmp(printer_state->values[0].string.text,
+                     "spool-area-full") ||
+             !strncmp(printer_state->values[0].string.text, "spool-area-full-",
+                      16))
+         {
+           busy = 1;
+           break;
+         }
+      }
+      else
+        update_reasons(NULL, "+cups-ipp-conformance-failure-report,"
+                            "cups-ipp-missing-printer-state-reasons");
+
+      if (busy)
+      {
+       _cupsLangPrintFilter(stderr, "INFO", _("The printer is busy."));
+
+       report_printer_state(supported);
+
+       sleep(delay);
+
+       delay = _cupsNextDelay(delay, &prev_delay);
+
+       ippDelete(supported);
+       supported = NULL;
+       continue;
+      }
+    }
+
    /*
     * Check for supported attributes...
     */
@@ -871,6 +1005,38 @@ main(int  argc,                           /* I - Number of command-line args */
     if ((operations_sup = ippFindAttribute(supported, "operations-supported",
                                           IPP_TAG_ENUM)) != NULL)
     {
+      for (i = 0; i < operations_sup->num_values; i ++)
+        if (operations_sup->values[i].integer == IPP_PRINT_JOB)
+         break;
+
+      if (i >= operations_sup->num_values)
+       update_reasons(NULL, "+cups-ipp-conformance-failure-report,"
+                            "cups-ipp-missing-print-job");
+
+      for (i = 0; i < operations_sup->num_values; i ++)
+        if (operations_sup->values[i].integer == IPP_CANCEL_JOB)
+         break;
+
+      if (i >= operations_sup->num_values)
+       update_reasons(NULL, "+cups-ipp-conformance-failure-report,"
+                            "cups-ipp-missing-cancel-job");
+
+      for (i = 0; i < operations_sup->num_values; i ++)
+        if (operations_sup->values[i].integer == IPP_GET_JOB_ATTRIBUTES)
+         break;
+
+      if (i >= operations_sup->num_values)
+       update_reasons(NULL, "+cups-ipp-conformance-failure-report,"
+                             "cups-ipp-missing-get-job-attributes");
+
+      for (i = 0; i < operations_sup->num_values; i ++)
+        if (operations_sup->values[i].integer == IPP_GET_PRINTER_ATTRIBUTES)
+         break;
+
+      if (i >= operations_sup->num_values)
+       update_reasons(NULL, "+cups-ipp-conformance-failure-report,"
+                            "cups-ipp-missing-get-printer-attributes");
+
       for (i = 0; i < operations_sup->num_values; i ++)
         if (operations_sup->values[i].integer == IPP_VALIDATE_JOB)
        {
@@ -879,28 +1045,18 @@ main(int  argc,                          /* I - Number of command-line args */
        }
 
       if (!validate_job)
-      {
-        _cupsLangPrintFilter(stderr, "WARNING",
-                            _("This printer does not conform to the IPP "
-                              "standard and may not work."));
-        fputs("DEBUG: operations-supported does not list Validate-Job.\n",
-             stderr);
-      }
+       update_reasons(NULL, "+cups-ipp-conformance-failure-report,"
+                             "cups-ipp-missing-validate-job");
     }
     else
-    {
-      _cupsLangPrintFilter(stderr, "WARNING",
-                          _("This printer does not conform to the IPP "
-                            "standard and may not work."));
-      fputs("DEBUG: operations-supported not returned in "
-            "Get-Printer-Attributes request.\n", stderr);
-    }
+      update_reasons(NULL, "+cups-ipp-conformance-failure-report,"
+                          "cups-ipp-missing-operations-supported");
 
     doc_handling_sup = ippFindAttribute(supported,
                                        "multiple-document-handling-supported",
                                        IPP_TAG_KEYWORD);
 
-    report_printer_state(supported, 0);
+    report_printer_state(supported);
   }
   while (ipp_status > IPP_OK_CONFLICT);
 
@@ -993,7 +1149,7 @@ main(int  argc,                            /* I - Number of command-line args */
   if (format_sup != NULL)
   {
     for (i = 0; i < format_sup->num_values; i ++)
-      if (!strcasecmp(final_content_type, format_sup->values[i].string.text))
+      if (!_cups_strcasecmp(final_content_type, format_sup->values[i].string.text))
       {
         document_format = final_content_type;
        break;
@@ -1002,7 +1158,7 @@ main(int  argc,                           /* I - Number of command-line args */
     if (!document_format)
     {
       for (i = 0; i < format_sup->num_values; i ++)
-       if (!strcasecmp("application/octet-stream",
+       if (!_cups_strcasecmp("application/octet-stream",
                        format_sup->values[i].string.text))
        {
          document_format = "application/octet-stream";
@@ -1066,7 +1222,7 @@ main(int  argc,                           /* I - Number of command-line args */
   * Validate access to the printer...
   */
 
-  while (!job_canceled)
+  while (!job_canceled && validate_job)
   {
     request = new_request(IPP_VALIDATE_JOB, version, uri, argv[2], argv[3],
                           num_options, options, compression,
@@ -1077,48 +1233,51 @@ main(int  argc,                         /* I - Number of command-line args */
 
     ipp_status = cupsLastError();
 
-    if (ipp_status > IPP_OK_CONFLICT &&
-        ipp_status != IPP_OPERATION_NOT_SUPPORTED)
-    {
-      if (job_canceled)
-        break;
+    fprintf(stderr, "DEBUG: Validate-Job: %s (%s)\n",
+            ippErrorString(ipp_status), cupsLastErrorString());
 
-      if (ipp_status == IPP_SERVICE_UNAVAILABLE ||
-         ipp_status == IPP_PRINTER_BUSY)
-      {
-        _cupsLangPrintFilter(stderr, "INFO",
-                            _("Printer busy; will retry in 10 seconds."));
-       sleep(10);
-      }
-      else
-      {
-       /*
-       * Update auth-info-required as needed...
-       */
+    if (job_canceled)
+      break;
 
-        _cupsLangPrintFilter(stderr, "ERROR", "%s", cupsLastErrorString());
+    if (ipp_status == IPP_SERVICE_UNAVAILABLE || ipp_status == IPP_PRINTER_BUSY)
+    {
+      _cupsLangPrintFilter(stderr, "INFO", _("The printer is busy."));
+      sleep(10);
+    }
+    else if (ipp_status == IPP_NOT_AUTHORIZED || ipp_status == IPP_FORBIDDEN ||
+            ipp_status == IPP_AUTHENTICATION_CANCELED)
+    {
+     /*
+      * Update auth-info-required as needed...
+      */
 
-       if (ipp_status == IPP_NOT_AUTHORIZED || ipp_status == IPP_FORBIDDEN)
-       {
-         fprintf(stderr, "DEBUG: WWW-Authenticate=\"%s\"\n",
-                 httpGetField(http, HTTP_FIELD_WWW_AUTHENTICATE));
+      fprintf(stderr, "DEBUG: WWW-Authenticate=\"%s\"\n",
+             httpGetField(http, HTTP_FIELD_WWW_AUTHENTICATE));
 
-         /*
-         * Normal authentication goes through the password callback, which sets
-         * auth_info_required to "username,password".  Kerberos goes directly
-         * through GSSAPI, so look for Negotiate in the WWW-Authenticate header
-         * here and set auth_info_required as needed...
-         */
+     /*
+      * Normal authentication goes through the password callback, which sets
+      * auth_info_required to "username,password".  Kerberos goes directly
+      * through GSSAPI, so look for Negotiate in the WWW-Authenticate header
+      * here and set auth_info_required as needed...
+      */
 
-         if (!strncmp(httpGetField(http, HTTP_FIELD_WWW_AUTHENTICATE),
-                      "Negotiate", 9))
-           auth_info_required = "negotiate";
-       }
+      if (!strncmp(httpGetField(http, HTTP_FIELD_WWW_AUTHENTICATE),
+                  "Negotiate", 9))
+       auth_info_required = "negotiate";
 
-       goto cleanup;
-      }
+      goto cleanup;
     }
-    else
+    else if (ipp_status == IPP_OPERATION_NOT_SUPPORTED)
+    {
+     /*
+      * This is all too common...
+      */
+
+      update_reasons(NULL, "+cups-ipp-conformance-failure-report,"
+                          "cups-ipp-missing-validate-job");
+      break;
+    }
+    else if (ipp_status < IPP_REDIRECTION_OTHER_SITE)
       break;
   }
 
@@ -1172,21 +1331,38 @@ main(int  argc,                         /* I - Number of command-line args */
         if (num_files == 1)
          fd = open(files[0], O_RDONLY);
        else
-         fd = 0;
+       {
+         fd          = 0;
+         http_status = cupsWriteRequestData(http, buffer, bytes);
+        }
 
-        while ((bytes = read(fd, buffer, sizeof(buffer))) > 0)
+        while (http_status == HTTP_CONTINUE)
        {
-         fprintf(stderr, "DEBUG: Read %d bytes...\n", (int)bytes);
+        /*
+         * Check for side-channel requests and more print data...
+         */
 
-         if (cupsWriteRequestData(http, buffer, bytes) != HTTP_CONTINUE)
-            break;
-          else
-         {
-          /*
-           * Check for side-channel requests...
-           */
+          FD_ZERO(&input);
+         FD_SET(fd, &input);
+         FD_SET(snmp_fd, &input);
+
+          while (select(fd > snmp_fd ? fd + 1 : snmp_fd + 1, &input, NULL, NULL,
+                       NULL) <= 0 && !job_canceled);
 
+         if (FD_ISSET(snmp_fd, &input))
            backendCheckSideChannel(snmp_fd, http->hostaddr);
+
+          if (FD_ISSET(fd, &input))
+          {
+            if ((bytes = read(fd, buffer, sizeof(buffer))) > 0)
+            {
+             fprintf(stderr, "DEBUG: Read %d bytes...\n", (int)bytes);
+
+             if (cupsWriteRequestData(http, buffer, bytes) != HTTP_CONTINUE)
+               break;
+           }
+           else if (bytes == 0 || (errno != EINTR && errno != EAGAIN))
+             break;
          }
        }
 
@@ -1200,6 +1376,10 @@ main(int  argc,                          /* I - Number of command-line args */
 
     ipp_status = cupsLastError();
 
+    fprintf(stderr, "DEBUG: %s: %s (%s)\n",
+            num_files > 1 ? "Create-Job" : "Print-Job",
+            ippErrorString(ipp_status), cupsLastErrorString());
+
     if (ipp_status > IPP_OK_CONFLICT)
     {
       job_id = 0;
@@ -1210,9 +1390,18 @@ main(int  argc,                          /* I - Number of command-line args */
       if (ipp_status == IPP_SERVICE_UNAVAILABLE ||
          ipp_status == IPP_PRINTER_BUSY)
       {
-        _cupsLangPrintFilter(stderr, "INFO",
-                            _("Printer busy; will retry in 10 seconds."));
+       _cupsLangPrintFilter(stderr, "INFO", _("The printer is busy."));
        sleep(10);
+
+       if (num_files == 0)
+       {
+        /*
+         * We can't re-submit when we have no files to print, so exit
+         * immediately with the right status code...
+         */
+
+         goto cleanup;
+       }
       }
       else
       {
@@ -1221,8 +1410,7 @@ main(int  argc,                           /* I - Number of command-line args */
        */
 
         _cupsLangPrintFilter(stderr, "ERROR",
-                            _("Print file was not accepted: %s"),
-                            cupsLastErrorString());
+                            _("Print file was not accepted."));
 
        if (ipp_status == IPP_NOT_AUTHORIZED || ipp_status == IPP_FORBIDDEN)
        {
@@ -1240,6 +1428,18 @@ main(int  argc,                          /* I - Number of command-line args */
                       "Negotiate", 9))
            auth_info_required = "negotiate";
        }
+       else
+         sleep(10);
+
+       if (num_files == 0)
+       {
+        /*
+         * We can't re-submit when we have no files to print, so exit
+         * immediately with the right status code...
+         */
+
+         goto cleanup;
+       }
       }
     }
     else if ((job_id_attr = ippFindAttribute(response, "job-id",
@@ -1247,6 +1447,8 @@ main(int  argc,                           /* I - Number of command-line args */
     {
       _cupsLangPrintFilter(stderr, "INFO",
                           _("Print file accepted - job ID unknown."));
+      update_reasons(NULL, "+cups-ipp-conformance-failure-report,"
+                          "cups-ipp-missing-job-id");
       job_id = 0;
     }
     else
@@ -1320,13 +1522,15 @@ main(int  argc,                         /* I - Number of command-line args */
        ippDelete(cupsGetResponse(http, resource));
        ippDelete(request);
 
+       fprintf(stderr, "DEBUG: Send-Document: %s (%s)\n",
+               ippErrorString(cupsLastError()), cupsLastErrorString());
+
        if (cupsLastError() > IPP_OK_CONFLICT)
        {
          ipp_status = cupsLastError();
 
          _cupsLangPrintFilter(stderr, "ERROR",
-                              _("Unable to add file to job: %s"),
-                              cupsLastErrorString());
+                              _("Unable to add document to print job."));
          break;
        }
       }
@@ -1396,12 +1600,17 @@ main(int  argc,                         /* I - Number of command-line args */
         * Job has gone away and/or the server has no job history...
        */
 
+       update_reasons(NULL, "+cups-ipp-conformance-failure-report,"
+                            "cups-ipp-missing-job-history");
         ippDelete(response);
 
        ipp_status = IPP_OK;
         break;
       }
 
+      fprintf(stderr, "DEBUG: Get-Job-Attributes: %s (%s)\n",
+             ippErrorString(ipp_status), cupsLastErrorString());
+
       if (ipp_status > IPP_OK_CONFLICT)
       {
        if (ipp_status != IPP_SERVICE_UNAVAILABLE &&
@@ -1410,8 +1619,7 @@ main(int  argc,                           /* I - Number of command-line args */
          ippDelete(response);
 
           _cupsLangPrintFilter(stderr, "ERROR",
-                              _("Unable to get job attributes: %s"),
-                              cupsLastErrorString());
+                              _("Unable to get print job status."));
           break;
        }
       }
@@ -1421,18 +1629,34 @@ main(int  argc,                         /* I - Number of command-line args */
        if ((job_state = ippFindAttribute(response, "job-state",
                                          IPP_TAG_ENUM)) != NULL)
        {
+         /*
+         * Reflect the remote job state in the local queue...
+         */
+
+         if (cups_version &&
+             job_state->values[0].integer >= IPP_JOB_PENDING &&
+             job_state->values[0].integer <= IPP_JOB_COMPLETED)
+           update_reasons(NULL,
+                          remote_job_states[job_state->values[0].integer -
+                                            IPP_JOB_PENDING]);
+
+         if ((job_sheets = ippFindAttribute(response,
+                                            "job-media-sheets-completed",
+                                            IPP_TAG_INTEGER)) == NULL)
+           job_sheets = ippFindAttribute(response,
+                                         "job-impressions-completed",
+                                         IPP_TAG_INTEGER);
+
+         if (job_sheets)
+           fprintf(stderr, "PAGE: total %d\n",
+                   job_sheets->values[0].integer);
+
         /*
           * Stop polling if the job is finished or pending-held...
          */
 
           if (job_state->values[0].integer > IPP_JOB_STOPPED)
          {
-           if ((job_sheets = ippFindAttribute(response,
-                                              "job-media-sheets-completed",
-                                              IPP_TAG_INTEGER)) != NULL)
-             fprintf(stderr, "PAGE: total %d\n",
-                     job_sheets->values[0].integer);
-
            ippDelete(response);
            break;
          }
@@ -1445,8 +1669,8 @@ main(int  argc,                           /* I - Number of command-line args */
          * the job...
          */
 
-          fputs("DEBUG: No job-state available from printer - stopping queue.\n",
-               stderr);
+         update_reasons(NULL, "+cups-ipp-conformance-failure-report,"
+                              "cups-ipp-missing-job-state");
          ipp_status = IPP_INTERNAL_ERROR;
          break;
        }
@@ -1475,7 +1699,7 @@ main(int  argc,                           /* I - Number of command-line args */
   * Check the printer state and report it if necessary...
   */
 
-  check_printer_state(http, uri, resource, argv[2], version, job_id);
+  check_printer_state(http, uri, resource, argv[2], version);
 
  /*
   * Collect the final page count as needed...
@@ -1537,8 +1761,11 @@ main(int  argc,                          /* I - Number of command-line args */
     return (CUPS_BACKEND_AUTH_REQUIRED);
   else if (ipp_status == IPP_INTERNAL_ERROR)
     return (CUPS_BACKEND_STOP);
-  else if (ipp_status > IPP_OK_CONFLICT)
+  else if (ipp_status == IPP_DOCUMENT_FORMAT ||
+           ipp_status == IPP_CONFLICT)
     return (CUPS_BACKEND_FAILED);
+  else if (ipp_status > IPP_OK_CONFLICT)
+    return (CUPS_BACKEND_RETRY_CURRENT);
   else
   {
     _cupsLangPrintFilter(stderr, "INFO", _("Ready to print."));
@@ -1583,8 +1810,7 @@ cancel_job(http_t     *http,              /* I - HTTP connection */
   ippDelete(cupsDoRequest(http, request, resource));
 
   if (cupsLastError() > IPP_OK_CONFLICT)
-    _cupsLangPrintFilter(stderr, "ERROR", _("Unable to cancel job: %s"),
-                        cupsLastErrorString());
+    _cupsLangPrintFilter(stderr, "ERROR", _("Unable to cancel print job."));
 }
 
 
@@ -1598,9 +1824,8 @@ check_printer_state(
     const char  *uri,                  /* I - Printer URI */
     const char  *resource,             /* I - Resource path */
     const char  *user,                 /* I - Username, if any */
-    int         version,               /* I - IPP version */
-    int         job_id)
-{
+    int         version)               /* I - IPP version */
+ {
   ipp_t                *request,               /* IPP request */
                *response;              /* IPP response */
   ipp_attribute_t *attr;               /* Attribute in response */
@@ -1629,7 +1854,7 @@ check_printer_state(
 
   if ((response = cupsDoRequest(http, request, resource)) != NULL)
   {
-    report_printer_state(response, job_id);
+    report_printer_state(response);
 
     if ((attr = ippFindAttribute(response, "printer-state",
                                 IPP_TAG_ENUM)) != NULL)
@@ -1638,6 +1863,9 @@ check_printer_state(
     ippDelete(response);
   }
 
+  fprintf(stderr, "DEBUG: Get-Printer-Attributes: %s (%s)\n",
+         ippErrorString(cupsLastError()), cupsLastErrorString());
+
  /*
   * Return the printer-state value...
   */
@@ -1648,7 +1876,7 @@ check_printer_state(
 
 #ifdef HAVE_LIBZ
 /*
- * 'compress_files()' - Compress print files...
+ * 'compress_files()' - Compress print files.
  */
 
 static void
@@ -1718,7 +1946,7 @@ compress_files(int  num_files,            /* I - Number of files */
 
 
 /*
- * 'monitor_printer()' - Monitor the printer state...
+ * 'monitor_printer()' - Monitor the printer state.
  */
 
 static void *                          /* O - Thread exit code */
@@ -1762,8 +1990,7 @@ monitor_printer(
       monitor->printer_state = check_printer_state(http, monitor->uri,
                                                    monitor->resource,
                                                   monitor->user,
-                                                  monitor->version,
-                                                  monitor->job_id);
+                                                  monitor->version);
 
       if (monitor->job_id > 0)
       {
@@ -1794,6 +2021,9 @@ monitor_printer(
 
        response = cupsDoRequest(http, request, monitor->resource);
 
+       fprintf(stderr, "DEBUG: Get-Job-Attributes: %s (%s)\n",
+               ippErrorString(cupsLastError()), cupsLastErrorString());
+
        if ((attr = ippFindAttribute(response, "job-state",
                                     IPP_TAG_ENUM)) != NULL)
          monitor->job_state = (ipp_jstate_t)attr->values[0].integer;
@@ -1995,7 +2225,7 @@ new_request(
       else if ((keyword = cupsGetOption("ColorModel", num_options,
                                        options)) != NULL)
       {
-       if (!strcasecmp(keyword, "Gray"))
+       if (!_cups_strcasecmp(keyword, "Gray"))
          ippAddString(request, IPP_TAG_JOB, IPP_TAG_KEYWORD, "output-mode",
                               NULL, "monochrome");
        else
@@ -2010,13 +2240,13 @@ new_request(
       else if ((keyword = cupsGetOption("cupsPrintQuality", num_options,
                                        options)) != NULL)
       {
-       if (!strcasecmp(keyword, "draft"))
+       if (!_cups_strcasecmp(keyword, "draft"))
          ippAddInteger(request, IPP_TAG_JOB, IPP_TAG_ENUM, "print-quality",
                        IPP_QUALITY_DRAFT);
-       else if (!strcasecmp(keyword, "normal"))
+       else if (!_cups_strcasecmp(keyword, "normal"))
          ippAddInteger(request, IPP_TAG_JOB, IPP_TAG_ENUM, "print-quality",
                        IPP_QUALITY_NORMAL);
-       else if (!strcasecmp(keyword, "high"))
+       else if (!_cups_strcasecmp(keyword, "high"))
          ippAddInteger(request, IPP_TAG_JOB, IPP_TAG_ENUM, "print-quality",
                        IPP_QUALITY_HIGH);
       }
@@ -2028,13 +2258,13 @@ new_request(
                (keyword = cupsGetOption(pc->sides_option, num_options,
                                        options)) != NULL)
       {
-       if (!strcasecmp(keyword, pc->sides_1sided))
+       if (!_cups_strcasecmp(keyword, pc->sides_1sided))
          ippAddString(request, IPP_TAG_JOB, IPP_TAG_KEYWORD, "sides",
                       NULL, "one-sided");
-       else if (!strcasecmp(keyword, pc->sides_2sided_long))
+       else if (!_cups_strcasecmp(keyword, pc->sides_2sided_long))
          ippAddString(request, IPP_TAG_JOB, IPP_TAG_KEYWORD, "sides",
                       NULL, "two-sided-long-edge");
-       if (!strcasecmp(keyword, pc->sides_2sided_short))
+       if (!_cups_strcasecmp(keyword, pc->sides_2sided_short))
          ippAddString(request, IPP_TAG_JOB, IPP_TAG_KEYWORD, "sides",
                       NULL, "two-sided-short-edge");
       }
@@ -2042,11 +2272,11 @@ new_request(
       if (doc_handling_sup &&
          (keyword = cupsGetOption("collate", num_options, options)) != NULL)
       {
-        if (!strcasecmp(keyword, "true"))
+        if (!_cups_strcasecmp(keyword, "true"))
          collate_str = "separate-documents-collated-copies";
        else
          collate_str = "separate-documents-uncollated-copies";
-       
+
         for (i = 0; i < doc_handling_sup->num_values; i ++)
          if (!strcmp(doc_handling_sup->values[i].string.text, collate_str))
          {
@@ -2112,10 +2342,11 @@ password_cb(const char *prompt)         /* I - Prompt (not used) */
 static void
 report_attr(ipp_attribute_t *attr)     /* I - Attribute */
 {
-  int  i;                              /* Looping var */
-  char value[1024],                    /* Value string */
-       *valptr,                        /* Pointer into value string */
-       *attrptr;                       /* Pointer into attribute value */
+  int          i;                      /* Looping var */
+  char         value[1024],            /* Value string */
+               *valptr,                /* Pointer into value string */
+               *attrptr;               /* Pointer into attribute value */
+  const char   *cached;                /* Cached attribute */
 
 
  /*
@@ -2165,11 +2396,21 @@ report_attr(ipp_attribute_t *attr)      /* I - Attribute */
 
   *valptr = '\0';
 
- /*
-  * Tell the scheduler about the new values...
-  */
+  _cupsMutexLock(&report_mutex);
 
-  fprintf(stderr, "ATTR: %s=%s\n", attr->name, value);
+  if ((cached = cupsGetOption(attr->name, num_attr_cache,
+                              attr_cache)) == NULL || strcmp(cached, value))
+  {
+   /*
+    * Tell the scheduler about the new values...
+    */
+
+    num_attr_cache = cupsAddOption(attr->name, value, num_attr_cache,
+                                   &attr_cache);
+    fprintf(stderr, "ATTR: %s=%s\n", attr->name, value);
+  }
+
+  _cupsMutexUnlock(&report_mutex);
 }
 
 
@@ -2177,19 +2418,14 @@ report_attr(ipp_attribute_t *attr)      /* I - Attribute */
  * 'report_printer_state()' - Report the printer state.
  */
 
-static int                             /* O - Number of reasons shown */
-report_printer_state(ipp_t *ipp,       /* I - IPP response */
-                     int   job_id)     /* I - Current job ID */
+static void
+report_printer_state(ipp_t *ipp)       /* I - IPP response */
 {
-  int                  i;              /* Looping var */
-  int                  count;          /* Count of reasons shown... */
   ipp_attribute_t      *pa,            /* printer-alert */
                        *pam,           /* printer-alert-message */
                        *psm,           /* printer-state-message */
                        *reasons,       /* printer-state-reasons */
                        *marker;        /* marker-* attributes */
-  const char           *reason;        /* Current reason */
-  const char           *prefix;        /* Prefix for STATE: line */
   char                 value[1024],    /* State/message string */
                        *valptr;        /* Pointer into string */
   static int           ipp_supplies = -1;
@@ -2245,33 +2481,9 @@ report_printer_state(ipp_t *ipp, /* I - IPP response */
 
   if ((reasons = ippFindAttribute(ipp, "printer-state-reasons",
                                   IPP_TAG_KEYWORD)) == NULL)
-    return (0);
-
-  value[0] = '\0';
-  prefix   = "STATE: ";
-
-  for (i = 0, count = 0, valptr = value; i < reasons->num_values; i ++)
-  {
-    reason = reasons->values[i].string.text;
-
-    if (strcmp(reason, "paused") &&
-       strcmp(reason, "com.apple.print.recoverable-warning"))
-    {
-      strlcpy(valptr, prefix, sizeof(value) - (valptr - value) - 1);
-      valptr += strlen(valptr);
-      strlcpy(valptr, reason, sizeof(value) - (valptr - value) - 1);
-      valptr += strlen(valptr);
-
-      prefix  = ",";
-    }
-  }
+    return;
 
-  if (value[0])
-  {
-    *valptr++ = '\n';
-    *valptr   = '\0';
-    fputs(value, stderr);
-  }
+  update_reasons(reasons, NULL);
 
  /*
   * Relay the current marker-* attribute values...
@@ -2284,7 +2496,7 @@ report_printer_state(ipp_t *ipp,  /* I - IPP response */
 
     if ((ppd = ppdOpenFile(getenv("PPD"))) != NULL &&
         (ppdattr = ppdFindAttr(ppd, "cupsIPPSupplies", NULL)) != NULL &&
-        ppdattr->value && strcasecmp(ppdattr->value, "true"))
+        ppdattr->value && _cups_strcasecmp(ppdattr->value, "true"))
       ipp_supplies = 0;
     else
       ipp_supplies = 1;
@@ -2314,9 +2526,200 @@ report_printer_state(ipp_t *ipp,        /* I - IPP response */
                                    IPP_TAG_KEYWORD)) != NULL)
       report_attr(marker);
   }
+}
+
+
+#if defined(HAVE_GSSAPI) && defined(HAVE_XPC)
+/*
+ * 'run_as_user()' - Run the IPP backend as the printing user.
+ *
+ * This function uses an XPC-based user agent to run the backend as the printing
+ * user. We need to do this in order to have access to the user's Kerberos
+ * credentials.
+ */
+
+static int                             /* O - Exit status */
+run_as_user(int        argc,           /* I - Number of command-line args */
+           char       *argv[],         /* I - Command-line arguments */
+           uid_t      uid,             /* I - User ID */
+           const char *device_uri,     /* I - Device URI */
+           int        fd)              /* I - File to print */
+{
+  const char           *auth_negotiate;/* AUTH_NEGOTIATE env var */
+  xpc_connection_t     conn;           /* Connection to XPC service */
+  xpc_object_t         request;        /* Request message dictionary */
+  __block xpc_object_t response;       /* Response message dictionary */
+  dispatch_semaphore_t sem;            /* Semaphore for waiting for response */
+  int                  status = CUPS_BACKEND_FAILED;
+                                       /* Status of request */
+
+
+  fprintf(stderr, "DEBUG: Running IPP backend as UID %d.\n", (int)uid);
 
-  return (count);
+ /*
+  * Connect to the user agent for the specified UID...
+  */
+
+  conn = xpc_connection_create_mach_service(kPMPrintUIToolAgent,
+                                            dispatch_get_global_queue(0, 0), 0);
+  if (!conn)
+  {
+    _cupsLangPrintFilter(stderr, "ERROR",
+                         _("Unable to start backend process."));
+    fputs("DEBUG: Unable to create connection to agent.\n", stderr);
+    goto cleanup;
+  }
+
+  xpc_connection_set_event_handler(conn,
+                                   ^(xpc_object_t event)
+                                  {
+                                    xpc_type_t messageType = xpc_get_type(event);
+
+                                    if (messageType == XPC_TYPE_ERROR)
+                                    {
+                                      if (event == XPC_ERROR_CONNECTION_INTERRUPTED)
+                                        fprintf(stderr, "DEBUG: Interrupted connection to service %s.\n",
+                                                xpc_connection_get_name(conn));
+                                      else if (event == XPC_ERROR_CONNECTION_INVALID)
+                                        fprintf(stderr, "DEBUG: Connection invalid for service %s.\n",
+                                                xpc_connection_get_name(conn));
+                                      else
+                                        fprintf(stderr, "DEBUG: Unxpected error for service %s: %s\n",
+                                                xpc_connection_get_name(conn),
+                                                xpc_dictionary_get_string(event, XPC_ERROR_KEY_DESCRIPTION));
+                                    }
+                                  });
+  xpc_connection_set_target_uid(conn, uid);
+  xpc_connection_resume(conn);
+
+ /*
+  * Try starting the backend...
+  */
+
+  request = xpc_dictionary_create(NULL, NULL, 0);
+  xpc_dictionary_set_int64(request, "command", kPMStartJob);
+  xpc_dictionary_set_string(request, "device-uri", device_uri);
+  xpc_dictionary_set_string(request, "job-id", argv[1]);
+  xpc_dictionary_set_string(request, "user", argv[2]);
+  xpc_dictionary_set_string(request, "title", argv[3]);
+  xpc_dictionary_set_string(request, "copies", argv[4]);
+  xpc_dictionary_set_string(request, "options", argv[5]);
+  xpc_dictionary_set_string(request, "auth-info-required",
+                            getenv("AUTH_INFO_REQUIRED"));
+  if ((auth_negotiate = getenv("AUTH_NEGOTIATE")) != NULL)
+    xpc_dictionary_set_string(request, "auth-negotiate", auth_negotiate);
+  xpc_dictionary_set_fd(request, "stdin", fd);
+  xpc_dictionary_set_fd(request, "stderr", 2);
+  xpc_dictionary_set_fd(request, "side-channel", CUPS_SC_FD);
+
+  sem      = dispatch_semaphore_create(0);
+  response = NULL;
+
+  xpc_connection_send_message_with_reply(conn, request,
+                                         dispatch_get_global_queue(0,0),
+                                        ^(xpc_object_t reply)
+                                        {
+                                          /* Save the response and wake up */
+                                          if (xpc_get_type(reply)
+                                                  == XPC_TYPE_DICTIONARY)
+                                            response = xpc_retain(reply);
+
+                                          dispatch_semaphore_signal(sem);
+                                        });
+
+  dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
+  xpc_release(request);
+  dispatch_release(sem);
+
+  if (response)
+  {
+    child_pid = xpc_dictionary_get_int64(response, "child-pid");
+
+    xpc_release(response);
+
+    if (child_pid)
+      fprintf(stderr, "DEBUG: Child PID=%d.\n", child_pid);
+    else
+    {
+      _cupsLangPrintFilter(stderr, "ERROR",
+                           _("Unable to start backend process."));
+      fputs("DEBUG: No child PID.\n", stderr);
+      goto cleanup;
+    }
+  }
+  else
+  {
+    _cupsLangPrintFilter(stderr, "ERROR",
+                         _("Unable to start backend process."));
+    fputs("DEBUG: No reply from agent.\n", stderr);
+    goto cleanup;
+  }
+
+ /*
+  * Then wait for the backend to finish...
+  */
+
+  request = xpc_dictionary_create(NULL, NULL, 0);
+  xpc_dictionary_set_int64(request, "command", kPMWaitForJob);
+  xpc_dictionary_set_fd(request, "stderr", 2);
+
+  sem      = dispatch_semaphore_create(0);
+  response = NULL;
+
+  xpc_connection_send_message_with_reply(conn, request,
+                                         dispatch_get_global_queue(0,0),
+                                        ^(xpc_object_t reply)
+                                        {
+                                          /* Save the response and wake up */
+                                          if (xpc_get_type(reply)
+                                                  == XPC_TYPE_DICTIONARY)
+                                            response = xpc_retain(reply);
+
+                                          dispatch_semaphore_signal(sem);
+                                        });
+
+  dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
+  xpc_release(request);
+  dispatch_release(sem);
+
+  if (response)
+  {
+    status = xpc_dictionary_get_int64(response, "status");
+
+    if (status == SIGTERM || status == SIGKILL || status == SIGPIPE)
+    {
+      fprintf(stderr, "DEBUG: Child terminated on signal %d.\n", status);
+      status = CUPS_BACKEND_FAILED;
+    }
+    else if (WIFSIGNALED(status))
+    {
+      fprintf(stderr, "DEBUG: Child crashed on signal %d.\n", status);
+      status = CUPS_BACKEND_STOP;
+    }
+    else if (WIFEXITED(status))
+    {
+      status = WEXITSTATUS(status);
+      fprintf(stderr, "DEBUG: Child exited with status %d.\n", status);
+    }
+
+    xpc_release(response);
+  }
+  else
+    _cupsLangPrintFilter(stderr, "ERROR",
+                         _("Unable to get backend exit status."));
+
+  cleanup:
+
+  if (conn)
+  {
+    xpc_connection_suspend(conn);
+    xpc_connection_cancel(conn);
+    xpc_release(conn);
+  }
+
+  return (status);
 }
+#endif /* HAVE_GSSAPI && HAVE_XPC */
 
 
 /*
@@ -2328,10 +2731,18 @@ sigterm_handler(int sig)                /* I - Signal */
 {
   (void)sig;   /* remove compiler warnings... */
 
+#if defined(HAVE_GSSAPI) && defined(HAVE_XPC)
+  if (child_pid)
+  {
+    kill(child_pid, sig);
+    child_pid = 0;
+  }
+#endif /* HAVE_GSSAPI && HAVE_XPC */
+
   if (!job_canceled)
   {
    /*
-    * Flag that the job should be cancelled...
+    * Flag that the job should be canceled...
     */
 
     job_canceled = 1;
@@ -2340,7 +2751,7 @@ sigterm_handler(int sig)          /* I - Signal */
 
  /*
   * The scheduler already tried to cancel us once, now just terminate
-  * after removing our temp files!
+  * after removing our temp file!
   */
 
   if (tmpfilename[0])
@@ -2351,5 +2762,201 @@ sigterm_handler(int sig)                /* I - Signal */
 
 
 /*
- * End of "$Id: ipp.c 7948 2008-09-17 00:04:12Z mike $".
+ * 'update_reasons()' - Update the printer-state-reasons values.
+ */
+
+static void
+update_reasons(ipp_attribute_t *attr,  /* I - printer-state-reasons or NULL */
+               const char      *s)     /* I - STATE: string or NULL */
+{
+  char         op;                     /* Add (+), remove (-), replace (\0) */
+  cups_array_t *new_reasons;           /* New reasons array */
+  char         *reason,                /* Current reason */
+               add[2048],              /* Reasons added string */
+               *addptr,                /* Pointer into add string */
+               rem[2048],              /* Reasons removed string */
+               *remptr;                /* Pointer into remove string */
+  const char   *addprefix,             /* Current add string prefix */
+               *remprefix;             /* Current remove string prefix */
+
+
+  fprintf(stderr, "DEBUG: update_reasons(attr=%d(%s%s), s=\"%s\")\n",
+         attr ? attr->num_values : 0, attr ? attr->values[0].string.text : "",
+         attr && attr->num_values > 1 ? ",..." : "", s ? s : "(null)");
+
+ /*
+  * Create an array of new reason keyword strings...
+  */
+
+  if (attr)
+  {
+    int        i;                              /* Looping var */
+
+    new_reasons = cupsArrayNew((cups_array_func_t)strcmp, NULL);
+    op          = '\0';
+
+    for (i = 0; i < attr->num_values; i ++)
+    {
+      reason = attr->values[i].string.text;
+
+      if (strcmp(reason, "none") &&
+         strcmp(reason, "none-report") &&
+         strcmp(reason, "paused") &&
+         strcmp(reason, "com.apple.print.recoverable-warning") &&
+         strncmp(reason, "cups-", 5))
+       cupsArrayAdd(new_reasons, reason);
+    }
+  }
+  else if (s)
+  {
+    if (*s == '+' || *s == '-')
+      op = *s++;
+    else
+      op = '\0';
+
+    new_reasons = _cupsArrayNewStrings(s);
+  }
+  else
+    return;
+
+ /*
+  * Compute the changes...
+  */
+
+  add[0]    = '\0';
+  addprefix = "STATE: +";
+  addptr    = add;
+  rem[0]    = '\0';
+  remprefix = "STATE: -";
+  remptr    = rem;
+
+  fprintf(stderr, "DEBUG2: op='%c', new_reasons=%d, state_reasons=%d\n",
+          op ? op : ' ', cupsArrayCount(new_reasons),
+         cupsArrayCount(state_reasons));
+
+  _cupsMutexLock(&report_mutex);
+
+  if (op == '+')
+  {
+   /*
+    * Add reasons...
+    */
+
+    for (reason = (char *)cupsArrayFirst(new_reasons);
+        reason;
+        reason = (char *)cupsArrayNext(new_reasons))
+    {
+      if (!cupsArrayFind(state_reasons, reason))
+      {
+        if (!strncmp(reason, "cups-remote-", 12))
+       {
+        /*
+         * If we are setting cups-remote-xxx, remove all other cups-remote-xxx
+         * keywords...
+         */
+
+         char  *temp;          /* Current reason in state_reasons */
+
+         cupsArraySave(state_reasons);
+
+         for (temp = (char *)cupsArrayFirst(state_reasons);
+              temp;
+              temp = (char *)cupsArrayNext(state_reasons))
+           if (!strncmp(temp, "cups-remote-", 12))
+           {
+             snprintf(remptr, sizeof(rem) - (remptr - rem), "%s%s", remprefix,
+                      temp);
+             remptr    += strlen(remptr);
+             remprefix = ",";
+
+             cupsArrayRemove(state_reasons, temp);
+             break;
+           }
+
+         cupsArrayRestore(state_reasons);
+       }
+
+        cupsArrayAdd(state_reasons, reason);
+
+        snprintf(addptr, sizeof(add) - (addptr - add), "%s%s", addprefix,
+                reason);
+       addptr    += strlen(addptr);
+       addprefix = ",";
+      }
+    }
+  }
+  else if (op == '-')
+  {
+   /*
+    * Remove reasons...
+    */
+
+    for (reason = (char *)cupsArrayFirst(new_reasons);
+        reason;
+        reason = (char *)cupsArrayNext(new_reasons))
+    {
+      if (cupsArrayFind(state_reasons, reason))
+      {
+       snprintf(remptr, sizeof(rem) - (remptr - rem), "%s%s", remprefix,
+                reason);
+       remptr    += strlen(remptr);
+       remprefix = ",";
+
+        cupsArrayRemove(state_reasons, reason);
+      }
+    }
+  }
+  else
+  {
+   /*
+    * Replace reasons...
+    */
+
+    for (reason = (char *)cupsArrayFirst(state_reasons);
+        reason;
+        reason = (char *)cupsArrayNext(state_reasons))
+    {
+      if (strncmp(reason, "cups-", 5) && !cupsArrayFind(new_reasons, reason))
+      {
+       snprintf(remptr, sizeof(rem) - (remptr - rem), "%s%s", remprefix,
+                reason);
+       remptr    += strlen(remptr);
+       remprefix = ",";
+
+        cupsArrayRemove(state_reasons, reason);
+      }
+    }
+
+    for (reason = (char *)cupsArrayFirst(new_reasons);
+        reason;
+        reason = (char *)cupsArrayNext(new_reasons))
+    {
+      if (!cupsArrayFind(state_reasons, reason))
+      {
+        cupsArrayAdd(state_reasons, reason);
+
+        snprintf(addptr, sizeof(add) - (addptr - add), "%s%s", addprefix,
+                reason);
+       addptr    += strlen(addptr);
+       addprefix = ",";
+      }
+    }
+  }
+
+  _cupsMutexUnlock(&report_mutex);
+
+ /*
+  * Report changes and return...
+  */
+
+  if (add[0] && rem[0])
+    fprintf(stderr, "%s\n%s\n", add, rem);
+  else if (add[0])
+    fprintf(stderr, "%s\n", add);
+  else if (rem[0])
+    fprintf(stderr, "%s\n", rem);
+}
+
+/*
+ * End of "$Id: ipp.c 9759 2011-05-11 03:24:33Z mike $".
  */