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