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