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