/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-10-24 19:17:52 UTC
  • Revision ID: teddy@fukt.bsnet.se-20091024191752-7g6xlf6wpp2pdexb
Convert some programs to use the exit codes from <sysexits.h>.  Change
all programs using the "argp" parsing functions to use them correctly;
checking return value, using argp_error() to report parse errors etc.

* plugin-runner.c: Use <sysexits.h> exit codes.  Always use fallback,
                   even on option errors, except for "--help", etc.
  (getplugin): Make sure "errno" is set correctly on return.
  (main): Declare our own "--help", "--usage", and "--version"
          options which do not cause the fallback to be invoked.
          In all other options, use fallback on any error.
  (parse_opt, parse_opt_config_file): Reset errno at start and return
                                      errno.  No need to check "arg"
                                      for NULL.  New "--help",
                                      "--usage", and "--version"
                                      options.
  (parse_opt): Accept empty string as global option.  Do not print
               errors which will be detected and reported later.  Do
               "argp_error()" on parse error or empty plugin names.
* plugins.d/mandos-client.c: Use <sysexits.h> exit codes.  Do not
                             return successful exit code on "--help",
                             etc. since this would give the wrong
                             message to "plugin-runner".
  (main): Declare our own "--help", "--usage", and "--version"
          options which do not return a successful exit code.
  (parse_opt): Reset errno at start and return errno.  Do
               "argp_error()" on parse errors.  New "--help",
               "--usage", and "--version" options.
* plugins.d/password-prompt.c: Use exit codes from <sysexits.h>.  Do
                               not return successful exit code on
                               "--help", etc. since this would give
                               the wrong message to "plugin-runner".
  (main): Declare our own "--help", "--usage", and "--version" options
          which do not return a successful exit code.  Do
          close(STDOUT_FILENO) after writing to check its return code.
  (parse_opt): Reset errno at start and return errno.

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
26
26
 * along with this program.  If not, see
27
27
 * <http://www.gnu.org/licenses/>.
28
28
 * 
29
 
 * Contact the authors at <mandos@recompile.se>.
 
29
 * Contact the authors at <mandos@fukt.bsnet.se>.
30
30
 */
31
31
 
32
32
/* Needed by GPGME, specifically gpgme_data_seek() */
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 */
 
85
#include <sysexits.h>           /* EX_OSERR, EX_USAGE */
88
86
 
89
87
#ifdef __linux__
90
88
#include <sys/klog.h>           /* klogctl() */
127
125
bool debug = false;
128
126
static const char mandos_protocol_version[] = "1";
129
127
const char *argp_program_version = "mandos-client " VERSION;
130
 
const char *argp_program_bug_address = "<mandos@recompile.se>";
131
 
static const char sys_class_net[] = "/sys/class/net";
132
 
char *connect_to = NULL;
133
 
 
134
 
/* Doubly linked list that need to be circularly linked when used */
135
 
typedef struct server{
136
 
  const char *ip;
137
 
  uint16_t port;
138
 
  AvahiIfIndex if_index;
139
 
  int af;
140
 
  struct timespec last_seen;
141
 
  struct server *next;
142
 
  struct server *prev;
143
 
} server;
 
128
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
144
129
 
145
130
/* Used for passing in values through the Avahi callback functions */
146
131
typedef struct {
151
136
  gnutls_dh_params_t dh_params;
152
137
  const char *priority;
153
138
  gpgme_ctx_t ctx;
154
 
  server *current_server;
155
139
} mandos_context;
156
140
 
157
141
/* global context so signal handler can reach it*/
158
142
mandos_context mc = { .simple_poll = NULL, .server = NULL,
159
143
                      .dh_bits = 1024, .priority = "SECURE256"
160
 
                      ":!CTYPE-X.509:+CTYPE-OPENPGP",
161
 
                      .current_server = NULL };
 
144
                      ":!CTYPE-X.509:+CTYPE-OPENPGP" };
162
145
 
163
146
sig_atomic_t quit_now = 0;
164
147
int signal_received = 0;
165
148
 
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
149
/*
174
150
 * Make additional room in "buffer" for at least BUFFER_SIZE more
175
151
 * bytes. "buffer_capacity" is how much is currently allocated,
187
163
  return buffer_capacity;
188
164
}
189
165
 
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
166
/* 
229
167
 * Initialize GPGME.
230
168
 */
244
182
    
245
183
    fd = (int)TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
246
184
    if(fd == -1){
247
 
      perror_plus("open");
 
185
      perror("open");
248
186
      return false;
249
187
    }
250
188
    
264
202
    
265
203
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
266
204
    if(ret == -1){
267
 
      perror_plus("close");
 
205
      perror("close");
268
206
    }
269
207
    gpgme_data_release(pgp_data);
270
208
    return true;
283
221
    return false;
284
222
  }
285
223
  
286
 
  /* Set GPGME home directory for the OpenPGP engine only */
 
224
    /* Set GPGME home directory for the OpenPGP engine only */
287
225
  rc = gpgme_get_engine_info(&engine_info);
288
226
  if(rc != GPG_ERR_NO_ERROR){
289
227
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
395
333
  
396
334
  /* Seek back to the beginning of the GPGME plaintext data buffer */
397
335
  if(gpgme_data_seek(dh_plain, (off_t)0, SEEK_SET) == -1){
398
 
    perror_plus("gpgme_data_seek");
 
336
    perror("gpgme_data_seek");
399
337
    plaintext_length = -1;
400
338
    goto decrypt_end;
401
339
  }
406
344
                                      (size_t)plaintext_length,
407
345
                                      plaintext_capacity);
408
346
    if(plaintext_capacity == 0){
409
 
        perror_plus("incbuffer");
 
347
        perror("incbuffer");
410
348
        plaintext_length = -1;
411
349
        goto decrypt_end;
412
350
    }
