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