/mandos/trunk

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

« back to all changes in this revision

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

  • Committer: Björn Påhlsson
  • Date: 2011-06-23 22:27:15 UTC
  • mto: This revision was merged to the branch mainline in revision 485.
  • Revision ID: belorn@fukt.bsnet.se-20110623222715-q5wro9ma9iyjl367
* Makefile (CFLAGS): Added "-lrt" to include real time library.
* plugins.d/mandos-client.c: use scandir(3) instead of readdir(3)
                             Prefix all debug output with "Mandos plugin " + program_invocation_short_name
                             Retry servers that failed to provide password.
                             New option --retry SECONDS that sets the interval between rechecking.
                             --retry also controls how often it retries a server when using --connect.
* plugins.d/splashy.c:  Prefix all debug output with "Mandos plugin " + program_invocation_short_name
* plugins.d/usplash.c: --||--
* plugins.d/askpass-fifo.c: --||--
* plugins.d/password-prompt.c: --||--
* plugins.d/plymouth.c: --||--
* mandos: Lower logger level from warning to info on failed client requests because client was disabled or unknown fingerprint.
* plugins.d/plymouth.c (get_pid): bug fix. Was not calling free on direntries. 

Show diffs side-by-side

added added

removed removed

Lines of Context:
26
26
 * along with this program.  If not, see
27
27
 * <http://www.gnu.org/licenses/>.
28
28
 * 
29
 
 * Contact the authors at <mandos@recompile.se>.
 
29
 * Contact the authors at <mandos@fukt.bsnet.se>.
30
30
 */
31
31
 
32
32
/* Needed by GPGME, specifically gpgme_data_seek() */
53
53
                                   sockaddr_in6, PF_INET6,
54
54
                                   SOCK_STREAM, uid_t, gid_t, open(),
55
55
                                   opendir(), DIR */
56
 
#include <sys/stat.h>           /* open(), S_ISREG */
 
56
#include <sys/stat.h>           /* open() */
57
57
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
58
58
                                   inet_pton(), connect() */
59
59
#include <fcntl.h>              /* open() */
62
62
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
63
63
                                   strtoimax() */
64
64
#include <assert.h>             /* assert() */
65
 
#include <errno.h>              /* perror(), errno,
66
 
                                   program_invocation_short_name */
 
65
#include <errno.h>              /* perror(), errno, program_invocation_short_name */
67
66
#include <time.h>               /* nanosleep(), time(), sleep() */
68
67
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
69
68
                                   SIOCSIFFLAGS, if_indextoname(),
73
72
                                */
74
73
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
75
74
                                   getuid(), getgid(), seteuid(),
76
 
                                   setgid(), pause(), _exit() */
77
 
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
 
75
                                   setgid(), pause() */
 
76
#include <arpa/inet.h>          /* inet_pton(), htons */
78
77
#include <iso646.h>             /* not, or, and */
79
78
#include <argp.h>               /* struct argp_option, error_t, struct
80
79
                                   argp_state, struct argp,
85
84
                                   raise() */
86
85
#include <sysexits.h>           /* EX_OSERR, EX_USAGE, EX_UNAVAILABLE,
87
86
                                   EX_NOHOST, EX_IOERR, EX_PROTOCOL */
88
 
#include <sys/wait.h>           /* waitpid(), WIFEXITED(),
89
 
                                   WEXITSTATUS(), WTERMSIG() */
90
87
 
91
88
#ifdef __linux__
92
89
#include <sys/klog.h>           /* klogctl() */
110
107
                                   init_gnutls_session(),
111
108
                                   GNUTLS_* */
112
109
#include <gnutls/openpgp.h>
113
 
                         /* gnutls_certificate_set_openpgp_key_file(),
114
 
                            GNUTLS_OPENPGP_FMT_BASE64 */
 
110
                          /* gnutls_certificate_set_openpgp_key_file(),
 
111
                                   GNUTLS_OPENPGP_FMT_BASE64 */
115
112
 
116
113
/* GPGME */
117
114
#include <gpgme.h>              /* All GPGME types, constants and
125
122
#define PATHDIR "/conf/conf.d/mandos"
126
123
#define SECKEY "seckey.txt"
127
124
#define PUBKEY "pubkey.txt"
128
 
#define HOOKDIR "/lib/mandos/network-hooks.d"
129
125
 
130
126
bool debug = false;
131
127
static const char mandos_protocol_version[] = "1";
132
128
const char *argp_program_version = "mandos-client " VERSION;
133
 
const char *argp_program_bug_address = "<mandos@recompile.se>";
 
129
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
134
130
static const char sys_class_net[] = "/sys/class/net";
135
131
char *connect_to = NULL;
136
 
const char *hookdir = HOOKDIR;
137
132
 
138
 
/* Doubly linked list that need to be circularly linked when used */
 
133
/* Doubly linked list that need to be circular linked when ever used */
139
134
typedef struct server{
140
135
  const char *ip;
141
136
  uint16_t port;
161
156
/* global context so signal handler can reach it*/
162
157
mandos_context mc = { .simple_poll = NULL, .server = NULL,
163
158
                      .dh_bits = 1024, .priority = "SECURE256"
164
 
                      ":!CTYPE-X.509:+CTYPE-OPENPGP",
165
 
                      .current_server = NULL };
 
159
                      ":!CTYPE-X.509:+CTYPE-OPENPGP", .current_server = NULL };
166
160
 
167
161
sig_atomic_t quit_now = 0;
168
162
int signal_received = 0;
169
163
 
170
164
/* Function to use when printing errors */
171
165
void perror_plus(const char *print_text){
172
 
  fprintf(stderr, "Mandos plugin %s: ",
173
 
          program_invocation_short_name);
 
166
  fprintf(stderr, "Mandos plugin %s: ", program_invocation_short_name);
174
167
  perror(print_text);
175
168
}
176
169
 
177
 
int fprintf_plus(FILE *stream, const char *format, ...){
178
 
  va_list ap;
179
 
  va_start (ap, format);
180
 
  
181
 
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ",
182
 
                             program_invocation_short_name));
183
 
  return TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
184
 
}
185
 
 
186
170
/*
187
171
 * Make additional room in "buffer" for at least BUFFER_SIZE more
188
172
 * bytes. "buffer_capacity" is how much is currently allocated,
189
173
 * "buffer_length" is how much is already used.
190
174
 */
