/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: Teddy Hogeborn
  • Date: 2014-07-13 21:55:28 UTC
  • mfrom: (237.4.49 release)
  • Revision ID: teddy@recompile.se-20140713215528-5lez8qv009g0i1h2
Merge from release branch.

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-2011 Teddy Hogeborn
13
 
 * Copyright © 2008-2011 Björn Påhlsson
 
12
 * Copyright © 2008-2014 Teddy Hogeborn
 
13
 * Copyright © 2008-2014 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
32
32
/* Needed by GPGME, specifically gpgme_data_seek() */
33
33
#ifndef _LARGEFILE_SOURCE
34
34
#define _LARGEFILE_SOURCE
35
 
#endif
 
35
#endif  /* not _LARGEFILE_SOURCE */
36
36
#ifndef _FILE_OFFSET_BITS
37
37
#define _FILE_OFFSET_BITS 64
38
 
#endif
 
38
#endif  /* not _FILE_OFFSET_BITS */
39
39
 
40
40
#define _GNU_SOURCE             /* TEMP_FAILURE_RETRY(), asprintf() */
41
41
 
42
42
#include <stdio.h>              /* fprintf(), stderr, fwrite(),
43
 
                                   stdout, ferror(), remove() */
44
 
#include <stdint.h>             /* uint16_t, uint32_t */
 
43
                                   stdout, ferror() */
 
44
#include <stdint.h>             /* uint16_t, uint32_t, intptr_t */
45
45
#include <stddef.h>             /* NULL, size_t, ssize_t */
46
46
#include <stdlib.h>             /* free(), EXIT_SUCCESS, srand(),
47
47
                                   strtof(), abort() */
55
55
                                   opendir(), DIR */
56
56
#include <sys/stat.h>           /* open(), S_ISREG */
57
57
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
58
 
                                   inet_pton(), connect() */
59
 
#include <fcntl.h>              /* open() */
 
58
                                   inet_pton(), connect(),
 
59
                                   getnameinfo() */
 
60
#include <fcntl.h>              /* open(), unlinkat() */
60
61
#include <dirent.h>             /* opendir(), struct dirent, readdir()
61
62
                                 */
62
63
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
63
64
                                   strtoimax() */
64
 
#include <assert.h>             /* assert() */
65
65
#include <errno.h>              /* perror(), errno,
66
66
                                   program_invocation_short_name */
67
67
#include <time.h>               /* nanosleep(), time(), sleep() */
73
73
                                */
74
74
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
75
75
                                   getuid(), getgid(), seteuid(),
76
 
                                   setgid(), pause() */
77
 
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
 
76
                                   setgid(), pause(), _exit(),
 
77
                                   unlinkat() */
 
78
#include <arpa/inet.h>          /* inet_pton(), htons() */
78
79
#include <iso646.h>             /* not, or, and */
79
80
#include <argp.h>               /* struct argp_option, error_t, struct
80
81
                                   argp_state, struct argp,
87
88
                                   EX_NOHOST, EX_IOERR, EX_PROTOCOL */
88
89
#include <sys/wait.h>           /* waitpid(), WIFEXITED(),
89
90
                                   WEXITSTATUS(), WTERMSIG() */
 
91
#include <grp.h>                /* setgroups() */
 
92
#include <argz.h>               /* argz_add_sep(), argz_next(),
 
93
                                   argz_delete(), argz_append(),
 
94
                                   argz_stringify(), argz_add(),
 
95
                                   argz_count() */
 
96
#include <netdb.h>              /* getnameinfo(), NI_NUMERICHOST,
 
97
                                   EAI_SYSTEM, gai_strerror() */
90
98
 
91
99
#ifdef __linux__
92
100
#include <sys/klog.h>           /* klogctl() */
134
142
static const char sys_class_net[] = "/sys/class/net";
135
143
char *connect_to = NULL;
136
144
const char *hookdir = HOOKDIR;
 
145
int hookdir_fd = -1;
 
146
uid_t uid = 65534;
 
147
gid_t gid = 65534;
137
148
 
138
149
/* Doubly linked list that need to be circularly linked when used */
139
150
typedef struct server{
140
151
  const char *ip;
141
 
  uint16_t port;
 
152
  in_port_t port;
142
153
  AvahiIfIndex if_index;
143
154
  int af;
144
155
  struct timespec last_seen;
148
159
 
149
160
/* Used for passing in values through the Avahi callback functions */
150
161
typedef struct {
151
 
  AvahiSimplePoll *simple_poll;
152
162
  AvahiServer *server;
153
163
  gnutls_certificate_credentials_t cred;
154
164
  unsigned int dh_bits;
156
166
  const char *priority;
157
167
  gpgme_ctx_t ctx;
158
168
  server *current_server;
 
169
  char *interfaces;
 
170
  size_t interfaces_size;
159
171
} mandos_context;
160
172
 
161
 
/* global context so signal handler can reach it*/
162
 
mandos_context mc = { .simple_poll = NULL, .server = NULL,
163
 
                      .dh_bits = 1024, .priority = "SECURE256"
164
 
                      ":!CTYPE-X.509:+CTYPE-OPENPGP",
165
 
                      .current_server = NULL };
 
173
/* global so signal handler can reach it*/
 
174
AvahiSimplePoll *simple_poll;
166
175
 
167
176
sig_atomic_t quit_now = 0;
168
177
int signal_received = 0;
169
178
 
170
179
/* Function to use when printing errors */
171
180
void perror_plus(const char *print_text){
 
181
  int e = errno;
172
182
  fprintf(stderr, "Mandos plugin %s: ",
173
183
          program_invocation_short_name);
 
184
  errno = e;
174
185
  perror(print_text);
175
186
}
176
187
 
 
188
__attribute__((format (gnu_printf, 2, 3), nonnull))
 
189
int fprintf_plus(FILE *stream, const char *format, ...){
 
190
  va_list ap;
 
191
  va_start (ap, format);
 
192
  
 
193
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ",
 
194
                             program_invocation_short_name));
 
195
  return (int)TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
 
196
}
 
197
 
177
198
/*
178
199
 * Make additional room in "buffer" for at least BUFFER_SIZE more
179
200
 * bytes. "buffer_capacity" is how much is currently allocated,
180
201
 * "buffer_length" is how much is already used.
181
202
 */
 
203
__attribute__((nonnull, warn_unused_result))
182
204
size_t incbuffer(char **buffer, size_t buffer_length,
183
205
                 size_t buffer_capacity){
184
206
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
185
 
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
186
 
    if(buffer == NULL){
 
207
    char *new_buf = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
 
208
    if(new_buf == NULL){
 
209
      int old_errno = errno;
 
210
      free(*buffer);
 
211
      errno = old_errno;
 
212
      *buffer = NULL;
187
213
      return 0;
188
214
    }
 
215
    *buffer = new_buf;
189
216
    buffer_capacity += BUFFER_SIZE;
190
217
  }
191
218
  return buffer_capacity;
192
219
}
193
220
 
194
221
/* Add server to set of servers to retry periodically */
195
 
