aboutsummaryrefslogtreecommitdiffstats
path: root/common/exectool.c
blob: 953c34af0b2c0f27bbe9708dc725a600a72b9f57 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
/* exectool.c - Utility functions to execute a helper tool
 * Copyright (C) 2015 Werner Koch
 *
 * This file is part of GnuPG.
 *
 * This file is free software; you can redistribute it and/or modify
 * it under the terms of either
 *
 *   - the GNU Lesser General Public License as published by the Free
 *     Software Foundation; either version 3 of the License, or (at
 *     your option) any later version.
 *
 * or
 *
 *   - the GNU General Public License as published by the Free
 *     Software Foundation; either version 2 of the License, or (at
 *     your option) any later version.
 *
 * or both in parallel, as here.
 *
 * This file is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 */

#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <errno.h>
#include <assert.h>
#include <gpg-error.h>

#include <assuan.h>
#include "i18n.h"
#include "logging.h"
#include "membuf.h"
#include "mischelp.h"
#include "exechelp.h"
#include "sysutils.h"
#include "util.h"

typedef struct
{
  const char *pgmname;
  int cont;
  int used;
  char buffer[256];
} read_and_log_buffer_t;


static inline gpg_error_t
my_error_from_syserror (void)
{
  return gpg_err_make (default_errsource, gpg_err_code_from_syserror ());
}


static void
read_and_log_stderr (read_and_log_buffer_t *state, es_poll_t *fderr)
{
  gpg_error_t err;
  int c;

  if (!fderr)
    {
      /* Flush internal buffer.  */
      if (state->used)
        {
          const char *pname;
          int len;

          state->buffer[state->used] = 0;
          state->used = 0;

          pname = strrchr (state->pgmname, '/');
          if (pname && pname != state->pgmname && pname[1])
            pname++;
          else
            pname = state->pgmname;
          /* If our pgmname plus colon is identical to the start of
             the output, print only the output.  */
          len = strlen (pname);
          if (!state->cont
              && !strncmp (state->buffer, pname, len)
              && strlen (state->buffer) > strlen (pname)
              && state->buffer[len] == ':' )
            log_info ("%s\n", state->buffer);
          else
            log_info ("%s%c %s\n",
                      pname, state->cont? '+':':', state->buffer);
        }
      state->cont = 0;
      return;
    }
  for (;;)
    {
      c = es_fgetc (fderr->stream);
      if (c == EOF)
        {
          if (es_feof (fderr->stream))
            {
              fderr->ignore = 1; /* Not anymore needed.  */
            }
          else if (es_ferror (fderr->stream))
            {
              err = my_error_from_syserror ();
              log_error ("error reading stderr of '%s': %s\n",
                         state->pgmname, gpg_strerror (err));
              fderr->ignore = 1; /* Disable.  */
            }

          break;
        }
      else if (c == '\n')
        {
          read_and_log_stderr (state, NULL);
        }
      else
        {
          if (state->used >= sizeof state->buffer - 1)
            {
              read_and_log_stderr (state, NULL);
              state->cont = 1;
            }
          state->buffer[state->used++] = c;
        }
    }
}



/* A buffer to copy from one stream to another.  */
struct copy_buffer
{
  char buffer[4096];
  char *writep;
  size_t nread;
};


/* Initialize a copy buffer.  */
static void
copy_buffer_init (struct copy_buffer *c)
{
  c->writep = c->buffer;
  c->nread = 0;
}


/* Securely wipe a copy buffer.  */
static void
copy_buffer_shred (struct copy_buffer *c)
{
  wipememory (c->buffer, sizeof c->buffer);
  c->writep = NULL;
  c->nread = ~0U;
}


/* Copy data from SOURCE to SINK using copy buffer C.  */
static gpg_error_t
copy_buffer_do_copy (struct copy_buffer *c, estream_t source, estream_t sink)
{
  gpg_error_t err;
  size_t nwritten;

  if (c->nread == 0)
    {
      c->writep = c->buffer;
      err = es_read (source, c->buffer, sizeof c->buffer, &c->nread);
      if (err)
        {
          if (errno == EAGAIN)
            return 0;	/* We will just retry next time.  */

          return my_error_from_syserror ();
        }

      assert (c->nread <= sizeof c->buffer);
    }

  if (c->nread == 0)
    return 0;	/* Done copying.  */


  err = sink? es_write (sink, c->writep, c->nread, &nwritten) : 0;
  if (err)
    {
      if (errno == EAGAIN)
        return 0;	/* We will just retry next time.  */

      return my_error_from_syserror ();
    }

  assert (nwritten <= c->nread);
  c->writep += nwritten;
  c->nread -= nwritten;
  assert (c->writep - c->buffer <= sizeof c->buffer);

  if (sink && es_fflush (sink) && errno != EAGAIN)
    err = my_error_from_syserror ();

  return err;
}