191
175
size_t incbuffer(char **buffer, size_t buffer_length,
192
 
                 size_t buffer_capacity){
 
176
                  size_t buffer_capacity){
193
177
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
194
178
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
195
179
    if(buffer == NULL){
200
184
  return buffer_capacity;
201
185
}
202
186
 
203
 
/* Add server to set of servers to retry periodically */
204
 
int add_server(const char *ip, uint16_t port, AvahiIfIndex if_index,
205
 
               int af){
 
187
int add_server(const char *ip, uint16_t port,
 
188
                 AvahiIfIndex if_index,
 
189
                 int af){
206
190
  int ret;
207
191
  server *new_server = malloc(sizeof(server));
208
192
  if(new_server == NULL){
210
194
    return -1;
211
195
  }
212
196
  *new_server = (server){ .ip = strdup(ip),
213
 
                          .port = port,
214
 
                          .if_index = if_index,
215
 
                          .af = af };
 
197
                         .port = port,
 
198
                         .if_index = if_index,
 
199
                         .af = af };
216
200
  if(new_server->ip == NULL){
217
201
    perror_plus("strdup");
218
 
    return -1;
 
202
    return -1;    
219
203
  }
220
 
  /* Special case of first server */
 
204
  /* uniqe case of first server */
221
205
  if (mc.current_server == NULL){
222
206
    new_server->next = new_server;
223
207
    new_server->prev = new_server;
224
208
    mc.current_server = new_server;
225
 
  /* Place the new server last in the list */
 
209
  /* Placing the new server last in the list */
226
210
  } else {
227
211
    new_server->next = mc.current_server;
228
212
    new_server->prev = mc.current_server->prev;
240
224
/* 
241
225
 * Initialize GPGME.
242
226
 */
243
 
static bool init_gpgme(const char *seckey, const char *pubkey,
244
 
                       const char *tempdir){
 
227
static bool init_gpgme(const char *seckey,
 
228
                       const char *pubkey, const char *tempdir){
245
229
  gpgme_error_t rc;
246
230
  gpgme_engine_info_t engine_info;
247
231
  
262
246
    
263
247
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
264
248
    if(rc != GPG_ERR_NO_ERROR){
265
 
      fprintf_plus(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
266
 
                   gpgme_strsource(rc), gpgme_strerror(rc));
 
249
      fprintf(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
 
250
              gpgme_strsource(rc), gpgme_strerror(rc));
267
251
      return false;
268
252
    }
269
253
    
270
254
    rc = gpgme_op_import(mc.ctx, pgp_data);
271
255
    if(rc != GPG_ERR_NO_ERROR){
272
 
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
273
 
                   gpgme_strsource(rc), gpgme_strerror(rc));
 
256
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
 
257
              gpgme_strsource(rc), gpgme_strerror(rc));
274
258
      return false;
275
259
    }
276
260
    
283
267
  }
284
268
  
285
269
  if(debug){
286
 
    fprintf_plus(stderr, "Initializing GPGME\n");
 
270
    fprintf(stderr, "Initializing GPGME\n");
287
271
  }
288
272
  
289
273
  /* Init GPGME */
290
274
  gpgme_check_version(NULL);
291
275
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
292
276
  if(rc != GPG_ERR_NO_ERROR){
293
 
    fprintf_plus(stderr, "bad gpgme_engine_check_version: %s: %s\n",
294
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
277
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
 
278
            gpgme_strsource(rc), gpgme_strerror(rc));
295
279
    return false;
296
280
  }
297
281
  
298
 
  /* Set GPGME home directory for the OpenPGP engine only */
 
282
    /* Set GPGME home directory for the OpenPGP engine only */
299
283
  rc = gpgme_get_engine_info(&engine_info);
300
284
  if(rc != GPG_ERR_NO_ERROR){
301
 
    fprintf_plus(stderr, "bad gpgme_get_engine_info: %s: %s\n",
302
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
285
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
 
286
            gpgme_strsource(rc), gpgme_strerror(rc));
303
287
    return false;
304
288
  }
305
289
  while(engine_info != NULL){
311
295
    engine_info = engine_info->next;
312
296
  }
313
297
  if(engine_info == NULL){
314
 
    fprintf_plus(stderr, "Could not set GPGME home dir to %s\n",
315
 
                 tempdir);
 
298
    fprintf(stderr, "Could not set GPGME home dir to %s\n", tempdir);
316
299
    return false;
317
300
  }
318
301
  
319
302
  /* Create new GPGME "context" */
320
303
  rc = gpgme_new(&(mc.ctx));
321
304
  if(rc != GPG_ERR_NO_ERROR){
322
 
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
323
 
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
324
 
                 gpgme_strerror(rc));
 
305
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
 
306
            gpgme_strsource(rc), gpgme_strerror(rc));
325
307
    return false;
326
308
  }
327
309
  
346
328
  ssize_t plaintext_length = 0;
347
329
  
348
330
  if(debug){
349
 
    fprintf_plus(stderr, "Trying to decrypt OpenPGP data\n");
 
331
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
350
332
  }
351
333
  
352
334
  /* Create new GPGME data buffer from memory cryptotext */
353
335
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
354
336
                               0);
355
337
  if(rc != GPG_ERR_NO_ERROR){
356
 
    fprintf_plus(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
357
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
338
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
 
339
            gpgme_strsource(rc), gpgme_strerror(rc));
358
340
    return -1;
359
341
  }
360
342
  
361
343
  /* Create new empty GPGME data buffer for the plaintext */
362
344
  rc = gpgme_data_new(&dh_plain);
363
345
  if(rc != GPG_ERR_NO_ERROR){
364
 
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
365
 
                 "bad gpgme_data_new: %s: %s\n",
366
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
346
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
 
347
            gpgme_strsource(rc), gpgme_strerror(rc));
367
348
    gpgme_data_release(dh_crypto);
368
349
    return -1;
369
350
  }
372
353
     data buffer */
373
354
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
374
355
  if(rc != GPG_ERR_NO_ERROR){
375
 
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
376
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
356
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
 
357
            gpgme_strsource(rc), gpgme_strerror(rc));
377
358
    plaintext_length = -1;
378
359
    if(debug){
379
360
      gpgme_decrypt_result_t result;
380
361
      result = gpgme_op_decrypt_result(mc.ctx);
381
362
      if(result == NULL){
382
 
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
 
363
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
383
364
      } else {
384
 
        fprintf_plus(stderr, "Unsupported algorithm: %s\n",
385
 
                     result->unsupported_algorithm);
386
 
        fprintf_plus(stderr, "Wrong key usage: %u\n",
387
 
                     result->wrong_key_usage);
 
365
        fprintf(stderr, "Unsupported algorithm: %s\n",
 
366
                result->unsupported_algorithm);
 
367
        fprintf(stderr, "Wrong key usage: %u\n",
 
368
                result->wrong_key_usage);
388
369
        if(result->file_name != NULL){
389
 
          fprintf_plus(stderr, "File name: %s\n", result->file_name);
 
370
          fprintf(stderr, "File name: %s\n", result->file_name);
390
371
        }
391
372
        gpgme_recipient_t recipient;
392
373
        recipient = result->recipients;
393
374
        while(recipient != NULL){
394
 
          fprintf_plus(stderr, "Public key algorithm: %s\n",
395
 
                       gpgme_pubkey_algo_name
396
 
                       (recipient->pubkey_algo));
397
 
          fprintf_plus(stderr, "Key ID: %s\n", recipient->keyid);
398
 
          fprintf_plus(stderr, "Secret key available: %s\n",
399
 
                       recipient->status == GPG_ERR_NO_SECKEY
400
 
                       ? "No" : "Yes");
 
375
          fprintf(stderr, "Public key algorithm: %s\n",
 
376
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
 
377
          fprintf(stderr, "Key ID: %s\n", recipient->keyid);
 
378
          fprintf(stderr, "Secret key available: %s\n",
 
379
                  recipient->status == GPG_ERR_NO_SECKEY
 
380
                  ? "No" : "Yes");
401
381
          recipient = recipient->next;
402
382
        }
403
383
      }
406
386
  }
407
387
  
408
388
  if(debug){
409
 
    fprintf_plus(stderr, "Decryption of OpenPGP data succeeded\n");
 
389
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
410
390
  }
411
391
  
412
392
  /* Seek back to the beginning of the GPGME plaintext data buffer */
419
399
  *plaintext = NULL;
420
400
  while(true){
421
401
    plaintext_capacity = incbuffer(plaintext,
422
 
                                   (size_t)plaintext_length,
423
 
                                   plaintext_capacity);
 
402
                                      (size_t)plaintext_length,
 
403
                                      plaintext_capacity);
424
404
    if(plaintext_capacity == 0){
425
 
      perror_plus("incbuffer");
426
 
      plaintext_length = -1;
427
 
      goto decrypt_end;
 
405
        perror_plus("incbuffer");
 
406
        plaintext_length = -1;
 
407
        goto decrypt_end;
428
408
    }
429
409
    
430
410
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
443
423
  }
444
424
  
445
425
  if(debug){
446
 
    fprintf_plus(stderr, "Decrypted password is: ");
 
426
    fprintf(stderr, "Decrypted password is: ");
447
427
    for(ssize_t i = 0; i < plaintext_length; i++){
448
428
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
449
429
    }
471
451
/* GnuTLS log function callback */
472
452
static void debuggnutls(__attribute__((unused)) int level,
473
453
                        const char* string){
474
 
  fprintf_plus(stderr, "GnuTLS: %s", string);
 
454
  fprintf(stderr, "GnuTLS: %s", string);
475
455
}
476
456
 
477
457
static int init_gnutls_global(const char *pubkeyfilename,
479
459
  int ret;
480
460
  
481
461
  if(debug){
482
 
    fprintf_plus(stderr, "Initializing GnuTLS\n");
 
462
    fprintf(stderr, "Initializing GnuTLS\n");
483
463
  }
484
464
  
485
465
  ret = gnutls_global_init();
486
466
  if(ret != GNUTLS_E_SUCCESS){
487
 
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
488
 
                 safer_gnutls_strerror(ret));
 
467
    fprintf(stderr, "GnuTLS global_init: %s\n",
 
468
            safer_gnutls_strerror(ret));
489
469
    return -1;
490
470
  }
491
471
  
498
478
  }
