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