/mandos/trunk

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

« back to all changes in this revision

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

  • Committer: Björn Påhlsson
  • Date: 2011-11-14 19:10:50 UTC
  • mto: (505.3.9 client-network-hooks)
  • mto: This revision was merged to the branch mainline in revision 525.
  • 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,2009 Teddy Hogeborn
13
 
 * Copyright © 2008,2009 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 */
66
 
#include <time.h>               /* nanosleep(), time() */
 
65
#include <errno.h>              /* perror(), errno,
 
66
                                   program_invocation_short_name */
 
67
#include <time.h>               /* nanosleep(), time(), sleep() */
67
68
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
68
69
                                   SIOCSIFFLAGS, if_indextoname(),
69
70
                                   if_nametoindex(), IF_NAMESIZE */
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>";
 
134
static const char sys_class_net[] = "/sys/class/net";
 
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;
130
148
 
131
149
/* Used for passing in values through the Avahi callback functions */
132
150
typedef struct {
137
155
  gnutls_dh_params_t dh_params;
138
156
  const char *priority;
139
157
  gpgme_ctx_t ctx;
 
158
  server *current_server;
140
159
} mandos_context;
141
160
 
142
161
/* global context so signal handler can reach it*/
143
162
mandos_context mc = { .simple_poll = NULL, .server = NULL,
144
163
                      .dh_bits = 1024, .priority = "SECURE256"
145
 
                      ":!CTYPE-X.509:+CTYPE-OPENPGP" };
 
164
                      ":!CTYPE-X.509:+CTYPE-OPENPGP",
 
165
                      .current_server = NULL };
146
166
 
147
167
sig_atomic_t quit_now = 0;
148
168
int signal_received = 0;
149
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
 
150
185
/*
151
186
 * Make additional room in "buffer" for at least BUFFER_SIZE more
152
187
 * bytes. "buffer_capacity" is how much is currently allocated,
153
188
 * "buffer_length" is how much is already used.
154
189
 */
155
190
size_t incbuffer(char **buffer, size_t buffer_length,
156
 
                  size_t buffer_capacity){
 
191
                 size_t buffer_capacity){
157
192
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
158
193
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
159
194
    if(buffer == NULL){
164
199
  return buffer_capacity;
165
200
}
166
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
 
167
239
/* 
168
240
 * Initialize GPGME.
169
241
 */
170
 
static bool init_gpgme(const char *seckey,
171
 
                       const char *pubkey, const char *tempdir){
 
242
static bool init_gpgme(const char *seckey, const char *pubkey,
 
243
                       const char *tempdir){
172
244
  gpgme_error_t rc;
173
245
  gpgme_engine_info_t engine_info;
174
246
  
183
255
    
184
256
    fd = (int)TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
185
257
    if(fd == -1){
186
 
      perror("open");
 
258
      perror_plus("open");
187
259
      return false;
188
260
    }
189
261
    
190
262
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
191
263
    if(rc != GPG_ERR_NO_ERROR){
192
 
      fprintf(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
 
264
      fprintf_plus(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
193
265
              gpgme_strsource(rc), gpgme_strerror(rc));
194
266
      return false;
195
267
    }
196
268
    
197
269
    rc = gpgme_op_import(mc.ctx, pgp_data);
198
270
    if(rc != GPG_ERR_NO_ERROR){
199
 
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
 
271
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
200
272
              gpgme_strsource(rc), gpgme_strerror(rc));
201
273
      return false;
202
274
    }
203
275
    
204
276
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
205
277
    if(ret == -1){
206
 
      perror("close");
 
278
      perror_plus("close");
207
279
    }
208
280
    gpgme_data_release(pgp_data);
209
281
    return true;
210
282
  }
211
283
  
212
284
  if(debug){
213
 
    fprintf(stderr, "Initializing GPGME\n");
 
285
    fprintf_plus(stderr, "Initializing GPGME\n");
214
286
  }
215
287
  
216
288
  /* Init GPGME */
217
289
  gpgme_check_version(NULL);
218
290
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
219
291
  if(rc != GPG_ERR_NO_ERROR){
220
 
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
 
292
    fprintf_plus(stderr, "bad gpgme_engine_check_version: %s: %s\n",
221
293
            gpgme_strsource(rc), gpgme_strerror(rc));
222
294
    return false;
223
295
  }
224
296
  
225
 
    /* Set GPGME home directory for the OpenPGP engine only */
 
297
  /* Set GPGME home directory for the OpenPGP engine only */
226
298
  rc = gpgme_get_engine_info(&engine_info);
227
299
  if(rc != GPG_ERR_NO_ERROR){
228
 
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
 
300
    fprintf_plus(stderr, "bad gpgme_get_engine_info: %s: %s\n",
229
301
            gpgme_strsource(rc), gpgme_strerror(rc));
230
302
    return false;
231
303
  }
238
310
    engine_info = engine_info->next;
239
311
  }
240
312
  if(engine_info == NULL){
241
 
    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);
242
314
    return false;
243
315
  }
244
316
  
245
317
  /* Create new GPGME "context" */
246
318
  rc = gpgme_new(&(mc.ctx));
247
319
  if(rc != GPG_ERR_NO_ERROR){
248
 
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
249
 
            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));
250
323
    return false;
251
324
  }
252
325
  
271
344
  ssize_t plaintext_length = 0;
272
345
  
273
346
  if(debug){
274
 
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
 
347
    fprintf_plus(stderr, "Trying to decrypt OpenPGP data\n");
275
348
  }
276
349
  
277
350
  /* Create new GPGME data buffer from memory cryptotext */
278
351
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
279
352
                               0);
280
353
  if(rc != GPG_ERR_NO_ERROR){
281
 
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
 
354
    fprintf_plus(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
282
355
            gpgme_strsource(rc), gpgme_strerror(rc));
283
356
    return -1;
284
357
  }
286
359
  /* Create new empty GPGME data buffer for the plaintext */
