2012-05-27 [paul] 3.8.0cvs48
[claws.git] / src / plugins / pgpcore / sgpgme.c
1 /*
2  * Claws Mail -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2012 the Claws Mail team
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  * 
18  */
19  
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #endif
23  
24 #ifdef USE_GPGME
25
26 #include <time.h>
27 #include <gtk/gtk.h>
28 #include <gpgme.h>
29 #include <glib.h>
30 #include <glib/gi18n.h>
31 #include <stdio.h>
32 #include <string.h>
33 #include <stdlib.h>
34 #include <errno.h>
35 #include <sys/types.h>
36 #ifndef G_OS_WIN32
37 #  include <sys/wait.h>
38 #endif
39 #if (defined(__DragonFly__) || defined(SOLARIS) || defined (__NetBSD__) || defined (__FreeBSD__) || defined (__OpenBSD__))
40 #  include <sys/signal.h>
41 #endif
42 #ifndef G_OS_WIN32
43 #include <sys/mman.h>
44 #endif
45 #if HAVE_LOCALE_H
46 #  include <locale.h>
47 #endif
48
49 #include "sgpgme.h"
50 #include "privacy.h"
51 #include "prefs_common.h"
52 #include "utils.h"
53 #include "alertpanel.h"
54 #include "passphrase.h"
55 #include "prefs_gpg.h"
56 #include "account.h"
57 #include "select-keys.h"
58
59 static void sgpgme_disable_all(void)
60 {
61     /* FIXME: set a flag, so that we don't bother the user with failed
62      * gpgme messages */
63 }
64
65 gpgme_verify_result_t sgpgme_verify_signature(gpgme_ctx_t ctx, gpgme_data_t sig, 
66                                         gpgme_data_t plain, gpgme_data_t dummy)
67 {
68         gpgme_verify_result_t status = NULL;
69         gpgme_error_t err;
70
71         if ((err = gpgme_op_verify(ctx, sig, plain, dummy)) != GPG_ERR_NO_ERROR) {
72                 debug_print("op_verify err %s\n", gpgme_strerror(err));
73                 privacy_set_error("%s", gpgme_strerror(err));
74                 return GINT_TO_POINTER(-GPG_ERR_SYSTEM_ERROR);
75         }
76         status = gpgme_op_verify_result(ctx);
77         if (status && status->signatures == NULL) {
78                 debug_print("no signature found\n");
79                 privacy_set_error(_("No signature found"));
80                 return GINT_TO_POINTER(-GPG_ERR_SYSTEM_ERROR);
81         }
82         return status;
83 }
84
85 SignatureStatus sgpgme_sigstat_gpgme_to_privacy(gpgme_ctx_t ctx, gpgme_verify_result_t status)
86 {
87         unsigned long validity = 0;
88         gpgme_signature_t sig = NULL;
89         
90         if (GPOINTER_TO_INT(status) == -GPG_ERR_SYSTEM_ERROR) {
91                 debug_print("system error\n");
92                 return SIGNATURE_CHECK_FAILED;
93         }
94
95         if (status == NULL) {
96                 debug_print("status == NULL\n");
97                 return SIGNATURE_UNCHECKED;
98         }
99         sig = status->signatures;
100
101         if (sig == NULL) {
102                 debug_print("sig == NULL\n");
103                 return SIGNATURE_UNCHECKED;
104         }
105         validity = sig->validity;
106
107         debug_print("err code %d\n", gpg_err_code(sig->status));
108         switch (gpg_err_code(sig->status)) {
109         case GPG_ERR_NO_ERROR:
110                 switch (gpg_err_code(sig->validity)) {
111                 case GPGME_VALIDITY_NEVER:
112                         return SIGNATURE_INVALID;
113                 case GPGME_VALIDITY_UNKNOWN:
114                 case GPGME_VALIDITY_UNDEFINED:
115                 case GPGME_VALIDITY_MARGINAL:
116                 case GPGME_VALIDITY_FULL:
117                 case GPGME_VALIDITY_ULTIMATE:
118                         return SIGNATURE_OK;
119                 default:
120                         return SIGNATURE_CHECK_FAILED;
121                 }
122         case GPG_ERR_SIG_EXPIRED:
123         case GPG_ERR_CERT_REVOKED:
124                 return SIGNATURE_WARN;
125         case GPG_ERR_KEY_EXPIRED:
126                 return SIGNATURE_KEY_EXPIRED;
127         case GPG_ERR_BAD_SIGNATURE:
128                 return SIGNATURE_INVALID;
129         case GPG_ERR_NO_PUBKEY:
130                 return SIGNATURE_CHECK_FAILED;
131         default:
132                 return SIGNATURE_CHECK_FAILED;
133         }
134         return SIGNATURE_CHECK_FAILED;
135 }
136
137 static const gchar *get_validity_str(unsigned long validity)
138 {
139         switch (gpg_err_code(validity)) {
140         case GPGME_VALIDITY_UNKNOWN:
141                 return _("Unknown");
142         case GPGME_VALIDITY_UNDEFINED:
143                 return _("Undefined");
144         case GPGME_VALIDITY_NEVER:
145                 return _("Never");
146         case GPGME_VALIDITY_MARGINAL:
147                 return _("Marginal");
148         case GPGME_VALIDITY_FULL:
149                 return _("Full");
150         case GPGME_VALIDITY_ULTIMATE:
151                 return _("Ultimate");
152         default:
153                 return _("Error");
154         }
155 }
156
157 static gchar *extract_name(const char *uid)
158 {
159         if (uid == NULL)
160                 return NULL;
161         if (!strncmp(uid, "CN=", 3)) {
162                 gchar *result = g_strdup(uid+3);
163                 if (strstr(result, ","))
164                         *(strstr(result, ",")) = '\0';
165                 return result;
166         } else if (strstr(uid, ",CN=")) {
167                 gchar *result = g_strdup(strstr(uid, ",CN=")+4);
168                 if (strstr(result, ","))
169                         *(strstr(result, ",")) = '\0';
170                 return result;
171         } else {
172                 return g_strdup(uid);
173         }
174 }
175 gchar *sgpgme_sigstat_info_short(gpgme_ctx_t ctx, gpgme_verify_result_t status)
176 {
177         gpgme_signature_t sig = NULL;
178         gchar *uname = NULL;
179         gpgme_key_t key;
180         gchar *result = NULL;
181         gpgme_error_t err = 0;
182         static gboolean warned = FALSE;
183
184         if (GPOINTER_TO_INT(status) == -GPG_ERR_SYSTEM_ERROR) {
185                 return g_strdup_printf(_("The signature can't be checked - %s"), privacy_get_error());
186         }
187
188         if (status == NULL) {
189                 return g_strdup(_("The signature has not been checked."));
190         }
191         sig = status->signatures;
192         if (sig == NULL) {
193                 return g_strdup(_("The signature has not been checked."));
194         }
195
196         err = gpgme_get_key(ctx, sig->fpr, &key, 0);
197         if (gpg_err_code(err) == GPG_ERR_NO_AGENT) {
198                 if (!warned)
199                         alertpanel_error(_("PGP Core: Can't get key - no gpg-agent running."));
200                 else
201                         g_warning(_("PGP Core: Can't get key - no gpg-agent running."));
202                 warned = TRUE;
203         } else if (gpg_err_code(err) != GPG_ERR_NO_ERROR && gpg_err_code(err) != GPG_ERR_EOF) {
204                 return g_strdup_printf(_("The signature can't be checked - %s"), 
205                         gpgme_strerror(err));
206         }
207         if (key)
208                 uname = extract_name(key->uids->uid);
209         else
210                 uname = g_strdup("<?>");
211         switch (gpg_err_code(sig->status)) {
212         case GPG_ERR_NO_ERROR:
213                 switch (gpg_err_code(sig->validity)) {
214                 case GPGME_VALIDITY_MARGINAL:
215                 case GPGME_VALIDITY_FULL:
216                 case GPGME_VALIDITY_ULTIMATE:
217                         result = g_strdup_printf(_("Good signature from %s."), uname);
218                         break;
219                 case GPGME_VALIDITY_UNKNOWN:
220                 case GPGME_VALIDITY_UNDEFINED:
221                 case GPGME_VALIDITY_NEVER:
222                 default:
223                         result = g_strdup_printf(_("Good signature (untrusted) from %s."), uname);
224                         break;
225                 }
226                 break;
227         case GPG_ERR_SIG_EXPIRED:
228                 result = g_strdup_printf(_("Expired signature from %s."), uname);
229                 break;
230         case GPG_ERR_KEY_EXPIRED:
231                 result = g_strdup_printf(_("Expired key from %s."), uname);
232                 break;
233         case GPG_ERR_BAD_SIGNATURE:
234                 result = g_strdup_printf(_("Bad signature from %s."), uname);
235                 break;
236         case GPG_ERR_NO_PUBKEY: {
237                 gchar *id = g_strdup(sig->fpr + strlen(sig->fpr)-8);
238                 result = g_strdup_printf(_("Key 0x%s not available to verify this signature."), id);
239                 g_free(id);
240                 break;
241                 }
242         default:
243                 result = g_strdup(_("The signature has not been checked."));
244                 break;
245         }
246         if (result == NULL)
247                 result = g_strdup(_("Error"));
248         g_free(uname);
249         return result;
250 }
251
252 gchar *sgpgme_sigstat_info_full(gpgme_ctx_t ctx, gpgme_verify_result_t status)
253 {
254         gint i = 0;
255         gchar *ret;
256         GString *siginfo;
257         gpgme_signature_t sig = NULL;
258
259         siginfo = g_string_sized_new(64);
260         if (status == NULL) {
261                 g_string_append_printf(siginfo,
262                         _("Error checking signature: no status\n"));
263                 goto bail;
264          }
265
266         sig = status->signatures;
267         
268         while (sig) {
269                 gpgme_user_id_t user = NULL;
270                 gpgme_key_t key;
271                 gpgme_error_t err;
272                 const gchar *keytype, *keyid, *uid;
273                 
274                 err = gpgme_get_key(ctx, sig->fpr, &key, 0);
275
276                 if (err != GPG_ERR_NO_ERROR) {
277                         key = NULL;
278                         g_string_append_printf(siginfo, 
279                                 _("Error checking signature: %s\n"),
280                                 gpgme_strerror(err));
281                         goto bail;
282                 }
283                 if (key) {
284                         user = key->uids;
285                         keytype = gpgme_pubkey_algo_name(
286                                         key->subkeys->pubkey_algo);
287                         keyid = key->subkeys->keyid;
288                         uid = user->uid;
289                 } else {
290                         keytype = "?";
291                         keyid = "?";
292                         uid = "?";
293                 }
294                 g_string_append_printf(siginfo,
295                         _("Signature made using %s key ID %s\n"),
296                         keytype, keyid);
297                 
298                 switch (gpg_err_code(sig->status)) {
299                 case GPG_ERR_NO_ERROR:
300                 case GPG_ERR_KEY_EXPIRED:
301                         g_string_append_printf(siginfo,
302                                 _("Good signature from uid \"%s\" (Validity: %s)\n"),
303                                 uid, get_validity_str(user?user->validity:GPGME_VALIDITY_UNKNOWN));
304                         break;
305                 case GPG_ERR_SIG_EXPIRED:
306                         g_string_append_printf(siginfo,
307                                 _("Expired signature from uid \"%s\" (Validity: %s)\n"),
308                                 uid, get_validity_str(user?user->validity:GPGME_VALIDITY_UNKNOWN));
309                         break;
310                 case GPG_ERR_BAD_SIGNATURE:
311                         g_string_append_printf(siginfo,
312                                 _("BAD signature from \"%s\"\n"),
313                                 uid);
314                         break;
315                 default:
316                         break;
317                 }
318                 if (sig->status != GPG_ERR_BAD_SIGNATURE) {
319                         gint j = 1;
320                         user = user ? user->next : NULL;
321                         while (user != NULL) {
322                                 g_string_append_printf(siginfo,
323                                         _("                    uid \"%s\" (Validity: %s)\n"),
324                                         user->uid,
325                                         get_validity_str(user->validity));
326                                 j++;
327                                 user = user->next;
328                         }
329                         g_string_append_printf(siginfo,
330                                 _("Primary key fingerprint:"));
331                         const char* primary_fpr = NULL;
332                         if (key && key->subkeys && key->subkeys->fpr)
333                                 primary_fpr = key->subkeys->fpr;
334                         else
335                                 g_string_append(siginfo, " ?");
336                         int idx; /* now pretty-print the fingerprint */
337                         for (idx=0; primary_fpr && *primary_fpr!='\0'; idx++, primary_fpr++) {
338                                 if (idx%4==0)
339                                         g_string_append_c(siginfo, ' ');
340                                 if (idx%20==0)
341                                         g_string_append_c(siginfo, ' ');
342                                 g_string_append_c(siginfo, (gchar)*primary_fpr);
343                         }
344                         g_string_append_c(siginfo, '\n');
345 #ifdef HAVE_GPGME_PKA_TRUST
346                         if (sig->pka_trust == 1 && sig->pka_address) {
347                                 g_string_append_printf(siginfo,
348                                    _("WARNING: Signer's address \"%s\" "
349                                       "does not match DNS entry\n"), 
350                                    sig->pka_address);
351                         }
352                         else if (sig->pka_trust == 2 && sig->pka_address) {
353                                 g_string_append_printf(siginfo,
354                                    _("Verified signer's address is \"%s\"\n"),
355                                    sig->pka_address);
356                                 /* FIXME: Compare the address to the
357                                  * From: address.  */
358                         }
359 #endif /*HAVE_GPGME_PKA_TRUST*/
360                 }
361
362                 g_string_append(siginfo, "\n");
363                 i++;
364                 sig = sig->next;
365         }
366 bail:
367         ret = siginfo->str;
368         g_string_free(siginfo, FALSE);
369         return ret;
370 }
371
372 gpgme_data_t sgpgme_data_from_mimeinfo(MimeInfo *mimeinfo)
373 {
374         gpgme_data_t data = NULL;
375         gpgme_error_t err;
376         FILE *fp = g_fopen(mimeinfo->data.filename, "rb");
377         gchar *tmp_file = NULL;
378
379         if (!fp) 
380                 return NULL;
381
382         tmp_file = get_tmp_file();
383         copy_file_part(fp, mimeinfo->offset, mimeinfo->length, tmp_file);
384         fclose(fp);
385         fp = NULL;
386         debug_print("tmp file %s\n", tmp_file);
387         
388         err = gpgme_data_new_from_file(&data, tmp_file, 1);
389         claws_unlink(tmp_file);
390         g_free(tmp_file);
391
392         debug_print("data %p (%d %d)\n", (void *)&data, mimeinfo->offset, mimeinfo->length);
393         if (err) {
394                 debug_print ("gpgme_data_new_from_file failed: %s\n",
395                              gpgme_strerror (err));
396                 privacy_set_error(_("Couldn't get data from message, %s"), gpgme_strerror(err));
397                 return NULL;
398         }
399         return data;
400 }
401
402 gpgme_data_t sgpgme_decrypt_verify(gpgme_data_t cipher, gpgme_verify_result_t *status, gpgme_ctx_t ctx)
403 {
404         struct passphrase_cb_info_s info;
405         gpgme_data_t plain;
406         gpgme_error_t err;
407
408         memset (&info, 0, sizeof info);
409         
410         if ((err = gpgme_data_new(&plain)) != GPG_ERR_NO_ERROR) {
411                 gpgme_release(ctx);
412                 privacy_set_error(_("Couldn't initialize data, %s"), gpgme_strerror(err));
413                 return NULL;
414         }
415         
416         if (gpgme_get_protocol(ctx) == GPGME_PROTOCOL_OpenPGP) {
417                 prefs_gpg_enable_agent(prefs_gpg_get_config()->use_gpg_agent);
418                 if (!getenv("GPG_AGENT_INFO") || !prefs_gpg_get_config()->use_gpg_agent) {
419                         info.c = ctx;
420                         gpgme_set_passphrase_cb (ctx, gpgmegtk_passphrase_cb, &info);
421                 }
422         } else {
423                 prefs_gpg_enable_agent(TRUE);
424                 info.c = ctx;
425                 gpgme_set_passphrase_cb (ctx, NULL, &info);
426         }
427         
428         
429         if (gpgme_get_protocol(ctx) == GPGME_PROTOCOL_OpenPGP) {
430                 err = gpgme_op_decrypt_verify(ctx, cipher, plain);
431                 if (err != GPG_ERR_NO_ERROR) {
432                         debug_print("can't decrypt (%s)\n", gpgme_strerror(err));
433                         privacy_set_error("%s", gpgme_strerror(err));
434                         gpgmegtk_free_passphrase();
435                         gpgme_data_release(plain);
436                         return NULL;
437                 }
438
439                 err = cm_gpgme_data_rewind(plain);
440                 if (err) {
441                         debug_print("can't seek (%d %d %s)\n", err, errno, strerror(errno));
442                 }
443
444                 debug_print("decrypted.\n");
445                 *status = gpgme_op_verify_result (ctx);
446         } else {
447                 err = gpgme_op_decrypt(ctx, cipher, plain);
448                 if (err != GPG_ERR_NO_ERROR) {
449                         debug_print("can't decrypt (%s)\n", gpgme_strerror(err));
450                         privacy_set_error("%s", gpgme_strerror(err));
451                         gpgmegtk_free_passphrase();
452                         gpgme_data_release(plain);
453                         return NULL;
454                 }
455
456                 err = cm_gpgme_data_rewind(plain);
457                 if (err) {
458                         debug_print("can't seek (%d %d %s)\n", err, errno, strerror(errno));
459                 }
460
461                 debug_print("decrypted.\n");
462                 *status = gpgme_op_verify_result (ctx);
463         }
464         return plain;
465 }
466
467 gchar *sgpgme_get_encrypt_data(GSList *recp_names, gpgme_protocol_t proto)
468 {
469         SelectionResult result = KEY_SELECTION_CANCEL;
470         gpgme_key_t *keys = gpgmegtk_recipient_selection(recp_names, &result,
471                                 proto);
472         gchar *ret = NULL;
473         int i = 0;
474
475         if (!keys) {
476                 if (result == KEY_SELECTION_DONT)
477                         return g_strdup("_DONT_ENCRYPT_");
478                 else
479                         return NULL;
480         }
481         while (keys[i]) {
482                 gpgme_subkey_t skey = keys[i]->subkeys;
483                 gchar *fpr = skey->fpr;
484                 gchar *tmp = NULL;
485                 debug_print("adding %s\n", fpr);
486                 tmp = g_strconcat(ret?ret:"", fpr, " ", NULL);
487                 g_free(ret);
488                 ret = tmp;
489                 i++;
490         }
491         return ret;
492 }
493
494 gboolean sgpgme_setup_signers(gpgme_ctx_t ctx, PrefsAccount *account,
495                               const gchar *from_addr)
496 {
497         GPGAccountConfig *config;
498         const gchar *signer_addr = account->address;
499
500         gpgme_signers_clear(ctx);
501
502         if (from_addr)
503                 signer_addr = from_addr;
504         config = prefs_gpg_account_get_config(account);
505
506         switch(config->sign_key) {
507         case SIGN_KEY_DEFAULT:
508                 debug_print("using default gnupg key\n");
509                 break;
510         case SIGN_KEY_BY_FROM:
511                 debug_print("using key for %s\n", signer_addr);
512                 break;
513         case SIGN_KEY_CUSTOM:
514                 debug_print("using key for %s\n", config->sign_key_id);
515                 break;
516         }
517
518         if (config->sign_key != SIGN_KEY_DEFAULT) {
519                 const gchar *keyid;
520                 gpgme_key_t key, key2;
521                 gpgme_error_t err;
522
523                 if (config->sign_key == SIGN_KEY_BY_FROM)
524                         keyid = signer_addr;
525                 else if (config->sign_key == SIGN_KEY_CUSTOM)
526                         keyid = config->sign_key_id;
527                 else
528                         goto bail;
529
530                 err = gpgme_op_keylist_start(ctx, keyid, 1);
531                 if (!err) {
532                         do {
533                                 err = gpgme_op_keylist_next(ctx, &key);
534                                 if (!err && key && key->protocol == gpgme_get_protocol(ctx) &&
535                                     !key->expired && !key->revoked && !key->disabled)
536                                         break;
537                                 if (!err && key && key->protocol != gpgme_get_protocol(ctx)) {
538                                         debug_print("skipping a key (wrong protocol %d)\n", key->protocol);
539                                         gpgme_key_release(key);
540                                 }
541                                 if (!err && key && (key->expired || key->revoked || key->disabled)) {
542                                         
543                                         debug_print("skipping a key");
544                                         if (key->expired) 
545                                                 debug_print(" expired");
546                                         if (key->revoked) 
547                                                 debug_print(" revoked");
548                                         if (key->disabled) 
549                                                 debug_print(" disabled");
550                                         debug_print("\n");
551                                         gpgme_key_release(key);
552                                 }
553                         } while (!err);
554                 }
555                 if (err) {
556                         g_warning("setup_signers start: %s", gpgme_strerror(err));
557                         privacy_set_error(_("Secret key not found (%s)"), gpgme_strerror(err));
558                         goto bail;
559                 }
560                 
561                 do {
562                         err = gpgme_op_keylist_next(ctx, &key2);
563                         if (!err && key2 && key2->protocol == gpgme_get_protocol(ctx) &&
564                             !key2->expired && !key2->revoked && !key2->disabled)
565                                 break;
566                         if (!err && key2 && key2->protocol != gpgme_get_protocol(ctx)) {
567                                 debug_print("skipping a key (wrong protocol %d)\n", key2->protocol);
568                                 gpgme_key_release(key2);
569                         }
570                         if (!err && key2 && (key2->expired || key2->revoked || key2->disabled)) {
571                                         debug_print("skipping a key");
572                                         if (key2->expired) 
573                                                 debug_print(" expired");
574                                         if (key2->revoked) 
575                                                 debug_print(" revoked");
576                                         if (key2->disabled) 
577                                                 debug_print(" disabled");
578                                         debug_print("\n");
579                                 gpgme_key_release(key2);
580                         }
581                 } while (!err);
582                 if (!err) {
583                         gpgme_key_release(key2);
584                         g_warning("ambiguous specification of secret key '%s'\n",
585                                 keyid);
586                         privacy_set_error(_("Secret key specification is ambiguous"));
587                         goto bail;
588                 }
589                 
590                 gpgme_op_keylist_end(ctx);
591                 err = gpgme_signers_add(ctx, key);
592                 debug_print("got key (proto %d (pgp %d, smime %d).\n", key->protocol,
593                                 GPGME_PROTOCOL_OpenPGP, GPGME_PROTOCOL_CMS);
594                 gpgme_key_release(key);
595                 
596                 if (err) {
597                         g_warning("error adding secret key: %s\n", gpgme_strerror(err));
598                         privacy_set_error(_("Error setting secret key: %s"), gpgme_strerror(err));
599                         goto bail;
600                 }
601         }
602
603         prefs_gpg_account_free_config(config);
604
605         return TRUE;
606 bail:
607         prefs_gpg_account_free_config(config);
608         return FALSE;
609 }
610
611 void sgpgme_init()
612 {
613         gpgme_engine_info_t engineInfo;
614         if (gpgme_check_version("1.0.0")) {
615 #ifdef LC_CTYPE
616                 gpgme_set_locale(NULL, LC_CTYPE, setlocale(LC_CTYPE, NULL));
617 #endif
618 #ifdef LC_MESSAGES
619                 gpgme_set_locale(NULL, LC_MESSAGES, setlocale(LC_MESSAGES, NULL));
620 #endif
621                 if (!gpgme_get_engine_info(&engineInfo)) {
622                         while (engineInfo) {
623 #ifndef G_OS_WIN32
624                                 debug_print("GpgME Protocol: %s\n"
625                                             "Version: %s (req %s)\n"
626                                             "Executable: %s\n",
627                                         gpgme_get_protocol_name(engineInfo->protocol) ? gpgme_get_protocol_name(engineInfo->protocol):"???",
628                                         engineInfo->version ? engineInfo->version:"???",
629                                         engineInfo->req_version ? engineInfo->req_version:"???",
630                                         engineInfo->file_name ? engineInfo->file_name:"???");
631 #endif
632                                 if (engineInfo->protocol == GPGME_PROTOCOL_OpenPGP
633                                 &&  gpgme_engine_check_version(engineInfo->protocol) != 
634                                         GPG_ERR_NO_ERROR) {
635                                         if (engineInfo->file_name && !engineInfo->version) {
636                                                 alertpanel_error(_("Gpgme protocol '%s' is unusable: "
637                                                                    "Engine '%s' isn't installed properly."),
638                                                                    gpgme_get_protocol_name(engineInfo->protocol),
639                                                                    engineInfo->file_name);
640                                         } else if (engineInfo->file_name && engineInfo->version
641                                           && engineInfo->req_version) {
642                                                 alertpanel_error(_("Gpgme protocol '%s' is unusable: "
643                                                                    "Engine '%s' version %s is installed, "
644                                                                    "but version %s is required.\n"),
645                                                                    gpgme_get_protocol_name(engineInfo->protocol),
646                                                                    engineInfo->file_name,
647                                                                    engineInfo->version,
648                                                                    engineInfo->req_version);
649                                         } else {
650                                                 alertpanel_error(_("Gpgme protocol '%s' is unusable "
651                                                                    "(unknown problem)"),
652                                                                    gpgme_get_protocol_name(engineInfo->protocol));
653                                         }
654                                 }
655                                 engineInfo = engineInfo->next;
656                         }
657                 }
658         } else {
659                 sgpgme_disable_all();
660
661                 if (prefs_gpg_get_config()->gpg_warning) {
662                         AlertValue val;
663
664                         val = alertpanel_full
665                                 (_("Warning"),
666                                  _("GnuPG is not installed properly, or needs "
667                                  "to be upgraded.\n"
668                                  "OpenPGP support disabled."),
669                                  GTK_STOCK_CLOSE, NULL, NULL, TRUE, NULL,
670                                  ALERT_WARNING, G_ALERTDEFAULT);
671                         if (val & G_ALERTDISABLE)
672                                 prefs_gpg_get_config()->gpg_warning = FALSE;
673                 }
674         }
675 }
676
677 void sgpgme_done()
678 {
679         gpgmegtk_free_passphrase();
680 }
681
682 void sgpgme_create_secret_key(PrefsAccount *account, gboolean ask_create)
683 {
684         AlertValue val = G_ALERTDEFAULT;
685         gchar *key_parms = NULL;
686         gchar *name = NULL;
687         gchar *email = NULL;
688         gchar *passphrase = NULL, *passphrase_second = NULL;
689         gint prev_bad = 0;
690         gchar *tmp = NULL;
691         gpgme_error_t err = 0;
692         gpgme_ctx_t ctx;
693         GtkWidget *window = NULL;
694         gpgme_genkey_result_t key;
695
696         if (account == NULL)
697                 account = account_get_default();
698
699         if (account->address == NULL) {
700                 alertpanel_error(_("You have to save the account's information with \"OK\" "
701                                    "before being able to generate a key pair.\n"));
702                 return;
703         }
704         if (ask_create) {
705                 val = alertpanel(_("No PGP key found"),
706                                 _("Claws Mail did not find a secret PGP key, "
707                                   "which means that you won't be able to sign "
708                                   "emails or receive encrypted emails.\n"
709                                   "Do you want to create a new key pair now?"),
710                                   GTK_STOCK_NO, "+" GTK_STOCK_YES, NULL);
711                 if (val == G_ALERTDEFAULT) {
712                         prefs_gpg_get_config()->gpg_ask_create_key = FALSE;
713                         prefs_gpg_save_config();
714                         return;
715                 }
716         }
717
718         if (account->name) {
719                 name = g_strdup(account->name);
720         } else {
721                 name = g_strdup(account->address);
722         }
723         email = g_strdup(account->address);
724         tmp = g_strdup_printf("%s <%s>", account->name?account->name:account->address, account->address);
725 again:
726         passphrase = passphrase_mbox(tmp, NULL, prev_bad, 1);
727         if (passphrase == NULL) {
728                 g_free(tmp);
729                 g_free(email);
730                 g_free(name);           
731                 return;
732         }
733         passphrase_second = passphrase_mbox(tmp, NULL, 0, 2);
734         if (passphrase_second == NULL) {
735                 g_free(tmp);
736                 g_free(email);
737                 g_free(passphrase);             
738                 g_free(name);           
739                 return;
740         }
741         if (strcmp(passphrase, passphrase_second)) {
742                 g_free(passphrase);
743                 g_free(passphrase_second);
744                 prev_bad = 1;
745                 goto again;
746         }
747         
748         key_parms = g_strdup_printf("<GnupgKeyParms format=\"internal\">\n"
749                                         "Key-Type: DSA\n"
750                                         "Key-Length: 1024\n"
751                                         "Subkey-Type: ELG-E\n"
752                                         "Subkey-Length: 2048\n"
753                                         "Name-Real: %s\n"
754                                         "Name-Email: %s\n"
755                                         "Expire-Date: 0\n"
756                                         "%s%s%s"
757                                         "</GnupgKeyParms>\n",
758                                         name, email, 
759                                         strlen(passphrase)?"Passphrase: ":"",
760                                         passphrase,
761                                         strlen(passphrase)?"\n":"");
762 #ifndef G_PLATFORM_WIN32
763         if (mlock(passphrase, strlen(passphrase)) == -1)
764                 debug_print("couldn't lock passphrase\n");
765         if (mlock(passphrase_second, strlen(passphrase_second)) == -1)
766                 debug_print("couldn't lock passphrase2\n");
767 #endif
768         g_free(tmp);
769         g_free(email);
770         g_free(name);
771         g_free(passphrase_second);
772         g_free(passphrase);
773         
774         err = gpgme_new (&ctx);
775         if (err) {
776                 alertpanel_error(_("Couldn't generate a new key pair: %s"),
777                                  gpgme_strerror(err));
778                 g_free(key_parms);
779                 return;
780         }
781         
782
783         window = label_window_create(_("Generating your new key pair... Please move the mouse "
784                               "around to help generate entropy..."));
785
786         err = gpgme_op_genkey(ctx, key_parms, NULL, NULL);
787         g_free(key_parms);
788
789         label_window_destroy(window);
790
791         if (err) {
792                 alertpanel_error(_("Couldn't generate a new key pair: %s"), gpgme_strerror(err));
793                 gpgme_release(ctx);
794                 return;
795         }
796         key = gpgme_op_genkey_result(ctx);
797         if (key == NULL) {
798                 alertpanel_error(_("Couldn't generate a new key pair: unknown error"));
799                 gpgme_release(ctx);
800                 return;
801         } else {
802                 gchar *buf = g_strdup_printf(_("Your new key pair has been generated. "
803                                     "Its fingerprint is:\n%s\n\nDo you want to export it "
804                                     "to a keyserver?"),
805                                     key->fpr ? key->fpr:"null");
806                 AlertValue val = alertpanel(_("Key generated"), buf,
807                                   GTK_STOCK_NO, "+" GTK_STOCK_YES, NULL);
808                 g_free(buf);
809                 if (val == G_ALERTALTERNATE) {
810 #ifndef G_OS_WIN32
811                         gchar *cmd = g_strdup_printf("gpg --no-tty --send-keys %s", key->fpr);
812                         int res = 0;
813                         pid_t pid = 0;
814                         pid = fork();
815                         if (pid == -1) {
816                                 res = -1;
817                         } else if (pid == 0) {
818                                 /* son */
819                                 res = system(cmd);
820                                 res = WEXITSTATUS(res);
821                                 _exit(res);
822                         } else {
823                                 int status = 0;
824                                 time_t start_wait = time(NULL);
825                                 res = -1;
826                                 do {
827                                         if (waitpid(pid, &status, WNOHANG) == 0 || !WIFEXITED(status)) {
828                                                 usleep(200000);
829                                         } else {
830                                                 res = WEXITSTATUS(status);
831                                                 break;
832                                         }
833                                         if (time(NULL) - start_wait > 5) {
834                                                 debug_print("SIGTERM'ing gpg\n");
835                                                 kill(pid, SIGTERM);
836                                         }
837                                         if (time(NULL) - start_wait > 6) {
838                                                 debug_print("SIGKILL'ing gpg\n");
839                                                 kill(pid, SIGKILL);
840                                                 break;
841                                         }
842                                 } while(1);
843                         }
844                         if (res == 0) {
845                                 alertpanel_notice(_("Key exported."));
846                         } else {
847                                 alertpanel_error(_("Couldn't export key."));
848                         }
849                         g_free(cmd);
850 #else
851                         alertpanel_error(_("Key export isn't implemented in Windows."));
852 #endif
853                 }
854         }
855         prefs_gpg_get_config()->gpg_ask_create_key = FALSE;
856         prefs_gpg_save_config();
857         gpgme_release(ctx);
858 }
859
860 gboolean sgpgme_has_secret_key(void)
861 {
862         gpgme_error_t err = 0;
863         gpgme_ctx_t ctx;
864         gpgme_key_t key;
865
866         err = gpgme_new (&ctx);
867         if (err) {
868                 debug_print("err : %s\n", gpgme_strerror(err));
869                 return TRUE;
870         }
871 check_again:
872         err = gpgme_op_keylist_start(ctx, NULL, TRUE);
873         if (!err)
874                 err = gpgme_op_keylist_next(ctx, &key);
875         gpgme_op_keylist_end(ctx);
876         if (gpg_err_code(err) == GPG_ERR_EOF) {
877                 if (gpgme_get_protocol(ctx) != GPGME_PROTOCOL_CMS) {
878                         gpgme_set_protocol(ctx, GPGME_PROTOCOL_CMS);
879                         goto check_again;
880                 }
881                 gpgme_release(ctx);
882                 return FALSE;
883         } else {
884                 gpgme_release(ctx);
885                 return TRUE;
886         }
887 }
888
889 void sgpgme_check_create_key(void)
890 {
891         if (prefs_gpg_get_config()->gpg_ask_create_key &&
892             !sgpgme_has_secret_key()) {
893                 sgpgme_create_secret_key(NULL, TRUE);
894         } else {
895                 prefs_gpg_get_config()->gpg_ask_create_key = FALSE;
896                 prefs_gpg_save_config();
897         }       
898 }
899
900 void *sgpgme_data_release_and_get_mem(gpgme_data_t data, size_t *len)
901 {
902         char buf[BUFSIZ];
903         void *result = NULL;
904         ssize_t r = 0;
905         size_t w = 0;
906         
907         if (data == NULL)
908                 return NULL;
909         if (len == NULL)
910                 return NULL;
911
912         /* I know it's deprecated, but we don't compile with _LARGEFILE */
913         cm_gpgme_data_rewind(data);
914         while ((r = gpgme_data_read(data, buf, BUFSIZ)) > 0) {
915                 result = realloc(result, r + w);
916                 memcpy(result+w, buf, r);
917                 w += r;
918         }
919         
920         *len = w;
921
922         gpgme_data_release(data);
923         if (r < 0) {
924                 free(result);
925                 *len = 0;
926                 return NULL;
927         }
928         return result;
929 }
930
931 gpgme_error_t cm_gpgme_data_rewind(gpgme_data_t dh)
932 {
933 #if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS == 64
934         if (gpgme_data_seek(dh, (off_t)0, SEEK_SET) == -1)
935                 return gpg_error_from_errno(errno);
936         else
937                 return 0;
938 #else
939         return gpgme_data_rewind(dh);
940 #endif
941 }
942
943 #endif /* USE_GPGME */