/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: 2011-07-25 18:50:00 UTC
  • mfrom: (24.1.176 mandos)
  • Revision ID: teddy@fukt.bsnet.se-20110725185000-paes3keuo0dj4m0z
Merge from Björn.

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,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
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(), sscanf(),
40
 
                                   remove() */
 
43
                                   stdout, ferror(), remove() */
41
44
#include <stdint.h>             /* uint16_t, uint32_t */
42
45
#include <stddef.h>             /* NULL, size_t, ssize_t */
43
 
#include <stdlib.h>             /* free(), EXIT_SUCCESS, EXIT_FAILURE,
44
 
                                   srand() */
 
46
#include <stdlib.h>             /* free(), EXIT_SUCCESS, srand(),
 
47
                                   strtof(), abort() */
45
48
#include <stdbool.h>            /* bool, false, true */
46
49
#include <string.h>             /* memset(), strcmp(), strlen(),
47
50
                                   strerror(), asprintf(), strcpy() */
56
59
#include <fcntl.h>              /* open() */
57
60
#include <dirent.h>             /* opendir(), struct dirent, readdir()
58
61
                                 */
59
 
#include <inttypes.h>           /* PRIu16, intmax_t, SCNdMAX */
 
62
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
 
63
                                   strtoimax() */
60
64
#include <assert.h>             /* assert() */
61
 
#include <errno.h>              /* perror(), errno */
62
 
#include <time.h>               /* nanosleep(), time() */
 
65
#include <errno.h>              /* perror(), errno,
 
66
                                   program_invocation_short_name */
 
67
#include <time.h>               /* nanosleep(), time(), sleep() */
63
68
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
64
69
                                   SIOCSIFFLAGS, if_indextoname(),
65
70
                                   if_nametoindex(), IF_NAMESIZE */
67
72
                                   INET_ADDRSTRLEN, INET6_ADDRSTRLEN
68
73
                                */
69
74
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
70
 
                                   getuid(), getgid(), setuid(),
71
 
                                   setgid() */
72
 
#include <arpa/inet.h>          /* inet_pton(), htons */
 
75
                                   getuid(), getgid(), seteuid(),
 
76
                                   setgid(), pause() */
 
77
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
73
78
#include <iso646.h>             /* not, or, and */
74
79
#include <argp.h>               /* struct argp_option, error_t, struct
75
80
                                   argp_state, struct argp,
76
81
                                   argp_parse(), ARGP_KEY_ARG,
77
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
 
78
89
#ifdef __linux__
79
90
#include <sys/klog.h>           /* klogctl() */
80
 
#endif
 
91
#endif  /* __linux__ */
81
92
 
82
93
/* Avahi */
83
94
/* All Avahi types, constants and functions
117
128
static const char mandos_protocol_version[] = "1";
118
129
const char *argp_program_version = "mandos-client " VERSION;
119
130
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
 
131
static const char sys_class_net[] = "/sys/class/net";
 
132
char *connect_to = NULL;
 
133
 
 
134
/* Doubly linked list that need to be circularly linked when used */
 
135
typedef struct server{
 
136
  const char *ip;
 
137
  uint16_t port;
 
138
  AvahiIfIndex if_index;
 
139
  int af;
 
140
  struct timespec last_seen;
 
141
  struct server *next;
 
142
  struct server *prev;
 
143
} server;
120
144
 
121
145
/* Used for passing in values through the Avahi callback functions */
122
146
typedef struct {
127
151
  gnutls_dh_params_t dh_params;
128
152
  const char *priority;
129
153
  gpgme_ctx_t ctx;
 
154
  server *current_server;
130
155
} mandos_context;
131
156
 
 
157
/* global context so signal handler can reach it*/
 
158
mandos_context mc = { .simple_poll = NULL, .server = NULL,
 
159
                      .dh_bits = 1024, .priority = "SECURE256"
 
160
                      ":!CTYPE-X.509:+CTYPE-OPENPGP",
 
161
                      .current_server = NULL };
 
162
 
 
163
sig_atomic_t quit_now = 0;
 
164
int signal_received = 0;
 
165
 
 
166
/* Function to use when printing errors */
 
167
void perror_plus(const char *print_text){
 
168
  fprintf(stderr, "Mandos plugin %s: ",
 
169
          program_invocation_short_name);
 
170
  perror(print_text);
 
171
}
 
172
 
132
173
/*
133
 
 * Make room in "buffer" for at least BUFFER_SIZE additional bytes.
134
 
 * "buffer_capacity" is how much is currently allocated,
 
174
 * Make additional room in "buffer" for at least BUFFER_SIZE more
 
175
 * bytes. "buffer_capacity" is how much is currently allocated,
135
176
 * "buffer_length" is how much is already used.
136
177
 */
137
 
size_t adjustbuffer(char **buffer, size_t buffer_length,
 
178
size_t incbuffer(char **buffer, size_t buffer_length,
138
179
                  size_t buffer_capacity){
139
180
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
140
181
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
146
187
  return buffer_capacity;
147
188
}
148
189
 
 
190
int add_server(const char *ip, uint16_t port,
 
191
                 AvahiIfIndex if_index,
 
192
                 int af){
 
193
  int ret;
 
194
  server *new_server = malloc(sizeof(server));
 
195
  if(new_server == NULL){
 
196
    perror_plus("malloc");
 
197
    return -1;
 
198
  }
 
199
  *new_server = (server){ .ip = strdup(ip),
 
200
                         .port = port,
 
201
                         .if_index = if_index,
 
202
                         .af = af };
 
203
  if(new_server->ip == NULL){
 
204
    perror_plus("strdup");
 
205
    return -1;
 
206
  }
 
207
  /* unique case of first server */
 
208
  if (mc.current_server == NULL){
 
209
    new_server->next = new_server;
 
210
    new_server->prev = new_server;
 
211
    mc.current_server = new_server;
 
212
  /* Placing the new server last in the list */
 
213
  } else {
 
214
    new_server->next = mc.current_server;
 
215
    new_server->prev = mc.current_server->prev;
 
216
    new_server->prev->next = new_server;
 
217
    mc.current_server->prev = new_server;
 
218
  }
 
219
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
 
220
  if(ret == -1){
 
221
    perror_plus("clock_gettime");
 
222
    return -1;
 
223
  }
 
224
  return 0;
 
225
}
 
226
 
149
227
/* 
150
228
 * Initialize GPGME.
151
229
 */
152
 
static bool init_gpgme(mandos_context *mc, const char *seckey,
 
230
static bool init_gpgme(const char *seckey,
153
231
                       const char *pubkey, const char *tempdir){
154
 
  int ret;
155
232
  gpgme_error_t rc;
156
233
  gpgme_engine_info_t engine_info;
157
234
  
160
237
   * Helper function to insert pub and seckey to the engine keyring.
161
238
   */
162
239
  bool import_key(const char *filename){
 
240
    int ret;
163
241
    int fd;
164
242
    gpgme_data_t pgp_data;
165
243
    
166
244
    fd = (int)TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
167
245
    if(fd == -1){
168
 
      perror("open");
 
246
      perror_plus("open");
169
247
      return false;
170
248
    }
171
249
    
176
254
      return false;
177
255
    }
178
256
    
179
 
    rc = gpgme_op_import(mc->ctx, pgp_data);
 
257
    rc = gpgme_op_import(mc.ctx, pgp_data);
180
258
    if(rc != GPG_ERR_NO_ERROR){
181
259
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
182
260
              gpgme_strsource(rc), gpgme_strerror(rc));
185
263
    
186
264
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
187
265
    if(ret == -1){
188
 
      perror("close");
 
266
      perror_plus("close");
189
267
    }
190
268
    gpgme_data_release(pgp_data);
191
269
    return true;
192
270
  }
193
271
  
194
272
  if(debug){
195
 
    fprintf(stderr, "Initialize gpgme\n");
 
273
    fprintf(stderr, "Initializing GPGME\n");
196
274
  }
197
275
  
198
276
  /* Init GPGME */
225
303
  }
226
304
  
227
305
  /* Create new GPGME "context" */
228
 
  rc = gpgme_new(&(mc->ctx));
 
306
  rc = gpgme_new(&(mc.ctx));
229
307
  if(rc != GPG_ERR_NO_ERROR){
230
308
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
231
309
            gpgme_strsource(rc), gpgme_strerror(rc));
236
314
    return false;
237
315
  }
238
316
  
239
 
  return true; 
 
317
  return true;
240
318
}
241
319
 
242
320
/* 
243
321
 * Decrypt OpenPGP data.
244
322
 * Returns -1 on error
245
323
 */
246
 
