/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: Björn Påhlsson
  • Date: 2011-10-02 19:18:24 UTC
  • mto: This revision was merged to the branch mainline in revision 505.
  • Revision ID: belorn@fukt.bsnet.se-20111002191824-eweh4pvneeg3qzia
transitional stuff actually working
documented change to D-Bus API

Show diffs side-by-side

added added

removed removed

Lines of Context:
62
62
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
63
63
                                   strtoimax() */
64
64
#include <assert.h>             /* assert() */
65
 
#include <errno.h>              /* perror(), errno */
 
65
#include <errno.h>              /* perror(), errno,
 
66
                                   program_invocation_short_name */
66
67
#include <time.h>               /* nanosleep(), time(), sleep() */
67
68
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
68
69
                                   SIOCSIFFLAGS, if_indextoname(),
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,
130
131
static const char sys_class_net[] = "/sys/class/net";
131
132
char *connect_to = NULL;
132
133
 
 
134
/* Doubly linked list that need to be circularly linked when used */
 
135
typedef struct server{
 
136
  const char *ip;
 
137
  uint16_t port;
 
138
  AvahiIfIndex if_index;
 
139
  int af;
 
140
  struct timespec last_seen;
 
141
  struct server *next;
 
142
  struct server *prev;
 
143
} server;
 
144
 
133
145
/* Used for passing in values through the Avahi callback functions */
134
146
typedef struct {
135
147
  AvahiSimplePoll *simple_poll;
139
151
  gnutls_dh_params_t dh_params;
140
152
  const char *priority;
141
153
  gpgme_ctx_t ctx;
 
154
  server *current_server;
142
155
} mandos_context;
143
156
 
144
157
/* global context so signal handler can reach it*/
145
158
mandos_context mc = { .simple_poll = NULL, .server = NULL,
146
159
                      .dh_bits = 1024, .priority = "SECURE256"
147
 
                      ":!CTYPE-X.509:+CTYPE-OPENPGP" };
 
160
                      ":!CTYPE-X.509:+CTYPE-OPENPGP",
 
161
                      .current_server = NULL };
148
162
 
149
163
sig_atomic_t quit_now = 0;
150
164
int signal_received = 0;
151
165
 
 
166
/* Function to use when printing errors */
 
167
void perror_plus(const char *print_text){
 
168
  fprintf(stderr, "Mandos plugin %s: ",
 
169
          program_invocation_short_name);
 
170
  perror(print_text);
 
171
}
 
172
 
152
173
/*
153
174
 * Make additional room in "buffer" for at least BUFFER_SIZE more
154
175
 * bytes. "buffer_capacity" is how much is currently allocated,
166
187
  return buffer_capacity;
167
188
}
168
189
 
 
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
 
169
228
/* 
170
229
 * Initialize GPGME.
171
230
 */
185
244
    
186
245
    fd = (int)TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
187
246
    if(fd == -1){
188
 
      perror("open");
 
247
      perror_plus("open");
189
248
      return false;
190
249
    }
191
250
    
205
264
    
206
265
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
207
266
    if(ret == -1){
208
 
      perror("close");
 
267
      perror_plus("close");
209
268
    }
210
269
    gpgme_data_release(pgp_data);
211
270
    return true;
224
283
    return false;
225
284
  }
226
285
  
227
 
    /* Set GPGME home directory for the OpenPGP engine only */
 
286
  /* Set GPGME home directory for the OpenPGP engine only */
228
287
  rc = gpgme_get_engine_info(&engine_info);
229
288
  if(rc != GPG_ERR_NO_ERROR){
230
289
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
336
395
  
337
396
  /* Seek back to the beginning of the GPGME plaintext data buffer */
338
397
  if(gpgme_data_seek(dh_plain, (off_t)0, SEEK_SET) == -1){
339
 
    perror("gpgme_data_seek");
 
398
    perror_plus("gpgme_data_seek");
340
399
    plaintext_length = -1;
341
400
    goto decrypt_end;
342
401
  }
347
406
                                      (size_t)plaintext_length,
348
407
                                      plaintext_capacity);
349
408
    if(plaintext_capacity == 0){
350
 
        perror("incbuffer");
 
409
        perror_plus("incbuffer");
351
410
        plaintext_length = -1;
352
411
        goto decrypt_end;
353
412
    }
360
419
      break;
361
420
    }
362
421
    if(ret < 0){
363
 
      perror("gpgme_data_read");
 
422
      perror_plus("gpgme_data_read");
364
423
      plaintext_length = -1;
365
424
      goto decrypt_end;
366
425
    }
