]> git.ipfire.org Git - thirdparty/cups.git/blob - scheduler/job.c
781b11514edf845a8aa488b83d8367fb2fae4112
[thirdparty/cups.git] / scheduler / job.c
1 /*
2 * Job management routines for the CUPS scheduler.
3 *
4 * Copyright © 2007-2018 by Apple Inc.
5 * Copyright © 1997-2007 by Easy Software Products, all rights reserved.
6 *
7 * Licensed under Apache License v2.0. See the file "LICENSE" for more
8 * information.
9 */
10
11 /*
12 * Include necessary headers...
13 */
14
15 #include "cupsd.h"
16 #include <grp.h>
17 #include <cups/backend.h>
18 #include <cups/dir.h>
19 #ifdef __APPLE__
20 # include <IOKit/pwr_mgt/IOPMLib.h>
21 # ifdef HAVE_IOKIT_PWR_MGT_IOPMLIBPRIVATE_H
22 # include <IOKit/pwr_mgt/IOPMLibPrivate.h>
23 # endif /* HAVE_IOKIT_PWR_MGT_IOPMLIBPRIVATE_H */
24 #endif /* __APPLE__ */
25
26
27 /*
28 * Design Notes for Job Management
29 * -------------------------------
30 *
31 * STATE CHANGES
32 *
33 * pending Do nothing/check jobs
34 * pending-held Send SIGTERM to filters and backend
35 * processing Do nothing/start job
36 * stopped Send SIGKILL to filters and backend
37 * canceled Send SIGTERM to filters and backend
38 * aborted Finalize
39 * completed Finalize
40 *
41 * Finalize clears the printer <-> job association, deletes the status
42 * buffer, closes all of the pipes, etc. and doesn't get run until all of
43 * the print processes are finished.
44 *
45 * UNLOADING OF JOBS (cupsdUnloadCompletedJobs)
46 *
47 * We unload the job attributes when they are not needed to reduce overall
48 * memory consumption. We don't unload jobs where job->state_value <
49 * IPP_JOB_STOPPED, job->printer != NULL, or job->access_time is recent.
50 *
51 * STARTING OF JOBS (start_job)
52 *
53 * When a job is started, a status buffer, several pipes, a security
54 * profile, and a backend process are created for the life of that job.
55 * These are shared for every file in a job. For remote print jobs, the
56 * IPP backend is provided with every file in the job and no filters are
57 * run.
58 *
59 * The job->printer member tracks which printer is printing a job, which
60 * can be different than the destination in job->dest for classes. The
61 * printer object also has a job pointer to track which job is being
62 * printed.
63 *
64 * PRINTING OF JOB FILES (cupsdContinueJob)
65 *
66 * Each file in a job is filtered by 0 or more programs. After getting the
67 * list of filters needed and the total cost, the job is either passed or
68 * put back to the processing state until the current FilterLevel comes down
69 * enough to allow printing.
70 *
71 * If we can print, we build a string for the print options and run each of
72 * the filters, piping the output from one into the next.
73 *
74 * JOB STATUS UPDATES (update_job)
75 *
76 * The update_job function gets called whenever there are pending messages
77 * on the status pipe. These generally are updates to the marker-*,
78 * printer-state-message, or printer-state-reasons attributes. On EOF,
79 * finalize_job is called to clean up.
80 *
81 * FINALIZING JOBS (finalize_job)
82 *
83 * When all filters and the backend are done, we set the job state to
84 * completed (no errors), aborted (filter errors or abort-job policy),
85 * pending-held (auth required or retry-job policy), or pending
86 * (retry-current-job or stop-printer policies) as appropriate.
87 *
88 * Then we close the pipes and free the status buffers and profiles.
89 *
90 * JOB FILE COMPLETION (process_children in main.c)
91 *
92 * For multiple-file jobs, process_children (in main.c) sees that all
93 * filters have exited and calls in to print the next file if there are
94 * more files in the job, otherwise it waits for the backend to exit and
95 * update_job to do the cleanup.
96 */
97
98
99 /*
100 * Local globals...
101 */
102
103 static mime_filter_t gziptoany_filter =
104 {
105 NULL, /* Source type */
106 NULL, /* Destination type */
107 0, /* Cost */
108 "gziptoany" /* Filter program to run */
109 };
110
111
112 /*
113 * Local functions...
114 */
115
116 static int compare_active_jobs(void *first, void *second, void *data);
117 static int compare_completed_jobs(void *first, void *second, void *data);
118 static int compare_jobs(void *first, void *second, void *data);
119 static void dump_job_history(cupsd_job_t *job);
120 static void finalize_job(cupsd_job_t *job, int set_job_state);
121 static void free_job_history(cupsd_job_t *job);
122 static char *get_options(cupsd_job_t *job, int banner_page, char *copies,
123 size_t copies_size, char *title,
124 size_t title_size);
125 static size_t ipp_length(ipp_t *ipp);
126 static void load_job_cache(const char *filename);
127 static void load_next_job_id(const char *filename);
128 static void load_request_root(void);
129 static void remove_job_files(cupsd_job_t *job);
130 static void remove_job_history(cupsd_job_t *job);
131 static void set_time(cupsd_job_t *job, const char *name);
132 static void start_job(cupsd_job_t *job, cupsd_printer_t *printer);
133 static void stop_job(cupsd_job_t *job, cupsd_jobaction_t action);
134 static void unload_job(cupsd_job_t *job);
135 static void update_job(cupsd_job_t *job);
136 static void update_job_attrs(cupsd_job_t *job, int do_message);
137
138
139 /*
140 * 'cupsdAddJob()' - Add a new job to the job queue.
141 */
142
143 cupsd_job_t * /* O - New job record */
144 cupsdAddJob(int priority, /* I - Job priority */
145 const char *dest) /* I - Job destination */
146 {
147 cupsd_job_t *job; /* New job record */
148
149
150 if ((job = calloc(sizeof(cupsd_job_t), 1)) == NULL)
151 return (NULL);
152
153 job->id = NextJobId ++;
154 job->priority = priority;
155 job->back_pipes[0] = -1;
156 job->back_pipes[1] = -1;
157 job->print_pipes[0] = -1;
158 job->print_pipes[1] = -1;
159 job->side_pipes[0] = -1;
160 job->side_pipes[1] = -1;
161 job->status_pipes[0] = -1;
162 job->status_pipes[1] = -1;
163
164 cupsdSetString(&job->dest, dest);
165
166 /*
167 * Add the new job to the "all jobs" and "active jobs" lists...
168 */
169
170 cupsArrayAdd(Jobs, job);
171 cupsArrayAdd(ActiveJobs, job);
172
173 return (job);
174 }
175
176
177 /*
178 * 'cupsdCancelJobs()' - Cancel all jobs for the given destination/user.
179 */
180
181 void
182 cupsdCancelJobs(const char *dest, /* I - Destination to cancel */
183 const char *username, /* I - Username or NULL */
184 int purge) /* I - Purge jobs? */
185 {
186 cupsd_job_t *job; /* Current job */
187
188
189 for (job = (cupsd_job_t *)cupsArrayFirst(Jobs);
190 job;
191 job = (cupsd_job_t *)cupsArrayNext(Jobs))
192 {
193 if ((!job->dest || !job->username) && !cupsdLoadJob(job))
194 continue;
195
196 if ((!dest || !strcmp(job->dest, dest)) &&
197 (!username || !strcmp(job->username, username)))
198 {
199 /*
200 * Cancel all jobs matching this destination/user...
201 */
202
203 if (purge)
204 cupsdSetJobState(job, IPP_JOB_CANCELED, CUPSD_JOB_PURGE,
205 "Job purged by user.");
206 else if (job->state_value < IPP_JOB_CANCELED)
207 cupsdSetJobState(job, IPP_JOB_CANCELED, CUPSD_JOB_DEFAULT,
208 "Job canceled by user.");
209 }
210 }
211 }
212
213
214 /*
215 * 'cupsdCheckJobs()' - Check the pending jobs and start any if the destination
216 * is available.
217 */
218
219 void
220 cupsdCheckJobs(void)
221 {
222 cupsd_job_t *job; /* Current job in queue */
223 cupsd_printer_t *printer, /* Printer destination */
224 *pclass; /* Printer class destination */
225 ipp_attribute_t *attr; /* Job attribute */
226 time_t curtime; /* Current time */
227 const char *reasons; /* job-state-reasons value */
228
229
230 curtime = time(NULL);
231
232 cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdCheckJobs: %d active jobs, sleeping=%d, ac-power=%d, reload=%d, curtime=%ld", cupsArrayCount(ActiveJobs), Sleeping, ACPower, NeedReload, (long)curtime);
233
234 for (job = (cupsd_job_t *)cupsArrayFirst(ActiveJobs);
235 job;
236 job = (cupsd_job_t *)cupsArrayNext(ActiveJobs))
237 {
238 cupsdLogMessage(CUPSD_LOG_DEBUG2,
239 "cupsdCheckJobs: Job %d - dest=\"%s\", printer=%p, "
240 "state=%d, cancel_time=%ld, hold_until=%ld, kill_time=%ld, "
241 "pending_cost=%d, pending_timeout=%ld", job->id, job->dest,
242 job->printer, job->state_value, (long)job->cancel_time,
243 (long)job->hold_until, (long)job->kill_time,
244 job->pending_cost, (long)job->pending_timeout);
245
246 /*
247 * Kill jobs if they are unresponsive...
248 */
249
250 if (job->kill_time && job->kill_time <= curtime)
251 {
252 if (!job->completed)
253 cupsdLogJob(job, CUPSD_LOG_ERROR, "Stopping unresponsive job.");
254
255 stop_job(job, CUPSD_JOB_FORCE);
256 continue;
257 }
258
259 /*
260 * Cancel stuck jobs...
261 */
262
263 if (job->cancel_time && job->cancel_time <= curtime)
264 {
265 int cancel_after; /* job-cancel-after value */
266
267 attr = ippFindAttribute(job->attrs, "job-cancel-after", IPP_TAG_INTEGER);
268 cancel_after = attr ? ippGetInteger(attr, 0) : MaxJobTime;
269
270 if (job->completed)
271 cupsdSetJobState(job, IPP_JOB_CANCELED, CUPSD_JOB_FORCE, "Marking stuck job as completed after %d seconds.", cancel_after);
272 else
273 cupsdSetJobState(job, IPP_JOB_CANCELED, CUPSD_JOB_DEFAULT, "Canceling stuck job after %d seconds.", cancel_after);
274 continue;
275 }
276
277 /*
278 * Start held jobs if they are ready...
279 */
280
281 if (job->state_value == IPP_JOB_HELD &&
282 job->hold_until &&
283 job->hold_until < curtime)
284 {
285 if (job->pending_timeout)
286 {
287 /*
288 * This job is pending; check that we don't have an active Send-Document
289 * operation in progress on any of the client connections, then timeout
290 * the job so we can start printing...
291 */
292
293 cupsd_client_t *con; /* Current client connection */
294
295 for (con = (cupsd_client_t *)cupsArrayFirst(Clients);
296 con;
297 con = (cupsd_client_t *)cupsArrayNext(Clients))
298 if (con->request &&
299 con->request->request.op.operation_id == IPP_SEND_DOCUMENT)
300 break;
301
302 if (con)
303 continue;
304
305 if (cupsdTimeoutJob(job))
306 continue;
307 }
308
309 cupsdSetJobState(job, IPP_JOB_PENDING, CUPSD_JOB_DEFAULT,
310 "Job submission timed out.");
311 }
312
313 /*
314 * Continue jobs that are waiting on the FilterLimit...
315 */
316
317 if (job->pending_cost > 0 &&
318 ((FilterLevel + job->pending_cost) < FilterLimit || FilterLevel == 0))
319 cupsdContinueJob(job);
320
321 /*
322 * Skip jobs that where held-on-create
323 */
324
325 reasons = ippGetString(job->reasons, 0, NULL);
326 if (reasons && !strcmp(reasons, "job-held-on-create"))
327 {
328 /*
329 * Check whether the printer is still holding new jobs...
330 */
331
332 printer = cupsdFindDest(job->dest);
333
334 if (printer->holding_new_jobs)
335 continue;
336
337 ippSetString(job->attrs, &job->reasons, 0, "none");
338 }
339
340 /*
341 * Start pending jobs if the destination is available...
342 */
343
344 if (job->state_value == IPP_JOB_PENDING && !NeedReload &&
345 (!Sleeping || ACPower) && !DoingShutdown && !job->printer)
346 {
347 printer = cupsdFindDest(job->dest);
348 pclass = NULL;
349
350 while (printer && (printer->type & CUPS_PRINTER_CLASS))
351 {
352 /*
353 * If the class is remote, just pass it to the remote server...
354 */
355
356 pclass = printer;
357
358 if (pclass->state == IPP_PRINTER_STOPPED)
359 printer = NULL;
360 else if (pclass->type & CUPS_PRINTER_REMOTE)
361 break;
362 else
363 printer = cupsdFindAvailablePrinter(printer->name);
364 }
365
366 if (!printer && !pclass)
367 {
368 /*
369 * Whoa, the printer and/or class for this destination went away;
370 * cancel the job...
371 */
372
373 cupsdSetJobState(job, IPP_JOB_ABORTED, CUPSD_JOB_PURGE,
374 "Job aborted because the destination printer/class "
375 "has gone away.");
376 }
377 else if (printer)
378 {
379 /*
380 * See if the printer is available or remote and not printing a job;
381 * if so, start the job...
382 */
383
384 if (pclass)
385 {
386 /*
387 * Add/update a job-printer-uri-actual attribute for this job
388 * so that we know which printer actually printed the job...
389 */
390
391 if ((attr = ippFindAttribute(job->attrs, "job-printer-uri-actual", IPP_TAG_URI)) != NULL)
392 ippSetString(job->attrs, &attr, 0, printer->uri);
393 else
394 ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_URI, "job-printer-uri-actual", NULL, printer->uri);
395
396 job->dirty = 1;
397 cupsdMarkDirty(CUPSD_DIRTY_JOBS);
398 }
399
400 if (!printer->job && printer->state == IPP_PRINTER_IDLE)
401 {
402 /*
403 * Start the job...
404 */
405
406 cupsArraySave(ActiveJobs);
407 start_job(job, printer);
408 cupsArrayRestore(ActiveJobs);
409 }
410 }
411 }
412 }
413 }
414
415
416 /*
417 * 'cupsdCleanJobs()' - Clean out old jobs.
418 */
419
420 void
421 cupsdCleanJobs(void)
422 {
423 cupsd_job_t *job; /* Current job */
424 time_t curtime; /* Current time */
425
426
427 cupsdLogMessage(CUPSD_LOG_DEBUG2,
428 "cupsdCleanJobs: MaxJobs=%d, JobHistory=%d, JobFiles=%d",
429 MaxJobs, JobHistory, JobFiles);
430
431 if (MaxJobs <= 0 && JobHistory == INT_MAX && JobFiles == INT_MAX)
432 return;
433
434 curtime = time(NULL);
435 JobHistoryUpdate = 0;
436
437 for (job = (cupsd_job_t *)cupsArrayFirst(Jobs);
438 job;
439 job = (cupsd_job_t *)cupsArrayNext(Jobs))
440 {
441 if (job->state_value >= IPP_JOB_CANCELED && !job->printer)
442 {
443 /*
444 * Expire old jobs (or job files)...
445 */
446
447 if ((MaxJobs > 0 && cupsArrayCount(Jobs) >= MaxJobs) ||
448 (job->history_time && job->history_time <= curtime))
449 {
450 cupsdLogJob(job, CUPSD_LOG_DEBUG, "Removing from history.");
451 cupsdDeleteJob(job, CUPSD_JOB_PURGE);
452 }
453 else if (job->file_time && job->file_time <= curtime)
454 {
455 cupsdLogJob(job, CUPSD_LOG_DEBUG, "Removing document files.");
456 cupsdLogJob(job, CUPSD_LOG_DEBUG2, "curtime=%ld, job->file_time=%ld", (long)curtime, (long)job->file_time);
457 remove_job_files(job);
458
459 cupsdMarkDirty(CUPSD_DIRTY_JOBS);
460
461 if (job->history_time < JobHistoryUpdate || !JobHistoryUpdate)
462 JobHistoryUpdate = job->history_time;
463 }
464 else
465 {
466 if (job->history_time < JobHistoryUpdate || !JobHistoryUpdate)
467 JobHistoryUpdate = job->history_time;
468
469 if (job->file_time < JobHistoryUpdate || !JobHistoryUpdate)
470 JobHistoryUpdate = job->file_time;
471 }
472 }
473 }
474
475 cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdCleanJobs: JobHistoryUpdate=%ld",
476 (long)JobHistoryUpdate);
477 }
478
479
480 /*
481 * 'cupsdContinueJob()' - Continue printing with the next file in a job.
482 */
483
484 void
485 cupsdContinueJob(cupsd_job_t *job) /* I - Job */
486 {
487 int i; /* Looping var */
488 int slot; /* Pipe slot */
489 cups_array_t *filters = NULL,/* Filters for job */
490 *prefilters; /* Filters with prefilters */
491 mime_filter_t *filter, /* Current filter */
492 *prefilter, /* Prefilter */
493 port_monitor; /* Port monitor filter */
494 char scheme[255]; /* Device URI scheme */
495 ipp_attribute_t *attr; /* Current attribute */
496 const char *ptr, /* Pointer into value */
497 *abort_message; /* Abort message */
498 ipp_jstate_t abort_state = IPP_JOB_STOPPED;
499 /* New job state on abort */
500 struct stat backinfo; /* Backend file information */
501 int backroot; /* Run backend as root? */
502 int pid; /* Process ID of new filter process */
503 int banner_page; /* 1 if banner page, 0 otherwise */
504 int filterfds[2][2] = { { -1, -1 }, { -1, -1 } };
505 /* Pipes used between filters */
506 int envc; /* Number of environment variables */
507 struct stat fileinfo; /* Job file information */
508 int argc = 0; /* Number of arguments */
509 char **argv = NULL, /* Filter command-line arguments */
510 filename[1024], /* Job filename */
511 command[1024], /* Full path to command */
512 jobid[255], /* Job ID string */
513 title[IPP_MAX_NAME],
514 /* Job title string */
515 copies[255], /* # copies string */
516 *options, /* Options string */
517 *envp[MAX_ENV + 21],
518 /* Environment variables */
519 charset[255], /* CHARSET env variable */
520 class_name[255],/* CLASS env variable */
521 classification[1024],
522 /* CLASSIFICATION env variable */
523 content_type[1024],
524 /* CONTENT_TYPE env variable */
525 device_uri[1024],
526 /* DEVICE_URI env variable */
527 final_content_type[1024] = "",
528 /* FINAL_CONTENT_TYPE env variable */
529 lang[255], /* LANG env variable */
530 #ifdef __APPLE__
531 apple_language[255],
532 /* APPLE_LANGUAGE env variable */
533 #endif /* __APPLE__ */
534 auth_info_required[255],
535 /* AUTH_INFO_REQUIRED env variable */
536 ppd[1024], /* PPD env variable */
537 printer_info[255],
538 /* PRINTER_INFO env variable */
539 printer_location[255],
540 /* PRINTER_LOCATION env variable */
541 printer_name[255],
542 /* PRINTER env variable */
543 *printer_state_reasons = NULL,
544 /* PRINTER_STATE_REASONS env var */
545 rip_max_cache[255];
546 /* RIP_MAX_CACHE env variable */
547
548
549 cupsdLogMessage(CUPSD_LOG_DEBUG2,
550 "cupsdContinueJob(job=%p(%d)): current_file=%d, num_files=%d",
551 job, job->id, job->current_file, job->num_files);
552
553 /*
554 * Figure out what filters are required to convert from
555 * the source to the destination type...
556 */
557
558 FilterLevel -= job->cost;
559
560 job->cost = 0;
561 job->pending_cost = 0;
562
563 memset(job->filters, 0, sizeof(job->filters));
564
565 if (job->printer->raw)
566 {
567 /*
568 * Remote jobs and raw queues go directly to the printer without
569 * filtering...
570 */
571
572 cupsdLogJob(job, CUPSD_LOG_DEBUG, "Sending job to queue tagged as raw...");
573 }
574 else
575 {
576 /*
577 * Local jobs get filtered...
578 */
579
580 mime_type_t *dst = job->printer->filetype;
581 /* Destination file type */
582
583 snprintf(filename, sizeof(filename), "%s/d%05d-%03d", RequestRoot,
584 job->id, job->current_file + 1);
585 if (stat(filename, &fileinfo))
586 fileinfo.st_size = 0;
587
588 if (job->retry_as_raster)
589 {
590 /*
591 * Need to figure out whether the printer supports image/pwg-raster or
592 * image/urf, and use the corresponding type...
593 */
594
595 char type[MIME_MAX_TYPE]; /* MIME media type for printer */
596
597 snprintf(type, sizeof(type), "%s/image/urf", job->printer->name);
598 if ((dst = mimeType(MimeDatabase, "printer", type)) == NULL)
599 {
600 snprintf(type, sizeof(type), "%s/image/pwg-raster", job->printer->name);
601 dst = mimeType(MimeDatabase, "printer", type);
602 }
603
604 if (dst)
605 cupsdLogJob(job, CUPSD_LOG_DEBUG, "Retrying job as \"%s\".", strchr(dst->type, '/') + 1);
606 else
607 cupsdLogJob(job, CUPSD_LOG_ERROR, "Unable to retry job using a supported raster format.");
608 }
609
610 filters = mimeFilter2(MimeDatabase, job->filetypes[job->current_file], (size_t)fileinfo.st_size, dst, &(job->cost));
611
612 if (!filters)
613 {
614 cupsdLogJob(job, CUPSD_LOG_ERROR,
615 "Unable to convert file %d to printable format.",
616 job->current_file);
617
618 abort_message = "Aborting job because it cannot be printed.";
619 abort_state = IPP_JOB_ABORTED;
620
621 ippSetString(job->attrs, &job->reasons, 0, "document-unprintable-error");
622 goto abort_job;
623 }
624
625 /*
626 * Figure out the final content type...
627 */
628
629 cupsdLogJob(job, CUPSD_LOG_DEBUG, "%d filters for job:",
630 cupsArrayCount(filters));
631 for (filter = (mime_filter_t *)cupsArrayFirst(filters);
632 filter;
633 filter = (mime_filter_t *)cupsArrayNext(filters))
634 cupsdLogJob(job, CUPSD_LOG_DEBUG, "%s (%s/%s to %s/%s, cost %d)",
635 filter->filter,
636 filter->src ? filter->src->super : "???",
637 filter->src ? filter->src->type : "???",
638 filter->dst ? filter->dst->super : "???",
639 filter->dst ? filter->dst->type : "???",
640 filter->cost);
641
642 if (!job->printer->remote)
643 {
644 for (filter = (mime_filter_t *)cupsArrayLast(filters);
645 filter && filter->dst;
646 filter = (mime_filter_t *)cupsArrayPrev(filters))
647 if (strcmp(filter->dst->super, "printer") ||
648 strcmp(filter->dst->type, job->printer->name))
649 break;
650
651 if (filter && filter->dst)
652 {
653 if ((ptr = strchr(filter->dst->type, '/')) != NULL)
654 snprintf(final_content_type, sizeof(final_content_type),
655 "FINAL_CONTENT_TYPE=%s", ptr + 1);
656 else
657 snprintf(final_content_type, sizeof(final_content_type),
658 "FINAL_CONTENT_TYPE=%s/%s", filter->dst->super,
659 filter->dst->type);
660 }
661 else
662 snprintf(final_content_type, sizeof(final_content_type),
663 "FINAL_CONTENT_TYPE=printer/%s", job->printer->name);
664 }
665
666 /*
667 * Remove NULL ("-") filters...
668 */
669
670 for (filter = (mime_filter_t *)cupsArrayFirst(filters);
671 filter;
672 filter = (mime_filter_t *)cupsArrayNext(filters))
673 if (!strcmp(filter->filter, "-"))
674 cupsArrayRemove(filters, filter);
675
676 if (cupsArrayCount(filters) == 0)
677 {
678 cupsArrayDelete(filters);
679 filters = NULL;
680 }
681
682 /*
683 * If this printer has any pre-filters, insert the required pre-filter
684 * in the filters array...
685 */
686
687 if (job->printer->prefiltertype && filters)
688 {
689 prefilters = cupsArrayNew(NULL, NULL);
690
691 for (filter = (mime_filter_t *)cupsArrayFirst(filters);
692 filter;
693 filter = (mime_filter_t *)cupsArrayNext(filters))
694 {
695 if ((prefilter = mimeFilterLookup(MimeDatabase, filter->src,
696 job->printer->prefiltertype)))
697 {
698 cupsArrayAdd(prefilters, prefilter);
699 job->cost += prefilter->cost;
700 }
701
702 cupsArrayAdd(prefilters, filter);
703 }
704
705 cupsArrayDelete(filters);
706 filters = prefilters;
707 }
708 }
709
710 /*
711 * Set a minimum cost of 100 for all jobs so that FilterLimit
712 * works with raw queues and other low-cost paths.
713 */
714
715 if (job->cost < 100)
716 job->cost = 100;
717
718 /*
719 * See if the filter cost is too high...
720 */
721
722 if ((FilterLevel + job->cost) > FilterLimit && FilterLevel > 0 &&
723 FilterLimit > 0)
724 {
725 /*
726 * Don't print this job quite yet...
727 */
728
729 cupsArrayDelete(filters);
730
731 cupsdLogJob(job, CUPSD_LOG_INFO,
732 "Holding because filter limit has been reached.");
733 cupsdLogJob(job, CUPSD_LOG_DEBUG2,
734 "cupsdContinueJob: file=%d, cost=%d, level=%d, limit=%d",
735 job->current_file, job->cost, FilterLevel,
736 FilterLimit);
737
738 job->pending_cost = job->cost;
739 job->cost = 0;
740 return;
741 }
742
743 FilterLevel += job->cost;
744
745 /*
746 * Add decompression/raw filter as needed...
747 */
748
749 if ((job->compressions[job->current_file] && (!job->printer->remote || job->num_files == 1)) ||
750 (!job->printer->remote && job->printer->raw && job->num_files > 1))
751 {
752 /*
753 * Add gziptoany filter to the front of the list...
754 */
755
756 if (!filters)
757 filters = cupsArrayNew(NULL, NULL);
758
759 if (!cupsArrayInsert(filters, &gziptoany_filter))
760 {
761 cupsdLogJob(job, CUPSD_LOG_DEBUG,
762 "Unable to add decompression filter - %s", strerror(errno));
763
764 cupsArrayDelete(filters);
765
766 abort_message = "Stopping job because the scheduler ran out of memory.";
767
768 goto abort_job;
769 }
770 }
771
772 /*
773 * Add port monitor, if any...
774 */
775
776 if (job->printer->port_monitor)
777 {
778 /*
779 * Add port monitor to the end of the list...
780 */
781
782 if (!filters)
783 filters = cupsArrayNew(NULL, NULL);
784
785 port_monitor.src = NULL;
786 port_monitor.dst = NULL;
787 port_monitor.cost = 0;
788
789 snprintf(port_monitor.filter, sizeof(port_monitor.filter),
790 "%s/monitor/%s", ServerBin, job->printer->port_monitor);
791
792 if (!cupsArrayAdd(filters, &port_monitor))
793 {
794 cupsdLogJob(job, CUPSD_LOG_DEBUG,
795 "Unable to add port monitor - %s", strerror(errno));
796
797 abort_message = "Stopping job because the scheduler ran out of memory.";
798
799 goto abort_job;
800 }
801 }
802
803 /*
804 * Make sure we don't go over the "MAX_FILTERS" limit...
805 */
806
807 if (cupsArrayCount(filters) > MAX_FILTERS)
808 {
809 cupsdLogJob(job, CUPSD_LOG_DEBUG,
810 "Too many filters (%d > %d), unable to print.",
811 cupsArrayCount(filters), MAX_FILTERS);
812
813 abort_message = "Aborting job because it needs too many filters to print.";
814 abort_state = IPP_JOB_ABORTED;
815
816 ippSetString(job->attrs, &job->reasons, 0, "document-unprintable-error");
817
818 goto abort_job;
819 }
820
821 /*
822 * Determine if we are printing a banner page or not...
823 */
824
825 if (job->job_sheets == NULL)
826 {
827 cupsdLogJob(job, CUPSD_LOG_DEBUG, "No job-sheets attribute.");
828 if ((job->job_sheets =
829 ippFindAttribute(job->attrs, "job-sheets", IPP_TAG_ZERO)) != NULL)
830 cupsdLogJob(job, CUPSD_LOG_DEBUG,
831 "... but someone added one without setting job_sheets.");
832 }
833 else if (job->job_sheets->num_values == 1)
834 cupsdLogJob(job, CUPSD_LOG_DEBUG, "job-sheets=%s",
835 job->job_sheets->values[0].string.text);
836 else
837 cupsdLogJob(job, CUPSD_LOG_DEBUG, "job-sheets=%s,%s",
838 job->job_sheets->values[0].string.text,
839 job->job_sheets->values[1].string.text);
840
841 if (job->printer->type & CUPS_PRINTER_REMOTE)
842 banner_page = 0;
843 else if (job->job_sheets == NULL)
844 banner_page = 0;
845 else if (_cups_strcasecmp(job->job_sheets->values[0].string.text, "none") != 0 &&
846 job->current_file == 0)
847 banner_page = 1;
848 else if (job->job_sheets->num_values > 1 &&
849 _cups_strcasecmp(job->job_sheets->values[1].string.text, "none") != 0 &&
850 job->current_file == (job->num_files - 1))
851 banner_page = 1;
852 else
853 banner_page = 0;
854
855 if ((options = get_options(job, banner_page, copies, sizeof(copies), title,
856 sizeof(title))) == NULL)
857 {
858 abort_message = "Stopping job because the scheduler ran out of memory.";
859
860 goto abort_job;
861 }
862
863 /*
864 * Build the command-line arguments for the filters. Each filter
865 * has 6 or 7 arguments:
866 *
867 * argv[0] = printer
868 * argv[1] = job ID
869 * argv[2] = username
870 * argv[3] = title
871 * argv[4] = # copies
872 * argv[5] = options
873 * argv[6] = filename (optional; normally stdin)
874 *
875 * This allows legacy printer drivers that use the old System V
876 * printing interface to be used by CUPS.
877 *
878 * For remote jobs, we send all of the files in the argument list.
879 */
880
881 if (job->printer->remote)
882 argc = 6 + job->num_files;
883 else
884 argc = 7;
885
886 if ((argv = calloc((size_t)argc + 1, sizeof(char *))) == NULL)
887 {
888 cupsdLogMessage(CUPSD_LOG_DEBUG, "Unable to allocate argument array - %s",
889 strerror(errno));
890
891 abort_message = "Stopping job because the scheduler ran out of memory.";
892
893 goto abort_job;
894 }
895
896 sprintf(jobid, "%d", job->id);
897
898 argv[0] = job->printer->name;
899 argv[1] = jobid;
900 argv[2] = job->username;
901 argv[3] = title;
902 argv[4] = copies;
903 argv[5] = options;
904
905 if (job->printer->remote && job->num_files > 1)
906 {
907 for (i = 0; i < job->num_files; i ++)
908 {
909 snprintf(filename, sizeof(filename), "%s/d%05d-%03d", RequestRoot,
910 job->id, i + 1);
911 argv[6 + i] = strdup(filename);
912 }
913 }
914 else
915 {
916 snprintf(filename, sizeof(filename), "%s/d%05d-%03d", RequestRoot,
917 job->id, job->current_file + 1);
918 argv[6] = strdup(filename);
919 }
920
921 for (i = 0; argv[i]; i ++)
922 cupsdLogJob(job, CUPSD_LOG_DEBUG, "argv[%d]=\"%s\"", i, argv[i]);
923
924 /*
925 * Create environment variable strings for the filters...
926 */
927
928 attr = ippFindAttribute(job->attrs, "attributes-natural-language",
929 IPP_TAG_LANGUAGE);
930
931 #ifdef __APPLE__
932 strlcpy(apple_language, "APPLE_LANGUAGE=", sizeof(apple_language));
933 _cupsAppleLanguage(attr->values[0].string.text,
934 apple_language + 15, sizeof(apple_language) - 15);
935 #endif /* __APPLE__ */
936
937 switch (strlen(attr->values[0].string.text))
938 {
939 default :
940 /*
941 * This is an unknown or badly formatted language code; use
942 * the POSIX locale...
943 */
944
945 strlcpy(lang, "LANG=C", sizeof(lang));
946 break;
947
948 case 2 :
949 /*
950 * Just the language code (ll)...
951 */
952
953 snprintf(lang, sizeof(lang), "LANG=%s.UTF-8",
954 attr->values[0].string.text);
955 break;
956
957 case 5 :
958 /*
959 * Language and country code (ll-cc)...
960 */
961
962 snprintf(lang, sizeof(lang), "LANG=%c%c_%c%c.UTF-8",
963 attr->values[0].string.text[0],
964 attr->values[0].string.text[1],
965 toupper(attr->values[0].string.text[3] & 255),
966 toupper(attr->values[0].string.text[4] & 255));
967 break;
968 }
969
970 if ((attr = ippFindAttribute(job->attrs, "document-format",
971 IPP_TAG_MIMETYPE)) != NULL &&
972 (ptr = strstr(attr->values[0].string.text, "charset=")) != NULL)
973 snprintf(charset, sizeof(charset), "CHARSET=%s", ptr + 8);
974 else
975 strlcpy(charset, "CHARSET=utf-8", sizeof(charset));
976
977 snprintf(content_type, sizeof(content_type), "CONTENT_TYPE=%s/%s",
978 job->filetypes[job->current_file]->super,
979 job->filetypes[job->current_file]->type);
980 snprintf(device_uri, sizeof(device_uri), "DEVICE_URI=%s",
981 job->printer->device_uri);
982 snprintf(ppd, sizeof(ppd), "PPD=%s/ppd/%s.ppd", ServerRoot,
983 job->printer->name);
984 snprintf(printer_info, sizeof(printer_name), "PRINTER_INFO=%s",
985 job->printer->info ? job->printer->info : "");
986 snprintf(printer_location, sizeof(printer_name), "PRINTER_LOCATION=%s",
987 job->printer->location ? job->printer->location : "");
988 snprintf(printer_name, sizeof(printer_name), "PRINTER=%s", job->printer->name);
989 if (job->printer->num_reasons > 0)
990 {
991 char *psrptr; /* Pointer into PRINTER_STATE_REASONS */
992 size_t psrlen; /* Size of PRINTER_STATE_REASONS */
993
994 for (psrlen = 22, i = 0; i < job->printer->num_reasons; i ++)
995 psrlen += strlen(job->printer->reasons[i]) + 1;
996
997 if ((printer_state_reasons = malloc(psrlen)) != NULL)
998 {
999 /*
1000 * All of these strcpy's are safe because we allocated the psr string...
1001 */
1002
1003 strlcpy(printer_state_reasons, "PRINTER_STATE_REASONS=", psrlen);
1004 for (psrptr = printer_state_reasons + 22, i = 0;
1005 i < job->printer->num_reasons;
1006 i ++)
1007 {
1008 if (i)
1009 *psrptr++ = ',';
1010 strlcpy(psrptr, job->printer->reasons[i], psrlen - (size_t)(psrptr - printer_state_reasons));
1011 psrptr += strlen(psrptr);
1012 }
1013 }
1014 }
1015 snprintf(rip_max_cache, sizeof(rip_max_cache), "RIP_MAX_CACHE=%s", RIPCache);
1016
1017 if (job->printer->num_auth_info_required == 1)
1018 snprintf(auth_info_required, sizeof(auth_info_required),
1019 "AUTH_INFO_REQUIRED=%s",
1020 job->printer->auth_info_required[0]);
1021 else if (job->printer->num_auth_info_required == 2)
1022 snprintf(auth_info_required, sizeof(auth_info_required),
1023 "AUTH_INFO_REQUIRED=%s,%s",
1024 job->printer->auth_info_required[0],
1025 job->printer->auth_info_required[1]);
1026 else if (job->printer->num_auth_info_required == 3)
1027 snprintf(auth_info_required, sizeof(auth_info_required),
1028 "AUTH_INFO_REQUIRED=%s,%s,%s",
1029 job->printer->auth_info_required[0],
1030 job->printer->auth_info_required[1],
1031 job->printer->auth_info_required[2]);
1032 else if (job->printer->num_auth_info_required == 4)
1033 snprintf(auth_info_required, sizeof(auth_info_required),
1034 "AUTH_INFO_REQUIRED=%s,%s,%s,%s",
1035 job->printer->auth_info_required[0],
1036 job->printer->auth_info_required[1],
1037 job->printer->auth_info_required[2],
1038 job->printer->auth_info_required[3]);
1039 else
1040 strlcpy(auth_info_required, "AUTH_INFO_REQUIRED=none",
1041 sizeof(auth_info_required));
1042
1043 envc = cupsdLoadEnv(envp, (int)(sizeof(envp) / sizeof(envp[0])));
1044
1045 envp[envc ++] = charset;
1046 envp[envc ++] = lang;
1047 #ifdef __APPLE__
1048 envp[envc ++] = apple_language;
1049 #endif /* __APPLE__ */
1050 envp[envc ++] = ppd;
1051 envp[envc ++] = rip_max_cache;
1052 envp[envc ++] = content_type;
1053 envp[envc ++] = device_uri;
1054 envp[envc ++] = printer_info;
1055 envp[envc ++] = printer_location;
1056 envp[envc ++] = printer_name;
1057 envp[envc ++] = printer_state_reasons ? printer_state_reasons :
1058 "PRINTER_STATE_REASONS=none";
1059 envp[envc ++] = banner_page ? "CUPS_FILETYPE=job-sheet" :
1060 "CUPS_FILETYPE=document";
1061
1062 if (final_content_type[0])
1063 envp[envc ++] = final_content_type;
1064
1065 if (Classification && !banner_page)
1066 {
1067 if ((attr = ippFindAttribute(job->attrs, "job-sheets",
1068 IPP_TAG_NAME)) == NULL)
1069 snprintf(classification, sizeof(classification), "CLASSIFICATION=%s",
1070 Classification);
1071 else if (attr->num_values > 1 &&
1072 strcmp(attr->values[1].string.text, "none") != 0)
1073 snprintf(classification, sizeof(classification), "CLASSIFICATION=%s",
1074 attr->values[1].string.text);
1075 else
1076 snprintf(classification, sizeof(classification), "CLASSIFICATION=%s",
1077 attr->values[0].string.text);
1078
1079 envp[envc ++] = classification;
1080 }
1081
1082 if (job->dtype & CUPS_PRINTER_CLASS)
1083 {
1084 snprintf(class_name, sizeof(class_name), "CLASS=%s", job->dest);
1085 envp[envc ++] = class_name;
1086 }
1087
1088 envp[envc ++] = auth_info_required;
1089
1090 for (i = 0;
1091 i < (int)(sizeof(job->auth_env) / sizeof(job->auth_env[0]));
1092 i ++)
1093 if (job->auth_env[i])
1094 envp[envc ++] = job->auth_env[i];
1095 else
1096 break;
1097
1098 if (job->auth_uid)
1099 envp[envc ++] = job->auth_uid;
1100
1101 envp[envc] = NULL;
1102
1103 for (i = 0; i < envc; i ++)
1104 if (!strncmp(envp[i], "AUTH_", 5))
1105 cupsdLogJob(job, CUPSD_LOG_DEBUG, "envp[%d]=\"AUTH_%c****\"", i,
1106 envp[i][5]);
1107 else if (strncmp(envp[i], "DEVICE_URI=", 11))
1108 cupsdLogJob(job, CUPSD_LOG_DEBUG, "envp[%d]=\"%s\"", i, envp[i]);
1109 else
1110 cupsdLogJob(job, CUPSD_LOG_DEBUG, "envp[%d]=\"DEVICE_URI=%s\"", i,
1111 job->printer->sanitized_device_uri);
1112
1113 if (job->printer->remote)
1114 job->current_file = job->num_files;
1115 else
1116 job->current_file ++;
1117
1118 /*
1119 * Now create processes for all of the filters...
1120 */
1121
1122 for (i = 0, slot = 0, filter = (mime_filter_t *)cupsArrayFirst(filters);
1123 filter;
1124 i ++, filter = (mime_filter_t *)cupsArrayNext(filters))
1125 {
1126 if (filter->filter[0] != '/')
1127 snprintf(command, sizeof(command), "%s/filter/%s", ServerBin,
1128 filter->filter);
1129 else
1130 strlcpy(command, filter->filter, sizeof(command));
1131
1132 if (i < (cupsArrayCount(filters) - 1))
1133 {
1134 if (cupsdOpenPipe(filterfds[slot]))
1135 {
1136 abort_message = "Stopping job because the scheduler could not create "
1137 "the filter pipes.";
1138
1139 goto abort_job;
1140 }
1141 }
1142 else
1143 {
1144 if (job->current_file == 1 ||
1145 (job->printer->pc && job->printer->pc->single_file))
1146 {
1147 if (strncmp(job->printer->device_uri, "file:", 5) != 0)
1148 {
1149 if (cupsdOpenPipe(job->print_pipes))
1150 {
1151 abort_message = "Stopping job because the scheduler could not "
1152 "create the backend pipes.";
1153
1154 goto abort_job;
1155 }
1156 }
1157 else
1158 {
1159 job->print_pipes[0] = -1;
1160 if (!strcmp(job->printer->device_uri, "file:/dev/null") ||
1161 !strcmp(job->printer->device_uri, "file:///dev/null"))
1162 job->print_pipes[1] = -1;
1163 else
1164 {
1165 if (!strncmp(job->printer->device_uri, "file:/dev/", 10))
1166 job->print_pipes[1] = open(job->printer->device_uri + 5,
1167 O_WRONLY | O_EXCL);
1168 else if (!strncmp(job->printer->device_uri, "file:///dev/", 12))
1169 job->print_pipes[1] = open(job->printer->device_uri + 7,
1170 O_WRONLY | O_EXCL);
1171 else if (!strncmp(job->printer->device_uri, "file:///", 8))
1172 job->print_pipes[1] = open(job->printer->device_uri + 7,
1173 O_WRONLY | O_CREAT | O_TRUNC, 0600);
1174 else
1175 job->print_pipes[1] = open(job->printer->device_uri + 5,
1176 O_WRONLY | O_CREAT | O_TRUNC, 0600);
1177
1178 if (job->print_pipes[1] < 0)
1179 {
1180 abort_message = "Stopping job because the scheduler could not "
1181 "open the output file.";
1182
1183 goto abort_job;
1184 }
1185
1186 fcntl(job->print_pipes[1], F_SETFD,
1187 fcntl(job->print_pipes[1], F_GETFD) | FD_CLOEXEC);
1188 }
1189 }
1190 }
1191
1192 filterfds[slot][0] = job->print_pipes[0];
1193 filterfds[slot][1] = job->print_pipes[1];
1194 }
1195
1196 pid = cupsdStartProcess(command, argv, envp, filterfds[!slot][0],
1197 filterfds[slot][1], job->status_pipes[1],
1198 job->back_pipes[0], job->side_pipes[0], 0,
1199 job->profile, job, job->filters + i);
1200
1201 cupsdClosePipe(filterfds[!slot]);
1202
1203 if (pid == 0)
1204 {
1205 cupsdLogJob(job, CUPSD_LOG_ERROR, "Unable to start filter \"%s\" - %s.",
1206 filter->filter, strerror(errno));
1207
1208 abort_message = "Stopping job because the scheduler could not execute a "
1209 "filter.";
1210
1211 goto abort_job;
1212 }
1213
1214 cupsdLogJob(job, CUPSD_LOG_INFO, "Started filter %s (PID %d)", command,
1215 pid);
1216
1217 if (argv[6])
1218 {
1219 free(argv[6]);
1220 argv[6] = NULL;
1221 }
1222
1223 slot = !slot;
1224 }
1225
1226 cupsArrayDelete(filters);
1227 filters = NULL;
1228
1229 /*
1230 * Finally, pipe the final output into a backend process if needed...
1231 */
1232
1233 if (strncmp(job->printer->device_uri, "file:", 5) != 0)
1234 {
1235 if (job->current_file == 1 || job->printer->remote ||
1236 (job->printer->pc && job->printer->pc->single_file))
1237 {
1238 sscanf(job->printer->device_uri, "%254[^:]", scheme);
1239 snprintf(command, sizeof(command), "%s/backend/%s", ServerBin, scheme);
1240
1241 /*
1242 * See if the backend needs to run as root...
1243 */
1244
1245 if (RunUser)
1246 backroot = 0;
1247 else if (stat(command, &backinfo))
1248 backroot = 0;
1249 else
1250 backroot = !(backinfo.st_mode & (S_IWGRP | S_IRWXO));
1251
1252 argv[0] = job->printer->sanitized_device_uri;
1253
1254 filterfds[slot][0] = -1;
1255 filterfds[slot][1] = -1;
1256
1257 pid = cupsdStartProcess(command, argv, envp, filterfds[!slot][0],
1258 filterfds[slot][1], job->status_pipes[1],
1259 job->back_pipes[1], job->side_pipes[1],
1260 backroot, job->bprofile, job, &(job->backend));
1261
1262 if (pid == 0)
1263 {
1264 abort_message = "Stopping job because the sheduler could not execute "
1265 "the backend.";
1266
1267 goto abort_job;
1268 }
1269 else
1270 {
1271 cupsdLogJob(job, CUPSD_LOG_INFO, "Started backend %s (PID %d)",
1272 command, pid);
1273 }
1274 }
1275
1276 if (job->current_file == job->num_files ||
1277 (job->printer->pc && job->printer->pc->single_file))
1278 cupsdClosePipe(job->print_pipes);
1279
1280 if (job->current_file == job->num_files)
1281 {
1282 cupsdClosePipe(job->back_pipes);
1283 cupsdClosePipe(job->side_pipes);
1284
1285 close(job->status_pipes[1]);
1286 job->status_pipes[1] = -1;
1287 }
1288 }
1289 else
1290 {
1291 filterfds[slot][0] = -1;
1292 filterfds[slot][1] = -1;
1293
1294 if (job->current_file == job->num_files ||
1295 (job->printer->pc && job->printer->pc->single_file))
1296 cupsdClosePipe(job->print_pipes);
1297
1298 if (job->current_file == job->num_files)
1299 {
1300 close(job->status_pipes[1]);
1301 job->status_pipes[1] = -1;
1302 }
1303 }
1304
1305 cupsdClosePipe(filterfds[slot]);
1306
1307 for (i = 6; i < argc; i ++)
1308 if (argv[i])
1309 free(argv[i]);
1310
1311 free(argv);
1312
1313 if (printer_state_reasons)
1314 free(printer_state_reasons);
1315
1316 cupsdAddSelect(job->status_buffer->fd, (cupsd_selfunc_t)update_job, NULL,
1317 job);
1318
1319 cupsdAddEvent(CUPSD_EVENT_JOB_STATE, job->printer, job, "Job #%d started.",
1320 job->id);
1321
1322 return;
1323
1324
1325 /*
1326 * If we get here, we need to abort the current job and close out all
1327 * files and pipes...
1328 */
1329
1330 abort_job:
1331
1332 FilterLevel -= job->cost;
1333 job->cost = 0;
1334
1335 for (slot = 0; slot < 2; slot ++)
1336 cupsdClosePipe(filterfds[slot]);
1337
1338 cupsArrayDelete(filters);
1339
1340 if (argv)
1341 {
1342 for (i = 6; i < argc; i ++)
1343 if (argv[i])
1344 free(argv[i]);
1345 }
1346
1347 if (printer_state_reasons)
1348 free(printer_state_reasons);
1349
1350 cupsdClosePipe(job->print_pipes);
1351 cupsdClosePipe(job->back_pipes);
1352 cupsdClosePipe(job->side_pipes);
1353
1354 cupsdRemoveSelect(job->status_pipes[0]);
1355 cupsdClosePipe(job->status_pipes);
1356 cupsdStatBufDelete(job->status_buffer);
1357 job->status_buffer = NULL;
1358
1359 /*
1360 * Update the printer and job state.
1361 */
1362
1363 cupsdSetJobState(job, abort_state, CUPSD_JOB_DEFAULT, "%s", abort_message);
1364 cupsdSetPrinterState(job->printer, IPP_PRINTER_IDLE, 0);
1365 update_job_attrs(job, 0);
1366
1367 if (job->history)
1368 free_job_history(job);
1369
1370 cupsArrayRemove(PrintingJobs, job);
1371
1372 /*
1373 * Clear the printer <-> job association...
1374 */
1375
1376 job->printer->job = NULL;
1377 job->printer = NULL;
1378 }
1379
1380
1381 /*
1382 * 'cupsdDeleteJob()' - Free all memory used by a job.
1383 */
1384
1385 void
1386 cupsdDeleteJob(cupsd_job_t *job, /* I - Job */
1387 cupsd_jobaction_t action)/* I - Action */
1388 {
1389 int i; /* Looping var */
1390
1391
1392 if (job->printer)
1393 finalize_job(job, 1);
1394
1395 if (action == CUPSD_JOB_PURGE)
1396 remove_job_history(job);
1397
1398 cupsdClearString(&job->username);
1399 cupsdClearString(&job->dest);
1400 for (i = 0;
1401 i < (int)(sizeof(job->auth_env) / sizeof(job->auth_env[0]));
1402 i ++)
1403 cupsdClearString(job->auth_env + i);
1404 cupsdClearString(&job->auth_uid);
1405
1406 if (action == CUPSD_JOB_PURGE)
1407 remove_job_files(job);
1408 else if (job->num_files > 0)
1409 {
1410 free(job->compressions);
1411 free(job->filetypes);
1412
1413 job->num_files = 0;
1414 }
1415
1416 if (job->history)
1417 free_job_history(job);
1418
1419 unload_job(job);
1420
1421 cupsArrayRemove(Jobs, job);
1422 cupsArrayRemove(ActiveJobs, job);
1423 cupsArrayRemove(PrintingJobs, job);
1424
1425 free(job);
1426 }
1427
1428
1429 /*
1430 * 'cupsdFreeAllJobs()' - Free all jobs from memory.
1431 */
1432
1433 void
1434 cupsdFreeAllJobs(void)
1435 {
1436 cupsd_job_t *job; /* Current job */
1437
1438
1439 if (!Jobs)
1440 return;
1441
1442 cupsdHoldSignals();
1443
1444 cupsdStopAllJobs(CUPSD_JOB_FORCE, 0);
1445 cupsdSaveAllJobs();
1446
1447 for (job = (cupsd_job_t *)cupsArrayFirst(Jobs);
1448 job;
1449 job = (cupsd_job_t *)cupsArrayNext(Jobs))
1450 cupsdDeleteJob(job, CUPSD_JOB_DEFAULT);
1451
1452 cupsdReleaseSignals();
1453 }
1454
1455
1456 /*
1457 * 'cupsdFindJob()' - Find the specified job.
1458 */
1459
1460 cupsd_job_t * /* O - Job data */
1461 cupsdFindJob(int id) /* I - Job ID */
1462 {
1463 cupsd_job_t key; /* Search key */
1464
1465
1466 key.id = id;
1467
1468 return ((cupsd_job_t *)cupsArrayFind(Jobs, &key));
1469 }
1470
1471
1472 /*
1473 * 'cupsdGetCompletedJobs()'- Generate a completed jobs list.
1474 */
1475
1476 cups_array_t * /* O - Array of jobs */
1477 cupsdGetCompletedJobs(
1478 cupsd_printer_t *p) /* I - Printer */
1479 {
1480 cups_array_t *list; /* Array of jobs */
1481 cupsd_job_t *job; /* Current job */
1482
1483
1484 list = cupsArrayNew(compare_completed_jobs, NULL);
1485
1486 for (job = (cupsd_job_t *)cupsArrayFirst(Jobs);
1487 job;
1488 job = (cupsd_job_t *)cupsArrayNext(Jobs))
1489 if ((!p || !_cups_strcasecmp(p->name, job->dest)) && job->state_value >= IPP_JOB_STOPPED && job->completed_time)
1490 cupsArrayAdd(list, job);
1491
1492 return (list);
1493 }
1494
1495
1496 /*
1497 * 'cupsdGetPrinterJobCount()' - Get the number of pending, processing,
1498 * or held jobs in a printer or class.
1499 */
1500
1501 int /* O - Job count */
1502 cupsdGetPrinterJobCount(
1503 const char *dest) /* I - Printer or class name */
1504 {
1505 int count; /* Job count */
1506 cupsd_job_t *job; /* Current job */
1507
1508
1509 for (job = (cupsd_job_t *)cupsArrayFirst(ActiveJobs), count = 0;
1510 job;
1511 job = (cupsd_job_t *)cupsArrayNext(ActiveJobs))
1512 if (job->dest && !_cups_strcasecmp(job->dest, dest))
1513 count ++;
1514
1515 return (count);
1516 }
1517
1518
1519 /*
1520 * 'cupsdGetUserJobCount()' - Get the number of pending, processing,
1521 * or held jobs for a user.
1522 */
1523
1524 int /* O - Job count */
1525 cupsdGetUserJobCount(
1526 const char *username) /* I - Username */
1527 {
1528 int count; /* Job count */
1529 cupsd_job_t *job; /* Current job */
1530
1531
1532 for (job = (cupsd_job_t *)cupsArrayFirst(ActiveJobs), count = 0;
1533 job;
1534 job = (cupsd_job_t *)cupsArrayNext(ActiveJobs))
1535 if (!_cups_strcasecmp(job->username, username))
1536 count ++;
1537
1538 return (count);
1539 }
1540
1541
1542 /*
1543 * 'cupsdLoadAllJobs()' - Load all jobs from disk.
1544 */
1545
1546 void
1547 cupsdLoadAllJobs(void)
1548 {
1549 char filename[1024]; /* Full filename of job.cache file */
1550 struct stat fileinfo; /* Information on job.cache file */
1551 cups_dir_t *dir; /* RequestRoot dir */
1552 cups_dentry_t *dent; /* Entry in RequestRoot */
1553 int load_cache = 1; /* Load the job.cache file? */
1554
1555
1556 /*
1557 * Create the job arrays as needed...
1558 */
1559
1560 if (!Jobs)
1561 Jobs = cupsArrayNew(compare_jobs, NULL);
1562
1563 if (!ActiveJobs)
1564 ActiveJobs = cupsArrayNew(compare_active_jobs, NULL);
1565
1566 if (!PrintingJobs)
1567 PrintingJobs = cupsArrayNew(compare_jobs, NULL);
1568
1569 /*
1570 * See whether the job.cache file is older than the RequestRoot directory...
1571 */
1572
1573 snprintf(filename, sizeof(filename), "%s/job.cache", CacheDir);
1574
1575 if (stat(filename, &fileinfo))
1576 {
1577 /*
1578 * No job.cache file...
1579 */
1580
1581 load_cache = 0;
1582
1583 if (errno != ENOENT)
1584 cupsdLogMessage(CUPSD_LOG_ERROR,
1585 "Unable to get file information for \"%s\" - %s",
1586 filename, strerror(errno));
1587 }
1588 else if ((dir = cupsDirOpen(RequestRoot)) == NULL)
1589 {
1590 /*
1591 * No spool directory...
1592 */
1593
1594 load_cache = 0;
1595 }
1596 else
1597 {
1598 while ((dent = cupsDirRead(dir)) != NULL)
1599 {
1600 if (strlen(dent->filename) >= 6 && dent->filename[0] == 'c' && dent->fileinfo.st_mtime > fileinfo.st_mtime)
1601 {
1602 /*
1603 * Job history file is newer than job.cache file...
1604 */
1605
1606 load_cache = 0;
1607 break;
1608 }
1609 }
1610
1611 cupsDirClose(dir);
1612 }
1613
1614 /*
1615 * Load the most recent source for job data...
1616 */
1617
1618 if (load_cache)
1619 {
1620 /*
1621 * Load the job.cache file...
1622 */
1623
1624 load_job_cache(filename);
1625 }
1626 else
1627 {
1628 /*
1629 * Load the job history files...
1630 */
1631
1632 load_request_root();
1633
1634 load_next_job_id(filename);
1635 }
1636
1637 /*
1638 * Clean out old jobs as needed...
1639 */
1640
1641 if (MaxJobs > 0 && cupsArrayCount(Jobs) >= MaxJobs)
1642 cupsdCleanJobs();
1643 }
1644
1645
1646 /*
1647 * 'cupsdLoadJob()' - Load a single job.
1648 */
1649
1650 int /* O - 1 on success, 0 on failure */
1651 cupsdLoadJob(cupsd_job_t *job) /* I - Job */
1652 {
1653 int i; /* Looping var */
1654 char jobfile[1024]; /* Job filename */
1655 cups_file_t *fp; /* Job file */
1656 int fileid; /* Current file ID */
1657 ipp_attribute_t *attr; /* Job attribute */
1658 const char *dest; /* Destination name */
1659 cupsd_printer_t *destptr; /* Pointer to destination */
1660 mime_type_t **filetypes; /* New filetypes array */
1661 int *compressions; /* New compressions array */
1662
1663
1664 if (job->attrs)
1665 {
1666 if (job->state_value > IPP_JOB_STOPPED)
1667 job->access_time = time(NULL);
1668
1669 return (1);
1670 }
1671
1672 if ((job->attrs = ippNew()) == NULL)
1673 {
1674 cupsdLogJob(job, CUPSD_LOG_ERROR, "Ran out of memory for job attributes.");
1675 return (0);
1676 }
1677
1678 /*
1679 * Load job attributes...
1680 */
1681
1682 cupsdLogJob(job, CUPSD_LOG_DEBUG, "Loading attributes...");
1683
1684 snprintf(jobfile, sizeof(jobfile), "%s/c%05d", RequestRoot, job->id);
1685 if ((fp = cupsdOpenConfFile(jobfile)) == NULL)
1686 goto error;
1687
1688 if (ippReadIO(fp, (ipp_iocb_t)cupsFileRead, 1, NULL, job->attrs) != IPP_DATA)
1689 {
1690 cupsdLogJob(job, CUPSD_LOG_ERROR,
1691 "Unable to read job control file \"%s\".", jobfile);
1692 cupsFileClose(fp);
1693 goto error;
1694 }
1695
1696 cupsFileClose(fp);
1697
1698 /*
1699 * Copy attribute data to the job object...
1700 */
1701
1702 if (!ippFindAttribute(job->attrs, "time-at-creation", IPP_TAG_INTEGER))
1703 {
1704 cupsdLogJob(job, CUPSD_LOG_ERROR,
1705 "Missing or bad time-at-creation attribute in control file.");
1706 goto error;
1707 }
1708
1709 if ((job->state = ippFindAttribute(job->attrs, "job-state",
1710 IPP_TAG_ENUM)) == NULL)
1711 {
1712 cupsdLogJob(job, CUPSD_LOG_ERROR,
1713 "Missing or bad job-state attribute in control file.");
1714 goto error;
1715 }
1716
1717 job->state_value = (ipp_jstate_t)job->state->values[0].integer;
1718 job->file_time = 0;
1719 job->history_time = 0;
1720
1721 if ((attr = ippFindAttribute(job->attrs, "time-at-creation", IPP_TAG_INTEGER)) != NULL)
1722 job->creation_time = attr->values[0].integer;
1723
1724 if (job->state_value >= IPP_JOB_CANCELED && (attr = ippFindAttribute(job->attrs, "time-at-completed", IPP_TAG_INTEGER)) != NULL)
1725 {
1726 job->completed_time = attr->values[0].integer;
1727
1728 if (JobHistory < INT_MAX)
1729 job->history_time = attr->values[0].integer + JobHistory;
1730 else
1731 job->history_time = INT_MAX;
1732
1733 if (job->history_time < time(NULL))
1734 goto error; /* Expired, remove from history */
1735
1736 if (job->history_time < JobHistoryUpdate || !JobHistoryUpdate)
1737 JobHistoryUpdate = job->history_time;
1738
1739 if (JobFiles < INT_MAX)
1740 job->file_time = attr->values[0].integer + JobFiles;
1741 else
1742 job->file_time = INT_MAX;
1743
1744 cupsdLogJob(job, CUPSD_LOG_DEBUG2, "cupsdLoadJob: job->file_time=%ld, time-at-completed=%ld, JobFiles=%d", (long)job->file_time, (long)attr->values[0].integer, JobFiles);
1745
1746 if (job->file_time < JobHistoryUpdate || !JobHistoryUpdate)
1747 JobHistoryUpdate = job->file_time;
1748
1749 cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdLoadJob: JobHistoryUpdate=%ld",
1750 (long)JobHistoryUpdate);
1751 }
1752
1753 if (!job->dest)
1754 {
1755 if ((attr = ippFindAttribute(job->attrs, "job-printer-uri",
1756 IPP_TAG_URI)) == NULL)
1757 {
1758 cupsdLogJob(job, CUPSD_LOG_ERROR,
1759 "No job-printer-uri attribute in control file.");
1760 goto error;
1761 }
1762
1763 if ((dest = cupsdValidateDest(attr->values[0].string.text, &(job->dtype),
1764 &destptr)) == NULL)
1765 {
1766 cupsdLogJob(job, CUPSD_LOG_ERROR,
1767 "Unable to queue job for destination \"%s\".",
1768 attr->values[0].string.text);
1769 goto error;
1770 }
1771
1772 cupsdSetString(&job->dest, dest);
1773 }
1774 else if ((destptr = cupsdFindDest(job->dest)) == NULL)
1775 {
1776 cupsdLogJob(job, CUPSD_LOG_ERROR,
1777 "Unable to queue job for destination \"%s\".",
1778 job->dest);
1779 goto error;
1780 }
1781
1782 if ((job->reasons = ippFindAttribute(job->attrs, "job-state-reasons",
1783 IPP_TAG_KEYWORD)) == NULL)
1784 {
1785 const char *reason; /* job-state-reason keyword */
1786
1787 cupsdLogJob(job, CUPSD_LOG_DEBUG,
1788 "Adding missing job-state-reasons attribute to control file.");
1789
1790 switch (job->state_value)
1791 {
1792 default :
1793 case IPP_JOB_PENDING :
1794 if (destptr->state == IPP_PRINTER_STOPPED)
1795 reason = "printer-stopped";
1796 else
1797 reason = "none";
1798 break;
1799
1800 case IPP_JOB_HELD :
1801 if ((attr = ippFindAttribute(job->attrs, "job-hold-until",
1802 IPP_TAG_ZERO)) != NULL &&
1803 (attr->value_tag == IPP_TAG_NAME ||
1804 attr->value_tag == IPP_TAG_NAMELANG ||
1805 attr->value_tag == IPP_TAG_KEYWORD) &&
1806 strcmp(attr->values[0].string.text, "no-hold"))
1807 reason = "job-hold-until-specified";
1808 else
1809 reason = "job-incoming";
1810 break;
1811
1812 case IPP_JOB_PROCESSING :
1813 reason = "job-printing";
1814 break;
1815
1816 case IPP_JOB_STOPPED :
1817 reason = "job-stopped";
1818 break;
1819
1820 case IPP_JOB_CANCELED :
1821 reason = "job-canceled-by-user";
1822 break;
1823
1824 case IPP_JOB_ABORTED :
1825 reason = "aborted-by-system";
1826 break;
1827
1828 case IPP_JOB_COMPLETED :
1829 reason = "job-completed-successfully";
1830 break;
1831 }
1832
1833 job->reasons = ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_KEYWORD,
1834 "job-state-reasons", NULL, reason);
1835 }
1836 else if (job->state_value == IPP_JOB_PENDING)
1837 {
1838 if (destptr->state == IPP_PRINTER_STOPPED)
1839 ippSetString(job->attrs, &job->reasons, 0, "printer-stopped");
1840 else
1841 ippSetString(job->attrs, &job->reasons, 0, "none");
1842 }
1843
1844 job->impressions = ippFindAttribute(job->attrs, "job-impressions-completed", IPP_TAG_INTEGER);
1845 job->sheets = ippFindAttribute(job->attrs, "job-media-sheets-completed", IPP_TAG_INTEGER);
1846 job->job_sheets = ippFindAttribute(job->attrs, "job-sheets", IPP_TAG_NAME);
1847
1848 if (!job->impressions)
1849 job->impressions = ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_INTEGER, "job-impressions-completed", 0);
1850 if (!job->sheets)
1851 job->sheets = ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_INTEGER, "job-media-sheets-completed", 0);
1852
1853 if (!job->priority)
1854 {
1855 if ((attr = ippFindAttribute(job->attrs, "job-priority",
1856 IPP_TAG_INTEGER)) == NULL)
1857 {
1858 cupsdLogJob(job, CUPSD_LOG_ERROR,
1859 "Missing or bad job-priority attribute in control file.");
1860 goto error;
1861 }
1862
1863 job->priority = attr->values[0].integer;
1864 }
1865
1866 if (!job->username)
1867 {
1868 if ((attr = ippFindAttribute(job->attrs, "job-originating-user-name",
1869 IPP_TAG_NAME)) == NULL)
1870 {
1871 cupsdLogJob(job, CUPSD_LOG_ERROR,
1872 "Missing or bad job-originating-user-name "
1873 "attribute in control file.");
1874 goto error;
1875 }
1876
1877 cupsdSetString(&job->username, attr->values[0].string.text);
1878 }
1879
1880 if (!job->name)
1881 {
1882 if ((attr = ippFindAttribute(job->attrs, "job-name", IPP_TAG_NAME)) != NULL)
1883 cupsdSetString(&job->name, attr->values[0].string.text);
1884 }
1885
1886 /*
1887 * Set the job hold-until time and state...
1888 */
1889
1890 if (job->state_value == IPP_JOB_HELD)
1891 {
1892 if ((attr = ippFindAttribute(job->attrs, "job-hold-until",
1893 IPP_TAG_KEYWORD)) == NULL)
1894 attr = ippFindAttribute(job->attrs, "job-hold-until", IPP_TAG_NAME);
1895
1896 if (attr)
1897 cupsdSetJobHoldUntil(job, attr->values[0].string.text, CUPSD_JOB_DEFAULT);
1898 else
1899 {
1900 job->state->values[0].integer = IPP_JOB_PENDING;
1901 job->state_value = IPP_JOB_PENDING;
1902 }
1903 }
1904 else if (job->state_value == IPP_JOB_PROCESSING)
1905 {
1906 job->state->values[0].integer = IPP_JOB_PENDING;
1907 job->state_value = IPP_JOB_PENDING;
1908 }
1909
1910 if ((attr = ippFindAttribute(job->attrs, "job-k-octets", IPP_TAG_INTEGER)) != NULL)
1911 job->koctets = attr->values[0].integer;
1912
1913 if (!job->num_files)
1914 {
1915 /*
1916 * Find all the d##### files...
1917 */
1918
1919 for (fileid = 1; fileid < 10000; fileid ++)
1920 {
1921 snprintf(jobfile, sizeof(jobfile), "%s/d%05d-%03d", RequestRoot,
1922 job->id, fileid);
1923
1924 if (access(jobfile, 0))
1925 break;
1926
1927 cupsdLogJob(job, CUPSD_LOG_DEBUG,
1928 "Auto-typing document file \"%s\"...", jobfile);
1929
1930 if (fileid > job->num_files)
1931 {
1932 if (job->num_files == 0)
1933 {
1934 compressions = (int *)calloc((size_t)fileid, sizeof(int));
1935 filetypes = (mime_type_t **)calloc((size_t)fileid, sizeof(mime_type_t *));
1936 }
1937 else
1938 {
1939 compressions = (int *)realloc(job->compressions, sizeof(int) * (size_t)fileid);
1940 filetypes = (mime_type_t **)realloc(job->filetypes, sizeof(mime_type_t *) * (size_t)fileid);
1941 }
1942
1943 if (compressions)
1944 job->compressions = compressions;
1945
1946 if (filetypes)
1947 job->filetypes = filetypes;
1948
1949 if (!compressions || !filetypes)
1950 {
1951 cupsdLogJob(job, CUPSD_LOG_ERROR,
1952 "Ran out of memory for job file types.");
1953
1954 ippDelete(job->attrs);
1955 job->attrs = NULL;
1956
1957 if (job->compressions)
1958 {
1959 free(job->compressions);
1960 job->compressions = NULL;
1961 }
1962
1963 if (job->filetypes)
1964 {
1965 free(job->filetypes);
1966 job->filetypes = NULL;
1967 }
1968
1969 job->num_files = 0;
1970 return (0);
1971 }
1972
1973 job->num_files = fileid;
1974 }
1975
1976 job->filetypes[fileid - 1] = mimeFileType(MimeDatabase, jobfile, NULL,
1977 job->compressions + fileid - 1);
1978
1979 if (!job->filetypes[fileid - 1])
1980 job->filetypes[fileid - 1] = mimeType(MimeDatabase, "application",
1981 "vnd.cups-raw");
1982 }
1983 }
1984
1985 /*
1986 * Load authentication information as needed...
1987 */
1988
1989 if (job->state_value < IPP_JOB_STOPPED)
1990 {
1991 snprintf(jobfile, sizeof(jobfile), "%s/a%05d", RequestRoot, job->id);
1992
1993 for (i = 0;
1994 i < (int)(sizeof(job->auth_env) / sizeof(job->auth_env[0]));
1995 i ++)
1996 cupsdClearString(job->auth_env + i);
1997 cupsdClearString(&job->auth_uid);
1998
1999 if ((fp = cupsFileOpen(jobfile, "r")) != NULL)
2000 {
2001 int bytes, /* Size of auth data */
2002 linenum = 1; /* Current line number */
2003 char line[65536], /* Line from file */
2004 *value, /* Value from line */
2005 data[65536]; /* Decoded data */
2006
2007
2008 if (cupsFileGets(fp, line, sizeof(line)) &&
2009 !strcmp(line, "CUPSD-AUTH-V3"))
2010 {
2011 i = 0;
2012 while (cupsFileGetConf(fp, line, sizeof(line), &value, &linenum))
2013 {
2014 /*
2015 * Decode value...
2016 */
2017
2018 if (strcmp(line, "negotiate") && strcmp(line, "uid"))
2019 {
2020 bytes = sizeof(data);
2021 httpDecode64_2(data, &bytes, value);
2022 }
2023
2024 /*
2025 * Assign environment variables...
2026 */
2027
2028 if (!strcmp(line, "uid"))
2029 {
2030 cupsdSetStringf(&job->auth_uid, "AUTH_UID=%s", value);
2031 continue;
2032 }
2033 else if (i >= (int)(sizeof(job->auth_env) / sizeof(job->auth_env[0])))
2034 break;
2035
2036 if (!strcmp(line, "username"))
2037 cupsdSetStringf(job->auth_env + i, "AUTH_USERNAME=%s", data);
2038 else if (!strcmp(line, "domain"))
2039 cupsdSetStringf(job->auth_env + i, "AUTH_DOMAIN=%s", data);
2040 else if (!strcmp(line, "password"))
2041 cupsdSetStringf(job->auth_env + i, "AUTH_PASSWORD=%s", data);
2042 else if (!strcmp(line, "negotiate"))
2043 cupsdSetStringf(job->auth_env + i, "AUTH_NEGOTIATE=%s", value);
2044 else
2045 continue;
2046
2047 i ++;
2048 }
2049 }
2050
2051 cupsFileClose(fp);
2052 }
2053 }
2054
2055 job->access_time = time(NULL);
2056 return (1);
2057
2058 /*
2059 * If we get here then something bad happened...
2060 */
2061
2062 error:
2063
2064 ippDelete(job->attrs);
2065 job->attrs = NULL;
2066
2067 remove_job_history(job);
2068 remove_job_files(job);
2069
2070 return (0);
2071 }
2072
2073
2074 /*
2075 * 'cupsdMoveJob()' - Move the specified job to a different destination.
2076 */
2077
2078 void
2079 cupsdMoveJob(cupsd_job_t *job, /* I - Job */
2080 cupsd_printer_t *p) /* I - Destination printer or class */
2081 {
2082 ipp_attribute_t *attr; /* job-printer-uri attribute */
2083 const char *olddest; /* Old destination */
2084 cupsd_printer_t *oldp; /* Old pointer */
2085
2086
2087 /*
2088 * Don't move completed jobs...
2089 */
2090
2091 if (job->state_value > IPP_JOB_STOPPED)
2092 return;
2093
2094 /*
2095 * Get the old destination...
2096 */
2097
2098 olddest = job->dest;
2099
2100 if (job->printer)
2101 oldp = job->printer;
2102 else
2103 oldp = cupsdFindDest(olddest);
2104
2105 /*
2106 * Change the destination information...
2107 */
2108
2109 if (job->state_value > IPP_JOB_HELD)
2110 cupsdSetJobState(job, IPP_JOB_PENDING, CUPSD_JOB_DEFAULT,
2111 "Stopping job prior to move.");
2112
2113 cupsdAddEvent(CUPSD_EVENT_JOB_CONFIG_CHANGED, oldp, job,
2114 "Job #%d moved from %s to %s.", job->id, olddest,
2115 p->name);
2116
2117 cupsdSetString(&job->dest, p->name);
2118 job->dtype = p->type & (CUPS_PRINTER_CLASS | CUPS_PRINTER_REMOTE);
2119
2120 if ((attr = ippFindAttribute(job->attrs, "job-printer-uri",
2121 IPP_TAG_URI)) != NULL)
2122 ippSetString(job->attrs, &attr, 0, p->uri);
2123
2124 cupsdAddEvent(CUPSD_EVENT_JOB_STOPPED, p, job,
2125 "Job #%d moved from %s to %s.", job->id, olddest,
2126 p->name);
2127
2128 job->dirty = 1;
2129 cupsdMarkDirty(CUPSD_DIRTY_JOBS);
2130 }
2131
2132
2133 /*
2134 * 'cupsdReleaseJob()' - Release the specified job.
2135 */
2136
2137 void
2138 cupsdReleaseJob(cupsd_job_t *job) /* I - Job */
2139 {
2140 cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdReleaseJob(job=%p(%d))", job,
2141 job->id);
2142
2143 if (job->state_value == IPP_JOB_HELD)
2144 {
2145 /*
2146 * Add trailing banner as needed...
2147 */
2148
2149 if (job->pending_timeout)
2150 cupsdTimeoutJob(job);
2151
2152 cupsdSetJobState(job, IPP_JOB_PENDING, CUPSD_JOB_DEFAULT,
2153 "Job released by user.");
2154 }
2155 }
2156
2157
2158 /*
2159 * 'cupsdRestartJob()' - Restart the specified job.
2160 */
2161
2162 void
2163 cupsdRestartJob(cupsd_job_t *job) /* I - Job */
2164 {
2165 cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdRestartJob(job=%p(%d))", job,
2166 job->id);
2167
2168 if (job->state_value == IPP_JOB_STOPPED || job->num_files)
2169 cupsdSetJobState(job, IPP_JOB_PENDING, CUPSD_JOB_DEFAULT,
2170 "Job restarted by user.");
2171 }
2172
2173
2174 /*
2175 * 'cupsdSaveAllJobs()' - Save a summary of all jobs to disk.
2176 */
2177
2178 void
2179 cupsdSaveAllJobs(void)
2180 {
2181 int i; /* Looping var */
2182 cups_file_t *fp; /* job.cache file */
2183 char filename[1024], /* job.cache filename */
2184 temp[1024]; /* Temporary string */
2185 cupsd_job_t *job; /* Current job */
2186 time_t curtime; /* Current time */
2187 struct tm *curdate; /* Current date */
2188
2189
2190 snprintf(filename, sizeof(filename), "%s/job.cache", CacheDir);
2191 if ((fp = cupsdCreateConfFile(filename, ConfigFilePerm)) == NULL)
2192 return;
2193
2194 cupsdLogMessage(CUPSD_LOG_INFO, "Saving job.cache...");
2195
2196 /*
2197 * Write a small header to the file...
2198 */
2199
2200 curtime = time(NULL);
2201 curdate = localtime(&curtime);
2202 strftime(temp, sizeof(temp) - 1, "%Y-%m-%d %H:%M", curdate);
2203
2204 cupsFilePuts(fp, "# Job cache file for " CUPS_SVERSION "\n");
2205 cupsFilePrintf(fp, "# Written by cupsd on %s\n", temp);
2206 cupsFilePrintf(fp, "NextJobId %d\n", NextJobId);
2207
2208 /*
2209 * Write each job known to the system...
2210 */
2211
2212 for (job = (cupsd_job_t *)cupsArrayFirst(Jobs);
2213 job;
2214 job = (cupsd_job_t *)cupsArrayNext(Jobs))
2215 {
2216 if (job->printer && job->printer->temporary)
2217 {
2218 /*
2219 * Don't save jobs on temporary printers...
2220 */
2221
2222 continue;
2223 }
2224
2225 cupsFilePrintf(fp, "<Job %d>\n", job->id);
2226 cupsFilePrintf(fp, "State %d\n", job->state_value);
2227 cupsFilePrintf(fp, "Created %ld\n", (long)job->creation_time);
2228 if (job->completed_time)
2229 cupsFilePrintf(fp, "Completed %ld\n", (long)job->completed_time);
2230 cupsFilePrintf(fp, "Priority %d\n", job->priority);
2231 if (job->hold_until)
2232 cupsFilePrintf(fp, "HoldUntil %ld\n", (long)job->hold_until);
2233 cupsFilePrintf(fp, "Username %s\n", job->username);
2234 if (job->name)
2235 cupsFilePutConf(fp, "Name", job->name);
2236 cupsFilePrintf(fp, "Destination %s\n", job->dest);
2237 cupsFilePrintf(fp, "DestType %d\n", job->dtype);
2238 cupsFilePrintf(fp, "KOctets %d\n", job->koctets);
2239 cupsFilePrintf(fp, "NumFiles %d\n", job->num_files);
2240 for (i = 0; i < job->num_files; i ++)
2241 cupsFilePrintf(fp, "File %d %s/%s %d\n", i + 1, job->filetypes[i]->super,
2242 job->filetypes[i]->type, job->compressions[i]);
2243 cupsFilePuts(fp, "</Job>\n");
2244 }
2245
2246 cupsdCloseCreatedConfFile(fp, filename);
2247 }
2248
2249
2250 /*
2251 * 'cupsdSaveJob()' - Save a job to disk.
2252 */
2253
2254 void
2255 cupsdSaveJob(cupsd_job_t *job) /* I - Job */
2256 {
2257 char filename[1024]; /* Job control filename */
2258 cups_file_t *fp; /* Job file */
2259
2260
2261 cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdSaveJob(job=%p(%d)): job->attrs=%p",
2262 job, job->id, job->attrs);
2263
2264 if (job->printer && job->printer->temporary)
2265 {
2266 /*
2267 * Don't save jobs on temporary printers...
2268 */
2269
2270 job->dirty = 0;
2271 return;
2272 }
2273
2274 snprintf(filename, sizeof(filename), "%s/c%05d", RequestRoot, job->id);
2275
2276 if ((fp = cupsdCreateConfFile(filename, ConfigFilePerm & 0600)) == NULL)
2277 return;
2278
2279 fchown(cupsFileNumber(fp), RunUser, Group);
2280
2281 job->attrs->state = IPP_IDLE;
2282
2283 if (ippWriteIO(fp, (ipp_iocb_t)cupsFileWrite, 1, NULL,
2284 job->attrs) != IPP_DATA)
2285 {
2286 cupsdLogJob(job, CUPSD_LOG_ERROR, "Unable to write job control file.");
2287 cupsFileClose(fp);
2288 return;
2289 }
2290
2291 if (!cupsdCloseCreatedConfFile(fp, filename))
2292 {
2293 /*
2294 * Remove backup file and mark this job as clean...
2295 */
2296
2297 strlcat(filename, ".O", sizeof(filename));
2298 unlink(filename);
2299
2300 job->dirty = 0;
2301 }
2302 }
2303
2304
2305 /*
2306 * 'cupsdSetJobHoldUntil()' - Set the hold time for a job.
2307 */
2308
2309 void
2310 cupsdSetJobHoldUntil(cupsd_job_t *job, /* I - Job */
2311 const char *when, /* I - When to resume */
2312 int update)/* I - Update job-hold-until attr? */
2313 {
2314 time_t curtime; /* Current time */
2315 struct tm *curdate; /* Current date */
2316 int hour; /* Hold hour */
2317 int minute; /* Hold minute */
2318 int second = 0; /* Hold second */
2319
2320
2321 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2322 "cupsdSetJobHoldUntil(job=%p(%d), when=\"%s\", update=%d)",
2323 job, job->id, when, update);
2324
2325 if (update)
2326 {
2327 /*
2328 * Update the job-hold-until attribute...
2329 */
2330
2331 ipp_attribute_t *attr; /* job-hold-until attribute */
2332
2333 if ((attr = ippFindAttribute(job->attrs, "job-hold-until",
2334 IPP_TAG_KEYWORD)) == NULL)
2335 attr = ippFindAttribute(job->attrs, "job-hold-until", IPP_TAG_NAME);
2336
2337 if (attr)
2338 ippSetString(job->attrs, &attr, 0, when);
2339 else
2340 attr = ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_KEYWORD,
2341 "job-hold-until", NULL, when);
2342
2343 if (attr)
2344 {
2345 if (isdigit(when[0] & 255))
2346 attr->value_tag = IPP_TAG_NAME;
2347 else
2348 attr->value_tag = IPP_TAG_KEYWORD;
2349
2350 job->dirty = 1;
2351 cupsdMarkDirty(CUPSD_DIRTY_JOBS);
2352 }
2353
2354 }
2355
2356 if (strcmp(when, "no-hold"))
2357 ippSetString(job->attrs, &job->reasons, 0, "job-hold-until-specified");
2358 else
2359 ippSetString(job->attrs, &job->reasons, 0, "none");
2360
2361 /*
2362 * Update the hold time...
2363 */
2364
2365 job->cancel_time = 0;
2366
2367 if (!strcmp(when, "indefinite") || !strcmp(when, "auth-info-required"))
2368 {
2369 /*
2370 * Hold indefinitely...
2371 */
2372
2373 job->hold_until = 0;
2374
2375 if (MaxHoldTime > 0)
2376 job->cancel_time = time(NULL) + MaxHoldTime;
2377 }
2378 else if (!strcmp(when, "day-time"))
2379 {
2380 /*
2381 * Hold to 6am the next morning unless local time is < 6pm.
2382 */
2383
2384 curtime = time(NULL);
2385 curdate = localtime(&curtime);
2386
2387 if (curdate->tm_hour < 18)
2388 job->hold_until = curtime;
2389 else
2390 job->hold_until = curtime +
2391 ((29 - curdate->tm_hour) * 60 + 59 -
2392 curdate->tm_min) * 60 + 60 - curdate->tm_sec;
2393 }
2394 else if (!strcmp(when, "evening") || !strcmp(when, "night"))
2395 {
2396 /*
2397 * Hold to 6pm unless local time is > 6pm or < 6am.
2398 */
2399
2400 curtime = time(NULL);
2401 curdate = localtime(&curtime);
2402
2403 if (curdate->tm_hour < 6 || curdate->tm_hour >= 18)
2404 job->hold_until = curtime;
2405 else
2406 job->hold_until = curtime +
2407 ((17 - curdate->tm_hour) * 60 + 59 -
2408 curdate->tm_min) * 60 + 60 - curdate->tm_sec;
2409 }
2410 else if (!strcmp(when, "second-shift"))
2411 {
2412 /*
2413 * Hold to 4pm unless local time is > 4pm.
2414 */
2415
2416 curtime = time(NULL);
2417 curdate = localtime(&curtime);
2418
2419 if (curdate->tm_hour >= 16)
2420 job->hold_until = curtime;
2421 else
2422 job->hold_until = curtime +
2423 ((15 - curdate->tm_hour) * 60 + 59 -
2424 curdate->tm_min) * 60 + 60 - curdate->tm_sec;
2425 }
2426 else if (!strcmp(when, "third-shift"))
2427 {
2428 /*
2429 * Hold to 12am unless local time is < 8am.
2430 */
2431
2432 curtime = time(NULL);
2433 curdate = localtime(&curtime);
2434
2435 if (curdate->tm_hour < 8)
2436 job->hold_until = curtime;
2437 else
2438 job->hold_until = curtime +
2439 ((23 - curdate->tm_hour) * 60 + 59 -
2440 curdate->tm_min) * 60 + 60 - curdate->tm_sec;
2441 }
2442 else if (!strcmp(when, "weekend"))
2443 {
2444 /*
2445 * Hold to weekend unless we are in the weekend.
2446 */
2447
2448 curtime = time(NULL);
2449 curdate = localtime(&curtime);
2450
2451 if (curdate->tm_wday == 0 || curdate->tm_wday == 6)
2452 job->hold_until = curtime;
2453 else
2454 job->hold_until = curtime +
2455 (((5 - curdate->tm_wday) * 24 +
2456 (17 - curdate->tm_hour)) * 60 + 59 -
2457 curdate->tm_min) * 60 + 60 - curdate->tm_sec;
2458 }
2459 else if (sscanf(when, "%d:%d:%d", &hour, &minute, &second) >= 2)
2460 {
2461 /*
2462 * Hold to specified GMT time (HH:MM or HH:MM:SS)...
2463 */
2464
2465 curtime = time(NULL);
2466 curdate = gmtime(&curtime);
2467
2468 job->hold_until = curtime +
2469 ((hour - curdate->tm_hour) * 60 + minute -
2470 curdate->tm_min) * 60 + second - curdate->tm_sec;
2471
2472 /*
2473 * Hold until next day as needed...
2474 */
2475
2476 if (job->hold_until < curtime)
2477 job->hold_until += 24 * 60 * 60;
2478 }
2479
2480 cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdSetJobHoldUntil: hold_until=%d",
2481 (int)job->hold_until);
2482 }
2483
2484
2485 /*
2486 * 'cupsdSetJobPriority()' - Set the priority of a job, moving it up/down in
2487 * the list as needed.
2488 */
2489
2490 void
2491 cupsdSetJobPriority(
2492 cupsd_job_t *job, /* I - Job ID */
2493 int priority) /* I - New priority (0 to 100) */
2494 {
2495 ipp_attribute_t *attr; /* Job attribute */
2496
2497
2498 /*
2499 * Don't change completed jobs...
2500 */
2501
2502 if (job->state_value >= IPP_JOB_PROCESSING)
2503 return;
2504
2505 /*
2506 * Set the new priority and re-add the job into the active list...
2507 */
2508
2509 cupsArrayRemove(ActiveJobs, job);
2510
2511 job->priority = priority;
2512
2513 if ((attr = ippFindAttribute(job->attrs, "job-priority",
2514 IPP_TAG_INTEGER)) != NULL)
2515 attr->values[0].integer = priority;
2516 else
2517 ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_INTEGER, "job-priority",
2518 priority);
2519
2520 cupsArrayAdd(ActiveJobs, job);
2521
2522 job->dirty = 1;
2523 cupsdMarkDirty(CUPSD_DIRTY_JOBS);
2524 }
2525
2526
2527 /*
2528 * 'cupsdSetJobState()' - Set the state of the specified print job.
2529 */
2530
2531 void
2532 cupsdSetJobState(
2533 cupsd_job_t *job, /* I - Job to cancel */
2534 ipp_jstate_t newstate, /* I - New job state */
2535 cupsd_jobaction_t action, /* I - Action to take */
2536 const char *message, /* I - Message to log */
2537 ...) /* I - Additional arguments as needed */
2538 {
2539 int i; /* Looping var */
2540 ipp_jstate_t oldstate; /* Old state */
2541 char filename[1024]; /* Job filename */
2542 ipp_attribute_t *attr; /* Job attribute */
2543
2544
2545 cupsdLogMessage(CUPSD_LOG_DEBUG2,
2546 "cupsdSetJobState(job=%p(%d), state=%d, newstate=%d, "
2547 "action=%d, message=\"%s\")", job, job->id, job->state_value,
2548 newstate, action, message ? message : "(null)");
2549
2550
2551 /*
2552 * Make sure we have the job attributes...
2553 */
2554
2555 if (!cupsdLoadJob(job))
2556 return;
2557
2558 /*
2559 * Don't do anything if the state is unchanged and we aren't purging the
2560 * job...
2561 */
2562
2563 oldstate = job->state_value;
2564 if (newstate == oldstate && action != CUPSD_JOB_PURGE)
2565 return;
2566
2567 /*
2568 * Stop any processes that are working on the current job...
2569 */
2570
2571 if (oldstate == IPP_JOB_PROCESSING)
2572 stop_job(job, action);
2573
2574 /*
2575 * Set the new job state...
2576 */
2577
2578 job->state_value = newstate;
2579
2580 if (job->state)
2581 job->state->values[0].integer = newstate;
2582
2583 switch (newstate)
2584 {
2585 case IPP_JOB_PENDING :
2586 /*
2587 * Update job-hold-until as needed...
2588 */
2589
2590 if ((attr = ippFindAttribute(job->attrs, "job-hold-until",
2591 IPP_TAG_KEYWORD)) == NULL)
2592 attr = ippFindAttribute(job->attrs, "job-hold-until", IPP_TAG_NAME);
2593
2594 if (attr)
2595 {
2596 ippSetValueTag(job->attrs, &attr, IPP_TAG_KEYWORD);
2597 ippSetString(job->attrs, &attr, 0, "no-hold");
2598 }
2599
2600 default :
2601 break;
2602
2603 case IPP_JOB_ABORTED :
2604 case IPP_JOB_CANCELED :
2605 case IPP_JOB_COMPLETED :
2606 set_time(job, "time-at-completed");
2607 ippSetString(job->attrs, &job->reasons, 0, "processing-to-stop-point");
2608 break;
2609 }
2610
2611 /*
2612 * Log message as needed...
2613 */
2614
2615 if (message)
2616 {
2617 char buffer[2048]; /* Message buffer */
2618 va_list ap; /* Pointer to additional arguments */
2619
2620 va_start(ap, message);
2621 vsnprintf(buffer, sizeof(buffer), message, ap);
2622 va_end(ap);
2623
2624 if (newstate > IPP_JOB_STOPPED)
2625 cupsdAddEvent(CUPSD_EVENT_JOB_COMPLETED, job->printer, job, "%s", buffer);
2626 else
2627 cupsdAddEvent(CUPSD_EVENT_JOB_STATE, job->printer, job, "%s", buffer);
2628
2629 if (newstate == IPP_JOB_STOPPED || newstate == IPP_JOB_ABORTED)
2630 cupsdLogJob(job, CUPSD_LOG_ERROR, "%s", buffer);
2631 else
2632 cupsdLogJob(job, CUPSD_LOG_INFO, "%s", buffer);
2633 }
2634
2635 /*
2636 * Handle post-state-change actions...
2637 */
2638
2639 switch (newstate)
2640 {
2641 case IPP_JOB_PROCESSING :
2642 /*
2643 * Add the job to the "printing" list...
2644 */
2645
2646 if (!cupsArrayFind(PrintingJobs, job))
2647 cupsArrayAdd(PrintingJobs, job);
2648
2649 /*
2650 * Set the processing time...
2651 */
2652
2653 set_time(job, "time-at-processing");
2654
2655 case IPP_JOB_PENDING :
2656 case IPP_JOB_HELD :
2657 case IPP_JOB_STOPPED :
2658 /*
2659 * Make sure the job is in the active list...
2660 */
2661
2662 if (!cupsArrayFind(ActiveJobs, job))
2663 cupsArrayAdd(ActiveJobs, job);
2664
2665 /*
2666 * Save the job state to disk...
2667 */
2668
2669 job->dirty = 1;
2670 cupsdMarkDirty(CUPSD_DIRTY_JOBS);
2671 break;
2672
2673 case IPP_JOB_ABORTED :
2674 case IPP_JOB_CANCELED :
2675 case IPP_JOB_COMPLETED :
2676 if (newstate == IPP_JOB_CANCELED)
2677 {
2678 /*
2679 * Remove the job from the active list if there are no processes still
2680 * running for it...
2681 */
2682
2683 for (i = 0; job->filters[i] < 0; i++);
2684
2685 if (!job->filters[i] && job->backend <= 0)
2686 cupsArrayRemove(ActiveJobs, job);
2687 }
2688 else
2689 {
2690 /*
2691 * Otherwise just remove the job from the active list immediately...
2692 */
2693
2694 cupsArrayRemove(ActiveJobs, job);
2695 }
2696
2697 /*
2698 * Expire job subscriptions since the job is now "completed"...
2699 */
2700
2701 cupsdExpireSubscriptions(NULL, job);
2702
2703 #ifdef __APPLE__
2704 /*
2705 * If we are going to sleep and the PrintingJobs count is now 0, allow the
2706 * sleep to happen immediately...
2707 */
2708
2709 if (Sleeping && cupsArrayCount(PrintingJobs) == 0)
2710 cupsdAllowSleep();
2711 #endif /* __APPLE__ */
2712
2713 /*
2714 * Remove any authentication data...
2715 */
2716
2717 snprintf(filename, sizeof(filename), "%s/a%05d", RequestRoot, job->id);
2718 if (cupsdRemoveFile(filename) && errno != ENOENT)
2719 cupsdLogMessage(CUPSD_LOG_ERROR,
2720 "Unable to remove authentication cache: %s",
2721 strerror(errno));
2722
2723 for (i = 0;
2724 i < (int)(sizeof(job->auth_env) / sizeof(job->auth_env[0]));
2725 i ++)
2726 cupsdClearString(job->auth_env + i);
2727
2728 cupsdClearString(&job->auth_uid);
2729
2730 /*
2731 * Remove the print file for good if we aren't preserving jobs or
2732 * files...
2733 */
2734
2735 if (!JobHistory || !JobFiles || action == CUPSD_JOB_PURGE)
2736 remove_job_files(job);
2737
2738 if (JobHistory && action != CUPSD_JOB_PURGE)
2739 {
2740 /*
2741 * Save job state info...
2742 */
2743
2744 job->dirty = 1;
2745 cupsdMarkDirty(CUPSD_DIRTY_JOBS);
2746 }
2747 else if (!job->printer)
2748 {
2749 /*
2750 * Delete the job immediately if not actively printing...
2751 */
2752
2753 cupsdDeleteJob(job, CUPSD_JOB_PURGE);
2754 job = NULL;
2755 }
2756 break;
2757 }
2758
2759 /*
2760 * Finalize the job immediately if we forced things...
2761 */
2762
2763 if (action >= CUPSD_JOB_FORCE && job && job->printer)
2764 finalize_job(job, 0);
2765
2766 /*
2767 * Update the server "busy" state...
2768 */
2769
2770 cupsdSetBusyState(0);
2771 }
2772
2773
2774 /*
2775 * 'cupsdStopAllJobs()' - Stop all print jobs.
2776 */
2777
2778 void
2779 cupsdStopAllJobs(
2780 cupsd_jobaction_t action, /* I - Action */
2781 int kill_delay) /* I - Number of seconds before we kill */
2782 {
2783 cupsd_job_t *job; /* Current job */
2784
2785
2786 DEBUG_puts("cupsdStopAllJobs()");
2787
2788 for (job = (cupsd_job_t *)cupsArrayFirst(PrintingJobs);
2789 job;
2790 job = (cupsd_job_t *)cupsArrayNext(PrintingJobs))
2791 {
2792 if (job->completed)
2793 {
2794 cupsdSetJobState(job, IPP_JOB_COMPLETED, CUPSD_JOB_FORCE, NULL);
2795 }
2796 else
2797 {
2798 if (kill_delay)
2799 job->kill_time = time(NULL) + kill_delay;
2800
2801 cupsdSetJobState(job, IPP_JOB_PENDING, action, NULL);
2802 }
2803 }
2804 }
2805
2806
2807 /*
2808 * 'cupsdUnloadCompletedJobs()' - Flush completed job history from memory.
2809 */
2810
2811 void
2812 cupsdUnloadCompletedJobs(void)
2813 {
2814 cupsd_job_t *job; /* Current job */
2815 time_t expire; /* Expiration time */
2816
2817
2818 expire = time(NULL) - 60;
2819
2820 for (job = (cupsd_job_t *)cupsArrayFirst(Jobs);
2821 job;
2822 job = (cupsd_job_t *)cupsArrayNext(Jobs))
2823 if (job->attrs && job->state_value >= IPP_JOB_STOPPED && !job->printer &&
2824 job->access_time < expire)
2825 {
2826 if (job->dirty)
2827 cupsdSaveJob(job);
2828
2829 if (!job->dirty)
2830 unload_job(job);
2831 }
2832 }
2833
2834
2835 /*
2836 * 'cupsdUpdateJobs()' - Update the history/file files for all jobs.
2837 */
2838
2839 void
2840 cupsdUpdateJobs(void)
2841 {
2842 cupsd_job_t *job; /* Current job */
2843 time_t curtime; /* Current time */
2844 ipp_attribute_t *attr; /* time-at-completed attribute */
2845
2846
2847 curtime = time(NULL);
2848 JobHistoryUpdate = 0;
2849
2850 for (job = (cupsd_job_t *)cupsArrayFirst(Jobs);
2851 job;
2852 job = (cupsd_job_t *)cupsArrayNext(Jobs))
2853 {
2854 if (job->state_value >= IPP_JOB_CANCELED &&
2855 (attr = ippFindAttribute(job->attrs, "time-at-completed",
2856 IPP_TAG_INTEGER)) != NULL)
2857 {
2858 /*
2859 * Update history/file expiration times...
2860 */
2861
2862 if (JobHistory < INT_MAX)
2863 job->history_time = attr->values[0].integer + JobHistory;
2864 else
2865 job->history_time = INT_MAX;
2866
2867 if (job->history_time < curtime)
2868 {
2869 cupsdDeleteJob(job, CUPSD_JOB_PURGE);
2870 continue;
2871 }
2872
2873 if (job->history_time < JobHistoryUpdate || !JobHistoryUpdate)
2874 JobHistoryUpdate = job->history_time;
2875
2876 if (JobFiles < INT_MAX)
2877 job->file_time = attr->values[0].integer + JobFiles;
2878 else
2879 job->file_time = INT_MAX;
2880
2881 cupsdLogJob(job, CUPSD_LOG_DEBUG2, "cupsdUpdateJobs: job->file_time=%ld, time-at-completed=%ld, JobFiles=%d", (long)job->file_time, (long)attr->values[0].integer, JobFiles);
2882
2883 if (job->file_time < JobHistoryUpdate || !JobHistoryUpdate)
2884 JobHistoryUpdate = job->file_time;
2885 }
2886 }
2887
2888 cupsdLogMessage(CUPSD_LOG_DEBUG2, "cupsdUpdateJobs: JobHistoryUpdate=%ld",
2889 (long)JobHistoryUpdate);
2890 }
2891
2892
2893 /*
2894 * 'compare_active_jobs()' - Compare the job IDs and priorities of two jobs.
2895 */
2896
2897 static int /* O - Difference */
2898 compare_active_jobs(void *first, /* I - First job */
2899 void *second, /* I - Second job */
2900 void *data) /* I - App data (not used) */
2901 {
2902 int diff; /* Difference */
2903
2904
2905 (void)data;
2906
2907 if ((diff = ((cupsd_job_t *)second)->priority -
2908 ((cupsd_job_t *)first)->priority) != 0)
2909 return (diff);
2910 else
2911 return (((cupsd_job_t *)first)->id - ((cupsd_job_t *)second)->id);
2912 }
2913
2914
2915 /*
2916 * 'compare_completed_jobs()' - Compare the job IDs and completion times of two jobs.
2917 */
2918
2919 static int /* O - Difference */
2920 compare_completed_jobs(void *first, /* I - First job */
2921 void *second, /* I - Second job */
2922 void *data) /* I - App data (not used) */
2923 {
2924 int diff; /* Difference */
2925
2926
2927 (void)data;
2928
2929 if ((diff = ((cupsd_job_t *)second)->completed_time -
2930 ((cupsd_job_t *)first)->completed_time) != 0)
2931 return (diff);
2932 else
2933 return (((cupsd_job_t *)first)->id - ((cupsd_job_t *)second)->id);
2934 }
2935
2936
2937 /*
2938 * 'compare_jobs()' - Compare the job IDs of two jobs.
2939 */
2940
2941 static int /* O - Difference */
2942 compare_jobs(void *first, /* I - First job */
2943 void *second, /* I - Second job */
2944 void *data) /* I - App data (not used) */
2945 {
2946 (void)data;
2947
2948 return (((cupsd_job_t *)first)->id - ((cupsd_job_t *)second)->id);
2949 }
2950
2951
2952 /*
2953 * 'dump_job_history()' - Dump any debug messages for a job.
2954 */
2955
2956 static void
2957 dump_job_history(cupsd_job_t *job) /* I - Job */
2958 {
2959 int i, /* Looping var */
2960 oldsize; /* Current MaxLogSize */
2961 struct tm *date; /* Date/time value */
2962 cupsd_joblog_t *message; /* Current message */
2963 char temp[2048], /* Log message */
2964 *ptr, /* Pointer into log message */
2965 start[256], /* Start time */
2966 end[256]; /* End time */
2967 cupsd_printer_t *printer; /* Printer for job */
2968
2969
2970 /*
2971 * See if we have anything to dump...
2972 */
2973
2974 if (!job->history)
2975 return;
2976
2977 /*
2978 * Disable log rotation temporarily...
2979 */
2980
2981 oldsize = MaxLogSize;
2982 MaxLogSize = 0;
2983
2984 /*
2985 * Copy the debug messages to the log...
2986 */
2987
2988 message = (cupsd_joblog_t *)cupsArrayFirst(job->history);
2989 date = localtime(&(message->time));
2990 strftime(start, sizeof(start), "%X", date);
2991
2992 message = (cupsd_joblog_t *)cupsArrayLast(job->history);
2993 date = localtime(&(message->time));
2994 strftime(end, sizeof(end), "%X", date);
2995
2996 snprintf(temp, sizeof(temp),
2997 "[Job %d] The following messages were recorded from %s to %s",
2998 job->id, start, end);
2999 cupsdWriteErrorLog(CUPSD_LOG_DEBUG, temp);
3000
3001 for (message = (cupsd_joblog_t *)cupsArrayFirst(job->history);
3002 message;
3003 message = (cupsd_joblog_t *)cupsArrayNext(job->history))
3004 cupsdWriteErrorLog(CUPSD_LOG_DEBUG, message->message);
3005
3006 snprintf(temp, sizeof(temp), "[Job %d] End of messages", job->id);
3007 cupsdWriteErrorLog(CUPSD_LOG_DEBUG, temp);
3008
3009 /*
3010 * Log the printer state values...
3011 */
3012
3013 if ((printer = job->printer) == NULL)
3014 printer = cupsdFindDest(job->dest);
3015
3016 if (printer)
3017 {
3018 snprintf(temp, sizeof(temp), "[Job %d] printer-state=%d(%s)", job->id,
3019 printer->state,
3020 printer->state == IPP_PRINTER_IDLE ? "idle" :
3021 printer->state == IPP_PRINTER_PROCESSING ? "processing" :
3022 "stopped");
3023 cupsdWriteErrorLog(CUPSD_LOG_DEBUG, temp);
3024
3025 snprintf(temp, sizeof(temp), "[Job %d] printer-state-message=\"%s\"",
3026 job->id, printer->state_message);
3027 cupsdWriteErrorLog(CUPSD_LOG_DEBUG, temp);
3028
3029 snprintf(temp, sizeof(temp), "[Job %d] printer-state-reasons=", job->id);
3030 ptr = temp + strlen(temp);
3031 if (printer->num_reasons == 0)
3032 strlcpy(ptr, "none", sizeof(temp) - (size_t)(ptr - temp));
3033 else
3034 {
3035 for (i = 0;
3036 i < printer->num_reasons && ptr < (temp + sizeof(temp) - 2);
3037 i ++)
3038 {
3039 if (i)
3040 *ptr++ = ',';
3041
3042 strlcpy(ptr, printer->reasons[i], sizeof(temp) - (size_t)(ptr - temp));
3043 ptr += strlen(ptr);
3044 }
3045 }
3046 cupsdWriteErrorLog(CUPSD_LOG_DEBUG, temp);
3047 }
3048
3049 /*
3050 * Restore log file rotation...
3051 */
3052
3053 MaxLogSize = oldsize;
3054
3055 /*
3056 * Free all messages...
3057 */
3058
3059 free_job_history(job);
3060 }
3061
3062
3063 /*
3064 * 'free_job_history()' - Free any log history.
3065 */
3066
3067 static void
3068 free_job_history(cupsd_job_t *job) /* I - Job */
3069 {
3070 char *message; /* Current message */
3071
3072
3073 if (!job->history)
3074 return;
3075
3076 for (message = (char *)cupsArrayFirst(job->history);
3077 message;
3078 message = (char *)cupsArrayNext(job->history))
3079 free(message);
3080
3081 cupsArrayDelete(job->history);
3082 job->history = NULL;
3083 }
3084
3085
3086 /*
3087 * 'finalize_job()' - Cleanup after job filter processes and support data.
3088 */
3089
3090 static void
3091 finalize_job(cupsd_job_t *job, /* I - Job */
3092 int set_job_state) /* I - 1 = set the job state */
3093 {
3094 ipp_pstate_t printer_state; /* New printer state value */
3095 ipp_jstate_t job_state; /* New job state value */
3096 const char *message; /* Message for job state */
3097 char buffer[1024]; /* Buffer for formatted messages */
3098
3099
3100 cupsdLogMessage(CUPSD_LOG_DEBUG2, "finalize_job(job=%p(%d))", job, job->id);
3101
3102 /*
3103 * Clear the "connecting-to-device" and "cups-waiting-for-job-completed"
3104 * reasons, which are only valid when a printer is processing, along with any
3105 * remote printing job state...
3106 */
3107
3108 cupsdSetPrinterReasons(job->printer, "-connecting-to-device,"
3109 "cups-waiting-for-job-completed,"
3110 "cups-remote-pending,"
3111 "cups-remote-pending-held,"
3112 "cups-remote-processing,"
3113 "cups-remote-stopped,"
3114 "cups-remote-canceled,"
3115 "cups-remote-aborted,"
3116 "cups-remote-completed");
3117
3118 /*
3119 * Similarly, clear the "offline-report" reason for non-USB devices since we
3120 * rarely have current information for network devices...
3121 */
3122
3123 if (strncmp(job->printer->device_uri, "usb:", 4) &&
3124 strncmp(job->printer->device_uri, "ippusb:", 7))
3125 cupsdSetPrinterReasons(job->printer, "-offline-report");
3126
3127 /*
3128 * Free the security profile...
3129 */
3130
3131 cupsdDestroyProfile(job->profile);
3132 job->profile = NULL;
3133 cupsdDestroyProfile(job->bprofile);
3134 job->bprofile = NULL;
3135
3136 /*
3137 * Clear the unresponsive job watchdog timers...
3138 */
3139
3140 job->cancel_time = 0;
3141 job->kill_time = 0;
3142
3143 /*
3144 * Close pipes and status buffer...
3145 */
3146
3147 cupsdClosePipe(job->print_pipes);
3148 cupsdClosePipe(job->back_pipes);
3149 cupsdClosePipe(job->side_pipes);
3150
3151 cupsdRemoveSelect(job->status_pipes[0]);
3152 cupsdClosePipe(job->status_pipes);
3153 cupsdStatBufDelete(job->status_buffer);
3154 job->status_buffer = NULL;
3155
3156 /*
3157 * Log the final impression (page) count...
3158 */
3159
3160 snprintf(buffer, sizeof(buffer), "total %d", ippGetInteger(job->impressions, 0));
3161 cupsdLogPage(job, buffer);
3162
3163 /*
3164 * Process the exit status...
3165 */
3166
3167 if (job->printer->state == IPP_PRINTER_PROCESSING)
3168 printer_state = IPP_PRINTER_IDLE;
3169 else
3170 printer_state = job->printer->state;
3171
3172 switch (job_state = job->state_value)
3173 {
3174 case IPP_JOB_PENDING :
3175 message = "Job paused.";
3176 break;
3177
3178 case IPP_JOB_HELD :
3179 message = "Job held.";
3180 break;
3181
3182 default :
3183 case IPP_JOB_PROCESSING :
3184 case IPP_JOB_COMPLETED :
3185 job_state = IPP_JOB_COMPLETED;
3186 message = "Job completed.";
3187
3188 if (!job->status)
3189 ippSetString(job->attrs, &job->reasons, 0,
3190 "job-completed-successfully");
3191 break;
3192
3193 case IPP_JOB_STOPPED :
3194 message = "Job stopped.";
3195
3196 ippSetString(job->attrs, &job->reasons, 0, "job-stopped");
3197 break;
3198
3199 case IPP_JOB_CANCELED :
3200 message = "Job canceled.";
3201
3202 ippSetString(job->attrs, &job->reasons, 0, "job-canceled-by-user");
3203 break;
3204
3205 case IPP_JOB_ABORTED :
3206 message = "Job aborted.";
3207 break;
3208 }
3209
3210 if (job->status < 0)
3211 {
3212 /*
3213 * Backend had errors...
3214 */
3215
3216 int exit_code; /* Exit code from backend */
3217
3218 /*
3219 * Convert the status to an exit code. Due to the way the W* macros are
3220 * implemented on macOS (bug?), we have to store the exit status in a
3221 * variable first and then convert...
3222 */
3223
3224 exit_code = -job->status;
3225 if (WIFEXITED(exit_code))
3226 exit_code = WEXITSTATUS(exit_code);
3227 else
3228 {
3229 ippSetString(job->attrs, &job->reasons, 0, "cups-backend-crashed");
3230 exit_code = job->status;
3231 }
3232
3233 cupsdLogJob(job, CUPSD_LOG_INFO, "Backend returned status %d (%s)",
3234 exit_code,
3235 exit_code == CUPS_BACKEND_FAILED ? "failed" :
3236 exit_code == CUPS_BACKEND_AUTH_REQUIRED ?
3237 "authentication required" :
3238 exit_code == CUPS_BACKEND_HOLD ? "hold job" :
3239 exit_code == CUPS_BACKEND_STOP ? "stop printer" :
3240 exit_code == CUPS_BACKEND_CANCEL ? "cancel job" :
3241 exit_code == CUPS_BACKEND_RETRY ? "retry job later" :
3242 exit_code == CUPS_BACKEND_RETRY_CURRENT ? "retry job immediately" :
3243 exit_code < 0 ? "crashed" : "unknown");
3244
3245 /*
3246 * Do what needs to be done...
3247 */
3248
3249 switch (exit_code)
3250 {
3251 default :
3252 case CUPS_BACKEND_FAILED :
3253 /*
3254 * Backend failure, use the error-policy to determine how to
3255 * act...
3256 */
3257
3258 if (job->dtype & CUPS_PRINTER_CLASS)
3259 {
3260 /*
3261 * Queued on a class - mark the job as pending and we'll retry on
3262 * another printer...
3263 */
3264
3265 if (job_state == IPP_JOB_COMPLETED)
3266 {
3267 job_state = IPP_JOB_PENDING;
3268 message = "Retrying job on another printer.";
3269
3270 ippSetString(job->attrs, &job->reasons, 0,
3271 "resources-are-not-ready");
3272 }
3273 }
3274 else if (!strcmp(job->printer->error_policy, "retry-current-job"))
3275 {
3276 /*
3277 * The error policy is "retry-current-job" - mark the job as pending
3278 * and we'll retry on the same printer...
3279 */
3280
3281 if (job_state == IPP_JOB_COMPLETED)
3282 {
3283 job_state = IPP_JOB_PENDING;
3284 message = "Retrying job on same printer.";
3285
3286 ippSetString(job->attrs, &job->reasons, 0, "none");
3287 }
3288 }
3289 else if ((job->printer->type & CUPS_PRINTER_FAX) ||
3290 !strcmp(job->printer->error_policy, "retry-job"))
3291 {
3292 if (job_state == IPP_JOB_COMPLETED)
3293 {
3294 /*
3295 * The job was queued on a fax or the error policy is "retry-job" -
3296 * hold the job if the number of retries is less than the
3297 * JobRetryLimit, otherwise abort the job.
3298 */
3299
3300 job->tries ++;
3301
3302 if (job->tries > JobRetryLimit && JobRetryLimit > 0)
3303 {
3304 /*
3305 * Too many tries...
3306 */
3307
3308 snprintf(buffer, sizeof(buffer),
3309 "Job aborted after %d unsuccessful attempts.",
3310 JobRetryLimit);
3311 job_state = IPP_JOB_ABORTED;
3312 message = buffer;
3313
3314 ippSetString(job->attrs, &job->reasons, 0, "aborted-by-system");
3315 }
3316 else
3317 {
3318 /*
3319 * Try again in N seconds...
3320 */
3321
3322 snprintf(buffer, sizeof(buffer),
3323 "Job held for %d seconds since it could not be sent.",
3324 JobRetryInterval);
3325
3326 job->hold_until = time(NULL) + JobRetryInterval;
3327 job_state = IPP_JOB_HELD;
3328 message = buffer;
3329
3330 ippSetString(job->attrs, &job->reasons, 0,
3331 "resources-are-not-ready");
3332 }
3333 }
3334 }
3335 else if (!strcmp(job->printer->error_policy, "abort-job") &&
3336 job_state == IPP_JOB_COMPLETED)
3337 {
3338 job_state = IPP_JOB_ABORTED;
3339
3340 if (ErrorLog)
3341 {
3342 snprintf(buffer, sizeof(buffer), "Job aborted due to backend errors; please consult the %s file for details.", ErrorLog);
3343 message = buffer;
3344 }
3345 else
3346 message = "Job aborted due to backend errors.";
3347
3348 ippSetString(job->attrs, &job->reasons, 0, "aborted-by-system");
3349 }
3350 else if (job->state_value == IPP_JOB_PROCESSING)
3351 {
3352 job_state = IPP_JOB_PENDING;
3353 printer_state = IPP_PRINTER_STOPPED;
3354
3355 if (ErrorLog)
3356 {
3357 snprintf(buffer, sizeof(buffer), "Printer stopped due to backend errors; please consult the %s file for details.", ErrorLog);
3358 message = buffer;
3359 }
3360 else
3361 message = "Printer stopped due to backend errors.";
3362
3363 ippSetString(job->attrs, &job->reasons, 0, "none");
3364 }
3365 break;
3366
3367 case CUPS_BACKEND_CANCEL :
3368 /*
3369 * Cancel the job...
3370 */
3371
3372 if (job_state == IPP_JOB_COMPLETED)
3373 {
3374 job_state = IPP_JOB_CANCELED;
3375 message = "Job canceled at printer.";
3376
3377 ippSetString(job->attrs, &job->reasons, 0, "canceled-at-device");
3378 }
3379 break;
3380
3381 case CUPS_BACKEND_HOLD :
3382 if (job_state == IPP_JOB_COMPLETED)
3383 {
3384 /*
3385 * Hold the job...
3386 */
3387
3388 const char *reason = ippGetString(job->reasons, 0, NULL);
3389
3390 cupsdLogJob(job, CUPSD_LOG_DEBUG, "job-state-reasons=\"%s\"",
3391 reason);
3392
3393 if (!reason || strncmp(reason, "account-", 8))
3394 {
3395 cupsdSetJobHoldUntil(job, "indefinite", 1);
3396
3397 ippSetString(job->attrs, &job->reasons, 0,
3398 "job-hold-until-specified");
3399
3400 if (ErrorLog)
3401 {
3402 snprintf(buffer, sizeof(buffer), "Job held indefinitely due to backend errors; please consult the %s file for details.", ErrorLog);
3403 message = buffer;
3404 }
3405 else
3406 message = "Job held indefinitely due to backend errors.";
3407 }
3408 else if (!strcmp(reason, "account-info-needed"))
3409 {
3410 cupsdSetJobHoldUntil(job, "indefinite", 0);
3411
3412 message = "Job held indefinitely - account information is required.";
3413 }
3414 else if (!strcmp(reason, "account-closed"))
3415 {
3416 cupsdSetJobHoldUntil(job, "indefinite", 0);
3417
3418 message = "Job held indefinitely - account has been closed.";
3419 }
3420 else if (!strcmp(reason, "account-limit-reached"))
3421 {
3422 cupsdSetJobHoldUntil(job, "indefinite", 0);
3423
3424 message = "Job held indefinitely - account limit has been reached.";
3425 }
3426 else
3427 {
3428 cupsdSetJobHoldUntil(job, "indefinite", 0);
3429
3430 message = "Job held indefinitely - account authorization failed.";
3431 }
3432
3433 job_state = IPP_JOB_HELD;
3434 }
3435 break;
3436
3437 case CUPS_BACKEND_STOP :
3438 /*
3439 * Stop the printer...
3440 */
3441
3442 printer_state = IPP_PRINTER_STOPPED;
3443
3444 if (ErrorLog)
3445 {
3446 snprintf(buffer, sizeof(buffer), "Printer stopped due to backend errors; please consult the %s file for details.", ErrorLog);
3447 message = buffer;
3448 }
3449 else
3450 message = "Printer stopped due to backend errors.";
3451
3452 if (job_state == IPP_JOB_COMPLETED)
3453 {
3454 job_state = IPP_JOB_PENDING;
3455
3456 ippSetString(job->attrs, &job->reasons, 0,
3457 "resources-are-not-ready");
3458 }
3459 break;
3460
3461 case CUPS_BACKEND_AUTH_REQUIRED :
3462 /*
3463 * Hold the job for authentication...
3464 */
3465
3466 if (job_state == IPP_JOB_COMPLETED)
3467 {
3468 cupsdSetJobHoldUntil(job, "auth-info-required", 1);
3469
3470 job_state = IPP_JOB_HELD;
3471 message = "Job held for authentication.";
3472
3473 if (strncmp(job->reasons->values[0].string.text, "account-", 8))
3474 ippSetString(job->attrs, &job->reasons, 0,
3475 "cups-held-for-authentication");
3476 }
3477 break;
3478
3479 case CUPS_BACKEND_RETRY :
3480 if (job_state == IPP_JOB_COMPLETED)
3481 {
3482 /*
3483 * Hold the job if the number of retries is less than the
3484 * JobRetryLimit, otherwise abort the job.
3485 */
3486
3487 job->tries ++;
3488
3489 if (job->tries > JobRetryLimit && JobRetryLimit > 0)
3490 {
3491 /*
3492 * Too many tries...
3493 */
3494
3495 snprintf(buffer, sizeof(buffer),
3496 "Job aborted after %d unsuccessful attempts.",
3497 JobRetryLimit);
3498 job_state = IPP_JOB_ABORTED;
3499 message = buffer;
3500
3501 ippSetString(job->attrs, &job->reasons, 0, "aborted-by-system");
3502 }
3503 else
3504 {
3505 /*
3506 * Try again in N seconds...
3507 */
3508
3509 snprintf(buffer, sizeof(buffer),
3510 "Job held for %d seconds since it could not be sent.",
3511 JobRetryInterval);
3512
3513 job->hold_until = time(NULL) + JobRetryInterval;
3514 job_state = IPP_JOB_HELD;
3515 message = buffer;
3516
3517 ippSetString(job->attrs, &job->reasons, 0,
3518 "resources-are-not-ready");
3519 }
3520 }
3521 break;
3522
3523 case CUPS_BACKEND_RETRY_CURRENT :
3524 /*
3525 * Mark the job as pending and retry on the same printer...
3526 */
3527
3528 if (job_state == IPP_JOB_COMPLETED)
3529 {
3530 job_state = IPP_JOB_PENDING;
3531 message = "Retrying job on same printer.";
3532
3533 ippSetString(job->attrs, &job->reasons, 0, "none");
3534 }
3535 break;
3536 }
3537 }
3538 else if (job->status > 0)
3539 {
3540 /*
3541 * Filter had errors; stop job...
3542 */
3543
3544 if (job_state == IPP_JOB_COMPLETED)
3545 {
3546 job_state = IPP_JOB_STOPPED;
3547
3548 if (ErrorLog)
3549 {
3550 snprintf(buffer, sizeof(buffer), "Job stopped due to filter errors; please consult the %s file for details.", ErrorLog);
3551 message = buffer;
3552 }
3553 else
3554 message = "Job stopped due to filter errors.";
3555
3556 if (WIFSIGNALED(job->status))
3557 ippSetString(job->attrs, &job->reasons, 0, "cups-filter-crashed");
3558 else
3559 ippSetString(job->attrs, &job->reasons, 0, "job-completed-with-errors");
3560 }
3561 }
3562
3563 /*
3564 * Update the printer and job state.
3565 */
3566
3567 if (set_job_state && job_state != job->state_value)
3568 cupsdSetJobState(job, job_state, CUPSD_JOB_DEFAULT, "%s", message);
3569
3570 cupsdSetPrinterState(job->printer, printer_state,
3571 printer_state == IPP_PRINTER_STOPPED);
3572 update_job_attrs(job, 0);
3573
3574 if (job->history)
3575 {
3576 if (job->status &&
3577 (job->state_value == IPP_JOB_ABORTED ||
3578 job->state_value == IPP_JOB_STOPPED))
3579 dump_job_history(job);
3580 else
3581 free_job_history(job);
3582 }
3583
3584 cupsArrayRemove(PrintingJobs, job);
3585
3586 /*
3587 * Clear informational messages...
3588 */
3589
3590 if (job->status_level > CUPSD_LOG_ERROR)
3591 job->printer->state_message[0] = '\0';
3592
3593 /*
3594 * Apply any PPD updates...
3595 */
3596
3597 if (job->num_keywords)
3598 {
3599 if (cupsdUpdatePrinterPPD(job->printer, job->num_keywords, job->keywords))
3600 cupsdSetPrinterAttrs(job->printer);
3601
3602 cupsFreeOptions(job->num_keywords, job->keywords);
3603
3604 job->num_keywords = 0;
3605 job->keywords = NULL;
3606 }
3607
3608 /*
3609 * Clear the printer <-> job association...
3610 */
3611
3612 job->printer->job = NULL;
3613 job->printer = NULL;
3614 }
3615
3616
3617 /*
3618 * 'get_options()' - Get a string containing the job options.
3619 */
3620
3621 static char * /* O - Options string */
3622 get_options(cupsd_job_t *job, /* I - Job */
3623 int banner_page, /* I - Printing a banner page? */
3624 char *copies, /* I - Copies buffer */
3625 size_t copies_size, /* I - Size of copies buffer */
3626 char *title, /* I - Title buffer */
3627 size_t title_size) /* I - Size of title buffer */
3628 {
3629 int i; /* Looping var */
3630 size_t newlength; /* New option buffer length */
3631 char *optptr, /* Pointer to options */
3632 *valptr; /* Pointer in value string */
3633 ipp_attribute_t *attr; /* Current attribute */
3634 _ppd_cache_t *pc; /* PPD cache and mapping data */
3635 int num_pwgppds; /* Number of PWG->PPD options */
3636 cups_option_t *pwgppds, /* PWG->PPD options */
3637 *pwgppd, /* Current PWG->PPD option */
3638 *preset; /* Current preset option */
3639 int print_color_mode,
3640 /* Output mode (if any) */
3641 print_quality; /* Print quality (if any) */
3642 const char *ppd; /* PPD option choice */
3643 int exact; /* Did we get an exact match? */
3644 static char *options = NULL;/* Full list of options */
3645 static size_t optlength = 0; /* Length of option buffer */
3646
3647
3648 /*
3649 * Building the options string is harder than it needs to be, but for the
3650 * moment we need to pass strings for command-line args and not IPP attribute
3651 * pointers... :)
3652 *
3653 * First build an options array for any PWG->PPD mapped option/choice pairs.
3654 */
3655
3656 pc = job->printer->pc;
3657 num_pwgppds = 0;
3658 pwgppds = NULL;
3659
3660 if (pc &&
3661 !ippFindAttribute(job->attrs, "com.apple.print.DocumentTicket.PMSpoolFormat", IPP_TAG_ZERO) &&
3662 !ippFindAttribute(job->attrs, "APPrinterPreset", IPP_TAG_ZERO) &&
3663 (ippFindAttribute(job->attrs, "print-color-mode", IPP_TAG_ZERO) || ippFindAttribute(job->attrs, "print-quality", IPP_TAG_ZERO) || ippFindAttribute(job->attrs, "cupsPrintQuality", IPP_TAG_ZERO)))
3664 {
3665 /*
3666 * Map print-color-mode and print-quality to a preset...
3667 */
3668
3669 if ((attr = ippFindAttribute(job->attrs, "print-color-mode",
3670 IPP_TAG_KEYWORD)) != NULL &&
3671 !strcmp(attr->values[0].string.text, "monochrome"))
3672 print_color_mode = _PWG_PRINT_COLOR_MODE_MONOCHROME;
3673 else
3674 print_color_mode = _PWG_PRINT_COLOR_MODE_COLOR;
3675
3676 if ((attr = ippFindAttribute(job->attrs, "print-quality", IPP_TAG_ENUM)) != NULL)
3677 {
3678 ipp_quality_t pq = (ipp_quality_t)ippGetInteger(attr, 0);
3679
3680 if (pq >= IPP_QUALITY_DRAFT && pq <= IPP_QUALITY_HIGH)
3681 print_quality = attr->values[0].integer - IPP_QUALITY_DRAFT;
3682 else
3683 print_quality = _PWG_PRINT_QUALITY_NORMAL;
3684 }
3685 else if ((attr = ippFindAttribute(job->attrs, "cupsPrintQuality", IPP_TAG_NAME)) != NULL)
3686 {
3687 const char *pq = ippGetString(attr, 0, NULL);
3688
3689 if (!_cups_strcasecmp(pq, "draft"))
3690 print_quality = _PWG_PRINT_QUALITY_DRAFT;
3691 else if (!_cups_strcasecmp(pq, "high"))
3692 print_quality = _PWG_PRINT_QUALITY_HIGH;
3693 else
3694 print_quality = _PWG_PRINT_QUALITY_NORMAL;
3695
3696 if (!ippFindAttribute(job->attrs, "print-quality", IPP_TAG_ENUM))
3697 {
3698 cupsdLogJob(job, CUPSD_LOG_DEBUG2, "Mapping cupsPrintQuality=%s to print-quality=%d", pq, print_quality + IPP_QUALITY_DRAFT);
3699 num_pwgppds = cupsAddIntegerOption("print-quality", print_quality + IPP_QUALITY_DRAFT, num_pwgppds, &pwgppds);
3700 }
3701 }
3702 else
3703 {
3704 print_quality = _PWG_PRINT_QUALITY_NORMAL;
3705 }
3706
3707 if (pc->num_presets[print_color_mode][print_quality] == 0)
3708 {
3709 /*
3710 * Try to find a preset that works so that we maximize the chances of us
3711 * getting a good print using IPP attributes.
3712 */
3713
3714 if (pc->num_presets[print_color_mode][_PWG_PRINT_QUALITY_NORMAL] > 0)
3715 print_quality = _PWG_PRINT_QUALITY_NORMAL;
3716 else if (pc->num_presets[_PWG_PRINT_COLOR_MODE_COLOR][print_quality] > 0)
3717 print_color_mode = _PWG_PRINT_COLOR_MODE_COLOR;
3718 else
3719 {
3720 print_quality = _PWG_PRINT_QUALITY_NORMAL;
3721 print_color_mode = _PWG_PRINT_COLOR_MODE_COLOR;
3722 }
3723 }
3724
3725 if (pc->num_presets[print_color_mode][print_quality] > 0)
3726 {
3727 /*
3728 * Copy the preset options as long as the corresponding names are not
3729 * already defined in the IPP request...
3730 */
3731
3732 for (i = pc->num_presets[print_color_mode][print_quality],
3733 preset = pc->presets[print_color_mode][print_quality];
3734 i > 0;
3735 i --, preset ++)
3736 {
3737 if (!ippFindAttribute(job->attrs, preset->name, IPP_TAG_ZERO))
3738 {
3739 cupsdLogJob(job, CUPSD_LOG_DEBUG2, "Adding preset option %s=%s", preset->name, preset->value);
3740
3741 num_pwgppds = cupsAddOption(preset->name, preset->value, num_pwgppds, &pwgppds);
3742 }
3743 }
3744 }
3745 }
3746
3747 if (pc)
3748 {
3749 if ((attr = ippFindAttribute(job->attrs, "print-quality", IPP_TAG_ENUM)) != NULL)
3750 {
3751 int pq = ippGetInteger(attr, 0);
3752 static const char * const pqs[] = { "Draft", "Normal", "High" };
3753
3754 if (pq >= IPP_QUALITY_DRAFT && pq <= IPP_QUALITY_HIGH)
3755 {
3756 cupsdLogJob(job, CUPSD_LOG_DEBUG2, "Mapping print-quality=%d to cupsPrintQuality=%s", pq, pqs[pq - IPP_QUALITY_DRAFT]);
3757
3758 num_pwgppds = cupsAddOption("cupsPrintQuality", pqs[pq - IPP_QUALITY_DRAFT], num_pwgppds, &pwgppds);
3759 }
3760 }
3761
3762 if (!ippFindAttribute(job->attrs, "InputSlot", IPP_TAG_ZERO) &&
3763 !ippFindAttribute(job->attrs, "HPPaperSource", IPP_TAG_ZERO))
3764 {
3765 if ((ppd = _ppdCacheGetInputSlot(pc, job->attrs, NULL)) != NULL)
3766 num_pwgppds = cupsAddOption(pc->source_option, ppd, num_pwgppds,
3767 &pwgppds);
3768 }
3769 if (!ippFindAttribute(job->attrs, "MediaType", IPP_TAG_ZERO) &&
3770 (ppd = _ppdCacheGetMediaType(pc, job->attrs, NULL)) != NULL)
3771 {
3772 cupsdLogJob(job, CUPSD_LOG_DEBUG2, "Mapping media to MediaType=%s", ppd);
3773
3774 num_pwgppds = cupsAddOption("MediaType", ppd, num_pwgppds, &pwgppds);
3775 }
3776
3777 if (!ippFindAttribute(job->attrs, "PageRegion", IPP_TAG_ZERO) &&
3778 !ippFindAttribute(job->attrs, "PageSize", IPP_TAG_ZERO) &&
3779 (ppd = _ppdCacheGetPageSize(pc, job->attrs, NULL, &exact)) != NULL)
3780 {
3781 cupsdLogJob(job, CUPSD_LOG_DEBUG2, "Mapping media to Pagesize=%s", ppd);
3782
3783 num_pwgppds = cupsAddOption("PageSize", ppd, num_pwgppds, &pwgppds);
3784
3785 if (!ippFindAttribute(job->attrs, "media", IPP_TAG_ZERO))
3786 {
3787 cupsdLogJob(job, CUPSD_LOG_DEBUG2, "Adding media=%s", ppd);
3788
3789 num_pwgppds = cupsAddOption("media", ppd, num_pwgppds, &pwgppds);
3790 }
3791 }
3792
3793 if (!ippFindAttribute(job->attrs, "OutputBin", IPP_TAG_ZERO) &&
3794 (attr = ippFindAttribute(job->attrs, "output-bin",
3795 IPP_TAG_ZERO)) != NULL &&
3796 (attr->value_tag == IPP_TAG_KEYWORD ||
3797 attr->value_tag == IPP_TAG_NAME) &&
3798 (ppd = _ppdCacheGetOutputBin(pc, attr->values[0].string.text)) != NULL)
3799 {
3800 /*
3801 * Map output-bin to OutputBin option...
3802 */
3803
3804 cupsdLogJob(job, CUPSD_LOG_DEBUG2, "Mapping output-bin to OutputBin=%s", ppd);
3805
3806 num_pwgppds = cupsAddOption("OutputBin", ppd, num_pwgppds, &pwgppds);
3807 }
3808
3809 if (pc->sides_option &&
3810 !ippFindAttribute(job->attrs, pc->sides_option, IPP_TAG_ZERO) &&
3811 (attr = ippFindAttribute(job->attrs, "sides", IPP_TAG_KEYWORD)) != NULL)
3812 {
3813 /*
3814 * Map sides to duplex option...
3815 */
3816
3817 if (!strcmp(attr->values[0].string.text, "one-sided"))
3818 {
3819 cupsdLogJob(job, CUPSD_LOG_DEBUG2, "Mapping sizes to Duplex=%s", pc->sides_1sided);
3820
3821 num_pwgppds = cupsAddOption(pc->sides_option, pc->sides_1sided, num_pwgppds, &pwgppds);
3822 }
3823 else if (!strcmp(attr->values[0].string.text, "two-sided-long-edge"))
3824 {
3825 cupsdLogJob(job, CUPSD_LOG_DEBUG2, "Mapping sizes to Duplex=%s", pc->sides_2sided_long);
3826
3827 num_pwgppds = cupsAddOption(pc->sides_option, pc->sides_2sided_long, num_pwgppds, &pwgppds);
3828 }
3829 else if (!strcmp(attr->values[0].string.text, "two-sided-short-edge"))
3830 {
3831 cupsdLogJob(job, CUPSD_LOG_DEBUG2, "Mapping sizes to Duplex=%s", pc->sides_2sided_short);
3832
3833 num_pwgppds = cupsAddOption(pc->sides_option, pc->sides_2sided_short, num_pwgppds, &pwgppds);
3834 }
3835 }
3836
3837 /*
3838 * Map finishings values...
3839 */
3840
3841 num_pwgppds = _ppdCacheGetFinishingOptions(pc, job->attrs, IPP_FINISHINGS_NONE, num_pwgppds, &pwgppds);
3842
3843 for (i = num_pwgppds, pwgppd = pwgppds; i > 0; i --, pwgppd ++)
3844 cupsdLogJob(job, CUPSD_LOG_DEBUG2, "After mapping finishings %s=%s", pwgppd->name, pwgppd->value);
3845 }
3846
3847 /*
3848 * Map page-delivery values...
3849 */
3850
3851 if ((attr = ippFindAttribute(job->attrs, "page-delivery", IPP_TAG_KEYWORD)) != NULL && !ippFindAttribute(job->attrs, "outputorder", IPP_TAG_ZERO))
3852 {
3853 const char *page_delivery = ippGetString(attr, 0, NULL);
3854
3855 if (!strncmp(page_delivery, "same-order", 10))
3856 num_pwgppds = cupsAddOption("OutputOrder", "Normal", num_pwgppds, &pwgppds);
3857 else if (!strncmp(page_delivery, "reverse-order", 13))
3858 num_pwgppds = cupsAddOption("OutputOrder", "Reverse", num_pwgppds, &pwgppds);
3859 }
3860
3861 /*
3862 * Figure out how much room we need...
3863 */
3864
3865 newlength = ipp_length(job->attrs);
3866
3867 for (i = num_pwgppds, pwgppd = pwgppds; i > 0; i --, pwgppd ++)
3868 newlength += 1 + strlen(pwgppd->name) + 1 + strlen(pwgppd->value);
3869
3870 /*
3871 * Then allocate/reallocate the option buffer as needed...
3872 */
3873
3874 if (newlength == 0) /* This can never happen, but Clang */
3875 newlength = 1; /* thinks it can... */
3876
3877 if (newlength > optlength || !options)
3878 {
3879 if (!options)
3880 optptr = malloc(newlength);
3881 else
3882 optptr = realloc(options, newlength);
3883
3884 if (!optptr)
3885 {
3886 cupsdLogJob(job, CUPSD_LOG_CRIT,
3887 "Unable to allocate " CUPS_LLFMT " bytes for option buffer.",
3888 CUPS_LLCAST newlength);
3889 return (NULL);
3890 }
3891
3892 options = optptr;
3893 optlength = newlength;
3894 }
3895
3896 /*
3897 * Now loop through the attributes and convert them to the textual
3898 * representation used by the filters...
3899 */
3900
3901 optptr = options;
3902 *optptr = '\0';
3903
3904 snprintf(title, title_size, "%s-%d", job->printer->name, job->id);
3905 strlcpy(copies, "1", copies_size);
3906
3907 for (attr = job->attrs->attrs; attr != NULL; attr = attr->next)
3908 {
3909 if (!strcmp(attr->name, "copies") &&
3910 attr->value_tag == IPP_TAG_INTEGER)
3911 {
3912 /*
3913 * Don't use the # copies attribute if we are printing the job sheets...
3914 */
3915
3916 if (!banner_page)
3917 snprintf(copies, copies_size, "%d", attr->values[0].integer);
3918 }
3919 else if (!strcmp(attr->name, "job-name") &&
3920 (attr->value_tag == IPP_TAG_NAME ||
3921 attr->value_tag == IPP_TAG_NAMELANG))
3922 strlcpy(title, attr->values[0].string.text, title_size);
3923 else if (attr->group_tag == IPP_TAG_JOB)
3924 {
3925 /*
3926 * Filter out other unwanted attributes...
3927 */
3928
3929 if (attr->value_tag == IPP_TAG_NOVALUE ||
3930 attr->value_tag == IPP_TAG_MIMETYPE ||
3931 attr->value_tag == IPP_TAG_NAMELANG ||
3932 attr->value_tag == IPP_TAG_TEXTLANG ||
3933 (attr->value_tag == IPP_TAG_URI && strcmp(attr->name, "job-uuid") &&
3934 strcmp(attr->name, "job-authorization-uri")) ||
3935 attr->value_tag == IPP_TAG_URISCHEME ||
3936 attr->value_tag == IPP_TAG_BEGIN_COLLECTION) /* Not yet supported */
3937 continue;
3938
3939 if (!strcmp(attr->name, "job-hold-until") ||
3940 !strcmp(attr->name, "job-id") ||
3941 !strcmp(attr->name, "job-k-octets") ||
3942 !strcmp(attr->name, "job-media-sheets") ||
3943 !strcmp(attr->name, "job-media-sheets-completed") ||
3944 !strcmp(attr->name, "job-state") ||
3945 !strcmp(attr->name, "job-state-reasons"))
3946 continue;
3947
3948 if (!strncmp(attr->name, "job-", 4) &&
3949 strcmp(attr->name, "job-account-id") &&
3950 strcmp(attr->name, "job-accounting-user-id") &&
3951 strcmp(attr->name, "job-authorization-uri") &&
3952 strcmp(attr->name, "job-billing") &&
3953 strcmp(attr->name, "job-impressions") &&
3954 strcmp(attr->name, "job-originating-host-name") &&
3955 strcmp(attr->name, "job-password") &&
3956 strcmp(attr->name, "job-password-encryption") &&
3957 strcmp(attr->name, "job-uuid") &&
3958 !(job->printer->type & CUPS_PRINTER_REMOTE))
3959 continue;
3960
3961 if ((!strcmp(attr->name, "job-impressions") ||
3962 !strcmp(attr->name, "page-label") ||
3963 !strcmp(attr->name, "page-border") ||
3964 !strncmp(attr->name, "number-up", 9) ||
3965 !strcmp(attr->name, "page-ranges") ||
3966 !strcmp(attr->name, "page-set") ||
3967 !_cups_strcasecmp(attr->name, "AP_FIRSTPAGE_InputSlot") ||
3968 !_cups_strcasecmp(attr->name, "AP_FIRSTPAGE_ManualFeed") ||
3969 !_cups_strcasecmp(attr->name, "com.apple.print.PrintSettings."
3970 "PMTotalSidesImaged..n.") ||
3971 !_cups_strcasecmp(attr->name, "com.apple.print.PrintSettings."
3972 "PMTotalBeginPages..n.")) &&
3973 banner_page)
3974 continue;
3975
3976 /*
3977 * Otherwise add them to the list...
3978 */
3979
3980 if (optptr > options)
3981 strlcat(optptr, " ", optlength - (size_t)(optptr - options));
3982
3983 if (attr->value_tag != IPP_TAG_BOOLEAN)
3984 {
3985 strlcat(optptr, attr->name, optlength - (size_t)(optptr - options));
3986 strlcat(optptr, "=", optlength - (size_t)(optptr - options));
3987 }
3988
3989 for (i = 0; i < attr->num_values; i ++)
3990 {
3991 if (i)
3992 strlcat(optptr, ",", optlength - (size_t)(optptr - options));
3993
3994 optptr += strlen(optptr);
3995
3996 switch (attr->value_tag)
3997 {
3998 case IPP_TAG_INTEGER :
3999 case IPP_TAG_ENUM :
4000 snprintf(optptr, optlength - (size_t)(optptr - options),
4001 "%d", attr->values[i].integer);
4002 break;
4003
4004 case IPP_TAG_BOOLEAN :
4005 if (!attr->values[i].boolean)
4006 strlcat(optptr, "no", optlength - (size_t)(optptr - options));
4007
4008 strlcat(optptr, attr->name, optlength - (size_t)(optptr - options));
4009 break;
4010
4011 case IPP_TAG_RANGE :
4012 if (attr->values[i].range.lower == attr->values[i].range.upper)
4013 snprintf(optptr, optlength - (size_t)(optptr - options) - 1,
4014 "%d", attr->values[i].range.lower);
4015 else
4016 snprintf(optptr, optlength - (size_t)(optptr - options) - 1,
4017 "%d-%d", attr->values[i].range.lower,
4018 attr->values[i].range.upper);
4019 break;
4020
4021 case IPP_TAG_RESOLUTION :
4022 snprintf(optptr, optlength - (size_t)(optptr - options) - 1,
4023 "%dx%d%s", attr->values[i].resolution.xres,
4024 attr->values[i].resolution.yres,
4025 attr->values[i].resolution.units == IPP_RES_PER_INCH ?
4026 "dpi" : "dpcm");
4027 break;
4028
4029 case IPP_TAG_STRING :
4030 case IPP_TAG_TEXT :
4031 case IPP_TAG_NAME :
4032 case IPP_TAG_KEYWORD :
4033 case IPP_TAG_CHARSET :
4034 case IPP_TAG_LANGUAGE :
4035 case IPP_TAG_URI :
4036 for (valptr = attr->values[i].string.text; *valptr;)
4037 {
4038 if (strchr(" \t\n\\\'\"", *valptr))
4039 *optptr++ = '\\';
4040 *optptr++ = *valptr++;
4041 }
4042
4043 *optptr = '\0';
4044 break;
4045
4046 default :
4047 break; /* anti-compiler-warning-code */
4048 }
4049 }
4050
4051 optptr += strlen(optptr);
4052 }
4053 }
4054
4055 /*
4056 * Finally loop through the PWG->PPD mapped options and add them...
4057 */
4058
4059 for (i = num_pwgppds, pwgppd = pwgppds; i > 0; i --, pwgppd ++)
4060 {
4061 *optptr++ = ' ';
4062 strlcpy(optptr, pwgppd->name, optlength - (size_t)(optptr - options));
4063 optptr += strlen(optptr);
4064 *optptr++ = '=';
4065 strlcpy(optptr, pwgppd->value, optlength - (size_t)(optptr - options));
4066 optptr += strlen(optptr);
4067 }
4068
4069 cupsFreeOptions(num_pwgppds, pwgppds);
4070
4071 /*
4072 * Return the options string...
4073 */
4074
4075 return (options);
4076 }
4077
4078
4079 /*
4080 * 'ipp_length()' - Compute the size of the buffer needed to hold
4081 * the textual IPP attributes.
4082 */
4083
4084 static size_t /* O - Size of attribute buffer */
4085 ipp_length(ipp_t *ipp) /* I - IPP request */
4086 {
4087 size_t bytes; /* Number of bytes */
4088 int i; /* Looping var */
4089 ipp_attribute_t *attr; /* Current attribute */
4090
4091
4092 /*
4093 * Loop through all attributes...
4094 */
4095
4096 bytes = 0;
4097
4098 for (attr = ipp->attrs; attr != NULL; attr = attr->next)
4099 {
4100 /*
4101 * Skip attributes that won't be sent to filters...
4102 */
4103
4104 if (attr->value_tag == IPP_TAG_NOVALUE ||
4105 attr->value_tag == IPP_TAG_MIMETYPE ||
4106 attr->value_tag == IPP_TAG_NAMELANG ||
4107 attr->value_tag == IPP_TAG_TEXTLANG ||
4108 attr->value_tag == IPP_TAG_URI ||
4109 attr->value_tag == IPP_TAG_URISCHEME)
4110 continue;
4111
4112 /*
4113 * Add space for a leading space and commas between each value.
4114 * For the first attribute, the leading space isn't used, so the
4115 * extra byte can be used as the nul terminator...
4116 */
4117
4118 bytes ++; /* " " separator */
4119 bytes += (size_t)attr->num_values; /* "," separators */
4120
4121 /*
4122 * Boolean attributes appear as "foo,nofoo,foo,nofoo", while
4123 * other attributes appear as "foo=value1,value2,...,valueN".
4124 */
4125
4126 if (attr->value_tag != IPP_TAG_BOOLEAN)
4127 bytes += strlen(attr->name);
4128 else
4129 bytes += (size_t)attr->num_values * strlen(attr->name);
4130
4131 /*
4132 * Now add the size required for each value in the attribute...
4133 */
4134
4135 switch (attr->value_tag)
4136 {
4137 case IPP_TAG_INTEGER :
4138 case IPP_TAG_ENUM :
4139 /*
4140 * Minimum value of a signed integer is -2147483647, or 11 digits.
4141 */
4142
4143 bytes += (size_t)attr->num_values * 11;
4144 break;
4145
4146 case IPP_TAG_BOOLEAN :
4147 /*
4148 * Add two bytes for each false ("no") value...
4149 */
4150
4151 for (i = 0; i < attr->num_values; i ++)
4152 if (!attr->values[i].boolean)
4153 bytes += 2;
4154 break;
4155
4156 case IPP_TAG_RANGE :
4157 /*
4158 * A range is two signed integers separated by a hyphen, or
4159 * 23 characters max.
4160 */
4161
4162 bytes += (size_t)attr->num_values * 23;
4163 break;
4164
4165 case IPP_TAG_RESOLUTION :
4166 /*
4167 * A resolution is two signed integers separated by an "x" and
4168 * suffixed by the units, or 26 characters max.
4169 */
4170
4171 bytes += (size_t)attr->num_values * 26;
4172 break;
4173
4174 case IPP_TAG_STRING :
4175 case IPP_TAG_TEXT :
4176 case IPP_TAG_NAME :
4177 case IPP_TAG_KEYWORD :
4178 case IPP_TAG_CHARSET :
4179 case IPP_TAG_LANGUAGE :
4180 case IPP_TAG_URI :
4181 /*
4182 * Strings can contain characters that need quoting. We need
4183 * at least 2 * len + 2 characters to cover the quotes and
4184 * any backslashes in the string.
4185 */
4186
4187 for (i = 0; i < attr->num_values; i ++)
4188 bytes += 2 * strlen(attr->values[i].string.text) + 2;
4189 break;
4190
4191 default :
4192 break; /* anti-compiler-warning-code */
4193 }
4194 }
4195
4196 return (bytes);
4197 }
4198
4199
4200 /*
4201 * 'load_job_cache()' - Load jobs from the job.cache file.
4202 */
4203
4204 static void
4205 load_job_cache(const char *filename) /* I - job.cache filename */
4206 {
4207 cups_file_t *fp; /* job.cache file */
4208 char line[1024], /* Line buffer */
4209 *value; /* Value on line */
4210 int linenum; /* Line number in file */
4211 cupsd_job_t *job; /* Current job */
4212 int jobid; /* Job ID */
4213 char jobfile[1024]; /* Job filename */
4214
4215
4216 /*
4217 * Open the job.cache file...
4218 */
4219
4220 if ((fp = cupsdOpenConfFile(filename)) == NULL)
4221 {
4222 load_request_root();
4223 return;
4224 }
4225
4226 /*
4227 * Read entries from the job cache file and create jobs as needed.
4228 */
4229
4230 cupsdLogMessage(CUPSD_LOG_INFO, "Loading job cache file \"%s\"...",
4231 filename);
4232
4233 linenum = 0;
4234 job = NULL;
4235
4236 while (cupsFileGetConf(fp, line, sizeof(line), &value, &linenum))
4237 {
4238 if (!_cups_strcasecmp(line, "NextJobId"))
4239 {
4240 if (value)
4241 NextJobId = atoi(value);
4242 }
4243 else if (!_cups_strcasecmp(line, "<Job"))
4244 {
4245 if (job)
4246 {
4247 cupsdLogMessage(CUPSD_LOG_ERROR, "Missing </Job> directive on line %d of %s.", linenum, filename);
4248 continue;
4249 }
4250
4251 if (!value)
4252 {
4253 cupsdLogMessage(CUPSD_LOG_ERROR, "Missing job ID on line %d of %s.", linenum, filename);
4254 continue;
4255 }
4256
4257 jobid = atoi(value);
4258
4259 if (jobid < 1)
4260 {
4261 cupsdLogMessage(CUPSD_LOG_ERROR, "Bad job ID %d on line %d of %s.", jobid, linenum, filename);
4262 continue;
4263 }
4264
4265 snprintf(jobfile, sizeof(jobfile), "%s/c%05d", RequestRoot, jobid);
4266 if (access(jobfile, 0))
4267 {
4268 snprintf(jobfile, sizeof(jobfile), "%s/c%05d.N", RequestRoot, jobid);
4269 if (access(jobfile, 0))
4270 {
4271 cupsdLogMessage(CUPSD_LOG_ERROR, "[Job %d] Files have gone away.",
4272 jobid);
4273
4274 /*
4275 * job.cache file is out-of-date compared to spool directory; load
4276 * that instead...
4277 */
4278
4279 cupsFileClose(fp);
4280 load_request_root();
4281 return;
4282 }
4283 }
4284
4285 job = calloc(1, sizeof(cupsd_job_t));
4286 if (!job)
4287 {
4288 cupsdLogMessage(CUPSD_LOG_EMERG,
4289 "[Job %d] Unable to allocate memory for job.", jobid);
4290 break;
4291 }
4292
4293 job->id = jobid;
4294 job->back_pipes[0] = -1;
4295 job->back_pipes[1] = -1;
4296 job->print_pipes[0] = -1;
4297 job->print_pipes[1] = -1;
4298 job->side_pipes[0] = -1;
4299 job->side_pipes[1] = -1;
4300 job->status_pipes[0] = -1;
4301 job->status_pipes[1] = -1;
4302
4303 cupsdLogJob(job, CUPSD_LOG_DEBUG, "Loading from cache...");
4304 }
4305 else if (!job)
4306 {
4307 cupsdLogMessage(CUPSD_LOG_ERROR,
4308 "Missing <Job #> directive on line %d of %s.", linenum, filename);
4309 continue;
4310 }
4311 else if (!_cups_strcasecmp(line, "</Job>"))
4312 {
4313 cupsArrayAdd(Jobs, job);
4314
4315 if (job->state_value <= IPP_JOB_STOPPED && cupsdLoadJob(job))
4316 cupsArrayAdd(ActiveJobs, job);
4317 else if (job->state_value > IPP_JOB_STOPPED)
4318 {
4319 if (!job->completed_time || !job->creation_time || !job->name || !job->koctets)
4320 {
4321 cupsdLoadJob(job);
4322 unload_job(job);
4323 }
4324 }
4325
4326 job = NULL;
4327 }
4328 else if (!value)
4329 {
4330 cupsdLogMessage(CUPSD_LOG_ERROR, "Missing value on line %d of %s.", linenum, filename);
4331 continue;
4332 }
4333 else if (!_cups_strcasecmp(line, "State"))
4334 {
4335 job->state_value = (ipp_jstate_t)atoi(value);
4336
4337 if (job->state_value < IPP_JOB_PENDING)
4338 job->state_value = IPP_JOB_PENDING;
4339 else if (job->state_value > IPP_JOB_COMPLETED)
4340 job->state_value = IPP_JOB_COMPLETED;
4341 }
4342 else if (!_cups_strcasecmp(line, "Name"))
4343 {
4344 cupsdSetString(&(job->name), value);
4345 }
4346 else if (!_cups_strcasecmp(line, "Created"))
4347 {
4348 job->creation_time = strtol(value, NULL, 10);
4349 }
4350 else if (!_cups_strcasecmp(line, "Completed"))
4351 {
4352 job->completed_time = strtol(value, NULL, 10);
4353 }
4354 else if (!_cups_strcasecmp(line, "HoldUntil"))
4355 {
4356 job->hold_until = strtol(value, NULL, 10);
4357 }
4358 else if (!_cups_strcasecmp(line, "Priority"))
4359 {
4360 job->priority = atoi(value);
4361 }
4362 else if (!_cups_strcasecmp(line, "Username"))
4363 {
4364 cupsdSetString(&job->username, value);
4365 }
4366 else if (!_cups_strcasecmp(line, "Destination"))
4367 {
4368 cupsdSetString(&job->dest, value);
4369 }
4370 else if (!_cups_strcasecmp(line, "DestType"))
4371 {
4372 job->dtype = (cups_ptype_t)atoi(value);
4373 }
4374 else if (!_cups_strcasecmp(line, "KOctets"))
4375 {
4376 job->koctets = atoi(value);
4377 }
4378 else if (!_cups_strcasecmp(line, "NumFiles"))
4379 {
4380 job->num_files = atoi(value);
4381
4382 if (job->num_files < 0)
4383 {
4384 cupsdLogMessage(CUPSD_LOG_ERROR, "Bad NumFiles value %d on line %d of %s.", job->num_files, linenum, filename);
4385 job->num_files = 0;
4386 continue;
4387 }
4388
4389 if (job->num_files > 0)
4390 {
4391 snprintf(jobfile, sizeof(jobfile), "%s/d%05d-001", RequestRoot,
4392 job->id);
4393 if (access(jobfile, 0))
4394 {
4395 cupsdLogJob(job, CUPSD_LOG_INFO, "Data files have gone away.");
4396 job->num_files = 0;
4397 continue;
4398 }
4399
4400 job->filetypes = calloc((size_t)job->num_files, sizeof(mime_type_t *));
4401 job->compressions = calloc((size_t)job->num_files, sizeof(int));
4402
4403 if (!job->filetypes || !job->compressions)
4404 {
4405 cupsdLogJob(job, CUPSD_LOG_EMERG,
4406 "Unable to allocate memory for %d files.",
4407 job->num_files);
4408 break;
4409 }
4410 }
4411 }
4412 else if (!_cups_strcasecmp(line, "File"))
4413 {
4414 int number, /* File number */
4415 compression; /* Compression value */
4416 char super[MIME_MAX_SUPER], /* MIME super type */
4417 type[MIME_MAX_TYPE]; /* MIME type */
4418
4419
4420 if (sscanf(value, "%d%*[ \t]%15[^/]/%255s%d", &number, super, type,
4421 &compression) != 4)
4422 {
4423 cupsdLogMessage(CUPSD_LOG_ERROR, "Bad File on line %d of %s.", linenum, filename);
4424 continue;
4425 }
4426
4427 if (number < 1 || number > job->num_files)
4428 {
4429 cupsdLogMessage(CUPSD_LOG_ERROR, "Bad File number %d on line %d of %s.", number, linenum, filename);
4430 continue;
4431 }
4432
4433 number --;
4434
4435 job->compressions[number] = compression;
4436 job->filetypes[number] = mimeType(MimeDatabase, super, type);
4437
4438 if (!job->filetypes[number])
4439 {
4440 /*
4441 * If the original MIME type is unknown, auto-type it!
4442 */
4443
4444 cupsdLogJob(job, CUPSD_LOG_ERROR,
4445 "Unknown MIME type %s/%s for file %d.",
4446 super, type, number + 1);
4447
4448 snprintf(jobfile, sizeof(jobfile), "%s/d%05d-%03d", RequestRoot,
4449 job->id, number + 1);
4450 job->filetypes[number] = mimeFileType(MimeDatabase, jobfile, NULL,
4451 job->compressions + number);
4452
4453 /*
4454 * If that didn't work, assume it is raw...
4455 */
4456
4457 if (!job->filetypes[number])
4458 job->filetypes[number] = mimeType(MimeDatabase, "application",
4459 "vnd.cups-raw");
4460 }
4461 }
4462 else
4463 cupsdLogMessage(CUPSD_LOG_ERROR, "Unknown %s directive on line %d of %s.", line, linenum, filename);
4464 }
4465
4466 if (job)
4467 {
4468 cupsdLogMessage(CUPSD_LOG_ERROR,
4469 "Missing </Job> directive on line %d of %s.", linenum, filename);
4470 cupsdDeleteJob(job, CUPSD_JOB_PURGE);
4471 }
4472
4473 cupsFileClose(fp);
4474 }
4475
4476
4477 /*
4478 * 'load_next_job_id()' - Load the NextJobId value from the job.cache file.
4479 */
4480
4481 static void
4482 load_next_job_id(const char *filename) /* I - job.cache filename */
4483 {
4484 cups_file_t *fp; /* job.cache file */
4485 char line[1024], /* Line buffer */
4486 *value; /* Value on line */
4487 int linenum; /* Line number in file */
4488 int next_job_id; /* NextJobId value from line */
4489
4490
4491 /*
4492 * Read the NextJobId directive from the job.cache file and use
4493 * the value (if any).
4494 */
4495
4496 if ((fp = cupsFileOpen(filename, "r")) == NULL)
4497 {
4498 if (errno != ENOENT)
4499 cupsdLogMessage(CUPSD_LOG_ERROR,
4500 "Unable to open job cache file \"%s\": %s",
4501 filename, strerror(errno));
4502
4503 return;
4504 }
4505
4506 cupsdLogMessage(CUPSD_LOG_INFO,
4507 "Loading NextJobId from job cache file \"%s\"...", filename);
4508
4509 linenum = 0;
4510
4511 while (cupsFileGetConf(fp, line, sizeof(line), &value, &linenum))
4512 {
4513 if (!_cups_strcasecmp(line, "NextJobId"))
4514 {
4515 if (value)
4516 {
4517 next_job_id = atoi(value);
4518
4519 if (next_job_id > NextJobId)
4520 NextJobId = next_job_id;
4521 }
4522 break;
4523 }
4524 }
4525
4526 cupsFileClose(fp);
4527 }
4528
4529
4530 /*
4531 * 'load_request_root()' - Load jobs from the RequestRoot directory.
4532 */
4533
4534 static void
4535 load_request_root(void)
4536 {
4537 cups_dir_t *dir; /* Directory */
4538 cups_dentry_t *dent; /* Directory entry */
4539 cupsd_job_t *job; /* New job */
4540
4541
4542 /*
4543 * Open the requests directory...
4544 */
4545
4546 cupsdLogMessage(CUPSD_LOG_DEBUG, "Scanning %s for jobs...", RequestRoot);
4547
4548 if ((dir = cupsDirOpen(RequestRoot)) == NULL)
4549 {
4550 cupsdLogMessage(CUPSD_LOG_ERROR,
4551 "Unable to open spool directory \"%s\": %s",
4552 RequestRoot, strerror(errno));
4553 return;
4554 }
4555
4556 /*
4557 * Read all the c##### files...
4558 */
4559
4560 while ((dent = cupsDirRead(dir)) != NULL)
4561 if (strlen(dent->filename) >= 6 && dent->filename[0] == 'c')
4562 {
4563 /*
4564 * Allocate memory for the job...
4565 */
4566
4567 if ((job = calloc(sizeof(cupsd_job_t), 1)) == NULL)
4568 {
4569 cupsdLogMessage(CUPSD_LOG_ERROR, "Ran out of memory for jobs.");
4570 cupsDirClose(dir);
4571 return;
4572 }
4573
4574 /*
4575 * Assign the job ID...
4576 */
4577
4578 job->id = atoi(dent->filename + 1);
4579 job->back_pipes[0] = -1;
4580 job->back_pipes[1] = -1;
4581 job->print_pipes[0] = -1;
4582 job->print_pipes[1] = -1;
4583 job->side_pipes[0] = -1;
4584 job->side_pipes[1] = -1;
4585 job->status_pipes[0] = -1;
4586 job->status_pipes[1] = -1;
4587
4588 if (job->id >= NextJobId)
4589 NextJobId = job->id + 1;
4590
4591 /*
4592 * Load the job...
4593 */
4594
4595 if (cupsdLoadJob(job))
4596 {
4597 /*
4598 * Insert the job into the array, sorting by job priority and ID...
4599 */
4600
4601 cupsArrayAdd(Jobs, job);
4602
4603 if (job->state_value <= IPP_JOB_STOPPED)
4604 cupsArrayAdd(ActiveJobs, job);
4605 else
4606 unload_job(job);
4607 }
4608 else
4609 free(job);
4610 }
4611
4612 cupsDirClose(dir);
4613 }
4614
4615
4616 /*
4617 * 'remove_job_files()' - Remove the document files for a job.
4618 */
4619
4620 static void
4621 remove_job_files(cupsd_job_t *job) /* I - Job */
4622 {
4623 int i; /* Looping var */
4624 char filename[1024]; /* Document filename */
4625
4626
4627 if (job->num_files <= 0)
4628 return;
4629
4630 for (i = 1; i <= job->num_files; i ++)
4631 {
4632 snprintf(filename, sizeof(filename), "%s/d%05d-%03d", RequestRoot,
4633 job->id, i);
4634 cupsdUnlinkOrRemoveFile(filename);
4635 }
4636
4637 free(job->filetypes);
4638 free(job->compressions);
4639
4640 job->file_time = 0;
4641 job->num_files = 0;
4642 job->filetypes = NULL;
4643 job->compressions = NULL;
4644
4645 LastEvent |= CUPSD_EVENT_PRINTER_STATE_CHANGED;
4646 }
4647
4648
4649 /*
4650 * 'remove_job_history()' - Remove the control file for a job.
4651 */
4652
4653 static void
4654 remove_job_history(cupsd_job_t *job) /* I - Job */
4655 {
4656 char filename[1024]; /* Control filename */
4657
4658
4659 /*
4660 * Remove the job info file...
4661 */
4662
4663 snprintf(filename, sizeof(filename), "%s/c%05d", RequestRoot,
4664 job->id);
4665 cupsdUnlinkOrRemoveFile(filename);
4666
4667 LastEvent |= CUPSD_EVENT_PRINTER_STATE_CHANGED;
4668 }
4669
4670
4671 /*
4672 * 'set_time()' - Set one of the "time-at-xyz" attributes.
4673 */
4674
4675 static void
4676 set_time(cupsd_job_t *job, /* I - Job to update */
4677 const char *name) /* I - Name of attribute */
4678 {
4679 char date_name[128]; /* date-time-at-xxx */
4680 ipp_attribute_t *attr; /* Time attribute */
4681 time_t curtime; /* Current time */
4682
4683
4684 curtime = time(NULL);
4685
4686 cupsdLogJob(job, CUPSD_LOG_DEBUG, "%s=%ld", name, (long)curtime);
4687
4688 if ((attr = ippFindAttribute(job->attrs, name, IPP_TAG_ZERO)) != NULL)
4689 {
4690 attr->value_tag = IPP_TAG_INTEGER;
4691 attr->values[0].integer = curtime;
4692 }
4693
4694 snprintf(date_name, sizeof(date_name), "date-%s", name);
4695
4696 if ((attr = ippFindAttribute(job->attrs, date_name, IPP_TAG_ZERO)) != NULL)
4697 {
4698 attr->value_tag = IPP_TAG_DATE;
4699 ippSetDate(job->attrs, &attr, 0, ippTimeToDate(curtime));
4700 }
4701
4702 if (!strcmp(name, "time-at-completed"))
4703 {
4704 job->completed_time = curtime;
4705
4706 if (JobHistory < INT_MAX && attr)
4707 job->history_time = attr->values[0].integer + JobHistory;
4708 else
4709 job->history_time = INT_MAX;
4710
4711 if (job->history_time < JobHistoryUpdate || !JobHistoryUpdate)
4712 JobHistoryUpdate = job->history_time;
4713
4714 if (JobFiles < INT_MAX && attr)
4715 job->file_time = curtime + JobFiles;
4716 else
4717 job->file_time = INT_MAX;
4718
4719 if (job->file_time < JobHistoryUpdate || !JobHistoryUpdate)
4720 JobHistoryUpdate = job->file_time;
4721
4722 cupsdLogMessage(CUPSD_LOG_DEBUG2, "set_time: JobHistoryUpdate=%ld",
4723 (long)JobHistoryUpdate);
4724 }
4725 }
4726
4727
4728 /*
4729 * 'start_job()' - Start a print job.
4730 */
4731
4732 static void
4733 start_job(cupsd_job_t *job, /* I - Job ID */
4734 cupsd_printer_t *printer) /* I - Printer to print job */
4735 {
4736 const char *filename; /* Support filename */
4737 ipp_attribute_t *cancel_after = ippFindAttribute(job->attrs,
4738 "job-cancel-after",
4739 IPP_TAG_INTEGER);
4740 /* job-cancel-after attribute */
4741
4742
4743 cupsdLogMessage(CUPSD_LOG_DEBUG2, "start_job(job=%p(%d), printer=%p(%s))",
4744 job, job->id, printer, printer->name);
4745
4746 /*
4747 * Make sure we have some files around before we try to print...
4748 */
4749
4750 if (job->num_files == 0)
4751 {
4752 ippSetString(job->attrs, &job->reasons, 0, "aborted-by-system");
4753 cupsdSetJobState(job, IPP_JOB_ABORTED, CUPSD_JOB_DEFAULT,
4754 "Aborting job because it has no files.");
4755 return;
4756 }
4757
4758 /*
4759 * Update the printer and job state to "processing"...
4760 */
4761
4762 if (!cupsdLoadJob(job))
4763 return;
4764
4765 if (!job->printer_message)
4766 job->printer_message = ippFindAttribute(job->attrs,
4767 "job-printer-state-message",
4768 IPP_TAG_TEXT);
4769 if (job->printer_message)
4770 ippSetString(job->attrs, &job->printer_message, 0, "");
4771
4772 ippSetString(job->attrs, &job->reasons, 0, "job-printing");
4773 cupsdSetJobState(job, IPP_JOB_PROCESSING, CUPSD_JOB_DEFAULT, NULL);
4774 cupsdSetPrinterState(printer, IPP_PRINTER_PROCESSING, 0);
4775 cupsdSetPrinterReasons(printer, "-cups-remote-pending,"
4776 "cups-remote-pending-held,"
4777 "cups-remote-processing,"
4778 "cups-remote-stopped,"
4779 "cups-remote-canceled,"
4780 "cups-remote-aborted,"
4781 "cups-remote-completed");
4782
4783 job->cost = 0;
4784 job->current_file = 0;
4785 job->file_time = 0;
4786 job->history_time = 0;
4787 job->progress = 0;
4788 job->printer = printer;
4789 printer->job = job;
4790
4791 if (cancel_after)
4792 job->cancel_time = time(NULL) + ippGetInteger(cancel_after, 0);
4793 else if (MaxJobTime > 0)
4794 job->cancel_time = time(NULL) + MaxJobTime;
4795 else
4796 job->cancel_time = 0;
4797
4798 /*
4799 * Check for support files...
4800 */
4801
4802 cupsdSetPrinterReasons(job->printer, "-cups-missing-filter-warning,"
4803 "cups-insecure-filter-warning");
4804
4805 if (printer->pc)
4806 {
4807 for (filename = (const char *)cupsArrayFirst(printer->pc->support_files);
4808 filename;
4809 filename = (const char *)cupsArrayNext(printer->pc->support_files))
4810 {
4811 if (_cupsFileCheck(filename, _CUPS_FILE_CHECK_FILE, !RunUser,
4812 cupsdLogFCMessage, printer))
4813 break;
4814 }
4815 }
4816
4817 /*
4818 * Setup the last exit status and security profiles...
4819 */
4820
4821 job->status = 0;
4822 job->profile = cupsdCreateProfile(job->id, 0);
4823 job->bprofile = cupsdCreateProfile(job->id, 1);
4824
4825 #ifdef HAVE_SANDBOX_H
4826 if ((!job->profile || !job->bprofile) && UseSandboxing && Sandboxing != CUPSD_SANDBOXING_OFF)
4827 {
4828 /*
4829 * Failure to create the sandbox profile means something really bad has
4830 * happened and we need to shutdown immediately.
4831 */
4832
4833 return;
4834 }
4835 #endif /* HAVE_SANDBOX_H */
4836
4837 /*
4838 * Create the status pipes and buffer...
4839 */
4840
4841 if (cupsdOpenPipe(job->status_pipes))
4842 {
4843 cupsdLogJob(job, CUPSD_LOG_DEBUG,
4844 "Unable to create job status pipes - %s.", strerror(errno));
4845
4846 cupsdSetJobState(job, IPP_JOB_STOPPED, CUPSD_JOB_DEFAULT,
4847 "Job stopped because the scheduler could not create the "
4848 "job status pipes.");
4849
4850 cupsdDestroyProfile(job->profile);
4851 job->profile = NULL;
4852 cupsdDestroyProfile(job->bprofile);
4853 job->bprofile = NULL;
4854 return;
4855 }
4856
4857 job->status_buffer = cupsdStatBufNew(job->status_pipes[0], NULL);
4858 job->status_level = CUPSD_LOG_INFO;
4859
4860 /*
4861 * Create the backchannel pipes and make them non-blocking...
4862 */
4863
4864 if (cupsdOpenPipe(job->back_pipes))
4865 {
4866 cupsdLogJob(job, CUPSD_LOG_DEBUG,
4867 "Unable to create back-channel pipes - %s.", strerror(errno));
4868
4869 cupsdSetJobState(job, IPP_JOB_STOPPED, CUPSD_JOB_DEFAULT,
4870 "Job stopped because the scheduler could not create the "
4871 "back-channel pipes.");
4872
4873 cupsdClosePipe(job->status_pipes);
4874 cupsdStatBufDelete(job->status_buffer);
4875 job->status_buffer = NULL;
4876
4877 cupsdDestroyProfile(job->profile);
4878 job->profile = NULL;
4879 cupsdDestroyProfile(job->bprofile);
4880 job->bprofile = NULL;
4881 return;
4882 }
4883
4884 fcntl(job->back_pipes[0], F_SETFL,
4885 fcntl(job->back_pipes[0], F_GETFL) | O_NONBLOCK);
4886 fcntl(job->back_pipes[1], F_SETFL,
4887 fcntl(job->back_pipes[1], F_GETFL) | O_NONBLOCK);
4888
4889 /*
4890 * Create the side-channel pipes and make them non-blocking...
4891 */
4892
4893 if (socketpair(AF_LOCAL, SOCK_STREAM, 0, job->side_pipes))
4894 {
4895 cupsdLogJob(job, CUPSD_LOG_DEBUG,
4896 "Unable to create side-channel pipes - %s.", strerror(errno));
4897
4898 cupsdSetJobState(job, IPP_JOB_STOPPED, CUPSD_JOB_DEFAULT,
4899 "Job stopped because the scheduler could not create the "
4900 "side-channel pipes.");
4901
4902 cupsdClosePipe(job->back_pipes);
4903
4904 cupsdClosePipe(job->status_pipes);
4905 cupsdStatBufDelete(job->status_buffer);
4906 job->status_buffer = NULL;
4907
4908 cupsdDestroyProfile(job->profile);
4909 job->profile = NULL;
4910 cupsdDestroyProfile(job->bprofile);
4911 job->bprofile = NULL;
4912 return;
4913 }
4914
4915 fcntl(job->side_pipes[0], F_SETFL,
4916 fcntl(job->side_pipes[0], F_GETFL) | O_NONBLOCK);
4917 fcntl(job->side_pipes[1], F_SETFL,
4918 fcntl(job->side_pipes[1], F_GETFL) | O_NONBLOCK);
4919
4920 fcntl(job->side_pipes[0], F_SETFD,
4921 fcntl(job->side_pipes[0], F_GETFD) | FD_CLOEXEC);
4922 fcntl(job->side_pipes[1], F_SETFD,
4923 fcntl(job->side_pipes[1], F_GETFD) | FD_CLOEXEC);
4924
4925 /*
4926 * Now start the first file in the job...
4927 */
4928
4929 cupsdContinueJob(job);
4930 }
4931
4932
4933 /*
4934 * 'stop_job()' - Stop a print job.
4935 */
4936
4937 static void
4938 stop_job(cupsd_job_t *job, /* I - Job */
4939 cupsd_jobaction_t action) /* I - Action */
4940 {
4941 int i; /* Looping var */
4942
4943
4944 cupsdLogMessage(CUPSD_LOG_DEBUG2, "stop_job(job=%p(%d), action=%d)", job,
4945 job->id, action);
4946
4947 FilterLevel -= job->cost;
4948 job->cost = 0;
4949
4950 if (action == CUPSD_JOB_DEFAULT && !job->kill_time && job->backend > 0)
4951 job->kill_time = time(NULL) + JobKillDelay;
4952 else if (action >= CUPSD_JOB_FORCE)
4953 job->kill_time = 0;
4954
4955 for (i = 0; job->filters[i]; i ++)
4956 if (job->filters[i] > 0)
4957 {
4958 cupsdEndProcess(job->filters[i], action >= CUPSD_JOB_FORCE);
4959
4960 if (action >= CUPSD_JOB_FORCE)
4961 job->filters[i] = -job->filters[i];
4962 }
4963
4964 if (job->backend > 0)
4965 {
4966 cupsdEndProcess(job->backend, action >= CUPSD_JOB_FORCE);
4967
4968 if (action >= CUPSD_JOB_FORCE)
4969 job->backend = -job->backend;
4970 }
4971
4972 if (action >= CUPSD_JOB_FORCE)
4973 {
4974 /*
4975 * Clear job status...
4976 */
4977
4978 job->status = 0;
4979 }
4980 }
4981
4982
4983 /*
4984 * 'unload_job()' - Unload a job from memory.
4985 */
4986
4987 static void
4988 unload_job(cupsd_job_t *job) /* I - Job */
4989 {
4990 if (!job->attrs)
4991 return;
4992
4993 cupsdLogJob(job, CUPSD_LOG_DEBUG, "Unloading...");
4994
4995 ippDelete(job->attrs);
4996
4997 job->attrs = NULL;
4998 job->state = NULL;
4999 job->reasons = NULL;
5000 job->impressions = NULL;
5001 job->sheets = NULL;
5002 job->job_sheets = NULL;
5003 job->printer_message = NULL;
5004 job->printer_reasons = NULL;
5005 }
5006
5007
5008 /*
5009 * 'update_job()' - Read a status update from a job's filters.
5010 */
5011
5012 void
5013 update_job(cupsd_job_t *job) /* I - Job to check */
5014 {
5015 int i; /* Looping var */
5016 char message[CUPSD_SB_BUFFER_SIZE],
5017 /* Message text */
5018 *ptr; /* Pointer update... */
5019 int loglevel, /* Log level for message */
5020 event = 0; /* Events? */
5021 cupsd_printer_t *printer = job->printer;
5022 /* Printer */
5023 static const char * const levels[] = /* Log levels */
5024 {
5025 "NONE",
5026 "EMERG",
5027 "ALERT",
5028 "CRIT",
5029 "ERROR",
5030 "WARN",
5031 "NOTICE",
5032 "INFO",
5033 "DEBUG",
5034 "DEBUG2"
5035 };
5036
5037
5038 /*
5039 * Get the printer associated with this job; if the printer is stopped for
5040 * any reason then job->printer will be reset to NULL, so make sure we have
5041 * a valid pointer...
5042 */
5043
5044 while ((ptr = cupsdStatBufUpdate(job->status_buffer, &loglevel,
5045 message, sizeof(message))) != NULL)
5046 {
5047 /*
5048 * Process page and printer state messages as needed...
5049 */
5050
5051 if (loglevel == CUPSD_LOG_PAGE)
5052 {
5053 int impressions = ippGetInteger(job->impressions, 0);
5054 /* Number of impressions printed */
5055 int delta; /* Number of impressions added */
5056
5057 /*
5058 * Page message; send the message to the page_log file and update the
5059 * job sheet count...
5060 */
5061
5062 cupsdLogJob(job, CUPSD_LOG_DEBUG, "PAGE: %s", message);
5063
5064 if (!_cups_strncasecmp(message, "total ", 6))
5065 {
5066 /*
5067 * Got a total count of pages from a backend or filter...
5068 */
5069
5070 int total = atoi(message + 6); /* Total impressions */
5071
5072 if (total > impressions)
5073 {
5074 delta = total - impressions;
5075 impressions = total;
5076 }
5077 else
5078 delta = 0;
5079 }
5080 else
5081 {
5082 /*
5083 * Add the number of copies to the impression count...
5084 */
5085
5086 int copies; /* Number of copies */
5087
5088 if (!sscanf(message, "%*d%d", &copies) || copies <= 0)
5089 copies = 1;
5090
5091 delta = copies;
5092 impressions += copies;
5093 }
5094
5095 if (job->impressions)
5096 ippSetInteger(job->attrs, &job->impressions, 0, impressions);
5097
5098 if (job->sheets)
5099 {
5100 const char *sides = ippGetString(ippFindAttribute(job->attrs, "sides", IPP_TAG_KEYWORD), 0, NULL);
5101
5102 if (sides && strcmp(sides, "one-sided"))
5103 ippSetInteger(job->attrs, &job->sheets, 0, impressions / 2);
5104 else
5105 ippSetInteger(job->attrs, &job->sheets, 0, impressions);
5106
5107 cupsdAddEvent(CUPSD_EVENT_JOB_PROGRESS, job->printer, job, "Printed %d page(s).", ippGetInteger(job->sheets, 0));
5108 }
5109
5110 job->dirty = 1;
5111 cupsdMarkDirty(CUPSD_DIRTY_JOBS);
5112
5113 if (job->printer->page_limit)
5114 cupsdUpdateQuota(job->printer, job->username, delta, 0);
5115 }
5116 else if (loglevel == CUPSD_LOG_JOBSTATE)
5117 {
5118 /*
5119 * Support "keyword" to set job-state-reasons to the specified keyword.
5120 * This is sufficient for the current paid printing stuff.
5121 */
5122
5123 cupsdLogJob(job, CUPSD_LOG_DEBUG, "JOBSTATE: %s", message);
5124
5125 if (!strcmp(message, "cups-retry-as-raster"))
5126 job->retry_as_raster = 1;
5127 else
5128 ippSetString(job->attrs, &job->reasons, 0, message);
5129 }
5130 else if (loglevel == CUPSD_LOG_STATE)
5131 {
5132 cupsdLogJob(job, CUPSD_LOG_DEBUG, "STATE: %s", message);
5133
5134 if (!strcmp(message, "paused"))
5135 {
5136 cupsdStopPrinter(job->printer, 1);
5137 return;
5138 }
5139 else if (message[0] && cupsdSetPrinterReasons(job->printer, message))
5140 {
5141 event |= CUPSD_EVENT_PRINTER_STATE;
5142
5143 if (MaxJobTime > 0)
5144 {
5145 /*
5146 * Reset cancel time after connecting to the device...
5147 */
5148
5149 for (i = 0; i < job->printer->num_reasons; i ++)
5150 if (!strcmp(job->printer->reasons[i], "connecting-to-device"))
5151 break;
5152
5153 if (i >= job->printer->num_reasons)
5154 {
5155 ipp_attribute_t *cancel_after = ippFindAttribute(job->attrs,
5156 "job-cancel-after",
5157 IPP_TAG_INTEGER);
5158 /* job-cancel-after attribute */
5159
5160 if (cancel_after)
5161 job->cancel_time = time(NULL) + ippGetInteger(cancel_after, 0);
5162 else
5163 job->cancel_time = time(NULL) + MaxJobTime;
5164 }
5165 }
5166 }
5167
5168 update_job_attrs(job, 0);
5169 }
5170 else if (loglevel == CUPSD_LOG_ATTR)
5171 {
5172 /*
5173 * Set attribute(s)...
5174 */
5175
5176 int num_attrs; /* Number of attributes */
5177 cups_option_t *attrs; /* Attributes */
5178 const char *attr; /* Attribute */
5179
5180 cupsdLogJob(job, CUPSD_LOG_DEBUG, "ATTR: %s", message);
5181
5182 num_attrs = cupsParseOptions(message, 0, &attrs);
5183
5184 if ((attr = cupsGetOption("auth-info-default", num_attrs,
5185 attrs)) != NULL)
5186 {
5187 job->printer->num_options = cupsAddOption("auth-info", attr,
5188 job->printer->num_options,
5189 &(job->printer->options));
5190 cupsdSetPrinterAttrs(job->printer);
5191
5192 cupsdMarkDirty(CUPSD_DIRTY_PRINTERS);
5193 }
5194
5195 if ((attr = cupsGetOption("auth-info-required", num_attrs,
5196 attrs)) != NULL)
5197 {
5198 cupsdSetAuthInfoRequired(job->printer, attr, NULL);
5199 cupsdSetPrinterAttrs(job->printer);
5200
5201 cupsdMarkDirty(CUPSD_DIRTY_PRINTERS);
5202 }
5203
5204 if ((attr = cupsGetOption("job-media-progress", num_attrs,
5205 attrs)) != NULL)
5206 {
5207 int progress = atoi(attr);
5208
5209
5210 if (progress >= 0 && progress <= 100)
5211 {
5212 job->progress = progress;
5213
5214 if (job->sheets)
5215 cupsdAddEvent(CUPSD_EVENT_JOB_PROGRESS, job->printer, job,
5216 "Printing page %d, %d%%",
5217 job->sheets->values[0].integer, job->progress);
5218 }
5219 }
5220
5221 if ((attr = cupsGetOption("printer-alert", num_attrs, attrs)) != NULL)
5222 {
5223 cupsdSetString(&job->printer->alert, attr);
5224 event |= CUPSD_EVENT_PRINTER_STATE;
5225 }
5226
5227 if ((attr = cupsGetOption("printer-alert-description", num_attrs,
5228 attrs)) != NULL)
5229 {
5230 cupsdSetString(&job->printer->alert_description, attr);
5231 event |= CUPSD_EVENT_PRINTER_STATE;
5232 }
5233
5234 if ((attr = cupsGetOption("marker-colors", num_attrs, attrs)) != NULL)
5235 {
5236 cupsdSetPrinterAttr(job->printer, "marker-colors", (char *)attr);
5237 job->printer->marker_time = time(NULL);
5238 event |= CUPSD_EVENT_PRINTER_STATE;
5239 cupsdMarkDirty(CUPSD_DIRTY_PRINTERS);
5240 }
5241
5242 if ((attr = cupsGetOption("marker-levels", num_attrs, attrs)) != NULL)
5243 {
5244 cupsdSetPrinterAttr(job->printer, "marker-levels", (char *)attr);
5245 job->printer->marker_time = time(NULL);
5246 event |= CUPSD_EVENT_PRINTER_STATE;
5247 cupsdMarkDirty(CUPSD_DIRTY_PRINTERS);
5248 }
5249
5250 if ((attr = cupsGetOption("marker-low-levels", num_attrs, attrs)) != NULL)
5251 {
5252 cupsdSetPrinterAttr(job->printer, "marker-low-levels", (char *)attr);
5253 job->printer->marker_time = time(NULL);
5254 event |= CUPSD_EVENT_PRINTER_STATE;
5255 cupsdMarkDirty(CUPSD_DIRTY_PRINTERS);
5256 }
5257
5258 if ((attr = cupsGetOption("marker-high-levels", num_attrs, attrs)) != NULL)
5259 {
5260 cupsdSetPrinterAttr(job->printer, "marker-high-levels", (char *)attr);
5261 job->printer->marker_time = time(NULL);
5262 event |= CUPSD_EVENT_PRINTER_STATE;
5263 cupsdMarkDirty(CUPSD_DIRTY_PRINTERS);
5264 }
5265
5266 if ((attr = cupsGetOption("marker-message", num_attrs, attrs)) != NULL)
5267 {
5268 cupsdSetPrinterAttr(job->printer, "marker-message", (char *)attr);
5269 job->printer->marker_time = time(NULL);
5270 event |= CUPSD_EVENT_PRINTER_STATE;
5271 cupsdMarkDirty(CUPSD_DIRTY_PRINTERS);
5272 }
5273
5274 if ((attr = cupsGetOption("marker-names", num_attrs, attrs)) != NULL)
5275 {
5276 cupsdSetPrinterAttr(job->printer, "marker-names", (char *)attr);
5277 job->printer->marker_time = time(NULL);
5278 event |= CUPSD_EVENT_PRINTER_STATE;
5279 cupsdMarkDirty(CUPSD_DIRTY_PRINTERS);
5280 }
5281
5282 if ((attr = cupsGetOption("marker-types", num_attrs, attrs)) != NULL)
5283 {
5284 cupsdSetPrinterAttr(job->printer, "marker-types", (char *)attr);
5285 job->printer->marker_time = time(NULL);
5286 event |= CUPSD_EVENT_PRINTER_STATE;
5287 cupsdMarkDirty(CUPSD_DIRTY_PRINTERS);
5288 }
5289
5290 cupsFreeOptions(num_attrs, attrs);
5291 }
5292 else if (loglevel == CUPSD_LOG_PPD)
5293 {
5294 /*
5295 * Set attribute(s)...
5296 */
5297
5298 cupsdLogJob(job, CUPSD_LOG_DEBUG, "PPD: %s", message);
5299
5300 job->num_keywords = cupsParseOptions(message, job->num_keywords,
5301 &job->keywords);
5302 }
5303 else
5304 {
5305 /*
5306 * Strip legacy message prefix...
5307 */
5308
5309 if (!strncmp(message, "recoverable:", 12))
5310 {
5311 ptr = message + 12;
5312 while (isspace(*ptr & 255))
5313 ptr ++;
5314 }
5315 else if (!strncmp(message, "recovered:", 10))
5316 {
5317 ptr = message + 10;
5318 while (isspace(*ptr & 255))
5319 ptr ++;
5320 }
5321 else
5322 ptr = message;
5323
5324 if (*ptr)
5325 cupsdLogJob(job, loglevel == CUPSD_LOG_INFO ? CUPSD_LOG_DEBUG : loglevel, "%s", ptr);
5326
5327 if (loglevel < CUPSD_LOG_DEBUG &&
5328 strcmp(job->printer->state_message, ptr))
5329 {
5330 strlcpy(job->printer->state_message, ptr,
5331 sizeof(job->printer->state_message));
5332
5333 event |= CUPSD_EVENT_PRINTER_STATE | CUPSD_EVENT_JOB_PROGRESS;
5334
5335 if (loglevel <= job->status_level && job->status_level > CUPSD_LOG_ERROR)
5336 {
5337 /*
5338 * Some messages show in the job-printer-state-message attribute...
5339 */
5340
5341 if (loglevel != CUPSD_LOG_NOTICE)
5342 job->status_level = loglevel;
5343
5344 update_job_attrs(job, 1);
5345
5346 cupsdLogJob(job, CUPSD_LOG_DEBUG,
5347 "Set job-printer-state-message to \"%s\", "
5348 "current level=%s",
5349 job->printer_message->values[0].string.text,
5350 levels[job->status_level]);
5351 }
5352 }
5353 }
5354
5355 if (!strchr(job->status_buffer->buffer, '\n'))
5356 break;
5357 }
5358
5359 if (event & CUPSD_EVENT_JOB_PROGRESS)
5360 cupsdAddEvent(CUPSD_EVENT_JOB_PROGRESS, job->printer, job,
5361 "%s", job->printer->state_message);
5362 if (event & CUPSD_EVENT_PRINTER_STATE)
5363 cupsdAddEvent(CUPSD_EVENT_PRINTER_STATE, job->printer, NULL,
5364 (job->printer->type & CUPS_PRINTER_CLASS) ?
5365 "Class \"%s\" state changed." :
5366 "Printer \"%s\" state changed.",
5367 job->printer->name);
5368
5369
5370 if (ptr == NULL && !job->status_buffer->bufused)
5371 {
5372 /*
5373 * See if all of the filters and the backend have returned their
5374 * exit statuses.
5375 */
5376
5377 for (i = 0; job->filters[i] < 0; i ++);
5378
5379 if (job->filters[i])
5380 {
5381 /*
5382 * EOF but we haven't collected the exit status of all filters...
5383 */
5384
5385 cupsdCheckProcess();
5386 return;
5387 }
5388
5389 if (job->current_file >= job->num_files && job->backend > 0)
5390 {
5391 /*
5392 * EOF but we haven't collected the exit status of the backend...
5393 */
5394
5395 cupsdCheckProcess();
5396 return;
5397 }
5398
5399 /*
5400 * Handle the end of job stuff...
5401 */
5402
5403 finalize_job(job, 1);
5404
5405 /*
5406 * Try printing another job...
5407 */
5408
5409 if (printer->state != IPP_PRINTER_STOPPED)
5410 cupsdCheckJobs();
5411 }
5412 }
5413
5414
5415 /*
5416 * 'update_job_attrs()' - Update the job-printer-* attributes.
5417 */
5418
5419 void
5420 update_job_attrs(cupsd_job_t *job, /* I - Job to update */
5421 int do_message)/* I - 1 = copy job-printer-state message */
5422 {
5423 int i; /* Looping var */
5424 int num_reasons; /* Actual number of reasons */
5425 const char * const *reasons; /* Reasons */
5426 static const char *none = "none"; /* "none" reason */
5427
5428
5429 /*
5430 * Get/create the job-printer-state-* attributes...
5431 */
5432
5433 if (!job->printer_message)
5434 {
5435 if ((job->printer_message = ippFindAttribute(job->attrs,
5436 "job-printer-state-message",
5437 IPP_TAG_TEXT)) == NULL)
5438 job->printer_message = ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_TEXT,
5439 "job-printer-state-message",
5440 NULL, "");
5441 }
5442
5443 if (!job->printer_reasons)
5444 job->printer_reasons = ippFindAttribute(job->attrs,
5445 "job-printer-state-reasons",
5446 IPP_TAG_KEYWORD);
5447
5448 /*
5449 * Copy or clear the printer-state-message value as needed...
5450 */
5451
5452 if (job->state_value != IPP_JOB_PROCESSING &&
5453 job->status_level == CUPSD_LOG_INFO)
5454 {
5455 ippSetString(job->attrs, &job->printer_message, 0, "");
5456
5457 job->dirty = 1;
5458 cupsdMarkDirty(CUPSD_DIRTY_JOBS);
5459 }
5460 else if (job->printer->state_message[0] && do_message)
5461 {
5462 ippSetString(job->attrs, &job->printer_message, 0, job->printer->state_message);
5463
5464 job->dirty = 1;
5465 cupsdMarkDirty(CUPSD_DIRTY_JOBS);
5466 }
5467
5468 /*
5469 * ... and the printer-state-reasons value...
5470 */
5471
5472 if (job->printer->num_reasons == 0)
5473 {
5474 num_reasons = 1;
5475 reasons = &none;
5476 }
5477 else
5478 {
5479 num_reasons = job->printer->num_reasons;
5480 reasons = (const char * const *)job->printer->reasons;
5481 }
5482
5483 if (!job->printer_reasons || job->printer_reasons->num_values != num_reasons)
5484 {
5485 /*
5486 * Replace/create a job-printer-state-reasons attribute...
5487 */
5488
5489 ippDeleteAttribute(job->attrs, job->printer_reasons);
5490
5491 job->printer_reasons = ippAddStrings(job->attrs,
5492 IPP_TAG_JOB, IPP_TAG_KEYWORD,
5493 "job-printer-state-reasons",
5494 num_reasons, NULL, NULL);
5495 }
5496 else
5497 {
5498 /*
5499 * Don't bother clearing the reason strings if they are the same...
5500 */
5501
5502 for (i = 0; i < num_reasons; i ++)
5503 if (strcmp(job->printer_reasons->values[i].string.text, reasons[i]))
5504 break;
5505
5506 if (i >= num_reasons)
5507 return;
5508
5509 /*
5510 * Not the same, so free the current strings...
5511 */
5512
5513 for (i = 0; i < num_reasons; i ++)
5514 _cupsStrFree(job->printer_reasons->values[i].string.text);
5515 }
5516
5517 /*
5518 * Copy the reasons...
5519 */
5520
5521 for (i = 0; i < num_reasons; i ++)
5522 job->printer_reasons->values[i].string.text = _cupsStrAlloc(reasons[i]);
5523
5524 job->dirty = 1;
5525 cupsdMarkDirty(CUPSD_DIRTY_JOBS);
5526 }