/* Flush the remaining data to SINK.  */
static gpg_error_t
copy_buffer_flush (struct copy_buffer *c, estream_t sink)
{
  gpg_error_t err;

  while (c->nread > 0)
    {
      err = copy_buffer_do_copy (c, NULL, sink);
      if (err)
        return err;
    }

  return 0;
}



/* Run the program PGMNAME with the command line arguments given in
 * the NULL terminates array ARGV.  If INPUT is not NULL it will be
 * fed to stdin of the process.  stderr is logged using log_info and
 * the process' stdout is written to OUTPUT.  If OUTPUT is NULL the
 * output is discarded.  If INEXTRA is given, an additional input
 * stream will be passed to the child; to tell the child about this
 * ARGV is scanned and the first occurrence of an argument
 * "-&@INEXTRA@" is replaced by the concatenation of "-&" and the
 * child's file descriptor of the pipe created for the INEXTRA stream.
 *
 * On error a diagnostic is printed and an error code returned.  */
gpg_error_t
gnupg_exec_tool_stream (const char *pgmname, const char *argv[],
                        estream_t input, estream_t inextra,
                        estream_t output)
{
  gpg_error_t err;
  pid_t pid;
  estream_t infp = NULL;
  estream_t extrafp = NULL;
  estream_t outfp, errfp;
  es_poll_t fds[4];
  int exceptclose[2];
  int extrapipe[2] = {-1, -1};
  char extrafdbuf[20];
  const char *argsave = NULL;
  int argsaveidx;
  int count;
  read_and_log_buffer_t fderrstate;
  struct copy_buffer cpbuf_in, cpbuf_out, cpbuf_extra; /* Fixme: malloc them. */

  memset (fds, 0, sizeof fds);
  memset (&fderrstate, 0, sizeof fderrstate);
  copy_buffer_init (&cpbuf_in);
  copy_buffer_init (&cpbuf_out);
  copy_buffer_init (&cpbuf_extra);

  if (inextra)
    {
      err = gnupg_create_outbound_pipe (extrapipe, &extrafp, 1);
      if (err)
        {
          log_error ("error running outbound pipe for extra fp: %s\n",
                     gpg_strerror (err));
          return err;
        }
      exceptclose[0] = extrapipe[0]; /* Do not close in child. */
      exceptclose[1] = -1;
      /* Now find the argument marker and replace by the pipe's fd.
         Yeah, that is an ugly non-thread safe hack but it safes us to
         create a copy of the array.  */
      snprintf (extrafdbuf, sizeof extrafdbuf, "-&%d", extrapipe[0]);
      for (argsaveidx=0; argv[argsaveidx]; argsaveidx++)
        if (!strcmp (argv[argsaveidx], "-&@INEXTRA@"))
          {
            argsave = argv[argsaveidx];
            argv[argsaveidx] = extrafdbuf;
            break;
          }
    }
  else
    exceptclose[0] = -1;

  err = gnupg_spawn_process (pgmname, argv,
                             exceptclose, NULL, GNUPG_SPAWN_NONBLOCK,
                             input? &infp : NULL,
                             &outfp, &errfp, &pid);
  if (extrapipe[0] != -1)
    close (extrapipe[0]);
  if (argsave)
    argv[argsaveidx] = argsave;
  if (err)
    {
      log_error ("error running '%s': %s\n", pgmname, gpg_strerror (err));
      es_fclose (extrafp);
      return err;
    }

  fderrstate.pgmname = pgmname;

  fds[0].stream = infp;
  fds[0].want_write = 1;
  if (!input)
    fds[0].ignore = 1;
  fds[1].stream = outfp;
  fds[1].want_read = 1;
  fds[2].stream = errfp;
  fds[2].want_read = 1;
  fds[3].stream = extrafp;
  fds[3].want_write = 1;
  if (!inextra)
    fds[3].ignore = 1;

  /* Now read as long as we have something to poll.  We continue
     reading even after EOF or error on stdout so that we get the
     other error messages or remaining outut.  */
  while (!fds[1].ignore && !fds[2].ignore)
    {
      count = es_poll (fds, DIM(fds), -1);
      if (count == -1)
        {
          err = my_error_from_syserror ();
          log_error ("error polling '%s': %s\n", pgmname, gpg_strerror (err));
          goto leave;
        }
      if (!count)
        {
          log_debug ("unexpected timeout while polling '%s'\n", pgmname);
          break;
        }

      if (fds[0].got_write)
        {
          err = copy_buffer_do_copy (&cpbuf_in, input, fds[0].stream);
          if (err)
            {
              log_error ("error feeding data to '%s': %s\n",
                         pgmname, gpg_strerror (err));
              goto leave;
            }

          if (es_feof (input))
            {
              err = copy_buffer_flush (&cpbuf_in, fds[0].stream);
              if (err)
                {
                  log_error ("error feeding data to '%s': %s\n",
                             pgmname, gpg_strerror (err));
                  goto leave;
                }

              fds[0].ignore = 1; /* ready.  */
              es_fclose (infp); infp = NULL;
            }
        }

      if (fds[3].got_write)
        {
          log_assert (inextra);
          err = copy_buffer_do_copy (&cpbuf_extra, inextra, fds[3].stream);
          if (err)
            {
              log_error ("error feeding data to '%s': %s\n",
                         pgmname, gpg_strerror (err));
              goto leave;
            }

          if (es_feof (inextra))
            {
              err = copy_buffer_flush (&cpbuf_extra, fds[3].stream);
              if (err)
                {
                  log_error ("error feeding data to '%s': %s\n",
                             pgmname, gpg_strerror (err));
                  goto leave;
                }

              fds[3].ignore = 1; /* ready.  */
              es_fclose (extrafp); extrafp = NULL;
            }
        }

      if (fds[1].got_read)
        {
          err = copy_buffer_do_copy (&cpbuf_out, fds[1].stream, output);
          if (err)
            {
              log_error ("error reading data from '%s': %s\n",
                         pgmname, gpg_strerror (err));
              goto leave;
            }
        }

      if (fds[2].got_read)
        read_and_log_stderr (&fderrstate, fds + 2);
    }

  err = copy_buffer_flush (&cpbuf_out, output);
  if (err)
    {
      log_error ("error reading data from '%s': %s\n",
                 pgmname, gpg_strerror (err));
      goto leave;
    }

  read_and_log_stderr (&fderrstate, NULL); /* Flush.  */
  es_fclose (infp); infp = NULL;
  es_fclose (extrafp); extrafp = NULL;
  es_fclose (outfp); outfp = NULL;
  es_fclose (errfp); errfp = NULL;

  err = gnupg_wait_process (pgmname, pid, 1, NULL);
  pid = (pid_t)(-1);

 leave:
  if (err)
    gnupg_kill_process (pid);

  es_fclose (infp);
  es_fclose (extrafp);
  es_fclose (outfp);
  es_fclose (errfp);
  if (pid != (pid_t)(-1))
    gnupg_wait_process (pgmname, pid, 1, NULL);
  gnupg_release_process (pid);

  copy_buffer_shred (&cpbuf_in);
  copy_buffer_shred (&cpbuf_out);
  if (inextra)
    copy_buffer_shred (&cpbuf_extra);
  return err;
}


