/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

Merge from Björn:

* plugin-runner.c (main): Bug fix: For the "--options-for" option, do
                          not mangle arguments with colon characters.
                          Also support adding empty arguments.

* plugins.d/mandos-client.c: (mc): New global variable; moved from
                                   "main".
  (init_gpgme, pgp_packet_decrypt, init_gnutls_global,
  init_gnutls_session, start_mandos_communication): Removed "mc"
                                                    argument.  All
                                                    callers changed.

  (resolve_callback, browse_callback): Ignore "userdata" argument.
                                       All callers changed.
  (handle_sigterm): New function.
  (main): Add "handle_sigterm" as signal handler for SIGTERM before
          starting the main loop.

Show diffs side-by-side

added added

removed removed

Lines of Context:
36
36
#define _GNU_SOURCE             /* TEMP_FAILURE_RETRY(), asprintf() */
37
37
 
38
38
#include <stdio.h>              /* fprintf(), stderr, fwrite(),
39
 
                                   stdout, ferror(), sscanf */
 
39
                                   stdout, ferror(), sscanf(),
 
40
                                   remove() */
40
41
#include <stdint.h>             /* uint16_t, uint32_t */
41
42
#include <stddef.h>             /* NULL, size_t, ssize_t */
42
43
#include <stdlib.h>             /* free(), EXIT_SUCCESS, EXIT_FAILURE,
43
44
                                   srand() */
44
 
#include <stdbool.h>            /* bool, true */
 
45
#include <stdbool.h>            /* bool, false, true */
45
46
#include <string.h>             /* memset(), strcmp(), strlen(),
46
47
                                   strerror(), asprintf(), strcpy() */
47
 
#include <sys/ioctl.h>          /* ioctl */
 
48
#include <sys/ioctl.h>          /* ioctl */
48
49
#include <sys/types.h>          /* socket(), inet_pton(), sockaddr,
49
50
                                   sockaddr_in6, PF_INET6,
50
 
                                   SOCK_STREAM, INET6_ADDRSTRLEN,
51
 
                                   uid_t, gid_t, open(), opendir(),
52
 
                                   DIR */
 
51
                                   SOCK_STREAM, uid_t, gid_t, open(),
 
52
                                   opendir(), DIR */
53
53
#include <sys/stat.h>           /* open() */
54
54
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
55
 
                                   struct in6_addr, inet_pton(),
56
 
                                   connect() */
 
55
                                   inet_pton(), connect() */
57
56
#include <fcntl.h>              /* open() */
58
57
#include <dirent.h>             /* opendir(), struct dirent, readdir()
59
58
                                 */
60
59
#include <inttypes.h>           /* PRIu16, intmax_t, SCNdMAX */
61
60
#include <assert.h>             /* assert() */
62
61
#include <errno.h>              /* perror(), errno */
63
 
#include <time.h>               /* time() */
 
62
#include <time.h>               /* nanosleep(), time() */
64
63
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
65
64
                                   SIOCSIFFLAGS, if_indextoname(),
66
65
                                   if_nametoindex(), IF_NAMESIZE */
67
 
#include <netinet/in.h>
 
66
#include <netinet/in.h>         /* IN6_IS_ADDR_LINKLOCAL,
 
67
                                   INET_ADDRSTRLEN, INET6_ADDRSTRLEN
 
68
                                */
68
69
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
69
70
                                   getuid(), getgid(), setuid(),
70
71
                                   setgid() */
71
72
#include <arpa/inet.h>          /* inet_pton(), htons */
72
 
#include <iso646.h>             /* not, and, or */
 
73
#include <iso646.h>             /* not, or, and */
73
74
#include <argp.h>               /* struct argp_option, error_t, struct
74
75
                                   argp_state, struct argp,
75
76
                                   argp_parse(), ARGP_KEY_ARG,
76
77
                                   ARGP_KEY_END, ARGP_ERR_UNKNOWN */
 
78
#include <signal.h>             /* sigemptyset(), sigaddset(),
 
79
                                   sigaction(), SIGTERM, sigaction */
 
80
 
 
81
#ifdef __linux__
 
82
#include <sys/klog.h>           /* klogctl() */
 
83
#endif
77
84
 
78
85
/* Avahi */
79
86
/* All Avahi types, constants and functions
125
132
  gpgme_ctx_t ctx;
126
133
} mandos_context;
127
134
 
 
135
/* global context so signal handler can reach it*/
 
136
mandos_context mc;
 
137
 
128
138
/*
129
 
 * Make room in "buffer" for at least BUFFER_SIZE additional bytes.
130
 
 * "buffer_capacity" is how much is currently allocated,
131
 
 * "buffer_length" is how much is already used.
 
139
 * Make additional room in "buffer" for at least BUFFER_SIZE
 
140
 * additional bytes. "buffer_capacity" is how much is currently
 
141
 * allocated, "buffer_length" is how much is already used.
132
142
 */
133
 
