/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

Intermediate commit - this does *not* work yet.

* plugins.d/mandos-client.c (HOOKDIR): New.
  (up_interface): New.
  (runnable_hook): New.
  (main): Run network hooks with "start" argument.

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
26
26
 * along with this program.  If not, see
27
27
 * <http://www.gnu.org/licenses/>.
28
28
 * 
29
 
 * Contact the authors at <mandos@fukt.bsnet.se>.
 
29
 * Contact the authors at <mandos@recompile.se>.
30
30
 */
31
31
 
32
32
/* Needed by GPGME, specifically gpgme_data_seek() */
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,
122
123
#define PATHDIR "/conf/conf.d/mandos"
123
124
#define SECKEY "seckey.txt"
124
125
#define PUBKEY "pubkey.txt"
 
126
#define HOOKDIR "/lib/mandos/network-hooks.d"
125
127
 
126
128
bool debug = false;
127
129
static const char mandos_protocol_version[] = "1";
128
130
const char *argp_program_version = "mandos-client " VERSION;
129
 
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
 
131
const char *argp_program_bug_address = "<mandos@recompile.se>";
 
132
static const char sys_class_net[] = "/sys/class/net";
 
133
char *connect_to = NULL;
 
134
 
 
135
/* Doubly linked list that need to be circularly linked when used */
 
136
typedef struct server{
 
137
  const char *ip;
 
138
  uint16_t port;
 
139
  AvahiIfIndex if_index;
 
140
  int af;
 
141
  struct timespec last_seen;
 
142
  struct server *next;
 
143
  struct server *prev;
 
144
} server;
130
145
 
131
146
/* Used for passing in values through the Avahi callback functions */
132
147
typedef struct {
137
152
  gnutls_dh_params_t dh_params;
138
153
  const char *priority;
139
154
  gpgme_ctx_t ctx;
 
155
  server *current_server;
140
156
} mandos_context;
141
157
 
142
158
/* global context so signal handler can reach it*/
143
159
mandos_context mc = { .simple_poll = NULL, .server = NULL,
144
160
                      .dh_bits = 1024, .priority = "SECURE256"
145
 
                      ":!CTYPE-X.509:+CTYPE-OPENPGP" };
 
161
                      ":!CTYPE-X.509:+CTYPE-OPENPGP",
 
162
                      .current_server = NULL };
146
163
 
147
164
sig_atomic_t quit_now = 0;
148
165
int signal_received = 0;
149
166
 
 
167
/* Function to use when printing errors */
 
168
void perror_plus(const char *print_text){
 
169
  fprintf(stderr, "Mandos plugin %s: ",
 
170
          program_invocation_short_name);
 
171
  perror(print_text);
 
172
}
 
173
 
150
174
/*
151
175
 * Make additional room in "buffer" for at least BUFFER_SIZE more
152
176
 * bytes. "buffer_capacity" is how much is currently allocated,
164
188
  return buffer_capacity;
165
189
}
166
190
 
 
191
/* Add server to set of servers to retry periodically */
 
192
int add_server(const char *ip, uint16_t port,
 
193
                 AvahiIfIndex if_index,
 
194
                 int af){
 
195
  int ret;
 
196
  server *new_server = malloc(sizeof(server));
 
197
  if(new_server == NULL){
 
198
    perror_plus("malloc");
 
199
    return -1;
 
200
  }
 
201
  *new_server = (server){ .ip = strdup(ip),
 
202
                         .port = port,
 
203
                         .if_index = if_index,
 
204
                         .af = af };
 
205
  if(new_server->ip == NULL){
 
206
    perror_plus("strdup");
 
207
    return -1;
 
208
  }
 
209
  /* Special case of first server */
 
210
  if (mc.current_server == NULL){
 
211
    new_server->next = new_server;
 
212
    new_server->prev = new_server;
 
213
    mc.current_server = new_server;
 
214
  /* Place the new server last in the list */
 
215
  } else {
 
216
    new_server->next = mc.current_server;
 
217
    new_server->prev = mc.current_server->prev;
 
218
    new_server->prev->next = new_server;
 
219
    mc.current_server->prev = new_server;
 
220
  }
 
221
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
 
222
  if(ret == -1){
 
223
    perror_plus("clock_gettime");
 
224
    return -1;
 
225
  }
 
226
  return 0;
 
227
}
 
228
 
167
229
/* 
168
230
 * Initialize GPGME.
169
231
 */
183
245
    
184
246
    fd = (int)TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
185
247
    if(fd == -1){
186
 
      perror("open");
 
248
      perror_plus("open");
187
249
      return false;
188
250
    }
189
251
    
203
265
    
204
266
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
205
267
    if(ret == -1){
206
 
      perror("close");
 
268
      perror_plus("close");
207
269
    }
208
270
    gpgme_data_release(pgp_data);
209
271
    return true;
222
284
    return false;
223
285
  }
224
286
  
225
 
    /* Set GPGME home directory for the OpenPGP engine only */
 
287
  /* Set GPGME home directory for the OpenPGP engine only */
226
288
  rc = gpgme_get_engine_info(&engine_info);
227
289
  if(rc != GPG_ERR_NO_ERROR){
228
290
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
334
396
  
335
397
  /* Seek back to the beginning of the GPGME plaintext data buffer */
336
398
  if(gpgme_data_seek(dh_plain, (off_t)0, SEEK_SET) == -1){
337
 
    perror("gpgme_data_seek");
 
399
    perror_plus("gpgme_data_seek");
338
400
    plaintext_length = -1;
339
401
    goto decrypt_end;
340
402
  }
345
407
                                      (size_t)plaintext_length,
346
408
                                      plaintext_capacity);
347
409
    if(plaintext_capacity == 0){
348
 
        perror("incbuffer");
 
410
        perror_plus("incbuffer");
349
411
        plaintext_length = -1;
350
412
        goto decrypt_end;
351
413
    }
358
420
      break;
359
421
    }
