/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-05 01:05:25 UTC
  • Revision ID: teddy@fukt.bsnet.se-20090905010525-7qeq05ztwc2ddhuv
* plugins.d/mandos-client.c (main): Do not handle ignored signals.
                                    Bug fix: remove signal handler
                                    before re-raising signal.

* plugins.d/password-prompt.c (main): Check return values from
                                      "sigaddset()".

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 © 2007-2008 Teddy Hogeborn & Björn Påhlsson
 
5
 * Copyright © 2008,2009 Teddy Hogeborn
 
6
 * Copyright © 2008,2009 Björn Påhlsson
6
7
 * 
7
8
 * This program is free software: you can redistribute it and/or
8
9
 * modify it under the terms of the GNU General Public License as
27
28
#include <stdlib.h>             /* malloc(), exit(), EXIT_FAILURE,
28
29
                                   EXIT_SUCCESS, realloc() */
29
30
#include <stdbool.h>            /* bool, true, false */
30
 
#include <stdio.h>              /* perror, popen(), fileno(),
31
 
                                   fprintf(), stderr, STDOUT_FILENO */
 
31
#include <stdio.h>              /* perror, fileno(), fprintf(),
 
32
                                   stderr, STDOUT_FILENO */
32
33
#include <sys/types.h>          /* DIR, opendir(), stat(), struct
33
34
                                   stat, waitpid(), WIFEXITED(),
34
35
                                   WEXITSTATUS(), wait(), pid_t,
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
45
#include <dirent.h>             /* DIR, struct dirent, opendir(),
46
48
                                   fcntl(), setuid(), setgid(),
47
49
                                   F_GETFD, F_SETFD, FD_CLOEXEC,
48
50
                                   access(), pipe(), fork(), close()
49
 
                                   dup2, STDOUT_FILENO, _exit(),
 
51
                                   dup2(), STDOUT_FILENO, _exit(),
50
52
                                   execv(), write(), read(),
51
53
                                   close() */
52
54
#include <fcntl.h>              /* fcntl(), F_GETFD, F_SETFD,
53
55
                                   FD_CLOEXEC */
54
 
#include <string.h>             /* strsep, strlen(), asprintf() */
 
56
#include <string.h>             /* strsep, strlen(), asprintf(),
 
57
                                   strsignal() */
55
58
#include <errno.h>              /* errno */
56
59
#include <argp.h>               /* struct argp_option, struct
57
60
                                   argp_state, struct argp,
61
64
#include <signal.h>             /* struct sigaction, sigemptyset(),
62
65
                                   sigaddset(), sigaction(),
63
66
                                   sigprocmask(), SIG_BLOCK, SIGCHLD,
64
 
                                   SIG_UNBLOCK, kill() */
 
67
                                   SIG_UNBLOCK, kill(), sig_atomic_t
 
68
                                */
65
69
#include <errno.h>              /* errno, EBADF */
 
70
#include <inttypes.h>           /* intmax_t, PRIdMAX, strtoimax() */
66
71
 
67
72
#define BUFFER_SIZE 256
68
73
 
69
74
#define PDIR "/lib/mandos/plugins.d"
70
75
#define AFILE "/conf/conf.d/mandos/plugin-runner.conf"
71
76
 
72
 
const char *argp_program_version = "plugin-runner 1.0";
 
77
const char *argp_program_version = "plugin-runner " VERSION;
73
78
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
74
79
 
75
 
struct plugin;
76
 
 
77
80
typedef struct plugin{
78
81
  char *name;                   /* can be NULL or any plugin name */
79
82
  char **argv;
81
84
  char **environ;
82
85
  int envc;
83
86
  bool disabled;
84
 
 
 
87
  
85
88
  /* Variables used for running processes*/
86
89
  pid_t pid;
87
90
  int fd;
89
92
  size_t buffer_size;
90
93
  size_t buffer_length;
91
94
  bool eof;
92
 
  volatile bool completed;
93
 
  volatile int status;
 
95
  volatile sig_atomic_t completed;
 
96
  int status;
94
97
  struct plugin *next;
95
98
} plugin;
96
99
 
97
100
static plugin *plugin_list = NULL;
98
101
 
99
 
/* Gets a existing plugin based on name,
 
102
/* Gets an existing plugin based on name,
100
103
   or if none is found, creates a new one */
