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