static ssize_t pgp_packet_decrypt(const mandos_context *mc,
247
 
                                  const char *cryptotext,
 
324
static ssize_t pgp_packet_decrypt(const char *cryptotext,
248
325
                                  size_t crypto_size,
249
326
                                  char **plaintext){
250
327
  gpgme_data_t dh_crypto, dh_plain;
277
354
  
278
355
  /* Decrypt data from the cryptotext data buffer to the plaintext
279
356
     data buffer */
280
 
  rc = gpgme_op_decrypt(mc->ctx, dh_crypto, dh_plain);
 
357
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
281
358
  if(rc != GPG_ERR_NO_ERROR){
282
359
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
283
360
            gpgme_strsource(rc), gpgme_strerror(rc));
284
361
    plaintext_length = -1;
285
362
    if(debug){
286
363
      gpgme_decrypt_result_t result;
287
 
      result = gpgme_op_decrypt_result(mc->ctx);
 
364
      result = gpgme_op_decrypt_result(mc.ctx);
288
365
      if(result == NULL){
289
366
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
290
367
      } else {
297
374
        }
298
375
        gpgme_recipient_t recipient;
299
376
        recipient = result->recipients;
300
 
        if(recipient){
301
 
          while(recipient != NULL){
302
 
            fprintf(stderr, "Public key algorithm: %s\n",
303
 
                    gpgme_pubkey_algo_name(recipient->pubkey_algo));
304
 
            fprintf(stderr, "Key ID: %s\n", recipient->keyid);
305
 
            fprintf(stderr, "Secret key available: %s\n",
306
 
                    recipient->status == GPG_ERR_NO_SECKEY
307
 
                    ? "No" : "Yes");
308
 
            recipient = recipient->next;
309
 
          }
 
377
        while(recipient != NULL){
 
378
          fprintf(stderr, "Public key algorithm: %s\n",
 
379
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
 
380
          fprintf(stderr, "Key ID: %s\n", recipient->keyid);
 
381
          fprintf(stderr, "Secret key available: %s\n",
 
382
                  recipient->status == GPG_ERR_NO_SECKEY
 
383
                  ? "No" : "Yes");
 
384
          recipient = recipient->next;
310
385
        }
311
386
      }
312
387
    }
319
394
  
320
395
  /* Seek back to the beginning of the GPGME plaintext data buffer */
321
396
  if(gpgme_data_seek(dh_plain, (off_t)0, SEEK_SET) == -1){
322
 
    perror("gpgme_data_seek");
 
397
    perror_plus("gpgme_data_seek");
323
398
    plaintext_length = -1;
324
399
    goto decrypt_end;
325
400
  }
326
401
  
327
402
  *plaintext = NULL;
328
403
  while(true){
329
 
    plaintext_capacity = adjustbuffer(plaintext,
 
404
    plaintext_capacity = incbuffer(plaintext,
330
405
                                      (size_t)plaintext_length,
331
406
                                      plaintext_capacity);
332
407
    if(plaintext_capacity == 0){
333
 
        perror("adjustbuffer");
 
408
        perror_plus("incbuffer");
334
409
        plaintext_length = -1;
335
410
        goto decrypt_end;
336
411
    }
343
418
      break;
344
419
    }
345
420
    if(ret < 0){
346
 
      perror("gpgme_data_read");
 
421
      perror_plus("gpgme_data_read");
347
422
      plaintext_length = -1;
348
423
      goto decrypt_end;
349
424
    }
382
457
  fprintf(stderr, "GnuTLS: %s", string);
383
458
}
384
459
 
385
 
static int init_gnutls_global(mandos_context *mc,
386
 
                              const char *pubkeyfilename,
 
460
static int init_gnutls_global(const char *pubkeyfilename,
387
461
                              const char *seckeyfilename){
388
462
  int ret;
389
463
  
407
481
  }
408
482
  
409
483
  /* OpenPGP credentials */
410
 
  gnutls_certificate_allocate_credentials(&mc->cred);
 
484
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
411
485
  if(ret != GNUTLS_E_SUCCESS){
412
 
    fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning
413
 
                                                    from
414
 
                                                    -Wunreachable-code
415
 
                                                 */
 
486
    fprintf(stderr, "GnuTLS memory error: %s\n",
416
487
            safer_gnutls_strerror(ret));
417
488
    gnutls_global_deinit();
418
489
    return -1;
425
496
  }
426
497
  
427
498
  ret = gnutls_certificate_set_openpgp_key_file
428
 
    (mc->cred, pubkeyfilename, seckeyfilename,
 
499
    (mc.cred, pubkeyfilename, seckeyfilename,
429
500
     GNUTLS_OPENPGP_FMT_BASE64);
430
501
  if(ret != GNUTLS_E_SUCCESS){
431
502
    fprintf(stderr,
437
508
  }
438
509
  
439
510
  /* GnuTLS server initialization */
440
 
  ret = gnutls_dh_params_init(&mc->dh_params);
 
511
  ret = gnutls_dh_params_init(&mc.dh_params);
441
512
  if(ret != GNUTLS_E_SUCCESS){
442
513
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
443
514
            " %s\n", safer_gnutls_strerror(ret));
444
515
    goto globalfail;
445
516
  }
446
 
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
 
517
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
447
518
  if(ret != GNUTLS_E_SUCCESS){
448
519
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
449
520
            safer_gnutls_strerror(ret));
450
521
    goto globalfail;
451
522
  }
452
523
  
453
 
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
 
524
  gnutls_certificate_set_dh_params(mc.cred, mc.dh_params);
454
525
  
455
526
  return 0;
456
527
  
457
528
 globalfail:
458
529
  
459
 
  gnutls_certificate_free_credentials(mc->cred);
 
530
  gnutls_certificate_free_credentials(mc.cred);
460
531
  gnutls_global_deinit();
461
 
  gnutls_dh_params_deinit(mc->dh_params);
 
532
  gnutls_dh_params_deinit(mc.dh_params);
462
533
  return -1;
463
534
}
464
535
 
465
 
static int init_gnutls_session(mandos_context *mc,
466
 
                               gnutls_session_t *session){
 
536
static int init_gnutls_session(gnutls_session_t *session){
467
537
  int ret;
468
538
  /* GnuTLS session creation */
469
 
  ret = gnutls_init(session, GNUTLS_SERVER);
 
539
  do {
 
540
    ret = gnutls_init(session, GNUTLS_SERVER);
 
541
    if(quit_now){
 
542
      return -1;
 
543
    }
 
544
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
470
545
  if(ret != GNUTLS_E_SUCCESS){
471
546
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
472
547
            safer_gnutls_strerror(ret));
474
549
  
475
550
  {
476
551
    const char *err;
477
 
    ret = gnutls_priority_set_direct(*session, mc->priority, &err);
 
552
    do {
 
553
      ret = gnutls_priority_set_direct(*session, mc.priority, &err);
 
554
      if(quit_now){
 
555
        gnutls_deinit(*session);
 
556
        return -1;
 
557
      }
 
558
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
478
559
    if(ret != GNUTLS_E_SUCCESS){
479
560
      fprintf(stderr, "Syntax error at: %s\n", err);
480
561
      fprintf(stderr, "GnuTLS error: %s\n",
484
565
    }
485
566
  }
486
567
  
487
 
  ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
488
 
                               mc->cred);
 
568
  do {
 
569
    ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
 
570
                                 mc.cred);
 
571
    if(quit_now){
 
572
      gnutls_deinit(*session);
 
573
      return -1;
 
574
    }
 
575
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
489
576
  if(ret != GNUTLS_E_SUCCESS){
490
577
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
491
578
            safer_gnutls_strerror(ret));
494
581
  }
495
582
  
496
583
  /* ignore client certificate if any. */
497
 
  gnutls_certificate_server_set_request(*session,
498
 
                                        GNUTLS_CERT_IGNORE);
 
584
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
499
585
  
500
 
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
 
586
  gnutls_dh_set_prime_bits(*session, mc.dh_bits);
501
587
  
502
588
  return 0;
503
589
}
509
595
/* Called when a Mandos server is found */
510
596
static int start_mandos_communication(const char *ip, uint16_t port,
511
597
                                      AvahiIfIndex if_index,
512
 
                                      mandos_context *mc, int af){
513
 
  int ret, tcp_sd;
 
598
                                      int af){
 
599
  int ret, tcp_sd = -1;
514
600
  ssize_t sret;
515
601
  union {
516
602
    struct sockaddr_in in;
517
603
    struct sockaddr_in6 in6;
518
604
  } to;
519
605
  char *buffer = NULL;
520
 
  char *decrypted_buffer;
 
606
  char *decrypted_buffer = NULL;
521
607
  size_t buffer_length = 0;
522
608
  size_t buffer_capacity = 0;
523
 
  ssize_t decrypted_buffer_size;
524
609
  size_t written;
525
 
  int retval = 0;
 
610
  int retval = -1;
526
611
  gnutls_session_t session;
527
612
  int pf;                       /* Protocol family */
528
613
  
 
614
  errno = 0;
 
615
  
 
616
  if(quit_now){
 
617
    errno = EINTR;
 
618
    return -1;
 
619
  }
 
620
  
529
621
  switch(af){
530
622
  case AF_INET6:
531
623
    pf = PF_INET6;
535
627
    break;
536
628
  default:
537
629
    fprintf(stderr, "Bad address family: %d\n", af);
 
630
    errno = EINVAL;
538
631
    return -1;
539
632
  }
540
633
  
541
 
  ret = init_gnutls_session(mc, &session);
 
634
  ret = init_gnutls_session(&session);
542
635
  if(ret != 0){
543
636
    return -1;
544
637
  }
550
643
  
551
644
  tcp_sd = socket(pf, SOCK_STREAM, 0);
552
645
  if(tcp_sd < 0){
553
 
    perror("socket");
554
 
    return -1;
 
646
    int e = errno;
 
647
    perror_plus("socket");
 
648
    errno = e;
 
649
    goto mandos_end;
 
650
  }
 
651
  
 
652
  if(quit_now){
 
653
    errno = EINTR;
 
654
    goto mandos_end;
555
655
  }
556
656
  
557
657
  memset(&to, 0, sizeof(to));
558
658
  if(af == AF_INET6){
559
 
    to.in6.sin6_family = (uint16_t)af;
 
659
    to.in6.sin6_family = (sa_family_t)af;
560
660
    ret = inet_pton(af, ip, &to.in6.sin6_addr);
561
661
  } else {                      /* IPv4 */
562
662
    to.in.sin_family = (sa_family_t)af;
563
663
    ret = inet_pton(af, ip, &to.in.sin_addr);
564
664
  }
565
665
  if(ret < 0 ){
566
 
    perror("inet_pton");
567
 
    return -1;
 
666
    int e = errno;
 
667
    perror_plus("inet_pton");
 
668
    errno = e;
 
669
    goto mandos_end;
568
670
  }
569
671
  if(ret == 0){
 
672
    int e = errno;
570
673
    fprintf(stderr, "Bad address: %s\n", ip);
571
 
    return -1;
 
674
    errno = e;
 
675
    goto mandos_end;
572
676
  }
573
677
  if(af == AF_INET6){
574
678
    to.in6.sin6_port = htons(port); /* Spurious warnings from
581
685
      if(if_index == AVAHI_IF_UNSPEC){
582
686
        fprintf(stderr, "An IPv6 link-local address is incomplete"
583
687
                " without a network interface\n");
584
 
        return -1;
 
688
        errno = EINVAL;
 
689
        goto mandos_end;
585
690
      }
586
691
      /* Set the network interface number as scope */
587
692
      to.in6.sin6_scope_id = (uint32_t)if_index;
592
697
                                     -Wunreachable-code */
593
698
  }
594
699
  
 
700
  if(quit_now){
 
701
    errno = EINTR;
 
702
    goto mandos_end;
 
703
  }
 
704
  
595
705
  if(debug){
596
706
    if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
597
707
      char interface[IF_NAMESIZE];
598
708
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
599
 
        perror("if_indextoname");
 
709
        perror_plus("if_indextoname");
600
710
      } else {
601
711
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
602
712
                ip, interface, port);
616
726
                        sizeof(addrstr));
617
727
    }
618
728
    if(pcret == NULL){
619
 
      perror("inet_ntop");
 
729
      perror_plus("inet_ntop");
620
730
    } else {
621
731
      if(strcmp(addrstr, ip) != 0){
622
732
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
624
734
    }
625
735
  }
626
736
  
 
737
  if(quit_now){
 
738
    errno = EINTR;
 
739
    goto mandos_end;
 
740
  }
 
741
  
627
742
  if(af == AF_INET6){
628
743
    ret = connect(tcp_sd, &to.in6, sizeof(to));
629
744
  } else {
630
745
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
631
746
  }
632
747
  if(ret < 0){
633
 
    perror("connect");
634
 
    return -1;
 
748
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
 
749
      int e = errno;
 
750
      perror_plus("connect");
 
751
      errno = e;
 
752
    }
 
753
    goto mandos_end;
 
754
  }
 
755
  
 
756
  if(quit_now){
 
757
    errno = EINTR;
 
758
    goto mandos_end;
635
759
  }
636
760
  
637
761
  const char *out = mandos_protocol_version;
641
765
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
642
766
                                   out_size - written));
643
767
    if(ret == -1){
644
 
      perror("write");
645
 
      retval = -1;
 
768
      int e = errno;
 
769
      perror_plus("write");
 
770
      errno = e;
646
771
      goto mandos_end;
647
772
    }
648
773
    written += (size_t)ret;
656
781
        break;
657
782
      }
