/mandos/trunk

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/trunk

« back to all changes in this revision

Viewing changes to plugin-runner.c

  • Committer: Teddy Hogeborn
  • Date: 2009-12-27 03:35:58 UTC
  • Revision ID: teddy@fukt.bsnet.se-20091227033558-y57wv1u4cls3i8kq
TODO file changes.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
/*  -*- coding: utf-8 -*- */
 
1
/*  -*- coding: utf-8; mode: c; mode: orgtbl -*- */
2
2
/*
3
3
 * Mandos plugin runner - Run Mandos plugins
4
4
 *
5
 
 * Copyright © 2008 Teddy Hogeborn & Björn Påhlsson
 
5
 * Copyright © 2008,2009 Teddy Hogeborn
 
6
 * Copyright © 2008,2009 Björn Påhlsson
6
7
 * 
7
8
 * This program is free software: you can redistribute it and/or
8
9
 * modify it under the terms of the GNU General Public License as
22
23
 */
23
24
 
24
25
#define _GNU_SOURCE             /* TEMP_FAILURE_RETRY(), getline(),
25
 
                                   asprintf() */
 
26
                                   asprintf(), O_CLOEXEC */
26
27
#include <stddef.h>             /* size_t, NULL */
27
 
#include <stdlib.h>             /* malloc(), exit(), EXIT_FAILURE,
28
 
                                   EXIT_SUCCESS, realloc() */
 
28
#include <stdlib.h>             /* malloc(), exit(), EXIT_SUCCESS,
 
29
                                   realloc() */
29
30
#include <stdbool.h>            /* bool, true, false */
30
31
#include <stdio.h>              /* perror, fileno(), fprintf(),
31
32
                                   stderr, STDOUT_FILENO */
32
 
#include <sys/types.h>          /* DIR, opendir(), stat(), struct
 
33
#include <sys/types.h>          /* DIR, fdopendir(), stat(), struct
33
34
                                   stat, waitpid(), WIFEXITED(),
34
35
                                   WEXITSTATUS(), wait(), pid_t,
35
36
                                   uid_t, gid_t, getuid(), getgid(),
37
38
#include <sys/select.h>         /* fd_set, select(), FD_ZERO(),
38
39
                                   FD_SET(), FD_ISSET(), FD_CLR */
39
40
#include <sys/wait.h>           /* wait(), waitpid(), WIFEXITED(),
40
 
                                   WEXITSTATUS() */
 
41
                                   WEXITSTATUS(), WTERMSIG(),
 
42
                                   WCOREDUMP() */
41
43
#include <sys/stat.h>           /* struct stat, stat(), S_ISREG() */
42
44
#include <iso646.h>             /* and, or, not */
43
 
#include <dirent.h>             /* DIR, struct dirent, opendir(),
 
45
#include <dirent.h>             /* DIR, struct dirent, fdopendir(),
44
46
                                   readdir(), closedir(), dirfd() */
45
47
#include <unistd.h>             /* struct stat, stat(), S_ISREG(),
46
48
                                   fcntl(), setuid(), setgid(),
51
53
                                   close() */
52
54
#include <fcntl.h>              /* fcntl(), F_GETFD, F_SETFD,
53
55
                                   FD_CLOEXEC */
54
 
#include <string.h>             /* strsep, strlen(), asprintf() */
 
56
#include <string.h>             /* strsep, strlen(), asprintf(),
 
57
                                   strsignal() */
55
58
#include <errno.h>              /* errno */
56
59
#include <argp.h>               /* struct argp_option, struct
57
60
                                   argp_state, struct argp,
61
64
#include <signal.h>             /* struct sigaction, sigemptyset(),
62
65
                                   sigaddset(), sigaction(),
63
66
                                   sigprocmask(), SIG_BLOCK, SIGCHLD,
64
 
                                   SIG_UNBLOCK, kill() */
 
67
                                   SIG_UNBLOCK, kill(), sig_atomic_t
 
68
                                */
65
69
#include <errno.h>              /* errno, EBADF */
 
70
#include <inttypes.h>           /* intmax_t, PRIdMAX, strtoimax() */
 
71
#include <sysexits.h>           /* EX_OSERR, EX_USAGE, EX_IOERR,
 
72
                                   EX_CONFIG, EX_UNAVAILABLE, EX_OK */
66
73
 
67
74
#define BUFFER_SIZE 256
68
75
 
79
86
  char **environ;
80
87
  int envc;
81
88
  bool disabled;
82
 
 
 
89
  
83
90
  /* Variables used for running processes*/
84
91
  pid_t pid;
85
92
  int fd;
87
94
  size_t buffer_size;
88
95
  size_t buffer_length;
89
96
  bool eof;
90
 
  volatile bool completed;
91
 
  volatile int status;
 
97
  volatile sig_atomic_t completed;
 
98
  int status;
92
99
  struct plugin *next;
93
100
} plugin;
94
101
 
97
104
/* Gets an existing plugin based on name,
98
105
   or if none is found, creates a new one */
