File: run-parts.c

package info (click to toggle)
debianutils 5.23.2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 664 kB
  • sloc: ansic: 1,021; sh: 727; makefile: 144
file content (862 lines) | stat: -rw-r--r-- 22,430 bytes parent folder | download
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
/* run-parts: run a bunch of scripts in a directory
 *
 * Debian run-parts program
 * Copyright (C) 1996 Jeff Noxon <jeff@router.patch.net>,
 * Copyright (C) 1996-1999 Guy Maor <maor@debian.org>
 * Copyright (C) 2002-2020 Clint Adams <clint@debian.org>
 *
 * This is free software; see the GNU General Public License version 2
 * or later for copying conditions.  There is NO warranty.
 *
 * Based on run-parts.pl version 0.2, Copyright (C) 1994 Ian Jackson.
 *
 */
#define _GNU_SOURCE

#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#ifdef HAVE_GETOPT_H
#include <getopt.h>
#endif /* HAVE_GETOPT_H */
#include <string.h>
#include <errno.h>
#include <ctype.h>
#include <signal.h>
#include <sys/time.h>
#include <regex.h>

#define RUNPARTS_NORMAL 0
#define RUNPARTS_ERE 1
#define RUNPARTS_LSBSYSINIT 100

int test_mode = 0;
int list_mode = 0;
int verbose_mode = 0;
int debug_mode = 0;
int report_mode = 0;
int reverse_mode = 0;
int exitstatus = 0;
int regex_mode = 0;
int exit_on_error_mode = 0;
int new_session_mode = 0;
int stdin_mode = 0;
int stdin_fd = -1; // initialized in run_parts() if {stdin_mode} != 0


int argcount = 0, argsize = 0;
char **args = 0;

char *custom_ere;
regex_t hierre, tradre, excsre, classicalre, customre;

static void catch_signals();
static void restore_signals();

static char* regex_get_error(int errcode, regex_t *compiled);
static void  regex_compile_pattern(void);
static void  regex_clean(void);

__attribute__((format (printf, 1, 2)))
void error(const char *format, ...)
{
  va_list ap;

  fprintf(stderr, "run-parts: ");

  va_start(ap, format);
  vfprintf(stderr, format, ap);
  va_end(ap);

  fprintf(stderr, "\n");
}


void version()
{
  printf( "Debian run-parts program, version " PACKAGE_VERSION
	  "\nCopyright (C) 1994 Ian Jackson, Copyright (C) 1996 Jeff Noxon.\n"
	  "Copyright (C) 1996,1997,1998,1999 Guy Maor\n"
	  "Copyright (C) 2002-2020 Clint Adams\n"
	  "This is free software; see the GNU General Public License version 2\n"
	  "or later for copying conditions.  There is NO warranty.\n");
  exit(0);
}


void usage()
{
  printf("Usage: run-parts [OPTION]... DIRECTORY [DIRECTORY ...]\n"
	  "      --test          print script names which would run, but don't run them.\n"
	  "      --list          print names of all valid files (can not be used with\n"
	  "                      --test)\n"
	  "  -v, --verbose       print script names before running them.\n"
	  "  -d, --debug         print script names while checking them.\n"
	  "      --report        print script names if they produce output.\n"
	  "      --reverse       reverse execution order of scripts.\n"
	  "      --exit-on-error exit as soon as a script returns with a non-zero exit\n"
	  "                      code.\n"
	  "      --stdin         multiplex stdin to scripts being run, using temporary file\n"
	  "      --lsbsysinit    validate filenames based on LSB sysinit specs.\n"
	  "      --new-session   run each script in a separate process session\n"
	  "      --regex=PATTERN validate filenames based on POSIX ERE pattern PATTERN.\n"
	  "  -u, --umask=UMASK   sets umask to UMASK (octal), default is 022.\n"
	  "  -a, --arg=ARGUMENT  pass ARGUMENT to scripts, use once for each argument.\n"
	  "  -V, --version       output version information and exit.\n"
	  "  -h, --help          display this help and exit.\n");
  exit(0);
}


/* The octal conversion in libc is not foolproof; it will take the 8 and 9
 * digits under some circumstances.  We'll just have to live with it.
 */
