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