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