/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: 2009-09-19 17:41:18 UTC
  • Revision ID: teddy@fukt.bsnet.se-20090919174118-274yt9wptmtx0ykn
* plugins.d/password-prompt.c (main): Fix "-Wconversion" warning.

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