/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-08-18 05:57:11 UTC
  • Revision ID: teddy@fukt.bsnet.se-20080818055711-2rpzat3hkbq3us62
No code or documentation changes.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
/*  -*- coding: utf-8; mode: c; mode: orgtbl -*- */
 
1
/*  -*- coding: utf-8 -*- */
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
23
22
 */
24
23
 
25
24
#define _GNU_SOURCE             /* TEMP_FAILURE_RETRY(), getline(),
26
 
                                   asprintf(), O_CLOEXEC */
 
25
                                   asprintf() */
27
26
#include <stddef.h>             /* size_t, NULL */
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 */
33
 
#include <sys/types.h>          /* DIR, fdopendir(), stat(), struct
 
30
#include <stdio.h>              /* perror, popen(), fileno(),
 
31
                                   fprintf(), stderr, STDOUT_FILENO */
 
32
#include <sys/types.h>          /* DIR, opendir(), stat(), struct
34
33
                                   stat, waitpid(), WIFEXITED(),
35
34
                                   WEXITSTATUS(), wait(), pid_t,
36
35
                                   uid_t, gid_t, getuid(), getgid(),
38
37
#include <sys/select.h>         /* fd_set, select(), FD_ZERO(),
39
38
                                   FD_SET(), FD_ISSET(), FD_CLR */
40
39
#include <sys/wait.h>           /* wait(), waitpid(), WIFEXITED(),
41
 
                                   WEXITSTATUS(), WTERMSIG(),
42
 
                                   WCOREDUMP() */
 
40
                                   WEXITSTATUS() */
43
41
#include <sys/stat.h>           /* struct stat, stat(), S_ISREG() */
44
42
#include <iso646.h>             /* and, or, not */
45
 
#include <dirent.h>             /* DIR, struct dirent, fdopendir(),
 
43
#include <dirent.h>             /* DIR, struct dirent, opendir(),
46
44
                                   readdir(), closedir(), dirfd() */
47
45
#include <unistd.h>             /* struct stat, stat(), S_ISREG(),
48
46
                                   fcntl(), setuid(), setgid(),
49
47
                                   F_GETFD, F_SETFD, FD_CLOEXEC,
50
48
                                   access(), pipe(), fork(), close()
51
 
                                   dup2(), STDOUT_FILENO, _exit(),
 
49
                                   dup2, STDOUT_FILENO, _exit(),
52
50
                                   execv(), write(), read(),
53
51
                                   close() */
54
52
#include <fcntl.h>              /* fcntl(), F_GETFD, F_SETFD,
55
53
                                   FD_CLOEXEC */
56
 
#include <string.h>             /* strsep, strlen(), asprintf(),
57
 
                                   strsignal() */
 
54
#include <string.h>             /* strsep, strlen(), asprintf() */
58
55
#include <errno.h>              /* errno */
59
56
#include <argp.h>               /* struct argp_option, struct
60
57
                                   argp_state, struct argp,
61
58
                                   argp_parse(), ARGP_ERR_UNKNOWN,
62
 
                                   ARGP_KEY_END, ARGP_KEY_ARG,
63
 
                                   error_t */
 
59
                                   ARGP_KEY_END, ARGP_KEY_ARG, error_t */
64
60
#include <signal.h>             /* struct sigaction, sigemptyset(),
65
61
                                   sigaddset(), sigaction(),
66
62
                                   sigprocmask(), SIG_BLOCK, SIGCHLD,
67
 
                                   SIG_UNBLOCK, kill(), sig_atomic_t
68
 
                                */
 
63
                                   SIG_UNBLOCK, kill() */
69
64
#include <errno.h>              /* errno, EBADF */
70
 
#include <inttypes.h>           /* intmax_t, PRIdMAX, strtoimax() */
71
 
#include <sysexits.h>           /* EX_OSERR, EX_USAGE */
72
65
 
73
66
#define BUFFER_SIZE 256
74
 
 
75
 
#define PDIR "/lib/mandos/plugins.d"
76
 
#define AFILE "/conf/conf.d/mandos/plugin-runner.conf"
77
 
 
78
 
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";
79
70
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
80
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
 
81
86
typedef struct plugin{
82
87
  char *name;                   /* can be NULL or any plugin name */
83
88
  char **argv;
85
90
  char **environ;
86
91
  int envc;
87
92
  bool disabled;
88
 
  
89
 
  /* Variables used for running processes*/
90
 
  pid_t pid;
91
 
  int fd;
92
 
  char *buffer;
93
 
  size_t buffer_size;
94
 
  size_t buffer_length;
95
 
  bool eof;
96
 
  volatile sig_atomic_t completed;
97
 
  int status;
98
93
  struct plugin *next;
99
94
} plugin;
100
95
 
101
 
static plugin *plugin_list = NULL;
102
 
 
103
 
/* Gets an existing plugin based on name,
104
 
   or if none is found, creates a new one */
105
 
