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