int add_server(const char *ip, uint16_t port, AvahiIfIndex if_index,
196
 
               int af){
 
222
__attribute__((nonnull, warn_unused_result))
 
223
bool add_server(const char *ip, in_port_t port, AvahiIfIndex if_index,
 
224
                int af, server **current_server){
197
225
  int ret;
198
226
  server *new_server = malloc(sizeof(server));
199
227
  if(new_server == NULL){
200
228
    perror_plus("malloc");
201
 
    return -1;
 
229
    return false;
202
230
  }
203
231
  *new_server = (server){ .ip = strdup(ip),
204
232
                          .port = port,
206
234
                          .af = af };
207
235
  if(new_server->ip == NULL){
208
236
    perror_plus("strdup");
209
 
    return -1;
 
237
    free(new_server);
 
238
    return false;
 
239
  }
 
240
  ret = clock_gettime(CLOCK_MONOTONIC, &(new_server->last_seen));
 
241
  if(ret == -1){
 
242
    perror_plus("clock_gettime");
 
243
    free(new_server->ip);
 
244
    free(new_server);
 
245
    return false;
210
246
  }
211
247
  /* Special case of first server */
212
 
  if (mc.current_server == NULL){
 
248
  if(*current_server == NULL){
213
249
    new_server->next = new_server;
214
250
    new_server->prev = new_server;
215
 
    mc.current_server = new_server;
216
 
  /* Place the new server last in the list */
 
251
    *current_server = new_server;
217
252
  } else {
218
 
    new_server->next = mc.current_server;
219
 
    new_server->prev = mc.current_server->prev;
 
253
    /* Place the new server last in the list */
 
254
    new_server->next = *current_server;
 
255
    new_server->prev = (*current_server)->prev;
220
256
    new_server->prev->next = new_server;
221
 
    mc.current_server->prev = new_server;
222
 
  }
223
 
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
224
 
  if(ret == -1){
225
 
    perror_plus("clock_gettime");
226
 
    return -1;
227
 
  }
228
 
  return 0;
 
257
    (*current_server)->prev = new_server;
 
258
  }
 
259
  return true;
229
260
}
230
261
 
231
262
/* 
232
263
 * Initialize GPGME.
233
264
 */
234
 
static bool init_gpgme(const char *seckey, const char *pubkey,
235
 
                       const char *tempdir){
 
265
__attribute__((nonnull, warn_unused_result))
 
266
static bool init_gpgme(const char * const seckey,
 
267
                       const char * const pubkey,
 
268
                       const char * const tempdir,
 
269
                       mandos_context *mc){
236
270
  gpgme_error_t rc;
237
271
  gpgme_engine_info_t engine_info;
238
272
  
239
 
  
240
273
  /*
241
274
   * Helper function to insert pub and seckey to the engine keyring.
242
275
   */
243
 
  bool import_key(const char *filename){
 
276
  bool import_key(const char * const filename){
244
277
    int ret;
245
278
    int fd;
246
279
    gpgme_data_t pgp_data;
253
286
    
254
287
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
255
288
    if(rc != GPG_ERR_NO_ERROR){
256
 
      fprintf(stderr, "Mandos plugin mandos-client: "
257
 
              "bad gpgme_data_new_from_fd: %s: %s\n",
258
 
              gpgme_strsource(rc), gpgme_strerror(rc));
 
289
      fprintf_plus(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
 
290
                   gpgme_strsource(rc), gpgme_strerror(rc));
259
291
      return false;
260
292
    }
261
293
    
262
 
    rc = gpgme_op_import(mc.ctx, pgp_data);
 
294
    rc = gpgme_op_import(mc->ctx, pgp_data);
263
295
    if(rc != GPG_ERR_NO_ERROR){
264
 
      fprintf(stderr, "Mandos plugin mandos-client: "
265
 
              "bad gpgme_op_import: %s: %s\n",
266
 
              gpgme_strsource(rc), gpgme_strerror(rc));
 
296
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
 
297
                   gpgme_strsource(rc), gpgme_strerror(rc));
267
298
      return false;
268
299
    }
269
300
    
276
307
  }
277
308
  
278
309
  if(debug){
279
 
    fprintf(stderr, "Mandos plugin mandos-client: "
280
 
            "Initializing GPGME\n");
 
310
    fprintf_plus(stderr, "Initializing GPGME\n");
281
311
  }
282
312
  
283
313
  /* Init GPGME */
284
314
  gpgme_check_version(NULL);
285
315
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
286
316
  if(rc != GPG_ERR_NO_ERROR){
287
 
    fprintf(stderr, "Mandos plugin mandos-client: "
288
 
            "bad gpgme_engine_check_version: %s: %s\n",
289
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
317
    fprintf_plus(stderr, "bad gpgme_engine_check_version: %s: %s\n",
 
318
                 gpgme_strsource(rc), gpgme_strerror(rc));
290
319
    return false;
291
320
  }
292
321
  
293
322
  /* Set GPGME home directory for the OpenPGP engine only */
294
323
  rc = gpgme_get_engine_info(&engine_info);
295
324
  if(rc != GPG_ERR_NO_ERROR){
296
 
    fprintf(stderr, "Mandos plugin mandos-client: "
297
 
            "bad gpgme_get_engine_info: %s: %s\n",
298
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
325
    fprintf_plus(stderr, "bad gpgme_get_engine_info: %s: %s\n",
 
326
                 gpgme_strsource(rc), gpgme_strerror(rc));
299
327
    return false;
300
328
  }
301
329
  while(engine_info != NULL){
307
335
    engine_info = engine_info->next;
308
336
  }
309
337
  if(engine_info == NULL){
310
 
    fprintf(stderr, "Mandos plugin mandos-client: "
311
 
            "Could not set GPGME home dir to %s\n", tempdir);
 
338
    fprintf_plus(stderr, "Could not set GPGME home dir to %s\n",
 
339
                 tempdir);
312
340
    return false;
313
341
  }
314
342
  
315
343
  /* Create new GPGME "context" */
316
 
  rc = gpgme_new(&(mc.ctx));
 
344
  rc = gpgme_new(&(mc->ctx));
317
345
  if(rc != GPG_ERR_NO_ERROR){
318
 
    fprintf(stderr, "Mandos plugin mandos-client: "
319
 
            "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
320
 
            gpgme_strerror(rc));
 
346
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
 
347
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
 
348
                 gpgme_strerror(rc));
321
349
    return false;
322
350
  }
323
351
  
332
360
 * Decrypt OpenPGP data.
333
361
 * Returns -1 on error
334
362
 */
 
363
__attribute__((nonnull, warn_unused_result))
335
364
static ssize_t pgp_packet_decrypt(const char *cryptotext,
336
365
                                  size_t crypto_size,
337
 
                                  char **plaintext){
 
366
                                  char **plaintext,
 
367
                                  mandos_context *mc){
338
368
  gpgme_data_t dh_crypto, dh_plain;
339
369
  gpgme_error_t rc;
340
370
  ssize_t ret;
342
372
  ssize_t plaintext_length = 0;
343
373
  
344
374
  if(debug){
345
 
    fprintf(stderr, "Mandos plugin mandos-client: "
346
 
            "Trying to decrypt OpenPGP data\n");
 
375
    fprintf_plus(stderr, "Trying to decrypt OpenPGP data\n");
347
376
  }
348
377
  
349
378
  /* Create new GPGME data buffer from memory cryptotext */
350
379
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
351
380
                               0);
352
381
  if(rc != GPG_ERR_NO_ERROR){
353
 
    fprintf(stderr, "Mandos plugin mandos-client: "
354
 
            "bad gpgme_data_new_from_mem: %s: %s\n",
355
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
382
    fprintf_plus(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
 
383
                 gpgme_strsource(rc), gpgme_strerror(rc));
356
384
    return -1;
357
385
  }
358
386
  
359
387
  /* Create new empty GPGME data buffer for the plaintext */
360
388
  rc = gpgme_data_new(&dh_plain);
361
389
  if(rc != GPG_ERR_NO_ERROR){
362
 
    fprintf(stderr, "Mandos plugin mandos-client: "
363
 
            "bad gpgme_data_new: %s: %s\n",
364
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
390
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
 
391
                 "bad gpgme_data_new: %s: %s\n",
 
392
                 gpgme_strsource(rc), gpgme_strerror(rc));
365
393
    gpgme_data_release(dh_crypto);
366
394
    return -1;
367
395
  }
368
396
  
369
397
  /* Decrypt data from the cryptotext data buffer to the plaintext
370
398
     data buffer */
371
 
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
 
399
  rc = gpgme_op_decrypt(mc->ctx, dh_crypto, dh_plain);
372
400
  if(rc != GPG_ERR_NO_ERROR){
373
 
    fprintf(stderr, "Mandos plugin mandos-client: "
374
 
            "bad gpgme_op_decrypt: %s: %s\n",
375
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
401
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
 
402
                 gpgme_strsource(rc), gpgme_strerror(rc));
376
403
    plaintext_length = -1;
377
404
    if(debug){
378
405
      gpgme_decrypt_result_t result;
379
 
      result = gpgme_op_decrypt_result(mc.ctx);
 
406
      result = gpgme_op_decrypt_result(mc->ctx);
380
407
      if(result == NULL){
381
 
        fprintf(stderr, "Mandos plugin mandos-client: "
382
 
                "gpgme_op_decrypt_result failed\n");
 
408
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
383
409
      } else {
384
 
        fprintf(stderr, "Mandos plugin mandos-client: "
385
 
                "Unsupported algorithm: %s\n",
386
 
                result->unsupported_algorithm);
387
 
        fprintf(stderr, "Mandos plugin mandos-client: "
388
 
                "Wrong key usage: %u\n",
389
 
                result->wrong_key_usage);
 
410
        fprintf_plus(stderr, "Unsupported algorithm: %s\n",
 
411
                     result->unsupported_algorithm);
 
412
        fprintf_plus(stderr, "Wrong key usage: %u\n",
 
413
                     result->wrong_key_usage);
390
414
        if(result->file_name != NULL){
391
 
          fprintf(stderr, "Mandos plugin mandos-client: "
392
 
                  "File name: %s\n", result->file_name);
 
415
          fprintf_plus(stderr, "File name: %s\n", result->file_name);
393
416
        }
394
417
        gpgme_recipient_t recipient;
395
418
        recipient = result->recipients;
396
419
        while(recipient != NULL){
397
 
          fprintf(stderr, "Mandos plugin mandos-client: "
398
 
                  "Public key algorithm: %s\n",
399
 
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
400
 
          fprintf(stderr, "Mandos plugin mandos-client: "
401
 
                  "Key ID: %s\n", recipient->keyid);
402
 
          fprintf(stderr, "Mandos plugin mandos-client: "
403
 
                  "Secret key available: %s\n",
404
 
                  recipient->status == GPG_ERR_NO_SECKEY
405
 
                  ? "No" : "Yes");
 
420
          fprintf_plus(stderr, "Public key algorithm: %s\n",
 
421
                       gpgme_pubkey_algo_name
 
422
                       (recipient->pubkey_algo));
 
423
          fprintf_plus(stderr, "Key ID: %s\n", recipient->keyid);
 
424
          fprintf_plus(stderr, "Secret key available: %s\n",
 
425
                       recipient->status == GPG_ERR_NO_SECKEY
 
426
                       ? "No" : "Yes");
406
427
          recipient = recipient->next;
407
428
        }
408
429
      }
411
432
  }
412
433
  
413
434
  if(debug){
414
 
    fprintf(stderr, "Mandos plugin mandos-client: "
415
 
            "Decryption of OpenPGP data succeeded\n");
 
435
    fprintf_plus(stderr, "Decryption of OpenPGP data succeeded\n");
416
436
  }
417
437
  
418
438
  /* Seek back to the beginning of the GPGME plaintext data buffer */
449
469
  }
450
470
  
451
471
  if(debug){
452
 
    fprintf(stderr, "Mandos plugin mandos-client: "
453
 
            "Decrypted password is: ");
 
472
    fprintf_plus(stderr, "Decrypted password is: ");
454
473
    for(ssize_t i = 0; i < plaintext_length; i++){
455
474
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
456
475
    }
467
486
  return plaintext_length;
468
487
}
469
488
 
470
 
static const char * safer_gnutls_strerror(int value){
471
 
  const char *ret = gnutls_strerror(value); /* Spurious warning from
472
 
                                               -Wunreachable-code */
 
489
__attribute__((warn_unused_result))
 
490
static const char *safer_gnutls_strerror(int value){
 
491
  const char *ret = gnutls_strerror(value);
473
492
  if(ret == NULL)
474
493
    ret = "(unknown)";
475
494
  return ret;
476
495
}
477
496
 
478
497
/* GnuTLS log function callback */
 
498
__attribute__((nonnull))
479
499
static void debuggnutls(__attribute__((unused)) int level,
480
500
                        const char* string){
481
 
  fprintf(stderr, "Mandos plugin mandos-client: GnuTLS: %s", string);
 
501
  fprintf_plus(stderr, "GnuTLS: %s", string);
482
502
}
483
503
 
 
504
__attribute__((nonnull, warn_unused_result))
484
505
static int init_gnutls_global(const char *pubkeyfilename,
485
 
                              const char *seckeyfilename){
 
506
                              const char *seckeyfilename,
 
507
                              mandos_context *mc){
486
508
  int ret;
487
509
  
488
510
  if(debug){
489
 
    fprintf(stderr, "Mandos plugin mandos-client: "
490
 
            "Initializing GnuTLS\n");
 
511
    fprintf_plus(stderr, "Initializing GnuTLS\n");
491
512
  }
492
513
  
493
514
  ret = gnutls_global_init();
494
515
  if(ret != GNUTLS_E_SUCCESS){
495
 
    fprintf(stderr, "Mandos plugin mandos-client: "
496
 
            "GnuTLS global_init: %s\n", safer_gnutls_strerror(ret));
 
516
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
 
517
                 safer_gnutls_strerror(ret));
497
518
    return -1;
498
519
  }
499
520
  
506
527
  }
507
528
  
508
529
  /* OpenPGP credentials */
509
 
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
 
530
  ret = gnutls_certificate_allocate_credentials(&mc->cred);
510
531
  if(ret != GNUTLS_E_SUCCESS){
511
 
    fprintf(stderr, "Mandos plugin mandos-client: "
512
 
            "GnuTLS memory error: %s\n", safer_gnutls_strerror(ret));
 
532
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
 
533
                 safer_gnutls_strerror(ret));
513
534
    gnutls_global_deinit();
514
535
    return -1;
515
536
  }
516
537
  
517
538
  if(debug){
518
 
    fprintf(stderr, "Mandos plugin mandos-client: "
519
 
            "Attempting to use OpenPGP public key %s and"
520
 
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
521
 
            seckeyfilename);
 
539
    fprintf_plus(stderr, "Attempting to use OpenPGP public key %s and"
 
540
                 " secret key %s as GnuTLS credentials\n",
 
541
                 pubkeyfilename,
 
542
                 seckeyfilename);
522
543
  }
523
544
  
524
545
  ret = gnutls_certificate_set_openpgp_key_file
525
 
    (mc.cred, pubkeyfilename, seckeyfilename,
 
546
    (mc->cred, pubkeyfilename, seckeyfilename,
526
547
     GNUTLS_OPENPGP_FMT_BASE64);
527
548
  if(ret != GNUTLS_E_SUCCESS){
528
 
    fprintf(stderr,
529
 
            "Mandos plugin mandos-client: "
530
 
            "Error[%d] while reading the OpenPGP key pair ('%s',"
531
 
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
532
 
    fprintf(stderr, "Mandos plugin mandos-client: "
533
 
            "The GnuTLS error is: %s\n", safer_gnutls_strerror(ret));
 
549
    fprintf_plus(stderr,
 
550
                 "Error[%d] while reading the OpenPGP key pair ('%s',"
 
551
                 " '%s')\n", ret, pubkeyfilename, seckeyfilename);
 
552
    fprintf_plus(stderr, "The GnuTLS error is: %s\n",
 
553
                 safer_gnutls_strerror(ret));
534
554
    goto globalfail;
535
555
  }
536
556
  
537
557
  /* GnuTLS server initialization */
538
 
  ret = gnutls_dh_params_init(&mc.dh_params);
 
558
  ret = gnutls_dh_params_init(&mc->dh_params);
539
559
  if(ret != GNUTLS_E_SUCCESS){
540
 
    fprintf(stderr, "Mandos plugin mandos-client: "
541
 
            "Error in GnuTLS DH parameter initialization:"
542
 
            " %s\n", safer_gnutls_strerror(ret));
 
560
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
 
561
                 " initialization: %s\n",
 
562
                 safer_gnutls_strerror(ret));
543
563
    goto globalfail;
544
564
  }
545
 
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
 
565
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
546
566
  if(ret != GNUTLS_E_SUCCESS){
547
 
    fprintf(stderr, "Mandos plugin mandos-client: "
548
 
            "Error in GnuTLS prime generation: %s\n",
549
 
            safer_gnutls_strerror(ret));
 
567
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
 
568
                 safer_gnutls_strerror(ret));
550
569
    goto globalfail;
551
570
  }
552
571
  
553
 
  gnutls_certificate_set_dh_params(mc.cred, mc.dh_params);
 
572
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
554
573
  
555
574
  return 0;
556
575
  
557
576
 globalfail:
558
577
  
559
 
  gnutls_certificate_free_credentials(mc.cred);
 
578
  gnutls_certificate_free_credentials(mc->cred);
560
579
  gnutls_global_deinit();
561
 
  gnutls_dh_params_deinit(mc.dh_params);
 
580
  gnutls_dh_params_deinit(mc->dh_params);
562
581
  return -1;
563
582
}
564
583
 
565
 
static int init_gnutls_session(gnutls_session_t *session){
 
584
__attribute__((nonnull, warn_unused_result))
 
585
static int init_gnutls_session(gnutls_session_t *session,
 
586
                               mandos_context *mc){
566
587
  int ret;
567
588
  /* GnuTLS session creation */
568
589
  do {
572
593
    }
573
594
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
574
595
  if(ret != GNUTLS_E_SUCCESS){
575
 
    fprintf(stderr, "Mandos plugin mandos-client: "
576
 
            "Error in GnuTLS session initialization: %s\n",
577
 
            safer_gnutls_strerror(ret));
 
596
    fprintf_plus(stderr,
 
597
                 "Error in GnuTLS session initialization: %s\n",
 
598
                 safer_gnutls_strerror(ret));
578
599
  }
579
600
  
580
601
  {
581
602
    const char *err;
582
603
    do {
583
 
      ret = gnutls_priority_set_direct(*session, mc.priority, &err);
 
604
      ret = gnutls_priority_set_direct(*session, mc->priority, &err);
584
605
      if(quit_now){
585
606
        gnutls_deinit(*session);
586
607
        return -1;
587
608
      }
588
609
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
589
610
    if(ret != GNUTLS_E_SUCCESS){
590
 
      fprintf(stderr, "Mandos plugin mandos-client: "
591
 
              "Syntax error at: %s\n", err);
592
 
      fprintf(stderr, "Mandos plugin mandos-client: "
593
 
              "GnuTLS error: %s\n", safer_gnutls_strerror(ret));
 
611
      fprintf_plus(stderr, "Syntax error at: %s\n", err);
 
612
      fprintf_plus(stderr, "GnuTLS error: %s\n",
 
613
                   safer_gnutls_strerror(ret));
594
614
      gnutls_deinit(*session);
595
615
      return -1;
596
616
    }
598
618
  
599
619
  do {
600
620
    ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
601
 
                                 mc.cred);
 
621
                                 mc->cred);
602
622
    if(quit_now){
603
623
      gnutls_deinit(*session);
604
624
      return -1;
605
625
    }
606
626
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
607
627
  if(ret != GNUTLS_E_SUCCESS){
608
 
    fprintf(stderr, "Mandos plugin mandos-client: "
609
 
            "Error setting GnuTLS credentials: %s\n",
610
 
            safer_gnutls_strerror(ret));
 
628
    fprintf_plus(stderr, "Error setting GnuTLS credentials: %s\n",
 
629
                 safer_gnutls_strerror(ret));
611
630
    gnutls_deinit(*session);
612
631
    return -1;
613
632
  }
615
634
  /* ignore client certificate if any. */
616
635
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
617
636
  
618
 
  gnutls_dh_set_prime_bits(*session, mc.dh_bits);
 
637
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
619
638
  
620
639
  return 0;
621
640
}
625
644
                      __attribute__((unused)) const char *txt){}
626
645
 
627
646
/* Called when a Mandos server is found */
628
 
static int start_mandos_communication(const char *ip, uint16_t port,
 
647
__attribute__((nonnull, warn_unused_result))
 
648
static int start_mandos_communication(const char *ip, in_port_t port,
629
649
                                      AvahiIfIndex if_index,
630
 
                                      int af){
 
650
                                      int af, mandos_context *mc){
631
651
  int ret, tcp_sd = -1;
632
652
  ssize_t sret;
633
 
  union {
634
 
    struct sockaddr_in in;
635
 
    struct sockaddr_in6 in6;
636
 
  } to;
 
653
  struct sockaddr_storage to;
637
654
  char *buffer = NULL;
638
655
  char *decrypted_buffer = NULL;
639
656
  size_t buffer_length = 0;
658
675
    pf = PF_INET;
659
676
    break;
660
677
  default:
661
 
    fprintf(stderr, "Mandos plugin mandos-client: "
662
 
            "Bad address family: %d\n", af);
 
678
    fprintf_plus(stderr, "Bad address family: %d\n", af);
663
679
    errno = EINVAL;
664
680
    return -1;
665
681
  }
666
682
  
667
 
  ret = init_gnutls_session(&session);
 
683
  /* If the interface is specified and we have a list of interfaces */
 
684
  if(if_index != AVAHI_IF_UNSPEC and mc->interfaces != NULL){
 
685
    /* Check if the interface is one of the interfaces we are using */
 
686
    bool match = false;
 
687
    {
 
688
      char *interface = NULL;
 
689
      while((interface=argz_next(mc->interfaces, mc->interfaces_size,
 
690
                                 interface))){
 
691
        if(if_nametoindex(interface) == (unsigned int)if_index){
 
692
          match = true;
 
693
          break;
 
694
        }
 
695
      }
 
696
    }
 
697
    if(not match){
 
698
      /* This interface does not match any in the list, so we don't
 
699
         connect to the server */
 
700
      if(debug){
 
701
        char interface[IF_NAMESIZE];
 
702
        if(if_indextoname((unsigned int)if_index, interface) == NULL){
 
703
          perror_plus("if_indextoname");
 
704
        } else {
 
705
          fprintf_plus(stderr, "Skipping server on non-used interface"
 
706
                       " \"%s\"\n",
 
707
                       if_indextoname((unsigned int)if_index,
 
708
                                      interface));
 
709
        }
 
710
      }
 
711
      return -1;
 
712
    }
 
713
  }
 
714
  
 
715
  ret = init_gnutls_session(&session, mc);
668
716
  if(ret != 0){
669
717
    return -1;
670
718
  }
671
719
  
672
720
  if(debug){
673
 
    fprintf(stderr, "Mandos plugin mandos-client: "
674
 
            "Setting up a TCP connection to %s, port %" PRIu16
675
 
            "\n", ip, port);
 
721
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
 
722
                 PRIuMAX "\n", ip, (uintmax_t)port);
676
723
  }
677
724
  
678
725
  tcp_sd = socket(pf, SOCK_STREAM, 0);
690
737
  
691
738
  memset(&to, 0, sizeof(to));
692
739
  if(af == AF_INET6){
693
 
    to.in6.sin6_family = (sa_family_t)af;
694
 
    ret = inet_pton(af, ip, &to.in6.sin6_addr);
 
740
    ((struct sockaddr_in6 *)&to)->sin6_family = (sa_family_t)af;
 
741
    ret = inet_pton(af, ip, &((struct sockaddr_in6 *)&to)->sin6_addr);
695
742
  } else {                      /* IPv4 */
696
 
    to.in.sin_family = (sa_family_t)af;
697
 
    ret = inet_pton(af, ip, &to.in.sin_addr);
 
743
    ((struct sockaddr_in *)&to)->sin_family = (sa_family_t)af;
 
744
    ret = inet_pton(af, ip, &((struct sockaddr_in *)&to)->sin_addr);
698
745
  }
699
746
  if(ret < 0 ){
700
747
    int e = errno;
704
751
  }
705
752
  if(ret == 0){
706
753
    int e = errno;
707
 
    fprintf(stderr, "Mandos plugin mandos-client: "
708
 
            "Bad address: %s\n", ip);
 
754
    fprintf_plus(stderr, "Bad address: %s\n", ip);
709
755
    errno = e;
710
756
    goto mandos_end;
711
757
  }
712
758
  if(af == AF_INET6){
713
 
    to.in6.sin6_port = htons(port); /* Spurious warnings from
714
 
                                       -Wconversion and
715
 
                                       -Wunreachable-code */
716
 
    
717
 
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
718
 
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
719
 
                                -Wunreachable-code*/
 
759
    ((struct sockaddr_in6 *)&to)->sin6_port = htons(port);
 
760
    if(IN6_IS_ADDR_LINKLOCAL
 
761
       (&((struct sockaddr_in6 *)&to)->sin6_addr)){
720
762
      if(if_index == AVAHI_IF_UNSPEC){
721
 
        fprintf(stderr, "Mandos plugin mandos-client: "
722
 
                "An IPv6 link-local address is incomplete"
723
 
                " without a network interface\n");
 
763
        fprintf_plus(stderr, "An IPv6 link-local address is"
 
764
                     " incomplete without a network interface\n");
724
765
        errno = EINVAL;
725
766
        goto mandos_end;
726
767
      }
727
768
      /* Set the network interface number as scope */
728
 
      to.in6.sin6_scope_id = (uint32_t)if_index;
 
769
      ((struct sockaddr_in6 *)&to)->sin6_scope_id = (uint32_t)if_index;
729
770
    }
730
771
  } else {
731
 
    to.in.sin_port = htons(port); /* Spurious warnings from
732
 
                                     -Wconversion and
733
 
                                     -Wunreachable-code */
 
772
    ((struct sockaddr_in *)&to)->sin_port = htons(port);
734
773
  }
735
774
  
736
775
  if(quit_now){
744
783
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
745
784
        perror_plus("if_indextoname");
746
785
      } else {
747
 
        fprintf(stderr, "Mandos plugin mandos-client: "
748
 
                "Connection to: %s%%%s, port %" PRIu16 "\n",
749
 
                ip, interface, port);
 
786
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIuMAX
 
787
                     "\n", ip, interface, (uintmax_t)port);
750
788
      }
751
789
    } else {
752
 
      fprintf(stderr, "Mandos plugin mandos-client: "
753
 
              "Connection to: %s, port %" PRIu16 "\n", ip, port);
 
790
      fprintf_plus(stderr, "Connection to: %s, port %" PRIuMAX "\n",
 
791
                   ip, (uintmax_t)port);
754
792
    }
755
793
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
756
794
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
757
 
    const char *pcret;
758
795
    if(af == AF_INET6){
759
 
      pcret = inet_ntop(af, &(to.in6.sin6_addr), addrstr,
760
 
                        sizeof(addrstr));
 
796
      ret = getnameinfo((struct sockaddr *)&to,
 
797
                        sizeof(struct sockaddr_in6),
 
798
                        addrstr, sizeof(addrstr), NULL, 0,
 
799
                        NI_NUMERICHOST);
761
800
    } else {
762
 
      pcret = inet_ntop(af, &(to.in.sin_addr), addrstr,
763
 
                        sizeof(addrstr));
 
801
      ret = getnameinfo((struct sockaddr *)&to,
 
802
                        sizeof(struct sockaddr_in),
 
803
                        addrstr, sizeof(addrstr), NULL, 0,
 
804
                        NI_NUMERICHOST);
764
805
    }
765
 
    if(pcret == NULL){
766
 
      perror_plus("inet_ntop");
767
 
    } else {
768
 
      if(strcmp(addrstr, ip) != 0){
769
 
        fprintf(stderr, "Mandos plugin mandos-client: "
770
 
                "Canonical address form: %s\n", addrstr);
771
 
      }
 
806
    if(ret == EAI_SYSTEM){
 
807
      perror_plus("getnameinfo");
 
808
    } else if(ret != 0) {
 
809
      fprintf_plus(stderr, "getnameinfo: %s", gai_strerror(ret));
 
810
    } else if(strcmp(addrstr, ip) != 0){
 
811
      fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
772
812
    }
773
813
  }
774
814
  
778
818
  }
779
819
  
780
820
  if(af == AF_INET6){
781
 
    ret = connect(tcp_sd, &to.in6, sizeof(to));
 
821
    ret = connect(tcp_sd, (struct sockaddr *)&to,
 
822
                  sizeof(struct sockaddr_in6));
782
823
  } else {
783
 
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
 
824
    ret = connect(tcp_sd, (struct sockaddr *)&to, /* IPv4 */
 
825
                  sizeof(struct sockaddr_in));
784
826
  }
785
827
  if(ret < 0){
786
 
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
 
828
    if((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
787
829
      int e = errno;
788
830
      perror_plus("connect");
789
831
      errno = e;
827
869
  }
828
870
  
829
871
  if(debug){
830
 
    fprintf(stderr, "Mandos plugin mandos-client: "
831
 
            "Establishing TLS session with %s\n", ip);
 
872
    fprintf_plus(stderr, "Establishing TLS session with %s\n", ip);
832
873
  }
833
874
  
834
875
  if(quit_now){
836
877
    goto mandos_end;
837
878
  }
838
879
  
839
 
  /* Spurious warning from -Wint-to-pointer-cast */
840
 
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
 
880
  /* This casting via intptr_t is to eliminate warning about casting
 
881
     an int to a pointer type.  This is exactly how the GnuTLS Guile
 
882
     function "set-session-transport-fd!" does it. */
 
883
  gnutls_transport_set_ptr(session,
 
884
                           (gnutls_transport_ptr_t)(intptr_t)tcp_sd);
841
885
  
842
886
  if(quit_now){
843
887
    errno = EINTR;
854
898
  
855
899
  if(ret != GNUTLS_E_SUCCESS){
856
900
    if(debug){
857
 
      fprintf(stderr, "Mandos plugin mandos-client: "
858
 
              "*** GnuTLS Handshake failed ***\n");
 
901
      fprintf_plus(stderr, "*** GnuTLS Handshake failed ***\n");
859
902
      gnutls_perror(ret);
860
903
    }
861
904
    errno = EPROTO;
865
908
  /* Read OpenPGP packet that contains the wanted password */
866
909
  
867
910
  if(debug){
868
 
    fprintf(stderr, "Mandos plugin mandos-client: "
869
 
            "Retrieving OpenPGP encrypted password from %s\n", ip);
 
911
    fprintf_plus(stderr, "Retrieving OpenPGP encrypted password from"
 
912
                 " %s\n", ip);
870
913
  }
871
914
  
872
915
  while(true){
910
953
          }
911
954
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
912
955
        if(ret < 0){
913
 
          fprintf(stderr, "Mandos plugin mandos-client: "
914
 
                  "*** GnuTLS Re-handshake failed ***\n");
 
956
          fprintf_plus(stderr, "*** GnuTLS Re-handshake failed "
 
957
                       "***\n");
915
958
          gnutls_perror(ret);
916
959
          errno = EPROTO;
917
960
          goto mandos_end;
918
961
        }
919
962
        break;
920
963
      default:
921
 
        fprintf(stderr, "Mandos plugin mandos-client: "
922
 
                "Unknown error while reading data from"
923
 
                " encrypted session with Mandos server\n");
 
964
        fprintf_plus(stderr, "Unknown error while reading data from"
 
965
                     " encrypted session with Mandos server\n");
924
966
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
925
967
        errno = EIO;
926
968
        goto mandos_end;
931
973
  }
932
974
  
933
975
  if(debug){
934
 
    fprintf(stderr, "Mandos plugin mandos-client: "
935
 
            "Closing TLS session\n");
 
976
    fprintf_plus(stderr, "Closing TLS session\n");
936
977
  }
937
978
  
938
979
  if(quit_now){
951
992
  if(buffer_length > 0){
952
993
    ssize_t decrypted_buffer_size;
953
994
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
954
 
                                               &decrypted_buffer);
 
995
                                               &decrypted_buffer, mc);
955
996
    if(decrypted_buffer_size >= 0){
956
997
      
957
998
      written = 0;
967
1008
        if(ret == 0 and ferror(stdout)){
968
1009
          int e = errno;
969
1010
          if(debug){
970
 
            fprintf(stderr, "Mandos plugin mandos-client: "
971
 
                    "Error writing encrypted data: %s\n",
972
 
                    strerror(errno));
 
1011
            fprintf_plus(stderr, "Error writing encrypted data: %s\n",
 
1012
                         strerror(errno));
973
1013
          }
974
1014
          errno = e;
975
1015
          goto mandos_end;
1006
1046
  return retval;
1007
1047
}
1008
1048
 
 
1049
__attribute__((nonnull))
1009
1050
static void resolve_callback(AvahiSServiceResolver *r,
1010
1051
                             AvahiIfIndex interface,
1011
1052
                             AvahiProtocol proto,
1019
1060
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
1020
1061
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
1021
1062
                             flags,
1022
 
                             AVAHI_GCC_UNUSED void* userdata){
1023
 
  assert(r);
 
1063
                             void *mc){
 
1064
  if(r == NULL){
 
1065
    return;
 
1066
  }
1024
1067
  
1025
1068
  /* Called whenever a service has been resolved successfully or
1026
1069
     timed out */
1032
1075
  switch(event){
1033
1076
  default:
1034
1077
  case AVAHI_RESOLVER_FAILURE:
1035
 
    fprintf(stderr, "Mandos plugin mandos-client: "
1036
 
            "(Avahi Resolver) Failed to resolve service '%s'"
1037
 
            " of type '%s' in domain '%s': %s\n", name, type, domain,
1038
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
1078
    fprintf_plus(stderr, "(Avahi Resolver) Failed to resolve service "
 
1079
                 "'%s' of type '%s' in domain '%s': %s\n", name, type,
 
1080
                 domain,
 
1081
                 avahi_strerror(avahi_server_errno
 
1082
                                (((mandos_context*)mc)->server)));
1039
1083
    break;
1040
1084
    
1041
1085
  case AVAHI_RESOLVER_FOUND:
1043
1087
      char ip[AVAHI_ADDRESS_STR_MAX];
1044
1088
      avahi_address_snprint(ip, sizeof(ip), address);
1045
1089
      if(debug){
1046
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1047
 
                "Mandos server \"%s\" found on %s (%s, %"
1048
 
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
1049
 
                ip, (intmax_t)interface, port);
 
1090
        fprintf_plus(stderr, "Mandos server \"%s\" found on %s (%s, %"
 
1091
                     PRIdMAX ") on port %" PRIu16 "\n", name,
 
1092
                     host_name, ip, (intmax_t)interface, port);
1050
1093
      }
1051
 
      int ret = start_mandos_communication(ip, port, interface,
1052
 
                                           avahi_proto_to_af(proto));
 
1094
      int ret = start_mandos_communication(ip, (in_port_t)port,
 
1095
                                           interface,
 
1096
                                           avahi_proto_to_af(proto),
 
1097
                                           mc);
1053
1098
      if(ret == 0){
1054
 
        avahi_simple_poll_quit(mc.simple_poll);
 
1099
        avahi_simple_poll_quit(simple_poll);
1055
1100
      } else {
1056
 
        ret = add_server(ip, port, interface,
1057
 
                         avahi_proto_to_af(proto));
 
1101
        if(not add_server(ip, (in_port_t)port, interface,
 
1102
                          avahi_proto_to_af(proto),
 
1103
                          &((mandos_context*)mc)->current_server)){
 
1104
          fprintf_plus(stderr, "Failed to add server \"%s\" to server"
 
1105
                       " list\n", name);
 
1106
        }
1058
1107
      }
1059
1108
    }
1060
1109
  }
1070
1119
                            const char *domain,
1071
1120
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
1072
1121
                            flags,
1073
 
                            AVAHI_GCC_UNUSED void* userdata){
1074
 
  assert(b);
 
1122
                            void *mc){
 
1123
  if(b == NULL){
 
1124
    return;
 
1125
  }
1075
1126
  
1076
1127
  /* Called whenever a new services becomes available on the LAN or
1077
1128
     is removed from the LAN */
1084
1135
  default:
1085
1136
  case AVAHI_BROWSER_FAILURE:
1086
1137
    
1087
 
    fprintf(stderr, "Mandos plugin mandos-client: "
1088
 
            "(Avahi browser) %s\n",
1089
 
            avahi_strerror(avahi_server_errno(mc.server)));
1090
 
    avahi_simple_poll_quit(mc.simple_poll);
 
1138
    fprintf_plus(stderr, "(Avahi browser) %s\n",
 
1139
                 avahi_strerror(avahi_server_errno
 
1140
                                (((mandos_context*)mc)->server)));
 
1141
    avahi_simple_poll_quit(simple_poll);
1091
1142
    return;
1092
1143
    
1093
1144
  case AVAHI_BROWSER_NEW:
1096
1147
       the callback function is called the Avahi server will free the
1097
1148
       resolver for us. */
1098
1149
    
1099
 
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
1100
 
                                    name, type, domain, protocol, 0,
1101
 
                                    resolve_callback, NULL) == NULL)
1102
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1103
 
              "Avahi: Failed to resolve service '%s': %s\n",
1104
 
              name, avahi_strerror(avahi_server_errno(mc.server)));
 
1150
    if(avahi_s_service_resolver_new(((mandos_context*)mc)->server,
 
1151
                                    interface, protocol, name, type,
 
1152
                                    domain, protocol, 0,
 
1153
                                    resolve_callback, mc) == NULL)
 
1154
      fprintf_plus(stderr, "Avahi: Failed to resolve service '%s':"
 
1155
                   " %s\n", name,
 
1156
                   avahi_strerror(avahi_server_errno
 
1157
                                  (((mandos_context*)mc)->server)));
1105
1158
    break;
1106
1159
    
1107
1160
  case AVAHI_BROWSER_REMOVE:
1110
1163
  case AVAHI_BROWSER_ALL_FOR_NOW:
1111
1164
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1112
1165
    if(debug){
1113
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1114
 
              "No Mandos server found, still searching...\n");
 
1166
      fprintf_plus(stderr, "No Mandos server found, still"
 
1167
                   " searching...\n");
1115
1168
    }
1116
1169
    break;
1117
1170
  }
1126
1179
  signal_received = sig;
1127
1180
  int old_errno = errno;
1128
1181
  /* set main loop to exit */
1129
 
  if(mc.simple_poll != NULL){
1130
 
    avahi_simple_poll_quit(mc.simple_poll);
 
1182
  if(simple_poll != NULL){
 
1183
    avahi_simple_poll_quit(simple_poll);
1131
1184
  }
1132
1185
  errno = old_errno;
1133
1186
}
1134
1187
 
 
1188
__attribute__((nonnull, warn_unused_result))
1135
1189
bool get_flags(const char *ifname, struct ifreq *ifr){
1136
1190
  int ret;
 
1191
  error_t ret_errno;
1137
1192
  
1138
1193
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1139
1194
  if(s < 0){
 
1195
    ret_errno = errno;
1140
1196
    perror_plus("socket");
 
1197
    errno = ret_errno;
1141
1198
    return false;
1142
1199
  }
1143
1200
  strcpy(ifr->ifr_name, ifname);
1144
1201
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1145
1202
  if(ret == -1){
1146
1203
    if(debug){
 
1204
      ret_errno = errno;
1147
1205
      perror_plus("ioctl SIOCGIFFLAGS");
 
1206
      errno = ret_errno;
1148
1207
    }
1149
1208
    return false;
1150
1209
  }
1151
1210
  return true;
1152
1211
}
1153
1212
 
 
1213
__attribute__((nonnull, warn_unused_result))
1154
1214
bool good_flags(const char *ifname, const struct ifreq *ifr){
1155
1215
  
1156
1216
  /* Reject the loopback device */
1157
1217
  if(ifr->ifr_flags & IFF_LOOPBACK){
1158
1218
    if(debug){
1159
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1160
 
              "Rejecting loopback interface \"%s\"\n", ifname);
 
1219
      fprintf_plus(stderr, "Rejecting loopback interface \"%s\"\n",
 
1220
                   ifname);
1161
1221
    }
1162
1222
    return false;
1163
1223
  }
1164
1224
  /* Accept point-to-point devices only if connect_to is specified */
1165
1225
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
1166
1226
    if(debug){
1167
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1168
 
              "Accepting point-to-point interface \"%s\"\n", ifname);
 
1227
      fprintf_plus(stderr, "Accepting point-to-point interface"
 
1228
                   " \"%s\"\n", ifname);
1169
1229
    }
