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