/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/mandosclient.c

  • Committer: Teddy Hogeborn
  • Date: 2008-07-22 01:59:47 UTC
  • Revision ID: teddy@fukt.bsnet.se-20080722015947-y7o6keji020nvrhw
* Makefile (OPTIMIZE): New; optimize for size.
  (CFLAGS): Use $(OPTIMIZE).

Show diffs side-by-side

added added

removed removed

Lines of Context:
8
8
 * includes the following functions: "resolve_callback",
9
9
 * "browse_callback", and parts of "main".
10
10
 * 
11
 
 * Everything else is
12
 
 * Copyright © 2007-2008 Teddy Hogeborn & Björn Påhlsson
 
11
 * Everything else is Copyright © 2007-2008 Teddy Hogeborn and Björn
 
12
 * Påhlsson.
13
13
 * 
14
14
 * This program is free software: you can redistribute it and/or
15
15
 * modify it under the terms of the GNU General Public License as
25
25
 * along with this program.  If not, see
26
26
 * <http://www.gnu.org/licenses/>.
27
27
 * 
28
 
 * Contact the authors at <mandos@fukt.bsnet.se>.
 
28
 * Contact the authors at <https://www.fukt.bsnet.se/~belorn/> and
 
29
 * <https://www.fukt.bsnet.se/~teddy/>.
29
30
 */
30
31
 
31
 
/* Needed by GPGME, specifically gpgme_data_seek() */
 
32
#define _FORTIFY_SOURCE 2
 
33
 
32
34
#define _LARGEFILE_SOURCE
33
35
#define _FILE_OFFSET_BITS 64
34
36
 
35
 
#define _GNU_SOURCE             /* TEMP_FAILURE_RETRY() */
36
 
 
37
37
#include <stdio.h>
38
38
#include <assert.h>
39
39
#include <stdlib.h>
40
40
#include <time.h>
41
41
#include <net/if.h>             /* if_nametoindex */
42
 
#include <sys/ioctl.h>          /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
43
 
                                   SIOCSIFFLAGS */
44
 
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
45
 
                                   SIOCSIFFLAGS */
46
42
 
47
43
#include <avahi-core/core.h>
48
44
#include <avahi-core/lookup.h>
51
47
#include <avahi-common/malloc.h>
52
48
#include <avahi-common/error.h>
53
49
 
54
 
/* Mandos client part */
 
50
//mandos client part
55
51
#include <sys/types.h>          /* socket(), inet_pton() */
56
52
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
57
53
                                   struct in6_addr, inet_pton() */
64
60
#include <string.h>             /* memset */
65
61
#include <arpa/inet.h>          /* inet_pton() */
66
62
#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() */
71
 
/* GPGME */
 
63
 
 
64
// gpgme
72
65
#include <errno.h>              /* perror() */
73
66
#include <gpgme.h>
74
67
 
 
68
// getopt long
 
69
#include <getopt.h>
 
70
 
 
71
#ifndef CERT_ROOT
 
72
#define CERT_ROOT "/conf/conf.d/cryptkeyreq/"
 
73
#endif
 
74
#define CERTFILE CERT_ROOT "openpgp-client.txt"
 
75
#define KEYFILE CERT_ROOT "openpgp-client-key.txt"
75
76
#define BUFFER_SIZE 256
 
77
#define DH_BITS 1024
76
78
 
77
79
bool debug = false;
78
 
static const char *keydir = "/conf/conf.d/mandos";
79
 
const char *argp_program_version = "mandosclient 0.9";
80
 
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
81
 
static const char mandos_protocol_version[] = "1";
82
80
 
83
 
/* Used for passing in values through the Avahi callback functions */
84
81
typedef struct {
85
 
  AvahiSimplePoll *simple_poll;
86
 
  AvahiServer *server;
 
82
  gnutls_session_t session;
87
83
  gnutls_certificate_credentials_t cred;
88
 
  unsigned int dh_bits;
89
84
  gnutls_dh_params_t dh_params;
90
 
  const char *priority;
91
 
} mandos_context;
92
 
 
93
 
/* Make room in "buffer" for at least BUFFER_SIZE additional bytes.
94
 
 * "buffer_capacity" is how much is currently allocated,
95
 
 * "buffer_length" is how much is already used. */
96
 
size_t adjustbuffer(char **buffer, size_t buffer_length,
97
 
                  size_t buffer_capacity){
98
 
  if (buffer_length + BUFFER_SIZE > buffer_capacity){
99
 
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
100
 
    if (buffer == NULL){
101
 
      return 0;
102
 
    }
103
 
    buffer_capacity += BUFFER_SIZE;
104
 
  }
105
 
  return buffer_capacity;
106
 
}
107
 
 
108
 
/* 
109
 
 * Decrypt OpenPGP data using keyrings in HOMEDIR.
110
 
 * Returns -1 on error
111
 
 */
112
 
static ssize_t pgp_packet_decrypt (const char *cryptotext,
113
 
                                   size_t crypto_size,
114
 
                                   char **plaintext,
115
 
                                   const char *homedir){
 
85
} encrypted_session;
 
86
 
 
87
 
 
88
ssize_t pgp_packet_decrypt (char *packet, size_t packet_size,
 
89
                            char **new_packet, const char *homedir){
116
90
  gpgme_data_t dh_crypto, dh_plain;
117
91
  gpgme_ctx_t ctx;
118
92
  gpgme_error_t rc;
119
93
  ssize_t ret;
120
 
  size_t plaintext_capacity = 0;
121
 
  ssize_t plaintext_length = 0;
 
94
  ssize_t new_packet_capacity = 0;
 
95
  ssize_t new_packet_length = 0;
122
96
  gpgme_engine_info_t engine_info;
123
 
  
 
97
 
124
98
  if (debug){
125
 
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
 
99
    fprintf(stderr, "Trying to decrypt OpenPGP packet\n");
126
100
  }
127
101
  
128
102
  /* Init GPGME */
129
103
  gpgme_check_version(NULL);
130
 
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
131
 
  if (rc != GPG_ERR_NO_ERROR){
132
 
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
133
 
            gpgme_strsource(rc), gpgme_strerror(rc));
134
 
    return -1;
135
 
  }
 
104
  gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
136
105
  
137
 
  /* Set GPGME home directory for the OpenPGP engine only */
 
106
  /* Set GPGME home directory */
138
107
  rc = gpgme_get_engine_info (&engine_info);
