/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 plugbasedclient.c

  • Committer: Teddy Hogeborn
  • Date: 2008-07-29 03:35:39 UTC
  • Revision ID: teddy@fukt.bsnet.se-20080729033539-08zecoj3jwlkpjhw
* server.conf: New file.

* mandos-clients.conf: Renamed to clients.conf.

* Makefile (FORTIFY): New.
  (CFLAGS): Include $(FORTIFY).

* plugins.d/mandosclient.c (main): New "if_index" variable.  Bug fix:
                                   check if interface exists.  New
                                   "--connect" option.

* server.py (serviceInterface): Removed; replaced by
                                "AvahiService.interface".  All users
                                changed.
  (AvahiError, AvahiServiceError, AvahiGroupError): New exception
                                                    classes.
  (AvahiService): New class.
  (serviceName): Removed; replaced by "AvahiService.name".  All users
                 changed.
  (serviceType): Removed; replaced by "AvahiService.type".  All users
                 changed.
  (servicePort): Removed; replaced by "AvahiService.port".  All users
                 changed.
  (serviceTXT): Removed; replaced by "AvahiService.TXT".  All users
                changed.
  (domain): Removed; replaced by "AvahiService.domain".  All users
            changed.
  (host): Removed; replaced by "AvahiService.host".  All users
          changed.
  (rename_count): Removed; replaced by "AvahiService.rename_count" and
                 "AvahiService.max_renames".  All users changed.
  (Client.__init__): If no secret or secfile, raise TypeError instead
                     of RuntimeError.
  (Client.last_seen): Renamed to "Client.last_checked_ok".  All users
                      changed.
  (Client.stop, Client.stop_checker): Use "getattr" with default value
                                      instead of "hasattr".
  (Client.still_valid): Removed "now" argument.
  (Client.handle): Separate the "no client found" and "client invalid"
                   cases for clearer code.
  (IPv6_TCPServer.__init__): "options" argument replaced by
                             "settings".  All callers changed.
  (IPv6_TCPServer.options): Replaced by "IPv6_TCPServer.settings".
                            All users changed.
  (IPv6_TCPServer.server_bind): Use getattr instead of hasattr.
  (add_service): Removed; replaced by "AvahiService.add".  All callers
                 changed.
  (remove_service): Removed; replaced by "AvahiService.remove".  All
                    callers changed.
  (entry_group_state_changed): On entry group collision, call the new
                               AvahiService.rename method.  Raise
                               AvahiGroupError on group error.
  (if_nametoindex): Use ctypes.utils.find_library to locate the C
                    library.  Cache the result.  Loop on EINTR.
  (daemon): Use os.path.devnull to locate "/dev/null".
  (killme): Removed.  All callers changed to do "sys.exit()" instead,
            except where stated otherwise.
  (main): Removed "exitstatus".  Removed all default values from all
          non-bool options.  New option "--configdir".  New variables
          "server_defaults" and "server_settings", read from
          "%(configdir)s/server.conf".  Let any supplied command line
          options override server settings.   Variable "defaults"
          renamed to "client_defaults", which is read from
          "clients.conf" instead of "mandos-clients.conf".  New global
          AvahiService object "service" replaces old global variables.
          Catch AvahiError and exit with error if caught.

Show diffs side-by-side

added added

removed removed

Lines of Context:
21
21
 * Contact the authors at <mandos@fukt.bsnet.se>.
22
22
 */
23
23
 
24
 
#include <stdio.h>              /* popen(), fileno(), fprintf(),
25
 
                                   stderr, STDOUT_FILENO */
26
 
#include <iso646.h>             /* and, or, not */
27
 
#include <sys/types.h>         /* DIR, opendir(), stat(), struct stat,
28
 
                                  waitpid(), WIFEXITED(),
29
 
                                  WEXITSTATUS(), wait() */
30
 
#include <sys/wait.h>           /* wait() */
31
 
#include <dirent.h>             /* DIR, struct dirent, opendir(),
32
 
                                   readdir(), closedir() */
33
 
#include <sys/stat.h>           /* struct stat, stat(), S_ISREG() */
34
 
#include <unistd.h>             /* struct stat, stat(), S_ISREG(),
35
 
                                   fcntl() */
36
 
#include <fcntl.h>              /* fcntl() */
37
 
#include <stddef.h>             /* NULL */
38
 
#include <stdlib.h>             /* EXIT_FAILURE */
39
 
#include <sys/select.h>         /* fd_set, select(), FD_ZERO(),
40
 
                                   FD_SET(), FD_ISSET() */
41
 
#include <string.h>             /* strlen(), strcpy(), strcat() */
42
 
