/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: 2012-06-09 23:41:07 UTC
  • mto: This revision was merged to the branch mainline in revision 596.
  • Revision ID: teddy@recompile.se-20120609234107-vm6zilzz0y6aihsm
* plugins.d/mandos-client.c (raise_privileges,
  raise_privileges_permanently, lower_privileges): Return error_t and
                                                   save old errno
                                                   before calling any
                                                   other function.

Show diffs side-by-side

added added

removed removed

Lines of Context:
9
9
 * "browse_callback", and parts of "main".
10
10
 * 
11
11
 * Everything else is
12
 
 * Copyright © 2008,2009 Teddy Hogeborn
13
 
 * Copyright © 2008,2009 Björn Påhlsson
 
12
 * Copyright © 2008-2012 Teddy Hogeborn
 
13
 * Copyright © 2008-2012 Björn Påhlsson
14
14
 * 
15
15
 * This program is free software: you can redistribute it and/or
16
16
 * modify it under the terms of the GNU General Public License as
26
26
 * along with this program.  If not, see
27
27
 * <http://www.gnu.org/licenses/>.
28
28
 * 
29
 
 * Contact the authors at <mandos@fukt.bsnet.se>.
 
29
 * Contact the authors at <mandos@recompile.se>.
30
30
 */
31
31
 
32
32
/* Needed by GPGME, specifically gpgme_data_seek() */
41
41
 
42
42
#include <stdio.h>              /* fprintf(), stderr, fwrite(),
43
43
                                   stdout, ferror(), remove() */
44
 
#include <stdint.h>             /* uint16_t, uint32_t */
 
44
#include <stdint.h>             /* uint16_t, uint32_t, intptr_t */
45
45
#include <stddef.h>             /* NULL, size_t, ssize_t */
46
 
#include <stdlib.h>             /* free(), EXIT_SUCCESS, EXIT_FAILURE,
47
 
                                   srand(), strtof(), abort() */
 
46
#include <stdlib.h>             /* free(), EXIT_SUCCESS, srand(),
 
47
                                   strtof(), abort() */
48
48
#include <stdbool.h>            /* bool, false, true */
49
49
#include <string.h>             /* memset(), strcmp(), strlen(),
50
50
                                   strerror(), asprintf(), strcpy() */
53
53
                                   sockaddr_in6, PF_INET6,
54
54
                                   SOCK_STREAM, uid_t, gid_t, open(),
55
55
                                   opendir(), DIR */
56
 
#include <sys/stat.h>           /* open() */
 
56
#include <sys/stat.h>           /* open(), S_ISREG */
57
57
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
58
58
                                   inet_pton(), connect() */
59
59
#include <fcntl.h>              /* open() */
62
62
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
63
63
                                   strtoimax() */
64
64
#include <assert.h>             /* assert() */
65
 
#include <errno.h>              /* perror(), errno */
66
 
#include <time.h>               /* nanosleep(), time() */
 
65
#include <errno.h>              /* perror(), errno,
 
66
                                   program_invocation_short_name */
 
67
#include <time.h>               /* nanosleep(), time(), sleep() */
67
68
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
68
69
                                   SIOCSIFFLAGS, if_indextoname(),
69
70
                                   if_nametoindex(), IF_NAMESIZE */
72
73
                                */
73
74
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
74
75
                                   getuid(), getgid(), seteuid(),
75
 
                                   setgid(), pause() */
76
 
#include <arpa/inet.h>          /* inet_pton(), htons */
 
76
                                   setgid(), pause(), _exit() */
 
77
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
77
78
#include <iso646.h>             /* not, or, and */
78
79
#include <argp.h>               /* struct argp_option, error_t, struct
79
80
                                   argp_state, struct argp,
82
83
#include <signal.h>             /* sigemptyset(), sigaddset(),
83
84
                                   sigaction(), SIGTERM, sig_atomic_t,
84
85
                                   raise() */
 
86
#include <sysexits.h>           /* EX_OSERR, EX_USAGE, EX_UNAVAILABLE,
 
87
                                   EX_NOHOST, EX_IOERR, EX_PROTOCOL */
 
88
#include <sys/wait.h>           /* waitpid(), WIFEXITED(),
 
89
                                   WEXITSTATUS(), WTERMSIG() */
 
90
#include <grp.h>                /* setgroups() */
85
91
 
86
92
#ifdef __linux__
87
93
#include <sys/klog.h>           /* klogctl() */
105
111
                                   init_gnutls_session(),
106
112
                                   GNUTLS_* */
107
113
#include <gnutls/openpgp.h>
108
 
                          /* gnutls_certificate_set_openpgp_key_file(),
109
 
                                   GNUTLS_OPENPGP_FMT_BASE64 */
 
114
                         /* gnutls_certificate_set_openpgp_key_file(),
 
115
                            GNUTLS_OPENPGP_FMT_BASE64 */
110
116
 
111
117
/* GPGME */
112
118
#include <gpgme.h>              /* All GPGME types, constants and
120
126
#define PATHDIR "/conf/conf.d/mandos"
121
127
#define SECKEY "seckey.txt"
122
128
#define PUBKEY "pubkey.txt"
 
129
#define HOOKDIR "/lib/mandos/network-hooks.d"
123
130
 
124
131
bool debug = false;
125
132
static const char mandos_protocol_version[] = "1";
126
133
const char *argp_program_version = "mandos-client " VERSION;
127
 
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
 
134
const char *argp_program_bug_address = "<mandos@recompile.se>";
 
135
static const char sys_class_net[] = "/sys/class/net";
 
136
char *connect_to = NULL;
 
137
const char *hookdir = HOOKDIR;
 
138
uid_t uid = 65534;
 
139
gid_t gid = 65534;
 
140
 
 
141
/* Doubly linked list that need to be circularly linked when used */
 
142
typedef struct server{
 
143
  const char *ip;
 
144
  uint16_t port;
 
145
  AvahiIfIndex if_index;
 
146
  int af;
 
147
  struct timespec last_seen;
 
148
  struct server *next;
 
149
  struct server *prev;
 
150
} server;
128
151
 
129
152
/* Used for passing in values through the Avahi callback functions */
130
153
typedef struct {
135
158
  gnutls_dh_params_t dh_params;
136
159
  const char *priority;
137
160
  gpgme_ctx_t ctx;
 
161
  server *current_server;
138
162
} mandos_context;
139
163
 
140
164
/* global context so signal handler can reach it*/
141
165
mandos_context mc = { .simple_poll = NULL, .server = NULL,
142
166
                      .dh_bits = 1024, .priority = "SECURE256"
143
 
                      ":!CTYPE-X.509:+CTYPE-OPENPGP" };
 
167
                      ":!CTYPE-X.509:+CTYPE-OPENPGP",
 
168
                      .current_server = NULL };
144
169
 
145
170
sig_atomic_t quit_now = 0;
146
171
int signal_received = 0;
147
172
 
 
173
/* Function to use when printing errors */
 
174
void perror_plus(const char *print_text){
 
175
  int e = errno;
 
176
  fprintf(stderr, "Mandos plugin %s: ",
 
177
          program_invocation_short_name);
 
178
  errno = e;
 
179
  perror(print_text);
 
180
}
 
181
 
 
182
__attribute__((format (gnu_printf, 2, 3)))
 
183
int fprintf_plus(FILE *stream, const char *format, ...){
 
184
  va_list ap;
 
185
  va_start (ap, format);
 
186
  
 
187
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ",
 
188
                             program_invocation_short_name));
 
189
  return TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
 
190
}
 
191
 
148
192
/*
149
193
 * Make additional room in "buffer" for at least BUFFER_SIZE more
150
194
 * bytes. "buffer_capacity" is how much is currently allocated,
151
195
 * "buffer_length" is how much is already used.
152
196
 */
153
197
size_t incbuffer(char **buffer, size_t buffer_length,
154
 
                  size_t buffer_capacity){
 
198
                 size_t buffer_capacity){
155
199
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
156
200
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
157
201
    if(buffer == NULL){
162
206
  return buffer_capacity;
163
207
}
164
208
 
 
209
/* Add server to set of servers to retry periodically */
 
210
bool add_server(const char *ip, uint16_t port, AvahiIfIndex if_index,
 
211
                int af){
 
212
  int ret;
 
213
  server *new_server = malloc(sizeof(server));
 
214
  if(new_server == NULL){
 
215
    perror_plus("malloc");
 
216
    return false;
 
217
  }
 
218
  *new_server = (server){ .ip = strdup(ip),
 
219
                          .port = port,
 
220
                          .if_index = if_index,
 
221
                          .af = af };
 
222
  if(new_server->ip == NULL){
 
223
    perror_plus("strdup");
 
224
    return false;
 
225
  }
 
226
  /* Special case of first server */
 
227
  if (mc.current_server == NULL){
 
228
    new_server->next = new_server;
 
229
    new_server->prev = new_server;
 
230
    mc.current_server = new_server;
 
231
  /* Place the new server last in the list */
 
232
  } else {
 
233
    new_server->next = mc.current_server;
 
234
    new_server->prev = mc.current_server->prev;
 
235
    new_server->prev->next = new_server;
 
236
    mc.current_server->prev = new_server;
 
237
  }
 
238
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
 
239
  if(ret == -1){
 
240
    perror_plus("clock_gettime");
 
241
    return false;
 
242
  }
 
243
  return true;
 
244
}
 
245
 
165
246
/* 
166
247
 * Initialize GPGME.
167
248
 */
168
 
static bool init_gpgme(const char *seckey,
169
 
                       const char *pubkey, const char *tempdir){
 
249
static bool init_gpgme(const char *seckey, const char *pubkey,
 
250
                       const char *tempdir){
170
251
  gpgme_error_t rc;
171
252
  gpgme_engine_info_t engine_info;
172
253
  
181
262
    
182
263
    fd = (int)TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
183
264
    if(fd == -1){
184
 
      perror("open");
 
265
      perror_plus("open");
185
266
      return false;
186
267
    }
187
268
    
188
269
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
189
270
    if(rc != GPG_ERR_NO_ERROR){
190
 
      fprintf(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
191
 
              gpgme_strsource(rc), gpgme_strerror(rc));
 
271
      fprintf_plus(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
 
272
                   gpgme_strsource(rc), gpgme_strerror(rc));
192
273
      return false;
193
274
    }
194
275
    
195
276
    rc = gpgme_op_import(mc.ctx, pgp_data);
196
277
    if(rc != GPG_ERR_NO_ERROR){
197
 
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
198
 
              gpgme_strsource(rc), gpgme_strerror(rc));
 
278
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
 
279
                   gpgme_strsource(rc), gpgme_strerror(rc));
199
280
      return false;
200
281
    }
201
282
    
202
283
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
203
284
    if(ret == -1){
204
 
      perror("close");
 
285
      perror_plus("close");
205
286
    }
206
287
    gpgme_data_release(pgp_data);
207
288
    return true;
208
289
  }
209
290
  
210
291
  if(debug){
211
 
    fprintf(stderr, "Initializing GPGME\n");
 
292
    fprintf_plus(stderr, "Initializing GPGME\n");
212
293
  }
213
294
  
214
295
  /* Init GPGME */
215
296
  gpgme_check_version(NULL);
