/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: Björn Påhlsson
  • Date: 2011-10-02 19:18:24 UTC
  • mto: This revision was merged to the branch mainline in revision 505.
  • Revision ID: belorn@fukt.bsnet.se-20111002191824-eweh4pvneeg3qzia
transitional stuff actually working
documented change to D-Bus API

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