/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

  • Committer: Björn Påhlsson
  • Date: 2011-11-14 19:10:50 UTC
  • mto: (237.16.9 client-network-hooks)
  • mto: This revision was merged to the branch mainline in revision 290.
  • Revision ID: belorn@fukt.bsnet.se-20111114191050-g11po6084bl9j5kf
replace calls to fprintf with fprintf_plus.

Show diffs side-by-side

added added

removed removed

Lines of Context:
9
9
 * "browse_callback", and parts of "main".
10
10
 * 
11
11
 * Everything else is
12
 
 * Copyright © 2008-2010 Teddy Hogeborn
13
 
 * Copyright © 2008-2010 Björn Påhlsson
 
12
 * Copyright © 2008-2011 Teddy Hogeborn
 
13
 * Copyright © 2008-2011 Björn Påhlsson
14
14
 * 
15
15
 * This program is free software: you can redistribute it and/or
16
16
 * modify it under the terms of the GNU General Public License as
26
26
 * along with this program.  If not, see
27
27
 * <http://www.gnu.org/licenses/>.
28
28
 * 
29
 
 * Contact the authors at <mandos@fukt.bsnet.se>.
 
29
 * Contact the authors at <mandos@recompile.se>.
30
30
 */
31
31
 
32
32
/* Needed by GPGME, specifically gpgme_data_seek() */
53
53
                                   sockaddr_in6, PF_INET6,
54
54
                                   SOCK_STREAM, uid_t, gid_t, open(),
55
55
                                   opendir(), DIR */
56
 
#include <sys/stat.h>           /* open() */
 
56
#include <sys/stat.h>           /* open(), S_ISREG */
57
57
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
58
58
                                   inet_pton(), connect() */
59
59
#include <fcntl.h>              /* open() */
62
62
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
63
63
                                   strtoimax() */
64
64
#include <assert.h>             /* assert() */
65
 
#include <errno.h>              /* perror(), errno */
 
65
#include <errno.h>              /* perror(), errno,
 
66
                                   program_invocation_short_name */
66
67
#include <time.h>               /* nanosleep(), time(), sleep() */
67
68
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
68
69
                                   SIOCSIFFLAGS, if_indextoname(),
73
74
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
74
75
                                   getuid(), getgid(), seteuid(),
75
76
                                   setgid(), pause() */
76
 
#include <arpa/inet.h>          /* inet_pton(), htons */
 
77
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
77
78
#include <iso646.h>             /* not, or, and */
78
79
#include <argp.h>               /* struct argp_option, error_t, struct
79
80
                                   argp_state, struct argp,
84
85
                                   raise() */
85
86
#include <sysexits.h>           /* EX_OSERR, EX_USAGE, EX_UNAVAILABLE,
86
87
                                   EX_NOHOST, EX_IOERR, EX_PROTOCOL */
 
88
#include <sys/wait.h>           /* waitpid(), WIFEXITED(),
 
89
                                   WEXITSTATUS(), WTERMSIG() */
87
90
 
88
91
#ifdef __linux__
89
92
#include <sys/klog.h>           /* klogctl() */
107
110
                                   init_gnutls_session(),
108
111
                                   GNUTLS_* */
109
112
#include <gnutls/openpgp.h>
110
 
                          /* gnutls_certificate_set_openpgp_key_file(),
111
 
                                   GNUTLS_OPENPGP_FMT_BASE64 */
 
113
                         /* gnutls_certificate_set_openpgp_key_file(),
 
114
                            GNUTLS_OPENPGP_FMT_BASE64 */
112
115
 
113
116
/* GPGME */
114
117
#include <gpgme.h>              /* All GPGME types, constants and
122
125
#define PATHDIR "/conf/conf.d/mandos"
123
126
#define SECKEY "seckey.txt"
124
127
#define PUBKEY "pubkey.txt"
 
128
#define HOOKDIR "/lib/mandos/network-hooks.d"
125
129
 
126
130
bool debug = false;
127
131
static const char mandos_protocol_version[] = "1";
128
132
const char *argp_program_version = "mandos-client " VERSION;
129
 
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
 
133
const char *argp_program_bug_address = "<mandos@recompile.se>";
130
134
static const char sys_class_net[] = "/sys/class/net";
131
135
char *connect_to = NULL;
 
136
const char *hookdir = HOOKDIR;
 
137
 
 
138
/* Doubly linked list that need to be circularly linked when used */
 
139
typedef struct server{
 
140
  const char *ip;
 
141
  uint16_t port;
 
142
  AvahiIfIndex if_index;
 
143
  int af;
 
144
  struct timespec last_seen;
 
145
  struct server *next;
 
146
  struct server *prev;
 
147
} server;
132
148
 
133
149
/* Used for passing in values through the Avahi callback functions */
134
150
typedef struct {
139
155
  gnutls_dh_params_t dh_params;
140
156
  const char *priority;
141
157
  gpgme_ctx_t ctx;
 
158
  server *current_server;
142
159
} mandos_context;
143
160
 
144
161
/* global context so signal handler can reach it*/
145
162
mandos_context mc = { .simple_poll = NULL, .server = NULL,
146
163
                      .dh_bits = 1024, .priority = "SECURE256"
147
 
                      ":!CTYPE-X.509:+CTYPE-OPENPGP" };
 
164
                      ":!CTYPE-X.509:+CTYPE-OPENPGP",
 
165
                      .current_server = NULL };
148
166
 
149
167
sig_atomic_t quit_now = 0;
150
168
int signal_received = 0;
151
169
 
 
170
/* Function to use when printing errors */
 
171
void perror_plus(const char *print_text){
 
172
  fprintf(stderr, "Mandos plugin %s: ",
 
173
          program_invocation_short_name);
 
174
  perror(print_text);
 
175
}
 
176
 
 
177
int fprintf_plus(FILE *stream, const char *format, ...){
 
178
  va_list ap;
 
179
  va_start (ap, format);
 
180
  
 
181
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ", program_invocation_short_name));
 
182
  return TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
 
183
}
 
184
 
152
185
/*
153
186
 * Make additional room in "buffer" for at least BUFFER_SIZE more
154
187
 * bytes. "buffer_capacity" is how much is currently allocated,
155
188
 * "buffer_length" is how much is already used.
156
189
 */
157
190
size_t incbuffer(char **buffer, size_t buffer_length,
158
 
                  size_t buffer_capacity){
 
191
                 size_t buffer_capacity){
159
192
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
160
193
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
161
194
    if(buffer == NULL){
166
199
  return buffer_capacity;
167
200
}
168
201
 
 
202
/* Add server to set of servers to retry periodically */
 
203
int add_server(const char *ip, uint16_t port, AvahiIfIndex if_index,
 
204
               int af){
 
205
  int ret;
 
206
  server *new_server = malloc(sizeof(server));
 
207
  if(new_server == NULL){
 
208
    perror_plus("malloc");
 
209
    return -1;
 
210
  }
 
211
  *new_server = (server){ .ip = strdup(ip),
 
212
                          .port = port,
 
213
                          .if_index = if_index,
 
214
                          .af = af };
 
215
  if(new_server->ip == NULL){
 
216
    perror_plus("strdup");
 
217
    return -1;
 
218
  }
 
219
  /* Special case of first server */
 
220
  if (mc.current_server == NULL){
 
221
    new_server->next = new_server;
 
222
    new_server->prev = new_server;
 
223
    mc.current_server = new_server;
 
224
  /* Place the new server last in the list */
 
225
  } else {
 
226
    new_server->next = mc.current_server;
 
227
    new_server->prev = mc.current_server->prev;
 
228
    new_server->prev->next = new_server;
 
229
    mc.current_server->prev = new_server;
 
230
  }
 
231
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
 
232
  if(ret == -1){
 
233
    perror_plus("clock_gettime");
 
234
    return -1;
 
235
  }
 
236
  return 0;
 
237
}
 
238
 
169
239
/* 
170
240
 * Initialize GPGME.
171
241
 */
172
 
static bool init_gpgme(const char *seckey,
173
 
                       const char *pubkey, const char *tempdir){
 
242
static bool init_gpgme(const char *seckey, const char *pubkey,
 
243
                       const char *tempdir){
174
244
  gpgme_error_t rc;
175
245
  gpgme_engine_info_t engine_info;
176
246
  
185
255
    
186
256
    fd = (int)TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
187
257
    if(fd == -1){
188
 
      perror("open");
 
258
      perror_plus("open");
189
259
      return false;
190
260
    }
191
261
    
192
262
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
193
263
    if(rc != GPG_ERR_NO_ERROR){
194
 
      fprintf(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
 
264
      fprintf_plus(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
195
265
              gpgme_strsource(rc), gpgme_strerror(rc));
196
266
      return false;
197
267
    }
198
268
    
199
269
    rc = gpgme_op_import(mc.ctx, pgp_data);
200
270
    if(rc != GPG_ERR_NO_ERROR){
201
 
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
 
271
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
202
272
              gpgme_strsource(rc), gpgme_strerror(rc));
203
273
      return false;
204
274
    }
205
275
    
206
276
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
207
277
    if(ret == -1){
208
 
      perror("close");
 
278
      perror_plus("close");
209
279
    }
210
280
    gpgme_data_release(pgp_data);
211
281
    return true;
212
282
  }
213
283
  
214
284
  if(debug){
215
 
    fprintf(stderr, "Initializing GPGME\n");
 
285
    fprintf_plus(stderr, "Initializing GPGME\n");
216
286
  }
217
287
  
218
288
  /* Init GPGME */
219
289
  gpgme_check_version(NULL);
220
290
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
221
291
  if(rc != GPG_ERR_NO_ERROR){
222
 
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
 
292
    fprintf_plus(stderr, "bad gpgme_engine_check_version: %s: %s\n",
223
293
            gpgme_strsource(rc), gpgme_strerror(rc));
224
294
    return false;
225
295
  }
226
296
  
227
 
    /* Set GPGME home directory for the OpenPGP engine only */
 
297
  /* Set GPGME home directory for the OpenPGP engine only */
228
298
  rc = gpgme_get_engine_info(&engine_info);
229
299
  if(rc != GPG_ERR_NO_ERROR){
230
 
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
 
300
    fprintf_plus(stderr, "bad gpgme_get_engine_info: %s: %s\n",
231
301
            gpgme_strsource(rc), gpgme_strerror(rc));
232
302
    return false;
233
303
  }
240
310
    engine_info = engine_info->next;
241
311
  }
242
312
  if(engine_info == NULL){
243
 
    fprintf(stderr, "Could not set GPGME home dir to %s\n", tempdir);
 
313
    fprintf_plus(stderr, "Could not set GPGME home dir to %s\n", tempdir);
244
314
    return false;
245
315
  }
246
316
  
247
317
  /* Create new GPGME "context" */
248
318
  rc = gpgme_new(&(mc.ctx));
249
319
  if(rc != GPG_ERR_NO_ERROR){
250
 
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
251
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
320
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
 
321
            "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
 
322
            gpgme_strerror(rc));
252
323
    return false;
253
324
  }
