File: gstoraster.c

package info (click to toggle)
cups-filters 1.28.17-3%2Bdeb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 6,096 kB
  • sloc: ansic: 54,489; cpp: 7,023; sh: 1,911; makefile: 963; xml: 127; perl: 73; php: 28; python: 8
file content (1047 lines) | stat: -rw-r--r-- 32,937 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
/*

Copyright (c) 2008-2016, Till Kamppeter
Copyright (c) 2011, Tim Waugh
Copyright (c) 2011-2013, Richard Hughes

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

MIT Open Source License  -  http://www.opensource.org/

*/


/* PS/PDF to CUPS Raster filter based on Ghostscript */

#include <config.h>
#include <cups/cups.h>
#if (CUPS_VERSION_MAJOR > 1) || (CUPS_VERSION_MINOR > 6)
#define HAVE_CUPS_1_7 1
#endif

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <fcntl.h>
#include <cups/raster.h>
#include <cupsfilters/colormanager.h>
#include <cupsfilters/raster.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <errno.h>
#include "pdf.h"

#define PDF_MAX_CHECK_COMMENT_LINES	20

typedef enum {
  GS_DOC_TYPE_PDF,
  GS_DOC_TYPE_PS,
  GS_DOC_TYPE_UNKNOWN
} GsDocType;

typedef enum {
  OUTPUT_FORMAT_RASTER,
  OUTPUT_FORMAT_PDF,
  OUTPUT_FORMAT_PXL
} OutFormatType;

#ifdef CUPS_RASTER_SYNCv1
typedef cups_page_header2_t gs_page_header;
#else
typedef cups_page_header_t gs_page_header;
#endif /* CUPS_RASTER_SYNCv1 */

static GsDocType
parse_doc_type(FILE *fp)
{
  char buf[5];

  /* get the first few bytes of the file */
  rewind(fp);
/* skip until PDF/PS start header */
 while (fgets(buf,sizeof(buf),fp) != 0) {
   if (strncmp(buf,"%PDF",4) == 0) return GS_DOC_TYPE_PDF;
   if (strncmp(buf,"%!",2) == 0) return GS_DOC_TYPE_PS;
  }
  return GS_DOC_TYPE_UNKNOWN;
}

static void
parse_pdf_header_options(FILE *fp, gs_page_header *h)
{
  char buf[4096];
  int i;

  rewind(fp);
  /* skip until PDF start header */
  while (fgets(buf,sizeof(buf),fp) != 0) {
    if (strncmp(buf,"%PDF",4) == 0) {
      break;
    }
  }
  for (i = 0;i < PDF_MAX_CHECK_COMMENT_LINES;i++) {
    if (fgets(buf,sizeof(buf),fp) == 0) break;
    if (strncmp(buf,"%%PDFTOPDFNumCopies",19) == 0) {
      char *p;

      p = strchr(buf+19,':');
      h->NumCopies = atoi(p+1);
    } else if (strncmp(buf,"%%PDFTOPDFCollate",17) == 0) {
      char *p;

      p = strchr(buf+17,':');
      while (*p == ' ' || *p == '\t') p++;
      if (strncasecmp(p,"true",4) == 0) {
        h->Collate = CUPS_TRUE;
      } else {
        h->Collate = CUPS_FALSE;
      }
    }
  }
}

