/mandos/release

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/release

« back to all changes in this revision

Viewing changes to plugins.d/mandos-client.c

  • Committer: Teddy Hogeborn
  • Date: 2009-02-13 08:00:47 UTC
  • mfrom: (237.2.78 mandos)
  • Revision ID: teddy@fukt.bsnet.se-20090213080047-eibfmj4j2a9zt53d
Merge from trunk.  Notable changes:

 1. Server package now depends on "python-gobject".
 2. Permission fix for /lib64.
 3. Support for DEVICE setting from initramfs.conf, kernel parameters
    "ip=" and "mandos=connect".
 4. Fix for the bug where the server would stop responding, with a
    zombie checker process.
 5. Add support for disabling IPv6 in the server
 6. Fix for the bug which made the server, plugin-runner and
    mandos-client fail to change group ID.
 7. Add GnuTLS debugging to server debug output.
 8. Fix for the bug of the "--options-for" option of plugin-runner,
    where it would cut the value at the first colon character.
 9. Stop using sscanf() throughout, since it does not detect overflow.
10. Fix for the bug where plugin-runner would not go to the fallback
    if all plugins failed.
11. Fix for the bug where mandos-client would not clean up after a
    signal.
12. Added support for connecting to IPv4 addresses in mandos-client.
13. Added support for not using a specific network interface in
    mandos-client.
14. Kernel log level will be lowered by mandos-client while bringing
    up the network interface.
15. Add an option for the maximum time for mandos-client to wait for
    the network interface to come up.
16. Fix for the bug where mandos-client would not clean the temporary
    directory on some filesystems.

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() */
33
 
#ifndef _LARGEFILE_SOURCE
34
33
#define _LARGEFILE_SOURCE
35
 
#endif
36
 
#ifndef _FILE_OFFSET_BITS
37
34
#define _FILE_OFFSET_BITS 64
38
 
#endif
39
35
 
40
36
#define _GNU_SOURCE             /* TEMP_FAILURE_RETRY(), asprintf() */
41
37
 
43
39
                                   stdout, ferror(), remove() */
44
40
#include <stdint.h>             /* uint16_t, uint32_t */
45
41
#include <stddef.h>             /* NULL, size_t, ssize_t */
46
 
#include <stdlib.h>             /* free(), EXIT_SUCCESS, srand(),
47
 
                                   strtof(), abort() */
 
42
#include <stdlib.h>             /* free(), EXIT_SUCCESS, EXIT_FAILURE,
 
43
                                   srand(), strtof() */
48
44
#include <stdbool.h>            /* bool, false, true */
49
45
#include <string.h>             /* memset(), strcmp(), strlen(),
50
46
                                   strerror(), asprintf(), strcpy() */
53
49
                                   sockaddr_in6, PF_INET6,
54
50
                                   SOCK_STREAM, uid_t, gid_t, open(),
55
51
                                   opendir(), DIR */
56
 
#include <sys/stat.h>           /* open(), S_ISREG */
 
52
#include <sys/stat.h>           /* open() */
57
53
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
58
54
                                   inet_pton(), connect() */
59
55
#include <fcntl.h>              /* open() */
62
58
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
63
59
                                   strtoimax() */
64
60
#include <assert.h>             /* assert() */
65
 
#include <errno.h>              /* perror(), errno,
66
 
                                   program_invocation_short_name */
67
 
#include <time.h>               /* nanosleep(), time(), sleep() */
 
61
#include <errno.h>              /* perror(), errno */
 
62
#include <time.h>               /* nanosleep(), time() */
68
63
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
69
64
                                   SIOCSIFFLAGS, if_indextoname(),
70
65
                                   if_nametoindex(), IF_NAMESIZE */
72
67
                                   INET_ADDRSTRLEN, INET6_ADDRSTRLEN
73
68
                                */
74
69
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
75
 
                                   getuid(), getgid(), seteuid(),
76
 
                                   setgid(), pause() */
77
 
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
 
70
                                   getuid(), getgid(), setuid(),
 
71
                                   setgid() */
 
72
#include <arpa/inet.h>          /* inet_pton(), htons */
78
73
#include <iso646.h>             /* not, or, and */
79
74
#include <argp.h>               /* struct argp_option, error_t, struct
80
75
                                   argp_state, struct argp,
81
76
                                   argp_parse(), ARGP_KEY_ARG,
82
77
                                   ARGP_KEY_END, ARGP_ERR_UNKNOWN */
83
78
#include <signal.h>             /* sigemptyset(), sigaddset(),
84
 
                                   sigaction(), SIGTERM, sig_atomic_t,
85
 
                                   raise() */
86
 
#include <sysexits.h>           /* EX_OSERR, EX_USAGE, EX_UNAVAILABLE,
87
 
                                   EX_NOHOST, EX_IOERR, EX_PROTOCOL */
 
79
                                   sigaction(), SIGTERM, sigaction,
 
80
                                   sig_atomic_t */
88
81
 
89
82
#ifdef __linux__
90
83
#include <sys/klog.h>           /* klogctl() */
123
116
#define PATHDIR "/conf/conf.d/mandos"
124
117
#define SECKEY "seckey.txt"
125
118
#define PUBKEY "pubkey.txt"
126
 
#define HOOKDIR "/lib/mandos/network-hooks.d"
127
119
 
128
120
bool debug = false;
129
121
static const char mandos_protocol_version[] = "1";
130
122
const char *argp_program_version = "mandos-client " VERSION;
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;
 
123
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
145
124
 
146
125
/* Used for passing in values through the Avahi callback functions */
147
126
typedef struct {
152
131
  gnutls_dh_params_t dh_params;
153
132
  const char *priority;
154
133
  gpgme_ctx_t ctx;
155
 
  server *current_server;
156
134
} mandos_context;
157
135
 
158
136
/* global context so signal handler can reach it*/
159
137
mandos_context mc = { .simple_poll = NULL, .server = NULL,
160
138
                      .dh_bits = 1024, .priority = "SECURE256"
161
 
                      ":!CTYPE-X.509:+CTYPE-OPENPGP",
162
 
                      .current_server = NULL };
163
 
 
164
 
sig_atomic_t quit_now = 0;
165
 
int signal_received = 0;
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
 
}
 
139
                      ":!CTYPE-X.509:+CTYPE-OPENPGP" };
173
140
 
174
141
/*
175
142
 * Make additional room in "buffer" for at least BUFFER_SIZE more
188
155
  return buffer_capacity;
189
156
}
190
157
 
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
 
 
229
158
/* 
230
159
 * Initialize GPGME.
231
160
 */
232
161
static bool init_gpgme(const char *seckey,
233
162
                       const char *pubkey, const char *tempdir){
 
163
  int ret;
234
164
  gpgme_error_t rc;
235
165
  gpgme_engine_info_t engine_info;
236
166
  
239
169
   * Helper function to insert pub and seckey to the engine keyring.
240
170
   */
241
171
  bool import_key(const char *filename){
242
 
    int ret;
243
172
    int fd;
244
173
    gpgme_data_t pgp_data;
245
174
    
246
175
    fd = (int)TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
247
176
    if(fd == -1){
248
 
      perror_plus("open");
 
177
      perror("open");
249
178
      return false;
250
179
    }
251
180
    
265
194
    
266
195
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
267
196
    if(ret == -1){
268
 
      perror_plus("close");
 
197
      perror("close");
269
198
    }
270
199
    gpgme_data_release(pgp_data);
271
200
    return true;
284
213
    return false;
285
214
  }
286
215
  
287
 
  /* Set GPGME home directory for the OpenPGP engine only */
 
216
    /* Set GPGME home directory for the OpenPGP engine only */
288
217
  rc = gpgme_get_engine_info(&engine_info);
289
218
  if(rc != GPG_ERR_NO_ERROR){
290
219
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
316
245
    return false;
317
246
  }
318
247
  
319
 
  return true;
 
248
  return true; 
320
249
}
321
250
 