658
783
    }
 
784
  
 
785
    if(quit_now){
 
786
      errno = EINTR;
 
787
      goto mandos_end;
 
788
    }
659
789
  }
660
790
  
661
791
  if(debug){
662
792
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
663
793
  }
664
794
  
 
795
  if(quit_now){
 
796
    errno = EINTR;
 
797
    goto mandos_end;
 
798
  }
 
799
  
 
800
  /* Spurious warning from -Wint-to-pointer-cast */
665
801
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
666
802
  
667
 
  do{
 
803
  if(quit_now){
 
804
    errno = EINTR;
 
805
    goto mandos_end;
 
806
  }
 
807
  
 
808
  do {
668
809
    ret = gnutls_handshake(session);
 
810
    if(quit_now){
 
811
      errno = EINTR;
 
812
      goto mandos_end;
 
813
    }
669
814
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
670
815
  
671
816
  if(ret != GNUTLS_E_SUCCESS){
673
818
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
674
819
      gnutls_perror(ret);
675
820
    }
676
 
    retval = -1;
 
821
    errno = EPROTO;
677
822
    goto mandos_end;
678
823
  }
679
824
  
685
830
  }
686
831
  
687
832
  while(true){
688
 
    buffer_capacity = adjustbuffer(&buffer, buffer_length,
 
833
    
 
834
    if(quit_now){
 
835
      errno = EINTR;
 
836
      goto mandos_end;
 
837
    }
 
838
    
 
839
    buffer_capacity = incbuffer(&buffer, buffer_length,
689
840
                                   buffer_capacity);
690
841
    if(buffer_capacity == 0){
691
 
      perror("adjustbuffer");
692
 
      retval = -1;
 
842
      int e = errno;
 
843
      perror_plus("incbuffer");
 
844
      errno = e;
 
845
      goto mandos_end;
 
846
    }
 
847
    
 
848
    if(quit_now){
 
849
      errno = EINTR;
693
850
      goto mandos_end;
694
851
    }
695
852
    
704
861
      case GNUTLS_E_AGAIN:
705
862
        break;
706
863
      case GNUTLS_E_REHANDSHAKE:
707
 
        do{
 
864
        do {
708
865
          ret = gnutls_handshake(session);
 
866
          
 
867
          if(quit_now){
 
868
            errno = EINTR;
 
869
            goto mandos_end;
 
870
          }
709
871
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
710
872
        if(ret < 0){
711
873
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
712
874
          gnutls_perror(ret);
713
 
          retval = -1;
 
875
          errno = EPROTO;
714
876
          goto mandos_end;
715
877
        }
716
878
        break;
717
879
      default:
718
880
        fprintf(stderr, "Unknown error while reading data from"
719
881
                " encrypted session with Mandos server\n");
720
 
        retval = -1;
721
882
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
 
883
        errno = EIO;
722
884
        goto mandos_end;
723
885
      }
724
886
    } else {
730
892
    fprintf(stderr, "Closing TLS session\n");
731
893
  }
732
894
  
733
 
  gnutls_bye(session, GNUTLS_SHUT_RDWR);
 
895
  if(quit_now){
 
896
    errno = EINTR;
 
897
    goto mandos_end;
 
898
  }
 
899
  
 
900
  do {
 
901
    ret = gnutls_bye(session, GNUTLS_SHUT_RDWR);
 
902
    if(quit_now){
 
903
      errno = EINTR;
 
904
      goto mandos_end;
 
905
    }
 
906
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
734
907
  
735
908
  if(buffer_length > 0){
736
 
    decrypted_buffer_size = pgp_packet_decrypt(mc, buffer,
 
909
    ssize_t decrypted_buffer_size;
 
910
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
737
911
                                               buffer_length,
738
912
                                               &decrypted_buffer);
739
913
    if(decrypted_buffer_size >= 0){
 
914
      
740
915
      written = 0;
741
916
      while(written < (size_t) decrypted_buffer_size){
 
917
        if(quit_now){
 
918
          errno = EINTR;
 
919
          goto mandos_end;
 
920
        }
 
921
        
742
922
        ret = (int)fwrite(decrypted_buffer + written, 1,
743
923
                          (size_t)decrypted_buffer_size - written,
744
924
                          stdout);
745
925
        if(ret == 0 and ferror(stdout)){
 
926
          int e = errno;
746
927
          if(debug){
747
928
            fprintf(stderr, "Error writing encrypted data: %s\n",
748
929
                    strerror(errno));
749
930
          }
750
 
          retval = -1;
751
 
          break;
 
931
          errno = e;
 
932
          goto mandos_end;
752
933
        }
753
934
        written += (size_t)ret;
754
935
      }
755
 
      free(decrypted_buffer);
756
 
    } else {
757
 
      retval = -1;
 
936
      retval = 0;
758
937
    }
759
 
  } else {
760
 
    retval = -1;
761
938
  }
762
939
  
763
940
  /* Shutdown procedure */
764
941
  
765
942
 mandos_end:
766
 
  free(buffer);
767
 
  ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
768
 
  if(ret == -1){
769
 
    perror("close");
 
943
  {
 
944
    int e = errno;
 
945
    free(decrypted_buffer);
 
946
    free(buffer);
 
947
    if(tcp_sd >= 0){
 
948
      ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
 
949
    }
 
950
    if(ret == -1){
 
951
      if(e == 0){
 
952
        e = errno;
 
953
      }
 
954
      perror_plus("close");
 
955
    }
 
956
    gnutls_deinit(session);
 
957
    errno = e;
 
958
    if(quit_now){
 
959
      errno = EINTR;
 
960
      retval = -1;
 
961
    }
770
962
  }
771
 
  gnutls_deinit(session);
772
963
  return retval;
773
964
}
774
965
 
785
976
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
786
977
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
787
978
                             flags,
788
 
                             void* userdata){
789
 
  mandos_context *mc = userdata;
 
979
                             AVAHI_GCC_UNUSED void* userdata){
790
980
  assert(r);
791
981
  
792
982
  /* Called whenever a service has been resolved successfully or
793
983
     timed out */
794
984
  
 
985
  if(quit_now){
 
986
    return;
 
987
  }
 
988
  
795
989
  switch(event){
796
990
  default:
797
991
  case AVAHI_RESOLVER_FAILURE:
798
992
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
799
993
            " of type '%s' in domain '%s': %s\n", name, type, domain,
800
 
            avahi_strerror(avahi_server_errno(mc->server)));
 
994
            avahi_strerror(avahi_server_errno(mc.server)));
801
995
    break;
802
996
    
803
997
  case AVAHI_RESOLVER_FOUND:
809
1003
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
810
1004
                ip, (intmax_t)interface, port);
811
1005
      }