499
479
  
500
480
  /* OpenPGP credentials */
501
 
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
 
481
  gnutls_certificate_allocate_credentials(&mc.cred);
502
482
  if(ret != GNUTLS_E_SUCCESS){
503
 
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
504
 
                 safer_gnutls_strerror(ret));
 
483
    fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning
 
484
                                                    from
 
485
                                                    -Wunreachable-code
 
486
                                                 */
 
487
            safer_gnutls_strerror(ret));
505
488
    gnutls_global_deinit();
506
489
    return -1;
507
490
  }
508
491
  
509
492
  if(debug){
510
 
    fprintf_plus(stderr, "Attempting to use OpenPGP public key %s and"
511
 
                 " secret key %s as GnuTLS credentials\n",
512
 
                 pubkeyfilename,
513
 
                 seckeyfilename);
 
493
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
 
494
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
 
495
            seckeyfilename);
514
496
  }
515
497
  
516
498
  ret = gnutls_certificate_set_openpgp_key_file
517
499
    (mc.cred, pubkeyfilename, seckeyfilename,
518
500
     GNUTLS_OPENPGP_FMT_BASE64);
519
501
  if(ret != GNUTLS_E_SUCCESS){
520
 
    fprintf_plus(stderr,
521
 
                 "Error[%d] while reading the OpenPGP key pair ('%s',"
522
 
                 " '%s')\n", ret, pubkeyfilename, seckeyfilename);
523
 
    fprintf_plus(stderr, "The GnuTLS error is: %s\n",
524
 
                 safer_gnutls_strerror(ret));
 
502
    fprintf(stderr,
 
503
            "Error[%d] while reading the OpenPGP key pair ('%s',"
 
504
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
 
505
    fprintf(stderr, "The GnuTLS error is: %s\n",
 
506
            safer_gnutls_strerror(ret));
525
507
    goto globalfail;
526
508
  }
527
509
  
528
510
  /* GnuTLS server initialization */
529
511
  ret = gnutls_dh_params_init(&mc.dh_params);
530
512
  if(ret != GNUTLS_E_SUCCESS){
531
 
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
532
 
                 " initialization: %s\n",
533
 
                 safer_gnutls_strerror(ret));
 
513
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
 
514
            " %s\n", safer_gnutls_strerror(ret));
534
515
    goto globalfail;
535
516
  }
536
517
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
537
518
  if(ret != GNUTLS_E_SUCCESS){
538
 
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
539
 
                 safer_gnutls_strerror(ret));
 
519
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
 
520
            safer_gnutls_strerror(ret));
540
521
    goto globalfail;
541
522
  }
542
523
  
562
543
    }
563
544
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
564
545
  if(ret != GNUTLS_E_SUCCESS){
565
 
    fprintf_plus(stderr,
566
 
                 "Error in GnuTLS session initialization: %s\n",
567
 
                 safer_gnutls_strerror(ret));
 
546
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
 
547
            safer_gnutls_strerror(ret));
568
548
  }
569
549
  
570
550
  {
577
557
      }
578
558
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
579
559
    if(ret != GNUTLS_E_SUCCESS){
580
 
      fprintf_plus(stderr, "Syntax error at: %s\n", err);
581
 
      fprintf_plus(stderr, "GnuTLS error: %s\n",
582
 
                   safer_gnutls_strerror(ret));
 
560
      fprintf(stderr, "Syntax error at: %s\n", err);
 
561
      fprintf(stderr, "GnuTLS error: %s\n",
 
562
              safer_gnutls_strerror(ret));
583
563
      gnutls_deinit(*session);
584
564
      return -1;
585
565
    }
594
574
    }
595
575
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
596
576
  if(ret != GNUTLS_E_SUCCESS){
597
 
    fprintf_plus(stderr, "Error setting GnuTLS credentials: %s\n",
598
 
                 safer_gnutls_strerror(ret));
 
577
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
 
578
            safer_gnutls_strerror(ret));
599
579
    gnutls_deinit(*session);
600
580
    return -1;
601
581
  }
646
626
    pf = PF_INET;
647
627
    break;
648
628
  default:
649
 
    fprintf_plus(stderr, "Bad address family: %d\n", af);
 
629
    fprintf(stderr, "Bad address family: %d\n", af);
650
630
    errno = EINVAL;
651
631
    return -1;
652
632
  }
657
637
  }
658
638
  
659
639
  if(debug){
660
 
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
661
 
                 PRIu16 "\n", ip, port);
 
640
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
 
641
            "\n", ip, port);
662
642
  }
663
643
  
664
644
  tcp_sd = socket(pf, SOCK_STREAM, 0);
690
670
  }
691
671
  if(ret == 0){
692
672
    int e = errno;
693
 
    fprintf_plus(stderr, "Bad address: %s\n", ip);
 
673
    fprintf(stderr, "Bad address: %s\n", ip);
694
674
    errno = e;
695
675
    goto mandos_end;
696
676
  }
701
681
    
702
682
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
703
683
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
704
 
                                -Wunreachable-code*/
 
684
                              -Wunreachable-code*/
705
685
      if(if_index == AVAHI_IF_UNSPEC){
706
 
        fprintf_plus(stderr, "An IPv6 link-local address is"
707
 
                     " incomplete without a network interface\n");
 
686
        fprintf(stderr, "An IPv6 link-local address is incomplete"
 
687
                " without a network interface\n");
708
688
        errno = EINVAL;
709
689
        goto mandos_end;
710
690
      }
728
708
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
729
709
        perror_plus("if_indextoname");
730
710
      } else {
731
 
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIu16
732
 
                     "\n", ip, interface, port);
 
711
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
 
712
                ip, interface, port);
733
713
      }
734
714
    } else {
735
 
      fprintf_plus(stderr, "Connection to: %s, port %" PRIu16 "\n",
736
 
                   ip, port);
 
715
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
 
716
              port);
737
717
    }
738
718
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
739
719
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
749
729
      perror_plus("inet_ntop");
750
730
    } else {
751
731
      if(strcmp(addrstr, ip) != 0){
752
 
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
 
732
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
753
733
      }
754
734
    }
755
735
  }
783
763
  while(true){
784
764
    size_t out_size = strlen(out);
785
765
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
786
 
                                        out_size - written));
 
766
                                   out_size - written));
787
767
    if(ret == -1){
788
768
      int e = errno;
789
769
      perror_plus("write");
809
789
  }
810
790
  
811
791
  if(debug){
812
 
    fprintf_plus(stderr, "Establishing TLS session with %s\n", ip);
 
792
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
813
793
  }
814
794
  
815
795
  if(quit_now){
816
796
    errno = EINTR;
817
797
    goto mandos_end;
818
798
  }
819
 
  
820
 
  /* Spurious warning from -Wint-to-pointer-cast */
 
799
 
 
800
  /* Spurious warnings from -Wint-to-pointer-cast */
821
801
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
822
802
  
823
803
  if(quit_now){
835
815
  
836
816
  if(ret != GNUTLS_E_SUCCESS){
837
817
    if(debug){
838
 
      fprintf_plus(stderr, "*** GnuTLS Handshake failed ***\n");
 
818
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
839
819
      gnutls_perror(ret);
840
820
    }
841
821
    errno = EPROTO;
845
825
  /* Read OpenPGP packet that contains the wanted password */
846
826
  
847
827
  if(debug){
848
 
    fprintf_plus(stderr, "Retrieving OpenPGP encrypted password from"
849
 
                 " %s\n", ip);
 
828
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
 
829
            ip);
850
830
  }
851
831
  
852
832
  while(true){
857
837
    }
858
838
    
859
839
    buffer_capacity = incbuffer(&buffer, buffer_length,
860
 
                                buffer_capacity);
 
840
                                   buffer_capacity);
861
841
    if(buffer_capacity == 0){
862
842
      int e = errno;
863
843
      perror_plus("incbuffer");
890
870
          }
891
871
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
892
872
        if(ret < 0){
893
 
          fprintf_plus(stderr, "*** GnuTLS Re-handshake failed "
894
 
                       "***\n");
 
873
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
895
874
          gnutls_perror(ret);
896
875
          errno = EPROTO;
897
876
          goto mandos_end;
898
877
        }
899
878
        break;
900
879
      default:
