]> git.ipfire.org Git - thirdparty/cups.git/blobdiff - scheduler/job.c
Merge changes from CUPS 1.3.1.
[thirdparty/cups.git] / scheduler / job.c
index 0c65f3e34b91bdbf3f717c43df0085f1823ebb3e..aecad497e0d8d49846d1648eab15b01909583b3a 100644 (file)
@@ -1,25 +1,16 @@
 /*
- * "$Id: job.c 5131 2006-02-18 05:31:36Z mike $"
+ * "$Id: job.c 6887 2007-08-29 21:52:06Z mike $"
  *
  *   Job management routines for the Common UNIX Printing System (CUPS).
  *
- *   Copyright 1997-2006 by Easy Software Products, all rights reserved.
+ *   Copyright 2007 by Apple Inc.
+ *   Copyright 1997-2007 by Easy Software Products, all rights reserved.
  *
  *   These coded instructions, statements, and computer programs are the
- *   property of Easy Software Products and are protected by Federal
- *   copyright law.  Distribution and use rights are outlined in the file
- *   "LICENSE.txt" which should have been included with this file.  If this
- *   file is missing or damaged please contact Easy Software Products
- *   at:
- *
- *       Attn: CUPS Licensing Information
- *       Easy Software Products
- *       44141 Airport View Drive, Suite 204
- *       Hollywood, Maryland 20636 USA
- *
- *       Voice: (301) 373-9600
- *       EMail: cups-info@cups.org
- *         WWW: http://www.cups.org
+ *   property of Apple Inc. and are protected by Federal copyright
+ *   law.  Distribution and use rights are outlined in the file "LICENSE.txt"
+ *   which should have been included with this file.  If this file is
+ *   file is missing or damaged, see the license at "http://www.cups.org/".
  *
  * Contents:
  *
  *   cupsdSetJobHoldUntil()     - Set the hold time for a job...
  *   cupsdSetJobPriority()      - Set the priority of a job, moving it
  *                                up/down in the list as needed.
- *   cupsdStartJob()            - Start a print job.
  *   cupsdStopAllJobs()         - Stop all print jobs.
  *   cupsdStopJob()             - Stop a print job.
  *   cupsdUnloadCompletedJobs() - Flush completed job history from memory.
- *   cupsdUnloadJob()           - Unload a job from memory.
- *   cupsdUpdateJob()           - Read a status update from a jobs filters.
  *   compare_active_jobs()      - Compare the job IDs and priorities of two
  *                                jobs.
  *   compare_jobs()             - Compare the job IDs of two jobs.
  *   set_time()                 - Set one of the "time-at-xyz" attributes...
  *   set_hold_until()           - Set the hold time and update job-hold-until
  *                                attribute...
+ *   start_job()                - Start a print job.
+ *   unload_job()               - Unload a job from memory.
+ *   update_job()               - Read a status update from a jobs filters.
+ *   update_job_attrs()         - Update the job-printer-* attributes.
  */
 
 /*
@@ -104,6 +96,10 @@ static void load_next_job_id(const char *filename);
 static void    load_request_root(void);
 static void    set_time(cupsd_job_t *job, const char *name);
 static void    set_hold_until(cupsd_job_t *job, time_t holdtime);
+static void    start_job(cupsd_job_t *job, cupsd_printer_t *printer);
+static void    unload_job(cupsd_job_t *job);
+static void    update_job(cupsd_job_t *job);
+static void    update_job_attrs(cupsd_job_t *job);
 
 
 /*
@@ -119,12 +115,16 @@ cupsdAddJob(int        priority,  /* I - Job priority */
 
   job = calloc(sizeof(cupsd_job_t), 1);
 
-  job->id             = NextJobId ++;
-  job->priority       = priority;
-  job->back_pipes[0]  = -1;
-  job->back_pipes[1]  = -1;
-  job->print_pipes[0] = -1;
-  job->print_pipes[1] = -1;
+  job->id              = NextJobId ++;
+  job->priority        = priority;
+  job->back_pipes[0]   = -1;
+  job->back_pipes[1]   = -1;
+  job->print_pipes[0]  = -1;
+  job->print_pipes[1]  = -1;
+  job->side_pipes[0]   = -1;
+  job->side_pipes[1]   = -1;
+  job->status_pipes[0] = -1;
+  job->status_pipes[1] = -1;
 
   cupsdSetString(&job->dest, dest);
 
@@ -144,11 +144,13 @@ cupsdAddJob(int        priority,  /* I - Job priority */
  */
 
 void
-cupsdCancelJob(cupsd_job_t *job,       /* I - Job to cancel */
-               int         purge)      /* I - Purge jobs? */
+cupsdCancelJob(cupsd_job_t  *job,      /* I - Job to cancel */
+               int          purge,     /* I - Purge jobs? */
+              ipp_jstate_t newstate)   /* I - New job state */
 {
   int          i;                      /* Looping var */
   char         filename[1024];         /* Job filename */
+  cupsd_printer_t *printer;            /* Printer used by job */
 
 
   cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdCancelJob: id = %d", job->id);
@@ -157,18 +159,54 @@ cupsdCancelJob(cupsd_job_t *job,  /* I - Job to cancel */
   * Stop any processes that are working on the current job...
   */
 
+  printer = job->printer;
+
   if (job->state_value == IPP_JOB_PROCESSING)
     cupsdStopJob(job, 0);
 
   cupsdLoadJob(job);
 
   if (job->attrs)
-    job->state->values[0].integer = IPP_JOB_CANCELLED;
+    job->state->values[0].integer = newstate;
 
-  job->state_value = IPP_JOB_CANCELLED;
+  job->state_value = newstate;
 
   set_time(job, "time-at-completed");
 
+ /*
+  * Send any pending notifications and then expire them...
+  */
+
+  switch (newstate)
+  {
+    default :
+        break;
+
+    case IPP_JOB_CANCELED :
+       cupsdAddEvent(CUPSD_EVENT_JOB_COMPLETED, printer, job,
+                      purge ? "Job purged." : "Job canceled.");
+        break;
+
+    case IPP_JOB_ABORTED :
+       cupsdAddEvent(CUPSD_EVENT_JOB_COMPLETED, printer, job,
+                      "Job aborted; please consult the error_log file "
+                     "for details.");
+        break;
+
+    case IPP_JOB_COMPLETED :
+       /*
+       * Clear the printer's printer-state-message and move on...
+       */
+
+       printer->state_message[0] = '\0';
+
+       cupsdSetPrinterState(printer, IPP_PRINTER_IDLE, 0);
+
+       cupsdAddEvent(CUPSD_EVENT_JOB_COMPLETED, printer, job,
+                      "Job completed.");
+        break;
+  }
+
   cupsdExpireSubscriptions(NULL, job);
 
  /*
@@ -182,7 +220,28 @@ cupsdCancelJob(cupsd_job_t *job,   /* I - Job to cancel */
   */
 
   snprintf(filename, sizeof(filename), "%s/a%05d", RequestRoot, job->id);
-  unlink(filename);
+  if (cupsdRemoveFile(filename) && errno != ENOENT)
+    cupsdLogMessage(CUPSD_LOG_ERROR,
+                    "Unable to remove authentication cache: %s",
+                   strerror(errno));
+
+  cupsdClearString(&job->auth_username);
+  cupsdClearString(&job->auth_domain);
+  cupsdClearString(&job->auth_password);
+
+#ifdef HAVE_GSSAPI
+ /*
+  * Destroy the credential cache and clear the KRB5CCNAME env var string.
+  */
+
+  if (job->ccache)
+  {
+    krb5_cc_destroy(KerberosContext, job->ccache);
+    job->ccache = NULL;
+  }
+
+  cupsdClearString(&job->ccname);
+#endif /* HAVE_GSSAPI */
 
  /*
   * Remove the print file for good if we aren't preserving jobs or
@@ -266,10 +325,7 @@ cupsdCancelJobs(const char *dest,  /* I - Destination to cancel */
       * Cancel all jobs matching this destination/user...
       */
 
-      cupsdAddEvent(CUPSD_EVENT_JOB_COMPLETED, job->printer, job,
-                    purge ? "Job purged." : "Job canceled.");
-
-      cupsdCancelJob(job, purge);
+      cupsdCancelJob(job, purge, IPP_JOB_CANCELED);
     }
 
   cupsdCheckJobs();
@@ -311,6 +367,9 @@ cupsdCheckJobs(void)
         job->hold_until &&
        job->hold_until < time(NULL))
     {
+      if (job->pending_timeout)
+        cupsdTimeoutJob(job);          /* Add trailing banner as needed */
+
       job->state->values[0].integer = IPP_JOB_PENDING;
       job->state_value              = IPP_JOB_PENDING;
     }
@@ -333,13 +392,12 @@ cupsdCheckJobs(void)
 
         pclass = printer;
 
-        if (!(pclass->type & CUPS_PRINTER_REMOTE))
-       {
-         if (pclass->state != IPP_PRINTER_STOPPED)
-           printer = cupsdFindAvailablePrinter(job->dest);
-         else
-           printer = NULL;
-       }
+        if (pclass->state == IPP_PRINTER_STOPPED)
+         printer = NULL;
+        else if (pclass->type & CUPS_PRINTER_REMOTE)
+         break;
+       else
+         printer = cupsdFindAvailablePrinter(printer->name);
       }
 
       if (!printer && !pclass)
@@ -350,14 +408,14 @@ cupsdCheckJobs(void)
        */
 
         cupsdLogMessage(CUPSD_LOG_WARN,
-                       "Printer/class %s has gone away; cancelling job %d!",
-                       job->dest, job->id);
+                       "[Job %d] Printer/class %s has gone away; canceling job!",
+                       job->id, job->dest);
 
        cupsdAddEvent(CUPSD_EVENT_JOB_COMPLETED, job->printer, job,
                       "Job canceled because the destination printer/class has "
                      "gone away.");
 
-        cupsdCancelJob(job, 1);
+        cupsdCancelJob(job, 1, IPP_JOB_ABORTED);
       }
       else if (printer)
       {
@@ -384,10 +442,25 @@ cupsdCheckJobs(void)
                         "job-actual-printer-uri", NULL, printer->uri);
        }
 
-        if (printer->state == IPP_PRINTER_IDLE ||      /* Printer is idle */
-           ((printer->type & CUPS_PRINTER_REMOTE) &&   /* Printer is remote */
+        if ((!(printer->type & CUPS_PRINTER_DISCOVERED) && /* Printer is local */
+            printer->state == IPP_PRINTER_IDLE) ||     /* and idle */
+           ((printer->type & CUPS_PRINTER_DISCOVERED) && /* Printer is remote */
             !printer->job))                            /* and not printing */
-         cupsdStartJob(job, printer);
+        {
+        /* 
+         * Clear any message and reasons for the queue...
+         */
+
+          printer->state_message[0] = '\0';
+
+         cupsdSetPrinterReasons(printer, "none");
+
+        /*
+         * Start the job...
+         */
+
+         start_job(job, printer);
+       }
       }
     }
   }
@@ -410,8 +483,8 @@ cupsdCleanJobs(void)
   for (job = (cupsd_job_t *)cupsArrayFirst(Jobs);
        job && cupsArrayCount(Jobs) >= MaxJobs;
        job = (cupsd_job_t *)cupsArrayNext(Jobs))
-    if (job->state_value >= IPP_JOB_CANCELLED)
-      cupsdCancelJob(job, 1);
+    if (job->state_value >= IPP_JOB_CANCELED)
+      cupsdCancelJob(job, 1, IPP_JOB_CANCELED);
 }
 
 
@@ -422,32 +495,31 @@ cupsdCleanJobs(void)
 void
 cupsdFinishJob(cupsd_job_t *job)       /* I - Job */
 {
-  int                  job_history;    /* Did cupsdCancelJob() keep the job? */
   cupsd_printer_t      *printer;       /* Current printer */
+  ipp_attribute_t      *attr;          /* job-hold-until attribute */
 
 
   cupsdLogMessage(CUPSD_LOG_DEBUG, "[Job %d] File %d is complete.",
                   job->id, job->current_file - 1);
 
-  cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdFinishJob: job->status is %d",
-                  job->status);
+  cupsdLogMessage(CUPSD_LOG_DEBUG2,
+                  "[Job %d] cupsdFinishJob: job->status is %d",
+                  job->id, job->status);
 
-  if (job->status_buffer && job->current_file >= job->num_files)
+  if (job->status_buffer &&
+      (job->status < 0 || job->current_file >= job->num_files))
   {
    /*
     * Close the pipe and clear the input bit.
     */
 
-    cupsdLogMessage(CUPSD_LOG_DEBUG2,
-                    "cupsdFinishJob: Removing fd %d from InputSet...",
-                    job->status_buffer->fd);
-
-    FD_CLR(job->status_buffer->fd, InputSet);
+    cupsdRemoveSelect(job->status_buffer->fd);
 
     cupsdLogMessage(CUPSD_LOG_DEBUG2,
-                    "cupsdFinishJob: Closing status input pipe %d...",
-                    job->status_buffer->fd);
+                   "[Job %d] cupsdFinishJob: Closing status pipes [ %d %d ]...",
+                   job->id, job->status_pipes[0], job->status_pipes[1]);
 
+    cupsdClosePipe(job->status_pipes);
     cupsdStatBufDelete(job->status_buffer);
 
     job->status_buffer = NULL;
@@ -455,13 +527,44 @@ cupsdFinishJob(cupsd_job_t *job)  /* I - Job */
 
   printer = job->printer;
 
+  update_job_attrs(job);
+
   if (job->status < 0)
   {
    /*
     * Backend had errors; stop it...
     */
 
-    switch (-job->status)
+    int exit_code;                     /* Exit code from backend */
+
+
+   /*
+    * Convert the status to an exit code.  Due to the way the W* macros are
+    * implemented on MacOS X (bug?), we have to store the exit status in a
+    * variable first and then convert...
+    */
+
+    exit_code = -job->status;
+    if (WIFEXITED(exit_code))
+      exit_code = WEXITSTATUS(exit_code);
+    else
+      exit_code = job->status;
+
+    cupsdLogMessage(CUPSD_LOG_INFO, "[Job %d] Backend returned status %d (%s)",
+                    job->id, exit_code,
+                   exit_code == CUPS_BACKEND_FAILED ? "failed" :
+                       exit_code == CUPS_BACKEND_AUTH_REQUIRED ?
+                           "authentication required" :
+                       exit_code == CUPS_BACKEND_HOLD ? "hold job" :
+                       exit_code == CUPS_BACKEND_STOP ? "stop printer" :
+                       exit_code == CUPS_BACKEND_CANCEL ? "cancel job" :
+                       exit_code < 0 ? "crashed" : "unknown");
+
+   /*
+    * Do what needs to be done...
+    */
+
+    switch (exit_code)
     {
       default :
       case CUPS_BACKEND_FAILED :
@@ -471,8 +574,18 @@ cupsdFinishJob(cupsd_job_t *job)   /* I - Job */
          */
 
          cupsdStopJob(job, 0);
-         job->state->values[0].integer = IPP_JOB_PENDING;
-         job->state_value              = IPP_JOB_PENDING;
+
+          if (job->dtype & (CUPS_PRINTER_CLASS | CUPS_PRINTER_IMPLICIT))
+         {
+          /*
+           * Mark the job as pending again - we'll retry on another
+           * printer...
+           */
+
+           job->state->values[0].integer = IPP_JOB_PENDING;
+           job->state_value              = IPP_JOB_PENDING;
+          }
+
          cupsdSaveJob(job);
 
         /*
@@ -499,16 +612,11 @@ cupsdFinishJob(cupsd_job_t *job)  /* I - Job */
              */
 
              cupsdLogMessage(CUPSD_LOG_ERROR,
-                             "Canceling job %d since it could not be sent "
-                             "after %d tries.",
+                             "[Job %d] Canceling job since it could not be "
+                             "sent after %d tries.",
                              job->id, JobRetryLimit);
 
-             cupsdAddEvent(CUPSD_EVENT_JOB_COMPLETED, printer, job,
-                           "Job canceled since it could not be sent after %d "
-                           "tries.",
-                           JobRetryLimit);
-
-             cupsdCancelJob(job, 0);
+             cupsdCancelJob(job, 0, IPP_JOB_ABORTED);
            }
            else
            {
@@ -517,10 +625,23 @@ cupsdFinishJob(cupsd_job_t *job)  /* I - Job */
              */
 
              set_hold_until(job, time(NULL) + JobRetryInterval);
+
+             cupsdAddEvent(CUPSD_EVENT_JOB_STATE, job->printer, job,
+                           "Job held due to fax errors; please consult "
+                           "the error_log file for details.");
+             cupsdSetPrinterState(printer, IPP_PRINTER_IDLE, 0);
            }
          }
          else if (!strcmp(printer->error_policy, "abort-job"))
-           cupsdCancelJob(job, 0);
+           cupsdCancelJob(job, 0, IPP_JOB_ABORTED);
+          else
+          {
+           cupsdSetPrinterState(printer, IPP_PRINTER_STOPPED, 1);
+
+           cupsdAddEvent(CUPSD_EVENT_JOB_STOPPED, printer, job,
+                         "Job stopped due to backend errors; please consult "
+                         "the error_log file for details.");
+         }
           break;
 
       case CUPS_BACKEND_CANCEL :
@@ -528,7 +649,7 @@ cupsdFinishJob(cupsd_job_t *job)    /* I - Job */
          * Cancel the job...
          */
 
-         cupsdCancelJob(job, 0);
+         cupsdCancelJob(job, 0, IPP_JOB_CANCELED);
           break;
 
       case CUPS_BACKEND_HOLD :
@@ -537,8 +658,17 @@ cupsdFinishJob(cupsd_job_t *job)   /* I - Job */
          */
 
          cupsdStopJob(job, 0);
+
          cupsdSetJobHoldUntil(job, "indefinite");
+
+         job->state->values[0].integer = IPP_JOB_HELD;
+         job->state_value              = IPP_JOB_HELD;
+
          cupsdSaveJob(job);
+
+         cupsdAddEvent(CUPSD_EVENT_JOB_STOPPED, printer, job,
+                       "Job held due to backend errors; please consult "
+                       "the error_log file for details.");
           break;
 
       case CUPS_BACKEND_STOP :
@@ -547,13 +677,37 @@ cupsdFinishJob(cupsd_job_t *job)  /* I - Job */
          */
 
          cupsdStopJob(job, 0);
+
+         job->state->values[0].integer = IPP_JOB_PENDING;
+         job->state_value              = IPP_JOB_PENDING;
+
          cupsdSaveJob(job);
          cupsdSetPrinterState(printer, IPP_PRINTER_STOPPED, 1);
+
+         cupsdAddEvent(CUPSD_EVENT_JOB_STOPPED, printer, job,
+                       "Job stopped due to backend errors; please consult "
+                       "the error_log file for details.");
           break;
 
       case CUPS_BACKEND_AUTH_REQUIRED :
          cupsdStopJob(job, 0);
-         cupsdSetJobHoldUntil(job, "authenticated");
+
+         cupsdSetJobHoldUntil(job, "auth-info-required");
+
+         if ((attr = ippFindAttribute(job->attrs, "job-hold-until",
+                                      IPP_TAG_KEYWORD)) == NULL)
+           attr = ippFindAttribute(job->attrs, "job-hold-until", IPP_TAG_NAME);
+
+         if (attr)
+         {
+           attr->value_tag = IPP_TAG_KEYWORD;
+           cupsdSetString(&(attr->values[0].string.text),
+                          "auth-info-required");
+         }
+
+         job->state->values[0].integer = IPP_JOB_HELD;
+         job->state_value              = IPP_JOB_HELD;
+
          cupsdSaveJob(job);
 
          cupsdAddEvent(CUPSD_EVENT_JOB_STOPPED, printer, job,
@@ -573,6 +727,8 @@ cupsdFinishJob(cupsd_job_t *job)    /* I - Job */
     * Filter had errors; stop job...
     */
 
+    cupsdLogMessage(CUPSD_LOG_ERROR,
+                    "[Job %d] Job stopped due to filter errors.", job->id);
     cupsdStopJob(job, 1);
     cupsdSaveJob(job);
     cupsdAddEvent(CUPSD_EVENT_JOB_STOPPED, printer, job,
@@ -593,7 +749,7 @@ cupsdFinishJob(cupsd_job_t *job)    /* I - Job */
       */
 
       FilterLevel -= job->cost;
-      cupsdStartJob(job, printer);
+      start_job(job, printer);
     }
     else
     {
@@ -601,28 +757,9 @@ cupsdFinishJob(cupsd_job_t *job)   /* I - Job */
       * Close out this job...
       */
 
-      cupsdAddEvent(CUPSD_EVENT_JOB_COMPLETED, printer, job,
-                    "Job completed successfully.");
-
-      job_history = JobHistory && !(job->dtype & CUPS_PRINTER_REMOTE);
-
-      cupsdCancelJob(job, 0);
-
-      if (job_history)
-      {
-        job->state->values[0].integer = IPP_JOB_COMPLETED;
-        job->state_value              = IPP_JOB_COMPLETED;
-       cupsdSaveJob(job);
-      }
-
-     /*
-      * Clear the printer's state_message and state_reasons and move on...
-      */
-
-      printer->state_message[0] = '\0';
-
-      cupsdSetPrinterReasons(printer, "");
-
+      cupsdLogMessage(CUPSD_LOG_INFO, "[Job %d] Completed successfully.",
+                     job->id);
+      cupsdCancelJob(job, 0, IPP_JOB_COMPLETED);
       cupsdCheckJobs();
     }
   }
