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