322
251
/* 
376
305
        }
377
306
        gpgme_recipient_t recipient;
378
307
        recipient = result->recipients;
379
 
        while(recipient != NULL){
380
 
          fprintf(stderr, "Public key algorithm: %s\n",
381
 
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
382
 
          fprintf(stderr, "Key ID: %s\n", recipient->keyid);
383
 
          fprintf(stderr, "Secret key available: %s\n",
384
 
                  recipient->status == GPG_ERR_NO_SECKEY
385
 
                  ? "No" : "Yes");
386
 
          recipient = recipient->next;
 
308
        if(recipient){
 
309
          while(recipient != NULL){
 
310
            fprintf(stderr, "Public key algorithm: %s\n",
 
311
                    gpgme_pubkey_algo_name(recipient->pubkey_algo));
 
312
            fprintf(stderr, "Key ID: %s\n", recipient->keyid);
 
313
            fprintf(stderr, "Secret key available: %s\n",
 
314
                    recipient->status == GPG_ERR_NO_SECKEY
 
315
                    ? "No" : "Yes");
 
316
            recipient = recipient->next;
 
317
          }
387
318
        }
388
319
      }
389
320
    }
396
327
  
397
328
  /* Seek back to the beginning of the GPGME plaintext data buffer */
398
329
  if(gpgme_data_seek(dh_plain, (off_t)0, SEEK_SET) == -1){
399
 
    perror_plus("gpgme_data_seek");
 
330
    perror("gpgme_data_seek");
400
331
    plaintext_length = -1;
401
332
    goto decrypt_end;
402
333
  }
407
338
                                      (size_t)plaintext_length,
408
339
                                      plaintext_capacity);
409
340
    if(plaintext_capacity == 0){
410
 
        perror_plus("incbuffer");
 
341
        perror("incbuffer");
411
342
        plaintext_length = -1;
412
343
        goto decrypt_end;
413
344
    }
420
351
      break;
421
352
    }
422
353
    if(ret < 0){
423
 
      perror_plus("gpgme_data_read");
 
354
      perror("gpgme_data_read");
424
355
      plaintext_length = -1;
425
356
      goto decrypt_end;
426
357
    }
483
414
  }
484
415
  
485
416
  /* OpenPGP credentials */
486
 
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
 
417
  gnutls_certificate_allocate_credentials(&mc.cred);
487
418
  if(ret != GNUTLS_E_SUCCESS){
488
 
    fprintf(stderr, "GnuTLS memory error: %s\n",
 
419
    fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning
 
420
                                                    from
 
421
                                                    -Wunreachable-code
 
422
                                                 */
489
423
            safer_gnutls_strerror(ret));
490
424
    gnutls_global_deinit();
491
425
    return -1;
538
472
static int init_gnutls_session(gnutls_session_t *session){
539
473
  int ret;
540
474
  /* GnuTLS session creation */
541
 
  do {
542
 
    ret = gnutls_init(session, GNUTLS_SERVER);
543
 
    if(quit_now){
544
 
      return -1;
545
 
    }
546
 
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
 
475
  ret = gnutls_init(session, GNUTLS_SERVER);
547
476
  if(ret != GNUTLS_E_SUCCESS){
548
477
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
549
478
            safer_gnutls_strerror(ret));
551
480
  
552
481
  {
553
482
    const char *err;
554
 
    do {
555
 
      ret = gnutls_priority_set_direct(*session, mc.priority, &err);
556
 
      if(quit_now){
557
 
        gnutls_deinit(*session);
558
 
        return -1;
559
 
      }
560
 
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
 
483
    ret = gnutls_priority_set_direct(*session, mc.priority, &err);
561
484
    if(ret != GNUTLS_E_SUCCESS){
562
485
      fprintf(stderr, "Syntax error at: %s\n", err);
563
486
      fprintf(stderr, "GnuTLS error: %s\n",
567
490
    }
568
491
  }
569
492
  
570
 
  do {
571
 
    ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
572
 
                                 mc.cred);
573
 
    if(quit_now){
574
 
      gnutls_deinit(*session);
575
 
      return -1;
576
 
    }
577
 
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
 
493
  ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
 
494
                               mc.cred);
578
495
  if(ret != GNUTLS_E_SUCCESS){
579
496
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
580
497
            safer_gnutls_strerror(ret));
583
500
  }
584
501
  
585
502
  /* ignore client certificate if any. */
586
 
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
 
503
  gnutls_certificate_server_set_request(*session,
 
504
                                        GNUTLS_CERT_IGNORE);
587
505
  
588
506
  gnutls_dh_set_prime_bits(*session, mc.dh_bits);
589
507
  
598
516
static int start_mandos_communication(const char *ip, uint16_t port,
599
517
                                      AvahiIfIndex if_index,
600
518
                                      int af){
601
 
  int ret, tcp_sd = -1;
 
519
  int ret, tcp_sd;
602
520
  ssize_t sret;
603
521
  union {
604
522
    struct sockaddr_in in;
605
523
    struct sockaddr_in6 in6;
606
524
  } to;
607
525
  char *buffer = NULL;
608
 
  char *decrypted_buffer = NULL;
 
526
  char *decrypted_buffer;
609
527
  size_t buffer_length = 0;
610
528
  size_t buffer_capacity = 0;
 
529
  ssize_t decrypted_buffer_size;
611
530
  size_t written;
612
 
  int retval = -1;
 
531
  int retval = 0;
613
532
  gnutls_session_t session;
614
533
  int pf;                       /* Protocol family */
615
534
  
616
 
  errno = 0;
617
 
  
618
 
  if(quit_now){
619
 
    errno = EINTR;
620
 
    return -1;
621
 
  }
622
 
  
623
535
  switch(af){
624
536
  case AF_INET6:
625
537
    pf = PF_INET6;
629
541
    break;
630
542
  default:
631
543
    fprintf(stderr, "Bad address family: %d\n", af);
632
 
    errno = EINVAL;
633
544
    return -1;
634
545
  }
635
546
  
645
556
  
646
557
  tcp_sd = socket(pf, SOCK_STREAM, 0);
647
558
  if(tcp_sd < 0){
648
 
    int e = errno;
649
 
    perror_plus("socket");
650
 
    errno = e;
651
 
    goto mandos_end;
652
 
  }
653
 
  
654
 
  if(quit_now){
655
 
    errno = EINTR;
656
 
    goto mandos_end;
 
559
    perror("socket");
 
560
    return -1;
657
561
  }
658
562
  
659
563
  memset(&to, 0, sizeof(to));
660
564
  if(af == AF_INET6){
661
 
    to.in6.sin6_family = (sa_family_t)af;
 
565
    to.in6.sin6_family = (uint16_t)af;
662
566
    ret = inet_pton(af, ip, &to.in6.sin6_addr);
663
567
  } else {                      /* IPv4 */
664
568
    to.in.sin_family = (sa_family_t)af;
665
569
    ret = inet_pton(af, ip, &to.in.sin_addr);
666
570
  }
667
571
  if(ret < 0 ){
668
 
    int e = errno;
669
 
    perror_plus("inet_pton");
670
 
    errno = e;
671
 
    goto mandos_end;
 
572
    perror("inet_pton");
 
573
    return -1;
672
574
  }
673
575
  if(ret == 0){
674
 
    int e = errno;
675
576
    fprintf(stderr, "Bad address: %s\n", ip);
676
 
    errno = e;
677
 
    goto mandos_end;
 
577
    return -1;
678
578
  }
679
579
  if(af == AF_INET6){
680
580
    to.in6.sin6_port = htons(port); /* Spurious warnings from
687
587
      if(if_index == AVAHI_IF_UNSPEC){
688
588
        fprintf(stderr, "An IPv6 link-local address is incomplete"
689
589
                " without a network interface\n");
690
 
        errno = EINVAL;
691
 
        goto mandos_end;
 
590
        return -1;
692
591
      }
693
592
      /* Set the network interface number as scope */
694
593
      to.in6.sin6_scope_id = (uint32_t)if_index;
699
598
                                     -Wunreachable-code */
700
599
  }
701
600
  
702
 
  if(quit_now){
703
 
    errno = EINTR;
704
 
    goto mandos_end;
705
 
  }
706
 
  
707
601
  if(debug){
708
602
    if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
709
603
      char interface[IF_NAMESIZE];
710
604
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
711
 
        perror_plus("if_indextoname");
 
605
        perror("if_indextoname");
712
606
      } else {
713
607
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
714
608
                ip, interface, port);
728
622
                        sizeof(addrstr));
729
623
    }
730
624
    if(pcret == NULL){
731
 
      perror_plus("inet_ntop");
 
625
      perror("inet_ntop");
732
626
    } else {
733
627
      if(strcmp(addrstr, ip) != 0){
734
628
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
736
630
    }
737
631
  }
738
632
  
739
 
  if(quit_now){
740
 
    errno = EINTR;
741
 
    goto mandos_end;
742
 
  }
743
 
  
744
633
  if(af == AF_INET6){
745
634
    ret = connect(tcp_sd, &to.in6, sizeof(to));
746
635
  } else {
747
636
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
748
637
  }
749
638
  if(ret < 0){
750
 
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
751
 
      int e = errno;
752
 
      perror_plus("connect");
753
 
      errno = e;
754
 
    }
755
 
    goto mandos_end;
756
 
  }
757
 
  
758
 
  if(quit_now){
759
 
    errno = EINTR;
760
 
    goto mandos_end;
 
639
    perror("connect");
 
640
    return -1;
761
641
  }
762
642
  
763
643
  const char *out = mandos_protocol_version;
767
647
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
768
648
                                   out_size - written));
