/mandos/trunk

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

« back to all changes in this revision

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

  • Committer: Teddy Hogeborn
  • Date: 2011-07-25 18:52:11 UTC
  • mfrom: (489 trunk)
  • mto: (237.4.29 release)
  • mto: This revision was merged to the branch mainline in revision 490.
  • Revision ID: teddy@fukt.bsnet.se-20110725185211-wlitr9jvs70e1xh8
Merge from trunk.

Show diffs side-by-side

added added

removed removed

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