254
325
  
273
344
  ssize_t plaintext_length = 0;
274
345
  
275
346
  if(debug){
276
 
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
 
347
    fprintf_plus(stderr, "Trying to decrypt OpenPGP data\n");
277
348
  }
278
349
  
279
350
  /* Create new GPGME data buffer from memory cryptotext */
280
351
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
281
352
                               0);
282
353
  if(rc != GPG_ERR_NO_ERROR){
283
 
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
 
354
    fprintf_plus(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
284
355
            gpgme_strsource(rc), gpgme_strerror(rc));
285
356
    return -1;
286
357
  }
288
359
  /* Create new empty GPGME data buffer for the plaintext */
289
360
  rc = gpgme_data_new(&dh_plain);
290
361
  if(rc != GPG_ERR_NO_ERROR){
291
 
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
 
362
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
 
363
            "bad gpgme_data_new: %s: %s\n",
292
364
            gpgme_strsource(rc), gpgme_strerror(rc));
293
365
    gpgme_data_release(dh_crypto);
294
366
    return -1;
298
370
     data buffer */
299
371
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
300
372
  if(rc != GPG_ERR_NO_ERROR){
301
 
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
 
373
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
302
374
            gpgme_strsource(rc), gpgme_strerror(rc));
303
375
    plaintext_length = -1;
304
376
    if(debug){
305
377
      gpgme_decrypt_result_t result;
306
378
      result = gpgme_op_decrypt_result(mc.ctx);
307
379
      if(result == NULL){
308
 
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
 
380
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
309
381
      } else {
310
 
        fprintf(stderr, "Unsupported algorithm: %s\n",
 
382
        fprintf_plus(stderr, "Unsupported algorithm: %s\n",
311
383
                result->unsupported_algorithm);
312
 
        fprintf(stderr, "Wrong key usage: %u\n",
 
384
        fprintf_plus(stderr, "Wrong key usage: %u\n",
313
385
                result->wrong_key_usage);
314
386
        if(result->file_name != NULL){
315
 
          fprintf(stderr, "File name: %s\n", result->file_name);
 
387
          fprintf_plus(stderr, "File name: %s\n", result->file_name);
316
388
        }
317
389
        gpgme_recipient_t recipient;
318
390
        recipient = result->recipients;
319
391
        while(recipient != NULL){
320
 
          fprintf(stderr, "Public key algorithm: %s\n",
 
392
          fprintf_plus(stderr, "Public key algorithm: %s\n",
321
393
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
322
 
          fprintf(stderr, "Key ID: %s\n", recipient->keyid);
323
 
          fprintf(stderr, "Secret key available: %s\n",
 
394
          fprintf_plus(stderr, "Key ID: %s\n", recipient->keyid);
 
395
          fprintf_plus(stderr, "Secret key available: %s\n",
324
396
                  recipient->status == GPG_ERR_NO_SECKEY
325
397
                  ? "No" : "Yes");
326
398
          recipient = recipient->next;
331
403
  }
332
404
  
333
405
  if(debug){
334
 
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
 
406
    fprintf_plus(stderr, "Decryption of OpenPGP data succeeded\n");
335
407
  }
336
408
  
337
409
  /* Seek back to the beginning of the GPGME plaintext data buffer */
338
410
  if(gpgme_data_seek(dh_plain, (off_t)0, SEEK_SET) == -1){
339
 
    perror("gpgme_data_seek");
 
411
    perror_plus("gpgme_data_seek");
340
412
    plaintext_length = -1;
341
413
    goto decrypt_end;
342
414
  }
344
416
  *plaintext = NULL;
345
417
  while(true){
346
418
    plaintext_capacity = incbuffer(plaintext,
347
 
                                      (size_t)plaintext_length,
348
 
                                      plaintext_capacity);
 
419
                                   (size_t)plaintext_length,
 
420
                                   plaintext_capacity);
349
421
    if(plaintext_capacity == 0){
350
 
        perror("incbuffer");
351
 
        plaintext_length = -1;
352
 
        goto decrypt_end;
 
422
      perror_plus("incbuffer");
 
423
      plaintext_length = -1;
 
424
      goto decrypt_end;
353
425
    }
354
426
    
355
427
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
360
432
      break;
361
433
    }
362
434
    if(ret < 0){
363
 
      perror("gpgme_data_read");
 
435
      perror_plus("gpgme_data_read");
364
436
      plaintext_length = -1;
365
437
      goto decrypt_end;
366
438
    }
368
440
  }
369
441
  
370
442
  if(debug){
371
 
    fprintf(stderr, "Decrypted password is: ");
 
443
    fprintf_plus(stderr, "Decrypted password is: ");
372
444
    for(ssize_t i = 0; i < plaintext_length; i++){
373
445
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
374
446
    }
396
468
/* GnuTLS log function callback */
397
469
static void debuggnutls(__attribute__((unused)) int level,
398
470
                        const char* string){
399
 
  fprintf(stderr, "GnuTLS: %s", string);
 
471
  fprintf_plus(stderr, "GnuTLS: %s", string);
400
472
}
401
473
 
402
474
static int init_gnutls_global(const char *pubkeyfilename,
404
476
  int ret;
405
477
  
406
478
  if(debug){
407
 
    fprintf(stderr, "Initializing GnuTLS\n");
 
479
    fprintf_plus(stderr, "Initializing GnuTLS\n");
408
480
  }
409
481
  
410
482
  ret = gnutls_global_init();
411
483
  if(ret != GNUTLS_E_SUCCESS){
412
 
    fprintf(stderr, "GnuTLS global_init: %s\n",
413
 
            safer_gnutls_strerror(ret));
 
484
    fprintf_plus(stderr, "GnuTLS global_init: %s\n", safer_gnutls_strerror(ret));
414
485
    return -1;
415
486
  }
416
487
  
423
494
  }
424
495
  
425
496
  /* OpenPGP credentials */
426
 
  gnutls_certificate_allocate_credentials(&mc.cred);
 
497
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
427
498
  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));
 
499
    fprintf_plus(stderr, "GnuTLS memory error: %s\n", safer_gnutls_strerror(ret));
433
500
    gnutls_global_deinit();
434
501
    return -1;
435
502
  }
436
503
  
437
504
  if(debug){
438
 
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
 
505
    fprintf_plus(stderr, "Attempting to use OpenPGP public key %s and"
439
506
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
440
507
            seckeyfilename);
441
508
  }
444
511
    (mc.cred, pubkeyfilename, seckeyfilename,
445
512
     GNUTLS_OPENPGP_FMT_BASE64);
446
513
  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));
 
514
    fprintf_plus(stderr,
 
515
                 "Error[%d] while reading the OpenPGP key pair ('%s',"
 
516
                 " '%s')\n", ret, pubkeyfilename, seckeyfilename);
 
517
    fprintf_plus(stderr, "The GnuTLS error is: %s\n", safer_gnutls_strerror(ret));
452
518
    goto globalfail;
453
519
  }
454
520
  
455
521
  /* GnuTLS server initialization */
456
522
  ret = gnutls_dh_params_init(&mc.dh_params);
