/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-09-08 04:41:37 UTC
  • Revision ID: teddy@fukt.bsnet.se-20090908044137-4cxubotvn4etoxxl
* plugins.d/mandos-client.c (main): Bug fix: Check result of setgid().
                                    Bug fix: If taking down network
                                    interface, do not drop privileges
                                    completely; save them and reassert
                                    privileges when needed.

Show diffs side-by-side

added added

removed removed

Lines of Context:
2
2
/*
3
3
 * Mandos plugin runner - Run Mandos plugins
4
4
 *
5
 
 * Copyright © 2008-2018 Teddy Hogeborn
6
 
 * Copyright © 2008-2018 Björn Påhlsson
7
 
 * 
8
 
 * This file is part of Mandos.
9
 
 * 
10
 
 * Mandos is free software: you can redistribute it and/or modify it
11
 
 * under the terms of the GNU General Public License as published by
12
 
 * the Free Software Foundation, either version 3 of the License, or
13
 
 * (at your option) any later version.
14
 
 * 
15
 
 * Mandos is distributed in the hope that it will be useful, but
 
5
 * Copyright © 2008,2009 Teddy Hogeborn
 
6
 * Copyright © 2008,2009 Björn Påhlsson
 
7
 * 
 
8
 * This program is free software: you can redistribute it and/or
 
9
 * modify it under the terms of the GNU General Public License as
 
10
 * published by the Free Software Foundation, either version 3 of the
 
11
 * License, or (at your option) any later version.
 
12
 * 
 
13
 * This program is distributed in the hope that it will be useful, but
16
14
 * WITHOUT ANY WARRANTY; without even the implied warranty of
17
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18
16
 * General Public License for more details.
19
17
 * 
20
18
 * You should have received a copy of the GNU General Public License
21
 
 * along with Mandos.  If not, see <http://www.gnu.org/licenses/>.
 
19
 * along with this program.  If not, see
 
20
 * <http://www.gnu.org/licenses/>.
22
21
 * 
23
 
 * Contact the authors at <mandos@recompile.se>.
 
22
 * Contact the authors at <mandos@fukt.bsnet.se>.
24
23
 */
25
24
 
26
25
#define _GNU_SOURCE             /* TEMP_FAILURE_RETRY(), getline(),
27
 
                                   O_CLOEXEC, pipe2() */
 
26
                                   asprintf() */
28
27
#include <stddef.h>             /* size_t, NULL */
29
 
#include <stdlib.h>             /* malloc(), exit(), EXIT_SUCCESS,
30
 
                                   realloc() */
 
28
#include <stdlib.h>             /* malloc(), exit(), EXIT_FAILURE,
 
29
                                   EXIT_SUCCESS, realloc() */
31
30
#include <stdbool.h>            /* bool, true, false */
32
 
#include <stdio.h>              /* fileno(), fprintf(),
33
 
                                   stderr, STDOUT_FILENO, fclose() */
34
 
#include <sys/types.h>          /* fstat(), struct stat, waitpid(),
35
 
                                   WIFEXITED(), WEXITSTATUS(), wait(),
36
 
                                   pid_t, uid_t, gid_t, getuid(),
37
 
                                   getgid() */
 
31
#include <stdio.h>              /* perror, fileno(), fprintf(),
 
32
                                   stderr, STDOUT_FILENO */
 
33
#include <sys/types.h>          /* DIR, opendir(), stat(), struct
 
34
                                   stat, waitpid(), WIFEXITED(),
 
35
                                   WEXITSTATUS(), wait(), pid_t,
 
36
                                   uid_t, gid_t, getuid(), getgid(),
 
37
                                   dirfd() */
38
38
#include <sys/select.h>         /* fd_set, select(), FD_ZERO(),
39
39
                                   FD_SET(), FD_ISSET(), FD_CLR */
40
40
#include <sys/wait.h>           /* wait(), waitpid(), WIFEXITED(),
41
 
                                   WEXITSTATUS(), WTERMSIG() */
42
 
#include <sys/stat.h>           /* struct stat, fstat(), S_ISREG() */
 
41
                                   WEXITSTATUS(), WTERMSIG(),
 
42
                                   WCOREDUMP() */
 
43
#include <sys/stat.h>           /* struct stat, stat(), S_ISREG() */
43
44
#include <iso646.h>             /* and, or, not */
44
 
#include <dirent.h>             /* struct dirent, scandirat() */
45
 
#include <unistd.h>             /* fcntl(), F_GETFD, F_SETFD,
46
 
                                   FD_CLOEXEC, write(), STDOUT_FILENO,
47
 
                                   struct stat, fstat(), close(),
48
 
                                   setgid(), setuid(), S_ISREG(),
49
 
                                   faccessat() pipe2(), fork(),
50
 
                                   _exit(), dup2(), fexecve(), read()
51
 
                                */
 
45
#include <dirent.h>             /* DIR, struct dirent, opendir(),
 
46
                                   readdir(), closedir(), dirfd() */
 
47
#include <unistd.h>             /* struct stat, stat(), S_ISREG(),
 
48
                                   fcntl(), setuid(), setgid(),
 
49
                                   F_GETFD, F_SETFD, FD_CLOEXEC,
 
50
                                   access(), pipe(), fork(), close()
 
51
                                   dup2(), STDOUT_FILENO, _exit(),
 
52
                                   execv(), write(), read(),
 
53
                                   close() */
52
54
#include <fcntl.h>              /* fcntl(), F_GETFD, F_SETFD,
53
 
                                   FD_CLOEXEC, openat(), scandirat(),
54
 
                                   pipe2() */
55
 
#include <string.h>             /* strsep, strlen(), strsignal(),
56
 
                                   strcmp(), strncmp() */
 
55
                                   FD_CLOEXEC */
 
56
#include <string.h>             /* strsep, strlen(), asprintf(),
 
57
                                   strsignal() */
57
58
#include <errno.h>              /* errno */
58
59
#include <argp.h>               /* struct argp_option, struct
59
60
                                   argp_state, struct argp,
67
68
                                */
68
69
#include <errno.h>              /* errno, EBADF */
69
70
#include <inttypes.h>           /* intmax_t, PRIdMAX, strtoimax() */
70
 
#include <sysexits.h>           /* EX_OSERR, EX_USAGE, EX_IOERR,
71
 
                                   EX_CONFIG, EX_UNAVAILABLE, EX_OK */
72
 
#include <errno.h>              /* errno */
73
 
#include <error.h>              /* error() */
74
 
#include <fnmatch.h>            /* fnmatch() */
75
71
 
76
72
#define BUFFER_SIZE 256
77
73
 
78
74
#define PDIR "/lib/mandos/plugins.d"
79
 
#define PHDIR "/lib/mandos/plugin-helpers"
80
75
#define AFILE "/conf/conf.d/mandos/plugin-runner.conf"
81
76
 
82
77
const char *argp_program_version = "plugin-runner " VERSION;
83
 
const char *argp_program_bug_address = "<mandos@recompile.se>";
 
78
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
84
79
 
