File: libbalsa.c

package info (click to toggle)
balsa 2.3.13-3
  • links: PTS
  • area: main
  • in suites: etch
  • size: 16,032 kB
  • ctags: 7,261
  • sloc: ansic: 79,348; sh: 8,731; xml: 4,721; makefile: 485; awk: 60
file content (942 lines) | stat: -rw-r--r-- 25,636 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
/* -*-mode:c; c-style:k&r; c-basic-offset:4; -*- */
/* Balsa E-Mail Client
 *
 * Copyright (C) 1997-2002 Stuart Parmenter and others,
 *                         See the file AUTHORS for a list.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2, or (at your option) 
 * any later version.
 *  
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the  
 * GNU General Public License for more details.
 *  
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  
 * 02111-1307, USA.
 */

#include "config.h"

#define _XOPEN_SOURCE 500

#include <glib.h>

#include <string.h>
#include <stdlib.h>
#include <sys/utsname.h>
#include <sys/stat.h>
#include <stdarg.h>
#include <unistd.h>

#if ENABLE_LDAP
#include <ldap.h>
#endif

#if HAVE_COMPFACE
#include <compface.h>
#endif                          /* HAVE_COMPFACE */

#if HAVE_GTKSOURCEVIEW
#include <gtksourceview/gtksourceview.h>
#include <gtksourceview/gtksourcebuffer.h>
#include <gtksourceview/gtksourcetag.h>
#include <gtksourceview/gtksourcetagstyle.h>
#endif

#include "libbalsa.h"
#include "misc.h"
#include "i18n.h"

#ifdef BALSA_USE_THREADS
static pthread_t main_thread_id;
static pthread_t libbalsa_threads_id;
#endif


void
libbalsa_message(const char *fmt, ...)
{
    va_list va_args;

    va_start(va_args, fmt);
    libbalsa_information_varg(NULL, LIBBALSA_INFORMATION_MESSAGE,
                              fmt, va_args);
    va_end(va_args);
}

void
libbalsa_init(LibBalsaInformationFunc information_callback)
{
    struct utsname utsname;


#ifdef BALSA_USE_THREADS
    if (!g_thread_supported()) {
	g_error("Threads have not been initialised.");
    }
    main_thread_id = pthread_self();
#endif

    uname(&utsname);

    libbalsa_real_information_func = information_callback;

    g_mime_init(0);

    /* Register our types */
    /* So that libbalsa_mailbox_new_from_config will work... */
    LIBBALSA_TYPE_MAILBOX_LOCAL;
    LIBBALSA_TYPE_MAILBOX_POP3;
    LIBBALSA_TYPE_MAILBOX_IMAP;
    LIBBALSA_TYPE_MAILBOX_MBOX;
    LIBBALSA_TYPE_MAILBOX_MH;
    LIBBALSA_TYPE_MAILBOX_MAILDIR;

    LIBBALSA_TYPE_ADDRESS_BOOK_VCARD;
    LIBBALSA_TYPE_ADDRESS_BOOK_EXTERN;
    LIBBALSA_TYPE_ADDRESS_BOOK_LDIF;
#if ENABLE_LDAP
    LIBBALSA_TYPE_ADDRESS_BOOK_LDAP;
#endif
#if HAVE_SQLITE
    LIBBALSA_TYPE_ADDRESS_BOOK_GPE;
#endif
}


/* libbalsa_rot:
   return rot13'ed string.
*/
gchar *
libbalsa_rot(const gchar * pass)
{
    gchar *buff;
    gint len = 0, i = 0;

    /*PKGW: let's do the assert() BEFORE we coredump... */

    len = strlen(pass);
    buff = g_strdup(pass);

    for (i = 0; i < len; i++) {
	if ((buff[i] <= 'M' && buff[i] >= 'A')
	    || (buff[i] <= 'm' && buff[i] >= 'a'))
	    buff[i] += 13;
	else if ((buff[i] <= 'Z' && buff[i] >= 'N')
		 || (buff[i] <= 'z' && buff[i] >= 'n'))
	    buff[i] -= 13;
    }
    return buff;
}