/* A dummy free function to pass to 'es_mopen'.  */
static void
nop_free (void *ptr)
{
  (void) ptr;
}

/* Run the program PGMNAME with the command line arguments given in
   the NULL terminates array ARGV.  If INPUT_STRING is not NULL it
   will be fed to stdin of the process.  stderr is logged using
   log_info and the process' stdout is returned in a newly malloced
   buffer RESULT with the length stored at RESULTLEN if not given as
   NULL.  A hidden Nul is appended to the output.  On error NULL is
   stored at RESULT, a diagnostic is printed, and an error code
   returned.  */
gpg_error_t
gnupg_exec_tool (const char *pgmname, const char *argv[],
                 const char *input_string,
                 char **result, size_t *resultlen)
{
  gpg_error_t err;
  estream_t input = NULL;
  estream_t output;
  size_t len;
  size_t nread;

  *result = NULL;
  if (resultlen)
    *resultlen = 0;

  if (input_string)
    {
      len = strlen (input_string);
      input = es_mopen ((char *) input_string, len, len,
                        0 /* don't grow */, NULL, nop_free, "rb");
      if (! input)
        return my_error_from_syserror ();
    }

  output = es_fopenmem (0, "wb");
  if (! output)
    {
      err = my_error_from_syserror ();
      goto leave;
    }

  err = gnupg_exec_tool_stream (pgmname, argv, input, NULL, output);
  if (err)
    goto leave;

  len = es_ftello (output);
  err = es_fseek (output, 0, SEEK_SET);
  if (err)
    goto leave;

  *result = xtrymalloc (len + 1);
  if (!*result)
    {
      err = my_error_from_syserror ();
      goto leave;
    }

  if (len)
    {
      err = es_read (output, *result, len, &nread);
      if (err)
        goto leave;
      if (nread != len)
        log_fatal ("%s: short read from memstream\n", __func__);
    }
  (*result)[len] = 0;

  if (resultlen)
    *resultlen = len;

 leave:
  es_fclose (input);
  es_fclose (output);
  if (err)
    {
      xfree (*result);
      *result = NULL;
    }
  return err;
}