summaryrefslogtreecommitdiff
path: root/wocky/wocky-tls.c
blob: 855b9e67b9e4f5df9fb74483965ac1260cccaafe (plain)
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
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
/*
 * Copyright © 2008 Christian Kellner, Samuel Cormier-Iijima
 * Copyright © 2008-2009 Codethink Limited
 * Copyright © 2009 Collabora Limited
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published
 * by the Free Software Foundation; either version 2 of the licence or (at
 * your option) any later version.
 *
 * Authors: Ryan Lortie <desrt@desrt.ca>
 *          Christian Kellner <gicmo@gnome.org>
 *          Samuel Cormier-Iijima <sciyoshi@gmail.com>
 *          Vivek Dasmohapatra <vivek@collabora.co.uk>
 *
 * Upstream: git://git.gnome.org/gnio
 * Branched at: 42b00d143fcf644880456d06d3a20b6e990a7fa3
 *   "toss out everything that moved to glib"
 *
 * This file follows the original coding style from upstream, not house
 * collabora style: It is a copy of unmerged gnio TLS support with the
 * 'g' prefixes changes to 'wocky' and server-side TLS support added.
 */

/**
 * SECTION: wocky-tls
 * @title: Wocky GnuTLS TLS
 * @short_description: Establish TLS sessions
 *
 * The WOCKY_TLS_DEBUG_LEVEL environment variable can be used to print debug
 * output from GNU TLS. To enable it, set it to a value from 1 to 9.
 * Higher values will print more information. See the documentation of
 * gnutls_global_set_log_level for more details.
 *
 * Increasing the value past certain thresholds will also trigger increased
 * debugging output from within wocky-tls.c as well.
 *
 * The WOCKY_GNUTLS_OPTIONS environment variable can be set to a gnutls
 * priority string [See gnutls-cli(1) or the gnutls_priority_init docs]
 * to control most tls protocol details. An empty or unset value is roughly
 * equivalent to a priority string of "SECURE:+COMP-DEFLATE".
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "wocky-tls.h"

#include <gnutls/x509.h>
#include <gnutls/openpgp.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>

#ifdef ENABLE_PREFER_STREAM_CIPHERS
#define DEFAULT_TLS_OPTIONS \
  /* start with nothing enabled by default */ \
  "NONE:" \
  /* enable all the normal algorithms */ \
  "+VERS-TLS-ALL:+SIGN-ALL:+MAC-ALL:+CTYPE-ALL:+RSA:" \
  /* prefer deflate compression, but fall back to null compression */ \
  "+COMP-DEFLATE:+COMP-NULL:" \
  /* our preferred stream ciphers */ \
  "+ARCFOUR-128:+ARCFOUR-40:" \
  /* all the other ciphers */ \
  "+AES-128-CBC:+AES-256-CBC:+3DES-CBC:+DES-CBC:+RC2-40:" \
  "+CAMELLIA-256-CBC:+CAMELLIA-128-CBC"
#else
#define DEFAULT_TLS_OPTIONS \
  "NORMAL:"        /* all secure algorithms */ \
  "-COMP-NULL:"    /* remove null compression */ \
  "+COMP-DEFLATE:" /* prefer deflate */ \
  "+COMP-NULL"     /* fall back to null */
#endif

#define DEBUG_FLAG DEBUG_TLS
#define DEBUG_HANDSHAKE_LEVEL 5
#define DEBUG_ASYNC_DETAIL_LEVEL 6

#define VERIFY_STRICT  GNUTLS_VERIFY_DO_NOT_ALLOW_SAME
#define VERIFY_NORMAL  GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT
#define VERIFY_LENIENT ( GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT     | \
                         GNUTLS_VERIFY_ALLOW_ANY_X509_V1_CA_CRT | \
                         GNUTLS_VERIFY_ALLOW_SIGN_RSA_MD2       | \
                         GNUTLS_VERIFY_ALLOW_SIGN_RSA_MD5       | \
                         GNUTLS_VERIFY_DISABLE_TIME_CHECKS      | \
                         GNUTLS_VERIFY_DISABLE_CA_SIGN          )

#include "wocky-debug.h"
#include "wocky-tls-enumtypes.h"
#include "wocky-utils.h"

#include <gnutls/gnutls.h>
#include <string.h>
#include <errno.h>
#include <gcrypt.h>
#include <sys/types.h>
#include <unistd.h>
enum
{
  PROP_S_NONE,
  PROP_S_STREAM,
  PROP_S_SERVER,
  PROP_S_DHBITS,
  PROP_S_KEYFILE,
  PROP_S_CERTFILE,
};

enum
{
  PROP_C_NONE,
  PROP_C_SESSION,
};

enum
{
  PROP_O_NONE,
  PROP_O_SESSION
};

enum
{
  PROP_I_NONE,
  PROP_I_SESSION
};

typedef struct
{
  gboolean active;

  gint io_priority;
  GCancellable *cancellable;
  GObject *source_object;
  GAsyncReadyCallback callback;
  gpointer user_data;
  gpointer source_tag;
  GError *error;
} WockyTLSJob;

typedef enum
{
  WOCKY_TLS_OP_READ,
  WOCKY_TLS_OP_WRITE
} WockyTLSOperation;

typedef enum
{
  WOCKY_TLS_OP_STATE_IDLE,
  WOCKY_TLS_OP_STATE_ACTIVE,
  WOCKY_TLS_OP_STATE_DONE
} WockyTLSOpState;

typedef struct
{
  WockyTLSJob job;
} WockyTLSJobHandshake;

typedef struct
{
  WockyTLSJob job;

  gconstpointer buffer;
  gsize count;
} WockyTLSJobWrite;

typedef struct
{
  WockyTLSJob job;

  gpointer buffer;
  gsize count;
} WockyTLSJobRead;

typedef struct
{
  WockyTLSOpState state;

  guint8 *buffer;
  gssize requested;
  gssize result;
  GError *error;
} WockyTLSOp;

typedef GIOStreamClass WockyTLSConnectionClass;
typedef GObjectClass WockyTLSSessionClass;
typedef GInputStreamClass WockyTLSInputStreamClass;
typedef GOutputStreamClass WockyTLSOutputStreamClass;

static gnutls_dh_params_t dh_0768 = NULL;
static gnutls_dh_params_t dh_1024 = NULL;
static gnutls_dh_params_t dh_2048 = NULL;
static gnutls_dh_params_t dh_3072 = NULL;
static gnutls_dh_params_t dh_4096 = NULL;

struct _WockyTLSSession
{
  GObject parent;

  GIOStream *stream;
  GCancellable *cancellable;
  GError *error;
  gboolean async;

  /* tls server support */
  gboolean server;
  gnutls_dh_params_t dh_params;
  guint dh_bits;
  gchar *key_file;
  gchar *cert_file;

  /* frontend jobs */
  WockyTLSJobHandshake handshake_job;
  WockyTLSJobRead      read_job;
  WockyTLSJobWrite     write_job;

  /* backend jobs */
  WockyTLSOp           read_op;
  WockyTLSOp           write_op;