423
482
  }
424
483
  
425
484
  /* OpenPGP credentials */
426
 
  gnutls_certificate_allocate_credentials(&mc.cred);
 
485
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
427
486
  if(ret != GNUTLS_E_SUCCESS){
428
 
    fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning
429
 
                                                    from
430
 
                                                    -Wunreachable-code
431
 
                                                 */
 
487
    fprintf(stderr, "GnuTLS memory error: %s\n",
432
488
            safer_gnutls_strerror(ret));
433
489
    gnutls_global_deinit();
434
490
    return -1;
589
645
  tcp_sd = socket(pf, SOCK_STREAM, 0);
590
646
  if(tcp_sd < 0){
591
647
    int e = errno;
592
 
    perror("socket");
 
648
    perror_plus("socket");
593
649
    errno = e;
594
650
    goto mandos_end;
595
651
  }
609
665
  }
610
666
  if(ret < 0 ){
611
667
    int e = errno;
612
 
    perror("inet_pton");
 
668
    perror_plus("inet_pton");
613
669
    errno = e;
614
670
    goto mandos_end;
615
671
  }
651
707
    if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
652
708
      char interface[IF_NAMESIZE];
653
709
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
654
 
        perror("if_indextoname");
 
710
        perror_plus("if_indextoname");
655
711
      } else {
656
712
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
657
713
                ip, interface, port);
671
727
                        sizeof(addrstr));
672
728
    }
673
729
    if(pcret == NULL){
674
 
      perror("inet_ntop");
 
730
      perror_plus("inet_ntop");
675
731
    } else {
676
732
      if(strcmp(addrstr, ip) != 0){
677
733
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
692
748
  if(ret < 0){
693
749
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
694
750
      int e = errno;
695
 
      perror("connect");
 
751
      perror_plus("connect");
696
752
      errno = e;
697
753
    }
698
754
    goto mandos_end;
711
767
                                   out_size - written));
712
768
    if(ret == -1){
713
769
      int e = errno;
714
 
      perror("write");
 
770
      perror_plus("write");
715
771
      errno = e;
716
772
      goto mandos_end;
717
773
    }
742
798
    goto mandos_end;
743
799
  }
744
800
  
 
801
  /* Spurious warning from -Wint-to-pointer-cast */
745
802
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
746
803
  
747
804
  if(quit_now){
784
841
                                   buffer_capacity);
785
842
    if(buffer_capacity == 0){
786
843
      int e = errno;
787
 
      perror("incbuffer");
 
844
      perror_plus("incbuffer");
788
845
      errno = e;
789
846
      goto mandos_end;
790
847
    }
895
952
      if(e == 0){
896
953
        e = errno;
897
954
      }
898
 
      perror("close");
 
955
      perror_plus("close");
899
956
    }
900
957
    gnutls_deinit(session);
 
958
    errno = e;
901
959
    if(quit_now){
902
 
      e = EINTR;
 
960
      errno = EINTR;
903
961
      retval = -1;
904
962
    }
905
 
    errno = e;
906
963
  }
907
964
  return retval;
908
965
}
951
1008
                                           avahi_proto_to_af(proto));
952
1009
      if(ret == 0){
953
1010
        avahi_simple_poll_quit(mc.simple_poll);
 
1011
      } else {
 
1012
        ret = add_server(ip, port, interface,
 
1013
                         avahi_proto_to_af(proto));
954
1014
      }
955
1015
    }
956
1016
  }
1010
1070
  }
1011
1071
}
1012
1072
 
1013
 
/* stop main loop after sigterm has been called */
 
