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