]> git.ipfire.org Git - thirdparty/cups.git/blobdiff - scheduler/job.c
Merge changes from CUPS 1.6svn-r10390.
[thirdparty/cups.git] / scheduler / job.c
index c0aa5b0d610c2aece718d9434608ff69f0d1d83a..53968b897b034f55637eef7f4eb3c34d6be5aa60 100644 (file)
@@ -1,9 +1,9 @@
 /*
  * "$Id: job.c 7902 2008-09-03 14:20:17Z mike $"
  *
- *   Job management routines for the Common UNIX Printing System (CUPS).
+ *   Job management routines for the CUPS scheduler.
  *
- *   Copyright 2007-2009 by Apple Inc.
+ *   Copyright 2007-2012 by Apple Inc.
  *   Copyright 1997-2007 by Easy Software Products, all rights reserved.
  *
  *   These coded instructions, statements, and computer programs are the
  *
  * Contents:
  *
- *   cupsdAddJob()              - Add a new job to the job queue.
- *   cupsdCancelJobs()          - Cancel all jobs for the given
- *                                destination/user.
- *   cupsdCheckJobs()           - Check the pending jobs and start any if the
- *                                destination is available.
- *   cupsdCleanJobs()           - Clean out old jobs.
- *   cupsdContinueJob()         - Continue printing with the next file in a job.
- *   cupsdDeleteJob()           - Free all memory used by a job.
- *   cupsdFreeAllJobs()         - Free all jobs from memory.
- *   cupsdFindJob()             - Find the specified job.
- *   cupsdGetPrinterJobCount()  - Get the number of pending, processing, or held
- *                                jobs in a printer or class.
- *   cupsdGetUserJobCount()     - Get the number of pending, processing, or held
- *                                jobs for a user.
- *   cupsdLoadAllJobs()         - Load all jobs from disk.
- *   cupsdLoadJob()             - Load a single job.
- *   cupsdMoveJob()             - Move the specified job to a different
- *                                destination.
- *   cupsdReleaseJob()          - Release the specified job.
- *   cupsdRestartJob()          - Restart the specified job.
- *   cupsdSaveAllJobs()         - Save a summary of all jobs to disk.
- *   cupsdSaveJob()             - Save a job to disk.
- *   cupsdSetJobHoldUntil()     - Set the hold time for a job.
- *   cupsdSetJobPriority()      - Set the priority of a job, moving it up/down
- *                                in the list as needed.
- *   cupsdSetJobState()         - Set the state of the specified print job.
- *   cupsdStopAllJobs()         - Stop all print jobs.
+*   cupsdAddJob()           - Add a new job to the job queue.
+ *   cupsdCancelJobs()         - Cancel all jobs for the given
+ *                               destination/user.
+ *   cupsdCheckJobs()          - Check the pending jobs and start any if the
+ *                               destination is available.
+ *   cupsdCleanJobs()          - Clean out old jobs.
+ *   cupsdContinueJob()        - Continue printing with the next file in a
+ *                               job.
+ *   cupsdDeleteJob()          - Free all memory used by a job.
+ *   cupsdFreeAllJobs()        - Free all jobs from memory.
+ *   cupsdFindJob()            - Find the specified job.
+ *   cupsdGetPrinterJobCount() - Get the number of pending, processing, or
+ *                               held jobs in a printer or class.
+ *   cupsdGetUserJobCount()    - Get the number of pending, processing, or
+ *                               held jobs for a user.
+ *   cupsdLoadAllJobs()        - Load all jobs from disk.
+ *   cupsdLoadJob()            - Load a single job.
+ *   cupsdMoveJob()            - Move the specified job to a different
+ *                               destination.
+ *   cupsdReleaseJob()         - Release the specified job.
+ *   cupsdRestartJob()         - Restart the specified job.
+ *   cupsdSaveAllJobs()        - Save a summary of all jobs to disk.
+ *   cupsdSaveJob()            - Save a job to disk.
+ *   cupsdSetJobHoldUntil()    - Set the hold time for a job.
+ *   cupsdSetJobPriority()     - Set the priority of a job, moving it up/down
+ *                               in the list as needed.
+ *   cupsdSetJobState()        - Set the state of the specified print job.
+ *   cupsdStopAllJobs()        - Stop all print jobs.
  *   cupsdUnloadCompletedJobs() - Flush completed job history from memory.
- *   compare_active_jobs()      - Compare the job IDs and priorities of two
- *                                jobs.
- *   compare_jobs()             - Compare the job IDs of two jobs.
- *   finalize_job()             - Cleanup after job filter processes and support
- *                                data.
- *   get_options()              - Get a string containing the job options.
- *   ipp_length()               - Compute the size of the buffer needed to hold
- *                                the textual IPP attributes.
- *   load_job_cache()           - Load jobs from the job.cache file.
- *   load_next_job_id()         - Load the NextJobId value from the job.cache
- *                                file.
- *   load_request_root()        - Load jobs from the RequestRoot directory.
- *   set_hold_until()           - Set the hold time and update job-hold-until
- *                                attribute.
- *   set_time()                 - Set one of the "time-at-xyz" attributes.
- *   start_job()                - Start a print job.
- *   stop_job()                 - Stop a print job.
- *   unload_job()               - Unload a job from memory.
- *   update_job()               - Read a status update from a job's filters.
- *   update_job_attrs()         - Update the job-printer-* attributes.
+ *   cupsdUpdateJobs()          - Update the history/file files for all jobs.
+ *   compare_active_jobs()     - Compare the job IDs and priorities of two
+ *                               jobs.
+ *   compare_jobs()            - Compare the job IDs of two jobs.
+ *   dump_job_history()        - Dump any debug messages for a job.
+ *   free_job_history()        - Free any log history.
+ *   finalize_job()            - Cleanup after job filter processes and
+ *                               support data.
+ *   get_options()             - Get a string containing the job options.
+ *   ipp_length()              - Compute the size of the buffer needed to hold
+ *                               the textual IPP attributes.
+ *   load_job_cache()          - Load jobs from the job.cache file.
+ *   load_next_job_id()        - Load the NextJobId value from the job.cache
+ *                               file.
+ *   load_request_root()       - Load jobs from the RequestRoot directory.
+ *   remove_job_files()        - Remove the document files for a job.
+ *   remove_job_history()      - Remove the control file for a job.
+ *   set_time()                - Set one of the "time-at-xyz" attributes.
+ *   start_job()               - Start a print job.
+ *   stop_job()                - Stop a print job.
+ *   unload_job()              - Unload a job from memory.
+ *   update_job()              - Read a status update from a job's filters.
+ *   update_job_attrs()        - Update the job-printer-* attributes.
  */
 
 /*
 #include <grp.h>
 #include <cups/backend.h>
 #include <cups/dir.h>
+#ifdef __APPLE__
+#  include <IOKit/pwr_mgt/IOPMLib.h>
+#  ifdef HAVE_IOKIT_PWR_MGT_IOPMLIBPRIVATE_H
+#    include <IOKit/pwr_mgt/IOPMLibPrivate.h>
+#  endif /* HAVE_IOKIT_PWR_MGT_IOPMLIBPRIVATE_H */
+#endif /* __APPLE__ */
 
 
 /*
@@ -165,15 +175,18 @@ static mime_filter_t      gziptoany_filter =
 
 static int     compare_active_jobs(void *first, void *second, void *data);
 static int     compare_jobs(void *first, void *second, void *data);
-static void    finalize_job(cupsd_job_t *job);
+static void    dump_job_history(cupsd_job_t *job);
+static void    finalize_job(cupsd_job_t *job, int set_job_state);
+static void    free_job_history(cupsd_job_t *job);
 static char    *get_options(cupsd_job_t *job, int banner_page, char *copies,
                             size_t copies_size, char *title,
                             size_t title_size);
-static int     ipp_length(ipp_t *ipp);
+static size_t  ipp_length(ipp_t *ipp);
 static void    load_job_cache(const char *filename);
 static void    load_next_job_id(const char *filename);
 static void    load_request_root(void);
-static void    set_hold_until(cupsd_job_t *job, time_t holdtime);
+static void    remove_job_files(cupsd_job_t *job);
+static void    remove_job_history(cupsd_job_t *job);
 static void    set_time(cupsd_job_t *job, const char *name);
 static void    start_job(cupsd_job_t *job, cupsd_printer_t *printer);
 static void    stop_job(cupsd_job_t *job, cupsd_jobaction_t action);
@@ -249,7 +262,7 @@ cupsdCancelJobs(const char *dest,   /* I - Destination to cancel */
       if (purge)
        cupsdSetJobState(job, IPP_JOB_CANCELED, CUPSD_JOB_PURGE,
                         "Job purged by user.");
-      else
+      else if (job->state_value < IPP_JOB_CANCELED)
        cupsdSetJobState(job, IPP_JOB_CANCELED, CUPSD_JOB_DEFAULT,
                         "Job canceled by user.");
     }
@@ -290,10 +303,24 @@ cupsdCheckJobs(void)
 
     if (job->kill_time && job->kill_time <= curtime)
     {
+      cupsdLogMessage(CUPSD_LOG_ERROR, "[Job %d] Stopping unresponsive job.",
+                     job->id);
+
       stop_job(job, CUPSD_JOB_FORCE);
       continue;
     }
 
+   /*
+    * Cancel stuck jobs...
+    */
+
+    if (job->cancel_time && job->cancel_time <= curtime)
+    {
+      cupsdSetJobState(job, IPP_JOB_CANCELED, CUPSD_JOB_DEFAULT,
+                       "Canceling stuck job after %d seconds.", MaxJobTime);
+      continue;
+    }
+
    /*
     * Start held jobs if they are ready...
     */
@@ -343,14 +370,16 @@ cupsdCheckJobs(void)
     * Start pending jobs if the destination is available...
     */
 
-    if (job->state_value == IPP_JOB_PENDING && !NeedReload && !Sleeping &&
-        !job->printer)
+    if (job->state_value == IPP_JOB_PENDING && !NeedReload &&
+#ifndef kIOPMAssertionTypeDenySystemSleep
+        !Sleeping &&
+#endif /* !kIOPMAssertionTypeDenySystemSleep */
+        !DoingShutdown && !job->printer)
     {
       printer = cupsdFindDest(job->dest);
       pclass  = NULL;
 
-      while (printer &&
-             (printer->type & (CUPS_PRINTER_IMPLICIT | CUPS_PRINTER_CLASS)))
+      while (printer && (printer->type & CUPS_PRINTER_CLASS))
       {
        /*
         * If the class is remote, just pass it to the remote server...
@@ -402,10 +431,7 @@ cupsdCheckJobs(void)
           cupsdMarkDirty(CUPSD_DIRTY_JOBS);
        }
 
-        if ((!(printer->type & CUPS_PRINTER_DISCOVERED) && /* Printer is local */
-            printer->state == IPP_PRINTER_IDLE) ||     /* and idle, OR */
-           ((printer->type & CUPS_PRINTER_DISCOVERED) && /* Printer is remote */
-            !printer->job))                            /* and not printing */
+        if (printer->state == IPP_PRINTER_IDLE)
         {
         /*
          * Start the job...
@@ -427,16 +453,56 @@ void
 cupsdCleanJobs(void)
 {
   cupsd_job_t  *job;                   /* Current job */
+  time_t       curtime;                /* Current time */
+
 
+  cupsdLogMessage(CUPSD_LOG_DEBUG2,
+                  "cupsdCleanJobs: MaxJobs=%d, JobHistory=%d, JobFiles=%d",
+                  MaxJobs, JobHistory, JobFiles);
 
-  if (MaxJobs <= 0)
+  if (MaxJobs <= 0 && JobHistory == INT_MAX && JobFiles == INT_MAX)
     return;
 
+  curtime          = time(NULL);
+  JobHistoryUpdate = 0;
+
   for (job = (cupsd_job_t *)cupsArrayFirst(Jobs);
-       job && cupsArrayCount(Jobs) >= MaxJobs;
+       job;
        job = (cupsd_job_t *)cupsArrayNext(Jobs))
+  {
     if (job->state_value >= IPP_JOB_CANCELED && !job->printer)
-      cupsdDeleteJob(job, CUPSD_JOB_PURGE);
+    {
+     /*
+      * Expire old jobs (or job files)...
+      */
+
+      if ((MaxJobs > 0 && cupsArrayCount(Jobs) >= MaxJobs) ||
+          (job->history_time && job->history_time <= curtime))
+      {
+        cupsdLogJob(job, CUPSD_LOG_DEBUG, "Removing from history.");
+       cupsdDeleteJob(job, CUPSD_JOB_PURGE);
+      }
+      else if (job->file_time && job->file_time <= curtime)
+      {
+        cupsdLogJob(job, CUPSD_LOG_DEBUG, "Removing document files.");
+        remove_job_files(job);
+
+        if (job->history_time < JobHistoryUpdate || !JobHistoryUpdate)
+         JobHistoryUpdate = job->history_time;
+      }
+      else
+      {
+        if (job->history_time < JobHistoryUpdate || !JobHistoryUpdate)
+         JobHistoryUpdate = job->history_time;
+
+       if (job->file_time < JobHistoryUpdate || !JobHistoryUpdate)
+         JobHistoryUpdate = job->file_time;
+      }
+    }
+  }
+
+  cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdCleanJobs: JobHistoryUpdate=%ld",
+                  (long)JobHistoryUpdate);
 }
 
 
@@ -458,7 +524,7 @@ cupsdContinueJob(cupsd_job_t *job)  /* I - Job */
   ipp_attribute_t      *attr;          /* Current attribute */
   const char           *ptr,           /* Pointer into value */
                        *abort_message; /* Abort message */
-  ipp_jstate_t         abort_state = IPP_JOB_ABORTED;
+  ipp_jstate_t         abort_state = IPP_JOB_STOPPED;
                                        /* New job state on abort */
   struct stat          backinfo;       /* Backend file information */
   int                  backroot;       /* Run backend as root? */
