/mandos/release

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

« back to all changes in this revision

Viewing changes to plugin-runner.c

  • Committer: Björn Påhlsson
  • Date: 2009-02-09 18:15:18 UTC
  • mto: (237.7.1 mandos) (24.1.154 mandos)
  • mto: This revision was merged to the branch mainline in revision 250.
  • Revision ID: belorn@braxen-20090209181518-powtql91qv3wu51d
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 & 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
21
22
 * Contact the authors at <mandos@fukt.bsnet.se>.
22
23
 */
23
24
 
24
 
#define _GNU_SOURCE             /* TEMP_FAILURE_RETRY() */
25
 
 
26
 
#include <stdio.h>              /* popen(), fileno(), fprintf(),
 
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(),
27
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() */
28
43
#include <iso646.h>             /* and, or, not */
29
 
#include <sys/types.h>          /* DIR, opendir(), stat(),
30
 
                                   struct stat, waitpid(),
31
 
                                   WIFEXITED(), WEXITSTATUS(),
32
 
                                   wait() */
33
 
#include <sys/wait.h>           /* wait() */
34
44
#include <dirent.h>             /* DIR, struct dirent, opendir(),
35
 
                                   readdir(), closedir() */
36
 
#include <sys/stat.h>           /* struct stat, stat(), S_ISREG() */
 
45
                                   readdir(), closedir(), dirfd() */
37
46
#include <unistd.h>             /* struct stat, stat(), S_ISREG(),
38
 
                                   fcntl() */
39
 
#include <fcntl.h>              /* fcntl() */
40
 
#include <stddef.h>             /* NULL */
41
 
#include <stdlib.h>             /* EXIT_FAILURE */
42
 
#include <sys/select.h>         /* fd_set, select(), FD_ZERO(),
43
 
                                   FD_SET(), FD_ISSET() */
44
 
#include <string.h>             /* strlen(), strcpy(), strcat() */
45
 
#include <stdbool.h>            /* true */
46
 
#include <sys/wait.h>           /* waitpid(), WIFEXITED(),
47
 
                                   WEXITSTATUS() */
 
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() */
48
56
#include <errno.h>              /* errno */
49
 
#include <argp.h>               /* struct argp_option,
50
 
                                   struct argp_state, struct argp,
51
 
                                   argp_parse() */
 
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,  */
52
68
 
53
69
#define BUFFER_SIZE 256
54
70
 
55
 
struct process;
56
 
 
57
 
typedef struct process{
 
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*/
58
86
  pid_t pid;
59
87
  int fd;
60
88
  char *buffer;
61
89
  size_t buffer_size;
62
90
  size_t buffer_length;
63
91
  bool eof;
64
 
  bool completed;
 
92
  volatile sig_atomic_t completed;
65
93
  int status;
66
 
  struct process *next;
67
 
} process;
68
 
 
69
 
typedef struct plugin{
70
 
  char *name;                   /* can be NULL or any plugin name */
71
 
  char **argv;
72
 
  int argc;
73
 
  bool disabled;
74
94
  struct plugin *next;
75
95
} plugin;
76
96
 
77
 
static plugin *getplugin(char *name, plugin **plugin_list){
78
 
  for (plugin *p = *plugin_list; p != NULL; p = p->next){
79
 
    if ((p->name == name)
80
 
        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))){
81
106
      return p;
82
107
    }
83
108
  }
84
109
  /* Create a new plugin */
85
110
  plugin *new_plugin = malloc(sizeof(plugin));
86
 
  if (new_plugin == NULL){
87
 
    perror("malloc");
88
 
    exit(EXIT_FAILURE);
89
 
  }
90
 
  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
  
91
128
  new_plugin->argv = malloc(sizeof(char *) * 2);
