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