@@ -467,6 +533,7 @@ cupsdContinueJob(cupsd_job_t *job)  /* I - Job */
   int                  filterfds[2][2] = { { -1, -1 }, { -1, -1 } };
                                        /* Pipes used between filters */
   int                  envc;           /* Number of environment variables */
+  struct stat          fileinfo;       /* Job file information */
   char                 **argv = NULL,  /* Filter command-line arguments */
                        filename[1024], /* Job filename */
                        command[1024],  /* Full path to command */
@@ -475,7 +542,7 @@ cupsdContinueJob(cupsd_job_t *job)  /* I - Job */
                                        /* Job title string */
                        copies[255],    /* # copies string */
                        *options,       /* Options string */
-                       *envp[MAX_ENV + 19],
+                       *envp[MAX_ENV + 21],
                                        /* Environment variables */
                        charset[255],   /* CHARSET env variable */
                        class_name[255],/* CLASS env variable */
@@ -492,6 +559,8 @@ cupsdContinueJob(cupsd_job_t *job)  /* I - Job */
                        apple_language[255],
                                        /* APPLE_LANGUAGE env variable */
 #endif /* __APPLE__ */
+                       auth_info_required[255],
+                                       /* AUTH_INFO_REQUIRED env variable */
                        ppd[1024],      /* PPD env variable */
                        printer_info[255],
                                        /* PRINTER_INFO env variable */
@@ -499,6 +568,8 @@ cupsdContinueJob(cupsd_job_t *job)  /* I - Job */
                                        /* PRINTER_LOCATION env variable */
                        printer_name[255],
                                        /* PRINTER env variable */
+                       *printer_state_reasons = NULL,
+                                       /* PRINTER_STATE_REASONS env var */
                        rip_max_cache[255];
                                        /* RIP_MAX_CACHE env variable */
 
@@ -535,16 +606,25 @@ cupsdContinueJob(cupsd_job_t *job)        /* I - Job */
     * Local jobs get filtered...
     */
 
-    filters = mimeFilter(MimeDatabase, job->filetypes[job->current_file],
-                         job->printer->filetype, &(job->cost));
+    snprintf(filename, sizeof(filename), "%s/d%05d-%03d", RequestRoot,
+             job->id, job->current_file + 1);
+    if (stat(filename, &fileinfo))
+      fileinfo.st_size = 0;
+
+    filters = mimeFilter2(MimeDatabase, job->filetypes[job->current_file],
+                          fileinfo.st_size, job->printer->filetype,
+                          &(job->cost));
 
     if (!filters)
     {
       cupsdLogJob(job, CUPSD_LOG_ERROR,
-                 "Unable to convert file %d to printable format!",
+                 "Unable to convert file %d to printable format.",
                  job->current_file);
 
       abort_message = "Aborting job because it cannot be printed.";
+      abort_state   = IPP_JOB_ABORTED;
+
+      ippSetString(job->attrs, &job->reasons, 0, "document-unprintable-error");
       goto abort_job;
     }
 
@@ -649,7 +729,6 @@ cupsdContinueJob(cupsd_job_t *job)  /* I - Job */
 
       cupsArrayDelete(filters);
 
-      abort_state = IPP_JOB_STOPPED;
       abort_message = "Stopping job because the scheduler ran out of memory.";
 
       goto abort_job;
@@ -681,7 +760,6 @@ cupsdContinueJob(cupsd_job_t *job)  /* I - Job */
       cupsdLogJob(job, CUPSD_LOG_DEBUG,
                  "Unable to add port monitor - %s", strerror(errno));
 
-      abort_state   = IPP_JOB_STOPPED;
       abort_message = "Stopping job because the scheduler ran out of memory.";
 
       goto abort_job;
@@ -695,10 +773,14 @@ cupsdContinueJob(cupsd_job_t *job)        /* I - Job */
   if (cupsArrayCount(filters) > MAX_FILTERS)
   {
     cupsdLogJob(job, CUPSD_LOG_DEBUG,
-               "Too many filters (%d > %d), unable to print!",
+               "Too many filters (%d > %d), unable to print.",
                cupsArrayCount(filters), MAX_FILTERS);
 
     abort_message = "Aborting job because it needs too many filters to print.";
+    abort_state   = IPP_JOB_ABORTED;
+
+    ippSetString(job->attrs, &job->reasons, 0, "document-unprintable-error");
+
     goto abort_job;
   }
 
@@ -712,7 +794,7 @@ cupsdContinueJob(cupsd_job_t *job)  /* I - Job */
     if ((job->job_sheets =
          ippFindAttribute(job->attrs, "job-sheets", IPP_TAG_ZERO)) != NULL)
       cupsdLogJob(job, CUPSD_LOG_DEBUG,
-                 "... but someone added one without setting job_sheets!");
+                 "... but someone added one without setting job_sheets.");
   }
   else if (job->job_sheets->num_values == 1)
     cupsdLogJob(job, CUPSD_LOG_DEBUG, "job-sheets=%s",
@@ -722,15 +804,15 @@ cupsdContinueJob(cupsd_job_t *job)        /* I - Job */
                 job->job_sheets->values[0].string.text,
                 job->job_sheets->values[1].string.text);
 
-  if (job->printer->type & (CUPS_PRINTER_REMOTE | CUPS_PRINTER_IMPLICIT))
+  if (job->printer->type & CUPS_PRINTER_REMOTE)
     banner_page = 0;
   else if (job->job_sheets == NULL)
     banner_page = 0;
-  else if (strcasecmp(job->job_sheets->values[0].string.text, "none") != 0 &&
+  else if (_cups_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 &&
+          _cups_strcasecmp(job->job_sheets->values[1].string.text, "none") != 0 &&
           job->current_file == (job->num_files - 1))
     banner_page = 1;
   else
@@ -739,7 +821,6 @@ cupsdContinueJob(cupsd_job_t *job)  /* I - Job */
   if ((options = get_options(job, banner_page, copies, sizeof(copies), title,
                              sizeof(title))) == NULL)
   {
-    abort_state   = IPP_JOB_STOPPED;
     abort_message = "Stopping job because the scheduler ran out of memory.";
 
     goto abort_job;
@@ -773,7 +854,6 @@ cupsdContinueJob(cupsd_job_t *job)  /* I - Job */
     cupsdLogMessage(CUPSD_LOG_DEBUG, "Unable to allocate argument array - %s",
                     strerror(errno));
 
-    abort_state   = IPP_JOB_STOPPED;
     abort_message = "Stopping job because the scheduler ran out of memory.";
 
     goto abort_job;
@@ -872,8 +952,60 @@ cupsdContinueJob(cupsd_job_t *job) /* I - Job */
   snprintf(printer_location, sizeof(printer_name), "PRINTER_LOCATION=%s",
            job->printer->location ? job->printer->location : "");
   snprintf(printer_name, sizeof(printer_name), "PRINTER=%s", job->printer->name);
+  if (job->printer->num_reasons > 0)
+  {
+    char       *psrptr;                /* Pointer into PRINTER_STATE_REASONS */
+    size_t     psrlen;                 /* Size of PRINTER_STATE_REASONS */
+
+    for (psrlen = 22, i = 0; i < job->printer->num_reasons; i ++)
+      psrlen += strlen(job->printer->reasons[i]) + 1;
+
+    if ((printer_state_reasons = malloc(psrlen)) != NULL)
+    {
+     /*
+      * All of these strcpy's are safe because we allocated the psr string...
+      */
+
+      strcpy(printer_state_reasons, "PRINTER_STATE_REASONS=");
+      for (psrptr = printer_state_reasons + 22, i = 0;
+           i < job->printer->num_reasons;
+          i ++)
+      {
+        if (i)
+         *psrptr++ = ',';
+       strcpy(psrptr, job->printer->reasons[i]);
+       psrptr += strlen(psrptr);
+      }
+    }
+  }
   snprintf(rip_max_cache, sizeof(rip_max_cache), "RIP_MAX_CACHE=%s", RIPCache);
 
+  if (job->printer->num_auth_info_required == 1)
+    snprintf(auth_info_required, sizeof(auth_info_required),
+             "AUTH_INFO_REQUIRED=%s",
+            job->printer->auth_info_required[0]);
+  else if (job->printer->num_auth_info_required == 2)
+    snprintf(auth_info_required, sizeof(auth_info_required),
+             "AUTH_INFO_REQUIRED=%s,%s",
+            job->printer->auth_info_required[0],
+            job->printer->auth_info_required[1]);
+  else if (job->printer->num_auth_info_required == 3)
+    snprintf(auth_info_required, sizeof(auth_info_required),
+             "AUTH_INFO_REQUIRED=%s,%s,%s",
+            job->printer->auth_info_required[0],
+            job->printer->auth_info_required[1],
+            job->printer->auth_info_required[2]);
+  else if (job->printer->num_auth_info_required == 4)
+    snprintf(auth_info_required, sizeof(auth_info_required),
+             "AUTH_INFO_REQUIRED=%s,%s,%s,%s",
+            job->printer->auth_info_required[0],
+            job->printer->auth_info_required[1],
+            job->printer->auth_info_required[2],
+            job->printer->auth_info_required[3]);
+  else
+    strlcpy(auth_info_required, "AUTH_INFO_REQUIRED=none",
+           sizeof(auth_info_required));
+
   envc = cupsdLoadEnv(envp, (int)(sizeof(envp) / sizeof(envp[0])));
 
   envp[envc ++] = charset;
@@ -888,6 +1020,8 @@ cupsdContinueJob(cupsd_job_t *job) /* I - Job */
   envp[envc ++] = printer_info;
   envp[envc ++] = printer_location;
   envp[envc ++] = printer_name;
+  envp[envc ++] = printer_state_reasons ? printer_state_reasons :
+                                          "PRINTER_STATE_REASONS=none";
   envp[envc ++] = banner_page ? "CUPS_FILETYPE=job-sheet" :
                                 "CUPS_FILETYPE=document";
 
@@ -900,9 +1034,13 @@ cupsdContinueJob(cupsd_job_t *job)        /* I - Job */
 
     if (filter && filter->dst)
     {
-      snprintf(final_content_type, sizeof(final_content_type),
-              "FINAL_CONTENT_TYPE=%s/%s",
-              filter->dst->super, filter->dst->type);
+      if ((ptr = strchr(filter->dst->type, '/')) != NULL)
+       snprintf(final_content_type, sizeof(final_content_type),
+                "FINAL_CONTENT_TYPE=%s", ptr + 1);
+      else
+       snprintf(final_content_type, sizeof(final_content_type),
+                "FINAL_CONTENT_TYPE=%s/%s", filter->dst->super,
+                filter->dst->type);
       envp[envc ++] = final_content_type;
     }
   }
@@ -924,23 +1062,24 @@ cupsdContinueJob(cupsd_job_t *job)       /* I - Job */
     envp[envc ++] = classification;
   }
 
-  if (job->dtype & (CUPS_PRINTER_CLASS | CUPS_PRINTER_IMPLICIT))
+  if (job->dtype & CUPS_PRINTER_CLASS)
   {
     snprintf(class_name, sizeof(class_name), "CLASS=%s", job->dest);
     envp[envc ++] = class_name;
   }
 
-  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;
+  envp[envc ++] = auth_info_required;
+
+  for (i = 0;
+       i < (int)(sizeof(job->auth_env) / sizeof(job->auth_env[0]));
+       i ++)
+    if (job->auth_env[i])
+      envp[envc ++] = job->auth_env[i];
+    else
+      break;
 
-#ifdef HAVE_GSSAPI
-  if (job->ccname)
-    envp[envc ++] = job->ccname;
-#endif /* HAVE_GSSAPI */
+  if (job->auth_uid)
+    envp[envc ++] = job->auth_uid;
 
   envp[envc] = NULL;
 
@@ -963,6 +1102,9 @@ cupsdContinueJob(cupsd_job_t *job) /* I - Job */
   * Now create processes for all of the filters...
   */
 
+  cupsdSetPrinterReasons(job->printer, "-cups-missing-filter-warning,"
+                                      "cups-insecure-filter-warning");
+
   for (i = 0, slot = 0, filter = (mime_filter_t *)cupsArrayFirst(filters);
        filter;
        i ++, filter = (mime_filter_t *)cupsArrayNext(filters))