  gnutls_session_t session;

  gnutls_certificate_credentials gnutls_cert_cred;
};

typedef struct
{
  GInputStream parent;
  WockyTLSSession *session;
} WockyTLSInputStream;

typedef struct
{
  GOutputStream parent;
  WockyTLSSession *session;
} WockyTLSOutputStream;

struct _WockyTLSConnection
{
  GIOStream parent;

  WockyTLSSession *session;
  WockyTLSInputStream *input;
  WockyTLSOutputStream *output;
};

static guint tls_debug_level = 0;

static GType wocky_tls_input_stream_get_type (void);
static GType wocky_tls_output_stream_get_type (void);
G_DEFINE_TYPE (WockyTLSConnection, wocky_tls_connection, G_TYPE_IO_STREAM);
G_DEFINE_TYPE (WockyTLSSession, wocky_tls_session, G_TYPE_OBJECT);
G_DEFINE_TYPE (WockyTLSInputStream, wocky_tls_input_stream, G_TYPE_INPUT_STREAM);
G_DEFINE_TYPE (WockyTLSOutputStream, wocky_tls_output_stream, G_TYPE_OUTPUT_STREAM);
#define WOCKY_TYPE_TLS_INPUT_STREAM (wocky_tls_input_stream_get_type ())
#define WOCKY_TYPE_TLS_OUTPUT_STREAM (wocky_tls_output_stream_get_type ())
#define WOCKY_TLS_INPUT_STREAM(inst) (G_TYPE_CHECK_INSTANCE_CAST ((inst),   \
                                      WOCKY_TYPE_TLS_INPUT_STREAM,          \
                                      WockyTLSInputStream))
#define WOCKY_TLS_OUTPUT_STREAM(inst) (G_TYPE_CHECK_INSTANCE_CAST ((inst),   \
                                       WOCKY_TYPE_TLS_OUTPUT_STREAM,         \
                                       WockyTLSOutputStream))

GQuark
wocky_tls_cert_error_quark (void)
{
  static GQuark quark = 0;

  if (quark == 0)
    quark = g_quark_from_static_string ("wocky-tls-cert-error");

  return quark;
}

static const gchar *hdesc_to_string (long desc)
{
#define HDESC(x) case GNUTLS_HANDSHAKE_##x: return #x; break;
  switch (desc)
    {
      HDESC (HELLO_REQUEST);
      HDESC (CLIENT_HELLO);
      HDESC (SERVER_HELLO);
      HDESC (CERTIFICATE_PKT);
      HDESC (SERVER_KEY_EXCHANGE);
      HDESC (CERTIFICATE_REQUEST);
      HDESC (SERVER_HELLO_DONE);
      HDESC (CERTIFICATE_VERIFY);
      HDESC (CLIENT_KEY_EXCHANGE);
      HDESC (FINISHED);
      HDESC (SUPPLEMENTAL);
    }
  return "Unknown State";
}

static const gchar *error_to_string (long error)
{
  const gchar *result;

  result = gnutls_strerror_name (error);
  if (result != NULL)
    return result;

  return "Unknown Error";
}

static gboolean
wocky_tls_set_error (GError **error,
                     gssize   result)
{
  int code = (int) result;

  if (result < 0)
    g_set_error (error, 0, 0, "%d: %s", code, error_to_string (code));

  return result < 0;
}

static GSimpleAsyncResult *
wocky_tls_job_make_result (WockyTLSJob *job,
                           gssize   result)
{
  if (result != GNUTLS_E_AGAIN)
    {
      GSimpleAsyncResult *simple;
      GError *error = NULL;

      simple = g_simple_async_result_new (job->source_object,
                                          job->callback,
                                          job->user_data,
                                          job->source_tag);

      if (job->error != NULL)
        {
#ifdef WOCKY_TLS_STRICT_ERROR_ASSERTIONS
          g_assert (result == GNUTLS_E_PUSH_ERROR ||
                    result == GNUTLS_E_PULL_ERROR);
#endif
          g_simple_async_result_set_from_error (simple, job->error);
          g_error_free (job->error);
        }
      else if (wocky_tls_set_error (&error, result))
        {
          g_simple_async_result_set_from_error (simple, error);
          g_error_free (error);
        }

      if (job->cancellable != NULL)
        g_object_unref (job->cancellable);
      job->cancellable = NULL;

      g_object_unref (job->source_object);
      job->source_object = NULL;

      job->active = FALSE;

      return simple;
    }
  else
    {
      g_assert (job->active);
      return NULL;
    }
}

static void
wocky_tls_job_result_gssize (WockyTLSJob *job,
                             gssize   result)
{
  GSimpleAsyncResult *simple;

  if ((simple = wocky_tls_job_make_result (job, result)))
    {
      if (result >= 0)
        g_simple_async_result_set_op_res_gssize (simple, result);

      g_simple_async_result_complete (simple);
      g_object_unref (simple);
    }
}

static void
wocky_tls_job_result_boolean (WockyTLSJob *job,
                              gint     result)
{
  GSimpleAsyncResult *simple;

  if ((simple = wocky_tls_job_make_result (job, result)))
    {
      g_simple_async_result_complete (simple);
      g_object_unref (simple);
    }
}

static void
wocky_tls_session_try_operation (WockyTLSSession   *session,
                                 WockyTLSOperation  operation)
{
  if (session->handshake_job.job.active)
    {
      gint result;
      DEBUG ("session %p: async job handshake", session);
      session->async = TRUE;
      result = gnutls_handshake (session->session);
      g_assert (result != GNUTLS_E_INTERRUPTED);

      if (tls_debug_level >= DEBUG_HANDSHAKE_LEVEL)
        {
          gnutls_handshake_description_t i;
          gnutls_handshake_description_t o;

          DEBUG ("session %p: async job handshake: %d %s", session,
              result, error_to_string(result));
          i = gnutls_handshake_get_last_in (session->session);
          o = gnutls_handshake_get_last_out (session->session);
          DEBUG ("session %p: async job handshake: { in: %s; out: %s }",
              session, hdesc_to_string (i), hdesc_to_string (o));
        }

      session->async = FALSE;

      wocky_tls_job_result_boolean (&session->handshake_job.job, result);
    }

  else if (operation == WOCKY_TLS_OP_READ)
    {
      gssize result = 0;

      if (tls_debug_level >= DEBUG_ASYNC_DETAIL_LEVEL)
        DEBUG ("async job OP_READ");
      g_assert (session->read_job.job.active);

      /* If the read result is 0, the remote end disconnected us, no need to
       * pull data through gnutls_record_recv in that case */

      if (session->read_op.result != 0)
        {

          session->async = TRUE;
          result = gnutls_record_recv (session->session,
              session->read_job.buffer,
              session->read_job.count);
          g_assert (result != GNUTLS_E_INTERRUPTED);
          session->async = FALSE;
        }

      wocky_tls_job_result_gssize (&session->read_job.job, result);
    }

  else
    {
      gssize result;
      if (tls_debug_level >= DEBUG_ASYNC_DETAIL_LEVEL)
        DEBUG ("async job OP_WRITE: %"G_GSIZE_FORMAT,
          session->write_job.count);
      g_assert (operation == WOCKY_TLS_OP_WRITE);
      g_assert (session->write_job.job.active);


      session->async = TRUE;
      result = gnutls_record_send (session->session,
                                   session->write_job.buffer,
                                   session->write_job.count);
      g_assert (result != GNUTLS_E_INTERRUPTED);
      session->async = FALSE;

      wocky_tls_job_result_gssize (&session->write_job.job, result);
    }
}

