File: gpgme-w32spawn.c

package info (click to toggle)
gpgme1.0 1.12.0-6
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 10,728 kB
  • sloc: ansic: 46,497; cpp: 17,783; sh: 12,574; python: 5,662; lisp: 1,432; makefile: 973
file content (487 lines) | stat: -rw-r--r-- 12,103 bytes parent folder | download
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
/* gpgme-w32spawn.c - Wrapper to spawn a process under Windows.
   Copyright (C) 2008 g10 Code GmbH

   This file is part of GPGME.

   GPGME is free software; you can redistribute it and/or modify it
   under the terms of the GNU Lesser General Public License as
   published by the Free Software Foundation; either version 2.1 of
   the License, or (at your option) any later version.

   GPGME 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
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with this program; if not, see <https://www.gnu.org/licenses/>.
 */


#ifdef HAVE_CONFIG_H
# include <config.h>
#endif

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <ctype.h>
#include <string.h>
#ifdef HAVE_SYS_TYPES_H
# include <sys/types.h>
#endif
#ifdef HAVE_SYS_STAT_H
# include <sys/stat.h>
#endif
#include <stdint.h>
#include <process.h>

#include "priv-io.h"


/* Name of this program.  */
#define PGM "gpgme-w32spawn"



static char *
build_commandline (char **argv)
{
  int i;
  int n = 0;
  char *buf;
  char *p;

  /* We have to quote some things because under Windows the program
     parses the commandline and does some unquoting.  We enclose the
     whole argument in double-quotes, and escape literal double-quotes
     as well as backslashes with a backslash.  We end up with a
     trailing space at the end of the line, but that is harmless.  */
  for (i = 0; argv[i]; i++)
    {
      p = argv[i];
      /* The leading double-quote.  */
      n++;
      while (*p)
	{
	  /* An extra one for each literal that must be escaped.  */
	  if (*p == '\\' || *p == '"')
	    n++;
	  n++;
	  p++;
	}
      /* The trailing double-quote and the delimiter.  */
      n += 2;
    }
  /* And a trailing zero.  */
  n++;

  buf = p = malloc (n);
  if (!buf)
    return NULL;
  for (i = 0; argv[i]; i++)
    {
      char *argvp = argv[i];

      *(p++) = '"';
      while (*argvp)
	{
	  if (*argvp == '\\' || *argvp == '"')
	    *(p++) = '\\';
	  *(p++) = *(argvp++);
	}
      *(p++) = '"';
      *(p++) = ' ';
    }
  *(p++) = 0;

  return buf;
}


