/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: 2011-07-25 18:52:11 UTC
  • mfrom: (489 trunk)
  • mto: (237.4.29 release)
  • mto: This revision was merged to the branch mainline in revision 490.
  • Revision ID: teddy@fukt.bsnet.se-20110725185211-wlitr9jvs70e1xh8
Merge from trunk.

Show diffs side-by-side

added added

removed removed

Lines of Context:
9
9
 * "browse_callback", and parts of "main".
10
10
 * 
11
11
 * Everything else is
12
 
 * Copyright © 2008,2009 Teddy Hogeborn
13
 
 * Copyright © 2008,2009 Björn Påhlsson
 
12
 * Copyright © 2008-2011 Teddy Hogeborn
 
13
 * Copyright © 2008-2011 Björn Påhlsson
14
14
 * 
15
15
 * This program is free software: you can redistribute it and/or
16
16
 * modify it under the terms of the GNU General Public License as
43
43
                                   stdout, ferror(), remove() */
44
44
#include <stdint.h>             /* uint16_t, uint32_t */
45
45
#include <stddef.h>             /* NULL, size_t, ssize_t */
46
 
#include <stdlib.h>             /* free(), EXIT_SUCCESS, EXIT_FAILURE,
47
 
                                   srand(), strtof() */
 
46
#include <stdlib.h>             /* free(), EXIT_SUCCESS, srand(),
 
47
                                   strtof(), abort() */
48
48
#include <stdbool.h>            /* bool, false, true */
49
49
#include <string.h>             /* memset(), strcmp(), strlen(),
50
50
                                   strerror(), asprintf(), strcpy() */
62
62
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
63
63
                                   strtoimax() */
64
64
#include <assert.h>             /* assert() */
65
 
#include <errno.h>              /* perror(), errno */
66
 
#include <time.h>               /* nanosleep(), time() */
 
65
#include <errno.h>              /* perror(), errno,
 
66
                                   program_invocation_short_name */
 
67
#include <time.h>               /* nanosleep(), time(), sleep() */
67
68
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
68
69
                                   SIOCSIFFLAGS, if_indextoname(),
69
70
                                   if_nametoindex(), IF_NAMESIZE */
72
73
                                */
73
74
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
74
75
                                   getuid(), getgid(), seteuid(),
75
 
                                   setgid() */
76
 
#include <arpa/inet.h>          /* inet_pton(), htons */
 
76
                                   setgid(), pause() */
 
77
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
77
78
#include <iso646.h>             /* not, or, and */
78
79
#include <argp.h>               /* struct argp_option, error_t, struct
79
80
                                   argp_state, struct argp,
82
83
#include <signal.h>             /* sigemptyset(), sigaddset(),
83
84
                                   sigaction(), SIGTERM, sig_atomic_t,
84
85
                                   raise() */
 
86
#include <sysexits.h>           /* EX_OSERR, EX_USAGE, EX_UNAVAILABLE,
 
87
                                   EX_NOHOST, EX_IOERR, EX_PROTOCOL */
85
88
 
86
89
#ifdef __linux__
87
90
#include <sys/klog.h>           /* klogctl() */
125
128
static const char mandos_protocol_version[] = "1";
126
129
const char *argp_program_version = "mandos-client " VERSION;
127
130
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
 
131
static const char sys_class_net[] = "/sys/class/net";
 
132
char *connect_to = NULL;
 
133
 
 
134
/* Doubly linked list that need to be circularly linked when used */
 
135
typedef struct server{
 
136
  const char *ip;
 
137
  uint16_t port;
 
138
  AvahiIfIndex if_index;
 
139
  int af;
 
140
  struct timespec last_seen;
 
141
  struct server *next;
 
142
  struct server *prev;
 
143
} server;
128
144
 
129
145
/* Used for passing in values through the Avahi callback functions */
130
146
typedef struct {
135
151
  gnutls_dh_params_t dh_params;
136
152
  const char *priority;
137
153
  gpgme_ctx_t ctx;
 
154
  server *current_server;
138
155
} mandos_context;
139
156
 
140
157
/* global context so signal handler can reach it*/
141
158
mandos_context mc = { .simple_poll = NULL, .server = NULL,
142
159
                      .dh_bits = 1024, .priority = "SECURE256"
143
 
                      ":!CTYPE-X.509:+CTYPE-OPENPGP" };
 
160
                      ":!CTYPE-X.509:+CTYPE-OPENPGP",
 
161
                      .current_server = NULL };
 
162
 
 
163
sig_atomic_t quit_now = 0;
 
164
int signal_received = 0;
 
165
 
 
166
/* Function to use when printing errors */
 
167
void perror_plus(const char *print_text){
 
168
  fprintf(stderr, "Mandos plugin %s: ",
 
169
          program_invocation_short_name);
 
170
  perror(print_text);
 
171
}
144
172
 
145
173
/*
146
174
 * Make additional room in "buffer" for at least BUFFER_SIZE more
159
187
  return buffer_capacity;
160
188
}
161
189
 
 
190
int add_server(const char *ip, uint16_t port,
 
191
                 AvahiIfIndex if_index,
 
192
                 int af){
 
193
  int ret;
 
194
  server *new_server = malloc(sizeof(server));
 
195
  if(new_server == NULL){
 
196
    perror_plus("malloc");
 
197
    return -1;
 
198
  }
 
199
  *new_server = (server){ .ip = strdup(ip),
 
200
                         .port = port,
 
201
                         .if_index = if_index,
 
202
                         .af = af };
 
203
  if(new_server->ip == NULL){
 
204
    perror_plus("strdup");
 
205
    return -1;
 
206
  }
 
207
  /* unique case of first server */
 
208
  if (mc.current_server == NULL){
 
209
    new_server->next = new_server;
 
210
    new_server->prev = new_server;
 
211
    mc.current_server = new_server;
 
212
  /* Placing the new server last in the list */
 
213
  } else {
 
214
    new_server->next = mc.current_server;
 
215
    new_server->prev = mc.current_server->prev;
 
216
    new_server->prev->next = new_server;
 
217
    mc.current_server->prev = new_server;
 
218
  }
 
219
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
 
220
  if(ret == -1){
 
221
    perror_plus("clock_gettime");
 
222
    return -1;
 
223
  }
 
224
  return 0;
 
225
}
 
226
 
162
227
/* 
163
228
 * Initialize GPGME.
164
229
 */
178
243
    
179
244
    fd = (int)TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
180
245
    if(fd == -1){
181
 
      perror("open");
 
246
      perror_plus("open");
182
247
      return false;
183
248
    }
184
249
    
198
263
    
199
264
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
200
265
    if(ret == -1){
201
 
      perror("close");
 
266
      perror_plus("close");
202
267
    }
203
268
    gpgme_data_release(pgp_data);
204
269
    return true;
329
394
  
330
395
  /* Seek back to the beginning of the GPGME plaintext data buffer */
331
396
  if(gpgme_data_seek(dh_plain, (off_t)0, SEEK_SET) == -1){
332
 
    perror("gpgme_data_seek");
 
397
    perror_plus("gpgme_data_seek");
333
398
    plaintext_length = -1;
334
399
    goto decrypt_end;
335
400
  }