static void
wocky_tls_job_start (WockyTLSJob             *job,
                     gpointer             source_object,
                     gint                 io_priority,
                     GCancellable        *cancellable,
                     GAsyncReadyCallback  callback,
                     gpointer             user_data,
                     gpointer             source_tag)
{
  g_assert (job->active == FALSE);
  g_assert (job->cancellable == NULL);

  /* this is always a circular reference, so it will keep the
   * session alive for as long as the job is running.
   */
  job->source_object = g_object_ref (source_object);

  job->io_priority = io_priority;
  if (cancellable != NULL)
    job->cancellable = g_object_ref (cancellable);
  job->callback = callback;
  job->user_data = user_data;
  job->source_tag = source_tag;
  job->error = NULL;
  job->active = TRUE;
}

WockyTLSConnection *
wocky_tls_session_handshake (WockyTLSSession   *session,
                             GCancellable  *cancellable,
                             GError       **error)
{
  gint result;

  DEBUG ("sync job handshake");
  session->error = NULL;
  session->cancellable = cancellable;
  result = gnutls_handshake (session->session);
  g_assert (result != GNUTLS_E_INTERRUPTED);
  g_assert (result != GNUTLS_E_AGAIN);
  session->cancellable = NULL;

  if (tls_debug_level >= DEBUG_HANDSHAKE_LEVEL)
    DEBUG ("sync job handshake: %d %s", result, error_to_string (result));

  if (session->error != NULL)
    {
      g_assert (result == GNUTLS_E_PULL_ERROR ||
                result == GNUTLS_E_PUSH_ERROR);

      g_propagate_error (error, session->error);
      return NULL;
    }
  else if (wocky_tls_set_error (error, result))
    return NULL;

  return g_object_new (WOCKY_TYPE_TLS_CONNECTION, "session", session, NULL);
}

/* ************************************************************************* */
/* adding CA certificates and CRL lists for peer certificate verification    */
typedef int (*add_certfile) (gnutls_certificate_credentials_t res,
                             const char *file,
                             gnutls_x509_crt_fmt_t type);

static void
add_certfiles (gnutls_certificate_credentials cred,
               const gchar *thing,
               add_certfile add)
{
  int n = 0;
  struct stat target;

  DEBUG ("checking %s", thing);

  if (stat (thing, &target) != 0)
    {
      DEBUG ("ca/crl file '%s': stat failed)", thing);
      return;
    }

  if (S_ISDIR (target.st_mode))
    {
      DIR *dir;
      struct dirent *entry;

      if ((dir = opendir (thing)) == NULL)
        return;

      for (entry = readdir (dir); entry != NULL; entry = readdir (dir))
        {
          struct stat file;
          gchar *path = g_build_path ("/", thing, entry->d_name, NULL);

          if ((stat (path, &file) == 0) && S_ISREG (file.st_mode))
            n += add (cred, path, GNUTLS_X509_FMT_PEM);

          g_free (path);
        }

      DEBUG ("+ %s: %d certs from dir", thing, n);
      closedir (dir);
    }
  else if (S_ISREG (target.st_mode))
    {
      n = add (cred, thing, GNUTLS_X509_FMT_PEM);
      DEBUG ("+ %s: %d certs from file", thing, n);
    }
}

void
wocky_tls_session_add_ca (WockyTLSSession *session,
                          const gchar *path)
{
  DEBUG ("adding CA CERT path '%s'", (gchar *) path);
  add_certfiles (session->gnutls_cert_cred, path,
                 gnutls_certificate_set_x509_trust_file);
}

void
wocky_tls_session_add_crl (WockyTLSSession *session,
                           const gchar *path)
{
  DEBUG ("adding CRL path '%s'", (gchar *) path);
  add_certfiles (session->gnutls_cert_cred, path,
                 gnutls_certificate_set_x509_crl_file);
}
/* ************************************************************************* */

void
wocky_tls_session_handshake_async (WockyTLSSession         *session,
                                   gint                 io_priority,
                                   GCancellable        *cancellable,
                                   GAsyncReadyCallback  callback,
                                   gpointer             user_data)
{
  wocky_tls_job_start (&session->handshake_job.job, session,
                       io_priority, cancellable, callback, user_data,
                       wocky_tls_session_handshake_async);
  wocky_tls_session_try_operation (session, 0);
}

WockyTLSConnection *
wocky_tls_session_handshake_finish (WockyTLSSession   *session,
                                    GAsyncResult  *result,
                                    GError       **error)
{
  GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (result);

  {
    GObject *source_object;

    source_object = g_async_result_get_source_object (result);
    g_object_unref (source_object);
    g_return_val_if_fail (G_OBJECT (session) == source_object, NULL);
  }

  g_return_val_if_fail (wocky_tls_session_handshake_async ==
                        g_simple_async_result_get_source_tag (simple), NULL);

  if (g_simple_async_result_propagate_error (simple, error))
    return NULL;

  DEBUG ("connection OK");
  return g_object_new (WOCKY_TYPE_TLS_CONNECTION, "session", session, NULL);
}

GPtrArray *
wocky_tls_session_get_peers_certificate (WockyTLSSession *session,
    WockyTLSCertType *type)
{
  guint idx;
  guint n_peers;
  const gnutls_datum_t *peers = NULL;
  GPtrArray *certificates;

  peers = gnutls_certificate_get_peers (session->session, &n_peers);

  if (peers == NULL)
    return NULL;

  certificates =
    g_ptr_array_new_with_free_func ((GDestroyNotify) g_array_unref);

  for (idx = 0; idx < n_peers; idx++)
    {
      GArray *cert = g_array_sized_new (TRUE, TRUE, sizeof (guchar),
          peers[idx].size);
      g_array_append_vals (cert, peers[idx].data, peers[idx].size);
      g_ptr_array_add (certificates, cert);
    }

  if (type != NULL)
    {
      switch (gnutls_certificate_type_get (session->session))
        {
        case GNUTLS_CRT_X509:
          *type = WOCKY_TLS_CERT_TYPE_X509;
          break;
        case GNUTLS_CRT_OPENPGP:
          *type = WOCKY_TLS_CERT_TYPE_OPENPGP;
          break;
        default:
          *type = WOCKY_TLS_CERT_TYPE_NONE;
          break;
        }
    }

  return certificates;
}

