/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

todo

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-2011 Teddy Hogeborn
13
 
 * Copyright © 2008-2011 Björn Påhlsson
 
12
 * Copyright © 2008,2009 Teddy Hogeborn
 
13
 * Copyright © 2008,2009 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, srand(),
47
 
                                   strtof(), abort() */
 
46
#include <stdlib.h>             /* free(), EXIT_SUCCESS, EXIT_FAILURE,
 
47
                                   srand(), 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
 
                                   program_invocation_short_name */
67
 
#include <time.h>               /* nanosleep(), time(), sleep() */
 
65
#include <errno.h>              /* perror(), errno */
 
66
#include <time.h>               /* nanosleep(), time() */
68
67
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
69
68
                                   SIOCSIFFLAGS, if_indextoname(),
70
69
                                   if_nametoindex(), IF_NAMESIZE */
74
73
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
75
74
                                   getuid(), getgid(), seteuid(),
76
75
                                   setgid(), pause() */
77
 
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
 
76
#include <arpa/inet.h>          /* inet_pton(), htons */
78
77
#include <iso646.h>             /* not, or, and */
79
78
#include <argp.h>               /* struct argp_option, error_t, struct
80
79
                                   argp_state, struct argp,
83
82
#include <signal.h>             /* sigemptyset(), sigaddset(),
84
83
                                   sigaction(), SIGTERM, sig_atomic_t,
85
84
                                   raise() */
86
 
#include <sysexits.h>           /* EX_OSERR, EX_USAGE, EX_UNAVAILABLE,
87
 
                                   EX_NOHOST, EX_IOERR, EX_PROTOCOL */
88
85
 
89
86
#ifdef __linux__
90
87
#include <sys/klog.h>           /* klogctl() */
128
125
static const char mandos_protocol_version[] = "1";
129
126
const char *argp_program_version = "mandos-client " VERSION;
130
127
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;
144
128
 
145
129
/* Used for passing in values through the Avahi callback functions */
146
130
typedef struct {
151
135
  gnutls_dh_params_t dh_params;
152
136
  const char *priority;
153
137
  gpgme_ctx_t ctx;
154
 
  server *current_server;
155
138
} mandos_context;
156
139
 
157
140
/* global context so signal handler can reach it*/
158
141
mandos_context mc = { .simple_poll = NULL, .server = NULL,
159
142
                      .dh_bits = 1024, .priority = "SECURE256"
160
 
                      ":!CTYPE-X.509:+CTYPE-OPENPGP",
161
 
                      .current_server = NULL };
 
143
                      ":!CTYPE-X.509:+CTYPE-OPENPGP" };
162
144
 
163
145
sig_atomic_t quit_now = 0;
164
146
int signal_received = 0;
165
147
 
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
 
}
172
 
 
173
148
/*
174
149
 * Make additional room in "buffer" for at least BUFFER_SIZE more
175
150
 * bytes. "buffer_capacity" is how much is currently allocated,
187
162
  return buffer_capacity;
188
163
}
189
164
 
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
 
 
227
165
/* 
228
166
 * Initialize GPGME.
229
167
 */
243
181
    
244
182
    fd = (int)TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
245
183
    if(fd == -1){
246
 
      perror_plus("open");
 
184
      perror("open");
247
185
      return false;
248
186
    }
249
187
    
263
201
    
264
202
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
265
203
    if(ret == -1){
266
 
      perror_plus("close");
 
204
      perror("close");
267
205
    }
268
206
    gpgme_data_release(pgp_data);
269
207
    return true;
394
332
  
395
333
  /* Seek back to the beginning of the GPGME plaintext data buffer */
396
334
  if(gpgme_data_seek(dh_plain, (off_t)0, SEEK_SET) == -1){
397
 
    perror_plus("gpgme_data_seek");
 
335
    perror("gpgme_data_seek");
398
336
    plaintext_length = -1;
399
337
    goto decrypt_end;
400
338
  }
405
343
                                      (size_t)plaintext_length,
406
344
                                      plaintext_capacity);
407
345
    if(plaintext_capacity == 0){
408
 
        perror_plus("incbuffer");
 
346
        perror("incbuffer");
409
347
        plaintext_length = -1;
410
348
        goto decrypt_end;
411
349
    }
418
356
      break;
419
357
    }
420
358
    if(ret < 0){
421
 
      perror_plus("gpgme_data_read");
 
359
      perror("gpgme_data_read");
422
360
      plaintext_length = -1;
423
361
      goto decrypt_end;
424
362
    }