size_t adjustbuffer(char **buffer, size_t buffer_length,
 
143
size_t incbuffer(char **buffer, size_t buffer_length,
134
144
                  size_t buffer_capacity){
135
145
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
136
146
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
145
155
/* 
146
156
 * Initialize GPGME.
147
157
 */
148
 
static bool init_gpgme(mandos_context *mc, const char *seckey,
 
158
static bool init_gpgme(const char *seckey,
149
159
                       const char *pubkey, const char *tempdir){
150
160
  int ret;
151
161
  gpgme_error_t rc;
153
163
  
154
164
  
155
165
  /*
156
 
   * Helper function to insert pub and seckey to the enigne keyring.
 
166
   * Helper function to insert pub and seckey to the engine keyring.
157
167
   */
158
168
  bool import_key(const char *filename){
159
169
    int fd;
172
182
      return false;
173
183
    }
174
184
    
175
 
    rc = gpgme_op_import(mc->ctx, pgp_data);
 
185
    rc = gpgme_op_import(mc.ctx, pgp_data);
176
186
    if(rc != GPG_ERR_NO_ERROR){
177
187
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
178
188
              gpgme_strsource(rc), gpgme_strerror(rc));
188
198
  }
189
199
  
190
200
  if(debug){
191
 
    fprintf(stderr, "Initialize gpgme\n");
 
201
    fprintf(stderr, "Initializing GPGME\n");
192
202
  }
193
203
  
194
204
  /* Init GPGME */
221
231
  }
222
232
  
223
233
  /* Create new GPGME "context" */
224
 
  rc = gpgme_new(&(mc->ctx));
 
234
  rc = gpgme_new(&(mc.ctx));
225
235
  if(rc != GPG_ERR_NO_ERROR){
226
236
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
227
237
            gpgme_strsource(rc), gpgme_strerror(rc));
239
249
 * Decrypt OpenPGP data.
240
250
 * Returns -1 on error
241
251
 */
242
 
static ssize_t pgp_packet_decrypt(const mandos_context *mc,
243
 
                                  const char *cryptotext,
 
252
static ssize_t pgp_packet_decrypt(const char *cryptotext,
244
253
                                  size_t crypto_size,
245
254
                                  char **plaintext){
246
255
  gpgme_data_t dh_crypto, dh_plain;
273
282
  
274
283
  /* Decrypt data from the cryptotext data buffer to the plaintext
275
284
     data buffer */
276
 
  rc = gpgme_op_decrypt(mc->ctx, dh_crypto, dh_plain);
 
285
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
277
286
  if(rc != GPG_ERR_NO_ERROR){
278
287
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
279
288
            gpgme_strsource(rc), gpgme_strerror(rc));
280
289
    plaintext_length = -1;
281
290
    if(debug){
282
291
      gpgme_decrypt_result_t result;
283
 
      result = gpgme_op_decrypt_result(mc->ctx);
 
292
      result = gpgme_op_decrypt_result(mc.ctx);
284
293
      if(result == NULL){
285
294
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
286
295
      } else {
322
331
  
323
332
  *plaintext = NULL;
324
333
  while(true){
325
 
    plaintext_capacity = adjustbuffer(plaintext,
 
334
    plaintext_capacity = incbuffer(plaintext,
326
335
                                      (size_t)plaintext_length,
327
336
                                      plaintext_capacity);
328
337
    if(plaintext_capacity == 0){
329
 
        perror("adjustbuffer");
 
338
        perror("incbuffer");
330
339
        plaintext_length = -1;
331
340
        goto decrypt_end;
332
341
    }
364
373
  return plaintext_length;
365
374
}
366
375
 
367
 
static const char * safer_gnutls_strerror(int value) {
 
376
static const char * safer_gnutls_strerror(int value){
368
377
  const char *ret = gnutls_strerror(value); /* Spurious warning from
369
378
                                               -Wunreachable-code */
370
379
  if(ret == NULL)
378
387
  fprintf(stderr, "GnuTLS: %s", string);
379
388
}
380
389
 
381
 
static int init_gnutls_global(mandos_context *mc,
382
 
                              const char *pubkeyfilename,
 
390
static int init_gnutls_global(const char *pubkeyfilename,
383
391
                              const char *seckeyfilename){
384
392
  int ret;
385
393
  
388
396
  }
389
397
  
390
398
  ret = gnutls_global_init();
391
 
  if(ret != GNUTLS_E_SUCCESS) {
 
399
  if(ret != GNUTLS_E_SUCCESS){
392
400
    fprintf(stderr, "GnuTLS global_init: %s\n",
393
401
            safer_gnutls_strerror(ret));
394
402
    return -1;
403
411
  }
404
412
  
405
413
  /* OpenPGP credentials */
406
 
  gnutls_certificate_allocate_credentials(&mc->cred);
 
414
  gnutls_certificate_allocate_credentials(&mc.cred);
407
415
  if(ret != GNUTLS_E_SUCCESS){
408
416
    fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning
409
 
                                                  * from
410
 
                                                  * -Wunreachable-code
411
 
                                                  */
 
417
                                                    from
 
418
                                                    -Wunreachable-code
 
419
                                                 */
412
420
            safer_gnutls_strerror(ret));
413
421
    gnutls_global_deinit();
414
422
    return -1;
421
429
  }
422
430
  
423
431
  ret = gnutls_certificate_set_openpgp_key_file
424
 
    (mc->cred, pubkeyfilename, seckeyfilename,
 
432
    (mc.cred, pubkeyfilename, seckeyfilename,
425
433
     GNUTLS_OPENPGP_FMT_BASE64);
426
 
  if(ret != GNUTLS_E_SUCCESS) {
 
434
  if(ret != GNUTLS_E_SUCCESS){
427
435
    fprintf(stderr,
428
436
            "Error[%d] while reading the OpenPGP key pair ('%s',"
429
437
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
433
441
  }
434
442
  
435
443
  /* GnuTLS server initialization */
436
 
  ret = gnutls_dh_params_init(&mc->dh_params);
437
 
  if(ret != GNUTLS_E_SUCCESS) {
 
444
  ret = gnutls_dh_params_init(&mc.dh_params);
 
445
  if(ret != GNUTLS_E_SUCCESS){
438
446
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
439
447
            " %s\n", safer_gnutls_strerror(ret));
440
448
    goto globalfail;
441
449
  }
442
 
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
443
 
  if(ret != GNUTLS_E_SUCCESS) {
 
450
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
 
451
  if(ret != GNUTLS_E_SUCCESS){
444
452
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
445
453
            safer_gnutls_strerror(ret));
446
454
    goto globalfail;
447
455
  }
448
456
  
449
 
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
 
457
  gnutls_certificate_set_dh_params(mc.cred, mc.dh_params);
450
458
  
451
459
  return 0;
452
460
  
453
461
 globalfail:
454
462
  
455
 
  gnutls_certificate_free_credentials(mc->cred);
 
463
  gnutls_certificate_free_credentials(mc.cred);
456
464
  gnutls_global_deinit();
457
 
  gnutls_dh_params_deinit(mc->dh_params);
 
465
  gnutls_dh_params_deinit(mc.dh_params);
458
466
  return -1;
459
467
}
460
468
 
461
 
static int init_gnutls_session(mandos_context *mc,
462
 
                               gnutls_session_t *session){
 
469
static int init_gnutls_session(gnutls_session_t *session){
463
470
  int ret;
464
471
  /* GnuTLS session creation */
465
472
  ret = gnutls_init(session, GNUTLS_SERVER);
470
477
  
471
478
  {
472
479
    const char *err;
473
 
    ret = gnutls_priority_set_direct(*session, mc->priority, &err);
474
 
    if(ret != GNUTLS_E_SUCCESS) {
 
480
    ret = gnutls_priority_set_direct(*session, mc.priority, &err);
 
481
    if(ret != GNUTLS_E_SUCCESS){
475
482
      fprintf(stderr, "Syntax error at: %s\n", err);
476
483
      fprintf(stderr, "GnuTLS error: %s\n",
477
484
              safer_gnutls_strerror(ret));
481
488
  }
482
489
  
483
490
  ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
484
 
                               mc->cred);
485
 
  if(ret != GNUTLS_E_SUCCESS) {
 
491
                               mc.cred);
 
492
  if(ret != GNUTLS_E_SUCCESS){
486
493
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
487
494
            safer_gnutls_strerror(ret));
488
495
    gnutls_deinit(*session);
493
500
  gnutls_certificate_server_set_request(*session,
494
501
                                        GNUTLS_CERT_IGNORE);
495
502
  
496
 
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
 
503
  gnutls_dh_set_prime_bits(*session, mc.dh_bits);
497
504
  
498
505
  return 0;
499
506
}
505
512
/* Called when a Mandos server is found */
506
513
static int start_mandos_communication(const char *ip, uint16_t port,
507
514
                                      AvahiIfIndex if_index,
508
 
                                      mandos_context *mc){
 
515
                                      int af){
509
516
  int ret, tcp_sd;
510
517
  ssize_t sret;
511
 
  union { struct sockaddr in; struct sockaddr_in6 in6; } to;
 
518
  union {
 
519
    struct sockaddr_in in;
 
520
    struct sockaddr_in6 in6;
 
521
  } to;
512
522
  char *buffer = NULL;
513
523
  char *decrypted_buffer;
514
524
  size_t buffer_length = 0;
516
526
  ssize_t decrypted_buffer_size;
517
527
  size_t written;
518
528
  int retval = 0;
519
 
  char interface[IF_NAMESIZE];
520
529
  gnutls_session_t session;
521
 
  
522
 
  ret = init_gnutls_session(mc, &session);
 
530
  int pf;                       /* Protocol family */
 
531
  
 
532
  switch(af){
 
533
  case AF_INET6:
 
534
    pf = PF_INET6;
 
535
    break;
 
536
  case AF_INET:
 
537
    pf = PF_INET;
 
538
    break;
 
539
  default:
 
540
    fprintf(stderr, "Bad address family: %d\n", af);
 
541
    return -1;
 
542
  }
 
543
  
 
544
  ret = init_gnutls_session(&session);
523
545
  if(ret != 0){
524
546
    return -1;
525
547
  }
526
548
  
527
549
  if(debug){
528
 
    fprintf(stderr, "Setting up a tcp connection to %s, port %" PRIu16
 
550
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
529
551
            "\n", ip, port);
530
552
  }
531
553
  
532
 
  tcp_sd = socket(PF_INET6, SOCK_STREAM, 0);
533
 
  if(tcp_sd < 0) {
 
554
  tcp_sd = socket(pf, SOCK_STREAM, 0);
 
555
  if(tcp_sd < 0){
534
556
    perror("socket");
535
557
    return -1;
536
558
  }
537
559
  
538
 
  if(debug){
539
 
    if(if_indextoname((unsigned int)if_index, interface) == NULL){
540
 
      perror("if_indextoname");
541
 
      return -1;
542
 
    }
543
 
    fprintf(stderr, "Binding to interface %s\n", interface);
544
 
  }
545
 
  
546
560
  memset(&to, 0, sizeof(to));
547
 
  to.in6.sin6_family = AF_INET6;
548
 
  /* It would be nice to have a way to detect if we were passed an
549
 
     IPv4 address here.   Now we assume an IPv6 address. */
550
 
  ret = inet_pton(AF_INET6, ip, &to.in6.sin6_addr);
 
561
  if(af == AF_INET6){
 
562
    to.in6.sin6_family = (uint16_t)af;
 
563
    ret = inet_pton(af, ip, &to.in6.sin6_addr);
 
564
  } else {                      /* IPv4 */
 
565
    to.in.sin_family = (sa_family_t)af;
 
566
    ret = inet_pton(af, ip, &to.in.sin_addr);
 
567
  }
551
568
  if(ret < 0 ){
552
569
    perror("inet_pton");
553
570
    return -1;
556
573
    fprintf(stderr, "Bad address: %s\n", ip);
557
574
    return -1;
558
575
  }
559
 
  to.in6.sin6_port = htons(port); /* Spurious warnings from
 
576
  if(af == AF_INET6){
 
577
    to.in6.sin6_port = htons(port); /* Spurious warnings from
 
578
                                       -Wconversion and
 
579
                                       -Wunreachable-code */
 
580
    
 
581
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
 
582
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
 
583
                              -Wunreachable-code*/
 
584
      if(if_index == AVAHI_IF_UNSPEC){
 
585
        fprintf(stderr, "An IPv6 link-local address is incomplete"
 
586
                " without a network interface\n");
 
587
        return -1;
 
588
      }
 
589
      /* Set the network interface number as scope */
 
590
      to.in6.sin6_scope_id = (uint32_t)if_index;
 
591
    }
 
592
  } else {
 
593
    to.in.sin_port = htons(port); /* Spurious warnings from
560
594
                                     -Wconversion and
561
595
                                     -Wunreachable-code */
562
 
  
563
 
  to.in6.sin6_scope_id = (uint32_t)if_index;
 
596
  }
564
597
  
565
598
  if(debug){
566
 
    fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
567
 
            port);
568
 
    char addrstr[INET6_ADDRSTRLEN] = "";
569
 
    if(inet_ntop(to.in6.sin6_family, &(to.in6.sin6_addr), addrstr,
570
 
                 sizeof(addrstr)) == NULL){
 
599
    if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
 
600
      char interface[IF_NAMESIZE];
 
601
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
 
602
        perror("if_indextoname");
 
603
      } else {
 
604
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
 
605
                ip, interface, port);
 
606
      }
 
607
    } else {
 
608
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
 
609
              port);
 
610
    }
 
611
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
 
612
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
 
613
    const char *pcret;
 
614
    if(af == AF_INET6){
 
615
      pcret = inet_ntop(af, &(to.in6.sin6_addr), addrstr,
 
616
                        sizeof(addrstr));
 
617
    } else {
 
618
      pcret = inet_ntop(af, &(to.in.sin_addr), addrstr,
 
619
                        sizeof(addrstr));
 
620
    }
 
621
    if(pcret == NULL){
571
622
      perror("inet_ntop");
572
623
    } else {
573
624
      if(strcmp(addrstr, ip) != 0){
576
627
    }
577
628
  }
578
629
  
579
 
  ret = connect(tcp_sd, &to.in, sizeof(to));
 
630
  if(af == AF_INET6){
 
631
    ret = connect(tcp_sd, &to.in6, sizeof(to));
 
632
  } else {
 
633
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
 
634
  }
580
635
  if(ret < 0){
581
636
    perror("connect");
582
637
    return -1;
628
683
  /* Read OpenPGP packet that contains the wanted password */
629
684
  
630
685
  if(debug){
631
 
    fprintf(stderr, "Retrieving pgp encrypted password from %s\n",
 
686
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
632
687
            ip);
633
688
  }
634
689
  
635
690
  while(true){
636
 
    buffer_capacity = adjustbuffer(&buffer, buffer_length,
 
691
    buffer_capacity = incbuffer(&buffer, buffer_length,
637
692
                                   buffer_capacity);
638
693
    if(buffer_capacity == 0){
639
 
      perror("adjustbuffer");
 
694
      perror("incbuffer");
640
695
      retval = -1;
641
696
      goto mandos_end;
642
697
    }
681
736
  gnutls_bye(session, GNUTLS_SHUT_RDWR);
682
737
  
683
738
  if(buffer_length > 0){
684
 
    decrypted_buffer_size = pgp_packet_decrypt(mc, buffer,
 
739
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
685
740
                                               buffer_length,
686
741
                                               &decrypted_buffer);
687
742
    if(decrypted_buffer_size >= 0){
722
777
 
723
778
static void resolve_callback(AvahiSServiceResolver *r,
724
779
                             AvahiIfIndex interface,
725
 
                             AVAHI_GCC_UNUSED AvahiProtocol protocol,
 
780
                             AvahiProtocol proto,
726
781
                             AvahiResolverEvent event,
727
782
                             const char *name,
728
783
                             const char *type,
733
788
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
734
789
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
735
790
                             flags,
736
 
                             void* userdata) {
737
 
  mandos_context *mc = userdata;
 
791
                             AVAHI_GCC_UNUSED void* userdata){
738
792
  assert(r);
739
793
  
740
794
  /* Called whenever a service has been resolved successfully or
741
795
     timed out */
742
796
  
743
 
  switch(event) {
 
797
  switch(event){
744
798
  default:
745
799
  case AVAHI_RESOLVER_FAILURE:
746
800
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
747
801
            " of type '%s' in domain '%s': %s\n", name, type, domain,
748
 
            avahi_strerror(avahi_server_errno(mc->server)));
 
802
            avahi_strerror(avahi_server_errno(mc.server)));
749
803
    break;
750
804
    
751
805
  case AVAHI_RESOLVER_FOUND:
757
811
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
758
812
                ip, (intmax_t)interface, port);
759
813
      }
760
 
      int ret = start_mandos_communication(ip, port, interface, mc);
 
814
      int ret = start_mandos_communication(ip, port, interface,
 
815
                                           avahi_proto_to_af(proto));
761
816
      if(ret == 0){
762
 
        avahi_simple_poll_quit(mc->simple_poll);
 
817
        avahi_simple_poll_quit(mc.simple_poll);
763
818
      }
764
819
    }
765
820
  }
766
821
  avahi_s_service_resolver_free(r);
767
822
}
768
823
 
769
 
static void browse_callback( AvahiSServiceBrowser *b,
770
 
                             AvahiIfIndex interface,
771
 
                             AvahiProtocol protocol,
772
 
                             AvahiBrowserEvent event,
773
 
                             const char *name,
774
 
                             const char *type,
775
 
                             const char *domain,
776
 
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
777
 
                             flags,
778
 
                             void* userdata) {
779
 
  mandos_context *mc = userdata;
 
824
static void browse_callback(AvahiSServiceBrowser *b,
 
825
                            AvahiIfIndex interface,
 
826
                            AvahiProtocol protocol,
 
827
                            AvahiBrowserEvent event,
 
828
                            const char *name,
 
829
                            const char *type,
 
830
                            const char *domain,
 
831
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
 
832
                            flags,
 
833
                            AVAHI_GCC_UNUSED void* userdata){
780
834
  assert(b);
781
835
  
782
836
  /* Called whenever a new services becomes available on the LAN or
783
837
     is removed from the LAN */
784
838
  
785
 
  switch(event) {
 
839
  switch(event){
786
840
  default:
787
841
  case AVAHI_BROWSER_FAILURE:
788
842
    
789
843
    fprintf(stderr, "(Avahi browser) %s\n",
790
 
            avahi_strerror(avahi_server_errno(mc->server)));
791
 
    avahi_simple_poll_quit(mc->simple_poll);
 
844
            avahi_strerror(avahi_server_errno(mc.server)));
 
845
    avahi_simple_poll_quit(mc.simple_poll);
792
846
    return;
793
847
    
794
848
  case AVAHI_BROWSER_NEW:
797
851
       the callback function is called the Avahi server will free the
798
852
       resolver for us. */
799
853
    
800
 
    if(!(avahi_s_service_resolver_new(mc->server, interface,
 
854
    if(!(avahi_s_service_resolver_new(mc.server, interface,
801
855
                                       protocol, name, type, domain,
802
856
                                       AVAHI_PROTO_INET6, 0,
803
 
                                       resolve_callback, mc)))
 
857
                                       resolve_callback, NULL)))
804
858
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
805
 
              name, avahi_strerror(avahi_server_errno(mc->server)));
 
859
              name, avahi_strerror(avahi_server_errno(mc.server)));
806
860
    break;
807
861
    
808
862
  case AVAHI_BROWSER_REMOVE:
817
871
  }
818
872
}
819
873
 
 
874
static void handle_sigterm(__attribute__((unused)) int sig){
 
875
  int old_errno = errno;
 
876
  avahi_simple_poll_quit(mc.simple_poll);
 
877
  errno = old_errno;
 
878
}
 
879
 
820
880
int main(int argc, char *argv[]){
821
 
    AvahiSServiceBrowser *sb = NULL;
822
 
    int error;
823
 
    int ret;
824
 
    intmax_t tmpmax;
825
 
    int numchars;
826
 
    int exitcode = EXIT_SUCCESS;
827
 
    const char *interface = "eth0";
828
 
    struct ifreq network;
829
 
    int sd;
830
 
    uid_t uid;
831
 
    gid_t gid;
832
 
    char *connect_to = NULL;
833
 
    char tempdir[] = "/tmp/mandosXXXXXX";
834
 
    AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
835
 
    const char *seckey = PATHDIR "/" SECKEY;
836
 
    const char *pubkey = PATHDIR "/" PUBKEY;
837
 
    
838
 
    mandos_context mc = { .simple_poll = NULL, .server = NULL,
839
 
                          .dh_bits = 1024, .priority = "SECURE256"
840
 
                          ":!CTYPE-X.509:+CTYPE-OPENPGP" };
841
 
    bool gnutls_initalized = false;
842
 
    bool gpgme_initalized = false;
843
 
    
844
 
    {
845
 
      struct argp_option options[] = {
846
 
        { .name = "debug", .key = 128,
847
 
          .doc = "Debug mode", .group = 3 },
848
 
        { .name = "connect", .key = 'c',
849
 
          .arg = "ADDRESS:PORT",
850
 
          .doc = "Connect directly to a specific Mandos server",
851
 
          .group = 1 },
852
 
        { .name = "interface", .key = 'i',
853
 
          .arg = "NAME",
854
 
          .doc = "Interface that will be used to search for Mandos"
855
 
          " servers",
856
 
          .group = 1 },
857
 
        { .name = "seckey", .key = 's',
858
 
          .arg = "FILE",
859
 
          .doc = "OpenPGP secret key file base name",
860
 
          .group = 1 },
861
 
        { .name = "pubkey", .key = 'p',
862
 
          .arg = "FILE",
863
 
          .doc = "OpenPGP public key file base name",
864
 
          .group = 2 },
865
 
        { .name = "dh-bits", .key = 129,
866
 
          .arg = "BITS",
867
 
          .doc = "Bit length of the prime number used in the"
868
 
          " Diffie-Hellman key exchange",
869
 
          .group = 2 },
870
 
        { .name = "priority", .key = 130,
871
 
          .arg = "STRING",
872
 
          .doc = "GnuTLS priority string for the TLS handshake",
873
 
          .group = 1 },
874
 
        { .name = NULL }
875
 
      };
876
 
      
877
 
      error_t parse_opt(int key, char *arg,
878
 
                        struct argp_state *state) {
879
 
        switch(key) {
880
 
        case 128:               /* --debug */
881
 
          debug = true;
882
 
          break;
883
 
        case 'c':               /* --connect */
884
 
          connect_to = arg;
885
 
          break;
886
 
        case 'i':               /* --interface */
887
 
          interface = arg;
888
 
          break;
889
 
        case 's':               /* --seckey */
890
 
          seckey = arg;
891
 
          break;
892
 
        case 'p':               /* --pubkey */
893
 
          pubkey = arg;
894
 
          break;
895
 
        case 129:               /* --dh-bits */
896
 
          ret = sscanf(arg, "%" SCNdMAX "%n", &tmpmax, &numchars);
897
 
          if(ret < 1 or tmpmax != (typeof(mc.dh_bits))tmpmax
898
 
             or arg[numchars] != '\0'){
899
 
            fprintf(stderr, "Bad number of DH bits\n");
900
 
            exit(EXIT_FAILURE);
 
881
  AvahiSServiceBrowser *sb = NULL;
 
882
  int error;
 
883
  int ret;
 
884
  intmax_t tmpmax;
 
885
  int numchars;
 
886
  int exitcode = EXIT_SUCCESS;
 
887
  const char *interface = "eth0";
 
888
  struct ifreq network;
 
889
  int sd;
 
890
  uid_t uid;
 
891
  gid_t gid;
 
892
  char *connect_to = NULL;
 
893
  char tempdir[] = "/tmp/mandosXXXXXX";
 
894
  bool tempdir_created = false;
 
895
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
 
896
  const char *seckey = PATHDIR "/" SECKEY;
 
897
  const char *pubkey = PATHDIR "/" PUBKEY;
 
898
  
 
899
  /* Initialize Mandos context */
 
900
  mc = (mandos_context){ .simple_poll = NULL, .server = NULL,
 
901
                         .dh_bits = 1024, .priority = "SECURE256"
 
902
                         ":!CTYPE-X.509:+CTYPE-OPENPGP" };
 
903
  bool gnutls_initialized = false;
 
904
  bool gpgme_initialized = false;
 
905
  double delay = 2.5;
 
906
 
 
907
  struct sigaction old_sigterm_action;
 
908
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
 
909
  
 
910
  {
 
911
    struct argp_option options[] = {
 
912
      { .name = "debug", .key = 128,
 
913
        .doc = "Debug mode", .group = 3 },
 
914
      { .name = "connect", .key = 'c',
 
915
        .arg = "ADDRESS:PORT",
 
916
        .doc = "Connect directly to a specific Mandos server",
 
917
        .group = 1 },
 
918
      { .name = "interface", .key = 'i',
 
919
        .arg = "NAME",
 
920
        .doc = "Network interface that will be used to search for"
 
921
        " Mandos servers",
 
922
        .group = 1 },
 
923
      { .name = "seckey", .key = 's',
 
924
        .arg = "FILE",
 
925
        .doc = "OpenPGP secret key file base name",
 
926
        .group = 1 },
 
927
      { .name = "pubkey", .key = 'p',
 
928
        .arg = "FILE",
 
929
        .doc = "OpenPGP public key file base name",
 
930
        .group = 2 },
 
931
      { .name = "dh-bits", .key = 129,
 
932
        .arg = "BITS",
 
933
        .doc = "Bit length of the prime number used in the"
 
934
        " Diffie-Hellman key exchange",
 
935
        .group = 2 },
 
936
      { .name = "priority", .key = 130,
 
937
        .arg = "STRING",
 
938
        .doc = "GnuTLS priority string for the TLS handshake",
 
939
        .group = 1 },
 
940
      { .name = "delay", .key = 131,
 
941
        .arg = "SECONDS",
 
942
        .doc = "Maximum delay to wait for interface startup",
 
943
        .group = 2 },
 
944
      { .name = NULL }
 
945
    };
 
946
    
 
947
    error_t parse_opt(int key, char *arg,
 
948
                      struct argp_state *state){
 
949
      switch(key){
 
950
      case 128:                 /* --debug */
 
951
        debug = true;
 
952
        break;
 
953
      case 'c':                 /* --connect */
 
954
        connect_to = arg;
 
955
        break;
 
956
      case 'i':                 /* --interface */
 
957
        interface = arg;
 
958
        break;
 
959
      case 's':                 /* --seckey */
 
960
        seckey = arg;
 
961
        break;
 
962
      case 'p':                 /* --pubkey */
 
963
        pubkey = arg;
 
964
        break;
 
965
      case 129:                 /* --dh-bits */
 
966
        ret = sscanf(arg, "%" SCNdMAX "%n", &tmpmax, &numchars);
 
967
        if(ret < 1 or tmpmax != (typeof(mc.dh_bits))tmpmax
 
968
           or arg[numchars] != '\0'){
 
969
          fprintf(stderr, "Bad number of DH bits\n");
 
970
          exit(EXIT_FAILURE);
 
971
        }
 
972
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
 
973
        break;
 
974
      case 130:                 /* --priority */
 
975
        mc.priority = arg;
 
976
        break;
 
977
      case 131:                 /* --delay */
 
978
        ret = sscanf(arg, "%lf%n", &delay, &numchars);
 
979
        if(ret < 1 or arg[numchars] != '\0'){
 
980
          fprintf(stderr, "Bad delay\n");
 
981
          exit(EXIT_FAILURE);
 
982
        }
 
983
        break;
 
984
      case ARGP_KEY_ARG:
 
985
        argp_usage(state);
 
986
      case ARGP_KEY_END:
 
987
        break;
 
988
      default:
 
989
        return ARGP_ERR_UNKNOWN;
 
990
      }
 
991
      return 0;
 
992
    }
 
993
    
 
994
    struct argp argp = { .options = options, .parser = parse_opt,
 
995
                         .args_doc = "",
 
996
                         .doc = "Mandos client -- Get and decrypt"
 
997
                         " passwords from a Mandos server" };
 
998
    ret = argp_parse(&argp, argc, argv, 0, 0, NULL);
 
999
    if(ret == ARGP_ERR_UNKNOWN){
 
1000
      fprintf(stderr, "Unknown error while parsing arguments\n");
 
1001
      exitcode = EXIT_FAILURE;
 
1002
      goto end;
 
1003
    }
 
1004
  }
 
1005
  
 
1006
  /* If the interface is down, bring it up */
 
1007
  if(interface[0] != '\0'){
 
1008
#ifdef __linux__
 
1009
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
 
1010
       messages to mess up the prompt */
 
1011
    ret = klogctl(8, NULL, 5);
 
1012
    bool restore_loglevel = true;
 
1013
    if(ret == -1){
 
1014
      restore_loglevel = false;
 
1015
      perror("klogctl");
 
1016
    }
 
1017
#endif
 
1018
    
 
1019
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1020
    if(sd < 0){
 
1021
      perror("socket");
 
1022
      exitcode = EXIT_FAILURE;
 
1023
#ifdef __linux__
 
1024
      if(restore_loglevel){
 
1025
        ret = klogctl(7, NULL, 0);
 
1026
        if(ret == -1){
 
1027
          perror("klogctl");
 
1028
        }
 
1029
      }
 
1030
#endif
 
1031
      goto end;
 
1032
    }
 
1033
    strcpy(network.ifr_name, interface);
 
1034
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
1035
    if(ret == -1){
 
1036
      perror("ioctl SIOCGIFFLAGS");
 
1037
#ifdef __linux__
 
1038
      if(restore_loglevel){
 
1039
        ret = klogctl(7, NULL, 0);
 
1040
        if(ret == -1){
 
1041
          perror("klogctl");
 
1042
        }
 
1043
      }
 
1044
#endif
 
1045
      exitcode = EXIT_FAILURE;
 
1046
      goto end;
 
1047
    }
 
1048
    if((network.ifr_flags & IFF_UP) == 0){
 
1049
      network.ifr_flags |= IFF_UP;
 
1050
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
1051
      if(ret == -1){
 
1052
        perror("ioctl SIOCSIFFLAGS");
 
1053
        exitcode = EXIT_FAILURE;
 
1054
#ifdef __linux__
 
1055
        if(restore_loglevel){
 
1056
          ret = klogctl(7, NULL, 0);
 
1057
          if(ret == -1){
 
1058
            perror("klogctl");
901
1059
          }
902
 
          mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
903
 
          break;
904
 
        case 130:               /* --priority */
905
 
          mc.priority = arg;
906
 
          break;
907
 
        case ARGP_KEY_ARG:
908
 
          argp_usage(state);
909
 
        case ARGP_KEY_END:
910
 
          break;
911
 
        default:
912
 
          return ARGP_ERR_UNKNOWN;
913
1060
        }
914
 
        return 0;
915
 
      }
916
 
      
917
 
      struct argp argp = { .options = options, .parser = parse_opt,
918
 
                           .args_doc = "",
919
 
                           .doc = "Mandos client -- Get and decrypt"
920
 
                           " passwords from a Mandos server" };
921
 
      ret = argp_parse(&argp, argc, argv, 0, 0, NULL);
922
 
      if(ret == ARGP_ERR_UNKNOWN){
923
 
        fprintf(stderr, "Unknown error while parsing arguments\n");
924
 
        exitcode = EXIT_FAILURE;
 
1061
#endif
925
1062
        goto end;
926
1063
      }
927
1064
    }
928
 
    
929
 
    /* If the interface is down, bring it up */
930
 
    {
931
 
      sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
932
 
      if(sd < 0) {
933
 
        perror("socket");
934
 
        exitcode = EXIT_FAILURE;
935
 
        goto end;
936
 
      }
937
 
      strcpy(network.ifr_name, interface);
 
1065
    /* sleep checking until interface is running */
 
1066
    for(int i=0; i < delay * 4; i++){
938
1067
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
939
1068
      if(ret == -1){
940
1069
        perror("ioctl SIOCGIFFLAGS");
941
 
        exitcode = EXIT_FAILURE;
942
 
        goto end;
943
 
      }
944
 
      if((network.ifr_flags & IFF_UP) == 0){
945
 
        network.ifr_flags |= IFF_UP;
946
 
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
947
 
        if(ret == -1){
948
 
          perror("ioctl SIOCSIFFLAGS");
949
 
          exitcode = EXIT_FAILURE;
950
 
          goto end;
951
 
        }
952
 
      }
953
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1070
      } else if(network.ifr_flags & IFF_RUNNING){
 
1071
        break;
 
1072
      }
 
1073
      struct timespec sleeptime = { .tv_nsec = 250000000 };
 
1074
      ret = nanosleep(&sleeptime, NULL);
 
1075
      if(ret == -1 and errno != EINTR){
 
1076
        perror("nanosleep");
 
1077
      }
 
1078
    }
 
1079
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1080
    if(ret == -1){
 
1081
      perror("close");
 
1082
    }
 
1083
#ifdef __linux__
 
1084
    if(restore_loglevel){
 
1085
      /* Restores kernel loglevel to default */
 
1086
      ret = klogctl(7, NULL, 0);
954
1087
      if(ret == -1){
955
 
        perror("close");
 
1088
        perror("klogctl");
956
1089
      }
957
1090
    }
958
 
    
959
 
    uid = getuid();
960
 
    gid = getgid();
961
 
    
962
 
    ret = setuid(uid);
963
 
    if(ret == -1){
964
 
      perror("setuid");
965
 
    }
966
 
    
967
 
    setgid(gid);
968
 
    if(ret == -1){
969
 
      perror("setgid");
970
 
    }
971
 
    
972
 
    ret = init_gnutls_global(&mc, pubkey, seckey);
973
 
    if(ret == -1){
974
 
      fprintf(stderr, "init_gnutls_global failed\n");
975
 
      exitcode = EXIT_FAILURE;
976
 
      goto end;
977
 
    } else {
978
 
      gnutls_initalized = true;
979
 
    }
980
 
    
981
 
    if(mkdtemp(tempdir) == NULL){
982
 
      perror("mkdtemp");
983
 
      tempdir[0] = '\0';
984
 
      goto end;
985
 
    }
986
 
    
987
 
    if(not init_gpgme(&mc, pubkey, seckey, tempdir)){
988
 
      fprintf(stderr, "gpgme_initalized failed\n");
989
 
      exitcode = EXIT_FAILURE;
990
 
      goto end;
991
 
    } else {
992
 
      gpgme_initalized = true;
993
 
    }
994
 
    
 
1091
#endif
 
1092
  }
 
1093
  
 
1094
  uid = getuid();
 
1095
  gid = getgid();
 
1096
  
 
1097
  errno = 0;
 
1098
  setgid(gid);
 
1099
  if(ret == -1){
 
1100
    perror("setgid");
 
1101
  }
 
1102
  
 
1103
  ret = setuid(uid);
 
1104
  if(ret == -1){
 
1105
    perror("setuid");
 
1106
  }
 
1107
  
 
1108
  ret = init_gnutls_global(pubkey, seckey);
 
1109
  if(ret == -1){
 
1110
    fprintf(stderr, "init_gnutls_global failed\n");
 
1111
    exitcode = EXIT_FAILURE;
 
1112
    goto end;
 
1113
  } else {
 
1114
    gnutls_initialized = true;
 
1115
  }
 
1116
  
 
1117
  if(mkdtemp(tempdir) == NULL){
 
1118
    perror("mkdtemp");
 
1119
    goto end;
 
1120
  }
 
1121
  tempdir_created = true;
 
1122
  
 
1123
  if(not init_gpgme(pubkey, seckey, tempdir)){
 
1124
    fprintf(stderr, "init_gpgme failed\n");
 
1125
    exitcode = EXIT_FAILURE;
 
1126
    goto end;
 
1127
  } else {
 
1128
    gpgme_initialized = true;
 
1129
  }
 
1130
  
 
1131
  if(interface[0] != '\0'){
995
1132
    if_index = (AvahiIfIndex) if_nametoindex(interface);
996
1133
    if(if_index == 0){
997
1134
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
998
 
      exit(EXIT_FAILURE);
999
 
    }
1000
 
    
1001
 
    if(connect_to != NULL){
1002
 
      /* Connect directly, do not use Zeroconf */
1003
 
      /* (Mainly meant for debugging) */
1004
 
      char *address = strrchr(connect_to, ':');
1005
 
      if(address == NULL){
1006
 
        fprintf(stderr, "No colon in address\n");
1007
 
        exitcode = EXIT_FAILURE;
1008
 
        goto end;
1009
 
      }
1010
 
      uint16_t port;
1011
 
      ret = sscanf(address+1, "%" SCNdMAX "%n", &tmpmax, &numchars);
1012
 
      if(ret < 1 or tmpmax != (uint16_t)tmpmax
1013
 
         or address[numchars+1] != '\0'){
1014
 
        fprintf(stderr, "Bad port number\n");
1015
 
        exitcode = EXIT_FAILURE;
1016
 
        goto end;
1017
 
      }
1018
 
      port = (uint16_t)tmpmax;
1019
 
      *address = '\0';
1020
 
      address = connect_to;
1021
 
      ret = start_mandos_communication(address, port, if_index, &mc);
1022
 
      if(ret < 0){
1023
 
        exitcode = EXIT_FAILURE;
1024
 
      } else {
1025
 
        exitcode = EXIT_SUCCESS;
1026
 
      }
1027
 
      goto end;
1028
 
    }
1029
 
    
1030
 
    if(not debug){
1031
 
      avahi_set_log_function(empty_log);
1032
 
    }
1033
 
    
1034
 
    /* Initialize the pseudo-RNG for Avahi */
1035
 
    srand((unsigned int) time(NULL));
1036
 
    
1037
 
    /* Allocate main Avahi loop object */
1038
 
    mc.simple_poll = avahi_simple_poll_new();
1039
 
    if(mc.simple_poll == NULL) {
1040
 
        fprintf(stderr, "Avahi: Failed to create simple poll"
1041
 
                " object.\n");
1042
 
        exitcode = EXIT_FAILURE;
1043
 
        goto end;
1044
 
    }
1045
 
    
1046
 
    {
1047
 
      AvahiServerConfig config;
1048
 
      /* Do not publish any local Zeroconf records */
1049
 
      avahi_server_config_init(&config);
1050
 
      config.publish_hinfo = 0;
1051
 
      config.publish_addresses = 0;
1052
 
      config.publish_workstation = 0;
1053
 
      config.publish_domain = 0;
1054
 
      
1055
 
      /* Allocate a new server */
1056
 
      mc.server = avahi_server_new(avahi_simple_poll_get
1057
 
                                   (mc.simple_poll), &config, NULL,
1058
 
                                   NULL, &error);
1059
 
      
1060
 
      /* Free the Avahi configuration data */
1061
 
      avahi_server_config_free(&config);
1062
 
    }
1063
 
    
1064
 
    /* Check if creating the Avahi server object succeeded */
1065
 
    if(mc.server == NULL) {
1066
 
        fprintf(stderr, "Failed to create Avahi server: %s\n",
1067
 
                avahi_strerror(error));
1068
 
        exitcode = EXIT_FAILURE;
1069
 
        goto end;
1070
 
    }
1071
 
    
1072
 
    /* Create the Avahi service browser */
1073
 
    sb = avahi_s_service_browser_new(mc.server, if_index,
1074
 
                                     AVAHI_PROTO_INET6,
1075
 
                                     "_mandos._tcp", NULL, 0,
1076
 
                                     browse_callback, &mc);
1077
 
    if(sb == NULL) {
1078
 
        fprintf(stderr, "Failed to create service browser: %s\n",
1079
 
                avahi_strerror(avahi_server_errno(mc.server)));
1080
 
        exitcode = EXIT_FAILURE;
1081
 
        goto end;
1082
 
    }
1083
 
    
1084
 
    /* Run the main loop */
1085
 
    
1086
 
    if(debug){
1087
 
      fprintf(stderr, "Starting Avahi loop search\n");
1088
 
    }
1089
 
    
1090
 
    avahi_simple_poll_loop(mc.simple_poll);
1091
 
    
 
1135
      exitcode = EXIT_FAILURE;
 
1136
      goto end;
 
1137
    }
 
1138
  }
 
1139
  
 
1140
  if(connect_to != NULL){
 
1141
    /* Connect directly, do not use Zeroconf */
 
1142
    /* (Mainly meant for debugging) */
 
1143
    char *address = strrchr(connect_to, ':');
 
1144
    if(address == NULL){
 
1145
      fprintf(stderr, "No colon in address\n");
 
1146
      exitcode = EXIT_FAILURE;
 
1147
      goto end;
 
1148
    }
 
1149
    uint16_t port;
 
1150
    ret = sscanf(address+1, "%" SCNdMAX "%n", &tmpmax, &numchars);
 
1151
    if(ret < 1 or tmpmax != (uint16_t)tmpmax
 
1152
       or address[numchars+1] != '\0'){
 
1153
      fprintf(stderr, "Bad port number\n");
 
1154
      exitcode = EXIT_FAILURE;
 
1155
      goto end;
 
1156
    }
 
1157
    port = (uint16_t)tmpmax;
 
1158
    *address = '\0';
 
1159
    address = connect_to;
 
1160
    /* Colon in address indicates IPv6 */
 
1161
    int af;
 
1162
    if(strchr(address, ':') != NULL){
 
1163
      af = AF_INET6;
 
1164
    } else {
 
1165
      af = AF_INET;
 
1166
    }
 
1167
    ret = start_mandos_communication(address, port, if_index, af);
 
1168
    if(ret < 0){
 
1169
      exitcode = EXIT_FAILURE;
 
1170
    } else {
 
1171
      exitcode = EXIT_SUCCESS;
 
1172
    }
 
1173
    goto end;
 
1174
  }
 
1175
  
 
1176
  if(not debug){
 
1177
    avahi_set_log_function(empty_log);
 
1178
  }
 
1179
  
 
1180
  /* Initialize the pseudo-RNG for Avahi */
 
1181
  srand((unsigned int) time(NULL));
 
1182
  
 
1183
  /* Allocate main Avahi loop object */
 
1184
  mc.simple_poll = avahi_simple_poll_new();
 
1185
  if(mc.simple_poll == NULL){
 
1186
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
 
1187
    exitcode = EXIT_FAILURE;
 
1188
    goto end;
 
1189
  }
 
1190
  
 
1191
  {
 
1192
    AvahiServerConfig config;
 
1193
    /* Do not publish any local Zeroconf records */
 
1194
    avahi_server_config_init(&config);
 
1195
    config.publish_hinfo = 0;
 
1196
    config.publish_addresses = 0;
 
1197
    config.publish_workstation = 0;
 
1198
    config.publish_domain = 0;
 
1199
    
 
1200
    /* Allocate a new server */
 
1201
    mc.server = avahi_server_new(avahi_simple_poll_get
 
1202
                                 (mc.simple_poll), &config, NULL,
 
1203
                                 NULL, &error);
 
1204
    
 
1205
    /* Free the Avahi configuration data */
 
1206
    avahi_server_config_free(&config);
 
1207
  }
 
1208
  
 
1209
  /* Check if creating the Avahi server object succeeded */
 
1210
  if(mc.server == NULL){
 
1211
    fprintf(stderr, "Failed to create Avahi server: %s\n",
 
1212
            avahi_strerror(error));
 
1213
    exitcode = EXIT_FAILURE;
 
1214
    goto end;
 
1215
  }
 
1216
  
 
1217
  /* Create the Avahi service browser */
 
1218
  sb = avahi_s_service_browser_new(mc.server, if_index,
 
1219
                                   AVAHI_PROTO_INET6, "_mandos._tcp",
 
1220
                                   NULL, 0, browse_callback, NULL);
 
1221
  if(sb == NULL){
 
1222
    fprintf(stderr, "Failed to create service browser: %s\n",
 
1223
            avahi_strerror(avahi_server_errno(mc.server)));
 
1224
    exitcode = EXIT_FAILURE;
 
1225
    goto end;
 
1226
  }
 
1227
  
 
1228
  sigemptyset(&sigterm_action.sa_mask);
 
1229
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
 
1230
  if(ret == -1){
 
1231
    perror("sigaddset");
 
1232
    exitcode = EXIT_FAILURE;
 
1233
    goto end;
 
1234
  }
 
1235
  ret = sigaction(SIGTERM, &sigterm_action, &old_sigterm_action);
 
1236
  if(ret == -1){
 
1237
    perror("sigaction");
 
1238
    exitcode = EXIT_FAILURE;
 
1239
    goto end;
 
1240
  }  
 
1241
  
 
1242
  /* Run the main loop */
 
1243
  
 
1244
  if(debug){
 
1245
    fprintf(stderr, "Starting Avahi loop search\n");
 
1246
  }
 
1247
  
 
1248
  avahi_simple_poll_loop(mc.simple_poll);
 
1249
  
1092
1250
 end:
1093
 
    
1094
 
    if(debug){
1095
 
      fprintf(stderr, "%s exiting\n", argv[0]);
1096
 
    }
1097
 
    
1098
 
    /* Cleanup things */
1099
 
    if(sb != NULL)
1100
 
        avahi_s_service_browser_free(sb);
1101
 
    
1102
 
    if(mc.server != NULL)
1103
 
        avahi_server_free(mc.server);
1104
 
    
1105
 
    if(mc.simple_poll != NULL)
1106
 
        avahi_simple_poll_free(mc.simple_poll);
1107
 
    
1108
 
    if(gnutls_initalized){
1109
 
      gnutls_certificate_free_credentials(mc.cred);
1110
 
      gnutls_global_deinit();
1111
 
      gnutls_dh_params_deinit(mc.dh_params);
1112
 
    }
1113
 
    
1114
 
    if(gpgme_initalized){
1115
 
      gpgme_release(mc.ctx);
1116
 
    }
1117
 
    
1118
 
    /* Removes the temp directory used by GPGME */
1119
 
    if(tempdir[0] != '\0'){
1120
 
      DIR *d;
1121
 
      struct dirent *direntry;
1122
 
      d = opendir(tempdir);
1123
 
      if(d == NULL){
1124
 
        if(errno != ENOENT){
1125
 
          perror("opendir");
1126
 
        }
1127
 
      } else {
1128
 
        while(true){
1129
 
          direntry = readdir(d);
1130
 
          if(direntry == NULL){
1131
 
            break;
1132
 
          }
1133
 
          if(direntry->d_type == DT_REG){
1134
 
            char *fullname = NULL;
1135
 
            ret = asprintf(&fullname, "%s/%s", tempdir,
1136
 
                           direntry->d_name);
1137
 
            if(ret < 0){
1138
 
              perror("asprintf");
1139
 
              continue;
1140
 
            }
1141
 
            ret = unlink(fullname);
1142
 
            if(ret == -1){
1143
 
              fprintf(stderr, "unlink(\"%s\"): %s",
1144
 
                      fullname, strerror(errno));
1145
 
            }
1146
 
            free(fullname);
1147
 
          }
1148
 
        }
1149
 
        closedir(d);
1150
 
      }
1151
 
      ret = rmdir(tempdir);
1152
 
      if(ret == -1 and errno != ENOENT){
1153
 
        perror("rmdir");
1154
 
      }
1155
 
    }
1156
 
          
1157
 
    return exitcode;
 
1251
  
 
1252
  if(debug){
 
1253
    fprintf(stderr, "%s exiting\n", argv[0]);
 
1254
  }
 
1255
  
 
1256
  /* Cleanup things */
 
1257
  if(sb != NULL)
 
1258
    avahi_s_service_browser_free(sb);
 
1259
  
 
1260
  if(mc.server != NULL)
 
1261
    avahi_server_free(mc.server);
 
1262
  
 
1263
  if(mc.simple_poll != NULL)
 
1264
    avahi_simple_poll_free(mc.simple_poll);
 
1265
  
 
1266
  if(gnutls_initialized){
 
1267
    gnutls_certificate_free_credentials(mc.cred);
 
1268
    gnutls_global_deinit();
 
1269
    gnutls_dh_params_deinit(mc.dh_params);
 
1270
  }
 
1271
  
 
1272
  if(gpgme_initialized){
 
1273
    gpgme_release(mc.ctx);
 
1274
  }
 
1275
  
 
1276
  /* Removes the temp directory used by GPGME */
 
1277
  if(tempdir_created){
 
1278
    DIR *d;
 
1279
    struct dirent *direntry;
 
1280
    d = opendir(tempdir);
 
1281
    if(d == NULL){
 
1282
      if(errno != ENOENT){
 
1283
        perror("opendir");
 
1284
      }
 
1285
    } else {
 
1286
      while(true){
 
1287
        direntry = readdir(d);
 
1288
        if(direntry == NULL){
 
1289
          break;
 
1290
        }
 
1291
        /* Skip "." and ".." */
 
1292
        if(direntry->d_name[0] == '.'
 
1293
           and (direntry->d_name[1] == '\0'
 
1294
                or (direntry->d_name[1] == '.'
 
1295
                    and direntry->d_name[2] == '\0'))){
 
1296
          continue;
 
1297
        }
 
1298
        char *fullname = NULL;
 
1299
        ret = asprintf(&fullname, "%s/%s", tempdir,
 
1300
                       direntry->d_name);
 
1301
        if(ret < 0){
 
1302
          perror("asprintf");
 
1303
          continue;
 
1304
        }
 
1305
        ret = remove(fullname);
 
1306
        if(ret == -1){
 
1307
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
 
1308
                  strerror(errno));
 
1309
        }
 
1310
        free(fullname);
 
1311
      }
 
1312
      closedir(d);
 
1313
    }
 
1314
    ret = rmdir(tempdir);
 
1315
    if(ret == -1 and errno != ENOENT){
 
1316
      perror("rmdir");
 
1317
    }
 
1318
  }
 
1319
  
 
1320
  return exitcode;
1158
1321
}