419
357
      break;
420
358
    }
421
359
    if(ret < 0){
422
 
      perror_plus("gpgme_data_read");
 
360
      perror("gpgme_data_read");
423
361
      plaintext_length = -1;
424
362
      goto decrypt_end;
425
363
    }
482
420
  }
483
421
  
484
422
  /* OpenPGP credentials */
485
 
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
 
423
  gnutls_certificate_allocate_credentials(&mc.cred);
486
424
  if(ret != GNUTLS_E_SUCCESS){
487
 
    fprintf(stderr, "GnuTLS memory error: %s\n",
 
425
    fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning
 
426
                                                    from
 
427
                                                    -Wunreachable-code
 
428
                                                 */
488
429
            safer_gnutls_strerror(ret));
489
430
    gnutls_global_deinit();
490
431
    return -1;
612
553
  gnutls_session_t session;
613
554
  int pf;                       /* Protocol family */
614
555
  
615
 
  errno = 0;
616
 
  
617
556
  if(quit_now){
618
 
    errno = EINTR;
619
557
    return -1;
620
558
  }
621
559
  
628
566
    break;
629
567
  default:
630
568
    fprintf(stderr, "Bad address family: %d\n", af);
631
 
    errno = EINVAL;
632
569
    return -1;
633
570
  }
634
571
  
644
581
  
645
582
  tcp_sd = socket(pf, SOCK_STREAM, 0);
646
583
  if(tcp_sd < 0){
647
 
    int e = errno;
648
 
    perror_plus("socket");
649
 
    errno = e;
 
584
    perror("socket");
650
585
    goto mandos_end;
651
586
  }
652
587
  
653
588
  if(quit_now){
654
 
    errno = EINTR;
655
589
    goto mandos_end;
656
590
  }
657
591
  
664
598
    ret = inet_pton(af, ip, &to.in.sin_addr);
665
599
  }
666
600
  if(ret < 0 ){
667
 
    int e = errno;
668
 
    perror_plus("inet_pton");
669
 
    errno = e;
 
601
    perror("inet_pton");
670
602
    goto mandos_end;
671
603
  }
672
604
  if(ret == 0){
673
 
    int e = errno;
674
605
    fprintf(stderr, "Bad address: %s\n", ip);
675
 
    errno = e;
676
606
    goto mandos_end;
677
607
  }
678
608
  if(af == AF_INET6){
686
616
      if(if_index == AVAHI_IF_UNSPEC){
687
617
        fprintf(stderr, "An IPv6 link-local address is incomplete"
688
618
                " without a network interface\n");
689
 
        errno = EINVAL;
690
619
        goto mandos_end;
691
620
      }
692
621
      /* Set the network interface number as scope */
699
628
  }
700
629
  
701
630
  if(quit_now){
702
 
    errno = EINTR;
703
631
    goto mandos_end;
704
632
  }
705
633
  
707
635
    if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
708
636
      char interface[IF_NAMESIZE];
709
637
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
710
 
        perror_plus("if_indextoname");
 
638
        perror("if_indextoname");
711
639
      } else {
712
640
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
713
641
                ip, interface, port);
727
655
                        sizeof(addrstr));
728
656
    }
729
657
    if(pcret == NULL){
730
 
      perror_plus("inet_ntop");
 
658
      perror("inet_ntop");
731
659
    } else {
732
660
      if(strcmp(addrstr, ip) != 0){
733
661
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
736
664
  }
737
665
  
738
666
  if(quit_now){
739
 
    errno = EINTR;
740
667
    goto mandos_end;
741
668
  }
742
669
  
746
673
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
747
674
  }
748
675
  if(ret < 0){
749
 
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
750
 
      int e = errno;
751
 
      perror_plus("connect");
752
 
      errno = e;
753
 
    }
 
676
    perror("connect");
754
677
    goto mandos_end;
755
678
  }
756
679
  
757
680
  if(quit_now){
758
 
    errno = EINTR;
759
681
    goto mandos_end;
760
682
  }
761
683
  
766
688
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
767
689
                                   out_size - written));
768
690
    if(ret == -1){
769
 
      int e = errno;
770
 
      perror_plus("write");
771
 
      errno = e;
 
691
      perror("write");
772
692
      goto mandos_end;
773
693
    }
774
694
    written += (size_t)ret;
784
704
    }
785
705
  
786
706
    if(quit_now){
787
 
      errno = EINTR;
788
707
      goto mandos_end;
789
708
    }
790
709
  }
794
713
  }
795
714
  
796
715
  if(quit_now){
797
 
    errno = EINTR;
798
716
    goto mandos_end;
799
717
  }
800
718
  
801
 
  /* Spurious warning from -Wint-to-pointer-cast */
802
719
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
803
720
  
804
721
  if(quit_now){
805
 
    errno = EINTR;
806
722
    goto mandos_end;
807
723
  }
808
724
  
809
725
  do {
810
726
    ret = gnutls_handshake(session);
811
727
    if(quit_now){
812
 
      errno = EINTR;
813
728
      goto mandos_end;
814
729
    }
815
730
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
819
734
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
820
735
      gnutls_perror(ret);
821
736
    }
822
 
    errno = EPROTO;
823
737
    goto mandos_end;
824
738
  }
825
739
  