/* libbalsa_guess_email_address:
   Email address can be determined in four ways:
   1. Using the environment variable 'EMAIL'

   2. The file '/etc/mailname' should contain the external host
      address for the host. Prepend the username (`username`@`cat
      /etc/mailname`).

   3. Append the domainname to the user name.
   4. Append the hostname to the user name.

*/
gchar*
libbalsa_guess_email_address(void)
{
    /* Q: Find this location with configure? or at run-time? */
    static const gchar* MAILNAME_FILE = "/etc/mailname";
    char hostbuf[512];
    FILE *mailname_in = NULL;

    gchar* preset, *domain;
    if(g_getenv("EMAIL") != NULL){                  /* 1. */
        preset = g_strdup(g_getenv("EMAIL"));
    } else if( (mailname_in = fopen(MAILNAME_FILE, "r")) != NULL
              && fgets(hostbuf, sizeof(hostbuf)-1, mailname_in)){ /* 2. */
        hostbuf[sizeof(hostbuf)-1] = '\0';
        preset = g_strconcat(g_get_user_name(), "@", hostbuf, NULL);
        
    }else if((domain = libbalsa_get_domainname())){ /* 3. */
        preset = g_strconcat(g_get_user_name(), "@", domain, NULL);
        g_free(domain);    
    } else {                                        /* 4. */
        gethostname(hostbuf, 511);
        preset = g_strconcat(g_get_user_name(), "@", hostbuf, NULL);
    }
    if (mailname_in)
        fclose(mailname_in);
    return preset;
}

/* libbalsa_guess_mail_spool

   Returns an allocated gchar * with our best guess of the user's
   mail spool file.
*/
gchar *
libbalsa_guess_mail_spool(void)
{
    int i;
    gchar *env;
    gchar *spool;
    static const gchar *guesses[] = {
	"/var/mail/",
	"/var/spool/mail/",
	"/usr/spool/mail/",
	"/usr/mail/",
	NULL
    };

    if ((env = getenv("MAIL")) != NULL)
	return g_strdup(env);

    if ((env = getenv("USER")) != NULL) {
	for (i = 0; guesses[i] != NULL; i++) {
	    spool = g_strconcat(guesses[i], env, NULL);

	    if (g_file_test(spool, G_FILE_TEST_EXISTS))
		return spool;

	    g_free(spool);
	}
    }

    /* libmutt's configure.in indicates that this 
     * ($HOME/mailbox) exists on
     * some systems, and it's a good enough default if we
     * can't guess it any other way. */
    return g_strconcat(g_get_home_dir(), "/mailbox", NULL);
}


gboolean libbalsa_ldap_exists(const gchar *server)
{
#if ENABLE_LDAP
    LDAP *ldap;
    ldap_initialize(&ldap, server);

    if(ldap) {
	ldap_unbind_ext(ldap, NULL, NULL);
	return TRUE;
    }
#endif /* #if ENABLE_LDAP */

    return FALSE;
}

gchar*
libbalsa_date_to_utf8(const time_t *date, const gchar *date_string)
{
    struct tm footime;
    gchar rettime[128];

    g_return_val_if_fail(date != NULL, NULL);
    g_return_val_if_fail(date_string != NULL, NULL);

    localtime_r(date, &footime);

    strftime(rettime, sizeof(rettime), date_string, &footime);

    return g_locale_to_utf8(rettime, -1, NULL, NULL, NULL);
}