@@ -644,7 +781,7 @@ cupsdFreeAllJobs(void)
 
   cupsdHoldSignals();
 
-  cupsdStopAllJobs();
+  cupsdStopAllJobs(1);
   cupsdSaveAllJobs();
 
   for (job = (cupsd_job_t *)cupsArrayFirst(Jobs);
@@ -830,21 +967,15 @@ cupsdLoadJob(cupsd_job_t *job)            /* I - Job */
   cups_file_t          *fp;            /* Job file */
   int                  fileid;         /* Current file ID */
   ipp_attribute_t      *attr;          /* Job attribute */
-  char                 scheme[32],     /* Scheme portion of URI */
-                       username[64],   /* Username portion of URI */
-                       host[HTTP_MAX_HOST],
-                                       /* Host portion of URI */
-                       resource[HTTP_MAX_URI];
-                                       /* Resource portion of URI */
-  int                  port;           /* Port portion of URI */
-  const char           *dest;          /* Destination */
+  const char           *dest;          /* Destination name */
+  cupsd_printer_t      *destptr;       /* Pointer to destination */
   mime_type_t          **filetypes;    /* New filetypes array */
   int                  *compressions;  /* New compressions array */
 
 
   if (job->attrs)
   {
-    if (job->state_value >= IPP_JOB_STOPPED)
+    if (job->state_value > IPP_JOB_STOPPED)
       job->access_time = time(NULL);
 
     return;
@@ -852,7 +983,8 @@ cupsdLoadJob(cupsd_job_t *job)              /* I - Job */
 
   if ((job->attrs = ippNew()) == NULL)
   {
-    cupsdLogMessage(CUPSD_LOG_ERROR, "Ran out of memory for job attributes!");
+    cupsdLogMessage(CUPSD_LOG_ERROR,
+                    "[Job %d] Ran out of memory for job attributes!", job->id);
     return;
   }
 
@@ -860,15 +992,14 @@ cupsdLoadJob(cupsd_job_t *job)            /* I - Job */
   * Load job attributes...
   */
 
-  cupsdLogMessage(CUPSD_LOG_DEBUG, "Loading attributes for job %d...",
-                  job->id);
+  cupsdLogMessage(CUPSD_LOG_DEBUG, "[Job %d] Loading attributes...", job->id);
 
   snprintf(jobfile, sizeof(jobfile), "%s/c%05d", RequestRoot, job->id);
   if ((fp = cupsFileOpen(jobfile, "r")) == NULL)
   {
     cupsdLogMessage(CUPSD_LOG_ERROR,
-                   "Unable to open job control file \"%s\" - %s!",
-                   jobfile, strerror(errno));
+                   "[Job %d] Unable to open job control file \"%s\" - %s!",
+                   job->id, jobfile, strerror(errno));
     ippDelete(job->attrs);
     job->attrs = NULL;
     return;
@@ -876,8 +1007,9 @@ cupsdLoadJob(cupsd_job_t *job)             /* I - Job */
 
   if (ippReadIO(fp, (ipp_iocb_t)cupsFileRead, 1, NULL, job->attrs) != IPP_DATA)
   {
-    cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to read job control file \"%s\"!",
-                   jobfile);
+    cupsdLogMessage(CUPSD_LOG_ERROR,
+                    "[Job %d] Unable to read job control file \"%s\"!",
+                   job->id, jobfile);
     cupsFileClose(fp);
     ippDelete(job->attrs);
     job->attrs = NULL;
@@ -895,9 +1027,9 @@ cupsdLoadJob(cupsd_job_t *job)             /* I - Job */
                                      IPP_TAG_ENUM)) == NULL)
   {
     cupsdLogMessage(CUPSD_LOG_ERROR,
-                   "Missing or bad job-state attribute in control "
-                   "file \"%s\"!",
-                   jobfile);
+                   "[Job %d] Missing or bad job-state attribute in "
+                   "control file!",
+                   job->id);
     ippDelete(job->attrs);
     job->attrs = NULL;
     unlink(jobfile);
@@ -912,24 +1044,20 @@ cupsdLoadJob(cupsd_job_t *job)           /* I - Job */
                                  IPP_TAG_URI)) == NULL)
     {
       cupsdLogMessage(CUPSD_LOG_ERROR,
-                     "No job-printer-uri attribute in control file \"%s\"!",
-                     jobfile);
+                     "[Job %d] No job-printer-uri attribute in control file!",
+                     job->id);
       ippDelete(job->attrs);
       job->attrs = NULL;
       unlink(jobfile);
       return;
     }
 
-    httpSeparateURI(HTTP_URI_CODING_ALL, attr->values[0].string.text, scheme,
-                    sizeof(scheme), username, sizeof(username), host,
-                   sizeof(host), &port, resource, sizeof(resource));
-
-    if ((dest = cupsdValidateDest(host, resource, &(job->dtype),
-                                  NULL)) == NULL)
+    if ((dest = cupsdValidateDest(attr->values[0].string.text, &(job->dtype),
+                                  &destptr)) == NULL)
     {
       cupsdLogMessage(CUPSD_LOG_ERROR,
-                     "Unable to queue job for destination \"%s\"!",
-                     attr->values[0].string.text);
+                     "[Job %d] Unable to queue job for destination \"%s\"!",
+                     job->id, attr->values[0].string.text);
       ippDelete(job->attrs);
       job->attrs = NULL;
       unlink(jobfile);
@@ -938,6 +1066,16 @@ cupsdLoadJob(cupsd_job_t *job)            /* I - Job */
 
     cupsdSetString(&job->dest, dest);
   }
+  else if ((destptr = cupsdFindDest(job->dest)) == NULL)
+  {
+    cupsdLogMessage(CUPSD_LOG_ERROR,
+                   "[Job %d] Unable to queue job for destination \"%s\"!",
+                   job->id, job->dest);
+    ippDelete(job->attrs);
+    job->attrs = NULL;
+    unlink(jobfile);
+    return;
+  }
 
   job->sheets     = ippFindAttribute(job->attrs, "job-media-sheets-completed",
                                      IPP_TAG_INTEGER);
@@ -949,8 +1087,8 @@ cupsdLoadJob(cupsd_job_t *job)             /* I - Job */
                                 IPP_TAG_INTEGER)) == NULL)
     {
       cupsdLogMessage(CUPSD_LOG_ERROR,
-                     "Missing or bad job-priority attribute in control "
-                     "file \"%s\"!", jobfile);
+                     "[Job %d] Missing or bad job-priority attribute in "
+                     "control file!", job->id);
       ippDelete(job->attrs);
       job->attrs = NULL;
       unlink(jobfile);
@@ -966,8 +1104,8 @@ cupsdLoadJob(cupsd_job_t *job)             /* I - Job */
                                 IPP_TAG_NAME)) == NULL)
     {
       cupsdLogMessage(CUPSD_LOG_ERROR,
-                     "Missing or bad job-originating-user-name attribute "
-                     "in control file \"%s\"!", jobfile);
+                     "[Job %d] Missing or bad job-originating-user-name "
+                     "attribute in control file!", job->id);
       ippDelete(job->attrs);
       job->attrs = NULL;
       unlink(jobfile);
@@ -1015,8 +1153,9 @@ cupsdLoadJob(cupsd_job_t *job)            /* I - Job */
       if (access(jobfile, 0))
         break;
 
-      cupsdLogMessage(CUPSD_LOG_DEBUG, "Auto-typing document file \"%s\"...",
-                      jobfile);
+      cupsdLogMessage(CUPSD_LOG_DEBUG,
+                      "[Job %d] Auto-typing document file \"%s\"...",
+                      job->id, jobfile);
 
       if (fileid > job->num_files)
       {
@@ -1037,7 +1176,8 @@ cupsdLoadJob(cupsd_job_t *job)            /* I - Job */
         if (!compressions || !filetypes)
        {
           cupsdLogMessage(CUPSD_LOG_ERROR,
-                         "Ran out of memory for job file types!");
+                         "[Job %d] Ran out of memory for job file types!",
+                         job->id);
          return;
        }
 
@@ -1055,6 +1195,45 @@ cupsdLoadJob(cupsd_job_t *job)           /* I - Job */
     }
   }
 
+ /*
+  * Load authentication information as needed...
+  */
+
+  if (job->state_value < IPP_JOB_STOPPED)
+  {
+    snprintf(jobfile, sizeof(jobfile), "%s/a%05d", RequestRoot, job->id);
+
+    cupsdClearString(&job->auth_username);
+    cupsdClearString(&job->auth_domain);
+    cupsdClearString(&job->auth_password);
+
+    if ((fp = cupsFileOpen(jobfile, "r")) != NULL)
+    {
+      int      i,                      /* Looping var */
+               bytes;                  /* Size of auth data */
+      char     line[255],              /* Line from file */
+               data[255];              /* Decoded data */
+
+
+      for (i = 0;
+           i < destptr->num_auth_info_required &&
+              cupsFileGets(fp, line, sizeof(line));
+          i ++)
+      {
+        bytes = sizeof(data);
+        httpDecode64_2(data, &bytes, line);
+
+       if (!strcmp(destptr->auth_info_required[i], "username"))
+         cupsdSetStringf(&job->auth_username, "AUTH_USERNAME=%s", data);
+       else if (!strcmp(destptr->auth_info_required[i], "domain"))
+         cupsdSetStringf(&job->auth_domain, "AUTH_DOMAIN=%s", data);
+       else if (!strcmp(destptr->auth_info_required[i], "password"))
+         cupsdSetStringf(&job->auth_password, "AUTH_PASSWORD=%s", data);
+      }
+
+      cupsFileClose(fp);
+    }
+  }
   job->access_time = time(NULL);
 }
 
@@ -1064,34 +1243,46 @@ cupsdLoadJob(cupsd_job_t *job)          /* I - Job */
  */
 
 void
-cupsdMoveJob(cupsd_job_t *job,         /* I - Job */
-             const char  *dest)                /* I - Destination */
+cupsdMoveJob(cupsd_job_t     *job,     /* I - Job */
+             cupsd_printer_t *p)       /* I - Destination printer or class */
 {
   ipp_attribute_t      *attr;          /* job-printer-uri attribute */
-  cupsd_printer_t      *p;             /* Destination printer or class */
+  const char           *olddest;       /* Old destination */
+  cupsd_printer_t      *oldp;          /* Old pointer */
 
 
  /*
-  * Find the printer...
+  * Don't move completed jobs...
   */
 
-  if ((p = cupsdFindDest(dest)) == NULL)
+  if (job->state_value > IPP_JOB_STOPPED)
     return;
 
  /*
-  * Don't move completed jobs...
+  * Get the old destination...
   */
 
-  if (job->state_value >= IPP_JOB_PROCESSING)
-    return;
+  olddest = job->dest;
+
+  if (job->printer)
+    oldp = job->printer;
+  else
+    oldp = cupsdFindDest(olddest);
 
  /*
   * Change the destination information...
   */
 
-  cupsdLoadJob(job);
+  if (job->state_value == IPP_JOB_PROCESSING)
+    cupsdStopJob(job, 0);
+  else
+    cupsdLoadJob(job);
 
-  cupsdSetString(&job->dest, dest);
+  cupsdAddEvent(CUPSD_EVENT_JOB_STOPPED, oldp, job,
+                "Job #%d moved from %s to %s.", job->id, olddest,
+               p->name);
+
+  cupsdSetString(&job->dest, p->name);
   job->dtype = p->type & (CUPS_PRINTER_CLASS | CUPS_PRINTER_REMOTE |
                           CUPS_PRINTER_IMPLICIT);
 
@@ -1099,6 +1290,10 @@ cupsdMoveJob(cupsd_job_t *job,           /* I - Job */
                                IPP_TAG_URI)) != NULL)
     cupsdSetString(&(attr->values[0].string.text), p->uri);
 
+  cupsdAddEvent(CUPSD_EVENT_JOB_STOPPED, p, job,
+                "Job #%d moved from %s to %s.", job->id, olddest,
+               p->name);
+
   cupsdSaveJob(job);
 }
 
@@ -1135,12 +1330,22 @@ cupsdRestartJob(cupsd_job_t *job)       /* I - Job */
 
   if (job->state_value == IPP_JOB_STOPPED || job->num_files)
   {
+    ipp_jstate_t       old_state;      /* Old job state */
+
+
     cupsdLoadJob(job);
 
+    old_state = job->state_value;
+
     job->tries = 0;
     job->state->values[0].integer = IPP_JOB_PENDING;
     job->state_value              = IPP_JOB_PENDING;
+
     cupsdSaveJob(job);
+
+    if (old_state > IPP_JOB_STOPPED)
+      cupsArrayAdd(ActiveJobs, job);
+
     cupsdCheckJobs();
   }
 }
@@ -1235,8 +1440,8 @@ cupsdSaveJob(cupsd_job_t *job)            /* I - Job */
   if ((fp = cupsFileOpen(filename, "w")) == NULL)
   {
     cupsdLogMessage(CUPSD_LOG_ERROR,
-                    "Unable to create job control file \"%s\" - %s.",
-                    filename, strerror(errno));
+                    "[Job %d] Unable to create job control file \"%s\" - %s.",
+                    job->id, filename, strerror(errno));
     return;
   }
 
@@ -1247,8 +1452,8 @@ cupsdSaveJob(cupsd_job_t *job)            /* I - Job */
 
   if (ippWriteIO(fp, (ipp_iocb_t)cupsFileWrite, 1, NULL,
                  job->attrs) != IPP_DATA)
-    cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to write job control file \"%s\"!",
-                   filename);
+    cupsdLogMessage(CUPSD_LOG_ERROR,
+                    "[Job %d] Unable to write job control file!", job->id);
 
   cupsFileClose(fp);
 }
@@ -1274,7 +1479,7 @@ cupsdSetJobHoldUntil(cupsd_job_t *job,    /* I - Job */
 
   second = 0;
 
-  if (!strcmp(when, "indefinite") || !strcmp(when, "authenticated"))
+  if (!strcmp(when, "indefinite") || !strcmp(when, "auth-info-required"))
   {
    /*
     * Hold indefinitely...
@@ -1298,7 +1503,7 @@ cupsdSetJobHoldUntil(cupsd_job_t *job,    /* I - Job */
                         ((29 - curdate->tm_hour) * 60 + 59 -
                         curdate->tm_min) * 60 + 60 - curdate->tm_sec;
   }
-  else if (!strcmp(when, "evening") || strcmp(when, "night"))
+  else if (!strcmp(when, "evening") || !strcmp(when, "night"))
   {
    /*
     * Hold to 6pm unless local time is > 6pm or < 6am.
@@ -1313,7 +1518,7 @@ cupsdSetJobHoldUntil(cupsd_job_t *job,    /* I - Job */
       job->hold_until = curtime +
                         ((17 - curdate->tm_hour) * 60 + 59 -
                         curdate->tm_min) * 60 + 60 - curdate->tm_sec;
-  }  
+  }
   else if (!strcmp(when, "second-shift"))
   {
    /*
@@ -1329,7 +1534,7 @@ cupsdSetJobHoldUntil(cupsd_job_t *job,    /* I - Job */
       job->hold_until = curtime +
                         ((15 - curdate->tm_hour) * 60 + 59 -
                         curdate->tm_min) * 60 + 60 - curdate->tm_sec;
-  }  
+  }
   else if (!strcmp(when, "third-shift"))
   {
    /*
@@ -1345,7 +1550,7 @@ cupsdSetJobHoldUntil(cupsd_job_t *job,    /* I - Job */
       job->hold_until = curtime +
                         ((23 - curdate->tm_hour) * 60 + 59 -
                         curdate->tm_min) * 60 + 60 - curdate->tm_sec;
-  }  
+  }
   else if (!strcmp(when, "weekend"))
   {
    /*
@@ -1381,7 +1586,7 @@ cupsdSetJobHoldUntil(cupsd_job_t *job,    /* I - Job */
     */
 
     if (job->hold_until < curtime)
-      job->hold_until += 24 * 60 * 60 * 60;
+      job->hold_until += 24 * 60 * 60;
   }
 
   cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdSetJobHoldUntil: hold_until = %d",
@@ -1431,1998 +1636,2157 @@ cupsdSetJobPriority(
 
 
 /*
- * 'cupsdStartJob()' - Start a print job.
+ * 'cupsdStopAllJobs()' - Stop all print jobs.
  */
 
 void
-cupsdStartJob(cupsd_job_t     *job,    /* I - Job ID */
-              cupsd_printer_t *printer)        /* I - Printer to print job */
+cupsdStopAllJobs(int force)            /* I - 1 = Force all filters to stop */
 {
-  int                  i;              /* Looping var */
-  int                  slot;           /* Pipe slot */
-  cups_array_t         *filters;       /* Filters for job */
-  mime_filter_t                *filter,        /* Current filter */
-                       port_monitor;   /* Port monitor filter */
-  char                 method[255],    /* Method for output */
-                       *optptr,        /* Pointer to options */
-                       *valptr;        /* Pointer in value string */
-  ipp_attribute_t      *attr;          /* Current attribute */
-  struct stat          backinfo;       /* Backend file information */
-  int                  backroot;       /* Run backend as root? */
-  int                  pid;            /* Process ID of new filter process */
-  int                  banner_page;    /* 1 if banner page, 0 otherwise */
-  int                  statusfds[2],   /* Pipes used with the scheduler */
-                       filterfds[2][2];/* Pipes used between filters */
-  int                  envc;           /* Number of environment variables */
-  char                 **argv,         /* Filter command-line arguments */
-                       sani_uri[1024], /* Sanitized DEVICE_URI env var */
-                       filename[1024], /* Job filename */
-                       command[1024],  /* Full path to command */
-                       jobid[255],     /* Job ID string */
-                       title[IPP_MAX_NAME],
-                                       /* Job title string */
-                       copies[255],    /* # copies string */
-                       *envp[MAX_ENV + 11],
-                                       /* Environment variables */
-                       charset[255],   /* CHARSET env variable */
-                       class_name[255],/* CLASS env variable */
-                       classification[1024],
-                                       /* CLASSIFICATION env variable */
-                       content_type[1024],
-                                       /* CONTENT_TYPE env variable */
-                       device_uri[1024],
-                                       /* DEVICE_URI env variable */
-                       final_content_type[1024],
-                                       /* FINAL_CONTENT_TYPE env variable */
-                       lang[255],      /* LANG env variable */
-                       ppd[1024],      /* PPD env variable */
-                       printer_name[255],
-                                       /* PRINTER env variable */
-                       rip_max_cache[255];
-                                       /* RIP_MAX_CACHE env variable */
-  int                  remote_job;     /* Remote print job? */
-  static char          *options = NULL;/* Full list of options */
-  static int           optlength = 0;  /* Length of option buffer */
-
+  cupsd_job_t  *job;                   /* Current job */
 
-  cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdStartJob: id = %d, file = %d/%d",
-                  job->id, job->current_file, job->num_files);
 
-  if (job->num_files == 0)
-  {
-    cupsdLogMessage(CUPSD_LOG_ERROR, "Job ID %d has no files!  Cancelling it!",
-                    job->id);
+  DEBUG_puts("cupsdStopAllJobs()");
 
-    cupsdAddEvent(CUPSD_EVENT_JOB_COMPLETED, job->printer, job,
-                  "Job canceled because it has no files.");
+  for (job = (cupsd_job_t *)cupsArrayFirst(ActiveJobs);
+       job;
+       job = (cupsd_job_t *)cupsArrayNext(ActiveJobs))
+    if (job->state_value == IPP_JOB_PROCESSING)
+    {
+      cupsdStopJob(job, force);
+      job->state->values[0].integer = IPP_JOB_PENDING;
+      job->state_value              = IPP_JOB_PENDING;
+    }
+}
 
-    cupsdCancelJob(job, 0);
-    return;
-  }
 
- /*
-  * Figure out what filters are required to convert from
-  * the source to the destination type...
-  */
+/*
+ * 'cupsdStopJob()' - Stop a print job.
+ */
 