void set_umask()
{
  unsigned int mask, result;

  result = sscanf(optarg, "%o", &mask);
  if ((result != 1) || (mask > 07777) || (mask < 0)) {
    error("bad umask value");
    exit(1);
  }

  umask(mask);
}

/* Add an argument to the commands that we will call.  Called once for
   every argument. */
void add_argument(char *newarg)
{
  if (argcount + 1 >= argsize) {
    argsize = argsize ? argsize * 2 : 4;
    args = realloc(args, argsize * (sizeof(char *)));
    if (!args) {
      error("failed to reallocate memory for arguments: %s", strerror(errno));
      exit(1);
    }
  }
  args[argcount++] = newarg;
  args[argcount] = 0;
}

/* True or false? Is this a valid filename? */
int valid_name(const struct dirent *d)
{
    char         *s;
    unsigned int  retval;

    s = (char *)&(d->d_name);

    if (regex_mode == RUNPARTS_ERE) {
        retval = !regexec(&customre, s, 0, NULL, 0);
	if (debug_mode)
	    fprintf(stderr, "\"%s\": customre %s\n", s, retval ? "pass" : "fail");

    } else if (regex_mode == RUNPARTS_LSBSYSINIT) {

        if (!regexec(&hierre, s, 0, NULL, 0)) {
            retval = regexec(&excsre, s, 0, NULL, 0);
	    if (debug_mode)
		fprintf(stderr, "\"%s\": hierre pass, excsre %s\n", s, retval ? "pass" : "fail");

	} else {
            retval = !regexec(&tradre, s, 0, NULL, 0);
	    if (debug_mode)
		fprintf(stderr, "\"%s\": tradre %s\n", s, retval ? "pass" : "fail");

	}
    } else {
        retval = !regexec(&classicalre, s, 0, NULL, 0);
	if (debug_mode)
	    fprintf(stderr, "\"%s\": classicalre %s\n", s, retval ? "pass" : "fail");

    }

    return retval;
}