769
649
    if(ret == -1){
770
 
      int e = errno;
771
 
      perror_plus("write");
772
 
      errno = e;
 
650
      perror("write");
 
651
      retval = -1;
773
652
      goto mandos_end;
774
653
    }
775
654
    written += (size_t)ret;
783
662
        break;
784
663
      }
785
664
    }
786
 
  
787
 
    if(quit_now){
788
 
      errno = EINTR;
789
 
      goto mandos_end;
790
 
    }
791
665
  }
792
666
  
793
667
  if(debug){
794
668
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
795
669
  }
796
670
  
797
 
  if(quit_now){
798
 
    errno = EINTR;
799
 
    goto mandos_end;
800
 
  }
801
 
  
802
 
  /* Spurious warning from -Wint-to-pointer-cast */
803
671
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
804
672
  
805
 
  if(quit_now){
806
 
    errno = EINTR;
807
 
    goto mandos_end;
808
 
  }
809
 
  
810
 
  do {
 
673
  do{
811
674
    ret = gnutls_handshake(session);
812
 
    if(quit_now){
813
 
      errno = EINTR;
814
 
      goto mandos_end;
815
 
    }
816
675
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
817
676
  
818
677
  if(ret != GNUTLS_E_SUCCESS){
820
679
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
821
680
      gnutls_perror(ret);
822
681
    }
823
 
    errno = EPROTO;
 
682
    retval = -1;
824
683
    goto mandos_end;
825
684
  }
826
685
  
832
691
  }
833
692
  
834
693
  while(true){
835
 
    
836
 
    if(quit_now){
837
 
      errno = EINTR;
838
 
      goto mandos_end;
839
 
    }
840
 
    
841
694
    buffer_capacity = incbuffer(&buffer, buffer_length,
842
695
                                   buffer_capacity);
843
696
    if(buffer_capacity == 0){
844
 
      int e = errno;
845
 
      perror_plus("incbuffer");
846
 
      errno = e;
847
 
      goto mandos_end;
848
 
    }
849
 
    
850
 
    if(quit_now){
851
 
      errno = EINTR;
 
697
      perror("incbuffer");
 
698
      retval = -1;
852
699
      goto mandos_end;
853
700
    }
854
701
    
863
710
      case GNUTLS_E_AGAIN:
864
711
        break;
865
712
      case GNUTLS_E_REHANDSHAKE:
866
 
        do {
 
713
        do{
867
714
          ret = gnutls_handshake(session);
868
 
          
869
 
          if(quit_now){
870
 
            errno = EINTR;
871
 
            goto mandos_end;
872
 
          }
873
715
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
874
716
        if(ret < 0){
875
717
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
876
718
          gnutls_perror(ret);
877
 
          errno = EPROTO;
 
719
          retval = -1;
878
720
          goto mandos_end;
879
721
        }
880
722
        break;
881
723
      default:
882
724
        fprintf(stderr, "Unknown error while reading data from"
883
725
                " encrypted session with Mandos server\n");
 
726
        retval = -1;
884
727
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
885
 
        errno = EIO;
886
728
        goto mandos_end;
887
729
      }
888
730
    } else {
894
736
    fprintf(stderr, "Closing TLS session\n");
895
737
  }
896
738
  
897
 
  if(quit_now){
898
 
    errno = EINTR;
899
 
    goto mandos_end;
900
 
  }
901
 
  
902
 
  do {
903
 
    ret = gnutls_bye(session, GNUTLS_SHUT_RDWR);
904
 
    if(quit_now){
905
 
      errno = EINTR;
906
 
      goto mandos_end;
907
 
    }
908
 
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
 
739
  gnutls_bye(session, GNUTLS_SHUT_RDWR);
909
740
  
910
741
  if(buffer_length > 0){
911
 
    ssize_t decrypted_buffer_size;
912
742
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
913
743
                                               buffer_length,
914
744
                                               &decrypted_buffer);
915
745
    if(decrypted_buffer_size >= 0){
916
 
      
917
746
      written = 0;
918
747
      while(written < (size_t) decrypted_buffer_size){
919
 
        if(quit_now){
920
 
          errno = EINTR;
921
 
          goto mandos_end;
922
 
        }
923
 
        
924
748
        ret = (int)fwrite(decrypted_buffer + written, 1,
925
749
                          (size_t)decrypted_buffer_size - written,
926
750
                          stdout);
927
751
        if(ret == 0 and ferror(stdout)){
928
 
          int e = errno;
929
752
          if(debug){
930
753
            fprintf(stderr, "Error writing encrypted data: %s\n",
931
754
                    strerror(errno));
932
755
          }
933
 
          errno = e;
934
 
          goto mandos_end;
 
756
          retval = -1;
 
757
          break;
935
758
        }
936
759
        written += (size_t)ret;
937
760
      }
938
 
      retval = 0;
 
761
      free(decrypted_buffer);
 
762
    } else {
 
763
      retval = -1;
939
764
    }
 
765
  } else {
 
766
    retval = -1;
940
767
  }
941
768
  
942
769
  /* Shutdown procedure */
943
770
  
944
771
 mandos_end:
945
 
  {
946
 
    int e = errno;
947
 
    free(decrypted_buffer);
948
 
    free(buffer);
949
 
    if(tcp_sd >= 0){
950
 
      ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
951
 
    }
952
 
    if(ret == -1){
953
 
      if(e == 0){
954
 
        e = errno;
955
 
      }
956
 
      perror_plus("close");
957
 
    }
958
 
    gnutls_deinit(session);
959
 
    errno = e;
960
 
    if(quit_now){
961
 
      errno = EINTR;
962
 
      retval = -1;
963
 
    }
 
772
  free(buffer);
 
773
  ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
 
774
  if(ret == -1){
 
775
    perror("close");
964
776
  }
 
777
  gnutls_deinit(session);
965
778
  return retval;
966
779
}
967
780
 
984
797
  /* Called whenever a service has been resolved successfully or
985
798
     timed out */
986
799
  
987
 
  if(quit_now){
988
 
    return;
989
 
  }
990
 
  
991
800
  switch(event){
992
801
  default:
993
802
  case AVAHI_RESOLVER_FAILURE:
1009
818
                                           avahi_proto_to_af(proto));
1010
819
      if(ret == 0){
1011
820
        avahi_simple_poll_quit(mc.simple_poll);
1012
 
      } else {
1013
 
        ret = add_server(ip, port, interface,
1014
 
                         avahi_proto_to_af(proto));
1015
821
      }
1016
822
    }
1017
823
  }
1033
839
  /* Called whenever a new services becomes available on the LAN or
1034
840
     is removed from the LAN */
1035
841
  
1036
 
  if(quit_now){
1037
 
    return;
1038
 
  }
1039
 
  
1040
842
  switch(event){
1041
843
  default:
1042
844
  case AVAHI_BROWSER_FAILURE:
1071
873
  }
1072
874
}
1073
875
 
1074
 
/* Signal handler that stops main loop after SIGTERM */
1075
 
