/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: 2014-06-08 17:36:33 UTC
  • mto: (237.7.272 trunk)
  • mto: This revision was merged to the branch mainline in revision 317.
  • Revision ID: teddy@recompile.se-20140608173633-miqqavhoxym10uiz
Fix mandos server "--servicename" option, broken since 1.6.4.

* mandos (initlogger): Make "syslogger" a global variable again.

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-2012 Teddy Hogeborn
13
 
 * Copyright © 2008-2012 Björn Påhlsson
 
12
 * Copyright © 2008-2014 Teddy Hogeborn
 
13
 * Copyright © 2008-2014 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
32
32
/* Needed by GPGME, specifically gpgme_data_seek() */
33
33
#ifndef _LARGEFILE_SOURCE
34
34
#define _LARGEFILE_SOURCE
35
 
#endif
 
35
#endif  /* not _LARGEFILE_SOURCE */
36
36
#ifndef _FILE_OFFSET_BITS
37
37
#define _FILE_OFFSET_BITS 64
38
 
#endif
 
38
#endif  /* not _FILE_OFFSET_BITS */
39
39
 
40
40
#define _GNU_SOURCE             /* TEMP_FAILURE_RETRY(), asprintf() */
41
41
 
42
42
#include <stdio.h>              /* fprintf(), stderr, fwrite(),
43
 
                                   stdout, ferror(), remove() */
 
43
                                   stdout, ferror() */
44
44
#include <stdint.h>             /* uint16_t, uint32_t, intptr_t */
45
45
#include <stddef.h>             /* NULL, size_t, ssize_t */
46
46
#include <stdlib.h>             /* free(), EXIT_SUCCESS, srand(),
55
55
                                   opendir(), DIR */
56
56
#include <sys/stat.h>           /* open(), S_ISREG */
57
57
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
58
 
                                   inet_pton(), connect() */
59
 
#include <fcntl.h>              /* open() */
 
58
                                   inet_pton(), connect(),
 
59
                                   getnameinfo() */
 
60
#include <fcntl.h>              /* open(), unlinkat() */
60
61
#include <dirent.h>             /* opendir(), struct dirent, readdir()
61
62
                                 */
62
63
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
63
64
                                   strtoimax() */
64
 
#include <assert.h>             /* assert() */
65
65
#include <errno.h>              /* perror(), errno,
66
66
                                   program_invocation_short_name */
67
67
#include <time.h>               /* nanosleep(), time(), sleep() */
73
73
                                */
74
74
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
75
75
                                   getuid(), getgid(), seteuid(),
76
 
                                   setgid(), pause(), _exit() */
77
 
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
 
76
                                   setgid(), pause(), _exit(),
 
77
                                   unlinkat() */
 
78
#include <arpa/inet.h>          /* inet_pton(), htons() */
78
79
#include <iso646.h>             /* not, or, and */
79
80
#include <argp.h>               /* struct argp_option, error_t, struct
80
81
                                   argp_state, struct argp,
92
93
                                   argz_delete(), argz_append(),
93
94
                                   argz_stringify(), argz_add(),
94
95
                                   argz_count() */
 
96
#include <netdb.h>              /* getnameinfo(), NI_NUMERICHOST,
 
97
                                   EAI_SYSTEM, gai_strerror() */
95
98
 
96
99
#ifdef __linux__
97
100
#include <sys/klog.h>           /* klogctl() */
139
142
static const char sys_class_net[] = "/sys/class/net";
140
143
char *connect_to = NULL;
141
144
const char *hookdir = HOOKDIR;
 
145
int hookdir_fd = -1;
142
146
uid_t uid = 65534;
143
147
gid_t gid = 65534;
144
148
 
145
149
/* Doubly linked list that need to be circularly linked when used */
146
150
typedef struct server{
147
151
  const char *ip;
148
 
  uint16_t port;
 
152
  in_port_t port;
149
153
  AvahiIfIndex if_index;
150
154
  int af;
151
155
  struct timespec last_seen;
155
159
 
156
160
/* Used for passing in values through the Avahi callback functions */
157
161
typedef struct {
158
 
  AvahiSimplePoll *simple_poll;
159
162
  AvahiServer *server;
160
163
  gnutls_certificate_credentials_t cred;
161
164
  unsigned int dh_bits;
163
166
  const char *priority;
164
167
  gpgme_ctx_t ctx;
165
168
  server *current_server;
 
169
  char *interfaces;
 
170
  size_t interfaces_size;
166
171
} mandos_context;
167
172
 
168
 
/* global context so signal handler can reach it*/
169
 
mandos_context mc = { .simple_poll = NULL, .server = NULL,
170
 
                      .dh_bits = 1024, .priority = "SECURE256"
171
 
                      ":!CTYPE-X.509:+CTYPE-OPENPGP",
172
 
                      .current_server = NULL };
 
173
/* global so signal handler can reach it*/
 
174
AvahiSimplePoll *simple_poll;
173
175
 
174
176
sig_atomic_t quit_now = 0;
175
177
int signal_received = 0;
183
185
  perror(print_text);
184
186
}
185
187
 
186
 
__attribute__((format (gnu_printf, 2, 3)))
 
188
__attribute__((format (gnu_printf, 2, 3), nonnull))
187
189
int fprintf_plus(FILE *stream, const char *format, ...){
188
190
  va_list ap;
189
191
  va_start (ap, format);
190
192
  
191
193
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ",
192
194
                             program_invocation_short_name));
193
 
  return TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
 
195
  return (int)TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
194
196
}
195
197
 
196
198
/*
198
200
 * bytes. "buffer_capacity" is how much is currently allocated,
199
201
 * "buffer_length" is how much is already used.
200
202
 */
 
203
__attribute__((nonnull, warn_unused_result))
201
204
size_t incbuffer(char **buffer, size_t buffer_length,
202
205
                 size_t buffer_capacity){
203
206
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
204
 
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
205
 
    if(buffer == NULL){
 
207
    char *new_buf = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
 
208
    if(new_buf == NULL){
 
209
      int old_errno = errno;
 
210
      free(*buffer);
 
211
      errno = old_errno;
 
212
      *buffer = NULL;
206
213
      return 0;
207
214
    }
 
215
    *buffer = new_buf;
208
216
    buffer_capacity += BUFFER_SIZE;
209
217
  }
210
218
  return buffer_capacity;
211
219
}
212
220
 
213
221
/* Add server to set of servers to retry periodically */
214
 