833
747
  while(true){
834
748
    
835
749
    if(quit_now){
836
 
      errno = EINTR;
837
750
      goto mandos_end;
838
751
    }
839
752
    
840
753
    buffer_capacity = incbuffer(&buffer, buffer_length,
841
754
                                   buffer_capacity);
842
755
    if(buffer_capacity == 0){
843
 
      int e = errno;
844
 
      perror_plus("incbuffer");
845
 
      errno = e;
 
756
      perror("incbuffer");
846
757
      goto mandos_end;
847
758
    }
848
759
    
849
760
    if(quit_now){
850
 
      errno = EINTR;
851
761
      goto mandos_end;
852
762
    }
853
763
    
866
776
          ret = gnutls_handshake(session);
867
777
          
868
778
          if(quit_now){
869
 
            errno = EINTR;
870
779
            goto mandos_end;
871
780
          }
872
781
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
873
782
        if(ret < 0){
874
783
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
875
784
          gnutls_perror(ret);
876
 
          errno = EPROTO;
877
785
          goto mandos_end;
878
786
        }
879
787
        break;
881
789
        fprintf(stderr, "Unknown error while reading data from"
882
790
                " encrypted session with Mandos server\n");
883
791
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
884
 
        errno = EIO;
885
792
        goto mandos_end;
886
793
      }
887
794
    } else {
894
801
  }
895
802
  
896
803
  if(quit_now){
897
 
    errno = EINTR;
898
804
    goto mandos_end;
899
805
  }
900
806
  
901
807
  do {
902
808
    ret = gnutls_bye(session, GNUTLS_SHUT_RDWR);
903
809
    if(quit_now){
904
 
      errno = EINTR;
905
810
      goto mandos_end;
906
811
    }
907
812
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
916
821
      written = 0;
917
822
      while(written < (size_t) decrypted_buffer_size){
918
823
        if(quit_now){
919
 
          errno = EINTR;
920
824
          goto mandos_end;
921
825
        }
922
826
        
924
828
                          (size_t)decrypted_buffer_size - written,
925
829
                          stdout);
926
830
        if(ret == 0 and ferror(stdout)){
927
 
          int e = errno;
928
831
          if(debug){
929
832
            fprintf(stderr, "Error writing encrypted data: %s\n",
930
833
                    strerror(errno));
931
834
          }
932
 
          errno = e;
933
835
          goto mandos_end;
934
836
        }
935
837
        written += (size_t)ret;
941
843
  /* Shutdown procedure */
942
844
  
943
845
 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
 
    }
 
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;
963
857
  }
964
858
  return retval;
965
859
}
1008
902
                                           avahi_proto_to_af(proto));
1009
903
      if(ret == 0){
1010
904
        avahi_simple_poll_quit(mc.simple_poll);
1011
 
      } else {
1012
 
        ret = add_server(ip, port, interface,
1013
 
                         avahi_proto_to_af(proto));
1014
905
      }
1015
906
    }
1016
907
  }
1070
961
  }
1071
962
}
1072
963
 
1073
 
/* Signal handler that stops main loop after SIGTERM */
 
964
/* stop main loop after sigterm has been called */
1074
965
static void handle_sigterm(int sig){
1075
966
  if(quit_now){
1076
967
    return;
1078
969
  quit_now = 1;
1079
970
  signal_received = sig;
1080
971
  int old_errno = errno;
1081
 
  /* set main loop to exit */
1082
972
  if(mc.simple_poll != NULL){
1083
973
    avahi_simple_poll_quit(mc.simple_poll);
1084
974
  }
1085
975
  errno = old_errno;
1086
976
}
1087
977
 
1088
 
bool get_flags(const char *ifname, struct ifreq *ifr){
1089
 
  int ret;
1090
 
  
1091
 
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1092
 
  if(s < 0){
1093
 
    perror_plus("socket");
1094
 
    return false;
1095
 
  }
1096
 
  strcpy(ifr->ifr_name, ifname);
1097
 
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1098
 
  if(ret == -1){
1099
 
    if(debug){
1100
 
      perror_plus("ioctl SIOCGIFFLAGS");
1101
 
    }
1102
 
    return false;
1103
 
  }
1104
 
  return true;
1105
 
}
1106
 
 
1107
 
bool good_flags(const char *ifname, const struct ifreq *ifr){
1108
 
  
1109
 
  /* Reject the loopback device */
1110
 
  if(ifr->ifr_flags & IFF_LOOPBACK){
1111
 
    if(debug){
1112
 
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
1113
 
              ifname);
1114
 
    }
1115
 
    return false;
1116
 
  }
1117
 
  /* Accept point-to-point devices only if connect_to is specified */
1118
 
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
1119
 
    if(debug){
1120
 
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
1121
 
              ifname);
1122
 
    }
1123
 
    return true;
1124
 
  }
1125
 
  /* Otherwise, reject non-broadcast-capable devices */
1126
 
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
1127
 
    if(debug){
1128
 
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
1129
 
              ifname);
1130
 
    }
1131
 
    return false;
1132
 
  }
1133
 
  /* Reject non-ARP interfaces (including dummy interfaces) */
1134
 
  if(ifr->ifr_flags & IFF_NOARP){
1135
 
    if(debug){
1136
 
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n", ifname);
1137
 
    }
1138
 
    return false;
1139
 
  }
1140
 
  
1141
 
  /* Accept this device */
1142
 
  if(debug){
1143
 
    fprintf(stderr, "Interface \"%s\" is good\n", ifname);
1144
 
  }
1145
 
  return true;
1146
 
}
1147
 
 
1148
 
/* 
1149
 
 * This function determines if a directory entry in /sys/class/net
1150
 
 * corresponds to an acceptable network device.
1151
 
 * (This function is passed to scandir(3) as a filter function.)
1152
 
 */
1153
 
int good_interface(const struct dirent *if_entry){
1154
 
  int ret;
1155
 
  if(if_entry->d_name[0] == '.'){
1156
 
    return 0;
1157
 
  }
1158
 
  struct ifreq ifr;
1159
 
 
1160
 
  if(not get_flags(if_entry->d_name, &ifr)){
1161
 
    return 0;
1162
 
  }
1163
 
  
1164
 
  if(not good_flags(if_entry->d_name, &ifr)){
1165
 
    return 0;
1166
 
  }
1167
 
  return 1;
1168
 
}
1169
 
 
1170
 
