/mandos/trunk

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

« back to all changes in this revision

Viewing changes to plugin-runner.c

  • Committer: Teddy Hogeborn
  • Date: 2008-09-01 16:53:17 UTC
  • Revision ID: teddy@fukt.bsnet.se-20080901165317-77dccp81zyqimt2j
* plugin-runner.c (add_environment): Override existing environment
                                     variables when asked to do so.
                                     All callers changed.
  (main): Removed old argp.args_doc string.  Parse argument file
          before normal command line arguments.  Use ARGP_IN_ORDER
          flag in both calls to argp_parse.  Do not strdup() strings
          to be sent to add_environment().

* plugin-runner.xml (OPTIONS): Document "--global-env" and "--envs-for".
  (FILES): Note that the config file is parsed before the command line
           options.

Show diffs side-by-side

added added

removed removed

Lines of Context:
21
21
 * Contact the authors at <mandos@fukt.bsnet.se>.
22
22
 */
23
23
 
24
 
#define _GNU_SOURCE             /* TEMP_FAILURE_RETRY() */
25
 
 
 
24
#define _GNU_SOURCE             /* TEMP_FAILURE_RETRY(), getline(),
 
25
                                   asprintf() */
26
26
#include <stddef.h>             /* size_t, NULL */
27
27
#include <stdlib.h>             /* malloc(), exit(), EXIT_FAILURE,
28
28
                                   EXIT_SUCCESS, realloc() */
51
51
                                   close() */
52
52
#include <fcntl.h>              /* fcntl(), F_GETFD, F_SETFD,
53
53
                                   FD_CLOEXEC */
54
 
#include <string.h>             /* strtok, strlen(), strcpy(),
55
 
                                   strcat() */
 
54
#include <string.h>             /* strsep, strlen(), asprintf() */
56
55
#include <errno.h>              /* errno */
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, error_t */
 
59
                                   ARGP_KEY_END, ARGP_KEY_ARG,
 
60
                                   error_t */
61
61
#include <signal.h>             /* struct sigaction, sigemptyset(),
62
62
                                   sigaddset(), sigaction(),
63
63
                                   sigprocmask(), SIG_BLOCK, SIGCHLD,
66
66
 
67
67
#define BUFFER_SIZE 256
68
68
 
69
 
const char *argp_program_version = "mandos-client 1.0";
 
69
#define PDIR "/lib/mandos/plugins.d"
 
70
#define AFILE "/conf/conf.d/mandos/plugin-runner.conf"
 
71
 
 
72
const char *argp_program_version = "plugin-runner 1.0";
70
73
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
71
74
 
72
 
struct process;
73
 
 
74
 
