e48fb44ff7aa700696100dfdb678e34a71228d43
[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 #ifndef G_OS_WIN32
551                                 debug_print("GpgME Protocol: %s\n"
552                                             "Version: %s (req %s)\n"
553                                             "Executable: %s\n",
554                                         gpgme_get_protocol_name(engineInfo->protocol) ? gpgme_get_protocol_name(engineInfo->protocol):"???",
555                                         engineInfo->version ? engineInfo->version:"???",
556                                         engineInfo->req_version ? engineInfo->req_version:"???",
557                                         engineInfo->file_name ? engineInfo->file_name:"???");
558 #endif
559                                 if (engineInfo->protocol == GPGME_PROTOCOL_OpenPGP
560                                 &&  gpgme_engine_check_version(engineInfo->protocol) != 
561                                         GPG_ERR_NO_ERROR) {
562                                         if (engineInfo->file_name && !engineInfo->version) {
563                                                 alertpanel_error(_("Gpgme protocol '%s' is unusable: "
564                                                                    "Engine '%s' isn't installed properly."),
565                                                                    gpgme_get_protocol_name(engineInfo->protocol),
566                                                                    engineInfo->file_name);
567                                         } else if (engineInfo->file_name && engineInfo->version
568                                           && engineInfo->req_version) {
569                                                 alertpanel_error(_("Gpgme protocol '%s' is unusable: "
570                                                                    "Engine '%s' version %s is installed, "
571                                                                    "but version %s is required.\n"),
572                                                                    gpgme_get_protocol_name(engineInfo->protocol),
573                                                                    engineInfo->file_name,
574                                                                    engineInfo->version,
575                                                                    engineInfo->req_version);
576                                         } else {
577                                                 alertpanel_error(_("Gpgme protocol '%s' is unusable "
578                                                                    "(unknown problem)"),
579                                                                    gpgme_get_protocol_name(engineInfo->protocol));
580                                         }
581                                 }
582                                 engineInfo = engineInfo->next;
583                         }
584                 }
585         } else {
586                 sgpgme_disable_all();
587
588                 if (prefs_gpg_get_config()->gpg_warning) {
589                         AlertValue val;
590
591                         val = alertpanel_full
592                                 (_("Warning"),
593                                  _("GnuPG is not installed properly, or needs "
594                                  "to be upgraded.\n"
595                                  "OpenPGP support disabled."),
596                                  GTK_STOCK_CLOSE, NULL, NULL, TRUE, NULL,
597                                  ALERT_WARNING, G_ALERTDEFAULT);
598                         if (val & G_ALERTDISABLE)
599                                 prefs_gpg_get_config()->gpg_warning = FALSE;
600                 }
601         }
602 }
603
604 void sgpgme_done()
605 {
606         gpgmegtk_free_passphrase();
607 }
608
609 void sgpgme_create_secret_key(PrefsAccount *account, gboolean ask_create)
610 {
611         AlertValue val = G_ALERTDEFAULT;
612         gchar *key_parms = NULL;
613         gchar *name = NULL;
614         gchar *email = NULL;
615         gchar *passphrase = NULL, *passphrase_second = NULL;
616         gint prev_bad = 0;
617         gchar *tmp = NULL;
618         gpgme_error_t err = 0;
619         gpgme_ctx_t ctx;
620         GtkWidget *window = NULL;
621         gpgme_genkey_result_t key;
622
623         if (account == NULL)
624                 account = account_get_default();
625
626         if (account->address == NULL) {
627                 alertpanel_error(_("You have to save the account's information with \"OK\" "
628                                    "before being able to generate a key pair.\n"));
629                 return;
630         }
631         if (ask_create) {
632                 val = alertpanel(_("No PGP key found"),
633                                 _("Claws Mail did not find a secret PGP key, "
634                                   "which means that you won't be able to sign "
635                                   "emails or receive encrypted emails.\n"
636                                   "Do you want to create a new key pair now?"),
637                                   GTK_STOCK_NO, "+" GTK_STOCK_YES, NULL);
638                 if (val == G_ALERTDEFAULT) {
639                         prefs_gpg_get_config()->gpg_ask_create_key = FALSE;
640                         prefs_gpg_save_config();
641                         return;
642                 }
643         }
644
645         if (account->name) {
646                 name = g_strdup(account->name);
647         } else {
648                 name = g_strdup(account->address);
649         }
650         email = g_strdup(account->address);
651         tmp = g_strdup_printf("%s <%s>", account->name?account->name:account->address, account->address);
652 again:
653         passphrase = passphrase_mbox(tmp, NULL, prev_bad, 1);
654         if (passphrase == NULL) {
655                 g_free(tmp);
656                 g_free(email);
657                 g_free(name);           
658                 return;
659         }
660         passphrase_second = passphrase_mbox(tmp, NULL, 0, 2);
661         if (passphrase_second == NULL) {
662                 g_free(tmp);
663                 g_free(email);
664                 g_free(passphrase);             
665                 g_free(name);           
666                 return;
667         }
668         if (strcmp(passphrase, passphrase_second)) {
669                 g_free(passphrase);
670                 g_free(passphrase_second);
671                 prev_bad = 1;
672                 goto again;
673         }
674         
675         key_parms = g_strdup_printf("<GnupgKeyParms format=\"internal\">\n"
676                                         "Key-Type: DSA\n"
677                                         "Key-Length: 1024\n"
678                                         "Subkey-Type: ELG-E\n"
679                                         "Subkey-Length: 2048\n"
680                                         "Name-Real: %s\n"
681                                         "Name-Email: %s\n"
682                                         "Expire-Date: 0\n"
683                                         "%s%s%s"
684                                         "</GnupgKeyParms>\n",
685                                         name, email, 
686                                         strlen(passphrase)?"Passphrase: ":"",
687                                         passphrase,
688                                         strlen(passphrase)?"\n":"");
689 #ifndef G_PLATFORM_WIN32
690         if (mlock(passphrase, strlen(passphrase)) == -1)
691                 debug_print("couldn't lock passphrase\n");
692         if (mlock(passphrase_second, strlen(passphrase_second)) == -1)
693                 debug_print("couldn't lock passphrase2\n");
694 #endif
695         g_free(tmp);
696         g_free(email);
697         g_free(name);
698         g_free(passphrase_second);
699         g_free(passphrase);
700         
701         err = gpgme_new (&ctx);
702         if (err) {
703                 alertpanel_error(_("Couldn't generate a new key pair: %s"),
704                                  gpgme_strerror(err));
705                 g_free(key_parms);
706                 return;
707         }
708         
709
710         window = label_window_create(_("Generating your new key pair... Please move the mouse "
711                               "around to help generate entropy..."));
712
713         err = gpgme_op_genkey(ctx, key_parms, NULL, NULL);
714         g_free(key_parms);
715
716         label_window_destroy(window);
717
718         if (err) {
719                 alertpanel_error(_("Couldn't generate a new key pair: %s"), gpgme_strerror(err));
720                 gpgme_release(ctx);
721                 return;
722         }
723         key = gpgme_op_genkey_result(ctx);
724         if (key == NULL) {
725                 alertpanel_error(_("Couldn't generate a new key pair: unknown error"));
726                 gpgme_release(ctx);
727                 return;
728         } else {
729                 gchar *buf = g_strdup_printf(_("Your new key pair has been generated. "
730                                     "Its fingerprint is:\n%s\n\nDo you want to export it "
731                                     "to a keyserver?"),
732                                     key->fpr ? key->fpr:"null");
733                 AlertValue val = alertpanel(_("Key generated"), buf,
734                                   GTK_STOCK_NO, "+" GTK_STOCK_YES, NULL);
735                 g_free(buf);
736                 if (val == G_ALERTALTERNATE) {
737 #ifndef G_OS_WIN32
738                         gchar *cmd = g_strdup_printf("gpg --no-tty --send-keys %s", key->fpr);
739                         int res = 0;
740                         pid_t pid = 0;
741                         pid = fork();
742                         if (pid == -1) {
743                                 res = -1;
744                         } else if (pid == 0) {
745                                 /* son */
746                                 res = system(cmd);
747                                 res = WEXITSTATUS(res);
748                                 _exit(res);
749                         } else {
750                                 int status = 0;
751                                 time_t start_wait = time(NULL);
752                                 res = -1;
753                                 do {
754                                         if (waitpid(pid, &status, WNOHANG) == 0 || !WIFEXITED(status)) {
755                                                 usleep(200000);
756                                         } else {
757                                                 res = WEXITSTATUS(status);
758                                                 break;
759                                         }
760                                         if (time(NULL) - start_wait > 5) {
761                                                 debug_print("SIGTERM'ing gpg\n");
762                                                 kill(pid, SIGTERM);
763                                         }
764                                         if (time(NULL) - start_wait > 6) {
765                                                 debug_print("SIGKILL'ing gpg\n");
766                                                 kill(pid, SIGKILL);
767                                                 break;
768                                         }
769                                 } while(1);
770                         }
771                         if (res == 0) {
772                                 alertpanel_notice(_("Key exported."));
773                         } else {
774                                 alertpanel_error(_("Couldn't export key."));
775                         }
776                         g_free(cmd);
777 #else
778                         alertpanel_error(_("Key export isn't implemented in Windows."));
779 #endif
780                 }
781         }
782         prefs_gpg_get_config()->gpg_ask_create_key = FALSE;
783         prefs_gpg_save_config();
784         gpgme_release(ctx);
785 }
786
787 gboolean sgpgme_has_secret_key(void)
788 {
789         gpgme_error_t err = 0;
790         gpgme_ctx_t ctx;
791         gpgme_key_t key;
792
793         err = gpgme_new (&ctx);
794         if (err) {
795                 debug_print("err : %s\n", gpgme_strerror(err));
796                 return TRUE;
797         }
798         err = gpgme_op_keylist_start(ctx, NULL, TRUE);
799         if (!err)
800                 err = gpgme_op_keylist_next(ctx, &key);
801         gpgme_op_keylist_end(ctx);
802         gpgme_release(ctx);
803         if (gpg_err_code(err) == GPG_ERR_EOF)
804                 return FALSE;
805         else
806                 return TRUE;
807 }
808
809 void sgpgme_check_create_key(void)
810 {
811         if (prefs_gpg_get_config()->gpg_ask_create_key &&
812             !sgpgme_has_secret_key()) {
813                 sgpgme_create_secret_key(NULL, TRUE);
814         } else {
815                 prefs_gpg_get_config()->gpg_ask_create_key = FALSE;
816                 prefs_gpg_save_config();
817         }       
818 }
819
820 void *sgpgme_data_release_and_get_mem(gpgme_data_t data, size_t *len)
821 {
822         char buf[BUFSIZ];
823         void *result = NULL;
824         ssize_t r = 0;
825         size_t w = 0;
826         
827         if (data == NULL)
828                 return NULL;
829         if (len == NULL)
830                 return NULL;
831
832         /* I know it's deprecated, but we don't compile with _LARGEFILE */
833         gpgme_data_rewind(data);
834         while ((r = gpgme_data_read(data, buf, BUFSIZ)) > 0) {
835                 result = realloc(result, r + w);
836                 memcpy(result+w, buf, r);
837                 w += r;
838         }
839         
840         *len = w;
841
842         gpgme_data_release(data);
843         if (r < 0) {
844                 free(result);
845                 *len = 0;
846                 return NULL;
847         }
848         return result;
849 }
850 #endif /* USE_GPGME */