1170
1230
    return true;
1171
1231
  }
1172
1232
  /* Otherwise, reject non-broadcast-capable devices */
1173
1233
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
1174
1234
    if(debug){
1175
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1176
 
              "Rejecting non-broadcast interface \"%s\"\n", ifname);
 
1235
      fprintf_plus(stderr, "Rejecting non-broadcast interface"
 
1236
                   " \"%s\"\n", ifname);
1177
1237
    }
1178
1238
    return false;
1179
1239
  }
1180
1240
  /* Reject non-ARP interfaces (including dummy interfaces) */
1181
1241
  if(ifr->ifr_flags & IFF_NOARP){
1182
1242
    if(debug){
1183
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1184
 
              "Rejecting non-ARP interface \"%s\"\n", ifname);
 
1243
      fprintf_plus(stderr, "Rejecting non-ARP interface \"%s\"\n",
 
1244
                   ifname);
1185
1245
    }
1186
1246
    return false;
1187
1247
  }
1188
1248
  
1189
1249
  /* Accept this device */
1190
1250
  if(debug){
1191
 
    fprintf(stderr, "Mandos plugin mandos-client: "
1192
 
            "Interface \"%s\" is good\n", ifname);
 
1251
    fprintf_plus(stderr, "Interface \"%s\" is good\n", ifname);
1193
1252
  }