@@ -985,7 +1127,8 @@ cupsdContinueJob(cupsd_job_t *job) /* I - Job */
     }
     else
     {
-      if (job->current_file == 1)
+      if (job->current_file == 1 ||
+          (job->printer->pc && job->printer->pc->single_file))
       {
        if (strncmp(job->printer->device_uri, "file:", 5) != 0)
        {
@@ -1048,7 +1191,7 @@ cupsdContinueJob(cupsd_job_t *job)        /* I - Job */
       cupsdLogJob(job, CUPSD_LOG_ERROR, "Unable to start filter \"%s\" - %s.",
                  filter->filter, strerror(errno));
 
-      abort_message = "Stopped job because the scheduler could not execute a "
+      abort_message = "Stopping job because the scheduler could not execute a "
                      "filter.";
 
       goto abort_job;
@@ -1070,7 +1213,8 @@ cupsdContinueJob(cupsd_job_t *job)        /* I - Job */
 
   if (strncmp(job->printer->device_uri, "file:", 5) != 0)
   {
-    if (job->current_file == 1 || job->printer->remote)
+    if (job->current_file == 1 || job->printer->remote ||
+        (job->printer->pc && job->printer->pc->single_file))
     {
       sscanf(job->printer->device_uri, "%254[^:]", scheme);
       snprintf(command, sizeof(command), "%s/backend/%s", ServerBin, scheme);
@@ -1110,9 +1254,12 @@ cupsdContinueJob(cupsd_job_t *job)       /* I - Job */
       }
     }
 
+    if (job->current_file == job->num_files ||
+        (job->printer->pc && job->printer->pc->single_file))
+      cupsdClosePipe(job->print_pipes);
+
     if (job->current_file == job->num_files)
     {
-      cupsdClosePipe(job->print_pipes);
       cupsdClosePipe(job->back_pipes);
       cupsdClosePipe(job->side_pipes);
 
@@ -1125,10 +1272,12 @@ cupsdContinueJob(cupsd_job_t *job)      /* I - Job */
     filterfds[slot][0] = -1;
     filterfds[slot][1] = -1;
 
-    if (job->current_file == job->num_files)
-    {
+    if (job->current_file == job->num_files ||
+        (job->printer->pc && job->printer->pc->single_file))
       cupsdClosePipe(job->print_pipes);
 
+    if (job->current_file == job->num_files)
+    {
       close(job->status_pipes[1]);
       job->status_pipes[1] = -1;
     }
@@ -1143,6 +1292,8 @@ cupsdContinueJob(cupsd_job_t *job)        /* I - Job */
   }
 
   free(argv);
+  if (printer_state_reasons)
+    free(printer_state_reasons);
 
   cupsdAddSelect(job->status_buffer->fd, (cupsd_selfunc_t)update_job, NULL,
                  job);
@@ -1150,16 +1301,6 @@ cupsdContinueJob(cupsd_job_t *job)       /* I - Job */
   cupsdAddEvent(CUPSD_EVENT_JOB_STATE, job->printer, job, "Job #%d started.",
                 job->id);
 
- /*
-  * If we get here than we are able to run the printer driver filters, so clear
-  * the missing and insecure warnings...
-  */
-
-  if (cupsdSetPrinterReasons(job->printer, "-cups-missing-filter-warning,"
-                                          "cups-insecure-filter-warning"))
-    cupsdAddEvent(CUPSD_EVENT_PRINTER_STATE, job->printer, NULL,
-                  "Printer drivers now functional.");
-
   return;
 
 
@@ -1189,6 +1330,9 @@ cupsdContinueJob(cupsd_job_t *job)        /* I - Job */
     free(argv);
   }
 
+  if (printer_state_reasons)
+    free(printer_state_reasons);
+
   cupsdClosePipe(job->print_pipes);
   cupsdClosePipe(job->back_pipes);
   cupsdClosePipe(job->side_pipes);
@@ -1206,6 +1350,9 @@ cupsdContinueJob(cupsd_job_t *job)        /* I - Job */
   cupsdSetPrinterState(job->printer, IPP_PRINTER_IDLE, 0);
   update_job_attrs(job, 0);
 
+  if (job->history)
+    free_job_history(job);
+
   cupsArrayRemove(PrintingJobs, job);
 
  /*
@@ -1225,43 +1372,26 @@ void
 cupsdDeleteJob(cupsd_job_t       *job, /* I - Job */
                cupsd_jobaction_t action)/* I - Action */
 {
-  if (job->printer)
-    finalize_job(job);
+  int  i;                              /* Looping var */
 
-  if (action == CUPSD_JOB_PURGE)
-  {
-   /*
-    * Remove the job info file...
-    */
 
-    char       filename[1024];         /* Job filename */
+  if (job->printer)
+    finalize_job(job, 1);
 
-    snprintf(filename, sizeof(filename), "%s/c%05d", RequestRoot,
-            job->id);
-    unlink(filename);
-  }
+  if (action == CUPSD_JOB_PURGE)
+    remove_job_history(job);
 
   cupsdClearString(&job->username);
   cupsdClearString(&job->dest);
-  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 */
+  for (i = 0;
+       i < (int)(sizeof(job->auth_env) / sizeof(job->auth_env[0]));
+       i ++)
+    cupsdClearString(job->auth_env + i);
+  cupsdClearString(&job->auth_uid);
 
-  if (job->num_files > 0)
+  if (action == CUPSD_JOB_PURGE)
+    remove_job_files(job);
+  else if (job->num_files > 0)
   {
     free(job->compressions);
     free(job->filetypes);
@@ -1269,6 +1399,9 @@ cupsdDeleteJob(cupsd_job_t       *job,    /* I - Job */
     job->num_files = 0;
   }
 
+  if (job->history)
+    free_job_history(job);
+
   unload_job(job);
 
   cupsArrayRemove(Jobs, job);
@@ -1338,7 +1471,7 @@ cupsdGetPrinterJobCount(
   for (job = (cupsd_job_t *)cupsArrayFirst(ActiveJobs), count = 0;
        job;
        job = (cupsd_job_t *)cupsArrayNext(ActiveJobs))
-    if (job->dest && !strcasecmp(job->dest, dest))
+    if (job->dest && !_cups_strcasecmp(job->dest, dest))
       count ++;
 
   return (count);
@@ -1361,7 +1494,7 @@ cupsdGetUserJobCount(
   for (job = (cupsd_job_t *)cupsArrayFirst(ActiveJobs), count = 0;
        job;
        job = (cupsd_job_t *)cupsArrayNext(ActiveJobs))
-    if (!strcasecmp(job->username, username))
+    if (!_cups_strcasecmp(job->username, username))
       count ++;
 
   return (count);
@@ -1449,6 +1582,7 @@ cupsdLoadAllJobs(void)
 int                                    /* O - 1 on success, 0 on failure */
 cupsdLoadJob(cupsd_job_t *job)         /* I - Job */
 {
+  int                  i;              /* Looping var */
   char                 jobfile[1024];  /* Job filename */
   cups_file_t          *fp;            /* Job file */
   int                  fileid;         /* Current file ID */
@@ -1469,7 +1603,7 @@ cupsdLoadJob(cupsd_job_t *job)            /* I - Job */
 
   if ((job->attrs = ippNew()) == NULL)
   {
-    cupsdLogJob(job, CUPSD_LOG_ERROR, "Ran out of memory for job attributes!");
+    cupsdLogJob(job, CUPSD_LOG_ERROR, "Ran out of memory for job attributes.");
     return (0);
   }
 
@@ -1480,18 +1614,13 @@ cupsdLoadJob(cupsd_job_t *job)          /* I - Job */
   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,
-                   "[Job %d] Unable to open job control file \"%s\" - %s!",
-                   job->id, jobfile, strerror(errno));
+  if ((fp = cupsdOpenConfFile(jobfile)) == NULL)
     goto error;
-  }
 
   if (ippReadIO(fp, (ipp_iocb_t)cupsFileRead, 1, NULL, job->attrs) != IPP_DATA)
   {
     cupsdLogMessage(CUPSD_LOG_ERROR,
-                   "[Job %d] Unable to read job control file \"%s\"!", job->id,
+                   "[Job %d] Unable to read job control file \"%s\".", job->id,
                    jobfile);
     cupsFileClose(fp);
     goto error;
@@ -1507,7 +1636,7 @@ cupsdLoadJob(cupsd_job_t *job)            /* I - Job */
   {
     cupsdLogMessage(CUPSD_LOG_ERROR,
                    "[Job %d] Missing or bad time-at-creation attribute in "
-                   "control file!", job->id);
+                   "control file.", job->id);
     goto error;
   }
 
@@ -1516,11 +1645,40 @@ cupsdLoadJob(cupsd_job_t *job)          /* I - Job */
   {
     cupsdLogMessage(CUPSD_LOG_ERROR,
                    "[Job %d] Missing or bad job-state attribute in control "
-                   "file!", job->id);
+                   "file.", job->id);
     goto error;
   }
 
-  job->state_value = (ipp_jstate_t)job->state->values[0].integer;
+  job->state_value  = (ipp_jstate_t)job->state->values[0].integer;
+  job->file_time    = 0;
+  job->history_time = 0;
+
+  if (job->state_value >= IPP_JOB_CANCELED &&
+      (attr = ippFindAttribute(job->attrs, "time-at-completed",
+                              IPP_TAG_INTEGER)) != NULL)
+  {
+    if (JobHistory < INT_MAX)
+      job->history_time = attr->values[0].integer + JobHistory;
+    else
+      job->history_time = INT_MAX;
+
+    if (job->history_time < time(NULL))
+      goto error;                      /* Expired, remove from history */
+
+    if (job->history_time < JobHistoryUpdate || !JobHistoryUpdate)
+      JobHistoryUpdate = job->history_time;
+
+    if (JobFiles < INT_MAX)
+      job->file_time = attr->values[0].integer + JobFiles;
+    else
+      job->file_time = INT_MAX;
+
+    if (job->file_time < JobHistoryUpdate || !JobHistoryUpdate)
+      JobHistoryUpdate = job->file_time;
+
+    cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdLoadJob: JobHistoryUpdate=%ld",
+                   (long)JobHistoryUpdate);
+  }
 
   if (!job->dest)
   {
@@ -1528,7 +1686,7 @@ cupsdLoadJob(cupsd_job_t *job)            /* I - Job */
                                  IPP_TAG_URI)) == NULL)
     {
       cupsdLogMessage(CUPSD_LOG_ERROR,
-                     "[Job %d] No job-printer-uri attribute in control file!",
+                     "[Job %d] No job-printer-uri attribute in control file.",
                      job->id);
       goto error;
     }
@@ -1537,7 +1695,7 @@ cupsdLoadJob(cupsd_job_t *job)            /* I - Job */
                                   &destptr)) == NULL)
     {
       cupsdLogMessage(CUPSD_LOG_ERROR,
-                     "[Job %d] Unable to queue job for destination \"%s\"!",
+                     "[Job %d] Unable to queue job for destination \"%s\".",
                      job->id, attr->values[0].string.text);
       goto error;
     }
@@ -1547,11 +1705,74 @@ cupsdLoadJob(cupsd_job_t *job)          /* I - Job */
   else if ((destptr = cupsdFindDest(job->dest)) == NULL)
   {
     cupsdLogMessage(CUPSD_LOG_ERROR,
-                   "[Job %d] Unable to queue job for destination \"%s\"!",
+                   "[Job %d] Unable to queue job for destination \"%s\".",
                    job->id, job->dest);
     goto error;
   }
 
+  if ((job->reasons = ippFindAttribute(job->attrs, "job-state-reasons",
+                                       IPP_TAG_KEYWORD)) == NULL)
+  {
+    const char *reason;                /* job-state-reason keyword */
+
+    cupsdLogMessage(CUPSD_LOG_DEBUG,
+                   "[Job %d] Adding missing job-state-reasons attribute to "
+                   " control file.", job->id);
+
+    switch (job->state_value)
+    {
+      default :
+      case IPP_JOB_PENDING :
+          if (destptr->state == IPP_PRINTER_STOPPED)
+            reason = "printer-stopped";
+          else
+            reason = "none";
+          break;
+
+      case IPP_JOB_HELD :
+          if ((attr = ippFindAttribute(job->attrs, "job-hold-until",
+                                       IPP_TAG_ZERO)) != NULL &&
+              (attr->value_tag == IPP_TAG_NAME ||
+              attr->value_tag == IPP_TAG_NAMELANG ||
+              attr->value_tag == IPP_TAG_KEYWORD) &&
+             strcmp(attr->values[0].string.text, "no-hold"))
+           reason = "job-hold-until-specified";
+         else
+           reason = "job-incoming";
+          break;
+
+      case IPP_JOB_PROCESSING :
+          reason = "job-printing";
+          break;
+
+      case IPP_JOB_STOPPED :
+          reason = "job-stopped";
+          break;
+
+      case IPP_JOB_CANCELED :
+          reason = "job-canceled-by-user";
+          break;
+
+      case IPP_JOB_ABORTED :
+          reason = "aborted-by-system";
+          break;
+
+      case IPP_JOB_COMPLETED :
+          reason = "job-completed-successfully";
+          break;
+    }
+
+    job->reasons = ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_KEYWORD,
+                                "job-state-reasons", NULL, reason);
+  }
+  else if (job->state_value == IPP_JOB_PENDING)
+  {
+    if (destptr->state == IPP_PRINTER_STOPPED)
+      ippSetString(job->attrs, &job->reasons, 0, "printer-stopped");
+    else
+      ippSetString(job->attrs, &job->reasons, 0, "none");
+  }
+
   job->sheets     = ippFindAttribute(job->attrs, "job-media-sheets-completed",
                                      IPP_TAG_INTEGER);
   job->job_sheets = ippFindAttribute(job->attrs, "job-sheets", IPP_TAG_NAME);
@@ -1563,7 +1784,7 @@ cupsdLoadJob(cupsd_job_t *job)            /* I - Job */
     {
       cupsdLogMessage(CUPSD_LOG_ERROR,
                      "[Job %d] Missing or bad job-priority attribute in "
-                     "control file!", job->id);
+                     "control file.", job->id);
       goto error;
     }
 
@@ -1577,7 +1798,7 @@ cupsdLoadJob(cupsd_job_t *job)            /* I - Job */
     {
       cupsdLogMessage(CUPSD_LOG_ERROR,
                      "[Job %d] Missing or bad job-originating-user-name "
-                     "attribute in control file!", job->id);
+                     "attribute in control file.", job->id);
       goto error;
     }
 
@@ -1645,9 +1866,32 @@ cupsdLoadJob(cupsd_job_t *job)           /* I - Job */
         if (!compressions || !filetypes)
        {
           cupsdLogMessage(CUPSD_LOG_ERROR,
-                         "[Job %d] Ran out of memory for job file types!",
+                         "[Job %d] Ran out of memory for job file types.",
                          job->id);
-         return (1);
+
+         ippDelete(job->attrs);
+         job->attrs = NULL;
+
+         if (compressions)
+           free(compressions);
+
+         if (filetypes)
+           free(filetypes);
+
+         if (job->compressions)
+         {
+           free(job->compressions);
+           job->compressions = NULL;
+         }
+
+         if (job->filetypes)
+         {
+           free(job->filetypes);
+           job->filetypes = NULL;
+         }
+
+         job->num_files = 0;
+         return (0);
        }
 
         job->compressions = compressions;