static void handle_sigterm(int sig){
 
876
sig_atomic_t quit_now = 0;
 
877
 
 
878
/* stop main loop after sigterm has been called */
 
879
static void handle_sigterm(__attribute__((unused)) int sig){
1076
880
  if(quit_now){
1077
881
    return;
1078
882
  }
1079
883
  quit_now = 1;
1080
 
  signal_received = sig;
1081
884
  int old_errno = errno;
1082
 
  /* set main loop to exit */
1083
885
  if(mc.simple_poll != NULL){
1084
886
    avahi_simple_poll_quit(mc.simple_poll);
1085
887
  }
1086
888
  errno = old_errno;
1087
889
}
1088
890
 
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
 
  if(if_entry->d_name[0] == '.'){
1156
 
    return 0;
1157
 
  }
1158
 
  
1159
 
  struct ifreq ifr;
1160
 
  if(not get_flags(if_entry->d_name, &ifr)){
1161
 
    if(debug){
1162
 
      fprintf(stderr, "Failed to get flags for interface \"%s\"\n",
1163
 
              if_entry->d_name);
1164
 
    }
1165
 
    return 0;
1166
 
  }
1167
 
  
1168
 
  if(not good_flags(if_entry->d_name, &ifr)){
1169
 
    return 0;
1170
 
  }
1171
 
  return 1;
1172
 
}
1173
 
 
1174
 
/* 
1175
 
 * This function determines if a directory entry in /sys/class/net
1176
 
 * corresponds to an acceptable network device which is up.
1177
 
 * (This function is passed to scandir(3) as a filter function.)
1178
 
 */
1179
 
int up_interface(const struct dirent *if_entry){
1180
 
  if(if_entry->d_name[0] == '.'){
1181
 
    return 0;
1182
 
  }
1183
 
  
1184
 
  struct ifreq ifr;
1185
 
  if(not get_flags(if_entry->d_name, &ifr)){
1186
 
    if(debug){
1187
 
      fprintf(stderr, "Failed to get flags for interface \"%s\"\n",
1188
 
              if_entry->d_name);
1189
 
    }
1190
 
    return 0;
1191
 
  }
1192
 
  
1193
 
  /* Reject down interfaces */
1194
 
  if(not (ifr.ifr_flags & IFF_UP)){
1195
 
    if(debug){
1196
 
      fprintf(stderr, "Rejecting down interface \"%s\"\n",
1197
 
              if_entry->d_name);
1198
 
    }
1199
 
    return 0;
1200
 
  }
1201
 
  
1202
 
  /* Reject non-running interfaces */
1203
 
  if(not (ifr.ifr_flags & IFF_RUNNING)){
1204
 
    if(debug){
1205
 
      fprintf(stderr, "Rejecting non-running interface \"%s\"\n",
1206
 
              if_entry->d_name);
1207
 
    }
1208
 
    return 0;
1209
 
  }
1210
 
  
1211
 
  if(not good_flags(if_entry->d_name, &ifr)){
1212
 
    return 0;
1213
 
  }
1214
 
  return 1;
1215
 
}
1216
 
 
1217
 
int notdotentries(const struct dirent *direntry){
1218
 
  /* Skip "." and ".." */
1219
 
  if(direntry->d_name[0] == '.'
1220
 
     and (direntry->d_name[1] == '\0'
1221
 
          or (direntry->d_name[1] == '.'
1222
 
              and direntry->d_name[2] == '\0'))){
1223
 
    return 0;
1224
 
  }
1225
 
  return 1;
1226
 
}
1227
 
 
1228
 
/* Is this directory entry a runnable program? */
1229
 
int runnable_hook(const struct dirent *direntry){
1230
 
  int ret;
1231
 
  struct stat st;
1232
 
  
1233
 
  if((direntry->d_name)[0] == '\0'){
1234
 
    /* Empty name? */
1235
 
    return 0;
1236
 
  }
1237
 
  
1238
 
  /* Save pointer to last character */
1239
 
  char *end = strchr(direntry->d_name, '\0')-1;
1240
 
  
1241
 
  if(*end == '~'){
1242
 
    /* Backup name~ */
1243
 
    return 0;
1244
 
  }
1245
 
  
1246
 
  if(((direntry->d_name)[0] == '#')
1247
 
     and (*end == '#')){
1248
 
    /* Temporary #name# */
1249
 
    return 0;
1250
 
  }
1251
 
  
1252
 
  /* XXX more rules here */
1253
 
  
1254
 
  ret = stat(direntry->d_name, &st);
1255
 
  if(ret == -1){
1256
 
    if(debug){
1257
 
      perror_plus("Could not stat plugin");
1258
 
    }
1259
 
    return 0;
1260
 
  }
1261
 
  if(not (S_ISREG(st.st_mode))){
1262
 
    /* Not a regular file */
1263
 
    return 0;
1264
 
  }
1265
 
  if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
1266
 
    /* Not executable */
1267
 
    return 0;
1268
 
  }
1269
 
  return 1;
1270
 
}
1271
 
 
1272
 
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
1273
 
  int ret;
1274
 
  struct timespec now;
1275
 
  struct timespec waited_time;
1276
 
  intmax_t block_time;