457
523
  if(ret != GNUTLS_E_SUCCESS){
458
 
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
 
524
    fprintf_plus(stderr, "Error in GnuTLS DH parameter initialization:"
459
525
            " %s\n", safer_gnutls_strerror(ret));
460
526
    goto globalfail;
461
527
  }
462
528
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
463
529
  if(ret != GNUTLS_E_SUCCESS){
464
 
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
 
530
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
465
531
            safer_gnutls_strerror(ret));
466
532
    goto globalfail;
467
533
  }
488
554
    }
489
555
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
490
556
  if(ret != GNUTLS_E_SUCCESS){
491
 
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
 
557
    fprintf_plus(stderr, "Error in GnuTLS session initialization: %s\n",
492
558
            safer_gnutls_strerror(ret));
493
559
  }
494
560
  
502
568
      }
503
569
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
504
570
    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));
 
571
      fprintf_plus(stderr, "Syntax error at: %s\n", err);
 
572
      fprintf_plus(stderr, "GnuTLS error: %s\n", safer_gnutls_strerror(ret));
508
573
      gnutls_deinit(*session);
509
574
      return -1;
510
575
    }
519
584
    }
520
585
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
521
586
  if(ret != GNUTLS_E_SUCCESS){
522
 
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
 
587
    fprintf_plus(stderr, "Error setting GnuTLS credentials: %s\n",
523
588
            safer_gnutls_strerror(ret));
524
589
    gnutls_deinit(*session);
525
590
    return -1;
571
636
    pf = PF_INET;
572
637
    break;
573
638
  default:
574
 
    fprintf(stderr, "Bad address family: %d\n", af);
 
639
    fprintf_plus(stderr, "Bad address family: %d\n", af);
575
640
    errno = EINVAL;
576
641
    return -1;
577
642
  }
582
647
  }
583
648
  
584
649
  if(debug){
585
 
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
 
650
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %" PRIu16
586
651
            "\n", ip, port);
587
652
  }
588
653
  
589
654
  tcp_sd = socket(pf, SOCK_STREAM, 0);
590
655
  if(tcp_sd < 0){
591
656
    int e = errno;
592
 
    perror("socket");
 
657
    perror_plus("socket");
593
658
    errno = e;
594
659
    goto mandos_end;
595
660
  }
609
674
  }
610
675
  if(ret < 0 ){
611
676
    int e = errno;
612
 
    perror("inet_pton");
 
677
    perror_plus("inet_pton");
613
678
    errno = e;
614
679
    goto mandos_end;
615
680
  }
616
681
  if(ret == 0){
617
682
    int e = errno;
618
 
    fprintf(stderr, "Bad address: %s\n", ip);
 
683
    fprintf_plus(stderr, "Bad address: %s\n", ip);
619
684
    errno = e;
620
685
    goto mandos_end;
621
686
  }
626
691
    
627
692
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
628
693
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
629
 
                              -Wunreachable-code*/
 
694
                                -Wunreachable-code*/
630
695
      if(if_index == AVAHI_IF_UNSPEC){
631
 
        fprintf(stderr, "An IPv6 link-local address is incomplete"
 
696
        fprintf_plus(stderr, "An IPv6 link-local address is incomplete"
632
697
                " without a network interface\n");
633
698
        errno = EINVAL;
634
699
        goto mandos_end;
651
716
    if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
652
717
      char interface[IF_NAMESIZE];
653
718
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
654
 
        perror("if_indextoname");
 
719
        perror_plus("if_indextoname");
655
720
      } else {
656
 
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
 
721
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
657
722
                ip, interface, port);
658
723
      }
659
724
    } else {
660
 
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
661
 
              port);
 
725
      fprintf_plus(stderr, "Connection to: %s, port %" PRIu16 "\n", ip, port);
662
726
    }
663
727
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
664
728
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
671
735
                        sizeof(addrstr));
672
736
    }
673
737
    if(pcret == NULL){
674
 
      perror("inet_ntop");
 
738
      perror_plus("inet_ntop");
675
739
    } else {
676
740
      if(strcmp(addrstr, ip) != 0){
677
 
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
 
741
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
678
742
      }
679
743
    }
680
744
  }
692
756
  if(ret < 0){
693
757
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
694
758
      int e = errno;
695
 
      perror("connect");
 
759
      perror_plus("connect");
696
760
      errno = e;
697
761
    }
698
762
    goto mandos_end;
708
772
  while(true){
709
773
    size_t out_size = strlen(out);
710
774
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
711
 
                                   out_size - written));
 
775
                                        out_size - written));
712
776
    if(ret == -1){
713
777
      int e = errno;
714
 
      perror("write");
 
778
      perror_plus("write");
715
779
      errno = e;
716
780
      goto mandos_end;
717
781
    }
734
798
  }
735
799
  
736
800
  if(debug){
737
 
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
 
801
    fprintf_plus(stderr, "Establishing TLS session with %s\n", ip);
738
802
  }
739
803
  
740
804
  if(quit_now){
742
806
    goto mandos_end;
743
807
  }
744
808
  
 
809
  /* Spurious warning from -Wint-to-pointer-cast */
745
810
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
746
811
  
747
812
  if(quit_now){
759
824
  
760
825
  if(ret != GNUTLS_E_SUCCESS){
761
826
    if(debug){
762
 
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
 
827
      fprintf_plus(stderr, "*** GnuTLS Handshake failed ***\n");
763
828
      gnutls_perror(ret);
764
829
    }
765
830
    errno = EPROTO;
769
834
  /* Read OpenPGP packet that contains the wanted password */
770
835
  
771
836
  if(debug){
772
 
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
773
 
            ip);
 
837
    fprintf_plus(stderr, "Retrieving OpenPGP encrypted password from %s\n", ip);
774
838
  }
775
839
  
776
840
  while(true){
781
845
    }
782
846
    
783
847
    buffer_capacity = incbuffer(&buffer, buffer_length,
784
 
                                   buffer_capacity);
 
848
                                buffer_capacity);
785
849
    if(buffer_capacity == 0){
786
850
      int e = errno;
787
 
      perror("incbuffer");
 
851
      perror_plus("incbuffer");
788
852
      errno = e;
789
853
      goto mandos_end;
790
854
    }
814
878
          }
815
879
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
816
880
        if(ret < 0){
817
 
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
 
881
          fprintf_plus(stderr, "*** GnuTLS Re-handshake failed ***\n");
818
882
          gnutls_perror(ret);
819
883
          errno = EPROTO;
820
884
          goto mandos_end;
821
885
        }
822
886
        break;
823
887
      default:
824
 
        fprintf(stderr, "Unknown error while reading data from"
 
888
        fprintf_plus(stderr, "Unknown error while reading data from"
825
889
                " encrypted session with Mandos server\n");
826
890
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
827
891
        errno = EIO;
833
897
  }
834
898
  
835
899
  if(debug){
836
 
    fprintf(stderr, "Closing TLS session\n");
 
900
    fprintf_plus(stderr, "Closing TLS session\n");
837
901
  }
838
902
  
839
903
  if(quit_now){
851
915
  
852
916
  if(buffer_length > 0){
853
917
    ssize_t decrypted_buffer_size;
854
 
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
855
 
                                               buffer_length,
 
918
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
856
919
                                               &decrypted_buffer);
857
920
    if(decrypted_buffer_size >= 0){
858
921
      
869
932
        if(ret == 0 and ferror(stdout)){
870
933
          int e = errno;
871
934
          if(debug){
872
 
            fprintf(stderr, "Error writing encrypted data: %s\n",
 
935
            fprintf_plus(stderr, "Error writing encrypted data: %s\n",
873
936
                    strerror(errno));
874
937
          }
875
938
          errno = e;
895
958
      if(e == 0){
896
959
        e = errno;
897
960
      }
898
 
      perror("close");
 
961
      perror_plus("close");
899
962
    }
900
963
    gnutls_deinit(session);
 
964
    errno = e;
901
965
    if(quit_now){
902
 
      e = EINTR;
 
966
      errno = EINTR;
903
967
      retval = -1;
904
968
    }
905
 
    errno = e;
906
969
  }
907
970
  return retval;
908
971
}
933
996
  switch(event){
934
997
  default:
935
998
  case AVAHI_RESOLVER_FAILURE:
936
 
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
 
999
    fprintf_plus(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
937
1000
            " of type '%s' in domain '%s': %s\n", name, type, domain,
938
1001
            avahi_strerror(avahi_server_errno(mc.server)));
939
1002
    break;
943
1006
      char ip[AVAHI_ADDRESS_STR_MAX];
944
1007
      avahi_address_snprint(ip, sizeof(ip), address);
945
1008
      if(debug){
946
 
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %"
 
1009
        fprintf_plus(stderr, "Mandos server \"%s\" found on %s (%s, %"
947
1010
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
948
1011
                ip, (intmax_t)interface, port);
949
1012
      }
951
1014
                                           avahi_proto_to_af(proto));
952
1015
      if(ret == 0){
953
1016
        avahi_simple_poll_quit(mc.simple_poll);
 
1017
      } else {
 
1018
        ret = add_server(ip, port, interface,
 
1019
                         avahi_proto_to_af(proto));
954
1020
      }
955
1021
    }