340
405
                                      (size_t)plaintext_length,
341
406
                                      plaintext_capacity);
342
407
    if(plaintext_capacity == 0){
343
 
        perror("incbuffer");
 
408
        perror_plus("incbuffer");
344
409
        plaintext_length = -1;
345
410
        goto decrypt_end;
346
411
    }
353
418
      break;
354
419
    }
355
420
    if(ret < 0){
356
 
      perror("gpgme_data_read");
 
421
      perror_plus("gpgme_data_read");
357
422
      plaintext_length = -1;
358
423
      goto decrypt_end;
359
424
    }
416
481
  }
417
482
  
418
483
  /* OpenPGP credentials */
419
 
  gnutls_certificate_allocate_credentials(&mc.cred);
 
484
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
420
485
  if(ret != GNUTLS_E_SUCCESS){
421
 
    fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning
422
 
                                                    from
423
 
                                                    -Wunreachable-code
424
 
                                                 */
 
486
    fprintf(stderr, "GnuTLS memory error: %s\n",
425
487
            safer_gnutls_strerror(ret));
426
488
    gnutls_global_deinit();
427
489
    return -1;
476
538
  /* GnuTLS session creation */
477
539
  do {
478
540
    ret = gnutls_init(session, GNUTLS_SERVER);
 
541
    if(quit_now){
 
542
      return -1;
 
543
    }
479
544
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
480
545
  if(ret != GNUTLS_E_SUCCESS){
481
546
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
486
551
    const char *err;
487
552
    do {
488
553
      ret = gnutls_priority_set_direct(*session, mc.priority, &err);
 
554
      if(quit_now){
 
555
        gnutls_deinit(*session);
 
556
        return -1;
 
557
      }
489
558
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
490
559
    if(ret != GNUTLS_E_SUCCESS){
491
560
      fprintf(stderr, "Syntax error at: %s\n", err);
499
568
  do {
500
569
    ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
501
570
                                 mc.cred);
 
571
    if(quit_now){
 
572
      gnutls_deinit(*session);
 
573
      return -1;
 
574
    }
502
575
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
503
576
  if(ret != GNUTLS_E_SUCCESS){
504
577
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
519
592
static void empty_log(__attribute__((unused)) AvahiLogLevel level,
520
593
                      __attribute__((unused)) const char *txt){}
521
594
 
522
 
sig_atomic_t quit_now = 0;
523
 
int signal_received = 0;
524
 
 
525
595
/* Called when a Mandos server is found */
526
596
static int start_mandos_communication(const char *ip, uint16_t port,
527
597
                                      AvahiIfIndex if_index,
533
603
    struct sockaddr_in6 in6;
534
604
  } to;
535
605
  char *buffer = NULL;
536
 
  char *decrypted_buffer;
 
606
  char *decrypted_buffer = NULL;
537
607
  size_t buffer_length = 0;
538
608
  size_t buffer_capacity = 0;
539
609
  size_t written;
540
 
  int retval = 0;
 
610
  int retval = -1;
541
611
  gnutls_session_t session;
542
612
  int pf;                       /* Protocol family */
543
613
  
 
614
  errno = 0;
 
615
  
544
616
  if(quit_now){
 
617
    errno = EINTR;
545
618
    return -1;
546
619
  }
547
620
  
554
627
    break;
555
628
  default:
556
629
    fprintf(stderr, "Bad address family: %d\n", af);
 
630
    errno = EINVAL;
557
631
    return -1;
558
632
  }
559
633
  
569
643
  
570
644
  tcp_sd = socket(pf, SOCK_STREAM, 0);
571
645
  if(tcp_sd < 0){
572
 
    perror("socket");
573
 
    retval = -1;
 
646
    int e = errno;
 
647
    perror_plus("socket");
 
648
    errno = e;
574
649
    goto mandos_end;
575
650
  }
576
651
  
577
652
  if(quit_now){
 
653
    errno = EINTR;
578
654
    goto mandos_end;
579
655
  }
580
656
  
587
663
    ret = inet_pton(af, ip, &to.in.sin_addr);
588
664
  }
589
665
  if(ret < 0 ){
590
 
    perror("inet_pton");
591
 
    retval = -1;
 
666
    int e = errno;
 
667
    perror_plus("inet_pton");
 
668
    errno = e;
592
669
    goto mandos_end;
593
670
  }
594
671
  if(ret == 0){
 
672
    int e = errno;
595
673
    fprintf(stderr, "Bad address: %s\n", ip);
596
 
    retval = -1;
 
674
    errno = e;
597
675
    goto mandos_end;
598
676
  }
599
677
  if(af == AF_INET6){
607
685
      if(if_index == AVAHI_IF_UNSPEC){
608
686
        fprintf(stderr, "An IPv6 link-local address is incomplete"
609
687
                " without a network interface\n");
610
 
        retval = -1;
 
688
        errno = EINVAL;
611
689
        goto mandos_end;
612
690
      }
613
691
      /* Set the network interface number as scope */
620
698
  }
621
699
  
622
700
  if(quit_now){
 
701
    errno = EINTR;
623
702
    goto mandos_end;
624
703
  }
625
704
  
627
706
    if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
628
707
      char interface[IF_NAMESIZE];
629
708
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
630
 
        perror("if_indextoname");
 
709
        perror_plus("if_indextoname");
631
710
      } else {
632
711
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
633
712
                ip, interface, port);
647
726
                        sizeof(addrstr));
648
727
    }
649
728
    if(pcret == NULL){
650
 
      perror("inet_ntop");
 
729
      perror_plus("inet_ntop");
651
730
    } else {
652
731
      if(strcmp(addrstr, ip) != 0){
653
732
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
656
735
  }
657
736
  
658
737
  if(quit_now){
 
738
    errno = EINTR;
659
739
    goto mandos_end;
660
740
  }
661
741
  
665
745
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
666
746
  }
667
747
  if(ret < 0){
668
 
    perror("connect");
669
 
    retval = -1;
 
748
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
 
749
      int e = errno;
 
750
      perror_plus("connect");
 
751
      errno = e;
 
752
    }
670
753
    goto mandos_end;
671
754
  }
672
755
  
673
756
  if(quit_now){
 
757
    errno = EINTR;
674
758
    goto mandos_end;
675
759
  }
676
760
  
681
765
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
682
766
                                   out_size - written));
683
767
    if(ret == -1){
684
 
      perror("write");
685
 
      retval = -1;
 
768
      int e = errno;
 
769
      perror_plus("write");
 
770
      errno = e;
686
771
      goto mandos_end;
687
772
    }
688
773
    written += (size_t)ret;
698
783
    }
699
784
  
700
785
    if(quit_now){
 
786
      errno = EINTR;
701
787
      goto mandos_end;
702
788
    }
703
789
  }
707
793
  }
708
794
  
709
795
  if(quit_now){
 
796
    errno = EINTR;
710
797
    goto mandos_end;
711
798
  }
712
799
  
 
800
  /* Spurious warning from -Wint-to-pointer-cast */
713
801
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
714
802
  
