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