]> git.ipfire.org Git - thirdparty/cups.git/blob - scheduler/job.c
Merge changes from CUPS 1.6svn-r9939.
[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[255], /* Line from file */
1820 data[255]; /* 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 > optlength || !options)
3375 {
3376 if (!options)
3377 optptr = malloc(newlength);
3378 else
3379 optptr = realloc(options, newlength);
3380
3381 if (!optptr)
3382 {
3383 cupsdLogJob(job, CUPSD_LOG_CRIT,
3384 "Unable to allocate " CUPS_LLFMT " bytes for option buffer!",
3385 CUPS_LLCAST newlength);
3386 return (NULL);
3387 }
3388
3389 options = optptr;
3390 optlength = newlength;
3391 }
3392
3393 /*
3394 * Now loop through the attributes and convert them to the textual
3395 * representation used by the filters...
3396 */
3397
3398 optptr = options;
3399 *optptr = '\0';
3400
3401 snprintf(title, title_size, "%s-%d", job->printer->name, job->id);
3402 strlcpy(copies, "1", copies_size);
3403
3404 for (attr = job->attrs->attrs; attr != NULL; attr = attr->next)
3405 {
3406 if (!strcmp(attr->name, "copies") &&
3407 attr->value_tag == IPP_TAG_INTEGER)
3408 {
3409 /*
3410 * Don't use the # copies attribute if we are printing the job sheets...
3411 */
3412
3413 if (!banner_page)
3414 snprintf(copies, copies_size, "%d", attr->values[0].integer);
3415 }
3416 else if (!strcmp(attr->name, "job-name") &&
3417 (attr->value_tag == IPP_TAG_NAME ||
3418 attr->value_tag == IPP_TAG_NAMELANG))
3419 strlcpy(title, attr->values[0].string.text, title_size);
3420 else if (attr->group_tag == IPP_TAG_JOB)
3421 {
3422 /*
3423 * Filter out other unwanted attributes...
3424 */
3425
3426 if (attr->value_tag == IPP_TAG_NOVALUE ||
3427 attr->value_tag == IPP_TAG_MIMETYPE ||
3428 attr->value_tag == IPP_TAG_NAMELANG ||
3429 attr->value_tag == IPP_TAG_TEXTLANG ||
3430 (attr->value_tag == IPP_TAG_URI && strcmp(attr->name, "job-uuid")) ||
3431 attr->value_tag == IPP_TAG_URISCHEME ||
3432 attr->value_tag == IPP_TAG_BEGIN_COLLECTION) /* Not yet supported */
3433 continue;
3434
3435 if (!strcmp(attr->name, "job-hold-until"))
3436 continue;
3437
3438 if (!strncmp(attr->name, "job-", 4) &&
3439 strcmp(attr->name, "job-billing") &&
3440 strcmp(attr->name, "job-impressions") &&
3441 strcmp(attr->name, "job-originating-host-name") &&
3442 strcmp(attr->name, "job-uuid") &&
3443 !(job->printer->type & CUPS_PRINTER_REMOTE))
3444 continue;
3445
3446 if ((!strcmp(attr->name, "job-impressions") ||
3447 !strcmp(attr->name, "page-label") ||
3448 !strcmp(attr->name, "page-border") ||
3449 !strncmp(attr->name, "number-up", 9) ||
3450 !strcmp(attr->name, "page-ranges") ||
3451 !strcmp(attr->name, "page-set") ||
3452 !_cups_strcasecmp(attr->name, "AP_FIRSTPAGE_InputSlot") ||
3453 !_cups_strcasecmp(attr->name, "AP_FIRSTPAGE_ManualFeed") ||
3454 !_cups_strcasecmp(attr->name, "com.apple.print.PrintSettings."
3455 "PMTotalSidesImaged..n.") ||
3456 !_cups_strcasecmp(attr->name, "com.apple.print.PrintSettings."
3457 "PMTotalBeginPages..n.")) &&
3458 banner_page)
3459 continue;
3460
3461 /*
3462 * Otherwise add them to the list...
3463 */
3464
3465 if (optptr > options)
3466 strlcat(optptr, " ", optlength - (optptr - options));
3467
3468 if (attr->value_tag != IPP_TAG_BOOLEAN)
3469 {
3470 strlcat(optptr, attr->name, optlength - (optptr - options));
3471 strlcat(optptr, "=", optlength - (optptr - options));
3472 }
3473
3474 for (i = 0; i < attr->num_values; i ++)
3475 {
3476 if (i)
3477 strlcat(optptr, ",", optlength - (optptr - options));
3478
3479 optptr += strlen(optptr);
3480
3481 switch (attr->value_tag)
3482 {
3483 case IPP_TAG_INTEGER :
3484 case IPP_TAG_ENUM :
3485 snprintf(optptr, optlength - (optptr - options),
3486 "%d", attr->values[i].integer);
3487 break;
3488
3489 case IPP_TAG_BOOLEAN :
3490 if (!attr->values[i].boolean)
3491 strlcat(optptr, "no", optlength - (optptr - options));
3492
3493 strlcat(optptr, attr->name,
3494 optlength - (optptr - options));
3495 break;
3496
3497 case IPP_TAG_RANGE :
3498 if (attr->values[i].range.lower == attr->values[i].range.upper)
3499 snprintf(optptr, optlength - (optptr - options) - 1,
3500 "%d", attr->values[i].range.lower);
3501 else
3502 snprintf(optptr, optlength - (optptr - options) - 1,
3503 "%d-%d", attr->values[i].range.lower,
3504 attr->values[i].range.upper);
3505 break;
3506
3507 case IPP_TAG_RESOLUTION :
3508 snprintf(optptr, optlength - (optptr - options) - 1,
3509 "%dx%d%s", attr->values[i].resolution.xres,
3510 attr->values[i].resolution.yres,
3511 attr->values[i].resolution.units == IPP_RES_PER_INCH ?
3512 "dpi" : "dpc");
3513 break;
3514
3515 case IPP_TAG_STRING :
3516 case IPP_TAG_TEXT :
3517 case IPP_TAG_NAME :
3518 case IPP_TAG_KEYWORD :
3519 case IPP_TAG_CHARSET :
3520 case IPP_TAG_LANGUAGE :
3521 case IPP_TAG_URI :
3522 for (valptr = attr->values[i].string.text; *valptr;)
3523 {
3524 if (strchr(" \t\n\\\'\"", *valptr))
3525 *optptr++ = '\\';
3526 *optptr++ = *valptr++;
3527 }
3528
3529 *optptr = '\0';
3530 break;
3531
3532 default :
3533 break; /* anti-compiler-warning-code */
3534 }
3535 }
3536
3537 optptr += strlen(optptr);
3538 }
3539 }
3540
3541 /*
3542 * Finally loop through the PWG->PPD mapped options and add them...
3543 */
3544
3545 for (i = num_pwgppds, pwgppd = pwgppds; i > 0; i --, pwgppd ++)
3546 {
3547 *optptr++ = ' ';
3548 strcpy(optptr, pwgppd->name);
3549 optptr += strlen(optptr);
3550 *optptr++ = '=';
3551 strcpy(optptr, pwgppd->value);
3552 optptr += strlen(optptr);
3553 }
3554
3555 cupsFreeOptions(num_pwgppds, pwgppds);
3556
3557 /*
3558 * Return the options string...
3559 */
3560
3561 return (options);
3562 }
3563
3564
3565 /*
3566 * 'ipp_length()' - Compute the size of the buffer needed to hold
3567 * the textual IPP attributes.
3568 */
3569
3570 static size_t /* O - Size of attribute buffer */
3571 ipp_length(ipp_t *ipp) /* I - IPP request */
3572 {
3573 size_t bytes; /* Number of bytes */
3574 int i; /* Looping var */
3575 ipp_attribute_t *attr; /* Current attribute */
3576
3577
3578 /*
3579 * Loop through all attributes...
3580 */
3581
3582 bytes = 0;
3583
3584 for (attr = ipp->attrs; attr != NULL; attr = attr->next)
3585 {
3586 /*
3587 * Skip attributes that won't be sent to filters...
3588 */
3589
3590 if (attr->value_tag == IPP_TAG_NOVALUE ||
3591 attr->value_tag == IPP_TAG_MIMETYPE ||
3592 attr->value_tag == IPP_TAG_NAMELANG ||
3593 attr->value_tag == IPP_TAG_TEXTLANG ||
3594 attr->value_tag == IPP_TAG_URI ||
3595 attr->value_tag == IPP_TAG_URISCHEME)
3596 continue;
3597
3598 /*
3599 * Add space for a leading space and commas between each value.
3600 * For the first attribute, the leading space isn't used, so the
3601 * extra byte can be used as the nul terminator...
3602 */
3603
3604 bytes ++; /* " " separator */
3605 bytes += attr->num_values; /* "," separators */
3606
3607 /*
3608 * Boolean attributes appear as "foo,nofoo,foo,nofoo", while
3609 * other attributes appear as "foo=value1,value2,...,valueN".
3610 */
3611
3612 if (attr->value_tag != IPP_TAG_BOOLEAN)
3613 bytes += strlen(attr->name);
3614 else
3615 bytes += attr->num_values * strlen(attr->name);
3616
3617 /*
3618 * Now add the size required for each value in the attribute...
3619 */
3620
3621 switch (attr->value_tag)
3622 {
3623 case IPP_TAG_INTEGER :
3624 case IPP_TAG_ENUM :
3625 /*
3626 * Minimum value of a signed integer is -2147483647, or 11 digits.
3627 */
3628
3629 bytes += attr->num_values * 11;
3630 break;
3631
3632 case IPP_TAG_BOOLEAN :
3633 /*
3634 * Add two bytes for each false ("no") value...
3635 */
3636
3637 for (i = 0; i < attr->num_values; i ++)
3638 if (!attr->values[i].boolean)
3639 bytes += 2;
3640 break;
3641
3642 case IPP_TAG_RANGE :
3643 /*
3644 * A range is two signed integers separated by a hyphen, or
3645 * 23 characters max.
3646 */
3647
3648 bytes += attr->num_values * 23;
3649 break;
3650
3651 case IPP_TAG_RESOLUTION :
3652 /*
3653 * A resolution is two signed integers separated by an "x" and
3654 * suffixed by the units, or 26 characters max.
3655 */
3656
3657 bytes += attr->num_values * 26;
3658 break;
3659
3660 case IPP_TAG_STRING :
3661 case IPP_TAG_TEXT :
3662 case IPP_TAG_NAME :
3663 case IPP_TAG_KEYWORD :
3664 case IPP_TAG_CHARSET :
3665 case IPP_TAG_LANGUAGE :
3666 case IPP_TAG_URI :
3667 /*
3668 * Strings can contain characters that need quoting. We need
3669 * at least 2 * len + 2 characters to cover the quotes and
3670 * any backslashes in the string.
3671 */
3672
3673 for (i = 0; i < attr->num_values; i ++)
3674 bytes += 2 * strlen(attr->values[i].string.text) + 2;
3675 break;
3676
3677 default :
3678 break; /* anti-compiler-warning-code */
3679 }
3680 }
3681
3682 return (bytes);
3683 }
3684
3685
3686 /*
3687 * 'load_job_cache()' - Load jobs from the job.cache file.
3688 */
3689
3690 static void
3691 load_job_cache(const char *filename) /* I - job.cache filename */
3692 {
3693 cups_file_t *fp; /* job.cache file */
3694 char line[1024], /* Line buffer */
3695 *value; /* Value on line */
3696 int linenum; /* Line number in file */
3697 cupsd_job_t *job; /* Current job */
3698 int jobid; /* Job ID */
3699 char jobfile[1024]; /* Job filename */
3700
3701
3702 /*
3703 * Open the job.cache file...
3704 */
3705
3706 if ((fp = cupsdOpenConfFile(filename)) == NULL)
3707 {
3708 load_request_root();
3709 return;
3710 }
3711
3712 /*
3713 * Read entries from the job cache file and create jobs as needed.
3714 */
3715
3716 cupsdLogMessage(CUPSD_LOG_INFO, "Loading job cache file \"%s\"...",
3717 filename);
3718
3719 linenum = 0;
3720 job = NULL;
3721
3722 while (cupsFileGetConf(fp, line, sizeof(line), &value, &linenum))
3723 {
3724 if (!_cups_strcasecmp(line, "NextJobId"))
3725 {
3726 if (value)
3727 NextJobId = atoi(value);
3728 }
3729 else if (!_cups_strcasecmp(line, "<Job"))
3730 {
3731 if (job)
3732 {
3733 cupsdLogMessage(CUPSD_LOG_ERROR, "Missing </Job> directive on line %d!",
3734 linenum);
3735 continue;
3736 }
3737
3738 if (!value)
3739 {
3740 cupsdLogMessage(CUPSD_LOG_ERROR, "Missing job ID on line %d!", linenum);
3741 continue;
3742 }
3743
3744 jobid = atoi(value);
3745
3746 if (jobid < 1)
3747 {
3748 cupsdLogMessage(CUPSD_LOG_ERROR, "Bad job ID %d on line %d!", jobid,
3749 linenum);
3750 continue;
3751 }
3752
3753 snprintf(jobfile, sizeof(jobfile), "%s/c%05d", RequestRoot, jobid);
3754 if (access(jobfile, 0))
3755 {
3756 snprintf(jobfile, sizeof(jobfile), "%s/c%05d.N", RequestRoot, jobid);
3757 if (access(jobfile, 0))
3758 {
3759 cupsdLogMessage(CUPSD_LOG_ERROR, "[Job %d] Files have gone away!",
3760 jobid);
3761 continue;
3762 }
3763 }
3764
3765 job = calloc(1, sizeof(cupsd_job_t));
3766 if (!job)
3767 {
3768 cupsdLogMessage(CUPSD_LOG_EMERG,
3769 "[Job %d] Unable to allocate memory for job!", jobid);
3770 break;
3771 }
3772
3773 job->id = jobid;
3774 job->back_pipes[0] = -1;
3775 job->back_pipes[1] = -1;
3776 job->print_pipes[0] = -1;
3777 job->print_pipes[1] = -1;
3778 job->side_pipes[0] = -1;
3779 job->side_pipes[1] = -1;
3780 job->status_pipes[0] = -1;
3781 job->status_pipes[1] = -1;
3782
3783 cupsdLogMessage(CUPSD_LOG_DEBUG, "[Job %d] Loading from cache...",
3784 job->id);
3785 }
3786 else if (!job)
3787 {
3788 cupsdLogMessage(CUPSD_LOG_ERROR,
3789 "Missing <Job #> directive on line %d!", linenum);
3790 continue;
3791 }
3792 else if (!_cups_strcasecmp(line, "</Job>"))
3793 {
3794 cupsArrayAdd(Jobs, job);
3795
3796 if (job->state_value <= IPP_JOB_STOPPED && cupsdLoadJob(job))
3797 cupsArrayAdd(ActiveJobs, job);
3798
3799 job = NULL;
3800 }
3801 else if (!value)
3802 {
3803 cupsdLogMessage(CUPSD_LOG_ERROR, "Missing value on line %d!", linenum);
3804 continue;
3805 }
3806 else if (!_cups_strcasecmp(line, "State"))
3807 {
3808 job->state_value = (ipp_jstate_t)atoi(value);
3809
3810 if (job->state_value < IPP_JOB_PENDING)
3811 job->state_value = IPP_JOB_PENDING;
3812 else if (job->state_value > IPP_JOB_COMPLETED)
3813 job->state_value = IPP_JOB_COMPLETED;
3814 }
3815 else if (!_cups_strcasecmp(line, "HoldUntil"))
3816 {
3817 job->hold_until = atoi(value);
3818 }
3819 else if (!_cups_strcasecmp(line, "Priority"))
3820 {
3821 job->priority = atoi(value);
3822 }
3823 else if (!_cups_strcasecmp(line, "Username"))
3824 {
3825 cupsdSetString(&job->username, value);
3826 }
3827 else if (!_cups_strcasecmp(line, "Destination"))
3828 {
3829 cupsdSetString(&job->dest, value);
3830 }
3831 else if (!_cups_strcasecmp(line, "DestType"))
3832 {
3833 job->dtype = (cups_ptype_t)atoi(value);
3834 }
3835 else if (!_cups_strcasecmp(line, "NumFiles"))
3836 {
3837 job->num_files = atoi(value);
3838
3839 if (job->num_files < 0)
3840 {
3841 cupsdLogMessage(CUPSD_LOG_ERROR, "Bad NumFiles value %d on line %d!",
3842 job->num_files, linenum);
3843 job->num_files = 0;
3844 continue;
3845 }
3846
3847 if (job->num_files > 0)
3848 {
3849 snprintf(jobfile, sizeof(jobfile), "%s/d%05d-001", RequestRoot,
3850 job->id);
3851 if (access(jobfile, 0))
3852 {
3853 cupsdLogMessage(CUPSD_LOG_INFO, "[Job %d] Data files have gone away!",
3854 job->id);
3855 job->num_files = 0;
3856 continue;
3857 }
3858
3859 job->filetypes = calloc(job->num_files, sizeof(mime_type_t *));
3860 job->compressions = calloc(job->num_files, sizeof(int));
3861
3862 if (!job->filetypes || !job->compressions)
3863 {
3864 cupsdLogMessage(CUPSD_LOG_EMERG,
3865 "[Job %d] Unable to allocate memory for %d files!",
3866 job->id, job->num_files);
3867 break;
3868 }
3869 }
3870 }
3871 else if (!_cups_strcasecmp(line, "File"))
3872 {
3873 int number, /* File number */
3874 compression; /* Compression value */
3875 char super[MIME_MAX_SUPER], /* MIME super type */
3876 type[MIME_MAX_TYPE]; /* MIME type */
3877
3878
3879 if (sscanf(value, "%d%*[ \t]%15[^/]/%255s%d", &number, super, type,
3880 &compression) != 4)
3881 {
3882 cupsdLogMessage(CUPSD_LOG_ERROR, "Bad File on line %d!", linenum);
3883 continue;
3884 }
3885
3886 if (number < 1 || number > job->num_files)
3887 {
3888 cupsdLogMessage(CUPSD_LOG_ERROR, "Bad File number %d on line %d!",
3889 number, linenum);
3890 continue;
3891 }
3892
3893 number --;
3894
3895 job->compressions[number] = compression;
3896 job->filetypes[number] = mimeType(MimeDatabase, super, type);
3897
3898 if (!job->filetypes[number])
3899 {
3900 /*
3901 * If the original MIME type is unknown, auto-type it!
3902 */
3903
3904 cupsdLogMessage(CUPSD_LOG_ERROR,
3905 "[Job %d] Unknown MIME type %s/%s for file %d!",
3906 job->id, super, type, number + 1);
3907
3908 snprintf(jobfile, sizeof(jobfile), "%s/d%05d-%03d", RequestRoot,
3909 job->id, number + 1);
3910 job->filetypes[number] = mimeFileType(MimeDatabase, jobfile, NULL,
3911 job->compressions + number);
3912
3913 /*
3914 * If that didn't work, assume it is raw...
3915 */
3916
3917 if (!job->filetypes[number])
3918 job->filetypes[number] = mimeType(MimeDatabase, "application",
3919 "vnd.cups-raw");
3920 }
3921 }
3922 else
3923 cupsdLogMessage(CUPSD_LOG_ERROR, "Unknown %s directive on line %d!",
3924 line, linenum);
3925 }
3926
3927 cupsFileClose(fp);
3928 }
3929
3930
3931 /*
3932 * 'load_next_job_id()' - Load the NextJobId value from the job.cache file.
3933 */
3934
3935 static void
3936 load_next_job_id(const char *filename) /* I - job.cache filename */
3937 {
3938 cups_file_t *fp; /* job.cache file */
3939 char line[1024], /* Line buffer */
3940 *value; /* Value on line */
3941 int linenum; /* Line number in file */
3942 int next_job_id; /* NextJobId value from line */
3943
3944
3945 /*
3946 * Read the NextJobId directive from the job.cache file and use
3947 * the value (if any).
3948 */
3949
3950 if ((fp = cupsFileOpen(filename, "r")) == NULL)
3951 {
3952 if (errno != ENOENT)
3953 cupsdLogMessage(CUPSD_LOG_ERROR,
3954 "Unable to open job cache file \"%s\": %s",
3955 filename, strerror(errno));
3956
3957 return;
3958 }
3959
3960 cupsdLogMessage(CUPSD_LOG_INFO,
3961 "Loading NextJobId from job cache file \"%s\"...", filename);
3962
3963 linenum = 0;
3964
3965 while (cupsFileGetConf(fp, line, sizeof(line), &value, &linenum))
3966 {
3967 if (!_cups_strcasecmp(line, "NextJobId"))
3968 {
3969 if (value)
3970 {
3971 next_job_id = atoi(value);
3972
3973 if (next_job_id > NextJobId)
3974 NextJobId = next_job_id;
3975 }
3976 break;
3977 }
3978 }
3979
3980 cupsFileClose(fp);
3981 }
3982
3983
3984 /*
3985 * 'load_request_root()' - Load jobs from the RequestRoot directory.
3986 */
3987
3988 static void
3989 load_request_root(void)
3990 {
3991 cups_dir_t *dir; /* Directory */
3992 cups_dentry_t *dent; /* Directory entry */
3993 cupsd_job_t *job; /* New job */
3994
3995
3996 /*
3997 * Open the requests directory...
3998 */
3999
4000 cupsdLogMessage(CUPSD_LOG_DEBUG, "Scanning %s for jobs...", RequestRoot);
4001
4002 if ((dir = cupsDirOpen(RequestRoot)) == NULL)
4003 {
4004 cupsdLogMessage(CUPSD_LOG_ERROR,
4005 "Unable to open spool directory \"%s\": %s",
4006 RequestRoot, strerror(errno));
4007 return;
4008 }
4009
4010 /*
4011 * Read all the c##### files...
4012 */
4013
4014 while ((dent = cupsDirRead(dir)) != NULL)
4015 if (strlen(dent->filename) >= 6 && dent->filename[0] == 'c')
4016 {
4017 /*
4018 * Allocate memory for the job...
4019 */
4020
4021 if ((job = calloc(sizeof(cupsd_job_t), 1)) == NULL)
4022 {
4023 cupsdLogMessage(CUPSD_LOG_ERROR, "Ran out of memory for jobs!");
4024 cupsDirClose(dir);
4025 return;
4026 }
4027
4028 /*
4029 * Assign the job ID...
4030 */
4031
4032 job->id = atoi(dent->filename + 1);
4033 job->back_pipes[0] = -1;
4034 job->back_pipes[1] = -1;
4035 job->print_pipes[0] = -1;
4036 job->print_pipes[1] = -1;
4037 job->side_pipes[0] = -1;
4038 job->side_pipes[1] = -1;
4039 job->status_pipes[0] = -1;
4040 job->status_pipes[1] = -1;
4041
4042 if (job->id >= NextJobId)
4043 NextJobId = job->id + 1;
4044
4045 /*
4046 * Load the job...
4047 */
4048
4049 if (cupsdLoadJob(job))
4050 {
4051 /*
4052 * Insert the job into the array, sorting by job priority and ID...
4053 */
4054
4055 cupsArrayAdd(Jobs, job);
4056
4057 if (job->state_value <= IPP_JOB_STOPPED)
4058 cupsArrayAdd(ActiveJobs, job);
4059 else
4060 unload_job(job);
4061 }
4062 }
4063
4064 cupsDirClose(dir);
4065 }
4066
4067
4068 /*
4069 * 'set_time()' - Set one of the "time-at-xyz" attributes.
4070 */
4071
4072 static void
4073 set_time(cupsd_job_t *job, /* I - Job to update */
4074 const char *name) /* I - Name of attribute */
4075 {
4076 ipp_attribute_t *attr; /* Time attribute */
4077
4078
4079 if ((attr = ippFindAttribute(job->attrs, name, IPP_TAG_ZERO)) != NULL)
4080 {
4081 attr->value_tag = IPP_TAG_INTEGER;
4082 attr->values[0].integer = time(NULL);
4083 }
4084 }
4085
4086
4087 /*
4088 * 'start_job()' - Start a print job.
4089 */
4090
4091 static void
4092 start_job(cupsd_job_t *job, /* I - Job ID */
4093 cupsd_printer_t *printer) /* I - Printer to print job */
4094 {
4095 cupsdLogMessage(CUPSD_LOG_DEBUG2, "start_job(job=%p(%d), printer=%p(%s))",
4096 job, job->id, printer, printer->name);
4097
4098 /*
4099 * Make sure we have some files around before we try to print...
4100 */
4101
4102 if (job->num_files == 0)
4103 {
4104 cupsdSetJobState(job, IPP_JOB_ABORTED, CUPSD_JOB_DEFAULT,
4105 "Aborting job because it has no files.");
4106 return;
4107 }
4108
4109 /*
4110 * Update the printer and job state to "processing"...
4111 */
4112
4113 if (!cupsdLoadJob(job))
4114 return;
4115
4116 if (job->printer_message)
4117 cupsdSetString(&(job->printer_message->values[0].string.text), "");
4118
4119 cupsdSetJobState(job, IPP_JOB_PROCESSING, CUPSD_JOB_DEFAULT, NULL);
4120 cupsdSetPrinterState(printer, IPP_PRINTER_PROCESSING, 0);
4121 cupsdSetPrinterReasons(printer, "-cups-remote-pending,"
4122 "cups-remote-pending-held,"
4123 "cups-remote-processing,"
4124 "cups-remote-stopped,"
4125 "cups-remote-canceled,"
4126 "cups-remote-aborted,"
4127 "cups-remote-completed");
4128
4129 job->cost = 0;
4130 job->current_file = 0;
4131 job->progress = 0;
4132 job->printer = printer;
4133 printer->job = job;
4134
4135 /*
4136 * Setup the last exit status and security profiles...
4137 */
4138
4139 job->status = 0;
4140 job->profile = cupsdCreateProfile(job->id);
4141
4142 /*
4143 * Create the status pipes and buffer...
4144 */
4145
4146 if (cupsdOpenPipe(job->status_pipes))
4147 {
4148 cupsdLogJob(job, CUPSD_LOG_DEBUG,
4149 "Unable to create job status pipes - %s.", strerror(errno));
4150
4151 cupsdSetJobState(job, IPP_JOB_STOPPED, CUPSD_JOB_DEFAULT,
4152 "Job stopped because the scheduler could not create the "
4153 "job status pipes.");
4154
4155 cupsdDestroyProfile(job->profile);
4156 job->profile = NULL;
4157 return;
4158 }
4159
4160 job->status_buffer = cupsdStatBufNew(job->status_pipes[0], NULL);
4161 job->status_level = CUPSD_LOG_INFO;
4162
4163 /*
4164 * Create the backchannel pipes and make them non-blocking...
4165 */
4166
4167 if (cupsdOpenPipe(job->back_pipes))
4168 {
4169 cupsdLogJob(job, CUPSD_LOG_DEBUG,
4170 "Unable to create back-channel pipes - %s.", strerror(errno));
4171
4172 cupsdSetJobState(job, IPP_JOB_STOPPED, CUPSD_JOB_DEFAULT,
4173 "Job stopped because the scheduler could not create the "
4174 "back-channel pipes.");
4175
4176 cupsdClosePipe(job->status_pipes);
4177 cupsdStatBufDelete(job->status_buffer);
4178 job->status_buffer = NULL;
4179
4180 cupsdDestroyProfile(job->profile);
4181 job->profile = NULL;
4182 return;
4183 }
4184
4185 fcntl(job->back_pipes[0], F_SETFL,
4186 fcntl(job->back_pipes[0], F_GETFL) | O_NONBLOCK);
4187 fcntl(job->back_pipes[1], F_SETFL,
4188 fcntl(job->back_pipes[1], F_GETFL) | O_NONBLOCK);
4189
4190 /*
4191 * Create the side-channel pipes and make them non-blocking...
4192 */
4193
4194 if (socketpair(AF_LOCAL, SOCK_STREAM, 0, job->side_pipes))
4195 {
4196 cupsdLogJob(job, CUPSD_LOG_DEBUG,
4197 "Unable to create side-channel pipes - %s.", strerror(errno));
4198
4199 cupsdSetJobState(job, IPP_JOB_STOPPED, CUPSD_JOB_DEFAULT,
4200 "Job stopped because the scheduler could not create the "
4201 "side-channel pipes.");
4202
4203 cupsdClosePipe(job->back_pipes);
4204
4205 cupsdClosePipe(job->status_pipes);
4206 cupsdStatBufDelete(job->status_buffer);
4207 job->status_buffer = NULL;
4208
4209 cupsdDestroyProfile(job->profile);
4210 job->profile = NULL;
4211 return;
4212 }
4213
4214 fcntl(job->side_pipes[0], F_SETFL,
4215 fcntl(job->side_pipes[0], F_GETFL) | O_NONBLOCK);
4216 fcntl(job->side_pipes[1], F_SETFL,
4217 fcntl(job->side_pipes[1], F_GETFL) | O_NONBLOCK);
4218
4219 fcntl(job->side_pipes[0], F_SETFD,
4220 fcntl(job->side_pipes[0], F_GETFD) | FD_CLOEXEC);
4221 fcntl(job->side_pipes[1], F_SETFD,
4222 fcntl(job->side_pipes[1], F_GETFD) | FD_CLOEXEC);
4223
4224 /*
4225 * Now start the first file in the job...
4226 */
4227
4228 cupsdContinueJob(job);
4229 }
4230
4231
4232 /*
4233 * 'stop_job()' - Stop a print job.
4234 */
4235
4236 static void
4237 stop_job(cupsd_job_t *job, /* I - Job */
4238 cupsd_jobaction_t action) /* I - Action */
4239 {
4240 int i; /* Looping var */
4241
4242
4243 cupsdLogMessage(CUPSD_LOG_DEBUG2, "stop_job(job=%p(%d), action=%d)", job,
4244 job->id, action);
4245
4246 FilterLevel -= job->cost;
4247 job->cost = 0;
4248
4249 if (action == CUPSD_JOB_DEFAULT && !job->kill_time)
4250 job->kill_time = time(NULL) + JobKillDelay;
4251 else if (action >= CUPSD_JOB_FORCE)
4252 job->kill_time = 0;
4253
4254 for (i = 0; job->filters[i]; i ++)
4255 if (job->filters[i] > 0)
4256 {
4257 cupsdEndProcess(job->filters[i], action >= CUPSD_JOB_FORCE);
4258
4259 if (action >= CUPSD_JOB_FORCE)
4260 job->filters[i] = -job->filters[i];
4261 }
4262
4263 if (job->backend > 0)
4264 {
4265 cupsdEndProcess(job->backend, action >= CUPSD_JOB_FORCE);
4266
4267 if (action >= CUPSD_JOB_FORCE)
4268 job->backend = -job->backend;
4269 }
4270
4271 if (action >= CUPSD_JOB_FORCE)
4272 {
4273 /*
4274 * Clear job status...
4275 */
4276
4277 job->status = 0;
4278 }
4279 }
4280
4281
4282 /*
4283 * 'unload_job()' - Unload a job from memory.
4284 */
4285
4286 static void
4287 unload_job(cupsd_job_t *job) /* I - Job */
4288 {
4289 if (!job->attrs)
4290 return;
4291
4292 cupsdLogMessage(CUPSD_LOG_DEBUG, "[Job %d] Unloading...", job->id);
4293
4294 ippDelete(job->attrs);
4295
4296 job->attrs = NULL;
4297 job->state = NULL;
4298 job->sheets = NULL;
4299 job->job_sheets = NULL;
4300 job->printer_message = NULL;
4301 job->printer_reasons = NULL;
4302 }
4303
4304
4305 /*
4306 * 'update_job()' - Read a status update from a job's filters.
4307 */
4308
4309 void
4310 update_job(cupsd_job_t *job) /* I - Job to check */
4311 {
4312 int i; /* Looping var */
4313 int copies; /* Number of copies printed */
4314 char message[CUPSD_SB_BUFFER_SIZE],
4315 /* Message text */
4316 *ptr; /* Pointer update... */
4317 int loglevel, /* Log level for message */
4318 event = 0; /* Events? */
4319 static const char * const levels[] = /* Log levels */
4320 {
4321 "NONE",
4322 "EMERG",
4323 "ALERT",
4324 "CRIT",
4325 "ERROR",
4326 "WARN",
4327 "NOTICE",
4328 "INFO",
4329 "DEBUG",
4330 "DEBUG2"
4331 };
4332
4333
4334 /*
4335 * Get the printer associated with this job; if the printer is stopped for
4336 * any reason then job->printer will be reset to NULL, so make sure we have
4337 * a valid pointer...
4338 */
4339
4340 while ((ptr = cupsdStatBufUpdate(job->status_buffer, &loglevel,
4341 message, sizeof(message))) != NULL)
4342 {
4343 /*
4344 * Process page and printer state messages as needed...
4345 */
4346
4347 if (loglevel == CUPSD_LOG_PAGE)
4348 {
4349 /*
4350 * Page message; send the message to the page_log file and update the
4351 * job sheet count...
4352 */
4353
4354 cupsdLogJob(job, CUPSD_LOG_DEBUG, "PAGE: %s", message);
4355
4356 if (job->sheets)
4357 {
4358 if (!_cups_strncasecmp(message, "total ", 6))
4359 {
4360 /*
4361 * Got a total count of pages from a backend or filter...
4362 */
4363
4364 copies = atoi(message + 6);
4365 copies -= job->sheets->values[0].integer; /* Just track the delta */
4366 }
4367 else if (!sscanf(message, "%*d%d", &copies))
4368 copies = 1;
4369
4370 job->sheets->values[0].integer += copies;
4371
4372 if (job->printer->page_limit)
4373 cupsdUpdateQuota(job->printer, job->username, copies, 0);
4374 }
4375
4376 cupsdLogPage(job, message);
4377
4378 if (job->sheets)
4379 cupsdAddEvent(CUPSD_EVENT_JOB_PROGRESS, job->printer, job,
4380 "Printed %d page(s).", job->sheets->values[0].integer);
4381 }
4382 else if (loglevel == CUPSD_LOG_STATE)
4383 {
4384 cupsdLogJob(job, CUPSD_LOG_DEBUG, "STATE: %s", message);
4385
4386 if (!strcmp(message, "paused"))
4387 {
4388 cupsdStopPrinter(job->printer, 1);
4389 return;
4390 }
4391 else if (cupsdSetPrinterReasons(job->printer, message))
4392 event |= CUPSD_EVENT_PRINTER_STATE;
4393
4394 update_job_attrs(job, 0);
4395 }
4396 else if (loglevel == CUPSD_LOG_ATTR)
4397 {
4398 /*
4399 * Set attribute(s)...
4400 */
4401
4402 int num_attrs; /* Number of attributes */
4403 cups_option_t *attrs; /* Attributes */
4404 const char *attr; /* Attribute */
4405
4406
4407 cupsdLogJob(job, CUPSD_LOG_DEBUG, "ATTR: %s", message);
4408
4409 num_attrs = cupsParseOptions(message, 0, &attrs);
4410
4411 if ((attr = cupsGetOption("auth-info-required", num_attrs,
4412 attrs)) != NULL)
4413 {
4414 cupsdSetAuthInfoRequired(job->printer, attr, NULL);
4415 cupsdSetPrinterAttrs(job->printer);
4416
4417 if (job->printer->type & CUPS_PRINTER_DISCOVERED)
4418 cupsdMarkDirty(CUPSD_DIRTY_REMOTE);
4419 else
4420 cupsdMarkDirty(CUPSD_DIRTY_PRINTERS);
4421 }
4422
4423 if ((attr = cupsGetOption("job-media-progress", num_attrs,
4424 attrs)) != NULL)
4425 {
4426 int progress = atoi(attr);
4427
4428
4429 if (progress >= 0 && progress <= 100)
4430 {
4431 job->progress = progress;
4432
4433 if (job->sheets)
4434 cupsdAddEvent(CUPSD_EVENT_JOB_PROGRESS, job->printer, job,
4435 "Printing page %d, %d%%",
4436 job->sheets->values[0].integer, job->progress);
4437 }
4438 }
4439
4440 if ((attr = cupsGetOption("printer-alert", num_attrs, attrs)) != NULL)
4441 {
4442 cupsdSetString(&job->printer->alert, attr);
4443 event |= CUPSD_EVENT_PRINTER_STATE;
4444 }
4445
4446 if ((attr = cupsGetOption("printer-alert-description", num_attrs,
4447 attrs)) != NULL)
4448 {
4449 cupsdSetString(&job->printer->alert_description, attr);
4450 event |= CUPSD_EVENT_PRINTER_STATE;
4451 }
4452
4453 if ((attr = cupsGetOption("marker-colors", num_attrs, attrs)) != NULL)
4454 {
4455 cupsdSetPrinterAttr(job->printer, "marker-colors", (char *)attr);
4456 job->printer->marker_time = time(NULL);
4457 event |= CUPSD_EVENT_PRINTER_STATE;
4458 cupsdMarkDirty(CUPSD_DIRTY_PRINTERS);
4459 }
4460
4461 if ((attr = cupsGetOption("marker-levels", num_attrs, attrs)) != NULL)
4462 {
4463 cupsdSetPrinterAttr(job->printer, "marker-levels", (char *)attr);
4464 job->printer->marker_time = time(NULL);
4465 event |= CUPSD_EVENT_PRINTER_STATE;
4466 cupsdMarkDirty(CUPSD_DIRTY_PRINTERS);
4467 }
4468
4469 if ((attr = cupsGetOption("marker-low-levels", num_attrs, attrs)) != NULL)
4470 {
4471 cupsdSetPrinterAttr(job->printer, "marker-low-levels", (char *)attr);
4472 job->printer->marker_time = time(NULL);
4473 event |= CUPSD_EVENT_PRINTER_STATE;
4474 cupsdMarkDirty(CUPSD_DIRTY_PRINTERS);
4475 }
4476
4477 if ((attr = cupsGetOption("marker-high-levels", num_attrs, attrs)) != NULL)
4478 {
4479 cupsdSetPrinterAttr(job->printer, "marker-high-levels", (char *)attr);
4480 job->printer->marker_time = time(NULL);
4481 event |= CUPSD_EVENT_PRINTER_STATE;
4482 cupsdMarkDirty(CUPSD_DIRTY_PRINTERS);
4483 }
4484
4485 if ((attr = cupsGetOption("marker-message", num_attrs, attrs)) != NULL)
4486 {
4487 cupsdSetPrinterAttr(job->printer, "marker-message", (char *)attr);
4488 job->printer->marker_time = time(NULL);
4489 event |= CUPSD_EVENT_PRINTER_STATE;
4490 cupsdMarkDirty(CUPSD_DIRTY_PRINTERS);
4491 }
4492
4493 if ((attr = cupsGetOption("marker-names", num_attrs, attrs)) != NULL)
4494 {
4495 cupsdSetPrinterAttr(job->printer, "marker-names", (char *)attr);
4496 job->printer->marker_time = time(NULL);
4497 event |= CUPSD_EVENT_PRINTER_STATE;
4498 cupsdMarkDirty(CUPSD_DIRTY_PRINTERS);
4499 }
4500
4501 if ((attr = cupsGetOption("marker-types", num_attrs, attrs)) != NULL)
4502 {
4503 cupsdSetPrinterAttr(job->printer, "marker-types", (char *)attr);
4504 job->printer->marker_time = time(NULL);
4505 event |= CUPSD_EVENT_PRINTER_STATE;
4506 cupsdMarkDirty(CUPSD_DIRTY_PRINTERS);
4507 }
4508
4509 cupsFreeOptions(num_attrs, attrs);
4510 }
4511 else if (loglevel == CUPSD_LOG_PPD)
4512 {
4513 /*
4514 * Set attribute(s)...
4515 */
4516
4517 int num_keywords; /* Number of keywords */
4518 cups_option_t *keywords; /* Keywords */
4519
4520
4521 cupsdLogJob(job, CUPSD_LOG_DEBUG, "PPD: %s", message);
4522
4523 num_keywords = cupsParseOptions(message, 0, &keywords);
4524
4525 if (cupsdUpdatePrinterPPD(job->printer, num_keywords, keywords))
4526 cupsdSetPrinterAttrs(job->printer);
4527
4528 cupsFreeOptions(num_keywords, keywords);
4529 }
4530 else
4531 {
4532 /*
4533 * Strip legacy message prefix...
4534 */
4535
4536 if (!strncmp(message, "recoverable:", 12))
4537 {
4538 ptr = message + 12;
4539 while (isspace(*ptr & 255))
4540 ptr ++;
4541 }
4542 else if (!strncmp(message, "recovered:", 10))
4543 {
4544 ptr = message + 10;
4545 while (isspace(*ptr & 255))
4546 ptr ++;
4547 }
4548 else
4549 ptr = message;
4550
4551 cupsdLogJob(job, loglevel, "%s", ptr);
4552
4553 if (loglevel < CUPSD_LOG_DEBUG &&
4554 strcmp(job->printer->state_message, ptr))
4555 {
4556 strlcpy(job->printer->state_message, ptr,
4557 sizeof(job->printer->state_message));
4558
4559 event |= CUPSD_EVENT_PRINTER_STATE | CUPSD_EVENT_JOB_PROGRESS;
4560
4561 if (loglevel <= job->status_level && job->status_level > CUPSD_LOG_ERROR)
4562 {
4563 /*
4564 * Some messages show in the job-printer-state-message attribute...
4565 */
4566
4567 if (loglevel != CUPSD_LOG_NOTICE)
4568 job->status_level = loglevel;
4569
4570 update_job_attrs(job, 1);
4571
4572 cupsdLogJob(job, CUPSD_LOG_DEBUG,
4573 "Set job-printer-state-message to \"%s\", "
4574 "current level=%s",
4575 job->printer_message->values[0].string.text,
4576 levels[job->status_level]);
4577 }
4578 }
4579 }
4580
4581 if (!strchr(job->status_buffer->buffer, '\n'))
4582 break;
4583 }
4584
4585 if (event & CUPSD_EVENT_JOB_PROGRESS)
4586 cupsdAddEvent(CUPSD_EVENT_JOB_PROGRESS, job->printer, job,
4587 "%s", job->printer->state_message);
4588 if (event & CUPSD_EVENT_PRINTER_STATE)
4589 cupsdAddEvent(CUPSD_EVENT_PRINTER_STATE, job->printer, NULL,
4590 (job->printer->type & CUPS_PRINTER_CLASS) ?
4591 "Class \"%s\" state changed." :
4592 "Printer \"%s\" state changed.",
4593 job->printer->name);
4594
4595
4596 if (ptr == NULL && !job->status_buffer->bufused)
4597 {
4598 /*
4599 * See if all of the filters and the backend have returned their
4600 * exit statuses.
4601 */
4602
4603 for (i = 0; job->filters[i] < 0; i ++);
4604
4605 if (job->filters[i])
4606 {
4607 /*
4608 * EOF but we haven't collected the exit status of all filters...
4609 */
4610
4611 cupsdCheckProcess();
4612 return;
4613 }
4614
4615 if (job->current_file >= job->num_files && job->backend > 0)
4616 {
4617 /*
4618 * EOF but we haven't collected the exit status of the backend...
4619 */
4620
4621 cupsdCheckProcess();
4622 return;
4623 }
4624
4625 /*
4626 * Handle the end of job stuff...
4627 */
4628
4629 finalize_job(job, 1);
4630
4631 /*
4632 * Check for new jobs...
4633 */
4634
4635 cupsdCheckJobs();
4636 }
4637 }
4638
4639
4640 /*
4641 * 'update_job_attrs()' - Update the job-printer-* attributes.
4642 */
4643
4644 void
4645 update_job_attrs(cupsd_job_t *job, /* I - Job to update */
4646 int do_message)/* I - 1 = copy job-printer-state message */
4647 {
4648 int i; /* Looping var */
4649 int num_reasons; /* Actual number of reasons */
4650 const char * const *reasons; /* Reasons */
4651 static const char *none = "none"; /* "none" reason */
4652
4653
4654 /*
4655 * Get/create the job-printer-state-* attributes...
4656 */
4657
4658 if (!job->printer_message)
4659 {
4660 if ((job->printer_message = ippFindAttribute(job->attrs,
4661 "job-printer-state-message",
4662 IPP_TAG_TEXT)) == NULL)
4663 job->printer_message = ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_TEXT,
4664 "job-printer-state-message",
4665 NULL, "");
4666 }
4667
4668 if (!job->printer_reasons)
4669 job->printer_reasons = ippFindAttribute(job->attrs,
4670 "job-printer-state-reasons",
4671 IPP_TAG_KEYWORD);
4672
4673 /*
4674 * Copy or clear the printer-state-message value as needed...
4675 */
4676
4677 if (job->state_value != IPP_JOB_PROCESSING &&
4678 job->status_level == CUPSD_LOG_INFO)
4679 cupsdSetString(&(job->printer_message->values[0].string.text), "");
4680 else if (job->printer->state_message[0] && do_message)
4681 cupsdSetString(&(job->printer_message->values[0].string.text),
4682 job->printer->state_message);
4683
4684 /*
4685 * ... and the printer-state-reasons value...
4686 */
4687
4688 if (job->printer->num_reasons == 0)
4689 {
4690 num_reasons = 1;
4691 reasons = &none;
4692 }
4693 else
4694 {
4695 num_reasons = job->printer->num_reasons;
4696 reasons = (const char * const *)job->printer->reasons;
4697 }
4698
4699 if (!job->printer_reasons || job->printer_reasons->num_values != num_reasons)
4700 {
4701 /*
4702 * Replace/create a job-printer-state-reasons attribute...
4703 */
4704
4705 ippDeleteAttribute(job->attrs, job->printer_reasons);
4706
4707 job->printer_reasons = ippAddStrings(job->attrs,
4708 IPP_TAG_JOB, IPP_TAG_KEYWORD,
4709 "job-printer-state-reasons",
4710 num_reasons, NULL, NULL);
4711 }
4712 else
4713 {
4714 /*
4715 * Don't bother clearing the reason strings if they are the same...
4716 */
4717
4718 for (i = 0; i < num_reasons; i ++)
4719 if (strcmp(job->printer_reasons->values[i].string.text, reasons[i]))
4720 break;
4721
4722 if (i >= num_reasons)
4723 return;
4724
4725 /*
4726 * Not the same, so free the current strings...
4727 */
4728
4729 for (i = 0; i < num_reasons; i ++)
4730 _cupsStrFree(job->printer_reasons->values[i].string.text);
4731 }
4732
4733 /*
4734 * Copy the reasons...
4735 */
4736
4737 for (i = 0; i < num_reasons; i ++)
4738 job->printer_reasons->values[i].string.text = _cupsStrAlloc(reasons[i]);
4739 }
4740
4741
4742 /*
4743 * End of "$Id: job.c 7902 2008-09-03 14:20:17Z mike $".
4744 */