/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

merge commit

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-2011 Teddy Hogeborn
13
 
 * Copyright © 2008-2011 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
30
29
 */
31
30
 
32
31
/* Needed by GPGME, specifically gpgme_data_seek() */
33
 
#ifndef _LARGEFILE_SOURCE
34
32
#define _LARGEFILE_SOURCE
35
 
#endif
36
 
#ifndef _FILE_OFFSET_BITS
37
33
#define _FILE_OFFSET_BITS 64
38
 
#endif
39
 
 
40
 
#define _GNU_SOURCE             /* TEMP_FAILURE_RETRY(), asprintf() */
41
 
 
42
 
#include <stdio.h>              /* fprintf(), stderr, fwrite(),
43
 
                                   stdout, ferror(), remove() */
44
 
#include <stdint.h>             /* uint16_t, uint32_t */
45
 
#include <stddef.h>             /* NULL, size_t, ssize_t */
46
 
#include <stdlib.h>             /* free(), EXIT_SUCCESS, srand(),
47
 
                                   strtof(), abort() */
48
 
#include <stdbool.h>            /* bool, false, true */
49
 
#include <string.h>             /* memset(), strcmp(), strlen(),
50
 
                                   strerror(), asprintf(), strcpy() */
51
 
#include <sys/ioctl.h>          /* ioctl */
52
 
#include <sys/types.h>          /* socket(), inet_pton(), sockaddr,
53
 
                                   sockaddr_in6, PF_INET6,
54
 
                                   SOCK_STREAM, uid_t, gid_t, open(),
55
 
                                   opendir(), DIR */
56
 
#include <sys/stat.h>           /* open() */
57
 
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
58
 
                                   inet_pton(), connect() */
59
 
#include <fcntl.h>              /* open() */
60
 
#include <dirent.h>             /* opendir(), struct dirent, readdir()
61
 
                                 */
62
 
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
63
 
                                   strtoimax() */
64
 
#include <assert.h>             /* assert() */
65
 
#include <errno.h>              /* perror(), errno */
66
 
#include <time.h>               /* nanosleep(), time(), sleep() */
67
 
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
68
 
                                   SIOCSIFFLAGS, if_indextoname(),
69
 
                                   if_nametoindex(), IF_NAMESIZE */
70
 
#include <netinet/in.h>         /* IN6_IS_ADDR_LINKLOCAL,
71
 
                                   INET_ADDRSTRLEN, INET6_ADDRSTRLEN
72
 
                                */
73
 
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
74
 
                                   getuid(), getgid(), seteuid(),
75
 
                                   setgid(), pause() */
76
 
#include <arpa/inet.h>          /* inet_pton(), htons */
77
 
#include <iso646.h>             /* not, or, and */
78
 
#include <argp.h>               /* struct argp_option, error_t, struct
79
 
                                   argp_state, struct argp,
80
 
                                   argp_parse(), ARGP_KEY_ARG,
81
 
                                   ARGP_KEY_END, ARGP_ERR_UNKNOWN */
82
 
#include <signal.h>             /* sigemptyset(), sigaddset(),
83
 
                                   sigaction(), SIGTERM, sig_atomic_t,
84
 
                                   raise() */
85
 
#include <sysexits.h>           /* EX_OSERR, EX_USAGE, EX_UNAVAILABLE,
86
 
                                   EX_NOHOST, EX_IOERR, EX_PROTOCOL */
87
 
 
88
 
#ifdef __linux__
89
 
#include <sys/klog.h>           /* klogctl() */
90
 
#endif  /* __linux__ */
91
 
 
92
 
/* Avahi */
93
 
/* All Avahi types, constants and functions
94
 
 Avahi*, avahi_*,
95
 
 AVAHI_* */
 
34
 
 
35
#define _GNU_SOURCE             /* TEMP_FAILURE_RETRY() */
 
36
 
 
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, SIOCSIFFLAGS
 
43
#include <net/if.h>             // ioctl, ifreq, SIOCGIFFLAGS, IFF_UP, SIOCSIFFLAGS
 
44
 
96
45
#include <avahi-core/core.h>
97
46
#include <avahi-core/lookup.h>
98
47
#include <avahi-core/log.h>
100
49
#include <avahi-common/malloc.h>
101
50
#include <avahi-common/error.h>
102
51
 
103
 
/* GnuTLS */
104
 
#include <gnutls/gnutls.h>      /* All GnuTLS types, constants and
105
 
                                   functions:
106
 
                                   gnutls_*
107
 
                                   init_gnutls_session(),
108
 
                                   GNUTLS_* */
109
 
#include <gnutls/openpgp.h>
110
 
                          /* gnutls_certificate_set_openpgp_key_file(),
111
 
                                   GNUTLS_OPENPGP_FMT_BASE64 */
112
 
 
113
 
/* GPGME */
114
 
#include <gpgme.h>              /* All GPGME types, constants and
115
 
                                   functions:
116
 
                                   gpgme_*
117
 
                                   GPGME_PROTOCOL_OpenPGP,
118
 
                                   GPG_ERR_NO_* */
 
52
//mandos client part
 
53
#include <sys/types.h>          /* socket(), inet_pton() */
 
54
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
 
55
                                   struct in6_addr, inet_pton() */
 
56
#include <gnutls/gnutls.h>      /* All GnuTLS stuff */
 
57
#include <gnutls/openpgp.h>     /* GnuTLS with openpgp stuff */
 
58
 
 
59
#include <unistd.h>             /* close() */
 
60
#include <netinet/in.h>
 
61
#include <stdbool.h>            /* true */
 
62
#include <string.h>             /* memset */
 
63
#include <arpa/inet.h>          /* inet_pton() */
 
64
#include <iso646.h>             /* not */
 
65
 
 
66
// gpgme
 
67
#include <errno.h>              /* perror() */
 
68
#include <gpgme.h>
 
69
 
 
70
// getopt long
 
71
#include <getopt.h>
119
72
 
120
73
#define BUFFER_SIZE 256
 
74
#define DH_BITS 1024
121
75
 
122
 
#define PATHDIR "/conf/conf.d/mandos"
123
 
#define SECKEY "seckey.txt"
124
 
#define PUBKEY "pubkey.txt"
 
76
static const char *certdir = "/conf/conf.d/mandos";
 
77
static const char *certfile = "openpgp-client.txt";
 
78
static const char *certkey = "openpgp-client-key.txt";
125
79
 
126
80
bool debug = false;
127
 
static const char mandos_protocol_version[] = "1";
128
 
const char *argp_program_version = "mandos-client " VERSION;
129
 
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
130
 
static const char sys_class_net[] = "/sys/class/net";
131
 
char *connect_to = NULL;
132
 
 
133
 
/* Used for passing in values through the Avahi callback functions */
 
81
 
 
82
const char mandos_protocol_version[] = "1";
 
83
 
134
84
typedef struct {
135
85
  AvahiSimplePoll *simple_poll;
136
86
  AvahiServer *server;
137
87
  gnutls_certificate_credentials_t cred;
138
88
  unsigned int dh_bits;
139
 
  gnutls_dh_params_t dh_params;
140
89
  const char *priority;
141
 
  gpgme_ctx_t ctx;
142
90
} mandos_context;
143
91
 
144
 
/* global context so signal handler can reach it*/
145
 
mandos_context mc = { .simple_poll = NULL, .server = NULL,
146
 
                      .dh_bits = 1024, .priority = "SECURE256"
147
 
                      ":!CTYPE-X.509:+CTYPE-OPENPGP" };
148
 
 
149
 
sig_atomic_t quit_now = 0;
150
 
int signal_received = 0;
151
 
 
152
 
/*
153
 
 * Make additional room in "buffer" for at least BUFFER_SIZE more
154
 
 * bytes. "buffer_capacity" is how much is currently allocated,
155
 
 * "buffer_length" is how much is already used.
156
 
 */
157
 
