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