@@ -1672,32 +1916,59 @@ cupsdLoadJob(cupsd_job_t *job)          /* I - Job */
   {
     snprintf(jobfile, sizeof(jobfile), "%s/a%05d", RequestRoot, job->id);
 
-    cupsdClearString(&job->auth_username);
-    cupsdClearString(&job->auth_domain);
-    cupsdClearString(&job->auth_password);
+    for (i = 0;
+        i < (int)(sizeof(job->auth_env) / sizeof(job->auth_env[0]));
+        i ++)
+      cupsdClearString(job->auth_env + i);
+    cupsdClearString(&job->auth_uid);
 
     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 */
+      int      bytes,                  /* Size of auth data */
+               linenum = 1;            /* Current line number */
+      char     line[65536],            /* Line from file */
+               *value,                 /* Value from line */
+               data[65536];            /* Decoded data */
 
 
-      for (i = 0;
-           i < destptr->num_auth_info_required &&
-              cupsFileGets(fp, line, sizeof(line));
-          i ++)
+      if (cupsFileGets(fp, line, sizeof(line)) &&
+          !strcmp(line, "CUPSD-AUTH-V2"))
       {
-        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);
+        i = 0;
+        while (cupsFileGetConf(fp, line, sizeof(line), &value, &linenum))
+        {
+         /*
+          * Decode value...
+          */
+
+         bytes = sizeof(data);
+         httpDecode64_2(data, &bytes, value);
+
+         /*
+          * Assign environment variables...
+          */
+
+          if (!strcmp(line, "uid"))
+          {
+            cupsdSetStringf(&job->auth_uid, "AUTH_UID=%s", value);
+            continue;
+          }
+          else if (i >= (int)(sizeof(job->auth_env) / sizeof(job->auth_env[0])))
+            break;
+
+         if (!strcmp(line, "username"))
+           cupsdSetStringf(job->auth_env + i, "AUTH_USERNAME=%s", data);
+         else if (!strcmp(line, "domain"))
+           cupsdSetStringf(job->auth_env + i, "AUTH_DOMAIN=%s", data);
+         else if (!strcmp(line, "password"))
+           cupsdSetStringf(job->auth_env + i, "AUTH_PASSWORD=%s", data);
+         else if (!strcmp(line, "negotiate"))
+           cupsdSetStringf(job->auth_env + i, "AUTH_NEGOTIATE=%s", line);
+         else
+           continue;
+
+         i ++;
+       }
       }
 
       cupsFileClose(fp);
@@ -1715,7 +1986,9 @@ cupsdLoadJob(cupsd_job_t *job)            /* I - Job */
 
   ippDelete(job->attrs);
   job->attrs = NULL;
-  unlink(jobfile);
+
+  remove_job_history(job);
+  remove_job_files(job);
 
   return (0);
 }
@@ -1756,16 +2029,16 @@ cupsdMoveJob(cupsd_job_t     *job,      /* I - Job */
   * Change the destination information...
   */
 
-  cupsdSetJobState(job, IPP_JOB_PENDING, CUPSD_JOB_DEFAULT,
-                   "Stopping job prior to move.");
+  if (job->state_value > IPP_JOB_HELD)
+    cupsdSetJobState(job, IPP_JOB_PENDING, CUPSD_JOB_DEFAULT,
+                    "Stopping job prior to move.");
 
   cupsdAddEvent(CUPSD_EVENT_JOB_CONFIG_CHANGED, 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);
+  job->dtype = p->type & (CUPS_PRINTER_CLASS | CUPS_PRINTER_REMOTE);
 
   if ((attr = ippFindAttribute(job->attrs, "job-printer-uri",
                                IPP_TAG_URI)) != NULL)
@@ -1829,30 +2102,19 @@ void
 cupsdSaveAllJobs(void)
 {
   int          i;                      /* Looping var */
-  cups_file_t  *fp;                    /* Job cache file */
-  char         temp[1024];             /* Temporary string */
+  cups_file_t  *fp;                    /* job.cache file */
+  char         filename[1024],         /* job.cache filename */
+               temp[1024];             /* Temporary string */
   cupsd_job_t  *job;                   /* Current job */
   time_t       curtime;                /* Current time */
   struct tm    *curdate;               /* Current date */
 
 
-  snprintf(temp, sizeof(temp), "%s/job.cache", CacheDir);
-  if ((fp = cupsFileOpen(temp, "w")) == NULL)
-  {
-    cupsdLogMessage(CUPSD_LOG_ERROR,
-                    "Unable to create job cache file \"%s\" - %s",
-                    temp, strerror(errno));
+  snprintf(filename, sizeof(filename), "%s/job.cache", CacheDir);
+  if ((fp = cupsdCreateConfFile(filename, ConfigFilePerm)) == NULL)
     return;
-  }
-
-  cupsdLogMessage(CUPSD_LOG_INFO, "Saving job cache file \"%s\"...", temp);
-
- /*
-  * Restrict access to the file...
-  */
 
-  fchown(cupsFileNumber(fp), getuid(), Group);
-  fchmod(cupsFileNumber(fp), ConfigFilePerm);
+  cupsdLogMessage(CUPSD_LOG_INFO, "Saving job.cache...");
 
  /*
   * Write a small header to the file...
@@ -1888,7 +2150,7 @@ cupsdSaveAllJobs(void)
     cupsFilePuts(fp, "</Job>\n");
   }
 
-  cupsFileClose(fp);
+  cupsdCloseCreatedConfFile(fp, filename);
 }
 
 
@@ -1908,27 +2170,24 @@ cupsdSaveJob(cupsd_job_t *job)          /* I - Job */
 
   snprintf(filename, sizeof(filename), "%s/c%05d", RequestRoot, job->id);
 
-  if ((fp = cupsFileOpen(filename, "w")) == NULL)
-  {
-    cupsdLogMessage(CUPSD_LOG_ERROR,
-                   "[Job %d] Unable to create job control file \"%s\" - %s.",
-                   job->id, filename, strerror(errno));
+  if ((fp = cupsdCreateConfFile(filename, ConfigFilePerm & 0600)) == NULL)
     return;
-  }
 
-  fchmod(cupsFileNumber(fp), 0600);
   fchown(cupsFileNumber(fp), RunUser, Group);
 
   job->attrs->state = IPP_IDLE;
 
   if (ippWriteIO(fp, (ipp_iocb_t)cupsFileWrite, 1, NULL,
                  job->attrs) != IPP_DATA)
+  {
     cupsdLogMessage(CUPSD_LOG_ERROR,
-                    "[Job %d] Unable to write job control file!", job->id);
-
-  cupsFileClose(fp);
+                    "[Job %d] Unable to write job control file.", job->id);
+    cupsFileClose(fp);
+    return;
+  }
 
-  job->dirty = 0;
+  if (!cupsdCloseCreatedConfFile(fp, filename))
+    job->dirty = 0;
 }
 
 
@@ -1980,12 +2239,16 @@ cupsdSetJobHoldUntil(cupsd_job_t *job,  /* I - Job */
       job->dirty = 1;
       cupsdMarkDirty(CUPSD_DIRTY_JOBS);
     }
+
+    ippSetString(job->attrs, &job->reasons, 0, "job-hold-until-specified");
   }
 
  /*
   * Update the hold time...
   */
 
