/mandos/trunk

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

« back to all changes in this revision

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

  • Committer: Teddy Hogeborn
  • Date: 2012-06-06 19:08:17 UTC
  • mto: This revision was merged to the branch mainline in revision 596.
  • Revision ID: teddy@recompile.se-20120606190817-c2x5o98vzn07xufd
* plugins.d/mandos-client.c: Refactoring.
  (uid, gid): New global variables.
  (raise_privileges, raise_privileges_permanently, lower_privileges,
  bring_up_interface): New functions.
  (main): Changed to use new functions.

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-2013 Teddy Hogeborn
13
 
 * Copyright © 2008-2013 Björn Påhlsson
 
12
 * Copyright © 2008-2012 Teddy Hogeborn
 
13
 * Copyright © 2008-2012 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
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
 
                                   getnameinfo() */
 
58
                                   inet_pton(), connect() */
60
59
#include <fcntl.h>              /* open() */
61
60
#include <dirent.h>             /* opendir(), struct dirent, readdir()
62
61
                                 */
63
62
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
64
63
                                   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() */
74
74
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
75
75
                                   getuid(), getgid(), seteuid(),
76
76
                                   setgid(), pause(), _exit() */
77
 
#include <arpa/inet.h>          /* inet_pton(), htons() */
 
77
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
78
78
#include <iso646.h>             /* not, or, and */
79
79
#include <argp.h>               /* struct argp_option, error_t, struct
80
80
                                   argp_state, struct argp,
88
88
#include <sys/wait.h>           /* waitpid(), WIFEXITED(),
89
89
                                   WEXITSTATUS(), WTERMSIG() */
90
90
#include <grp.h>                /* setgroups() */
91
 
#include <argz.h>               /* argz_add_sep(), argz_next(),
92
 
                                   argz_delete(), argz_append(),
93
 
                                   argz_stringify(), argz_add(),
94
 
                                   argz_count() */
95
 
#include <netdb.h>              /* getnameinfo(), NI_NUMERICHOST,
96
 
                                   EAI_SYSTEM, gai_strerror() */
97
91
 
98
92
#ifdef __linux__
99
93
#include <sys/klog.h>           /* klogctl() */
136
130
 
137
131
bool debug = false;
138
132
static const char mandos_protocol_version[] = "1";
139
 
const char * argp_program_version = "mandos-client " VERSION;
140
 
const char * argp_program_bug_address = "<mandos@recompile.se>";
 
133
const char *argp_program_version = "mandos-client " VERSION;
 
134
const char *argp_program_bug_address = "<mandos@recompile.se>";
141
135
static const char sys_class_net[] = "/sys/class/net";
142
136
char *connect_to = NULL;
143
137
const char *hookdir = HOOKDIR;
147
141
/* Doubly linked list that need to be circularly linked when used */
148
142
typedef struct server{
149
143
  const char *ip;
150
 
  in_port_t port;
 
144
  uint16_t port;
151
145
  AvahiIfIndex if_index;
152
146
  int af;
153
147
  struct timespec last_seen;
157
151
 
158
152
/* Used for passing in values through the Avahi callback functions */
159
153
typedef struct {
 
154
  AvahiSimplePoll *simple_poll;
160
155
  AvahiServer *server;
161
156
  gnutls_certificate_credentials_t cred;
162
157
  unsigned int dh_bits;
164
159
  const char *priority;
165
160
  gpgme_ctx_t ctx;
166
161
  server *current_server;
167
 
  char *interfaces;
168
 
  size_t interfaces_size;
169
162
} mandos_context;
170
163
 
171
 
/* global so signal handler can reach it*/
172
 
AvahiSimplePoll *simple_poll;
 
164
/* global context so signal handler can reach it*/
 
165
mandos_context mc = { .simple_poll = NULL, .server = NULL,
 
166
                      .dh_bits = 1024, .priority = "SECURE256"
 
167
                      ":!CTYPE-X.509:+CTYPE-OPENPGP",
 
168
                      .current_server = NULL };
173
169
 
174
170
sig_atomic_t quit_now = 0;
175
171
int signal_received = 0;
183
179
  perror(print_text);
184
180
}
185
181
 
186
 
__attribute__((format (gnu_printf, 2, 3), nonnull))
 
182
__attribute__((format (gnu_printf, 2, 3)))
187
183
int fprintf_plus(FILE *stream, const char *format, ...){
188
184
  va_list ap;
189
185
  va_start (ap, format);
190
186
  
191
187
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ",
192
188
                             program_invocation_short_name));
193
 
  return (int)TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
 
189
  return TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
194
190
}
195
191
 
196
192
/*
198
194
 * bytes. "buffer_capacity" is how much is currently allocated,
199
195
 * "buffer_length" is how much is already used.
200
196
 */
201
 
__attribute__((nonnull, warn_unused_result))
202
197
size_t incbuffer(char **buffer, size_t buffer_length,
203
198
                 size_t buffer_capacity){
204
199
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
205
 
    char *new_buf = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
206
 
    if(new_buf == NULL){
207
 
      int old_errno = errno;
208
 
      free(*buffer);
209
 
      errno = old_errno;
210
 
      *buffer = NULL;
 
200
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
 
201
    if(buffer == NULL){
211
202
      return 0;
212
203
    }
213
 
    *buffer = new_buf;
214
204
    buffer_capacity += BUFFER_SIZE;
215
205
  }
216
206
  return buffer_capacity;
217
207
}
218
208
 
219
209
/* Add server to set of servers to retry periodically */
220
 
__attribute__((nonnull, warn_unused_result))
221
 
