/mandos/trunk

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

« back to all changes in this revision

Viewing changes to plugin-runner.c

  • Committer: Teddy Hogeborn
  • Date: 2009-10-30 16:23:43 UTC
  • Revision ID: teddy@fukt.bsnet.se-20091030162343-1p2a8bf3gc084kc9
* plugins.d/password-prompt.c: Use environment variables and prompt
                               text from cryptsetup 1.1.
* plugins.d/password-prompt.xml (ENVIRONMENT): Document change in
                                               environment variables
                                               used.

Show diffs side-by-side

added added

removed removed

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