360
422
    if(ret < 0){
361
 
      perror("gpgme_data_read");
 
423
      perror_plus("gpgme_data_read");
362
424
      plaintext_length = -1;
363
425
      goto decrypt_end;
364
426
    }
421
483
  }
422
484
  
423
485
  /* OpenPGP credentials */
424
 
  gnutls_certificate_allocate_credentials(&mc.cred);
 
486
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
425
487
  if(ret != GNUTLS_E_SUCCESS){
426
 
    fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning
427
 
                                                    from
428
 
                                                    -Wunreachable-code
429
 
                                                 */
 
488
    fprintf(stderr, "GnuTLS memory error: %s\n",
430
489
            safer_gnutls_strerror(ret));
431
490
    gnutls_global_deinit();
432
491
    return -1;
587
646
  tcp_sd = socket(pf, SOCK_STREAM, 0);
588
647
  if(tcp_sd < 0){
589
648
    int e = errno;
590
 
    perror("socket");
 
649
    perror_plus("socket");
591
650
    errno = e;
592
651
    goto mandos_end;
593
652
  }
607
666
  }
608
667
  if(ret < 0 ){
609
668
    int e = errno;
610
 
    perror("inet_pton");
 
669
    perror_plus("inet_pton");
611
670
    errno = e;
612
671
    goto mandos_end;
613
672
  }
649
708
    if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
650
709
      char interface[IF_NAMESIZE];
651
710
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
652
 
        perror("if_indextoname");
 
711
        perror_plus("if_indextoname");
653
712
      } else {
654
713
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
655
714
                ip, interface, port);
669
728
                        sizeof(addrstr));
670
729
    }
671
730
    if(pcret == NULL){
672
 
      perror("inet_ntop");
 
731
      perror_plus("inet_ntop");
673
732
    } else {
674
733
      if(strcmp(addrstr, ip) != 0){
675
734
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
688
747
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
689
748
  }
690
749
  if(ret < 0){
691
 
    int e = errno;
692
 
    perror("connect");
693
 
    errno = e;
 
750
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
 
751
      int e = errno;
 
752
      perror_plus("connect");
 
753
      errno = e;
 
754
    }
694
755
    goto mandos_end;
695
756
  }
696
757
  
707
768
                                   out_size - written));
708
769
    if(ret == -1){
709
770
      int e = errno;
710
 
      perror("write");
 
771
      perror_plus("write");
711
772
      errno = e;
712
773
      goto mandos_end;
713
774
    }
738
799
    goto mandos_end;
739
800
  }
740
801
  
 
802
  /* Spurious warning from -Wint-to-pointer-cast */
741
803
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
742
804
  
743
805
  if(quit_now){
780
842
                                   buffer_capacity);
781
843
    if(buffer_capacity == 0){
782
844
      int e = errno;
783
 
      perror("incbuffer");
 
845
      perror_plus("incbuffer");
784
846
      errno = e;
785
847
      goto mandos_end;
786
848
    }
891
953
      if(e == 0){
892
954
        e = errno;
893
955
      }
894
 
      perror("close");
 
956
      perror_plus("close");
895
957
    }
896
958
    gnutls_deinit(session);
 
959
    errno = e;
897
960
    if(quit_now){
898
 
      e = EINTR;
 
961
      errno = EINTR;
899
962
      retval = -1;
900
963
    }
901
 
    errno = e;
902
964
  }
903
965
  return retval;
904
966
}
947
1009
                                           avahi_proto_to_af(proto));
948
1010
      if(ret == 0){
949
1011
        avahi_simple_poll_quit(mc.simple_poll);
 
1012
      } else {
 
1013
        ret = add_server(ip, port, interface,
 
1014
                         avahi_proto_to_af(proto));
950
1015
      }
951
1016
    }
952
1017
  }
1006
1071
  }
1007
1072
}
1008
1073
 
1009
 
/* stop main loop after sigterm has been called */
 
1074
/* Signal handler that stops main loop after SIGTERM */
1010
1075
static void handle_sigterm(int sig){
1011
1076
  if(quit_now){
1012
1077
    return;
1014
1079
  quit_now = 1;
1015
1080
  signal_received = sig;
1016
1081
  int old_errno = errno;
 
1082
  /* set main loop to exit */
1017
1083
  if(mc.simple_poll != NULL){
1018
1084
    avahi_simple_poll_quit(mc.simple_poll);
1019
1085
  }
1020
1086
  errno = old_errno;
1021
1087
}
1022
1088
 
 
1089
bool get_flags(const char *ifname, struct ifreq *ifr){
 
1090
  int ret;
 
1091
  
 
1092
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1093
  if(s < 0){
 
1094
    perror_plus("socket");
 
1095
    return false;
 
1096
  }
 
1097
  strcpy(ifr->ifr_name, ifname);
 
1098
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
 
1099
  if(ret == -1){
 
1100
    if(debug){
 
1101
      perror_plus("ioctl SIOCGIFFLAGS");
 
1102
    }
 
1103
    return false;
 
1104
  }
 
1105
  return true;
 
1106
}
 
1107
 
 
1108
bool good_flags(const char *ifname, const struct ifreq *ifr){
 
1109
  
 
1110
  /* Reject the loopback device */
 
1111
  if(ifr->ifr_flags & IFF_LOOPBACK){
 
1112
    if(debug){
 
1113
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
 
1114
              ifname);
 
1115
    }
 
1116
    return false;
 
1117
  }
 
1118
  /* Accept point-to-point devices only if connect_to is specified */
 
1119
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
 
1120
    if(debug){
 
1121
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
 
1122
              ifname);
 
1123
    }
 
1124
    return true;
 
1125
  }
 
1126
  /* Otherwise, reject non-broadcast-capable devices */
 
1127
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
 
1128
    if(debug){
 
1129
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
 
1130
              ifname);
 
1131
    }
 
1132
    return false;
 
1133
  }
 
1134
  /* Reject non-ARP interfaces (including dummy interfaces) */
 