481
419
  }
482
420
  
483
421
  /* OpenPGP credentials */
484
 
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
 
422
  gnutls_certificate_allocate_credentials(&mc.cred);
485
423
  if(ret != GNUTLS_E_SUCCESS){
486
 
    fprintf(stderr, "GnuTLS memory error: %s\n",
 
424
    fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning
 
425
                                                    from
 
426
                                                    -Wunreachable-code
 
427
                                                 */
487
428
            safer_gnutls_strerror(ret));
488
429
    gnutls_global_deinit();
489
430
    return -1;
611
552
  gnutls_session_t session;
612
553
  int pf;                       /* Protocol family */
613
554
  
614
 
  errno = 0;
615
 
  
616
555
  if(quit_now){
617
 
    errno = EINTR;
618
556
    return -1;
619
557
  }
620
558
  
627
565
    break;
628
566
  default:
629
567
    fprintf(stderr, "Bad address family: %d\n", af);
630
 
    errno = EINVAL;
631
568
    return -1;
632
569
  }
633
570
  
643
580
  
644
581
  tcp_sd = socket(pf, SOCK_STREAM, 0);
645
582
  if(tcp_sd < 0){
646
 
    int e = errno;
647
 
    perror_plus("socket");
648
 
    errno = e;
 
583
    perror("socket");
649
584
    goto mandos_end;
650
585
  }
651
586
  
652
587
  if(quit_now){
653
 
    errno = EINTR;
654
588
    goto mandos_end;
655
589
  }
656
590
  
663
597
    ret = inet_pton(af, ip, &to.in.sin_addr);
664
598
  }
665
599
  if(ret < 0 ){
666
 
    int e = errno;
667
 
    perror_plus("inet_pton");
668
 
    errno = e;
 
600
    perror("inet_pton");
669
601
    goto mandos_end;
670
602
  }
671
603
  if(ret == 0){
672
 
    int e = errno;
673
604
    fprintf(stderr, "Bad address: %s\n", ip);
674
 
    errno = e;
675
605
    goto mandos_end;
676
606
  }
677
607
  if(af == AF_INET6){
685
615
      if(if_index == AVAHI_IF_UNSPEC){
686
616
        fprintf(stderr, "An IPv6 link-local address is incomplete"
687
617
                " without a network interface\n");
688
 
        errno = EINVAL;
689
618
        goto mandos_end;
690
619
      }
691
620
      /* Set the network interface number as scope */
698
627
  }
699
628
  
700
629
  if(quit_now){
701
 
    errno = EINTR;
702
630
    goto mandos_end;
703
631
  }
704
632
  
706
634
    if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
707
635
      char interface[IF_NAMESIZE];
708
636
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
709
 
        perror_plus("if_indextoname");
 
637
        perror("if_indextoname");
710
638
      } else {
711
639
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
712
640
                ip, interface, port);
726
654
                        sizeof(addrstr));
727
655
    }
728
656
    if(pcret == NULL){
729
 
      perror_plus("inet_ntop");
 
657
      perror("inet_ntop");
730
658
    } else {
731
659
      if(strcmp(addrstr, ip) != 0){
732
660
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
735
663
  }
736
664
  
737
665
  if(quit_now){
738
 
    errno = EINTR;
739
666
    goto mandos_end;
740
667
  }
741
668
  
745
672
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
746
673
  }
747
674
  if(ret < 0){
748
 
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
749
 
      int e = errno;
750
 
      perror_plus("connect");
751
 
      errno = e;
752
 
    }
 
675
    perror("connect");
753
676
    goto mandos_end;
754
677
  }
755
678
  
756
679
  if(quit_now){
757
 
    errno = EINTR;
758
680
    goto mandos_end;
759
681
  }
760
682
  
765
687
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
766
688
                                   out_size - written));
767
689
    if(ret == -1){
768
 
      int e = errno;
769
 
      perror_plus("write");
770
 
      errno = e;
 
690
      perror("write");
771
691
      goto mandos_end;
772
692
    }
773
693
    written += (size_t)ret;
783
703
    }
784
704
  
785
705
    if(quit_now){
786
 
      errno = EINTR;
787
706
      goto mandos_end;
788
707
    }
789
708
  }
793
712
  }
794
713
  