812
 
      int ret = start_mandos_communication(ip, port, interface, mc,
 
1006
      int ret = start_mandos_communication(ip, port, interface,
813
1007
                                           avahi_proto_to_af(proto));
814
1008
      if(ret == 0){
815
 
        avahi_simple_poll_quit(mc->simple_poll);
 
1009
        avahi_simple_poll_quit(mc.simple_poll);
 
1010
      } else {
 
1011
        ret = add_server(ip, port, interface,
 
1012
                         avahi_proto_to_af(proto));
816
1013
      }
817
1014
    }
818
1015
  }
828
1025
                            const char *domain,
829
1026
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
830
1027
                            flags,
831
 
                            void* userdata){
832
 
  mandos_context *mc = userdata;
 
1028
                            AVAHI_GCC_UNUSED void* userdata){
833
1029
  assert(b);
834
1030
  
835
1031
  /* Called whenever a new services becomes available on the LAN or
836
1032
     is removed from the LAN */
837
1033
  
 
1034
  if(quit_now){
 
1035
    return;
 
1036
  }
 
1037
  
838
1038
  switch(event){
839
1039
  default:
840
1040
  case AVAHI_BROWSER_FAILURE:
841
1041
    
842
1042
    fprintf(stderr, "(Avahi browser) %s\n",
843
 
            avahi_strerror(avahi_server_errno(mc->server)));
844
 
    avahi_simple_poll_quit(mc->simple_poll);
 
1043
            avahi_strerror(avahi_server_errno(mc.server)));
 
1044
    avahi_simple_poll_quit(mc.simple_poll);
845
1045
    return;
846
1046
    
847
1047
  case AVAHI_BROWSER_NEW:
850
1050
       the callback function is called the Avahi server will free the
851
1051
       resolver for us. */
852
1052
    
853
 
    if(!(avahi_s_service_resolver_new(mc->server, interface,
854
 
                                       protocol, name, type, domain,
855
 
                                       AVAHI_PROTO_INET6, 0,
856
 
                                       resolve_callback, mc)))
 
1053
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
 
1054
                                    name, type, domain, protocol, 0,
 
1055
                                    resolve_callback, NULL) == NULL)
857
1056
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
858
 
              name, avahi_strerror(avahi_server_errno(mc->server)));
 
1057
              name, avahi_strerror(avahi_server_errno(mc.server)));
859
1058
    break;
860
1059
    
861
1060
  case AVAHI_BROWSER_REMOVE:
870
1069
  }
871
1070
}
872
1071
 
 
1072
/* Signal handler that stops main loop after SIGTERM */
 
1073
static void handle_sigterm(int sig){
 
1074
  if(quit_now){
 
1075
    return;
 
1076
  }
 
1077
  quit_now = 1;
 
1078
  signal_received = sig;
 
1079
  int old_errno = errno;
 
1080
  /* set main loop to exit */
 
1081
  if(mc.simple_poll != NULL){
 
1082
    avahi_simple_poll_quit(mc.simple_poll);
 
1083
  }
 
1084
  errno = old_errno;
 
1085
}
 
1086
 
 
1087
/* 
 
1088
 * This function determines if a directory entry in /sys/class/net
 
1089
 * corresponds to an acceptable network device.
 
1090
 * (This function is passed to scandir(3) as a filter function.)
 
1091
 */
 
1092
int good_interface(const struct dirent *if_entry){
 
1093
  ssize_t ssret;
 
1094
  char *flagname = NULL;
 
1095
  if(if_entry->d_name[0] == '.'){
 
1096
    return 0;
 
1097
  }
 
1098
  int ret = asprintf(&flagname, "%s/%s/flags", sys_class_net,
 
1099
                     if_entry->d_name);
 
1100
  if(ret < 0){
 
1101
    perror_plus("asprintf");
 
1102
    return 0;
 
1103
  }
 
1104
  int flags_fd = (int)TEMP_FAILURE_RETRY(open(flagname, O_RDONLY));
 
1105
  if(flags_fd == -1){
 
1106
    perror_plus("open");
 
1107
    free(flagname);
 
1108
    return 0;
 
1109
  }
 
1110
  free(flagname);
 
1111
  typedef short ifreq_flags;    /* ifreq.ifr_flags in netdevice(7) */
 
1112
  /* read line from flags_fd */
 
1113
  ssize_t to_read = 2+(sizeof(ifreq_flags)*2)+1; /* "0x1003\n" */
 
1114
  char *flagstring = malloc((size_t)to_read+1); /* +1 for final \0 */
 
1115
  flagstring[(size_t)to_read] = '\0';
 
1116
  if(flagstring == NULL){
 
1117
    perror_plus("malloc");
 
1118
    close(flags_fd);
 
1119
    return 0;
 
1120
  }
 
1121
  while(to_read > 0){
 
1122
    ssret = (ssize_t)TEMP_FAILURE_RETRY(read(flags_fd, flagstring,
 
1123
                                             (size_t)to_read));
 
1124
    if(ssret == -1){
 
1125
      perror_plus("read");
 
1126
      free(flagstring);
 
1127
      close(flags_fd);
 
1128
      return 0;
 
1129
    }
 
1130
    to_read -= ssret;
 
1131
    if(ssret == 0){
 
1132
      break;
 
1133
    }
 
1134
  }
 
1135
  close(flags_fd);
 
1136
  intmax_t tmpmax;
 
1137
  char *tmp;
 
1138
  errno = 0;
 
1139
  tmpmax = strtoimax(flagstring, &tmp, 0);
 
1140
  if(errno != 0 or tmp == flagstring or (*tmp != '\0'
 
1141
                                         and not (isspace(*tmp)))
 
1142
     or tmpmax != (ifreq_flags)tmpmax){
 
1143
    if(debug){
 
1144
      fprintf(stderr, "Invalid flags \"%s\" for interface \"%s\"\n",
 
1145
              flagstring, if_entry->d_name);
 
1146
    }
 
1147
    free(flagstring);
 
1148
    return 0;
 
1149
  }
 
1150
  free(flagstring);
 
1151
  ifreq_flags flags = (ifreq_flags)tmpmax;
 
1152
  /* Reject the loopback device */
 
1153
  if(flags & IFF_LOOPBACK){
 
1154
    if(debug){
 
1155
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
 
1156
              if_entry->d_name);
 
1157
    }
 
1158
    return 0;
 
1159
  }
 
1160
  /* Accept point-to-point devices only if connect_to is specified */
 
1161
  if(connect_to != NULL and (flags & IFF_POINTOPOINT)){
 
1162
    if(debug){
 
1163
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
 
1164
              if_entry->d_name);
 
1165
    }
 
1166
    return 1;
 
1167
  }
 
1168
  /* Otherwise, reject non-broadcast-capable devices */
 
1169
  if(not (flags & IFF_BROADCAST)){
 
1170
    if(debug){
 
1171
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
 
1172
              if_entry->d_name);
 
1173
    }
 
1174
    return 0;
 
1175
  }
 
1176
  /* Reject non-ARP interfaces (including dummy interfaces) */
 
1177
  if(flags & IFF_NOARP){
 
1178
    if(debug){
 
1179
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n",
 
1180
              if_entry->d_name);
 
1181
    }
 