int
wocky_tls_session_verify_peer (WockyTLSSession    *session,
                               const gchar        *peername,
                               GStrv               extra_identities,
                               WockyTLSVerificationLevel level,
                               WockyTLSCertStatus *status)
{
  int rval = -1;
  guint _stat = 0;
  gboolean peer_name_ok = TRUE;
  gnutls_certificate_verify_flags check;

  /* list gnutls cert error conditions in descending order of noteworthiness *
   * and map them to wocky cert error conditions                             */
  static const struct
  {
    gnutls_certificate_status_t gnutls;
    WockyTLSCertStatus wocky;
  } status_map[] =
    { { GNUTLS_CERT_REVOKED,            WOCKY_TLS_CERT_REVOKED             },
      { GNUTLS_CERT_NOT_ACTIVATED,      WOCKY_TLS_CERT_NOT_ACTIVE          },
      { GNUTLS_CERT_EXPIRED,            WOCKY_TLS_CERT_EXPIRED             },
      { GNUTLS_CERT_SIGNER_NOT_FOUND,   WOCKY_TLS_CERT_SIGNER_UNKNOWN      },
      { GNUTLS_CERT_SIGNER_NOT_CA,      WOCKY_TLS_CERT_SIGNER_UNAUTHORISED },
      { GNUTLS_CERT_INSECURE_ALGORITHM, WOCKY_TLS_CERT_INSECURE            },
      { GNUTLS_CERT_INVALID,            WOCKY_TLS_CERT_INVALID             },
      { ~((long) 0),                    WOCKY_TLS_CERT_UNKNOWN_ERROR       },
      { 0,                              WOCKY_TLS_CERT_OK                  } };

  g_assert (status != NULL);
  *status = WOCKY_TLS_CERT_OK;

  switch (level)
    {
    case WOCKY_TLS_VERIFY_STRICT:
      check = VERIFY_STRICT;
      break;
    case WOCKY_TLS_VERIFY_NORMAL:
      check = VERIFY_NORMAL;
      break;
    case WOCKY_TLS_VERIFY_LENIENT:
      check = VERIFY_LENIENT;
      break;
    default:
      g_warn_if_reached ();
      check = VERIFY_STRICT;
      break;
    }

  DEBUG ("setting gnutls verify flags level to: %s",
      wocky_enum_to_nick (WOCKY_TYPE_TLS_VERIFICATION_LEVEL, level));
  gnutls_certificate_set_verify_flags (session->gnutls_cert_cred, check);
  rval = gnutls_certificate_verify_peers2 (session->session, &_stat);

  if (rval != GNUTLS_E_SUCCESS)
    {
      switch (rval)
        {
        case GNUTLS_E_NO_CERTIFICATE_FOUND:
        case GNUTLS_E_INVALID_REQUEST:
          *status = WOCKY_TLS_CERT_NO_CERTIFICATE;
          break;
        case GNUTLS_E_INSUFFICIENT_CREDENTIALS:
          *status = WOCKY_TLS_CERT_INSECURE;
          break;
        case GNUTLS_E_CONSTRAINT_ERROR:
          *status = WOCKY_TLS_CERT_MAYBE_DOS;
          break;
        case GNUTLS_E_MEMORY_ERROR:
          *status = WOCKY_TLS_CERT_INTERNAL_ERROR;
          break;
        default:
          *status = WOCKY_TLS_CERT_UNKNOWN_ERROR;
	}

      return rval;
    }

  /* if we get this far, we have a structurally valid certificate *
   * signed by _someone_: check the hostname matches the peername */
  if (peername != NULL || extra_identities != NULL)
    {
      const gnutls_datum_t *peers;
      guint n_peers;
      gnutls_x509_crt_t x509;
      gnutls_openpgp_crt_t opgp;

      /* we know these ops must succeed, or verify_peers2 would have *
       * failed before we got here: We just need to duplicate a bit  *
       * of what it does:                                            */
      peers = gnutls_certificate_get_peers (session->session, &n_peers);

      switch (gnutls_certificate_type_get (session->session))
        {
        case GNUTLS_CRT_X509:
          DEBUG ("checking X509 cert");
          if ((rval = gnutls_x509_crt_init (&x509)) == GNUTLS_E_SUCCESS)
            {
              gnutls_x509_crt_import (x509, &peers[0], GNUTLS_X509_FMT_DER);

              if (peername != NULL)
                {
                  rval = gnutls_x509_crt_check_hostname (x509, peername);
                  DEBUG ("gnutls_x509_crt_check_hostname: %s -> %d",
                      peername, rval);
                }
              else
                {
                  rval = 0;
                }

              if (rval == 0 && extra_identities != NULL)
                {
                  gint i;

                  for (i = 0; extra_identities[i] != NULL; i++)
                    {
                      rval = gnutls_x509_crt_check_hostname (x509,
                          extra_identities[i]);
                      DEBUG ("gnutls_x509_crt_check_hostname: %s -> %d",
                          extra_identities[i], rval);

                      if (rval != 0)
                        break;
                    }
                }

              rval = (rval == 0) ? -1 : GNUTLS_E_SUCCESS;

              gnutls_x509_crt_deinit (x509);
            }
          break;
        case GNUTLS_CRT_OPENPGP:
          DEBUG ("checking PGP cert");
          if ((rval = gnutls_openpgp_crt_init (&opgp)) == GNUTLS_E_SUCCESS)
            {
              gnutls_openpgp_crt_import (opgp, &peers[0], GNUTLS_OPENPGP_FMT_RAW);
              rval = gnutls_openpgp_crt_check_hostname (opgp, peername);
              DEBUG ("gnutls_openpgp_crt_check_hostname: %s -> %d", peername, rval);

              if (peername != NULL)
                {
                  rval = gnutls_openpgp_crt_check_hostname (opgp, peername);
                  DEBUG ("gnutls_openpgp_crt_check_hostname: %s -> %d",
                      peername, rval);
                }
              else
                {
                  rval = 0;
                }

              if (rval == 0 && extra_identities != NULL)
                {
                  gint i;

                  for (i = 0; extra_identities[i] != NULL; i++)
                    {
                      rval = gnutls_openpgp_crt_check_hostname (opgp,
                          extra_identities[i]);
                      DEBUG ("gnutls_openpgp_crt_check_hostname: %s -> %d",
                          extra_identities[i], rval);

                      if (rval != 0)
                        break;
                    }
                }

              rval = (rval == 0) ? -1 : GNUTLS_E_SUCCESS;

              gnutls_openpgp_crt_deinit (opgp);
            }
          break;
        default:
          /* theoretically, this can't happen if ...verify_peers2 is working: */
          DEBUG ("unknown cert type!");
          rval = GNUTLS_E_INVALID_REQUEST;
        }

      peer_name_ok = (rval == GNUTLS_E_SUCCESS);
    }

  DEBUG ("peer_name_ok: %d", peer_name_ok );

  /* if the hostname didn't match, we can just bail out with an error here *
   * otherwise we need to figure out which error (if any) our verification *
   * call failed with:                                                     */
  if (!peer_name_ok)
    *status = WOCKY_TLS_CERT_NAME_MISMATCH;
  else
    { /* Gnutls cert checking can return multiple errors bitwise &ed together *
       * but we are realy only interested in the "most important" error:      */
      int x;
      *status = WOCKY_TLS_CERT_OK;
      for (x = 0; status_map[x].gnutls != 0; x++)
        {
          DEBUG ("checking gnutls error %d", status_map[x].gnutls);
          if (_stat & status_map[x].gnutls)
            {
              DEBUG ("gnutls error %d set", status_map[x].gnutls);
              *status = status_map[x].wocky;
              rval = GNUTLS_E_CERTIFICATE_ERROR;
              break;
            }
        }
    }

  return rval;
}