715
803
  if(quit_now){
 
804
    errno = EINTR;
716
805
    goto mandos_end;
717
806
  }
718
807
  
719
808
  do {
720
809
    ret = gnutls_handshake(session);
721
810
    if(quit_now){
 
811
      errno = EINTR;
722
812
      goto mandos_end;
723
813
    }
724
814
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
728
818
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
729
819
      gnutls_perror(ret);
730
820
    }
731
 
    retval = -1;
 
821
    errno = EPROTO;
732
822
    goto mandos_end;
733
823
  }
734
824
  
742
832
  while(true){
743
833
    
744
834
    if(quit_now){
 
835
      errno = EINTR;
745
836
      goto mandos_end;
746
837
    }
747
838
    
748
839
    buffer_capacity = incbuffer(&buffer, buffer_length,
749
840
                                   buffer_capacity);
750
841
    if(buffer_capacity == 0){
751
 
      perror("incbuffer");
752
 
      retval = -1;
 
842
      int e = errno;
 
843
      perror_plus("incbuffer");
 
844
      errno = e;
753
845
      goto mandos_end;
754
846
    }
755
847
    
756
848
    if(quit_now){
 
849
      errno = EINTR;
757
850
      goto mandos_end;
758
851
    }
759
852
    
772
865
          ret = gnutls_handshake(session);
773
866
          
774
867
          if(quit_now){
 
868
            errno = EINTR;
775
869
            goto mandos_end;
776
870
          }
777
871
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
778
872
        if(ret < 0){
779
873
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
780
874
          gnutls_perror(ret);
781
 
          retval = -1;
 
875
          errno = EPROTO;
782
876
          goto mandos_end;
783
877
        }
784
878
        break;
785
879
      default:
786
880
        fprintf(stderr, "Unknown error while reading data from"
787
881
                " encrypted session with Mandos server\n");
788
 
        retval = -1;
789
882
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
 
883
        errno = EIO;
790
884
        goto mandos_end;
791
885
      }
792
886
    } else {
799
893
  }
800
894
  
801
895
  if(quit_now){
802
 
    goto mandos_end;
803
 
  }
804
 
  
805
 
  gnutls_bye(session, GNUTLS_SHUT_RDWR);
806
 
  
807
 
  if(quit_now){
808
 
    goto mandos_end;
809
 
  }
 
896
    errno = EINTR;
 
897
    goto mandos_end;
 
898
  }
 
899
  
 
900
  do {
 
901
    ret = gnutls_bye(session, GNUTLS_SHUT_RDWR);
 
902
    if(quit_now){
 
903
      errno = EINTR;
 
904
      goto mandos_end;
 
905
    }
 
906
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
810
907
  
811
908
  if(buffer_length > 0){
812
909
    ssize_t decrypted_buffer_size;
818
915
      written = 0;
819
916
      while(written < (size_t) decrypted_buffer_size){
820
917
        if(quit_now){
 
918
          errno = EINTR;
821
919
          goto mandos_end;
822
920
        }
823
921
        
825
923
                          (size_t)decrypted_buffer_size - written,
826
924
                          stdout);
827
925
        if(ret == 0 and ferror(stdout)){
 
926
          int e = errno;
828
927
          if(debug){
829
928
            fprintf(stderr, "Error writing encrypted data: %s\n",
830
929
                    strerror(errno));
831
930
          }
832
 
          retval = -1;
833
 
          break;
 
931
          errno = e;
 
932
          goto mandos_end;
834
933
        }
835
934
        written += (size_t)ret;
836
935
      }
837
 
      free(decrypted_buffer);
838
 
    } else {
839
 
      retval = -1;
 
936
      retval = 0;
840
937
    }
841
 
  } else {
842
 
    retval = -1;
843
938
  }
844
939
  
845
940
  /* Shutdown procedure */
846
941
  
847
942
 mandos_end:
848
 
  free(buffer);
849
 
  if(tcp_sd >= 0){
850
 
    ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
851
 
  }
852
 
  if(ret == -1){
853
 
    perror("close");
854
 
  }
855
 
  gnutls_deinit(session);
856
 
  if(quit_now){
857
 
    retval = -1;
 
943
  {
 
944
    int e = errno;
 
945
    free(decrypted_buffer);
 
946
    free(buffer);
 
947
    if(tcp_sd >= 0){
 
948
      ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
 
949
    }
 
950
    if(ret == -1){
 
951
      if(e == 0){
 
952
        e = errno;
 
953
      }
 
954
      perror_plus("close");
 
955
    }
 
956
    gnutls_deinit(session);
 
957
    errno = e;
 
958
    if(quit_now){
 
959
      errno = EINTR;
 
960
      retval = -1;
 
961
    }
858
962
  }
859
963
  return retval;
860
964
}
903
1007
                                           avahi_proto_to_af(proto));
904
1008
      if(ret == 0){
905
1009
        avahi_simple_poll_quit(mc.simple_poll);
 
1010
      } else {
 
1011
        ret = add_server(ip, port, interface,
 
1012
                         avahi_proto_to_af(proto));
906
1013
      }
907
1014
    }
908
1015
  }
962
1069
  }
963
1070
}
964
1071
 
965
 
/* stop main loop after sigterm has been called */
 