-  filters   = NULL;
-  job->cost = 0;
+void
+cupsdStopJob(cupsd_job_t *job,         /* I - Job */
+             int         force)                /* I - 1 = Force all filters to stop */
+{
+  int  i;                              /* Looping var */
 
-  if (printer->raw)
-  {
-   /*
-    * Remote jobs and raw queues go directly to the printer without
-    * filtering...
-    */
 
-    cupsdLogMessage(CUPSD_LOG_DEBUG,
-                    "[Job %d] Sending job to queue tagged as raw...", job->id);
+  cupsdLogMessage(CUPSD_LOG_DEBUG2,
+                  "[Job %d] cupsdStopJob: force = %d", job->id, force);
 
-    filters = NULL;
-  }
-  else
-  {
-   /*
-    * Local jobs get filtered...
-    */
+  if (job->state_value != IPP_JOB_PROCESSING)
+    return;
 
-    filters = mimeFilter(MimeDatabase, job->filetypes[job->current_file],
-                         printer->filetype, &(job->cost));
+  FilterLevel -= job->cost;
 
-    if (!filters)
-    {
-      cupsdLogMessage(CUPSD_LOG_ERROR,
-                      "Unable to convert file %d to printable format for "
-                     "job %d!",
-                     job->current_file, job->id);
-      cupsdLogMessage(CUPSD_LOG_INFO,
-                      "Hint: Do you have ESP Ghostscript installed?");
+  if (job->printer->state == IPP_PRINTER_PROCESSING)
+    cupsdSetPrinterState(job->printer, IPP_PRINTER_IDLE, 0);
 
-      if (LogLevel < CUPSD_LOG_DEBUG)
-        cupsdLogMessage(CUPSD_LOG_INFO,
-                       "Hint: Try setting the LogLevel to \"debug\".");
+  job->state->values[0].integer = IPP_JOB_STOPPED;
+  job->state_value              = IPP_JOB_STOPPED;
+  job->printer->job = NULL;
+  job->printer      = NULL;
 
-      job->current_file ++;
+  job->current_file --;
 
-      if (job->current_file == job->num_files)
-      {
-       cupsdAddEvent(CUPSD_EVENT_JOB_COMPLETED, job->printer, job,
-                      "Job canceled because it has no files that can be "
-                     "printed.");
+  for (i = 0; job->filters[i]; i ++)
+    if (job->filters[i] > 0)
+    {
+      cupsdEndProcess(job->filters[i], force);
+      job->filters[i] = 0;
+    }
 
-        cupsdCancelJob(job, 0);
-      }
+  if (job->backend > 0)
+  {
+    cupsdEndProcess(job->backend, force);
+    job->backend = 0;
+  }
 
-      return;
-    }
+  cupsdLogMessage(CUPSD_LOG_DEBUG2, "[Job %d] Closing print pipes [ %d %d ]...",
+                  job->id, job->print_pipes[0], job->print_pipes[1]);
 
-   /*
-    * Remove NULL ("-") filters...
-    */
+  cupsdClosePipe(job->print_pipes);
 
-    for (filter = (mime_filter_t *)cupsArrayFirst(filters);
-         filter;
-        filter = (mime_filter_t *)cupsArrayNext(filters))
-      if (!strcmp(filter->filter, "-"))
-        cupsArrayRemove(filters, filter);
+  cupsdLogMessage(CUPSD_LOG_DEBUG2, "[Job %d] Closing back pipes [ %d %d ]...",
+                  job->id, job->back_pipes[0], job->back_pipes[1]);
 
-    if (cupsArrayCount(filters) == 0)
-    {
-      cupsArrayDelete(filters);
-      filters = NULL;
-    }
-  }
+  cupsdClosePipe(job->back_pipes);
 
- /*
-  * See if the filter cost is too high...
-  */
+  cupsdLogMessage(CUPSD_LOG_DEBUG2, "[Job %d] Closing side pipes [ %d %d ]...",
+                  job->id, job->side_pipes[0], job->side_pipes[1]);
 
-  if ((FilterLevel + job->cost) > FilterLimit && FilterLevel > 0 &&
-      FilterLimit > 0)
+  cupsdClosePipe(job->side_pipes);
+
+  if (job->status_buffer)
   {
    /*
-    * Don't print this job quite yet...
+    * Close the pipe and clear the input bit.
     */
 
-    cupsArrayDelete(filters);
+    cupsdRemoveSelect(job->status_buffer->fd);
 
-    cupsdLogMessage(CUPSD_LOG_INFO,
-                    "Holding job %d because filter limit has been reached.",
-                    job->id);
     cupsdLogMessage(CUPSD_LOG_DEBUG2,
-                    "cupsdStartJob: id=%d, file=%d, cost=%d, level=%d, "
-                   "limit=%d",
-                    job->id, job->current_file, job->cost, FilterLevel,
-                   FilterLimit);
-    return;
-  }
+                    "[Job %d] Closing status pipes [ %d %d ]...", job->id,
+                    job->status_pipes[0], job->status_pipes[1]);
 
-  FilterLevel += job->cost;
-
- /*
-  * Determine if we are printing to a remote printer...
-  */
-
-  remote_job = printer->raw && job->num_files > 1 &&
-               !strncmp(printer->device_uri, "ipp://", 6);
+    cupsdClosePipe(job->status_pipes);
+    cupsdStatBufDelete(job->status_buffer);
 
- /*
-  * Add decompression filters, if any...
-  */
+    job->status_buffer = NULL;
+  }
+}
 
-  if (!remote_job && job->compressions[job->current_file])
-  {
-   /*
-    * Add gziptoany filter to the front of the list...
-    */
 
-    if (!cupsArrayInsert(filters, &gziptoany_filter))
-    {
-      cupsdLogMessage(CUPSD_LOG_ERROR,
-                      "Unable to add decompression filter - %s",
-                     strerror(errno));
+/*
+ * 'cupsdUnloadCompletedJobs()' - Flush completed job history from memory.
+ */
 
-      cupsArrayDelete(filters);
+void
+cupsdUnloadCompletedJobs(void)
+{
+  cupsd_job_t  *job;                   /* Current job */
+  time_t       expire;                 /* Expiration time */
 
-      job->current_file ++;
 
-      if (job->current_file == job->num_files)
-      {
-       cupsdAddEvent(CUPSD_EVENT_JOB_COMPLETED, job->printer, job,
-                      "Job canceled because the print file could not be "
-                     "decompressed.");
+  expire = time(NULL) - 60;
 
-        cupsdCancelJob(job, 0);
-      }
+  for (job = (cupsd_job_t *)cupsArrayFirst(Jobs);
+       job;
+       job = (cupsd_job_t *)cupsArrayNext(Jobs))
+    if (job->attrs && job->state_value >= IPP_JOB_STOPPED &&
+        job->access_time < expire)
+      unload_job(job);
+}
 
-      return;
-    }
-  }
 
- /*
 * Add port monitor, if any...
 */
+/*
* 'compare_active_jobs()' - Compare the job IDs and priorities of two jobs.
+ */
 
-  if (printer->port_monitor)
-  {
-   /*
-    * Add port monitor to the end of the list...
-    */
+static int                             /* O - Difference */
+compare_active_jobs(void *first,       /* I - First job */
+                    void *second,      /* I - Second job */
+                   void *data)         /* I - App data (not used) */
+{
+  int  diff;                           /* Difference */
 
-    if (!cupsArrayAdd(filters, &port_monitor))
-    {
-      cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to add port monitor - %s",
-                      strerror(errno));
 
-      cupsArrayDelete(filters);
+  if ((diff = ((cupsd_job_t *)second)->priority -
+              ((cupsd_job_t *)first)->priority) != 0)
+    return (diff);
+  else
+    return (((cupsd_job_t *)first)->id - ((cupsd_job_t *)second)->id);
+}
 
-      job->current_file ++;
 
-      if (job->current_file == job->num_files)
-      {
-       cupsdAddEvent(CUPSD_EVENT_JOB_COMPLETED, job->printer, job,
-                      "Job canceled because the port monitor could not be "
-                     "added.");
+/*
+ * 'compare_jobs()' - Compare the job IDs of two jobs.
+ */
 
-        cupsdCancelJob(job, 0);
-      }
+static int                             /* O - Difference */
+compare_jobs(void *first,              /* I - First job */
+             void *second,             /* I - Second job */
+            void *data)                /* I - App data (not used) */
+{
+  return (((cupsd_job_t *)first)->id - ((cupsd_job_t *)second)->id);
+}
 
-      return;
-    }
 
-    snprintf(port_monitor.filter, sizeof(port_monitor.filter),
-             "%s/monitor/%s", ServerBin, printer->port_monitor);
-  }
+/*
+ * 'free_job()' - Free all memory used by a job.
+ */
 
+static void
+free_job(cupsd_job_t *job)             /* I - Job */
+{
+  cupsdClearString(&job->username);
+  cupsdClearString(&job->dest);
+  cupsdClearString(&job->auth_username);
+  cupsdClearString(&job->auth_domain);
+  cupsdClearString(&job->auth_password);
+#ifdef HAVE_GSSAPI
  /*
-  * Update the printer and job state to "processing"...
+  * Destroy the credential cache and clear the KRB5CCNAME env var string.
   */
 
-  job->state->values[0].integer = IPP_JOB_PROCESSING;
-  job->state_value              = IPP_JOB_PROCESSING;
-  job->status  = 0;
-  job->printer = printer;
-  printer->job = job;
-  cupsdSetPrinterState(printer, IPP_PRINTER_PROCESSING, 0);
-
-  if (job->current_file == 0)
+  if (job->ccache)
   {
-    set_time(job, "time-at-processing");
-    cupsdOpenPipe(job->back_pipes);
+    krb5_cc_destroy(KerberosContext, job->ccache);
+    job->ccache = NULL;
   }
 
- /*
-  * Determine if we are printing a banner page or not...
-  */
+  cupsdClearString(&job->ccname);
+#endif /* HAVE_GSSAPI */
 
-  if (job->job_sheets == NULL)
+  if (job->num_files > 0)
   {
-    cupsdLogMessage(CUPSD_LOG_DEBUG, "No job-sheets attribute.");
-    if ((job->job_sheets =
-         ippFindAttribute(job->attrs, "job-sheets", IPP_TAG_ZERO)) != NULL)
-      cupsdLogMessage(CUPSD_LOG_DEBUG,
-                      "... but someone added one without setting job_sheets!");
+    free(job->compressions);
+    free(job->filetypes);
   }
-  else if (job->job_sheets->num_values == 1)
-    cupsdLogMessage(CUPSD_LOG_DEBUG, "job-sheets=%s",
-               job->job_sheets->values[0].string.text);
-  else
-    cupsdLogMessage(CUPSD_LOG_DEBUG, "job-sheets=%s,%s",
-               job->job_sheets->values[0].string.text,
-               job->job_sheets->values[1].string.text);
 
-  if (printer->type & (CUPS_PRINTER_REMOTE | CUPS_PRINTER_IMPLICIT))
-    banner_page = 0;
-  else if (job->job_sheets == NULL)
-    banner_page = 0;
-  else if (strcasecmp(job->job_sheets->values[0].string.text, "none") != 0 &&
-          job->current_file == 0)
-    banner_page = 1;
-  else if (job->job_sheets->num_values > 1 &&
-          strcasecmp(job->job_sheets->values[1].string.text, "none") != 0 &&
-          job->current_file == (job->num_files - 1))
-    banner_page = 1;
-  else
-    banner_page = 0;
+  ippDelete(job->attrs);
+
+  free(job);
+}
+
+
+/*
+ * 'ipp_length()' - Compute the size of the buffer needed to hold
+ *                 the textual IPP attributes.
+ */
+
+static int                             /* O - Size of attribute buffer */
+ipp_length(ipp_t *ipp)                 /* I - IPP request */
+{
+  int                  bytes;          /* Number of bytes */
+  int                  i;              /* Looping var */
+  ipp_attribute_t      *attr;          /* Current attribute */
 
-  cupsdLogMessage(CUPSD_LOG_DEBUG, "banner_page = %d", banner_page);
 
  /*
-  * Building the options string is harder than it needs to be, but
-  * for the moment we need to pass strings for command-line args and
-  * not IPP attribute pointers... :)
-  *
-  * First allocate/reallocate the option buffer as needed...
+  * Loop through all attributes...
   */
 
-  i = ipp_length(job->attrs);
+  bytes = 0;
 
-  if (i > optlength)
+  for (attr = ipp->attrs; attr != NULL; attr = attr->next)
   {
-    if (optlength == 0)
-      optptr = malloc(i);
-    else
-      optptr = realloc(options, i);
+   /*
+    * Skip attributes that won't be sent to filters...
+    */
 
-    if (optptr == NULL)
-    {
-      cupsdLogMessage(CUPSD_LOG_CRIT,
-                      "Unable to allocate %d bytes for option buffer for "
-                     "job %d!", i, job->id);
+    if (attr->value_tag == IPP_TAG_MIMETYPE ||
+       attr->value_tag == IPP_TAG_NAMELANG ||
+       attr->value_tag == IPP_TAG_TEXTLANG ||
+       attr->value_tag == IPP_TAG_URI ||
+       attr->value_tag == IPP_TAG_URISCHEME)
+      continue;
 
-      cupsArrayDelete(filters);
+    if (strncmp(attr->name, "time-", 5) == 0)
+      continue;
 
-      FilterLevel -= job->cost;
+   /*
+    * Add space for a leading space and commas between each value.
+    * For the first attribute, the leading space isn't used, so the
+    * extra byte can be used as the nul terminator...
+    */
 
-      cupsdAddEvent(CUPSD_EVENT_JOB_COMPLETED, job->printer, job,
-                    "Job canceled because the server ran out of memory.");
+    bytes ++;                          /* " " separator */
+    bytes += attr->num_values;         /* "," separators */
 
-      cupsdCancelJob(job, 0);
-      return;
-    }
+   /*
+    * Boolean attributes appear as "foo,nofoo,foo,nofoo", while
+    * other attributes appear as "foo=value1,value2,...,valueN".
+    */
 
-    options   = optptr;
-    optlength = i;
-  }
+    if (attr->value_tag != IPP_TAG_BOOLEAN)
+      bytes += strlen(attr->name);
+    else
+      bytes += attr->num_values * strlen(attr->name);
 
- /*
-  * Now loop through the attributes and convert them to the textual
-  * representation used by the filters...
-  */
-
-  optptr  = options;
-  *optptr = '\0';
-
-  snprintf(title, sizeof(title), "%s-%d", printer->name, job->id);
-  strcpy(copies, "1");
-
-  for (attr = job->attrs->attrs; attr != NULL; attr = attr->next)
-  {
-    if (!strcmp(attr->name, "copies") &&
-       attr->value_tag == IPP_TAG_INTEGER)
-    {
-     /*
-      * Don't use the # copies attribute if we are printing the job sheets...
-      */
+   /*
+    * Now add the size required for each value in the attribute...
+    */
 
-      if (!banner_page)
-        sprintf(copies, "%d", attr->values[0].integer);
-    }
-    else if (!strcmp(attr->name, "job-name") &&
-            (attr->value_tag == IPP_TAG_NAME ||
-             attr->value_tag == IPP_TAG_NAMELANG))
-      strlcpy(title, attr->values[0].string.text, sizeof(title));
-    else if (attr->group_tag == IPP_TAG_JOB)
+    switch (attr->value_tag)
     {
-     /*
-      * Filter out other unwanted attributes...
-      */
+      case IPP_TAG_INTEGER :
+      case IPP_TAG_ENUM :
+         /*
+         * Minimum value of a signed integer is -2147483647, or 11 digits.
+         */
 
-      if (attr->value_tag == IPP_TAG_MIMETYPE ||
-         attr->value_tag == IPP_TAG_NAMELANG ||
-         attr->value_tag == IPP_TAG_TEXTLANG ||
-         (attr->value_tag == IPP_TAG_URI && strcmp(attr->name, "job-uuid")) ||
-         attr->value_tag == IPP_TAG_URISCHEME ||
-         attr->value_tag == IPP_TAG_BEGIN_COLLECTION) /* Not yet supported */
-       continue;
+         bytes += attr->num_values * 11;
+         break;
 
-      if (!strncmp(attr->name, "time-", 5))
-       continue;
+      case IPP_TAG_BOOLEAN :
+         /*
+         * Add two bytes for each false ("no") value...
+         */
 
-      if (!strncmp(attr->name, "job-", 4) && strcmp(attr->name, "job-uuid") &&
-          !(printer->type & CUPS_PRINTER_REMOTE))
-       continue;
+          for (i = 0; i < attr->num_values; i ++)
+           if (!attr->values[i].boolean)
+             bytes += 2;
+         break;
 
-      if (!strncmp(attr->name, "job-", 4) &&
-          strcmp(attr->name, "job-uuid") &&
-          strcmp(attr->name, "job-billing") &&
-          strcmp(attr->name, "job-sheets") &&
-          strcmp(attr->name, "job-hold-until") &&
-         strcmp(attr->name, "job-priority"))
-       continue;
+      case IPP_TAG_RANGE :
+         /*
+         * A range is two signed integers separated by a hyphen, or
+         * 23 characters max.
+         */
 
-      if ((!strcmp(attr->name, "page-label") ||
-           !strcmp(attr->name, "page-border") ||
-           !strncmp(attr->name, "number-up", 9) ||
-          !strcmp(attr->name, "page-set") ||
-          !strcasecmp(attr->name, "AP_FIRSTPAGE_InputSlot") ||
-          !strcasecmp(attr->name, "AP_FIRSTPAGE_ManualFeed")) &&
-         banner_page)
-        continue;
+         bytes += attr->num_values * 23;
+         break;
 
-     /*
-      * Otherwise add them to the list...
-      */
+      case IPP_TAG_RESOLUTION :
+         /*
+         * A resolution is two signed integers separated by an "x" and
+         * suffixed by the units, or 26 characters max.
+         */
 
-      if (optptr > options)
-       strlcat(optptr, " ", optlength - (optptr - options));
+         bytes += attr->num_values * 26;
+         break;
 
-      if (attr->value_tag != IPP_TAG_BOOLEAN)
-      {
-       strlcat(optptr, attr->name, optlength - (optptr - options));
-       strlcat(optptr, "=", optlength - (optptr - options));
-      }
+      case IPP_TAG_STRING :
+      case IPP_TAG_TEXT :
+      case IPP_TAG_NAME :
+      case IPP_TAG_KEYWORD :
+      case IPP_TAG_CHARSET :
+      case IPP_TAG_LANGUAGE :
+      case IPP_TAG_URI :
+         /*
+         * Strings can contain characters that need quoting.  We need
+         * at least 2 * len + 2 characters to cover the quotes and
+         * any backslashes in the string.
+         */
 
-      for (i = 0; i < attr->num_values; i ++)
-      {
-       if (i)
-         strlcat(optptr, ",", optlength - (optptr - options));
+          for (i = 0; i < attr->num_values; i ++)
+           bytes += 2 * strlen(attr->values[i].string.text) + 2;
+         break;
 
-       optptr += strlen(optptr);
+       default :
+         break; /* anti-compiler-warning-code */
+    }
+  }
 
-       switch (attr->value_tag)
-       {
-         case IPP_TAG_INTEGER :
-         case IPP_TAG_ENUM :
-             snprintf(optptr, optlength - (optptr - options),
-                      "%d", attr->values[i].integer);
-             break;
+  return (bytes);
+}
 
-         case IPP_TAG_BOOLEAN :
-             if (!attr->values[i].boolean)
-               strlcat(optptr, "no", optlength - (optptr - options));
 
-         case IPP_TAG_NOVALUE :
-             strlcat(optptr, attr->name,
-                     optlength - (optptr - options));
-             break;
+/*
+ * 'load_job_cache()' - Load jobs from the job.cache file.
+ */
 
-         case IPP_TAG_RANGE :
-             if (attr->values[i].range.lower == attr->values[i].range.upper)
-               snprintf(optptr, optlength - (optptr - options) - 1,
-                        "%d", attr->values[i].range.lower);
-              else
-               snprintf(optptr, optlength - (optptr - options) - 1,
-                        "%d-%d", attr->values[i].range.lower,
-                        attr->values[i].range.upper);
-             break;
+static void
+load_job_cache(const char *filename)   /* I - job.cache filename */
+{
+  cups_file_t  *fp;                    /* job.cache file */
+  char         line[1024],             /* Line buffer */
+               *value;                 /* Value on line */
+  int          linenum;                /* Line number in file */
+  cupsd_job_t  *job;                   /* Current job */
+  int          jobid;                  /* Job ID */
+  char         jobfile[1024];          /* Job filename */
 
-         case IPP_TAG_RESOLUTION :
-             snprintf(optptr, optlength - (optptr - options) - 1,
-                      "%dx%d%s", attr->values[i].resolution.xres,
-                      attr->values[i].resolution.yres,
-                      attr->values[i].resolution.units == IPP_RES_PER_INCH ?
-                          "dpi" : "dpc");
-             break;
 
-          case IPP_TAG_STRING :
-         case IPP_TAG_TEXT :
-         case IPP_TAG_NAME :
-         case IPP_TAG_KEYWORD :
-         case IPP_TAG_CHARSET :
-         case IPP_TAG_LANGUAGE :
-         case IPP_TAG_URI :
-             for (valptr = attr->values[i].string.text; *valptr;)
-             {
-               if (strchr(" \t\n\\\'\"", *valptr))
-                 *optptr++ = '\\';
-               *optptr++ = *valptr++;
-             }
+ /*
+  * Open the job.cache file...
+  */
 
-             *optptr = '\0';
-             break;
+  if ((fp = cupsFileOpen(filename, "r")) == NULL)
+  {
+    if (errno != ENOENT)
+      cupsdLogMessage(CUPSD_LOG_ERROR,
+                      "Unable to open job cache file \"%s\": %s",
+                      filename, strerror(errno));
 
-          default :
-             break; /* anti-compiler-warning-code */
-       }
-      }
+    load_request_root();
 
-      optptr += strlen(optptr);
-    }
+    return;
   }
 
  /*
-  * Build the command-line arguments for the filters.  Each filter
-  * has 6 or 7 arguments:
-  *
-  *     argv[0] = printer
-  *     argv[1] = job ID
-  *     argv[2] = username
-  *     argv[3] = title
-  *     argv[4] = # copies
-  *     argv[5] = options
-  *     argv[6] = filename (optional; normally stdin)
-  *
-  * This allows legacy printer drivers that use the old System V
-  * printing interface to be used by CUPS.
-  *
-  * For remote jobs, we send all of the files in the argument list.
+  * Read entries from the job cache file and create jobs as needed.
   */
 
