1 /*
2 ** Copyright 2001-2003 Double Precision, Inc.  See COPYING for
3 ** distribution information.
4 */
5 
6 static const char rcsid[]="$Id: libgpg.c,v 1.2 2003/06/02 23:47:16 mrsam Exp $";
7 
8 #include	"config.h"
9 #include	<stdio.h>
10 #include	<stdlib.h>
11 #include	<string.h>
12 #include	<unistd.h>
13 #include	<signal.h>
14 #include	<errno.h>
15 #include	<sys/types.h>
16 #include	<sys/stat.h>
17 #if	HAVE_SYS_TIME_H
18 #include	<sys/time.h>
19 #endif
20 #if HAVE_SYS_WAIT_H
21 #include	<sys/wait.h>
22 #endif
23 #ifndef WEXITSTATUS
24 #define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
25 #endif
26 #ifndef WIFEXITED
27 #define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
28 #endif
29 
30 #include	"gpg.h"
31 #include	"gpglib.h"
32 
33 int libmail_gpg_stdin= -1, libmail_gpg_stdout= -1,
34 	libmail_gpg_stderr= -1;
35 pid_t libmail_gpg_pid= -1;
36 
libmail_gpg_cleanup()37 int libmail_gpg_cleanup()
38 {
39 	int rc=0;
40 
41 	if (libmail_gpg_stdin >= 0)
42 	{
43 		close(libmail_gpg_stdin);
44 		libmail_gpg_stdin= -1;
45 	}
46 
47 	if (libmail_gpg_stdout >= 0)
48 	{
49 		close(libmail_gpg_stdout);
50 		libmail_gpg_stdout= -1;
51 	}
52 
53 	if (libmail_gpg_stderr >= 0)
54 	{
55 		close(libmail_gpg_stderr);
56 		libmail_gpg_stderr= -1;
57 	}
58 
59 	if (libmail_gpg_pid >= 0 && kill(libmail_gpg_pid, 0) >= 0)
60 	{
61 		int waitstat;
62 		pid_t p;
63 
64 		while ((p=wait(&waitstat)) != libmail_gpg_pid)
65 		{
66 			if (p < 0 && errno == ECHILD)
67 				return (-1);
68 		}
69 
70 		rc= WIFEXITED(waitstat) ? WEXITSTATUS(waitstat): -1;
71 		libmail_gpg_pid= -1;
72 	}
73 	return (rc);
74 }
75 
optionfile(const char * gpgdir)76 static char *optionfile(const char *gpgdir)
77 {
78 	char *p=malloc(strlen(gpgdir)+sizeof("/options"));
79 
80 	if (p)
81 		strcat(strcpy(p, gpgdir), "/options");
82 	return (p);
83 }
84 
85 /*
86 ** Determine of GPG is available by checking for the options file, and the
87 ** gpg binary itself.
88 */
89 
libmail_gpg_has_gpg(const char * gpgdir)90 int libmail_gpg_has_gpg(const char *gpgdir)
91 {
92 	char *p=optionfile(gpgdir);
93 	struct stat stat_buf;
94 	int rc;
95 
96 	if (!p)
97 		return (-1);
98 
99 	rc=stat(p, &stat_buf);
100 	free(p);
101 	if (rc == 0)
102 		rc=stat(GPG, &stat_buf);
103 
104 	return (rc);
105 }
106