1073
/* Signal handler that stops main loop after SIGTERM */
1014
1074
static void handle_sigterm(int sig){
1015
1075
  if(quit_now){
1016
1076
    return;
1018
1078
  quit_now = 1;
1019
1079
  signal_received = sig;
1020
1080
  int old_errno = errno;
 
1081
  /* set main loop to exit */
1021
1082
  if(mc.simple_poll != NULL){
1022
1083
    avahi_simple_poll_quit(mc.simple_poll);
1023
1084
  }
1032
1093
int good_interface(const struct dirent *if_entry){
1033
1094
  ssize_t ssret;
1034
1095
  char *flagname = NULL;
 
1096
  if(if_entry->d_name[0] == '.'){
 
1097
    return 0;
 
1098
  }
1035
1099
  int ret = asprintf(&flagname, "%s/%s/flags", sys_class_net,
1036
1100
                     if_entry->d_name);
1037
1101
  if(ret < 0){
1038
 
    perror("asprintf");
1039
 
    return 0;
1040
 
  }
1041
 
  if(if_entry->d_name[0] == '.'){
 
1102
    perror_plus("asprintf");
1042
1103
    return 0;
1043
1104
  }
1044
1105
  int flags_fd = (int)TEMP_FAILURE_RETRY(open(flagname, O_RDONLY));
1045
1106
  if(flags_fd == -1){
1046
 
    perror("open");
 
1107
    perror_plus("open");
 
1108
    free(flagname);
1047
1109
    return 0;
1048
1110
  }
 
1111
  free(flagname);
1049
1112
  typedef short ifreq_flags;    /* ifreq.ifr_flags in netdevice(7) */
1050
1113
  /* read line from flags_fd */
1051
 
  ssize_t to_read = (sizeof(ifreq_flags)*2)+3; /* "0x1003\n" */
 
1114
  ssize_t to_read = 2+(sizeof(ifreq_flags)*2)+1; /* "0x1003\n" */
1052
1115
  char *flagstring = malloc((size_t)to_read+1); /* +1 for final \0 */
1053
1116
  flagstring[(size_t)to_read] = '\0';
1054
1117
  if(flagstring == NULL){
1055
 
    perror("malloc");
 
1118
    perror_plus("malloc");
1056
1119
    close(flags_fd);
1057
1120
    return 0;
1058
1121
  }
1060
1123
    ssret = (ssize_t)TEMP_FAILURE_RETRY(read(flags_fd, flagstring,
1061
1124
                                             (size_t)to_read));
1062
1125
    if(ssret == -1){
1063
 
      perror("read");
 
1126
      perror_plus("read");
1064
1127
      free(flagstring);
1065
1128
      close(flags_fd);
1066
1129
      return 0;
1111
1174
    }
1112
1175
    return 0;
1113
1176
  }
 
1177
  /* Reject non-ARP interfaces (including dummy interfaces) */
 
1178
  if(flags & IFF_NOARP){
 
1179
    if(debug){
 
1180
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n",
 
1181
              if_entry->d_name);
 
1182
    }
 
1183
    return 0;
 
1184
  }
1114
1185
  /* Accept this device */
1115
1186
  if(debug){
1116
1187
    fprintf(stderr, "Interface \"%s\" is acceptable\n",
1119
1190
  return 1;
1120
1191
}
1121
1192
 
 
1193
int notdotentries(const struct dirent *direntry){
 
1194
  /* Skip "." and ".." */
 
1195
  if(direntry->d_name[0] == '.'
 
1196
     and (direntry->d_name[1] == '\0'
 
1197
          or (direntry->d_name[1] == '.'
 
1198
              and direntry->d_name[2] == '\0'))){
 
1199
    return 0;
 
1200
  }
 
1201
  return 1;
 
1202
}
 
1203
 
 
1204
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
 
1205
  int ret;
 
1206
  struct timespec now;
 
1207
  struct timespec waited_time;
 
1208
  intmax_t block_time;
 
1209
  
 
1210
  while(true){
 
1211
    if(mc.current_server == NULL){
 
1212
      if (debug){
 
1213
        fprintf(stderr,
 
1214
                "Wait until first server is found. No timeout!\n");
 
1215
      }
 
1216
      ret = avahi_simple_poll_iterate(s, -1);
 
1217
    } else {
 
1218
      if (debug){
 
1219
        fprintf(stderr, "Check current_server if we should run it,"
 
1220
                " or wait\n");
 
1221
      }
 
1222
      /* the current time */
 
1223
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
 
1224
      if(ret == -1){
 
1225
        perror_plus("clock_gettime");
 
1226
        return -1;
 
1227
      }
 
1228
      /* Calculating in ms how long time between now and server
 
1229
         who we visted longest time ago. Now - last seen.  */
 
1230
      waited_time.tv_sec = (now.tv_sec
 
1231
                            - mc.current_server->last_seen.tv_sec);
 
1232
      waited_time.tv_nsec = (now.tv_nsec
 
1233
                             - mc.current_server->last_seen.tv_nsec);
 
1234
      /* total time is 10s/10,000ms.
 
1235
         Converting to s from ms by dividing by 1,000,
 
1236
         and ns to ms by dividing by 1,000,000. */
 
1237
      block_time = ((retry_interval
 
1238
                     - ((intmax_t)waited_time.tv_sec * 1000))
 
1239
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
 
1240
      
 
1241
      if (debug){
 
1242
        fprintf(stderr, "Blocking for %" PRIdMAX " ms\n", block_time);
 
1243
      }
 
1244
      
 
1245
      if(block_time <= 0){
 
1246
        ret = start_mandos_communication(mc.current_server->ip,
 
1247
                                         mc.current_server->port,
 
1248
                                         mc.current_server->if_index,
 
1249
                                         mc.current_server->af);
 
1250
        if(ret == 0){
 
1251
          avahi_simple_poll_quit(mc.simple_poll);
 
1252
          return 0;
 
1253
        }
 
1254
        ret = clock_gettime(CLOCK_MONOTONIC,
 
1255
                            &mc.current_server->last_seen);
 
1256
        if(ret == -1){
 
1257
          perror_plus("clock_gettime");
 
1258
          return -1;
 
1259
        }
 
1260
        mc.current_server = mc.current_server->next;
 
1261
        block_time = 0;         /* Call avahi to find new Mandos
 
1262
                                   servers, but don't block */
 
1263
      }
 
1264
      
 
1265
      ret = avahi_simple_poll_iterate(s, (int)block_time);
 
1266
    }
 
1267
    if(ret != 0){
 
1268
      if (ret > 0 or errno != EINTR) {
 
1269
        return (ret != 1) ? ret : 0;
 
1270
      }
 
1271
    }
 
1272
  }
 
1273
}
 
1274
 
1122
1275
int main(int argc, char *argv[]){
1123
1276
  AvahiSServiceBrowser *sb = NULL;
1124
1277
  int error;
1141
1294
  bool gnutls_initialized = false;
1142
1295
  bool gpgme_initialized = false;
1143
1296
  float delay = 2.5f;
 
1297
  double retry_interval = 10; /* 10s between trying a server and
 
1298
                                 retrying the same server again */
1144
1299
  
1145
1300
  struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
1146
1301
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
1152
1307
  errno = 0;
1153
1308
  ret = setgid(gid);
1154
1309
  if(ret == -1){
1155
 
    perror("setgid");
 
1310
    perror_plus("setgid");
1156
1311
  }
1157
1312
  
1158
1313
  /* Lower user privileges (temporarily) */
1159
1314
  errno = 0;
1160
1315
  ret = seteuid(uid);
1161
1316
  if(ret == -1){
1162
 
    perror("seteuid");
 
1317
    perror_plus("seteuid");
1163
1318
  }
1164
1319
  
1165
1320
  if(quit_now){
1200
1355
        .arg = "SECONDS",
1201
1356
        .doc = "Maximum delay to wait for interface startup",
1202
1357
        .group = 2 },
 
1358
      { .name = "retry", .key = 132,
 
1359
        .arg = "SECONDS",
 
1360
        .doc = "Retry interval used when denied by the mandos server",
 
1361
        .group = 2 },
1203
1362
      /*
1204
1363
       * These reproduce what we would get without ARGP_NO_HELP
1205
1364
       */
1249
1408
        if(errno != 0 or tmp == arg or *tmp != '\0'){
1250
1409
          argp_error(state, "Bad delay");
1251
1410
        }
 
1411
      case 132:                 /* --retry */
 
1412
        errno = 0;
 
1413
        retry_interval = strtod(arg, &tmp);
 
1414
        if(errno != 0 or tmp == arg or *tmp != '\0'
 
1415
           or (retry_interval * 1000) > INT_MAX
 
1416
           or retry_interval < 0){
 
1417
          argp_error(state, "Bad retry interval");
 
1418
        }
1252
1419
        break;
1253
1420
        /*
1254
1421
         * These reproduce what we would get without ARGP_NO_HELP
1282
1449
    case ENOMEM:
1283
1450
    default:
1284
1451
      errno = ret;
1285
 
      perror("argp_parse");
 
1452
      perror_plus("argp_parse");
1286
1453
      exitcode = EX_OSERR;
1287
1454
      goto end;
1288
1455
    case EINVAL:
1290
1457
      goto end;
1291
1458
    }
1292
1459
  }
 
1460
    
 
1461
  {
 
1462
    /* Work around Debian bug #633582:
 
1463
       <http://bugs.debian.org/633582> */
 
1464
    struct stat st;
 
1465
    
 
1466
    /* Re-raise priviliges */
 
1467
    errno = 0;
 
1468
    ret = seteuid(0);
 
1469
    if(ret == -1){
 
1470
      perror_plus("seteuid");
 
1471
    }
 
1472
    
 
1473
    if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
 
1474
      int seckey_fd = open(seckey, O_RDONLY);
 
1475
      if(seckey_fd == -1){
 
1476
        perror_plus("open");
 
1477
      } else {
 
1478
        ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
 
1479
        if(ret == -1){
 
1480
          perror_plus("fstat");
 
1481
        } else {
 
1482
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
 
1483
            ret = fchown(seckey_fd, uid, gid);
 
1484
            if(ret == -1){
 
1485
              perror_plus("fchown");
 
1486
            }
 
1487
          }
 
1488
        }
 
1489
        TEMP_FAILURE_RETRY(close(seckey_fd));
 
1490
      }
 
1491
    }
 
1492
    
 
1493
    if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
 
1494
      int pubkey_fd = open(pubkey, O_RDONLY);
 
1495
      if(pubkey_fd == -1){
 
1496
        perror_plus("open");
 
1497
      } else {
 
1498
        ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
 
1499
        if(ret == -1){
 
1500
          perror_plus("fstat");
 
1501
        } else {
 
1502
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
 
1503
            ret = fchown(pubkey_fd, uid, gid);
 
1504
            if(ret == -1){
 
1505
              perror_plus("fchown");
 
1506
            }
 
1507
          }
 
1508
        }
 
1509
        TEMP_FAILURE_RETRY(close(pubkey_fd));
 
1510
      }
 