216
297
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
217
298
  if(rc != GPG_ERR_NO_ERROR){
218
 
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
219
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
299
    fprintf_plus(stderr, "bad gpgme_engine_check_version: %s: %s\n",
 
300
                 gpgme_strsource(rc), gpgme_strerror(rc));
220
301
    return false;
221
302
  }
222
303
  
223
 
    /* Set GPGME home directory for the OpenPGP engine only */
 
304
  /* Set GPGME home directory for the OpenPGP engine only */
224
305
  rc = gpgme_get_engine_info(&engine_info);
225
306
  if(rc != GPG_ERR_NO_ERROR){
226
 
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
227
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
307
    fprintf_plus(stderr, "bad gpgme_get_engine_info: %s: %s\n",
 
308
                 gpgme_strsource(rc), gpgme_strerror(rc));
228
309
    return false;
229
310
  }
230
311
  while(engine_info != NULL){
236
317
    engine_info = engine_info->next;
237
318
  }
238
319
  if(engine_info == NULL){
239
 
    fprintf(stderr, "Could not set GPGME home dir to %s\n", tempdir);
 
320
    fprintf_plus(stderr, "Could not set GPGME home dir to %s\n",
 
321
                 tempdir);
240
322
    return false;
241
323
  }
242
324
  
243
325
  /* Create new GPGME "context" */
244
326
  rc = gpgme_new(&(mc.ctx));
245
327
  if(rc != GPG_ERR_NO_ERROR){
246
 
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
247
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
328
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
 
329
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
 
330
                 gpgme_strerror(rc));
248
331
    return false;
249
332
  }
250
333
  
269
352
  ssize_t plaintext_length = 0;
270
353
  
271
354
  if(debug){
272
 
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
 
355
    fprintf_plus(stderr, "Trying to decrypt OpenPGP data\n");
273
356
  }
274
357
  
275
358
  /* Create new GPGME data buffer from memory cryptotext */
276
359
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
277
360
                               0);
278
361
  if(rc != GPG_ERR_NO_ERROR){
279
 
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
280
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
362
    fprintf_plus(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
 
363
                 gpgme_strsource(rc), gpgme_strerror(rc));
281
364
    return -1;
282
365
  }
283
366
  
284
367
  /* Create new empty GPGME data buffer for the plaintext */
285
368
  rc = gpgme_data_new(&dh_plain);
286
369
  if(rc != GPG_ERR_NO_ERROR){
287
 
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
288
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
370
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
 
371
                 "bad gpgme_data_new: %s: %s\n",
 
372
                 gpgme_strsource(rc), gpgme_strerror(rc));
289
373
    gpgme_data_release(dh_crypto);
290
374
    return -1;
291
375
  }
294
378
     data buffer */
295
379
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
296
380
  if(rc != GPG_ERR_NO_ERROR){
297
 
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
298
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
381
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
 
382
                 gpgme_strsource(rc), gpgme_strerror(rc));
299
383
    plaintext_length = -1;
300
384
    if(debug){
301
385
      gpgme_decrypt_result_t result;
302
386
      result = gpgme_op_decrypt_result(mc.ctx);
303
387
      if(result == NULL){
304
 
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
 
388
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
305
389
      } else {
306
 
        fprintf(stderr, "Unsupported algorithm: %s\n",
307
 
                result->unsupported_algorithm);
308
 
        fprintf(stderr, "Wrong key usage: %u\n",
309
 
                result->wrong_key_usage);
 
390
        fprintf_plus(stderr, "Unsupported algorithm: %s\n",
 
391
                     result->unsupported_algorithm);
 
392
        fprintf_plus(stderr, "Wrong key usage: %u\n",
 
393
                     result->wrong_key_usage);
310
394
        if(result->file_name != NULL){
311
 
          fprintf(stderr, "File name: %s\n", result->file_name);
 
395
          fprintf_plus(stderr, "File name: %s\n", result->file_name);
312
396
        }
313
397
        gpgme_recipient_t recipient;
314
398
        recipient = result->recipients;
315
399
        while(recipient != NULL){
316
 
          fprintf(stderr, "Public key algorithm: %s\n",
317
 
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
318
 
          fprintf(stderr, "Key ID: %s\n", recipient->keyid);
319
 
          fprintf(stderr, "Secret key available: %s\n",
320
 
                  recipient->status == GPG_ERR_NO_SECKEY
321
 
                  ? "No" : "Yes");
 
400
          fprintf_plus(stderr, "Public key algorithm: %s\n",
 
401
                       gpgme_pubkey_algo_name
 
402
                       (recipient->pubkey_algo));
 
403
          fprintf_plus(stderr, "Key ID: %s\n", recipient->keyid);
 
404
          fprintf_plus(stderr, "Secret key available: %s\n",
 
405
                       recipient->status == GPG_ERR_NO_SECKEY
 
406
                       ? "No" : "Yes");
322
407
          recipient = recipient->next;
323
408
        }
324
409
      }
327
412
  }
328
413
  
329
414
  if(debug){
330
 
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
 
415
    fprintf_plus(stderr, "Decryption of OpenPGP data succeeded\n");
331
416
  }
332
417
  
333
418
  /* Seek back to the beginning of the GPGME plaintext data buffer */
334
419
  if(gpgme_data_seek(dh_plain, (off_t)0, SEEK_SET) == -1){
335
 
    perror("gpgme_data_seek");
 
420
    perror_plus("gpgme_data_seek");
336
421
    plaintext_length = -1;
337
422
    goto decrypt_end;
338
423
  }
340
425
  *plaintext = NULL;
341
426
  while(true){
342
427
    plaintext_capacity = incbuffer(plaintext,
343
 
                                      (size_t)plaintext_length,
344
 
                                      plaintext_capacity);
 
428
                                   (size_t)plaintext_length,
 
429
                                   plaintext_capacity);
345
430
    if(plaintext_capacity == 0){
346
 
        perror("incbuffer");
347
 
        plaintext_length = -1;
348
 
        goto decrypt_end;
 
431
      perror_plus("incbuffer");
 
432
      plaintext_length = -1;
 
433
      goto decrypt_end;
349
434
    }
350
435
    
351
436
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
356
441
      break;
357
442
    }
358
443
    if(ret < 0){
359
 
      perror("gpgme_data_read");
 
444
      perror_plus("gpgme_data_read");
360
445
      plaintext_length = -1;
361
446
      goto decrypt_end;
362
447
    }
364
449
  }
365
450
  
366
451
  if(debug){
367
 
    fprintf(stderr, "Decrypted password is: ");
 
452
    fprintf_plus(stderr, "Decrypted password is: ");
368
453
    for(ssize_t i = 0; i < plaintext_length; i++){
369
454
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
370
455
    }
392
477
/* GnuTLS log function callback */
393
478
static void debuggnutls(__attribute__((unused)) int level,
394
479
                        const char* string){
395
 
  fprintf(stderr, "GnuTLS: %s", string);
 
480
  fprintf_plus(stderr, "GnuTLS: %s", string);
396
481
}
397
482
 
398
483
static int init_gnutls_global(const char *pubkeyfilename,
400
485
  int ret;
401
486
  
402
487
  if(debug){
403
 
    fprintf(stderr, "Initializing GnuTLS\n");
 
488
    fprintf_plus(stderr, "Initializing GnuTLS\n");
404
489
  }
405
490
  
406
491
  ret = gnutls_global_init();
407
492
  if(ret != GNUTLS_E_SUCCESS){
408
 
    fprintf(stderr, "GnuTLS global_init: %s\n",
409
 
            safer_gnutls_strerror(ret));
 
493
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
 
494
                 safer_gnutls_strerror(ret));
410
495
    return -1;
411
496
  }
412
497
  
419
504
  }
420
505
  
421
506
  /* OpenPGP credentials */
422
 
  gnutls_certificate_allocate_credentials(&mc.cred);
 
507
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
423
508
  if(ret != GNUTLS_E_SUCCESS){
424
 
    fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning
425
 
                                                    from
426
 
                                                    -Wunreachable-code
427
 
                                                 */
428
 
            safer_gnutls_strerror(ret));
 
509
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
 
510
                 safer_gnutls_strerror(ret));
429
511
    gnutls_global_deinit();
430
512
    return -1;
431
513
  }
432
514
  
433
515
  if(debug){
434
 
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
435
 
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
436
 
            seckeyfilename);
 
516
    fprintf_plus(stderr, "Attempting to use OpenPGP public key %s and"
 
517
                 " secret key %s as GnuTLS credentials\n",
 
518
                 pubkeyfilename,
 
519
                 seckeyfilename);
437
520
  }
438
521
  
439
522
  ret = gnutls_certificate_set_openpgp_key_file
440
523
    (mc.cred, pubkeyfilename, seckeyfilename,
441
524
     GNUTLS_OPENPGP_FMT_BASE64);
442
525
  if(ret != GNUTLS_E_SUCCESS){
443
 
    fprintf(stderr,
444
 
            "Error[%d] while reading the OpenPGP key pair ('%s',"
445
 
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
446
 
    fprintf(stderr, "The GnuTLS error is: %s\n",
447
 
            safer_gnutls_strerror(ret));
 
526
    fprintf_plus(stderr,
 
527
                 "Error[%d] while reading the OpenPGP key pair ('%s',"
 
528
                 " '%s')\n", ret, pubkeyfilename, seckeyfilename);
 
529
    fprintf_plus(stderr, "The GnuTLS error is: %s\n",
 
530
                 safer_gnutls_strerror(ret));
448
531
    goto globalfail;
449
532
  }
450
533
  
451
534
  /* GnuTLS server initialization */
452
535
  ret = gnutls_dh_params_init(&mc.dh_params);
453
536
  if(ret != GNUTLS_E_SUCCESS){
454
 
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
455
 
            " %s\n", safer_gnutls_strerror(ret));
 
537
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
 
538
                 " initialization: %s\n",
 
539
                 safer_gnutls_strerror(ret));
456
540
    goto globalfail;
457
541
  }
458
542
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
459
543
  if(ret != GNUTLS_E_SUCCESS){
460
 
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
461
 
            safer_gnutls_strerror(ret));
 
544
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
 
545
                 safer_gnutls_strerror(ret));
462
546
    goto globalfail;
463
547
  }
464
548
  
484
568
    }
485
569
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
486
570
  if(ret != GNUTLS_E_SUCCESS){
487
 
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
488
 
            safer_gnutls_strerror(ret));
 
571
    fprintf_plus(stderr,
 
572
                 "Error in GnuTLS session initialization: %s\n",
 
573
                 safer_gnutls_strerror(ret));
489
574
  }
490
575
  
491
576
  {
498
583
      }
499
584
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
500
585
    if(ret != GNUTLS_E_SUCCESS){
501
 
      fprintf(stderr, "Syntax error at: %s\n", err);
502
 
      fprintf(stderr, "GnuTLS error: %s\n",
503
 
              safer_gnutls_strerror(ret));
 
586
      fprintf_plus(stderr, "Syntax error at: %s\n", err);
 
587
      fprintf_plus(stderr, "GnuTLS error: %s\n",
 
588
                   safer_gnutls_strerror(ret));
504
589
      gnutls_deinit(*session);
505
590
      return -1;
506
591
    }
515
600
    }
516
601
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
517
602
  if(ret != GNUTLS_E_SUCCESS){
518
 
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
519
 
            safer_gnutls_strerror(ret));
 
