Source

CUPS-PDF for Mac OS X / src-2.0.5 / cups-pdf.c

Full commit
  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
/* cups-pdf.c -- CUPS Backend 
   08.02.2003, Volker C. Behr
   Exp. Physik V, Uni Wuerzburg 
   vrbehr@cip.physik.uni-wuerzburg.de
   http://cip.physik.uni-wuerzburg.de/~vrbehr/cups-pdf

   This code may be freely distributed as long as this header 
   is preserved. 

   This code is distributed under the GPL.
   (http://www.gnu.org/copyleft/gpl.html)

   ---------------------------------------------------------------------------

   Copyright (C) 2003,2004,2005,2006  Volker C. Behr

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public License
   as published by the Free Software Foundation; either version 2
   of the License, or (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

   ---------------------------------------------------------------------------
  
   If you want to redistribute modified sources/binaries this header
   has to be preserved and all modifications should be clearly 
   indicated.
   In case you want to include this code into your own programs 
   I would appreciate your feedback via email.

  
   HISTORY: 
   2006-02-26 : 2.0.5      - several code optimizations
   2006-01-29 : 2.0.4      - beginning of (E)PS-code now determined by "%!",
                             optimized system call to GS in cups-pdf.conf,
              		     some minor code changes,
			     debug information shows version number,
      			     updated PostScript PPD file supporting ledger paper
   2006-01-07 : 2.0.3	   - improved checking for root privileges (incl. EUID)
   2006-01-04 : 2.0.2	   - fixed possible testing of an uninitialized variable
   2006-01-03 : 2.0.1	   - fixed hanging jobs when logging is disabled
   2005-12-23 : 2.0.0      - creation of non-existent parent directories,
                             improved configurability of output directories,
			     option CPHOMESUB is now obsolete,
                             PPD file now matches Adobe specifications
   2005-10-23 : 2.0beta2   - added support for post-processing script,
                             fixed a bug when parsing cups-pdf.conf
   2005-09-18 : 2.0beta1   - added support for runtime configuration,
                             introduced cups-pdf.conf,
                             made AnonDirName an abolute path
   2005-09-08 : 1.7.4      - added some options to cups-pdf.h for MacOSX
   2005-07-23 : 1.7.3      - fixed GhostScript failure with error 11,
                             fixed segfault when called without root privileges
   2005-07-07 : 1.7.2	   - adjustment of file mode moved to non-privileged child
   2005-06-16 : 1.7.1	   - PDFs are protected during creation by file mode 000
   2005-03-07 : 1.7.0a
   2005-03-01 : 1.7.0      - call of GhostScript from a non-privileged child process,
                             no more additional programs in the call of GhostScript,
                             several code optimizations
   2005-02-09 : 1.6.6      - updated PostScript PPD file supporting more DIN formats
   2005-01-04 : 1.6.5      - cups-pdf is running with gid of group defined in conf.grp
   2004-10-11 : 1.6.4      - improved configurability for different versions of 'su'
   2004-10-07 : 1.6.3      - corrected erroneous call of GhostScript
   2004-10-05 : 1.6.2      - added necessary quotes in the call of GhostScript
   2004-10-03 : 1.6.1      - allow users w/o valid shell in /etc/passwd,
                             several code optimizations
   2004-09-08 : 1.6.0      - new option to check against user names in lower case,
                             new option to label all created PDFs with a job-id
   2004-08-10 : 1.5.2      - fixed insecure creation of spoolfile,
     			     several smaller code optimizations
   2004-08-09 : 1.5.1	   - fixed possible access to element outside allocated area,
                             fixed possible conflict with overlapping memory areas
   2004-08-03 : 1.5.0      - call to GS without root privileges for enhanced security
   2004-08-01 : 1.4.3      - added -dSAFER to the call to GS to improve security
   2004-02-25 : 1.4.2a
   2004-02-24 : 1.4.2      - improved extraction of filenames,
                             handling of embedded (e)ps code (RVT)
   2004-02-09 : 1.4.1	   - logfile is created with mode 644 if it does not exist
   2004-01-27 : 1.4.0      - new option to set permissions for PDF output,
                             alternative options for improved image conversion
                             (moved conf.gscall to cups-pdf.h)
   2004-01-06 : 1.3.2	   - exit status of ghostscript gets logged in debug mode
   2004-01-02 : 1.3.1a
   2003-11-29 : 1.3.1	   - improved handling of domain prefix
   2003-11-02 : 1.3	   - new option to cut file name extensions
   2003-10-25 : 1.2        - untitled documents are labelled with job-id,
			     new option to add a domain prefix to user names,
                             removed a minor bug during character replacement
   2003-08-02 : 1.1	   - files not viewable until creation is finished,
   			     new qualifier "$HOME" for output directory,
			     "$HOME"-related new define in the header file
   2003-07-17 : 1.0.1	   - improved user name handling for multi-word names,
                             code now distributed under the GPL
   2003-06-29 : 1.0	   - enhanced debug output,
   			     replacement of special characters in title,
			     new option in the header file
   2003-05-26 : 1.0pre3    - several minor bugfixes and improvements 
   2003-05-21 : 1.0pre2    - optimized memory management
   2003-05-16 : 1.0pre1    - introduced cups-pdf.h, 
			     code now entirely written in C,
 			     cups-pdfgen is obsolete
   2003-02-14 : 0.2    - script re-located to /usr/lib/cups/filter/cups-pdfgen
   2003-02-12 : 0.1    - first beta release			                */