139
108
  if (rc != GPG_ERR_NO_ERROR){
140
109
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
150
119
    engine_info = engine_info->next;
151
120
  }
152
121
  if(engine_info == NULL){
153
 
    fprintf(stderr, "Could not set GPGME home dir to %s\n", homedir);
 
122
    fprintf(stderr, "Could not set home dir to %s\n", homedir);
154
123
    return -1;
155
124
  }
156
125
  
157
 
  /* Create new GPGME data buffer from memory cryptotext */
158
 
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
159
 
                               0);
 
126
  /* Create new GPGME data buffer from packet buffer */
 
127
  rc = gpgme_data_new_from_mem(&dh_crypto, packet, packet_size, 0);
160
128
  if (rc != GPG_ERR_NO_ERROR){
161
129
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
162
130
            gpgme_strsource(rc), gpgme_strerror(rc));
168
136
  if (rc != GPG_ERR_NO_ERROR){
169
137
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
170
138
            gpgme_strsource(rc), gpgme_strerror(rc));
171
 
    gpgme_data_release(dh_crypto);
172
139
    return -1;
173
140
  }
174
141
  
177
144
  if (rc != GPG_ERR_NO_ERROR){
178
145
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
179
146
            gpgme_strsource(rc), gpgme_strerror(rc));
180
 
    plaintext_length = -1;
181
 
    goto decrypt_end;
 
147
    return -1;
182
148
  }
183
149
  
184
 
  /* Decrypt data from the cryptotext data buffer to the plaintext
185
 
     data buffer */
 
150
  /* Decrypt data from the FILE pointer to the plaintext data
 
151
     buffer */
186
152
  rc = gpgme_op_decrypt(ctx, dh_crypto, dh_plain);
187
153
  if (rc != GPG_ERR_NO_ERROR){
188
154
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
189
155
            gpgme_strsource(rc), gpgme_strerror(rc));
190
 
    plaintext_length = -1;
191
 
    goto decrypt_end;
 
156
    return -1;
192
157
  }
193
 
  
 
158
 
194
159
  if(debug){
195
 
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
 
160
    fprintf(stderr, "Decryption of OpenPGP packet succeeded\n");
196
161
  }
197
 
  
 
162
 
198
163
  if (debug){
199
164
    gpgme_decrypt_result_t result;
200
165
    result = gpgme_op_decrypt_result(ctx);
224
189
    }
225
190
  }
226
191
  
 
192
  /* Delete the GPGME FILE pointer cryptotext data buffer */
 
193
  gpgme_data_release(dh_crypto);
 
194
  
227
195
  /* Seek back to the beginning of the GPGME plaintext data buffer */
228
 
  if (gpgme_data_seek(dh_plain, (off_t) 0, SEEK_SET) == -1){
229
 
    perror("pgpme_data_seek");
230
 
    plaintext_length = -1;
231
 
    goto decrypt_end;
232
 
  }
233
 
  
234
 
  *plaintext = NULL;
 
196
  gpgme_data_seek(dh_plain, (off_t) 0, SEEK_SET);
 
197
 
 
198
  *new_packet = 0;
235
199
  while(true){
236
 
    plaintext_capacity = adjustbuffer(plaintext,
237
 
                                      (size_t)plaintext_length,
238
 
                                      plaintext_capacity);
239
 
    if (plaintext_capacity == 0){
240
 
        perror("adjustbuffer");
241
 
        plaintext_length = -1;
242
 
        goto decrypt_end;
 
200
    if (new_packet_length + BUFFER_SIZE > new_packet_capacity){
 
201
      *new_packet = realloc(*new_packet,
 
202
                            (unsigned int)new_packet_capacity
 
203
                            + BUFFER_SIZE);
 
204
      if (*new_packet == NULL){
 
205
        perror("realloc");
 
206
        return -1;
 
207
      }
 
208
      new_packet_capacity += BUFFER_SIZE;
243
209
    }
244
210
    
245
 
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
 
211
    ret = gpgme_data_read(dh_plain, *new_packet + new_packet_length,
246
212
                          BUFFER_SIZE);
247
213
    /* Print the data, if any */
248
214
    if (ret == 0){
249
 
      /* EOF */
250
215
      break;
251
216
    }
252
217
    if(ret < 0){
253
218
      perror("gpgme_data_read");
254
 
      plaintext_length = -1;
255
 
      goto decrypt_end;
 
219
      return -1;
256
220
    }
257
 
    plaintext_length += ret;
 
221
    new_packet_length += ret;
258
222
  }
259
223
 
260
 
  if(debug){
261
 
    fprintf(stderr, "Decrypted password is: ");
262
 
    for(ssize_t i = 0; i < plaintext_length; i++){
263
 
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
264
 
    }
265
 
    fprintf(stderr, "\n");
266
 
  }
267
 
  
268
 
 decrypt_end:
269
 
  
270
 
  /* Delete the GPGME cryptotext data buffer */
271
 
  gpgme_data_release(dh_crypto);
 
224
  /* FIXME: check characters before printing to screen so to not print
 
225
     terminal control characters */
 
226
  /*   if(debug){ */
 
227
  /*     fprintf(stderr, "decrypted password is: "); */
 
228
  /*     fwrite(*new_packet, 1, new_packet_length, stderr); */
 
229
  /*     fprintf(stderr, "\n"); */
 
230
  /*   } */
272
231
  
273
232
  /* Delete the GPGME plaintext data buffer */
274
233
  gpgme_data_release(dh_plain);
275
 
  return plaintext_length;
 
234
  return new_packet_length;
276
235
}
277
236
 
278
237
static const char * safer_gnutls_strerror (int value) {
282
241
  return ret;
283
242
}
284
243
 
285
 
/* GnuTLS log function callback */
286
 
