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