-  if (remote_job)
-    argv = calloc(7 + job->num_files, sizeof(char *));
-  else
-    argv = calloc(8, sizeof(char *));
-
-  sprintf(jobid, "%d", job->id);
+  cupsdLogMessage(CUPSD_LOG_INFO, "Loading job cache file \"%s\"...",
+                  filename);
 
-  argv[0] = printer->name;
-  argv[1] = jobid;
-  argv[2] = job->username;
-  argv[3] = title;
-  argv[4] = copies;
-  argv[5] = options;
+  linenum = 0;
+  job     = NULL;
 
-  if (remote_job)
+  while (cupsFileGetConf(fp, line, sizeof(line), &value, &linenum))
   {
-    for (i = 0; i < job->num_files; i ++)
+    if (!strcasecmp(line, "NextJobId"))
     {
-      snprintf(filename, sizeof(filename), "%s/d%05d-%03d", RequestRoot,
-               job->id, i + 1);
-      argv[6 + i] = strdup(filename);
+      if (value)
+        NextJobId = atoi(value);
     }
-  }
-  else
-  {
-    snprintf(filename, sizeof(filename), "%s/d%05d-%03d", RequestRoot,
-             job->id, job->current_file + 1);
-    argv[6] = filename;
-  }
+    else if (!strcasecmp(line, "<Job"))
+    {
+      if (job)
+      {
+        cupsdLogMessage(CUPSD_LOG_ERROR, "Missing </Job> directive on line %d!",
+                       linenum);
+        continue;
+      }
 
-  for (i = 0; argv[i]; i ++)
-    cupsdLogMessage(CUPSD_LOG_DEBUG,
-                    "[Job %d] argv[%d]=\"%s\"", job->id, i, argv[i]);
+      if (!value)
+      {
+        cupsdLogMessage(CUPSD_LOG_ERROR, "Missing job ID on line %d!", linenum);
+       continue;
+      }
 
- /*
-  * Create environment variable strings for the filters...
-  */
+      jobid = atoi(value);
 
-  attr = ippFindAttribute(job->attrs, "attributes-natural-language",
-                          IPP_TAG_LANGUAGE);
+      if (jobid < 1)
+      {
+        cupsdLogMessage(CUPSD_LOG_ERROR, "Bad job ID %d on line %d!", jobid,
+                       linenum);
+        continue;
+      }
 
-  switch (strlen(attr->values[0].string.text))
-  {
-    default :
-       /*
-        * This is an unknown or badly formatted language code; use
-       * the POSIX locale...
-       */
+      snprintf(jobfile, sizeof(jobfile), "%s/c%05d", RequestRoot, jobid);
+      if (access(jobfile, 0))
+      {
+        cupsdLogMessage(CUPSD_LOG_ERROR, "[Job %d] Files have gone away!",
+                       jobid);
+        continue;
+      }
 
-       strcpy(lang, "LANG=C");
-       break;
+      job = calloc(1, sizeof(cupsd_job_t));
+      if (!job)
+      {
+        cupsdLogMessage(CUPSD_LOG_EMERG,
+                       "[Job %d] Unable to allocate memory for job!", jobid);
+        break;
+      }
 
-    case 2 :
-       /*
-        * Just the language code (ll)...
-       */
+      job->id              = jobid;
+      job->back_pipes[0]   = -1;
+      job->back_pipes[1]   = -1;
+      job->print_pipes[0]  = -1;
+      job->print_pipes[1]  = -1;
+      job->side_pipes[0]   = -1;
+      job->side_pipes[1]   = -1;
+      job->status_pipes[0] = -1;
+      job->status_pipes[1] = -1;
+
+      cupsdLogMessage(CUPSD_LOG_DEBUG, "[Job %d] Loading from cache...", job->id);
+    }
+    else if (!job)
+    {
+      cupsdLogMessage(CUPSD_LOG_ERROR,
+                     "Missing <Job #> directive on line %d!", linenum);
+      continue;
+    }
+    else if (!strcasecmp(line, "</Job>"))
+    {
+      cupsArrayAdd(Jobs, job);
+
+      if (job->state_value <= IPP_JOB_STOPPED)
+      {
+        cupsArrayAdd(ActiveJobs, job);
+       cupsdLoadJob(job);
+      }
+
+      job = NULL;
+    }
+    else if (!value)
+    {
+      cupsdLogMessage(CUPSD_LOG_ERROR, "Missing value on line %d!", linenum);
+      continue;
+    }
+    else if (!strcasecmp(line, "State"))
+    {
+      job->state_value = (ipp_jstate_t)atoi(value);
+
+      if (job->state_value < IPP_JOB_PENDING)
+        job->state_value = IPP_JOB_PENDING;
+      else if (job->state_value > IPP_JOB_COMPLETED)
+        job->state_value = IPP_JOB_COMPLETED;
+    }
+    else if (!strcasecmp(line, "Priority"))
+    {
+      job->priority = atoi(value);
+    }
+    else if (!strcasecmp(line, "Username"))
+    {
+      cupsdSetString(&job->username, value);
+    }
+    else if (!strcasecmp(line, "Destination"))
+    {
+      cupsdSetString(&job->dest, value);
+    }
+    else if (!strcasecmp(line, "DestType"))
+    {
+      job->dtype = (cups_ptype_t)atoi(value);
+    }
+    else if (!strcasecmp(line, "NumFiles"))
+    {
+      job->num_files = atoi(value);
+
+      if (job->num_files < 0)
+      {
+       cupsdLogMessage(CUPSD_LOG_ERROR, "Bad NumFiles value %d on line %d!",
+                       job->num_files, linenum);
+        job->num_files = 0;
+       continue;
+      }
+
+      if (job->num_files > 0)
+      {
+        snprintf(jobfile, sizeof(jobfile), "%s/d%05d-001", RequestRoot,
+                job->id);
+        if (access(jobfile, 0))
+       {
+         cupsdLogMessage(CUPSD_LOG_INFO,
+                         "[Job %d] Data files have gone away!", job->id);
+          job->num_files = 0;
+         continue;
+       }
+
+        job->filetypes    = calloc(job->num_files, sizeof(mime_type_t *));
+       job->compressions = calloc(job->num_files, sizeof(int));
+
+        if (!job->filetypes || !job->compressions)
+       {
+         cupsdLogMessage(CUPSD_LOG_EMERG,
+                         "[Job %d] Unable to allocate memory for %d files!",
+                         job->id, job->num_files);
+          break;
+       }
+      }
+    }
+    else if (!strcasecmp(line, "File"))
+    {
+      int      number,                 /* File number */
+               compression;            /* Compression value */
+      char     super[MIME_MAX_SUPER],  /* MIME super type */
+               type[MIME_MAX_TYPE];    /* MIME type */
+
+
+      if (sscanf(value, "%d%*[ \t]%15[^/]/%255s%d", &number, super, type,
+                 &compression) != 4)
+      {
+        cupsdLogMessage(CUPSD_LOG_ERROR, "Bad File on line %d!", linenum);
+       continue;
+      }
+
+      if (number < 1 || number > job->num_files)
+      {
+        cupsdLogMessage(CUPSD_LOG_ERROR, "Bad File number %d on line %d!",
+                       number, linenum);
+        continue;
+      }
 
-        snprintf(lang, sizeof(lang), "LANG=%s",
-                attr->values[0].string.text);
-        break;
+      number --;
 
-    case 5 :
+      job->compressions[number] = compression;
+      job->filetypes[number]    = mimeType(MimeDatabase, super, type);
+
+      if (!job->filetypes[number])
+      {
        /*
-        * Language and country code (ll-cc)...
+        * If the original MIME type is unknown, auto-type it!
        */
 
-        snprintf(lang, sizeof(lang), "LANG=%c%c_%c%c",
-                attr->values[0].string.text[0],
-                attr->values[0].string.text[1],
-                toupper(attr->values[0].string.text[3] & 255),
-                toupper(attr->values[0].string.text[4] & 255));
-        break;
-  }
-
-  attr = ippFindAttribute(job->attrs, "document-format",
-                          IPP_TAG_MIMETYPE);
-  if (attr != NULL &&
-      (optptr = strstr(attr->values[0].string.text, "charset=")) != NULL)
-    snprintf(charset, sizeof(charset), "CHARSET=%s", optptr + 8);
-  else
-  {
-    attr = ippFindAttribute(job->attrs, "attributes-charset",
-                           IPP_TAG_CHARSET);
-    snprintf(charset, sizeof(charset), "CHARSET=%s",
-             attr->values[0].string.text);
-  }
-
-  snprintf(content_type, sizeof(content_type), "CONTENT_TYPE=%s/%s",
-           job->filetypes[job->current_file]->super,
-           job->filetypes[job->current_file]->type);
-  snprintf(device_uri, sizeof(device_uri), "DEVICE_URI=%s",
-           printer->device_uri);
-  cupsdSanitizeURI(printer->device_uri, sani_uri, sizeof(sani_uri));
-  snprintf(ppd, sizeof(ppd), "PPD=%s/ppd/%s.ppd", ServerRoot, printer->name);
-  snprintf(printer_name, sizeof(printer_name), "PRINTER=%s", printer->name);
-  snprintf(rip_max_cache, sizeof(rip_max_cache), "RIP_MAX_CACHE=%s", RIPCache);
-
-  envc = cupsdLoadEnv(envp, (int)(sizeof(envp) / sizeof(envp[0])));
+        cupsdLogMessage(CUPSD_LOG_ERROR,
+                       "[Job %d] Unknown MIME type %s/%s for file %d!",
+                       job->id, super, type, number + 1);
 
-  envp[envc ++] = charset;
-  envp[envc ++] = lang;
-  envp[envc ++] = ppd;
-  envp[envc ++] = rip_max_cache;
-  envp[envc ++] = content_type;
-  envp[envc ++] = device_uri;
-  envp[envc ++] = printer_name;
+        snprintf(jobfile, sizeof(jobfile), "%s/d%05d-%03d", RequestRoot,
+                job->id, number + 1);
+        job->filetypes[number] = mimeFileType(MimeDatabase, jobfile, NULL,
+                                             job->compressions + number);
 
-  if ((filter = (mime_filter_t *)cupsArrayLast(filters)) != NULL)
-  {
-    snprintf(final_content_type, sizeof(final_content_type),
-             "FINAL_CONTENT_TYPE=%s/%s",
-            filter->dst->super, filter->dst->type);
-    envp[envc ++] = final_content_type;
-  }
+       /*
+        * If that didn't work, assume it is raw...
+       */
 
-  if (Classification && !banner_page)
-  {
-    if ((attr = ippFindAttribute(job->attrs, "job-sheets",
-                                 IPP_TAG_NAME)) == NULL)
-      snprintf(classification, sizeof(classification), "CLASSIFICATION=%s",
-               Classification);
-    else if (attr->num_values > 1 &&
-             strcmp(attr->values[1].string.text, "none") != 0)
-      snprintf(classification, sizeof(classification), "CLASSIFICATION=%s",
-               attr->values[1].string.text);
+        if (!job->filetypes[number])
+         job->filetypes[number] = mimeType(MimeDatabase, "application",
+                                           "vnd.cups-raw");
+      }
+    }
     else
-      snprintf(classification, sizeof(classification), "CLASSIFICATION=%s",
-               attr->values[0].string.text);
-
-    envp[envc ++] = classification;
+      cupsdLogMessage(CUPSD_LOG_ERROR, "Unknown %s directive on line %d!",
+                      line, linenum);
   }
 
-  if (job->dtype & (CUPS_PRINTER_CLASS | CUPS_PRINTER_IMPLICIT))
-  {
-    snprintf(class_name, sizeof(class_name), "CLASS=%s", job->dest);
-    envp[envc ++] = class_name;
-  }
+  cupsFileClose(fp);
+}
 
-  envp[envc] = NULL;
 
-  for (i = 0; i < envc; i ++)
-    if (strncmp(envp[i], "DEVICE_URI=", 11))
-      cupsdLogMessage(CUPSD_LOG_DEBUG, "[Job %d] envp[%d]=\"%s\"",
-                      job->id, i, envp[i]);
-    else
-      cupsdLogMessage(CUPSD_LOG_DEBUG, "[Job %d] envp[%d]=\"DEVICE_URI=%s\"",
-                      job->id, i, sani_uri);
+/*
+ * 'load_next_job_id()' - Load the NextJobId value from the job.cache file.
+ */
+
+static void
+load_next_job_id(const char *filename) /* I - job.cache filename */
+{
+  cups_file_t  *fp;                    /* job.cache file */
+  char         line[1024],             /* Line buffer */
+               *value;                 /* Value on line */
+  int          linenum;                /* Line number in file */
+  int          next_job_id;            /* NextJobId value from line */
 
-  if (remote_job)
-    job->current_file = job->num_files;
-  else
-    job->current_file ++;
 
  /*
-  * Now create processes for all of the filters...
+  * Read the NextJobId directive from the job.cache file and use
+  * the value (if any).
   */
 
-  if (cupsdOpenPipe(statusfds))
+  if ((fp = cupsFileOpen(filename, "r")) == NULL)
   {
-    cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to create job status pipes - %s.",
-                   strerror(errno));
-    snprintf(printer->state_message, sizeof(printer->state_message),
-             "Unable to create status pipes - %s.", strerror(errno));
+    if (errno != ENOENT)
+      cupsdLogMessage(CUPSD_LOG_ERROR,
+                      "Unable to open job cache file \"%s\": %s",
+                      filename, strerror(errno));
 
-    cupsdAddPrinterHistory(printer);
+    return;
+  }
 
-    cupsArrayDelete(filters);
+  cupsdLogMessage(CUPSD_LOG_INFO,
+                  "Loading NextJobId from job cache file \"%s\"...", filename);
 
-    cupsdAddEvent(CUPSD_EVENT_JOB_COMPLETED, job->printer, job,
-                  "Job canceled because the server could not create the job "
-                 "status pipes.");
+  linenum = 0;
 
-    if (remote_job)
+  while (cupsFileGetConf(fp, line, sizeof(line), &value, &linenum))
+  {
+    if (!strcasecmp(line, "NextJobId"))
     {
-      for (i = 0; i < job->num_files; i ++)
-        free(argv[i + 6]);
-    }
-
-    free(argv);
+      if (value)
+      {
+        next_job_id = atoi(value);
 
-    cupsdCancelJob(job, 0);
-    return;
+        if (next_job_id > NextJobId)
+         NextJobId = next_job_id;
+      }
+      break;
+    }
   }
 
-  cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdStartJob: statusfds = [ %d %d ]",
-                  statusfds[0], statusfds[1]);
-
-#ifdef FD_CLOEXEC
-  fcntl(statusfds[0], F_SETFD, FD_CLOEXEC);
-  fcntl(statusfds[1], F_SETFD, FD_CLOEXEC);
-#endif /* FD_CLOEXEC */
-
-  job->status_buffer = cupsdStatBufNew(statusfds[0], "[Job %d]",
-                                           job->id);
-  job->status        = 0;
-  memset(job->filters, 0, sizeof(job->filters));
-
-  filterfds[1][0] = open("/dev/null", O_RDONLY);
-  filterfds[1][1] = -1;
+  cupsFileClose(fp);
+}
 
-  if (filterfds[1][0] < 0)
-  {
-    cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to open \"/dev/null\" - %s.",
-                    strerror(errno));
-    snprintf(printer->state_message, sizeof(printer->state_message),
-             "Unable to open \"/dev/null\" - %s.", strerror(errno));
 
-    cupsdAddPrinterHistory(printer);
+/*
+ * 'load_request_root()' - Load jobs from the RequestRoot directory.
+ */
 
-    cupsArrayDelete(filters);
+static void
+load_request_root(void)
+{
+  cups_dir_t           *dir;           /* Directory */
+  cups_dentry_t                *dent;          /* Directory entry */
+  cupsd_job_t          *job;           /* New job */
 
-    cupsdClosePipe(statusfds);
 
-    if (remote_job)
-    {
-      for (i = 0; i < job->num_files; i ++)
-        free(argv[i + 6]);
-    }
+ /*
+  * Open the requests directory...
+  */
 
-    free(argv);
+  cupsdLogMessage(CUPSD_LOG_DEBUG, "Scanning %s for jobs...", RequestRoot);
 
-    cupsdCancelJob(job, 0);
+  if ((dir = cupsDirOpen(RequestRoot)) == NULL)
+  {
+    cupsdLogMessage(CUPSD_LOG_ERROR,
+                    "Unable to open spool directory \"%s\": %s",
+                    RequestRoot, strerror(errno));
     return;
   }
 
-  fcntl(filterfds[1][0], F_SETFD, fcntl(filterfds[1][0], F_GETFD) | FD_CLOEXEC);
-
-  cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdStartJob: filterfds[%d] = [ %d %d ]",
-                  1, filterfds[1][0], filterfds[1][1]);
-
-  for (i = 0, slot = 0, filter = (mime_filter_t *)cupsArrayFirst(filters);
-       filter;
-       i ++, filter = (mime_filter_t *)cupsArrayNext(filters))
-  {
-    if (filter->filter[0] != '/')
-      snprintf(command, sizeof(command), "%s/filter/%s", ServerBin,
-               filter->filter);
-    else
-      strlcpy(command, filter->filter, sizeof(command));
+ /*
+  * Read all the c##### files...
+  */
 
-    if (i < (cupsArrayCount(filters) - 1))
+  while ((dent = cupsDirRead(dir)) != NULL)
+    if (strlen(dent->filename) >= 6 && dent->filename[0] == 'c')
     {
-      if (cupsdOpenPipe(filterfds[slot]))
-      {
-       cupsdLogMessage(CUPSD_LOG_ERROR,
-                       "Unable to create job filter pipes - %s.",
-                       strerror(errno));
-       snprintf(printer->state_message, sizeof(printer->state_message),
-               "Unable to create filter pipes - %s.", strerror(errno));
-       cupsdAddPrinterHistory(printer);
-
-       cupsArrayDelete(filters);
-
-       cupsdClosePipe(statusfds);
-       cupsdClosePipe(filterfds[!slot]);
+     /*
+      * Allocate memory for the job...
+      */
 
-       cupsdAddEvent(CUPSD_EVENT_JOB_COMPLETED, job->printer, job,
-                      "Job canceled because the server could not create the "
-                     "filter pipes.");
+      if ((job = calloc(sizeof(cupsd_job_t), 1)) == NULL)
+      {
+        cupsdLogMessage(CUPSD_LOG_ERROR, "Ran out of memory for jobs!");
+       cupsDirClose(dir);
+       return;
+      }
 
-        if (remote_job)
-       {
-         for (i = 0; i < job->num_files; i ++)
-            free(argv[i + 6]);
-       }
+     /*
+      * Assign the job ID...
+      */
 
-       free(argv);
+      job->id              = atoi(dent->filename + 1);
+      job->back_pipes[0]   = -1;
+      job->back_pipes[1]   = -1;
+      job->print_pipes[0]  = -1;
+      job->print_pipes[1]  = -1;
+      job->side_pipes[0]   = -1;
+      job->side_pipes[1]   = -1;
+      job->status_pipes[0] = -1;
+      job->status_pipes[1] = -1;
 
-       cupsdCancelJob(job, 0);
-       return;
-      }
-    }
-    else
-    {
-      if (job->current_file == 1)
-      {
-       if (strncmp(printer->device_uri, "file:", 5) != 0)
-       {
-         if (cupsdOpenPipe(job->print_pipes))
-         {
-           cupsdLogMessage(CUPSD_LOG_ERROR,
-                           "Unable to create job backend pipes - %s.",
-                           strerror(errno));
-           snprintf(printer->state_message, sizeof(printer->state_message),
-                   "Unable to create backend pipes - %s.", strerror(errno));
-           cupsdAddPrinterHistory(printer);
+      if (job->id >= NextJobId)
+        NextJobId = job->id + 1;
 
-           cupsArrayDelete(filters);
+     /*
+      * Load the job...
+      */
 
-           cupsdClosePipe(statusfds);
-           cupsdClosePipe(filterfds[!slot]);
+      cupsdLoadJob(job);
 
-           cupsdAddEvent(CUPSD_EVENT_JOB_COMPLETED, job->printer, job,
-                         "Job canceled because the server could not create "
-                         "the backend pipes.");
+     /*
+      * Insert the job into the array, sorting by job priority and ID...
+      */
 
-            if (remote_job)
-           {
-             for (i = 0; i < job->num_files; i ++)
-               free(argv[i + 6]);
-           }
+      cupsArrayAdd(Jobs, job);
 
-           free(argv);
+      if (job->state_value <= IPP_JOB_STOPPED)
+        cupsArrayAdd(ActiveJobs, job);
+      else
+        unload_job(job);
+    }
 
-           cupsdCancelJob(job, 0);
-           return;
-         }
-       }
-       else
-       {
-         job->print_pipes[0] = -1;
-         if (!strncmp(printer->device_uri, "file:/dev/", 10) &&
-             strcmp(printer->device_uri, "file:/dev/null"))
-           job->print_pipes[1] = open(printer->device_uri + 5,
-                                      O_WRONLY | O_EXCL);
-         else if (!strncmp(printer->device_uri, "file:///dev/", 12) &&
-                  strcmp(printer->device_uri, "file:///dev/null"))
-           job->print_pipes[1] = open(printer->device_uri + 7,
-                                      O_WRONLY | O_EXCL);
-         else
-           job->print_pipes[1] = open(printer->device_uri + 5,
-                                      O_WRONLY | O_CREAT | O_TRUNC, 0600);
+  cupsDirClose(dir);
+}
 
-         if (job->print_pipes[1] < 0)
-         {
-            cupsdLogMessage(CUPSD_LOG_ERROR,
-                           "Unable to open output file \"%s\" - %s.",
-                           printer->device_uri, strerror(errno));
-            snprintf(printer->state_message, sizeof(printer->state_message),
-                    "Unable to open output file \"%s\" - %s.",
-                    printer->device_uri, strerror(errno));
 
-           cupsdAddPrinterHistory(printer);
+/*
+ * 'set_time()' - Set one of the "time-at-xyz" attributes...
+ */
 
-           cupsArrayDelete(filters);
+static void
+set_time(cupsd_job_t *job,             /* I - Job to update */
+         const char  *name)            /* I - Name of attribute */
+{
+  ipp_attribute_t      *attr;          /* Time attribute */
 
-           cupsdClosePipe(statusfds);
-           cupsdClosePipe(filterfds[!slot]);
 
-           cupsdAddEvent(CUPSD_EVENT_JOB_COMPLETED, job->printer, job,
-                         "Job canceled because the server could not open the "
-                         "output file.");
+  if ((attr = ippFindAttribute(job->attrs, name, IPP_TAG_ZERO)) != NULL)
+  {
+    attr->value_tag         = IPP_TAG_INTEGER;
+    attr->values[0].integer = time(NULL);
+  }
+}
 
-            if (remote_job)
-           {
-             for (i = 0; i < job->num_files; i ++)
-               free(argv[i + 6]);
-           }
 
-           free(argv);
+/*
+ * 'set_hold_until()' - Set the hold time and update job-hold-until attribute...
+ */
 
-           cupsdCancelJob(job, 0);
-           return;
-         }
+static void
+set_hold_until(cupsd_job_t *job,       /* I - Job to update */
+              time_t      holdtime)    /* I - Hold until time */
+{
+  ipp_attribute_t      *attr;          /* job-hold-until attribute */
+  struct tm            *holddate;      /* Hold date */
+  char                 holdstr[64];    /* Hold time */
 
-         fcntl(job->print_pipes[1], F_SETFD,
-               fcntl(job->print_pipes[1], F_GETFD) | FD_CLOEXEC);
-       }
 
-       cupsdLogMessage(CUPSD_LOG_DEBUG2,
-                       "cupsdStartJob: print_pipes = [ %d %d ]",
-                        job->print_pipes[0], job->print_pipes[1]);
-      }
+ /*
+  * Set the hold_until value and hold the job...
+  */
 
-      filterfds[slot][0] = job->print_pipes[0];
-      filterfds[slot][1] = job->print_pipes[1];
-    }
+  cupsdLogMessage(CUPSD_LOG_DEBUG, "set_hold_until: hold_until = %d",
+                  (int)holdtime);
 
