/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

* plugin-runner.c: Whitespace changes only.

* plugins.d/mandos-client.c: Wrap calls to klogctl() inside "#ifdef
                             __linux__".  Detect and show any error
                             from nanosleep.

* plugins.d/password-prompt.c: Whitespace changes only.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
/*  -*- coding: utf-8 -*- */
2
2
/*
3
 
 * Mandos client - get and decrypt data from a Mandos server
 
3
 * Mandos-client - get and decrypt data from a Mandos server
4
4
 *
5
5
 * This program is partly derived from an example program for an Avahi
6
6
 * service browser, downloaded from
36
36
#define _GNU_SOURCE             /* TEMP_FAILURE_RETRY(), asprintf() */
37
37
 
38
38
#include <stdio.h>              /* fprintf(), stderr, fwrite(),
39
 
                                   stdout, ferror() */
 
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,
48
49
#include <sys/types.h>          /* socket(), inet_pton(), sockaddr,
49
50
                                   sockaddr_in6, PF_INET6,
50
51
                                   SOCK_STREAM, INET6_ADDRSTRLEN,
51
 
                                   uid_t, gid_t, open(), opendir(), DIR */
 
52
                                   uid_t, gid_t, open(), opendir(),
 
53
                                   DIR */
52
54
#include <sys/stat.h>           /* open() */
53
55
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
54
56
                                   struct in6_addr, inet_pton(),
55
57
                                   connect() */
56
58
#include <fcntl.h>              /* open() */
57
 
#include <dirent.h>             /* opendir(), struct dirent, readdir() */
58
 
#include <inttypes.h>           /* PRIu16 */
 
59
#include <dirent.h>             /* opendir(), struct dirent, readdir()
 
60
                                 */
 
61
#include <inttypes.h>           /* PRIu16, intmax_t, SCNdMAX */
59
62
#include <assert.h>             /* assert() */
60
63
#include <errno.h>              /* perror(), errno */
61
 
#include <time.h>               /* time() */
 
64
#include <time.h>               /* nanosleep(), time() */
62
65
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
63
66
                                   SIOCSIFFLAGS, if_indextoname(),
64
67
                                   if_nametoindex(), IF_NAMESIZE */
67
70
                                   getuid(), getgid(), setuid(),
68
71
                                   setgid() */
69
72
#include <arpa/inet.h>          /* inet_pton(), htons */
70
 
#include <iso646.h>             /* not, and */
 
73
#include <iso646.h>             /* not, and, or */
71
74
#include <argp.h>               /* struct argp_option, error_t, struct
72
75
                                   argp_state, struct argp,
73
76
                                   argp_parse(), ARGP_KEY_ARG,
74
77
                                   ARGP_KEY_END, ARGP_ERR_UNKNOWN */
 
78
#ifdef __linux__
 
79
#include <sys/klog.h>           /* klogctl() */
 
80
#endif
75
81
 
76
82
/* Avahi */
77
83
/* All Avahi types, constants and functions
90
96
                                   gnutls_*
91
97
                                   init_gnutls_session(),
92
98
                                   GNUTLS_* */
93
 
#include <gnutls/openpgp.h>     /* gnutls_certificate_set_openpgp_key_file(),
 
99
#include <gnutls/openpgp.h>
 
100
                          /* gnutls_certificate_set_openpgp_key_file(),
94
101
                                   GNUTLS_OPENPGP_FMT_BASE64 */
95
102
 
96
103
/* GPGME */
129
136
 */