#include <time.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include <stddef.h>
#include <pwd.h>
#include <grp.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>

#include "cups-pdf.h"

extern int errno;

FILE *logfp=NULL;

void log_event(char type, char message[48], char *detail) {
  time_t secs;
  char ctype[8], *timestring;

  if (strlen(conf.log) && (type & conf.logtype)) { 
    time(&secs);
    timestring=ctime(&secs);
    timestring[strlen(timestring)-1]='\0';

    if (type == CPERROR) 
      sprintf(ctype, "ERROR");
    else if (type == CPSTATUS)
      sprintf(ctype, "STATUS");
    else
      sprintf(ctype, "DEBUG");
    if (detail != NULL)  {
      while (detail[strlen(detail)-1] == '\n') 
        detail[strlen(detail)-1]='\0';
      fprintf(logfp,"%s  [%s] %s (%s)\n", timestring, ctype, message, detail);
      if ((conf.logtype & CPDEBUG) && (type & CPERROR)) 
        fprintf(logfp,"%s  [DEBUG] ERRNO: %d\n", timestring, errno);
    }
    else
      fprintf(logfp,"%s  [%s] %s\n", timestring, ctype, message);
  }
  return;
}

void read_config() {
  FILE *fp;
  cp_string buffer, key, value;

  fp=fopen(CPCONFIG,"r");
  if (fp==NULL)
    return;

  while (fgets(buffer, BUFSIZE, fp) != NULL) {
    key[0]='\0';
    value[0]='\0';
    if (sscanf(buffer,"%s %[^\n]",key,value)) {
      if (!strlen(key) || !strncmp(key,"#",1))
        continue;
      if (!_assign_value(key, value))
        fputs("Error in configuration file!\n", stderr);
    }
  }

  fclose(fp);
  return;
}

int create_dir(char *dirname, int nolog) {
  struct stat fstatus;
  char buffer[BUFSIZE],*delim;
  int i;

  while ((i=strlen(dirname))>1 && dirname[i-1]=='/')
    dirname[i-1]='\0';
  if (stat(dirname, &fstatus) || !S_ISDIR(fstatus.st_mode)) {
    memcpy(buffer,dirname,BUFSIZE-1);
    delim=strrchr(buffer,'/');
    if (delim!=buffer)
      delim[0]='\0';
    else
      delim[1]='\0';
    if (create_dir(buffer,nolog)!=0)
      return 1;
    stat(buffer, &fstatus);
    if (mkdir(dirname,fstatus.st_mode)!=0) {
      if (!nolog)
        log_event(CPERROR, "failed to create directory", dirname);
      return 1;
    }
    else
      if (!nolog)
        log_event(CPSTATUS, "directory created", dirname);
    if (chown(dirname,fstatus.st_uid,fstatus.st_gid)!=0)
      if (!nolog)
        log_event(CPDEBUG, "failed to set mode on directory (non fatal)", dirname);
  }
  return 0;
}
    
