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