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