1182
    return 0;
 
1183
  }
 
1184
  /* Accept this device */
 
1185
  if(debug){
 
1186
    fprintf(stderr, "Interface \"%s\" is acceptable\n",
 
1187
            if_entry->d_name);
 
1188
  }
 
1189
  return 1;
 
1190
}
 
1191
 
 
1192
int notdotentries(const struct dirent *direntry){
 
1193
  /* Skip "." and ".." */
 
1194
  if(direntry->d_name[0] == '.'
 
1195
     and (direntry->d_name[1] == '\0'
 
1196
          or (direntry->d_name[1] == '.'
 
1197
              and direntry->d_name[2] == '\0'))){
 
1198
    return 0;
 
1199
  }
 
1200
  return 1;
 
1201
}
 
1202
 
 
1203
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
 
1204
  int ret;
 
1205
  struct timespec now;
 
1206
  struct timespec waited_time;
 
1207
  intmax_t block_time;
 
1208
 
 
1209
  while(true){
 
1210
    if(mc.current_server == NULL){
 
1211
      if (debug){
 
1212
        fprintf(stderr,
 
1213
                "Wait until first server is found. No timeout!\n");
 
1214
      }
 
1215
      ret = avahi_simple_poll_iterate(s, -1);
 
1216
    } else {
 
1217
      if (debug){
 
1218
        fprintf(stderr, "Check current_server if we should run it,"
 
1219
                " or wait\n");
 
1220
      }
 
1221
      /* the current time */
 
1222
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
 
1223
      if(ret == -1){
 
1224
        perror_plus("clock_gettime");
 
1225
        return -1;
 
1226
      }
 
1227
      /* Calculating in ms how long time between now and server
 
1228
         who we visted longest time ago. Now - last seen.  */
 
1229
      waited_time.tv_sec = (now.tv_sec
 
1230
                            - mc.current_server->last_seen.tv_sec);
 
1231
      waited_time.tv_nsec = (now.tv_nsec
 
1232
                             - mc.current_server->last_seen.tv_nsec);
 
1233
      /* total time is 10s/10,000ms.
 
1234
         Converting to s from ms by dividing by 1,000,
 
1235
         and ns to ms by dividing by 1,000,000. */
 
1236
      block_time = ((retry_interval
 
1237
                     - ((intmax_t)waited_time.tv_sec * 1000))
 
1238
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
 
1239
 
 
1240
      if (debug){
 
1241
        fprintf(stderr, "Blocking for %ld ms\n", block_time);
 
1242
      }
 
1243
 
 
1244
      if(block_time <= 0){
 
1245
        ret = start_mandos_communication(mc.current_server->ip,
 
1246
                                         mc.current_server->port,
 
1247
                                         mc.current_server->if_index,
 
1248
                                         mc.current_server->af);
 
1249
        if(ret == 0){
 
1250
          avahi_simple_poll_quit(mc.simple_poll);
 
1251
          return 0;
 
1252
        }
 
1253
        ret = clock_gettime(CLOCK_MONOTONIC,
 
1254
                            &mc.current_server->last_seen);
 
1255
        if(ret == -1){
 
1256
          perror_plus("clock_gettime");
 
1257
          return -1;
 
1258
        }
 
1259
        mc.current_server = mc.current_server->next;
 
1260
        block_time = 0;         /* Call avahi to find new Mandos
 
1261
                                   servers, but don't block */
 
1262
      }
 
1263
      
 
1264
      ret = avahi_simple_poll_iterate(s, (int)block_time);
 
1265
    }
 
1266
    if(ret != 0){
 
1267
      if (ret > 0 or errno != EINTR) {
 
1268
        return (ret != 1) ? ret : 0;
 
1269
      }
 
1270
    }
 
1271
  }
 
1272
}
 
1273
 