1194
1253
  return true;
1195
1254
}
1199
1258
 * corresponds to an acceptable network device.
1200
1259
 * (This function is passed to scandir(3) as a filter function.)
1201
1260
 */
 
1261
__attribute__((nonnull, warn_unused_result))
1202
1262
int good_interface(const struct dirent *if_entry){
1203
1263
  if(if_entry->d_name[0] == '.'){
1204
1264
    return 0;
1207
1267
  struct ifreq ifr;
1208
1268
  if(not get_flags(if_entry->d_name, &ifr)){
1209
1269
    if(debug){
1210
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1211
 
              "Failed to get flags for interface \"%s\"\n",
1212
 
              if_entry->d_name);
1213
 
    }
1214
 
    return 0;
1215
 
  }
1216
 
  
1217
 
  if(not good_flags(if_entry->d_name, &ifr)){
1218
 
    return 0;
1219
 
  }
1220
 
  return 1;
1221
 
}
1222
 
 
1223
 
/* 
1224
 
 * This function determines if a directory entry in /sys/class/net
1225
 
 * corresponds to an acceptable network device which is up.
1226
 
 * (This function is passed to scandir(3) as a filter function.)
1227
 
 */
1228
 
int up_interface(const struct dirent *if_entry){
1229
 
  if(if_entry->d_name[0] == '.'){
1230
 
    return 0;
1231
 
  }
1232
 
  
1233
 
  struct ifreq ifr;
1234
 
  if(not get_flags(if_entry->d_name, &ifr)){
1235
 
    if(debug){
1236
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1237
 
              "Failed to get flags for interface \"%s\"\n",
1238
 
              if_entry->d_name);
1239
 
    }
1240
 
    return 0;
1241
 
  }
1242
 
  
1243
 
  /* Reject down interfaces */
1244
 
  if(not (ifr.ifr_flags & IFF_UP)){
1245
 
    if(debug){
1246
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1247
 
              "Rejecting down interface \"%s\"\n",
1248
 
              if_entry->d_name);
1249
 
    }
1250
 
    return 0;
1251
 
  }
1252
 
  
1253
 
  /* Reject non-running interfaces */
1254
 
  if(not (ifr.ifr_flags & IFF_RUNNING)){
1255
 
    if(debug){
1256
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1257
 
              "Rejecting non-running interface \"%s\"\n",
1258
 
              if_entry->d_name);
1259
 
    }
1260
 
    return 0;
1261
 
  }
1262
 
  
1263
 
  if(not good_flags(if_entry->d_name, &ifr)){
1264
 
    return 0;
1265
 
  }
1266
 
  return 1;
1267
 
}
1268
 
 
 
1270
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1271
                   "\"%s\"\n", if_entry->d_name);
 
1272
    }
 
1273
    return 0;
 
1274
  }
 
1275
  
 
1276
  if(not good_flags(if_entry->d_name, &ifr)){
 
1277
    return 0;
 
1278
  }
 
1279
  return 1;
 
1280
}
 
1281
 
 
1282
/* 
 
1283
 * This function determines if a network interface is up.
 
1284
 */
 
1285
__attribute__((nonnull, warn_unused_result))
 
1286
bool interface_is_up(const char *interface){
 
1287
  struct ifreq ifr;
 
1288
  if(not get_flags(interface, &ifr)){
 
1289
    if(debug){
 
1290
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1291
                   "\"%s\"\n", interface);
 
1292
    }
 
1293
    return false;
 
1294
  }
 
1295
  
 
1296
  return (bool)(ifr.ifr_flags & IFF_UP);
 
1297
}
 
1298
 
 
1299
/* 
 
1300
 * This function determines if a network interface is running
 
1301
 */
 
1302
__attribute__((nonnull, warn_unused_result))
 
1303
bool interface_is_running(const char *interface){
 
1304
  struct ifreq ifr;
 
1305
  if(not get_flags(interface, &ifr)){
 
1306
    if(debug){
 
1307
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1308
                   "\"%s\"\n", interface);
 
1309
    }
 
1310
    return false;
 
1311
  }
 
1312
  
 
1313
  return (bool)(ifr.ifr_flags & IFF_RUNNING);
 
1314
}
 
1315
 
 
1316
__attribute__((nonnull, pure, warn_unused_result))
1269
1317
int notdotentries(const struct dirent *direntry){
1270
1318
  /* Skip "." and ".." */
1271
1319
  if(direntry->d_name[0] == '.'
1278
1326
}
1279
1327
 
1280
1328
/* Is this directory entry a runnable program? */
 
1329
__attribute__((nonnull, warn_unused_result))
1281
1330
int runnable_hook(const struct dirent *direntry){
1282
1331
  int ret;
1283
1332
  size_t sret;
1291
1340
  sret = strspn(direntry->d_name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1292
1341
                "abcdefghijklmnopqrstuvwxyz"
1293
1342
                "0123456789"
1294
 
                "_-");
 
1343
                "_.-");
1295
1344
  if((direntry->d_name)[sret] != '\0'){
1296
1345
    /* Contains non-allowed characters */
1297
1346
    if(debug){
1298
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1299
 
              "Ignoring hook \"%s\" with bad name\n",
1300
 
              direntry->d_name);
 
1347
      fprintf_plus(stderr, "Ignoring hook \"%s\" with bad name\n",
 
1348
                   direntry->d_name);
1301
1349
    }
1302
1350
    return 0;
1303
1351
  }
1304
1352
  
1305
 
  char *fullname = NULL;
1306
 
  ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
1307
 
  if(ret < 0){
1308
 
    perror_plus("asprintf");
1309
 
    return 0;
1310
 
  }
1311
 
  
1312
 
  ret = stat(fullname, &st);
 
1353
  ret = fstatat(hookdir_fd, direntry->d_name, &st, 0);
1313
1354
  if(ret == -1){
1314
1355
    if(debug){
1315
1356
      perror_plus("Could not stat hook");
1319
1360
  if(not (S_ISREG(st.st_mode))){
1320
1361
    /* Not a regular file */
1321
1362
    if(debug){
1322
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1323
 
              "Ignoring hook \"%s\" - not a file\n",
1324
 
              direntry->d_name);
 
1363
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not a file\n",
 
1364
                   direntry->d_name);
1325
1365
    }
1326
1366
    return 0;
1327
1367
  }
1328
1368
  if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
1329
1369
    /* Not executable */
1330
1370
    if(debug){
1331
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1332
 
              "Ignoring hook \"%s\" - not executable\n",
1333
 
              direntry->d_name);
 
1371
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not executable\n",
 
1372
                   direntry->d_name);
1334
1373
    }
1335
1374
    return 0;
1336
1375
  }
 
1376
  if(debug){
 
1377
    fprintf_plus(stderr, "Hook \"%s\" is acceptable\n",
 
1378
                 direntry->d_name);
 
1379
  }
1337
1380
  return 1;
1338
1381
}
1339
1382
 
1340
 
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
 
1383
__attribute__((nonnull, warn_unused_result))
 
1384
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval,
 