1135
  if(ifr->ifr_flags & IFF_NOARP){
 
1136
    if(debug){
 
1137
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n", ifname);
 
1138
    }
 
1139
    return false;
 
1140
  }
 
1141
  
 
1142
  /* Accept this device */
 
1143
  if(debug){
 
1144
    fprintf(stderr, "Interface \"%s\" is good\n", ifname);
 
1145
  }
 
1146
  return true;
 
1147
}
 
1148
 
 
1149
/* 
 
1150
 * This function determines if a directory entry in /sys/class/net
 
1151
 * corresponds to an acceptable network device.
 
1152
 * (This function is passed to scandir(3) as a filter function.)
 
1153
 */
 
1154
int good_interface(const struct dirent *if_entry){
 
1155
  int ret;
 
1156
  if(if_entry->d_name[0] == '.'){
 
1157
    return 0;
 
1158
  }
 
1159
  struct ifreq ifr;
 
1160
 
 
1161
  if(not get_flags(if_entry->d_name, &ifr)){
 
1162
    return 0;
 
1163
  }
 
1164
  
 
1165
  if(not good_flags(if_entry->d_name, &ifr)){
 
1166
    return 0;
 
1167
  }
 
1168
  return 1;
 
1169
}
 
1170
 
 
1171
/* 
 
1172
 * This function determines if a directory entry in /sys/class/net
 
1173
 * corresponds to an acceptable network device which is up.
 
1174
 * (This function is passed to scandir(3) as a filter function.)
 
1175
 */
 
1176
int up_interface(const struct dirent *if_entry){
 
1177
  ssize_t ssret;
 
1178
  char *flagname = NULL;
 
1179
  if(if_entry->d_name[0] == '.'){
 
1180
    return 0;
 
1181
  }
 
1182
  int ret = asprintf(&flagname, "%s/%s/flags", sys_class_net,
 
1183
                     if_entry->d_name);
 
1184
  if(ret < 0){
 
1185
    perror_plus("asprintf");
 
1186
    return 0;
 
1187
  }
 
1188
  int flags_fd = (int)TEMP_FAILURE_RETRY(open(flagname, O_RDONLY));
 
1189
  if(flags_fd == -1){
 
1190
    perror_plus("open");
 
1191
    free(flagname);
 
1192
    return 0;
 
1193
  }
 
1194
  free(flagname);
 
1195
  typedef short ifreq_flags;    /* ifreq.ifr_flags in netdevice(7) */
 
1196
  /* read line from flags_fd */
 
1197
  ssize_t to_read = 2+(sizeof(ifreq_flags)*2)+1; /* "0x1003\n" */
 
1198
  char *flagstring = malloc((size_t)to_read+1); /* +1 for final \0 */
 
1199
  flagstring[(size_t)to_read] = '\0';
 
1200
  if(flagstring == NULL){
 
1201
    perror_plus("malloc");
 
1202
    close(flags_fd);
 
1203
    return 0;
 
1204
  }
 
1205
  while(to_read > 0){
 
1206
    ssret = (ssize_t)TEMP_FAILURE_RETRY(read(flags_fd, flagstring,
 
1207
                                             (size_t)to_read));
 
1208
    if(ssret == -1){
 
1209
      perror_plus("read");
 
1210
      free(flagstring);
 
1211
      close(flags_fd);
 
1212
      return 0;
 
1213
    }
 
1214
    to_read -= ssret;
 
1215
    if(ssret == 0){
 
1216
      break;
 
1217
    }
 
1218
  }
 
1219
  close(flags_fd);
 
1220
  intmax_t tmpmax;
 
1221
  char *tmp;
 
1222
  errno = 0;
 
1223
  tmpmax = strtoimax(flagstring, &tmp, 0);
 
1224
  if(errno != 0 or tmp == flagstring or (*tmp != '\0'
 
1225
                                         and not (isspace(*tmp)))
 
1226
     or tmpmax != (ifreq_flags)tmpmax){
 
1227
    if(debug){
 
1228
      fprintf(stderr, "Invalid flags \"%s\" for interface \"%s\"\n",
 
1229
              flagstring, if_entry->d_name);
 
1230
    }
 
1231
    free(flagstring);
 
1232
    return 0;
 
1233
  }
 
1234
  free(flagstring);
 
1235
  ifreq_flags flags = (ifreq_flags)tmpmax;
 
1236
  /* Reject the loopback device */
 
1237
  if(flags & IFF_LOOPBACK){
 
1238
    if(debug){
 
1239
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
 
1240
              if_entry->d_name);
 
1241
    }
 
1242
    return 0;
 
1243
  }
 
1244
 
 
1245
  /* Reject down interfaces */
 
1246
  if(not (flags & IFF_UP)){
 
1247
    return 0;
 
1248
  }
 
1249
  
 
1250
  /* Accept point-to-point devices only if connect_to is specified */
 
1251
  if(connect_to != NULL and (flags & IFF_POINTOPOINT)){
 
1252
    if(debug){
 
1253
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
 
1254
              if_entry->d_name);
 
1255
    }
 
1256
    return 1;
 
1257
  }
 
1258
  /* Otherwise, reject non-broadcast-capable devices */
 
1259
  if(not (flags & IFF_BROADCAST)){
 
1260
    if(debug){
 
1261
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
 
1262
              if_entry->d_name);
 
1263
    }
 
1264
    return 0;
 
1265
  }
 
1266
  /* Reject non-ARP interfaces (including dummy interfaces) */
 
1267
  if(flags & IFF_NOARP){
 
1268
    if(debug){
 
1269
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n",
 
1270
              if_entry->d_name);
 
1271
    }
 
1272
    return 0;
 
1273
  }
 
1274
  /* Accept this device */
 
1275
  if(debug){
 
1276
    fprintf(stderr, "Interface \"%s\" is acceptable\n",
 
1277
            if_entry->d_name);
 
1278
  }
 
1279
  return 1;
 
1280
}
 
