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