956
1022
  }
980
1046
  default:
981
1047
  case AVAHI_BROWSER_FAILURE:
982
1048
    
983
 
    fprintf(stderr, "(Avahi browser) %s\n",
 
1049
    fprintf_plus(stderr, "(Avahi browser) %s\n",
984
1050
            avahi_strerror(avahi_server_errno(mc.server)));
985
1051
    avahi_simple_poll_quit(mc.simple_poll);
986
1052
    return;
994
1060
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
995
1061
                                    name, type, domain, protocol, 0,
996
1062
                                    resolve_callback, NULL) == NULL)
997
 
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
 
1063
      fprintf_plus(stderr, "Avahi: Failed to resolve service '%s': %s\n",
998
1064
              name, avahi_strerror(avahi_server_errno(mc.server)));
999
1065
    break;
1000
1066
    
1004
1070
  case AVAHI_BROWSER_ALL_FOR_NOW:
1005
1071
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1006
1072
    if(debug){
1007
 
      fprintf(stderr, "No Mandos server found, still searching...\n");
 
1073
      fprintf_plus(stderr, "No Mandos server found, still searching...\n");
1008
1074
    }
1009
1075
    break;
1010
1076
  }
1011
1077
}
1012
1078
 
1013
 
/* stop main loop after sigterm has been called */
 
1079
/* Signal handler that stops main loop after SIGTERM */
1014
1080
static void handle_sigterm(int sig){
1015
1081
  if(quit_now){
1016
1082
    return;
1018
1084
  quit_now = 1;
1019
1085
  signal_received = sig;
1020
1086
  int old_errno = errno;
 
1087
  /* set main loop to exit */
1021
1088
  if(mc.simple_poll != NULL){
1022
1089
    avahi_simple_poll_quit(mc.simple_poll);
1023
1090
  }
1024
1091
  errno = old_errno;
1025
1092
}
1026
1093
 
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
 
  int ret = asprintf(&flagname, "%s/%s/flags", sys_class_net,
1036
 
                     if_entry->d_name);
1037
 
  if(ret < 0){
1038
 
    perror("asprintf");
1039
 
    return 0;
1040
 
  }
1041
 
  if(if_entry->d_name[0] == '.'){
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
 
    return 0;
1048
 
  }
1049
 
  typedef short ifreq_flags;    /* ifreq.ifr_flags in netdevice(7) */
1050
 
  /* read line from flags_fd */
1051
 
  ssize_t to_read = (sizeof(ifreq_flags)*2)+3; /* "0x1003\n" */
1052
 
  char *flagstring = malloc((size_t)to_read+1); /* +1 for final \0 */
1053
 
  flagstring[(size_t)to_read] = '\0';
1054
 
  if(flagstring == NULL){
1055
 
    perror("malloc");
1056
 
    close(flags_fd);
1057
 
    return 0;
1058
 
  }
1059
 
  while(to_read > 0){
1060
 
    ssret = (ssize_t)TEMP_FAILURE_RETRY(read(flags_fd, flagstring,
1061
 
                                             (size_t)to_read));
1062
 
    if(ssret == -1){
1063
 
      perror("read");
1064
 
      free(flagstring);
1065
 
      close(flags_fd);
1066
 
      return 0;
1067
 
    }
1068
 
    to_read -= ssret;
1069
 
    if(ssret == 0){
1070
 
      break;
1071
 
    }
1072
 
  }
1073
 
  close(flags_fd);
1074
 
  intmax_t tmpmax;
1075
 
  char *tmp;
1076
 
  errno = 0;
1077
 
  tmpmax = strtoimax(flagstring, &tmp, 0);
1078
 
  if(errno != 0 or tmp == flagstring or (*tmp != '\0'
1079
 
                                         and not (isspace(*tmp)))
1080
 
     or tmpmax != (ifreq_flags)tmpmax){
 
1094
bool get_flags(const char *ifname, struct ifreq *ifr){
 
1095
  int ret;
 
1096
  
 
1097
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1098
  if(s < 0){
 
1099
    perror_plus("socket");
 
1100
    return false;
 
1101
  }
 
1102
  strcpy(ifr->ifr_name, ifname);
 
1103
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
 
1104
  if(ret == -1){
1081
1105
    if(debug){
1082
 
      fprintf(stderr, "Invalid flags \"%s\" for interface \"%s\"\n",
1083
 
              flagstring, if_entry->d_name);
 
1106
      perror_plus("ioctl SIOCGIFFLAGS");
1084
1107
    }
1085
 
    free(flagstring);
1086
 
    return 0;
 
1108
    return false;
1087
1109
  }
1088
 
  free(flagstring);
1089
 
  ifreq_flags flags = (ifreq_flags)tmpmax;
 
1110
  return true;
 
1111
}
 
1112
 
 
1113
bool good_flags(const char *ifname, const struct ifreq *ifr){
 
1114
  
1090
1115
  /* Reject the loopback device */
1091
 
  if(flags & IFF_LOOPBACK){
 
1116
  if(ifr->ifr_flags & IFF_LOOPBACK){
1092
1117
    if(debug){
1093
 
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
1094
 
              if_entry->d_name);
 
1118
      fprintf_plus(stderr, "Rejecting loopback interface \"%s\"\n", ifname);
1095
1119
    }
1096
 
    return 0;
 
1120
    return false;
1097
1121
  }
1098
1122
  /* Accept point-to-point devices only if connect_to is specified */
1099
 
  if(connect_to != NULL and (flags & IFF_POINTOPOINT)){
 
1123
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
1100
1124
    if(debug){
1101
 
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
1102
 
              if_entry->d_name);
 
1125
      fprintf_plus(stderr, "Accepting point-to-point interface \"%s\"\n", ifname);
1103
1126
    }
1104
 
    return 1;
 
1127
    return true;
1105
1128
  }
1106
1129
  /* Otherwise, reject non-broadcast-capable devices */
1107
 
  if(not (flags & IFF_BROADCAST)){
1108
 
    if(debug){
1109
 
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
1110
 
              if_entry->d_name);
1111
 
    }
1112
 
    return 0;
1113
 
  }
 
1130
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
 
1131
    if(debug){
 
1132
      fprintf_plus(stderr, "Rejecting non-broadcast interface \"%s\"\n", ifname);
 
1133
    }
 
1134
    return false;
 
1135
  }
 
1136
  /* Reject non-ARP interfaces (including dummy interfaces) */
 
1137
  if(ifr->ifr_flags & IFF_NOARP){
 
1138
    if(debug){
 
1139
      fprintf_plus(stderr, "Rejecting non-ARP interface \"%s\"\n", ifname);
 
1140
    }
 
1141
    return false;
 
1142
  }
 
1143
  
1114
1144
  /* Accept this device */
1115
1145
  if(debug){
1116
 
    fprintf(stderr, "Interface \"%s\" is acceptable\n",
1117
 
            if_entry->d_name);
1118
 
  }
1119
 
  return 1;
 
1146
    fprintf_plus(stderr, "Interface \"%s\" is good\n", ifname);
 
1147
  }
 
1148
  return true;
 
1149
}
 
1150
 
 
1151
/* 
 
1152
 * This function determines if a directory entry in /sys/class/net
 
1153
 * corresponds to an acceptable network device.
 
1154
 * (This function is passed to scandir(3) as a filter function.)
 
1155
 */
 
1156
int good_interface(const struct dirent *if_entry){
 
1157
  if(if_entry->d_name[0] == '.'){
 
1158
    return 0;
 
1159
  }
 
1160
  
 
1161
  struct ifreq ifr;
 
1162
  if(not get_flags(if_entry->d_name, &ifr)){
 
1163
    if(debug){
 
1164
      fprintf_plus(stderr, "Failed to get flags for interface \"%s\"\n",
 
1165
              if_entry->d_name);
 
1166
    }
 
1167
    return 0;
 
1168
  }
 
1169
  
 
1170
  if(not good_flags(if_entry->d_name, &ifr)){
 
1171
    return 0;
 
1172
  }
 
1173
  return 1;
 
1174
}
 
1175
 
 
1176
/* 
 
1177
 * This function determines if a directory entry in /sys/class/net
 
1178
 * corresponds to an acceptable network device which is up.
 
1179
 * (This function is passed to scandir(3) as a filter function.)
 
1180
 */
 
