51939ded602630ef500db168247b343e38cd8010
[claws.git] / src / plugins / pgpcore / sgpgme.c
1 /*
2  * Claws Mail -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2015 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 #ifdef HAVE_CONFIG_H
20 #  include "config.h"
21 #include "claws-features.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 #else
39 #  include <pthread.h>
40 #  include <windows.h>
41 #endif
42 #if (defined(__DragonFly__) || defined(SOLARIS) || defined (__NetBSD__) || defined (__FreeBSD__) || defined (__OpenBSD__))
43 #  include <sys/signal.h>
44 #endif
45 #ifndef G_OS_WIN32
46 #include <sys/mman.h>
47 #endif
48 #if HAVE_LOCALE_H
49 #  include <locale.h>
50 #endif
51
52 #include "sgpgme.h"
53 #include "privacy.h"
54 #include "prefs_common.h"
55 #include "utils.h"
56 #include "alertpanel.h"
57 #include "passphrase.h"
58 #include "prefs_gpg.h"
59 #include "account.h"
60 #include "select-keys.h"
61 #include "claws.h"
62
63 static void sgpgme_disable_all(void)
64 {
65     /* FIXME: set a flag, so that we don't bother the user with failed
66      * gpgme messages */
67 }
68
69 gpgme_verify_result_t sgpgme_verify_signature(gpgme_ctx_t ctx, gpgme_data_t sig, 
70                                         gpgme_data_t plain, gpgme_data_t dummy)
71 {
72         gpgme_verify_result_t status = NULL;
73         gpgme_error_t err;
74
75         if ((err = gpgme_op_verify(ctx, sig, plain, dummy)) != GPG_ERR_NO_ERROR) {
76                 debug_print("op_verify err %s\n", gpgme_strerror(err));
77                 privacy_set_error("%s", gpgme_strerror(err));
78                 return GINT_TO_POINTER(-GPG_ERR_SYSTEM_ERROR);
79         }
80         status = gpgme_op_verify_result(ctx);
81         if (status && status->signatures == NULL) {
82                 debug_print("no signature found\n");
83                 privacy_set_error(_("No signature found"));
84                 return GINT_TO_POINTER(-GPG_ERR_SYSTEM_ERROR);
85         }
86         return status;
87 }
88
89 SignatureStatus sgpgme_sigstat_gpgme_to_privacy(gpgme_ctx_t ctx, gpgme_verify_result_t status)
90 {
91         gpgme_signature_t sig = NULL;
92         
93         if (GPOINTER_TO_INT(status) == -GPG_ERR_SYSTEM_ERROR) {
94                 debug_print("system error\n");
95                 return SIGNATURE_CHECK_FAILED;
96         }
97
98         if (status == NULL) {
99                 debug_print("status == NULL\n");
100                 return SIGNATURE_UNCHECKED;
101         }
102         sig = status->signatures;
103
104         if (sig == NULL) {
105                 debug_print("sig == NULL\n");
106                 return SIGNATURE_UNCHECKED;
107         }
108
109         debug_print("err code %d\n", gpg_err_code(sig->status));
110         switch (gpg_err_code(sig->status)) {
111         case GPG_ERR_NO_ERROR:
112                 switch (sig->validity) {
113                 case GPGME_VALIDITY_NEVER:
114                         return SIGNATURE_INVALID;
115                 case GPGME_VALIDITY_UNKNOWN:
116                 case GPGME_VALIDITY_UNDEFINED:
117                 case GPGME_VALIDITY_MARGINAL:
118                 case GPGME_VALIDITY_FULL:
119                 case GPGME_VALIDITY_ULTIMATE:
120                         return SIGNATURE_OK;
121                 default:
122                         return SIGNATURE_CHECK_FAILED;
123                 }
124         case GPG_ERR_SIG_EXPIRED:
125         case GPG_ERR_CERT_REVOKED:
126                 return SIGNATURE_WARN;
127         case GPG_ERR_KEY_EXPIRED:
128                 return SIGNATURE_KEY_EXPIRED;
129         case GPG_ERR_BAD_SIGNATURE:
130                 return SIGNATURE_INVALID;
131         case GPG_ERR_NO_PUBKEY:
132                 return SIGNATURE_CHECK_FAILED;
133         default:
134                 return SIGNATURE_CHECK_FAILED;
135         }
136         return SIGNATURE_CHECK_FAILED;
137 }
138
139 static const gchar *get_validity_str(unsigned long validity)
140 {
141         switch (gpg_err_code(validity)) {
142         case GPGME_VALIDITY_UNKNOWN:
143                 return _("Unknown");
144         case GPGME_VALIDITY_UNDEFINED:
145                 return _("Undefined");
146         case GPGME_VALIDITY_NEVER:
147                 return _("Never");
148         case GPGME_VALIDITY_MARGINAL:
149                 return _("Marginal");
150         case GPGME_VALIDITY_FULL:
151                 return _("Full");
152         case GPGME_VALIDITY_ULTIMATE:
153                 return _("Ultimate");
154         default:
155                 return _("Error");
156         }
157 }
158
159 static const gchar *get_owner_trust_str(unsigned long owner_trust)
160 {
161         switch (gpgme_err_code(owner_trust)) {
162         case GPGME_VALIDITY_NEVER:
163                 return _("Untrusted");
164         case GPGME_VALIDITY_MARGINAL:
165                 return _("Marginal");
166         case GPGME_VALIDITY_FULL:
167                 return _("Full");
168         case GPGME_VALIDITY_ULTIMATE:
169                 return _("Ultimate");
170         default:
171                 return _("Unknown");
172         }
173 }
174
175 gchar *get_gpg_executable_name()
176 {
177         gpgme_engine_info_t e;
178
179         if (!gpgme_get_engine_info(&e)) {
180                 while (e != NULL) {
181                         if (e->protocol == GPGME_PROTOCOL_OpenPGP
182                                         && e->file_name != NULL) {
183                                 debug_print("Found gpg executable: '%s'\n", e->file_name);
184                                 return e->file_name;
185                         }
186                 }
187         }
188
189         return NULL;
190 }
191
192 static gchar *extract_name(const char *uid)
193 {
194         if (uid == NULL)
195                 return NULL;
196         if (!strncmp(uid, "CN=", 3)) {
197                 gchar *result = g_strdup(uid+3);
198                 if (strstr(result, ","))
199                         *(strstr(result, ",")) = '\0';
200                 return result;
201         } else if (strstr(uid, ",CN=")) {
202                 gchar *result = g_strdup(strstr(uid, ",CN=")+4);
203                 if (strstr(result, ","))
204                         *(strstr(result, ",")) = '\0';
205                 return result;
206         } else {
207                 return g_strdup(uid);
208         }
209 }
210 gchar *sgpgme_sigstat_info_short(gpgme_ctx_t ctx, gpgme_verify_result_t status)
211 {
212         gpgme_signature_t sig = NULL;
213         gchar *uname = NULL;
214         gpgme_key_t key;
215         gchar *result = NULL;
216         gpgme_error_t err = 0;
217         static gboolean warned = FALSE;
218
219         if (GPOINTER_TO_INT(status) == -GPG_ERR_SYSTEM_ERROR) {
220                 return g_strdup_printf(_("The signature can't be checked - %s"), privacy_get_error());
221         }
222
223         if (status == NULL) {
224                 return g_strdup(_("The signature has not been checked."));
225         }
226         sig = status->signatures;
227         if (sig == NULL) {
228                 return g_strdup(_("The signature has not been checked."));
229         }
230
231         err = gpgme_get_key(ctx, sig->fpr, &key, 0);
232         if (gpg_err_code(err) == GPG_ERR_NO_AGENT) {
233                 if (!warned)
234                         alertpanel_error(_("PGP Core: Can't get key - no gpg-agent running."));
235                 else
236                         g_warning("PGP Core: Can't get key - no gpg-agent running.");
237                 warned = TRUE;
238         } else if (gpg_err_code(err) != GPG_ERR_NO_ERROR && gpg_err_code(err) != GPG_ERR_EOF) {
239                 return g_strdup_printf(_("The signature can't be checked - %s"), 
240                         gpgme_strerror(err));
241   }
242
243         if (key)
244                 uname = extract_name(key->uids->uid);
245         else
246                 uname = g_strdup("<?>");
247
248         switch (gpg_err_code(sig->status)) {
249         case GPG_ERR_NO_ERROR:
250                switch ((key && key->uids) ? key->uids->validity : GPGME_VALIDITY_UNKNOWN) {
251                 case GPGME_VALIDITY_ULTIMATE:
252                         result = g_strdup_printf(_("Good signature from \"%s\" [ultimate]"), uname);
253                         break;
254                 case GPGME_VALIDITY_FULL:
255                         result = g_strdup_printf(_("Good signature from \"%s\" [full]"), uname);
256                         break;
257                 case GPGME_VALIDITY_MARGINAL:
258                         result = g_strdup_printf(_("Good signature from \"%s\" [marginal]"), uname);
259                         break;
260                 case GPGME_VALIDITY_UNKNOWN:
261                 case GPGME_VALIDITY_UNDEFINED:
262                 case GPGME_VALIDITY_NEVER:
263                 default:
264                         if (key) {
265                                 result = g_strdup_printf(_("Good signature from \"%s\""), uname);
266                         } else {
267                                 gchar *id = g_strdup(sig->fpr + strlen(sig->fpr)-8);
268                                 result = g_strdup_printf(_("Key 0x%s not available to verify this signature"), id);
269                                 g_free(id);
270                         }
271                         break;
272                }
273                 break;
274         case GPG_ERR_SIG_EXPIRED:
275                 result = g_strdup_printf(_("Expired signature from \"%s\""), uname);
276                 break;
277         case GPG_ERR_KEY_EXPIRED:
278                 result = g_strdup_printf(_("Good signature from \"%s\", but the key has expired"), uname);
279                 break;
280         case GPG_ERR_CERT_REVOKED:
281                 result = g_strdup_printf(_("Good signature from \"%s\", but the key has been revoked"), uname);
282                 break;
283         case GPG_ERR_BAD_SIGNATURE:
284                 result = g_strdup_printf(_("Bad signature from \"%s\""), uname);
285                 break;
286         case GPG_ERR_NO_PUBKEY: {
287                 gchar *id = g_strdup(sig->fpr + strlen(sig->fpr)-8);
288                 result = g_strdup_printf(_("Key 0x%s not available to verify this signature"), id);
289                 g_free(id);
290                 break;
291                 }
292         default:
293                 result = g_strdup(_("The signature has not been checked"));
294                 break;
295         }
296         if (result == NULL)
297                 result = g_strdup(_("Error"));
298         g_free(uname);
299         return result;
300 }
301
302 gchar *sgpgme_sigstat_info_full(gpgme_ctx_t ctx, gpgme_verify_result_t status)
303 {
304         gint i = 0;
305         gchar *ret;
306         GString *siginfo;
307         gpgme_signature_t sig = NULL;
308
309         siginfo = g_string_sized_new(64);
310         if (status == NULL) {
311                 g_string_append_printf(siginfo,
312                         _("Error checking signature: no status\n"));
313                 goto bail;
314          }
315
316         sig = status->signatures;
317         
318         while (sig) {
319                 char buf[100];
320                 struct tm lt;
321                 gpgme_key_t key;
322                 gpgme_error_t err;
323                 const gchar *keytype, *keyid, *uid;
324                 
325                 err = gpgme_get_key(ctx, sig->fpr, &key, 0);
326
327                 if (err != GPG_ERR_NO_ERROR) {
328                         key = NULL;
329                         g_string_append_printf(siginfo, 
330                                 _("Error checking signature: %s\n"),
331                                 gpgme_strerror(err));
332                         goto bail;
333                 }
334                 if (key) {
335                         keytype = gpgme_pubkey_algo_name(
336                                         key->subkeys->pubkey_algo);
337                         keyid = key->subkeys->keyid;
338                         uid = key->uids->uid;
339                 } else {
340                         keytype = "?";
341                         keyid = "?";
342                         uid = "?";
343                 }
344
345                 memset(buf, 0, sizeof(buf));
346                 fast_strftime(buf, sizeof(buf)-1, prefs_common_get_prefs()->date_format, localtime_r(&sig->timestamp, &lt));
347                 g_string_append_printf(siginfo,
348                         _("Signature made on %s using %s key ID %s\n"),
349                         buf, keytype, keyid);
350                 
351                 switch (gpg_err_code(sig->status)) {
352                 case GPG_ERR_NO_ERROR:
353                         g_string_append_printf(siginfo,
354                                 _("Good signature from uid \"%s\" (Validity: %s)\n"),
355                                 uid, get_validity_str((key && key->uids) ? key->uids->validity:GPGME_VALIDITY_UNKNOWN));
356                         break;
357                 case GPG_ERR_KEY_EXPIRED:
358                         g_string_append_printf(siginfo,
359                                 _("Expired key uid \"%s\"\n"),
360                                 uid);
361                         break;
362                 case GPG_ERR_SIG_EXPIRED:
363                         g_string_append_printf(siginfo,
364                                 _("Expired signature from uid \"%s\" (Validity: %s)\n"),
365                                 uid, get_validity_str((key && key->uids) ? key->uids->validity:GPGME_VALIDITY_UNKNOWN));
366                         break;
367                 case GPG_ERR_CERT_REVOKED:
368                         g_string_append_printf(siginfo,
369                                 _("Revoked key uid \"%s\"\n"),
370                                 uid);
371                         break;
372                 case GPG_ERR_BAD_SIGNATURE:
373                         g_string_append_printf(siginfo,
374                                 _("BAD signature from \"%s\"\n"),
375                                 uid);
376                         break;
377                 default:
378                         break;
379                 }
380                 if (sig->status != GPG_ERR_BAD_SIGNATURE) {
381                         gint j = 1;
382                         if (key) {
383                                 key->uids = key->uids ? key->uids->next : NULL;
384                                 while (key->uids != NULL) {
385                                         g_string_append_printf(siginfo,
386                                                 g_strconcat("                    ",
387                                                             _("uid \"%s\" (Validity: %s)\n"), NULL),
388                                                 key->uids->uid,
389                                                 key->uids->revoked==TRUE?_("Revoked"):get_validity_str(key->uids->validity));
390                                         j++;
391                                         key->uids = key->uids->next;
392                                 }
393                         }
394                         g_string_append_printf(siginfo,_("Owner Trust: %s\n"),
395                                                key ? get_owner_trust_str(key->owner_trust) : _("No key!"));
396                         g_string_append(siginfo,
397                                 _("Primary key fingerprint:"));
398                         const char* primary_fpr = NULL;
399                         if (key && key->subkeys && key->subkeys->fpr)
400                                 primary_fpr = key->subkeys->fpr;
401                         else
402                                 g_string_append(siginfo, " ?");
403                         int idx; /* now pretty-print the fingerprint */
404                         for (idx=0; primary_fpr && *primary_fpr!='\0'; idx++, primary_fpr++) {
405                                 if (idx%4==0)
406                                         g_string_append_c(siginfo, ' ');
407                                 if (idx%20==0)
408                                         g_string_append_c(siginfo, ' ');
409                                 g_string_append_c(siginfo, (gchar)*primary_fpr);
410                         }
411                         g_string_append_c(siginfo, '\n');
412 #ifdef HAVE_GPGME_PKA_TRUST
413                         if (sig->pka_trust == 1 && sig->pka_address) {
414                                 g_string_append_printf(siginfo,
415                                    _("WARNING: Signer's address \"%s\" "
416                                       "does not match DNS entry\n"), 
417                                    sig->pka_address);
418                         }
419                         else if (sig->pka_trust == 2 && sig->pka_address) {
420                                 g_string_append_printf(siginfo,
421                                    _("Verified signer's address is \"%s\"\n"),
422                                    sig->pka_address);
423                                 /* FIXME: Compare the address to the
424                                  * From: address.  */
425                         }
426 #endif /*HAVE_GPGME_PKA_TRUST*/
427                 }
428
429                 g_string_append(siginfo, "\n");
430                 i++;
431                 sig = sig->next;
432         }
433 bail:
434         ret = siginfo->str;
435         g_string_free(siginfo, FALSE);
436         return ret;
437 }
438
439 gpgme_data_t sgpgme_data_from_mimeinfo(MimeInfo *mimeinfo)
440 {
441         gpgme_data_t data = NULL;
442         gpgme_error_t err;
443         FILE *fp = g_fopen(mimeinfo->data.filename, "rb");
444
445         if (!fp) 
446                 return NULL;
447
448         err = gpgme_data_new_from_filepart(&data, NULL, fp, mimeinfo->offset, mimeinfo->length);
449         fclose(fp);
450
451         debug_print("data %p (%d %d)\n", (void *)&data, mimeinfo->offset, mimeinfo->length);
452         if (err) {
453                 debug_print ("gpgme_data_new_from_file failed: %s\n",
454                              gpgme_strerror (err));
455                 privacy_set_error(_("Couldn't get data from message, %s"), gpgme_strerror(err));
456                 return NULL;
457         }
458         return data;
459 }
460
461 gpgme_data_t sgpgme_decrypt_verify(gpgme_data_t cipher, gpgme_verify_result_t *status, gpgme_ctx_t ctx)
462 {
463         struct passphrase_cb_info_s info;
464         gpgme_data_t plain;
465         gpgme_error_t err;
466
467         memset (&info, 0, sizeof info);
468         
469         if ((err = gpgme_data_new(&plain)) != GPG_ERR_NO_ERROR) {
470                 gpgme_release(ctx);
471                 privacy_set_error(_("Couldn't initialize data, %s"), gpgme_strerror(err));
472                 return NULL;
473         }
474         
475         if (gpgme_get_protocol(ctx) == GPGME_PROTOCOL_OpenPGP) {
476                 prefs_gpg_enable_agent(prefs_gpg_get_config()->use_gpg_agent);
477                 if (!g_getenv("GPG_AGENT_INFO") || !prefs_gpg_get_config()->use_gpg_agent) {
478                         info.c = ctx;
479                         gpgme_set_passphrase_cb (ctx, gpgmegtk_passphrase_cb, &info);
480                 }
481         } else {
482                 prefs_gpg_enable_agent(TRUE);
483                 info.c = ctx;
484                 gpgme_set_passphrase_cb (ctx, NULL, &info);
485         }
486         
487         
488         if (gpgme_get_protocol(ctx) == GPGME_PROTOCOL_OpenPGP) {
489                 err = gpgme_op_decrypt_verify(ctx, cipher, plain);
490                 if (err != GPG_ERR_NO_ERROR) {
491                         debug_print("can't decrypt (%s)\n", gpgme_strerror(err));
492                         privacy_set_error("%s", gpgme_strerror(err));
493                         gpgmegtk_free_passphrase();
494                         gpgme_data_release(plain);
495                         return NULL;
496                 }
497
498                 err = cm_gpgme_data_rewind(plain);
499                 if (err) {
500                         debug_print("can't seek (%d %d %s)\n", err, errno, g_strerror(errno));
501                 }
502
503                 debug_print("decrypted.\n");
504                 *status = gpgme_op_verify_result (ctx);
505         } else {
506                 err = gpgme_op_decrypt(ctx, cipher, plain);
507                 if (err != GPG_ERR_NO_ERROR) {
508                         debug_print("can't decrypt (%s)\n", gpgme_strerror(err));
509                         privacy_set_error("%s", gpgme_strerror(err));
510                         gpgmegtk_free_passphrase();
511                         gpgme_data_release(plain);
512                         return NULL;
513                 }
514
515                 err = cm_gpgme_data_rewind(plain);
516                 if (err) {
517                         debug_print("can't seek (%d %d %s)\n", err, errno, g_strerror(errno));
518                 }
519
520                 debug_print("decrypted.\n");
521                 *status = gpgme_op_verify_result (ctx);
522         }
523         return plain;
524 }
525
526 gchar *sgpgme_get_encrypt_data(GSList *recp_names, gpgme_protocol_t proto)
527 {
528         SelectionResult result = KEY_SELECTION_CANCEL;
529         gpgme_key_t *keys = gpgmegtk_recipient_selection(recp_names, &result,
530                                 proto);
531         gchar *ret = NULL;
532         int i = 0;
533
534         if (!keys) {
535                 if (result == KEY_SELECTION_DONT)
536                         return g_strdup("_DONT_ENCRYPT_");
537                 else
538                         return NULL;
539         }
540         while (keys[i]) {
541                 gpgme_subkey_t skey = keys[i]->subkeys;
542                 gchar *fpr = skey->fpr;
543                 gchar *tmp = NULL;
544                 debug_print("adding %s\n", fpr);
545                 tmp = g_strconcat(ret?ret:"", fpr, " ", NULL);
546                 g_free(ret);
547                 ret = tmp;
548                 i++;
549         }
550         return ret;
551 }
552
553 gboolean sgpgme_setup_signers(gpgme_ctx_t ctx, PrefsAccount *account,
554                               const gchar *from_addr)
555 {
556         GPGAccountConfig *config;
557         const gchar *signer_addr = account->address;
558
559         gpgme_signers_clear(ctx);
560
561         if (from_addr)
562                 signer_addr = from_addr;
563         config = prefs_gpg_account_get_config(account);
564
565         switch(config->sign_key) {
566         case SIGN_KEY_DEFAULT:
567                 debug_print("using default gnupg key\n");
568                 break;
569         case SIGN_KEY_BY_FROM:
570                 debug_print("using key for %s\n", signer_addr);
571                 break;
572         case SIGN_KEY_CUSTOM:
573                 debug_print("using key for %s\n", config->sign_key_id);
574                 break;
575         }
576
577         if (config->sign_key != SIGN_KEY_DEFAULT) {
578                 const gchar *keyid;
579                 gpgme_key_t key, found_key;
580                 gpgme_error_t err;
581
582                 if (config->sign_key == SIGN_KEY_BY_FROM)
583                         keyid = signer_addr;
584                 else if (config->sign_key == SIGN_KEY_CUSTOM)
585                         keyid = config->sign_key_id;
586                 else
587                         goto bail;
588
589                 found_key = NULL;
590                 /* Look for any key, not just private ones, or GPGMe doesn't
591                  * correctly set the revoked flag. */
592                 err = gpgme_op_keylist_start(ctx, keyid, 0);
593                 while ((err = gpgme_op_keylist_next(ctx, &key)) == 0) {
594                         if (key == NULL)
595                                 continue;
596
597                         if (!key->can_sign)
598                                 continue;
599
600                         if (key->protocol != gpgme_get_protocol(ctx)) {
601                                 debug_print("skipping a key (wrong protocol %d)\n", key->protocol);
602                                 gpgme_key_release(key);
603                                 continue;
604                         }
605
606                         if (key->expired) {
607                                 debug_print("skipping a key, expired");
608                                 gpgme_key_release(key);
609                                 continue;
610                         }
611                         if (key->revoked) {
612                                 debug_print("skipping a key, revoked");
613                                 gpgme_key_release(key);
614                                 continue;
615                         }
616                         if (key->disabled) {
617                                 debug_print("skipping a key, disabled");
618                                 gpgme_key_release(key);
619                                 continue;
620                         }
621
622                         if (found_key != NULL) {
623                                 gpgme_key_release(key);
624                                 gpgme_op_keylist_end(ctx);
625                                 g_warning("ambiguous specification of secret key '%s'", keyid);
626                                 privacy_set_error(_("Secret key specification is ambiguous"));
627                                 goto bail;
628                         }
629
630                         found_key = key;
631                 }
632                 gpgme_op_keylist_end(ctx);
633
634                 if (found_key == NULL) {
635                         g_warning("setup_signers start: %s", gpgme_strerror(err));
636                         privacy_set_error(_("Secret key not found (%s)"), gpgme_strerror(err));
637                         goto bail;
638                 }
639
640                 err = gpgme_signers_add(ctx, found_key);
641                 debug_print("got key (proto %d (pgp %d, smime %d).\n",
642                             found_key->protocol, GPGME_PROTOCOL_OpenPGP,
643                             GPGME_PROTOCOL_CMS);
644                 gpgme_key_release(found_key);
645
646                 if (err) {
647                         g_warning("error adding secret key: %s",
648                                   gpgme_strerror(err));
649                         privacy_set_error(_("Error setting secret key: %s"),
650                                           gpgme_strerror(err));
651                         goto bail;
652                 }
653         }
654
655         prefs_gpg_account_free_config(config);
656
657         return TRUE;
658 bail:
659         prefs_gpg_account_free_config(config);
660         return FALSE;
661 }
662
663 void sgpgme_init()
664 {
665         gchar *ctype_locale = NULL, *messages_locale = NULL;
666         gchar *ctype_utf8_locale = NULL, *messages_utf8_locale = NULL;
667         gpgme_error_t err = 0;
668
669         gpgme_engine_info_t engineInfo;
670
671         if (strcmp(prefs_gpg_get_config()->gpg_path, "") != 0
672             && access(prefs_gpg_get_config()->gpg_path, X_OK) != -1) {
673                 err = gpgme_set_engine_info(GPGME_PROTOCOL_OpenPGP, prefs_gpg_get_config()->gpg_path, NULL);
674                 if (err != GPG_ERR_NO_ERROR)
675                         g_warning("failed to set crypto engine configuration: %s", gpgme_strerror(err));
676         }
677
678         if (gpgme_check_version("1.0.0")) {
679 #ifdef LC_CTYPE
680                 debug_print("setting gpgme CTYPE locale\n");
681 #ifdef G_OS_WIN32
682                 ctype_locale = g_win32_getlocale();
683 #else
684                 ctype_locale = g_strdup(setlocale(LC_CTYPE, NULL));
685 #endif
686                 if (ctype_locale) {
687                         debug_print("setting gpgme CTYPE locale to: %s\n", ctype_locale);
688                         if (strchr(ctype_locale, '.'))
689                                 *(strchr(ctype_locale, '.')) = '\0';
690                         else if (strchr(ctype_locale, '@'))
691                                 *(strchr(ctype_locale, '@')) = '\0';
692                         ctype_utf8_locale = g_strconcat(ctype_locale, ".UTF-8", NULL);
693
694                         debug_print("setting gpgme locale to UTF8: %s\n", ctype_utf8_locale ? ctype_utf8_locale : "NULL");
695                         gpgme_set_locale(NULL, LC_CTYPE, ctype_utf8_locale);
696
697                         debug_print("done\n");
698                         g_free(ctype_utf8_locale);
699                         g_free(ctype_locale);
700                 } else {
701                         debug_print("couldn't set gpgme CTYPE locale\n");
702                 }
703 #endif
704 #ifdef LC_MESSAGES
705                 debug_print("setting gpgme MESSAGES locale\n");
706 #ifdef G_OS_WIN32
707                 messages_locale = g_win32_getlocale();
708 #else
709                 messages_locale = g_strdup(setlocale(LC_MESSAGES, NULL));
710 #endif
711                 if (messages_locale) {
712                         debug_print("setting gpgme MESSAGES locale to: %s\n", messages_locale);
713                         if (strchr(messages_locale, '.'))
714                                 *(strchr(messages_locale, '.')) = '\0';
715                         else if (strchr(messages_locale, '@'))
716                                 *(strchr(messages_locale, '@')) = '\0';
717                         messages_utf8_locale = g_strconcat(messages_locale, ".UTF-8", NULL);
718                         debug_print("setting gpgme locale to UTF8: %s\n", messages_utf8_locale ? messages_utf8_locale : "NULL");
719
720                         gpgme_set_locale(NULL, LC_MESSAGES, messages_utf8_locale);
721
722                         debug_print("done\n");
723                         g_free(messages_utf8_locale);
724                         g_free(messages_locale);
725                 } else {
726                         debug_print("couldn't set gpgme MESSAGES locale\n");
727                 }
728 #endif
729                 if (!gpgme_get_engine_info(&engineInfo)) {
730                         while (engineInfo) {
731                                 debug_print("GpgME Protocol: %s\n"
732                                             "Version: %s (req %s)\n"
733                                             "Executable: %s\n",
734                                         gpgme_get_protocol_name(engineInfo->protocol) ? gpgme_get_protocol_name(engineInfo->protocol):"???",
735                                         engineInfo->version ? engineInfo->version:"???",
736                                         engineInfo->req_version ? engineInfo->req_version:"???",
737                                         engineInfo->file_name ? engineInfo->file_name:"???");
738                                 if (engineInfo->protocol == GPGME_PROTOCOL_OpenPGP
739                                 &&  gpgme_engine_check_version(engineInfo->protocol) != 
740                                         GPG_ERR_NO_ERROR) {
741                                         if (engineInfo->file_name && !engineInfo->version) {
742                                                 alertpanel_error(_("Gpgme protocol '%s' is unusable: "
743                                                                    "Engine '%s' isn't installed properly."),
744                                                                    gpgme_get_protocol_name(engineInfo->protocol),
745                                                                    engineInfo->file_name);
746                                         } else if (engineInfo->file_name && engineInfo->version
747                                           && engineInfo->req_version) {
748                                                 alertpanel_error(_("Gpgme protocol '%s' is unusable: "
749                                                                    "Engine '%s' version %s is installed, "
750                                                                    "but version %s is required.\n"),
751                                                                    gpgme_get_protocol_name(engineInfo->protocol),
752                                                                    engineInfo->file_name,
753                                                                    engineInfo->version,
754                                                                    engineInfo->req_version);
755                                         } else {
756                                                 alertpanel_error(_("Gpgme protocol '%s' is unusable "
757                                                                    "(unknown problem)"),
758                                                                    gpgme_get_protocol_name(engineInfo->protocol));
759                                         }
760                                 }
761                                 engineInfo = engineInfo->next;
762                         }
763                 }
764         } else {
765                 sgpgme_disable_all();
766
767                 if (prefs_gpg_get_config()->gpg_warning) {
768                         AlertValue val;
769
770                         val = alertpanel_full
771                                 (_("Warning"),
772                                  _("GnuPG is not installed properly, or needs "
773                                  "to be upgraded.\n"
774                                  "OpenPGP support disabled."),
775                                  GTK_STOCK_CLOSE, NULL, NULL, TRUE, NULL,
776                                  ALERT_WARNING, G_ALERTDEFAULT);
777                         if (val & G_ALERTDISABLE)
778                                 prefs_gpg_get_config()->gpg_warning = FALSE;
779                 }
780         }
781 }
782
783 void sgpgme_done()
784 {
785         gpgmegtk_free_passphrase();
786 }
787
788 #ifdef G_OS_WIN32
789 struct _ExportCtx {
790         gboolean done;
791         gchar *cmd;
792         DWORD exitcode;
793 };
794
795 static void *_export_threaded(void *arg)
796 {
797         struct _ExportCtx *ctx = (struct _ExportCtx *)arg;
798         gboolean result;
799
800         PROCESS_INFORMATION pi = {0};
801         STARTUPINFO si = {0};
802
803         result = CreateProcess(NULL, ctx->cmd, NULL, NULL, FALSE,
804                         NORMAL_PRIORITY_CLASS | CREATE_NO_WINDOW,
805                         NULL, NULL, &si, &pi);
806
807         if (!result) {
808                 debug_print("Couldn't execute '%s'\n", ctx->cmd);
809         } else {
810                 WaitForSingleObject(pi.hProcess, 10000);
811                 result = GetExitCodeProcess(pi.hProcess, &ctx->exitcode);
812                 if (ctx->exitcode == STILL_ACTIVE) {
813                         debug_print("Process still running, terminating it.\n");
814                         TerminateProcess(pi.hProcess, 255);
815                 }
816
817                 CloseHandle(pi.hProcess);
818                 CloseHandle(pi.hThread);
819
820                 if (!result) {
821                         debug_print("Process executed, but we couldn't get its exit code (huh?)\n");
822                 }
823         }
824
825         ctx->done = TRUE;
826         return NULL;
827 }
828 #endif
829
830 void sgpgme_create_secret_key(PrefsAccount *account, gboolean ask_create)
831 {
832         AlertValue val = G_ALERTDEFAULT;
833         gchar *key_parms = NULL;
834         gchar *name = NULL;
835         gchar *email = NULL;
836         gchar *passphrase = NULL, *passphrase_second = NULL;
837         gint prev_bad = 0;
838         gchar *tmp = NULL;
839         gpgme_error_t err = 0;
840         gpgme_ctx_t ctx;
841         GtkWidget *window = NULL;
842         gpgme_genkey_result_t key;
843         gboolean exported = FALSE;
844
845         if (account == NULL)
846                 account = account_get_default();
847
848         if (account->address == NULL) {
849                 alertpanel_error(_("You have to save the account's information with \"OK\" "
850                                    "before being able to generate a key pair.\n"));
851                 return;
852         }
853         if (ask_create) {
854                 val = alertpanel(_("No PGP key found"),
855                                 _("Claws Mail did not find a secret PGP key, "
856                                   "which means that you won't be able to sign "
857                                   "emails or receive encrypted emails.\n"
858                                   "Do you want to create a new key pair now?"),
859                                   GTK_STOCK_NO, "+" GTK_STOCK_YES, NULL);
860                 if (val == G_ALERTDEFAULT) {
861                         return;
862                 }
863         }
864
865         if (account->name) {
866                 name = g_strdup(account->name);
867         } else {
868                 name = g_strdup(account->address);
869         }
870         email = g_strdup(account->address);
871         tmp = g_strdup_printf("%s <%s>", account->name?account->name:account->address, account->address);
872 again:
873         passphrase = passphrase_mbox(tmp, NULL, prev_bad, 1);
874         if (passphrase == NULL) {
875                 g_free(tmp);
876                 g_free(email);
877                 g_free(name);           
878                 return;
879         }
880         passphrase_second = passphrase_mbox(tmp, NULL, 0, 2);
881         if (passphrase_second == NULL) {
882                 g_free(tmp);
883                 g_free(email);
884                 g_free(passphrase);             
885                 g_free(name);           
886                 return;
887         }
888         if (strcmp(passphrase, passphrase_second)) {
889                 g_free(passphrase);
890                 g_free(passphrase_second);
891                 prev_bad = 1;
892                 goto again;
893         }
894         
895         key_parms = g_strdup_printf("<GnupgKeyParms format=\"internal\">\n"
896                                         "Key-Type: RSA\n"
897                                         "Key-Length: 2048\n"
898                                         "Subkey-Type: RSA\n"
899                                         "Subkey-Length: 2048\n"
900                                         "Name-Real: %s\n"
901                                         "Name-Email: %s\n"
902                                         "Expire-Date: 0\n"
903                                         "%s%s%s"
904                                         "</GnupgKeyParms>\n",
905                                         name, email, 
906                                         strlen(passphrase)?"Passphrase: ":"",
907                                         passphrase,
908                                         strlen(passphrase)?"\n":"");
909 #ifndef G_PLATFORM_WIN32
910         if (mlock(passphrase, strlen(passphrase)) == -1)
911                 debug_print("couldn't lock passphrase\n");
912         if (mlock(passphrase_second, strlen(passphrase_second)) == -1)
913                 debug_print("couldn't lock passphrase2\n");
914 #endif
915         g_free(tmp);
916         g_free(email);
917         g_free(name);
918         g_free(passphrase_second);
919         g_free(passphrase);
920         
921         err = gpgme_new (&ctx);
922         if (err) {
923                 alertpanel_error(_("Couldn't generate a new key pair: %s"),
924                                  gpgme_strerror(err));
925                 g_free(key_parms);
926                 return;
927         }
928         
929
930         window = label_window_create(_("Generating your new key pair... Please move the mouse "
931                               "around to help generate entropy..."));
932
933         err = gpgme_op_genkey(ctx, key_parms, NULL, NULL);
934         g_free(key_parms);
935
936         label_window_destroy(window);
937
938         if (err) {
939                 alertpanel_error(_("Couldn't generate a new key pair: %s"), gpgme_strerror(err));
940                 gpgme_release(ctx);
941                 return;
942         }
943         key = gpgme_op_genkey_result(ctx);
944         if (key == NULL) {
945                 alertpanel_error(_("Couldn't generate a new key pair: unknown error"));
946                 gpgme_release(ctx);
947                 return;
948         } else {
949                 gchar *buf = g_strdup_printf(_("Your new key pair has been generated. "
950                                     "Its fingerprint is:\n%s\n\nDo you want to export it "
951                                     "to a keyserver?"),
952                                     key->fpr ? key->fpr:"null");
953                 AlertValue val = alertpanel(_("Key generated"), buf,
954                                   GTK_STOCK_NO, "+" GTK_STOCK_YES, NULL);
955                 g_free(buf);
956                 if (val == G_ALERTALTERNATE) {
957                         gchar *gpgbin = get_gpg_executable_name();
958                         gchar *cmd = g_strdup_printf("\"%s\" --batch --no-tty --send-keys %s",
959                                 (gpgbin ? gpgbin : "gpg"), key->fpr);
960                         debug_print("Executing command: %s\n", cmd);
961
962 #ifndef G_OS_WIN32
963                         int res = 0;
964                         pid_t pid = 0;
965                         pid = fork();
966                         if (pid == -1) {
967                                 res = -1;
968                         } else if (pid == 0) {
969                                 /* son */
970                                 res = system(cmd);
971                                 res = WEXITSTATUS(res);
972                                 _exit(res);
973                         } else {
974                                 int status = 0;
975                                 time_t start_wait = time(NULL);
976                                 res = -1;
977                                 do {
978                                         if (waitpid(pid, &status, WNOHANG) == 0 || !WIFEXITED(status)) {
979                                                 usleep(200000);
980                                         } else {
981                                                 res = WEXITSTATUS(status);
982                                                 break;
983                                         }
984                                         if (time(NULL) - start_wait > 5) {
985                                                 debug_print("SIGTERM'ing gpg\n");
986                                                 kill(pid, SIGTERM);
987                                         }
988                                         if (time(NULL) - start_wait > 6) {
989                                                 debug_print("SIGKILL'ing gpg\n");
990                                                 kill(pid, SIGKILL);
991                                                 break;
992                                         }
993                                 } while(1);
994                         }
995
996                         if (res == 0)
997                                 exported = TRUE;
998 #else
999                         /* We need to call gpg in a separate thread, so that waiting for
1000                          * it to finish does not block the UI. */
1001                         pthread_t pt;
1002                         struct _ExportCtx *ectx = malloc(sizeof(struct _ExportCtx));
1003
1004                         ectx->done = FALSE;
1005                         ectx->exitcode = STILL_ACTIVE;
1006                         ectx->cmd = cmd;
1007
1008                         if (pthread_create(&pt, PTHREAD_CREATE_JOINABLE,
1009                                                 _export_threaded, (void *)ectx) != 0) {
1010                                 debug_print("Couldn't create thread, continuing unthreaded.\n");
1011                                 _export_threaded(ctx);
1012                         } else {
1013                                 debug_print("Thread created, waiting for it to finish...\n");
1014                                 while (!ectx->done)
1015                                         claws_do_idle();
1016                         }
1017
1018                         debug_print("Thread finished.\n");
1019                         pthread_join(pt, NULL);
1020
1021                         if (ectx->exitcode == 0)
1022                                 exported = TRUE;
1023
1024                         g_free(ectx);
1025 #endif
1026                         g_free(cmd);
1027
1028                         if (exported) {
1029                                 alertpanel_notice(_("Key exported."));
1030                         } else {
1031                                 alertpanel_error(_("Couldn't export key."));
1032                         }
1033                 }
1034         }
1035         gpgme_release(ctx);
1036 }
1037
1038 gboolean sgpgme_has_secret_key(void)
1039 {
1040         gpgme_error_t err = 0;
1041         gpgme_ctx_t ctx;
1042         gpgme_key_t key;
1043
1044         err = gpgme_new (&ctx);
1045         if (err) {
1046                 debug_print("err : %s\n", gpgme_strerror(err));
1047                 return TRUE;
1048         }
1049 check_again:
1050         err = gpgme_op_keylist_start(ctx, NULL, TRUE);
1051         if (!err)
1052                 err = gpgme_op_keylist_next(ctx, &key);
1053         gpgme_op_keylist_end(ctx);
1054         if (gpg_err_code(err) == GPG_ERR_EOF) {
1055                 if (gpgme_get_protocol(ctx) != GPGME_PROTOCOL_CMS) {
1056                         gpgme_set_protocol(ctx, GPGME_PROTOCOL_CMS);
1057                         goto check_again;
1058                 }
1059                 gpgme_release(ctx);
1060                 return FALSE;
1061         } else {
1062                 gpgme_release(ctx);
1063                 return TRUE;
1064         }
1065 }
1066
1067 void sgpgme_check_create_key(void)
1068 {
1069         if (prefs_gpg_get_config()->gpg_ask_create_key &&
1070             !sgpgme_has_secret_key()) {
1071                 sgpgme_create_secret_key(NULL, TRUE);
1072         }
1073
1074         prefs_gpg_get_config()->gpg_ask_create_key = FALSE;
1075         prefs_gpg_save_config();
1076 }
1077
1078 void *sgpgme_data_release_and_get_mem(gpgme_data_t data, size_t *len)
1079 {
1080         char buf[BUFSIZ];
1081         void *result = NULL;
1082         ssize_t r = 0;
1083         size_t w = 0;
1084         
1085         if (data == NULL)
1086                 return NULL;
1087         if (len == NULL)
1088                 return NULL;
1089
1090         /* I know it's deprecated, but we don't compile with _LARGEFILE */
1091         cm_gpgme_data_rewind(data);
1092         while ((r = gpgme_data_read(data, buf, BUFSIZ)) > 0) {
1093                 void *rresult = realloc(result, r + w);
1094                 if (rresult == NULL) {
1095                         g_warning("can't allocate memory");
1096                         if (result != NULL)
1097                                 free(result);
1098                         return NULL;
1099                 }
1100                 result = rresult;
1101                 memcpy(result+w, buf, r);
1102                 w += r;
1103         }
1104         
1105         *len = w;
1106
1107         gpgme_data_release(data);
1108         if (r < 0) {
1109                 free(result);
1110                 *len = 0;
1111                 return NULL;
1112         }
1113         return result;
1114 }
1115
1116 gpgme_error_t cm_gpgme_data_rewind(gpgme_data_t dh)
1117 {
1118 #if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS == 64
1119         if (gpgme_data_seek(dh, (off_t)0, SEEK_SET) == -1)
1120                 return gpg_error_from_errno(errno);
1121         else
1122                 return 0;
1123 #else
1124         return gpgme_data_rewind(dh);
1125 #endif
1126 }
1127
1128 #endif /* USE_GPGME */