603
    fprintf_plus(stderr, "Error setting GnuTLS credentials: %s\n",
 
604
                 safer_gnutls_strerror(ret));
520
605
    gnutls_deinit(*session);
521
606
    return -1;
522
607
  }
552
637
  gnutls_session_t session;
553
638
  int pf;                       /* Protocol family */
554
639
  
 
640
  errno = 0;
 
641
  
555
642
  if(quit_now){
 
643
    errno = EINTR;
556
644
    return -1;
557
645
  }
558
646
  
564
652
    pf = PF_INET;
565
653
    break;
566
654
  default:
567
 
    fprintf(stderr, "Bad address family: %d\n", af);
 
655
    fprintf_plus(stderr, "Bad address family: %d\n", af);
 
656
    errno = EINVAL;
568
657
    return -1;
569
658
  }
570
659
  
574
663
  }
575
664
  
576
665
  if(debug){
577
 
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
578
 
            "\n", ip, port);
 
666
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
 
667
                 PRIu16 "\n", ip, port);
579
668
  }
580
669
  
581
670
  tcp_sd = socket(pf, SOCK_STREAM, 0);
582
671
  if(tcp_sd < 0){
583
 
    perror("socket");
 
672
    int e = errno;
 
673
    perror_plus("socket");
 
674
    errno = e;
584
675
    goto mandos_end;
585
676
  }
586
677
  
587
678
  if(quit_now){
 
679
    errno = EINTR;
588
680
    goto mandos_end;
589
681
  }
590
682
  
597
689
    ret = inet_pton(af, ip, &to.in.sin_addr);
598
690
  }
599
691
  if(ret < 0 ){
600
 
    perror("inet_pton");
 
692
    int e = errno;
 
693
    perror_plus("inet_pton");
 
694
    errno = e;
601
695
    goto mandos_end;
602
696
  }
603
697
  if(ret == 0){
604
 
    fprintf(stderr, "Bad address: %s\n", ip);
 
698
    int e = errno;
 
699
    fprintf_plus(stderr, "Bad address: %s\n", ip);
 
700
    errno = e;
605
701
    goto mandos_end;
606
702
  }
607
703
  if(af == AF_INET6){
611
707
    
612
708
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
613
709
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
614
 
                              -Wunreachable-code*/
 
710
                                -Wunreachable-code*/
615
711
      if(if_index == AVAHI_IF_UNSPEC){
616
 
        fprintf(stderr, "An IPv6 link-local address is incomplete"
617
 
                " without a network interface\n");
 
712
        fprintf_plus(stderr, "An IPv6 link-local address is"
 
713
                     " incomplete without a network interface\n");
 
714
        errno = EINVAL;
618
715
        goto mandos_end;
619
716
      }
620
717
      /* Set the network interface number as scope */
627
724
  }
628
725
  
629
726
  if(quit_now){
 
727
    errno = EINTR;
630
728
    goto mandos_end;
631
729
  }
632
730
  
634
732
    if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
635
733
      char interface[IF_NAMESIZE];
636
734
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
637
 
        perror("if_indextoname");
 
735
        perror_plus("if_indextoname");
638
736
      } else {
639
 
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
640
 
                ip, interface, port);
 
737
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIu16
 
738
                     "\n", ip, interface, port);
641
739
      }
642
740
    } else {
643
 
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
644
 
              port);
 
741
      fprintf_plus(stderr, "Connection to: %s, port %" PRIu16 "\n",
 
742
                   ip, port);
645
743
    }
646
744
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
647
745
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
654
752
                        sizeof(addrstr));
655
753
    }
656
754
    if(pcret == NULL){
657
 
      perror("inet_ntop");
 
755
      perror_plus("inet_ntop");
658
756
    } else {
659
757
      if(strcmp(addrstr, ip) != 0){
660
 
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
 
758
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
661
759
      }
662
760
    }
663
761
  }
664
762
  
665
763
  if(quit_now){
 
764
    errno = EINTR;
666
765
    goto mandos_end;
667
766
  }
668
767
  
672
771
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
673
772
  }
674
773
  if(ret < 0){
675
 
    perror("connect");
 
774
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
 
775
      int e = errno;
 
776
      perror_plus("connect");
 
777
      errno = e;
 
778
    }
676
779
    goto mandos_end;
677
780
  }
678
781
  
679
782
  if(quit_now){
 
783
    errno = EINTR;
680
784
    goto mandos_end;
681
785
  }
682
786
  
685
789
  while(true){
686
790
    size_t out_size = strlen(out);
687
791
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
688
 
                                   out_size - written));
 
792
                                        out_size - written));
689
793
    if(ret == -1){
690
 
      perror("write");
 
794
      int e = errno;
 
795
      perror_plus("write");
 
796
      errno = e;
691
797
      goto mandos_end;
692
798
    }
693
799
    written += (size_t)ret;
703
809
    }
704
810
  
705
811
    if(quit_now){
 
812
      errno = EINTR;
706
813
      goto mandos_end;
707
814
    }
708
815
  }
709
816
  
710
817
  if(debug){
711
 
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
 
818
    fprintf_plus(stderr, "Establishing TLS session with %s\n", ip);
712
819
  }
713
820
  
714
821
  if(quit_now){
 
822
    errno = EINTR;
715
823
    goto mandos_end;
716
824
  }
717
825
  
718
 
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
 
826
  /* This casting via intptr_t is to eliminate warning about casting
 
827
     an int to a pointer type.  This is exactly how the GnuTLS Guile
 
828
     function "set-session-transport-fd!" does it. */
 
829
  gnutls_transport_set_ptr(session,
 
830
                           (gnutls_transport_ptr_t)(intptr_t)tcp_sd);
719
831
  
720
832
  if(quit_now){
 
833
    errno = EINTR;
721
834
    goto mandos_end;
722
835
  }
723
836
  
724
837
  do {
725
838
    ret = gnutls_handshake(session);
726
839
    if(quit_now){
 
840
      errno = EINTR;
727
841
      goto mandos_end;
728
842
    }
729
843
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
730
844
  
731
845
  if(ret != GNUTLS_E_SUCCESS){
732
846
    if(debug){
733
 
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
 
847
      fprintf_plus(stderr, "*** GnuTLS Handshake failed ***\n");
734
848
      gnutls_perror(ret);
735
849
    }
 
850
    errno = EPROTO;
736
851
    goto mandos_end;
737
852
  }
738
853
  
739
854
  /* Read OpenPGP packet that contains the wanted password */
740
855
  
741
856
  if(debug){
742
 
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
743
 
            ip);
 
857
    fprintf_plus(stderr, "Retrieving OpenPGP encrypted password from"
 
858
                 " %s\n", ip);
744
859
  }
745
860
  
746
861
  while(true){
747
862
    
748
863
    if(quit_now){
 
864
      errno = EINTR;
749
865
      goto mandos_end;
750
866
    }
751
867
    
752
868
    buffer_capacity = incbuffer(&buffer, buffer_length,
753
 
                                   buffer_capacity);
 
869
                                buffer_capacity);
754
870
    if(buffer_capacity == 0){
755
 
      perror("incbuffer");
 
871
      int e = errno;
 
872
      perror_plus("incbuffer");
 
873
      errno = e;
756
874
      goto mandos_end;
757
875
    }
758
876
    
759
877
    if(quit_now){
 
878
      errno = EINTR;
760
879
      goto mandos_end;
761
880
    }
762
881
    
775
894
          ret = gnutls_handshake(session);
776
895
          
777
896
          if(quit_now){
 
897
            errno = EINTR;
778
898
            goto mandos_end;
779
899
          }
780
900
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
781
901
        if(ret < 0){
782
 
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
 
902
          fprintf_plus(stderr, "*** GnuTLS Re-handshake failed "
 
903
                       "***\n");
783
904
          gnutls_perror(ret);
 
905
          errno = EPROTO;
784
906
          goto mandos_end;
785
907
        }
786
908
        break;
787
909
      default:
788
 
        fprintf(stderr, "Unknown error while reading data from"
789
 
                " encrypted session with Mandos server\n");
 
910
        fprintf_plus(stderr, "Unknown error while reading data from"
 
911
                     " encrypted session with Mandos server\n");
790
912
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
 
913
        errno = EIO;
791
914
        goto mandos_end;
792
915
      }
793
916
    } else {
796
919
  }
797
920
  
798
921
  if(debug){
799
 
    fprintf(stderr, "Closing TLS session\n");
 
922
    fprintf_plus(stderr, "Closing TLS session\n");
800
923
  }
801
924
  
802
925
  if(quit_now){
 
926
    errno = EINTR;
803
927
    goto mandos_end;
804
928
  }
805
929
  
806
930
  do {
807
931
    ret = gnutls_bye(session, GNUTLS_SHUT_RDWR);
808
932
    if(quit_now){
 
933
      errno = EINTR;
809
934
      goto mandos_end;
810
935
    }
811
936
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
812
937
  
813
938
  if(buffer_length > 0){
814
939
    ssize_t decrypted_buffer_size;
815
 
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
816
 
                                               buffer_length,
 
940
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
817
941
                                               &decrypted_buffer);
818
942
    if(decrypted_buffer_size >= 0){
819
943
      
820
944
      written = 0;
821
945
      while(written < (size_t) decrypted_buffer_size){
822
946
        if(quit_now){
 
947
          errno = EINTR;
823
948
          goto mandos_end;
824
949
        }
825
950
        
827
952
                          (size_t)decrypted_buffer_size - written,
828
953
                          stdout);
829
954
        if(ret == 0 and ferror(stdout)){
 
955
          int e = errno;
830
956
          if(debug){
831
 
            fprintf(stderr, "Error writing encrypted data: %s\n",
832
 
                    strerror(errno));
 
957
            fprintf_plus(stderr, "Error writing encrypted data: %s\n",
 
958
                         strerror(errno));
833
959
          }
 
960
          errno = e;
834
961
          goto mandos_end;
835
962
        }
836
963
        written += (size_t)ret;
842
969
  /* Shutdown procedure */
843
970
  
844
971
 mandos_end:
845
 
  free(decrypted_buffer);
846
 
  free(buffer);
847
 
  if(tcp_sd >= 0){
848
 
    ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
849
 
  }
850
 
  if(ret == -1){
851
 
    perror("close");
852
 
  }
853
 
  gnutls_deinit(session);
854
 
  if(quit_now){
855
 
    retval = -1;
 
972
  {
 
973
    int e = errno;
 
974
    free(decrypted_buffer);
 
975
    free(buffer);
 
976
    if(tcp_sd >= 0){
 
977
      ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
 
978
    }
 
979
    if(ret == -1){
 
980
      if(e == 0){
 
981
        e = errno;
 
982
      }
 
983
      perror_plus("close");
 
984
    }
 
985
    gnutls_deinit(session);
 
986
    errno = e;
 
987
    if(quit_now){
 
988
      errno = EINTR;
 
989
      retval = -1;
 
990
    }
856
991
  }
857
992
  return retval;
858
993
}
883
1018
  switch(event){
884
1019
  default:
885
1020
  case AVAHI_RESOLVER_FAILURE:
886
 
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
887
 
            " of type '%s' in domain '%s': %s\n", name, type, domain,
888
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
1021
    fprintf_plus(stderr, "(Avahi Resolver) Failed to resolve service "
 
1022
                 "'%s' of type '%s' in domain '%s': %s\n", name, type,
 
1023
                 domain,
 
1024
                 avahi_strerror(avahi_server_errno(mc.server)));
889
1025
    break;
890
1026
    
891
1027
  case AVAHI_RESOLVER_FOUND:
893
1029
      char ip[AVAHI_ADDRESS_STR_MAX];
894
1030
      avahi_address_snprint(ip, sizeof(ip), address);
895
1031
      if(debug){
896
 
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %"
897
 
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
898
 
                ip, (intmax_t)interface, port);
 
1032
        fprintf_plus(stderr, "Mandos server \"%s\" found on %s (%s, %"
 
1033
                     PRIdMAX ") on port %" PRIu16 "\n", name,
 
1034
                     host_name, ip, (intmax_t)interface, port);
899
1035
      }
900
1036
      int ret = start_mandos_communication(ip, port, interface,
901
1037
                                           avahi_proto_to_af(proto));
902
1038
      if(ret == 0){
903
1039
        avahi_simple_poll_quit(mc.simple_poll);
 
1040
      } else {
 
1041
        if(not add_server(ip, port, interface,
 
1042
                          avahi_proto_to_af(proto))){
 
1043
          fprintf_plus(stderr, "Failed to add server \"%s\" to server"
 
1044
                       " list\n", name);
 
1045
        }
904
1046
      }
905
1047
    }
906
1048
  }