LibBalsaMessageStatus
libbalsa_get_icon_from_flags(LibBalsaMessageFlag flags)
{
    LibBalsaMessageStatus icon;
    if (flags & LIBBALSA_MESSAGE_FLAG_DELETED)
	icon = LIBBALSA_MESSAGE_STATUS_DELETED;
    else if (flags & LIBBALSA_MESSAGE_FLAG_NEW)
	icon = LIBBALSA_MESSAGE_STATUS_UNREAD;
    else if (flags & LIBBALSA_MESSAGE_FLAG_FLAGGED)
	icon = LIBBALSA_MESSAGE_STATUS_FLAGGED;
    else if (flags & LIBBALSA_MESSAGE_FLAG_REPLIED)
	icon = LIBBALSA_MESSAGE_STATUS_REPLIED;
    else
	icon = LIBBALSA_MESSAGE_STATUS_ICONS_NUM;
    return icon;
}


#if defined(USE_SSL)
#include <openssl/ssl.h>
#include <openssl/x509.h>
#include <openssl/err.h>
static int libbalsa_ask_for_cert_acceptance(X509 *cert,
					    const char *explanation);
static char*
asn1time_to_string(ASN1_UTCTIME *tm)
{
    char buf[64];
    int cnt;
    BIO *bio  = BIO_new(BIO_s_mem());
    strncpy(buf, _("Invalid date"), sizeof(buf)); buf[sizeof(buf)-1]='\0';

    if(ASN1_TIME_print(bio, tm)) {
        cnt = BIO_read(bio, buf, sizeof(buf)-1);
        buf[cnt] = '\0';
    }
    BIO_free(bio);
    return g_strdup(buf);
}

static char*
x509_get_part (char *line, const char *ndx)
{
    static char ret[256];
    char *c, *c2;
    
    strncpy (ret, _("Unknown"), sizeof (ret)); ret[sizeof(ret)-1]='\0';
    
    c = strstr(line, ndx);
    if (c) {
        c += strlen (ndx);
        c2 = strchr (c, '/');
        if (c2)
            *c2 = '\0';
        strncpy (ret, c, sizeof (ret));
        if (c2)
            *c2 = '/';
    }
    
    return ret;
}
static void
x509_fingerprint (char *s, unsigned len, X509 * cert)
{
    unsigned j, i, n, c;
    unsigned char md[EVP_MAX_MD_SIZE];


    X509_digest(cert, EVP_md5(), md, &n);
    if(len<3*n) n = len/3;
    for (j=i=0; j<n; j++) {
        c = (md[j] >>4) & 0xF; s[i++] = c<10 ? c + '0' : c+'A'-10;
        c = md[j] & 0xF;       s[i++] = c<10 ? c + '0' : c+'A'-10;
        if(j<n-1) s[i++] = ':';
    }
    s[i] = '\0';
}

static GList *accepted_certs = NULL; /* certs accepted for this session */

#ifdef BALSA_USE_THREADS
static pthread_mutex_t certificate_lock = PTHREAD_MUTEX_INITIALIZER;
#define LOCK_CERTIFICATES   pthread_mutex_lock(&certificate_lock)
#define UNLOCK_CERTIFICATES pthread_mutex_unlock(&certificate_lock)
#else
#define LOCK_CERTIFICATES
#define UNLOCK_CERTIFICATES
#endif

void
libbalsa_certs_destroy(void)
{
    LOCK_CERTIFICATES;
    g_list_foreach(accepted_certs, (GFunc)X509_free, NULL);
    g_list_free(accepted_certs);
    accepted_certs = NULL;
    UNLOCK_CERTIFICATES;
}

