/mandos/trunk

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

« back to all changes in this revision

Viewing changes to plugins.d/mandos-client.c

  • Committer: Teddy Hogeborn
  • Date: 2009-04-17 08:26:17 UTC
  • Revision ID: teddy@fukt.bsnet.se-20090417082617-eltetak5lzjyz55o
* initramfs-tools-hook: Bug fix: Add "--userid" and "--groupid" to
                        start of "plugin-runner.conf" file instead of
                        appending, to allow any preexisting options to
                        override.
* plugin-runner.conf: Improved wording.

Show diffs side-by-side

added added

removed removed

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