930
1072
  default:
931
1073
  case AVAHI_BROWSER_FAILURE:
932
1074
    
933
 
    fprintf(stderr, "(Avahi browser) %s\n",
934
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
1075
    fprintf_plus(stderr, "(Avahi browser) %s\n",
 
1076
                 avahi_strerror(avahi_server_errno(mc.server)));
935
1077
    avahi_simple_poll_quit(mc.simple_poll);
936
1078
    return;
937
1079
    
944
1086
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
945
1087
                                    name, type, domain, protocol, 0,
946
1088
                                    resolve_callback, NULL) == NULL)
947
 
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
948
 
              name, avahi_strerror(avahi_server_errno(mc.server)));
 
1089
      fprintf_plus(stderr, "Avahi: Failed to resolve service '%s':"
 
1090
                   " %s\n", name,
 
1091
                   avahi_strerror(avahi_server_errno(mc.server)));
949
1092
    break;
950
1093
    
951
1094
  case AVAHI_BROWSER_REMOVE:
954
1097
  case AVAHI_BROWSER_ALL_FOR_NOW:
955
1098
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
956
1099
    if(debug){
957
 
      fprintf(stderr, "No Mandos server found, still searching...\n");
 
1100
      fprintf_plus(stderr, "No Mandos server found, still"
 
1101
                   " searching...\n");
958
1102
    }
959
1103
    break;
960
1104
  }
961
1105
}
962
1106
 
963
 
/* stop main loop after sigterm has been called */
 
1107
/* Signal handler that stops main loop after SIGTERM */
964
1108
static void handle_sigterm(int sig){
965
1109
  if(quit_now){
966
1110
    return;
968
1112
  quit_now = 1;
969
1113
  signal_received = sig;
970
1114
  int old_errno = errno;
 
1115
  /* set main loop to exit */
971
1116
  if(mc.simple_poll != NULL){
972
1117
    avahi_simple_poll_quit(mc.simple_poll);
973
1118
  }
974
1119
  errno = old_errno;
975
1120
}
976
1121
 
 
1122
bool get_flags(const char *ifname, struct ifreq *ifr){
 
1123
  int ret;
 
1124
  
 
1125
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1126
  if(s < 0){
 
1127
    perror_plus("socket");
 
1128
    return false;
 
1129
  }
 
1130
  strcpy(ifr->ifr_name, ifname);
 
1131
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
 
1132
  if(ret == -1){
 
1133
    if(debug){
 
1134
      perror_plus("ioctl SIOCGIFFLAGS");
 
1135
    }
 
1136
    return false;
 
1137
  }
 
1138
  return true;
 
1139
}
 
1140
 
 
1141
bool good_flags(const char *ifname, const struct ifreq *ifr){
 
1142
  
 
1143
  /* Reject the loopback device */
 
1144
  if(ifr->ifr_flags & IFF_LOOPBACK){
 
1145
    if(debug){
 
1146
      fprintf_plus(stderr, "Rejecting loopback interface \"%s\"\n",
 
1147
                   ifname);
 
1148
    }
 
1149
    return false;
 
1150
  }
 
1151
  /* Accept point-to-point devices only if connect_to is specified */
 
1152
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
 
1153
    if(debug){
 
1154
      fprintf_plus(stderr, "Accepting point-to-point interface"
 
1155
                   " \"%s\"\n", ifname);
 
1156
    }
 
1157
    return true;
 
1158
  }
 
1159
  /* Otherwise, reject non-broadcast-capable devices */
 
1160
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
 
1161
    if(debug){
 
1162
      fprintf_plus(stderr, "Rejecting non-broadcast interface"
 
1163
                   " \"%s\"\n", ifname);
 
1164
    }
 
1165
    return false;
 
1166
  }
 
1167
  /* Reject non-ARP interfaces (including dummy interfaces) */
 
1168
  if(ifr->ifr_flags & IFF_NOARP){
 
1169
    if(debug){
 
1170
      fprintf_plus(stderr, "Rejecting non-ARP interface \"%s\"\n",
 
1171
                   ifname);
 
1172
    }
 
1173
    return false;
 
1174
  }
 
1175
  
 
1176
  /* Accept this device */
 
1177
  if(debug){
 
1178
    fprintf_plus(stderr, "Interface \"%s\" is good\n", ifname);
 
1179
  }
 
1180
  return true;
 
1181
}
 
1182
 
 
1183
/* 
 
1184
 * This function determines if a directory entry in /sys/class/net
 
1185
 * corresponds to an acceptable network device.
 
1186
 * (This function is passed to scandir(3) as a filter function.)
 
1187
 */
 
1188
int good_interface(const struct dirent *if_entry){
 
1189
  if(if_entry->d_name[0] == '.'){
 
1190
    return 0;
 
1191
  }
 
1192
  
 
1193
  struct ifreq ifr;
 
1194
  if(not get_flags(if_entry->d_name, &ifr)){
 
1195
    if(debug){
 
1196
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1197
                   "\"%s\"\n", if_entry->d_name);
 
1198
    }
 
1199
    return 0;
 
1200
  }
 
1201
  
 
1202
  if(not good_flags(if_entry->d_name, &ifr)){
 
1203
    return 0;
 
1204
  }
 
1205
  return 1;
 
1206
}
 
1207
 
 
1208
/* 
 
1209
 * This function determines if a directory entry in /sys/class/net
 
1210
 * corresponds to an acceptable network device which is up.
 
1211
 * (This function is passed to scandir(3) as a filter function.)
 
1212
 */
 
1213
int up_interface(const struct dirent *if_entry){
 
1214
  if(if_entry->d_name[0] == '.'){
 
1215
    return 0;
 
1216
  }
 
1217
  
 
1218
  struct ifreq ifr;
 
1219
  if(not get_flags(if_entry->d_name, &ifr)){
 
1220
    if(debug){
 
1221
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1222
                   "\"%s\"\n", if_entry->d_name);
 
1223
    }
 
1224
    return 0;
 
1225
  }
 
1226
  
 
1227
  /* Reject down interfaces */
 
1228
  if(not (ifr.ifr_flags & IFF_UP)){
 
1229
    if(debug){
 
1230
      fprintf_plus(stderr, "Rejecting down interface \"%s\"\n",
 
1231
                   if_entry->d_name);
 
1232
    }
 
1233
    return 0;
 
1234
  }
 
1235
  
 
1236
  /* Reject non-running interfaces */
 
1237
  if(not (ifr.ifr_flags & IFF_RUNNING)){
 
1238
    if(debug){
 
1239
      fprintf_plus(stderr, "Rejecting non-running interface \"%s\"\n",
 
1240
                   if_entry->d_name);
 
1241
    }
 
1242
    return 0;
 
1243
  }
 
1244
  
 
1245
  if(not good_flags(if_entry->d_name, &ifr)){
 
1246
    return 0;
 
1247
  }
 
1248
  return 1;
 
1249
}
 
1250
 
 
1251
int notdotentries(const struct dirent *direntry){
 
1252
  /* Skip "." and ".." */
 
1253
  if(direntry->d_name[0] == '.'
 
1254
     and (direntry->d_name[1] == '\0'
 
1255
          or (direntry->d_name[1] == '.'
 
1256
              and direntry->d_name[2] == '\0'))){
 
1257
    return 0;
 
1258
  }
 
1259
  return 1;
 
1260
}
 
1261
 
 
1262
/* Is this directory entry a runnable program? */
 
1263
int runnable_hook(const struct dirent *direntry){
 
1264
  int ret;
 
1265
  size_t sret;
 
1266
  struct stat st;
 
1267
  
 
1268
  if((direntry->d_name)[0] == '\0'){
 
1269
    /* Empty name? */
 
1270
    return 0;
 
1271
  }
 
1272
  
 
1273
  sret = strspn(direntry->d_name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
 
1274
                "abcdefghijklmnopqrstuvwxyz"
 
1275
                "0123456789"
 
1276
                "_-");
 
1277
  if((direntry->d_name)[sret] != '\0'){
 
1278
    /* Contains non-allowed characters */
 
1279
    if(debug){
 
1280
      fprintf_plus(stderr, "Ignoring hook \"%s\" with bad name\n",
 
1281
                   direntry->d_name);
 
1282
    }
 
1283
    return 0;
 
1284
  }
 
1285
  
 
1286
  char *fullname = NULL;
 
1287
  ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
 
1288
  if(ret < 0){
 
1289
    perror_plus("asprintf");
 
1290
    return 0;
 
1291
  }
 
1292
  
 
1293
  ret = stat(fullname, &st);
 
1294
  if(ret == -1){
 
1295
    if(debug){
 
1296
      perror_plus("Could not stat hook");
 
1297
    }
 
1298
    return 0;
 
1299
  }
 
1300
  if(not (S_ISREG(st.st_mode))){
 
1301
    /* Not a regular file */
 
1302
    if(debug){
 
1303
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not a file\n",
 
1304
                   direntry->d_name);
 
1305
    }
 
1306
    return 0;
 
1307
  }
 
1308
  if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
 
1309
    /* Not executable */
 
1310
    if(debug){
 
1311
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not executable\n",
 
1312
                   direntry->d_name);
 
1313
    }
 
1314
    return 0;
 
1315
  }
 
1316
  if(debug){
 
1317
    fprintf_plus(stderr, "Hook \"%s\" is acceptable\n",
 
1318
                 direntry->d_name);
 
1319
  }
 
1320
  return 1;
 
1321
}
 
1322
 
 
1323
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
 
1324
  int ret;
 
1325
  struct timespec now;
 
1326
  struct timespec waited_time;
 
1327
  intmax_t block_time;
 