int notdotentries(const struct dirent *direntry){
1171
 
  /* Skip "." and ".." */
1172
 
  if(direntry->d_name[0] == '.'
1173
 
     and (direntry->d_name[1] == '\0'
1174
 
          or (direntry->d_name[1] == '.'
1175
 
              and direntry->d_name[2] == '\0'))){
1176
 
    return 0;
1177
 
  }
1178
 
  return 1;
1179
 
}
1180
 
 
1181
 
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
1182
 
  int ret;
1183
 
  struct timespec now;
1184
 
  struct timespec waited_time;
1185
 
  intmax_t block_time;
1186
 
  
1187
 
  while(true){
1188
 
    if(mc.current_server == NULL){
1189
 
      if (debug){
1190
 
        fprintf(stderr,
1191
 
                "Wait until first server is found. No timeout!\n");
1192
 
      }
1193
 
      ret = avahi_simple_poll_iterate(s, -1);
1194
 
    } else {
1195
 
      if (debug){
1196
 
        fprintf(stderr, "Check current_server if we should run it,"
1197
 
                " or wait\n");
1198
 
      }
1199
 
      /* the current time */
1200
 
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
1201
 
      if(ret == -1){
1202
 
        perror_plus("clock_gettime");
1203
 
        return -1;
1204
 
      }
1205
 
      /* Calculating in ms how long time between now and server
1206
 
         who we visted longest time ago. Now - last seen.  */
1207
 
      waited_time.tv_sec = (now.tv_sec
1208
 
                            - mc.current_server->last_seen.tv_sec);
1209
 
      waited_time.tv_nsec = (now.tv_nsec
1210
 
                             - mc.current_server->last_seen.tv_nsec);
1211
 
      /* total time is 10s/10,000ms.
1212
 
         Converting to s from ms by dividing by 1,000,
1213
 
         and ns to ms by dividing by 1,000,000. */
1214
 
      block_time = ((retry_interval
1215
 
                     - ((intmax_t)waited_time.tv_sec * 1000))
1216
 
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1217
 
      
1218
 
      if (debug){
1219
 
        fprintf(stderr, "Blocking for %" PRIdMAX " ms\n", block_time);
1220
 
      }
1221
 
      
1222
 
      if(block_time <= 0){
1223
 
        ret = start_mandos_communication(mc.current_server->ip,
1224
 
                                         mc.current_server->port,
1225
 
                                         mc.current_server->if_index,
1226
 
                                         mc.current_server->af);
1227
 
        if(ret == 0){
1228
 
          avahi_simple_poll_quit(mc.simple_poll);
1229
 
          return 0;
1230
 
        }
1231
 
        ret = clock_gettime(CLOCK_MONOTONIC,
1232
 
                            &mc.current_server->last_seen);
1233
 
        if(ret == -1){
1234
 
          perror_plus("clock_gettime");
1235
 
          return -1;
1236
 
        }
1237
 
        mc.current_server = mc.current_server->next;
1238
 
        block_time = 0;         /* Call avahi to find new Mandos
1239
 
                                   servers, but don't block */
1240
 
      }
1241
 
      
1242
 
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1243
 
    }
1244
 
    if(ret != 0){
1245
 
      if (ret > 0 or errno != EINTR) {
1246
 
        return (ret != 1) ? ret : 0;
1247
 
      }
1248
 
    }
1249
 
  }
1250
 
}
1251
 
 
1252
978
int main(int argc, char *argv[]){
1253
979
  AvahiSServiceBrowser *sb = NULL;
1254
980
  int error;
1256
982
  intmax_t tmpmax;
1257
983
  char *tmp;
1258
984
  int exitcode = EXIT_SUCCESS;
1259
 
  const char *interface = "";
 
985
  const char *interface = "eth0";
1260
986
  struct ifreq network;
1261
987
  int sd = -1;
1262
988
  bool take_down_interface = false;
1263
989
  uid_t uid;
1264
990
  gid_t gid;
 
991
  char *connect_to = NULL;
1265
992
  char tempdir[] = "/tmp/mandosXXXXXX";
1266
993
  bool tempdir_created = false;
1267
994
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1271
998
  bool gnutls_initialized = false;
1272
999
  bool gpgme_initialized = false;
1273
1000
  float delay = 2.5f;
1274
 
  double retry_interval = 10; /* 10s between trying a server and
1275
 
                                 retrying the same server again */
1276
1001
  
1277
1002
  struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
1278
1003
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
1284
1009
  errno = 0;
1285
1010
  ret = setgid(gid);
1286
1011
  if(ret == -1){
1287
 
    perror_plus("setgid");
 
1012
    perror("setgid");
1288
1013
  }
1289
1014
  
1290
1015
  /* Lower user privileges (temporarily) */
1291
1016
  errno = 0;
1292
1017
  ret = seteuid(uid);
1293
1018
  if(ret == -1){
1294
 
    perror_plus("seteuid");
 
1019
    perror("seteuid");
1295
1020
  }
1296
1021
  
1297
1022
  if(quit_now){
1332
1057
        .arg = "SECONDS",
1333
1058
        .doc = "Maximum delay to wait for interface startup",
1334
1059
        .group = 2 },
1335
 
      { .name = "retry", .key = 132,
1336
 
        .arg = "SECONDS",
1337
 
        .doc = "Retry interval used when denied by the mandos server",
1338
 
        .group = 2 },
1339
1060
      /*
1340
1061
       * These reproduce what we would get without ARGP_NO_HELP
1341
1062
       */
1385
1106
        if(errno != 0 or tmp == arg or *tmp != '\0'){
1386
1107
          argp_error(state, "Bad delay");
1387
1108
        }
1388
 
      case 132:                 /* --retry */
1389
 
        errno = 0;
1390
 
        retry_interval = strtod(arg, &tmp);
1391
 
        if(errno != 0 or tmp == arg or *tmp != '\0'
1392
 
           or (retry_interval * 1000) > INT_MAX
1393
 
           or retry_interval < 0){
1394
 
          argp_error(state, "Bad retry interval");
1395
 
        }
1396
1109
        break;
1397
1110
        /*
1398
1111
         * These reproduce what we would get without ARGP_NO_HELP
1426
1139
    case ENOMEM:
1427
1140
    default:
1428
1141
      errno = ret;
1429
 
      perror_plus("argp_parse");
 
1142
      perror("argp_parse");
1430
1143
      exitcode = EX_OSERR;
1431
1144
      goto end;
1432
1145
    case EINVAL:
1434
1147
      goto end;
1435
1148
    }
1436
1149
  }
1437
 
    
1438
 
  {
1439
 
    /* Work around Debian bug #633582:
1440
 
       <http://bugs.debian.org/633582> */
1441
 
    struct stat st;
1442
 
    
1443
 
    /* Re-raise priviliges */
1444
 
    errno = 0;
1445
 
    ret = seteuid(0);
1446
 
    if(ret == -1){
1447
 
      perror_plus("seteuid");
1448
 
    }
1449
 
    
1450
 
    if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
1451
 
      int seckey_fd = open(seckey, O_RDONLY);
1452
 
      if(seckey_fd == -1){
1453
 
        perror_plus("open");
1454
 
      } else {
1455
 
        ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
1456
 
        if(ret == -1){
1457
 
          perror_plus("fstat");
1458
 
        } else {
1459
 
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1460
 
            ret = fchown(seckey_fd, uid, gid);
1461
 
            if(ret == -1){
1462
 
              perror_plus("fchown");
1463
 
            }
1464
 
          }
1465
 
        }
1466
 
        TEMP_FAILURE_RETRY(close(seckey_fd));
1467
 
      }
