/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: 2008-10-15 19:54:11 UTC
  • Revision ID: teddy@fukt.bsnet.se-20081015195411-y5rr8hh3u7koihgi
* debian/copyright: Removed non-standard headers.

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 Teddy Hogeborn & Björn Påhlsson
6
6
 * 
7
7
 * This program is free software: you can redistribute it and/or
8
8
 * modify it under the terms of the GNU General Public License as
27
27
#include <stdlib.h>             /* malloc(), exit(), EXIT_FAILURE,
28
28
                                   EXIT_SUCCESS, realloc() */
29
29
#include <stdbool.h>            /* bool, true, false */
30
 
#include <stdio.h>              /* perror, popen(), fileno(),
31
 
                                   fprintf(), stderr, STDOUT_FILENO */
 
30
#include <stdio.h>              /* perror, fileno(), fprintf(),
 
31
                                   stderr, STDOUT_FILENO */
32
32
#include <sys/types.h>          /* DIR, opendir(), stat(), struct
33
33
                                   stat, waitpid(), WIFEXITED(),
34
34
                                   WEXITSTATUS(), wait(), pid_t,
46
46
                                   fcntl(), setuid(), setgid(),
47
47
                                   F_GETFD, F_SETFD, FD_CLOEXEC,
48
48
                                   access(), pipe(), fork(), close()
49
 
                                   dup2, STDOUT_FILENO, _exit(),
 
49
                                   dup2(), STDOUT_FILENO, _exit(),
50
50
                                   execv(), write(), read(),
51
51
                                   close() */
52
52
#include <fcntl.h>              /* fcntl(), F_GETFD, F_SETFD,
65
65
#include <errno.h>              /* errno, EBADF */
66
66
 
67
67
#define BUFFER_SIZE 256
68
 
#define ARGFILE "/conf/conf.d/mandos/plugin-runner.conf"
69
 
 
70
 
const char *argp_program_version = "plugin-runner 1.0";
 
68
 
 
69
#define PDIR "/lib/mandos/plugins.d"
 
70
#define AFILE "/conf/conf.d/mandos/plugin-runner.conf"
 
71
 
 
72
const char *argp_program_version = "plugin-runner " VERSION;
71
73
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
72
74
 
73
 
struct process;
 
