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