1281
 
 
1282
int notdotentries(const struct dirent *direntry){
 
1283
  /* Skip "." and ".." */
 
1284
  if(direntry->d_name[0] == '.'
 
1285
     and (direntry->d_name[1] == '\0'
 
1286
          or (direntry->d_name[1] == '.'
 
1287
              and direntry->d_name[2] == '\0'))){
 
1288
    return 0;
 
1289
  }
 
1290
  return 1;
 
1291
}
 
1292
 
 
1293
/* Is this directory entry a runnable program? */
 
1294
int runnable_hook(const struct dirent *direntry){
 
1295
  int ret;
 
1296
  struct stat st;
 
1297
  
 
1298
  if((direntry->d_name)[0] == '\0'){
 
1299
    /* Empty name? */
 
1300
    return 0;
 
1301
  }
 
1302
  
 
1303
  /* Save pointer to last character */
 
1304
  char *end = strchr(direntry->d_name, '\0')-1;
 
1305
  
 
1306
  if(*end == '~'){
 
1307
    /* Backup name~ */
 
1308
    return 0;
 
1309
  }
 
1310
  
 
1311
  if(((direntry->d_name)[0] == '#')
 
1312
     and (*end == '#')){
 
1313
    /* Temporary #name# */
 
1314
    return 0;
 
1315
  }
 
1316
  
 
1317
  /* XXX more rules here */
 
1318
  
 
1319
  ret = stat(direntry->d_name, &st);
 
1320
  if(ret == -1){
 
1321
    if(debug){
 
1322
      perror_plus("Could not stat plugin");
 
1323
    }
 
1324
    return 0;
 
1325
  }
 
1326
  if(not (st.st_mode & S_ISREG)){
 
1327
    /* Not a regular file */
 
1328
    return 0;
 
1329
  }
 
1330
  if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
 
1331
    /* Not executable */
 
1332
    return 0;
 
1333
  }
 
1334
  return 1;
 
1335
}
 
1336
 
 
1337
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
 
1338
  int ret;
 
1339
  struct timespec now;
 
1340
  struct timespec waited_time;
 
1341
  intmax_t block_time;
 
1342
  
 
1343
  while(true){
 
1344
    if(mc.current_server == NULL){
 
1345
      if (debug){
 
1346
        fprintf(stderr,
 
1347
                "Wait until first server is found. No timeout!\n");
 
1348
      }
 
1349
      ret = avahi_simple_poll_iterate(s, -1);
 
1350
    } else {
 
1351
      if (debug){
 
1352
        fprintf(stderr, "Check current_server if we should run it,"
 
1353
                " or wait\n");
 
1354
      }
 
1355
      /* the current time */
 
1356
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
 
1357
      if(ret == -1){
 
1358
        perror_plus("clock_gettime");
 
1359
        return -1;
 
1360
      }
 
1361
      /* Calculating in ms how long time between now and server
 
1362
         who we visted longest time ago. Now - last seen.  */
 
1363
      waited_time.tv_sec = (now.tv_sec
 
1364
                            - mc.current_server->last_seen.tv_sec);
 
1365
      waited_time.tv_nsec = (now.tv_nsec
 
1366
                             - mc.current_server->last_seen.tv_nsec);
 
1367
      /* total time is 10s/10,000ms.
 
1368
         Converting to s from ms by dividing by 1,000,
 
1369
         and ns to ms by dividing by 1,000,000. */
 
1370
      block_time = ((retry_interval
 
1371
                     - ((intmax_t)waited_time.tv_sec * 1000))
 
1372
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
 
1373
      
 
1374
      if (debug){
 
1375
        fprintf(stderr, "Blocking for %" PRIdMAX " ms\n", block_time);
 
1376
      }
 
1377
      
 
1378
      if(block_time <= 0){
 
1379
        ret = start_mandos_communication(mc.current_server->ip,
 
1380
                                         mc.current_server->port,
 
1381
                                         mc.current_server->if_index,
 
1382
                                         mc.current_server->af);
 
1383
        if(ret == 0){
 
1384
          avahi_simple_poll_quit(mc.simple_poll);
 
1385
          return 0;
 
1386
        }
 
1387
        ret = clock_gettime(CLOCK_MONOTONIC,
 
1388
                            &mc.current_server->last_seen);
 
1389
        if(ret == -1){
 
1390
          perror_plus("clock_gettime");
 
1391
          return -1;
 
1392
        }
 
1393
        mc.current_server = mc.current_server->next;
 
1394
        block_time = 0;         /* Call avahi to find new Mandos
 
1395
                                   servers, but don't block */
 
1396
      }
 
1397
      
 
1398
      ret = avahi_simple_poll_iterate(s, (int)block_time);
 
1399
    }
 
1400
    if(ret != 0){
 
1401
      if (ret > 0 or errno != EINTR) {
 
1402
        return (ret != 1) ? ret : 0;
 
1403
      }
 
1404
    }
 
1405
  }
 
1406
}
 
1407
 