/* compare Example 10-7 in the OpenSSL book */
gboolean
libbalsa_is_cert_known(X509* cert, long vfy_result)
{
    X509 *tmpcert = NULL;
    FILE *fp;
    gchar *cert_name;
    gboolean res = FALSE;
    GList *lst;

    LOCK_CERTIFICATES;
    for(lst = accepted_certs; lst; lst = lst->next) {
        int res = X509_cmp(cert, lst->data);
        if(res == 0) {
	    UNLOCK_CERTIFICATES;
            return TRUE;
	}
    }
    
    cert_name = g_strconcat(g_get_home_dir(), "/.balsa/certificates", NULL);

    fp = fopen(cert_name, "rt");
    g_free(cert_name);
    if(fp) {
        /* 
        printf("Looking for cert: %s\n", 
               X509_NAME_oneline(X509_get_subject_name (cert),
                                 buf, sizeof (buf)));
        */
        res = FALSE;
        while ((tmpcert = PEM_read_X509(fp, NULL, NULL, NULL)) != NULL) {
            res = X509_cmp(cert, tmpcert)==0;
            X509_free(tmpcert);
            if(res) break;
        }
        ERR_clear_error();
        fclose(fp);
    }
    UNLOCK_CERTIFICATES;
    
    if(!res) {
	const char *reason = X509_verify_cert_error_string(vfy_result);
	res = libbalsa_ask_for_cert_acceptance(cert, reason);
	LOCK_CERTIFICATES;
	if(res == 2) {
	    cert_name = g_strconcat(g_get_home_dir(),
				    "/.balsa/certificates", NULL);
            libbalsa_assure_balsa_dir();
	    fp = fopen(cert_name, "a");
	    if (fp) {
		if(PEM_write_X509 (fp, cert))
		    res = TRUE;
		fclose(fp);
	    }
	    g_free(cert_name);
	}
	if(res == 1)
	    accepted_certs = 
		g_list_prepend(accepted_certs, X509_dup(cert));
	UNLOCK_CERTIFICATES;
    }

    return res;
}

/* libbalsa_ask_for_cert_acceptance():
   returns:
   OP_EXIT on reject.
   OP_SAVE - on accept and save.
   OP_MAX - on accept once.
   TODO: check treading issues.

*/
static int
ask_cert_real(X509 *cert, const char *explanation)
{

    char *part[] =
        {"/CN=", "/Email=", "/O=", "/OU=", "/L=", "/ST=", "/C="};
    char buf[256]; /* fingerprint requires EVP_MAX_MD_SIZE*3 */
    char *name = NULL, *c, *valid_from, *valid_until;
    GtkWidget* dialog, *label;
    unsigned i;

    GString* str = g_string_new("");

    g_string_printf(str, _("Authenticity of this certificate "
                           "could not be verified.\n"
                           "<b>Reason:</b> %s\n"
                           "<b>This certificate belongs to:</b>\n"),
                    explanation);

    name = X509_NAME_oneline(X509_get_subject_name (cert), buf, sizeof (buf));
    for (i = 0; i < ELEMENTS(part); i++) {
        g_string_append(str, x509_get_part (name, part[i]));
        g_string_append_c(str, '\n');
    }

    g_string_append(str, _("\n<b>This certificate was issued by:</b>\n"));
    name = X509_NAME_oneline(X509_get_issuer_name(cert), buf, sizeof (buf));
    for (i = 0; i < ELEMENTS(part); i++) {
        g_string_append(str, x509_get_part (name, part[i]));
        g_string_append_c(str, '\n');
    }

    buf[0] = '\0';
    x509_fingerprint (buf, sizeof (buf), cert);
    valid_from  = asn1time_to_string(X509_get_notBefore(cert));
    valid_until = asn1time_to_string(X509_get_notAfter(cert)),
    c = g_strdup_printf(_("<b>This certificate is valid</b>\n"
                          "from %s\n"
                          "to %s\n"
                          "<b>Fingerprint:</b> %s"),
                        valid_from, valid_until,
                        buf);
    g_string_append(str, c); g_free(c);
    g_free(valid_from); g_free(valid_until);

    dialog = gtk_dialog_new_with_buttons(_("SSL/TLS certificate"), NULL,
                                         GTK_DIALOG_MODAL,
                                         _("_Accept Once"), 0,
                                         _("Accept&_Save"), 1,
                                         _("_Reject"), GTK_RESPONSE_CANCEL, 
                                         NULL);
    gtk_window_set_wmclass(GTK_WINDOW(dialog), "tls_cert_dialog", "Balsa");
    label = gtk_label_new(str->str);
    g_string_free(str, TRUE);
    gtk_label_set_use_markup(GTK_LABEL(label), TRUE);
    gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->vbox),
                       label, TRUE, TRUE, 1);
    gtk_widget_show(label);

    switch(gtk_dialog_run(GTK_DIALOG(dialog))) {
    case 0: i = 1; break;
    case 1: i = 2; break;
    case GTK_RESPONSE_CANCEL:
    default: i=0; break;
    }
    gtk_widget_destroy(dialog);
    /* Process some events to let the window disappear:
     * not really necessary but helps with debugging. */
   while(gtk_events_pending()) 
        gtk_main_iteration_do(FALSE);
    printf("%s returns %d\n", __FUNCTION__, i);
    return i;
}

