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