795
714
  if(quit_now){
796
 
    errno = EINTR;
797
715
    goto mandos_end;
798
716
  }
799
717
  
800
 
  /* Spurious warning from -Wint-to-pointer-cast */
801
718
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
802
719
  
803
720
  if(quit_now){
804
 
    errno = EINTR;
805
721
    goto mandos_end;
806
722
  }
807
723
  
808
724
  do {
809
725
    ret = gnutls_handshake(session);
810
726
    if(quit_now){
811
 
      errno = EINTR;
812
727
      goto mandos_end;
813
728
    }
814
729
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
818
733
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
819
734
      gnutls_perror(ret);
820
735
    }
821
 
    errno = EPROTO;
822
736
    goto mandos_end;
823
737
  }
824
738
  
832
746
  while(true){
833
747
    
834
748
    if(quit_now){
835
 
      errno = EINTR;
836
749
      goto mandos_end;
837
750
    }
838
751
    
839
752
    buffer_capacity = incbuffer(&buffer, buffer_length,
840
753
                                   buffer_capacity);
841
754
    if(buffer_capacity == 0){
842
 
      int e = errno;
843
 
      perror_plus("incbuffer");
844
 
      errno = e;
 
755
      perror("incbuffer");
845
756
      goto mandos_end;
846
757
    }
847
758
    
848
759
    if(quit_now){
849
 
      errno = EINTR;
850
760
      goto mandos_end;
851
761
    }
852
762
    
865
775
          ret = gnutls_handshake(session);
866
776
          
867
777
          if(quit_now){
868
 
            errno = EINTR;
869
778
            goto mandos_end;
870
779
          }
871
780
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
872
781
        if(ret < 0){
873
782
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
874
783
          gnutls_perror(ret);
875
 
          errno = EPROTO;
876
784
          goto mandos_end;
877
785
        }
878
786
        break;
880
788
        fprintf(stderr, "Unknown error while reading data from"
881
789
                " encrypted session with Mandos server\n");
882
790
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
883
 
        errno = EIO;
884
791
        goto mandos_end;
885
792
      }
886
793
    } else {
893
800
  }
894
801
  
895
802
  if(quit_now){
896
 
    errno = EINTR;
897
803
    goto mandos_end;
898
804
  }
899
805
  
900
806
  do {
901
807
    ret = gnutls_bye(session, GNUTLS_SHUT_RDWR);
902
808
    if(quit_now){
903
 
      errno = EINTR;
904
809
      goto mandos_end;
905
810
    }
906
811
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
915
820
      written = 0;
916
821
      while(written < (size_t) decrypted_buffer_size){
917
822
        if(quit_now){
918
 
          errno = EINTR;
919
823
          goto mandos_end;
920
824
        }
921
825
        
923
827
                          (size_t)decrypted_buffer_size - written,
924
828
                          stdout);
925
829
        if(ret == 0 and ferror(stdout)){
926
 
          int e = errno;
927
830
          if(debug){
928
831
            fprintf(stderr, "Error writing encrypted data: %s\n",
929
832
                    strerror(errno));
930
833
          }
931
 
          errno = e;
932
834
          goto mandos_end;
933
835
        }
934
836
        written += (size_t)ret;
940
842
  /* Shutdown procedure */
941
843
  
942
844
 mandos_end:
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
 
    }
 
845
  free(decrypted_buffer);
 
846
  free(buffer);
 
847
  if(tcp_sd >= 0){
 
848
    ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
 
849
  }
 
850
  if(ret == -1){
 
851
    perror("close");
 
852
  }
 
853
  gnutls_deinit(session);
 
854
  if(quit_now){
 
855
    retval = -1;
962
856
  }
963
857
  return retval;
964
858
}
1007
901
                                           avahi_proto_to_af(proto));
1008
902
      if(ret == 0){
1009
903
        avahi_simple_poll_quit(mc.simple_poll);
1010
 
      } else {
1011
 
        ret = add_server(ip, port, interface,
1012
 
                         avahi_proto_to_af(proto));
1013
904
      }
1014
905
    }
1015
906
  }
1069
960
  }
1070
961
}
1071
962
 
1072
 
/* Signal handler that stops main loop after SIGTERM */
 