/* Execute a file */
void run_part(char *progname)
{
  int result, waited;
  int pid, r;
  int pout[2], perr[2];

  waited = 0;

  if (report_mode && (pipe(pout) || pipe(perr))) {
    error("pipe: %s", strerror(errno));
    exit(1);
  }
  if ((pid = fork()) < 0) {
    error("failed to fork: %s", strerror(errno));
    exit(1);
  }
  else if (!pid) {
    restore_signals();
    if (new_session_mode)
      setsid();

    if (stdin_mode) {
      if (dup2(stdin_fd, STDIN_FILENO) == -1) {
        error("dup2: %s", strerror(errno));
        exit(1);
      }
      if (lseek(STDIN_FILENO, 0, SEEK_SET) == (off_t) -1) {
        error("run-parts: failed to rewind temporary file: %s\n", strerror(errno));
        exit(1);
      }
    }
    if (report_mode) {
      if (dup2(pout[1], STDOUT_FILENO) == -1 ||
	  dup2(perr[1], STDERR_FILENO) == -1) {
	error("dup2: %s", strerror(errno));
	exit(1);
      }
      close(pout[0]);
      close(perr[0]);
      close(pout[1]);
      close(perr[1]);
    }
    args[0] = progname;
    execv(progname, args);
    error("failed to exec %s: %s", progname, strerror(errno));
    exit(1);
  }

  if (report_mode) {
    fd_set set;
    sigset_t tempmask;
    struct timespec zero_timeout;
    struct timespec *the_timeout;
    int max, printflag;
    ssize_t c;
    char buf[4096];

    sigemptyset(&tempmask);
    sigprocmask(0, NULL, &tempmask);
    sigdelset(&tempmask, SIGCHLD);

    memset(&zero_timeout, 0, sizeof(zero_timeout));
    the_timeout = NULL;

    close(pout[1]);
    close(perr[1]);
    max = pout[0] > perr[0] ? pout[0] + 1 : perr[0] + 1;
    printflag = 0;

    while (pout[0] >= 0 || perr[0] >= 0) {
      if (!waited) {
        r = waitpid(pid, &result, WNOHANG);
        if (r == -1) {
          error("waitpid: %s", strerror(errno));
          exit(1);
        }
        if (r != 0 && (WIFEXITED(result) || WIFSIGNALED(result))) {
          /* If the process dies, set a zero timeout. Rarely, some processes
           * leak file descriptors (e.g., by starting a naughty daemon).
           * select() would wait forever since the pipes wouldn't close.
           * We loop, with a zero timeout, until there's no data left, then
           * give up. This shouldn't affect non-leaky processes. */
          waited = 1;
          the_timeout = &zero_timeout;
        }
      }

      FD_ZERO(&set);
      if (pout[0] >= 0)
        FD_SET(pout[0], &set);
      if (perr[0] >= 0)
        FD_SET(perr[0], &set);
      r = pselect(max, &set, 0, 0, the_timeout, &tempmask);

      if (r < 0) {
        if (errno == EINTR)
            continue;

        error("select: %s", strerror(errno));
        exit(1);
      }
      else if (r > 0) {
	/* If STDOUT or STDERR get closed / full, we still run to completion
	 * (and just ignore that we can't output process output any more).
	 * Perhaps we should instead kill the child process we are running
	 * if that happens.
	 * For now partial writes are not retried to complete - that can
	 * and should be done, but needs care to ensure that we don't hang
	 * if the fd doesn't accept more data ever - or we need to decide that
	 * waiting is the appropriate thing to do.
	 */
	int ignored;
	if (pout[0] >= 0 && FD_ISSET(pout[0], &set)) {
	  c = read(pout[0], buf, sizeof(buf));
	  if (c > 0) {
	    if (!printflag) {
	      printf("%s:\n", progname);
	      fflush(stdout);
	      printflag = 1;
	    }
	    ignored = write(STDOUT_FILENO, buf, c);
	  }
	  else if (c == 0) {
	    close(pout[0]);
	    pout[0] = -1;
	  }
	  else if (c < 0) {
	    close(pout[0]);
	    pout[0] = -1;
	    error("failed to read from stdout pipe: %s", strerror (errno));
	  }
	}
	if (perr[0] >= 0 && FD_ISSET(perr[0], &set)) {
	  c = read(perr[0], buf, sizeof(buf));
	  if (c > 0) {
	    if (!printflag) {
	      fprintf(stderr, "%s:\n", progname);
	      fflush(stderr);
	      printflag = 1;
	    }
	    ignored = write(STDERR_FILENO, buf, c);
	  }
	  else if (c == 0) {
	    close(perr[0]);
	    perr[0] = -1;
	  }
	  else if (c < 0) {
	    close(perr[0]);
	    perr[0] = -1;
	    error("failed to read from error pipe: %s", strerror (errno));
	  }
	}
      }
      else if (r == 0 && waited) {
        /* Zero timeout, no data left. */
        close(perr[0]);
        perr[0] = -1;
        close(pout[0]);
        pout[0] = -1;
      }
      else {
	/* assert(FALSE): select was called with infinite timeout, so
	   it either returns successfully or is interrupted */
      }				/*if */
    }				/*while */
  }

  if (!waited) {
    r = waitpid(pid, &result, 0);

    if (r == -1) {
		  error("waitpid: %s", strerror(errno));
			exit(1);
    }
  }

  if (WIFEXITED(result) && WEXITSTATUS(result)) {
    error("%s exited with return code %d", progname, WEXITSTATUS(result));
    exitstatus = WEXITSTATUS(result);
  }
  else if (WIFSIGNALED(result)) {
    error("%s exited because of uncaught signal %d", progname,
	  WTERMSIG(result));
    exitstatus = 1;
  }
}

static void handle_signal(int s)
{
    /* Do nothing */
}

/* Catch SIGCHLD with an empty function to interrupt select() */
static void catch_signals()
{
    struct sigaction act;
    sigset_t set;

    memset(&act, 0, sizeof(act));
    act.sa_handler = handle_signal;
    act.sa_flags = SA_NOCLDSTOP;
    sigaction(SIGCHLD, &act, NULL);

    sigemptyset(&set);
    sigaddset(&set, SIGCHLD);
    sigprocmask(SIG_BLOCK, &set, NULL);
}

/* Unblock signals before execing a child */
static void restore_signals()
{
    sigset_t set;
    sigemptyset(&set);
    sigaddset(&set, SIGCHLD);
    sigprocmask(SIG_UNBLOCK, &set, NULL);
}