static plugin *getplugin(char *name){
106
 
  /* Check for existing plugin with that name */
107
 
  for(plugin *p = plugin_list; p != NULL; p = p->next){
108
 
    if((p->name == name)
109
 
       or (p->name and name and (strcmp(p->name, name) == 0))){
 
96
static plugin *getplugin(char *name, plugin **plugin_list){
 
97
  for (plugin *p = *plugin_list; p != NULL; p = p->next){
 
98
    if ((p->name == name)
 
99
        or (p->name and name and (strcmp(p->name, name) == 0))){
110
100
      return p;
111
101
    }
112
102
  }
113
103
  /* Create a new plugin */
114
 
  plugin *new_plugin = NULL;
115
 
  do {
116
 
    new_plugin = malloc(sizeof(plugin));
117
 
  } while(new_plugin == NULL and errno == EINTR);
118
 
  if(new_plugin == NULL){
119
 
    return NULL;
120
 
  }
121
 
  char *copy_name = NULL;
122
 
  if(name != NULL){
123
 
    do {
124
 
      copy_name = strdup(name);
125
 
    } while(copy_name == NULL and errno == EINTR);
126
 
    if(copy_name == NULL){
127
 
      int e = errno;
128
 
      free(new_plugin);
129
 
      errno = e;
130
 
      return NULL;
131
 
    }
132
 
  }
133
 
  
134
 
  *new_plugin = (plugin){ .name = copy_name,
135
 
                          .argc = 1,
136
 
                          .disabled = false,
137
 
                          .next = plugin_list };
138
 
  
139
 
  do {
140
 
    new_plugin->argv = malloc(sizeof(char *) * 2);
141
 
  } while(new_plugin->argv == NULL and errno == EINTR);
142
 
  if(new_plugin->argv == NULL){
143
 
    int e = errno;
144
 
    free(copy_name);
 
104
  plugin *new_plugin = malloc(sizeof(plugin));
 
105
  if (new_plugin == NULL){
 
106
    return NULL;
 
107
  }
 
108
  char *copy_name = strdup(name);
 
109
  if(copy_name == NULL){
 
110
    return NULL;
 
111
  }
 
112
  
 
113
  *new_plugin = (plugin) { .name = copy_name,
 
114
                           .argc = 1,
 
115
                           .envc = 0,
 
116
                           .disabled = false,
 
117
                           .next = *plugin_list };
 
118
  
 
119
  new_plugin->argv = malloc(sizeof(char *) * 2);
 
120
  if (new_plugin->argv == NULL){
145
121
    free(new_plugin);
146
 
    errno = e;
147
122
    return NULL;
148
123
  }
149
124
  new_plugin->argv[0] = copy_name;
150
125
  new_plugin->argv[1] = NULL;
151
 
  
152
 
  do {
153
 
    new_plugin->environ = malloc(sizeof(char *));
154
 
  } while(new_plugin->environ == NULL and errno == EINTR);
 
126
 
 
127
  new_plugin->environ = malloc(sizeof(char *));
155
128
  if(new_plugin->environ == NULL){
156
 
    int e = errno;
157
 
    free(copy_name);
158
129
    free(new_plugin->argv);
159
130
    free(new_plugin);
160
 
    errno = e;
161
131
    return NULL;
162
132
  }
163
133
  new_plugin->environ[0] = NULL;
164
 
  
165
134
  /* Append the new plugin to the list */
166
 
  plugin_list = new_plugin;
 
135
  *plugin_list = new_plugin;
167
136
  return new_plugin;
168
137
}
169
138
 
171
140
static bool add_to_char_array(const char *new, char ***array,
172
141
                              int *len){
173
142
  /* Resize the pointed-to array to hold one more pointer */
174
 
  do {
175
 
    *array = realloc(*array, sizeof(char *)
176
 
                     * (size_t) ((*len) + 2));
177
 
  } while(*array == NULL and errno == EINTR);
 
143
  *array = realloc(*array, sizeof(char *)
 
144
                   * (size_t) ((*len) + 2));
178
145
  /* Malloc check */
179
146
  if(*array == NULL){
180
147
    return false;
181
148
  }
182
149
  /* Make a copy of the new string */
183
 
  char *copy;
184
 
  do {
185
 
    copy = strdup(new);
186
 
  } while(copy == NULL and errno == EINTR);
 
150
  char *copy = strdup(new);
187
151
  if(copy == NULL){
188
152
    return false;
189
153
  }
204
168
}
205
169
 
206
170
/* Add to a plugin's environment */
207
 
static bool add_environment(plugin *p, const char *def, bool replace){
 
171
static bool add_environment(plugin *p, const char *def){
208
172
  if(p == NULL){
209
173
    return false;
210
174
  }
211
 
  /* namelen = length of name of environment variable */
212
 
  size_t namelen = (size_t)(strchrnul(def, '=') - def);
213
 
  /* Search for this environment variable */
214
 
  for(char **e = p->environ; *e != NULL; e++){
215
 
    if(strncmp(*e, def, namelen + 1) == 0){
216
 
      /* It already exists */
217
 
      if(replace){
218
 
        char *new;
219
 
        do {
220
 
          new = realloc(*e, strlen(def) + 1);
221
 
        } while(new == NULL and errno == EINTR);
222
 
        if(new == NULL){
223
 
          return false;
224
 
        }
225
 
        *e = new;
226
 
        strcpy(*e, def);
227
 
      }
228
 
      return true;
229
 
    }
230
 
  }
231
175
  return add_to_char_array(def, &(p->environ), &(p->envc));
232
176
}
233
177
 
 
178
 
234
179
/*
235
180
 * Based on the example in the GNU LibC manual chapter 13.13 "File
236
181
 * Descriptor Flags".
237
 
 | [[info:libc:Descriptor%20Flags][File Descriptor Flags]] |
 
182
 * *Note File Descriptor Flags:(libc)Descriptor Flags.
238
183
 */
239
 
static int set_cloexec_flag(int fd){
240
 
  int ret = (int)TEMP_FAILURE_RETRY(fcntl(fd, F_GETFD, 0));
 
184
static int set_cloexec_flag(int fd)
 
185
{
 
186
  int ret = fcntl(fd, F_GETFD, 0);
241
187
  /* If reading the flags failed, return error indication now. */
242
188
  if(ret < 0){
243
189
    return ret;
244
190
  }
245
191
  /* Store modified flag word in the descriptor. */
246
 
  return (int)TEMP_FAILURE_RETRY(fcntl(fd, F_SETFD,
247
 
                                       ret | FD_CLOEXEC));
 
192
  return fcntl(fd, F_SETFD, ret | FD_CLOEXEC);
248
193
}
249
194
 
 
195
process *process_list = NULL;
250
196
 
251
 
/* Mark processes as completed when they exit, and save their exit
 
197
/* Mark a process as completed when it exits, and save its exit
252
198
   status. */
253
 
static void handle_sigchld(__attribute__((unused)) int sig){
254
 
  int old_errno = errno;
255
 
  while(true){
256
 
    plugin *proc = plugin_list;
257
 
    int status;
258
 
    pid_t pid = waitpid(-1, &status, WNOHANG);
259
 
    if(pid == 0){
260
 
      /* Only still running child processes */
261
 
      break;
262
 
    }
263
 
    if(pid == -1){
264
 
      if(errno == ECHILD){
265
 
        /* No child processes */
266
 
        break;
267
 
      }
268
 
      perror("waitpid");
269
 
    }
270
 
    
271
 
    /* A child exited, find it in process_list */
272
 
    while(proc != NULL and proc->pid != pid){
273
 
      proc = proc->next;
274
 
    }
275
 
    if(proc == NULL){
276
 
      /* Process not found in process list */
277
 
      continue;
278
 
    }
279
 
    proc->status = status;
280
 
    proc->completed = 1;
281
 
  }
282
 
  errno = old_errno;
 
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;
283
216
}
284
217
 
285
 
/* Prints out a password to stdout */
286
 
static bool print_out_password(const char *buffer, size_t length){
 
218
bool print_out_password(const char *buffer, size_t length){
287
219
  ssize_t ret;
 
220
  if(length>0 and buffer[length-1] == '\n'){
 
221
    length--;
 
222
  }
288
223
  for(size_t written = 0; written < length; written += (size_t)ret){
289
224
    ret = TEMP_FAILURE_RETRY(write(STDOUT_FILENO, buffer + written,
290
225
                                   length - written));
295
230
  return true;
296
231
}
297
232
 
298
 
/* Removes and free a plugin from the plugin list */
299
 
static void free_plugin(plugin *plugin_node){
300
 
  
301
 
  for(char **arg = plugin_node->argv; *arg != NULL; arg++){
302
 
    free(*arg);
303
 
  }
304
 
  free(plugin_node->argv);
305
 
  for(char **env = plugin_node->environ; *env != NULL; env++){
306
 
    free(*env);
307
 
  }
308
 
  free(plugin_node->environ);
309
 
  free(plugin_node->buffer);
310
 
  
311
 
  /* Removes the plugin from the singly-linked list */
312
 
  if(plugin_node == plugin_list){
313
 
    /* First one - simple */
314
 
    plugin_list = plugin_list->next;
315
 
  } else {
316
 
    /* Second one or later */
317
 
    for(plugin *p = plugin_list; p != NULL; p = p->next){
318
 
      if(p->next == plugin_node){
319
 
        p->next = plugin_node->next;
320
 
        break;
321
 
      }
 
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;
322
239
    }
323
 
  }
324
 
  
325
 
  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;
326
252
}
327
253
 
328
 
static void free_plugin_list(void){
329
 
  while(plugin_list != NULL){
330
 
    free_plugin(plugin_list);
331
 
  }
 
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
  }  
332
268
}
333
269
 
334
270
int main(int argc, char *argv[]){
335
 
  char *plugindir = NULL;
336
 
  char *argfile = NULL;
 
271
  const char *plugindir = "/lib/mandos/plugins.d";
 
272
  const char *argfile = ARGFILE;
337
273
  FILE *conffp;
338
274
  size_t d_name_len;
339
275
  DIR *dir = NULL;
341
277
  struct stat st;
342
278
  fd_set rfds_all;
343
279
  int ret, maxfd = 0;
344
 
  ssize_t sret;
345
280
  uid_t uid = 65534;
346
281
  gid_t gid = 65534;
347
282
  bool debug = false;
363
298
  ret = sigaction(SIGCHLD, &sigchld_action, &old_sigchld_action);
364
299
  if(ret == -1){
365
300
    perror("sigaction");
366
 
    exitstatus = EXIT_FAILURE;
 
301
    exitstatus = EXIT_FAILURE;    
367
302
    goto fallback;
368
303
  }
369
304
  
372
307
    { .name = "global-options", .key = 'g',
373
308
      .arg = "OPTION[,OPTION[,...]]",
374
309
      .doc = "Options passed to all plugins" },
375
 
    { .name = "global-env", .key = 'G',
 
310
    { .name = "global-envs", .key = 'e',
376
311
      .arg = "VAR=value",
377
312
      .doc = "Environment variable passed to all plugins" },
378
313
    { .name = "options-for", .key = 'o',
379
314
      .arg = "PLUGIN:OPTION[,OPTION[,...]]",
380
315
      .doc = "Options passed only to specified plugin" },
381
 
    { .name = "env-for", .key = 'E',
 
316
    { .name = "envs-for", .key = 'f',
382
317
      .arg = "PLUGIN:ENV=value",
383
318
      .doc = "Environment variable passed to specified plugin" },
384
319
    { .name = "disable", .key = 'd',
385
320
      .arg = "PLUGIN",
386
321
      .doc = "Disable a specific plugin", .group = 1 },
387
 
    { .name = "enable", .key = 'e',
388
 
      .arg = "PLUGIN",
389
 
      .doc = "Enable a specific plugin", .group = 1 },
390
322
    { .name = "plugin-dir", .key = 128,
391
323
      .arg = "DIRECTORY",
392
324
      .doc = "Specify a different plugin directory", .group = 2 },
393
 
    { .name = "config-file", .key = 129,
394
 
      .arg = "FILE",
395
 
      .doc = "Specify a different configuration file", .group = 2 },
396
 
    { .name = "userid", .key = 130,
397
 
      .arg = "ID", .flags = 0,
398
 
      .doc = "User ID the plugins will run as", .group = 3 },
399
 
    { .name = "groupid", .key = 131,
400
 
      .arg = "ID", .flags = 0,
401
 
      .doc = "Group ID the plugins will run as", .group = 3 },
402
 
    { .name = "debug", .key = 132,
403
 
      .doc = "Debug mode", .group = 4 },
404
 
    /*
405
 
     * These reproduce what we would get without ARGP_NO_HELP
406
 
     */
407
 
    { .name = "help", .key = '?',
408
 
      .doc = "Give this help list", .group = -1 },
409
 
    { .name = "usage", .key = -3,
410
 
      .doc = "Give a short usage message", .group = -1 },
411
 
    { .name = "version", .key = 'V',
412
 
      .doc = "Print program version", .group = -1 },
 
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 },
413
333
    { .name = NULL }
414
334
  };
415
335
  
416
 
  error_t parse_opt(int key, char *arg, struct argp_state *state){
417
 
    errno = 0;
418
 
    switch(key){
419
 
      char *tmp;
420
 
      intmax_t tmpmax;
421
 
    case 'g':                   /* --global-options */
422
 
      {
423
 
        char *plugin_option;
424
 
        while((plugin_option = strsep(&arg, ",")) != NULL){
425
 
          if(not add_argument(getplugin(NULL), plugin_option)){
426
 
            break;
427
 
          }
428
 
        }
429
 
      }
430
 
      break;
431
 
    case 'G':                   /* --global-env */
432
 
      add_environment(getplugin(NULL), arg, true);
433
 
      break;
434
 
    case 'o':                   /* --options-for */
435
 
      {
436
 
        char *option_list = strchr(arg, ':');
437
 
        if(option_list == NULL){
438
 
          argp_error(state, "No colon in \"%s\"", arg);
439
 
          errno = EINVAL;
440
 
          break;
441
 
        }
442
 
        *option_list = '\0';
443
 
        option_list++;
444
 
        if(arg[0] == '\0'){
445
 
          argp_error(state, "Empty plugin name");
446
 
          errno = EINVAL;
447
 
          break;
448
 
        }
449
 
        char *option;
450
 
        while((option = strsep(&option_list, ",")) != NULL){
451
 
          if(not add_argument(getplugin(arg), option)){
452
 
            break;
453
 
          }
454
 
        }
455
 
      }
456
 
      break;
457
 
    case 'E':                   /* --env-for */
 
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;
 
340
    switch (key) {
 
341
    case 'g':
 
342
      if (arg != NULL){
 
343
        char *p;
 
344
        while((p = strsep(&arg, ",")) != NULL){
 
345
          if(p[0] == '\0'){
 
346
            continue;
 
347
          }
 
348
          if(not add_argument(getplugin(NULL, plugins), p)){
 
349
            perror("add_argument");
 
350
            return ARGP_ERR_UNKNOWN;
 
351
          }
 
352
        }
 
353
      }
 
354
      break;
 
355
    case 'e':
 
356
      if(arg == NULL){
 
357
        break;
 
358
      }
 
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
        }
 
367
      }
 
368
      break;
 
369
    case 'o':
 
370
      if (arg != NULL){
 
371
        char *p_name = strsep(&arg, ":");
 
372
        if(p_name[0] == '\0'){
 
373
          break;
 
374
        }
 
375
        char *opt = strsep(&arg, ":");
 
376
        if(opt[0] == '\0'){
 
377
          break;
 
378
        }
 
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
            }
 
389
          }
 
390
        }
 
391
      }
 
392
      break;
 
393
    case 'f':
 
394
      if(arg == NULL){
 
395
        break;
 
396
      }
458
397
      {
459
398
        char *envdef = strchr(arg, ':');
460
399
        if(envdef == NULL){
461
 
          argp_error(state, "No colon in \"%s\"", arg);
462
 
          errno = EINVAL;
463
 
          break;
464
 
        }
465
 
        *envdef = '\0';
 
400
          break;
 
401
        }
 
402
        char *p_name = strndup(arg, (size_t) (envdef-arg));
 
403
        if(p_name == NULL){
 
404
          break;
 
405
        }
466
406
        envdef++;
467
 
        if(arg[0] == '\0'){
468
 
          argp_error(state, "Empty plugin name");
469
 
          errno = EINVAL;
470
 
          break;
471
 
        }
472
 
        add_environment(getplugin(arg), envdef, true);
473
 
      }
474
 
      break;
475
 
    case 'd':                   /* --disable */
476
 
      {
477
 
        plugin *p = getplugin(arg);
478
 
        if(p != NULL){
479
 
          p->disabled = true;
480
 
        }
481
 
      }
482
 
      break;
483
 
    case 'e':                   /* --enable */
484
 
      {
485
 
        plugin *p = getplugin(arg);
486
 
        if(p != NULL){
487
 
          p->disabled = false;
488
 
        }
489
 
      }
490
 
      break;
491
 
    case 128:                   /* --plugin-dir */
492
 
      free(plugindir);
493
 
      plugindir = strdup(arg);
494
 
      break;
495
 
    case 129:                   /* --config-file */
496
 
      /* This is already done by parse_opt_config_file() */
497
 
      break;
498
 
    case 130:                   /* --userid */
499
 
      tmpmax = strtoimax(arg, &tmp, 10);
500
 
      if(errno != 0 or tmp == arg or *tmp != '\0'
501
 
         or tmpmax != (uid_t)tmpmax){
502
 
        argp_error(state, "Bad user ID number: \"%s\", using %"
503
 
                   PRIdMAX, arg, (intmax_t)uid);
504
 
        break;
505
 
      }
506
 
      uid = (uid_t)tmpmax;
507
 
      break;
508
 
    case 131:                   /* --groupid */
509
 
      tmpmax = strtoimax(arg, &tmp, 10);
510
 
      if(errno != 0 or tmp == arg or *tmp != '\0'
511
 
         or tmpmax != (gid_t)tmpmax){
512
 
        argp_error(state, "Bad group ID number: \"%s\", using %"
513
 
                   PRIdMAX, arg, (intmax_t)gid);
514
 
        break;
515
 
      }
516
 
      gid = (gid_t)tmpmax;
517
 
      break;
518
 
    case 132:                   /* --debug */
 
407
        if(not add_environment(getplugin(p_name, plugins), envdef)){
 
408
          perror("add_environment");
 
409
        }
 
410
      }
 
411
      break;
 
412
    case 'd':
 
413
      if (arg != NULL){
 
414
        plugin *p = getplugin(arg, plugins);
 
415
        if(p == NULL){
 
416
          return ARGP_ERR_UNKNOWN;
 
417
        }
 
418
        p->disabled = true;
 
419
      }
 
420
      break;
 
421
    case 128:
 
422
      plugindir = arg;
 
423
      break;
 
424
    case 129:
 
425
      uid = (uid_t)strtol(arg, NULL, 10);
 
426
      break;
 
427
    case 130:
 
428
      gid = (gid_t)strtol(arg, NULL, 10);
 
429
      break;
 
430
    case 131:
519
431
      debug = true;
520
432
      break;
521
 
      /*
522
 
       * These reproduce what we would get without ARGP_NO_HELP
523
 
       */
524
 
    case '?':                   /* --help */
525
 
      state->flags &= ~(unsigned int)ARGP_NO_EXIT; /* force exit */
526
 
      argp_state_help(state, state->out_stream, ARGP_HELP_STD_HELP);
527
 
    case -3:                    /* --usage */
528
 
      state->flags &= ~(unsigned int)ARGP_NO_EXIT; /* force exit */
529
 
      argp_state_help(state, state->out_stream,
530
 
                      ARGP_HELP_USAGE | ARGP_HELP_EXIT_OK);
531
 
    case 'V':                   /* --version */
532
 
      fprintf(state->out_stream, "%s\n", argp_program_version);
533
 
      exit(EXIT_SUCCESS);
534
 
      break;
535
 
/*
536
 
 * When adding more options before this line, remember to also add a
537
 
 * "case" to the "parse_opt_config_file" function below.
538
 
 */
539
 
    case ARGP_KEY_ARG:
540
 
      /* Cryptsetup always passes an argument, which is an empty
541
 
         string if "none" was specified in /etc/crypttab.  So if
542
 
         argument was empty, we ignore it silently. */
543
 
      if(arg[0] == '\0'){
544
 
        break;
545
 
      }
546
 
    default:
547
 
      return ARGP_ERR_UNKNOWN;
548
 
    }
549
 
    return errno;               /* Set to 0 at start */
550
 
  }
551
 
  
552
 
  /* This option parser is the same as parse_opt() above, except it
553
 
     ignores everything but the --config-file option. */
554
 
  error_t parse_opt_config_file(int key, char *arg,
555
 
                                __attribute__((unused))
556
 
                                struct argp_state *state){
557
 
    errno = 0;
558
 
    switch(key){
559
 
    case 'g':                   /* --global-options */
560
 
    case 'G':                   /* --global-env */
561
 
    case 'o':                   /* --options-for */
562
 
    case 'E':                   /* --env-for */
563
 
    case 'd':                   /* --disable */
564
 
    case 'e':                   /* --enable */
565
 
    case 128:                   /* --plugin-dir */
566
 
      break;
567
 
    case 129:                   /* --config-file */
568
 
      free(argfile);
569
 
      argfile = strdup(arg);
570
 
      break;
571
 
    case 130:                   /* --userid */
572
 
    case 131:                   /* --groupid */
573
 
    case 132:                   /* --debug */
574
 
    case '?':                   /* --help */
575
 
    case -3:                    /* --usage */
576
 
    case 'V':                   /* --version */
577
 
    case ARGP_KEY_ARG:
578
 
      break;
579
 
    default:
580
 
      return ARGP_ERR_UNKNOWN;
581
 
    }
582
 
    return errno;
583
 
  }
584
 
  
585
 
  struct argp argp = { .options = options,
586
 
                       .parser = parse_opt_config_file,
587
 
                       .args_doc = "",
 
433
    case ARGP_KEY_ARG:
 
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]",
588
448
                       .doc = "Mandos plugin runner -- Run plugins" };
589
449
  
590
 
  /* Parse using parse_opt_config_file() in order to get the custom
591
 
     config file location, if any. */
592
 
  ret = argp_parse(&argp, argc, argv,
593
 
                   ARGP_IN_ORDER | ARGP_NO_EXIT | ARGP_NO_HELP,
594
 
                   NULL, NULL);
595
 
  switch(ret){
596
 
  case 0:
597
 
    break;
598
 
  case ENOMEM:
599
 
  default:
600
 
    errno = ret;
601
 
    perror("argp_parse");
602
 
    exitstatus = EX_OSERR;
603
 
    goto fallback;
604
 
  case EINVAL:
605
 
    exitstatus = EX_USAGE;
606
 
    goto fallback;
607
 
  }
608
 
  
609
 
  /* Reset to the normal argument parser */
610
 
  argp.parser = parse_opt;
611
 
  
612
 
  /* Open the configfile if available */
613
 
  if(argfile == NULL){
614
 
    conffp = fopen(AFILE, "r");
615
 
  } else {
616
 
    conffp = fopen(argfile, "r");
617
 
  }
 
450
  ret = argp_parse (&argp, argc, argv, 0, 0, &plugin_list);
 
451
  if (ret == ARGP_ERR_UNKNOWN){
 
452
    fprintf(stderr, "Unknown error while parsing arguments\n");
 
453
    exitstatus = EXIT_FAILURE;
 
454
    goto fallback;
 
455
  }
 
456
 
 
457
  conffp = fopen(argfile, "r");
618
458
  if(conffp != NULL){
619
459
    char *org_line = NULL;
620
460
    char *p, *arg, *new_arg, *line;
621
461
    size_t size = 0;
 
462
    ssize_t sret;
622
463
    const char whitespace_delims[] = " \r\t\f\v\n";
623
464
    const char comment_delim[] = "#";
624
 
    
625
 
    custom_argc = 1;
626
 
    custom_argv = malloc(sizeof(char*) * 2);
627
 
    if(custom_argv == NULL){
628
 
      perror("malloc");
629
 
      exitstatus = EXIT_FAILURE;
630
 
      goto fallback;
631
 
    }
632
 
    custom_argv[0] = argv[0];
633
 
    custom_argv[1] = NULL;
634
 
    
635
 
    /* for each line in the config file, strip whitespace and ignore
636
 
       commented text */
 
465
 
637
466
    while(true){
638
467
      sret = getline(&org_line, &size, conffp);
639
468
      if(sret == -1){
640
469
        break;
641
470
      }
642
 
      
 
471
 
643
472
      line = org_line;
644
473
      arg = strsep(&line, comment_delim);
645
474
      while((p = strsep(&arg, whitespace_delims)) != NULL){
647
476
          continue;
648
477
        }
649
478
        new_arg = strdup(p);
650
 
        if(new_arg == NULL){
651
 
          perror("strdup");
652
 
          exitstatus = EXIT_FAILURE;
653
 
          free(org_line);
654
 
          goto fallback;
655
 
        }
656
 
        
657
 
        custom_argc += 1;
658
 
        custom_argv = realloc(custom_argv, sizeof(char *)
659
 
                              * ((unsigned int) custom_argc + 1));
660
 
        if(custom_argv == NULL){
661
 
          perror("realloc");
662
 
          exitstatus = EXIT_FAILURE;
663
 
          free(org_line);
664
 
          goto fallback;
665
 
        }
666
 
        custom_argv[custom_argc-1] = new_arg;
667
 
        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
        }
668
485
      }
669
486
    }
