/mandos/release

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

« back to all changes in this revision

Viewing changes to plugins.d/mandos-client.c

* plugin-runner.c (main): When a plugin is killed by a signal, show
                          the signal name, not just the number, in the
                          debug log message.

* plugins.d/password-prompt.c (termination_handler): Store received
                                                     signal in
                                                     "signal_received".
  (main): If exiting due to signal, re-raise signal received instead
          of returning.

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