/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

  • Committer: Björn Påhlsson
  • Date: 2009-02-08 01:50:24 UTC
  • mto: (237.7.1 mandos) (24.1.154 mandos)
  • mto: This revision was merged to the branch mainline in revision 250.
  • Revision ID: belorn@braxen-20090208015024-jewaulcqtxvbopq6
Fixed a bug in fallback handling

Show diffs side-by-side

added added

removed removed

Lines of Context:
36
36
#define _GNU_SOURCE             /* TEMP_FAILURE_RETRY(), asprintf() */
37
37
 
38
38
#include <stdio.h>              /* fprintf(), stderr, fwrite(),
39
 
                                   stdout, ferror(), sscanf */
 
39
                                   stdout, ferror(), sscanf(),
 
40
                                   remove() */
40
41
#include <stdint.h>             /* uint16_t, uint32_t */
41
42
#include <stddef.h>             /* NULL, size_t, ssize_t */
42
43
#include <stdlib.h>             /* free(), EXIT_SUCCESS, EXIT_FAILURE,
57
58
#include <fcntl.h>              /* open() */
58
59
#include <dirent.h>             /* opendir(), struct dirent, readdir()
59
60
                                 */
60
 
#include <inttypes.h>           /* PRIu16, SCNu16 */
 
61
#include <inttypes.h>           /* PRIu16, intmax_t, SCNdMAX */
61
62
#include <assert.h>             /* assert() */
62
63
#include <errno.h>              /* perror(), errno */
63
 
#include <time.h>               /* time() */
 
64
#include <time.h>               /* nanosleep(), time() */
64
65
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
65
66
                                   SIOCSIFFLAGS, if_indextoname(),
66
67
                                   if_nametoindex(), IF_NAMESIZE */
74
75
                                   argp_state, struct argp,
75
76
                                   argp_parse(), ARGP_KEY_ARG,
76
77
                                   ARGP_KEY_END, ARGP_ERR_UNKNOWN */
 
78
#ifdef __linux__
 
79
#include <sys/klog.h>           /* klogctl() */
 
80
#endif
77
81
 
78
82
/* Avahi */
79
83
/* All Avahi types, constants and functions
126
130
} mandos_context;
127
131
 
128
132
/*
129
 
 * Make room in "buffer" for at least BUFFER_SIZE additional bytes.
130
 
 * "buffer_capacity" is how much is currently allocated,
131
 
 * "buffer_length" is how much is already used.
 
133
 * Make additional room in "buffer" for at least BUFFER_SIZE
 
134
 * additional bytes. "buffer_capacity" is how much is currently
 
135
 * allocated, "buffer_length" is how much is already used.
132
136
 */
133
 
