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