/mandos/trunk

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

« back to all changes in this revision

Viewing changes to plugins.d/password-request.c

  • Committer: Teddy Hogeborn
  • Date: 2008-08-07 22:30:45 UTC
  • Revision ID: teddy@fukt.bsnet.se-20080807223045-58y7vw4bcqlmesv5
* network-protocol.txt: Flip table.

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
9
9
 * "browse_callback", and parts of "main".
10
10
 * 
11
11
 * Everything else is
12
 
 * Copyright © 2008,2009 Teddy Hogeborn
13
 
 * Copyright © 2008,2009 Björn Påhlsson
 
12
 * Copyright © 2007-2008 Teddy Hogeborn & Björn Påhlsson
14
13
 * 
15
14
 * This program is free software: you can redistribute it and/or
16
15
 * modify it under the terms of the GNU General Public License as
33
32
#define _LARGEFILE_SOURCE
34
33
#define _FILE_OFFSET_BITS 64
35
34
 
36
 
#define _GNU_SOURCE             /* TEMP_FAILURE_RETRY(), asprintf() */
 
35
#define _GNU_SOURCE             /* TEMP_FAILURE_RETRY() */
37
36
 
38
 
#include <stdio.h>              /* fprintf(), stderr, fwrite(),
39
 
                                   stdout, ferror(), sscanf(),
40
 
                                   remove() */
41
 
#include <stdint.h>             /* uint16_t, uint32_t */
42
 
#include <stddef.h>             /* NULL, size_t, ssize_t */
43
 
#include <stdlib.h>             /* free(), EXIT_SUCCESS, EXIT_FAILURE,
44
 
                                   srand() */
45
 
#include <stdbool.h>            /* bool, false, true */
46
 
#include <string.h>             /* memset(), strcmp(), strlen(),
47
 
                                   strerror(), asprintf(), strcpy() */
48
 
#include <sys/ioctl.h>          /* ioctl */
49
 
#include <sys/types.h>          /* socket(), inet_pton(), sockaddr,
50
 
                                   sockaddr_in6, PF_INET6,
51
 
                                   SOCK_STREAM, uid_t, gid_t, open(),
52
 
                                   opendir(), DIR */
53
 
#include <sys/stat.h>           /* open() */
54
 
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
55
 
                                   inet_pton(), connect() */
56
 
#include <fcntl.h>              /* open() */
57
 
#include <dirent.h>             /* opendir(), struct dirent, readdir()
58
 
                                 */
59
 
#include <inttypes.h>           /* PRIu16, intmax_t, SCNdMAX */
60
 
#include <assert.h>             /* assert() */
61
 
#include <errno.h>              /* perror(), errno */
62
 
#include <time.h>               /* nanosleep(), time() */
 
37
#include <stdio.h>
 
38
#include <assert.h>
 
39
#include <stdlib.h>
 
40
#include <time.h>
 
41
#include <net/if.h>             /* if_nametoindex */
 
42
#include <sys/ioctl.h>          /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
 
43
                                   SIOCSIFFLAGS */
63
44
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
64
 
                                   SIOCSIFFLAGS, if_indextoname(),
65
 
                                   if_nametoindex(), IF_NAMESIZE */
66
 
#include <netinet/in.h>         /* IN6_IS_ADDR_LINKLOCAL,
67
 
                                   INET_ADDRSTRLEN, INET6_ADDRSTRLEN
68
 
                                */
69
 
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
70
 
                                   getuid(), getgid(), setuid(),
71
 
                                   setgid() */
72
 
#include <arpa/inet.h>          /* inet_pton(), htons */
73
 
#include <iso646.h>             /* not, or, and */
74
 
#include <argp.h>               /* struct argp_option, error_t, struct
75
 
                                   argp_state, struct argp,
76
 
                                   argp_parse(), ARGP_KEY_ARG,
77
 
                                   ARGP_KEY_END, ARGP_ERR_UNKNOWN */
78
 
#include <signal.h>             /* sigemptyset(), sigaddset(), sigaction(), SIGTERM, sigaction */
79
 
#ifdef __linux__
80
 
#include <sys/klog.h>           /* klogctl() */
81
 
#endif
 
45
                                   SIOCSIFFLAGS */
82
46
 
83
 
/* Avahi */
84
 
/* All Avahi types, constants and functions
85
 
 Avahi*, avahi_*,
86
 
 AVAHI_* */
87
47
#include <avahi-core/core.h>
88
48
#include <avahi-core/lookup.h>
89
49
#include <avahi-core/log.h>
91
51
#include <avahi-common/malloc.h>
92
52
#include <avahi-common/error.h>
93
53
 
94
 
/* GnuTLS */
95
 
#include <gnutls/gnutls.h>      /* All GnuTLS types, constants and
96
 
                                   functions:
97
 
                                   gnutls_*
98
 
                                   init_gnutls_session(),
99
 
                                   GNUTLS_* */
100
 
#include <gnutls/openpgp.h>
101
 
                          /* gnutls_certificate_set_openpgp_key_file(),
102
 
                                   GNUTLS_OPENPGP_FMT_BASE64 */
 
54
/* Mandos client part */
 
55
#include <sys/types.h>          /* socket(), inet_pton() */
 
56
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
 
57
                                   struct in6_addr, inet_pton() */
 
58
#include <gnutls/gnutls.h>      /* All GnuTLS stuff */
 
59
#include <gnutls/openpgp.h>     /* GnuTLS with openpgp stuff */
103
60
 
 
61
#include <unistd.h>             /* close() */
 
62
#include <netinet/in.h>
 
63
#include <stdbool.h>            /* true */
 
64
#include <string.h>             /* memset */
 
65
#include <arpa/inet.h>          /* inet_pton() */
 
66
#include <iso646.h>             /* not */
 
67
#include <net/if.h>             /* IF_NAMESIZE */
 
68
#include <argp.h>               /* struct argp_option,
 
69
                                   struct argp_state, struct argp,
 
70
                                   argp_parse() */
104
71
/* GPGME */
105
 
#include <gpgme.h>              /* All GPGME types, constants and
106
 
                                   functions:
107
 
                                   gpgme_*
108
 
                                   GPGME_PROTOCOL_OpenPGP,
109
 
                                   GPG_ERR_NO_* */
 
72
#include <errno.h>              /* perror() */
 
73
#include <gpgme.h>
110
74
 
111
75
#define BUFFER_SIZE 256
112
76
 
113
 
#define PATHDIR "/conf/conf.d/mandos"
114
 
#define SECKEY "seckey.txt"
115
 
#define PUBKEY "pubkey.txt"
116
 
 
117
77
bool debug = false;
 
78
static const char *keydir = "/conf/conf.d/mandos";
118
79
static const char mandos_protocol_version[] = "1";
119
 
const char *argp_program_version = "mandos-client " VERSION;
 
80
const char *argp_program_version = "mandosclient 0.9";
120
81
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
121
82
 
122
83
/* Used for passing in values through the Avahi callback functions */
127
88
  unsigned int dh_bits;
128
89
  gnutls_dh_params_t dh_params;
129
90
  const char *priority;
130
 
  gpgme_ctx_t ctx;
131
91
} mandos_context;
132
92
 
133
 
/* global context so signal handler can reach it*/
134
 
mandos_context mc = { .simple_poll = NULL, .server = NULL,
135
 
                      .dh_bits = 1024, .priority = "SECURE256"
136
 
                      ":!CTYPE-X.509:+CTYPE-OPENPGP" };
137
 
 
138
93
/*
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.
 
94
 * Make room in "buffer" for at least BUFFER_SIZE additional bytes.
 
95
 * "buffer_capacity" is how much is currently allocated,
 
96
 * "buffer_length" is how much is already used.
142
97
 */
143
 