1468
 
    }
1469
 
    
1470
 
    if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
1471
 
      int pubkey_fd = open(pubkey, O_RDONLY);
1472
 
      if(pubkey_fd == -1){
1473
 
        perror_plus("open");
1474
 
      } else {
1475
 
        ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_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(pubkey_fd, uid, gid);
1481
 
            if(ret == -1){
1482
 
              perror_plus("fchown");
1483
 
            }
1484
 
          }
1485
 
        }
1486
 
        TEMP_FAILURE_RETRY(close(pubkey_fd));
1487
 
      }
1488
 
    }
1489
 
    
1490
 
    /* Lower privileges */
1491
 
    errno = 0;
1492
 
    ret = seteuid(uid);
1493
 
    if(ret == -1){
1494
 
      perror_plus("seteuid");
1495
 
    }
1496
 
  }
1497
1150
  
1498
1151
  if(not debug){
1499
1152
    avahi_set_log_function(empty_log);
1500
1153
  }
1501
 
 
1502
 
  if(interface[0] == '\0'){
1503
 
    struct dirent **direntries;
1504
 
    ret = scandir(sys_class_net, &direntries, good_interface,
1505
 
                  alphasort);
1506
 
    if(ret >= 1){
1507
 
      /* Pick the first good interface */
1508
 
      interface = strdup(direntries[0]->d_name);
1509
 
      if(debug){
1510
 
        fprintf(stderr, "Using interface \"%s\"\n", interface);
1511
 
      }
1512
 
      if(interface == NULL){
1513
 
        perror_plus("malloc");
1514
 
        free(direntries);
1515
 
        exitcode = EXIT_FAILURE;
1516
 
        goto end;
1517
 
      }
1518
 
      free(direntries);
1519
 
    } else {
1520
 
      free(direntries);
1521
 
      fprintf(stderr, "Could not find a network interface\n");
1522
 
      exitcode = EXIT_FAILURE;
1523
 
      goto end;
1524
 
    }
1525
 
  }
1526
1154
  
1527
1155
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
1528
1156
     from the signal handler */
1531
1159
  mc.simple_poll = avahi_simple_poll_new();
1532
1160
  if(mc.simple_poll == NULL){
1533
1161
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
1534
 
    exitcode = EX_UNAVAILABLE;
 
1162
    exitcode = EXIT_FAILURE;
1535
1163
    goto end;
1536
1164
  }
1537
1165
  
1538
1166
  sigemptyset(&sigterm_action.sa_mask);
1539
1167
  ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
1540
1168
  if(ret == -1){
1541
 
    perror_plus("sigaddset");
1542
 
    exitcode = EX_OSERR;
 
1169
    perror("sigaddset");
 
1170
    exitcode = EXIT_FAILURE;
1543
1171
    goto end;
1544
1172
  }
1545
1173
  ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
1546
1174
  if(ret == -1){
1547
 
    perror_plus("sigaddset");
1548
 
    exitcode = EX_OSERR;
 
1175
    perror("sigaddset");
 
1176
    exitcode = EXIT_FAILURE;
1549
1177
    goto end;
1550
1178
  }
1551
1179
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
1552
1180
  if(ret == -1){
1553
 
    perror_plus("sigaddset");
1554
 
    exitcode = EX_OSERR;
 
1181
    perror("sigaddset");
 
1182
    exitcode = EXIT_FAILURE;
1555
1183
    goto end;
1556
1184
  }
1557
1185
  /* Need to check if the handler is SIG_IGN before handling:
1560
1188
  */
1561
1189
  ret = sigaction(SIGINT, NULL, &old_sigterm_action);
1562
1190
  if(ret == -1){
1563
 
    perror_plus("sigaction");
1564
 
    return EX_OSERR;
 
1191
    perror("sigaction");
 
1192
    return EXIT_FAILURE;
1565
1193
  }