99
106
static plugin *getplugin(char *name){
100
 
  /* Check for exiting plugin with that name */
101
 
  for (plugin *p = plugin_list; p != NULL; p = p->next){
102
 
    if ((p->name == name)
103
 
        or (p->name and name and (strcmp(p->name, name) == 0))){
 
107
  /* Check for existing plugin with that name */
 
108
  for(plugin *p = plugin_list; p != NULL; p = p->next){
 
109
    if((p->name == name)
 
110
       or (p->name and name and (strcmp(p->name, name) == 0))){
104
111
      return p;
105
112
    }
106
113
  }
107
114
  /* Create a new plugin */
108
 
  plugin *new_plugin = malloc(sizeof(plugin));
109
 
  if (new_plugin == NULL){
 
115
  plugin *new_plugin = NULL;
 
116
  do {
 
117
    new_plugin = malloc(sizeof(plugin));
 
118
  } while(new_plugin == NULL and errno == EINTR);
 
119
  if(new_plugin == NULL){
110
120
    return NULL;
111
121
  }
112
122
  char *copy_name = NULL;
113
123
  if(name != NULL){
114
 
    copy_name = strdup(name);
 
124
    do {
 
125
      copy_name = strdup(name);
 
126
    } while(copy_name == NULL and errno == EINTR);
115
127
    if(copy_name == NULL){
 
128
      int e = errno;
 
129
      free(new_plugin);
 
130
      errno = e;
116
131
      return NULL;
117
132
    }
118
133
  }
119
134
  
120
 
  *new_plugin = (plugin) { .name = copy_name,
121
 
                           .argc = 1,
122
 
                           .disabled = false,
123
 
                           .next = plugin_list };
 
135
  *new_plugin = (plugin){ .name = copy_name,
 
136
                          .argc = 1,
 
137
                          .disabled = false,
 
138
                          .next = plugin_list };
124
139
  
125
 
  new_plugin->argv = malloc(sizeof(char *) * 2);
126
 
  if (new_plugin->argv == NULL){
 
140
  do {
 
141
    new_plugin->argv = malloc(sizeof(char *) * 2);
 
142
  } while(new_plugin->argv == NULL and errno == EINTR);
 
143
  if(new_plugin->argv == NULL){
 
144
    int e = errno;
127
145
    free(copy_name);
128
146
    free(new_plugin);
 
147
    errno = e;
129
148
    return NULL;
130
149
  }
131
150
  new_plugin->argv[0] = copy_name;
132
151
  new_plugin->argv[1] = NULL;
133
152
  
134
 
  new_plugin->environ = malloc(sizeof(char *));
 
153
  do {
 
154
    new_plugin->environ = malloc(sizeof(char *));
 
155
  } while(new_plugin->environ == NULL and errno == EINTR);
135
156
  if(new_plugin->environ == NULL){
 
157
    int e = errno;
136
158
    free(copy_name);
137
159
    free(new_plugin->argv);
138
160
    free(new_plugin);
 
161
    errno = e;
139
162
    return NULL;
140
163
  }
141
164
  new_plugin->environ[0] = NULL;
149
172
static bool add_to_char_array(const char *new, char ***array,
150
173
                              int *len){
151
174
  /* Resize the pointed-to array to hold one more pointer */
152
 
  *array = realloc(*array, sizeof(char *)
153
 
                   * (size_t) ((*len) + 2));
 
175
  do {
 
176
    *array = realloc(*array, sizeof(char *)
 
177
                     * (size_t) ((*len) + 2));
 
178
  } while(*array == NULL and errno == EINTR);
154
179
  /* Malloc check */
155
180
  if(*array == NULL){
156
181
    return false;
157
182
  }
158
183
  /* Make a copy of the new string */
159
 
  char *copy = strdup(new);
 
184
  char *copy;
 
185
  do {
 
186
    copy = strdup(new);
 
187
  } while(copy == NULL and errno == EINTR);
160
188
  if(copy == NULL){
161
189
    return false;
162
190
  }
188
216
    if(strncmp(*e, def, namelen + 1) == 0){
189
217
      /* It already exists */
190
218
      if(replace){
191
 
        char *new = realloc(*e, strlen(def) + 1);
 
219
        char *new;
 
220
        do {
 
221
          new = realloc(*e, strlen(def) + 1);
 
222
        } while(new == NULL and errno == EINTR);
192
223
        if(new == NULL){
193
224
          return false;
194
225
        }
204
235
/*
205
236
 * Based on the example in the GNU LibC manual chapter 13.13 "File
206
237
 * Descriptor Flags".
207
 
 * *Note File Descriptor Flags:(libc)Descriptor Flags.
 
238
 | [[info:libc:Descriptor%20Flags][File Descriptor Flags]] |
208
239
 */
209
240
static int set_cloexec_flag(int fd){
210
 
  int ret = fcntl(fd, F_GETFD, 0);
 
241
  int ret = (int)TEMP_FAILURE_RETRY(fcntl(fd, F_GETFD, 0));
211
242
  /* If reading the flags failed, return error indication now. */
212
243
  if(ret < 0){
213
244
    return ret;
214
245
  }
215
246
  /* Store modified flag word in the descriptor. */
216
 
  return fcntl(fd, F_SETFD, ret | FD_CLOEXEC);
 
247
  return (int)TEMP_FAILURE_RETRY(fcntl(fd, F_SETFD,
 
248
                                       ret | FD_CLOEXEC));
217
249
}
218
250
 
219
251
 
220
252
/* Mark processes as completed when they exit, and save their exit
221
253
   status. */
222
254
static void handle_sigchld(__attribute__((unused)) int sig){
 
255
  int old_errno = errno;
223
256
  while(true){
224
257
    plugin *proc = plugin_list;
225
258
    int status;
229
262
      break;
230
263
    }
231
264
    if(pid == -1){
232
 
      if (errno != ECHILD){
233
 
        perror("waitpid");
 
265
      if(errno == ECHILD){
 
266
        /* No child processes */
 
267
        break;
234
268
      }
235
 
      /* No child processes */
236
 
      break;
 
269
      perror("waitpid");
237
270
    }
238
271
    
239
272
    /* A child exited, find it in process_list */
245
278
      continue;
246
279
    }
247
280
    proc->status = status;
248
 
    proc->completed = true;
 
281
    proc->completed = 1;
249
282
  }
 
283
  errno = old_errno;
250
284
}
251
285
 
252
286
/* Prints out a password to stdout */
274
308
  }
275
309
  free(plugin_node->environ);
276
310
  free(plugin_node->buffer);
277
 
 
 
311
  
278
312
  /* Removes the plugin from the singly-linked list */
279
313
  if(plugin_node == plugin_list){
280
314
    /* First one - simple */
308
342
  struct stat st;
309
343
  fd_set rfds_all;
310
344
  int ret, maxfd = 0;
 
345
  ssize_t sret;
311
346
  uid_t uid = 65534;
312
347
  gid_t gid = 65534;
313
348
  bool debug = false;
323
358
  ret = sigaddset(&sigchld_action.sa_mask, SIGCHLD);
324
359
  if(ret == -1){
325
360
    perror("sigaddset");
326
 
    exitstatus = EXIT_FAILURE;
 
361
    exitstatus = EX_OSERR;
327
362
    goto fallback;
328
363
  }
329
364
  ret = sigaction(SIGCHLD, &sigchld_action, &old_sigchld_action);
330
365
  if(ret == -1){
331
366
    perror("sigaction");
332
 
    exitstatus = EXIT_FAILURE;
 
367
    exitstatus = EX_OSERR;
333
368
    goto fallback;
334
369
  }
335
370
  
367
402
      .doc = "Group ID the plugins will run as", .group = 3 },
368
403
    { .name = "debug", .key = 132,
369
404
      .doc = "Debug mode", .group = 4 },
 
405
    /*
 
406
     * These reproduce what we would get without ARGP_NO_HELP
 
407
     */
 
408
    { .name = "help", .key = '?',
 
409
      .doc = "Give this help list", .group = -1 },
 
410
    { .name = "usage", .key = -3,
 
411
      .doc = "Give a short usage message", .group = -1 },
 
412
    { .name = "version", .key = 'V',
 
413
      .doc = "Print program version", .group = -1 },
370
414
    { .name = NULL }
371
415
  };
372
416
  
373
 
  error_t parse_opt (int key, char *arg, __attribute__((unused))
374
 
                     struct argp_state *state) {
375
 
    switch (key) {
 
417
  error_t parse_opt(int key, char *arg, struct argp_state *state){
 
418
    errno = 0;
 
419
    switch(key){
 
420
      char *tmp;
 
421
      intmax_t tmpmax;
376
422
    case 'g':                   /* --global-options */
377
 
      if (arg != NULL){
378
 
        char *p;
379
 
        while((p = strsep(&arg, ",")) != NULL){
380
 
          if(p[0] == '\0'){
381
 
            continue;
382
 
          }
383
 
          if(not add_argument(getplugin(NULL), p)){
384
 
            perror("add_argument");
385
 
            return ARGP_ERR_UNKNOWN;
 
423
      {
 
424
        char *plugin_option;
 
425
        while((plugin_option = strsep(&arg, ",")) != NULL){
 
426
          if(not add_argument(getplugin(NULL), plugin_option)){
 
427
            break;
386
428
          }
387
429
        }
388
430
      }
389
431
      break;
390
432
    case 'G':                   /* --global-env */
391
 
      if(arg == NULL){
392
 
        break;
393
 
      }
394
 
      if(not add_environment(getplugin(NULL), arg, true)){
395
 
        perror("add_environment");
396
 
      }
 
433
      add_environment(getplugin(NULL), arg, true);
397
434
      break;
398
435
    case 'o':                   /* --options-for */
399
 
      if (arg != NULL){
400
 
        char *p_name = strsep(&arg, ":");
401
 
        if(p_name[0] == '\0' or arg == NULL){
402
 
          break;
403
 
        }
404
 
        char *opt = strsep(&arg, ":");
405
 
        if(opt[0] == '\0' or opt == NULL){
406
 
          break;
407
 
        }
408
 
        char *p;
409
 
        while((p = strsep(&opt, ",")) != NULL){
410
 
          if(p[0] == '\0'){
411
 
            continue;
412
 
          }
413
 
          if(not add_argument(getplugin(p_name), p)){
414
 
            perror("add_argument");
415
 
            return ARGP_ERR_UNKNOWN;
 
436
      {
 
437
        char *option_list = strchr(arg, ':');
 
438
        if(option_list == NULL){
 
439
          argp_error(state, "No colon in \"%s\"", arg);
 
440
          errno = EINVAL;
 
441
          break;
 
442
        }
 
443
        *option_list = '\0';
 
444
        option_list++;
 
445
        if(arg[0] == '\0'){
 
446
          argp_error(state, "Empty plugin name");
 
447
          errno = EINVAL;
 
448
          break;
 
449
        }
 
450
        char *option;
 
451
        while((option = strsep(&option_list, ",")) != NULL){
 
452
          if(not add_argument(getplugin(arg), option)){
 
453
            break;
416
454
          }
417
455
        }
418
456
      }
419
457
      break;
420
458
    case 'E':                   /* --env-for */
421
 
      if(arg == NULL){
422
 
        break;
423
 
      }
424
459
      {
425
460
        char *envdef = strchr(arg, ':');
426
461
        if(envdef == NULL){
 
462
          argp_error(state, "No colon in \"%s\"", arg);
 
463
          errno = EINVAL;
427
464
          break;
428
465
        }
429
466
        *envdef = '\0';
430
 
        if(not add_environment(getplugin(arg), envdef+1, true)){
431
 
          perror("add_environment");
 
467
        envdef++;
 
468
        if(arg[0] == '\0'){
 
469
          argp_error(state, "Empty plugin name");
 
470
          errno = EINVAL;
 
471
          break;
432
472
        }
 
473
        add_environment(getplugin(arg), envdef, true);
433
474
      }
434
475
      break;
435
476
    case 'd':                   /* --disable */
436
 
      if (arg != NULL){
 
477
      {
437
478
        plugin *p = getplugin(arg);
438
 
        if(p == NULL){
439
 
          return ARGP_ERR_UNKNOWN;
 
479
        if(p != NULL){
 
480
          p->disabled = true;
440
481
        }
441
 
        p->disabled = true;
442
482
      }
443
483
      break;
444
484
    case 'e':                   /* --enable */
445
 
      if (arg != NULL){
 
485
      {
446
486
        plugin *p = getplugin(arg);
447
 
        if(p == NULL){
448
 
          return ARGP_ERR_UNKNOWN;
 
487
        if(p != NULL){
 
488
          p->disabled = false;
449
489
        }
450
 
        p->disabled = false;
451
490
      }
452
491
      break;
453
492
    case 128:                   /* --plugin-dir */
454
493
      free(plugindir);
455
494
      plugindir = strdup(arg);
456
 
      if(plugindir == NULL){
457
 
        perror("strdup");
458
 
      }      
459
495
      break;
460
496
    case 129:                   /* --config-file */
461
497
      /* This is already done by parse_opt_config_file() */
462
498
      break;
463
499
    case 130:                   /* --userid */
464
 
      uid = (uid_t)strtol(arg, NULL, 10);
 
500
      tmpmax = strtoimax(arg, &tmp, 10);
 
501
      if(errno != 0 or tmp == arg or *tmp != '\0'
 
502
         or tmpmax != (uid_t)tmpmax){
 
503
        argp_error(state, "Bad user ID number: \"%s\", using %"
 
504
                   PRIdMAX, arg, (intmax_t)uid);
 
505
        break;
 
506
      }
 
507
      uid = (uid_t)tmpmax;
465
508
      break;
466
509
    case 131:                   /* --groupid */
467
 
      gid = (gid_t)strtol(arg, NULL, 10);
 
510
      tmpmax = strtoimax(arg, &tmp, 10);
 
511
      if(errno != 0 or tmp == arg or *tmp != '\0'
 
512
         or tmpmax != (gid_t)tmpmax){
 
513
        argp_error(state, "Bad group ID number: \"%s\", using %"
 
514
                   PRIdMAX, arg, (intmax_t)gid);
 
515
        break;
 
516
      }
 
517
      gid = (gid_t)tmpmax;
468
518
      break;
469
519
    case 132:                   /* --debug */
470
520
      debug = true;
471
521
      break;
 
522
      /*
 
523
       * These reproduce what we would get without ARGP_NO_HELP
 
524
       */
 
525
    case '?':                   /* --help */
 
526
      state->flags &= ~(unsigned int)ARGP_NO_EXIT; /* force exit */
 
527
      argp_state_help(state, state->out_stream, ARGP_HELP_STD_HELP);
 
528
    case -3:                    /* --usage */
 
529
      state->flags &= ~(unsigned int)ARGP_NO_EXIT; /* force exit */
 
530
      argp_state_help(state, state->out_stream,
 
531
                      ARGP_HELP_USAGE | ARGP_HELP_EXIT_OK);
 
532
    case 'V':                   /* --version */
 
533
      fprintf(state->out_stream, "%s\n", argp_program_version);
 
534
      exit(EXIT_SUCCESS);
 
535
      break;
 
536
/*
 
537
 * When adding more options before this line, remember to also add a
 
538
 * "case" to the "parse_opt_config_file" function below.
 
539
 */
472
540
    case ARGP_KEY_ARG:
473
541
      /* Cryptsetup always passes an argument, which is an empty
474
542
         string if "none" was specified in /etc/crypttab.  So if
475
543
         argument was empty, we ignore it silently. */
476
 
      if(arg[0] != '\0'){
477
 
        fprintf(stderr, "Ignoring unknown argument \"%s\"\n", arg);
 
544
      if(arg[0] == '\0'){
 
545
        break;
478
546
      }
479
 
      break;
480
 
    case ARGP_KEY_END:
481
 
      break;
482
547
    default:
483
548
      return ARGP_ERR_UNKNOWN;
484
549
    }
485
 
    return 0;
 
550
    return errno;               /* Set to 0 at start */
486
551
  }
487
552
  
488
553
  /* This option parser is the same as parse_opt() above, except it
489
554
     ignores everything but the --config-file option. */
490
 
  error_t parse_opt_config_file (int key, char *arg,
491
 
                                 __attribute__((unused))
492
 
                                 struct argp_state *state) {
493
 
    switch (key) {
 
555
  error_t parse_opt_config_file(int key, char *arg,
 
556
                                __attribute__((unused))
 
557
                                struct argp_state *state){
 
558
    errno = 0;
 
559
    switch(key){
494
560
    case 'g':                   /* --global-options */
495
561
    case 'G':                   /* --global-env */
496
562
    case 'o':                   /* --options-for */
502
568
    case 129:                   /* --config-file */
503
569
      free(argfile);
504
570
      argfile = strdup(arg);
505
 
      if(argfile == NULL){
506
 
        perror("strdup");
507
 
      }
508
 
      break;      
 
571
      break;
509
572
    case 130:                   /* --userid */
510
573
    case 131:                   /* --groupid */
511
574
    case 132:                   /* --debug */
 
575
    case '?':                   /* --help */
 
576
    case -3:                    /* --usage */
 
577
    case 'V':                   /* --version */
512
578
    case ARGP_KEY_ARG:
513
 
    case ARGP_KEY_END:
514
579
      break;
515
580
    default:
516
581
      return ARGP_ERR_UNKNOWN;
517
582
    }
518
 
    return 0;
 
583
    return errno;
519
584
  }
520
585
  
521
586
  struct argp argp = { .options = options,
523
588
                       .args_doc = "",
524
589
                       .doc = "Mandos plugin runner -- Run plugins" };
525
590
  
526
 
  /* Parse using the parse_opt_config_file in order to get the custom
 
591
  /* Parse using parse_opt_config_file() in order to get the custom
527
592
     config file location, if any. */
528
 
  ret = argp_parse (&argp, argc, argv, ARGP_IN_ORDER, 0, NULL);
529
 
  if (ret == ARGP_ERR_UNKNOWN){
530
 
    fprintf(stderr, "Unknown error while parsing arguments\n");
531
 
    exitstatus = EXIT_FAILURE;
 
593
  ret = argp_parse(&argp, argc, argv,
 
594
                   ARGP_IN_ORDER | ARGP_NO_EXIT | ARGP_NO_HELP,
 
595
                   NULL, NULL);
 
596
  switch(ret){
 
597
  case 0:
 
598
    break;
 
599
  case ENOMEM:
 
600
  default:
 
601
    errno = ret;
 
602
    perror("argp_parse");
 
603
    exitstatus = EX_OSERR;
 
604
    goto fallback;
 
605
  case EINVAL:
 
606
    exitstatus = EX_USAGE;
532
607
    goto fallback;
533
608
  }
534
609
  
536
611
  argp.parser = parse_opt;
537
612
  
538
613
  /* Open the configfile if available */
539
 
  if (argfile == NULL){
 
614
  if(argfile == NULL){
540
615
    conffp = fopen(AFILE, "r");
541
616
  } else {
542
617
    conffp = fopen(argfile, "r");
543
 
  }  
 
618
  }
544
619
  if(conffp != NULL){
545
620
    char *org_line = NULL;
546
621
    char *p, *arg, *new_arg, *line;
547
622
    size_t size = 0;
548
 
    ssize_t sret;
549
623
    const char whitespace_delims[] = " \r\t\f\v\n";
550
624
    const char comment_delim[] = "#";
551
 
 
 
625
    
552
626
    custom_argc = 1;
553
627
    custom_argv = malloc(sizeof(char*) * 2);
554
628
    if(custom_argv == NULL){
555
629
      perror("malloc");
556
 
      exitstatus = EXIT_FAILURE;
 
630
      exitstatus = EX_OSERR;
557
631
      goto fallback;
558
632
    }
559
633
    custom_argv[0] = argv[0];
560
634
    custom_argv[1] = NULL;
561
 
 
 
635
    
562
636
    /* for each line in the config file, strip whitespace and ignore
563
637
       commented text */
564
638
    while(true){
566
640
      if(sret == -1){
567
641
        break;
568
642
      }
569
 
 
 
643
      
570
644
      line = org_line;
571
645
      arg = strsep(&line, comment_delim);
572
646
      while((p = strsep(&arg, whitespace_delims)) != NULL){
576
650
        new_arg = strdup(p);
577
651
        if(new_arg == NULL){
578
652
          perror("strdup");
579
 
          exitstatus = EXIT_FAILURE;
 
653
          exitstatus = EX_OSERR;
580
654
          free(org_line);
581
655
          goto fallback;
582
656
        }
586
660
                              * ((unsigned int) custom_argc + 1));
587
661
        if(custom_argv == NULL){
588
662
          perror("realloc");
589
 
          exitstatus = EXIT_FAILURE;
 
663
          exitstatus = EX_OSERR;
590
664
          free(org_line);
591
665
          goto fallback;
592
666
        }
593
667
        custom_argv[custom_argc-1] = new_arg;
594
 
        custom_argv[custom_argc] = NULL;        
 
668
        custom_argv[custom_argc] = NULL;
595
669
      }
596
670
    }
 
671
    do {
 
672
      ret = fclose(conffp);
 
673
    } while(ret == EOF and errno == EINTR);
 
674
    if(ret == EOF){
 
675
      perror("fclose");
 
676
      exitstatus = EX_IOERR;
 
677
      goto fallback;
 
678
    }
597
679
    free(org_line);
598
680
  } else {
599
681
    /* Check for harmful errors and go to fallback. Other errors might
600
682
       not affect opening plugins */
601
 
    if (errno == EMFILE or errno == ENFILE or errno == ENOMEM){
 
683
    if(errno == EMFILE or errno == ENFILE or errno == ENOMEM){
602
684
      perror("fopen");
603
 
      exitstatus = EXIT_FAILURE;
 
685
      exitstatus = EX_OSERR;
604
686
      goto fallback;
605
687
    }
606
688
  }
607
 
  /* If there was any arguments from configuration file,
608
 
     pass them to parser as command arguments */
 
689
  /* If there were any arguments from the configuration file, pass
 
690
     them to parser as command line arguments */
609
691
  if(custom_argv != NULL){
610
 
    ret = argp_parse (&argp, custom_argc, custom_argv, ARGP_IN_ORDER,
611
 
                      0, NULL);
612
 
    if (ret == ARGP_ERR_UNKNOWN){
613
 
      fprintf(stderr, "Unknown error while parsing arguments\n");
614
 
      exitstatus = EXIT_FAILURE;
 
692
    ret = argp_parse(&argp, custom_argc, custom_argv,
 
693
                     ARGP_IN_ORDER | ARGP_NO_EXIT | ARGP_NO_HELP,
 
694
                     NULL, NULL);
 
695
    switch(ret){
 
696
    case 0:
 
697
      break;
 
698
    case ENOMEM:
 
699
    default:
 
700
      errno = ret;
 
701
      perror("argp_parse");
 
702
      exitstatus = EX_OSERR;
 
703
      goto fallback;
 
704
    case EINVAL:
 
705
      exitstatus = EX_CONFIG;
615
706
      goto fallback;
616
707
    }
617
708
  }
618
709
  
619
710
  /* Parse actual command line arguments, to let them override the
620
711
     config file */
621
 
  ret = argp_parse (&argp, argc, argv, ARGP_IN_ORDER, 0, NULL);
622
 
  if (ret == ARGP_ERR_UNKNOWN){
623
 
    fprintf(stderr, "Unknown error while parsing arguments\n");
624
 
    exitstatus = EXIT_FAILURE;
 
712
  ret = argp_parse(&argp, argc, argv,
 
713
                   ARGP_IN_ORDER | ARGP_NO_EXIT | ARGP_NO_HELP,
 
714
                   NULL, NULL);
 
715
  switch(ret){
 
716
  case 0:
 
717
    break;
 
718
  case ENOMEM:
 
719
  default:
 
720
    errno = ret;
 
721
    perror("argp_parse");
 
722
    exitstatus = EX_OSERR;
 
723
    goto fallback;
 
724
  case EINVAL:
 
725
    exitstatus = EX_USAGE;
625
726
    goto fallback;
626
727
  }
627
728
  
632
733
      for(char **a = p->argv; *a != NULL; a++){
633
734
        fprintf(stderr, "\tArg: %s\n", *a);
634
735
      }
635
 
      fprintf(stderr, "...and %u environment variables\n", p->envc);
 
736
      fprintf(stderr, "...and %d environment variables\n", p->envc);
636
737
      for(char **a = p->environ; *a != NULL; a++){
637
738
        fprintf(stderr, "\t%s\n", *a);
638
739
      }
640
741
  }
641
742
  
642
743
  /* Strip permissions down to nobody */
 
744
  setgid(gid);
 
745
  if(ret == -1){
 
746
    perror("setgid");
 
747
  }
643
748
  ret = setuid(uid);
644
 
  if (ret == -1){
 
749
  if(ret == -1){
645
750
    perror("setuid");
646
 
  }  
647
 
  setgid(gid);
648
 
  if (ret == -1){
649
 
    perror("setgid");
650
 
  }
651
 
  
652
 
  if (plugindir == NULL){
653
 
    dir = opendir(PDIR);
654
 
  } else {
655
 
    dir = opendir(plugindir);
656
 
  }
657
 
  
658
 
  if(dir == NULL){
659
 
    perror("Could not open plugin dir");
660
 
    exitstatus = EXIT_FAILURE;
661
 
    goto fallback;
662
 
  }
663
 
  
664
 
  /* Set the FD_CLOEXEC flag on the directory, if possible */
 
751
  }
 
752
  
 
753
  /* Open plugin directory with close_on_exec flag */
665
754
  {
666
 
    int dir_fd = dirfd(dir);
667
 
    if(dir_fd >= 0){
668
 
      ret = set_cloexec_flag(dir_fd);
669
 
      if(ret < 0){
670
 
        perror("set_cloexec_flag");
671
 
        exitstatus = EXIT_FAILURE;
672
 
        goto fallback;
673
 
      }
 
755
    int dir_fd = -1;
 
756
    if(plugindir == NULL){
 
757
      dir_fd = open(PDIR, O_RDONLY |
 
758
#ifdef O_CLOEXEC
 
759
                    O_CLOEXEC
 
760
#else  /* not O_CLOEXEC */
 
761
                    0
 
762
#endif  /* not O_CLOEXEC */
 
763
                    );
 
764
    } else {
 
765
      dir_fd = open(plugindir, O_RDONLY |
 
766
#ifdef O_CLOEXEC
 
767
                    O_CLOEXEC
 
768
#else  /* not O_CLOEXEC */
 
769
                    0
 
770
#endif  /* not O_CLOEXEC */
 
771
                    );
 
772
    }
 
773
    if(dir_fd == -1){
 
774
      perror("Could not open plugin dir");
 
775
      exitstatus = EX_UNAVAILABLE;
 
776
      goto fallback;
 
777
    }
 
778
    
 
779
#ifndef O_CLOEXEC
 
780
  /* Set the FD_CLOEXEC flag on the directory */
 
781
    ret = set_cloexec_flag(dir_fd);
 
782
    if(ret < 0){
 
783
      perror("set_cloexec_flag");
 
784
      TEMP_FAILURE_RETRY(close(dir_fd));
 
785
      exitstatus = EX_OSERR;
 
786
      goto fallback;
 
787
    }
 
788
#endif  /* O_CLOEXEC */
 
789
    
 
790
    dir = fdopendir(dir_fd);
 
791
    if(dir == NULL){
 
792
      perror("Could not open plugin dir");
 
793
      TEMP_FAILURE_RETRY(close(dir_fd));
 
794
      exitstatus = EX_OSERR;
 
795
      goto fallback;
674
796
    }
675
797
  }
676
798
  
678
800
  
679
801
  /* Read and execute any executable in the plugin directory*/
680
802
  while(true){
681
 
    dirst = readdir(dir);
 
803
    do {
 
804
      dirst = readdir(dir);
 
805
    } while(dirst == NULL and errno == EINTR);
682
806
    
683
807
    /* All directory entries have been processed */
684
808
    if(dirst == NULL){
685
 
      if (errno == EBADF){
 
809
      if(errno == EBADF){
686
810
        perror("readdir");
687
 
        exitstatus = EXIT_FAILURE;
 
811
        exitstatus = EX_IOERR;
688
812
        goto fallback;
689
813
      }
690
814
      break;
700
824
      
701
825
      const char const *bad_suffixes[] = { "~", "#", ".dpkg-new",
702
826
                                           ".dpkg-old",
 
827
                                           ".dpkg-bak",
703
828
                                           ".dpkg-divert", NULL };
704
829
      for(const char **pre = bad_prefixes; *pre != NULL; pre++){
705
830
        size_t pre_len = strlen(*pre);
734
859
        continue;
735
860
      }
736
861
    }
737
 
 
 
862
    
738
863
    char *filename;
739
864
    if(plugindir == NULL){
740
 
      ret = asprintf(&filename, PDIR "/%s", dirst->d_name);
 
865
      ret = (int)TEMP_FAILURE_RETRY(asprintf(&filename, PDIR "/%s",
 
866
                                             dirst->d_name));
741
867
    } else {
742
 
      ret = asprintf(&filename, "%s/%s", plugindir, dirst->d_name);
 
868
      ret = (int)TEMP_FAILURE_RETRY(asprintf(&filename, "%s/%s",
 
869
                                             plugindir,
 
870
                                             dirst->d_name));
743
871
    }
744
872
    if(ret < 0){
745
873
      perror("asprintf");
746
874
      continue;
747
875
    }
748
876
    
749
 
    ret = stat(filename, &st);
750
 
    if (ret == -1){
 
877
    ret = (int)TEMP_FAILURE_RETRY(stat(filename, &st));
 
878
    if(ret == -1){
751
879
      perror("stat");
752
880
      free(filename);
753
881
      continue;
754
882
    }
755
 
 
 
883
    
756
884
    /* Ignore non-executable files */
757
 
    if (not S_ISREG(st.st_mode) or (access(filename, X_OK) != 0)){
 
885
    if(not S_ISREG(st.st_mode)
 
886
       or (TEMP_FAILURE_RETRY(access(filename, X_OK)) != 0)){
758
887
      if(debug){
759
888
        fprintf(stderr, "Ignoring plugin dir entry \"%s\""
760
889
                " with bad type or mode\n", filename);
806
935
    }
807
936
    
808
937
    int pipefd[2];
809
 
    ret = pipe(pipefd);
810
 
    if (ret == -1){
 
938
    ret = (int)TEMP_FAILURE_RETRY(pipe(pipefd));
 
939
    if(ret == -1){
811
940
      perror("pipe");
812
 
      exitstatus = EXIT_FAILURE;
 
941
      exitstatus = EX_OSERR;
813
942
      goto fallback;
814
943
    }
815
944
    /* Ask OS to automatic close the pipe on exec */
816
945
    ret = set_cloexec_flag(pipefd[0]);
817
946
    if(ret < 0){
818
947
      perror("set_cloexec_flag");
819
 
      exitstatus = EXIT_FAILURE;
 
948
      exitstatus = EX_OSERR;
820
949
      goto fallback;
821
950
    }
822
951
    ret = set_cloexec_flag(pipefd[1]);
823
952
    if(ret < 0){
824
953
      perror("set_cloexec_flag");
825
 
      exitstatus = EXIT_FAILURE;
 
954
      exitstatus = EX_OSERR;
826
955
      goto fallback;
827
956
    }
828
957
    /* Block SIGCHLD until process is safely in process list */
829
 
    ret = sigprocmask (SIG_BLOCK, &sigchld_action.sa_mask, NULL);
 
958
    ret = (int)TEMP_FAILURE_RETRY(sigprocmask(SIG_BLOCK,
 
959
                                              &sigchld_action.sa_mask,
 
960
                                              NULL));
830
961
    if(ret < 0){
831
962
      perror("sigprocmask");
832
 
      exitstatus = EXIT_FAILURE;
 
963
      exitstatus = EX_OSERR;
833
964
      goto fallback;
834
965
    }
835
966
    /* Starting a new process to be watched */
836
 
    pid_t pid = fork();
 
967
    pid_t pid;
 
968
    do {
 
969
      pid = fork();
 
970
    } while(pid == -1 and errno == EINTR);
837
971
    if(pid == -1){
838
972
      perror("fork");
839
 
      exitstatus = EXIT_FAILURE;
 
973
      exitstatus = EX_OSERR;
840
974
      goto fallback;
841
975
    }
842
976
    if(pid == 0){
844
978
      ret = sigaction(SIGCHLD, &old_sigchld_action, NULL);
845
979
      if(ret < 0){
846
980
        perror("sigaction");
847
 
        _exit(EXIT_FAILURE);
 
981
        _exit(EX_OSERR);
848
982
      }
849
983
      ret = sigprocmask(SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
850
984
      if(ret < 0){
851
985
        perror("sigprocmask");
852
 
        _exit(EXIT_FAILURE);
 
986
        _exit(EX_OSERR);
853
987
      }
854
988
      
855
989
      ret = dup2(pipefd[1], STDOUT_FILENO); /* replace our stdout */
856
990
      if(ret == -1){
857
991
        perror("dup2");
858
 
        _exit(EXIT_FAILURE);
 
992
        _exit(EX_OSERR);
859
993
      }
860
994
      
861
995
      if(dirfd(dir) < 0){
866
1000
      if(p->environ[0] == NULL){
867
1001
        if(execv(filename, p->argv) < 0){
868
1002
          perror("execv");
869
 
          _exit(EXIT_FAILURE);
 
1003
          _exit(EX_OSERR);
870
1004
        }
871
1005
      } else {
872
1006
        if(execve(filename, p->argv, p->environ) < 0){
873
1007
          perror("execve");
874
 
          _exit(EXIT_FAILURE);
 
1008
          _exit(EX_OSERR);
875
1009
        }
876
1010
      }
877
1011
      /* no return */
878
1012
    }
879
1013
    /* Parent process */
880
 
    close(pipefd[1]);           /* Close unused write end of pipe */
 
1014
    TEMP_FAILURE_RETRY(close(pipefd[1])); /* Close unused write end of
 
1015
                                             pipe */
881
1016
    free(filename);
882
1017
    plugin *new_plugin = getplugin(dirst->d_name);
883
 
    if (new_plugin == NULL){
 
1018
    if(new_plugin == NULL){
884
1019
      perror("getplugin");
885
 
      ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
 
1020
      ret = (int)(TEMP_FAILURE_RETRY
 
1021
                  (sigprocmask(SIG_UNBLOCK, &sigchld_action.sa_mask,
 
1022
                               NULL)));
886
1023
      if(ret < 0){
887
1024
        perror("sigprocmask");
888
1025
      }
889
 
      exitstatus = EXIT_FAILURE;
 
1026
      exitstatus = EX_OSERR;
890
1027
      goto fallback;
891
1028
    }
892
1029
    
895
1032
    
896
1033
    /* Unblock SIGCHLD so signal handler can be run if this process
897
1034
       has already completed */
898
 
    ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
 
1035
    ret = (int)TEMP_FAILURE_RETRY(sigprocmask(SIG_UNBLOCK,
 
1036
                                              &sigchld_action.sa_mask,
 
1037
                                              NULL));
899
1038
    if(ret < 0){
900
1039
      perror("sigprocmask");
901
 
      exitstatus = EXIT_FAILURE;
 
1040
      exitstatus = EX_OSERR;
902
1041
      goto fallback;
903
1042
    }
904
1043
    
905
 
    FD_SET(new_plugin->fd, &rfds_all);
 
1044
    FD_SET(new_plugin->fd, &rfds_all); /* Spurious warning from
 
1045
                                          -Wconversion */
906
1046
    
907
 
    if (maxfd < new_plugin->fd){
 
1047
    if(maxfd < new_plugin->fd){
908
1048
      maxfd = new_plugin->fd;
909
1049
    }
910
1050
  }
911
1051
  
912
 
  closedir(dir);
 
1052
  TEMP_FAILURE_RETRY(closedir(dir));
913
1053
  dir = NULL;
 
1054
  free_plugin(getplugin(NULL));
914
1055
  
915
1056
  for(plugin *p = plugin_list; p != NULL; p = p->next){
916
1057
    if(p->pid != 0){
927
1068
  while(plugin_list){
928
1069
    fd_set rfds = rfds_all;
929
1070
    int select_ret = select(maxfd+1, &rfds, NULL, NULL, NULL);
930
 
    if (select_ret == -1){
 
1071
    if(select_ret == -1 and errno != EINTR){
931
1072
      perror("select");
932
 
      exitstatus = EXIT_FAILURE;
 
1073
      exitstatus = EX_OSERR;
933
1074
      goto fallback;
934
1075
    }
935
1076
    /* OK, now either a process completed, or something can be read
936
1077
       from one of them */
937
1078
    for(plugin *proc = plugin_list; proc != NULL;){
938
1079
      /* Is this process completely done? */
939
 
      if(proc->eof and proc->completed){
 
1080
      if(proc->completed and proc->eof){
940
1081
        /* Only accept the plugin output if it exited cleanly */
941
1082
        if(not WIFEXITED(proc->status)
942
1083
           or WEXITSTATUS(proc->status) != 0){
943
1084
          /* Bad exit by plugin */
944
 
 
 
1085
          
945
1086
          if(debug){
946
1087
            if(WIFEXITED(proc->status)){
947
 
              fprintf(stderr, "Plugin %u exited with status %d\n",
948
 
                      (unsigned int) (proc->pid),
 
1088
              fprintf(stderr, "Plugin %s [%" PRIdMAX "] exited with"
 
1089
                      " status %d\n", proc->name,
 
1090
                      (intmax_t) (proc->pid),
949
1091
                      WEXITSTATUS(proc->status));
950
 
            } else if(WIFSIGNALED(proc->status)) {
951
 
              fprintf(stderr, "Plugin %u killed by signal %d\n",
952
 
                      (unsigned int) (proc->pid),
953
 
                      WTERMSIG(proc->status));
 
1092
            } else if(WIFSIGNALED(proc->status)){
 
1093
              fprintf(stderr, "Plugin %s [%" PRIdMAX "] killed by"
 
1094
                      " signal %d: %s\n", proc->name,
 
1095
                      (intmax_t) (proc->pid),
 
1096
                      WTERMSIG(proc->status),
 
1097
                      strsignal(WTERMSIG(proc->status)));
954
1098
            } else if(WCOREDUMP(proc->status)){
955
 
              fprintf(stderr, "Plugin %d dumped core\n",
956
 
                      (unsigned int) (proc->pid));
 
1099
              fprintf(stderr, "Plugin %s [%" PRIdMAX "] dumped"
 
1100
                      " core\n", proc->name, (intmax_t) (proc->pid));
957
1101
            }
958
1102
          }
959
1103
          
960
1104
          /* Remove the plugin */
961
 
          FD_CLR(proc->fd, &rfds_all);
962
 
 
 
1105
          FD_CLR(proc->fd, &rfds_all); /* Spurious warning from
 
1106
                                          -Wconversion */
 
1107
          
963
1108
          /* Block signal while modifying process_list */
964
 
          ret = sigprocmask(SIG_BLOCK, &sigchld_action.sa_mask, NULL);
 
1109
          ret = (int)TEMP_FAILURE_RETRY(sigprocmask
 
1110
                                        (SIG_BLOCK,
 
1111
                                         &sigchld_action.sa_mask,
 
1112
                                         NULL));
965
1113
          if(ret < 0){
966
1114
            perror("sigprocmask");
967
 
            exitstatus = EXIT_FAILURE;
 
1115
            exitstatus = EX_OSERR;
968
1116
            goto fallback;
969
1117
          }
970
1118
          
973
1121
          proc = next_plugin;
974
1122
          
975
1123
          /* We are done modifying process list, so unblock signal */
976
 
          ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask,
977
 
                             NULL);
 
1124
          ret = (int)(TEMP_FAILURE_RETRY
 
1125
                      (sigprocmask(SIG_UNBLOCK,
 
1126
                                   &sigchld_action.sa_mask, NULL)));
978
1127
          if(ret < 0){
979
1128
            perror("sigprocmask");
980
 
            exitstatus = EXIT_FAILURE;
 
1129
            exitstatus = EX_OSERR;
981
1130
            goto fallback;
982
1131
          }
983
1132
          
994
1143
                                       proc->buffer_length);
995
1144
        if(not bret){
996
1145
          perror("print_out_password");
997
 
          exitstatus = EXIT_FAILURE;
 
1146
          exitstatus = EX_IOERR;
998
1147
        }
999
1148
        goto fallback;
1000
1149
      }
1001
1150
      
1002
1151
      /* This process has not completed.  Does it have any output? */
1003
 
      if(proc->eof or not FD_ISSET(proc->fd, &rfds)){
 
1152
      if(proc->eof or not FD_ISSET(proc->fd, &rfds)){ /* Spurious
 
1153
                                                         warning from
 
1154
                                                         -Wconversion */
1004
1155
        /* This process had nothing to say at this time */
1005
1156
        proc = proc->next;
1006
1157
        continue;
1009
1160
      if(proc->buffer_length + BUFFER_SIZE > proc->buffer_size){
1010
1161
        proc->buffer = realloc(proc->buffer, proc->buffer_size
1011
1162
                               + (size_t) BUFFER_SIZE);
1012
 
        if (proc->buffer == NULL){
 
1163
        if(proc->buffer == NULL){
1013
1164
          perror("malloc");
1014
 
          exitstatus = EXIT_FAILURE;
 
1165
          exitstatus = EX_OSERR;
1015
1166
          goto fallback;
1016
1167
        }
1017
1168
        proc->buffer_size += BUFFER_SIZE;
1018
1169
      }
1019
1170
      /* Read from the process */
1020
 
      ret = read(proc->fd, proc->buffer + proc->buffer_length,
1021
 
                 BUFFER_SIZE);
1022
 
      if(ret < 0){
 
1171
      sret = TEMP_FAILURE_RETRY(read(proc->fd,
 
1172
                                     proc->buffer
 
1173
                                     + proc->buffer_length,
 
1174
                                     BUFFER_SIZE));
 
1175
      if(sret < 0){
1023
1176
        /* Read error from this process; ignore the error */
1024
1177
        proc = proc->next;
1025
1178
        continue;
1026
1179
      }
1027
 
      if(ret == 0){
 
1180
      if(sret == 0){
1028
1181
        /* got EOF */
1029
1182
        proc->eof = true;
1030
1183
      } else {
1031
 
        proc->buffer_length += (size_t) ret;
 
1184
        proc->buffer_length += (size_t) sret;
1032
1185
      }
1033
1186
    }
1034
1187
  }
1035
 
 
1036
 
 
 
1188
  
 
1189
  
1037
1190
 fallback:
1038
1191
  
1039
 
  if(plugin_list == NULL or exitstatus != EXIT_SUCCESS){
 
1192
  if(plugin_list == NULL or (exitstatus != EXIT_SUCCESS
 
1193
                             and exitstatus != EX_OK)){
1040
1194
    /* Fallback if all plugins failed, none are found or an error
1041
1195
       occured */
1042
1196
    bool bret;
1051
1205
    bret = print_out_password(passwordbuffer, len);
1052
1206
    if(not bret){
1053
1207
      perror("print_out_password");
1054
 
      exitstatus = EXIT_FAILURE;
 
1208
      exitstatus = EX_IOERR;
1055
1209
    }
1056
1210
  }
1057
1211
  
1059
1213
  ret = sigaction(SIGCHLD, &old_sigchld_action, NULL);
1060
1214
  if(ret == -1){
1061
1215
    perror("sigaction");
1062
 
    exitstatus = EXIT_FAILURE;
 
1216
    exitstatus = EX_OSERR;
1063
1217
  }
1064
1218
  
1065
1219
  if(custom_argv != NULL){
1086
1240
  }
1087
1241
  
1088
1242
  /* Wait for any remaining child processes to terminate */
1089
 
  do{
 
1243
  do {
1090
1244
    ret = wait(NULL);
1091
1245
  } while(ret >= 0);
1092
1246
  if(errno != ECHILD){