int
my_spawn (char **argv, struct spawn_fd_item_s *fd_list, unsigned int flags)
{
  SECURITY_ATTRIBUTES sec_attr;
  PROCESS_INFORMATION pi =
    {
      NULL,      /* returns process handle */
      0,         /* returns primary thread handle */
      0,         /* returns pid */
      0          /* returns tid */
    };
  STARTUPINFO si;
  char *envblock = NULL;
  int cr_flags = CREATE_DEFAULT_ERROR_MODE
    | GetPriorityClass (GetCurrentProcess ());
  int i;
  char *arg_string;
  int duped_stdin = 0;
  int duped_stdout = 0;
  int duped_stderr = 0;
  HANDLE hnul = INVALID_HANDLE_VALUE;

  i = 0;
  while (argv[i])
    {
      fprintf (stderr, PGM": argv[%2i] = %s\n", i, argv[i]);
      i++;
    }

  memset (&sec_attr, 0, sizeof sec_attr);
  sec_attr.nLength = sizeof sec_attr;
  sec_attr.bInheritHandle = FALSE;

  arg_string = build_commandline (argv);
  if (!arg_string)
    return -1;

  memset (&si, 0, sizeof si);
  si.cb = sizeof (si);
  si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  si.wShowWindow = (flags & IOSPAWN_FLAG_SHOW_WINDOW) ? SW_SHOW : SW_HIDE;
  si.hStdInput = GetStdHandle (STD_INPUT_HANDLE);
  si.hStdOutput = GetStdHandle (STD_OUTPUT_HANDLE);
  si.hStdError = GetStdHandle (STD_ERROR_HANDLE);

  fprintf (stderr, PGM": spawning: %s\n", arg_string);

  for (i = 0; fd_list[i].fd != -1; i++)
    {
      /* The handle already is inheritable.  */
      if (fd_list[i].dup_to == 0)
	{
	  si.hStdInput = (HANDLE) fd_list[i].peer_name;
	  duped_stdin = 1;
	  fprintf (stderr, PGM": dup 0x%x to stdin\n", fd_list[i].peer_name);
        }
      else if (fd_list[i].dup_to == 1)
	{
	  si.hStdOutput = (HANDLE) fd_list[i].peer_name;
	  duped_stdout = 1;
	  fprintf (stderr, PGM": dup 0x%x to stdout\n", fd_list[i].peer_name);
        }
      else if (fd_list[i].dup_to == 2)
	{
	  si.hStdError = (HANDLE) fd_list[i].peer_name;
	  duped_stderr = 1;
	  fprintf (stderr, PGM":dup 0x%x to stderr\n", fd_list[i].peer_name);
        }
    }

  if (!duped_stdin || !duped_stdout || !duped_stderr)
    {
      SECURITY_ATTRIBUTES sa;

      memset (&sa, 0, sizeof sa);
      sa.nLength = sizeof sa;
      sa.bInheritHandle = TRUE;
      hnul = CreateFile ("nul",
			 GENERIC_READ|GENERIC_WRITE,
			 FILE_SHARE_READ|FILE_SHARE_WRITE,
			 &sa,
			 OPEN_EXISTING,
			 FILE_ATTRIBUTE_NORMAL,
			 NULL);
      if (hnul == INVALID_HANDLE_VALUE)
	{
	  free (arg_string);
	  /* FIXME: Should translate the error code.  */
	  errno = EIO;
	  return -1;
        }
      /* Make sure that the process has a connected stdin.  */
      if (!duped_stdin)
	si.hStdInput = hnul;
      /* Make sure that the process has a connected stdout.  */
      if (!duped_stdout)
	si.hStdOutput = hnul;
      /* We normally don't want all the normal output.  */
      if (!duped_stderr)
	si.hStdError = hnul;
    }

  cr_flags |= CREATE_SUSPENDED;
  if (!CreateProcessA (argv[0],
		       arg_string,
		       &sec_attr,     /* process security attributes */
		       &sec_attr,     /* thread security attributes */
		       TRUE,          /* inherit handles */
		       cr_flags,      /* creation flags */
		       envblock,      /* environment */
		       NULL,          /* use current drive/directory */
		       &si,           /* startup information */
		       &pi))          /* returns process information */
    {
      free (arg_string);
      /* FIXME: Should translate the error code.  */
      errno = EIO;
      return -1;
    }

  free (arg_string);

  /* Close the /dev/nul handle if used.  */
  if (hnul != INVALID_HANDLE_VALUE)
    CloseHandle (hnul);

  for (i = 0; fd_list[i].fd != -1; i++)
    CloseHandle ((HANDLE) fd_list[i].fd);

  if (flags & IOSPAWN_FLAG_ALLOW_SET_FG)
    {
      static int initialized;
      static BOOL (WINAPI * func)(DWORD);
      void *handle;

      if (!initialized)
        {
          /* Available since W2000; thus we dynload it.  */
          initialized = 1;
          handle = LoadLibrary ("user32.dll");
          if (handle)
            {
              func = GetProcAddress (handle, "AllowSetForegroundWindow");
              if (!func)
                FreeLibrary (handle);
            }
        }

      if (func)
        {
          int rc = func (pi.dwProcessId);
          fprintf (stderr, PGM": AllowSetForegroundWindow(%d): rc=%d\n",
                   (int)pi.dwProcessId, rc);
        }
    }

  ResumeThread (pi.hThread);
  CloseHandle (pi.hThread);
  CloseHandle (pi.hProcess);

  return 0;
}


#define MAX_TRANS 10

