/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-21 04:22:50 UTC
  • Revision ID: teddy@fukt.bsnet.se-20080921042250-r0qqjsbz2ulfo5le
* Makefile: Bug fix: fix syntax error.

* debian/control: Depend on "po-debconf".
  (mandos, mandos-client): Add "${misc:Depends}", used by
                           dh_installdebconf.

* debian/mandos-client.config: New; show note.
* debian/mandos-client.template: New.

* debian/mandos.README.Debian: New.

* debian/mandos.config: New; show note.
* debian/mandos.prerm: New; stop daemon.
* debian/mandos.template: New.

* debian/po/POTFILES.in: New.
* debian/po/sv.po: New.

* debian/rules (clean): Added "debconf-updatepo" as suggested by
                        po-debconf(7).
  (binary-common): Added "dh_installdebconf" to use "debian/*.config"
                   and "debian/*.template" files.

Show diffs side-by-side

added added

removed removed

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