1328
  
 
1329
  while(true){
 
1330
    if(mc.current_server == NULL){
 
1331
      if (debug){
 
1332
        fprintf_plus(stderr, "Wait until first server is found."
 
1333
                     " No timeout!\n");
 
1334
      }
 
1335
      ret = avahi_simple_poll_iterate(s, -1);
 
1336
    } else {
 
1337
      if (debug){
 
1338
        fprintf_plus(stderr, "Check current_server if we should run"
 
1339
                     " it, or wait\n");
 
1340
      }
 
1341
      /* the current time */
 
1342
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
 
1343
      if(ret == -1){
 
1344
        perror_plus("clock_gettime");
 
1345
        return -1;
 
1346
      }
 
1347
      /* Calculating in ms how long time between now and server
 
1348
         who we visted longest time ago. Now - last seen.  */
 
1349
      waited_time.tv_sec = (now.tv_sec
 
1350
                            - mc.current_server->last_seen.tv_sec);
 
1351
      waited_time.tv_nsec = (now.tv_nsec
 
1352
                             - mc.current_server->last_seen.tv_nsec);
 
1353
      /* total time is 10s/10,000ms.
 
1354
         Converting to s from ms by dividing by 1,000,
 
1355
         and ns to ms by dividing by 1,000,000. */
 
1356
      block_time = ((retry_interval
 
1357
                     - ((intmax_t)waited_time.tv_sec * 1000))
 
1358
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
 
1359
      
 
1360
      if (debug){
 
1361
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
 
1362
                     block_time);
 
1363
      }
 
1364
      
 
1365
      if(block_time <= 0){
 
1366
        ret = start_mandos_communication(mc.current_server->ip,
 
1367
                                         mc.current_server->port,
 
1368
                                         mc.current_server->if_index,
 
1369
                                         mc.current_server->af);
 
1370
        if(ret == 0){
 
1371
          avahi_simple_poll_quit(mc.simple_poll);
 
1372
          return 0;
 
1373
        }
 
1374
        ret = clock_gettime(CLOCK_MONOTONIC,
 
1375
                            &mc.current_server->last_seen);
 
1376
        if(ret == -1){
 
1377
          perror_plus("clock_gettime");
 
1378
          return -1;
 
1379
        }
 
1380
        mc.current_server = mc.current_server->next;
 
1381
        block_time = 0;         /* Call avahi to find new Mandos
 
1382
                                   servers, but don't block */
 
1383
      }
 
1384
      
 
1385
      ret = avahi_simple_poll_iterate(s, (int)block_time);
 
1386
    }
 
1387
    if(ret != 0){
 
1388
      if (ret > 0 or errno != EINTR){
 
1389
        return (ret != 1) ? ret : 0;
 
1390
      }
 
1391
    }
 
1392
  }
 
1393
}
 
1394
 
 
1395
/* Set effective uid to 0, return errno */
 
1396
error_t raise_privileges(void){
 
1397
  error_t old_errno = errno;
 
1398
  error_t ret_errno = 0;
 
1399
  if(seteuid(0) == -1){
 
1400
    ret_errno = errno;
 
1401
    perror_plus("seteuid");
 
1402
  }
 
1403
  errno = old_errno;
 
1404
  return ret_errno;
 
1405
}
 
1406
 
 
1407
/* Set effective and real user ID to 0.  Return errno. */
 
1408
error_t raise_privileges_permanently(void){
 
1409
  error_t old_errno = errno;
 
1410
  error_t ret_errno = raise_privileges();
 
1411
  if(ret_errno != 0){
 
1412
    errno = old_errno;
 
1413
    return ret_errno;
 
1414
  }
 
1415
  if(setuid(0) == -1){
 
1416
    ret_errno = errno;
 
1417
    perror_plus("seteuid");
 
1418
  }
 
1419
  errno = old_errno;
 
1420
  return ret_errno;
 
1421
}
 
1422
 
 
1423
/* Set effective user ID to unprivileged saved user ID */
 
1424
error_t lower_privileges(void){
 
1425
  error_t old_errno = errno;
 
1426
  error_t ret_errno = 0;
 
1427
  if(seteuid(uid) == -1){
 
1428
    ret_errno = errno;
 
1429
    perror_plus("seteuid");
 
1430
  }
 
1431
  errno = old_errno;
 
1432
  return ret_errno;
 
1433
}
 
1434
 
 
1435
bool run_network_hooks(const char *mode, const char *interface,
 
1436
                       const float delay){
 
1437
  struct dirent **direntries;
 
1438
  struct dirent *direntry;
 
1439
  int ret;
 
1440
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
 
1441
                         alphasort);
 
1442
  if(numhooks == -1){
 
1443
    perror_plus("scandir");
 
1444
  } else {
 
1445
    int devnull = open("/dev/null", O_RDONLY);
 
1446
    for(int i = 0; i < numhooks; i++){
 
1447
      direntry = direntries[i];
 
1448
      char *fullname = NULL;
 
1449
      ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
 
1450
      if(ret < 0){
 
1451
        perror_plus("asprintf");
 
1452
        continue;
 
1453
      }
 
1454
      if(debug){
 
1455
        fprintf_plus(stderr, "Running network hook \"%s\"\n",
 
1456
                     direntry->d_name);
 
1457
      }
 
1458
      pid_t hook_pid = fork();
 
1459
      if(hook_pid == 0){
 
1460
        /* Child */
 
1461
        /* Raise privileges */
 
1462
        raise_privileges_permanently();
 
1463
        /* Set group */
 
1464
        errno = 0;
 
1465
        ret = setgid(0);
 
1466
        if(ret == -1){
 
1467
          perror_plus("setgid");
 
1468
        }
 
1469
        /* Reset supplementary groups */
 
1470
        errno = 0;
 
1471
        ret = setgroups(0, NULL);
 
1472
        if(ret == -1){
 
1473
          perror_plus("setgroups");
 
1474
        }
 
1475
        dup2(devnull, STDIN_FILENO);
 
1476
        close(devnull);
 
1477
        dup2(STDERR_FILENO, STDOUT_FILENO);
 
1478
        ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
 
1479
        if(ret == -1){
 
1480
          perror_plus("setenv");
 
1481
          _exit(EX_OSERR);
 
1482
        }
 
1483
        ret = setenv("DEVICE", interface, 1);
 
1484
        if(ret == -1){
 
1485
          perror_plus("setenv");
 
1486
          _exit(EX_OSERR);
 
1487
        }
 
1488
        ret = setenv("VERBOSITY", debug ? "1" : "0", 1);
 
1489
        if(ret == -1){
 
1490
          perror_plus("setenv");
 
1491
          _exit(EX_OSERR);
 
1492
        }
 
1493
        ret = setenv("MODE", mode, 1);
 
1494
        if(ret == -1){
 
1495
          perror_plus("setenv");
 
1496
          _exit(EX_OSERR);
 
1497
        }
 
1498
        char *delaystring;
 
1499
        ret = asprintf(&delaystring, "%f", delay);
 
1500
        if(ret == -1){
 
1501
          perror_plus("asprintf");
 
1502
          _exit(EX_OSERR);
 
1503
        }
 
1504
        ret = setenv("DELAY", delaystring, 1);
 
1505
        if(ret == -1){
 
1506
          free(delaystring);
 
1507
          perror_plus("setenv");
 
1508
          _exit(EX_OSERR);
 
1509
        }
 
1510
        free(delaystring);
 
1511
        if(connect_to != NULL){
 
1512
          ret = setenv("CONNECT", connect_to, 1);
 
1513
          if(ret == -1){
 
1514
            perror_plus("setenv");
 
1515
            _exit(EX_OSERR);
 
1516
          }
 
1517
        }
 
1518
        if(execl(fullname, direntry->d_name, mode, NULL) == -1){
 
1519
          perror_plus("execl");
 
1520
          _exit(EXIT_FAILURE);
 
1521
        }
 
1522
      } else {
 
1523
        int status;
 
1524
        if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
 
1525
          perror_plus("waitpid");
 
1526
          free(fullname);
 
1527
          continue;
 
1528
        }
 
1529
        if(WIFEXITED(status)){
 
1530
          if(WEXITSTATUS(status) != 0){
 
1531
            fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
 
1532
                         " with status %d\n", direntry->d_name,
 
1533
                         WEXITSTATUS(status));
 
1534
            free(fullname);
 
1535
            continue;
 
1536
          }
 
1537
        } else if(WIFSIGNALED(status)){
 
1538
          fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
 
1539
                       " signal %d\n", direntry->d_name,
 
1540
                       WTERMSIG(status));
 
1541
          free(fullname);
 
1542
          continue;
 
1543
        } else {
 
1544
          fprintf_plus(stderr, "Warning: network hook \"%s\""
 
1545
                       " crashed\n", direntry->d_name);
 
1546
          free(fullname);
 
1547
          continue;
 
1548
        }
 
1549
      }
 
1550
      free(fullname);
 
1551
      if(debug){
 
1552
        fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
 
1553
                     direntry->d_name);
 
1554
      }
 
1555
    }
 
1556
    close(devnull);
 
1557
  }
 
1558
  return true;
 
1559
}
 
1560
 
 
1561
int bring_up_interface(const char *const interface,
 
1562
                       const float delay){
 
1563
  int sd = -1;
 
1564
  int old_errno = errno;
 
1565
  int ret_errno = 0;
 
1566
  int ret;
 
1567
  struct ifreq network;
 
1568
  AvahiIfIndex if_index = (AvahiIfIndex)if_nametoindex(interface);
 
1569
  if(if_index == 0){
 
1570
    fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
 
1571
    errno = old_errno;
 
1572
    return ENXIO;
 
1573
  }
 
1574
  
 
1575
  if(quit_now){
 
1576
    errno = old_errno;
 
1577
    return EINTR;
 
1578
  }
 
1579
  
 
1580
  /* Re-raise priviliges */
 
1581
  raise_privileges();
 
1582
  
 
1583
#ifdef __linux__
 
1584
  /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
 
1585
     messages about the network interface to mess up the prompt */
 
1586
  ret = klogctl(8, NULL, 5);
 
1587
  bool restore_loglevel = true;
 
1588
  if(ret == -1){
 
1589
    restore_loglevel = false;
 
1590
    perror_plus("klogctl");
 
1591
  }
 
1592
#endif  /* __linux__ */
 
1593
    
 
1594
  sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1595
  if(sd < 0){
 
1596
    ret_errno = errno;
 
1597
    perror_plus("socket");
 
1598
#ifdef __linux__
 
1599
    if(restore_loglevel){
 
1600
      ret = klogctl(7, NULL, 0);
 
1601
      if(ret == -1){
 
1602
        perror_plus("klogctl");
 
1603
      }
 
1604
    }
 
1605
#endif  /* __linux__ */
 
1606
    /* Lower privileges */
 
1607
    lower_privileges();
 
1608
    errno = old_errno;
 
1609
    return ret_errno;
 
1610
  }
 
1611
  strcpy(network.ifr_name, interface);
 
1612
  ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
1613
  if(ret == -1){
 
1614
    ret_errno = errno;
 
1615
    perror_plus("ioctl SIOCGIFFLAGS");
 
1616
#ifdef __linux__
 
1617
    if(restore_loglevel){
 
1618
      ret = klogctl(7, NULL, 0);
 
1619
      if(ret == -1){
 
1620
        perror_plus("klogctl");
 
1621
      }
 
1622
    }
 
1623
#endif  /* __linux__ */
 
1624
    /* Lower privileges */
 
1625
    lower_privileges();
 
1626
    errno = old_errno;
 
1627
    return ret_errno;
 
1628
  }
 
1629
  if((network.ifr_flags & IFF_UP) == 0){
 
1630
    network.ifr_flags |= IFF_UP;
 
1631
    ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
1632
    if(ret == -1){
 
1633
      ret_errno = errno;
 
1634
      perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
 
1635
#ifdef __linux__
 
1636
      if(restore_loglevel){
 
1637
        ret = klogctl(7, NULL, 0);
 
1638
        if(ret == -1){
 
1639
          perror_plus("klogctl");
 
1640
        }
 
1641
      }
 
1642
#endif  /* __linux__ */
 
1643
        /* Lower privileges */
 
1644
      lower_privileges();
 
1645
      errno = old_errno;
 
1646
      return ret_errno;
 
1647
    }
 
1648
  }
 
1649
  /* Sleep checking until interface is running.
 
1650
     Check every 0.25s, up to total time of delay */
 
1651
  for(int i=0; i < delay * 4; i++){
 
1652
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
1653
    if(ret == -1){
 
1654
      perror_plus("ioctl SIOCGIFFLAGS");
 
1655
    } else if(network.ifr_flags & IFF_RUNNING){
 
1656
      break;
 
1657
    }
 
1658
    struct timespec sleeptime = { .tv_nsec = 250000000 };
 
1659
    ret = nanosleep(&sleeptime, NULL);
 
1660
    if(ret == -1 and errno != EINTR){
 
1661
      perror_plus("nanosleep");
 
1662
    }
 
1663
  }
 
1664
  /* Close the socket */
 
1665
  ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1666
  if(ret == -1){
 
1667
    perror_plus("close");
 
1668
  }
 
1669
#ifdef __linux__
 
1670
  if(restore_loglevel){
 
1671
    /* Restores kernel loglevel to default */
 
1672
    ret = klogctl(7, NULL, 0);
 
1673
    if(ret == -1){
 
1674
      perror_plus("klogctl");
 
1675
    }
 
1676
  }
 
1677
#endif  /* __linux__ */
 
1678
  /* Lower privileges */
 
1679
  lower_privileges();
 
1680
  errno = old_errno;
 
1681
  return 0;
 
1682
}
 