int
translate_get_from_file (const char *trans_file,
			 struct spawn_fd_item_s *fd_list,
                         unsigned int *r_flags)
{
  /* Hold roughly MAX_TRANS triplets of 64 bit numbers in hex
     notation: "0xFEDCBA9876543210".  10*19*4 - 1 = 759.  This plans
     ahead for a time when a HANDLE is 64 bit.  */
#define BUFFER_MAX 810

  char line[BUFFER_MAX + 1];
  char *linep;
  int idx;
  int res;
  int fd;

  *r_flags = 0;

  fd = open (trans_file, O_RDONLY);
  if (fd < 0)
    return -1;

  /* We always read one line from stdin.  */
  res = read (fd, line, BUFFER_MAX);
  close (fd);
  if (res < 0)
    return -1;

  line[BUFFER_MAX] = '\0';
  linep = strchr (line, '\n');
  if (linep)
    {
      if (linep > line && linep[-1] == '\r')
        linep--;
      *linep = '\0';
    }
  linep = line;

  /* Now start to read mapping pairs.  */
  for (idx = 0; idx < MAX_TRANS; idx++)
    {
      unsigned long from;
      long dup_to;
      unsigned long to;
      unsigned long loc;
      char *tail;

      /* FIXME: Maybe could use scanf.  */
      while (isspace (*((unsigned char *)linep)))
	linep++;
      if (*linep == '\0')
	break;
      if (!idx && *linep == '~')
        {
          /* Spawn flags have been passed.  */
          linep++;
          *r_flags = strtoul (linep, &tail, 0);
          if (tail == NULL || ! (*tail == '\0' || isspace (*tail)))
            break;
          linep = tail;

          while (isspace (*((unsigned char *)linep)))
            linep++;
          if (*linep == '\0')
            break;
        }

      from = strtoul (linep, &tail, 0);
      if (tail == NULL || ! (*tail == '\0' || isspace (*tail)))
	break;
      linep = tail;

      while (isspace (*linep))
	linep++;
      if (*linep == '\0')
	break;
      dup_to = strtol (linep, &tail, 0);
      if (tail == NULL || ! (*tail == '\0' || isspace (*tail)))
	break;
      linep = tail;

      while (isspace (*linep))
	linep++;
      if (*linep == '\0')
	break;
      to = strtoul (linep, &tail, 0);
      if (tail == NULL || ! (*tail == '\0' || isspace (*tail)))
	break;
      linep = tail;

      while (isspace (*linep))
	linep++;
      if (*linep == '\0')
	break;
      loc = strtoul (linep, &tail, 0);
      if (tail == NULL || ! (*tail == '\0' || isspace (*tail)))
	break;
      linep = tail;

      fd_list[idx].fd = from;
      fd_list[idx].dup_to = dup_to;
      fd_list[idx].peer_name = to;
      fd_list[idx].arg_loc = loc;
    }
  fd_list[idx].fd = -1;
  fd_list[idx].dup_to = -1;
  fd_list[idx].peer_name = -1;
  fd_list[idx].arg_loc = 0;
  return 0;
}


/* Read the translated handles from TRANS_FILE and do a substitution
   in ARGV.  Returns the new argv and the list of substitutions in
   FD_LIST (which must be MAX_TRANS+1 large).  */
char **
translate_handles (const char *trans_file, const char * const *argv,
		   struct spawn_fd_item_s *fd_list, unsigned int *r_flags)
{
  int res;
  int idx;
  int n_args;
  char **args;

  res = translate_get_from_file (trans_file, fd_list, r_flags);
  if (res < 0)
    return NULL;

  for (idx = 0; argv[idx]; idx++)
    ;
  args = malloc (sizeof (*args) * (idx + 1));
  for (idx = 0; argv[idx]; idx++)
    {
      args[idx] = strdup (argv[idx]);
      if (!args[idx])
	return NULL;
    }
  args[idx] = NULL;
  n_args = idx;

  for (idx = 0; fd_list[idx].fd != -1; idx++)
    {
      char buf[25];
      int aidx;

      aidx = fd_list[idx].arg_loc;
      if (aidx == 0)
	continue;

      if (aidx >= n_args)
        {
	  fprintf (stderr, PGM": translation file does not match args\n");
          return NULL;
        }

      args[aidx] = malloc (sizeof (buf));
      /* We currently disable translation for stdin/stdout/stderr.  We
	 assume that the spawned program handles 0/1/2 specially
	 already.  FIXME: Check if this is true.  */
      if (!args[idx] || fd_list[idx].dup_to != -1)
	return NULL;

      /* NOTE: Here is the part where application specific knowledge
	 comes in.  GPGME/GnuPG uses two forms of descriptor
	 specification, a plain number and a "-&" form.  */
      if (argv[aidx][0] == '-' && argv[aidx][1] == '&')
	snprintf (args[aidx], sizeof (buf), "-&%d", fd_list[idx].peer_name);
      else
	snprintf (args[aidx], sizeof (buf), "%d", fd_list[idx].peer_name);
    }
  return args;
}


int
main (int argc, const char * const *argv)
{
  int rc = 0;
  char **argv_spawn;
  struct spawn_fd_item_s fd_list[MAX_TRANS + 1];
  unsigned int flags;

  if (argc < 3)
    {
      rc = 2;
      goto leave;
    }

  argv_spawn = translate_handles (argv[1], &argv[2], fd_list, &flags);
  if (!argv_spawn)
    {
      rc = 2;
      goto leave;
    }

  /* Using execv does not replace the existing program image, but
     spawns a new one and daemonizes it, confusing the command line
     interpreter.  So we have to use spawnv.  */
  rc = my_spawn (argv_spawn, fd_list, flags);
  if (rc < 0)
    {
      fprintf (stderr, PGM": executing `%s' failed: %s\n",
	       argv[0], strerror (errno));
      rc = 2;
      goto leave;
    }

 leave:
  if (rc)
    fprintf (stderr, PGM": internal error\n");
  /* Always try to delete the temporary file.  */
  if (argc >= 2)
    {
      if (DeleteFile (argv[1]) == 0)
	fprintf (stderr, PGM": failed to delete %s: ec=%ld\n",
		 argv[1], GetLastError ());
    }
  return rc;
}