92
 
  if (new_plugin->argv == NULL){
93
 
    perror("malloc");
94
 
    exit(EXIT_FAILURE);
 
129
  if(new_plugin->argv == NULL){
 
130
    free(copy_name);
 
131
    free(new_plugin);
 
132
    return NULL;
95
133
  }
96
 
  new_plugin->argv[0] = name;
 
134
  new_plugin->argv[0] = copy_name;
97
135
  new_plugin->argv[1] = NULL;
98
 
  new_plugin->argc = 1;
99
 
  new_plugin->disabled = false;
100
 
  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
  
101
146
  /* Append the new plugin to the list */
102
 
  *plugin_list = new_plugin;
 
147
  plugin_list = new_plugin;
103
148
  return new_plugin;
104
149
}
105
150
 
106
 
static void addargument(plugin *p, char *arg){
107
 
  p->argv[p->argc] = arg;
108
 
  p->argv = realloc(p->argv, sizeof(char *) * (size_t)(p->argc + 2));
109
 
  if (p->argv == NULL){
110
 
    perror("malloc");
111
 
    exit(EXIT_FAILURE);
112
 
  }
113
 
  p->argc++;
114
 
  p->argv[p->argc] = NULL;
 
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));
115
205
}
116
206
 
117
207
/*
119
209
 * Descriptor Flags".
120
210
 * *Note File Descriptor Flags:(libc)Descriptor Flags.
121
211
 */
122
 
static int set_cloexec_flag(int fd)
123
 
