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