bool add_server(const char *ip, in_port_t port, AvahiIfIndex if_index,
222
 
                int af, server **current_server){
 
210
bool add_server(const char *ip, uint16_t port, AvahiIfIndex if_index,
 
211
                int af){
223
212
  int ret;
224
213
  server *new_server = malloc(sizeof(server));
225
214
  if(new_server == NULL){
234
223
    perror_plus("strdup");
235
224
    return false;
236
225
  }
237
 
  ret = clock_gettime(CLOCK_MONOTONIC, &(new_server->last_seen));
238
 
  if(ret == -1){
239
 
    perror_plus("clock_gettime");
240
 
    return false;
241
 
  }
242
226
  /* Special case of first server */
243
 
  if(*current_server == NULL){
 
227
  if (mc.current_server == NULL){
244
228
    new_server->next = new_server;
245
229
    new_server->prev = new_server;
246
 
    *current_server = new_server;
 
230
    mc.current_server = new_server;
 
231
  /* Place the new server last in the list */
247
232
  } else {
248
 
    /* Place the new server last in the list */
249
 
    new_server->next = *current_server;
250
 
    new_server->prev = (*current_server)->prev;
 
233
    new_server->next = mc.current_server;
 
234
    new_server->prev = mc.current_server->prev;
251
235
    new_server->prev->next = new_server;
252
 
    (*current_server)->prev = new_server;
 
236
    mc.current_server->prev = new_server;
 
237
  }
 
238
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
 
239
  if(ret == -1){
 
240
    perror_plus("clock_gettime");
 
241
    return false;
253
242
  }
254
243
  return true;
255
244
}
257
246
/* 
258
247
 * Initialize GPGME.
259
248
 */
260
 
__attribute__((nonnull, warn_unused_result))
261
 
static bool init_gpgme(const char * const seckey,
262
 
                       const char * const pubkey,
263
 
                       const char * const tempdir,
264
 
                       mandos_context *mc){
 
249
static bool init_gpgme(const char *seckey, const char *pubkey,
 
250
                       const char *tempdir){
265
251
  gpgme_error_t rc;
266
252
  gpgme_engine_info_t engine_info;
267
253
  
 
254
  
268
255
  /*
269
256
   * Helper function to insert pub and seckey to the engine keyring.
270
257
   */
271
 
  bool import_key(const char * const filename){
 
258
  bool import_key(const char *filename){
272
259
    int ret;
273
260
    int fd;
274
261
    gpgme_data_t pgp_data;
286
273
      return false;
287
274
    }
288
275
    
289
 
    rc = gpgme_op_import(mc->ctx, pgp_data);
 
276
    rc = gpgme_op_import(mc.ctx, pgp_data);
290
277
    if(rc != GPG_ERR_NO_ERROR){
291
278
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
292
279
                   gpgme_strsource(rc), gpgme_strerror(rc));
336
323
  }
337
324
  
338
325
  /* Create new GPGME "context" */
339
 
  rc = gpgme_new(&(mc->ctx));
 
326
  rc = gpgme_new(&(mc.ctx));
340
327
  if(rc != GPG_ERR_NO_ERROR){
341
328
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
342
329
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
355
342
 * Decrypt OpenPGP data.
356
343
 * Returns -1 on error
357
344
 */
358
 
__attribute__((nonnull, warn_unused_result))
359
345
static ssize_t pgp_packet_decrypt(const char *cryptotext,
360
346
                                  size_t crypto_size,
361
 
                                  char **plaintext,
362
 
                                  mandos_context *mc){
 
347
                                  char **plaintext){
363
348
  gpgme_data_t dh_crypto, dh_plain;
364
349
  gpgme_error_t rc;
365
350
  ssize_t ret;
391
376
  
392
377
  /* Decrypt data from the cryptotext data buffer to the plaintext
393
378
     data buffer */
394
 
  rc = gpgme_op_decrypt(mc->ctx, dh_crypto, dh_plain);
 
379
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
395
380
  if(rc != GPG_ERR_NO_ERROR){
396
381
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
397
382
                 gpgme_strsource(rc), gpgme_strerror(rc));
398
383
    plaintext_length = -1;
399
384
    if(debug){
400
385
      gpgme_decrypt_result_t result;
401
 
      result = gpgme_op_decrypt_result(mc->ctx);
 
386
      result = gpgme_op_decrypt_result(mc.ctx);
402
387
      if(result == NULL){
403
388
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
404
389
      } else {
481
466
  return plaintext_length;
482
467
}
483
468
 
484
 
__attribute__((warn_unused_result))
485
 
static const char *safer_gnutls_strerror(int value){
486
 
  const char *ret = gnutls_strerror(value);
 
469
static const char * safer_gnutls_strerror(int value){
 
470
  const char *ret = gnutls_strerror(value); /* Spurious warning from
 
471
                                               -Wunreachable-code */
487
472
  if(ret == NULL)
488
473
    ret = "(unknown)";
489
474
  return ret;
490
475
}
491
476
 
492
477
/* GnuTLS log function callback */
493
 
__attribute__((nonnull))
494
478
static void debuggnutls(__attribute__((unused)) int level,
495
479
                        const char* string){
496
480
  fprintf_plus(stderr, "GnuTLS: %s", string);
497
481
}
498
482
 
499
 
__attribute__((nonnull, warn_unused_result))
500
483
static int init_gnutls_global(const char *pubkeyfilename,
501
 
                              const char *seckeyfilename,
502
 
                              mandos_context *mc){
 
484
                              const char *seckeyfilename){
503
485
  int ret;
504
486
  
505
487
  if(debug){
522
504
  }
523
505
  
524
506
  /* OpenPGP credentials */
525
 
  ret = gnutls_certificate_allocate_credentials(&mc->cred);
 
507
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
526
508
  if(ret != GNUTLS_E_SUCCESS){
527
509
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
528
510
                 safer_gnutls_strerror(ret));
538
520
  }
539
521
  
540
522
  ret = gnutls_certificate_set_openpgp_key_file
541
 
    (mc->cred, pubkeyfilename, seckeyfilename,
 
523
    (mc.cred, pubkeyfilename, seckeyfilename,
542
524
     GNUTLS_OPENPGP_FMT_BASE64);
543
525
  if(ret != GNUTLS_E_SUCCESS){
544
526
    fprintf_plus(stderr,
550
532
  }
551
533
  
552
534
  /* GnuTLS server initialization */
553
 
  ret = gnutls_dh_params_init(&mc->dh_params);
 
535
  ret = gnutls_dh_params_init(&mc.dh_params);
554
536
  if(ret != GNUTLS_E_SUCCESS){
555
537
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
556
538
                 " initialization: %s\n",
557
539
                 safer_gnutls_strerror(ret));
558
540
    goto globalfail;
559
541
  }
560
 
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
 
542
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
561
543
  if(ret != GNUTLS_E_SUCCESS){
562
544
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
563
545
                 safer_gnutls_strerror(ret));
564
546
    goto globalfail;
565
547
  }
566
548
  
567
 
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
 
549
  gnutls_certificate_set_dh_params(mc.cred, mc.dh_params);
568
550
  
569
551
  return 0;
570
552
  
571
553
 globalfail:
572
554
  
573
 
  gnutls_certificate_free_credentials(mc->cred);
 
555
  gnutls_certificate_free_credentials(mc.cred);
574
556
  gnutls_global_deinit();
575
 
  gnutls_dh_params_deinit(mc->dh_params);
 
557
  gnutls_dh_params_deinit(mc.dh_params);
576
558
  return -1;
577
559
}
578
560
 
579
 
__attribute__((nonnull, warn_unused_result))
580
 
static int init_gnutls_session(gnutls_session_t *session,
581
 
                               mandos_context *mc){
 
561
static int init_gnutls_session(gnutls_session_t *session){
582
562
  int ret;
583
563
  /* GnuTLS session creation */
584
564
  do {
596
576
  {
597
577
    const char *err;
598
578
    do {
599
 
      ret = gnutls_priority_set_direct(*session, mc->priority, &err);
 
579
      ret = gnutls_priority_set_direct(*session, mc.priority, &err);
600
580
      if(quit_now){
601
581
        gnutls_deinit(*session);
602
582
        return -1;
613
593
  
614
594
  do {
615
595
    ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
616
 
                                 mc->cred);
 
596
                                 mc.cred);
617
597
    if(quit_now){
618
598
      gnutls_deinit(*session);
619
599
      return -1;
629
609
  /* ignore client certificate if any. */
630
610
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
631
611
  
632
 
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
 
612
  gnutls_dh_set_prime_bits(*session, mc.dh_bits);
633
613
  
634
614
  return 0;
635
615
}
639
619
                      __attribute__((unused)) const char *txt){}
640
620
 
641
621
/* Called when a Mandos server is found */
642
 
__attribute__((nonnull, warn_unused_result))
643
 
static int start_mandos_communication(const char *ip, in_port_t port,
 
622
static int start_mandos_communication(const char *ip, uint16_t port,
644
623
                                      AvahiIfIndex if_index,
645
 
                                      int af, mandos_context *mc){
 
624
                                      int af){
646
625
  int ret, tcp_sd = -1;
647
626
  ssize_t sret;
648
 
  struct sockaddr_storage to;
 
627
  union {
 
628
    struct sockaddr_in in;
 
629
    struct sockaddr_in6 in6;
 
630
  } to;
649
631
  char *buffer = NULL;
650
632
  char *decrypted_buffer = NULL;
651
633
  size_t buffer_length = 0;
675
657
    return -1;
676
658
  }
677
659
  
678
 
  /* If the interface is specified and we have a list of interfaces */
679
 
  if(if_index != AVAHI_IF_UNSPEC and mc->interfaces != NULL){
680
 
    /* Check if the interface is one of the interfaces we are using */
681
 
    bool match = false;
682
 
    {
683
 
      char *interface = NULL;
684
 
      while((interface=argz_next(mc->interfaces, mc->interfaces_size,
685
 
                                 interface))){
686
 
        if(if_nametoindex(interface) == (unsigned int)if_index){
687
 
          match = true;
688
 
          break;
689
 
        }
690
 
      }
691
 
    }
692
 
    if(not match){
693
 
      /* This interface does not match any in the list, so we don't
694
 
         connect to the server */
695
 
      if(debug){
696
 
        char interface[IF_NAMESIZE];
697
 
        if(if_indextoname((unsigned int)if_index, interface) == NULL){
698
 
          perror_plus("if_indextoname");
699
 
        } else {
700
 
          fprintf_plus(stderr, "Skipping server on non-used interface"
701
 
                       " \"%s\"\n",
702
 
                       if_indextoname((unsigned int)if_index,
703
 
                                      interface));
704
 
        }
705
 
      }
706
 
      return -1;
707
 
    }
708
 
  }
709
 
  
710
 
  ret = init_gnutls_session(&session, mc);
 
660
  ret = init_gnutls_session(&session);
711
661
  if(ret != 0){
712
662
    return -1;
713
663
  }
714
664
  
715
665
  if(debug){
716
666
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
717
 
                 PRIuMAX "\n", ip, (uintmax_t)port);
 
667
                 PRIu16 "\n", ip, port);
718
668
  }
719
669
  
720
670
  tcp_sd = socket(pf, SOCK_STREAM, 0);
732
682
  
733
683
  memset(&to, 0, sizeof(to));
734
684
  if(af == AF_INET6){
735
 
    ((struct sockaddr_in6 *)&to)->sin6_family = (sa_family_t)af;
736
 
    ret = inet_pton(af, ip, &((struct sockaddr_in6 *)&to)->sin6_addr);
 
685
    to.in6.sin6_family = (sa_family_t)af;
 
686
    ret = inet_pton(af, ip, &to.in6.sin6_addr);
737
687
  } else {                      /* IPv4 */
738
 
    ((struct sockaddr_in *)&to)->sin_family = (sa_family_t)af;
739
 
    ret = inet_pton(af, ip, &((struct sockaddr_in *)&to)->sin_addr);
 
688
    to.in.sin_family = (sa_family_t)af;
 
689
    ret = inet_pton(af, ip, &to.in.sin_addr);
740
690
  }
741
691
  if(ret < 0 ){
742
692
    int e = errno;
751
701
    goto mandos_end;
752
702
  }
753
703
  if(af == AF_INET6){
754
 
    ((struct sockaddr_in6 *)&to)->sin6_port = htons(port);
755
 
    if(IN6_IS_ADDR_LINKLOCAL
756
 
       (&((struct sockaddr_in6 *)&to)->sin6_addr)){
 
704
    to.in6.sin6_port = htons(port); /* Spurious warnings from
 
705
                                       -Wconversion and
 
706
                                       -Wunreachable-code */
 
707
    
 
708
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
 
709
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
 
710
                                -Wunreachable-code*/
757
711
      if(if_index == AVAHI_IF_UNSPEC){
758
712
        fprintf_plus(stderr, "An IPv6 link-local address is"
759
713
                     " incomplete without a network interface\n");
761
715
        goto mandos_end;
762
716
      }
763
717
      /* Set the network interface number as scope */
764
 
      ((struct sockaddr_in6 *)&to)->sin6_scope_id = (uint32_t)if_index;
 
718
      to.in6.sin6_scope_id = (uint32_t)if_index;
765
719
    }
766
720
  } else {
767
 
    ((struct sockaddr_in *)&to)->sin_port = htons(port);
 
721
    to.in.sin_port = htons(port); /* Spurious warnings from
 
722
                                     -Wconversion and
 
723
                                     -Wunreachable-code */
768
724
  }
769
725
  
770
726
  if(quit_now){
778
734
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
779
735
        perror_plus("if_indextoname");
780
736
      } else {
781
 
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIuMAX
782
 
                     "\n", ip, interface, (uintmax_t)port);
 
737
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIu16
 
738
                     "\n", ip, interface, port);
783
739
      }
784
740
    } else {
785
 
      fprintf_plus(stderr, "Connection to: %s, port %" PRIuMAX "\n",
786
 
                   ip, (uintmax_t)port);
 
741
      fprintf_plus(stderr, "Connection to: %s, port %" PRIu16 "\n",
 
742
                   ip, port);
787
743
    }
788
744
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
789
745
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
 
746
    const char *pcret;
790
747
    if(af == AF_INET6){
791
 
      ret = getnameinfo((struct sockaddr *)&to,
792
 
                        sizeof(struct sockaddr_in6),
793
 
                        addrstr, sizeof(addrstr), NULL, 0,
794
 
                        NI_NUMERICHOST);
 
748
      pcret = inet_ntop(af, &(to.in6.sin6_addr), addrstr,
 
749
                        sizeof(addrstr));
795
750
    } else {
796
 
      ret = getnameinfo((struct sockaddr *)&to,
797
 
                        sizeof(struct sockaddr_in),
798
 
                        addrstr, sizeof(addrstr), NULL, 0,
799
 
                        NI_NUMERICHOST);
 
751
      pcret = inet_ntop(af, &(to.in.sin_addr), addrstr,
 
752
                        sizeof(addrstr));
800
753
    }
801
 
    if(ret == EAI_SYSTEM){
802
 
      perror_plus("getnameinfo");
803
 
    } else if(ret != 0) {
804
 
      fprintf_plus(stderr, "getnameinfo: %s", gai_strerror(ret));
805
 
    } else if(strcmp(addrstr, ip) != 0){
806
 
      fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
 
754
    if(pcret == NULL){
 
755
      perror_plus("inet_ntop");
 
756
    } else {
 
757
      if(strcmp(addrstr, ip) != 0){
 
758
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
 
759
      }
807
760
    }
808
761
  }
809
762
  
813
766
  }
814
767
  
815
768
  if(af == AF_INET6){
816
 
    ret = connect(tcp_sd, (struct sockaddr *)&to,
817
 
                  sizeof(struct sockaddr_in6));
 
769
    ret = connect(tcp_sd, &to.in6, sizeof(to));
818
770
  } else {
819
 
    ret = connect(tcp_sd, (struct sockaddr *)&to, /* IPv4 */
820
 
                  sizeof(struct sockaddr_in));
 
771
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
821
772
  }
822
773
  if(ret < 0){
823
 
    if((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
 
774
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
824
775
      int e = errno;
825
776
      perror_plus("connect");
826
777
      errno = e;
987
938
  if(buffer_length > 0){
988
939
    ssize_t decrypted_buffer_size;
989
940
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
990
 
                                               &decrypted_buffer, mc);
 
941
                                               &decrypted_buffer);
991
942
    if(decrypted_buffer_size >= 0){
992
943
      
993
944
      written = 0;
1041
992
  return retval;
1042
993
}
1043
994
 
1044
 
__attribute__((nonnull))
1045
995
static void resolve_callback(AvahiSServiceResolver *r,
1046
996
                             AvahiIfIndex interface,
1047
997
                             AvahiProtocol proto,
1055
1005
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
1056
1006
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
1057
1007
                             flags,
1058
 
                             void *mc){
1059
 
  if(r == NULL){
1060
 
    return;
1061
 
  }
 
1008
                             AVAHI_GCC_UNUSED void* userdata){
 
1009
  assert(r);
1062
1010
  
1063
1011
  /* Called whenever a service has been resolved successfully or
1064
1012
     timed out */
1073
1021
    fprintf_plus(stderr, "(Avahi Resolver) Failed to resolve service "
1074
1022
                 "'%s' of type '%s' in domain '%s': %s\n", name, type,
1075
1023
                 domain,
1076
 
                 avahi_strerror(avahi_server_errno
1077
 
                                (((mandos_context*)mc)->server)));
 
1024
                 avahi_strerror(avahi_server_errno(mc.server)));
1078
1025
    break;
1079
1026
    
1080
1027
  case AVAHI_RESOLVER_FOUND:
1086
1033
                     PRIdMAX ") on port %" PRIu16 "\n", name,
1087
1034
                     host_name, ip, (intmax_t)interface, port);
1088
1035
      }
1089
 
      int ret = start_mandos_communication(ip, (in_port_t)port,
1090
 
                                           interface,
1091
 
                                           avahi_proto_to_af(proto),
1092
 
                                           mc);
 
1036
      int ret = start_mandos_communication(ip, port, interface,
 
1037
                                           avahi_proto_to_af(proto));
1093
1038
      if(ret == 0){
1094
 
        avahi_simple_poll_quit(simple_poll);
 
1039
        avahi_simple_poll_quit(mc.simple_poll);
1095
1040
      } else {
1096
 
        if(not add_server(ip, (in_port_t)port, interface,
1097
 
                          avahi_proto_to_af(proto),
1098
 
                          &((mandos_context*)mc)->current_server)){
 
1041
        if(not add_server(ip, port, interface,
 
1042
                          avahi_proto_to_af(proto))){
1099
1043
          fprintf_plus(stderr, "Failed to add server \"%s\" to server"
1100
1044
                       " list\n", name);
1101
1045
        }
1114
1058
                            const char *domain,
1115
1059
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
1116
1060
                            flags,
1117
 
                            void *mc){
1118
 
  if(b == NULL){
1119
 
    return;
1120
 
  }
 
1061
                            AVAHI_GCC_UNUSED void* userdata){
 
1062
  assert(b);
1121
1063
  
1122
1064
  /* Called whenever a new services becomes available on the LAN or
1123
1065
     is removed from the LAN */
1131
1073
  case AVAHI_BROWSER_FAILURE:
1132
1074
    
1133
1075
    fprintf_plus(stderr, "(Avahi browser) %s\n",
1134
 
                 avahi_strerror(avahi_server_errno
1135
 
                                (((mandos_context*)mc)->server)));
1136
 
    avahi_simple_poll_quit(simple_poll);
 
1076
                 avahi_strerror(avahi_server_errno(mc.server)));
 
1077
    avahi_simple_poll_quit(mc.simple_poll);
1137
1078
    return;
1138
1079
    
1139
1080
  case AVAHI_BROWSER_NEW:
1142
1083
       the callback function is called the Avahi server will free the
1143
1084
       resolver for us. */
1144
1085
    
1145
 
    if(avahi_s_service_resolver_new(((mandos_context*)mc)->server,
1146
 
                                    interface, protocol, name, type,
1147
 
                                    domain, protocol, 0,
1148
 
                                    resolve_callback, mc) == NULL)
 
1086
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
 
1087
                                    name, type, domain, protocol, 0,
 
1088
                                    resolve_callback, NULL) == NULL)
1149
1089
      fprintf_plus(stderr, "Avahi: Failed to resolve service '%s':"
1150
1090
                   " %s\n", name,
1151
 
                   avahi_strerror(avahi_server_errno
1152
 
                                  (((mandos_context*)mc)->server)));
 
1091
                   avahi_strerror(avahi_server_errno(mc.server)));
1153
1092
    break;
1154
1093
    
1155
1094
  case AVAHI_BROWSER_REMOVE:
1174
1113
  signal_received = sig;
1175
1114
  int old_errno = errno;
1176
1115
  /* set main loop to exit */
1177
 
  if(simple_poll != NULL){
1178
 
    avahi_simple_poll_quit(simple_poll);
 
1116
  if(mc.simple_poll != NULL){
 
1117
    avahi_simple_poll_quit(mc.simple_poll);
1179
1118
  }
1180
1119
  errno = old_errno;
1181
1120
}
1182
1121
 
1183
 
__attribute__((nonnull, warn_unused_result))
1184
1122
bool get_flags(const char *ifname, struct ifreq *ifr){
1185
1123
  int ret;
1186
 
  error_t ret_errno;
1187
1124
  
1188
1125
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1189
1126
  if(s < 0){
1190
 
    ret_errno = errno;
1191
1127
    perror_plus("socket");
1192
 
    errno = ret_errno;
1193
1128
    return false;
1194
1129
  }
1195
1130
  strcpy(ifr->ifr_name, ifname);
1196
1131
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1197
1132
  if(ret == -1){
1198
1133
    if(debug){
1199
 
      ret_errno = errno;
1200
1134
      perror_plus("ioctl SIOCGIFFLAGS");
1201
 
      errno = ret_errno;
1202
1135
    }
1203
1136
    return false;
1204
1137
  }
1205
1138
  return true;
1206
1139
}
1207
1140
 
1208
 
__attribute__((nonnull, warn_unused_result))
1209
1141
bool good_flags(const char *ifname, const struct ifreq *ifr){
1210
1142
  
1211
1143
  /* Reject the loopback device */
1253
1185
 * corresponds to an acceptable network device.
1254
1186
 * (This function is passed to scandir(3) as a filter function.)
1255
1187
 */
1256
 
__attribute__((nonnull, warn_unused_result))
1257
1188
int good_interface(const struct dirent *if_entry){
1258
1189
  if(if_entry->d_name[0] == '.'){
1259
1190
    return 0;
1275
1206
}
1276
1207
 
1277
1208
/* 
1278
 
 * This function determines if a network interface is up.
1279
 
 */
1280
 
__attribute__((nonnull, warn_unused_result))
1281
 
bool interface_is_up(const char *interface){
1282
 
  struct ifreq ifr;
1283
 
  if(not get_flags(interface, &ifr)){
1284
 
    if(debug){
1285
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1286
 
                   "\"%s\"\n", interface);
1287
 
    }
1288
 
    return false;
1289
 
  }
1290
 
  
1291
 
  return (bool)(ifr.ifr_flags & IFF_UP);
1292
 
}
1293
 
 
1294
 
/* 
1295
 
 * This function determines if a network interface is running
1296
 
 */
1297
 
__attribute__((nonnull, warn_unused_result))
1298
 
bool interface_is_running(const char *interface){
1299
 
  struct ifreq ifr;
1300
 
  if(not get_flags(interface, &ifr)){
1301
 
    if(debug){
1302
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1303
 
                   "\"%s\"\n", interface);
1304
 
    }
1305
 
    return false;
1306
 
  }
1307
 
  
1308
 
  return (bool)(ifr.ifr_flags & IFF_RUNNING);
1309
 
}
1310
 
 
1311
 
__attribute__((nonnull, pure, warn_unused_result))
 
1209
 * This function determines if a directory entry in /sys/class/net
 
1210
 * corresponds to an acceptable network device which is up.
 
1211
 * (This function is passed to scandir(3) as a filter function.)
 
1212
 */
 
1213
int up_interface(const struct dirent *if_entry){
 
1214
  if(if_entry->d_name[0] == '.'){
 
1215
    return 0;
 
1216
  }
 
1217
  
 
1218
  struct ifreq ifr;
 
1219
  if(not get_flags(if_entry->d_name, &ifr)){
 
1220
    if(debug){
 
1221
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1222
                   "\"%s\"\n", if_entry->d_name);
 
1223
    }
 
1224
    return 0;
 
1225
  }
 
1226
  
 
1227
  /* Reject down interfaces */
 
1228
  if(not (ifr.ifr_flags & IFF_UP)){
 
1229
    if(debug){
 
1230
      fprintf_plus(stderr, "Rejecting down interface \"%s\"\n",
 
1231
                   if_entry->d_name);
 
1232
    }
 
1233
    return 0;
 
1234
  }
 
1235
  
 
1236
  /* Reject non-running interfaces */
 
1237
  if(not (ifr.ifr_flags & IFF_RUNNING)){
 
1238
    if(debug){
 
1239
      fprintf_plus(stderr, "Rejecting non-running interface \"%s\"\n",
 
1240
                   if_entry->d_name);
 
1241
    }
 
1242
    return 0;
 
1243
  }
 
1244
  
 
1245
  if(not good_flags(if_entry->d_name, &ifr)){
 
1246
    return 0;
 
1247
  }
 
1248
  return 1;
 
1249
}
 
1250
 
1312
1251
int notdotentries(const struct dirent *direntry){
1313
1252
  /* Skip "." and ".." */
1314
1253
  if(direntry->d_name[0] == '.'
1321
1260
}
1322
1261
 
1323
1262
/* Is this directory entry a runnable program? */
1324
 
__attribute__((nonnull, warn_unused_result))
1325
1263
int runnable_hook(const struct dirent *direntry){
1326
1264
  int ret;
1327
1265
  size_t sret;
1382
1320
  return 1;
1383
1321
}
1384
1322
 
1385
 
__attribute__((nonnull, warn_unused_result))
1386
 
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval,
1387
 
                            mandos_context *mc){
 
1323
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
1388
1324
  int ret;
1389
1325
  struct timespec now;
1390
1326
  struct timespec waited_time;
1391
1327
  intmax_t block_time;
1392
1328
  
1393
1329
  while(true){
1394
 
    if(mc->current_server == NULL){
1395
 
      if(debug){
 
1330
    if(mc.current_server == NULL){
 
1331
      if (debug){
1396
1332
        fprintf_plus(stderr, "Wait until first server is found."
1397
1333
                     " No timeout!\n");
1398
1334
      }
1399
1335
      ret = avahi_simple_poll_iterate(s, -1);
1400
1336
    } else {
1401
 
      if(debug){
 
1337
      if (debug){
1402
1338
        fprintf_plus(stderr, "Check current_server if we should run"
1403
1339
                     " it, or wait\n");
1404
1340
      }
1411
1347
      /* Calculating in ms how long time between now and server
1412
1348
         who we visted longest time ago. Now - last seen.  */
1413
1349
      waited_time.tv_sec = (now.tv_sec
1414
 
                            - mc->current_server->last_seen.tv_sec);
 
1350
                            - mc.current_server->last_seen.tv_sec);
1415
1351
      waited_time.tv_nsec = (now.tv_nsec
1416
 
                             - mc->current_server->last_seen.tv_nsec);
 
1352
                             - mc.current_server->last_seen.tv_nsec);
1417
1353
      /* total time is 10s/10,000ms.
1418
1354
         Converting to s from ms by dividing by 1,000,
1419
1355
         and ns to ms by dividing by 1,000,000. */
1421
1357
                     - ((intmax_t)waited_time.tv_sec * 1000))
1422
1358
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1423
1359
      
1424
 
      if(debug){
 
1360
      if (debug){
1425
1361
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
1426
1362
                     block_time);
1427
1363
      }
1428
1364
      
1429
1365
      if(block_time <= 0){
1430
 
        ret = start_mandos_communication(mc->current_server->ip,
1431
 
                                         mc->current_server->port,
1432
 
                                         mc->current_server->if_index,
1433
 
                                         mc->current_server->af, mc);
 
1366
        ret = start_mandos_communication(mc.current_server->ip,
 
1367
                                         mc.current_server->port,
 
1368
                                         mc.current_server->if_index,
 
1369
                                         mc.current_server->af);
1434
1370
        if(ret == 0){
1435
 
          avahi_simple_poll_quit(s);
 
1371
          avahi_simple_poll_quit(mc.simple_poll);
1436
1372
          return 0;
1437
1373
        }
1438
1374
        ret = clock_gettime(CLOCK_MONOTONIC,
1439
 
                            &mc->current_server->last_seen);
 
1375
                            &mc.current_server->last_seen);
1440
1376
        if(ret == -1){
1441
1377
          perror_plus("clock_gettime");
1442
1378
          return -1;
1443
1379
        }
1444
 
        mc->current_server = mc->current_server->next;
 
1380
        mc.current_server = mc.current_server->next;
1445
1381
        block_time = 0;         /* Call avahi to find new Mandos
1446
1382
                                   servers, but don't block */
1447
1383
      }
1449
1385
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1450
1386
    }
1451
1387
    if(ret != 0){
1452
 
      if(ret > 0 or errno != EINTR){
 
1388
      if (ret > 0 or errno != EINTR){
1453
1389
        return (ret != 1) ? ret : 0;
1454
1390
      }
1455
1391
    }
1457
1393
}
1458
1394
 
1459
1395
/* Set effective uid to 0, return errno */
1460
 
__attribute__((warn_unused_result))
1461
 
error_t raise_privileges(void){
1462
 
  error_t old_errno = errno;
1463
 
  error_t ret_errno = 0;
 
1396
int raise_privileges(void){
 
1397
  int old_errno = errno;
 
1398
  int ret_errno = 0;
 
1399
  errno = 0;
1464
1400
  if(seteuid(0) == -1){
1465
 
    ret_errno = errno;
1466
1401
    perror_plus("seteuid");
1467
1402
  }
 
1403
  ret_errno = errno;
1468
1404
  errno = old_errno;
1469
1405
  return ret_errno;
1470
1406
}
1471
1407
 
1472
1408
/* Set effective and real user ID to 0.  Return errno. */
1473
 
__attribute__((warn_unused_result))
1474
 
error_t raise_privileges_permanently(void){
1475
 
  error_t old_errno = errno;
1476
 
  error_t ret_errno = raise_privileges();
 
1409
int raise_privileges_permanently(void){
 
1410
  int old_errno = errno;
 
1411
  int ret_errno = raise_privileges();
1477
1412
  if(ret_errno != 0){
1478
1413
    errno = old_errno;
1479
1414
    return ret_errno;
1480
1415
  }
 
1416
  errno = 0;
1481
1417
  if(setuid(0) == -1){
1482
 
    ret_errno = errno;
1483
1418
    perror_plus("seteuid");
1484
1419
  }
 
1420
  ret_errno = errno;
1485
1421
  errno = old_errno;
1486
1422
  return ret_errno;
1487
1423
}
1488
1424
 
1489
1425
/* Set effective user ID to unprivileged saved user ID */
1490
 
__attribute__((warn_unused_result))
1491
 
error_t lower_privileges(void){
1492
 
  error_t old_errno = errno;
1493
 
  error_t ret_errno = 0;
 
1426
int lower_privileges(void){
 
1427
  int old_errno = errno;
 
1428
  int ret_errno = 0;
 
1429
  errno = 0;
1494
1430
  if(seteuid(uid) == -1){
1495
 
    ret_errno = errno;
1496
1431
    perror_plus("seteuid");
1497
1432
  }
1498
 
  errno = old_errno;
1499
 
  return ret_errno;
1500
 
}
1501
 
 
1502
 
/* Lower privileges permanently */
1503
 
__attribute__((warn_unused_result))
1504
 
error_t lower_privileges_permanently(void){
1505
 
  error_t old_errno = errno;
1506
 
  error_t ret_errno = 0;
1507
 
  if(setuid(uid) == -1){
1508
 
    ret_errno = errno;
1509
 
    perror_plus("setuid");
1510
 
  }
1511
 
  errno = old_errno;
1512
 
  return ret_errno;
1513
 
}
1514
 
 
1515
 
__attribute__((nonnull))
1516
 
void run_network_hooks(const char *mode, const char *interface,
 
1433
  ret_errno = errno;
 
1434
  errno = old_errno;
 
1435
  return ret_errno;
 
1436
}
 
1437
 
 
1438
bool run_network_hooks(const char *mode, const char *interface,
1517
1439
                       const float delay){
1518
1440
  struct dirent **direntries;
 
1441
  struct dirent *direntry;
 
1442
  int ret;
1519
1443
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
1520
1444
                         alphasort);
1521
1445
  if(numhooks == -1){
1522
 
    if(errno == ENOENT){
1523
 
      if(debug){
1524
 
        fprintf_plus(stderr, "Network hook directory \"%s\" not"
1525
 
                     " found\n", hookdir);
1526
 
      }
1527
 
    } else {
1528
 
      perror_plus("scandir");
1529
 
    }
 
1446
    perror_plus("scandir");
1530
1447
  } else {
1531
 
    struct dirent *direntry;
1532
 
    int ret;
1533
1448
    int devnull = open("/dev/null", O_RDONLY);
1534
1449
    for(int i = 0; i < numhooks; i++){
1535
1450
      direntry = direntries[i];
1547
1462
      if(hook_pid == 0){
1548
1463
        /* Child */
1549
1464
        /* Raise privileges */
1550
 
        if(raise_privileges_permanently() != 0){
1551
 
          perror_plus("Failed to raise privileges");
1552
 
          _exit(EX_NOPERM);
1553
 
        }
 
1465
        raise_privileges_permanently();
1554
1466
        /* Set group */
1555
1467
        errno = 0;
1556
1468
        ret = setgid(0);
1557
1469
        if(ret == -1){
1558
1470
          perror_plus("setgid");
1559
 
          _exit(EX_NOPERM);
1560
1471
        }
1561
1472
        /* Reset supplementary groups */
1562
1473
        errno = 0;
1563
1474
        ret = setgroups(0, NULL);
1564
1475
        if(ret == -1){
1565
1476
          perror_plus("setgroups");
1566
 
          _exit(EX_NOPERM);
1567
 
        }
1568
 
        ret = dup2(devnull, STDIN_FILENO);
1569
 
        if(ret == -1){
1570
 
          perror_plus("dup2(devnull, STDIN_FILENO)");
1571
 
          _exit(EX_OSERR);
1572
 
        }
1573
 
        ret = close(devnull);
1574
 
        if(ret == -1){
1575
 
          perror_plus("close");
1576
 
          _exit(EX_OSERR);
1577
 
        }
1578
 
        ret = dup2(STDERR_FILENO, STDOUT_FILENO);
1579
 
        if(ret == -1){
1580
 
          perror_plus("dup2(STDERR_FILENO, STDOUT_FILENO)");
1581
 
          _exit(EX_OSERR);
1582
 
        }
 
1477
        }
 
1478
        dup2(devnull, STDIN_FILENO);
 
1479
        close(devnull);
 
1480
        dup2(STDERR_FILENO, STDOUT_FILENO);
1583
1481
        ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
1584
1482
        if(ret == -1){
1585
1483
          perror_plus("setenv");
1601
1499
          _exit(EX_OSERR);
1602
1500
        }
1603
1501
        char *delaystring;
1604
 
        ret = asprintf(&delaystring, "%f", (double)delay);
 
1502
        ret = asprintf(&delaystring, "%f", delay);
1605
1503
        if(ret == -1){
1606
1504
          perror_plus("asprintf");
1607
1505
          _exit(EX_OSERR);
1660
1558
    }
1661
1559
    close(devnull);
1662
1560
  }
 
1561
  return true;
1663
1562
}
1664
1563
 
1665
 
__attribute__((nonnull, warn_unused_result))
1666
 
error_t bring_up_interface(const char *const interface,
1667
 
                           const float delay){
1668
 
  error_t old_errno = errno;
 
1564
int bring_up_interface(const char * const interface, const float delay){
 
1565
  int sd = -1;
1669
1566
  int ret;
1670
1567
  struct ifreq network;
1671
 
  unsigned int if_index = if_nametoindex(interface);
 
1568
  AvahiIfIndex if_index = (AvahiIfIndex)if_nametoindex(interface);
1672
1569
  if(if_index == 0){
1673
1570
    fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
1674
 
    errno = old_errno;
1675
 
    return ENXIO;
 
1571
    return EX_UNAVAILABLE;
1676
1572
  }
1677
1573
  
1678
1574
  if(quit_now){
1679
 
    errno = old_errno;
1680
1575
    return EINTR;
1681
1576
  }
1682
1577
  
1683
 
  if(not interface_is_up(interface)){
1684
 
    error_t ret_errno = 0, ioctl_errno = 0;
1685
 
    if(not get_flags(interface, &network)){
1686
 
      ret_errno = errno;
1687
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1688
 
                   "\"%s\"\n", interface);
1689
 
      errno = old_errno;
1690
 
      return ret_errno;
1691
 
    }
1692
 
    network.ifr_flags |= IFF_UP; /* set flag */
1693
 
    
1694
 
    int sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1695
 
    if(sd == -1){
1696
 
      ret_errno = errno;
1697
 
      perror_plus("socket");
1698
 
      errno = old_errno;
1699
 
      return ret_errno;
1700
 
    }
1701
 
    
1702
 
    if(quit_now){
1703
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1704
 
      if(ret == -1){
1705
 
        perror_plus("close");
1706
 
      }
1707
 
      errno = old_errno;
1708
 
      return EINTR;
1709
 
    }
1710
 
    
1711
 
    if(debug){
1712
 
      fprintf_plus(stderr, "Bringing up interface \"%s\"\n",
1713
 
                   interface);
1714
 
    }
1715
 
    
1716
 
    /* Raise privileges */
1717
 
    ret_errno = raise_privileges();
1718
 
    bool restore_loglevel = false;
1719
 
    if(ret_errno != 0){
1720
 
      perror_plus("Failed to raise privileges");
1721
 
    }
1722
 
#ifdef __linux__
1723
 
    int ret_linux;
1724
 
    if(ret_errno == 0){
1725
 
      /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1726
 
         messages about the network interface to mess up the prompt */
1727
 
      ret_linux = klogctl(8, NULL, 5);
1728
 
      if(ret_linux == -1){
1729
 
        perror_plus("klogctl");
1730
 
      } else {
1731
 
        restore_loglevel = true;
1732
 
      }
1733
 
    }
1734
 
#endif  /* __linux__ */
1735
 
    int ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
1736
 
    ioctl_errno = errno;
1737
 
#ifdef __linux__
1738
 
    if(restore_loglevel){
1739
 
      ret_linux = klogctl(7, NULL, 0);
1740
 
      if(ret_linux == -1){
1741
 
        perror_plus("klogctl");
1742
 
      }
1743
 
    }
1744
 
#endif  /* __linux__ */
1745
 
    
1746
 
    /* If raise_privileges() succeeded above */
1747
 
    if(ret_errno == 0){
1748
 
      /* Lower privileges */
1749
 
      ret_errno = lower_privileges();
1750
 
      if(ret_errno != 0){
1751
 
        errno = ret_errno;
1752
 
        perror_plus("Failed to lower privileges");
1753
 
      }
1754
 
    }
1755
 
    
1756
 
    /* Close the socket */
1757
 
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1578
  /* Re-raise priviliges */
 
1579
  raise_privileges();
 
1580
    
 
1581
#ifdef __linux__
 
1582
  /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
 
1583
     messages about the network interface to mess up the prompt */
 
1584
  ret = klogctl(8, NULL, 5);
 
1585
  bool restore_loglevel = true;
 
1586
  if(ret == -1){
 
1587
    restore_loglevel = false;
 
1588
    perror_plus("klogctl");
 
1589
  }
 
1590
#endif  /* __linux__ */
 
1591
    
 
1592
  sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1593
  if(sd < 0){
 
1594
    perror_plus("socket");
 
1595
#ifdef __linux__
 
1596
    if(restore_loglevel){
 
1597
      ret = klogctl(7, NULL, 0);
 
1598
      if(ret == -1){
 
1599
        perror_plus("klogctl");
 
1600
      }
 
1601
    }
 
1602
#endif  /* __linux__ */
 
1603
    /* Lower privileges */
 
1604
    lower_privileges();
 
1605
    return EX_OSERR;
 
1606
;
 
1607
  }
 
1608
  strcpy(network.ifr_name, interface);
 
1609
  ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
1610
  if(ret == -1){
 
1611
    perror_plus("ioctl SIOCGIFFLAGS");
 
1612
#ifdef __linux__
 
1613
    if(restore_loglevel){
 
1614
      ret = klogctl(7, NULL, 0);
 
1615
      if(ret == -1){
 
1616
        perror_plus("klogctl");
 
1617
      }
 
1618
    }
 
1619
#endif  /* __linux__ */
 
1620
    /* Lower privileges */
 
1621
    lower_privileges();
 
1622
    return EX_OSERR;
 
1623
  }
 
1624
  if((network.ifr_flags & IFF_UP) == 0){
 
1625
    network.ifr_flags |= IFF_UP;
 
1626
    ret = ioctl(sd, SIOCSIFFLAGS, &network);
1758
1627
    if(ret == -1){
1759
 
      perror_plus("close");
1760
 
    }
1761
 
    
1762
 
    if(ret_setflags == -1){
1763
 
      errno = ioctl_errno;
1764
1628
      perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1765
 
      errno = old_errno;
1766
 
      return ioctl_errno;
 
1629
#ifdef __linux__
 
1630
      if(restore_loglevel){
 
1631
        ret = klogctl(7, NULL, 0);
 
1632
        if(ret == -1){
 
1633
          perror_plus("klogctl");
 
1634
        }
 
1635
      }
 
1636
#endif  /* __linux__ */
 
1637
        /* Lower privileges */
 
1638
      lower_privileges();
 
1639
      return EX_OSERR;
1767
1640
    }
1768
 
  } else if(debug){
1769
 
    fprintf_plus(stderr, "Interface \"%s\" is already up; good\n",
1770
 
                 interface);
1771
1641
  }
1772
 
  
1773
1642
  /* Sleep checking until interface is running.
1774
1643
     Check every 0.25s, up to total time of delay */
1775
1644
  for(int i=0; i < delay * 4; i++){
1776
 
    if(interface_is_running(interface)){
 
1645
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
1646
    if(ret == -1){
 
1647
      perror_plus("ioctl SIOCGIFFLAGS");
 
1648
    } else if(network.ifr_flags & IFF_RUNNING){
1777
1649
      break;
1778
1650
    }
1779
1651
    struct timespec sleeptime = { .tv_nsec = 250000000 };
1782
1654
      perror_plus("nanosleep");
1783
1655
    }
1784
1656
  }
1785
 
  
1786
 
  errno = old_errno;
1787
 
  return 0;
1788
 
}
1789
 
 
1790
 
__attribute__((nonnull, warn_unused_result))
1791
 
error_t take_down_interface(const char *const interface){
1792
 
  error_t old_errno = errno;
1793
 
  struct ifreq network;
1794
 
  unsigned int if_index = if_nametoindex(interface);
1795
 
  if(if_index == 0){
1796
 
    fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
1797
 
    errno = old_errno;
1798
 
    return ENXIO;
 
1657
  /* Close the socket */
 
1658
  ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1659
  if(ret == -1){
 
1660
    perror_plus("close");
1799
1661
  }
1800
 
  if(interface_is_up(interface)){
1801
 
    error_t ret_errno = 0, ioctl_errno = 0;
1802
 
    if(not get_flags(interface, &network) and debug){
1803
 
      ret_errno = errno;
1804
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1805
 
                   "\"%s\"\n", interface);
1806
 
      errno = old_errno;
1807
 
      return ret_errno;
1808
 
    }
1809
 
    network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
1810
 
    
1811
 
    int sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1812
 
    if(sd == -1){
1813
 
      ret_errno = errno;
1814
 
      perror_plus("socket");
1815
 
      errno = old_errno;
1816
 
      return ret_errno;
1817
 
    }
1818
 
    
1819
 
    if(debug){
1820
 
      fprintf_plus(stderr, "Taking down interface \"%s\"\n",
1821
 
                   interface);
1822
 
    }
1823
 
    
1824
 
    /* Raise privileges */
1825
 
    ret_errno = raise_privileges();
1826
 
    if(ret_errno != 0){
1827
 
      perror_plus("Failed to raise privileges");
1828
 
    }
1829
 
    int ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
1830
 
    ioctl_errno = errno;
1831
 
    
1832
 
    /* If raise_privileges() succeeded above */
1833
 
    if(ret_errno == 0){
1834
 
      /* Lower privileges */
1835
 
      ret_errno = lower_privileges();
1836
 
      if(ret_errno != 0){
1837
 
        errno = ret_errno;
1838
 
        perror_plus("Failed to lower privileges");
1839
 
      }
1840
 
    }
1841
 
    
1842
 
    /* Close the socket */
1843
 
    int ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1662
#ifdef __linux__
 
1663
  if(restore_loglevel){
 
1664
    /* Restores kernel loglevel to default */
 
1665
    ret = klogctl(7, NULL, 0);
1844
1666
    if(ret == -1){
1845
 
      perror_plus("close");
1846
 
    }
1847
 
    
1848
 
    if(ret_setflags == -1){
1849
 
      errno = ioctl_errno;
1850
 
      perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
1851
 
      errno = old_errno;
1852
 
      return ioctl_errno;
1853
 
    }
1854
 
  } else if(debug){
1855
 
    fprintf_plus(stderr, "Interface \"%s\" is already down; odd\n",
1856
 
                 interface);
 
1667
      perror_plus("klogctl");
 
1668
    }
1857
1669
  }
1858
 
  
1859
 
  errno = old_errno;
1860
 
  return 0;
 
1670
#endif  /* __linux__ */
 
1671
  /* Lower privileges */
 
1672
  lower_privileges();
 
1673
  return errno;
1861
1674
}
1862
1675
 
1863
1676
int main(int argc, char *argv[]){
1864
 
  mandos_context mc = { .server = NULL, .dh_bits = 1024,
1865
 
                        .priority = "SECURE256:!CTYPE-X.509:"
1866
 
                        "+CTYPE-OPENPGP", .current_server = NULL,
1867
 
                        .interfaces = NULL, .interfaces_size = 0 };
1868
1677
  AvahiSServiceBrowser *sb = NULL;
1869
 
  error_t ret_errno;
 
1678
  int error;
1870
1679
  int ret;
1871
1680
  intmax_t tmpmax;
1872
1681
  char *tmp;
1873
1682
  int exitcode = EXIT_SUCCESS;
1874
 
  char *interfaces_to_take_down = NULL;
1875
 
  size_t interfaces_to_take_down_size = 0;
1876
 
  char run_tempdir[] = "/run/tmp/mandosXXXXXX";
1877
 
  char old_tempdir[] = "/tmp/mandosXXXXXX";
1878
 
  char *tempdir = NULL;
 
1683
  const char *interface = "";
 
1684
  struct ifreq network;
 
1685
  int sd = -1;
 
1686
  bool take_down_interface = false;
 
1687
  char tempdir[] = "/tmp/mandosXXXXXX";
 
1688
  bool tempdir_created = false;
1879
1689
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1880
1690
  const char *seckey = PATHDIR "/" SECKEY;
1881
1691
  const char *pubkey = PATHDIR "/" PUBKEY;
1882
 
  char *interfaces_hooks = NULL;
1883
1692
  
1884
1693
  bool gnutls_initialized = false;
1885
1694
  bool gpgme_initialized = false;
1976
1785
        connect_to = arg;
1977
1786
        break;
1978
1787
      case 'i':                 /* --interface */
1979
 
        ret_errno = argz_add_sep(&mc.interfaces, &mc.interfaces_size,
1980
 
                                 arg, (int)',');
1981
 
        if(ret_errno != 0){
1982
 
          argp_error(state, "%s", strerror(ret_errno));
1983
 
        }
 
1788
        interface = arg;
1984
1789
        break;
1985
1790
      case 's':                 /* --seckey */
1986
1791
        seckey = arg;
2063
1868
    /* Work around Debian bug #633582:
2064
1869
       <http://bugs.debian.org/633582> */
2065
1870
    
2066
 
    /* Re-raise privileges */
2067
 
    ret_errno = raise_privileges();
2068
 
    if(ret_errno != 0){
2069
 
      errno = ret_errno;
2070
 
      perror_plus("Failed to raise privileges");
2071
 
    } else {
 
1871
    /* Re-raise priviliges */
 
1872
    if(raise_privileges() == 0){
2072
1873
      struct stat st;
2073
1874
      
2074
1875
      if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
2114
1915
      }
2115
1916
    
2116
1917
      /* Lower privileges */
2117
 
      ret_errno = lower_privileges();
2118
 
      if(ret_errno != 0){
2119
 
        errno = ret_errno;
2120
 
        perror_plus("Failed to lower privileges");
2121
 
      }
2122
 
    }
2123
 
  }
2124
 
  
2125
 
  /* Remove invalid interface names (except "none") */
2126
 
  {
2127
 
    char *interface = NULL;
2128
 
    while((interface = argz_next(mc.interfaces, mc.interfaces_size,
2129
 
                                 interface))){
2130
 
      if(strcmp(interface, "none") != 0
2131
 
         and if_nametoindex(interface) == 0){
2132
 
        if(interface[0] != '\0'){
2133
 
          fprintf_plus(stderr, "Not using nonexisting interface"
2134
 
                       " \"%s\"\n", interface);
2135
 
        }
2136
 
        argz_delete(&mc.interfaces, &mc.interfaces_size, interface);
2137
 
        interface = NULL;
 
1918
      errno = 0;
 
1919
      ret = seteuid(uid);
 
1920
      if(ret == -1){
 
1921
        perror_plus("seteuid");
2138
1922
      }
2139
1923
    }
2140
1924
  }
2141
1925
  
2142
1926
  /* Run network hooks */
2143
 
  {
2144
 
    if(mc.interfaces != NULL){
2145
 
      interfaces_hooks = malloc(mc.interfaces_size);
2146
 
      if(interfaces_hooks == NULL){
 
1927
  if(not run_network_hooks("start", interface, delay)){
 
1928
    goto end;
 
1929
  }
 
1930
  
 
1931
  if(not debug){
 
1932
    avahi_set_log_function(empty_log);
 
1933
  }
 
1934
  
 
1935
  if(interface[0] == '\0'){
 
1936
    struct dirent **direntries;
 
1937
    /* First look for interfaces that are up */
 
1938
    ret = scandir(sys_class_net, &direntries, up_interface,
 
1939
                  alphasort);
 
1940
    if(ret == 0){
 
1941
      /* No up interfaces, look for any good interfaces */
 
1942
      free(direntries);
 
1943
      ret = scandir(sys_class_net, &direntries, good_interface,
 
1944
                    alphasort);
 
1945
    }
 
1946
    if(ret >= 1){
 
1947
      /* Pick the first interface returned */
 
1948
      interface = strdup(direntries[0]->d_name);
 
1949
      if(debug){
 
1950
        fprintf_plus(stderr, "Using interface \"%s\"\n", interface);
 
1951
      }
 
1952
      if(interface == NULL){
2147
1953
        perror_plus("malloc");
 
1954
        free(direntries);
 
1955
        exitcode = EXIT_FAILURE;
2148
1956
        goto end;
2149
1957
      }
2150
 
      memcpy(interfaces_hooks, mc.interfaces, mc.interfaces_size);
2151
 
      argz_stringify(interfaces_hooks, mc.interfaces_size, (int)',');
 
1958
      free(direntries);
 
1959
    } else {
 
1960
      free(direntries);
 
1961
      fprintf_plus(stderr, "Could not find a network interface\n");
 
1962
      exitcode = EXIT_FAILURE;
 
1963
      goto end;
2152
1964
    }
2153
 
    run_network_hooks("start", interfaces_hooks != NULL ?
2154
 
                      interfaces_hooks : "", delay);
2155
 
  }
2156
 
  
2157
 
  if(not debug){
2158
 
    avahi_set_log_function(empty_log);
2159
1965
  }
2160
1966
  
2161
1967
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
2162
1968
     from the signal handler */
2163
1969
  /* Initialize the pseudo-RNG for Avahi */
2164
1970
  srand((unsigned int) time(NULL));
2165
 
  simple_poll = avahi_simple_poll_new();
2166
 
  if(simple_poll == NULL){
 
1971
  mc.simple_poll = avahi_simple_poll_new();
 
1972
  if(mc.simple_poll == NULL){
2167
1973
    fprintf_plus(stderr,
2168
1974
                 "Avahi: Failed to create simple poll object.\n");
2169
1975
    exitcode = EX_UNAVAILABLE;
2233
2039
    }
2234
2040
  }
2235
2041
  
2236
 
  /* If no interfaces were specified, make a list */
2237
 
  if(mc.interfaces == NULL){
2238
 
    struct dirent **direntries;
2239
 
    /* Look for any good interfaces */
2240
 
    ret = scandir(sys_class_net, &direntries, good_interface,
2241
 
                  alphasort);
2242
 
    if(ret >= 1){
2243
 
      /* Add all found interfaces to interfaces list */
2244
 
      for(int i = 0; i < ret; ++i){
2245
 
        ret_errno = argz_add(&mc.interfaces, &mc.interfaces_size,
2246
 
                             direntries[i]->d_name);
2247
 
        if(ret_errno != 0){
2248
 
          errno = ret_errno;
2249
 
          perror_plus("argz_add");
2250
 
          continue;
2251
 
        }
2252
 
        if(debug){
2253
 
          fprintf_plus(stderr, "Will use interface \"%s\"\n",
2254
 
                       direntries[i]->d_name);
2255
 
        }
2256
 
      }
2257
 
      free(direntries);
2258
 
    } else {
2259
 
      free(direntries);
2260
 
      fprintf_plus(stderr, "Could not find a network interface\n");
2261
 
      exitcode = EXIT_FAILURE;
2262
 
      goto end;
2263
 
    }
2264
 
  }
2265
 
  
2266
 
  /* Bring up interfaces which are down, and remove any "none"s */
2267
 
  {
2268
 
    char *interface = NULL;
2269
 
    while((interface = argz_next(mc.interfaces, mc.interfaces_size,
2270
 
                                 interface))){
2271
 
      /* If interface name is "none", stop bringing up interfaces.
2272
 
         Also remove all instances of "none" from the list */
2273
 
      if(strcmp(interface, "none") == 0){
2274
 
        argz_delete(&mc.interfaces, &mc.interfaces_size,
2275
 
                    interface);
2276
 
        interface = NULL;
2277
 
        while((interface = argz_next(mc.interfaces,
2278
 
                                     mc.interfaces_size, interface))){
2279
 
          if(strcmp(interface, "none") == 0){
2280
 
            argz_delete(&mc.interfaces, &mc.interfaces_size,
2281
 
                        interface);
2282
 
            interface = NULL;
2283
 
          }
2284
 
        }
2285
 
        break;
2286
 
      }
2287
 
      bool interface_was_up = interface_is_up(interface);
2288
 
      errno = bring_up_interface(interface, delay);
2289
 
      if(not interface_was_up){
2290
 
        if(errno != 0){
2291
 
          perror_plus("Failed to bring up interface");
2292
 
        } else {
2293
 
          errno = argz_add(&interfaces_to_take_down,
2294
 
                           &interfaces_to_take_down_size,
2295
 
                           interface);
2296
 
          if(errno != 0){
2297
 
            perror_plus("argz_add");
2298
 
          }
2299
 
        }
2300
 
      }
2301
 
    }
2302
 
    if(debug and (interfaces_to_take_down == NULL)){
2303
 
      fprintf_plus(stderr, "No interfaces were brought up\n");
2304
 
    }
2305
 
  }
2306
 
  
2307
 
  /* If we only got one interface, explicitly use only that one */
2308
 
  if(argz_count(mc.interfaces, mc.interfaces_size) == 1){
2309
 
    if(debug){
2310
 
      fprintf_plus(stderr, "Using only interface \"%s\"\n",
2311
 
                   mc.interfaces);
2312
 
    }
2313
 
    if_index = (AvahiIfIndex)if_nametoindex(mc.interfaces);
 
2042
  /* If the interface is down, bring it up */
 
2043
  if((interface[0] != '\0') and (strcmp(interface, "none") != 0)){
 
2044
    ret = bring_up_interface(interface, delay);
 
2045
    if(ret){
 
2046
      errno = ret;
 
2047
      perror_plus("Failed to bring up interface");
 
2048
    }
2314
2049
  }
2315
2050
  
2316
2051
  if(quit_now){
2317
2052
    goto end;
2318
2053
  }
2319
2054
  
2320
 
  ret = init_gnutls_global(pubkey, seckey, &mc);
 
2055
  ret = init_gnutls_global(pubkey, seckey);
2321
2056
  if(ret == -1){
2322
2057
    fprintf_plus(stderr, "init_gnutls_global failed\n");
2323
2058
    exitcode = EX_UNAVAILABLE;
2330
2065
    goto end;
2331
2066
  }
2332
2067
  
2333
 
  /* Try /run/tmp before /tmp */
2334
 
  tempdir = mkdtemp(run_tempdir);
2335
 
  if(tempdir == NULL and errno == ENOENT){
2336
 
      if(debug){
2337
 
        fprintf_plus(stderr, "Tempdir %s did not work, trying %s\n",
2338
 
                     run_tempdir, old_tempdir);
2339
 
      }
2340
 
      tempdir = mkdtemp(old_tempdir);
2341
 
  }
2342
 
  if(tempdir == NULL){
 
2068
  if(mkdtemp(tempdir) == NULL){
2343
2069
    perror_plus("mkdtemp");
2344
2070
    goto end;
2345
2071
  }
 
2072
  tempdir_created = true;
2346
2073
  
2347
2074
  if(quit_now){
2348
2075
    goto end;
2349
2076
  }
2350
2077
  
2351
 
  if(not init_gpgme(pubkey, seckey, tempdir, &mc)){
 
2078
  if(not init_gpgme(pubkey, seckey, tempdir)){
2352
2079
    fprintf_plus(stderr, "init_gpgme failed\n");
2353
2080
    exitcode = EX_UNAVAILABLE;
2354
2081
    goto end;
2375
2102
      goto end;
2376
2103
    }
2377
2104
    
2378
 
    in_port_t port;
 
2105
    uint16_t port;
2379
2106
    errno = 0;
2380
2107
    tmpmax = strtoimax(address+1, &tmp, 10);
2381
2108
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
2382
 
       or tmpmax != (in_port_t)tmpmax){
 
2109
       or tmpmax != (uint16_t)tmpmax){
2383
2110
      fprintf_plus(stderr, "Bad port number\n");
2384
2111
      exitcode = EX_USAGE;
2385
2112
      goto end;
2386
2113
    }
2387
 
    
 
2114
  
2388
2115
    if(quit_now){
2389
2116
      goto end;
2390
2117
    }
2391
2118
    
2392
 
    port = (in_port_t)tmpmax;
 
2119
    port = (uint16_t)tmpmax;
2393
2120
    *address = '\0';
2394
2121
    /* Colon in address indicates IPv6 */
2395
2122
    int af;
2411
2138
    }
2412
2139
    
2413
2140
    while(not quit_now){
2414
 
      ret = start_mandos_communication(address, port, if_index, af,
2415
 
                                       &mc);
 
2141
      ret = start_mandos_communication(address, port, if_index, af);
2416
2142
      if(quit_now or ret == 0){
2417
2143
        break;
2418
2144
      }
2420
2146
        fprintf_plus(stderr, "Retrying in %d seconds\n",
2421
2147
                     (int)retry_interval);
2422
2148
      }
2423
 
      sleep((unsigned int)retry_interval);
 
2149
      sleep((int)retry_interval);
2424
2150
    }
2425
2151
    
2426
 
    if(not quit_now){
 
2152
    if (not quit_now){
2427
2153
      exitcode = EXIT_SUCCESS;
2428
2154
    }
2429
2155
    
2444
2170
    config.publish_domain = 0;
2445
2171
    
2446
2172
    /* Allocate a new server */
2447
 
    mc.server = avahi_server_new(avahi_simple_poll_get(simple_poll),
2448
 
                                 &config, NULL, NULL, &ret_errno);
 
2173
    mc.server = avahi_server_new(avahi_simple_poll_get
 
2174
                                 (mc.simple_poll), &config, NULL,
 
2175
                                 NULL, &error);
2449
2176
    
2450
2177
    /* Free the Avahi configuration data */
2451
2178
    avahi_server_config_free(&config);
2454
2181
  /* Check if creating the Avahi server object succeeded */
2455
2182
  if(mc.server == NULL){
2456
2183
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
2457
 
                 avahi_strerror(ret_errno));
 
2184
                 avahi_strerror(error));
2458
2185
    exitcode = EX_UNAVAILABLE;
2459
2186
    goto end;
2460
2187
  }
2466
2193
  /* Create the Avahi service browser */
2467
2194
  sb = avahi_s_service_browser_new(mc.server, if_index,
2468
2195
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2469
 
                                   NULL, 0, browse_callback,
2470
 
                                   (void *)&mc);
 
2196
                                   NULL, 0, browse_callback, NULL);
2471
2197
  if(sb == NULL){
2472
2198
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
2473
2199
                 avahi_strerror(avahi_server_errno(mc.server)));
2485
2211
    fprintf_plus(stderr, "Starting Avahi loop search\n");
2486
2212
  }
2487
2213
 
2488
 
  ret = avahi_loop_with_timeout(simple_poll,
2489
 
                                (int)(retry_interval * 1000), &mc);
 
2214
  ret = avahi_loop_with_timeout(mc.simple_poll,
 
2215
                                (int)(retry_interval * 1000));
2490
2216
  if(debug){
2491
2217
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
2492
2218
                 (ret == 0) ? "successfully" : "with error");
2499
2225
  }
2500
2226
  
2501
2227
  /* Cleanup things */
2502
 
  free(mc.interfaces);
2503
 
  
2504
2228
  if(sb != NULL)
2505
2229
    avahi_s_service_browser_free(sb);
2506
2230
  
2507
2231
  if(mc.server != NULL)
2508
2232
    avahi_server_free(mc.server);
2509
2233
  
2510
 
  if(simple_poll != NULL)
2511
 
    avahi_simple_poll_free(simple_poll);
 
2234
  if(mc.simple_poll != NULL)
 
2235
    avahi_simple_poll_free(mc.simple_poll);
2512
2236
  
2513
2237
  if(gnutls_initialized){
2514
2238
    gnutls_certificate_free_credentials(mc.cred);
2531
2255
    }
2532
2256
  }
2533
2257
  
2534
 
  /* Re-raise privileges */
 
2258
  /* Run network hooks */
 
2259
  run_network_hooks("stop", interface, delay);
 
2260
  
 
2261
  /* Re-raise priviliges */
2535
2262
  {
2536
 
    ret_errno = raise_privileges();
2537
 
    if(ret_errno != 0){
2538
 
      perror_plus("Failed to raise privileges");
2539
 
    } else {
2540
 
      
2541
 
      /* Run network hooks */
2542
 
      run_network_hooks("stop", interfaces_hooks != NULL ?
2543
 
                        interfaces_hooks : "", delay);
2544
 
      
2545
 
      /* Take down the network interfaces which were brought up */
2546
 
      {
2547
 
        char *interface = NULL;
2548
 
        while((interface=argz_next(interfaces_to_take_down,
2549
 
                                   interfaces_to_take_down_size,
2550
 
                                   interface))){
2551
 
          ret_errno = take_down_interface(interface);
2552
 
          if(ret_errno != 0){
2553
 
            errno = ret_errno;
2554
 
            perror_plus("Failed to take down interface");
2555
 
          }
2556
 
        }
2557
 
        if(debug and (interfaces_to_take_down == NULL)){
2558
 
          fprintf_plus(stderr, "No interfaces needed to be taken"
2559
 
                       " down\n");
2560
 
        }
2561
 
      }
2562
 
    }
2563
 
    ret_errno = lower_privileges_permanently();
2564
 
    if(ret_errno != 0){
2565
 
      perror_plus("Failed to lower privileges permanently");
2566
 
    }
2567
 
  }
2568
 
  
2569
 
  free(interfaces_to_take_down);
2570
 
  free(interfaces_hooks);
 
2263
    raise_privileges();
 
2264
    
 
2265
    /* Take down the network interface */
 
2266
    if(take_down_interface and geteuid() == 0){
 
2267
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
2268
      if(ret == -1){
 
2269
        perror_plus("ioctl SIOCGIFFLAGS");
 
2270
      } else if(network.ifr_flags & IFF_UP){
 
2271
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
 
2272
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
2273
        if(ret == -1){
 
2274
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
 
2275
        }
 
2276
      }
 
2277
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
2278
      if(ret == -1){
 
2279
        perror_plus("close");
 
2280
      }
 
2281
    }
 
2282
  }
 
2283
  /* Lower privileges permanently */
 
2284
  errno = 0;
 
2285
  ret = setuid(uid);
 
2286
  if(ret == -1){
 
2287
    perror_plus("setuid");
 
2288
  }
2571
2289
  
2572
2290
  /* Removes the GPGME temp directory and all files inside */
2573
 
  if(tempdir != NULL){
 
2291
  if(tempdir_created){
2574
2292
    struct dirent **direntries = NULL;
2575
2293
    struct dirent *direntry = NULL;
2576
2294
    int numentries = scandir(tempdir, &direntries, notdotentries,
2577
2295
                             alphasort);
2578
 
    if(numentries > 0){
 
2296
    if (numentries > 0){
2579
2297
      for(int i = 0; i < numentries; i++){
2580
2298
        direntry = direntries[i];
2581
2299
        char *fullname = NULL;
2596
2314
 
2597
2315
    /* need to clean even if 0 because man page doesn't specify */
2598
2316
    free(direntries);
2599
 
    if(numentries == -1){
 
2317
    if (numentries == -1){
2600
2318
      perror_plus("scandir");
2601
2319
    }
2602
2320
    ret = rmdir(tempdir);