1683
 
977
1684
int main(int argc, char *argv[]){
978
1685
  AvahiSServiceBrowser *sb = NULL;
979
1686
  int error;
981
1688
  intmax_t tmpmax;
982
1689
  char *tmp;
983
1690
  int exitcode = EXIT_SUCCESS;
984
 
  const char *interface = "eth0";
 
1691
  const char *interface = "";
985
1692
  struct ifreq network;
986
1693
  int sd = -1;
987
1694
  bool take_down_interface = false;
988
 
  uid_t uid;
989
 
  gid_t gid;
990
 
  char *connect_to = NULL;
991
1695
  char tempdir[] = "/tmp/mandosXXXXXX";
992
1696
  bool tempdir_created = false;
993
1697
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
997
1701
  bool gnutls_initialized = false;
998
1702
  bool gpgme_initialized = false;
999
1703
  float delay = 2.5f;
 
1704
  double retry_interval = 10; /* 10s between trying a server and
 
1705
                                 retrying the same server again */
1000
1706
  
1001
1707
  struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
1002
1708
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
1008
1714
  errno = 0;
1009
1715
  ret = setgid(gid);
1010
1716
  if(ret == -1){
1011
 
    perror("setgid");
 
1717
    perror_plus("setgid");
1012
1718
  }
1013
1719
  
1014
1720
  /* Lower user privileges (temporarily) */
1015
1721
  errno = 0;
1016
1722
  ret = seteuid(uid);
1017
1723
  if(ret == -1){
1018
 
    perror("seteuid");
 
1724
    perror_plus("seteuid");
1019
1725
  }
1020
1726
  
1021
1727
  if(quit_now){
1056
1762
        .arg = "SECONDS",
1057
1763
        .doc = "Maximum delay to wait for interface startup",
1058
1764
        .group = 2 },
 
1765
      { .name = "retry", .key = 132,
 
1766
        .arg = "SECONDS",
 
1767
        .doc = "Retry interval used when denied by the Mandos server",
 
1768
        .group = 2 },
 
1769
      { .name = "network-hook-dir", .key = 133,
 
1770
        .arg = "DIR",
 
1771
        .doc = "Directory where network hooks are located",
 
1772
        .group = 2 },
 
1773
      /*
 
1774
       * These reproduce what we would get without ARGP_NO_HELP
 
1775
       */
 
1776
      { .name = "help", .key = '?',
 
1777
        .doc = "Give this help list", .group = -1 },
 
1778
      { .name = "usage", .key = -3,
 
1779
        .doc = "Give a short usage message", .group = -1 },
 
1780
      { .name = "version", .key = 'V',
 
1781
        .doc = "Print program version", .group = -1 },
1059
1782
      { .name = NULL }
1060
1783
    };
1061
1784
    
1062
1785
    error_t parse_opt(int key, char *arg,
1063
1786
                      struct argp_state *state){
 
1787
      errno = 0;
1064
1788
      switch(key){
1065
1789
      case 128:                 /* --debug */
1066
1790
        debug = true;
1082
1806
        tmpmax = strtoimax(arg, &tmp, 10);
1083
1807
        if(errno != 0 or tmp == arg or *tmp != '\0'
1084
1808
           or tmpmax != (typeof(mc.dh_bits))tmpmax){
1085
 
          fprintf(stderr, "Bad number of DH bits\n");
1086
 
          exit(EXIT_FAILURE);
 
1809
          argp_error(state, "Bad number of DH bits");
1087
1810
        }
1088
1811
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
1089
1812
        break;
1094
1817
        errno = 0;
1095
1818
        delay = strtof(arg, &tmp);
1096
1819
        if(errno != 0 or tmp == arg or *tmp != '\0'){
1097
 
          fprintf(stderr, "Bad delay\n");
1098
 
          exit(EXIT_FAILURE);
1099
 
        }
1100
 
        break;
1101
 
      case ARGP_KEY_ARG:
1102
 
        argp_usage(state);
1103
 
      case ARGP_KEY_END:
 
1820
          argp_error(state, "Bad delay");
 
1821
        }
 
1822
      case 132:                 /* --retry */
 
1823
        errno = 0;
 
1824
        retry_interval = strtod(arg, &tmp);
 
1825
        if(errno != 0 or tmp == arg or *tmp != '\0'
 
1826
           or (retry_interval * 1000) > INT_MAX
 
1827
           or retry_interval < 0){
 
1828
          argp_error(state, "Bad retry interval");
 
1829
        }
 
1830
        break;
 
1831
      case 133:                 /* --network-hook-dir */
 
1832
        hookdir = arg;
 
1833
        break;
 
1834
        /*
 
1835
         * These reproduce what we would get without ARGP_NO_HELP
 
1836
         */
 
1837
      case '?':                 /* --help */
 
1838
        argp_state_help(state, state->out_stream,
 
1839
                        (ARGP_HELP_STD_HELP | ARGP_HELP_EXIT_ERR)
 
1840
                        & ~(unsigned int)ARGP_HELP_EXIT_OK);
 
1841
      case -3:                  /* --usage */
 
1842
        argp_state_help(state, state->out_stream,
 
1843
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
 
1844
      case 'V':                 /* --version */
 
1845
        fprintf_plus(state->out_stream, "%s\n", argp_program_version);
 
1846
        exit(argp_err_exit_status);
1104
1847
        break;
1105
1848
      default:
1106
1849
        return ARGP_ERR_UNKNOWN;
1107
1850
      }
1108
 
      return 0;
 
1851
      return errno;
1109
1852
    }
1110
1853
    
1111
1854
    struct argp argp = { .options = options, .parser = parse_opt,
1112
1855
                         .args_doc = "",
1113
1856
                         .doc = "Mandos client -- Get and decrypt"
1114
1857
                         " passwords from a Mandos server" };
1115
 
    ret = argp_parse(&argp, argc, argv, 0, 0, NULL);
1116
 
    if(ret == ARGP_ERR_UNKNOWN){
1117
 
      fprintf(stderr, "Unknown error while parsing arguments\n");
1118
 
      exitcode = EXIT_FAILURE;
1119
 
      goto end;
1120
 
    }
 
1858
    ret = argp_parse(&argp, argc, argv,
 
1859
                     ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
 
1860
    switch(ret){
 
1861
    case 0:
 
1862
      break;
 
1863
    case ENOMEM:
 
1864
    default:
 
1865
      errno = ret;
 
1866
      perror_plus("argp_parse");
 
1867
      exitcode = EX_OSERR;
 
1868
      goto end;
 
1869
    case EINVAL:
 
1870
      exitcode = EX_USAGE;
 
1871
      goto end;
 
1872
    }
 
1873
  }
 
1874
    
 
1875
  {
 
1876
    /* Work around Debian bug #633582:
 
1877
       <http://bugs.debian.org/633582> */
 
1878
    
 
1879
    /* Re-raise priviliges */
 
1880
    if(raise_privileges() == 0){
 
1881
      struct stat st;
 
1882
      
 
1883
      if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
 
1884
        int seckey_fd = open(seckey, O_RDONLY);
 
1885
        if(seckey_fd == -1){
 
1886
          perror_plus("open");
 
1887
        } else {
 
1888
          ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
 
1889
          if(ret == -1){
 
1890
            perror_plus("fstat");
 
1891
          } else {
 
1892
            if(S_ISREG(st.st_mode)
 
1893
               and st.st_uid == 0 and st.st_gid == 0){
 
1894
              ret = fchown(seckey_fd, uid, gid);
 
1895
              if(ret == -1){
 
1896
                perror_plus("fchown");
 
1897
              }
 
1898
            }
 
1899
          }
 
1900
          TEMP_FAILURE_RETRY(close(seckey_fd));
 
1901
        }
 
1902
      }
 
1903
    
 
1904
      if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
 
1905
        int pubkey_fd = open(pubkey, O_RDONLY);
 
1906
        if(pubkey_fd == -1){
 
1907
          perror_plus("open");
 
1908
        } else {
 
1909
          ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
 
1910
          if(ret == -1){
 
1911
            perror_plus("fstat");
 
1912
          } else {
 
1913
            if(S_ISREG(st.st_mode)
 
1914
               and st.st_uid == 0 and st.st_gid == 0){
 
1915
              ret = fchown(pubkey_fd, uid, gid);
 
1916
              if(ret == -1){
 
1917
                perror_plus("fchown");
 
1918
              }
 
1919
            }
 
1920
          }
 
1921
          TEMP_FAILURE_RETRY(close(pubkey_fd));
 
1922
        }
 
1923
      }
 
1924
    
 
1925
      /* Lower privileges */
 
1926
      errno = 0;
 
1927
      ret = seteuid(uid);
 
1928
      if(ret == -1){
 
1929
        perror_plus("seteuid");
 
1930
      }
 
1931
    }
 
1932
  }
 
1933
  
 
1934
  /* Run network hooks */
 
1935
  if(not run_network_hooks("start", interface, delay)){
 
1936
    goto end;
1121
1937
  }
1122
1938
  
1123
1939
  if(not debug){
1124
1940
    avahi_set_log_function(empty_log);
1125
1941
  }