1385
                            mandos_context *mc){
1341
1386
  int ret;
1342
1387
  struct timespec now;
1343
1388
  struct timespec waited_time;
1344
1389
  intmax_t block_time;
1345
1390
  
1346
1391
  while(true){
1347
 
    if(mc.current_server == NULL){
1348
 
      if (debug){
1349
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1350
 
                "Wait until first server is found. No timeout!\n");
 
1392
    if(mc->current_server == NULL){
 
1393
      if(debug){
 
1394
        fprintf_plus(stderr, "Wait until first server is found."
 
1395
                     " No timeout!\n");
1351
1396
      }
1352
1397
      ret = avahi_simple_poll_iterate(s, -1);
1353
1398
    } else {
1354
 
      if (debug){
1355
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1356
 
                "Check current_server if we should run it,"
1357
 
                " or wait\n");
 
1399
      if(debug){
 
1400
        fprintf_plus(stderr, "Check current_server if we should run"
 
1401
                     " it, or wait\n");
1358
1402
      }
1359
1403
      /* the current time */
1360
1404
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
1365
1409
      /* Calculating in ms how long time between now and server
1366
1410
         who we visted longest time ago. Now - last seen.  */
1367
1411
      waited_time.tv_sec = (now.tv_sec
1368
 
                            - mc.current_server->last_seen.tv_sec);
 
1412
                            - mc->current_server->last_seen.tv_sec);
1369
1413
      waited_time.tv_nsec = (now.tv_nsec
1370
 
                             - mc.current_server->last_seen.tv_nsec);
 
1414
                             - mc->current_server->last_seen.tv_nsec);
1371
1415
      /* total time is 10s/10,000ms.
1372
1416
         Converting to s from ms by dividing by 1,000,
1373
1417
         and ns to ms by dividing by 1,000,000. */
1375
1419
                     - ((intmax_t)waited_time.tv_sec * 1000))
1376
1420
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1377
1421
      
1378
 
      if (debug){
1379
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1380
 
                "Blocking for %" PRIdMAX " ms\n", block_time);
 
1422
      if(debug){
 
1423
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
 
1424
                     block_time);
1381
1425
      }
1382
1426
      
1383
1427
      if(block_time <= 0){
1384
 
        ret = start_mandos_communication(mc.current_server->ip,
1385
 
                                         mc.current_server->port,
1386
 
                                         mc.current_server->if_index,
1387
 
                                         mc.current_server->af);
 
1428
        ret = start_mandos_communication(mc->current_server->ip,
 
1429
                                         mc->current_server->port,
 
1430
                                         mc->current_server->if_index,
 
1431
                                         mc->current_server->af, mc);
1388
1432
        if(ret == 0){
1389
 
          avahi_simple_poll_quit(mc.simple_poll);
 
1433
          avahi_simple_poll_quit(s);
1390
1434
          return 0;
1391
1435
        }
1392
1436
        ret = clock_gettime(CLOCK_MONOTONIC,
1393
 
                            &mc.current_server->last_seen);
 
1437
                            &mc->current_server->last_seen);
1394
1438
        if(ret == -1){
1395
1439
          perror_plus("clock_gettime");
1396
1440
          return -1;
1397
1441
        }
1398
 
        mc.current_server = mc.current_server->next;
 
1442
        mc->current_server = mc->current_server->next;
1399
1443
        block_time = 0;         /* Call avahi to find new Mandos
1400
1444
                                   servers, but don't block */
1401
1445
      }
1403
1447
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1404
1448
    }
1405
1449
    if(ret != 0){
1406
 
      if (ret > 0 or errno != EINTR){
 
1450
      if(ret > 0 or errno != EINTR){
1407
1451
        return (ret != 1) ? ret : 0;
1408
1452
      }
1409
1453
    }
1410
1454
  }
1411
1455
}
1412
1456
 
 
1457
/* Set effective uid to 0, return errno */
 
1458
__attribute__((warn_unused_result))
 
1459
error_t raise_privileges(void){
 
1460
  error_t old_errno = errno;
 
1461
  error_t ret_errno = 0;
 
1462
  if(seteuid(0) == -1){
 
1463
    ret_errno = errno;
 
1464
  }
 
1465
  errno = old_errno;
 
1466
  return ret_errno;
 
1467
}
 
1468
 
 
1469
/* Set effective and real user ID to 0.  Return errno. */
 
1470
__attribute__((warn_unused_result))
 
1471
error_t raise_privileges_permanently(void){
 
1472
  error_t old_errno = errno;
 
1473
  error_t ret_errno = raise_privileges();
 
1474
  if(ret_errno != 0){
 
1475
    errno = old_errno;
 
1476
    return ret_errno;
 
1477
  }
 
1478
  if(setuid(0) == -1){
 
1479
    ret_errno = errno;
 
1480
  }
 
1481
  errno = old_errno;
 
1482
  return ret_errno;
 
1483
}
 
1484
 
 
1485
/* Set effective user ID to unprivileged saved user ID */
 
1486
__attribute__((warn_unused_result))
 
1487
error_t lower_privileges(void){
 
1488
  error_t old_errno = errno;
 
1489
  error_t ret_errno = 0;
 
1490
  if(seteuid(uid) == -1){
 
1491
    ret_errno = errno;
 
1492
  }
 
1493
  errno = old_errno;
 
1494
  return ret_errno;
 
1495
}
 
1496
 
 
1497
/* Lower privileges permanently */
 
1498
__attribute__((warn_unused_result))
 
1499
error_t lower_privileges_permanently(void){
 
1500
  error_t old_errno = errno;
 
1501
  error_t ret_errno = 0;
 
1502
  if(setuid(uid) == -1){
 
1503
    ret_errno = errno;
 
1504
  }
 
1505
  errno = old_errno;
 
1506
  return ret_errno;
 
1507
}
 
1508
 
 
1509
__attribute__((nonnull))
 
1510
void run_network_hooks(const char *mode, const char *interface,
 
1511
                       const float delay){
 
1512
  struct dirent **direntries = NULL;
 
1513
  if(hookdir_fd == -1){
 
1514
    hookdir_fd = open(hookdir, O_RDONLY);
 
1515
    if(hookdir_fd == -1){
 
1516
      if(errno == ENOENT){
 
1517
        if(debug){
 
1518
          fprintf_plus(stderr, "Network hook directory \"%s\" not"
 
1519
                       " found\n", hookdir);
 
1520
        }
 
1521
      } else {
 
1522
        perror_plus("open");
 
1523
      }
 
1524
      return;
 
1525
    }
 
1526
  }
 
1527
#ifdef __GLIBC__
 
1528
#if __GLIBC_PREREQ(2, 15)
 
1529
  int numhooks = scandirat(hookdir_fd, ".", &direntries,
 
1530
                           runnable_hook, alphasort);
 
1531
#else  /* not __GLIBC_PREREQ(2, 15) */
 
1532
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
 
1533
                         alphasort);
 
1534
#endif  /* not __GLIBC_PREREQ(2, 15) */
 
1535
#else   /* not __GLIBC__ */
 
1536
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
 
1537
                         alphasort);
 
1538
#endif  /* not __GLIBC__ */
 
1539
  if(numhooks == -1){
 
1540
    perror_plus("scandir");
 
1541
    return;
 
1542
  }
 
1543
  struct dirent *direntry;
 
1544
  int ret;
 
1545
  int devnull = open("/dev/null", O_RDONLY);
 
1546
  for(int i = 0; i < numhooks; i++){
 
1547
    direntry = direntries[i];
 
1548
    if(debug){
 
1549
      fprintf_plus(stderr, "Running network hook \"%s\"\n",
 
1550
                   direntry->d_name);
 
1551
    }
 
1552
    pid_t hook_pid = fork();
 
1553
    if(hook_pid == 0){
 
1554
      /* Child */
 
1555
      /* Raise privileges */
 
1556
      errno = raise_privileges_permanently();
 
1557
      if(errno != 0){
 
1558
        perror_plus("Failed to raise privileges");
 
1559
        _exit(EX_NOPERM);
 
1560
      }
 
1561
      /* Set group */
 
1562
      errno = 0;
 
1563
      ret = setgid(0);
 
1564
      if(ret == -1){
 
1565
        perror_plus("setgid");
 
1566
        _exit(EX_NOPERM);
 
1567
      }
 
1568
      /* Reset supplementary groups */
 
1569
      errno = 0;
 
1570
      ret = setgroups(0, NULL);
 
1571
      if(ret == -1){
 
1572
        perror_plus("setgroups");
 
1573
        _exit(EX_NOPERM);
 
1574
      }
 
1575
      ret = dup2(devnull, STDIN_FILENO);
 
1576
      if(ret == -1){
 
1577
        perror_plus("dup2(devnull, STDIN_FILENO)");
 
1578
        _exit(EX_OSERR);
 
1579
      }
 
1580
      ret = close(devnull);
 
1581
      if(ret == -1){
 
1582
        perror_plus("close");
 
1583
        _exit(EX_OSERR);
 
1584
      }
 
1585
      ret = dup2(STDERR_FILENO, STDOUT_FILENO);
 
1586
      if(ret == -1){
 
1587
        perror_plus("dup2(STDERR_FILENO, STDOUT_FILENO)");
 
1588
        _exit(EX_OSERR);
 
1589
      }
 
1590
      ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
 
1591
      if(ret == -1){
 
1592
        perror_plus("setenv");
 
1593
        _exit(EX_OSERR);
 
1594
      }
 
1595
      ret = setenv("DEVICE", interface, 1);
 
1596
      if(ret == -1){
 
1597
        perror_plus("setenv");
 
1598
        _exit(EX_OSERR);
 
1599
      }
 
1600
      ret = setenv("VERBOSITY", debug ? "1" : "0", 1);
 
1601
      if(ret == -1){
 
1602
        perror_plus("setenv");
 
1603
        _exit(EX_OSERR);
 
1604
      }
 
1605
      ret = setenv("MODE", mode, 1);
 
1606
      if(ret == -1){
 
1607
        perror_plus("setenv");
 
1608
        _exit(EX_OSERR);
 
1609
      }
 
1610
      char *delaystring;
 
1611
      ret = asprintf(&delaystring, "%f", (double)delay);
 
1612
      if(ret == -1){
 
1613
        perror_plus("asprintf");
 
1614
        _exit(EX_OSERR);
 
1615
      }
 
1616
      ret = setenv("DELAY", delaystring, 1);
 
1617
      if(ret == -1){
 
1618
        free(delaystring);
 
1619
        perror_plus("setenv");
 
1620
        _exit(EX_OSERR);
 
1621
      }
 
1622
      free(delaystring);
 
1623
      if(connect_to != NULL){
 
1624
        ret = setenv("CONNECT", connect_to, 1);
 
1625
        if(ret == -1){
 
1626
          perror_plus("setenv");
 
1627
          _exit(EX_OSERR);
 
1628
        }
 
1629
      }
 
1630
      int hook_fd = openat(hookdir_fd, direntry->d_name, O_RDONLY);
 
1631
      if(hook_fd == -1){
 
1632
        perror_plus("openat");
 
1633
        _exit(EXIT_FAILURE);
 
1634
      }
 
1635
      if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
 
1636
        perror_plus("close");
 
1637
        _exit(EXIT_FAILURE);
 
1638
      }
 
1639
      if(fexecve(hook_fd, (char *const []){ direntry->d_name, NULL },
 
1640
                 environ) == -1){
 
1641
        perror_plus("fexecve");
 
1642
        _exit(EXIT_FAILURE);
 
1643
      }
 
1644
    } else {
 
1645
      int status;
 
1646
      if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
 
1647
        perror_plus("waitpid");
 
1648
        continue;
 
1649
      }
 
1650
      if(WIFEXITED(status)){
 
1651
        if(WEXITSTATUS(status) != 0){
 
1652
          fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
 
1653
                       " with status %d\n", direntry->d_name,
 
1654
                       WEXITSTATUS(status));
 
1655
          continue;
 
1656
        }
 
1657
      } else if(WIFSIGNALED(status)){
 
1658
        fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
 
1659
                     " signal %d\n", direntry->d_name,
 
1660
                     WTERMSIG(status));
 
1661
        continue;
 
1662
      } else {
 
1663
        fprintf_plus(stderr, "Warning: network hook \"%s\""
 
1664
                     " crashed\n", direntry->d_name);
 
1665
        continue;
 
1666
      }
 
1667
    }
 
1668
    if(debug){
 
1669
      fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
 
1670
                   direntry->d_name);
 
1671
    }
 
1672
  }
 
1673
  free(direntries);
 
1674
  if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
 
1675
    perror_plus("close");
 
1676
  } else {
 
1677
    hookdir_fd = -1;
 
1678
  }
 
1679
  close(devnull);
 
1680
}
 
1681
 
 
1682
__attribute__((nonnull, warn_unused_result))
 
1683
error_t bring_up_interface(const char *const interface,
 
1684
                           const float delay){
 
1685
  error_t old_errno = errno;
 
1686
  int ret;
 
1687
  struct ifreq network;
 
1688
  unsigned int if_index = if_nametoindex(interface);
 
1689
  if(if_index == 0){
 
1690
    fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
 
1691
    errno = old_errno;
 
1692
    return ENXIO;
 
1693
  }
 
1694
  
 
1695
  if(quit_now){
 
1696
    errno = old_errno;
 
1697
    return EINTR;
 
1698
  }
 
1699
  
 
1700
  if(not interface_is_up(interface)){
 
1701
    error_t ret_errno = 0, ioctl_errno = 0;
 
1702
    if(not get_flags(interface, &network)){
 
1703
      ret_errno = errno;
 
1704
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1705
                   "\"%s\"\n", interface);
 
1706
      errno = old_errno;
 
1707
      return ret_errno;
 
1708
    }
 
1709
    network.ifr_flags |= IFF_UP; /* set flag */
 
1710
    
 
1711
    int sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1712
    if(sd == -1){
 
1713
      ret_errno = errno;
 
1714
      perror_plus("socket");
 
1715
      errno = old_errno;
 
1716
      return ret_errno;
 
1717
    }
 
1718
    
 
1719
    if(quit_now){
 
1720
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1721
      if(ret == -1){
 
1722
        perror_plus("close");
 
1723
      }
 
1724
      errno = old_errno;
 
1725
      return EINTR;
 
1726
    }
 
1727
    
 
1728
    if(debug){
 
1729
      fprintf_plus(stderr, "Bringing up interface \"%s\"\n",
 
1730
                   interface);
 
1731
    }
 
1732
    
 
1733
    /* Raise privileges */
 
1734
    ret_errno = raise_privileges();
 
1735
    if(ret_errno != 0){
 
1736
      errno = ret_errno;
 
1737
      perror_plus("Failed to raise privileges");
 
1738
    }
 
1739
    
 
1740
#ifdef __linux__
 
1741
    int ret_linux;
 
1742
    bool restore_loglevel = false;
 
1743
    if(ret_errno == 0){
 
1744
      /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
 
1745
         messages about the network interface to mess up the prompt */
 
1746
      ret_linux = klogctl(8, NULL, 5);
 
1747
      if(ret_linux == -1){
 
1748
        perror_plus("klogctl");
 
1749
      } else {
 
1750
        restore_loglevel = true;
 
1751
      }
 
1752
    }
 
1753
#endif  /* __linux__ */
 
1754
    int ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
 
1755
    ioctl_errno = errno;
 
1756
#ifdef __linux__
 
1757
    if(restore_loglevel){
 
1758
      ret_linux = klogctl(7, NULL, 0);
 
1759
      if(ret_linux == -1){
 
1760
        perror_plus("klogctl");
 
1761
      }
 
1762
    }
 
1763
#endif  /* __linux__ */
 
1764
    
 
1765
    /* If raise_privileges() succeeded above */
 
1766
    if(ret_errno == 0){
 
1767
      /* Lower privileges */
 
1768
      ret_errno = lower_privileges();
 
1769
      if(ret_errno != 0){
 
1770
        errno = ret_errno;
 
1771
        perror_plus("Failed to lower privileges");
 
1772
      }
 
1773
    }
 
1774
    
 
1775
    /* Close the socket */
 
1776
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1777
    if(ret == -1){
 
1778
      perror_plus("close");
 
1779
    }
 
1780
    
 
1781
    if(ret_setflags == -1){
 
1782
      errno = ioctl_errno;
 
1783
      perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
 
1784
      errno = old_errno;
 
1785
      return ioctl_errno;
 
1786
    }
 
1787
  } else if(debug){
 
1788
    fprintf_plus(stderr, "Interface \"%s\" is already up; good\n",
 
1789
                 interface);
 
1790
  }
 