1023
1408
int main(int argc, char *argv[]){
1024
1409
  AvahiSServiceBrowser *sb = NULL;
1025
1410
  int error;
1027
1412
  intmax_t tmpmax;
1028
1413
  char *tmp;
1029
1414
  int exitcode = EXIT_SUCCESS;
1030
 
  const char *interface = "eth0";
 
1415
  const char *interface = "";
1031
1416
  struct ifreq network;
1032
1417
  int sd = -1;
1033
1418
  bool take_down_interface = false;
1034
1419
  uid_t uid;
1035
1420
  gid_t gid;
1036
 
  char *connect_to = NULL;
1037
1421
  char tempdir[] = "/tmp/mandosXXXXXX";
1038
1422
  bool tempdir_created = false;
1039
1423
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1043
1427
  bool gnutls_initialized = false;
1044
1428
  bool gpgme_initialized = false;
1045
1429
  float delay = 2.5f;
 
1430
  double retry_interval = 10; /* 10s between trying a server and
 
1431
                                 retrying the same server again */
1046
1432
  
1047
1433
  struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
1048
1434
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
1054
1440
  errno = 0;
1055
1441
  ret = setgid(gid);
1056
1442
  if(ret == -1){
1057
 
    perror("setgid");
 
1443
    perror_plus("setgid");
1058
1444
  }
1059
1445
  
1060
1446
  /* Lower user privileges (temporarily) */
1061
1447
  errno = 0;
1062
1448
  ret = seteuid(uid);
1063
1449
  if(ret == -1){
1064
 
    perror("seteuid");
 
1450
    perror_plus("seteuid");
1065
1451
  }
1066
1452
  
1067
1453
  if(quit_now){
1102
1488
        .arg = "SECONDS",
1103
1489
        .doc = "Maximum delay to wait for interface startup",
1104
1490
        .group = 2 },
 
1491
      { .name = "retry", .key = 132,
 
1492
        .arg = "SECONDS",
 
1493
        .doc = "Retry interval used when denied by the mandos server",
 
1494
        .group = 2 },
1105
1495
      /*
1106
1496
       * These reproduce what we would get without ARGP_NO_HELP
1107
1497
       */
1151
1541
        if(errno != 0 or tmp == arg or *tmp != '\0'){
1152
1542
          argp_error(state, "Bad delay");
1153
1543
        }
 
1544
      case 132:                 /* --retry */
 
1545
        errno = 0;
 
1546
        retry_interval = strtod(arg, &tmp);
 
1547
        if(errno != 0 or tmp == arg or *tmp != '\0'
 
1548
           or (retry_interval * 1000) > INT_MAX
 
1549
           or retry_interval < 0){
 
1550
          argp_error(state, "Bad retry interval");
 
1551
        }
1154
1552
        break;
1155
1553
        /*
1156
1554
         * These reproduce what we would get without ARGP_NO_HELP
1184
1582
    case ENOMEM:
1185
1583
    default:
1186
1584
      errno = ret;
1187
 
      perror("argp_parse");
 
1585
      perror_plus("argp_parse");
1188
1586
      exitcode = EX_OSERR;
1189
1587
      goto end;
1190
1588
    case EINVAL:
1192
1590
      goto end;
1193
1591
    }
1194
1592
  }
 
1593
    
 
1594
  {
 
1595
    /* Work around Debian bug #633582:
 
1596
       <http://bugs.debian.org/633582> */
 
1597
    struct stat st;
 
1598
    
 
1599
    /* Re-raise priviliges */
 
1600
    errno = 0;
 
1601
    ret = seteuid(0);
 
1602
    if(ret == -1){
 
1603
      perror_plus("seteuid");
 
1604
    }
 
1605
    
 
1606
    if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
 
1607
      int seckey_fd = open(seckey, O_RDONLY);
 
1608
      if(seckey_fd == -1){
 
1609
        perror_plus("open");
 
1610
      } else {
 
1611
        ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
 
1612
        if(ret == -1){
 
1613
          perror_plus("fstat");
 
1614
        } else {
 
1615
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
 
1616
            ret = fchown(seckey_fd, uid, gid);
 
1617
            if(ret == -1){
 
1618
              perror_plus("fchown");
 
1619
            }
 
1620
          }
 
1621
        }
 
1622
        TEMP_FAILURE_RETRY(close(seckey_fd));
 
1623
      }
 
1624
    }
 
1625
    
 
1626
    if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
 
1627
      int pubkey_fd = open(pubkey, O_RDONLY);
 
1628
      if(pubkey_fd == -1){
 
1629
        perror_plus("open");
 
1630
      } else {
 
1631
        ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
 
1632
        if(ret == -1){
 
1633
          perror_plus("fstat");
 
1634
        } else {
 
1635
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
 
1636
            ret = fchown(pubkey_fd, uid, gid);
 
1637
            if(ret == -1){
 
1638
              perror_plus("fchown");
 
1639
            }
 
1640
          }
 
1641
        }
 
1642
        TEMP_FAILURE_RETRY(close(pubkey_fd));
 
1643
      }
 
1644
    }
 
1645
    
 
1646
    /* Lower privileges */
 
1647
    errno = 0;
 
1648
    ret = seteuid(uid);
 
1649
    if(ret == -1){
 
1650
      perror_plus("seteuid");
 
1651
    }
 
1652
  }
 
1653
  
 
1654
  /* Find network hooks and run them */
 
1655
  {
 
1656
    struct dirent **direntries;
 
1657
    struct dirent *direntry;
 
1658
    int numhooks = scandir(HOOKDIR, &direntries, runnable_hook,
 
1659
                           alphasort);
 
1660
    int devnull = open("/dev/null", O_RDONLY);
 
1661
    for(int i = 0; i < numhooks; i++){
 
1662
      direntry = direntries[0];
 
1663
      char *fullname = NULL;
 
1664
      ret = asprintf(&fullname, "%s/%s", tempdir,
 
1665
                     direntry->d_name);
 
1666
      if(ret < 0){
 
1667
        perror_plus("asprintf");
 
1668
        continue;
 
1669
      }
 
1670
      pid_t hook_pid = fork();
 
1671
      if(hook_pid == 0){
 
1672
        /* Child */
 
1673
        dup2(devnull, STDIN_FILENO);
 
1674
        close(devnull);
 
1675
        dup2(STDERR_FILENO, STDOUT_FILENO);
 
1676
        setenv("DEVICE", interface, 1);
 
1677
        setenv("VERBOSE", debug ? "1" : "0", 1);
 
1678
        setenv("MODE", "start", 1);
 
1679
        /* setenv( XXX more here */
 
1680
        ret = execl(fullname, direntry->d_name, "start");
 
1681
        perror_plus("execl");
 
1682
      }
 
1683
      free(fullname);
 
1684
      if(quit_now){
 
1685
        goto end;
 
1686
      }
 
1687
    }
 
1688
    close(devnull);
 
1689
  }
1195
1690
  
1196
1691
  if(not debug){
1197
1692
    avahi_set_log_function(empty_log);
1198
1693
  }