901
 
        fprintf_plus(stderr, "Unknown error while reading data from"
902
 
                     " encrypted session with Mandos server\n");
 
880
        fprintf(stderr, "Unknown error while reading data from"
 
881
                " encrypted session with Mandos server\n");
903
882
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
904
883
        errno = EIO;
905
884
        goto mandos_end;
910
889
  }
911
890
  
912
891
  if(debug){
913
 
    fprintf_plus(stderr, "Closing TLS session\n");
 
892
    fprintf(stderr, "Closing TLS session\n");
914
893
  }
915
894
  
916
895
  if(quit_now){
928
907
  
929
908
  if(buffer_length > 0){
930
909
    ssize_t decrypted_buffer_size;
931
 
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
 
910
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
 
911
                                               buffer_length,
932
912
                                               &decrypted_buffer);
933
913
    if(decrypted_buffer_size >= 0){
934
914
      
945
925
        if(ret == 0 and ferror(stdout)){
946
926
          int e = errno;
947
927
          if(debug){
948
 
            fprintf_plus(stderr, "Error writing encrypted data: %s\n",
949
 
                         strerror(errno));
 
928
            fprintf(stderr, "Error writing encrypted data: %s\n",
 
929
                    strerror(errno));
950
930
          }
951
931
          errno = e;
952
932
          goto mandos_end;
1009
989
  switch(event){
1010
990
  default:
1011
991
  case AVAHI_RESOLVER_FAILURE:
1012
 
    fprintf_plus(stderr, "(Avahi Resolver) Failed to resolve service "
1013
 
                 "'%s' of type '%s' in domain '%s': %s\n", name, type,
1014
 
                 domain,
1015
 
                 avahi_strerror(avahi_server_errno(mc.server)));
 
992
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
 
993
            " of type '%s' in domain '%s': %s\n", name, type, domain,
 
994
            avahi_strerror(avahi_server_errno(mc.server)));
1016
995
    break;
1017
996
    
1018
997
  case AVAHI_RESOLVER_FOUND:
1020
999
      char ip[AVAHI_ADDRESS_STR_MAX];
1021
1000
      avahi_address_snprint(ip, sizeof(ip), address);
1022
1001
      if(debug){
1023
 
        fprintf_plus(stderr, "Mandos server \"%s\" found on %s (%s, %"
1024
 
                     PRIdMAX ") on port %" PRIu16 "\n", name,
1025
 
                     host_name, ip, (intmax_t)interface, port);
 
1002
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %"
 
1003
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
 
1004
                ip, (intmax_t)interface, port);
1026
1005
      }
1027
1006
      int ret = start_mandos_communication(ip, port, interface,
1028
1007
                                           avahi_proto_to_af(proto));
1060
1039
  default:
1061
1040
  case AVAHI_BROWSER_FAILURE:
1062
1041
    
1063
 
    fprintf_plus(stderr, "(Avahi browser) %s\n",
1064
 
                 avahi_strerror(avahi_server_errno(mc.server)));
 
1042
    fprintf(stderr, "(Avahi browser) %s\n",
 
1043
            avahi_strerror(avahi_server_errno(mc.server)));
1065
1044
    avahi_simple_poll_quit(mc.simple_poll);
1066
1045
    return;
1067
1046
    
1074
1053
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
1075
1054
                                    name, type, domain, protocol, 0,
1076
1055
                                    resolve_callback, NULL) == NULL)
1077
 
      fprintf_plus(stderr, "Avahi: Failed to resolve service '%s':"
1078
 
                   " %s\n", name,
1079
 
                   avahi_strerror(avahi_server_errno(mc.server)));
 
1056
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
 
1057
              name, avahi_strerror(avahi_server_errno(mc.server)));
1080
1058
    break;
1081
1059
    
1082
1060
  case AVAHI_BROWSER_REMOVE:
1085
1063
  case AVAHI_BROWSER_ALL_FOR_NOW:
1086
1064
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1087
1065
    if(debug){
1088
 
      fprintf_plus(stderr, "No Mandos server found, still"
1089
 
                   " searching...\n");
 
1066
      fprintf(stderr, "No Mandos server found, still searching...\n");
1090
1067
    }
1091
1068
    break;
1092
1069
  }
1093
1070
}
1094
1071
 
1095
 
/* Signal handler that stops main loop after SIGTERM */
 
1072
/* Signal handler that stops main loop after sigterm has been called */
1096
1073
static void handle_sigterm(int sig){
1097
1074
  if(quit_now){
1098
1075
    return;
1107
1084
  errno = old_errno;
1108
1085
}
1109
1086
 
1110
 
bool get_flags(const char *ifname, struct ifreq *ifr){
1111
 
  int ret;
1112
 
  
1113
 
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1114
 
  if(s < 0){
1115
 
    perror_plus("socket");
1116
 
    return false;
1117
 
  }
1118
 
  strcpy(ifr->ifr_name, ifname);
1119
 
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1120
 
  if(ret == -1){
 
1087
/* 
 
1088
 * This function determines if a directory entry in /sys/class/net
 
1089
 * corresponds to an acceptable network device.
 
1090
 * (This function is passed to scandir(3) as a filter function.)
 
1091
 */
 
1092
int good_interface(const struct dirent *if_entry){
 
1093
  ssize_t ssret;
 
1094
  char *flagname = NULL;
 
1095
  if(if_entry->d_name[0] == '.'){
 
1096
    return 0;
 
1097
  }
 
1098
  int ret = asprintf(&flagname, "%s/%s/flags", sys_class_net,
 
1099
                     if_entry->d_name);
 
1100
  if(ret < 0){
 
1101
    perror_plus("asprintf");
 
1102
    return 0;
 
1103
  }
 
1104
  int flags_fd = (int)TEMP_FAILURE_RETRY(open(flagname, O_RDONLY));
 
1105
  if(flags_fd == -1){
 
1106
    perror_plus("open");
 
1107
    free(flagname);
 
1108
    return 0;
 
1109
  }
 
1110
  free(flagname);
 
1111
  typedef short ifreq_flags;    /* ifreq.ifr_flags in netdevice(7) */
 
1112
  /* read line from flags_fd */
 
1113
  ssize_t to_read = (sizeof(ifreq_flags)*2)+3; /* "0x1003\n" */
 
1114
  char *flagstring = malloc((size_t)to_read+1); /* +1 for final \0 */
 
1115
  flagstring[(size_t)to_read] = '\0';
 
1116
  if(flagstring == NULL){
 
1117
    perror_plus("malloc");
 
1118
    close(flags_fd);
 
1119
    return 0;
 
1120
  }
 
1121
  while(to_read > 0){
 
1122
    ssret = (ssize_t)TEMP_FAILURE_RETRY(read(flags_fd, flagstring,
 
1123
                                             (size_t)to_read));
 
1124
    if(ssret == -1){
 
1125
      perror_plus("read");
 
1126
      free(flagstring);
 
1127
      close(flags_fd);
 
1128
      return 0;
 
1129
    }
 
1130
    to_read -= ssret;
 
1131
    if(ssret == 0){
 
1132
      break;
 
1133
    }
 
1134
  }
 
1135
  close(flags_fd);
 
1136
  intmax_t tmpmax;
 
1137
  char *tmp;
 
1138
  errno = 0;
 
1139
  tmpmax = strtoimax(flagstring, &tmp, 0);
 
1140
  if(errno != 0 or tmp == flagstring or (*tmp != '\0'
 
1141
                                         and not (isspace(*tmp)))
 
1142
     or tmpmax != (ifreq_flags)tmpmax){
1121
1143
    if(debug){
1122
 
      perror_plus("ioctl SIOCGIFFLAGS");
 
1144
      fprintf(stderr, "Invalid flags \"%s\" for interface \"%s\"\n",
 
1145
              flagstring, if_entry->d_name);
1123
1146
    }
1124
 
    return false;
 
1147
    free(flagstring);
 
1148
    return 0;
1125
1149
  }
1126
 
  return true;
1127
 
}
1128
 
 
1129
 
bool good_flags(const char *ifname, const struct ifreq *ifr){
1130
 
  
 
1150
  free(flagstring);
 
1151
  ifreq_flags flags = (ifreq_flags)tmpmax;
1131
1152
  /* Reject the loopback device */
1132
 
  if(ifr->ifr_flags & IFF_LOOPBACK){
 
1153
  if(flags & IFF_LOOPBACK){
1133
1154
    if(debug){
1134
 
      fprintf_plus(stderr, "Rejecting loopback interface \"%s\"\n",
1135
 
                   ifname);
 
1155
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
 
1156
              if_entry->d_name);
1136
1157
    }
1137
 
    return false;
 
1158
    return 0;
1138
1159
  }
1139
1160
  /* Accept point-to-point devices only if connect_to is specified */
1140
 
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
 
1161
  if(connect_to != NULL and (flags & IFF_POINTOPOINT)){
1141
1162
    if(debug){
1142
 
      fprintf_plus(stderr, "Accepting point-to-point interface"
1143
 
                   " \"%s\"\n", ifname);
 
1163
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
 
1164
              if_entry->d_name);
1144
1165
    }
1145
 
    return true;
 
1166
    return 1;
1146
1167
  }
1147
1168
  /* Otherwise, reject non-broadcast-capable devices */
1148
 
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
 
1169
  if(not (flags & IFF_BROADCAST)){
1149
1170
    if(debug){
1150
 
      fprintf_plus(stderr, "Rejecting non-broadcast interface"
1151
 
                   " \"%s\"\n", ifname);
 
1171
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
 
1172
              if_entry->d_name);
1152
1173
    }
1153
 
    return false;
 
1174
    return 0;
1154
1175
  }
1155
1176
  /* Reject non-ARP interfaces (including dummy interfaces) */
1156
 
  if(ifr->ifr_flags & IFF_NOARP){
 
1177
  if(flags & IFF_NOARP){
1157
1178
    if(debug){
1158
 
      fprintf_plus(stderr, "Rejecting non-ARP interface \"%s\"\n",
1159
 
                   ifname);
 
1179
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n",
 
1180
              if_entry->d_name);
1160
1181
    }
1161
 
    return false;
 
1182
    return 0;
1162
1183
  }
1163
 
  
1164
1184
  /* Accept this device */
1165
1185
  if(debug){
1166
 
    fprintf_plus(stderr, "Interface \"%s\" is good\n", ifname);
1167
 
  }
1168
 
  return true;
1169
 
}
1170
 
 
1171
 
/* 
1172
 
 * This function determines if a directory entry in /sys/class/net
1173
 
 * corresponds to an acceptable network device.
1174
 
 * (This function is passed to scandir(3) as a filter function.)
1175
 
 */
1176
 
int good_interface(const struct dirent *if_entry){
1177
 
  if(if_entry->d_name[0] == '.'){
1178
 
    return 0;
1179
 
  }
1180
 
  
1181
 
  struct ifreq ifr;
1182
 
  if(not get_flags(if_entry->d_name, &ifr)){
1183
 
    if(debug){
1184
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1185
 
                   "\"%s\"\n", if_entry->d_name);
1186
 
    }
1187
 
    return 0;
1188
 
  }
1189
 
  
1190
 
  if(not good_flags(if_entry->d_name, &ifr)){
1191
 
    return 0;
1192
 
  }
1193
 
  return 1;
1194
 
}
1195
 
 
1196
 