1566
1194
  if(old_sigterm_action.sa_handler != SIG_IGN){
1567
1195
    ret = sigaction(SIGINT, &sigterm_action, NULL);
1568
1196
    if(ret == -1){
1569
 
      perror_plus("sigaction");
1570
 
      exitcode = EX_OSERR;
 
1197
      perror("sigaction");
 
1198
      exitcode = EXIT_FAILURE;
1571
1199
      goto end;
1572
1200
    }
1573
1201
  }
1574
1202
  ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
1575
1203
  if(ret == -1){
1576
 
    perror_plus("sigaction");
1577
 
    return EX_OSERR;
 
1204
    perror("sigaction");
 
1205
    return EXIT_FAILURE;
1578
1206
  }
1579
1207
  if(old_sigterm_action.sa_handler != SIG_IGN){
1580
1208
    ret = sigaction(SIGHUP, &sigterm_action, NULL);
1581
1209
    if(ret == -1){
1582
 
      perror_plus("sigaction");
1583
 
      exitcode = EX_OSERR;
 
1210
      perror("sigaction");
 
1211
      exitcode = EXIT_FAILURE;
1584
1212
      goto end;
1585
1213
    }
1586
1214
  }
1587
1215
  ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
1588
1216
  if(ret == -1){
1589
 
    perror_plus("sigaction");
1590
 
    return EX_OSERR;
 
1217
    perror("sigaction");
 
1218
    return EXIT_FAILURE;
1591
1219
  }
1592
1220
  if(old_sigterm_action.sa_handler != SIG_IGN){
1593
1221
    ret = sigaction(SIGTERM, &sigterm_action, NULL);
1594
1222
    if(ret == -1){
1595
 
      perror_plus("sigaction");
1596
 
      exitcode = EX_OSERR;
 
1223
      perror("sigaction");
 
1224
      exitcode = EXIT_FAILURE;
1597
1225
      goto end;
1598
1226
    }
1599
1227
  }
1600
1228
  
1601
1229
  /* If the interface is down, bring it up */
1602
 
  if(strcmp(interface, "none") != 0){
 
1230
  if(interface[0] != '\0'){
1603
1231
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1604
1232
    if(if_index == 0){
1605
1233
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
1606
 
      exitcode = EX_UNAVAILABLE;
 
1234
      exitcode = EXIT_FAILURE;
1607
1235
      goto end;
1608
1236
    }
1609
1237
    
1615
1243
    errno = 0;
1616
1244
    ret = seteuid(0);
1617
1245
    if(ret == -1){
1618
 
      perror_plus("seteuid");
 
1246
      perror("seteuid");
1619
1247
    }
1620
1248
    
1621
1249
#ifdef __linux__
1625
1253
    bool restore_loglevel = true;
1626
1254
    if(ret == -1){
1627
1255
      restore_loglevel = false;
1628
 
      perror_plus("klogctl");
 
1256
      perror("klogctl");
1629
1257
    }
1630
1258
#endif  /* __linux__ */
1631
1259
    
1632
1260
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1633
1261
    if(sd < 0){
1634
 
      perror_plus("socket");
1635
 
      exitcode = EX_OSERR;
 
1262
      perror("socket");
 
1263
      exitcode = EXIT_FAILURE;
1636
1264
#ifdef __linux__
1637
1265
      if(restore_loglevel){
1638
1266
        ret = klogctl(7, NULL, 0);
1639
1267
        if(ret == -1){
1640
 
          perror_plus("klogctl");
 
1268
          perror("klogctl");
1641
1269
        }
1642
1270
      }
1643
1271
#endif  /* __linux__ */
1645
1273
      errno = 0;
1646
1274
      ret = seteuid(uid);
1647
1275
      if(ret == -1){
1648
 
        perror_plus("seteuid");
 
1276
        perror("seteuid");
1649
1277
      }
1650
1278
      goto end;
1651
1279
    }
1652
1280
    strcpy(network.ifr_name, interface);
1653
1281
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
1654
1282
    if(ret == -1){
1655
 
      perror_plus("ioctl SIOCGIFFLAGS");
 
1283
      perror("ioctl SIOCGIFFLAGS");
1656
1284
#ifdef __linux__
1657
1285
      if(restore_loglevel){
1658
1286
        ret = klogctl(7, NULL, 0);
1659
1287
        if(ret == -1){
1660
 
          perror_plus("klogctl");
 
1288
          perror("klogctl");
1661
1289
        }
1662
1290
      }
1663
1291
#endif  /* __linux__ */
1664
 
      exitcode = EX_OSERR;
 
1292
      exitcode = EXIT_FAILURE;
1665
1293
      /* Lower privileges */
1666
1294
      errno = 0;
1667
1295
      ret = seteuid(uid);
1668
1296
      if(ret == -1){
1669
 
        perror_plus("seteuid");
 
1297
        perror("seteuid");
1670
1298
      }
1671
1299
      goto end;
1672
1300
    }
1676
1304
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1677
1305
      if(ret == -1){
1678
1306
        take_down_interface = false;
1679
 
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1680
 
        exitcode = EX_OSERR;
 
1307
        perror("ioctl SIOCSIFFLAGS");
 
1308
        exitcode = EXIT_FAILURE;
1681
1309
#ifdef __linux__
1682
1310
        if(restore_loglevel){
1683
1311
          ret = klogctl(7, NULL, 0);
1684
1312
          if(ret == -1){
1685
 
            perror_plus("klogctl");
 
1313
            perror("klogctl");
1686
1314
          }
1687
1315
        }
1688
1316
#endif  /* __linux__ */
1690
1318
        errno = 0;
1691
1319
        ret = seteuid(uid);
1692
1320
        if(ret == -1){
1693
 
          perror_plus("seteuid");
 
1321
          perror("seteuid");
1694
1322
        }
1695
1323
        goto end;
1696
1324
      }
1697
1325
    }
1698
 
    /* Sleep checking until interface is running.
1699
 
       Check every 0.25s, up to total time of delay */
 
1326
    /* sleep checking until interface is running */
1700
1327
    for(int i=0; i < delay * 4; i++){
1701
1328
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1702
1329
      if(ret == -1){
1703
 
        perror_plus("ioctl SIOCGIFFLAGS");
 
1330
        perror("ioctl SIOCGIFFLAGS");
1704
1331
      } else if(network.ifr_flags & IFF_RUNNING){
1705
1332
        break;
1706
1333
      }
1707
1334
      struct timespec sleeptime = { .tv_nsec = 250000000 };
1708
1335
      ret = nanosleep(&sleeptime, NULL);
1709
1336
      if(ret == -1 and errno != EINTR){
1710
 
        perror_plus("nanosleep");
 
1337
        perror("nanosleep");
1711
1338
      }
1712
1339
    }
1713
1340
    if(not take_down_interface){
1714
1341
      /* We won't need the socket anymore */
1715
1342
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1716
1343
      if(ret == -1){
1717
 
        perror_plus("close");
 
1344
        perror("close");
1718
1345
      }
1719
1346
    }
1720
1347
#ifdef __linux__
1722
1349
      /* Restores kernel loglevel to default */
1723
1350
      ret = klogctl(7, NULL, 0);
1724
1351
      if(ret == -1){
1725
 
        perror_plus("klogctl");
 
1352
        perror("klogctl");
1726
1353
      }
1727
1354
    }
