/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

* Makefile (run-server): Use "--no-dbus" unconditionally.

* initramfs-tools-script: Correct tests for writable "/conf/conf.d".

* mandos: Add process ID number to logging messages.
  (IPv6_TCPServer.server_bind): Use plain "raise".
  (main): Do not try to handle SIGSEGV; it does not work.  Use plain
         "raise".  Log KeyboardInterrupt and server exit.

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