2006-11-12 [colin] 2.6.0cvs36
[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
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")) {
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                         gpgmegtk_free_passphrase();
412                         gpgme_data_release(plain);
413                         return NULL;
414                 }
415
416                 err = gpgme_data_rewind(plain);
417                 if (err) {
418                         debug_print("can't seek (%d %d %s)\n", err, errno, strerror(errno));
419                 }
420
421                 debug_print("decrypted.\n");
422                 *status = gpgme_op_verify_result (ctx);
423         }
424         return plain;
425 }
426
427 gchar *sgpgme_get_encrypt_data(GSList *recp_names, gpgme_protocol_t proto)
428 {
429         SelectionResult result = KEY_SELECTION_CANCEL;
430         gpgme_key_t *keys = gpgmegtk_recipient_selection(recp_names, &result,
431                                 proto);
432         gchar *ret = NULL;
433         int i = 0;
434
435         if (!keys) {
436                 if (result == KEY_SELECTION_DONT)
437                         return g_strdup("_DONT_ENCRYPT_");
438                 else
439                         return NULL;
440         }
441         while (keys[i]) {
442                 gpgme_subkey_t skey = keys[i]->subkeys;
443                 gchar *fpr = skey->fpr;
444                 gchar *tmp = NULL;
445                 debug_print("adding %s\n", fpr);
446                 tmp = g_strconcat(ret?ret:"", fpr, " ", NULL);
447                 g_free(ret);
448                 ret = tmp;
449                 i++;
450         }
451         return ret;
452 }
453
454 gboolean sgpgme_setup_signers(gpgme_ctx_t ctx, PrefsAccount *account)
455 {
456         GPGAccountConfig *config;
457
458         gpgme_signers_clear(ctx);
459
460         config = prefs_gpg_account_get_config(account);
461
462         switch(config->sign_key) {
463         case SIGN_KEY_DEFAULT:
464                 debug_print("using default gnupg key\n");
465                 break;
466         case SIGN_KEY_BY_FROM:
467                 debug_print("using key for %s\n", account->address);
468                 break;
469         case SIGN_KEY_CUSTOM:
470                 debug_print("using key for %s\n", config->sign_key_id);
471                 break;
472         }
473
474         if (config->sign_key != SIGN_KEY_DEFAULT) {
475                 gchar *keyid;
476                 gpgme_key_t key, key2;
477                 gpgme_error_t err;
478
479                 if (config->sign_key == SIGN_KEY_BY_FROM)
480                         keyid = account->address;
481                 else if (config->sign_key == SIGN_KEY_CUSTOM)
482                         keyid = config->sign_key_id;
483                 else
484                         goto bail;
485
486                 err = gpgme_op_keylist_start(ctx, keyid, 1);
487                 if (!err)
488                         err = gpgme_op_keylist_next(ctx, &key);
489                 if (err) {
490                         g_warning("setup_signers start: %s", gpgme_strerror(err));
491                         privacy_set_error(_("Secret key not found (%s)"), gpgme_strerror(err));
492                         goto bail;
493                 }
494                 
495                 err = gpgme_op_keylist_next(ctx, &key2);
496                 if (!err) {
497                         g_warning("ambiguous specification of secret key '%s'\n",
498                                 keyid);
499                         privacy_set_error(_("Secret key specification is ambiguous"));
500                         goto bail;
501                 }
502                 
503                 gpgme_op_keylist_end(ctx);
504                 err = gpgme_signers_add(ctx, key);
505                 gpgme_key_release(key);
506                 
507                 if (err) {
508                         g_warning("error adding secret key: %s\n", gpgme_strerror(err));
509                         privacy_set_error(_("Error setting secret key: %s"), gpgme_strerror(err));
510                         goto bail;
511                 }
512         }
513
514         prefs_gpg_account_free_config(config);
515
516         return TRUE;
517 bail:
518         prefs_gpg_account_free_config(config);
519         return FALSE;
520 }
521
522 void sgpgme_init()
523 {
524         gpgme_engine_info_t engineInfo;
525         if (gpgme_check_version("1.0.0")) {
526 #ifdef LC_CTYPE
527                 gpgme_set_locale(NULL, LC_CTYPE, setlocale(LC_CTYPE, NULL));
528 #endif
529 #ifdef LC_MESSAGES
530                 gpgme_set_locale(NULL, LC_MESSAGES, setlocale(LC_MESSAGES, NULL));
531 #endif
532                 if (!gpgme_get_engine_info(&engineInfo)) {
533                         while (engineInfo) {
534                                 debug_print("GpgME Protocol: %s\n"
535                                             "Version: %s (req %s)\n"
536                                             "Executable: %s\n",
537                                         gpgme_get_protocol_name(engineInfo->protocol),
538                                         engineInfo->version ? engineInfo->version:"???",
539                                         engineInfo->req_version ? engineInfo->req_version:"???",
540                                         engineInfo->file_name ? engineInfo->file_name:"???");
541                                 if (engineInfo->protocol == GPGME_PROTOCOL_OpenPGP
542                                 &&  gpgme_engine_check_version(engineInfo->protocol) != 
543                                         GPG_ERR_NO_ERROR) {
544                                         if (engineInfo->file_name && !engineInfo->version) {
545                                                 alertpanel_error(_("Gpgme protocol '%s' is unusable: "
546                                                                    "Engine '%s' isn't installed properly."),
547                                                                    gpgme_get_protocol_name(engineInfo->protocol),
548                                                                    engineInfo->file_name);
549                                         } else if (engineInfo->file_name && engineInfo->version
550                                           && engineInfo->req_version) {
551                                                 alertpanel_error(_("Gpgme protocol '%s' is unusable: "
552                                                                    "Engine '%s' version %s is installed, "
553                                                                    "but version %s is required.\n"),
554                                                                    gpgme_get_protocol_name(engineInfo->protocol),
555                                                                    engineInfo->file_name,
556                                                                    engineInfo->version,
557                                                                    engineInfo->req_version);
558                                         } else {
559                                                 alertpanel_error(_("Gpgme protocol '%s' is unusable "
560                                                                    "(unknown problem)"),
561                                                                    gpgme_get_protocol_name(engineInfo->protocol));
562                                         }
563                                 }
564                                 engineInfo = engineInfo->next;
565                         }
566                 }
567         } else {
568                 sgpgme_disable_all();
569
570                 if (prefs_gpg_get_config()->gpg_warning) {
571                         AlertValue val;
572
573                         val = alertpanel_full
574                                 (_("Warning"),
575                                  _("GnuPG is not installed properly, or needs "
576                                  "to be upgraded.\n"
577                                  "OpenPGP support disabled."),
578                                  GTK_STOCK_CLOSE, NULL, NULL, TRUE, NULL,
579                                  ALERT_WARNING, G_ALERTDEFAULT);
580                         if (val & G_ALERTDISABLE)
581                                 prefs_gpg_get_config()->gpg_warning = FALSE;
582                 }
583         }
584 }
585
586 void sgpgme_done()
587 {
588         gpgmegtk_free_passphrase();
589 }
590
591 void sgpgme_create_secret_key(PrefsAccount *account, gboolean ask_create)
592 {
593         AlertValue val = G_ALERTDEFAULT;
594         gchar *key_parms = NULL;
595         gchar *name = NULL;
596         gchar *email = NULL;
597         gchar *passphrase = NULL, *passphrase_second = NULL;
598         gint prev_bad = 0;
599         gchar *tmp = NULL;
600         gpgme_error_t err = 0;
601         gpgme_ctx_t ctx;
602         GtkWidget *window = NULL;
603         gpgme_genkey_result_t key;
604
605         if (account == NULL)
606                 account = account_get_default();
607
608         if (account->address == NULL) {
609                 alertpanel_error(_("You have to save the account's information with \"OK\" "
610                                    "before being able to generate a key pair.\n"));
611                 return;
612         }
613         if (ask_create) {
614                 val = alertpanel(_("No PGP key found"),
615                                 _("Claws Mail did not find a secret PGP key, "
616                                   "which means that you won't be able to sign "
617                                   "emails or receive encrypted emails.\n"
618                                   "Do you want to create a new key pair now?"),
619                                   GTK_STOCK_NO, "+" GTK_STOCK_YES, NULL);
620                 if (val == G_ALERTDEFAULT) {
621                         prefs_gpg_get_config()->gpg_ask_create_key = FALSE;
622                         prefs_gpg_save_config();
623                         return;
624                 }
625         }
626
627         if (account->name) {
628                 name = g_strdup(account->name);
629         } else {
630                 name = g_strdup(account->address);
631         }
632         email = g_strdup(account->address);
633         tmp = g_strdup_printf("%s <%s>", account->name?account->name:account->address, account->address);
634 again:
635         passphrase = passphrase_mbox(tmp, NULL, prev_bad, 1);
636         if (passphrase == NULL) {
637                 g_free(tmp);
638                 g_free(email);
639                 g_free(name);           
640                 return;
641         }
642         passphrase_second = passphrase_mbox(tmp, NULL, 0, 2);
643         if (passphrase_second == NULL) {
644                 g_free(tmp);
645                 g_free(email);
646                 g_free(passphrase);             
647                 g_free(name);           
648                 return;
649         }
650         if (strcmp(passphrase, passphrase_second)) {
651                 g_free(passphrase);
652                 g_free(passphrase_second);
653                 prev_bad = 1;
654                 goto again;
655         }
656         
657         key_parms = g_strdup_printf("<GnupgKeyParms format=\"internal\">\n"
658                                         "Key-Type: DSA\n"
659                                         "Key-Length: 1024\n"
660                                         "Subkey-Type: ELG-E\n"
661                                         "Subkey-Length: 2048\n"
662                                         "Name-Real: %s\n"
663                                         "Name-Email: %s\n"
664                                         "Expire-Date: 0\n"
665                                         "%s%s%s"
666                                         "</GnupgKeyParms>\n",
667                                         name, email, 
668                                         strlen(passphrase)?"Passphrase: ":"",
669                                         passphrase,
670                                         strlen(passphrase)?"\n":"");
671 #ifndef G_PLATFORM_WIN32
672         if (mlock(passphrase, strlen(passphrase)) == -1)
673                 debug_print("couldn't lock passphrase\n");
674         if (mlock(passphrase_second, strlen(passphrase_second)) == -1)
675                 debug_print("couldn't lock passphrase2\n");
676 #endif
677         g_free(tmp);
678         g_free(email);
679         g_free(name);
680         g_free(passphrase_second);
681         g_free(passphrase);
682         
683         err = gpgme_new (&ctx);
684         if (err) {
685                 alertpanel_error(_("Couldn't generate a new key pair: %s"),
686                                  gpgme_strerror(err));
687                 g_free(key_parms);
688                 return;
689         }
690         
691
692         window = label_window_create(_("Generating your new key pair... Please move the mouse "
693                               "around to help generate entropy..."));
694
695         err = gpgme_op_genkey(ctx, key_parms, NULL, NULL);
696         g_free(key_parms);
697
698         gtk_widget_destroy(window);
699
700         if (err) {
701                 alertpanel_error(_("Couldn't generate a new key pair: %s"), gpgme_strerror(err));
702                 gpgme_release(ctx);
703                 return;
704         }
705         key = gpgme_op_genkey_result(ctx);
706         if (key == NULL) {
707                 alertpanel_error(_("Couldn't generate a new key pair: unknown error"));
708                 gpgme_release(ctx);
709                 return;
710         } else {
711                 gchar *buf = g_strdup_printf(_("Your new key pair has been generated. "
712                                     "Its fingerprint is:\n%s\n\nDo you want to export it "
713                                     "to a keyserver?"),
714                                     key->fpr ? key->fpr:"null");
715                 AlertValue val = alertpanel(_("Key generated"), buf,
716                                   GTK_STOCK_NO, "+" GTK_STOCK_YES, NULL);
717                 g_free(buf);
718                 if (val == G_ALERTALTERNATE) {
719 #ifndef G_OS_WIN32
720                         gchar *cmd = g_strdup_printf("gpg --no-tty --send-keys %s", key->fpr);
721                         int res = 0;
722                         pid_t pid = 0;
723                         pid = fork();
724                         if (pid == -1) {
725                                 res = -1;
726                         } else if (pid == 0) {
727                                 /* son */
728                                 res = system(cmd);
729                                 res = WEXITSTATUS(res);
730                                 _exit(res);
731                         } else {
732                                 int status = 0;
733                                 time_t start_wait = time(NULL);
734                                 res = -1;
735                                 do {
736                                         if (waitpid(pid, &status, WNOHANG) == 0 || !WIFEXITED(status)) {
737                                                 usleep(200000);
738                                         } else {
739                                                 res = WEXITSTATUS(status);
740                                                 break;
741                                         }
742                                         if (time(NULL) - start_wait > 5) {
743                                                 debug_print("SIGTERM'ing gpg\n");
744                                                 kill(pid, SIGTERM);
745                                         }
746                                         if (time(NULL) - start_wait > 6) {
747                                                 debug_print("SIGKILL'ing gpg\n");
748                                                 kill(pid, SIGKILL);
749                                                 break;
750                                         }
751                                 } while(1);
752                         }
753                         if (res == 0) {
754                                 alertpanel_notice(_("Key exported."));
755                         } else {
756                                 alertpanel_error(_("Couldn't export key."));
757                         }
758                         g_free(cmd);
759 #else
760                         alertpanel_error(_("Key export isn't implemented in Windows."));
761 #endif
762                 }
763         }
764         prefs_gpg_get_config()->gpg_ask_create_key = FALSE;
765         prefs_gpg_save_config();
766         gpgme_release(ctx);
767 }
768
769 gboolean sgpgme_has_secret_key(void)
770 {
771         gpgme_error_t err = 0;
772         gpgme_ctx_t ctx;
773         gpgme_key_t key;
774
775         err = gpgme_new (&ctx);
776         if (err) {
777                 debug_print("err : %s\n", gpgme_strerror(err));
778                 return TRUE;
779         }
780         err = gpgme_op_keylist_start(ctx, NULL, TRUE);
781         if (!err)
782                 err = gpgme_op_keylist_next(ctx, &key);
783         gpgme_op_keylist_end(ctx);
784         gpgme_release(ctx);
785         if (gpg_err_code(err) == GPG_ERR_EOF)
786                 return FALSE;
787         else
788                 return TRUE;
789 }
790
791 void sgpgme_check_create_key(void)
792 {
793         if (prefs_gpg_get_config()->gpg_ask_create_key &&
794             !sgpgme_has_secret_key()) {
795                 sgpgme_create_secret_key(NULL, TRUE);
796         } else {
797                 prefs_gpg_get_config()->gpg_ask_create_key = FALSE;
798                 prefs_gpg_save_config();
799         }       
800 }
801 #endif /* USE_GPGME */