static void
add_pdf_header_options(gs_page_header *h, cups_array_t *gs_args,
		       OutFormatType outformat, int pxlcolor)
{
  int i;
  char tmpstr[1024];

  /* Simple boolean, enumerated choice, numerical, and string parameters */
  if (outformat == OUTPUT_FORMAT_RASTER) {
    if (h->MediaClass[0] |= '\0') {
      snprintf(tmpstr, sizeof(tmpstr), "-sMediaClass=%s", h->MediaClass);
      cupsArrayAdd(gs_args, strdup(tmpstr));
    }
    if (h->MediaColor[0] |= '\0') {
      snprintf(tmpstr, sizeof(tmpstr), "-sMediaColor=%s", h->MediaColor);
      cupsArrayAdd(gs_args, strdup(tmpstr));
    }
    if (h->MediaType[0] |= '\0') {
      snprintf(tmpstr, sizeof(tmpstr), "-sMediaType=%s", h->MediaType);
      cupsArrayAdd(gs_args, strdup(tmpstr));
    }
    if (h->OutputType[0] |= '\0') {
      snprintf(tmpstr, sizeof(tmpstr), "-sOutputType=%s", h->OutputType);
      cupsArrayAdd(gs_args, strdup(tmpstr));
    }
    if (h->AdvanceDistance) {
      snprintf(tmpstr, sizeof(tmpstr), "-dAdvanceDistance=%d",
	       (unsigned)(h->AdvanceDistance));
      cupsArrayAdd(gs_args, strdup(tmpstr));
    }
    if (h->AdvanceMedia) {
      snprintf(tmpstr, sizeof(tmpstr), "-dAdvanceMedia=%d",
	       (unsigned)(h->AdvanceMedia));
      cupsArrayAdd(gs_args, strdup(tmpstr));
    }
    if (h->Collate) {
      cupsArrayAdd(gs_args, strdup("-dCollate"));
    }
    if (h->CutMedia) {
      snprintf(tmpstr, sizeof(tmpstr), "-dCutMedia=%d",
	       (unsigned)(h->CutMedia));
      cupsArrayAdd(gs_args, strdup(tmpstr));
    }
  }
  if (outformat == OUTPUT_FORMAT_RASTER ||
      outformat == OUTPUT_FORMAT_PXL) {
    /* PDF output is only for turning PostScript input data into PDF
       not for sending PDF to a PDF printer (this is done by pdftopdf)
       therefore we do not apply duplex/tumble here. */
    if (h->Duplex) {
      cupsArrayAdd(gs_args, strdup("-dDuplex"));
    }
  }
  snprintf(tmpstr, sizeof(tmpstr), "-r%dx%d",h->HWResolution[0], h->HWResolution[1]);
  cupsArrayAdd(gs_args, strdup(tmpstr));
  if (outformat == OUTPUT_FORMAT_RASTER) {
    if (h->InsertSheet) {
      cupsArrayAdd(gs_args, strdup("-dInsertSheet"));
    }
    if (h->Jog) {
      snprintf(tmpstr, sizeof(tmpstr), "-dJog=%d",
	       (unsigned)(h->Jog));
      cupsArrayAdd(gs_args, strdup(tmpstr));
    }
    if (h->LeadingEdge) {
      snprintf(tmpstr, sizeof(tmpstr), "-dLeadingEdge=%d",
	       (unsigned)(h->LeadingEdge));
      cupsArrayAdd(gs_args, strdup(tmpstr));
    }
    if (h->ManualFeed) {
      cupsArrayAdd(gs_args, strdup("-dManualFeed"));
    }
  }
  if (outformat == OUTPUT_FORMAT_RASTER ||
      outformat == OUTPUT_FORMAT_PXL) {
    if (h->MediaPosition) {
      int mediapos;
      if (outformat == OUTPUT_FORMAT_PXL) {
	/* Convert PWG MediaPosition values to PXL-ones */
	if (h->MediaPosition == 1) /* Main */
	  mediapos = 4;
	else if (h->MediaPosition == 2) /* Alternate */
	  mediapos = 5;
	else if (h->MediaPosition == 3) /* Large Capacity */
	  mediapos = 7;
	else if (h->MediaPosition == 4) /* Manual */
	  mediapos = 2;
	else if (h->MediaPosition == 5) /* Envelope */
	  mediapos = 6;
	else if (h->MediaPosition == 11) /* Top */
	  mediapos = 4;
	else if (h->MediaPosition == 12) /* Middle */
	  mediapos = 5;
	else if (h->MediaPosition == 13) /* Bottom */
	  mediapos = 7;
	else if (h->MediaPosition == 19) /* Bypass */
	  mediapos = 3;
	else if (h->MediaPosition == 20) /* Tray 1 */
	  mediapos = 3;
	else if (h->MediaPosition == 21) /* Tray 2 */
	  mediapos = 4;
	else if (h->MediaPosition == 22) /* Tray 3 */
	  mediapos = 5;
	else if (h->MediaPosition == 23) /* Tray 4 */
	  mediapos = 7;
	else
	  mediapos = 0;
      } else
	mediapos = h->MediaPosition;
      snprintf(tmpstr, sizeof(tmpstr), "-dMediaPosition=%d",
	       (unsigned)(mediapos));
      cupsArrayAdd(gs_args, strdup(tmpstr));
    }
  }
  if (outformat == OUTPUT_FORMAT_RASTER) {
    if (h->MediaWeight) {
      snprintf(tmpstr, sizeof(tmpstr), "-dMediaWeight=%d",
	       (unsigned)(h->MediaWeight));
      cupsArrayAdd(gs_args, strdup(tmpstr));
    }
    if (h->MirrorPrint) {
      cupsArrayAdd(gs_args, strdup("-dMirrorPrint"));
    }
    if (h->NegativePrint) {
      cupsArrayAdd(gs_args, strdup("-dNegativePrint"));
    }
    if (h->NumCopies != 1) {
      snprintf(tmpstr, sizeof(tmpstr), "-dNumCopies=%d",
	       (unsigned)(h->NumCopies));
      cupsArrayAdd(gs_args, strdup(tmpstr));
    }
    if (h->Orientation) {
      snprintf(tmpstr, sizeof(tmpstr), "-dOrientation=%d",
	       (unsigned)(h->Orientation));
      cupsArrayAdd(gs_args, strdup(tmpstr));
    }
    if (h->OutputFaceUp) {
      cupsArrayAdd(gs_args, strdup("-dOutputFaceUp"));
    }
  }
  snprintf(tmpstr, sizeof(tmpstr), "-dDEVICEWIDTHPOINTS=%d",h->PageSize[0]);
  cupsArrayAdd(gs_args, strdup(tmpstr));
  snprintf(tmpstr, sizeof(tmpstr), "-dDEVICEHEIGHTPOINTS=%d",h->PageSize[1]);
  cupsArrayAdd(gs_args, strdup(tmpstr));
  if (outformat == OUTPUT_FORMAT_RASTER) {
    if (h->Separations) {
      cupsArrayAdd(gs_args, strdup("-dSeparations"));
    }
    if (h->TraySwitch) {
      cupsArrayAdd(gs_args, strdup("-dTraySwitch"));
    }
  }
  if (outformat == OUTPUT_FORMAT_RASTER ||
      outformat == OUTPUT_FORMAT_PXL) {
    /* PDF output is only for turning PostScript input data into PDF
       not for sending PDF to a PDF printer (this is done by pdftopdf)
       therefore we do not apply duplex/tumble here. */
    if (h->Tumble) {
      cupsArrayAdd(gs_args, strdup("-dTumble"));
    }
  }
  if (outformat == OUTPUT_FORMAT_RASTER) {
    if (h->cupsMediaType) {
      snprintf(tmpstr, sizeof(tmpstr), "-dcupsMediaType=%d",
	       (unsigned)(h->cupsMediaType));
      cupsArrayAdd(gs_args, strdup(tmpstr));
    }
    snprintf(tmpstr, sizeof(tmpstr), "-dcupsBitsPerColor=%d",h->cupsBitsPerColor);
    cupsArrayAdd(gs_args, strdup(tmpstr));
    snprintf(tmpstr, sizeof(tmpstr), "-dcupsColorOrder=%d",h->cupsColorOrder);
    cupsArrayAdd(gs_args, strdup(tmpstr));
    snprintf(tmpstr, sizeof(tmpstr), "-dcupsColorSpace=%d",h->cupsColorSpace);
    cupsArrayAdd(gs_args, strdup(tmpstr));
  }
  
  if (outformat == OUTPUT_FORMAT_PXL) {
    if (h->cupsColorSpace == CUPS_CSPACE_W ||
	h->cupsColorSpace == CUPS_CSPACE_K ||
	h->cupsColorSpace == CUPS_CSPACE_WHITE ||
	h->cupsColorSpace == CUPS_CSPACE_GOLD ||
	h->cupsColorSpace == CUPS_CSPACE_SILVER ||
	h->cupsColorSpace == CUPS_CSPACE_SW ||
	h->cupsColorSpace == CUPS_CSPACE_ICC1 ||
	h->cupsColorSpace == CUPS_CSPACE_DEVICE1)
      /* Monochrome color spaces -> use "pxlmono" device */
      pxlcolor = 0;
    if (pxlcolor == 1)
      cupsArrayAdd(gs_args, strdup("-sDEVICE=pxlcolor"));
    else
      cupsArrayAdd(gs_args, strdup("-sDEVICE=pxlmono"));
  }
  if (outformat == OUTPUT_FORMAT_RASTER) {
    if (h->cupsCompression) {
      snprintf(tmpstr, sizeof(tmpstr), "-dcupsCompression=%d",
	       (unsigned)(h->cupsCompression));
      cupsArrayAdd(gs_args, strdup(tmpstr));
    }
    if (h->cupsRowCount) {
      snprintf(tmpstr, sizeof(tmpstr), "-dcupsRowCount=%d",
	       (unsigned)(h->cupsRowCount));
      cupsArrayAdd(gs_args, strdup(tmpstr));
    }
    if (h->cupsRowFeed) {
      snprintf(tmpstr, sizeof(tmpstr), "-dcupsRowFeed=%d",
	       (unsigned)(h->cupsRowFeed));
      cupsArrayAdd(gs_args, strdup(tmpstr));
    }
    if (h->cupsRowStep) {
      snprintf(tmpstr, sizeof(tmpstr), "-dcupsRowStep=%d",
	       (unsigned)(h->cupsRowStep));
      cupsArrayAdd(gs_args, strdup(tmpstr));
    }
  }
#ifdef CUPS_RASTER_SYNCv1
  if (outformat == OUTPUT_FORMAT_RASTER) {
    if (h->cupsBorderlessScalingFactor != 1.0f) {
      snprintf(tmpstr, sizeof(tmpstr), "-dcupsBorderlessScalingFactor=%.4f",
	       h->cupsBorderlessScalingFactor);
      cupsArrayAdd(gs_args, strdup(tmpstr));
    }
    for (i=0; i <= 15; i ++)
      if (h->cupsInteger[i]) {
	snprintf(tmpstr, sizeof(tmpstr), "-dcupsInteger%d=%d",
		 i, (unsigned)(h->cupsInteger[i]));
	cupsArrayAdd(gs_args, strdup(tmpstr));
      }
    for (i=0; i <= 15; i ++)
      if (h->cupsReal[i]) {
	snprintf(tmpstr, sizeof(tmpstr), "-dcupsReal%d=%.4f",
		 i, h->cupsReal[i]);
	cupsArrayAdd(gs_args, strdup(tmpstr));
      }
    for (i=0; i <= 15; i ++)
      if (h->cupsString[i][0] != '\0') {
	snprintf(tmpstr, sizeof(tmpstr), "-scupsString%d=%s",
		 i, h->cupsString[i]);
	cupsArrayAdd(gs_args, strdup(tmpstr));
      }
    if (h->cupsMarkerType[0] != '\0') {
      snprintf(tmpstr, sizeof(tmpstr), "-scupsMarkerType=%s",
	       h->cupsMarkerType);
      cupsArrayAdd(gs_args, strdup(tmpstr));
    }
    if (h->cupsRenderingIntent[0] != '\0') {
      snprintf(tmpstr, sizeof(tmpstr), "-scupsRenderingIntent=%s",
	       h->cupsRenderingIntent);
      cupsArrayAdd(gs_args, strdup(tmpstr));
    }
    if (h->cupsPageSizeName[0] != '\0') {
      snprintf(tmpstr, sizeof(tmpstr), "-scupsPageSizeName=%s",
	       h->cupsPageSizeName);
      cupsArrayAdd(gs_args, strdup(tmpstr));
    }
  }
#endif /* CUPS_RASTER_SYNCv1 */
}