287
360
  rc = gpgme_data_new(&dh_plain);
288
361
  if(rc != GPG_ERR_NO_ERROR){
289
 
    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",
290
364
            gpgme_strsource(rc), gpgme_strerror(rc));
291
365
    gpgme_data_release(dh_crypto);
292
366
    return -1;
296
370
     data buffer */
297
371
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
298
372
  if(rc != GPG_ERR_NO_ERROR){
299
 
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
 
373
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
300
374
            gpgme_strsource(rc), gpgme_strerror(rc));
301
375
    plaintext_length = -1;
302
376
    if(debug){
303
377
      gpgme_decrypt_result_t result;
304
378
      result = gpgme_op_decrypt_result(mc.ctx);
305
379
      if(result == NULL){
306
 
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
 
380
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
307
381
      } else {
308
 
        fprintf(stderr, "Unsupported algorithm: %s\n",
 
382
        fprintf_plus(stderr, "Unsupported algorithm: %s\n",
309
383
                result->unsupported_algorithm);
310
 
        fprintf(stderr, "Wrong key usage: %u\n",
 
384
        fprintf_plus(stderr, "Wrong key usage: %u\n",
311
385
                result->wrong_key_usage);
312
386
        if(result->file_name != NULL){
313
 
          fprintf(stderr, "File name: %s\n", result->file_name);
 
387
          fprintf_plus(stderr, "File name: %s\n", result->file_name);
314
388
        }
315
389
        gpgme_recipient_t recipient;
316
390
        recipient = result->recipients;
317
391
        while(recipient != NULL){
318
 
          fprintf(stderr, "Public key algorithm: %s\n",
 
392
          fprintf_plus(stderr, "Public key algorithm: %s\n",
319
393
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
320
 
          fprintf(stderr, "Key ID: %s\n", recipient->keyid);
321
 
          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",
322
396
                  recipient->status == GPG_ERR_NO_SECKEY
323
397
                  ? "No" : "Yes");
324
398
          recipient = recipient->next;
329
403
  }
330
404
  
331
405
  if(debug){
332
 
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
 
406
    fprintf_plus(stderr, "Decryption of OpenPGP data succeeded\n");
333
407
  }
334
408
  
335
409
  /* Seek back to the beginning of the GPGME plaintext data buffer */
336
410
  if(gpgme_data_seek(dh_plain, (off_t)0, SEEK_SET) == -1){
337
 
    perror("gpgme_data_seek");
 
411
    perror_plus("gpgme_data_seek");
338
412
    plaintext_length = -1;
339
413
    goto decrypt_end;
340
414
  }
342
416
  *plaintext = NULL;
343
417
  while(true){
344
418
    plaintext_capacity = incbuffer(plaintext,
345
 
                                      (size_t)plaintext_length,
346
 
                                      plaintext_capacity);
 
419
                                   (size_t)plaintext_length,
 
420
                                   plaintext_capacity);
347
421
    if(plaintext_capacity == 0){
348
 
        perror("incbuffer");
349
 
        plaintext_length = -1;
350
 
        goto decrypt_end;
 
422
      perror_plus("incbuffer");
 
423
      plaintext_length = -1;
 
424
      goto decrypt_end;
351
425
    }
352
426
    
353
427
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
358
432
      break;
359
433
    }
360
434
    if(ret < 0){
361
 
      perror("gpgme_data_read");
 
435
      perror_plus("gpgme_data_read");
362
436
      plaintext_length = -1;
363
437
      goto decrypt_end;
364
438
    }
366
440
  }
367
441
  
368
442
  if(debug){
369
 
    fprintf(stderr, "Decrypted password is: ");
 
443
    fprintf_plus(stderr, "Decrypted password is: ");
370
444
    for(ssize_t i = 0; i < plaintext_length; i++){
371
445
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
372
446
    }
394
468
/* GnuTLS log function callback */
395
469
static void debuggnutls(__attribute__((unused)) int level,
396
470
                        const char* string){
397
 
  fprintf(stderr, "GnuTLS: %s", string);
 
471
  fprintf_plus(stderr, "GnuTLS: %s", string);
398
472
}
399
473
 
400
474
static int init_gnutls_global(const char *pubkeyfilename,
402
476
  int ret;
403
477
  
404
478
  if(debug){
405
 
    fprintf(stderr, "Initializing GnuTLS\n");
 
479
    fprintf_plus(stderr, "Initializing GnuTLS\n");
406
480
  }
407
481
  
408
482
  ret = gnutls_global_init();
409
483
  if(ret != GNUTLS_E_SUCCESS){
410
 
    fprintf(stderr, "GnuTLS global_init: %s\n",
411
 
            safer_gnutls_strerror(ret));
 
484
    fprintf_plus(stderr, "GnuTLS global_init: %s\n", safer_gnutls_strerror(ret));
412
485
    return -1;
413
486
  }
414
487
  
421
494
  }
422
495
  
423
496
  /* OpenPGP credentials */
424
 
  gnutls_certificate_allocate_credentials(&mc.cred);
 
497
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
425
498
  if(ret != GNUTLS_E_SUCCESS){
426
 
    fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning
427
 
                                                    from
428
 
                                                    -Wunreachable-code
429
 
                                                 */
430
 
            safer_gnutls_strerror(ret));
 
499
    fprintf_plus(stderr, "GnuTLS memory error: %s\n", safer_gnutls_strerror(ret));
431
500
    gnutls_global_deinit();
432
501
    return -1;
433
502
  }
434
503
  
435
504
  if(debug){
436
 
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
 
505
    fprintf_plus(stderr, "Attempting to use OpenPGP public key %s and"
437
506
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
438
507
            seckeyfilename);
439
508
  }
442
511
    (mc.cred, pubkeyfilename, seckeyfilename,
443
512
     GNUTLS_OPENPGP_FMT_BASE64);
444
513
  if(ret != GNUTLS_E_SUCCESS){
445
 
    fprintf(stderr,
446
 
            "Error[%d] while reading the OpenPGP key pair ('%s',"
447
 
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
448
 
    fprintf(stderr, "The GnuTLS error is: %s\n",
449
 
            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));
450
518
    goto globalfail;
451
519
  }
452
520
  
453
521
  /* GnuTLS server initialization */
454
522
  ret = gnutls_dh_params_init(&mc.dh_params);
455
523
  if(ret != GNUTLS_E_SUCCESS){
456
 
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
 
524
    fprintf_plus(stderr, "Error in GnuTLS DH parameter initialization:"
457
525
            " %s\n", safer_gnutls_strerror(ret));
458
526
    goto globalfail;
459
527
  }
460
528
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
461
529
  if(ret != GNUTLS_E_SUCCESS){
462
 
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
 
530
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
463
531
            safer_gnutls_strerror(ret));
464
532
    goto globalfail;
465
533
  }
486
554
    }
487
555
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
488
556
  if(ret != GNUTLS_E_SUCCESS){
489
 
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
 
557
    fprintf_plus(stderr, "Error in GnuTLS session initialization: %s\n",
490
558
            safer_gnutls_strerror(ret));
491
559
  }
492
560
  
500
568
      }
