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