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