2006-09-06 Marcus Brinkmann <marcus@g10code.de>
[gnupg.git] / g10 / exec.c
blob203c4c78f56e41a6a28e8466a107176db71a2aa5
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 2 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, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
19 * USA.
22 #include <config.h>
23 #include <stdlib.h>
24 #include <stdarg.h>
25 #include <stdio.h>
26 #include <sys/stat.h>
27 #include <sys/types.h>
28 #ifndef EXEC_TEMPFILE_ONLY
29 #include <sys/wait.h>
30 #endif
31 #ifdef HAVE_DOSISH_SYSTEM
32 #include <windows.h>
33 #endif
34 #include <fcntl.h>
35 #include <unistd.h>
36 #include <string.h>
37 #include <errno.h>
39 #include "gpg.h"
40 #include "options.h"
41 #include "i18n.h"
42 #include "iobuf.h"
43 #include "util.h"
44 #include "mkdtemp.h" /* From gnulib. */
45 #include "exec.h"
47 #ifdef NO_EXEC
48 int exec_write(struct exec_info **info,const char *program,
49 const char *args_in,const char *name,int writeonly,int binary)
51 log_error(_("no remote program execution supported\n"));
52 return G10ERR_GENERAL;
55 int exec_read(struct exec_info *info) { return G10ERR_GENERAL; }
56 int exec_finish(struct exec_info *info) { return G10ERR_GENERAL; }
57 int set_exec_path(const char *path) { return G10ERR_GENERAL; }
59 #else /* ! NO_EXEC */
61 #if defined (_WIN32)
62 /* This is a nicer system() for windows that waits for programs to
63 return before returning control to the caller. I hate helpful
64 computers. */
65 static int w32_system(const char *command)
67 PROCESS_INFORMATION pi;
68 STARTUPINFO si;
69 char *string;
71 /* We must use a copy of the command as CreateProcess modifies this
72 argument. */
73 string=xstrdup(command);
75 memset(&pi,0,sizeof(pi));
76 memset(&si,0,sizeof(si));
77 si.cb=sizeof(si);
79 if(!CreateProcess(NULL,string,NULL,NULL,FALSE,0,NULL,NULL,&si,&pi))
80 return -1;
82 /* Wait for the child to exit */
83 WaitForSingleObject(pi.hProcess,INFINITE);
85 CloseHandle(pi.hProcess);
86 CloseHandle(pi.hThread);
87 xfree(string);
89 return 0;
91 #endif
93 /* Replaces current $PATH */
94 int set_exec_path(const char *path)
96 char *p;
98 p=xmalloc(5+strlen(path)+1);
99 strcpy(p,"PATH=");
100 strcat(p,path);
102 if(DBG_EXTPROG)
103 log_debug("set_exec_path: %s\n",p);
105 /* Notice that path is never freed. That is intentional due to the
106 way putenv() works. This leaks a few bytes if we call
107 set_exec_path multiple times. */
109 if(putenv(p)!=0)
110 return G10ERR_GENERAL;
111 else
112 return 0;
115 /* Makes a temp directory and filenames */
116 static int make_tempdir(struct exec_info *info)
118 char *tmp=opt.temp_dir,*namein=info->name,*nameout;
120 if(!namein)
121 namein=info->flags.binary?"tempin" EXTSEP_S "bin":"tempin" EXTSEP_S "txt";
123 nameout=info->flags.binary?"tempout" EXTSEP_S "bin":"tempout" EXTSEP_S "txt";
125 /* Make up the temp dir and files in case we need them */
127 if(tmp==NULL)
129 #if defined (_WIN32)
130 int err;
132 tmp=xmalloc(MAX_PATH+2);
133 err=GetTempPath(MAX_PATH+1,tmp);
134 if(err==0 || err>MAX_PATH+1)
135 strcpy(tmp,"c:\\windows\\temp");
136 else
138 int len=strlen(tmp);
140 /* GetTempPath may return with \ on the end */
141 while(len>0 && tmp[len-1]=='\\')
143 tmp[len-1]='\0';
144 len--;
147 #else /* More unixish systems */
148 tmp=getenv("TMPDIR");
149 if(tmp==NULL)
151 tmp=getenv("TMP");
152 if(tmp==NULL)
154 #ifdef __riscos__
155 tmp="<Wimp$ScrapDir>.GnuPG";
156 mkdir(tmp,0700); /* Error checks occur later on */
157 #else
158 tmp="/tmp";
159 #endif
162 #endif
165 info->tempdir=xmalloc(strlen(tmp)+strlen(DIRSEP_S)+10+1);
167 sprintf(info->tempdir,"%s" DIRSEP_S "gpg-XXXXXX",tmp);
169 #if defined (_WIN32)
170 xfree(tmp);
171 #endif
173 if(mkdtemp(info->tempdir)==NULL)
174 log_error(_("can't create directory `%s': %s\n"),
175 info->tempdir,strerror(errno));
176 else
178 info->flags.madedir=1;
180 info->tempfile_in=xmalloc(strlen(info->tempdir)+
181 strlen(DIRSEP_S)+strlen(namein)+1);
182 sprintf(info->tempfile_in,"%s" DIRSEP_S "%s",info->tempdir,namein);
184 if(!info->flags.writeonly)
186 info->tempfile_out=xmalloc(strlen(info->tempdir)+
187 strlen(DIRSEP_S)+strlen(nameout)+1);
188 sprintf(info->tempfile_out,"%s" DIRSEP_S "%s",info->tempdir,nameout);
192 return info->flags.madedir?0:G10ERR_GENERAL;
195 /* Expands %i and %o in the args to the full temp files within the
196 temp directory. */
197 static int expand_args(struct exec_info *info,const char *args_in)
199 const char *ch=args_in;
200 unsigned int size,len;
202 info->flags.use_temp_files=0;
203 info->flags.keep_temp_files=0;
205 if(DBG_EXTPROG)
206 log_debug("expanding string \"%s\"\n",args_in);
208 size=100;
209 info->command=xmalloc(size);
210 len=0;
211 info->command[0]='\0';
213 while(*ch!='\0')
215 if(*ch=='%')
217 char *append=NULL;
219 ch++;
221 switch(*ch)
223 case 'O':
224 info->flags.keep_temp_files=1;
225 /* fall through */
227 case 'o': /* out */
228 if(!info->flags.madedir)
230 if(make_tempdir(info))
231 goto fail;
233 append=info->tempfile_out;
234 info->flags.use_temp_files=1;
235 break;
237 case 'I':
238 info->flags.keep_temp_files=1;
239 /* fall through */
241 case 'i': /* in */
242 if(!info->flags.madedir)
244 if(make_tempdir(info))
245 goto fail;
247 append=info->tempfile_in;
248 info->flags.use_temp_files=1;
249 break;
251 case '%':
252 append="%";
253 break;
256 if(append)
258 size_t applen=strlen(append);
260 if(applen+len>size-1)
262 if(applen<100)
263 applen=100;
265 size+=applen;
266 info->command=xrealloc(info->command,size);
269 strcat(info->command,append);
270 len+=strlen(append);
273 else
275 if(len==size-1) /* leave room for the \0 */
277 size+=100;
278 info->command=xrealloc(info->command,size);
281 info->command[len++]=*ch;
282 info->command[len]='\0';
285 ch++;
288 if(DBG_EXTPROG)
289 log_debug("args expanded to \"%s\", use %u, keep %u\n",info->command,
290 info->flags.use_temp_files,info->flags.keep_temp_files);
292 return 0;
294 fail:
296 xfree(info->command);
297 info->command=NULL;
299 return G10ERR_GENERAL;
302 /* Either handles the tempfile creation, or the fork/exec. If it
303 returns ok, then info->tochild is a FILE * that can be written to.
304 The rules are: if there are no args, then it's a fork/exec/pipe.
305 If there are args, but no tempfiles, then it's a fork/exec/pipe via
306 shell -c. If there are tempfiles, then it's a system. */
308 int exec_write(struct exec_info **info,const char *program,
309 const char *args_in,const char *name,int writeonly,int binary)
311 int ret=G10ERR_GENERAL;
313 if(opt.exec_disable && !opt.no_perm_warn)
315 log_info(_("external program calls are disabled due to unsafe "
316 "options file permissions\n"));
318 return ret;
321 #if defined(HAVE_GETUID) && defined(HAVE_GETEUID)
322 /* There should be no way to get to this spot while still carrying
323 setuid privs. Just in case, bomb out if we are. */
324 if(getuid()!=geteuid())
325 BUG();
326 #endif
328 if(program==NULL && args_in==NULL)
329 BUG();
331 *info=xmalloc_clear(sizeof(struct exec_info));
333 if(name)
334 (*info)->name=xstrdup(name);
335 (*info)->flags.binary=binary;
336 (*info)->flags.writeonly=writeonly;
338 /* Expand the args, if any */
339 if(args_in && expand_args(*info,args_in))
340 goto fail;
342 #ifdef EXEC_TEMPFILE_ONLY
343 if(!(*info)->flags.use_temp_files)
345 log_error(_("this platform requires temporary files when calling"
346 " external programs\n"));
347 goto fail;
350 #else /* !EXEC_TEMPFILE_ONLY */
352 /* If there are no args, or there are args, but no temp files, we
353 can use fork/exec/pipe */
354 if(args_in==NULL || (*info)->flags.use_temp_files==0)
356 int to[2],from[2];
358 if(pipe(to)==-1)
359 goto fail;
361 if(pipe(from)==-1)
363 close(to[0]);
364 close(to[1]);
365 goto fail;
368 if(((*info)->child=fork())==-1)
370 close(to[0]);
371 close(to[1]);
372 close(from[0]);
373 close(from[1]);
374 goto fail;
377 if((*info)->child==0)
379 char *shell=getenv("SHELL");
381 if(shell==NULL)
382 shell="/bin/sh";
384 /* I'm the child */
386 /* If the program isn't going to respond back, they get to
387 keep their stdout/stderr */
388 if(!(*info)->flags.writeonly)
390 /* implied close of STDERR */
391 if(dup2(STDOUT_FILENO,STDERR_FILENO)==-1)
392 _exit(1);
394 /* implied close of STDOUT */
395 close(from[0]);
396 if(dup2(from[1],STDOUT_FILENO)==-1)
397 _exit(1);
400 /* implied close of STDIN */
401 close(to[1]);
402 if(dup2(to[0],STDIN_FILENO)==-1)
403 _exit(1);
405 if(args_in==NULL)
407 if(DBG_EXTPROG)
408 log_debug("execlp: %s\n",program);
410 execlp(program,program,(void *)NULL);
412 else
414 if(DBG_EXTPROG)
415 log_debug("execlp: %s -c %s\n",shell,(*info)->command);
417 execlp(shell,shell,"-c",(*info)->command,(void *)NULL);
420 /* If we get this far the exec failed. Clean up and return. */
422 if(args_in==NULL)
423 log_error(_("unable to execute program `%s': %s\n"),
424 program,strerror(errno));
425 else
426 log_error(_("unable to execute shell `%s': %s\n"),
427 shell,strerror(errno));
429 /* This mimics the POSIX sh behavior - 127 means "not found"
430 from the shell. */
431 if(errno==ENOENT)
432 _exit(127);
434 _exit(1);
437 /* I'm the parent */
439 close(to[0]);
441 (*info)->tochild=fdopen(to[1],binary?"wb":"w");
442 if((*info)->tochild==NULL)
444 ret = gpg_error_from_errno (errno);
445 close(to[1]);
446 goto fail;
449 close(from[1]);
451 (*info)->fromchild=iobuf_fdopen(from[0],"r");
452 if((*info)->fromchild==NULL)
454 ret = gpg_error_from_errno (errno);
455 close(from[0]);
456 goto fail;
459 /* fd iobufs are cached?! */
460 iobuf_ioctl((*info)->fromchild,3,1,NULL);
462 return 0;
464 #endif /* !EXEC_TEMPFILE_ONLY */
466 if(DBG_EXTPROG)
467 log_debug("using temp file `%s'\n",(*info)->tempfile_in);
469 /* It's not fork/exec/pipe, so create a temp file */
470 if( is_secured_filename ((*info)->tempfile_in) )
472 (*info)->tochild = NULL;
473 errno = EPERM;
475 else
476 (*info)->tochild=fopen((*info)->tempfile_in,binary?"wb":"w");
477 if((*info)->tochild==NULL)
479 ret = gpg_error_from_errno (errno);
480 log_error(_("can't create `%s': %s\n"),
481 (*info)->tempfile_in,strerror(errno));
482 goto fail;
485 ret=0;
487 fail:
488 return ret;
491 int exec_read(struct exec_info *info)
493 int ret=G10ERR_GENERAL;
495 fclose(info->tochild);
496 info->tochild=NULL;
498 if(info->flags.use_temp_files)
500 if(DBG_EXTPROG)
501 log_debug("system() command is %s\n",info->command);
503 #if defined (_WIN32)
504 info->progreturn=w32_system(info->command);
505 #else
506 info->progreturn=system(info->command);
507 #endif
509 if(info->progreturn==-1)
511 log_error(_("system error while calling external program: %s\n"),
512 strerror(errno));
513 info->progreturn=127;
514 goto fail;
517 #if defined(WIFEXITED) && defined(WEXITSTATUS)
518 if(WIFEXITED(info->progreturn))
519 info->progreturn=WEXITSTATUS(info->progreturn);
520 else
522 log_error(_("unnatural exit of external program\n"));
523 info->progreturn=127;
524 goto fail;
526 #else
527 /* If we don't have the macros, do the best we can. */
528 info->progreturn = (info->progreturn & 0xff00) >> 8;
529 #endif
531 /* 127 is the magic value returned from system() to indicate
532 that the shell could not be executed, or from /bin/sh to
533 indicate that the program could not be executed. */
535 if(info->progreturn==127)
537 log_error(_("unable to execute external program\n"));
538 goto fail;
541 if(!info->flags.writeonly)
543 info->fromchild=iobuf_open(info->tempfile_out);
544 if (info->fromchild
545 && is_secured_file (iobuf_get_fd (info->fromchild)))
547 iobuf_close (info->fromchild);
548 info->fromchild = NULL;
549 errno = EPERM;
551 if(info->fromchild==NULL)
553 ret = gpg_error_from_errno (errno);
554 log_error(_("unable to read external program response: %s\n"),
555 strerror(errno));
556 goto fail;
559 /* Do not cache this iobuf on close */
560 iobuf_ioctl(info->fromchild,3,1,NULL);
564 ret=0;
566 fail:
567 return ret;
570 int 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 */