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