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