963
/* stop main loop after sigterm has been called */
1073
964
static void handle_sigterm(int sig){
1074
965
  if(quit_now){
1075
966
    return;
1077
968
  quit_now = 1;
1078
969
  signal_received = sig;
1079
970
  int old_errno = errno;
1080
 
  /* set main loop to exit */
1081
971
  if(mc.simple_poll != NULL){
1082
972
    avahi_simple_poll_quit(mc.simple_poll);
1083
973
  }
1084
974
  errno = old_errno;
1085
975
}
1086
976
 
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
 
 
1274
977
int main(int argc, char *argv[]){
1275
978
  AvahiSServiceBrowser *sb = NULL;
1276
979
  int error;
1278
981
  intmax_t tmpmax;
1279
982
  char *tmp;
1280
983
  int exitcode = EXIT_SUCCESS;
1281
 
  const char *interface = "";
 
984
  const char *interface = "eth0";
1282
985
  struct ifreq network;
1283
986
  int sd = -1;
1284
987
  bool take_down_interface = false;
1285
988
  uid_t uid;
1286
989
  gid_t gid;
 
990
  char *connect_to = NULL;
1287
991
  char tempdir[] = "/tmp/mandosXXXXXX";
1288
992
  bool tempdir_created = false;
1289
993
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1293
997
  bool gnutls_initialized = false;
1294
998
  bool gpgme_initialized = false;
1295
999
  float delay = 2.5f;
1296
 
  double retry_interval = 10; /* 10s between trying a server and
1297
 
                                 retrying the same server again */
1298
1000
  
1299
1001
  struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
1300
1002
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
1306
1008
  errno = 0;
1307
1009
  ret = setgid(gid);
1308
1010
  if(ret == -1){
1309
 
    perror_plus("setgid");
 
1011
    perror("setgid");
1310
1012
  }
1311
1013
  
1312
1014
  /* Lower user privileges (temporarily) */
1313
1015
  errno = 0;
1314
1016
  ret = seteuid(uid);
1315
1017
  if(ret == -1){
1316
 
    perror_plus("seteuid");
 
1018
    perror("seteuid");
1317
1019
  }
1318
1020
  
1319
1021
  if(quit_now){
1354
1056
        .arg = "SECONDS",
1355
1057
        .doc = "Maximum delay to wait for interface startup",
1356
1058
        .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 },
1370
1059
      { .name = NULL }
1371
1060
    };
1372
1061
    
1373
1062
    error_t parse_opt(int key, char *arg,
1374
1063
                      struct argp_state *state){
1375
 
      errno = 0;
1376
1064
      switch(key){
1377
1065
      case 128:                 /* --debug */
1378
1066
        debug = true;
1394
1082
        tmpmax = strtoimax(arg, &tmp, 10);
1395
1083
        if(errno != 0 or tmp == arg or *tmp != '\0'
1396
1084
           or tmpmax != (typeof(mc.dh_bits))tmpmax){
1397
 
          argp_error(state, "Bad number of DH bits");
 
1085
          fprintf(stderr, "Bad number of DH bits\n");
 
1086
          exit(EXIT_FAILURE);
1398
1087
        }
1399
1088
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
1400
1089
        break;
1405
1094
        errno = 0;
1406
1095
        delay = strtof(arg, &tmp);
1407
1096
        if(errno != 0 or tmp == arg or *tmp != '\0'){
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");
 
1097
          fprintf(stderr, "Bad delay\n");
 
1098
          exit(EXIT_FAILURE);
1416
1099
        }
1417
1100
        break;
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);
 
1101
      case ARGP_KEY_ARG:
 
1102
        argp_usage(state);
 
1103
      case ARGP_KEY_END:
1431
1104
        break;
1432
1105
      default:
1433
1106
        return ARGP_ERR_UNKNOWN;
1434
1107
      }
1435
 
      return errno;
 
1108
      return 0;
1436
1109
    }
1437
1110
    
1438
1111
    struct argp argp = { .options = options, .parser = parse_opt,
1439
1112
                         .args_doc = "",
1440
1113
                         .doc = "Mandos client -- Get and decrypt"
1441
1114
                         " passwords from a Mandos server" };
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");
 
1115
    ret = argp_parse(&argp, argc, argv, 0, 0, NULL);
 
1116
    if(ret == ARGP_ERR_UNKNOWN){
 
1117
      fprintf(stderr, "Unknown error while parsing arguments\n");
 
1118
      exitcode = EXIT_FAILURE;
 
1119
      goto end;
1512
1120
    }
1513
1121
  }
1514
1122
  
1515
1123
  if(not debug){
1516
1124
    avahi_set_log_function(empty_log);
1517
1125
  }
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
 
  }