-    cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdStartJob: filter=\"%s\"",
-                    command);
-    cupsdLogMessage(CUPSD_LOG_DEBUG2,
-                    "cupsdStartJob: filterfds[%d]=[ %d %d ]",
-                    slot, filterfds[slot][0], filterfds[slot][1]);
+  job->state->values[0].integer = IPP_JOB_HELD;
+  job->state_value              = IPP_JOB_HELD;
+  job->hold_until               = holdtime;
 
-    pid = cupsdStartProcess(command, argv, envp, filterfds[!slot][0],
-                            filterfds[slot][1], statusfds[1],
-                           job->back_pipes[0], 0, job->filters + i);
+ /*
+  * Update the job-hold-until attribute with a string representing GMT
+  * time (HH:MM:SS)...
+  */
 
-    cupsdLogMessage(CUPSD_LOG_DEBUG2,
-                    "cupsdStartJob: Closing filter pipes for slot %d "
-                   "[ %d %d ]...",
-                    !slot, filterfds[!slot][0], filterfds[!slot][1]);
+  holddate = gmtime(&holdtime);
+  snprintf(holdstr, sizeof(holdstr), "%d:%d:%d", holddate->tm_hour,
+          holddate->tm_min, holddate->tm_sec);
 
-    cupsdClosePipe(filterfds[!slot]);
+  if ((attr = ippFindAttribute(job->attrs, "job-hold-until",
+                               IPP_TAG_KEYWORD)) == NULL)
+    attr = ippFindAttribute(job->attrs, "job-hold-until", IPP_TAG_NAME);
 
-    if (pid == 0)
-    {
-      cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to start filter \"%s\" - %s.",
-                      filter->filter, strerror(errno));
-      snprintf(printer->state_message, sizeof(printer->state_message),
-               "Unable to start filter \"%s\" - %s.",
-               filter->filter, strerror(errno));
+ /*
+  * Either add the attribute or update the value of the existing one
+  */
 
-      cupsdAddPrinterHistory(printer);
+  if (attr == NULL)
+    attr = ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_KEYWORD,
+                        "job-hold-until", NULL, holdstr);
+  else
+    cupsdSetString(&attr->values[0].string.text, holdstr);
 
-      cupsArrayDelete(filters);
+  cupsdSaveJob(job);
+}
 
-      cupsdAddPrinterHistory(printer);
 
-      cupsdAddEvent(CUPSD_EVENT_JOB_COMPLETED, job->printer, job,
-                    "Job canceled because the server could not execute a "
-                   "filter.");
+/*
+ * 'start_job()' - Start a print job.
+ */
 
-      if (remote_job)
-      {
-       for (i = 0; i < job->num_files; i ++)
-          free(argv[i + 6]);
-      }
+static void
+start_job(cupsd_job_t     *job,                /* I - Job ID */
+          cupsd_printer_t *printer)    /* I - Printer to print job */
+{
+  int                  i;              /* Looping var */
+  int                  slot;           /* Pipe slot */
+  cups_array_t         *filters,       /* Filters for job */
+                       *prefilters;    /* Filters with prefilters */
+  mime_filter_t                *filter,        /* Current filter */
+                       *prefilter,     /* Prefilter */
+                       port_monitor;   /* Port monitor filter */
+  char                 method[255],    /* Method for output */
+                       *optptr,        /* Pointer to options */
+                       *valptr;        /* Pointer in value string */
+  ipp_attribute_t      *attr;          /* Current attribute */
+  struct stat          backinfo;       /* Backend file information */
+  int                  backroot;       /* Run backend as root? */
+  int                  pid;            /* Process ID of new filter process */
+  int                  banner_page;    /* 1 if banner page, 0 otherwise */
+  int                  filterfds[2][2];/* Pipes used between filters */
+  int                  envc;           /* Number of environment variables */
+  char                 **argv,         /* Filter command-line arguments */
+                       sani_uri[1024], /* Sanitized DEVICE_URI env var */
+                       filename[1024], /* Job filename */
+                       command[1024],  /* Full path to command */
+                       jobid[255],     /* Job ID string */
+                       title[IPP_MAX_NAME],
+                                       /* Job title string */
+                       copies[255],    /* # copies string */
+                       *envp[MAX_ENV + 15],
+                                       /* Environment variables */
+                       charset[255],   /* CHARSET env variable */
+                       class_name[255],/* CLASS env variable */
+                       classification[1024],
+                                       /* CLASSIFICATION env variable */
+                       content_type[1024],
+                                       /* CONTENT_TYPE env variable */
+                       device_uri[1024],
+                                       /* DEVICE_URI env variable */
+                       final_content_type[1024],
+                                       /* FINAL_CONTENT_TYPE env variable */
+                       lang[255],      /* LANG env variable */
+                       ppd[1024],      /* PPD env variable */
+                       printer_name[255],
+                                       /* PRINTER env variable */
+                       rip_max_cache[255];
+                                       /* RIP_MAX_CACHE env variable */
+  static char          *options = NULL;/* Full list of options */
+  static int           optlength = 0;  /* Length of option buffer */
 
-      free(argv);
 
-      cupsdCancelJob(job, 0);
-      return;
-    }
+  cupsdLogMessage(CUPSD_LOG_DEBUG2, "[Job %d] start_job: file = %d/%d",
+                  job->id, job->current_file, job->num_files);
 
-    cupsdLogMessage(CUPSD_LOG_INFO, "Started filter %s (PID %d) for job %d.",
-                    command, pid, job->id);
+  if (job->num_files == 0)
+  {
+    cupsdLogMessage(CUPSD_LOG_ERROR, "[Job %d] No files, canceling job!",
+                    job->id);
 
-    argv[6] = NULL;
-    slot    = !slot;
+    cupsdCancelJob(job, 0, IPP_JOB_ABORTED);
+    return;
   }
 
-  cupsArrayDelete(filters);
-
  /*
-  * Finally, pipe the final output into a backend process if needed...
+  * Figure out what filters are required to convert from
+  * the source to the destination type...
   */
 
-  if (strncmp(printer->device_uri, "file:", 5) != 0)
-  {
-    if (job->current_file == 1)
-    {
-      sscanf(printer->device_uri, "%254[^:]", method);
-      snprintf(command, sizeof(command), "%s/backend/%s", ServerBin, method);
+  filters   = NULL;
+  job->cost = 0;
 
-     /*
-      * See if the backend needs to run as root...
-      */
+  if (printer->raw)
+  {
+   /*
+    * Remote jobs and raw queues go directly to the printer without
+    * filtering...
+    */
 
-      if (RunUser)
-        backroot = 0;
-      else if (lstat(command, &backinfo))
-       backroot = 0;
-      else
-        backroot = !(backinfo.st_mode & (S_IRWXG | S_IRWXO));
+    cupsdLogMessage(CUPSD_LOG_DEBUG,
+                    "[Job %d] Sending job to queue tagged as raw...", job->id);
 
-      argv[0] = sani_uri;
+    filters = NULL;
+  }
+  else
+  {
+   /*
+    * Local jobs get filtered...
+    */
 
-      filterfds[slot][0] = -1;
-      filterfds[slot][1] = open("/dev/null", O_WRONLY);
+    filters = mimeFilter(MimeDatabase, job->filetypes[job->current_file],
+                         printer->filetype, &(job->cost));
 
-      if (filterfds[slot][1] < 0)
-      {
-       cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to open \"/dev/null\" - %s.",
-                       strerror(errno));
-       snprintf(printer->state_message, sizeof(printer->state_message),
-                "Unable to open \"/dev/null\" - %s.", strerror(errno));
+    if (!filters)
+    {
+      cupsdLogMessage(CUPSD_LOG_ERROR,
+                      "[Job %d] Unable to convert file %d to printable format!",
+                     job->current_file, job->id);
+      cupsdLogMessage(CUPSD_LOG_INFO,
+                      "Hint: Do you have ESP Ghostscript installed?");
 
-       cupsdAddPrinterHistory(printer);
+      if (LogLevel < CUPSD_LOG_DEBUG)
+        cupsdLogMessage(CUPSD_LOG_INFO,
+                       "Hint: Try setting the LogLevel to \"debug\".");
 
-       cupsdClosePipe(statusfds);
+      job->current_file ++;
 
-       cupsdAddEvent(CUPSD_EVENT_JOB_COMPLETED, job->printer, job,
-                      "Job canceled because the server could not open a file.");
+      if (job->current_file == job->num_files)
+        cupsdCancelJob(job, 0, IPP_JOB_ABORTED);
 
-        if (remote_job)
-       {
-         for (i = 0; i < job->num_files; i ++)
-            free(argv[i + 6]);
-       }
+      return;
+    }
 
-       free(argv);
+   /*
+    * Remove NULL ("-") filters...
+    */
 
-       cupsdCancelJob(job, 0);
-       return;
-      }
+    for (filter = (mime_filter_t *)cupsArrayFirst(filters);
+         filter;
+        filter = (mime_filter_t *)cupsArrayNext(filters))
+      if (!strcmp(filter->filter, "-"))
+        cupsArrayRemove(filters, filter);
 
-      fcntl(filterfds[slot][1], F_SETFD,
-            fcntl(filterfds[slot][1], F_GETFD) | FD_CLOEXEC);
+    if (cupsArrayCount(filters) == 0)
+    {
+      cupsArrayDelete(filters);
+      filters = NULL;
+    }
 
-      cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdStartJob: backend=\"%s\"",
-                      command);
-      cupsdLogMessage(CUPSD_LOG_DEBUG2,
-                      "cupsdStartJob: filterfds[%d] = [ %d %d ]",
-                     slot, filterfds[slot][0], filterfds[slot][1]);
+   /*
+    * If this printer has any pre-filters, insert the required pre-filter
+    * in the filters array...
+    */
 
-      pid = cupsdStartProcess(command, argv, envp, filterfds[!slot][0],
-                             filterfds[slot][1], statusfds[1],
-                             job->back_pipes[1], backroot,
-                             &(job->backend));
+    if (printer->prefiltertype && filters)
+    {
+      prefilters = cupsArrayNew(NULL, NULL);
 
-      if (pid == 0)
+      for (filter = (mime_filter_t *)cupsArrayFirst(filters);
+          filter;
+          filter = (mime_filter_t *)cupsArrayNext(filters))
       {
-       cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to start backend \"%s\" - %s.",
-                        method, strerror(errno));
-       snprintf(printer->state_message, sizeof(printer->state_message),
-                "Unable to start backend \"%s\" - %s.", method,
-                strerror(errno));
-
-       cupsdLogMessage(CUPSD_LOG_DEBUG2,
-                       "cupsdStartJob: Closing print pipes [ %d %d ]...",
-                       job->print_pipes[0], job->print_pipes[1]);
+       if ((prefilter = mimeFilterLookup(MimeDatabase, filter->src,
+                                         printer->prefiltertype)))
+       {
+         cupsArrayAdd(prefilters, prefilter);
+         job->cost += prefilter->cost;
+       }
 
-        cupsdClosePipe(job->print_pipes);
+       cupsArrayAdd(prefilters, filter);
+      }
 
-       cupsdLogMessage(CUPSD_LOG_DEBUG2,
-                       "cupsdStartJob: Closing back pipes [ %d %d ]...",
-                       job->back_pipes[0], job->back_pipes[1]);
+      cupsArrayDelete(filters);
+      filters = prefilters;
+    }
+  }
 
-        cupsdClosePipe(job->back_pipes);
+ /*
+  * Set a minimum cost of 100 for all jobs so that FilterLimit
+  * works with raw queues and other low-cost paths.
+  */
 
-       cupsdAddEvent(CUPSD_EVENT_JOB_COMPLETED, job->printer, job,
-                      "Job canceled because the server could not execute "
-                     "the backend.");
+  if (job->cost < 100)
+    job->cost = 100;
 
-        if (remote_job)
-       {
-         for (i = 0; i < job->num_files; i ++)
-            free(argv[i + 6]);
-       }
+ /*
+  * See if the filter cost is too high...
+  */
 
-       free(argv);
+  if ((FilterLevel + job->cost) > FilterLimit && FilterLevel > 0 &&
+      FilterLimit > 0)
+  {
+   /*
+    * Don't print this job quite yet...
+    */
 
-        cupsdCancelJob(job, 0);
-       return;
-      }
-      else
-      {
-       cupsdLogMessage(CUPSD_LOG_INFO,
-                       "Started backend %s (PID %d) for job %d.",
-                       command, pid, job->id);
-      }
-    }
+    cupsArrayDelete(filters);
 
-    if (job->current_file == job->num_files)
-    {
-      cupsdLogMessage(CUPSD_LOG_DEBUG2,
-                      "cupsdStartJob: Closing print pipes [ %d %d ]...",
-                     job->print_pipes[0], job->print_pipes[1]);
+    cupsdLogMessage(CUPSD_LOG_INFO,
+                    "[Job %d] Holding because filter limit has been reached.",
+                    job->id);
+    cupsdLogMessage(CUPSD_LOG_DEBUG2,
+                    "[Job %d] start_job: file=%d, cost=%d, level=%d, limit=%d",
+                    job->id, job->current_file, job->cost, FilterLevel,
+                   FilterLimit);
+    return;
+  }
 
-      cupsdClosePipe(job->print_pipes);
+  FilterLevel += job->cost;
 
-      cupsdLogMessage(CUPSD_LOG_DEBUG2,
-                      "cupsdStartJob: Closing back pipes [ %d %d ]...",
-                     job->back_pipes[0], job->back_pipes[1]);
+ /*
+  * Add decompression/raw filter as needed...
+  */
 
-      cupsdClosePipe(job->back_pipes);
-    }
-  }
-  else
+  if ((!printer->raw && job->compressions[job->current_file]) ||
+      (!filters && !printer->remote &&
+       (job->num_files > 1 || !strncmp(printer->device_uri, "file:", 5))))
   {
-    filterfds[slot][0] = -1;
-    filterfds[slot][1] = -1;
+   /*
+    * Add gziptoany filter to the front of the list...
+    */
 
-    if (job->current_file == job->num_files)
+    if (!filters)
+      filters = cupsArrayNew(NULL, NULL);
+
+    if (!cupsArrayInsert(filters, &gziptoany_filter))
     {
-      cupsdLogMessage(CUPSD_LOG_DEBUG2,
-                      "cupsdStartJob: Closing print pipes [ %d %d ]...",
-                     job->print_pipes[0], job->print_pipes[1]);
+      cupsdLogMessage(CUPSD_LOG_ERROR,
+                      "[Job %d] Unable to add decompression filter - %s",
+                     job->id, strerror(errno));
 
-      cupsdClosePipe(job->print_pipes);
-    }
-  }
+      cupsArrayDelete(filters);
 
-  if (remote_job)
-  {
-    for (i = 0; i < job->num_files; i ++)
-      free(argv[i + 6]);
-  }
+      job->current_file ++;
 
-  free(argv);
+      if (job->current_file == job->num_files)
+        cupsdCancelJob(job, 0, IPP_JOB_ABORTED);
 
-  cupsdLogMessage(CUPSD_LOG_DEBUG2,
-                  "cupsdStartJob: Closing filter pipes for slot %d "
-                 "[ %d %d ]...",
-                  slot, filterfds[slot][0], filterfds[slot][1]);
+      return;
+    }
+  }
 
-  cupsdClosePipe(filterfds[slot]);
+ /*
+  * Add port monitor, if any...
+  */
 
-  cupsdLogMessage(CUPSD_LOG_DEBUG2,
-                  "cupsdStartJob: Closing status output pipe %d...",
-                  statusfds[1]);
+  if (printer->port_monitor)
+  {
+   /*
+    * Add port monitor to the end of the list...
+    */
 
-  close(statusfds[1]);
+    if (!filters)
+      filters = cupsArrayNew(NULL, NULL);
 
-  cupsdLogMessage(CUPSD_LOG_DEBUG2,
-                  "cupsdStartJob: Adding fd %d to InputSet...",
-                  job->status_buffer->fd);
+    if (!cupsArrayAdd(filters, &port_monitor))
+    {
+      cupsdLogMessage(CUPSD_LOG_ERROR,
+                      "[Job %d] Unable to add port monitor - %s",
+                      job->id, strerror(errno));
 
-  FD_SET(job->status_buffer->fd, InputSet);
+      cupsArrayDelete(filters);
 
-  cupsdAddEvent(CUPSD_EVENT_JOB_STATE, job->printer, job, "Job #%d started.",
-                job->id);
-}
+      job->current_file ++;
 
+      if (job->current_file == job->num_files)
+        cupsdCancelJob(job, 0, IPP_JOB_ABORTED);
 
-/*
- * 'cupsdStopAllJobs()' - Stop all print jobs.
- */
+      return;
+    }
 
-void
-cupsdStopAllJobs(void)
-{
-  cupsd_job_t  *job;                   /* Current job */
+    snprintf(port_monitor.filter, sizeof(port_monitor.filter),
+             "%s/monitor/%s", ServerBin, printer->port_monitor);
+  }
 
+ /*
+  * Update the printer and job state to "processing"...
+  */
 
-  DEBUG_puts("cupsdStopAllJobs()");
+  job->state->values[0].integer = IPP_JOB_PROCESSING;
+  job->state_value              = IPP_JOB_PROCESSING;
 
-  for (job = (cupsd_job_t *)cupsArrayFirst(ActiveJobs);
-       job;
-       job = (cupsd_job_t *)cupsArrayNext(ActiveJobs))
-    if (job->state_value == IPP_JOB_PROCESSING)
-    {
-      cupsdStopJob(job, 1);
-      job->state->values[0].integer = IPP_JOB_PENDING;
-      job->state_value              = IPP_JOB_PENDING;
-    }
-}
+  job->status  = 0;
+  job->printer = printer;
+  printer->job = job;
 
+  cupsdSetPrinterState(printer, IPP_PRINTER_PROCESSING, 0);
 