#include <stdbool.h>            /* true */
43
 
#include <sys/wait.h>           /* waitpid(), WIFEXITED(),
44
 
                                   WEXITSTATUS() */
45
 
#include <errno.h>              /* errno */
46
 
#include <argp.h>               /* struct argp_option,
47
 
                                   struct argp_state, struct argp,
48
 
                                   argp_parse() */
 
24
#include <stdio.h>      /* popen, fileno */
 
25
#include <iso646.h>     /* and, or, not */
 
26
#include <sys/types.h>  /* DIR, opendir, stat, struct stat, waitpid,
 
27
                           WIFEXITED, WEXITSTATUS, wait */
 
28
#include <sys/wait.h>   /* wait */
 
29
#include <dirent.h>     /* DIR, opendir */
 
30
#include <sys/stat.h>   /* stat, struct stat */
 
31
#include <unistd.h>     /* stat, struct stat, chdir */
 
32
#include <stdlib.h>     /* EXIT_FAILURE */
 
33
#include <sys/select.h> /* fd_set, select, FD_ZERO, FD_SET,
 
34
                           FD_ISSET */
 
35
#include <string.h>     /* strlen, strcpy, strcat */
 
36
#include <stdbool.h>    /* true */
 
37
#include <sys/wait.h>   /* waitpid, WIFEXITED, WEXITSTATUS */
 
38
#include <errno.h>      /* errno */
 
39
#include <argp.h>       /* argp */
49
40
 
50
41
struct process;
51
42
 
59
50
} process;
60
51
 
61
52
typedef struct plugin{
62
 
  char *name;                   /* can be NULL or any plugin name */
 
53
  char *name;           /* can be "global" and any plugin name */
63
54
  char **argv;
64
55
  int argc;
65
 
  bool disabled;
66
56
  struct plugin *next;
67
57
} plugin;
68
58
 
88
78
  new_plugin->argv[0] = name;
89
79
  new_plugin->argv[1] = NULL;
90
80
  new_plugin->argc = 1;
91
 
  new_plugin->disabled = false;
 
81
  /* Append the new plugin to the list */
92
82
  new_plugin->next = *plugin_list;
93
 
  /* Append the new plugin to the list */
94
83
  *plugin_list = new_plugin;
95
84
  return new_plugin;
96
85
}
97
86
 
98
 