1511
    }
 
1512
    
 
1513
    /* Lower privileges */
 
1514
    errno = 0;
 
1515
    ret = seteuid(uid);
 
1516
    if(ret == -1){
 
1517
      perror_plus("seteuid");
 
1518
    }
 
1519
  }
1293
1520
  
1294
1521
  if(not debug){
1295
1522
    avahi_set_log_function(empty_log);
1306
1533
        fprintf(stderr, "Using interface \"%s\"\n", interface);
1307
1534
      }
1308
1535
      if(interface == NULL){
1309
 
        perror("malloc");
 
1536
        perror_plus("malloc");
1310
1537
        free(direntries);
1311
1538
        exitcode = EXIT_FAILURE;
1312
1539
        goto end;
1334
1561
  sigemptyset(&sigterm_action.sa_mask);
1335
1562
  ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
1336
1563
  if(ret == -1){
1337
 
    perror("sigaddset");
 
1564
    perror_plus("sigaddset");
1338
1565
    exitcode = EX_OSERR;
1339
1566
    goto end;
1340
1567
  }
1341
1568
  ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
1342
1569
  if(ret == -1){
1343
 
    perror("sigaddset");
 
1570
    perror_plus("sigaddset");
1344
1571
    exitcode = EX_OSERR;
1345
1572
    goto end;
1346
1573
  }
1347
1574
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
1348
1575
  if(ret == -1){
1349
 
    perror("sigaddset");
 
1576
    perror_plus("sigaddset");
1350
1577
    exitcode = EX_OSERR;
1351
1578
    goto end;
1352
1579
  }
1356
1583
  */
1357
1584
  ret = sigaction(SIGINT, NULL, &old_sigterm_action);
1358
1585
  if(ret == -1){
1359
 
    perror("sigaction");
 
1586
    perror_plus("sigaction");
1360
1587
    return EX_OSERR;
1361
1588
  }
1362
1589
  if(old_sigterm_action.sa_handler != SIG_IGN){
1363
1590
    ret = sigaction(SIGINT, &sigterm_action, NULL);
1364
1591
    if(ret == -1){
1365
 
      perror("sigaction");
 
1592
      perror_plus("sigaction");
1366
1593
      exitcode = EX_OSERR;
1367
1594
      goto end;
1368
1595
    }
1369
1596
  }
1370
1597
  ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
1371
1598
  if(ret == -1){
1372
 
    perror("sigaction");
 
1599
    perror_plus("sigaction");
1373
1600
    return EX_OSERR;
1374
1601
  }
1375
1602
  if(old_sigterm_action.sa_handler != SIG_IGN){
1376
1603
    ret = sigaction(SIGHUP, &sigterm_action, NULL);
1377
1604
    if(ret == -1){
1378
 
      perror("sigaction");
 
1605
      perror_plus("sigaction");
1379
1606
      exitcode = EX_OSERR;
1380
1607
      goto end;
1381
1608
    }
1382
1609
  }
1383
1610
  ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
1384
1611
  if(ret == -1){
1385
 
    perror("sigaction");
 
1612
    perror_plus("sigaction");
1386
1613
    return EX_OSERR;
1387
1614
  }
1388
1615
  if(old_sigterm_action.sa_handler != SIG_IGN){
1389
1616
    ret = sigaction(SIGTERM, &sigterm_action, NULL);
1390
1617
    if(ret == -1){
1391
 
      perror("sigaction");
 
1618
      perror_plus("sigaction");
1392
1619
      exitcode = EX_OSERR;
1393
1620
      goto end;
1394
1621
    }
1411
1638
    errno = 0;
1412
1639
    ret = seteuid(0);
1413
1640
    if(ret == -1){
1414
 
      perror("seteuid");
 
1641
      perror_plus("seteuid");
1415
1642
    }
1416
1643
    
1417
1644
#ifdef __linux__
1421
1648
    bool restore_loglevel = true;
1422
1649
    if(ret == -1){
1423
1650
      restore_loglevel = false;
1424
 
      perror("klogctl");
 
1651
      perror_plus("klogctl");
1425
1652
    }
1426
1653
#endif  /* __linux__ */
1427
1654
    
1428
1655
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1429
1656
    if(sd < 0){
1430
 
      perror("socket");
 
1657
      perror_plus("socket");
1431
1658
      exitcode = EX_OSERR;
1432
1659
#ifdef __linux__
1433
1660
      if(restore_loglevel){
1434
1661
        ret = klogctl(7, NULL, 0);
1435
1662
        if(ret == -1){
1436
 
          perror("klogctl");
 
1663
          perror_plus("klogctl");
1437
1664
        }
1438
1665
      }
1439
1666
#endif  /* __linux__ */
1441
1668
      errno = 0;
1442
1669
      ret = seteuid(uid);
1443
1670
      if(ret == -1){
1444
 
        perror("seteuid");
 
1671
        perror_plus("seteuid");
1445
1672
      }
1446
1673
      goto end;
1447
1674
    }
1448
1675
    strcpy(network.ifr_name, interface);
1449
1676
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
1450
1677
    if(ret == -1){
1451
 
      perror("ioctl SIOCGIFFLAGS");
 
1678
      perror_plus("ioctl SIOCGIFFLAGS");
1452
1679
#ifdef __linux__
1453
1680
      if(restore_loglevel){
1454
1681
        ret = klogctl(7, NULL, 0);
1455
1682
        if(ret == -1){
1456
 
          perror("klogctl");
 
1683
          perror_plus("klogctl");
1457
1684
        }
1458
1685
      }
1459
1686
#endif  /* __linux__ */
1462
1689
      errno = 0;
1463
1690
      ret = seteuid(uid);
1464
1691
      if(ret == -1){
1465
 
        perror("seteuid");
 
1692
        perror_plus("seteuid");
1466
1693
      }
1467
1694
      goto end;
1468
1695
    }
1472
1699
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1473
1700
      if(ret == -1){
1474
1701
        take_down_interface = false;
1475
 
        perror("ioctl SIOCSIFFLAGS +IFF_UP");
 
1702
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1476
1703
        exitcode = EX_OSERR;
1477
1704
#ifdef __linux__
1478
1705
        if(restore_loglevel){
1479
1706
          ret = klogctl(7, NULL, 0);
1480
1707
          if(ret == -1){
1481
 
            perror("klogctl");
 
1708
            perror_plus("klogctl");
1482
1709
          }
1483
1710
        }
1484
1711
#endif  /* __linux__ */
1486
1713
        errno = 0;
1487
1714
        ret = seteuid(uid);
1488
1715
        if(ret == -1){
1489
 
          perror("seteuid");
 
1716
          perror_plus("seteuid");
1490
1717
        }
1491
1718
        goto end;
1492
1719
      }
1493
1720
    }
1494
 
    /* sleep checking until interface is running */
 
1721
    /* Sleep checking until interface is running.
 
1722
       Check every 0.25s, up to total time of delay */
1495
1723
    for(int i=0; i < delay * 4; i++){
1496
1724
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1497
1725
      if(ret == -1){
1498
 
        perror("ioctl SIOCGIFFLAGS");
 
1726
        perror_plus("ioctl SIOCGIFFLAGS");
1499
1727
      } else if(network.ifr_flags & IFF_RUNNING){
1500
1728
        break;
1501
1729
      }
1502
1730
      struct timespec sleeptime = { .tv_nsec = 250000000 };
1503
1731
      ret = nanosleep(&sleeptime, NULL);
1504
1732
      if(ret == -1 and errno != EINTR){
1505
 
        perror("nanosleep");
 
1733
        perror_plus("nanosleep");
1506
1734
      }
1507
1735
    }
1508
1736
    if(not take_down_interface){
1509
1737
      /* We won't need the socket anymore */
1510
1738
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1511
1739
      if(ret == -1){
1512
 
        perror("close");
 
1740
        perror_plus("close");
1513
1741
      }
1514
1742
    }
1515
1743
#ifdef __linux__
1517
1745
      /* Restores kernel loglevel to default */
1518
1746
      ret = klogctl(7, NULL, 0);
1519
1747
      if(ret == -1){
1520
 
        perror("klogctl");
 
1748
        perror_plus("klogctl");
1521
1749
      }
1522
1750
    }
