/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-08-31 09:26:12 UTC
  • Revision ID: teddy@fukt.bsnet.se-20080831092612-atz9uzia38h1ijy5
* mandos.xml (OPTIONS): Moved long options before short.  Use <option>
                        tags instead of <literal>.

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