static int
gs_spawn (const char *filename,
          cups_array_t *gs_args,
          char **envp,
          FILE *fp)
{
  char *argument;
  char buf[BUFSIZ];
  char **gsargv;
  const char* apos;
  int fds[2];
  int i;
  int n;
  int numargs;
  int pid;
  int status = 65536;
  int wstatus;

  /* Put Ghostscript command line argument into an array for the "exec()"
     call */
  numargs = cupsArrayCount(gs_args);
  gsargv = calloc(numargs + 1, sizeof(char *));
  for (argument = (char *)cupsArrayFirst(gs_args), i = 0; argument;
       argument = (char *)cupsArrayNext(gs_args), i++) {
    gsargv[i] = argument;
  }
  gsargv[i] = NULL;

  /* Debug output: Full Ghostscript command line and environment variables */
  fprintf(stderr, "DEBUG: Ghostscript command line:");
  for (i = 0; gsargv[i]; i ++) {
    if ((strchr(gsargv[i],' ')) || (strchr(gsargv[i],'\t')))
      apos = "'";
    else
      apos = "";
    fprintf(stderr, " %s%s%s", apos, gsargv[i], apos);
  }
  fprintf(stderr, "\n");

  for (i = 0; envp[i]; i ++)
    fprintf(stderr, "DEBUG: envp[%d]=\"%s\"\n", i, envp[i]);

  /* Create a pipe for feeding the job into Ghostscript */
  if (pipe(fds))
  {
    fds[0] = -1;
    fds[1] = -1;
    fprintf(stderr, "ERROR: Unable to establish pipe for Ghostscript call\n");
    goto out;
  }

  /* Set the "close on exec" flag on each end of the pipe... */
  if (fcntl(fds[0], F_SETFD, fcntl(fds[0], F_GETFD) | FD_CLOEXEC))
  {
    close(fds[0]);
    close(fds[1]);
    fds[0] = -1;
    fds[1] = -1;
    fprintf(stderr, "ERROR: Unable to set \"close on exec\" flag on read end of the pipe for Ghostscript call\n");
    goto out;
  }
  if (fcntl(fds[1], F_SETFD, fcntl(fds[1], F_GETFD) | FD_CLOEXEC))
  {
    close(fds[0]);
    close(fds[1]);
    fprintf(stderr, "ERROR: Unable to set \"close on exec\" flag on write end of the pipe for Ghostscript call\n");
    goto out;
  }

  if ((pid = fork()) == 0)
  {
    /* Couple pipe with STDIN of Ghostscript process */
    if (fds[0] != 0) {
      close(0);
      if (fds[0] > 0) {
        if (dup(fds[0]) < 0) {
	  fprintf(stderr, "ERROR: Unable to couple pipe with STDIN of Ghostscript process\n");
	  goto out;
	}
      } else {
        fprintf(stderr, "ERROR: Unable to couple pipe with STDIN of Ghostscript process\n");
        goto out;
      }
    }

    /* Execute Ghostscript command line ... */
    execvpe(filename, gsargv, envp);
    fprintf(stderr, "ERROR: Unable to launch Ghostscript: %s: %s\n", filename, strerror(errno));
    goto out;
  }

  /* Feed job data into Ghostscript */
  while ((n = fread(buf, 1, BUFSIZ, fp)) > 0) {
    int count;
retry_write:
    count = write(fds[1], buf, n);
    if (count != n) {
      if (count == -1) {
        if (errno == EINTR)
          goto retry_write;
        fprintf(stderr, "ERROR: write failed: %s\n", strerror(errno));
      }
      fprintf(stderr, "ERROR: Can't feed job data into Ghostscript\n");
      goto out;
    }
  }
  close (fds[1]);

retry_wait:
  if (waitpid (pid, &wstatus, 0) == -1) {
    if (errno == EINTR)
      goto retry_wait;
    perror ("gs");
    goto out;
  }

  /* How did Ghostscript terminate */
  if (WIFEXITED(wstatus))
    /* Via exit() anywhere or return() in the main() function */
    status = WEXITSTATUS(wstatus);
  else if (WIFSIGNALED(wstatus))
    /* Via signal */
    status = 256 * WTERMSIG(wstatus);

out:
  free(gsargv);
  return status;
}

