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