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