85
80
typedef struct plugin{
86
81
  char *name;                   /* can be NULL or any plugin name */
106
101
 
107
102
/* Gets an existing plugin based on name,
108
103
   or if none is found, creates a new one */
109
 
__attribute__((warn_unused_result))
110
104
static plugin *getplugin(char *name){
111
 
  /* Check for existing plugin with that name */
 
105
  /* Check for exiting plugin with that name */
112
106
  for(plugin *p = plugin_list; p != NULL; p = p->next){
113
107
    if((p->name == name)
114
108
       or (p->name and name and (strcmp(p->name, name) == 0))){
129
123
      copy_name = strdup(name);
130
124
    } while(copy_name == NULL and errno == EINTR);
131
125
    if(copy_name == NULL){
132
 
      int e = errno;
133
126
      free(new_plugin);
134
 
      errno = e;
135
127
      return NULL;
136
128
    }
137
129
  }
145
137
    new_plugin->argv = malloc(sizeof(char *) * 2);
146
138
  } while(new_plugin->argv == NULL and errno == EINTR);
147
139
  if(new_plugin->argv == NULL){
148
 
    int e = errno;
149
140
    free(copy_name);
150
141
    free(new_plugin);
151
 
    errno = e;
152
142
    return NULL;
153
143
  }
154
144
  new_plugin->argv[0] = copy_name;
158
148
    new_plugin->environ = malloc(sizeof(char *));
159
149
  } while(new_plugin->environ == NULL and errno == EINTR);
160
150
  if(new_plugin->environ == NULL){
161
 
    int e = errno;
162
151
    free(copy_name);
163
152
    free(new_plugin->argv);
164
153
    free(new_plugin);
165
 
    errno = e;
166
154
    return NULL;
167
155
  }
168
156
  new_plugin->environ[0] = NULL;
173
161
}
174
162
 
175
163
/* Helper function for add_argument and add_environment */
176
 
__attribute__((nonnull, warn_unused_result))
177
164
static bool add_to_char_array(const char *new, char ***array,
178
165
                              int *len){
179
166
  /* Resize the pointed-to array to hold one more pointer */
180
 
  char **new_array = NULL;
181
167
  do {
182
 
    new_array = realloc(*array, sizeof(char *)
183
 
                        * (size_t) ((*len) + 2));
184
 
  } while(new_array == NULL and errno == EINTR);
 
168
    *array = realloc(*array, sizeof(char *)
 
169
                     * (size_t) ((*len) + 2));
 
170
  } while(*array == NULL and errno == EINTR);
185
171
  /* Malloc check */