501
569
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
502
570
    if(ret != GNUTLS_E_SUCCESS){
503
 
      fprintf(stderr, "Syntax error at: %s\n", err);
504
 
      fprintf(stderr, "GnuTLS error: %s\n",
505
 
              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));
506
573
      gnutls_deinit(*session);
507
574
      return -1;
508
575
    }
517
584
    }
518
585
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
519
586
  if(ret != GNUTLS_E_SUCCESS){
520
 
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
 
587
    fprintf_plus(stderr, "Error setting GnuTLS credentials: %s\n",
521
588
            safer_gnutls_strerror(ret));
522
589
    gnutls_deinit(*session);
523
590
    return -1;
569
636
    pf = PF_INET;
570
637
    break;
571
638
  default:
572
 
    fprintf(stderr, "Bad address family: %d\n", af);
 
639
    fprintf_plus(stderr, "Bad address family: %d\n", af);
573
640
    errno = EINVAL;
574
641
    return -1;
575
642
  }
580
647
  }
581
648
  
582
649
  if(debug){
583
 
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
 
650
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %" PRIu16
584
651
            "\n", ip, port);
585
652
  }
586
653
  
587
654
  tcp_sd = socket(pf, SOCK_STREAM, 0);
588
655
  if(tcp_sd < 0){
589
656
    int e = errno;
590
 
    perror("socket");
 
657
    perror_plus("socket");
591
658
    errno = e;
592
659
    goto mandos_end;
593
660
  }
607
674
  }
608
675
  if(ret < 0 ){
609
676
    int e = errno;
610
 
    perror("inet_pton");
 
677
    perror_plus("inet_pton");
611
678
    errno = e;
612
679
    goto mandos_end;
613
680
  }
614
681
  if(ret == 0){
615
682
    int e = errno;
616
 
    fprintf(stderr, "Bad address: %s\n", ip);
 
683
    fprintf_plus(stderr, "Bad address: %s\n", ip);
617
684
    errno = e;
618
685
    goto mandos_end;
619
686
  }
624
691
    
625
692
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
626
693
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
627
 
                              -Wunreachable-code*/
 
694
                                -Wunreachable-code*/
628
695
      if(if_index == AVAHI_IF_UNSPEC){
629
 
        fprintf(stderr, "An IPv6 link-local address is incomplete"
 
696
        fprintf_plus(stderr, "An IPv6 link-local address is incomplete"
630
697
                " without a network interface\n");
631
698
        errno = EINVAL;
632
699
        goto mandos_end;
649
716
    if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
650
717
      char interface[IF_NAMESIZE];
651
718
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
652
 
        perror("if_indextoname");
 
719
        perror_plus("if_indextoname");
653
720
      } else {
654
 
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
 
721
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
655
722
                ip, interface, port);
656
723
      }
657
724
    } else {
658
 
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
659
 
              port);
 
725
      fprintf_plus(stderr, "Connection to: %s, port %" PRIu16 "\n", ip, port);
660
726
    }
661
727
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
662
728
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
669
735
                        sizeof(addrstr));
670
736
    }
671
737
    if(pcret == NULL){
672
 
      perror("inet_ntop");
 
738
      perror_plus("inet_ntop");
673
739
    } else {
674
740
      if(strcmp(addrstr, ip) != 0){
675
 
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
 
741
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
676
742
      }
677
743
    }
678
744
  }
688
754
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
689
755
  }
690
756
  if(ret < 0){
691
 
    int e = errno;
692
 
    perror("connect");
693
 
    errno = e;
 
757
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
 
758
      int e = errno;
 
759
      perror_plus("connect");
 
760
      errno = e;
 
761
    }
694
762
    goto mandos_end;
695
763
  }
696
764
  
704
772
  while(true){
705
773
    size_t out_size = strlen(out);
706
774
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
707
 
                                   out_size - written));
 
775
                                        out_size - written));
708
776
    if(ret == -1){
709
777
      int e = errno;
710
 
      perror("write");
 
778
      perror_plus("write");
711
779
      errno = e;
712
780
      goto mandos_end;
713
781
    }
730
798
  }
731
799
  
732
800
  if(debug){
733
 
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
 
801
    fprintf_plus(stderr, "Establishing TLS session with %s\n", ip);
734
802
  }
735
803
  
736
804
  if(quit_now){
738
806
    goto mandos_end;
739
807
  }
740
808
  
 
809
  /* Spurious warning from -Wint-to-pointer-cast */
741
810
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
742
811
  