1072
/* Signal handler that stops main loop after SIGTERM */
966
1073
static void handle_sigterm(int sig){
967
1074
  if(quit_now){
968
1075
    return;
970
1077
  quit_now = 1;
971
1078
  signal_received = sig;
972
1079
  int old_errno = errno;
 
1080
  /* set main loop to exit */
973
1081
  if(mc.simple_poll != NULL){
974
1082
    avahi_simple_poll_quit(mc.simple_poll);
975
1083
  }
976
1084
  errno = old_errno;
977
1085
}
978
1086
 
 
1087
/* 
 
1088
 * This function determines if a directory entry in /sys/class/net
 
1089
 * corresponds to an acceptable network device.
 
1090
 * (This function is passed to scandir(3) as a filter function.)
 
1091
 */
 
1092
int good_interface(const struct dirent *if_entry){
 
1093
  ssize_t ssret;
 
1094
  char *flagname = NULL;
 
1095
  if(if_entry->d_name[0] == '.'){
 
1096
    return 0;
 
1097
  }
 
1098
  int ret = asprintf(&flagname, "%s/%s/flags", sys_class_net,
 
1099
                     if_entry->d_name);
 
1100
  if(ret < 0){
 
1101
    perror_plus("asprintf");
 
1102
    return 0;
 
1103
  }
 
1104
  int flags_fd = (int)TEMP_FAILURE_RETRY(open(flagname, O_RDONLY));
 
1105
  if(flags_fd == -1){
 
1106
    perror_plus("open");
 
1107
    free(flagname);
 
1108
    return 0;
 
1109
  }
 
1110
  free(flagname);
 
1111
  typedef short ifreq_flags;    /* ifreq.ifr_flags in netdevice(7) */
 
1112
  /* read line from flags_fd */
 
1113
  ssize_t to_read = 2+(sizeof(ifreq_flags)*2)+1; /* "0x1003\n" */
 
1114
  char *flagstring = malloc((size_t)to_read+1); /* +1 for final \0 */
 
1115
  flagstring[(size_t)to_read] = '\0';
 
1116
  if(flagstring == NULL){
 
1117
    perror_plus("malloc");
 
1118
    close(flags_fd);
 
1119
    return 0;
 
1120
  }
 
1121
  while(to_read > 0){
 
1122
    ssret = (ssize_t)TEMP_FAILURE_RETRY(read(flags_fd, flagstring,
 
1123
                                             (size_t)to_read));
 
1124
    if(ssret == -1){
 
1125
      perror_plus("read");
 
1126
      free(flagstring);
 
1127
      close(flags_fd);
 
1128
      return 0;
 
1129
    }
 
1130
    to_read -= ssret;
 
1131
    if(ssret == 0){
 
1132
      break;
 
1133
    }
 
1134
  }
 
1135
  close(flags_fd);
 
1136
  intmax_t tmpmax;
 
1137
  char *tmp;
 
1138
  errno = 0;
 
1139
  tmpmax = strtoimax(flagstring, &tmp, 0);
 
1140
  if(errno != 0 or tmp == flagstring or (*tmp != '\0'
 
1141
                                         and not (isspace(*tmp)))
 
1142
     or tmpmax != (ifreq_flags)tmpmax){
 
1143
    if(debug){
 
1144
      fprintf(stderr, "Invalid flags \"%s\" for interface \"%s\"\n",
 
1145
              flagstring, if_entry->d_name);
 
1146
    }
 
1147
    free(flagstring);
 
1148
    return 0;
 
1149
  }
 
1150
  free(flagstring);
 
1151
  ifreq_flags flags = (ifreq_flags)tmpmax;
 
1152
  /* Reject the loopback device */
 
1153
  if(flags & IFF_LOOPBACK){
 
1154
    if(debug){
 
1155
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
 
1156
              if_entry->d_name);
 
1157
    }
 
1158
    return 0;
 
1159
  }
 
1160
  /* Accept point-to-point devices only if connect_to is specified */
 
1161
  if(connect_to != NULL and (flags & IFF_POINTOPOINT)){
 
1162
    if(debug){
 
1163
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
 
1164
              if_entry->d_name);
 
1165
    }
 
1166
    return 1;
 
1167
  }
 
1168
  /* Otherwise, reject non-broadcast-capable devices */
 
1169
  if(not (flags & IFF_BROADCAST)){
 
1170
    if(debug){
 
1171
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
 
1172
              if_entry->d_name);
 
1173
    }
 
1174
    return 0;
 
1175
  }
 
1176
  /* Reject non-ARP interfaces (including dummy interfaces) */
 
1177
  if(flags & IFF_NOARP){
 
1178
    if(debug){
 
1179
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n",
 
1180
              if_entry->d_name);
 
1181
    }
 
1182
    return 0;
 
1183
  }
 
1184
  /* Accept this device */
 
1185
  if(debug){
 
1186
    fprintf(stderr, "Interface \"%s\" is acceptable\n",
 
1187
            if_entry->d_name);
 
1188
  }
 
1189
  return 1;
 
1190
}
 
1191
 
 
1192
int notdotentries(const struct dirent *direntry){
 
1193
  /* Skip "." and ".." */
 
1194
  if(direntry->d_name[0] == '.'
 
1195
     and (direntry->d_name[1] == '\0'
 
1196
          or (direntry->d_name[1] == '.'
 
1197
              and direntry->d_name[2] == '\0'))){
 
1198
    return 0;
 
1199
  }
 
1200
  return 1;
 
1201
}
 
1202
 
 
1203
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
 
1204
  int ret;
 
1205
  struct timespec now;
 
1206
  struct timespec waited_time;
 
1207
  intmax_t block_time;
 
1208
 
 
1209
  while(true){
 
1210
    if(mc.current_server == NULL){
 
1211
      if (debug){
 
1212
        fprintf(stderr,
 
1213
                "Wait until first server is found. No timeout!\n");
 
1214
      }
 
1215
      ret = avahi_simple_poll_iterate(s, -1);
 
1216
    } else {
 
1217
      if (debug){
 
1218
        fprintf(stderr, "Check current_server if we should run it,"
 
1219
                " or wait\n");
 
1220
      }
 
1221
      /* the current time */
 
1222
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
 
1223
      if(ret == -1){
 
1224
        perror_plus("clock_gettime");
 
1225
        return -1;
 
1226
      }
 
1227
      /* Calculating in ms how long time between now and server
 
1228
         who we visted longest time ago. Now - last seen.  */
 
1229
      waited_time.tv_sec = (now.tv_sec
 
1230
                            - mc.current_server->last_seen.tv_sec);
 
1231
      waited_time.tv_nsec = (now.tv_nsec
 
1232
                             - mc.current_server->last_seen.tv_nsec);
 
1233
      /* total time is 10s/10,000ms.
 
1234
         Converting to s from ms by dividing by 1,000,
 
1235
         and ns to ms by dividing by 1,000,000. */
 
1236
      block_time = ((retry_interval
 
1237
                     - ((intmax_t)waited_time.tv_sec * 1000))
 
1238
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
 
1239
 
 
1240
      if (debug){
 
1241
        fprintf(stderr, "Blocking for %ld ms\n", block_time);
 
1242
      }
 
1243
 
 
1244
      if(block_time <= 0){
 
1245
        ret = start_mandos_communication(mc.current_server->ip,
 
1246
                                         mc.current_server->port,
 
1247
                                         mc.current_server->if_index,
 
1248
                                         mc.current_server->af);
 
1249
        if(ret == 0){
 
1250
          avahi_simple_poll_quit(mc.simple_poll);
 
1251
          return 0;
 
1252
        }
 
1253
        ret = clock_gettime(CLOCK_MONOTONIC,
 
1254
                            &mc.current_server->last_seen);
 
1255
        if(ret == -1){
 
1256
          perror_plus("clock_gettime");
 
1257
          return -1;
 
1258
        }
 
1259
        mc.current_server = mc.current_server->next;
 
1260
        block_time = 0;         /* Call avahi to find new Mandos
 
1261
                                   servers, but don't block */
 
1262
      }
 
1263
      
 
1264
      ret = avahi_simple_poll_iterate(s, (int)block_time);
 
1265
    }
 
1266
    if(ret != 0){
 
1267
      if (ret > 0 or errno != EINTR) {
 
1268
        return (ret != 1) ? ret : 0;
 
1269
      }
 
1270
    }
 
1271
  }
 
1272
}
 
1273
 
