/[winpt]/trunk/Src/wptGPGUtil.cpp
ViewVC logotype

Annotation of /trunk/Src/wptGPGUtil.cpp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 36 - (hide annotations)
Thu Oct 27 15:25:13 2005 UTC (19 years, 4 months ago) by werner
File size: 15838 byte(s)
First set of changes to use autotools for building.
1 werner 36 /* wptGPGUtil.cpp - GPG helper functions
2     * Copyright (C) 2005 g10 Code GmbH
3     *
4     * This file is part of WinPT.
5     *
6     * WinPT 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.
10     *
11     * WinPT 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.
15     *
16     * You should have received a copy of the GNU General Public License
17     * along with WinPT; if not, write to the Free Software Foundation,
18     * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
19     */
20     #ifdef HAVE_CONFIG_H
21     #include <config.h>
22     #endif
23    
24     #include <windows.h>
25     #include <windows.h>
26     #include <sys/stat.h>
27    
28     #include "gpgme.h"
29    
30    
31     #define NROFHEXDIGITS 2
32     /* Convert two hexadecimal digits from STR to the value they
33     represent. Returns -1 if one of the characters is not a
34     hexadecimal digit. */
35     static int
36     hextobyte (const unsigned char *str)
37     {
38     int val = 0;
39     int i;
40    
41     for (i = 0; i < NROFHEXDIGITS; i++) {
42     if (*str >= '0' && *str <= '9')
43     val += *str - '0';
44     else if (*str >= 'A' && *str <= 'F')
45     val += 10 + *str - 'A';
46     else if (*str >= 'a' && *str <= 'f')
47     val += 10 + *str - 'a';
48     else
49     return -1;
50     if (i < NROFHEXDIGITS - 1)
51     val *= 16;
52     str++;
53     }
54     return val;
55     }
56    
57     /* Decode the C formatted string @src and store the result in the
58     buffer @destp which is @len bytes long. If @len is zero, then a
59     large enough buffer is allocated with malloc and @destp is set to
60     the result. Currently, @len is only used to specify if allocation
61     is desired or not, the caller is expected to make sure that @destp
62     is large enough if @len is not zero. */
63     gpgme_error_t
64     gpg_decode_c_string (const char *src, char **destp, size_t len)
65     {
66     char *dest;
67    
68     /* Set up the destination buffer. */
69     if (len) {
70     if (len < strlen (src) + 1)
71     return gpg_error (GPG_ERR_TOO_SHORT);
72     dest = *destp;
73     }
74     else {
75     /* The converted string will never be larger than the original string. */
76     dest = (char*)malloc (strlen (src) + 1);
77     if (!dest)
78     return gpg_error (GPG_ERR_ENOMEM);
79     *destp = dest;
80     }
81    
82     /* Convert the string. */
83     while (*src) {
84     if (*src != '\\') {
85     *(dest++) = *(src++);
86     continue;
87     }
88    
89     switch (src[1]) {
90     #define DECODE_ONE(match,result) \
91     case match: \
92     src += 2; \
93     *(dest++) = result; \
94     break;
95    
96     DECODE_ONE ('\'', '\'');
97     DECODE_ONE ('\"', '\"');
98     DECODE_ONE ('\?', '\?');
99     DECODE_ONE ('\\', '\\');
100     DECODE_ONE ('a', '\a');
101     DECODE_ONE ('b', '\b');
102     DECODE_ONE ('f', '\f');
103     DECODE_ONE ('n', '\n');
104     DECODE_ONE ('r', '\r');
105     DECODE_ONE ('t', '\t');
106     DECODE_ONE ('v', '\v');
107    
108     case 'x': {
109     int val = hextobyte ((unsigned char*)&src[2]);
110     if (val == -1) { /* Should not happen. */
111     *(dest++) = *(src++);
112     *(dest++) = *(src++);
113     if (*src)
114     *(dest++) = *(src++);
115     if (*src)
116     *(dest++) = *(src++);
117     }
118     else {
119     if (!val) {
120     /* A binary zero is not representable in a C string. */
121     *(dest++) = '\\';
122     *(dest++) = '0';
123     }
124     else
125     *((unsigned char *) dest++) = val;
126     src += 4;
127     }
128     }
129    
130     default: /* Should not happen. */
131     {
132     *(dest++) = *(src++);
133     *(dest++) = *(src++);
134     }
135     }
136     }
137     *(dest++) = 0;
138     return 0;
139     }
140    
141     /* Replace %foo% entries with its real values.
142     Return value: expanded path or NULL on error. */
143     static char *
144     expand_path (const char *path)
145     {
146     DWORD len;
147     char *p;
148    
149     len = ExpandEnvironmentStrings (path, NULL, 0);
150     if (!len)
151     return NULL;
152     len += 1;
153     p = (char*)calloc (1, len+1);
154     if (!p)
155     abort ();
156     len = ExpandEnvironmentStrings (path, p, len);
157     if (!len) {
158     free (p);
159     return NULL;
160     }
161     return p;
162     }
163    
164    
165     /* Read a string from the W32 registry. The directory is given
166     in @dir and the name of the value in @name, */
167     static char *
168     read_w32_registry (HKEY root_key, const char *dir, const char *name)
169     {
170     HKEY key_handle;
171     DWORD n1, nbytes;
172     DWORD type;
173     char *result = NULL;
174    
175     if (RegOpenKeyEx (root_key, dir, 0, KEY_READ, &key_handle))
176     return NULL; /* no need for a RegClose, so return direct */
177    
178     nbytes = 1;
179     if (RegQueryValueEx (key_handle, name, 0, NULL, NULL, &nbytes))
180     goto leave;
181     result = (char*)calloc (1, (n1=nbytes+1));
182     if (!result)
183     abort ();
184     if (RegQueryValueEx (key_handle, name, 0, &type, (BYTE*)result, &n1)) {
185     free (result);
186     result = NULL;
187     goto leave;
188     }
189     if (type == REG_EXPAND_SZ && strchr (result, '%')) {
190     char *p = expand_path (result);
191     free (result);
192     result = p;
193     }
194    
195     leave:
196     RegCloseKey (key_handle);
197     return result;
198     }
199    
200    
201     /* Create a temp file based on the name of @name.
202     Return value: handle to the file in case of success. */
203     static HANDLE
204     create_tmpfile (const char *name)
205     {
206     HANDLE out;
207     SECURITY_ATTRIBUTES sattr;
208     char tmp[300];
209    
210     memset (&sattr, 0, sizeof sattr);
211     sattr.bInheritHandle = TRUE;
212     sattr.lpSecurityDescriptor = NULL;
213     sattr.nLength = sizeof sattr;
214    
215     GetTempPath (sizeof (tmp)-1 - strlen (name)-1, tmp);
216     strcat (tmp, name);
217     out = CreateFile (tmp, GENERIC_READ|GENERIC_WRITE,
218     FILE_SHARE_WRITE, &sattr,
219     OPEN_ALWAYS, FILE_FLAG_DELETE_ON_CLOSE, NULL);
220     return out;
221     }
222    
223    
224     /* Create a pipe with a readable remote end and
225     write the data from @dat to the local end.
226     Return value: read handle on success. */
227     static HANDLE
228     create_in_pipe (const char *dat)
229     {
230     HANDLE r, w;
231     SECURITY_ATTRIBUTES sec_attr;
232     DWORD n;
233    
234     memset (&sec_attr, 0, sizeof sec_attr);
235     sec_attr.bInheritHandle = TRUE;
236     sec_attr.nLength = sizeof sec_attr;
237    
238     if (!CreatePipe (&r, &w, &sec_attr, 4096))
239     return NULL;
240    
241     WriteFile (w, dat, strlen (dat), &n, NULL);
242     CloseHandle (w);
243    
244     return r;
245     }
246    
247    
248     /* Map the contents of the file handle @out to
249     a buffer and return it. */
250     static char*
251     map_tmpfile (HANDLE out)
252     {
253     DWORD n;
254     char *p;
255    
256     FlushFileBuffers (out);
257     SetFilePointer (out, 0, NULL, FILE_BEGIN);
258     n = GetFileSize (out, NULL);
259     p = (char*)calloc (1, n+1);
260     if (!p)
261     abort ();
262     ReadFile (out, p, n, &n, NULL);
263     p[n] = 0;
264     return p;
265     }
266    
267    
268     /* Create a process from the command line in @cmd.
269     If @out is != NULL, the output of the process will
270     be redirected to @out. If @in is != NULL the input
271     will be read from @in.
272     Return value: 0 on success. */
273     static int
274     create_process (const char *cmd, HANDLE in, HANDLE out)
275     {
276     STARTUPINFO si;
277     PROCESS_INFORMATION pi;
278    
279     memset (&si, 0, sizeof (si));
280     si.cb = sizeof si;
281     if (in || out)
282     si.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
283     if (out)
284     si.hStdOutput = out;
285     if (in)
286     si.hStdInput = in;
287     si.wShowWindow = SW_HIDE;
288     if (!CreateProcess (NULL, (char*)cmd, NULL, NULL, TRUE, 0,
289     NULL, NULL, &si, &pi))
290     return -1;
291     WaitForSingleObject (pi.hProcess, INFINITE);
292     CloseHandle (pi.hProcess);
293     return 0;
294     }
295    
296    
297     /* Export a GPG secret key given by @keyid into the file @outfile.
298     Return value: 0 on success. */
299     gpgme_error_t
300     gpg_export_seckey (const char *keyid, const char *outfile)
301     {
302     gpgme_error_t err = gpg_error (GPG_ERR_NO_ERROR);
303     struct stat st;
304     char *p;
305     char *cmd;
306    
307     p = read_w32_registry (HKEY_CURRENT_USER,
308     "Software\\GNU\\GnuPG", "gpgProgram");
309     if (!p)
310     return gpg_error (GPG_ERR_INV_ARG);
311     cmd = (char*)calloc (1, strlen (p) + strlen (keyid)
312     + strlen (outfile) + 64 + 2);
313     if (!cmd)
314     abort ();
315     sprintf (cmd, "%s --yes --output \"%s\" --export-secret-key %s",
316     p, outfile, keyid);
317     if (create_process (cmd, NULL, NULL))
318     err = gpg_error (GPG_ERR_INTERNAL);
319    
320     if (stat (outfile, &st) == -1 || st.st_size == 0)
321     err = gpg_error (GPG_ERR_NO_DATA);
322    
323     free (p);
324     free (cmd);
325     return err;
326     }
327    
328    
329     /* If @export is 1, export the ownertrust data to the
330     buffer @data. Otherwise import the ownertrust data from @data.
331     Return value: 0 on success. */
332     gpgme_error_t
333     gpg_manage_ownertrust (char **data, int export)
334     {
335     gpgme_error_t err = gpg_error (GPG_ERR_NO_ERROR);
336     HANDLE out = NULL, in = NULL;
337     char *p;
338     char *cmd;
339    
340     p = read_w32_registry (HKEY_CURRENT_USER,
341     "Software\\GNU\\GnuPG", "gpgProgram");
342     if (!p)
343     return gpg_error (GPG_ERR_INV_ARG);
344    
345     cmd = (char*)calloc (1, strlen (p) + 64 + 1);
346     if (!cmd)
347     abort ();
348     sprintf (cmd, "%s %s", p,
349     export? "--export-ownertrust" : "--import-ownertrust");
350    
351     if (export)
352     out = create_tmpfile ("gpg_ot_out");
353     else {
354     DWORD nw;
355     in = create_tmpfile ("gpg_ot_in");
356     WriteFile (in, *data, strlen (*data), &nw, NULL);
357     FlushFileBuffers (in);
358     /* XXX: need a rewind? */
359     }
360     if (create_process (cmd, in, out))
361     err = gpg_error (GPG_ERR_INTERNAL);
362    
363     free (p);
364     free (cmd);
365    
366     if (in)
367     CloseHandle (in);
368     if (out) {
369     *data = map_tmpfile (out);
370     CloseHandle (out);
371     }
372     return err;
373     }
374    
375    
376     /* Call gpg --rebuild-keydb-caches to speed up signature listings. */
377     gpgme_error_t
378     gpg_rebuild_cache (char **r_inf)
379     {
380     gpgme_error_t err = gpg_error (GPG_ERR_NO_ERROR);
381     HANDLE out = NULL;
382     char *p;
383     char *cmd;
384    
385     p = read_w32_registry (HKEY_CURRENT_USER,
386     "Software\\GNU\\GnuPG", "gpgProgram");
387     if (!p)
388     return gpg_error (GPG_ERR_INV_ARG);
389     cmd = (char*)calloc (1, strlen (p) + 64);
390     if (!cmd)
391     abort ();
392     sprintf (cmd, "%s --logger-fd=1 --rebuild-keydb-caches", p);
393    
394     if (r_inf)
395     out = create_tmpfile ("gpg_rebuild_cache");
396    
397     if (create_process (cmd, NULL, out))
398     err = gpg_error (GPG_ERR_INTERNAL);
399    
400     if (r_inf)
401     *r_inf = map_tmpfile (out);
402     if (out)
403     CloseHandle (out);
404     free (p);
405     free (cmd);
406     return 0;
407     }
408    
409    
410     /* Call gpg --version to retrieve the 'about' information. */
411     gpgme_error_t
412     gpg_get_version (char **r_inf)
413     {
414     gpgme_error_t err= gpg_error (GPG_ERR_NO_ERROR);
415     HANDLE out;
416     char *p, *cmd;
417    
418     p =read_w32_registry (HKEY_CURRENT_USER,
419     "Software\\GNU\\GnuPG", "gpgProgram");
420     if (!p)
421     return gpg_error (GPG_ERR_INV_ARG);
422     cmd = (char*)calloc (1, strlen (p) + 32);
423     if (!cmd)
424     abort ();
425     sprintf (cmd, "%s --version", p);
426    
427     out = create_tmpfile ("gpg_out");
428     if (create_process (cmd, NULL, out))
429     err = gpg_error (GPG_ERR_INTERNAL);
430    
431     free (p);
432     free (cmd);
433    
434     *r_inf = map_tmpfile (out);
435     CloseHandle (out);
436     return err;
437     }
438    
439    
440     /* Return the colon file output of the given file @fname in @r_out.
441     Return value: 0 on success. */
442     gpgme_error_t
443     gpg_import_key_list (const char *fname, char **r_out)
444     {
445     gpgme_error_t err = gpg_error (GPG_ERR_NO_ERROR);
446     char *cmd, *p;
447     HANDLE out;
448    
449     p = read_w32_registry (HKEY_CURRENT_USER,
450     "Software\\GNU\\GnuPG", "gpgProgram");
451     if (!p)
452     return gpg_error (GPG_ERR_INV_ARG);
453    
454     cmd = (char*)calloc (1, strlen (p) + strlen (fname) + 2+2 + 64);
455     if (!cmd)
456     abort ();
457     sprintf (cmd, "%s --fixed-list-mode --with-colons \"%s\"", p, fname);
458    
459     out = create_tmpfile ("gpg_keys");
460     if (create_process (cmd, NULL, out))
461     err = gpg_error (GPG_ERR_INTERNAL);
462    
463     free (p);
464     free (cmd);
465    
466     *r_out = map_tmpfile (out);
467     CloseHandle (out);
468     return err;
469     }
470    
471     char*
472     generate_revoc_input (int code, const char *cmt, const char *pass)
473     {
474     const char *fmt;
475     char *p;
476     size_t n;
477    
478     fmt = "Y\n" /* gen_revoke.okay */
479     "%d\n" /* ask_revocation_reason.code */
480     "%s\n" /* ask_revocation_reason.text */
481     "%s" /* text != NULL '\n' otherwise '' */
482     "Y\n" /* ask_revocation_reason.okay */
483     "%s\n"; /* passphrase.enter. */
484     n = strlen (fmt) + 32;
485     if (pass)
486     n += strlen (pass) + 1;
487     if (cmt)
488     n += strlen (cmt) + 1;
489     p = (char*)calloc (1, n+1);
490     if (!p)
491     abort ();
492     sprintf (p, fmt, code, cmt? cmt : "", cmt? "\n" : "", pass? pass : "");
493     return p;
494     }
495    
496    
497     /* Generate a revocation certificate for the key with the keyid @keyid.
498     @inp_data contains all needed data to answer the questions of the
499     command handler. Each separate with a '\n'.
500     @r_revcert contains the revocation cert on success.
501     Return value: 0 on success. */
502     gpgme_error_t
503     gpg_revoke_key (const char *inp_data, const char *keyid, char **r_revcert)
504     {
505     gpgme_error_t err = gpg_error (GPG_ERR_NO_ERROR);
506     char *rcrt;
507     char *cmd, *p;
508     HANDLE in, out;
509    
510     p = read_w32_registry (HKEY_CURRENT_USER,
511     "Software\\GNU\\GnuPG", "gpgProgram");
512     if (!p)
513     return gpg_error (GPG_ERR_INV_ARG);
514    
515     cmd = (char*)calloc (1, strlen (p) + strlen (keyid)+1 + 128);
516     if (!cmd)
517     abort ();
518     sprintf (cmd, "%s --pgp7 --command-fd=0 --status-fd=2 --gen-revoke %s",
519     p, keyid);
520    
521     in = create_in_pipe (inp_data);
522     out = create_tmpfile ("gpg_revcert");
523     if (create_process (cmd, in, out)) {
524     *r_revcert = NULL;
525     err = gpg_error (GPG_ERR_INTERNAL);
526     }
527     else {
528     rcrt = map_tmpfile (out);
529     *r_revcert = rcrt;
530     }
531    
532     free (p);
533     free (cmd);
534    
535     CloseHandle (in);
536     CloseHandle (out);
537     return err;
538     }
539    
540    
541     /* Return the validity of the user attribute, informerly known
542     as photo-ID. If no uat was found, return 0 for unknown. */
543     gpgme_error_t
544     get_uat_validity (const char *keyid, gpgme_validity_t *r_valid)
545     {
546     gpgme_error_t err = gpg_error (GPG_ERR_NO_ERROR);
547     HANDLE out;
548     char *p, *cmd;
549     char *uat;
550    
551     *r_valid = GPGME_VALIDITY_UNKNOWN;
552     p = read_w32_registry (HKEY_CURRENT_USER,
553     "Software\\GNU\\GnuPG", "gpgProgram");
554     if (!p)
555     return gpg_error (GPG_ERR_INV_ARG);
556    
557     cmd = (char*)calloc (1, strlen (p) + strlen (keyid)+1 + 128);
558     if (!cmd)
559     abort ();
560     sprintf (cmd, "%s --with-colons --fixed-list-mode --list-keys \"%s\"",
561     p, keyid);
562    
563     out = create_tmpfile ("gpg_keys");
564     if (create_process (cmd, NULL, out))
565     err = gpg_error (GPG_ERR_INTERNAL);
566    
567     free (p);
568     free (cmd);
569    
570     p = map_tmpfile (out);
571     if ((uat = strstr (p, "uat:"))) {
572     switch (*(uat+4)) {
573     case 'm': *r_valid = GPGME_VALIDITY_MARGINAL; break;
574     case 'f':
575     case 'u': *r_valid = GPGME_VALIDITY_FULL; break;
576     default: *r_valid = GPGME_VALIDITY_UNDEFINED; break;
577     }
578     }
579    
580     free (p);
581     CloseHandle (out);
582     return err;
583     }
584    
585    
586     #if 0
587     /* Extract all recipients from the file @file.
588     Return value: 0 on success. */
589     static int
590     do_get_recipients (const char *file, gpgme_recipient_t *r_list)
591     {
592     gpgme_recipient_t l;
593     PACKET *pkt;
594     gpg_iobuf_t inp = NULL;
595     armor_filter_context_t afx;
596     int rc = 0, quit=0;
597    
598     if (!file || !r_list) {
599     log_debug ("do_list_packets: !r_list || !file");
600     return -1;
601     }
602    
603     *r_list=NULL;
604     inp = gpg_iobuf_open (file);
605     if (!inp)
606     return WPTERR_FILE_OPEN;
607     gpg_iobuf_ioctl (inp, 3, 1, NULL); /* disable cache */
608     if (gpg_use_armor_filter (inp)) {
609     memset (&afx, 0, sizeof (afx));
610     gpg_iobuf_push_filter (inp, gpg_armor_filter, &afx);
611     }
612     pkt = (PACKET *)calloc(1, sizeof *pkt);
613     gpg_init_packet (pkt);
614     while (!quit && (rc = gpg_parse_packet (inp, pkt)) != -1) {
615     switch (pkt->pkttype) {
616     case PKT_PUBKEY_ENC:
617     {PKT_pubkey_enc *enc = pkt->pkt.pubkey_enc;
618     if (!enc)
619     break;
620     l = calloc (1, sizeof *l);
621     l->keyid = calloc (1, 16+1);
622     _snprintf (l->keyid, 16, "%08lX%08lX", enc->keyid[0], enc->keyid[1]);
623     l->pubkey_algo = enc->pubkey_algo;
624     l->status = 0;
625     l->next = (*r_list);
626     *r_list = l;
627     break;}
628    
629     case PKT_ENCRYPTED:
630     case PKT_ENCRYPTED_MDC:
631     case PKT_COMPRESSED:
632     case PKT_PUBLIC_KEY:
633     case PKT_SECRET_KEY:
634     quit = 1;
635     break;
636     }
637     gpg_free_packet (pkt);
638     gpg_init_packet (pkt);
639     }
640     gpg_iobuf_close (inp);
641     safe_free (pkt);
642     return 0;
643     }
644     #endif

Properties

Name Value
svn:eol-style native

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26