#ifdef BALSA_USE_THREADS
#include <pthread.h>
typedef struct {
    pthread_cond_t cond;
    X509 *cert;
    const char *expl;
    int res;
} AskCertData;
/* ask_cert_idle:
   called in MT mode by the main thread.
 */
static gboolean
ask_cert_idle(gpointer data)
{
    AskCertData* acd = (AskCertData*)data;
    gdk_threads_enter();
    acd->res = ask_cert_real(acd->cert, acd->expl);
    gdk_threads_leave();
    pthread_cond_signal(&acd->cond);
    return FALSE;
}
/* libmutt_ask_for_cert_acceptance:
   executed with GDK UNLOCKED. see mailbox_imap_open() and
   imap_dir_cb()/imap_folder_imap_dir().
*/
static int
libbalsa_ask_for_cert_acceptance(X509 *cert, const char *explanation)
{
    static pthread_mutex_t ask_cert_lock = PTHREAD_MUTEX_INITIALIZER;
    AskCertData acd;

    if (pthread_self() == main_thread_id)
	return ask_cert_real(cert, explanation);

    pthread_mutex_lock(&ask_cert_lock);
    pthread_cond_init(&acd.cond, NULL);
    acd.cert = cert;
    acd.expl = explanation;
    g_idle_add(ask_cert_idle, &acd);
    pthread_cond_wait(&acd.cond, &ask_cert_lock);
    
    pthread_cond_destroy(&acd.cond);
    pthread_mutex_unlock(&ask_cert_lock);
    return acd.res;
}
#else /* BALSA_USE_THREADS */
static int
libbalsa_ask_for_cert_acceptance(X509 *cert, const char *explanation)
{
    return ask_cert_real(cert, explanation);
}
#endif /* BALSA_USE_THREADS */

#endif /* WITH_SSL */


#ifdef BALSA_USE_THREADS
pthread_t
libbalsa_get_main_thread(void)
{
    return main_thread_id;
}

gboolean
libbalsa_am_i_subthread(void)
{
    return pthread_self() != main_thread_id;
}
#endif /* BALSA_USE_THREADS */

#ifdef BALSA_USE_THREADS
#include "libbalsa_private.h"	/* for prototypes */
pthread_mutex_t mailbox_lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t mailbox_cond = PTHREAD_COND_INITIALIZER;

/* Lock/unlock a mailbox; no argument checking--we'll assume the caller
 * took care of that. 
 */