979
1274
int main(int argc, char *argv[]){
980
1275
  AvahiSServiceBrowser *sb = NULL;
981
1276
  int error;
983
1278
  intmax_t tmpmax;
984
1279
  char *tmp;
985
1280
  int exitcode = EXIT_SUCCESS;
986
 
  const char *interface = "eth0";
 
1281
  const char *interface = "";
987
1282
  struct ifreq network;
988
1283
  int sd = -1;
989
1284
  bool take_down_interface = false;
990
1285
  uid_t uid;
991
1286
  gid_t gid;
992
 
  char *connect_to = NULL;
993
1287
  char tempdir[] = "/tmp/mandosXXXXXX";
994
1288
  bool tempdir_created = false;
995
1289
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
999
1293
  bool gnutls_initialized = false;
1000
1294
  bool gpgme_initialized = false;
1001
1295
  float delay = 2.5f;
 
1296
  double retry_interval = 10; /* 10s between trying a server and
 
1297
                                 retrying the same server again */
1002
1298
  
1003
1299
  struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
1004
1300
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
1010
1306
  errno = 0;
1011
1307
  ret = setgid(gid);
1012
1308
  if(ret == -1){
1013
 
    perror("setgid");
 
1309
    perror_plus("setgid");
1014
1310
  }
1015
1311
  
1016
1312
  /* Lower user privileges (temporarily) */
1017
1313
  errno = 0;
1018
1314
  ret = seteuid(uid);
1019
1315
  if(ret == -1){
1020
 
    perror("seteuid");
 
1316
    perror_plus("seteuid");
1021
1317
  }
1022
1318
  
1023
1319
  if(quit_now){
1058
1354
        .arg = "SECONDS",
1059
1355
        .doc = "Maximum delay to wait for interface startup",
1060
1356
        .group = 2 },
 
1357
      { .name = "retry", .key = 132,
 
1358
        .arg = "SECONDS",
 
1359
        .doc = "Retry interval used when denied by the mandos server",
 
1360
        .group = 2 },
 
1361
      /*
 
1362
       * These reproduce what we would get without ARGP_NO_HELP
 
1363
       */
 
1364
      { .name = "help", .key = '?',
 
1365
        .doc = "Give this help list", .group = -1 },
 
1366
      { .name = "usage", .key = -3,
 
1367
        .doc = "Give a short usage message", .group = -1 },
 
1368
      { .name = "version", .key = 'V',
 
1369
        .doc = "Print program version", .group = -1 },
1061
1370
      { .name = NULL }
1062
1371
    };
1063
1372
    
1064
1373
    error_t parse_opt(int key, char *arg,
1065
1374
                      struct argp_state *state){
 
1375
      errno = 0;
1066
1376
      switch(key){
1067
1377
      case 128:                 /* --debug */
1068
1378
        debug = true;
1084
1394
        tmpmax = strtoimax(arg, &tmp, 10);
1085
1395
        if(errno != 0 or tmp == arg or *tmp != '\0'
1086
1396
           or tmpmax != (typeof(mc.dh_bits))tmpmax){
1087
 
          fprintf(stderr, "Bad number of DH bits\n");
1088
 
          exit(EXIT_FAILURE);
 
1397
          argp_error(state, "Bad number of DH bits");
1089
1398
        }
1090
1399
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
1091
1400
        break;
1096
1405
        errno = 0;
1097
1406
        delay = strtof(arg, &tmp);
1098
1407
        if(errno != 0 or tmp == arg or *tmp != '\0'){
1099
 
          fprintf(stderr, "Bad delay\n");
1100
 
          exit(EXIT_FAILURE);
 
1408
          argp_error(state, "Bad delay");
 
1409
        }
 
1410
      case 132:                 /* --retry */
 
1411
        errno = 0;
 
1412
        retry_interval = strtod(arg, &tmp);
 
1413
        if(errno != 0 or tmp == arg or *tmp != '\0'
 
1414
           or (retry_interval * 1000) > INT_MAX){
 
1415
          argp_error(state, "Bad retry interval");
1101
1416
        }
1102
1417
        break;
1103
 
      case ARGP_KEY_ARG:
1104
 
        argp_usage(state);
1105
 
      case ARGP_KEY_END:
 
1418
        /*
 
1419
         * These reproduce what we would get without ARGP_NO_HELP
 
1420
         */
 
1421
      case '?':                 /* --help */
 
1422
        argp_state_help(state, state->out_stream,
 
1423
                        (ARGP_HELP_STD_HELP | ARGP_HELP_EXIT_ERR)
 
1424
                        & ~(unsigned int)ARGP_HELP_EXIT_OK);
 
1425
      case -3:                  /* --usage */
 
1426
        argp_state_help(state, state->out_stream,
 
1427
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
 
1428
      case 'V':                 /* --version */
 
1429
        fprintf(state->out_stream, "%s\n", argp_program_version);
 
1430
        exit(argp_err_exit_status);
1106
1431
        break;
1107
1432
      default:
1108
1433
        return ARGP_ERR_UNKNOWN;
1109
1434
      }
1110
 
      return 0;
 
1435
      return errno;
1111
1436
    }
1112
1437
    
1113
1438
    struct argp argp = { .options = options, .parser = parse_opt,
1114
1439
                         .args_doc = "",
1115
1440
                         .doc = "Mandos client -- Get and decrypt"
1116
1441
                         " passwords from a Mandos server" };
1117
 
    ret = argp_parse(&argp, argc, argv, 0, 0, NULL);
1118
 
    if(ret == ARGP_ERR_UNKNOWN){
1119
 
      fprintf(stderr, "Unknown error while parsing arguments\n");
1120
 
      exitcode = EXIT_FAILURE;
1121
 
      goto end;
 
1442
    ret = argp_parse(&argp, argc, argv,
 
1443
                     ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
 
1444
    switch(ret){
 
1445
    case 0:
 
1446
      break;
 
1447
    case ENOMEM:
 
1448
    default:
 
1449
      errno = ret;
 
1450
      perror_plus("argp_parse");
 
1451
      exitcode = EX_OSERR;
 
1452
      goto end;
 
1453
    case EINVAL:
 
1454
      exitcode = EX_USAGE;
 
1455
      goto end;
 
1456
    }
 
1457
  }
 
1458
    
 
1459
  {
 
1460
    /* Work around Debian bug #633582:
 
1461
       <http://bugs.debian.org/633582> */
 
1462
    struct stat st;
 
1463
    
 
1464
    /* Re-raise priviliges */
 
1465
    errno = 0;
 
1466
    ret = seteuid(0);
 
1467
    if(ret == -1){
 
1468
      perror_plus("seteuid");
 
1469
    }
 
1470
    
 
1471
    int seckey_fd = open(PATHDIR "/" SECKEY, O_RDONLY);
 
1472
    if(seckey_fd == -1){
 
1473
      perror_plus("open");
 
1474
    } else {
 
1475
      ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
 
1476
      if(ret == -1){
 
1477
        perror_plus("fstat");
 
1478
      } else {
 
1479
        if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
 
1480
          ret = fchown(seckey_fd, uid, gid);
 
1481
          if(ret == -1){
 
1482
            perror_plus("fchown");
 
1483
          }
 
1484
        }
 
1485
      }
 
1486
      TEMP_FAILURE_RETRY(close(seckey_fd));
 
1487
    }
 
1488
    
 
1489
    int pubkey_fd = open(PATHDIR "/" PUBKEY, O_RDONLY);
 
1490
    if(pubkey_fd == -1){
 
1491
      perror_plus("open");
 
1492
    } else {
 
1493
      ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
 
1494
      if(ret == -1){
 
1495
        perror_plus("fstat");
 
1496
      } else {
 
1497
        if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
 
1498
          ret = fchown(pubkey_fd, uid, gid);
 
1499
          if(ret == -1){
 
1500
            perror_plus("fchown");
 
1501
          }
 
1502
        }
 
1503
      }
 
1504
      TEMP_FAILURE_RETRY(close(pubkey_fd));
 
1505
    }
 
1506
    
 
1507
    /* Lower privileges */
 
1508
    errno = 0;
 
1509
    ret = seteuid(uid);
 
1510
    if(ret == -1){
 
1511
      perror_plus("seteuid");
1122
1512
    }
1123
1513
  }