/* 
1197
 
 * This function determines if a directory entry in /sys/class/net
1198
 
 * corresponds to an acceptable network device which is up.
1199
 
 * (This function is passed to scandir(3) as a filter function.)
1200
 
 */
1201
 
int up_interface(const struct dirent *if_entry){
1202
 
  if(if_entry->d_name[0] == '.'){
1203
 
    return 0;
1204
 
  }
1205
 
  
1206
 
  struct ifreq ifr;
1207
 
  if(not get_flags(if_entry->d_name, &ifr)){
1208
 
    if(debug){
1209
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1210
 
                   "\"%s\"\n", if_entry->d_name);
1211
 
    }
1212
 
    return 0;
1213
 
  }
1214
 
  
1215
 
  /* Reject down interfaces */
1216
 
  if(not (ifr.ifr_flags & IFF_UP)){
1217
 
    if(debug){
1218
 
      fprintf_plus(stderr, "Rejecting down interface \"%s\"\n",
1219
 
                   if_entry->d_name);
1220
 
    }
1221
 
    return 0;
1222
 
  }
1223
 
  
1224
 
  /* Reject non-running interfaces */
1225
 
  if(not (ifr.ifr_flags & IFF_RUNNING)){
1226
 
    if(debug){
1227
 
      fprintf_plus(stderr, "Rejecting non-running interface \"%s\"\n",
1228
 
                   if_entry->d_name);
1229
 
    }
1230
 
    return 0;
1231
 
  }
1232
 
  
1233
 
  if(not good_flags(if_entry->d_name, &ifr)){
1234
 
    return 0;
 
1186
    fprintf(stderr, "Interface \"%s\" is acceptable\n",
 
1187
            if_entry->d_name);
1235
1188
  }
1236
1189
  return 1;
1237
1190
}
1247
1200
  return 1;
1248
1201
}
1249
1202
 
1250
 
/* Is this directory entry a runnable program? */
1251
 
int runnable_hook(const struct dirent *direntry){
1252
 
  int ret;
1253
 
  size_t sret;
1254
 
  struct stat st;
1255
 
  
1256
 
  if((direntry->d_name)[0] == '\0'){
1257
 
    /* Empty name? */
1258
 
    return 0;
1259
 
  }
1260
 
  
1261
 
  sret = strspn(direntry->d_name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1262
 
                "abcdefghijklmnopqrstuvwxyz"
1263
 
                "0123456789"
1264
 
                "_-");
1265
 
  if((direntry->d_name)[sret] != '\0'){
1266
 
    /* Contains non-allowed characters */
1267
 
    if(debug){
1268
 
      fprintf_plus(stderr, "Ignoring hook \"%s\" with bad name\n",
1269
 
                   direntry->d_name);
1270
 
    }
1271
 
    return 0;
1272
 
  }
1273
 
  
1274
 
  char *fullname = NULL;
1275
 
  ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
1276
 
  if(ret < 0){
1277
 
    perror_plus("asprintf");
1278
 
    return 0;
1279
 
  }
1280
 
  
1281
 
  ret = stat(fullname, &st);
1282
 
  if(ret == -1){
1283
 
    if(debug){
1284
 
      perror_plus("Could not stat hook");
1285
 
    }
1286
 
    return 0;
1287
 
  }
1288
 
  if(not (S_ISREG(st.st_mode))){
1289
 
    /* Not a regular file */
1290
 
    if(debug){
1291
 
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not a file\n",
1292
 
                   direntry->d_name);
1293
 
    }
1294
 
    return 0;
1295
 
  }
1296
 
  if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
1297
 
    /* Not executable */
1298
 
    if(debug){
1299
 
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not executable\n",
1300
 
                   direntry->d_name);
1301
 
    }
1302
 
    return 0;
1303
 
  }
1304
 
  if(debug){
1305
 
    fprintf_plus(stderr, "Hook \"%s\" is acceptable\n",
1306
 
                 direntry->d_name);
1307
 
  }
1308
 
  return 1;
1309
 
}
1310
 
 
1311
1203
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
1312
1204
  int ret;
1313
1205
  struct timespec now;
1314
1206
  struct timespec waited_time;
1315
1207
  intmax_t block_time;
1316
 
  
 
1208
 