1277
 
  
1278
 
  while(true){
1279
 
    if(mc.current_server == NULL){
1280
 
      if (debug){
1281
 
        fprintf(stderr,
1282
 
                "Wait until first server is found. No timeout!\n");
1283
 
      }
1284
 
      ret = avahi_simple_poll_iterate(s, -1);
1285
 
    } else {
1286
 
      if (debug){
1287
 
        fprintf(stderr, "Check current_server if we should run it,"
1288
 
                " or wait\n");
1289
 
      }
1290
 
      /* the current time */
1291
 
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
1292
 
      if(ret == -1){
1293
 
        perror_plus("clock_gettime");
1294
 
        return -1;
1295
 
      }
1296
 
      /* Calculating in ms how long time between now and server
1297
 
         who we visted longest time ago. Now - last seen.  */
1298
 
      waited_time.tv_sec = (now.tv_sec
1299
 
                            - mc.current_server->last_seen.tv_sec);
1300
 
      waited_time.tv_nsec = (now.tv_nsec
1301
 
                             - mc.current_server->last_seen.tv_nsec);
1302
 
      /* total time is 10s/10,000ms.
1303
 
         Converting to s from ms by dividing by 1,000,
1304
 
         and ns to ms by dividing by 1,000,000. */
1305
 
      block_time = ((retry_interval
1306
 
                     - ((intmax_t)waited_time.tv_sec * 1000))
1307
 
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1308
 
      
1309
 
      if (debug){
1310
 
        fprintf(stderr, "Blocking for %" PRIdMAX " ms\n", block_time);
1311
 
      }
1312
 
      
1313
 
      if(block_time <= 0){
1314
 
        ret = start_mandos_communication(mc.current_server->ip,
1315
 
                                         mc.current_server->port,
1316
 
                                         mc.current_server->if_index,
1317
 
                                         mc.current_server->af);
1318
 
        if(ret == 0){
1319
 
          avahi_simple_poll_quit(mc.simple_poll);
1320
 
          return 0;
1321
 
        }
1322
 
        ret = clock_gettime(CLOCK_MONOTONIC,
1323
 
                            &mc.current_server->last_seen);
1324
 
        if(ret == -1){
1325
 
          perror_plus("clock_gettime");
1326
 
          return -1;
1327
 
        }
1328
 
        mc.current_server = mc.current_server->next;
1329
 
        block_time = 0;         /* Call avahi to find new Mandos
1330
 
                                   servers, but don't block */
1331
 
      }
1332
 
      
1333
 
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1334
 
    }
1335
 
    if(ret != 0){
1336
 
      if (ret > 0 or errno != EINTR) {
1337
 
        return (ret != 1) ? ret : 0;
1338
 
      }
1339
 
    }
1340
 
  }
1341
 
}
1342
 
 
1343
891
int main(int argc, char *argv[]){
1344
892
  AvahiSServiceBrowser *sb = NULL;
1345
893
  int error;
1347
895
  intmax_t tmpmax;
1348
896
  char *tmp;
1349
897
  int exitcode = EXIT_SUCCESS;
1350
 
  const char *interface = "";
 
898
  const char *interface = "eth0";
1351
899
  struct ifreq network;
1352
 
  int sd = -1;
1353
 
  bool take_down_interface = false;
 
900
  int sd;
1354
901
  uid_t uid;
1355
902
  gid_t gid;
 
903
  char *connect_to = NULL;
1356
904
  char tempdir[] = "/tmp/mandosXXXXXX";
1357
905
  bool tempdir_created = false;
1358
906
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1362
910
  bool gnutls_initialized = false;
1363
911
  bool gpgme_initialized = false;
1364
912
  float delay = 2.5f;
1365
 
  double retry_interval = 10; /* 10s between trying a server and
1366
 
                                 retrying the same server again */
1367
913
  
1368
 
  struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
 
914
  struct sigaction old_sigterm_action;
1369
915
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
1370
916
  
1371
 
  uid = getuid();
1372
 
  gid = getgid();
1373
 
  
1374
 
  /* Lower any group privileges we might have, just to be safe */
1375
 
  errno = 0;
1376
 
  ret = setgid(gid);
1377
 
  if(ret == -1){
1378
 
    perror_plus("setgid");
1379
 
  }
1380
 
  
1381
 
  /* Lower user privileges (temporarily) */
1382
 
  errno = 0;
1383
 
  ret = seteuid(uid);
1384
 
  if(ret == -1){
1385
 
    perror_plus("seteuid");
1386
 
  }
1387
 
  
1388
 
  if(quit_now){
1389
 
    goto end;
1390
 
  }
1391
 
  
1392
917
  {
1393
918
    struct argp_option options[] = {
1394
919
      { .name = "debug", .key = 128,
1423
948
        .arg = "SECONDS",
1424
949
        .doc = "Maximum delay to wait for interface startup",
1425
950
        .group = 2 },
1426
 
      { .name = "retry", .key = 132,
1427
 
        .arg = "SECONDS",
1428
 
        .doc = "Retry interval used when denied by the mandos server",
1429
 
        .group = 2 },
1430
 
      /*
1431
 
       * These reproduce what we would get without ARGP_NO_HELP
1432
 
       */
1433
 
      { .name = "help", .key = '?',
1434
 
        .doc = "Give this help list", .group = -1 },
1435
 
      { .name = "usage", .key = -3,
1436
 
        .doc = "Give a short usage message", .group = -1 },
1437
 
      { .name = "version", .key = 'V',
1438
 
        .doc = "Print program version", .group = -1 },
1439
951
      { .name = NULL }
1440
952
    };
1441
953
    
1442
954
    error_t parse_opt(int key, char *arg,
1443
955
                      struct argp_state *state){
1444
 
      errno = 0;
1445
956
      switch(key){
1446
957
      case 128:                 /* --debug */
1447
958
        debug = true;
1463
974
        tmpmax = strtoimax(arg, &tmp, 10);
1464
975
        if(errno != 0 or tmp == arg or *tmp != '\0'
1465
976
           or tmpmax != (typeof(mc.dh_bits))tmpmax){
1466
 
          argp_error(state, "Bad number of DH bits");
 
977
          fprintf(stderr, "Bad number of DH bits\n");
 
978
          exit(EXIT_FAILURE);
1467
979
        }
1468
980
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
1469
981
        break;
1474
986
        errno = 0;
1475
987
        delay = strtof(arg, &tmp);
1476
988
        if(errno != 0 or tmp == arg or *tmp != '\0'){
1477
 
          argp_error(state, "Bad delay");
1478
 
        }
1479
 
      case 132:                 /* --retry */
1480
 
        errno = 0;
1481
 
        retry_interval = strtod(arg, &tmp);
1482
 
        if(errno != 0 or tmp == arg or *tmp != '\0'
1483
 
           or (retry_interval * 1000) > INT_MAX
1484
 
           or retry_interval < 0){
1485
 
          argp_error(state, "Bad retry interval");
 
989
          fprintf(stderr, "Bad delay\n");
 
990
          exit(EXIT_FAILURE);
1486
991
        }
1487
992
        break;
1488
 
        /*
1489
 
         * These reproduce what we would get without ARGP_NO_HELP
1490
 
         */
1491
 
      case '?':                 /* --help */
1492
 
        argp_state_help(state, state->out_stream,
1493
 
                        (ARGP_HELP_STD_HELP | ARGP_HELP_EXIT_ERR)
1494
 
                        & ~(unsigned int)ARGP_HELP_EXIT_OK);
1495
 
      case -3:                  /* --usage */
1496
 
        argp_state_help(state, state->out_stream,
1497
 
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1498
 
      case 'V':                 /* --version */
1499
 
        fprintf(state->out_stream, "%s\n", argp_program_version);
1500
 
        exit(argp_err_exit_status);
 
993
      case ARGP_KEY_ARG:
 
994
        argp_usage(state);
 
995
      case ARGP_KEY_END:
1501
996
        break;
1502
997
      default:
1503
998
        return ARGP_ERR_UNKNOWN;
1504
999
      }
1505
 
      return errno;
 
1000
      return 0;
1506
1001
    }
1507
1002
    
1508
1003
    struct argp argp = { .options = options, .parser = parse_opt,
1509
1004
                         .args_doc = "",
1510
1005
                         .doc = "Mandos client -- Get and decrypt"
1511
1006
                         " passwords from a Mandos server" };
1512
 
    ret = argp_parse(&argp, argc, argv,
1513
 
                     ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
1514
 
    switch(ret){
1515
 
    case 0:
1516
 
      break;
1517
 
    case ENOMEM:
1518
 
    default:
1519
 
      errno = ret;
1520
 
      perror_plus("argp_parse");
1521
 
      exitcode = EX_OSERR;
1522
 
      goto end;
1523
 
    case EINVAL:
1524
 
      exitcode = EX_USAGE;
1525
 
      goto end;
1526
 
    }
1527
 
  }
1528
 
    
1529
 
  {
1530
 
    /* Work around Debian bug #633582:
1531
 
       <http://bugs.debian.org/633582> */
1532
 
    struct stat st;
1533
 
    
1534
 
    /* Re-raise priviliges */
1535
 
    errno = 0;
1536
 
    ret = seteuid(0);
1537
 
    if(ret == -1){
1538
 
      perror_plus("seteuid");
1539
 
    }
1540
 
    
1541
 
    if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
1542
 
      int seckey_fd = open(seckey, O_RDONLY);
1543
 
      if(seckey_fd == -1){
1544
 
        perror_plus("open");
1545
 
      } else {
1546
 
        ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
1547
 
        if(ret == -1){
1548
 
          perror_plus("fstat");
1549
 
        } else {
1550
 
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1551
 
            ret = fchown(seckey_fd, uid, gid);
1552
 
            if(ret == -1){
1553
 
              perror_plus("fchown");
1554
 
            }
1555
 
          }
1556
 
        }
1557
 
        TEMP_FAILURE_RETRY(close(seckey_fd));
1558
 
      }
1559
 
    }
1560
 
    
1561
 
    if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
1562
 
      int pubkey_fd = open(pubkey, O_RDONLY);
1563
 
      if(pubkey_fd == -1){
1564
 
        perror_plus("open");
1565
 
      } else {
1566
 
        ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
1567
 
        if(ret == -1){
1568
 
          perror_plus("fstat");
1569
 
        } else {
1570
 
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1571
 
            ret = fchown(pubkey_fd, uid, gid);
1572
 
            if(ret == -1){
1573
 
              perror_plus("fchown");
1574
 
            }
1575
 
          }
1576
 
        }
1577
 
        TEMP_FAILURE_RETRY(close(pubkey_fd));
1578
 
      }
1579
 
    }
1580
 
    
1581
 
    /* Lower privileges */
1582
 
    errno = 0;
1583
 
    ret = seteuid(uid);
1584
 
    if(ret == -1){
1585
 
      perror_plus("seteuid");
1586
 
    }
1587
 
  }
1588
 
  
1589
 
  /* Find network hooks and run them */