#ifdef O_TMPFILE
static int open_tmpfile_rw(void)
{
	const char *tmpdir;

	tmpdir = getenv("TMPDIR");
	if (!tmpdir) {
		tmpdir = "/tmp";
	}

	return open(tmpdir, O_TMPFILE|O_RDWR|O_EXCL, S_IRUSR | S_IWUSR);
}
#else
static char tmpfile_path[] = "/tmp/run-parts.stdin.XXXXXX";
static void cleanup_tmpfile(void)
{
	unlink(tmpfile_path);
}

static int open_tmpfile_rw(void)
{
	int fd;

	fd = mkstemp(tmpfile_path);
	if (fd != -1) {
		atexit(&cleanup_tmpfile);
	}
	return fd;
}
#endif

/*
 * Copy stdin into temporary read-write file, and return file descriptor to it.
 */
static int copy_stdin(void)
{
  int fd;
  char buffer[4096];
  ssize_t bytes;

  fd = open_tmpfile_rw();

  do {
    ssize_t rest;

    bytes = rest = read(STDIN_FILENO, buffer, sizeof(buffer));
    if (bytes < 0) {
      error("run-parts: failed to read from stdin\n");
      close(fd);
      return -1;
    }

    while (rest > 0) {
      ssize_t written;

      written = write(fd, buffer, rest);
      if (written < 0) {
        error("run-parts: failed to write to temporary file\n");
        close(fd);
        return -1;
      }
      rest -= written;
    }
  } while (bytes > 0);

  return fd;
}

static int qsort_strcoll(const void *p1, const void *p2) {
  /* The actual arguments to this function are "pointers to
     pointers to char", but strcoll(3) arguments are "pointers
     to char", hence the following cast plus dereference. */
  return strcoll(*(const char **)p1, *(const char **)p2);
}

static int remove_dupes(char **list, int len) {
	if (len == 0) {
		return 0;
	}
	int j = 1;
	for (int i = 1; i < len; i++) {
		// compare each element with the one before
		if (strcmp(list[j-1], list[i]) == 0) {
			// found duplicate, free memory
			free(list[i]);
			continue;
		}
		// not a duplicate
		list[j] = list[i];
		j++;
	}
	return j;
}