1181
int up_interface(const struct dirent *if_entry){
 
1182
  if(if_entry->d_name[0] == '.'){
 
1183
    return 0;
 
1184
  }
 
1185
  
 
1186
  struct ifreq ifr;
 
1187
  if(not get_flags(if_entry->d_name, &ifr)){
 
1188
    if(debug){
 
1189
      fprintf_plus(stderr, "Failed to get flags for interface \"%s\"\n",
 
1190
              if_entry->d_name);
 
1191
    }
 
1192
    return 0;
 
1193
  }
 
1194
  
 
1195
  /* Reject down interfaces */
 
1196
  if(not (ifr.ifr_flags & IFF_UP)){
 
1197
    if(debug){
 
1198
      fprintf_plus(stderr, "Rejecting down interface \"%s\"\n",
 
1199
              if_entry->d_name);
 
1200
    }
 
1201
    return 0;
 
1202
  }
 
1203
  
 
1204
  /* Reject non-running interfaces */
 
1205
  if(not (ifr.ifr_flags & IFF_RUNNING)){
 
1206
    if(debug){
 
1207
      fprintf_plus(stderr, "Rejecting non-running interface \"%s\"\n",
 
1208
              if_entry->d_name);
 
1209
    }
 
1210
    return 0;
 
1211
  }
 
1212
  
 
1213
  if(not good_flags(if_entry->d_name, &ifr)){
 
1214
    return 0;
 
1215
  }
 
1216
  return 1;
 
1217
}
 
1218
 
 
1219
int notdotentries(const struct dirent *direntry){
 
1220
  /* Skip "." and ".." */
 
1221
  if(direntry->d_name[0] == '.'
 
1222
     and (direntry->d_name[1] == '\0'
 
1223
          or (direntry->d_name[1] == '.'
 
1224
              and direntry->d_name[2] == '\0'))){
 
1225
    return 0;
 
1226
  }
 
1227
  return 1;
 
1228
}
 
1229
 
 
1230
/* Is this directory entry a runnable program? */
 
1231
int runnable_hook(const struct dirent *direntry){
 
1232
  int ret;
 
1233
  size_t sret;
 
1234
  struct stat st;
 
1235
  
 
1236
  if((direntry->d_name)[0] == '\0'){
 
1237
    /* Empty name? */
 
1238
    return 0;
 
1239
  }
 
1240
  
 
1241
  sret = strspn(direntry->d_name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
 
1242
                "abcdefghijklmnopqrstuvwxyz"
 
1243
                "0123456789"
 
1244
                "_-");
 
1245
  if((direntry->d_name)[sret] != '\0'){
 
1246
    /* Contains non-allowed characters */
 
1247
    if(debug){
 
1248
      fprintf_plus(stderr, "Ignoring hook \"%s\" with bad name\n",
 
1249
              direntry->d_name);
 
1250
    }
 
1251
    return 0;
 
1252
  }
 
1253
  
 
1254
  char *fullname = NULL;
 
1255
  ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
 
1256
  if(ret < 0){
 
1257
    perror_plus("asprintf");
 
1258
    return 0;
 
1259
  }
 
1260
  
 
1261
  ret = stat(fullname, &st);
 
1262
  if(ret == -1){
 
1263
    if(debug){
 
1264
      perror_plus("Could not stat hook");
 
1265
    }
 
1266
    return 0;
 
1267
  }
 
1268
  if(not (S_ISREG(st.st_mode))){
 
1269
    /* Not a regular file */
 
1270
    if(debug){
 
1271
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not a file\n",
 
1272
              direntry->d_name);
 
1273
    }
 
1274
    return 0;
 
1275
  }
 
1276
  if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
 
1277
    /* Not executable */
 
1278
    if(debug){
 
1279
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not executable\n",
 
1280
              direntry->d_name);
 
1281
    }
 
1282
    return 0;
 
1283
  }
 
1284
  return 1;
 
1285
}
 
1286
 
 
1287
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
 
1288
  int ret;
 
1289
  struct timespec now;
 
1290
  struct timespec waited_time;
 
1291
  intmax_t block_time;
 
1292
  
 
1293
  while(true){
 
1294
    if(mc.current_server == NULL){
 
1295
      if (debug){
 
1296
        fprintf_plus(stderr, "Wait until first server is found. No timeout!\n");
 
1297
      }
 
1298
      ret = avahi_simple_poll_iterate(s, -1);
 
1299
    } else {
 
1300
      if (debug){
 
1301
        fprintf_plus(stderr, "Check current_server if we should run it,"
 
1302
                " or wait\n");
 
1303
      }
 
1304
      /* the current time */
 
1305
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
 
1306
      if(ret == -1){
 
1307
        perror_plus("clock_gettime");
 
1308
        return -1;
 
1309
      }
 
1310
      /* Calculating in ms how long time between now and server
 
1311
         who we visted longest time ago. Now - last seen.  */
 
1312
      waited_time.tv_sec = (now.tv_sec
 
1313
                            - mc.current_server->last_seen.tv_sec);
 
1314
      waited_time.tv_nsec = (now.tv_nsec
 
1315
                             - mc.current_server->last_seen.tv_nsec);
 
1316
      /* total time is 10s/10,000ms.
 
1317
         Converting to s from ms by dividing by 1,000,
 
1318
         and ns to ms by dividing by 1,000,000. */
 
1319
      block_time = ((retry_interval
 
1320
                     - ((intmax_t)waited_time.tv_sec * 1000))
 
1321
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
 
1322
      
 
1323
      if (debug){
 
1324
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n", block_time);
 
1325
      }
 
1326
      
 
1327
      if(block_time <= 0){
 
1328
        ret = start_mandos_communication(mc.current_server->ip,
 
1329
                                         mc.current_server->port,
 
1330
                                         mc.current_server->if_index,
 
1331
                                         mc.current_server->af);
 
1332
        if(ret == 0){
 
1333
          avahi_simple_poll_quit(mc.simple_poll);
 
1334
          return 0;
 
1335
        }
 
1336
        ret = clock_gettime(CLOCK_MONOTONIC,
 
1337
                            &mc.current_server->last_seen);
 
1338
        if(ret == -1){
 
1339
          perror_plus("clock_gettime");
 
1340
          return -1;
 
1341
        }
 
1342
        mc.current_server = mc.current_server->next;
 
1343
        block_time = 0;         /* Call avahi to find new Mandos
 
1344
                                   servers, but don't block */
 
1345
      }
 
1346
      
 
1347
      ret = avahi_simple_poll_iterate(s, (int)block_time);
 
1348
    }
 
1349
    if(ret != 0){
 
1350
      if (ret > 0 or errno != EINTR){
 
1351
        return (ret != 1) ? ret : 0;
 
1352
      }
 
1353
    }
 
1354
  }
1120
1355
}
1121
1356
 
1122
1357
int main(int argc, char *argv[]){
1141
1376
  bool gnutls_initialized = false;
1142
1377
  bool gpgme_initialized = false;
1143
1378
  float delay = 2.5f;
 
1379
  double retry_interval = 10; /* 10s between trying a server and
 
1380
                                 retrying the same server again */
1144
1381
  
1145
1382
  struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
1146
1383
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
1152
1389
  errno = 0;
1153
1390
  ret = setgid(gid);
1154
1391
  if(ret == -1){
1155
 
    perror("setgid");
 
1392
    perror_plus("setgid");
1156
1393
  }
1157
1394
  
1158
1395
  /* Lower user privileges (temporarily) */
1159
1396
  errno = 0;
1160
1397
  ret = seteuid(uid);
1161
1398
  if(ret == -1){
1162
 
    perror("seteuid");
 
1399
    perror_plus("seteuid");
1163
1400
  }
1164
1401
  
1165
1402
  if(quit_now){
1200
1437
        .arg = "SECONDS",
1201
1438
        .doc = "Maximum delay to wait for interface startup",
1202
1439
        .group = 2 },
 
1440
      { .name = "retry", .key = 132,
 
1441
        .arg = "SECONDS",
 
1442
        .doc = "Retry interval used when denied by the mandos server",
 
1443
        .group = 2 },
 
1444
      { .name = "network-hook-dir", .key = 133,
 
1445
        .arg = "DIR",
 
1446
        .doc = "Directory where network hooks are located",
 
1447
        .group = 2 },
1203
1448
      /*
1204
1449
       * These reproduce what we would get without ARGP_NO_HELP
1205
1450
       */
1249
1494
        if(errno != 0 or tmp == arg or *tmp != '\0'){
1250
1495
          argp_error(state, "Bad delay");
1251
1496
        }
 
1497
      case 132:                 /* --retry */
 
1498
        errno = 0;
 
1499
        retry_interval = strtod(arg, &tmp);
 
1500
        if(errno != 0 or tmp == arg or *tmp != '\0'
 
1501
           or (retry_interval * 1000) > INT_MAX
 
1502
           or retry_interval < 0){
 
1503
          argp_error(state, "Bad retry interval");
 
1504
        }
 
1505
        break;
 
1506
      case 133:                 /* --network-hook-dir */
 
1507
        hookdir = arg;
1252
1508
        break;
1253
1509
        /*
1254
1510
         * These reproduce what we would get without ARGP_NO_HELP
1261
1517
        argp_state_help(state, state->out_stream,
1262
1518
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1263
1519
      case 'V':                 /* --version */
1264
 
        fprintf(state->out_stream, "%s\n", argp_program_version);
 
1520
        fprintf_plus(state->out_stream, "Mandos plugin mandos-client: ");
 
1521
        fprintf_plus(state->out_stream, "%s\n", argp_program_version);
1265
1522
        exit(argp_err_exit_status);
1266
1523
        break;
1267
1524
      default:
1282
1539
    case ENOMEM:
1283
1540
    default:
1284
1541
      errno = ret;
1285
 
      perror("argp_parse");
 
1542
      perror_plus("argp_parse");
1286
1543
      exitcode = EX_OSERR;
1287
1544
      goto end;
1288
1545
    case EINVAL:
1290
1547
      goto end;
1291
1548
    }