#define LIBBALSA_DEBUG_THREADS FALSE
void
libbalsa_lock_mailbox(LibBalsaMailbox * mailbox)
{
    pthread_t thread_id = pthread_self();
    gint count = 0;

    if (thread_id == libbalsa_threads_id
        && thread_id == mailbox->thread_id
        && mailbox->lock > 0) {
        /* We already have both locks, so we'll just hold on to both of
         * them. */
        ++mailbox->lock;
#if LIBBALSA_DEBUG_THREADS
        g_message("Avoided temporary gdk_threads_leave!!!");
#endif                          /* LIBBALSA_DEBUG_THREADS */
        return;
    }

    while (thread_id == libbalsa_threads_id) {
        ++count;
#if LIBBALSA_DEBUG_THREADS
        g_message("Temporary gdk_threads_leave!!!");
#endif                          /* LIBBALSA_DEBUG_THREADS */
        gdk_threads_leave();
    }

    pthread_mutex_lock(&mailbox_lock);

    while (mailbox->lock && mailbox->thread_id != thread_id)
        pthread_cond_wait(&mailbox_cond, &mailbox_lock);

    /* We'll assume that no-one would destroy a mailbox while we've been
     * trying to lock it. If they have, we have larger problems than
     * this reference! */
    mailbox->lock++;
    mailbox->thread_id = thread_id;

    pthread_mutex_unlock(&mailbox_lock);

    while (--count >= 0) {
        gdk_threads_enter();
#if LIBBALSA_DEBUG_THREADS
        g_message("...and gdk_threads_enter!!!");
#endif                          /* LIBBALSA_DEBUG_THREADS */
    }
}

void
libbalsa_unlock_mailbox(LibBalsaMailbox * mailbox)
{
    pthread_t self;

    self = pthread_self();

    pthread_mutex_lock(&mailbox_lock);

    if (mailbox->lock == 0 || self != mailbox->thread_id) {
	g_warning("Not holding mailbox lock!!!");
        pthread_mutex_unlock(&mailbox_lock);
	return;
    }

    if(--mailbox->lock == 0) {
        pthread_cond_broadcast(&mailbox_cond);
        mailbox->thread_id = 0;
    }

    pthread_mutex_unlock(&mailbox_lock);
}

/* Recursive mutex for gdk_threads_{enter,leave}. */
static pthread_mutex_t libbalsa_threads_mutex;
static guint libbalsa_threads_lock;

static void
libbalsa_threads_enter(void)
{
    pthread_t self;

    self = pthread_self();

    if (self != libbalsa_threads_id) {
        pthread_mutex_lock(&libbalsa_threads_mutex);
        libbalsa_threads_id = self;
    }
    ++libbalsa_threads_lock;
}

static void
libbalsa_threads_leave(void)
{
    pthread_t self;

    self = pthread_self();

    if (libbalsa_threads_lock == 0 || self != libbalsa_threads_id) {
	g_warning("Not holding gdk lock!!!");
	return;
    }

    if (--libbalsa_threads_lock == 0) {
	if (self != main_thread_id)
	    gdk_display_flush(gdk_display_get_default());
        libbalsa_threads_id = 0;
        pthread_mutex_unlock(&libbalsa_threads_mutex);
    }
}

void
libbalsa_threads_init(void)
{
    pthread_mutex_init(&libbalsa_threads_mutex, NULL);
    gdk_threads_set_lock_functions(G_CALLBACK(libbalsa_threads_enter),
                                   G_CALLBACK(libbalsa_threads_leave));
}

void
libbalsa_threads_destroy(void)
{
    pthread_mutex_destroy(&libbalsa_threads_mutex);
}

gboolean
libbalsa_threads_has_lock(void)
{
    return libbalsa_threads_lock > 0
        && libbalsa_threads_id == pthread_self();
}

#endif				/* BALSA_USE_THREADS */

/* Initialized by the front end. */
void (*libbalsa_progress_set_text) (LibBalsaProgress * progress,
                                    const gchar * text, guint total);
void (*libbalsa_progress_set_fraction) (LibBalsaProgress * progress,
                                        gdouble fraction);

/*
 * Face and X-Face header support.
 */
gchar *
libbalsa_get_header_from_path(const gchar * header, const gchar * path,
                              gsize * size, GError ** err)
{
    gchar *buf, *content;
    size_t name_len;
    gchar *p, *q;

    if (!g_file_get_contents(path, &buf, size, err))
        return NULL;

    content = buf;
    name_len = strlen(header);
    if (g_ascii_strncasecmp(content, header, name_len) == 0)
        /* Skip header and trailing colon: */
        content += name_len + 1;

    /* Unfold. */
    for (p = q = content; *p; p++)
        if (*p != '\r' && *p != '\n')
            *q++ = *p;
    *q = '\0';

    content = g_strdup(content);
    g_free(buf);

    return content;
}