1543
1126
  
1544
1127
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
1545
1128
     from the signal handler */
1548
1131
  mc.simple_poll = avahi_simple_poll_new();
1549
1132
  if(mc.simple_poll == NULL){
1550
1133
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
1551
 
    exitcode = EX_UNAVAILABLE;
 
1134
    exitcode = EXIT_FAILURE;
1552
1135
    goto end;
1553
1136
  }
1554
1137
  
1555
1138
  sigemptyset(&sigterm_action.sa_mask);
1556
1139
  ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
1557
1140
  if(ret == -1){
1558
 
    perror_plus("sigaddset");
1559
 
    exitcode = EX_OSERR;
 
1141
    perror("sigaddset");
 
1142
    exitcode = EXIT_FAILURE;
1560
1143
    goto end;
1561
1144
  }
1562
1145
  ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
1563
1146
  if(ret == -1){
1564
 
    perror_plus("sigaddset");
1565
 
    exitcode = EX_OSERR;
 
1147
    perror("sigaddset");
 
1148
    exitcode = EXIT_FAILURE;
1566
1149
    goto end;
1567
1150
  }
1568
1151
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
1569
1152
  if(ret == -1){
1570
 
    perror_plus("sigaddset");
1571
 
    exitcode = EX_OSERR;
 
1153
    perror("sigaddset");
 
1154
    exitcode = EXIT_FAILURE;
1572
1155
    goto end;
1573
1156
  }
1574
1157
  /* Need to check if the handler is SIG_IGN before handling:
1577
1160
  */
1578
1161
  ret = sigaction(SIGINT, NULL, &old_sigterm_action);
1579
1162
  if(ret == -1){
1580
 
    perror_plus("sigaction");
1581
 
    return EX_OSERR;
 
1163
    perror("sigaction");
 
1164
    return EXIT_FAILURE;
1582
1165
  }
1583
1166
  if(old_sigterm_action.sa_handler != SIG_IGN){
1584
1167
    ret = sigaction(SIGINT, &sigterm_action, NULL);
1585
1168
    if(ret == -1){
1586
 
      perror_plus("sigaction");
1587
 
      exitcode = EX_OSERR;
 
1169
      perror("sigaction");
 
1170
      exitcode = EXIT_FAILURE;
1588
1171
      goto end;
1589
1172
    }
1590
1173
  }
1591
1174
  ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
1592
1175
  if(ret == -1){
1593
 
    perror_plus("sigaction");
1594
 
    return EX_OSERR;
 
1176
    perror("sigaction");
 
1177
    return EXIT_FAILURE;
1595
1178
  }
1596
1179
  if(old_sigterm_action.sa_handler != SIG_IGN){
1597
1180
    ret = sigaction(SIGHUP, &sigterm_action, NULL);
1598
1181
    if(ret == -1){
1599
 
      perror_plus("sigaction");
1600
 
      exitcode = EX_OSERR;
 
1182
      perror("sigaction");
 
1183
      exitcode = EXIT_FAILURE;
1601
1184
      goto end;
1602
1185
    }
1603
1186
  }
1604
1187
  ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
1605
1188
  if(ret == -1){
1606
 
    perror_plus("sigaction");
1607
 
    return EX_OSERR;
 
1189
    perror("sigaction");
 
1190
    return EXIT_FAILURE;
1608
1191
  }
1609
1192
  if(old_sigterm_action.sa_handler != SIG_IGN){
1610
1193
    ret = sigaction(SIGTERM, &sigterm_action, NULL);
1611
1194
    if(ret == -1){
1612
 
      perror_plus("sigaction");
1613
 
      exitcode = EX_OSERR;
 
1195
      perror("sigaction");
 
1196
      exitcode = EXIT_FAILURE;
1614
1197
      goto end;
1615
1198
    }
1616
1199
  }
1617
1200
  
1618
1201
  /* If the interface is down, bring it up */