1791
  
 
1792
  /* Sleep checking until interface is running.
 
1793
     Check every 0.25s, up to total time of delay */
 
1794
  for(int i=0; i < delay * 4; i++){
 
1795
    if(interface_is_running(interface)){
 
1796
      break;
 
1797
    }
 
1798
    struct timespec sleeptime = { .tv_nsec = 250000000 };
 
1799
    ret = nanosleep(&sleeptime, NULL);
 
1800
    if(ret == -1 and errno != EINTR){
 
1801
      perror_plus("nanosleep");
 
1802
    }
 
1803
  }
 
1804
  
 
1805
  errno = old_errno;
 
1806
  return 0;
 
1807
}
 
1808
 
 
1809
__attribute__((nonnull, warn_unused_result))
 
1810
error_t take_down_interface(const char *const interface){
 
1811
  error_t old_errno = errno;
 
1812
  struct ifreq network;
 
1813
  unsigned int if_index = if_nametoindex(interface);
 
1814
  if(if_index == 0){
 
1815
    fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
 
1816
    errno = old_errno;
 
1817
    return ENXIO;
 
1818
  }
 
1819
  if(interface_is_up(interface)){
 
1820
    error_t ret_errno = 0, ioctl_errno = 0;
 
1821
    if(not get_flags(interface, &network) and debug){
 
1822
      ret_errno = errno;
 
1823
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1824
                   "\"%s\"\n", interface);
 
1825
      errno = old_errno;
 
1826
      return ret_errno;
 
1827
    }
 
1828
    network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
 
1829
    
 
1830
    int sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1831
    if(sd == -1){
 
1832
      ret_errno = errno;
 
1833
      perror_plus("socket");
 
1834
      errno = old_errno;
 
1835
      return ret_errno;
 
1836
    }
 
1837
    
 
1838
    if(debug){
 
1839
      fprintf_plus(stderr, "Taking down interface \"%s\"\n",
 
1840
                   interface);
 
1841
    }
 
1842
    
 
1843
    /* Raise privileges */
 
1844
    ret_errno = raise_privileges();
 
1845
    if(ret_errno != 0){
 
1846
      errno = ret_errno;
 
1847
      perror_plus("Failed to raise privileges");
 
1848
    }
 
1849
    
 
1850
    int ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
 
1851
    ioctl_errno = errno;
 
1852
    
 
1853
    /* If raise_privileges() succeeded above */
 
1854
    if(ret_errno == 0){
 
1855
      /* Lower privileges */
 
1856
      ret_errno = lower_privileges();
 
1857
      if(ret_errno != 0){
 
1858
        errno = ret_errno;
 
1859
        perror_plus("Failed to lower privileges");
 
1860
      }
 
1861
    }
 
1862
    
 
1863
    /* Close the socket */
 
1864
    int ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1865
    if(ret == -1){
 
1866
      perror_plus("close");
 
1867
    }
 
1868
    
 
1869
    if(ret_setflags == -1){
 
1870
      errno = ioctl_errno;
 
1871
      perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
 
1872
      errno = old_errno;
 
1873
      return ioctl_errno;
 
1874
    }
 
1875
  } else if(debug){
 
1876
    fprintf_plus(stderr, "Interface \"%s\" is already down; odd\n",
 
1877
                 interface);
 
1878
  }
 
1879
  
 
1880
  errno = old_errno;
 
1881
  return 0;
 
1882
}
 
1883
 
1413
1884
int main(int argc, char *argv[]){
 
1885
  mandos_context mc = { .server = NULL, .dh_bits = 1024,
 
1886
                        .priority = "SECURE256:!CTYPE-X.509:"
 
1887
                        "+CTYPE-OPENPGP", .current_server = NULL,
 
1888
                        .interfaces = NULL, .interfaces_size = 0 };
1414
1889
  AvahiSServiceBrowser *sb = NULL;
1415
 
  int error;
 
1890
  error_t ret_errno;
1416
1891
  int ret;
1417
1892
  intmax_t tmpmax;
1418
1893
  char *tmp;
1419
1894
  int exitcode = EXIT_SUCCESS;
1420
 
  const char *interface = "";
1421
 
  struct ifreq network;
1422
 
  int sd = -1;
1423
 
  bool take_down_interface = false;
1424
 
  uid_t uid;
1425
 
  gid_t gid;
1426
 
  char tempdir[] = "/tmp/mandosXXXXXX";
1427
 
  bool tempdir_created = false;
 
1895
  char *interfaces_to_take_down = NULL;
 
1896
  size_t interfaces_to_take_down_size = 0;
 
1897
  char run_tempdir[] = "/run/tmp/mandosXXXXXX";
 
1898
  char old_tempdir[] = "/tmp/mandosXXXXXX";
 
1899
  char *tempdir = NULL;
1428
1900
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1429
1901
  const char *seckey = PATHDIR "/" SECKEY;
1430
1902
  const char *pubkey = PATHDIR "/" PUBKEY;
 
1903
  char *interfaces_hooks = NULL;
1431
1904
  
1432
1905
  bool gnutls_initialized = false;
1433
1906
  bool gpgme_initialized = false;
1495
1968
        .group = 2 },
1496
1969
      { .name = "retry", .key = 132,
1497
1970
        .arg = "SECONDS",
1498
 
        .doc = "Retry interval used when denied by the mandos server",
 
1971
        .doc = "Retry interval used when denied by the Mandos server",
1499
1972
        .group = 2 },
1500
1973
      { .name = "network-hook-dir", .key = 133,
1501
1974
        .arg = "DIR",
1524
1997
        connect_to = arg;
1525
1998
        break;
1526
1999
      case 'i':                 /* --interface */
1527
 
        interface = arg;
 
2000
        ret_errno = argz_add_sep(&mc.interfaces, &mc.interfaces_size,
 
2001
                                 arg, (int)',');
 
2002
        if(ret_errno != 0){
 
2003
          argp_error(state, "%s", strerror(ret_errno));
 
2004
        }
1528
2005
        break;
1529
2006
      case 's':                 /* --seckey */
1530
2007
        seckey = arg;
1573
2050
        argp_state_help(state, state->out_stream,
1574
2051
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1575
2052
      case 'V':                 /* --version */
1576
 
        fprintf(state->out_stream, "Mandos plugin mandos-client: ");
1577
 
        fprintf(state->out_stream, "%s\n", argp_program_version);
 
2053
        fprintf_plus(state->out_stream, "%s\n", argp_program_version);
1578
2054
        exit(argp_err_exit_status);
1579
2055
        break;
1580
2056
      default:
1607
2083
  {
1608
2084
    /* Work around Debian bug #633582:
1609
2085
       <http://bugs.debian.org/633582> */
1610
 
    struct stat st;
1611
 
    
1612
 
    /* Re-raise priviliges */
1613
 
    errno = 0;
1614
 
    ret = seteuid(0);
1615
 
    if(ret == -1){
1616
 
      perror_plus("seteuid");
1617
 
    }
1618
 
    
1619
 
    if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
1620
 
      int seckey_fd = open(seckey, O_RDONLY);
1621
 
      if(seckey_fd == -1){
1622
 
        perror_plus("open");
1623
 
      } else {
1624
 
        ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
1625
 
        if(ret == -1){
1626
 
          perror_plus("fstat");
1627
 
        } else {
1628
 
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1629
 
            ret = fchown(seckey_fd, uid, gid);
1630
 
            if(ret == -1){
1631
 
              perror_plus("fchown");
1632
 
            }
1633
 
          }
1634
 
        }
1635
 
        TEMP_FAILURE_RETRY(close(seckey_fd));
1636
 
      }
1637
 
    }
1638
 
    
1639
 
    if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
1640
 
      int pubkey_fd = open(pubkey, O_RDONLY);
1641
 
      if(pubkey_fd == -1){
1642
 
        perror_plus("open");
1643
 
      } else {
1644
 
        ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
1645
 
        if(ret == -1){
1646
 
          perror_plus("fstat");
1647
 
        } else {
1648
 
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1649
 
            ret = fchown(pubkey_fd, uid, gid);
1650
 
            if(ret == -1){
1651
 
              perror_plus("fchown");
1652
 
            }
1653
 
          }
1654
 
        }
1655
 
        TEMP_FAILURE_RETRY(close(pubkey_fd));
1656
 
      }
1657
 
    }
1658
 
    
1659
 
    /* Lower privileges */
1660
 
    errno = 0;
1661
 
    ret = seteuid(uid);
1662
 
    if(ret == -1){
1663
 
      perror_plus("seteuid");
1664
 
    }
1665
 
  }
1666
 
  
1667
 
  /* Find network hooks and run them */
1668
 
  {
1669
 
    struct dirent **direntries;
1670
 
    struct dirent *direntry;
1671
 
    int numhooks = scandir(hookdir, &direntries, runnable_hook,
1672
 
                           alphasort);
1673
 
    if(numhooks == -1){
1674
 
      perror_plus("scandir");
 
2086
    
 
2087
    /* Re-raise privileges */
 
2088
    ret_errno = raise_privileges();
 
2089
    if(ret_errno != 0){
 
2090
      errno = ret_errno;
 
2091
      perror_plus("Failed to raise privileges");
1675
2092
    } else {
1676
 
      int devnull = open("/dev/null", O_RDONLY);
1677
 
      for(int i = 0; i < numhooks; i++){
1678
 
        direntry = direntries[0];
1679
 
        char *fullname = NULL;
1680
 
        ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
1681
 
        if(ret < 0){
1682
 
          perror_plus("asprintf");
1683
 
          continue;
1684
 
        }
1685
 
        pid_t hook_pid = fork();
1686
 
        if(hook_pid == 0){
1687
 
          /* Child */
1688
 
          dup2(devnull, STDIN_FILENO);
1689
 
          close(devnull);
1690
 
          dup2(STDERR_FILENO, STDOUT_FILENO);
1691
 
          ret = setenv("DEVICE", interface, 1);
1692
 
          if(ret == -1){
1693
 
            perror_plus("setenv");
1694
 
            exit(1);
1695
 
          }
1696
 
          ret = setenv("VERBOSE", debug ? "1" : "0", 1);
1697
 
          if(ret == -1){
1698
 
            perror_plus("setenv");
1699
 
            exit(1);
1700
 
          }
1701
 
          ret = setenv("MODE", "start", 1);
1702
 
          if(ret == -1){
1703
 
            perror_plus("setenv");
1704
 
            exit(1);
1705
 
          }
1706
 
          char *delaystring;
1707
 
          ret = asprintf(&delaystring, "%f", delay);
1708
 
          if(ret == -1){
1709
 
            perror_plus("asprintf");
1710
 
            exit(1);
1711
 
          }
1712
 
          ret = setenv("DELAY", delaystring, 1);
1713
 
          if(ret == -1){
1714
 
            free(delaystring);
1715
 
            perror_plus("setenv");
1716
 
            exit(1);
1717
 
          }
1718
 
          free(delaystring);
1719
 
          ret = execl(fullname, direntry->d_name, "start", NULL);
1720
 
          perror_plus("execl");
1721
 
        } else {
1722
 
          int status;
1723
 
          if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
1724
 
            perror_plus("waitpid");
1725
 
            free(fullname);
1726
 
            continue;
1727
 
          }
1728
 
          if(WIFEXITED(status)){
1729
 
            if(WEXITSTATUS(status) != 0){
1730
 
              fprintf(stderr, "Mandos plugin mandos-client: "
1731
 
                      "Warning: network hook \"%s\" exited"
1732
 
                      " with status %d\n", direntry->d_name,
1733
 
                      WEXITSTATUS(status));
1734
 
              free(fullname);
1735
 
              continue;
1736
 
            }
1737
 
          } else if(WIFSIGNALED(status)){
1738
 
            fprintf(stderr, "Mandos plugin mandos-client: "
1739
 
                    "Warning: network hook \"%s\" died by"
1740
 
                    " signal %d\n", direntry->d_name,
1741
 
                    WTERMSIG(status));
1742
 
            free(fullname);
1743
 
            continue;
1744
 
          } else {
1745
 
            fprintf(stderr, "Mandos plugin mandos-client: "
1746
 
                    "Warning: network hook \"%s\" crashed\n",
1747
 
                    direntry->d_name);
1748
 
            free(fullname);
1749
 
            continue;
1750
 
          }
1751
 
        }
1752
 
        free(fullname);
1753
 
        if(quit_now){
1754
 
          goto end;
1755
 
        }
1756
 
      }
1757
 
      close(devnull);
1758
 
    }
 
2093
      struct stat st;
 
2094
      
 
2095
      if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
 
2096
        int seckey_fd = open(seckey, O_RDONLY);
 
2097
        if(seckey_fd == -1){
 
2098
          perror_plus("open");
 
2099
        } else {
 
2100
          ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
 
2101
          if(ret == -1){
 
2102
            perror_plus("fstat");
 
2103
          } else {
 
2104
            if(S_ISREG(st.st_mode)
 
2105
               and st.st_uid == 0 and st.st_gid == 0){
 
2106
              ret = fchown(seckey_fd, uid, gid);
 
2107
              if(ret == -1){
 
2108
                perror_plus("fchown");
 
2109
              }
 
2110
            }
 
2111
          }
 
2112
          TEMP_FAILURE_RETRY(close(seckey_fd));
 
2113
        }
 
2114
      }
 