void addargument(plugin *p, char *arg){
 
87
void addarguments(plugin *p, char *arg){
99
88
  p->argv[p->argc] = arg;
100
89
  p->argv = realloc(p->argv, sizeof(char *) * (size_t)(p->argc + 2));
101
90
  if (p->argv == NULL){
105
94
  p->argc++;
106
95
  p->argv[p->argc] = NULL;
107
96
}
108
 
 
109
 
/*
110
 
 * Based on the example in the GNU LibC manual chapter 13.13 "File
111
 
 * Descriptor Flags".
112
 
 * *Note File Descriptor Flags:(libc)Descriptor Flags.
113
 
 */
114
 
int set_cloexec_flag(int fd)
115
 
{
116
 
  int ret = fcntl(fd, F_GETFD, 0);
117
 
  /* If reading the flags failed, return error indication now. */
118
 
  if(ret < 0){
119
 
    return ret;
120
 
  }
121
 
  /* Store modified flag word in the descriptor. */
122
 
  return fcntl(fd, F_SETFD, ret | FD_CLOEXEC);
123
 
}
124
 
 
125
 
 
 
97
        
126
98
#define BUFFER_SIZE 256
127
99
 
128
100
const char *argp_program_version =
129
101
  "plugbasedclient 0.9";
130
102
const char *argp_program_bug_address =
131
103
  "<mandos@fukt.bsnet.se>";
 
104
static char doc[] =
 
105
  "Mandos plugin runner -- Run Mandos plugins";
 
106
/* A description of the arguments we accept. */
 
107
static char args_doc[] = "";
132
108
 
133
109
int main(int argc, char *argv[]){
134
 
  const char *plugindir = "/conf/conf.d/mandos/plugins.d";
135
 
  size_t d_name_len;
 
110
  char plugindir[] = "plugins.d";
 
111
  size_t d_name_len, plugindir_len = sizeof(plugindir)-1;
136
112
  DIR *dir;
137
113
  struct dirent *dirst;
138
114
  struct stat st;
139
 
  fd_set rfds_all;
 
115
  fd_set rfds_orig;
140
116
  int ret, maxfd = 0;
141
117
  process *process_list = NULL;
142
 
  bool debug = false;
143
 
  int exitstatus = EXIT_SUCCESS;
144
118
  
145
119
  /* The options we understand. */
146
120
  struct argp_option options[] = {
147
121
    { .name = "global-options", .key = 'g',
148
 
      .arg = "OPTION[,OPTION[,...]]",
149
 
      .doc = "Options passed to all plugins" },
 
122
      .arg = "option[,option[,...]]", .flags = 0,
 
123
      .doc = "Options effecting all plugins" },
150
124
    { .name = "options-for", .key = 'o',
151
 
      .arg = "PLUGIN:OPTION[,OPTION[,...]]",
152
 
      .doc = "Options passed only to specified plugin" },
153
 
    { .name = "disable", .key = 'd',
154
 
      .arg = "PLUGIN",
155
 
      .doc = "Disable a specific plugin", .group = 1 },
156
 
    { .name = "plugin-dir", .key = 128,
157
 
      .arg = "DIRECTORY",
158
 
      .doc = "Specify a different plugin directory", .group = 2 },
159
 
    { .name = "debug", .key = 129,
160
 
      .doc = "Debug mode", .group = 3 },
 
125
      .arg = "plugin:option[,option[,...]]", .flags = 0,
 
126
      .doc = "Options effecting only specified plugins" },
161
127
    { .name = NULL }
162
128
  };
163
129
  
164
130
  error_t parse_opt (int key, char *arg, struct argp_state *state) {
165
131
       /* Get the INPUT argument from `argp_parse', which we
166
 
          know is a pointer to our plugin list pointer. */
 
132
          know is a pointer to our arguments structure. */
167
133
    plugin **plugins = state->input;
168
134
    switch (key) {
169
135
    case 'g':
170
136
      if (arg != NULL){
171
137
        char *p = strtok(arg, ",");
172
138
        do{
173
 
          addargument(getplugin(NULL, plugins), p);
 
139
          addarguments(getplugin(NULL, plugins), p);
174
140
          p = strtok(NULL, ",");
175
141
        } while (p);
176
142
      }
179
145
      if (arg != NULL){
180
146
        char *name = strtok(arg, ":");
181
147
        char *p = strtok(NULL, ":");
182
 
        if(p){
183
 
          p = strtok(p, ",");
184
 
          do{
185
 
            addargument(getplugin(name, plugins), p);
186
 
            p = strtok(NULL, ",");
187
 
          } while (p);
188
 
        }
189
 
      }
190
 
      break;
191
 
    case 'd':
192
 
      if (arg != NULL){
193
 
        getplugin(arg, plugins)->disabled = true;
194
 
      }
195
 
      break;
196
 
    case 128:
197
 
      plugindir = arg;
198
 
      break;
199
 
    case 129:
200
 
      debug = true;
 
148
        p = strtok(p, ",");
 
149
        do{
 
150
          addarguments(getplugin(name, plugins), p);
 
151
          p = strtok(NULL, ",");
 
152
        } while (p);
 
153
      }
201
154
      break;
202
155
    case ARGP_KEY_ARG:
203
156
      argp_usage (state);
209
162
    }
210
163
    return 0;
211
164
  }
212
 
  
 
165
 
213
166
  plugin *plugin_list = NULL;
214
167
  
215
168
  struct argp argp = { .options = options, .parser = parse_opt,
216
 
                       .args_doc = "",
217
 
                       .doc = "Mandos plugin runner -- Run plugins" };
218
 
  
 
169
                       .args_doc = args_doc, .doc = doc };
 
170
 
219
171
  argp_parse (&argp, argc, argv, 0, 0, &plugin_list);
 
172
 
 
173
/*   for(plugin *p = plugin_list; p != NULL; p=p->next){ */
 
174
/*     fprintf(stderr, "Plugin: %s has %d arguments\n", p->name ? p->name : "Global", p->argc); */
 
175
/*     for(char **a = p->argv + 1; *a != NULL; a++){ */
 
176
/*       fprintf(stderr, "\tArg: %s\n", *a); */
 
177
/*     } */
 
178
/*   } */
220
179
  
221
 
  if(debug){
222
 
    for(plugin *p = plugin_list; p != NULL; p=p->next){
223
 
      fprintf(stderr, "Plugin: %s has %d arguments\n",
224
 
              p->name ? p->name : "Global", p->argc - 1);
225
 
      for(char **a = p->argv; *a != NULL; a++){
226
 
        fprintf(stderr, "\tArg: %s\n", *a);
227
 
      }
228
 
    }
229
 
  }
 
180
/*   return 0; */
230
181
  
231
182
  dir = opendir(plugindir);
232
 
  /* Set the FD_CLOEXEC flag on the directory */