-/*
- * 'cupsdStopJob()' - Stop a print job.
- */
+  if (job->current_file == 0)
+  {
+   /*
+    * Set the processing time...
+    */
 
-void
-cupsdStopJob(cupsd_job_t *job,         /* I - Job */
-             int         force)                /* I - 1 = Force all filters to stop */
-{
-  int  i;                              /* Looping var */
+    set_time(job, "time-at-processing");
 
+   /*
+    * Create the backchannel pipes and make them non-blocking...
+    */
 
-  cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdStopJob: id = %d, force = %d",
-                  job->id, force);
+    cupsdOpenPipe(job->back_pipes);
 
-  if (job->state_value != IPP_JOB_PROCESSING)
-    return;
+    fcntl(job->back_pipes[0], F_SETFL,
+          fcntl(job->back_pipes[0], F_GETFL) | O_NONBLOCK);
 
-  FilterLevel -= job->cost;
+    fcntl(job->back_pipes[1], F_SETFL,
+          fcntl(job->back_pipes[1], F_GETFL) | O_NONBLOCK);
 
-  if (job->status < 0 &&
-      !(job->dtype & (CUPS_PRINTER_CLASS | CUPS_PRINTER_IMPLICIT)) &&
-      !(job->printer->type & CUPS_PRINTER_FAX) &&
-      !strcmp(job->printer->error_policy, "stop-printer"))
-    cupsdSetPrinterState(job->printer, IPP_PRINTER_STOPPED, 1);
-  else if (job->printer->state != IPP_PRINTER_STOPPED)
-    cupsdSetPrinterState(job->printer, IPP_PRINTER_IDLE, 0);
+   /*
+    * Create the side-channel pipes and make them non-blocking...
+    */
 
-  cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdStopJob: printer state is %d",
-                  job->printer->state);
+    socketpair(AF_LOCAL, SOCK_STREAM, 0, job->side_pipes);
 
-  job->state->values[0].integer = IPP_JOB_STOPPED;
-  job->state_value              = IPP_JOB_STOPPED;
-  job->printer->job = NULL;
-  job->printer      = NULL;
+    fcntl(job->side_pipes[0], F_SETFL,
+          fcntl(job->side_pipes[0], F_GETFL) | O_NONBLOCK);
 
-  job->current_file --;
+    fcntl(job->side_pipes[1], F_SETFL,
+          fcntl(job->side_pipes[1], F_GETFL) | O_NONBLOCK);
+  }
 
-  for (i = 0; job->filters[i]; i ++)
-    if (job->filters[i] > 0)
-    {
-      cupsdEndProcess(job->filters[i], force);
-      job->filters[i] = 0;
-    }
+ /*
+  * Determine if we are printing a banner page or not...
+  */
 
-  if (job->backend > 0)
+  if (job->job_sheets == NULL)
   {
-    cupsdEndProcess(job->backend, force);
-    job->backend = 0;
+    cupsdLogMessage(CUPSD_LOG_DEBUG, "[Job %d] No job-sheets attribute.",
+                    job->id);
+    if ((job->job_sheets =
+         ippFindAttribute(job->attrs, "job-sheets", IPP_TAG_ZERO)) != NULL)
+      cupsdLogMessage(CUPSD_LOG_DEBUG,
+                      "[Job %d] ... but someone added one without setting "
+                     "job_sheets!", job->id);
   }
+  else if (job->job_sheets->num_values == 1)
+    cupsdLogMessage(CUPSD_LOG_DEBUG, "[Job %d] job-sheets=%s", job->id,
+                    job->job_sheets->values[0].string.text);
+  else
+    cupsdLogMessage(CUPSD_LOG_DEBUG, "[Job %d] job-sheets=%s,%s", job->id,
+               job->job_sheets->values[0].string.text,
+               job->job_sheets->values[1].string.text);
 
-  cupsdLogMessage(CUPSD_LOG_DEBUG2,
-                  "cupsdStopJob: Closing print pipes [ %d %d ]...",
-                  job->print_pipes[0], job->print_pipes[1]);
+  if (printer->type & (CUPS_PRINTER_REMOTE | CUPS_PRINTER_IMPLICIT))
+    banner_page = 0;
+  else if (job->job_sheets == NULL)
+    banner_page = 0;
+  else if (strcasecmp(job->job_sheets->values[0].string.text, "none") != 0 &&
+          job->current_file == 0)
+    banner_page = 1;
+  else if (job->job_sheets->num_values > 1 &&
+          strcasecmp(job->job_sheets->values[1].string.text, "none") != 0 &&
+          job->current_file == (job->num_files - 1))
+    banner_page = 1;
+  else
+    banner_page = 0;
 
-  cupsdClosePipe(job->print_pipes);
+  cupsdLogMessage(CUPSD_LOG_DEBUG, "[Job %d] banner_page = %d", job->id,
+                  banner_page);
 
-  cupsdLogMessage(CUPSD_LOG_DEBUG2,
-                  "cupsdStopJob: Closing back pipes [ %d %d ]...",
-                  job->back_pipes[0], job->back_pipes[1]);
+ /*
+  * Building the options string is harder than it needs to be, but
+  * for the moment we need to pass strings for command-line args and
+  * not IPP attribute pointers... :)
+  *
+  * First allocate/reallocate the option buffer as needed...
+  */
 
-  cupsdClosePipe(job->back_pipes);
+  i = ipp_length(job->attrs);
 
-  if (job->status_buffer)
+  if (i > optlength)
   {
-   /*
-    * Close the pipe and clear the input bit.
-    */
+    if (optlength == 0)
+      optptr = malloc(i);
+    else
+      optptr = realloc(options, i);
 
-    cupsdLogMessage(CUPSD_LOG_DEBUG2,
-                    "cupsdStopJob: Removing fd %d from InputSet...",
-                   job->status_buffer->fd);
+    if (optptr == NULL)
+    {
+      cupsdLogMessage(CUPSD_LOG_CRIT,
+                      "[Job %d] Unable to allocate %d bytes for option buffer!",
+                     job->id, i);
 
-    FD_CLR(job->status_buffer->fd, InputSet);
+      cupsArrayDelete(filters);
 
-    cupsdLogMessage(CUPSD_LOG_DEBUG2,
-                    "cupsdStopJob: Closing status input pipe %d...",
-                    job->status_buffer->fd);
+      FilterLevel -= job->cost;
 
-    cupsdStatBufDelete(job->status_buffer);
+      cupsdCancelJob(job, 0, IPP_JOB_ABORTED);
+      return;
+    }
 
-    job->status_buffer = NULL;
+    options   = optptr;
+    optlength = i;
   }
-}
 
+ /*
+  * Now loop through the attributes and convert them to the textual
+  * representation used by the filters...
+  */
 
-/*
- * 'cupsdUnloadCompletedJobs()' - Flush completed job history from memory.
- */
+  optptr  = options;
+  *optptr = '\0';
 