1292
1549
  }
 
1550
    
 
1551
  {
 
1552
    /* Work around Debian bug #633582:
 
1553
       <http://bugs.debian.org/633582> */
 
1554
    struct stat st;
 
1555
    
 
1556
    /* Re-raise priviliges */
 
1557
    errno = 0;
 
1558
    ret = seteuid(0);
 
1559
    if(ret == -1){
 
1560
      perror_plus("seteuid");
 
1561
    }
 
1562
    
 
1563
    if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
 
1564
      int seckey_fd = open(seckey, O_RDONLY);
 
1565
      if(seckey_fd == -1){
 
1566
        perror_plus("open");
 
1567
      } else {
 
1568
        ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
 
1569
        if(ret == -1){
 
1570
          perror_plus("fstat");
 
1571
        } else {
 
1572
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
 
1573
            ret = fchown(seckey_fd, uid, gid);
 
1574
            if(ret == -1){
 
1575
              perror_plus("fchown");
 
1576
            }
 
1577
          }
 
1578
        }
 
1579
        TEMP_FAILURE_RETRY(close(seckey_fd));
 
1580
      }
 
1581
    }
 
1582
    
 
1583
    if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
 
1584
      int pubkey_fd = open(pubkey, O_RDONLY);
 
1585
      if(pubkey_fd == -1){
 
1586
        perror_plus("open");
 
1587
      } else {
 
1588
        ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
 
1589
        if(ret == -1){
 
1590
          perror_plus("fstat");
 
1591
        } else {
 
1592
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
 
1593
            ret = fchown(pubkey_fd, uid, gid);
 
1594
            if(ret == -1){
 
1595
              perror_plus("fchown");
 
1596
            }
 
1597
          }
 
1598
        }
 
1599
        TEMP_FAILURE_RETRY(close(pubkey_fd));
 
1600
      }
 
1601
    }
 
1602
    
 
1603
    /* Lower privileges */
 
1604
    errno = 0;
 
1605
    ret = seteuid(uid);
 
1606
    if(ret == -1){
 
1607
      perror_plus("seteuid");
 
1608
    }
 
1609
  }
 
1610
  
 
1611
  /* Find network hooks and run them */
 
1612
  {
 
1613
    struct dirent **direntries;
 
1614
    struct dirent *direntry;
 
1615
    int numhooks = scandir(hookdir, &direntries, runnable_hook,
 
1616
                           alphasort);
 
1617
    if(numhooks == -1){
 
1618
      perror_plus("scandir");
 
1619
    } else {
 
1620
      int devnull = open("/dev/null", O_RDONLY);
 
1621
      for(int i = 0; i < numhooks; i++){
 
1622
        direntry = direntries[0];
 
1623
        char *fullname = NULL;
 
1624
        ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
 
1625
        if(ret < 0){
 
1626
          perror_plus("asprintf");
 
1627
          continue;
 
1628
        }
 
1629
        pid_t hook_pid = fork();
 
1630
        if(hook_pid == 0){
 
1631
          /* Child */
 
1632
          dup2(devnull, STDIN_FILENO);
 
1633
          close(devnull);
 
1634
          dup2(STDERR_FILENO, STDOUT_FILENO);
 
1635
          ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
 
1636
          if(ret == -1){
 
1637
            perror_plus("setenv");
 
1638
            exit(1);
 
1639
          }
 
1640
          ret = setenv("DEVICE", interface, 1);
 
1641
          if(ret == -1){
 
1642
            perror_plus("setenv");
 
1643
            exit(1);
 
1644
          }
 
1645
          ret = setenv("VERBOSE", debug ? "1" : "0", 1);
 
1646
          if(ret == -1){
 
1647
            perror_plus("setenv");
 
1648
            exit(1);
 
1649
          }
 
1650
          ret = setenv("MODE", "start", 1);
 
1651
          if(ret == -1){
 
1652
            perror_plus("setenv");
 
1653
            exit(1);
 
1654
          }
 
1655
          char *delaystring;
 
1656
          ret = asprintf(&delaystring, "%f", delay);
 
1657
          if(ret == -1){
 
1658
            perror_plus("asprintf");
 
1659
            exit(1);
 
1660
          }
 
1661
          ret = setenv("DELAY", delaystring, 1);
 
1662
          if(ret == -1){
 
1663
            free(delaystring);
 
1664
            perror_plus("setenv");
 
1665
            exit(1);
 
1666
          }
 
1667
          free(delaystring);
 
1668
          ret = execl(fullname, direntry->d_name, "start", NULL);
 
1669
          perror_plus("execl");
 
1670
        } else {
 
1671
          int status;
 
1672
          if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
 
1673
            perror_plus("waitpid");
 
1674
            free(fullname);
 
1675
            continue;
 
1676
          }
 
1677
          if(WIFEXITED(status)){
 
1678
            if(WEXITSTATUS(status) != 0){
 
1679
              fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
 
1680
                      " with status %d\n", direntry->d_name,
 
1681
                      WEXITSTATUS(status));
 
1682
              free(fullname);
 
1683
              continue;
 
1684
            }
 
1685
          } else if(WIFSIGNALED(status)){
 
1686
            fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
 
1687
                    " signal %d\n", direntry->d_name,
 
1688
                    WTERMSIG(status));
 
1689
            free(fullname);
 
1690
            continue;
 
1691
          } else {
 
1692
            fprintf_plus(stderr, "Warning: network hook \"%s\" crashed\n",
 
1693
                    direntry->d_name);
 
1694
            free(fullname);
 
1695
            continue;
 
1696
          }
 
1697
        }
 
1698
        free(fullname);
 
1699
        if(quit_now){
 
1700
          goto end;
 
1701
        }
 
1702
      }
 
1703
      close(devnull);
 
1704
    }
 
1705
  }
1293
1706
  
1294
1707
  if(not debug){
1295
1708
    avahi_set_log_function(empty_log);
1296
1709
  }
1297
 
 
 
1710
  
