/mandos/release

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

« back to all changes in this revision

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

* plugin-runner.c: Comment change.

* plugins.d/mandos-client.c: Comment changes.
  (quit_now): New global flag.
  (handle_sigterm): Only call avahi_simple_poll_quit once.
  (main): Also handle SIGINT and SIGHUP.

Show diffs side-by-side

added added

removed removed

Lines of Context:
42
42
#include <stddef.h>             /* NULL, size_t, ssize_t */
43
43
#include <stdlib.h>             /* free(), EXIT_SUCCESS, EXIT_FAILURE,
44
44
                                   srand() */
45
 
#include <stdbool.h>            /* bool, true */
 
45
#include <stdbool.h>            /* bool, false, true */
46
46
#include <string.h>             /* memset(), strcmp(), strlen(),
47
47
                                   strerror(), asprintf(), strcpy() */
48
 
#include <sys/ioctl.h>          /* ioctl */
 
48
#include <sys/ioctl.h>          /* ioctl */
49
49
#include <sys/types.h>          /* socket(), inet_pton(), sockaddr,
50
50
                                   sockaddr_in6, PF_INET6,
51
 
                                   SOCK_STREAM, INET6_ADDRSTRLEN,
52
 
                                   uid_t, gid_t, open(), opendir(),
53
 
                                   DIR */
 
51
                                   SOCK_STREAM, uid_t, gid_t, open(),
 
52
                                   opendir(), DIR */
54
53
#include <sys/stat.h>           /* open() */
55
54
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
56
 
                                   struct in6_addr, inet_pton(),
57
 
                                   connect() */
 
55
                                   inet_pton(), connect() */
58
56
#include <fcntl.h>              /* open() */
59
57
#include <dirent.h>             /* opendir(), struct dirent, readdir()
60
58
                                 */
61
59
#include <inttypes.h>           /* PRIu16, intmax_t, SCNdMAX */
62
60
#include <assert.h>             /* assert() */
63
61
#include <errno.h>              /* perror(), errno */
64
 
#include <time.h>               /* time() */
 
62
#include <time.h>               /* nanosleep(), time() */
65
63
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
66
64
                                   SIOCSIFFLAGS, if_indextoname(),
67
65
                                   if_nametoindex(), IF_NAMESIZE */
68
 
#include <netinet/in.h>
 
66
#include <netinet/in.h>         /* IN6_IS_ADDR_LINKLOCAL,
 
67
                                   INET_ADDRSTRLEN, INET6_ADDRSTRLEN
 
68
                                */
69
69
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
70
70
                                   getuid(), getgid(), setuid(),
71
71
                                   setgid() */
72
72
#include <arpa/inet.h>          /* inet_pton(), htons */
73
 
#include <iso646.h>             /* not, and, or */
 
73
#include <iso646.h>             /* not, or, and */
74
74
#include <argp.h>               /* struct argp_option, error_t, struct
75
75
                                   argp_state, struct argp,
76
76
                                   argp_parse(), ARGP_KEY_ARG,
77
77
                                   ARGP_KEY_END, ARGP_ERR_UNKNOWN */
 
78
#include <signal.h>             /* sigemptyset(), sigaddset(),
 
79
                                   sigaction(), SIGTERM, sigaction,
 
80
                                   sig_atomic_t */
 
81
 
 
82
#ifdef __linux__
 
83
#include <sys/klog.h>           /* klogctl() */
 
84
#endif  /* __linux__ */
78
85
 
79
86
/* Avahi */
80
87
/* All Avahi types, constants and functions
126
133
  gpgme_ctx_t ctx;
127
134
} mandos_context;
128
135
 
 
136
/* global context so signal handler can reach it*/
 
137
mandos_context mc;
 
138
 
129
139
/*
130
 
 * Make room in "buffer" for at least BUFFER_SIZE additional bytes.
131
 
 * "buffer_capacity" is how much is currently allocated,
 
140
 * Make additional room in "buffer" for at least BUFFER_SIZE more
 
141
 * bytes. "buffer_capacity" is how much is currently allocated,
132
142
 * "buffer_length" is how much is already used.
133
143
 */
134
 