2115
    
 
2116
      if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
 
2117
        int pubkey_fd = open(pubkey, O_RDONLY);
 
2118
        if(pubkey_fd == -1){
 
2119
          perror_plus("open");
 
2120
        } else {
 
2121
          ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
 
2122
          if(ret == -1){
 
2123
            perror_plus("fstat");
 
2124
          } else {
 
2125
            if(S_ISREG(st.st_mode)
 
2126
               and st.st_uid == 0 and st.st_gid == 0){
 
2127
              ret = fchown(pubkey_fd, uid, gid);
 
2128
              if(ret == -1){
 
2129
                perror_plus("fchown");
 
2130
              }
 
2131
            }
 
2132
          }
 
2133
          TEMP_FAILURE_RETRY(close(pubkey_fd));
 
2134
        }
 
2135
      }
 
2136
    
 
2137
      /* Lower privileges */
 
2138
      ret_errno = lower_privileges();
 
2139
      if(ret_errno != 0){
 
2140
        errno = ret_errno;
 
2141
        perror_plus("Failed to lower privileges");
 
2142
      }
 
2143
    }
 
2144
  }
 
2145
  
 
2146
  /* Remove invalid interface names (except "none") */
 
2147
  {
 
2148
    char *interface = NULL;
 
2149
    while((interface = argz_next(mc.interfaces, mc.interfaces_size,
 
2150
                                 interface))){
 
2151
      if(strcmp(interface, "none") != 0
 
2152
         and if_nametoindex(interface) == 0){
 
2153
        if(interface[0] != '\0'){
 
2154
          fprintf_plus(stderr, "Not using nonexisting interface"
 
2155
                       " \"%s\"\n", interface);
 
2156
        }
 
2157
        argz_delete(&mc.interfaces, &mc.interfaces_size, interface);
 
2158
        interface = NULL;
 
2159
      }
 
2160
    }
 
2161
  }
 
2162
  
 
2163
  /* Run network hooks */
 
2164
  {
 
2165
    if(mc.interfaces != NULL){
 
2166
      interfaces_hooks = malloc(mc.interfaces_size);
 
2167
      if(interfaces_hooks == NULL){
 
2168
        perror_plus("malloc");
 
2169
        goto end;
 
2170
      }
 
2171
      memcpy(interfaces_hooks, mc.interfaces, mc.interfaces_size);
 
2172
      argz_stringify(interfaces_hooks, mc.interfaces_size, (int)',');
 
2173
    }
 
2174
    run_network_hooks("start", interfaces_hooks != NULL ?
 
2175
                      interfaces_hooks : "", delay);
1759
2176
  }
1760
2177
  
1761
2178
  if(not debug){
1762
2179
    avahi_set_log_function(empty_log);
1763
2180
  }
1764
2181
  
1765
 
  if(interface[0] == '\0'){
1766
 
    struct dirent **direntries;
1767
 
    /* First look for interfaces that are up */
1768
 
    ret = scandir(sys_class_net, &direntries, up_interface,
1769
 
                  alphasort);
1770
 
    if(ret == 0){
1771
 
      /* No up interfaces, look for any good interfaces */
1772
 
      free(direntries);
1773
 
      ret = scandir(sys_class_net, &direntries, good_interface,
1774
 
                    alphasort);
1775
 
    }
1776
 
    if(ret >= 1){
1777
 
      /* Pick the first interface returned */
1778
 
      interface = strdup(direntries[0]->d_name);
1779
 
      if(debug){
1780
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1781
 
                "Using interface \"%s\"\n", interface);
1782
 
      }
1783
 
      if(interface == NULL){
1784
 
        perror_plus("malloc");
1785
 
        free(direntries);
1786
 
        exitcode = EXIT_FAILURE;
1787
 
        goto end;
1788
 
      }
1789
 
      free(direntries);
1790
 
    } else {
1791
 
      free(direntries);
1792
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1793
 
              "Could not find a network interface\n");
1794
 
      exitcode = EXIT_FAILURE;
1795
 
      goto end;
1796
 
    }
1797
 
  }
1798
 
  
1799
2182
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
1800
2183
     from the signal handler */
1801
2184
  /* Initialize the pseudo-RNG for Avahi */
1802
2185
  srand((unsigned int) time(NULL));
1803
 
  mc.simple_poll = avahi_simple_poll_new();
1804
 
  if(mc.simple_poll == NULL){
1805
 
    fprintf(stderr, "Mandos plugin mandos-client: "
1806
 
            "Avahi: Failed to create simple poll object.\n");
 
2186
  simple_poll = avahi_simple_poll_new();
 
2187
  if(simple_poll == NULL){
 
2188
    fprintf_plus(stderr,
 
2189
                 "Avahi: Failed to create simple poll object.\n");
1807
2190
    exitcode = EX_UNAVAILABLE;
1808
2191
    goto end;
1809
2192
  }
1871
2254
    }
1872
2255
  }
1873
2256
  
1874
 
  /* If the interface is down, bring it up */
1875
 
  if(strcmp(interface, "none") != 0){
1876
 
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1877
 
    if(if_index == 0){
1878
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1879
 
              "No such interface: \"%s\"\n", interface);
1880
 
      exitcode = EX_UNAVAILABLE;
1881
 
      goto end;
1882
 
    }
1883
 
    
1884
 
    if(quit_now){
1885
 
      goto end;
1886
 
    }
1887
 
    
1888
 
    /* Re-raise priviliges */
1889
 
    errno = 0;
1890
 
    ret = seteuid(0);
1891
 
    if(ret == -1){
1892
 
      perror_plus("seteuid");
1893
 
    }
1894
 
    
1895
 
#ifdef __linux__
1896
 
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1897
 
       messages about the network interface to mess up the prompt */
1898
 
    ret = klogctl(8, NULL, 5);
1899
 
    bool restore_loglevel = true;
1900
 
    if(ret == -1){
1901
 
      restore_loglevel = false;
1902
 
      perror_plus("klogctl");
1903
 
    }
1904
 
#endif  /* __linux__ */
1905
 
    
1906
 
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1907
 
    if(sd < 0){
1908
 
      perror_plus("socket");
1909
 
      exitcode = EX_OSERR;
1910
 
#ifdef __linux__
1911
 
      if(restore_loglevel){
1912
 
        ret = klogctl(7, NULL, 0);
1913
 
        if(ret == -1){
1914
 
          perror_plus("klogctl");
1915
 
        }
1916
 
      }
1917
 
#endif  /* __linux__ */
1918
 
      /* Lower privileges */
1919
 
      errno = 0;
1920
 
      ret = seteuid(uid);
1921
 
      if(ret == -1){
1922
 
        perror_plus("seteuid");
1923
 
      }
1924
 
      goto end;
1925
 
    }
1926
 
    strcpy(network.ifr_name, interface);
1927
 
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
1928
 
    if(ret == -1){
1929
 
      perror_plus("ioctl SIOCGIFFLAGS");
1930
 
#ifdef __linux__
1931
 
      if(restore_loglevel){
1932
 
        ret = klogctl(7, NULL, 0);
1933
 
        if(ret == -1){
1934
 
          perror_plus("klogctl");
1935
 
        }
1936
 
      }
1937
 
#endif  /* __linux__ */
1938
 
      exitcode = EX_OSERR;
1939
 
      /* Lower privileges */
1940
 
      errno = 0;
1941
 
      ret = seteuid(uid);
1942
 
      if(ret == -1){
1943
 
        perror_plus("seteuid");
1944
 
      }
1945
 
      goto end;
1946
 
    }
1947
 
    if((network.ifr_flags & IFF_UP) == 0){
1948
 
      network.ifr_flags |= IFF_UP;
1949
 
      take_down_interface = true;
1950
 
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1951
 
      if(ret == -1){
1952
 
        take_down_interface = false;
1953
 
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1954
 
        exitcode = EX_OSERR;
1955
 
#ifdef __linux__
1956
 
        if(restore_loglevel){
1957
 
          ret = klogctl(7, NULL, 0);
1958
 
          if(ret == -1){
1959
 
            perror_plus("klogctl");
 
2257
  /* If no interfaces were specified, make a list */
 
2258
  if(mc.interfaces == NULL){
 
2259
    struct dirent **direntries = NULL;
 
2260
    /* Look for any good interfaces */
 
2261
    ret = scandir(sys_class_net, &direntries, good_interface,
 
2262
                  alphasort);
 
2263
    if(ret >= 1){
 
2264
      /* Add all found interfaces to interfaces list */
 
2265
      for(int i = 0; i < ret; ++i){
 
2266
        ret_errno = argz_add(&mc.interfaces, &mc.interfaces_size,
 
2267
                             direntries[i]->d_name);
 
2268
        if(ret_errno != 0){
 
2269
          errno = ret_errno;
 
2270
          perror_plus("argz_add");
 
2271
          continue;
 
2272
        }
 
2273
        if(debug){
 
2274
          fprintf_plus(stderr, "Will use interface \"%s\"\n",
 
2275
                       direntries[i]->d_name);
 
2276
        }
 
2277
      }
 
2278
      free(direntries);
 
2279
    } else {
 
2280
      if(ret == 0){
 
2281
        free(direntries);
 
2282
      }
 
2283
      fprintf_plus(stderr, "Could not find a network interface\n");
 
2284
      exitcode = EXIT_FAILURE;
 
2285
      goto end;
 
2286
    }
 
2287
  }
 
2288
  
 
2289
  /* Bring up interfaces which are down, and remove any "none"s */
 
2290
  {
 
2291
    char *interface = NULL;
 
2292
    while((interface = argz_next(mc.interfaces, mc.interfaces_size,
 
2293
                                 interface))){
 
2294
      /* If interface name is "none", stop bringing up interfaces.
 
2295
         Also remove all instances of "none" from the list */
 
2296
      if(strcmp(interface, "none") == 0){
 
2297
        argz_delete(&mc.interfaces, &mc.interfaces_size,
 
2298
                    interface);
 
2299
        interface = NULL;
 
2300
        while((interface = argz_next(mc.interfaces,
 
2301
                                     mc.interfaces_size, interface))){
 
2302
          if(strcmp(interface, "none") == 0){
 
2303
            argz_delete(&mc.interfaces, &mc.interfaces_size,
 
2304
                        interface);
 
2305
            interface = NULL;
1960
2306
          }
1961
2307
        }
1962
 
#endif  /* __linux__ */
1963
 
        /* Lower privileges */
1964
 
        errno = 0;
1965
 
        ret = seteuid(uid);
1966
 
        if(ret == -1){
1967
 
          perror_plus("seteuid");
1968
 
        }
1969
 
        goto end;
1970
 
      }
1971
 
    }
1972
 
    /* Sleep checking until interface is running.
1973
 
       Check every 0.25s, up to total time of delay */
1974
 
    for(int i=0; i < delay * 4; i++){
1975
 
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1976
 
      if(ret == -1){
1977
 
        perror_plus("ioctl SIOCGIFFLAGS");
1978
 
      } else if(network.ifr_flags & IFF_RUNNING){
1979
2308
        break;
1980
2309
      }
1981
 
      struct timespec sleeptime = { .tv_nsec = 250000000 };
1982
 
      ret = nanosleep(&sleeptime, NULL);
1983
 
      if(ret == -1 and errno != EINTR){
1984
 
        perror_plus("nanosleep");
1985
 
      }
1986
 
    }
1987
 
    if(not take_down_interface){
1988
 
      /* We won't need the socket anymore */
1989
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1990
 
      if(ret == -1){
1991
 
        perror_plus("close");
1992
 
      }
1993
 
    }
1994
 
#ifdef __linux__
1995
 
    if(restore_loglevel){
1996
 
      /* Restores kernel loglevel to default */
1997
 
      ret = klogctl(7, NULL, 0);
1998
 
      if(ret == -1){
1999
 
        perror_plus("klogctl");
2000
 
      }
2001
 
    }
2002
 
#endif  /* __linux__ */
2003
 
    /* Lower privileges */
2004
 
    errno = 0;
2005
 
    if(take_down_interface){
2006
 
      /* Lower privileges */
2007
 
      ret = seteuid(uid);
2008
 
      if(ret == -1){
2009
 
        perror_plus("seteuid");
2010
 
      }
2011
 
    } else {
2012
 
      /* Lower privileges permanently */
2013
 
      ret = setuid(uid);
2014
 
      if(ret == -1){
2015
 
        perror_plus("setuid");
2016
 
      }
2017
 
    }
 
2310
      bool interface_was_up = interface_is_up(interface);
 
2311
      errno = bring_up_interface(interface, delay);
 
2312
      if(not interface_was_up){
 
2313
        if(errno != 0){
 
2314
          perror_plus("Failed to bring up interface");
 
2315
        } else {
 
2316
          errno = argz_add(&interfaces_to_take_down,
 
2317
                           &interfaces_to_take_down_size,
 
2318
                           interface);
 
2319
          if(errno != 0){
 
2320
            perror_plus("argz_add");
 
2321
          }
 
2322
        }
 
2323
      }
 
2324
    }
 
2325
    if(debug and (interfaces_to_take_down == NULL)){
 
2326
      fprintf_plus(stderr, "No interfaces were brought up\n");
 
2327
    }
 
2328
  }
 
2329
  
 
2330
  /* If we only got one interface, explicitly use only that one */
 
2331
  if(argz_count(mc.interfaces, mc.interfaces_size) == 1){
 
2332
    if(debug){
 
2333
      fprintf_plus(stderr, "Using only interface \"%s\"\n",
 
2334
                   mc.interfaces);
 
2335
    }
 
2336
    if_index = (AvahiIfIndex)if_nametoindex(mc.interfaces);
2018
2337
  }
2019
2338
  
2020
2339
  if(quit_now){
2021
2340
    goto end;
2022
2341
  }
2023
2342
  
2024
 
  ret = init_gnutls_global(pubkey, seckey);
 
2343
  ret = init_gnutls_global(pubkey, seckey, &mc);
2025
2344
  if(ret == -1){
2026
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2027
 
            "init_gnutls_global failed\n");
 
2345
    fprintf_plus(stderr, "init_gnutls_global failed\n");
2028
2346
    exitcode = EX_UNAVAILABLE;
2029
2347
    goto end;
2030
2348
  } else {
2035
2353
    goto end;
2036
2354
  }
2037
2355
  
2038
 
  if(mkdtemp(tempdir) == NULL){
 
2356
  /* Try /run/tmp before /tmp */
 
2357
  tempdir = mkdtemp(run_tempdir);
 
2358
  if(tempdir == NULL and errno == ENOENT){
 
2359
      if(debug){
 
2360
        fprintf_plus(stderr, "Tempdir %s did not work, trying %s\n",
 
2361
                     run_tempdir, old_tempdir);
 
2362
      }
 
2363
      tempdir = mkdtemp(old_tempdir);
 
2364
  }
 
2365
  if(tempdir == NULL){
2039
2366
    perror_plus("mkdtemp");
2040
2367
    goto end;
2041
2368
  }
2042
 
  tempdir_created = true;
2043
2369
  
2044
2370
  if(quit_now){
2045
2371
    goto end;
2046
2372
  }
2047
2373
  
2048
 
  if(not init_gpgme(pubkey, seckey, tempdir)){
2049
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2050
 
            "init_gpgme failed\n");
 
2374
  if(not init_gpgme(pubkey, seckey, tempdir, &mc)){
 
2375
    fprintf_plus(stderr, "init_gpgme failed\n");
2051
2376
    exitcode = EX_UNAVAILABLE;
2052
2377
    goto end;
2053
2378
  } else {
2062
2387
    /* Connect directly, do not use Zeroconf */
2063
2388
    /* (Mainly meant for debugging) */
2064
2389
    char *address = strrchr(connect_to, ':');
 
2390
    
2065
2391
    if(address == NULL){
2066
 
      fprintf(stderr, "Mandos plugin mandos-client: "
2067
 
              "No colon in address\n");
 
2392
      fprintf_plus(stderr, "No colon in address\n");
2068
2393
      exitcode = EX_USAGE;
2069
2394
      goto end;
2070
2395
    }
2073
2398
      goto end;
2074
2399
    }
2075
2400
    
2076
 
    uint16_t port;
 
2401
    in_port_t port;
2077
2402
    errno = 0;
2078
2403
    tmpmax = strtoimax(address+1, &tmp, 10);
2079
2404
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
2080
 
       or tmpmax != (uint16_t)tmpmax){
2081
 
      fprintf(stderr, "Mandos plugin mandos-client: "
2082
 
              "Bad port number\n");
 
2405
       or tmpmax != (in_port_t)tmpmax){
 
2406
      fprintf_plus(stderr, "Bad port number\n");
2083
2407
      exitcode = EX_USAGE;
2084
2408
      goto end;
2085
2409
    }
2086
 
  
 
2410
    
2087
2411
    if(quit_now){
2088
2412
      goto end;
2089
2413
    }
2090
2414
    
2091
 
    port = (uint16_t)tmpmax;
 
2415
    port = (in_port_t)tmpmax;
2092
2416
    *address = '\0';
2093
2417
    /* Colon in address indicates IPv6 */
2094
2418
    int af;
2110
2434
    }
2111
2435
    
2112
2436
    while(not quit_now){
2113
 
      ret = start_mandos_communication(address, port, if_index, af);
 
2437
      ret = start_mandos_communication(address, port, if_index, af,
 
2438
                                       &mc);
2114
2439
      if(quit_now or ret == 0){
2115
2440
        break;
2116
2441
      }
2117
2442
      if(debug){
2118
 
        fprintf(stderr, "Mandos plugin mandos-client: "
2119
 
                "Retrying in %d seconds\n", (int)retry_interval);
 
2443
        fprintf_plus(stderr, "Retrying in %d seconds\n",
 
2444
                     (int)retry_interval);
2120
2445
      }
2121
 
      sleep((int)retry_interval);
 
2446
      sleep((unsigned int)retry_interval);
2122
2447
    }
2123
2448
    
2124
 
    if (not quit_now){
 
2449
    if(not quit_now){
2125
2450
      exitcode = EXIT_SUCCESS;
2126
2451
    }
2127
2452
    
2142
2467
    config.publish_domain = 0;
2143
2468
    
2144
2469
    /* Allocate a new server */
2145
 
    mc.server = avahi_server_new(avahi_simple_poll_get
2146
 
                                 (mc.simple_poll), &config, NULL,
2147
 
                                 NULL, &error);
 
2470
    mc.server = avahi_server_new(avahi_simple_poll_get(simple_poll),
 
2471
                                 &config, NULL, NULL, &ret_errno);
2148
2472
    
2149
2473
    /* Free the Avahi configuration data */
2150
2474
    avahi_server_config_free(&config);
2152
2476
  
2153
2477
  /* Check if creating the Avahi server object succeeded */
2154
2478
  if(mc.server == NULL){
2155
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2156
 
            "Failed to create Avahi server: %s\n",
2157
 
            avahi_strerror(error));
 
2479
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
 
2480
                 avahi_strerror(ret_errno));
2158
2481
    exitcode = EX_UNAVAILABLE;
2159
2482
    goto end;
2160
2483
  }