1124
1514
  
1125
1515
  if(not debug){
1126
1516
    avahi_set_log_function(empty_log);
1127
1517
  }
 
1518
 
 
1519
  if(interface[0] == '\0'){
 
1520
    struct dirent **direntries;
 
1521
    ret = scandir(sys_class_net, &direntries, good_interface,
 
1522
                  alphasort);
 
1523
    if(ret >= 1){
 
1524
      /* Pick the first good interface */
 
1525
      interface = strdup(direntries[0]->d_name);
 
1526
      if(debug){
 
1527
        fprintf(stderr, "Using interface \"%s\"\n", interface);
 
1528
      }
 
1529
      if(interface == NULL){
 
1530
        perror_plus("malloc");
 
1531
        free(direntries);
 
1532
        exitcode = EXIT_FAILURE;
 
1533
        goto end;
 
1534
      }
 
1535
      free(direntries);
 
1536
    } else {
 
1537
      free(direntries);
 
1538
      fprintf(stderr, "Could not find a network interface\n");
 
1539
      exitcode = EXIT_FAILURE;
 
1540
      goto end;
 
1541
    }
 
1542
  }
1128
1543
  
1129
1544
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
1130
1545
     from the signal handler */
1133
1548
  mc.simple_poll = avahi_simple_poll_new();
1134
1549
  if(mc.simple_poll == NULL){
1135
1550
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
1136
 
    exitcode = EXIT_FAILURE;
 
1551
    exitcode = EX_UNAVAILABLE;
1137
1552
    goto end;
1138
1553
  }
1139
1554
  
1140
1555
  sigemptyset(&sigterm_action.sa_mask);
1141
1556
  ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
1142
1557
  if(ret == -1){
1143
 
    perror("sigaddset");
1144
 
    exitcode = EXIT_FAILURE;
 
1558
    perror_plus("sigaddset");
 
1559
    exitcode = EX_OSERR;
1145
1560
    goto end;
1146
1561
  }
1147
1562
  ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
1148
1563
  if(ret == -1){
1149
 
    perror("sigaddset");
1150
 
    exitcode = EXIT_FAILURE;
 
1564
    perror_plus("sigaddset");
 
1565
    exitcode = EX_OSERR;
1151
1566
    goto end;
1152
1567
  }
1153
1568
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
1154
1569
  if(ret == -1){
1155
 
    perror("sigaddset");
1156
 
    exitcode = EXIT_FAILURE;
 
1570
    perror_plus("sigaddset");
 
1571
    exitcode = EX_OSERR;
1157
1572
    goto end;
1158
1573
  }
1159
1574
  /* Need to check if the handler is SIG_IGN before handling:
1162
1577
  */
1163
1578
  ret = sigaction(SIGINT, NULL, &old_sigterm_action);
1164
1579
  if(ret == -1){
1165
 
    perror("sigaction");
1166
 
    return EXIT_FAILURE;
 
1580
    perror_plus("sigaction");
 
1581
    return EX_OSERR;
1167
1582
  }
1168
1583
  if(old_sigterm_action.sa_handler != SIG_IGN){
1169
1584
    ret = sigaction(SIGINT, &sigterm_action, NULL);
1170
1585
    if(ret == -1){
1171
 
      perror("sigaction");
1172
 
      exitcode = EXIT_FAILURE;
 
1586
      perror_plus("sigaction");
 
1587
      exitcode = EX_OSERR;
1173
1588
      goto end;
1174
1589
    }
1175
1590
  }
1176
1591
  ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
1177
1592
  if(ret == -1){
1178
 
    perror("sigaction");
1179
 
    return EXIT_FAILURE;
 
1593
    perror_plus("sigaction");
 
1594
    return EX_OSERR;
1180
1595
  }
1181
1596
  if(old_sigterm_action.sa_handler != SIG_IGN){
1182
1597
    ret = sigaction(SIGHUP, &sigterm_action, NULL);
1183
1598
    if(ret == -1){
1184
 
      perror("sigaction");
1185
 
      exitcode = EXIT_FAILURE;
 
1599
      perror_plus("sigaction");
 
1600
      exitcode = EX_OSERR;
1186
1601
      goto end;
1187
1602
    }
1188
1603
  }
1189
1604
  ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
1190
1605
  if(ret == -1){
1191
 
    perror("sigaction");
1192
 
    return EXIT_FAILURE;
 
1606
    perror_plus("sigaction");
 
1607
    return EX_OSERR;
1193
1608
  }
1194
1609
  if(old_sigterm_action.sa_handler != SIG_IGN){
1195
1610
    ret = sigaction(SIGTERM, &sigterm_action, NULL);
1196
1611
    if(ret == -1){
1197
 
      perror("sigaction");
1198
 
      exitcode = EXIT_FAILURE;
 
1612
      perror_plus("sigaction");
 
1613
      exitcode = EX_OSERR;
1199
1614
      goto end;
1200
1615
    }
1201
1616
  }
1202
1617
  
1203
1618
  /* If the interface is down, bring it up */
