/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

transformed a function to a part of main

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