186
 
  if(new_array == NULL){
 
172
  if(*array == NULL){
187
173
    return false;
188
174
  }
189
 
  *array = new_array;
190
175
  /* Make a copy of the new string */
191
176
  char *copy;
192
177
  do {
204
189
}
205
190
 
206
191
/* Add to a plugin's argument vector */
207
 
__attribute__((nonnull(2), warn_unused_result))
208
192
static bool add_argument(plugin *p, const char *arg){
209
193
  if(p == NULL){
210
194
    return false;
213
197
}
214
198
 
215
199
/* Add to a plugin's environment */
216
 
__attribute__((nonnull(2), warn_unused_result))
217
200
static bool add_environment(plugin *p, const char *def, bool replace){
218
201
  if(p == NULL){
219
202
    return false;
221
204
  /* namelen = length of name of environment variable */
222
205
  size_t namelen = (size_t)(strchrnul(def, '=') - def);
223
206
  /* Search for this environment variable */
224
 
  for(char **envdef = p->environ; *envdef != NULL; envdef++){
225
 
    if(strncmp(*envdef, def, namelen + 1) == 0){
 
207
  for(char **e = p->environ; *e != NULL; e++){
 
208
    if(strncmp(*e, def, namelen + 1) == 0){
226
209
      /* It already exists */
227
210
      if(replace){
228
 
        char *new_envdef;
 
211
        char *new;
229
212
        do {
230
 
          new_envdef = realloc(*envdef, strlen(def) + 1);
231
 
        } while(new_envdef == NULL and errno == EINTR);
232
 
        if(new_envdef == NULL){
 
213
          new = realloc(*e, strlen(def) + 1);
 
214
        } while(new == NULL and errno == EINTR);
 
215
        if(new == NULL){
233
216
          return false;
234
217
        }
235
 
        *envdef = new_envdef;
236
 
        strcpy(*envdef, def);
 
218
        *e = new;
 
219
        strcpy(*e, def);
237
220
      }
238
221
      return true;
239
222
    }
241
224
  return add_to_char_array(def, &(p->environ), &(p->envc));
242
225
}
243
226
 
244
 
#ifndef O_CLOEXEC
245
227
/*
246
228
 * Based on the example in the GNU LibC manual chapter 13.13 "File
247
229
 * Descriptor Flags".
248
230
 | [[info:libc:Descriptor%20Flags][File Descriptor Flags]] |
249
231
 */
250
 
__attribute__((warn_unused_result))
251
232
static int set_cloexec_flag(int fd){
252
 
  int ret = (int)TEMP_FAILURE_RETRY(fcntl(fd, F_GETFD, 0));
 
233
  int ret = TEMP_FAILURE_RETRY(fcntl(fd, F_GETFD, 0));
253
234
  /* If reading the flags failed, return error indication now. */
254
235
  if(ret < 0){
255
236
    return ret;
256
237
  }
257
238
  /* Store modified flag word in the descriptor. */
258
 
  return (int)TEMP_FAILURE_RETRY(fcntl(fd, F_SETFD,
259
 
                                       ret | FD_CLOEXEC));
 
239
  return TEMP_FAILURE_RETRY(fcntl(fd, F_SETFD, ret | FD_CLOEXEC));
260
240
}
261
 
#endif  /* not O_CLOEXEC */
262
241
 
263
242
 
264
243
/* Mark processes as completed when they exit, and save their exit
278
257
        /* No child processes */
279
258
        break;
280
259
      }
281
 
      error(0, errno, "waitpid");
 
260
      perror("waitpid");
282
261
    }
283
262
    
284
263
    /* A child exited, find it in process_list */
296
275
}
297
276
 
298
277
/* Prints out a password to stdout */
299
 
__attribute__((nonnull, warn_unused_result))
300
278
static bool print_out_password(const char *buffer, size_t length){
301
279
  ssize_t ret;
302
280
  for(size_t written = 0; written < length; written += (size_t)ret){
310
288
}
311
289
 
312
290
/* Removes and free a plugin from the plugin list */
313
 
__attribute__((nonnull))
314
291
static void free_plugin(plugin *plugin_node){
315
292
  
316
293
  for(char **arg = plugin_node->argv; *arg != NULL; arg++){
348
325
 
349
326
int main(int argc, char *argv[]){
350
327
  char *plugindir = NULL;
351
 
  char *pluginhelperdir = NULL;
352
328
  char *argfile = NULL;
353
329
  FILE *conffp;
354
 
  struct dirent **direntries = NULL;
 
330
  size_t d_name_len;
 
331
  DIR *dir = NULL;
 
332
  struct dirent *dirst;
355
333
  struct stat st;
356
334
  fd_set rfds_all;
357
335
  int ret, maxfd = 0;
365
343
                                      .sa_flags = SA_NOCLDSTOP };
366
344
  char **custom_argv = NULL;
367
345
  int custom_argc = 0;
368
 
  int dir_fd = -1;
369
346
  
370
347
  /* Establish a signal handler */
371
348
  sigemptyset(&sigchld_action.sa_mask);
372
349
  ret = sigaddset(&sigchld_action.sa_mask, SIGCHLD);
373
350
  if(ret == -1){
374
 
    error(0, errno, "sigaddset");
375
 
    exitstatus = EX_OSERR;
 
351
    perror("sigaddset");
 
352
    exitstatus = EXIT_FAILURE;
376
353
    goto fallback;
377
354
  }
378
355
  ret = sigaction(SIGCHLD, &sigchld_action, &old_sigchld_action);
379
356
  if(ret == -1){
380
 
    error(0, errno, "sigaction");
381
 
    exitstatus = EX_OSERR;
 
357
    perror("sigaction");
 
358
    exitstatus = EXIT_FAILURE;
382
359
    goto fallback;
383
360
  }
384
361
  
416
393
      .doc = "Group ID the plugins will run as", .group = 3 },
417
394
    { .name = "debug", .key = 132,
418
395
      .doc = "Debug mode", .group = 4 },
419
 
    { .name = "plugin-helper-dir", .key = 133,
420
 
      .arg = "DIRECTORY",
421
 
      .doc = "Specify a different plugin helper directory",
422
 
      .group = 2 },
423
 
    /*
424
 
     * These reproduce what we would get without ARGP_NO_HELP
425
 
     */
426
 
    { .name = "help", .key = '?',
427
 
      .doc = "Give this help list", .group = -1 },
428
 
    { .name = "usage", .key = -3,
429
 
      .doc = "Give a short usage message", .group = -1 },
430
 
    { .name = "version", .key = 'V',
431
 
      .doc = "Print program version", .group = -1 },
432
396
    { .name = NULL }
433
397
  };
434
398
  
435
 
  __attribute__((nonnull(3)))
436
 
  error_t parse_opt(int key, char *arg, struct argp_state *state){
437
 
    errno = 0;
 
399
  error_t parse_opt(int key, char *arg, __attribute__((unused))
 
400
                    struct argp_state *state){
438
401
    switch(key){
439
402
      char *tmp;
440
 
      intmax_t tmp_id;
 
403
      intmax_t tmpmax;
441
404
    case 'g':                   /* --global-options */
442
 
      {
 
405
      if(arg != NULL){
443
406
        char *plugin_option;
444
407
        while((plugin_option = strsep(&arg, ",")) != NULL){
 
408
          if(plugin_option[0] == '\0'){
 
409
            continue;
 
410
          }
445
411
          if(not add_argument(getplugin(NULL), plugin_option)){
446
 
            break;
 
412
            perror("add_argument");
 
413
            return ARGP_ERR_UNKNOWN;
447
414
          }
448
415
        }
449
 
        errno = 0;
450
416
      }
451
417
      break;
452
418
    case 'G':                   /* --global-env */
453
 
      if(add_environment(getplugin(NULL), arg, true)){
454
 
        errno = 0;
 
419
      if(arg == NULL){
 
420
        break;
 
421
      }
 
422
      if(not add_environment(getplugin(NULL), arg, true)){
 
423
        perror("add_environment");
455
424
      }
456
425
      break;
457
426
    case 'o':                   /* --options-for */
458
 
      {
459
 
        char *option_list = strchr(arg, ':');
460
 
        if(option_list == NULL){
461
 
          argp_error(state, "No colon in \"%s\"", arg);
462
 
          errno = EINVAL;
463
 
          break;
464
 
        }
465
 
        *option_list = '\0';
466
 
        option_list++;
467
 
        if(arg[0] == '\0'){
468
 
          argp_error(state, "Empty plugin name");
469
 
          errno = EINVAL;
470
 
          break;
471
 
        }
472
 
        char *option;
473
 
        while((option = strsep(&option_list, ",")) != NULL){
474
 
          if(not add_argument(getplugin(arg), option)){
475
 
            break;
 
427
      if(arg != NULL){
 
428
        char *plugin_name = strsep(&arg, ":");
 
429
        if(plugin_name[0] == '\0'){
 
430
          break;
 
431
        }
 
432
        char *plugin_option;
 
433
        while((plugin_option = strsep(&arg, ",")) != NULL){
 
434
          if(not add_argument(getplugin(plugin_name), plugin_option)){
 
435
            perror("add_argument");
 
436
            return ARGP_ERR_UNKNOWN;
476
437
          }
477
438
        }
478
 
        errno = 0;
479
439
      }
480
440
      break;
481
441
    case 'E':                   /* --env-for */
 
442
      if(arg == NULL){
 
443
        break;
 
444
      }
482
445
      {
483
446
        char *envdef = strchr(arg, ':');
484
447
        if(envdef == NULL){
485
 
          argp_error(state, "No colon in \"%s\"", arg);
486
 
          errno = EINVAL;
487
448
          break;
488
449
        }
489
450
        *envdef = '\0';
490
 
        envdef++;
491
 
        if(arg[0] == '\0'){
492
 
          argp_error(state, "Empty plugin name");
493
 
          errno = EINVAL;
494
 
          break;
495
 
        }
496
 
        if(add_environment(getplugin(arg), envdef, true)){
497
 
          errno = 0;
 
451
        if(not add_environment(getplugin(arg), envdef+1, true)){
 
452
          perror("add_environment");
498
453
        }
499
454
      }
500
455
      break;
501
456
    case 'd':                   /* --disable */
502
 
      {
 
457
      if(arg != NULL){
503
458
        plugin *p = getplugin(arg);
504
 
        if(p != NULL){
505
 
          p->disabled = true;
506
 
          errno = 0;
 
459
        if(p == NULL){
 
460
          return ARGP_ERR_UNKNOWN;
507
461
        }
 
462
        p->disabled = true;
508
463
      }
509
464
      break;
510
465
    case 'e':                   /* --enable */
511
 
      {
 
466
      if(arg != NULL){
512
467
        plugin *p = getplugin(arg);
513
 
        if(p != NULL){
514
 
          p->disabled = false;
515
 
          errno = 0;
 
468
        if(p == NULL){
 
469
          return ARGP_ERR_UNKNOWN;
516
470
        }
 
471
        p->disabled = false;
517
472
      }
518
473
      break;
519
474
    case 128:                   /* --plugin-dir */
520
475
      free(plugindir);
521
476
      plugindir = strdup(arg);
522
 
      if(plugindir != NULL){
523
 
        errno = 0;
 
477
      if(plugindir == NULL){
 
478
        perror("strdup");
524
479
      }
525
480
      break;
526
481
    case 129:                   /* --config-file */
527
482
      /* This is already done by parse_opt_config_file() */
528
483
      break;
529
484
    case 130:                   /* --userid */
530
 
      tmp_id = strtoimax(arg, &tmp, 10);
 
485
      errno = 0;
 
486
      tmpmax = strtoimax(arg, &tmp, 10);
531
487
      if(errno != 0 or tmp == arg or *tmp != '\0'
532
 
         or tmp_id != (uid_t)tmp_id){
533
 
        argp_error(state, "Bad user ID number: \"%s\", using %"
534
 
                   PRIdMAX, arg, (intmax_t)uid);
535
 
        break;
 
488
         or tmpmax != (uid_t)tmpmax){
 
489
        fprintf(stderr, "Bad user ID number: \"%s\", using %"
 
490
                PRIdMAX "\n", arg, (intmax_t)uid);
 
491
      } else {
 
492
        uid = (uid_t)tmpmax;
536
493
      }
537
 
      uid = (uid_t)tmp_id;
538
 
      errno = 0;
539
494
      break;
540
495
    case 131:                   /* --groupid */
541
 
      tmp_id = strtoimax(arg, &tmp, 10);
 
496
      errno = 0;
 
497
      tmpmax = strtoimax(arg, &tmp, 10);
542
498
      if(errno != 0 or tmp == arg or *tmp != '\0'
543
 
         or tmp_id != (gid_t)tmp_id){
544
 
        argp_error(state, "Bad group ID number: \"%s\", using %"
545
 
                   PRIdMAX, arg, (intmax_t)gid);
546
 
        break;
 
499
         or tmpmax != (gid_t)tmpmax){
 
500
        fprintf(stderr, "Bad group ID number: \"%s\", using %"
 
501
                PRIdMAX "\n", arg, (intmax_t)gid);
 
502
      } else {
 
503
        gid = (gid_t)tmpmax;
547
504
      }
548
 
      gid = (gid_t)tmp_id;
549
 
      errno = 0;
550
505
      break;
551
506
    case 132:                   /* --debug */
552
507
      debug = true;
553
508
      break;
554
 
    case 133:                   /* --plugin-helper-dir */
555
 
      free(pluginhelperdir);
556
 
      pluginhelperdir = strdup(arg);
557
 
      if(pluginhelperdir != NULL){
558
 
        errno = 0;
559
 
      }
560
 
      break;
561
 
      /*
562
 
       * These reproduce what we would get without ARGP_NO_HELP
563
 
       */
564
 
    case '?':                   /* --help */
565
 
      state->flags &= ~(unsigned int)ARGP_NO_EXIT; /* force exit */
566
 
      argp_state_help(state, state->out_stream, ARGP_HELP_STD_HELP);
567
 
    case -3:                    /* --usage */
568
 
      state->flags &= ~(unsigned int)ARGP_NO_EXIT; /* force exit */
569
 
      argp_state_help(state, state->out_stream,
570
 
                      ARGP_HELP_USAGE | ARGP_HELP_EXIT_OK);
571
 
    case 'V':                   /* --version */
572
 
      fprintf(state->out_stream, "%s\n", argp_program_version);
573
 
      exit(EXIT_SUCCESS);
574
 
      break;
575
509
/*
576
510
 * When adding more options before this line, remember to also add a
577
511
 * "case" to the "parse_opt_config_file" function below.
580
514
      /* Cryptsetup always passes an argument, which is an empty
581
515
         string if "none" was specified in /etc/crypttab.  So if
582
516
         argument was empty, we ignore it silently. */
583
 
      if(arg[0] == '\0'){
584
 
        break;
 
517
      if(arg[0] != '\0'){
 
518
        fprintf(stderr, "Ignoring unknown argument \"%s\"\n", arg);
585
519
      }
586
 
      /* FALLTHROUGH */
 
520
      break;
 
521
    case ARGP_KEY_END:
 
522
      break;
587
523
    default:
588
524
      return ARGP_ERR_UNKNOWN;
589
525
    }
590
 
    return errno;               /* Set to 0 at start */
 
526
    return 0;
591
527
  }
592
528
  
593
529
  /* This option parser is the same as parse_opt() above, except it
595
531
  error_t parse_opt_config_file(int key, char *arg,
596
532
                                __attribute__((unused))
597
533
                                struct argp_state *state){
598
 
    errno = 0;
599
534
    switch(key){
600
535
    case 'g':                   /* --global-options */
601
536
    case 'G':                   /* --global-env */
608
543
    case 129:                   /* --config-file */
609
544
      free(argfile);
610
545
      argfile = strdup(arg);
611
 
      if(argfile != NULL){
612
 
        errno = 0;
 
546
      if(argfile == NULL){
 
547
        perror("strdup");
613
548
      }
614
549
      break;
615
550
    case 130:                   /* --userid */
616
551
    case 131:                   /* --groupid */
617
552
    case 132:                   /* --debug */
618
 
    case 133:                   /* --plugin-helper-dir */
619
 
    case '?':                   /* --help */
620
 
    case -3:                    /* --usage */
621
 
    case 'V':                   /* --version */
622
553
    case ARGP_KEY_ARG:
 
554
    case ARGP_KEY_END:
623
555
      break;
624
556
    default:
625
557
      return ARGP_ERR_UNKNOWN;
626
558
    }
627
 
    return errno;
 
559
    return 0;
628
560
  }
629
561
  
630
562
  struct argp argp = { .options = options,
634
566
  
635
567
  /* Parse using parse_opt_config_file() in order to get the custom
636
568
     config file location, if any. */
637
 
  ret = argp_parse(&argp, argc, argv,
638
 
                   ARGP_IN_ORDER | ARGP_NO_EXIT | ARGP_NO_HELP,
639
 
                   NULL, NULL);
640
 
  switch(ret){
641
 
  case 0:
642
 
    break;
643
 
  case ENOMEM:
644
 
  default:
645
 
    errno = ret;
646
 
    error(0, errno, "argp_parse");
647
 
    exitstatus = EX_OSERR;
648
 
    goto fallback;
649
 
  case EINVAL:
650
 
    exitstatus = EX_USAGE;
 
569
  ret = argp_parse(&argp, argc, argv, ARGP_IN_ORDER, 0, NULL);
 
570
  if(ret == ARGP_ERR_UNKNOWN){
 
571
    fprintf(stderr, "Unknown error while parsing arguments\n");
 
572
    exitstatus = EXIT_FAILURE;
651
573
    goto fallback;
652
574
  }
653
575
  
670
592
    custom_argc = 1;
671
593
    custom_argv = malloc(sizeof(char*) * 2);
672
594
    if(custom_argv == NULL){
673
 
      error(0, errno, "malloc");
674
 
      exitstatus = EX_OSERR;
 
595
      perror("malloc");
 
596
      exitstatus = EXIT_FAILURE;
675
597
      goto fallback;
676
598
    }
677
599
    custom_argv[0] = argv[0];
693
615
        }
694
616
        new_arg = strdup(p);
695
617
        if(new_arg == NULL){
696
 
          error(0, errno, "strdup");
697
 
          exitstatus = EX_OSERR;
 
618
          perror("strdup");
 
619
          exitstatus = EXIT_FAILURE;
698
620
          free(org_line);
699
621
          goto fallback;
700
622
        }
701
623
        
702
624
        custom_argc += 1;
703
 
        {
704
 
          char **new_argv = realloc(custom_argv, sizeof(char *)
705
 
                                    * ((size_t)custom_argc + 1));
706
 
          if(new_argv == NULL){
707
 
            error(0, errno, "realloc");
708
 
            exitstatus = EX_OSERR;
709
 
            free(new_arg);
710
 
            free(org_line);
711
 
            goto fallback;
712
 
          } else {
713
 
            custom_argv = new_argv;
714
 
          }
 
625
        custom_argv = realloc(custom_argv, sizeof(char *)
 
626
                              * ((unsigned int) custom_argc + 1));
 
627
        if(custom_argv == NULL){
 
628
          perror("realloc");
 
629
          exitstatus = EXIT_FAILURE;
 
630
          free(org_line);
 
631
          goto fallback;
715
632
        }
716
633
        custom_argv[custom_argc-1] = new_arg;
717
634
        custom_argv[custom_argc] = NULL;
721
638
      ret = fclose(conffp);
722
639
    } while(ret == EOF and errno == EINTR);
723
640
    if(ret == EOF){
724
 
      error(0, errno, "fclose");
725
 
      exitstatus = EX_IOERR;
 
641
      perror("fclose");
 
642
      exitstatus = EXIT_FAILURE;
726
643
      goto fallback;
727
644
    }
728
645
    free(org_line);
730
647
    /* Check for harmful errors and go to fallback. Other errors might
731
648
       not affect opening plugins */
732
649
    if(errno == EMFILE or errno == ENFILE or errno == ENOMEM){
733
 
      error(0, errno, "fopen");
734
 
      exitstatus = EX_OSERR;
 
650
      perror("fopen");
 
651
      exitstatus = EXIT_FAILURE;
735
652
      goto fallback;
736
653
    }
737
654
  }
738
 
  /* If there were any arguments from the configuration file, pass
739
 
     them to parser as command line arguments */
 
655
  /* If there was any arguments from configuration file,
 
656
     pass them to parser as command arguments */
740
657
  if(custom_argv != NULL){
741
 
    ret = argp_parse(&argp, custom_argc, custom_argv,
742
 
                     ARGP_IN_ORDER | ARGP_NO_EXIT | ARGP_NO_HELP,
743
 
                     NULL, NULL);
744
 
    switch(ret){
745
 
    case 0:
746
 
      break;
747
 
    case ENOMEM:
748
 
    default:
749
 
      errno = ret;
750
 
      error(0, errno, "argp_parse");
751
 
      exitstatus = EX_OSERR;
752
 
      goto fallback;
753
 
    case EINVAL:
754
 
      exitstatus = EX_CONFIG;
 
658
    ret = argp_parse(&argp, custom_argc, custom_argv, ARGP_IN_ORDER,
 
659
                     0, NULL);
 
660
    if(ret == ARGP_ERR_UNKNOWN){
 
661
      fprintf(stderr, "Unknown error while parsing arguments\n");
 
662
      exitstatus = EXIT_FAILURE;
755
663
      goto fallback;
756
664
    }
757
665
  }
758
666
  
759
667
  /* Parse actual command line arguments, to let them override the
760
668
     config file */
761
 
  ret = argp_parse(&argp, argc, argv,
762
 
                   ARGP_IN_ORDER | ARGP_NO_EXIT | ARGP_NO_HELP,
763
 
                   NULL, NULL);
764
 
  switch(ret){
765
 
  case 0:
766
 
    break;
767
 
  case ENOMEM:
768
 
  default:
769
 
    errno = ret;
770
 
    error(0, errno, "argp_parse");
771
 
    exitstatus = EX_OSERR;
772
 
    goto fallback;
773
 
  case EINVAL:
774
 
    exitstatus = EX_USAGE;
775
 
    goto fallback;
776
 
  }
777
 
  
778
 
  {
779
 
    char *pluginhelperenv;
780
 
    bool bret = true;
781
 
    ret = asprintf(&pluginhelperenv, "MANDOSPLUGINHELPERDIR=%s",
782
 
                   pluginhelperdir != NULL ? pluginhelperdir : PHDIR);
783
 
    if(ret != -1){
784
 
      bret = add_environment(getplugin(NULL), pluginhelperenv, true);
785
 
    }
786
 
    if(ret == -1 or not bret){
787
 
      error(0, errno, "Failed to set MANDOSPLUGINHELPERDIR"
788
 
            " environment variable to \"%s\" for all plugins\n",
789
 
            pluginhelperdir != NULL ? pluginhelperdir : PHDIR);
790
 
    }
791
 
    if(ret != -1){
792
 
      free(pluginhelperenv);
793
 
    }
 
669
  ret = argp_parse(&argp, argc, argv, ARGP_IN_ORDER, 0, NULL);
 
670
  if(ret == ARGP_ERR_UNKNOWN){
 
671
    fprintf(stderr, "Unknown error while parsing arguments\n");
 
672
    exitstatus = EXIT_FAILURE;
 
673
    goto fallback;
794
674
  }
795
675
  
796
676
  if(debug){
797
 
    for(plugin *p = plugin_list; p != NULL; p = p->next){
 
677
    for(plugin *p = plugin_list; p != NULL; p=p->next){
798
678
      fprintf(stderr, "Plugin: %s has %d arguments\n",
799
679
              p->name ? p->name : "Global", p->argc - 1);
800
680
      for(char **a = p->argv; *a != NULL; a++){
807
687
    }
808
688
  }
809
689
  
810
 
  if(getuid() == 0){
811
 
    /* Work around Debian bug #633582:
812
 
       <https://bugs.debian.org/633582> */
813
 
    int plugindir_fd = open(/* plugindir or */ PDIR, O_RDONLY);
814
 
    if(plugindir_fd == -1){
815
 
      if(errno != ENOENT){
816
 
        error(0, errno, "open(\"" PDIR "\")");
817
 
      }
818
 
    } else {
819
 
      ret = (int)TEMP_FAILURE_RETRY(fstat(plugindir_fd, &st));
820
 
      if(ret == -1){
821
 
        error(0, errno, "fstat");
822
 
      } else {
823
 
        if(S_ISDIR(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
824
 
          ret = fchown(plugindir_fd, uid, gid);
825
 
          if(ret == -1){
826
 
            error(0, errno, "fchown");
827
 
          }
828
 
        }
829
 
      }
830
 
      close(plugindir_fd);
831
 
    }
832
 
  }
833
 
  
834
 
  /* Lower permissions */
835
 
  ret = setgid(gid);
 
690
  /* Strip permissions down to nobody */
 
691
  setgid(gid);
836
692
  if(ret == -1){
837
 
    error(0, errno, "setgid");
 
693
    perror("setgid");
838
694
  }
839
695
  ret = setuid(uid);
840
696
  if(ret == -1){
841
 
    error(0, errno, "setuid");
842
 
  }
843
 
  
844
 
  /* Open plugin directory with close_on_exec flag */
 
697
    perror("setuid");
 
698
  }
 
699
  
 
700
  if(plugindir == NULL){
 
701
    dir = opendir(PDIR);
 
702
  } else {
 
703
    dir = opendir(plugindir);
 
704
  }
 
705
  
 
706
  if(dir == NULL){
 
707
    perror("Could not open plugin dir");
 
708
    exitstatus = EXIT_FAILURE;
 
709
    goto fallback;
 
710
  }
 
711
  
 
712
  /* Set the FD_CLOEXEC flag on the directory, if possible */
845
713
  {
846
 
    dir_fd = open(plugindir != NULL ? plugindir : PDIR, O_RDONLY |
847
 
#ifdef O_CLOEXEC
848
 
                  O_CLOEXEC
849
 
#else  /* not O_CLOEXEC */
850
 
                  0
851
 
#endif  /* not O_CLOEXEC */
852
 
                  );
853
 
    if(dir_fd == -1){
854
 
      error(0, errno, "Could not open plugin dir");
855
 
      exitstatus = EX_UNAVAILABLE;
856
 
      goto fallback;
857
 
    }
858
 
    
859
 
#ifndef O_CLOEXEC
860
 
  /* Set the FD_CLOEXEC flag on the directory */
861
 
    ret = set_cloexec_flag(dir_fd);
862
 
    if(ret < 0){
863
 
      error(0, errno, "set_cloexec_flag");
864
 
      exitstatus = EX_OSERR;
865
 
      goto fallback;
866
 
    }
867
 
#endif  /* O_CLOEXEC */
868
 
  }
869
 
  
870
 
  int good_name(const struct dirent * const dirent){
871
 
    const char * const patterns[] = { ".*", "#*#", "*~", "*.dpkg-new",
872
 
                                      "*.dpkg-old", "*.dpkg-bak",
873
 
                                      "*.dpkg-divert", NULL };
874
 
#ifdef __GNUC__
875
 
#pragma GCC diagnostic push
876
 
#pragma GCC diagnostic ignored "-Wcast-qual"
877
 
#endif
878
 
    for(const char **pat = (const char **)patterns;
879
 
        *pat != NULL; pat++){
880
 
#ifdef __GNUC__
881
 
#pragma GCC diagnostic pop
882
 
#endif
883
 
      if(fnmatch(*pat, dirent->d_name, FNM_FILE_NAME | FNM_PERIOD)
884
 
         != FNM_NOMATCH){
885
 
        if(debug){
886
 
            fprintf(stderr, "Ignoring plugin dir entry \"%s\""
887
 
                    " matching pattern %s\n", dirent->d_name, *pat);
888
 
        }
889
 
        return 0;
 
714
    int dir_fd = dirfd(dir);
 
715
    if(dir_fd >= 0){
 
716
      ret = set_cloexec_flag(dir_fd);
 
717
      if(ret < 0){
 
718
        perror("set_cloexec_flag");
 
719
        exitstatus = EXIT_FAILURE;
 
720
        goto fallback;
890
721
      }
891
722
    }
892
 
    return 1;
893
 
  }
894
 
  
895
 
  int numplugins = scandirat(dir_fd, ".", &direntries, good_name,
896
 
                             alphasort);
897
 
  if(numplugins == -1){
898
 
    error(0, errno, "Could not scan plugin dir");
899
 
    direntries = NULL;
900
 
    exitstatus = EX_OSERR;
901
 
    goto fallback;
902
723
  }
903
724
  
904
725
  FD_ZERO(&rfds_all);
905
726
  
906
727
  /* Read and execute any executable in the plugin directory*/
907
 
  for(int i = 0; i < numplugins; i++){
908
 
    
909
 
    int plugin_fd = openat(dir_fd, direntries[i]->d_name, O_RDONLY);
910
 
    if(plugin_fd == -1){
911
 
      error(0, errno, "Could not open plugin");
912
 
      free(direntries[i]);
 
728
  while(true){
 
729
    do {
 
730
      dirst = readdir(dir);
 
731
    } while(dirst == NULL and errno == EINTR);
 
732
    
 
733
    /* All directory entries have been processed */
 
734
    if(dirst == NULL){
 
735
      if(errno == EBADF){
 
736
        perror("readdir");
 
737
        exitstatus = EXIT_FAILURE;
 
738
        goto fallback;
 
739
      }
 
740
      break;
 
741
    }
 
742
    
 
743
    d_name_len = strlen(dirst->d_name);
 
744
    
 
745
    /* Ignore dotfiles, backup files and other junk */
 
746
    {
 
747
      bool bad_name = false;
 
748
      
 
749
      const char const *bad_prefixes[] = { ".", "#", NULL };
 
750
      
 
751
      const char const *bad_suffixes[] = { "~", "#", ".dpkg-new",
 
752
                                           ".dpkg-old",
 
753
                                           ".dpkg-bak",
 
754
                                           ".dpkg-divert", NULL };
 
755
      for(const char **pre = bad_prefixes; *pre != NULL; pre++){
 
756
        size_t pre_len = strlen(*pre);
 
757
        if((d_name_len >= pre_len)
 
758
           and strncmp((dirst->d_name), *pre, pre_len) == 0){
 
759
          if(debug){
 
760
            fprintf(stderr, "Ignoring plugin dir entry \"%s\""
 
761
                    " with bad prefix %s\n", dirst->d_name, *pre);
 
762
          }
 
763
          bad_name = true;
 
764
          break;
 
765
        }
 
766
      }
 
767
      if(bad_name){
 
768
        continue;
 
769
      }
 
770
      for(const char **suf = bad_suffixes; *suf != NULL; suf++){
 
771
        size_t suf_len = strlen(*suf);
 
772
        if((d_name_len >= suf_len)
 
773
           and (strcmp((dirst->d_name)+d_name_len-suf_len, *suf)
 
774
                == 0)){
 
775
          if(debug){
 
776
            fprintf(stderr, "Ignoring plugin dir entry \"%s\""
 
777
                    " with bad suffix %s\n", dirst->d_name, *suf);
 
778
          }
 
779
          bad_name = true;
 
780
          break;
 
781
        }
 
782
      }
 
783
      
 
784
      if(bad_name){
 
785
        continue;
 
786
      }
 
787
    }
 
788
    
 
789
    char *filename;
 
790
    if(plugindir == NULL){
 
791
      ret = TEMP_FAILURE_RETRY(asprintf(&filename, PDIR "/%s",
 
792
                                        dirst->d_name));
 
793
    } else {
 
794
      ret = TEMP_FAILURE_RETRY(asprintf(&filename, "%s/%s", plugindir,
 
795
                                        dirst->d_name));
 
796
    }
 
797
    if(ret < 0){
 
798
      perror("asprintf");
913
799
      continue;
914
800
    }
915
 
    ret = (int)TEMP_FAILURE_RETRY(fstat(plugin_fd, &st));
 
801
    
 
802
    ret = TEMP_FAILURE_RETRY(stat(filename, &st));
916
803
    if(ret == -1){
917
 
      error(0, errno, "stat");
918
 
      close(plugin_fd);
919
 
      free(direntries[i]);
 
804
      perror("stat");
 
805
      free(filename);
920
806
      continue;
921
807
    }
922
808
    
923
809
    /* Ignore non-executable files */
924
810
    if(not S_ISREG(st.st_mode)
925
 
       or (TEMP_FAILURE_RETRY(faccessat(dir_fd, direntries[i]->d_name,
926
 
                                        X_OK, 0)) != 0)){
 
811
       or (TEMP_FAILURE_RETRY(access(filename, X_OK)) != 0)){
927
812
      if(debug){
928
 
        fprintf(stderr, "Ignoring plugin dir entry \"%s/%s\""
929
 
                " with bad type or mode\n",
930
 
                plugindir != NULL ? plugindir : PDIR,
931
 
                direntries[i]->d_name);
 
813
        fprintf(stderr, "Ignoring plugin dir entry \"%s\""
 
814
                " with bad type or mode\n", filename);
932
815
      }
933
 
      close(plugin_fd);
934
 
      free(direntries[i]);
 
816
      free(filename);
935
817
      continue;
936
818
    }
937
819
    
938
 
    plugin *p = getplugin(direntries[i]->d_name);
 
820
    plugin *p = getplugin(dirst->d_name);
939
821
    if(p == NULL){
940
 
      error(0, errno, "getplugin");
941
 
      close(plugin_fd);
942
 
      free(direntries[i]);
 
822
      perror("getplugin");
 
823
      free(filename);
943
824
      continue;
944
825
    }
945
826
    if(p->disabled){
946
827
      if(debug){
947
828
        fprintf(stderr, "Ignoring disabled plugin \"%s\"\n",
948
 
                direntries[i]->d_name);
 
829
                dirst->d_name);
949
830
      }
950
 
      close(plugin_fd);
951
 
      free(direntries[i]);
 
831
      free(filename);
952
832
      continue;
953
833
    }
954
834
    {
957
837
      if(g != NULL){
958
838
        for(char **a = g->argv + 1; *a != NULL; a++){
959
839
          if(not add_argument(p, *a)){
960
 
            error(0, errno, "add_argument");
 
840
            perror("add_argument");
961
841
          }
962
842
        }
963
843
        /* Add global environment variables */
964
844
        for(char **e = g->environ; *e != NULL; e++){
965
845
          if(not add_environment(p, *e, false)){
966
 
            error(0, errno, "add_environment");
 
846
            perror("add_environment");
967
847
          }
968
848
        }
969
849
      }
970
850
    }
971
 
    /* If this plugin has any environment variables, we need to
972
 
       duplicate the environment from this process, too. */
 
851
    /* If this plugin has any environment variables, we will call
 
852
       using execve and need to duplicate the environment from this
 
853
       process, too. */
973
854
    if(p->environ[0] != NULL){
974
855
      for(char **e = environ; *e != NULL; e++){
975
856
        if(not add_environment(p, *e, false)){
976
 
          error(0, errno, "add_environment");
 
857
          perror("add_environment");
977
858
        }
978
859
      }
979
860
    }
980
861
    
981
862
    int pipefd[2];
982
 
#ifndef O_CLOEXEC
983
 
    ret = (int)TEMP_FAILURE_RETRY(pipe(pipefd));
984
 
#else  /* O_CLOEXEC */
985
 
    ret = (int)TEMP_FAILURE_RETRY(pipe2(pipefd, O_CLOEXEC));
986
 
#endif  /* O_CLOEXEC */
 
863
    ret = TEMP_FAILURE_RETRY(pipe(pipefd));
987
864
    if(ret == -1){
988
 
      error(0, errno, "pipe");
989
 
      exitstatus = EX_OSERR;
990
 
      free(direntries[i]);
991
 
      goto fallback;
992
 
    }
993
 
    if(pipefd[0] >= FD_SETSIZE){
994
 
      fprintf(stderr, "pipe()[0] (%d) >= FD_SETSIZE (%d)", pipefd[0],
995
 
              FD_SETSIZE);
996
 
      close(pipefd[0]);
997
 
      close(pipefd[1]);
998
 
      exitstatus = EX_OSERR;
999
 
      free(direntries[i]);
1000
 
      goto fallback;
1001
 
    }
1002
 
#ifndef O_CLOEXEC
 
865
      perror("pipe");
 
866
      exitstatus = EXIT_FAILURE;
 
867
      goto fallback;
 
868
    }
1003
869
    /* Ask OS to automatic close the pipe on exec */
1004
870
    ret = set_cloexec_flag(pipefd[0]);
1005
871
    if(ret < 0){
1006
 
      error(0, errno, "set_cloexec_flag");
1007
 
      close(pipefd[0]);
1008
 
      close(pipefd[1]);
1009
 
      exitstatus = EX_OSERR;
1010
 
      free(direntries[i]);
 
872
      perror("set_cloexec_flag");
 
873
      exitstatus = EXIT_FAILURE;
1011
874
      goto fallback;
1012
875
    }
1013
876
    ret = set_cloexec_flag(pipefd[1]);
1014
877
    if(ret < 0){
1015
 
      error(0, errno, "set_cloexec_flag");
1016
 
      close(pipefd[0]);
1017
 
      close(pipefd[1]);
1018
 
      exitstatus = EX_OSERR;
1019
 
      free(direntries[i]);
 
878
      perror("set_cloexec_flag");
 
879
      exitstatus = EXIT_FAILURE;
1020
880
      goto fallback;
1021
881
    }
1022
 
#endif  /* not O_CLOEXEC */
1023
882
    /* Block SIGCHLD until process is safely in process list */
1024
 
    ret = (int)TEMP_FAILURE_RETRY(sigprocmask(SIG_BLOCK,
1025
 
                                              &sigchld_action.sa_mask,
1026
 
                                              NULL));
 
883
    ret = TEMP_FAILURE_RETRY(sigprocmask(SIG_BLOCK,
 
884
                                         &sigchld_action.sa_mask,
 
885
                                         NULL));
1027
886
    if(ret < 0){
1028
 
      error(0, errno, "sigprocmask");
1029
 
      exitstatus = EX_OSERR;
1030
 
      free(direntries[i]);
 
887
      perror("sigprocmask");
 
888
      exitstatus = EXIT_FAILURE;
1031
889
      goto fallback;
1032
890
    }
1033
891
    /* Starting a new process to be watched */
1036
894
      pid = fork();
1037
895
    } while(pid == -1 and errno == EINTR);
1038
896
    if(pid == -1){
1039
 
      error(0, errno, "fork");
1040
 
      TEMP_FAILURE_RETRY(sigprocmask(SIG_UNBLOCK,
1041
 
                                     &sigchld_action.sa_mask, NULL));
1042
 
      close(pipefd[0]);
1043
 
      close(pipefd[1]);
1044
 
      exitstatus = EX_OSERR;
1045
 
      free(direntries[i]);
 
897
      perror("fork");
 
898
      exitstatus = EXIT_FAILURE;
1046
899
      goto fallback;
1047
900
    }
1048
901
    if(pid == 0){
1049
902
      /* this is the child process */
1050
903
      ret = sigaction(SIGCHLD, &old_sigchld_action, NULL);
1051
904
      if(ret < 0){
1052
 
        error(0, errno, "sigaction");
1053
 
        _exit(EX_OSERR);
 
905
        perror("sigaction");
 
906
        _exit(EXIT_FAILURE);
1054
907
      }
1055
908
      ret = sigprocmask(SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
1056
909
      if(ret < 0){
1057
 
        error(0, errno, "sigprocmask");
1058
 
        _exit(EX_OSERR);
 
910
        perror("sigprocmask");
 
911
        _exit(EXIT_FAILURE);
1059
912
      }
1060
913
      
1061
914
      ret = dup2(pipefd[1], STDOUT_FILENO); /* replace our stdout */
1062
915
      if(ret == -1){
1063
 
        error(0, errno, "dup2");
1064
 
        _exit(EX_OSERR);
 
916
        perror("dup2");
 
917
        _exit(EXIT_FAILURE);
1065
918
      }
1066
919
      
1067
 
      if(fexecve(plugin_fd, p->argv,
1068
 
                (p->environ[0] != NULL) ? p->environ : environ) < 0){
1069
 
        error(0, errno, "fexecve for %s/%s",
1070
 
              plugindir != NULL ? plugindir : PDIR,
1071
 
              direntries[i]->d_name);
1072
 
        _exit(EX_OSERR);
 
920
      if(dirfd(dir) < 0){
 
921
        /* If dir has no file descriptor, we could not set FD_CLOEXEC
 
922
           above and must now close it manually here. */
 
923
        closedir(dir);
 
924
      }
 
925
      if(p->environ[0] == NULL){
 
926
        if(execv(filename, p->argv) < 0){
 
927
          perror("execv");
 
928
          _exit(EXIT_FAILURE);
 
929
        }
 
930
      } else {
 
931
        if(execve(filename, p->argv, p->environ) < 0){
 
932
          perror("execve");
 
933
          _exit(EXIT_FAILURE);
 
934
        }
1073
935
      }
1074
936
      /* no return */
1075
937
    }
1076
938
    /* Parent process */
1077
 
    close(pipefd[1]);           /* Close unused write end of pipe */
1078
 
    close(plugin_fd);
1079
 
    plugin *new_plugin = getplugin(direntries[i]->d_name);
 
939
    TEMP_FAILURE_RETRY(close(pipefd[1])); /* Close unused write end of
 
940
                                             pipe */
 
941
    free(filename);
 
942
    plugin *new_plugin = getplugin(dirst->d_name);
1080
943
    if(new_plugin == NULL){
1081
 
      error(0, errno, "getplugin");
1082
 
      ret = (int)(TEMP_FAILURE_RETRY
1083
 
                  (sigprocmask(SIG_UNBLOCK, &sigchld_action.sa_mask,
1084
 
                               NULL)));
 
944
      perror("getplugin");
 
945
      ret = TEMP_FAILURE_RETRY(sigprocmask(SIG_UNBLOCK,
 
946
                                           &sigchld_action.sa_mask,
 
947
                                           NULL));
1085
948
      if(ret < 0){
1086
 
        error(0, errno, "sigprocmask");
 
949
        perror("sigprocmask");
1087
950
      }
1088
 
      exitstatus = EX_OSERR;
1089
 
      free(direntries[i]);
 
951
      exitstatus = EXIT_FAILURE;
1090
952
      goto fallback;
1091
953
    }
1092
 
    free(direntries[i]);
1093
954
    
1094
955
    new_plugin->pid = pid;
1095
956
    new_plugin->fd = pipefd[0];
1096
 
 
1097
 
    if(debug){
1098
 
      fprintf(stderr, "Plugin %s started (PID %" PRIdMAX ")\n",
1099
 
              new_plugin->name, (intmax_t) (new_plugin->pid));
1100
 
    }
1101
 
 
 
957
    
1102
958
    /* Unblock SIGCHLD so signal handler can be run if this process
1103
959
       has already completed */
1104
 
    ret = (int)TEMP_FAILURE_RETRY(sigprocmask(SIG_UNBLOCK,
1105
 
                                              &sigchld_action.sa_mask,
1106
 
                                              NULL));
 
960
    ret = TEMP_FAILURE_RETRY(sigprocmask(SIG_UNBLOCK,
 
961
                                         &sigchld_action.sa_mask,
 
962
                                         NULL));
1107
963
    if(ret < 0){
1108
 
      error(0, errno, "sigprocmask");
1109
 
      exitstatus = EX_OSERR;
 
964
      perror("sigprocmask");
 
965
      exitstatus = EXIT_FAILURE;
1110
966
      goto fallback;
1111
967
    }
1112
968
    
1117
973
    }
1118
974
  }
1119
975
  
1120
 
  free(direntries);
1121
 
  direntries = NULL;
1122
 
  close(dir_fd);
1123
 
  dir_fd = -1;
 
976
  TEMP_FAILURE_RETRY(closedir(dir));
 
977
  dir = NULL;
1124
978
  free_plugin(getplugin(NULL));
1125
979
  
1126
980
  for(plugin *p = plugin_list; p != NULL; p = p->next){
1139
993
    fd_set rfds = rfds_all;
1140
994
    int select_ret = select(maxfd+1, &rfds, NULL, NULL, NULL);
1141
995
    if(select_ret == -1 and errno != EINTR){
1142
 
      error(0, errno, "select");
1143
 
      exitstatus = EX_OSERR;
 
996
      perror("select");
 
997
      exitstatus = EXIT_FAILURE;
1144
998
      goto fallback;
1145
999
    }
1146
1000
    /* OK, now either a process completed, or something can be read
1165
1019
                      (intmax_t) (proc->pid),
1166
1020
                      WTERMSIG(proc->status),
1167
1021
                      strsignal(WTERMSIG(proc->status)));
 
1022
            } else if(WCOREDUMP(proc->status)){
 
1023
              fprintf(stderr, "Plugin %s [%" PRIdMAX "] dumped"
 
1024
                      " core\n", proc->name, (intmax_t) (proc->pid));
1168
1025
            }
1169
1026
          }
1170
1027
          
1172
1029
          FD_CLR(proc->fd, &rfds_all);
1173
1030
          
1174
1031
          /* Block signal while modifying process_list */
1175
 
          ret = (int)TEMP_FAILURE_RETRY(sigprocmask
1176
 
                                        (SIG_BLOCK,
1177
 
                                         &sigchld_action.sa_mask,
1178
 
                                         NULL));
 
1032
          ret = TEMP_FAILURE_RETRY(sigprocmask(SIG_BLOCK,
 
1033
                                               &sigchld_action.sa_mask,
 
1034
                                               NULL));
1179
1035
          if(ret < 0){
1180
 
            error(0, errno, "sigprocmask");
1181
 
            exitstatus = EX_OSERR;
 
1036
            perror("sigprocmask");
 
1037
            exitstatus = EXIT_FAILURE;
1182
1038
            goto fallback;
1183
1039
          }
1184
1040
          
1187
1043
          proc = next_plugin;
1188
1044
          
1189
1045
          /* We are done modifying process list, so unblock signal */
1190
 
          ret = (int)(TEMP_FAILURE_RETRY
1191
 
                      (sigprocmask(SIG_UNBLOCK,
1192
 
                                   &sigchld_action.sa_mask, NULL)));
 
1046
          ret = TEMP_FAILURE_RETRY(sigprocmask(SIG_UNBLOCK,
 
1047
                                               &sigchld_action.sa_mask,
 
1048
                                               NULL));
1193
1049
          if(ret < 0){
1194
 
            error(0, errno, "sigprocmask");
1195
 
            exitstatus = EX_OSERR;
 
1050
            perror("sigprocmask");
 
1051
            exitstatus = EXIT_FAILURE;
1196
1052
            goto fallback;
1197
1053
          }
1198
1054
          
1208
1064
        bool bret = print_out_password(proc->buffer,
1209
1065
                                       proc->buffer_length);
1210
1066
        if(not bret){
1211
 
          error(0, errno, "print_out_password");
1212
 
          exitstatus = EX_IOERR;
 
1067
          perror("print_out_password");
 
1068
          exitstatus = EXIT_FAILURE;
1213
1069
        }
1214
1070
        goto fallback;
1215
1071
      }
1222
1078
      }
1223
1079
      /* Before reading, make the process' data buffer large enough */
1224
1080
      if(proc->buffer_length + BUFFER_SIZE > proc->buffer_size){
1225
 
        char *new_buffer = realloc(proc->buffer, proc->buffer_size
1226
 
                                   + (size_t) BUFFER_SIZE);
1227
 
        if(new_buffer == NULL){
1228
 
          error(0, errno, "malloc");
1229
 
          exitstatus = EX_OSERR;
 
1081
        proc->buffer = realloc(proc->buffer, proc->buffer_size
 
1082
                               + (size_t) BUFFER_SIZE);
 
1083
        if(proc->buffer == NULL){
 
1084
          perror("malloc");
 
1085
          exitstatus = EXIT_FAILURE;
1230
1086
          goto fallback;
1231
1087
        }
1232
 
        proc->buffer = new_buffer;
1233
1088
        proc->buffer_size += BUFFER_SIZE;
1234
1089
      }
1235
1090
      /* Read from the process */
1254
1109
  
1255
1110
 fallback:
1256
1111
  
1257
 
  if(plugin_list == NULL or (exitstatus != EXIT_SUCCESS
1258
 
                             and exitstatus != EX_OK)){
 
1112
  if(plugin_list == NULL or exitstatus != EXIT_SUCCESS){
1259
1113
    /* Fallback if all plugins failed, none are found or an error
1260
1114
       occured */
1261
1115
    bool bret;
1269
1123
    }
1270
1124
    bret = print_out_password(passwordbuffer, len);
1271
1125
    if(not bret){
1272
 
      error(0, errno, "print_out_password");
1273
 
      exitstatus = EX_IOERR;
 
1126
      perror("print_out_password");
 
1127
      exitstatus = EXIT_FAILURE;
1274
1128
    }
1275
1129
  }
1276
1130
  
1277
1131
  /* Restore old signal handler */
1278
1132
  ret = sigaction(SIGCHLD, &old_sigchld_action, NULL);
1279
1133
  if(ret == -1){
1280
 
    error(0, errno, "sigaction");
1281
 
    exitstatus = EX_OSERR;
 
1134
    perror("sigaction");
 
1135
    exitstatus = EXIT_FAILURE;
1282
1136
  }
1283
1137
  
1284
1138
  if(custom_argv != NULL){
1288
1142
    free(custom_argv);
1289
1143
  }
1290
1144
  
1291
 
  free(direntries);
1292
 
  
1293
 
  if(dir_fd != -1){
1294
 
    close(dir_fd);
 
1145
  if(dir != NULL){
 
1146
    closedir(dir);
1295
1147
  }
1296
1148
  
1297
1149
  /* Kill the processes */
1301
1153
      ret = kill(p->pid, SIGTERM);
1302
1154
      if(ret == -1 and errno != ESRCH){
1303
1155
        /* Set-uid proccesses might not get closed */
1304
 
        error(0, errno, "kill");
 
1156
        perror("kill");
1305
1157
      }
1306
1158
    }
1307
1159
  }
1311
1163
    ret = wait(NULL);
1312
1164
  } while(ret >= 0);
1313
1165
  if(errno != ECHILD){
1314
 
    error(0, errno, "wait");
 
1166
    perror("wait");
1315
1167
  }
1316
1168
  
1317
1169
  free_plugin_list();
1318
1170
  
1319
1171
  free(plugindir);
1320
 
  free(pluginhelperdir);
1321
1172
  free(argfile);
1322
1173
  
1323
1174
  return exitstatus;