75
typedef struct plugin{
 
76
  char *name;                   /* can be NULL or any plugin name */
 
77
  char **argv;
 
78
  int argc;
 
79
  char **environ;
 
80
  int envc;
 
81
  bool disabled;
74
82
 
75
 
typedef struct process{
 
83
  /* Variables used for running processes*/
76
84
  pid_t pid;
77
85
  int fd;
78
86
  char *buffer;
81
89
  bool eof;
82
90
  volatile bool completed;
83
91
  volatile int status;
84
 
  struct process *next;
85
 
} process;
86
 
 
87
 
typedef struct plugin{
88
 
  char *name;                   /* can be NULL or any plugin name */
89
 
  char **argv;
90
 
  int argc;
91
 
  char **environ;
92
 
  int envc;
93
 
  bool disabled;
94
92
  struct plugin *next;
95
93
} plugin;
96
94
 
97
 
static plugin *getplugin(char *name, plugin **plugin_list){
98
 
  for (plugin *p = *plugin_list; p != NULL; p = p->next){
 
95
static plugin *plugin_list = NULL;
 
96
 
 
97
/* Gets an existing plugin based on name,
 
98
   or if none is found, creates a new one */
 
99
static plugin *getplugin(char *name){
 
100
  /* Check for exiting plugin with that name */
 
101
  for (plugin *p = plugin_list; p != NULL; p = p->next){
99
102
    if ((p->name == name)
100
103
        or (p->name and name and (strcmp(p->name, name) == 0))){
101
104
      return p;
116
119
  
117
120
  *new_plugin = (plugin) { .name = copy_name,
118
121
                           .argc = 1,
119
 
                           .envc = 0,
120
122
                           .disabled = false,
121
 
                           .next = *plugin_list };
 
123
                           .next = plugin_list };
122
124
  
123
125
  new_plugin->argv = malloc(sizeof(char *) * 2);
124
126
  if (new_plugin->argv == NULL){
128
130
  }
129
131
  new_plugin->argv[0] = copy_name;
130
132
  new_plugin->argv[1] = NULL;
131
 
 
 
133
  
132
134
  new_plugin->environ = malloc(sizeof(char *));
133
135
  if(new_plugin->environ == NULL){
134
136
    free(copy_name);
137
139
    return NULL;
138
140
  }
139
141
  new_plugin->environ[0] = NULL;
 
142
  
140
143
  /* Append the new plugin to the list */
141
 
  *plugin_list = new_plugin;
 
144
  plugin_list = new_plugin;
142
145
  return new_plugin;
143
146
}
144
147
 
174
177
}
175
178
 
176
179
/* Add to a plugin's environment */
177
 
static bool add_environment(plugin *p, const char *def){
 
180
static bool add_environment(plugin *p, const char *def, bool replace){
178
181
  if(p == NULL){
179
182
    return false;
180
183
  }
 
184
  /* namelen = length of name of environment variable */
 
185
  size_t namelen = (size_t)(strchrnul(def, '=') - def);
 
186
  /* Search for this environment variable */
 
187
  for(char **e = p->environ; *e != NULL; e++){
 
188
    if(strncmp(*e, def, namelen + 1) == 0){
 
189
      /* It already exists */
 
190
      if(replace){
 
191
        char *new = realloc(*e, strlen(def) + 1);
 
192
        if(new == NULL){
 
193
          return false;
 
194
        }
 
195
        *e = new;
 
196
        strcpy(*e, def);
 
197
      }
 
198
      return true;
 
199
    }
 
200
  }
181
201
  return add_to_char_array(def, &(p->environ), &(p->envc));
182
202
}
183
203
 
184
 
 
185
204
/*
186
205
 * Based on the example in the GNU LibC manual chapter 13.13 "File
187
206
 * Descriptor Flags".
188
207
 * *Note File Descriptor Flags:(libc)Descriptor Flags.
189
208
 */
190
 
static int set_cloexec_flag(int fd)
191
 
{
 
209
static int set_cloexec_flag(int fd){
192
210
  int ret = fcntl(fd, F_GETFD, 0);
193
211
  /* If reading the flags failed, return error indication now. */
194
212
  if(ret < 0){
198
216
  return fcntl(fd, F_SETFD, ret | FD_CLOEXEC);
199
217
}
200
218
 
201
 
process *process_list = NULL;
202
219
 
203
220
/* Mark processes as completed when they exit, and save their exit
204
221
   status. */
205
 
void handle_sigchld(__attribute__((unused)) int sig){
 
222
static void handle_sigchld(__attribute__((unused)) int sig){
206
223
  while(true){
207
 
    process *proc = process_list;
 
224
    plugin *proc = plugin_list;
208
225
    int status;
209
226
    pid_t pid = waitpid(-1, &status, WNOHANG);
210
227
    if(pid == 0){
218
235
      /* No child processes */
219
236
      break;
220
237
    }
221
 
 
 
238
    
222
239
    /* A child exited, find it in process_list */
223
240
    while(proc != NULL and proc->pid != pid){
224
241
      proc = proc->next;
232
249
  }
233
250
}
234
251
 
235
 
bool print_out_password(const char *buffer, size_t length){
 
252
/* Prints out a password to stdout */
 
253
static bool print_out_password(const char *buffer, size_t length){
236
254
  ssize_t ret;
237
 
  if(length>0 and buffer[length-1] == '\n'){
238
 
    length--;
239
 
  }
240
255
  for(size_t written = 0; written < length; written += (size_t)ret){
241
256
    ret = TEMP_FAILURE_RETRY(write(STDOUT_FILENO, buffer + written,
242
257
                                   length - written));
247
262
  return true;
248
263
}
249
264
 
250
 
char **add_to_argv(char **argv, int *argc, char *arg){
251
 
  if (argv == NULL){
252
 
    *argc = 1;
253
 
    argv = malloc(sizeof(char*) * 2);
254
 
    if(argv == NULL){
255
 
      return NULL;
 
265
/* Removes and free a plugin from the plugin list */
 
266
static void free_plugin(plugin *plugin_node){
 
267
  
 
268
  for(char **arg = plugin_node->argv; *arg != NULL; arg++){
 
269
    free(*arg);
 
270
  }
 
271
  free(plugin_node->argv);
 
272
  for(char **env = plugin_node->environ; *env != NULL; env++){
 
273
    free(*env);
 
274
  }
 
275
  free(plugin_node->environ);
 
276
  free(plugin_node->buffer);
 
277
 
 
278
  /* Removes the plugin from the singly-linked list */
 
279
  if(plugin_node == plugin_list){
 
280
    /* First one - simple */
 
281
    plugin_list = plugin_list->next;
 
282
  } else {
 
283
    /* Second one or later */
 
284
    for(plugin *p = plugin_list; p != NULL; p = p->next){
 
285
      if(p->next == plugin_node){
 
286
        p->next = plugin_node->next;
 
287
        break;
 
288
      }
256
289
    }
257
 
    argv[0] = NULL;     /* Will be set to argv[0] in main before
258
 
                           parsing */
259
 
    argv[1] = NULL;
260
 
  }
261
 
  *argc += 1;
262
 
  argv = realloc(argv, sizeof(char *)
263
 
                  * ((unsigned int) *argc + 1));
264
 
  if(argv == NULL){
265
 
    return NULL;
266
 
  }
267
 
  argv[*argc-1] = arg;
268
 
  argv[*argc] = NULL;
269
 
  return argv;
 
290
  }
 
291
  
 
292
  free(plugin_node);
270
293
}
271
294
 
272
 
static void free_plugin_list(plugin *plugin_list){
273
 
  for(plugin *next; plugin_list != NULL; plugin_list = next){
274
 
    next = plugin_list->next;
275
 
    for(char **arg = plugin_list->argv; *arg != NULL; arg++){
276
 
      free(*arg);
277
 
    }
278
 
    free(plugin_list->argv);
279
 
    for(char **env = plugin_list->environ; *env != NULL; env++){
280
 
      free(*env);
281
 
    }
282
 
    free(plugin_list->environ);
283
 
    free(plugin_list);
 
295
static void free_plugin_list(void){
 
296
  while(plugin_list != NULL){
 
297
    free_plugin(plugin_list);
284
298
  }
285
299
}
286
300
 
287
301
int main(int argc, char *argv[]){
288
 
  const char *plugindir = "/lib/mandos/plugins.d";
289
 
  const char *argfile = ARGFILE;
 
302
  char *plugindir = NULL;
 
303
  char *argfile = NULL;
290
304
  FILE *conffp;
291
305
  size_t d_name_len;
292
306
  DIR *dir = NULL;
324
338
    { .name = "global-options", .key = 'g',
325
339
      .arg = "OPTION[,OPTION[,...]]",
326
340
      .doc = "Options passed to all plugins" },
327
 
    { .name = "global-envs", .key = 'e',
 
341
    { .name = "global-env", .key = 'G',
328
342
      .arg = "VAR=value",
329
343
      .doc = "Environment variable passed to all plugins" },
330
344
    { .name = "options-for", .key = 'o',
331
345
      .arg = "PLUGIN:OPTION[,OPTION[,...]]",
332
346
      .doc = "Options passed only to specified plugin" },
333
 
    { .name = "envs-for", .key = 'f',
 
347
    { .name = "env-for", .key = 'E',
334
348
      .arg = "PLUGIN:ENV=value",
335
349
      .doc = "Environment variable passed to specified plugin" },
336
350
    { .name = "disable", .key = 'd',
337
351
      .arg = "PLUGIN",
338
352
      .doc = "Disable a specific plugin", .group = 1 },
 
353
    { .name = "enable", .key = 'e',
 
354
      .arg = "PLUGIN",
 
355
      .doc = "Enable a specific plugin", .group = 1 },
339
356
    { .name = "plugin-dir", .key = 128,
340
357
      .arg = "DIRECTORY",
341
358
      .doc = "Specify a different plugin directory", .group = 2 },
342
 
    { .name = "userid", .key = 129,
343
 
      .arg = "ID", .flags = 0,
344
 
      .doc = "User ID the plugins will run as", .group = 2 },
345
 
    { .name = "groupid", .key = 130,
346
 
      .arg = "ID", .flags = 0,
347
 
      .doc = "Group ID the plugins will run as", .group = 2 },
348
 
    { .name = "debug", .key = 131,
349
 
      .doc = "Debug mode", .group = 3 },
 
359
    { .name = "config-file", .key = 129,
 
360
      .arg = "FILE",
 
361
      .doc = "Specify a different configuration file", .group = 2 },
 
362
    { .name = "userid", .key = 130,
 
363
      .arg = "ID", .flags = 0,
 
364
      .doc = "User ID the plugins will run as", .group = 3 },
 
365
    { .name = "groupid", .key = 131,
 
366
      .arg = "ID", .flags = 0,
 
367
      .doc = "Group ID the plugins will run as", .group = 3 },
 
368
    { .name = "debug", .key = 132,
 
369
      .doc = "Debug mode", .group = 4 },
350
370
    { .name = NULL }
351
371
  };
352
372
  
353
 
  error_t parse_opt (int key, char *arg, struct argp_state *state) {
354
 
    /* Get the INPUT argument from `argp_parse', which we know is a
355
 
       pointer to our plugin list pointer. */
356
 
    plugin **plugins = state->input;
 
373
  error_t parse_opt (int key, char *arg, __attribute__((unused))
 
374
                     struct argp_state *state) {
357
375
    switch (key) {
358
 
    case 'g':
 
376
    case 'g':                   /* --global-options */
359
377
      if (arg != NULL){
360
378
        char *p;
361
379
        while((p = strsep(&arg, ",")) != NULL){
362
380
          if(p[0] == '\0'){
363
381
            continue;
364
382
          }
365
 
          if(not add_argument(getplugin(NULL, plugins), p)){
 
383
          if(not add_argument(getplugin(NULL), p)){
366
384
            perror("add_argument");
367
385
            return ARGP_ERR_UNKNOWN;
368
386
          }
369
387
        }
370
388
      }
371
389
      break;
372
 
    case 'e':
 
390
    case 'G':                   /* --global-env */
373
391
      if(arg == NULL){
374
392
        break;
375
393
      }
376
 
      {
377
 
        char *envdef = strdup(arg);
378
 
        if(envdef == NULL){
379
 
          break;
380
 
        }
381
 
        if(not add_environment(getplugin(NULL, plugins), envdef)){
382
 
          perror("add_environment");
383
 
        }
 
394
      if(not add_environment(getplugin(NULL), arg, true)){
 
395
        perror("add_environment");
384
396
      }
385
397
      break;
386
 
    case 'o':
 
398
    case 'o':                   /* --options-for */
387
399
      if (arg != NULL){
388
400
        char *p_name = strsep(&arg, ":");
389
 
        if(p_name[0] == '\0'){
 
401
        if(p_name[0] == '\0' or arg == NULL){
390
402
          break;
391
403
        }
392
404
        char *opt = strsep(&arg, ":");
393
 
        if(opt[0] == '\0'){
 
405
        if(opt[0] == '\0' or opt == NULL){
394
406
          break;
395
407
        }
396
 
        if(opt != NULL){
397
 
          char *p;
398
 
          while((p = strsep(&opt, ",")) != NULL){
399
 
            if(p[0] == '\0'){
400
 
              continue;
401
 
            }
402
 
            if(not add_argument(getplugin(p_name, plugins), p)){
403
 
              perror("add_argument");
404
 
              return ARGP_ERR_UNKNOWN;
405
 
            }
 
408
        char *p;
 
409
        while((p = strsep(&opt, ",")) != NULL){
 
410
          if(p[0] == '\0'){
 
411
            continue;
 
412
          }
 
413
          if(not add_argument(getplugin(p_name), p)){
 
414
            perror("add_argument");
 
415
            return ARGP_ERR_UNKNOWN;
406
416
          }
407
417
        }
408
418
      }
409
419
      break;
410
 
    case 'f':
 
420
    case 'E':                   /* --env-for */
411
421
      if(arg == NULL){
412
422
        break;
413
423
      }
416
426
        if(envdef == NULL){
417
427
          break;
418
428
        }
419
 
        char *p_name = strndup(arg, (size_t) (envdef-arg));
420
 
        if(p_name == NULL){
421
 
          break;
422
 
        }
423
 
        envdef++;
424
 
        if(not add_environment(getplugin(p_name, plugins), envdef)){
 
429
        *envdef = '\0';
 
430
        if(not add_environment(getplugin(arg), envdef+1, true)){
425
431
          perror("add_environment");
426
432
        }
427
433
      }
428
434
      break;
429
 
    case 'd':
 
435
    case 'd':                   /* --disable */
430
436
      if (arg != NULL){
431
 
        plugin *p = getplugin(arg, plugins);
 
437
        plugin *p = getplugin(arg);
432
438
        if(p == NULL){
433
439
          return ARGP_ERR_UNKNOWN;
434
440
        }
435
441
        p->disabled = true;
436
442
      }
437
443
      break;
438
 
    case 128:
439
 
      plugindir = arg;
440
 
      break;
441
 
    case 129:
 
444
    case 'e':                   /* --enable */
 
445
      if (arg != NULL){
 
446
        plugin *p = getplugin(arg);
 
447
        if(p == NULL){
 
448
          return ARGP_ERR_UNKNOWN;
 
449
        }
 
450
        p->disabled = false;
 
451
      }
 
452
      break;
 
453
    case 128:                   /* --plugin-dir */
 
454
      free(plugindir);
 
455
      plugindir = strdup(arg);
 
456
      if(plugindir == NULL){
 
457
        perror("strdup");
 
458
      }      
 
459
      break;
 
460
    case 129:                   /* --config-file */
 
461
      /* This is already done by parse_opt_config_file() */
 
462
      break;
 
463
    case 130:                   /* --userid */
442
464
      uid = (uid_t)strtol(arg, NULL, 10);
443
465
      break;
444
 
    case 130:
 
466
    case 131:                   /* --groupid */
445
467
      gid = (gid_t)strtol(arg, NULL, 10);
446
468
      break;
447
 
    case 131:
 
469
    case 132:                   /* --debug */
448
470
      debug = true;
449
471
      break;
450
472
    case ARGP_KEY_ARG:
451
 
      fprintf(stderr, "Ignoring unknown argument \"%s\"\n", arg);
452
 
      break;
453
 
    case ARGP_KEY_END:
454
 
      break;
455
 
    default:
456
 
      return ARGP_ERR_UNKNOWN;
457
 
    }
458
 
    return 0;
459
 
  }
460
 
  
461
 
  plugin *plugin_list = NULL;
462
 
  
463
 
  struct argp argp = { .options = options, .parser = parse_opt,
464
 
                       .args_doc = "[+PLUS_SEPARATED_OPTIONS]",
 
473
      /* Cryptsetup always passes an argument, which is an empty
 
474
         string if "none" was specified in /etc/crypttab.  So if
 
475
         argument was empty, we ignore it silently. */
 
476
      if(arg[0] != '\0'){
 
477
        fprintf(stderr, "Ignoring unknown argument \"%s\"\n", arg);
 
478
      }
 
479
      break;
 
480
    case ARGP_KEY_END:
 
481
      break;
 
482
    default:
 
483
      return ARGP_ERR_UNKNOWN;
 
484
    }
 
485
    return 0;
 
486
  }
 
487
  
 
488
  /* This option parser is the same as parse_opt() above, except it
 
489
     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) {
 
494
    case 'g':                   /* --global-options */
 
495
    case 'G':                   /* --global-env */
 
496
    case 'o':                   /* --options-for */
 
497
    case 'E':                   /* --env-for */
 
498
    case 'd':                   /* --disable */
 
499
    case 'e':                   /* --enable */
 
500
    case 128:                   /* --plugin-dir */
 
501
      break;
 
502
    case 129:                   /* --config-file */
 
503
      free(argfile);
 
504
      argfile = strdup(arg);
 
505
      if(argfile == NULL){
 
506
        perror("strdup");
 
507
      }
 
508
      break;      
 
509
    case 130:                   /* --userid */
 
510
    case 131:                   /* --groupid */
 
511
    case 132:                   /* --debug */
 
512
    case ARGP_KEY_ARG:
 
513
    case ARGP_KEY_END:
 
514
      break;
 
515
    default:
 
516
      return ARGP_ERR_UNKNOWN;
 
517
    }
 
518
    return 0;
 
519
  }
 
520
  
 
521
  struct argp argp = { .options = options,
 
522
                       .parser = parse_opt_config_file,
 
523
                       .args_doc = "",
465
524
                       .doc = "Mandos plugin runner -- Run plugins" };
466
525
  
467
 
  ret = argp_parse (&argp, argc, argv, 0, 0, &plugin_list);
 
526
  /* Parse using the parse_opt_config_file in order to get the custom
 
527
     config file location, if any. */
 
528
  ret = argp_parse (&argp, argc, argv, ARGP_IN_ORDER, 0, NULL);
468
529
  if (ret == ARGP_ERR_UNKNOWN){
469
530
    fprintf(stderr, "Unknown error while parsing arguments\n");
470
531
    exitstatus = EXIT_FAILURE;
471
532
    goto fallback;
472
533
  }
473
 
 
474
 
  conffp = fopen(argfile, "r");
 
534
  
 
535
  /* Reset to the normal argument parser */
 
536
  argp.parser = parse_opt;
 
537
  
 
538
  /* Open the configfile if available */
 
539
  if (argfile == NULL){
 
540
    conffp = fopen(AFILE, "r");
 
541
  } else {
 
542
    conffp = fopen(argfile, "r");
 
543
  }  
475
544
  if(conffp != NULL){
476
545
    char *org_line = NULL;
477
546
    char *p, *arg, *new_arg, *line;
480
549
    const char whitespace_delims[] = " \r\t\f\v\n";
481
550
    const char comment_delim[] = "#";
482
551
 
 
552
    custom_argc = 1;
 
553
    custom_argv = malloc(sizeof(char*) * 2);
 
554
    if(custom_argv == NULL){
 
555
      perror("malloc");
 
556
      exitstatus = EXIT_FAILURE;
 
557
      goto fallback;
 
558
    }
 
559
    custom_argv[0] = argv[0];
 
560
    custom_argv[1] = NULL;
 
561
 
 
562
    /* for each line in the config file, strip whitespace and ignore
 
563
       commented text */
483
564
    while(true){
484
565
      sret = getline(&org_line, &size, conffp);
485
566
      if(sret == -1){
493
574
          continue;
494
575
        }
495
576
        new_arg = strdup(p);
496
 
        custom_argv = add_to_argv(custom_argv, &custom_argc, new_arg);
497
 
        if (custom_argv == NULL){
498
 
          perror("add_to_argv");
499
 
          exitstatus = EXIT_FAILURE;
500
 
          goto fallback;
501
 
        }
 
577
        if(new_arg == NULL){
 
578
          perror("strdup");
 
579
          exitstatus = EXIT_FAILURE;
 
580
          free(org_line);
 
581
          goto fallback;
 
582
        }
 
583
        
 
584
        custom_argc += 1;
 
585
        custom_argv = realloc(custom_argv, sizeof(char *)
 
586
                              * ((unsigned int) custom_argc + 1));
 
587
        if(custom_argv == NULL){
 
588
          perror("realloc");
 
589
          exitstatus = EXIT_FAILURE;
 
590
          free(org_line);
 
591
          goto fallback;
 
592
        }
 
593
        custom_argv[custom_argc-1] = new_arg;
 
594
        custom_argv[custom_argc] = NULL;        
502
595
      }
503
596
    }
504
597
    free(org_line);
505
 
  } else{
 
598
  } else {
506
599
    /* Check for harmful errors and go to fallback. Other errors might
507
600
       not affect opening plugins */
508
601
    if (errno == EMFILE or errno == ENFILE or errno == ENOMEM){
511
604
      goto fallback;
512
605
    }
513
606
  }
514
 
 
 
607
  /* If there was any arguments from configuration file,
 
608
     pass them to parser as command arguments */
515
609
  if(custom_argv != NULL){
516
 
    custom_argv[0] = argv[0];
517
 
    ret = argp_parse (&argp, custom_argc, custom_argv, 0, 0,
518
 
                      &plugin_list);
 
610
    ret = argp_parse (&argp, custom_argc, custom_argv, ARGP_IN_ORDER,
 
611
                      0, NULL);
519
612
    if (ret == ARGP_ERR_UNKNOWN){
520
613
      fprintf(stderr, "Unknown error while parsing arguments\n");
521
614
      exitstatus = EXIT_FAILURE;
523
616
    }
524
617
  }
525
618
  
 
619
  /* Parse actual command line arguments, to let them override the
 
620
     config file */
 
621
  ret = argp_parse (&argp, argc, argv, ARGP_IN_ORDER, 0, NULL);
 
622
  if (ret == ARGP_ERR_UNKNOWN){
 
623
    fprintf(stderr, "Unknown error while parsing arguments\n");
 
624
    exitstatus = EXIT_FAILURE;
 
625
    goto fallback;
 
626
  }
 
627
  
526
628
  if(debug){
527
629
    for(plugin *p = plugin_list; p != NULL; p=p->next){
528
630
      fprintf(stderr, "Plugin: %s has %d arguments\n",
537
639
    }
538
640
  }
539
641
  
 
642
  /* Strip permissions down to nobody */
540
643
  ret = setuid(uid);
541
644
  if (ret == -1){
542
645
    perror("setuid");
543
 
  }
544
 
  
 
646
  }  
545
647
  setgid(gid);
546
648
  if (ret == -1){
547
649
    perror("setgid");
548
650
  }
549
651
  
550
 
  dir = opendir(plugindir);
 
652
  if (plugindir == NULL){
 
653
    dir = opendir(PDIR);
 
654
  } else {
 
655
    dir = opendir(plugindir);
 
656
  }
 
657
  
551
658
  if(dir == NULL){
552
659
    perror("Could not open plugin dir");
553
660
    exitstatus = EXIT_FAILURE;
569
676
  
570
677
  FD_ZERO(&rfds_all);
571
678
  
 
679
  /* Read and execute any executable in the plugin directory*/
572
680
  while(true){
573
681
    dirst = readdir(dir);
574
682
    
575
 
    // All directory entries have been processed
 
683
    /* All directory entries have been processed */
576
684
    if(dirst == NULL){
577
685
      if (errno == EBADF){
578
686
        perror("readdir");
584
692
    
585
693
    d_name_len = strlen(dirst->d_name);
586
694
    
587
 
    // Ignore dotfiles, backup files and other junk
 
695
    /* Ignore dotfiles, backup files and other junk */
588
696
    {
589
697
      bool bad_name = false;
590
698
      
605
713
          break;
606
714
        }
607
715
      }
608
 
      
609
716
      if(bad_name){
610
717
        continue;
611
718
      }
612
 
      
613
719
      for(const char **suf = bad_suffixes; *suf != NULL; suf++){
614
720
        size_t suf_len = strlen(*suf);
615
721
        if((d_name_len >= suf_len)
630
736
    }
631
737
 
632
738
    char *filename;
633
 
    ret = asprintf(&filename, "%s/%s", plugindir, dirst->d_name);
 
739
    if(plugindir == NULL){
 
740
      ret = asprintf(&filename, PDIR "/%s", dirst->d_name);
 
741
    } else {
 
742
      ret = asprintf(&filename, "%s/%s", plugindir, dirst->d_name);
 
743
    }
634
744
    if(ret < 0){
635
745
      perror("asprintf");
636
746
      continue;
642
752
      free(filename);
643
753
      continue;
644
754
    }
645
 
    
 
755
 
 
756
    /* Ignore non-executable files */
646
757
    if (not S_ISREG(st.st_mode) or (access(filename, X_OK) != 0)){
647
758
      if(debug){
648
759
        fprintf(stderr, "Ignoring plugin dir entry \"%s\""
651
762
      free(filename);
652
763
      continue;
653
764
    }
654
 
    plugin *p = getplugin(dirst->d_name, &plugin_list);
 
765
    
 
766
    plugin *p = getplugin(dirst->d_name);
655
767
    if(p == NULL){
656
768
      perror("getplugin");
657
769
      free(filename);
667
779
    }
668
780
    {
669
781
      /* Add global arguments to argument list for this plugin */
670
 
      plugin *g = getplugin(NULL, &plugin_list);
 
782
      plugin *g = getplugin(NULL);
671
783
      if(g != NULL){
672
784
        for(char **a = g->argv + 1; *a != NULL; a++){
673
785
          if(not add_argument(p, *a)){
676
788
        }
677
789
        /* Add global environment variables */
678
790
        for(char **e = g->environ; *e != NULL; e++){
679
 
          if(not add_environment(p, *e)){
 
791
          if(not add_environment(p, *e, false)){
680
792
            perror("add_environment");
681
793
          }
682
794
        }
687
799
       process, too. */
688
800
    if(p->environ[0] != NULL){
689
801
      for(char **e = environ; *e != NULL; e++){
690
 
        char *copy = strdup(*e);
691
 
        if(copy == NULL){
692
 
          perror("strdup");
693
 
          continue;
694
 
        }
695
 
        if(not add_environment(p, copy)){
 
802
        if(not add_environment(p, *e, false)){
696
803
          perror("add_environment");
697
804
        }
698
805
      }
705
812
      exitstatus = EXIT_FAILURE;
706
813
      goto fallback;
707
814
    }
 
815
    /* Ask OS to automatic close the pipe on exec */
708
816
    ret = set_cloexec_flag(pipefd[0]);
709
817
    if(ret < 0){
710
818
      perror("set_cloexec_flag");
724
832
      exitstatus = EXIT_FAILURE;
725
833
      goto fallback;
726
834
    }
727
 
    // Starting a new process to be watched
 
835
    /* Starting a new process to be watched */
728
836
    pid_t pid = fork();
729
837
    if(pid == -1){
730
838
      perror("fork");
738
846
        perror("sigaction");
739
847
        _exit(EXIT_FAILURE);
740
848
      }
741
 
      ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
 
849
      ret = sigprocmask(SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
742
850
      if(ret < 0){
743
851
        perror("sigprocmask");
744
852
        _exit(EXIT_FAILURE);
745
853
      }
746
 
 
 
854
      
747
855
      ret = dup2(pipefd[1], STDOUT_FILENO); /* replace our stdout */
748
856
      if(ret == -1){
749
857
        perror("dup2");
768
876
      }
769
877
      /* no return */
770
878
    }
771
 
    /* parent process */
 
879
    /* Parent process */
 
880
    close(pipefd[1]);           /* Close unused write end of pipe */
772
881
    free(filename);
773
 
    close(pipefd[1]);           /* close unused write end of pipe */
774
 
    process *new_process = malloc(sizeof(process));
775
 
    if (new_process == NULL){
776
 
      perror("malloc");
 
882
    plugin *new_plugin = getplugin(dirst->d_name);
 
883
    if (new_plugin == NULL){
 
884
      perror("getplugin");
777
885
      ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
778
886
      if(ret < 0){
779
 
        perror("sigprocmask");
 
887
        perror("sigprocmask");
780
888
      }
781
889
      exitstatus = EXIT_FAILURE;
782
890
      goto fallback;
783
891
    }
784
892
    
785
 
    *new_process = (struct process){ .pid = pid,
786
 
                                     .fd = pipefd[0],
787
 
                                     .next = process_list };
788
 
    // List handling
789
 
    process_list = new_process;
 
893
    new_plugin->pid = pid;
 
894
    new_plugin->fd = pipefd[0];
 
895
    
790
896
    /* Unblock SIGCHLD so signal handler can be run if this process
791
897
       has already completed */
792
898
    ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
796
902
      goto fallback;
797
903
    }
798
904
    
799
 
    FD_SET(new_process->fd, &rfds_all);
 
905
    FD_SET(new_plugin->fd, &rfds_all);
800
906
    
801
 
    if (maxfd < new_process->fd){
802
 
      maxfd = new_process->fd;
 
907
    if (maxfd < new_plugin->fd){
 
908
      maxfd = new_plugin->fd;
803
909
    }
804
 
    
805
910
  }
806
911
  
807
 
  free_plugin_list(plugin_list);
808
 
  plugin_list = NULL;
809
 
  
810
912
  closedir(dir);
811
913
  dir = NULL;
812
 
    
813
 
  if (process_list == NULL){
814
 
    fprintf(stderr, "No plugin processes started. Incorrect plugin"
815
 
            " directory?\n");
816
 
    process_list = NULL;
 
914
  
 
915
  for(plugin *p = plugin_list; p != NULL; p = p->next){
 
916
    if(p->pid != 0){
 
917
      break;
 
918
    }
 
919
    if(p->next == NULL){
 
920
      fprintf(stderr, "No plugin processes started. Incorrect plugin"
 
921
              " directory?\n");
 
922
      free_plugin_list();
 
923
    }
817
924
  }
818
 
  while(process_list){
 
925
  
 
926
  /* Main loop while running plugins exist */
 
927
  while(plugin_list){
819
928
    fd_set rfds = rfds_all;
820
929
    int select_ret = select(maxfd+1, &rfds, NULL, NULL, NULL);
821
930
    if (select_ret == -1){
825
934
    }
826
935
    /* OK, now either a process completed, or something can be read
827
936
       from one of them */
828
 
    for(process *proc = process_list; proc ; proc = proc->next){
 
937
    for(plugin *proc = plugin_list; proc != NULL;){
829
938
      /* Is this process completely done? */
830
939
      if(proc->eof and proc->completed){
831
940
        /* Only accept the plugin output if it exited cleanly */
832
941
        if(not WIFEXITED(proc->status)
833
942
           or WEXITSTATUS(proc->status) != 0){
834
943
          /* Bad exit by plugin */
 
944
 
835
945
          if(debug){
836
946
            if(WIFEXITED(proc->status)){
837
947
              fprintf(stderr, "Plugin %u exited with status %d\n",
846
956
                      (unsigned int) (proc->pid));
847
957
            }
848
958
          }
 
959
          
849
960
          /* Remove the plugin */
850
961
          FD_CLR(proc->fd, &rfds_all);
 
962
 
851
963
          /* Block signal while modifying process_list */
852
964
          ret = sigprocmask(SIG_BLOCK, &sigchld_action.sa_mask, NULL);
853
965
          if(ret < 0){
855
967
            exitstatus = EXIT_FAILURE;
856
968
            goto fallback;
857
969
          }
858
 
          /* Delete this process entry from the list */
859
 
          if(process_list == proc){
860
 
            /* First one - simple */
861
 
            process_list = proc->next;
862
 
          } else {
863
 
            /* Second one or later */
864
 
            for(process *p = process_list; p != NULL; p = p->next){
865
 
              if(p->next == proc){
866
 
                p->next = proc->next;
867
 
                break;
868
 
              }
869
 
            }
870
 
          }
 
970
          
 
971
          plugin *next_plugin = proc->next;
 
972
          free_plugin(proc);
 
973
          proc = next_plugin;
 
974
          
871
975
          /* We are done modifying process list, so unblock signal */
872
976
          ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask,
873
977
                             NULL);
874
978
          if(ret < 0){
875
979
            perror("sigprocmask");
876
 
          }
877
 
          free(proc->buffer);
878
 
          free(proc);
879
 
          /* We deleted this process from the list, so we can't go
880
 
             proc->next.  Therefore, start over from the beginning of
881
 
             the process list */
882
 
          break;
 
980
            exitstatus = EXIT_FAILURE;
 
981
            goto fallback;
 
982
          }
 
983
          
 
984
          if(plugin_list == NULL){
 
985
            break;
 
986
          }
 
987
          
 
988
          continue;
883
989
        }
 
990
        
884
991
        /* This process exited nicely, so print its buffer */
885
 
 
 
992
        
886
993
        bool bret = print_out_password(proc->buffer,
887
994
                                       proc->buffer_length);
888
995
        if(not bret){
891
998
        }
892
999
        goto fallback;
893
1000
      }
 
1001
      
894
1002
      /* This process has not completed.  Does it have any output? */
895
1003
      if(proc->eof or not FD_ISSET(proc->fd, &rfds)){
896
1004
        /* This process had nothing to say at this time */
 
1005
        proc = proc->next;
897
1006
        continue;
898
1007
      }
899
1008
      /* Before reading, make the process' data buffer large enough */
912
1021
                 BUFFER_SIZE);
913
1022
      if(ret < 0){
914
1023
        /* Read error from this process; ignore the error */
 
1024
        proc = proc->next;
915
1025
        continue;
916
1026
      }
917
1027
      if(ret == 0){
926
1036
 
927
1037
 fallback:
928
1038
  
929
 
  if(process_list == NULL or exitstatus != EXIT_SUCCESS){
 
1039
  if(plugin_list == NULL or exitstatus != EXIT_SUCCESS){
930
1040
    /* Fallback if all plugins failed, none are found or an error
931
1041
       occured */
932
1042
    bool bret;
933
1043
    fprintf(stderr, "Going to fallback mode using getpass(3)\n");
934
1044
    char *passwordbuffer = getpass("Password: ");
935
 
    bret = print_out_password(passwordbuffer, strlen(passwordbuffer));
 
1045
    size_t len = strlen(passwordbuffer);
 
1046
    /* Strip trailing newline */
 
1047
    if(len > 0 and passwordbuffer[len-1] == '\n'){
 
1048
      passwordbuffer[len-1] = '\0'; /* not strictly necessary */
 
1049
      len--;
 
1050
    }
 
1051
    bret = print_out_password(passwordbuffer, len);
936
1052
    if(not bret){
937
1053
      perror("print_out_password");
938
1054
      exitstatus = EXIT_FAILURE;
945
1061
    perror("sigaction");
946
1062
    exitstatus = EXIT_FAILURE;
947
1063
  }
948
 
 
 
1064
  
949
1065
  if(custom_argv != NULL){
950
 
    for(char **arg = custom_argv; *arg != NULL; arg++){
 
1066
    for(char **arg = custom_argv+1; *arg != NULL; arg++){
951
1067
      free(*arg);
952
1068
    }
953
1069
    free(custom_argv);
954
1070
  }
955
 
  free_plugin_list(plugin_list);
956
1071
  
957
1072
  if(dir != NULL){
958
1073
    closedir(dir);
959
1074
  }
960
1075
  
961
 
  /* Free the process list and kill the processes */
962
 
  for(process *next; process_list != NULL; process_list = next){
963
 
    next = process_list->next;
964
 
    close(process_list->fd);
965
 
    ret = kill(process_list->pid, SIGTERM);
966
 
    if(ret == -1 and errno != ESRCH){
967
 
      /* set-uid proccesses migth not get closed */
968
 
      perror("kill");
 
1076
  /* Kill the processes */
 
1077
  for(plugin *p = plugin_list; p != NULL; p = p->next){
 
1078
    if(p->pid != 0){
 
1079
      close(p->fd);
 
1080
      ret = kill(p->pid, SIGTERM);
 
1081
      if(ret == -1 and errno != ESRCH){
 
1082
        /* Set-uid proccesses might not get closed */
 
1083
        perror("kill");
 
1084
      }
969
1085
    }
970
 
    free(process_list->buffer);
971
 
    free(process_list);
972
1086
  }
973
1087
  
974
1088
  /* Wait for any remaining child processes to terminate */
979
1093
    perror("wait");
980
1094
  }
981
1095
  
 
1096
  free_plugin_list();
 
1097
  
 
1098
  free(plugindir);
 
1099
  free(argfile);
 
1100
  
982
1101
  return exitstatus;
983
1102
}