1317
1209
  while(true){
1318
1210
    if(mc.current_server == NULL){
1319
1211
      if (debug){
1320
 
        fprintf_plus(stderr, "Wait until first server is found."
1321
 
                     " No timeout!\n");
 
1212
        fprintf(stderr, "Wait until first server is found. No timeout!\n");     
1322
1213
      }
1323
1214
      ret = avahi_simple_poll_iterate(s, -1);
1324
1215
    } else {
1325
1216
      if (debug){
1326
 
        fprintf_plus(stderr, "Check current_server if we should run"
1327
 
                     " it, or wait\n");
 
1217
        fprintf(stderr, "Check current_server if we should run it, or wait\n"); 
1328
1218
      }
1329
1219
      /* the current time */
1330
1220
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
1334
1224
      }
1335
1225
      /* Calculating in ms how long time between now and server
1336
1226
         who we visted longest time ago. Now - last seen.  */
1337
 
      waited_time.tv_sec = (now.tv_sec
1338
 
                            - mc.current_server->last_seen.tv_sec);
1339
 
      waited_time.tv_nsec = (now.tv_nsec
1340
 
                             - mc.current_server->last_seen.tv_nsec);
1341
 
      /* total time is 10s/10,000ms.
1342
 
         Converting to s from ms by dividing by 1,000,
1343
 
         and ns to ms by dividing by 1,000,000. */
1344
 
      block_time = ((retry_interval
1345
 
                     - ((intmax_t)waited_time.tv_sec * 1000))
1346
 
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1347
 
      
 
1227
      waited_time.tv_sec = now.tv_sec - mc.current_server->last_seen.tv_sec;
 
1228
      waited_time.tv_nsec = now.tv_nsec - mc.current_server->last_seen.tv_nsec;
 
1229
      /* total time is 10s/10000ms. Converting to s to ms by 1000/s, and ns to ms by divind by 1000000. */
 
1230
      block_time = (retry_interval - ((intmax_t)waited_time.tv_sec * 1000)) - ((intmax_t)waited_time.tv_nsec / 1000000);
 
1231
 
1348
1232
      if (debug){
1349
 
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
1350
 
                     block_time);
 
1233
        fprintf(stderr, "Blocking for %ld ms\n", block_time);   
1351
1234
      }
1352
 
      
 
1235
 
1353
1236
      if(block_time <= 0){
1354
1237
        ret = start_mandos_communication(mc.current_server->ip,
1355
 
                                         mc.current_server->port,
1356
 
                                         mc.current_server->if_index,
1357
 
                                         mc.current_server->af);
 
1238
                                   mc.current_server->port,
 
1239
                                   mc.current_server->if_index,
 
1240
                                   mc.current_server->af);
1358
1241
        if(ret == 0){
1359
1242
          avahi_simple_poll_quit(mc.simple_poll);
1360
1243
          return 0;
1361
1244
        }
1362
 
        ret = clock_gettime(CLOCK_MONOTONIC,
1363
 
                            &mc.current_server->last_seen);
 
1245
        ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
1364
1246
        if(ret == -1){
1365
1247
          perror_plus("clock_gettime");
1366
1248
          return -1;
1367
1249
        }
1368
1250
        mc.current_server = mc.current_server->next;
1369
 
        block_time = 0;         /* Call avahi to find new Mandos
1370
 
                                   servers, but don't block */
 
1251
        block_time = 0;         /* call avahi to find new mandos servers, but dont block */
1371
1252
      }
1372
1253
      
1373
1254
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1374
1255
    }
1375
1256
    if(ret != 0){
1376
 
      if (ret > 0 or errno != EINTR){
 
1257
      if (ret > 0 or errno != EINTR) {
1377
1258
        return (ret != 1) ? ret : 0;
1378
1259
      }
1379
1260
    }
1380
1261
  }
1381
1262
}
1382
1263
 
1383
 
bool run_network_hooks(const char *mode, const char *interface,
1384
 
                       const float delay){
1385
 
  struct dirent **direntries;
1386
 
  struct dirent *direntry;
1387
 
  int ret;
1388
 
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
1389
 
                         alphasort);
1390
 
  if(numhooks == -1){
1391
 
    perror_plus("scandir");
1392
 
  } else {
1393
 
    int devnull = open("/dev/null", O_RDONLY);
1394
 
    for(int i = 0; i < numhooks; i++){
1395
 
      direntry = direntries[i];
1396
 
      char *fullname = NULL;
1397
 
      ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
1398
 
      if(ret < 0){
1399
 
        perror_plus("asprintf");
1400
 
        continue;
1401
 
      }
1402
 
      if(debug){
1403
 
        fprintf_plus(stderr, "Running network hook \"%s\"\n",
1404
 
                     direntry->d_name);
1405
 
      }
1406
 
      pid_t hook_pid = fork();
1407
 
      if(hook_pid == 0){
1408
 
        /* Child */
1409
 
        dup2(devnull, STDIN_FILENO);
1410
 
        close(devnull);
1411
 
        dup2(STDERR_FILENO, STDOUT_FILENO);
1412
 
        ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
1413
 
        if(ret == -1){
1414
 
          perror_plus("setenv");
1415
 
          _exit(EX_OSERR);
1416
 
        }
1417
 
        ret = setenv("DEVICE", interface, 1);
1418
 
        if(ret == -1){
1419
 
          perror_plus("setenv");
1420
 
          _exit(EX_OSERR);
1421
 
        }
1422
 
        ret = setenv("VERBOSE", debug ? "1" : "0", 1);
1423
 
        if(ret == -1){
1424
 
          perror_plus("setenv");
1425
 
          _exit(EX_OSERR);
1426
 
        }
1427
 
        ret = setenv("MODE", mode, 1);
1428
 
        if(ret == -1){
1429
 
          perror_plus("setenv");
1430
 
          _exit(EX_OSERR);
1431
 
        }
1432
 
        char *delaystring;
1433
 
        ret = asprintf(&delaystring, "%f", delay);
1434
 
        if(ret == -1){
1435
 
          perror_plus("asprintf");
1436
 
          _exit(EX_OSERR);
1437
 
        }
1438
 
        ret = setenv("DELAY", delaystring, 1);
1439
 
        if(ret == -1){
1440
 
          free(delaystring);
1441
 
          perror_plus("setenv");
1442
 
          _exit(EX_OSERR);
1443
 
        }
1444
 
        free(delaystring);
1445
 
        ret = execl(fullname, direntry->d_name, mode, NULL);
1446
 
        perror_plus("execl");
1447
 
      } else {
1448
 
        int status;
1449
 
        if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
1450
 
          perror_plus("waitpid");
1451
 
          free(fullname);
1452
 
          continue;
1453
 
        }
1454
 
        if(WIFEXITED(status)){
1455
 
          if(WEXITSTATUS(status) != 0){
1456
 
            fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
1457
 
                         " with status %d\n", direntry->d_name,
1458
 
                         WEXITSTATUS(status));
1459
 
            free(fullname);
1460
 
            continue;
1461
 
          }
1462
 
        } else if(WIFSIGNALED(status)){
1463
 
          fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
1464
 
                       " signal %d\n", direntry->d_name,
1465
 
                       WTERMSIG(status));
1466
 
          free(fullname);
1467
 
          continue;
1468
 
        } else {
1469
 
          fprintf_plus(stderr, "Warning: network hook \"%s\""
1470
 
                       " crashed\n", direntry->d_name);
1471
 
          free(fullname);
1472
 
          continue;
1473
 
        }
1474
 
      }
1475
 
      free(fullname);
1476
 
      if(debug){
1477
 
        fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
1478
 
                     direntry->d_name);
1479
 
      }
1480
 
    }
1481
 
    close(devnull);
1482
 
  }
1483
 
  return true;
1484
 
}
1485
 
 
1486
1264
int main(int argc, char *argv[]){
1487
1265
  AvahiSServiceBrowser *sb = NULL;
1488
1266
  int error;
1505
1283
  bool gnutls_initialized = false;
1506
1284
  bool gpgme_initialized = false;
1507
1285
  float delay = 2.5f;
1508
 
  double retry_interval = 10; /* 10s between trying a server and
1509
 
                                 retrying the same server again */
 
1286
  double retry_interval = 10; /* 10s between retrying a server and checking again*/
1510
1287
  
1511
1288
  struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
1512
1289
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
1570
1347
        .arg = "SECONDS",
1571
1348
        .doc = "Retry interval used when denied by the mandos server",
1572
1349
        .group = 2 },
1573
 
      { .name = "network-hook-dir", .key = 133,
1574
 
        .arg = "DIR",
1575
 
        .doc = "Directory where network hooks are located",
1576
 
        .group = 2 },
1577
1350
      /*
1578
1351
       * These reproduce what we would get without ARGP_NO_HELP
1579
1352
       */
1627
1400
        errno = 0;
1628
1401
        retry_interval = strtod(arg, &tmp);
1629
1402
        if(errno != 0 or tmp == arg or *tmp != '\0'
1630
 
           or (retry_interval * 1000) > INT_MAX
1631
 
           or retry_interval < 0){
 
1403
           or (retry_interval * 1000) > INT_MAX){
1632
1404
          argp_error(state, "Bad retry interval");
1633
1405
        }
1634
1406
        break;
1635
 
      case 133:                 /* --network-hook-dir */
1636
 
        hookdir = arg;