670
 
    do {
671
 
      ret = fclose(conffp);
672
 
    } while(ret == EOF and errno == EINTR);
673
 
    if(ret == EOF){
674
 
      perror("fclose");
675
 
      exitstatus = EXIT_FAILURE;
676
 
      goto fallback;
677
 
    }
678
487
    free(org_line);
679
 
  } else {
 
488
  } else{
680
489
    /* Check for harmful errors and go to fallback. Other errors might
681
490
       not affect opening plugins */
682
 
    if(errno == EMFILE or errno == ENFILE or errno == ENOMEM){
 
491
    if (errno == EMFILE or errno == ENFILE or errno == ENOMEM){
683
492
      perror("fopen");
684
493
      exitstatus = EXIT_FAILURE;
685
494
      goto fallback;
686
495
    }
687
496
  }
688
 
  /* If there were any arguments from the configuration file, pass
689
 
     them to parser as command line arguments */
 
497
 
690
498
  if(custom_argv != NULL){
691
 
    ret = argp_parse(&argp, custom_argc, custom_argv,
692
 
                     ARGP_IN_ORDER | ARGP_NO_EXIT | ARGP_NO_HELP,
693
 
                     NULL, NULL);
694
 
    switch(ret){
695
 
    case 0:
696
 
      break;
697
 
    case ENOMEM:
698
 
    default:
699
 
      errno = ret;
700
 
      perror("argp_parse");
701
 
      exitstatus = EX_OSERR;
702
 
      goto fallback;
703
 
    case EINVAL:
704
 
      exitstatus = EX_CONFIG;
 
499
    custom_argv[0] = argv[0];
 
500
    ret = argp_parse (&argp, custom_argc, custom_argv, 0, 0, &plugin_list);
 
501
    if (ret == ARGP_ERR_UNKNOWN){
 
502
      fprintf(stderr, "Unknown error while parsing arguments\n");
 
503
      exitstatus = EXIT_FAILURE;
705
504
      goto fallback;
706
505
    }
707
506
  }
708
507
  
709
 
  /* Parse actual command line arguments, to let them override the
710
 
     config file */
711
 
  ret = argp_parse(&argp, argc, argv,
712
 
                   ARGP_IN_ORDER | ARGP_NO_EXIT | ARGP_NO_HELP,
713
 
                   NULL, NULL);
714
 
  switch(ret){
715
 
  case 0:
716
 
    break;
717
 
  case ENOMEM:
718
 
  default:
719
 
    errno = ret;
720
 
    perror("argp_parse");
721
 
    exitstatus = EX_OSERR;
722
 
    goto fallback;
723
 
  case EINVAL:
724
 
    exitstatus = EX_USAGE;
725
 
    goto fallback;
726
 
  }
727
 
  
728
508
  if(debug){
729
509
    for(plugin *p = plugin_list; p != NULL; p=p->next){
730
510
      fprintf(stderr, "Plugin: %s has %d arguments\n",
732
512
      for(char **a = p->argv; *a != NULL; a++){
733
513
        fprintf(stderr, "\tArg: %s\n", *a);
734
514
      }
735
 
      fprintf(stderr, "...and %d environment variables\n", p->envc);
 
515
      fprintf(stderr, "...and %u environment variables\n", p->envc);
736
516
      for(char **a = p->environ; *a != NULL; a++){
737
517
        fprintf(stderr, "\t%s\n", *a);
738
518
      }
739
519
    }
740
520
  }
741
521
  
742
 
  /* Strip permissions down to nobody */
 
522
  ret = setuid(uid);
 
523
  if (ret == -1){
 
524
    perror("setuid");
 
525
  }
 
526
  
743
527
  setgid(gid);
744
 
  if(ret == -1){
 
528
  if (ret == -1){
745
529
    perror("setgid");
746
530
  }
747
 
  ret = setuid(uid);
748
 
  if(ret == -1){
749
 
    perror("setuid");
 
531
  
 
532
  dir = opendir(plugindir);
 
533
  if(dir == NULL){
 
534
    perror("Could not open plugin dir");
 
535
    exitstatus = EXIT_FAILURE;
 
536
    goto fallback;
750
537
  }
751
538
  
752
 
  /* Open plugin directory with close_on_exec flag */
 
539
  /* Set the FD_CLOEXEC flag on the directory, if possible */
753
540
  {
754
 
    int dir_fd = -1;
755
 
    if(plugindir == NULL){
756
 
      dir_fd = open(PDIR, O_RDONLY |
757
 
#ifdef O_CLOEXEC
758
 
                    O_CLOEXEC
759
 
#else  /* not O_CLOEXEC */
760
 
                    0
761
 
#endif  /* not O_CLOEXEC */
762
 
                    );
763
 
    } else {
764
 
      dir_fd = open(plugindir, O_RDONLY |
765
 
#ifdef O_CLOEXEC
766
 
                    O_CLOEXEC
767
 
#else  /* not O_CLOEXEC */
768
 
                    0
769
 
#endif  /* not O_CLOEXEC */
770
 
                    );
771
 
    }
772
 
    if(dir_fd == -1){
773
 
      perror("Could not open plugin dir");
774
 
      exitstatus = EXIT_FAILURE;
775
 
      goto fallback;
776
 
    }
777
 
    
778
 
#ifndef O_CLOEXEC
779
 
  /* Set the FD_CLOEXEC flag on the directory */
780
 
    ret = set_cloexec_flag(dir_fd);
781
 
    if(ret < 0){
782
 
      perror("set_cloexec_flag");
783
 
      TEMP_FAILURE_RETRY(close(dir_fd));
784
 
      exitstatus = EXIT_FAILURE;
785
 
      goto fallback;
786
 
    }
787
 
#endif  /* O_CLOEXEC */
788
 
    
789
 
    dir = fdopendir(dir_fd);
790
 
    if(dir == NULL){
791
 
      perror("Could not open plugin dir");
792
 
      TEMP_FAILURE_RETRY(close(dir_fd));
793
 
      exitstatus = EXIT_FAILURE;
794
 
      goto fallback;
 
541
    int dir_fd = dirfd(dir);
 
542
    if(dir_fd >= 0){
 
543
      ret = set_cloexec_flag(dir_fd);
 
544
      if(ret < 0){
 
545
        perror("set_cloexec_flag");
 
546
        exitstatus = EXIT_FAILURE;
 
547
        goto fallback;
 
548
      }
795
549
    }
796
550
  }
797
551
  
798
552
  FD_ZERO(&rfds_all);
799
553
  
800
 
  /* Read and execute any executable in the plugin directory*/
801
554
  while(true){
802
 
    do {
803
 
      dirst = readdir(dir);
804
 
    } while(dirst == NULL and errno == EINTR);
 
555
    dirst = readdir(dir);
805
556
    
806
 
    /* All directory entries have been processed */
 
557
    // All directory entries have been processed
807
558
    if(dirst == NULL){
808
 
      if(errno == EBADF){
 
559
      if (errno == EBADF){
809
560
        perror("readdir");
810
561
        exitstatus = EXIT_FAILURE;
811
562
        goto fallback;
815
566
    
816
567
    d_name_len = strlen(dirst->d_name);
817
568
    
818
 
    /* Ignore dotfiles, backup files and other junk */
 
569
    // Ignore dotfiles, backup files and other junk
819
570
    {
820
571
      bool bad_name = false;
821
572
      
823
574
      
824
575
      const char const *bad_suffixes[] = { "~", "#", ".dpkg-new",
825
576
                                           ".dpkg-old",
826
 
                                           ".dpkg-bak",
827
577
                                           ".dpkg-divert", NULL };
828
578
      for(const char **pre = bad_prefixes; *pre != NULL; pre++){
829
579
        size_t pre_len = strlen(*pre);
837
587
          break;
838
588
        }
839
589
      }
 
590
      
840
591
      if(bad_name){
841
592
        continue;
842
593
      }
 
594
      
843
595
      for(const char **suf = bad_suffixes; *suf != NULL; suf++){
844
596
        size_t suf_len = strlen(*suf);
845
597
        if((d_name_len >= suf_len)
858
610
        continue;
859
611
      }
860
612
    }
861
 
    
 
613
 
862
614
    char *filename;
863
 
    if(plugindir == NULL){
864
 
      ret = (int)TEMP_FAILURE_RETRY(asprintf(&filename, PDIR "/%s",
865
 
                                             dirst->d_name));
866
 
    } else {
867
 
      ret = (int)TEMP_FAILURE_RETRY(asprintf(&filename, "%s/%s",
868
 
                                             plugindir,
869
 
                                             dirst->d_name));
870
 
    }
 
615
    ret = asprintf(&filename, "%s/%s", plugindir, dirst->d_name);
871
616
    if(ret < 0){
872
617
      perror("asprintf");
873
618
      continue;
874
619
    }
875
620
    
876
 
    ret = (int)TEMP_FAILURE_RETRY(stat(filename, &st));
877
 
    if(ret == -1){
 
621
    ret = stat(filename, &st);
 
622
    if (ret == -1){
878
623
      perror("stat");
879
624
      free(filename);
880
625
      continue;
881
626
    }
882
627
    
883
 
    /* Ignore non-executable files */
884
 
    if(not S_ISREG(st.st_mode)
885
 
       or (TEMP_FAILURE_RETRY(access(filename, X_OK)) != 0)){
 
628
    if (not S_ISREG(st.st_mode) or (access(filename, X_OK) != 0)){
886
629
      if(debug){
887
630
        fprintf(stderr, "Ignoring plugin dir entry \"%s\""
888
631
                " with bad type or mode\n", filename);
890
633
      free(filename);
891
634
      continue;
892
635
    }
893
 
    
894
 
    plugin *p = getplugin(dirst->d_name);
 
636
    plugin *p = getplugin(dirst->d_name, &plugin_list);
895
637
    if(p == NULL){
896
638
      perror("getplugin");
897
639
      free(filename);
907
649
    }
908
650
    {
909
651
      /* Add global arguments to argument list for this plugin */
910
 
      plugin *g = getplugin(NULL);
 
652
      plugin *g = getplugin(NULL, &plugin_list);
911
653
      if(g != NULL){
912
654
        for(char **a = g->argv + 1; *a != NULL; a++){
913
655
          if(not add_argument(p, *a)){
916
658
        }
917
659
        /* Add global environment variables */
918
660
        for(char **e = g->environ; *e != NULL; e++){
919
 
          if(not add_environment(p, *e, false)){
 
661
          if(not add_environment(p, *e)){
920
662
            perror("add_environment");
921
663
          }
922
664
        }
927
669
       process, too. */
928
670
    if(p->environ[0] != NULL){
929
671
      for(char **e = environ; *e != NULL; e++){
930
 
        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)){
931
678
          perror("add_environment");
932
679
        }
933
680
      }
934
681
    }
935
682
    
936
 
    int pipefd[2];
937
 
    ret = (int)TEMP_FAILURE_RETRY(pipe(pipefd));
938
 
    if(ret == -1){
 
683
    int pipefd[2]; 
 
684
    ret = pipe(pipefd);
 
685
    if (ret == -1){
939
686
      perror("pipe");
940
687
      exitstatus = EXIT_FAILURE;
941
688
      goto fallback;
942
689
    }
943
 
    /* Ask OS to automatic close the pipe on exec */
944
690
    ret = set_cloexec_flag(pipefd[0]);
945
691
    if(ret < 0){
946
692
      perror("set_cloexec_flag");
954
700
      goto fallback;
955
701
    }
956
702
    /* Block SIGCHLD until process is safely in process list */
957
 
    ret = (int)TEMP_FAILURE_RETRY(sigprocmask(SIG_BLOCK,
958
 
                                              &sigchld_action.sa_mask,
959
 
                                              NULL));
 
703
    ret = sigprocmask (SIG_BLOCK, &sigchld_action.sa_mask, NULL);
960
704
    if(ret < 0){
961
705
      perror("sigprocmask");
962
706
      exitstatus = EXIT_FAILURE;
963
707
      goto fallback;
964
708
    }
965
 
    /* Starting a new process to be watched */
966
 
    pid_t pid;
967
 
    do {
968
 
      pid = fork();
969
 
    } while(pid == -1 and errno == EINTR);
 
709
    // Starting a new process to be watched
 
710
    pid_t pid = fork();
970
711
    if(pid == -1){
971
712
      perror("fork");
972
713
      exitstatus = EXIT_FAILURE;
979
720
        perror("sigaction");
980
721
        _exit(EXIT_FAILURE);
981
722
      }
982
 
      ret = sigprocmask(SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
 
723
      ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
983
724
      if(ret < 0){
984
725
        perror("sigprocmask");
985
726
        _exit(EXIT_FAILURE);
986
727
      }
987
 
      
 
728
 
988
729
      ret = dup2(pipefd[1], STDOUT_FILENO); /* replace our stdout */
989
730
      if(ret == -1){
990
731
        perror("dup2");
1009
750
      }
1010
751
      /* no return */
1011
752
    }
1012
 
    /* Parent process */
1013
 
    TEMP_FAILURE_RETRY(close(pipefd[1])); /* Close unused write end of
1014
 
                                             pipe */
 
753
    /* parent process */
1015
754
    free(filename);
1016
 
    plugin *new_plugin = getplugin(dirst->d_name);
1017
 
    if(new_plugin == NULL){
1018
 
      perror("getplugin");
1019
 
      ret = (int)(TEMP_FAILURE_RETRY
1020
 
                  (sigprocmask(SIG_UNBLOCK, &sigchld_action.sa_mask,
1021
 
                               NULL)));
 
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");
 
759
      ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
1022
760
      if(ret < 0){
1023
 
        perror("sigprocmask");
 
761
        perror("sigprocmask");
1024
762
      }
1025
763
      exitstatus = EXIT_FAILURE;
1026
764
      goto fallback;
1027
765
    }
1028
766
    
1029
 
    new_plugin->pid = pid;
1030
 
    new_plugin->fd = pipefd[0];
1031
 
    
 
767
    *new_process = (struct process){ .pid = pid,
 
768
                                     .fd = pipefd[0],
 
769
                                     .next = process_list };
 
770
    // List handling
 
771
    process_list = new_process;
1032
772
    /* Unblock SIGCHLD so signal handler can be run if this process
1033
773
       has already completed */
1034
 
    ret = (int)TEMP_FAILURE_RETRY(sigprocmask(SIG_UNBLOCK,
1035
 
                                              &sigchld_action.sa_mask,
1036
 
                                              NULL));
 
774
    ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
1037
775
    if(ret < 0){
1038
776
      perror("sigprocmask");
1039
777
      exitstatus = EXIT_FAILURE;
1040
778
      goto fallback;
1041
779
    }
1042
780
    
1043
 
    FD_SET(new_plugin->fd, &rfds_all); /* Spurious warning from
1044
 
                                          -Wconversion */
 
781
    FD_SET(new_process->fd, &rfds_all);
1045
782
    
1046
 
    if(maxfd < new_plugin->fd){
1047
 
      maxfd = new_plugin->fd;
 
783
    if (maxfd < new_process->fd){
 
784
      maxfd = new_process->fd;
1048
785
    }
 
786
    
1049
787
  }
1050
788
  
1051
 
  TEMP_FAILURE_RETRY(closedir(dir));
 
789
  free_plugin_list(plugin_list);
 
790
  
 
791
  closedir(dir);
1052
792
  dir = NULL;
1053
 
  free_plugin(getplugin(NULL));
1054
 
  
1055
 
  for(plugin *p = plugin_list; p != NULL; p = p->next){
1056
 
    if(p->pid != 0){
1057
 
      break;
1058
 
    }
1059
 
    if(p->next == NULL){
1060
 
      fprintf(stderr, "No plugin processes started. Incorrect plugin"
1061
 
              " directory?\n");
1062
 
      free_plugin_list();
1063
 
    }
 
793
    
 
794
  if (process_list == NULL){
 
795
    fprintf(stderr, "No plugin processes started. Incorrect plugin"
 
796
            " directory?\n");
 
797
    process_list = NULL;
1064
798
  }
1065
 
  
1066
 
  /* Main loop while running plugins exist */
1067
 
  while(plugin_list){
 
799
  while(process_list){
1068
800
    fd_set rfds = rfds_all;
1069
801
    int select_ret = select(maxfd+1, &rfds, NULL, NULL, NULL);
1070
 
    if(select_ret == -1 and errno != EINTR){
 
802
    if (select_ret == -1){
1071
803
      perror("select");
1072
804
      exitstatus = EXIT_FAILURE;
1073
805
      goto fallback;
1074
806
    }
1075
807
    /* OK, now either a process completed, or something can be read
1076
808
       from one of them */
1077
 
    for(plugin *proc = plugin_list; proc != NULL;){
 
809
    for(process *proc = process_list; proc ; proc = proc->next){
1078
810
      /* Is this process completely done? */
1079
 
      if(proc->completed and proc->eof){
 
811
      if(proc->eof and proc->completed){
1080
812
        /* Only accept the plugin output if it exited cleanly */
1081
813
        if(not WIFEXITED(proc->status)
1082
814
           or WEXITSTATUS(proc->status) != 0){
1083
815
          /* Bad exit by plugin */
1084
 
          
1085
816
          if(debug){
1086
817
            if(WIFEXITED(proc->status)){
1087
 
              fprintf(stderr, "Plugin %s [%" PRIdMAX "] exited with"
1088
 
                      " status %d\n", proc->name,
1089
 
                      (intmax_t) (proc->pid),
 
818
              fprintf(stderr, "Plugin %u exited with status %d\n",
 
819
                      (unsigned int) (proc->pid),
1090
820
                      WEXITSTATUS(proc->status));
1091
 
            } else if(WIFSIGNALED(proc->status)){
1092
 
              fprintf(stderr, "Plugin %s [%" PRIdMAX "] killed by"
1093
 
                      " signal %d: %s\n", proc->name,
1094
 
                      (intmax_t) (proc->pid),
1095
 
                      WTERMSIG(proc->status),
1096
 
                      strsignal(WTERMSIG(proc->status)));
 
821
            } else if(WIFSIGNALED(proc->status)) {
 
822
              fprintf(stderr, "Plugin %u killed by signal %d\n",
 
823
                      (unsigned int) (proc->pid),
 
824
                      WTERMSIG(proc->status));
1097
825
            } else if(WCOREDUMP(proc->status)){
1098
 
              fprintf(stderr, "Plugin %s [%" PRIdMAX "] dumped"
1099
 
                      " core\n", proc->name, (intmax_t) (proc->pid));
 
826
              fprintf(stderr, "Plugin %d dumped core\n",
 
827
                      (unsigned int) (proc->pid));
1100
828
            }
1101
829
          }
1102
 
          
1103
830
          /* Remove the plugin */
1104
 
          FD_CLR(proc->fd, &rfds_all); /* Spurious warning from
1105
 
                                          -Wconversion */
1106
 
          
 
831
          FD_CLR(proc->fd, &rfds_all);
1107
832
          /* Block signal while modifying process_list */
1108
 
          ret = (int)TEMP_FAILURE_RETRY(sigprocmask
1109
 
                                        (SIG_BLOCK,
1110
 
                                         &sigchld_action.sa_mask,
1111
 
                                         NULL));
 
833
          ret = sigprocmask (SIG_BLOCK, &sigchld_action.sa_mask, NULL);
1112
834
          if(ret < 0){
1113
835
            perror("sigprocmask");
1114
836
            exitstatus = EXIT_FAILURE;
1115
837
            goto fallback;
1116
838
          }
1117
 
          
1118
 
          plugin *next_plugin = proc->next;
1119
 
          free_plugin(proc);
1120
 
          proc = next_plugin;
1121
 
          
 
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
          }
1122
852
          /* We are done modifying process list, so unblock signal */
1123
 
          ret = (int)(TEMP_FAILURE_RETRY
1124
 
                      (sigprocmask(SIG_UNBLOCK,
1125
 
                                   &sigchld_action.sa_mask, NULL)));
 
853
          ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask,
 
854
                             NULL);
1126
855
          if(ret < 0){
1127
856
            perror("sigprocmask");
1128
 
            exitstatus = EXIT_FAILURE;
1129
 
            goto fallback;
1130
 
          }
1131
 
          
1132
 
          if(plugin_list == NULL){
1133
 
            break;
1134
 
          }
1135
 
          
1136
 
          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;
1137
864
        }
1138
 
        
1139
865
        /* This process exited nicely, so print its buffer */
1140
 
        
1141
 
        bool bret = print_out_password(proc->buffer,
1142
 
                                       proc->buffer_length);
 
866
 
 
867
        bool bret = print_out_password(proc->buffer, proc->buffer_length);
1143
868
        if(not bret){
1144
869
          perror("print_out_password");
1145
870
          exitstatus = EXIT_FAILURE;
1146
871
        }
1147
872
        goto fallback;
1148
873
      }
1149
 
      
1150
874
      /* This process has not completed.  Does it have any output? */
1151
 
      if(proc->eof or not FD_ISSET(proc->fd, &rfds)){ /* Spurious
1152
 
                                                         warning from
1153
 
                                                         -Wconversion */
 
875
      if(proc->eof or not FD_ISSET(proc->fd, &rfds)){
1154
876
        /* This process had nothing to say at this time */
1155
 
        proc = proc->next;
1156
877
        continue;
1157
878
      }
1158
879
      /* Before reading, make the process' data buffer large enough */
1159
880
      if(proc->buffer_length + BUFFER_SIZE > proc->buffer_size){
1160
881
        proc->buffer = realloc(proc->buffer, proc->buffer_size
1161
882
                               + (size_t) BUFFER_SIZE);
1162
 
        if(proc->buffer == NULL){
 
883
        if (proc->buffer == NULL){
1163
884
          perror("malloc");
1164
885
          exitstatus = EXIT_FAILURE;
1165
886
          goto fallback;
1167
888
        proc->buffer_size += BUFFER_SIZE;
1168
889
      }
1169
890
      /* Read from the process */
1170
 
      sret = TEMP_FAILURE_RETRY(read(proc->fd,
1171
 
                                     proc->buffer
1172
 
                                     + proc->buffer_length,
1173
 
                                     BUFFER_SIZE));
1174
 
      if(sret < 0){
 
891
      ret = read(proc->fd, proc->buffer + proc->buffer_length,
 
892
                 BUFFER_SIZE);
 
893
      if(ret < 0){
1175
894
        /* Read error from this process; ignore the error */
1176
 
        proc = proc->next;
1177
895
        continue;
1178
896
      }
1179
 
      if(sret == 0){
 
897
      if(ret == 0){
1180
898
        /* got EOF */
1181
899
        proc->eof = true;
1182
900
      } else {
1183
 
        proc->buffer_length += (size_t) sret;
 
901
        proc->buffer_length += (size_t) ret;
1184
902
      }
1185
903
    }
1186
904
  }
1187
 
  
1188
 
  
 
905
 
 
906
 
1189
907
 fallback:
1190
908
  
1191
 
  if(plugin_list == NULL or exitstatus != EXIT_SUCCESS){
1192
 
    /* Fallback if all plugins failed, none are found or an error
1193
 
       occured */
 
909
  if(process_list == NULL or exitstatus != EXIT_SUCCESS){
 
910
    /* Fallback if all plugins failed, none are found or an error occured */
1194
911
    bool bret;
1195
912
    fprintf(stderr, "Going to fallback mode using getpass(3)\n");
1196
913
    char *passwordbuffer = getpass("Password: ");
1197
 
    size_t len = strlen(passwordbuffer);
1198
 
    /* Strip trailing newline */
1199
 
    if(len > 0 and passwordbuffer[len-1] == '\n'){
1200
 
      passwordbuffer[len-1] = '\0'; /* not strictly necessary */
1201
 
      len--;
1202
 
    }
1203
 
    bret = print_out_password(passwordbuffer, len);
 
914
    bret = print_out_password(passwordbuffer, strlen(passwordbuffer));
1204
915
    if(not bret){
1205
916
      perror("print_out_password");
1206
917
      exitstatus = EXIT_FAILURE;
1213
924
    perror("sigaction");
1214
925
    exitstatus = EXIT_FAILURE;
1215
926
  }
1216
 
  
 
927
 
1217
928
  if(custom_argv != NULL){
1218
 
    for(char **arg = custom_argv+1; *arg != NULL; arg++){
 
929
    for(char **arg = custom_argv; *arg != NULL; arg++){
1219
930
      free(*arg);
1220
931
    }
1221
932
    free(custom_argv);
1222
933
  }
 
934
  free_plugin_list(plugin_list);
1223
935
  
1224
936
  if(dir != NULL){
1225
937
    closedir(dir);
1226
938
  }
1227
939
  
1228
 
  /* Kill the processes */
1229
 
  for(plugin *p = plugin_list; p != NULL; p = p->next){
1230
 
    if(p->pid != 0){
1231
 
      close(p->fd);
1232
 
      ret = kill(p->pid, SIGTERM);
1233
 
      if(ret == -1 and errno != ESRCH){
1234
 
        /* Set-uid proccesses might not get closed */
1235
 
        perror("kill");
1236
 
      }
 
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");
1237
948
    }
 
949
    free(process_list->buffer);
 
950
    free(process_list);
1238
951
  }
1239
952
  
1240
953
  /* Wait for any remaining child processes to terminate */
1241
 
  do {
 
954
  do{
1242
955
    ret = wait(NULL);
1243
956
  } while(ret >= 0);
1244
957
  if(errno != ECHILD){
1245
958
    perror("wait");
1246
959
  }
1247
960
  
1248
 
  free_plugin_list();
1249
 
  
1250
 
  free(plugindir);
1251
 
  free(argfile);
1252
 
  
1253
961
  return exitstatus;
1254
962
}