agent/
[gnupg.git] / g10 / exec.c
blob6ab24793f897ad8f6021b290e20054b3802429b4
1 /* exec.c - generic call-a-program code
2 * Copyright (C) 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
4 * This file is part of GnuPG.
6 * GnuPG is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
11 * GnuPG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, see <http://www.gnu.org/licenses/>.
20 /*
21 FIXME: We should replace most code in this module by our
22 spawn implementation from common/exechelp.c.
26 #include <config.h>
27 #include <stdlib.h>
28 #include <stdarg.h>
29 #include <stdio.h>
30 #include <sys/stat.h>
31 #include <sys/types.h>
32 #ifndef EXEC_TEMPFILE_ONLY
33 #include <sys/wait.h>
34 #endif
35 #ifdef HAVE_DOSISH_SYSTEM
36 #include <windows.h>
37 #endif
38 #include <fcntl.h>
39 #include <unistd.h>
40 #include <string.h>
41 #include <errno.h>
43 #include "gpg.h"
44 #include "options.h"
45 #include "i18n.h"
46 #include "iobuf.h"
47 #include "util.h"
48 #include "mkdtemp.h" /* From gnulib. */
49 #include "membuf.h"
50 #include "exec.h"
52 #ifdef NO_EXEC
53 int
54 exec_write(struct exec_info **info,const char *program,
55 const char *args_in,const char *name,int writeonly,int binary)
57 log_error(_("no remote program execution supported\n"));
58 return G10ERR_GENERAL;
61 int
62 exec_read(struct exec_info *info) { return G10ERR_GENERAL; }
63 int
64 exec_finish(struct exec_info *info) { return G10ERR_GENERAL; }
65 int
66 set_exec_path(const char *path) { return G10ERR_GENERAL; }
68 #else /* ! NO_EXEC */
70 #if defined (_WIN32)
71 /* This is a nicer system() for windows that waits for programs to
72 return before returning control to the caller. I hate helpful
73 computers. */
74 static int
75 w32_system(const char *command)
77 PROCESS_INFORMATION pi;
78 STARTUPINFO si;
79 char *string;
81 /* We must use a copy of the command as CreateProcess modifies this
82 argument. */
83 string=xstrdup(command);
85 memset(&pi,0,sizeof(pi));
86 memset(&si,0,sizeof(si));
87 si.cb=sizeof(si);
89 if(!CreateProcess(NULL,string,NULL,NULL,FALSE,
90 DETACHED_PROCESS,
91 NULL,NULL,&si,&pi))
92 return -1;
94 /* Wait for the child to exit */
95 WaitForSingleObject(pi.hProcess,INFINITE);
97 CloseHandle(pi.hProcess);
98 CloseHandle(pi.hThread);
99 xfree(string);
101 return 0;
103 #endif
105 /* Replaces current $PATH */
106 int
107 set_exec_path(const char *path)
109 char *p;
111 p=xmalloc(5+strlen(path)+1);
112 strcpy(p,"PATH=");
113 strcat(p,path);
115 if(DBG_EXTPROG)
116 log_debug("set_exec_path: %s\n",p);
118 /* Notice that path is never freed. That is intentional due to the
119 way putenv() works. This leaks a few bytes if we call
120 set_exec_path multiple times. */
122 if(putenv(p)!=0)
123 return G10ERR_GENERAL;
124 else
125 return 0;
128 /* Makes a temp directory and filenames */
129 static int
130 make_tempdir(struct exec_info *info)
132 char *tmp=opt.temp_dir,*namein=info->name,*nameout;
134 if(!namein)
135 namein=info->flags.binary?"tempin" EXTSEP_S "bin":"tempin" EXTSEP_S "txt";
137 nameout=info->flags.binary?"tempout" EXTSEP_S "bin":"tempout" EXTSEP_S "txt";
139 /* Make up the temp dir and files in case we need them */
141 if(tmp==NULL)
143 #if defined (_WIN32)
144 int err;
146 tmp=xmalloc(MAX_PATH+2);
147 err=GetTempPath(MAX_PATH+1,tmp);
148 if(err==0 || err>MAX_PATH+1)
149 strcpy(tmp,"c:\\windows\\temp");
150 else
152 int len=strlen(tmp);
154 /* GetTempPath may return with \ on the end */
155 while(len>0 && tmp[len-1]=='\\')
157 tmp[len-1]='\0';
158 len--;
161 #else /* More unixish systems */
162 tmp=getenv("TMPDIR");
163 if(tmp==NULL)
165 tmp=getenv("TMP");
166 if(tmp==NULL)
168 #ifdef __riscos__
169 tmp="<Wimp$ScrapDir>.GnuPG";
170 mkdir(tmp,0700); /* Error checks occur later on */
171 #else
172 tmp="/tmp";
173 #endif
176 #endif
179 info->tempdir=xmalloc(strlen(tmp)+strlen(DIRSEP_S)+10+1);
181 sprintf(info->tempdir,"%s" DIRSEP_S "gpg-XXXXXX",tmp);
183 #if defined (_WIN32)
184 xfree(tmp);
185 #endif
187 if(mkdtemp(info->tempdir)==NULL)
188 log_error(_("can't create directory `%s': %s\n"),
189 info->tempdir,strerror(errno));
190 else
192 info->flags.madedir=1;
194 info->tempfile_in=xmalloc(strlen(info->tempdir)+
195 strlen(DIRSEP_S)+strlen(namein)+1);
196 sprintf(info->tempfile_in,"%s" DIRSEP_S "%s",info->tempdir,namein);
198 if(!info->flags.writeonly)
200 info->tempfile_out=xmalloc(strlen(info->tempdir)+
201 strlen(DIRSEP_S)+strlen(nameout)+1);
202 sprintf(info->tempfile_out,"%s" DIRSEP_S "%s",info->tempdir,nameout);
206 return info->flags.madedir?0:G10ERR_GENERAL;
209 /* Expands %i and %o in the args to the full temp files within the
210 temp directory. */
211 static int
212 expand_args(struct exec_info *info,const char *args_in)
214 const char *ch = args_in;
215 membuf_t command;
217 info->flags.use_temp_files=0;
218 info->flags.keep_temp_files=0;
220 if(DBG_EXTPROG)
221 log_debug("expanding string \"%s\"\n",args_in);
223 init_membuf (&command, 100);
225 while(*ch!='\0')
227 if(*ch=='%')
229 char *append=NULL;
231 ch++;
233 switch(*ch)
235 case 'O':
236 info->flags.keep_temp_files=1;
237 /* fall through */
239 case 'o': /* out */
240 if(!info->flags.madedir)
242 if(make_tempdir(info))
243 goto fail;
245 append=info->tempfile_out;
246 info->flags.use_temp_files=1;
247 break;
249 case 'I':
250 info->flags.keep_temp_files=1;
251 /* fall through */
253 case 'i': /* in */
254 if(!info->flags.madedir)
256 if(make_tempdir(info))
257 goto fail;
259 append=info->tempfile_in;
260 info->flags.use_temp_files=1;
261 break;
263 case '%':
264 append="%";
265 break;
268 if(append)
269 put_membuf_str (&command, append);
271 else
272 put_membuf (&command, ch, 1);
274 ch++;
277 put_membuf (&command, "", 1); /* Terminate string. */
279 info->command = get_membuf (&command, NULL);
280 if (!info->command)
281 return gpg_error_from_syserror ();
283 if(DBG_EXTPROG)
284 log_debug("args expanded to \"%s\", use %u, keep %u\n",info->command,
285 info->flags.use_temp_files,info->flags.keep_temp_files);
287 return 0;
289 fail:
290 xfree (get_membuf (&command, NULL));
291 return G10ERR_GENERAL;
294 /* Either handles the tempfile creation, or the fork/exec. If it
295 returns ok, then info->tochild is a FILE * that can be written to.
296 The rules are: if there are no args, then it's a fork/exec/pipe.
297 If there are args, but no tempfiles, then it's a fork/exec/pipe via
298 shell -c. If there are tempfiles, then it's a system. */
300 int
301 exec_write(struct exec_info **info,const char *program,
302 const char *args_in,const char *name,int writeonly,int binary)
304 int ret=G10ERR_GENERAL;
306 if(opt.exec_disable && !opt.no_perm_warn)
308 log_info(_("external program calls are disabled due to unsafe "
309 "options file permissions\n"));
311 return ret;
314 #if defined(HAVE_GETUID) && defined(HAVE_GETEUID)
315 /* There should be no way to get to this spot while still carrying
316 setuid privs. Just in case, bomb out if we are. */
317 if ( getuid () != geteuid ())
318 BUG ();
319 #endif
321 if(program==NULL && args_in==NULL)
322 BUG();
324 *info=xmalloc_clear(sizeof(struct exec_info));
326 if(name)
327 (*info)->name=xstrdup(name);
328 (*info)->flags.binary=binary;
329 (*info)->flags.writeonly=writeonly;
331 /* Expand the args, if any */
332 if(args_in && expand_args(*info,args_in))
333 goto fail;
335 #ifdef EXEC_TEMPFILE_ONLY
336 if(!(*info)->flags.use_temp_files)
338 log_error(_("this platform requires temporary files when calling"
339 " external programs\n"));
340 goto fail;
343 #else /* !EXEC_TEMPFILE_ONLY */
345 /* If there are no args, or there are args, but no temp files, we
346 can use fork/exec/pipe */
347 if(args_in==NULL || (*info)->flags.use_temp_files==0)
349 int to[2],from[2];
351 if(pipe(to)==-1)
352 goto fail;
354 if(pipe(from)==-1)
356 close(to[0]);
357 close(to[1]);
358 goto fail;
361 if(((*info)->child=fork())==-1)
363 close(to[0]);
364 close(to[1]);
365 close(from[0]);
366 close(from[1]);
367 goto fail;
370 if((*info)->child==0)
372 char *shell=getenv("SHELL");
374 if(shell==NULL)
375 shell="/bin/sh";
377 /* I'm the child */
379 /* If the program isn't going to respond back, they get to
380 keep their stdout/stderr */
381 if(!(*info)->flags.writeonly)
383 /* implied close of STDERR */
384 if(dup2(STDOUT_FILENO,STDERR_FILENO)==-1)
385 _exit(1);
387 /* implied close of STDOUT */
388 close(from[0]);
389 if(dup2(from[1],STDOUT_FILENO)==-1)
390 _exit(1);
393 /* implied close of STDIN */
394 close(to[1]);
395 if(dup2(to[0],STDIN_FILENO)==-1)
396 _exit(1);
398 if(args_in==NULL)
400 if(DBG_EXTPROG)
401 log_debug("execlp: %s\n",program);
403 execlp(program,program,(void *)NULL);
405 else
407 if(DBG_EXTPROG)
408 log_debug("execlp: %s -c %s\n",shell,(*info)->command);
410 execlp(shell,shell,"-c",(*info)->command,(void *)NULL);
413 /* If we get this far the exec failed. Clean up and return. */
415 if(args_in==NULL)
416 log_error(_("unable to execute program `%s': %s\n"),
417 program,strerror(errno));
418 else
419 log_error(_("unable to execute shell `%s': %s\n"),
420 shell,strerror(errno));
422 /* This mimics the POSIX sh behavior - 127 means "not found"
423 from the shell. */
424 if(errno==ENOENT)
425 _exit(127);
427 _exit(1);
430 /* I'm the parent */
432 close(to[0]);
434 (*info)->tochild=fdopen(to[1],binary?"wb":"w");
435 if((*info)->tochild==NULL)
437 ret = gpg_error_from_syserror ();
438 close(to[1]);
439 goto fail;
442 close(from[1]);
444 (*info)->fromchild=iobuf_fdopen(from[0],"r");
445 if((*info)->fromchild==NULL)
447 ret = gpg_error_from_syserror ();
448 close(from[0]);
449 goto fail;
452 /* fd iobufs are cached?! */
453 iobuf_ioctl((*info)->fromchild,3,1,NULL);
455 return 0;
457 #endif /* !EXEC_TEMPFILE_ONLY */
459 if(DBG_EXTPROG)
460 log_debug("using temp file `%s'\n",(*info)->tempfile_in);
462 /* It's not fork/exec/pipe, so create a temp file */
463 if( is_secured_filename ((*info)->tempfile_in) )
465 (*info)->tochild = NULL;
466 errno = EPERM;
468 else
469 (*info)->tochild=fopen((*info)->tempfile_in,binary?"wb":"w");
470 if((*info)->tochild==NULL)
472 ret = gpg_error_from_syserror ();
473 log_error(_("can't create `%s': %s\n"),
474 (*info)->tempfile_in,strerror(errno));
475 goto fail;
478 ret=0;
480 fail:
481 if (ret)
483 xfree (*info);
484 *info = NULL;
486 return ret;
490 exec_read(struct exec_info *info)
492 int ret=G10ERR_GENERAL;
494 fclose(info->tochild);
495 info->tochild=NULL;
497 if(info->flags.use_temp_files)
499 if(DBG_EXTPROG)
500 log_debug("system() command is %s\n",info->command);
502 #if defined (_WIN32)
503 info->progreturn=w32_system(info->command);
504 #else
505 info->progreturn=system(info->command);
506 #endif
508 if(info->progreturn==-1)
510 log_error(_("system error while calling external program: %s\n"),
511 strerror(errno));
512 info->progreturn=127;
513 goto fail;
516 #if defined(WIFEXITED) && defined(WEXITSTATUS)
517 if(WIFEXITED(info->progreturn))
518 info->progreturn=WEXITSTATUS(info->progreturn);
519 else
521 log_error(_("unnatural exit of external program\n"));
522 info->progreturn=127;
523 goto fail;
525 #else
526 /* If we don't have the macros, do the best we can. */
527 info->progreturn = (info->progreturn & 0xff00) >> 8;
528 #endif
530 /* 127 is the magic value returned from system() to indicate
531 that the shell could not be executed, or from /bin/sh to
532 indicate that the program could not be executed. */
534 if(info->progreturn==127)
536 log_error(_("unable to execute external program\n"));
537 goto fail;
540 if(!info->flags.writeonly)
542 info->fromchild=iobuf_open(info->tempfile_out);
543 if (info->fromchild
544 && is_secured_file (iobuf_get_fd (info->fromchild)))
546 iobuf_close (info->fromchild);
547 info->fromchild = NULL;
548 errno = EPERM;
550 if(info->fromchild==NULL)
552 ret = gpg_error_from_syserror ();
553 log_error(_("unable to read external program response: %s\n"),
554 strerror(errno));
555 goto fail;
558 /* Do not cache this iobuf on close */
559 iobuf_ioctl(info->fromchild,3,1,NULL);
563 ret=0;
565 fail:
566 return ret;
570 exec_finish(struct exec_info *info)
572 int ret=info->progreturn;
574 if(info->fromchild)
575 iobuf_close(info->fromchild);
577 if(info->tochild)
578 fclose(info->tochild);
580 #ifndef EXEC_TEMPFILE_ONLY
581 if(info->child>0)
583 if(waitpid(info->child,&info->progreturn,0)!=0 &&
584 WIFEXITED(info->progreturn))
585 ret=WEXITSTATUS(info->progreturn);
586 else
588 log_error(_("unnatural exit of external program\n"));
589 ret=127;
592 #endif
594 if(info->flags.madedir && !info->flags.keep_temp_files)
596 if(info->tempfile_in)
598 if(unlink(info->tempfile_in)==-1)
599 log_info(_("WARNING: unable to remove tempfile (%s) `%s': %s\n"),
600 "in",info->tempfile_in,strerror(errno));
603 if(info->tempfile_out)
605 if(unlink(info->tempfile_out)==-1)
606 log_info(_("WARNING: unable to remove tempfile (%s) `%s': %s\n"),
607 "out",info->tempfile_out,strerror(errno));
610 if(rmdir(info->tempdir)==-1)
611 log_info(_("WARNING: unable to remove temp directory `%s': %s\n"),
612 info->tempdir,strerror(errno));
615 xfree(info->command);
616 xfree(info->name);
617 xfree(info->tempdir);
618 xfree(info->tempfile_in);
619 xfree(info->tempfile_out);
620 xfree(info);
622 return ret;
624 #endif /* ! NO_EXEC */