Fix a few memory leaks when enumerating keys with GpgME.
[claws.git] / src / plugins / pgpcore / sgpgme.c
index 7d0fd9f52190c1e42f44c997d06bfe70c1a94db6..0579f42056e51f609ce5704830efeb0464f2c63e 100644 (file)
@@ -1,6 +1,6 @@
 /*
  * Claws Mail -- a GTK+ based, lightweight, and fast e-mail client
- * Copyright (C) 1999-2012 the Claws Mail team
+ * Copyright (C) 1999-2016 the Claws Mail team
  *
  * This program is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
  *
  * You should have received a copy of the GNU General Public License
  * along with this program. If not, see <http://www.gnu.org/licenses/>.
- * 
  */
+
 #ifdef HAVE_CONFIG_H
 #  include "config.h"
 #include "claws-features.h"
 #endif
+
 #ifdef USE_GPGME
 
 #include <time.h>
@@ -36,6 +35,9 @@
 #include <sys/types.h>
 #ifndef G_OS_WIN32
 #  include <sys/wait.h>
+#else
+#  include <pthread.h>
+#  include <windows.h>
 #endif
 #if (defined(__DragonFly__) || defined(SOLARIS) || defined (__NetBSD__) || defined (__FreeBSD__) || defined (__OpenBSD__))
 #  include <sys/signal.h>
@@ -56,6 +58,7 @@
 #include "prefs_gpg.h"
 #include "account.h"
 #include "select-keys.h"