static gssize
wocky_tls_input_stream_read (GInputStream  *stream,
                             void          *buffer,
                             gsize          count,
                             GCancellable  *cancellable,
                             GError       **error)
{
  WockyTLSSession *session = WOCKY_TLS_INPUT_STREAM (stream)->session;
  gssize result;

  session->cancellable = cancellable;
  result = gnutls_record_recv (session->session, buffer, count);
  g_assert (result != GNUTLS_E_INTERRUPTED);
  g_assert (result != GNUTLS_E_AGAIN);
  session->cancellable = NULL;

  if (session->error != NULL)
    {
      g_assert (result == GNUTLS_E_PULL_ERROR);
      g_propagate_error (error, session->error);
      return -1;
    }
  else if (wocky_tls_set_error (error, result))
    return -1;

  return result;
}

static void
wocky_tls_input_stream_read_async (GInputStream        *stream,
                                   void                *buffer,
                                   gsize                count,
                                   gint                 io_priority,
                                   GCancellable        *cancellable,
                                   GAsyncReadyCallback  callback,
                                   gpointer             user_data)
{
  WockyTLSSession *session = WOCKY_TLS_INPUT_STREAM (stream)->session;

  wocky_tls_job_start (&session->read_job.job, stream,
                       io_priority, cancellable, callback, user_data,
                       wocky_tls_input_stream_read_async);

  session->read_job.buffer = buffer;
  session->read_job.count = count;

  wocky_tls_session_try_operation (session, WOCKY_TLS_OP_READ);
}

static gssize
wocky_tls_input_stream_read_finish (GInputStream  *stream,
                                    GAsyncResult  *result,
                                    GError       **error)
{
  GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (result);

  {
    GObject *source_object;

    source_object = g_async_result_get_source_object (result);
    g_object_unref (source_object);
    g_return_val_if_fail (G_OBJECT (stream) == source_object, -1);
  }

  g_return_val_if_fail (wocky_tls_input_stream_read_async ==
                        g_simple_async_result_get_source_tag (simple), -1);

  if (g_simple_async_result_propagate_error (simple, error))
    return -1;

  return g_simple_async_result_get_op_res_gssize (simple);
}

static gssize
wocky_tls_output_stream_write (GOutputStream  *stream,
                               const void     *buffer,
                               gsize           count,
                               GCancellable   *cancellable,
                               GError        **error)
{
  WockyTLSSession *session = WOCKY_TLS_OUTPUT_STREAM (stream)->session;
  gssize result;

  session->cancellable = cancellable;
  result = gnutls_record_send (session->session, buffer, count);
  g_assert (result != GNUTLS_E_INTERRUPTED);
  g_assert (result != GNUTLS_E_AGAIN);
  session->cancellable = NULL;

  if (session->error != NULL)
    {
      g_assert (result == GNUTLS_E_PUSH_ERROR);
      g_propagate_error (error, session->error);
      return -1;
    }
  else if (wocky_tls_set_error (error, result))
    return -1;

  return result;
}

static void
wocky_tls_output_stream_write_async (GOutputStream       *stream,
                                     const void          *buffer,
                                     gsize                count,
                                     gint                 io_priority,
                                     GCancellable        *cancellable,
                                     GAsyncReadyCallback  callback,
                                     gpointer             user_data)
{
  WockyTLSSession *session = WOCKY_TLS_OUTPUT_STREAM (stream)->session;

  wocky_tls_job_start (&session->write_job.job, stream,
                   io_priority, cancellable, callback, user_data,
                   wocky_tls_output_stream_write_async);

  session->write_job.buffer = buffer;
  session->write_job.count = count;

  wocky_tls_session_try_operation (session, WOCKY_TLS_OP_WRITE);
}

static gssize
wocky_tls_output_stream_write_finish (GOutputStream   *stream,
                                      GAsyncResult   *result,
                                      GError        **error)
{
  GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (result);

  {
    GObject *source_object;

    source_object = g_async_result_get_source_object (result);
    g_object_unref (source_object);
    g_return_val_if_fail (G_OBJECT (stream) == source_object, -1);
  }

  g_return_val_if_fail (wocky_tls_output_stream_write_async ==
                        g_simple_async_result_get_source_tag (simple), -1);

  if (g_simple_async_result_propagate_error (simple, error))
    return -1;

  return g_simple_async_result_get_op_res_gssize (simple);
}

static void
wocky_tls_output_stream_init (WockyTLSOutputStream *stream)
{
}

static void
wocky_tls_input_stream_init (WockyTLSInputStream *stream)
{
}

static void
wocky_tls_output_stream_set_property (GObject *object, guint prop_id,
                                      const GValue *value, GParamSpec *pspec)
{
  WockyTLSOutputStream *stream = WOCKY_TLS_OUTPUT_STREAM (object);

  switch (prop_id)
    {
     case PROP_C_SESSION:
      stream->session = g_value_dup_object (value);
      break;

     default:
      g_assert_not_reached ();
    }
}

static void
wocky_tls_output_stream_constructed (GObject *object)
{
  WockyTLSOutputStream *stream = WOCKY_TLS_OUTPUT_STREAM (object);

  g_assert (stream->session);
}

static void
wocky_tls_output_stream_finalize (GObject *object)
{
  WockyTLSOutputStream *stream = WOCKY_TLS_OUTPUT_STREAM (object);

  g_object_unref (stream->session);

  G_OBJECT_CLASS (wocky_tls_output_stream_parent_class)
    ->finalize (object);
}

static void
wocky_tls_output_stream_class_init (GOutputStreamClass *class)
{
  GObjectClass *obj_class = G_OBJECT_CLASS (class);

  class->write_fn = wocky_tls_output_stream_write;
  class->write_async = wocky_tls_output_stream_write_async;
  class->write_finish = wocky_tls_output_stream_write_finish;
  obj_class->set_property = wocky_tls_output_stream_set_property;
  obj_class->constructed = wocky_tls_output_stream_constructed;
  obj_class->finalize = wocky_tls_output_stream_finalize;

  g_object_class_install_property (obj_class, PROP_O_SESSION,
    g_param_spec_object ("session", "TLS session",
                         "the TLS session object for this stream",
                         WOCKY_TYPE_TLS_SESSION, G_PARAM_WRITABLE |
                         G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_NAME |
                         G_PARAM_STATIC_NICK | G_PARAM_STATIC_BLURB));
}

static void
wocky_tls_input_stream_set_property (GObject *object, guint prop_id,
                                     const GValue *value, GParamSpec *pspec)
{
  WockyTLSInputStream *stream = WOCKY_TLS_INPUT_STREAM (object);

  switch (prop_id)
    {
     case PROP_C_SESSION:
      stream->session = g_value_dup_object (value);
      break;

     default:
      g_assert_not_reached ();
    }
}

