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