1298
1711
  if(interface[0] == '\0'){
1299
1712
    struct dirent **direntries;
1300
 
    ret = scandir(sys_class_net, &direntries, good_interface,
 
1713
    /* First look for interfaces that are up */
 
1714
    ret = scandir(sys_class_net, &direntries, up_interface,
1301
1715
                  alphasort);
 
1716
    if(ret == 0){
 
1717
      /* No up interfaces, look for any good interfaces */
 
1718
      free(direntries);
 
1719
      ret = scandir(sys_class_net, &direntries, good_interface,
 
1720
                    alphasort);
 
1721
    }
1302
1722
    if(ret >= 1){
1303
 
      /* Pick the first good interface */
 
1723
      /* Pick the first interface returned */
1304
1724
      interface = strdup(direntries[0]->d_name);
1305
1725
      if(debug){
1306
 
        fprintf(stderr, "Using interface \"%s\"\n", interface);
 
1726
        fprintf_plus(stderr, "Using interface \"%s\"\n", interface);
1307
1727
      }
1308
1728
      if(interface == NULL){
1309
 
        perror("malloc");
 
1729
        perror_plus("malloc");
1310
1730
        free(direntries);
1311
1731
        exitcode = EXIT_FAILURE;
1312
1732
        goto end;
1314
1734
      free(direntries);
1315
1735
    } else {
1316
1736
      free(direntries);
1317
 
      fprintf(stderr, "Could not find a network interface\n");
 
1737
      fprintf_plus(stderr, "Could not find a network interface\n");
1318
1738
      exitcode = EXIT_FAILURE;
1319
1739
      goto end;
1320
1740
    }
1326
1746
  srand((unsigned int) time(NULL));
1327
1747
  mc.simple_poll = avahi_simple_poll_new();
1328
1748
  if(mc.simple_poll == NULL){
1329
 
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
 
1749
    fprintf_plus(stderr, "Avahi: Failed to create simple poll object.\n");
1330
1750
    exitcode = EX_UNAVAILABLE;
1331
1751
    goto end;
1332
1752
  }
1334
1754
  sigemptyset(&sigterm_action.sa_mask);
1335
1755
  ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
1336
1756
  if(ret == -1){
1337
 
    perror("sigaddset");
 
1757
    perror_plus("sigaddset");
1338
1758
    exitcode = EX_OSERR;
1339
1759
    goto end;
1340
1760
  }
1341
1761
  ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
1342
1762
  if(ret == -1){
1343
 
    perror("sigaddset");
 
1763
    perror_plus("sigaddset");
1344
1764
    exitcode = EX_OSERR;
1345
1765
    goto end;
1346
1766
  }
1347
1767
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
1348
1768
  if(ret == -1){
1349
 
    perror("sigaddset");
 
1769
    perror_plus("sigaddset");
1350
1770
    exitcode = EX_OSERR;
1351
1771
    goto end;
1352
1772
  }
1356
1776
  */
1357
1777
  ret = sigaction(SIGINT, NULL, &old_sigterm_action);
1358
1778
  if(ret == -1){
1359
 
    perror("sigaction");
 
1779
    perror_plus("sigaction");
1360
1780
    return EX_OSERR;
1361
1781
  }
1362
1782
  if(old_sigterm_action.sa_handler != SIG_IGN){
1363
1783
    ret = sigaction(SIGINT, &sigterm_action, NULL);
1364
1784
    if(ret == -1){
1365
 
      perror("sigaction");
 
1785
      perror_plus("sigaction");
1366
1786
      exitcode = EX_OSERR;
1367
1787
      goto end;
1368
1788
    }
1369
1789
  }
1370
1790
  ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
1371
1791
  if(ret == -1){
1372
 
    perror("sigaction");
 
1792
    perror_plus("sigaction");
1373
1793
    return EX_OSERR;
1374
1794
  }
1375
1795
  if(old_sigterm_action.sa_handler != SIG_IGN){
1376
1796
    ret = sigaction(SIGHUP, &sigterm_action, NULL);
1377
1797
    if(ret == -1){
1378
 
      perror("sigaction");
 
1798
      perror_plus("sigaction");
1379
1799
      exitcode = EX_OSERR;
1380
1800
      goto end;
1381
1801
    }
1382
1802
  }
1383
1803
  ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
1384
1804
  if(ret == -1){
1385
 
    perror("sigaction");
 
1805
    perror_plus("sigaction");
1386
1806
    return EX_OSERR;
1387
1807
  }
1388
1808
  if(old_sigterm_action.sa_handler != SIG_IGN){
1389
1809
    ret = sigaction(SIGTERM, &sigterm_action, NULL);
1390
1810
    if(ret == -1){
1391
 
      perror("sigaction");
 
1811
      perror_plus("sigaction");
1392
1812
      exitcode = EX_OSERR;
1393
1813
      goto end;
1394
1814
    }
1398
1818
  if(strcmp(interface, "none") != 0){
1399
1819
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1400
1820
    if(if_index == 0){
1401
 
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
 
1821
      fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
1402
1822
      exitcode = EX_UNAVAILABLE;
1403
1823
      goto end;
1404
1824
    }
1411
1831
    errno = 0;
1412
1832
    ret = seteuid(0);
1413
1833
    if(ret == -1){
1414
 
      perror("seteuid");
 
1834
      perror_plus("seteuid");
1415
1835
    }
1416
1836
    
1417
1837
#ifdef __linux__
1421
1841
    bool restore_loglevel = true;
1422
1842
    if(ret == -1){
1423
1843
      restore_loglevel = false;
1424
 
      perror("klogctl");
 
1844
      perror_plus("klogctl");
1425
1845
    }
1426
1846
#endif  /* __linux__ */
1427
1847
    
1428
1848
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1429
1849
    if(sd < 0){
1430
 
      perror("socket");
 
1850
      perror_plus("socket");
1431
1851
      exitcode = EX_OSERR;
1432
1852
#ifdef __linux__
1433
1853
      if(restore_loglevel){
1434
1854
        ret = klogctl(7, NULL, 0);
1435
1855
        if(ret == -1){
1436
 
          perror("klogctl");
 
1856
          perror_plus("klogctl");
1437
1857
        }
1438
1858
      }
1439
1859
#endif  /* __linux__ */
1441
1861
      errno = 0;
1442
1862
      ret = seteuid(uid);
1443
1863
      if(ret == -1){
1444
 
        perror("seteuid");
 
1864
        perror_plus("seteuid");
1445
1865
      }
1446
1866
      goto end;
1447
1867
    }
1448
1868
    strcpy(network.ifr_name, interface);
1449
1869
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
1450
1870
    if(ret == -1){
1451
 
      perror("ioctl SIOCGIFFLAGS");
 
1871
      perror_plus("ioctl SIOCGIFFLAGS");
1452
1872
#ifdef __linux__
1453
1873
      if(restore_loglevel){
1454
1874
        ret = klogctl(7, NULL, 0);
1455
1875
        if(ret == -1){
1456
 
          perror("klogctl");
 
1876
          perror_plus("klogctl");
1457
1877
        }
1458
1878
      }
1459
1879
#endif  /* __linux__ */
1462
1882
      errno = 0;
1463
1883
      ret = seteuid(uid);
1464
1884
      if(ret == -1){
1465
 
        perror("seteuid");
 
1885
        perror_plus("seteuid");
1466
1886
      }
1467
1887
      goto end;
1468
1888
    }
1472
1892
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1473
1893
      if(ret == -1){
1474
1894
        take_down_interface = false;
1475
 
        perror("ioctl SIOCSIFFLAGS +IFF_UP");
 
1895
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1476
1896
        exitcode = EX_OSERR;
1477
1897
#ifdef __linux__
1478
1898
        if(restore_loglevel){
1479
1899
          ret = klogctl(7, NULL, 0);
1480
1900
          if(ret == -1){
1481
 
            perror("klogctl");
 
1901
            perror_plus("klogctl");
1482
1902
          }
1483
1903
        }
1484
1904
#endif  /* __linux__ */
1486
1906
        errno = 0;
1487
1907
        ret = seteuid(uid);
1488
1908
        if(ret == -1){
1489
 
          perror("seteuid");
 
1909
          perror_plus("seteuid");
1490
1910
        }
1491
1911
        goto end;
1492
1912
      }
1493
1913
    }
1494
 
    /* sleep checking until interface is running */
 
1914
    /* Sleep checking until interface is running.
 
1915
       Check every 0.25s, up to total time of delay */
1495
1916
    for(int i=0; i < delay * 4; i++){
1496
1917
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1497
1918
      if(ret == -1){
1498
 
        perror("ioctl SIOCGIFFLAGS");
 
1919
        perror_plus("ioctl SIOCGIFFLAGS");
1499
1920
      } else if(network.ifr_flags & IFF_RUNNING){
1500
1921
        break;
1501
1922
      }
1502
1923
      struct timespec sleeptime = { .tv_nsec = 250000000 };
1503
1924
      ret = nanosleep(&sleeptime, NULL);
1504
1925
      if(ret == -1 and errno != EINTR){
1505
 
        perror("nanosleep");
 
1926
        perror_plus("nanosleep");
1506
1927
      }
1507
1928
    }
1508
1929
    if(not take_down_interface){
1509
1930
      /* We won't need the socket anymore */
1510
1931
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1511
1932
      if(ret == -1){
1512
 
        perror("close");
 
1933
        perror_plus("close");
1513
1934
      }
1514
1935
    }
1515
1936
#ifdef __linux__
1517
1938
      /* Restores kernel loglevel to default */
1518
1939
      ret = klogctl(7, NULL, 0);
1519
1940
      if(ret == -1){
1520
 
        perror("klogctl");
 
1941
        perror_plus("klogctl");
1521
1942
      }
1522
1943
    }
1523
1944
#endif  /* __linux__ */
1527
1948
      /* Lower privileges */
1528
1949
      ret = seteuid(uid);
1529
1950
      if(ret == -1){
1530
 
        perror("seteuid");
 
1951
        perror_plus("seteuid");
1531
1952
      }
1532
1953
    } else {
1533
1954
      /* Lower privileges permanently */
1534
1955
      ret = setuid(uid);
1535
1956
      if(ret == -1){
1536
 
        perror("setuid");
 
1957
        perror_plus("setuid");
1537
1958
      }
1538
1959
    }
1539
1960
  }
1544
1965
  
1545
1966
  ret = init_gnutls_global(pubkey, seckey);
1546
1967
  if(ret == -1){
1547
 
    fprintf(stderr, "init_gnutls_global failed\n");
 
1968
    fprintf_plus(stderr, "init_gnutls_global failed\n");
1548
1969
    exitcode = EX_UNAVAILABLE;
1549
1970
    goto end;
1550
1971
  } else {
1555
1976
    goto end;
1556
1977
  }
1557
1978
  
 
1979
  if(mkdtemp(tempdir) == NULL){
 
1980
    perror_plus("mkdtemp");
 
1981
    goto end;
 
1982
  }
1558
1983
  tempdir_created = true;
1559
 
  if(mkdtemp(tempdir) == NULL){
1560
 
    tempdir_created = false;
1561
 
    perror("mkdtemp");
1562
 
    goto end;
1563
 
  }
1564
1984
  
1565
1985
  if(quit_now){
1566
1986
    goto end;
1567
1987
  }
1568
1988
  
1569
1989
  if(not init_gpgme(pubkey, seckey, tempdir)){
1570
 
    fprintf(stderr, "init_gpgme failed\n");
 
1990
    fprintf_plus(stderr, "init_gpgme failed\n");
1571
1991
    exitcode = EX_UNAVAILABLE;
1572
1992
    goto end;
1573
1993
  } else {
1583
2003
    /* (Mainly meant for debugging) */
1584
2004
    char *address = strrchr(connect_to, ':');
1585
2005
    if(address == NULL){
1586
 
      fprintf(stderr, "No colon in address\n");
 
2006
      fprintf_plus(stderr, "No colon in address\n");
1587
2007
      exitcode = EX_USAGE;
1588
2008
      goto end;
1589
2009
    }
1597
2017
    tmpmax = strtoimax(address+1, &tmp, 10);
1598
2018
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
1599
2019
       or tmpmax != (uint16_t)tmpmax){
1600
 
      fprintf(stderr, "Bad port number\n");
 
2020
      fprintf_plus(stderr, "Bad port number\n");
1601
2021
      exitcode = EX_USAGE;
1602
2022
      goto end;
1603
2023
    }
1608
2028
    
1609
2029
    port = (uint16_t)tmpmax;
1610
2030
    *address = '\0';
1611
 
    address = connect_to;
1612
2031
    /* Colon in address indicates IPv6 */
1613
2032
    int af;
1614
 
    if(strchr(address, ':') != NULL){
 
2033
    if(strchr(connect_to, ':') != NULL){
1615
2034
      af = AF_INET6;
 
2035
      /* Accept [] around IPv6 address - see RFC 5952 */
 
2036
      if(connect_to[0] == '[' and address[-1] == ']')
 
2037
        {
 
2038
          connect_to++;
 
2039
          address[-1] = '\0';
 
2040
        }
1616
2041
    } else {
1617
2042
      af = AF_INET;
1618
2043
    }
 
2044
    address = connect_to;
1619
2045
    
1620
2046
    if(quit_now){
1621
2047
      goto end;
1622
2048
    }
1623
 
 
 
2049
    
1624
2050
    while(not quit_now){
1625
2051
      ret = start_mandos_communication(address, port, if_index, af);
1626
2052
      if(quit_now or ret == 0){
1627
2053
        break;
1628
2054
      }
1629
 
      sleep(15);
1630
 
    };
1631
 
 
 
2055
      if(debug){
 
2056
        fprintf_plus(stderr, "Retrying in %d seconds\n", (int)retry_interval);
 
2057
      }
 
2058
      sleep((int)retry_interval);
 
2059
    }
 
2060
    
1632
2061
    if (not quit_now){
1633
2062
      exitcode = EXIT_SUCCESS;
1634
2063
    }
1635
 
 
 
2064
    
1636
2065
    goto end;
1637
2066
  }