1728
1355
#endif  /* __linux__ */
1732
1359
      /* Lower privileges */
1733
1360
      ret = seteuid(uid);
1734
1361
      if(ret == -1){
1735
 
        perror_plus("seteuid");
 
1362
        perror("seteuid");
1736
1363
      }
1737
1364
    } else {
1738
1365
      /* Lower privileges permanently */
1739
1366
      ret = setuid(uid);
1740
1367
      if(ret == -1){
1741
 
        perror_plus("setuid");
 
1368
        perror("setuid");
1742
1369
      }
1743
1370
    }
1744
1371
  }
1750
1377
  ret = init_gnutls_global(pubkey, seckey);
1751
1378
  if(ret == -1){
1752
1379
    fprintf(stderr, "init_gnutls_global failed\n");
1753
 
    exitcode = EX_UNAVAILABLE;
 
1380
    exitcode = EXIT_FAILURE;
1754
1381
    goto end;
1755
1382
  } else {
1756
1383
    gnutls_initialized = true;
1760
1387
    goto end;
1761
1388
  }
1762
1389
  
 
1390
  tempdir_created = true;
1763
1391
  if(mkdtemp(tempdir) == NULL){
1764
 
    perror_plus("mkdtemp");
 
1392
    tempdir_created = false;
 
1393
    perror("mkdtemp");
1765
1394
    goto end;
1766
1395
  }
1767
 
  tempdir_created = true;
1768
1396
  