1199
1694
  
 
1695
  if(interface[0] == '\0'){
 
1696
    struct dirent **direntries;
 
1697
    ret = scandir(sys_class_net, &direntries, good_interface,
 
1698
                  alphasort);
 
1699
    if(ret >= 1){
 
1700
      /* Pick the first good interface */
 
1701
      interface = strdup(direntries[0]->d_name);
 
1702
      if(debug){
 
1703
        fprintf(stderr, "Using interface \"%s\"\n", interface);
 
1704
      }
 
1705
      if(interface == NULL){
 
1706
        perror_plus("malloc");
 
1707
        free(direntries);
 
1708
        exitcode = EXIT_FAILURE;
 
1709
        goto end;
 
1710
      }
 
1711
      free(direntries);
 
1712
    } else {
 
1713
      free(direntries);
 
1714
      fprintf(stderr, "Could not find a network interface\n");
 
1715
      exitcode = EXIT_FAILURE;
 
1716
      goto end;
 
1717
    }
 
1718
  }
 
1719
  
1200
1720
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
1201
1721
     from the signal handler */
1202
1722
  /* Initialize the pseudo-RNG for Avahi */
1211
1731
  sigemptyset(&sigterm_action.sa_mask);
1212
1732
  ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
1213
1733
  if(ret == -1){
1214
 
    perror("sigaddset");
 
1734
    perror_plus("sigaddset");
1215
1735
    exitcode = EX_OSERR;
1216
1736
    goto end;
1217
1737
  }
1218
1738
  ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
1219
1739
  if(ret == -1){
1220
 
    perror("sigaddset");
 
1740
    perror_plus("sigaddset");
1221
1741
    exitcode = EX_OSERR;
1222
1742
    goto end;
1223
1743
  }
1224
1744
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
1225
1745
  if(ret == -1){
1226
 
    perror("sigaddset");
 
1746
    perror_plus("sigaddset");
1227
1747
    exitcode = EX_OSERR;
1228
1748
    goto end;
1229
1749
  }
1233
1753
  */
1234
1754
  ret = sigaction(SIGINT, NULL, &old_sigterm_action);
1235
1755
  if(ret == -1){
1236
 
    perror("sigaction");
 
1756
    perror_plus("sigaction");
1237
1757
    return EX_OSERR;
1238
1758
  }
1239
1759
  if(old_sigterm_action.sa_handler != SIG_IGN){
1240
1760
    ret = sigaction(SIGINT, &sigterm_action, NULL);
1241
1761
    if(ret == -1){
1242
 
      perror("sigaction");
 
1762
      perror_plus("sigaction");
1243
1763
      exitcode = EX_OSERR;
1244
1764
      goto end;
1245
1765
    }
1246
1766
  }
1247
1767
  ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
1248
1768
  if(ret == -1){
1249
 
    perror("sigaction");
 
1769
    perror_plus("sigaction");
1250
1770
    return EX_OSERR;
1251
1771
  }
1252
1772
  if(old_sigterm_action.sa_handler != SIG_IGN){
1253
1773
    ret = sigaction(SIGHUP, &sigterm_action, NULL);
1254
1774
    if(ret == -1){
1255
 
      perror("sigaction");
 
1775
      perror_plus("sigaction");
1256
1776
      exitcode = EX_OSERR;
1257
1777
      goto end;
1258
1778
    }
1259
1779
  }
1260
1780
  ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
1261
1781
  if(ret == -1){
1262
 
    perror("sigaction");
 
1782
    perror_plus("sigaction");
1263
1783
    return EX_OSERR;
1264
1784
  }
1265
1785
  if(old_sigterm_action.sa_handler != SIG_IGN){
1266
1786
    ret = sigaction(SIGTERM, &sigterm_action, NULL);
1267
1787
    if(ret == -1){
1268
 
      perror("sigaction");
 
1788
      perror_plus("sigaction");
1269
1789
      exitcode = EX_OSERR;
1270
1790
      goto end;
1271
1791
    }
1272
1792
  }
1273
1793
  
1274
1794
  /* If the interface is down, bring it up */
