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