743
812
  if(quit_now){
755
824
  
756
825
  if(ret != GNUTLS_E_SUCCESS){
757
826
    if(debug){
758
 
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
 
827
      fprintf_plus(stderr, "*** GnuTLS Handshake failed ***\n");
759
828
      gnutls_perror(ret);
760
829
    }
761
830
    errno = EPROTO;
765
834
  /* Read OpenPGP packet that contains the wanted password */
766
835
  
767
836
  if(debug){
768
 
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
769
 
            ip);
 
837
    fprintf_plus(stderr, "Retrieving OpenPGP encrypted password from %s\n", ip);
770
838
  }
771
839
  
772
840
  while(true){
777
845
    }
778
846
    
779
847
    buffer_capacity = incbuffer(&buffer, buffer_length,
780
 
                                   buffer_capacity);
 
848
                                buffer_capacity);
781
849
    if(buffer_capacity == 0){
782
850
      int e = errno;
783
 
      perror("incbuffer");
 
851
      perror_plus("incbuffer");
784
852
      errno = e;
785
853
      goto mandos_end;
786
854
    }
810
878
          }
811
879
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
812
880
        if(ret < 0){
813
 
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
 
881
          fprintf_plus(stderr, "*** GnuTLS Re-handshake failed ***\n");
814
882
          gnutls_perror(ret);
815
883
          errno = EPROTO;
816
884
          goto mandos_end;
817
885
        }
818
886
        break;
819
887
      default:
820
 
        fprintf(stderr, "Unknown error while reading data from"
 
888
        fprintf_plus(stderr, "Unknown error while reading data from"
821
889
                " encrypted session with Mandos server\n");
822
890
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
823
891
        errno = EIO;
829
897
  }
830
898
  
831
899
  if(debug){
832
 
    fprintf(stderr, "Closing TLS session\n");
 
900
    fprintf_plus(stderr, "Closing TLS session\n");
833
901
  }
834
902
  
835
903
  if(quit_now){
847
915
  
848
916
  if(buffer_length > 0){
849
917
    ssize_t decrypted_buffer_size;
850
 
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
851
 
                                               buffer_length,
 
918
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
852
919
                                               &decrypted_buffer);
853
920
    if(decrypted_buffer_size >= 0){
854
921
      
865
932
        if(ret == 0 and ferror(stdout)){
866
933
          int e = errno;
867
934
          if(debug){
868
 
            fprintf(stderr, "Error writing encrypted data: %s\n",
 
935
            fprintf_plus(stderr, "Error writing encrypted data: %s\n",
869
936
                    strerror(errno));
870
937
          }
871
938
          errno = e;
891
958
      if(e == 0){
892
959
        e = errno;
893
960
      }
894
 
      perror("close");
 
961
      perror_plus("close");
895
962
    }
896
963
    gnutls_deinit(session);
 
964
    errno = e;
897
965
    if(quit_now){
898
 
      e = EINTR;
 
966
      errno = EINTR;
899
967
      retval = -1;
900
968
    }
901
 
    errno = e;
902
969
  }
903
970
  return retval;
904
971
}
929
996
  switch(event){
930
997
  default:
931
998
  case AVAHI_RESOLVER_FAILURE:
932
 
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
 
999
    fprintf_plus(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
933
1000
            " of type '%s' in domain '%s': %s\n", name, type, domain,
934
1001
            avahi_strerror(avahi_server_errno(mc.server)));
935
1002
    break;
939
1006
      char ip[AVAHI_ADDRESS_STR_MAX];
940
1007
      avahi_address_snprint(ip, sizeof(ip), address);
941
1008
      if(debug){
942
 
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %"
 
1009
        fprintf_plus(stderr, "Mandos server \"%s\" found on %s (%s, %"
943
1010
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
944
1011
                ip, (intmax_t)interface, port);
945
1012
      }
947
1014
                                           avahi_proto_to_af(proto));
948
1015
      if(ret == 0){
949
1016
        avahi_simple_poll_quit(mc.simple_poll);
 
1017
      } else {
 
1018
        ret = add_server(ip, port, interface,
 
1019
                         avahi_proto_to_af(proto));
950
1020
      }
951
1021
    }
952
1022
  }
976
1046
  default:
977
1047
  case AVAHI_BROWSER_FAILURE:
978
1048
    
979
 
    fprintf(stderr, "(Avahi browser) %s\n",
 
1049
    fprintf_plus(stderr, "(Avahi browser) %s\n",
980
1050
            avahi_strerror(avahi_server_errno(mc.server)));
981
1051
    avahi_simple_poll_quit(mc.simple_poll);
982
1052
    return;
990
1060
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
991
1061
                                    name, type, domain, protocol, 0,
992
1062
                                    resolve_callback, NULL) == NULL)
993
 
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
 
1063
      fprintf_plus(stderr, "Avahi: Failed to resolve service '%s': %s\n",
994
1064
              name, avahi_strerror(avahi_server_errno(mc.server)));
995
1065
    break;
996
1066
    
1000
1070
  case AVAHI_BROWSER_ALL_FOR_NOW:
1001
1071
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1002
1072
    if(debug){
1003
 
      fprintf(stderr, "No Mandos server found, still searching...\n");
 
1073
      fprintf_plus(stderr, "No Mandos server found, still searching...\n");
1004
1074
    }
1005
1075
    break;
1006
1076
  }
1007
1077
}
1008
1078
 
1009
 
/* stop main loop after sigterm has been called */
 
1079
/* Signal handler that stops main loop after SIGTERM */
1010
1080
static void handle_sigterm(int sig){
1011
1081
  if(quit_now){
1012
1082
    return;
1014
1084
  quit_now = 1;
1015
1085
  signal_received = sig;
1016
1086
  int old_errno = errno;
 
1087
  /* set main loop to exit */
1017
1088
  if(mc.simple_poll != NULL){
1018
1089
    avahi_simple_poll_quit(mc.simple_poll);
1019
1090
  }
1020
1091
  errno = old_errno;
1021
1092
}
1022
1093
 
 
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){
 
1105
    if(debug){
 
1106
      perror_plus("ioctl SIOCGIFFLAGS");
 
1107
    }
 
1108
    return false;
 
1109
  }
 