static void
wocky_tls_input_stream_constructed (GObject *object)
{
  WockyTLSInputStream *stream = WOCKY_TLS_INPUT_STREAM (object);

  g_assert (stream->session);
}

static void
wocky_tls_input_stream_finalize (GObject *object)
{
  WockyTLSInputStream *stream = WOCKY_TLS_INPUT_STREAM (object);

  g_object_unref (stream->session);

  G_OBJECT_CLASS (wocky_tls_input_stream_parent_class)
    ->finalize (object);
}

static void
wocky_tls_input_stream_class_init (GInputStreamClass *class)
{
  GObjectClass *obj_class = G_OBJECT_CLASS (class);

  class->read_fn = wocky_tls_input_stream_read;
  class->read_async = wocky_tls_input_stream_read_async;
  class->read_finish = wocky_tls_input_stream_read_finish;
  obj_class->set_property = wocky_tls_input_stream_set_property;
  obj_class->constructed = wocky_tls_input_stream_constructed;
  obj_class->finalize = wocky_tls_input_stream_finalize;

  g_object_class_install_property (obj_class, PROP_I_SESSION,
    g_param_spec_object ("session", "TLS session",
                         "the TLS session object for this stream",
                         WOCKY_TYPE_TLS_SESSION, G_PARAM_WRITABLE |
                         G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_NAME |
                         G_PARAM_STATIC_NICK | G_PARAM_STATIC_BLURB));
}

static void
wocky_tls_connection_init (WockyTLSConnection *connection)
{
}

static void
wocky_tls_session_read_ready (GObject      *object,
                              GAsyncResult *result,
                              gpointer      user_data)
{
  WockyTLSSession *session = WOCKY_TLS_SESSION (user_data);

  g_assert (session->read_op.state == WOCKY_TLS_OP_STATE_ACTIVE);

  session->read_op.result =
    g_input_stream_read_finish (G_INPUT_STREAM (object), result,
                                &session->read_op.error);
  session->read_op.state = WOCKY_TLS_OP_STATE_DONE;

  /* don't recurse if the async handler is already running */
  if (!session->async)
    wocky_tls_session_try_operation (session, WOCKY_TLS_OP_READ);
}

static void
wocky_tls_session_write_ready (GObject      *object,
                               GAsyncResult *result,
                               gpointer      user_data)
{
  WockyTLSSession *session = WOCKY_TLS_SESSION (user_data);
  gssize ret;

  g_assert (session->write_op.state == WOCKY_TLS_OP_STATE_ACTIVE);

  ret = g_output_stream_write_finish (G_OUTPUT_STREAM (object), result,
                                  &session->write_op.error);
  if (ret > 0)
    {
      session->write_op.result += ret;

      if (session->write_op.result < session->write_op.requested)
        {
          GOutputStream *stream;
          WockyTLSJob *active_job;

          stream = g_io_stream_get_output_stream (session->stream);

          if (session->handshake_job.job.active)
              active_job = &session->handshake_job.job;
          else
              active_job = &session->write_job.job;

          g_output_stream_write_async (stream,
            session->write_op.buffer + session->write_op.result,
            session->write_op.requested - session->write_op.result,
            active_job->io_priority,
            active_job->cancellable,
            wocky_tls_session_write_ready,
            session);
          return;
        }
    }
  else
    {
      /* Error or EOF, we're done */
      session->write_op.result = ret;
    }

  session->write_op.state = WOCKY_TLS_OP_STATE_DONE;

  /* don't recurse if the async handler is already running */
  if (!session->async)
    wocky_tls_session_try_operation (session, WOCKY_TLS_OP_WRITE);
}

static gssize
wocky_tls_session_push_func (gpointer    user_data,
                             const void *buffer,
                             gsize       count)
{
  WockyTLSSession *session = WOCKY_TLS_SESSION (user_data);
  GOutputStream *stream;

  stream = g_io_stream_get_output_stream (session->stream);

  if (session->async)
    {
      WockyTLSJob *active_job;

      g_assert (session->handshake_job.job.active ||
                session->write_job.job.active);

      if (session->handshake_job.job.active)
        active_job = &session->handshake_job.job;
      else
        active_job = &session->write_job.job;

      g_assert (active_job->active);

      if (session->write_op.state == WOCKY_TLS_OP_STATE_IDLE)
        {
          session->write_op.state = WOCKY_TLS_OP_STATE_ACTIVE;
          session->write_op.buffer = g_memdup (buffer, count);
          session->write_op.requested = count;
          session->write_op.error = NULL;
          session->write_op.result = 0;

          g_output_stream_write_async (stream,
                                       session->write_op.buffer,
                                       session->write_op.requested,
                                       active_job->io_priority,
                                       active_job->cancellable,
                                       wocky_tls_session_write_ready,
                                       session);

          if G_UNLIKELY (session->write_op.state != WOCKY_TLS_OP_STATE_ACTIVE)
            g_warning ("The underlying stream '%s' used by the WockyTLSSession "
                       "called the GAsyncResultCallback recursively.  This "
                       "is an error in the underlying implementation: in "
                       "some cases it may lead to unbounded recursion.  "
                       "Result callbacks should always be dispatched from "
                       "the mainloop.",
                       G_OBJECT_TYPE_NAME (stream));
        }

      g_assert (session->write_op.state != WOCKY_TLS_OP_STATE_IDLE);
      g_assert_cmpint (session->write_op.requested, ==, count);
      g_assert (memcmp (session->write_op.buffer, buffer, count) == 0);

      if (session->write_op.state == WOCKY_TLS_OP_STATE_DONE)
        {
          session->write_op.state = WOCKY_TLS_OP_STATE_IDLE;
          g_free (session->write_op.buffer);

          if (session->write_op.result < 0)
            {
              active_job->error = session->write_op.error;
              gnutls_transport_set_errno (session->session, EIO);

              return -1;
            }
          else
            {
              g_assert_cmpint (session->write_op.result, <=, count);

              return session->write_op.result;
            }
        }

      gnutls_transport_set_errno (session->session, EAGAIN);

      return -1;
    }
  else
    {
      gssize result;

      result = g_output_stream_write (stream, buffer, count,
                                      session->cancellable,
                                      &session->error);

      if (result < 0)
        gnutls_transport_set_errno (session->session, EIO);

      return result;
    }
}

