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