/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 plugins.d/mandos-client.c

* initramfs-tools-hook: Install network hooks (and any required files)
                        in the initramfs image.
* plugins.d/mandos-client.c (main): Also set MANDOSNETHOOKDIR for
                                    network hooks.
* plugins.d/mandos-client.xml (OPTIONS): Use <filename
                                         class="directory">, not
                                         <directory>.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
/*  -*- coding: utf-8 -*- */
2
2
/*
3
 
 * Mandos client - get and decrypt data from a Mandos server
 
3
 * Mandos-client - get and decrypt data from a Mandos server
4
4
 *
5
5
 * This program is partly derived from an example program for an Avahi
6
6
 * service browser, downloaded from
9
9
 * "browse_callback", and parts of "main".
10
10
 * 
11
11
 * Everything else is
12
 
 * Copyright © 2008,2009 Teddy Hogeborn
13
 
 * Copyright © 2008,2009 Björn Påhlsson
 
12
 * Copyright © 2008-2011 Teddy Hogeborn
 
13
 * Copyright © 2008-2011 Björn Påhlsson
14
14
 * 
15
15
 * This program is free software: you can redistribute it and/or
16
16
 * modify it under the terms of the GNU General Public License as
26
26
 * along with this program.  If not, see
27
27
 * <http://www.gnu.org/licenses/>.
28
28
 * 
29
 
 * Contact the authors at <mandos@fukt.bsnet.se>.
 
29
 * Contact the authors at <mandos@recompile.se>.
30
30
 */
31
31
 
32
32
/* Needed by GPGME, specifically gpgme_data_seek() */
 
33
#ifndef _LARGEFILE_SOURCE
33
34
#define _LARGEFILE_SOURCE
 
35
#endif
 
36
#ifndef _FILE_OFFSET_BITS
34
37
#define _FILE_OFFSET_BITS 64
 
38
#endif
35
39
 
36
40
#define _GNU_SOURCE             /* TEMP_FAILURE_RETRY(), asprintf() */
37
41
 
38
42
#include <stdio.h>              /* fprintf(), stderr, fwrite(),
39
 
                                   stdout, ferror() */
 
43
                                   stdout, ferror(), remove() */
40
44
#include <stdint.h>             /* uint16_t, uint32_t */
41
45
#include <stddef.h>             /* NULL, size_t, ssize_t */
42
 
#include <stdlib.h>             /* free(), EXIT_SUCCESS, EXIT_FAILURE,
43
 
                                   srand() */
44
 
#include <stdbool.h>            /* bool, true */
 
46
#include <stdlib.h>             /* free(), EXIT_SUCCESS, srand(),
 
47
                                   strtof(), abort() */
 
48
#include <stdbool.h>            /* bool, false, true */
45
49
#include <string.h>             /* memset(), strcmp(), strlen(),
46
50
                                   strerror(), asprintf(), strcpy() */
47
 
#include <sys/ioctl.h>          /* ioctl */
 
51
#include <sys/ioctl.h>          /* ioctl */
48
52
#include <sys/types.h>          /* socket(), inet_pton(), sockaddr,
49
53
                                   sockaddr_in6, PF_INET6,
50
 
                                   SOCK_STREAM, INET6_ADDRSTRLEN,
51
 
                                   uid_t, gid_t, open(), opendir(), DIR */
52
 
#include <sys/stat.h>           /* open() */
 
54
                                   SOCK_STREAM, uid_t, gid_t, open(),
 
55
                                   opendir(), DIR */
 
56
#include <sys/stat.h>           /* open(), S_ISREG */
53
57
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
54
 
                                   struct in6_addr, inet_pton(),
55
 
                                   connect() */
 
58
                                   inet_pton(), connect() */
56
59
#include <fcntl.h>              /* open() */
57
 
#include <dirent.h>             /* opendir(), struct dirent, readdir() */
58
 
#include <inttypes.h>           /* PRIu16 */
 
60
#include <dirent.h>             /* opendir(), struct dirent, readdir()
 
61
                                 */
 
62
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
 
63
                                   strtoimax() */
59
64
#include <assert.h>             /* assert() */
60
 
#include <errno.h>              /* perror(), errno */
61
 
#include <time.h>               /* time() */
 
65
#include <errno.h>              /* perror(), errno,
 
66
                                   program_invocation_short_name */
 
67
#include <time.h>               /* nanosleep(), time(), sleep() */
62
68
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
63
69
                                   SIOCSIFFLAGS, if_indextoname(),
64
70
                                   if_nametoindex(), IF_NAMESIZE */
65
 
#include <netinet/in.h>
 
71
#include <netinet/in.h>         /* IN6_IS_ADDR_LINKLOCAL,
 
72
                                   INET_ADDRSTRLEN, INET6_ADDRSTRLEN
 
73
                                */
66
74
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
67
 
                                   getuid(), getgid(), setuid(),
68
 
                                   setgid() */
69
 
#include <arpa/inet.h>          /* inet_pton(), htons */
70
 
#include <iso646.h>             /* not, and */
 
75
                                   getuid(), getgid(), seteuid(),
 
76
                                   setgid(), pause() */
 
77
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
 
78
#include <iso646.h>             /* not, or, and */
71
79
#include <argp.h>               /* struct argp_option, error_t, struct
72
80
                                   argp_state, struct argp,
73
81
                                   argp_parse(), ARGP_KEY_ARG,
74
82
                                   ARGP_KEY_END, ARGP_ERR_UNKNOWN */
 
83
#include <signal.h>             /* sigemptyset(), sigaddset(),
 
84
                                   sigaction(), SIGTERM, sig_atomic_t,
 
85
                                   raise() */
 
86
#include <sysexits.h>           /* EX_OSERR, EX_USAGE, EX_UNAVAILABLE,
 
87
                                   EX_NOHOST, EX_IOERR, EX_PROTOCOL */
 
88
#include <sys/wait.h>           /* waitpid(), WIFEXITED(),
 
89
                                   WEXITSTATUS(), WTERMSIG() */
 
90
 
 
91
#ifdef __linux__
 
92
#include <sys/klog.h>           /* klogctl() */
 
93
#endif  /* __linux__ */
75
94
 
76
95
/* Avahi */
77
96
/* All Avahi types, constants and functions
90
109
                                   gnutls_*
91
110
                                   init_gnutls_session(),
92
111
                                   GNUTLS_* */
93
 
#include <gnutls/openpgp.h>     /* gnutls_certificate_set_openpgp_key_file(),
94
 
                                   GNUTLS_OPENPGP_FMT_BASE64 */
 
112
#include <gnutls/openpgp.h>
 
113
                         /* gnutls_certificate_set_openpgp_key_file(),
 
114
                            GNUTLS_OPENPGP_FMT_BASE64 */
95
115
 
96
116
/* GPGME */
97
117
#include <gpgme.h>              /* All GPGME types, constants and
105
125
#define PATHDIR "/conf/conf.d/mandos"
106
126
#define SECKEY "seckey.txt"
107
127
#define PUBKEY "pubkey.txt"
 
128
#define HOOKDIR "/lib/mandos/network-hooks.d"
108
129
 
109
130
bool debug = false;
110
131
static const char mandos_protocol_version[] = "1";
111
132
const char *argp_program_version = "mandos-client " VERSION;
112
 
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
 
133
const char *argp_program_bug_address = "<mandos@recompile.se>";
 
134
static const char sys_class_net[] = "/sys/class/net";
 
135
char *connect_to = NULL;
 
136
const char *hookdir = HOOKDIR;
 
137
 
 
138
/* Doubly linked list that need to be circularly linked when used */
 
139
typedef struct server{
 
140
  const char *ip;
 
141
  uint16_t port;
 
142
  AvahiIfIndex if_index;
 
143
  int af;
 
144
  struct timespec last_seen;
 
145
  struct server *next;
 
146
  struct server *prev;
 
147
} server;
113
148
 
114
149
/* Used for passing in values through the Avahi callback functions */
115
150
typedef struct {
120
155
  gnutls_dh_params_t dh_params;
121
156
  const char *priority;
122
157
  gpgme_ctx_t ctx;
 
158
  server *current_server;
123
159
} mandos_context;
124
160
 
 
161
/* global context so signal handler can reach it*/
 
162
mandos_context mc = { .simple_poll = NULL, .server = NULL,
 
163
                      .dh_bits = 1024, .priority = "SECURE256"
 
164
                      ":!CTYPE-X.509:+CTYPE-OPENPGP",
 
165
                      .current_server = NULL };
 
166
 
 
167
sig_atomic_t quit_now = 0;
 
168
int signal_received = 0;
 
169
 
 
170
/* Function to use when printing errors */
 
171
void perror_plus(const char *print_text){
 
172
  fprintf(stderr, "Mandos plugin %s: ",
 
173
          program_invocation_short_name);
 
174
  perror(print_text);
 
175
}
 
176
 
125
177
/*
126
 
 * Make room in "buffer" for at least BUFFER_SIZE additional bytes.
127
 
 * "buffer_capacity" is how much is currently allocated,
 
178
 * Make additional room in "buffer" for at least BUFFER_SIZE more
 
179
 * bytes. "buffer_capacity" is how much is currently allocated,
128
180
 * "buffer_length" is how much is already used.
129
181
 */
130
 
