]> git.ipfire.org Git - thirdparty/cups.git/blob - scheduler/cupsfilter.c
Update svn:keyword properties.
[thirdparty/cups.git] / scheduler / cupsfilter.c
1 /*
2 * "$Id$"
3 *
4 * Filtering program for CUPS.
5 *
6 * Copyright 2007-2013 by Apple Inc.
7 * Copyright 1997-2006 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 * main() - Main entry for the test program.
18 * add_printer_filter() - Add a single filters from a PPD file.
19 * add_printer_filters() - Add filters from a PPD file.
20 * check_cb() - Callback function for _cupsFileCheck.
21 * compare_pids() - Compare two filter PIDs...
22 * escape_options() - Convert an options array to a string.
23 * exec_filter() - Execute a single filter.
24 * exec_filters() - Execute filters for the given file and options.
25 * get_job_file() - Get the specified job file.
26 * open_pipe() - Create a pipe which is closed on exec.
27 * read_cupsd_conf() - Read the cupsd.conf file to get the filter
28 * settings.
29 * set_string() - Copy and set a string.
30 * sighandler() - Signal catcher for when we print from stdin...
31 * usage() - Show program usage...
32 */
33
34 /*
35 * Include necessary headers...
36 */
37
38 #include <cups/cups-private.h>
39 #include <cups/file-private.h>
40 #include <cups/ppd-private.h>
41 #include "mime.h"
42 #include <limits.h>
43 #include <unistd.h>
44 #include <fcntl.h>
45 #include <signal.h>
46 #include <sys/wait.h>
47 #if defined(__APPLE__)
48 # include <libgen.h>
49 #endif /* __APPLE__ */
50
51
52 /*
53 * Local globals...
54 */
55
56 static char *DataDir = NULL;/* CUPS_DATADIR environment variable */
57 static char *FontPath = NULL;
58 /* CUPS_FONTPATH environment variable */
59 static mime_filter_t GZIPFilter = /* gziptoany filter */
60 {
61 NULL, /* Source type */
62 NULL, /* Destination type */
63 0, /* Cost */
64 "gziptoany" /* Filter program to run */
65 };
66 static char *Path = NULL; /* PATH environment variable */
67 static char *ServerBin = NULL;
68 /* CUPS_SERVERBIN environment variable */
69 static char *ServerRoot = NULL;
70 /* CUPS_SERVERROOT environment variable */
71 static char *RIPCache = NULL;
72 /* RIP_MAX_CACHE environment variable */
73 static char TempFile[1024] = "";
74 /* Temporary file */
75
76
77 /*
78 * Local functions...
79 */
80
81 static void add_printer_filter(const char *command, mime_t *mime,
82 mime_type_t *printer_type,
83 const char *filter);
84 static mime_type_t *add_printer_filters(const char *command,
85 mime_t *mime, const char *printer,
86 const char *ppdfile,
87 mime_type_t **prefilter_type);
88 static void check_cb(void *context, _cups_fc_result_t result,
89 const char *message);
90 static int compare_pids(mime_filter_t *a, mime_filter_t *b);
91 static char *escape_options(int num_options, cups_option_t *options);
92 static int exec_filter(const char *filter, char **argv,
93 char **envp, int infd, int outfd);
94 static int exec_filters(mime_type_t *srctype,
95 cups_array_t *filters, const char *infile,
96 const char *outfile, const char *ppdfile,
97 const char *printer, const char *user,
98 const char *title, int num_options,
99 cups_option_t *options);
100 static void get_job_file(const char *job);
101 static int open_pipe(int *fds);
102 static int read_cupsd_conf(const char *filename);
103 static void set_string(char **s, const char *val);
104 static void sighandler(int sig);
105 static void usage(const char *opt) __attribute__((noreturn));
106
107
108 /*
109 * 'main()' - Main entry for the test program.
110 */
111
112 int /* O - Exit status */
113 main(int argc, /* I - Number of command-line args */
114 char *argv[]) /* I - Command-line arguments */
115 {
116 int i; /* Looping vars */
117 const char *command, /* Command name */
118 *opt, /* Current option */
119 *printer; /* Printer name */
120 mime_type_t *printer_type, /* Printer MIME type */
121 *prefilter_type; /* Printer prefilter MIME type */
122 char *srctype, /* Source type */
123 *dsttype, /* Destination type */
124 super[MIME_MAX_SUPER], /* Super-type name */
125 type[MIME_MAX_TYPE]; /* Type name */
126 int compression; /* Compression of file */
127 int cost; /* Cost of filters */
128 mime_t *mime; /* MIME database */
129 char mimedir[1024]; /* MIME directory */
130 char *infile, /* File to filter */
131 *outfile; /* File to create */
132 char cupsdconf[1024]; /* cupsd.conf file */
133 const char *server_root; /* CUPS_SERVERROOT environment variable */
134 mime_type_t *src, /* Source type */
135 *dst; /* Destination type */
136 cups_array_t *filters; /* Filters for the file */
137 int num_options; /* Number of options */
138 cups_option_t *options; /* Options */
139 const char *ppdfile; /* PPD file */
140 const char *title, /* Title string */
141 *user; /* Username */
142 int all_filters, /* Use all filters */
143 removeppd, /* Remove PPD file */
144 removeinfile; /* Remove input file */
145 int status; /* Execution status */
146
147
148 /*
149 * Setup defaults...
150 */
151
152 if ((command = strrchr(argv[0], '/')) != NULL)
153 command ++;
154 else
155 command = argv[0];
156
157 printer = !strcmp(command, "convert") ? "tofile" : "cupsfilter";
158 mime = NULL;
159 srctype = NULL;
160 compression = 0;
161 dsttype = "application/pdf";
162 infile = NULL;
163 outfile = NULL;
164 num_options = 0;
165 options = NULL;
166 ppdfile = NULL;
167 title = NULL;
168 user = cupsUser();
169 all_filters = 0;
170 removeppd = 0;
171 removeinfile = 0;
172
173 if ((server_root = getenv("CUPS_SERVERROOT")) == NULL)
174 server_root = CUPS_SERVERROOT;
175
176 snprintf(cupsdconf, sizeof(cupsdconf), "%s/cupsd.conf", server_root);
177
178 /*
179 * Process command-line arguments...
180 */
181
182 _cupsSetLocale(argv);
183
184 for (i = 1; i < argc; i ++)
185 if (argv[i][0] == '-')
186 {
187 for (opt = argv[i] + 1; *opt; opt ++)
188 switch (*opt)
189 {
190 case '-' : /* Next argument is a filename... */
191 i ++;
192 if (i < argc && !infile)
193 infile = argv[i];
194 else
195 usage(opt);
196 break;
197
198 case 'a' : /* Specify option... */
199 i ++;
200 if (i < argc)
201 num_options = cupsParseOptions(argv[i], num_options, &options);
202 else
203 usage(opt);
204 break;
205
206 case 'c' : /* Specify cupsd.conf file location... */
207 i ++;
208 if (i < argc)
209 {
210 if (!strcmp(command, "convert"))
211 num_options = cupsAddOption("copies", argv[i], num_options,
212 &options);
213 else
214 strlcpy(cupsdconf, argv[i], sizeof(cupsdconf));
215 }
216 else
217 usage(opt);
218 break;
219
220 case 'd' : /* Specify the real printer name */
221 i ++;
222 if (i < argc)
223 printer = argv[i];
224 else
225 usage(opt);
226 break;
227
228 case 'D' : /* Delete input file after conversion */
229 removeinfile = 1;
230 break;
231
232 case 'e' : /* Use every filter from the PPD file */
233 all_filters = 1;
234 break;
235
236 case 'f' : /* Specify input file... */
237 i ++;
238 if (i < argc && !infile)
239 infile = argv[i];
240 else
241 usage(opt);
242 break;
243
244 case 'i' : /* Specify source MIME type... */
245 i ++;
246 if (i < argc)
247 {
248 if (sscanf(argv[i], "%15[^/]/%255s", super, type) != 2)
249 usage(opt);
250
251 srctype = argv[i];
252 }
253 else
254 usage(opt);
255 break;
256
257 case 'j' : /* Get job file or specify destination MIME type... */
258 if (strcmp(command, "convert"))
259 {
260 i ++;
261 if (i < argc)
262 {
263 get_job_file(argv[i]);
264 infile = TempFile;
265 }
266 else
267 usage(opt);
268
269 break;
270 }
271
272 case 'm' : /* Specify destination MIME type... */
273 i ++;
274 if (i < argc)
275 {
276 if (sscanf(argv[i], "%15[^/]/%255s", super, type) != 2)
277 usage(opt);
278
279 dsttype = argv[i];
280 }
281 else
282 usage(opt);
283 break;
284
285 case 'n' : /* Specify number of copies... */
286 i ++;
287 if (i < argc)
288 num_options = cupsAddOption("copies", argv[i], num_options,
289 &options);
290 else
291 usage(opt);
292 break;
293
294 case 'o' : /* Specify option(s) or output filename */
295 i ++;
296 if (i < argc)
297 {
298 if (!strcmp(command, "convert"))
299 {
300 if (outfile)
301 usage(NULL);
302 else
303 outfile = argv[i];
304 }
305 else
306 num_options = cupsParseOptions(argv[i], num_options,
307 &options);
308 }
309 else
310 usage(opt);
311 break;
312
313 case 'p' : /* Specify PPD file... */
314 case 'P' : /* Specify PPD file... */
315 i ++;
316 if (i < argc)
317 ppdfile = argv[i];
318 else
319 usage(opt);
320 break;
321
322 case 't' : /* Specify title... */
323 case 'J' : /* Specify title... */
324 i ++;
325 if (i < argc)
326 title = argv[i];
327 else
328 usage(opt);
329 break;
330
331 case 'u' : /* Delete PPD file after conversion */
332 removeppd = 1;
333 break;
334
335 case 'U' : /* Specify username... */
336 i ++;
337 if (i < argc)
338 user = argv[i];
339 else
340 usage(opt);
341 break;
342
343 default : /* Something we don't understand... */
344 usage(opt);
345 break;
346 }
347 }
348 else if (!infile)
349 {
350 if (strcmp(command, "convert"))
351 infile = argv[i];
352 else
353 usage(NULL);
354 }
355 else
356 {
357 _cupsLangPuts(stderr,
358 _("cupsfilter: Only one filename can be specified."));
359 usage(NULL);
360 }
361
362 if (!infile && !srctype)
363 usage(NULL);
364
365 if (!title)
366 {
367 if (!infile)
368 title = "(stdin)";
369 else if ((title = strrchr(infile, '/')) != NULL)
370 title ++;
371 else
372 title = infile;
373 }
374
375 /*
376 * Load the cupsd.conf file and create the MIME database...
377 */
378
379 if (read_cupsd_conf(cupsdconf))
380 return (1);
381
382 snprintf(mimedir, sizeof(mimedir), "%s/mime", DataDir);
383
384 mime = mimeLoadTypes(NULL, mimedir);
385 mime = mimeLoadTypes(mime, ServerRoot);
386 mime = mimeLoadFilters(mime, mimedir, Path);
387 mime = mimeLoadFilters(mime, ServerRoot, Path);
388
389 if (!mime)
390 {
391 _cupsLangPrintf(stderr,
392 _("%s: Unable to read MIME database from \"%s\" or "
393 "\"%s\"."),
394 command, mimedir, ServerRoot);
395 return (1);
396 }
397
398 prefilter_type = NULL;
399
400 if (all_filters)
401 printer_type = add_printer_filters(command, mime, printer, ppdfile,
402 &prefilter_type);
403 else
404 printer_type = mimeType(mime, "application", "vnd.cups-postscript");
405
406 /*
407 * Get the source and destination types...
408 */
409
410 if (srctype)
411 {
412 /* sscanf return value already checked above */
413 sscanf(srctype, "%15[^/]/%255s", super, type);
414 if ((src = mimeType(mime, super, type)) == NULL)
415 {
416 _cupsLangPrintf(stderr,
417 _("%s: Unknown source MIME type %s/%s."),
418 command, super, type);
419 return (1);
420 }
421 }
422 else if ((src = mimeFileType(mime, infile, infile, &compression)) == NULL)
423 {
424 _cupsLangPrintf(stderr,
425 _("%s: Unable to determine MIME type of \"%s\"."),
426 command, infile);
427 return (1);
428 }
429
430 /* sscanf return value already checked above */
431 sscanf(dsttype, "%15[^/]/%255s", super, type);
432 if (!_cups_strcasecmp(super, "printer"))
433 dst = printer_type;
434 else if ((dst = mimeType(mime, super, type)) == NULL)
435 {
436 _cupsLangPrintf(stderr,
437 _("%s: Unknown destination MIME type %s/%s."),
438 command, super, type);
439 return (1);
440 }
441
442 /*
443 * Figure out how to filter the file...
444 */
445
446 if (src == dst)
447 {
448 /*
449 * Special case - no filtering needed...
450 */
451
452 filters = cupsArrayNew(NULL, NULL);
453 cupsArrayAdd(filters, &GZIPFilter);
454 GZIPFilter.src = src;
455 GZIPFilter.dst = dst;
456 }
457 else if ((filters = mimeFilter(mime, src, dst, &cost)) == NULL)
458 {
459 _cupsLangPrintf(stderr,
460 _("%s: No filter to convert from %s/%s to %s/%s."),
461 command, src->super, src->type, dst->super, dst->type);
462 return (1);
463 }
464 else if (compression)
465 cupsArrayInsert(filters, &GZIPFilter);
466
467 if (prefilter_type)
468 {
469 /*
470 * Add pre-filters...
471 */
472
473 mime_filter_t *filter, /* Current filter */
474 *prefilter; /* Current pre-filter */
475 cups_array_t *prefilters = cupsArrayNew(NULL, NULL);
476 /* New filters array */
477
478
479 for (filter = (mime_filter_t *)cupsArrayFirst(filters);
480 filter;
481 filter = (mime_filter_t *)cupsArrayNext(filters))
482 {
483 if ((prefilter = mimeFilterLookup(mime, filter->src,
484 prefilter_type)) != NULL)
485 cupsArrayAdd(prefilters, prefilter);
486
487 cupsArrayAdd(prefilters, filter);
488 }
489
490 cupsArrayDelete(filters);
491 filters = prefilters;
492 }
493
494 /*
495 * Do it!
496 */
497
498 status = exec_filters(src, filters, infile, outfile, ppdfile, printer, user,
499 title, num_options, options);
500
501 /*
502 * Remove files as needed, then exit...
503 */
504
505 if (TempFile[0])
506 unlink(TempFile);
507
508 if (removeppd && ppdfile)
509 unlink(ppdfile);
510
511 if (removeinfile && infile)
512 unlink(infile);
513
514 return (status);
515 }
516
517
518 /*
519 * 'add_printer_filter()' - Add a single filters from a PPD file.
520 */
521
522 static void
523 add_printer_filter(
524 const char *command, /* I - Command name */
525 mime_t *mime, /* I - MIME database */
526 mime_type_t *filtertype, /* I - Printer or prefilter MIME type */
527 const char *filter) /* I - Filter to add */
528 {
529 char super[MIME_MAX_SUPER], /* Super-type for filter */
530 type[MIME_MAX_TYPE], /* Type for filter */
531 dsuper[MIME_MAX_SUPER], /* Destination super-type for filter */
532 dtype[MIME_MAX_TYPE], /* Destination type for filter */
533 dest[MIME_MAX_SUPER + MIME_MAX_TYPE + 2],
534 /* Destination super/type */
535 program[1024]; /* Program/filter name */
536 int cost; /* Cost of filter */
537 size_t maxsize = 0; /* Maximum supported file size */
538 mime_type_t *temptype, /* MIME type looping var */
539 *desttype; /* Destination MIME type */
540 mime_filter_t *filterptr; /* MIME filter */
541
542
543 /*
544 * Parse the filter string; it should be in one of the following formats:
545 *
546 * source/type cost program
547 * source/type cost maxsize(nnnn) program
548 * source/type dest/type cost program
549 * source/type dest/type cost maxsize(nnnn) program
550 */
551
552 if (sscanf(filter, "%15[^/]/%255s%*[ \t]%15[^/]/%255s%d%*[ \t]%1023[^\n]",
553 super, type, dsuper, dtype, &cost, program) == 6)
554 {
555 snprintf(dest, sizeof(dest), "%s/%s/%s", filtertype->type, dsuper, dtype);
556
557 if ((desttype = mimeType(mime, "printer", dest)) == NULL)
558 desttype = mimeAddType(mime, "printer", dest);
559 }
560 else
561 {
562 if (sscanf(filter, "%15[^/]/%255s%d%*[ \t]%1023[^\n]", super, type, &cost,
563 program) == 4)
564 {
565 desttype = filtertype;
566 }
567 else
568 {
569 _cupsLangPrintf(stderr, _("%s: Invalid filter string \"%s\"."), command,
570 filter);
571 return;
572 }
573 }
574
575 if (!strncmp(program, "maxsize(", 8))
576 {
577 char *ptr; /* Pointer into maxsize(nnnn) program */
578
579 maxsize = strtoll(program + 8, &ptr, 10);
580
581 if (*ptr != ')')
582 {
583 printf("testmime: Invalid filter string \"%s\".\n", filter);
584 return;
585 }
586
587 ptr ++;
588 while (_cups_isspace(*ptr))
589 ptr ++;
590
591 _cups_strcpy(program, ptr);
592 }
593
594 /*
595 * See if the filter program exists; if not, stop the printer and flag
596 * the error!
597 */
598
599 if (strcmp(program, "-"))
600 {
601 char filename[1024]; /* Full path to program */
602
603 if (program[0] == '/')
604 strlcpy(filename, program, sizeof(filename));
605 else
606 snprintf(filename, sizeof(filename), "%s/filter/%s", ServerBin, program);
607
608 if (_cupsFileCheck(filename, _CUPS_FILE_CHECK_PROGRAM, !geteuid(), check_cb,
609 (void *)command))
610 return;
611 }
612
613 /*
614 * Add the filter to the MIME database, supporting wildcards as needed...
615 */
616
617 for (temptype = mimeFirstType(mime);
618 temptype;
619 temptype = mimeNextType(mime))
620 if (((super[0] == '*' && _cups_strcasecmp(temptype->super, "printer")) ||
621 !_cups_strcasecmp(temptype->super, super)) &&
622 (type[0] == '*' || !_cups_strcasecmp(temptype->type, type)))
623 {
624 if (desttype != filtertype)
625 {
626 filterptr = mimeAddFilter(mime, temptype, desttype, cost, program);
627
628 if (!mimeFilterLookup(mime, desttype, filtertype))
629 mimeAddFilter(mime, desttype, filtertype, 0, "-");
630 }
631 else
632 filterptr = mimeAddFilter(mime, temptype, filtertype, cost, program);
633
634 if (filterptr)
635 filterptr->maxsize = maxsize;
636 }
637 }
638
639
640 /*
641 * 'add_printer_filters()' - Add filters from a PPD file.
642 */
643
644 static mime_type_t * /* O - Printer type or NULL on error */
645 add_printer_filters(
646 const char *command, /* I - Command name */
647 mime_t *mime, /* I - MIME database */
648 const char *printer, /* I - Printer name */
649 const char *ppdfile, /* I - PPD file */
650 mime_type_t **prefilter_type) /* O - Prefilter type */
651 {
652 ppd_file_t *ppd; /* PPD file data */
653 _ppd_cache_t *pc; /* Cache data for PPD */
654 const char *value; /* Filter definition value */
655 mime_type_t *printer_type; /* Printer filter type */
656
657
658 if ((ppd = _ppdOpenFile(ppdfile, _PPD_LOCALIZATION_NONE)) == NULL)
659 {
660 ppd_status_t status; /* PPD load status */
661 int linenum; /* Line number */
662
663 status = ppdLastError(&linenum);
664 _cupsLangPrintf(stderr, _("%s: Unable to open PPD file: %s on line %d."),
665 command, ppdErrorString(status), linenum);
666 return (NULL);
667 }
668
669 pc = _ppdCacheCreateWithPPD(ppd);
670 if (!pc)
671 return (NULL);
672
673 printer_type = mimeAddType(mime, "printer", printer);
674 *prefilter_type = NULL;
675
676 if (pc->filters)
677 {
678 for (value = (const char *)cupsArrayFirst(pc->filters);
679 value;
680 value = (const char *)cupsArrayNext(pc->filters))
681 add_printer_filter(command, mime, printer_type, value);
682 }
683 else
684 {
685 add_printer_filter(command, mime, printer_type,
686 "application/vnd.cups-raw 0 -");
687 add_printer_filter(command, mime, printer_type,
688 "application/vnd.cups-postscript 0 -");
689 }
690
691 if (pc->prefilters)
692 {
693 *prefilter_type = mimeAddType(mime, "prefilter", printer);
694
695 for (value = (const char *)cupsArrayFirst(pc->prefilters);
696 value;
697 value = (const char *)cupsArrayNext(pc->prefilters))
698 add_printer_filter(command, mime, *prefilter_type, value);
699 }
700
701 return (printer_type);
702 }
703
704
705 /*
706 * 'check_cb()' - Callback function for _cupsFileCheck.
707 */
708
709 static void
710 check_cb(void *context, /* I - Context (command name) */
711 _cups_fc_result_t result, /* I - Result of check */
712 const char *message) /* I - Localized message */
713 {
714 (void)result;
715
716 _cupsLangPrintf(stderr, _("%s: %s"), (char *)context, message);
717 }
718
719
720 /*
721 * 'compare_pids()' - Compare two filter PIDs...
722 */
723
724 static int /* O - Result of comparison */
725 compare_pids(mime_filter_t *a, /* I - First filter */
726 mime_filter_t *b) /* I - Second filter */
727 {
728 /*
729 * Because we're particularly lazy, we store the process ID in the "cost"
730 * variable...
731 */
732
733 return (a->cost - b->cost);
734 }
735
736
737 /*
738 * 'escape_options()' - Convert an options array to a string.
739 */
740
741 static char * /* O - Option string */
742 escape_options(
743 int num_options, /* I - Number of options */
744 cups_option_t *options) /* I - Options */
745 {
746 int i; /* Looping var */
747 cups_option_t *option; /* Current option */
748 int bytes; /* Number of bytes needed */
749 char *s, /* Option string */
750 *sptr, /* Pointer into string */
751 *vptr; /* Pointer into value */
752
753
754 /*
755 * Figure out the worst-case number of bytes we need for the option string.
756 */
757
758 for (i = num_options, option = options, bytes = 1; i > 0; i --, option ++)
759 bytes += 2 * (strlen(option->name) + strlen(option->value)) + 2;
760
761 if ((s = malloc(bytes)) == NULL)
762 return (NULL);
763
764 /*
765 * Copy the options to the string...
766 */
767
768 for (i = num_options, option = options, sptr = s; i > 0; i --, option ++)
769 {
770 if (!strcmp(option->name, "copies"))
771 continue;
772
773 if (sptr > s)
774 *sptr++ = ' ';
775
776 strlcpy(sptr, option->name, bytes - (sptr - s));
777 sptr += strlen(sptr);
778 *sptr++ = '=';
779
780 for (vptr = option->value; *vptr;)
781 {
782 if (strchr("\\ \t\n", *vptr))
783 *sptr++ = '\\';
784
785 *sptr++ = *vptr++;
786 }
787 }
788
789 *sptr = '\0';
790
791 return (s);
792 }
793
794
795 /*
796 * 'exec_filter()' - Execute a single filter.
797 */
798
799 static int /* O - Process ID or -1 on error */
800 exec_filter(const char *filter, /* I - Filter to execute */
801 char **argv, /* I - Argument list */
802 char **envp, /* I - Environment list */
803 int infd, /* I - Stdin file descriptor */
804 int outfd) /* I - Stdout file descriptor */
805 {
806 int pid, /* Process ID */
807 fd; /* Temporary file descriptor */
808 #if defined(__APPLE__)
809 char processPath[1024], /* CFProcessPath environment variable */
810 linkpath[1024]; /* Link path for symlinks... */
811 int linkbytes; /* Bytes for link path */
812
813
814 /*
815 * Add special voodoo magic for MacOS X - this allows MacOS X
816 * programs to access their bundle resources properly...
817 */
818
819 if ((linkbytes = readlink(filter, linkpath, sizeof(linkpath) - 1)) > 0)
820 {
821 /*
822 * Yes, this is a symlink to the actual program, nul-terminate and
823 * use it...
824 */
825
826 linkpath[linkbytes] = '\0';
827
828 if (linkpath[0] == '/')
829 snprintf(processPath, sizeof(processPath), "CFProcessPath=%s",
830 linkpath);
831 else
832 snprintf(processPath, sizeof(processPath), "CFProcessPath=%s/%s",
833 dirname((char *)filter), linkpath);
834 }
835 else
836 snprintf(processPath, sizeof(processPath), "CFProcessPath=%s", filter);
837
838 envp[0] = processPath; /* Replace <CFProcessPath> string */
839 #endif /* __APPLE__ */
840
841 if ((pid = fork()) == 0)
842 {
843 /*
844 * Child process goes here...
845 *
846 * Update stdin/stdout/stderr as needed...
847 */
848
849 if (infd != 0)
850 {
851 if (infd < 0)
852 infd = open("/dev/null", O_RDONLY);
853
854 if (infd > 0)
855 {
856 dup2(infd, 0);
857 close(infd);
858 }
859 }
860
861 if (outfd != 1)
862 {
863 if (outfd < 0)
864 outfd = open("/dev/null", O_WRONLY);
865
866 if (outfd > 1)
867 {
868 dup2(outfd, 1);
869 close(outfd);
870 }
871 }
872
873 if ((fd = open("/dev/null", O_RDWR)) > 3)
874 {
875 dup2(fd, 3);
876 close(fd);
877 }
878 fcntl(3, F_SETFL, O_NDELAY);
879
880 if ((fd = open("/dev/null", O_RDWR)) > 4)
881 {
882 dup2(fd, 4);
883 close(fd);
884 }
885 fcntl(4, F_SETFL, O_NDELAY);
886
887 /*
888 * Execute command...
889 */
890
891 execve(filter, argv, envp);
892
893 perror(filter);
894
895 exit(errno);
896 }
897
898 return (pid);
899 }
900
901
902 /*
903 * 'exec_filters()' - Execute filters for the given file and options.
904 */
905
906 static int /* O - 0 on success, 1 on error */
907 exec_filters(mime_type_t *srctype, /* I - Source type */
908 cups_array_t *filters, /* I - Array of filters to run */
909 const char *infile, /* I - File to filter */
910 const char *outfile, /* I - File to create */
911 const char *ppdfile, /* I - PPD file, if any */
912 const char *printer, /* I - Printer name */
913 const char *user, /* I - Username */
914 const char *title, /* I - Job title */
915 int num_options, /* I - Number of filter options */
916 cups_option_t *options) /* I - Filter options */
917 {
918 int i; /* Looping var */
919 const char *argv[8], /* Command-line arguments */
920 *envp[17], /* Environment variables */
921 *temp; /* Temporary string */
922 char *optstr, /* Filter options */
923 content_type[1024], /* CONTENT_TYPE */
924 cups_datadir[1024], /* CUPS_DATADIR */
925 cups_fontpath[1024], /* CUPS_FONTPATH */
926 cups_serverbin[1024], /* CUPS_SERVERBIN */
927 cups_serverroot[1024], /* CUPS_SERVERROOT */
928 final_content_type[1024] = "",
929 /* FINAL_CONTENT_TYPE */
930 lang[1024], /* LANG */
931 path[1024], /* PATH */
932 ppd[1024], /* PPD */
933 printer_info[255], /* PRINTER_INFO env variable */
934 printer_location[255], /* PRINTER_LOCATION env variable */
935 printer_name[255], /* PRINTER env variable */
936 rip_max_cache[1024], /* RIP_MAX_CACHE */
937 userenv[1024], /* USER */
938 program[1024]; /* Program to run */
939 mime_filter_t *filter, /* Current filter */
940 *next; /* Next filter */
941 int current, /* Current filter */
942 filterfds[2][2], /* Pipes for filters */
943 pid, /* Process ID of filter */
944 status, /* Exit status */
945 retval; /* Return value */
946 cups_array_t *pids; /* Executed filters array */
947 mime_filter_t key; /* Search key for filters */
948 cups_lang_t *language; /* Current language */
949 cups_dest_t *dest; /* Destination information */
950
951
952 /*
953 * Figure out the final content type...
954 */
955
956 for (filter = (mime_filter_t *)cupsArrayLast(filters);
957 filter && filter->dst;
958 filter = (mime_filter_t *)cupsArrayPrev(filters))
959 if (strcmp(filter->dst->super, "printer"))
960 break;
961
962 if (filter && filter->dst)
963 {
964 const char *ptr; /* Pointer in type name */
965
966 if ((ptr = strchr(filter->dst->type, '/')) != NULL)
967 snprintf(final_content_type, sizeof(final_content_type),
968 "FINAL_CONTENT_TYPE=%s", ptr + 1);
969 else
970 snprintf(final_content_type, sizeof(final_content_type),
971 "FINAL_CONTENT_TYPE=%s/%s", filter->dst->super,
972 filter->dst->type);
973 }
974
975 /*
976 * Remove NULL ("-") filters...
977 */
978
979 for (filter = (mime_filter_t *)cupsArrayFirst(filters);
980 filter;
981 filter = (mime_filter_t *)cupsArrayNext(filters))
982 if (!strcmp(filter->filter, "-"))
983 cupsArrayRemove(filters, filter);
984
985 /*
986 * Setup the filter environment and command-line...
987 */
988
989 optstr = escape_options(num_options, options);
990
991 snprintf(content_type, sizeof(content_type), "CONTENT_TYPE=%s/%s",
992 srctype->super, srctype->type);
993 snprintf(cups_datadir, sizeof(cups_datadir), "CUPS_DATADIR=%s", DataDir);
994 snprintf(cups_fontpath, sizeof(cups_fontpath), "CUPS_FONTPATH=%s", FontPath);
995 snprintf(cups_serverbin, sizeof(cups_serverbin), "CUPS_SERVERBIN=%s",
996 ServerBin);
997 snprintf(cups_serverroot, sizeof(cups_serverroot), "CUPS_SERVERROOT=%s",
998 ServerRoot);
999 language = cupsLangDefault();
1000 snprintf(lang, sizeof(lang), "LANG=%s.UTF8", language->language);
1001 snprintf(path, sizeof(path), "PATH=%s", Path);
1002 if (ppdfile)
1003 snprintf(ppd, sizeof(ppd), "PPD=%s", ppdfile);
1004 else if ((temp = getenv("PPD")) != NULL)
1005 snprintf(ppd, sizeof(ppd), "PPD=%s", temp);
1006 else
1007 #ifdef __APPLE__
1008 if (!access("/System/Library/Frameworks/ApplicationServices.framework/"
1009 "Versions/A/Frameworks/PrintCore.framework/Versions/A/"
1010 "Resources/English.lproj/Generic.ppd", 0))
1011 strlcpy(ppd, "PPD=/System/Library/Frameworks/ApplicationServices.framework/"
1012 "Versions/A/Frameworks/PrintCore.framework/Versions/A/"
1013 "Resources/English.lproj/Generic.ppd", sizeof(ppd));
1014 else
1015 strlcpy(ppd, "PPD=/System/Library/Frameworks/ApplicationServices.framework/"
1016 "Versions/A/Frameworks/PrintCore.framework/Versions/A/"
1017 "Resources/Generic.ppd", sizeof(ppd));
1018 #else
1019 snprintf(ppd, sizeof(ppd), "PPD=%s/model/laserjet.ppd", DataDir);
1020 #endif /* __APPLE__ */
1021 snprintf(rip_max_cache, sizeof(rip_max_cache), "RIP_MAX_CACHE=%s", RIPCache);
1022 snprintf(userenv, sizeof(userenv), "USER=%s", user);
1023
1024 if (printer &&
1025 (dest = cupsGetNamedDest(CUPS_HTTP_DEFAULT, printer, NULL)) != NULL)
1026 {
1027 if ((temp = cupsGetOption("printer-info", dest->num_options,
1028 dest->options)) != NULL)
1029 snprintf(printer_info, sizeof(printer_info), "PRINTER_INFO=%s", temp);
1030 else
1031 snprintf(printer_info, sizeof(printer_info), "PRINTER_INFO=%s", printer);
1032
1033 if ((temp = cupsGetOption("printer-location", dest->num_options,
1034 dest->options)) != NULL)
1035 snprintf(printer_location, sizeof(printer_location),
1036 "PRINTER_LOCATION=%s", temp);
1037 else
1038 strlcpy(printer_location, "PRINTER_LOCATION=Unknown",
1039 sizeof(printer_location));
1040 }
1041 else
1042 {
1043 snprintf(printer_info, sizeof(printer_info), "PRINTER_INFO=%s",
1044 printer ? printer : "Unknown");
1045 strlcpy(printer_location, "PRINTER_LOCATION=Unknown",
1046 sizeof(printer_location));
1047 }
1048
1049 snprintf(printer_name, sizeof(printer_name), "PRINTER=%s",
1050 printer ? printer : "Unknown");
1051
1052 argv[0] = (char *)printer;
1053 argv[1] = "1";
1054 argv[2] = user;
1055 argv[3] = title;
1056 argv[4] = cupsGetOption("copies", num_options, options);
1057 argv[5] = optstr;
1058 argv[6] = infile;
1059 argv[7] = NULL;
1060
1061 if (!argv[4])
1062 argv[4] = "1";
1063
1064 envp[0] = "<CFProcessPath>";
1065 envp[1] = content_type;
1066 envp[2] = cups_datadir;
1067 envp[3] = cups_fontpath;
1068 envp[4] = cups_serverbin;
1069 envp[5] = cups_serverroot;
1070 envp[6] = lang;
1071 envp[7] = path;
1072 envp[8] = ppd;
1073 envp[9] = printer_info;
1074 envp[10] = printer_location;
1075 envp[11] = printer_name;
1076 envp[12] = rip_max_cache;
1077 envp[13] = userenv;
1078 envp[14] = "CHARSET=utf-8";
1079 if (final_content_type[0])
1080 {
1081 envp[15] = final_content_type;
1082 envp[16] = NULL;
1083 }
1084 else
1085 envp[15] = NULL;
1086
1087 for (i = 0; argv[i]; i ++)
1088 fprintf(stderr, "DEBUG: argv[%d]=\"%s\"\n", i, argv[i]);
1089
1090 for (i = 0; envp[i]; i ++)
1091 fprintf(stderr, "DEBUG: envp[%d]=\"%s\"\n", i, envp[i]);
1092
1093 /*
1094 * Execute all of the filters...
1095 */
1096
1097 pids = cupsArrayNew((cups_array_func_t)compare_pids, NULL);
1098 current = 0;
1099 filterfds[0][0] = -1;
1100 filterfds[0][1] = -1;
1101 filterfds[1][0] = -1;
1102 filterfds[1][1] = -1;
1103
1104 if (!infile)
1105 filterfds[0][0] = 0;
1106
1107 for (filter = (mime_filter_t *)cupsArrayFirst(filters);
1108 filter;
1109 filter = next, current = 1 - current)
1110 {
1111 next = (mime_filter_t *)cupsArrayNext(filters);
1112
1113 if (filter->filter[0] == '/')
1114 strlcpy(program, filter->filter, sizeof(program));
1115 else
1116 snprintf(program, sizeof(program), "%s/filter/%s", ServerBin,
1117 filter->filter);
1118
1119 if (filterfds[!current][1] > 1)
1120 {
1121 close(filterfds[1 - current][0]);
1122 close(filterfds[1 - current][1]);
1123
1124 filterfds[1 - current][0] = -1;
1125 filterfds[1 - current][0] = -1;
1126 }
1127
1128 if (next)
1129 open_pipe(filterfds[1 - current]);
1130 else if (outfile)
1131 {
1132 filterfds[1 - current][1] = open(outfile, O_CREAT | O_TRUNC | O_WRONLY,
1133 0666);
1134
1135 if (filterfds[1 - current][1] < 0)
1136 fprintf(stderr, "ERROR: Unable to create \"%s\" - %s\n", outfile,
1137 strerror(errno));
1138 }
1139 else
1140 filterfds[1 - current][1] = 1;
1141
1142 pid = exec_filter(program, (char **)argv, (char **)envp,
1143 filterfds[current][0], filterfds[1 - current][1]);
1144
1145 if (pid > 0)
1146 {
1147 fprintf(stderr, "INFO: %s (PID %d) started.\n", filter->filter, pid);
1148
1149 filter->cost = pid;
1150 cupsArrayAdd(pids, filter);
1151 }
1152 else
1153 break;
1154
1155 argv[6] = NULL;
1156 }
1157
1158 /*
1159 * Close remaining pipes...
1160 */
1161
1162 if (filterfds[0][1] > 1)
1163 {
1164 close(filterfds[0][0]);
1165 close(filterfds[0][1]);
1166 }
1167
1168 if (filterfds[1][1] > 1)
1169 {
1170 close(filterfds[1][0]);
1171 close(filterfds[1][1]);
1172 }
1173
1174 /*
1175 * Wait for the children to exit...
1176 */
1177
1178 retval = 0;
1179
1180 while (cupsArrayCount(pids) > 0)
1181 {
1182 if ((pid = wait(&status)) < 0)
1183 continue;
1184
1185 key.cost = pid;
1186 if ((filter = (mime_filter_t *)cupsArrayFind(pids, &key)) != NULL)
1187 {
1188 cupsArrayRemove(pids, filter);
1189
1190 if (status)
1191 {
1192 if (WIFEXITED(status))
1193 fprintf(stderr, "ERROR: %s (PID %d) stopped with status %d\n",
1194 filter->filter, pid, WEXITSTATUS(status));
1195 else
1196 fprintf(stderr, "ERROR: %s (PID %d) crashed on signal %d\n",
1197 filter->filter, pid, WTERMSIG(status));
1198
1199 retval = 1;
1200 }
1201 else
1202 fprintf(stderr, "INFO: %s (PID %d) exited with no errors.\n",
1203 filter->filter, pid);
1204 }
1205 }
1206
1207 cupsArrayDelete(pids);
1208
1209 return (retval);
1210 }
1211
1212
1213 /*
1214 * 'get_job_file()' - Get the specified job file.
1215 */
1216
1217 static void
1218 get_job_file(const char *job) /* I - Job ID */
1219 {
1220 long jobid, /* Job ID */
1221 docnum; /* Document number */
1222 const char *jobptr; /* Pointer into job ID string */
1223 char uri[1024]; /* job-uri */
1224 http_t *http; /* Connection to server */
1225 ipp_t *request; /* Request data */
1226 int tempfd; /* Temporary file */
1227
1228
1229 /*
1230 * Get the job ID and document number, if any...
1231 */
1232
1233 if ((jobptr = strrchr(job, '-')) != NULL)
1234 jobptr ++;
1235 else
1236 jobptr = job;
1237
1238 jobid = strtol(jobptr, (char **)&jobptr, 10);
1239
1240 if (*jobptr == ',')
1241 docnum = strtol(jobptr + 1, NULL, 10);
1242 else
1243 docnum = 1;
1244
1245 if (jobid < 1 || jobid > INT_MAX)
1246 {
1247 _cupsLangPrintf(stderr, _("cupsfilter: Invalid job ID %d."), (int)jobid);
1248 exit(1);
1249 }
1250
1251 if (docnum < 1 || docnum > INT_MAX)
1252 {
1253 _cupsLangPrintf(stderr, _("cupsfilter: Invalid document number %d."),
1254 (int)docnum);
1255 exit(1);
1256 }
1257
1258 /*
1259 * Ask the server for the document file...
1260 */
1261
1262 if ((http = httpConnectEncrypt(cupsServer(), ippPort(),
1263 cupsEncryption())) == NULL)
1264 {
1265 _cupsLangPrintf(stderr, _("%s: Unable to connect to server."),
1266 "cupsfilter");
1267 exit(1);
1268 }
1269
1270 request = ippNewRequest(CUPS_GET_DOCUMENT);
1271
1272 snprintf(uri, sizeof(uri), "ipp://localhost/jobs/%d", (int)jobid);
1273
1274 ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "job-uri", NULL, uri);
1275 ippAddInteger(request, IPP_TAG_OPERATION, IPP_TAG_INTEGER, "document-number",
1276 (int)docnum);
1277
1278 if ((tempfd = cupsTempFd(TempFile, sizeof(TempFile))) == -1)
1279 {
1280 _cupsLangPrintError("ERROR", _("Unable to create temporary file"));
1281 httpClose(http);
1282 exit(1);
1283 }
1284
1285 signal(SIGTERM, sighandler);
1286
1287 ippDelete(cupsDoIORequest(http, request, "/", -1, tempfd));
1288
1289 close(tempfd);
1290
1291 httpClose(http);
1292
1293 if (cupsLastError() != IPP_OK)
1294 {
1295 _cupsLangPrintf(stderr, _("cupsfilter: Unable to get job file - %s"),
1296 cupsLastErrorString());
1297 unlink(TempFile);
1298 exit(1);
1299 }
1300 }
1301
1302
1303 /*
1304 * 'open_pipe()' - Create a pipe which is closed on exec.
1305 */
1306
1307 static int /* O - 0 on success, -1 on error */
1308 open_pipe(int *fds) /* O - Pipe file descriptors (2) */
1309 {
1310 /*
1311 * Create the pipe...
1312 */
1313
1314 if (pipe(fds))
1315 {
1316 fds[0] = -1;
1317 fds[1] = -1;
1318
1319 return (-1);
1320 }
1321
1322 /*
1323 * Set the "close on exec" flag on each end of the pipe...
1324 */
1325
1326 if (fcntl(fds[0], F_SETFD, fcntl(fds[0], F_GETFD) | FD_CLOEXEC))
1327 {
1328 close(fds[0]);
1329 close(fds[1]);
1330
1331 fds[0] = -1;
1332 fds[1] = -1;
1333
1334 return (-1);
1335 }
1336
1337 if (fcntl(fds[1], F_SETFD, fcntl(fds[1], F_GETFD) | FD_CLOEXEC))
1338 {
1339 close(fds[0]);
1340 close(fds[1]);
1341
1342 fds[0] = -1;
1343 fds[1] = -1;
1344
1345 return (-1);
1346 }
1347
1348 /*
1349 * Return 0 indicating success...
1350 */
1351
1352 return (0);
1353 }
1354
1355
1356 /*
1357 * 'read_cupsd_conf()' - Read the cupsd.conf file to get the filter settings.
1358 */
1359
1360 static int /* O - 0 on success, 1 on error */
1361 read_cupsd_conf(const char *filename) /* I - File to read */
1362 {
1363 cups_file_t *fp; /* cupsd.conf file */
1364 const char *temp; /* Temporary string */
1365 char line[1024], /* Line from file */
1366 *ptr; /* Pointer into line */
1367 int linenum; /* Current line number */
1368
1369
1370 if ((temp = getenv("CUPS_DATADIR")) != NULL)
1371 set_string(&DataDir, temp);
1372 else
1373 set_string(&DataDir, CUPS_DATADIR);
1374
1375 if ((temp = getenv("CUPS_FONTPATH")) != NULL)
1376 set_string(&FontPath, temp);
1377 else
1378 set_string(&FontPath, CUPS_FONTPATH);
1379
1380 set_string(&RIPCache, "128m");
1381
1382 if ((temp = getenv("CUPS_SERVERBIN")) != NULL)
1383 set_string(&ServerBin, temp);
1384 else
1385 set_string(&ServerBin, CUPS_SERVERBIN);
1386
1387 strlcpy(line, filename, sizeof(line));
1388 if ((ptr = strrchr(line, '/')) != NULL)
1389 *ptr = '\0';
1390 else
1391 getcwd(line, sizeof(line));
1392
1393 set_string(&ServerRoot, line);
1394
1395 if ((fp = cupsFileOpen(filename, "r")) != NULL)
1396 {
1397 linenum = 0;
1398
1399 while (cupsFileGetConf(fp, line, sizeof(line), &ptr, &linenum))
1400 {
1401 if (!_cups_strcasecmp(line, "DataDir"))
1402 set_string(&DataDir, ptr);
1403 else if (!_cups_strcasecmp(line, "FontPath"))
1404 set_string(&FontPath, ptr);
1405 else if (!_cups_strcasecmp(line, "RIPCache"))
1406 set_string(&RIPCache, ptr);
1407 else if (!_cups_strcasecmp(line, "ServerBin"))
1408 set_string(&ServerBin, ptr);
1409 else if (!_cups_strcasecmp(line, "ServerRoot"))
1410 set_string(&ServerRoot, ptr);
1411 }
1412
1413 cupsFileClose(fp);
1414 }
1415
1416 snprintf(line, sizeof(line),
1417 "%s/filter:" CUPS_BINDIR ":" CUPS_SBINDIR ":/bin:/usr/bin",
1418 ServerBin);
1419 set_string(&Path, line);
1420
1421 return (0);
1422 }
1423
1424
1425 /*
1426 * 'set_string()' - Copy and set a string.
1427 */
1428
1429 static void
1430 set_string(char **s, /* O - Copy of string */
1431 const char *val) /* I - String to copy */
1432 {
1433 if (*s)
1434 free(*s);
1435
1436 *s = strdup(val);
1437 }
1438
1439
1440 /*
1441 * 'sighandler()' - Signal catcher for when we print from stdin...
1442 */
1443
1444 static void
1445 sighandler(int s) /* I - Signal number */
1446 {
1447 /*
1448 * Remove the temporary file we're using to print a job file...
1449 */
1450
1451 if (TempFile[0])
1452 unlink(TempFile);
1453
1454 /*
1455 * Exit...
1456 */
1457
1458 exit(s);
1459 }
1460
1461
1462 /*
1463 * 'usage()' - Show program usage...
1464 */
1465
1466 static void
1467 usage(const char *opt) /* I - Incorrect option, if any */
1468 {
1469 if (opt)
1470 _cupsLangPrintf(stderr, _("%s: Unknown option \"%c\"."), "cupsfilter",
1471 *opt);
1472
1473 _cupsLangPuts(stdout, _("Usage: cupsfilter [ options ] filename"));
1474 _cupsLangPuts(stdout, _("Options:"));
1475 _cupsLangPuts(stdout, _(" -D Remove the input file "
1476 "when finished."));
1477 _cupsLangPuts(stdout, _(" -P filename.ppd Set PPD file."));
1478 _cupsLangPuts(stdout, _(" -U username Specify username."));
1479 _cupsLangPuts(stdout, _(" -c cupsd.conf Set cupsd.conf file to "
1480 "use."));
1481 _cupsLangPuts(stdout, _(" -d printer Use the named "
1482 "printer."));
1483 _cupsLangPuts(stdout, _(" -e Use every filter from "
1484 "the PPD file."));
1485 _cupsLangPuts(stdout, _(" -i mime/type Set input MIME type "
1486 "(otherwise auto-typed)."));
1487 _cupsLangPuts(stdout, _(" -j job-id[,N] Filter file N from the "
1488 "specified job (default is file 1)."));
1489 _cupsLangPuts(stdout, _(" -m mime/type Set output MIME type "
1490 "(otherwise application/pdf)."));
1491 _cupsLangPuts(stdout, _(" -n copies Set number of copies."));
1492 _cupsLangPuts(stdout, _(" -o name=value Set option(s)."));
1493 _cupsLangPuts(stdout, _(" -p filename.ppd Set PPD file."));
1494 _cupsLangPuts(stdout, _(" -t title Set title."));
1495 _cupsLangPuts(stdout, _(" -u Remove the PPD file "
1496 "when finished."));
1497
1498 exit(1);
1499 }
1500
1501
1502 /*
1503 * End of "$Id$".
1504 */