size_t incbuffer(char **buffer, size_t buffer_length,
 
98
size_t adjustbuffer(char **buffer, size_t buffer_length,
144
99
                  size_t buffer_capacity){
145
 
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
 
100
  if (buffer_length + BUFFER_SIZE > buffer_capacity){
146
101
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
147
 
    if(buffer == NULL){
 
102
    if (buffer == NULL){
148
103
      return 0;
149
104
    }
150
105
    buffer_capacity += BUFFER_SIZE;
153
108
}
154
109
 
155
110
/* 
156
 
 * Initialize GPGME.
 
111
 * Decrypt OpenPGP data using keyrings in HOMEDIR.
 
112
 * Returns -1 on error
157
113
 */
158
 
static bool init_gpgme(const char *seckey,
159
 
                       const char *pubkey, const char *tempdir){
160
 
  int ret;
 
114
static ssize_t pgp_packet_decrypt (const char *cryptotext,
 
115
                                   size_t crypto_size,
 
116
                                   char **plaintext,
 
117
                                   const char *homedir){
 
118
  gpgme_data_t dh_crypto, dh_plain;
 
119
  gpgme_ctx_t ctx;
161
120
  gpgme_error_t rc;
 
121
  ssize_t ret;
 
122
  size_t plaintext_capacity = 0;
 
123
  ssize_t plaintext_length = 0;
162
124
  gpgme_engine_info_t engine_info;
163
125
  
164
 
  
165
 
  /*
166
 
   * Helper function to insert pub and seckey to the engine keyring.
167
 
   */
168
 
  bool import_key(const char *filename){
169
 
    int fd;
170
 
    gpgme_data_t pgp_data;
171
 
    
172
 
    fd = (int)TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
173
 
    if(fd == -1){
174
 
      perror("open");
175
 
      return false;
176
 
    }
177
 
    
178
 
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
179
 
    if(rc != GPG_ERR_NO_ERROR){
180
 
      fprintf(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
181
 
              gpgme_strsource(rc), gpgme_strerror(rc));
182
 
      return false;
183
 
    }
184
 
    
185
 
    rc = gpgme_op_import(mc.ctx, pgp_data);
186
 
    if(rc != GPG_ERR_NO_ERROR){
187
 
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
188
 
              gpgme_strsource(rc), gpgme_strerror(rc));
189
 
      return false;
190
 
    }
191
 
    
192
 
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
193
 
    if(ret == -1){
194
 
      perror("close");
195
 
    }
196
 
    gpgme_data_release(pgp_data);
197
 
    return true;
198
 
  }
199
 
  
200
 
  if(debug){
201
 
    fprintf(stderr, "Initialize gpgme\n");
 
126
  if (debug){
 
127
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
202
128
  }
203
129
  
204
130
  /* Init GPGME */
205
131
  gpgme_check_version(NULL);
206
132
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
207
 
  if(rc != GPG_ERR_NO_ERROR){
 
133
  if (rc != GPG_ERR_NO_ERROR){
208
134
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
209
135
            gpgme_strsource(rc), gpgme_strerror(rc));
210
 
    return false;
 
136
    return -1;
211
137
  }
212
138
  
213
 
    /* Set GPGME home directory for the OpenPGP engine only */
214
 
  rc = gpgme_get_engine_info(&engine_info);
215
 
  if(rc != GPG_ERR_NO_ERROR){
 
139
  /* Set GPGME home directory for the OpenPGP engine only */
 
140
  rc = gpgme_get_engine_info (&engine_info);
 
141
  if (rc != GPG_ERR_NO_ERROR){
216
142
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
217
143
            gpgme_strsource(rc), gpgme_strerror(rc));
218
 
    return false;
 
144
    return -1;
219
145
  }
220
146
  while(engine_info != NULL){
221
147
    if(engine_info->protocol == GPGME_PROTOCOL_OpenPGP){
222
148
      gpgme_set_engine_info(GPGME_PROTOCOL_OpenPGP,
223
 
                            engine_info->file_name, tempdir);
 
149
                            engine_info->file_name, homedir);
224
150
      break;
225
151
    }
226
152
    engine_info = engine_info->next;
227
153
  }
228
154
  if(engine_info == NULL){
229
 
    fprintf(stderr, "Could not set GPGME home dir to %s\n", tempdir);
230
 
    return false;
231
 
  }
232
 
  
233
 
  /* Create new GPGME "context" */
234
 
  rc = gpgme_new(&(mc.ctx));
235
 
  if(rc != GPG_ERR_NO_ERROR){
236
 
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
237
 
            gpgme_strsource(rc), gpgme_strerror(rc));
238
 
    return false;
239
 
  }
240
 
  
241
 
  if(not import_key(pubkey) or not import_key(seckey)){
242
 
    return false;
243
 
  }
244
 
  
245
 
  return true; 
246
 
}
247
 
 
248
 
/* 
249
 
 * Decrypt OpenPGP data.
250
 
 * Returns -1 on error
251
 
 */
252
 
static ssize_t pgp_packet_decrypt(const char *cryptotext,
253
 
                                  size_t crypto_size,
254
 
                                  char **plaintext){
255
 
  gpgme_data_t dh_crypto, dh_plain;
256
 
  gpgme_error_t rc;
257
 
  ssize_t ret;
258
 
  size_t plaintext_capacity = 0;
259
 
  ssize_t plaintext_length = 0;
260
 
  
261
 
  if(debug){
262
 
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
 
155
    fprintf(stderr, "Could not set GPGME home dir to %s\n", homedir);
 
156
    return -1;
263
157
  }
264
158
  
265
159
  /* Create new GPGME data buffer from memory cryptotext */
266
160
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
267
161
                               0);
268
 
  if(rc != GPG_ERR_NO_ERROR){
 
162
  if (rc != GPG_ERR_NO_ERROR){
269
163
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
270
164
            gpgme_strsource(rc), gpgme_strerror(rc));
271
165
    return -1;
273
167
  
274
168
  /* Create new empty GPGME data buffer for the plaintext */
275
169
  rc = gpgme_data_new(&dh_plain);
276
 
  if(rc != GPG_ERR_NO_ERROR){
 
170
  if (rc != GPG_ERR_NO_ERROR){
277
171
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
278
172
            gpgme_strsource(rc), gpgme_strerror(rc));
279
173
    gpgme_data_release(dh_crypto);
280
174
    return -1;
281
175
  }
282
176
  
 
177
  /* Create new GPGME "context" */
 
178
  rc = gpgme_new(&ctx);
 
179
  if (rc != GPG_ERR_NO_ERROR){
 
180
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
 
181
            gpgme_strsource(rc), gpgme_strerror(rc));
 
182
    plaintext_length = -1;
 
183
    goto decrypt_end;
 
184
  }
 
185
  
283
186
  /* Decrypt data from the cryptotext data buffer to the plaintext
284
187
     data buffer */
285
 
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
286
 
  if(rc != GPG_ERR_NO_ERROR){
 
188
  rc = gpgme_op_decrypt(ctx, dh_crypto, dh_plain);
 
189
  if (rc != GPG_ERR_NO_ERROR){
287
190
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
288
191
            gpgme_strsource(rc), gpgme_strerror(rc));
289
192
    plaintext_length = -1;
290
 
    if(debug){
291
 
      gpgme_decrypt_result_t result;
292
 
      result = gpgme_op_decrypt_result(mc.ctx);
293
 
      if(result == NULL){
294
 
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
295
 
      } else {
296
 
        fprintf(stderr, "Unsupported algorithm: %s\n",
297
 
                result->unsupported_algorithm);
298
 
        fprintf(stderr, "Wrong key usage: %u\n",
299
 
                result->wrong_key_usage);
300
 
        if(result->file_name != NULL){
301
 
          fprintf(stderr, "File name: %s\n", result->file_name);
302
 
        }
303
 
        gpgme_recipient_t recipient;
304
 
        recipient = result->recipients;
305
 
        if(recipient){
306
 
          while(recipient != NULL){
307
 
            fprintf(stderr, "Public key algorithm: %s\n",
308
 
                    gpgme_pubkey_algo_name(recipient->pubkey_algo));
309
 
            fprintf(stderr, "Key ID: %s\n", recipient->keyid);
310
 
            fprintf(stderr, "Secret key available: %s\n",
311
 
                    recipient->status == GPG_ERR_NO_SECKEY
312
 
                    ? "No" : "Yes");
313
 
            recipient = recipient->next;
314
 
          }
315
 
        }
316
 
      }
317
 
    }
318
193
    goto decrypt_end;
319
194
  }
320
195
  
322
197
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
323
198
  }
324
199
  
 
200
  if (debug){
 
201
    gpgme_decrypt_result_t result;
 
202
    result = gpgme_op_decrypt_result(ctx);
 
203
    if (result == NULL){
 
204
      fprintf(stderr, "gpgme_op_decrypt_result failed\n");
 
205
    } else {
 
206
      fprintf(stderr, "Unsupported algorithm: %s\n",
 
207
              result->unsupported_algorithm);
 
208
      fprintf(stderr, "Wrong key usage: %d\n",
 
209
              result->wrong_key_usage);
 
210
      if(result->file_name != NULL){
 
211
        fprintf(stderr, "File name: %s\n", result->file_name);
 
212
      }
 
213
      gpgme_recipient_t recipient;
 
214
      recipient = result->recipients;
 
215
      if(recipient){
 
216
        while(recipient != NULL){
 
217
          fprintf(stderr, "Public key algorithm: %s\n",
 
218
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
 
219
          fprintf(stderr, "Key ID: %s\n", recipient->keyid);
 
220
          fprintf(stderr, "Secret key available: %s\n",
 
221
                  recipient->status == GPG_ERR_NO_SECKEY
 
222
                  ? "No" : "Yes");
 
223
          recipient = recipient->next;
 
224
        }
 
225
      }
 
226
    }
 
227
  }
 
228
  
325
229
  /* Seek back to the beginning of the GPGME plaintext data buffer */
326
 
  if(gpgme_data_seek(dh_plain, (off_t)0, SEEK_SET) == -1){
327
 
    perror("gpgme_data_seek");
 
230
  if (gpgme_data_seek(dh_plain, (off_t) 0, SEEK_SET) == -1){
 
231
    perror("pgpme_data_seek");
328
232
    plaintext_length = -1;
329
233
    goto decrypt_end;
330
234
  }
331
235
  
332
236
  *plaintext = NULL;
333
237
  while(true){
334
 
    plaintext_capacity = incbuffer(plaintext,
 
238
    plaintext_capacity = adjustbuffer(plaintext,
335
239
                                      (size_t)plaintext_length,
336
240
                                      plaintext_capacity);
337
 
    if(plaintext_capacity == 0){
338
 
        perror("incbuffer");
 
241
    if (plaintext_capacity == 0){
 
242
        perror("adjustbuffer");
339
243
        plaintext_length = -1;
340
244
        goto decrypt_end;
341
245
    }
343
247
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
344
248
                          BUFFER_SIZE);
345
249
    /* Print the data, if any */
346
 
    if(ret == 0){
 
250
    if (ret == 0){
347
251
      /* EOF */
348
252
      break;
349
253
    }
354
258
    }
355
259
    plaintext_length += ret;
356
260
  }
357
 
  
 
261
 
358
262
  if(debug){
359
263
    fprintf(stderr, "Decrypted password is: ");
360
264
    for(ssize_t i = 0; i < plaintext_length; i++){
373
277
  return plaintext_length;
374
278
}
375
279
 
376
 
static const char * safer_gnutls_strerror(int value){
377
 
  const char *ret = gnutls_strerror(value); /* Spurious warning from
378
 
                                               -Wunreachable-code */
379
 
  if(ret == NULL)
 
280
static const char * safer_gnutls_strerror (int value) {
 
281
  const char *ret = gnutls_strerror (value);
 
282
  if (ret == NULL)
380
283
    ret = "(unknown)";
381
284
  return ret;
382
285
}
387
290
  fprintf(stderr, "GnuTLS: %s", string);
388
291
}
389
292
 
390
 
static int init_gnutls_global(const char *pubkeyfilename,
391
 
                              const char *seckeyfilename){
 
293
static int init_gnutls_global(mandos_context *mc,
 
294
                              const char *pubkeyfile,
 
295
                              const char *seckeyfile){
392
296
  int ret;
393
297
  
394
298
  if(debug){
395
299
    fprintf(stderr, "Initializing GnuTLS\n");
396
300
  }
397
 
  
398
 
  ret = gnutls_global_init();
399
 
  if(ret != GNUTLS_E_SUCCESS){
400
 
    fprintf(stderr, "GnuTLS global_init: %s\n",
401
 
            safer_gnutls_strerror(ret));
 
301
 
 
302
  if ((ret = gnutls_global_init ())
 
303
      != GNUTLS_E_SUCCESS) {
 
304
    fprintf (stderr, "GnuTLS global_init: %s\n",
 
305
             safer_gnutls_strerror(ret));
402
306
    return -1;
403
307
  }
404
308
  
405
 
  if(debug){
 
309
  if (debug){
406
310
    /* "Use a log level over 10 to enable all debugging options."
407
311
     * - GnuTLS manual
408
312
     */
411
315
  }
412
316
  
413
317
  /* OpenPGP credentials */
414
 
  gnutls_certificate_allocate_credentials(&mc.cred);
415
 
  if(ret != GNUTLS_E_SUCCESS){
416
 
    fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning
417
 
                                                    from
418
 
                                                    -Wunreachable-code
419
 
                                                 */
420
 
            safer_gnutls_strerror(ret));
421
 
    gnutls_global_deinit();
 
318
  if ((ret = gnutls_certificate_allocate_credentials (&mc->cred))
 
319
      != GNUTLS_E_SUCCESS) {
 
320
    fprintf (stderr, "GnuTLS memory error: %s\n",
 
321
             safer_gnutls_strerror(ret));
 
322
    gnutls_global_deinit ();
422
323
    return -1;
423
324
  }
424
325
  
425
326
  if(debug){
426
 
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
427
 
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
428
 
            seckeyfilename);
 
327
    fprintf(stderr, "Attempting to use OpenPGP certificate %s"
 
328
            " and keyfile %s as GnuTLS credentials\n", pubkeyfile,
 
329
            seckeyfile);
429
330
  }
430
331
  
431
332
  ret = gnutls_certificate_set_openpgp_key_file
432
 
    (mc.cred, pubkeyfilename, seckeyfilename,
433
 
     GNUTLS_OPENPGP_FMT_BASE64);
434
 
  if(ret != GNUTLS_E_SUCCESS){
 
333
    (mc->cred, pubkeyfile, seckeyfile, GNUTLS_OPENPGP_FMT_BASE64);
 
334
  if (ret != GNUTLS_E_SUCCESS) {
435
335
    fprintf(stderr,
436
336
            "Error[%d] while reading the OpenPGP key pair ('%s',"
437
 
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
438
 
    fprintf(stderr, "The GnuTLS error is: %s\n",
 
337
            " '%s')\n", ret, pubkeyfile, seckeyfile);
 
338
    fprintf(stdout, "The GnuTLS error is: %s\n",
439
339
            safer_gnutls_strerror(ret));
440
340
    goto globalfail;
441
341
  }
442
342
  
443
343
  /* GnuTLS server initialization */
444
 
  ret = gnutls_dh_params_init(&mc.dh_params);
445
 
  if(ret != GNUTLS_E_SUCCESS){
446
 
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
447
 
            " %s\n", safer_gnutls_strerror(ret));
448
 
    goto globalfail;
449
 
  }
450
 
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
451
 
  if(ret != GNUTLS_E_SUCCESS){
452
 
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
453
 
            safer_gnutls_strerror(ret));
454
 
    goto globalfail;
455
 
  }
456
 
  
457
 
  gnutls_certificate_set_dh_params(mc.cred, mc.dh_params);
458
 
  
 
344
  ret = gnutls_dh_params_init(&mc->dh_params);
 
345
  if (ret != GNUTLS_E_SUCCESS) {
 
346
    fprintf (stderr, "Error in GnuTLS DH parameter initialization:"
 
347
             " %s\n", safer_gnutls_strerror(ret));
 
348
    goto globalfail;
 
349
  }
 
350
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
 
351
  if (ret != GNUTLS_E_SUCCESS) {
 
352
    fprintf (stderr, "Error in GnuTLS prime generation: %s\n",
 
353
             safer_gnutls_strerror(ret));
 
354
    goto globalfail;
 
355
  }
 
356
  
 
357
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
 
358
 
459
359
  return 0;
460
 
  
 
360
 
461
361
 globalfail:
462
 
  
463
 
  gnutls_certificate_free_credentials(mc.cred);
464
 
  gnutls_global_deinit();
465
 
  gnutls_dh_params_deinit(mc.dh_params);
 
362
 
 
363
  gnutls_certificate_free_credentials (mc->cred);
 
364
  gnutls_global_deinit ();
466
365
  return -1;
 
366
 
467
367
}
468
368
 
469
 
static int init_gnutls_session(gnutls_session_t *session){
 
369
static int init_gnutls_session(mandos_context *mc,
 
370
                               gnutls_session_t *session){
470
371
  int ret;
471
372
  /* GnuTLS session creation */
472
373
  ret = gnutls_init(session, GNUTLS_SERVER);
473
 
  if(ret != GNUTLS_E_SUCCESS){
 
374
  if (ret != GNUTLS_E_SUCCESS){
474
375
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
475
376
            safer_gnutls_strerror(ret));
476
377
  }
477
378
  
478
379
  {
479
380
    const char *err;
480
 
    ret = gnutls_priority_set_direct(*session, mc.priority, &err);
481
 
    if(ret != GNUTLS_E_SUCCESS){
 
381
    ret = gnutls_priority_set_direct(*session, mc->priority, &err);
 
382
    if (ret != GNUTLS_E_SUCCESS) {
482
383
      fprintf(stderr, "Syntax error at: %s\n", err);
483
384
      fprintf(stderr, "GnuTLS error: %s\n",
484
385
              safer_gnutls_strerror(ret));
485
 
      gnutls_deinit(*session);
 
386
      gnutls_deinit (*session);
486
387
      return -1;
487
388
    }
488
389
  }
489
390
  
490
391
  ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
491
 
                               mc.cred);
492
 
  if(ret != GNUTLS_E_SUCCESS){
 
392
                               mc->cred);
 
393
  if (ret != GNUTLS_E_SUCCESS) {
493
394
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
494
395
            safer_gnutls_strerror(ret));
495
 
    gnutls_deinit(*session);
 
396
    gnutls_deinit (*session);
496
397
    return -1;
497
398
  }
498
399
  
499
400
  /* ignore client certificate if any. */
500
 
  gnutls_certificate_server_set_request(*session,
501
 
                                        GNUTLS_CERT_IGNORE);
 
401
  gnutls_certificate_server_set_request (*session,
 
402
                                         GNUTLS_CERT_IGNORE);
502
403
  
503
 
  gnutls_dh_set_prime_bits(*session, mc.dh_bits);
 
404
  gnutls_dh_set_prime_bits (*session, mc->dh_bits);
504
405
  
505
406
  return 0;
506
407
}
512
413
/* Called when a Mandos server is found */
513
414
static int start_mandos_communication(const char *ip, uint16_t port,
514
415
                                      AvahiIfIndex if_index,
515
 
                                      int af){
 
416
                                      mandos_context *mc){
516
417
  int ret, tcp_sd;
517
 
  ssize_t sret;
518
 
  union {
519
 
    struct sockaddr_in in;
520
 
    struct sockaddr_in6 in6;
521
 
  } to;
 
418
  union { struct sockaddr in; struct sockaddr_in6 in6; } to;
522
419
  char *buffer = NULL;
523
420
  char *decrypted_buffer;
524
421
  size_t buffer_length = 0;
526
423
  ssize_t decrypted_buffer_size;
527
424
  size_t written;
528
425
  int retval = 0;
 
426
  char interface[IF_NAMESIZE];
529
427
  gnutls_session_t 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);
545
 
  if(ret != 0){
 
428
  
 
429
  ret = init_gnutls_session (mc, &session);
 
430
  if (ret != 0){
546
431
    return -1;
547
432
  }
548
433
  
549
434
  if(debug){
550
 
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
551
 
            "\n", ip, port);
 
435
    fprintf(stderr, "Setting up a tcp connection to %s, port %d\n",
 
436
            ip, port);
552
437
  }
553
438
  
554
 
  tcp_sd = socket(pf, SOCK_STREAM, 0);
555
 
  if(tcp_sd < 0){
 
439
  tcp_sd = socket(PF_INET6, SOCK_STREAM, 0);
 
440
  if(tcp_sd < 0) {
556
441
    perror("socket");
557
442
    return -1;
558
443
  }
 
444
 
 
445
  if(debug){
 
446
    if(if_indextoname((unsigned int)if_index, interface) == NULL){
 
447
      perror("if_indextoname");
 
448
      return -1;
 
449
    }
 
450
    fprintf(stderr, "Binding to interface %s\n", interface);
 
451
  }
559
452
  
560
 
  memset(&to, 0, sizeof(to));
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
 
  }
568
 
  if(ret < 0 ){
 
453
  memset(&to,0,sizeof(to));     /* Spurious warning */
 
454
  to.in6.sin6_family = AF_INET6;
 
455
  /* It would be nice to have a way to detect if we were passed an
 
456
     IPv4 address here.   Now we assume an IPv6 address. */
 
457
  ret = inet_pton(AF_INET6, ip, &to.in6.sin6_addr);
 
458
  if (ret < 0 ){
569
459
    perror("inet_pton");
570
460
    return -1;
571
461
  }
573
463
    fprintf(stderr, "Bad address: %s\n", ip);
574
464
    return -1;
575
465
  }
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
594
 
                                     -Wconversion and
595
 
                                     -Wunreachable-code */
596
 
  }
 
466
  to.in6.sin6_port = htons(port);       /* Spurious warning */
 
467
  
 
468
  to.in6.sin6_scope_id = (uint32_t)if_index;
597
469
  
598
470
  if(debug){
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){
 
471
    fprintf(stderr, "Connection to: %s, port %d\n", ip, port);
 
472
    char addrstr[INET6_ADDRSTRLEN] = "";
 
473
    if(inet_ntop(to.in6.sin6_family, &(to.in6.sin6_addr), addrstr,
 
474
                 sizeof(addrstr)) == NULL){
622
475
      perror("inet_ntop");
623
476
    } else {
624
477
      if(strcmp(addrstr, ip) != 0){
627
480
    }
628
481
  }
629
482
  
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
 
  }
635
 
  if(ret < 0){
 
483
  ret = connect(tcp_sd, &to.in, sizeof(to));
 
484
  if (ret < 0){
636
485
    perror("connect");
637
486
    return -1;
638
487
  }
639
 
  
 
488
 
640
489
  const char *out = mandos_protocol_version;
641
490
  written = 0;
642
 
  while(true){
 
491
  while (true){
643
492
    size_t out_size = strlen(out);
644
 
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
 
493
    ret = TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
645
494
                                   out_size - written));
646
 
    if(ret == -1){
 
495
    if (ret == -1){
647
496
      perror("write");
648
497
      retval = -1;
649
498
      goto mandos_end;
652
501
    if(written < out_size){
653
502
      continue;
654
503
    } else {
655
 
      if(out == mandos_protocol_version){
 
504
      if (out == mandos_protocol_version){
656
505
        written = 0;
657
506
        out = "\r\n";
658
507
      } else {
660
509
      }
661
510
    }
662
511
  }
663
 
  
 
512
 
664
513
  if(debug){
665
514
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
666
515
  }
667
516
  
668
 
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
669
 
  
670
 
  do{
671
 
    ret = gnutls_handshake(session);
672
 
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
673
 
  
674
 
  if(ret != GNUTLS_E_SUCCESS){
 
517
  gnutls_transport_set_ptr (session, (gnutls_transport_ptr_t) tcp_sd);
 
518
  
 
519
  ret = gnutls_handshake (session);
 
520
  
 
521
  if (ret != GNUTLS_E_SUCCESS){
675
522
    if(debug){
676
523
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
677
 
      gnutls_perror(ret);
 
524
      gnutls_perror (ret);
678
525
    }
679
526
    retval = -1;
680
527
    goto mandos_end;
683
530
  /* Read OpenPGP packet that contains the wanted password */
684
531
  
685
532
  if(debug){
686
 
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
 
533
    fprintf(stderr, "Retrieving pgp encrypted password from %s\n",
687
534
            ip);
688
535
  }
689
 
  
 
536
 
690
537
  while(true){
691
 
    buffer_capacity = incbuffer(&buffer, buffer_length,
 
538
    buffer_capacity = adjustbuffer(&buffer, buffer_length,
692
539
                                   buffer_capacity);
693
 
    if(buffer_capacity == 0){
694
 
      perror("incbuffer");
 
540
    if (buffer_capacity == 0){
 
541
      perror("adjustbuffer");
695
542
      retval = -1;
696
543
      goto mandos_end;
697
544
    }
698
545
    
699
 
    sret = gnutls_record_recv(session, buffer+buffer_length,
700
 
                              BUFFER_SIZE);
701
 
    if(sret == 0){
 
546
    ret = gnutls_record_recv(session, buffer+buffer_length,
 
547
                             BUFFER_SIZE);
 
548
    if (ret == 0){
702
549
      break;
703
550
    }
704
 
    if(sret < 0){
705
 
      switch(sret){
 
551
    if (ret < 0){
 
552
      switch(ret){
706
553
      case GNUTLS_E_INTERRUPTED:
707
554
      case GNUTLS_E_AGAIN:
708
555
        break;
709
556
      case GNUTLS_E_REHANDSHAKE:
710
 
        do{
711
 
          ret = gnutls_handshake(session);
712
 
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
713
 
        if(ret < 0){
 
557
        ret = gnutls_handshake (session);
 
558
        if (ret < 0){
714
559
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
715
 
          gnutls_perror(ret);
 
560
          gnutls_perror (ret);
716
561
          retval = -1;
717
562
          goto mandos_end;
718
563
        }
721
566
        fprintf(stderr, "Unknown error while reading data from"
722
567
                " encrypted session with Mandos server\n");
723
568
        retval = -1;
724
 
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
 
569
        gnutls_bye (session, GNUTLS_SHUT_RDWR);
725
570
        goto mandos_end;
726
571
      }
727
572
    } else {
728
 
      buffer_length += (size_t) sret;
 
573
      buffer_length += (size_t) ret;
729
574
    }
730
575
  }
731
576
  
733
578
    fprintf(stderr, "Closing TLS session\n");
734
579
  }
735
580
  
736
 
  gnutls_bye(session, GNUTLS_SHUT_RDWR);
 
581
  gnutls_bye (session, GNUTLS_SHUT_RDWR);
737
582
  
738
 
  if(buffer_length > 0){
 
583
  if (buffer_length > 0){
739
584
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
740
585
                                               buffer_length,
741
 
                                               &decrypted_buffer);
742
 
    if(decrypted_buffer_size >= 0){
 
586
                                               &decrypted_buffer,
 
587
                                               keydir);
 
588
    if (decrypted_buffer_size >= 0){
743
589
      written = 0;
744
590
      while(written < (size_t) decrypted_buffer_size){
745
 
        ret = (int)fwrite(decrypted_buffer + written, 1,
746
 
                          (size_t)decrypted_buffer_size - written,
747
 
                          stdout);
 
591
        ret = (int)fwrite (decrypted_buffer + written, 1,
 
592
                           (size_t)decrypted_buffer_size - written,
 
593
                           stdout);
748
594
        if(ret == 0 and ferror(stdout)){
749
595
          if(debug){
750
596
            fprintf(stderr, "Error writing encrypted data: %s\n",
759
605
    } else {
760
606
      retval = -1;
761
607
    }
762
 
  } else {
763
 
    retval = -1;
764
608
  }
765
609
  
766
610
  /* Shutdown procedure */
767
611
  
768
612
 mandos_end:
769
613
  free(buffer);
770
 
  ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
771
 
  if(ret == -1){
772
 
    perror("close");
773
 
  }
774
 
  gnutls_deinit(session);
 
614
  close(tcp_sd);
 
615
  gnutls_deinit (session);
775
616
  return retval;
776
617
}
777
618
 
778
619
static void resolve_callback(AvahiSServiceResolver *r,
779
620
                             AvahiIfIndex interface,
780
 
                             AvahiProtocol proto,
 
621
                             AVAHI_GCC_UNUSED AvahiProtocol protocol,
781
622
                             AvahiResolverEvent event,
782
623
                             const char *name,
783
624
                             const char *type,
788
629
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
789
630
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
790
631
                             flags,
791
 
                             __attribute__((unused)) void* userdata){
792
 
  assert(r);
 
632
                             void* userdata) {
 
633
  mandos_context *mc = userdata;
 
634
  assert(r);                    /* Spurious warning */
793
635
  
794
636
  /* Called whenever a service has been resolved successfully or
795
637
     timed out */
796
638
  
797
 
  switch(event){
 
639
  switch (event) {
798
640
  default:
799
641
  case AVAHI_RESOLVER_FAILURE:
800
642
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
801
643
            " of type '%s' in domain '%s': %s\n", name, type, domain,
802
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
644
            avahi_strerror(avahi_server_errno(mc->server)));
803
645
    break;
804
646
    
805
647
  case AVAHI_RESOLVER_FOUND:
807
649
      char ip[AVAHI_ADDRESS_STR_MAX];
808
650
      avahi_address_snprint(ip, sizeof(ip), address);
809
651
      if(debug){
810
 
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %"
811
 
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
812
 
                ip, (intmax_t)interface, port);
 
652
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %d) on"
 
653
                " port %d\n", name, host_name, ip, interface, port);
813
654
      }
814
 
      int ret = start_mandos_communication(ip, port, interface,
815
 
                                           avahi_proto_to_af(proto));
816
 
      if(ret == 0){
817
 
        avahi_simple_poll_quit(mc.simple_poll);
 
655
      int ret = start_mandos_communication(ip, port, interface, mc);
 
656
      if (ret == 0){
 
657
        exit(EXIT_SUCCESS);
818
658
      }
819
659
    }
820
660
  }
821
661
  avahi_s_service_resolver_free(r);
822
662
}
823
663
 
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
 
                            __attribute__((unused)) void* userdata){
834
 
  assert(b);
 
664
static void browse_callback( AvahiSServiceBrowser *b,
 
665
                             AvahiIfIndex interface,
 
666
                             AvahiProtocol protocol,
 
667
                             AvahiBrowserEvent event,
 
668
                             const char *name,
 
669
                             const char *type,
 
670
                             const char *domain,
 
671
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
 
672
                             flags,
 
673
                             void* userdata) {
 
674
  mandos_context *mc = userdata;
 
675
  assert(b);                    /* Spurious warning */
835
676
  
836
677
  /* Called whenever a new services becomes available on the LAN or
837
678
     is removed from the LAN */
838
679
  
839
 
  switch(event){
 
680
  switch (event) {
840
681
  default:
841
682
  case AVAHI_BROWSER_FAILURE:
842
683
    
843
684
    fprintf(stderr, "(Avahi browser) %s\n",
844
 
            avahi_strerror(avahi_server_errno(mc.server)));
845
 
    avahi_simple_poll_quit(mc.simple_poll);
 
685
            avahi_strerror(avahi_server_errno(mc->server)));
 
686
    avahi_simple_poll_quit(mc->simple_poll);
846
687
    return;
847
688
    
848
689
  case AVAHI_BROWSER_NEW:
851
692
       the callback function is called the Avahi server will free the
852
693
       resolver for us. */
853
694
    
854
 
    if(!(avahi_s_service_resolver_new(mc.server, interface,
 
695
    if (!(avahi_s_service_resolver_new(mc->server, interface,
855
696
                                       protocol, name, type, domain,
856
697
                                       AVAHI_PROTO_INET6, 0,
857
 
                                       resolve_callback, NULL)))
 
698
                                       resolve_callback, mc)))
858
699
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
859
 
              name, avahi_strerror(avahi_server_errno(mc.server)));
 
700
              name, avahi_strerror(avahi_server_errno(mc->server)));
860
701
    break;
861
702
    
862
703
  case AVAHI_BROWSER_REMOVE:
871
712
  }
872
713
}
873
714
 
874
 
/* stop main loop after sigterm has been called */
875
 
static void handle_sigterm(__attribute__((unused)) int sig){
876
 
  int old_errno = errno;
877
 
  avahi_simple_poll_quit(mc.simple_poll);
878
 
  errno = old_errno;
 
715
/* Combines file name and path and returns the malloced new
 
716
   string. some sane checks could/should be added */
 
717
static const char *combinepath(const char *first, const char *second){
 
718
  size_t f_len = strlen(first);
 
719
  size_t s_len = strlen(second);
 
720
  char *tmp = malloc(f_len + s_len + 2);
 
721
  if (tmp == NULL){
 
722
    return NULL;
 
723
  }
 
724
  if(f_len > 0){
 
725
    memcpy(tmp, first, f_len);  /* Spurious warning */
 
726
  }
 
727
  tmp[f_len] = '/';
 
728
  if(s_len > 0){
 
729
    memcpy(tmp + f_len + 1, second, s_len); /* Spurious warning */
 
730
  }
 
731
  tmp[f_len + 1 + s_len] = '\0';
 
732
  return tmp;
879
733
}
880
734
 
 
735
 
881
736
int main(int argc, char *argv[]){
882
 
  AvahiSServiceBrowser *sb = NULL;
883
 
  int error;
884
 
  int ret;
885
 
  intmax_t tmpmax;
886
 
  int numchars;
887
 
  int exitcode = EXIT_SUCCESS;
888
 
  const char *interface = "eth0";
889
 
  struct ifreq network;
890
 
  int sd;
891
 
  uid_t uid;
892
 
  gid_t gid;
893
 
  char *connect_to = NULL;
894
 
  char tempdir[] = "/tmp/mandosXXXXXX";
895
 
  bool tempdir_created = false;
896
 
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
897
 
  const char *seckey = PATHDIR "/" SECKEY;
898
 
  const char *pubkey = PATHDIR "/" PUBKEY;
899
 
  
900
 
  bool gnutls_initialized = false;
901
 
  bool gpgme_initialized = false;
902
 
  double delay = 2.5;
903
 
 
904
 
  struct sigaction old_sigterm_action;
905
 
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
906
 
 
907
 
  {
908
 
    struct argp_option options[] = {
909
 
      { .name = "debug", .key = 128,
910
 
        .doc = "Debug mode", .group = 3 },
911
 
      { .name = "connect", .key = 'c',
912
 
        .arg = "ADDRESS:PORT",
913
 
        .doc = "Connect directly to a specific Mandos server",
914
 
        .group = 1 },
915
 
      { .name = "interface", .key = 'i',
916
 
        .arg = "NAME",
917
 
        .doc = "Network interface that will be used to search for"
918
 
        " Mandos servers",
919
 
        .group = 1 },
920
 
      { .name = "seckey", .key = 's',
921
 
        .arg = "FILE",
922
 
        .doc = "OpenPGP secret key file base name",
923
 
        .group = 1 },
924
 
      { .name = "pubkey", .key = 'p',
925
 
        .arg = "FILE",
926
 
        .doc = "OpenPGP public key file base name",
927
 
        .group = 2 },
928
 
      { .name = "dh-bits", .key = 129,
929
 
        .arg = "BITS",
930
 
        .doc = "Bit length of the prime number used in the"
931
 
        " Diffie-Hellman key exchange",
932
 
        .group = 2 },
933
 
      { .name = "priority", .key = 130,
934
 
        .arg = "STRING",
935
 
        .doc = "GnuTLS priority string for the TLS handshake",
936
 
        .group = 1 },
937
 
      { .name = "delay", .key = 131,
938
 
        .arg = "SECONDS",
939
 
        .doc = "Maximum delay to wait for interface startup",
940
 
        .group = 2 },
941
 
      { .name = NULL }
942
 
    };
943
 
    
944
 
    error_t parse_opt(int key, char *arg,
945
 
                      struct argp_state *state){
946
 
      switch(key){
947
 
      case 128:                 /* --debug */
948
 
        debug = true;
949
 
        break;
950
 
      case 'c':                 /* --connect */
951
 
        connect_to = arg;
952
 
        break;
953
 
      case 'i':                 /* --interface */
954
 
        interface = arg;
955
 
        break;
956
 
      case 's':                 /* --seckey */
957
 
        seckey = arg;
958
 
        break;
959
 
      case 'p':                 /* --pubkey */
960
 
        pubkey = arg;
961
 
        break;
962
 
      case 129:                 /* --dh-bits */
963
 
        ret = sscanf(arg, "%" SCNdMAX "%n", &tmpmax, &numchars);
964
 
        if(ret < 1 or tmpmax != (typeof(mc.dh_bits))tmpmax
965
 
           or arg[numchars] != '\0'){
966
 
          fprintf(stderr, "Bad number of DH bits\n");
967
 
          exit(EXIT_FAILURE);
968
 
        }
969
 
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
970
 
        break;
971
 
      case 130:                 /* --priority */
972
 
        mc.priority = arg;
973
 
        break;
974
 
      case 131:                 /* --delay */
975
 
        ret = sscanf(arg, "%lf%n", &delay, &numchars);
976
 
        if(ret < 1 or arg[numchars] != '\0'){
977
 
          fprintf(stderr, "Bad delay\n");
978
 
          exit(EXIT_FAILURE);
979
 
        }
980
 
        break;
981
 
      case ARGP_KEY_ARG:
982
 
        argp_usage(state);
983
 
      case ARGP_KEY_END:
984
 
        break;
985
 
      default:
986
 
        return ARGP_ERR_UNKNOWN;
987
 
      }
988
 
      return 0;
989
 
    }
990
 
    
991
 
    struct argp argp = { .options = options, .parser = parse_opt,
992
 
                         .args_doc = "",
993
 
                         .doc = "Mandos client -- Get and decrypt"
994
 
                         " passwords from a Mandos server" };
995
 
    ret = argp_parse(&argp, argc, argv, 0, 0, NULL);
996
 
    if(ret == ARGP_ERR_UNKNOWN){
997
 
      fprintf(stderr, "Unknown error while parsing arguments\n");
998
 
      exitcode = EXIT_FAILURE;
999
 
      goto end;
1000
 
    }
1001
 
  }
1002
 
 
1003
 
  if(not debug){
1004
 
    avahi_set_log_function(empty_log);
1005
 
  }
1006
 
 
1007
 
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
1008
 
     from the signal handler */
1009
 
  /* Initialize the pseudo-RNG for Avahi */
1010
 
  srand((unsigned int) time(NULL));
1011
 
  mc.simple_poll = avahi_simple_poll_new();
1012
 
  if(mc.simple_poll == NULL){
1013
 
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
1014
 
    exitcode = EXIT_FAILURE;
1015
 
    goto end;
1016
 
  }
1017
 
 
1018
 
  sigemptyset(&sigterm_action.sa_mask);
1019
 
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
1020
 
  if(ret == -1){
1021
 
    perror("sigaddset");
1022
 
    exitcode = EXIT_FAILURE;
1023
 
    goto end;
1024
 
  }
1025
 
  ret = sigaction(SIGTERM, &sigterm_action, &old_sigterm_action);
1026
 
  if(ret == -1){
1027
 
    perror("sigaction");
1028
 
    exitcode = EXIT_FAILURE;
1029
 
    goto end;
1030
 
  }  
1031
 
 
1032
 
  
1033
 
  /* If the interface is down, bring it up */
1034
 
  if(interface[0] != '\0'){
1035
 
#ifdef __linux__
1036
 
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1037
 
       messages to mess up the prompt */
1038
 
    ret = klogctl(8, NULL, 5);
1039
 
    bool restore_loglevel = true;
1040
 
    if(ret == -1){
1041
 
      restore_loglevel = false;
1042
 
      perror("klogctl");
1043
 
    }
1044
 
#endif
1045
 
    
1046
 
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1047
 
    if(sd < 0){
1048
 
      perror("socket");
1049
 
      exitcode = EXIT_FAILURE;
1050
 
#ifdef __linux__
1051
 
      if(restore_loglevel){
1052
 
        ret = klogctl(7, NULL, 0);
1053
 
        if(ret == -1){
1054
 
          perror("klogctl");
1055
 
        }
1056
 
      }
1057
 
#endif
1058
 
      goto end;
1059
 
    }
1060
 
    strcpy(network.ifr_name, interface);
1061
 
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
1062
 
    if(ret == -1){
1063
 
      perror("ioctl SIOCGIFFLAGS");
1064
 
#ifdef __linux__
1065
 
      if(restore_loglevel){
1066
 
        ret = klogctl(7, NULL, 0);
1067
 
        if(ret == -1){
1068
 
          perror("klogctl");
1069
 
        }
1070
 
      }
1071
 
#endif
1072
 
      exitcode = EXIT_FAILURE;
1073
 
      goto end;
1074
 
    }
1075
 
    if((network.ifr_flags & IFF_UP) == 0){
1076
 
      network.ifr_flags |= IFF_UP;
1077
 
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1078
 
      if(ret == -1){
1079
 
        perror("ioctl SIOCSIFFLAGS");
1080
 
        exitcode = EXIT_FAILURE;
1081
 
#ifdef __linux__
1082
 
        if(restore_loglevel){
1083
 
          ret = klogctl(7, NULL, 0);
1084
 
          if(ret == -1){
1085
 
            perror("klogctl");
 
737
    AvahiSServiceBrowser *sb = NULL;
 
738
    int error;
 
739
    int ret;
 
740
    int exitcode = EXIT_SUCCESS;
 
741
    const char *interface = "eth0";
 
742
    struct ifreq network;
 
743
    int sd;
 
744
    uid_t uid;
 
745
    gid_t gid;
 
746
    char *connect_to = NULL;
 
747
    AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
 
748
    const char *pubkeyfile = "pubkey.txt";
 
749
    const char *seckeyfile = "seckey.txt";
 
750
    mandos_context mc = { .simple_poll = NULL, .server = NULL,
 
751
                          .dh_bits = 1024, .priority = "SECURE256"};
 
752
    bool gnutls_initalized = false;
 
753
    
 
754
    {
 
755
      struct argp_option options[] = {
 
756
        { .name = "debug", .key = 128,
 
757
          .doc = "Debug mode", .group = 3 },
 
758
        { .name = "connect", .key = 'c',
 
759
          .arg = "IP",
 
760
          .doc = "Connect directly to a sepcified mandos server",
 
761
          .group = 1 },
 
762
        { .name = "interface", .key = 'i',
 
763
          .arg = "INTERFACE",
 
764
          .doc = "Interface that Avahi will conntect through",
 
765
          .group = 1 },
 
766
        { .name = "keydir", .key = 'd',
 
767
          .arg = "KEYDIR",
 
768
          .doc = "Directory where the openpgp keyring is",
 
769
          .group = 1 },
 
770
        { .name = "seckey", .key = 's',
 
771
          .arg = "SECKEY",
 
772
          .doc = "Secret openpgp key for gnutls authentication",
 
773
          .group = 1 },
 
774
        { .name = "pubkey", .key = 'p',
 
775
          .arg = "PUBKEY",
 
776
          .doc = "Public openpgp key for gnutls authentication",
 
777
          .group = 2 },
 
778
        { .name = "dh-bits", .key = 129,
 
779
          .arg = "BITS",
 
780
          .doc = "dh-bits to use in gnutls communication",
 
781
          .group = 2 },
 
782
        { .name = "priority", .key = 130,
 
783
          .arg = "PRIORITY",
 
784
          .doc = "GNUTLS priority", .group = 1 },
 
785
        { .name = NULL }
 
786
      };
 
787
 
 
788
      
 
789
      error_t parse_opt (int key, char *arg,
 
790
                         struct argp_state *state) {
 
791
        /* Get the INPUT argument from `argp_parse', which we know is
 
792
           a pointer to our plugin list pointer. */
 
793
        switch (key) {
 
794
        case 128:
 
795
          debug = true;
 
796
          break;
 
797
        case 'c':
 
798
          connect_to = arg;
 
799
          break;
 
800
        case 'i':
 
801
          interface = arg;
 
802
          break;
 
803
        case 'd':
 
804
          keydir = arg;
 
805
          break;
 
806
        case 's':
 
807
          seckeyfile = arg;
 
808
          break;
 
809
        case 'p':
 
810
          pubkeyfile = arg;
 
811
          break;
 
812
        case 129:
 
813
          errno = 0;
 
814
          mc.dh_bits = (unsigned int) strtol(arg, NULL, 10);
 
815
          if (errno){
 
816
            perror("strtol");
 
817
            exit(EXIT_FAILURE);
1086
818
          }
 
819
          break;
 
820
        case 130:
 
821
          mc.priority = arg;
 
822
          break;
 
823
        case ARGP_KEY_ARG:
 
824
          argp_usage (state);
 
825
          break;
 
826
          case ARGP_KEY_END:
 
827
            break;
 
828
        default:
 
829
          return ARGP_ERR_UNKNOWN;
1087
830
        }
1088
 
#endif
1089
 
        goto end;
1090
 
      }
1091
 
    }
1092
 
    /* sleep checking until interface is running */
1093
 
    for(int i=0; i < delay * 4; i++){
1094
 
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1095
 
      if(ret == -1){
1096
 
        perror("ioctl SIOCGIFFLAGS");
1097
 
      } else if(network.ifr_flags & IFF_RUNNING){
1098
 
        break;
1099
 
      }
1100
 
      struct timespec sleeptime = { .tv_nsec = 250000000 };
1101
 
      ret = nanosleep(&sleeptime, NULL);
1102
 
      if(ret == -1 and errno != EINTR){
1103
 
        perror("nanosleep");
1104
 
      }
1105
 
    }
1106
 
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
1107
 
    if(ret == -1){
1108
 
      perror("close");
1109
 
    }
1110
 
#ifdef __linux__
1111
 
    if(restore_loglevel){
1112
 
      /* Restores kernel loglevel to default */
1113
 
      ret = klogctl(7, NULL, 0);
1114
 
      if(ret == -1){
1115
 
        perror("klogctl");
1116
 
      }
1117
 
    }
1118
 
#endif
1119
 
  }
1120
 
  
1121
 
  uid = getuid();
1122
 
  gid = getgid();
1123
 
  
1124
 
  errno = 0;
1125
 
  setgid(gid);
1126
 
  if(ret == -1){
1127
 
    perror("setgid");
1128
 
  }
1129
 
  
1130
 
  ret = setuid(uid);
1131
 
  if(ret == -1){
1132
 
    perror("setuid");
1133
 
  }
1134
 
  
1135
 
  ret = init_gnutls_global(pubkey, seckey);
1136
 
  if(ret == -1){
1137
 
    fprintf(stderr, "init_gnutls_global failed\n");
1138
 
    exitcode = EXIT_FAILURE;
1139
 
    goto end;
1140
 
  } else {
1141
 
    gnutls_initialized = true;
1142
 
  }
1143
 
  
1144
 
  if(mkdtemp(tempdir) == NULL){
1145
 
    perror("mkdtemp");
1146
 
    goto end;
1147
 
  }
1148
 
  tempdir_created = true;
1149
 
  
1150
 
  if(not init_gpgme(pubkey, seckey, tempdir)){
1151
 
    fprintf(stderr, "init_gpgme failed\n");
1152
 
    exitcode = EXIT_FAILURE;
1153
 
    goto end;
1154
 
  } else {
1155
 
    gpgme_initialized = true;
1156
 
  }
1157
 
  
1158
 
  if(interface[0] != '\0'){
 
831
        return 0;
 
832
      }
 
833
 
 
834
      struct argp argp = { .options = options, .parser = parse_opt,
 
835
                           .args_doc = "",
 
836
                           .doc = "Mandos client -- Get and decrypt"
 
837
                           " passwords from mandos server" };
 
838
      argp_parse (&argp, argc, argv, 0, 0, NULL);
 
839
    }
 
840
      
 
841
    pubkeyfile = combinepath(keydir, pubkeyfile);
 
842
    if (pubkeyfile == NULL){
 
843
      perror("combinepath");
 
844
      exitcode = EXIT_FAILURE;
 
845
      goto end;
 
846
    }
 
847
    
 
848
    seckeyfile = combinepath(keydir, seckeyfile);
 
849
    if (seckeyfile == NULL){
 
850
      perror("combinepath");
 
851
      goto end;
 
852
    }
 
853
 
 
854
    ret = init_gnutls_global(&mc, pubkeyfile, seckeyfile);
 
855
    if (ret == -1){
 
856
      fprintf(stderr, "init_gnutls_global\n");
 
857
      goto end;
 
858
    } else {
 
859
      gnutls_initalized = true;
 
860
    }
 
861
 
 
862
    uid = getuid();
 
863
    gid = getgid();
 
864
 
 
865
    ret = setuid(uid);
 
866
    if (ret == -1){
 
867
      perror("setuid");
 
868
    }
 
869
    
 
870
    setgid(gid);
 
871
    if (ret == -1){
 
872
      perror("setgid");
 
873
    }
 
874
    
1159
875
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1160
876
    if(if_index == 0){
1161
877
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
1162
 
      exitcode = EXIT_FAILURE;
1163
 
      goto end;
1164
 
    }
1165
 
  }
1166
 
  
1167
 
  if(connect_to != NULL){
1168
 
    /* Connect directly, do not use Zeroconf */
1169
 
    /* (Mainly meant for debugging) */
1170
 
    char *address = strrchr(connect_to, ':');
1171
 
    if(address == NULL){
1172
 
      fprintf(stderr, "No colon in address\n");
1173
 
      exitcode = EXIT_FAILURE;
1174
 
      goto end;
1175
 
    }
1176
 
    uint16_t port;
1177
 
    ret = sscanf(address+1, "%" SCNdMAX "%n", &tmpmax, &numchars);
1178
 
    if(ret < 1 or tmpmax != (uint16_t)tmpmax
1179
 
       or address[numchars+1] != '\0'){
1180
 
      fprintf(stderr, "Bad port number\n");
1181
 
      exitcode = EXIT_FAILURE;
1182
 
      goto end;
1183
 
    }
1184
 
    port = (uint16_t)tmpmax;
1185
 
    *address = '\0';
1186
 
    address = connect_to;
1187
 
    /* Colon in address indicates IPv6 */
1188
 
    int af;
1189
 
    if(strchr(address, ':') != NULL){
1190
 
      af = AF_INET6;
1191
 
    } else {
1192
 
      af = AF_INET;
1193
 
    }
1194
 
    ret = start_mandos_communication(address, port, if_index,
1195
 
                                     af);
1196
 
    if(ret < 0){
1197
 
      exitcode = EXIT_FAILURE;
1198
 
    } else {
1199
 
      exitcode = EXIT_SUCCESS;
1200
 
    }
1201
 
    goto end;
1202
 
  }
1203
 
    
1204
 
  {
1205
 
    AvahiServerConfig config;
1206
 
    /* Do not publish any local Zeroconf records */
1207
 
    avahi_server_config_init(&config);
1208
 
    config.publish_hinfo = 0;
1209
 
    config.publish_addresses = 0;
1210
 
    config.publish_workstation = 0;
1211
 
    config.publish_domain = 0;
1212
 
    
1213
 
    /* Allocate a new server */
1214
 
    mc.server = avahi_server_new(avahi_simple_poll_get
1215
 
                                 (mc.simple_poll), &config, NULL,
1216
 
                                 NULL, &error);
1217
 
    
1218
 
    /* Free the Avahi configuration data */
1219
 
    avahi_server_config_free(&config);
1220
 
  }
1221
 
  
1222
 
  /* Check if creating the Avahi server object succeeded */
1223
 
  if(mc.server == NULL){
1224
 
    fprintf(stderr, "Failed to create Avahi server: %s\n",
1225
 
            avahi_strerror(error));
1226
 
    exitcode = EXIT_FAILURE;
1227
 
    goto end;
1228
 
  }
1229
 
  
1230
 
  /* Create the Avahi service browser */
1231
 
  sb = avahi_s_service_browser_new(mc.server, if_index,
1232
 
                                   AVAHI_PROTO_INET6, "_mandos._tcp",
1233
 
                                   NULL, 0, browse_callback, NULL);
1234
 
  if(sb == NULL){
1235
 
    fprintf(stderr, "Failed to create service browser: %s\n",
1236
 
            avahi_strerror(avahi_server_errno(mc.server)));
1237
 
    exitcode = EXIT_FAILURE;
1238
 
    goto end;
1239
 
  }
1240
 
  
1241
 
  /* Run the main loop */
1242
 
  
1243
 
  if(debug){
1244
 
    fprintf(stderr, "Starting Avahi loop search\n");
1245
 
  }
1246
 
  
1247
 
  avahi_simple_poll_loop(mc.simple_poll);
1248
 
  
 
878
      exit(EXIT_FAILURE);
 
879
    }
 
880
    
 
881
    if(connect_to != NULL){
 
882
      /* Connect directly, do not use Zeroconf */
 
883
      /* (Mainly meant for debugging) */
 
884
      char *address = strrchr(connect_to, ':');
 
885
      if(address == NULL){
 
886
        fprintf(stderr, "No colon in address\n");
 
887
        exitcode = EXIT_FAILURE;
 
888
        goto end;
 
889
      }
 
890
      errno = 0;
 
891
      uint16_t port = (uint16_t) strtol(address+1, NULL, 10);
 
892
      if(errno){
 
893
        perror("Bad port number");
 
894
        exitcode = EXIT_FAILURE;
 
895
        goto end;
 
896
      }
 
897
      *address = '\0';
 
898
      address = connect_to;
 
899
      ret = start_mandos_communication(address, port, if_index, &mc);
 
900
      if(ret < 0){
 
901
        exitcode = EXIT_FAILURE;
 
902
      } else {
 
903
        exitcode = EXIT_SUCCESS;
 
904
      }
 
905
      goto end;
 
906
    }
 
907
    
 
908
    /* If the interface is down, bring it up */
 
909
    {
 
910
      sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
911
      if(sd < 0) {
 
912
        perror("socket");
 
913
        exitcode = EXIT_FAILURE;
 
914
        goto end;
 
915
      }
 
916
      strcpy(network.ifr_name, interface); /* Spurious warning */
 
917
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
918
      if(ret == -1){
 
919
        perror("ioctl SIOCGIFFLAGS");
 
920
        exitcode = EXIT_FAILURE;
 
921
        goto end;
 
922
      }
 
923
      if((network.ifr_flags & IFF_UP) == 0){
 
924
        network.ifr_flags |= IFF_UP;
 
925
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
926
        if(ret == -1){
 
927
          perror("ioctl SIOCSIFFLAGS");
 
928
          exitcode = EXIT_FAILURE;
 
929
          goto end;
 
930
        }
 
931
      }
 
932
      close(sd);
 
933
    }
 
934
    
 
935
    if (not debug){
 
936
      avahi_set_log_function(empty_log);
 
937
    }
 
938
    
 
939
    /* Initialize the pseudo-RNG for Avahi */
 
940
    srand((unsigned int) time(NULL));
 
941
    
 
942
    /* Allocate main Avahi loop object */
 
943
    mc.simple_poll = avahi_simple_poll_new();
 
944
    if (mc.simple_poll == NULL) {
 
945
        fprintf(stderr, "Avahi: Failed to create simple poll"
 
946
                " object.\n");
 
947
        exitcode = EXIT_FAILURE;
 
948
        goto end;
 
949
    }
 
950
 
 
951
    {
 
952
      AvahiServerConfig config;
 
953
      /* Do not publish any local Zeroconf records */
 
954
      avahi_server_config_init(&config);
 
955
      config.publish_hinfo = 0;
 
956
      config.publish_addresses = 0;
 
957
      config.publish_workstation = 0;
 
958
      config.publish_domain = 0;
 
959
 
 
960
      /* Allocate a new server */
 
961
      mc.server = avahi_server_new(avahi_simple_poll_get
 
962
                                   (mc.simple_poll), &config, NULL,
 
963
                                   NULL, &error);
 
964
    
 
965
      /* Free the Avahi configuration data */
 
966
      avahi_server_config_free(&config);
 
967
    }
 
968
    
 
969
    /* Check if creating the Avahi server object succeeded */
 
970
    if (mc.server == NULL) {
 
971
        fprintf(stderr, "Failed to create Avahi server: %s\n",
 
972
                avahi_strerror(error));
 
973
        exitcode = EXIT_FAILURE;
 
974
        goto end;
 
975
    }
 
976
    
 
977
    /* Create the Avahi service browser */
 
978
    sb = avahi_s_service_browser_new(mc.server, if_index,
 
979
                                     AVAHI_PROTO_INET6,
 
980
                                     "_mandos._tcp", NULL, 0,
 
981
                                     browse_callback, &mc);
 
982
    if (sb == NULL) {
 
983
        fprintf(stderr, "Failed to create service browser: %s\n",
 
984
                avahi_strerror(avahi_server_errno(mc.server)));
 
985
        exitcode = EXIT_FAILURE;
 
986
        goto end;
 
987
    }
 
988
    
 
989
    /* Run the main loop */
 
990
 
 
991
    if (debug){
 
992
      fprintf(stderr, "Starting Avahi loop search\n");
 
993
    }
 
994
    
 
995
    avahi_simple_poll_loop(mc.simple_poll);
 
996
    
1249
997
 end:
1250
 
  
1251
 
  if(debug){
1252
 
    fprintf(stderr, "%s exiting\n", argv[0]);
1253
 
  }
1254
 
  
1255
 
  /* Cleanup things */
1256
 
  if(sb != NULL)
1257
 
    avahi_s_service_browser_free(sb);
1258
 
  
1259
 
  if(mc.server != NULL)
1260
 
    avahi_server_free(mc.server);
1261
 
  
1262
 
  if(mc.simple_poll != NULL)
1263
 
    avahi_simple_poll_free(mc.simple_poll);
1264
 
  
1265
 
  if(gnutls_initialized){
1266
 
    gnutls_certificate_free_credentials(mc.cred);
1267
 
    gnutls_global_deinit();
1268
 
    gnutls_dh_params_deinit(mc.dh_params);
1269
 
  }
1270
 
  
1271
 
  if(gpgme_initialized){
1272
 
    gpgme_release(mc.ctx);
1273
 
  }
1274
 
  
1275
 
  /* Removes the temp directory used by GPGME */
1276
 
  if(tempdir_created){
1277
 
    DIR *d;
1278
 
    struct dirent *direntry;
1279
 
    d = opendir(tempdir);
1280
 
    if(d == NULL){
1281
 
      if(errno != ENOENT){
1282
 
        perror("opendir");
1283
 
      }
1284
 
    } else {
1285
 
      while(true){
1286
 
        direntry = readdir(d);
1287
 
        if(direntry == NULL){
1288
 
          break;
1289
 
        }
1290
 
        /* Skip "." and ".." */
1291
 
        if(direntry->d_name[0] == '.'
1292
 
           and (direntry->d_name[1] == '\0'
1293
 
                or (direntry->d_name[1] == '.'
1294
 
                    and direntry->d_name[2] == '\0'))){
1295
 
          continue;
1296
 
        }
1297
 
        char *fullname = NULL;
1298
 
        ret = asprintf(&fullname, "%s/%s", tempdir,
1299
 
                       direntry->d_name);
1300
 
        if(ret < 0){
1301
 
          perror("asprintf");
1302
 
          continue;
1303
 
        }
1304
 
        ret = remove(fullname);
1305
 
        if(ret == -1){
1306
 
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
1307
 
                  strerror(errno));
1308
 
        }
1309
 
        free(fullname);
1310
 
      }
1311
 
      closedir(d);
1312
 
    }
1313
 
    ret = rmdir(tempdir);
1314
 
    if(ret == -1 and errno != ENOENT){
1315
 
      perror("rmdir");
1316
 
    }
1317
 
  }
1318
 
  
1319
 
  return exitcode;
 
998
 
 
999
    if (debug){
 
1000
      fprintf(stderr, "%s exiting\n", argv[0]);
 
1001
    }
 
1002
    
 
1003
    /* Cleanup things */
 
1004
    if (sb != NULL)
 
1005
        avahi_s_service_browser_free(sb);
 
1006
    
 
1007
    if (mc.server != NULL)
 
1008
        avahi_server_free(mc.server);
 
1009
 
 
1010
    if (mc.simple_poll != NULL)
 
1011
        avahi_simple_poll_free(mc.simple_poll);
 
1012
    free(pubkeyfile);
 
1013
    free(seckeyfile);
 
1014
 
 
1015
    if (gnutls_initalized){
 
1016
      gnutls_certificate_free_credentials (mc.cred);
 
1017
      gnutls_global_deinit ();
 
1018
    }
 
1019
    
 
1020
    return exitcode;
1320
1021
}