/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

Earlier signal handling

Show diffs side-by-side

added added

removed removed

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