1590
 
  {
1591
 
    struct dirent **direntries;
1592
 
    struct dirent *direntry;
1593
 
    int numhooks = scandir(HOOKDIR, &direntries, runnable_hook,
1594
 
                           alphasort);
1595
 
    int devnull = open("/dev/null", O_RDONLY);
1596
 
    for(int i = 0; i < numhooks; i++){
1597
 
      direntry = direntries[0];
1598
 
      char *fullname = NULL;
1599
 
      ret = asprintf(&fullname, "%s/%s", tempdir,
1600
 
                     direntry->d_name);
1601
 
      if(ret < 0){
1602
 
        perror_plus("asprintf");
1603
 
        continue;
1604
 
      }
1605
 
      pid_t hook_pid = fork();
1606
 
      if(hook_pid == 0){
1607
 
        /* Child */
1608
 
        dup2(devnull, STDIN_FILENO);
1609
 
        close(devnull);
1610
 
        dup2(STDERR_FILENO, STDOUT_FILENO);
1611
 
        setenv("DEVICE", interface, 1);
1612
 
        setenv("VERBOSE", debug ? "1" : "0", 1);
1613
 
        setenv("MODE", "start", 1);
1614
 
        /* setenv( XXX more here */
1615
 
        ret = execl(fullname, direntry->d_name, "start", NULL);
1616
 
        perror_plus("execl");
1617
 
      }
1618
 
      free(fullname);
1619
 
      if(quit_now){
1620
 
        goto end;
1621
 
      }
1622
 
    }
1623
 
    close(devnull);
 
1007
    ret = argp_parse(&argp, argc, argv, 0, 0, NULL);
 
1008
    if(ret == ARGP_ERR_UNKNOWN){
 
1009
      fprintf(stderr, "Unknown error while parsing arguments\n");
 
1010
      exitcode = EXIT_FAILURE;
 
1011
      goto end;
 
1012
    }
1624
1013
  }
1625
1014
  
1626
1015
  if(not debug){
1627
1016
    avahi_set_log_function(empty_log);
1628
1017
  }
1629
1018
  
1630
 
  if(interface[0] == '\0'){
1631
 
    struct dirent **direntries;
1632
 
    /* First look for interfaces that are up */
1633
 
    ret = scandir(sys_class_net, &direntries, up_interface,
1634
 
                  alphasort);
1635
 
    if(ret == 0){
1636
 
      /* No up interfaces, look for any good interfaces */
1637
 
      free(direntries);
1638
 
      ret = scandir(sys_class_net, &direntries, good_interface,
1639
 
                    alphasort);
1640
 
    }
1641
 
    if(ret >= 1){
1642
 
      /* Pick the first interface returned */
1643
 
      interface = strdup(direntries[0]->d_name);
1644
 
      if(debug){
1645
 
        fprintf(stderr, "Using interface \"%s\"\n", interface);
1646
 
      }
1647
 
      if(interface == NULL){
1648
 
        perror_plus("malloc");
1649
 
        free(direntries);
1650
 
        exitcode = EXIT_FAILURE;
1651
 
        goto end;
1652
 
      }
1653
 
      free(direntries);
1654
 
    } else {
1655
 
      free(direntries);
1656
 
      fprintf(stderr, "Could not find a network interface\n");
1657
 
      exitcode = EXIT_FAILURE;
1658
 
      goto end;
1659
 
    }
1660
 
  }
1661
 
  
1662
1019
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
1663
1020
     from the signal handler */
1664
1021
  /* Initialize the pseudo-RNG for Avahi */
1666
1023
  mc.simple_poll = avahi_simple_poll_new();
1667
1024
  if(mc.simple_poll == NULL){
1668
1025
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
1669
 
    exitcode = EX_UNAVAILABLE;
 
1026
    exitcode = EXIT_FAILURE;
1670
1027
    goto end;
1671
1028
  }
1672
1029
  
1673
1030
  sigemptyset(&sigterm_action.sa_mask);
1674
1031
  ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
1675
1032
  if(ret == -1){
1676
 
    perror_plus("sigaddset");
1677
 
    exitcode = EX_OSERR;
 
1033
    perror("sigaddset");
 
1034
    exitcode = EXIT_FAILURE;
1678
1035
    goto end;
1679
1036
  }
1680
1037
  ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
1681
1038
  if(ret == -1){
1682
 
    perror_plus("sigaddset");
1683
 
    exitcode = EX_OSERR;
 
1039
    perror("sigaddset");
 
1040
    exitcode = EXIT_FAILURE;
1684
1041
    goto end;
1685
1042
  }
1686
1043
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
1687
1044
  if(ret == -1){
1688
 
    perror_plus("sigaddset");
1689
 
    exitcode = EX_OSERR;
1690
 
    goto end;
1691
 
  }
1692
 
  /* Need to check if the handler is SIG_IGN before handling:
1693
 
     | [[info:libc:Initial Signal Actions]] |
1694
 
     | [[info:libc:Basic Signal Handling]]  |
1695
 
  */
1696
 
  ret = sigaction(SIGINT, NULL, &old_sigterm_action);
1697
 
  if(ret == -1){
1698
 
    perror_plus("sigaction");
1699
 
    return EX_OSERR;
1700
 
  }
1701
 
  if(old_sigterm_action.sa_handler != SIG_IGN){
1702
 
    ret = sigaction(SIGINT, &sigterm_action, NULL);
1703
 
    if(ret == -1){
1704
 
      perror_plus("sigaction");
1705
 
      exitcode = EX_OSERR;
1706
 
      goto end;
1707
 
    }
1708
 
  }
1709
 
  ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
1710
 
  if(ret == -1){
1711
 
    perror_plus("sigaction");
1712
 
    return EX_OSERR;
1713
 
  }
1714
 
  if(old_sigterm_action.sa_handler != SIG_IGN){
1715
 
    ret = sigaction(SIGHUP, &sigterm_action, NULL);
1716
 
    if(ret == -1){
1717
 
      perror_plus("sigaction");
1718
 
      exitcode = EX_OSERR;
1719
 
      goto end;
1720
 
    }
1721
 
  }
1722
 
  ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
1723
 
  if(ret == -1){
1724
 
    perror_plus("sigaction");
1725
 
    return EX_OSERR;
1726
 
  }
1727
 
  if(old_sigterm_action.sa_handler != SIG_IGN){
1728
 
    ret = sigaction(SIGTERM, &sigterm_action, NULL);
1729
 
    if(ret == -1){
1730
 
      perror_plus("sigaction");
1731
 
      exitcode = EX_OSERR;
1732
 
      goto end;
1733
 
    }
1734
 
  }
 
1045
    perror("sigaddset");
 
1046
    exitcode = EXIT_FAILURE;
 
1047
    goto end;
 
1048
  }
 
1049
  ret = sigaction(SIGTERM, &sigterm_action, &old_sigterm_action);
 
1050
  if(ret == -1){
 
1051
    perror("sigaction");
 
1052
    exitcode = EXIT_FAILURE;
 
1053
    goto end;
 
1054
  }  
1735
1055
  
1736
1056
  /* If the interface is down, bring it up */