bool add_server(const char *ip, uint16_t port, AvahiIfIndex if_index,
215
 
                int af){
 
222
__attribute__((nonnull, warn_unused_result))
 
223
bool add_server(const char *ip, in_port_t port, AvahiIfIndex if_index,
 
224
                int af, server **current_server){
216
225
  int ret;
217
226
  server *new_server = malloc(sizeof(server));
218
227
  if(new_server == NULL){
227
236
    perror_plus("strdup");
228
237
    return false;
229
238
  }
 
239
  ret = clock_gettime(CLOCK_MONOTONIC, &(new_server->last_seen));
 
240
  if(ret == -1){
 
241
    perror_plus("clock_gettime");
 
242
    return false;
 
243
  }
230
244
  /* Special case of first server */
231
 
  if (mc.current_server == NULL){
 
245
  if(*current_server == NULL){
232
246
    new_server->next = new_server;
233
247
    new_server->prev = new_server;
234
 
    mc.current_server = new_server;
235
 
  /* Place the new server last in the list */
 
248
    *current_server = new_server;
236
249
  } else {
237
 
    new_server->next = mc.current_server;
238
 
    new_server->prev = mc.current_server->prev;
 
250
    /* Place the new server last in the list */
 
251
    new_server->next = *current_server;
 
252
    new_server->prev = (*current_server)->prev;
239
253
    new_server->prev->next = new_server;
240
 
    mc.current_server->prev = new_server;
241
 
  }
242
 
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
243
 
  if(ret == -1){
244
 
    perror_plus("clock_gettime");
245
 
    return false;
 
254
    (*current_server)->prev = new_server;
246
255
  }
247
256
  return true;
248
257
}
250
259
/* 
251
260
 * Initialize GPGME.
252
261
 */
253
 
static bool init_gpgme(const char *seckey, const char *pubkey,
254
 
                       const char *tempdir){
 
262
__attribute__((nonnull, warn_unused_result))
 
263
static bool init_gpgme(const char * const seckey,
 
264
                       const char * const pubkey,
 
265
                       const char * const tempdir,
 
266
                       mandos_context *mc){
255
267
  gpgme_error_t rc;
256
268
  gpgme_engine_info_t engine_info;
257
269
  
258
 
  
259
270
  /*
260
271
   * Helper function to insert pub and seckey to the engine keyring.
261
272
   */
262
 
  bool import_key(const char *filename){
 
273
  bool import_key(const char * const filename){
263
274
    int ret;
264
275
    int fd;
265
276
    gpgme_data_t pgp_data;
277
288
      return false;
278
289
    }
279
290
    
280
 
    rc = gpgme_op_import(mc.ctx, pgp_data);
 
291
    rc = gpgme_op_import(mc->ctx, pgp_data);
281
292
    if(rc != GPG_ERR_NO_ERROR){
282
293
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
283
294
                   gpgme_strsource(rc), gpgme_strerror(rc));
327
338
  }
328
339
  
329
340
  /* Create new GPGME "context" */
330
 
  rc = gpgme_new(&(mc.ctx));
 
341
  rc = gpgme_new(&(mc->ctx));
331
342
  if(rc != GPG_ERR_NO_ERROR){
332
343
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
333
344
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
346
357
 * Decrypt OpenPGP data.
347
358
 * Returns -1 on error
348
359
 */
 
360
__attribute__((nonnull, warn_unused_result))
349
361
static ssize_t pgp_packet_decrypt(const char *cryptotext,
350
362
                                  size_t crypto_size,
351
 
                                  char **plaintext){
 
363
                                  char **plaintext,
 
364
                                  mandos_context *mc){
352
365
  gpgme_data_t dh_crypto, dh_plain;
353
366
  gpgme_error_t rc;
354
367
  ssize_t ret;
380
393
  
381
394
  /* Decrypt data from the cryptotext data buffer to the plaintext
382
395
     data buffer */
383
 
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
 
396
  rc = gpgme_op_decrypt(mc->ctx, dh_crypto, dh_plain);
384
397
  if(rc != GPG_ERR_NO_ERROR){
385
398
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
386
399
                 gpgme_strsource(rc), gpgme_strerror(rc));
387
400
    plaintext_length = -1;
388
401
    if(debug){
389
402
      gpgme_decrypt_result_t result;
390
 
      result = gpgme_op_decrypt_result(mc.ctx);
 
403
      result = gpgme_op_decrypt_result(mc->ctx);
391
404
      if(result == NULL){
392
405
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
393
406
      } else {
470
483
  return plaintext_length;
471
484
}
472
485
 
473
 
static const char * safer_gnutls_strerror(int value){
474
 
  const char *ret = gnutls_strerror(value); /* Spurious warning from
475
 
                                               -Wunreachable-code */
 
486
__attribute__((warn_unused_result))
 
487
static const char *safer_gnutls_strerror(int value){
 
488
  const char *ret = gnutls_strerror(value);
476
489
  if(ret == NULL)
477
490
    ret = "(unknown)";
478
491
  return ret;
479
492
}
480
493
 
481
494
/* GnuTLS log function callback */
 
495
__attribute__((nonnull))
482
496
static void debuggnutls(__attribute__((unused)) int level,
483
497
                        const char* string){
484
498
  fprintf_plus(stderr, "GnuTLS: %s", string);
485
499
}
486
500
 
 
501
__attribute__((nonnull, warn_unused_result))
487
502
static int init_gnutls_global(const char *pubkeyfilename,
488
 
                              const char *seckeyfilename){
 
503
                              const char *seckeyfilename,
 
504
                              mandos_context *mc){
489
505
  int ret;
490
506
  
491
507
  if(debug){
508
524
  }
509
525
  
510
526
  /* OpenPGP credentials */
511
 
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
 
527
  ret = gnutls_certificate_allocate_credentials(&mc->cred);
512
528
  if(ret != GNUTLS_E_SUCCESS){
513
529
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
514
530
                 safer_gnutls_strerror(ret));
524
540
  }
525
541
  
526
542
  ret = gnutls_certificate_set_openpgp_key_file
527
 
    (mc.cred, pubkeyfilename, seckeyfilename,
 
543
    (mc->cred, pubkeyfilename, seckeyfilename,
528
544
     GNUTLS_OPENPGP_FMT_BASE64);
529
545
  if(ret != GNUTLS_E_SUCCESS){
530
546
    fprintf_plus(stderr,
536
552
  }
537
553
  
538
554
  /* GnuTLS server initialization */
539
 
  ret = gnutls_dh_params_init(&mc.dh_params);
 
555
  ret = gnutls_dh_params_init(&mc->dh_params);
540
556
  if(ret != GNUTLS_E_SUCCESS){
541
557
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
542
558
                 " initialization: %s\n",
543
559
                 safer_gnutls_strerror(ret));
544
560
    goto globalfail;
545
561
  }
546
 
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
 
562
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
547
563
  if(ret != GNUTLS_E_SUCCESS){
548
564
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
549
565
                 safer_gnutls_strerror(ret));
550
566
    goto globalfail;
551
567
  }
552
568
  
553
 
  gnutls_certificate_set_dh_params(mc.cred, mc.dh_params);
 
569
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
554
570
  
555
571
  return 0;
556
572
  
557
573
 globalfail:
558
574
  
559
 
  gnutls_certificate_free_credentials(mc.cred);
 
575
  gnutls_certificate_free_credentials(mc->cred);
560
576
  gnutls_global_deinit();
561
 
  gnutls_dh_params_deinit(mc.dh_params);
 
577
  gnutls_dh_params_deinit(mc->dh_params);
562
578
  return -1;
563
579
}
564
580
 
565
 
static int init_gnutls_session(gnutls_session_t *session){
 
581
__attribute__((nonnull, warn_unused_result))
 
582
static int init_gnutls_session(gnutls_session_t *session,
 
583
                               mandos_context *mc){
566
584
  int ret;
567
585
  /* GnuTLS session creation */
568
586
  do {
580
598
  {
581
599
    const char *err;
582
600
    do {
583
 
      ret = gnutls_priority_set_direct(*session, mc.priority, &err);
 
601
      ret = gnutls_priority_set_direct(*session, mc->priority, &err);
584
602
      if(quit_now){
585
603
        gnutls_deinit(*session);
586
604
        return -1;
597
615
  
598
616
  do {
599
617
    ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
600
 
                                 mc.cred);
 
618
                                 mc->cred);
601
619
    if(quit_now){
602
620
      gnutls_deinit(*session);
603
621
      return -1;
613
631
  /* ignore client certificate if any. */
614
632
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
615
633
  
616
 
  gnutls_dh_set_prime_bits(*session, mc.dh_bits);
 
634
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
617
635
  
618
636
  return 0;
619
637
}
623
641
                      __attribute__((unused)) const char *txt){}
624
642
 
625
643
/* Called when a Mandos server is found */
626
 
static int start_mandos_communication(const char *ip, uint16_t port,
 
644
__attribute__((nonnull, warn_unused_result))
 
645
static int start_mandos_communication(const char *ip, in_port_t port,
627
646
                                      AvahiIfIndex if_index,
628
 
                                      int af){
 
647
                                      int af, mandos_context *mc){
629
648
  int ret, tcp_sd = -1;
630
649
  ssize_t sret;
631
 
  union {
632
 
    struct sockaddr_in in;
633
 
    struct sockaddr_in6 in6;
634
 
  } to;
 
650
  struct sockaddr_storage to;
635
651
  char *buffer = NULL;
636
652
  char *decrypted_buffer = NULL;
637
653
  size_t buffer_length = 0;
661
677
    return -1;
662
678
  }
663
679
  
664
 
  ret = init_gnutls_session(&session);
 
680
  /* If the interface is specified and we have a list of interfaces */
 
681
  if(if_index != AVAHI_IF_UNSPEC and mc->interfaces != NULL){
 
682
    /* Check if the interface is one of the interfaces we are using */
 
683
    bool match = false;
 
684
    {
 
685
      char *interface = NULL;
 
686
      while((interface=argz_next(mc->interfaces, mc->interfaces_size,
 
687
                                 interface))){
 
688
        if(if_nametoindex(interface) == (unsigned int)if_index){
 
689
          match = true;
 
690
          break;
 
691
        }
 
692
      }
 
693
    }
 
694
    if(not match){
 
695
      /* This interface does not match any in the list, so we don't
 
696
         connect to the server */
 
697
      if(debug){
 
698
        char interface[IF_NAMESIZE];
 
699
        if(if_indextoname((unsigned int)if_index, interface) == NULL){
 
700
          perror_plus("if_indextoname");
 
701
        } else {
 
702
          fprintf_plus(stderr, "Skipping server on non-used interface"
 
703
                       " \"%s\"\n",
 
704
                       if_indextoname((unsigned int)if_index,
 
705
                                      interface));
 
706
        }
 
707
      }
 
708
      return -1;
 
709
    }
 
710
  }
 
711
  
 
712
  ret = init_gnutls_session(&session, mc);
665
713
  if(ret != 0){
666
714
    return -1;
667
715
  }
668
716
  
669
717
  if(debug){
670
718
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
671
 
                 PRIu16 "\n", ip, port);
 
719
                 PRIuMAX "\n", ip, (uintmax_t)port);
672
720
  }
673
721
  
674
722
  tcp_sd = socket(pf, SOCK_STREAM, 0);
686
734
  
687
735
  memset(&to, 0, sizeof(to));
688
736
  if(af == AF_INET6){
689
 
    to.in6.sin6_family = (sa_family_t)af;
690
 
    ret = inet_pton(af, ip, &to.in6.sin6_addr);
 
737
    ((struct sockaddr_in6 *)&to)->sin6_family = (sa_family_t)af;
 
738
    ret = inet_pton(af, ip, &((struct sockaddr_in6 *)&to)->sin6_addr);
691
739
  } else {                      /* IPv4 */
692
 
    to.in.sin_family = (sa_family_t)af;
693
 
    ret = inet_pton(af, ip, &to.in.sin_addr);
 
740
    ((struct sockaddr_in *)&to)->sin_family = (sa_family_t)af;
 
741
    ret = inet_pton(af, ip, &((struct sockaddr_in *)&to)->sin_addr);
694
742
  }
695
743
  if(ret < 0 ){
696
744
    int e = errno;
705
753
    goto mandos_end;
706
754
  }
707
755
  if(af == AF_INET6){
708
 
    to.in6.sin6_port = htons(port); /* Spurious warnings from
709
 
                                       -Wconversion and
710
 
                                       -Wunreachable-code */
711
 
    
712
 
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
713
 
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
714
 
                                -Wunreachable-code*/
 
756
    ((struct sockaddr_in6 *)&to)->sin6_port = htons(port);
 
757
    if(IN6_IS_ADDR_LINKLOCAL
 
758
       (&((struct sockaddr_in6 *)&to)->sin6_addr)){
715
759
      if(if_index == AVAHI_IF_UNSPEC){
716
760
        fprintf_plus(stderr, "An IPv6 link-local address is"
717
761
                     " incomplete without a network interface\n");
719
763
        goto mandos_end;
720
764
      }
721
765
      /* Set the network interface number as scope */
722
 
      to.in6.sin6_scope_id = (uint32_t)if_index;
 
766
      ((struct sockaddr_in6 *)&to)->sin6_scope_id = (uint32_t)if_index;
723
767
    }
724
768
  } else {
725
 
    to.in.sin_port = htons(port); /* Spurious warnings from
726
 
                                     -Wconversion and
727
 
                                     -Wunreachable-code */
 
769
    ((struct sockaddr_in *)&to)->sin_port = htons(port);
728
770
  }
729
771
  
730
772
  if(quit_now){
738
780
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
739
781
        perror_plus("if_indextoname");
740
782
      } else {
741
 
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIu16
742
 
                     "\n", ip, interface, port);
 
783
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIuMAX
 
784
                     "\n", ip, interface, (uintmax_t)port);
743
785
      }
744
786
    } else {
745
 
      fprintf_plus(stderr, "Connection to: %s, port %" PRIu16 "\n",
746
 
                   ip, port);
 
787
      fprintf_plus(stderr, "Connection to: %s, port %" PRIuMAX "\n",
 
788
                   ip, (uintmax_t)port);
747
789
    }
748
790
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
749
791
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
750
 
    const char *pcret;
751
792
    if(af == AF_INET6){
752
 
      pcret = inet_ntop(af, &(to.in6.sin6_addr), addrstr,
753
 
                        sizeof(addrstr));
 
793
      ret = getnameinfo((struct sockaddr *)&to,
 
794
                        sizeof(struct sockaddr_in6),
 
795
                        addrstr, sizeof(addrstr), NULL, 0,
 
796
                        NI_NUMERICHOST);
754
797
    } else {
755
 
      pcret = inet_ntop(af, &(to.in.sin_addr), addrstr,
756
 
                        sizeof(addrstr));
 
798
      ret = getnameinfo((struct sockaddr *)&to,
 
799
                        sizeof(struct sockaddr_in),
 
800
                        addrstr, sizeof(addrstr), NULL, 0,
 
801
                        NI_NUMERICHOST);
757
802
    }
758
 
    if(pcret == NULL){
759
 
      perror_plus("inet_ntop");
760
 
    } else {
761
 
      if(strcmp(addrstr, ip) != 0){
762
 
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
763
 
      }
 
803
    if(ret == EAI_SYSTEM){
 
804
      perror_plus("getnameinfo");
 
805
    } else if(ret != 0) {
 
806
      fprintf_plus(stderr, "getnameinfo: %s", gai_strerror(ret));
 
807
    } else if(strcmp(addrstr, ip) != 0){
 
808
      fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
764
809
    }
765
810
  }
766
811
  
770
815
  }
771
816
  
772
817
  if(af == AF_INET6){
773
 
    ret = connect(tcp_sd, &to.in6, sizeof(to));
 
818
    ret = connect(tcp_sd, (struct sockaddr *)&to,
 
819
                  sizeof(struct sockaddr_in6));
774
820
  } else {
775
 
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
 
821
    ret = connect(tcp_sd, (struct sockaddr *)&to, /* IPv4 */
 
822
                  sizeof(struct sockaddr_in));
776
823
  }
777
824
  if(ret < 0){
778
 
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
 
825
    if((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
779
826
      int e = errno;
780
827
      perror_plus("connect");
781
828
      errno = e;
942
989
  if(buffer_length > 0){
943
990
    ssize_t decrypted_buffer_size;
944
991
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
945
 
                                               &decrypted_buffer);
 
992
                                               &decrypted_buffer, mc);
946
993
    if(decrypted_buffer_size >= 0){
947
994
      
948
995
      written = 0;
996
1043
  return retval;
997
1044
}
998
1045
 
 
1046
__attribute__((nonnull))
999
1047
static void resolve_callback(AvahiSServiceResolver *r,
1000
1048
                             AvahiIfIndex interface,
1001
1049
                             AvahiProtocol proto,
1009
1057
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
1010
1058
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
1011
1059
                             flags,
1012
 
                             AVAHI_GCC_UNUSED void* userdata){
1013
 
  assert(r);
 
1060
                             void *mc){
 
1061
  if(r == NULL){
 
1062
    return;
 
1063
  }
1014
1064
  
1015
1065
  /* Called whenever a service has been resolved successfully or
1016
1066
     timed out */
1025
1075
    fprintf_plus(stderr, "(Avahi Resolver) Failed to resolve service "
1026
1076
                 "'%s' of type '%s' in domain '%s': %s\n", name, type,
1027
1077
                 domain,
1028
 
                 avahi_strerror(avahi_server_errno(mc.server)));
 
1078
                 avahi_strerror(avahi_server_errno
 
1079
                                (((mandos_context*)mc)->server)));
1029
1080
    break;
1030
1081
    
1031
1082
  case AVAHI_RESOLVER_FOUND:
1037
1088
                     PRIdMAX ") on port %" PRIu16 "\n", name,
1038
1089
                     host_name, ip, (intmax_t)interface, port);
1039
1090
      }
1040
 
      int ret = start_mandos_communication(ip, port, interface,
1041
 
                                           avahi_proto_to_af(proto));
 
1091
      int ret = start_mandos_communication(ip, (in_port_t)port,
 
1092
                                           interface,
 
1093
                                           avahi_proto_to_af(proto),
 
1094
                                           mc);
1042
1095
      if(ret == 0){
1043
 
        avahi_simple_poll_quit(mc.simple_poll);
 
1096
        avahi_simple_poll_quit(simple_poll);
1044
1097
      } else {
1045
 
        if(not add_server(ip, port, interface,
1046
 
                          avahi_proto_to_af(proto))){
 
1098
        if(not add_server(ip, (in_port_t)port, interface,
 
1099
                          avahi_proto_to_af(proto),
 
1100
                          &((mandos_context*)mc)->current_server)){
1047
1101
          fprintf_plus(stderr, "Failed to add server \"%s\" to server"
1048
1102
                       " list\n", name);
1049
1103
        }
1062
1116
                            const char *domain,
1063
1117
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
1064
1118
                            flags,
1065
 
                            AVAHI_GCC_UNUSED void* userdata){
1066
 
  assert(b);
 
1119
                            void *mc){
 
1120
  if(b == NULL){
 
1121
    return;
 
1122
  }
1067
1123
  
1068
1124
  /* Called whenever a new services becomes available on the LAN or
1069
1125
     is removed from the LAN */
1077
1133
  case AVAHI_BROWSER_FAILURE:
1078
1134
    
1079
1135
    fprintf_plus(stderr, "(Avahi browser) %s\n",
1080
 
                 avahi_strerror(avahi_server_errno(mc.server)));
1081
 
    avahi_simple_poll_quit(mc.simple_poll);
 
1136
                 avahi_strerror(avahi_server_errno
 
1137
                                (((mandos_context*)mc)->server)));
 
1138
    avahi_simple_poll_quit(simple_poll);
1082
1139
    return;
1083
1140
    
1084
1141
  case AVAHI_BROWSER_NEW:
1087
1144
       the callback function is called the Avahi server will free the
1088
1145
       resolver for us. */
1089
1146
    
1090
 
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
1091
 
                                    name, type, domain, protocol, 0,
1092
 
                                    resolve_callback, NULL) == NULL)
 
1147
    if(avahi_s_service_resolver_new(((mandos_context*)mc)->server,
 
1148
                                    interface, protocol, name, type,
 
1149
                                    domain, protocol, 0,
 
1150
                                    resolve_callback, mc) == NULL)
1093
1151
      fprintf_plus(stderr, "Avahi: Failed to resolve service '%s':"
1094
1152
                   " %s\n", name,
1095
 
                   avahi_strerror(avahi_server_errno(mc.server)));
 
1153
                   avahi_strerror(avahi_server_errno
 
1154
                                  (((mandos_context*)mc)->server)));
1096
1155
    break;
1097
1156
    
1098
1157
  case AVAHI_BROWSER_REMOVE:
1117
1176
  signal_received = sig;
1118
1177
  int old_errno = errno;
1119
1178
  /* set main loop to exit */
1120
 
  if(mc.simple_poll != NULL){
1121
 
    avahi_simple_poll_quit(mc.simple_poll);
 
1179
  if(simple_poll != NULL){
 
1180
    avahi_simple_poll_quit(simple_poll);
1122
1181
  }
1123
1182
  errno = old_errno;
1124
1183
}
1125
1184
 
 
1185
__attribute__((nonnull, warn_unused_result))
1126
1186
bool get_flags(const char *ifname, struct ifreq *ifr){
1127
1187
  int ret;
1128
1188
  error_t ret_errno;
1147
1207
  return true;
1148
1208
}
1149
1209
 
 
1210
__attribute__((nonnull, warn_unused_result))
1150
1211
bool good_flags(const char *ifname, const struct ifreq *ifr){
1151
1212
  
1152
1213
  /* Reject the loopback device */
1194
1255
 * corresponds to an acceptable network device.
1195
1256
 * (This function is passed to scandir(3) as a filter function.)
1196
1257
 */
 
1258
__attribute__((nonnull, warn_unused_result))
1197
1259
int good_interface(const struct dirent *if_entry){
1198
1260
  if(if_entry->d_name[0] == '.'){
1199
1261
    return 0;
1217
1279
/* 
1218
1280
 * This function determines if a network interface is up.
1219
1281
 */
 
1282
__attribute__((nonnull, warn_unused_result))
1220
1283
bool interface_is_up(const char *interface){
1221
1284
  struct ifreq ifr;
1222
1285
  if(not get_flags(interface, &ifr)){
1233
1296
/* 
1234
1297
 * This function determines if a network interface is running
1235
1298
 */
 
1299
__attribute__((nonnull, warn_unused_result))
1236
1300
bool interface_is_running(const char *interface){
1237
1301
  struct ifreq ifr;
1238
1302
  if(not get_flags(interface, &ifr)){
1246
1310
  return (bool)(ifr.ifr_flags & IFF_RUNNING);
1247
1311
}
1248
1312
 
 
1313
__attribute__((nonnull, pure, warn_unused_result))
1249
1314
int notdotentries(const struct dirent *direntry){
1250
1315
  /* Skip "." and ".." */
1251
1316
  if(direntry->d_name[0] == '.'
1258
1323
}
1259
1324
 
1260
1325
/* Is this directory entry a runnable program? */
 
1326
__attribute__((nonnull, warn_unused_result))
1261
1327
int runnable_hook(const struct dirent *direntry){
1262
1328
  int ret;
1263
1329
  size_t sret;
1271
1337
  sret = strspn(direntry->d_name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1272
1338
                "abcdefghijklmnopqrstuvwxyz"
1273
1339
                "0123456789"
1274
 
                "_-");
 
1340
                "_.-");
1275
1341
  if((direntry->d_name)[sret] != '\0'){
1276
1342
    /* Contains non-allowed characters */
1277
1343
    if(debug){
1281
1347
    return 0;
1282
1348
  }
1283
1349
  
1284
 
  char *fullname = NULL;
1285
 
  ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
1286
 
  if(ret < 0){
1287
 
    perror_plus("asprintf");
1288
 
    return 0;
1289
 
  }
1290
 
  
1291
 
  ret = stat(fullname, &st);
 
1350
  ret = fstatat(hookdir_fd, direntry->d_name, &st, 0);
1292
1351
  if(ret == -1){
1293
1352
    if(debug){
1294
1353
      perror_plus("Could not stat hook");
1318
1377
  return 1;
1319
1378
}
1320
1379
 
1321
 
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
 
1380
__attribute__((nonnull, warn_unused_result))
 
1381
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval,
 
1382
                            mandos_context *mc){
1322
1383
  int ret;
1323
1384
  struct timespec now;
1324
1385
  struct timespec waited_time;
1325
1386
  intmax_t block_time;
1326
1387
  
1327
1388
  while(true){
1328
 
    if(mc.current_server == NULL){
1329
 
      if (debug){
 
1389
    if(mc->current_server == NULL){
 
1390
      if(debug){
1330
1391
        fprintf_plus(stderr, "Wait until first server is found."
1331
1392
                     " No timeout!\n");
1332
1393
      }
1333
1394
      ret = avahi_simple_poll_iterate(s, -1);
1334
1395
    } else {
1335
 
      if (debug){
 
1396
      if(debug){
1336
1397
        fprintf_plus(stderr, "Check current_server if we should run"
1337
1398
                     " it, or wait\n");
1338
1399
      }
1345
1406
      /* Calculating in ms how long time between now and server
1346
1407
         who we visted longest time ago. Now - last seen.  */
1347
1408
      waited_time.tv_sec = (now.tv_sec
1348
 
                            - mc.current_server->last_seen.tv_sec);
 
1409
                            - mc->current_server->last_seen.tv_sec);
1349
1410
      waited_time.tv_nsec = (now.tv_nsec
1350
 
                             - mc.current_server->last_seen.tv_nsec);
 
1411
                             - mc->current_server->last_seen.tv_nsec);
1351
1412
      /* total time is 10s/10,000ms.
1352
1413
         Converting to s from ms by dividing by 1,000,
1353
1414
         and ns to ms by dividing by 1,000,000. */
1355
1416
                     - ((intmax_t)waited_time.tv_sec * 1000))
1356
1417
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1357
1418
      
1358
 
      if (debug){
 
1419
      if(debug){
1359
1420
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
1360
1421
                     block_time);
1361
1422
      }
1362
1423
      
1363
1424
      if(block_time <= 0){
1364
 
        ret = start_mandos_communication(mc.current_server->ip,
1365
 
                                         mc.current_server->port,
1366
 
                                         mc.current_server->if_index,
1367
 
                                         mc.current_server->af);
 
1425
        ret = start_mandos_communication(mc->current_server->ip,
 
1426
                                         mc->current_server->port,
 
1427
                                         mc->current_server->if_index,
 
1428
                                         mc->current_server->af, mc);
1368
1429
        if(ret == 0){
1369
 
          avahi_simple_poll_quit(mc.simple_poll);
 
1430
          avahi_simple_poll_quit(s);
1370
1431
          return 0;
1371
1432
        }
1372
1433
        ret = clock_gettime(CLOCK_MONOTONIC,
1373
 
                            &mc.current_server->last_seen);
 
1434
                            &mc->current_server->last_seen);
1374
1435
        if(ret == -1){
1375
1436
          perror_plus("clock_gettime");
1376
1437
          return -1;
1377
1438
        }
1378
 
        mc.current_server = mc.current_server->next;
 
1439
        mc->current_server = mc->current_server->next;
1379
1440
        block_time = 0;         /* Call avahi to find new Mandos
1380
1441
                                   servers, but don't block */
1381
1442
      }
1383
1444
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1384
1445
    }
1385
1446
    if(ret != 0){
1386
 
      if (ret > 0 or errno != EINTR){
 
1447
      if(ret > 0 or errno != EINTR){
1387
1448
        return (ret != 1) ? ret : 0;
1388
1449
      }
1389
1450
    }
1391
1452
}
1392
1453
 
1393
1454
/* Set effective uid to 0, return errno */
 
1455
__attribute__((warn_unused_result))
1394
1456
error_t raise_privileges(void){
1395
1457
  error_t old_errno = errno;
1396
1458
  error_t ret_errno = 0;
1403
1465
}
1404
1466
 
1405
1467
/* Set effective and real user ID to 0.  Return errno. */
 
1468
__attribute__((warn_unused_result))
1406
1469
error_t raise_privileges_permanently(void){
1407
1470
  error_t old_errno = errno;
1408
1471
  error_t ret_errno = raise_privileges();
1419
1482
}
1420
1483
 
1421
1484
/* Set effective user ID to unprivileged saved user ID */
 
1485
__attribute__((warn_unused_result))
1422
1486
error_t lower_privileges(void){
1423
1487
  error_t old_errno = errno;
1424
1488
  error_t ret_errno = 0;
1431
1495
}
1432
1496
 
1433
1497
/* Lower privileges permanently */
 
1498
__attribute__((warn_unused_result))
1434
1499
error_t lower_privileges_permanently(void){
1435
1500
  error_t old_errno = errno;
1436
1501
  error_t ret_errno = 0;
1442
1507
  return ret_errno;
1443
1508
}
1444
1509
 
1445
 
bool run_network_hooks(const char *mode, const char *interface,
 
1510
__attribute__((nonnull))
 
1511
void run_network_hooks(const char *mode, const char *interface,
1446
1512
                       const float delay){
1447
1513
  struct dirent **direntries;
1448
 
  struct dirent *direntry;
1449
 
  int ret;
1450
 
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
1451
 
                         alphasort);
 
1514
  if(hookdir_fd == -1){
 
1515
    hookdir_fd = open(hookdir, O_RDONLY);
 
1516
    if(hookdir_fd == -1){
 
1517
      if(errno == ENOENT){
 
1518
        if(debug){
 
1519
          fprintf_plus(stderr, "Network hook directory \"%s\" not"
 
1520
                       " found\n", hookdir);
 
1521
        }
 
1522
      } else {
 
1523
        perror_plus("open");
 
1524
      }
 
1525
      return;
 
1526
    }
 
1527
  }
 
1528
#ifdef __GLIBC__
 
1529
#if __GLIBC_PREREQ(2, 15)
 
1530
  int numhooks = scandirat(hookdir_fd, ".", &direntries,
 
1531
                           runnable_hook, alphasort);
 
1532
#else  /* not __GLIBC_PREREQ(2, 15) */
 
1533
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
 
1534
                         alphasort);
 
1535
#endif  /* not __GLIBC_PREREQ(2, 15) */
 
1536
#else   /* not __GLIBC__ */
 
1537
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
 
1538
                         alphasort);
 
1539
#endif  /* not __GLIBC__ */
1452
1540
  if(numhooks == -1){
1453
1541
    perror_plus("scandir");
1454
 
  } else {
1455
 
    int devnull = open("/dev/null", O_RDONLY);
1456
 
    for(int i = 0; i < numhooks; i++){
1457
 
      direntry = direntries[i];
1458
 
      char *fullname = NULL;
1459
 
      ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
1460
 
      if(ret < 0){
 
1542
    return;
 
1543
  }
 
1544
  struct dirent *direntry;
 
1545
  int ret;
 
1546
  int devnull = open("/dev/null", O_RDONLY);
 
1547
  for(int i = 0; i < numhooks; i++){
 
1548
    direntry = direntries[i];
 
1549
    if(debug){
 
1550
      fprintf_plus(stderr, "Running network hook \"%s\"\n",
 
1551
                   direntry->d_name);
 
1552
    }
 
1553
    pid_t hook_pid = fork();
 
1554
    if(hook_pid == 0){
 
1555
      /* Child */
 
1556
      /* Raise privileges */
 
1557
      if(raise_privileges_permanently() != 0){
 
1558
        perror_plus("Failed to raise privileges");
 
1559
        _exit(EX_NOPERM);
 
1560
      }
 
1561
      /* Set group */
 
1562
      errno = 0;
 
1563
      ret = setgid(0);
 
1564
      if(ret == -1){
 
1565
        perror_plus("setgid");
 
1566
        _exit(EX_NOPERM);
 
1567
      }
 
1568
      /* Reset supplementary groups */
 
1569
      errno = 0;
 
1570
      ret = setgroups(0, NULL);
 
1571
      if(ret == -1){
 
1572
        perror_plus("setgroups");
 
1573
        _exit(EX_NOPERM);
 
1574
      }
 
1575
      ret = dup2(devnull, STDIN_FILENO);
 
1576
      if(ret == -1){
 
1577
        perror_plus("dup2(devnull, STDIN_FILENO)");
 
1578
        _exit(EX_OSERR);
 
1579
      }
 
1580
      ret = close(devnull);
 
1581
      if(ret == -1){
 
1582
        perror_plus("close");
 
1583
        _exit(EX_OSERR);
 
1584
      }
 
1585
      ret = dup2(STDERR_FILENO, STDOUT_FILENO);
 
1586
      if(ret == -1){
 
1587
        perror_plus("dup2(STDERR_FILENO, STDOUT_FILENO)");
 
1588
        _exit(EX_OSERR);
 
1589
      }
 
1590
      ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
 
1591
      if(ret == -1){
 
1592
        perror_plus("setenv");
 
1593
        _exit(EX_OSERR);
 
1594
      }
 
1595
      ret = setenv("DEVICE", interface, 1);
 
1596
      if(ret == -1){
 
1597
        perror_plus("setenv");
 
1598
        _exit(EX_OSERR);
 
1599
      }
 
1600
      ret = setenv("VERBOSITY", debug ? "1" : "0", 1);
 
1601
      if(ret == -1){
 
1602
        perror_plus("setenv");
 
1603
        _exit(EX_OSERR);
 
1604
      }
 
1605
      ret = setenv("MODE", mode, 1);
 
1606
      if(ret == -1){
 
1607
        perror_plus("setenv");
 
1608
        _exit(EX_OSERR);
 
1609
      }
 
1610
      char *delaystring;
 
1611
      ret = asprintf(&delaystring, "%f", (double)delay);
 
1612
      if(ret == -1){
1461
1613
        perror_plus("asprintf");
1462
 
        continue;
1463
 
      }
1464
 
      if(debug){
1465
 
        fprintf_plus(stderr, "Running network hook \"%s\"\n",
1466
 
                     direntry->d_name);
1467
 
      }
1468
 
      pid_t hook_pid = fork();
1469
 
      if(hook_pid == 0){
1470
 
        /* Child */
1471
 
        /* Raise privileges */
1472
 
        raise_privileges_permanently();
1473
 
        /* Set group */
1474
 
        errno = 0;
1475
 
        ret = setgid(0);
1476
 
        if(ret == -1){
1477
 
          perror_plus("setgid");
1478
 
        }
1479
 
        /* Reset supplementary groups */
1480
 
        errno = 0;
1481
 
        ret = setgroups(0, NULL);
1482
 
        if(ret == -1){
1483
 
          perror_plus("setgroups");
1484
 
        }
1485
 
        dup2(devnull, STDIN_FILENO);
1486
 
        close(devnull);
1487
 
        dup2(STDERR_FILENO, STDOUT_FILENO);
1488
 
        ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
1489
 
        if(ret == -1){
1490
 
          perror_plus("setenv");
1491
 
          _exit(EX_OSERR);
1492
 
        }
1493
 
        ret = setenv("DEVICE", interface, 1);
1494
 
        if(ret == -1){
1495
 
          perror_plus("setenv");
1496
 
          _exit(EX_OSERR);
1497
 
        }
1498
 
        ret = setenv("VERBOSITY", debug ? "1" : "0", 1);
1499
 
        if(ret == -1){
1500
 
          perror_plus("setenv");
1501
 
          _exit(EX_OSERR);
1502
 
        }
1503
 
        ret = setenv("MODE", mode, 1);
1504
 
        if(ret == -1){
1505
 
          perror_plus("setenv");
1506
 
          _exit(EX_OSERR);
1507
 
        }
1508
 
        char *delaystring;
1509
 
        ret = asprintf(&delaystring, "%f", delay);
1510
 
        if(ret == -1){
1511
 
          perror_plus("asprintf");
1512
 
          _exit(EX_OSERR);
1513
 
        }
1514
 
        ret = setenv("DELAY", delaystring, 1);
1515
 
        if(ret == -1){
1516
 
          free(delaystring);
1517
 
          perror_plus("setenv");
1518
 
          _exit(EX_OSERR);
1519
 
        }
 
1614
        _exit(EX_OSERR);
 
1615
      }
 
1616
      ret = setenv("DELAY", delaystring, 1);
 
1617
      if(ret == -1){
1520
1618
        free(delaystring);
1521
 
        if(connect_to != NULL){
1522
 
          ret = setenv("CONNECT", connect_to, 1);
1523
 
          if(ret == -1){
1524
 
            perror_plus("setenv");
1525
 
            _exit(EX_OSERR);
1526
 
          }
1527
 
        }
1528
 
        if(execl(fullname, direntry->d_name, mode, NULL) == -1){
1529
 
          perror_plus("execl");
1530
 
          _exit(EXIT_FAILURE);
1531
 
        }
 
1619
        perror_plus("setenv");
 
1620
        _exit(EX_OSERR);
 
1621
      }
 
1622
      free(delaystring);
 
1623
      if(connect_to != NULL){
 
1624
        ret = setenv("CONNECT", connect_to, 1);
 
1625
        if(ret == -1){
 
1626
          perror_plus("setenv");
 
1627
          _exit(EX_OSERR);
 
1628
        }
 
1629
      }
 
1630
      int hook_fd = openat(hookdir_fd, direntry->d_name, O_RDONLY);
 
1631
      if(hook_fd == -1){
 
1632
        perror_plus("openat");
 
1633
        _exit(EXIT_FAILURE);
 
1634
      }
 
1635
      if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
 
1636
        perror_plus("close");
 
1637
        _exit(EXIT_FAILURE);
 
1638
      }
 
1639
      if(fexecve(hook_fd, (char *const []){ direntry->d_name, NULL },
 
1640
                 environ) == -1){
 
1641
        perror_plus("fexecve");
 
1642
        _exit(EXIT_FAILURE);
 
1643
      }
 
1644
    } else {
 
1645
      int status;
 
1646
      if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
 
1647
        perror_plus("waitpid");
 
1648
        continue;
 
1649
      }
 
1650
      if(WIFEXITED(status)){
 
1651
        if(WEXITSTATUS(status) != 0){
 
1652
          fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
 
1653
                       " with status %d\n", direntry->d_name,
 
1654
                       WEXITSTATUS(status));
 
1655
          continue;
 
1656
        }
 
1657
      } else if(WIFSIGNALED(status)){
 
1658
        fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
 
1659
                     " signal %d\n", direntry->d_name,
 
1660
                     WTERMSIG(status));
 
1661
        continue;
1532
1662
      } else {
1533
 
        int status;
1534
 
        if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
1535
 
          perror_plus("waitpid");
1536
 
          free(fullname);
1537
 
          continue;
1538
 
        }
1539
 
        if(WIFEXITED(status)){
1540
 
          if(WEXITSTATUS(status) != 0){
1541
 
            fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
1542
 
                         " with status %d\n", direntry->d_name,
1543
 
                         WEXITSTATUS(status));
1544
 
            free(fullname);
1545
 
            continue;
1546
 
          }
1547
 
        } else if(WIFSIGNALED(status)){
1548
 
          fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
1549
 
                       " signal %d\n", direntry->d_name,
1550
 
                       WTERMSIG(status));
1551
 
          free(fullname);
1552
 
          continue;
1553
 
        } else {
1554
 
          fprintf_plus(stderr, "Warning: network hook \"%s\""
1555
 
                       " crashed\n", direntry->d_name);
1556
 
          free(fullname);
1557
 
          continue;
1558
 
        }
1559
 
      }
1560
 
      free(fullname);
1561
 
      if(debug){
1562
 
        fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
1563
 
                     direntry->d_name);
1564
 
      }
1565
 
    }
1566
 
    close(devnull);
1567
 
  }
1568
 
  return true;
 
1663
        fprintf_plus(stderr, "Warning: network hook \"%s\""
 
1664
                     " crashed\n", direntry->d_name);
 
1665
        continue;
 
1666
      }
 
1667
    }
 
1668
    if(debug){
 
1669
      fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
 
1670
                   direntry->d_name);
 
1671
    }
 
1672
  }
 
1673
  if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
 
1674
    perror_plus("close");
 
1675
  } else {
 
1676
    hookdir_fd = -1;
 
1677
  }
 
1678
  close(devnull);
1569
1679
}
1570
1680
 
 
1681
__attribute__((nonnull, warn_unused_result))
1571
1682
error_t bring_up_interface(const char *const interface,
1572
1683
                           const float delay){
1573
 
  int sd = -1;
1574
1684
  error_t old_errno = errno;
1575
 
  error_t ret_errno = 0;
1576
 
  int ret, ret_setflags;
 
1685
  int ret;
1577
1686
  struct ifreq network;
1578
1687
  unsigned int if_index = if_nametoindex(interface);
1579
1688
  if(if_index == 0){
1588
1697
  }
1589
1698
  
1590
1699
  if(not interface_is_up(interface)){
1591
 
    if(not get_flags(interface, &network) and debug){
 
1700
    error_t ret_errno = 0, ioctl_errno = 0;
 
1701
    if(not get_flags(interface, &network)){
1592
1702
      ret_errno = errno;
1593
1703
      fprintf_plus(stderr, "Failed to get flags for interface "
1594
1704
                   "\"%s\"\n", interface);
 
1705
      errno = old_errno;
1595
1706
      return ret_errno;
1596
1707
    }
1597
 
    network.ifr_flags |= IFF_UP;
 
1708
    network.ifr_flags |= IFF_UP; /* set flag */
1598
1709
    
1599
 
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1600
 
    if(sd < 0){
 
1710
    int sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1711
    if(sd == -1){
1601
1712
      ret_errno = errno;
1602
1713
      perror_plus("socket");
1603
1714
      errno = old_errno;
1604
1715
      return ret_errno;
1605
1716
    }
1606
 
  
 
1717
    
1607
1718
    if(quit_now){
1608
 
      close(sd);
 
1719
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1720
      if(ret == -1){
 
1721
        perror_plus("close");
 
1722
      }
1609
1723
      errno = old_errno;
1610
1724
      return EINTR;
1611
1725
    }
1615
1729
                   interface);
1616
1730
    }
1617
1731
    
1618
 
    /* Raise priviliges */
1619
 
    raise_privileges();
 
1732
    /* Raise privileges */
 
1733
    ret_errno = raise_privileges();
 
1734
    if(ret_errno != 0){
 
1735
      perror_plus("Failed to raise privileges");
 
1736
    }
1620
1737
    
1621
1738
#ifdef __linux__
1622
 
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1623
 
       messages about the network interface to mess up the prompt */
1624
 
    int ret_linux = klogctl(8, NULL, 5);
1625
 
    bool restore_loglevel = true;
1626
 
    if(ret_linux == -1){
1627
 
      restore_loglevel = false;
1628
 
      perror_plus("klogctl");
 
1739
    int ret_linux;
 
1740
    bool restore_loglevel = false;
 
1741
    if(ret_errno == 0){
 
1742
      /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
 
1743
         messages about the network interface to mess up the prompt */
 
1744
      ret_linux = klogctl(8, NULL, 5);
 
1745
      if(ret_linux == -1){
 
1746
        perror_plus("klogctl");
 
1747
      } else {
 
1748
        restore_loglevel = true;
 
1749
      }
1629
1750
    }
1630
1751
#endif  /* __linux__ */
1631
 
    ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
1632
 
    ret_errno = errno;
 
1752
    int ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
 
1753
    ioctl_errno = errno;
1633
1754
#ifdef __linux__
1634
1755
    if(restore_loglevel){
1635
1756
      ret_linux = klogctl(7, NULL, 0);
1639
1760
    }
1640
1761
#endif  /* __linux__ */
1641
1762
    
1642
 
    /* Lower privileges */
1643
 
    lower_privileges();
 
1763
    /* If raise_privileges() succeeded above */
 
1764
    if(ret_errno == 0){
 
1765
      /* Lower privileges */
 
1766
      ret_errno = lower_privileges();
 
1767
      if(ret_errno != 0){
 
1768
        errno = ret_errno;
 
1769
        perror_plus("Failed to lower privileges");
 
1770
      }
 
1771
    }
1644
1772
    
1645
1773
    /* Close the socket */
1646
1774
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
1649
1777
    }
1650
1778
    
1651
1779
    if(ret_setflags == -1){
1652
 
      errno = ret_errno;
 
1780
      errno = ioctl_errno;
1653
1781
      perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1654
1782
      errno = old_errno;
1655
 
      return ret_errno;
 
1783
      return ioctl_errno;
1656
1784
    }
1657
1785
  } else if(debug){
1658
1786
    fprintf_plus(stderr, "Interface \"%s\" is already up; good\n",
1676
1804
  return 0;
1677
1805
}
1678
1806
 
 
1807
__attribute__((nonnull, warn_unused_result))
1679
1808
error_t take_down_interface(const char *const interface){
1680
 
  int sd = -1;
1681
1809
  error_t old_errno = errno;
1682
 
  error_t ret_errno = 0;
1683
 
  int ret, ret_setflags;
1684
1810
  struct ifreq network;
1685
1811
  unsigned int if_index = if_nametoindex(interface);
1686
1812
  if(if_index == 0){
1689
1815
    return ENXIO;
1690
1816
  }
1691
1817
  if(interface_is_up(interface)){
 
1818
    error_t ret_errno = 0, ioctl_errno = 0;
1692
1819
    if(not get_flags(interface, &network) and debug){
1693
1820
      ret_errno = errno;
1694
1821
      fprintf_plus(stderr, "Failed to get flags for interface "
1695
1822
                   "\"%s\"\n", interface);
 
1823
      errno = old_errno;
1696
1824
      return ret_errno;
1697
1825
    }
1698
1826
    network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
1699
1827
    
1700
 
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1701
 
    if(sd < 0){
 
1828
    int sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1829
    if(sd == -1){
1702
1830
      ret_errno = errno;
1703
1831
      perror_plus("socket");
1704
1832
      errno = old_errno;
1710
1838
                   interface);
1711
1839
    }
1712
1840
    
1713
 
    /* Raise priviliges */
1714
 
    raise_privileges();
1715
 
    
1716
 
    ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
1717
 
    ret_errno = errno;
1718
 
    
1719
 
    /* Lower privileges */
1720
 
    lower_privileges();
 
1841
    /* Raise privileges */
 
1842
    ret_errno = raise_privileges();
 
1843
    if(ret_errno != 0){
 
1844
      perror_plus("Failed to raise privileges");
 
1845
    }
 
1846
    
 
1847
    int ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
 
1848
    ioctl_errno = errno;
 
1849
    
 
1850
    /* If raise_privileges() succeeded above */
 
1851
    if(ret_errno == 0){
 
1852
      /* Lower privileges */
 
1853
      ret_errno = lower_privileges();
 
1854
      if(ret_errno != 0){
 
1855
        errno = ret_errno;
 
1856
        perror_plus("Failed to lower privileges");
 
1857
      }
 
1858
    }
1721
1859
    
1722
1860
    /* Close the socket */
1723
 
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1861
    int ret = (int)TEMP_FAILURE_RETRY(close(sd));
1724
1862
    if(ret == -1){
1725
1863
      perror_plus("close");
1726
1864
    }
1727
1865
    
1728
1866
    if(ret_setflags == -1){
1729
 
      errno = ret_errno;
 
1867
      errno = ioctl_errno;
1730
1868
      perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
1731
1869
      errno = old_errno;
1732
 
      return ret_errno;
 
1870
      return ioctl_errno;
1733
1871
    }
1734
1872
  } else if(debug){
1735
1873
    fprintf_plus(stderr, "Interface \"%s\" is already down; odd\n",
1741
1879
}
1742
1880
 
1743
1881
int main(int argc, char *argv[]){
 
1882
  mandos_context mc = { .server = NULL, .dh_bits = 1024,
 
1883
                        .priority = "SECURE256:!CTYPE-X.509:"
 
1884
                        "+CTYPE-OPENPGP", .current_server = NULL,
 
1885
                        .interfaces = NULL, .interfaces_size = 0 };
1744
1886
  AvahiSServiceBrowser *sb = NULL;
1745
1887
  error_t ret_errno;
1746
1888
  int ret;
1747
1889
  intmax_t tmpmax;
1748
1890
  char *tmp;
1749
1891
  int exitcode = EXIT_SUCCESS;
1750
 
  char *interfaces = NULL;
1751
 
  size_t interfaces_size = 0;
1752
1892
  char *interfaces_to_take_down = NULL;
1753
1893
  size_t interfaces_to_take_down_size = 0;
1754
 
  char tempdir[] = "/tmp/mandosXXXXXX";
1755
 
  bool tempdir_created = false;
 
1894
  char run_tempdir[] = "/run/tmp/mandosXXXXXX";
 
1895
  char old_tempdir[] = "/tmp/mandosXXXXXX";
 
1896
  char *tempdir = NULL;
1756
1897
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1757
1898
  const char *seckey = PATHDIR "/" SECKEY;
1758
1899
  const char *pubkey = PATHDIR "/" PUBKEY;
1759
1900
  char *interfaces_hooks = NULL;
1760
 
  size_t interfaces_hooks_size = 0;
1761
1901
  
1762
1902
  bool gnutls_initialized = false;
1763
1903
  bool gpgme_initialized = false;
1854
1994
        connect_to = arg;
1855
1995
        break;
1856
1996
      case 'i':                 /* --interface */
1857
 
        ret_errno = argz_add_sep(&interfaces, &interfaces_size, arg,
1858
 
                                 (int)',');
 
1997
        ret_errno = argz_add_sep(&mc.interfaces, &mc.interfaces_size,
 
1998
                                 arg, (int)',');
1859
1999
        if(ret_errno != 0){
1860
2000
          argp_error(state, "%s", strerror(ret_errno));
1861
2001
        }
1941
2081
    /* Work around Debian bug #633582:
1942
2082
       <http://bugs.debian.org/633582> */
1943
2083
    
1944
 
    /* Re-raise priviliges */
1945
 
    if(raise_privileges() == 0){
 
2084
    /* Re-raise privileges */
 
2085
    ret_errno = raise_privileges();
 
2086
    if(ret_errno != 0){
 
2087
      errno = ret_errno;
 
2088
      perror_plus("Failed to raise privileges");
 
2089
    } else {
1946
2090
      struct stat st;
1947
2091
      
1948
2092
      if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
1988
2132
      }
1989
2133
    
1990
2134
      /* Lower privileges */
1991
 
      errno = 0;
1992
 
      ret = seteuid(uid);
1993
 
      if(ret == -1){
1994
 
        perror_plus("seteuid");
 
2135
      ret_errno = lower_privileges();
 
2136
      if(ret_errno != 0){
 
2137
        errno = ret_errno;
 
2138
        perror_plus("Failed to lower privileges");
1995
2139
      }
1996
2140
    }
1997
2141
  }
1998
2142
  
1999
 
  /* Remove empty interface names */
 
2143
  /* Remove invalid interface names (except "none") */
2000
2144
  {
2001
2145
    char *interface = NULL;
2002
 
    while((interface = argz_next(interfaces, interfaces_size,
 
2146
    while((interface = argz_next(mc.interfaces, mc.interfaces_size,
2003
2147
                                 interface))){
2004
 
      if(if_nametoindex(interface) == 0){
2005
 
        if(interface[0] != '\0' and strcmp(interface, "none") != 0){
 
2148
      if(strcmp(interface, "none") != 0
 
2149
         and if_nametoindex(interface) == 0){
 
2150
        if(interface[0] != '\0'){
2006
2151
          fprintf_plus(stderr, "Not using nonexisting interface"
2007
2152
                       " \"%s\"\n", interface);
2008
2153
        }
2009
 
        argz_delete(&interfaces, &interfaces_size, interface);
 
2154
        argz_delete(&mc.interfaces, &mc.interfaces_size, interface);
2010
2155
        interface = NULL;
2011
2156
      }
2012
2157
    }
2014
2159
  
2015
2160
  /* Run network hooks */
2016
2161
  {
2017
 
    ret_errno = argz_append(&interfaces_hooks, &interfaces_hooks_size,
2018
 
                            interfaces, interfaces_size);
2019
 
    if(ret_errno != 0){
2020
 
      errno = ret_errno;
2021
 
      perror_plus("argz_append");
2022
 
      goto end;
2023
 
    }
2024
 
    argz_stringify(interfaces_hooks, interfaces_hooks_size, (int)',');
2025
 
    if(not run_network_hooks("start", interfaces_hooks, delay)){
2026
 
      goto end;
2027
 
    }
 
2162
    if(mc.interfaces != NULL){
 
2163
      interfaces_hooks = malloc(mc.interfaces_size);
 
2164
      if(interfaces_hooks == NULL){
 
2165
        perror_plus("malloc");
 
2166
        goto end;
 
2167
      }
 
2168
      memcpy(interfaces_hooks, mc.interfaces, mc.interfaces_size);
 
2169
      argz_stringify(interfaces_hooks, mc.interfaces_size, (int)',');
 
2170
    }
 
2171
    run_network_hooks("start", interfaces_hooks != NULL ?
 
2172
                      interfaces_hooks : "", delay);
2028
2173
  }
2029
2174
  
2030
2175
  if(not debug){
2035
2180
     from the signal handler */
2036
2181
  /* Initialize the pseudo-RNG for Avahi */
2037
2182
  srand((unsigned int) time(NULL));
2038
 
  mc.simple_poll = avahi_simple_poll_new();
2039
 
  if(mc.simple_poll == NULL){
 
2183
  simple_poll = avahi_simple_poll_new();
 
2184
  if(simple_poll == NULL){
2040
2185
    fprintf_plus(stderr,
2041
2186
                 "Avahi: Failed to create simple poll object.\n");
2042
2187
    exitcode = EX_UNAVAILABLE;
2107
2252
  }
2108
2253
  
2109
2254
  /* If no interfaces were specified, make a list */
2110
 
  if(interfaces == NULL){
 
2255
  if(mc.interfaces == NULL){
2111
2256
    struct dirent **direntries;
2112
2257
    /* Look for any good interfaces */
2113
2258
    ret = scandir(sys_class_net, &direntries, good_interface,
2115
2260
    if(ret >= 1){
2116
2261
      /* Add all found interfaces to interfaces list */
2117
2262
      for(int i = 0; i < ret; ++i){
2118
 
        ret_errno = argz_add(&interfaces, &interfaces_size,
 
2263
        ret_errno = argz_add(&mc.interfaces, &mc.interfaces_size,
2119
2264
                             direntries[i]->d_name);
2120
2265
        if(ret_errno != 0){
 
2266
          errno = ret_errno;
2121
2267
          perror_plus("argz_add");
2122
2268
          continue;
2123
2269
        }
2135
2281
    }
2136
2282
  }
2137
2283
  
2138
 
  /* If we only got one interface, explicitly use only that one */
2139
 
  if(argz_count(interfaces, interfaces_size) == 1){
2140
 
    if(debug){
2141
 
      fprintf_plus(stderr, "Using only interface \"%s\"\n",
2142
 
                   interfaces);
2143
 
    }
2144
 
    if_index = (AvahiIfIndex)if_nametoindex(interfaces);
2145
 
  }
2146
 
  
2147
 
  /* Bring up interfaces which are down */
2148
 
  if(not (argz_count(interfaces, interfaces_size) == 1
2149
 
          and strcmp(interfaces, "none") == 0)){
 
2284
  /* Bring up interfaces which are down, and remove any "none"s */
 
2285
  {
2150
2286
    char *interface = NULL;
2151
 
    while((interface = argz_next(interfaces, interfaces_size,
 
2287
    while((interface = argz_next(mc.interfaces, mc.interfaces_size,
2152
2288
                                 interface))){
 
2289
      /* If interface name is "none", stop bringing up interfaces.
 
2290
         Also remove all instances of "none" from the list */
 
2291
      if(strcmp(interface, "none") == 0){
 
2292
        argz_delete(&mc.interfaces, &mc.interfaces_size,
 
2293
                    interface);
 
2294
        interface = NULL;
 
2295
        while((interface = argz_next(mc.interfaces,
 
2296
                                     mc.interfaces_size, interface))){
 
2297
          if(strcmp(interface, "none") == 0){
 
2298
            argz_delete(&mc.interfaces, &mc.interfaces_size,
 
2299
                        interface);
 
2300
            interface = NULL;
 
2301
          }
 
2302
        }
 
2303
        break;
 
2304
      }
2153
2305
      bool interface_was_up = interface_is_up(interface);
2154
 
      ret = bring_up_interface(interface, delay);
 
2306
      errno = bring_up_interface(interface, delay);
2155
2307
      if(not interface_was_up){
2156
 
        if(ret != 0){
2157
 
          errno = ret;
 
2308
        if(errno != 0){
2158
2309
          perror_plus("Failed to bring up interface");
2159
2310
        } else {
2160
 
          ret_errno = argz_add(&interfaces_to_take_down,
2161
 
                               &interfaces_to_take_down_size,
2162
 
                               interface);
 
2311
          errno = argz_add(&interfaces_to_take_down,
 
2312
                           &interfaces_to_take_down_size,
 
2313
                           interface);
 
2314
          if(errno != 0){
 
2315
            perror_plus("argz_add");
 
2316
          }
2163
2317
        }
2164
2318
      }
2165
2319
    }
2166
 
    free(interfaces);
2167
 
    interfaces = NULL;
2168
 
    interfaces_size = 0;
2169
2320
    if(debug and (interfaces_to_take_down == NULL)){
2170
2321
      fprintf_plus(stderr, "No interfaces were brought up\n");
2171
2322
    }
2172
2323
  }
2173
2324
  
 
2325
  /* If we only got one interface, explicitly use only that one */
 
2326
  if(argz_count(mc.interfaces, mc.interfaces_size) == 1){
 
2327
    if(debug){
 
2328
      fprintf_plus(stderr, "Using only interface \"%s\"\n",
 
2329
                   mc.interfaces);
 
2330
    }
 
2331
    if_index = (AvahiIfIndex)if_nametoindex(mc.interfaces);
 
2332
  }
 
2333
  
2174
2334
  if(quit_now){
2175
2335
    goto end;
2176
2336
  }
2177
2337
  
2178
 
  ret = init_gnutls_global(pubkey, seckey);
 
2338
  ret = init_gnutls_global(pubkey, seckey, &mc);
2179
2339
  if(ret == -1){
2180
2340
    fprintf_plus(stderr, "init_gnutls_global failed\n");
2181
2341
    exitcode = EX_UNAVAILABLE;
2188
2348
    goto end;
2189
2349
  }
2190
2350
  
2191
 
  if(mkdtemp(tempdir) == NULL){
 
2351
  /* Try /run/tmp before /tmp */
 
2352
  tempdir = mkdtemp(run_tempdir);
 
2353
  if(tempdir == NULL and errno == ENOENT){
 
2354
      if(debug){
 
2355
        fprintf_plus(stderr, "Tempdir %s did not work, trying %s\n",
 
2356
                     run_tempdir, old_tempdir);
 
2357
      }
 
2358
      tempdir = mkdtemp(old_tempdir);
 
2359
  }
 
2360
  if(tempdir == NULL){
2192
2361
    perror_plus("mkdtemp");
2193
2362
    goto end;
2194
2363
  }
2195
 
  tempdir_created = true;
2196
2364
  
2197
2365
  if(quit_now){
2198
2366
    goto end;
2199
2367
  }
2200
2368
  
2201
 
  if(not init_gpgme(pubkey, seckey, tempdir)){
 
2369
  if(not init_gpgme(pubkey, seckey, tempdir, &mc)){
2202
2370
    fprintf_plus(stderr, "init_gpgme failed\n");
2203
2371
    exitcode = EX_UNAVAILABLE;
2204
2372
    goto end;
2225
2393
      goto end;
2226
2394
    }
2227
2395
    
2228
 
    uint16_t port;
 
2396
    in_port_t port;
2229
2397
    errno = 0;
2230
2398
    tmpmax = strtoimax(address+1, &tmp, 10);
2231
2399
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
2232
 
       or tmpmax != (uint16_t)tmpmax){
 
2400
       or tmpmax != (in_port_t)tmpmax){
2233
2401
      fprintf_plus(stderr, "Bad port number\n");
2234
2402
      exitcode = EX_USAGE;
2235
2403
      goto end;
2236
2404
    }
2237
 
  
 
2405
    
2238
2406
    if(quit_now){
2239
2407
      goto end;
2240
2408
    }
2241
2409
    
2242
 
    port = (uint16_t)tmpmax;
 
2410
    port = (in_port_t)tmpmax;
2243
2411
    *address = '\0';
2244
2412
    /* Colon in address indicates IPv6 */
2245
2413
    int af;
2261
2429
    }
2262
2430
    
2263
2431
    while(not quit_now){
2264
 
      ret = start_mandos_communication(address, port, if_index, af);
 
2432
      ret = start_mandos_communication(address, port, if_index, af,
 
2433
                                       &mc);
2265
2434
      if(quit_now or ret == 0){
2266
2435
        break;
2267
2436
      }
2269
2438
        fprintf_plus(stderr, "Retrying in %d seconds\n",
2270
2439
                     (int)retry_interval);
2271
2440
      }
2272
 
      sleep((int)retry_interval);
 
2441
      sleep((unsigned int)retry_interval);
2273
2442
    }
2274
2443
    
2275
 
    if (not quit_now){
 
2444
    if(not quit_now){
2276
2445
      exitcode = EXIT_SUCCESS;
2277
2446
    }
2278
2447
    
2293
2462
    config.publish_domain = 0;
2294
2463
    
2295
2464
    /* Allocate a new server */
2296
 
    mc.server = avahi_server_new(avahi_simple_poll_get
2297
 
                                 (mc.simple_poll), &config, NULL,
2298
 
                                 NULL, &ret_errno);
 
2465
    mc.server = avahi_server_new(avahi_simple_poll_get(simple_poll),
 
2466
                                 &config, NULL, NULL, &ret_errno);
2299
2467
    
2300
2468
    /* Free the Avahi configuration data */
2301
2469
    avahi_server_config_free(&config);
2316
2484
  /* Create the Avahi service browser */
2317
2485
  sb = avahi_s_service_browser_new(mc.server, if_index,
2318
2486
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2319
 
                                   NULL, 0, browse_callback, NULL);
 
2487
                                   NULL, 0, browse_callback,
 
2488
                                   (void *)&mc);
2320
2489
  if(sb == NULL){
2321
2490
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
2322
2491
                 avahi_strerror(avahi_server_errno(mc.server)));
2333
2502
  if(debug){
2334
2503
    fprintf_plus(stderr, "Starting Avahi loop search\n");
2335
2504
  }
2336
 
 
2337
 
  ret = avahi_loop_with_timeout(mc.simple_poll,
2338
 
                                (int)(retry_interval * 1000));
 
2505
  
 
2506
  ret = avahi_loop_with_timeout(simple_poll,
 
2507
                                (int)(retry_interval * 1000), &mc);
2339
2508
  if(debug){
2340
2509
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
2341
2510
                 (ret == 0) ? "successfully" : "with error");
2348
2517
  }
2349
2518
  
2350
2519
  /* Cleanup things */
 
2520
  free(mc.interfaces);
 
2521
  
2351
2522
  if(sb != NULL)
2352
2523
    avahi_s_service_browser_free(sb);
2353
2524
  
2354
2525
  if(mc.server != NULL)
2355
2526
    avahi_server_free(mc.server);
2356
2527
  
2357
 
  if(mc.simple_poll != NULL)
2358
 
    avahi_simple_poll_free(mc.simple_poll);
 
2528
  if(simple_poll != NULL)
 
2529
    avahi_simple_poll_free(simple_poll);
2359
2530
  
2360
2531
  if(gnutls_initialized){
2361
2532
    gnutls_certificate_free_credentials(mc.cred);
2378
2549
    }
2379
2550
  }
2380
2551
  
2381
 
  /* Re-raise priviliges */
 
2552
  /* Re-raise privileges */
2382
2553
  {
2383
 
    raise_privileges();
2384
 
    
2385
 
    /* Run network hooks */
2386
 
    run_network_hooks("stop", interfaces_hooks, delay);
2387
 
    
2388
 
    /* Take down the network interfaces which were brought up */
2389
 
    {
2390
 
      char *interface = NULL;
2391
 
      while((interface=argz_next(interfaces_to_take_down,
2392
 
                                 interfaces_to_take_down_size,
2393
 
                                 interface))){
2394
 
        ret_errno = take_down_interface(interface);
2395
 
        if(ret_errno != 0){
2396
 
          errno = ret_errno;
2397
 
          perror_plus("Failed to take down interface");
2398
 
        }
2399
 
      }
2400
 
      if(debug and (interfaces_to_take_down == NULL)){
2401
 
        fprintf_plus(stderr, "No interfaces needed to be taken"
2402
 
                     " down\n");
2403
 
      }
2404
 
    }
2405
 
    
2406
 
    lower_privileges_permanently();
 
2554
    ret_errno = raise_privileges();
 
2555
    if(ret_errno != 0){
 
2556
      perror_plus("Failed to raise privileges");
 
2557
    } else {
 
2558
      
 
2559
      /* Run network hooks */
 
2560
      run_network_hooks("stop", interfaces_hooks != NULL ?
 
2561
                        interfaces_hooks : "", delay);
 
2562
      
 
2563
      /* Take down the network interfaces which were brought up */
 
2564
      {
 
2565
        char *interface = NULL;
 
2566
        while((interface=argz_next(interfaces_to_take_down,
 
2567
                                   interfaces_to_take_down_size,
 
2568
                                   interface))){
 
2569
          ret_errno = take_down_interface(interface);
 
2570
          if(ret_errno != 0){
 
2571
            errno = ret_errno;
 
2572
            perror_plus("Failed to take down interface");
 
2573
          }
 
2574
        }
 
2575
        if(debug and (interfaces_to_take_down == NULL)){
 
2576
          fprintf_plus(stderr, "No interfaces needed to be taken"
 
2577
                       " down\n");
 
2578
        }
 
2579
      }
 
2580
    }
 
2581
    
 
2582
    ret_errno = lower_privileges_permanently();
 
2583
    if(ret_errno != 0){
 
2584
      perror_plus("Failed to lower privileges permanently");
 
2585
    }
2407
2586
  }
2408
2587
  
2409
2588
  free(interfaces_to_take_down);
2410
2589
  free(interfaces_hooks);
2411
2590
  
2412
2591
  /* Removes the GPGME temp directory and all files inside */
2413
 
  if(tempdir_created){
 
2592
  if(tempdir != NULL){
2414
2593
    struct dirent **direntries = NULL;
2415
 
    struct dirent *direntry = NULL;
2416
 
    int numentries = scandir(tempdir, &direntries, notdotentries,
2417
 
                             alphasort);
2418
 
    if (numentries > 0){
2419
 
      for(int i = 0; i < numentries; i++){
2420
 
        direntry = direntries[i];
2421
 
        char *fullname = NULL;
2422
 
        ret = asprintf(&fullname, "%s/%s", tempdir,
2423
 
                       direntry->d_name);
2424
 
        if(ret < 0){
2425
 
          perror_plus("asprintf");
2426
 
          continue;
2427
 
        }
2428
 
        ret = remove(fullname);
2429
 
        if(ret == -1){
2430
 
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
2431
 
                       strerror(errno));
2432
 
        }
2433
 
        free(fullname);
 
2594
    int tempdir_fd = (int)TEMP_FAILURE_RETRY(open(tempdir, O_RDONLY |
 
2595
                                                  O_NOFOLLOW));
 
2596
    if(tempdir_fd == -1){
 
2597
      perror_plus("open");
 
2598
    } else {
 
2599
#ifdef __GLIBC__
 
2600
#if __GLIBC_PREREQ(2, 15)
 
2601
      int numentries = scandirat(tempdir_fd, ".", &direntries,
 
2602
                                 notdotentries, alphasort);
 
2603
#else  /* not __GLIBC_PREREQ(2, 15) */
 
2604
      int numentries = scandir(tempdir, &direntries, notdotentries,
 
2605
                               alphasort);
 
2606
#endif  /* not __GLIBC_PREREQ(2, 15) */
 
2607
#else   /* not __GLIBC__ */
 
2608
      int numentries = scandir(tempdir, &direntries, notdotentries,
 
2609
                               alphasort);
 
2610
#endif  /* not __GLIBC__ */
 
2611
      if(numentries > 0){
 
2612
        for(int i = 0; i < numentries; i++){
 
2613
          ret = unlinkat(tempdir_fd, direntries[i]->d_name, 0);
 
2614
          if(ret == -1){
 
2615
            fprintf_plus(stderr, "unlinkat(open(\"%s\", O_RDONLY),"
 
2616
                         " \"%s\", 0): %s\n", tempdir,
 
2617
                         direntries[i]->d_name, strerror(errno));
 
2618
          }
 
2619
        }
 
2620
        
 
2621
        /* need to clean even if 0 because man page doesn't specify */
 
2622
        free(direntries);
 
2623
        if(numentries == -1){
 
2624
          perror_plus("scandir");
 
2625
        }
 
2626
        ret = rmdir(tempdir);
 
2627
        if(ret == -1 and errno != ENOENT){
 
2628
          perror_plus("rmdir");
 
2629
        }
2434
2630
      }
2435
 
    }
2436
 
 
2437
 
    /* need to clean even if 0 because man page doesn't specify */
2438
 
    free(direntries);
2439
 
    if (numentries == -1){
2440
 
      perror_plus("scandir");
2441
 
    }
2442
 
    ret = rmdir(tempdir);
2443
 
    if(ret == -1 and errno != ENOENT){
2444
 
      perror_plus("rmdir");
 
2631
      TEMP_FAILURE_RETRY(close(tempdir_fd));
2445
2632
    }
2446
2633
  }
2447
2634