1638
2067
  
1660
2089
  
1661
2090
  /* Check if creating the Avahi server object succeeded */
1662
2091
  if(mc.server == NULL){
1663
 
    fprintf(stderr, "Failed to create Avahi server: %s\n",
 
2092
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
1664
2093
            avahi_strerror(error));
1665
2094
    exitcode = EX_UNAVAILABLE;
1666
2095
    goto end;
1675
2104
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
1676
2105
                                   NULL, 0, browse_callback, NULL);
1677
2106
  if(sb == NULL){
1678
 
    fprintf(stderr, "Failed to create service browser: %s\n",
 
2107
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
1679
2108
            avahi_strerror(avahi_server_errno(mc.server)));
1680
2109
    exitcode = EX_UNAVAILABLE;
1681
2110
    goto end;
1688
2117
  /* Run the main loop */
1689
2118
  
1690
2119
  if(debug){
1691
 
    fprintf(stderr, "Starting Avahi loop search\n");
1692
 
  }
1693
 
  
1694
 
  avahi_simple_poll_loop(mc.simple_poll);
 
2120
    fprintf_plus(stderr, "Starting Avahi loop search\n");
 
2121
  }
 
2122
 
 
2123
  ret = avahi_loop_with_timeout(mc.simple_poll,
 
2124
                                (int)(retry_interval * 1000));
 
2125
  if(debug){
 
2126
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
 
2127
            (ret == 0) ? "successfully" : "with error");
 
2128
  }
1695
2129
  
1696
2130
 end:
1697
2131
  
1698
2132
  if(debug){
1699
 
    fprintf(stderr, "%s exiting\n", argv[0]);
 
2133
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
1700
2134
  }
1701
2135
  
1702
2136
  /* Cleanup things */
1718
2152
  if(gpgme_initialized){
1719
2153
    gpgme_release(mc.ctx);
1720
2154
  }
 
2155
 
 
2156
  /* Cleans up the circular linked list of Mandos servers the client
 
2157
     has seen */
 
2158
  if(mc.current_server != NULL){
 
2159
    mc.current_server->prev->next = NULL;
 
2160
    while(mc.current_server != NULL){
 
2161
      server *next = mc.current_server->next;
 
2162
      free(mc.current_server);
 
2163
      mc.current_server = next;
 
2164
    }
 
2165
  }
 
2166
  
 
2167
  /* XXX run network hooks "stop" here  */
1721
2168
  
1722
2169
  /* Take down the network interface */
1723
2170
  if(take_down_interface){
1725
2172
    errno = 0;
1726
2173
    ret = seteuid(0);
1727
2174
    if(ret == -1){
1728
 
      perror("seteuid");
 
2175
      perror_plus("seteuid");
1729
2176
    }
1730
2177
    if(geteuid() == 0){
1731
2178
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1732
2179
      if(ret == -1){
1733
 
        perror("ioctl SIOCGIFFLAGS");
1734
 
      } else if(network.ifr_flags & IFF_UP) {
 
2180
        perror_plus("ioctl SIOCGIFFLAGS");
 
2181
      } else if(network.ifr_flags & IFF_UP){
1735
2182
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
1736
2183
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
1737
2184
        if(ret == -1){
1738
 
          perror("ioctl SIOCSIFFLAGS -IFF_UP");
 
2185
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
1739
2186
        }
1740
2187
      }
1741
2188
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1742
2189
      if(ret == -1){
1743
 
        perror("close");
 
2190
        perror_plus("close");
1744
2191
      }
1745
2192
      /* Lower privileges permanently */
1746
2193
      errno = 0;
1747
2194
      ret = setuid(uid);
1748
2195
      if(ret == -1){
1749
 
        perror("setuid");
 
2196
        perror_plus("setuid");
1750
2197
      }
1751
2198
    }
1752
2199
  }
1753
2200
  
1754
 
  /* Removes the temp directory used by GPGME */
 
2201
  /* Removes the GPGME temp directory and all files inside */
1755
2202
  if(tempdir_created){
1756
 
    DIR *d;
1757
 
    struct dirent *direntry;
1758
 
    d = opendir(tempdir);
1759
 
    if(d == NULL){
1760
 
      if(errno != ENOENT){
1761
 
        perror("opendir");
1762
 
      }
1763
 
    } else {
1764
 
      while(true){
1765
 
        direntry = readdir(d);
1766
 
        if(direntry == NULL){
1767
 
          break;
1768
 
        }
1769
 
        /* Skip "." and ".." */
1770
 
        if(direntry->d_name[0] == '.'
1771
 
           and (direntry->d_name[1] == '\0'
1772
 
                or (direntry->d_name[1] == '.'
1773
 
                    and direntry->d_name[2] == '\0'))){
1774
 
          continue;
1775
 
        }
 
2203
    struct dirent **direntries = NULL;
 
2204
    struct dirent *direntry = NULL;
 
2205
    int numentries = scandir(tempdir, &direntries, notdotentries,
 
2206
                             alphasort);
 
2207
    if (numentries > 0){
 
2208
      for(int i = 0; i < numentries; i++){
 
2209
        direntry = direntries[i];
1776
2210
        char *fullname = NULL;
1777
2211
        ret = asprintf(&fullname, "%s/%s", tempdir,
1778
2212
                       direntry->d_name);
1779
2213
        if(ret < 0){
1780
 
          perror("asprintf");
 
2214
          perror_plus("asprintf");
1781
2215
          continue;
1782
2216
        }
1783
2217
        ret = remove(fullname);
1784
2218
        if(ret == -1){
1785
 
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
1786
 
                  strerror(errno));
 
2219
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname, strerror(errno));
1787
2220
        }
1788
2221
        free(fullname);
1789
2222
      }
1790
 
      closedir(d);
 
2223
    }
 
2224
 
 
2225
    /* need to clean even if 0 because man page doesn't specify */
 
2226
    free(direntries);
 
2227
    if (numentries == -1){
 
2228
      perror_plus("scandir");
1791
2229
    }
1792
2230
    ret = rmdir(tempdir);
1793
2231
    if(ret == -1 and errno != ENOENT){
1794
 
      perror("rmdir");
 
2232
      perror_plus("rmdir");
1795
2233
    }
1796
2234
  }
1797
2235
  
1802
2240
                                            &old_sigterm_action,
1803
2241
                                            NULL));
1804
2242
    if(ret == -1){
1805
 
      perror("sigaction");
 
2243
      perror_plus("sigaction");
1806
2244
    }
1807
2245
    do {
1808
2246
      ret = raise(signal_received);
1809
2247
    } while(ret != 0 and errno == EINTR);
1810
2248
    if(ret != 0){
1811
 
      perror("raise");
 
2249
      perror_plus("raise");
1812
2250
      abort();
1813
2251
    }
1814
2252
    TEMP_FAILURE_RETRY(pause());