static gssize
wocky_tls_session_pull_func (gpointer  user_data,
                             void     *buffer,
                             gsize     count)
{
  WockyTLSSession *session = WOCKY_TLS_SESSION (user_data);
  GInputStream *stream;

  stream = g_io_stream_get_input_stream (session->stream);

  if (session->async)
    {
      WockyTLSJob *active_job;

      g_assert (session->handshake_job.job.active ||
                session->read_job.job.active);

      if (session->handshake_job.job.active)
        active_job = &session->handshake_job.job;
      else
        active_job = &session->read_job.job;

      g_assert (active_job->active);

      if (session->read_op.state == WOCKY_TLS_OP_STATE_IDLE)
        {
          session->read_op.state = WOCKY_TLS_OP_STATE_ACTIVE;
          session->read_op.buffer = g_malloc (count);
          session->read_op.requested = count;
          session->read_op.error = NULL;

          g_input_stream_read_async (stream,
                                     session->read_op.buffer,
                                     session->read_op.requested,
                                     active_job->io_priority,
                                     active_job->cancellable,
                                     wocky_tls_session_read_ready,
                                     session);

          if G_UNLIKELY (session->read_op.state != WOCKY_TLS_OP_STATE_ACTIVE)
            g_warning ("The underlying stream '%s' used by the WockyTLSSession "
                       "called the GAsyncResultCallback recursively.  This "
                       "is an error in the underlying implementation: in "
                       "some cases it may lead to unbounded recursion.  "
                       "Result callbacks should always be dispatched from "
                       "the mainloop.",
                       G_OBJECT_TYPE_NAME (stream));
        }

      g_assert (session->read_op.state != WOCKY_TLS_OP_STATE_IDLE);
      g_assert_cmpint (session->read_op.requested, ==, count);

      if (session->read_op.state == WOCKY_TLS_OP_STATE_DONE)
        {
          session->read_op.state = WOCKY_TLS_OP_STATE_IDLE;

          if (session->read_op.result < 0)
            {
              g_free (session->read_op.buffer);
              session->read_op.buffer = NULL;
              active_job->error = session->read_op.error;
              gnutls_transport_set_errno (session->session, EIO);

              return -1;
            }
          else
            {
              g_assert_cmpint (session->read_op.result, <=, count);

              memcpy (buffer,
                      session->read_op.buffer,
                      session->read_op.result);
              g_free (session->read_op.buffer);
              session->read_op.buffer = NULL;

              return session->read_op.result;
            }
        }

      gnutls_transport_set_errno (session->session, EAGAIN);

      return -1;
    }
  else
    {
      gssize result;

      result = g_input_stream_read (stream, buffer, count,
                                    session->cancellable,
                                    &session->error);
      if (result < 0)
        gnutls_transport_set_errno (session->session, EIO);

      return result;
    }
}

static void
tls_debug (int level,
    const char *msg)
{
  DEBUG ("[%d] [%02d] %s", getpid(), level, msg);
}

static void
wocky_tls_session_init (WockyTLSSession *session)
{
  const char *level;
  guint lvl = 0;
  static gsize initialised;

  if G_UNLIKELY (g_once_init_enter (&initialised))
    {
      gnutls_global_init ();
      gnutls_global_set_log_function (tls_debug);
      g_once_init_leave (&initialised, 1);
    }

  if ((level = getenv ("WOCKY_TLS_DEBUG_LEVEL")) != NULL)
    lvl = atoi (level);

  tls_debug_level = lvl;
  gnutls_global_set_log_level (lvl);
}

static void
wocky_tls_session_set_property (GObject *object, guint prop_id,
                                const GValue *value, GParamSpec *pspec)
{
  WockyTLSSession *session = WOCKY_TLS_SESSION (object);

  switch (prop_id)
    {
     case PROP_S_STREAM:
      session->stream = g_value_dup_object (value);
      break;
    case PROP_S_SERVER:
      session->server = g_value_get_boolean (value);
      break;
    case PROP_S_DHBITS:
      session->dh_bits = g_value_get_uint (value);
      break;
    case PROP_S_KEYFILE:
      session->key_file = g_value_dup_string (value);
      break;
    case PROP_S_CERTFILE:
      session->cert_file = g_value_dup_string (value);
      break;
     default:
      g_assert_not_reached ();
    }
}

static const char *
tls_options (void)
{
  const char *options = getenv ("WOCKY_GNUTLS_OPTIONS");
  return (options != NULL && *options != '\0') ? options : DEFAULT_TLS_OPTIONS;
}

static void
wocky_tls_session_constructed (GObject *object)
{
  WockyTLSSession *session = WOCKY_TLS_SESSION (object);

  gboolean server = session->server;
  gint code;
  const gchar *opt = tls_options ();
  const gchar *pos = NULL;

  /* gnutls_handshake_set_private_extensions (session->session, 1); */
  gnutls_certificate_allocate_credentials (&(session->gnutls_cert_cred));

  /* I think this all needs to be done per connection: conceivably
     the DH parameters could be moved to the global section above,
     but IANA cryptographer */
  if (server)
    {
      gnutls_dh_params_t *dhp;

      if ((session->key_file != NULL) && (session->cert_file != NULL))
        {
          DEBUG ("cert/key pair: %s/%s", session->cert_file, session->key_file);
          gnutls_certificate_set_x509_key_file (session->gnutls_cert_cred,
                                                session->cert_file,
                                                session->key_file,
                                                GNUTLS_X509_FMT_PEM);
        }

      switch (session->dh_bits)
        {
        case 768:
          dhp = &dh_0768;
          break;
        case 1024:
          dhp = &dh_1024;
          break;
        case 2048:
          dhp = &dh_2048;
          break;
        case 3072:
          dhp = &dh_3072;
          break;
        case 4096:
          dhp = &dh_4096;
          break;
        default:
          dhp = &dh_1024;
          break;
        }

      if (*dhp == NULL)
        {
          DEBUG ("Initialising DH parameters (%d bits)", session->dh_bits);
          gnutls_dh_params_init (dhp);
          gnutls_dh_params_generate2 (*dhp, session->dh_bits);
        }

      session->dh_params = *dhp;
      gnutls_certificate_set_dh_params (session->gnutls_cert_cred, *dhp);
      gnutls_init (&session->session, GNUTLS_SERVER);
    }
  else
    gnutls_init (&session->session, GNUTLS_CLIENT);

  code = gnutls_priority_set_direct (session->session, opt, &pos);
  if (code != GNUTLS_E_SUCCESS)
    {
      DEBUG ("could not set priority string: %s", error_to_string (code));
      DEBUG ("    '%s'", opt);
      if (pos >= opt)
        DEBUG ("     %*s^", (int) (pos - opt), "");
    }
  else
    {
      DEBUG ("priority set to: '%s'", opt);
    }

  code = gnutls_credentials_set (session->session,
                                 GNUTLS_CRD_CERTIFICATE,
                                 session->gnutls_cert_cred);
  if (code != GNUTLS_E_SUCCESS)
    DEBUG ("could not set credentials: %s", error_to_string (code));

  gnutls_transport_set_push_function (session->session,
                                      wocky_tls_session_push_func);
  gnutls_transport_set_pull_function (session->session,
                                      wocky_tls_session_pull_func);
  gnutls_transport_set_ptr (session->session, session);

  g_assert (session->stream);
}

static void
wocky_tls_session_finalize (GObject *object)
{
  WockyTLSSession *session = WOCKY_TLS_SESSION (object);

  gnutls_deinit (session->session);
  gnutls_certificate_free_credentials (session->gnutls_cert_cred);
  g_object_unref (session->stream);

  G_OBJECT_CLASS (wocky_tls_session_parent_class)
    ->finalize (object);
}