int init() {
  struct stat fstatus;
  struct group *group;
  cp_string logfile;

  _set_defaults();
  if (strlen(CPCONFIG))
    if (!stat(CPCONFIG, &fstatus) && 
        (S_ISREG(fstatus.st_mode) || S_ISLNK(fstatus.st_mode)))
      read_config();

  umask(0077);

  group=getgrnam(conf.grp);
  if (group)
    setgid(group->gr_gid);

  if (strlen(conf.log)) {
    if (stat(conf.log, &fstatus) || !S_ISDIR(fstatus.st_mode)) {
      if (create_dir(conf.log, 1)) 
        return 1;
      if (chmod(conf.log, 0700))
        return 1;
      log_event(CPSTATUS, "log directory created", conf.log);
    }
    snprintf(logfile,BUFSIZE,"%s%s",conf.log,"/cups-pdf_log");
    logfp=fopen(logfile, "a");
  }

  if (!group) {
    log_event(CPERROR, "Grp not found", conf.grp);
    return 1;
  }
  else 
    log_event(CPDEBUG, "switching to new gid", conf.grp);

  umask(0022);

  if (stat(conf.spool, &fstatus) || !S_ISDIR(fstatus.st_mode)) {
    if (create_dir(conf.spool, 0)) {
      log_event(CPERROR, "failed to create spool directory", conf.spool);
      return 1;
    }
    if (chmod(conf.spool, 0755)) {
      log_event(CPERROR, "failed to set mode on spool directory", conf.spool);
      return 1;
    }
    if (chown(conf.spool, -1, group->gr_gid)) 
      log_event(CPERROR, "failed to set group id on spool directory (non fatal)", conf.grp);
    log_event(CPSTATUS, "spool directory created", conf.spool);
  }

  umask(0077);
  return 0;
}

char *preparedirname(struct passwd *passwd, char *uname) {
  int size;
  char bufin[BUFSIZE], bufout[BUFSIZE], *needle, *cptr;

  strncpy(bufin, conf.out, BUFSIZE);
  do {
    needle=strstr(bufin, "${HOME}");
    if (needle == NULL)
      break;
    needle[0]='\0';
    cptr=needle+7;
    snprintf(bufout, BUFSIZE, "%s%s%s", bufin, passwd->pw_dir, cptr);
    strncpy(bufin, bufout, BUFSIZE);
  } while (needle != NULL);
  do {
    needle=strstr(bufin, "${USER}");
    if (needle == NULL)
      break;
    needle[0]='\0';
    cptr=needle+7;
    if (!conf.dirprefix)
      snprintf(bufout, BUFSIZE, "%s%s%s", bufin, uname, cptr);
    else
      snprintf(bufout, BUFSIZE, "%s%s%s", bufin, passwd->pw_name, cptr);
    strncpy(bufin, bufout, BUFSIZE);
  } while (needle != NULL);
  size=strlen(bufin)+1;
  cptr=calloc(size, sizeof(char));
  if (cptr == NULL)
    return NULL;
  snprintf(cptr,size,"%s",bufin);
  return cptr;
}

int prepareuser(struct passwd *passwd, char *dirname) {
  struct stat fstatus;

  umask(0000);
  if (stat(dirname, &fstatus) || !S_ISDIR(fstatus.st_mode)) {
    if (!strcmp(passwd->pw_name, conf.anonuser)) {
      if (create_dir(dirname, 0)) {
        log_event(CPERROR, "failed to create anonymous output directory", dirname);
        return 1;
      }
      if (chmod(dirname, (0777&~conf.anonumask))) {
        log_event(CPERROR, "failed to set mode on anonymous output directory", dirname);
        return 1;
      }
      log_event(CPDEBUG, "anonymous output directory created", dirname);
    }
    else {
      if (create_dir(dirname, 0)) {
        log_event(CPERROR, "failed to create user output directory", dirname);
        return 1;
      }
      if (chmod(dirname, (0777&~conf.userumask))) {
        log_event(CPERROR, "failed to set mode on user output directory", dirname);
        return 1;
      }
      log_event(CPDEBUG, "user output directory created", dirname);
    }
    if (chown(dirname, passwd->pw_uid, passwd->pw_gid)) {
      log_event(CPERROR, "failed to set owner for output directory", passwd->pw_name);
      return 1;
    }
    log_event(CPDEBUG, "owner set for output directory", passwd->pw_name);
  }
  umask(0077);
  return 0;
}

