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