static void debuggnutls(__attribute__((unused)) int level,
287
 
                        const char* string){
288
 
  fprintf(stderr, "GnuTLS: %s", string);
 
244
void debuggnutls(__attribute__((unused)) int level,
 
245
                 const char* string){
 
246
  fprintf(stderr, "%s", string);
289
247
}
290
248
 
291
 
static int init_gnutls_global(mandos_context *mc,
292
 
                              const char *pubkeyfile,
293
 
                              const char *seckeyfile){
 
249
int initgnutls(encrypted_session *es){
 
250
  const char *err;
294
251
  int ret;
295
252
  
296
253
  if(debug){
297
254
    fprintf(stderr, "Initializing GnuTLS\n");
298
255
  }
299
 
 
 
256
  
300
257
  if ((ret = gnutls_global_init ())
301
258
      != GNUTLS_E_SUCCESS) {
302
 
    fprintf (stderr, "GnuTLS global_init: %s\n",
303
 
             safer_gnutls_strerror(ret));
 
259
    fprintf (stderr, "global_init: %s\n", safer_gnutls_strerror(ret));
304
260
    return -1;
305
261
  }
306
 
  
 
262
 
307
263
  if (debug){
308
 
    /* "Use a log level over 10 to enable all debugging options."
309
 
     * - GnuTLS manual
310
 
     */
311
264
    gnutls_global_set_log_level(11);
312
265
    gnutls_global_set_log_function(debuggnutls);
313
266
  }
314
267
  
315
 
  /* OpenPGP credentials */
316
 
  if ((ret = gnutls_certificate_allocate_credentials (&mc->cred))
 
268
  /* openpgp credentials */
 
269
  if ((ret = gnutls_certificate_allocate_credentials (&es->cred))
317
270
      != GNUTLS_E_SUCCESS) {
318
 
    fprintf (stderr, "GnuTLS memory error: %s\n",
 
271
    fprintf (stderr, "memory error: %s\n",
319
272
             safer_gnutls_strerror(ret));
320
273
    return -1;
321
274
  }
322
275
  
323
276
  if(debug){
324
277
    fprintf(stderr, "Attempting to use OpenPGP certificate %s"
325
 
            " and keyfile %s as GnuTLS credentials\n", pubkeyfile,
326
 
            seckeyfile);
 
278
            " and keyfile %s as GnuTLS credentials\n", CERTFILE,
 
279
            KEYFILE);
327
280
  }
328
281
  
329
282
  ret = gnutls_certificate_set_openpgp_key_file
330
 
    (mc->cred, pubkeyfile, seckeyfile, GNUTLS_OPENPGP_FMT_BASE64);
 
283
    (es->cred, CERTFILE, KEYFILE, GNUTLS_OPENPGP_FMT_BASE64);
331
284
  if (ret != GNUTLS_E_SUCCESS) {
332
 
    fprintf(stderr,
333
 
            "Error[%d] while reading the OpenPGP key pair ('%s',"
334
 
            " '%s')\n", ret, pubkeyfile, seckeyfile);
335
 
    fprintf(stdout, "The GnuTLS error is: %s\n",
 
285
    fprintf
 
286
      (stderr, "Error[%d] while reading the OpenPGP key pair ('%s',"
 
287
       " '%s')\n",
 
288
       ret, CERTFILE, KEYFILE);
 
289
    fprintf(stdout, "The Error is: %s\n",
336
290
            safer_gnutls_strerror(ret));
337
291
    return -1;
338
292
  }
339
293
  
340
 
  /* GnuTLS server initialization */
341
 
  ret = gnutls_dh_params_init(&mc->dh_params);
342
 
  if (ret != GNUTLS_E_SUCCESS) {
343
 
    fprintf (stderr, "Error in GnuTLS DH parameter initialization:"
344
 
             " %s\n", safer_gnutls_strerror(ret));
345
 
    return -1;
346
 
  }
347
 
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
348
 
  if (ret != GNUTLS_E_SUCCESS) {
349
 
    fprintf (stderr, "Error in GnuTLS prime generation: %s\n",
350
 
             safer_gnutls_strerror(ret));
351
 
    return -1;
352
 
  }
353
 
  
354
 
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
355
 
 
356
 
  return 0;
357
 
}
358
 
 
359
 
static int init_gnutls_session(mandos_context *mc,
360
 
                               gnutls_session_t *session){
361
 
  int ret;
362
 
  /* GnuTLS session creation */
363
 
  ret = gnutls_init(session, GNUTLS_SERVER);
364
 
  if (ret != GNUTLS_E_SUCCESS){
 
294
  //GnuTLS server initialization
 
295
  if ((ret = gnutls_dh_params_init (&es->dh_params))
 
296
      != GNUTLS_E_SUCCESS) {
 
297
    fprintf (stderr, "Error in dh parameter initialization: %s\n",
 
298
             safer_gnutls_strerror(ret));
 
299
    return -1;
 
300
  }
 
301
  
 
302
  if ((ret = gnutls_dh_params_generate2 (es->dh_params, DH_BITS))
 
303
      != GNUTLS_E_SUCCESS) {
 
304
    fprintf (stderr, "Error in prime generation: %s\n",
 
305
             safer_gnutls_strerror(ret));
 
306
    return -1;
 
307
  }
 
308
  
 
309
  gnutls_certificate_set_dh_params (es->cred, es->dh_params);
 
310
  
 
311
  // GnuTLS session creation
 
312
  if ((ret = gnutls_init (&es->session, GNUTLS_SERVER))
 
313
      != GNUTLS_E_SUCCESS){
365
314
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
366
315
            safer_gnutls_strerror(ret));
367
316
  }
368
317
  
369
 
  {
370
 
    const char *err;
371
 
    ret = gnutls_priority_set_direct(*session, mc->priority, &err);
372
 
    if (ret != GNUTLS_E_SUCCESS) {
373
 
      fprintf(stderr, "Syntax error at: %s\n", err);
374
 
      fprintf(stderr, "GnuTLS error: %s\n",
375
 
              safer_gnutls_strerror(ret));
376
 
      return -1;
377
 
    }
 
318
  if ((ret = gnutls_priority_set_direct (es->session, "NORMAL", &err))
 
319
      != GNUTLS_E_SUCCESS) {
 
320
    fprintf(stderr, "Syntax error at: %s\n", err);
 
321
    fprintf(stderr, "GnuTLS error: %s\n",
 
322
            safer_gnutls_strerror(ret));
 
323
    return -1;
378
324
  }
379
325
  
380
 
  ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
381
 
                               mc->cred);
382
 
  if (ret != GNUTLS_E_SUCCESS) {
383
 
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
 
326
  if ((ret = gnutls_credentials_set
 
327
       (es->session, GNUTLS_CRD_CERTIFICATE, es->cred))
 
328
      != GNUTLS_E_SUCCESS) {
 
329
    fprintf(stderr, "Error setting a credentials set: %s\n",
384
330
            safer_gnutls_strerror(ret));
385
331
    return -1;
386
332
  }
387
333
  
388
334
  /* ignore client certificate if any. */
389
 
  gnutls_certificate_server_set_request (*session,
 
335
  gnutls_certificate_server_set_request (es->session,
390
336
                                         GNUTLS_CERT_IGNORE);
391
337
  
392
 
  gnutls_dh_set_prime_bits (*session, mc->dh_bits);
 
338
  gnutls_dh_set_prime_bits (es->session, DH_BITS);
393
339
  
394
340
  return 0;
395
341
}
396
342
 
397
 
/* Avahi log function callback */
398
 
static void empty_log(__attribute__((unused)) AvahiLogLevel level,
399
 
                      __attribute__((unused)) const char *txt){}
 
343
void empty_log(__attribute__((unused)) AvahiLogLevel level,
 
344
               __attribute__((unused)) const char *txt){}
400
345
 
401
 
/* Called when a Mandos server is found */
402
 
static int start_mandos_communication(const char *ip, uint16_t port,
403
 
                                      AvahiIfIndex if_index,
404
 
                                      mandos_context *mc){
 
346
int start_mandos_communication(const char *ip, uint16_t port,
 
347
                               unsigned int if_index){
405
348
  int ret, tcp_sd;
406
 
  union { struct sockaddr in; struct sockaddr_in6 in6; } to;
 
349
  struct sockaddr_in6 to;
 
350
  encrypted_session es;
407
351
  char *buffer = NULL;
408
352
  char *decrypted_buffer;
409
353
  size_t buffer_length = 0;
410
354
  size_t buffer_capacity = 0;
411
355
  ssize_t decrypted_buffer_size;
412
 
  size_t written;
 
356
  size_t written = 0;
413
357
  int retval = 0;
414
358
  char interface[IF_NAMESIZE];
415
 
  gnutls_session_t session;
416
 
  
417
 
  ret = init_gnutls_session (mc, &session);
418
 
  if (ret != 0){
419
 
    return -1;
420
 
  }
421
359
  
422
360
  if(debug){
423
 
    fprintf(stderr, "Setting up a tcp connection to %s, port %d\n",
424
 
            ip, port);
 
361
    fprintf(stderr, "Setting up a tcp connection to %s\n", ip);
425
362
  }
426
363
  
427
364
  tcp_sd = socket(PF_INET6, SOCK_STREAM, 0);
429
366
    perror("socket");
430
367
    return -1;
431
368
  }
432
 
 
433
 
  if(debug){
434
 
    if(if_indextoname((unsigned int)if_index, interface) == NULL){
 
369
  
 
370
  if(if_indextoname(if_index, interface) == NULL){
 
371
    if(debug){
435
372
      perror("if_indextoname");
436
 
      return -1;
437
373
    }
 
374
    return -1;
 
375
  }
 
376
  
 
377
  if(debug){
438
378
    fprintf(stderr, "Binding to interface %s\n", interface);
439
379
  }
440
380
  
441
381
  memset(&to,0,sizeof(to));     /* Spurious warning */
442
 
  to.in6.sin6_family = AF_INET6;
443
 
  /* It would be nice to have a way to detect if we were passed an
444
 
     IPv4 address here.   Now we assume an IPv6 address. */
445
 
  ret = inet_pton(AF_INET6, ip, &to.in6.sin6_addr);
 
382
  to.sin6_family = AF_INET6;
 
383
  ret = inet_pton(AF_INET6, ip, &to.sin6_addr);
446
384
  if (ret < 0 ){
447
385
    perror("inet_pton");
448
386
    return -1;
449
 
  }
 
387
  }  
450
388
  if(ret == 0){
451
389
    fprintf(stderr, "Bad address: %s\n", ip);
452
390
    return -1;
453
391
  }
454
 
  to.in6.sin6_port = htons(port);       /* Spurious warning */
 
392
  to.sin6_port = htons(port);   /* Spurious warning */
455
393
  
456
 
  to.in6.sin6_scope_id = (uint32_t)if_index;
 
394
  to.sin6_scope_id = (uint32_t)if_index;
457
395
  
458
396
  if(debug){
459
 
    fprintf(stderr, "Connection to: %s, port %d\n", ip, port);
460
 
    char addrstr[INET6_ADDRSTRLEN] = "";
461
 
    if(inet_ntop(to.in6.sin6_family, &(to.in6.sin6_addr), addrstr,
462
 
                 sizeof(addrstr)) == NULL){
463
 
      perror("inet_ntop");
464
 
    } else {
465
 
      if(strcmp(addrstr, ip) != 0){
466
 
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
467
 
      }
468
 
    }
 
397
    fprintf(stderr, "Connection to: %s\n", ip);
469
398
  }
470
399
  
471
 
  ret = connect(tcp_sd, &to.in, sizeof(to));
 
400
  ret = connect(tcp_sd, (struct sockaddr *) &to, sizeof(to));
472
401
  if (ret < 0){
473
402
    perror("connect");
474
403
    return -1;
475
404
  }
476
 
 
477
 
  const char *out = mandos_protocol_version;
478
 
  written = 0;
479
 
  while (true){
480
 
    size_t out_size = strlen(out);
481
 
    ret = TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
482
 
                                   out_size - written));
483
 
    if (ret == -1){
484
 
      perror("write");
485
 
      retval = -1;
486
 
      goto mandos_end;
487
 
    }
488
 
    written += (size_t)ret;
489
 
    if(written < out_size){
490
 
      continue;
491
 
    } else {
492
 
      if (out == mandos_protocol_version){
493
 
        written = 0;
494
 
        out = "\r\n";
495
 
      } else {
496
 
        break;
497
 
      }
498
 
    }
 
405
  
 
406
  ret = initgnutls (&es);
 
407
  if (ret != 0){
 
408
    retval = -1;
 
409
    return -1;
499
410
  }
500
 
 
 
411
  
 
412
  gnutls_transport_set_ptr (es.session,
 
413
                            (gnutls_transport_ptr_t) tcp_sd);
 
414
  
501
415
  if(debug){
502
416
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
503
417
  }
504
418
  
505
 
  gnutls_transport_set_ptr (session, (gnutls_transport_ptr_t) tcp_sd);
506
 
  
507
 
  ret = gnutls_handshake (session);
 
419
  ret = gnutls_handshake (es.session);
508
420
  
509
421
  if (ret != GNUTLS_E_SUCCESS){
510
 
    if(debug){
511
 
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
512
 
      gnutls_perror (ret);
513
 
    }
 
422
    fprintf(stderr, "\n*** Handshake failed ***\n");
 
423
    gnutls_perror (ret);
514
424
    retval = -1;
515
 
    goto mandos_end;
 
425
    goto exit;
516
426
  }
517
427
  
518
 
  /* Read OpenPGP packet that contains the wanted password */
 
428
  //Retrieve OpenPGP packet that contains the wanted password
519
429
  
520
430
  if(debug){
521
431
    fprintf(stderr, "Retrieving pgp encrypted password from %s\n",
523
433
  }
524
434
 
525
435
  while(true){
526
 
    buffer_capacity = adjustbuffer(&buffer, buffer_length,
527
 
                                   buffer_capacity);
528
 
    if (buffer_capacity == 0){
529
 
      perror("adjustbuffer");
530
 
      retval = -1;
531
 
      goto mandos_end;
 
436
    if (buffer_length + BUFFER_SIZE > buffer_capacity){
 
437
      buffer = realloc(buffer, buffer_capacity + BUFFER_SIZE);
 
438
      if (buffer == NULL){
 
439
        perror("realloc");
 
440
        goto exit;
 
441
      }
 
442
      buffer_capacity += BUFFER_SIZE;
532
443
    }
533
444
    
534
 
    ret = gnutls_record_recv(session, buffer+buffer_length,
535
 
                             BUFFER_SIZE);
 
445
    ret = gnutls_record_recv
 
446
      (es.session, buffer+buffer_length, BUFFER_SIZE);
536
447
    if (ret == 0){
537
448
      break;
538
449
    }
542
453
      case GNUTLS_E_AGAIN:
543
454
        break;
544
455
      case GNUTLS_E_REHANDSHAKE:
545
 
        ret = gnutls_handshake (session);
 
456
        ret = gnutls_handshake (es.session);
546
457
        if (ret < 0){
547
 
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
 
458
          fprintf(stderr, "\n*** Handshake failed ***\n");
548
459
          gnutls_perror (ret);
549
460
          retval = -1;
550
 
          goto mandos_end;
 
461
          goto exit;
551
462
        }
552
463
        break;
553
464
      default:
554
465
        fprintf(stderr, "Unknown error while reading data from"
555
 
                " encrypted session with Mandos server\n");
 
466
                " encrypted session with mandos server\n");
556
467
        retval = -1;
557
 
        gnutls_bye (session, GNUTLS_SHUT_RDWR);
558
 
        goto mandos_end;
 
468
        gnutls_bye (es.session, GNUTLS_SHUT_RDWR);
 
469
        goto exit;
559
470
      }
560
471
    } else {
561
472
      buffer_length += (size_t) ret;
562
473
    }
563
474
  }
564
475
  
565
 
  if(debug){
566
 
    fprintf(stderr, "Closing TLS session\n");
567
 
  }
568
 
  
569
 
  gnutls_bye (session, GNUTLS_SHUT_RDWR);
570
 
  
571
476
  if (buffer_length > 0){
572
477
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
573
478
                                               buffer_length,
574
479
                                               &decrypted_buffer,
575
 
                                               keydir);
 
480
                                               CERT_ROOT);
576
481
    if (decrypted_buffer_size >= 0){
577
 
      written = 0;
578
 
      while(written < (size_t) decrypted_buffer_size){
 
482
      while(written < decrypted_buffer_size){
579
483
        ret = (int)fwrite (decrypted_buffer + written, 1,
580
484
                           (size_t)decrypted_buffer_size - written,
581
485
                           stdout);
594
498
      retval = -1;
595
499
    }
596
500
  }
597
 
  
598
 
  /* Shutdown procedure */
599
 
  
600
 
 mandos_end:
 
501
 
 
502
  //shutdown procedure
 
503
 
 
504
  if(debug){
 
505
    fprintf(stderr, "Closing TLS session\n");
 
506
  }
 
507
 
601
508
  free(buffer);
 
509
  gnutls_bye (es.session, GNUTLS_SHUT_RDWR);
 
510
 exit:
602
511
  close(tcp_sd);
603
 
  gnutls_deinit (session);
604
 
  gnutls_certificate_free_credentials (mc->cred);
 
512
  gnutls_deinit (es.session);
 
513
  gnutls_certificate_free_credentials (es.cred);
605
514
  gnutls_global_deinit ();
606
515
  return retval;
607
516
}
608
517
 
609
 
static void resolve_callback(AvahiSServiceResolver *r,
610
 
                             AvahiIfIndex interface,
611
 
                             AVAHI_GCC_UNUSED AvahiProtocol protocol,
612
 
                             AvahiResolverEvent event,
613
 
                             const char *name,
614
 
                             const char *type,
615
 
                             const char *domain,
616
 
                             const char *host_name,
617
 
                             const AvahiAddress *address,
618
 
                             uint16_t port,
619
 
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
620
 
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
621
 
                             flags,
622
 
                             void* userdata) {
623
 
  mandos_context *mc = userdata;
 
518
static AvahiSimplePoll *simple_poll = NULL;
 
519
static AvahiServer *server = NULL;
 
520
 
 
521
static void resolve_callback(
 
522
    AvahiSServiceResolver *r,
 
523
    AvahiIfIndex interface,
 
524
    AVAHI_GCC_UNUSED AvahiProtocol protocol,
 
525
    AvahiResolverEvent event,
 
526
    const char *name,
 
527
    const char *type,
 
528
    const char *domain,
 
529
    const char *host_name,
 
530
    const AvahiAddress *address,
 
531
    uint16_t port,
 
532
    AVAHI_GCC_UNUSED AvahiStringList *txt,
 
533
    AVAHI_GCC_UNUSED AvahiLookupResultFlags flags,
 
534
    AVAHI_GCC_UNUSED void* userdata) {
 
535
    
624
536
  assert(r);                    /* Spurious warning */
625
537
  
626
538
  /* Called whenever a service has been resolved successfully or
629
541
  switch (event) {
630
542
  default:
631
543
  case AVAHI_RESOLVER_FAILURE:
632
 
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
633
 
            " of type '%s' in domain '%s': %s\n", name, type, domain,
634
 
            avahi_strerror(avahi_server_errno(mc->server)));
 
544
    fprintf(stderr, "(Resolver) Failed to resolve service '%s' of"
 
545
            " type '%s' in domain '%s': %s\n", name, type, domain,
 
546
            avahi_strerror(avahi_server_errno(server)));
635
547
    break;
636
548
    
637
549
  case AVAHI_RESOLVER_FOUND:
639
551
      char ip[AVAHI_ADDRESS_STR_MAX];
640
552
      avahi_address_snprint(ip, sizeof(ip), address);
641
553
      if(debug){
642
 
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %d) on"
643
 
                " port %d\n", name, host_name, ip, interface, port);
 
554
        fprintf(stderr, "Mandos server found on %s (%s) on port %d\n",
 
555
                host_name, ip, port);
644
556
      }
645
 
      int ret = start_mandos_communication(ip, port, interface, mc);
 
557
      int ret = start_mandos_communication(ip, port,
 
558
                                           (unsigned int) interface);
646
559
      if (ret == 0){
647
560
        exit(EXIT_SUCCESS);
 
561
      } else {
 
562
        exit(EXIT_FAILURE);
648
563
      }
649
564
    }
650
565
  }
651
566
  avahi_s_service_resolver_free(r);
652
567
}
653
568
 
654
 
static void browse_callback( AvahiSServiceBrowser *b,
655
 
                             AvahiIfIndex interface,
656
 
                             AvahiProtocol protocol,
657
 
                             AvahiBrowserEvent event,
658
 
                             const char *name,
659
 
                             const char *type,
660
 
                             const char *domain,
661
 
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
662
 
                             flags,
663
 
                             void* userdata) {
664
 
  mandos_context *mc = userdata;
665
 
  assert(b);                    /* Spurious warning */
666
 
  
667
 
  /* Called whenever a new services becomes available on the LAN or
668
 
     is removed from the LAN */
669
 
  
670
 
  switch (event) {
671
 
  default:
672
 
  case AVAHI_BROWSER_FAILURE:
673
 
    
674
 
    fprintf(stderr, "(Avahi browser) %s\n",
675
 
            avahi_strerror(avahi_server_errno(mc->server)));
676
 
    avahi_simple_poll_quit(mc->simple_poll);
677
 
    return;
678
 
    
679
 
  case AVAHI_BROWSER_NEW:
680
 
    /* We ignore the returned Avahi resolver object. In the callback
681
 
       function we free it. If the Avahi server is terminated before
682
 
       the callback function is called the Avahi server will free the
683
 
       resolver for us. */
684
 
    
685
 
    if (!(avahi_s_service_resolver_new(mc->server, interface,
686
 
                                       protocol, name, type, domain,
687
 
                                       AVAHI_PROTO_INET6, 0,
688
 
                                       resolve_callback, mc)))
689
 
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
690
 
              name, avahi_strerror(avahi_server_errno(mc->server)));
691
 
    break;
692
 
    
693
 
  case AVAHI_BROWSER_REMOVE:
694
 
    break;
695
 
    
696
 
  case AVAHI_BROWSER_ALL_FOR_NOW:
697
 
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
698
 
    if(debug){
699
 
      fprintf(stderr, "No Mandos server found, still searching...\n");
 
569
static void browse_callback(
 
570
    AvahiSServiceBrowser *b,
 
571
    AvahiIfIndex interface,
 
572
    AvahiProtocol protocol,
 
573
    AvahiBrowserEvent event,
 
574
    const char *name,
 
575
    const char *type,
 
576
    const char *domain,
 
577
    AVAHI_GCC_UNUSED AvahiLookupResultFlags flags,
 
578
    void* userdata) {
 
579
    
 
580
    AvahiServer *s = userdata;
 
581
    assert(b);                  /* Spurious warning */
 
582
    
 
583
    /* Called whenever a new services becomes available on the LAN or
 
584
       is removed from the LAN */
 
585
    
 
586
    switch (event) {
 
587
    default:
 
588
    case AVAHI_BROWSER_FAILURE:
 
589
      
 
590
      fprintf(stderr, "(Browser) %s\n",
 
591
              avahi_strerror(avahi_server_errno(server)));
 
592
      avahi_simple_poll_quit(simple_poll);
 
593
      return;
 
594
      
 
595
    case AVAHI_BROWSER_NEW:
 
596
      /* We ignore the returned resolver object. In the callback
 
597
         function we free it. If the server is terminated before
 
598
         the callback function is called the server will free
 
599
         the resolver for us. */
 
600
      
 
601
      if (!(avahi_s_service_resolver_new(s, interface, protocol, name,
 
602
                                         type, domain,
 
603
                                         AVAHI_PROTO_INET6, 0,
 
604
                                         resolve_callback, s)))
 
605
        fprintf(stderr, "Failed to resolve service '%s': %s\n", name,
 
606
                avahi_strerror(avahi_server_errno(s)));
 
607
      break;
 
608
      
 
609
    case AVAHI_BROWSER_REMOVE:
 
610
      break;
 
611
      
 
612
    case AVAHI_BROWSER_ALL_FOR_NOW:
 
613
    case AVAHI_BROWSER_CACHE_EXHAUSTED:
 
614
      break;
700
615
    }
701
 
    break;
702
 
  }
703
 
}
704
 
 
705
 
/* Combines file name and path and returns the malloced new
706
 
   string. some sane checks could/should be added */
707
 
static const char *combinepath(const char *first, const char *second){
708
 
  size_t f_len = strlen(first);
709
 
  size_t s_len = strlen(second);
710
 
  char *tmp = malloc(f_len + s_len + 2);
711
 
  if (tmp == NULL){
712
 
    return NULL;
713
 
  }
714
 
  if(f_len > 0){
715
 
    memcpy(tmp, first, f_len);  /* Spurious warning */
716
 
  }
717
 
  tmp[f_len] = '/';
718
 
  if(s_len > 0){
719
 
    memcpy(tmp + f_len + 1, second, s_len); /* Spurious warning */
720
 
  }
721
 
  tmp[f_len + 1 + s_len] = '\0';
722
 
  return tmp;
723
 
}
724
 
 
725
 
 
726
 
int main(int argc, char *argv[]){
 
616
}
 
617
 
 
618
int main(AVAHI_GCC_UNUSED int argc, AVAHI_GCC_UNUSED char*argv[]) {
 
619
    AvahiServerConfig config;
727
620
    AvahiSServiceBrowser *sb = NULL;
728
621
    int error;
729
622
    int ret;
730
 
    int exitcode = EXIT_SUCCESS;
 
623
    int returncode = EXIT_SUCCESS;
731
624
    const char *interface = "eth0";
732
 
    struct ifreq network;
733
 
    int sd;
734
 
    uid_t uid;
735
 
    gid_t gid;
736
 
    char *connect_to = NULL;
737
 
    AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
738
 
    const char *pubkeyfile = "pubkey.txt";
739
 
    const char *seckeyfile = "seckey.txt";
740
 
    mandos_context mc = { .simple_poll = NULL, .server = NULL,
741
 
                          .dh_bits = 1024, .priority = "SECURE256"};
742
 
    
743
 
    {
744
 
      struct argp_option options[] = {
745
 
        { .name = "debug", .key = 128,
746
 
          .doc = "Debug mode", .group = 3 },
747
 
        { .name = "connect", .key = 'c',
748
 
          .arg = "IP",
749
 
          .doc = "Connect directly to a sepcified mandos server",
750
 
          .group = 1 },
751
 
        { .name = "interface", .key = 'i',
752
 
          .arg = "INTERFACE",
753
 
          .doc = "Interface that Avahi will conntect through",
754
 
          .group = 1 },
755
 
        { .name = "keydir", .key = 'd',
756
 
          .arg = "KEYDIR",
757
 
          .doc = "Directory where the openpgp keyring is",
758
 
          .group = 1 },
759
 
        { .name = "seckey", .key = 's',
760
 
          .arg = "SECKEY",
761
 
          .doc = "Secret openpgp key for gnutls authentication",
762
 
          .group = 1 },
763
 
        { .name = "pubkey", .key = 'p',
764
 
          .arg = "PUBKEY",
765
 
          .doc = "Public openpgp key for gnutls authentication",
766
 
          .group = 2 },
767
 
        { .name = "dh-bits", .key = 129,
768
 
          .arg = "BITS",
769
 
          .doc = "dh-bits to use in gnutls communication",
770
 
          .group = 2 },
771
 
        { .name = "priority", .key = 130,
772
 
          .arg = "PRIORITY",
773
 
          .doc = "GNUTLS priority", .group = 1 },
774
 
        { .name = NULL }
775
 
      };
776
 
 
777
 
      
778
 
      error_t parse_opt (int key, char *arg,
779
 
                         struct argp_state *state) {
780
 
        /* Get the INPUT argument from `argp_parse', which we know is
781
 
           a pointer to our plugin list pointer. */
782
 
        switch (key) {
783
 
        case 128:
784
 
          debug = true;
785
 
          break;
786
 
        case 'c':
787
 
          connect_to = arg;
788
 
          break;
789
 
        case 'i':
790
 
          interface = arg;
791
 
          break;
792
 
        case 'd':
793
 
          keydir = arg;
794
 
          break;
795
 
        case 's':
796
 
          seckeyfile = arg;
797
 
          break;
798
 
        case 'p':
799
 
          pubkeyfile = arg;
800
 
          break;
801
 
        case 129:
802
 
          errno = 0;
803
 
          mc.dh_bits = (unsigned int) strtol(arg, NULL, 10);
804
 
          if (errno){
805
 
            perror("strtol");
806
 
            exit(EXIT_FAILURE);
807
 
          }
808
 
          break;
809
 
        case 130:
810
 
          mc.priority = arg;
811
 
          break;
812
 
        case ARGP_KEY_ARG:
813
 
          argp_usage (state);
814
 
          break;
815
 
          case ARGP_KEY_END:
816
 
            break;
817
 
        default:
818
 
          return ARGP_ERR_UNKNOWN;
819
 
        }
820
 
        return 0;
821
 
      }
822
 
 
823
 
      struct argp argp = { .options = options, .parser = parse_opt,
824
 
                           .args_doc = "",
825
 
                           .doc = "Mandos client -- Get and decrypt"
826
 
                           " passwords from mandos server" };
827
 
      argp_parse (&argp, argc, argv, 0, 0, NULL);
828
 
    }
829
 
      
830
 
    pubkeyfile = combinepath(keydir, pubkeyfile);
831
 
    if (pubkeyfile == NULL){
832
 
      perror("combinepath");
833
 
      exitcode = EXIT_FAILURE;
834
 
      goto end;
835
 
    }
836
 
    
837
 
    seckeyfile = combinepath(keydir, seckeyfile);
838
 
    if (seckeyfile == NULL){
839
 
      perror("combinepath");
840
 
      goto end;
841
 
    }
842
 
 
843
 
    ret = init_gnutls_global(&mc, pubkeyfile, seckeyfile);
844
 
    if (ret == -1){
845
 
      fprintf(stderr, "init_gnutls_global\n");
846
 
      goto end;
847
 
    }
848
 
 
849
 
    uid = getuid();
850
 
    gid = getgid();
851
 
 
852
 
    ret = setuid(uid);
853
 
    if (ret == -1){
854
 
      perror("setuid");
855
 
    }
856
 
    
857
 
    setgid(gid);
858
 
    if (ret == -1){
859
 
      perror("setgid");
860
 
    }
861
 
    
862
 
    if_index = (AvahiIfIndex) if_nametoindex(interface);
863
 
    if(if_index == 0){
864
 
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
865
 
      exit(EXIT_FAILURE);
866
 
    }
867
 
    
868
 
    if(connect_to != NULL){
869
 
      /* Connect directly, do not use Zeroconf */
870
 
      /* (Mainly meant for debugging) */
871
 
      char *address = strrchr(connect_to, ':');
872
 
      if(address == NULL){
873
 
        fprintf(stderr, "No colon in address\n");
874
 
        exitcode = EXIT_FAILURE;
875
 
        goto end;
876
 
      }
877
 
      errno = 0;
878
 
      uint16_t port = (uint16_t) strtol(address+1, NULL, 10);
879
 
      if(errno){
880
 
        perror("Bad port number");
881
 
        exitcode = EXIT_FAILURE;
882
 
        goto end;
883
 
      }
884
 
      *address = '\0';
885
 
      address = connect_to;
886
 
      ret = start_mandos_communication(address, port, if_index, &mc);
887
 
      if(ret < 0){
888
 
        exitcode = EXIT_FAILURE;
889
 
      } else {
890
 
        exitcode = EXIT_SUCCESS;
891
 
      }
892
 
      goto end;
893
 
    }
894
 
    
895
 
    /* If the interface is down, bring it up */
896
 
    {
897
 
      sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
898
 
      if(sd < 0) {
899
 
        perror("socket");
900
 
        exitcode = EXIT_FAILURE;
901
 
        goto end;
902
 
      }
903
 
      strcpy(network.ifr_name, interface); /* Spurious warning */
904
 
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
905
 
      if(ret == -1){
906
 
        perror("ioctl SIOCGIFFLAGS");
907
 
        exitcode = EXIT_FAILURE;
908
 
        goto end;
909
 
      }
910
 
      if((network.ifr_flags & IFF_UP) == 0){
911
 
        network.ifr_flags |= IFF_UP;
912
 
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
913
 
        if(ret == -1){
914
 
          perror("ioctl SIOCSIFFLAGS");
915
 
          exitcode = EXIT_FAILURE;
916
 
          goto end;
917
 
        }
918
 
      }
919
 
      close(sd);
 
625
    
 
626
    while (true){
 
627
      static struct option long_options[] = {
 
628
        {"debug", no_argument, (int *)&debug, 1},
 
629
        {"interface", required_argument, 0, 'i'},
 
630
        {0, 0, 0, 0} };
 
631
      
 
632
      int option_index = 0;
 
633
      ret = getopt_long (argc, argv, "i:", long_options,
 
634
                         &option_index);
 
635
      
 
636
      if (ret == -1){
 
637
        break;
 
638
      }
 
639
      
 
640
      switch(ret){
 
641
      case 0:
 
642
        break;
 
643
      case 'i':
 
644
        interface = optarg;
 
645
        break;
 
646
      default:
 
647
        exit(EXIT_FAILURE);
 
648
      }
920
649
    }
921
650
    
922
651
    if (not debug){
923
652
      avahi_set_log_function(empty_log);
924
653
    }
925
654
    
926
 
    /* Initialize the pseudo-RNG for Avahi */
 
655
    /* Initialize the psuedo-RNG */
927
656
    srand((unsigned int) time(NULL));
928
 
    
929
 
    /* Allocate main Avahi loop object */
930
 
    mc.simple_poll = avahi_simple_poll_new();
931
 
    if (mc.simple_poll == NULL) {
932
 
        fprintf(stderr, "Avahi: Failed to create simple poll"
933
 
                " object.\n");
934
 
        exitcode = EXIT_FAILURE;
935
 
        goto end;
936
 
    }
937
 
 
938
 
    {
939
 
      AvahiServerConfig config;
940
 
      /* Do not publish any local Zeroconf records */
941
 
      avahi_server_config_init(&config);
942
 
      config.publish_hinfo = 0;
943
 
      config.publish_addresses = 0;
944
 
      config.publish_workstation = 0;
945
 
      config.publish_domain = 0;
946
 
 
947
 
      /* Allocate a new server */
948
 
      mc.server = avahi_server_new(avahi_simple_poll_get
949
 
                                   (mc.simple_poll), &config, NULL,
950
 
                                   NULL, &error);
951
 
    
952
 
      /* Free the Avahi configuration data */
953
 
      avahi_server_config_free(&config);
954
 
    }
955
 
    
956
 
    /* Check if creating the Avahi server object succeeded */
957
 
    if (mc.server == NULL) {
958
 
        fprintf(stderr, "Failed to create Avahi server: %s\n",
 
657
 
 
658
    /* Allocate main loop object */
 
659
    if (!(simple_poll = avahi_simple_poll_new())) {
 
660
        fprintf(stderr, "Failed to create simple poll object.\n");
 
661
        
 
662
        goto exit;
 
663
    }
 
664
 
 
665
    /* Do not publish any local records */
 
666
    avahi_server_config_init(&config);
 
667
    config.publish_hinfo = 0;
 
668
    config.publish_addresses = 0;
 
669
    config.publish_workstation = 0;
 
670
    config.publish_domain = 0;
 
671
 
 
672
    /* Allocate a new server */
 
673
    server = avahi_server_new(avahi_simple_poll_get(simple_poll),
 
674
                              &config, NULL, NULL, &error);
 
675
 
 
676
    /* Free the configuration data */
 
677
    avahi_server_config_free(&config);
 
678
 
 
679
    /* Check if creating the server object succeeded */
 
680
    if (!server) {
 
681
        fprintf(stderr, "Failed to create server: %s\n",
959
682
                avahi_strerror(error));
960
 
        exitcode = EXIT_FAILURE;
961
 
        goto end;
 
683
        returncode = EXIT_FAILURE;
 
684
        goto exit;
962
685
    }
963
686
    
964
 
    /* Create the Avahi service browser */
965
 
    sb = avahi_s_service_browser_new(mc.server, if_index,
 
687
    /* Create the service browser */
 
688
    sb = avahi_s_service_browser_new(server,
 
689
                                     (AvahiIfIndex)
 
690
                                     if_nametoindex(interface),
966
691
                                     AVAHI_PROTO_INET6,
967
692
                                     "_mandos._tcp", NULL, 0,
968
 
                                     browse_callback, &mc);
969
 
    if (sb == NULL) {
 
693
                                     browse_callback, server);
 
694
    if (!sb) {
970
695
        fprintf(stderr, "Failed to create service browser: %s\n",
971
 
                avahi_strerror(avahi_server_errno(mc.server)));
972
 
        exitcode = EXIT_FAILURE;
973
 
        goto end;
 
696
                avahi_strerror(avahi_server_errno(server)));
 
697
        returncode = EXIT_FAILURE;
 
698
        goto exit;
974
699
    }
975
700
    
976
701
    /* Run the main loop */
977
702
 
978
703
    if (debug){
979
 
      fprintf(stderr, "Starting Avahi loop search\n");
 
704
      fprintf(stderr, "Starting avahi loop search\n");
980
705
    }
981
706
    
982
 
    avahi_simple_poll_loop(mc.simple_poll);
 
707
    avahi_simple_poll_loop(simple_poll);
983
708
    
984
 
 end:
 
709
 exit:
985
710
 
986
711
    if (debug){
987
712
      fprintf(stderr, "%s exiting\n", argv[0]);
988
713
    }
989
714
    
990
715
    /* Cleanup things */
991
 
    if (sb != NULL)
 
716
    if (sb)
992
717
        avahi_s_service_browser_free(sb);
993
718
    
994
 
    if (mc.server != NULL)
995
 
        avahi_server_free(mc.server);
996
 
 
997
 
    if (mc.simple_poll != NULL)
998
 
        avahi_simple_poll_free(mc.simple_poll);
999
 
    free(pubkeyfile);
1000
 
    free(seckeyfile);
1001
 
    
1002
 
    return exitcode;
 
719
    if (server)
 
720
        avahi_server_free(server);
 
721
 
 
722
    if (simple_poll)
 
723
        avahi_simple_poll_free(simple_poll);
 
724
 
 
725
    return returncode;
1003
726
}