static void
wocky_tls_session_dispose (GObject *object)
{
  WockyTLSSession *session = WOCKY_TLS_SESSION (object);

  g_free (session->key_file);
  session->key_file = NULL;

  g_free (session->cert_file);
  session->cert_file = NULL;

  g_free (session->read_op.buffer);
  session->read_op.buffer = NULL;

  G_OBJECT_CLASS (wocky_tls_session_parent_class)->dispose (object);
}

static void
wocky_tls_session_class_init (GObjectClass *class)
{
  class->set_property = wocky_tls_session_set_property;
  class->constructed = wocky_tls_session_constructed;
  class->finalize = wocky_tls_session_finalize;
  class->dispose = wocky_tls_session_dispose;

  g_object_class_install_property (class, PROP_S_STREAM,
    g_param_spec_object ("base-stream", "base stream",
                         "the stream that TLS communicates over",
                         G_TYPE_IO_STREAM, G_PARAM_WRITABLE |
                         G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_NAME |
                         G_PARAM_STATIC_NICK | G_PARAM_STATIC_BLURB));

  g_object_class_install_property (class, PROP_S_SERVER,
    g_param_spec_boolean ("server", "server",
                          "whether this is a server",
                          FALSE, G_PARAM_WRITABLE |
                          G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_NAME |
                          G_PARAM_STATIC_NICK | G_PARAM_STATIC_BLURB));

  g_object_class_install_property (class, PROP_S_DHBITS,
    g_param_spec_uint ("dh-bits", "Diffie-Hellman bits",
                       "Diffie-Hellmann bits: 768, 1024, 2048, 3072 0r 4096",
                       768, 4096, 1024, G_PARAM_WRITABLE |
                       G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_NAME |
                       G_PARAM_STATIC_NICK | G_PARAM_STATIC_BLURB));

  g_object_class_install_property (class, PROP_S_KEYFILE,
    g_param_spec_string ("x509-key", "x509 key",
                         "x509 PEM key file",
                         NULL, G_PARAM_WRITABLE |
                         G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_NAME |
                         G_PARAM_STATIC_NICK | G_PARAM_STATIC_BLURB));

  g_object_class_install_property (class, PROP_S_CERTFILE,
    g_param_spec_string ("x509-cert", "x509 certificate",
                         "x509 PEM certificate file",
                         NULL, G_PARAM_WRITABLE |
                         G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_NAME |
                         G_PARAM_STATIC_NICK | G_PARAM_STATIC_BLURB));
}

static void
wocky_tls_connection_set_property (GObject *object, guint prop_id,
                                   const GValue *value, GParamSpec *pspec)
{
  WockyTLSConnection *connection = WOCKY_TLS_CONNECTION (object);

  switch (prop_id)
    {
     case PROP_C_SESSION:
      connection->session = g_value_dup_object (value);
      break;

     default:
      g_assert_not_reached ();
    }
}

static gboolean
wocky_tls_connection_close (GIOStream *stream,
  GCancellable *cancellable,
  GError **error)
{
  WockyTLSConnection *connection = WOCKY_TLS_CONNECTION (stream);

  return g_io_stream_close (connection->session->stream, cancellable, error);
}

static GInputStream *
wocky_tls_connection_get_input_stream (GIOStream *io_stream)
{
  WockyTLSConnection *connection = WOCKY_TLS_CONNECTION (io_stream);

  if (connection->input == NULL)
    connection->input = g_object_new (WOCKY_TYPE_TLS_INPUT_STREAM,
                                      "session", connection->session,
                                      NULL);

  return (GInputStream *)connection->input;
}

static GOutputStream *
wocky_tls_connection_get_output_stream (GIOStream *io_stream)
{
  WockyTLSConnection *connection = WOCKY_TLS_CONNECTION (io_stream);

  if (connection->output == NULL)
    connection->output = g_object_new (WOCKY_TYPE_TLS_OUTPUT_STREAM,
                                       "session", connection->session,
                                       NULL);

  return (GOutputStream *)connection->output;
}

static void
wocky_tls_connection_get_property (GObject *object, guint prop_id,
                               GValue *value, GParamSpec *pspec)
{
  switch (prop_id)
    {
     default:
      g_assert_not_reached ();
    }
}

static void
wocky_tls_connection_constructed (GObject *object)
{
  WockyTLSConnection *connection = WOCKY_TLS_CONNECTION (object);

  g_assert (connection->session);
}

static void
wocky_tls_connection_finalize (GObject *object)
{
  WockyTLSConnection *connection = WOCKY_TLS_CONNECTION (object);

  g_object_unref (connection->session);

  if (connection->input != NULL)
    g_object_unref (connection->input);

  if (connection->output != NULL)
    g_object_unref (connection->output);

  G_OBJECT_CLASS (wocky_tls_connection_parent_class)
    ->finalize (object);
}

static void
wocky_tls_connection_class_init (WockyTLSConnectionClass *class)
{
  GObjectClass *gobject_class = G_OBJECT_CLASS (class);
  GIOStreamClass *stream_class = G_IO_STREAM_CLASS (class);

  gobject_class->get_property = wocky_tls_connection_get_property;
  gobject_class->set_property = wocky_tls_connection_set_property;
  gobject_class->constructed = wocky_tls_connection_constructed;
  gobject_class->finalize = wocky_tls_connection_finalize;

  g_object_class_install_property (gobject_class, PROP_C_SESSION,
    g_param_spec_object ("session", "TLS session",
                         "the TLS session object for this connection",
                         WOCKY_TYPE_TLS_SESSION, G_PARAM_WRITABLE |
                         G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS));
  stream_class->get_input_stream = wocky_tls_connection_get_input_stream;
  stream_class->get_output_stream = wocky_tls_connection_get_output_stream;
  stream_class->close_fn = wocky_tls_connection_close;
}

WockyTLSSession *
wocky_tls_session_new (GIOStream *stream)
{
  return g_object_new (WOCKY_TYPE_TLS_SESSION,
                       "base-stream", stream,
                       "server", FALSE, NULL);
}

/**
 * wocky_tls_session_server_new:
 * @stream: a GIOStream on which we expect to receive the client TLS handshake
 * @dhbits: size of the DH parameters (see gnutls for valid settings)
 * @key: the path to the X509 PEM key file
 * @cert: the path to the X509 PEM certificate
 *
 * Create a new TLS server session
 *
 * Returns: a #WockyTLSSession object
 */
WockyTLSSession *
wocky_tls_session_server_new (GIOStream *stream, guint dhbits,
                              const gchar* key, const gchar* cert)
{
  if (dhbits == 0)
    dhbits = 1024;
  return g_object_new (WOCKY_TYPE_TLS_SESSION, "base-stream", stream,
                       "dh-bits", dhbits, "x509-key", key, "x509-cert", cert,
                       "server", TRUE,
                       NULL);
}

/* this file is "borrowed" from an unmerged gnio feature: */
/* Local Variables:                                       */
/* c-file-style: "gnu"                                    */
/* End:                                                   */