#if 0
static char *
get_ppd_icc_fallback (ppd_file_t *ppd, char **qualifier)
{
  char full_path[1024];
  char *icc_profile = NULL;
  char qualifer_tmp[1024];
  const char *profile_key;
  ppd_attr_t *attr;
  char *datadir;

  /* get profile attr, falling back to CUPS */
  profile_key = "APTiogaProfile";
  attr = ppdFindAttr(ppd, profile_key, NULL);
  if (attr == NULL) {
    profile_key = "cupsICCProfile";
    attr = ppdFindAttr(ppd, profile_key, NULL);
  }

  /* create a string for a quick comparion */
  snprintf(qualifer_tmp, sizeof(qualifer_tmp),
           "%s.%s.%s",
           qualifier[0],
           qualifier[1],
           qualifier[2]);

  /* neither */
  if (attr == NULL) {
    fprintf(stderr, "INFO: no profiles specified in PPD\n");
    goto out;
  }

  if ((datadir = getenv("CUPS_DATADIR")) == NULL)
    datadir = CUPS_DATADIR;

  /* try to find a profile that matches the qualifier exactly */
  for (;attr != NULL; attr = ppdFindNextAttr(ppd, profile_key, NULL)) {
    fprintf(stderr, "INFO: found profile %s in PPD with qualifier '%s'\n",
            attr->value, attr->spec);

    /* invalid entry */
    if (attr->spec == NULL || attr->value == NULL)
      continue;

    /* expand to a full path if not already specified */
    if (attr->value[0] != '/')
      snprintf(full_path, sizeof(full_path),
               "%s/profiles/%s", datadir, attr->value);
    else
      strncpy(full_path, attr->value, sizeof(full_path));

    /* check the file exists */
    if (access(full_path, 0)) {
      fprintf(stderr, "INFO: found profile %s in PPD that does not exist\n",
              full_path);
      continue;
    }

    /* matches the qualifier */
    if (strcmp(qualifer_tmp, attr->spec) == 0) {
      icc_profile = strdup(full_path);
      goto out;
    }
  }

  /* no match */
  if (attr == NULL) {
    fprintf(stderr, "INFO: no profiles in PPD for qualifier '%s'\n",
            qualifer_tmp);
    goto out;
  }

out:
  return icc_profile;
}
#endif