1275
 
  if(interface[0] != '\0'){
 
1795
  if(strcmp(interface, "none") != 0){
1276
1796
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1277
1797
    if(if_index == 0){
1278
1798
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
1288
1808
    errno = 0;
1289
1809
    ret = seteuid(0);
1290
1810
    if(ret == -1){
1291
 
      perror("seteuid");
 
1811
      perror_plus("seteuid");
1292
1812
    }
1293
1813
    
1294
1814
#ifdef __linux__
1298
1818
    bool restore_loglevel = true;
1299
1819
    if(ret == -1){
1300
1820
      restore_loglevel = false;
1301
 
      perror("klogctl");
 
1821
      perror_plus("klogctl");
1302
1822
    }
1303
1823
#endif  /* __linux__ */
1304
1824
    
1305
1825
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1306
1826
    if(sd < 0){
1307
 
      perror("socket");
 
1827
      perror_plus("socket");
1308
1828
      exitcode = EX_OSERR;
1309
1829
#ifdef __linux__
1310
1830
      if(restore_loglevel){
1311
1831
        ret = klogctl(7, NULL, 0);
1312
1832
        if(ret == -1){
1313
 
          perror("klogctl");
 
1833
          perror_plus("klogctl");
1314
1834
        }
1315
1835
      }
1316
1836
#endif  /* __linux__ */
1318
1838
      errno = 0;
1319
1839
      ret = seteuid(uid);
1320
1840
      if(ret == -1){
1321
 
        perror("seteuid");
 
1841
        perror_plus("seteuid");
1322
1842
      }
1323
1843
      goto end;
1324
1844
    }
1325
1845
    strcpy(network.ifr_name, interface);
1326
1846
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
1327
1847
    if(ret == -1){
1328
 
      perror("ioctl SIOCGIFFLAGS");
 
1848
      perror_plus("ioctl SIOCGIFFLAGS");
1329
1849
#ifdef __linux__
1330
1850
      if(restore_loglevel){
1331
1851
        ret = klogctl(7, NULL, 0);
1332
1852
        if(ret == -1){
1333
 
          perror("klogctl");
 
1853
          perror_plus("klogctl");
1334
1854
        }
1335
1855
      }
1336
1856
#endif  /* __linux__ */
1339
1859
      errno = 0;
1340
1860
      ret = seteuid(uid);
1341
1861
      if(ret == -1){
1342
 
        perror("seteuid");
 
1862
        perror_plus("seteuid");
1343
1863
      }
1344
1864
      goto end;
1345
1865
    }
1349
1869
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1350
1870
      if(ret == -1){
1351
1871
        take_down_interface = false;
1352
 
        perror("ioctl SIOCSIFFLAGS");
 
1872
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1353
1873
        exitcode = EX_OSERR;
1354
1874
#ifdef __linux__
1355
1875
        if(restore_loglevel){
1356
1876
          ret = klogctl(7, NULL, 0);
1357
1877
          if(ret == -1){
1358
 
            perror("klogctl");
 
1878
            perror_plus("klogctl");
1359
1879
          }
1360
1880
        }
1361
1881
#endif  /* __linux__ */
1363
1883
        errno = 0;
1364
1884
        ret = seteuid(uid);
1365
1885
        if(ret == -1){
1366
 
          perror("seteuid");
 
1886
          perror_plus("seteuid");
1367
1887
        }
1368
1888
        goto end;
1369
1889
      }
1370
1890
    }
1371
 
    /* sleep checking until interface is running */
 
1891
    /* Sleep checking until interface is running.
 
1892
       Check every 0.25s, up to total time of delay */
1372
1893
    for(int i=0; i < delay * 4; i++){
1373
1894
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1374
1895
      if(ret == -1){
1375
 
        perror("ioctl SIOCGIFFLAGS");
 
1896
        perror_plus("ioctl SIOCGIFFLAGS");
1376
1897
      } else if(network.ifr_flags & IFF_RUNNING){
1377
1898
        break;
1378
1899
      }
1379
1900
      struct timespec sleeptime = { .tv_nsec = 250000000 };
1380
1901
      ret = nanosleep(&sleeptime, NULL);
1381
1902
      if(ret == -1 and errno != EINTR){
1382
 
        perror("nanosleep");
 
1903
        perror_plus("nanosleep");
1383
1904
      }
1384
1905
    }
1385
1906
    if(not take_down_interface){
1386
1907
      /* We won't need the socket anymore */
1387
1908
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1388
1909
      if(ret == -1){
1389
 
        perror("close");
 
1910
        perror_plus("close");
1390
1911
      }
1391
1912
    }
1392
1913
#ifdef __linux__
1394
1915
      /* Restores kernel loglevel to default */
1395
1916
      ret = klogctl(7, NULL, 0);
1396
1917
      if(ret == -1){
1397
 
        perror("klogctl");
 
1918
        perror_plus("klogctl");
1398
1919
      }
1399
1920
    }
1400
1921
#endif  /* __linux__ */
1404
1925
      /* Lower privileges */
1405
1926
      ret = seteuid(uid);
1406
1927
      if(ret == -1){
1407
 
        perror("seteuid");
 
1928
        perror_plus("seteuid");
1408
1929
      }
1409
1930
    } else {
1410
1931
      /* Lower privileges permanently */
1411
1932
      ret = setuid(uid);
1412
1933
      if(ret == -1){
1413
 
        perror("setuid");
 
1934
        perror_plus("setuid");
1414
1935
      }
1415
1936
    }
1416
1937
  }
1432
1953
    goto end;
1433
1954
  }
1434
1955
  
 
1956
  if(mkdtemp(tempdir) == NULL){
 
1957
    perror_plus("mkdtemp");
 
1958
    goto end;
 
1959
  }
1435
1960
  tempdir_created = true;
1436
 
  if(mkdtemp(tempdir) == NULL){
1437
 
    tempdir_created = false;
1438
 
    perror("mkdtemp");
1439
 
    goto end;
1440
 
  }
1441
1961
  
