2009-01-09 [paul] 3.7.0cvs22
[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)
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)) {
521                                         debug_print("skipping a key (%s)\n", key->expired?"expired":"revoked");
522                                         gpgme_key_release(key);
523                                 }
524                         } while (!err);
525                 }
526                 if (err) {
527                         g_warning("setup_signers start: %s", gpgme_strerror(err));
528                         privacy_set_error(_("Secret key not found (%s)"), gpgme_strerror(err));
529                         goto bail;
530                 }
531                 
532                 do {
533                         err = gpgme_op_keylist_next(ctx, &key2);
534                         if (!err && key2 && key2->protocol == gpgme_get_protocol(ctx) &&
535                             !key2->expired && !key2->revoked)
536                                 break;
537                         if (!err && key && key2->protocol != gpgme_get_protocol(ctx)) {
538                                 debug_print("skipping a key (wrong protocol %d)\n", key2->protocol);
539                                 gpgme_key_release(key2);
540                         }
541                         if (!err && key && (key2->expired || key2->revoked)) {
542                                 debug_print("skipping a key (%s)\n", key2->expired?"expired":"revoked");
543                                 gpgme_key_release(key2);
544                         }
545                 } while (!err);
546                 if (!err) {
547                         gpgme_key_release(key2);
548                         g_warning("ambiguous specification of secret key '%s'\n",
549                                 keyid);
550                         privacy_set_error(_("Secret key specification is ambiguous"));
551                         goto bail;
552                 }
553                 
554                 gpgme_op_keylist_end(ctx);
555                 err = gpgme_signers_add(ctx, key);
556                 debug_print("got key (proto %d (pgp %d, smime %d).\n", key->protocol,
557                                 GPGME_PROTOCOL_OpenPGP, GPGME_PROTOCOL_CMS);
558                 gpgme_key_release(key);
559                 
560                 if (err) {
561                         g_warning("error adding secret key: %s\n", gpgme_strerror(err));
562                         privacy_set_error(_("Error setting secret key: %s"), gpgme_strerror(err));
563                         goto bail;
564                 }
565         }
566
567         prefs_gpg_account_free_config(config);
568
569         return TRUE;
570 bail:
571         prefs_gpg_account_free_config(config);
572         return FALSE;
573 }
574
575 void sgpgme_init()
576 {
577         gpgme_engine_info_t engineInfo;
578         if (gpgme_check_version("1.0.0")) {
579 #ifdef LC_CTYPE
580                 gpgme_set_locale(NULL, LC_CTYPE, setlocale(LC_CTYPE, NULL));
581 #endif
582 #ifdef LC_MESSAGES
583                 gpgme_set_locale(NULL, LC_MESSAGES, setlocale(LC_MESSAGES, NULL));
584 #endif
585                 if (!gpgme_get_engine_info(&engineInfo)) {
586                         while (engineInfo) {
587 #ifndef G_OS_WIN32
588                                 debug_print("GpgME Protocol: %s\n"
589                                             "Version: %s (req %s)\n"
590                                             "Executable: %s\n",
591                                         gpgme_get_protocol_name(engineInfo->protocol) ? gpgme_get_protocol_name(engineInfo->protocol):"???",
592                                         engineInfo->version ? engineInfo->version:"???",
593                                         engineInfo->req_version ? engineInfo->req_version:"???",
594                                         engineInfo->file_name ? engineInfo->file_name:"???");
595 #endif
596                                 if (engineInfo->protocol == GPGME_PROTOCOL_OpenPGP
597                                 &&  gpgme_engine_check_version(engineInfo->protocol) != 
598                                         GPG_ERR_NO_ERROR) {
599                                         if (engineInfo->file_name && !engineInfo->version) {
600                                                 alertpanel_error(_("Gpgme protocol '%s' is unusable: "
601                                                                    "Engine '%s' isn't installed properly."),
602                                                                    gpgme_get_protocol_name(engineInfo->protocol),
603                                                                    engineInfo->file_name);
604                                         } else if (engineInfo->file_name && engineInfo->version
605                                           && engineInfo->req_version) {
606                                                 alertpanel_error(_("Gpgme protocol '%s' is unusable: "
607                                                                    "Engine '%s' version %s is installed, "
608                                                                    "but version %s is required.\n"),
609                                                                    gpgme_get_protocol_name(engineInfo->protocol),
610                                                                    engineInfo->file_name,
611                                                                    engineInfo->version,
612                                                                    engineInfo->req_version);
613                                         } else {
614                                                 alertpanel_error(_("Gpgme protocol '%s' is unusable "
615                                                                    "(unknown problem)"),
616                                                                    gpgme_get_protocol_name(engineInfo->protocol));
617                                         }
618                                 }
619                                 engineInfo = engineInfo->next;
620                         }
621                 }
622         } else {
623                 sgpgme_disable_all();
624
625                 if (prefs_gpg_get_config()->gpg_warning) {
626                         AlertValue val;
627
628                         val = alertpanel_full
629                                 (_("Warning"),
630                                  _("GnuPG is not installed properly, or needs "
631                                  "to be upgraded.\n"
632                                  "OpenPGP support disabled."),
633                                  GTK_STOCK_CLOSE, NULL, NULL, TRUE, NULL,
634                                  ALERT_WARNING, G_ALERTDEFAULT);
635                         if (val & G_ALERTDISABLE)
636                                 prefs_gpg_get_config()->gpg_warning = FALSE;
637                 }
638         }
639 }
640
641 void sgpgme_done()
642 {
643         gpgmegtk_free_passphrase();
644 }
645
646 void sgpgme_create_secret_key(PrefsAccount *account, gboolean ask_create)
647 {
648         AlertValue val = G_ALERTDEFAULT;
649         gchar *key_parms = NULL;
650         gchar *name = NULL;
651         gchar *email = NULL;
652         gchar *passphrase = NULL, *passphrase_second = NULL;
653         gint prev_bad = 0;
654         gchar *tmp = NULL;
655         gpgme_error_t err = 0;
656         gpgme_ctx_t ctx;
657         GtkWidget *window = NULL;
658         gpgme_genkey_result_t key;
659
660         if (account == NULL)
661                 account = account_get_default();
662
663         if (account->address == NULL) {
664                 alertpanel_error(_("You have to save the account's information with \"OK\" "
665                                    "before being able to generate a key pair.\n"));
666                 return;
667         }
668         if (ask_create) {
669                 val = alertpanel(_("No PGP key found"),
670                                 _("Claws Mail did not find a secret PGP key, "
671                                   "which means that you won't be able to sign "
672                                   "emails or receive encrypted emails.\n"
673                                   "Do you want to create a new key pair now?"),
674                                   GTK_STOCK_NO, "+" GTK_STOCK_YES, NULL);
675                 if (val == G_ALERTDEFAULT) {
676                         prefs_gpg_get_config()->gpg_ask_create_key = FALSE;
677                         prefs_gpg_save_config();
678                         return;
679                 }
680         }
681
682         if (account->name) {
683                 name = g_strdup(account->name);
684         } else {
685                 name = g_strdup(account->address);
686         }
687         email = g_strdup(account->address);
688         tmp = g_strdup_printf("%s <%s>", account->name?account->name:account->address, account->address);
689 again:
690         passphrase = passphrase_mbox(tmp, NULL, prev_bad, 1);
691         if (passphrase == NULL) {
692                 g_free(tmp);
693                 g_free(email);
694                 g_free(name);           
695                 return;
696         }
697         passphrase_second = passphrase_mbox(tmp, NULL, 0, 2);
698         if (passphrase_second == NULL) {
699                 g_free(tmp);
700                 g_free(email);
701                 g_free(passphrase);             
702                 g_free(name);           
703                 return;
704         }
705         if (strcmp(passphrase, passphrase_second)) {
706                 g_free(passphrase);
707                 g_free(passphrase_second);
708                 prev_bad = 1;
709                 goto again;
710         }
711         
712         key_parms = g_strdup_printf("<GnupgKeyParms format=\"internal\">\n"
713                                         "Key-Type: DSA\n"
714                                         "Key-Length: 1024\n"
715                                         "Subkey-Type: ELG-E\n"
716                                         "Subkey-Length: 2048\n"
717                                         "Name-Real: %s\n"
718                                         "Name-Email: %s\n"
719                                         "Expire-Date: 0\n"
720                                         "%s%s%s"
721                                         "</GnupgKeyParms>\n",
722                                         name, email, 
723                                         strlen(passphrase)?"Passphrase: ":"",
724                                         passphrase,
725                                         strlen(passphrase)?"\n":"");
726 #ifndef G_PLATFORM_WIN32
727         if (mlock(passphrase, strlen(passphrase)) == -1)
728                 debug_print("couldn't lock passphrase\n");
729         if (mlock(passphrase_second, strlen(passphrase_second)) == -1)
730                 debug_print("couldn't lock passphrase2\n");
731 #endif
732         g_free(tmp);
733         g_free(email);
734         g_free(name);
735         g_free(passphrase_second);
736         g_free(passphrase);
737         
738         err = gpgme_new (&ctx);
739         if (err) {
740                 alertpanel_error(_("Couldn't generate a new key pair: %s"),
741                                  gpgme_strerror(err));
742                 g_free(key_parms);
743                 return;
744         }
745         
746
747         window = label_window_create(_("Generating your new key pair... Please move the mouse "
748                               "around to help generate entropy..."));
749
750         err = gpgme_op_genkey(ctx, key_parms, NULL, NULL);
751         g_free(key_parms);
752
753         label_window_destroy(window);
754
755         if (err) {
756                 alertpanel_error(_("Couldn't generate a new key pair: %s"), gpgme_strerror(err));
757                 gpgme_release(ctx);
758                 return;
759         }
760         key = gpgme_op_genkey_result(ctx);
761         if (key == NULL) {
762                 alertpanel_error(_("Couldn't generate a new key pair: unknown error"));
763                 gpgme_release(ctx);
764                 return;
765         } else {
766                 gchar *buf = g_strdup_printf(_("Your new key pair has been generated. "
767                                     "Its fingerprint is:\n%s\n\nDo you want to export it "
768                                     "to a keyserver?"),
769                                     key->fpr ? key->fpr:"null");
770                 AlertValue val = alertpanel(_("Key generated"), buf,
771                                   GTK_STOCK_NO, "+" GTK_STOCK_YES, NULL);
772                 g_free(buf);
773                 if (val == G_ALERTALTERNATE) {
774 #ifndef G_OS_WIN32
775                         gchar *cmd = g_strdup_printf("gpg --no-tty --send-keys %s", key->fpr);
776                         int res = 0;
777                         pid_t pid = 0;
778                         pid = fork();
779                         if (pid == -1) {
780                                 res = -1;
781                         } else if (pid == 0) {
782                                 /* son */
783                                 res = system(cmd);
784                                 res = WEXITSTATUS(res);
785                                 _exit(res);
786                         } else {
787                                 int status = 0;
788                                 time_t start_wait = time(NULL);
789                                 res = -1;
790                                 do {
791                                         if (waitpid(pid, &status, WNOHANG) == 0 || !WIFEXITED(status)) {
792                                                 usleep(200000);
793                                         } else {
794                                                 res = WEXITSTATUS(status);
795                                                 break;
796                                         }
797                                         if (time(NULL) - start_wait > 5) {
798                                                 debug_print("SIGTERM'ing gpg\n");
799                                                 kill(pid, SIGTERM);
800                                         }
801                                         if (time(NULL) - start_wait > 6) {
802                                                 debug_print("SIGKILL'ing gpg\n");
803                                                 kill(pid, SIGKILL);
804                                                 break;
805                                         }
806                                 } while(1);
807                         }
808                         if (res == 0) {
809                                 alertpanel_notice(_("Key exported."));
810                         } else {
811                                 alertpanel_error(_("Couldn't export key."));
812                         }
813                         g_free(cmd);
814 #else
815                         alertpanel_error(_("Key export isn't implemented in Windows."));
816 #endif
817                 }
818         }
819         prefs_gpg_get_config()->gpg_ask_create_key = FALSE;
820         prefs_gpg_save_config();
821         gpgme_release(ctx);
822 }
823
824 gboolean sgpgme_has_secret_key(void)
825 {
826         gpgme_error_t err = 0;
827         gpgme_ctx_t ctx;
828         gpgme_key_t key;
829
830         err = gpgme_new (&ctx);
831         if (err) {
832                 debug_print("err : %s\n", gpgme_strerror(err));
833                 return TRUE;
834         }
835         err = gpgme_op_keylist_start(ctx, NULL, TRUE);
836         if (!err)
837                 err = gpgme_op_keylist_next(ctx, &key);
838         gpgme_op_keylist_end(ctx);
839         gpgme_release(ctx);
840         if (gpg_err_code(err) == GPG_ERR_EOF)
841                 return FALSE;
842         else
843                 return TRUE;
844 }
845
846 void sgpgme_check_create_key(void)
847 {
848         if (prefs_gpg_get_config()->gpg_ask_create_key &&
849             !sgpgme_has_secret_key()) {
850                 sgpgme_create_secret_key(NULL, TRUE);
851         } else {
852                 prefs_gpg_get_config()->gpg_ask_create_key = FALSE;
853                 prefs_gpg_save_config();
854         }       
855 }
856
857 void *sgpgme_data_release_and_get_mem(gpgme_data_t data, size_t *len)
858 {
859         char buf[BUFSIZ];
860         void *result = NULL;
861         ssize_t r = 0;
862         size_t w = 0;
863         
864         if (data == NULL)
865                 return NULL;
866         if (len == NULL)
867                 return NULL;
868
869         /* I know it's deprecated, but we don't compile with _LARGEFILE */
870         gpgme_data_rewind(data);
871         while ((r = gpgme_data_read(data, buf, BUFSIZ)) > 0) {
872                 result = realloc(result, r + w);
873                 memcpy(result+w, buf, r);
874                 w += r;
875         }
876         
877         *len = w;
878
879         gpgme_data_release(data);
880         if (r < 0) {
881                 free(result);
882                 *len = 0;
883                 return NULL;
884         }
885         return result;
886 }
887 #endif /* USE_GPGME */