size_t incbuffer(char **buffer, size_t buffer_length,
 
92
size_t adjustbuffer(char *buffer, size_t buffer_length,
158
93
                  size_t buffer_capacity){
159
 
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
160
 
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
161
 
    if(buffer == NULL){
 
94
  if (buffer_length + BUFFER_SIZE > buffer_capacity){
 
95
    buffer = realloc(buffer, buffer_capacity + BUFFER_SIZE);
 
96
    if (buffer == NULL){
162
97
      return 0;
163
98
    }
164
99
    buffer_capacity += BUFFER_SIZE;
166
101
  return buffer_capacity;
167
102
}
168
103
 
169
 
/* 
170
 
 * Initialize GPGME.
171
 
 */
172
 
static bool init_gpgme(const char *seckey,
173
 
                       const char *pubkey, const char *tempdir){
 
104
static ssize_t pgp_packet_decrypt (char *packet, size_t packet_size,
 
105
                                   char **new_packet,
 
106
                                   const char *homedir){
 
107
  gpgme_data_t dh_crypto, dh_plain;
 
108
  gpgme_ctx_t ctx;
174
109
  gpgme_error_t rc;
 
110
  ssize_t ret;
 
111
  size_t new_packet_capacity = 0;
 
112
  ssize_t new_packet_length = 0;
175
113
  gpgme_engine_info_t engine_info;
176
 
  
177
 
  
178
 
  /*
179
 
   * Helper function to insert pub and seckey to the engine keyring.
180
 
   */
181
 
  bool import_key(const char *filename){
182
 
    int ret;
183
 
    int fd;
184
 
    gpgme_data_t pgp_data;
185
 
    
186
 
    fd = (int)TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
187
 
    if(fd == -1){
188
 
      perror("open");
189
 
      return false;
190
 
    }
191
 
    
192
 
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
193
 
    if(rc != GPG_ERR_NO_ERROR){
194
 
      fprintf(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
195
 
              gpgme_strsource(rc), gpgme_strerror(rc));
196
 
      return false;
197
 
    }
198
 
    
199
 
    rc = gpgme_op_import(mc.ctx, pgp_data);
200
 
    if(rc != GPG_ERR_NO_ERROR){
201
 
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
202
 
              gpgme_strsource(rc), gpgme_strerror(rc));
203
 
      return false;
204
 
    }
205
 
    
206
 
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
207
 
    if(ret == -1){
208
 
      perror("close");
209
 
    }
210
 
    gpgme_data_release(pgp_data);
211
 
    return true;
212
 
  }
213
 
  
214
 
  if(debug){
215
 
    fprintf(stderr, "Initializing GPGME\n");
 
114
 
 
115
  if (debug){
 
116
    fprintf(stderr, "Trying to decrypt OpenPGP packet\n");
216
117
  }
217
118
  
218
119
  /* Init GPGME */
219
120
  gpgme_check_version(NULL);
220
121
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
221
 
  if(rc != GPG_ERR_NO_ERROR){
 
122
  if (rc != GPG_ERR_NO_ERROR){
222
123
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
223
124
            gpgme_strsource(rc), gpgme_strerror(rc));
224
 
    return false;
 
125
    return -1;
225
126
  }
226
127
  
227
 
    /* Set GPGME home directory for the OpenPGP engine only */
228
 
  rc = gpgme_get_engine_info(&engine_info);
229
 
  if(rc != GPG_ERR_NO_ERROR){
 
128
  /* Set GPGME home directory */
 
129
  rc = gpgme_get_engine_info (&engine_info);
 
130
  if (rc != GPG_ERR_NO_ERROR){
230
131
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
231
132
            gpgme_strsource(rc), gpgme_strerror(rc));
232
 
    return false;
 
133
    return -1;
233
134
  }
234
135
  while(engine_info != NULL){
235
136
    if(engine_info->protocol == GPGME_PROTOCOL_OpenPGP){
236
137
      gpgme_set_engine_info(GPGME_PROTOCOL_OpenPGP,
237
 
                            engine_info->file_name, tempdir);
 
138
                            engine_info->file_name, homedir);
238
139
      break;
239
140
    }
240
141
    engine_info = engine_info->next;
241
142
  }
242
143
  if(engine_info == NULL){
243
 
    fprintf(stderr, "Could not set GPGME home dir to %s\n", tempdir);
244
 
    return false;
245
 
  }
246
 
  
247
 
  /* Create new GPGME "context" */
248
 
  rc = gpgme_new(&(mc.ctx));
249
 
  if(rc != GPG_ERR_NO_ERROR){
250
 
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
251
 
            gpgme_strsource(rc), gpgme_strerror(rc));
252
 
    return false;
253
 
  }
254
 
  
255
 
  if(not import_key(pubkey) or not import_key(seckey)){
256
 
    return false;
257
 
  }
258
 
  
259
 
  return true;
260
 
}
261
 
 
262
 
/* 
263
 
 * Decrypt OpenPGP data.
264
 
 * Returns -1 on error
265
 
 */
266
 
static ssize_t pgp_packet_decrypt(const char *cryptotext,
267
 
                                  size_t crypto_size,
268
 
                                  char **plaintext){
269
 
  gpgme_data_t dh_crypto, dh_plain;
270
 
  gpgme_error_t rc;
271
 
  ssize_t ret;
272
 
  size_t plaintext_capacity = 0;
273
 
  ssize_t plaintext_length = 0;
274
 
  
275
 
  if(debug){
276
 
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
277
 
  }
278
 
  
279
 
  /* Create new GPGME data buffer from memory cryptotext */
280
 
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
281
 
                               0);
282
 
  if(rc != GPG_ERR_NO_ERROR){
 
144
    fprintf(stderr, "Could not set home dir to %s\n", homedir);
 
145
    return -1;
 
146
  }
 
147
  
 
148
  /* Create new GPGME data buffer from packet buffer */
 
149
  rc = gpgme_data_new_from_mem(&dh_crypto, packet, packet_size, 0);
 
150
  if (rc != GPG_ERR_NO_ERROR){
283
151
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
284
152
            gpgme_strsource(rc), gpgme_strerror(rc));
285
153
    return -1;
287
155
  
288
156
  /* Create new empty GPGME data buffer for the plaintext */
289
157
  rc = gpgme_data_new(&dh_plain);
290
 
  if(rc != GPG_ERR_NO_ERROR){
 
158
  if (rc != GPG_ERR_NO_ERROR){
291
159
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
292
160
            gpgme_strsource(rc), gpgme_strerror(rc));
293
 
    gpgme_data_release(dh_crypto);
294
 
    return -1;
295
 
  }
296
 
  
297
 
  /* Decrypt data from the cryptotext data buffer to the plaintext
298
 
     data buffer */
299
 
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
300
 
  if(rc != GPG_ERR_NO_ERROR){
 
161
    return -1;
 
162
  }
 
163
  
 
164
  /* Create new GPGME "context" */
 
165
  rc = gpgme_new(&ctx);
 
166
  if (rc != GPG_ERR_NO_ERROR){
 
167
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
 
168
            gpgme_strsource(rc), gpgme_strerror(rc));
 
169
    return -1;
 
170
  }
 
171
  
 
172
  /* Decrypt data from the FILE pointer to the plaintext data
 
173
     buffer */
 
174
  rc = gpgme_op_decrypt(ctx, dh_crypto, dh_plain);
 
175
  if (rc != GPG_ERR_NO_ERROR){
301
176
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
302
177
            gpgme_strsource(rc), gpgme_strerror(rc));
303
 
    plaintext_length = -1;
304
 
    if(debug){
305
 
      gpgme_decrypt_result_t result;
306
 
      result = gpgme_op_decrypt_result(mc.ctx);
307
 
      if(result == NULL){
308
 
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
309
 
      } else {
310
 
        fprintf(stderr, "Unsupported algorithm: %s\n",
311
 
                result->unsupported_algorithm);
312
 
        fprintf(stderr, "Wrong key usage: %u\n",
313
 
                result->wrong_key_usage);
314
 
        if(result->file_name != NULL){
315
 
          fprintf(stderr, "File name: %s\n", result->file_name);
316
 
        }
317
 
        gpgme_recipient_t recipient;
318
 
        recipient = result->recipients;
 
178
    return -1;
 
179
  }
 
180
 
 
181
  if(debug){
 
182
    fprintf(stderr, "Decryption of OpenPGP packet succeeded\n");
 
183
  }
 
184
 
 
185
  if (debug){
 
186
    gpgme_decrypt_result_t result;
 
187
    result = gpgme_op_decrypt_result(ctx);
 
188
    if (result == NULL){
 
189
      fprintf(stderr, "gpgme_op_decrypt_result failed\n");
 
190
    } else {
 
191
      fprintf(stderr, "Unsupported algorithm: %s\n",
 
192
              result->unsupported_algorithm);
 
193
      fprintf(stderr, "Wrong key usage: %d\n",
 
194
              result->wrong_key_usage);
 
195
      if(result->file_name != NULL){
 
196
        fprintf(stderr, "File name: %s\n", result->file_name);
 
197
      }
 
198
      gpgme_recipient_t recipient;
 
199
      recipient = result->recipients;
 
200
      if(recipient){
319
201
        while(recipient != NULL){
320
202
          fprintf(stderr, "Public key algorithm: %s\n",
321
203
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
327
209
        }
328
210
      }
329
211
    }
330
 
    goto decrypt_end;
331
212
  }
332
213
  
333
 
  if(debug){
334
 
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
335
 
  }
 
214
  /* Delete the GPGME FILE pointer cryptotext data buffer */
 
215
  gpgme_data_release(dh_crypto);
336
216
  
337
217
  /* Seek back to the beginning of the GPGME plaintext data buffer */
338
 
  if(gpgme_data_seek(dh_plain, (off_t)0, SEEK_SET) == -1){
339
 
    perror("gpgme_data_seek");
340
 
    plaintext_length = -1;
341
 
    goto decrypt_end;
 
218
  if (gpgme_data_seek(dh_plain, (off_t) 0, SEEK_SET) == -1){
 
219
    perror("pgpme_data_seek");
342
220
  }
343
221
  
344
 
  *plaintext = NULL;
 
222
  *new_packet = 0;
345
223
  while(true){
346
 
    plaintext_capacity = incbuffer(plaintext,
347
 
                                      (size_t)plaintext_length,
348
 
                                      plaintext_capacity);
349
 
    if(plaintext_capacity == 0){
350
 
        perror("incbuffer");
351
 
        plaintext_length = -1;
352
 
        goto decrypt_end;
 
224
    new_packet_capacity = adjustbuffer(*new_packet, new_packet_length,
 
225
                                       new_packet_capacity);
 
226
    if (new_packet_capacity == 0){
 
227
        perror("adjustbuffer");
 
228
        return -1;
 
229
      }
 
230
      new_packet_capacity += BUFFER_SIZE;
353
231
    }
354
232
    
355
 
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
 
233
    ret = gpgme_data_read(dh_plain, *new_packet + new_packet_length,
356
234
                          BUFFER_SIZE);
357
235
    /* Print the data, if any */
358
 
    if(ret == 0){
359
 
      /* EOF */
 
236
    if (ret == 0){
360
237
      break;
361
238
    }
362
239
    if(ret < 0){
363
240
      perror("gpgme_data_read");
364
 
      plaintext_length = -1;
365
 
      goto decrypt_end;
366
 
    }
367
 
    plaintext_length += ret;
368
 
  }
369
 
  
370
 
  if(debug){
371
 
    fprintf(stderr, "Decrypted password is: ");
372
 
    for(ssize_t i = 0; i < plaintext_length; i++){
373
 
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
374
 
    }
375
 
    fprintf(stderr, "\n");
376
 
  }
377
 
  
378
 
 decrypt_end:
379
 
  
380
 
  /* Delete the GPGME cryptotext data buffer */
381
 
  gpgme_data_release(dh_crypto);
 
241
      return -1;
 
242
    }
 
243
    new_packet_length += ret;
 
244
  }
 
245
 
 
246
  /* FIXME: check characters before printing to screen so to not print
 
247
     terminal control characters */
 
248
  /*   if(debug){ */
 
249
  /*     fprintf(stderr, "decrypted password is: "); */
 
250
  /*     fwrite(*new_packet, 1, new_packet_length, stderr); */
 
251
  /*     fprintf(stderr, "\n"); */
 
252
  /*   } */
382
253
  
383
254
  /* Delete the GPGME plaintext data buffer */
384
255
  gpgme_data_release(dh_plain);
385
 
  return plaintext_length;
 
256
  return new_packet_length;
386
257
}
387
258
 
388
 
static const char * safer_gnutls_strerror(int value){
389
 
  const char *ret = gnutls_strerror(value); /* Spurious warning from
390
 
                                               -Wunreachable-code */
391
 
  if(ret == NULL)
 
259
static const char * safer_gnutls_strerror (int value) {
 
260
  const char *ret = gnutls_strerror (value);
 
261
  if (ret == NULL)
392
262
    ret = "(unknown)";
393
263
  return ret;
394
264
}
395
265
 
396
 
/* GnuTLS log function callback */
397
266
static void debuggnutls(__attribute__((unused)) int level,
398
267
                        const char* string){
399
 
  fprintf(stderr, "GnuTLS: %s", string);
 
268
  fprintf(stderr, "%s", string);
400
269
}
401
270
 
402
 
static int init_gnutls_global(const char *pubkeyfilename,
403
 
                              const char *seckeyfilename){
 
271
static int initgnutls(mandos_context *mc){
 
272
  const char *err;
404
273
  int ret;
405
274
  
406
275
  if(debug){
407
276
    fprintf(stderr, "Initializing GnuTLS\n");
408
277
  }
409
 
  
410
 
  ret = gnutls_global_init();
411
 
  if(ret != GNUTLS_E_SUCCESS){
412
 
    fprintf(stderr, "GnuTLS global_init: %s\n",
413
 
            safer_gnutls_strerror(ret));
 
278
 
 
279
  if ((ret = gnutls_global_init ())
 
280
      != GNUTLS_E_SUCCESS) {
 
281
    fprintf (stderr, "global_init: %s\n", safer_gnutls_strerror(ret));
414
282
    return -1;
415
283
  }
416
 
  
417
 
  if(debug){
418
 
    /* "Use a log level over 10 to enable all debugging options."
419
 
     * - GnuTLS manual
420
 
     */
 
284
 
 
285
  if (debug){
421
286
    gnutls_global_set_log_level(11);
422
287
    gnutls_global_set_log_function(debuggnutls);
423
288
  }
424
289
  
425
 
  /* OpenPGP credentials */
426
 
  gnutls_certificate_allocate_credentials(&mc.cred);
427
 
  if(ret != GNUTLS_E_SUCCESS){
428
 
    fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning
429
 
                                                    from
430
 
                                                    -Wunreachable-code
431
 
                                                 */
432
 
            safer_gnutls_strerror(ret));
433
 
    gnutls_global_deinit();
 
290
  /* openpgp credentials */
 
291
  if ((ret = gnutls_certificate_allocate_credentials (&es->cred))
 
292
      != GNUTLS_E_SUCCESS) {
 
293
    fprintf (stderr, "memory error: %s\n",
 
294
             safer_gnutls_strerror(ret));
434
295
    return -1;
435
296
  }
436
297
  
437
298
  if(debug){
438
 
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
439
 
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
440
 
            seckeyfilename);
 
299
    fprintf(stderr, "Attempting to use OpenPGP certificate %s"
 
300
            " and keyfile %s as GnuTLS credentials\n", certfile,
 
301
            certkey);
441
302
  }
442
303
  
443
304
  ret = gnutls_certificate_set_openpgp_key_file
444
 
    (mc.cred, pubkeyfilename, seckeyfilename,
445
 
     GNUTLS_OPENPGP_FMT_BASE64);
446
 
  if(ret != GNUTLS_E_SUCCESS){
447
 
    fprintf(stderr,
448
 
            "Error[%d] while reading the OpenPGP key pair ('%s',"
449
 
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
450
 
    fprintf(stderr, "The GnuTLS error is: %s\n",
451
 
            safer_gnutls_strerror(ret));
452
 
    goto globalfail;
453
 
  }
454
 
  
455
 
  /* GnuTLS server initialization */
456
 
  ret = gnutls_dh_params_init(&mc.dh_params);
457
 
  if(ret != GNUTLS_E_SUCCESS){
458
 
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
459
 
            " %s\n", safer_gnutls_strerror(ret));
460
 
    goto globalfail;
461
 
  }
462
 
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
463
 
  if(ret != GNUTLS_E_SUCCESS){
464
 
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
465
 
            safer_gnutls_strerror(ret));
466
 
    goto globalfail;
467
 
  }
468
 
  
469
 
  gnutls_certificate_set_dh_params(mc.cred, mc.dh_params);
470
 
  
471
 
  return 0;
472
 
  
473
 
 globalfail:
474
 
  
475
 
  gnutls_certificate_free_credentials(mc.cred);
476
 
  gnutls_global_deinit();
477
 
  gnutls_dh_params_deinit(mc.dh_params);
478
 
  return -1;
479
 
}
480
 
 
481
 
static int init_gnutls_session(gnutls_session_t *session){
482
 
  int ret;
483
 
  /* GnuTLS session creation */
484
 
  do {
485
 
    ret = gnutls_init(session, GNUTLS_SERVER);
486
 
    if(quit_now){
487
 
      return -1;
488
 
    }
489
 
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
490
 
  if(ret != GNUTLS_E_SUCCESS){
 
305
    (es->cred, certfile, certkey, GNUTLS_OPENPGP_FMT_BASE64);
 
306
  if (ret != GNUTLS_E_SUCCESS) {
 
307
    fprintf
 
308
      (stderr, "Error[%d] while reading the OpenPGP key pair ('%s',"
 
309
       " '%s')\n",
 
310
       ret, certfile, certkey);
 
311
    fprintf(stdout, "The Error is: %s\n",
 
312
            safer_gnutls_strerror(ret));
 
313
    return -1;
 
314
  }
 
315
  
 
316
  //GnuTLS server initialization
 
317
  if ((ret = gnutls_dh_params_init (&es->dh_params))
 
318
      != GNUTLS_E_SUCCESS) {
 
319
    fprintf (stderr, "Error in dh parameter initialization: %s\n",
 
320
             safer_gnutls_strerror(ret));
 
321
    return -1;
 
322
  }
 
323
  
 
324
  if ((ret = gnutls_dh_params_generate2 (es->dh_params, DH_BITS))
 
325
      != GNUTLS_E_SUCCESS) {
 
326
    fprintf (stderr, "Error in prime generation: %s\n",
 
327
             safer_gnutls_strerror(ret));
 
328
    return -1;
 
329
  }
 
330
  
 
331
  gnutls_certificate_set_dh_params (es->cred, es->dh_params);
 
332
  
 
333
  // GnuTLS session creation
 
334
  if ((ret = gnutls_init (&es->session, GNUTLS_SERVER))
 
335
      != GNUTLS_E_SUCCESS){
491
336
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
492
337
            safer_gnutls_strerror(ret));
493
338
  }
494
339
  
495
 
  {
496
 
    const char *err;
497
 
    do {
498
 
      ret = gnutls_priority_set_direct(*session, mc.priority, &err);
499
 
      if(quit_now){
500
 
        gnutls_deinit(*session);
501
 
        return -1;
502
 
      }
503
 
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
504
 
    if(ret != GNUTLS_E_SUCCESS){
505
 
      fprintf(stderr, "Syntax error at: %s\n", err);
506
 
      fprintf(stderr, "GnuTLS error: %s\n",
507
 
              safer_gnutls_strerror(ret));
508
 
      gnutls_deinit(*session);
509
 
      return -1;
510
 
    }
 
340
  if ((ret = gnutls_priority_set_direct (es->session, mc->priority, &err))
 
341
      != GNUTLS_E_SUCCESS) {
 
342
    fprintf(stderr, "Syntax error at: %s\n", err);
 
343
    fprintf(stderr, "GnuTLS error: %s\n",
 
344
            safer_gnutls_strerror(ret));
 
345
    return -1;
511
346
  }
512
347
  
513
 
  do {
514
 
    ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
515
 
                                 mc.cred);
516
 
    if(quit_now){
517
 
      gnutls_deinit(*session);
518
 
      return -1;
519
 
    }
520
 
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
521
 
  if(ret != GNUTLS_E_SUCCESS){
522
 
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
 
348
  if ((ret = gnutls_credentials_set
 
349
       (es->session, GNUTLS_CRD_CERTIFICATE, es->cred))
 
350
      != GNUTLS_E_SUCCESS) {
 
351
    fprintf(stderr, "Error setting a credentials set: %s\n",
523
352
            safer_gnutls_strerror(ret));
524
 
    gnutls_deinit(*session);
525
353
    return -1;
526
354
  }
527
355
  
528
356
  /* ignore client certificate if any. */
529
 
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
 
357
  gnutls_certificate_server_set_request (es->session,
 
358
                                         GNUTLS_CERT_IGNORE);
530
359
  
531
 
  gnutls_dh_set_prime_bits(*session, mc.dh_bits);
 
360
  gnutls_dh_set_prime_bits (es->session, DH_BITS);
532
361
  
533
362
  return 0;
534
363
}
535
364
 
536
 
/* Avahi log function callback */
537
365
static void empty_log(__attribute__((unused)) AvahiLogLevel level,
538
366
                      __attribute__((unused)) const char *txt){}
539
367
 
540
 
/* Called when a Mandos server is found */
541
368
static int start_mandos_communication(const char *ip, uint16_t port,
542
369
                                      AvahiIfIndex if_index,
543
 
                                      int af){
544
 
  int ret, tcp_sd = -1;
545
 
  ssize_t sret;
546
 
  union {
547
 
    struct sockaddr_in in;
548
 
    struct sockaddr_in6 in6;
549
 
  } to;
 
370
                                      mandos_context *mc){
 
371
  int ret, tcp_sd;
 
372
  struct sockaddr_in6 to;
 
373
  encrypted_session es;
550
374
  char *buffer = NULL;
551
 
  char *decrypted_buffer = NULL;
 
375
  char *decrypted_buffer;
552
376
  size_t buffer_length = 0;
553
377
  size_t buffer_capacity = 0;
 
378
  ssize_t decrypted_buffer_size;
554
379
  size_t written;
555
 
  int retval = -1;
556
 
  gnutls_session_t session;
557
 
  int pf;                       /* Protocol family */
558
 
  
559
 
  errno = 0;
560
 
  
561
 
  if(quit_now){
562
 
    errno = EINTR;
563
 
    return -1;
564
 
  }
565
 
  
566
 
  switch(af){
567
 
  case AF_INET6:
568
 
    pf = PF_INET6;
569
 
    break;
570
 
  case AF_INET:
571
 
    pf = PF_INET;
572
 
    break;
573
 
  default:
574
 
    fprintf(stderr, "Bad address family: %d\n", af);
575
 
    errno = EINVAL;
576
 
    return -1;
577
 
  }
578
 
  
579
 
  ret = init_gnutls_session(&session);
580
 
  if(ret != 0){
581
 
    return -1;
582
 
  }
 
380
  int retval = 0;
 
381
  char interface[IF_NAMESIZE];
583
382
  
584
383
  if(debug){
585
 
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
586
 
            "\n", ip, port);
 
384
    fprintf(stderr, "Setting up a tcp connection to %s, port %d\n",
 
385
            ip, port);
587
386
  }
588
387
  
589
 
  tcp_sd = socket(pf, SOCK_STREAM, 0);
590
 
  if(tcp_sd < 0){
591
 
    int e = errno;
 
388
  tcp_sd = socket(PF_INET6, SOCK_STREAM, 0);
 
389
  if(tcp_sd < 0) {
592
390
    perror("socket");
593
 
    errno = e;
594
 
    goto mandos_end;
595
 
  }
596
 
  
597
 
  if(quit_now){
598
 
    errno = EINTR;
599
 
    goto mandos_end;
600
 
  }
601
 
  
602
 
  memset(&to, 0, sizeof(to));
603
 
  if(af == AF_INET6){
604
 
    to.in6.sin6_family = (sa_family_t)af;
605
 
    ret = inet_pton(af, ip, &to.in6.sin6_addr);
606
 
  } else {                      /* IPv4 */
607
 
    to.in.sin_family = (sa_family_t)af;
608
 
    ret = inet_pton(af, ip, &to.in.sin_addr);
609
 
  }
610
 
  if(ret < 0 ){
611
 
    int e = errno;
 
391
    return -1;
 
392
  }
 
393
 
 
394
  if(debug){
 
395
    if(if_indextoname((unsigned int)if_index, interface) == NULL){
 
396
      if(debug){
 
397
        perror("if_indextoname");
 
398
      }
 
399
      return -1;
 
400
    }
 
401
    
 
402
    fprintf(stderr, "Binding to interface %s\n", interface);
 
403
  }
 
404
  
 
405
  memset(&to,0,sizeof(to));     /* Spurious warning */
 
406
  to.sin6_family = AF_INET6;
 
407
  ret = inet_pton(AF_INET6, ip, &to.sin6_addr);
 
408
  if (ret < 0 ){
612
409
    perror("inet_pton");
613
 
    errno = e;
614
 
    goto mandos_end;
615
 
  }
 
410
    return -1;
 
411
  }  
616
412
  if(ret == 0){
617
 
    int e = errno;
618
413
    fprintf(stderr, "Bad address: %s\n", ip);
619
 
    errno = e;
620
 
    goto mandos_end;
621
 
  }
622
 
  if(af == AF_INET6){
623
 
    to.in6.sin6_port = htons(port); /* Spurious warnings from
624
 
                                       -Wconversion and
625
 
                                       -Wunreachable-code */
626
 
    
627
 
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
628
 
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
629
 
                              -Wunreachable-code*/
630
 
      if(if_index == AVAHI_IF_UNSPEC){
631
 
        fprintf(stderr, "An IPv6 link-local address is incomplete"
632
 
                " without a network interface\n");
633
 
        errno = EINVAL;
634
 
        goto mandos_end;
635
 
      }
636
 
      /* Set the network interface number as scope */
637
 
      to.in6.sin6_scope_id = (uint32_t)if_index;
638
 
    }
639
 
  } else {
640
 
    to.in.sin_port = htons(port); /* Spurious warnings from
641
 
                                     -Wconversion and
642
 
                                     -Wunreachable-code */
643
 
  }
 
414
    return -1;
 
415
  }
 
416
  to.sin6_port = htons(port);   /* Spurious warning */
644
417
  
645
 
  if(quit_now){
646
 
    errno = EINTR;
647
 
    goto mandos_end;
648
 
  }
 
418
  to.sin6_scope_id = (uint32_t)if_index;
649
419
  
650
420
  if(debug){
651
 
    if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
652
 
      char interface[IF_NAMESIZE];
653
 
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
654
 
        perror("if_indextoname");
655
 
      } else {
656
 
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
657
 
                ip, interface, port);
658
 
      }
659
 
    } else {
660
 
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
661
 
              port);
662
 
    }
663
 
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
664
 
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
665
 
    const char *pcret;
666
 
    if(af == AF_INET6){
667
 
      pcret = inet_ntop(af, &(to.in6.sin6_addr), addrstr,
668
 
                        sizeof(addrstr));
669
 
    } else {
670
 
      pcret = inet_ntop(af, &(to.in.sin_addr), addrstr,
671
 
                        sizeof(addrstr));
672
 
    }
673
 
    if(pcret == NULL){
674
 
      perror("inet_ntop");
675
 
    } else {
676
 
      if(strcmp(addrstr, ip) != 0){
677
 
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
678
 
      }
679
 
    }
680
 
  }
681
 
  
682
 
  if(quit_now){
683
 
    errno = EINTR;
684
 
    goto mandos_end;
685
 
  }
686
 
  
687
 
  if(af == AF_INET6){
688
 
    ret = connect(tcp_sd, &to.in6, sizeof(to));
689
 
  } else {
690
 
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
691
 
  }
692
 
  if(ret < 0){
693
 
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
694
 
      int e = errno;
695
 
      perror("connect");
696
 
      errno = e;
697
 
    }
698
 
    goto mandos_end;
699
 
  }
700
 
  
701
 
  if(quit_now){
702
 
    errno = EINTR;
703
 
    goto mandos_end;
704
 
  }
705
 
  
706
 
  const char *out = mandos_protocol_version;
 
421
    fprintf(stderr, "Connection to: %s, port %d\n", ip, port);
 
422
/*     char addrstr[INET6_ADDRSTRLEN]; */
 
423
/*     if(inet_ntop(to.sin6_family, &(to.sin6_addr), addrstr, */
 
424
/*               sizeof(addrstr)) == NULL){ */
 
425
/*       perror("inet_ntop"); */
 
426
/*     } else { */
 
427
/*       fprintf(stderr, "Really connecting to: %s, port %d\n", */
 
428
/*            addrstr, ntohs(to.sin6_port)); */
 
429
/*     } */
 
430
  }
 