1737
 
  if(strcmp(interface, "none") != 0){
1738
 
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1739
 
    if(if_index == 0){
1740
 
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
1741
 
      exitcode = EX_UNAVAILABLE;
1742
 
      goto end;
1743
 
    }
1744
 
    
1745
 
    if(quit_now){
1746
 
      goto end;
1747
 
    }
1748
 
    
1749
 
    /* Re-raise priviliges */
1750
 
    errno = 0;
1751
 
    ret = seteuid(0);
1752
 
    if(ret == -1){
1753
 
      perror_plus("seteuid");
1754
 
    }
1755
 
    
 
1057
  if(interface[0] != '\0'){
1756
1058
#ifdef __linux__
1757
1059
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1758
 
       messages about the network interface to mess up the prompt */
 
1060
       messages to mess up the prompt */
1759
1061
    ret = klogctl(8, NULL, 5);
1760
1062
    bool restore_loglevel = true;
1761
1063
    if(ret == -1){
1762
1064
      restore_loglevel = false;
1763
 
      perror_plus("klogctl");
 
1065
      perror("klogctl");
1764
1066
    }
1765
1067
#endif  /* __linux__ */
1766
1068
    
1767
1069
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1768
1070
    if(sd < 0){
1769
 
      perror_plus("socket");
1770
 
      exitcode = EX_OSERR;
 
1071
      perror("socket");
 
1072
      exitcode = EXIT_FAILURE;
1771
1073
#ifdef __linux__
1772
1074
      if(restore_loglevel){
1773
1075
        ret = klogctl(7, NULL, 0);
1774
1076
        if(ret == -1){
1775
 
          perror_plus("klogctl");
 
1077
          perror("klogctl");
1776
1078
        }
1777
1079
      }
1778
1080
#endif  /* __linux__ */
1779
 
      /* Lower privileges */
1780
 
      errno = 0;
1781
 
      ret = seteuid(uid);
1782
 
      if(ret == -1){
1783
 
        perror_plus("seteuid");
1784
 
      }
1785
1081
      goto end;
1786
1082
    }
1787
1083
    strcpy(network.ifr_name, interface);
1788
1084
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
1789
1085
    if(ret == -1){
1790
 
      perror_plus("ioctl SIOCGIFFLAGS");
 
1086
      perror("ioctl SIOCGIFFLAGS");
1791
1087
#ifdef __linux__
1792
1088
      if(restore_loglevel){
1793
1089
        ret = klogctl(7, NULL, 0);
1794
1090
        if(ret == -1){
1795
 
          perror_plus("klogctl");
 
1091
          perror("klogctl");
1796
1092
        }
1797
1093
      }
1798
1094
#endif  /* __linux__ */
1799
 
      exitcode = EX_OSERR;
1800
 
      /* Lower privileges */
1801
 
      errno = 0;
1802
 
      ret = seteuid(uid);
1803
 
      if(ret == -1){
1804
 
        perror_plus("seteuid");
1805
 
      }
 
1095
      exitcode = EXIT_FAILURE;
1806
1096
      goto end;
1807
1097
    }
1808
1098
    if((network.ifr_flags & IFF_UP) == 0){
1809
1099
      network.ifr_flags |= IFF_UP;
1810
 
      take_down_interface = true;
1811
1100
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1812
1101
      if(ret == -1){
1813
 
        take_down_interface = false;
1814
 
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1815
 
        exitcode = EX_OSERR;
 
1102
        perror("ioctl SIOCSIFFLAGS");
 
1103
        exitcode = EXIT_FAILURE;
1816
1104
#ifdef __linux__
1817
1105
        if(restore_loglevel){
1818
1106
          ret = klogctl(7, NULL, 0);
1819
1107
          if(ret == -1){
1820
 
            perror_plus("klogctl");
 
1108
            perror("klogctl");
1821
1109
          }
1822
1110
        }
1823
1111
#endif  /* __linux__ */
1824
 
        /* Lower privileges */
1825
 
        errno = 0;
1826
 
        ret = seteuid(uid);
1827
 
        if(ret == -1){
1828
 
          perror_plus("seteuid");
1829
 
        }
1830
1112
        goto end;
1831
1113
      }
1832
1114
    }
1833
 
    /* Sleep checking until interface is running.
1834
 
       Check every 0.25s, up to total time of delay */
 
1115
    /* sleep checking until interface is running */
1835
1116
    for(int i=0; i < delay * 4; i++){
1836
1117
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1837
1118
      if(ret == -1){
1838
 
        perror_plus("ioctl SIOCGIFFLAGS");
 
1119
        perror("ioctl SIOCGIFFLAGS");
1839
1120
      } else if(network.ifr_flags & IFF_RUNNING){
1840
1121
        break;
1841
1122
      }
1842
1123
      struct timespec sleeptime = { .tv_nsec = 250000000 };
1843
1124
      ret = nanosleep(&sleeptime, NULL);
1844
1125
      if(ret == -1 and errno != EINTR){
1845
 
        perror_plus("nanosleep");
 
1126
        perror("nanosleep");
1846
1127
      }
1847
1128
    }
1848
 
    if(not take_down_interface){
1849
 
      /* We won't need the socket anymore */
1850
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1851
 
      if(ret == -1){
1852
 
        perror_plus("close");
1853
 
      }
 
1129
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1130
    if(ret == -1){
 
1131
      perror("close");
1854
1132
    }
1855
1133
#ifdef __linux__
1856
1134
    if(restore_loglevel){
1857
1135
      /* Restores kernel loglevel to default */
1858
1136
      ret = klogctl(7, NULL, 0);
1859
1137
      if(ret == -1){
1860
 
        perror_plus("klogctl");
 
1138
        perror("klogctl");
1861
1139
      }
1862
1140
    }
1863
1141
#endif  /* __linux__ */
1864
 
    /* Lower privileges */
1865
 
    errno = 0;
1866
 
    if(take_down_interface){
1867
 
      /* Lower privileges */
1868
 
      ret = seteuid(uid);
1869
 
      if(ret == -1){
1870
 
        perror_plus("seteuid");
1871
 
      }
1872
 
    } else {
1873
 
      /* Lower privileges permanently */
1874
 
      ret = setuid(uid);
1875
 
      if(ret == -1){
1876
 
        perror_plus("setuid");
1877
 
      }
1878
 
    }
1879
 
  }
1880
 
  
1881
 
  if(quit_now){
1882
 
    goto end;
 
1142
  }
 
1143
  
 
1144
  uid = getuid();
 
1145
  gid = getgid();
 
1146
  
 
1147
  errno = 0;
 
1148
  setgid(gid);
 
1149
  if(ret == -1){
 
1150
    perror("setgid");
 
1151
  }
 
1152
  
 
1153
  ret = setuid(uid);
 
1154
  if(ret == -1){
 
1155
    perror("setuid");
1883
1156
  }
1884
1157
  
1885
1158
  ret = init_gnutls_global(pubkey, seckey);
1886
1159
  if(ret == -1){
1887
1160
    fprintf(stderr, "init_gnutls_global failed\n");
1888
 
    exitcode = EX_UNAVAILABLE;
 
1161
    exitcode = EXIT_FAILURE;
1889
1162
    goto end;
1890
1163
  } else {
1891
1164
    gnutls_initialized = true;
1892
1165
  }
1893
1166
  
1894
 
  if(quit_now){
1895
 
    goto end;
1896
 
  }
1897
 
  
1898
1167
  if(mkdtemp(tempdir) == NULL){
1899
 
    perror_plus("mkdtemp");
 
1168
    perror("mkdtemp");
1900
1169
    goto end;
1901
1170
  }
1902
1171
  tempdir_created = true;
1903
1172
  
1904
 
  if(quit_now){
1905
 
    goto end;
1906
 
  }
1907
 
  
1908
1173
  if(not init_gpgme(pubkey, seckey, tempdir)){
1909
1174
    fprintf(stderr, "init_gpgme failed\n");
1910
 
    exitcode = EX_UNAVAILABLE;
 
1175
    exitcode = EXIT_FAILURE;
1911
1176
    goto end;
1912
1177
  } else {
1913
1178
    gpgme_initialized = true;
1914
1179
  }
1915
1180
  
1916
 
  if(quit_now){
1917
 
    goto end;
 
1181
  if(interface[0] != '\0'){
 
1182
    if_index = (AvahiIfIndex) if_nametoindex(interface);
 
1183
    if(if_index == 0){
 
1184
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
 
1185
      exitcode = EXIT_FAILURE;
 
1186
      goto end;
 
1187
    }
1918
1188
  }
1919
1189
  
1920
1190
  if(connect_to != NULL){
1923
1193
    char *address = strrchr(connect_to, ':');
1924
1194
    if(address == NULL){
1925
1195
      fprintf(stderr, "No colon in address\n");
1926
 
      exitcode = EX_USAGE;
1927
 
      goto end;
1928
 
    }
1929
 
    
1930
 
    if(quit_now){
1931
 
      goto end;
1932
 
    }
1933
 
    
 
1196
      exitcode = EXIT_FAILURE;
 
1197
      goto end;
 
1198
    }
1934
1199
    uint16_t port;
1935
1200
    errno = 0;
1936
1201
    tmpmax = strtoimax(address+1, &tmp, 10);
1937
1202
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
1938
1203
       or tmpmax != (uint16_t)tmpmax){
1939
1204
      fprintf(stderr, "Bad port number\n");
1940
 
      exitcode = EX_USAGE;
1941
 
      goto end;
1942
 
    }
1943
 
  
1944
 
    if(quit_now){
1945
 
      goto end;
1946
 
    }
1947
 
    
 
1205
      exitcode = EXIT_FAILURE;
 
1206
      goto end;
 
1207
    }
1948
1208
    port = (uint16_t)tmpmax;
1949
1209
    *address = '\0';
 
1210
    address = connect_to;
1950
1211
    /* Colon in address indicates IPv6 */
1951
1212
    int af;
1952
 
    if(strchr(connect_to, ':') != NULL){
 
1213
    if(strchr(address, ':') != NULL){
1953
1214
      af = AF_INET6;
1954
 
      /* Accept [] around IPv6 address - see RFC 5952 */
1955
 
      if(connect_to[0] == '[' and address[-1] == ']')
1956
 
        {
1957
 
          connect_to++;
1958
 
          address[-1] = '\0';
1959
 
        }
1960
1215
    } else {
1961
1216
      af = AF_INET;
1962
1217
    }
1963
 
    address = connect_to;
1964
 
    
1965
 
    if(quit_now){
1966
 
      goto end;
1967
 
    }
1968
 
    
1969
 
    while(not quit_now){
1970
 
      ret = start_mandos_communication(address, port, if_index, af);
1971
 
      if(quit_now or ret == 0){
1972
 
        break;
1973
 
      }
1974
 
      if(debug){
1975
 
        fprintf(stderr, "Retrying in %d seconds\n",
1976
 
                (int)retry_interval);
1977
 
      }
1978
 
      sleep((int)retry_interval);
1979
 
    }
1980
 
    
1981
 
    if (not quit_now){
 
1218
    ret = start_mandos_communication(address, port, if_index, af);
 
1219
    if(ret < 0){
 
1220
      exitcode = EXIT_FAILURE;
 
1221
    } else {
1982
1222
      exitcode = EXIT_SUCCESS;
1983
1223
    }
 
1224
    goto end;
 
1225
  }
1984
1226
    
1985
 
    goto end;
1986
 
  }
1987
 
  
1988
 
  if(quit_now){
1989
 
    goto end;
1990
 
  }
1991
 
  
1992
1227
  {
1993
1228
    AvahiServerConfig config;
1994
1229
    /* Do not publish any local Zeroconf records */
2011
1246
  if(mc.server == NULL){
2012
1247
    fprintf(stderr, "Failed to create Avahi server: %s\n",
2013
1248
            avahi_strerror(error));
2014
 
    exitcode = EX_UNAVAILABLE;
2015
 
    goto end;
2016
 
  }
2017
 
  
2018
 
  if(quit_now){
 
1249
    exitcode = EXIT_FAILURE;
2019
1250
    goto end;
2020
1251
  }
2021
1252
  
2026
1257
  if(sb == NULL){
2027
1258
    fprintf(stderr, "Failed to create service browser: %s\n",
2028
1259
            avahi_strerror(avahi_server_errno(mc.server)));
2029
 
    exitcode = EX_UNAVAILABLE;
2030
 
    goto end;
2031
 
  }
2032
 
  
2033
 
  if(quit_now){
 
1260
    exitcode = EXIT_FAILURE;
2034
1261
    goto end;
2035
1262
  }
2036
1263
  
2039
1266
  if(debug){
2040
1267
    fprintf(stderr, "Starting Avahi loop search\n");
2041
1268
  }
2042
 
 
2043
 
  ret = avahi_loop_with_timeout(mc.simple_poll,
2044
 
                                (int)(retry_interval * 1000));
2045
 
  if(debug){
2046
 
    fprintf(stderr, "avahi_loop_with_timeout exited %s\n",
2047
 
            (ret == 0) ? "successfully" : "with error");
2048
 
  }
 
1269
  
 
1270
  avahi_simple_poll_loop(mc.simple_poll);
2049
1271
  
2050
1272
 end:
2051
1273
  
2072
1294
  if(gpgme_initialized){
2073
1295
    gpgme_release(mc.ctx);
2074
1296
  }
2075
 
 
2076
 
  /* Cleans up the circular linked list of Mandos servers the client
2077
 
     has seen */
2078
 
  if(mc.current_server != NULL){
2079
 
    mc.current_server->prev->next = NULL;
2080
 
    while(mc.current_server != NULL){
2081
 
      server *next = mc.current_server->next;
2082
 
      free(mc.current_server);
2083
 
      mc.current_server = next;
2084
 
    }
2085
 
  }
2086
 
  
2087
 
  /* XXX run network hooks "stop" here  */
2088
 
  
2089
 
  /* Take down the network interface */
2090
 
  if(take_down_interface){
2091
 
    /* Re-raise priviliges */
2092
 
    errno = 0;
2093
 
    ret = seteuid(0);
2094
 
    if(ret == -1){
2095
 
      perror_plus("seteuid");
2096
 
    }
2097
 
    if(geteuid() == 0){
2098
 
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
2099
 
      if(ret == -1){
2100
 
        perror_plus("ioctl SIOCGIFFLAGS");
2101
 
      } else if(network.ifr_flags & IFF_UP) {
2102
 
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
2103
 
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
2104
 
        if(ret == -1){
2105
 
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
2106
 
        }
2107
 
      }
2108
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
2109
 
      if(ret == -1){
2110
 
        perror_plus("close");
2111
 
      }
2112
 
      /* Lower privileges permanently */
2113
 
      errno = 0;
2114
 
      ret = setuid(uid);
2115
 
      if(ret == -1){
2116
 
        perror_plus("setuid");
2117
 
      }
2118
 
    }
2119
 
  }
2120
 
  
2121
 
  /* Removes the GPGME temp directory and all files inside */
 
1297
  
 
1298
  /* Removes the temp directory used by GPGME */
2122
1299
  if(tempdir_created){
2123
 
    struct dirent **direntries = NULL;
2124
 
    struct dirent *direntry = NULL;
2125
 
    int numentries = scandir(tempdir, &direntries, notdotentries,
2126
 
                             alphasort);
2127
 
    if (numentries > 0){
2128
 
      for(int i = 0; i < numentries; i++){
2129
 
        direntry = direntries[i];
 
1300
    DIR *d;
 
1301
    struct dirent *direntry;
 
1302
    d = opendir(tempdir);
 
1303
    if(d == NULL){
 
1304
      if(errno != ENOENT){
 
1305
        perror("opendir");
 
1306
      }
 
1307
    } else {
 
1308
      while(true){
 
1309
        direntry = readdir(d);
 
1310
        if(direntry == NULL){
 
1311
          break;
 
1312
        }
 
1313
        /* Skip "." and ".." */
 
1314
        if(direntry->d_name[0] == '.'
 
1315
           and (direntry->d_name[1] == '\0'
 
1316
                or (direntry->d_name[1] == '.'
 
1317
                    and direntry->d_name[2] == '\0'))){
 
1318
          continue;
 
1319
        }
2130
1320
        char *fullname = NULL;
2131
1321
        ret = asprintf(&fullname, "%s/%s", tempdir,
2132
1322
                       direntry->d_name);
2133
1323
        if(ret < 0){
2134
 
          perror_plus("asprintf");
 
1324
          perror("asprintf");
2135
1325
          continue;
2136
1326
        }
2137
1327
        ret = remove(fullname);
2141
1331
        }
2142
1332
        free(fullname);
2143
1333
      }
2144
 
    }
2145
 
 
2146
 
    /* need to clean even if 0 because man page doesn't specify */
2147
 
    free(direntries);
2148
 
    if (numentries == -1){
2149
 
      perror_plus("scandir");
 
1334
      closedir(d);
2150
1335
    }
2151
1336
    ret = rmdir(tempdir);
2152
1337
    if(ret == -1 and errno != ENOENT){
2153
 
      perror_plus("rmdir");
2154
 
    }
2155
 
  }
2156
 
  
2157
 
  if(quit_now){
2158
 
    sigemptyset(&old_sigterm_action.sa_mask);
2159
 
    old_sigterm_action.sa_handler = SIG_DFL;
2160
 
    ret = (int)TEMP_FAILURE_RETRY(sigaction(signal_received,
2161
 
                                            &old_sigterm_action,
2162
 
                                            NULL));
2163
 
    if(ret == -1){
2164
 
      perror_plus("sigaction");
2165
 
    }
2166
 
    do {
2167
 
      ret = raise(signal_received);
2168
 
    } while(ret != 0 and errno == EINTR);
2169
 
    if(ret != 0){
2170
 
      perror_plus("raise");
2171
 
      abort();
2172
 
    }
2173
 
    TEMP_FAILURE_RETRY(pause());
 
1338
      perror("rmdir");
 
1339
    }
2174
1340
  }
2175
1341
  
2176
1342
  return exitcode;