size_t adjustbuffer(char **buffer, size_t buffer_length,
 
144
size_t incbuffer(char **buffer, size_t buffer_length,
135
145
                  size_t buffer_capacity){
136
146
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
137
147
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
146
156
/* 
147
157
 * Initialize GPGME.
148
158
 */
149
 
static bool init_gpgme(mandos_context *mc, const char *seckey,
 
159
static bool init_gpgme(const char *seckey,
150
160
                       const char *pubkey, const char *tempdir){
151
161
  int ret;
152
162
  gpgme_error_t rc;
154
164
  
155
165
  
156
166
  /*
157
 
   * Helper function to insert pub and seckey to the enigne keyring.
 
167
   * Helper function to insert pub and seckey to the engine keyring.
158
168
   */
159
169
  bool import_key(const char *filename){
160
170
    int fd;
173
183
      return false;
174
184
    }
175
185
    
176
 
    rc = gpgme_op_import(mc->ctx, pgp_data);
 
186
    rc = gpgme_op_import(mc.ctx, pgp_data);
177
187
    if(rc != GPG_ERR_NO_ERROR){
178
188
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
179
189
              gpgme_strsource(rc), gpgme_strerror(rc));
189
199
  }
190
200
  
191
201
  if(debug){
192
 
    fprintf(stderr, "Initialize gpgme\n");
 
202
    fprintf(stderr, "Initializing GPGME\n");
193
203
  }
194
204
  
195
205
  /* Init GPGME */
222
232
  }
223
233
  
224
234
  /* Create new GPGME "context" */
225
 
  rc = gpgme_new(&(mc->ctx));
 
235
  rc = gpgme_new(&(mc.ctx));
226
236
  if(rc != GPG_ERR_NO_ERROR){
227
237
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
228
238
            gpgme_strsource(rc), gpgme_strerror(rc));
240
250
 * Decrypt OpenPGP data.
241
251
 * Returns -1 on error
242
252
 */
243
 
static ssize_t pgp_packet_decrypt(const mandos_context *mc,
244
 
                                  const char *cryptotext,
 
253
static ssize_t pgp_packet_decrypt(const char *cryptotext,
245
254
                                  size_t crypto_size,
246
255
                                  char **plaintext){
247
256
  gpgme_data_t dh_crypto, dh_plain;
274
283
  
275
284
  /* Decrypt data from the cryptotext data buffer to the plaintext
276
285
     data buffer */
277
 
  rc = gpgme_op_decrypt(mc->ctx, dh_crypto, dh_plain);
 
286
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
278
287
  if(rc != GPG_ERR_NO_ERROR){
279
288
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
280
289
            gpgme_strsource(rc), gpgme_strerror(rc));
281
290
    plaintext_length = -1;
282
291
    if(debug){
283
292
      gpgme_decrypt_result_t result;
284
 
      result = gpgme_op_decrypt_result(mc->ctx);
 
293
      result = gpgme_op_decrypt_result(mc.ctx);
285
294
      if(result == NULL){
286
295
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
287
296
      } else {
323
332
  
324
333
  *plaintext = NULL;
325
334
  while(true){
326
 
    plaintext_capacity = adjustbuffer(plaintext,
 
335
    plaintext_capacity = incbuffer(plaintext,
327
336
                                      (size_t)plaintext_length,
328
337
                                      plaintext_capacity);
329
338
    if(plaintext_capacity == 0){
330
 
        perror("adjustbuffer");
 
339
        perror("incbuffer");
331
340
        plaintext_length = -1;
332
341
        goto decrypt_end;
333
342
    }
365
374
  return plaintext_length;
366
375
}
367
376
 
368
 
static const char * safer_gnutls_strerror(int value) {
 
377
static const char * safer_gnutls_strerror(int value){
369
378
  const char *ret = gnutls_strerror(value); /* Spurious warning from
370
379
                                               -Wunreachable-code */
371
380
  if(ret == NULL)
379
388
  fprintf(stderr, "GnuTLS: %s", string);
380
389
}
381
390
 
382
 
static int init_gnutls_global(mandos_context *mc,
383
 
                              const char *pubkeyfilename,
 
391
static int init_gnutls_global(const char *pubkeyfilename,
384
392
                              const char *seckeyfilename){
385
393
  int ret;
386
394
  
389
397
  }
390
398
  
391
399
  ret = gnutls_global_init();
392
 
  if(ret != GNUTLS_E_SUCCESS) {
 
400
  if(ret != GNUTLS_E_SUCCESS){
393
401
    fprintf(stderr, "GnuTLS global_init: %s\n",
394
402
            safer_gnutls_strerror(ret));
395
403
    return -1;
404
412
  }
405
413
  
406
414
  /* OpenPGP credentials */
407
 
  gnutls_certificate_allocate_credentials(&mc->cred);
 
415
  gnutls_certificate_allocate_credentials(&mc.cred);
408
416
  if(ret != GNUTLS_E_SUCCESS){
409
417
    fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning
410
 
                                                  * from
411
 
                                                  * -Wunreachable-code
412
 
                                                  */
 
418
                                                    from
 
419
                                                    -Wunreachable-code
 
420
                                                 */
413
421
            safer_gnutls_strerror(ret));
414
422
    gnutls_global_deinit();
415
423
    return -1;
422
430
  }
423
431
  
424
432
  ret = gnutls_certificate_set_openpgp_key_file
425
 
    (mc->cred, pubkeyfilename, seckeyfilename,
 
433
    (mc.cred, pubkeyfilename, seckeyfilename,
426
434
     GNUTLS_OPENPGP_FMT_BASE64);
427
 
  if(ret != GNUTLS_E_SUCCESS) {
 
435
  if(ret != GNUTLS_E_SUCCESS){
428
436
    fprintf(stderr,
429
437
            "Error[%d] while reading the OpenPGP key pair ('%s',"
430
438
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
434
442
  }
435
443
  
436
444
  /* GnuTLS server initialization */
437
 
  ret = gnutls_dh_params_init(&mc->dh_params);
438
 
  if(ret != GNUTLS_E_SUCCESS) {
 
445
  ret = gnutls_dh_params_init(&mc.dh_params);
 
446
  if(ret != GNUTLS_E_SUCCESS){
439
447
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
440
448
            " %s\n", safer_gnutls_strerror(ret));
441
449
    goto globalfail;
442
450
  }
443
 
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
444
 
  if(ret != GNUTLS_E_SUCCESS) {
 
451
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
 
452
  if(ret != GNUTLS_E_SUCCESS){
445
453
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
446
454
            safer_gnutls_strerror(ret));
447
455
    goto globalfail;
448
456
  }
449
457
  
450
 
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
 
458
  gnutls_certificate_set_dh_params(mc.cred, mc.dh_params);
451
459
  
452
460
  return 0;
453
461
  
454
462
 globalfail:
455
463
  
456
 
  gnutls_certificate_free_credentials(mc->cred);
 
464
  gnutls_certificate_free_credentials(mc.cred);
457
465
  gnutls_global_deinit();
458
 
  gnutls_dh_params_deinit(mc->dh_params);
 
466
  gnutls_dh_params_deinit(mc.dh_params);
459
467
  return -1;
460
468
}
461
469
 
462
 
static int init_gnutls_session(mandos_context *mc,
463
 
                               gnutls_session_t *session){
 
470
static int init_gnutls_session(gnutls_session_t *session){
464
471
  int ret;
465
472
  /* GnuTLS session creation */
466
473
  ret = gnutls_init(session, GNUTLS_SERVER);
471
478
  
472
479
  {
473
480
    const char *err;
474
 
    ret = gnutls_priority_set_direct(*session, mc->priority, &err);
475
 
    if(ret != GNUTLS_E_SUCCESS) {
 
481
    ret = gnutls_priority_set_direct(*session, mc.priority, &err);
 
482
    if(ret != GNUTLS_E_SUCCESS){
476
483
      fprintf(stderr, "Syntax error at: %s\n", err);
477
484
      fprintf(stderr, "GnuTLS error: %s\n",
478
485
              safer_gnutls_strerror(ret));
482
489
  }
483
490
  
484
491
  ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
485
 
                               mc->cred);
486
 
  if(ret != GNUTLS_E_SUCCESS) {
 
492
                               mc.cred);
 
493
  if(ret != GNUTLS_E_SUCCESS){
487
494
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
488
495
            safer_gnutls_strerror(ret));
489
496
    gnutls_deinit(*session);
494
501
  gnutls_certificate_server_set_request(*session,
495
502
                                        GNUTLS_CERT_IGNORE);
496
503
  
497
 
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
 
504
  gnutls_dh_set_prime_bits(*session, mc.dh_bits);
498
505
  
499
506
  return 0;
500
507
}
506
513
/* Called when a Mandos server is found */
507
514
static int start_mandos_communication(const char *ip, uint16_t port,
508
515
                                      AvahiIfIndex if_index,
509
 
                                      mandos_context *mc){
 
516
                                      int af){
510
517
  int ret, tcp_sd;
511
518
  ssize_t sret;
512
 
  union { struct sockaddr in; struct sockaddr_in6 in6; } to;
 
519
  union {
 
520
    struct sockaddr_in in;
 
521
    struct sockaddr_in6 in6;
 
522
  } to;
513
523
  char *buffer = NULL;
514
524
  char *decrypted_buffer;
515
525
  size_t buffer_length = 0;
517
527
  ssize_t decrypted_buffer_size;
518
528
  size_t written;
519
529
  int retval = 0;
520
 
  char interface[IF_NAMESIZE];
521
530
  gnutls_session_t session;
522
 
  
523
 
  ret = init_gnutls_session(mc, &session);
 
531
  int pf;                       /* Protocol family */
 
532
  
 
533
  switch(af){
 
534
  case AF_INET6:
 
535
    pf = PF_INET6;
 
536
    break;
 
537
  case AF_INET:
 
538
    pf = PF_INET;
 
539
    break;
 
540
  default:
 
541
    fprintf(stderr, "Bad address family: %d\n", af);
 
542
    return -1;
 
543
  }
 
544
  
 
545
  ret = init_gnutls_session(&session);
524
546
  if(ret != 0){
525
547
    return -1;
526
548
  }
527
549
  
528
550
  if(debug){
529
 
    fprintf(stderr, "Setting up a tcp connection to %s, port %" PRIu16
 
551
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
530
552
            "\n", ip, port);
531
553
  }
532
554
  
533
 
  tcp_sd = socket(PF_INET6, SOCK_STREAM, 0);
534
 
  if(tcp_sd < 0) {
 
555
  tcp_sd = socket(pf, SOCK_STREAM, 0);
 
556
  if(tcp_sd < 0){
535
557
    perror("socket");
536
558
    return -1;
537
559
  }
538
560
  
539
 
  if(debug){
540
 
    if(if_indextoname((unsigned int)if_index, interface) == NULL){
541
 
      perror("if_indextoname");
542
 
      return -1;
543
 
    }
544
 
    fprintf(stderr, "Binding to interface %s\n", interface);
545
 
  }
546
 
  
547
561
  memset(&to, 0, sizeof(to));
548
 
  to.in6.sin6_family = AF_INET6;
549
 
  /* It would be nice to have a way to detect if we were passed an
550
 
     IPv4 address here.   Now we assume an IPv6 address. */
551
 
  ret = inet_pton(AF_INET6, ip, &to.in6.sin6_addr);
 
562
  if(af == AF_INET6){
 
563
    to.in6.sin6_family = (uint16_t)af;
 
564
    ret = inet_pton(af, ip, &to.in6.sin6_addr);
 
565
  } else {                      /* IPv4 */
 
566
    to.in.sin_family = (sa_family_t)af;
 
567
    ret = inet_pton(af, ip, &to.in.sin_addr);
 
568
  }
552
569
  if(ret < 0 ){
553
570
    perror("inet_pton");
554
571
    return -1;
557
574
    fprintf(stderr, "Bad address: %s\n", ip);
558
575
    return -1;
559
576
  }
560
 
  to.in6.sin6_port = htons(port); /* Spurious warnings from
 
577
  if(af == AF_INET6){
 
578
    to.in6.sin6_port = htons(port); /* Spurious warnings from
 
579
                                       -Wconversion and
 
580
                                       -Wunreachable-code */
 
581
    
 
582
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
 
583
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
 
584
                              -Wunreachable-code*/
 
585
      if(if_index == AVAHI_IF_UNSPEC){
 
586
        fprintf(stderr, "An IPv6 link-local address is incomplete"
 
587
                " without a network interface\n");
 
588
        return -1;
 
589
      }
 
590
      /* Set the network interface number as scope */
 
591
      to.in6.sin6_scope_id = (uint32_t)if_index;
 
592
    }
 
593
  } else {
 
594
    to.in.sin_port = htons(port); /* Spurious warnings from
561
595
                                     -Wconversion and
562
596
                                     -Wunreachable-code */
563
 
  
564
 
  to.in6.sin6_scope_id = (uint32_t)if_index;
 
597
  }
565
598
  
566
599
  if(debug){
567
 
    fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
568
 
            port);
569
 
    char addrstr[INET6_ADDRSTRLEN] = "";
570
 
    if(inet_ntop(to.in6.sin6_family, &(to.in6.sin6_addr), addrstr,
571
 
                 sizeof(addrstr)) == NULL){
 
600
    if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
 
601
      char interface[IF_NAMESIZE];
 
602
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
 
603
        perror("if_indextoname");
 
604
      } else {
 
605
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
 
606
                ip, interface, port);
 
607
      }
 
608
    } else {
 
609
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
 
610
              port);
 
611
    }
 
612
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
 
613
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
 
614
    const char *pcret;
 
615
    if(af == AF_INET6){
 
616
      pcret = inet_ntop(af, &(to.in6.sin6_addr), addrstr,
 
617
                        sizeof(addrstr));
 
618
    } else {
 
619
      pcret = inet_ntop(af, &(to.in.sin_addr), addrstr,
 
620
                        sizeof(addrstr));
 
621
    }
 
622
    if(pcret == NULL){
572
623
      perror("inet_ntop");
573
624
    } else {
574
625
      if(strcmp(addrstr, ip) != 0){
577
628
    }
578
629
  }
579
630
  
580
 
  ret = connect(tcp_sd, &to.in, sizeof(to));
 
631
  if(af == AF_INET6){
 
632
    ret = connect(tcp_sd, &to.in6, sizeof(to));
 
633
  } else {
 
634
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
 
635
  }
581
636
  if(ret < 0){
582
637
    perror("connect");
583
638
    return -1;
629
684
  /* Read OpenPGP packet that contains the wanted password */
630
685
  
631
686
  if(debug){
632
 
    fprintf(stderr, "Retrieving pgp encrypted password from %s\n",
 
687
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
633
688
            ip);
634
689
  }
635
690
  
636
691
  while(true){
637
 
    buffer_capacity = adjustbuffer(&buffer, buffer_length,
 
692
    buffer_capacity = incbuffer(&buffer, buffer_length,
638
693
                                   buffer_capacity);
639
694
    if(buffer_capacity == 0){
640
 
      perror("adjustbuffer");
 
695
      perror("incbuffer");
641
696
      retval = -1;
642
697
      goto mandos_end;
643
698
    }
682
737
  gnutls_bye(session, GNUTLS_SHUT_RDWR);
683
738
  
684
739
  if(buffer_length > 0){
685
 
    decrypted_buffer_size = pgp_packet_decrypt(mc, buffer,
 
740
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
686
741
                                               buffer_length,
687
742
                                               &decrypted_buffer);
688
743
    if(decrypted_buffer_size >= 0){
723
778
 
724
779
static void resolve_callback(AvahiSServiceResolver *r,
725
780
                             AvahiIfIndex interface,
726
 
                             AVAHI_GCC_UNUSED AvahiProtocol protocol,
 
781
                             AvahiProtocol proto,
727
782
                             AvahiResolverEvent event,
728
783
                             const char *name,
729
784
                             const char *type,
734
789
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
735
790
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
736
791
                             flags,
737
 
                             void* userdata) {
738
 
  mandos_context *mc = userdata;
 
792
                             AVAHI_GCC_UNUSED void* userdata){
739
793
  assert(r);
740
794
  
741
795
  /* Called whenever a service has been resolved successfully or
742
796
     timed out */
743
797
  
744
 
  switch(event) {
 
798
  switch(event){
745
799
  default:
746
800
  case AVAHI_RESOLVER_FAILURE:
747
801
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
748
802
            " of type '%s' in domain '%s': %s\n", name, type, domain,
749
 
            avahi_strerror(avahi_server_errno(mc->server)));
 
803
            avahi_strerror(avahi_server_errno(mc.server)));
750
804
    break;
751
805
    
752
806
  case AVAHI_RESOLVER_FOUND:
758
812
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
759
813
                ip, (intmax_t)interface, port);
760
814
      }
761
 
      int ret = start_mandos_communication(ip, port, interface, mc);
 
815
      int ret = start_mandos_communication(ip, port, interface,
 
816
                                           avahi_proto_to_af(proto));
762
817
      if(ret == 0){
763
 
        avahi_simple_poll_quit(mc->simple_poll);
 
818
        avahi_simple_poll_quit(mc.simple_poll);
764
819
      }
765
820
    }
766
821
  }
767
822
  avahi_s_service_resolver_free(r);
768
823
}
769
824
 
770
 
static void browse_callback( AvahiSServiceBrowser *b,
771
 
                             AvahiIfIndex interface,
772
 
                             AvahiProtocol protocol,
773
 
                             AvahiBrowserEvent event,
774
 
                             const char *name,
775
 
                             const char *type,
776
 
                             const char *domain,
777
 
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
778
 
                             flags,
779
 
                             void* userdata) {
780
 
  mandos_context *mc = userdata;
 
825
static void browse_callback(AvahiSServiceBrowser *b,
 
826
                            AvahiIfIndex interface,
 
827
                            AvahiProtocol protocol,
 
828
                            AvahiBrowserEvent event,
 
829
                            const char *name,
 
830
                            const char *type,
 
831
                            const char *domain,
 
832
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
 
833
                            flags,
 
834
                            AVAHI_GCC_UNUSED void* userdata){
781
835
  assert(b);
782
836
  
783
837
  /* Called whenever a new services becomes available on the LAN or
784
838
     is removed from the LAN */
785
839
  
786
 
  switch(event) {
 
840
  switch(event){
787
841
  default:
788
842
  case AVAHI_BROWSER_FAILURE:
789
843
    
790
844
    fprintf(stderr, "(Avahi browser) %s\n",
791
 
            avahi_strerror(avahi_server_errno(mc->server)));
792
 
    avahi_simple_poll_quit(mc->simple_poll);
 
845
            avahi_strerror(avahi_server_errno(mc.server)));
 
846
    avahi_simple_poll_quit(mc.simple_poll);
793
847
    return;
794
848
    
795
849
  case AVAHI_BROWSER_NEW:
798
852
       the callback function is called the Avahi server will free the
799
853
       resolver for us. */
800
854
    
801
 
    if(!(avahi_s_service_resolver_new(mc->server, interface,
 
855
    if(!(avahi_s_service_resolver_new(mc.server, interface,
802
856
                                       protocol, name, type, domain,
803
857
                                       AVAHI_PROTO_INET6, 0,
804
 
                                       resolve_callback, mc)))
 
858
                                       resolve_callback, NULL)))
805
859
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
806
 
              name, avahi_strerror(avahi_server_errno(mc->server)));
 
860
              name, avahi_strerror(avahi_server_errno(mc.server)));
807
861
    break;
808
862
    
809
863
  case AVAHI_BROWSER_REMOVE:
818
872
  }
819
873
}
820
874
 
 
875
sig_atomic_t quit_now = 0;
 
876
 
 
877
static void handle_sigterm(__attribute__((unused)) int sig){
 
878
  if(quit_now){
 
879
    return;
 
880
  }
 
881
  quit_now = 1;
 
882
  int old_errno = errno;
 
883
  if(mc.simple_poll != NULL){
 
884
    avahi_simple_poll_quit(mc.simple_poll);
 
885
  }
 
886
  errno = old_errno;
 
887
}
 
888
 
821
889
int main(int argc, char *argv[]){
822
 
    AvahiSServiceBrowser *sb = NULL;
823
 
    int error;
824
 
    int ret;
825
 
    intmax_t tmpmax;
826
 
    int numchars;
827
 
    int exitcode = EXIT_SUCCESS;
828
 
    const char *interface = "eth0";
829
 
    struct ifreq network;
830
 
    int sd;
831
 
    uid_t uid;
832
 
    gid_t gid;
833
 
    char *connect_to = NULL;
834
 
    char tempdir[] = "/tmp/mandosXXXXXX";
835
 
    AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
836
 
    const char *seckey = PATHDIR "/" SECKEY;
837
 
    const char *pubkey = PATHDIR "/" PUBKEY;
838
 
    
839
 
    mandos_context mc = { .simple_poll = NULL, .server = NULL,
840
 
                          .dh_bits = 1024, .priority = "SECURE256"
841
 
                          ":!CTYPE-X.509:+CTYPE-OPENPGP" };
842
 
    bool gnutls_initialized = false;
843
 
    bool gpgme_initialized = false;
844
 
    
845
 
    {
846
 
      struct argp_option options[] = {
847
 
        { .name = "debug", .key = 128,
848
 
          .doc = "Debug mode", .group = 3 },
849
 
        { .name = "connect", .key = 'c',
850
 
          .arg = "ADDRESS:PORT",
851
 
          .doc = "Connect directly to a specific Mandos server",
852
 
          .group = 1 },
853
 
        { .name = "interface", .key = 'i',
854
 
          .arg = "NAME",
855
 
          .doc = "Interface that will be used to search for Mandos"
856
 
          " servers",
857
 
          .group = 1 },
858
 
        { .name = "seckey", .key = 's',
859
 
          .arg = "FILE",
860
 
          .doc = "OpenPGP secret key file base name",
861
 
          .group = 1 },
862
 
        { .name = "pubkey", .key = 'p',
863
 
          .arg = "FILE",
864
 
          .doc = "OpenPGP public key file base name",
865
 
          .group = 2 },
866
 
        { .name = "dh-bits", .key = 129,
867
 
          .arg = "BITS",
868
 
          .doc = "Bit length of the prime number used in the"
869
 
          " Diffie-Hellman key exchange",
870
 
          .group = 2 },
871
 
        { .name = "priority", .key = 130,
872
 
          .arg = "STRING",
873
 
          .doc = "GnuTLS priority string for the TLS handshake",
874
 
          .group = 1 },
875
 
        { .name = NULL }
876
 
      };
877
 
      
878
 
      error_t parse_opt(int key, char *arg,
879
 
                        struct argp_state *state) {
880
 
        switch(key) {
881
 
        case 128:               /* --debug */
882
 
          debug = true;
883
 
          break;
884
 
        case 'c':               /* --connect */
885
 
          connect_to = arg;
886
 
          break;
887
 
        case 'i':               /* --interface */
888
 
          interface = arg;
889
 
          break;
890
 
        case 's':               /* --seckey */
891
 
          seckey = arg;
892
 
          break;
893
 
        case 'p':               /* --pubkey */
894
 
          pubkey = arg;
895
 
          break;
896
 
        case 129:               /* --dh-bits */
897
 
          ret = sscanf(arg, "%" SCNdMAX "%n", &tmpmax, &numchars);
898
 
          if(ret < 1 or tmpmax != (typeof(mc.dh_bits))tmpmax
899
 
             or arg[numchars] != '\0'){
900
 
            fprintf(stderr, "Bad number of DH bits\n");
901
 
            exit(EXIT_FAILURE);
 
890
  AvahiSServiceBrowser *sb = NULL;
 
891
  int error;
 
892
  int ret;
 
893
  intmax_t tmpmax;
 
894
  int numchars;
 
895
  int exitcode = EXIT_SUCCESS;
 
896
  const char *interface = "eth0";
 
897
  struct ifreq network;
 
898
  int sd;
 
899
  uid_t uid;
 
900
  gid_t gid;
 
901
  char *connect_to = NULL;
 
902
  char tempdir[] = "/tmp/mandosXXXXXX";
 
903
  bool tempdir_created = false;
 
904
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
 
905
  const char *seckey = PATHDIR "/" SECKEY;
 
906
  const char *pubkey = PATHDIR "/" PUBKEY;
 
907
  
 
908
  /* Initialize Mandos context */
 
909
  mc = (mandos_context){ .simple_poll = NULL, .server = NULL,
 
910
                         .dh_bits = 1024, .priority = "SECURE256"
 
911
                         ":!CTYPE-X.509:+CTYPE-OPENPGP" };
 
912
  bool gnutls_initialized = false;
 
913
  bool gpgme_initialized = false;
 
914
  double delay = 2.5;
 
915
 
 
916
  struct sigaction old_sigterm_action;
 
917
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
 
918
  
 
919
  {
 
920
    struct argp_option options[] = {
 
921
      { .name = "debug", .key = 128,
 
922
        .doc = "Debug mode", .group = 3 },
 
923
      { .name = "connect", .key = 'c',
 
924
        .arg = "ADDRESS:PORT",
 
925
        .doc = "Connect directly to a specific Mandos server",
 
926
        .group = 1 },
 
927
      { .name = "interface", .key = 'i',
 
928
        .arg = "NAME",
 
929
        .doc = "Network interface that will be used to search for"
 
930
        " Mandos servers",
 
931
        .group = 1 },
 
932
      { .name = "seckey", .key = 's',
 
933
        .arg = "FILE",
 
934
        .doc = "OpenPGP secret key file base name",
 
935
        .group = 1 },
 
936
      { .name = "pubkey", .key = 'p',
 
937
        .arg = "FILE",
 
938
        .doc = "OpenPGP public key file base name",
 
939
        .group = 2 },
 
940
      { .name = "dh-bits", .key = 129,
 
941
        .arg = "BITS",
 
942
        .doc = "Bit length of the prime number used in the"
 
943
        " Diffie-Hellman key exchange",
 
944
        .group = 2 },
 
945
      { .name = "priority", .key = 130,
 
946
        .arg = "STRING",
 
947
        .doc = "GnuTLS priority string for the TLS handshake",
 
948
        .group = 1 },
 
949
      { .name = "delay", .key = 131,
 
950
        .arg = "SECONDS",
 
951
        .doc = "Maximum delay to wait for interface startup",
 
952
        .group = 2 },
 
953
      { .name = NULL }
 
954
    };
 
955
    
 
956
    error_t parse_opt(int key, char *arg,
 
957
                      struct argp_state *state){
 
958
      switch(key){
 
959
      case 128:                 /* --debug */
 
960
        debug = true;
 
961
        break;
 
962
      case 'c':                 /* --connect */
 
963
        connect_to = arg;
 
964
        break;
 
965
      case 'i':                 /* --interface */
 
966
        interface = arg;
 
967
        break;
 
968
      case 's':                 /* --seckey */
 
969
        seckey = arg;
 
970
        break;
 
971
      case 'p':                 /* --pubkey */
 
972
        pubkey = arg;
 
973
        break;
 
974
      case 129:                 /* --dh-bits */
 
975
        ret = sscanf(arg, "%" SCNdMAX "%n", &tmpmax, &numchars);
 
976
        if(ret < 1 or tmpmax != (typeof(mc.dh_bits))tmpmax
 
977
           or arg[numchars] != '\0'){
 
978
          fprintf(stderr, "Bad number of DH bits\n");
 
979
          exit(EXIT_FAILURE);
 
980
        }
 
981
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
 
982
        break;
 
983
      case 130:                 /* --priority */
 
984
        mc.priority = arg;
 
985
        break;
 
986
      case 131:                 /* --delay */
 
987
        ret = sscanf(arg, "%lf%n", &delay, &numchars);
 
988
        if(ret < 1 or arg[numchars] != '\0'){
 
989
          fprintf(stderr, "Bad delay\n");
 
990
          exit(EXIT_FAILURE);
 
991
        }
 
992
        break;
 
993
      case ARGP_KEY_ARG:
 
994
        argp_usage(state);
 
995
      case ARGP_KEY_END:
 
996
        break;
 
997
      default:
 
998
        return ARGP_ERR_UNKNOWN;
 
999
      }
 
1000
      return 0;
 
1001
    }
 
1002
    
 
1003
    struct argp argp = { .options = options, .parser = parse_opt,
 
1004
                         .args_doc = "",
 
1005
                         .doc = "Mandos client -- Get and decrypt"
 
1006
                         " passwords from a Mandos server" };
 
1007
    ret = argp_parse(&argp, argc, argv, 0, 0, NULL);
 
1008
    if(ret == ARGP_ERR_UNKNOWN){
 
1009
      fprintf(stderr, "Unknown error while parsing arguments\n");
 
1010
      exitcode = EXIT_FAILURE;
 
1011
      goto end;
 
1012
    }
 
1013
  }
 
1014
  
 
1015
  /* If the interface is down, bring it up */
 
1016
  if(interface[0] != '\0'){
 
1017
#ifdef __linux__
 
1018
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
 
1019
       messages to mess up the prompt */
 
1020
    ret = klogctl(8, NULL, 5);
 
1021
    bool restore_loglevel = true;
 
1022
    if(ret == -1){
 
1023
      restore_loglevel = false;
 
1024
      perror("klogctl");
 
1025
    }
 
1026
#endif  /* __linux__ */
 
1027
    
 
1028
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1029
    if(sd < 0){
 
1030
      perror("socket");
 
1031
      exitcode = EXIT_FAILURE;
 
1032
#ifdef __linux__
 
1033
      if(restore_loglevel){
 
1034
        ret = klogctl(7, NULL, 0);
 
1035
        if(ret == -1){
 
1036
          perror("klogctl");
 
1037
        }
 
1038
      }
 
1039
#endif  /* __linux__ */
 
1040
      goto end;
 
1041
    }
 
1042
    strcpy(network.ifr_name, interface);
 
1043
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
1044
    if(ret == -1){
 
1045
      perror("ioctl SIOCGIFFLAGS");
 
1046
#ifdef __linux__
 
1047
      if(restore_loglevel){
 
1048
        ret = klogctl(7, NULL, 0);
 
1049
        if(ret == -1){
 
1050
          perror("klogctl");
 
1051
        }
 
1052
      }
 
1053
#endif  /* __linux__ */
 
1054
      exitcode = EXIT_FAILURE;
 
1055
      goto end;
 
1056
    }
 
1057
    if((network.ifr_flags & IFF_UP) == 0){
 
1058
      network.ifr_flags |= IFF_UP;
 
1059
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
1060
      if(ret == -1){
 
1061
        perror("ioctl SIOCSIFFLAGS");
 
1062
        exitcode = EXIT_FAILURE;
 
1063
#ifdef __linux__
 
1064
        if(restore_loglevel){
 
1065
          ret = klogctl(7, NULL, 0);
 
1066
          if(ret == -1){
 
1067
            perror("klogctl");
902
1068
          }
903
 
          mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
904
 
          break;
905
 
        case 130:               /* --priority */
906
 
          mc.priority = arg;
907
 
          break;
908
 
        case ARGP_KEY_ARG:
909
 
          argp_usage(state);
910
 
        case ARGP_KEY_END:
911
 
          break;
912
 
        default:
913
 
          return ARGP_ERR_UNKNOWN;
914
1069
        }
915
 
        return 0;
916
 
      }
917
 
      
918
 
      struct argp argp = { .options = options, .parser = parse_opt,
919
 
                           .args_doc = "",
920
 
                           .doc = "Mandos client -- Get and decrypt"
921
 
                           " passwords from a Mandos server" };
922
 
      ret = argp_parse(&argp, argc, argv, 0, 0, NULL);
923
 
      if(ret == ARGP_ERR_UNKNOWN){
924
 
        fprintf(stderr, "Unknown error while parsing arguments\n");
925
 
        exitcode = EXIT_FAILURE;
 
1070
#endif  /* __linux__ */
926
1071
        goto end;
927
1072
      }
928
1073
    }
929
 
    
930
 
    /* If the interface is down, bring it up */
931
 
    {
932
 
      sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
933
 
      if(sd < 0) {
934
 
        perror("socket");
935
 
        exitcode = EXIT_FAILURE;
936
 
        goto end;
937
 
      }
938
 
      strcpy(network.ifr_name, interface);
 
1074
    /* sleep checking until interface is running */
 
1075
    for(int i=0; i < delay * 4; i++){
939
1076
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
940
1077
      if(ret == -1){
941
1078
        perror("ioctl SIOCGIFFLAGS");
942
 
        exitcode = EXIT_FAILURE;
943
 
        goto end;
944
 
      }
945
 
      if((network.ifr_flags & IFF_UP) == 0){
946
 
        network.ifr_flags |= IFF_UP;
947
 
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
948
 
        if(ret == -1){
949
 
          perror("ioctl SIOCSIFFLAGS");
950
 
          exitcode = EXIT_FAILURE;
951
 
          goto end;
952
 
        }
953
 
      }
954
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1079
      } else if(network.ifr_flags & IFF_RUNNING){
 
1080
        break;
 
1081
      }
 
1082
      struct timespec sleeptime = { .tv_nsec = 250000000 };
 
1083
      ret = nanosleep(&sleeptime, NULL);
 
1084
      if(ret == -1 and errno != EINTR){
 
1085
        perror("nanosleep");
 
1086
      }
 
1087
    }
 
1088
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1089
    if(ret == -1){
 
1090
      perror("close");
 
1091
    }
 
1092
#ifdef __linux__
 
1093
    if(restore_loglevel){
 
1094
      /* Restores kernel loglevel to default */
 
1095
      ret = klogctl(7, NULL, 0);
955
1096
      if(ret == -1){
956
 
        perror("close");
 
1097
        perror("klogctl");
957
1098
      }
958
1099
    }
959
 
    
960
 
    uid = getuid();
961
 
    gid = getgid();
962
 
    
963
 
    ret = setuid(uid);
964
 
    if(ret == -1){
965
 
      perror("setuid");
966
 
    }
967
 
    
968
 
    setgid(gid);
969
 
    if(ret == -1){
970
 
      perror("setgid");
971
 
    }
972
 
    
973
 
    ret = init_gnutls_global(&mc, pubkey, seckey);
974
 
    if(ret == -1){
975
 
      fprintf(stderr, "init_gnutls_global failed\n");
976
 
      exitcode = EXIT_FAILURE;
977
 
      goto end;
978
 
    } else {
979
 
      gnutls_initialized = true;
980
 
    }
981
 
    
982
 
    if(mkdtemp(tempdir) == NULL){
983
 
      perror("mkdtemp");
984
 
      tempdir[0] = '\0';
985
 
      goto end;
986
 
    }
987
 
    
988
 
    if(not init_gpgme(&mc, pubkey, seckey, tempdir)){
989
 
      fprintf(stderr, "init_gpgme failed\n");
990
 
      exitcode = EXIT_FAILURE;
991
 
      goto end;
992
 
    } else {
993
 
      gpgme_initialized = true;
994
 
    }
995
 
    
 
1100
#endif  /* __linux__ */
 
1101
  }
 
1102
  
 
1103
  uid = getuid();
 
1104
  gid = getgid();
 
1105
  
 
1106
  errno = 0;
 
1107
  setgid(gid);
 
1108
  if(ret == -1){
 
1109
    perror("setgid");
 
1110
  }
 
1111
  
 
1112
  ret = setuid(uid);
 
1113
  if(ret == -1){
 
1114
    perror("setuid");
 
1115
  }
 
1116
  
 
1117
  ret = init_gnutls_global(pubkey, seckey);
 
1118
  if(ret == -1){
 
1119
    fprintf(stderr, "init_gnutls_global failed\n");
 
1120
    exitcode = EXIT_FAILURE;
 
1121
    goto end;
 
1122
  } else {
 
1123
    gnutls_initialized = true;
 
1124
  }
 
1125
  
 
1126
  if(mkdtemp(tempdir) == NULL){
 
1127
    perror("mkdtemp");
 
1128
    goto end;
 
1129
  }
 
1130
  tempdir_created = true;
 
1131
  
 
1132
  if(not init_gpgme(pubkey, seckey, tempdir)){
 
1133
    fprintf(stderr, "init_gpgme failed\n");
 
1134
    exitcode = EXIT_FAILURE;
 
1135
    goto end;
 
1136
  } else {
 
1137
    gpgme_initialized = true;
 
1138
  }
 
1139
  
 
1140
  if(interface[0] != '\0'){
996
1141
    if_index = (AvahiIfIndex) if_nametoindex(interface);
997
1142
    if(if_index == 0){
998
1143
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
999
 
      exit(EXIT_FAILURE);
1000
 
    }
1001
 
    
1002
 
    if(connect_to != NULL){
1003
 
      /* Connect directly, do not use Zeroconf */
1004
 
      /* (Mainly meant for debugging) */
1005
 
      char *address = strrchr(connect_to, ':');
1006
 
      if(address == NULL){
1007
 
        fprintf(stderr, "No colon in address\n");
1008
 
        exitcode = EXIT_FAILURE;
1009
 
        goto end;
1010
 
      }
1011
 
      uint16_t port;
1012
 
      ret = sscanf(address+1, "%" SCNdMAX "%n", &tmpmax, &numchars);
1013
 
      if(ret < 1 or tmpmax != (uint16_t)tmpmax
1014
 
         or address[numchars+1] != '\0'){
1015
 
        fprintf(stderr, "Bad port number\n");
1016
 
        exitcode = EXIT_FAILURE;
1017
 
        goto end;
1018
 
      }
1019
 
      port = (uint16_t)tmpmax;
1020
 
      *address = '\0';
1021
 
      address = connect_to;
1022
 
      ret = start_mandos_communication(address, port, if_index, &mc);
1023
 
      if(ret < 0){
1024
 
        exitcode = EXIT_FAILURE;
1025
 
      } else {
1026
 
        exitcode = EXIT_SUCCESS;
1027
 
      }
1028
 
      goto end;
1029
 
    }
1030
 
    
1031
 
    if(not debug){
1032
 
      avahi_set_log_function(empty_log);
1033
 
    }
1034
 
    
1035
 
    /* Initialize the pseudo-RNG for Avahi */
1036
 
    srand((unsigned int) time(NULL));
1037
 
    
1038
 
    /* Allocate main Avahi loop object */
1039
 
    mc.simple_poll = avahi_simple_poll_new();
1040
 
    if(mc.simple_poll == NULL) {
1041
 
        fprintf(stderr, "Avahi: Failed to create simple poll"
1042
 
                " object.\n");
1043
 
        exitcode = EXIT_FAILURE;
1044
 
        goto end;
1045
 
    }
1046
 
    
1047
 
    {
1048
 
      AvahiServerConfig config;
1049
 
      /* Do not publish any local Zeroconf records */
1050
 
      avahi_server_config_init(&config);
1051
 
      config.publish_hinfo = 0;
1052
 
      config.publish_addresses = 0;
1053
 
      config.publish_workstation = 0;
1054
 
      config.publish_domain = 0;
1055
 
      
1056
 
      /* Allocate a new server */
1057
 
      mc.server = avahi_server_new(avahi_simple_poll_get
1058
 
                                   (mc.simple_poll), &config, NULL,
1059
 
                                   NULL, &error);
1060
 
      
1061
 
      /* Free the Avahi configuration data */
1062
 
      avahi_server_config_free(&config);
1063
 
    }
1064
 
    
1065
 
    /* Check if creating the Avahi server object succeeded */
1066
 
    if(mc.server == NULL) {
1067
 
        fprintf(stderr, "Failed to create Avahi server: %s\n",
1068
 
                avahi_strerror(error));
1069
 
        exitcode = EXIT_FAILURE;
1070
 
        goto end;
1071
 
    }
1072
 
    
1073
 
    /* Create the Avahi service browser */
1074
 
    sb = avahi_s_service_browser_new(mc.server, if_index,
1075
 
                                     AVAHI_PROTO_INET6,
1076
 
                                     "_mandos._tcp", NULL, 0,
1077
 
                                     browse_callback, &mc);
1078
 
    if(sb == NULL) {
1079
 
        fprintf(stderr, "Failed to create service browser: %s\n",
1080
 
                avahi_strerror(avahi_server_errno(mc.server)));
1081
 
        exitcode = EXIT_FAILURE;
1082
 
        goto end;
1083
 
    }
1084
 
    
1085
 
    /* Run the main loop */
1086
 
    
1087
 
    if(debug){
1088
 
      fprintf(stderr, "Starting Avahi loop search\n");
1089
 
    }
1090
 
    
1091
 
    avahi_simple_poll_loop(mc.simple_poll);
1092
 
    
 
1144
      exitcode = EXIT_FAILURE;
 
1145
      goto end;
 
1146
    }
 
1147
  }
 
1148
  
 
1149
  if(connect_to != NULL){
 
1150
    /* Connect directly, do not use Zeroconf */
 
1151
    /* (Mainly meant for debugging) */
 
1152
    char *address = strrchr(connect_to, ':');
 
1153
    if(address == NULL){
 
1154
      fprintf(stderr, "No colon in address\n");
 
1155
      exitcode = EXIT_FAILURE;
 
1156
      goto end;
 
1157
    }
 
1158
    uint16_t port;
 
1159
    ret = sscanf(address+1, "%" SCNdMAX "%n", &tmpmax, &numchars);
 
1160
    if(ret < 1 or tmpmax != (uint16_t)tmpmax
 
1161
       or address[numchars+1] != '\0'){
 
1162
      fprintf(stderr, "Bad port number\n");
 
1163
      exitcode = EXIT_FAILURE;
 
1164
      goto end;
 
1165
    }
 
1166
    port = (uint16_t)tmpmax;
 
1167
    *address = '\0';
 
1168
    address = connect_to;
 
1169
    /* Colon in address indicates IPv6 */
 
1170
    int af;
 
1171
    if(strchr(address, ':') != NULL){
 
1172
      af = AF_INET6;
 
1173
    } else {
 
1174
      af = AF_INET;
 
1175
    }
 
1176
    ret = start_mandos_communication(address, port, if_index, af);
 
1177
    if(ret < 0){
 
1178
      exitcode = EXIT_FAILURE;
 
1179
    } else {
 
1180
      exitcode = EXIT_SUCCESS;
 
1181
    }
 
1182
    goto end;
 
1183
  }
 
1184
  
 
1185
  if(not debug){
 
1186
    avahi_set_log_function(empty_log);
 
1187
  }
 
1188
  
 
1189
  /* Initialize the pseudo-RNG for Avahi */
 
1190
  srand((unsigned int) time(NULL));
 
1191
  
 
1192
  /* Allocate main Avahi loop object */
 
1193
  mc.simple_poll = avahi_simple_poll_new();
 
1194
  if(mc.simple_poll == NULL){
 
1195
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
 
1196
    exitcode = EXIT_FAILURE;
 
1197
    goto end;
 
1198
  }
 
1199
  
 
1200
  {
 
1201
    AvahiServerConfig config;
 
1202
    /* Do not publish any local Zeroconf records */
 
1203
    avahi_server_config_init(&config);
 
1204
    config.publish_hinfo = 0;
 
1205
    config.publish_addresses = 0;
 
1206
    config.publish_workstation = 0;
 
1207
    config.publish_domain = 0;
 
1208
    
 
1209
    /* Allocate a new server */
 
1210
    mc.server = avahi_server_new(avahi_simple_poll_get
 
1211
                                 (mc.simple_poll), &config, NULL,
 
1212
                                 NULL, &error);
 
1213
    
 
1214
    /* Free the Avahi configuration data */
 
1215
    avahi_server_config_free(&config);
 
1216
  }
 
1217
  
 
1218
  /* Check if creating the Avahi server object succeeded */
 
1219
  if(mc.server == NULL){
 
1220
    fprintf(stderr, "Failed to create Avahi server: %s\n",
 
1221
            avahi_strerror(error));
 
1222
    exitcode = EXIT_FAILURE;
 
1223
    goto end;
 
1224
  }
 
1225
  
 
1226
  /* Create the Avahi service browser */
 
1227
  sb = avahi_s_service_browser_new(mc.server, if_index,
 
1228
                                   AVAHI_PROTO_INET6, "_mandos._tcp",
 
1229
                                   NULL, 0, browse_callback, NULL);
 
1230
  if(sb == NULL){
 
1231
    fprintf(stderr, "Failed to create service browser: %s\n",
 
1232
            avahi_strerror(avahi_server_errno(mc.server)));
 
1233
    exitcode = EXIT_FAILURE;
 
1234
    goto end;
 
1235
  }
 
1236
  
 
1237
  sigemptyset(&sigterm_action.sa_mask);
 
1238
  ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
 
1239
  if(ret == -1){
 
1240
    perror("sigaddset");
 
1241
    exitcode = EXIT_FAILURE;
 
1242
    goto end;
 
1243
  }
 
1244
  ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
 
1245
  if(ret == -1){
 
1246
    perror("sigaddset");
 
1247
    exitcode = EXIT_FAILURE;
 
1248
    goto end;
 
1249
  }
 
1250
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
 
1251
  if(ret == -1){
 
1252
    perror("sigaddset");
 
1253
    exitcode = EXIT_FAILURE;
 
1254
    goto end;
 
1255
  }
 
1256
  ret = sigaction(SIGTERM, &sigterm_action, &old_sigterm_action);
 
1257
  if(ret == -1){
 
1258
    perror("sigaction");
 
1259
    exitcode = EXIT_FAILURE;
 
1260
    goto end;
 
1261
  }  
 
1262
  
 
1263
  /* Run the main loop */
 
1264
  
 
1265
  if(debug){
 
1266
    fprintf(stderr, "Starting Avahi loop search\n");
 
1267
  }
 
1268
  
 
1269
  avahi_simple_poll_loop(mc.simple_poll);
 
1270
  
1093
1271
 end:
1094
 
    
1095
 
    if(debug){
1096
 
      fprintf(stderr, "%s exiting\n", argv[0]);
1097
 
    }
1098
 
    
1099
 
    /* Cleanup things */
1100
 
    if(sb != NULL)
1101
 
        avahi_s_service_browser_free(sb);
1102
 
    
1103
 
    if(mc.server != NULL)
1104
 
        avahi_server_free(mc.server);
1105
 
    
1106
 
    if(mc.simple_poll != NULL)
1107
 
        avahi_simple_poll_free(mc.simple_poll);
1108
 
    
1109
 
    if(gnutls_initialized){
1110
 
      gnutls_certificate_free_credentials(mc.cred);
1111
 
      gnutls_global_deinit();
1112
 
      gnutls_dh_params_deinit(mc.dh_params);
1113
 
    }
1114
 
    
1115
 
    if(gpgme_initialized){
1116
 
      gpgme_release(mc.ctx);
1117
 
    }
1118
 
    
1119
 
    /* Removes the temp directory used by GPGME */
1120
 
    if(tempdir[0] != '\0'){
1121
 
      DIR *d;
1122
 
      struct dirent *direntry;
1123
 
      d = opendir(tempdir);
1124
 
      if(d == NULL){
1125
 
        if(errno != ENOENT){
1126
 
          perror("opendir");
1127
 
        }
1128
 
      } else {
1129
 
        while(true){
1130
 
          direntry = readdir(d);
1131
 
          if(direntry == NULL){
1132
 
            break;
1133
 
          }
1134
 
          /* Skip "." and ".." */
1135
 
          if(direntry->d_name[0] == '.'
1136
 
             and (direntry->d_name[1] == '\0'
1137
 
                  or (direntry->d_name[1] == '.'
1138
 
                      and direntry->d_name[2] == '\0'))){
1139
 
            continue;
1140
 
          }
1141
 
          char *fullname = NULL;
1142
 
          ret = asprintf(&fullname, "%s/%s", tempdir,
1143
 
                         direntry->d_name);
1144
 
          if(ret < 0){
1145
 
            perror("asprintf");
1146
 
            continue;
1147
 
          }
1148
 
          ret = remove(fullname);
1149
 
          if(ret == -1){
1150
 
            fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
1151
 
                    strerror(errno));
1152
 
          }
1153
 
          free(fullname);
1154
 
        }
1155
 
        closedir(d);
1156
 
      }
1157
 
      ret = rmdir(tempdir);
1158
 
      if(ret == -1 and errno != ENOENT){
1159
 
        perror("rmdir");
1160
 
      }
1161
 
    }
1162
 
    
1163
 
    return exitcode;
 
1272
  
 
1273
  if(debug){
 
1274
    fprintf(stderr, "%s exiting\n", argv[0]);
 
1275
  }
 
1276
  
 
1277
  /* Cleanup things */
 
1278
  if(sb != NULL)
 
1279
    avahi_s_service_browser_free(sb);
 
1280
  
 
1281
  if(mc.server != NULL)
 
1282
    avahi_server_free(mc.server);
 
1283
  
 
1284
  if(mc.simple_poll != NULL)
 
1285
    avahi_simple_poll_free(mc.simple_poll);
 
1286
  
 
1287
  if(gnutls_initialized){
 
1288
    gnutls_certificate_free_credentials(mc.cred);
 
1289
    gnutls_global_deinit();
 
1290
    gnutls_dh_params_deinit(mc.dh_params);
 
1291
  }
 
1292
  
 
1293
  if(gpgme_initialized){
 
1294
    gpgme_release(mc.ctx);
 
1295
  }
 
1296
  
 
1297
  /* Removes the temp directory used by GPGME */
 
1298
  if(tempdir_created){
 
1299
    DIR *d;
 
1300
    struct dirent *direntry;
 
1301
    d = opendir(tempdir);
 
1302
    if(d == NULL){
 
1303
      if(errno != ENOENT){
 
1304
        perror("opendir");
 
1305
      }
 
1306
    } else {
 
1307
      while(true){
 
1308
        direntry = readdir(d);
 
1309
        if(direntry == NULL){
 
1310
          break;
 
1311
        }
 
1312
        /* Skip "." and ".." */
 
1313
        if(direntry->d_name[0] == '.'
 
1314
           and (direntry->d_name[1] == '\0'
 
1315
                or (direntry->d_name[1] == '.'
 
1316
                    and direntry->d_name[2] == '\0'))){
 
1317
          continue;
 
1318
        }
 
1319
        char *fullname = NULL;
 
1320
        ret = asprintf(&fullname, "%s/%s", tempdir,
 
1321
                       direntry->d_name);
 
1322
        if(ret < 0){
 
1323
          perror("asprintf");
 
1324
          continue;
 
1325
        }
 
1326
        ret = remove(fullname);
 
1327
        if(ret == -1){
 
1328
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
 
1329
                  strerror(errno));
 
1330
        }
 
1331
        free(fullname);
 
1332
      }
 
1333
      closedir(d);
 
1334
    }
 
1335
    ret = rmdir(tempdir);
 
1336
    if(ret == -1 and errno != ENOENT){
 
1337
      perror("rmdir");
 
1338
    }
 
1339
  }
 
1340
  
 
1341
  return exitcode;
1164
1342
}