1110
  return true;
 
1111
}
 
1112
 
 
1113
bool good_flags(const char *ifname, const struct ifreq *ifr){
 
1114
  
 
1115
  /* Reject the loopback device */
 
1116
  if(ifr->ifr_flags & IFF_LOOPBACK){
 
1117
    if(debug){
 
1118
      fprintf_plus(stderr, "Rejecting loopback interface \"%s\"\n", ifname);
 
1119
    }
 
1120
    return false;
 
1121
  }
 
1122
  /* Accept point-to-point devices only if connect_to is specified */
 
1123
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
 
1124
    if(debug){
 
1125
      fprintf_plus(stderr, "Accepting point-to-point interface \"%s\"\n", ifname);
 
1126
    }
 
1127
    return true;
 
1128
  }
 
1129
  /* Otherwise, reject non-broadcast-capable devices */
 
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
  
 
1144
  /* Accept this device */
 
1145
  if(debug){
 
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
  }
 
1355
}
 
1356
 
1023
1357
int main(int argc, char *argv[]){
1024
1358
  AvahiSServiceBrowser *sb = NULL;
1025
1359
  int error;
1027
1361
  intmax_t tmpmax;
1028
1362
  char *tmp;
1029
1363
  int exitcode = EXIT_SUCCESS;
1030
 
  const char *interface = "eth0";
 
1364
  const char *interface = "";
1031
1365
  struct ifreq network;
1032
1366
  int sd = -1;
1033
1367
  bool take_down_interface = false;
1034
1368
  uid_t uid;
1035
1369
  gid_t gid;
1036
 
  char *connect_to = NULL;
1037
1370
  char tempdir[] = "/tmp/mandosXXXXXX";
1038
1371
  bool tempdir_created = false;
1039
1372
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1043
1376
  bool gnutls_initialized = false;
1044
1377
  bool gpgme_initialized = false;
1045
1378
  float delay = 2.5f;
 
1379
  double retry_interval = 10; /* 10s between trying a server and
 
1380
                                 retrying the same server again */
1046
1381
  
1047
1382
  struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
1048
1383
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
1054
1389
  errno = 0;
1055
1390
  ret = setgid(gid);
1056
1391
  if(ret == -1){
1057
 
    perror("setgid");
 
1392
    perror_plus("setgid");
1058
1393
  }
1059
1394
  
1060
1395
  /* Lower user privileges (temporarily) */
1061
1396
  errno = 0;
1062
1397
  ret = seteuid(uid);
1063
1398
  if(ret == -1){
1064
 
    perror("seteuid");
 
1399
    perror_plus("seteuid");
1065
1400
  }
1066
1401
  
1067
1402
  if(quit_now){
1102
1437
        .arg = "SECONDS",
1103
1438
        .doc = "Maximum delay to wait for interface startup",
1104
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 },
1105
1448
      /*
1106
1449
       * These reproduce what we would get without ARGP_NO_HELP
1107
1450
       */
1151
1494
        if(errno != 0 or tmp == arg or *tmp != '\0'){
1152
1495
          argp_error(state, "Bad delay");
1153
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;
1154
1508
        break;
1155
1509
        /*
1156
1510
         * These reproduce what we would get without ARGP_NO_HELP
1163
1517
        argp_state_help(state, state->out_stream,
1164
1518
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1165
1519
      case 'V':                 /* --version */
1166
 
        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);
1167
1522
        exit(argp_err_exit_status);
1168
1523
        break;
1169
1524
      default:
1184
1539
    case ENOMEM:
1185
1540
    default:
1186
1541
      errno = ret;
1187
 
      perror("argp_parse");
 
1542
      perror_plus("argp_parse");
1188
1543
      exitcode = EX_OSERR;
1189
1544
      goto end;
1190
1545
    case EINVAL:
1192
1547
      goto end;
1193
1548
    }
1194
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
  }
1195
1706
  
1196
1707
  if(not debug){
1197
1708
    avahi_set_log_function(empty_log);
1198
1709
  }
1199
1710
  
 
1711
  if(interface[0] == '\0'){
 
1712
    struct dirent **direntries;
 
1713
    /* First look for interfaces that are up */
 
1714
    ret = scandir(sys_class_net, &direntries, up_interface,
 
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
    }
 
1722
    if(ret >= 1){
 
1723
      /* Pick the first interface returned */
 
1724
      interface = strdup(direntries[0]->d_name);
 
1725
      if(debug){
 
1726
        fprintf_plus(stderr, "Using interface \"%s\"\n", interface);
 
1727
      }
 
1728
      if(interface == NULL){
 
1729
        perror_plus("malloc");
 
1730
        free(direntries);
 
1731
        exitcode = EXIT_FAILURE;
 
1732
        goto end;
 
1733
      }
 
1734
      free(direntries);
 
1735
    } else {
 
1736
      free(direntries);
 
1737
      fprintf_plus(stderr, "Could not find a network interface\n");
 
1738
      exitcode = EXIT_FAILURE;
 
1739
      goto end;
 
1740
    }
 
1741
  }
 
1742
  
1200
1743
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
1201
1744
     from the signal handler */
1202
1745
  /* Initialize the pseudo-RNG for Avahi */
1203
1746
  srand((unsigned int) time(NULL));
1204
1747
  mc.simple_poll = avahi_simple_poll_new();
1205
1748
  if(mc.simple_poll == NULL){
1206
 
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
 
1749
    fprintf_plus(stderr, "Avahi: Failed to create simple poll object.\n");
1207
1750
    exitcode = EX_UNAVAILABLE;
1208
1751
    goto end;
1209
1752
  }
1211
1754
  sigemptyset(&sigterm_action.sa_mask);
1212
1755
  ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
1213
1756
  if(ret == -1){
1214
 
    perror("sigaddset");
 
1757
    perror_plus("sigaddset");
1215
1758
    exitcode = EX_OSERR;
1216
1759
    goto end;
1217
1760
  }