431
  
 
432
  ret = connect(tcp_sd, (struct sockaddr *) &to, sizeof(to));
 
433
  if (ret < 0){
 
434
    perror("connect");
 
435
    return -1;
 
436
  }
 
437
 
 
438
  char *out = mandos_protocol_version;
707
439
  written = 0;
708
 
  while(true){
 
440
  while (true){
709
441
    size_t out_size = strlen(out);
710
 
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
 
442
    ret = TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
711
443
                                   out_size - written));
712
 
    if(ret == -1){
713
 
      int e = errno;
 
444
    if (ret == -1){
714
445
      perror("write");
715
 
      errno = e;
716
 
      goto mandos_end;
 
446
      retval = -1;
 
447
      goto end;
717
448
    }
718
 
    written += (size_t)ret;
 
449
    written += ret;
719
450
    if(written < out_size){
720
451
      continue;
721
452
    } else {
722
 
      if(out == mandos_protocol_version){
 
453
      if (out == mandos_protocol_version){
723
454
        written = 0;
724
455
        out = "\r\n";
725
456
      } else {
726
457
        break;
727
458
      }
728
459
    }
 
460
  }
 
461
 
 
462
  ret = initgnutls (&es);
 
463
  if (ret != 0){
 
464
    retval = -1;
 
465
    return -1;
 
466
  }
729
467
  
730
 
    if(quit_now){
731
 
      errno = EINTR;
732
 
      goto mandos_end;
733
 
    }
734
 
  }
 