130
137
size_t adjustbuffer(char **buffer, size_t buffer_length,
131
138
                  size_t buffer_capacity){
132
 
  if (buffer_length + BUFFER_SIZE > buffer_capacity){
 
139
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
133
140
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
134
 
    if (buffer == NULL){
 
141
    if(buffer == NULL){
135
142
      return 0;
136
143
    }
137
144
    buffer_capacity += BUFFER_SIZE;
150
157
  
151
158
  
152
159
  /*
153
 
   * Helper function to insert pub and seckey to the enigne keyring.
 
160
   * Helper function to insert pub and seckey to the engine keyring.
154
161
   */
155
162
  bool import_key(const char *filename){
156
163
    int fd;
163
170
    }
164
171
    
165
172
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
166
 
    if (rc != GPG_ERR_NO_ERROR){
 
173
    if(rc != GPG_ERR_NO_ERROR){
167
174
      fprintf(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
168
175
              gpgme_strsource(rc), gpgme_strerror(rc));
169
176
      return false;
170
177
    }
171
178
    
172
179
    rc = gpgme_op_import(mc->ctx, pgp_data);
173
 
    if (rc != GPG_ERR_NO_ERROR){
 
180
    if(rc != GPG_ERR_NO_ERROR){
174
181
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
175
182
              gpgme_strsource(rc), gpgme_strerror(rc));
176
183
      return false;
184
191
    return true;
185
192
  }
186
193
  
187
 
  if (debug){
 
194
  if(debug){
188
195
    fprintf(stderr, "Initialize gpgme\n");
189
196
  }
190
197
  
191
198
  /* Init GPGME */
192
199
  gpgme_check_version(NULL);
193
200
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
194
 
  if (rc != GPG_ERR_NO_ERROR){
 
201
  if(rc != GPG_ERR_NO_ERROR){
195
202
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
196
203
            gpgme_strsource(rc), gpgme_strerror(rc));
197
204
    return false;
198
205
  }
199
206
  
200
207
    /* Set GPGME home directory for the OpenPGP engine only */
201
 
  rc = gpgme_get_engine_info (&engine_info);
202
 
  if (rc != GPG_ERR_NO_ERROR){
 
208
  rc = gpgme_get_engine_info(&engine_info);
 
209
  if(rc != GPG_ERR_NO_ERROR){
203
210
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
204
211
            gpgme_strsource(rc), gpgme_strerror(rc));
205
212
    return false;
219
226
  
220
227
  /* Create new GPGME "context" */
221
228
  rc = gpgme_new(&(mc->ctx));
222
 
  if (rc != GPG_ERR_NO_ERROR){
 
229
  if(rc != GPG_ERR_NO_ERROR){
223
230
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
224
231
            gpgme_strsource(rc), gpgme_strerror(rc));
225
232
    return false;
226
233
  }
227
234
  
228
 
  if (not import_key(pubkey) or not import_key(seckey)){
 
235
  if(not import_key(pubkey) or not import_key(seckey)){
229
236
    return false;
230
237
  }
231
238
  
236
243
 * Decrypt OpenPGP data.
237
244
 * Returns -1 on error
238
245
 */
239
 
static ssize_t pgp_packet_decrypt (const mandos_context *mc,
240
 
                                   const char *cryptotext,
241
 
                                   size_t crypto_size,
242
 
                                   char **plaintext){
 
246
static ssize_t pgp_packet_decrypt(const mandos_context *mc,
 
247
                                  const char *cryptotext,
 
248
                                  size_t crypto_size,
 
249
                                  char **plaintext){
243
250
  gpgme_data_t dh_crypto, dh_plain;
244
251
  gpgme_error_t rc;
245
252
  ssize_t ret;
246
253
  size_t plaintext_capacity = 0;
247
254
  ssize_t plaintext_length = 0;
248
255
  
249
 
  if (debug){
 
256
  if(debug){
250
257
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
251
258
  }
252
259
  
253
260
  /* Create new GPGME data buffer from memory cryptotext */
254
261
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
255
262
                               0);
256
 
  if (rc != GPG_ERR_NO_ERROR){
 
263
  if(rc != GPG_ERR_NO_ERROR){
257
264
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
258
265
            gpgme_strsource(rc), gpgme_strerror(rc));
259
266
    return -1;
261
268
  
262
269
  /* Create new empty GPGME data buffer for the plaintext */
263
270
  rc = gpgme_data_new(&dh_plain);
264
 
  if (rc != GPG_ERR_NO_ERROR){
 
271
  if(rc != GPG_ERR_NO_ERROR){
265
272
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
266
273
            gpgme_strsource(rc), gpgme_strerror(rc));
267
274
    gpgme_data_release(dh_crypto);
271
278
  /* Decrypt data from the cryptotext data buffer to the plaintext
272
279
     data buffer */
273
280
  rc = gpgme_op_decrypt(mc->ctx, dh_crypto, dh_plain);
274
 
  if (rc != GPG_ERR_NO_ERROR){
 
281
  if(rc != GPG_ERR_NO_ERROR){
275
282
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
276
283
            gpgme_strsource(rc), gpgme_strerror(rc));
277
284
    plaintext_length = -1;
278
 
    if (debug){
 
285
    if(debug){
279
286
      gpgme_decrypt_result_t result;
280
287
      result = gpgme_op_decrypt_result(mc->ctx);
281
 
      if (result == NULL){
 
288
      if(result == NULL){
282
289
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
283
290
      } else {
284
291
        fprintf(stderr, "Unsupported algorithm: %s\n",
311
318
  }
312
319
  
313
320
  /* Seek back to the beginning of the GPGME plaintext data buffer */
314
 
  if (gpgme_data_seek(dh_plain, (off_t) 0, SEEK_SET) == -1){
 
321
  if(gpgme_data_seek(dh_plain, (off_t)0, SEEK_SET) == -1){
315
322
    perror("gpgme_data_seek");
316
323
    plaintext_length = -1;
317
324
    goto decrypt_end;
322
329
    plaintext_capacity = adjustbuffer(plaintext,
323
330
                                      (size_t)plaintext_length,
324
331
                                      plaintext_capacity);
325
 
    if (plaintext_capacity == 0){
 
332
    if(plaintext_capacity == 0){
326
333
        perror("adjustbuffer");
327
334
        plaintext_length = -1;
328
335
        goto decrypt_end;
331
338
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
332
339
                          BUFFER_SIZE);
333
340
    /* Print the data, if any */
334
 
    if (ret == 0){
 
341
    if(ret == 0){
335
342
      /* EOF */
336
343
      break;
337
344
    }
361
368
  return plaintext_length;
362
369
}
363
370
 
364
 
static const char * safer_gnutls_strerror (int value) {
365
 
  const char *ret = gnutls_strerror (value); /* Spurious warning */
366
 
  if (ret == NULL)
 
371
static const char * safer_gnutls_strerror(int value){
 
372
  const char *ret = gnutls_strerror(value); /* Spurious warning from
 
373
                                               -Wunreachable-code */
 
374
  if(ret == NULL)
367
375
    ret = "(unknown)";
368
376
  return ret;
369
377
}
384
392
  }
385
393
  
386
394
  ret = gnutls_global_init();
387
 
  if (ret != GNUTLS_E_SUCCESS) {
388
 
    fprintf (stderr, "GnuTLS global_init: %s\n",
389
 
             safer_gnutls_strerror(ret));
 
395
  if(ret != GNUTLS_E_SUCCESS){
 
396
    fprintf(stderr, "GnuTLS global_init: %s\n",
 
397
            safer_gnutls_strerror(ret));
390
398
    return -1;
391
399
  }
392
400
  
393
 
  if (debug){
 
401
  if(debug){
394
402
    /* "Use a log level over 10 to enable all debugging options."
395
403
     * - GnuTLS manual
396
404
     */
400
408
  
401
409
  /* OpenPGP credentials */
402
410
  gnutls_certificate_allocate_credentials(&mc->cred);
403
 
  if (ret != GNUTLS_E_SUCCESS){
404
 
    fprintf (stderr, "GnuTLS memory error: %s\n", /* Spurious
405
 
                                                     warning */
406
 
             safer_gnutls_strerror(ret));
407
 
    gnutls_global_deinit ();
 
411
  if(ret != GNUTLS_E_SUCCESS){
 
412
    fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning
 
413
                                                  * from
 
414
                                                  * -Wunreachable-code
 
415
                                                  */
 
416
            safer_gnutls_strerror(ret));
 
417
    gnutls_global_deinit();
408
418
    return -1;
409
419
  }
410
420
  
417
427
  ret = gnutls_certificate_set_openpgp_key_file
418
428
    (mc->cred, pubkeyfilename, seckeyfilename,
419
429
     GNUTLS_OPENPGP_FMT_BASE64);
420
 
  if (ret != GNUTLS_E_SUCCESS) {
 
430
  if(ret != GNUTLS_E_SUCCESS){
421
431
    fprintf(stderr,
422
432
            "Error[%d] while reading the OpenPGP key pair ('%s',"
423
433
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
428
438
  
429
439
  /* GnuTLS server initialization */
430
440
  ret = gnutls_dh_params_init(&mc->dh_params);
431
 
  if (ret != GNUTLS_E_SUCCESS) {
432
 
    fprintf (stderr, "Error in GnuTLS DH parameter initialization:"
433
 
             " %s\n", safer_gnutls_strerror(ret));
 
441
  if(ret != GNUTLS_E_SUCCESS){
 
442
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
 
443
            " %s\n", safer_gnutls_strerror(ret));
434
444
    goto globalfail;
435
445
  }
436
446
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
437
 
  if (ret != GNUTLS_E_SUCCESS) {
438
 
    fprintf (stderr, "Error in GnuTLS prime generation: %s\n",
439
 
             safer_gnutls_strerror(ret));
 
447
  if(ret != GNUTLS_E_SUCCESS){
 
448
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
 
449
            safer_gnutls_strerror(ret));
440
450
    goto globalfail;
441
451
  }
442
452
  
457
467
  int ret;
458
468
  /* GnuTLS session creation */
459
469
  ret = gnutls_init(session, GNUTLS_SERVER);
460
 
  if (ret != GNUTLS_E_SUCCESS){
 
470
  if(ret != GNUTLS_E_SUCCESS){
461
471
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
462
472
            safer_gnutls_strerror(ret));
463
473
  }
465
475
  {
466
476
    const char *err;
467
477
    ret = gnutls_priority_set_direct(*session, mc->priority, &err);
468
 
    if (ret != GNUTLS_E_SUCCESS) {
 
478
    if(ret != GNUTLS_E_SUCCESS){
469
479
      fprintf(stderr, "Syntax error at: %s\n", err);
470
480
      fprintf(stderr, "GnuTLS error: %s\n",
471
481
              safer_gnutls_strerror(ret));
472
 
      gnutls_deinit (*session);
 
482
      gnutls_deinit(*session);
473
483
      return -1;
474
484
    }
475
485
  }
476
486
  
477
487
  ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
478
488
                               mc->cred);
479
 
  if (ret != GNUTLS_E_SUCCESS) {
 
489
  if(ret != GNUTLS_E_SUCCESS){
480
490
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
481
491
            safer_gnutls_strerror(ret));
482
 
    gnutls_deinit (*session);
 
492
    gnutls_deinit(*session);
483
493
    return -1;
484
494
  }
485
495
  
486
496
  /* ignore client certificate if any. */
487
 
  gnutls_certificate_server_set_request (*session,
488
 
                                         GNUTLS_CERT_IGNORE);
 
497
  gnutls_certificate_server_set_request(*session,
 
498
                                        GNUTLS_CERT_IGNORE);
489
499
  
490
 
  gnutls_dh_set_prime_bits (*session, mc->dh_bits);
 
500
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
491
501
  
492
502
  return 0;
493
503
}
513
523
  char interface[IF_NAMESIZE];
514
524
  gnutls_session_t session;
515
525
  
516
 
  ret = init_gnutls_session (mc, &session);
517
 
  if (ret != 0){
 
526
  ret = init_gnutls_session(mc, &session);
 
527
  if(ret != 0){
518
528
    return -1;
519
529
  }
520
530
  
524
534
  }
525
535
  
526
536
  tcp_sd = socket(PF_INET6, SOCK_STREAM, 0);
527
 
  if(tcp_sd < 0) {
 
537
  if(tcp_sd < 0){
528
538
    perror("socket");
529
539
    return -1;
530
540
  }
542
552
  /* It would be nice to have a way to detect if we were passed an
543
553
     IPv4 address here.   Now we assume an IPv6 address. */
544
554
  ret = inet_pton(AF_INET6, ip, &to.in6.sin6_addr);
545
 
  if (ret < 0 ){
 
555
  if(ret < 0 ){
546
556
    perror("inet_pton");
547
557
    return -1;
548
558
  }
550
560
    fprintf(stderr, "Bad address: %s\n", ip);
551
561
    return -1;
552
562
  }
553
 
  to.in6.sin6_port = htons(port); /* Spurious warning */
 
563
  to.in6.sin6_port = htons(port); /* Spurious warnings from
 
564
                                     -Wconversion and
 
565
                                     -Wunreachable-code */
554
566
  
555
567
  to.in6.sin6_scope_id = (uint32_t)if_index;
556
568
  
569
581
  }
570
582
  
571
583
  ret = connect(tcp_sd, &to.in, sizeof(to));
572
 
  if (ret < 0){
 
584
  if(ret < 0){
573
585
    perror("connect");
574
586
    return -1;
575
587
  }
576
588
  
577
589
  const char *out = mandos_protocol_version;
578
590
  written = 0;
579
 
  while (true){
 
591
  while(true){
580
592
    size_t out_size = strlen(out);
581
593
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
582
594
                                   out_size - written));
583
 
    if (ret == -1){
 
595
    if(ret == -1){
584
596
      perror("write");
585
597
      retval = -1;
586
598
      goto mandos_end;
589
601
    if(written < out_size){
590
602
      continue;
591
603
    } else {
592
 
      if (out == mandos_protocol_version){
 
604
      if(out == mandos_protocol_version){
593
605
        written = 0;
594
606
        out = "\r\n";
595
607
      } else {
602
614
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
603
615
  }
604
616
  
605
 
  gnutls_transport_set_ptr (session, (gnutls_transport_ptr_t) tcp_sd);
 
617
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
606
618
  
607
619
  do{
608
 
    ret = gnutls_handshake (session);
 
620
    ret = gnutls_handshake(session);
609
621
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
610
622
  
611
 
  if (ret != GNUTLS_E_SUCCESS){
 
623
  if(ret != GNUTLS_E_SUCCESS){
612
624
    if(debug){
613
625
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
614
 
      gnutls_perror (ret);
 
626
      gnutls_perror(ret);
615
627
    }
616
628
    retval = -1;
617
629
    goto mandos_end;
627
639
  while(true){
628
640
    buffer_capacity = adjustbuffer(&buffer, buffer_length,
629
641
                                   buffer_capacity);
630
 
    if (buffer_capacity == 0){
 
642
    if(buffer_capacity == 0){
631
643
      perror("adjustbuffer");
632
644
      retval = -1;
633
645
      goto mandos_end;
635
647
    
636
648
    sret = gnutls_record_recv(session, buffer+buffer_length,
637
649
                              BUFFER_SIZE);
638
 
    if (sret == 0){
 
650
    if(sret == 0){
639
651
      break;
640
652
    }
641
 
    if (sret < 0){
 
653
    if(sret < 0){
642
654
      switch(sret){
643
655
      case GNUTLS_E_INTERRUPTED:
644
656
      case GNUTLS_E_AGAIN:
645
657
        break;
646
658
      case GNUTLS_E_REHANDSHAKE:
647
659
        do{
648
 
          ret = gnutls_handshake (session);
 
660
          ret = gnutls_handshake(session);
649
661
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
650
 
        if (ret < 0){
 
662
        if(ret < 0){
651
663
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
652
 
          gnutls_perror (ret);
 
664
          gnutls_perror(ret);
653
665
          retval = -1;
654
666
          goto mandos_end;
655
667
        }
658
670
        fprintf(stderr, "Unknown error while reading data from"
659
671
                " encrypted session with Mandos server\n");
660
672
        retval = -1;
661
 
        gnutls_bye (session, GNUTLS_SHUT_RDWR);
 
673
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
662
674
        goto mandos_end;
663
675
      }
664
676
    } else {
670
682
    fprintf(stderr, "Closing TLS session\n");
671
683
  }
672
684
  
673
 
  gnutls_bye (session, GNUTLS_SHUT_RDWR);
 
685
  gnutls_bye(session, GNUTLS_SHUT_RDWR);
674
686
  
675
 
  if (buffer_length > 0){
 
687
  if(buffer_length > 0){
676
688
    decrypted_buffer_size = pgp_packet_decrypt(mc, buffer,
677
689
                                               buffer_length,
678
690
                                               &decrypted_buffer);
679
 
    if (decrypted_buffer_size >= 0){
 
691
    if(decrypted_buffer_size >= 0){
680
692
      written = 0;
681
693
      while(written < (size_t) decrypted_buffer_size){
682
 
        ret = (int)fwrite (decrypted_buffer + written, 1,
683
 
                           (size_t)decrypted_buffer_size - written,
684
 
                           stdout);
 
694
        ret = (int)fwrite(decrypted_buffer + written, 1,
 
695
                          (size_t)decrypted_buffer_size - written,
 
696
                          stdout);
685
697
        if(ret == 0 and ferror(stdout)){
686
698
          if(debug){
687
699
            fprintf(stderr, "Error writing encrypted data: %s\n",
708
720
  if(ret == -1){
709
721
    perror("close");
710
722
  }
711
 
  gnutls_deinit (session);
 
723
  gnutls_deinit(session);
712
724
  return retval;
713
725
}
714
726
 
725
737
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
726
738
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
727
739
                             flags,
728
 
                             void* userdata) {
 
740
                             void* userdata){
729
741
  mandos_context *mc = userdata;
730
742
  assert(r);
731
743
  
732
744
  /* Called whenever a service has been resolved successfully or
733
745
     timed out */
734
746
  
735
 
  switch (event) {
 
747
  switch(event){
736
748
  default:
737
749
  case AVAHI_RESOLVER_FAILURE:
738
750
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
746
758
      avahi_address_snprint(ip, sizeof(ip), address);
747
759
      if(debug){
748
760
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %"
749
 
                PRIu16 ") on port %d\n", name, host_name, ip,
750
 
                interface, port);
 
761
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
 
762
                ip, (intmax_t)interface, port);
751
763
      }
752
764
      int ret = start_mandos_communication(ip, port, interface, mc);
753
 
      if (ret == 0){
 
765
      if(ret == 0){
754
766
        avahi_simple_poll_quit(mc->simple_poll);
755
767
      }
756
768
    }
758
770
  avahi_s_service_resolver_free(r);
759
771
}
760
772
 
761
 
static void browse_callback( AvahiSServiceBrowser *b,
762
 
                             AvahiIfIndex interface,
763
 
                             AvahiProtocol protocol,
764
 
                             AvahiBrowserEvent event,
765
 
                             const char *name,
766
 
                             const char *type,
767
 
                             const char *domain,
768
 
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
769
 
                             flags,
770
 
                             void* userdata) {
 
773
static void browse_callback(AvahiSServiceBrowser *b,
 
774
                            AvahiIfIndex interface,
 
775
                            AvahiProtocol protocol,
 
776
                            AvahiBrowserEvent event,
 
777
                            const char *name,
 
778
                            const char *type,
 
779
                            const char *domain,
 
780
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
 
781
                            flags,
 
782
                            void* userdata){
771
783
  mandos_context *mc = userdata;
772
784
  assert(b);
773
785
  
774
786
  /* Called whenever a new services becomes available on the LAN or
775
787
     is removed from the LAN */
776
788
  
777
 
  switch (event) {
 
789
  switch(event){
778
790
  default:
779
791
  case AVAHI_BROWSER_FAILURE:
780
792
    
789
801
       the callback function is called the Avahi server will free the
790
802
       resolver for us. */
791
803
    
792
 
    if (!(avahi_s_service_resolver_new(mc->server, interface,
 
804
    if(!(avahi_s_service_resolver_new(mc->server, interface,
793
805
                                       protocol, name, type, domain,
794
806
                                       AVAHI_PROTO_INET6, 0,
795
807
                                       resolve_callback, mc)))
810
822
}
811
823
 
812
824
int main(int argc, char *argv[]){
813
 
    AvahiSServiceBrowser *sb = NULL;
814
 
    int error;
815
 
    int ret;
816
 
    int exitcode = EXIT_SUCCESS;
817
 
    const char *interface = "eth0";
818
 
    struct ifreq network;
819
 
    int sd;
820
 
    uid_t uid;
821
 
    gid_t gid;
822
 
    char *connect_to = NULL;
823
 
    char tempdir[] = "/tmp/mandosXXXXXX";
824
 
    AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
825
 
    const char *seckey = PATHDIR "/" SECKEY;
826
 
    const char *pubkey = PATHDIR "/" PUBKEY;
827
 
    
828
 
    mandos_context mc = { .simple_poll = NULL, .server = NULL,
829
 
                          .dh_bits = 1024, .priority = "SECURE256"
830
 
                          ":!CTYPE-X.509:+CTYPE-OPENPGP" };
831
 
    bool gnutls_initalized = false;
832
 
    bool gpgme_initalized = false;
833
 
    
834
 
    {
835
 
      struct argp_option options[] = {
836
 
        { .name = "debug", .key = 128,
837
 
          .doc = "Debug mode", .group = 3 },
838
 
        { .name = "connect", .key = 'c',
839
 
          .arg = "ADDRESS:PORT",
840
 
          .doc = "Connect directly to a specific Mandos server",
841
 
          .group = 1 },
842
 
        { .name = "interface", .key = 'i',
843
 
          .arg = "NAME",
844
 
          .doc = "Interface that will be used to search for Mandos"
845
 
          " servers",
846
 
          .group = 1 },
847
 
        { .name = "seckey", .key = 's',
848
 
          .arg = "FILE",
849
 
          .doc = "OpenPGP secret key file base name",
850
 
          .group = 1 },
851
 
        { .name = "pubkey", .key = 'p',
852
 
          .arg = "FILE",
853
 
          .doc = "OpenPGP public key file base name",
854
 
          .group = 2 },
855
 
        { .name = "dh-bits", .key = 129,
856
 
          .arg = "BITS",
857
 
          .doc = "Bit length of the prime number used in the"
858
 
          " Diffie-Hellman key exchange",
859
 
          .group = 2 },
860
 
        { .name = "priority", .key = 130,
861
 
          .arg = "STRING",
862
 
          .doc = "GnuTLS priority string for the TLS handshake",
863
 
          .group = 1 },
864
 
        { .name = NULL }
865
 
      };
866
 
      
867
 
      error_t parse_opt (int key, char *arg,
868
 
                         struct argp_state *state) {
869
 
        /* Get the INPUT argument from `argp_parse', which we know is
870
 
           a pointer to our plugin list pointer. */
871
 
        switch (key) {
872
 
        case 128:               /* --debug */
873
 
          debug = true;
874
 
          break;
875
 
        case 'c':               /* --connect */
876
 
          connect_to = arg;
877
 
          break;
878
 
        case 'i':               /* --interface */
879
 
          interface = arg;
880
 
          break;
881
 
        case 's':               /* --seckey */
882
 
          seckey = arg;
883
 
          break;
884
 
        case 'p':               /* --pubkey */
885
 
          pubkey = arg;
886
 
          break;
887
 
        case 129:               /* --dh-bits */
888
 
          errno = 0;
889
 
          mc.dh_bits = (unsigned int) strtol(arg, NULL, 10);
890
 
          if (errno){
891
 
            perror("strtol");
892
 
            exit(EXIT_FAILURE);
893
 
          }
894
 
          break;
895
 
        case 130:               /* --priority */
896
 
          mc.priority = arg;
897
 
          break;
898
 
        case ARGP_KEY_ARG:
899
 
          argp_usage (state);
900
 
        case ARGP_KEY_END:
901
 
          break;
902
 
        default:
903
 
          return ARGP_ERR_UNKNOWN;
904
 
        }
905
 
        return 0;
906
 
      }
907
 
      
908
 
      struct argp argp = { .options = options, .parser = parse_opt,
909
 
                           .args_doc = "",
910
 
                           .doc = "Mandos client -- Get and decrypt"
911
 
                           " passwords from a Mandos server" };
912
 
      ret = argp_parse (&argp, argc, argv, 0, 0, NULL);
913
 
      if (ret == ARGP_ERR_UNKNOWN){
914
 
        fprintf(stderr, "Unknown error while parsing arguments\n");
915
 
        exitcode = EXIT_FAILURE;
916
 
        goto end;
917
 
      }
918
 
    }
919
 
    
920
 
    /* If the interface is down, bring it up */
921
 
    {
922
 
      sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
923
 
      if(sd < 0) {
924
 
        perror("socket");
925
 
        exitcode = EXIT_FAILURE;
926
 
        goto end;
927
 
      }
928
 
      strcpy(network.ifr_name, interface);
 
825
  AvahiSServiceBrowser *sb = NULL;
 
826
  int error;
 
827
  int ret;
 
828
  intmax_t tmpmax;
 
829
  int numchars;
 
830
  int exitcode = EXIT_SUCCESS;
 
831
  const char *interface = "eth0";
 
832
  struct ifreq network;
 
833
  int sd;
 
834
  uid_t uid;
 
835
  gid_t gid;
 
836
  char *connect_to = NULL;
 
837
  char tempdir[] = "/tmp/mandosXXXXXX";
 
838
  bool tempdir_created = false;
 
839
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
 
840
  const char *seckey = PATHDIR "/" SECKEY;
 
841
  const char *pubkey = PATHDIR "/" PUBKEY;
 
842
  
 
843
  mandos_context mc = { .simple_poll = NULL, .server = NULL,
 
844
                        .dh_bits = 1024, .priority = "SECURE256"
 
845
                        ":!CTYPE-X.509:+CTYPE-OPENPGP" };
 
846
  bool gnutls_initialized = false;
 
847
  bool gpgme_initialized = false;
 
848
  double delay = 2.5;
 
849
  
 
850
  {
 
851
    struct argp_option options[] = {
 
852
      { .name = "debug", .key = 128,
 
853
        .doc = "Debug mode", .group = 3 },
 
854
      { .name = "connect", .key = 'c',
 
855
        .arg = "ADDRESS:PORT",
 
856
        .doc = "Connect directly to a specific Mandos server",
 
857
        .group = 1 },
 
858
      { .name = "interface", .key = 'i',
 
859
        .arg = "NAME",
 
860
        .doc = "Interface that will be used to search for Mandos"
 
861
        " servers",
 
862
        .group = 1 },
 
863
      { .name = "seckey", .key = 's',
 
864
        .arg = "FILE",
 
865
        .doc = "OpenPGP secret key file base name",
 
866
        .group = 1 },
 
867
      { .name = "pubkey", .key = 'p',
 
868
        .arg = "FILE",
 
869
        .doc = "OpenPGP public key file base name",
 
870
        .group = 2 },
 
871
      { .name = "dh-bits", .key = 129,
 
872
        .arg = "BITS",
 
873
        .doc = "Bit length of the prime number used in the"
 
874
        " Diffie-Hellman key exchange",
 
875
        .group = 2 },
 
876
      { .name = "priority", .key = 130,
 
877
        .arg = "STRING",
 
878
        .doc = "GnuTLS priority string for the TLS handshake",
 
879
        .group = 1 },
 
880
      { .name = "delay", .key = 131,
 
881
        .arg = "SECONDS",
 
882
        .doc = "Maximum delay to wait for interface startup",
 
883
        .group = 2 },
 
884
      { .name = NULL }
 
885
    };
 
886
    
 
887
    error_t parse_opt(int key, char *arg,
 
888
                      struct argp_state *state){
 
889
      switch(key){
 
890
      case 128:                 /* --debug */
 
891
        debug = true;
 
892
        break;
 
893
      case 'c':                 /* --connect */
 
894
        connect_to = arg;
 
895
        break;
 
896
      case 'i':                 /* --interface */
 
897
        interface = arg;
 
898
        break;
 
899
      case 's':                 /* --seckey */
 
900
        seckey = arg;
 
901
        break;
 
902
      case 'p':                 /* --pubkey */
 
903
        pubkey = arg;
 
904
        break;
 
905
      case 129:                 /* --dh-bits */
 
906
        ret = sscanf(arg, "%" SCNdMAX "%n", &tmpmax, &numchars);
 
907
        if(ret < 1 or tmpmax != (typeof(mc.dh_bits))tmpmax
 
908
           or arg[numchars] != '\0'){
 
909
          fprintf(stderr, "Bad number of DH bits\n");
 
910
          exit(EXIT_FAILURE);
 
911
        }
 
912
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
 
913
        break;
 
914
      case 130:                 /* --priority */
 
915
        mc.priority = arg;
 
916
        break;
 
917
      case 131:                 /* --delay */
 
918
        ret = sscanf(arg, "%lf%n", &delay, &numchars);
 
919
        if(ret < 1 or arg[numchars] != '\0'){
 
920
          fprintf(stderr, "Bad delay\n");
 
921
          exit(EXIT_FAILURE);
 
922
        }
 
923
        break;
 
924
      case ARGP_KEY_ARG:
 
925
        argp_usage(state);
 
926
      case ARGP_KEY_END:
 
927
        break;
 
928
      default:
 
929
        return ARGP_ERR_UNKNOWN;
 
930
      }
 
931
      return 0;
 
932
    }
 
933
    
 
934
    struct argp argp = { .options = options, .parser = parse_opt,
 
935
                         .args_doc = "",
 
936
                         .doc = "Mandos client -- Get and decrypt"
 
937
                         " passwords from a Mandos server" };
 
938
    ret = argp_parse(&argp, argc, argv, 0, 0, NULL);
 
939
    if(ret == ARGP_ERR_UNKNOWN){
 
940
      fprintf(stderr, "Unknown error while parsing arguments\n");
 
941
      exitcode = EXIT_FAILURE;
 
942
      goto end;
 
943
    }
 
944
  }
 
945
  
 
946
  /* If the interface is down, bring it up */
 
947
  {
 
948
#ifdef __linux__
 
949
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
 
950
       messages to mess up the prompt */
 
951
    ret = klogctl(8, NULL, 5);
 
952
    if(ret == -1){
 
953
      perror("klogctl");
 
954
    }
 
955
#endif
 
956
    
 
957
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
958
    if(sd < 0){
 
959
      perror("socket");
 
960
      exitcode = EXIT_FAILURE;
 
961
#ifdef __linux__
 
962
      ret = klogctl(7, NULL, 0);
 
963
      if(ret == -1){
 
964
        perror("klogctl");
 
965
      }
 
966
#endif
 
967
      goto end;
 
968
    }
 
969
    strcpy(network.ifr_name, interface);
 
970
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
971
    if(ret == -1){
 
972
      perror("ioctl SIOCGIFFLAGS");
 
973
#ifdef __linux__
 
974
      ret = klogctl(7, NULL, 0);
 
975
      if(ret == -1){
 
976
        perror("klogctl");
 
977
      }
 
978
#endif
 
979
      exitcode = EXIT_FAILURE;
 
980
      goto end;
 
981
    }
 
982
    if((network.ifr_flags & IFF_UP) == 0){
 
983
      network.ifr_flags |= IFF_UP;
 
984
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
985
      if(ret == -1){
 
986
        perror("ioctl SIOCSIFFLAGS");
 
987
        exitcode = EXIT_FAILURE;
 
988
#ifdef __linux__
 
989
        ret = klogctl(7, NULL, 0);
 
990
        if(ret == -1){
 
991
          perror("klogctl");
 
992
        }
 
993
#endif
 
994
        goto end;
 
995
      }
 
996
    }
 
997
    /* sleep checking until interface is running */
 
998
    for(int i=0; i < delay * 4; i++){
929
999
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
930
1000
      if(ret == -1){
931
1001
        perror("ioctl SIOCGIFFLAGS");
932
 
        exitcode = EXIT_FAILURE;
933
 
        goto end;
934
 
      }
935
 
      if((network.ifr_flags & IFF_UP) == 0){
936
 
        network.ifr_flags |= IFF_UP;
937
 
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
938
 
        if(ret == -1){
939
 
          perror("ioctl SIOCSIFFLAGS");
940
 
          exitcode = EXIT_FAILURE;
941
 
          goto end;
942
 
        }
943
 
      }
944
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
945
 
      if(ret == -1){
946
 
        perror("close");
947
 
      }
948
 
    }
949
 
    
950
 
    uid = getuid();
951
 
    gid = getgid();
952
 
    
953
 
    ret = setuid(uid);
954
 
    if (ret == -1){
955
 
      perror("setuid");
956
 
    }
957
 
    
958
 
    setgid(gid);
959
 
    if (ret == -1){
960
 
      perror("setgid");
961
 
    }
962
 
    
963
 
    ret = init_gnutls_global(&mc, pubkey, seckey);
964
 
    if (ret == -1){
965
 
      fprintf(stderr, "init_gnutls_global failed\n");
966
 
      exitcode = EXIT_FAILURE;
967
 
      goto end;
968
 
    } else {
969
 
      gnutls_initalized = true;
970
 
    }
971
 
    
972
 
    if(mkdtemp(tempdir) == NULL){
973
 
      perror("mkdtemp");
974
 
      tempdir[0] = '\0';
975
 
      goto end;
976
 
    }
977
 
    
978
 
    if(not init_gpgme(&mc, pubkey, seckey, tempdir)){
979
 
      fprintf(stderr, "gpgme_initalized failed\n");
980
 
      exitcode = EXIT_FAILURE;
981
 
      goto end;
982
 
    } else {
983
 
      gpgme_initalized = true;
984
 
    }
985
 
    
986
 
    if_index = (AvahiIfIndex) if_nametoindex(interface);
987
 
    if(if_index == 0){
988
 
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
989
 
      exit(EXIT_FAILURE);
990
 
    }
991
 
    
992
 
    if(connect_to != NULL){
993
 
      /* Connect directly, do not use Zeroconf */
994
 
      /* (Mainly meant for debugging) */
995
 
      char *address = strrchr(connect_to, ':');
996
 
      if(address == NULL){
997
 
        fprintf(stderr, "No colon in address\n");
998
 
        exitcode = EXIT_FAILURE;
999
 
        goto end;
1000
 
      }
1001
 
      errno = 0;
1002
 
      uint16_t port = (uint16_t) strtol(address+1, NULL, 10);
1003
 
      if(errno){
1004
 
        perror("Bad port number");
1005
 
        exitcode = EXIT_FAILURE;
1006
 
        goto end;
1007
 
      }
1008
 
      *address = '\0';
1009
 
      address = connect_to;
1010
 
      ret = start_mandos_communication(address, port, if_index, &mc);
1011
 
      if(ret < 0){
1012
 
        exitcode = EXIT_FAILURE;
1013
 
      } else {
1014
 
        exitcode = EXIT_SUCCESS;
1015
 
      }
1016
 
      goto end;
1017
 
    }
1018
 
    
1019
 
    if (not debug){
1020
 
      avahi_set_log_function(empty_log);
1021
 
    }
1022
 
    
1023
 
    /* Initialize the pseudo-RNG for Avahi */
1024
 
    srand((unsigned int) time(NULL));
1025
 
    
1026
 
    /* Allocate main Avahi loop object */
1027
 
    mc.simple_poll = avahi_simple_poll_new();
1028
 
    if (mc.simple_poll == NULL) {
1029
 
        fprintf(stderr, "Avahi: Failed to create simple poll"
1030
 
                " object.\n");
1031
 
        exitcode = EXIT_FAILURE;
1032
 
        goto end;
1033
 
    }
1034
 
    
1035
 
    {
1036
 
      AvahiServerConfig config;
1037
 
      /* Do not publish any local Zeroconf records */
1038
 
      avahi_server_config_init(&config);
1039
 
      config.publish_hinfo = 0;
1040
 
      config.publish_addresses = 0;
1041
 
      config.publish_workstation = 0;
1042
 
      config.publish_domain = 0;
1043
 
      
1044
 
      /* Allocate a new server */
1045
 
      mc.server = avahi_server_new(avahi_simple_poll_get
1046
 
                                   (mc.simple_poll), &config, NULL,
1047
 
                                   NULL, &error);
1048
 
      
1049
 
      /* Free the Avahi configuration data */
1050
 
      avahi_server_config_free(&config);
1051
 
    }
1052
 
    
1053
 
    /* Check if creating the Avahi server object succeeded */
1054
 
    if (mc.server == NULL) {
1055
 
        fprintf(stderr, "Failed to create Avahi server: %s\n",
1056
 
                avahi_strerror(error));
1057
 
        exitcode = EXIT_FAILURE;
1058
 
        goto end;
1059
 
    }
1060
 
    
1061
 
    /* Create the Avahi service browser */
1062
 
    sb = avahi_s_service_browser_new(mc.server, if_index,
1063
 
                                     AVAHI_PROTO_INET6,
1064
 
                                     "_mandos._tcp", NULL, 0,
1065
 
                                     browse_callback, &mc);
1066
 
    if (sb == NULL) {
1067
 
        fprintf(stderr, "Failed to create service browser: %s\n",
1068
 
                avahi_strerror(avahi_server_errno(mc.server)));
1069
 
        exitcode = EXIT_FAILURE;
1070
 
        goto end;
1071
 
    }
1072
 
    
1073
 
    /* Run the main loop */
1074
 
    
1075
 
    if (debug){
1076
 
      fprintf(stderr, "Starting Avahi loop search\n");
1077
 
    }
1078
 
    
1079
 
    avahi_simple_poll_loop(mc.simple_poll);
1080
 
    
 
1002
      } else if(network.ifr_flags & IFF_RUNNING){
 
1003
        break;
 
1004
      }
 
1005
      struct timespec sleeptime = { .tv_nsec = 250000000 };
 
1006
      ret = nanosleep(&sleeptime, NULL);
 
1007
      if(ret == -1 and errno != EINTR){
 
1008
        perror("nanosleep");
 
1009
      }
 
1010
    }
 
1011
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1012
    if(ret == -1){
 
1013
      perror("close");
 
1014
    }
 
1015
#ifdef __linux__
 
1016
    /* Restores kernel loglevel to default */
 
1017
    ret = klogctl(7, NULL, 0);
 
1018
    if(ret == -1){
 
1019
      perror("klogctl");
 
1020
    }
 
1021
#endif
 
1022
  }
 
1023
  
 
1024
  uid = getuid();
 
1025
  gid = getgid();
 
1026
  
 
1027
  setgid(gid);
 
1028
  if(ret == -1){
 
1029
    perror("setgid");
 
1030
  }
 
1031
  
 
1032
  ret = setuid(uid);
 
1033
  if(ret == -1){
 
1034
    perror("setuid");
 
1035
  }
 
1036
  
 
1037
  ret = init_gnutls_global(&mc, pubkey, seckey);
 
1038
  if(ret == -1){
 
1039
    fprintf(stderr, "init_gnutls_global failed\n");
 
1040
    exitcode = EXIT_FAILURE;
 
1041
    goto end;
 
1042
  } else {
 
1043
    gnutls_initialized = true;
 
1044
  }
 
1045
  
 
1046
  if(mkdtemp(tempdir) == NULL){
 
1047
    perror("mkdtemp");
 
1048
    goto end;
 
1049
  }
 
1050
  tempdir_created = true;
 
1051
  
 
1052
  if(not init_gpgme(&mc, pubkey, seckey, tempdir)){
 
1053
    fprintf(stderr, "init_gpgme failed\n");
 
1054
    exitcode = EXIT_FAILURE;
 
1055
    goto end;
 
1056
  } else {
 
1057
    gpgme_initialized = true;
 
1058
  }
 
1059
  
 
1060
  if_index = (AvahiIfIndex) if_nametoindex(interface);
 
1061
  if(if_index == 0){
 
1062
    fprintf(stderr, "No such interface: \"%s\"\n", interface);
 
1063
    exitcode = EXIT_FAILURE;
 
1064
    goto end;
 
1065
  }
 
1066
  
 
1067
  if(connect_to != NULL){
 
1068
    /* Connect directly, do not use Zeroconf */
 
1069
    /* (Mainly meant for debugging) */
 
1070
    char *address = strrchr(connect_to, ':');
 
1071
    if(address == NULL){
 
1072
      fprintf(stderr, "No colon in address\n");
 
1073
      exitcode = EXIT_FAILURE;
 
1074
      goto end;
 
1075
    }
 
1076
    uint16_t port;
 
1077
    ret = sscanf(address+1, "%" SCNdMAX "%n", &tmpmax, &numchars);
 
1078
    if(ret < 1 or tmpmax != (uint16_t)tmpmax
 
1079
       or address[numchars+1] != '\0'){
 
1080
      fprintf(stderr, "Bad port number\n");
 
1081
      exitcode = EXIT_FAILURE;
 
1082
      goto end;
 
1083
    }
 
1084
    port = (uint16_t)tmpmax;
 
1085
    *address = '\0';
 
1086
    address = connect_to;
 
1087
    ret = start_mandos_communication(address, port, if_index, &mc);
 
1088
    if(ret < 0){
 
1089
      exitcode = EXIT_FAILURE;
 
1090
    } else {
 
1091
      exitcode = EXIT_SUCCESS;
 
1092
    }
 
1093
    goto end;
 
1094
  }
 
1095
  
 
1096
  if(not debug){
 
1097
    avahi_set_log_function(empty_log);
 
1098
  }
 
1099
  
 
1100
  /* Initialize the pseudo-RNG for Avahi */
 
1101
  srand((unsigned int) time(NULL));
 
1102
  
 
1103
  /* Allocate main Avahi loop object */
 
1104
  mc.simple_poll = avahi_simple_poll_new();
 
1105
  if(mc.simple_poll == NULL){
 
1106
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
 
1107
    exitcode = EXIT_FAILURE;
 
1108
    goto end;
 
1109
  }
 
1110
  
 
1111
  {
 
1112
    AvahiServerConfig config;
 
1113
    /* Do not publish any local Zeroconf records */
 
1114
    avahi_server_config_init(&config);
 
1115
    config.publish_hinfo = 0;
 
1116
    config.publish_addresses = 0;
 
1117
    config.publish_workstation = 0;
 
1118
    config.publish_domain = 0;
 
1119
    
 
1120
    /* Allocate a new server */
 
1121
    mc.server = avahi_server_new(avahi_simple_poll_get
 
1122
                                 (mc.simple_poll), &config, NULL,
 
1123
                                 NULL, &error);
 
1124
    
 
1125
    /* Free the Avahi configuration data */
 
1126
    avahi_server_config_free(&config);
 
1127
  }
 
1128
  
 
1129
  /* Check if creating the Avahi server object succeeded */
 
1130
  if(mc.server == NULL){
 
1131
    fprintf(stderr, "Failed to create Avahi server: %s\n",
 
1132
            avahi_strerror(error));
 
1133
    exitcode = EXIT_FAILURE;
 
1134
    goto end;
 
1135
  }
 
1136
  
 
1137
  /* Create the Avahi service browser */
 
1138
  sb = avahi_s_service_browser_new(mc.server, if_index,
 
1139
                                   AVAHI_PROTO_INET6, "_mandos._tcp",
 
1140
                                   NULL, 0, browse_callback, &mc);
 
1141
  if(sb == NULL){
 
1142
    fprintf(stderr, "Failed to create service browser: %s\n",
 
1143
            avahi_strerror(avahi_server_errno(mc.server)));
 
1144
    exitcode = EXIT_FAILURE;
 
1145
    goto end;
 
1146
  }
 
1147
  
 
1148
  /* Run the main loop */
 
1149
  
 
1150
  if(debug){
 
1151
    fprintf(stderr, "Starting Avahi loop search\n");
 
1152
  }
 
1153
  
 
1154
  avahi_simple_poll_loop(mc.simple_poll);
 
1155
  
1081
1156
 end:
1082
 
    
1083
 
    if (debug){
1084
 
      fprintf(stderr, "%s exiting\n", argv[0]);
1085
 
    }
1086
 
    
1087
 
    /* Cleanup things */
1088
 
    if (sb != NULL)
1089
 
        avahi_s_service_browser_free(sb);
1090
 
    
1091
 
    if (mc.server != NULL)
1092
 
        avahi_server_free(mc.server);
1093
 
    
1094
 
    if (mc.simple_poll != NULL)
1095
 
        avahi_simple_poll_free(mc.simple_poll);
1096
 
    
1097
 
    if (gnutls_initalized){
1098
 
      gnutls_certificate_free_credentials(mc.cred);
1099
 
      gnutls_global_deinit ();
1100
 
      gnutls_dh_params_deinit(mc.dh_params);
1101
 
    }
1102
 
    
1103
 
    if(gpgme_initalized){
1104
 
      gpgme_release(mc.ctx);
1105
 
    }
1106
 
    
1107
 
    /* Removes the temp directory used by GPGME */
1108
 
    if(tempdir[0] != '\0'){
1109
 
      DIR *d;
1110
 
      struct dirent *direntry;
1111
 
      d = opendir(tempdir);
1112
 
      if(d == NULL){
 
1157
  
 
1158
  if(debug){
 
1159
    fprintf(stderr, "%s exiting\n", argv[0]);
 
1160
  }
 
1161
  
 
1162
  /* Cleanup things */
 
1163
  if(sb != NULL)
 
1164
    avahi_s_service_browser_free(sb);
 
1165
  
 
1166
  if(mc.server != NULL)
 
1167
    avahi_server_free(mc.server);
 
1168
  
 
1169
  if(mc.simple_poll != NULL)
 
1170
    avahi_simple_poll_free(mc.simple_poll);
 
1171
  
 
1172
  if(gnutls_initialized){
 
1173
    gnutls_certificate_free_credentials(mc.cred);
 
1174
    gnutls_global_deinit();
 
1175
    gnutls_dh_params_deinit(mc.dh_params);
 
1176
  }
 
1177
  
 
1178
  if(gpgme_initialized){
 
1179
    gpgme_release(mc.ctx);
 
1180
  }
 
1181
  
 
1182
  /* Removes the temp directory used by GPGME */
 
1183
  if(tempdir_created){
 
1184
    DIR *d;
 
1185
    struct dirent *direntry;
 
1186
    d = opendir(tempdir);
 
1187
    if(d == NULL){
 
1188
      if(errno != ENOENT){
1113
1189
        perror("opendir");
1114
 
      } else {
1115
 
        while(true){
1116
 
          direntry = readdir(d);
1117
 
          if(direntry == NULL){
1118
 
            break;
1119
 
          }
1120
 
          if (direntry->d_type == DT_REG){
1121
 
            char *fullname = NULL;
1122
 
            ret = asprintf(&fullname, "%s/%s", tempdir,
1123
 
                           direntry->d_name);
1124
 
            if(ret < 0){
1125
 
              perror("asprintf");
1126
 
              continue;
1127
 
            }
1128
 
            ret = unlink(fullname);
1129
 
            if(ret == -1){
1130
 
              fprintf(stderr, "unlink(\"%s\"): %s",
1131
 
                      fullname, strerror(errno));
1132
 
            }
1133
 
            free(fullname);
1134
 
          }
1135
 
        }
1136
 
        closedir(d);
1137
 
      }
1138
 
      ret = rmdir(tempdir);
1139
 
      if(ret == -1){
1140
 
        perror("rmdir");
1141
 
      }
1142
 
    }
1143
 
          
1144
 
    return exitcode;
 
1190
      }
 
1191
    } else {
 
1192
      while(true){
 
1193
        direntry = readdir(d);
 
1194
        if(direntry == NULL){
 
1195
          break;
 
1196
        }
 
1197
        /* Skip "." and ".." */
 
1198
        if(direntry->d_name[0] == '.'
 
1199
           and (direntry->d_name[1] == '\0'
 
1200
                or (direntry->d_name[1] == '.'
 
1201
                    and direntry->d_name[2] == '\0'))){
 
1202
          continue;
 
1203
        }
 
1204
        char *fullname = NULL;
 
1205
        ret = asprintf(&fullname, "%s/%s", tempdir,
 
1206
                       direntry->d_name);
 
1207
        if(ret < 0){
 
1208
          perror("asprintf");
 
1209
          continue;
 
1210
        }
 
1211
        ret = remove(fullname);
 
1212
        if(ret == -1){
 
1213
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
 
1214
                  strerror(errno));
 
1215
        }
 
1216
        free(fullname);
 
1217
      }
 
1218
      closedir(d);
 
1219
    }
 
1220
    ret = rmdir(tempdir);
 
1221
    if(ret == -1 and errno != ENOENT){
 
1222
      perror("rmdir");
 
1223
    }
 
1224
  }
 
1225
  
 
1226
  return exitcode;
1145
1227
}