1769
1397
  if(quit_now){
1770
1398
    goto end;
1772
1400
  
1773
1401
  if(not init_gpgme(pubkey, seckey, tempdir)){
1774
1402
    fprintf(stderr, "init_gpgme failed\n");
1775
 
    exitcode = EX_UNAVAILABLE;
 
1403
    exitcode = EXIT_FAILURE;
1776
1404
    goto end;
1777
1405
  } else {
1778
1406
    gpgme_initialized = true;
1788
1416
    char *address = strrchr(connect_to, ':');
1789
1417
    if(address == NULL){
1790
1418
      fprintf(stderr, "No colon in address\n");
1791
 
      exitcode = EX_USAGE;
 
1419
      exitcode = EXIT_FAILURE;
1792
1420
      goto end;
1793
1421
    }
1794
1422
    
1802
1430
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
1803
1431
       or tmpmax != (uint16_t)tmpmax){
1804
1432
      fprintf(stderr, "Bad port number\n");
1805
 
      exitcode = EX_USAGE;
 
1433
      exitcode = EXIT_FAILURE;
1806
1434
      goto end;
1807
1435
    }
1808
1436
  
1812
1440
    
1813
1441
    port = (uint16_t)tmpmax;
1814
1442
    *address = '\0';
 
1443
    address = connect_to;
1815
1444
    /* Colon in address indicates IPv6 */
1816
1445
    int af;
1817
 
    if(strchr(connect_to, ':') != NULL){
 
1446
    if(strchr(address, ':') != NULL){
1818
1447
      af = AF_INET6;
1819
 
      /* Accept [] around IPv6 address - see RFC 5952 */
1820
 
      if(connect_to[0] == '[' and address[-1] == ']')
1821
 
        {
1822
 
          connect_to++;
1823
 
          address[-1] = '\0';
1824
 
        }
1825
1448
    } else {
1826
1449
      af = AF_INET;
1827
1450
    }
1828
 
    address = connect_to;
1829
1451
    
1830
1452
    if(quit_now){
1831
1453
      goto end;
1832
1454
    }
1833
1455
    
1834
 
    while(not quit_now){
1835
 
      ret = start_mandos_communication(address, port, if_index, af);
1836
 
      if(quit_now or ret == 0){
1837
 
        break;
1838
 
      }
1839
 
      if(debug){
1840
 
        fprintf(stderr, "Retrying in %d seconds\n",
1841
 
                (int)retry_interval);
1842
 
      }
1843
 
      sleep((int)retry_interval);
1844
 
    }
1845
 
    
1846
 
    if (not quit_now){
 
1456
    ret = start_mandos_communication(address, port, if_index, af);
 
1457
    if(ret < 0){
 
1458
      exitcode = EXIT_FAILURE;
 
1459
    } else {
1847
1460
      exitcode = EXIT_SUCCESS;
1848
1461
    }
1849
 
 
1850
1462
    goto end;
1851
1463
  }
1852
1464
  
1876
1488
  if(mc.server == NULL){
1877
1489
    fprintf(stderr, "Failed to create Avahi server: %s\n",
1878
1490
            avahi_strerror(error));
1879
 
    exitcode = EX_UNAVAILABLE;
 
1491
    exitcode = EXIT_FAILURE;
1880
1492
    goto end;
1881
1493
  }
1882
1494
  
1891
1503
  if(sb == NULL){
1892
1504
    fprintf(stderr, "Failed to create service browser: %s\n",
1893
1505
            avahi_strerror(avahi_server_errno(mc.server)));
1894
 
    exitcode = EX_UNAVAILABLE;
 
1506
    exitcode = EXIT_FAILURE;
1895
1507
    goto end;
1896
1508
  }
1897
1509
  
1904
1516
  if(debug){
1905
1517
    fprintf(stderr, "Starting Avahi loop search\n");
1906
1518
  }
1907
 
 
1908
 
  ret = avahi_loop_with_timeout(mc.simple_poll,
1909
 
                                (int)(retry_interval * 1000));
1910
 
  if(debug){
1911
 
    fprintf(stderr, "avahi_loop_with_timeout exited %s\n",
1912
 
            (ret == 0) ? "successfully" : "with error");
1913
 
  }
 
1519
  
 
1520
  avahi_simple_poll_loop(mc.simple_poll);
1914
1521
  
1915
1522
 end:
1916
1523
  
1937
1544
  if(gpgme_initialized){
1938
1545
    gpgme_release(mc.ctx);
1939
1546
  }
1940
 
 
1941
 
  /* Cleans up the circular linked list of Mandos servers the client
1942
 
     has seen */
1943
 
  if(mc.current_server != NULL){
1944
 
    mc.current_server->prev->next = NULL;
1945
 
    while(mc.current_server != NULL){
1946
 
      server *next = mc.current_server->next;
1947
 
      free(mc.current_server);
1948
 
      mc.current_server = next;
1949
 
    }
1950
 
  }
1951
1547
  
1952
1548
  /* Take down the network interface */
1953
1549
  if(take_down_interface){
1955
1551
    errno = 0;
1956
1552
    ret = seteuid(0);
1957
1553
    if(ret == -1){
1958
 
      perror_plus("seteuid");
 
1554
      perror("seteuid");
1959
1555
    }
1960
1556
    if(geteuid() == 0){
1961
1557
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1962
1558
      if(ret == -1){
1963
 
        perror_plus("ioctl SIOCGIFFLAGS");
 
1559
        perror("ioctl SIOCGIFFLAGS");
1964
1560
      } else if(network.ifr_flags & IFF_UP) {
1965
1561
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
1966
1562
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
1967
1563
        if(ret == -1){
1968
 
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
 
1564
          perror("ioctl SIOCSIFFLAGS");
1969
1565
        }
1970
1566
      }
1971
1567
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1972
1568
      if(ret == -1){
1973
 
        perror_plus("close");
 
1569
        perror("close");
1974
1570
      }
1975
1571
      /* Lower privileges permanently */
1976
1572
      errno = 0;
1977
1573
      ret = setuid(uid);
1978
1574
      if(ret == -1){
1979
 
        perror_plus("setuid");
 
1575
        perror("setuid");
1980
1576
      }
1981
1577
    }
1982
1578
  }
1983
1579
  
1984
 
  /* Removes the GPGME temp directory and all files inside */
 
1580
  /* Removes the temp directory used by GPGME */
1985
1581
  if(tempdir_created){
1986
 
    struct dirent **direntries = NULL;
1987
 
    struct dirent *direntry = NULL;
1988
 
    int numentries = scandir(tempdir, &direntries, notdotentries,
1989
 
                             alphasort);
1990
 
    if (numentries > 0){
1991
 
      for(int i = 0; i < numentries; i++){
1992
 
        direntry = direntries[i];
 
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
1602
        char *fullname = NULL;
1994
1603
        ret = asprintf(&fullname, "%s/%s", tempdir,
1995
1604
                       direntry->d_name);
1996
1605
        if(ret < 0){
1997
 
          perror_plus("asprintf");
 
1606
          perror("asprintf");
1998
1607
          continue;
1999
1608
        }
2000
1609
        ret = remove(fullname);
2004
1613
        }
2005
1614
        free(fullname);
2006
1615
      }
2007
 
    }
2008
 
 
2009
 
    /* need to clean even if 0 because man page doesn't specify */
2010
 
    free(direntries);
2011
 
    if (numentries == -1){
2012
 
      perror_plus("scandir");
 
1616
      closedir(d);
2013
1617
    }
2014
1618
    ret = rmdir(tempdir);
2015
1619
    if(ret == -1 and errno != ENOENT){
2016
 
      perror_plus("rmdir");
 
1620
      perror("rmdir");
2017
1621
    }
2018
1622
  }
2019
1623
  
2024
1628
                                            &old_sigterm_action,
2025
1629
                                            NULL));
2026
1630
    if(ret == -1){
2027
 
      perror_plus("sigaction");
 
1631
      perror("sigaction");
2028
1632
    }
2029
1633
    do {
2030
1634
      ret = raise(signal_received);
2031
1635
    } while(ret != 0 and errno == EINTR);
2032
1636
    if(ret != 0){
2033
 
      perror_plus("raise");
 
1637
      perror("raise");
2034
1638
      abort();
2035
1639
    }
2036
1640
    TEMP_FAILURE_RETRY(pause());