{
 
212
static int set_cloexec_flag(int fd){
124
213
  int ret = fcntl(fd, F_GETFD, 0);
125
214
  /* If reading the flags failed, return error indication now. */
126
215
  if(ret < 0){
130
219
  return fcntl(fd, F_SETFD, ret | FD_CLOEXEC);
131
220
}
132
221
 
133
 
const char *argp_program_version = "plugbasedclient 0.9";
134
 
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
135
 
 
136
 
process *process_list = NULL;
137
 
 
138
 
/* Mark a process as completed when it exits, and save its exit
 
222
 
 
223
/* Mark processes as completed when they exit, and save their exit
139
224
   status. */
140
 
void handle_sigchld(__attribute__((unused)) int sig){
141
 
  process *proc = process_list;
142
 
  int status;
143
 
  pid_t pid = wait(&status);
144
 
  while(proc != NULL and proc->pid != pid){
145
 
    proc = proc->next;
146
 
  }
147
 
  if(proc == NULL){
148
 
    /* Process not found in process list */
149
 
    return;
150
 
  }
151
 
  proc->status = status;
152
 
  proc->completed = true;
 
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
  }
153
304
}
154
305
 
155
306
int main(int argc, char *argv[]){
156
 
  const char *plugindir = "/conf/conf.d/mandos/plugins.d";
 
307
  char *plugindir = NULL;
 
308
  char *argfile = NULL;
 
309
  FILE *conffp;
157
310
  size_t d_name_len;
158
311
  DIR *dir = NULL;
159
312
  struct dirent *dirst;
160
313
  struct stat st;
161
314
  fd_set rfds_all;
162
 
  int ret, maxfd = 0;
 
315
  int ret, numchars, maxfd = 0;
 
316
  ssize_t sret;
 
317
  intmax_t tmpmax;
163
318
  uid_t uid = 65534;
164
319
  gid_t gid = 65534;
165
320
  bool debug = false;
167
322
  struct sigaction old_sigchld_action;
168
323
  struct sigaction sigchld_action = { .sa_handler = handle_sigchld,
169
324
                                      .sa_flags = SA_NOCLDSTOP };
170
 
  char *plus_options = NULL;
171
 
  char **plus_argv = NULL;
 
325
  char **custom_argv = NULL;
 
326
  int custom_argc = 0;
172
327
  
173
328
  /* Establish a signal handler */
174
329
  sigemptyset(&sigchld_action.sa_mask);
175
330
  ret = sigaddset(&sigchld_action.sa_mask, SIGCHLD);
176
 
  if(ret < 0){
 
331
  if(ret == -1){
177
332
    perror("sigaddset");
178
 
    exit(EXIT_FAILURE);
 
333
    exitstatus = EXIT_FAILURE;
 
334
    goto fallback;
179
335
  }
180
336
  ret = sigaction(SIGCHLD, &sigchld_action, &old_sigchld_action);
181
 
  if(ret < 0){
 
337
  if(ret == -1){
182
338
    perror("sigaction");
183
 
    exit(EXIT_FAILURE);
 
339
    exitstatus = EXIT_FAILURE;
 
340
    goto fallback;
184
341
  }
185
342
  
186
343
  /* The options we understand. */
188
345
    { .name = "global-options", .key = 'g',
189
346
      .arg = "OPTION[,OPTION[,...]]",
190
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" },
191
351
    { .name = "options-for", .key = 'o',
192
352
      .arg = "PLUGIN:OPTION[,OPTION[,...]]",
193
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" },
194
357
    { .name = "disable", .key = 'd',
195
358
      .arg = "PLUGIN",
196
359
      .doc = "Disable a specific plugin", .group = 1 },
 
360
    { .name = "enable", .key = 'e',
 
361
      .arg = "PLUGIN",
 
362
      .doc = "Enable a specific plugin", .group = 1 },
197
363
    { .name = "plugin-dir", .key = 128,
198
364
      .arg = "DIRECTORY",
199
365
      .doc = "Specify a different plugin directory", .group = 2 },
200
 
    { .name = "userid", .key = 129,
201
 
      .arg = "ID", .flags = 0,
202
 
      .doc = "User ID the plugins will run as", .group = 2 },
203
 
    { .name = "groupid", .key = 130,
204
 
      .arg = "ID", .flags = 0,
205
 
      .doc = "Group ID the plugins will run as", .group = 2 },
206
 
    { .name = "debug", .key = 131,
207
 
      .doc = "Debug mode", .group = 3 },
 
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 },
208
377
    { .name = NULL }
209
378
  };
210
379
  
211
 
  error_t parse_opt (int key, char *arg, struct argp_state *state) {
212
 
    /* Get the INPUT argument from `argp_parse', which we know is a
213
 
       pointer to our plugin list pointer. */
214
 
    plugin **plugins = state->input;
215
 
    switch (key) {
216
 
    case 'g':
217
 
      if (arg != NULL){
218
 
        char *p = strtok(arg, ",");
219
 
        do{
220
 
          addargument(getplugin(NULL, plugins), p);
221
 
          p = strtok(NULL, ",");
222
 
        } while (p != NULL);
223
 
      }
224
 
      break;
225
 
    case 'o':
226
 
      if (arg != NULL){
227
 
        char *name = strtok(arg, ":");
228
 
        char *p = strtok(NULL, ":");
229
 
        if(p != NULL){
230
 
          p = strtok(p, ",");
231
 
          do{
232
 
            addargument(getplugin(name, plugins), p);
233
 
            p = strtok(NULL, ",");
234
 
          } while (p != NULL);
235
 
        }
236
 
      }
237
 
      break;
238
 
    case 'd':
239
 
      if (arg != NULL){
240
 
        getplugin(arg, plugins)->disabled = true;
241
 
      }
242
 
      break;
243
 
    case 128:
244
 
      plugindir = arg;
245
 
      break;
246
 
    case 129:
247
 
      uid = (uid_t)strtol(arg, NULL, 10);
248
 
      break;
249
 
    case 130:
250
 
      gid = (gid_t)strtol(arg, NULL, 10);
251
 
      break;
252
 
    case 131:
 
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 */
253
484
      debug = true;
254
485
      break;
255
 
    case ARGP_KEY_ARG:
256
 
      if(plus_options != NULL or arg == NULL or arg[0] != '+'){
257
 
        argp_usage (state);
258
 
      }
259
 
      plus_options = arg;
260
 
      break;
261
 
    case ARGP_KEY_END:
262
 
      break;
263
 
    default:
264
 
      return ARGP_ERR_UNKNOWN;
265
 
    }
266
 
    return 0;
267
 
  }
268
 
  
269
 
  plugin *plugin_list = NULL;
270
 
  
271
 
  struct argp argp = { .options = options, .parser = parse_opt,
272
 
                       .args_doc = "[+PLUS_SEPARATED_OPTIONS]",
 
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 = "",
273
542
                       .doc = "Mandos plugin runner -- Run plugins" };
274
543
  
275
 
  argp_parse (&argp, argc, argv, 0, 0, &plugin_list);  
276
 
  
277
 
  if(plus_options){
278
 
    /* This is a mangled argument in the form of
279
 
     "+--option+--other-option=parameter+--yet-another-option", etc */
280
 
    /* Make new argc and argv vars, and call argp_parse() again. */
281
 
    plus_options++;             /* skip the first '+' character */
282
 
    const char delims[] = "+";
283
 
    char *arg;
284
 
    int new_argc = 1;
285
 
    plus_argv = malloc(sizeof(char*) * 2);
286
 
    if(plus_argv == NULL){
 
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){
287
572
      perror("malloc");
288
573
      exitstatus = EXIT_FAILURE;
289
 
      goto end;
290
 
    }
291
 
    plus_argv[0] = argv[0];
292
 
    plus_argv[1] = NULL;
293
 
    arg = strtok(plus_options, delims); /* Get first argument */
294
 
    while(arg != NULL){
295
 
      new_argc++;
296
 
      plus_argv = realloc(plus_argv, sizeof(char *)
297
 
                         * ((unsigned int) new_argc + 1));
298
 
      if(plus_argv == NULL){
299
 
        perror("malloc");
300
 
        exitstatus = EXIT_FAILURE;
301
 
        goto end;
302
 
      }
303
 
      plus_argv[new_argc-1] = arg;
304
 
      plus_argv[new_argc] = NULL;
305
 
      arg = strtok(NULL, delims); /* Get next argument */
306
 
    }
307
 
    argp_parse (&argp, new_argc, plus_argv, 0, 0, &plugin_list);  
 
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;
308
643
  }
309
644
  
310
645
  if(debug){
314
649
      for(char **a = p->argv; *a != NULL; a++){
315
650
        fprintf(stderr, "\tArg: %s\n", *a);
316
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
      }
317
656
    }
318
657
  }
319
658
  
 
659
  /* Strip permissions down to nobody */
 
660
  setgid(gid);
 
661
  if(ret == -1){
 
662
    perror("setgid");
 
663
  }
320
664
  ret = setuid(uid);
321
 
  if (ret == -1){
 
665
  if(ret == -1){
322
666
    perror("setuid");
323
667
  }
324
668
  
325
 
  setgid(gid);
326
 
  if (ret == -1){
327
 
    perror("setgid");
 
669
  if(plugindir == NULL){
 
670
    dir = opendir(PDIR);
 
671
  } else {
 
672
    dir = opendir(plugindir);
328
673
  }
329
674
  
330
 
  dir = opendir(plugindir);
331
675
  if(dir == NULL){
332
676
    perror("Could not open plugin dir");
333
677
    exitstatus = EXIT_FAILURE;
334
 
    goto end;
 
678
    goto fallback;
335
679
  }
336
680
  
337
681
  /* Set the FD_CLOEXEC flag on the directory, if possible */
342
686
      if(ret < 0){
343
687
        perror("set_cloexec_flag");
344
688
        exitstatus = EXIT_FAILURE;
345
 
        goto end;
 
689
        goto fallback;
346
690
      }
347
691
    }
348
692
  }
349
693
  
350
694
  FD_ZERO(&rfds_all);
351
695
  
 
696
  /* Read and execute any executable in the plugin directory*/
352
697
  while(true){
353
698
    dirst = readdir(dir);
354
699
    
355
 
    // All directory entries have been processed
 
700
    /* All directory entries have been processed */
356
701
    if(dirst == NULL){
 
702
      if(errno == EBADF){
 
703
        perror("readdir");
 
704
        exitstatus = EXIT_FAILURE;
 
705
        goto fallback;
 
706
      }
357
707
      break;
358
708
    }
359
709
    
360
710
    d_name_len = strlen(dirst->d_name);
361
711
    
362
 
    // Ignore dotfiles, backup files and other junk
 
712
    /* Ignore dotfiles, backup files and other junk */
363
713
    {
364
714
      bool bad_name = false;
365
715
      
367
717
      
368
718
      const char const *bad_suffixes[] = { "~", "#", ".dpkg-new",
369
719
                                           ".dpkg-old",
 
720
                                           ".dpkg-bak",
370
721
                                           ".dpkg-divert", NULL };
371
722
      for(const char **pre = bad_prefixes; *pre != NULL; pre++){
372
723
        size_t pre_len = strlen(*pre);
380
731
          break;
381
732
        }
382
733
      }
383
 
      
384
734
      if(bad_name){
385
735
        continue;
386
736
      }
387
 
      
388
737
      for(const char **suf = bad_suffixes; *suf != NULL; suf++){
389
738
        size_t suf_len = strlen(*suf);
390
739
        if((d_name_len >= suf_len)
403
752
        continue;
404
753
      }
405
754
    }
406
 
    
407
 
    char *filename = malloc(d_name_len + strlen(plugindir) + 2);
408
 
    if (filename == NULL){
409
 
      perror("malloc");
410
 
      exitstatus = EXIT_FAILURE;
411
 
      goto end;
412
 
    }
413
 
    strcpy(filename, plugindir); /* Spurious warning */
414
 
    strcat(filename, "/");      /* Spurious warning */
415
 
    strcat(filename, dirst->d_name); /* Spurious warning */
416
 
    
417
 
    stat(filename, &st);
418
 
    
419
 
    if (not S_ISREG(st.st_mode) or (access(filename, X_OK) != 0)){
 
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)){
420
776
      if(debug){
421
777
        fprintf(stderr, "Ignoring plugin dir entry \"%s\""
422
778
                " with bad type or mode\n", filename);
424
780
      free(filename);
425
781
      continue;
426
782
    }
427
 
    if(getplugin(dirst->d_name, &plugin_list)->disabled){
 
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){
428
791
      if(debug){
429
792
        fprintf(stderr, "Ignoring disabled plugin \"%s\"\n",
430
793
                dirst->d_name);
432
795
      free(filename);
433
796
      continue;
434
797
    }
435
 
    plugin *p = getplugin(dirst->d_name, &plugin_list);
436
798
    {
437
799
      /* Add global arguments to argument list for this plugin */
438
 
      plugin *g = getplugin(NULL, &plugin_list);
439
 
      for(char **a = g->argv + 1; *a != NULL; a++){
440
 
        addargument(p, *a);
441
 
      }
442
 
    }
443
 
    int pipefd[2]; 
 
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];
444
827
    ret = pipe(pipefd);
445
 
    if (ret == -1){
 
828
    if(ret == -1){
446
829
      perror("pipe");
447
830
      exitstatus = EXIT_FAILURE;
448
 
      goto end;
 
831
      goto fallback;
449
832
    }
 
833
    /* Ask OS to automatic close the pipe on exec */
450
834
    ret = set_cloexec_flag(pipefd[0]);
451
835
    if(ret < 0){
452
836
      perror("set_cloexec_flag");
453
837
      exitstatus = EXIT_FAILURE;
454
 
      goto end;
 
838
      goto fallback;
455
839
    }
456
840
    ret = set_cloexec_flag(pipefd[1]);
457
841
    if(ret < 0){
458
842
      perror("set_cloexec_flag");
459
843
      exitstatus = EXIT_FAILURE;
460
 
      goto end;
 
844
      goto fallback;
461
845
    }
462
846
    /* Block SIGCHLD until process is safely in process list */
463
 
    ret = sigprocmask (SIG_BLOCK, &sigchld_action.sa_mask, NULL);
 
847
    ret = sigprocmask(SIG_BLOCK, &sigchld_action.sa_mask, NULL);
464
848
    if(ret < 0){
465
849
      perror("sigprocmask");
466
850
      exitstatus = EXIT_FAILURE;
467
 
      goto end;
 
851
      goto fallback;
468
852
    }
469
 
    // Starting a new process to be watched
 
853
    /* Starting a new process to be watched */
470
854
    pid_t pid = fork();
 
855
    if(pid == -1){
 
856
      perror("fork");
 
857
      exitstatus = EXIT_FAILURE;
 
858
      goto fallback;
 
859
    }
471
860
    if(pid == 0){
472
861
      /* this is the child process */
473
862
      ret = sigaction(SIGCHLD, &old_sigchld_action, NULL);
475
864
        perror("sigaction");
476
865
        _exit(EXIT_FAILURE);
477
866
      }
478
 
      ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
 
867
      ret = sigprocmask(SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
479
868
      if(ret < 0){
480
869
        perror("sigprocmask");
481
870
        _exit(EXIT_FAILURE);
482
871
      }
483
 
      dup2(pipefd[1], STDOUT_FILENO); /* replace our stdout */
 
872
      
 
873
      ret = dup2(pipefd[1], STDOUT_FILENO); /* replace our stdout */
 
874
      if(ret == -1){
 
875
        perror("dup2");
 
876
        _exit(EXIT_FAILURE);
 
877
      }
484
878
      
485
879
      if(dirfd(dir) < 0){
486
880
        /* If dir has no file descriptor, we could not set FD_CLOEXEC
487
881
           above and must now close it manually here. */
488
882
        closedir(dir);
489
883
      }
490
 
      if(execv(filename, p->argv) < 0){
491
 
        perror("execv");
492
 
        _exit(EXIT_FAILURE);
 
884
      if(p->environ[0] == NULL){
 
885
        if(execv(filename, p->argv) < 0){
 
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
        }
493
894
      }
494
895
      /* no return */
495
896
    }
496
 
    /* parent process */
 
897
    /* Parent process */
 
898
    close(pipefd[1]);           /* Close unused write end of pipe */
497
899
    free(filename);
498
 
    close(pipefd[1]);           /* close unused write end of pipe */
499
 
    process *new_process = malloc(sizeof(process));
500
 
    if (new_process == NULL){
501
 
      perror("malloc");
502
 
      ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
 
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);
503
904
      if(ret < 0){
504
 
        perror("sigprocmask");
 
905
        perror("sigprocmask");
505
906
      }
506
907
      exitstatus = EXIT_FAILURE;
507
 
      goto end;
 
908
      goto fallback;
508
909
    }
509
910
    
510
 
    *new_process = (struct process){ .pid = pid,
511
 
                                     .fd = pipefd[0],
512
 
                                     .next = process_list };
513
 
    // List handling
514
 
    process_list = new_process;
 
911
    new_plugin->pid = pid;
 
912
    new_plugin->fd = pipefd[0];
 
913
    
515
914
    /* Unblock SIGCHLD so signal handler can be run if this process
516
915
       has already completed */
517
 
    ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
 
916
    ret = sigprocmask(SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
518
917
    if(ret < 0){
519
918
      perror("sigprocmask");
520
919
      exitstatus = EXIT_FAILURE;
521
 
      goto end;
522
 
    }
523
 
    
524
 
    FD_SET(new_process->fd, &rfds_all);
525
 
    
526
 
    if (maxfd < new_process->fd){
527
 
      maxfd = new_process->fd;
528
 
    }
529
 
    
530
 
  }
531
 
  
532
 
  /* Free the plugin list */
533
 
  for(plugin *next; plugin_list != NULL; plugin_list = next){
534
 
    next = plugin_list->next;
535
 
    free(plugin_list->argv);
536
 
    free(plugin_list);
 
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;
 
927
    }
537
928
  }
538
929
  
539
930
  closedir(dir);
540
931
  dir = NULL;
 
932
  free_plugin(getplugin(NULL));
541
933
  
542
 
  if (process_list == NULL){
543
 
    fprintf(stderr, "No plugin processes started, exiting\n");
544
 
    exitstatus = EXIT_FAILURE;
545
 
    goto end;
 
934
  for(plugin *p = plugin_list; p != NULL; p = p->next){
 
935
    if(p->pid != 0){
 
936
      break;
 
937
    }
 
938
    if(p->next == NULL){
 
939
      fprintf(stderr, "No plugin processes started. Incorrect plugin"
 
940
              " directory?\n");
 
941
      free_plugin_list();
 
942
    }
546
943
  }
547
 
  while(process_list){
 
944
  
 
945
  /* Main loop while running plugins exist */
 
946
  while(plugin_list){
548
947
    fd_set rfds = rfds_all;
549
948
    int select_ret = select(maxfd+1, &rfds, NULL, NULL, NULL);
550
 
    if (select_ret == -1){
 
949
    if(select_ret == -1){
551
950
      perror("select");
552
951
      exitstatus = EXIT_FAILURE;
553
 
      goto end;
 
952
      goto fallback;
554
953
    }
555
954
    /* OK, now either a process completed, or something can be read
556
955
       from one of them */
557
 
    for(process *proc = process_list; proc ; proc = proc->next){
 
956
    for(plugin *proc = plugin_list; proc != NULL;){
558
957
      /* Is this process completely done? */
559
 
      if(proc->eof and proc->completed){
 
958
      if(proc->completed and proc->eof){
560
959
        /* Only accept the plugin output if it exited cleanly */
561
960
        if(not WIFEXITED(proc->status)
562
961
           or WEXITSTATUS(proc->status) != 0){
563
962
          /* Bad exit by plugin */
 
963
 
564
964
          if(debug){
565
965
            if(WIFEXITED(proc->status)){
566
 
              fprintf(stderr, "Plugin %d exited with status %d\n",
567
 
                      proc->pid, WEXITSTATUS(proc->status));
568
 
            } else if(WIFSIGNALED(proc->status)) {
569
 
              fprintf(stderr, "Plugin %d killed by signal %d\n",
570
 
                      proc->pid, WTERMSIG(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));
571
975
            } else if(WCOREDUMP(proc->status)){
572
 
              fprintf(stderr, "Plugin %d dumped core\n", proc->pid);
 
976
              fprintf(stderr, "Plugin %s [%" PRIdMAX "] dumped"
 
977
                      " core\n", proc->name, (intmax_t) (proc->pid));
573
978
            }
574
979
          }
 
980
          
575
981
          /* Remove the plugin */
576
982
          FD_CLR(proc->fd, &rfds_all);
 
983
 
577
984
          /* Block signal while modifying process_list */
578
 
          ret = sigprocmask (SIG_BLOCK, &sigchld_action.sa_mask, NULL);
 
985
          ret = sigprocmask(SIG_BLOCK, &sigchld_action.sa_mask, NULL);
579
986
          if(ret < 0){
580
987
            perror("sigprocmask");
581
988
            exitstatus = EXIT_FAILURE;
582
 
            goto end;
583
 
          }
584
 
          /* Delete this process entry from the list */
585
 
          if(process_list == proc){
586
 
            /* First one - simple */
587
 
            process_list = proc->next;
588
 
          } else {
589
 
            /* Second one or later */
590
 
            for(process *p = process_list; p != NULL; p = p->next){
591
 
              if(p->next == proc){
592
 
                p->next = proc->next;
593
 
                break;
594
 
              }
595
 
            }
596
 
          }
 
989
            goto fallback;
 
990
          }
 
991
          
 
992
          plugin *next_plugin = proc->next;
 
993
          free_plugin(proc);
 
994
          proc = next_plugin;
 
995
          
597
996
          /* We are done modifying process list, so unblock signal */
598
 
          ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask,
599
 
                             NULL);
 
997
          ret = sigprocmask(SIG_UNBLOCK, &sigchld_action.sa_mask,
 
998
                            NULL);
600
999
          if(ret < 0){
601
1000
            perror("sigprocmask");
602
 
          }
603
 
          free(proc->buffer);
604
 
          free(proc);
605
 
          /* We deleted this process from the list, so we can't go
606
 
             proc->next.  Therefore, start over from the beginning of
607
 
             the process list */
608
 
          break;
 
1001
            exitstatus = EXIT_FAILURE;
 
1002
            goto fallback;
 
1003
          }
 
1004
          
 
1005
          if(plugin_list == NULL){
 
1006
            break;
 
1007
          }
 
1008
          
 
1009
          continue;
609
1010
        }
 
1011
        
610
1012
        /* This process exited nicely, so print its buffer */
611
 
        for(size_t written = 0; written < proc->buffer_length;
612
 
            written += (size_t)ret){
613
 
          ret = TEMP_FAILURE_RETRY(write(STDOUT_FILENO,
614
 
                                         proc->buffer + written,
615
 
                                         proc->buffer_length
616
 
                                         - written));
617
 
          if(ret < 0){
618
 
            perror("write");
619
 
            exitstatus = EXIT_FAILURE;
620
 
            goto end;
621
 
          }
 
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;
622
1019
        }
623
 
        goto end;
 
1020
        goto fallback;
624
1021
      }
 
1022
      
625
1023
      /* This process has not completed.  Does it have any output? */
626
1024
      if(proc->eof or not FD_ISSET(proc->fd, &rfds)){
627
1025
        /* This process had nothing to say at this time */
 
1026
        proc = proc->next;
628
1027
        continue;
629
1028
      }
630
1029
      /* Before reading, make the process' data buffer large enough */
631
1030
      if(proc->buffer_length + BUFFER_SIZE > proc->buffer_size){
632
1031
        proc->buffer = realloc(proc->buffer, proc->buffer_size
633
1032
                               + (size_t) BUFFER_SIZE);
634
 
        if (proc->buffer == NULL){
 
1033
        if(proc->buffer == NULL){
635
1034
          perror("malloc");
636
1035
          exitstatus = EXIT_FAILURE;
637
 
          goto end;
 
1036
          goto fallback;
638
1037
        }
639
1038
        proc->buffer_size += BUFFER_SIZE;
640
1039
      }
641
1040
      /* Read from the process */
642
 
      ret = read(proc->fd, proc->buffer + proc->buffer_length,
643
 
                 BUFFER_SIZE);
644
 
      if(ret < 0){
 
1041
      sret = read(proc->fd, proc->buffer + proc->buffer_length,
 
1042
                  BUFFER_SIZE);
 
1043
      if(sret < 0){
645
1044
        /* Read error from this process; ignore the error */
 
1045
        proc = proc->next;
646
1046
        continue;
647
1047
      }
648
 
      if(ret == 0){
 
1048
      if(sret == 0){
649
1049
        /* got EOF */
650
1050
        proc->eof = true;
651
1051
      } else {
652
 
        proc->buffer_length += (size_t) ret;
 
1052
        proc->buffer_length += (size_t) sret;
653
1053
      }
654
1054
    }
655
1055
  }
656
 
  if(process_list == NULL){
657
 
    fprintf(stderr, "All plugin processes failed, exiting\n");
658
 
    exitstatus = EXIT_FAILURE;
 
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
    }
659
1077
  }
660
1078
  
661
 
 end:
662
1079
  /* Restore old signal handler */
663
 
  sigaction(SIGCHLD, &old_sigchld_action, NULL);
664
 
  
665
 
  free(plus_argv);
666
 
  
667
 
  /* Free the plugin list */
668
 
  for(plugin *next; plugin_list != NULL; plugin_list = next){
669
 
    next = plugin_list->next;
670
 
    free(plugin_list->argv);
671
 
    free(plugin_list);
 
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);
672
1091
  }
673
1092
  
674
1093
  if(dir != NULL){
675
1094
    closedir(dir);
676
1095
  }
677
1096
  
678
 
  /* Free the process list and kill the processes */
679
 
  for(process *next; process_list != NULL; process_list = next){
680
 
    next = process_list->next;
681
 
    close(process_list->fd);
682
 
    kill(process_list->pid, SIGTERM);
683
 
    free(process_list->buffer);
684
 
    free(process_list);
 
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
    }
685
1107
  }
686
1108
  
687
1109
  /* Wait for any remaining child processes to terminate */
692
1114
    perror("wait");
693
1115
  }
694
1116
  
 
1117
  free_plugin_list();
 
1118
  
 
1119
  free(plugindir);
 
1120
  free(argfile);
 
1121
  
695
1122
  return exitstatus;
696
1123
}