/mandos/release

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/release

« back to all changes in this revision

Viewing changes to plugin-runner.c

  • Committer: Teddy Hogeborn
  • Date: 2008-08-24 09:40:58 UTC
  • Revision ID: teddy@fukt.bsnet.se-20080824094058-bdqng3t1e3hfnk2e
* plugin-runner.c (getplugin): Only copy "name" if not NULL.  Free
                               "copy_name" if any error occurs.
  (free_plugin_list): Do not free "name" member; it it freed as part
                      of argv.
  (main): Set plugin_list to NULL after freeing it.

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