void replace_string(char *string) {
 unsigned int i;

 log_event(CPDEBUG, "removing special characters from title", string);
 for (i=0;i<strlen(string);i++) 
   if ( ( (int) string[i] < '0' || (int) string[i] > '9' ) &&
        ( (int) string[i] < 'A' || (int) string[i] > 'Z' ) &&
        ( (int) string[i] < 'a' || (int) string[i] > 'z' ) &&
        (int) string[i] != '-' && (int) string[i] != '+' )
    string[i]='_';
  return;
}
  
int preparespoolfile(FILE *fpsrc, char *spoolfile, char *title, int job, struct passwd *passwd) {
  cp_string buffer;
  char *cut;
  int rec_depth,is_title=0;
  FILE *fpdest;

  if (fpsrc == NULL) {
    log_event(CPERROR, "failed to open source stream", NULL);
    return 1;
  }
  log_event(CPDEBUG, "source stream ready", NULL);
  fpdest=fopen(spoolfile, "w");
  if (fpdest == NULL) {
    log_event(CPERROR, "failed to open spoolfile", spoolfile);
    fclose(fpsrc);
    return 1;
  }
  log_event(CPDEBUG, "destination stream ready", spoolfile);
  if (chown(spoolfile, passwd->pw_uid, -1)) {
    log_event(CPERROR, "failed to set owner for spoolfile", spoolfile);
    return 1;
  }
  log_event(CPDEBUG, "owner set for spoolfile", spoolfile);
  rec_depth=0;
  while (fgets(buffer, BUFSIZE, fpsrc) != NULL) {
    if (!strncmp(buffer, "%!", 2)) {
      log_event(CPDEBUG, "found beginning of postscript code", buffer);
      break;
    }
  }
  log_event(CPDEBUG, "now extracting postscript code", NULL);
  fputs(buffer, fpdest);
  while (fgets(buffer, BUFSIZE, fpsrc) != NULL) {
    fputs(buffer, fpdest);
    if (!is_title && !rec_depth)
      if (sscanf(buffer, "%%%%Title: %"TBUFSIZE"c", title)==1) {
        log_event(CPDEBUG, "found title in ps code", title);
        is_title=1;
      }
    if (!strncmp(buffer, "%!", 2)) {
      log_event(CPDEBUG, "found embedded (e)ps code", buffer);
      rec_depth++;
    }
    else if (!strncmp(buffer, "%%EOF", 5)) {
      if (!rec_depth) {
        log_event(CPDEBUG, "found end of postscript code", buffer);
        break;
      }
      else {
        log_event(CPDEBUG, "found end of embedded (e)ps code", buffer);
        rec_depth--;
      }
    }
  }
  fclose(fpdest);
  fclose(fpsrc);
  log_event(CPDEBUG, "all data written to spoolfile", spoolfile);
  cut=strrchr(title, '/');
  if (cut != NULL) {
    log_event(CPDEBUG, "removing slashes from full title", title);
    memmove(title, cut+1, strlen(cut+1)+1);
  }  
  if (title != NULL) 
    while (strlen(title) && ((title[strlen(title)-1] == '\n') || (title[strlen(title)-1] == '\r'))) 
      title[strlen(title)-1]='\0';
  cut=strrchr(title, '.');
  if ((cut != NULL) && ((short)strlen(cut) <= conf.cut+1) && (cut != title)) {
    log_event(CPDEBUG, "removing file name extension", cut);
    cut[0]='\0';
  }
  replace_string(title);
  if (!strcmp(title, "")) { 
    snprintf(title, BUFSIZE, "job_%i-untitled_document", job);
    log_event(CPDEBUG, "no title found - using default value", title);
  }
  else {
    if (conf.label) {
      strcpy(buffer, title);
      snprintf(title, BUFSIZE, "job_%i-%s", job, buffer);
    }
    log_event(CPDEBUG, "title successfully retrieved", title);
  }
  return 0;
}

