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