1619
 
  if(strcmp(interface, "none") != 0){
 
1202
  if(interface[0] != '\0'){
1620
1203
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1621
1204
    if(if_index == 0){
1622
1205
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
1623
 
      exitcode = EX_UNAVAILABLE;
 
1206
      exitcode = EXIT_FAILURE;
1624
1207
      goto end;
1625
1208
    }
1626
1209
    
1632
1215
    errno = 0;
1633
1216
    ret = seteuid(0);
1634
1217
    if(ret == -1){
1635
 
      perror_plus("seteuid");
 
1218
      perror("seteuid");
1636
1219
    }
1637
1220
    
1638
1221
#ifdef __linux__
1639
1222
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1640
 
       messages about the network interface to mess up the prompt */
 
1223
       messages to mess up the prompt */
1641
1224
    ret = klogctl(8, NULL, 5);
1642
1225
    bool restore_loglevel = true;
1643
1226
    if(ret == -1){
1644
1227
      restore_loglevel = false;
1645
 
      perror_plus("klogctl");
 
1228
      perror("klogctl");
1646
1229
    }
1647
1230
#endif  /* __linux__ */
1648
1231
    
1649
1232
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1650
1233
    if(sd < 0){
1651
 
      perror_plus("socket");
1652
 
      exitcode = EX_OSERR;
 
1234
      perror("socket");
 
1235
      exitcode = EXIT_FAILURE;
1653
1236
#ifdef __linux__
1654
1237
      if(restore_loglevel){
1655
1238
        ret = klogctl(7, NULL, 0);
1656
1239
        if(ret == -1){
1657
 
          perror_plus("klogctl");
 
1240
          perror("klogctl");
1658
1241
        }
1659
1242
      }
1660
1243
#endif  /* __linux__ */
1662
1245
      errno = 0;
1663
1246
      ret = seteuid(uid);
1664
1247
      if(ret == -1){
1665
 
        perror_plus("seteuid");
 
1248
        perror("seteuid");
1666
1249
      }
1667
1250
      goto end;
1668
1251
    }
1669
1252
    strcpy(network.ifr_name, interface);
1670
1253
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
1671
1254
    if(ret == -1){
1672
 
      perror_plus("ioctl SIOCGIFFLAGS");
 
1255
      perror("ioctl SIOCGIFFLAGS");
1673
1256
#ifdef __linux__
1674
1257
      if(restore_loglevel){
1675
1258
        ret = klogctl(7, NULL, 0);
1676
1259
        if(ret == -1){
1677
 
          perror_plus("klogctl");
 
1260
          perror("klogctl");
1678
1261
        }
1679
1262
      }
1680
1263
#endif  /* __linux__ */
1681
 
      exitcode = EX_OSERR;
 
1264
      exitcode = EXIT_FAILURE;
1682
1265
      /* Lower privileges */
1683
1266
      errno = 0;
1684
1267
      ret = seteuid(uid);
1685
1268
      if(ret == -1){
1686
 
        perror_plus("seteuid");
 
1269
        perror("seteuid");
1687
1270
      }
1688
1271
      goto end;
1689
1272
    }
1693
1276
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1694
1277
      if(ret == -1){
1695
1278
        take_down_interface = false;
1696
 
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1697
 
        exitcode = EX_OSERR;
 
1279
        perror("ioctl SIOCSIFFLAGS");
 
1280
        exitcode = EXIT_FAILURE;
1698
1281
#ifdef __linux__
1699
1282
        if(restore_loglevel){
1700
1283
          ret = klogctl(7, NULL, 0);
1701
1284
          if(ret == -1){
1702
 
            perror_plus("klogctl");
 
1285
            perror("klogctl");
1703
1286
          }
1704
1287
        }
1705
1288
#endif  /* __linux__ */
1707
1290
        errno = 0;
1708
1291
        ret = seteuid(uid);
1709
1292
        if(ret == -1){
1710
 
          perror_plus("seteuid");
 
1293
          perror("seteuid");
1711
1294
        }
1712
1295
        goto end;
1713
1296
      }
1714
1297
    }
1715
 
    /* Sleep checking until interface is running.
1716
 
       Check every 0.25s, up to total time of delay */
 
1298
    /* sleep checking until interface is running */
1717
1299
    for(int i=0; i < delay * 4; i++){
1718
1300
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1719
1301
      if(ret == -1){
1720
 
        perror_plus("ioctl SIOCGIFFLAGS");
 
1302
        perror("ioctl SIOCGIFFLAGS");
1721
1303
      } else if(network.ifr_flags & IFF_RUNNING){
1722
1304
        break;
1723
1305
      }
1724
1306
      struct timespec sleeptime = { .tv_nsec = 250000000 };
1725
1307
      ret = nanosleep(&sleeptime, NULL);
1726
1308
      if(ret == -1 and errno != EINTR){
1727
 
        perror_plus("nanosleep");
 
1309
        perror("nanosleep");
1728
1310
      }
1729
1311
    }
1730
1312
    if(not take_down_interface){
1731
1313
      /* We won't need the socket anymore */
1732
1314
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1733
1315
      if(ret == -1){
1734
 
        perror_plus("close");
 
1316
        perror("close");
1735
1317
      }
1736
1318
    }
1737
1319
#ifdef __linux__
1739
1321
      /* Restores kernel loglevel to default */
1740
1322
      ret = klogctl(7, NULL, 0);
1741
1323
      if(ret == -1){
1742
 
        perror_plus("klogctl");
 
1324
        perror("klogctl");
1743
1325
      }
1744
1326
    }