// Returns the number of pages in the document |filename|. Returns -1 if there was an error.
static int
count_pages(char* filename, GsDocType doc_type) {
  int pagecount = 0;

  if (doc_type == GS_DOC_TYPE_PDF) {
    return pdf_pages(filename);
  }

  // All other content needs to be rendered.
  char gscommand[65536];
  char output[31] = "";
  size_t bytes;
  /* Ghostscript runs too long while printing PDF fikes converted from
     djvu files. Using -dDEVICEWIDTHPOINTS=1 -dDEVICEHEIGHTPOINTS=1
     solves the problem */
  snprintf(gscommand, 65536, "%s -q -dNOPAUSE -dBATCH -sDEVICE=bbox -dDEVICEWIDTHPOINTS=1 -dDEVICEHEIGHTPOINTS=1 %s 2>&1 | grep -c HiResBoundingBox",
      CUPS_GHOSTSCRIPT, filename);

  FILE *pd = popen(gscommand, "r");
  if (!pd) {
    fprintf(stderr, "Failed to execute ghostscript to determine number of input pages!\n");
    return -1;
  }

  bytes = fread(output, 1, 31, pd);
  pclose(pd);

  if (bytes <= 0 || sscanf(output, "%d", &pagecount) < 1)
    return -1;

  return pagecount;
}

