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