1745
1327
#endif  /* __linux__ */
1749
1331
      /* Lower privileges */
1750
1332
      ret = seteuid(uid);
1751
1333
      if(ret == -1){
1752
 
        perror_plus("seteuid");
 
1334
        perror("seteuid");
1753
1335
      }
1754
1336
    } else {
1755
1337
      /* Lower privileges permanently */
1756
1338
      ret = setuid(uid);
1757
1339
      if(ret == -1){
1758
 
        perror_plus("setuid");
 
1340
        perror("setuid");
1759
1341
      }
1760
1342
    }
1761
1343
  }
1767
1349
  ret = init_gnutls_global(pubkey, seckey);
1768
1350
  if(ret == -1){
1769
1351
    fprintf(stderr, "init_gnutls_global failed\n");
1770
 
    exitcode = EX_UNAVAILABLE;
 
1352
    exitcode = EXIT_FAILURE;
1771
1353
    goto end;
1772
1354
  } else {
1773
1355
    gnutls_initialized = true;
1777
1359
    goto end;
1778
1360
  }
1779
1361
  
 
1362
  tempdir_created = true;
1780
1363
  if(mkdtemp(tempdir) == NULL){
1781
 
    perror_plus("mkdtemp");
 
1364
    tempdir_created = false;
 
1365
    perror("mkdtemp");
1782
1366
    goto end;
1783
1367
  }
1784
 
  tempdir_created = true;
1785
1368
  
1786
1369
  if(quit_now){
1787
1370
    goto end;
1789
1372
  
1790
1373
  if(not init_gpgme(pubkey, seckey, tempdir)){
1791
1374
    fprintf(stderr, "init_gpgme failed\n");
1792
 
    exitcode = EX_UNAVAILABLE;
 
1375
    exitcode = EXIT_FAILURE;
1793
1376
    goto end;
1794
1377
  } else {
1795
1378
    gpgme_initialized = true;
1805
1388
    char *address = strrchr(connect_to, ':');
1806
1389
    if(address == NULL){
1807
1390
      fprintf(stderr, "No colon in address\n");
1808
 
      exitcode = EX_USAGE;
 
1391
      exitcode = EXIT_FAILURE;
1809
1392
      goto end;
1810
1393
    }
1811
1394
    
1819
1402
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
1820
1403
       or tmpmax != (uint16_t)tmpmax){
1821
1404
      fprintf(stderr, "Bad port number\n");
1822
 
      exitcode = EX_USAGE;
 
1405
      exitcode = EXIT_FAILURE;
1823
1406
      goto end;
1824
1407
    }
1825
1408
  
1841
1424
    if(quit_now){
1842
1425
      goto end;
1843
1426
    }
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){
 
1427
    
 
1428
    ret = start_mandos_communication(address, port, if_index, af);
 
1429
    if(ret < 0){
 
1430
      exitcode = EXIT_FAILURE;
 
1431
    } else {
1854
1432
      exitcode = EXIT_SUCCESS;
1855
1433
    }
1856
 
 
1857
1434
    goto end;
1858
1435
  }
1859
1436
  
1883
1460
  if(mc.server == NULL){
1884
1461
    fprintf(stderr, "Failed to create Avahi server: %s\n",
1885
1462
            avahi_strerror(error));
1886
 
    exitcode = EX_UNAVAILABLE;
 
1463
    exitcode = EXIT_FAILURE;
1887
1464
    goto end;
1888
1465
  }
1889
1466
  
1898
1475
  if(sb == NULL){
1899
1476
    fprintf(stderr, "Failed to create service browser: %s\n",
1900
1477
            avahi_strerror(avahi_server_errno(mc.server)));
1901
 
    exitcode = EX_UNAVAILABLE;
 
1478
    exitcode = EXIT_FAILURE;
1902
1479
    goto end;
1903
1480
  }