233
 
  ret = set_cloexec_flag(dirfd(dir));
234
 
  if(ret < 0){
235
 
    perror("set_cloexec_flag");
236
 
    goto end;
237
 
  }
238
183
  
239
184
  if(dir == NULL){
240
185
    fprintf(stderr, "Can not open directory\n");
241
186
    return EXIT_FAILURE;
242
187
  }
243
188
  
244
 
  FD_ZERO(&rfds_all);
 
189
  FD_ZERO(&rfds_orig);
245
190
  
246
191
  while(true){
247
192
    dirst = readdir(dir);
253
198
    
254
199
    d_name_len = strlen(dirst->d_name);
255
200
    
256
 
    // Ignore dotfiles, backup files and other junk
257
 
    {
258
 
      bool bad_name = false;
259
 
      
260
 
      const char const *bad_prefixes[] = { ".", "#", NULL };
261
 
      
262
 
      const char const *bad_suffixes[] = { "~", "#", ".dpkg-new",
263
 
                                           ".dpkg-old",
264
 
                                           ".dpkg-divert", NULL };
265
 
      for(const char **pre = bad_prefixes; *pre != NULL; pre++){
266
 
        size_t pre_len = strlen(*pre);
267
 
        if((d_name_len >= pre_len)
268
 
           and strncmp((dirst->d_name), *pre, pre_len) == 0){
269
 
          if(debug){
270
 
            fprintf(stderr, "Ignoring plugin dir entry name \"%s\""
271
 
                    " with bad prefix %s\n", dirst->d_name, *pre);
272
 
          }
273
 
          bad_name = true;
274
 
          break;
275
 
        }
276
 
      }
277
 
      
278
 
      if(bad_name){
279
 
        continue;
280
 
      }
281
 
      
282
 
      for(const char **suf = bad_suffixes; *suf != NULL; suf++){
283
 
        size_t suf_len = strlen(*suf);
284
 
        if((d_name_len >= suf_len)
285
 
           and (strcmp((dirst->d_name)+d_name_len-suf_len, *suf)
286
 
                == 0)){
287
 
          if(debug){
288
 
            fprintf(stderr, "Ignoring plugin dir entry name \"%s\""
289
 
                    " with bad suffix %s\n", dirst->d_name, *suf);
290
 
          }
291
 
          bad_name = true;
292
 
          break;
293
 
        }
294
 
      }
295
 
      
296
 
      if(bad_name){
297
 
        continue;
298
 
      }
299
 
    }
300
 
    
301
 
    char *filename = malloc(d_name_len + strlen(plugindir) + 2);
302
 
    if (filename == NULL){
303
 
      perror("malloc");
304
 
      exitstatus =EXIT_FAILURE;
305
 
      goto end;
306
 
    }
 
201
    // Ignore dotfiles and backup files
 
202
    if (dirst->d_name[0] == '.'
 
203
        or dirst->d_name[d_name_len - 1] == '~'){
 
204
      continue;
 
205
    }
 
206
 
 
207
    char *filename = malloc(d_name_len + plugindir_len + 2);
307
208
    strcpy(filename, plugindir);
308
209
    strcat(filename, "/");
309
210
    strcat(filename, dirst->d_name);    
310
211
 
311
212
    stat(filename, &st);
312
213
 
313
 
    if (not S_ISREG(st.st_mode) or (access(filename, X_OK) != 0)){
314
 
      if(debug){
315
 
        fprintf(stderr, "Ignoring plugin dir entry name \"%s\""
316
 
                " with bad type or mode\n", filename);
317
 
      }
318
 
      continue;
319
 
    }
320
 
    if(getplugin(dirst->d_name, &plugin_list)->disabled){
321
 
      if(debug){
322
 
        fprintf(stderr, "Ignoring disabled plugin \"%s\"",
323
 
                dirst->d_name);
324
 
      }
325
 
      continue;
326
 
    }
327
 
    // Starting a new process to be watched
328
 
    int pipefd[2]; 
329
 
    ret = pipe(pipefd);
330
 
    if (ret == -1){
331
 
      perror(argv[0]);
332
 
      goto end;
333
 
    }
334
 
    plugin *p = getplugin(dirst->d_name, &plugin_list);
335
 
    {
336
 
      /* Add global arguments to argument list for this plugin */
337
 
      plugin *g = getplugin(NULL, &plugin_list);
338
 
      for(char **a = g->argv + 1; *a != NULL; a++){
339
 
        addargument(p, *a);
340
 
      }
341
 
    }
342
 
    pid_t pid = fork();
343
 
    if(pid == 0){
344
 
      /* this is the child process */
345
 
      closedir(dir);
346
 
      close(pipefd[0]); /* close unused read end of pipe */
347
 
      dup2(pipefd[1], STDOUT_FILENO); /* replace our stdout */
348
 
      
349
 
      if(execv(filename, p->argv) < 0){
350
 
        perror(argv[0]);
351
 
        close(pipefd[1]);
352
 
        _exit(EXIT_FAILURE);
353
 
      }
354
 
      /* no return */
355
 
    }
356
 
    close(pipefd[1]);           /* close unused write end of pipe */
357
 
    process *new_process = malloc(sizeof(process));
358
 
    if (new_process == NULL){
359
 
      perror("malloc");
360
 
      exitstatus = EXIT_FAILURE;
361
 
      goto end;
362
 
    }
363
 
    
364
 
    new_process->fd = pipefd[0];
365
 
    new_process->buffer = malloc(BUFFER_SIZE);
366
 
    if (new_process->buffer == NULL){
367
 
      perror("malloc");
368
 
      exitstatus = EXIT_FAILURE;
369
 
      goto end;
370
 
    }
371
 
    new_process->buffer_size = BUFFER_SIZE;
372
 
    new_process->buffer_length = 0;
373
 
    FD_SET(new_process->fd, &rfds_all);
374
 
      
375
 
    if (maxfd < new_process->fd){
376
 
      maxfd = new_process->fd;
377
 
    }
378
 
    
379
 
    //List handling
380
 
    new_process->next = process_list;
381
 
    process_list = new_process;
 
214
    if (S_ISREG(st.st_mode) and (access(filename, X_OK) == 0)){
 
215
      // Starting a new process to be watched
 
216
      process *new_process = malloc(sizeof(process));
 
217
      int pipefd[2];
 
218
      ret = pipe(pipefd);
 
219
      if (ret == -1){
 
220
        perror(argv[0]);
 
221
        goto end;
 
222
      }
 
223
      new_process->pid = fork();
 
224
      if(new_process->pid == 0){
 
225
        /* this is the child process */
 
226
        closedir(dir);
 
227
        close(pipefd[0]);       /* close unused read end of pipe */
 
228
        dup2(pipefd[1], STDOUT_FILENO); /* replace our stdout */
 
229
        char *basename;
 
230
        basename = strrchr(filename, '/');
 
231
        if (basename == NULL){
 
232
          basename = filename;
 
233
        } else {
 
234
          basename++;
 
235
        }
 
236
        plugin *p = getplugin(basename, &plugin_list);
 
237
 
 
238
        plugin *g = getplugin(NULL, &plugin_list);
 
239
        for(char **a = g->argv + 1; *a != NULL; a++){
 
240
          addarguments(p, *a);
 
241
        }
 
242
        if(execv(filename, p->argv) < 0){
 
243
          perror(argv[0]);
 
244
          close(pipefd[1]);
 
245
          exit(EXIT_FAILURE);
 
246
        }
 
247
        /* no return */
 
248
      }
 
249
      close(pipefd[1]);         /* close unused write end of pipe */
 
250
      new_process->fd = pipefd[0];
 
251
      new_process->buffer = malloc(BUFFER_SIZE);
 
252
      if (new_process->buffer == NULL){
 
253
        perror(argv[0]);
 
254
        goto end;
 
255
      }
 
256
      new_process->buffer_size = BUFFER_SIZE;
 
257
      new_process->buffer_length = 0;
 
258
      FD_SET(new_process->fd, &rfds_orig);
 
259
      
 
260
      if (maxfd < new_process->fd){
 
261
        maxfd = new_process->fd;
 
262
      }
 
263
      
 
264
      //List handling
 
265
      new_process->next = process_list;
 
266
      process_list = new_process;
 
267
    }
382
268
  }
383
269
  
384
270
  closedir(dir);
385
271
  
386
272
  if (process_list != NULL){
387
273
    while(true){
388
 
      fd_set rfds = rfds_all;
 
274
      fd_set rfds = rfds_orig;
389
275
      int select_ret = select(maxfd+1, &rfds, NULL, NULL, NULL);
390
276
      if (select_ret == -1){
391
277
        perror(argv[0]);
431
317
                }
432
318
                goto end;
433
319
              } else {
434
 
                FD_CLR(process_itr->fd, &rfds_all);
 
320
                FD_CLR(process_itr->fd, &rfds_orig);
435
321
              }
436
322
            }
437
323
          }
458
344
      break;
459
345
    }
460
346
  }  
461
 
  return exitstatus;
 
347
  return EXIT_SUCCESS;
462
348
}