2006-06-09 Marcus Brinkmann <marcus@g10code.de>
[gnupg.git] / g10 / exec.c
blob6938a409a493957d64fe2202d31058154485da34
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 tmp=xmalloc(256);
131 if(GetTempPath(256,tmp)==0)
132 strcpy(tmp,"c:\\windows\\temp");
133 else
135 int len=strlen(tmp);
137 /* GetTempPath may return with \ on the end */
138 while(len>0 && tmp[len-1]=='\\')
140 tmp[len-1]='\0';
141 len--;
144 #else /* More unixish systems */
145 tmp=getenv("TMPDIR");
146 if(tmp==NULL)
148 tmp=getenv("TMP");
149 if(tmp==NULL)
151 #ifdef __riscos__
152 tmp="<Wimp$ScrapDir>.GnuPG";
153 mkdir(tmp,0700); /* Error checks occur later on */
154 #else
155 tmp="/tmp";
156 #endif
159 #endif
162 info->tempdir=xmalloc(strlen(tmp)+strlen(DIRSEP_S)+10+1);
164 sprintf(info->tempdir,"%s" DIRSEP_S "gpg-XXXXXX",tmp);
166 #if defined (_WIN32)
167 xfree(tmp);
168 #endif
170 if(mkdtemp(info->tempdir)==NULL)
171 log_error(_("can't create directory `%s': %s\n"),
172 info->tempdir,strerror(errno));
173 else
175 info->flags.madedir=1;
177 info->tempfile_in=xmalloc(strlen(info->tempdir)+
178 strlen(DIRSEP_S)+strlen(namein)+1);
179 sprintf(info->tempfile_in,"%s" DIRSEP_S "%s",info->tempdir,namein);
181 if(!info->flags.writeonly)
183 info->tempfile_out=xmalloc(strlen(info->tempdir)+
184 strlen(DIRSEP_S)+strlen(nameout)+1);
185 sprintf(info->tempfile_out,"%s" DIRSEP_S "%s",info->tempdir,nameout);
189 return info->flags.madedir?0:G10ERR_GENERAL;
192 /* Expands %i and %o in the args to the full temp files within the
193 temp directory. */
194 static int expand_args(struct exec_info *info,const char *args_in)
196 const char *ch=args_in;
197 unsigned int size,len;
199 info->flags.use_temp_files=0;
200 info->flags.keep_temp_files=0;
202 if(DBG_EXTPROG)
203 log_debug("expanding string \"%s\"\n",args_in);
205 size=100;
206 info->command=xmalloc(size);
207 len=0;
208 info->command[0]='\0';
210 while(*ch!='\0')
212 if(*ch=='%')
214 char *append=NULL;
216 ch++;
218 switch(*ch)
220 case 'O':
221 info->flags.keep_temp_files=1;
222 /* fall through */
224 case 'o': /* out */
225 if(!info->flags.madedir)
227 if(make_tempdir(info))
228 goto fail;
230 append=info->tempfile_out;
231 info->flags.use_temp_files=1;
232 break;
234 case 'I':
235 info->flags.keep_temp_files=1;
236 /* fall through */
238 case 'i': /* in */
239 if(!info->flags.madedir)
241 if(make_tempdir(info))
242 goto fail;
244 append=info->tempfile_in;
245 info->flags.use_temp_files=1;
246 break;
248 case '%':
249 append="%";
250 break;
253 if(append)
255 size_t applen=strlen(append);
257 if(applen+len>size-1)
259 if(applen<100)
260 applen=100;
262 size+=applen;
263 info->command=xrealloc(info->command,size);
266 strcat(info->command,append);
267 len+=strlen(append);
270 else
272 if(len==size-1) /* leave room for the \0 */
274 size+=100;
275 info->command=xrealloc(info->command,size);
278 info->command[len++]=*ch;
279 info->command[len]='\0';
282 ch++;
285 if(DBG_EXTPROG)
286 log_debug("args expanded to \"%s\", use %u, keep %u\n",info->command,
287 info->flags.use_temp_files,info->flags.keep_temp_files);
289 return 0;
291 fail:
293 xfree(info->command);
294 info->command=NULL;
296 return G10ERR_GENERAL;
299 /* Either handles the tempfile creation, or the fork/exec. If it
300 returns ok, then info->tochild is a FILE * that can be written to.
301 The rules are: if there are no args, then it's a fork/exec/pipe.
302 If there are args, but no tempfiles, then it's a fork/exec/pipe via
303 shell -c. If there are tempfiles, then it's a system. */
305 int exec_write(struct exec_info **info,const char *program,
306 const char *args_in,const char *name,int writeonly,int binary)
308 int ret=G10ERR_GENERAL;
310 if(opt.exec_disable && !opt.no_perm_warn)
312 log_info(_("external program calls are disabled due to unsafe "
313 "options file permissions\n"));
315 return ret;
318 #if defined(HAVE_GETUID) && defined(HAVE_GETEUID)
319 /* There should be no way to get to this spot while still carrying
320 setuid privs. Just in case, bomb out if we are. */
321 if(getuid()!=geteuid())
322 BUG();
323 #endif
325 if(program==NULL && args_in==NULL)
326 BUG();
328 *info=xmalloc_clear(sizeof(struct exec_info));
330 if(name)
331 (*info)->name=xstrdup(name);
332 (*info)->flags.binary=binary;
333 (*info)->flags.writeonly=writeonly;
335 /* Expand the args, if any */
336 if(args_in && expand_args(*info,args_in))
337 goto fail;
339 #ifdef EXEC_TEMPFILE_ONLY
340 if(!(*info)->flags.use_temp_files)
342 log_error(_("this platform requires temporary files when calling"
343 " external programs\n"));
344 goto fail;
347 #else /* !EXEC_TEMPFILE_ONLY */
349 /* If there are no args, or there are args, but no temp files, we
350 can use fork/exec/pipe */
351 if(args_in==NULL || (*info)->flags.use_temp_files==0)
353 int to[2],from[2];
355 if(pipe(to)==-1)
356 goto fail;
358 if(pipe(from)==-1)
360 close(to[0]);
361 close(to[1]);
362 goto fail;
365 if(((*info)->child=fork())==-1)
367 close(to[0]);
368 close(to[1]);
369 close(from[0]);
370 close(from[1]);
371 goto fail;
374 if((*info)->child==0)
376 char *shell=getenv("SHELL");
378 if(shell==NULL)
379 shell="/bin/sh";
381 /* I'm the child */
383 /* If the program isn't going to respond back, they get to
384 keep their stdout/stderr */
385 if(!(*info)->flags.writeonly)
387 /* implied close of STDERR */
388 if(dup2(STDOUT_FILENO,STDERR_FILENO)==-1)
389 _exit(1);
391 /* implied close of STDOUT */
392 close(from[0]);
393 if(dup2(from[1],STDOUT_FILENO)==-1)
394 _exit(1);
397 /* implied close of STDIN */
398 close(to[1]);
399 if(dup2(to[0],STDIN_FILENO)==-1)
400 _exit(1);
402 if(args_in==NULL)
404 if(DBG_EXTPROG)
405 log_debug("execlp: %s\n",program);
407 execlp(program,program,(void *)NULL);
409 else
411 if(DBG_EXTPROG)
412 log_debug("execlp: %s -c %s\n",shell,(*info)->command);
414 execlp(shell,shell,"-c",(*info)->command,(void *)NULL);
417 /* If we get this far the exec failed. Clean up and return. */
419 if(args_in==NULL)
420 log_error(_("unable to execute program `%s': %s\n"),
421 program,strerror(errno));
422 else
423 log_error(_("unable to execute shell `%s': %s\n"),
424 shell,strerror(errno));
426 /* This mimics the POSIX sh behavior - 127 means "not found"
427 from the shell. */
428 if(errno==ENOENT)
429 _exit(127);
431 _exit(1);
434 /* I'm the parent */
436 close(to[0]);
438 (*info)->tochild=fdopen(to[1],binary?"wb":"w");
439 if((*info)->tochild==NULL)
441 ret = gpg_error_from_errno (errno);
442 close(to[1]);
443 goto fail;
446 close(from[1]);
448 (*info)->fromchild=iobuf_fdopen(from[0],"r");
449 if((*info)->fromchild==NULL)
451 ret = gpg_error_from_errno (errno);
452 close(from[0]);
453 goto fail;
456 /* fd iobufs are cached?! */
457 iobuf_ioctl((*info)->fromchild,3,1,NULL);
459 return 0;
461 #endif /* !EXEC_TEMPFILE_ONLY */
463 if(DBG_EXTPROG)
464 log_debug("using temp file `%s'\n",(*info)->tempfile_in);
466 /* It's not fork/exec/pipe, so create a temp file */
467 if( is_secured_filename ((*info)->tempfile_in) )
469 (*info)->tochild = NULL;
470 errno = EPERM;
472 else
473 (*info)->tochild=fopen((*info)->tempfile_in,binary?"wb":"w");
474 if((*info)->tochild==NULL)
476 ret = gpg_error_from_errno (errno);
477 log_error(_("can't create `%s': %s\n"),
478 (*info)->tempfile_in,strerror(errno));
479 goto fail;
482 ret=0;
484 fail:
485 return ret;
488 int exec_read(struct exec_info *info)
490 int ret=G10ERR_GENERAL;
492 fclose(info->tochild);
493 info->tochild=NULL;
495 if(info->flags.use_temp_files)
497 if(DBG_EXTPROG)
498 log_debug("system() command is %s\n",info->command);
500 #if defined (_WIN32)
501 info->progreturn=w32_system(info->command);
502 #else
503 info->progreturn=system(info->command);
504 #endif
506 if(info->progreturn==-1)
508 log_error(_("system error while calling external program: %s\n"),
509 strerror(errno));
510 info->progreturn=127;
511 goto fail;
514 #if defined(WIFEXITED) && defined(WEXITSTATUS)
515 if(WIFEXITED(info->progreturn))
516 info->progreturn=WEXITSTATUS(info->progreturn);
517 else
519 log_error(_("unnatural exit of external program\n"));
520 info->progreturn=127;
521 goto fail;
523 #else
524 /* If we don't have the macros, do the best we can. */
525 info->progreturn = (info->progreturn & 0xff00) >> 8;
526 #endif
528 /* 127 is the magic value returned from system() to indicate
529 that the shell could not be executed, or from /bin/sh to
530 indicate that the program could not be executed. */
532 if(info->progreturn==127)
534 log_error(_("unable to execute external program\n"));
535 goto fail;
538 if(!info->flags.writeonly)
540 info->fromchild=iobuf_open(info->tempfile_out);
541 if (info->fromchild
542 && is_secured_file (iobuf_get_fd (info->fromchild)))
544 iobuf_close (info->fromchild);
545 info->fromchild = NULL;
546 errno = EPERM;
548 if(info->fromchild==NULL)
550 ret = gpg_error_from_errno (errno);
551 log_error(_("unable to read external program response: %s\n"),
552 strerror(errno));
553 goto fail;
556 /* Do not cache this iobuf on close */
557 iobuf_ioctl(info->fromchild,3,1,NULL);
561 ret=0;
563 fail:
564 return ret;
567 int exec_finish(struct exec_info *info)
569 int ret=info->progreturn;
571 if(info->fromchild)
572 iobuf_close(info->fromchild);
574 if(info->tochild)
575 fclose(info->tochild);
577 #ifndef EXEC_TEMPFILE_ONLY
578 if(info->child>0)
580 if(waitpid(info->child,&info->progreturn,0)!=0 &&
581 WIFEXITED(info->progreturn))
582 ret=WEXITSTATUS(info->progreturn);
583 else
585 log_error(_("unnatural exit of external program\n"));
586 ret=127;
589 #endif
591 if(info->flags.madedir && !info->flags.keep_temp_files)
593 if(info->tempfile_in)
595 if(unlink(info->tempfile_in)==-1)
596 log_info(_("WARNING: unable to remove tempfile (%s) `%s': %s\n"),
597 "in",info->tempfile_in,strerror(errno));
600 if(info->tempfile_out)
602 if(unlink(info->tempfile_out)==-1)
603 log_info(_("WARNING: unable to remove tempfile (%s) `%s': %s\n"),
604 "out",info->tempfile_out,strerror(errno));
607 if(rmdir(info->tempdir)==-1)
608 log_info(_("WARNING: unable to remove temp directory `%s': %s\n"),
609 info->tempdir,strerror(errno));
612 xfree(info->command);
613 xfree(info->name);
614 xfree(info->tempdir);
615 xfree(info->tempfile_in);
616 xfree(info->tempfile_out);
617 xfree(info);
619 return ret;
621 #endif /* ! NO_EXEC */