1218
1761
  ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
1219
1762
  if(ret == -1){
1220
 
    perror("sigaddset");
 
1763
    perror_plus("sigaddset");
1221
1764
    exitcode = EX_OSERR;
1222
1765
    goto end;
1223
1766
  }
1224
1767
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
1225
1768
  if(ret == -1){
1226
 
    perror("sigaddset");
 
1769
    perror_plus("sigaddset");
1227
1770
    exitcode = EX_OSERR;
1228
1771
    goto end;
1229
1772
  }
1233
1776
  */
1234
1777
  ret = sigaction(SIGINT, NULL, &old_sigterm_action);
1235
1778
  if(ret == -1){
1236
 
    perror("sigaction");
 
1779
    perror_plus("sigaction");
1237
1780
    return EX_OSERR;
1238
1781
  }
1239
1782
  if(old_sigterm_action.sa_handler != SIG_IGN){
1240
1783
    ret = sigaction(SIGINT, &sigterm_action, NULL);
1241
1784
    if(ret == -1){
1242
 
      perror("sigaction");
 
1785
      perror_plus("sigaction");
1243
1786
      exitcode = EX_OSERR;
1244
1787
      goto end;
1245
1788
    }
1246
1789
  }
1247
1790
  ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
1248
1791
  if(ret == -1){
1249
 
    perror("sigaction");
 
1792
    perror_plus("sigaction");
1250
1793
    return EX_OSERR;
1251
1794
  }
1252
1795
  if(old_sigterm_action.sa_handler != SIG_IGN){
1253
1796
    ret = sigaction(SIGHUP, &sigterm_action, NULL);
1254
1797
    if(ret == -1){
1255
 
      perror("sigaction");
 
1798
      perror_plus("sigaction");
1256
1799
      exitcode = EX_OSERR;
1257
1800
      goto end;
1258
1801
    }
1259
1802
  }
1260
1803
  ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
1261
1804
  if(ret == -1){
1262
 
    perror("sigaction");
 
1805
    perror_plus("sigaction");
1263
1806
    return EX_OSERR;
1264
1807
  }
1265
1808
  if(old_sigterm_action.sa_handler != SIG_IGN){
1266
1809
    ret = sigaction(SIGTERM, &sigterm_action, NULL);
1267
1810
    if(ret == -1){
1268
 
      perror("sigaction");
 
1811
      perror_plus("sigaction");
1269
1812
      exitcode = EX_OSERR;
1270
1813
      goto end;
1271
1814
    }
1272
1815
  }
1273
1816
  
1274
1817
  /* If the interface is down, bring it up */
1275
 
  if(interface[0] != '\0'){
 
1818
  if(strcmp(interface, "none") != 0){
1276
1819
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1277
1820
    if(if_index == 0){
1278
 
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
 
1821
      fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
1279
1822
      exitcode = EX_UNAVAILABLE;
1280
1823
      goto end;
1281
1824
    }
1288
1831
    errno = 0;
1289
1832
    ret = seteuid(0);
1290
1833
    if(ret == -1){
1291
 
      perror("seteuid");
 
1834
      perror_plus("seteuid");
1292
1835
    }
1293
1836
    
1294
1837
#ifdef __linux__
1298
1841
    bool restore_loglevel = true;
1299
1842
    if(ret == -1){
1300
1843
      restore_loglevel = false;
1301
 
      perror("klogctl");
 
1844
      perror_plus("klogctl");
1302
1845
    }
1303
1846
#endif  /* __linux__ */
1304
1847
    
1305
1848
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1306
1849
    if(sd < 0){
1307
 
      perror("socket");
 
1850
      perror_plus("socket");
1308
1851
      exitcode = EX_OSERR;
1309
1852
#ifdef __linux__
1310
1853
      if(restore_loglevel){
1311
1854
        ret = klogctl(7, NULL, 0);
1312
1855
        if(ret == -1){
1313
 
          perror("klogctl");
 
1856
          perror_plus("klogctl");
1314
1857
        }
1315
1858
      }
1316
1859
#endif  /* __linux__ */
1318
1861
      errno = 0;
1319
1862
      ret = seteuid(uid);
1320
1863
      if(ret == -1){
1321
 
        perror("seteuid");
 
1864
        perror_plus("seteuid");
1322
1865
      }
1323
1866
      goto end;
1324
1867
    }
1325
1868
    strcpy(network.ifr_name, interface);
1326
1869
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
1327
1870
    if(ret == -1){
1328
 
      perror("ioctl SIOCGIFFLAGS");
 
1871
      perror_plus("ioctl SIOCGIFFLAGS");
1329
1872
#ifdef __linux__
1330
1873
      if(restore_loglevel){
1331
1874
        ret = klogctl(7, NULL, 0);
1332
1875
        if(ret == -1){
1333
 
          perror("klogctl");
 
1876
          perror_plus("klogctl");
1334
1877
        }
1335
1878
      }
1336
1879
#endif  /* __linux__ */
1339
1882
      errno = 0;
1340
1883
      ret = seteuid(uid);
1341
1884
      if(ret == -1){
1342
 
        perror("seteuid");
 
1885
        perror_plus("seteuid");
1343
1886
      }
1344
1887
      goto end;
1345
1888
    }
1349
1892
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1350
1893
      if(ret == -1){
1351
1894
        take_down_interface = false;
1352
 
        perror("ioctl SIOCSIFFLAGS");
 
1895
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1353
1896
        exitcode = EX_OSERR;
1354
1897
#ifdef __linux__
1355
1898
        if(restore_loglevel){
1356
1899
          ret = klogctl(7, NULL, 0);
1357
1900
          if(ret == -1){
1358
 
            perror("klogctl");
 
1901
            perror_plus("klogctl");
1359
1902
          }
1360
1903
        }
1361
1904
#endif  /* __linux__ */
1363
1906
        errno = 0;
1364
1907
        ret = seteuid(uid);
1365
1908
        if(ret == -1){
1366
 
          perror("seteuid");
 
1909
          perror_plus("seteuid");
1367
1910
        }
1368
1911
        goto end;
1369
1912
      }
1370
1913
    }
1371
 
    /* sleep checking until interface is running */
 
1914
    /* Sleep checking until interface is running.
 
1915
       Check every 0.25s, up to total time of delay */
1372
1916
    for(int i=0; i < delay * 4; i++){
1373
1917
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1374
1918
      if(ret == -1){
1375
 
        perror("ioctl SIOCGIFFLAGS");
 
1919
        perror_plus("ioctl SIOCGIFFLAGS");
1376
1920
      } else if(network.ifr_flags & IFF_RUNNING){
1377
1921
        break;
1378
1922
      }
1379
1923
      struct timespec sleeptime = { .tv_nsec = 250000000 };
1380
1924
      ret = nanosleep(&sleeptime, NULL);
1381
1925
      if(ret == -1 and errno != EINTR){
1382
 
        perror("nanosleep");
 
1926
        perror_plus("nanosleep");
1383
1927
      }
1384
1928
    }
1385
1929
    if(not take_down_interface){
1386
1930
      /* We won't need the socket anymore */
1387
1931
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1388
1932
      if(ret == -1){
1389
 
        perror("close");
 
1933
        perror_plus("close");
1390
1934
      }
1391
1935
    }
1392
1936
#ifdef __linux__
1394
1938
      /* Restores kernel loglevel to default */
1395
1939
      ret = klogctl(7, NULL, 0);
1396
1940
      if(ret == -1){
1397
 
        perror("klogctl");
 
1941
        perror_plus("klogctl");
1398
1942
      }
1399
1943
    }
