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