GtkWidget *
libbalsa_get_image_from_face_header(const gchar * content, GError ** err)
{
    GMimeStream *stream;
    GMimeStream *stream_filter;
    GMimeFilter *filter;
    GByteArray *array;
    GtkWidget *image = NULL;

    stream = g_mime_stream_mem_new();
    stream_filter = g_mime_stream_filter_new_with_stream(stream);

    filter = g_mime_filter_basic_new_type(GMIME_FILTER_BASIC_BASE64_DEC);
    g_mime_stream_filter_add(GMIME_STREAM_FILTER(stream_filter), filter);
    g_object_unref(filter);

    g_mime_stream_write_string(stream_filter, content);
    g_object_unref(stream_filter);

    array = GMIME_STREAM_MEM(stream)->buffer;
    if (array->len == 0)
        g_set_error(err, LIBBALSA_IMAGE_ERROR,
                    LIBBALSA_IMAGE_ERROR_NO_DATA, _("No image data"));
    else {
        GdkPixbufLoader *loader =
            gdk_pixbuf_loader_new_with_type("png", NULL);

        gdk_pixbuf_loader_write(loader, array->data, array->len, err);
        gdk_pixbuf_loader_close(loader, *err ? NULL : err);

        if (!*err)
            image = gtk_image_new_from_pixbuf(gdk_pixbuf_loader_get_pixbuf
                                              (loader));
        g_object_unref(loader);
    }
    g_object_unref(stream);

    return image;
}


GQuark
libbalsa_image_error_quark(void)
{
    static GQuark quark = 0;
    if (quark == 0)
        quark = g_quark_from_static_string("libbalsa-image-error-quark");
    return quark;
}

#if HAVE_COMPFACE
GtkWidget *
libbalsa_get_image_from_x_face_header(const gchar * content, GError ** err)
{
    gchar buf[2048];
    GdkPixbuf *pixbuf;
    guchar *pixels;
    gint lines;
    const gchar *p;
    GtkWidget *image = NULL;

    strncpy(buf, content, sizeof buf - 1);

    switch (uncompface(buf)) {
    case -1:
        g_set_error(err, LIBBALSA_IMAGE_ERROR, LIBBALSA_IMAGE_ERROR_FORMAT,
                    _("Invalid input format"));
        return image;
    case -2:
        g_set_error(err, LIBBALSA_IMAGE_ERROR, LIBBALSA_IMAGE_ERROR_BUFFER,
                    _("Internal buffer overrun"));
        return image;
    }

    pixbuf = gdk_pixbuf_new(GDK_COLORSPACE_RGB, FALSE, 8, 48, 48);
    pixels = gdk_pixbuf_get_pixels(pixbuf);

    p = buf;
    for (lines = 48; lines > 0; --lines) {
        guint x[3];
        gint j, k;
        guchar *q;

        if (sscanf(p, "%x,%x,%x,", &x[0], &x[1], &x[2]) != 3) {
            g_set_error(err, LIBBALSA_IMAGE_ERROR,
                        LIBBALSA_IMAGE_ERROR_BAD_DATA,
                        /* Translators: please do not translate Face. */
                        _("Bad X-Face data"));
            g_object_unref(pixbuf);
            return image;
        }
        for (j = 0, q = pixels; j < 3; j++)
            for (k = 15; k >= 0; --k){
                guchar c = x[j] & (1 << k) ? 0x00 : 0xff;
                *q++ = c;       /* red   */
                *q++ = c;       /* green */
                *q++ = c;       /* blue  */
            }
        p = strchr(p, '\n') + 1;
        pixels += gdk_pixbuf_get_rowstride(pixbuf);
    }

    image = gtk_image_new_from_pixbuf(pixbuf);
    g_object_unref(pixbuf);

    return image;
}
#endif                          /* HAVE_COMPFACE */