1204
 
  if(interface[0] != '\0'){
 
1619
  if(strcmp(interface, "none") != 0){
1205
1620
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1206
1621
    if(if_index == 0){
1207
1622
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
1208
 
      exitcode = EXIT_FAILURE;
 
1623
      exitcode = EX_UNAVAILABLE;
1209
1624
      goto end;
1210
1625
    }
1211
1626
    
1217
1632
    errno = 0;
1218
1633
    ret = seteuid(0);
1219
1634
    if(ret == -1){
1220
 
      perror("seteuid");
 
1635
      perror_plus("seteuid");
1221
1636
    }
1222
1637
    
1223
1638
#ifdef __linux__
1224
1639
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1225
 
       messages to mess up the prompt */
 
1640
       messages about the network interface to mess up the prompt */
1226
1641
    ret = klogctl(8, NULL, 5);
1227
1642
    bool restore_loglevel = true;
1228
1643
    if(ret == -1){
1229
1644
      restore_loglevel = false;
1230
 
      perror("klogctl");
 
1645
      perror_plus("klogctl");
1231
1646
    }
1232
1647
#endif  /* __linux__ */
1233
1648
    
1234
1649
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1235
1650
    if(sd < 0){
1236
 
      perror("socket");
1237
 
      exitcode = EXIT_FAILURE;
 
1651
      perror_plus("socket");
 
1652
      exitcode = EX_OSERR;
1238
1653
#ifdef __linux__
1239
1654
      if(restore_loglevel){
1240
1655
        ret = klogctl(7, NULL, 0);
1241
1656
        if(ret == -1){
1242
 
          perror("klogctl");
 
1657
          perror_plus("klogctl");
1243
1658
        }
1244
1659
      }
1245
1660
#endif  /* __linux__ */
1247
1662
      errno = 0;
1248
1663
      ret = seteuid(uid);
1249
1664
      if(ret == -1){
1250
 
        perror("seteuid");
 
1665
        perror_plus("seteuid");
1251
1666
      }
1252
1667
      goto end;
1253
1668
    }
1254
1669
    strcpy(network.ifr_name, interface);
1255
1670
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
1256
1671
    if(ret == -1){
1257
 
      perror("ioctl SIOCGIFFLAGS");
 
1672
      perror_plus("ioctl SIOCGIFFLAGS");
1258
1673
#ifdef __linux__
1259
1674
      if(restore_loglevel){
1260
1675
        ret = klogctl(7, NULL, 0);
1261
1676
        if(ret == -1){
1262
 
          perror("klogctl");
 
1677
          perror_plus("klogctl");
1263
1678
        }
1264
1679
      }
1265
1680
#endif  /* __linux__ */
1266
 
      exitcode = EXIT_FAILURE;
 
1681
      exitcode = EX_OSERR;
1267
1682
      /* Lower privileges */
1268
1683
      errno = 0;
1269
1684
      ret = seteuid(uid);
1270
1685
      if(ret == -1){
1271
 
        perror("seteuid");
 
1686
        perror_plus("seteuid");
1272
1687
      }
1273
1688
      goto end;
1274
1689
    }
1278
1693
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1279
1694
      if(ret == -1){
1280
1695
        take_down_interface = false;
1281
 
        perror("ioctl SIOCSIFFLAGS");
1282
 
        exitcode = EXIT_FAILURE;
 
1696
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
 
1697
        exitcode = EX_OSERR;
1283
1698
#ifdef __linux__
1284
1699
        if(restore_loglevel){
1285
1700
          ret = klogctl(7, NULL, 0);
1286
1701
          if(ret == -1){
1287
 
            perror("klogctl");
 
1702
            perror_plus("klogctl");
1288
1703
          }
1289
1704
        }
1290
1705
#endif  /* __linux__ */
1292
1707
        errno = 0;
1293
1708
        ret = seteuid(uid);
1294
1709
        if(ret == -1){
1295
 
          perror("seteuid");
 
1710
          perror_plus("seteuid");
1296
1711
        }
1297
1712
        goto end;
1298
1713
      }
1299
1714
    }
1300
 
    /* sleep checking until interface is running */
 
1715
    /* Sleep checking until interface is running.
 
1716
       Check every 0.25s, up to total time of delay */
1301
1717
    for(int i=0; i < delay * 4; i++){
1302
1718
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1303
1719
      if(ret == -1){
1304
 
        perror("ioctl SIOCGIFFLAGS");
 
1720
        perror_plus("ioctl SIOCGIFFLAGS");
1305
1721
      } else if(network.ifr_flags & IFF_RUNNING){
1306
1722
        break;
1307
1723
      }
1308
1724
      struct timespec sleeptime = { .tv_nsec = 250000000 };
1309
1725
      ret = nanosleep(&sleeptime, NULL);
1310
1726
      if(ret == -1 and errno != EINTR){
1311
 
        perror("nanosleep");
 
1727
        perror_plus("nanosleep");
1312
1728
      }
1313
1729
    }
1314
1730
    if(not take_down_interface){
1315
1731
      /* We won't need the socket anymore */
1316
1732
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1317
1733
      if(ret == -1){
1318
 
        perror("close");
 
1734
        perror_plus("close");
1319
1735
      }
1320
1736
    }
1321
1737
#ifdef __linux__
1323
1739
      /* Restores kernel loglevel to default */
1324
1740
      ret = klogctl(7, NULL, 0);
1325
1741
      if(ret == -1){
1326
 
        perror("klogctl");
 
1742
        perror_plus("klogctl");
1327
1743
      }
1328
1744
    }
1329
1745
#endif  /* __linux__ */
1333
1749
      /* Lower privileges */
1334
1750
      ret = seteuid(uid);
1335
1751
      if(ret == -1){
1336
 
        perror("seteuid");
 
1752
        perror_plus("seteuid");
1337
1753
      }
1338
1754
    } else {
1339
1755
      /* Lower privileges permanently */
1340
1756
      ret = setuid(uid);
1341
1757
      if(ret == -1){
1342
 
        perror("setuid");
 
1758
        perror_plus("setuid");
1343
1759
      }
1344
1760
    }
1345
1761
  }
1351
1767
  ret = init_gnutls_global(pubkey, seckey);
1352
1768
  if(ret == -1){
1353
1769
    fprintf(stderr, "init_gnutls_global failed\n");
1354
 
    exitcode = EXIT_FAILURE;
 
1770
    exitcode = EX_UNAVAILABLE;
1355
1771
    goto end;
1356
1772
  } else {
1357
1773
    gnutls_initialized = true;
1361
1777
    goto end;
1362
1778
  }
1363
1779
  
 
1780
  if(mkdtemp(tempdir) == NULL){
 
1781
    perror_plus("mkdtemp");
 
1782
    goto end;
 
1783
  }
1364
1784
  tempdir_created = true;
1365
 
  if(mkdtemp(tempdir) == NULL){
1366
 
    tempdir_created = false;
1367
 
    perror("mkdtemp");
1368
 
    goto end;
1369
 
  }
1370
1785
  
