/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-10-30 16:23:43 UTC
  • Revision ID: teddy@fukt.bsnet.se-20091030162343-1p2a8bf3gc084kc9
* plugins.d/password-prompt.c: Use environment variables and prompt
                               text from cryptsetup 1.1.
* plugins.d/password-prompt.xml (ENVIRONMENT): Document change in
                                               environment variables
                                               used.

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