+  job->cancel_time = 0;
+
   if (!strcmp(when, "indefinite") || !strcmp(when, "auth-info-required"))
   {
    /*
@@ -1993,6 +2256,9 @@ cupsdSetJobHoldUntil(cupsd_job_t *job,    /* I - Job */
     */
 
     job->hold_until = 0;
+
+    if (MaxHoldTime > 0)
+      job->cancel_time = time(NULL) + MaxHoldTime;
   }
   else if (!strcmp(when, "day-time"))
   {
@@ -2175,10 +2441,12 @@ cupsdSetJobState(
     return;
 
  /*
-  * Don't do anything if the state is unchanged...
+  * Don't do anything if the state is unchanged and we aren't purging the
+  * job...
   */
 
-  if (newstate == (oldstate = job->state_value))
+  oldstate = job->state_value;
+  if (newstate == oldstate && action != CUPSD_JOB_PURGE)
     return;
 
  /*
@@ -2186,7 +2454,7 @@ cupsdSetJobState(
   */
 
   if (oldstate == IPP_JOB_PROCESSING)
-    stop_job(job, action != CUPSD_JOB_DEFAULT);
+    stop_job(job, action);
 
  /*
   * Set the new job state...
@@ -2219,6 +2487,7 @@ cupsdSetJobState(
     case IPP_JOB_CANCELED :
     case IPP_JOB_COMPLETED :
        set_time(job, "time-at-completed");
+       ippSetString(job->attrs, &job->reasons, 0, "processing-to-stop-point");
         break;
   }
 
@@ -2287,17 +2556,32 @@ cupsdSetJobState(
     case IPP_JOB_ABORTED :
     case IPP_JOB_CANCELED :
     case IPP_JOB_COMPLETED :
-       /*
-        * Expire job subscriptions since the job is now "completed"...
-       */
+        if (newstate == IPP_JOB_CANCELED)
+       {
+        /*
+         * Remove the job from the active list if there are no processes still
+         * running for it...
+         */
 
-        cupsdExpireSubscriptions(NULL, job);
+         for (i = 0; job->filters[i] < 0; i++);
+
+         if (!job->filters[i] && job->backend <= 0)
+           cupsArrayRemove(ActiveJobs, job);
+       }
+       else
+       {
+        /*
+         * Otherwise just remove the job from the active list immediately...
+         */
+
+         cupsArrayRemove(ActiveJobs, job);
+       }
 
        /*
-       * Remove the job from the active list...
+        * Expire job subscriptions since the job is now "completed"...
        */
 
-       cupsArrayRemove(ActiveJobs, job);
+        cupsdExpireSubscriptions(NULL, job);
 
 #ifdef __APPLE__
        /*
@@ -2319,23 +2603,12 @@ cupsdSetJobState(
                          "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;
-       }
+       for (i = 0;
+            i < (int)(sizeof(job->auth_env) / sizeof(job->auth_env[0]));
+            i ++)
+         cupsdClearString(job->auth_env + i);
 
-       cupsdClearString(&job->ccname);
-#endif /* HAVE_GSSAPI */
+       cupsdClearString(&job->auth_uid);
 
        /*
        * Remove the print file for good if we aren't preserving jobs or
@@ -2343,24 +2616,7 @@ cupsdSetJobState(
        */
 
        if (!JobHistory || !JobFiles || action == CUPSD_JOB_PURGE)
-       {
-         for (i = 1; i <= job->num_files; i ++)
-         {
-           snprintf(filename, sizeof(filename), "%s/d%05d-%03d", RequestRoot,
-                    job->id, i);
-           unlink(filename);
-         }
-
-         if (job->num_files > 0)
-         {
-           free(job->filetypes);
-           free(job->compressions);
-
-           job->num_files    = 0;
-           job->filetypes    = NULL;
-           job->compressions = NULL;
-         }
-       }
+         remove_job_files(job);
 
        if (JobHistory && action != CUPSD_JOB_PURGE)
        {
@@ -2372,7 +2628,14 @@ cupsdSetJobState(
          cupsdMarkDirty(CUPSD_DIRTY_JOBS);
        }
        else if (!job->printer)
+       {
+        /*
+         * Delete the job immediately if not actively printing...
+         */
+
          cupsdDeleteJob(job, CUPSD_JOB_PURGE);
+         job = NULL;
+       }
        break;
   }
 
@@ -2380,8 +2643,8 @@ cupsdSetJobState(
   * Finalize the job immediately if we forced things...
   */
 
-  if (action == CUPSD_JOB_FORCE)
-    finalize_job(job);
+  if (action >= CUPSD_JOB_FORCE && job && job->printer)
+    finalize_job(job, 0);
 
  /*
   * Update the server "busy" state...
@@ -2444,6 +2707,62 @@ cupsdUnloadCompletedJobs(void)
 }
 
 
+/*
+ * 'cupsdUpdateJobs()' - Update the history/file files for all jobs.
+ */
+
+void
+cupsdUpdateJobs(void)
+{
+  cupsd_job_t          *job;           /* Current job */
+  time_t               curtime;        /* Current time */
+  ipp_attribute_t      *attr;          /* time-at-completed attribute */
+
+
+  curtime          = time(NULL);
+  JobHistoryUpdate = 0;
+
+  for (job = (cupsd_job_t *)cupsArrayFirst(Jobs);
+       job;
+       job = (cupsd_job_t *)cupsArrayNext(Jobs))
+  {
+    if (job->state_value >= IPP_JOB_CANCELED &&
+        (attr = ippFindAttribute(job->attrs, "time-at-completed",
+                                 IPP_TAG_INTEGER)) != NULL)
+    {
+     /*
+      * Update history/file expiration times...
+      */
+
+      if (JobHistory < INT_MAX)
+       job->history_time = attr->values[0].integer + JobHistory;
+      else
+       job->history_time = INT_MAX;
+
+      if (job->history_time < curtime)
+      {
+        cupsdDeleteJob(job, CUPSD_JOB_PURGE);
+        continue;
+      }
+
+      if (job->history_time < JobHistoryUpdate || !JobHistoryUpdate)
+       JobHistoryUpdate = job->history_time;
+
+      if (JobFiles < INT_MAX)
+       job->file_time = attr->values[0].integer + JobFiles;
+      else
+       job->file_time = INT_MAX;
+
+      if (job->file_time < JobHistoryUpdate || !JobHistoryUpdate)
+       JobHistoryUpdate = job->file_time;
+    }
+  }
+
+  cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdUpdateAllJobs: JobHistoryUpdate=%ld",
+                  (long)JobHistoryUpdate);
+}
+
+
 /*
  * 'compare_active_jobs()' - Compare the job IDs and priorities of two jobs.
  */
@@ -2456,6 +2775,8 @@ compare_active_jobs(void *first,  /* I - First job */
   int  diff;                           /* Difference */
 
 
+  (void)data;
+
   if ((diff = ((cupsd_job_t *)second)->priority -
               ((cupsd_job_t *)first)->priority) != 0)
     return (diff);
@@ -2473,16 +2794,153 @@ compare_jobs(void *first,              /* I - First job */
              void *second,             /* I - Second job */
             void *data)                /* I - App data (not used) */
 {
+  (void)data;
+
   return (((cupsd_job_t *)first)->id - ((cupsd_job_t *)second)->id);
 }
 
 
 /*
- * 'finalize_job()' - Cleanup after job filter processes and support data.
+ * 'dump_job_history()' - Dump any debug messages for a job.
  */
 
 static void
-finalize_job(cupsd_job_t *job)         /* I - Job */
+dump_job_history(cupsd_job_t *job)     /* I - Job */
+{
+  int                  i,              /* Looping var */
+                       oldsize;        /* Current MaxLogSize */
+  struct tm            *date;          /* Date/time value */
+  cupsd_joblog_t       *message;       /* Current message */
+  char                 temp[2048],     /* Log message */
+                       *ptr,           /* Pointer into log message */
+                       start[256],     /* Start time */
+                       end[256];       /* End time */
+  cupsd_printer_t      *printer;       /* Printer for job */
+
+
+ /*
+  * See if we have anything to dump...
+  */
+
+  if (!job->history)
+    return;
+
+ /*
+  * Disable log rotation temporarily...
+  */
+
+  oldsize    = MaxLogSize;
+  MaxLogSize = 0;
+
+ /*
+  * Copy the debug messages to the log...
+  */
+
+  message = (cupsd_joblog_t *)cupsArrayFirst(job->history);
+  date = localtime(&(message->time));
+  strftime(start, sizeof(start), "%X", date);
+
+  message = (cupsd_joblog_t *)cupsArrayLast(job->history);
+  date = localtime(&(message->time));
+  strftime(end, sizeof(end), "%X", date);
+
+  snprintf(temp, sizeof(temp),
+           "[Job %d] The following messages were recorded from %s to %s",
+           job->id, start, end);
+  cupsdWriteErrorLog(CUPSD_LOG_DEBUG, temp);
+
+  for (message = (cupsd_joblog_t *)cupsArrayFirst(job->history);
+       message;
+       message = (cupsd_joblog_t *)cupsArrayNext(job->history))
+    cupsdWriteErrorLog(CUPSD_LOG_DEBUG, message->message);
+
+  snprintf(temp, sizeof(temp), "[Job %d] End of messages", job->id);
+  cupsdWriteErrorLog(CUPSD_LOG_DEBUG, temp);
+
+ /*
+  * Log the printer state values...
+  */
+
+  if ((printer = job->printer) == NULL)
+    printer = cupsdFindDest(job->dest);
+
+  if (printer)
+  {
+    snprintf(temp, sizeof(temp), "[Job %d] printer-state=%d(%s)", job->id,
+             printer->state,
+            printer->state == IPP_PRINTER_IDLE ? "idle" :
+                printer->state == IPP_PRINTER_PROCESSING ? "processing" :
+                "stopped");
+    cupsdWriteErrorLog(CUPSD_LOG_DEBUG, temp);
+
+    snprintf(temp, sizeof(temp), "[Job %d] printer-state-message=\"%s\"",
+             job->id, printer->state_message);
+    cupsdWriteErrorLog(CUPSD_LOG_DEBUG, temp);
+
+    snprintf(temp, sizeof(temp), "[Job %d] printer-state-reasons=", job->id);
+    ptr = temp + strlen(temp);
+    if (printer->num_reasons == 0)
+      strlcpy(ptr, "none", sizeof(temp) - (ptr - temp));
+    else
+    {
+      for (i = 0;
+           i < printer->num_reasons && ptr < (temp + sizeof(temp) - 2);
+           i ++)
+      {
+        if (i)
+         *ptr++ = ',';
+
+       strlcpy(ptr, printer->reasons[i], sizeof(temp) - (ptr - temp));
+       ptr += strlen(ptr);
+      }
+    }
+    cupsdWriteErrorLog(CUPSD_LOG_DEBUG, temp);
+  }
+
+ /*
+  * Restore log file rotation...
+  */
+
+  MaxLogSize = oldsize;
+
+ /*
+  * Free all messages...
+  */
+
+  free_job_history(job);
+}
+
+
+/*
+ * 'free_job_history()' - Free any log history.
+ */
+
+static void
+free_job_history(cupsd_job_t *job)     /* I - Job */
+{
+  char *message;                       /* Current message */
+
+
+  if (!job->history)
+    return;
+
+  for (message = (char *)cupsArrayFirst(job->history);
+       message;
+       message = (char *)cupsArrayNext(job->history))
+    free(message);
+
+  cupsArrayDelete(job->history);
+  job->history = NULL;
+}
+
+
+/*
+ * 'finalize_job()' - Cleanup after job filter processes and support data.
+ */
+
+static void
+finalize_job(cupsd_job_t *job,         /* I - Job */
+             int         set_job_state)        /* I - 1 = set the job state */
 {
   ipp_pstate_t         printer_state;  /* New printer state value */
   ipp_jstate_t         job_state;      /* New job state value */
@@ -2493,11 +2951,18 @@ finalize_job(cupsd_job_t *job)          /* I - Job */
   cupsdLogMessage(CUPSD_LOG_DEBUG2, "finalize_job(job=%p(%d))", job, job->id);
 
  /*
-  * Clear the "connecting-to-device" reason, which is only valid when a
-  * printer is processing...
+  * Clear the "connecting-to-device" reason, which is only valid when a printer
+  * is processing, along with any remote printing job state...
   */
 
-  cupsdSetPrinterReasons(job->printer, "-connecting-to-device");
+  cupsdSetPrinterReasons(job->printer, "-connecting-to-device,"
+                                      "cups-remote-pending,"
+                                      "cups-remote-pending-held,"
+                                      "cups-remote-processing,"
+                                      "cups-remote-stopped,"
+                                      "cups-remote-canceled,"
+                                      "cups-remote-aborted,"
+                                      "cups-remote-completed");
 
  /*
   * Similarly, clear the "offline-report" reason for non-USB devices since we
@@ -2514,6 +2979,12 @@ finalize_job(cupsd_job_t *job)           /* I - Job */
   cupsdDestroyProfile(job->profile);
   job->profile = NULL;
 
+ /*
+  * Clear the unresponsive job watchdog timer...
+  */
+
+  job->kill_time = 0;
+
  /*
   * Close pipes and status buffer...
   */
@@ -2549,16 +3020,23 @@ finalize_job(cupsd_job_t *job)          /* I - Job */
     default :
     case IPP_JOB_PROCESSING :
     case IPP_JOB_COMPLETED :
-       job_state     = IPP_JOB_COMPLETED;
-       message       = "Job completed.";
+       job_state = IPP_JOB_COMPLETED;
+       message   = "Job completed.";
+
+       ippSetString(job->attrs, &job->reasons, 0,
+                    "job-completed-successfully");
         break;
 
     case IPP_JOB_STOPPED :
         message = "Job stopped.";
+
+       ippSetString(job->attrs, &job->reasons, 0, "job-stopped");
        break;
 
     case IPP_JOB_CANCELED :
         message = "Job canceled.";
+
+       ippSetString(job->attrs, &job->reasons, 0, "job-canceled-by-user");
        break;
 
     case IPP_JOB_ABORTED :
@@ -2574,7 +3052,6 @@ finalize_job(cupsd_job_t *job)            /* I - Job */
 
     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
@@ -2585,7 +3062,10 @@ finalize_job(cupsd_job_t *job)           /* I - Job */
     if (WIFEXITED(exit_code))
       exit_code = WEXITSTATUS(exit_code);
     else
+    {
+      ippSetString(job->attrs, &job->reasons, 0, "cups-backend-crashed");
       exit_code = job->status;
+    }
 
     cupsdLogJob(job, CUPSD_LOG_INFO, "Backend returned status %d (%s)",
                exit_code,
@@ -2610,7 +3090,7 @@ finalize_job(cupsd_job_t *job)            /* I - Job */
          * act...
          */
 
-          if (job->dtype & (CUPS_PRINTER_CLASS | CUPS_PRINTER_IMPLICIT))
+          if (job->dtype & CUPS_PRINTER_CLASS)
          {
           /*
            * Queued on a class - mark the job as pending and we'll retry on
@@ -2621,6 +3101,9 @@ finalize_job(cupsd_job_t *job)            /* I - Job */
            {
              job_state = IPP_JOB_PENDING;
              message   = "Retrying job on another printer.";
+
+             ippSetString(job->attrs, &job->reasons, 0,
+                          "resources-are-not-ready");
            }
           }
          else if (!strcmp(job->printer->error_policy, "retry-current-job"))
@@ -2634,6 +3117,8 @@ finalize_job(cupsd_job_t *job)            /* I - Job */
            {
              job_state = IPP_JOB_PENDING;
              message   = "Retrying job on same printer.";
+
+             ippSetString(job->attrs, &job->reasons, 0, "none");
            }
           }
          else if ((job->printer->type & CUPS_PRINTER_FAX) ||
@@ -2649,7 +3134,7 @@ finalize_job(cupsd_job_t *job)            /* I - Job */
 
              job->tries ++;
 
-             if (job->tries >= JobRetryLimit)
+             if (job->tries > JobRetryLimit && JobRetryLimit > 0)
              {
               /*
                * Too many tries...
@@ -2660,6 +3145,8 @@ finalize_job(cupsd_job_t *job)            /* I - Job */
                         JobRetryLimit);
                job_state = IPP_JOB_ABORTED;
                message   = buffer;
+
+               ippSetString(job->attrs, &job->reasons, 0, "aborted-by-system");
              }
              else
              {
@@ -2667,13 +3154,16 @@ finalize_job(cupsd_job_t *job)          /* I - Job */
                * Try again in N seconds...
                */
 
-               set_hold_until(job, time(NULL) + JobRetryInterval);
-
                snprintf(buffer, sizeof(buffer),
                         "Job held for %d seconds since it could not be sent.",
                         JobRetryInterval);
-               job_state = IPP_JOB_HELD;
-               message   = buffer;
+
+               job->hold_until = time(NULL) + JobRetryInterval;
+               job_state       = IPP_JOB_HELD;
+               message         = buffer;
+
+               ippSetString(job->attrs, &job->reasons, 0,
+                            "resources-are-not-ready");
              }
             }
          }
@@ -2683,15 +3173,17 @@ finalize_job(cupsd_job_t *job)          /* I - Job */
            job_state = IPP_JOB_ABORTED;
            message   = "Job aborted due to backend errors; please consult "
                        "the error_log file for details.";
+
+           ippSetString(job->attrs, &job->reasons, 0, "aborted-by-system");
          }
-         else
+         else if (job->state_value == IPP_JOB_PROCESSING)
           {
+            job_state     = IPP_JOB_PENDING;
            printer_state = IPP_PRINTER_STOPPED;
            message       = "Printer stopped due to backend errors; please "
                            "consult the error_log file for details.";
 
-            if (job_state == IPP_JOB_COMPLETED)
-             job_state = IPP_JOB_PENDING;
+           ippSetString(job->attrs, &job->reasons, 0, "none");
          }
           break;
 
@@ -2705,6 +3197,8 @@ finalize_job(cupsd_job_t *job)            /* I - Job */
            job_state = IPP_JOB_ABORTED;
            message   = "Job aborted due to backend errors; please consult "
                        "the error_log file for details.";
+
+           ippSetString(job->attrs, &job->reasons, 0, "aborted-by-system");
          }
           break;
 
@@ -2716,6 +3210,8 @@ finalize_job(cupsd_job_t *job)            /* I - Job */
            */
 
            cupsdSetJobHoldUntil(job, "indefinite", 1);
+           ippSetString(job->attrs, &job->reasons, 0,
+                        "job-hold-until-specified");
 
            job_state = IPP_JOB_HELD;
            message   = "Job held indefinitely due to backend errors; please "
@@ -2733,7 +3229,12 @@ finalize_job(cupsd_job_t *job)           /* I - Job */
                          "consult the error_log file for details.";
 
          if (job_state == IPP_JOB_COMPLETED)
+         {
            job_state = IPP_JOB_PENDING;
+
+           ippSetString(job->attrs, &job->reasons, 0,
+                        "resources-are-not-ready");
+         }
           break;
 
       case CUPS_BACKEND_AUTH_REQUIRED :
@@ -2747,8 +3248,69 @@ finalize_job(cupsd_job_t *job)           /* I - Job */
 
            job_state = IPP_JOB_HELD;
            message   = "Job held for authentication.";
+
+           ippSetString(job->attrs, &job->reasons, 0,
+                        "cups-held-for-authentication");
           }
           break;
+
+      case CUPS_BACKEND_RETRY :
+         if (job_state == IPP_JOB_COMPLETED)
+         {
+          /*
+           * Hold the job if the number of retries is less than the
+           * JobRetryLimit, otherwise abort the job.
+           */
+
+           job->tries ++;
+
+           if (job->tries > JobRetryLimit && JobRetryLimit > 0)
+           {
+            /*
+             * Too many tries...
+             */
+
+             snprintf(buffer, sizeof(buffer),
+                      "Job aborted after %d unsuccessful attempts.",
+                      JobRetryLimit);
+             job_state = IPP_JOB_ABORTED;
+             message   = buffer;
+
+             ippSetString(job->attrs, &job->reasons, 0, "aborted-by-system");
+           }
+           else
+           {
+            /*
+             * Try again in N seconds...
+             */
+
+             snprintf(buffer, sizeof(buffer),
+                      "Job held for %d seconds since it could not be sent.",
+                      JobRetryInterval);
+
+             job->hold_until = time(NULL) + JobRetryInterval;
+             job_state       = IPP_JOB_HELD;
+             message         = buffer;
+
+             ippSetString(job->attrs, &job->reasons, 0,
+                          "resources-are-not-ready");
+           }
+         }
+          break;
+
+      case CUPS_BACKEND_RETRY_CURRENT :
+        /*
+         * Mark the job as pending and retry on the same printer...
+         */
+
+         if (job_state == IPP_JOB_COMPLETED)
+         {
+           job_state = IPP_JOB_PENDING;
+           message   = "Retrying job on same printer.";
+
+           ippSetString(job->attrs, &job->reasons, 0, "none");
+         }
+          break;
     }
   }
   else if (job->status > 0)