size_t adjustbuffer(char **buffer, size_t buffer_length,
131
 
                  size_t buffer_capacity){
132
 
  if (buffer_length + BUFFER_SIZE > buffer_capacity){
 
182
size_t incbuffer(char **buffer, size_t buffer_length,
 
183
                 size_t buffer_capacity){
 
184
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
133
185
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
134
 
    if (buffer == NULL){
 
186
    if(buffer == NULL){
135
187
      return 0;
136
188
    }
137
189
    buffer_capacity += BUFFER_SIZE;
139
191
  return buffer_capacity;
140
192
}
141
193
 
 
194
/* Add server to set of servers to retry periodically */
 
195
int add_server(const char *ip, uint16_t port, AvahiIfIndex if_index,
 
196
               int af){
 
197
  int ret;
 
198
  server *new_server = malloc(sizeof(server));
 
199
  if(new_server == NULL){
 
200
    perror_plus("malloc");
 
201
    return -1;
 
202
  }
 
203
  *new_server = (server){ .ip = strdup(ip),
 
204
                          .port = port,
 
205
                          .if_index = if_index,
 
206
                          .af = af };
 
207
  if(new_server->ip == NULL){
 
208
    perror_plus("strdup");
 
209
    return -1;
 
210
  }
 
211
  /* Special case of first server */
 
212
  if (mc.current_server == NULL){
 
213
    new_server->next = new_server;
 
214
    new_server->prev = new_server;
 
215
    mc.current_server = new_server;
 
216
  /* Place the new server last in the list */
 
217
  } else {
 
218
    new_server->next = mc.current_server;
 
219
    new_server->prev = mc.current_server->prev;
 
220
    new_server->prev->next = new_server;
 
221
    mc.current_server->prev = new_server;
 
222
  }
 
223
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
 
224
  if(ret == -1){
 
225
    perror_plus("clock_gettime");
 
226
    return -1;
 
227
  }
 
228
  return 0;
 
229
}
 
230
 
142
231
/* 
143
232
 * Initialize GPGME.
144
233
 */
145
 
static bool init_gpgme(mandos_context *mc, const char *seckey,
146
 
                       const char *pubkey, const char *tempdir){
147
 
  int ret;
 
234
static bool init_gpgme(const char *seckey, const char *pubkey,
 
235
                       const char *tempdir){
148
236
  gpgme_error_t rc;
149
237
  gpgme_engine_info_t engine_info;
150
238
  
151
239
  
152
240
  /*
153
 
   * Helper function to insert pub and seckey to the enigne keyring.
 
241
   * Helper function to insert pub and seckey to the engine keyring.
154
242
   */
155
243
  bool import_key(const char *filename){
 
244
    int ret;
156
245
    int fd;
157
246
    gpgme_data_t pgp_data;
158
247
    
159
 
    fd = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
 
248
    fd = (int)TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
160
249
    if(fd == -1){
161
 
      perror("open");
 
250
      perror_plus("open");
162
251
      return false;
163
252
    }
164
253
    
165
254
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
166
 
    if (rc != GPG_ERR_NO_ERROR){
167
 
      fprintf(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
168
 
              gpgme_strsource(rc), gpgme_strerror(rc));
169
 
      return false;
170
 
    }
171
 
    
172
 
    rc = gpgme_op_import(mc->ctx, pgp_data);
173
 
    if (rc != GPG_ERR_NO_ERROR){
174
 
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
175
 
              gpgme_strsource(rc), gpgme_strerror(rc));
176
 
      return false;
177
 
    }
178
 
    
179
 
    ret = TEMP_FAILURE_RETRY(close(fd));
 
255
    if(rc != GPG_ERR_NO_ERROR){
 
256
      fprintf(stderr, "Mandos plugin mandos-client: "
 
257
              "bad gpgme_data_new_from_fd: %s: %s\n",
 
258
              gpgme_strsource(rc), gpgme_strerror(rc));
 
259
      return false;
 
260
    }
 
261
    
 
262
    rc = gpgme_op_import(mc.ctx, pgp_data);
 
263
    if(rc != GPG_ERR_NO_ERROR){
 
264
      fprintf(stderr, "Mandos plugin mandos-client: "
 
265
              "bad gpgme_op_import: %s: %s\n",
 
266
              gpgme_strsource(rc), gpgme_strerror(rc));
 
267
      return false;
 
268
    }
 
269
    
 
270
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
180
271
    if(ret == -1){
181
 
      perror("close");
 
272
      perror_plus("close");
182
273
    }
183
274
    gpgme_data_release(pgp_data);
184
275
    return true;
185
276
  }
186
277
  
187
 
  if (debug){
188
 
    fprintf(stderr, "Initialize gpgme\n");
 
278
  if(debug){
 
279
    fprintf(stderr, "Mandos plugin mandos-client: "
 
280
            "Initializing GPGME\n");
189
281
  }
190
282
  
191
283
  /* Init GPGME */
192
284
  gpgme_check_version(NULL);
193
285
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
194
 
  if (rc != GPG_ERR_NO_ERROR){
195
 
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
 
286
  if(rc != GPG_ERR_NO_ERROR){
 
287
    fprintf(stderr, "Mandos plugin mandos-client: "
 
288
            "bad gpgme_engine_check_version: %s: %s\n",
196
289
            gpgme_strsource(rc), gpgme_strerror(rc));
197
290
    return false;
198
291
  }
199
292
  
200
 
    /* Set GPGME home directory for the OpenPGP engine only */
201
 
  rc = gpgme_get_engine_info (&engine_info);
202
 
  if (rc != GPG_ERR_NO_ERROR){
203
 
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
 
293
  /* Set GPGME home directory for the OpenPGP engine only */
 
294
  rc = gpgme_get_engine_info(&engine_info);
 
295
  if(rc != GPG_ERR_NO_ERROR){
 
296
    fprintf(stderr, "Mandos plugin mandos-client: "
 
297
            "bad gpgme_get_engine_info: %s: %s\n",
204
298
            gpgme_strsource(rc), gpgme_strerror(rc));
205
299
    return false;
206
300
  }
213
307
    engine_info = engine_info->next;
214
308
  }
215
309
  if(engine_info == NULL){
216
 
    fprintf(stderr, "Could not set GPGME home dir to %s\n", tempdir);
 
310
    fprintf(stderr, "Mandos plugin mandos-client: "
 
311
            "Could not set GPGME home dir to %s\n", tempdir);
217
312
    return false;
218
313
  }
219
314
  
220
315
  /* Create new GPGME "context" */
221
 
  rc = gpgme_new(&(mc->ctx));
222
 
  if (rc != GPG_ERR_NO_ERROR){
223
 
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
224
 
            gpgme_strsource(rc), gpgme_strerror(rc));
225
 
    return false;
226
 
  }
227
 
  
228
 
  if (not import_key(pubkey) or not import_key(seckey)){
229
 
    return false;
230
 
  }
231
 
  
232
 
  return true; 
 
316
  rc = gpgme_new(&(mc.ctx));
 
317
  if(rc != GPG_ERR_NO_ERROR){
 
318
    fprintf(stderr, "Mandos plugin mandos-client: "
 
319
            "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
 
320
            gpgme_strerror(rc));
 
321
    return false;
 
322
  }
 
323
  
 
324
  if(not import_key(pubkey) or not import_key(seckey)){
 
325
    return false;
 
326
  }
 
327
  
 
328
  return true;
233
329
}
234
330
 
235
331
/* 
236
332
 * Decrypt OpenPGP data.
237
333
 * Returns -1 on error
238
334
 */
239
 
static ssize_t pgp_packet_decrypt (const mandos_context *mc,
240
 
                                   const char *cryptotext,
241
 
                                   size_t crypto_size,
242
 
                                   char **plaintext){
 
335
static ssize_t pgp_packet_decrypt(const char *cryptotext,
 
336
                                  size_t crypto_size,
 
337
                                  char **plaintext){
243
338
  gpgme_data_t dh_crypto, dh_plain;
244
339
  gpgme_error_t rc;
245
340
  ssize_t ret;
246
341
  size_t plaintext_capacity = 0;
247
342
  ssize_t plaintext_length = 0;
248
343
  
249
 
  if (debug){
250
 
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
 
344
  if(debug){
 
345
    fprintf(stderr, "Mandos plugin mandos-client: "
 
346
            "Trying to decrypt OpenPGP data\n");
251
347
  }
252
348
  
253
349
  /* Create new GPGME data buffer from memory cryptotext */
254
350
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
255
351
                               0);
256
 
  if (rc != GPG_ERR_NO_ERROR){
257
 
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
 
352
  if(rc != GPG_ERR_NO_ERROR){
 
353
    fprintf(stderr, "Mandos plugin mandos-client: "
 
354
            "bad gpgme_data_new_from_mem: %s: %s\n",
258
355
            gpgme_strsource(rc), gpgme_strerror(rc));
259
356
    return -1;
260
357
  }
261
358
  
262
359
  /* Create new empty GPGME data buffer for the plaintext */
263
360
  rc = gpgme_data_new(&dh_plain);
264
 
  if (rc != GPG_ERR_NO_ERROR){
265
 
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
 
361
  if(rc != GPG_ERR_NO_ERROR){
 
362
    fprintf(stderr, "Mandos plugin mandos-client: "
 
363
            "bad gpgme_data_new: %s: %s\n",
266
364
            gpgme_strsource(rc), gpgme_strerror(rc));
267
365
    gpgme_data_release(dh_crypto);
268
366
    return -1;
270
368
  
271
369
  /* Decrypt data from the cryptotext data buffer to the plaintext
272
370
     data buffer */
273
 
  rc = gpgme_op_decrypt(mc->ctx, dh_crypto, dh_plain);
274
 
  if (rc != GPG_ERR_NO_ERROR){
275
 
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
 
371
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
 
372
  if(rc != GPG_ERR_NO_ERROR){
 
373
    fprintf(stderr, "Mandos plugin mandos-client: "
 
374
            "bad gpgme_op_decrypt: %s: %s\n",
276
375
            gpgme_strsource(rc), gpgme_strerror(rc));
277
376
    plaintext_length = -1;
278
 
    if (debug){
 
377
    if(debug){
279
378
      gpgme_decrypt_result_t result;
280
 
      result = gpgme_op_decrypt_result(mc->ctx);
281
 
      if (result == NULL){
282
 
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
 
379
      result = gpgme_op_decrypt_result(mc.ctx);
 
380
      if(result == NULL){
 
381
        fprintf(stderr, "Mandos plugin mandos-client: "
 
382
                "gpgme_op_decrypt_result failed\n");
283
383
      } else {
284
 
        fprintf(stderr, "Unsupported algorithm: %s\n",
 
384
        fprintf(stderr, "Mandos plugin mandos-client: "
 
385
                "Unsupported algorithm: %s\n",
285
386
                result->unsupported_algorithm);
286
 
        fprintf(stderr, "Wrong key usage: %u\n",
 
387
        fprintf(stderr, "Mandos plugin mandos-client: "
 
388
                "Wrong key usage: %u\n",
287
389
                result->wrong_key_usage);
288
390
        if(result->file_name != NULL){
289
 
          fprintf(stderr, "File name: %s\n", result->file_name);
 
391
          fprintf(stderr, "Mandos plugin mandos-client: "
 
392
                  "File name: %s\n", result->file_name);
290
393
        }
291
394
        gpgme_recipient_t recipient;
292
395
        recipient = result->recipients;
293
 
        if(recipient){
294
 
          while(recipient != NULL){
295
 
            fprintf(stderr, "Public key algorithm: %s\n",
296
 
                    gpgme_pubkey_algo_name(recipient->pubkey_algo));
297
 
            fprintf(stderr, "Key ID: %s\n", recipient->keyid);
298
 
            fprintf(stderr, "Secret key available: %s\n",
299
 
                    recipient->status == GPG_ERR_NO_SECKEY
300
 
                    ? "No" : "Yes");
301
 
            recipient = recipient->next;
302
 
          }
 
396
        while(recipient != NULL){
 
397
          fprintf(stderr, "Mandos plugin mandos-client: "
 
398
                  "Public key algorithm: %s\n",
 
399
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
 
400
          fprintf(stderr, "Mandos plugin mandos-client: "
 
401
                  "Key ID: %s\n", recipient->keyid);
 
402
          fprintf(stderr, "Mandos plugin mandos-client: "
 
403
                  "Secret key available: %s\n",
 
404
                  recipient->status == GPG_ERR_NO_SECKEY
 
405
                  ? "No" : "Yes");
 
406
          recipient = recipient->next;
303
407
        }
304
408
      }
305
409
    }
307
411
  }
308
412
  
309
413
  if(debug){
310
 
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
 
414
    fprintf(stderr, "Mandos plugin mandos-client: "
 
415
            "Decryption of OpenPGP data succeeded\n");
311
416
  }
312
417
  
313
418
  /* Seek back to the beginning of the GPGME plaintext data buffer */
314
 
  if (gpgme_data_seek(dh_plain, (off_t) 0, SEEK_SET) == -1){
315
 
    perror("gpgme_data_seek");
 
419
  if(gpgme_data_seek(dh_plain, (off_t)0, SEEK_SET) == -1){
 
420
    perror_plus("gpgme_data_seek");
316
421
    plaintext_length = -1;
317
422
    goto decrypt_end;
318
423
  }
319
424
  
320
425
  *plaintext = NULL;
321
426
  while(true){
322
 
    plaintext_capacity = adjustbuffer(plaintext,
323
 
                                      (size_t)plaintext_length,
324
 
                                      plaintext_capacity);
325
 
    if (plaintext_capacity == 0){
326
 
        perror("adjustbuffer");
327
 
        plaintext_length = -1;
328
 
        goto decrypt_end;
 
427
    plaintext_capacity = incbuffer(plaintext,
 
428
                                   (size_t)plaintext_length,
 
429
                                   plaintext_capacity);
 
430
    if(plaintext_capacity == 0){
 
431
      perror_plus("incbuffer");
 
432
      plaintext_length = -1;
 
433
      goto decrypt_end;
329
434
    }
330
435
    
331
436
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
332
437
                          BUFFER_SIZE);
333
438
    /* Print the data, if any */
334
 
    if (ret == 0){
 
439
    if(ret == 0){
335
440
      /* EOF */
336
441
      break;
337
442
    }
338
443
    if(ret < 0){
339
 
      perror("gpgme_data_read");
 
444
      perror_plus("gpgme_data_read");
340
445
      plaintext_length = -1;
341
446
      goto decrypt_end;
342
447
    }
344
449
  }
345
450
  
346
451
  if(debug){
347
 
    fprintf(stderr, "Decrypted password is: ");
 
452
    fprintf(stderr, "Mandos plugin mandos-client: "
 
453
            "Decrypted password is: ");
348
454
    for(ssize_t i = 0; i < plaintext_length; i++){
349
455
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
350
456
    }
361
467
  return plaintext_length;
362
468
}
363
469
 
364
 
static const char * safer_gnutls_strerror (int value) {
365
 
  const char *ret = gnutls_strerror (value); /* Spurious warning */
366
 
  if (ret == NULL)
 
470
static const char * safer_gnutls_strerror(int value){
 
471
  const char *ret = gnutls_strerror(value); /* Spurious warning from
 
472
                                               -Wunreachable-code */
 
473
  if(ret == NULL)
367
474
    ret = "(unknown)";
368
475
  return ret;
369
476
}
371
478
/* GnuTLS log function callback */
372
479
static void debuggnutls(__attribute__((unused)) int level,
373
480
                        const char* string){
374
 
  fprintf(stderr, "GnuTLS: %s", string);
 
481
  fprintf(stderr, "Mandos plugin mandos-client: GnuTLS: %s", string);
375
482
}
376
483
 
377
 
static int init_gnutls_global(mandos_context *mc,
378
 
                              const char *pubkeyfilename,
 
484
static int init_gnutls_global(const char *pubkeyfilename,
379
485
                              const char *seckeyfilename){
380
486
  int ret;
381
487
  
382
488
  if(debug){
383
 
    fprintf(stderr, "Initializing GnuTLS\n");
 
489
    fprintf(stderr, "Mandos plugin mandos-client: "
 
490
            "Initializing GnuTLS\n");
384
491
  }
385
492
  
386
493
  ret = gnutls_global_init();
387
 
  if (ret != GNUTLS_E_SUCCESS) {
388
 
    fprintf (stderr, "GnuTLS global_init: %s\n",
389
 
             safer_gnutls_strerror(ret));
 
494
  if(ret != GNUTLS_E_SUCCESS){
 
495
    fprintf(stderr, "Mandos plugin mandos-client: "
 
496
            "GnuTLS global_init: %s\n", safer_gnutls_strerror(ret));
390
497
    return -1;
391
498
  }
392
499
  
393
 
  if (debug){
 
500
  if(debug){
394
501
    /* "Use a log level over 10 to enable all debugging options."
395
502
     * - GnuTLS manual
396
503
     */
399
506
  }
400
507
  
401
508
  /* OpenPGP credentials */
402
 
  gnutls_certificate_allocate_credentials(&mc->cred);
403
 
  if (ret != GNUTLS_E_SUCCESS){
404
 
    fprintf (stderr, "GnuTLS memory error: %s\n", /* Spurious
405
 
                                                     warning */
406
 
             safer_gnutls_strerror(ret));
407
 
    gnutls_global_deinit ();
 
509
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
 
510
  if(ret != GNUTLS_E_SUCCESS){
 
511
    fprintf(stderr, "Mandos plugin mandos-client: "
 
512
            "GnuTLS memory error: %s\n", safer_gnutls_strerror(ret));
 
513
    gnutls_global_deinit();
408
514
    return -1;
409
515
  }
410
516
  
411
517
  if(debug){
412
 
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
 
518
    fprintf(stderr, "Mandos plugin mandos-client: "
 
519
            "Attempting to use OpenPGP public key %s and"
413
520
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
414
521
            seckeyfilename);
415
522
  }
416
523
  
417
524
  ret = gnutls_certificate_set_openpgp_key_file
418
 
    (mc->cred, pubkeyfilename, seckeyfilename,
 
525
    (mc.cred, pubkeyfilename, seckeyfilename,
419
526
     GNUTLS_OPENPGP_FMT_BASE64);
420
 
  if (ret != GNUTLS_E_SUCCESS) {
 
527
  if(ret != GNUTLS_E_SUCCESS){
421
528
    fprintf(stderr,
 
529
            "Mandos plugin mandos-client: "
422
530
            "Error[%d] while reading the OpenPGP key pair ('%s',"
423
531
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
424
 
    fprintf(stderr, "The GnuTLS error is: %s\n",
425
 
            safer_gnutls_strerror(ret));
 
532
    fprintf(stderr, "Mandos plugin mandos-client: "
 
533
            "The GnuTLS error is: %s\n", safer_gnutls_strerror(ret));
426
534
    goto globalfail;
427
535
  }
428
536
  
429
537
  /* GnuTLS server initialization */
430
 
  ret = gnutls_dh_params_init(&mc->dh_params);
431
 
  if (ret != GNUTLS_E_SUCCESS) {
432
 
    fprintf (stderr, "Error in GnuTLS DH parameter initialization:"
433
 
             " %s\n", safer_gnutls_strerror(ret));
 
538
  ret = gnutls_dh_params_init(&mc.dh_params);
 
539
  if(ret != GNUTLS_E_SUCCESS){
 
540
    fprintf(stderr, "Mandos plugin mandos-client: "
 
541
            "Error in GnuTLS DH parameter initialization:"
 
542
            " %s\n", safer_gnutls_strerror(ret));
434
543
    goto globalfail;
435
544
  }
436
 
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
437
 
  if (ret != GNUTLS_E_SUCCESS) {
438
 
    fprintf (stderr, "Error in GnuTLS prime generation: %s\n",
439
 
             safer_gnutls_strerror(ret));
 
545
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
 
546
  if(ret != GNUTLS_E_SUCCESS){
 
547
    fprintf(stderr, "Mandos plugin mandos-client: "
 
548
            "Error in GnuTLS prime generation: %s\n",
 
549
            safer_gnutls_strerror(ret));
440
550
    goto globalfail;
441
551
  }
442
552
  
443
 
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
 
553
  gnutls_certificate_set_dh_params(mc.cred, mc.dh_params);
444
554
  
445
555
  return 0;
446
556
  
447
557
 globalfail:
448
558
  
449
 
  gnutls_certificate_free_credentials(mc->cred);
 
559
  gnutls_certificate_free_credentials(mc.cred);
450
560
  gnutls_global_deinit();
451
 
  gnutls_dh_params_deinit(mc->dh_params);
 
561
  gnutls_dh_params_deinit(mc.dh_params);
452
562
  return -1;
453
563
}
454
564
 
455
 
static int init_gnutls_session(mandos_context *mc,
456
 
                               gnutls_session_t *session){
 
565
static int init_gnutls_session(gnutls_session_t *session){
457
566
  int ret;
458
567
  /* GnuTLS session creation */
459
 
  ret = gnutls_init(session, GNUTLS_SERVER);
460
 
  if (ret != GNUTLS_E_SUCCESS){
461
 
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
 
568
  do {
 
569
    ret = gnutls_init(session, GNUTLS_SERVER);
 
570
    if(quit_now){
 
571
      return -1;
 
572
    }
 
573
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
 
574
  if(ret != GNUTLS_E_SUCCESS){
 
575
    fprintf(stderr, "Mandos plugin mandos-client: "
 
576
            "Error in GnuTLS session initialization: %s\n",
462
577
            safer_gnutls_strerror(ret));
463
578
  }
464
579
  
465
580
  {
466
581
    const char *err;
467
 
    ret = gnutls_priority_set_direct(*session, mc->priority, &err);
468
 
    if (ret != GNUTLS_E_SUCCESS) {
469
 
      fprintf(stderr, "Syntax error at: %s\n", err);
470
 
      fprintf(stderr, "GnuTLS error: %s\n",
471
 
              safer_gnutls_strerror(ret));
472
 
      gnutls_deinit (*session);
 
582
    do {
 
583
      ret = gnutls_priority_set_direct(*session, mc.priority, &err);
 
584
      if(quit_now){
 
585
        gnutls_deinit(*session);
 
586
        return -1;
 
587
      }
 
588
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
 
589
    if(ret != GNUTLS_E_SUCCESS){
 
590
      fprintf(stderr, "Mandos plugin mandos-client: "
 
591
              "Syntax error at: %s\n", err);
 
592
      fprintf(stderr, "Mandos plugin mandos-client: "
 
593
              "GnuTLS error: %s\n", safer_gnutls_strerror(ret));
 
594
      gnutls_deinit(*session);
473
595
      return -1;
474
596
    }
475
597
  }
476
598
  
477
 
  ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
478
 
                               mc->cred);
479
 
  if (ret != GNUTLS_E_SUCCESS) {
480
 
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
 
599
  do {
 
600
    ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
 
601
                                 mc.cred);
 
602
    if(quit_now){
 
603
      gnutls_deinit(*session);
 
604
      return -1;
 
605
    }
 
606
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
 
607
  if(ret != GNUTLS_E_SUCCESS){
 
608
    fprintf(stderr, "Mandos plugin mandos-client: "
 
609
            "Error setting GnuTLS credentials: %s\n",
481
610
            safer_gnutls_strerror(ret));
482
 
    gnutls_deinit (*session);
 
611
    gnutls_deinit(*session);
483
612
    return -1;
484
613
  }
485
614
  
486
615
  /* ignore client certificate if any. */
487
 
  gnutls_certificate_server_set_request (*session,
488
 
                                         GNUTLS_CERT_IGNORE);
 
616
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
489
617
  
490
 
  gnutls_dh_set_prime_bits (*session, mc->dh_bits);
 
618
  gnutls_dh_set_prime_bits(*session, mc.dh_bits);
491
619
  
492
620
  return 0;
493
621
}
499
627
/* Called when a Mandos server is found */
500
628
static int start_mandos_communication(const char *ip, uint16_t port,
501
629
                                      AvahiIfIndex if_index,
502
 
                                      mandos_context *mc){
503
 
  int ret, tcp_sd;
504
 
  union { struct sockaddr in; struct sockaddr_in6 in6; } to;
 
630
                                      int af){
 
631
  int ret, tcp_sd = -1;
 
632
  ssize_t sret;
 
633
  union {
 
634
    struct sockaddr_in in;
 
635
    struct sockaddr_in6 in6;
 
636
  } to;
505
637
  char *buffer = NULL;
506
 
  char *decrypted_buffer;
 
638
  char *decrypted_buffer = NULL;
507
639
  size_t buffer_length = 0;
508
640
  size_t buffer_capacity = 0;
509
 
  ssize_t decrypted_buffer_size;
510
641
  size_t written;
511
 
  int retval = 0;
512
 
  char interface[IF_NAMESIZE];
 
642
  int retval = -1;
513
643
  gnutls_session_t session;
514
 
  
515
 
  ret = init_gnutls_session (mc, &session);
516
 
  if (ret != 0){
 
644
  int pf;                       /* Protocol family */
 
645
  
 
646
  errno = 0;
 
647
  
 
648
  if(quit_now){
 
649
    errno = EINTR;
 
650
    return -1;
 
651
  }
 
652
  
 
653
  switch(af){
 
654
  case AF_INET6:
 
655
    pf = PF_INET6;
 
656
    break;
 
657
  case AF_INET:
 
658
    pf = PF_INET;
 
659
    break;
 
660
  default:
 
661
    fprintf(stderr, "Mandos plugin mandos-client: "
 
662
            "Bad address family: %d\n", af);
 
663
    errno = EINVAL;
 
664
    return -1;
 
665
  }
 
666
  
 
667
  ret = init_gnutls_session(&session);
 
668
  if(ret != 0){
517
669
    return -1;
518
670
  }
519
671
  
520
672
  if(debug){
521
 
    fprintf(stderr, "Setting up a tcp connection to %s, port %" PRIu16
 
673
    fprintf(stderr, "Mandos plugin mandos-client: "
 
674
            "Setting up a TCP connection to %s, port %" PRIu16
522
675
            "\n", ip, port);
523
676
  }
524
677
  
525
 
  tcp_sd = socket(PF_INET6, SOCK_STREAM, 0);
526
 
  if(tcp_sd < 0) {
527
 
    perror("socket");
528
 
    return -1;
 
678
  tcp_sd = socket(pf, SOCK_STREAM, 0);
 
679
  if(tcp_sd < 0){
 
680
    int e = errno;
 
681
    perror_plus("socket");
 
682
    errno = e;
 
683
    goto mandos_end;
529
684
  }
530
685
  
531
 
  if(debug){
532
 
    if(if_indextoname((unsigned int)if_index, interface) == NULL){
533
 
      perror("if_indextoname");
534
 
      return -1;
535
 
    }
536
 
    fprintf(stderr, "Binding to interface %s\n", interface);
 
686
  if(quit_now){
 
687
    errno = EINTR;
 
688
    goto mandos_end;
537
689
  }
538
690
  
539
691
  memset(&to, 0, sizeof(to));
540
 
  to.in6.sin6_family = AF_INET6;
541
 
  /* It would be nice to have a way to detect if we were passed an
542
 
     IPv4 address here.   Now we assume an IPv6 address. */
543
 
  ret = inet_pton(AF_INET6, ip, &to.in6.sin6_addr);
544
 
  if (ret < 0 ){
545
 
    perror("inet_pton");
546
 
    return -1;
 
692
  if(af == AF_INET6){
 
693
    to.in6.sin6_family = (sa_family_t)af;
 
694
    ret = inet_pton(af, ip, &to.in6.sin6_addr);
 
695
  } else {                      /* IPv4 */
 
696
    to.in.sin_family = (sa_family_t)af;
 
697
    ret = inet_pton(af, ip, &to.in.sin_addr);
 
698
  }
 
699
  if(ret < 0 ){
 
700
    int e = errno;
 
701
    perror_plus("inet_pton");
 
702
    errno = e;
 
703
    goto mandos_end;
547
704
  }
548
705
  if(ret == 0){
549
 
    fprintf(stderr, "Bad address: %s\n", ip);
550
 
    return -1;
551
 
  }
552
 
  to.in6.sin6_port = htons(port); /* Spurious warning */
 
706
    int e = errno;
 
707
    fprintf(stderr, "Mandos plugin mandos-client: "
 
708
            "Bad address: %s\n", ip);
 
709
    errno = e;
 
710
    goto mandos_end;
 
711
  }
 
712
  if(af == AF_INET6){
 
713
    to.in6.sin6_port = htons(port); /* Spurious warnings from
 
714
                                       -Wconversion and
 
715
                                       -Wunreachable-code */
 
716
    
 
717
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
 
718
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
 
719
                                -Wunreachable-code*/
 
720
      if(if_index == AVAHI_IF_UNSPEC){
 
721
        fprintf(stderr, "Mandos plugin mandos-client: "
 
722
                "An IPv6 link-local address is incomplete"
 
723
                " without a network interface\n");
 
724
        errno = EINVAL;
 
725
        goto mandos_end;
 
726
      }
 
727
      /* Set the network interface number as scope */
 
728
      to.in6.sin6_scope_id = (uint32_t)if_index;
 
729
    }
 
730
  } else {
 
731
    to.in.sin_port = htons(port); /* Spurious warnings from
 
732
                                     -Wconversion and
 
733
                                     -Wunreachable-code */
 
734
  }
553
735
  
554
 
  to.in6.sin6_scope_id = (uint32_t)if_index;
 
736
  if(quit_now){
 
737
    errno = EINTR;
 
738
    goto mandos_end;
 
739
  }
555
740
  
556
741
  if(debug){
557
 
    fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
558
 
            port);
559
 
    char addrstr[INET6_ADDRSTRLEN] = "";
560
 
    if(inet_ntop(to.in6.sin6_family, &(to.in6.sin6_addr), addrstr,
561
 
                 sizeof(addrstr)) == NULL){
562
 
      perror("inet_ntop");
 
742
    if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
 
743
      char interface[IF_NAMESIZE];
 
744
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
 
745
        perror_plus("if_indextoname");
 
746
      } else {
 
747
        fprintf(stderr, "Mandos plugin mandos-client: "
 
748
                "Connection to: %s%%%s, port %" PRIu16 "\n",
 
749
                ip, interface, port);
 
750
      }
 
751
    } else {
 
752
      fprintf(stderr, "Mandos plugin mandos-client: "
 
753
              "Connection to: %s, port %" PRIu16 "\n", ip, port);
 
754
    }
 
755
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
 
756
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
 
757
    const char *pcret;
 
758
    if(af == AF_INET6){
 
759
      pcret = inet_ntop(af, &(to.in6.sin6_addr), addrstr,
 
760
                        sizeof(addrstr));
 
761
    } else {
 
762
      pcret = inet_ntop(af, &(to.in.sin_addr), addrstr,
 
763
                        sizeof(addrstr));
 
764
    }
 
765
    if(pcret == NULL){
 
766
      perror_plus("inet_ntop");
563
767
    } else {
564
768
      if(strcmp(addrstr, ip) != 0){
565
 
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
 
769
        fprintf(stderr, "Mandos plugin mandos-client: "
 
770
                "Canonical address form: %s\n", addrstr);
566
771
      }
567
772
    }
568
773
  }
569
774
  
570
 
  ret = connect(tcp_sd, &to.in, sizeof(to));
571
 
  if (ret < 0){
572
 
    perror("connect");
573
 
    return -1;
 
775
  if(quit_now){
 
776
    errno = EINTR;
 
777
    goto mandos_end;
 
778
  }
 
779
  
 
780
  if(af == AF_INET6){
 
781
    ret = connect(tcp_sd, &to.in6, sizeof(to));
 
782
  } else {
 
783
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
 
784
  }
 
785
  if(ret < 0){
 
786
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
 
787
      int e = errno;
 
788
      perror_plus("connect");
 
789
      errno = e;
 
790
    }
 
791
    goto mandos_end;
 
792
  }
 
793
  
 
794
  if(quit_now){
 
795
    errno = EINTR;
 
796
    goto mandos_end;
574
797
  }
575
798
  
576
799
  const char *out = mandos_protocol_version;
577
800
  written = 0;
578
 
  while (true){
 
801
  while(true){
579
802
    size_t out_size = strlen(out);
580
 
    ret = TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
581
 
                                   out_size - written));
582
 
    if (ret == -1){
583
 
      perror("write");
584
 
      retval = -1;
 
803
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
 
804
                                        out_size - written));
 
805
    if(ret == -1){
 
806
      int e = errno;
 
807
      perror_plus("write");
 
808
      errno = e;
585
809
      goto mandos_end;
586
810
    }
587
811
    written += (size_t)ret;
588
812
    if(written < out_size){
589
813
      continue;
590
814
    } else {
591
 
      if (out == mandos_protocol_version){
 
815
      if(out == mandos_protocol_version){
592
816
        written = 0;
593
817
        out = "\r\n";
594
818
      } else {
595
819
        break;
596
820
      }
597
821
    }
 
822
  
 
823
    if(quit_now){
 
824
      errno = EINTR;
 
825
      goto mandos_end;
 
826
    }
598
827
  }
599
828
  
600
829
  if(debug){
601
 
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
602
 
  }
603
 
  
604
 
  gnutls_transport_set_ptr (session, (gnutls_transport_ptr_t) tcp_sd);
605
 
  
606
 
  do{
607
 
    ret = gnutls_handshake (session);
 
830
    fprintf(stderr, "Mandos plugin mandos-client: "
 
831
            "Establishing TLS session with %s\n", ip);
 
832
  }
 
833
  
 
834
  if(quit_now){
 
835
    errno = EINTR;
 
836
    goto mandos_end;
 
837
  }
 
838
  
 
839
  /* Spurious warning from -Wint-to-pointer-cast */
 
840
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
 
841
  
 
842
  if(quit_now){
 
843
    errno = EINTR;
 
844
    goto mandos_end;
 
845
  }
 
846
  
 
847
  do {
 
848
    ret = gnutls_handshake(session);
 
849
    if(quit_now){
 
850
      errno = EINTR;
 
851
      goto mandos_end;
 
852
    }
608
853
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
609
854
  
610
 
  if (ret != GNUTLS_E_SUCCESS){
 
855
  if(ret != GNUTLS_E_SUCCESS){
611
856
    if(debug){
612
 
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
613
 
      gnutls_perror (ret);
 
857
      fprintf(stderr, "Mandos plugin mandos-client: "
 
858
              "*** GnuTLS Handshake failed ***\n");
 
859
      gnutls_perror(ret);
614
860
    }
615
 
    retval = -1;
 
861
    errno = EPROTO;
616
862
    goto mandos_end;
617
863
  }
618
864
  
619
865
  /* Read OpenPGP packet that contains the wanted password */
620
866
  
621
867
  if(debug){
622
 
    fprintf(stderr, "Retrieving pgp encrypted password from %s\n",
623
 
            ip);
 
868
    fprintf(stderr, "Mandos plugin mandos-client: "
 
869
            "Retrieving OpenPGP encrypted password from %s\n", ip);
624
870
  }
625
871
  
626
872
  while(true){
627
 
    buffer_capacity = adjustbuffer(&buffer, buffer_length,
628
 
                                   buffer_capacity);
629
 
    if (buffer_capacity == 0){
630
 
      perror("adjustbuffer");
631
 
      retval = -1;
632
 
      goto mandos_end;
633
 
    }
634
 
    
635
 
    ret = gnutls_record_recv(session, buffer+buffer_length,
636
 
                             BUFFER_SIZE);
637
 
    if (ret == 0){
 
873
    
 
874
    if(quit_now){
 
875
      errno = EINTR;
 
876
      goto mandos_end;
 
877
    }
 
878
    
 
879
    buffer_capacity = incbuffer(&buffer, buffer_length,
 
880
                                buffer_capacity);
 
881
    if(buffer_capacity == 0){
 
882
      int e = errno;
 
883
      perror_plus("incbuffer");
 
884
      errno = e;
 
885
      goto mandos_end;
 
886
    }
 
887
    
 
888
    if(quit_now){
 
889
      errno = EINTR;
 
890
      goto mandos_end;
 
891
    }
 
892
    
 
893
    sret = gnutls_record_recv(session, buffer+buffer_length,
 
894
                              BUFFER_SIZE);
 
895
    if(sret == 0){
638
896
      break;
639
897
    }
640
 
    if (ret < 0){
641
 
      switch(ret){
 
898
    if(sret < 0){
 
899
      switch(sret){
642
900
      case GNUTLS_E_INTERRUPTED:
643
901
      case GNUTLS_E_AGAIN:
644
902
        break;
645
903
      case GNUTLS_E_REHANDSHAKE:
646
 
        do{
647
 
          ret = gnutls_handshake (session);
 
904
        do {
 
905
          ret = gnutls_handshake(session);
 
906
          
 
907
          if(quit_now){
 
908
            errno = EINTR;
 
909
            goto mandos_end;
 
910
          }
648
911
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
649
 
        if (ret < 0){
650
 
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
651
 
          gnutls_perror (ret);
652
 
          retval = -1;
 
912
        if(ret < 0){
 
913
          fprintf(stderr, "Mandos plugin mandos-client: "
 
914
                  "*** GnuTLS Re-handshake failed ***\n");
 
915
          gnutls_perror(ret);
 
916
          errno = EPROTO;
653
917
          goto mandos_end;
654
918
        }
655
919
        break;
656
920
      default:
657
 
        fprintf(stderr, "Unknown error while reading data from"
 
921
        fprintf(stderr, "Mandos plugin mandos-client: "
 
922
                "Unknown error while reading data from"
658
923
                " encrypted session with Mandos server\n");
659
 
        retval = -1;
660
 
        gnutls_bye (session, GNUTLS_SHUT_RDWR);
 
924
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
 
925
        errno = EIO;
661
926
        goto mandos_end;
662
927
      }
663
928
    } else {
664
 
      buffer_length += (size_t) ret;
 
929
      buffer_length += (size_t) sret;
665
930
    }
666
931
  }
667
932
  
668
933
  if(debug){
669
 
    fprintf(stderr, "Closing TLS session\n");
670
 
  }
671
 
  
672
 
  gnutls_bye (session, GNUTLS_SHUT_RDWR);
673
 
  
674
 
  if (buffer_length > 0){
675
 
    decrypted_buffer_size = pgp_packet_decrypt(mc, buffer,
676
 
                                               buffer_length,
 
934
    fprintf(stderr, "Mandos plugin mandos-client: "
 
935
            "Closing TLS session\n");
 
936
  }
 
937
  
 
938
  if(quit_now){
 
939
    errno = EINTR;
 
940
    goto mandos_end;
 
941
  }
 
942
  
 
943
  do {
 
944
    ret = gnutls_bye(session, GNUTLS_SHUT_RDWR);
 
945
    if(quit_now){
 
946
      errno = EINTR;
 
947
      goto mandos_end;
 
948
    }
 
949
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
 
950
  
 
951
  if(buffer_length > 0){
 
952
    ssize_t decrypted_buffer_size;
 
953
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
677
954
                                               &decrypted_buffer);
678
 
    if (decrypted_buffer_size >= 0){
 
955
    if(decrypted_buffer_size >= 0){
 
956
      
679
957
      written = 0;
680
958
      while(written < (size_t) decrypted_buffer_size){
681
 
        ret = (int)fwrite (decrypted_buffer + written, 1,
682
 
                           (size_t)decrypted_buffer_size - written,
683
 
                           stdout);
 
959
        if(quit_now){
 
960
          errno = EINTR;
 
961
          goto mandos_end;
 
962
        }
 
963
        
 
964
        ret = (int)fwrite(decrypted_buffer + written, 1,
 
965
                          (size_t)decrypted_buffer_size - written,
 
966
                          stdout);
684
967
        if(ret == 0 and ferror(stdout)){
 
968
          int e = errno;
685
969
          if(debug){
686
 
            fprintf(stderr, "Error writing encrypted data: %s\n",
 
970
            fprintf(stderr, "Mandos plugin mandos-client: "
 
971
                    "Error writing encrypted data: %s\n",
687
972
                    strerror(errno));
688
973
          }
689
 
          retval = -1;
690
 
          break;
 
974
          errno = e;
 
975
          goto mandos_end;
691
976
        }
692
977
        written += (size_t)ret;
693
978
      }
694
 
      free(decrypted_buffer);
695
 
    } else {
696
 
      retval = -1;
 
979
      retval = 0;
697
980
    }
698
 
  } else {
699
 
    retval = -1;
700
981
  }
701
982
  
702
983
  /* Shutdown procedure */
703
984
  
704
985
 mandos_end:
705
 
  free(buffer);
706
 
  ret = TEMP_FAILURE_RETRY(close(tcp_sd));
707
 
  if(ret == -1){
708
 
    perror("close");
 
986
  {
 
987
    int e = errno;
 
988
    free(decrypted_buffer);
 
989
    free(buffer);
 
990
    if(tcp_sd >= 0){
 
991
      ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
 
992
    }
 
993
    if(ret == -1){
 
994
      if(e == 0){
 
995
        e = errno;
 
996
      }
 
997
      perror_plus("close");
 
998
    }
 
999
    gnutls_deinit(session);
 
1000
    errno = e;
 
1001
    if(quit_now){
 
1002
      errno = EINTR;
 
1003
      retval = -1;
 
1004
    }
709
1005
  }
710
 
  gnutls_deinit (session);
711
1006
  return retval;
712
1007
}
713
1008
 
714
1009
static void resolve_callback(AvahiSServiceResolver *r,
715
1010
                             AvahiIfIndex interface,
716
 
                             AVAHI_GCC_UNUSED AvahiProtocol protocol,
 
1011
                             AvahiProtocol proto,
717
1012
                             AvahiResolverEvent event,
718
1013
                             const char *name,
719
1014
                             const char *type,
724
1019
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
725
1020
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
726
1021
                             flags,
727
 
                             void* userdata) {
728
 
  mandos_context *mc = userdata;
 
1022
                             AVAHI_GCC_UNUSED void* userdata){
729
1023
  assert(r);
730
1024
  
731
1025
  /* Called whenever a service has been resolved successfully or
732
1026
     timed out */
733
1027
  
734
 
  switch (event) {
 
1028
  if(quit_now){
 
1029
    return;
 
1030
  }
 
1031
  
 
1032
  switch(event){
735
1033
  default:
736
1034
  case AVAHI_RESOLVER_FAILURE:
737
 
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
 
1035
    fprintf(stderr, "Mandos plugin mandos-client: "
 
1036
            "(Avahi Resolver) Failed to resolve service '%s'"
738
1037
            " of type '%s' in domain '%s': %s\n", name, type, domain,
739
 
            avahi_strerror(avahi_server_errno(mc->server)));
 
1038
            avahi_strerror(avahi_server_errno(mc.server)));
740
1039
    break;
741
1040
    
742
1041
  case AVAHI_RESOLVER_FOUND:
744
1043
      char ip[AVAHI_ADDRESS_STR_MAX];
745
1044
      avahi_address_snprint(ip, sizeof(ip), address);
746
1045
      if(debug){
747
 
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %"
748
 
                PRIu16 ") on port %d\n", name, host_name, ip,
749
 
                interface, port);
 
1046
        fprintf(stderr, "Mandos plugin mandos-client: "
 
1047
                "Mandos server \"%s\" found on %s (%s, %"
 
1048
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
 
1049
                ip, (intmax_t)interface, port);
750
1050
      }
751
 
      int ret = start_mandos_communication(ip, port, interface, mc);
752
 
      if (ret == 0){
753
 
        avahi_simple_poll_quit(mc->simple_poll);
 
1051
      int ret = start_mandos_communication(ip, port, interface,
 
1052
                                           avahi_proto_to_af(proto));
 
1053
      if(ret == 0){
 
1054
        avahi_simple_poll_quit(mc.simple_poll);
 
1055
      } else {
 
1056
        ret = add_server(ip, port, interface,
 
1057
                         avahi_proto_to_af(proto));
754
1058
      }
755
1059
    }
756
1060
  }
757
1061
  avahi_s_service_resolver_free(r);
758
1062
}
759
1063
 
760
 
static void browse_callback( AvahiSServiceBrowser *b,
761
 
                             AvahiIfIndex interface,
762
 
                             AvahiProtocol protocol,
763
 
                             AvahiBrowserEvent event,
764
 
                             const char *name,
765
 
                             const char *type,
766
 
                             const char *domain,
767
 
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
768
 
                             flags,
769
 
                             void* userdata) {
770
 
  mandos_context *mc = userdata;
 
1064
static void browse_callback(AvahiSServiceBrowser *b,
 
1065
                            AvahiIfIndex interface,
 
1066
                            AvahiProtocol protocol,
 
1067
                            AvahiBrowserEvent event,
 
1068
                            const char *name,
 
1069
                            const char *type,
 
1070
                            const char *domain,
 
1071
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
 
1072
                            flags,
 
1073
                            AVAHI_GCC_UNUSED void* userdata){
771
1074
  assert(b);
772
1075
  
773
1076
  /* Called whenever a new services becomes available on the LAN or
774
1077
     is removed from the LAN */
775
1078
  
776
 
  switch (event) {
 
1079
  if(quit_now){
 
1080
    return;
 
1081
  }
 
1082
  
 
1083
  switch(event){
777
1084
  default:
778
1085
  case AVAHI_BROWSER_FAILURE:
779
1086
    
780
 
    fprintf(stderr, "(Avahi browser) %s\n",
781
 
            avahi_strerror(avahi_server_errno(mc->server)));
782
 
    avahi_simple_poll_quit(mc->simple_poll);
 
1087
    fprintf(stderr, "Mandos plugin mandos-client: "
 
1088
            "(Avahi browser) %s\n",
 
1089
            avahi_strerror(avahi_server_errno(mc.server)));
 
1090
    avahi_simple_poll_quit(mc.simple_poll);
783
1091
    return;
784
1092
    
785
1093
  case AVAHI_BROWSER_NEW:
788
1096
       the callback function is called the Avahi server will free the
789
1097
       resolver for us. */
790
1098
    
791
 
    if (!(avahi_s_service_resolver_new(mc->server, interface,
792
 
                                       protocol, name, type, domain,
793
 
                                       AVAHI_PROTO_INET6, 0,
794
 
                                       resolve_callback, mc)))
795
 
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
796
 
              name, avahi_strerror(avahi_server_errno(mc->server)));
 
1099
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
 
1100
                                    name, type, domain, protocol, 0,
 
1101
                                    resolve_callback, NULL) == NULL)
 
1102
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1103
              "Avahi: Failed to resolve service '%s': %s\n",
 
1104
              name, avahi_strerror(avahi_server_errno(mc.server)));
797
1105
    break;
798
1106
    
799
1107
  case AVAHI_BROWSER_REMOVE:
802
1110
  case AVAHI_BROWSER_ALL_FOR_NOW:
803
1111
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
804
1112
    if(debug){
805
 
      fprintf(stderr, "No Mandos server found, still searching...\n");
 
1113
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1114
              "No Mandos server found, still searching...\n");
806
1115
    }
807
1116
    break;
808
1117
  }
809
1118
}
810
1119
 
 
1120
/* Signal handler that stops main loop after SIGTERM */
 
1121
static void handle_sigterm(int sig){
 
1122
  if(quit_now){
 
1123
    return;
 
1124
  }
 
1125
  quit_now = 1;
 
1126
  signal_received = sig;
 
1127
  int old_errno = errno;
 
1128
  /* set main loop to exit */
 
1129
  if(mc.simple_poll != NULL){
 
1130
    avahi_simple_poll_quit(mc.simple_poll);
 
1131
  }
 
1132
  errno = old_errno;
 
1133
}
 
1134
 
 
1135
bool get_flags(const char *ifname, struct ifreq *ifr){
 
1136
  int ret;
 
1137
  
 
1138
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1139
  if(s < 0){
 
1140
    perror_plus("socket");
 
1141
    return false;
 
1142
  }
 
1143
  strcpy(ifr->ifr_name, ifname);
 
1144
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
 
1145
  if(ret == -1){
 
1146
    if(debug){
 
1147
      perror_plus("ioctl SIOCGIFFLAGS");
 
1148
    }
 
1149
    return false;
 
1150
  }
 
1151
  return true;
 
1152
}
 
1153
 
 
1154
bool good_flags(const char *ifname, const struct ifreq *ifr){
 
1155
  
 
1156
  /* Reject the loopback device */
 
1157
  if(ifr->ifr_flags & IFF_LOOPBACK){
 
1158
    if(debug){
 
1159
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1160
              "Rejecting loopback interface \"%s\"\n", ifname);
 
1161
    }
 
1162
    return false;
 
1163
  }
 
1164
  /* Accept point-to-point devices only if connect_to is specified */
 
1165
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
 
1166
    if(debug){
 
1167
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1168
              "Accepting point-to-point interface \"%s\"\n", ifname);
 
1169
    }
 
1170
    return true;
 
1171
  }
 
1172
  /* Otherwise, reject non-broadcast-capable devices */
 
1173
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
 
1174
    if(debug){
 
1175
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1176
              "Rejecting non-broadcast interface \"%s\"\n", ifname);
 
1177
    }
 
1178
    return false;
 
1179
  }
 
1180
  /* Reject non-ARP interfaces (including dummy interfaces) */
 
1181
  if(ifr->ifr_flags & IFF_NOARP){
 
1182
    if(debug){
 
1183
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1184
              "Rejecting non-ARP interface \"%s\"\n", ifname);
 
1185
    }
 
1186
    return false;
 
1187
  }
 
1188
  
 
1189
  /* Accept this device */
 
1190
  if(debug){
 
1191
    fprintf(stderr, "Mandos plugin mandos-client: "
 
1192
            "Interface \"%s\" is good\n", ifname);
 
1193
  }
 
1194
  return true;
 
1195
}
 
1196
 
 
1197
/* 
 
1198
 * This function determines if a directory entry in /sys/class/net
 
1199
 * corresponds to an acceptable network device.
 
1200
 * (This function is passed to scandir(3) as a filter function.)
 
1201
 */
 
1202
int good_interface(const struct dirent *if_entry){
 
1203
  if(if_entry->d_name[0] == '.'){
 
1204
    return 0;
 
1205
  }
 
1206
  
 
1207
  struct ifreq ifr;
 
1208
  if(not get_flags(if_entry->d_name, &ifr)){
 
1209
    if(debug){
 
1210
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1211
              "Failed to get flags for interface \"%s\"\n",
 
1212
              if_entry->d_name);
 
1213
    }
 
1214
    return 0;
 
1215
  }
 
1216
  
 
1217
  if(not good_flags(if_entry->d_name, &ifr)){
 
1218
    return 0;
 
1219
  }
 
1220
  return 1;
 
1221
}
 
1222
 
 
1223
/* 
 
1224
 * This function determines if a directory entry in /sys/class/net
 
1225
 * corresponds to an acceptable network device which is up.
 
1226
 * (This function is passed to scandir(3) as a filter function.)
 
1227
 */
 
1228
int up_interface(const struct dirent *if_entry){
 
1229
  if(if_entry->d_name[0] == '.'){
 
1230
    return 0;
 
1231
  }
 
1232
  
 
1233
  struct ifreq ifr;
 
1234
  if(not get_flags(if_entry->d_name, &ifr)){
 
1235
    if(debug){
 
1236
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1237
              "Failed to get flags for interface \"%s\"\n",
 
1238
              if_entry->d_name);
 
1239
    }
 
1240
    return 0;
 
1241
  }
 
1242
  
 
1243
  /* Reject down interfaces */
 
1244
  if(not (ifr.ifr_flags & IFF_UP)){
 
1245
    if(debug){
 
1246
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1247
              "Rejecting down interface \"%s\"\n",
 
1248
              if_entry->d_name);
 
1249
    }
 
1250
    return 0;
 
1251
  }
 
1252
  
 
1253
  /* Reject non-running interfaces */
 
1254
  if(not (ifr.ifr_flags & IFF_RUNNING)){
 
1255
    if(debug){
 
1256
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1257
              "Rejecting non-running interface \"%s\"\n",
 
1258
              if_entry->d_name);
 
1259
    }
 
1260
    return 0;
 
1261
  }
 
1262
  
 
1263
  if(not good_flags(if_entry->d_name, &ifr)){
 
1264
    return 0;
 
1265
  }
 
1266
  return 1;
 
1267
}
 
1268
 
 
1269
int notdotentries(const struct dirent *direntry){
 
1270
  /* Skip "." and ".." */
 
1271
  if(direntry->d_name[0] == '.'
 
1272
     and (direntry->d_name[1] == '\0'
 
1273
          or (direntry->d_name[1] == '.'
 
1274
              and direntry->d_name[2] == '\0'))){
 
1275
    return 0;
 
1276
  }
 
1277
  return 1;
 
1278
}
 
1279
 
 
1280
/* Is this directory entry a runnable program? */
 
1281
int runnable_hook(const struct dirent *direntry){
 
1282
  int ret;
 
1283
  size_t sret;
 
1284
  struct stat st;
 
1285
  
 
1286
  if((direntry->d_name)[0] == '\0'){
 
1287
    /* Empty name? */
 
1288
    return 0;
 
1289
  }
 
1290
  
 
1291
  sret = strspn(direntry->d_name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
 
1292
                "abcdefghijklmnopqrstuvwxyz"
 
1293
                "0123456789"
 
1294
                "_-");
 
1295
  if((direntry->d_name)[sret] != '\0'){
 
1296
    /* Contains non-allowed characters */
 
1297
    if(debug){
 
1298
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1299
              "Ignoring hook \"%s\" with bad name\n",
 
1300
              direntry->d_name);
 
1301
    }
 
1302
    return 0;
 
1303
  }
 
1304
  
 
1305
  char *fullname = NULL;
 
1306
  ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
 
1307
  if(ret < 0){
 
1308
    perror_plus("asprintf");
 
1309
    return 0;
 
1310
  }
 
1311
  
 
1312
  ret = stat(fullname, &st);
 
1313
  if(ret == -1){
 
1314
    if(debug){
 
1315
      perror_plus("Could not stat hook");
 
1316
    }
 
1317
    return 0;
 
1318
  }
 
1319
  if(not (S_ISREG(st.st_mode))){
 
1320
    /* Not a regular file */
 
1321
    if(debug){
 
1322
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1323
              "Ignoring hook \"%s\" - not a file\n",
 
1324
              direntry->d_name);
 
1325
    }
 
1326
    return 0;
 
1327
  }
 
1328
  if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
 
1329
    /* Not executable */
 
1330
    if(debug){
 
1331
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1332
              "Ignoring hook \"%s\" - not executable\n",
 
1333
              direntry->d_name);
 
1334
    }
 
1335
    return 0;
 
1336
  }
 
1337
  return 1;
 
1338
}
 
1339
 
 
1340
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
 
1341
  int ret;
 
1342
  struct timespec now;
 
1343
  struct timespec waited_time;
 
1344
  intmax_t block_time;
 
1345
  
 
1346
  while(true){
 
1347
    if(mc.current_server == NULL){
 
1348
      if (debug){
 
1349
        fprintf(stderr, "Mandos plugin mandos-client: "
 
1350
                "Wait until first server is found. No timeout!\n");
 
1351
      }
 
1352
      ret = avahi_simple_poll_iterate(s, -1);
 
1353
    } else {
 
1354
      if (debug){
 
1355
        fprintf(stderr, "Mandos plugin mandos-client: "
 
1356
                "Check current_server if we should run it,"
 
1357
                " or wait\n");
 
1358
      }
 
1359
      /* the current time */
 
1360
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
 
1361
      if(ret == -1){
 
1362
        perror_plus("clock_gettime");
 
1363
        return -1;
 
1364
      }
 
1365
      /* Calculating in ms how long time between now and server
 
1366
         who we visted longest time ago. Now - last seen.  */
 
1367
      waited_time.tv_sec = (now.tv_sec
 
1368
                            - mc.current_server->last_seen.tv_sec);
 
1369
      waited_time.tv_nsec = (now.tv_nsec
 
1370
                             - mc.current_server->last_seen.tv_nsec);
 
1371
      /* total time is 10s/10,000ms.
 
1372
         Converting to s from ms by dividing by 1,000,
 
1373
         and ns to ms by dividing by 1,000,000. */
 
1374
      block_time = ((retry_interval
 
1375
                     - ((intmax_t)waited_time.tv_sec * 1000))
 
1376
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
 
1377
      
 
1378
      if (debug){
 
1379
        fprintf(stderr, "Mandos plugin mandos-client: "
 
1380
                "Blocking for %" PRIdMAX " ms\n", block_time);
 
1381
      }
 
1382
      
 
1383
      if(block_time <= 0){
 
1384
        ret = start_mandos_communication(mc.current_server->ip,
 
1385
                                         mc.current_server->port,
 
1386
                                         mc.current_server->if_index,
 
1387
                                         mc.current_server->af);
 
1388
        if(ret == 0){
 
1389
          avahi_simple_poll_quit(mc.simple_poll);
 
1390
          return 0;
 
1391
        }
 
1392
        ret = clock_gettime(CLOCK_MONOTONIC,
 
1393
                            &mc.current_server->last_seen);
 
1394
        if(ret == -1){
 
1395
          perror_plus("clock_gettime");
 
1396
          return -1;
 
1397
        }
 
1398
        mc.current_server = mc.current_server->next;
 
1399
        block_time = 0;         /* Call avahi to find new Mandos
 
1400
                                   servers, but don't block */
 
1401
      }
 
1402
      
 
1403
      ret = avahi_simple_poll_iterate(s, (int)block_time);
 
1404
    }
 
1405
    if(ret != 0){
 
1406
      if (ret > 0 or errno != EINTR){
 
1407
        return (ret != 1) ? ret : 0;
 
1408
      }
 
1409
    }
 
1410
  }
 
1411
}
 
1412
 
811
1413
int main(int argc, char *argv[]){
812
 
    AvahiSServiceBrowser *sb = NULL;
813
 
    int error;
814
 
    int ret;
815
 
    int exitcode = EXIT_SUCCESS;
816
 
    const char *interface = "eth0";
817
 
    struct ifreq network;
818
 
    int sd;
819
 
    uid_t uid;
820
 
    gid_t gid;
821
 
    char *connect_to = NULL;
822
 
    char tempdir[] = "/tmp/mandosXXXXXX";
823
 
    AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
824
 
    const char *seckey = PATHDIR "/" SECKEY;
825
 
    const char *pubkey = PATHDIR "/" PUBKEY;
826
 
    
827
 
    mandos_context mc = { .simple_poll = NULL, .server = NULL,
828
 
                          .dh_bits = 1024, .priority = "SECURE256"
829
 
                          ":!CTYPE-X.509:+CTYPE-OPENPGP" };
830
 
    bool gnutls_initalized = false;
831
 
    bool gpgme_initalized = false;
832
 
    
833
 
    {
834
 
      struct argp_option options[] = {
835
 
        { .name = "debug", .key = 128,
836
 
          .doc = "Debug mode", .group = 3 },
837
 
        { .name = "connect", .key = 'c',
838
 
          .arg = "ADDRESS:PORT",
839
 
          .doc = "Connect directly to a specific Mandos server",
840
 
          .group = 1 },
841
 
        { .name = "interface", .key = 'i',
842
 
          .arg = "NAME",
843
 
          .doc = "Interface that will be used to search for Mandos"
844
 
          " servers",
845
 
          .group = 1 },
846
 
        { .name = "seckey", .key = 's',
847
 
          .arg = "FILE",
848
 
          .doc = "OpenPGP secret key file base name",
849
 
          .group = 1 },
850
 
        { .name = "pubkey", .key = 'p',
851
 
          .arg = "FILE",
852
 
          .doc = "OpenPGP public key file base name",
853
 
          .group = 2 },
854
 
        { .name = "dh-bits", .key = 129,
855
 
          .arg = "BITS",
856
 
          .doc = "Bit length of the prime number used in the"
857
 
          " Diffie-Hellman key exchange",
858
 
          .group = 2 },
859
 
        { .name = "priority", .key = 130,
860
 
          .arg = "STRING",
861
 
          .doc = "GnuTLS priority string for the TLS handshake",
862
 
          .group = 1 },
863
 
        { .name = NULL }
864
 
      };
865
 
      
866
 
      error_t parse_opt (int key, char *arg,
867
 
                         struct argp_state *state) {
868
 
        /* Get the INPUT argument from `argp_parse', which we know is
869
 
           a pointer to our plugin list pointer. */
870
 
        switch (key) {
871
 
        case 128:               /* --debug */
872
 
          debug = true;
873
 
          break;
874
 
        case 'c':               /* --connect */
875
 
          connect_to = arg;
876
 
          break;
877
 
        case 'i':               /* --interface */
878
 
          interface = arg;
879
 
          break;
880
 
        case 's':               /* --seckey */
881
 
          seckey = arg;
882
 
          break;
883
 
        case 'p':               /* --pubkey */
884
 
          pubkey = arg;
885
 
          break;
886
 
        case 129:               /* --dh-bits */
887
 
          errno = 0;
888
 
          mc.dh_bits = (unsigned int) strtol(arg, NULL, 10);
889
 
          if (errno){
890
 
            perror("strtol");
891
 
            exit(EXIT_FAILURE);
892
 
          }
893
 
          break;
894
 
        case 130:               /* --priority */
895
 
          mc.priority = arg;
896
 
          break;
897
 
        case ARGP_KEY_ARG:
898
 
          argp_usage (state);
899
 
        case ARGP_KEY_END:
900
 
          break;
901
 
        default:
902
 
          return ARGP_ERR_UNKNOWN;
903
 
        }
904
 
        return 0;
905
 
      }
906
 
      
907
 
      struct argp argp = { .options = options, .parser = parse_opt,
908
 
                           .args_doc = "",
909
 
                           .doc = "Mandos client -- Get and decrypt"
910
 
                           " passwords from a Mandos server" };
911
 
      ret = argp_parse (&argp, argc, argv, 0, 0, NULL);
912
 
      if (ret == ARGP_ERR_UNKNOWN){
913
 
        fprintf(stderr, "Unknown error while parsing arguments\n");
914
 
        exitcode = EXIT_FAILURE;
915
 
        goto end;
916
 
      }
917
 
    }
918
 
    
919
 
    /* If the interface is down, bring it up */
920
 
    {
921
 
      sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
922
 
      if(sd < 0) {
923
 
        perror("socket");
924
 
        exitcode = EXIT_FAILURE;
925
 
        goto end;
926
 
      }
927
 
      strcpy(network.ifr_name, interface);
928
 
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
929
 
      if(ret == -1){
930
 
        perror("ioctl SIOCGIFFLAGS");
931
 
        exitcode = EXIT_FAILURE;
932
 
        goto end;
933
 
      }
934
 
      if((network.ifr_flags & IFF_UP) == 0){
935
 
        network.ifr_flags |= IFF_UP;
936
 
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
937
 
        if(ret == -1){
938
 
          perror("ioctl SIOCSIFFLAGS");
939
 
          exitcode = EXIT_FAILURE;
 
1414
  AvahiSServiceBrowser *sb = NULL;
 
1415
  int error;
 
1416
  int ret;
 
1417
  intmax_t tmpmax;
 
1418
  char *tmp;
 
1419
  int exitcode = EXIT_SUCCESS;
 
1420
  const char *interface = "";
 
1421
  struct ifreq network;
 
1422
  int sd = -1;
 
1423
  bool take_down_interface = false;
 
1424
  uid_t uid;
 
1425
  gid_t gid;
 
1426
  char tempdir[] = "/tmp/mandosXXXXXX";
 
1427
  bool tempdir_created = false;
 
1428
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
 
1429
  const char *seckey = PATHDIR "/" SECKEY;
 
1430
  const char *pubkey = PATHDIR "/" PUBKEY;
 
1431
  
 
1432
  bool gnutls_initialized = false;
 
1433
  bool gpgme_initialized = false;
 
1434
  float delay = 2.5f;
 
1435
  double retry_interval = 10; /* 10s between trying a server and
 
1436
                                 retrying the same server again */
 
1437
  
 
1438
  struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
 
1439
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
 
1440
  
 
1441
  uid = getuid();
 
1442
  gid = getgid();
 
1443
  
 
1444
  /* Lower any group privileges we might have, just to be safe */
 
1445
  errno = 0;
 
1446
  ret = setgid(gid);
 
1447
  if(ret == -1){
 
1448
    perror_plus("setgid");
 
1449
  }
 
1450
  
 
1451
  /* Lower user privileges (temporarily) */
 
1452
  errno = 0;
 
1453
  ret = seteuid(uid);
 
1454
  if(ret == -1){
 
1455
    perror_plus("seteuid");
 
1456
  }
 
1457
  
 
1458
  if(quit_now){
 
1459
    goto end;
 
1460
  }
 
1461
  
 
1462
  {
 
1463
    struct argp_option options[] = {
 
1464
      { .name = "debug", .key = 128,
 
1465
        .doc = "Debug mode", .group = 3 },
 
1466
      { .name = "connect", .key = 'c',
 
1467
        .arg = "ADDRESS:PORT",
 
1468
        .doc = "Connect directly to a specific Mandos server",
 
1469
        .group = 1 },
 
1470
      { .name = "interface", .key = 'i',
 
1471
        .arg = "NAME",
 
1472
        .doc = "Network interface that will be used to search for"
 
1473
        " Mandos servers",
 
1474
        .group = 1 },
 
1475
      { .name = "seckey", .key = 's',
 
1476
        .arg = "FILE",
 
1477
        .doc = "OpenPGP secret key file base name",
 
1478
        .group = 1 },
 
1479
      { .name = "pubkey", .key = 'p',
 
1480
        .arg = "FILE",
 
1481
        .doc = "OpenPGP public key file base name",
 
1482
        .group = 2 },
 
1483
      { .name = "dh-bits", .key = 129,
 
1484
        .arg = "BITS",
 
1485
        .doc = "Bit length of the prime number used in the"
 
1486
        " Diffie-Hellman key exchange",
 
1487
        .group = 2 },
 
1488
      { .name = "priority", .key = 130,
 
1489
        .arg = "STRING",
 
1490
        .doc = "GnuTLS priority string for the TLS handshake",
 
1491
        .group = 1 },
 
1492
      { .name = "delay", .key = 131,
 
1493
        .arg = "SECONDS",
 
1494
        .doc = "Maximum delay to wait for interface startup",
 
1495
        .group = 2 },
 
1496
      { .name = "retry", .key = 132,
 
1497
        .arg = "SECONDS",
 
1498
        .doc = "Retry interval used when denied by the mandos server",
 
1499
        .group = 2 },
 
1500
      { .name = "network-hook-dir", .key = 133,
 
1501
        .arg = "DIR",
 
1502
        .doc = "Directory where network hooks are located",
 
1503
        .group = 2 },
 
1504
      /*
 
1505
       * These reproduce what we would get without ARGP_NO_HELP
 
1506
       */
 
1507
      { .name = "help", .key = '?',
 
1508
        .doc = "Give this help list", .group = -1 },
 
1509
      { .name = "usage", .key = -3,
 
1510
        .doc = "Give a short usage message", .group = -1 },
 
1511
      { .name = "version", .key = 'V',
 
1512
        .doc = "Print program version", .group = -1 },
 
1513
      { .name = NULL }
 
1514
    };
 
1515
    
 
1516
    error_t parse_opt(int key, char *arg,
 
1517
                      struct argp_state *state){
 
1518
      errno = 0;
 
1519
      switch(key){
 
1520
      case 128:                 /* --debug */
 
1521
        debug = true;
 
1522
        break;
 
1523
      case 'c':                 /* --connect */
 
1524
        connect_to = arg;
 
1525
        break;
 
1526
      case 'i':                 /* --interface */
 
1527
        interface = arg;
 
1528
        break;
 
1529
      case 's':                 /* --seckey */
 
1530
        seckey = arg;
 
1531
        break;
 
1532
      case 'p':                 /* --pubkey */
 
1533
        pubkey = arg;
 
1534
        break;
 
1535
      case 129:                 /* --dh-bits */
 
1536
        errno = 0;
 
1537
        tmpmax = strtoimax(arg, &tmp, 10);
 
1538
        if(errno != 0 or tmp == arg or *tmp != '\0'
 
1539
           or tmpmax != (typeof(mc.dh_bits))tmpmax){
 
1540
          argp_error(state, "Bad number of DH bits");
 
1541
        }
 
1542
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
 
1543
        break;
 
1544
      case 130:                 /* --priority */
 
1545
        mc.priority = arg;
 
1546
        break;
 
1547
      case 131:                 /* --delay */
 
1548
        errno = 0;
 
1549
        delay = strtof(arg, &tmp);
 
1550
        if(errno != 0 or tmp == arg or *tmp != '\0'){
 
1551
          argp_error(state, "Bad delay");
 
1552
        }
 
1553
      case 132:                 /* --retry */
 
1554
        errno = 0;
 
1555
        retry_interval = strtod(arg, &tmp);
 
1556
        if(errno != 0 or tmp == arg or *tmp != '\0'
 
1557
           or (retry_interval * 1000) > INT_MAX
 
1558
           or retry_interval < 0){
 
1559
          argp_error(state, "Bad retry interval");
 
1560
        }
 
1561
        break;
 
1562
      case 133:                 /* --network-hook-dir */
 
1563
        hookdir = arg;
 
1564
        break;
 
1565
        /*
 
1566
         * These reproduce what we would get without ARGP_NO_HELP
 
1567
         */
 
1568
      case '?':                 /* --help */
 
1569
        argp_state_help(state, state->out_stream,
 
1570
                        (ARGP_HELP_STD_HELP | ARGP_HELP_EXIT_ERR)
 
1571
                        & ~(unsigned int)ARGP_HELP_EXIT_OK);
 
1572
      case -3:                  /* --usage */
 
1573
        argp_state_help(state, state->out_stream,
 
1574
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
 
1575
      case 'V':                 /* --version */
 
1576
        fprintf(state->out_stream, "Mandos plugin mandos-client: ");
 
1577
        fprintf(state->out_stream, "%s\n", argp_program_version);
 
1578
        exit(argp_err_exit_status);
 
1579
        break;
 
1580
      default:
 
1581
        return ARGP_ERR_UNKNOWN;
 
1582
      }
 
1583
      return errno;
 
1584
    }
 
1585
    
 
1586
    struct argp argp = { .options = options, .parser = parse_opt,
 
1587
                         .args_doc = "",
 
1588
                         .doc = "Mandos client -- Get and decrypt"
 
1589
                         " passwords from a Mandos server" };
 
1590
    ret = argp_parse(&argp, argc, argv,
 
1591
                     ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
 
1592
    switch(ret){
 
1593
    case 0:
 
1594
      break;
 
1595
    case ENOMEM:
 
1596
    default:
 
1597
      errno = ret;
 
1598
      perror_plus("argp_parse");
 
1599
      exitcode = EX_OSERR;
 
1600
      goto end;
 
1601
    case EINVAL:
 
1602
      exitcode = EX_USAGE;
 
1603
      goto end;
 
1604
    }
 
1605
  }
 
1606
    
 
1607
  {
 
1608
    /* Work around Debian bug #633582:
 
1609
       <http://bugs.debian.org/633582> */
 
1610
    struct stat st;
 
1611
    
 
1612
    /* Re-raise priviliges */
 
1613
    errno = 0;
 
1614
    ret = seteuid(0);
 
1615
    if(ret == -1){
 
1616
      perror_plus("seteuid");
 
1617
    }
 
1618
    
 
1619
    if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
 
1620
      int seckey_fd = open(seckey, O_RDONLY);
 
1621
      if(seckey_fd == -1){
 
1622
        perror_plus("open");
 
1623
      } else {
 
1624
        ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
 
1625
        if(ret == -1){
 
1626
          perror_plus("fstat");
 
1627
        } else {
 
1628
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
 
1629
            ret = fchown(seckey_fd, uid, gid);
 
1630
            if(ret == -1){
 
1631
              perror_plus("fchown");
 
1632
            }
 
1633
          }
 
1634
        }
 
1635
        TEMP_FAILURE_RETRY(close(seckey_fd));
 
1636
      }
 
1637
    }
 
1638
    
 
1639
    if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
 
1640
      int pubkey_fd = open(pubkey, O_RDONLY);
 
1641
      if(pubkey_fd == -1){
 
1642
        perror_plus("open");
 
1643
      } else {
 
1644
        ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
 
1645
        if(ret == -1){
 
1646
          perror_plus("fstat");
 
1647
        } else {
 
1648
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
 
1649
            ret = fchown(pubkey_fd, uid, gid);
 
1650
            if(ret == -1){
 
1651
              perror_plus("fchown");
 
1652
            }
 
1653
          }
 
1654
        }
 
1655
        TEMP_FAILURE_RETRY(close(pubkey_fd));
 
1656
      }
 
1657
    }
 
1658
    
 
1659
    /* Lower privileges */
 
1660
    errno = 0;
 
1661
    ret = seteuid(uid);
 
1662
    if(ret == -1){
 
1663
      perror_plus("seteuid");
 
1664
    }
 
1665
  }
 
1666
  
 
1667
  /* Find network hooks and run them */
 
1668
  {
 
1669
    struct dirent **direntries;
 
1670
    struct dirent *direntry;
 
1671
    int numhooks = scandir(hookdir, &direntries, runnable_hook,
 
1672
                           alphasort);
 
1673
    if(numhooks == -1){
 
1674
      perror_plus("scandir");
 
1675
    } else {
 
1676
      int devnull = open("/dev/null", O_RDONLY);
 
1677
      for(int i = 0; i < numhooks; i++){
 
1678
        direntry = direntries[0];
 
1679
        char *fullname = NULL;
 
1680
        ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
 
1681
        if(ret < 0){
 
1682
          perror_plus("asprintf");
 
1683
          continue;
 
1684
        }
 
1685
        pid_t hook_pid = fork();
 
1686
        if(hook_pid == 0){
 
1687
          /* Child */
 
1688
          dup2(devnull, STDIN_FILENO);
 
1689
          close(devnull);
 
1690
          dup2(STDERR_FILENO, STDOUT_FILENO);
 
1691
          ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
 
1692
          if(ret == -1){
 
1693
            perror_plus("setenv");
 
1694
            exit(1);
 
1695
          }
 
1696
          ret = setenv("DEVICE", interface, 1);
 
1697
          if(ret == -1){
 
1698
            perror_plus("setenv");
 
1699
            exit(1);
 
1700
          }
 
1701
          ret = setenv("VERBOSE", debug ? "1" : "0", 1);
 
1702
          if(ret == -1){
 
1703
            perror_plus("setenv");
 
1704
            exit(1);
 
1705
          }
 
1706
          ret = setenv("MODE", "start", 1);
 
1707
          if(ret == -1){
 
1708
            perror_plus("setenv");
 
1709
            exit(1);
 
1710
          }
 
1711
          char *delaystring;
 
1712
          ret = asprintf(&delaystring, "%f", delay);
 
1713
          if(ret == -1){
 
1714
            perror_plus("asprintf");
 
1715
            exit(1);
 
1716
          }
 
1717
          ret = setenv("DELAY", delaystring, 1);
 
1718
          if(ret == -1){
 
1719
            free(delaystring);
 
1720
            perror_plus("setenv");
 
1721
            exit(1);
 
1722
          }
 
1723
          free(delaystring);
 
1724
          ret = execl(fullname, direntry->d_name, "start", NULL);
 
1725
          perror_plus("execl");
 
1726
        } else {
 
1727
          int status;
 
1728
          if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
 
1729
            perror_plus("waitpid");
 
1730
            free(fullname);
 
1731
            continue;
 
1732
          }
 
1733
          if(WIFEXITED(status)){
 
1734
            if(WEXITSTATUS(status) != 0){
 
1735
              fprintf(stderr, "Mandos plugin mandos-client: "
 
1736
                      "Warning: network hook \"%s\" exited"
 
1737
                      " with status %d\n", direntry->d_name,
 
1738
                      WEXITSTATUS(status));
 
1739
              free(fullname);
 
1740
              continue;
 
1741
            }
 
1742
          } else if(WIFSIGNALED(status)){
 
1743
            fprintf(stderr, "Mandos plugin mandos-client: "
 
1744
                    "Warning: network hook \"%s\" died by"
 
1745
                    " signal %d\n", direntry->d_name,
 
1746
                    WTERMSIG(status));
 
1747
            free(fullname);
 
1748
            continue;
 
1749
          } else {
 
1750
            fprintf(stderr, "Mandos plugin mandos-client: "
 
1751
                    "Warning: network hook \"%s\" crashed\n",
 
1752
                    direntry->d_name);
 
1753
            free(fullname);
 
1754
            continue;
 
1755
          }
 
1756
        }
 
1757
        free(fullname);
 
1758
        if(quit_now){
940
1759
          goto end;
941
1760
        }
942
1761
      }
943
 
      ret = TEMP_FAILURE_RETRY(close(sd));
944
 
      if(ret == -1){
945
 
        perror("close");
946
 
      }
947
 
    }
948
 
    
949
 
    uid = getuid();
950
 
    gid = getgid();
951
 
    
952
 
    ret = setuid(uid);
953
 
    if (ret == -1){
954
 
      perror("setuid");
955
 
    }
956
 
    
957
 
    setgid(gid);
958
 
    if (ret == -1){
959
 
      perror("setgid");
960
 
    }
961
 
    
962
 
    ret = init_gnutls_global(&mc, pubkey, seckey);
963
 
    if (ret == -1){
964
 
      fprintf(stderr, "init_gnutls_global failed\n");
965
 
      exitcode = EXIT_FAILURE;
966
 
      goto end;
967
 
    } else {
968
 
      gnutls_initalized = true;
969
 
    }
970
 
    
971
 
    if(mkdtemp(tempdir) == NULL){
972
 
      perror("mkdtemp");
973
 
      tempdir[0] = '\0';
974
 
      goto end;
975
 
    }
976
 
    
977
 
    if(not init_gpgme(&mc, pubkey, seckey, tempdir)){
978
 
      fprintf(stderr, "gpgme_initalized failed\n");
979
 
      exitcode = EXIT_FAILURE;
980
 
      goto end;
981
 
    } else {
982
 
      gpgme_initalized = true;
983
 
    }
984
 
    
 
1762
      close(devnull);
 
1763
    }
 
1764
  }
 
1765
  
 
1766
  if(not debug){
 
1767
    avahi_set_log_function(empty_log);
 
1768
  }
 
1769
  
 
1770
  if(interface[0] == '\0'){
 
1771
    struct dirent **direntries;
 
1772
    /* First look for interfaces that are up */
 
1773
    ret = scandir(sys_class_net, &direntries, up_interface,
 
1774
                  alphasort);
 
1775
    if(ret == 0){
 
1776
      /* No up interfaces, look for any good interfaces */
 
1777
      free(direntries);
 
1778
      ret = scandir(sys_class_net, &direntries, good_interface,
 
1779
                    alphasort);
 
1780
    }
 
1781
    if(ret >= 1){
 
1782
      /* Pick the first interface returned */
 
1783
      interface = strdup(direntries[0]->d_name);
 
1784
      if(debug){
 
1785
        fprintf(stderr, "Mandos plugin mandos-client: "
 
1786
                "Using interface \"%s\"\n", interface);
 
1787
      }
 
1788
      if(interface == NULL){
 
1789
        perror_plus("malloc");
 
1790
        free(direntries);
 
1791
        exitcode = EXIT_FAILURE;
 
1792
        goto end;
 
1793
      }
 
1794
      free(direntries);
 
1795
    } else {
 
1796
      free(direntries);
 
1797
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1798
              "Could not find a network interface\n");
 
1799
      exitcode = EXIT_FAILURE;
 
1800
      goto end;
 
1801
    }
 
1802
  }
 
1803
  
 
1804
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
 
1805
     from the signal handler */
 
1806
  /* Initialize the pseudo-RNG for Avahi */
 
1807
  srand((unsigned int) time(NULL));
 
1808
  mc.simple_poll = avahi_simple_poll_new();
 
1809
  if(mc.simple_poll == NULL){
 
1810
    fprintf(stderr, "Mandos plugin mandos-client: "
 
1811
            "Avahi: Failed to create simple poll object.\n");
 
1812
    exitcode = EX_UNAVAILABLE;
 
1813
    goto end;
 
1814
  }
 
1815
  
 
1816
  sigemptyset(&sigterm_action.sa_mask);
 
1817
  ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
 
1818
  if(ret == -1){
 
1819
    perror_plus("sigaddset");
 
1820
    exitcode = EX_OSERR;
 
1821
    goto end;
 
1822
  }
 
1823
  ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
 
1824
  if(ret == -1){
 
1825
    perror_plus("sigaddset");
 
1826
    exitcode = EX_OSERR;
 
1827
    goto end;
 
1828
  }
 
1829
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
 
1830
  if(ret == -1){
 
1831
    perror_plus("sigaddset");
 
1832
    exitcode = EX_OSERR;
 
1833
    goto end;
 
1834
  }
 
1835
  /* Need to check if the handler is SIG_IGN before handling:
 
1836
     | [[info:libc:Initial Signal Actions]] |
 
1837
     | [[info:libc:Basic Signal Handling]]  |
 
1838
  */
 
1839
  ret = sigaction(SIGINT, NULL, &old_sigterm_action);
 
1840
  if(ret == -1){
 
1841
    perror_plus("sigaction");
 
1842
    return EX_OSERR;
 
1843
  }
 
1844
  if(old_sigterm_action.sa_handler != SIG_IGN){
 
1845
    ret = sigaction(SIGINT, &sigterm_action, NULL);
 
1846
    if(ret == -1){
 
1847
      perror_plus("sigaction");
 
1848
      exitcode = EX_OSERR;
 
1849
      goto end;
 
1850
    }
 
1851
  }
 
1852
  ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
 
1853
  if(ret == -1){
 
1854
    perror_plus("sigaction");
 
1855
    return EX_OSERR;
 
1856
  }
 
1857
  if(old_sigterm_action.sa_handler != SIG_IGN){
 
1858
    ret = sigaction(SIGHUP, &sigterm_action, NULL);
 
1859
    if(ret == -1){
 
1860
      perror_plus("sigaction");
 
1861
      exitcode = EX_OSERR;
 
1862
      goto end;
 
1863
    }
 
1864
  }
 
1865
  ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
 
1866
  if(ret == -1){
 
1867
    perror_plus("sigaction");
 
1868
    return EX_OSERR;
 
1869
  }
 
1870
  if(old_sigterm_action.sa_handler != SIG_IGN){
 
1871
    ret = sigaction(SIGTERM, &sigterm_action, NULL);
 
1872
    if(ret == -1){
 
1873
      perror_plus("sigaction");
 
1874
      exitcode = EX_OSERR;
 
1875
      goto end;
 
1876
    }
 
1877
  }
 
1878
  
 
1879
  /* If the interface is down, bring it up */
 
1880
  if(strcmp(interface, "none") != 0){
985
1881
    if_index = (AvahiIfIndex) if_nametoindex(interface);
986
1882
    if(if_index == 0){
987
 
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
988
 
      exit(EXIT_FAILURE);
989
 
    }
990
 
    
991
 
    if(connect_to != NULL){
992
 
      /* Connect directly, do not use Zeroconf */
993
 
      /* (Mainly meant for debugging) */
994
 
      char *address = strrchr(connect_to, ':');
995
 
      if(address == NULL){
996
 
        fprintf(stderr, "No colon in address\n");
997
 
        exitcode = EXIT_FAILURE;
998
 
        goto end;
999
 
      }
1000
 
      errno = 0;
1001
 
      uint16_t port = (uint16_t) strtol(address+1, NULL, 10);
1002
 
      if(errno){
1003
 
        perror("Bad port number");
1004
 
        exitcode = EXIT_FAILURE;
1005
 
        goto end;
1006
 
      }
1007
 
      *address = '\0';
1008
 
      address = connect_to;
1009
 
      ret = start_mandos_communication(address, port, if_index, &mc);
1010
 
      if(ret < 0){
1011
 
        exitcode = EXIT_FAILURE;
1012
 
      } else {
1013
 
        exitcode = EXIT_SUCCESS;
1014
 
      }
1015
 
      goto end;
1016
 
    }
1017
 
    
1018
 
    if (not debug){
1019
 
      avahi_set_log_function(empty_log);
1020
 
    }
1021
 
    
1022
 
    /* Initialize the pseudo-RNG for Avahi */
1023
 
    srand((unsigned int) time(NULL));
1024
 
    
1025
 
    /* Allocate main Avahi loop object */
1026
 
    mc.simple_poll = avahi_simple_poll_new();
1027
 
    if (mc.simple_poll == NULL) {
1028
 
        fprintf(stderr, "Avahi: Failed to create simple poll"
1029
 
                " object.\n");
1030
 
        exitcode = EXIT_FAILURE;
1031
 
        goto end;
1032
 
    }
1033
 
    
1034
 
    {
1035
 
      AvahiServerConfig config;
1036
 
      /* Do not publish any local Zeroconf records */
1037
 
      avahi_server_config_init(&config);
1038
 
      config.publish_hinfo = 0;
1039
 
      config.publish_addresses = 0;
1040
 
      config.publish_workstation = 0;
1041
 
      config.publish_domain = 0;
1042
 
      
1043
 
      /* Allocate a new server */
1044
 
      mc.server = avahi_server_new(avahi_simple_poll_get
1045
 
                                   (mc.simple_poll), &config, NULL,
1046
 
                                   NULL, &error);
1047
 
      
1048
 
      /* Free the Avahi configuration data */
1049
 
      avahi_server_config_free(&config);
1050
 
    }
1051
 
    
1052
 
    /* Check if creating the Avahi server object succeeded */
1053
 
    if (mc.server == NULL) {
1054
 
        fprintf(stderr, "Failed to create Avahi server: %s\n",
1055
 
                avahi_strerror(error));
1056
 
        exitcode = EXIT_FAILURE;
1057
 
        goto end;
1058
 
    }
1059
 
    
1060
 
    /* Create the Avahi service browser */
1061
 
    sb = avahi_s_service_browser_new(mc.server, if_index,
1062
 
                                     AVAHI_PROTO_INET6,
1063
 
                                     "_mandos._tcp", NULL, 0,
1064
 
                                     browse_callback, &mc);
1065
 
    if (sb == NULL) {
1066
 
        fprintf(stderr, "Failed to create service browser: %s\n",
1067
 
                avahi_strerror(avahi_server_errno(mc.server)));
1068
 
        exitcode = EXIT_FAILURE;
1069
 
        goto end;
1070
 
    }
1071
 
    
1072
 
    /* Run the main loop */
1073
 
    
1074
 
    if (debug){
1075
 
      fprintf(stderr, "Starting Avahi loop search\n");
1076
 
    }
1077
 
    
1078
 
    avahi_simple_poll_loop(mc.simple_poll);
1079
 
    
 
1883
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1884
              "No such interface: \"%s\"\n", interface);
 
1885
      exitcode = EX_UNAVAILABLE;
 
1886
      goto end;
 
1887
    }
 
1888
    
 
1889
    if(quit_now){
 
1890
      goto end;
 
1891
    }
 
1892
    
 
1893
    /* Re-raise priviliges */
 
1894
    errno = 0;
 
1895
    ret = seteuid(0);
 
1896
    if(ret == -1){
 
1897
      perror_plus("seteuid");
 
1898
    }
 
1899
    
 
1900
#ifdef __linux__
 
1901
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
 
1902
       messages about the network interface to mess up the prompt */
 
1903
    ret = klogctl(8, NULL, 5);
 
1904
    bool restore_loglevel = true;
 
1905
    if(ret == -1){
 
1906
      restore_loglevel = false;
 
1907
      perror_plus("klogctl");
 
1908
    }
 
1909
#endif  /* __linux__ */
 
1910
    
 
1911
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1912
    if(sd < 0){
 
1913
      perror_plus("socket");
 
1914
      exitcode = EX_OSERR;
 
1915
#ifdef __linux__
 
1916
      if(restore_loglevel){
 
1917
        ret = klogctl(7, NULL, 0);
 
1918
        if(ret == -1){
 
1919
          perror_plus("klogctl");
 
1920
        }
 
1921
      }
 
1922
#endif  /* __linux__ */
 
1923
      /* Lower privileges */
 
1924
      errno = 0;
 
1925
      ret = seteuid(uid);
 
1926
      if(ret == -1){
 
1927
        perror_plus("seteuid");
 
1928
      }
 
1929
      goto end;
 
1930
    }
 
1931
    strcpy(network.ifr_name, interface);
 
1932
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
1933
    if(ret == -1){
 
1934
      perror_plus("ioctl SIOCGIFFLAGS");
 
1935
#ifdef __linux__
 
1936
      if(restore_loglevel){
 
1937
        ret = klogctl(7, NULL, 0);
 
1938
        if(ret == -1){
 
1939
          perror_plus("klogctl");
 
1940
        }
 
1941
      }
 
1942
#endif  /* __linux__ */
 
1943
      exitcode = EX_OSERR;
 
1944
      /* Lower privileges */
 
1945
      errno = 0;
 
1946
      ret = seteuid(uid);
 
1947
      if(ret == -1){
 
1948
        perror_plus("seteuid");
 
1949
      }
 
1950
      goto end;
 
1951
    }
 
1952
    if((network.ifr_flags & IFF_UP) == 0){
 
1953
      network.ifr_flags |= IFF_UP;
 
1954
      take_down_interface = true;
 
1955
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
1956
      if(ret == -1){
 
1957
        take_down_interface = false;
 
1958
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
 
1959
        exitcode = EX_OSERR;
 
1960
#ifdef __linux__
 
1961
        if(restore_loglevel){
 
1962
          ret = klogctl(7, NULL, 0);
 
1963
          if(ret == -1){
 
1964
            perror_plus("klogctl");
 
1965
          }
 
1966
        }
 
1967
#endif  /* __linux__ */
 
1968
        /* Lower privileges */
 
1969
        errno = 0;
 
1970
        ret = seteuid(uid);
 
1971
        if(ret == -1){
 
1972
          perror_plus("seteuid");
 
1973
        }
 
1974
        goto end;
 
1975
      }
 
1976
    }
 
1977
    /* Sleep checking until interface is running.
 
1978
       Check every 0.25s, up to total time of delay */
 
1979
    for(int i=0; i < delay * 4; i++){
 
1980
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
1981
      if(ret == -1){
 
1982
        perror_plus("ioctl SIOCGIFFLAGS");
 
1983
      } else if(network.ifr_flags & IFF_RUNNING){
 
1984
        break;
 
1985
      }
 
1986
      struct timespec sleeptime = { .tv_nsec = 250000000 };
 
1987
      ret = nanosleep(&sleeptime, NULL);
 
1988
      if(ret == -1 and errno != EINTR){
 
1989
        perror_plus("nanosleep");
 
1990
      }
 
1991
    }
 
1992
    if(not take_down_interface){
 
1993
      /* We won't need the socket anymore */
 
1994
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1995
      if(ret == -1){
 
1996
        perror_plus("close");
 
1997
      }
 
1998
    }
 
1999
#ifdef __linux__
 
2000
    if(restore_loglevel){
 
2001
      /* Restores kernel loglevel to default */
 
2002
      ret = klogctl(7, NULL, 0);
 
2003
      if(ret == -1){
 
2004
        perror_plus("klogctl");
 
2005
      }
 
2006
    }
 
2007
#endif  /* __linux__ */
 
2008
    /* Lower privileges */
 
2009
    errno = 0;
 
2010
    if(take_down_interface){
 
2011
      /* Lower privileges */
 
2012
      ret = seteuid(uid);
 
2013
      if(ret == -1){
 
2014
        perror_plus("seteuid");
 
2015
      }
 
2016
    } else {
 
2017
      /* Lower privileges permanently */
 
2018
      ret = setuid(uid);
 
2019
      if(ret == -1){
 
2020
        perror_plus("setuid");
 
2021
      }
 
2022
    }
 
2023
  }
 
2024
  
 
2025
  if(quit_now){
 
2026
    goto end;
 
2027
  }
 
2028
  
 
2029
  ret = init_gnutls_global(pubkey, seckey);
 
2030
  if(ret == -1){
 
2031
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2032
            "init_gnutls_global failed\n");
 
2033
    exitcode = EX_UNAVAILABLE;
 
2034
    goto end;
 
2035
  } else {
 
2036
    gnutls_initialized = true;
 
2037
  }
 
2038
  
 
2039
  if(quit_now){
 
2040
    goto end;
 
2041
  }
 
2042
  
 
2043
  if(mkdtemp(tempdir) == NULL){
 
2044
    perror_plus("mkdtemp");
 
2045
    goto end;
 
2046
  }
 
2047
  tempdir_created = true;
 
2048
  
 
2049
  if(quit_now){
 
2050
    goto end;
 
2051
  }
 
2052
  
 
2053
  if(not init_gpgme(pubkey, seckey, tempdir)){
 
2054
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2055
            "init_gpgme failed\n");
 
2056
    exitcode = EX_UNAVAILABLE;
 
2057
    goto end;
 
2058
  } else {
 
2059
    gpgme_initialized = true;
 
2060
  }
 
2061
  
 
2062
  if(quit_now){
 
2063
    goto end;
 
2064
  }
 
2065
  
 
2066
  if(connect_to != NULL){
 
2067
    /* Connect directly, do not use Zeroconf */
 
2068
    /* (Mainly meant for debugging) */
 
2069
    char *address = strrchr(connect_to, ':');
 
2070
    if(address == NULL){
 
2071
      fprintf(stderr, "Mandos plugin mandos-client: "
 
2072
              "No colon in address\n");
 
2073
      exitcode = EX_USAGE;
 
2074
      goto end;
 
2075
    }
 
2076
    
 
2077
    if(quit_now){
 
2078
      goto end;
 
2079
    }
 
2080
    
 
2081
    uint16_t port;
 
2082
    errno = 0;
 
2083
    tmpmax = strtoimax(address+1, &tmp, 10);
 
2084
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
 
2085
       or tmpmax != (uint16_t)tmpmax){
 
2086
      fprintf(stderr, "Mandos plugin mandos-client: "
 
2087
              "Bad port number\n");
 
2088
      exitcode = EX_USAGE;
 
2089
      goto end;
 
2090
    }
 
2091
  
 
2092
    if(quit_now){
 
2093
      goto end;
 
2094
    }
 
2095
    
 
2096
    port = (uint16_t)tmpmax;
 
2097
    *address = '\0';
 
2098
    /* Colon in address indicates IPv6 */
 
2099
    int af;
 
2100
    if(strchr(connect_to, ':') != NULL){
 
2101
      af = AF_INET6;
 
2102
      /* Accept [] around IPv6 address - see RFC 5952 */
 
2103
      if(connect_to[0] == '[' and address[-1] == ']')
 
2104
        {
 
2105
          connect_to++;
 
2106
          address[-1] = '\0';
 
2107
        }
 
2108
    } else {
 
2109
      af = AF_INET;
 
2110
    }
 
2111
    address = connect_to;
 
2112
    
 
2113
    if(quit_now){
 
2114
      goto end;
 
2115
    }
 
2116
    
 
2117
    while(not quit_now){
 
2118
      ret = start_mandos_communication(address, port, if_index, af);
 
2119
      if(quit_now or ret == 0){
 
2120
        break;
 
2121
      }
 
2122
      if(debug){
 
2123
        fprintf(stderr, "Mandos plugin mandos-client: "
 
2124
                "Retrying in %d seconds\n", (int)retry_interval);
 
2125
      }
 
2126
      sleep((int)retry_interval);
 
2127
    }
 
2128
    
 
2129
    if (not quit_now){
 
2130
      exitcode = EXIT_SUCCESS;
 
2131
    }
 
2132
    
 
2133
    goto end;
 
2134
  }
 
2135
  
 
2136
  if(quit_now){
 
2137
    goto end;
 
2138
  }
 
2139
  
 
2140
  {
 
2141
    AvahiServerConfig config;
 
2142
    /* Do not publish any local Zeroconf records */
 
2143
    avahi_server_config_init(&config);
 
2144
    config.publish_hinfo = 0;
 
2145
    config.publish_addresses = 0;
 
2146
    config.publish_workstation = 0;
 
2147
    config.publish_domain = 0;
 
2148
    
 
2149
    /* Allocate a new server */
 
2150
    mc.server = avahi_server_new(avahi_simple_poll_get
 
2151
                                 (mc.simple_poll), &config, NULL,
 
2152
                                 NULL, &error);
 
2153
    
 
2154
    /* Free the Avahi configuration data */
 
2155
    avahi_server_config_free(&config);
 
2156
  }
 
2157
  
 
2158
  /* Check if creating the Avahi server object succeeded */
 
2159
  if(mc.server == NULL){
 
2160
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2161
            "Failed to create Avahi server: %s\n",
 
2162
            avahi_strerror(error));
 
2163
    exitcode = EX_UNAVAILABLE;
 
2164
    goto end;
 
2165
  }
 
2166
  
 
2167
  if(quit_now){
 
2168
    goto end;
 
2169
  }
 
2170
  
 
2171
  /* Create the Avahi service browser */
 
2172
  sb = avahi_s_service_browser_new(mc.server, if_index,
 
2173
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
 
2174
                                   NULL, 0, browse_callback, NULL);
 
2175
  if(sb == NULL){
 
2176
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2177
            "Failed to create service browser: %s\n",
 
2178
            avahi_strerror(avahi_server_errno(mc.server)));
 
2179
    exitcode = EX_UNAVAILABLE;
 
2180
    goto end;
 
2181
  }
 
2182
  
 
2183
  if(quit_now){
 
2184
    goto end;
 
2185
  }
 
2186
  
 
2187
  /* Run the main loop */
 
2188
  
 
2189
  if(debug){
 
2190
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2191
            "Starting Avahi loop search\n");
 
2192
  }
 
2193
 
 
2194
  ret = avahi_loop_with_timeout(mc.simple_poll,
 
2195
                                (int)(retry_interval * 1000));
 
2196
  if(debug){
 
2197
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2198
            "avahi_loop_with_timeout exited %s\n",
 
2199
            (ret == 0) ? "successfully" : "with error");
 
2200
  }
 
2201
  
1080
2202
 end:
1081
 
    
1082
 
    if (debug){
1083
 
      fprintf(stderr, "%s exiting\n", argv[0]);
1084
 
    }
1085
 
    
1086
 
    /* Cleanup things */
1087
 
    if (sb != NULL)
1088
 
        avahi_s_service_browser_free(sb);
1089
 
    
1090
 
    if (mc.server != NULL)
1091
 
        avahi_server_free(mc.server);
1092
 
    
1093
 
    if (mc.simple_poll != NULL)
1094
 
        avahi_simple_poll_free(mc.simple_poll);
1095
 
    
1096
 
    if (gnutls_initalized){
1097
 
      gnutls_certificate_free_credentials(mc.cred);
1098
 
      gnutls_global_deinit ();
1099
 
      gnutls_dh_params_deinit(mc.dh_params);
1100
 
    }
1101
 
    
1102
 
    if(gpgme_initalized){
1103
 
      gpgme_release(mc.ctx);
1104
 
    }
1105
 
    
1106
 
    /* Removes the temp directory used by GPGME */
1107
 
    if(tempdir[0] != '\0'){
1108
 
      DIR *d;
1109
 
      struct dirent *direntry;
1110
 
      d = opendir(tempdir);
1111
 
      if(d == NULL){
1112
 
        perror("opendir");
1113
 
      } else {
1114
 
        while(true){
1115
 
          direntry = readdir(d);
1116
 
          if(direntry == NULL){
1117
 
            break;
1118
 
          }
1119
 
          if (direntry->d_type == DT_REG){
1120
 
            char *fullname = NULL;
1121
 
            ret = asprintf(&fullname, "%s/%s", tempdir,
1122
 
                           direntry->d_name);
1123
 
            if(ret < 0){
1124
 
              perror("asprintf");
1125
 
              continue;
1126
 
            }
1127
 
            ret = unlink(fullname);
1128
 
            if(ret == -1){
1129
 
              fprintf(stderr, "unlink(\"%s\"): %s",
1130
 
                      fullname, strerror(errno));
1131
 
            }
1132
 
            free(fullname);
1133
 
          }
1134
 
        }
1135
 
        closedir(d);
1136
 
      }
1137
 
      ret = rmdir(tempdir);
1138
 
      if(ret == -1){
1139
 
        perror("rmdir");
1140
 
      }
1141
 
    }
1142
 
          
1143
 
    return exitcode;
 
2203
  
 
2204
  if(debug){
 
2205
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2206
            "%s exiting\n", argv[0]);
 
2207
  }
 
2208
  
 
2209
  /* Cleanup things */
 
2210
  if(sb != NULL)
 
2211
    avahi_s_service_browser_free(sb);
 
2212
  
 
2213
  if(mc.server != NULL)
 
2214
    avahi_server_free(mc.server);
 
2215
  
 
2216
  if(mc.simple_poll != NULL)
 
2217
    avahi_simple_poll_free(mc.simple_poll);
 
2218
  
 
2219
  if(gnutls_initialized){
 
2220
    gnutls_certificate_free_credentials(mc.cred);
 
2221
    gnutls_global_deinit();
 
2222
    gnutls_dh_params_deinit(mc.dh_params);
 
2223
  }
 
2224
  
 
2225
  if(gpgme_initialized){
 
2226
    gpgme_release(mc.ctx);
 
2227
  }
 
2228
 
 
2229
  /* Cleans up the circular linked list of Mandos servers the client
 
2230
     has seen */
 
2231
  if(mc.current_server != NULL){
 
2232
    mc.current_server->prev->next = NULL;
 
2233
    while(mc.current_server != NULL){
 
2234
      server *next = mc.current_server->next;
 
2235
      free(mc.current_server);
 
2236
      mc.current_server = next;
 
2237
    }
 
2238
  }
 
2239
  
 
2240
  /* XXX run network hooks "stop" here  */
 
2241
  
 
2242
  /* Take down the network interface */
 
2243
  if(take_down_interface){
 
2244
    /* Re-raise priviliges */
 
2245
    errno = 0;
 
2246
    ret = seteuid(0);
 
2247
    if(ret == -1){
 
2248
      perror_plus("seteuid");
 
2249
    }
 
2250
    if(geteuid() == 0){
 
2251
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
2252
      if(ret == -1){
 
2253
        perror_plus("ioctl SIOCGIFFLAGS");
 
2254
      } else if(network.ifr_flags & IFF_UP){
 
2255
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
 
2256
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
2257
        if(ret == -1){
 
2258
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
 
2259
        }
 
2260
      }
 
2261
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
2262
      if(ret == -1){
 
2263
        perror_plus("close");
 
2264
      }
 
2265
      /* Lower privileges permanently */
 
2266
      errno = 0;
 
2267
      ret = setuid(uid);
 
2268
      if(ret == -1){
 
2269
        perror_plus("setuid");
 
2270
      }
 
2271
    }
 
2272
  }
 
2273
  
 
2274
  /* Removes the GPGME temp directory and all files inside */
 
2275
  if(tempdir_created){
 
2276
    struct dirent **direntries = NULL;
 
2277
    struct dirent *direntry = NULL;
 
2278
    int numentries = scandir(tempdir, &direntries, notdotentries,
 
2279
                             alphasort);
 
2280
    if (numentries > 0){
 
2281
      for(int i = 0; i < numentries; i++){
 
2282
        direntry = direntries[i];
 
2283
        char *fullname = NULL;
 
2284
        ret = asprintf(&fullname, "%s/%s", tempdir,
 
2285
                       direntry->d_name);
 
2286
        if(ret < 0){
 
2287
          perror_plus("asprintf");
 
2288
          continue;
 
2289
        }
 
2290
        ret = remove(fullname);
 
2291
        if(ret == -1){
 
2292
          fprintf(stderr, "Mandos plugin mandos-client: "
 
2293
                  "remove(\"%s\"): %s\n", fullname, strerror(errno));
 
2294
        }
 
2295
        free(fullname);
 
2296
      }
 
2297
    }
 
2298
 
 
2299
    /* need to clean even if 0 because man page doesn't specify */
 
2300
    free(direntries);
 
2301
    if (numentries == -1){
 
2302
      perror_plus("scandir");
 
2303
    }
 
2304
    ret = rmdir(tempdir);
 
2305
    if(ret == -1 and errno != ENOENT){
 
2306
      perror_plus("rmdir");
 
2307
    }
 
2308
  }
 
2309
  
 
2310
  if(quit_now){
 
2311
    sigemptyset(&old_sigterm_action.sa_mask);
 
2312
    old_sigterm_action.sa_handler = SIG_DFL;
 
2313
    ret = (int)TEMP_FAILURE_RETRY(sigaction(signal_received,
 
2314
                                            &old_sigterm_action,
 
2315
                                            NULL));
 
2316
    if(ret == -1){
 
2317
      perror_plus("sigaction");
 
2318
    }
 
2319
    do {
 
2320
      ret = raise(signal_received);
 
2321
    } while(ret != 0 and errno == EINTR);
 
2322
    if(ret != 0){
 
2323
      perror_plus("raise");
 
2324
      abort();
 
2325
    }
 
2326
    TEMP_FAILURE_RETRY(pause());
 
2327
  }
 
2328
  
 
2329
  return exitcode;
1144
2330
}