468
  gnutls_transport_set_ptr (es.session,
 
469
                            (gnutls_transport_ptr_t) tcp_sd);
735
470
  
736
471
  if(debug){
737
472
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
738
473
  }
739
474
  
740
 
  if(quit_now){
741
 
    errno = EINTR;
742
 
    goto mandos_end;
743
 
  }
744
 
  
745
 
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
746
 
  
747
 
  if(quit_now){
748
 
    errno = EINTR;
749
 
    goto mandos_end;
750
 
  }
751
 
  
752
 
  do {
753
 
    ret = gnutls_handshake(session);
754
 
    if(quit_now){
755
 
      errno = EINTR;
756
 
      goto mandos_end;
757
 
    }
758
 
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
759
 
  
760
 
  if(ret != GNUTLS_E_SUCCESS){
 
475
  ret = gnutls_handshake (es.session);
 
476
  
 
477
  if (ret != GNUTLS_E_SUCCESS){
761
478
    if(debug){
762
 
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
763
 
      gnutls_perror(ret);
 
479
      fprintf(stderr, "\n*** Handshake failed ***\n");
 
480
      gnutls_perror (ret);
764
481
    }
765
 
    errno = EPROTO;
766
 
    goto mandos_end;
 
482
    retval = -1;
 
483
    goto exit;
767
484
  }
768
485
  
769
 
  /* Read OpenPGP packet that contains the wanted password */
 
486
  //Retrieve OpenPGP packet that contains the wanted password
770
487
  
771
488
  if(debug){
772
 
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
 
489
    fprintf(stderr, "Retrieving pgp encrypted password from %s\n",
773
490
            ip);
774
491
  }
775
 
  
 
492
 
776
493
  while(true){
777
 
    
778
 
    if(quit_now){
779
 
      errno = EINTR;
780
 
      goto mandos_end;
781
 
    }
782
 
    
783
 
    buffer_capacity = incbuffer(&buffer, buffer_length,
784
 
                                   buffer_capacity);
785
 
    if(buffer_capacity == 0){
786
 
      int e = errno;
787
 
      perror("incbuffer");
788
 
      errno = e;
789
 
      goto mandos_end;
790
 
    }
791
 
    
792
 
    if(quit_now){
793
 
      errno = EINTR;
794
 
      goto mandos_end;
795
 
    }
796
 
    
797
 
    sret = gnutls_record_recv(session, buffer+buffer_length,
798
 
                              BUFFER_SIZE);
799
 
    if(sret == 0){
 
494
    buffer_capacity = adjustbuffer(buffer, buffer_length, buffer_capacity);
 
495
    if (buffer_capacity == 0){
 
496
      perror("adjustbuffer");
 
497
      retval = -1;
 
498
      goto exit;
 
499
    }
 
500
    
 
501
    ret = gnutls_record_recv
 
502
      (es.session, buffer+buffer_length, BUFFER_SIZE);
 
503
    if (ret == 0){
800
504
      break;
801
505
    }
802
 
    if(sret < 0){
803
 
      switch(sret){
 
506
    if (ret < 0){
 
507
      switch(ret){
804
508
      case GNUTLS_E_INTERRUPTED:
805
509
      case GNUTLS_E_AGAIN:
806
510
        break;
807
511
      case GNUTLS_E_REHANDSHAKE:
808
 
        do {
809
 
          ret = gnutls_handshake(session);
810
 
          
811
 
          if(quit_now){
812
 
            errno = EINTR;
813
 
            goto mandos_end;
814
 
          }
815
 
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
816
 
        if(ret < 0){
817
 
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
818
 
          gnutls_perror(ret);
819
 
          errno = EPROTO;
820
 
          goto mandos_end;
 
512
        ret = gnutls_handshake (es.session);
 
513
        if (ret < 0){
 
514
          fprintf(stderr, "\n*** Handshake failed ***\n");
 
515
          gnutls_perror (ret);
 
516
          retval = -1;
 
517
          goto exit;
821
518
        }
822
519
        break;
823
520
      default:
824
521
        fprintf(stderr, "Unknown error while reading data from"
825
 
                " encrypted session with Mandos server\n");
826
 
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
827
 
        errno = EIO;
828
 
        goto mandos_end;
 
522
                " encrypted session with mandos server\n");
 
523
        retval = -1;
 
524
        gnutls_bye (es.session, GNUTLS_SHUT_RDWR);
 
525
        goto exit;
829
526
      }
830
527
    } else {
831
 
      buffer_length += (size_t) sret;
832
 
    }
833
 
  }
834
 
  
835
 
  if(debug){
836
 
    fprintf(stderr, "Closing TLS session\n");
837
 
  }
838
 
  
839
 
  if(quit_now){
840
 
    errno = EINTR;
841
 
    goto mandos_end;
842
 
  }
843
 
  
844
 
  do {
845
 
    ret = gnutls_bye(session, GNUTLS_SHUT_RDWR);
846
 
    if(quit_now){
847
 
      errno = EINTR;
848
 
      goto mandos_end;
849
 
    }
850
 
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
851
 
  
852
 
  if(buffer_length > 0){
853
 
    ssize_t decrypted_buffer_size;
 
528
      buffer_length += (size_t) ret;
 
529
    }
 
530
  }
 
531
  
 
532
  if (buffer_length > 0){
854
533
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
855
534
                                               buffer_length,
856
 
                                               &decrypted_buffer);
857
 
    if(decrypted_buffer_size >= 0){
858
 
      
 
535
                                               &decrypted_buffer,
 
536
                                               certdir);
 
537
    if (decrypted_buffer_size >= 0){
859
538
      written = 0;
860
539
      while(written < (size_t) decrypted_buffer_size){
861
 
        if(quit_now){
862
 
          errno = EINTR;
863
 
          goto mandos_end;
864
 
        }
865
 
        
866
 
        ret = (int)fwrite(decrypted_buffer + written, 1,
867
 
                          (size_t)decrypted_buffer_size - written,
868
 
                          stdout);
 
540
        ret = (int)fwrite (decrypted_buffer + written, 1,
 
541
                           (size_t)decrypted_buffer_size - written,
 
542
                           stdout);
869
543
        if(ret == 0 and ferror(stdout)){
870
 
          int e = errno;
871
544
          if(debug){
872
545
            fprintf(stderr, "Error writing encrypted data: %s\n",
873
546
                    strerror(errno));
874
547
          }
875
 
          errno = e;
876
 
          goto mandos_end;
 
548
          retval = -1;
 
549
          break;
877
550
        }
878
551
        written += (size_t)ret;
879
552
      }
880
 
      retval = 0;
881
 
    }
882
 
  }
883
 
  
884
 
  /* Shutdown procedure */
885
 
  
886
 
 mandos_end:
887
 
  {
888
 
    int e = errno;
889
 
    free(decrypted_buffer);
890
 
    free(buffer);
891
 
    if(tcp_sd >= 0){
892
 
      ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
893
 
    }
894
 
    if(ret == -1){
895
 
      if(e == 0){
896
 
        e = errno;
897
 
      }
898
 
      perror("close");
899
 
    }
900
 
    gnutls_deinit(session);
901
 
    if(quit_now){
902
 
      e = EINTR;
 
553
      free(decrypted_buffer);
 
554
    } else {
903
555
      retval = -1;
904
556
    }
905
 
    errno = e;
906
 
  }
 
557
  }
 
558
 
 
559
  //shutdown procedure
 
560
 
 
561
  if(debug){
 
562
    fprintf(stderr, "Closing TLS session\n");
 
563
  }
 
564
 
 
565
  free(buffer);
 
566
  gnutls_bye (es.session, GNUTLS_SHUT_RDWR);
 
567
 exit:
 
568
  close(tcp_sd);
 
569
  gnutls_deinit (es.session);
 
570
  gnutls_certificate_free_credentials (es.cred);
 
571
  gnutls_global_deinit ();
907
572
  return retval;
908
573
}
909
574
 
910
 
static void resolve_callback(AvahiSServiceResolver *r,
911
 
                             AvahiIfIndex interface,
912
 
                             AvahiProtocol proto,
913
 
                             AvahiResolverEvent event,
914
 
                             const char *name,
915
 
                             const char *type,
916
 
                             const char *domain,
917
 
                             const char *host_name,
918
 
                             const AvahiAddress *address,
919
 
                             uint16_t port,
920
 
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
921
 
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
922
 
                             flags,
923
 
                             AVAHI_GCC_UNUSED void* userdata){
924
 
  assert(r);
 
575
static void resolve_callback( AvahiSServiceResolver *r,
 
576
                              AvahiIfIndex interface,
 
577
                              AVAHI_GCC_UNUSED AvahiProtocol protocol,
 
578
                              AvahiResolverEvent event,
 
579
                              const char *name,
 
580
                              const char *type,
 
581
                              const char *domain,
 
582
                              const char *host_name,
 
583
                              const AvahiAddress *address,
 
584
                              uint16_t port,
 
585
                              AVAHI_GCC_UNUSED AvahiStringList *txt,
 
586
                              AVAHI_GCC_UNUSED AvahiLookupResultFlags flags,
 
587
                              AVAHI_GCC_UNUSED void* userdata) {
 
588
  mandos_context *mc = userdata;
 
589
  assert(r);                    /* Spurious warning */
925
590
  
926
591
  /* Called whenever a service has been resolved successfully or
927
592
     timed out */
928
593
  
929
 
  if(quit_now){
930
 
    return;
931
 
  }
932
 
  
933
 
  switch(event){
 
594
  switch (event) {
934
595
  default:
935
596
  case AVAHI_RESOLVER_FAILURE:
936
 
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
937
 
            " of type '%s' in domain '%s': %s\n", name, type, domain,
938
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
597
    fprintf(stderr, "(Resolver) Failed to resolve service '%s' of"
 
598
            " type '%s' in domain '%s': %s\n", name, type, domain,
 
599
            avahi_strerror(avahi_server_errno(mc->server)));
939
600
    break;
940
601
    
941
602
  case AVAHI_RESOLVER_FOUND:
943
604
      char ip[AVAHI_ADDRESS_STR_MAX];
944
605
      avahi_address_snprint(ip, sizeof(ip), address);
945
606
      if(debug){
946
 
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %"
947
 
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
948
 
                ip, (intmax_t)interface, port);
 
607
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s) on"
 
608
                " port %d\n", name, host_name, ip, port);
949
609
      }
950
 
      int ret = start_mandos_communication(ip, port, interface,
951
 
                                           avahi_proto_to_af(proto));
952
 
      if(ret == 0){
953
 
        avahi_simple_poll_quit(mc.simple_poll);
 
610
      int ret = start_mandos_communication(ip, port, interface, mc);
 
611
      if (ret == 0){
 
612
        exit(EXIT_SUCCESS);
954
613
      }
955
614
    }
956
615
  }
957
616
  avahi_s_service_resolver_free(r);
958
617
}
959
618
 
960
 
static void browse_callback(AvahiSServiceBrowser *b,
961
 
                            AvahiIfIndex interface,
962
 
                            AvahiProtocol protocol,
963
 
                            AvahiBrowserEvent event,
964
 
                            const char *name,
965
 
                            const char *type,
966
 
                            const char *domain,
967
 
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
968
 
                            flags,
969
 
                            AVAHI_GCC_UNUSED void* userdata){
970
 
  assert(b);
 
619
static void browse_callback( AvahiSServiceBrowser *b,
 
620
                             AvahiIfIndex interface,
 
621
                             AvahiProtocol protocol,
 
622
                             AvahiBrowserEvent event,
 
623
                             const char *name,
 
624
                             const char *type,
 
625
                             const char *domain,
 
626
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags flags,
 
627
                             void* userdata) {
 
628
  mandos_context *mc = userdata;
 
629
  assert(b);                    /* Spurious warning */
971
630
  
972
631
  /* Called whenever a new services becomes available on the LAN or
973
632
     is removed from the LAN */
974
633
  
975
 
  if(quit_now){
976
 
    return;
977
 
  }
978
 
  
979
 
  switch(event){
 
634
  switch (event) {
980
635
  default:
981
636
  case AVAHI_BROWSER_FAILURE:
982
 
    
983
 
    fprintf(stderr, "(Avahi browser) %s\n",
984
 
            avahi_strerror(avahi_server_errno(mc.server)));
985
 
    avahi_simple_poll_quit(mc.simple_poll);
 
637
      
 
638
    fprintf(stderr, "(Browser) %s\n",
 
639
            avahi_strerror(avahi_server_errno(mc->server)));
 
640
    avahi_simple_poll_quit(mc->simple_poll);
986
641
    return;
987
 
    
 
642
      
988
643
  case AVAHI_BROWSER_NEW:
989
 
    /* We ignore the returned Avahi resolver object. In the callback
990
 
       function we free it. If the Avahi server is terminated before
991
 
       the callback function is called the Avahi server will free the
992
 
       resolver for us. */
993
 
    
994
 
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
995
 
                                    name, type, domain, protocol, 0,
996
 
                                    resolve_callback, NULL) == NULL)
997
 
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
998
 
              name, avahi_strerror(avahi_server_errno(mc.server)));
 
644
    /* We ignore the returned resolver object. In the callback
 
645
       function we free it. If the server is terminated before
 
646
       the callback function is called the server will free
 
647
       the resolver for us. */
 
648
      
 
649
    if (!(avahi_s_service_resolver_new(mc->server, interface, protocol, name,
 
650
                                       type, domain,
 
651
                                       AVAHI_PROTO_INET6, 0,
 
652
                                       resolve_callback, mc)))
 
653
      fprintf(stderr, "Failed to resolve service '%s': %s\n", name,
 
654
              avahi_strerror(avahi_server_errno(s)));
999
655
    break;
1000
 
    
 
656
      
1001
657
  case AVAHI_BROWSER_REMOVE:
1002
658
    break;
1003
 
    
 
659
      
1004
660
  case AVAHI_BROWSER_ALL_FOR_NOW:
1005
661
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1006
 
    if(debug){
1007
 
      fprintf(stderr, "No Mandos server found, still searching...\n");
1008
 
    }
1009
662
    break;
1010
663
  }
1011
664
}
1012
665
 
1013
 
/* stop main loop after sigterm has been called */
1014
 
static void handle_sigterm(int sig){
1015
 
  if(quit_now){
1016
 
    return;
1017
 
  }
1018
 
  quit_now = 1;
1019
 
  signal_received = sig;
1020
 
  int old_errno = errno;
1021
 
  if(mc.simple_poll != NULL){
1022
 
    avahi_simple_poll_quit(mc.simple_poll);
1023
 
  }
1024
 
  errno = old_errno;
1025
 
}
1026
 
 
1027
 
/* 
1028
 
 * This function determines if a directory entry in /sys/class/net
1029
 
 * corresponds to an acceptable network device.
1030
 
 * (This function is passed to scandir(3) as a filter function.)
1031
 
 */
1032
 
int good_interface(const struct dirent *if_entry){
1033
 
  ssize_t ssret;
1034
 
  char *flagname = NULL;
1035
 
  if(if_entry->d_name[0] == '.'){
1036
 
    return 0;
1037
 
  }
1038
 
  int ret = asprintf(&flagname, "%s/%s/flags", sys_class_net,
1039
 
                     if_entry->d_name);
1040
 
  if(ret < 0){
1041
 
    perror("asprintf");
1042
 
    return 0;
1043
 
  }
1044
 
  int flags_fd = (int)TEMP_FAILURE_RETRY(open(flagname, O_RDONLY));
1045
 
  if(flags_fd == -1){
1046
 
    perror("open");
1047
 
    free(flagname);
1048
 
    return 0;
1049
 
  }
1050
 
  free(flagname);
1051
 
  typedef short ifreq_flags;    /* ifreq.ifr_flags in netdevice(7) */
1052
 
  /* read line from flags_fd */
1053
 
  ssize_t to_read = (sizeof(ifreq_flags)*2)+3; /* "0x1003\n" */
1054
 
  char *flagstring = malloc((size_t)to_read+1); /* +1 for final \0 */
1055
 
  flagstring[(size_t)to_read] = '\0';
1056
 
  if(flagstring == NULL){
1057
 
    perror("malloc");
1058
 
    close(flags_fd);
1059
 
    return 0;
1060
 
  }
1061
 
  while(to_read > 0){
1062
 
    ssret = (ssize_t)TEMP_FAILURE_RETRY(read(flags_fd, flagstring,
1063
 
                                             (size_t)to_read));
1064
 
    if(ssret == -1){
1065
 
      perror("read");
1066
 
      free(flagstring);
1067
 
      close(flags_fd);
1068
 
      return 0;
1069
 
    }
1070
 
    to_read -= ssret;
1071
 
    if(ssret == 0){
1072
 
      break;
1073
 
    }
1074
 
  }
1075
 
  close(flags_fd);
1076
 
  intmax_t tmpmax;
1077
 
  char *tmp;
1078
 
  errno = 0;
1079
 
  tmpmax = strtoimax(flagstring, &tmp, 0);
1080
 
  if(errno != 0 or tmp == flagstring or (*tmp != '\0'
1081
 
                                         and not (isspace(*tmp)))
1082
 
     or tmpmax != (ifreq_flags)tmpmax){
1083
 
    if(debug){
1084
 
      fprintf(stderr, "Invalid flags \"%s\" for interface \"%s\"\n",
1085
 
              flagstring, if_entry->d_name);
1086
 
    }
1087
 
    free(flagstring);
1088
 
    return 0;
1089
 
  }
1090
 
  free(flagstring);
1091
 
  ifreq_flags flags = (ifreq_flags)tmpmax;
1092
 
  /* Reject the loopback device */
1093
 
  if(flags & IFF_LOOPBACK){
1094
 
    if(debug){
1095
 
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
1096
 
              if_entry->d_name);
1097
 
    }
1098
 
    return 0;
1099
 
  }
1100
 
  /* Accept point-to-point devices only if connect_to is specified */
1101
 
  if(connect_to != NULL and (flags & IFF_POINTOPOINT)){
1102
 
    if(debug){
1103
 
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
1104
 
              if_entry->d_name);
1105
 
    }
1106
 
    return 1;
1107
 
  }