1442
1962
  if(quit_now){
1443
1963
    goto end;
1485
2005
    
1486
2006
    port = (uint16_t)tmpmax;
1487
2007
    *address = '\0';
1488
 
    address = connect_to;
1489
2008
    /* Colon in address indicates IPv6 */
1490
2009
    int af;
1491
 
    if(strchr(address, ':') != NULL){
 
2010
    if(strchr(connect_to, ':') != NULL){
1492
2011
      af = AF_INET6;
 
2012
      /* Accept [] around IPv6 address - see RFC 5952 */
 
2013
      if(connect_to[0] == '[' and address[-1] == ']')
 
2014
        {
 
2015
          connect_to++;
 
2016
          address[-1] = '\0';
 
2017
        }
1493
2018
    } else {
1494
2019
      af = AF_INET;
1495
2020
    }
 
2021
    address = connect_to;
1496
2022
    
1497
2023
    if(quit_now){
1498
2024
      goto end;
1499
2025
    }
1500
2026
    
1501
 
    ret = start_mandos_communication(address, port, if_index, af);
1502
 
    if(ret < 0){
1503
 
      switch(errno){
1504
 
      case ENETUNREACH:
1505
 
      case EHOSTDOWN:
1506
 
      case EHOSTUNREACH:
1507
 
        exitcode = EX_NOHOST;
1508
 
        break;
1509
 
      case EINVAL:
1510
 
        exitcode = EX_USAGE;
1511
 
        break;
1512
 
      case EIO:
1513
 
        exitcode = EX_IOERR;
1514
 
        break;
1515
 
      case EPROTO:
1516
 
        exitcode = EX_PROTOCOL;
1517
 
        break;
1518
 
      default:
1519
 
        exitcode = EX_OSERR;
1520
 
        break;
1521
 
      }
1522
 
    } else {
 
2027
    while(not quit_now){
 
2028
      ret = start_mandos_communication(address, port, if_index, af);
 
2029
      if(quit_now or ret == 0){
 
2030
        break;
 
2031
      }
 
2032
      if(debug){
 
2033
        fprintf(stderr, "Retrying in %d seconds\n",
 
2034
                (int)retry_interval);
 
2035
      }
 
2036
      sleep((int)retry_interval);
 
2037
    }
 
2038
    
 
2039
    if (not quit_now){
1523
2040
      exitcode = EXIT_SUCCESS;
1524
2041
    }
 
2042
    
1525
2043
    goto end;
1526
2044
  }
1527
2045
  
1579
2097
  if(debug){
1580
2098
    fprintf(stderr, "Starting Avahi loop search\n");
1581
2099
  }
1582
 
  
1583
 
  avahi_simple_poll_loop(mc.simple_poll);
 
2100
 
 
2101
  ret = avahi_loop_with_timeout(mc.simple_poll,
 
2102
                                (int)(retry_interval * 1000));
 
2103
  if(debug){
 
2104
    fprintf(stderr, "avahi_loop_with_timeout exited %s\n",
 
2105
            (ret == 0) ? "successfully" : "with error");
 
2106
  }
1584
2107
  
1585
2108
 end:
1586
2109
  
1607
2130
  if(gpgme_initialized){
1608
2131
    gpgme_release(mc.ctx);
1609
2132
  }
 
2133
 
 
2134
  /* Cleans up the circular linked list of Mandos servers the client
 
2135
     has seen */
 
2136
  if(mc.current_server != NULL){
 
2137
    mc.current_server->prev->next = NULL;
 
2138
    while(mc.current_server != NULL){
 
2139
      server *next = mc.current_server->next;
 
2140
      free(mc.current_server);
 
2141
      mc.current_server = next;
 
2142
    }
 
2143
  }
 
2144
  
 
2145
  /* XXX run network hooks "stop" here  */
1610
2146
  
1611
2147
  /* Take down the network interface */
1612
2148
  if(take_down_interface){
1614
2150
    errno = 0;
1615
2151
    ret = seteuid(0);
1616
2152
    if(ret == -1){
1617
 
      perror("seteuid");
 
2153
      perror_plus("seteuid");
1618
2154
    }
1619
2155
    if(geteuid() == 0){
1620
2156
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1621
2157
      if(ret == -1){
1622
 
        perror("ioctl SIOCGIFFLAGS");
 
2158
        perror_plus("ioctl SIOCGIFFLAGS");
1623
2159
      } else if(network.ifr_flags & IFF_UP) {
1624
2160
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
1625
2161
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
1626
2162
        if(ret == -1){
1627
 
          perror("ioctl SIOCSIFFLAGS");
 
2163
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
1628
2164
        }
1629
2165
      }
1630
2166
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1631
2167
      if(ret == -1){
1632
 
        perror("close");
 
2168
        perror_plus("close");
1633
2169
      }
1634
2170
      /* Lower privileges permanently */
1635
2171
      errno = 0;
1636
2172
      ret = setuid(uid);
1637
2173
      if(ret == -1){
1638
 
        perror("setuid");
 
2174
        perror_plus("setuid");
1639
2175
      }
1640
2176
    }
1641
2177
  }
1642
2178
  
1643
 
  /* Removes the temp directory used by GPGME */
 
2179
  /* Removes the GPGME temp directory and all files inside */
1644
2180
  if(tempdir_created){
1645
 
    DIR *d;
1646
 
    struct dirent *direntry;
1647
 
    d = opendir(tempdir);
1648
 
    if(d == NULL){
1649
 
      if(errno != ENOENT){
1650
 
        perror("opendir");
1651
 
      }
1652
 
    } else {
1653
 
      while(true){
1654
 
        direntry = readdir(d);
1655
 
        if(direntry == NULL){
1656
 
          break;
1657
 
        }
1658
 
        /* Skip "." and ".." */
1659
 
        if(direntry->d_name[0] == '.'
1660
 
           and (direntry->d_name[1] == '\0'
1661
 
                or (direntry->d_name[1] == '.'
1662
 
                    and direntry->d_name[2] == '\0'))){
1663
 
          continue;
1664
 
        }
 
2181
    struct dirent **direntries = NULL;
 
2182
    struct dirent *direntry = NULL;
 
2183
    int numentries = scandir(tempdir, &direntries, notdotentries,
 
2184
                             alphasort);
 
2185
    if (numentries > 0){
 
2186
      for(int i = 0; i < numentries; i++){
 
2187
        direntry = direntries[i];
1665
2188
        char *fullname = NULL;
1666
2189
        ret = asprintf(&fullname, "%s/%s", tempdir,
1667
2190
                       direntry->d_name);
1668
2191
        if(ret < 0){
1669
 
          perror("asprintf");
 
2192
          perror_plus("asprintf");
1670
2193
          continue;
1671
2194
        }
1672
2195
        ret = remove(fullname);
1676
2199
        }
1677
2200
        free(fullname);
1678
2201
      }
1679
 
      closedir(d);
 
2202
    }
 
2203
 
 
2204
    /* need to clean even if 0 because man page doesn't specify */
 
2205
    free(direntries);
 
2206
    if (numentries == -1){
 
2207
      perror_plus("scandir");
1680
2208
    }
1681
2209
    ret = rmdir(tempdir);
1682
2210
    if(ret == -1 and errno != ENOENT){
1683
 
      perror("rmdir");
 
2211
      perror_plus("rmdir");
1684
2212
    }
1685
2213
  }
1686
2214
  
1691
2219
                                            &old_sigterm_action,
1692
2220
                                            NULL));
1693
2221
    if(ret == -1){
1694
 
      perror("sigaction");
 
2222
      perror_plus("sigaction");
1695
2223
    }
1696
2224
    do {
1697
2225
      ret = raise(signal_received);
1698
2226
    } while(ret != 0 and errno == EINTR);
1699
2227
    if(ret != 0){
1700
 
      perror("raise");
 
2228
      perror_plus("raise");
1701
2229
      abort();
1702
2230
    }
1703
2231
    TEMP_FAILURE_RETRY(pause());