-void
-cupsdUnloadCompletedJobs(void)
-{
-  cupsd_job_t  *job;                   /* Current job */
-  time_t       expire;                 /* Expiration time */
+  snprintf(title, sizeof(title), "%s-%d", printer->name, job->id);
+  strcpy(copies, "1");
 
+  for (attr = job->attrs->attrs; attr != NULL; attr = attr->next)
+  {
+    if (!strcmp(attr->name, "copies") &&
+       attr->value_tag == IPP_TAG_INTEGER)
+    {
+     /*
+      * Don't use the # copies attribute if we are printing the job sheets...
+      */
 
-  expire = time(NULL) - 60;
+      if (!banner_page)
+        sprintf(copies, "%d", attr->values[0].integer);
+    }
+    else if (!strcmp(attr->name, "job-name") &&
+            (attr->value_tag == IPP_TAG_NAME ||
+             attr->value_tag == IPP_TAG_NAMELANG))
+      strlcpy(title, attr->values[0].string.text, sizeof(title));
+    else if (attr->group_tag == IPP_TAG_JOB)
+    {
+     /*
+      * Filter out other unwanted attributes...
+      */
 
-  for (job = (cupsd_job_t *)cupsArrayFirst(Jobs);
-       job;
-       job = (cupsd_job_t *)cupsArrayNext(Jobs))
-    if (job->attrs && job->state_value >= IPP_JOB_STOPPED &&
-        job->access_time < expire)
-      cupsdUnloadJob(job);
-}
+      if (attr->value_tag == IPP_TAG_MIMETYPE ||
+         attr->value_tag == IPP_TAG_NAMELANG ||
+         attr->value_tag == IPP_TAG_TEXTLANG ||
+         (attr->value_tag == IPP_TAG_URI && strcmp(attr->name, "job-uuid")) ||
+         attr->value_tag == IPP_TAG_URISCHEME ||
+         attr->value_tag == IPP_TAG_BEGIN_COLLECTION) /* Not yet supported */
+       continue;
+
+      if (!strncmp(attr->name, "time-", 5))
+       continue;
 
+      if (!strncmp(attr->name, "job-", 4) && strcmp(attr->name, "job-uuid") &&
+          !(printer->type & CUPS_PRINTER_REMOTE))
+       continue;
+
+      if (!strncmp(attr->name, "job-", 4) &&
+          strcmp(attr->name, "job-uuid") &&
+          strcmp(attr->name, "job-billing") &&
+          strcmp(attr->name, "job-sheets") &&
+          strcmp(attr->name, "job-hold-until") &&
+         strcmp(attr->name, "job-priority"))
+       continue;
+
+      if ((!strcmp(attr->name, "page-label") ||
+           !strcmp(attr->name, "page-border") ||
+           !strncmp(attr->name, "number-up", 9) ||
+          !strcmp(attr->name, "page-ranges") ||
+          !strcmp(attr->name, "page-set") ||
+          !strcasecmp(attr->name, "AP_FIRSTPAGE_InputSlot") ||
+          !strcasecmp(attr->name, "AP_FIRSTPAGE_ManualFeed") ||
+          !strcasecmp(attr->name, "com.apple.print.PrintSettings."
+                                  "PMTotalSidesImaged..n.") ||
+          !strcasecmp(attr->name, "com.apple.print.PrintSettings."
+                                  "PMTotalBeginPages..n.")) &&
+         banner_page)
+        continue;
 
-/*
* 'cupsdUnloadJob()' - Unload a job from memory.
- */
+     /*
     * Otherwise add them to the list...
     */
 
-void
-cupsdUnloadJob(cupsd_job_t *job)       /* I - Job */
-{
-  if (!job->attrs)
-    return;
+      if (optptr > options)
+       strlcat(optptr, " ", optlength - (optptr - options));
 
-  cupsdLogMessage(CUPSD_LOG_DEBUG, "Unloading job %d...", job->id);
+      if (attr->value_tag != IPP_TAG_BOOLEAN)
+      {
+       strlcat(optptr, attr->name, optlength - (optptr - options));
+       strlcat(optptr, "=", optlength - (optptr - options));
+      }
 
-  ippDelete(job->attrs);
+      for (i = 0; i < attr->num_values; i ++)
+      {
+       if (i)
+         strlcat(optptr, ",", optlength - (optptr - options));
 
-  job->attrs      = NULL;
-  job->state      = NULL;
-  job->sheets     = NULL;
-  job->job_sheets = NULL;
-}
+       optptr += strlen(optptr);
 
+       switch (attr->value_tag)
+       {
+         case IPP_TAG_INTEGER :
+         case IPP_TAG_ENUM :
+             snprintf(optptr, optlength - (optptr - options),
+                      "%d", attr->values[i].integer);
+             break;
 
-/*
- * 'cupsdUpdateJob()' - Read a status update from a job's filters.
- */
+         case IPP_TAG_BOOLEAN :
+             if (!attr->values[i].boolean)
+               strlcat(optptr, "no", optlength - (optptr - options));
 
-void
-cupsdUpdateJob(cupsd_job_t *job)       /* I - Job to check */
-{
-  int          i;                      /* Looping var */
-  int          copies;                 /* Number of copies printed */
-  char         message[1024],          /* Message text */
-               *ptr;                   /* Pointer update... */
-  int          loglevel;               /* Log level for message */
+         case IPP_TAG_NOVALUE :
+             strlcat(optptr, attr->name,
+                     optlength - (optptr - options));
+             break;
 
+         case IPP_TAG_RANGE :
+             if (attr->values[i].range.lower == attr->values[i].range.upper)
+               snprintf(optptr, optlength - (optptr - options) - 1,
+                        "%d", attr->values[i].range.lower);
+              else
+               snprintf(optptr, optlength - (optptr - options) - 1,
+                        "%d-%d", attr->values[i].range.lower,
+                        attr->values[i].range.upper);
+             break;
 
-  while ((ptr = cupsdStatBufUpdate(job->status_buffer, &loglevel,
-                                   message, sizeof(message))) != NULL)
-  {
-   /*
-    * Process page and printer state messages as needed...
-    */
+         case IPP_TAG_RESOLUTION :
+             snprintf(optptr, optlength - (optptr - options) - 1,
+                      "%dx%d%s", attr->values[i].resolution.xres,
+                      attr->values[i].resolution.yres,
+                      attr->values[i].resolution.units == IPP_RES_PER_INCH ?
+                          "dpi" : "dpc");
+             break;
 
-    if (loglevel == CUPSD_LOG_PAGE)
-    {
-     /*
-      * Page message; send the message to the page_log file and update the
-      * job sheet count...
-      */
+          case IPP_TAG_STRING :
+         case IPP_TAG_TEXT :
+         case IPP_TAG_NAME :
+         case IPP_TAG_KEYWORD :
+         case IPP_TAG_CHARSET :
+         case IPP_TAG_LANGUAGE :
+         case IPP_TAG_URI :
+             for (valptr = attr->values[i].string.text; *valptr;)
+             {
+               if (strchr(" \t\n\\\'\"", *valptr))
+                 *optptr++ = '\\';
+               *optptr++ = *valptr++;
+             }
 
-      if (job->sheets != NULL)
-      {
-        if (!strncasecmp(message, "total ", 6))
-       {
-        /*
-         * Got a total count of pages from a backend or filter...
-         */
+             *optptr = '\0';
+             break;
 
-         copies = atoi(message + 6);
-         copies -= job->sheets->values[0].integer; /* Just track the delta */
+          default :
+             break; /* anti-compiler-warning-code */
        }
-       else if (!sscanf(message, "%*d%d", &copies))
-         copies = 1;
-         
-        job->sheets->values[0].integer += copies;
-
-       if (job->printer->page_limit)
-         cupsdUpdateQuota(job->printer, job->username, copies, 0);
       }
 
-      cupsdLogPage(job, message);
-
-      cupsdAddEvent(CUPSD_EVENT_JOB_PROGRESS, job->printer, job,
-                    "Printed %d page(s).", job->sheets->values[0].integer);
-    }
-    else if (loglevel == CUPSD_LOG_STATE)
-    {
-      cupsdSetPrinterReasons(job->printer, message);
-      cupsdAddPrinterHistory(job->printer);
+      optptr += strlen(optptr);
     }
-    else if (loglevel == CUPSD_LOG_ATTR)
-    {
-     /*
-      * Set attribute(s)...
-      */
+  }
 
-      /**** TODO ****/
-    }
-#ifdef __APPLE__
-    else if (!strncmp(message, "recoverable:", 12))
-    {
-      cupsdSetPrinterReasons(job->printer,
-                             "+com.apple.print.recoverable-warning");
+ /*
+  * Build the command-line arguments for the filters.  Each filter
+  * has 6 or 7 arguments:
+  *
+  *     argv[0] = printer
+  *     argv[1] = job ID
+  *     argv[2] = username
+  *     argv[3] = title
+  *     argv[4] = # copies
+  *     argv[5] = options
+  *     argv[6] = filename (optional; normally stdin)
+  *
+  * This allows legacy printer drivers that use the old System V
+  * printing interface to be used by CUPS.
+  *
+  * For remote jobs, we send all of the files in the argument list.
+  */
 
-      ptr = message + 12;
-      while (isspace(*ptr & 255))
-        ptr ++;
+  if (printer->remote && job->num_files > 1)
+    argv = calloc(7 + job->num_files, sizeof(char *));
+  else
+    argv = calloc(8, sizeof(char *));
 
-      cupsdSetString(&job->printer->recoverable, ptr);
-      cupsdAddPrinterHistory(job->printer);
-    }
-    else if (!strncmp(message, "recovered:", 10))
-    {
-      cupsdSetPrinterReasons(job->printer,
-                             "-com.apple.print.recoverable-warning");
+  sprintf(jobid, "%d", job->id);
 
-      ptr = message + 10;
-      while (isspace(*ptr & 255))
-        ptr ++;
+  argv[0] = printer->name;
+  argv[1] = jobid;
+  argv[2] = job->username;
+  argv[3] = title;
+  argv[4] = copies;
+  argv[5] = options;
 
-      cupsdSetString(&job->printer->recoverable, ptr);
-      cupsdAddPrinterHistory(job->printer);
-    }
-#endif /* __APPLE__ */
-    else if (loglevel <= CUPSD_LOG_INFO)
+  if (printer->remote && job->num_files > 1)
+  {
+    for (i = 0; i < job->num_files; i ++)
     {
-     /*
-      * Some message to show in the printer-state-message attribute...
-      */
-
-      strlcpy(job->printer->state_message, message,
-              sizeof(job->printer->state_message));
-      cupsdAddPrinterHistory(job->printer);
+      snprintf(filename, sizeof(filename), "%s/d%05d-%03d", RequestRoot,
+               job->id, i + 1);
+      argv[6 + i] = strdup(filename);
     }
-
-    if (!strchr(job->status_buffer->buffer, '\n'))
-      break;
   }
-
-  if (ptr == NULL)
+  else
   {
-   /*
-    * See if all of the filters and the backend have returned their
-    * exit statuses.
-    */
+    snprintf(filename, sizeof(filename), "%s/d%05d-%03d", RequestRoot,
+             job->id, job->current_file + 1);
+    argv[6] = filename;
+  }
 
-    for (i = 0; job->filters[i] < 0; i ++);
+  for (i = 0; argv[i]; i ++)
+    cupsdLogMessage(CUPSD_LOG_DEBUG,
+                    "[Job %d] argv[%d]=\"%s\"", job->id, i, argv[i]);
 
-    if (job->filters[i])
-      return;
+ /*
+  * Create environment variable strings for the filters...
+  */
 
-    if (job->current_file >= job->num_files && job->backend > 0)
-      return;
+  attr = ippFindAttribute(job->attrs, "attributes-natural-language",
+                          IPP_TAG_LANGUAGE);
 
-   /*
-    * Handle the end of job stuff...
-    */
+  switch (strlen(attr->values[0].string.text))
+  {
+    default :
+       /*
+        * This is an unknown or badly formatted language code; use
+       * the POSIX locale...
+       */
 
-    cupsdFinishJob(job);
-  }
-}
+       strcpy(lang, "LANG=C");
+       break;
 
+    case 2 :
+       /*
+        * Just the language code (ll)...
+       */
 
-/*
- * 'compare_active_jobs()' - Compare the job IDs and priorities of two jobs.
- */
+        snprintf(lang, sizeof(lang), "LANG=%s",
+                attr->values[0].string.text);
+        break;
 
-static int                             /* O - Difference */
-compare_active_jobs(void *first,       /* I - First job */
-                    void *second,      /* I - Second job */
-                   void *data)         /* I - App data (not used) */
-{
-  int  diff;                           /* Difference */
+    case 5 :
+       /*
+        * Language and country code (ll-cc)...
+       */
 
+        snprintf(lang, sizeof(lang), "LANG=%c%c_%c%c",
+                attr->values[0].string.text[0],
+                attr->values[0].string.text[1],
+                toupper(attr->values[0].string.text[3] & 255),
+                toupper(attr->values[0].string.text[4] & 255));
+        break;
+  }
 
-  if ((diff = ((cupsd_job_t *)first)->priority -
-              ((cupsd_job_t *)second)->priority) != 0)
-    return (diff);
+  attr = ippFindAttribute(job->attrs, "document-format",
+                          IPP_TAG_MIMETYPE);
+  if (attr != NULL &&
+      (optptr = strstr(attr->values[0].string.text, "charset=")) != NULL)
+    snprintf(charset, sizeof(charset), "CHARSET=%s", optptr + 8);
   else
-    return (((cupsd_job_t *)first)->id - ((cupsd_job_t *)second)->id);
-}
+  {
+    attr = ippFindAttribute(job->attrs, "attributes-charset",
+                           IPP_TAG_CHARSET);
+    snprintf(charset, sizeof(charset), "CHARSET=%s",
+             attr->values[0].string.text);
+  }
 
+  snprintf(content_type, sizeof(content_type), "CONTENT_TYPE=%s/%s",
+           job->filetypes[job->current_file]->super,
+           job->filetypes[job->current_file]->type);
+  snprintf(device_uri, sizeof(device_uri), "DEVICE_URI=%s",
+           printer->device_uri);
+  cupsdSanitizeURI(printer->device_uri, sani_uri, sizeof(sani_uri));
+  snprintf(ppd, sizeof(ppd), "PPD=%s/ppd/%s.ppd", ServerRoot, printer->name);
+  snprintf(printer_name, sizeof(printer_name), "PRINTER=%s", printer->name);
+  snprintf(rip_max_cache, sizeof(rip_max_cache), "RIP_MAX_CACHE=%s", RIPCache);
 
-/*
- * 'compare_jobs()' - Compare the job IDs of two jobs.
- */
+  envc = cupsdLoadEnv(envp, (int)(sizeof(envp) / sizeof(envp[0])));
 
-static int                             /* O - Difference */
-compare_jobs(void *first,              /* I - First job */
-             void *second,             /* I - Second job */
-            void *data)                /* I - App data (not used) */
-{
-  return (((cupsd_job_t *)first)->id - ((cupsd_job_t *)second)->id);
-}
+  envp[envc ++] = charset;
+  envp[envc ++] = lang;
+  envp[envc ++] = ppd;
+  envp[envc ++] = rip_max_cache;
+  envp[envc ++] = content_type;
+  envp[envc ++] = device_uri;
+  envp[envc ++] = printer_name;
 
+  if (!printer->remote && !printer->raw &&
+      (filter = (mime_filter_t *)cupsArrayLast(filters)) != NULL &&
+      filter->dst)
+  {
+    snprintf(final_content_type, sizeof(final_content_type),
+             "FINAL_CONTENT_TYPE=%s/%s",
+            filter->dst->super, filter->dst->type);
+    envp[envc ++] = final_content_type;
+  }
 
-/*
- * 'free_job()' - Free all memory used by a job.
- */
+  if (Classification && !banner_page)
+  {
+    if ((attr = ippFindAttribute(job->attrs, "job-sheets",
+                                 IPP_TAG_NAME)) == NULL)
+      snprintf(classification, sizeof(classification), "CLASSIFICATION=%s",
+               Classification);
+    else if (attr->num_values > 1 &&
+             strcmp(attr->values[1].string.text, "none") != 0)
+      snprintf(classification, sizeof(classification), "CLASSIFICATION=%s",
+               attr->values[1].string.text);
+    else
+      snprintf(classification, sizeof(classification), "CLASSIFICATION=%s",
+               attr->values[0].string.text);
 
-static void
-free_job(cupsd_job_t *job)             /* I - Job */
-{
-  cupsdClearString(&job->username);
-  cupsdClearString(&job->dest);
+    envp[envc ++] = classification;
+  }
 
-  if (job->num_files > 0)
+  if (job->dtype & (CUPS_PRINTER_CLASS | CUPS_PRINTER_IMPLICIT))
   {
-    free(job->compressions);
-    free(job->filetypes);
+    snprintf(class_name, sizeof(class_name), "CLASS=%s", job->dest);
+    envp[envc ++] = class_name;
   }
 
-  ippDelete(job->attrs);
-
-  free(job);
-}
+  if (job->auth_username)
+    envp[envc ++] = job->auth_username;
+  if (job->auth_domain)
+    envp[envc ++] = job->auth_domain;
+  if (job->auth_password)
+    envp[envc ++] = job->auth_password;
 
+#ifdef HAVE_GSSAPI
+  if (job->ccname)
+    envp[envc ++] = job->ccname;
+#endif /* HAVE_GSSAPI */
 
-/*
- * 'ipp_length()' - Compute the size of the buffer needed to hold 
- *                 the textual IPP attributes.
- */
+  envp[envc] = NULL;
 
-int                                    /* O - Size of attribute buffer */
-ipp_length(ipp_t *ipp)                 /* I - IPP request */
-{
-  int                  bytes;          /* Number of bytes */
-  int                  i;              /* Looping var */
-  ipp_attribute_t      *attr;          /* Current attribute */
+  for (i = 0; i < envc; i ++)
+    if (!strncmp(envp[i], "AUTH_", 5))
+      cupsdLogMessage(CUPSD_LOG_DEBUG, "[Job %d] envp[%d]=\"AUTH_%c****\"",
+                      job->id, i, envp[i][5]);
+    else if (strncmp(envp[i], "DEVICE_URI=", 11))
+      cupsdLogMessage(CUPSD_LOG_DEBUG, "[Job %d] envp[%d]=\"%s\"",
+                      job->id, i, envp[i]);
+    else
+      cupsdLogMessage(CUPSD_LOG_DEBUG, "[Job %d] envp[%d]=\"DEVICE_URI=%s\"",
+                      job->id, i, sani_uri);
 
+  if (printer->remote)
+    job->current_file = job->num_files;
+  else
+    job->current_file ++;
 
  /*
-  * Loop through all attributes...
+  * Now create processes for all of the filters...
   */
 
-  bytes = 0;
+  filterfds[0][0] = -1;
+  filterfds[0][1] = -1;
+  filterfds[1][0] = -1;
+  filterfds[1][1] = -1;
 
-  for (attr = ipp->attrs; attr != NULL; attr = attr->next)
+  if (!job->status_buffer)
   {
-   /*
-    * Skip attributes that won't be sent to filters...
-    */
+    if (cupsdOpenPipe(job->status_pipes))
+    {
+      cupsdLogMessage(CUPSD_LOG_ERROR,
+                      "[Job %d] Unable to create job status pipes - %s.",
+                     job->id, strerror(errno));
+      snprintf(printer->state_message, sizeof(printer->state_message),
+              "Unable to create status pipes - %s.", strerror(errno));
 
-    if (attr->value_tag == IPP_TAG_MIMETYPE ||
-       attr->value_tag == IPP_TAG_NAMELANG ||
-       attr->value_tag == IPP_TAG_TEXTLANG ||
-       attr->value_tag == IPP_TAG_URI ||
-       attr->value_tag == IPP_TAG_URISCHEME)
-      continue;
+      cupsdAddPrinterHistory(printer);
 
-    if (strncmp(attr->name, "time-", 5) == 0)
-      continue;
+      cupsdAddEvent(CUPSD_EVENT_JOB_COMPLETED, job->printer, job,
+                   "Job canceled because the server could not create the job "
+                   "status pipes.");
 
-   /*
-    * Add space for a leading space and commas between each value.
-    * For the first attribute, the leading space isn't used, so the
-    * extra byte can be used as the nul terminator...
-    */
+      goto abort_job;
+    }
 
-    bytes ++;                          /* " " separator */
-    bytes += attr->num_values;         /* "," separators */
+    cupsdLogMessage(CUPSD_LOG_DEBUG2,
+                    "[Job %d] start_job: status_pipes = [ %d %d ]",
+                   job->id, job->status_pipes[0], job->status_pipes[1]);
 
-   /*
-    * Boolean attributes appear as "foo,nofoo,foo,nofoo", while
-    * other attributes appear as "foo=value1,value2,...,valueN".
-    */
+    job->status_buffer = cupsdStatBufNew(job->status_pipes[0], "[Job %d]",
+                                        job->id);
+    job->status_level  = CUPSD_LOG_INFO;
+  }
 
-    if (attr->value_tag != IPP_TAG_BOOLEAN)
-      bytes += strlen(attr->name);
-    else
-      bytes += attr->num_values * strlen(attr->name);
+  job->status = 0;
+  memset(job->filters, 0, sizeof(job->filters));
 
-   /*
-    * Now add the size required for each value in the attribute...
-    */
+  for (i = 0, slot = 0, filter = (mime_filter_t *)cupsArrayFirst(filters);
+       filter;
+       i ++, filter = (mime_filter_t *)cupsArrayNext(filters))
+  {
+    if (filter->filter[0] != '/')
+      snprintf(command, sizeof(command), "%s/filter/%s", ServerBin,
+               filter->filter);
+    else
+      strlcpy(command, filter->filter, sizeof(command));
 
-    switch (attr->value_tag)
+    if (i < (cupsArrayCount(filters) - 1))
     {
-      case IPP_TAG_INTEGER :
-      case IPP_TAG_ENUM :
-         /*
-         * Minimum value of a signed integer is -2147483647, or 11 digits.
-         */
-
-         bytes += attr->num_values * 11;
-         break;
-
-      case IPP_TAG_BOOLEAN :
-         /*
-         * Add two bytes for each false ("no") value...
-         */
+      if (cupsdOpenPipe(filterfds[slot]))
+      {
+       cupsdLogMessage(CUPSD_LOG_ERROR,
+                       "[Job %d] Unable to create job filter pipes - %s.",
+                       job->id, strerror(errno));
+       snprintf(printer->state_message, sizeof(printer->state_message),
+               "Unable to create filter pipes - %s.", strerror(errno));
+       cupsdAddPrinterHistory(printer);
 
-          for (i = 0; i < attr->num_values; i ++)
-           if (!attr->values[i].boolean)
-             bytes += 2;
-         break;
+       cupsdAddEvent(CUPSD_EVENT_JOB_COMPLETED, job->printer, job,
+                      "Job canceled because the server could not create the "
+                     "filter pipes.");
 
-      case IPP_TAG_RANGE :
-         /*
-         * A range is two signed integers separated by a hyphen, or
-         * 23 characters max.
-         */
+        goto abort_job;
+      }
+    }
+    else
+    {
+      if (job->current_file == 1)
+      {
+       if (strncmp(printer->device_uri, "file:", 5) != 0)
+       {
+         if (cupsdOpenPipe(job->print_pipes))
+         {
+           cupsdLogMessage(CUPSD_LOG_ERROR,
+                           "[Job %d] Unable to create job backend pipes - %s.",
+                           job->id, strerror(errno));
+           snprintf(printer->state_message, sizeof(printer->state_message),
+                   "Unable to create backend pipes - %s.", strerror(errno));
+           cupsdAddPrinterHistory(printer);
 
-         bytes += attr->num_values * 23;
-         break;
+           cupsdAddEvent(CUPSD_EVENT_JOB_COMPLETED, job->printer, job,
+                         "Job canceled because the server could not create "
+                         "the backend pipes.");
 
-      case IPP_TAG_RESOLUTION :
-         /*
-         * A resolution is two signed integers separated by an "x" and
-         * suffixed by the units, or 26 characters max.
-         */
+            goto abort_job;
+         }
+       }
+       else
+       {
+         job->print_pipes[0] = -1;
+         if (!strcmp(printer->device_uri, "file:/dev/null") ||
+             !strcmp(printer->device_uri, "file:///dev/null"))
+           job->print_pipes[1] = -1;
+         else
+         {
+           if (!strncmp(printer->device_uri, "file:/dev/", 10))
+             job->print_pipes[1] = open(printer->device_uri + 5,
+                                        O_WRONLY | O_EXCL);
+           else if (!strncmp(printer->device_uri, "file:///dev/", 12))
+             job->print_pipes[1] = open(printer->device_uri + 7,
+                                        O_WRONLY | O_EXCL);
+           else if (!strncmp(printer->device_uri, "file:///", 8))
+             job->print_pipes[1] = open(printer->device_uri + 7,
+                                        O_WRONLY | O_CREAT | O_TRUNC, 0600);
+           else
+             job->print_pipes[1] = open(printer->device_uri + 5,
+                                        O_WRONLY | O_CREAT | O_TRUNC, 0600);
 
-         bytes += attr->num_values * 26;
-         break;
+           if (job->print_pipes[1] < 0)
+           {
+              cupsdLogMessage(CUPSD_LOG_ERROR,
+                             "[Job %d] Unable to open output file \"%s\" - %s.",
+                             job->id, printer->device_uri, strerror(errno));
+              snprintf(printer->state_message, sizeof(printer->state_message),
+                      "Unable to open output file \"%s\" - %s.",
+                      printer->device_uri, strerror(errno));
+
+             cupsdAddEvent(CUPSD_EVENT_JOB_COMPLETED, job->printer, job,
+                           "Job canceled because the server could not open the "
+                           "output file.");
+
+              goto abort_job;
+           }
 
-      case IPP_TAG_STRING :
-      case IPP_TAG_TEXT :
-      case IPP_TAG_NAME :
-      case IPP_TAG_KEYWORD :
-      case IPP_TAG_CHARSET :
-      case IPP_TAG_LANGUAGE :
-      case IPP_TAG_URI :
-         /*
-         * Strings can contain characters that need quoting.  We need
-         * at least 2 * len + 2 characters to cover the quotes and
-         * any backslashes in the string.
-         */
+           fcntl(job->print_pipes[1], F_SETFD,
+                 fcntl(job->print_pipes[1], F_GETFD) | FD_CLOEXEC);
+          }
+       }
 
-          for (i = 0; i < attr->num_values; i ++)
-           bytes += 2 * strlen(attr->values[i].string.text) + 2;
-         break;
+       cupsdLogMessage(CUPSD_LOG_DEBUG2,
+                       "[Job %d] start_job: print_pipes = [ %d %d ]",
+                        job->id, job->print_pipes[0], job->print_pipes[1]);
+      }
 
-       default :
-         break; /* anti-compiler-warning-code */
+      filterfds[slot][0] = job->print_pipes[0];
+      filterfds[slot][1] = job->print_pipes[1];
     }
-  }
-
-  return (bytes);
-}
-
-
-/*
- * 'load_job_cache()' - Load jobs from the job.cache file.
- */
 
-static void
-load_job_cache(const char *filename)   /* I - job.cache filename */
-{
-  cups_file_t  *fp;                    /* job.cache file */
-  char         line[1024],             /* Line buffer */
-               *value;                 /* Value on line */
-  int          linenum;                /* Line number in file */
-  cupsd_job_t  *job;                   /* Current job */
-  int          jobid;                  /* Job ID */
-  char         jobfile[1024];          /* Job filename */
+    cupsdLogMessage(CUPSD_LOG_DEBUG2, "[Job %d] start_job: filter=\"%s\"",
+                    job->id, command);
+    cupsdLogMessage(CUPSD_LOG_DEBUG2,
+                    "[Job %d] start_job: filterfds[%d]=[ %d %d ]",
+                    job->id, slot, filterfds[slot][0], filterfds[slot][1]);
 
+    pid = cupsdStartProcess(command, argv, envp, filterfds[!slot][0],
+                            filterfds[slot][1], job->status_pipes[1],
+                           job->back_pipes[0], job->side_pipes[0], 0,
+                           job->filters + i);
 
- /*
-  * Open the job.cache file...
-  */
+    cupsdLogMessage(CUPSD_LOG_DEBUG2,
+                    "[Job %d] start_job: Closing filter pipes for slot %d "
+                   "[ %d %d ]...",
+                    job->id, !slot, filterfds[!slot][0], filterfds[!slot][1]);
 
-  if ((fp = cupsFileOpen(filename, "r")) == NULL)
-  {
-    if (errno != ENOENT)
+    cupsdClosePipe(filterfds[!slot]);
+
+    if (pid == 0)
+    {
       cupsdLogMessage(CUPSD_LOG_ERROR,
-                      "Unable to open job cache file \"%s\": %s",
-                      filename, strerror(errno));
+                      "[Job %d] Unable to start filter \"%s\" - %s.",
+                      job->id, filter->filter, strerror(errno));
+      snprintf(printer->state_message, sizeof(printer->state_message),
+               "Unable to start filter \"%s\" - %s.",
+               filter->filter, strerror(errno));
 
-    load_request_root();
+      cupsdAddPrinterHistory(printer);
 
-    return;
+      cupsdAddEvent(CUPSD_EVENT_JOB_COMPLETED, job->printer, job,
+                    "Job canceled because the server could not execute a "
+                   "filter.");
+
+      goto abort_job;
+    }
+
+    cupsdLogMessage(CUPSD_LOG_INFO, "[Job %d] Started filter %s (PID %d)",
+                    job->id, command, pid);
+
+    argv[6] = NULL;
+    slot    = !slot;
   }
 
+  cupsArrayDelete(filters);
+
  /*
-  * Read entries from the job cache file and create jobs as needed.
+  * Finally, pipe the final output into a backend process if needed...
   */
 
-  cupsdLogMessage(CUPSD_LOG_INFO, "Loading job cache file \"%s\"...",
-                  filename);
-
-  linenum = 0;
-  job     = NULL;
-
-  while (cupsFileGetConf(fp, line, sizeof(line), &value, &linenum))
+  if (strncmp(printer->device_uri, "file:", 5) != 0)
   {
-    if (!strcasecmp(line, "NextJobId"))
-    {
-      if (value)
-        NextJobId = atoi(value);
-    }
-    else if (!strcasecmp(line, "<Job"))
+    if (job->current_file == 1)
     {
-      if (job)
-      {
-        cupsdLogMessage(CUPSD_LOG_ERROR, "Missing </Job> directive on line %d!",
-                       linenum);
-        continue;
-      }
-
-      if (!value)
-      {
-        cupsdLogMessage(CUPSD_LOG_ERROR, "Missing job ID on line %d!", linenum);
-       continue;
-      }
+      sscanf(printer->device_uri, "%254[^:]", method);
+      snprintf(command, sizeof(command), "%s/backend/%s", ServerBin, method);
 
-      jobid = atoi(value);
+     /*
+      * See if the backend needs to run as root...
+      */
 
-      if (jobid < 1)
-      {
-        cupsdLogMessage(CUPSD_LOG_ERROR, "Bad job ID %d on line %d!", jobid,
-                       linenum);
-        continue;
-      }
+      if (RunUser)
+        backroot = 0;
+      else if (stat(command, &backinfo))
+       backroot = 0;
+      else
+        backroot = !(backinfo.st_mode & (S_IRWXG | S_IRWXO));
 
-      snprintf(jobfile, sizeof(jobfile), "%s/c%05d", RequestRoot, jobid);
-      if (access(jobfile, 0))
-      {
-        cupsdLogMessage(CUPSD_LOG_ERROR, "Job %d files have gone away!", jobid);
-        continue;
-      }
+      argv[0] = sani_uri;
 
-      job = calloc(1, sizeof(cupsd_job_t));
-      if (!job)
-      {
-        cupsdLogMessage(CUPSD_LOG_EMERG,
-                       "Unable to allocate memory for job %d!", jobid);
-        break;
-      }
+      filterfds[slot][0] = -1;
+      filterfds[slot][1] = -1;
 
-      job->id             = jobid;
-      job->back_pipes[0]  = -1;
-      job->back_pipes[1]  = -1;
-      job->print_pipes[0] = -1;
-      job->print_pipes[1] = -1;
+      cupsdLogMessage(CUPSD_LOG_DEBUG2, "[Job %d] start_job: backend=\"%s\"",
+                      job->id, command);
+      cupsdLogMessage(CUPSD_LOG_DEBUG2,
+                      "[Job %d] start_job: filterfds[%d] = [ %d %d ]", job->id,
+                     slot, filterfds[slot][0], filterfds[slot][1]);
 
-      cupsdLogMessage(CUPSD_LOG_DEBUG, "Loading job %d from cache...", job->id);
-    }
-    else if (!job)
-    {
-      cupsdLogMessage(CUPSD_LOG_ERROR,
-                     "Missing <Job #> directive on line %d!", linenum);
-      continue;
-    }
-    else if (!strcasecmp(line, "</Job>"))
-    {
-      cupsArrayAdd(Jobs, job);
+      pid = cupsdStartProcess(command, argv, envp, filterfds[!slot][0],
+                             filterfds[slot][1], job->status_pipes[1],
+                             job->back_pipes[1], job->side_pipes[1],
+                             backroot, &(job->backend));
 
-      if (job->state_value < IPP_JOB_STOPPED)
+      if (pid == 0)
       {
-        cupsArrayAdd(ActiveJobs, job);
-       cupsdLoadJob(job);
-      }
-
-      job = NULL;
-    }
-    else if (!value)
-    {
-      cupsdLogMessage(CUPSD_LOG_ERROR, "Missing value on line %d!", linenum);
-      continue;
-    }
-    else if (!strcasecmp(line, "State"))
-    {
-      job->state_value = atoi(value);
+       cupsdLogMessage(CUPSD_LOG_ERROR,
+                       "[Job %d] Unable to start backend \"%s\" - %s.",
+                       job->id, method, strerror(errno));
+       snprintf(printer->state_message, sizeof(printer->state_message),
+                "Unable to start backend \"%s\" - %s.", method,
+                strerror(errno));
 
-      if (job->state_value < IPP_JOB_PENDING)
-        job->state_value = IPP_JOB_PENDING;
-      else if (job->state_value > IPP_JOB_COMPLETED)
-        job->state_value = IPP_JOB_COMPLETED;
-    }
-    else if (!strcasecmp(line, "Priority"))
-    {
-      job->priority = atoi(value);
-    }
-    else if (!strcasecmp(line, "Username"))
-    {
-      cupsdSetString(&job->username, value);
-    }
-    else if (!strcasecmp(line, "Destination"))
-    {
-      cupsdSetString(&job->dest, value);
-    }
-    else if (!strcasecmp(line, "DestType"))
-    {
-      job->dtype = (cups_ptype_t)atoi(value);
-    }
-    else if (!strcasecmp(line, "NumFiles"))
-    {
-      job->num_files = atoi(value);
+       cupsdAddEvent(CUPSD_EVENT_JOB_COMPLETED, job->printer, job,
+                      "Job canceled because the server could not execute "
+                     "the backend.");
 
-      if (job->num_files < 0)
-      {
-       cupsdLogMessage(CUPSD_LOG_ERROR, "Bad NumFiles value %d on line %d!",
-                       job->num_files, linenum);
-        job->num_files = 0;
-       continue;
+        goto abort_job;
       }
-
-      if (job->num_files > 0)
+      else
       {
-        snprintf(jobfile, sizeof(jobfile), "%s/d%05d-001", RequestRoot,
-                job->id);
-        if (access(jobfile, 0))
-       {
-         cupsdLogMessage(CUPSD_LOG_INFO,
-                         "Data files for job %d have gone away!", job->id);
-          job->num_files = 0;
-         continue;
-       }
-
-        job->filetypes    = calloc(job->num_files, sizeof(mime_type_t *));
-       job->compressions = calloc(job->num_files, sizeof(int));
-
-        if (!job->filetypes || !job->compressions)
-       {
-         cupsdLogMessage(CUPSD_LOG_EMERG,
-                         "Unable to allocate memory for %d files!",
-                         job->num_files);
-          break;
-       }
+       cupsdLogMessage(CUPSD_LOG_INFO, "[Job %d] Started backend %s (PID %d)",
+                       job->id, command, pid);
       }
     }
-    else if (!strcasecmp(line, "File"))
+
+    if (job->current_file == job->num_files)
     {
-      int      number,                 /* File number */
-               compression;            /* Compression value */
-      char     super[MIME_MAX_SUPER],  /* MIME super type */
-               type[MIME_MAX_TYPE];    /* MIME type */
+      cupsdLogMessage(CUPSD_LOG_DEBUG2,
+                      "[Job %d] start_job: Closing print pipes [ %d %d ]...",
+                     job->id, job->print_pipes[0], job->print_pipes[1]);
 
+      cupsdClosePipe(job->print_pipes);
 
-      if (sscanf(value, "%d%*[ \t]%15[^/]/%255s%d", &number, super, type,
-                 &compression) != 4)
-      {
-        cupsdLogMessage(CUPSD_LOG_ERROR, "Bad File on line %d!", linenum);
-       continue;
-      }
+      cupsdLogMessage(CUPSD_LOG_DEBUG2,
+                      "[Job %d] start_job: Closing back pipes [ %d %d ]...",
+                     job->id, job->back_pipes[0], job->back_pipes[1]);
 
-      if (number < 1 || number > job->num_files)
-      {
-        cupsdLogMessage(CUPSD_LOG_ERROR, "Bad File number %d on line %d!",
-                       number, linenum);
-        continue;
-      }
+      cupsdClosePipe(job->back_pipes);
 
-      number --;
+      cupsdLogMessage(CUPSD_LOG_DEBUG2,
+                      "[Job %d] start_job: Closing side pipes [ %d %d ]...",
+                     job->id, job->side_pipes[0], job->side_pipes[1]);
 
-      job->compressions[number] = compression;
-      job->filetypes[number]    = mimeType(MimeDatabase, super, type);
+      cupsdClosePipe(job->side_pipes);
 
-      if (!job->filetypes[number])
-      {
-       /*
-        * If the original MIME type is unknown, auto-type it!
-       */
+      cupsdLogMessage(CUPSD_LOG_DEBUG2,
+                     "[Job %d] start_job: Closing status output pipe %d...",
+                     job->id, job->status_pipes[1]);
 
-        cupsdLogMessage(CUPSD_LOG_ERROR,
-                       "Unknown MIME type %s/%s for file %d of job %d!",
-                       super, type, number + 1, job->id);
+      close(job->status_pipes[1]);
+      job->status_pipes[1] = -1;
+    }
+  }
+  else
+  {
+    filterfds[slot][0] = -1;
+    filterfds[slot][1] = -1;
 
-        snprintf(jobfile, sizeof(jobfile), "%s/d%05d-%03d", RequestRoot,
-                job->id, number + 1);
-        job->filetypes[number] = mimeFileType(MimeDatabase, jobfile, NULL,
-                                             job->compressions + number);
+    if (job->current_file == job->num_files)
+    {
+      cupsdLogMessage(CUPSD_LOG_DEBUG2,
+                      "[Job %d] start_job: Closing print pipes [ %d %d ]...",
+                     job->id, job->print_pipes[0], job->print_pipes[1]);
 
-       /*
-        * If that didn't work, assume it is raw...
-       */
+      cupsdClosePipe(job->print_pipes);
 
-        if (!job->filetypes[number])
-         job->filetypes[number] = mimeType(MimeDatabase, "application",
-                                           "vnd.cups-raw");
-      }
+      cupsdLogMessage(CUPSD_LOG_DEBUG2,
+                     "[Job %d] start_job: Closing status output pipe %d...",
+                     job->id, job->status_pipes[1]);
+
+      close(job->status_pipes[1]);
+      job->status_pipes[1] = -1;
     }
-    else
-      cupsdLogMessage(CUPSD_LOG_ERROR, "Unknown %s directive on line %d!",
-                      line, linenum);
   }
 
-  cupsFileClose(fp);
-}
-
+  cupsdLogMessage(CUPSD_LOG_DEBUG2,
+                 "[Job %d] start_job: Closing filter pipes for slot %d "
+                 "[ %d %d ]...",
+                 job->id, slot, filterfds[slot][0], filterfds[slot][1]);
+  cupsdClosePipe(filterfds[slot]);
 
-/*
- * 'load_next_job_id()' - Load the NextJobId value from the job.cache file.
- */
+  if (printer->remote && job->num_files > 1)
+  {
+    for (i = 0; i < job->num_files; i ++)
+      free(argv[i + 6]);
+  }
 
-static void
-load_next_job_id(const char *filename) /* I - job.cache filename */
-{
-  cups_file_t  *fp;                    /* job.cache file */
-  char         line[1024],             /* Line buffer */
-               *value;                 /* Value on line */
-  int          linenum;                /* Line number in file */
+  free(argv);
+
+  cupsdAddSelect(job->status_buffer->fd, (cupsd_selfunc_t)update_job, NULL,
+                 job);
+
+  cupsdAddEvent(CUPSD_EVENT_JOB_STATE, job->printer, job, "Job #%d started.",
+                job->id);
+
+  return;
 
 
  /*
-  * Read the NextJobId directive from the job.cache file and use
-  * the value (if any).
+  * If we get here, we need to abort the current job and close out all
+  * files and pipes...
   */
 
-  if ((fp = cupsFileOpen(filename, "r")) == NULL)
-  {
-    if (errno != ENOENT)
-      cupsdLogMessage(CUPSD_LOG_ERROR,
-                      "Unable to open job cache file \"%s\": %s",
-                      filename, strerror(errno));
+  abort_job:
 
-    return;
+  for (slot = 0; slot < 2; slot ++)
+  {
+    cupsdLogMessage(CUPSD_LOG_DEBUG2,
+                    "[Job %d] start_job: Closing filter pipes for slot %d "
+                   "[ %d %d ]...",
+                    job->id, slot, filterfds[slot][0], filterfds[slot][1]);
+    cupsdClosePipe(filterfds[slot]);
   }
 
-  cupsdLogMessage(CUPSD_LOG_INFO,
-                  "Loading NextJobId from job cache file \"%s\"...", filename);
+  cupsdLogMessage(CUPSD_LOG_DEBUG2,
+                  "[Job %d] start_job: Closing status pipes [ %d %d ]...",
+                  job->id, job->status_pipes[0], job->status_pipes[1]);
+  cupsdClosePipe(job->status_pipes);
+  cupsdStatBufDelete(job->status_buffer);
 
-  linenum = 0;
+  job->status_buffer = NULL;
 
-  while (cupsFileGetConf(fp, line, sizeof(line), &value, &linenum))
-  {
-    if (!strcasecmp(line, "NextJobId"))
-    {
-      if (value)
-        NextJobId = atoi(value);
+  cupsArrayDelete(filters);
 
-      break;
-    }
+  if (printer->remote && job->num_files > 1)
+  {
+    for (i = 0; i < job->num_files; i ++)
+      free(argv[i + 6]);
   }
 
-  cupsFileClose(fp);
+  free(argv);
+
+  cupsdStopJob(job, 0);
 }
 
 
 /*
- * 'load_request_root()' - Load jobs from the RequestRoot directory.
+ * 'unload_job()' - Unload a job from memory.
  */
 
 static void
-load_request_root(void)
+unload_job(cupsd_job_t *job)           /* I - Job */
 {
-  cups_dir_t           *dir;           /* Directory */
-  cups_dentry_t                *dent;          /* Directory entry */
-  cupsd_job_t          *job;           /* New job */
+  if (!job->attrs)
+    return;
 
+  cupsdLogMessage(CUPSD_LOG_DEBUG, "[Job %d] Unloading...", job->id);
 
- /*
-  * Open the requests directory...
-  */
+  ippDelete(job->attrs);
 
-  cupsdLogMessage(CUPSD_LOG_DEBUG, "Scanning %s for jobs...", RequestRoot);
+  job->attrs           = NULL;
+  job->state           = NULL;
+  job->sheets          = NULL;
+  job->job_sheets      = NULL;
+  job->printer_message = NULL;
+  job->printer_reasons = NULL;
+}
 
-  if ((dir = cupsDirOpen(RequestRoot)) == NULL)
-  {
-    cupsdLogMessage(CUPSD_LOG_ERROR,
-                    "Unable to open spool directory \"%s\": %s",
-                    RequestRoot, strerror(errno));
-    return;
-  }
 
- /*
 * Read all the c##### files...
 */
+/*
* 'update_job()' - Read a status update from a job's filters.
+ */
 
-  while ((dent = cupsDirRead(dir)) != NULL)
-    if (strlen(dent->filename) >= 6 && dent->filename[0] == 'c')
+void
+update_job(cupsd_job_t *job)           /* I - Job to check */
+{
+  int          i;                      /* Looping var */
+  int          copies;                 /* Number of copies printed */
+  char         message[1024],          /* Message text */
+               *ptr;                   /* Pointer update... */
+  int          loglevel,               /* Log level for message */
+               event = 0;              /* Events? */
+
+
+  while ((ptr = cupsdStatBufUpdate(job->status_buffer, &loglevel,
+                                   message, sizeof(message))) != NULL)
+  {
+   /*
+    * Process page and printer state messages as needed...
+    */
+
+    if (loglevel == CUPSD_LOG_PAGE)
     {
      /*
-      * Allocate memory for the job...
+      * Page message; send the message to the page_log file and update the
+      * job sheet count...
       */
 
-      if ((job = calloc(sizeof(cupsd_job_t), 1)) == NULL)
+      if (job->sheets != NULL)
       {
-        cupsdLogMessage(CUPSD_LOG_ERROR, "Ran out of memory for jobs!");
-       cupsDirClose(dir);
+        if (!strncasecmp(message, "total ", 6))
+       {
+        /*
+         * Got a total count of pages from a backend or filter...
+         */
+
+         copies = atoi(message + 6);
+         copies -= job->sheets->values[0].integer; /* Just track the delta */
+       }
+       else if (!sscanf(message, "%*d%d", &copies))
+         copies = 1;
+
+        job->sheets->values[0].integer += copies;
+
+       if (job->printer->page_limit)
+       {
+         cupsd_quota_t *q = cupsdUpdateQuota(job->printer, job->username,
+                                             copies, 0);
+
+#ifdef __APPLE__
+         if (AppleQuotas && q->page_count == -3)
+         {
+          /*
+           * Quota limit exceeded, cancel job in progress immediately...
+           */
+
+           cupsdLogMessage(CUPSD_LOG_INFO,
+                           "[Job %d] Canceled because pages exceed user %s "
+                           "quota limit on printer %s (%s).",
+                           job->id, job->username, job->printer->name,
+                           job->printer->info);
+
+           cupsdCancelJob(job, 1, IPP_JOB_CANCELED);
+           return;
+         }
+#else
+          (void)q;
+#endif /* __APPLE__ */
+       }
+      }
+
+      cupsdLogPage(job, message);
+
+      cupsdAddEvent(CUPSD_EVENT_JOB_PROGRESS, job->printer, job,
+                    "Printed %d page(s).", job->sheets->values[0].integer);
+    }
+    else if (loglevel == CUPSD_LOG_STATE)
+    {
+      if (!strcmp(message, "paused"))
+      {
+        cupsdStopPrinter(job->printer, 1);
        return;
       }
+      else
+      {
+       cupsdSetPrinterReasons(job->printer, message);
+       cupsdAddPrinterHistory(job->printer);
+       event |= CUPSD_EVENT_PRINTER_STATE_CHANGED;
+      }
 
+      update_job_attrs(job);
+    }
+    else if (loglevel == CUPSD_LOG_ATTR)
+    {
      /*
-      * Assign the job ID...
+      * Set attribute(s)...
       */
 
-      job->id             = atoi(dent->filename + 1);
-      job->back_pipes[0]  = -1;
-      job->back_pipes[1]  = -1;
-      job->print_pipes[0] = -1;
-      job->print_pipes[1] = -1;
+      int              num_attrs;      /* Number of attributes */
+      cups_option_t    *attrs;         /* Attributes */
+      const char       *attr;          /* Attribute */
 
-      if (job->id >= NextJobId)
-        NextJobId = job->id + 1;
 
-     /*
-      * Load the job...
-      */
+      num_attrs = cupsParseOptions(message, 0, &attrs);
 
-      cupsdLoadJob(job);
+      if ((attr = cupsGetOption("auth-info-required", num_attrs,
+                                attrs)) != NULL)
+      {
+        cupsdSetAuthInfoRequired(job->printer, attr, NULL);
+       cupsdSaveAllPrinters();
+      }
+
+      if ((attr = cupsGetOption("printer-alert", num_attrs, attrs)) != NULL)
+      {
+        cupsdSetString(&job->printer->alert, attr);
+       event |= CUPSD_EVENT_PRINTER_STATE_CHANGED;
+      }
+
+      if ((attr = cupsGetOption("printer-alert-description", num_attrs,
+                                attrs)) != NULL)
+      {
+        cupsdSetString(&job->printer->alert_description, attr);
+       event |= CUPSD_EVENT_PRINTER_STATE_CHANGED;
+      }
+
+      cupsFreeOptions(num_attrs, attrs);
+    }
+#ifdef __APPLE__
+    else if (!strncmp(message, "recoverable:", 12))
+    {
+      cupsdSetPrinterReasons(job->printer,
+                             "+com.apple.print.recoverable-warning");
+
+      ptr = message + 12;
+      while (isspace(*ptr & 255))
+        ptr ++;
+
+      cupsdSetString(&job->printer->recoverable, ptr);
+      cupsdAddPrinterHistory(job->printer);
+      event |= CUPSD_EVENT_PRINTER_STATE_CHANGED;
+    }
+    else if (!strncmp(message, "recovered:", 10))
+    {
+      cupsdSetPrinterReasons(job->printer,
+                             "-com.apple.print.recoverable-warning");
+
+      ptr = message + 10;
+      while (isspace(*ptr & 255))
+        ptr ++;
 
+      cupsdSetString(&job->printer->recoverable, ptr);
+      cupsdAddPrinterHistory(job->printer);
+      event |= CUPSD_EVENT_PRINTER_STATE_CHANGED;
+    }
+#endif /* __APPLE__ */
+    else if (loglevel <= job->status_level)
+    {
      /*
-      * Insert the job into the array, sorting by job priority and ID...
+      * Some message to show in the printer-state-message attribute...
       */
 
-      cupsArrayAdd(Jobs, job);
+      if (loglevel != CUPSD_LOG_NOTICE)
+        job->status_level = loglevel;
 
-      if (job->state_value < IPP_JOB_STOPPED)
-        cupsArrayAdd(ActiveJobs,job);
-      else
-        cupsdUnloadJob(job);
+      strlcpy(job->printer->state_message, message,
+              sizeof(job->printer->state_message));
+      cupsdAddPrinterHistory(job->printer);
+      event |= CUPSD_EVENT_PRINTER_STATE_CHANGED;
+
+      update_job_attrs(job);
     }
 
-  cupsDirClose(dir);
-}
+    if (!strchr(job->status_buffer->buffer, '\n'))
+      break;
+  }
 
+  if ((event & CUPSD_EVENT_PRINTER_STATE_CHANGED))
+    cupsdAddEvent(CUPSD_EVENT_PRINTER_STATE_CHANGED, job->printer, NULL,
+                 (job->printer->type & CUPS_PRINTER_CLASS) ?
+                     "Class \"%s\" state changed." :
+                     "Printer \"%s\" state changed.",
+                 job->printer->name);
 
-/*
- * 'set_time()' - Set one of the "time-at-xyz" attributes...
- */
+  if (ptr == NULL && !job->status_buffer->bufused)
+  {
+   /*
+    * See if all of the filters and the backend have returned their
+    * exit statuses.
+    */
 
-static void
-set_time(cupsd_job_t *job,             /* I - Job to update */
-         const char  *name)            /* I - Name of attribute */
-{
-  ipp_attribute_t      *attr;          /* Time attribute */
+    for (i = 0; job->filters[i] < 0; i ++);
 
+    if (job->filters[i])
+      return;
 
-  if ((attr = ippFindAttribute(job->attrs, name, IPP_TAG_ZERO)) != NULL)
-  {
-    attr->value_tag         = IPP_TAG_INTEGER;
-    attr->values[0].integer = time(NULL);
+    if (job->current_file >= job->num_files && job->backend > 0)
+      return;
+
+   /*
+    * Handle the end of job stuff...
+    */
+
+    cupsdFinishJob(job);
   }
 }
 
 
 /*
- * 'set_hold_until()' - Set the hold time and update job-hold-until attribute...
+ * 'update_job_attrs()' - Update the job-printer-* attributes.
  */
 
-static void 
-set_hold_until(cupsd_job_t *job,       /* I - Job to update */
-              time_t      holdtime)    /* I - Hold until time */
+void
+update_job_attrs(cupsd_job_t *job)     /* I - Job to update */
 {
-  ipp_attribute_t      *attr;          /* job-hold-until attribute */
-  struct tm            *holddate;      /* Hold date */
-  char                 holdstr[64];    /* Hold time */
+  int                  i;              /* Looping var */
+  int                  num_reasons;    /* Actual number of reasons */
+  const char * const   *reasons;       /* Reasons */
+  static const char    *none = "none", /* "none" */
+                       *paused = "paused";
+                                       /* "paused" */
 
 
  /*
-  * Set the hold_until value and hold the job...
+  * Get/create the job-printer-state-* attributes...
   */
 
-  cupsdLogMessage(CUPSD_LOG_DEBUG, "set_hold_until: hold_until = %d",
-                  (int)holdtime);
+  if (!job->printer_message)
+  {
+    if ((job->printer_message = ippFindAttribute(job->attrs,
+                                                 "job-printer-state-message",
+                                                IPP_TAG_TEXT)) == NULL)
+      job->printer_message = ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_TEXT,
+                                          "job-printer-state-message",
+                                         NULL, "");
+  }
 
-  job->state->values[0].integer = IPP_JOB_HELD;
-  job->state_value              = IPP_JOB_HELD;
-  job->hold_until               = holdtime;
+  if (!job->printer_reasons)
+    job->printer_reasons = ippFindAttribute(job->attrs,
+                                           "job-printer-state-reasons",
+                                           IPP_TAG_KEYWORD);
 
  /*
-  * Update the job-hold-until attribute with a string representing GMT
-  * time (HH:MM:SS)...
+  * If the job isn't printing, return now...
   */
 
-  holddate = gmtime(&holdtime);
-  snprintf(holdstr, sizeof(holdstr), "%d:%d:%d", holddate->tm_hour, 
-          holddate->tm_min, holddate->tm_sec);
+  if (!job->printer)
+    return;
 
-  if ((attr = ippFindAttribute(job->attrs, "job-hold-until",
-                               IPP_TAG_KEYWORD)) == NULL)
-    attr = ippFindAttribute(job->attrs, "job-hold-until", IPP_TAG_NAME);
+ /*
+  * Otherwise copy the printer-state-message value...
+  */
+
+  if (job->printer->state_message[0])
+    cupsdSetString(&(job->printer_message->values[0].string.text),
+                  job->printer->state_message);
 
  /*
-  * Either add the attribute or update the value of the existing one
+  * ... and the printer-state-reasons value...
   */
 
-  if (attr == NULL)
-    attr = ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_KEYWORD,
-                        "job-hold-until", NULL, holdstr);
+  if (job->printer->num_reasons == 0)
+  {
+    num_reasons = 1;
+    reasons     = job->printer->state == IPP_PRINTER_STOPPED ? &paused : &none;
+  }
   else
-    cupsdSetString(&attr->values[0].string.text, holdstr);
+  {
+    num_reasons = job->printer->num_reasons;
+    reasons     = (const char * const *)job->printer->reasons;
+  }
 
-  cupsdSaveJob(job);
+  if (!job->printer_reasons || job->printer_reasons->num_values != num_reasons)
+  {
+    ippDeleteAttribute(job->attrs, job->printer_reasons);
+
+    job->printer_reasons = ippAddStrings(job->attrs,
+                                         IPP_TAG_JOB, IPP_TAG_KEYWORD,
+                                        "job-printer-state-reasons",
+                                        num_reasons, NULL, NULL);
+  }
+
+  for (i = 0; i < num_reasons; i ++)
+    cupsdSetString(&(job->printer_reasons->values[i].string.text), reasons[i]);
 }
 
 
 /*
- * End of "$Id: job.c 5131 2006-02-18 05:31:36Z mike $".
+ * End of "$Id: job.c 6887 2007-08-29 21:52:06Z mike $".
  */