int main(int argc, char *argv[]) {
  char *user, *dirname, *spoolfile, *outfile, *gscall, *ppcall;
  cp_string title="";
  int size;
  mode_t mode;
  struct passwd *passwd;
  pid_t pid;

  if (setuid(0)) {
    fputs("cups-pdf cannot be called without root privileges!\n", stderr);
    return 0;
  }

  if (init()) 
    return -1;
  log_event(CPDEBUG, "initialization finished", CPVERSION);

  if (argc==1) {
    printf("file cups-pdf:/ \"PDF Printer\" \"Virtual Printer\"\n"); 
    log_event(CPSTATUS, "identification string sent", NULL);
    return 0;
  }
  if (argc<6 || argc>7) {
    fputs("Usage: cups-pdf job-id user title copies options [file]\n", stderr);
    log_event(CPERROR, "call contained illegal number of arguments", NULL);
    return 0;
  }

  size=strlen(conf.userprefix)+strlen(argv[2])+1;
  user=calloc(size, sizeof(char));
  if (user == NULL) {
    fputs("CUPS-PDF: failed to allocate memory\n", stderr);
    return -2;
  }  
  snprintf(user, size, "%s%s", conf.userprefix, argv[2]);
  passwd=getpwnam(user);
  if (passwd == NULL && conf.lowercase) {
    log_event(CPDEBUG, "unknown user", user);
    for (size=0;size<(int) strlen(argv[2]);size++) 
      argv[2][size]=tolower(argv[2][size]);
    log_event(CPDEBUG, "trying lower case user name", argv[2]);
    size=strlen(conf.userprefix)+strlen(argv[2])+1;
    snprintf(user, size, "%s%s", conf.userprefix, argv[2]);
    passwd=getpwnam(user);
  }  
  if (passwd == NULL) {
    if (strlen(conf.anonuser)) {
      passwd=getpwnam(conf.anonuser);
      if (passwd == NULL) {
        log_event(CPERROR, "username for anonymous access unknown", conf.anonuser);
        free(user);
        if (logfp!=NULL)
          fclose(logfp);
        return -2;
      }
      log_event(CPDEBUG, "unknown user", user);
      size=strlen(conf.anondirname)+4;
      dirname=calloc(size, sizeof(char));
      if (dirname == NULL) {
        fputs("CUPS-PDF: failed to allocate memory\n", stderr);
        free(user);
        if (logfp!=NULL)
          fclose(logfp);
        return -2;
      }  
      snprintf(dirname, size, "%s", conf.anondirname);
      while (strlen(dirname) && ((dirname[strlen(dirname)-1] == '\n') ||
             (dirname[strlen(dirname)-1] == '\r')))
        dirname[strlen(dirname)-1]='\0';
      log_event(CPDEBUG, "output directory name generated", dirname);
    }
    else {
      log_event(CPSTATUS, "anonymous access denied", user);
      free(user);
      if (logfp!=NULL)
        fclose(logfp);
      return 0;
    }
    mode=(0666&~conf.anonumask);
  } 
  else {
    log_event(CPDEBUG, "user identified", passwd->pw_name);
    if ((dirname=preparedirname(passwd, argv[2])) == NULL) {
      fputs("CUPS-PDF: failed to allocate memory\n", stderr);
      free(user);
      if (logfp!=NULL)
        fclose(logfp);
      return -2;
    }  
    while (strlen(dirname) && ((dirname[strlen(dirname)-1] == '\n') ||
           (dirname[strlen(dirname)-1] == '\r')))
      dirname[strlen(dirname)-1]='\0';
    log_event(CPDEBUG, "output directory name generated", dirname);
    mode=(0666&~conf.userumask);
  }
  free(user);
  if (prepareuser(passwd, dirname)) {
    free(dirname);
    if (logfp!=NULL)
      fclose(logfp);
    return -2;
  }
  log_event(CPDEBUG, "user information prepared", NULL);

  size=strlen(conf.spool)+22;
  spoolfile=calloc(size, sizeof(char));
  if (spoolfile == NULL) {
    fputs("CUPS-PDF: failed to allocate memory\n", stderr);
    free(dirname);
    if (logfp!=NULL)
      fclose(logfp);
    return -3;
  }
  snprintf(spoolfile, size, "%s/cups2pdf-%i", conf.spool, (int) getpid());
  log_event(CPDEBUG, "spoolfile name created", spoolfile);

  if (argc == 6) {
    if (preparespoolfile(stdin, spoolfile, title, atoi(argv[1]), passwd)) {
      free(dirname);
      free(spoolfile);
      if (logfp!=NULL)
        fclose(logfp);
      return -4;
    }
    log_event(CPDEBUG, "input data read from stdin", NULL);
  }
  else {
    if (preparespoolfile(fopen(argv[6], "r"), spoolfile, title, atoi(argv[1]), passwd)) {
      free(dirname);
      free(spoolfile);
      if (logfp!=NULL)
        fclose(logfp);
      return -4;
    }
    log_event(CPDEBUG, "input data read from file", argv[6]);
  }  

  size=strlen(dirname)+strlen(title)+6;
  outfile=calloc(size, sizeof(char));
  if (outfile == NULL) {
    fputs("CUPS-PDF: failed to allocate memory\n", stderr);
    free(dirname);
    free(spoolfile);
    if (logfp!=NULL)
      fclose(logfp);
    return -5;
  }
  snprintf(outfile, size, "%s/%s.pdf", dirname, title);
  log_event(CPDEBUG, "output filename created", outfile);

  size=strlen(conf.gscall)+strlen(conf.ghostscript)+strlen(conf.pdfver)+strlen(outfile)+strlen(spoolfile)+6;
  gscall=calloc(size, sizeof(char));
  if (gscall == NULL) {
    fputs("CUPS-PDF: failed to allocate memory\n", stderr);
    free(dirname);
    free(spoolfile);
    free(outfile);
    if (logfp!=NULL)
      fclose(logfp);
    return -6;
  }
  snprintf(gscall, size, conf.gscall, conf.ghostscript, conf.pdfver, outfile, spoolfile);
  log_event(CPDEBUG, "ghostscript commandline built", gscall);

  unlink(outfile);
  log_event(CPDEBUG, "output file unlinked", outfile);

  if (setenv("TMPDIR", conf.gstmp, 1)) {
    log_event(CPERROR, "insufficient space in environment to set TMPDIR", conf.gstmp);
    free(dirname);
    free(spoolfile);
    free(outfile);
    free(gscall);
    if (logfp!=NULL)
      fclose(logfp);
    return -7;
  }
  log_event(CPDEBUG, "TMPDIR set for GhostScript", getenv("TMPDIR"));

  if (logfp!=NULL)
    fflush(logfp);
  pid=fork();

  if (!pid) {
    log_event(CPDEBUG, "entering child process", NULL);

    if (setgid(passwd->pw_gid))
      log_event(CPERROR, "failed to set GID for current user", NULL);
    else 
      log_event(CPDEBUG, "GID set for current user", NULL);
    if (setuid(passwd->pw_uid))
      log_event(CPERROR, "failed to set UID for current user", passwd->pw_name);
    else 
      log_event(CPDEBUG, "UID set for current user", passwd->pw_name);
     
    umask(0077);
    size=system(gscall);
    snprintf(title,BUFSIZE,"%d",size);
    log_event(CPDEBUG, "ghostscript has finished", title);
    if (chmod(outfile, mode)) {
      log_event(CPERROR, "failed to set file mode for PDF file (non fatal)", outfile);
      return -101;
    }
    log_event(CPDEBUG, "file mode set for user output", outfile);
    
    if (strlen(conf.postprocessing)) {
      size=strlen(conf.postprocessing)+strlen(outfile)+strlen(passwd->pw_name)+3;
      ppcall=calloc(size, sizeof(char));
      if (ppcall == NULL) 
        log_event(CPERROR, "failed to allocate memory for postprocessing (non fatal)", NULL);
      else {
        snprintf(ppcall, size, "%s %s %s", conf.postprocessing, outfile, passwd->pw_name);
        log_event(CPDEBUG, "postprocessing commandline built", ppcall);
        size=system(ppcall);
        snprintf(title,BUFSIZE,"%d",size);
        log_event(CPDEBUG, "postprocessing has finished", title);
        free(ppcall);
      }
    }
    else
     log_event(CPDEBUG, "no postprocessing", NULL);

    return 0;
  }
  log_event(CPDEBUG, "waiting for child to exit", NULL);
  waitpid(pid,NULL,0);

  if (unlink(spoolfile)) 
    log_event(CPERROR, "failed to unlink spoolfile (non fatal)", spoolfile);
  else 
    log_event(CPDEBUG, "spoolfile unlinked", spoolfile);

  free(dirname);
  free(spoolfile);
  free(outfile);
  free(gscall);
  
  log_event(CPDEBUG, "all memory has been freed", NULL);

  log_event(CPSTATUS, "PDF creation successfully finished", passwd->pw_name);

  if (logfp!=NULL)
    fclose(logfp);
  return 0;
}