typedef struct process{
 
75
struct plugin;
 
76
 
 
77
typedef struct plugin{
 
78
  char *name;                   /* can be NULL or any plugin name */
 
79
  char **argv;
 
80
  int argc;
 
81
  char **environ;
 
82
  int envc;
 
83
  bool disabled;
 
84
 
 
85
  /* Variables used for running processes*/
75
86
  pid_t pid;
76
87
  int fd;
77
88
  char *buffer;
78
89
  size_t buffer_size;
79
90
  size_t buffer_length;
80
91
  bool eof;
81
 
  bool completed;
82
 
  int status;
83
 
  struct process *next;
84
 
} process;
85
 
 
86
 
typedef struct plugin{
87
 
  char *name;                   /* can be NULL or any plugin name */
88
 
  char **argv;
89
 
  int argc;
90
 
  bool disabled;
 
92
  volatile bool completed;
 
93
  volatile int status;
91
94
  struct plugin *next;
92
95
} plugin;
93
96
 
94
 
static plugin *getplugin(char *name, plugin **plugin_list){
95
 
  for (plugin *p = *plugin_list; p != NULL; p = p->next){
 
97
static plugin *plugin_list = NULL;
 
98
 
 
99
/* Gets a existing plugin based on name,
 
100
   or if none is found, creates a new one */
 
101
static plugin *getplugin(char *name){
 
102
  /* Check for exiting plugin with that name */
 
103
  for (plugin *p = plugin_list; p != NULL; p = p->next){
96
104
    if ((p->name == name)
97
105
        or (p->name and name and (strcmp(p->name, name) == 0))){
98
106
      return p;
101
109
  /* Create a new plugin */
102
110
  plugin *new_plugin = malloc(sizeof(plugin));
103
111
  if (new_plugin == NULL){
104
 
    perror("malloc");
105
 
    exit(EXIT_FAILURE);
106
 
  }
107
 
  new_plugin->name = name;
 
112
    return NULL;
 
113
  }
 
114
  char *copy_name = NULL;
 
115
  if(name != NULL){
 
116
    copy_name = strdup(name);
 
117
    if(copy_name == NULL){
 
118
      return NULL;
 
119
    }
 
120
  }
 
121
 
 
122
  *new_plugin = (plugin) { .name = copy_name,
 
123
                           .argc = 1,
 
124
                           .disabled = false,
 
125
                           .next = plugin_list };
 
126
  
108
127
  new_plugin->argv = malloc(sizeof(char *) * 2);
109
128
  if (new_plugin->argv == NULL){
110
 
    perror("malloc");
111
 
    exit(EXIT_FAILURE);
 
129
    free(copy_name);
 
130
    free(new_plugin);
 
131
    return NULL;
112
132
  }
113
 
  new_plugin->argv[0] = name;
 
133
  new_plugin->argv[0] = copy_name;
114
134
  new_plugin->argv[1] = NULL;
115
 
  new_plugin->argc = 1;
116
 
  new_plugin->disabled = false;
117
 
  new_plugin->next = *plugin_list;
 
135
  
 
136
  new_plugin->environ = malloc(sizeof(char *));
 
137
  if(new_plugin->environ == NULL){
 
138
    free(copy_name);
 
139
    free(new_plugin->argv);
 
140
    free(new_plugin);
 
141
    return NULL;
 
142
  }
 
143
  new_plugin->environ[0] = NULL;
 
144
  
118
145
  /* Append the new plugin to the list */
119
 
  *plugin_list = new_plugin;
 
146
  plugin_list = new_plugin;
120
147
  return new_plugin;
121
148
}
122
149
 
123
 
static void addargument(plugin *p, char *arg){
124
 
  p->argv[p->argc] = arg;
125
 
  p->argv = realloc(p->argv, sizeof(char *) * (size_t)(p->argc + 2));
126
 
  if (p->argv == NULL){
127
 
    perror("malloc");
128
 
    exit(EXIT_FAILURE);
129
 
  }
130
 
  p->argc++;
131
 
  p->argv[p->argc] = NULL;
 
150
/* Helper function for add_argument and add_environment */
 
151
static bool add_to_char_array(const char *new, char ***array,
 
152
                              int *len){
 
153
  /* Resize the pointed-to array to hold one more pointer */
 
154
  *array = realloc(*array, sizeof(char *)
 
155
                   * (size_t) ((*len) + 2));
 
156
  /* Malloc check */
 
157
  if(*array == NULL){
 
158
    return false;
 
159
  }
 
160
  /* Make a copy of the new string */
 
161
  char *copy = strdup(new);
 
162
  if(copy == NULL){
 
163
    return false;
 
164
  }
 
165
  /* Insert the copy */
 
166
  (*array)[*len] = copy;
 
167
  (*len)++;
 
168
  /* Add a new terminating NULL pointer to the last element */
 
169
  (*array)[*len] = NULL;
 
170
  return true;
 
171
}
 
172
 
 
173
/* Add to a plugin's argument vector */
 
174
static bool add_argument(plugin *p, const char *arg){
 
175
  if(p == NULL){
 
176
    return false;
 
177
  }
 
178
  return add_to_char_array(arg, &(p->argv), &(p->argc));
 
179
}
 
180
 
 
181
/* Add to a plugin's environment */
 
182
static bool add_environment(plugin *p, const char *def, bool replace){
 
183
  if(p == NULL){
 
184
    return false;
 
185
  }
 
186
  /* namelen = length of name of environment variable */
 
187
  size_t namelen = (size_t)(strchrnul(def, '=') - def);
 
188
  /* Search for this environment variable */
 
189
  for(char **e = p->environ; *e != NULL; e++){
 
190
    if(strncmp(*e, def, namelen+1) == 0){
 
191
      /* It already exists */
 
192
      if(replace){
 
193
        char *new = realloc(*e, strlen(def));
 
194
        if(new == NULL){
 
195
          return false;
 
196
        }
 
197
        *e = new;
 
198
        strcpy(*e, def);
 
199
      }
 
200
      return true;
 
201
    }
 
202
  }
 
203
  return add_to_char_array(def, &(p->environ), &(p->envc));
132
204
}
133
205
 
134
206
/*
147
219
  return fcntl(fd, F_SETFD, ret | FD_CLOEXEC);
148
220
}
149
221
 
150
 
process *process_list = NULL;
151
222
 
152
 
/* Mark a process as completed when it exits, and save its exit
 
223
/* Mark processes as completed when they exit, and save their exit
153
224
   status. */
154
225
void handle_sigchld(__attribute__((unused)) int sig){
155
 
  process *proc = process_list;
156
 
  int status;
157
 
  pid_t pid = wait(&status);
158
 
  if(pid == -1){
159
 
    perror("wait");
160
 
    return;
161
 
  }
162
 
  while(proc != NULL and proc->pid != pid){
163
 
    proc = proc->next;
164
 
  }
165
 
  if(proc == NULL){
166
 
    /* Process not found in process list */
167
 
    return;
168
 
  }
169
 
  proc->status = status;
170
 
  proc->completed = true;
 
226
  while(true){
 
227
    plugin *proc = plugin_list;
 
228
    int status;
 
229
    pid_t pid = waitpid(-1, &status, WNOHANG);
 
230
    if(pid == 0){
 
231
      /* Only still running child processes */
 
232
      break;
 
233
    }
 
234
    if(pid == -1){
 
235
      if (errno != ECHILD){
 
236
        perror("waitpid");
 
237
      }
 
238
      /* No child processes */
 
239
      break;
 
240
    }
 
241
 
 
242
    /* A child exited, find it in process_list */
 
243
    while(proc != NULL and proc->pid != pid){
 
244
      proc = proc->next;
 
245
    }
 
246
    if(proc == NULL){
 
247
      /* Process not found in process list */
 
248
      continue;
 
249
    }
 
250
    proc->status = status;
 
251
    proc->completed = true;
 
252
  }
171
253
}
172
254
 
 
255
/* Prints out a password to stdout */
173
256
bool print_out_password(const char *buffer, size_t length){
174
 
  size_t ret;
175
 
  for(size_t written = 0; written < length; written += ret){
 
257
  ssize_t ret;
 
258
  if(length>0 and buffer[length-1] == '\n'){
 
259
    length--;
 
260
  }
 
261
  for(size_t written = 0; written < length; written += (size_t)ret){
176
262
    ret = TEMP_FAILURE_RETRY(write(STDOUT_FILENO, buffer + written,
177
263
                                   length - written));
178
264
    if(ret < 0){
182
268
  return true;
183
269
}
184
270
 
 
271
/* Removes and free a plugin from the plugin list */
 
272
static void free_plugin(plugin *plugin_node){
 
273
  
 
274
  for(char **arg = plugin_node->argv; *arg != NULL; arg++){
 
275
    free(*arg);
 
276
  }
 
277
  free(plugin_node->argv);
 
278
  for(char **env = plugin_node->environ; *env != NULL; env++){
 
279
    free(*env);
 
280
  }
 
281
  free(plugin_node->environ);
 
282
  free(plugin_node->buffer);
 
283
 
 
284
  /* Removes the plugin from the singly-linked list */
 
285
  if(plugin_node == plugin_list){
 
286
    /* First one - simple */
 
287
    plugin_list = plugin_list->next;
 
288
  } else {
 
289
    /* Second one or later */
 
290
    for(plugin *p = plugin_list; p != NULL; p = p->next){
 
291
      if(p->next == plugin_node){
 
292
        p->next = plugin_node->next;
 
293
        break;
 
294
      }
 
295
    }
 
296
  }
 
297
  
 
298
  free(plugin_node);
 
299
}
 
300
 
 
301
static void free_plugin_list(void){
 
302
  while(plugin_list != NULL){
 
303
    free_plugin(plugin_list);
 
304
  }
 
305
}
 
306
 
185
307
int main(int argc, char *argv[]){
186
 
  const char *plugindir = "/conf/conf.d/mandos/plugins.d";
 
308
  char *plugindir = NULL;
 
309
  char *argfile = NULL;
 
310
  FILE *conffp;
187
311
  size_t d_name_len;
188
312
  DIR *dir = NULL;
189
313
  struct dirent *dirst;
197
321
  struct sigaction old_sigchld_action;
198
322
  struct sigaction sigchld_action = { .sa_handler = handle_sigchld,
199
323
                                      .sa_flags = SA_NOCLDSTOP };
200
 
  char *plus_options = NULL;
201
 
  char **plus_argv = NULL;
 
324
  char **custom_argv = NULL;
 
325
  int custom_argc = 0;
202
326
  
203
327
  /* Establish a signal handler */
204
328
  sigemptyset(&sigchld_action.sa_mask);
205
329
  ret = sigaddset(&sigchld_action.sa_mask, SIGCHLD);
206
 
  if(ret < 0){
 
330
  if(ret == -1){
207
331
    perror("sigaddset");
208
 
    exit(EXIT_FAILURE);
 
332
    exitstatus = EXIT_FAILURE;
 
333
    goto fallback;
209
334
  }
210
335
  ret = sigaction(SIGCHLD, &sigchld_action, &old_sigchld_action);
211
 
  if(ret < 0){
 
336
  if(ret == -1){
212
337
    perror("sigaction");
213
 
    exit(EXIT_FAILURE);
 
338
    exitstatus = EXIT_FAILURE;
 
339
    goto fallback;
214
340
  }
215
341
  
216
342
  /* The options we understand. */
218
344
    { .name = "global-options", .key = 'g',
219
345
      .arg = "OPTION[,OPTION[,...]]",
220
346
      .doc = "Options passed to all plugins" },
 
347
    { .name = "global-env", .key = 'e',
 
348
      .arg = "VAR=value",
 
349
      .doc = "Environment variable passed to all plugins" },
221
350
    { .name = "options-for", .key = 'o',
222
351
      .arg = "PLUGIN:OPTION[,OPTION[,...]]",
223
352
      .doc = "Options passed only to specified plugin" },
 
353
    { .name = "env-for", .key = 'f',
 
354
      .arg = "PLUGIN:ENV=value",
 
355
      .doc = "Environment variable passed to specified plugin" },
224
356
    { .name = "disable", .key = 'd',
225
357
      .arg = "PLUGIN",
226
358
      .doc = "Disable a specific plugin", .group = 1 },
227
359
    { .name = "plugin-dir", .key = 128,
228
360
      .arg = "DIRECTORY",
229
361
      .doc = "Specify a different plugin directory", .group = 2 },
230
 
    { .name = "userid", .key = 129,
231
 
      .arg = "ID", .flags = 0,
232
 
      .doc = "User ID the plugins will run as", .group = 2 },
233
 
    { .name = "groupid", .key = 130,
234
 
      .arg = "ID", .flags = 0,
235
 
      .doc = "Group ID the plugins will run as", .group = 2 },
236
 
    { .name = "debug", .key = 131,
237
 
      .doc = "Debug mode", .group = 3 },
 
362
    { .name = "config-file", .key = 129,
 
363
      .arg = "FILE",
 
364
      .doc = "Specify a different configuration file", .group = 2 },
 
365
    { .name = "userid", .key = 130,
 
366
      .arg = "ID", .flags = 0,
 
367
      .doc = "User ID the plugins will run as", .group = 3 },
 
368
    { .name = "groupid", .key = 131,
 
369
      .arg = "ID", .flags = 0,
 
370
      .doc = "Group ID the plugins will run as", .group = 3 },
 
371
    { .name = "debug", .key = 132,
 
372
      .doc = "Debug mode", .group = 4 },
238
373
    { .name = NULL }
239
374
  };
240
375
  
241
 
  error_t parse_opt (int key, char *arg, struct argp_state *state) {
 
376
  error_t parse_opt (int key, char *arg, __attribute__((unused))
 
377
                     struct argp_state *state) {
242
378
    /* Get the INPUT argument from `argp_parse', which we know is a
243
379
       pointer to our plugin list pointer. */
244
 
    plugin **plugins = state->input;
245
380
    switch (key) {
246
 
    case 'g':
247
 
      if (arg != NULL){
248
 
        char *p = strtok(arg, ",");
249
 
        do{
250
 
          addargument(getplugin(NULL, plugins), p);
251
 
          p = strtok(NULL, ",");
252
 
        } while (p != NULL);
253
 
      }
254
 
      break;
255
 
    case 'o':
256
 
      if (arg != NULL){
257
 
        char *name = strtok(arg, ":");
258
 
        char *p = strtok(NULL, ":");
259
 
        if(p != NULL){
260
 
          p = strtok(p, ",");
261
 
          do{
262
 
            addargument(getplugin(name, plugins), p);
263
 
            p = strtok(NULL, ",");
264
 
          } while (p != NULL);
265
 
        }
266
 
      }
267
 
      break;
268
 
    case 'd':
269
 
      if (arg != NULL){
270
 
        getplugin(arg, plugins)->disabled = true;
271
 
      }
272
 
      break;
273
 
    case 128:
274
 
      plugindir = arg;
275
 
      break;
276
 
    case 129:
 
381
    case 'g':                   /* --global-options */
 
382
      if (arg != NULL){
 
383
        char *p;
 
384
        while((p = strsep(&arg, ",")) != NULL){
 
385
          if(p[0] == '\0'){
 
386
            continue;
 
387
          }
 
388
          if(not add_argument(getplugin(NULL), p)){
 
389
            perror("add_argument");
 
390
            return ARGP_ERR_UNKNOWN;
 
391
          }
 
392
        }
 
393
      }
 
394
      break;
 
395
    case 'e':                   /* --global-env */
 
396
      if(arg == NULL){
 
397
        break;
 
398
      }
 
399
      {
 
400
        char *envdef = strdup(arg);
 
401
        if(envdef == NULL){
 
402
          break;
 
403
        }
 
404
        if(not add_environment(getplugin(NULL), envdef, true)){
 
405
          perror("add_environment");
 
406
        }
 
407
      }
 
408
      break;
 
409
    case 'o':                   /* --options-for */
 
410
      if (arg != NULL){
 
411
        char *p_name = strsep(&arg, ":");
 
412
        if(p_name[0] == '\0'){
 
413
          break;
 
414
        }
 
415
        char *opt = strsep(&arg, ":");
 
416
        if(opt[0] == '\0'){
 
417
          break;
 
418
        }
 
419
        if(opt != NULL){
 
420
          char *p;
 
421
          while((p = strsep(&opt, ",")) != NULL){
 
422
            if(p[0] == '\0'){
 
423
              continue;
 
424
            }
 
425
            if(not add_argument(getplugin(p_name), p)){
 
426
              perror("add_argument");
 
427
              return ARGP_ERR_UNKNOWN;
 
428
            }
 
429
          }
 
430
        }
 
431
      }
 
432
      break;
 
433
    case 'f':                   /* --env-for */
 
434
      if(arg == NULL){
 
435
        break;
 
436
      }
 
437
      {
 
438
        char *envdef = strchr(arg, ':');
 
439
        if(envdef == NULL){
 
440
          break;
 
441
        }
 
442
        char *p_name = strndup(arg, (size_t) (envdef-arg));
 
443
        if(p_name == NULL){
 
444
          break;
 
445
        }
 
446
        envdef++;
 
447
        if(not add_environment(getplugin(p_name), envdef, true)){
 
448
          perror("add_environment");
 
449
        }
 
450
      }
 
451
      break;
 
452
    case 'd':                   /* --disable */
 
453
      if (arg != NULL){
 
454
        plugin *p = getplugin(arg);
 
455
        if(p == NULL){
 
456
          return ARGP_ERR_UNKNOWN;
 
457
        }
 
458
        p->disabled = true;
 
459
      }
 
460
      break;
 
461
    case 128:                   /* --plugin-dir */
 
462
      plugindir = strdup(arg);
 
463
      if(plugindir == NULL){
 
464
        perror("strdup");
 
465
      }      
 
466
      break;
 
467
    case 129:                   /* --config-file */
 
468
      argfile = strdup(arg);
 
469
      if(argfile == NULL){
 
470
        perror("strdup");
 
471
      }
 
472
      break;      
 
473
    case 130:                   /* --userid */
277
474
      uid = (uid_t)strtol(arg, NULL, 10);
278
475
      break;
279
 
    case 130:
 
476
    case 131:                   /* --groupid */
280
477
      gid = (gid_t)strtol(arg, NULL, 10);
281
478
      break;
282
 
    case 131:
 
479
    case 132:                   /* --debug */
283
480
      debug = true;
284
481
      break;
285
482
    case ARGP_KEY_ARG:
286
 
      if(plus_options != NULL or arg == NULL or arg[0] != '+'){
287
 
        argp_usage (state);
288
 
      }
289
 
      plus_options = arg;
 
483
      fprintf(stderr, "Ignoring unknown argument \"%s\"\n", arg);
290
484
      break;
291
485
    case ARGP_KEY_END:
292
486
      break;
296
490
    return 0;
297
491
  }
298
492
  
299
 
  plugin *plugin_list = NULL;
300
 
  
301
493
  struct argp argp = { .options = options, .parser = parse_opt,
302
 
                       .args_doc = "[+PLUS_SEPARATED_OPTIONS]",
 
494
                       .args_doc = "",
303
495
                       .doc = "Mandos plugin runner -- Run plugins" };
304
496
  
305
 
  ret = argp_parse (&argp, argc, argv, 0, 0, &plugin_list);
 
497
  /* Open the configfile if available */
 
498
  if (argfile == NULL){
 
499
    conffp = fopen(AFILE, "r");
 
500
  } else {
 
501
    conffp = fopen(argfile, "r");
 
502
  }  
 
503
  if(conffp != NULL){
 
504
    char *org_line = NULL;
 
505
    char *p, *arg, *new_arg, *line;
 
506
    size_t size = 0;
 
507
    ssize_t sret;
 
508
    const char whitespace_delims[] = " \r\t\f\v\n";
 
509
    const char comment_delim[] = "#";
 
510
 
 
511
    custom_argc = 1;
 
512
    custom_argv = malloc(sizeof(char*) * 2);
 
513
    if(custom_argv == NULL){
 
514
      perror("malloc");
 
515
      exitstatus = EXIT_FAILURE;
 
516
      goto fallback;
 
517
    }
 
518
    custom_argv[0] = argv[0];
 
519
    custom_argv[1] = NULL;
 
520
 
 
521
    /* for each line in the config file, strip whitespace and ignore
 
522
       commented text */
 
523
    while(true){
 
524
      sret = getline(&org_line, &size, conffp);
 
525
      if(sret == -1){
 
526
        break;
 
527
      }
 
528
 
 
529
      line = org_line;
 
530
      arg = strsep(&line, comment_delim);
 
531
      while((p = strsep(&arg, whitespace_delims)) != NULL){
 
532
        if(p[0] == '\0'){
 
533
          continue;
 
534
        }
 
535
        new_arg = strdup(p);
 
536
        if(new_arg == NULL){
 
537
          perror("strdup");
 
538
          exitstatus = EXIT_FAILURE;
 
539
          free(org_line);
 
540
          goto fallback;
 
541
        }
 
542
        
 
543
        custom_argc += 1;
 
544
        custom_argv = realloc(custom_argv, sizeof(char *)
 
545
                              * ((unsigned int) custom_argc + 1));
 
546
        if(custom_argv == NULL){
 
547
          perror("realloc");
 
548
          exitstatus = EXIT_FAILURE;
 
549
          free(org_line);
 
550
          goto fallback;
 
551
        }
 
552
        custom_argv[custom_argc-1] = new_arg;
 
553
        custom_argv[custom_argc] = NULL;        
 
554
      }
 
555
    }
 
556
    free(org_line);
 
557
  } else {
 
558
    /* Check for harmful errors and go to fallback. Other errors might
 
559
       not affect opening plugins */
 
560
    if (errno == EMFILE or errno == ENFILE or errno == ENOMEM){
 
561
      perror("fopen");
 
562
      exitstatus = EXIT_FAILURE;
 
563
      goto fallback;
 
564
    }
 
565
  }
 
566
  /* If there was any arguments from configuration file,
 
567
     pass them to parser as command arguments */
 
568
  if(custom_argv != NULL){
 
569
    ret = argp_parse (&argp, custom_argc, custom_argv, ARGP_IN_ORDER,
 
570
                      0, NULL);
 
571
    if (ret == ARGP_ERR_UNKNOWN){
 
572
      fprintf(stderr, "Unknown error while parsing arguments\n");
 
573
      exitstatus = EXIT_FAILURE;
 
574
      goto fallback;
 
575
    }
 
576
  }
 
577
  
 
578
  /* Parse actual command line arguments, to let them override the
 
579
     config file */
 
580
  ret = argp_parse (&argp, argc, argv, ARGP_IN_ORDER, 0, NULL);
306
581
  if (ret == ARGP_ERR_UNKNOWN){
307
 
    fprintf(stderr, "Unkown error while parsing arguments\n");
 
582
    fprintf(stderr, "Unknown error while parsing arguments\n");
308
583
    exitstatus = EXIT_FAILURE;
309
 
    goto end;
310
 
  }
311
 
  
312
 
  if(plus_options){
313
 
    /* This is a mangled argument in the form of
314
 
     "+--option+--other-option=parameter+--yet-another-option", etc */
315
 
    /* Make new argc and argv vars, and call argp_parse() again. */
316
 
    plus_options++;             /* skip the first '+' character */
317
 
    const char delims[] = "+";
318
 
    char *arg;
319
 
    int new_argc = 1;
320
 
    plus_argv = malloc(sizeof(char*) * 2);
321
 
    if(plus_argv == NULL){
322
 
      perror("malloc");
323
 
      exitstatus = EXIT_FAILURE;
324
 
      goto end;
325
 
    }
326
 
    plus_argv[0] = argv[0];
327
 
    plus_argv[1] = NULL;
328
 
    arg = strtok(plus_options, delims); /* Get first argument */
329
 
    while(arg != NULL){
330
 
      new_argc++;
331
 
      plus_argv = realloc(plus_argv, sizeof(char *)
332
 
                         * ((unsigned int) new_argc + 1));
333
 
      if(plus_argv == NULL){
334
 
        perror("realloc");
335
 
        exitstatus = EXIT_FAILURE;
336
 
        goto end;
337
 
      }
338
 
      plus_argv[new_argc-1] = arg;
339
 
      plus_argv[new_argc] = NULL;
340
 
      arg = strtok(NULL, delims); /* Get next argument */
341
 
    }
342
 
    ret = argp_parse (&argp, new_argc, plus_argv, 0, 0, &plugin_list);
343
 
    if (ret == ARGP_ERR_UNKNOWN){
344
 
      fprintf(stderr, "Unkown error while parsing arguments\n");
345
 
      exitstatus = EXIT_FAILURE;
346
 
      goto end;
347
 
    }
 
584
    goto fallback;
348
585
  }
349
586
  
350
587
  if(debug){
354
591
      for(char **a = p->argv; *a != NULL; a++){
355
592
        fprintf(stderr, "\tArg: %s\n", *a);
356
593
      }
 
594
      fprintf(stderr, "...and %u environment variables\n", p->envc);
 
595
      for(char **a = p->environ; *a != NULL; a++){
 
596
        fprintf(stderr, "\t%s\n", *a);
 
597
      }
357
598
    }
358
599
  }
359
600
  
 
601
  /* Strip permissions down to nobody */
360
602
  ret = setuid(uid);
361
603
  if (ret == -1){
362
604
    perror("setuid");
363
 
  }
364
 
  
 
605
  }  
365
606
  setgid(gid);
366
607
  if (ret == -1){
367
608
    perror("setgid");
368
609
  }
369
610
  
370
 
  dir = opendir(plugindir);
 
611
  if (plugindir == NULL){
 
612
    dir = opendir(PDIR);
 
613
  } else {
 
614
    dir = opendir(plugindir);
 
615
  }
 
616
  
371
617
  if(dir == NULL){
372
618
    perror("Could not open plugin dir");
373
619
    exitstatus = EXIT_FAILURE;
374
 
    goto end;
 
620
    goto fallback;
375
621
  }
376
622
  
377
623
  /* Set the FD_CLOEXEC flag on the directory, if possible */
382
628
      if(ret < 0){
383
629
        perror("set_cloexec_flag");
384
630
        exitstatus = EXIT_FAILURE;
385
 
        goto end;
 
631
        goto fallback;
386
632
      }
387
633
    }
388
634
  }
389
635
  
390
636
  FD_ZERO(&rfds_all);
391
637
  
 
638
  /* Read and execute any executable in the plugin directory*/
392
639
  while(true){
393
640
    dirst = readdir(dir);
394
641
    
395
 
    // All directory entries have been processed
 
642
    /* All directory entries have been processed */
396
643
    if(dirst == NULL){
397
644
      if (errno == EBADF){
398
645
        perror("readdir");
399
646
        exitstatus = EXIT_FAILURE;
400
 
        goto end;
 
647
        goto fallback;
401
648
      }
402
649
      break;
403
650
    }
404
651
    
405
652
    d_name_len = strlen(dirst->d_name);
406
653
    
407
 
    // Ignore dotfiles, backup files and other junk
 
654
    /* Ignore dotfiles, backup files and other junk */
408
655
    {
409
656
      bool bad_name = false;
410
657
      
425
672
          break;
426
673
        }
427
674
      }
428
 
      
429
675
      if(bad_name){
430
676
        continue;
431
677
      }
432
 
      
433
678
      for(const char **suf = bad_suffixes; *suf != NULL; suf++){
434
679
        size_t suf_len = strlen(*suf);
435
680
        if((d_name_len >= suf_len)
448
693
        continue;
449
694
      }
450
695
    }
451
 
    
452
 
    char *filename = malloc(d_name_len + strlen(plugindir) + 2);
453
 
    if (filename == NULL){
454
 
      perror("malloc");
455
 
      exitstatus = EXIT_FAILURE;
456
 
      goto end;
 
696
 
 
697
    char *filename;
 
698
    ret = asprintf(&filename, "%s/%s", plugindir, dirst->d_name);
 
699
    if(ret < 0){
 
700
      perror("asprintf");
 
701
      continue;
457
702
    }
458
 
    strcpy(filename, plugindir); /* Spurious warning */
459
 
    strcat(filename, "/");      /* Spurious warning */
460
 
    strcat(filename, dirst->d_name); /* Spurious warning */
461
703
    
462
704
    ret = stat(filename, &st);
463
705
    if (ret == -1){
464
706
      perror("stat");
465
 
      exitstatus = EXIT_FAILURE;
466
 
      goto end;
 
707
      free(filename);
 
708
      continue;
467
709
    }
468
 
    
 
710
 
 
711
    /* Ignore non-executable files */
469
712
    if (not S_ISREG(st.st_mode) or (access(filename, X_OK) != 0)){
470
713
      if(debug){
471
714
        fprintf(stderr, "Ignoring plugin dir entry \"%s\""
474
717
      free(filename);
475
718
      continue;
476
719
    }
477
 
    if(getplugin(dirst->d_name, &plugin_list)->disabled){
 
720
    
 
721
    plugin *p = getplugin(dirst->d_name);
 
722
    if(p == NULL){
 
723
      perror("getplugin");
 
724
      free(filename);
 
725
      continue;
 
726
    }
 
727
    if(p->disabled){
478
728
      if(debug){
479
729
        fprintf(stderr, "Ignoring disabled plugin \"%s\"\n",
480
730
                dirst->d_name);
482
732
      free(filename);
483
733
      continue;
484
734
    }
485
 
    plugin *p = getplugin(dirst->d_name, &plugin_list);
486
735
    {
487
736
      /* Add global arguments to argument list for this plugin */
488
 
      plugin *g = getplugin(NULL, &plugin_list);
489
 
      for(char **a = g->argv + 1; *a != NULL; a++){
490
 
        addargument(p, *a);
491
 
      }
492
 
    }
493
 
    int pipefd[2]; 
 
737
      plugin *g = getplugin(NULL);
 
738
      if(g != NULL){
 
739
        for(char **a = g->argv + 1; *a != NULL; a++){
 
740
          if(not add_argument(p, *a)){
 
741
            perror("add_argument");
 
742
          }
 
743
        }
 
744
        /* Add global environment variables */
 
745
        for(char **e = g->environ; *e != NULL; e++){
 
746
          if(not add_environment(p, *e, false)){
 
747
            perror("add_environment");
 
748
          }
 
749
        }
 
750
      }
 
751
    }
 
752
    /* If this plugin has any environment variables, we will call
 
753
       using execve and need to duplicate the environment from this
 
754
       process, too. */
 
755
    if(p->environ[0] != NULL){
 
756
      for(char **e = environ; *e != NULL; e++){
 
757
        if(not add_environment(p, *e, false)){
 
758
          perror("add_environment");
 
759
        }
 
760
      }
 
761
    }
 
762
    
 
763
    int pipefd[2];
494
764
    ret = pipe(pipefd);
495
765
    if (ret == -1){
496
766
      perror("pipe");
497
767
      exitstatus = EXIT_FAILURE;
498
 
      goto end;
 
768
      goto fallback;
499
769
    }
 
770
    /* Ask OS to automatic close the pipe on exec */
500
771
    ret = set_cloexec_flag(pipefd[0]);
501
772
    if(ret < 0){
502
773
      perror("set_cloexec_flag");
503
774
      exitstatus = EXIT_FAILURE;
504
 
      goto end;
 
775
      goto fallback;
505
776
    }
506
777
    ret = set_cloexec_flag(pipefd[1]);
507
778
    if(ret < 0){
508
779
      perror("set_cloexec_flag");
509
780
      exitstatus = EXIT_FAILURE;
510
 
      goto end;
 
781
      goto fallback;
511
782
    }
512
783
    /* Block SIGCHLD until process is safely in process list */
513
784
    ret = sigprocmask (SIG_BLOCK, &sigchld_action.sa_mask, NULL);
514
785
    if(ret < 0){
515
786
      perror("sigprocmask");
516
787
      exitstatus = EXIT_FAILURE;
517
 
      goto end;
 
788
      goto fallback;
518
789
    }
519
 
    // Starting a new process to be watched
 
790
    /* Starting a new process to be watched */
520
791
    pid_t pid = fork();
 
792
    if(pid == -1){
 
793
      perror("fork");
 
794
      exitstatus = EXIT_FAILURE;
 
795
      goto fallback;
 
796
    }
521
797
    if(pid == 0){
522
798
      /* this is the child process */
523
799
      ret = sigaction(SIGCHLD, &old_sigchld_action, NULL);
542
818
           above and must now close it manually here. */
543
819
        closedir(dir);
544
820
      }
545
 
      if(execv(filename, p->argv) < 0){
546
 
        perror("execv");
547
 
        _exit(EXIT_FAILURE);
 
821
      if(p->environ[0] == NULL){
 
822
        if(execv(filename, p->argv) < 0){
 
823
          perror("execv");
 
824
          _exit(EXIT_FAILURE);
 
825
        }
 
826
      } else {
 
827
        if(execve(filename, p->argv, p->environ) < 0){
 
828
          perror("execve");
 
829
          _exit(EXIT_FAILURE);
 
830
        }
548
831
      }
549
832
      /* no return */
550
833
    }
551
 
    /* parent process */
 
834
    /* Parent process */
 
835
    close(pipefd[1]);           /* Close unused write end of pipe */
552
836
    free(filename);
553
 
    close(pipefd[1]);           /* close unused write end of pipe */
554
 
    process *new_process = malloc(sizeof(process));
555
 
    if (new_process == NULL){
556
 
      perror("malloc");
 
837
    plugin *new_plugin = getplugin(dirst->d_name);
 
838
    if (new_plugin == NULL){
 
839
      perror("getplugin");
557
840
      ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
558
841
      if(ret < 0){
559
 
        perror("sigprocmask");
 
842
        perror("sigprocmask");
560
843
      }
561
844
      exitstatus = EXIT_FAILURE;
562
 
      goto end;
 
845
      goto fallback;
563
846
    }
564
847
    
565
 
    *new_process = (struct process){ .pid = pid,
566
 
                                     .fd = pipefd[0],
567
 
                                     .next = process_list };
568
 
    // List handling
569
 
    process_list = new_process;
 
848
    new_plugin->pid = pid;
 
849
    new_plugin->fd = pipefd[0];
 
850
    
570
851
    /* Unblock SIGCHLD so signal handler can be run if this process
571
852
       has already completed */
572
853
    ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
573
854
    if(ret < 0){
574
855
      perror("sigprocmask");
575
856
      exitstatus = EXIT_FAILURE;
576
 
      goto end;
577
 
    }
578
 
    
579
 
    FD_SET(new_process->fd, &rfds_all);
580
 
    
581
 
    if (maxfd < new_process->fd){
582
 
      maxfd = new_process->fd;
583
 
    }
584
 
    
585
 
  }
586
 
  
587
 
  /* Free the plugin list */
588
 
  for(plugin *next; plugin_list != NULL; plugin_list = next){
589
 
    next = plugin_list->next;
590
 
    free(plugin_list->argv);
591
 
    free(plugin_list);
 
857
      goto fallback;
 
858
    }
 
859
    
 
860
    FD_SET(new_plugin->fd, &rfds_all);
 
861
    
 
862
    if (maxfd < new_plugin->fd){
 
863
      maxfd = new_plugin->fd;
 
864
    }
 
865
    
592
866
  }
593
867
  
594
868
  closedir(dir);
595
869
  dir = NULL;
596
 
    
597
 
  if (process_list == NULL){
598
 
    fprintf(stderr, "No plugin processes started. Incorrect plugin"
599
 
            " directory?\n");
600
 
    process_list = NULL;
 
870
 
 
871
  for(plugin *p = plugin_list; p != NULL; p = p->next){
 
872
    if(p->pid != 0){
 
873
      break;
 
874
    }
 
875
    if(p->next == NULL){
 
876
      fprintf(stderr, "No plugin processes started. Incorrect plugin"
 
877
              " directory?\n");
 
878
      free_plugin_list();
 
879
    }
601
880
  }
602
 
  while(process_list){
 
881
 
 
882
  /* Main loop while running plugins exist */
 
883
  while(plugin_list){
603
884
    fd_set rfds = rfds_all;
604
885
    int select_ret = select(maxfd+1, &rfds, NULL, NULL, NULL);
605
886
    if (select_ret == -1){
606
887
      perror("select");
607
888
      exitstatus = EXIT_FAILURE;
608
 
      goto end;
 
889
      goto fallback;
609
890
    }
610
891
    /* OK, now either a process completed, or something can be read
611
892
       from one of them */
612
 
    for(process *proc = process_list; proc ; proc = proc->next){
 
893
    for(plugin *proc = plugin_list; proc != NULL; proc = proc->next){
613
894
      /* Is this process completely done? */
614
895
      if(proc->eof and proc->completed){
615
896
        /* Only accept the plugin output if it exited cleanly */
616
897
        if(not WIFEXITED(proc->status)
617
898
           or WEXITSTATUS(proc->status) != 0){
618
899
          /* Bad exit by plugin */
 
900
 
619
901
          if(debug){
620
902
            if(WIFEXITED(proc->status)){
621
903
              fprintf(stderr, "Plugin %u exited with status %d\n",
630
912
                      (unsigned int) (proc->pid));
631
913
            }
632
914
          }
 
915
          
633
916
          /* Remove the plugin */
634
917
          FD_CLR(proc->fd, &rfds_all);
 
918
 
635
919
          /* Block signal while modifying process_list */
636
 
          ret = sigprocmask (SIG_BLOCK, &sigchld_action.sa_mask, NULL);
 
920
          ret = sigprocmask(SIG_BLOCK, &sigchld_action.sa_mask, NULL);
637
921
          if(ret < 0){
638
922
            perror("sigprocmask");
639
923
            exitstatus = EXIT_FAILURE;
640
 
            goto end;
641
 
          }
642
 
          /* Delete this process entry from the list */
643
 
          if(process_list == proc){
644
 
            /* First one - simple */
645
 
            process_list = proc->next;
646
 
          } else {
647
 
            /* Second one or later */
648
 
            for(process *p = process_list; p != NULL; p = p->next){
649
 
              if(p->next == proc){
650
 
                p->next = proc->next;
651
 
                break;
652
 
              }
653
 
            }
654
 
          }
 
924
            goto fallback;
 
925
          }
 
926
          free_plugin(proc);
655
927
          /* We are done modifying process list, so unblock signal */
656
928
          ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask,
657
929
                             NULL);
658
930
          if(ret < 0){
659
931
            perror("sigprocmask");
660
 
          }
661
 
          free(proc->buffer);
662
 
          free(proc);
663
 
          /* We deleted this process from the list, so we can't go
664
 
             proc->next.  Therefore, start over from the beginning of
665
 
             the process list */
666
 
          break;
 
932
            exitstatus = EXIT_FAILURE;
 
933
            goto fallback;
 
934
          }
 
935
          
 
936
          if(plugin_list == NULL){
 
937
            break;
 
938
          }
 
939
          continue;
667
940
        }
 
941
        
668
942
        /* This process exited nicely, so print its buffer */
669
943
 
670
 
        bool bret = print_out_password(proc->buffer, proc->buffer_length);
 
944
        bool bret = print_out_password(proc->buffer,
 
945
                                       proc->buffer_length);
671
946
        if(not bret){
672
947
          perror("print_out_password");
673
948
          exitstatus = EXIT_FAILURE;
674
949
        }
675
 
        goto end;
 
950
        goto fallback;
676
951
      }
 
952
      
677
953
      /* This process has not completed.  Does it have any output? */
678
954
      if(proc->eof or not FD_ISSET(proc->fd, &rfds)){
679
955
        /* This process had nothing to say at this time */
686
962
        if (proc->buffer == NULL){
687
963
          perror("malloc");
688
964
          exitstatus = EXIT_FAILURE;
689
 
          goto end;
 
965
          goto fallback;
690
966
        }
691
967
        proc->buffer_size += BUFFER_SIZE;
692
968
      }
705
981
      }
706
982
    }
707
983
  }
 
984
 
 
985
 
 
986
 fallback:
708
987
  
709
 
  if(process_list == NULL){
 
988
  if(plugin_list == NULL or exitstatus != EXIT_SUCCESS){
 
989
    /* Fallback if all plugins failed, none are found or an error
 
990
       occured */
710
991
    bool bret;
711
992
    fprintf(stderr, "Going to fallback mode using getpass(3)\n");
712
993
    char *passwordbuffer = getpass("Password: ");
714
995
    if(not bret){
715
996
      perror("print_out_password");
716
997
      exitstatus = EXIT_FAILURE;
717
 
      goto end;
718
 
    }
719
 
    bret = print_out_password("\n", 1);
720
 
    if(not bret){
721
 
      perror("print_out_password");
722
 
      exitstatus = EXIT_FAILURE;
723
998
    }
724
999
  }
725
 
 
726
 
 end:
727
1000
  
728
1001
  /* Restore old signal handler */
729
 
  sigaction(SIGCHLD, &old_sigchld_action, NULL);
730
 
  
731
 
  free(plus_argv);
732
 
  
733
 
  /* Free the plugin list */
734
 
  for(plugin *next; plugin_list != NULL; plugin_list = next){
735
 
    next = plugin_list->next;
736
 
    free(plugin_list->argv);
737
 
    free(plugin_list);
 
1002
  ret = sigaction(SIGCHLD, &old_sigchld_action, NULL);
 
1003
  if(ret == -1){
 
1004
    perror("sigaction");
 
1005
    exitstatus = EXIT_FAILURE;
 
1006
  }
 
1007
 
 
1008
  if(custom_argv != NULL){
 
1009
    for(char **arg = custom_argv+1; *arg != NULL; arg++){
 
1010
      free(*arg);
 
1011
    }
 
1012
    free(custom_argv);
738
1013
  }
739
1014
  
740
1015
  if(dir != NULL){
742
1017
  }
743
1018
  
744
1019
  /* Free the process list and kill the processes */
745
 
  for(process *next; process_list != NULL; process_list = next){
746
 
    next = process_list->next;
747
 
    close(process_list->fd);
748
 
    ret = kill(process_list->pid, SIGTERM);
749
 
    if(ret == -1 and errno != ESRCH){
750
 
      /* set-uid proccesses migth not get closed */
751
 
      perror("kill");
 
1020
  for(plugin *p = plugin_list; p != NULL; p = p->next){
 
1021
    if(p->pid != 0){
 
1022
      close(p->fd);
 
1023
      ret = kill(p->pid, SIGTERM);
 
1024
      if(ret == -1 and errno != ESRCH){
 
1025
        /* Set-uid proccesses might not get closed */
 
1026
        perror("kill");
 
1027
      }
752
1028
    }
753
 
    free(process_list->buffer);
754
 
    free(process_list);
755
1029
  }
756
1030
  
757
1031
  /* Wait for any remaining child processes to terminate */
761
1035
  if(errno != ECHILD){
762
1036
    perror("wait");
763
1037
  }
 
1038
 
 
1039
  free_plugin_list();
 
1040
  
 
1041
  free(plugindir);
 
1042
  free(argfile);
764
1043
  
765
1044
  return exitstatus;
766
1045
}