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