+#include "claws.h"
 
 static void sgpgme_disable_all(void)
 {
@@ -106,7 +109,7 @@ SignatureStatus sgpgme_sigstat_gpgme_to_privacy(gpgme_ctx_t ctx, gpgme_verify_re
        debug_print("err code %d\n", gpg_err_code(sig->status));
        switch (gpg_err_code(sig->status)) {
        case GPG_ERR_NO_ERROR:
-               switch (gpg_err_code(sig->validity)) {
+               switch (sig->validity) {
                case GPGME_VALIDITY_NEVER:
                        return SIGNATURE_INVALID;
                case GPGME_VALIDITY_UNKNOWN:
@@ -153,6 +156,56 @@ static const gchar *get_validity_str(unsigned long validity)
        }
 }
 
+static const gchar *get_owner_trust_str(unsigned long owner_trust)
+{
+       switch (gpgme_err_code(owner_trust)) {
+       case GPGME_VALIDITY_NEVER:
+               return _("Untrusted");
+       case GPGME_VALIDITY_MARGINAL:
+               return _("Marginal");
+       case GPGME_VALIDITY_FULL:
+               return _("Full");
+       case GPGME_VALIDITY_ULTIMATE:
+               return _("Ultimate");
+       default:
+               return _("Unknown");
+       }
+}
+
+gchar *get_gpg_executable_name()
+{
+       gpgme_engine_info_t e;
+
+       if (!gpgme_get_engine_info(&e)) {
+               while (e != NULL) {
+                       if (e->protocol == GPGME_PROTOCOL_OpenPGP
+                                       && e->file_name != NULL) {
+                               debug_print("Found gpg executable: '%s'\n", e->file_name);
+                               return e->file_name;
+                       }
+               }
+       }
+
+       return NULL;
+}
+
+static gchar *get_gpg_version_string()
+{
+       gpgme_engine_info_t e;
+
+       if (!gpgme_get_engine_info(&e)) {
+               while (e != NULL) {
+                       if (e->protocol == GPGME_PROTOCOL_OpenPGP
+                                       && e->version != NULL) {
+                               debug_print("Got OpenPGP version: '%s'\n", e->version);
+                               return e->version;
+                       }
+               }
+       }
+
+       return NULL;
+}
+
 static gchar *extract_name(const char *uid)
 {
        if (uid == NULL)
@@ -197,49 +250,64 @@ gchar *sgpgme_sigstat_info_short(gpgme_ctx_t ctx, gpgme_verify_result_t status)
                if (!warned)
                        alertpanel_error(_("PGP Core: Can't get key - no gpg-agent running."));
                else
-                       g_warning(_("PGP Core: Can't get key - no gpg-agent running."));
+                       g_warning("PGP Core: Can't get key - no gpg-agent running.");
                warned = TRUE;
        } else if (gpg_err_code(err) != GPG_ERR_NO_ERROR && gpg_err_code(err) != GPG_ERR_EOF) {
                return g_strdup_printf(_("The signature can't be checked - %s"), 
                        gpgme_strerror(err));
-       }
+  }
+
        if (key)
                uname = extract_name(key->uids->uid);
        else
                uname = g_strdup("<?>");
+
        switch (gpg_err_code(sig->status)) {
        case GPG_ERR_NO_ERROR:
-               switch (gpg_err_code(sig->validity)) {
-               case GPGME_VALIDITY_FULL:
+               switch ((key && key->uids) ? key->uids->validity : GPGME_VALIDITY_UNKNOWN) {
                case GPGME_VALIDITY_ULTIMATE:
-                       result = g_strdup_printf(_("Good signature from %s."), uname);
+                       result = g_strdup_printf(_("Good signature from \"%s\" [ultimate]"), uname);
+                       break;
+               case GPGME_VALIDITY_FULL:
+                       result = g_strdup_printf(_("Good signature from \"%s\" [full]"), uname);
                        break;
                case GPGME_VALIDITY_MARGINAL:
+                       result = g_strdup_printf(_("Good signature from \"%s\" [marginal]"), uname);
+                       break;
                case GPGME_VALIDITY_UNKNOWN:
                case GPGME_VALIDITY_UNDEFINED:
                case GPGME_VALIDITY_NEVER:
                default:
-                       result = g_strdup_printf(_("Good signature (untrusted) from %s."), uname);
+                       if (key) {
+                               result = g_strdup_printf(_("Good signature from \"%s\""), uname);
+                       } else {
+                               gchar *id = g_strdup(sig->fpr + strlen(sig->fpr)-8);
+                               result = g_strdup_printf(_("Key 0x%s not available to verify this signature"), id);
+                               g_free(id);
+                       }
                        break;
-               }
+               }
                break;
        case GPG_ERR_SIG_EXPIRED:
-               result = g_strdup_printf(_("Expired signature from %s."), uname);
+               result = g_strdup_printf(_("Expired signature from \"%s\""), uname);
                break;
        case GPG_ERR_KEY_EXPIRED:
-               result = g_strdup_printf(_("Expired key from %s."), uname);
+               result = g_strdup_printf(_("Good signature from \"%s\", but the key has expired"), uname);
+               break;
+       case GPG_ERR_CERT_REVOKED:
+               result = g_strdup_printf(_("Good signature from \"%s\", but the key has been revoked"), uname);
                break;
        case GPG_ERR_BAD_SIGNATURE:
-               result = g_strdup_printf(_("Bad signature from %s."), uname);
+               result = g_strdup_printf(_("Bad signature from \"%s\""), uname);
                break;
        case GPG_ERR_NO_PUBKEY: {
                gchar *id = g_strdup(sig->fpr + strlen(sig->fpr)-8);
-               result = g_strdup_printf(_("Key 0x%s not available to verify this signature."), id);
+               result = g_strdup_printf(_("Key 0x%s not available to verify this signature"), id);
                g_free(id);
                break;
                }
        default:
-               result = g_strdup(_("The signature has not been checked."));
+               result = g_strdup(_("The signature has not been checked"));
                break;
        }
        if (result == NULL)
@@ -265,7 +333,8 @@ gchar *sgpgme_sigstat_info_full(gpgme_ctx_t ctx, gpgme_verify_result_t status)
        sig = status->signatures;
        
        while (sig) {
-               gpgme_user_id_t user = NULL;
+               char buf[100];
+               struct tm lt;
                gpgme_key_t key;
                gpgme_error_t err;
                const gchar *keytype, *keyid, *uid;
@@ -280,31 +349,42 @@ gchar *sgpgme_sigstat_info_full(gpgme_ctx_t ctx, gpgme_verify_result_t status)
                        goto bail;
                }
                if (key) {
-                       user = key->uids;
                        keytype = gpgme_pubkey_algo_name(
                                        key->subkeys->pubkey_algo);
                        keyid = key->subkeys->keyid;
-                       uid = user->uid;
+                       uid = key->uids->uid;
                } else {
                        keytype = "?";
                        keyid = "?";
                        uid = "?";
                }
+
+               memset(buf, 0, sizeof(buf));
+               fast_strftime(buf, sizeof(buf)-1, prefs_common_get_prefs()->date_format, localtime_r(&sig->timestamp, &lt));
                g_string_append_printf(siginfo,
-                       _("Signature made using %s key ID %s\n"),
-                       keytype, keyid);
+                       _("Signature made on %s using %s key ID %s\n"),
+                       buf, keytype, keyid);
                
                switch (gpg_err_code(sig->status)) {
                case GPG_ERR_NO_ERROR:
-               case GPG_ERR_KEY_EXPIRED:
                        g_string_append_printf(siginfo,
                                _("Good signature from uid \"%s\" (Validity: %s)\n"),
-                               uid, get_validity_str(user?user->validity:GPGME_VALIDITY_UNKNOWN));
+                               uid, get_validity_str((key && key->uids) ? key->uids->validity:GPGME_VALIDITY_UNKNOWN));
+                       break;
+               case GPG_ERR_KEY_EXPIRED:
+                       g_string_append_printf(siginfo,
+                               _("Expired key uid \"%s\"\n"),
+                               uid);
                        break;
                case GPG_ERR_SIG_EXPIRED:
                        g_string_append_printf(siginfo,
                                _("Expired signature from uid \"%s\" (Validity: %s)\n"),
-                               uid, get_validity_str(user?user->validity:GPGME_VALIDITY_UNKNOWN));
+                               uid, get_validity_str((key && key->uids) ? key->uids->validity:GPGME_VALIDITY_UNKNOWN));
+                       break;
+               case GPG_ERR_CERT_REVOKED:
+                       g_string_append_printf(siginfo,
+                               _("Revoked key uid \"%s\"\n"),
+                               uid);
                        break;
                case GPG_ERR_BAD_SIGNATURE:
                        g_string_append_printf(siginfo,
@@ -316,15 +396,20 @@ gchar *sgpgme_sigstat_info_full(gpgme_ctx_t ctx, gpgme_verify_result_t status)
                }
                if (sig->status != GPG_ERR_BAD_SIGNATURE) {
                        gint j = 1;
-                       user = user ? user->next : NULL;
-                       while (user != NULL) {
-                               g_string_append_printf(siginfo,
-                                       _("                    uid \"%s\" (Validity: %s)\n"),
-                                       user->uid,
-                                       get_validity_str(user->validity));
-                               j++;
-                               user = user->next;
+                       if (key) {
+                               key->uids = key->uids ? key->uids->next : NULL;
+                               while (key->uids != NULL) {
+                                       g_string_append_printf(siginfo,
+                                               g_strconcat("                    ",
+                                                           _("uid \"%s\" (Validity: %s)\n"), NULL),
+                                               key->uids->uid,
+                                               key->uids->revoked==TRUE?_("Revoked"):get_validity_str(key->uids->validity));
+                                       j++;
+                                       key->uids = key->uids->next;
+                               }
                        }
+                       g_string_append_printf(siginfo,_("Owner Trust: %s\n"),
+                                              key ? get_owner_trust_str(key->owner_trust) : _("No key!"));
                        g_string_append(siginfo,
                                _("Primary key fingerprint:"));
                        const char* primary_fpr = NULL;
@@ -373,20 +458,12 @@ gpgme_data_t sgpgme_data_from_mimeinfo(MimeInfo *mimeinfo)
        gpgme_data_t data = NULL;
        gpgme_error_t err;
        FILE *fp = g_fopen(mimeinfo->data.filename, "rb");
-       gchar *tmp_file = NULL;
 
        if (!fp) 
                return NULL;
 
-       tmp_file = get_tmp_file();
-       copy_file_part(fp, mimeinfo->offset, mimeinfo->length, tmp_file);
+       err = gpgme_data_new_from_filepart(&data, NULL, fp, mimeinfo->offset, mimeinfo->length);
        fclose(fp);
-       fp = NULL;
-       debug_print("tmp file %s\n", tmp_file);
-       
-       err = gpgme_data_new_from_file(&data, tmp_file, 1);
-       claws_unlink(tmp_file);
-       g_free(tmp_file);
 
        debug_print("data %p (%d %d)\n", (void *)&data, mimeinfo->offset, mimeinfo->length);
        if (err) {
@@ -414,7 +491,7 @@ gpgme_data_t sgpgme_decrypt_verify(gpgme_data_t cipher, gpgme_verify_result_t *s
        
        if (gpgme_get_protocol(ctx) == GPGME_PROTOCOL_OpenPGP) {
                prefs_gpg_enable_agent(prefs_gpg_get_config()->use_gpg_agent);
-               if (!getenv("GPG_AGENT_INFO") || !prefs_gpg_get_config()->use_gpg_agent) {
+               if (!g_getenv("GPG_AGENT_INFO") || !prefs_gpg_get_config()->use_gpg_agent) {
                        info.c = ctx;
                        gpgme_set_passphrase_cb (ctx, gpgmegtk_passphrase_cb, &info);
                }
@@ -437,7 +514,7 @@ gpgme_data_t sgpgme_decrypt_verify(gpgme_data_t cipher, gpgme_verify_result_t *s
 
                err = cm_gpgme_data_rewind(plain);
                if (err) {
-                       debug_print("can't seek (%d %d %s)\n", err, errno, strerror(errno));
+                       debug_print("can't seek (%d %d %s)\n", err, errno, g_strerror(errno));
                }
 
                debug_print("decrypted.\n");
@@ -454,7 +531,7 @@ gpgme_data_t sgpgme_decrypt_verify(gpgme_data_t cipher, gpgme_verify_result_t *s
 
                err = cm_gpgme_data_rewind(plain);
                if (err) {
-                       debug_print("can't seek (%d %d %s)\n", err, errno, strerror(errno));
+                       debug_print("can't seek (%d %d %s)\n", err, errno, g_strerror(errno));
                }
 
                debug_print("decrypted.\n");
@@ -516,7 +593,7 @@ gboolean sgpgme_setup_signers(gpgme_ctx_t ctx, PrefsAccount *account,
 
        if (config->sign_key != SIGN_KEY_DEFAULT) {
                const gchar *keyid;
-               gpgme_key_t key, key2;
+               gpgme_key_t key, found_key;
                gpgme_error_t err;
 
                if (config->sign_key == SIGN_KEY_BY_FROM)
@@ -526,78 +603,77 @@ gboolean sgpgme_setup_signers(gpgme_ctx_t ctx, PrefsAccount *account,
                else
                        goto bail;
 
-               err = gpgme_op_keylist_start(ctx, keyid, 1);
-               if (!err) {
-                       do {
-                               err = gpgme_op_keylist_next(ctx, &key);
-                               if (!err && key && key->protocol == gpgme_get_protocol(ctx) &&
-                                   !key->expired && !key->revoked && !key->disabled)
-                                       break;
-                               if (!err && key && key->protocol != gpgme_get_protocol(ctx)) {
-                                       debug_print("skipping a key (wrong protocol %d)\n", key->protocol);
-                                       gpgme_key_release(key);
-                               }
-                               if (!err && key && (key->expired || key->revoked || key->disabled)) {
-                                       
-                                       debug_print("skipping a key");
-                                       if (key->expired) 
-                                               debug_print(" expired");
-                                       if (key->revoked) 
-                                               debug_print(" revoked");
-                                       if (key->disabled) 
-                                               debug_print(" disabled");
-                                       debug_print("\n");
-                                       gpgme_key_release(key);
-                               }
-                       } while (!err);
-               }
-               if (err) {
-                       g_warning("setup_signers start: %s", gpgme_strerror(err));
-                       privacy_set_error(_("Secret key not found (%s)"), gpgme_strerror(err));
-                       goto bail;
-               }
-               
-               do {
-                       err = gpgme_op_keylist_next(ctx, &key2);
-                       if (!err && key2 && key2->protocol == gpgme_get_protocol(ctx) &&
-                           !key2->expired && !key2->revoked && !key2->disabled)
+                found_key = NULL;
+               /* Look for any key, not just private ones, or GPGMe doesn't
+                * correctly set the revoked flag. */
+               err = gpgme_op_keylist_start(ctx, keyid, 0);
+               while (err == 0) {
+                       if ((err = gpgme_op_keylist_next(ctx, &key)) != 0)
                                break;
-                       if (!err && key2 && key2->protocol != gpgme_get_protocol(ctx)) {
-                               debug_print("skipping a key (wrong protocol %d)\n", key2->protocol);
-                               gpgme_key_release(key2);
+
+                       if (key == NULL)
+                               continue;
+
+                       if (!key->can_sign) {
+                               debug_print("skipping a key, can not be used for signing\n");
+                               gpgme_key_unref(key);
+                               continue;
                        }
-                       if (!err && key2 && (key2->expired || key2->revoked || key2->disabled)) {
-                                       debug_print("skipping a key");
-                                       if (key2->expired) 
-                                               debug_print(" expired");
-                                       if (key2->revoked) 
-                                               debug_print(" revoked");
-                                       if (key2->disabled) 
-                                               debug_print(" disabled");
-                                       debug_print("\n");
-                               gpgme_key_release(key2);
+
+                       if (key->protocol != gpgme_get_protocol(ctx)) {
+                               debug_print("skipping a key (wrong protocol %d)\n", key->protocol);
+                               gpgme_key_unref(key);
+                               continue;
                        }
-               } while (!err);
-               if (!err) {
-                       gpgme_key_release(key2);
-                       g_warning("ambiguous specification of secret key '%s'\n",
-                               keyid);
-                       privacy_set_error(_("Secret key specification is ambiguous"));
-                       goto bail;
+
+                       if (key->expired) {
+                               debug_print("skipping a key, expired\n");
+                               gpgme_key_unref(key);
+                               continue;
+                       }
+                       if (key->revoked) {
+                               debug_print("skipping a key, revoked\n");
+                               gpgme_key_unref(key);
+                               continue;
+                       }
+                       if (key->disabled) {
+                               debug_print("skipping a key, disabled\n");
+                               gpgme_key_unref(key);
+                               continue;
+                       }
+
+                       if (found_key != NULL) {
+                               gpgme_key_unref(key);
+                               gpgme_op_keylist_end(ctx);
+                               g_warning("ambiguous specification of secret key '%s'", keyid);
+                               privacy_set_error(_("Secret key specification is ambiguous"));
+                               goto bail;
+                       }
+
+                       found_key = key;
                }
-               
                gpgme_op_keylist_end(ctx);
-               err = gpgme_signers_add(ctx, key);
-               debug_print("got key (proto %d (pgp %d, smime %d).\n", key->protocol,
-                               GPGME_PROTOCOL_OpenPGP, GPGME_PROTOCOL_CMS);
-               gpgme_key_release(key);
-               
+
+               if (found_key == NULL) {
+                       g_warning("setup_signers start: %s", gpgme_strerror(err));
+                       privacy_set_error(_("Secret key not found (%s)"), gpgme_strerror(err));
+                       goto bail;
+                }
+
+               err = gpgme_signers_add(ctx, found_key);
+               debug_print("got key (proto %d (pgp %d, smime %d).\n",
+                           found_key->protocol, GPGME_PROTOCOL_OpenPGP,
+                           GPGME_PROTOCOL_CMS);
+               gpgme_key_unref(found_key);
+
                if (err) {
-                       g_warning("error adding secret key: %s\n", gpgme_strerror(err));
-                       privacy_set_error(_("Error setting secret key: %s"), gpgme_strerror(err));
+                       g_warning("error adding secret key: %s",
+                                 gpgme_strerror(err));
+                       privacy_set_error(_("Error setting secret key: %s"),
+                                         gpgme_strerror(err));
                        goto bail;
                }
-       }
+        }
 
        prefs_gpg_account_free_config(config);
 
@@ -611,38 +687,70 @@ void sgpgme_init()
 {
        gchar *ctype_locale = NULL, *messages_locale = NULL;
        gchar *ctype_utf8_locale = NULL, *messages_utf8_locale = NULL;
+       gpgme_error_t err = 0;
 
        gpgme_engine_info_t engineInfo;
+
+       if (strcmp(prefs_gpg_get_config()->gpg_path, "") != 0
+           && access(prefs_gpg_get_config()->gpg_path, X_OK) != -1) {
+               err = gpgme_set_engine_info(GPGME_PROTOCOL_OpenPGP, prefs_gpg_get_config()->gpg_path, NULL);
+               if (err != GPG_ERR_NO_ERROR)
+                       g_warning("failed to set crypto engine configuration: %s", gpgme_strerror(err));
+       }
+
        if (gpgme_check_version("1.0.0")) {
 #ifdef LC_CTYPE
+               debug_print("setting gpgme CTYPE locale\n");
+#ifdef G_OS_WIN32
+               ctype_locale = g_win32_getlocale();
+#else
                ctype_locale = g_strdup(setlocale(LC_CTYPE, NULL));
-               if (strchr(ctype_locale, '.'))
-                       *(strchr(ctype_locale, '.')) = '\0';
-               else if (strchr(ctype_locale, '@'))
-                       *(strchr(ctype_locale, '@')) = '\0';
-               ctype_utf8_locale = g_strconcat(ctype_locale, ".UTF-8", NULL);
-
-               gpgme_set_locale(NULL, LC_CTYPE, ctype_utf8_locale);
-
-               g_free(ctype_utf8_locale);
-               g_free(ctype_locale);
+#endif
+               if (ctype_locale) {
+                       debug_print("setting gpgme CTYPE locale to: %s\n", ctype_locale);
+                       if (strchr(ctype_locale, '.'))
+                               *(strchr(ctype_locale, '.')) = '\0';
+                       else if (strchr(ctype_locale, '@'))
+                               *(strchr(ctype_locale, '@')) = '\0';
+                       ctype_utf8_locale = g_strconcat(ctype_locale, ".UTF-8", NULL);
+
+                       debug_print("setting gpgme locale to UTF8: %s\n", ctype_utf8_locale ? ctype_utf8_locale : "NULL");
+                       gpgme_set_locale(NULL, LC_CTYPE, ctype_utf8_locale);
+
+                       debug_print("done\n");
+                       g_free(ctype_utf8_locale);
+                       g_free(ctype_locale);
+               } else {
+                       debug_print("couldn't set gpgme CTYPE locale\n");
+               }
 #endif
 #ifdef LC_MESSAGES
+               debug_print("setting gpgme MESSAGES locale\n");
+#ifdef G_OS_WIN32
+               messages_locale = g_win32_getlocale();
+#else
                messages_locale = g_strdup(setlocale(LC_MESSAGES, NULL));
-               if (strchr(messages_locale, '.'))
-                       *(strchr(messages_locale, '.')) = '\0';
-               else if (strchr(messages_locale, '@'))
-                       *(strchr(messages_locale, '@')) = '\0';
-               messages_utf8_locale = g_strconcat(messages_locale, ".UTF-8", NULL);
-
-               gpgme_set_locale(NULL, LC_MESSAGES, messages_utf8_locale);
-
-               g_free(messages_utf8_locale);
-               g_free(messages_locale);
+#endif
+               if (messages_locale) {
+                       debug_print("setting gpgme MESSAGES locale to: %s\n", messages_locale);
+                       if (strchr(messages_locale, '.'))
+                               *(strchr(messages_locale, '.')) = '\0';
+                       else if (strchr(messages_locale, '@'))
+                               *(strchr(messages_locale, '@')) = '\0';
+                       messages_utf8_locale = g_strconcat(messages_locale, ".UTF-8", NULL);
+                       debug_print("setting gpgme locale to UTF8: %s\n", messages_utf8_locale ? messages_utf8_locale : "NULL");
+
+                       gpgme_set_locale(NULL, LC_MESSAGES, messages_utf8_locale);
+
+                       debug_print("done\n");
+                       g_free(messages_utf8_locale);
+                       g_free(messages_locale);
+               } else {
+                       debug_print("couldn't set gpgme MESSAGES locale\n");
+               }
 #endif
                if (!gpgme_get_engine_info(&engineInfo)) {
                        while (engineInfo) {
-#ifndef G_OS_WIN32
                                debug_print("GpgME Protocol: %s\n"
                                            "Version: %s (req %s)\n"
                                            "Executable: %s\n",
@@ -650,7 +758,6 @@ void sgpgme_init()
                                        engineInfo->version ? engineInfo->version:"???",
                                        engineInfo->req_version ? engineInfo->req_version:"???",
                                        engineInfo->file_name ? engineInfo->file_name:"???");
-#endif
                                if (engineInfo->protocol == GPGME_PROTOCOL_OpenPGP
                                &&  gpgme_engine_check_version(engineInfo->protocol) != 
                                        GPG_ERR_NO_ERROR) {
@@ -701,6 +808,48 @@ void sgpgme_done()
         gpgmegtk_free_passphrase();
 }
 
+#ifdef G_OS_WIN32
+struct _ExportCtx {
+       gboolean done;
+       gchar *cmd;
+       DWORD exitcode;
+};
+
+static void *_export_threaded(void *arg)
+{
+       struct _ExportCtx *ctx = (struct _ExportCtx *)arg;
+       gboolean result;
+
+       PROCESS_INFORMATION pi = {0};
+       STARTUPINFO si = {0};
+
+       result = CreateProcess(NULL, ctx->cmd, NULL, NULL, FALSE,
+                       NORMAL_PRIORITY_CLASS | CREATE_NO_WINDOW,
+                       NULL, NULL, &si, &pi);
+
+       if (!result) {
+               debug_print("Couldn't execute '%s'\n", ctx->cmd);
+       } else {
+               WaitForSingleObject(pi.hProcess, 10000);
+               result = GetExitCodeProcess(pi.hProcess, &ctx->exitcode);
+               if (ctx->exitcode == STILL_ACTIVE) {
+                       debug_print("Process still running, terminating it.\n");
+                       TerminateProcess(pi.hProcess, 255);
+               }
+
+               CloseHandle(pi.hProcess);
+               CloseHandle(pi.hThread);
+
+               if (!result) {
+                       debug_print("Process executed, but we couldn't get its exit code (huh?)\n");
+               }
+       }
+
+       ctx->done = TRUE;
+       return NULL;
+}
+#endif
+
 void sgpgme_create_secret_key(PrefsAccount *account, gboolean ask_create)
 {
        AlertValue val = G_ALERTDEFAULT;
@@ -709,11 +858,12 @@ void sgpgme_create_secret_key(PrefsAccount *account, gboolean ask_create)
        gchar *email = NULL;
        gchar *passphrase = NULL, *passphrase_second = NULL;
        gint prev_bad = 0;
-       gchar *tmp = NULL;
+       gchar *tmp = NULL, *gpgver;
        gpgme_error_t err = 0;
        gpgme_ctx_t ctx;
        GtkWidget *window = NULL;
        gpgme_genkey_result_t key;
+       gboolean exported = FALSE;
 
        if (account == NULL)
                account = account_get_default();
@@ -731,8 +881,6 @@ void sgpgme_create_secret_key(PrefsAccount *account, gboolean ask_create)
                                  "Do you want to create a new key pair now?"),
                                  GTK_STOCK_NO, "+" GTK_STOCK_YES, NULL);
                if (val == G_ALERTDEFAULT) {
-                       prefs_gpg_get_config()->gpg_ask_create_key = FALSE;
-                       prefs_gpg_save_config();
                        return;
                }
        }
@@ -744,33 +892,46 @@ void sgpgme_create_secret_key(PrefsAccount *account, gboolean ask_create)
        }
        email = g_strdup(account->address);
        tmp = g_strdup_printf("%s <%s>", account->name?account->name:account->address, account->address);
+       gpgver = get_gpg_version_string();
+       if (gpgver == NULL || !strncmp(gpgver, "1.", 2)) {
+               debug_print("Using gpg 1.x, using builtin passphrase dialog.\n");
 again:
-       passphrase = passphrase_mbox(tmp, NULL, prev_bad, 1);
-       if (passphrase == NULL) {
-               g_free(tmp);
-               g_free(email);
-               g_free(name);           
-               return;
-       }
-       passphrase_second = passphrase_mbox(tmp, NULL, 0, 2);
-       if (passphrase_second == NULL) {
-               g_free(tmp);
-               g_free(email);
-               g_free(passphrase);             
-               g_free(name);           
-               return;
-       }
-       if (strcmp(passphrase, passphrase_second)) {
-               g_free(passphrase);
-               g_free(passphrase_second);
-               prev_bad = 1;
-               goto again;
+               passphrase = passphrase_mbox(tmp, NULL, prev_bad, 1);
+               if (passphrase == NULL) {
+                       g_free(tmp);
+                       g_free(email);
+                       g_free(name);
+                       return;
+               }
+               passphrase_second = passphrase_mbox(tmp, NULL, 0, 2);
+               if (passphrase_second == NULL) {
+                       g_free(tmp);
+                       g_free(email);
+                       if (passphrase != NULL) {
+                               memset(passphrase, 0, strlen(passphrase));
+                               g_free(passphrase);
+                       }
+                       g_free(name);
+                       return;
+               }
+               if (strcmp(passphrase, passphrase_second)) {
+                       if (passphrase != NULL) {
+                               memset(passphrase, 0, strlen(passphrase));
+                               g_free(passphrase);
+                       }
+                       if (passphrase_second != NULL) {
+                               memset(passphrase_second, 0, strlen(passphrase_second));
+                               g_free(passphrase_second);
+                       }
+                       prev_bad = 1;
+                       goto again;
+               }
        }
        
        key_parms = g_strdup_printf("<GnupgKeyParms format=\"internal\">\n"
-                                       "Key-Type: DSA\n"
-                                       "Key-Length: 1024\n"
-                                       "Subkey-Type: ELG-E\n"
+                                       "Key-Type: RSA\n"
+                                       "Key-Length: 2048\n"
+                                       "Subkey-Type: RSA\n"
                                        "Subkey-Length: 2048\n"
                                        "Name-Real: %s\n"
                                        "Name-Email: %s\n"
@@ -778,26 +939,37 @@ again:
                                        "%s%s%s"
                                        "</GnupgKeyParms>\n",
                                        name, email, 
-                                       strlen(passphrase)?"Passphrase: ":"",
-                                       passphrase,
-                                       strlen(passphrase)?"\n":"");
+                                       passphrase?"Passphrase: ":"",
+                                       passphrase?passphrase:"",
+                                       passphrase?"\n":"");
 #ifndef G_PLATFORM_WIN32
-       if (mlock(passphrase, strlen(passphrase)) == -1)
+       if (passphrase &&
+                       mlock(passphrase, strlen(passphrase)) == -1)
                debug_print("couldn't lock passphrase\n");
-       if (mlock(passphrase_second, strlen(passphrase_second)) == -1)
+       if (passphrase_second &&
+                       mlock(passphrase_second, strlen(passphrase_second)) == -1)
                debug_print("couldn't lock passphrase2\n");
 #endif
        g_free(tmp);
        g_free(email);
        g_free(name);
-       g_free(passphrase_second);
-       g_free(passphrase);
+       if (passphrase_second != NULL) {
+               memset(passphrase_second, 0, strlen(passphrase_second));
+               g_free(passphrase_second);
+       }
+       if (passphrase != NULL) {
+               memset(passphrase, 0, strlen(passphrase));
+               g_free(passphrase);
+       }
        
        err = gpgme_new (&ctx);
        if (err) {
                alertpanel_error(_("Couldn't generate a new key pair: %s"),
                                 gpgme_strerror(err));
-               g_free(key_parms);
+               if (key_parms != NULL) {
+                       memset(key_parms, 0, strlen(key_parms));
+                       g_free(key_parms);
+               }
                return;
        }
        
@@ -806,7 +978,10 @@ again:
                              "around to help generate entropy..."));
 
        err = gpgme_op_genkey(ctx, key_parms, NULL, NULL);
-       g_free(key_parms);
+       if (key_parms != NULL) {
+               memset(key_parms, 0, strlen(key_parms));
+               g_free(key_parms);
+       }
 
        label_window_destroy(window);
 
@@ -829,8 +1004,12 @@ again:
                                  GTK_STOCK_NO, "+" GTK_STOCK_YES, NULL);
                g_free(buf);
                if (val == G_ALERTALTERNATE) {
+                       gchar *gpgbin = get_gpg_executable_name();
+                       gchar *cmd = g_strdup_printf("\"%s\" --batch --no-tty --send-keys %s",
+                               (gpgbin ? gpgbin : "gpg"), key->fpr);
+                       debug_print("Executing command: %s\n", cmd);
+
 #ifndef G_OS_WIN32
-                       gchar *cmd = g_strdup_printf("gpg --no-tty --send-keys %s", key->fpr);
                        int res = 0;
                        pid_t pid = 0;
                        pid = fork();
@@ -863,19 +1042,46 @@ again:
                                        }
                                } while(1);
                        }
-                       if (res == 0) {
+
+                       if (res == 0)
+                               exported = TRUE;
+#else
+                       /* We need to call gpg in a separate thread, so that waiting for
+                        * it to finish does not block the UI. */
+                       pthread_t pt;
+                       struct _ExportCtx *ectx = malloc(sizeof(struct _ExportCtx));
+
+                       ectx->done = FALSE;
+                       ectx->exitcode = STILL_ACTIVE;
+                       ectx->cmd = cmd;
+
+                       if (pthread_create(&pt, NULL,
+                                               _export_threaded, (void *)ectx) != 0) {
+                               debug_print("Couldn't create thread, continuing unthreaded.\n");
+                               _export_threaded(ctx);
+                       } else {
+                               debug_print("Thread created, waiting for it to finish...\n");
+                               while (!ectx->done)
+                                       claws_do_idle();
+                       }
+
+                       debug_print("Thread finished.\n");
+                       pthread_join(pt, NULL);
+
+                       if (ectx->exitcode == 0)
+                               exported = TRUE;
+
+                       g_free(ectx);
+#endif
+                       g_free(cmd);
+
+                       if (exported) {
                                alertpanel_notice(_("Key exported."));
                        } else {
                                alertpanel_error(_("Couldn't export key."));
                        }
-                       g_free(cmd);
-#else
-                       alertpanel_error(_("Key export isn't implemented in Windows."));
-#endif
                }
        }
-       prefs_gpg_get_config()->gpg_ask_create_key = FALSE;
-       prefs_gpg_save_config();
        gpgme_release(ctx);
 }
 
@@ -894,6 +1100,7 @@ check_again:
        err = gpgme_op_keylist_start(ctx, NULL, TRUE);
        if (!err)
                err = gpgme_op_keylist_next(ctx, &key);
+       gpgme_key_unref(key); /* We're not interested in the key itself. */
        gpgme_op_keylist_end(ctx);
        if (gpg_err_code(err) == GPG_ERR_EOF) {
                if (gpgme_get_protocol(ctx) != GPGME_PROTOCOL_CMS) {
@@ -913,10 +1120,10 @@ void sgpgme_check_create_key(void)
        if (prefs_gpg_get_config()->gpg_ask_create_key &&
            !sgpgme_has_secret_key()) {
                sgpgme_create_secret_key(NULL, TRUE);
-       } else {
-               prefs_gpg_get_config()->gpg_ask_create_key = FALSE;
-               prefs_gpg_save_config();
-       }       
+       }
+
+       prefs_gpg_get_config()->gpg_ask_create_key = FALSE;
+       prefs_gpg_save_config();
 }
 
 void *sgpgme_data_release_and_get_mem(gpgme_data_t data, size_t *len)
@@ -926,15 +1133,20 @@ void *sgpgme_data_release_and_get_mem(gpgme_data_t data, size_t *len)
        ssize_t r = 0;
        size_t w = 0;
        
-       if (data == NULL)
-               return NULL;
-       if (len == NULL)
-               return NULL;
+       cm_return_val_if_fail(data != NULL, NULL);
+       cm_return_val_if_fail(len != NULL, NULL);
 
        /* I know it's deprecated, but we don't compile with _LARGEFILE */
        cm_gpgme_data_rewind(data);
        while ((r = gpgme_data_read(data, buf, BUFSIZ)) > 0) {
-               result = realloc(result, r + w);
+               void *rresult = realloc(result, r + w);
+               if (rresult == NULL) {
+                       g_warning("can't allocate memory");
+                       if (result != NULL)
+                               free(result);
+                       return NULL;
+               }
+               result = rresult;
                memcpy(result+w, buf, r);
                w += r;
        }
@@ -943,6 +1155,7 @@ void *sgpgme_data_release_and_get_mem(gpgme_data_t data, size_t *len)
 
        gpgme_data_release(data);
        if (r < 0) {
+               g_warning("gpgme_data_read() returned an error: %d", (int)r);
                free(result);
                *len = 0;
                return NULL;