/* Find the parts to run & call run_part() */
void run_parts(char **dirnames)
{
  struct stat st;

  /* 1st step: gather a list of all files in the given directories */

  char **basenames = NULL;
  int num_basenames = 0;
  for (int i = 0; dirnames[i] != NULL; i++) {
    DIR *dirfd = opendir(dirnames[i]);
    if (!dirfd) {
      continue;
    }
    struct dirent *dp;
    while ((dp = readdir(dirfd)) != NULL) {
      if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
        continue;
      }
      if (!valid_name(dp)) {
        continue;
      }
      num_basenames++;
      if (!(basenames = realloc(basenames, num_basenames * sizeof(char *)))) {
        error("failed to reallocate memory for basenames: %s", strerror(errno));
        exit(1);
      }
      basenames[num_basenames - 1] = strdup(dp->d_name);
    }
  }

  if (num_basenames == 0) {
    // nothing to do
    return;
  }

  /* 2nd step: sort that list with alphasort */

  qsort(basenames, num_basenames, sizeof(char *), qsort_strcoll);

  /* 3rd step: make the sorted list only contain unique elements */

  num_basenames = remove_dupes(basenames, num_basenames);
  if (!(basenames = realloc(basenames, num_basenames * sizeof(char *)))) {
    error("failed to reallocate memory for basenames: %s", strerror(errno));
    exit(1);
  }
  if (debug_mode) {
    fprintf(stderr, "list of unique basenames:\n");
    for (int i = 0; i < num_basenames; i++) {
      fprintf(stderr, " - %s\n", basenames[i]);
    }
  }

  /* 4th step: for each of the basenames, loop over the given directories
   *           and store the full path of the first directory in which a
   *           file with that basename was found */
  char **full_paths = NULL;
  int num_full_paths = 0;
  char *tmp_full_path = NULL;
  int max_full_path_length = 0;
  for (int i = 0; i < num_basenames; i++) {
    // Try to find the filename in each of the given directories, first match
    // wins.
    size_t basename_length = strlen(basenames[i]);
    for (int j = 0; dirnames[j] != NULL; j++) {
      size_t dirname_length = strlen(dirnames[j]);
      // check if we need to increase the buffer for the temporary full path
      if (max_full_path_length < basename_length + dirname_length + 2) {
        max_full_path_length = basename_length + dirname_length + 2;
        if (!(tmp_full_path = realloc(tmp_full_path, max_full_path_length))) {
          error("failed to reallocate memory for path: %s", strerror(errno));
          exit(1);
        }
      }
      strcpy(tmp_full_path, dirnames[j]);
      strcpy(tmp_full_path + dirname_length, "/");
      strcpy(tmp_full_path + dirname_length + 1, basenames[i]);
      if (debug_mode)
        fprintf(stderr, "checking %s... ", tmp_full_path);
      int result = stat(tmp_full_path, &st);
      if (result < 0) {
        if (debug_mode)
          fprintf(stderr, "not found\n");
        // not found in this directory, keep searching
        continue;
      }
      // this path exists, so do not search further directories for matches
      num_full_paths++;
      if (!(full_paths = realloc(full_paths, num_full_paths * sizeof(char *)))) {
        error("failed to reallocate memory for full paths: %s", strerror(errno));
        exit(1);
      }
      full_paths[num_full_paths - 1] = strdup(tmp_full_path);
      if (debug_mode)
        fprintf(stderr, "found\n");
      break;
    }
  }

  if (stdin_mode) {
    stdin_fd = copy_stdin();
    if (stdin_fd < 0) {
      error("run-parts: failed to copy content of stdin\n");
      exit(1);
    }
  }

  /* 5th step: process the list of full paths */
  for (int i = reverse_mode ? (num_full_paths - 1) : 0;
       reverse_mode ? (i >= 0) : (i < num_full_paths); reverse_mode ? i-- : i++) {
    char *filename = full_paths[i];
    if (debug_mode)
      fprintf(stderr, "processing: %s\n", filename);
    int result = stat(filename, &st);
    if (result < 0) {
      error("failed to stat component %s: %s", filename, strerror(errno));
      if (exit_on_error_mode) {
        exit(1);
      }
      else
        continue;
    }

    if (S_ISREG(st.st_mode)) {
      if (!access(filename, X_OK)) {
	if (test_mode) {
	  printf("%s\n", filename);
	}
	else if (list_mode) {
	  if (!access(filename, R_OK))
	    printf("%s\n", filename);
	}
	else {
	  if (verbose_mode) {
	    if (argcount) {
	      char **a = args;

	      fprintf(stderr, "run-parts: executing %s", filename);
	      while(*(++a))
		fprintf(stderr, " %s", *a);
	      fprintf(stderr, "\n");
	    } else {
	      fprintf(stderr, "run-parts: executing %s\n", filename);
	    }
	  }
	  run_part(filename);
	  if (exitstatus != 0 && exit_on_error_mode) return;
	}
      }
      else if (!access(filename, R_OK)) {
	if (list_mode) {
	  printf("%s\n", filename);
	}
      }
      else if (S_ISLNK(st.st_mode)) {
	if (!list_mode) {
	  error("run-parts: component %s is a broken symbolic link\n",filename);
	  exitstatus = 1;
	}
      }
    }
    else if (!S_ISDIR(st.st_mode)) {
      if (!list_mode) {
	error("run-parts: component %s is not an executable plain file\n",
	       filename);
	exitstatus = 1;
      }
    }

  }

  if (full_paths != NULL) {
    for (int i = 0; i < num_full_paths; i++) {
      free(full_paths[i]);
    }
    free(full_paths);
  }

  if (basenames != NULL) {
    for (int i = 0; i < num_basenames; i++) {
      free(basenames[i]);
    }
    free(basenames);
  }

}