int
main (int argc, char **argv, char *envp[])
{
  char *outformat_env = NULL;
  OutFormatType outformat;
  char buf[BUFSIZ];
  char *filename;
  char *icc_profile = NULL;
  /*char **qualifier = NULL;*/
  char *tmp;
  char tmpstr[1024];
  const char *t = NULL;
  cups_array_t *gs_args = NULL;
  cups_option_t *options = NULL;
  FILE *fp = NULL;
  GsDocType doc_type;
  gs_page_header h;
  int fd;
  int cm_disabled;
  int n;
  int num_options;
  int status = 1;
  ppd_file_t *ppd = NULL;
  struct sigaction sa;
  cm_calibration_t cm_calibrate;
  int pxlcolor = 1;
#ifdef HAVE_CUPS_1_7
  int pwgraster = 0;
  ppd_attr_t *attr;
#endif /* HAVE_CUPS_1_7 */

  if (argc < 6 || argc > 7) {
    fprintf(stderr, "ERROR: %s job-id user title copies options [file]\n",
      argv[0]);
    goto out;
  }

  memset(&sa, 0, sizeof(sa));
  /* Ignore SIGPIPE and have write return an error instead */
  sa.sa_handler = SIG_IGN;
  sigaction(SIGPIPE, &sa, NULL);

  /* Determine the output format via an environment variable set by a wrapper
     script */
  outformat_env = getenv("OUTFORMAT");
  if (outformat_env == NULL || strcasestr(outformat_env, "raster"))
    outformat = OUTPUT_FORMAT_RASTER;
  else if (strcasestr(outformat_env, "pdf"))
    outformat = OUTPUT_FORMAT_PDF;
  else if (strcasestr(outformat_env, "xl"))
    outformat = OUTPUT_FORMAT_PXL;
  else {
    fprintf(stderr, "ERROR: OUTFORMAT=\"%s\", cannot determine output format\n",
      outformat_env);
    goto out;
  }
  fprintf(stderr, "DEBUG: OUTFORMAT=\"%s\", so output format will be %s\n",
	  (outformat_env ? outformat_env : "<none>"),
	  (outformat == OUTPUT_FORMAT_RASTER ? "CUPS/PWG Raster" :
	   (outformat == OUTPUT_FORMAT_PDF ? "PDF" :
	    "PCL XL")));
  
  num_options = cupsParseOptions(argv[5], 0, &options);

  t = getenv("PPD");
  if (t && t[0] != '\0')
    if ((ppd = ppdOpenFile(t)) == NULL) {
      fprintf(stderr, "ERROR: Failed to open PPD: %s\n", t);
    }
      
  if (ppd) {
    ppdMarkDefaults (ppd);
    cupsMarkOptions (ppd, num_options, options);
  }

  if (argc == 6) {
    /* stdin */

    fd = cupsTempFd(buf,BUFSIZ);
    if (fd < 0) {
      fprintf(stderr, "ERROR: Can't create temporary file\n");
      goto out;
    }

    filename = strdup(buf);

    /* copy stdin to the tmp file */
    while ((n = read(0,buf,BUFSIZ)) > 0) {
      if (write(fd,buf,n) != n) {
        fprintf(stderr, "ERROR: Can't copy stdin to temporary file\n");
        close(fd);
        goto out;
      }
    }
    if (lseek(fd,0,SEEK_SET) < 0) {
        fprintf(stderr, "ERROR: Can't rewind temporary file\n");
        close(fd);
        goto out;
    }

    if ((fp = fdopen(fd,"rb")) == 0) {
        fprintf(stderr, "ERROR: Can't fdopen temporary file\n");
        close(fd);
        goto out;
    }
  } else {
    /* argc == 7 filename is specified */

    if ((fp = fopen(argv[6],"rb")) == 0) {
        fprintf(stderr, "ERROR: Can't open input file %s\n",argv[6]);
        goto out;
    }
    filename = argv[6];
  }

  /* find out file type */
  doc_type = parse_doc_type(fp);
  if (doc_type == GS_DOC_TYPE_UNKNOWN) {
    char buf[1];
    rewind(fp);
    if (fread(buf, 1, 1, fp) == 0) {
      fprintf(stderr, "DEBUG: Input is empty, outputting empty file.\n");
      status = 0;
      if (outformat == OUTPUT_FORMAT_RASTER)
        fprintf(stdout, "RaS2");
      goto out;
    }
    fprintf(stderr, "ERROR: Can't detect file type\n");
    goto out;
  }

  // Determine how many pages we have and if we have something valid to print.
  int pagecount = count_pages(filename, doc_type);
  if (pagecount == 0) {
    fprintf(stderr, "DEBUG: No pages left, outputting empty file.\n");
    status = 0;
    if (outformat == OUTPUT_FORMAT_RASTER)
      fprintf(stdout, "RaS2");
    goto out;
  }
  if (pagecount < 0) {
    fprintf(stderr, "DEBUG: Unexpected page count\n");
    goto out;
  }

  if (pwgraster) {
    // Set job-impressions for later embedding as TotalPageCount.
    num_options = cupsAddIntegerOption("job-impressions", pagecount, num_options, &options);
  }

  if (argc == 6) {
    /* input from stdin */
    /* remove name of temp file*/
    unlink(filename);
    free(filename);
  }

  /*  Check status of color management in CUPS */
  cm_calibrate = cmGetCupsColorCalibrateMode(options, num_options);

  if (cm_calibrate == CM_CALIBRATION_ENABLED)
    cm_disabled = 1;
  else 
    cm_disabled = cmIsPrinterCmDisabled(getenv("PRINTER"));

  if (!cm_disabled)
    cmGetPrinterIccProfile(getenv("PRINTER"), &icc_profile, ppd);

  /* Ghostscript parameters */
  gs_args = cupsArrayNew(NULL, NULL);
  if (!gs_args) {
    fprintf(stderr, "ERROR: Unable to allocate memory for Ghostscript arguments array\n");
    goto out;
  }

  /* Part of Ghostscript command line which is not dependent on the job and/or
     the driver */
  snprintf(tmpstr, sizeof(tmpstr), "%s", CUPS_GHOSTSCRIPT);
  cupsArrayAdd(gs_args, strdup(tmpstr));
  cupsArrayAdd(gs_args, strdup("-dQUIET"));
  /*cupsArrayAdd(gs_args, strdup("-dDEBUG"));*/
  cupsArrayAdd(gs_args, strdup("-dSAFER"));
  cupsArrayAdd(gs_args, strdup("-dNOPAUSE"));
  cupsArrayAdd(gs_args, strdup("-dBATCH"));
  cupsArrayAdd(gs_args, strdup("-dNOINTERPOLATE"));
  cupsArrayAdd(gs_args, strdup("-dNOMEDIAATTRS"));
  if (cm_disabled)
    cupsArrayAdd(gs_args, strdup("-dUseFastColor"));
  if (doc_type == GS_DOC_TYPE_PDF)
    cupsArrayAdd(gs_args, strdup("-dShowAcroForm"));
  cupsArrayAdd(gs_args, strdup("-sstdout=%stderr"));
  cupsArrayAdd(gs_args, strdup("-sOutputFile=%stdout"));

  /* Ghostscript output device */
  if (outformat == OUTPUT_FORMAT_RASTER)
    cupsArrayAdd(gs_args, strdup("-sDEVICE=cups"));
  else if (outformat == OUTPUT_FORMAT_PDF)
    cupsArrayAdd(gs_args, strdup("-sDEVICE=pdfwrite"));
  /* In case of PCL XL output we determine later whether we will have
     to use the "pxlmono" or "pxlcolor" output device */

  /* Special Ghostscript options for PDF output */
  if (outformat == OUTPUT_FORMAT_PDF) {
    /* If we output PDF we are running as a PostScript-to-PDF filter
       for incoming PostScript jobs. If the client embeds a command
       for multiple copies in the PostScript job instead of using the
       CUPS argument for the number of copies, we need to run
       Ghostscript with the "-dDoNumCopies" option so that it respects
       the embedded command for the number of copies.

       We always supply this option if the number of copies CUPS got
       told about is 1, as this is the case if a client sets the
       number of copies as embedded PostScript command, and it is also
       not doing the wrong thing if the command is missing when the
       client only wants a single copy, independent how the client
       actually triggers multiple copies. If the CUPS arguments tells
       us that the clients wants more than one copy we do not supply
       "-dDoNumCopies" as the client does the right, modern CUPS way,
       and if the client got a "dirty" PostScript file with an
       embedded multi-copy setting, he does not get unwished copies.
       also a buggy client supplying the number of copies both via
       PostScript and CUPS will not cause an unwished number of copies
       this way.

       See https://github.com/OpenPrinting/cups-filters/issues/255

       This was already correctly implemented in the former pdftops
       shell-script-based filter but overlooked when the filter's
       functionality got folded into this gstoraster.c filter. It was
       not seen for long time as clients sending PostScript jobs with
       embedded number of copies are rare. */
    if (atoi(argv[4]) <= 1)
      cupsArrayAdd(gs_args, strdup("-dDoNumCopies"));

    cupsArrayAdd(gs_args, strdup("-dCompatibilityLevel=1.3"));
    cupsArrayAdd(gs_args, strdup("-dAutoRotatePages=/None"));
    cupsArrayAdd(gs_args, strdup("-dAutoFilterColorImages=false"));
    cupsArrayAdd(gs_args, strdup("-dNOPLATFONTS"));
    cupsArrayAdd(gs_args, strdup("-dColorImageFilter=/FlateEncode"));
    cupsArrayAdd(gs_args, strdup("-dPDFSETTINGS=/default"));
    cupsArrayAdd(gs_args, strdup("-dColorConversionStrategy=/LeaveColorUnchanged"));
  }
  
#ifdef HAVE_CUPS_1_7
  if (outformat == OUTPUT_FORMAT_RASTER)
  {
    t = getenv("FINAL_CONTENT_TYPE");
    if (t && strcasestr(t, "pwg"))
      pwgraster = 1;
  }
#endif /* HAVE_CUPS_1_7 */
    
  if (ppd)
  {
    cupsRasterInterpretPPD(&h,ppd,num_options,options,0);
#ifdef HAVE_CUPS_1_7
    if (outformat == OUTPUT_FORMAT_RASTER)
    {
      if ((attr = ppdFindAttr(ppd,"PWGRaster",0)) != 0 &&
	  (!strcasecmp(attr->value, "true") ||
	   !strcasecmp(attr->value, "on") ||
	   !strcasecmp(attr->value, "yes")))
	pwgraster = 1;
      if (pwgraster == 1)
	cupsRasterParseIPPOptions(&h, num_options, options, pwgraster, 0);
    }
#endif /* HAVE_CUPS_1_7 */
    if (outformat == OUTPUT_FORMAT_PXL)
    {
      if ((attr = ppdFindAttr(ppd,"ColorDevice",0)) != 0 &&
	  (!strcasecmp(attr->value, "false") ||
	   !strcasecmp(attr->value, "off") ||
	   !strcasecmp(attr->value, "no")))
	/* Monochrome PCL XL printer, according to PPD */
	pxlcolor = 0;
    }
  }
  else
  {
#ifdef HAVE_CUPS_1_7
    if (outformat == OUTPUT_FORMAT_RASTER)
    {
      pwgraster = 1;
      t = cupsGetOption("media-class", num_options, options);
      if (t == NULL)
	t = cupsGetOption("MediaClass", num_options, options);
      if (t != NULL)
      {
	if (strcasestr(t, "pwg"))
	  pwgraster = 1;
	else
	  pwgraster = 0; 
      }
    }
    cupsRasterParseIPPOptions(&h, num_options, options, pwgraster, 1);

    /*
     * cupsRasterParseIPPOptions() would populate the TotalPageCount field
     * (h.cupsInteger[0]) if CUPS passed "job-impressions" to this filter.
     * CUPS does not do so, so we set it manually here. */
    if (pagecount > 0 && pwgraster) {
      h.cupsInteger[0] = pagecount;
    }
#else
    fprintf(stderr, "ERROR: No PPD file specified.\n");
    goto out;
#endif /* HAVE_CUPS_1_7 */
  }

  if ((h.HWResolution[0] == 100) && (h.HWResolution[1] == 100)) {
    /* No "Resolution" option */
    if (ppd && (attr = ppdFindAttr(ppd, "DefaultResolution", 0)) != NULL) {
      /* "*DefaultResolution" keyword in the PPD */
      const char *p = attr->value;
      h.HWResolution[0] = atoi(p);
      if ((p = strchr(p, 'x')) != NULL)
	h.HWResolution[1] = atoi(p);
      else
	h.HWResolution[1] = h.HWResolution[0];
      if (h.HWResolution[0] <= 0)
	h.HWResolution[0] = 300;
      if (h.HWResolution[1] <= 0)
	h.HWResolution[1] = h.HWResolution[0];
    } else {
      h.HWResolution[0] = 300;
      h.HWResolution[1] = 300;
    }
    h.cupsWidth = h.HWResolution[0] * h.PageSize[0] / 72;
    h.cupsHeight = h.HWResolution[1] * h.PageSize[1] / 72;
  }

  /* set PDF-specific options */
  if (doc_type == GS_DOC_TYPE_PDF) {
    parse_pdf_header_options(fp, &h);
  }

  /* fixed other values that pdftopdf handles */
  h.MirrorPrint = CUPS_FALSE;
  h.Orientation = CUPS_ORIENT_0;

  /* get all the data from the header and pass it to ghostscript */
  add_pdf_header_options (&h, gs_args, outformat, pxlcolor);

  /* CUPS font path */
  if ((t = getenv("CUPS_FONTPATH")) == NULL)
    t = CUPS_FONTPATH;
  snprintf(tmpstr, sizeof(tmpstr), "-I%s", t);
  cupsArrayAdd(gs_args, strdup(tmpstr));

  /* set the device output ICC profile */
  if(icc_profile != NULL && icc_profile[0] != '\0') {
    snprintf(tmpstr, sizeof(tmpstr), "-sOutputICCProfile=%s", icc_profile);
    cupsArrayAdd(gs_args, strdup(tmpstr));
  }

  /* Switch to taking PostScript commands on the Ghostscript command line */
  cupsArrayAdd(gs_args, strdup("-c"));

  /* Set margins if we have a bounding box defined and output format
     is not PDF, as PDF output we have only in the PostScript-to-PDF
     filtering case which happens for converting PostScript input
     files before pdftopdf so margins will be handled later, whereas
     the other output formats for PDF-to-something filtering after
     pdftopdf, to format the pages for the printer, so margins are
     important. */
  if (h.cupsImagingBBox[3] > 0.0 && outformat != OUTPUT_FORMAT_PDF) {
    snprintf(tmpstr, sizeof(tmpstr),
	     "<</.HWMargins[%f %f %f %f] /Margins[0 0]>>setpagedevice",
	     h.cupsImagingBBox[0], h.cupsImagingBBox[1],
	     h.cupsPageSize[0] - h.cupsImagingBBox[2],
	     h.cupsPageSize[1] - h.cupsImagingBBox[3]);
    cupsArrayAdd(gs_args, strdup(tmpstr));
  }

  if ((t = cupsGetOption("profile", num_options, options)) != NULL) {
    snprintf(tmpstr, sizeof(tmpstr), "<</cupsProfile(%s)>>setpagedevice", t);
    cupsArrayAdd(gs_args, strdup(tmpstr));
  }

  /* Do we have a "center-of-pixel" command line option or
     "CenterOfPixel" PPD option set to "true"? In this case let
     Ghostscript use the center-of-pixel rule instead of the
     PostScript-standard any-part-of-pixel rule when filling a
     path. This improves the accuracy of graphics (like bar codes for
     example) on low-resolution printers (like label printers with
     typically 203 dpi). See
     https://bugs.linuxfoundation.org/show_bug.cgi?id=1373 */
  if (((t = cupsGetOption("CenterOfPixel", num_options, options)) == NULL &&
       (t = cupsGetOption("center-of-pixel", num_options, options)) == NULL &&
       ppd && (attr = ppdFindAttr(ppd,"DefaultCenterOfPixel", NULL)) != NULL &&
       (!strcasecmp(attr->value, "true") ||
	!strcasecmp(attr->value, "on") ||
	!strcasecmp(attr->value, "yes"))) ||
      (t && (!strcasecmp(t, "true") || !strcasecmp(t, "on") ||
	     !strcasecmp(t, "yes")))) {
    fprintf(stderr, "DEBUG: Ghostscript using Center-of-Pixel method to fill paths.\n");
    cupsArrayAdd(gs_args, strdup("0 0 .setfilladjust2"));
  } else
    fprintf(stderr, "DEBUG: Ghostscript using Any-Part-of-Pixel method to fill paths.\n");

  /* Mark the end of PostScript commands supplied on the Ghostscript command
     line (with the "-c" option), so that we can supply the input file name */
  cupsArrayAdd(gs_args, strdup("-f"));

  /* Let Ghostscript read from STDIN */
  cupsArrayAdd(gs_args, strdup("-_"));

  /* Execute Ghostscript command line ... */
  snprintf(tmpstr, sizeof(tmpstr), "%s", CUPS_GHOSTSCRIPT);

  /* call Ghostscript */
  rewind(fp);
  status = gs_spawn (tmpstr, gs_args, envp, fp);
  if (status != 0) status = 1;
out:
  if (fp)
    fclose(fp);
  if (gs_args) {
    while ((tmp = cupsArrayFirst(gs_args)) != NULL) {
      cupsArrayRemove(gs_args,tmp);
      free(tmp);
    }
    cupsArrayDelete(gs_args);
  }
  free(icc_profile);
  if (ppd)
    ppdClose(ppd);
  return status;
}