@@ -2762,6 +3324,11 @@ finalize_job(cupsd_job_t *job)           /* I - Job */
       job_state = IPP_JOB_STOPPED;
       message   = "Job stopped due to filter errors; please consult the "
                  "error_log file for details.";
+
+      if (WIFSIGNALED(job->status))
+       ippSetString(job->attrs, &job->reasons, 0, "cups-filter-crashed");
+      else
+       ippSetString(job->attrs, &job->reasons, 0, "job-completed-with-errors");
     }
   }
 
@@ -2769,11 +3336,23 @@ finalize_job(cupsd_job_t *job)          /* I - Job */
   * Update the printer and job state.
   */
 
-  cupsdSetJobState(job, job_state, CUPSD_JOB_DEFAULT, "%s", message);
+  if (set_job_state && job_state != job->state_value)
+    cupsdSetJobState(job, job_state, CUPSD_JOB_DEFAULT, "%s", message);
+
   cupsdSetPrinterState(job->printer, printer_state,
                        printer_state == IPP_PRINTER_STOPPED);
   update_job_attrs(job, 0);
 
+  if (job->history)
+  {
+    if (job->status &&
+        (job->state_value == IPP_JOB_ABORTED ||
+         job->state_value == IPP_JOB_STOPPED))
+      dump_job_history(job);
+    else
+      free_job_history(job);
+  }
+
   cupsArrayRemove(PrintingJobs, job);
 
  /*
@@ -2805,39 +3384,201 @@ get_options(cupsd_job_t *job,          /* I - Job */
            size_t      title_size)     /* I - Size of title buffer */
 {
   int                  i;              /* Looping var */
+  size_t               newlength;      /* New option buffer length */
   char                 *optptr,        /* Pointer to options */
                        *valptr;        /* Pointer in value string */
   ipp_attribute_t      *attr;          /* Current attribute */
+  _ppd_cache_t         *pc;            /* PPD cache and mapping data */
+  int                  num_pwgppds;    /* Number of PWG->PPD options */
+  cups_option_t                *pwgppds,       /* PWG->PPD options */
+                       *pwgppd,        /* Current PWG->PPD option */
+                       *preset;        /* Current preset option */
+  int                  print_color_mode,
+                                       /* Output mode (if any) */
+                       print_quality;  /* Print quality (if any) */
+  const char           *ppd;           /* PPD option choice */
+  int                  exact;          /* Did we get an exact match? */
   static char          *options = NULL;/* Full list of options */
-  static int           optlength = 0;  /* Length of option buffer */
+  static size_t                optlength = 0;  /* Length of option buffer */
 
 
  /*
-  * 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... :)
+  * 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...
+  * First build an options array for any PWG->PPD mapped option/choice pairs.
+  */
+
+  pc          = job->printer->pc;
+  num_pwgppds = 0;
+  pwgppds     = NULL;
+
+  if (pc &&
+      !ippFindAttribute(job->attrs,
+                        "com.apple.print.DocumentTicket.PMSpoolFormat",
+                       IPP_TAG_ZERO) &&
+      !ippFindAttribute(job->attrs, "APPrinterPreset", IPP_TAG_ZERO) &&
+      (ippFindAttribute(job->attrs, "output-mode", IPP_TAG_ZERO) ||
+       ippFindAttribute(job->attrs, "print-color-mode", IPP_TAG_ZERO) ||
+       ippFindAttribute(job->attrs, "print-quality", IPP_TAG_ZERO)))
+  {
+   /*
+    * Map output-mode and print-quality to a preset...
+    */
+
+    if ((attr = ippFindAttribute(job->attrs, "print-color-mode",
+                                IPP_TAG_KEYWORD)) == NULL)
+      attr = ippFindAttribute(job->attrs, "output-mode", IPP_TAG_KEYWORD);
+
+    if (attr && !strcmp(attr->values[0].string.text, "monochrome"))
+      print_color_mode = _PWG_PRINT_COLOR_MODE_MONOCHROME;
+    else
+      print_color_mode = _PWG_PRINT_COLOR_MODE_COLOR;
+
+    if ((attr = ippFindAttribute(job->attrs, "print-quality",
+                                IPP_TAG_ENUM)) != NULL &&
+       attr->values[0].integer >= IPP_QUALITY_DRAFT &&
+       attr->values[0].integer <= IPP_QUALITY_HIGH)
+      print_quality = attr->values[0].integer - IPP_QUALITY_DRAFT;
+    else
+      print_quality = _PWG_PRINT_QUALITY_NORMAL;
+
+    if (pc->num_presets[print_color_mode][print_quality] == 0)
+    {
+     /*
+      * Try to find a preset that works so that we maximize the chances of us
+      * getting a good print using IPP attributes.
+      */
+
+      if (pc->num_presets[print_color_mode][_PWG_PRINT_QUALITY_NORMAL] > 0)
+        print_quality = _PWG_PRINT_QUALITY_NORMAL;
+      else if (pc->num_presets[_PWG_PRINT_COLOR_MODE_COLOR][print_quality] > 0)
+        print_color_mode = _PWG_PRINT_COLOR_MODE_COLOR;
+      else
+      {
+        print_quality    = _PWG_PRINT_QUALITY_NORMAL;
+        print_color_mode = _PWG_PRINT_COLOR_MODE_COLOR;
+      }
+    }
+
+    if (pc->num_presets[print_color_mode][print_quality] > 0)
+    {
+     /*
+      * Copy the preset options as long as the corresponding names are not
+      * already defined in the IPP request...
+      */
+
+      for (i = pc->num_presets[print_color_mode][print_quality],
+              preset = pc->presets[print_color_mode][print_quality];
+          i > 0;
+          i --, preset ++)
+      {
+        if (!ippFindAttribute(job->attrs, preset->name, IPP_TAG_ZERO))
+         num_pwgppds = cupsAddOption(preset->name, preset->value, num_pwgppds,
+                                     &pwgppds);
+      }
+    }
+  }
+
+  if (pc)
+  {
+    if (!ippFindAttribute(job->attrs, "InputSlot", IPP_TAG_ZERO) &&
+       !ippFindAttribute(job->attrs, "HPPaperSource", IPP_TAG_ZERO))
+    {
+      if ((ppd = _ppdCacheGetInputSlot(pc, job->attrs, NULL)) != NULL)
+       num_pwgppds = cupsAddOption(pc->source_option, ppd, num_pwgppds,
+                                   &pwgppds);
+    }
+    if (!ippFindAttribute(job->attrs, "MediaType", IPP_TAG_ZERO) &&
+       (ppd = _ppdCacheGetMediaType(pc, job->attrs, NULL)) != NULL)
+      num_pwgppds = cupsAddOption("MediaType", ppd, num_pwgppds, &pwgppds);
+
+    if (!ippFindAttribute(job->attrs, "PageRegion", IPP_TAG_ZERO) &&
+       !ippFindAttribute(job->attrs, "PageSize", IPP_TAG_ZERO) &&
+       (ppd = _ppdCacheGetPageSize(pc, job->attrs, NULL, &exact)) != NULL)
+    {
+      num_pwgppds = cupsAddOption("PageSize", ppd, num_pwgppds, &pwgppds);
+
+      if (!ippFindAttribute(job->attrs, "media", IPP_TAG_ZERO))
+        num_pwgppds = cupsAddOption("media", ppd, num_pwgppds, &pwgppds);
+    }
+
+    if (!ippFindAttribute(job->attrs, "OutputBin", IPP_TAG_ZERO) &&
+       (attr = ippFindAttribute(job->attrs, "output-bin",
+                                IPP_TAG_ZERO)) != NULL &&
+       (attr->value_tag == IPP_TAG_KEYWORD ||
+        attr->value_tag == IPP_TAG_NAME) &&
+       (ppd = _ppdCacheGetOutputBin(pc, attr->values[0].string.text)) != NULL)
+    {
+     /*
+      * Map output-bin to OutputBin option...
+      */
+
+      num_pwgppds = cupsAddOption("OutputBin", ppd, num_pwgppds, &pwgppds);
+    }
+
+    if (pc->sides_option &&
+        !ippFindAttribute(job->attrs, pc->sides_option, IPP_TAG_ZERO) &&
+       (attr = ippFindAttribute(job->attrs, "sides", IPP_TAG_KEYWORD)) != NULL)
+    {
+     /*
+      * Map sides to duplex option...
+      */
+
+      if (!strcmp(attr->values[0].string.text, "one-sided"))
+        num_pwgppds = cupsAddOption(pc->sides_option, pc->sides_1sided,
+                                   num_pwgppds, &pwgppds);
+      else if (!strcmp(attr->values[0].string.text, "two-sided-long-edge"))
+        num_pwgppds = cupsAddOption(pc->sides_option, pc->sides_2sided_long,
+                                   num_pwgppds, &pwgppds);
+      else if (!strcmp(attr->values[0].string.text, "two-sided-short-edge"))
+        num_pwgppds = cupsAddOption(pc->sides_option, pc->sides_2sided_short,
+                                   num_pwgppds, &pwgppds);
+    }
+
+   /*
+    * Map finishings values...
+    */
+
+    num_pwgppds = _ppdCacheGetFinishingOptions(pc, job->attrs,
+                                               IPP_FINISHINGS_NONE, num_pwgppds,
+                                               &pwgppds);
+  }
+
+ /*
+  * Figure out how much room we need...
+  */
+
+  newlength = ipp_length(job->attrs);
+
+  for (i = num_pwgppds, pwgppd = pwgppds; i > 0; i --, pwgppd ++)
+    newlength += 1 + strlen(pwgppd->name) + 1 + strlen(pwgppd->value);
+
+ /*
+  * Then allocate/reallocate the option buffer as needed...
   */
 
-  i = ipp_length(job->attrs);
+  if (newlength == 0)                  /* This can never happen, but Clang */
+    newlength = 1;                     /* thinks it can... */
 
-  if (i > optlength || !options)
+  if (newlength > optlength || !options)
   {
     if (!options)
-      optptr = malloc(i);
+      optptr = malloc(newlength);
     else
-      optptr = realloc(options, i);
+      optptr = realloc(options, newlength);
 
     if (!optptr)
     {
       cupsdLogJob(job, CUPSD_LOG_CRIT,
-                 "Unable to allocate %d bytes for option buffer!", i);
+                 "Unable to allocate " CUPS_LLFMT " bytes for option buffer.",
+                 CUPS_LLCAST newlength);
       return (NULL);
     }
 
     options   = optptr;
-    optlength = i;
+    optlength = newlength;
   }
 
  /*
@@ -2873,7 +3614,8 @@ get_options(cupsd_job_t *job,             /* I - Job */
       * Filter out other unwanted attributes...
       */
 