1126
1942
  
 
1943
  if(interface[0] == '\0'){
 
1944
    struct dirent **direntries;
 
1945
    /* First look for interfaces that are up */
 
1946
    ret = scandir(sys_class_net, &direntries, up_interface,
 
1947
                  alphasort);
 
1948
    if(ret == 0){
 
1949
      /* No up interfaces, look for any good interfaces */
 
1950
      free(direntries);
 
1951
      ret = scandir(sys_class_net, &direntries, good_interface,
 
1952
                    alphasort);
 
1953
    }
 
1954
    if(ret >= 1){
 
1955
      /* Pick the first interface returned */
 
1956
      interface = strdup(direntries[0]->d_name);
 
1957
      if(debug){
 
1958
        fprintf_plus(stderr, "Using interface \"%s\"\n", interface);
 
1959
      }
 
1960
      if(interface == NULL){
 
1961
        perror_plus("malloc");
 
1962
        free(direntries);
 
1963
        exitcode = EXIT_FAILURE;
 
1964
        goto end;
 
1965
      }
 
1966
      free(direntries);
 
1967
    } else {
 
1968
      free(direntries);
 
1969
      fprintf_plus(stderr, "Could not find a network interface\n");
 
1970
      exitcode = EXIT_FAILURE;
 
1971
      goto end;
 
1972
    }
 
1973
  }
 
1974
  
1127
1975
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
1128
1976
     from the signal handler */
1129
1977
  /* Initialize the pseudo-RNG for Avahi */
1130
1978
  srand((unsigned int) time(NULL));
1131
1979
  mc.simple_poll = avahi_simple_poll_new();
1132
1980
  if(mc.simple_poll == NULL){
1133
 
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
1134
 
    exitcode = EXIT_FAILURE;
 
1981
    fprintf_plus(stderr,
 
1982
                 "Avahi: Failed to create simple poll object.\n");
 
1983
    exitcode = EX_UNAVAILABLE;
1135
1984
    goto end;
1136
1985
  }
1137
1986
  
1138
1987
  sigemptyset(&sigterm_action.sa_mask);
1139
1988
  ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
1140
1989
  if(ret == -1){
1141
 
    perror("sigaddset");
1142
 
    exitcode = EXIT_FAILURE;
 
1990
    perror_plus("sigaddset");
 
1991
    exitcode = EX_OSERR;
1143
1992
    goto end;
1144
1993
  }
1145
1994
  ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
1146
1995
  if(ret == -1){
1147
 
    perror("sigaddset");
1148
 
    exitcode = EXIT_FAILURE;
 
1996
    perror_plus("sigaddset");
 
1997
    exitcode = EX_OSERR;
1149
1998
    goto end;
1150
1999
  }
1151
2000
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
1152
2001
  if(ret == -1){
1153
 
    perror("sigaddset");
1154
 
    exitcode = EXIT_FAILURE;
 
2002
    perror_plus("sigaddset");
 
2003
    exitcode = EX_OSERR;
1155
2004
    goto end;
1156
2005
  }
1157
2006
  /* Need to check if the handler is SIG_IGN before handling:
1160
2009
  */
1161
2010
  ret = sigaction(SIGINT, NULL, &old_sigterm_action);
1162
2011
  if(ret == -1){
1163
 
    perror("sigaction");
1164
 
    return EXIT_FAILURE;
 
2012
    perror_plus("sigaction");
 
2013
    return EX_OSERR;
1165
2014
  }
1166
2015
  if(old_sigterm_action.sa_handler != SIG_IGN){
1167
2016
    ret = sigaction(SIGINT, &sigterm_action, NULL);
1168
2017
    if(ret == -1){
1169
 
      perror("sigaction");
1170
 
      exitcode = EXIT_FAILURE;
 
2018
      perror_plus("sigaction");
 
2019
      exitcode = EX_OSERR;
1171
2020
      goto end;
1172
2021
    }
1173
2022
  }
1174
2023
  ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
1175
2024
  if(ret == -1){
1176
 
    perror("sigaction");
1177
 
    return EXIT_FAILURE;
 
2025
    perror_plus("sigaction");
 
2026
    return EX_OSERR;
1178
2027
  }
1179
2028
  if(old_sigterm_action.sa_handler != SIG_IGN){
1180
2029
    ret = sigaction(SIGHUP, &sigterm_action, NULL);
1181
2030
    if(ret == -1){
1182
 
      perror("sigaction");
1183
 
      exitcode = EXIT_FAILURE;
 
2031
      perror_plus("sigaction");
 
2032
      exitcode = EX_OSERR;
1184
2033
      goto end;
1185
2034
    }
1186
2035
  }
1187
2036
  ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
1188
2037
  if(ret == -1){
1189
 
    perror("sigaction");
1190
 
    return EXIT_FAILURE;
 
2038
    perror_plus("sigaction");
 
2039
    return EX_OSERR;
1191
2040
  }
1192
2041
  if(old_sigterm_action.sa_handler != SIG_IGN){
1193
2042
    ret = sigaction(SIGTERM, &sigterm_action, NULL);
1194
2043
    if(ret == -1){
1195
 
      perror("sigaction");
1196
 
      exitcode = EXIT_FAILURE;
 
2044
      perror_plus("sigaction");
 
2045
      exitcode = EX_OSERR;
1197
2046
      goto end;
1198
2047
    }
1199
2048
  }
1200
2049
  
1201
2050
  /* If the interface is down, bring it up */
1202
 
  if(interface[0] != '\0'){
1203
 
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1204
 
    if(if_index == 0){
1205
 
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
1206
 
      exitcode = EXIT_FAILURE;
1207
 
      goto end;
1208
 
    }
1209
 
    
1210
 
    if(quit_now){
1211
 
      goto end;
1212
 
    }
1213
 
    
1214
 
    /* Re-raise priviliges */
1215
 
    errno = 0;
1216
 
    ret = seteuid(0);
1217
 
    if(ret == -1){
1218
 
      perror("seteuid");
1219
 
    }
1220
 
    
1221
 
#ifdef __linux__
1222
 
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1223
 
       messages to mess up the prompt */
1224
 
    ret = klogctl(8, NULL, 5);
1225
 
    bool restore_loglevel = true;
1226
 
    if(ret == -1){
1227
 
      restore_loglevel = false;
1228
 
      perror("klogctl");
1229
 
    }
1230
 
#endif  /* __linux__ */
1231
 
    
1232
 
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1233
 
    if(sd < 0){
1234
 
      perror("socket");
1235
 
      exitcode = EXIT_FAILURE;
1236
 
#ifdef __linux__
1237
 
      if(restore_loglevel){
1238
 
        ret = klogctl(7, NULL, 0);
1239
 
        if(ret == -1){
1240
 
          perror("klogctl");
1241
 
        }
1242
 
      }
1243
 
#endif  /* __linux__ */
1244
 
      /* Lower privileges */
1245
 
      errno = 0;
1246
 
      ret = seteuid(uid);
1247
 
      if(ret == -1){
1248
 
        perror("seteuid");
1249
 
      }
1250
 
      goto end;
1251
 
    }
1252
 
    strcpy(network.ifr_name, interface);
1253
 
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
1254
 
    if(ret == -1){
1255
 
      perror("ioctl SIOCGIFFLAGS");
1256
 
#ifdef __linux__
1257
 
      if(restore_loglevel){
1258
 
        ret = klogctl(7, NULL, 0);
1259
 
        if(ret == -1){
1260
 
          perror("klogctl");
1261
 
        }
1262
 
      }
1263
 
#endif  /* __linux__ */
1264
 
      exitcode = EXIT_FAILURE;
1265
 
      /* Lower privileges */
1266
 
      errno = 0;
1267
 
      ret = seteuid(uid);
1268
 
      if(ret == -1){
1269
 
        perror("seteuid");
1270
 
      }
1271
 
      goto end;
1272
 
    }
1273
 
    if((network.ifr_flags & IFF_UP) == 0){
1274
 
      network.ifr_flags |= IFF_UP;
1275
 
      take_down_interface = true;
1276
 
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1277
 
      if(ret == -1){
1278
 
        take_down_interface = false;
1279
 
        perror("ioctl SIOCSIFFLAGS");
1280
 
        exitcode = EXIT_FAILURE;
1281
 
#ifdef __linux__
1282
 
        if(restore_loglevel){
1283
 
          ret = klogctl(7, NULL, 0);
1284
 
          if(ret == -1){
1285
 
            perror("klogctl");
1286
 
          }
1287
 
        }
1288
 
#endif  /* __linux__ */
1289
 
        /* Lower privileges */
1290
 
        errno = 0;
1291
 
        ret = seteuid(uid);
1292
 
        if(ret == -1){
1293
 
          perror("seteuid");
1294
 
        }
1295
 
        goto end;
1296
 
      }
1297
 
    }
1298
 
    /* sleep checking until interface is running */
1299
 
    for(int i=0; i < delay * 4; i++){
1300
 
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1301
 
      if(ret == -1){
1302
 
        perror("ioctl SIOCGIFFLAGS");
1303
 
      } else if(network.ifr_flags & IFF_RUNNING){
1304
 
        break;
1305
 
      }
1306
 
      struct timespec sleeptime = { .tv_nsec = 250000000 };
1307
 
      ret = nanosleep(&sleeptime, NULL);
1308
 
      if(ret == -1 and errno != EINTR){
1309
 
        perror("nanosleep");
1310
 
      }
1311
 
    }
1312
 
    if(not take_down_interface){
1313
 
      /* We won't need the socket anymore */
1314
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1315
 
      if(ret == -1){
1316
 
        perror("close");
1317
 
      }
1318
 
    }
1319
 
#ifdef __linux__
1320
 
    if(restore_loglevel){
1321
 
      /* Restores kernel loglevel to default */
1322
 
      ret = klogctl(7, NULL, 0);
1323
 
      if(ret == -1){
1324
 
        perror("klogctl");
1325
 
      }
1326
 
    }
1327
 
#endif  /* __linux__ */
1328
 
    /* Lower privileges */
1329
 
    errno = 0;
1330
 
    if(take_down_interface){
1331
 
      /* Lower privileges */
1332
 
      ret = seteuid(uid);
1333
 
      if(ret == -1){
1334
 
        perror("seteuid");
1335
 
      }
1336
 
    } else {
1337
 
      /* Lower privileges permanently */
1338
 
      ret = setuid(uid);
1339
 
      if(ret == -1){
1340
 
        perror("setuid");
1341
 
      }
 
2051
  if((interface[0] != '\0') and (strcmp(interface, "none") != 0)){
 
2052
    ret = bring_up_interface(interface, delay);
 
2053
    if(ret != 0){
 
2054
      errno = ret;
 
2055
      perror_plus("Failed to bring up interface");
1342
2056
    }
1343
2057
  }
1344
2058
  
1348
2062
  
1349
2063
  ret = init_gnutls_global(pubkey, seckey);
1350
2064
  if(ret == -1){
1351
 
    fprintf(stderr, "init_gnutls_global failed\n");
1352
 
    exitcode = EXIT_FAILURE;
 
2065
    fprintf_plus(stderr, "init_gnutls_global failed\n");
 
2066
    exitcode = EX_UNAVAILABLE;
1353
2067
    goto end;
1354
2068
  } else {
1355
2069
    gnutls_initialized = true;
1359
2073
    goto end;
1360
2074
  }
1361
2075
  
 
2076
  if(mkdtemp(tempdir) == NULL){
 
2077
    perror_plus("mkdtemp");
 
2078
    goto end;
 
2079
  }
1362
2080
  tempdir_created = true;
1363
 
  if(mkdtemp(tempdir) == NULL){
1364
 
    tempdir_created = false;
1365
 
    perror("mkdtemp");
1366
 
    goto end;
1367
 
  }
1368
2081
  
1369
2082
  if(quit_now){
1370
2083
    goto end;
1371
2084
  }
1372
2085
  
1373
2086
  if(not init_gpgme(pubkey, seckey, tempdir)){
1374
 
    fprintf(stderr, "init_gpgme failed\n");
1375
 
    exitcode = EXIT_FAILURE;
 
2087
    fprintf_plus(stderr, "init_gpgme failed\n");
 
2088
    exitcode = EX_UNAVAILABLE;
1376
2089
    goto end;
1377
2090
  } else {
1378
2091
    gpgme_initialized = true;
1386
2099
    /* Connect directly, do not use Zeroconf */
1387
2100
    /* (Mainly meant for debugging) */
1388
2101
    char *address = strrchr(connect_to, ':');
 
2102
    
1389
2103
    if(address == NULL){
1390
 
      fprintf(stderr, "No colon in address\n");
1391
 
      exitcode = EXIT_FAILURE;
 
2104
      fprintf_plus(stderr, "No colon in address\n");
 
2105
      exitcode = EX_USAGE;
1392
2106
      goto end;
1393
2107
    }
1394
2108
    
1401
2115
    tmpmax = strtoimax(address+1, &tmp, 10);
1402
2116
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
1403
2117
       or tmpmax != (uint16_t)tmpmax){
1404
 
      fprintf(stderr, "Bad port number\n");
1405
 
      exitcode = EXIT_FAILURE;
 
2118
      fprintf_plus(stderr, "Bad port number\n");
 
2119
      exitcode = EX_USAGE;
1406
2120
      goto end;
1407
2121
    }
1408
2122
  
1412
2126
    
1413
2127
    port = (uint16_t)tmpmax;
1414
2128
    *address = '\0';
1415
 
    address = connect_to;
1416
2129
    /* Colon in address indicates IPv6 */
1417
2130
    int af;
1418
 
    if(strchr(address, ':') != NULL){
 
2131
    if(strchr(connect_to, ':') != NULL){
1419
2132
      af = AF_INET6;
 
2133
      /* Accept [] around IPv6 address - see RFC 5952 */
 
2134
      if(connect_to[0] == '[' and address[-1] == ']')
 
2135
        {
 
2136
          connect_to++;
 
2137
          address[-1] = '\0';
 
2138
        }
1420
2139
    } else {
1421
2140
      af = AF_INET;
1422
2141
    }
 
2142
    address = connect_to;
1423
2143
    
1424
2144
    if(quit_now){
1425
2145
      goto end;
1426
2146
    }
1427
2147
    
1428
 
    ret = start_mandos_communication(address, port, if_index, af);
1429
 
    if(ret < 0){
1430
 
      exitcode = EXIT_FAILURE;
1431
 
    } else {
 
2148
    while(not quit_now){
 
2149
      ret = start_mandos_communication(address, port, if_index, af);
 
2150
      if(quit_now or ret == 0){
 
2151
        break;
 
2152
      }
 
2153
      if(debug){
 
2154
        fprintf_plus(stderr, "Retrying in %d seconds\n",
 
2155
                     (int)retry_interval);
 
2156
      }
 
2157
      sleep((int)retry_interval);
 
2158
    }
 
2159
    
 
2160
    if (not quit_now){
1432
2161
      exitcode = EXIT_SUCCESS;
1433
2162
    }
 
2163
    
1434
2164
    goto end;
1435
2165
  }
1436
2166
  
1458
2188
  
1459
2189
  /* Check if creating the Avahi server object succeeded */
1460
2190
  if(mc.server == NULL){
1461
 
    fprintf(stderr, "Failed to create Avahi server: %s\n",
1462
 
            avahi_strerror(error));
1463
 
    exitcode = EXIT_FAILURE;
 
2191
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
 
2192
                 avahi_strerror(error));
 
2193
    exitcode = EX_UNAVAILABLE;
1464
2194
    goto end;
1465
2195
  }
1466
2196
  
1473
2203
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
1474
2204
                                   NULL, 0, browse_callback, NULL);
1475
2205
  if(sb == NULL){
1476
 
    fprintf(stderr, "Failed to create service browser: %s\n",
1477
 
            avahi_strerror(avahi_server_errno(mc.server)));
1478
 
    exitcode = EXIT_FAILURE;
 
2206
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
 
2207
                 avahi_strerror(avahi_server_errno(mc.server)));
 
2208
    exitcode = EX_UNAVAILABLE;
1479
2209
    goto end;
1480
2210
  }