2166
2489
  /* Create the Avahi service browser */
2167
2490
  sb = avahi_s_service_browser_new(mc.server, if_index,
2168
2491
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2169
 
                                   NULL, 0, browse_callback, NULL);
 
2492
                                   NULL, 0, browse_callback,
 
2493
                                   (void *)&mc);
2170
2494
  if(sb == NULL){
2171
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2172
 
            "Failed to create service browser: %s\n",
2173
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
2495
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
 
2496
                 avahi_strerror(avahi_server_errno(mc.server)));
2174
2497
    exitcode = EX_UNAVAILABLE;
2175
2498
    goto end;
2176
2499
  }
2182
2505
  /* Run the main loop */
2183
2506
  
2184
2507
  if(debug){
2185
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2186
 
            "Starting Avahi loop search\n");
 
2508
    fprintf_plus(stderr, "Starting Avahi loop search\n");
2187
2509
  }
2188
 
 
2189
 
  ret = avahi_loop_with_timeout(mc.simple_poll,
2190
 
                                (int)(retry_interval * 1000));
 
2510
  
 
2511
  ret = avahi_loop_with_timeout(simple_poll,
 
2512
                                (int)(retry_interval * 1000), &mc);
2191
2513
  if(debug){
2192
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2193
 
            "avahi_loop_with_timeout exited %s\n",
2194
 
            (ret == 0) ? "successfully" : "with error");
 
2514
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
 
2515
                 (ret == 0) ? "successfully" : "with error");
2195
2516
  }
2196
2517
  
2197
2518
 end:
2198
2519
  
2199
2520
  if(debug){
2200
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2201
 
            "%s exiting\n", argv[0]);
 
2521
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
2202
2522
  }
2203
2523
  
2204
2524
  /* Cleanup things */
 
2525
  free(mc.interfaces);
 
2526
  
2205
2527
  if(sb != NULL)
2206
2528
    avahi_s_service_browser_free(sb);
2207
2529
  
2208
2530
  if(mc.server != NULL)
2209
2531
    avahi_server_free(mc.server);
2210
2532
  
2211
 
  if(mc.simple_poll != NULL)
2212
 
    avahi_simple_poll_free(mc.simple_poll);
 
2533
  if(simple_poll != NULL)
 
2534
    avahi_simple_poll_free(simple_poll);
2213
2535
  
2214
2536
  if(gnutls_initialized){
2215
2537
    gnutls_certificate_free_credentials(mc.cred);
2220
2542
  if(gpgme_initialized){
2221
2543
    gpgme_release(mc.ctx);
2222
2544
  }
2223
 
 
 
2545
  
2224
2546
  /* Cleans up the circular linked list of Mandos servers the client
2225
2547
     has seen */
2226
2548
  if(mc.current_server != NULL){
2232
2554
    }
2233
2555
  }
2234
2556
  
2235
 
  /* XXX run network hooks "stop" here  */
2236
 
  
2237
 
  /* Take down the network interface */
2238
 
  if(take_down_interface){
2239
 
    /* Re-raise priviliges */
2240
 
    errno = 0;
2241
 
    ret = seteuid(0);
2242
 
    if(ret == -1){
2243
 
      perror_plus("seteuid");
 
2557
  /* Re-raise privileges */
 
2558
  {
 
2559
    ret_errno = raise_privileges();
 
2560
    if(ret_errno != 0){
 
2561
      errno = ret_errno;
 
2562
      perror_plus("Failed to raise privileges");
 
2563
    } else {
 
2564
      
 
2565
      /* Run network hooks */
 
2566
      run_network_hooks("stop", interfaces_hooks != NULL ?
 
2567
                        interfaces_hooks : "", delay);
 
2568
      
 
2569
      /* Take down the network interfaces which were brought up */
 
2570
      {
 
2571
        char *interface = NULL;
 
2572
        while((interface=argz_next(interfaces_to_take_down,
 
2573
                                   interfaces_to_take_down_size,
 
2574
                                   interface))){
 
2575
          ret_errno = take_down_interface(interface);
 
2576
          if(ret_errno != 0){
 
2577
            errno = ret_errno;
 
2578
            perror_plus("Failed to take down interface");
 
2579
          }
 
2580
        }
 
2581
        if(debug and (interfaces_to_take_down == NULL)){
 
2582
          fprintf_plus(stderr, "No interfaces needed to be taken"
 
2583
                       " down\n");
 
2584
        }
 
2585
      }
2244
2586
    }
2245
 
    if(geteuid() == 0){
2246
 
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
2247
 
      if(ret == -1){
2248
 
        perror_plus("ioctl SIOCGIFFLAGS");
2249
 
      } else if(network.ifr_flags & IFF_UP){
2250
 
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
2251
 
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
2252
 
        if(ret == -1){
2253
 
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
2254
 
        }
2255
 
      }
2256
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
2257
 
      if(ret == -1){
2258
 
        perror_plus("close");
2259
 
      }
2260
 
      /* Lower privileges permanently */
2261
 
      errno = 0;
2262
 
      ret = setuid(uid);
2263
 
      if(ret == -1){
2264
 
        perror_plus("setuid");
2265
 
      }
 
2587
    
 
2588
    ret_errno = lower_privileges_permanently();
 
2589
    if(ret_errno != 0){
 
2590
      errno = ret_errno;
 
2591
      perror_plus("Failed to lower privileges permanently");
2266
2592
    }
2267
2593
  }
2268
2594
  
 
2595
  free(interfaces_to_take_down);
 
2596
  free(interfaces_hooks);
 
2597
  
2269
2598
  /* Removes the GPGME temp directory and all files inside */
2270
 
  if(tempdir_created){
 
2599
  if(tempdir != NULL){
2271
2600
    struct dirent **direntries = NULL;
2272
 
    struct dirent *direntry = NULL;
2273
 
    int numentries = scandir(tempdir, &direntries, notdotentries,
2274
 
                             alphasort);
2275
 
    if (numentries > 0){
2276
 
      for(int i = 0; i < numentries; i++){
2277
 
        direntry = direntries[i];
2278
 
        char *fullname = NULL;
2279
 
        ret = asprintf(&fullname, "%s/%s", tempdir,
2280
 
                       direntry->d_name);
2281
 
        if(ret < 0){
2282
 
          perror_plus("asprintf");
2283
 
          continue;
2284
 
        }
2285
 
        ret = remove(fullname);
2286
 
        if(ret == -1){
2287
 
          fprintf(stderr, "Mandos plugin mandos-client: "
2288
 
                  "remove(\"%s\"): %s\n", fullname, strerror(errno));
2289
 
        }
2290
 
        free(fullname);
 
2601
    int tempdir_fd = (int)TEMP_FAILURE_RETRY(open(tempdir, O_RDONLY |
 
2602
                                                  O_NOFOLLOW));
 
2603
    if(tempdir_fd == -1){
 
2604
      perror_plus("open");
 
2605
    } else {
 
2606
#ifdef __GLIBC__
 
2607
#if __GLIBC_PREREQ(2, 15)
 
2608
      int numentries = scandirat(tempdir_fd, ".", &direntries,
 
2609
                                 notdotentries, alphasort);
 
2610
#else  /* not __GLIBC_PREREQ(2, 15) */
 
2611
      int numentries = scandir(tempdir, &direntries, notdotentries,
 
2612
                               alphasort);
 
2613
#endif  /* not __GLIBC_PREREQ(2, 15) */
 
2614
#else   /* not __GLIBC__ */
 
2615
      int numentries = scandir(tempdir, &direntries, notdotentries,
 
2616
                               alphasort);
 
2617
#endif  /* not __GLIBC__ */
 
2618
      if(numentries >= 0){
 
2619
        for(int i = 0; i < numentries; i++){
 
2620
          ret = unlinkat(tempdir_fd, direntries[i]->d_name, 0);
 
2621
          if(ret == -1){
 
2622
            fprintf_plus(stderr, "unlinkat(open(\"%s\", O_RDONLY),"
 
2623
                         " \"%s\", 0): %s\n", tempdir,
 
2624
                         direntries[i]->d_name, strerror(errno));
 
2625
          }
 
2626
        }
 
2627
        
 
2628
        /* need to clean even if 0 because man page doesn't specify */
 
2629
        free(direntries);
 
2630
        if(numentries == -1){
 
2631
          perror_plus("scandir");
 
2632
        }
 
2633
        ret = rmdir(tempdir);
 
2634
        if(ret == -1 and errno != ENOENT){
 
2635
          perror_plus("rmdir");
 
2636
        }
2291
2637
      }
2292
 
    }
2293
 
 
2294
 
    /* need to clean even if 0 because man page doesn't specify */
2295
 
    free(direntries);
2296
 
    if (numentries == -1){
2297
 
      perror_plus("scandir");
2298
 
    }
2299
 
    ret = rmdir(tempdir);
2300
 
    if(ret == -1 and errno != ENOENT){
2301
 
      perror_plus("rmdir");
 
2638
      TEMP_FAILURE_RETRY(close(tempdir_fd));
2302
2639
    }
2303
2640
  }
2304
2641