/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:50:00 UTC
  • mfrom: (24.1.176 mandos)
  • Revision ID: teddy@fukt.bsnet.se-20110725185000-paes3keuo0dj4m0z
Merge from Björn.

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