size_t adjustbuffer(char **buffer, size_t buffer_length,
 
137
size_t incbuffer(char **buffer, size_t buffer_length,
134
138
                  size_t buffer_capacity){
135
139
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
136
140
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
153
157
  
154
158
  
155
159
  /*
156
 
   * Helper function to insert pub and seckey to the enigne keyring.
 
160
   * Helper function to insert pub and seckey to the engine keyring.
157
161
   */
158
162
  bool import_key(const char *filename){
159
163
    int fd;
322
326
  
323
327
  *plaintext = NULL;
324
328
  while(true){
325
 
    plaintext_capacity = adjustbuffer(plaintext,
 
329
    plaintext_capacity = incbuffer(plaintext,
326
330
                                      (size_t)plaintext_length,
327
331
                                      plaintext_capacity);
328
332
    if(plaintext_capacity == 0){
329
 
        perror("adjustbuffer");
 
333
        perror("incbuffer");
330
334
        plaintext_length = -1;
331
335
        goto decrypt_end;
332
336
    }
364
368
  return plaintext_length;
365
369
}
366
370
 
367
 
static const char * safer_gnutls_strerror(int value) {
 
371
static const char * safer_gnutls_strerror(int value){
368
372
  const char *ret = gnutls_strerror(value); /* Spurious warning from
369
373
                                               -Wunreachable-code */
370
374
  if(ret == NULL)
388
392
  }
389
393
  
390
394
  ret = gnutls_global_init();
391
 
  if(ret != GNUTLS_E_SUCCESS) {
 
395
  if(ret != GNUTLS_E_SUCCESS){
392
396
    fprintf(stderr, "GnuTLS global_init: %s\n",
393
397
            safer_gnutls_strerror(ret));
394
398
    return -1;
423
427
  ret = gnutls_certificate_set_openpgp_key_file
424
428
    (mc->cred, pubkeyfilename, seckeyfilename,
425
429
     GNUTLS_OPENPGP_FMT_BASE64);
426
 
  if(ret != GNUTLS_E_SUCCESS) {
 
430
  if(ret != GNUTLS_E_SUCCESS){
427
431
    fprintf(stderr,
428
432
            "Error[%d] while reading the OpenPGP key pair ('%s',"
429
433
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
434
438
  
435
439
  /* GnuTLS server initialization */
436
440
  ret = gnutls_dh_params_init(&mc->dh_params);
437
 
  if(ret != GNUTLS_E_SUCCESS) {
 
441
  if(ret != GNUTLS_E_SUCCESS){
438
442
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
439
443
            " %s\n", safer_gnutls_strerror(ret));
440
444
    goto globalfail;
441
445
  }
442
446
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
443
 
  if(ret != GNUTLS_E_SUCCESS) {
 
447
  if(ret != GNUTLS_E_SUCCESS){
444
448
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
445
449
            safer_gnutls_strerror(ret));
446
450
    goto globalfail;
471
475
  {
472
476
    const char *err;
473
477
    ret = gnutls_priority_set_direct(*session, mc->priority, &err);
474
 
    if(ret != GNUTLS_E_SUCCESS) {
 
478
    if(ret != GNUTLS_E_SUCCESS){
475
479
      fprintf(stderr, "Syntax error at: %s\n", err);
476
480
      fprintf(stderr, "GnuTLS error: %s\n",
477
481
              safer_gnutls_strerror(ret));
482
486
  
483
487
  ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
484
488
                               mc->cred);
485
 
  if(ret != GNUTLS_E_SUCCESS) {
 
489
  if(ret != GNUTLS_E_SUCCESS){
486
490
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
487
491
            safer_gnutls_strerror(ret));
488
492
    gnutls_deinit(*session);
530
534
  }
531
535
  
532
536
  tcp_sd = socket(PF_INET6, SOCK_STREAM, 0);
533
 
  if(tcp_sd < 0) {
 
537
  if(tcp_sd < 0){
534
538
    perror("socket");
535
539
    return -1;
536
540
  }
633
637
  }
634
638
  
635
639
  while(true){
636
 
    buffer_capacity = adjustbuffer(&buffer, buffer_length,
 
640
    buffer_capacity = incbuffer(&buffer, buffer_length,
637
641
                                   buffer_capacity);
638
642
    if(buffer_capacity == 0){
639
 
      perror("adjustbuffer");
 
643
      perror("incbuffer");
640
644
      retval = -1;
641
645
      goto mandos_end;
642
646
    }
733
737
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
734
738
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
735
739
                             flags,
736
 
                             void* userdata) {
 
740
                             void* userdata){
737
741
  mandos_context *mc = userdata;
738
742
  assert(r);
739
743
  
740
744
  /* Called whenever a service has been resolved successfully or
741
745
     timed out */
742
746
  
743
 
  switch(event) {
 
747
  switch(event){
744
748
  default:
745
749
  case AVAHI_RESOLVER_FAILURE:
746
750
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
754
758
      avahi_address_snprint(ip, sizeof(ip), address);
755
759
      if(debug){
756
760
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %"
757
 
                PRIu16 ") on port %d\n", name, host_name, ip,
758
 
                interface, port);
 
761
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
 
762
                ip, (intmax_t)interface, port);
759
763
      }
760
764
      int ret = start_mandos_communication(ip, port, interface, mc);
761
765
      if(ret == 0){
766
770
  avahi_s_service_resolver_free(r);
767
771
}
768
772
 
769
 
static void browse_callback( AvahiSServiceBrowser *b,
770
 
                             AvahiIfIndex interface,
771
 
                             AvahiProtocol protocol,
772
 
                             AvahiBrowserEvent event,
773
 
                             const char *name,
774
 
                             const char *type,
775
 
                             const char *domain,
776
 
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
777
 
                             flags,
778
 
                             void* userdata) {
 
773
static void browse_callback(AvahiSServiceBrowser *b,
 
774
                            AvahiIfIndex interface,
 
775
                            AvahiProtocol protocol,
 
776
                            AvahiBrowserEvent event,
 
777
                            const char *name,
 
778
                            const char *type,
 
779
                            const char *domain,
 
780
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
 
781
                            flags,
 
782
                            void* userdata){
779
783
  mandos_context *mc = userdata;
780
784
  assert(b);
781
785
  
782
786
  /* Called whenever a new services becomes available on the LAN or
783
787
     is removed from the LAN */
784
788
  
785
 
  switch(event) {
 
789
  switch(event){
786
790
  default:
787
791
  case AVAHI_BROWSER_FAILURE:
788
792
    
818
822
}
819
823
 
820
824
int main(int argc, char *argv[]){
821
 
    AvahiSServiceBrowser *sb = NULL;
822
 
    int error;
823
 
    int ret;
824
 
    int exitcode = EXIT_SUCCESS;
825
 
    const char *interface = "eth0";
826
 
    struct ifreq network;
827
 
    int sd;
828
 
    uid_t uid;
829
 
    gid_t gid;
830
 
    char *connect_to = NULL;
831
 
    char tempdir[] = "/tmp/mandosXXXXXX";
832
 
    AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
833
 
    const char *seckey = PATHDIR "/" SECKEY;
834
 
    const char *pubkey = PATHDIR "/" PUBKEY;
835
 
    
836
 
    mandos_context mc = { .simple_poll = NULL, .server = NULL,
837
 
                          .dh_bits = 1024, .priority = "SECURE256"
838
 
                          ":!CTYPE-X.509:+CTYPE-OPENPGP" };
839
 
    bool gnutls_initalized = false;
840
 
    bool gpgme_initalized = false;
841
 
    
842
 
    {
843
 
      struct argp_option options[] = {
844
 
        { .name = "debug", .key = 128,
845
 
          .doc = "Debug mode", .group = 3 },
846
 
        { .name = "connect", .key = 'c',
847
 
          .arg = "ADDRESS:PORT",
848
 
          .doc = "Connect directly to a specific Mandos server",
849
 
          .group = 1 },
850
 
        { .name = "interface", .key = 'i',
851
 
          .arg = "NAME",
852
 
          .doc = "Interface that will be used to search for Mandos"
853
 
          " servers",
854
 
          .group = 1 },
855
 
        { .name = "seckey", .key = 's',
856
 
          .arg = "FILE",
857
 
          .doc = "OpenPGP secret key file base name",
858
 
          .group = 1 },
859
 
        { .name = "pubkey", .key = 'p',
860
 
          .arg = "FILE",
861
 
          .doc = "OpenPGP public key file base name",
862
 
          .group = 2 },
863
 
        { .name = "dh-bits", .key = 129,
864
 
          .arg = "BITS",
865
 
          .doc = "Bit length of the prime number used in the"
866
 
          " Diffie-Hellman key exchange",
867
 
          .group = 2 },
868
 
        { .name = "priority", .key = 130,
869
 
          .arg = "STRING",
870
 
          .doc = "GnuTLS priority string for the TLS handshake",
871
 
          .group = 1 },
872
 
        { .name = NULL }
873
 
      };
874
 
      
875
 
      error_t parse_opt(int key, char *arg,
876
 
                        struct argp_state *state) {
877
 
        switch(key) {
878
 
        case 128:               /* --debug */
879
 
          debug = true;
880
 
          break;
881
 
        case 'c':               /* --connect */
882
 
          connect_to = arg;
883
 
          break;
884
 
        case 'i':               /* --interface */
885
 
          interface = arg;
886
 
          break;
887
 
        case 's':               /* --seckey */
888
 
          seckey = arg;
889
 
          break;
890
 
        case 'p':               /* --pubkey */
891
 
          pubkey = arg;
892
 
          break;
893
 
        case 129:               /* --dh-bits */
894
 
          ret = sscanf(arg, "%u", &mc.dh_bits);
895
 
          if(ret != 1){
896
 
            fprintf(stderr, "Bad number of DH bits\n");
897
 
            exit(EXIT_FAILURE);
898
 
          }
899
 
          break;
900
 
        case 130:               /* --priority */
901
 
          mc.priority = arg;
902
 
          break;
903
 
        case ARGP_KEY_ARG:
904
 
          argp_usage(state);
905
 
        case ARGP_KEY_END:
906
 
          break;
907
 
        default:
908
 
          return ARGP_ERR_UNKNOWN;
909
 
        }
910
 
        return 0;
911
 
      }
912
 
      
913
 
      struct argp argp = { .options = options, .parser = parse_opt,
914
 
                           .args_doc = "",
915
 
                           .doc = "Mandos client -- Get and decrypt"
916
 
                           " passwords from a Mandos server" };
917
 
      ret = argp_parse(&argp, argc, argv, 0, 0, NULL);
918
 
      if(ret == ARGP_ERR_UNKNOWN){
919
 
        fprintf(stderr, "Unknown error while parsing arguments\n");
920
 
        exitcode = EXIT_FAILURE;
921
 
        goto end;
922
 
      }
923
 
    }
924
 
    
925
 
    /* If the interface is down, bring it up */
926
 
    {
927
 
      sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
928
 
      if(sd < 0) {
929
 
        perror("socket");
930
 
        exitcode = EXIT_FAILURE;
931
 
        goto end;
932
 
      }
933
 
      strcpy(network.ifr_name, interface);
 
825
  AvahiSServiceBrowser *sb = NULL;
 
826
  int error;
 
827
  int ret;
 
828
  intmax_t tmpmax;
 
829
  int numchars;
 
830
  int exitcode = EXIT_SUCCESS;
 
831
  const char *interface = "eth0";
 
832
  struct ifreq network;
 
833
  int sd;
 
834
  uid_t uid;
 
835
  gid_t gid;
 
836
  char *connect_to = NULL;
 
837
  char tempdir[] = "/tmp/mandosXXXXXX";
 
838
  bool tempdir_created = false;
 
839
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
 
840
  const char *seckey = PATHDIR "/" SECKEY;
 
841
  const char *pubkey = PATHDIR "/" PUBKEY;
 
842
  
 
843
  mandos_context mc = { .simple_poll = NULL, .server = NULL,
 
844
                        .dh_bits = 1024, .priority = "SECURE256"
 
845
                        ":!CTYPE-X.509:+CTYPE-OPENPGP" };
 
846
  bool gnutls_initialized = false;
 
847
  bool gpgme_initialized = false;
 
848
  double delay = 2.5;
 
849
  
 
850
  {
 
851
    struct argp_option options[] = {
 
852
      { .name = "debug", .key = 128,
 
853
        .doc = "Debug mode", .group = 3 },
 
854
      { .name = "connect", .key = 'c',
 
855
        .arg = "ADDRESS:PORT",
 
856
        .doc = "Connect directly to a specific Mandos server",
 
857
        .group = 1 },
 
858
      { .name = "interface", .key = 'i',
 
859
        .arg = "NAME",
 
860
        .doc = "Interface that will be used to search for Mandos"
 
861
        " servers",
 
862
        .group = 1 },
 
863
      { .name = "seckey", .key = 's',
 
864
        .arg = "FILE",
 
865
        .doc = "OpenPGP secret key file base name",
 
866
        .group = 1 },
 
867
      { .name = "pubkey", .key = 'p',
 
868
        .arg = "FILE",
 
869
        .doc = "OpenPGP public key file base name",
 
870
        .group = 2 },
 
871
      { .name = "dh-bits", .key = 129,
 
872
        .arg = "BITS",
 
873
        .doc = "Bit length of the prime number used in the"
 
874
        " Diffie-Hellman key exchange",
 
875
        .group = 2 },
 
876
      { .name = "priority", .key = 130,
 
877
        .arg = "STRING",
 
878
        .doc = "GnuTLS priority string for the TLS handshake",
 
879
        .group = 1 },
 
880
      { .name = "delay", .key = 131,
 
881
        .arg = "SECONDS",
 
882
        .doc = "Maximum delay to wait for interface startup",
 
883
        .group = 2 },
 
884
      { .name = NULL }
 
885
    };
 
886
    
 
887
    error_t parse_opt(int key, char *arg,
 
888
                      struct argp_state *state){
 
889
      switch(key){
 
890
      case 128:                 /* --debug */
 
891
        debug = true;
 
892
        break;
 
893
      case 'c':                 /* --connect */
 
894
        connect_to = arg;
 
895
        break;
 
896
      case 'i':                 /* --interface */
 
897
        interface = arg;
 
898
        break;
 
899
      case 's':                 /* --seckey */
 
900
        seckey = arg;
 
901
        break;
 
902
      case 'p':                 /* --pubkey */
 
903
        pubkey = arg;
 
904
        break;
 
905
      case 129:                 /* --dh-bits */
 
906
        ret = sscanf(arg, "%" SCNdMAX "%n", &tmpmax, &numchars);
 
907
        if(ret < 1 or tmpmax != (typeof(mc.dh_bits))tmpmax
 
908
           or arg[numchars] != '\0'){
 
909
          fprintf(stderr, "Bad number of DH bits\n");
 
910
          exit(EXIT_FAILURE);
 
911
        }
 
912
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
 
913
        break;
 
914
      case 130:                 /* --priority */
 
915
        mc.priority = arg;
 
916
        break;
 
917
      case 131:                 /* --delay */
 
918
        ret = sscanf(arg, "%lf%n", &delay, &numchars);
 
919
        if(ret < 1 or arg[numchars] != '\0'){
 
920
          fprintf(stderr, "Bad delay\n");
 
921
          exit(EXIT_FAILURE);
 
922
        }
 
923
        break;
 
924
      case ARGP_KEY_ARG:
 
925
        argp_usage(state);
 
926
      case ARGP_KEY_END:
 
927
        break;
 
928
      default:
 
929
        return ARGP_ERR_UNKNOWN;
 
930
      }
 
931
      return 0;
 
932
    }
 
933
    
 
934
    struct argp argp = { .options = options, .parser = parse_opt,
 
935
                         .args_doc = "",
 
936
                         .doc = "Mandos client -- Get and decrypt"
 
937
                         " passwords from a Mandos server" };
 
938
    ret = argp_parse(&argp, argc, argv, 0, 0, NULL);
 
939
    if(ret == ARGP_ERR_UNKNOWN){
 
940
      fprintf(stderr, "Unknown error while parsing arguments\n");
 
941
      exitcode = EXIT_FAILURE;
 
942
      goto end;
 
943
    }
 
944
  }
 
945
  
 
946
  /* If the interface is down, bring it up */
 
947
  {
 
948
#ifdef __linux__
 
949
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
 
950
       messages to mess up the prompt */
 
951
    ret = klogctl(8, NULL, 5);
 
952
    if(ret == -1){
 
953
      perror("klogctl");
 
954
    }
 
955
#endif
 
956
    
 
957
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
958
    if(sd < 0){
 
959
      perror("socket");
 
960
      exitcode = EXIT_FAILURE;
 
961
#ifdef __linux__
 
962
      ret = klogctl(7, NULL, 0);
 
963
      if(ret == -1){
 
964
        perror("klogctl");
 
965
      }
 
966
#endif
 
967
      goto end;
 
968
    }
 
969
    strcpy(network.ifr_name, interface);
 
970
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
971
    if(ret == -1){
 
972
      perror("ioctl SIOCGIFFLAGS");
 
973
#ifdef __linux__
 
974
      ret = klogctl(7, NULL, 0);
 
975
      if(ret == -1){
 
976
        perror("klogctl");
 
977
      }
 
978
#endif
 
979
      exitcode = EXIT_FAILURE;
 
980
      goto end;
 
981
    }
 
982
    if((network.ifr_flags & IFF_UP) == 0){
 
983
      network.ifr_flags |= IFF_UP;
 
984
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
985
      if(ret == -1){
 
986
        perror("ioctl SIOCSIFFLAGS");
 
987
        exitcode = EXIT_FAILURE;
 
988
#ifdef __linux__
 
989
        ret = klogctl(7, NULL, 0);
 
990
        if(ret == -1){
 
991
          perror("klogctl");
 
992
        }
 
993
#endif
 
994
        goto end;
 
995
      }
 
996
    }
 
997
    /* sleep checking until interface is running */
 
998
    for(int i=0; i < delay * 4; i++){
934
999
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
935
1000
      if(ret == -1){
936
1001
        perror("ioctl SIOCGIFFLAGS");
937
 
        exitcode = EXIT_FAILURE;
938
 
        goto end;
939
 
      }
940
 
      if((network.ifr_flags & IFF_UP) == 0){
941
 
        network.ifr_flags |= IFF_UP;
942
 
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
943
 
        if(ret == -1){
944
 
          perror("ioctl SIOCSIFFLAGS");
945
 
          exitcode = EXIT_FAILURE;
946
 
          goto end;
947
 
        }
948
 
      }
949
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
950
 
      if(ret == -1){
951
 
        perror("close");
952
 
      }
953
 
    }
954
 
    
955
 
    uid = getuid();
956
 
    gid = getgid();
957
 
    
958
 
    ret = setuid(uid);
959
 
    if(ret == -1){
960
 
      perror("setuid");
961
 
    }
962
 
    
963
 
    setgid(gid);
964
 
    if(ret == -1){
965
 
      perror("setgid");
966
 
    }
967
 
    
968
 
    ret = init_gnutls_global(&mc, pubkey, seckey);
969
 
    if(ret == -1){
970
 
      fprintf(stderr, "init_gnutls_global failed\n");
971
 
      exitcode = EXIT_FAILURE;
972
 
      goto end;
973
 
    } else {
974
 
      gnutls_initalized = true;
975
 
    }
976
 
    
977
 
    if(mkdtemp(tempdir) == NULL){
978
 
      perror("mkdtemp");
979
 
      tempdir[0] = '\0';
980
 
      goto end;
981
 
    }
982
 
    
983
 
    if(not init_gpgme(&mc, pubkey, seckey, tempdir)){
984
 
      fprintf(stderr, "gpgme_initalized failed\n");
985
 
      exitcode = EXIT_FAILURE;
986
 
      goto end;
987
 
    } else {
988
 
      gpgme_initalized = true;
989
 
    }
990
 
    
991
 
    if_index = (AvahiIfIndex) if_nametoindex(interface);
992
 
    if(if_index == 0){
993
 
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
994
 
      exit(EXIT_FAILURE);
995
 
    }
996
 
    
997
 
    if(connect_to != NULL){
998
 
      /* Connect directly, do not use Zeroconf */
999
 
      /* (Mainly meant for debugging) */
1000
 
      char *address = strrchr(connect_to, ':');
1001
 
      if(address == NULL){
1002
 
        fprintf(stderr, "No colon in address\n");
1003
 
        exitcode = EXIT_FAILURE;
1004
 
        goto end;
1005
 
      }
1006
 
      uint16_t port;
1007
 
      ret = sscanf(address+1, "%" SCNu16, &port);
1008
 
      if(ret != 1){
1009
 
        fprintf(stderr, "Bad port number\n");
1010
 
        exitcode = EXIT_FAILURE;
1011
 
        goto end;
1012
 
      }
1013
 
      *address = '\0';
1014
 
      address = connect_to;
1015
 
      ret = start_mandos_communication(address, port, if_index, &mc);
1016
 
      if(ret < 0){
1017
 
        exitcode = EXIT_FAILURE;
1018
 
      } else {
1019
 
        exitcode = EXIT_SUCCESS;
1020
 
      }
1021
 
      goto end;
1022
 
    }
1023
 
    
1024
 
    if(not debug){
1025
 
      avahi_set_log_function(empty_log);
1026
 
    }
1027
 
    
1028
 
    /* Initialize the pseudo-RNG for Avahi */
1029
 
    srand((unsigned int) time(NULL));
1030
 
    
1031
 
    /* Allocate main Avahi loop object */
1032
 
    mc.simple_poll = avahi_simple_poll_new();
1033
 
    if(mc.simple_poll == NULL) {
1034
 
        fprintf(stderr, "Avahi: Failed to create simple poll"
1035
 
                " object.\n");
1036
 
        exitcode = EXIT_FAILURE;
1037
 
        goto end;
1038
 
    }
1039
 
    
1040
 
    {
1041
 
      AvahiServerConfig config;
1042
 
      /* Do not publish any local Zeroconf records */
1043
 
      avahi_server_config_init(&config);
1044
 
      config.publish_hinfo = 0;
1045
 
      config.publish_addresses = 0;
1046
 
      config.publish_workstation = 0;
1047
 
      config.publish_domain = 0;
1048
 
      
1049
 
      /* Allocate a new server */
1050
 
      mc.server = avahi_server_new(avahi_simple_poll_get
1051
 
                                   (mc.simple_poll), &config, NULL,
1052
 
                                   NULL, &error);
1053
 
      
1054
 
      /* Free the Avahi configuration data */
1055
 
      avahi_server_config_free(&config);
1056
 
    }
1057
 
    
1058
 
    /* Check if creating the Avahi server object succeeded */
1059
 
    if(mc.server == NULL) {
1060
 
        fprintf(stderr, "Failed to create Avahi server: %s\n",
1061
 
                avahi_strerror(error));
1062
 
        exitcode = EXIT_FAILURE;
1063
 
        goto end;
1064
 
    }
1065
 
    
1066
 
    /* Create the Avahi service browser */
1067
 
    sb = avahi_s_service_browser_new(mc.server, if_index,
1068
 
                                     AVAHI_PROTO_INET6,
1069
 
                                     "_mandos._tcp", NULL, 0,
1070
 
                                     browse_callback, &mc);
1071
 
    if(sb == NULL) {
1072
 
        fprintf(stderr, "Failed to create service browser: %s\n",
1073
 
                avahi_strerror(avahi_server_errno(mc.server)));
1074
 
        exitcode = EXIT_FAILURE;
1075
 
        goto end;
1076
 
    }
1077
 
    
1078
 
    /* Run the main loop */
1079
 
    
1080
 
    if(debug){
1081
 
      fprintf(stderr, "Starting Avahi loop search\n");
1082
 
    }
1083
 
    
1084
 
    avahi_simple_poll_loop(mc.simple_poll);
1085
 
    
 
1002
      } else if(network.ifr_flags & IFF_RUNNING){
 
1003
        break;
 
1004
      }
 
1005
      struct timespec sleeptime = { .tv_nsec = 250000000 };
 
1006
      ret = nanosleep(&sleeptime, NULL);
 
1007
      if(ret == -1 and errno != EINTR){
 
1008
        perror("nanosleep");
 
1009
      }
 
1010
    }
 
1011
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1012
    if(ret == -1){
 
1013
      perror("close");
 
1014
    }
 
1015
#ifdef __linux__
 
1016
    /* Restores kernel loglevel to default */
 
1017
    ret = klogctl(7, NULL, 0);
 
1018
    if(ret == -1){
 
1019
      perror("klogctl");
 
1020
    }
 
1021
#endif
 
1022
  }
 
1023
  
 
1024
  uid = getuid();
 
1025
  gid = getgid();
 
1026
  
 
1027
  setgid(gid);
 
1028
  if(ret == -1){
 
1029
    perror("setgid");
 
1030
  }
 
1031
  
 
1032
  ret = setuid(uid);
 
1033
  if(ret == -1){
 
1034
    perror("setuid");
 
1035
  }
 
1036
  
 
1037
  ret = init_gnutls_global(&mc, pubkey, seckey);
 
1038
  if(ret == -1){
 
1039
    fprintf(stderr, "init_gnutls_global failed\n");
 
1040
    exitcode = EXIT_FAILURE;
 
1041
    goto end;
 
1042
  } else {
 
1043
    gnutls_initialized = true;
 
1044
  }
 
1045
  
 
1046
  if(mkdtemp(tempdir) == NULL){
 
1047
    perror("mkdtemp");
 
1048
    goto end;
 
1049
  }
 
1050
  tempdir_created = true;
 
1051
  
 
1052
  if(not init_gpgme(&mc, pubkey, seckey, tempdir)){
 
1053
    fprintf(stderr, "init_gpgme failed\n");
 
1054
    exitcode = EXIT_FAILURE;
 
1055
    goto end;
 
1056
  } else {
 
1057
    gpgme_initialized = true;
 
1058
  }
 
1059
  
 
1060
  if_index = (AvahiIfIndex) if_nametoindex(interface);
 
1061
  if(if_index == 0){
 
1062
    fprintf(stderr, "No such interface: \"%s\"\n", interface);
 
1063
    exitcode = EXIT_FAILURE;
 
1064
    goto end;
 
1065
  }
 
1066
  
 
1067
  if(connect_to != NULL){
 
1068
    /* Connect directly, do not use Zeroconf */
 
1069
    /* (Mainly meant for debugging) */
 
1070
    char *address = strrchr(connect_to, ':');
 
1071
    if(address == NULL){
 
1072
      fprintf(stderr, "No colon in address\n");
 
1073
      exitcode = EXIT_FAILURE;
 
1074
      goto end;
 
1075
    }
 
1076
    uint16_t port;
 
1077
    ret = sscanf(address+1, "%" SCNdMAX "%n", &tmpmax, &numchars);
 
1078
    if(ret < 1 or tmpmax != (uint16_t)tmpmax
 
1079
       or address[numchars+1] != '\0'){
 
1080
      fprintf(stderr, "Bad port number\n");
 
1081
      exitcode = EXIT_FAILURE;
 
1082
      goto end;
 
1083
    }
 
1084
    port = (uint16_t)tmpmax;
 
1085
    *address = '\0';
 
1086
    address = connect_to;
 
1087
    ret = start_mandos_communication(address, port, if_index, &mc);
 
1088
    if(ret < 0){
 
1089
      exitcode = EXIT_FAILURE;
 
1090
    } else {
 
1091
      exitcode = EXIT_SUCCESS;
 
1092
    }
 
1093
    goto end;
 
1094
  }
 
1095
  
 
1096
  if(not debug){
 
1097
    avahi_set_log_function(empty_log);
 
1098
  }
 
1099
  
 
1100
  /* Initialize the pseudo-RNG for Avahi */
 
1101
  srand((unsigned int) time(NULL));
 
1102
  
 
1103
  /* Allocate main Avahi loop object */
 
1104
  mc.simple_poll = avahi_simple_poll_new();
 
1105
  if(mc.simple_poll == NULL){
 
1106
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
 
1107
    exitcode = EXIT_FAILURE;
 
1108
    goto end;
 
1109
  }
 
1110
  
 
1111
  {
 
1112
    AvahiServerConfig config;
 
1113
    /* Do not publish any local Zeroconf records */
 
1114
    avahi_server_config_init(&config);
 
1115
    config.publish_hinfo = 0;
 
1116
    config.publish_addresses = 0;
 
1117
    config.publish_workstation = 0;
 
1118
    config.publish_domain = 0;
 
1119
    
 
1120
    /* Allocate a new server */
 
1121
    mc.server = avahi_server_new(avahi_simple_poll_get
 
1122
                                 (mc.simple_poll), &config, NULL,
 
1123
                                 NULL, &error);
 
1124
    
 
1125
    /* Free the Avahi configuration data */
 
1126
    avahi_server_config_free(&config);
 
1127
  }
 
1128
  
 
1129
  /* Check if creating the Avahi server object succeeded */
 
1130
  if(mc.server == NULL){
 
1131
    fprintf(stderr, "Failed to create Avahi server: %s\n",
 
1132
            avahi_strerror(error));
 
1133
    exitcode = EXIT_FAILURE;
 
1134
    goto end;
 
1135
  }
 
1136
  
 
1137
  /* Create the Avahi service browser */
 
1138
  sb = avahi_s_service_browser_new(mc.server, if_index,
 
1139
                                   AVAHI_PROTO_INET6, "_mandos._tcp",
 
1140
                                   NULL, 0, browse_callback, &mc);
 
1141
  if(sb == NULL){
 
1142
    fprintf(stderr, "Failed to create service browser: %s\n",
 
1143
            avahi_strerror(avahi_server_errno(mc.server)));
 
1144
    exitcode = EXIT_FAILURE;
 
1145
    goto end;
 
1146
  }
 
1147
  
 
1148
  /* Run the main loop */
 
1149
  
 
1150
  if(debug){
 
1151
    fprintf(stderr, "Starting Avahi loop search\n");
 
1152
  }
 
1153
  
 
1154
  avahi_simple_poll_loop(mc.simple_poll);
 
1155
  
1086
1156
 end:
1087
 
    
1088
 
    if(debug){
1089
 
      fprintf(stderr, "%s exiting\n", argv[0]);
1090
 
    }
1091
 
    
1092
 
    /* Cleanup things */
1093
 
    if(sb != NULL)
1094
 
        avahi_s_service_browser_free(sb);
1095
 
    
1096
 
    if(mc.server != NULL)
1097
 
        avahi_server_free(mc.server);
1098
 
    
1099
 
    if(mc.simple_poll != NULL)
1100
 
        avahi_simple_poll_free(mc.simple_poll);
1101
 
    
1102
 
    if(gnutls_initalized){
1103
 
      gnutls_certificate_free_credentials(mc.cred);
1104
 
      gnutls_global_deinit();
1105
 
      gnutls_dh_params_deinit(mc.dh_params);
1106
 
    }
1107
 
    
1108
 
    if(gpgme_initalized){
1109
 
      gpgme_release(mc.ctx);
1110
 
    }
1111
 
    
1112
 
    /* Removes the temp directory used by GPGME */
1113
 
    if(tempdir[0] != '\0'){
1114
 
      DIR *d;
1115
 
      struct dirent *direntry;
1116
 
      d = opendir(tempdir);
1117
 
      if(d == NULL){
1118
 
        if(errno != ENOENT){
1119
 
          perror("opendir");
1120
 
        }
1121
 
      } else {
1122
 
        while(true){
1123
 
          direntry = readdir(d);
1124
 
          if(direntry == NULL){
1125
 
            break;
1126
 
          }
1127
 
          if(direntry->d_type == DT_REG){
1128
 
            char *fullname = NULL;
1129
 
            ret = asprintf(&fullname, "%s/%s", tempdir,
1130
 
                           direntry->d_name);
1131
 
            if(ret < 0){
1132
 
              perror("asprintf");
1133
 
              continue;
1134
 
            }
1135
 
            ret = unlink(fullname);
1136
 
            if(ret == -1){
1137
 
              fprintf(stderr, "unlink(\"%s\"): %s",
1138
 
                      fullname, strerror(errno));
1139
 
            }
1140
 
            free(fullname);
1141
 
          }
1142
 
        }
1143
 
        closedir(d);
1144
 
      }
1145
 
      ret = rmdir(tempdir);
1146
 
      if(ret == -1 and errno != ENOENT){
1147
 
        perror("rmdir");
1148
 
      }
1149
 
    }
1150
 
          
1151
 
    return exitcode;
 
1157
  
 
1158
  if(debug){
 
1159
    fprintf(stderr, "%s exiting\n", argv[0]);
 
1160
  }
 
1161
  
 
1162
  /* Cleanup things */
 
1163
  if(sb != NULL)
 
1164
    avahi_s_service_browser_free(sb);
 
1165
  
 
1166
  if(mc.server != NULL)
 
1167
    avahi_server_free(mc.server);
 
1168
  
 
1169
  if(mc.simple_poll != NULL)
 
1170
    avahi_simple_poll_free(mc.simple_poll);
 
1171
  
 
1172
  if(gnutls_initialized){
 
1173
    gnutls_certificate_free_credentials(mc.cred);
 
1174
    gnutls_global_deinit();
 
1175
    gnutls_dh_params_deinit(mc.dh_params);
 
1176
  }
 
1177
  
 
1178
  if(gpgme_initialized){
 
1179
    gpgme_release(mc.ctx);
 
1180
  }
 
1181
  
 
1182
  /* Removes the temp directory used by GPGME */
 
1183
  if(tempdir_created){
 
1184
    DIR *d;
 
1185
    struct dirent *direntry;
 
1186
    d = opendir(tempdir);
 
1187
    if(d == NULL){
 
1188
      if(errno != ENOENT){
 
1189
        perror("opendir");
 
1190
      }
 
1191
    } else {
 
1192
      while(true){
 
1193
        direntry = readdir(d);
 
1194
        if(direntry == NULL){
 
1195
          break;
 
1196
        }
 
1197
        /* Skip "." and ".." */
 
1198
        if(direntry->d_name[0] == '.'
 
1199
           and (direntry->d_name[1] == '\0'
 
1200
                or (direntry->d_name[1] == '.'
 
1201
                    and direntry->d_name[2] == '\0'))){
 
1202
          continue;
 
1203
        }
 
1204
        char *fullname = NULL;
 
1205
        ret = asprintf(&fullname, "%s/%s", tempdir,
 
1206
                       direntry->d_name);
 
1207
        if(ret < 0){
 
1208
          perror("asprintf");
 
1209
          continue;
 
1210
        }
 
1211
        ret = remove(fullname);
 
1212
        if(ret == -1){
 
1213
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
 
1214
                  strerror(errno));
 
1215
        }
 
1216
        free(fullname);
 
1217
      }
 
1218
      closedir(d);
 
1219
    }
 
1220
    ret = rmdir(tempdir);
 
1221
    if(ret == -1 and errno != ENOENT){
 
1222
      perror("rmdir");
 
1223
    }
 
1224
  }
 
1225
  
 
1226
  return exitcode;
1152
1227
}