summaryrefslogtreecommitdiff
path: root/src/bytestream-socks5.c
blob: 32f0082fdbcead876377d26acc8b587177288d8c (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
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
/*
 * bytestream-socks5.c - Source for GabbleBytestreamSocks5
 * Copyright (C) 2006 Youness Alaoui <kakaroto@kakaroto.homelinux.net>
 * Copyright (C) 2007-2008 Collabora Ltd.
 *
 * This library 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.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "config.h"
#include "bytestream-socks5.h"

#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <netdb.h>
#include <net/if.h>
#include <netinet/in.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>

#ifdef HAVE_GETIFADDRS
 #include <ifaddrs.h>
#endif

#include <dbus/dbus-glib.h>
#include <dbus/dbus-glib-lowlevel.h>
#include <telepathy-glib/interfaces.h>

#include <gibber/gibber-transport.h>
#include <gibber/gibber-tcp-transport.h>
#include <gibber/gibber-listener.h>

#define DEBUG_FLAG GABBLE_DEBUG_BYTESTREAM

#include "base64.h"
#include "bytestream-factory.h"
#include "bytestream-iface.h"
#include "connection.h"
#include "debug.h"
#include "disco.h"
#include "gabble-signals-marshal.h"
#include "namespaces.h"
#include "util.h"

static void
bytestream_iface_init (gpointer g_iface, gpointer iface_data);

G_DEFINE_TYPE_WITH_CODE (GabbleBytestreamSocks5, gabble_bytestream_socks5,
    G_TYPE_OBJECT,
    G_IMPLEMENT_INTERFACE (GABBLE_TYPE_BYTESTREAM_IFACE,
      bytestream_iface_init));

/* properties */
enum
{
  PROP_CONNECTION = 1,
  PROP_PEER_HANDLE,
  PROP_PEER_HANDLE_TYPE,
  PROP_STREAM_ID,
  PROP_STREAM_INIT_ID,
  PROP_PEER_JID,
  PROP_PEER_RESOURCE,
  PROP_STATE,
  PROP_PROTOCOL,
  PROP_SELF_JID,
  LAST_PROPERTY
};

enum _Socks5State
{
  SOCKS5_STATE_INVALID,
  SOCKS5_STATE_TARGET_TRYING_CONNECT,
  SOCKS5_STATE_TARGET_AUTH_REQUEST_SENT,
  SOCKS5_STATE_TARGET_CONNECT_REQUESTED,
  SOCKS5_STATE_CONNECTED,
  SOCKS5_STATE_INITIATOR_OFFER_SENT,
  SOCKS5_STATE_INITIATOR_AWAITING_AUTH_REQUEST,
  SOCKS5_STATE_INITIATOR_AWAITING_COMMAND,
  SOCKS5_STATE_INITIATOR_TRYING_CONNECT,
  SOCKS5_STATE_INITIATOR_AUTH_REQUEST_SENT,
  SOCKS5_STATE_INITIATOR_CONNECT_REQUESTED,
  SOCKS5_STATE_INITIATOR_ACTIVATION_SENT,
  SOCKS5_STATE_ERROR
};

typedef enum _Socks5State Socks5State;

/* SOCKS5 commands */
#define SOCKS5_VERSION     0x05
#define SOCKS5_CMD_CONNECT 0x01
#define SOCKS5_RESERVED    0x00
#define SOCKS5_ATYP_DOMAIN 0x03
#define SOCKS5_STATUS_OK   0x00
#define SOCKS5_AUTH_NONE   0x00

#define SHA1_LENGTH 40
#define SOCKS5_CONNECT_LENGTH (7 + SHA1_LENGTH)
/* VER + CMD/REP + RSV + ATYP + PORT (2) */
#define SOCKS5_MIN_LENGTH 6

#define CONNECT_REPLY_TIMEOUT 30
#define CONNECT_TIMEOUT 10

struct _Streamhost
{
  gchar *jid;
  gchar *host;
  gchar *port;
};
typedef struct _Streamhost Streamhost;

static Streamhost *
streamhost_new (const gchar *jid,
                const gchar *host,
                const gchar *port)
{
  Streamhost *streamhost;

  g_return_val_if_fail (jid != NULL, NULL);
  g_return_val_if_fail (host != NULL, NULL);

  streamhost = g_slice_new0 (Streamhost);
  streamhost->jid = g_strdup (jid);
  streamhost->host = g_strdup (host);
  streamhost->port = g_strdup (port);

  return streamhost;
}

static void
streamhost_free (Streamhost *streamhost)
{
  if (streamhost == NULL)
    return;

  g_free (streamhost->jid);
  g_free (streamhost->host);
  g_free (streamhost->port);
  g_slice_free (Streamhost, streamhost);
}

struct _GabbleBytestreamSocks5Private
{
  GabbleConnection *conn;
  TpHandle peer_handle;
  gchar *stream_id;
  gchar *stream_init_id;
  gchar *peer_resource;
  GabbleBytestreamState bytestream_state;
  gchar *peer_jid;
  gchar *self_full_jid;
  gchar *proxy_jid;
  /* TRUE if the peer of this bytestream is a muc contact */
  gboolean muc_contact;

  /* List of Streamhost */
  GSList *streamhosts;

  /* Connections to streamhosts are async, so we keep the IQ set message
   * around */
  LmMessage *msg_for_acknowledge_connection;

  Socks5State socks5_state;
  GibberTransport *transport;
  gboolean write_blocked;
  gboolean read_blocked;
  GibberListener *listener;
  guint timer_id;

  GString *read_buffer;

  gboolean dispose_has_run;
};

#define GABBLE_BYTESTREAM_SOCKS5_GET_PRIVATE(obj) ((obj)->priv)

static void socks5_connect (GabbleBytestreamSocks5 *self);

static void gabble_bytestream_socks5_close (GabbleBytestreamIface *iface,
    GError *error);

static void socks5_error (GabbleBytestreamSocks5 *self);

static void transport_handler (GibberTransport *transport,
    GibberBuffer *data, gpointer user_data);

static void
gabble_bytestream_socks5_init (GabbleBytestreamSocks5 *self)
{
  GabbleBytestreamSocks5Private *priv = G_TYPE_INSTANCE_GET_PRIVATE (self,
      GABBLE_TYPE_BYTESTREAM_SOCKS5, GabbleBytestreamSocks5Private);

  self->priv = priv;
}

static void
stop_timer (GabbleBytestreamSocks5 *self)
{
  GabbleBytestreamSocks5Private *priv = GABBLE_BYTESTREAM_SOCKS5_GET_PRIVATE (
      self);

  if (priv->timer_id == 0)
    return;

  g_source_remove (priv->timer_id);
  priv->timer_id = 0;
}

static void
gabble_bytestream_socks5_dispose (GObject *object)
{
  GabbleBytestreamSocks5 *self = GABBLE_BYTESTREAM_SOCKS5 (object);
  GabbleBytestreamSocks5Private *priv =
      GABBLE_BYTESTREAM_SOCKS5_GET_PRIVATE (self);
  TpHandleRepoIface *contact_repo = tp_base_connection_get_handles (
      (TpBaseConnection *) priv->conn, TP_HANDLE_TYPE_CONTACT);

  if (priv->dispose_has_run)
    return;

  priv->dispose_has_run = TRUE;

  stop_timer (self);

  tp_handle_unref (contact_repo, priv->peer_handle);

  if (priv->bytestream_state != GABBLE_BYTESTREAM_STATE_CLOSED)
    {
      gabble_bytestream_iface_close (GABBLE_BYTESTREAM_IFACE (self), NULL);
    }

  if (priv->transport != NULL)
    {
      g_object_unref (priv->transport);
      priv->transport = NULL;
    }

  if (priv->listener != NULL)
    {
      g_object_unref (priv->listener);
      priv->listener = NULL;
    }

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

static void
gabble_bytestream_socks5_finalize (GObject *object)
{
  GabbleBytestreamSocks5 *self = GABBLE_BYTESTREAM_SOCKS5 (object);
  GabbleBytestreamSocks5Private *priv =
      GABBLE_BYTESTREAM_SOCKS5_GET_PRIVATE (self);

  g_free (priv->stream_id);
  g_free (priv->stream_init_id);
  g_free (priv->peer_resource);
  g_free (priv->peer_jid);
  g_free (priv->self_full_jid);
  g_free (priv->proxy_jid);

  g_slist_foreach (priv->streamhosts, (GFunc) streamhost_free, NULL);
  g_slist_free (priv->streamhosts);

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

static void
gabble_bytestream_socks5_get_property (GObject *object,
                                       guint property_id,
                                       GValue *value,
                                       GParamSpec *pspec)
{
  GabbleBytestreamSocks5 *self = GABBLE_BYTESTREAM_SOCKS5 (object);
  GabbleBytestreamSocks5Private *priv =
      GABBLE_BYTESTREAM_SOCKS5_GET_PRIVATE (self);

  switch (property_id)
    {
      case PROP_CONNECTION:
        g_value_set_object (value, priv->conn);
        break;
      case PROP_PEER_HANDLE:
        g_value_set_uint (value, priv->peer_handle);
        break;
      case PROP_PEER_HANDLE_TYPE:
        g_value_set_uint (value, TP_HANDLE_TYPE_CONTACT);
        break;
      case PROP_STREAM_ID:
        g_value_set_string (value, priv->stream_id);
        break;
      case PROP_STREAM_INIT_ID:
        g_value_set_string (value, priv->stream_init_id);
        break;
      case PROP_PEER_RESOURCE:
        g_value_set_string (value, priv->peer_resource);
        break;
      case PROP_PEER_JID:
        g_value_set_string (value, priv->peer_jid);
        break;
      case PROP_STATE:
        g_value_set_uint (value, priv->bytestream_state);
        break;
      case PROP_PROTOCOL:
        g_value_set_string (value, NS_BYTESTREAMS);
        break;
      case PROP_SELF_JID:
        g_value_set_string (value, priv->self_full_jid);
        break;
      default:
        G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
        break;
    }
}

static void
gabble_bytestream_socks5_set_property (GObject *object,
                                       guint property_id,
                                       const GValue *value,
                                       GParamSpec *pspec)
{
  GabbleBytestreamSocks5 *self = GABBLE_BYTESTREAM_SOCKS5 (object);
  GabbleBytestreamSocks5Private *priv =
      GABBLE_BYTESTREAM_SOCKS5_GET_PRIVATE (self);

  switch (property_id)
    {
      case PROP_CONNECTION:
        priv->conn = g_value_get_object (value);
        break;
      case PROP_PEER_HANDLE:
        priv->peer_handle = g_value_get_uint (value);
        break;
      case PROP_STREAM_ID:
        g_free (priv->stream_id);
        priv->stream_id = g_value_dup_string (value);
        break;
      case PROP_STREAM_INIT_ID:
        g_free (priv->stream_init_id);
        priv->stream_init_id = g_value_dup_string (value);
        break;
      case PROP_PEER_RESOURCE:
        g_free (priv->peer_resource);
        priv->peer_resource = g_value_dup_string (value);
        break;
      case PROP_STATE:
        if (priv->bytestream_state != g_value_get_uint (value))
            {
              priv->bytestream_state = g_value_get_uint (value);
              g_signal_emit_by_name (object, "state-changed",
                  priv->bytestream_state);
            }
        break;
      case PROP_SELF_JID:
        g_free (priv->self_full_jid);
        priv->self_full_jid = g_value_dup_string (value);
        break;
      default:
        G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
        break;
    }
}

static GObject *
gabble_bytestream_socks5_constructor (GType type,
                                      guint n_props,
                                      GObjectConstructParam *props)
{
  GObject *obj;
  GabbleBytestreamSocks5Private *priv;
  TpBaseConnection *base_conn;
  TpHandleRepoIface *contact_repo, *room_repo;
  const gchar *jid;

  obj = G_OBJECT_CLASS (gabble_bytestream_socks5_parent_class)->
           constructor (type, n_props, props);

  priv =
      GABBLE_BYTESTREAM_SOCKS5_GET_PRIVATE (GABBLE_BYTESTREAM_SOCKS5 (obj));

  g_assert (priv->conn != NULL);
  g_assert (priv->peer_handle != 0);
  g_assert (priv->stream_id != NULL);

  base_conn = TP_BASE_CONNECTION (priv->conn);
  contact_repo = tp_base_connection_get_handles (base_conn,
      TP_HANDLE_TYPE_CONTACT);
  room_repo = tp_base_connection_get_handles (base_conn,
      TP_HANDLE_TYPE_ROOM);

  tp_handle_ref (contact_repo, priv->peer_handle);

  jid = tp_handle_inspect (contact_repo, priv->peer_handle);

  if (priv->peer_resource != NULL)
    priv->peer_jid = g_strdup_printf ("%s/%s", jid, priv->peer_resource);
  else
    priv->peer_jid = g_strdup (jid);

  g_assert (priv->self_full_jid != NULL);

  priv->muc_contact = (gabble_get_room_handle_from_jid (room_repo,
        priv->peer_jid) != 0);

  return obj;
}

static void
gabble_bytestream_socks5_class_init (
    GabbleBytestreamSocks5Class *gabble_bytestream_socks5_class)
{
  GObjectClass *object_class =
      G_OBJECT_CLASS (gabble_bytestream_socks5_class);
  GParamSpec *param_spec;

  g_type_class_add_private (gabble_bytestream_socks5_class,
      sizeof (GabbleBytestreamSocks5Private));

  object_class->dispose = gabble_bytestream_socks5_dispose;
  object_class->finalize = gabble_bytestream_socks5_finalize;

  object_class->get_property = gabble_bytestream_socks5_get_property;
  object_class->set_property = gabble_bytestream_socks5_set_property;
  object_class->constructor = gabble_bytestream_socks5_constructor;

   g_object_class_override_property (object_class, PROP_CONNECTION,
      "connection");
   g_object_class_override_property (object_class, PROP_PEER_HANDLE,
       "peer-handle");
   g_object_class_override_property (object_class, PROP_PEER_HANDLE_TYPE,
       "peer-handle-type");
   g_object_class_override_property (object_class, PROP_STREAM_ID,
       "stream-id");
   g_object_class_override_property (object_class, PROP_PEER_JID,
       "peer-jid");
   g_object_class_override_property (object_class, PROP_STATE,
       "state");
   g_object_class_override_property (object_class, PROP_PROTOCOL,
       "protocol");

  param_spec = g_param_spec_string (
      "peer-resource",
      "Peer resource",
      "the resource used by the remote peer during the SI, if any",
      NULL,
      G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_PEER_RESOURCE,
      param_spec);

  param_spec = g_param_spec_string (
      "stream-init-id",
      "stream init ID",
      "the iq ID of the SI request, if any",
      NULL,
      G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_STREAM_INIT_ID,
      param_spec);

  param_spec = g_param_spec_string (
      "self-jid",
      "Our self jid",
      "Either a contact full jid or a muc jid",
      NULL,
      G_PARAM_CONSTRUCT_ONLY  | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
  g_object_class_install_property (object_class, PROP_SELF_JID,
      param_spec);
}

static gboolean
write_to_transport (GabbleBytestreamSocks5 *self,
                    const gchar *data,
                    guint len,
                    GError **error)
{
  GabbleBytestreamSocks5Private *priv =
      GABBLE_BYTESTREAM_SOCKS5_GET_PRIVATE (self);

  if (!gibber_transport_send (priv->transport, (const guint8 *) data, len,
        error))
    {
      return FALSE;
    }

  return TRUE;
}

static void
transport_connected_cb (GibberTransport *transport,
                        GabbleBytestreamSocks5 *self)
{
  GabbleBytestreamSocks5Private *priv =
    GABBLE_BYTESTREAM_SOCKS5_GET_PRIVATE (self);

  stop_timer (self);

  if (priv->socks5_state == SOCKS5_STATE_TARGET_TRYING_CONNECT ||
      priv->socks5_state == SOCKS5_STATE_INITIATOR_TRYING_CONNECT)
    {
      gchar msg[3];

      DEBUG ("transport is connected. Sending auth request");

      msg[0] = SOCKS5_VERSION;
      /* Number of auth methods we are offering, we support just
       * SOCKS5_AUTH_NONE */
      msg[1] = 1;
      msg[2] = SOCKS5_AUTH_NONE;

      write_to_transport (self, msg, 3, NULL);

      if (priv->socks5_state == SOCKS5_STATE_TARGET_TRYING_CONNECT)
        priv->socks5_state = SOCKS5_STATE_TARGET_AUTH_REQUEST_SENT;
      else
        priv->socks5_state = SOCKS5_STATE_INITIATOR_AUTH_REQUEST_SENT;
    }
}

static void
transport_disconnected_cb (GibberTransport *transport,
                           GabbleBytestreamSocks5 *self)
{
  stop_timer (self);
  DEBUG ("Sock5 transport disconnected");
  socks5_error (self);
}

static void
change_write_blocked_state (GabbleBytestreamSocks5 *self,
                            gboolean blocked)
{
  GabbleBytestreamSocks5Private *priv =
      GABBLE_BYTESTREAM_SOCKS5_GET_PRIVATE (self);

  if (priv->write_blocked == blocked)
    return;

  priv->write_blocked = blocked;
  g_signal_emit_by_name (self, "write-blocked", blocked);
}

static void
socks5_close_transport (GabbleBytestreamSocks5 *self)
{
  GabbleBytestreamSocks5Private *priv =
    GABBLE_BYTESTREAM_SOCKS5_GET_PRIVATE (self);

  if (priv->read_buffer != NULL)
    {
      g_string_free (priv->read_buffer, TRUE);
      priv->read_buffer = NULL;
    }

  if (priv->transport == NULL)
    return;

  g_signal_handlers_disconnect_matched (priv->transport,
      G_SIGNAL_MATCH_DATA, 0, 0, NULL, NULL, self);

  g_object_unref (priv->transport);
  priv->transport = NULL;
}

static void
bytestream_closed (GabbleBytestreamSocks5 *self)
{
  socks5_close_transport (self);
  g_object_set (self, "state", GABBLE_BYTESTREAM_STATE_CLOSED, NULL);
}

static void
transport_buffer_empty_cb (GibberTransport *transport,
                           GabbleBytestreamSocks5 *self)
{
  GabbleBytestreamSocks5Private *priv = GABBLE_BYTESTREAM_SOCKS5_GET_PRIVATE
      (self);

  if (priv->bytestream_state == GABBLE_BYTESTREAM_STATE_CLOSING)
    {
      DEBUG ("buffer is now empty. Bytestream can be closed");
      bytestream_closed (self);
    }
  else if (priv->write_blocked)
    {
      change_write_blocked_state (self, FALSE);
    }
}

static void
set_transport (GabbleBytestreamSocks5 *self,
               GibberTransport *transport)
{
  GabbleBytestreamSocks5Private *priv =
      GABBLE_BYTESTREAM_SOCKS5_GET_PRIVATE (self);

  priv->transport = g_object_ref (transport);

  g_assert (priv->read_buffer == NULL);
  priv->read_buffer = g_string_sized_new (4096);

  gibber_transport_set_handler (transport, transport_handler, self);

  g_signal_connect (transport, "connected",
      G_CALLBACK (transport_connected_cb), self);
  g_signal_connect (transport, "disconnected",
      G_CALLBACK (transport_disconnected_cb), self);
  g_signal_connect (priv->transport, "buffer-empty",
      G_CALLBACK (transport_buffer_empty_cb), self);
}

static void
socks5_error (GabbleBytestreamSocks5 *self)
{
  GabbleBytestreamSocks5Private *priv =
      GABBLE_BYTESTREAM_SOCKS5_GET_PRIVATE (self);
  Socks5State previous_state;

  stop_timer (self);

  previous_state = priv->socks5_state;
  priv->socks5_state = SOCKS5_STATE_ERROR;

  switch (previous_state)
    {
      case SOCKS5_STATE_TARGET_TRYING_CONNECT:
      case SOCKS5_STATE_TARGET_AUTH_REQUEST_SENT:
      case SOCKS5_STATE_TARGET_CONNECT_REQUESTED:
        /* The attempt for connect to the streamhost failed */
        socks5_close_transport (self);

        if (priv->streamhosts != NULL)
          {
            /* Remove the failed streamhost */
            streamhost_free (priv->streamhosts->data);
            priv->streamhosts = g_slist_delete_link (priv->streamhosts,
                priv->streamhosts);
          }

        if (priv->streamhosts != NULL)
          {
            DEBUG ("connection to streamhost failed, trying the next one");

            socks5_connect (self);
            return;
          }

        DEBUG ("no more streamhosts to try");

        g_signal_emit_by_name (self, "connection-error");

        g_assert (priv->msg_for_acknowledge_connection != NULL);
        _gabble_connection_send_iq_error (priv->conn,
            priv->msg_for_acknowledge_connection, XMPP_ERROR_ITEM_NOT_FOUND,
            "impossible to connect to any streamhost");

        lm_message_unref (priv->msg_for_acknowledge_connection);
        priv->msg_for_acknowledge_connection = NULL;
        break;

      case SOCKS5_STATE_INITIATOR_AWAITING_AUTH_REQUEST:
      case SOCKS5_STATE_INITIATOR_AWAITING_COMMAND:
        DEBUG ("Something goes wrong during SOCKS5 negotiation. Don't close "
            "the bytestream yet as the target can still try other streamhosts");
        break;

      default:
        DEBUG ("error, closing the connection\n");
        gabble_bytestream_socks5_close (GABBLE_BYTESTREAM_IFACE (self), NULL);
    }
}

static gchar *
compute_domain (const gchar *sid,
                const gchar *initiator,
                const gchar *target)
{
  gchar *unhashed_domain;
  gchar *domain;

  unhashed_domain = g_strconcat (sid, initiator, target, NULL);
  domain = sha1_hex (unhashed_domain, strlen (unhashed_domain));

  g_free (unhashed_domain);
  return domain;
}

static gboolean
check_domain (const gchar *domain,
              guint8 len,
              const gchar *expected)
{
  if (len != SHA1_LENGTH || strncmp (domain, expected, SHA1_LENGTH) != 0)
    {
      DEBUG ("Wrong domain hash: %s (expected: %s)", domain, expected);
      return FALSE;
    }

  return TRUE;
}

static gboolean
socks5_timer_cb (gpointer data)
{
  GabbleBytestreamSocks5 *self = GABBLE_BYTESTREAM_SOCKS5 (data);

  DEBUG ("Timed out; closing SOCKS5 connection");

  socks5_error (self);
  return FALSE;
}

static void
start_timer (GabbleBytestreamSocks5 *self,
             guint seconds)
{
  GabbleBytestreamSocks5Private *priv = GABBLE_BYTESTREAM_SOCKS5_GET_PRIVATE (
      self);

  g_assert (priv->timer_id == 0);

  priv->timer_id = g_timeout_add_seconds (seconds, socks5_timer_cb, self);
}

static void
target_got_connect_reply (GabbleBytestreamSocks5 *self)
{
  GabbleBytestreamSocks5Private *priv = GABBLE_BYTESTREAM_SOCKS5_GET_PRIVATE (
      self);
  LmMessage *iq_result;

  DEBUG ("Received CONNECT reply. Socks5 stream connected. "
      "Bytestream is now open");
  priv->socks5_state = SOCKS5_STATE_CONNECTED;
  g_object_set (self, "state", GABBLE_BYTESTREAM_STATE_OPEN, NULL);

  /* Acknowledge the connection */
  iq_result = lm_iq_message_make_result (
      priv->msg_for_acknowledge_connection);
  if (NULL != iq_result)
    {
      LmMessageNode *node;
      Streamhost *current_streamhost;

      node = lm_message_node_add_child (iq_result->node, "query", "");
      lm_message_node_set_attribute (node, "xmlns", NS_BYTESTREAMS);

      /* streamhost-used informs the other end of the streamhost we
       * decided to use. In case of a direct connetion this is useless
       * but if we are using an external proxy we need to know which
       * one was selected */
      node = lm_message_node_add_child (node, "streamhost-used", "");
      current_streamhost = priv->streamhosts->data;
      lm_message_node_set_attribute (node, "jid",
          current_streamhost->jid);

      _gabble_connection_send (priv->conn, iq_result, NULL);
      lm_message_unref (iq_result);
    }

  if (priv->read_blocked)
    {
      DEBUG ("reading has been blocked. Blocking now as the socks5 "
          "negotiation is done");
      gibber_transport_block_receiving (priv->transport, TRUE);
    }
}

static LmHandlerResult
socks5_activation_reply_cb (GabbleConnection *conn,
                            LmMessage *sent_msg,
                            LmMessage *reply_msg,
                            GObject *obj,
                            gpointer user_data)
{
  GabbleBytestreamSocks5 *self = GABBLE_BYTESTREAM_SOCKS5 (user_data);
  GabbleBytestreamSocks5Private *priv = GABBLE_BYTESTREAM_SOCKS5_GET_PRIVATE (
      self);

  if (lm_message_get_sub_type (reply_msg) != LM_MESSAGE_SUB_TYPE_RESULT)
    {
      DEBUG ("Activation failed");
      goto activation_failed;
    }

  if (priv->socks5_state != SOCKS5_STATE_INITIATOR_ACTIVATION_SENT)
    {
      DEBUG ("We are not waiting for an activation reply (state: %u)",
          priv->socks5_state);
      goto activation_failed;
    }

  DEBUG ("Proxy activated the bytestream. It's now open");

  priv->socks5_state = SOCKS5_STATE_CONNECTED;
  g_object_set (self, "state", GABBLE_BYTESTREAM_STATE_OPEN, NULL);
  /* We can read data from the sock5 socket now */
  gibber_transport_block_receiving (priv->transport, FALSE);

  return LM_HANDLER_RESULT_REMOVE_MESSAGE;
activation_failed:
  g_signal_emit_by_name (self, "connection-error");
  g_object_set (self, "state", GABBLE_BYTESTREAM_STATE_CLOSED, NULL);
  return LM_HANDLER_RESULT_REMOVE_MESSAGE;
}

static void
initiator_got_connect_reply (GabbleBytestreamSocks5 *self)
{
  GabbleBytestreamSocks5Private *priv = GABBLE_BYTESTREAM_SOCKS5_GET_PRIVATE (
      self);
  LmMessage *iq;

  DEBUG ("Got CONNECT reply. SOCKS5 negotiation with proxy is done. "
      "Sending activation IQ");

  iq = lm_message_build (priv->proxy_jid, LM_MESSAGE_TYPE_IQ,
      '@', "type", "set",
      '(', "query", "",
        '@', "xmlns", NS_BYTESTREAMS,
        '@', "sid", priv->stream_id,
        '(', "activate", priv->peer_jid, ')',
      ')', NULL);

  priv->socks5_state = SOCKS5_STATE_INITIATOR_ACTIVATION_SENT;

  /* Block reading while waiting for the activation reply */
  gibber_transport_block_receiving (priv->transport, TRUE);

  if (!_gabble_connection_send_with_reply (priv->conn, iq,
      socks5_activation_reply_cb, G_OBJECT (self), self, NULL))
    {
      DEBUG ("Sending activation IQ failed");

      g_signal_emit_by_name (self, "connection-error");
      g_object_set (self, "state", GABBLE_BYTESTREAM_STATE_CLOSED, NULL);
    }

  lm_message_unref (iq);
}

/* Process the received data and returns the number of bytes that have been
 * used */
static gssize
socks5_handle_received_data (GabbleBytestreamSocks5 *self,
                             GString *string)
{
  GabbleBytestreamSocks5Private *priv =
      GABBLE_BYTESTREAM_SOCKS5_GET_PRIVATE (self);
  gchar msg[SOCKS5_CONNECT_LENGTH];
  guint auth_len;
  guint i;
  gchar *domain;
  /* the length of the BND.ADDR field */
  guint8 addr_len;
  gsize len;

  switch (priv->socks5_state)
    {
      case SOCKS5_STATE_TARGET_AUTH_REQUEST_SENT:
      case SOCKS5_STATE_INITIATOR_AUTH_REQUEST_SENT:
        /* We sent an authorization request and we are awaiting for a
         * response, the response is 2 bytes-long */
        if (string->len < 2)
          return 0;

        if (string->str[0] != SOCKS5_VERSION ||
            string->str[1] != SOCKS5_STATUS_OK)
          {
            DEBUG ("Authentication failed");

            socks5_error (self);
            return -1;
          }

        /* We have been authorized, let's send a CONNECT command */

        DEBUG ("Received auth reply. Sending CONNECT command");

        if (priv->socks5_state == SOCKS5_STATE_TARGET_AUTH_REQUEST_SENT)
          {
            domain = compute_domain (priv->stream_id, priv->peer_jid,
                priv->self_full_jid);
          }
        else
          {
            /* SOCKS5_STATE_INITIATOR_AUTH_REQUEST_SENT */
            domain = compute_domain (priv->stream_id, priv->self_full_jid,
                priv->peer_jid);
          }

        msg[0] = SOCKS5_VERSION;
        msg[1] = SOCKS5_CMD_CONNECT;
        msg[2] = SOCKS5_RESERVED;
        msg[3] = SOCKS5_ATYP_DOMAIN;
        /* Length of a hex SHA1 */
        msg[4] = 40;
        /* Domain name: SHA-1(sid + initiator + target) */
        memcpy (&msg[5], domain, 40);
        /* Port: 0 */
        msg[45] = 0x00;
        msg[46] = 0x00;

        g_free (domain);

        write_to_transport (self, msg, SOCKS5_CONNECT_LENGTH, NULL);

        if (priv->socks5_state == SOCKS5_STATE_TARGET_AUTH_REQUEST_SENT)
          priv->socks5_state = SOCKS5_STATE_TARGET_CONNECT_REQUESTED;
        else
          /* SOCKS5_STATE_INITIATOR_AUTH_REQUEST_SENT */
          priv->socks5_state = SOCKS5_STATE_INITIATOR_CONNECT_REQUESTED;

        /* Older version of Gabble (pre 0.7.22) are bugged and just send 2
         * bytes as CONNECT reply. We set a timer to not wait the full reply
         * forever if we are connected to such Gabble.
         * Once timed out, the SOCKS5 negotiation will fail and Gabble
         * will switch to IBB as a fallback. */
        start_timer (self, CONNECT_REPLY_TIMEOUT);

        return 2;

      case SOCKS5_STATE_TARGET_CONNECT_REQUESTED:
      case SOCKS5_STATE_INITIATOR_CONNECT_REQUESTED:
        /* We sent a CONNECT request and are awaiting for the response */
        if (string->len < SOCKS5_MIN_LENGTH)
          return 0;

        if (string->str[0] != SOCKS5_VERSION ||
            string->str[1] != SOCKS5_STATUS_OK ||
            string->str[2] != SOCKS5_RESERVED)
          {
            DEBUG ("Connection refused");

            socks5_error (self);
            return -1;
          }

        if (string->str[3] == SOCKS5_ATYP_DOMAIN)
          {
            /* correct domain. The first byte of the domain contains its
             * length */
            addr_len = (guint8) string->str[4];
            addr_len += 1;
          }
        else if (string->str[3] == 0x00)
          {
            DEBUG ("Got 0x00 as domain. Pretend it's ok to be able to interop "
                "with ejabberd < 2.0.2");
            addr_len = 0;
          }
        else
          {
            DEBUG ("Wrong domain");

            socks5_error (self);
            return -1;
          }

        if ((guint8) string->len < SOCKS5_MIN_LENGTH + addr_len)
          /* We didn't receive the full packet yet */
          return 0;

        stop_timer (self);

        if (
            /* first half of the port number */
            string->str[4 + addr_len] != 0 ||
            /* second half of the port number */
            string->str[5 + addr_len] != 0)
          {
            DEBUG ("Connection refused");

            socks5_error (self);
            return -1;
          }

        if (priv->socks5_state == SOCKS5_STATE_TARGET_CONNECT_REQUESTED)
          {
            domain = compute_domain (priv->stream_id, priv->peer_jid,
                priv->self_full_jid);
          }
        else
          {
            /* SOCKS5_STATE_INITIATOR_CONNECT_REQUESTED */
            domain = compute_domain (priv->stream_id, priv->self_full_jid,
                priv->peer_jid);
          }

        if (addr_len > 0)
          {
            if (!check_domain (&string->str[5], addr_len - 1, domain))
              {
                /* Thanks Pidgin... */
                DEBUG ("Ignoring to interop with buggy implementations");
              }
          }

        g_free (domain);

        if (priv->socks5_state == SOCKS5_STATE_TARGET_CONNECT_REQUESTED)
          target_got_connect_reply (self);
        else
          /* SOCKS5_STATE_INITIATOR_CONNECT_REQUESTED */
          initiator_got_connect_reply (self);

        return SOCKS5_MIN_LENGTH + addr_len;

      case SOCKS5_STATE_INITIATOR_AWAITING_AUTH_REQUEST:
        /* A client connected to us and we are awaiting for the authorization
         * request (at least 2 bytes) */
        if (string->len < 2)
          return 0;

        if (string->str[0] != SOCKS5_VERSION)
          {
            DEBUG ("Authentication failed");

            socks5_error (self);
            return -1;
          }

        /* The auth request string is SOCKS5_VERSION + # of methods + methods */
        auth_len = string->str[1] + 2;
        if (string->len < auth_len)
          /* We are still receiving some auth method */
          return 0;

        for (i = 2; i < auth_len; i++)
          {
            if (string->str[i] == SOCKS5_AUTH_NONE)
              {
                /* Authorize the connection */
                msg[0] = SOCKS5_VERSION;
                msg[1] = SOCKS5_AUTH_NONE;

                DEBUG ("Received auth request. Sending auth reply");
                write_to_transport (self, msg, 2, NULL);

                priv->socks5_state = SOCKS5_STATE_INITIATOR_AWAITING_COMMAND;

                return auth_len;
              }
          }

        DEBUG ("Unauthenticated access is not supported by the streamhost");

        socks5_error (self);

        return -1;

      case SOCKS5_STATE_INITIATOR_AWAITING_COMMAND:
        /* The client has been authorized and we are waiting for a command,
         * the only one supported by the SOCKS5 bytestreams XEP is
         * CONNECT with:
         *  - ATYP = DOMAIN
         *  - PORT = 0
         *  - DOMAIN = SHA1(sid + initiator + target)
         */
        if (string->len < SOCKS5_MIN_LENGTH)
          return 0;

        addr_len = (guint8) string->str[4];
        /* the first byte is the length */
        addr_len += 1;

        if ((guint8) string->len < SOCKS5_MIN_LENGTH + addr_len)
          /* We didn't receive the full packet yet */
          return 0;

        if (string->str[0] != SOCKS5_VERSION ||
            string->str[1] != SOCKS5_CMD_CONNECT ||
            string->str[2] != SOCKS5_RESERVED ||
            string->str[3] != SOCKS5_ATYP_DOMAIN ||
            /* first half of the port number */
            string->str[4 + addr_len] != 0 ||
            /* second half of the port number */
            string->str[5 + addr_len] != 0)
          {
            DEBUG ("Invalid SOCKS5 connect message");

            socks5_error (self);
            return -1;
          }

        domain = compute_domain (priv->stream_id, priv->self_full_jid,
            priv->peer_jid);

        if (!check_domain (&string->str[5], addr_len - 1, domain))
          {
            DEBUG ("Reject connection to prevent spoofing");
            socks5_close_transport (self);
            socks5_error (self);
            g_free (domain);
            return -1;
          }

        msg[0] = SOCKS5_VERSION;
        msg[1] = SOCKS5_STATUS_OK;
        msg[2] = SOCKS5_RESERVED;
        msg[3] = SOCKS5_ATYP_DOMAIN;
        msg[4] = SHA1_LENGTH;
        /* Domain name: SHA-1(sid + initiator + target) */
        memcpy (&msg[5], domain, 40);
        /* Port: 0 */
        msg[45] = 0x00;
        msg[46] = 0x00;

        g_free (domain);

        DEBUG ("Received CONNECT cmd. Sending CONNECT reply");
        write_to_transport (self, msg, 47, NULL);

        priv->socks5_state = SOCKS5_STATE_CONNECTED;

        /* Sock5 is connected but the bytestream is not open yet as we need
         * to wait for the IQ reply. Stop reading until the bytestream
         * is open to avoid data loss. */
        gibber_transport_block_receiving (priv->transport, TRUE);

        DEBUG ("sock5 stream connected. Stop to listen for connections");
        g_assert (priv->listener != NULL);
        g_object_unref (priv->listener);
        priv->listener = NULL;

        return SOCKS5_MIN_LENGTH + addr_len;

      case SOCKS5_STATE_CONNECTED:
        /* We are connected, everything we receive now is data */

        /* store the buffer len because if something went wront in the
         * data-received callback, the bytestream could be freed and so the
         * priv->read_buffer */
        len = string->len;
        g_signal_emit_by_name (G_OBJECT (self), "data-received",
            priv->peer_handle, string);

        return len;

      case SOCKS5_STATE_ERROR:
        /* An error occurred and the channel will be closed in an idle
         * callback, so let's just throw away the data we receive */
        DEBUG ("An error occurred, throwing away received data");
        return string->len;

      case SOCKS5_STATE_TARGET_TRYING_CONNECT:
      case SOCKS5_STATE_INITIATOR_TRYING_CONNECT:
        DEBUG ("Impossible to receive data when not yet connected to the "
            "socket");
        break;

      case SOCKS5_STATE_INITIATOR_OFFER_SENT:
        DEBUG ("Shouldn't receive data when we just sent the offer");
        break;

      case SOCKS5_STATE_INITIATOR_ACTIVATION_SENT:
        DEBUG ("Shouldn't receive data before we received activation reply");
        break;

      case SOCKS5_STATE_INVALID:
        DEBUG ("Invalid SOCKS5 state");
        break;
    }

  g_assert_not_reached ();
  return string->len;
}

static void
transport_handler (GibberTransport *transport,
                   GibberBuffer *data,
                   gpointer user_data)

{
  GabbleBytestreamSocks5 *self = GABBLE_BYTESTREAM_SOCKS5 (user_data);
  GabbleBytestreamSocks5Private *priv =
      GABBLE_BYTESTREAM_SOCKS5_GET_PRIVATE (self);
  gssize used_bytes;

  g_assert (priv->read_buffer != NULL);
  g_string_append_len (priv->read_buffer, (const gchar *) data->data,
      data->length);

  /* If something goes wrong in socks5_handle_received_data, the bytestream
   * could be closed and disposed. Ref it to artificially keep this bytestream
   * object alive while we are in this function. */
  g_object_ref (self);

  do
    {
      /* socks5_handle_received_data() processes the data and returns the
       * number of bytes that have been used. 0 means that there is not enough
       * data to do anything, so we just wait for more data from the socket */
      used_bytes = socks5_handle_received_data (self, priv->read_buffer);

      if (priv->read_buffer == NULL)
        /* If something did wrong in socks5_handle_received_data, the
         * bytestream can be closed and so destroyed. */
        break;

      g_string_erase (priv->read_buffer, 0, used_bytes);
    }
  while (used_bytes > 0 && priv->read_buffer->len > 0);

  g_object_unref (self);
}

static void
socks5_connect (GabbleBytestreamSocks5 *self)
{
  GabbleBytestreamSocks5Private *priv =
      GABBLE_BYTESTREAM_SOCKS5_GET_PRIVATE (self);
  Streamhost* streamhost;
  GibberTCPTransport *transport;

  priv->socks5_state = SOCKS5_STATE_TARGET_TRYING_CONNECT;

  if (priv->streamhosts != NULL)
    {
      streamhost = priv->streamhosts->data;
    }
  else
    {
      DEBUG ("No more streamhosts to try, closing");

      socks5_error (self);
      return;
    }

  DEBUG ("Trying streamhost %s on port %s", streamhost->host,
      streamhost->port);

  transport = gibber_tcp_transport_new ();
  set_transport (self, GIBBER_TRANSPORT (transport));
  g_object_unref (transport);

  /* We don't wait to wait for the TCP timeout is the host is unreachable */
  start_timer (self, CONNECT_TIMEOUT);

  gibber_tcp_transport_connect (transport, streamhost->host,
      streamhost->port);

  /* We'll send the auth request once the transport is connected */
}

/**
 * gabble_bytestream_socks5_add_streamhost
 *
 * Adds the streamhost as a candidate for connection.
 */
void
gabble_bytestream_socks5_add_streamhost (GabbleBytestreamSocks5 *self,
                                         LmMessageNode *streamhost_node)
{
  GabbleBytestreamSocks5Private *priv =
      GABBLE_BYTESTREAM_SOCKS5_GET_PRIVATE (self);
  const gchar *zeroconf;
  const gchar *jid;
  const gchar *host;
  const gchar *port;
  Streamhost *streamhost;

  g_return_if_fail (!tp_strdiff (streamhost_node->name, "streamhost"));

  zeroconf = lm_message_node_get_attribute (streamhost_node, "zeroconf");
  if (zeroconf != NULL)
    {
      /* TODO: add suppport for zeroconf */
      DEBUG ("zeroconf streamhosts are not supported");
      return;
    }

  jid = lm_message_node_get_attribute (streamhost_node, "jid");
  if (jid == NULL)
    {
      DEBUG ("streamhost doesn't contain a JID");
      return;
    }

  host = lm_message_node_get_attribute (streamhost_node, "host");
  if (host == NULL)
    {
      DEBUG ("streamhost doesn't contain a host");
      return;
    }

  port = lm_message_node_get_attribute (streamhost_node, "port");
  if (port == NULL)
    {
      DEBUG ("streamhost doesn't contain a port");
      return;
    }

  if (tp_strdiff (jid, priv->peer_jid) && priv->muc_contact)
    {
      DEBUG ("skip streamhost %s (%s:%s); we don't support relay with muc "
          "contact", jid, host, port);
      return;
    }

  DEBUG ("streamhost with jid %s, host %s and port %s added", jid, host,
      port);

  streamhost = streamhost_new (jid, host, port);
  priv->streamhosts = g_slist_append (priv->streamhosts, streamhost);
}

/**
 * gabble_bytestream_socks5_connect_to_streamhost
 *
 * Try to connect to a streamhost.
 */
void
gabble_bytestream_socks5_connect_to_streamhost (GabbleBytestreamSocks5 *self,
                                                LmMessage *msg)

{
  GabbleBytestreamSocks5Private *priv =
      GABBLE_BYTESTREAM_SOCKS5_GET_PRIVATE (self);

  priv->msg_for_acknowledge_connection = lm_message_ref (msg);

  socks5_connect (self);
}

/*
 * gabble_bytestream_socks5_send
 *
 * Implements gabble_bytestream_iface_send on GabbleBytestreamIface
 */
static gboolean
gabble_bytestream_socks5_send (GabbleBytestreamIface *iface,
                               guint len,
                               const gchar *str)
{
  GabbleBytestreamSocks5 *self = GABBLE_BYTESTREAM_SOCKS5 (iface);
  GabbleBytestreamSocks5Private *priv =
      GABBLE_BYTESTREAM_SOCKS5_GET_PRIVATE (self);
  GError *error = NULL;

  if (priv->bytestream_state != GABBLE_BYTESTREAM_STATE_OPEN)
    {
      DEBUG ("can't send data through a not open bytestream (state: %d)",
          priv->bytestream_state);
      return FALSE;
    }

  /* if something goes wrong during the sending, the bytestream could be
   * closed and so disposed by the bytestream factory. Ref it to keep it
   * artifically alive if such case happen. */
  g_object_ref (self);

  if (!write_to_transport (self, str, len, &error))
    {
      DEBUG ("sending failed: %s", error->message);

      g_error_free (error);
      gabble_bytestream_iface_close (GABBLE_BYTESTREAM_IFACE (self), NULL);
      g_object_unref (self);
      return FALSE;
    }

  /* If something wennt wrong during the writting, the transport has been closed
   * and so set to NULL. */
  if (priv->transport == NULL)
    {
      g_object_unref (self);
      return FALSE;
    }

  /* At this point we know that the bytestream has not been closed */
  g_object_unref (self);

  if (!gibber_transport_buffer_is_empty (priv->transport))
    {
      /* We >don't want to send more data while the buffer isn't empty */
      change_write_blocked_state (self, TRUE);
    }

  return TRUE;
}

/*
 * gabble_bytestream_socks5_accept
 *
 * Implements gabble_bytestream_iface_accept on GabbleBytestreamIface
 */
static void
gabble_bytestream_socks5_accept (GabbleBytestreamIface *iface,
                                 GabbleBytestreamAugmentSiAcceptReply func,
                                 gpointer user_data)
{
  GabbleBytestreamSocks5 *self = GABBLE_BYTESTREAM_SOCKS5 (iface);
  GabbleBytestreamSocks5Private *priv =
      GABBLE_BYTESTREAM_SOCKS5_GET_PRIVATE (self);
  LmMessage *msg;
  LmMessageNode *si;

  if (priv->bytestream_state != GABBLE_BYTESTREAM_STATE_LOCAL_PENDING)
    {
      /* The stream was previoulsy or automatically accepted */
      return;
    }

  msg = gabble_bytestream_factory_make_accept_iq (priv->peer_jid,
      priv->stream_init_id, NS_BYTESTREAMS);
  si = lm_message_node_get_child_with_namespace (msg->node, "si", NS_SI);
  g_assert (si != NULL);

  if (func != NULL)
    {
      /* let the caller add his profile specific data */
      func (si, user_data);
    }

  if (_gabble_connection_send (priv->conn, msg, NULL))
    {
      DEBUG ("stream %s with %s is now accepted", priv->stream_id,
          priv->peer_jid);
      g_object_set (self, "state", GABBLE_BYTESTREAM_STATE_ACCEPTED, NULL);
    }

  lm_message_unref (msg);
}

static void
gabble_bytestream_socks5_decline (GabbleBytestreamSocks5 *self,
                                  GError *error)
{
  GabbleBytestreamSocks5Private *priv =
      GABBLE_BYTESTREAM_SOCKS5_GET_PRIVATE (self);
  LmMessage *msg;

  g_return_if_fail (priv->bytestream_state ==
      GABBLE_BYTESTREAM_STATE_LOCAL_PENDING);

  msg = lm_message_build (priv->peer_jid, LM_MESSAGE_TYPE_IQ,
      '@', "type", "error",
      '@', "id", priv->stream_init_id,
      NULL);

  if (error != NULL && error->domain == GABBLE_XMPP_ERROR)
    {
      gabble_xmpp_error_to_node (error->code, msg->node, error->message);
    }
  else
    {
      gabble_xmpp_error_to_node (XMPP_ERROR_FORBIDDEN, msg->node,
          "Offer Declined");
    }

  _gabble_connection_send (priv->conn, msg, NULL);

  lm_message_unref (msg);

  g_object_set (self, "state", GABBLE_BYTESTREAM_STATE_CLOSED, NULL);
}

/*
 * gabble_bytestream_socks5_close
 *
 * Implements gabble_bytestream_iface_close on GabbleBytestreamIface
 */
static void
gabble_bytestream_socks5_close (GabbleBytestreamIface *iface,
                                GError *error)
{
  GabbleBytestreamSocks5 *self = GABBLE_BYTESTREAM_SOCKS5 (iface);
  GabbleBytestreamSocks5Private *priv =
      GABBLE_BYTESTREAM_SOCKS5_GET_PRIVATE (self);

  if (priv->bytestream_state == GABBLE_BYTESTREAM_STATE_CLOSED)
     /* bytestream already closed, do nothing */
     return;

  if (priv->bytestream_state == GABBLE_BYTESTREAM_STATE_LOCAL_PENDING)
    {
      /* Stream was created using SI so we decline the request */
      gabble_bytestream_socks5_decline (self, error);
    }
  else
    {
      g_object_set (self, "state", GABBLE_BYTESTREAM_STATE_CLOSING, NULL);
      if (priv->transport != NULL &&
          !gibber_transport_buffer_is_empty (priv->transport))
        {
          DEBUG ("Wait transport buffer is empty before close the bytestream");
        }
      else
        {
          DEBUG ("Transport buffer is empty, we can close the bytestream");
          bytestream_closed (self);
        }
    }
}

static void
initiator_connected_to_proxy (GabbleBytestreamSocks5 *self)
{
  GabbleBytestreamSocks5Private *priv = GABBLE_BYTESTREAM_SOCKS5_GET_PRIVATE (
      self);
  GSList *proxies, *l;
  GabbleSocks5Proxy *proxy = NULL;
  GibberTCPTransport *transport;

  proxies = gabble_bytestream_factory_get_socks5_proxies (
      priv->conn->bytestream_factory);
  for (l = proxies; l != NULL; l = g_slist_next (l))
     {
       proxy = (GabbleSocks5Proxy *) l->data;

       if (!tp_strdiff (proxy->jid, priv->proxy_jid))
         break;

       proxy = NULL;
     }
  g_slist_free (proxies);

  if (proxy == NULL)
    {
      DEBUG ("Unknown proxy: %s. Closing the bytestream", priv->proxy_jid);
      g_signal_emit_by_name (self, "connection-error");
      g_object_set (self, "state", GABBLE_BYTESTREAM_STATE_CLOSED, NULL);
      return;
    }

  DEBUG ("connect to proxy: %s (%s:%s)", proxy->jid, proxy->host, proxy->port);
  priv->socks5_state = SOCKS5_STATE_INITIATOR_TRYING_CONNECT;

  transport = gibber_tcp_transport_new ();
  set_transport (self, GIBBER_TRANSPORT (transport));
  g_object_unref (transport);

  gibber_tcp_transport_connect (transport, proxy->host,
      proxy->port);
}

static LmHandlerResult
socks5_init_reply_cb (GabbleConnection *conn,
                      LmMessage *sent_msg,
                      LmMessage *reply_msg,
                      GObject *obj,
                      gpointer user_data)
{
  GabbleBytestreamSocks5 *self = GABBLE_BYTESTREAM_SOCKS5 (obj);
  GabbleBytestreamSocks5Private *priv =
      GABBLE_BYTESTREAM_SOCKS5_GET_PRIVATE (self);

  if (lm_message_get_sub_type (reply_msg) == LM_MESSAGE_SUB_TYPE_RESULT)
    {
      LmMessageNode *query, *streamhost = NULL;
      const gchar *jid;

      query = lm_message_node_get_child_with_namespace (reply_msg->node,
          "query", NS_BYTESTREAMS);

      if (query != NULL)
        streamhost = lm_message_node_get_child (query, "streamhost-used");

      if (streamhost == NULL)
        {
          DEBUG ("no streamhost-used has been defined. Closing the bytestream");
          goto socks5_init_error;
        }

      jid = lm_message_node_get_attribute (streamhost, "jid");
      if (jid == NULL)
        {
          DEBUG ("no jid attribute in streamhost. Closing the bytestream");
          goto socks5_init_error;
        }

      if (tp_strdiff (jid, priv->self_full_jid))
        {
          DEBUG ("Target is connected to proxy: %s", jid);

          if (priv->socks5_state != SOCKS5_STATE_INITIATOR_OFFER_SENT)
            {
              DEBUG ("We are already in the negotiation process (state: %u). "
                  "Closing the bytestream", priv->socks5_state);
              goto socks5_init_error;
            }

          priv->proxy_jid = g_strdup (jid);
          initiator_connected_to_proxy (self);
          return LM_HANDLER_RESULT_REMOVE_MESSAGE;
        }

      /* No proxy used */
      DEBUG ("Target is connected to us");

      if (priv->socks5_state != SOCKS5_STATE_CONNECTED)
        {
          DEBUG ("Target claims that the bytestream is open but SOCKS5 is not "
              "connected (state: %u). Closing the bytestream",
              priv->socks5_state);
          goto socks5_init_error;
        }

      /* yeah, stream initiated */
      DEBUG ("Socks5 stream initiated using stream: %s", jid);
      g_object_set (self, "state", GABBLE_BYTESTREAM_STATE_OPEN, NULL);
      /* We can read data from the sock5 socket now */
      gibber_transport_block_receiving (priv->transport, FALSE);
      return LM_HANDLER_RESULT_REMOVE_MESSAGE;
    }

socks5_init_error:
  DEBUG ("error during Socks5 initiation");

  g_signal_emit_by_name (self, "connection-error");
  g_object_set (self, "state", GABBLE_BYTESTREAM_STATE_CLOSED, NULL);

  return LM_HANDLER_RESULT_REMOVE_MESSAGE;
}

/* get_local_interfaces_ips original code from Farsight 2 (function
 * fs_interfaces_get_local_ips in /gst-libs/gst/farsight/fs-interfaces.c).
 *   Copyright (C) 2006 Youness Alaoui <kakaroto@kakaroto.homelinux.net>
 *   Copyright (C) 2007 Collabora
 */
#ifdef HAVE_GETIFADDRS

static GSList *
get_local_interfaces_ips (void)
{
  struct ifaddrs *ifa, *results;
  GSList *ips = NULL;

  if (getifaddrs (&results) < 0)
    return NULL;

  /* Loop through the interface list and get the IP address of each IF */
  for (ifa = results; ifa; ifa = ifa->ifa_next)
    {
      char straddr[INET6_ADDRSTRLEN];

      /* no ip address from interface that is down */
      if ((ifa->ifa_flags & IFF_UP) == 0)
        continue;

      if (ifa->ifa_addr == NULL)
        continue;

      if ((ifa->ifa_flags & IFF_LOOPBACK) == IFF_LOOPBACK)
        {
          DEBUG ("Ignoring loopback interface");
          continue;
        }

      if (ifa->ifa_addr->sa_family == AF_INET)
        {
          struct sockaddr_in *sa = (struct sockaddr_in *) ifa->ifa_addr;

          inet_ntop (AF_INET, &sa->sin_addr, straddr, sizeof (straddr));

          /* Add IPv4 addresses to the end of the list */
          ips = g_slist_append (ips, g_strdup (straddr));
        }
      else if (ifa->ifa_addr->sa_family == AF_INET6)
        {
          struct sockaddr_in6 *sa6 = (struct sockaddr_in6 *) ifa->ifa_addr;

          inet_ntop (AF_INET6, &sa6->sin6_addr, straddr, sizeof (straddr));

          if (IN6_IS_ADDR_LINKLOCAL (&sa6->sin6_addr))
            {
              DEBUG ("Ignoring link-local address: %s", straddr);
              continue;
            }

          /* Add IPv6 addresss to the begin of the list */
          ips = g_slist_prepend (ips, g_strdup (straddr));
        }
      else
        {
          continue;
        }

      DEBUG ("Interface:  %s", ifa->ifa_name);
      DEBUG ("IP Address: %s", straddr);
    }

  freeifaddrs (results);

  return ips;
}

#else /* ! HAVE_GETIFADDRS */

static GSList *
get_local_interfaces_ips (void)
{
  gint sockfd;
  gint size = 0;
  struct ifreq *ifr;
  struct ifconf ifc;
  struct sockaddr_in *sa;
  GSList *ips = NULL;

  /* FIXME: add IPv6 addresses */
  if ((sockfd = socket (AF_INET, SOCK_DGRAM, IPPROTO_IP)) < 0)
    {
      DEBUG ("Cannot open socket to retreive interface list");
      return NULL;
    }

  ifc.ifc_len = 0;
  ifc.ifc_req = NULL;

  /* Loop and get each interface the system has, one by one... */
  do
    {
      size += sizeof (struct ifreq);
      /* realloc buffer size until no overflow occurs  */
      if (NULL == (ifc.ifc_req = realloc (ifc.ifc_req, size)))
        {
          DEBUG ("Out of memory while allocation interface configuration"
              " structure");
          close (sockfd);
          return NULL;
        }
      ifc.ifc_len = size;

      if (ioctl (sockfd, SIOCGIFCONF, &ifc))
        {
          DEBUG ("ioctl SIOCFIFCONF");
          close (sockfd);
          free (ifc.ifc_req);
          return NULL;
        }
    } while  (size <= ifc.ifc_len);

  /* Loop throught the interface list and get the IP address of each IF */
  for (ifr = ifc.ifc_req;
      (gchar *) ifr < (gchar *) ifc.ifc_req + ifc.ifc_len;
      ++ifr)
    {

      if (ioctl (sockfd, SIOCGIFFLAGS, ifr))
        {
          DEBUG ("Unable to get IP information for interface %s. Skipping...",
              ifr->ifr_name);
          continue;  /* failed to get flags, skip it */
        }
      sa = (struct sockaddr_in *) &ifr->ifr_addr;
      DEBUG ("Interface:  %s", ifr->ifr_name);
      DEBUG ("IP Address: %s", inet_ntoa (sa->sin_addr));
      if ((ifr->ifr_flags & IFF_LOOPBACK) == IFF_LOOPBACK)
        {
          DEBUG ("Ignoring loopback interface");
        }
      else
        {
          ips = g_slist_prepend (ips, g_strdup (inet_ntoa (sa->sin_addr)));
        }
    }

  close (sockfd);
  free (ifc.ifc_req);

  return ips;
}

#endif /* ! HAVE_GETIFADDRS */

static void
new_connection_cb (GibberListener *listener,
                   GibberTransport *transport,
                   struct sockaddr *addr,
                   guint size,
                   gpointer user_data)
{
  GabbleBytestreamSocks5 *self = GABBLE_BYTESTREAM_SOCKS5 (user_data);
  GabbleBytestreamSocks5Private *priv =
    GABBLE_BYTESTREAM_SOCKS5_GET_PRIVATE (self);

  DEBUG ("New connection...");

  priv->socks5_state = SOCKS5_STATE_INITIATOR_AWAITING_AUTH_REQUEST;
  set_transport (self, transport);
}

/*
 * gabble_bytestream_socks5_initiate
 *
 * Implements gabble_bytestream_iface_initiate on GabbleBytestreamIface
 */
static gboolean
gabble_bytestream_socks5_initiate (GabbleBytestreamIface *iface)
{
  GabbleBytestreamSocks5 *self = GABBLE_BYTESTREAM_SOCKS5 (iface);
  GabbleBytestreamSocks5Private *priv =
      GABBLE_BYTESTREAM_SOCKS5_GET_PRIVATE (self);
  gchar *port;
  gint port_num;
  LmMessage *msg;
  GSList *ips, *ip;

  if (priv->bytestream_state != GABBLE_BYTESTREAM_STATE_INITIATING)
    {
      DEBUG ("bytestream is not is the initiating state (state %d)",
          priv->bytestream_state);
      return FALSE;
    }

  ips = get_local_interfaces_ips ();
  if (ips == NULL)
    {
      DEBUG ("Can't get IP addresses");
      return FALSE;
    }

  g_assert (priv->listener == NULL);
  priv->listener = gibber_listener_new ();

  g_signal_connect (priv->listener, "new-connection",
      G_CALLBACK (new_connection_cb), self);

  if (!gibber_listener_listen_tcp (priv->listener, 0, NULL))
    {
      DEBUG ("can't listen for incoming connection");
      return FALSE;
    }

  port_num = gibber_listener_get_port (priv->listener);
  port = g_strdup_printf ("%d", port_num);

  msg = lm_message_build (priv->peer_jid, LM_MESSAGE_TYPE_IQ,
      '@', "type", "set",
      '(', "query", "",
        '@', "xmlns", NS_BYTESTREAMS,
        '@', "sid", priv->stream_id,
        '@', "mode", "tcp",
      ')', NULL);

  for (ip = ips; ip != NULL; ip = g_slist_next (ip))
    {
      LmMessageNode *node;
      NodeIter i = node_iter (msg->node);

      node = lm_message_node_add_child (node_iter_data (i),
          "streamhost", "");

      lm_message_node_set_attributes (node,
          "jid", priv->self_full_jid,
          "host", ip->data,
          "port", port,
          NULL);

      g_free (ip->data);
    }

  g_slist_free (ips);
  g_free (port);

  if (!priv->muc_contact)
    {
      GSList *proxies, *l;

      proxies = gabble_bytestream_factory_get_socks5_proxies (
          priv->conn->bytestream_factory);

      for (l = proxies; l != NULL; l = g_slist_next (l))
        {
          LmMessageNode *node;
          GabbleSocks5Proxy *proxy = (GabbleSocks5Proxy *) l->data;
          NodeIter i = node_iter (msg->node);

          node = lm_message_node_add_child (node_iter_data (i),
              "streamhost", "");

          lm_message_node_set_attributes (node,
              "jid", proxy->jid,
              "host", proxy->host,
              "port", proxy->port,
              NULL);
        }
      g_slist_free (proxies);
    }
  else
    {
      DEBUG ("don't propose to use SOCKS5 relays as we are offering bytestream "
          "to a muc contact");
    }

  priv->socks5_state = SOCKS5_STATE_INITIATOR_OFFER_SENT;

  if (!_gabble_connection_send_with_reply (priv->conn, msg,
      socks5_init_reply_cb, G_OBJECT (self), NULL, NULL))
    {
      DEBUG ("Error when sending Socks5 init stanza");

      lm_message_unref (msg);
      return FALSE;
    }

  lm_message_unref (msg);

  return TRUE;
}

static void
gabble_bytestream_socks5_block_reading (GabbleBytestreamIface *iface,
                                        gboolean block)
{
  GabbleBytestreamSocks5 *self = GABBLE_BYTESTREAM_SOCKS5 (iface);
  GabbleBytestreamSocks5Private *priv =
      GABBLE_BYTESTREAM_SOCKS5_GET_PRIVATE (self);

  if (priv->read_blocked == block)
    return;

  priv->read_blocked = block;

  if (priv->transport != NULL)
    gibber_transport_block_receiving (priv->transport, block);
}

static void
bytestream_iface_init (gpointer g_iface,
                       gpointer iface_data)
{
  GabbleBytestreamIfaceClass *klass = (GabbleBytestreamIfaceClass *) g_iface;

  klass->initiate = gabble_bytestream_socks5_initiate;
  klass->send = gabble_bytestream_socks5_send;
  klass->close = gabble_bytestream_socks5_close;
  klass->accept = gabble_bytestream_socks5_accept;
  klass->block_reading = gabble_bytestream_socks5_block_reading;
}