1637
 
        break;
1638
1407
        /*
1639
1408
         * These reproduce what we would get without ARGP_NO_HELP
1640
1409
         */
1646
1415
        argp_state_help(state, state->out_stream,
1647
1416
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1648
1417
      case 'V':                 /* --version */
1649
 
        fprintf_plus(state->out_stream,
1650
 
                     "Mandos plugin mandos-client: ");
1651
 
        fprintf_plus(state->out_stream, "%s\n", argp_program_version);
 
1418
        fprintf(state->out_stream, "%s\n", argp_program_version);
1652
1419
        exit(argp_err_exit_status);
1653
1420
        break;
1654
1421
      default:
1677
1444
      goto end;
1678
1445
    }
1679
1446
  }
1680
 
    
1681
 
  if(getuid() == 0){
1682
 
    /* Work around Debian bug #633582:
1683
 
       <http://bugs.debian.org/633582> */
1684
 
    struct stat st;
1685
 
    
1686
 
    /* Re-raise priviliges */
1687
 
    errno = 0;
1688
 
    ret = seteuid(0);
1689
 
    if(ret == -1){
1690
 
      perror_plus("seteuid");
1691
 
    }
1692
 
    
1693
 
    if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
1694
 
      int seckey_fd = open(seckey, O_RDONLY);
1695
 
      if(seckey_fd == -1){
1696
 
        perror_plus("open");
1697
 
      } else {
1698
 
        ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
1699
 
        if(ret == -1){
1700
 
          perror_plus("fstat");
1701
 
        } else {
1702
 
          if(S_ISREG(st.st_mode)
1703
 
             and st.st_uid == 0 and st.st_gid == 0){
1704
 
            ret = fchown(seckey_fd, uid, gid);
1705
 
            if(ret == -1){
1706
 
              perror_plus("fchown");
1707
 
            }
1708
 
          }
1709
 
        }
1710
 
        TEMP_FAILURE_RETRY(close(seckey_fd));
1711
 
      }
1712
 
    }
1713
 
    
1714
 
    if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
1715
 
      int pubkey_fd = open(pubkey, O_RDONLY);
1716
 
      if(pubkey_fd == -1){
1717
 
        perror_plus("open");
1718
 
      } else {
1719
 
        ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
1720
 
        if(ret == -1){
1721
 
          perror_plus("fstat");
1722
 
        } else {
1723
 
          if(S_ISREG(st.st_mode)
1724
 
             and st.st_uid == 0 and st.st_gid == 0){
1725
 
            ret = fchown(pubkey_fd, uid, gid);
1726
 
            if(ret == -1){
1727
 
              perror_plus("fchown");
1728
 
            }
1729
 
          }
1730
 
        }
1731
 
        TEMP_FAILURE_RETRY(close(pubkey_fd));
1732
 
      }
1733
 
    }
1734
 
    
1735
 
    /* Lower privileges */
1736
 
    errno = 0;
1737
 
    ret = seteuid(uid);
1738
 
    if(ret == -1){
1739
 
      perror_plus("seteuid");
1740
 
    }
1741
 
  }
1742
 
  
1743
 
  /* Run network hooks */
1744
 
  {
1745
 
    if(getuid() == 0){
1746
 
      /* Re-raise priviliges */
1747
 
      errno = 0;
1748
 
      ret = seteuid(0);
1749
 
      if(ret == -1){
1750
 
        perror_plus("seteuid");
1751
 
      }
1752
 
    }
1753
 
    if(not run_network_hooks("start", interface, delay)){
1754
 
      goto end;
1755
 
    }
1756
 
    if(getuid() == 0){
1757
 
      /* Lower privileges */
1758
 
      errno = 0;
1759
 
      ret = seteuid(uid);
1760
 
      if(ret == -1){
1761
 
        perror_plus("seteuid");
1762
 
      }
1763
 
    }
1764
 
  }
1765
1447
  
1766
1448
  if(not debug){
1767
1449
    avahi_set_log_function(empty_log);
1768
1450
  }
1769
 
  
 
1451
 
1770
1452
  if(interface[0] == '\0'){
1771
1453
    struct dirent **direntries;
1772
 
    /* First look for interfaces that are up */
1773
 
    ret = scandir(sys_class_net, &direntries, up_interface,
 
1454
    ret = scandir(sys_class_net, &direntries, good_interface,
1774
1455
                  alphasort);
1775
 
    if(ret == 0){
1776
 
      /* No up interfaces, look for any good interfaces */
1777
 
      free(direntries);
1778
 
      ret = scandir(sys_class_net, &direntries, good_interface,
1779
 
                    alphasort);
1780
 
    }
1781
1456
    if(ret >= 1){
1782
 
      /* Pick the first interface returned */
 
1457
      /* Pick the first good interface */
1783
1458
      interface = strdup(direntries[0]->d_name);
1784
1459
      if(debug){
1785
 
        fprintf_plus(stderr, "Using interface \"%s\"\n", interface);
 
1460
        fprintf(stderr, "Using interface \"%s\"\n", interface);
1786
1461
      }
1787
1462
      if(interface == NULL){
1788
1463
        perror_plus("malloc");
1793
1468
      free(direntries);
1794
1469
    } else {
1795
1470
      free(direntries);
1796
 
      fprintf_plus(stderr, "Could not find a network interface\n");
 
1471
      fprintf(stderr, "Could not find a network interface\n");
1797
1472
      exitcode = EXIT_FAILURE;
1798
1473
      goto end;
1799
1474
    }
1805
1480
  srand((unsigned int) time(NULL));
1806
1481
  mc.simple_poll = avahi_simple_poll_new();
1807
1482
  if(mc.simple_poll == NULL){
1808
 
    fprintf_plus(stderr,
1809
 
                 "Avahi: Failed to create simple poll object.\n");
 
1483
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
1810
1484
    exitcode = EX_UNAVAILABLE;
1811
1485
    goto end;
1812
1486
  }
1878
1552
  if(strcmp(interface, "none") != 0){
1879
1553
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1880
1554
    if(if_index == 0){
1881
 
      fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
 
1555
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
1882
1556
      exitcode = EX_UNAVAILABLE;
1883
1557
      goto end;
1884
1558
    }
1971
1645
        goto end;
1972
1646
      }
1973
1647
    }
1974
 
    /* Sleep checking until interface is running.
1975
 
       Check every 0.25s, up to total time of delay */
 
1648
    /* sleep checking until interface is running. Check every 0.25s, up to total time of delay */
1976
1649
    for(int i=0; i < delay * 4; i++){
1977
1650
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1978
1651
      if(ret == -1){
2004
1677
#endif  /* __linux__ */
2005
1678
    /* Lower privileges */
2006
1679
    errno = 0;
2007
 
    /* Lower privileges */
2008
 
    ret = seteuid(uid);
2009
 
    if(ret == -1){
2010
 
      perror_plus("seteuid");
 
1680
    if(take_down_interface){
 
1681
      /* Lower privileges */
 
1682
      ret = seteuid(uid);
 
1683
      if(ret == -1){
 
1684
        perror_plus("seteuid");
 
1685
      }
 
1686
    } else {
 
1687
      /* Lower privileges permanently */
 
1688
      ret = setuid(uid);
 
1689
      if(ret == -1){
 
1690
        perror_plus("setuid");
 
1691
      }
2011
1692
    }
2012
1693
  }
2013
1694
  
2017
1698
  
2018
1699
  ret = init_gnutls_global(pubkey, seckey);
2019
1700
  if(ret == -1){
2020
 
    fprintf_plus(stderr, "init_gnutls_global failed\n");
 
1701
    fprintf(stderr, "init_gnutls_global failed\n");
2021
1702
    exitcode = EX_UNAVAILABLE;
2022
1703
    goto end;
2023
1704
  } else {
2039
1720
  }
2040
1721
  
2041
1722
  if(not init_gpgme(pubkey, seckey, tempdir)){
2042
 
    fprintf_plus(stderr, "init_gpgme failed\n");
 
1723
    fprintf(stderr, "init_gpgme failed\n");
2043
1724
    exitcode = EX_UNAVAILABLE;
2044
1725
    goto end;
2045
1726
  } else {
2055
1736
    /* (Mainly meant for debugging) */
2056
1737
    char *address = strrchr(connect_to, ':');
2057
1738
    if(address == NULL){
2058
 
      fprintf_plus(stderr, "No colon in address\n");
 
1739
      fprintf(stderr, "No colon in address\n");
2059
1740
      exitcode = EX_USAGE;
2060
1741
      goto end;
2061
1742
    }
2069
1750
    tmpmax = strtoimax(address+1, &tmp, 10);
2070
1751
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
2071
1752
       or tmpmax != (uint16_t)tmpmax){
2072
 
      fprintf_plus(stderr, "Bad port number\n");
 
1753
      fprintf(stderr, "Bad port number\n");
2073
1754
      exitcode = EX_USAGE;
2074
1755
      goto end;
2075
1756
    }
2080
1761
    
2081
1762
    port = (uint16_t)tmpmax;
2082
1763
    *address = '\0';
 
1764
    address = connect_to;
2083
1765
    /* Colon in address indicates IPv6 */
2084
1766
    int af;
2085
 
    if(strchr(connect_to, ':') != NULL){
 
1767
    if(strchr(address, ':') != NULL){
2086
1768
      af = AF_INET6;
2087
 
      /* Accept [] around IPv6 address - see RFC 5952 */
2088
 
      if(connect_to[0] == '[' and address[-1] == ']')
2089
 
        {
2090
 
          connect_to++;
2091
 
          address[-1] = '\0';
2092
 
        }
2093
1769
    } else {
2094
1770
      af = AF_INET;
2095
1771
    }
2096
 
    address = connect_to;
2097
1772
    
2098
1773
    if(quit_now){
2099
1774
      goto end;
2100
1775
    }
2101
 
    
 
1776
 
2102
1777
    while(not quit_now){
2103
1778
      ret = start_mandos_communication(address, port, if_index, af);
2104
1779
      if(quit_now or ret == 0){
2105
1780
        break;
2106
1781
      }
2107
 
      if(debug){
2108
 
        fprintf_plus(stderr, "Retrying in %d seconds\n",
2109
 
                     (int)retry_interval);
2110
 
      }
2111
 
      sleep((int)retry_interval);
2112
 
    }
2113
 
    
 
1782
      sleep((int)retry_interval or 1);
 
1783
    };
 
1784
 
2114
1785
    if (not quit_now){
2115
1786
      exitcode = EXIT_SUCCESS;
2116
1787
    }
2117
 
    
 
1788
 
2118
1789
    goto end;
2119
1790
  }
2120
1791
  
2142
1813
  
2143
1814
  /* Check if creating the Avahi server object succeeded */
2144
1815
  if(mc.server == NULL){
2145
 
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
2146
 
                 avahi_strerror(error));
 
1816
    fprintf(stderr, "Failed to create Avahi server: %s\n",
 
1817
            avahi_strerror(error));
2147
1818
    exitcode = EX_UNAVAILABLE;
2148
1819
    goto end;
2149
1820
  }
2157
1828
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2158
1829
                                   NULL, 0, browse_callback, NULL);
2159
1830
  if(sb == NULL){
2160
 
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
2161
 
                 avahi_strerror(avahi_server_errno(mc.server)));
 
1831
    fprintf(stderr, "Failed to create service browser: %s\n",
 
1832
            avahi_strerror(avahi_server_errno(mc.server)));
2162
1833
    exitcode = EX_UNAVAILABLE;
2163
1834
    goto end;
2164
1835
  }
