/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

merge

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