1371
1786
  if(quit_now){
1372
1787
    goto end;
1374
1789
  
1375
1790
  if(not init_gpgme(pubkey, seckey, tempdir)){
1376
1791
    fprintf(stderr, "init_gpgme failed\n");
1377
 
    exitcode = EXIT_FAILURE;
 
1792
    exitcode = EX_UNAVAILABLE;
1378
1793
    goto end;
1379
1794
  } else {
1380
1795
    gpgme_initialized = true;
1390
1805
    char *address = strrchr(connect_to, ':');
1391
1806
    if(address == NULL){
1392
1807
      fprintf(stderr, "No colon in address\n");
1393
 
      exitcode = EXIT_FAILURE;
 
1808
      exitcode = EX_USAGE;
1394
1809
      goto end;
1395
1810
    }
1396
1811
    
1404
1819
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
1405
1820
       or tmpmax != (uint16_t)tmpmax){
1406
1821
      fprintf(stderr, "Bad port number\n");
1407
 
      exitcode = EXIT_FAILURE;
 
1822
      exitcode = EX_USAGE;
1408
1823
      goto end;
1409
1824
    }
1410
1825
  
1426
1841
    if(quit_now){
1427
1842
      goto end;
1428
1843
    }
1429
 
    
1430
 
    ret = start_mandos_communication(address, port, if_index, af);
1431
 
    if(ret < 0){
1432
 
      exitcode = EXIT_FAILURE;
1433
 
    } else {
 
1844
 
 
1845
    while(not quit_now){
 
1846
      ret = start_mandos_communication(address, port, if_index, af);
 
1847
      if(quit_now or ret == 0){
 
1848
        break;
 
1849
      }
 
1850
      sleep((int)retry_interval or 1);
 
1851
    };
 
1852
 
 
1853
    if (not quit_now){
1434
1854
      exitcode = EXIT_SUCCESS;
1435
1855
    }
 
1856
 
1436
1857
    goto end;
1437
1858
  }
1438
1859
  
1462
1883
  if(mc.server == NULL){
1463
1884
    fprintf(stderr, "Failed to create Avahi server: %s\n",
1464
1885
            avahi_strerror(error));
1465
 
    exitcode = EXIT_FAILURE;
 
1886
    exitcode = EX_UNAVAILABLE;
1466
1887
    goto end;
1467
1888
  }
1468
1889
  
1477
1898
  if(sb == NULL){
1478
1899
    fprintf(stderr, "Failed to create service browser: %s\n",
1479
1900
            avahi_strerror(avahi_server_errno(mc.server)));
1480
 
    exitcode = EXIT_FAILURE;
 
1901
    exitcode = EX_UNAVAILABLE;
1481
1902
    goto end;
1482
1903
  }
1483
1904
  
1490
1911
  if(debug){
1491
1912
    fprintf(stderr, "Starting Avahi loop search\n");
1492
1913
  }
1493
 
  
1494
 
  avahi_simple_poll_loop(mc.simple_poll);
 
1914
 
 
1915
  ret = avahi_loop_with_timeout(mc.simple_poll,
 
1916
                                (int)(retry_interval * 1000));
 
1917
  if(debug){
 
1918
    fprintf(stderr, "avahi_loop_with_timeout exited %s\n",
 
1919
            (ret == 0) ? "successfully" : "with error");
 
1920
  }
1495
1921
  
1496
1922
 end:
1497
1923
  
1518
1944
  if(gpgme_initialized){
1519
1945
    gpgme_release(mc.ctx);
1520
1946
  }
 
1947
 
 
1948
  /* Cleans up the circular linked list of Mandos servers the client
 
1949
     has seen */
 
1950
  if(mc.current_server != NULL){
 
1951
    mc.current_server->prev->next = NULL;
 
1952
    while(mc.current_server != NULL){
 
1953
      server *next = mc.current_server->next;
 
1954
      free(mc.current_server);
 
1955
      mc.current_server = next;
 
1956
    }
 
1957
  }
1521
1958
  
1522
1959
  /* Take down the network interface */
1523
1960
  if(take_down_interface){
1525
1962
    errno = 0;
1526
1963
    ret = seteuid(0);
1527
1964
    if(ret == -1){
1528
 
      perror("seteuid");
 
1965
      perror_plus("seteuid");
1529
1966
    }
1530
1967
    if(geteuid() == 0){
1531
1968
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1532
1969
      if(ret == -1){
1533
 
        perror("ioctl SIOCGIFFLAGS");
 
1970
        perror_plus("ioctl SIOCGIFFLAGS");
1534
1971
      } else if(network.ifr_flags & IFF_UP) {
1535
 
        network.ifr_flags &= ~IFF_UP; /* clear flag */
 
1972
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
1536
1973
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
1537
1974
        if(ret == -1){
1538
 
          perror("ioctl SIOCSIFFLAGS");
 
1975
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
1539
1976
        }
1540
1977
      }
1541
1978
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1542
1979
      if(ret == -1){
1543
 
        perror("close");
 
1980
        perror_plus("close");
1544
1981
      }
1545
1982
      /* Lower privileges permanently */
1546
1983
      errno = 0;
1547
1984
      ret = setuid(uid);
1548
1985
      if(ret == -1){
1549
 
        perror("setuid");
 
1986
        perror_plus("setuid");
1550
1987
      }
1551
1988
    }
1552
1989
  }
1553
1990
  
1554
 
  /* Removes the temp directory used by GPGME */
 
1991
  /* Removes the GPGME temp directory and all files inside */
1555
1992
  if(tempdir_created){
1556
 
    DIR *d;
1557
 
    struct dirent *direntry;
1558
 
    d = opendir(tempdir);
1559
 
    if(d == NULL){
1560
 
      if(errno != ENOENT){
1561
 
        perror("opendir");
1562
 
      }
1563
 
    } else {
1564
 
      while(true){
1565
 
        direntry = readdir(d);
1566
 
        if(direntry == NULL){
1567
 
          break;
1568
 
        }
1569
 
        /* Skip "." and ".." */
1570
 
        if(direntry->d_name[0] == '.'
1571
 
           and (direntry->d_name[1] == '\0'
1572
 
                or (direntry->d_name[1] == '.'
1573
 
                    and direntry->d_name[2] == '\0'))){
1574
 
          continue;
1575
 
        }
 
1993
    struct dirent **direntries = NULL;
 
1994
    struct dirent *direntry = NULL;
 
1995
    ret = scandir(tempdir, &direntries, notdotentries, alphasort);
 
1996
    if (ret > 0){
 
1997
      for(int i = 0; i < ret; i++){
 
1998
        direntry = direntries[i];
1576
1999
        char *fullname = NULL;
1577
2000
        ret = asprintf(&fullname, "%s/%s", tempdir,
1578
2001
                       direntry->d_name);
1579
2002
        if(ret < 0){
1580
 
          perror("asprintf");
 
2003
          perror_plus("asprintf");
1581
2004
          continue;
1582
2005
        }
1583
2006
        ret = remove(fullname);
1587
2010
        }
1588
2011
        free(fullname);
1589
2012
      }
1590
 
      closedir(d);
 
2013
    }
 
2014
 
 
2015
    /* need to be cleaned even if ret == 0 because man page doesn't
 
2016
       specify */
 
2017
    free(direntries);
 
2018
    if (ret == -1){
 
2019
      perror_plus("scandir");
1591
2020
    }
1592
2021
    ret = rmdir(tempdir);
1593
2022
    if(ret == -1 and errno != ENOENT){
1594
 
      perror("rmdir");
 
2023
      perror_plus("rmdir");
1595
2024
    }
1596
2025
  }
1597
2026
  
1598
2027
  if(quit_now){
1599
2028
    sigemptyset(&old_sigterm_action.sa_mask);
1600
2029
    old_sigterm_action.sa_handler = SIG_DFL;
1601
 
    ret = sigaction(signal_received, &old_sigterm_action, NULL);
 
2030
    ret = (int)TEMP_FAILURE_RETRY(sigaction(signal_received,
 
2031
                                            &old_sigterm_action,
 
2032
                                            NULL));
1602
2033
    if(ret == -1){
1603
 
      perror("sigaction");
1604
 
    }
1605
 
    raise(signal_received);
 
2034
      perror_plus("sigaction");
 
2035
    }
 
2036
    do {
 
2037
      ret = raise(signal_received);
 
2038
    } while(ret != 0 and errno == EINTR);
 
2039
    if(ret != 0){
 
2040
      perror_plus("raise");
 
2041
      abort();
 
2042
    }
 
2043
    TEMP_FAILURE_RETRY(pause());
1606
2044
  }
1607
2045
  
1608
2046
  return exitcode;