1904
1481
  
1911
1488
  if(debug){
1912
1489
    fprintf(stderr, "Starting Avahi loop search\n");
1913
1490
  }
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
 
  }
 
1491
  
 
1492
  avahi_simple_poll_loop(mc.simple_poll);
1921
1493
  
1922
1494
 end:
1923
1495
  
1944
1516
  if(gpgme_initialized){
1945
1517
    gpgme_release(mc.ctx);
1946
1518
  }
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
 
  }
1958
1519
  
1959
1520
  /* Take down the network interface */
1960
1521
  if(take_down_interface){
1962
1523
    errno = 0;
1963
1524
    ret = seteuid(0);
1964
1525
    if(ret == -1){
1965
 
      perror_plus("seteuid");
 
1526
      perror("seteuid");
1966
1527
    }
1967
1528
    if(geteuid() == 0){
1968
1529
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1969
1530
      if(ret == -1){
1970
 
        perror_plus("ioctl SIOCGIFFLAGS");
 
1531
        perror("ioctl SIOCGIFFLAGS");
1971
1532
      } else if(network.ifr_flags & IFF_UP) {
1972
 
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
 
1533
        network.ifr_flags &= ~IFF_UP; /* clear flag */
1973
1534
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
1974
1535
        if(ret == -1){
1975
 
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
 
1536
          perror("ioctl SIOCSIFFLAGS");
1976
1537
        }
1977
1538
      }
1978
1539
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1979
1540
      if(ret == -1){
1980
 
        perror_plus("close");
 
1541
        perror("close");
1981
1542
      }
1982
1543
      /* Lower privileges permanently */
1983
1544
      errno = 0;
1984
1545
      ret = setuid(uid);
1985
1546
      if(ret == -1){
1986
 
        perror_plus("setuid");
 
1547
        perror("setuid");
1987
1548
      }
1988
1549
    }
1989
1550
  }
1990
1551
  
1991
 
  /* Removes the GPGME temp directory and all files inside */
 
1552
  /* Removes the temp directory used by GPGME */
1992
1553
  if(tempdir_created){
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];
 
1554
    DIR *d;
 
1555
    struct dirent *direntry;
 
1556
    d = opendir(tempdir);
 
1557
    if(d == NULL){
 
1558
      if(errno != ENOENT){
 
1559
        perror("opendir");
 
1560
      }
 
1561
    } else {
 
1562
      while(true){
 
1563
        direntry = readdir(d);
 
1564
        if(direntry == NULL){
 
1565
          break;
 
1566
        }
 
1567
        /* Skip "." and ".." */
 
1568
        if(direntry->d_name[0] == '.'
 
1569
           and (direntry->d_name[1] == '\0'
 
1570
                or (direntry->d_name[1] == '.'
 
1571
                    and direntry->d_name[2] == '\0'))){
 
1572
          continue;
 
1573
        }
1999
1574
        char *fullname = NULL;
2000
1575
        ret = asprintf(&fullname, "%s/%s", tempdir,
2001
1576
                       direntry->d_name);
2002
1577
        if(ret < 0){
2003
 
          perror_plus("asprintf");
 
1578
          perror("asprintf");
2004
1579
          continue;
2005
1580
        }
2006
1581
        ret = remove(fullname);
2010
1585
        }
2011
1586
        free(fullname);
2012
1587
      }
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");
 
1588
      closedir(d);
2020
1589
    }
2021
1590
    ret = rmdir(tempdir);
2022
1591
    if(ret == -1 and errno != ENOENT){
2023
 
      perror_plus("rmdir");
 
1592
      perror("rmdir");
2024
1593
    }
2025
1594
  }
2026
1595
  
2031
1600
                                            &old_sigterm_action,
2032
1601
                                            NULL));
2033
1602
    if(ret == -1){
2034
 
      perror_plus("sigaction");
 
1603
      perror("sigaction");
2035
1604
    }
2036
1605
    do {
2037
1606
      ret = raise(signal_received);
2038
1607
    } while(ret != 0 and errno == EINTR);
2039
1608
    if(ret != 0){
2040
 
      perror_plus("raise");
 
1609
      perror("raise");
2041
1610
      abort();
2042
1611
    }
2043
1612
    TEMP_FAILURE_RETRY(pause());