/mandos/trunk

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

« back to all changes in this revision

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

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