/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: Björn Påhlsson
  • Date: 2011-10-02 19:18:24 UTC
  • mto: This revision was merged to the branch mainline in revision 505.
  • Revision ID: belorn@fukt.bsnet.se-20111002191824-eweh4pvneeg3qzia
transitional stuff actually working
documented change to D-Bus API

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