873
1274
int main(int argc, char *argv[]){
874
1275
  AvahiSServiceBrowser *sb = NULL;
875
1276
  int error;
876
1277
  int ret;
877
1278
  intmax_t tmpmax;
878
 
  int numchars;
 
1279
  char *tmp;
879
1280
  int exitcode = EXIT_SUCCESS;
880
 
  const char *interface = "eth0";
 
1281
  const char *interface = "";
881
1282
  struct ifreq network;
882
 
  int sd;
 
1283
  int sd = -1;
 
1284
  bool take_down_interface = false;
883
1285
  uid_t uid;
884
1286
  gid_t gid;
885
 
  char *connect_to = NULL;
886
1287
  char tempdir[] = "/tmp/mandosXXXXXX";
887
1288
  bool tempdir_created = false;
888
1289
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
889
1290
  const char *seckey = PATHDIR "/" SECKEY;
890
1291
  const char *pubkey = PATHDIR "/" PUBKEY;
891
1292
  
892
 
  mandos_context mc = { .simple_poll = NULL, .server = NULL,
893
 
                        .dh_bits = 1024, .priority = "SECURE256"
894
 
                        ":!CTYPE-X.509:+CTYPE-OPENPGP" };
895
1293
  bool gnutls_initialized = false;
896
1294
  bool gpgme_initialized = false;
897
 
  double delay = 2.5;
 
1295
  float delay = 2.5f;
 
1296
  double retry_interval = 10; /* 10s between trying a server and
 
1297
                                 retrying the same server again */
 
1298
  
 
1299
  struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
 
1300
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
 
1301
  
 
1302
  uid = getuid();
 
1303
  gid = getgid();
 
1304
  
 
1305
  /* Lower any group privileges we might have, just to be safe */
 
1306
  errno = 0;
 
1307
  ret = setgid(gid);
 
1308
  if(ret == -1){
 
1309
    perror_plus("setgid");
 
1310
  }
 
1311
  
 
1312
  /* Lower user privileges (temporarily) */
 
1313
  errno = 0;
 
1314
  ret = seteuid(uid);
 
1315
  if(ret == -1){
 
1316
    perror_plus("seteuid");
 
1317
  }
 
1318
  
 
1319
  if(quit_now){
 
1320
    goto end;
 
1321
  }
898
1322
  
899
1323
  {
900
1324
    struct argp_option options[] = {
930
1354
        .arg = "SECONDS",
931
1355
        .doc = "Maximum delay to wait for interface startup",
932
1356
        .group = 2 },
 
1357
      { .name = "retry", .key = 132,
 
1358
        .arg = "SECONDS",
 
1359
        .doc = "Retry interval used when denied by the mandos server",
 
1360
        .group = 2 },
 
1361
      /*
 
1362
       * These reproduce what we would get without ARGP_NO_HELP
 
1363
       */
 
1364
      { .name = "help", .key = '?',
 
1365
        .doc = "Give this help list", .group = -1 },
 
1366
      { .name = "usage", .key = -3,
 
1367
        .doc = "Give a short usage message", .group = -1 },
 
1368
      { .name = "version", .key = 'V',
 
1369
        .doc = "Print program version", .group = -1 },
933
1370
      { .name = NULL }
934
1371
    };
935
1372
    
936
1373
    error_t parse_opt(int key, char *arg,
937
1374
                      struct argp_state *state){
 
1375
      errno = 0;
938
1376
      switch(key){
939
1377
      case 128:                 /* --debug */
940
1378
        debug = true;
952
1390
        pubkey = arg;
953
1391
        break;
954
1392
      case 129:                 /* --dh-bits */
955
 
        ret = sscanf(arg, "%" SCNdMAX "%n", &tmpmax, &numchars);
956
 
        if(ret < 1 or tmpmax != (typeof(mc.dh_bits))tmpmax
957
 
           or arg[numchars] != '\0'){
958
 
          fprintf(stderr, "Bad number of DH bits\n");
959
 
          exit(EXIT_FAILURE);
 
1393
        errno = 0;
 
1394
        tmpmax = strtoimax(arg, &tmp, 10);
 
1395
        if(errno != 0 or tmp == arg or *tmp != '\0'
 
1396
           or tmpmax != (typeof(mc.dh_bits))tmpmax){
 
1397
          argp_error(state, "Bad number of DH bits");
960
1398
        }
961
1399
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
962
1400
        break;
964
1402
        mc.priority = arg;
965
1403
        break;
966
1404
      case 131:                 /* --delay */
967
 
        ret = sscanf(arg, "%lf%n", &delay, &numchars);
968
 
        if(ret < 1 or arg[numchars] != '\0'){
969
 
          fprintf(stderr, "Bad delay\n");
970
 
          exit(EXIT_FAILURE);
 
1405
        errno = 0;
 
1406
        delay = strtof(arg, &tmp);
 
1407
        if(errno != 0 or tmp == arg or *tmp != '\0'){
 
1408
          argp_error(state, "Bad delay");
 
1409
        }
 
1410
      case 132:                 /* --retry */
 
1411
        errno = 0;
 
1412
        retry_interval = strtod(arg, &tmp);
 
1413
        if(errno != 0 or tmp == arg or *tmp != '\0'
 
1414
           or (retry_interval * 1000) > INT_MAX){
 
1415
          argp_error(state, "Bad retry interval");
971
1416
        }
972
1417
        break;
973
 
      case ARGP_KEY_ARG:
974
 
        argp_usage(state);
975
 
      case ARGP_KEY_END:
 
1418
        /*
 
1419
         * These reproduce what we would get without ARGP_NO_HELP
 
1420
         */
 
1421
      case '?':                 /* --help */
 
1422
        argp_state_help(state, state->out_stream,
 
1423
                        (ARGP_HELP_STD_HELP | ARGP_HELP_EXIT_ERR)
 
1424
                        & ~(unsigned int)ARGP_HELP_EXIT_OK);
 
1425
      case -3:                  /* --usage */
 
1426
        argp_state_help(state, state->out_stream,
 
1427
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
 
1428
      case 'V':                 /* --version */
 
1429
        fprintf(state->out_stream, "%s\n", argp_program_version);
 
1430
        exit(argp_err_exit_status);
976
1431
        break;
977
1432
      default:
978
1433
        return ARGP_ERR_UNKNOWN;
979
1434
      }
980
 
      return 0;
 
1435
      return errno;
981
1436
    }
982
1437
    
983
1438
    struct argp argp = { .options = options, .parser = parse_opt,
984
1439
                         .args_doc = "",
985
1440
                         .doc = "Mandos client -- Get and decrypt"
986
1441
                         " passwords from a Mandos server" };
987
 
    ret = argp_parse(&argp, argc, argv, 0, 0, NULL);
988
 
    if(ret == ARGP_ERR_UNKNOWN){
989
 
      fprintf(stderr, "Unknown error while parsing arguments\n");
 
1442
    ret = argp_parse(&argp, argc, argv,
 
1443
                     ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
 
1444
    switch(ret){
 
1445
    case 0:
 
1446
      break;
 
1447
    case ENOMEM:
 
1448
    default:
 
1449
      errno = ret;
 
1450
      perror_plus("argp_parse");
 
1451
      exitcode = EX_OSERR;
 
1452
      goto end;
 
1453
    case EINVAL:
 
1454
      exitcode = EX_USAGE;
 
1455
      goto end;
 
1456
    }
 
1457
  }
 
1458
    
 
1459
  {
 
1460
    /* Work around Debian bug #633582:
 
1461
       <http://bugs.debian.org/633582> */
 
1462
    struct stat st;
 
1463
    
 
1464
    /* Re-raise priviliges */
 
1465
    errno = 0;
 
1466
    ret = seteuid(0);
 
1467
    if(ret == -1){
 
1468
      perror_plus("seteuid");
 
1469
    }
 
1470
    
 
1471
    int seckey_fd = open(PATHDIR "/" SECKEY, O_RDONLY);
 
1472
    if(seckey_fd == -1){
 
1473
      perror_plus("open");
 
1474
    } else {
 
1475
      ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
 
1476
      if(ret == -1){
 
1477
        perror_plus("fstat");
 
1478
      } else {
 
1479
        if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
 
1480
          ret = fchown(seckey_fd, uid, gid);
 
1481
          if(ret == -1){
 
1482
            perror_plus("fchown");
 
1483
          }
 
1484
        }
 
1485
      }
 
1486
      TEMP_FAILURE_RETRY(close(seckey_fd));
 
1487
    }
 
1488
    
 
1489
    int pubkey_fd = open(PATHDIR "/" PUBKEY, O_RDONLY);
 
1490
    if(pubkey_fd == -1){
 
1491
      perror_plus("open");
 
1492
    } else {
 
1493
      ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
 
1494
      if(ret == -1){
 
1495
        perror_plus("fstat");
 
1496
      } else {
 
1497
        if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
 
1498
          ret = fchown(pubkey_fd, uid, gid);
 
1499
          if(ret == -1){
 
1500
            perror_plus("fchown");
 
1501
          }
 
1502
        }
 
1503
      }
 
1504
      TEMP_FAILURE_RETRY(close(pubkey_fd));
 
1505
    }
 
1506
    
 
1507
    /* Lower privileges */
 
1508
    errno = 0;
 
1509
    ret = seteuid(uid);
 
1510
    if(ret == -1){
 
1511
      perror_plus("seteuid");
 
1512
    }
 
1513
  }
 
1514
  
 
1515
  if(not debug){
 
1516
    avahi_set_log_function(empty_log);
 
1517
  }
 
1518
 
 
1519
  if(interface[0] == '\0'){
 
1520
    struct dirent **direntries;
 
1521
    ret = scandir(sys_class_net, &direntries, good_interface,
 
1522
                  alphasort);
 
1523
    if(ret >= 1){
 
1524
      /* Pick the first good interface */
 
1525
      interface = strdup(direntries[0]->d_name);
 
1526
      if(debug){
 
1527
        fprintf(stderr, "Using interface \"%s\"\n", interface);
 
1528
      }
 
1529
      if(interface == NULL){
 
1530
        perror_plus("malloc");
 
1531
        free(direntries);
 
1532
        exitcode = EXIT_FAILURE;
 
1533
        goto end;
 
1534
      }
 
1535
      free(direntries);
 
1536
    } else {
 
1537
      free(direntries);
 
1538
      fprintf(stderr, "Could not find a network interface\n");
990
1539
      exitcode = EXIT_FAILURE;
991
1540
      goto end;
992
1541
    }
993
1542
  }
994
1543
  
 
1544
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
 
1545
     from the signal handler */
 
1546
  /* Initialize the pseudo-RNG for Avahi */
 
1547
  srand((unsigned int) time(NULL));
 
1548
  mc.simple_poll = avahi_simple_poll_new();
 
1549
  if(mc.simple_poll == NULL){
 
1550
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
 
1551
    exitcode = EX_UNAVAILABLE;
 
1552
    goto end;
 
1553
  }
 
1554
  
 
1555
  sigemptyset(&sigterm_action.sa_mask);
 
1556
  ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
 
1557
  if(ret == -1){
 
1558
    perror_plus("sigaddset");
 
1559
    exitcode = EX_OSERR;
 
1560
    goto end;
 
1561
  }
 
1562
  ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
 
1563
  if(ret == -1){
 
1564
    perror_plus("sigaddset");
 
1565
    exitcode = EX_OSERR;
 
1566
    goto end;
 
1567
  }
 
1568
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
 
1569
  if(ret == -1){
 
1570
    perror_plus("sigaddset");
 
1571
    exitcode = EX_OSERR;
 
1572
    goto end;
 
1573
  }
 
1574
  /* Need to check if the handler is SIG_IGN before handling:
 
1575
     | [[info:libc:Initial Signal Actions]] |
 
1576
     | [[info:libc:Basic Signal Handling]]  |
 
1577
  */
 
1578
  ret = sigaction(SIGINT, NULL, &old_sigterm_action);
 
1579
  if(ret == -1){
 
1580
    perror_plus("sigaction");
 
1581
    return EX_OSERR;
 
1582
  }
 
1583
  if(old_sigterm_action.sa_handler != SIG_IGN){
 
1584
    ret = sigaction(SIGINT, &sigterm_action, NULL);
 
1585
    if(ret == -1){
 
1586
      perror_plus("sigaction");
 
1587
      exitcode = EX_OSERR;
 
1588
      goto end;
 
1589
    }
 
1590
  }
 
1591
  ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
 
1592
  if(ret == -1){
 
1593
    perror_plus("sigaction");
 
1594
    return EX_OSERR;
 
1595
  }
 
1596
  if(old_sigterm_action.sa_handler != SIG_IGN){
 
1597
    ret = sigaction(SIGHUP, &sigterm_action, NULL);
 
1598
    if(ret == -1){
 
1599
      perror_plus("sigaction");
 
1600
      exitcode = EX_OSERR;
 
1601
      goto end;
 
1602
    }
 
1603
  }
 
1604
  ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
 
1605
  if(ret == -1){
 
1606
    perror_plus("sigaction");
 
1607
    return EX_OSERR;
 
1608
  }
 
1609
  if(old_sigterm_action.sa_handler != SIG_IGN){
 
1610
    ret = sigaction(SIGTERM, &sigterm_action, NULL);
 
1611
    if(ret == -1){
 
1612
      perror_plus("sigaction");
 
1613
      exitcode = EX_OSERR;
 
1614
      goto end;
 
1615
    }
 
1616
  }
 
1617
  
995
1618
  /* If the interface is down, bring it up */
996
 
  if(interface[0] != '\0'){
 
1619
  if(strcmp(interface, "none") != 0){
 
1620
    if_index = (AvahiIfIndex) if_nametoindex(interface);
 
1621
    if(if_index == 0){
 
1622
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
 
1623
      exitcode = EX_UNAVAILABLE;
 
1624
      goto end;
 
1625
    }
 
1626
    
 
1627
    if(quit_now){
 
1628
      goto end;
 
1629
    }
 
1630
    
 
1631
    /* Re-raise priviliges */
 
1632
    errno = 0;
 
1633
    ret = seteuid(0);
 
1634
    if(ret == -1){
 
1635
      perror_plus("seteuid");
 
1636
    }
 
1637
    
997
1638
#ifdef __linux__
998
1639
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
999
 
       messages to mess up the prompt */
 
1640
       messages about the network interface to mess up the prompt */
1000
1641
    ret = klogctl(8, NULL, 5);
1001
1642
    bool restore_loglevel = true;
1002
1643
    if(ret == -1){
1003
1644
      restore_loglevel = false;
1004
 
      perror("klogctl");
 
1645
      perror_plus("klogctl");
1005
1646
    }
1006
 
#endif
 
1647
#endif  /* __linux__ */
1007
1648
    
1008
1649
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1009
1650
    if(sd < 0){
1010
 
      perror("socket");
1011
 
      exitcode = EXIT_FAILURE;
 
1651
      perror_plus("socket");
 
1652
      exitcode = EX_OSERR;
1012
1653
#ifdef __linux__
1013
1654
      if(restore_loglevel){
1014
1655
        ret = klogctl(7, NULL, 0);
1015
1656
        if(ret == -1){
1016
 
          perror("klogctl");
 
1657
          perror_plus("klogctl");
1017
1658
        }
1018
1659
      }
1019
 
#endif
 
1660
#endif  /* __linux__ */
 
1661
      /* Lower privileges */
 
1662
      errno = 0;
 
1663
      ret = seteuid(uid);
 
1664
      if(ret == -1){
 
1665
        perror_plus("seteuid");
 
1666
      }
1020
1667
      goto end;
1021
1668
    }
1022
1669
    strcpy(network.ifr_name, interface);
1023
1670
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
1024
1671
    if(ret == -1){
1025
 
      perror("ioctl SIOCGIFFLAGS");
 
1672
      perror_plus("ioctl SIOCGIFFLAGS");
1026
1673
#ifdef __linux__
1027
1674
      if(restore_loglevel){
1028
1675
        ret = klogctl(7, NULL, 0);
1029
1676
        if(ret == -1){
1030
 
          perror("klogctl");
 
1677
          perror_plus("klogctl");
1031
1678
        }
1032
1679
      }
1033
 
#endif
1034
 
      exitcode = EXIT_FAILURE;
 
1680
#endif  /* __linux__ */
 
1681
      exitcode = EX_OSERR;
 
1682
      /* Lower privileges */
 
1683
      errno = 0;
 
1684
      ret = seteuid(uid);
 
1685
      if(ret == -1){
 
1686
        perror_plus("seteuid");
 
1687
      }
1035
1688
      goto end;
1036
1689
    }
1037
1690
    if((network.ifr_flags & IFF_UP) == 0){
1038
1691
      network.ifr_flags |= IFF_UP;
 
1692
      take_down_interface = true;
1039
1693
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1040
1694
      if(ret == -1){
1041
 
        perror("ioctl SIOCSIFFLAGS");
1042
 
        exitcode = EXIT_FAILURE;
 
1695
        take_down_interface = false;
 
1696
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
 
1697
        exitcode = EX_OSERR;
1043
1698
#ifdef __linux__
1044
1699
        if(restore_loglevel){
1045
1700
          ret = klogctl(7, NULL, 0);
1046
1701
          if(ret == -1){
1047
 
            perror("klogctl");
 
1702
            perror_plus("klogctl");
1048
1703
          }
1049
1704
        }
1050
 
#endif
 
1705
#endif  /* __linux__ */
 
1706
        /* Lower privileges */
 
1707
        errno = 0;
 
1708
        ret = seteuid(uid);
 
1709
        if(ret == -1){
 
1710
          perror_plus("seteuid");
 
1711
        }
1051
1712
        goto end;
1052
1713
      }
1053
1714
    }
1054
 
    /* sleep checking until interface is running */
 
1715
    /* Sleep checking until interface is running.
 
1716
       Check every 0.25s, up to total time of delay */
1055
1717
    for(int i=0; i < delay * 4; i++){
1056
1718
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1057
1719
      if(ret == -1){
1058
 
        perror("ioctl SIOCGIFFLAGS");
 
1720
        perror_plus("ioctl SIOCGIFFLAGS");
1059
1721
      } else if(network.ifr_flags & IFF_RUNNING){
1060
1722
        break;
1061
1723
      }
1062
1724
      struct timespec sleeptime = { .tv_nsec = 250000000 };
1063
1725
      ret = nanosleep(&sleeptime, NULL);
1064
1726
      if(ret == -1 and errno != EINTR){
1065
 
        perror("nanosleep");
 
1727
        perror_plus("nanosleep");
1066
1728
      }
1067
1729
    }
1068
 
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
1069
 
    if(ret == -1){
1070
 
      perror("close");
 
1730
    if(not take_down_interface){
 
1731
      /* We won't need the socket anymore */
 
1732
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1733
      if(ret == -1){
 
1734
        perror_plus("close");
 
1735
      }
1071
1736
    }
1072
1737
#ifdef __linux__
1073
1738
    if(restore_loglevel){
1074
1739
      /* Restores kernel loglevel to default */
1075
1740
      ret = klogctl(7, NULL, 0);
1076
1741
      if(ret == -1){
1077
 
        perror("klogctl");
1078
 
      }
1079
 
    }
1080
 
#endif
1081
 
  }
1082
 
  
1083
 
  uid = getuid();
1084
 
  gid = getgid();
1085
 
  
1086
 
  errno = 0;
1087
 
  setgid(gid);
1088
 
  if(ret == -1){
1089
 
    perror("setgid");
1090
 
  }
1091
 
  
1092
 
  ret = setuid(uid);
1093
 
  if(ret == -1){
1094
 
    perror("setuid");
1095
 
  }
1096
 
  
1097
 
  ret = init_gnutls_global(&mc, pubkey, seckey);
 
1742
        perror_plus("klogctl");
 
1743
      }
 
1744
    }
 
1745
#endif  /* __linux__ */
 
1746
    /* Lower privileges */
 
1747
    errno = 0;
 
1748
    if(take_down_interface){
 
1749
      /* Lower privileges */
 
1750
      ret = seteuid(uid);
 
1751
      if(ret == -1){
 
1752
        perror_plus("seteuid");
 
1753
      }
 
1754
    } else {
 
1755
      /* Lower privileges permanently */
 
1756
      ret = setuid(uid);
 
1757
      if(ret == -1){
 
1758
        perror_plus("setuid");
 
1759
      }
 
1760
    }
 
1761
  }
 
1762
  
 
1763
  if(quit_now){
 
1764
    goto end;
 
1765
  }
 
1766
  
 
1767
  ret = init_gnutls_global(pubkey, seckey);
1098
1768
  if(ret == -1){
1099
1769
    fprintf(stderr, "init_gnutls_global failed\n");
1100
 
    exitcode = EXIT_FAILURE;
 
1770
    exitcode = EX_UNAVAILABLE;
1101
1771
    goto end;
1102
1772
  } else {
1103
1773
    gnutls_initialized = true;
1104
1774
  }
1105
1775
  
 
1776
  if(quit_now){
 
1777
    goto end;
 
1778
  }
 
1779
  
1106
1780
  if(mkdtemp(tempdir) == NULL){
1107
 
    perror("mkdtemp");
 
1781
    perror_plus("mkdtemp");
1108
1782
    goto end;
1109
1783
  }
1110
1784
  tempdir_created = true;
1111
1785
  
1112
 
  if(not init_gpgme(&mc, pubkey, seckey, tempdir)){
 
1786
  if(quit_now){
 
1787
    goto end;
 
1788
  }
 
1789
  
 
1790
  if(not init_gpgme(pubkey, seckey, tempdir)){
1113
1791
    fprintf(stderr, "init_gpgme failed\n");
1114
 
    exitcode = EXIT_FAILURE;
 
1792
    exitcode = EX_UNAVAILABLE;
1115
1793
    goto end;
1116
1794
  } else {
1117
1795
    gpgme_initialized = true;
1118
1796
  }
1119
1797
  
1120
 
  if(interface[0] != '\0'){
1121
 
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1122
 
    if(if_index == 0){
1123
 
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
1124
 
      exitcode = EXIT_FAILURE;
1125
 
      goto end;
1126
 
    }
 
1798
  if(quit_now){
 
1799
    goto end;
1127
1800
  }
1128
1801
  
1129
1802
  if(connect_to != NULL){
1132
1805
    char *address = strrchr(connect_to, ':');
1133
1806
    if(address == NULL){
1134
1807
      fprintf(stderr, "No colon in address\n");
1135
 
      exitcode = EXIT_FAILURE;
1136
 
      goto end;
1137
 
    }
 
1808
      exitcode = EX_USAGE;
 
1809
      goto end;
 
1810
    }
 
1811
    
 
1812
    if(quit_now){
 
1813
      goto end;
 
1814
    }
 
1815
    
1138
1816
    uint16_t port;
1139
 
    ret = sscanf(address+1, "%" SCNdMAX "%n", &tmpmax, &numchars);
1140
 
    if(ret < 1 or tmpmax != (uint16_t)tmpmax
1141
 
       or address[numchars+1] != '\0'){
 
1817
    errno = 0;
 
1818
    tmpmax = strtoimax(address+1, &tmp, 10);
 
1819
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
 
1820
       or tmpmax != (uint16_t)tmpmax){
1142
1821
      fprintf(stderr, "Bad port number\n");
1143
 
      exitcode = EXIT_FAILURE;
1144
 
      goto end;
1145
 
    }
 
1822
      exitcode = EX_USAGE;
 
1823
      goto end;
 
1824
    }
 
1825
  
 
1826
    if(quit_now){
 
1827
      goto end;
 
1828
    }
 
1829
    
1146
1830
    port = (uint16_t)tmpmax;
1147
1831
    *address = '\0';
1148
1832
    address = connect_to;
1153
1837
    } else {
1154
1838
      af = AF_INET;
1155
1839
    }
1156
 
    ret = start_mandos_communication(address, port, if_index, &mc,
1157
 
                                     af);
1158
 
    if(ret < 0){
1159
 
      exitcode = EXIT_FAILURE;
1160
 
    } else {
 
1840
    
 
1841
    if(quit_now){
 
1842
      goto end;
 
1843
    }
 
1844
 
 
1845
    while(not quit_now){
 
1846
      ret = start_mandos_communication(address, port, if_index, af);
 
1847
      if(quit_now or ret == 0){
 
1848
        break;
 
1849
      }
 
1850
      sleep((int)retry_interval or 1);
 
1851
    };
 
1852
 
 
1853
    if (not quit_now){
1161
1854
      exitcode = EXIT_SUCCESS;
1162
1855
    }
 
1856
 
1163
1857
    goto end;
1164
1858
  }
1165
1859
  
1166
 
  if(not debug){
1167
 
    avahi_set_log_function(empty_log);
1168
 
  }
1169
 
  
1170
 
  /* Initialize the pseudo-RNG for Avahi */
1171
 
  srand((unsigned int) time(NULL));
1172
 
  
1173
 
  /* Allocate main Avahi loop object */
1174
 
  mc.simple_poll = avahi_simple_poll_new();
1175
 
  if(mc.simple_poll == NULL){
1176
 
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
1177
 
    exitcode = EXIT_FAILURE;
 
1860
  if(quit_now){
1178
1861
    goto end;
1179
1862
  }
1180
1863
  
1200
1883
  if(mc.server == NULL){
1201
1884
    fprintf(stderr, "Failed to create Avahi server: %s\n",
1202
1885
            avahi_strerror(error));
1203
 
    exitcode = EXIT_FAILURE;
 
1886
    exitcode = EX_UNAVAILABLE;
 
1887
    goto end;
 
1888
  }
 
1889
  
 
1890
  if(quit_now){
1204
1891
    goto end;
1205
1892
  }
1206
1893
  
1207
1894
  /* Create the Avahi service browser */
1208
1895
  sb = avahi_s_service_browser_new(mc.server, if_index,
1209
 
                                   AVAHI_PROTO_INET6, "_mandos._tcp",
1210
 
                                   NULL, 0, browse_callback, &mc);
 
1896
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
 
1897
                                   NULL, 0, browse_callback, NULL);
1211
1898
  if(sb == NULL){
1212
1899
    fprintf(stderr, "Failed to create service browser: %s\n",
1213
1900
            avahi_strerror(avahi_server_errno(mc.server)));
1214
 
    exitcode = EXIT_FAILURE;
 
1901
    exitcode = EX_UNAVAILABLE;
 
1902
    goto end;
 
1903
  }
 
1904
  
 
1905
  if(quit_now){
1215
1906
    goto end;
1216
1907
  }
1217
1908
  
1220
1911
  if(debug){
1221
1912
    fprintf(stderr, "Starting Avahi loop search\n");
1222
1913
  }
1223
 
  
1224
 
  avahi_simple_poll_loop(mc.simple_poll);
 
1914
 
 
1915
  ret = avahi_loop_with_timeout(mc.simple_poll,
 
1916
                                (int)(retry_interval * 1000));
 
1917
  if(debug){
 
1918
    fprintf(stderr, "avahi_loop_with_timeout exited %s\n",
 
1919
            (ret == 0) ? "successfully" : "with error");
 
1920
  }
1225
1921
  
1226
1922
 end:
1227
1923
  
1248
1944
  if(gpgme_initialized){
1249
1945
    gpgme_release(mc.ctx);
1250
1946
  }
1251
 
  
1252
 
  /* Removes the temp directory used by GPGME */
 
1947
 
 
1948
  /* Cleans up the circular linked list of Mandos servers the client
 
1949
     has seen */
 
1950
  if(mc.current_server != NULL){
 
1951
    mc.current_server->prev->next = NULL;
 
1952
    while(mc.current_server != NULL){
 
1953
      server *next = mc.current_server->next;
 
1954
      free(mc.current_server);
 
1955
      mc.current_server = next;
 
1956
    }
 
1957
  }
 
1958
  
 
1959
  /* Take down the network interface */
 
1960
  if(take_down_interface){
 
1961
    /* Re-raise priviliges */
 
1962
    errno = 0;
 
1963
    ret = seteuid(0);
 
1964
    if(ret == -1){
 
1965
      perror_plus("seteuid");
 
1966
    }
 
1967
    if(geteuid() == 0){
 
1968
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
1969
      if(ret == -1){
 
1970
        perror_plus("ioctl SIOCGIFFLAGS");
 
1971
      } else if(network.ifr_flags & IFF_UP) {
 
1972
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
 
1973
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
1974
        if(ret == -1){
 
1975
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
 
1976
        }
 
1977
      }
 
1978
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1979
      if(ret == -1){
 
1980
        perror_plus("close");
 
1981
      }
 
1982
      /* Lower privileges permanently */
 
1983
      errno = 0;
 
1984
      ret = setuid(uid);
 
1985
      if(ret == -1){
 
1986
        perror_plus("setuid");
 
1987
      }
 
1988
    }
 
1989
  }
 
1990
  
 
1991
  /* Removes the GPGME temp directory and all files inside */
1253
1992
  if(tempdir_created){
1254
 
    DIR *d;
1255
 
    struct dirent *direntry;
1256
 
    d = opendir(tempdir);
1257
 
    if(d == NULL){
1258
 
      if(errno != ENOENT){
1259
 
        perror("opendir");
1260
 
      }
1261
 
    } else {
1262
 
      while(true){
1263
 
        direntry = readdir(d);
1264
 
        if(direntry == NULL){
1265
 
          break;
1266
 
        }
1267
 
        /* Skip "." and ".." */
1268
 
        if(direntry->d_name[0] == '.'
1269
 
           and (direntry->d_name[1] == '\0'
1270
 
                or (direntry->d_name[1] == '.'
1271
 
                    and direntry->d_name[2] == '\0'))){
1272
 
          continue;
1273
 
        }
 
1993
    struct dirent **direntries = NULL;
 
1994
    struct dirent *direntry = NULL;
 
1995
    ret = scandir(tempdir, &direntries, notdotentries, alphasort);
 
1996
    if (ret > 0){
 
1997
      for(int i = 0; i < ret; i++){
 
1998
        direntry = direntries[i];
1274
1999
        char *fullname = NULL;
1275
2000
        ret = asprintf(&fullname, "%s/%s", tempdir,
1276
2001
                       direntry->d_name);
1277
2002
        if(ret < 0){
1278
 
          perror("asprintf");
 
2003
          perror_plus("asprintf");
1279
2004
          continue;
1280
2005
        }
1281
2006
        ret = remove(fullname);
1285
2010
        }
1286
2011
        free(fullname);
1287
2012
      }
1288
 
      closedir(d);
 
2013
    }
 
2014
 
 
2015
    /* need to be cleaned even if ret == 0 because man page doesn't
 
2016
       specify */
 
2017
    free(direntries);
 
2018
    if (ret == -1){
 
2019
      perror_plus("scandir");
1289
2020
    }
1290
2021
    ret = rmdir(tempdir);
1291
2022
    if(ret == -1 and errno != ENOENT){
1292
 
      perror("rmdir");
1293
 
    }
 
2023
      perror_plus("rmdir");
 
2024
    }
 
2025
  }
 
2026
  
 
2027
  if(quit_now){
 
2028
    sigemptyset(&old_sigterm_action.sa_mask);
 
2029
    old_sigterm_action.sa_handler = SIG_DFL;
 
2030
    ret = (int)TEMP_FAILURE_RETRY(sigaction(signal_received,
 
2031
                                            &old_sigterm_action,
 
2032
                                            NULL));
 
2033
    if(ret == -1){
 
2034
      perror_plus("sigaction");
 
2035
    }
 
2036
    do {
 
2037
      ret = raise(signal_received);
 
2038
    } while(ret != 0 and errno == EINTR);
 
2039
    if(ret != 0){
 
2040
      perror_plus("raise");
 
2041
      abort();
 
2042
    }
 
2043
    TEMP_FAILURE_RETRY(pause());
1294
2044
  }
1295
2045
  
1296
2046
  return exitcode;