101
104
static plugin *getplugin(char *name){
102
105
  /* Check for exiting plugin with that name */
103
 
  for (plugin *p = plugin_list; p != NULL; p = p->next){
104
 
    if ((p->name == name)
105
 
        or (p->name and name and (strcmp(p->name, name) == 0))){
 
106
  for(plugin *p = plugin_list; p != NULL; p = p->next){
 
107
    if((p->name == name)
 
108
       or (p->name and name and (strcmp(p->name, name) == 0))){
106
109
      return p;
107
110
    }
108
111
  }
109
112
  /* Create a new plugin */
110
113
  plugin *new_plugin = malloc(sizeof(plugin));
111
 
  if (new_plugin == NULL){
 
114
  if(new_plugin == NULL){
112
115
    return NULL;
113
116
  }
114
117
  char *copy_name = NULL;
115
118
  if(name != NULL){
116
119
    copy_name = strdup(name);
117
120
    if(copy_name == NULL){
 
121
      free(new_plugin);
118
122
      return NULL;
119
123
    }
120
124
  }
121
 
 
122
 
  *new_plugin = (plugin) { .name = copy_name,
123
 
                           .argc = 1,
124
 
                           .disabled = false,
125
 
                           .next = plugin_list };
 
125
  
 
126
  *new_plugin = (plugin){ .name = copy_name,
 
127
                          .argc = 1,
 
128
                          .disabled = false,
 
129
                          .next = plugin_list };
126
130
  
127
131
  new_plugin->argv = malloc(sizeof(char *) * 2);
128
 
  if (new_plugin->argv == NULL){
 
132
  if(new_plugin->argv == NULL){
129
133
    free(copy_name);
130
134
    free(new_plugin);
131
135
    return NULL;
132
136
  }
133
137
  new_plugin->argv[0] = copy_name;
134
138
  new_plugin->argv[1] = NULL;
135
 
 
 
139
  
136
140
  new_plugin->environ = malloc(sizeof(char *));
137
141
  if(new_plugin->environ == NULL){
138
142
    free(copy_name);
141
145
    return NULL;
142
146
  }
143
147
  new_plugin->environ[0] = NULL;
144
 
 
 
148
  
145
149
  /* Append the new plugin to the list */
146
150
  plugin_list = new_plugin;
147
151
  return new_plugin;
179
183
}
180
184
 
181
185
/* Add to a plugin's environment */
182
 
static bool add_environment(plugin *p, const char *def){
 
186
static bool add_environment(plugin *p, const char *def, bool replace){
183
187
  if(p == NULL){
184
188
    return false;
185
189
  }
 
190
  /* namelen = length of name of environment variable */
 
191
  size_t namelen = (size_t)(strchrnul(def, '=') - def);
 
192
  /* Search for this environment variable */
 
193
  for(char **e = p->environ; *e != NULL; e++){
 
194
    if(strncmp(*e, def, namelen + 1) == 0){
 
195
      /* It already exists */
 
196
      if(replace){
 
197
        char *new = realloc(*e, strlen(def) + 1);
 
198
        if(new == NULL){
 
199
          return false;
 
200
        }
 
201
        *e = new;
 
202
        strcpy(*e, def);
 
203
      }
 
204
      return true;
 
205
    }
 
206
  }
186
207
  return add_to_char_array(def, &(p->environ), &(p->envc));
187
208
}
188
209
 
191
212
 * Descriptor Flags".
192
213
 * *Note File Descriptor Flags:(libc)Descriptor Flags.
193
214
 */
194
 
static int set_cloexec_flag(int fd)
195
 
{
 
215
static int set_cloexec_flag(int fd){
196
216
  int ret = fcntl(fd, F_GETFD, 0);
197
217
  /* If reading the flags failed, return error indication now. */
198
218
  if(ret < 0){
205
225
 
206
226
/* Mark processes as completed when they exit, and save their exit
207
227
   status. */
208
 
void handle_sigchld(__attribute__((unused)) int sig){
 
228
static void handle_sigchld(__attribute__((unused)) int sig){
 
229
  int old_errno = errno;
209
230
  while(true){
210
231
    plugin *proc = plugin_list;
211
232
    int status;
215
236
      break;
216
237
    }
217
238
    if(pid == -1){
218
 
      if (errno != ECHILD){
219
 
        perror("waitpid");
 
239
      if(errno == ECHILD){
 
240
        /* No child processes */
 
241
        break;
220
242
      }
221
 
      /* No child processes */
222
 
      break;
 
243
      perror("waitpid");
223
244
    }
224
 
 
 
245
    
225
246
    /* A child exited, find it in process_list */
226
247
    while(proc != NULL and proc->pid != pid){
227
248
      proc = proc->next;
231
252
      continue;
232
253
    }
233
254
    proc->status = status;
234
 
    proc->completed = true;
 
255
    proc->completed = 1;
235
256
  }
 
257
  errno = old_errno;
236
258
}
237
259
 
238
260
/* Prints out a password to stdout */
239
 
bool print_out_password(const char *buffer, size_t length){
 
261
static bool print_out_password(const char *buffer, size_t length){
240
262
  ssize_t ret;
241
 
  if(length>0 and buffer[length-1] == '\n'){
242
 
    length--;
243
 
  }
244
263
  for(size_t written = 0; written < length; written += (size_t)ret){
245
264
    ret = TEMP_FAILURE_RETRY(write(STDOUT_FILENO, buffer + written,
246
265
                                   length - written));
263
282
  }
264
283
  free(plugin_node->environ);
265
284
  free(plugin_node->buffer);
266
 
 
 
285
  
267
286
  /* Removes the plugin from the singly-linked list */
268
287
  if(plugin_node == plugin_list){
269
288
    /* First one - simple */
297
316
  struct stat st;
298
317
  fd_set rfds_all;
299
318
  int ret, maxfd = 0;
 
319
  ssize_t sret;
 
320
  intmax_t tmpmax;
300
321
  uid_t uid = 65534;
301
322
  gid_t gid = 65534;
302
323
  bool debug = false;
327
348
    { .name = "global-options", .key = 'g',
328
349
      .arg = "OPTION[,OPTION[,...]]",
329
350
      .doc = "Options passed to all plugins" },
330
 
    { .name = "global-envs", .key = 'e',
 
351
    { .name = "global-env", .key = 'G',
331
352
      .arg = "VAR=value",
332
353
      .doc = "Environment variable passed to all plugins" },
333
354
    { .name = "options-for", .key = 'o',
334
355
      .arg = "PLUGIN:OPTION[,OPTION[,...]]",
335
356
      .doc = "Options passed only to specified plugin" },
336
 
    { .name = "envs-for", .key = 'f',
 
357
    { .name = "env-for", .key = 'E',
337
358
      .arg = "PLUGIN:ENV=value",
338
359
      .doc = "Environment variable passed to specified plugin" },
339
360
    { .name = "disable", .key = 'd',
340
361
      .arg = "PLUGIN",
341
362
      .doc = "Disable a specific plugin", .group = 1 },
 
363
    { .name = "enable", .key = 'e',
 
364
      .arg = "PLUGIN",
 
365
      .doc = "Enable a specific plugin", .group = 1 },
342
366
    { .name = "plugin-dir", .key = 128,
343
367
      .arg = "DIRECTORY",
344
368
      .doc = "Specify a different plugin directory", .group = 2 },
356
380
    { .name = NULL }
357
381
  };
358
382
  
359
 
  error_t parse_opt (int key, char *arg, __attribute__((unused))
360
 
                     struct argp_state *state) {
361
 
    /* Get the INPUT argument from `argp_parse', which we know is a
362
 
       pointer to our plugin list pointer. */
363
 
    switch (key) {
 
383
  error_t parse_opt(int key, char *arg, __attribute__((unused))
 
384
                    struct argp_state *state){
 
385
    char *tmp;
 
386
    switch(key){
364
387
    case 'g':                   /* --global-options */
365
 
      if (arg != NULL){
366
 
        char *p;
367
 
        while((p = strsep(&arg, ",")) != NULL){
368
 
          if(p[0] == '\0'){
 
388
      if(arg != NULL){
 
389
        char *plugin_option;
 
390
        while((plugin_option = strsep(&arg, ",")) != NULL){
 
391
          if(plugin_option[0] == '\0'){
369
392
            continue;
370
393
          }
371
 
          if(not add_argument(getplugin(NULL), p)){
 
394
          if(not add_argument(getplugin(NULL), plugin_option)){
372
395
            perror("add_argument");
373
396
            return ARGP_ERR_UNKNOWN;
374
397
          }
375
398
        }
376
399
      }
377
400
      break;
378
 
    case 'e':                   /* --global-envs */
 
401
    case 'G':                   /* --global-env */
379
402
      if(arg == NULL){
380
403
        break;
381
404
      }
382
 
      {
383
 
        char *envdef = strdup(arg);
384
 
        if(envdef == NULL){
385
 
          break;
386
 
        }
387
 
        if(not add_environment(getplugin(NULL), envdef)){
388
 
          perror("add_environment");
389
 
        }
 
405
      if(not add_environment(getplugin(NULL), arg, true)){
 
406
        perror("add_environment");
390
407
      }
391
408
      break;
392
409
    case 'o':                   /* --options-for */
393
 
      if (arg != NULL){
394
 
        char *p_name = strsep(&arg, ":");
395
 
        if(p_name[0] == '\0'){
396
 
          break;
397
 
        }
398
 
        char *opt = strsep(&arg, ":");
399
 
        if(opt[0] == '\0'){
400
 
          break;
401
 
        }
402
 
        if(opt != NULL){
403
 
          char *p;
404
 
          while((p = strsep(&opt, ",")) != NULL){
405
 
            if(p[0] == '\0'){
406
 
              continue;
407
 
            }
408
 
            if(not add_argument(getplugin(p_name), p)){
409
 
              perror("add_argument");
410
 
              return ARGP_ERR_UNKNOWN;
411
 
            }
 
410
      if(arg != NULL){
 
411
        char *plugin_name = strsep(&arg, ":");
 
412
        if(plugin_name[0] == '\0'){
 
413
          break;
 
414
        }
 
415
        char *plugin_option;
 
416
        while((plugin_option = strsep(&arg, ",")) != NULL){
 
417
          if(not add_argument(getplugin(plugin_name), plugin_option)){
 
418
            perror("add_argument");
 
419
            return ARGP_ERR_UNKNOWN;
412
420
          }
413
421
        }
414
422
      }
415
423
      break;
416
 
    case 'f':                   /* --envs-for */
 
424
    case 'E':                   /* --env-for */
417
425
      if(arg == NULL){
418
426
        break;
419
427
      }
422
430
        if(envdef == NULL){
423
431
          break;
424
432
        }
425
 
        char *p_name = strndup(arg, (size_t) (envdef-arg));
426
 
        if(p_name == NULL){
427
 
          break;
428
 
        }
429
 
        envdef++;
430
 
        if(not add_environment(getplugin(p_name), envdef)){
 
433
        *envdef = '\0';
 
434
        if(not add_environment(getplugin(arg), envdef+1, true)){
431
435
          perror("add_environment");
432
436
        }
433
437
      }
434
438
      break;
435
439
    case 'd':                   /* --disable */
436
 
      if (arg != NULL){
 
440
      if(arg != NULL){
437
441
        plugin *p = getplugin(arg);
438
442
        if(p == NULL){
439
443
          return ARGP_ERR_UNKNOWN;
441
445
        p->disabled = true;
442
446
      }
443
447
      break;
 
448
    case 'e':                   /* --enable */
 
449
      if(arg != NULL){
 
450
        plugin *p = getplugin(arg);
 
451
        if(p == NULL){
 
452
          return ARGP_ERR_UNKNOWN;
 
453
        }
 
454
        p->disabled = false;
 
455
      }
 
456
      break;
444
457
    case 128:                   /* --plugin-dir */
 
458
      free(plugindir);
445
459
      plugindir = strdup(arg);
446
460
      if(plugindir == NULL){
447
461
        perror("strdup");
448
 
      }      
449
 
      break;
450
 
    case 129:                   /* --config-file */
 
462
      }
 
463
      break;
 
464
    case 129:                   /* --config-file */
 
465
      /* This is already done by parse_opt_config_file() */
 
466
      break;
 
467
    case 130:                   /* --userid */
 
468
      errno = 0;
 
469
      tmpmax = strtoimax(arg, &tmp, 10);
 
470
      if(errno != 0 or tmp == arg or *tmp != '\0'
 
471
         or tmpmax != (uid_t)tmpmax){
 
472
        fprintf(stderr, "Bad user ID number: \"%s\", using %"
 
473
                PRIdMAX "\n", arg, (intmax_t)uid);
 
474
      } else {
 
475
        uid = (uid_t)tmpmax;
 
476
      }
 
477
      break;
 
478
    case 131:                   /* --groupid */
 
479
      errno = 0;
 
480
      tmpmax = strtoimax(arg, &tmp, 10);
 
481
      if(errno != 0 or tmp == arg or *tmp != '\0'
 
482
         or tmpmax != (gid_t)tmpmax){
 
483
        fprintf(stderr, "Bad group ID number: \"%s\", using %"
 
484
                PRIdMAX "\n", arg, (intmax_t)gid);
 
485
      } else {
 
486
        gid = (gid_t)tmpmax;
 
487
      }
 
488
      break;
 
489
    case 132:                   /* --debug */
 
490
      debug = true;
 
491
      break;
 
492
/*
 
493
 * When adding more options before this line, remember to also add a
 
494
 * "case" to the "parse_opt_config_file" function below.
 
495
 */
 
496
    case ARGP_KEY_ARG:
 
497
      /* Cryptsetup always passes an argument, which is an empty
 
498
         string if "none" was specified in /etc/crypttab.  So if
 
499
         argument was empty, we ignore it silently. */
 
500
      if(arg[0] != '\0'){
 
501
        fprintf(stderr, "Ignoring unknown argument \"%s\"\n", arg);
 
502
      }
 
503
      break;
 
504
    case ARGP_KEY_END:
 
505
      break;
 
506
    default:
 
507
      return ARGP_ERR_UNKNOWN;
 
508
    }
 
509
    return 0;
 
510
  }
 
511
  
 
512
  /* This option parser is the same as parse_opt() above, except it
 
513
     ignores everything but the --config-file option. */
 
514
  error_t parse_opt_config_file(int key, char *arg,
 
515
                                __attribute__((unused))
 
516
                                struct argp_state *state){
 
517
    switch(key){
 
518
    case 'g':                   /* --global-options */
 
519
    case 'G':                   /* --global-env */
 
520
    case 'o':                   /* --options-for */
 
521
    case 'E':                   /* --env-for */
 
522
    case 'd':                   /* --disable */
 
523
    case 'e':                   /* --enable */
 
524
    case 128:                   /* --plugin-dir */
 
525
      break;
 
526
    case 129:                   /* --config-file */
 
527
      free(argfile);
451
528
      argfile = strdup(arg);
452
529
      if(argfile == NULL){
453
530
        perror("strdup");
454
531
      }
455
 
      break;      
 
532
      break;
456
533
    case 130:                   /* --userid */
457
 
      uid = (uid_t)strtol(arg, NULL, 10);
458
 
      break;
459
534
    case 131:                   /* --groupid */
460
 
      gid = (gid_t)strtol(arg, NULL, 10);
461
 
      break;
462
535
    case 132:                   /* --debug */
463
 
      debug = true;
464
 
      break;
465
536
    case ARGP_KEY_ARG:
466
 
      fprintf(stderr, "Ignoring unknown argument \"%s\"\n", arg);
467
 
      break;
468
537
    case ARGP_KEY_END:
469
538
      break;
470
539
    default:
473
542
    return 0;
474
543
  }
475
544
  
476
 
  struct argp argp = { .options = options, .parser = parse_opt,
477
 
                       .args_doc = "[+PLUS_SEPARATED_OPTIONS]",
 
545
  struct argp argp = { .options = options,
 
546
                       .parser = parse_opt_config_file,
 
547
                       .args_doc = "",
478
548
                       .doc = "Mandos plugin runner -- Run plugins" };
479
549
  
480
 
  ret = argp_parse (&argp, argc, argv, 0, 0, NULL);
481
 
  if (ret == ARGP_ERR_UNKNOWN){
 
550
  /* Parse using parse_opt_config_file() in order to get the custom
 
551
     config file location, if any. */
 
552
  ret = argp_parse(&argp, argc, argv, ARGP_IN_ORDER, 0, NULL);
 
553
  if(ret == ARGP_ERR_UNKNOWN){
482
554
    fprintf(stderr, "Unknown error while parsing arguments\n");
483
555
    exitstatus = EXIT_FAILURE;
484
556
    goto fallback;
485
557
  }
486
 
 
487
 
  /* Opens the configfile if aviable */
488
 
  if (argfile == NULL){
 
558
  
 
559
  /* Reset to the normal argument parser */
 
560
  argp.parser = parse_opt;
 
561
  
 
562
  /* Open the configfile if available */
 
563
  if(argfile == NULL){
489
564
    conffp = fopen(AFILE, "r");
490
565
  } else {
491
566
    conffp = fopen(argfile, "r");
492
 
  }  
 
567
  }
493
568
  if(conffp != NULL){
494
569
    char *org_line = NULL;
495
570
    char *p, *arg, *new_arg, *line;
496
571
    size_t size = 0;
497
 
    ssize_t sret;
498
572
    const char whitespace_delims[] = " \r\t\f\v\n";
499
573
    const char comment_delim[] = "#";
500
 
 
 
574
    
501
575
    custom_argc = 1;
502
576
    custom_argv = malloc(sizeof(char*) * 2);
503
577
    if(custom_argv == NULL){
507
581
    }
508
582
    custom_argv[0] = argv[0];
509
583
    custom_argv[1] = NULL;
510
 
 
 
584
    
511
585
    /* for each line in the config file, strip whitespace and ignore
512
586
       commented text */
513
587
    while(true){
515
589
      if(sret == -1){
516
590
        break;
517
591
      }
518
 
 
 
592
      
519
593
      line = org_line;
520
594
      arg = strsep(&line, comment_delim);
521
595
      while((p = strsep(&arg, whitespace_delims)) != NULL){
540
614
          goto fallback;
541
615
        }
542
616
        custom_argv[custom_argc-1] = new_arg;
543
 
        custom_argv[custom_argc] = NULL;        
 
617
        custom_argv[custom_argc] = NULL;
544
618
      }
545
619
    }
546
620
    free(org_line);
547
 
  } else{
 
621
  } else {
548
622
    /* Check for harmful errors and go to fallback. Other errors might
549
623
       not affect opening plugins */
550
 
    if (errno == EMFILE or errno == ENFILE or errno == ENOMEM){
 
624
    if(errno == EMFILE or errno == ENFILE or errno == ENOMEM){
551
625
      perror("fopen");
552
626
      exitstatus = EXIT_FAILURE;
553
627
      goto fallback;
556
630
  /* If there was any arguments from configuration file,
557
631
     pass them to parser as command arguments */
558
632
  if(custom_argv != NULL){
559
 
    ret = argp_parse (&argp, custom_argc, custom_argv, 0, 0, NULL);
560
 
    if (ret == ARGP_ERR_UNKNOWN){
 
633
    ret = argp_parse(&argp, custom_argc, custom_argv, ARGP_IN_ORDER,
 
634
                     0, NULL);
 
635
    if(ret == ARGP_ERR_UNKNOWN){
561
636
      fprintf(stderr, "Unknown error while parsing arguments\n");
562
637
      exitstatus = EXIT_FAILURE;
563
638
      goto fallback;
564
639
    }
565
640
  }
566
641
  
 
642
  /* Parse actual command line arguments, to let them override the
 
643
     config file */
 
644
  ret = argp_parse(&argp, argc, argv, ARGP_IN_ORDER, 0, NULL);
 
645
  if(ret == ARGP_ERR_UNKNOWN){
 
646
    fprintf(stderr, "Unknown error while parsing arguments\n");
 
647
    exitstatus = EXIT_FAILURE;
 
648
    goto fallback;
 
649
  }
 
650
  
567
651
  if(debug){
568
652
    for(plugin *p = plugin_list; p != NULL; p=p->next){
569
653
      fprintf(stderr, "Plugin: %s has %d arguments\n",
571
655
      for(char **a = p->argv; *a != NULL; a++){
572
656
        fprintf(stderr, "\tArg: %s\n", *a);
573
657
      }
574
 
      fprintf(stderr, "...and %u environment variables\n", p->envc);
 
658
      fprintf(stderr, "...and %d environment variables\n", p->envc);
575
659
      for(char **a = p->environ; *a != NULL; a++){
576
660
        fprintf(stderr, "\t%s\n", *a);
577
661
      }
578
662
    }
579
663
  }
580
 
 
 
664
  
581
665
  /* Strip permissions down to nobody */
 
666
  setgid(gid);
 
667
  if(ret == -1){
 
668
    perror("setgid");
 
669
  }
582
670
  ret = setuid(uid);
583
 
  if (ret == -1){
 
671
  if(ret == -1){
584
672
    perror("setuid");
585
 
  }  
586
 
  setgid(gid);
587
 
  if (ret == -1){
588
 
    perror("setgid");
589
673
  }
590
 
 
591
 
  if (plugindir == NULL){
 
674
  
 
675
  if(plugindir == NULL){
592
676
    dir = opendir(PDIR);
593
677
  } else {
594
678
    dir = opendir(plugindir);
614
698
  }
615
699
  
616
700
  FD_ZERO(&rfds_all);
617
 
 
 
701
  
618
702
  /* Read and execute any executable in the plugin directory*/
619
703
  while(true){
620
704
    dirst = readdir(dir);
621
705
    
622
 
    // All directory entries have been processed
 
706
    /* All directory entries have been processed */
623
707
    if(dirst == NULL){
624
 
      if (errno == EBADF){
 
708
      if(errno == EBADF){
625
709
        perror("readdir");
626
710
        exitstatus = EXIT_FAILURE;
627
711
        goto fallback;
631
715
    
632
716
    d_name_len = strlen(dirst->d_name);
633
717
    
634
 
    // Ignore dotfiles, backup files and other junk
 
718
    /* Ignore dotfiles, backup files and other junk */
635
719
    {
636
720
      bool bad_name = false;
637
721
      
639
723
      
640
724
      const char const *bad_suffixes[] = { "~", "#", ".dpkg-new",
641
725
                                           ".dpkg-old",
 
726
                                           ".dpkg-bak",
642
727
                                           ".dpkg-divert", NULL };
643
728
      for(const char **pre = bad_prefixes; *pre != NULL; pre++){
644
729
        size_t pre_len = strlen(*pre);
673
758
        continue;
674
759
      }
675
760
    }
676
 
 
 
761
    
677
762
    char *filename;
678
 
    ret = asprintf(&filename, "%s/%s", plugindir, dirst->d_name);
 
763
    if(plugindir == NULL){
 
764
      ret = asprintf(&filename, PDIR "/%s", dirst->d_name);
 
765
    } else {
 
766
      ret = asprintf(&filename, "%s/%s", plugindir, dirst->d_name);
 
767
    }
679
768
    if(ret < 0){
680
769
      perror("asprintf");
681
770
      continue;
682
771
    }
683
772
    
684
773
    ret = stat(filename, &st);
685
 
    if (ret == -1){
 
774
    if(ret == -1){
686
775
      perror("stat");
687
776
      free(filename);
688
777
      continue;
689
778
    }
690
 
 
 
779
    
691
780
    /* Ignore non-executable files */
692
 
    if (not S_ISREG(st.st_mode) or (access(filename, X_OK) != 0)){
 
781
    if(not S_ISREG(st.st_mode) or (access(filename, X_OK) != 0)){
693
782
      if(debug){
694
783
        fprintf(stderr, "Ignoring plugin dir entry \"%s\""
695
784
                " with bad type or mode\n", filename);
723
812
        }
724
813
        /* Add global environment variables */
725
814
        for(char **e = g->environ; *e != NULL; e++){
726
 
          if(not add_environment(p, *e)){
 
815
          if(not add_environment(p, *e, false)){
727
816
            perror("add_environment");
728
817
          }
729
818
        }
734
823
       process, too. */
735
824
    if(p->environ[0] != NULL){
736
825
      for(char **e = environ; *e != NULL; e++){
737
 
        char *copy = strdup(*e);
738
 
        if(copy == NULL){
739
 
          perror("strdup");
740
 
          continue;
741
 
        }
742
 
        if(not add_environment(p, copy)){
 
826
        if(not add_environment(p, *e, false)){
743
827
          perror("add_environment");
744
828
        }
745
829
      }
747
831
    
748
832
    int pipefd[2];
749
833
    ret = pipe(pipefd);
750
 
    if (ret == -1){
 
834
    if(ret == -1){
751
835
      perror("pipe");
752
836
      exitstatus = EXIT_FAILURE;
753
837
      goto fallback;
766
850
      goto fallback;
767
851
    }
768
852
    /* Block SIGCHLD until process is safely in process list */
769
 
    ret = sigprocmask (SIG_BLOCK, &sigchld_action.sa_mask, NULL);
 
853
    ret = sigprocmask(SIG_BLOCK, &sigchld_action.sa_mask, NULL);
770
854
    if(ret < 0){
771
855
      perror("sigprocmask");
772
856
      exitstatus = EXIT_FAILURE;
773
857
      goto fallback;
774
858
    }
775
 
    // Starting a new process to be watched
 
859
    /* Starting a new process to be watched */
776
860
    pid_t pid = fork();
777
861
    if(pid == -1){
778
862
      perror("fork");
786
870
        perror("sigaction");
787
871
        _exit(EXIT_FAILURE);
788
872
      }
789
 
      ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
 
873
      ret = sigprocmask(SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
790
874
      if(ret < 0){
791
875
        perror("sigprocmask");
792
876
        _exit(EXIT_FAILURE);
793
877
      }
794
 
 
 
878
      
795
879
      ret = dup2(pipefd[1], STDOUT_FILENO); /* replace our stdout */
796
880
      if(ret == -1){
797
881
        perror("dup2");
820
904
    close(pipefd[1]);           /* Close unused write end of pipe */
821
905
    free(filename);
822
906
    plugin *new_plugin = getplugin(dirst->d_name);
823
 
    if (new_plugin == NULL){
 
907
    if(new_plugin == NULL){
824
908
      perror("getplugin");
825
 
      ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
 
909
      ret = sigprocmask(SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
826
910
      if(ret < 0){
827
911
        perror("sigprocmask");
828
912
      }
835
919
    
836
920
    /* Unblock SIGCHLD so signal handler can be run if this process
837
921
       has already completed */
838
 
    ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
 
922
    ret = sigprocmask(SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
839
923
    if(ret < 0){
840
924
      perror("sigprocmask");
841
925
      exitstatus = EXIT_FAILURE;
844
928
    
845
929
    FD_SET(new_plugin->fd, &rfds_all);
846
930
    
847
 
    if (maxfd < new_plugin->fd){
 
931
    if(maxfd < new_plugin->fd){
848
932
      maxfd = new_plugin->fd;
849
933
    }
850
 
    
851
934
  }
852
935
  
853
936
  closedir(dir);
854
937
  dir = NULL;
855
 
 
 
938
  free_plugin(getplugin(NULL));
 
939
  
856
940
  for(plugin *p = plugin_list; p != NULL; p = p->next){
857
941
    if(p->pid != 0){
858
942
      break;
863
947
      free_plugin_list();
864
948
    }
865
949
  }
866
 
 
 
950
  
867
951
  /* Main loop while running plugins exist */
868
952
  while(plugin_list){
869
953
    fd_set rfds = rfds_all;
870
954
    int select_ret = select(maxfd+1, &rfds, NULL, NULL, NULL);
871
 
    if (select_ret == -1){
 
955
    if(select_ret == -1){
872
956
      perror("select");
873
957
      exitstatus = EXIT_FAILURE;
874
958
      goto fallback;
875
959
    }
876
960
    /* OK, now either a process completed, or something can be read
877
961
       from one of them */
878
 
    for(plugin *proc = plugin_list; proc != NULL; proc = proc->next){
 
962
    for(plugin *proc = plugin_list; proc != NULL;){
879
963
      /* Is this process completely done? */
880
 
      if(proc->eof and proc->completed){
 
964
      if(proc->completed and proc->eof){
881
965
        /* Only accept the plugin output if it exited cleanly */
882
966
        if(not WIFEXITED(proc->status)
883
967
           or WEXITSTATUS(proc->status) != 0){
884
968
          /* Bad exit by plugin */
885
 
 
 
969
          
886
970
          if(debug){
887
971
            if(WIFEXITED(proc->status)){
888
 
              fprintf(stderr, "Plugin %u exited with status %d\n",
889
 
                      (unsigned int) (proc->pid),
 
972
              fprintf(stderr, "Plugin %s [%" PRIdMAX "] exited with"
 
973
                      " status %d\n", proc->name,
 
974
                      (intmax_t) (proc->pid),
890
975
                      WEXITSTATUS(proc->status));
891
 
            } else if(WIFSIGNALED(proc->status)) {
892
 
              fprintf(stderr, "Plugin %u killed by signal %d\n",
893
 
                      (unsigned int) (proc->pid),
894
 
                      WTERMSIG(proc->status));
 
976
            } else if(WIFSIGNALED(proc->status)){
 
977
              fprintf(stderr, "Plugin %s [%" PRIdMAX "] killed by"
 
978
                      " signal %d: %s\n", proc->name,
 
979
                      (intmax_t) (proc->pid),
 
980
                      WTERMSIG(proc->status),
 
981
                      strsignal(WTERMSIG(proc->status)));
895
982
            } else if(WCOREDUMP(proc->status)){
896
 
              fprintf(stderr, "Plugin %d dumped core\n",
897
 
                      (unsigned int) (proc->pid));
 
983
              fprintf(stderr, "Plugin %s [%" PRIdMAX "] dumped"
 
984
                      " core\n", proc->name, (intmax_t) (proc->pid));
898
985
            }
899
986
          }
900
987
          
901
988
          /* Remove the plugin */
902
989
          FD_CLR(proc->fd, &rfds_all);
903
 
 
 
990
          
904
991
          /* Block signal while modifying process_list */
905
992
          ret = sigprocmask(SIG_BLOCK, &sigchld_action.sa_mask, NULL);
906
993
          if(ret < 0){
908
995
            exitstatus = EXIT_FAILURE;
909
996
            goto fallback;
910
997
          }
 
998
          
 
999
          plugin *next_plugin = proc->next;
911
1000
          free_plugin(proc);
 
1001
          proc = next_plugin;
 
1002
          
912
1003
          /* We are done modifying process list, so unblock signal */
913
 
          ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask,
914
 
                             NULL);
 
1004
          ret = sigprocmask(SIG_UNBLOCK, &sigchld_action.sa_mask,
 
1005
                            NULL);
915
1006
          if(ret < 0){
916
1007
            perror("sigprocmask");
917
1008
            exitstatus = EXIT_FAILURE;
921
1012
          if(plugin_list == NULL){
922
1013
            break;
923
1014
          }
 
1015
          
924
1016
          continue;
925
1017
        }
926
1018
        
927
1019
        /* This process exited nicely, so print its buffer */
928
 
 
 
1020
        
929
1021
        bool bret = print_out_password(proc->buffer,
930
1022
                                       proc->buffer_length);
931
1023
        if(not bret){
938
1030
      /* This process has not completed.  Does it have any output? */
939
1031
      if(proc->eof or not FD_ISSET(proc->fd, &rfds)){
940
1032
        /* This process had nothing to say at this time */
 
1033
        proc = proc->next;
941
1034
        continue;
942
1035
      }
943
1036
      /* Before reading, make the process' data buffer large enough */
944
1037
      if(proc->buffer_length + BUFFER_SIZE > proc->buffer_size){
945
1038
        proc->buffer = realloc(proc->buffer, proc->buffer_size
946
1039
                               + (size_t) BUFFER_SIZE);
947
 
        if (proc->buffer == NULL){
 
1040
        if(proc->buffer == NULL){
948
1041
          perror("malloc");
949
1042
          exitstatus = EXIT_FAILURE;
950
1043
          goto fallback;
952
1045
        proc->buffer_size += BUFFER_SIZE;
953
1046
      }
954
1047
      /* Read from the process */
955
 
      ret = read(proc->fd, proc->buffer + proc->buffer_length,
956
 
                 BUFFER_SIZE);
957
 
      if(ret < 0){
 
1048
      sret = read(proc->fd, proc->buffer + proc->buffer_length,
 
1049
                  BUFFER_SIZE);
 
1050
      if(sret < 0){
958
1051
        /* Read error from this process; ignore the error */
 
1052
        proc = proc->next;
959
1053
        continue;
960
1054
      }
961
 
      if(ret == 0){
 
1055
      if(sret == 0){
962
1056
        /* got EOF */
963
1057
        proc->eof = true;
964
1058
      } else {
965
 
        proc->buffer_length += (size_t) ret;
 
1059
        proc->buffer_length += (size_t) sret;
966
1060
      }
967
1061
    }
968
1062
  }
969
 
 
970
 
 
 
1063
  
 
1064
  
971
1065
 fallback:
972
1066
  
973
1067
  if(plugin_list == NULL or exitstatus != EXIT_SUCCESS){
976
1070
    bool bret;
977
1071
    fprintf(stderr, "Going to fallback mode using getpass(3)\n");
978
1072
    char *passwordbuffer = getpass("Password: ");
979
 
    bret = print_out_password(passwordbuffer, strlen(passwordbuffer));
 
1073
    size_t len = strlen(passwordbuffer);
 
1074
    /* Strip trailing newline */
 
1075
    if(len > 0 and passwordbuffer[len-1] == '\n'){
 
1076
      passwordbuffer[len-1] = '\0'; /* not strictly necessary */
 
1077
      len--;
 
1078
    }
 
1079
    bret = print_out_password(passwordbuffer, len);
980
1080
    if(not bret){
981
1081
      perror("print_out_password");
982
1082
      exitstatus = EXIT_FAILURE;
989
1089
    perror("sigaction");
990
1090
    exitstatus = EXIT_FAILURE;
991
1091
  }
992
 
 
 
1092
  
993
1093
  if(custom_argv != NULL){
994
1094
    for(char **arg = custom_argv+1; *arg != NULL; arg++){
995
1095
      free(*arg);
1001
1101
    closedir(dir);
1002
1102
  }
1003
1103
  
1004
 
  /* Free the process list and kill the processes */
 
1104
  /* Kill the processes */
1005
1105
  for(plugin *p = plugin_list; p != NULL; p = p->next){
1006
1106
    if(p->pid != 0){
1007
1107
      close(p->fd);
1020
1120
  if(errno != ECHILD){
1021
1121
    perror("wait");
1022
1122
  }
1023
 
 
 
1123
  
1024
1124
  free_plugin_list();
1025
1125
  
1026
1126
  free(plugindir);