/* Process options */
int main(int argc, char *argv[])
{
  custom_ere = NULL;
  umask(022);
  add_argument(0);

  for (;;) {
    int c;
    int option_index = 0;

    static struct option long_options[] = {
      {"test", 0, &test_mode, 1},
      {"list", 0, &list_mode, 1},
      {"verbose", 0, 0, 'v'},
      {"debug", 0, 0, 'd'},
      {"report", 0, &report_mode, 1},
      {"reverse", 0, &reverse_mode, 1},
      {"umask", 1, 0, 'u'},
      {"arg", 1, 0, 'a'},
      {"help", 0, 0, 'h'},
      {"version", 0, 0, 'V'},
      {"lsbsysinit", 0, &regex_mode, RUNPARTS_LSBSYSINIT},
      {"regex", 1, &regex_mode, RUNPARTS_ERE},
      {"stdin", 0, &stdin_mode, 1},
      {"exit-on-error", 0, &exit_on_error_mode, 1},
      {"new-session", 0, &new_session_mode, 1},
      {0, 0, 0, 0}
    };

    c = getopt_long(argc, argv, "u:ha:vV", long_options, &option_index);
    if (c == EOF)
      break;
    switch (c) {
    case 0:
      if(option_index==11) { /* hardcoding this will lead to trouble */
        custom_ere = strdup(optarg);
      }
      break;
    case 'u':
      set_umask();
      break;
    case 'a':
      add_argument(optarg);
      break;
    case 'h':
      usage();
      break;
    case 'v':
      verbose_mode = 1;
      break;
    case 'd':
      debug_mode = 1;
      break;
    case 'V':
      version();
      break;
    default:
      fprintf(stderr, "Try `run-parts --help' for more information.\n");
      exit(1);
    }
  }

  /* We require exactly one argument: the directory name */
  if (optind == argc) {
    error("missing operand");
    fprintf(stderr, "Try `run-parts --help' for more information.\n");
    exit(1);
  }

  if (list_mode && test_mode) {
    error("--list and --test can not be used together");
    fprintf(stderr, "Try `run-parts --help' for more information.\n");
    exit(1);
  }

  catch_signals();
  regex_compile_pattern();
  run_parts(argv+optind);
  regex_clean();

  free(args);
  free(custom_ere);

  return exitstatus;
}

/*
 * Compile patterns used by the application
 *
 * In order for a string to be matched by a pattern, this pattern must be
 * compiled with the regcomp function. If an error occurs, the application
 * exits and displays the error.
 */
static void
regex_compile_pattern (void)
{
    int      err;
    regex_t *pt_regex;

    if (regex_mode == RUNPARTS_ERE) {

        if ((err = regcomp(&customre, custom_ere,
                    REG_EXTENDED | REG_NOSUB)) != 0)
            pt_regex = &customre;

    } else if (regex_mode == RUNPARTS_LSBSYSINIT) {

        if ( (err = regcomp(&hierre, "^_?([a-z0-9_.]+-)+[a-z0-9]+$",
                    REG_EXTENDED | REG_NOSUB)) != 0)
            pt_regex = &hierre;

        else if ( (err = regcomp(&excsre, "^[a-z0-9-].*\\.dpkg-(old|dist|new|tmp)$",
                    REG_EXTENDED | REG_NOSUB)) != 0)
            pt_regex = &excsre;

        else if ( (err = regcomp(&tradre, "^[a-z0-9][a-z0-9_-]*$", REG_NOSUB))
                    != 0)
            pt_regex = &tradre;

    } else if ( (err = regcomp(&classicalre, "^[a-zA-Z0-9_-]+$",
                    REG_EXTENDED | REG_NOSUB)) != 0)
        pt_regex = &classicalre;

    if (err != 0) {
        fprintf(stderr, "Unable to build regexp: %s\n", \
                            regex_get_error(err, pt_regex));
        exit(1);
    }
}

/*
 * Get a regex error.
 *
 * This function allocates a buffer to store the regex error description.
 * If a buffer cannot be allocated, then the use of xmalloc will end the
 * program.
 *
 * @errcode: return error code from a one of the regex functions
 * @compiled: compile pattern which causes the failure
 *
 * It returns a pointer on the current regex error description.
 */
static char *
regex_get_error(int errcode, regex_t *compiled)
{
    size_t  length;
    char     *buf;

    length = regerror(errcode, compiled, NULL, 0);
    buf    = malloc(length);
    if (buf == 0) {
        error("Virtual memory exhausted\n");
        exit(1);
    }

    regerror(errcode, compiled, buf, length);

    return buf;
}

/*
 * Clean the compiled patterns according to the current regex_mode
 */
static void
regex_clean(void)
{
    if (regex_mode == RUNPARTS_ERE)
        regfree(&customre);

    else if (regex_mode == RUNPARTS_LSBSYSINIT) {
        regfree(&hierre);
        regfree(&excsre);
        regfree(&tradre);

    } else
        regfree(&classicalre);
}