1400
1944
#endif  /* __linux__ */
1404
1948
      /* Lower privileges */
1405
1949
      ret = seteuid(uid);
1406
1950
      if(ret == -1){
1407
 
        perror("seteuid");
 
1951
        perror_plus("seteuid");
1408
1952
      }
1409
1953
    } else {
1410
1954
      /* Lower privileges permanently */
1411
1955
      ret = setuid(uid);
1412
1956
      if(ret == -1){
1413
 
        perror("setuid");
 
1957
        perror_plus("setuid");
1414
1958
      }
1415
1959
    }
1416
1960
  }
1421
1965
  
1422
1966
  ret = init_gnutls_global(pubkey, seckey);
1423
1967
  if(ret == -1){
1424
 
    fprintf(stderr, "init_gnutls_global failed\n");
 
1968
    fprintf_plus(stderr, "init_gnutls_global failed\n");
1425
1969
    exitcode = EX_UNAVAILABLE;
1426
1970
    goto end;
1427
1971
  } else {
1432
1976
    goto end;
1433
1977
  }
1434
1978
  
 
1979
  if(mkdtemp(tempdir) == NULL){
 
1980
    perror_plus("mkdtemp");
 
1981
    goto end;
 
1982
  }
1435
1983
  tempdir_created = true;
1436
 
  if(mkdtemp(tempdir) == NULL){
1437
 
    tempdir_created = false;
1438
 
    perror("mkdtemp");
1439
 
    goto end;
1440
 
  }
1441
1984
  
1442
1985
  if(quit_now){
1443
1986
    goto end;
1444
1987
  }
1445
1988
  
1446
1989
  if(not init_gpgme(pubkey, seckey, tempdir)){
1447
 
    fprintf(stderr, "init_gpgme failed\n");
 
1990
    fprintf_plus(stderr, "init_gpgme failed\n");
1448
1991
    exitcode = EX_UNAVAILABLE;
1449
1992
    goto end;
1450
1993
  } else {
1460
2003
    /* (Mainly meant for debugging) */
1461
2004
    char *address = strrchr(connect_to, ':');
1462
2005
    if(address == NULL){
1463
 
      fprintf(stderr, "No colon in address\n");
 
2006
      fprintf_plus(stderr, "No colon in address\n");
1464
2007
      exitcode = EX_USAGE;
1465
2008
      goto end;
1466
2009
    }
1474
2017
    tmpmax = strtoimax(address+1, &tmp, 10);
1475
2018
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
1476
2019
       or tmpmax != (uint16_t)tmpmax){
1477
 
      fprintf(stderr, "Bad port number\n");
 
2020
      fprintf_plus(stderr, "Bad port number\n");
1478
2021
      exitcode = EX_USAGE;
1479
2022
      goto end;
1480
2023
    }
1485
2028
    
1486
2029
    port = (uint16_t)tmpmax;
1487
2030
    *address = '\0';
1488
 
    address = connect_to;
1489
2031
    /* Colon in address indicates IPv6 */
1490
2032
    int af;
1491
 
    if(strchr(address, ':') != NULL){
 
2033
    if(strchr(connect_to, ':') != NULL){
1492
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
        }
1493
2041
    } else {
1494
2042
      af = AF_INET;
1495
2043
    }
 
2044
    address = connect_to;
1496
2045
    
1497
2046
    if(quit_now){
1498
2047
      goto end;
1499
2048
    }
1500
2049
    
1501
 
    ret = start_mandos_communication(address, port, if_index, af);
1502
 
    if(ret < 0){
1503
 
      switch(errno){
1504
 
      case ENETUNREACH:
1505
 
      case EHOSTDOWN:
1506
 
      case EHOSTUNREACH:
1507
 
        exitcode = EX_NOHOST;
1508
 
        break;
1509
 
      case EINVAL:
1510
 
        exitcode = EX_USAGE;
1511
 
        break;
1512
 
      case EIO:
1513
 
        exitcode = EX_IOERR;
1514
 
        break;
1515
 
      case EPROTO:
1516
 
        exitcode = EX_PROTOCOL;
1517
 
        break;
1518
 
      default:
1519
 
        exitcode = EX_OSERR;
1520
 
        break;
1521
 
      }
1522
 
    } else {
 
2050
    while(not quit_now){
 
2051
      ret = start_mandos_communication(address, port, if_index, af);
 
2052
      if(quit_now or ret == 0){
 
2053
        break;
 
2054
      }
 
2055
      if(debug){
 
2056
        fprintf_plus(stderr, "Retrying in %d seconds\n", (int)retry_interval);
 
2057
      }
 
2058
      sleep((int)retry_interval);
 
2059
    }
 
2060
    
 
2061
    if (not quit_now){
1523
2062
      exitcode = EXIT_SUCCESS;
1524
2063
    }
 
2064
    
1525
2065
    goto end;
1526
2066
  }