1523
1751
#endif  /* __linux__ */
1527
1755
      /* Lower privileges */
1528
1756
      ret = seteuid(uid);
1529
1757
      if(ret == -1){
1530
 
        perror("seteuid");
 
1758
        perror_plus("seteuid");
1531
1759
      }
1532
1760
    } else {
1533
1761
      /* Lower privileges permanently */
1534
1762
      ret = setuid(uid);
1535
1763
      if(ret == -1){
1536
 
        perror("setuid");
 
1764
        perror_plus("setuid");
1537
1765
      }
1538
1766
    }
1539
1767
  }
1555
1783
    goto end;
1556
1784
  }
1557
1785
  
 
1786
  if(mkdtemp(tempdir) == NULL){
 
1787
    perror_plus("mkdtemp");
 
1788
    goto end;
 
1789
  }
1558
1790
  tempdir_created = true;
1559
 
  if(mkdtemp(tempdir) == NULL){
1560
 
    tempdir_created = false;
1561
 
    perror("mkdtemp");
1562
 
    goto end;
1563
 
  }
1564
1791
  
1565
1792
  if(quit_now){
1566
1793
    goto end;
1608
1835
    
1609
1836
    port = (uint16_t)tmpmax;
1610
1837
    *address = '\0';
1611
 
    address = connect_to;
1612
1838
    /* Colon in address indicates IPv6 */
1613
1839
    int af;
1614
 
    if(strchr(address, ':') != NULL){
 
1840
    if(strchr(connect_to, ':') != NULL){
1615
1841
      af = AF_INET6;
 
1842
      /* Accept [] around IPv6 address - see RFC 5952 */
 
1843
      if(connect_to[0] == '[' and address[-1] == ']')
 
1844
        {
 
1845
          connect_to++;
 
1846
          address[-1] = '\0';
 
1847
        }
1616
1848
    } else {
1617
1849
      af = AF_INET;
1618
1850
    }
 
1851
    address = connect_to;
1619
1852
    
1620
1853
    if(quit_now){
1621
1854
      goto end;
1622
1855
    }
1623
 
 
 
1856
    
1624
1857
    while(not quit_now){
1625
1858
      ret = start_mandos_communication(address, port, if_index, af);
1626
1859
      if(quit_now or ret == 0){
1627
1860
        break;
1628
1861
      }
1629
 
      sleep(15);
1630
 
    };
1631
 
 
 
1862
      if(debug){
 
1863
        fprintf(stderr, "Retrying in %d seconds\n",
 
1864
                (int)retry_interval);
 
1865
      }
 
1866
      sleep((int)retry_interval);
 
1867
    }
 
1868
    
1632
1869
    if (not quit_now){
1633
1870
      exitcode = EXIT_SUCCESS;
1634
1871
    }
1690
1927
  if(debug){
1691
1928
    fprintf(stderr, "Starting Avahi loop search\n");
1692
1929
  }
1693
 
  
1694
 
  avahi_simple_poll_loop(mc.simple_poll);
 
1930
 
 
1931
  ret = avahi_loop_with_timeout(mc.simple_poll,
 
1932
                                (int)(retry_interval * 1000));
 
1933
  if(debug){
 
1934
    fprintf(stderr, "avahi_loop_with_timeout exited %s\n",
 
1935
            (ret == 0) ? "successfully" : "with error");
 
1936
  }
1695
1937
  
1696
1938
 end:
1697
1939
  
1718
1960
  if(gpgme_initialized){
1719
1961
    gpgme_release(mc.ctx);
1720
1962
  }
 
1963
 
 
1964
  /* Cleans up the circular linked list of Mandos servers the client
 
1965
     has seen */
 
1966
  if(mc.current_server != NULL){
 
1967
    mc.current_server->prev->next = NULL;
 
1968
    while(mc.current_server != NULL){
 
1969
      server *next = mc.current_server->next;
 
1970
      free(mc.current_server);
 
1971
      mc.current_server = next;
 
1972
    }
 
1973
  }
1721
1974
  
1722
1975
  /* Take down the network interface */
1723
1976
  if(take_down_interface){
1725
1978
    errno = 0;
1726
1979
    ret = seteuid(0);
1727
1980
    if(ret == -1){
1728
 
      perror("seteuid");
 
1981
      perror_plus("seteuid");
1729
1982
    }
1730
1983
    if(geteuid() == 0){
1731
1984
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1732
1985
      if(ret == -1){
1733
 
        perror("ioctl SIOCGIFFLAGS");
 
1986
        perror_plus("ioctl SIOCGIFFLAGS");
1734
1987
      } else if(network.ifr_flags & IFF_UP) {
1735
1988
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
1736
1989
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
1737
1990
        if(ret == -1){
1738
 
          perror("ioctl SIOCSIFFLAGS -IFF_UP");
 
1991
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
1739
1992
        }
1740
1993
      }
1741
1994
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1742
1995
      if(ret == -1){
1743
 
        perror("close");
 
1996
        perror_plus("close");
1744
1997
      }
1745
1998
      /* Lower privileges permanently */
1746
1999
      errno = 0;
1747
2000
      ret = setuid(uid);
1748
2001
      if(ret == -1){
1749
 
        perror("setuid");
 
2002
        perror_plus("setuid");
1750
2003
      }
1751
2004
    }
1752
2005
  }
1753
2006
  
1754
 
  /* Removes the temp directory used by GPGME */
 
2007
  /* Removes the GPGME temp directory and all files inside */
1755
2008
  if(tempdir_created){
1756
 
    DIR *d;
1757
 
    struct dirent *direntry;
1758
 
    d = opendir(tempdir);
1759
 
    if(d == NULL){
1760
 
      if(errno != ENOENT){
1761
 
        perror("opendir");
1762
 
      }
1763
 
    } else {
1764
 
      while(true){
1765
 
        direntry = readdir(d);
1766
 
        if(direntry == NULL){
1767
 
          break;
1768
 
        }
1769
 
        /* Skip "." and ".." */
1770
 
        if(direntry->d_name[0] == '.'
1771
 
           and (direntry->d_name[1] == '\0'
1772
 
                or (direntry->d_name[1] == '.'
1773
 
                    and direntry->d_name[2] == '\0'))){
1774
 
          continue;
1775
 
        }
 
2009
    struct dirent **direntries = NULL;
 
2010
    struct dirent *direntry = NULL;
 
2011
    int numentries = scandir(tempdir, &direntries, notdotentries,
 
2012
                             alphasort);
 
2013
    if (numentries > 0){
 
2014
      for(int i = 0; i < numentries; i++){
 
2015
        direntry = direntries[i];
1776
2016
        char *fullname = NULL;
1777
2017
        ret = asprintf(&fullname, "%s/%s", tempdir,
1778
2018
                       direntry->d_name);
1779
2019
        if(ret < 0){
1780
 
          perror("asprintf");
 
2020
          perror_plus("asprintf");
1781
2021
          continue;
1782
2022
        }
1783
2023
        ret = remove(fullname);
1787
2027
        }
1788
2028
        free(fullname);
1789
2029
      }
1790
 
      closedir(d);
 
2030
    }
 
2031
 
 
2032
    /* need to clean even if 0 because man page doesn't specify */
 
2033
    free(direntries);
 
2034
    if (numentries == -1){
 
2035
      perror_plus("scandir");
1791
2036
    }
1792
2037
    ret = rmdir(tempdir);
1793
2038
    if(ret == -1 and errno != ENOENT){
1794
 
      perror("rmdir");
 
2039
      perror_plus("rmdir");
1795
2040
    }
1796
2041
  }
1797
2042
  
1802
2047
                                            &old_sigterm_action,
1803
2048
                                            NULL));
1804
2049
    if(ret == -1){
1805
 
      perror("sigaction");
 
2050
      perror_plus("sigaction");
1806
2051
    }
1807
2052
    do {
1808
2053
      ret = raise(signal_received);
1809
2054
    } while(ret != 0 and errno == EINTR);
1810
2055
    if(ret != 0){
1811
 
      perror("raise");
 
2056
      perror_plus("raise");
1812
2057
      abort();
1813
2058
    }
1814
2059
    TEMP_FAILURE_RETRY(pause());