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