1527
2067
  
1549
2089
  
1550
2090
  /* Check if creating the Avahi server object succeeded */
1551
2091
  if(mc.server == NULL){
1552
 
    fprintf(stderr, "Failed to create Avahi server: %s\n",
 
2092
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
1553
2093
            avahi_strerror(error));
1554
2094
    exitcode = EX_UNAVAILABLE;
1555
2095
    goto end;
1564
2104
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
1565
2105
                                   NULL, 0, browse_callback, NULL);
1566
2106
  if(sb == NULL){
1567
 
    fprintf(stderr, "Failed to create service browser: %s\n",
 
2107
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
1568
2108
            avahi_strerror(avahi_server_errno(mc.server)));
1569
2109
    exitcode = EX_UNAVAILABLE;
1570
2110
    goto end;
1577
2117
  /* Run the main loop */
1578
2118
  
1579
2119
  if(debug){
1580
 
    fprintf(stderr, "Starting Avahi loop search\n");
1581
 
  }
1582
 
  
1583
 
  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
  }
1584
2129
  
1585
2130
 end:
1586
2131
  
1587
2132
  if(debug){
1588
 
    fprintf(stderr, "%s exiting\n", argv[0]);
 
2133
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
1589
2134
  }
1590
2135
  
1591
2136
  /* Cleanup things */
1607
2152
  if(gpgme_initialized){
1608
2153
    gpgme_release(mc.ctx);
1609
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  */
1610
2168
  
1611
2169
  /* Take down the network interface */
1612
2170
  if(take_down_interface){
1614
2172
    errno = 0;
1615
2173
    ret = seteuid(0);
1616
2174
    if(ret == -1){
1617
 
      perror("seteuid");
 
2175
      perror_plus("seteuid");
1618
2176
    }
1619
2177
    if(geteuid() == 0){
1620
2178
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1621
2179
      if(ret == -1){
1622
 
        perror("ioctl SIOCGIFFLAGS");
1623
 
      } else if(network.ifr_flags & IFF_UP) {
 
2180
        perror_plus("ioctl SIOCGIFFLAGS");
 
2181
      } else if(network.ifr_flags & IFF_UP){
1624
2182
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
1625
2183
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
1626
2184
        if(ret == -1){
1627
 
          perror("ioctl SIOCSIFFLAGS");
 
2185
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
1628
2186
        }
1629
2187
      }
1630
2188
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1631
2189
      if(ret == -1){
1632
 
        perror("close");
 
2190
        perror_plus("close");
1633
2191
      }
1634
2192
      /* Lower privileges permanently */
1635
2193
      errno = 0;
1636
2194
      ret = setuid(uid);
1637
2195
      if(ret == -1){
1638
 
        perror("setuid");
 
2196
        perror_plus("setuid");
1639
2197
      }
1640
2198
    }
1641
2199
  }
1642
2200
  
1643
 
  /* Removes the temp directory used by GPGME */
 
2201
  /* Removes the GPGME temp directory and all files inside */
1644
2202
  if(tempdir_created){
1645
 
    DIR *d;
1646
 
    struct dirent *direntry;
1647
 
    d = opendir(tempdir);
1648
 
    if(d == NULL){
1649
 
      if(errno != ENOENT){
1650
 
        perror("opendir");
1651
 
      }
1652
 
    } else {
1653
 
      while(true){
1654
 
        direntry = readdir(d);
1655
 
        if(direntry == NULL){
1656
 
          break;
1657
 
        }
1658
 
        /* Skip "." and ".." */
1659
 
        if(direntry->d_name[0] == '.'
1660
 
           and (direntry->d_name[1] == '\0'
1661
 
                or (direntry->d_name[1] == '.'
1662
 
                    and direntry->d_name[2] == '\0'))){
1663
 
          continue;
1664
 
        }
 
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];
1665
2210
        char *fullname = NULL;
1666
2211
        ret = asprintf(&fullname, "%s/%s", tempdir,
1667
2212
                       direntry->d_name);
1668
2213
        if(ret < 0){
1669
 
          perror("asprintf");
 
2214
          perror_plus("asprintf");
1670
2215
          continue;
1671
2216
        }
1672
2217
        ret = remove(fullname);
1673
2218
        if(ret == -1){
1674
 
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
1675
 
                  strerror(errno));
 
2219
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname, strerror(errno));
1676
2220
        }
1677
2221
        free(fullname);
1678
2222
      }
1679
 
      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");
1680
2229
    }
1681
2230
    ret = rmdir(tempdir);
1682
2231
    if(ret == -1 and errno != ENOENT){
1683
 
      perror("rmdir");
 
2232
      perror_plus("rmdir");
1684
2233
    }
1685
2234
  }
1686
2235
  
1691
2240
                                            &old_sigterm_action,
1692
2241
                                            NULL));
1693
2242
    if(ret == -1){
1694
 
      perror("sigaction");
 
2243
      perror_plus("sigaction");
1695
2244
    }
1696
2245
    do {
1697
2246
      ret = raise(signal_received);
1698
2247
    } while(ret != 0 and errno == EINTR);
1699
2248
    if(ret != 0){
1700
 
      perror("raise");
 
2249
      perror_plus("raise");
1701
2250
      abort();
1702
2251
    }
1703
2252
    TEMP_FAILURE_RETRY(pause());