1108
 
  /* Otherwise, reject non-broadcast-capable devices */
1109
 
  if(not (flags & IFF_BROADCAST)){
1110
 
    if(debug){
1111
 
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
1112
 
              if_entry->d_name);
1113
 
    }
1114
 
    return 0;
1115
 
  }
1116
 
  /* Reject non-ARP interfaces (including dummy interfaces) */
1117
 
  if(flags & IFF_NOARP){
1118
 
    if(debug){
1119
 
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n",
1120
 
              if_entry->d_name);
1121
 
    }
1122
 
    return 0;
1123
 
  }
1124
 
  /* Accept this device */
1125
 
  if(debug){
1126
 
    fprintf(stderr, "Interface \"%s\" is acceptable\n",
1127
 
            if_entry->d_name);
1128
 
  }
1129
 
  return 1;
1130
 
}
1131
 
 
1132
 
int main(int argc, char *argv[]){
1133
 
  AvahiSServiceBrowser *sb = NULL;
1134
 
  int error;
1135
 
  int ret;
1136
 
  intmax_t tmpmax;
1137
 
  char *tmp;
1138
 
  int exitcode = EXIT_SUCCESS;
1139
 
  const char *interface = "";
1140
 
  struct ifreq network;
1141
 
  int sd = -1;
1142
 
  bool take_down_interface = false;
1143
 
  uid_t uid;
1144
 
  gid_t gid;
1145
 
  char tempdir[] = "/tmp/mandosXXXXXX";
1146
 
  bool tempdir_created = false;
1147
 
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1148
 
  const char *seckey = PATHDIR "/" SECKEY;
1149
 
  const char *pubkey = PATHDIR "/" PUBKEY;
1150
 
  
1151
 
  bool gnutls_initialized = false;
1152
 
  bool gpgme_initialized = false;
1153
 
  float delay = 2.5f;
1154
 
  
1155
 
  struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
1156
 
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
1157
 
  
1158
 
  uid = getuid();
1159
 
  gid = getgid();
1160
 
  
1161
 
  /* Lower any group privileges we might have, just to be safe */
1162
 
  errno = 0;
1163
 
  ret = setgid(gid);
1164
 
  if(ret == -1){
1165
 
    perror("setgid");
1166
 
  }
1167
 
  
1168
 
  /* Lower user privileges (temporarily) */
1169
 
  errno = 0;
1170
 
  ret = seteuid(uid);
1171
 
  if(ret == -1){
1172
 
    perror("seteuid");
1173
 
  }
1174
 
  
1175
 
  if(quit_now){
1176
 
    goto end;
1177
 
  }
1178
 
  
1179
 
  {
1180
 
    struct argp_option options[] = {
1181
 
      { .name = "debug", .key = 128,
1182
 
        .doc = "Debug mode", .group = 3 },
1183
 
      { .name = "connect", .key = 'c',
1184
 
        .arg = "ADDRESS:PORT",
1185
 
        .doc = "Connect directly to a specific Mandos server",
1186
 
        .group = 1 },
1187
 
      { .name = "interface", .key = 'i',
1188
 
        .arg = "NAME",
1189
 
        .doc = "Network interface that will be used to search for"
1190
 
        " Mandos servers",
1191
 
        .group = 1 },
1192
 
      { .name = "seckey", .key = 's',
1193
 
        .arg = "FILE",
1194
 
        .doc = "OpenPGP secret key file base name",
1195
 
        .group = 1 },
1196
 
      { .name = "pubkey", .key = 'p',
1197
 
        .arg = "FILE",
1198
 
        .doc = "OpenPGP public key file base name",
1199
 
        .group = 2 },
1200
 
      { .name = "dh-bits", .key = 129,
1201
 
        .arg = "BITS",
1202
 
        .doc = "Bit length of the prime number used in the"
1203
 
        " Diffie-Hellman key exchange",
1204
 
        .group = 2 },
1205
 
      { .name = "priority", .key = 130,
1206
 
        .arg = "STRING",
1207
 
        .doc = "GnuTLS priority string for the TLS handshake",
1208
 
        .group = 1 },
1209
 
      { .name = "delay", .key = 131,
1210
 
        .arg = "SECONDS",
1211
 
        .doc = "Maximum delay to wait for interface startup",
1212
 
        .group = 2 },
1213
 
      /*
1214
 
       * These reproduce what we would get without ARGP_NO_HELP
1215
 
       */
1216
 
      { .name = "help", .key = '?',
1217
 
        .doc = "Give this help list", .group = -1 },
1218
 
      { .name = "usage", .key = -3,
1219
 
        .doc = "Give a short usage message", .group = -1 },
1220
 
      { .name = "version", .key = 'V',
1221
 
        .doc = "Print program version", .group = -1 },
1222
 
      { .name = NULL }
1223
 
    };
 
666
/* Combines file name and path and returns the malloced new
 
667
   string. some sane checks could/should be added */
 
668
static const char *combinepath(const char *first, const char *second){
 
669
  size_t f_len = strlen(first);
 
670
  size_t s_len = strlen(second);
 
671
  char *tmp = malloc(f_len + s_len + 2);
 
672
  if (tmp == NULL){
 
673
    return NULL;
 
674
  }
 
675
  if(f_len > 0){
 
676
    memcpy(tmp, first, f_len);
 
677
  }
 
678
  tmp[f_len] = '/';
 
679
  if(s_len > 0){
 
680
    memcpy(tmp + f_len + 1, second, s_len);
 
681
  }
 
682
  tmp[f_len + 1 + s_len] = '\0';
 
683
  return tmp;
 
684
}
 
685
 
 
686
 
 
687
int main(AVAHI_GCC_UNUSED int argc, AVAHI_GCC_UNUSED char*argv[]) {
 
688
    AvahiServerConfig config;
 
689
    AvahiSServiceBrowser *sb = NULL;
 
690
    int error;
 
691
    int ret;
 
692
    int returncode = EXIT_SUCCESS;
 
693
    const char *interface = "eth0";
 
694
    struct ifreq network;
 
695
    int sd;
 
696
    char *connect_to = NULL;
 
697
    AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
 
698
    mandos_context mc = { .simple_poll = NULL, .server = NULL,
 
699
                          .dh_bits = 2048, .priority = "SECURE256"};
1224
700
    
1225
 
    error_t parse_opt(int key, char *arg,
1226
 
                      struct argp_state *state){
1227
 
      errno = 0;
1228
 
      switch(key){
1229
 
      case 128:                 /* --debug */
1230
 
        debug = true;
1231
 
        break;
1232
 
      case 'c':                 /* --connect */
1233
 
        connect_to = arg;
1234
 
        break;
1235
 
      case 'i':                 /* --interface */
1236
 
        interface = arg;
1237
 
        break;
1238
 
      case 's':                 /* --seckey */
1239
 
        seckey = arg;
1240
 
        break;
1241
 
      case 'p':                 /* --pubkey */
1242
 
        pubkey = arg;
1243
 
        break;
1244
 
      case 129:                 /* --dh-bits */
1245
 
        errno = 0;
1246
 
        tmpmax = strtoimax(arg, &tmp, 10);
1247
 
        if(errno != 0 or tmp == arg or *tmp != '\0'
1248
 
           or tmpmax != (typeof(mc.dh_bits))tmpmax){
1249
 
          argp_error(state, "Bad number of DH bits");
1250
 
        }
1251
 
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
1252
 
        break;
1253
 
      case 130:                 /* --priority */
1254
 
        mc.priority = arg;
1255
 
        break;
1256
 
      case 131:                 /* --delay */
1257
 
        errno = 0;
1258
 
        delay = strtof(arg, &tmp);
1259
 
        if(errno != 0 or tmp == arg or *tmp != '\0'){
1260
 
          argp_error(state, "Bad delay");
1261
 
        }
1262
 
        break;
1263
 
        /*
1264
 
         * These reproduce what we would get without ARGP_NO_HELP
1265
 
         */
1266
 
      case '?':                 /* --help */
1267
 
        argp_state_help(state, state->out_stream,
1268
 
                        (ARGP_HELP_STD_HELP | ARGP_HELP_EXIT_ERR)
1269
 
                        & ~(unsigned int)ARGP_HELP_EXIT_OK);
1270
 
      case -3:                  /* --usage */
1271
 
        argp_state_help(state, state->out_stream,
1272
 
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1273
 
      case 'V':                 /* --version */
1274
 
        fprintf(state->out_stream, "%s\n", argp_program_version);
1275
 
        exit(argp_err_exit_status);
 
701
    while (true){
 
702
      static struct option long_options[] = {
 
703
        {"debug", no_argument, (int *)&debug, 1},
 
704
        {"connect", required_argument, 0, 'C'},
 
705
        {"interface", required_argument, 0, 'i'},
 
706
        {"certdir", required_argument, 0, 'd'},
 
707
        {"certkey", required_argument, 0, 'c'},
 
708
        {"certfile", required_argument, 0, 'k'},
 
709
        {"dh_bits", required_argument, 0, 'D'},
 
710
        {"priority", required_argument, 0, 'p'},
 
711
        {0, 0, 0, 0} };
 
712
      
 
713
      int option_index = 0;
 
714
      ret = getopt_long (argc, argv, "i:", long_options,
 
715
                         &option_index);
 
716
      
 
717
      if (ret == -1){
 
718
        break;
 
719
      }
 
720
      
 
721
      switch(ret){
 
722
      case 0:
 
723
        break;
 
724
      case 'i':
 
725
        interface = optarg;
 
726
        break;
 
727
      case 'C':
 
728
        connect_to = optarg;
 
729
        break;
 
730
      case 'd':
 
731
        certdir = optarg;
 
732
        break;
 
733
      case 'c':
 
734
        certfile = optarg;
 
735
        break;
 
736
      case 'k':
 
737
        certkey = optarg;
 
738
        break;
 
739
      case 'D':
 
740
        {
 
741
          long int tmp;
 
742
          errno = 0;
 
743
          tmp = strtol(optarg, NULL, 10);
 
744
          if (errno == ERANGE){
 
745
            perror("strtol");
 
746
            exit(EXIT_FAILURE);
 
747
          }
 
748
          mc.dh_bits = tmp;
 
749
        }
 
750
        break;
 
751
      case 'p':
 
752
        mc.priority = optarg;
1276
753
        break;
1277
754
      default:
1278
 
        return ARGP_ERR_UNKNOWN;
 
755
        exit(EXIT_FAILURE);
1279
756
      }
1280
 
      return errno;
1281
757
    }
1282
758
    
1283
 
    struct argp argp = { .options = options, .parser = parse_opt,
1284
 
                         .args_doc = "",
1285
 
                         .doc = "Mandos client -- Get and decrypt"
1286
 
                         " passwords from a Mandos server" };
1287
 
    ret = argp_parse(&argp, argc, argv,
1288
 
                     ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
1289
 
    switch(ret){
1290
 
    case 0:
1291
 
      break;
1292
 
    case ENOMEM:
1293
 
    default:
1294
 
      errno = ret;
1295
 
      perror("argp_parse");
1296
 
      exitcode = EX_OSERR;
1297
 
      goto end;
1298
 
    case EINVAL:
1299
 
      exitcode = EX_USAGE;
1300
 
      goto end;
 
759
    certfile = combinepath(certdir, certfile);
 
760
    if (certfile == NULL){
 
761
      perror("combinepath");
 
762
      returncode = EXIT_FAILURE;
 
763
      goto exit;
1301
764
    }
1302
 
  }
1303
 
  
1304
 
  if(not debug){
1305
 
    avahi_set_log_function(empty_log);
1306
 
  }
1307
765
 
1308
 
  if(interface[0] == '\0'){
1309
 
    struct dirent **direntries;
1310
 
    ret = scandir(sys_class_net, &direntries, good_interface,
1311
 
                  alphasort);
1312
 
    if(ret >= 1){
1313
 
      /* Pick the first good interface */
1314
 
      interface = strdup(direntries[0]->d_name);
1315
 
      if(debug){
1316
 
        fprintf(stderr, "Using interface \"%s\"\n", interface);
1317
 
      }
1318
 
      if(interface == NULL){
1319
 
        perror("malloc");
1320
 
        free(direntries);
1321
 
        exitcode = EXIT_FAILURE;
1322
 
        goto end;
1323
 
      }
1324
 
      free(direntries);
1325
 
    } else {
1326
 
      free(direntries);
1327
 
      fprintf(stderr, "Could not find a network interface\n");
1328
 
      exitcode = EXIT_FAILURE;
1329
 
      goto end;
1330
 
    }
1331
 
  }
1332
 
  
1333
 
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
1334
 
     from the signal handler */
1335
 
  /* Initialize the pseudo-RNG for Avahi */
1336
 
  srand((unsigned int) time(NULL));
1337
 
  mc.simple_poll = avahi_simple_poll_new();
1338
 
  if(mc.simple_poll == NULL){
1339
 
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
1340
 
    exitcode = EX_UNAVAILABLE;
1341
 
    goto end;
1342
 
  }
1343
 
  
1344
 
  sigemptyset(&sigterm_action.sa_mask);
1345
 
  ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
1346
 
  if(ret == -1){
1347
 
    perror("sigaddset");
1348
 
    exitcode = EX_OSERR;
1349
 
    goto end;
1350
 
  }
1351
 
  ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
1352
 
  if(ret == -1){
1353
 
    perror("sigaddset");
1354
 
    exitcode = EX_OSERR;
1355
 
    goto end;
1356
 
  }
1357
 
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
1358
 
  if(ret == -1){
1359
 
    perror("sigaddset");
1360
 
    exitcode = EX_OSERR;
1361
 
    goto end;
1362
 
  }
1363
 
  /* Need to check if the handler is SIG_IGN before handling:
1364
 
     | [[info:libc:Initial Signal Actions]] |
1365
 
     | [[info:libc:Basic Signal Handling]]  |
1366
 
  */
1367
 
  ret = sigaction(SIGINT, NULL, &old_sigterm_action);
1368
 
  if(ret == -1){
1369
 
    perror("sigaction");
1370
 
    return EX_OSERR;
1371
 
  }
1372
 
  if(old_sigterm_action.sa_handler != SIG_IGN){
1373
 
    ret = sigaction(SIGINT, &sigterm_action, NULL);
1374
 
    if(ret == -1){
1375
 
      perror("sigaction");
1376
 
      exitcode = EX_OSERR;
1377
 
      goto end;
1378
 
    }
1379
 
  }
1380
 
  ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
1381
 
  if(ret == -1){
1382
 
    perror("sigaction");
1383
 
    return EX_OSERR;
1384
 
  }
1385
 
  if(old_sigterm_action.sa_handler != SIG_IGN){
1386
 
    ret = sigaction(SIGHUP, &sigterm_action, NULL);
1387
 
    if(ret == -1){
1388
 
      perror("sigaction");
1389
 
      exitcode = EX_OSERR;
1390
 
      goto end;
1391
 
    }
1392
 
  }
1393
 
  ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
1394
 
  if(ret == -1){
1395
 
    perror("sigaction");
1396
 
    return EX_OSERR;
1397
 
  }
1398
 
  if(old_sigterm_action.sa_handler != SIG_IGN){
1399
 
    ret = sigaction(SIGTERM, &sigterm_action, NULL);
1400
 
    if(ret == -1){
1401
 
      perror("sigaction");
1402
 
      exitcode = EX_OSERR;
1403
 
      goto end;
1404
 
    }
1405
 
  }
1406
 
  
1407
 
  /* If the interface is down, bring it up */
1408
 
  if(strcmp(interface, "none") != 0){
 
766
    certkey = combinepath(certdir, certkey);
 
767
    if (certkey == NULL){
 
768
      perror("combinepath");
 
769
      returncode = EXIT_FAILURE;
 
770
      goto exit;
 
771
    }
 
772
    
1409
773
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1410
774
    if(if_index == 0){
1411
775
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
1412
 
      exitcode = EX_UNAVAILABLE;
1413
 
      goto end;
1414
 
    }
1415
 
    
1416
 
    if(quit_now){
1417
 
      goto end;
1418
 
    }
1419
 
    
1420
 
    /* Re-raise priviliges */
1421
 
    errno = 0;
1422
 
    ret = seteuid(0);
1423
 
    if(ret == -1){
1424
 
      perror("seteuid");
1425
 
    }
1426
 
    
1427
 
#ifdef __linux__
1428
 
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1429
 
       messages about the network interface to mess up the prompt */
1430
 
    ret = klogctl(8, NULL, 5);
1431
 
    bool restore_loglevel = true;
1432
 
    if(ret == -1){
1433
 
      restore_loglevel = false;
1434
 
      perror("klogctl");
1435
 
    }
1436
 
#endif  /* __linux__ */
 
776
      exit(EXIT_FAILURE);
 
777
    }
 
778
    
 
779
    if(connect_to != NULL){
 
780
      /* Connect directly, do not use Zeroconf */
 
781
      /* (Mainly meant for debugging) */
 
782
      char *address = strrchr(connect_to, ':');
 
783
      if(address == NULL){
 
784
        fprintf(stderr, "No colon in address\n");
 
785
        exit(EXIT_FAILURE);
 
786
      }
 
787
      errno = 0;
 
788
      uint16_t port = (uint16_t) strtol(address+1, NULL, 10);
 
789
      if(errno){
 
790
        perror("Bad port number");
 
791
        exit(EXIT_FAILURE);
 
792
      }
 
793
      *address = '\0';
 
794
      address = connect_to;
 
795
      ret = start_mandos_communication(address, port, if_index);
 
796
      if(ret < 0){
 
797
        exit(EXIT_FAILURE);
 
798
      } else {
 
799
        exit(EXIT_SUCCESS);
 
800
      }
 
801
    }
1437
802
    
1438
803
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1439
 
    if(sd < 0){
 
804
    if(sd < 0) {
1440
805
      perror("socket");
1441
 
      exitcode = EX_OSERR;
1442
 
#ifdef __linux__
1443
 
      if(restore_loglevel){
1444
 
        ret = klogctl(7, NULL, 0);
1445
 
        if(ret == -1){
1446
 
          perror("klogctl");
1447
 
        }
1448
 
      }
1449
 
#endif  /* __linux__ */
1450
 
      /* Lower privileges */
1451
 
      errno = 0;
1452
 
      ret = seteuid(uid);
1453
 
      if(ret == -1){
1454
 
        perror("seteuid");
1455
 
      }
1456
 
      goto end;
 
806
      returncode = EXIT_FAILURE;
 
807
      goto exit;
1457
808
    }
1458
 
    strcpy(network.ifr_name, interface);
 
809
    strcpy(network.ifr_name, interface);    
1459
810
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
1460
811
    if(ret == -1){
 
812
      
1461
813
      perror("ioctl SIOCGIFFLAGS");
1462
 
#ifdef __linux__
1463
 
      if(restore_loglevel){
1464
 
        ret = klogctl(7, NULL, 0);
1465
 
        if(ret == -1){
1466
 
          perror("klogctl");
1467
 
        }
1468
 
      }
1469
 
#endif  /* __linux__ */
1470
 
      exitcode = EX_OSERR;
1471
 
      /* Lower privileges */
1472
 
      errno = 0;
1473
 
      ret = seteuid(uid);
1474
 
      if(ret == -1){
1475
 
        perror("seteuid");
1476
 
      }
1477
 
      goto end;
 
814
      returncode = EXIT_FAILURE;
 
815
      goto exit;
1478
816
    }
1479
817
    if((network.ifr_flags & IFF_UP) == 0){
1480
818
      network.ifr_flags |= IFF_UP;
1481
 
      take_down_interface = true;
1482
819
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1483
820
      if(ret == -1){
1484
 
        take_down_interface = false;
1485
 
        perror("ioctl SIOCSIFFLAGS +IFF_UP");
1486
 
        exitcode = EX_OSERR;
1487
 
#ifdef __linux__
1488
 
        if(restore_loglevel){
1489
 
          ret = klogctl(7, NULL, 0);
1490
 
          if(ret == -1){
1491
 
            perror("klogctl");
1492
 
          }
1493
 
        }
1494
 
#endif  /* __linux__ */
1495
 
        /* Lower privileges */
1496
 
        errno = 0;
1497
 
        ret = seteuid(uid);
1498
 
        if(ret == -1){
1499
 
          perror("seteuid");
1500
 
        }
1501
 
        goto end;
1502
 
      }
1503
 
    }
1504
 
    /* sleep checking until interface is running */
1505
 
    for(int i=0; i < delay * 4; i++){
1506
 
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1507
 
      if(ret == -1){
1508
 
        perror("ioctl SIOCGIFFLAGS");
1509
 
      } else if(network.ifr_flags & IFF_RUNNING){
1510
 
        break;
1511
 
      }
1512
 
      struct timespec sleeptime = { .tv_nsec = 250000000 };
1513
 
      ret = nanosleep(&sleeptime, NULL);
1514
 
      if(ret == -1 and errno != EINTR){
1515
 
        perror("nanosleep");
1516
 
      }
1517
 
    }
1518
 
    if(not take_down_interface){
1519
 
      /* We won't need the socket anymore */
1520
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1521
 
      if(ret == -1){
1522
 
        perror("close");
1523
 
      }
1524
 
    }
1525
 
#ifdef __linux__
1526
 
    if(restore_loglevel){
1527
 
      /* Restores kernel loglevel to default */
1528
 
      ret = klogctl(7, NULL, 0);
1529
 
      if(ret == -1){
1530
 
        perror("klogctl");
1531
 
      }
1532
 
    }
1533
 
#endif  /* __linux__ */
1534
 
    /* Lower privileges */
1535
 
    errno = 0;
1536
 
    if(take_down_interface){
1537
 
      /* Lower privileges */
1538
 
      ret = seteuid(uid);
1539
 
      if(ret == -1){
1540
 
        perror("seteuid");
1541
 
      }
1542
 
    } else {
1543
 
      /* Lower privileges permanently */
1544
 
      ret = setuid(uid);
1545
 
      if(ret == -1){
1546
 
        perror("setuid");
1547
 
      }
1548
 
    }
1549
 
  }
1550
 
  
1551
 
  if(quit_now){
1552
 
    goto end;
1553
 
  }
1554
 
  
1555
 
  ret = init_gnutls_global(pubkey, seckey);
1556
 
  if(ret == -1){
1557
 
    fprintf(stderr, "init_gnutls_global failed\n");
1558
 
    exitcode = EX_UNAVAILABLE;
1559
 
    goto end;
1560
 
  } else {
1561
 
    gnutls_initialized = true;
1562
 
  }
1563
 
  
1564
 
  if(quit_now){
1565
 
    goto end;
1566
 
  }
1567
 
  
1568
 
  tempdir_created = true;
1569
 
  if(mkdtemp(tempdir) == NULL){
1570
 
    tempdir_created = false;
1571
 
    perror("mkdtemp");
1572
 
    goto end;
1573
 
  }
1574
 
  
1575
 
  if(quit_now){
1576
 
    goto end;
1577
 
  }
1578
 
  
1579
 
  if(not init_gpgme(pubkey, seckey, tempdir)){
1580
 
    fprintf(stderr, "init_gpgme failed\n");
1581
 
    exitcode = EX_UNAVAILABLE;
1582
 
    goto end;
1583
 
  } else {
1584
 
    gpgme_initialized = true;
1585
 
  }
1586
 
  
1587
 
  if(quit_now){
1588
 
    goto end;
1589
 
  }
1590
 
  
1591
 
  if(connect_to != NULL){
1592
 
    /* Connect directly, do not use Zeroconf */
1593
 
    /* (Mainly meant for debugging) */
1594
 
    char *address = strrchr(connect_to, ':');
1595
 
    if(address == NULL){
1596
 
      fprintf(stderr, "No colon in address\n");
1597
 
      exitcode = EX_USAGE;
1598
 
      goto end;
1599
 
    }
1600
 
    
1601
 
    if(quit_now){
1602
 
      goto end;
1603
 
    }
1604
 
    
1605
 
    uint16_t port;
1606
 
    errno = 0;
1607
 
    tmpmax = strtoimax(address+1, &tmp, 10);
1608
 
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
1609
 
       or tmpmax != (uint16_t)tmpmax){
1610
 
      fprintf(stderr, "Bad port number\n");
1611
 
      exitcode = EX_USAGE;
1612
 
      goto end;
1613
 
    }
1614
 
  
1615
 
    if(quit_now){
1616
 
      goto end;
1617
 
    }
1618
 
    
1619
 
    port = (uint16_t)tmpmax;
1620
 
    *address = '\0';
1621
 
    address = connect_to;
1622
 
    /* Colon in address indicates IPv6 */
1623
 
    int af;
1624
 
    if(strchr(address, ':') != NULL){
1625
 
      af = AF_INET6;
1626
 
    } else {
1627
 
      af = AF_INET;
1628
 
    }
1629
 
    
1630
 
    if(quit_now){
1631
 
      goto end;
1632
 
    }
1633
 
 
1634
 
    while(not quit_now){
1635
 
      ret = start_mandos_communication(address, port, if_index, af);
1636
 
      if(quit_now or ret == 0){
1637
 
        break;
1638
 
      }
1639
 
      sleep(15);
1640
 
    };
1641
 
 
1642
 
    if (not quit_now){
1643
 
      exitcode = EXIT_SUCCESS;
1644
 
    }
1645
 
 
1646
 
    goto end;
1647
 
  }
1648
 
  
1649
 
  if(quit_now){
1650
 
    goto end;
1651
 
  }
1652
 
  
1653
 
  {
1654
 
    AvahiServerConfig config;
1655
 
    /* Do not publish any local Zeroconf records */
 
821
        perror("ioctl SIOCSIFFLAGS");
 
822
        returncode = EXIT_FAILURE;
 
823
        goto exit;
 
824
      }
 
825
    }
 
826
    close(sd);
 
827
    
 
828
    if (not debug){
 
829
      avahi_set_log_function(empty_log);
 
830
    }
 
831
    
 
832
    /* Initialize the psuedo-RNG */
 
833
    srand((unsigned int) time(NULL));
 
834
 
 
835
    /* Allocate main loop object */
 
836
    if (!(mc.simple_poll = avahi_simple_poll_new())) {
 
837
        fprintf(stderr, "Failed to create simple poll object.\n");
 
838
        returncode = EXIT_FAILURE;      
 
839
        goto exit;
 
840
    }
 
841
 
 
842
    /* Do not publish any local records */
1656
843
    avahi_server_config_init(&config);
1657
844
    config.publish_hinfo = 0;
1658
845
    config.publish_addresses = 0;
1659
846
    config.publish_workstation = 0;
1660
847
    config.publish_domain = 0;
1661
 
    
 
848
 
1662
849
    /* Allocate a new server */
1663
 
    mc.server = avahi_server_new(avahi_simple_poll_get
1664
 
                                 (mc.simple_poll), &config, NULL,
1665
 
                                 NULL, &error);
1666
 
    
1667
 
    /* Free the Avahi configuration data */
 
850
    mc.server = avahi_server_new(avahi_simple_poll_get(simple_poll),
 
851
                              &config, NULL, NULL, &error);
 
852
 
 
853
    /* Free the configuration data */
1668
854
    avahi_server_config_free(&config);
1669
 
  }
1670
 
  
1671
 
  /* Check if creating the Avahi server object succeeded */
1672
 
  if(mc.server == NULL){
1673
 
    fprintf(stderr, "Failed to create Avahi server: %s\n",
1674
 
            avahi_strerror(error));
1675
 
    exitcode = EX_UNAVAILABLE;
1676
 
    goto end;
1677
 
  }
1678
 
  
1679
 
  if(quit_now){
1680
 
    goto end;
1681
 
  }
1682
 
  
1683
 
  /* Create the Avahi service browser */
1684
 
  sb = avahi_s_service_browser_new(mc.server, if_index,
1685
 
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
1686
 
                                   NULL, 0, browse_callback, NULL);
1687
 
  if(sb == NULL){
1688
 
    fprintf(stderr, "Failed to create service browser: %s\n",
1689
 
            avahi_strerror(avahi_server_errno(mc.server)));
1690
 
    exitcode = EX_UNAVAILABLE;
1691
 
    goto end;
1692
 
  }
1693
 
  
1694
 
  if(quit_now){
1695
 
    goto end;
1696
 
  }
1697
 
  
1698
 
  /* Run the main loop */
1699
 
  
1700
 
  if(debug){
1701
 
    fprintf(stderr, "Starting Avahi loop search\n");
1702
 
  }
1703
 
  
1704
 
  avahi_simple_poll_loop(mc.simple_poll);
1705
 
  
1706
 
 end:
1707
 
  
1708
 
  if(debug){
1709
 
    fprintf(stderr, "%s exiting\n", argv[0]);
1710
 
  }
1711
 
  
1712
 
  /* Cleanup things */
1713
 
  if(sb != NULL)
1714
 
    avahi_s_service_browser_free(sb);
1715
 
  
1716
 
  if(mc.server != NULL)
1717
 
    avahi_server_free(mc.server);
1718
 
  
1719
 
  if(mc.simple_poll != NULL)
1720
 
    avahi_simple_poll_free(mc.simple_poll);
1721
 
  
1722
 
  if(gnutls_initialized){
1723
 
    gnutls_certificate_free_credentials(mc.cred);
1724
 
    gnutls_global_deinit();
1725
 
    gnutls_dh_params_deinit(mc.dh_params);
1726
 
  }
1727
 
  
1728
 
  if(gpgme_initialized){
1729
 
    gpgme_release(mc.ctx);
1730
 
  }
1731
 
  
1732
 
  /* Take down the network interface */
1733
 
  if(take_down_interface){
1734
 
    /* Re-raise priviliges */
1735
 
    errno = 0;
1736
 
    ret = seteuid(0);
1737
 
    if(ret == -1){
1738
 
      perror("seteuid");
1739
 
    }
1740
 
    if(geteuid() == 0){
1741
 
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1742
 
      if(ret == -1){
1743
 
        perror("ioctl SIOCGIFFLAGS");
1744
 
      } else if(network.ifr_flags & IFF_UP) {
1745
 
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
1746
 
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
1747
 
        if(ret == -1){
1748
 
          perror("ioctl SIOCSIFFLAGS -IFF_UP");
1749
 
        }
1750
 
      }
1751
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1752
 
      if(ret == -1){
1753
 
        perror("close");
1754
 
      }
1755
 
      /* Lower privileges permanently */
1756
 
      errno = 0;
1757
 
      ret = setuid(uid);
1758
 
      if(ret == -1){
1759
 
        perror("setuid");
1760
 
      }
1761
 
    }
1762
 
  }
1763
 
  
1764
 
  /* Removes the temp directory used by GPGME */
1765
 
  if(tempdir_created){
1766
 
    DIR *d;
1767
 
    struct dirent *direntry;
1768
 
    d = opendir(tempdir);
1769
 
    if(d == NULL){
1770
 
      if(errno != ENOENT){
1771
 
        perror("opendir");
1772
 
      }
1773
 
    } else {
1774
 
      while(true){
1775
 
        direntry = readdir(d);
1776
 
        if(direntry == NULL){
1777
 
          break;
1778
 
        }
1779
 
        /* Skip "." and ".." */
1780
 
        if(direntry->d_name[0] == '.'
1781
 
           and (direntry->d_name[1] == '\0'
1782
 
                or (direntry->d_name[1] == '.'
1783
 
                    and direntry->d_name[2] == '\0'))){
1784
 
          continue;
1785
 
        }
1786
 
        char *fullname = NULL;
1787
 
        ret = asprintf(&fullname, "%s/%s", tempdir,
1788
 
                       direntry->d_name);
1789
 
        if(ret < 0){
1790
 
          perror("asprintf");
1791
 
          continue;
1792
 
        }
1793
 
        ret = remove(fullname);
1794
 
        if(ret == -1){
1795
 
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
1796
 
                  strerror(errno));
1797
 
        }
1798
 
        free(fullname);
1799
 
      }
1800
 
      closedir(d);
1801
 
    }
1802
 
    ret = rmdir(tempdir);
1803
 
    if(ret == -1 and errno != ENOENT){
1804
 
      perror("rmdir");
1805
 
    }
1806
 
  }
1807
 
  
1808
 
  if(quit_now){
1809
 
    sigemptyset(&old_sigterm_action.sa_mask);
1810
 
    old_sigterm_action.sa_handler = SIG_DFL;
1811
 
    ret = (int)TEMP_FAILURE_RETRY(sigaction(signal_received,
1812
 
                                            &old_sigterm_action,
1813
 
                                            NULL));
1814
 
    if(ret == -1){
1815
 
      perror("sigaction");
1816
 
    }
1817
 
    do {
1818
 
      ret = raise(signal_received);
1819
 
    } while(ret != 0 and errno == EINTR);
1820
 
    if(ret != 0){
1821
 
      perror("raise");
1822
 
      abort();
1823
 
    }
1824
 
    TEMP_FAILURE_RETRY(pause());
1825
 
  }
1826
 
  
1827
 
  return exitcode;
 
855
 
 
856
    /* Check if creating the server object succeeded */
 
857
    if (!mc.server) {
 
858
        fprintf(stderr, "Failed to create server: %s\n",
 
859
                avahi_strerror(error));
 
860
        returncode = EXIT_FAILURE;
 
861
        goto exit;
 
862
    }
 
863
    
 
864
    /* Create the service browser */
 
865
    sb = avahi_s_service_browser_new(mc.server, if_index,
 
866
                                     AVAHI_PROTO_INET6,
 
867
                                     "_mandos._tcp", NULL, 0,
 
868
                                     browse_callback, &mc);
 
869
    if (!sb) {
 
870
        fprintf(stderr, "Failed to create service browser: %s\n",
 
871
                avahi_strerror(avahi_server_errno(mc.server)));
 
872
        returncode = EXIT_FAILURE;
 
873
        goto exit;
 
874
    }
 
875
    
 
876
    /* Run the main loop */
 
877
 
 
878
    if (debug){
 
879
      fprintf(stderr, "Starting avahi loop search\n");
 
880
    }
 
881
    
 
882
    avahi_simple_poll_loop(simple_poll);
 
883
    
 
884
 exit:
 
885
 
 
886
    if (debug){
 
887
      fprintf(stderr, "%s exiting\n", argv[0]);
 
888
    }
 
889
    
 
890
    /* Cleanup things */
 
891
    if (sb)
 
892
        avahi_s_service_browser_free(sb);
 
893
    
 
894
    if (mc.server)
 
895
        avahi_server_free(mc.server);
 
896
 
 
897
    if (simple_poll)
 
898
        avahi_simple_poll_free(simple_poll);
 
899
    free(certfile);
 
900
    free(certkey);
 
901
    
 
902
    return returncode;
1828
903
}