1481
2211
  
1486
2216
  /* Run the main loop */
1487
2217
  
1488
2218
  if(debug){
1489
 
    fprintf(stderr, "Starting Avahi loop search\n");
1490
 
  }
1491
 
  
1492
 
  avahi_simple_poll_loop(mc.simple_poll);
 
2219
    fprintf_plus(stderr, "Starting Avahi loop search\n");
 
2220
  }
 
2221
 
 
2222
  ret = avahi_loop_with_timeout(mc.simple_poll,
 
2223
                                (int)(retry_interval * 1000));
 
2224
  if(debug){
 
2225
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
 
2226
                 (ret == 0) ? "successfully" : "with error");
 
2227
  }
1493
2228
  
1494
2229
 end:
1495
2230
  
1496
2231
  if(debug){
1497
 
    fprintf(stderr, "%s exiting\n", argv[0]);
 
2232
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
1498
2233
  }
1499
2234
  
1500
2235
  /* Cleanup things */
1517
2252
    gpgme_release(mc.ctx);
1518
2253
  }
1519
2254
  
1520
 
  /* Take down the network interface */
1521
 
  if(take_down_interface){
1522
 
    /* Re-raise priviliges */
1523
 
    errno = 0;
1524
 
    ret = seteuid(0);
1525
 
    if(ret == -1){
1526
 
      perror("seteuid");
 
2255
  /* Cleans up the circular linked list of Mandos servers the client
 
2256
     has seen */
 
2257
  if(mc.current_server != NULL){
 
2258
    mc.current_server->prev->next = NULL;
 
2259
    while(mc.current_server != NULL){
 
2260
      server *next = mc.current_server->next;
 
2261
      free(mc.current_server);
 
2262
      mc.current_server = next;
1527
2263
    }
1528
 
    if(geteuid() == 0){
 
2264
  }
 
2265
  
 
2266
  /* Run network hooks */
 
2267
  run_network_hooks("stop", interface, delay);
 
2268
  
 
2269
  /* Re-raise priviliges */
 
2270
  {
 
2271
    raise_privileges();
 
2272
    
 
2273
    /* Take down the network interface */
 
2274
    if(take_down_interface and geteuid() == 0){
1529
2275
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1530
2276
      if(ret == -1){
1531
 
        perror("ioctl SIOCGIFFLAGS");
1532
 
      } else if(network.ifr_flags & IFF_UP) {
1533
 
        network.ifr_flags &= ~IFF_UP; /* clear flag */
 
2277
        perror_plus("ioctl SIOCGIFFLAGS");
 
2278
      } else if(network.ifr_flags & IFF_UP){
 
2279
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
1534
2280
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
1535
2281
        if(ret == -1){
1536
 
          perror("ioctl SIOCSIFFLAGS");
 
2282
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
1537
2283
        }
1538
2284
      }
1539
2285
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1540
2286
      if(ret == -1){
1541
 
        perror("close");
1542
 
      }
1543
 
      /* Lower privileges permanently */
1544
 
      errno = 0;
1545
 
      ret = setuid(uid);
1546
 
      if(ret == -1){
1547
 
        perror("setuid");
 
2287
        perror_plus("close");
1548
2288
      }
1549
2289
    }
1550
2290
  }
 
2291
  /* Lower privileges permanently */
 
2292
  errno = 0;
 
2293
  ret = setuid(uid);
 
2294
  if(ret == -1){
 
2295
    perror_plus("setuid");
 
2296
  }
1551
2297
  
1552
 
  /* Removes the temp directory used by GPGME */
 
2298
  /* Removes the GPGME temp directory and all files inside */
1553
2299
  if(tempdir_created){
1554
 
    DIR *d;
1555
 
    struct dirent *direntry;
1556
 
    d = opendir(tempdir);
1557
 
    if(d == NULL){
1558
 
      if(errno != ENOENT){
1559
 
        perror("opendir");
1560
 
      }
1561
 
    } else {
1562
 
      while(true){
1563
 
        direntry = readdir(d);
1564
 
        if(direntry == NULL){
1565
 
          break;
1566
 
        }
1567
 
        /* Skip "." and ".." */
1568
 
        if(direntry->d_name[0] == '.'
1569
 
           and (direntry->d_name[1] == '\0'
1570
 
                or (direntry->d_name[1] == '.'
1571
 
                    and direntry->d_name[2] == '\0'))){
1572
 
          continue;
1573
 
        }
 
2300
    struct dirent **direntries = NULL;
 
2301
    struct dirent *direntry = NULL;
 
2302
    int numentries = scandir(tempdir, &direntries, notdotentries,
 
2303
                             alphasort);
 
2304
    if (numentries > 0){
 
2305
      for(int i = 0; i < numentries; i++){
 
2306
        direntry = direntries[i];
1574
2307
        char *fullname = NULL;
1575
2308
        ret = asprintf(&fullname, "%s/%s", tempdir,
1576
2309
                       direntry->d_name);
1577
2310
        if(ret < 0){
1578
 
          perror("asprintf");
 
2311
          perror_plus("asprintf");
1579
2312
          continue;
1580
2313
        }
1581
2314
        ret = remove(fullname);
1582
2315
        if(ret == -1){
1583
 
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
1584
 
                  strerror(errno));
 
2316
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
 
2317
                       strerror(errno));
1585
2318
        }
1586
2319
        free(fullname);
1587
2320
      }
1588
 
      closedir(d);
 
2321
    }
 
2322
 
 
2323
    /* need to clean even if 0 because man page doesn't specify */
 
2324
    free(direntries);
 
2325
    if (numentries == -1){
 
2326
      perror_plus("scandir");
1589
2327
    }
1590
2328
    ret = rmdir(tempdir);
1591
2329
    if(ret == -1 and errno != ENOENT){
1592
 
      perror("rmdir");
 
2330
      perror_plus("rmdir");
1593
2331
    }
1594
2332
  }
1595
2333
  
1600
2338
                                            &old_sigterm_action,
1601
2339
                                            NULL));
1602
2340
    if(ret == -1){
1603
 
      perror("sigaction");
 
2341
      perror_plus("sigaction");
1604
2342
    }
1605
2343
    do {
1606
2344
      ret = raise(signal_received);
1607
2345
    } while(ret != 0 and errno == EINTR);
1608
2346
    if(ret != 0){
1609
 
      perror("raise");
 
2347
      perror_plus("raise");
1610
2348
      abort();
1611
2349
    }
1612
2350
    TEMP_FAILURE_RETRY(pause());