2170
1841
  /* Run the main loop */
2171
1842
  
2172
1843
  if(debug){
2173
 
    fprintf_plus(stderr, "Starting Avahi loop search\n");
 
1844
    fprintf(stderr, "Starting Avahi loop search\n");
2174
1845
  }
2175
1846
 
2176
 
  ret = avahi_loop_with_timeout(mc.simple_poll,
2177
 
                                (int)(retry_interval * 1000));
 
1847
  ret = avahi_loop_with_timeout(mc.simple_poll, (int)(retry_interval * 1000));
2178
1848
  if(debug){
2179
 
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
2180
 
                 (ret == 0) ? "successfully" : "with error");
 
1849
    fprintf(stderr, "avahi_loop_with_timeout exited %s\n",
 
1850
            (ret == 0) ? "successfully" : "with error");
2181
1851
  }
2182
1852
  
2183
1853
 end:
2184
1854
  
2185
1855
  if(debug){
2186
 
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
 
1856
    fprintf(stderr, "%s exiting\n", argv[0]);
2187
1857
  }
2188
1858
  
2189
1859
  /* Cleanup things */
2205
1875
  if(gpgme_initialized){
2206
1876
    gpgme_release(mc.ctx);
2207
1877
  }
2208
 
  
2209
 
  /* Cleans up the circular linked list of Mandos servers the client
2210
 
     has seen */
 
1878
 
 
1879
  /* cleans up the circular linked list of mandos servers the client has seen */
2211
1880
  if(mc.current_server != NULL){
2212
1881
    mc.current_server->prev->next = NULL;
2213
1882
    while(mc.current_server != NULL){
2217
1886
    }
2218
1887
  }
2219
1888
  
2220
 
  /* Re-raise priviliges */
2221
 
  {
2222
 
    if(getuid() == 0){
2223
 
      errno = 0;
2224
 
      ret = seteuid(0);
2225
 
      if(ret == -1){
2226
 
        perror_plus("seteuid");
2227
 
      }
 
1889
  /* Take down the network interface */
 
1890
  if(take_down_interface){
 
1891
    /* Re-raise priviliges */
 
1892
    errno = 0;
 
1893
    ret = seteuid(0);
 
1894
    if(ret == -1){
 
1895
      perror_plus("seteuid");
2228
1896
    }
2229
 
    
2230
 
    /* Run network hooks */
2231
 
    run_network_hooks("stop", interface, delay);
2232
 
    
2233
 
    /* Take down the network interface */
2234
 
    if(take_down_interface and geteuid() == 0){
 
1897
    if(geteuid() == 0){
2235
1898
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
2236
1899
      if(ret == -1){
2237
1900
        perror_plus("ioctl SIOCGIFFLAGS");
2238
 
      } else if(network.ifr_flags & IFF_UP){
 
1901
      } else if(network.ifr_flags & IFF_UP) {
2239
1902
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
2240
1903
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
2241
1904
        if(ret == -1){
2246
1909
      if(ret == -1){
2247
1910
        perror_plus("close");
2248
1911
      }
2249
 
    }
2250
 
  }
2251
 
  if(getuid() == 0){
2252
 
    /* Lower privileges permanently */
2253
 
    errno = 0;
2254
 
    ret = setuid(uid);
2255
 
    if(ret == -1){
2256
 
      perror_plus("setuid");
 
1912
      /* Lower privileges permanently */
 
1913
      errno = 0;
 
1914
      ret = setuid(uid);
 
1915
      if(ret == -1){
 
1916
        perror_plus("setuid");
 
1917
      }
2257
1918
    }
2258
1919
  }
2259
1920
  
2261
1922
  if(tempdir_created){
2262
1923
    struct dirent **direntries = NULL;
2263
1924
    struct dirent *direntry = NULL;
2264
 
    int numentries = scandir(tempdir, &direntries, notdotentries,
2265
 
                             alphasort);
2266
 
    if (numentries > 0){
2267
 
      for(int i = 0; i < numentries; i++){
 
1925
    ret = scandir(tempdir, &direntries, notdotentries, alphasort);
 
1926
    if (ret > 0){
 
1927
      for(int i = 0; i < ret; i++){
2268
1928
        direntry = direntries[i];
2269
1929
        char *fullname = NULL;
2270
1930
        ret = asprintf(&fullname, "%s/%s", tempdir,
2275
1935
        }
2276
1936
        ret = remove(fullname);
2277
1937
        if(ret == -1){
2278
 
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
2279
 
                       strerror(errno));
 
1938
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
 
1939
                  strerror(errno));
2280
1940
        }
2281
1941
        free(fullname);
2282
1942
      }
2283
1943
    }
2284
1944
 
2285
 
    /* need to clean even if 0 because man page doesn't specify */
 
1945
    /* need to be cleaned even if ret == 0 because man page dont specify */
2286
1946
    free(direntries);
2287
 
    if (numentries == -1){
 
1947
    if (ret == -1){
2288
1948
      perror_plus("scandir");
2289
1949
    }
2290
1950
    ret = rmdir(tempdir);