-      if (attr->value_tag == IPP_TAG_MIMETYPE ||
+      if (attr->value_tag == IPP_TAG_NOVALUE ||
+          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")) ||
@@ -2881,7 +3623,7 @@ get_options(cupsd_job_t *job,             /* I - Job */
          attr->value_tag == IPP_TAG_BEGIN_COLLECTION) /* Not yet supported */
        continue;
 
-      if (!strncmp(attr->name, "time-", 5))
+      if (!strcmp(attr->name, "job-hold-until"))
        continue;
 
       if (!strncmp(attr->name, "job-", 4) &&
@@ -2898,11 +3640,11 @@ get_options(cupsd_job_t *job,           /* I - Job */
            !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."
+          !_cups_strcasecmp(attr->name, "AP_FIRSTPAGE_InputSlot") ||
+          !_cups_strcasecmp(attr->name, "AP_FIRSTPAGE_ManualFeed") ||
+          !_cups_strcasecmp(attr->name, "com.apple.print.PrintSettings."
                                   "PMTotalSidesImaged..n.") ||
-          !strcasecmp(attr->name, "com.apple.print.PrintSettings."
+          !_cups_strcasecmp(attr->name, "com.apple.print.PrintSettings."
                                   "PMTotalBeginPages..n.")) &&
          banner_page)
         continue;
@@ -2939,7 +3681,6 @@ get_options(cupsd_job_t *job,             /* I - Job */
              if (!attr->values[i].boolean)
                strlcat(optptr, "no", optlength - (optptr - options));
 
-         case IPP_TAG_NOVALUE :
              strlcat(optptr, attr->name,
                      optlength - (optptr - options));
              break;
@@ -2959,7 +3700,7 @@ get_options(cupsd_job_t *job,             /* I - Job */
                       "%dx%d%s", attr->values[i].resolution.xres,
                       attr->values[i].resolution.yres,
                       attr->values[i].resolution.units == IPP_RES_PER_INCH ?
-                          "dpi" : "dpc");
+                          "dpi" : "dpcm");
              break;
 
           case IPP_TAG_STRING :
@@ -2988,6 +3729,25 @@ get_options(cupsd_job_t *job,            /* I - Job */
     }
   }
 
+ /*
+  * Finally loop through the PWG->PPD mapped options and add them...
+  */
+
+  for (i = num_pwgppds, pwgppd = pwgppds; i > 0; i --, pwgppd ++)
+  {
+    *optptr++ = ' ';
+    strcpy(optptr, pwgppd->name);
+    optptr += strlen(optptr);
+    *optptr++ = '=';
+    strcpy(optptr, pwgppd->value);
+    optptr += strlen(optptr);
+  }
+
+  cupsFreeOptions(num_pwgppds, pwgppds);
+
+ /*
+  * Return the options string...
+  */
 
   return (options);
 }
@@ -2998,10 +3758,10 @@ get_options(cupsd_job_t *job,           /* I - Job */
  *                 the textual IPP attributes.
  */
 
-static int                             /* O - Size of attribute buffer */
+static size_t                          /* O - Size of attribute buffer */
 ipp_length(ipp_t *ipp)                 /* I - IPP request */
 {
-  int                  bytes;          /* Number of bytes */
+  size_t               bytes;          /* Number of bytes */
   int                  i;              /* Looping var */
   ipp_attribute_t      *attr;          /* Current attribute */
 
@@ -3018,16 +3778,14 @@ ipp_length(ipp_t *ipp)                  /* I - IPP request */
     * Skip attributes that won't be sent to filters...
     */
 
-    if (attr->value_tag == IPP_TAG_MIMETYPE ||
+    if (attr->value_tag == IPP_TAG_NOVALUE ||
+       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;
 
-    if (strncmp(attr->name, "time-", 5) == 0)
-      continue;
-
    /*
     * Add space for a leading space and commas between each value.
     * For the first attribute, the leading space isn't used, so the
@@ -3136,15 +3894,9 @@ load_job_cache(const char *filename)     /* I - job.cache filename */
   * Open the job.cache file...
   */
 
-  if ((fp = cupsFileOpen(filename, "r")) == NULL)
+  if ((fp = cupsdOpenConfFile(filename)) == NULL)
   {
-    if (errno != ENOENT)
-      cupsdLogMessage(CUPSD_LOG_ERROR,
-                      "Unable to open job cache file \"%s\": %s",
-                      filename, strerror(errno));
-
     load_request_root();
-
     return;
   }
 
@@ -3160,23 +3912,23 @@ load_job_cache(const char *filename)    /* I - job.cache filename */
 
   while (cupsFileGetConf(fp, line, sizeof(line), &value, &linenum))
   {
-    if (!strcasecmp(line, "NextJobId"))
+    if (!_cups_strcasecmp(line, "NextJobId"))
     {
       if (value)
         NextJobId = atoi(value);
     }
-    else if (!strcasecmp(line, "<Job"))
+    else if (!_cups_strcasecmp(line, "<Job"))
     {
       if (job)
       {
-        cupsdLogMessage(CUPSD_LOG_ERROR, "Missing </Job> directive on line %d!",
+        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);
+        cupsdLogMessage(CUPSD_LOG_ERROR, "Missing job ID on line %d.", linenum);
        continue;
       }
 
@@ -3184,7 +3936,7 @@ load_job_cache(const char *filename)      /* I - job.cache filename */
 
       if (jobid < 1)
       {
-        cupsdLogMessage(CUPSD_LOG_ERROR, "Bad job ID %d on line %d!", jobid,
+        cupsdLogMessage(CUPSD_LOG_ERROR, "Bad job ID %d on line %d.", jobid,
                        linenum);
         continue;
       }
@@ -3192,16 +3944,20 @@ load_job_cache(const char *filename)    /* I - job.cache filename */
       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;
+       snprintf(jobfile, sizeof(jobfile), "%s/c%05d.N", RequestRoot, jobid);
+       if (access(jobfile, 0))
+       {
+         cupsdLogMessage(CUPSD_LOG_ERROR, "[Job %d] Files have gone away.",
+                         jobid);
+         continue;
+       }
       }
 
       job = calloc(1, sizeof(cupsd_job_t));
       if (!job)
       {
         cupsdLogMessage(CUPSD_LOG_EMERG,
-                       "[Job %d] Unable to allocate memory for job!", jobid);
+                       "[Job %d] Unable to allocate memory for job.", jobid);
         break;
       }
 
@@ -3221,27 +3977,24 @@ load_job_cache(const char *filename)    /* I - job.cache filename */
     else if (!job)
     {
       cupsdLogMessage(CUPSD_LOG_ERROR,
-                     "Missing <Job #> directive on line %d!", linenum);
+                     "Missing <Job #> directive on line %d.", linenum);
       continue;
     }
-    else if (!strcasecmp(line, "</Job>"))
+    else if (!_cups_strcasecmp(line, "</Job>"))
     {
       cupsArrayAdd(Jobs, job);
 
-      if (job->state_value <= IPP_JOB_STOPPED)
-      {
-        cupsArrayAdd(ActiveJobs, job);
-       cupsdLoadJob(job);
-      }
+      if (job->state_value <= IPP_JOB_STOPPED && cupsdLoadJob(job))
+       cupsArrayAdd(ActiveJobs, job);
 
       job = NULL;
     }
     else if (!value)
     {
-      cupsdLogMessage(CUPSD_LOG_ERROR, "Missing value on line %d!", linenum);
+      cupsdLogMessage(CUPSD_LOG_ERROR, "Missing value on line %d.", linenum);
       continue;
     }
-    else if (!strcasecmp(line, "State"))
+    else if (!_cups_strcasecmp(line, "State"))
     {
       job->state_value = (ipp_jstate_t)atoi(value);
 
@@ -3250,33 +4003,33 @@ load_job_cache(const char *filename)    /* I - job.cache filename */
       else if (job->state_value > IPP_JOB_COMPLETED)
         job->state_value = IPP_JOB_COMPLETED;
     }
-    else if (!strcasecmp(line, "HoldUntil"))
+    else if (!_cups_strcasecmp(line, "HoldUntil"))
     {
       job->hold_until = atoi(value);
     }
-    else if (!strcasecmp(line, "Priority"))
+    else if (!_cups_strcasecmp(line, "Priority"))
     {
       job->priority = atoi(value);
     }
-    else if (!strcasecmp(line, "Username"))
+    else if (!_cups_strcasecmp(line, "Username"))
     {
       cupsdSetString(&job->username, value);
     }
-    else if (!strcasecmp(line, "Destination"))
+    else if (!_cups_strcasecmp(line, "Destination"))
     {
       cupsdSetString(&job->dest, value);
     }
-    else if (!strcasecmp(line, "DestType"))
+    else if (!_cups_strcasecmp(line, "DestType"))
     {
       job->dtype = (cups_ptype_t)atoi(value);
     }
-    else if (!strcasecmp(line, "NumFiles"))
+    else if (!_cups_strcasecmp(line, "NumFiles"))
     {
       job->num_files = atoi(value);
 
       if (job->num_files < 0)
       {
-       cupsdLogMessage(CUPSD_LOG_ERROR, "Bad NumFiles value %d on line %d!",
+       cupsdLogMessage(CUPSD_LOG_ERROR, "Bad NumFiles value %d on line %d.",
                        job->num_files, linenum);
         job->num_files = 0;
        continue;
@@ -3288,7 +4041,7 @@ load_job_cache(const char *filename)      /* I - job.cache filename */
                 job->id);
         if (access(jobfile, 0))
        {
-         cupsdLogMessage(CUPSD_LOG_INFO, "[Job %d] Data files have gone away!",
+         cupsdLogMessage(CUPSD_LOG_INFO, "[Job %d] Data files have gone away.",
                          job->id);
           job->num_files = 0;
          continue;
@@ -3300,13 +4053,13 @@ load_job_cache(const char *filename)    /* I - job.cache filename */
         if (!job->filetypes || !job->compressions)
        {
          cupsdLogMessage(CUPSD_LOG_EMERG,
-                         "[Job %d] Unable to allocate memory for %d files!",
+                         "[Job %d] Unable to allocate memory for %d files.",
                          job->id, job->num_files);
           break;
        }
       }
     }
-    else if (!strcasecmp(line, "File"))
+    else if (!_cups_strcasecmp(line, "File"))
     {
       int      number,                 /* File number */
                compression;            /* Compression value */
@@ -3317,13 +4070,13 @@ load_job_cache(const char *filename)    /* I - job.cache filename */
       if (sscanf(value, "%d%*[ \t]%15[^/]/%255s%d", &number, super, type,
                  &compression) != 4)
       {
-        cupsdLogMessage(CUPSD_LOG_ERROR, "Bad File on line %d!", linenum);
+        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!",
+        cupsdLogMessage(CUPSD_LOG_ERROR, "Bad File number %d on line %d.",
                        number, linenum);
         continue;
       }
@@ -3340,7 +4093,7 @@ load_job_cache(const char *filename)      /* I - job.cache filename */
        */
 
         cupsdLogMessage(CUPSD_LOG_ERROR,
-                       "[Job %d] Unknown MIME type %s/%s for file %d!",
+                       "[Job %d] Unknown MIME type %s/%s for file %d.",
                        job->id, super, type, number + 1);
 
         snprintf(jobfile, sizeof(jobfile), "%s/d%05d-%03d", RequestRoot,
@@ -3358,7 +4111,7 @@ load_job_cache(const char *filename)      /* I - job.cache filename */
       }
     }
     else
-      cupsdLogMessage(CUPSD_LOG_ERROR, "Unknown %s directive on line %d!",
+      cupsdLogMessage(CUPSD_LOG_ERROR, "Unknown %s directive on line %d.",
                       line, linenum);
   }
 
@@ -3402,7 +4155,7 @@ load_next_job_id(const char *filename)    /* I - job.cache filename */
 
   while (cupsFileGetConf(fp, line, sizeof(line), &value, &linenum))
   {
-    if (!strcasecmp(line, "NextJobId"))
+    if (!_cups_strcasecmp(line, "NextJobId"))
     {
       if (value)
       {
@@ -3458,7 +4211,7 @@ load_request_root(void)
 
       if ((job = calloc(sizeof(cupsd_job_t), 1)) == NULL)
       {
-        cupsdLogMessage(CUPSD_LOG_ERROR, "Ran out of memory for jobs!");
+        cupsdLogMessage(CUPSD_LOG_ERROR, "Ran out of memory for jobs.");
        cupsDirClose(dir);
        return;
       }
@@ -3484,18 +4237,19 @@ load_request_root(void)
       * Load the job...
       */
 
-      cupsdLoadJob(job);
+      if (cupsdLoadJob(job))
+      {
+       /*
+        * Insert the job into the array, sorting by job priority and ID...
+        */
 
-     /*
-      * Insert the job into the array, sorting by job priority and ID...
-      */
+       cupsArrayAdd(Jobs, job);
 
-      cupsArrayAdd(Jobs, job);
-
-      if (job->state_value <= IPP_JOB_STOPPED)
-        cupsArrayAdd(ActiveJobs, job);
-      else
-        unload_job(job);
+       if (job->state_value <= IPP_JOB_STOPPED)
+         cupsArrayAdd(ActiveJobs, job);
+       else
+         unload_job(job);
+      }
     }
 
   cupsDirClose(dir);
@@ -3503,54 +4257,63 @@ load_request_root(void)
 
 
 /*
- * 'set_hold_until()' - Set the hold time and update job-hold-until attribute.
+ * 'remove_job_files()' - Remove the document files for a job.
  */
 
 static void
-set_hold_until(cupsd_job_t *job,       /* I - Job to update */
-              time_t      holdtime)    /* I - Hold until time */
+remove_job_files(cupsd_job_t *job)     /* I - Job */
 {
-  ipp_attribute_t      *attr;          /* job-hold-until attribute */
-  struct tm            *holddate;      /* Hold date */
-  char                 holdstr[64];    /* Hold time */
+  int  i;                              /* Looping var */
+  char filename[1024];                 /* Document filename */
 
 
- /*
-  * Set the hold_until value and hold the job...
-  */
+  if (job->num_files <= 0)
+    return;
 
-  cupsdLogMessage(CUPSD_LOG_DEBUG, "set_hold_until: hold_until = %d",
-                  (int)holdtime);
+  for (i = 1; i <= job->num_files; i ++)
+  {
+    snprintf(filename, sizeof(filename), "%s/d%05d-%03d", RequestRoot,
+            job->id, i);
+    if (Classification)
+      cupsdRemoveFile(filename);
+    else
+      unlink(filename);
+  }
 
-  job->state->values[0].integer = IPP_JOB_HELD;
-  job->state_value              = IPP_JOB_HELD;
-  job->hold_until               = holdtime;
+  free(job->filetypes);
+  free(job->compressions);
 
- /*
-  * Update the job-hold-until attribute with a string representing GMT
-  * time (HH:MM:SS)...
-  */
+  job->file_time    = 0;
+  job->num_files    = 0;
+  job->filetypes    = NULL;
+  job->compressions = NULL;
+
+  LastEvent |= CUPSD_EVENT_PRINTER_STATE_CHANGED;
+}
+
+
+/*
+ * 'remove_job_history()' - Remove the control file for a job.
+ */
 
-  holddate = gmtime(&holdtime);
-  snprintf(holdstr, sizeof(holdstr), "%d:%d:%d", holddate->tm_hour,
-          holddate->tm_min, holddate->tm_sec);
+static void
+remove_job_history(cupsd_job_t *job)   /* I - Job */
+{
+  char filename[1024];                 /* Control filename */
 
-  if ((attr = ippFindAttribute(job->attrs, "job-hold-until",
-                               IPP_TAG_KEYWORD)) == NULL)
-    attr = ippFindAttribute(job->attrs, "job-hold-until", IPP_TAG_NAME);
 
  /*
-  * Either add the attribute or update the value of the existing one
+  * Remove the job info file...
   */
 
-  if (attr == NULL)
-    ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_KEYWORD, "job-hold-until",
-                 NULL, holdstr);
+  snprintf(filename, sizeof(filename), "%s/c%05d", RequestRoot,
+          job->id);
+  if (Classification)
+    cupsdRemoveFile(filename);
   else
-    cupsdSetString(&attr->values[0].string.text, holdstr);
+    unlink(filename);
 
-  job->dirty = 1;
-  cupsdMarkDirty(CUPSD_DIRTY_JOBS);
+  LastEvent |= CUPSD_EVENT_PRINTER_STATE_CHANGED;
 }
 
 
@@ -3563,12 +4326,39 @@ set_time(cupsd_job_t *job,              /* I - Job to update */
          const char  *name)            /* I - Name of attribute */
 {
   ipp_attribute_t      *attr;          /* Time attribute */
+  time_t               curtime;        /* Current time */
+
+
+  curtime = time(NULL);
 
+  cupsdLogJob(job, CUPSD_LOG_DEBUG, "%s=%ld", name, (long)curtime);
 
   if ((attr = ippFindAttribute(job->attrs, name, IPP_TAG_ZERO)) != NULL)
   {
     attr->value_tag         = IPP_TAG_INTEGER;
-    attr->values[0].integer = time(NULL);
+    attr->values[0].integer = curtime;
+  }
+
+  if (!strcmp(name, "time-at-completed"))
+  {
+    if (JobHistory < INT_MAX)
+      job->history_time = attr->values[0].integer + JobHistory;
+    else
+      job->history_time = INT_MAX;
+
+    if (job->history_time < JobHistoryUpdate || !JobHistoryUpdate)
+      JobHistoryUpdate = job->history_time;
+
+    if (JobFiles < INT_MAX)
+      job->file_time = attr->values[0].integer + JobFiles;
+    else
+      job->file_time = INT_MAX;
+
+    if (job->file_time < JobHistoryUpdate || !JobHistoryUpdate)
+      JobHistoryUpdate = job->file_time;
+
+    cupsdLogMessage(CUPSD_LOG_DEBUG2, "set_time: JobHistoryUpdate=%ld",
+                   (long)JobHistoryUpdate);
   }
 }
 
@@ -3590,6 +4380,7 @@ start_job(cupsd_job_t     *job,           /* I - Job ID */
 
   if (job->num_files == 0)
   {
+    ippSetString(job->attrs, &job->reasons, 0, "aborted-by-system");
     cupsdSetJobState(job, IPP_JOB_ABORTED, CUPSD_JOB_DEFAULT,
                      "Aborting job because it has no files.");
     return;
@@ -3602,15 +4393,37 @@ start_job(cupsd_job_t     *job,         /* I - Job ID */
   if (!cupsdLoadJob(job))
     return;
 
+  if (!job->printer_message)
+    job->printer_message = ippFindAttribute(job->attrs,
+                                            "job-printer-state-message",
+                                            IPP_TAG_TEXT);
+  if (job->printer_message)
+    cupsdSetString(&(job->printer_message->values[0].string.text), "");
+
+  ippSetString(job->attrs, &job->reasons, 0, "job-printing");
   cupsdSetJobState(job, IPP_JOB_PROCESSING, CUPSD_JOB_DEFAULT, NULL);
   cupsdSetPrinterState(printer, IPP_PRINTER_PROCESSING, 0);
+  cupsdSetPrinterReasons(printer, "-cups-remote-pending,"
+                                 "cups-remote-pending-held,"
+                                 "cups-remote-processing,"
+                                 "cups-remote-stopped,"
+                                 "cups-remote-canceled,"
+                                 "cups-remote-aborted,"
+                                 "cups-remote-completed");
 
   job->cost         = 0;
   job->current_file = 0;
+  job->file_time    = 0;
+  job->history_time = 0;
   job->progress     = 0;
   job->printer      = printer;
   printer->job      = job;
 
+  if (MaxJobTime > 0)
+    job->cancel_time = time(NULL) + MaxJobTime;
+  else
+    job->cancel_time = 0;
+
  /*
   * Setup the last exit status and security profiles...
   */
@@ -3639,9 +4452,6 @@ start_job(cupsd_job_t     *job,           /* I - Job ID */
   job->status_buffer = cupsdStatBufNew(job->status_pipes[0], NULL);
   job->status_level  = CUPSD_LOG_INFO;
 
-  if (job->printer_message)
-    cupsdSetString(&(job->printer_message->values[0].string.text), "");
-
  /*
   * Create the backchannel pipes and make them non-blocking...
   */
@@ -3698,6 +4508,11 @@ start_job(cupsd_job_t     *job,          /* I - Job ID */
   fcntl(job->side_pipes[1], F_SETFL,
        fcntl(job->side_pipes[1], F_GETFL) | O_NONBLOCK);
 
+  fcntl(job->side_pipes[0], F_SETFD,
+       fcntl(job->side_pipes[0], F_GETFD) | FD_CLOEXEC);
+  fcntl(job->side_pipes[1], F_SETFD,
+       fcntl(job->side_pipes[1], F_GETFD) | FD_CLOEXEC);
+
  /*
   * Now start the first file in the job...
   */
@@ -3725,15 +4540,34 @@ stop_job(cupsd_job_t       *job,        /* I - Job */
 
   if (action == CUPSD_JOB_DEFAULT && !job->kill_time)
     job->kill_time = time(NULL) + JobKillDelay;
-  else if (action == CUPSD_JOB_FORCE)
+  else if (action >= CUPSD_JOB_FORCE)
     job->kill_time = 0;
 
   for (i = 0; job->filters[i]; i ++)
     if (job->filters[i] > 0)
-      cupsdEndProcess(job->filters[i], action == CUPSD_JOB_FORCE);
+    {
+      cupsdEndProcess(job->filters[i], action >= CUPSD_JOB_FORCE);
+
+      if (action >= CUPSD_JOB_FORCE)
+        job->filters[i] = -job->filters[i];
+    }
 
   if (job->backend > 0)
-    cupsdEndProcess(job->backend, action == CUPSD_JOB_FORCE);
+  {
+    cupsdEndProcess(job->backend, action >= CUPSD_JOB_FORCE);
+
+    if (action >= CUPSD_JOB_FORCE)
+      job->backend = -job->backend;
+  }
+
+  if (action >= CUPSD_JOB_FORCE)
+  {
+   /*
+    * Clear job status...
+    */
+
+    job->status = 0;
+  }
 }
 
 
@@ -3753,6 +4587,7 @@ unload_job(cupsd_job_t *job)              /* I - Job */
 
   job->attrs           = NULL;
   job->state           = NULL;
+  job->reasons         = NULL;
   job->sheets          = NULL;
   job->job_sheets      = NULL;
   job->printer_message = NULL;
@@ -3769,7 +4604,8 @@ 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 */
+  char         message[CUPSD_SB_BUFFER_SIZE],
+                                       /* Message text */
                *ptr;                   /* Pointer update... */
   int          loglevel,               /* Log level for message */
                event = 0;              /* Events? */
@@ -3812,7 +4648,7 @@ update_job(cupsd_job_t *job)              /* I - Job to check */
 
       if (job->sheets)
       {
-        if (!strncasecmp(message, "total ", 6))
+        if (!_cups_strncasecmp(message, "total ", 6))
        {
         /*
          * Got a total count of pages from a backend or filter...
@@ -3827,28 +4663,7 @@ update_job(cupsd_job_t *job)             /* I - Job to check */
         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...
-           */
-
-           cupsdSetJobState(job, IPP_JOB_CANCELED, CUPSD_JOB_DEFAULT,
-                            "Canceled job because pages exceed user %s "
-                            "quota limit on printer %s (%s).",
-                            job->username, job->printer->name,
-                            job->printer->info);
-           return;
-         }
-#else
-          (void)q;
-#endif /* __APPLE__ */
-       }
+         cupsdUpdateQuota(job->printer, job->username, copies, 0);
       }
 
       cupsdLogPage(job, message);
@@ -3866,11 +4681,23 @@ update_job(cupsd_job_t *job)            /* I - Job to check */
         cupsdStopPrinter(job->printer, 1);
        return;
       }
-      else
+      else if (cupsdSetPrinterReasons(job->printer, message))
       {
-       cupsdSetPrinterReasons(job->printer, message);
-       cupsdAddPrinterHistory(job->printer);
        event |= CUPSD_EVENT_PRINTER_STATE;
+
+        if (MaxJobTime > 0 && strstr(message, "connecting-to-device") != NULL)
+        {
+         /*
+          * Reset cancel time after connecting to the device...
+          */
+
+          for (i = 0; i < job->printer->num_reasons; i ++)
+            if (!strcmp(job->printer->reasons[i], "connecting-to-device"))
+              break;
+
+          if (i >= job->printer->num_reasons)
+           job->cancel_time = time(NULL) + MaxJobTime;
+        }
       }
 
       update_job_attrs(job, 0);
@@ -3896,10 +4723,7 @@ update_job(cupsd_job_t *job)             /* I - Job to check */
         cupsdSetAuthInfoRequired(job->printer, attr, NULL);
        cupsdSetPrinterAttrs(job->printer);
 
-       if (job->printer->type & CUPS_PRINTER_DISCOVERED)
-         cupsdMarkDirty(CUPSD_DIRTY_REMOTE);
-       else
-         cupsdMarkDirty(CUPSD_DIRTY_PRINTERS);
+       cupsdMarkDirty(CUPSD_DIRTY_PRINTERS);
       }
 
       if ((attr = cupsGetOption("job-media-progress", num_attrs,
@@ -4009,49 +4833,39 @@ update_job(cupsd_job_t *job)            /* I - Job to check */
 
       cupsFreeOptions(num_keywords, keywords);
     }
-#ifdef __APPLE__
-    else if (!strncmp(message, "recoverable:", 12))
+    else
     {
-      ptr = message + 12;
-      while (isspace(*ptr & 255))
-        ptr ++;
+     /*
+      * Strip legacy message prefix...
+      */
 
-      if (*ptr)
+      if (!strncmp(message, "recoverable:", 12))
       {
-       cupsdSetPrinterReasons(job->printer,
-                              "+com.apple.print.recoverable-warning");
-       cupsdSetString(&(job->printer->recoverable), ptr);
-       cupsdAddPrinterHistory(job->printer);
-       event |= CUPSD_EVENT_PRINTER_STATE;
+        ptr = message + 12;
+       while (isspace(*ptr & 255))
+          ptr ++;
       }
-    }
-    else if (!strncmp(message, "recovered:", 10))
-    {
-      cupsdSetPrinterReasons(job->printer,
-                             "-com.apple.print.recoverable-warning");
-
-      ptr = message + 10;
-      while (isspace(*ptr & 255))
-        ptr ++;
+      else if (!strncmp(message, "recovered:", 10))
+      {
+        ptr = message + 10;
+       while (isspace(*ptr & 255))
+          ptr ++;
+      }
+      else
+        ptr = message;
 
-      cupsdSetString(&(job->printer->recoverable), ptr);
-      cupsdAddPrinterHistory(job->printer);
-      event |= CUPSD_EVENT_PRINTER_STATE;
-    }
-#endif /* __APPLE__ */
-    else
-    {
-      cupsdLogJob(job, loglevel, "%s", message);
+      if (*ptr)
+        cupsdLogJob(job, loglevel, "%s", ptr);
 
-      if (loglevel < CUPSD_LOG_DEBUG)
+      if (loglevel < CUPSD_LOG_DEBUG &&
+          strcmp(job->printer->state_message, ptr))
       {
-       strlcpy(job->printer->state_message, message,
+       strlcpy(job->printer->state_message, ptr,
                sizeof(job->printer->state_message));
-       cupsdAddPrinterHistory(job->printer);
 
        event |= CUPSD_EVENT_PRINTER_STATE | CUPSD_EVENT_JOB_PROGRESS;
 
-       if (loglevel < job->status_level)
+       if (loglevel <= job->status_level && job->status_level > CUPSD_LOG_ERROR)
        {
         /*
          * Some messages show in the job-printer-state-message attribute...
@@ -4075,6 +4889,9 @@ update_job(cupsd_job_t *job)              /* I - Job to check */
       break;
   }
 
+  if (event & CUPSD_EVENT_JOB_PROGRESS)
+    cupsdAddEvent(CUPSD_EVENT_JOB_PROGRESS, job->printer, job,
+                  "%s", job->printer->state_message);
   if (event & CUPSD_EVENT_PRINTER_STATE)
     cupsdAddEvent(CUPSD_EVENT_PRINTER_STATE, job->printer, NULL,
                  (job->printer->type & CUPS_PRINTER_CLASS) ?
@@ -4082,9 +4899,6 @@ update_job(cupsd_job_t *job)              /* I - Job to check */
                      "Printer \"%s\" state changed.",
                  job->printer->name);
 
-  if (event & CUPSD_EVENT_JOB_PROGRESS)
-    cupsdAddEvent(CUPSD_EVENT_JOB_PROGRESS, job->printer, job,
-                  "%s", job->printer->state_message);
 
   if (ptr == NULL && !job->status_buffer->bufused)
   {
@@ -4119,7 +4933,7 @@ update_job(cupsd_job_t *job)              /* I - Job to check */
     * Handle the end of job stuff...
     */
 
-    finalize_job(job);
+    finalize_job(job, 1);
 
    /*
     * Check for new jobs...
@@ -4169,11 +4983,21 @@ update_job_attrs(cupsd_job_t *job,      /* I - Job to update */
 
   if (job->state_value != IPP_JOB_PROCESSING &&
       job->status_level == CUPSD_LOG_INFO)
+  {
     cupsdSetString(&(job->printer_message->values[0].string.text), "");
+
+    job->dirty = 1;
+    cupsdMarkDirty(CUPSD_DIRTY_JOBS);
+  }
   else if (job->printer->state_message[0] && do_message)
+  {
     cupsdSetString(&(job->printer_message->values[0].string.text),
                   job->printer->state_message);
-  
+
+    job->dirty = 1;
+    cupsdMarkDirty(CUPSD_DIRTY_JOBS);
+  }
+
  /*
   * ... and the printer-state-reasons value...
   */
@@ -4229,6 +5053,9 @@ update_job_attrs(cupsd_job_t *job,        /* I - Job to update */
 
   for (i = 0; i < num_reasons; i ++)
     job->printer_reasons->values[i].string.text = _cupsStrAlloc(reasons[i]);
+
+  job->dirty = 1;
+  cupsdMarkDirty(CUPSD_DIRTY_JOBS);
 }