#if HAVE_GTKSOURCEVIEW
GtkWidget *
libbalsa_source_view_new(gboolean highlight_phrases, GdkColor *q_colour)
{
    GtkTextTag * text_tag;
    GtkSourceTagStyle *tag_style;
    GtkSourceTagTable *tag_table;
    GSList *tag_list;
    GtkSourceBuffer *sbuffer;
    GtkWidget *sview;

    /* create the tag table */
    tag_list = NULL;
    tag_table = gtk_source_tag_table_new();

    /* add highlighting for quoted text if requested */
    if (q_colour) {
	int k;

	for (k = 1; k <= 9; k++) {
	    gchar * tag_id;
	    const gchar * pattern;
            gchar *tmp = NULL;

	    tag_id = g_strdup_printf("Quote-%d", k);
	    if (k == 1)
		pattern = "^> *($|[^ |>:}#\n])";
	    else
		pattern = tmp =
                    g_strdup_printf("^(> *){%d}($|[^ |>:}#\n])", k);
	    text_tag = gtk_line_comment_tag_new(tag_id, tag_id, pattern);
	    g_free(tmp);
	    g_free(tag_id);
	    tag_style = gtk_source_tag_style_new();
	    tag_style->mask = GTK_SOURCE_TAG_STYLE_USE_FOREGROUND;
	    tag_style->foreground = q_colour[(k - 1) & 1];
	    gtk_source_tag_set_style(GTK_SOURCE_TAG(text_tag), tag_style);
	    gtk_source_tag_style_free(tag_style);
	    tag_list = g_slist_prepend(tag_list, text_tag);
	}
    }

    /* if requested create the patterns for bold, italic and underline */
    if (highlight_phrases) {
	text_tag = gtk_pattern_tag_new("Bold", "Bold",
				       "(^|[[:space:]])\\*[[:alnum:]][^*\n]*[[:alnum:]]\\*");
	tag_style = gtk_source_tag_style_new();
	tag_style->bold = TRUE;
	gtk_source_tag_set_style(GTK_SOURCE_TAG(text_tag), tag_style);
	gtk_source_tag_style_free(tag_style);
	tag_list = g_slist_prepend(tag_list, text_tag);

	text_tag = gtk_pattern_tag_new("Italic", "Italic",
				       "(^|[[:space:]])/[[:alnum:]][^/\n]*[[:alnum:]]/");
	tag_style = gtk_source_tag_style_new();
	tag_style->italic = TRUE;
	gtk_source_tag_set_style(GTK_SOURCE_TAG(text_tag), tag_style);
	gtk_source_tag_style_free(tag_style);
	tag_list = g_slist_prepend(tag_list, text_tag);

	text_tag = gtk_pattern_tag_new("Underline", "Underline",
				       "(^|[[:space:]])_[[:alnum:]][^_\n]*[[:alnum:]]_");
	tag_style = gtk_source_tag_style_new();
	tag_style->underline = TRUE;
	gtk_source_tag_set_style(GTK_SOURCE_TAG(text_tag), tag_style);
	gtk_source_tag_style_free(tag_style);
	tag_list = g_slist_prepend(tag_list, text_tag);
    }

    /* add tags to the table if present */
    if (tag_list) {
	gtk_source_tag_table_add_tags(tag_table, tag_list);
	g_slist_foreach(tag_list, (GFunc)g_object_unref, NULL);
	g_slist_free(tag_list);
    }

    /* create the source buffer */
    sbuffer = gtk_source_buffer_new(tag_table);
    g_object_unref(tag_table);
    gtk_source_buffer_set_highlight(sbuffer, highlight_phrases || q_colour);
    gtk_source_buffer_set_check_brackets(sbuffer, FALSE);

    /* create & return the source view */
    sview = gtk_source_view_new_with_buffer(sbuffer);
    g_object_unref(sbuffer);

    return sview;
}
#endif  /* HAVE_GTKSOURCEVIEW */