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